cyc-stack 0.7.0 → 0.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,10 +7,12 @@ import { hostname, tmpdir } from 'node:os';
7
7
  import { digest } from './response-gate.mjs';
8
8
  import { getPlaybook, routeTask } from './catalog.mjs';
9
9
  import { forgetDisproved, inspectSource as inspectSourceFiles, saveCache, sourcePolicy } from './source-snapshot.mjs';
10
- import { assessmentRequirements, assessmentTemplate, derivedAssessment, renderReview, reviewPath, validateAssessment, reviewCoverage, validateProofReview } from './work-review.mjs';
10
+ import { assessmentRequirements, assessmentTemplate, derivedAssessment, renderReview, reviewPath, validateAssessment, reviewCoverage, reviewCurrent, validateProofReview } from './work-review.mjs';
11
11
  import { recoveryGuidance } from './recovery.mjs';
12
12
  import { cutOff, outputLimit, stable, summarizeTests, testsOf, failureHint } from './test-output.mjs';
13
13
  import { runPacketDigest, writeRunPacket } from './packet.mjs';
14
+ import { artifactFiles, resolveExecution } from './execution.mjs';
15
+ import { planRetention, retentionOf, prepareRetention, checkRetention, contextLocation, isComponentDoc, parseDoc } from './context-review.mjs';
14
16
  export { sourceSnapshot } from './source-snapshot.mjs';
15
17
 
16
18
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -30,6 +32,7 @@ const slash = path => path.split(sep).join('/');
30
32
  let cacheStage = null;
31
33
  // The operation lock this process holds, so a running check can record how long it may last.
32
34
  let activeOwnership = null;
35
+ let activeProgress = null;
33
36
  const inspectSource = (root, options) => inspectSourceFiles(root, { ...options, writeCache: cacheStage ?? false });
34
37
  const sourceSnapshot = (root, options) => inspectSource(root, options).snapshot;
35
38
  // Views between checks reuse cached hashes. Snapshots that record evidence, at run start, around
@@ -156,6 +159,7 @@ export function configuration(root) {
156
159
  if (!limitKeys.includes(key) || !Number.isSafeInteger(value) || value <= 0) throw new Error(`Invalid run limit: ${key}`);
157
160
  }
158
161
  const commands = config.verification?.commands ?? [];
162
+ validateCommands(commands, 'verification.commands');
159
163
  if (!Array.isArray(commands)) throw new Error('verification.commands must be an array.');
160
164
  const ids = new Set();
161
165
  for (const command of commands) {
@@ -167,6 +171,35 @@ export function configuration(root) {
167
171
  const ledgerPath = normalizePaths(root, [config.context?.ledgerPath ?? (existsSync(resolve(root, 'INCIDENT-LEDGER.md')) ? 'INCIDENT-LEDGER.md' : 'docs/context/error-ledger.md')], 'context.ledgerPath')[0];
168
172
  return { limits, commands, ledgerPath, baseline: config.verification?.baseline === true, protectedPaths: normalizePaths(root, ['.cyc/config.json', ...(config.protectedPaths ?? [])], 'protectedPaths') };
169
173
  }
174
+ function validateCommands(commands, label) {
175
+ if (!Array.isArray(commands) || new Set(commands.map(c => c?.id)).size !== commands.length || commands.some(c => !text(c?.id) || !text(c.command) || !Array.isArray(c.args) || c.args.some(a => typeof a !== 'string' || a.includes('\0')) || (c.timeoutMs !== undefined && (!Number.isSafeInteger(c.timeoutMs) || c.timeoutMs <= 0)))) throw new Error(`${label} needs unique id, command, string args and positive timeoutMs.`);
176
+ for (const command of commands) if (command.reuse !== undefined && (command.reuse?.kind !== 'local-deterministic' || !Array.isArray(command.reuse.inputs) || command.reuse.inputs.some(p => !text(p)))) throw new Error(`${label}.reuse needs {kind:"local-deterministic", inputs:[explicit dependency/input paths]}; external or freshness-dependent checks cannot opt in.`);
177
+ }
178
+ // This is a compatibility key, not a second cache. Environment values are hashed, never logged.
179
+ // Unknown executables, links or an excessive dependency tree disable reuse conservatively.
180
+ function measurementInputs(root, commands) {
181
+ const files = {}; let count = 0, bytes = 0, limitation = null;
182
+ const visit = (path, key) => {
183
+ const info = lstatSync(path);
184
+ if (info.isSymbolicLink()) throw new Error(`Linked dependency: ${key}`);
185
+ if (info.isDirectory()) { files[key] = 'directory'; for (const name of readdirSync(path).sort()) visit(resolve(path, name), `${key}/${name}`); }
186
+ else if (info.isFile()) { if (++count > 50000 || (bytes += info.size) > 512 * 1024 * 1024) throw new Error('Dependency inputs exceed bounded reuse inspection.'); files[key] = digest(readFileSync(path)); }
187
+ else throw new Error(`Nonregular input: ${key}`);
188
+ };
189
+ try {
190
+ files.node = digest(readFileSync(process.execPath));
191
+ if (existsSync(resolve(root, 'node_modules'))) visit(resolve(root, 'node_modules'), 'node_modules');
192
+ for (const command of commands) {
193
+ const candidates = isAbsolute(command.command) ? [command.command] : [resolve(root, command.command), ...(process.env.PATH ?? '').split(process.platform === 'win32' ? ';' : ':').flatMap(folder => [resolve(folder, command.command), ...(process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE;.CMD').split(';').map(ext => resolve(folder, command.command + ext.toLowerCase())) : [])])];
194
+ const executable = candidates.find(path => { try { return lstatSync(path).isFile(); } catch { return false; } });
195
+ if (!executable) throw new Error(`Cannot bound executable ${command.command}`);
196
+ files[`executable:${command.id}`] = digest(readFileSync(realpathSync(executable)));
197
+ for (const path of command.reuse?.inputs ?? []) visit(projectFile(root, path), path);
198
+ }
199
+ } catch (error) { limitation = error.message; }
200
+ const key = digest(JSON.stringify({ files, commands, config: existsSync(resolve(root, '.cyc/config.json')) ? digest(readFileSync(resolve(root, '.cyc/config.json'))) : null, node: process.versions, platform: process.platform, arch: process.arch, environment: digest(JSON.stringify(Object.entries(process.env).filter(([name]) => name !== 'CODEX_TOOL_CALL_ID').sort())) }));
201
+ return { key, bounded: limitation === null, suitable: !limitation && commands.every(c => c.reuse?.kind === 'local-deterministic'), limitation };
202
+ }
170
203
 
171
204
  function runPath(root, id) {
172
205
  if (!/^[a-z0-9-]{1,80}$/.test(id ?? '')) throw new Error('A valid --run ID is required.');
@@ -188,7 +221,7 @@ export function activeRun(root, session = callerSession()) {
188
221
  .map(entry => { try { return json(resolve(directory, entry.name, 'state.json')); } catch { return null; } })
189
222
  .filter(run => run && ['running', 'paused', 'blocked'].includes(run.status));
190
223
  const key = session === undefined ? undefined : gateSession(root, session);
191
- const candidates = key === undefined ? runs : runs.filter(run => run.session === key || !run.session);
224
+ const candidates = key === undefined ? runs.filter(run => !run.execution?.conversationId) : runs.filter(run => run.execution ? run.execution.conversationId === session || (!run.execution.conversationId && !run.session) : run.session === key || !run.session);
192
225
  if (candidates.length === 1) return candidates[0].id;
193
226
  if (!candidates.length) throw new Error(key === undefined || !runs.length ? 'No active CYC run in this project. Start one with run start, or pass --run ID for a finished run.' : `No active run for session ${key}; other conversations' runs are not selected implicitly. Pass --run ID.`);
194
227
  throw new Error(`Several runs are active: ${candidates.map(run => `${run.id} (${run.status}: ${run.goal.slice(0, 60)})`).join('; ')}. Pass --run ID or --session.`);
@@ -335,7 +368,9 @@ function withWorkspaceLock(root, operation, protectedPaths, work) {
335
368
  }
336
369
 
337
370
  function transact(root, id, work) {
371
+ if (operationCancelled() && !activeProgress.stopping) throw new Error('Operation cancelled; no further workflow stages will advance.');
338
372
  const path = runPath(root, id);
373
+ assertRunOwner(root, json(path));
339
374
  return withWorkspaceLock(root, `update run ${id}`, json(path).protectedPaths, ownership => {
340
375
  const lock = `${path}.lock`;
341
376
  // The run lock is taken only while holding the workspace lock, so one left behind belongs to an
@@ -376,6 +411,14 @@ function requireActive(state) {
376
411
  if (state.status !== 'running') throw new Error(`Run is ${state.status}; it cannot advance.`);
377
412
  if (state.engineVersion && state.engineVersion !== engineVersion) throw new Error(`Run started with CYC ${state.engineVersion}, current engine is ${engineVersion}. Stop this run, reload host skills, and explicitly start a new run; previous evidence is retained.`);
378
413
  }
414
+ export function assertRunOwner(root, state) {
415
+ if (!state.execution) return;
416
+ const execution = state.execution, caller = callerSession();
417
+ if (execution.conversationId && execution.conversationId !== caller) throw new Error(`Run ${state.id} belongs to conversation ${execution.conversationId}; the current conversation cannot mutate it.`);
418
+ if (execution.gateSession && !caller) throw new Error(`Run ${state.id} needs its current conversation context before mutation.`);
419
+ const observed = resolveExecution(root, { executionMode: execution.mode, conversationId: execution.gateSession ? caller : execution.conversationId ?? undefined, ...(execution.gateSession ? {} : { session: execution.workflowSession ?? undefined }) });
420
+ if (execution.gateSession && observed.gateSession !== execution.gateSession) throw new Error(`Run ${state.id} belongs to native gate ${execution.gateSession}; the current conversation cannot mutate it.`);
421
+ }
379
422
  function budget(state) {
380
423
  if (!state.limits.maxDurationMs || Date.now() - Date.parse(state.startedAt) < state.limits.maxDurationMs) return true;
381
424
  state.status = 'exhausted';
@@ -454,7 +497,14 @@ const tailBytes = outputLimit * 4;
454
497
  export function runCheckProcess(spec, io) {
455
498
  return new Promise(finish => {
456
499
  const streams = {};
457
- let child, timedOut = false, failure = null, done = false, grace, drain, watch;
500
+ let child, timedOut = false, failure = null, done = false, grace, drain, watch, progressTimer, lastOutputAt = null, lastProgressAt = 0;
501
+ const report = status => {
502
+ if (!spec.progressPath) return;
503
+ lastProgressAt = Date.now();
504
+ const latestOutput = Object.values(streams).map(s => Buffer.concat(s.tail).toString('utf8')).join('\n').slice(-2000);
505
+ const record = { ...spec.progress, status, check: spec.checkId, elapsedSeconds: (Date.now() - Date.parse(spec.progress.startedAt)) / 1000, latestOutput, lastOutputAt, logs: { stdout: spec.stdout, stderr: spec.stderr }, updatedAt: new Date().toISOString() };
506
+ try { const temp = `${spec.progressPath}.${process.pid}.tmp`; io.writeFileSync(temp, JSON.stringify(record)); io.renameSync(temp, spec.progressPath); } catch { /* a lost progress update cannot decide the check */ }
507
+ };
458
508
  const stop = () => {
459
509
  if (!child?.pid) return;
460
510
  if (process.platform === 'win32') {
@@ -466,25 +516,30 @@ export function runCheckProcess(spec, io) {
466
516
  const end = status => {
467
517
  if (done) return;
468
518
  done = true;
469
- clearTimeout(timer); clearTimeout(grace); clearTimeout(drain); clearInterval(watch);
519
+ clearTimeout(timer); clearTimeout(grace); clearTimeout(drain); clearInterval(watch); clearInterval(progressTimer);
470
520
  const bytes = {}, stored = {}, tailPeak = {};
471
521
  for (const [name, stream] of Object.entries(streams)) {
472
522
  io.closeSync(stream.fd);
473
523
  io.writeFileSync(`${spec[name]}.tail`, Buffer.concat(stream.tail).subarray(-spec.tailBytes));
474
524
  bytes[name] = stream.bytes; stored[name] = stream.stored; tailPeak[name] = stream.tailPeak;
475
525
  }
526
+ report(timedOut ? 'timeout' : failure?.code === 'CYC_CHECK_CANCELLED' ? 'cancelled' : failure?.code === 'CYC_CONTROLLER_ENDED' ? 'interrupted' : failure ? 'crashed' : 'check-complete');
476
527
  finish({ status: timedOut ? null : status, timedOut, error: failure, bytes, stored, tailPeak });
477
528
  };
478
529
  // A process that ignores the kill and keeps its output open must not hold the controller.
479
530
  const timer = setTimeout(() => { timedOut = true; stop(); grace = setTimeout(() => end(null), 5000); }, spec.timeoutMs);
480
- if (spec.parentPid) {
531
+ if (spec.parentPid || spec.cancelPath) {
481
532
  watch = setInterval(() => {
482
- try { process.kill(spec.parentPid, 0); } catch (error) { if (error.code === 'ESRCH') { stop(); failure = { code: 'CYC_CONTROLLER_ENDED', message: 'The controller ended while the check ran.' }; end(null); } }
483
- }, 500);
533
+ if (spec.cancelPath && io.existsSync(spec.cancelPath)) { failure = { code: 'CYC_CHECK_CANCELLED', message: 'Check cancelled by the owned stop request.' }; stop(); end(null); return; }
534
+ if (spec.parentPid) try { process.kill(spec.parentPid, 0); } catch (error) { if (error.code === 'ESRCH') { failure = { code: 'CYC_CONTROLLER_ENDED', message: 'The controller ended while the check ran.' }; stop(); end(null); } }
535
+ }, 200);
484
536
  }
485
- if (spec.forwardSignals) for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { stop(); process.exit(1); });
537
+ if (spec.forwardSignals) for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { failure = { code: 'CYC_CHECK_CANCELLED', message: `Check cancelled by ${signal}.` }; stop(); end(null); });
486
538
  for (const name of ['stdout', 'stderr']) streams[name] = { fd: io.openSync(spec[name], 'w'), bytes: 0, stored: 0, tail: [], tailLength: 0, tailPeak: 0 };
539
+ report('running');
540
+ if (spec.progressPath) progressTimer = setInterval(() => report('running'), 1000);
487
541
  const env = { ...process.env };
542
+ delete env.CODEX_TOOL_CALL_ID; // invocation transport metadata is neither a check input nor a reusable context
488
543
  if (spec.nodeOptions === null) delete env.NODE_OPTIONS; else if (spec.nodeOptions !== undefined) env.NODE_OPTIONS = spec.nodeOptions;
489
544
  try { child = io.spawn(spec.command, spec.args, { cwd: spec.cwd, env, shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'], detached: process.platform !== 'win32' }); }
490
545
  catch (error) { failure = { code: error.code ?? null, message: error.message }; end(null); return; }
@@ -496,10 +551,13 @@ export function runCheckProcess(spec, io) {
496
551
  // A write that fails (a full disk) stops storing; the stream then counts as cut off.
497
552
  try { stream.stored += io.writeSync(stream.fd, chunk, 0, Math.min(chunk.length, spec.limit - stream.stored)); } catch { /* stored stays short of bytes */ }
498
553
  }
554
+ const firstOutput = lastOutputAt === null;
499
555
  stream.bytes += chunk.length;
556
+ lastOutputAt = new Date().toISOString();
500
557
  stream.tail.push(chunk); stream.tailLength += chunk.length;
501
558
  while (stream.tailLength - stream.tail[0].length >= spec.tailBytes) stream.tailLength -= stream.tail.shift().length;
502
559
  stream.tailPeak = Math.max(stream.tailPeak, stream.tailLength);
560
+ if (firstOutput || Date.now() - lastProgressAt >= 250) report('running');
503
561
  });
504
562
  }
505
563
  child.on('error', error => { failure = { code: error.code ?? null, message: error.message }; if (!child.pid) end(null); });
@@ -544,18 +602,21 @@ function readOutput(path, bytes, stored, limit) {
544
602
  return { whole: null, tail: keepTail(readFileSync(`${path}.tail`).toString('utf8')) };
545
603
  }
546
604
 
547
- export function runCommands(root, commands, remaining = () => Infinity, { readLimit = outputReadLimit } = {}) {
605
+ export function runCommands(root, commands, remaining = () => Infinity, { readLimit = outputReadLimit, phase = 'candidate' } = {}) {
548
606
  const results = [];
549
607
  for (const command of commands) {
608
+ if (operationCancelled()) throw Object.assign(new Error('Operation cancelled before the next check; proof restoration still runs.'), { code: 'CYC_OPERATION_CANCELLED' });
550
609
  const left = remaining();
551
610
  if (left <= 0) break;
552
611
  const timeoutMs = Math.min(command.timeoutMs ?? defaultCheckTimeoutMs, left);
553
- const folder = checkFolder(root);
612
+ const logsRoot = activeProgress ? projectFile(root, `.cyc/runs/${activeProgress.runId}/check-logs`) : null;
613
+ if (logsRoot) mkdirSync(logsRoot, { recursive: true });
614
+ const folder = logsRoot ? mkdtempSync(resolve(logsRoot, 'check-')) : checkFolder(root);
554
615
  let run, stdout = '', stderr = '', tests = null;
555
616
  try {
556
617
  const file = name => resolve(folder, name);
557
618
  // The runner gets no NODE_OPTIONS, so a preload cannot break it; the check still gets them.
558
- const spec = { command: command.command, args: command.args ?? [], cwd: root, timeoutMs, limit: readLimit, tailBytes, stdout: file('stdout'), stderr: file('stderr'), parentPid: process.pid, forwardSignals: true, nodeOptions: process.env.NODE_OPTIONS ?? null };
619
+ const spec = { command: command.command, args: command.args ?? [], cwd: root, timeoutMs, limit: readLimit, tailBytes, stdout: file('stdout'), stderr: file('stderr'), parentPid: process.pid, forwardSignals: true, nodeOptions: process.env.NODE_OPTIONS ?? null, ...(activeProgress ? { cancelPath: activeProgress.cancelPath, progressPath: activeProgress.path, progress: { ...activeProgress, phase }, checkId: command.id } : {}) };
559
620
  writeFileSync(file('runner.cjs'), checkRunnerSource);
560
621
  writeFileSync(file('spec.json'), JSON.stringify(spec));
561
622
  const { NODE_OPTIONS, ...env } = process.env;
@@ -577,7 +638,7 @@ export function runCommands(root, commands, remaining = () => Infinity, { readLi
577
638
  } finally {
578
639
  // A scanner can still hold the files open on Windows; a folder left in the temp directory
579
640
  // must not decide the check.
580
- try { rmSync(folder, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { /* left for the system's temp cleanup */ }
641
+ if (!activeProgress) try { rmSync(folder, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { /* left for the system's temp cleanup */ }
581
642
  }
582
643
  // A check cut short by the run's own deadline needs a longer budget, not a longer timeout.
583
644
  const error = !run.timedOut ? run.error?.message ?? null
@@ -585,6 +646,7 @@ export function runCommands(root, commands, remaining = () => Infinity, { readLi
585
646
  : `Check timed out after ${timeoutMs} ms. If it needs longer, give it a larger timeoutMs; a check without one gets ${defaultCheckTimeoutMs / 60000} minutes.`;
586
647
  results.push({ id: command.id, command: command.command, args: command.args, exitCode: run.status,
587
648
  passed: run.status === 0 && !run.error && !run.timedOut, stdout, stderr, ...(tests ? { tests } : {}), error, errorCode: run.timedOut ? 'ETIMEDOUT' : run.error?.code ?? null, timeoutMs });
649
+ if (run.error?.code === 'CYC_CHECK_CANCELLED') break;
588
650
  }
589
651
  return results;
590
652
  }
@@ -618,7 +680,7 @@ export function measureBaseline(root, id) {
618
680
  try { atomicJSON(path, record); } catch { /* the run may have been removed */ }
619
681
  return record;
620
682
  }
621
- const base = { cacheKey: state.baseline.cacheKey, sourceHash: state.baseline.sourceHash, startedAt: new Date().toISOString() };
683
+ const base = { role: 'original-only', inputs: state.baseline.inputs, cacheKey: state.baseline.cacheKey, sourceHash: state.baseline.sourceHash, startedAt: new Date().toISOString() };
622
684
  let record;
623
685
  try {
624
686
  // The agent's first command and this measurement both take the operation lock. The measurement
@@ -630,12 +692,13 @@ export function measureBaseline(root, id) {
630
692
  const results = runCommands(root, state.commands).map(measuredResult);
631
693
  const after = sourceSnapshot(root);
632
694
  // Edits by the agent, another session, or a file-writing check make the measurement unreliable.
633
- const clean = before.hash === state.baseline.sourceHash && after.hash === state.baseline.sourceHash;
695
+ const inputs = state.baseline.inputs ? measurementInputs(root, state.commands) : null;
696
+ const clean = before.hash === state.baseline.sourceHash && after.hash === state.baseline.sourceHash && (!inputs || inputs.bounded && inputs.key === state.baseline.inputs.key);
634
697
  return clean
635
698
  ? { ...base, status: 'complete', checkedAt: new Date().toISOString(), results }
636
699
  : { ...base, status: 'invalid', checkedAt: new Date().toISOString(), results, reason: 'Project files changed while the baseline was measured (an edit started before it finished, another session edited the folder, or a configured check writes files). Pre-existing failures cannot be accepted for this run.' };
637
700
  }));
638
- if (record.status === 'complete') cacheBaseline(root, record);
701
+ if (record.status === 'complete' && state.baseline.inputs?.suitable) cacheBaseline(root, record);
639
702
  } catch (error) {
640
703
  record = { ...base, status: 'error', reason: error.message };
641
704
  }
@@ -655,6 +718,78 @@ function retryWhileBusy(work, { attempts = 40, delayMs = 250 } = {}) {
655
718
  }
656
719
  }
657
720
 
721
+ const progressPath = (root, id) => projectFile(root, `.cyc/runs/${id}/progress.json`);
722
+ const cancellationPath = (root, id, operationId) => projectFile(root, `.cyc/runs/${id}/operations/${operationId}.cancel.json`);
723
+ const operationCancelled = () => Boolean(activeProgress?.cancelPath && existsSync(activeProgress.cancelPath));
724
+ const sameLockIdentity = owner => Object.entries(lockIdentity()).every(([key, value]) => (owner[key] ?? null) === value);
725
+ function operationView(root, id, operationId) {
726
+ const record = json(progressPath(root, id));
727
+ if (record.operationId !== operationId) throw new Error('Unknown or superseded operation handle; use the exact run/operation IDs returned by the controller.');
728
+ if (!record.result && !record.error && record.workerPid && sameLockIdentity(record) && !processAlive(record.workerPid)) return { ...record, status: 'crashed', error: { message: 'Operation worker ended without a result. Use run recover with this run ID; retain ownership and any proof backup.' } };
729
+ return { ...record, elapsedSeconds: (Date.now() - Date.parse(record.startedAt)) / 1000 };
730
+ }
731
+ export function waitOperation(root, id, operationId, waitMs = 30000) {
732
+ assertRunOwner(root, readRun(root, id));
733
+ if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 60000) throw new Error('waitMs must be 0-60000; use a bounded 30000-60000 ms wait when the host permits.');
734
+ const deadline = Date.now() + waitMs;
735
+ let view;
736
+ do {
737
+ view = operationView(root, id, operationId);
738
+ if (view.result || view.error || Date.now() >= deadline) break;
739
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(200, deadline - Date.now()));
740
+ } while (true);
741
+ const { path, ...safe } = view;
742
+ return { ...safe, runId: id, operationId, operationComplete: Boolean(view.result || view.error), finished: view.result?.finished === true, ...(view.error ? { ok: false } : {}), nextAction: view.result?.nextAction ?? (view.result || view.error ? null : { action: 'wait', command: `run wait --run ${id} --operation ${operationId} --wait-ms 30000`, instruction: 'This background operation remains active. Wait on this handle; locks are reserved for ownership/recovery.' }) };
743
+ }
744
+ export function startOperation(root, id, { action, input = {}, waitMs = 30000 } = {}) {
745
+ const state = readRun(root, id); assertRunOwner(root, state); requireActive(state);
746
+ if (!['finish', 'verify', 'prove-red'].includes(action)) throw new Error('Background operation must be finish, verify or prove-red.');
747
+ if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 60000) throw new Error('waitMs must be 0-60000.');
748
+ let pending;
749
+ try { pending = json(progressPath(root, id)); } catch { /* no active handle */ }
750
+ if (pending && !pending.result && !pending.error && pending.workerPid && processAlive(pending.workerPid)) return waitOperation(root, id, pending.operationId, waitMs);
751
+ const operationId = withWorkspaceLock(root, `launch ${action} run ${id}`, state.protectedPaths, () => {
752
+ const operationId = randomUUID(), requestPath = projectFile(root, `.cyc/runs/${id}/operations/${operationId}.json`);
753
+ atomicJSON(requestPath, { action, input });
754
+ const record = { runId: id, operationId, action, phase: 'starting', status: 'running', startedAt: new Date().toISOString(), latestOutput: '', lastOutputAt: null, ...lockIdentity() };
755
+ const worker = spawn(process.execPath, [fileURLToPath(new URL('./run-worker.mjs', import.meta.url)), root, id, operationId], { cwd: tmpdir(), detached: true, windowsHide: true, stdio: 'ignore' });
756
+ record.workerPid = worker.pid ?? null;
757
+ if (!worker.pid) record.error = { message: 'Operation worker could not start.' };
758
+ atomicJSON(progressPath(root, id), record);
759
+ worker.on('error', error => atomicJSON(progressPath(root, id), { ...record, status: 'crashed', error: { message: error.message } })); worker.unref();
760
+ return operationId;
761
+ });
762
+ return waitOperation(root, id, operationId, waitMs);
763
+ }
764
+ export function executeOperation(root, id, operationId) {
765
+ if (!/^[a-f0-9-]{36}$/.test(operationId ?? '')) throw new Error('Invalid operation ID.');
766
+ const path = progressPath(root, id), initial = operationView(root, id, operationId);
767
+ if (initial.workerPid !== process.pid) throw new Error('Operation belongs to a different worker.');
768
+ const request = json(projectFile(root, `.cyc/runs/${id}/operations/${operationId}.json`));
769
+ activeProgress = { ...initial, path, cancelPath: cancellationPath(root, id, operationId), phase: request.action };
770
+ const acknowledgeStop = () => {
771
+ if (!operationCancelled()) return false;
772
+ const state = readRun(root, id);
773
+ activeProgress.stopping = true;
774
+ try { if (!terminal.has(state.status)) controlRun(root, id, 'stop'); }
775
+ finally { activeProgress.stopping = false; }
776
+ return true;
777
+ };
778
+ try {
779
+ if (operationCancelled()) throw new Error('Operation cancelled before starting.');
780
+ const result = retryWhileBusy(() => request.action === 'finish' ? finishRun(root, id, request.input) : request.action === 'prove-red' ? proveRun(root, id, request.input) : verifyRun(root, id));
781
+ const cancelled = acknowledgeStop();
782
+ if (cancelled) Object.assign(result, { cancelled: true, passed: false, finished: false, status: readRun(root, id).status });
783
+ if (result.results) result.results = result.results.map(({ stdout, stderr, ...r }) => ({ ...r, outputTail: `${stdout ?? ''}\n${stderr ?? ''}`.slice(-2000) }));
784
+ const latest = json(path);
785
+ atomicJSON(path, { ...latest, status: cancelled ? 'cancelled' : 'finished', completedAt: new Date().toISOString(), result });
786
+ } catch (error) {
787
+ const cancelled = acknowledgeStop();
788
+ const latest = json(path);
789
+ atomicJSON(path, { ...latest, status: cancelled ? 'cancelled' : 'failed', completedAt: new Date().toISOString(), error: { message: error.message, field: error.field, repairTemplate: error.repairTemplate, setup: error.setup } });
790
+ } finally { activeProgress = null; }
791
+ }
792
+
658
793
  // The background worker's process, recorded at start so a worker that ended without writing its
659
794
  // result is noticed, instead of leaving the baseline pending for the rest of the run.
660
795
  const baselineWorkerFile = (root, id) => projectFile(root, `.cyc/runs/${id}/baseline-worker.json`);
@@ -761,6 +896,7 @@ function testProofStatus(root, state, snapshot = null) {
761
896
  const proof = state.testProof;
762
897
  if (!proof?.passed) return { required: true, mode, status: proof ? 'failed' : 'missing', command: `run prove-red --run ${state.id}`, ...(proof ? { verdict: proof.verdict } : {}) };
763
898
  const files = (snapshot ?? cachedSnapshot(root)).files;
899
+ if (proof.commandPlanHash && (proof.commandPlanHash !== digest(JSON.stringify(state.proofCommands ?? state.commands)) || proof.inputs?.key !== measurementInputs(root, state.proofCommands ?? state.commands).key)) return { required: true, mode, status: 'stale', stale: ['proof commands/toolchain/environment/dependencies'], command: `run prove-red --run ${state.id}` };
764
900
  const stale = Object.entries(proof.testFiles).filter(([path, hash]) => files[path] !== hash).map(([path]) => path);
765
901
  return stale.length ? { required: true, mode, status: 'stale', stale, command: `run prove-red --run ${state.id}` } : { required: true, mode, status: 'proven', testFiles: Object.keys(proof.testFiles) };
766
902
  }
@@ -770,7 +906,7 @@ function testProofStatus(root, state, snapshot = null) {
770
906
  // project must pass, so the failure comes from the new tests. Refactors must stay green, which
771
907
  // shows the tests pin behavior the original code already had. Files are restored afterwards; a
772
908
  // backup stays until the restored tree matches the pre-proof snapshot exactly.
773
- export function proveRun(root, id, { tests } = {}) {
909
+ export function proveRun(root, id, { tests, measureOriginal = false } = {}) {
774
910
  return transact(root, id, (state, ownership) => {
775
911
  requireActive(state);
776
912
  if (!budget(state) || !guard(root, state)) return state;
@@ -780,6 +916,9 @@ export function proveRun(root, id, { tests } = {}) {
780
916
  const baseline = currentBaseline(root, state);
781
917
  if (baseline?.status === 'pending') throw new Error('The baseline is still measuring in the background. Try again when run next shows it complete.');
782
918
  const mode = state.playbook === 'refactor' ? 'green' : 'red';
919
+ const proofCommands = state.proofCommands ?? state.commands;
920
+ const proofInputs = measurementInputs(root, proofCommands);
921
+ if (typeof measureOriginal !== 'boolean') throw new Error('measureOriginal must be boolean.');
783
922
  const before = sourceSnapshot(root);
784
923
  const initial = state.initialSource.files;
785
924
  const changed = [...new Set([...Object.keys(initial), ...Object.keys(before.files)])].filter(path => initial[path] !== before.files[path]);
@@ -845,11 +984,19 @@ export function proveRun(root, id, { tests } = {}) {
845
984
  // A failure's file as an exact project-relative path. Runners report absolute paths (node --test)
846
985
  // or paths relative to the project (tap, jest); a suffix match would let an old failure in
847
986
  // legacy/test/x.test.mjs pass for a new test/x.test.mjs. Anything outside the project is null.
848
- const realRoot = realpathSync(root);
987
+ const realRoot = realpathSync.native(root);
849
988
  const projectRelative = file => {
850
989
  if (!text(file)) return null;
851
- const value = file.replace(/^file:\/\/\/?/, '').split(String.fromCharCode(92)).join('/');
852
- const path = isAbsolute(value) || /^[A-Za-z]:\//.test(value) ? slash(relative(realRoot, resolve(value))) : value.replace(/^\.\//, '');
990
+ let value;
991
+ try { value = (file.startsWith('file:') ? fileURLToPath(file) : file).split(String.fromCharCode(92)).join('/'); }
992
+ catch { return null; }
993
+ let path = value.replace(/^\.\//, '');
994
+ if (isAbsolute(value) || /^[A-Za-z]:\//.test(value)) {
995
+ // Reject foreign roots before lookup; native realpath expands Windows 8.3 aliases.
996
+ if (isAbsolute(relative(realRoot, resolve(value)))) return null;
997
+ try { path = slash(relative(realRoot, realpathSync.native(value))); }
998
+ catch { return null; }
999
+ }
853
1000
  return !path || path === '..' || path.startsWith('../') || isAbsolute(path) ? null : path;
854
1001
  };
855
1002
  const failuresInNewTestFiles = results => {
@@ -868,10 +1015,16 @@ export function proveRun(root, id, { tests } = {}) {
868
1015
  }
869
1016
  return added;
870
1017
  };
871
- let treatment; let control = null; let controlSource = null; let added = null; let failure;
1018
+ let treatment; let control = null; let broadControl = null; let broadInputs = null; let controlSource = null; let added = null; let failure; let reusedTreatmentFrom = null;
1019
+ let previous = null;
1020
+ if (measureOriginal && state.testProof?.passed && state.testProof.commandPlanHash === digest(JSON.stringify(proofCommands)) && state.testProof.inputs?.bounded && state.testProof.inputs.key === proofInputs.key && Object.entries(state.testProof.testFiles).every(([path, hash]) => before.files[path] === hash) && testFiles.length === Object.keys(state.testProof.testFiles).length) {
1021
+ assertArtifacts(root, [{ path: state.testProof.receiptPath, sha256: state.testProof.receiptHash }]);
1022
+ previous = json(projectFile(root, state.testProof.receiptPath)); reusedTreatmentFrom = state.testProof.receiptPath;
1023
+ }
872
1024
  try {
873
1025
  apply(sourceFiles, originals);
874
- if (!conflicts.size) treatment = runCommands(root, state.commands);
1026
+ if (!conflicts.size) treatment = previous?.treatment ?? runCommands(root, proofCommands, undefined, { phase: 'original-plus-new-tests' });
1027
+ if (operationCancelled()) throw Object.assign(new Error('Original-source proof cancelled.'), { code: 'CYC_OPERATION_CANCELLED' });
875
1028
  inspect();
876
1029
  if (!conflicts.size && mode === 'red') {
877
1030
  // The control run measures the run-start code, to tell a failure the new tests cause from
@@ -879,10 +1032,15 @@ export function proveRun(root, id, { tests } = {}) {
879
1032
  // check (the new tests would not catch the change), or when every failure is in a new file.
880
1033
  added = treatment.every(result => result.passed) ? {} : failuresInNewTestFiles(treatment);
881
1034
  if (added) controlSource = Object.keys(added).length ? 'not needed: every failure is in a test file this change added' : 'not needed: every check passed with the new tests';
882
- else if (baseline?.status === 'complete' && baseline.sourceHash === state.initialSource.hash) { control = baseline.results; controlSource = 'baseline at run start'; }
883
- else { apply(testFiles, originals); if (!conflicts.size) { control = runCommands(root, state.commands); controlSource = 'in place'; } }
1035
+ else if (previous?.control) { control = previous.control; controlSource = `reused original-only from ${reusedTreatmentFrom}`; }
1036
+ else if (baseline?.status === 'complete' && baseline.sourceHash === state.initialSource.hash && digest(JSON.stringify(proofCommands)) === digest(JSON.stringify(state.commands))) { control = baseline.results; controlSource = 'baseline at run start'; }
1037
+ else { apply(testFiles, originals); if (!conflicts.size) { control = runCommands(root, proofCommands, undefined, { phase: 'original-only' }); controlSource = 'in place'; } }
884
1038
  }
885
- } catch (error) { failure = error.message; }
1039
+ if (!conflicts.size && measureOriginal && digest(JSON.stringify(proofCommands)) !== digest(JSON.stringify(state.commands))) {
1040
+ apply(testFiles, originals); broadInputs = measurementInputs(root, state.commands);
1041
+ if (!conflicts.size) broadControl = runCommands(root, state.commands, undefined, { phase: 'original-only-broad' });
1042
+ }
1043
+ } catch (error) { if (error.code !== 'CYC_OPERATION_CANCELLED') failure = error.message; }
886
1044
  finally {
887
1045
  inspect();
888
1046
  // Restore owned paths independently: one I/O failure must not abandon the
@@ -912,6 +1070,13 @@ export function proveRun(root, id, { tests } = {}) {
912
1070
  return { runId: id, status: state.status, passed: false, error: `Proof halted. Preserve current files and compare them with candidate versions in ${backup}; do not overwrite either blindly.`, recovery: state.proofRecovery };
913
1071
  }
914
1072
  rmSync(backup, { recursive: true, force: true });
1073
+ if (operationCancelled()) {
1074
+ const receiptPath = `.cyc/runs/${id}/checks/proof-cancelled-${randomUUID()}.json`;
1075
+ atomicJSON(projectFile(root, receiptPath), { passed: false, cancelled: true, restored: true, treatment: treatment ?? [], control, checkedAt: new Date().toISOString() });
1076
+ state.testProof = null; state.verification = null;
1077
+ log(state, 'proof-cancelled', { receipt: receiptPath, restored: true });
1078
+ return { runId: id, passed: false, cancelled: true, restored: true, receiptPath };
1079
+ }
915
1080
  const summary = results => results?.map(({ id: check, passed, exitCode }) => ({ id: check, passed, exitCode })) ?? null;
916
1081
  // With test runner output (TAP, mocha, jest) the proof sees test names: treatment and control
917
1082
  // differ only by the new tests, so a failing test that the control run did not have is one of
@@ -956,10 +1121,24 @@ export function proveRun(root, id, { tests } = {}) {
956
1121
  const parsed = testsOf(result);
957
1122
  const selected = [...(parsed?.failing.values() ?? [])].filter(entry => !named[result.id]?.length || named[result.id].includes(entry.path.join(' > ')));
958
1123
  if (!selected.length) return [{ id: digest(`${result.id}:check`).slice(0, 24), check: result.id, name: result.id, file: null, error: result.error ?? '', hint: 'unclassified' }];
959
- return selected.map(entry => ({ id: digest(`${result.id}:${entry.file}:${entry.path.join(' > ')}`).slice(0, 24), check: result.id, name: entry.path.join(' > '), file: entry.file ?? null, error: entry.error ?? '', details: entry.details, hint: failureHint(entry) }));
1124
+ const loads = new Map(); let headerFile = null;
1125
+ for (const line of parsed.other?.values() ?? []) {
1126
+ const header = line.match(/^# (file:\/\/\/.+?):\d+(?::\d+)?$/);
1127
+ if (header) headerFile = projectRelative(header[1]);
1128
+ const importer = projectRelative(line.split(' imported from ')[1]?.trim()) ?? (/does not provide an export/.test(line) ? headerFile : null);
1129
+ if (importer && /Cannot find (?:module|package)|does not provide an export/.test(line)) loads.set(importer, [...(loads.get(importer) ?? []), line]);
1130
+ }
1131
+ return selected.map(entry => {
1132
+ // Node reports a load failure outside its generic file-level "test failed" wrapper.
1133
+ // Associate only an explicit matching importer, never another test's suite diagnostic.
1134
+ const diagnostics = loads.get(projectRelative(entry.file)) ?? [];
1135
+ const observed = diagnostics.length ? { ...entry, error: diagnostics.join('\n'), details: [...(entry.details ?? []), ...diagnostics] } : entry;
1136
+ return { id: digest(`${result.id}:${entry.file}:${entry.path.join(' > ')}`).slice(0, 24), check: result.id, name: entry.path.join(' > '), file: entry.file ?? null, error: observed.error ?? '', details: observed.details, hint: failureHint(observed), boundary: diagnostics[0]?.match(/Cannot find (?:module|package) '([^']+)'|requested module ('[^']+' does not provide an export named '[^']+')/)?.slice(1).find(Boolean) ?? null };
1137
+ });
960
1138
  });
961
- atomicJSON(projectFile(root, receiptPath), { mode, passed, verdict, claim, failures, base: state.base?.commit ?? null, originalSourceHash: state.initialSource.hash, testFiles, sourceFiles, treatment, control, ...(controlSource ? { controlSource } : {}), checkedAt: new Date().toISOString() });
962
- state.testProof = { mode, passed, verdict, claim, failures, testFiles: Object.fromEntries(testFiles.map(path => [path, before.files[path]])), sourceFiles, receiptPath, receiptHash: digest(readFileSync(projectFile(root, receiptPath))), checkedAt: new Date().toISOString() };
1139
+ const commandPlanHash = digest(JSON.stringify(proofCommands)), broadCommandsHash = digest(JSON.stringify(state.commands));
1140
+ atomicJSON(projectFile(root, receiptPath), { mode, passed, verdict, claim, failures, roles: { treatment: 'original-plus-new-tests', control: control ? 'original-only' : 'not-executed', broadControl: broadControl ? 'original-only-broad' : 'not-executed' }, commandPlanHash, broadCommandsHash, focused: commandPlanHash !== broadCommandsHash, inputs: proofInputs, broadInputs, broadControl, ...(reusedTreatmentFrom ? { reusedTreatmentFrom } : {}), base: state.base?.commit ?? null, originalSourceHash: state.initialSource.hash, testFiles, sourceFiles, treatment, control, ...(controlSource ? { controlSource } : {}), checkedAt: new Date().toISOString() });
1141
+ state.testProof = { mode, passed, verdict, claim, failures, commandPlanHash, inputs: proofInputs, testFiles: Object.fromEntries(testFiles.map(path => [path, before.files[path]])), sourceFiles, receiptPath, receiptHash: digest(readFileSync(projectFile(root, receiptPath))), checkedAt: new Date().toISOString() };
963
1142
  log(state, 'test-proof', { mode, passed, receipt: receiptPath });
964
1143
  return { runId: id, mode, passed, verdict, failures, ...(state.evidenceVersion === 1 && passed && mode === 'red' ? { proofReviewTemplate: { receipt: 'current-proof', cases: failures.map(f => ({ id: f.id, category: 'behavioral | new-interface | setup | unclassified', reason: '<why this failure establishes the selected category>', boundary: '' })) } } : {}), ...(claim ? { proofClaim: claim } : {}), testFiles, sourceFiles, treatment: summary(treatment), control: summary(control), receiptPath };
965
1144
  });
@@ -1034,13 +1213,14 @@ function declaredChecks(root) {
1034
1213
  return { source: commands.length > 1 ? `${found[0].source}, run as ${commands.map(command => command.id).join(', ')}` : found[0].source, commands };
1035
1214
  }
1036
1215
 
1037
- export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy }) {
1216
+ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy, executionMode, conversationId, proofCommands, contextRetention }) {
1038
1217
  root = realpathSync(root);
1039
1218
  if (!text(goal)) throw new Error('A nonempty goal is required.');
1040
1219
  const selected = getPlaybook(playbook ?? routeTask(goal).playbook);
1041
1220
  const config = configuration(root);
1042
1221
  const declared = selected.requiresChecks && !config.commands.length ? declaredChecks(root) : null;
1043
1222
  const commands = declared?.commands ?? config.commands;
1223
+ if (proofCommands !== undefined) { validateCommands(proofCommands, 'proofCommands'); if (!proofCommands.length || !proofPlaybooks.includes(selected.id)) throw new Error('proofCommands needs a nonempty feature/bug-fix/refactor proof plan frozen at start.'); }
1044
1224
  // Checks are frozen into the run and the config is protected while it runs, so a run that
1045
1225
  // starts without them can never verify. Refuse before any run record exists.
1046
1226
  if (selected.requiresChecks && !commands.length) throw new Error(`The ${selected.id} playbook needs project checks, but .cyc/config.json has no verification.commands and the project declares no test command (package.json scripts.test, a Makefile test target, pytest configuration, go.mod, or Cargo.toml). Configure them before starting: follow the CYC Setup method (methods/cyc-setup/SKILL.md, steps 3-7) and add only commands the project already defines, running each once. Editing .cyc/config.json after a run starts halts that run. Advisory playbooks (investigation, explore, plan, review) start without checks.`);
@@ -1052,15 +1232,22 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1052
1232
  if (reviewPolicy !== undefined && (evidenceVersion !== 1 || !['self-allowed', 'fresh-required'].includes(reviewPolicy))) throw new Error('reviewPolicy needs evidenceVersion 1 and self-allowed or fresh-required.');
1053
1233
  for (const c of criteria) if (c.clauses !== undefined && (!Array.isArray(c.clauses) || !c.clauses.length || new Set(c.clauses.map(x => x?.id)).size !== c.clauses.length || c.clauses.some(x => !/^[a-zA-Z0-9_-]+$/.test(x?.id ?? '') || !text(x.description)))) throw new Error(`Criterion ${c.id} clauses need unique {id, description} records.`);
1054
1234
  if (session !== undefined && !/^[A-Za-z0-9_-]{4,80}$/.test(session)) throw new Error('--session must be 4-80 letters, digits, dashes, or underscores.');
1055
- session = gateSession(root, session);
1235
+ const execution = executionMode !== undefined || conversationId !== undefined ? resolveExecution(root, { executionMode, conversationId, session }) : null;
1236
+ session = execution ? execution.gateSession ?? execution.conversationId ?? undefined : gateSession(root, session);
1056
1237
  const id = randomUUID();
1057
1238
  // Scout can be recorded with the start. Check it before any run exists, so a bad assessment
1058
1239
  // creates nothing and the agent fixes one file instead of repairing a half-started run.
1059
1240
  const workContractVersion = selected.stages.includes('build') ? 1 : null;
1241
+ allowedPaths = normalizePaths(root, allowedPaths, 'allowedPaths');
1242
+ const retention = planRetention(root, { goal, build: !!workContractVersion, allowedPaths, explicit: contextRetention ?? scout?.context?.retention });
1243
+ const contextScope = retention.disposition === 'required' ? [retention.index, ...retention.features.map(f => f.doc)] : [];
1244
+ const protectedContext = contextScope.filter(path => protectedPathMatcher(root, config.protectedPaths)(path));
1245
+ if (protectedContext.length) { retention.disposition = 'restricted'; retention.reason = `Context is protected: ${protectedContext.join(', ')}. Retention remains pending.`; }
1246
+ else if (allowedPaths.length) allowedPaths = [...new Set([...allowedPaths, ...contextScope])];
1060
1247
  if (scout !== undefined) {
1061
1248
  if (selected.stages[0] !== 'scout') throw new Error(`The ${selected.id} playbook starts with ${selected.stages[0]}, not Scout; record it with run record.`);
1062
1249
  if (!text(plan)) throw new Error('A scout assessment at start needs plan: one or two sentences on the approach.');
1063
- const draft = { id, playbook: selected.id, workContractVersion, handoffs: [] };
1250
+ const draft = { id, playbook: selected.id, workContractVersion, contextRetention: retention, handoffs: [] };
1064
1251
  fillDerived(root, draft, 'scout', scout);
1065
1252
  validateAssessment(draft, { stage: 'scout', status: 'passed', assessment: assessmentPaths(root, scout) }, path => readFileSync(projectFile(root, path)));
1066
1253
  }
@@ -1077,16 +1264,18 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1077
1264
  // still prevent completion. Reuse a matching earlier measurement; otherwise measure in the
1078
1265
  // background while the agent does read-only work.
1079
1266
  const wanted = selected.requiresChecks && commands.length && config.baseline && mode !== 'off';
1080
- const cacheKey = wanted ? digest(`${initialSource.hash}:${JSON.stringify(commands)}`) : null;
1081
- const cached = wanted ? readBaselineCache(root)[cacheKey] : null;
1267
+ const inputs = wanted ? measurementInputs(root, commands) : null;
1268
+ const cacheKey = wanted ? digest(`${initialSource.hash}:${inputs.key}`) : null;
1269
+ const cached = wanted && inputs.suitable ? readBaselineCache(root)[cacheKey] : null;
1082
1270
  const baseline = !wanted ? null
1083
- : cached ? { status: 'complete', reused: true, cacheKey, sourceHash: initialSource.hash, checkedAt: cached.checkedAt, results: cached.results }
1084
- : { status: 'pending', cacheKey, sourceHash: initialSource.hash, requestedAt: new Date().toISOString() };
1271
+ : cached ? { status: 'complete', reused: true, cacheKey, inputs, sourceHash: initialSource.hash, checkedAt: cached.checkedAt, results: cached.results }
1272
+ : { status: 'pending', cacheKey, inputs, sourceHash: initialSource.hash, requestedAt: new Date().toISOString() };
1085
1273
  const state = {
1086
1274
  schemaVersion: 1, engineVersion, id, goal, playbook: selected.id, stages: selected.stages, requiresChecks: selected.requiresChecks,
1087
- workContractVersion, ...(evidenceVersion === 1 ? { evidenceVersion, reviewPolicy: reviewPolicy ?? 'self-allowed', requirements: { text: requirements, sha256: digest(requirements) }, criteriaHash: digest(JSON.stringify(criteria)) } : {}), ...ledger,
1088
- criteria, inferredCriteria, session: session ?? null, status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1275
+ workContractVersion, contextRetention: retention, ...(evidenceVersion === 1 ? { evidenceVersion, reviewPolicy: reviewPolicy ?? 'self-allowed', requirements: { text: requirements, sha256: digest(requirements) }, criteriaHash: digest(JSON.stringify(criteria)) } : {}), ...ledger,
1276
+ criteria, inferredCriteria, session: session ?? null, ...(execution ? { execution } : {}), status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1089
1277
  startedAt: new Date().toISOString(), limits: config.limits, commands, ...(declared ? { verificationSource: `declared by ${declared.source}` } : {}),
1278
+ ...(proofCommands ? { proofCommands: structuredClone(proofCommands) } : {}),
1090
1279
  protectedPaths: config.protectedPaths, protectedFiles: protectedSnapshot(root, config.protectedPaths), allowedPaths,
1091
1280
  initialSource, base, ...(capture ? { sourceCapture: capture.metadata } : {}), testProof: null, baseline, acceptedFailures: [], handoffs: [], verification: null, history: []
1092
1281
  };
@@ -1137,7 +1326,15 @@ function stageTemplate(root, state) {
1137
1326
  // reason it is unrelated, or delete the entry and fix the check. The placeholder cannot pass.
1138
1327
  const failureHints = baseline => (baseline?.status === 'complete' ? baseline.results : []).filter(result => !result.passed)
1139
1328
  .map(result => ({ check: result.id, reason: `<why ${result.id}, which already failed on the run-start code, is unrelated to this change; or delete this entry and fix it>` }));
1140
- const finishTemplateContent = (root, state, acceptFailures) => JSON.stringify({ runId: state.id, summary: '<result and limits>', criterionEvidence: Object.fromEntries(state.criteria.map(item => [item.id, '<evidence>'])), assessment: finishAssessmentTemplate(root, state), acceptFailures }, null, 2) + '\n';
1329
+ const finishTemplateContent = (root, state, acceptFailures) => {
1330
+ const assessment = finishAssessmentTemplate(root, state);
1331
+ if (state.evidenceVersion === 1) {
1332
+ const scenarioEvidence = assessment.criterionChecks.map(row => ({ ...row, consumers: [] }));
1333
+ delete assessment.criterionChecks; delete assessment.consumerChecks;
1334
+ return JSON.stringify({ runId: state.id, summary: '<result and limits>', scenarioEvidence, assessment, acceptFailures }, null, 2) + '\n';
1335
+ }
1336
+ return JSON.stringify({ runId: state.id, summary: '<result and limits>', criterionEvidence: Object.fromEntries(state.criteria.map(item => [item.id, '<evidence>'])), assessment, acceptFailures }, null, 2) + '\n';
1337
+ };
1141
1338
  const finishTemplatePath = state => `.cyc/runs/${state.id}/finish-template.json`;
1142
1339
 
1143
1340
  // The finish input, written once next to the run so the agent copies a file instead of asking
@@ -1150,6 +1347,11 @@ function writeFinishTemplate(root, state) {
1150
1347
  return path;
1151
1348
  } catch { return null; }
1152
1349
  }
1350
+ function writeHandoffTemplate(root, state) {
1351
+ const stage = current(state), path = `.cyc/runs/${state.id}/handoff-${stage}-${state.attempt}.json`;
1352
+ if (!existsSync(projectFile(root, path))) atomicJSON(projectFile(root, path), { runId: state.id, stage, attempt: state.attempt, status: 'passed | failed | blocked', summary: '<actual stage outcome>', evidence: [{ kind: 'observation', detail: '<what was observed>' }], artifacts: [], assessment: stageTemplate(root, state), criteria: state.criteria.map(c => ({ id: c.id, result: 'unverified', evidence: '<actual result or remaining limit>' })) });
1353
+ return path;
1354
+ }
1153
1355
 
1154
1356
  // A background measurement that finds failing checks adds them to the template, but only while
1155
1357
  // the file is still exactly what CYC wrote; a template the agent has started editing is left alone.
@@ -1174,19 +1376,28 @@ function fillDerived(root, state, stage, assessment) {
1174
1376
  if (!assessment || typeof assessment !== 'object') return assessment;
1175
1377
  const derived = derivedAssessment(state, stage, { contextHistory: hasContextHistory(root, state) });
1176
1378
  for (const [key, value] of Object.entries(derived)) if (!(key in assessment)) assessment[key] = structuredClone(value);
1379
+ if (stage === 'scout' && assessment.context && state.contextRetention) {
1380
+ const declared = assessment.context.retention;
1381
+ if (declared && digest(JSON.stringify(declared.features)) !== digest(JSON.stringify(state.contextRetention.features.map(({ baselineViewHash, ...f }) => f))) && digest(JSON.stringify(declared.features)) !== digest(JSON.stringify(state.contextRetention.features))) throw new Error('Feature context paths differ from the frozen start plan; retain pending scope or start an authorized scoped follow-up.');
1382
+ assessment.context.retention = structuredClone(state.contextRetention);
1383
+ }
1177
1384
  return assessment;
1178
1385
  }
1179
1386
 
1180
1387
  export function nextRun(root, id) {
1181
1388
  const state = readRun(root, id);
1182
1389
  const finishTemplate = finishing(state) && state.status === 'running' ? writeFinishTemplate(root, state) : null;
1390
+ const handoffTemplate = !finishing(state) && current(state) && state.status === 'running' ? writeHandoffTemplate(root, state) : null;
1183
1391
  return {
1184
1392
  runId: state.id, engineVersion: state.engineVersion ?? 'unknown (legacy run)', status: state.status, goal: state.goal, playbook: state.playbook,
1393
+ ...(state.execution ? { execution: state.execution } : {}),
1394
+ ...(retentionOf(state) ? { contextRetention: retentionOf(state), contextPreparation: state.contextPreparation ? { docs: state.contextPreparation.docs, status: state.contextPreparation.status } : null } : {}),
1395
+ nextAction: finishTemplate || handoffTemplate ? { action: finishing(state) ? 'finish' : 'record', runId: state.id, inputTemplate: finishTemplate ?? handoffTemplate, command: finishing(state) ? `run finish --run ${state.id} --file ${finishTemplate}` : `run record --run ${state.id} --file ${handoffTemplate}` } : null,
1185
1396
  stage: current(state), attempt: state.attempt, criteria: state.criteria,
1186
1397
  workContractVersion: state.workContractVersion ?? null, assessmentRequired: Object.keys(stageTemplate(root, state) ?? {}),
1187
1398
  ...(state.evidenceVersion === 1 ? { evidenceVersion: 1, reviewPolicy: state.reviewPolicy, requirements: state.requirements } : {}),
1188
1399
  assessmentTemplate: stageTemplate(root, state),
1189
- ...(finishTemplate ? { finishTemplate, finishWith: `Copy ${finishTemplate} to FINISH.json, replace every <...> with what you found, list under acceptFailures only a check that already failed before this run and is unrelated, then: run finish --file FINISH.json` } : {}),
1400
+ ...(finishTemplate ? { finishTemplate, finishWith: `Copy ${finishTemplate} to FINISH.json, replace every <...> with what you found, list under acceptFailures only a check that already failed before this run and is unrelated, then: run finish --file FINISH.json --run ${state.id}` } : {}),
1190
1401
  ...(finishing(state) && !finishTemplate ? { finishWith: `run finish --run ${state.id} --summary "<result and limits>" --assessment <file with the template filled in> --criterion-evidence '${JSON.stringify(Object.fromEntries(state.criteria.map(item => [item.id, '<evidence>'])))}' (records Build if needed, proves new tests, verifies, and lists changed files itself)` } : {}),
1191
1402
  ...(state.verificationSource ? { verificationSource: state.verificationSource } : {}),
1192
1403
  ...(state.commands?.length ? { verificationCommands: state.commands.map(item => `${item.id}: ${[item.command, ...item.args].join(' ')}`) } : {}),
@@ -1256,8 +1467,8 @@ function assertArtifacts(root, artifacts) {
1256
1467
  if (!Array.isArray(artifacts)) throw new Error('artifacts must be an array (empty for no file deliverables).');
1257
1468
  for (const artifact of artifacts) {
1258
1469
  if (!artifact || !/^[a-f0-9]{64}$/.test(artifact.sha256 ?? '')) throw new Error('Each artifact needs its current SHA-256.');
1259
- const path = projectFile(root, artifact.path);
1260
- if (digest(readFileSync(path)) !== artifact.sha256) throw new Error(`Artifact changed after review: ${artifact.path}`);
1470
+ projectFile(root, artifact.path);
1471
+ if (artifactFiles(root, [artifact.path])[0].sha256 !== artifact.sha256) throw new Error(`Artifact changed after review: ${artifact.path}`);
1261
1472
  }
1262
1473
  }
1263
1474
  function validatePacket(root, state, packet) {
@@ -1286,11 +1497,62 @@ function validatePacket(root, state, packet) {
1286
1497
  packet.artifacts = [...packet.artifacts, ...assessmentArtifacts.filter(item => !packet.artifacts.some(existing => existing.path === item.path))];
1287
1498
  }
1288
1499
  function requireVerification(root, state) {
1500
+ requireRetention(root, state);
1289
1501
  if (!state.requiresChecks) return;
1290
1502
  if (!state.verification?.passed) throw new Error('Run project verification successfully before passing this stage.');
1503
+ if (state.verification.role !== undefined && state.verification.role !== 'candidate') throw new Error('Only a candidate verification receipt can pass this stage; original/proof roles cannot substitute.');
1291
1504
  const snapshot = cachedSnapshot(root);
1292
1505
  if (snapshot.skipped.length) throw new Error('Executable verification cannot cover symlink dependencies; use a project without linked source.');
1293
1506
  if (snapshot.hash !== state.verification.sourceHash) throw new Error('Source changed after verification; run verification again.');
1507
+ if (state.verification.inputs && measurementInputs(root, state.commands).key !== state.verification.inputs.key) throw new Error('Verification inputs changed after the check; run verification again.');
1508
+ }
1509
+
1510
+ function requireRetention(root, state) {
1511
+ const checked = checkRetention(root, state, cachedSnapshot(root).files);
1512
+ if (!checked.ok) {
1513
+ const error = new Error(`Feature context is incomplete: ${checked.issues.map(i => `${i.doc ?? ''} ${i.rule}: ${i.message}`).join('; ')}`);
1514
+ error.retention = checked;
1515
+ throw error;
1516
+ }
1517
+ return checked;
1518
+ }
1519
+
1520
+ export function contextUpdate(root, id, paths, work) {
1521
+ return transact(root, id, state => {
1522
+ requireActive(state);
1523
+ if (!budget(state) || !guard(root, state)) return state;
1524
+ if (state.verification?.passed) throw new Error('Context writes after verification require run retry to Build and fresh verification; a reply packet cannot refresh source evidence.');
1525
+ for (const path of paths) {
1526
+ projectFile(root, path);
1527
+ if (protectedPathMatcher(root, state.protectedPaths)(path) || state.allowedPaths.length && !state.allowedPaths.some(prefix => isWithin(path, prefix))) throw new Error(`Context path outside frozen authorized scope: ${path}. Retain pending context; do not broaden this run.`);
1528
+ }
1529
+ const result = work(state);
1530
+ if (!guard(root, state)) return state;
1531
+ log(state, 'context-update', { paths });
1532
+ return result;
1533
+ });
1534
+ }
1535
+
1536
+ export function prepareRunContext(root, id, input = {}) {
1537
+ const before = readRun(root, id), raw = retentionOf(before);
1538
+ assertRunOwner(root, before);
1539
+ if (!raw) return { runId: id, ...checkRetention(root, before, cachedSnapshot(root).files) };
1540
+ const plan = before.contextRetention ?? planRetention(root, { goal: before.goal, build: !!before.workContractVersion, allowedPaths: before.allowedPaths, explicit: raw });
1541
+ const paths = plan.disposition === 'required' ? [plan.index, ...plan.features.map(f => f.doc)] : [];
1542
+ return contextUpdate(root, id, paths, state => {
1543
+ if (!state.contextRetention) {
1544
+ for (const f of plan.features) {
1545
+ const original = originalContent(root, state, f.doc);
1546
+ if (original) f.baselineViewHash = digest(parseDoc(original.toString('utf8'), f.doc.split('/').at(-1)).currentView);
1547
+ }
1548
+ state.contextRetention = plan;
1549
+ }
1550
+ const prepared = prepareRetention(root, state, input, cachedSnapshot(root).files, () => {});
1551
+ state.contextPreparation = { ...prepared };
1552
+ const checked = checkRetention(root, state, cachedSnapshot(root).files);
1553
+ Object.assign(state.contextPreparation, { docs: checked.docs, status: checked.status });
1554
+ return { runId: id, status: checked.ok ? 'context-ready' : 'needs-context', ...checked, changed: prepared.paths };
1555
+ });
1294
1556
  }
1295
1557
 
1296
1558
  // Shorthand for the common case: the agent states the outcome in one line and names changed
@@ -1308,7 +1570,7 @@ export function quickHandoff(root, id, { status = 'passed', summary, artifacts =
1308
1570
  runId: id, stage, attempt: state.attempt, status, summary,
1309
1571
  ...(assessment !== undefined ? { assessment: assessmentPaths(root, assessment) } : {}),
1310
1572
  evidence: [{ kind: 'observation', detail: summary }],
1311
- artifacts: artifacts.map(path => inputPath(root, path)).map(path => ({ path, sha256: digest(readFileSync(projectFile(root, path))) })),
1573
+ artifacts: artifactFiles(root, artifacts.map(path => inputPath(root, path))),
1312
1574
  criteria: state.criteria.map(item => criterionEvidence || text(passedEvidence)
1313
1575
  ? { id: item.id, result: 'passed', evidence: criterionEvidence?.[item.id] ?? passedEvidence }
1314
1576
  : { id: item.id, result: 'unverified', evidence: `Not verified yet; checked at verify.` }),
@@ -1316,7 +1578,7 @@ export function quickHandoff(root, id, { status = 'passed', summary, artifacts =
1316
1578
  };
1317
1579
  // Deliver records which component context docs this change touched, so the context review can
1318
1580
  // tell a run that updated its component's doc from one that should have.
1319
- if (stage === 'deliver') packet.contextDocs = [...new Set([...packet.artifacts.map(item => item.path), ...(assessment?.learning?.artifacts ?? [])].filter(path => path.startsWith('docs/context/') && path.endsWith('.md') && !path.slice('docs/context/'.length).includes('/')))].sort();
1581
+ if (stage === 'deliver') packet.contextDocs = [...new Set([...packet.artifacts.map(item => item.path), ...(assessment?.learning?.artifacts ?? [])].filter(path => isComponentDoc(path, contextLocation(root).folder)))].sort();
1320
1582
  return recordHandoff(root, packet);
1321
1583
  }
1322
1584
 
@@ -1336,6 +1598,7 @@ export function recordHandoff(root, packet) {
1336
1598
  for (const artifact of reviewed.artifacts) if (!packet.artifacts.some(a => a.path === artifact.path)) packet.artifacts.push(artifact);
1337
1599
  }
1338
1600
  }
1601
+ if (packet.stage === 'deliver') packet.contextDocs = retentionOf(state)?.disposition === 'required' ? requireRetention(root, state).docs : [...new Set([...(packet.artifacts ?? []).map(a => a.path), ...(packet.assessment?.learning?.artifacts ?? [])].filter(path => isComponentDoc(path, contextLocation(root).folder)))].sort();
1339
1602
  const entry = { ...packet, recordedAt: new Date().toISOString(), sourceHash: cachedSnapshot(root).hash };
1340
1603
  state.handoffs.push(entry);
1341
1604
  log(state, 'handoff', { stage: packet.stage, status: packet.status, summary: packet.summary });
@@ -1350,14 +1613,23 @@ export function verifyRun(root, id) {
1350
1613
  return transact(root, id, state => {
1351
1614
  requireActive(state);
1352
1615
  if (!budget(state) || !guard(root, state)) return state;
1616
+ const retained = checkRetention(root, state, cachedSnapshot(root).files);
1617
+ if (!retained.ok) { const inputTemplate = writeFinishTemplate(root, state); return { runId: id, passed: false, status: 'needs-context', finished: false, retention: retained, nextAction: { action: 'finish', inputTemplate, command: `run finish --run ${id} --file ${inputTemplate} --wait-ms 30000`, instruction: 'Prepare scoped canonical feature context before verification; do not replace a reply packet.' } }; }
1353
1618
  if (!state.stages.includes('verify')) throw new Error('This playbook has no executable verification stage.');
1354
1619
  if (!['verify', 'deliver'].includes(current(state)) && current(state) !== null) throw new Error('Record prerequisite skill handoffs before running verification.');
1355
1620
  if (!state.commands.length) throw new Error('No project verification commands configured. Add explicit commands before starting a new run; do not invent a passing check.');
1356
1621
  // A stale cached hash here can only make the check look unstable; the full snapshot after it decides.
1357
- const before = cachedSnapshot(root);
1622
+ const before = sourceSnapshot(root);
1623
+ const inputsBefore = measurementInputs(root, state.commands);
1624
+ if (state.verification?.passed && state.verification.reusable === true && state.verification.role === 'candidate' && before.hash === state.verification.sourceHash && inputsBefore.suitable && state.verification.inputs?.key === inputsBefore.key) {
1625
+ assertArtifacts(root, [{ path: state.verification.receiptPath, sha256: state.verification.receiptHash }]);
1626
+ log(state, 'verification-reused', { receipt: state.verification.receiptPath, sourceHash: before.hash });
1627
+ return { runId: id, status: state.status, ...state.verification, reused: true };
1628
+ }
1358
1629
  if (before.skipped.length) throw new Error('Executable verification cannot cover symlink dependencies; use a project without linked source.');
1359
1630
  const results = runCommands(root, state.commands, () => state.limits.maxDurationMs ? state.limits.maxDurationMs - (Date.now() - Date.parse(state.startedAt)) : Infinity);
1360
1631
  const after = sourceSnapshot(root);
1632
+ const inputsAfter = measurementInputs(root, state.commands);
1361
1633
  // A check that already failed on the run-start code, and was accepted with a reason, does not
1362
1634
  // block completion if it fails exactly as it did then: the same exit code and error, the same
1363
1635
  // output lines (timings and timestamps aside), neither output cut short, and no file this run
@@ -1410,7 +1682,7 @@ export function verifyRun(root, id) {
1410
1682
  const excused = failing.filter(item => !item.changed).map(item => item.id);
1411
1683
  // Something must still be verified: a passing check, or passing tests inside an excused suite.
1412
1684
  const verifiedSomething = results.some(result => result.passed || (excused.includes(result.id) && (testsOf(result)?.passingCount ?? 0) > 0));
1413
- const passed = results.length === state.commands.length && results.every(result => result.passed || excused.includes(result.id)) && verifiedSomething && before.hash === after.hash && after.skipped.length === 0;
1685
+ const passed = results.length === state.commands.length && results.every(result => result.passed || excused.includes(result.id)) && verifiedSomething && before.hash === after.hash && inputsBefore.key === inputsAfter.key && after.skipped.length === 0;
1414
1686
  const changedPaths = [...new Set([...Object.keys(before.files), ...Object.keys(after.files)])].filter(path => before.files[path] !== after.files[path]);
1415
1687
  // Failing checks that also failed in the run-start measurement and are not accepted yet: the
1416
1688
  // agent decides whether they are unrelated, and says why, instead of retrying unchanged.
@@ -1422,6 +1694,7 @@ export function verifyRun(root, id) {
1422
1694
  const awaitingAcceptance = !passed && !state.awaitedAcceptance && failedAtRunStart.length > 0 && results.every(excusable) && before.hash === after.hash
1423
1695
  && results.some(result => result.passed || (testsOf(result)?.passingCount ?? 0) > 0);
1424
1696
  const receipt = { passed, changedPaths, verificationStatus: passed ? (excused.length ? 'passed-with-accepted-failures' : 'passed') : failing.length ? 'unverified' : 'failed', ...(failedAtRunStart.length ? { failedAtRunStart } : {}), ...(awaitingAcceptance ? { awaitingAcceptance } : {}), sourceHash: after.hash, sourceStable: before.hash === after.hash, checkedAt: new Date().toISOString(), results, acceptedPreexistingFailures: excused, ...(changedFailures.length ? { acceptedFailuresThatChanged: changedFailures.map(item => ({ id: item.id, ...item.changed })) } : {}), skippedSymlinks: after.skipped };
1697
+ Object.assign(receipt, { role: 'candidate', inputs: inputsAfter, inputsStable: inputsBefore.bounded && inputsAfter.bounded ? inputsBefore.key === inputsAfter.key : null, reusable: passed && inputsBefore.suitable && inputsAfter.suitable });
1425
1698
  // Every command reads and writes the run state, so test summaries of long output stay in the receipt file.
1426
1699
  state.verification = { ...receipt, results: results.map(({ tests, ...result }) => result) };
1427
1700
  const receiptPath = `.cyc/runs/${id}/checks/${randomUUID()}.json`;
@@ -1450,6 +1723,7 @@ export function verifyRun(root, id) {
1450
1723
  // shadow a proof control that exists.
1451
1724
  function runStartMeasurement(root, state) {
1452
1725
  const measured = currentBaseline(root, state);
1726
+ if (measured?.status === 'complete' && measured.inputs && (!measured.inputs.bounded || measured.inputs.key !== measurementInputs(root, state.commands).key)) return { status: 'invalid', reason: 'Run-start toolchain/environment/dependency inputs changed or could not be bounded; pre-existing final failures cannot be accepted.' };
1453
1727
  return measured?.status === 'complete' ? measured : proofBaseline(root, state) ?? measured;
1454
1728
  }
1455
1729
  function runStartResults(root, state) {
@@ -1464,7 +1738,7 @@ function proofSkippedControl(root, state) {
1464
1738
  if (!path) return false;
1465
1739
  try {
1466
1740
  const receipt = json(projectFile(root, path));
1467
- return receipt.originalSourceHash === state.initialSource.hash && receipt.control === null && /^not needed/.test(receipt.controlSource ?? '');
1741
+ return !receipt.focused && receipt.originalSourceHash === state.initialSource.hash && receipt.control === null && /^not needed/.test(receipt.controlSource ?? '');
1468
1742
  } catch { return false; }
1469
1743
  }
1470
1744
  const passedAtRunStart = (root, state, check) => runStartResults(root, state)?.find(result => result.id === check)?.passed ?? (proofSkippedControl(root, state) ? true : null);
@@ -1474,7 +1748,9 @@ function proofBaseline(root, state) {
1474
1748
  if (!path) return null;
1475
1749
  try {
1476
1750
  const receipt = json(projectFile(root, path));
1477
- return receipt.originalSourceHash === state.initialSource.hash && Array.isArray(receipt.control) ? { status: 'complete', source: 'proof control', results: receipt.control } : null;
1751
+ if (receipt.broadControl && receipt.broadCommandsHash === digest(JSON.stringify(state.commands)) && receipt.broadInputs?.bounded && receipt.broadInputs.key === measurementInputs(root, state.commands).key && receipt.originalSourceHash === state.initialSource.hash) return { status: 'complete', role: 'original-only-broad', source: 'measured broad proof control', results: receipt.broadControl };
1752
+ const compatible = !receipt.focused && (!receipt.commandPlanHash || receipt.commandPlanHash === digest(JSON.stringify(state.commands))) && (!receipt.inputs || receipt.inputs.bounded && receipt.inputs.key === measurementInputs(root, state.commands).key);
1753
+ return compatible && receipt.originalSourceHash === state.initialSource.hash && Array.isArray(receipt.control) ? { status: 'complete', role: 'original-only', source: 'proof control', results: receipt.control } : null;
1478
1754
  } catch { return null; }
1479
1755
  }
1480
1756
 
@@ -1522,6 +1798,17 @@ export function retryRun(root, id, { stage, reason }) {
1522
1798
  }
1523
1799
 
1524
1800
  export function controlRun(root, id, action) {
1801
+ if (action === 'stop') {
1802
+ const state = readRun(root, id); assertRunOwner(root, state);
1803
+ if (terminal.has(state.status)) throw new Error(`Run is terminal: ${state.status}. Start a new run rather than resetting its budget.`);
1804
+ let pending;
1805
+ try { pending = json(progressPath(root, id)); } catch { /* synchronous run */ }
1806
+ if (pending && !pending.result && !pending.error && pending.workerPid !== process.pid && processAlive(pending.workerPid)) {
1807
+ if (!sameLockIdentity(pending)) throw new Error('Operation belongs to another controller context; retain its ownership and recovery handle.');
1808
+ atomicJSON(cancellationPath(root, id, pending.operationId), { operationId: pending.operationId, requestedAt: new Date().toISOString(), ...lockIdentity() });
1809
+ return { runId: id, status: 'stop-requested', operationId: pending.operationId, finished: false, nextAction: { action: 'wait', command: `run wait --run ${id} --operation ${pending.operationId} --wait-ms 30000` } };
1810
+ }
1811
+ }
1525
1812
  return transact(root, id, state => {
1526
1813
  if (terminal.has(state.status)) throw new Error(`Run is terminal: ${state.status}. Start a new run rather than resetting its budget.`);
1527
1814
  if (action === 'pause') { requireActive(state); state.status = 'paused'; }
@@ -1593,12 +1880,82 @@ function proofOutdated(root, state) {
1593
1880
  return changed.some(path => state.testProof.testFiles[path] !== files[path]) || Object.keys(state.testProof.testFiles).some(path => !changed.includes(path));
1594
1881
  }
1595
1882
 
1883
+ // One scenario observation can project to multiple exact criterion/consumer views. Its origin
1884
+ // remains agent-reported; passing a command never invents a named assertion observation.
1885
+ function scenarioViews(state, rows) {
1886
+ const criterionEvidence = Object.fromEntries(state.criteria.map(c => [c.id, rows.filter(row => row.id === c.id).map(row => `${row.clause ? `${row.clause}: ` : ''}${row.scenario}: ${row.evidence}`).join('\n')]));
1887
+ const consumers = state.handoffs.findLast(h => h.stage === 'scout' && h.status === 'passed')?.assessment?.consumers ?? [];
1888
+ const consumerChecks = consumers.map(c => {
1889
+ const matched = rows.filter(row => row.consumers?.includes(c.id));
1890
+ return { id: c.id, result: matched.length && matched.every(r => r.result === 'passed') ? 'passed' : 'unverified', evidence: matched.map(row => `${row.scenario}: ${row.evidence}`).join('\n') || 'No mapped scenario observation is available.' };
1891
+ });
1892
+ return { criterionEvidence, consumerChecks };
1893
+ }
1894
+ function importReviews(root, state, assessment) {
1895
+ const review = assessment.semanticReview;
1896
+ if (!review) return;
1897
+ if (review.receipts === undefined) review.receipts = (state.reviewReceipts ?? []).filter(r => {
1898
+ if (r.status !== 'recorded') return false;
1899
+ try { checkedReview(root, state, r.id, cachedSnapshot(root).hash); return true; } catch { return false; }
1900
+ }).map(r => r.id);
1901
+ if (review.receipts.length) review.findings ??= [];
1902
+ for (const id of review.receipts) {
1903
+ const receipt = state.reviewReceipts?.find(r => r.id === id);
1904
+ for (const finding of receipt?.findings ?? []) if (!review.findings.some(f => f.reviewId === id && f.id === finding.id)) review.findings.push({ ...finding, reviewId: id });
1905
+ }
1906
+ }
1907
+ const continuationBinding = (root, state) => digest(JSON.stringify({ run: state.id, source: sourceSnapshot(root).hash, inputs: measurementInputs(root, state.commands).key, proof: state.testProof?.receiptHash, tests: state.testProof?.testFiles }));
1908
+ function needsProofReview(root, state, input, steps) {
1909
+ const binding = continuationBinding(root, state);
1910
+ let continuation = state.finishContinuation;
1911
+ if (!continuation || continuation.binding !== binding) {
1912
+ continuation = { token: randomUUID(), binding, attempts: 0 };
1913
+ transact(root, state.id, saved => { saved.finishContinuation = continuation; });
1914
+ }
1915
+ const inputTemplate = `.cyc/runs/${state.id}/finish-proof-${continuation.token}.json`;
1916
+ const failures = state.testProof.failures.map(f => ({ id: f.id, check: f.check, name: f.name, file: f.file, hint: f.hint, error: f.error?.slice(0, 2000) ?? '', boundary: f.boundary ?? null }));
1917
+ atomicJSON(projectFile(root, inputTemplate), { runId: state.id, ...input, continuation: { token: continuation.token, binding }, assessment: { ...input.assessment, proofReview: { receipt: 'current-proof', cases: failures.map(f => ({ id: f.id, category: 'behavioral | new-interface | setup | unclassified', reason: '<why this observed failure establishes that category>', boundary: f.boundary ?? '' })) } } });
1918
+ return { runId: state.id, status: 'needs-proof-review', finished: false, steps, proof: { receiptPath: state.testProof.receiptPath, receiptHash: state.testProof.receiptHash, role: 'original-plus-new-tests', failures }, nextAction: { action: 'finish', inputTemplate, command: `run finish --run ${state.id} --file ${inputTemplate} --wait-ms 30000`, instruction: 'Fill the decisive proof categories/reasons in this file, retaining its bound continuation. Unknown boundaries stay unknown; module-load failures are not behavioral proof.' } };
1919
+ }
1920
+
1596
1921
  // From Build or Verify to complete in one call: record Build, prove the new tests, verify, record
1597
1922
  // Verify and Deliver, and complete. Each step is its own transaction, so a failure stops at a
1598
1923
  // defined point: a failed proof or check is reported as such, a failed check is recorded as a
1599
1924
  // normal failed attempt, and a later refusal leaves the run at the stage named in the error.
1600
- export function finishRun(root, id, { summary, artifacts, passedEvidence, criterionEvidence, assessment = {}, acceptFailures = [] }) {
1925
+ export function finishRun(root, id, { summary, artifacts, passedEvidence, criterionEvidence, assessment = {}, acceptFailures = [], scenarioEvidence, continuation }) {
1601
1926
  let state = readRun(root, id);
1927
+ assertRunOwner(root, state);
1928
+ if (current(state) === null && ['running', 'complete'].includes(state.status)) {
1929
+ const delivery = state.handoffs.at(-1);
1930
+ if (delivery?.stage !== 'deliver' || delivery.status !== 'passed') throw new Error('No confirmed delivery to resume.');
1931
+ assertArtifacts(root, delivery.artifacts);
1932
+ if (sourceSnapshot(root).hash !== delivery.sourceHash) throw new Error('Source changed after delivery; completed evidence cannot be republished.');
1933
+ requireVerification(root, state);
1934
+ if (state.execution?.mode.startsWith('native-') || !state.execution && /^[a-f0-9]{32}$/.test(state.session ?? '')) {
1935
+ const gate = json(projectFile(root, `.cyc/runtime/${state.session}.state.json`));
1936
+ if (!(Date.parse(delivery.recordedAt) >= Date.parse(gate.updatedAt))) throw new Error('Delivery is outside the current native request window.');
1937
+ }
1938
+ if (state.status === 'running') state = completeRun(root, id);
1939
+ return { runId: id, status: state.status, finished: true, steps: ['resume delivery'], packet: projectDelivery(root, state) };
1940
+ }
1941
+ if (artifacts !== undefined) artifactFiles(root, artifacts.map(path => inputPath(root, path)));
1942
+ if (continuation) {
1943
+ const saved = state.finishContinuation;
1944
+ if (!saved || continuation.token !== saved.token || continuation.binding !== saved.binding || saved.binding !== continuationBinding(root, state)) throw new Error('Finish continuation is stale or foreign; call finish with current evidence to obtain the remaining input.');
1945
+ if (saved.attempts >= state.limits.maxAttempts) throw new Error('Proof judgment continuation limit reached; retain the failed judgments and repair the source/evidence before another finish.');
1946
+ transact(root, id, current => { current.finishContinuation.attempts++; });
1947
+ }
1948
+ if (scenarioEvidence !== undefined) {
1949
+ if (!Array.isArray(scenarioEvidence)) throw new Error('scenarioEvidence needs named criterion/clause observations.');
1950
+ if (assessment.criterionChecks && digest(JSON.stringify(assessment.criterionChecks)) !== digest(JSON.stringify(scenarioEvidence))) throw new Error('Supply one canonical scenarioEvidence record, not conflicting criterionChecks.');
1951
+ assessment.criterionChecks = structuredClone(scenarioEvidence);
1952
+ }
1953
+ if (assessment.criterionChecks) {
1954
+ const views = scenarioViews(state, assessment.criterionChecks);
1955
+ criterionEvidence ??= views.criterionEvidence;
1956
+ assessment.consumerChecks ??= views.consumerChecks;
1957
+ }
1958
+ importReviews(root, state, assessment);
1602
1959
  if (!Array.isArray(acceptFailures) || acceptFailures.some(item => !item || !state.commands.some(command => command.id === item.check) || !text(item.reason))) throw new Error(`acceptFailures lists checks that already failed before this run: [{"check": "${state.commands.map(command => command.id).join('|')}", "reason": "why it is unrelated"}].`);
1603
1960
  let stage = current(state);
1604
1961
  if (!['build', 'verify', 'deliver'].includes(stage)) throw new Error(`Finish starts at build, verify, or deliver; this run is at ${stage ?? 'no remaining stage'}.`);
@@ -1621,7 +1978,10 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1621
1978
  if (!criterionEvidence && state.criteria.length > 1) throw new Error('Multiple criteria need criterionEvidence mapping each criterion ID to its evidence.');
1622
1979
  if (criterionEvidence && (Object.keys(criterionEvidence).length !== state.criteria.length || state.criteria.some(item => !text(criterionEvidence[item.id])))) throw new Error(`Criterion evidence must cover every criterion exactly once: ${state.criteria.map(item => item.id).join(', ')}.`);
1623
1980
  for (const name of ['verify', 'deliver'].filter(name => state.stages.indexOf(name) >= state.stageIndex)) {
1624
- validateAssessment(state, { stage: name, status: 'passed', assessment: part(name) }, path => generatesLedger && path === state.ledgerPath ? null : readFileSync(projectFile(root, path)));
1981
+ validateAssessment(state, { stage: name, status: 'passed', assessment: part(name) }, path => {
1982
+ const plannedContext = retentionOf(state)?.features?.some(f => f.doc === path);
1983
+ return generatesLedger && path === state.ledgerPath || plannedContext && !existsSync(projectFile(root, path)) ? null : artifactFiles(root, [path])[0];
1984
+ }, { proofPending: true });
1625
1985
  }
1626
1986
  const steps = [];
1627
1987
  const dropped = [];
@@ -1654,15 +2014,30 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1654
2014
  state = readRun(root, id);
1655
2015
  stage = current(state);
1656
2016
  }
2017
+ if (retentionOf(state)) {
2018
+ let retained = checkRetention(root, state, cachedSnapshot(root).files);
2019
+ if (!retained.ok) {
2020
+ retained = prepareRunContext(root, id, { records: assessment.learning?.context ?? [], summary, reason: assessment.learning?.reason ?? '' });
2021
+ state = readRun(root, id);
2022
+ if (!retained.ok) {
2023
+ const inputTemplate = `.cyc/runs/${id}/finish-context.json`;
2024
+ atomicJSON(projectFile(root, inputTemplate), { runId: id, summary, artifacts, passedEvidence, criterionEvidence, assessment, acceptFailures });
2025
+ return { runId: id, status: 'needs-context', finished: false, steps, retention: retained, nextAction: { action: 'finish', inputTemplate, command: `run finish --run ${id} --file ${inputTemplate} --wait-ms 30000`, instruction: 'Fill or repair the canonical target feature docs and index, or learning.context Current views; preserve restrictions and the frozen plan. Then resume finish. No proof/check has been promoted.' } };
2026
+ }
2027
+ steps.push('prepare context');
2028
+ }
2029
+ const contextArtifacts = [...retained.docs, ...(retentionOf(state).disposition === 'required' ? [retentionOf(state).index] : [])];
2030
+ if (artifacts) artifacts = [...new Set([...artifacts, ...contextArtifacts])];
2031
+ }
1657
2032
  // Listed artifacts win; otherwise the controller names what this run changed.
1658
2033
  artifacts ??= changedArtifacts(root, state);
1659
2034
  if (stage === 'verify') {
1660
2035
  if (provable(state)) {
1661
2036
  const exemption = part('verify')?.testProof;
1662
2037
  // Prove here rather than refuse: a missing or outdated proof is one more step, not a retry.
1663
- if (exemption === undefined && proofOutdated(root, state)) {
2038
+ if (exemption === undefined && (proofOutdated(root, state) || acceptFailures.length > 0 && runStartMeasurement(root, state)?.status !== 'complete')) {
1664
2039
  let proof;
1665
- try { proof = proveRun(root, id); }
2040
+ try { proof = proveRun(root, id, { measureOriginal: acceptFailures.length > 0 }); }
1666
2041
  catch (error) { throw new Error(`Finish stopped at prove-red: ${error.message}`); }
1667
2042
  const stop = !proof.passed && stoppedBy('prove-red', proof);
1668
2043
  if (stop) return stop;
@@ -1671,6 +2046,10 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1671
2046
  state = readRun(root, id);
1672
2047
  }
1673
2048
  requireTestProof(root, state, exemption);
2049
+ if (state.evidenceVersion === 1 && exemption === undefined) {
2050
+ if (!assessment.proofReview) return needsProofReview(root, state, { summary, artifacts, passedEvidence, criterionEvidence, assessment, acceptFailures }, steps);
2051
+ validateProofReview(state, assessment.proofReview);
2052
+ }
1674
2053
  }
1675
2054
  // The proof's control run has now measured the run-start code, so listed pre-existing failures
1676
2055
  // can be checked against it. A check that passed there has nothing to accept: the entry is
@@ -1707,15 +2086,7 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1707
2086
  const completed = completeRun(root, id);
1708
2087
  steps.push('complete');
1709
2088
  // The run's own record is the review: each criterion's evidence and the files it changed.
1710
- let packet = null;
1711
- if (completed.status === 'complete') {
1712
- try {
1713
- const recorded = earlier => { try { return readRun(root, earlier.runId).reviewPacket?.digest === runPacketDigest(earlier); } catch { return false; } };
1714
- packet = writeRunPacket(root, { session: completed.session, runId: id, checks: completed.criteria.map(item => ({ criterion: item.description, result: 'passed', evidence: (criterionEvidence?.[item.id] ?? passedEvidence).trim() })), artifacts, recorded });
1715
- // The gate accepts the packet only with this record in the run that wrote it.
1716
- if (packet.written) transact(root, id, state => { state.reviewPacket = { digest: packet.digest, writtenAt: new Date().toISOString() }; log(state, 'review-packet', { digest: packet.digest }); return state; });
1717
- } catch (error) { packet = { written: false, reason: `Could not write the review packet (${error.message}); write it with cyc packet.` }; }
1718
- }
2089
+ const packet = completed.status === 'complete' ? projectDelivery(root, completed) : null;
1719
2090
  // What the reply may state: the proof's scope and any pre-existing failure it must disclose.
1720
2091
  return { runId: id, status: completed.status, finished: completed.status === 'complete', steps, reviewPath: reviewPath(completed),
1721
2092
  ...(packet ? { packet } : {}),
@@ -1724,6 +2095,16 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1724
2095
  ...(dropped.length ? { droppedAcceptFailures: dropped } : {}) };
1725
2096
  }
1726
2097
 
2098
+ function projectDelivery(root, state) {
2099
+ try {
2100
+ const delivery = state.handoffs.at(-1);
2101
+ const recorded = earlier => { try { return readRun(root, earlier.runId).reviewPacket?.digest === runPacketDigest(earlier); } catch { return false; } };
2102
+ const packet = writeRunPacket(root, { session: state.session, execution: state.execution, evidence: state.evidence, runId: state.id, checks: delivery.criteria.map(item => ({ criterion: state.criteria.find(c => c.id === item.id).description, result: item.result, evidence: item.evidence.trim() })), artifacts: delivery.artifacts.map(a => a.path), recorded });
2103
+ if (packet.written) transact(root, state.id, saved => { saved.reviewPacket = { digest: packet.digest, writtenAt: new Date().toISOString() }; log(saved, 'review-packet', { digest: packet.digest }); });
2104
+ return packet;
2105
+ } catch (error) { return { written: false, reason: `Delivery evidence publication failed (${error.message}); resume finish after repairing the path/context.` }; }
2106
+ }
2107
+
1727
2108
  function writeReview(root, state) {
1728
2109
  const path = projectFile(root, reviewPath(state));
1729
2110
  const temporary = `${path}.${randomUUID()}.tmp`;
@@ -1739,7 +2120,8 @@ function writeReview(root, state) {
1739
2120
  try { if (!receipt) throw new Error('Missing registered review receipt.'); assertArtifacts(root, [{ path: receipt.path, sha256: receipt.sha256 }]); }
1740
2121
  catch (error) { artifactIssues.push(`Review ${id}: ${error.message}`); }
1741
2122
  }
1742
- writeFileSync(temporary, renderReview(state, cachedSnapshot(root).hash, artifactIssues), { mode: 0o600 });
2123
+ const source = cachedSnapshot(root), contextKey = state.reviewReceipts?.some(r => r.contextMode === 'bounded') ? measurementInputs(root, []).key : undefined;
2124
+ writeFileSync(temporary, renderReview(state, source.hash, artifactIssues, source.files, contextKey), { mode: 0o600 });
1743
2125
  renameSync(temporary, path);
1744
2126
  return reviewPath(state);
1745
2127
  }
@@ -1748,7 +2130,31 @@ export function reviewRun(root, id) {
1748
2130
  return transact(root, id, state => ({ runId: id, status: state.status, reviewPath: reviewPath(state) }));
1749
2131
  }
1750
2132
 
1751
- export function captureReview(root, id, { reviewer, scope = [] } = {}) {
2133
+ function reviewContext(root, scope, files, explicit, evidence) {
2134
+ if (explicit === undefined || !scope.length) return { contextMode: 'whole-source', contextPaths: [], contextEvidence: 'Dependency impact not bounded; whole-source freshness required.' };
2135
+ if (!text(evidence) || /^<.*>$/.test(evidence.trim())) throw new Error('contextEvidence needs the actual bounded dependency/contract review, or omit contextPaths for conservative whole-source freshness.');
2136
+ const paths = normalizePaths(root, explicit, 'review context');
2137
+ const covered = path => scope.some(prefix => isWithin(path, prefix));
2138
+ const pending = Object.keys(files).filter(covered), visited = new Set(); let unknown = false;
2139
+ while (pending.length) {
2140
+ const path = pending.pop(); if (visited.has(path)) continue; visited.add(path);
2141
+ if (!/\.[cm]?[jt]sx?$/.test(path)) continue;
2142
+ const body = readFileSync(projectFile(root, path), 'utf8');
2143
+ if (/\b(?:import|require)\s*\(\s*[^'"\s]/.test(body)) unknown = true;
2144
+ const imports = [...body.matchAll(/\b(?:import|export)\s+(?:[^'";]*?\s+from\s+)?['"]([^'"]+)['"]|\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)|\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)/g)].map(m => m[1] ?? m[2] ?? m[3]);
2145
+ for (const specifier of imports) {
2146
+ if (specifier.startsWith('node:')) continue;
2147
+ if (specifier.startsWith('.')) {
2148
+ const base = slash(relative(root, resolve(root, dirname(path), specifier)));
2149
+ const target = [base, ...['.mjs', '.js', '.ts', '.tsx', '/index.mjs', '/index.js', '/index.ts', '/index.tsx'].map(ext => base + ext)].find(p => files[p]);
2150
+ if (!target) unknown = true; else { paths.push(target); pending.push(target); }
2151
+ } else if (specifier.startsWith('@/') || specifier.startsWith('#') || !files['package-lock.json']) unknown = true;
2152
+ }
2153
+ }
2154
+ const contextInputs = measurementInputs(root, []);
2155
+ return { contextMode: unknown || !contextInputs.bounded ? 'whole-source' : 'bounded', contextPaths: [...new Set([...paths, 'package.json', 'package-lock.json', 'tsconfig.json', 'jsconfig.json'])], contextEvidence: unknown ? `${evidence} Unresolved dependency impact requires whole-source freshness.` : evidence, contextInputs };
2156
+ }
2157
+ export function captureReview(root, id, { reviewer, scope = [], contextPaths, contextEvidence } = {}) {
1752
2158
  return transact(root, id, state => {
1753
2159
  requireActive(state);
1754
2160
  if (!['self', 'fresh-context', 'peer'].includes(reviewer)) throw new Error('Review reviewer must be self, fresh-context or peer.');
@@ -1758,11 +2164,18 @@ export function captureReview(root, id, { reviewer, scope = [] } = {}) {
1758
2164
  if (source.skipped.length) throw new Error('Review capture cannot cover symlink source dependencies.');
1759
2165
  for (const path of paths) if (![...Object.keys(source.files), ...Object.keys(state.initialSource.files)].some(file => file === path || file.startsWith(`${path}/`))) throw new Error(`Review scope has no covered source: ${path}.`);
1760
2166
  const reviewId = randomUUID(), path = `.cyc/runs/${id}/reviews/${reviewId}.json`;
1761
- const receipt = { version: 1, runId: id, id: reviewId, status: 'captured', reviewer, identity: null, provenance: 'agent-reported', scope: paths, sourceHash: source.hash, files: source.files, criteriaHash: state.criteriaHash ?? digest(JSON.stringify(state.criteria)), capturedAt: new Date().toISOString(), path };
2167
+ const context = reviewContext(root, paths, source.files, contextPaths, contextEvidence);
2168
+ const previous = (state.reviewReceipts ?? []).at(-1);
2169
+ const changedPaths = previous ? [...new Set([...Object.keys(previous.files), ...Object.keys(source.files)])].filter(p => previous.files[p] !== source.files[p]) : Object.keys(source.files).filter(p => state.initialSource.files[p] !== source.files[p]);
2170
+ const followupPath = `.cyc/runs/${id}/reviews/${reviewId}-followup.json`;
2171
+ atomicJSON(projectFile(root, followupPath), { runId: id, changedPaths, contractsChanged: changedPaths.filter(p => (state.reviewReceipts ?? []).some(r => r.contextPaths?.some(prefix => isWithin(p, prefix)))), dependencyImpact: context.contextMode, findings: (state.reviewReceipts ?? []).flatMap(r => (r.findings ?? []).map(f => ({ reviewId: r.id, ...f }))), brief: 'Demonstrate authoritative writer/status/protected read-write transitions and conflicting representations, then async actor/resource send/read identity; retain history continuity and keyboard/return-focus review before cosmetic findings.' });
2172
+ const receipt = { version: 1, runId: id, id: reviewId, status: 'captured', reviewer, identity: null, provenance: 'agent-reported', scope: paths, ...context, sourceHash: source.hash, files: source.files, criteriaHash: digest(JSON.stringify(state.criteria)), capturedAt: new Date().toISOString(), path };
1762
2173
  atomicJSON(projectFile(root, path), receipt);
2174
+ const recordTemplate = `.cyc/runs/${id}/reviews/${reviewId}-record.json`;
2175
+ atomicJSON(projectFile(root, recordTemplate), { reviewId, identity: null, evidence: '<actual observations from the captured review>', findings: [] });
1763
2176
  (state.reviewReceipts ??= []).push({ ...receipt, sha256: digest(readFileSync(projectFile(root, path))) });
1764
2177
  log(state, 'review-captured', { reviewId, sourceHash: source.hash });
1765
- return receipt;
2178
+ return { ...receipt, recordTemplate, followupPath, nextAction: { action: 'review-record', runId: id, command: `run review-record --run ${id} --file ${recordTemplate}` } };
1766
2179
  });
1767
2180
  }
1768
2181
 
@@ -1770,11 +2183,14 @@ function checkedReview(root, state, id, sourceHash) {
1770
2183
  const record = state.reviewReceipts?.find(r => r.id === id);
1771
2184
  if (!record) throw new Error(`Unknown review ${id}.`);
1772
2185
  assertArtifacts(root, [{ path: record.path, sha256: record.sha256 }]);
1773
- if (record.sourceHash !== sourceHash || record.criteriaHash !== (state.criteriaHash ?? digest(JSON.stringify(state.criteria)))) throw new Error(`Review ${id} is stale: source or criteria changed since capture.`);
2186
+ const source = cachedSnapshot(root);
2187
+ if (!reviewCurrent(record, state, sourceHash, source.files, record.contextMode === 'bounded' ? measurementInputs(root, []).key : undefined)) throw new Error(`Review ${id} is stale: reviewed source, criteria or dependency/contract context changed since capture.`);
1774
2188
  return record;
1775
2189
  }
1776
2190
 
1777
2191
  export function recordReview(root, id, { reviewId, evidence, identity = null, findings = [] } = {}) {
2192
+ const invalid = !text(evidence) || /^<.*>$/.test(evidence.trim()) ? 'evidence' : identity !== null && (!text(identity) || /^<.*>$/.test(identity.trim())) ? 'identity' : null;
2193
+ if (invalid) { const error = new Error(`Review ${invalid} needs ${invalid === 'identity' ? 'observed text or null' : 'actual non-placeholder evidence'}.`); error.field = invalid; error.repairTemplate = `.cyc/runs/${id}/reviews/${reviewId}-record.json`; throw error; }
1778
2194
  return transact(root, id, state => {
1779
2195
  requireActive(state);
1780
2196
  if (!budget(state) || !guard(root, state)) return state;
@@ -1802,6 +2218,7 @@ function bindEvidence(root, state, packet) {
1802
2218
  if (!verification.results.some(r => r.id === row.check && (r.passed || verification.acceptedPreexistingFailures?.includes(r.id)))) throw new Error(`Scenario ${row.id} check did not pass or retain an accepted baseline failure.`);
1803
2219
  row.receipt = verification.receiptPath;
1804
2220
  }
2221
+ state.evidence = { version: 1, sourceHash, verification: { path: verification.receiptPath, sha256: verification.receiptHash }, scenarios: structuredClone(a.criterionChecks), criteria: structuredClone(state.criteria), reviews: [...(a.semanticReview.receipts ?? [])], origin: 'agent-reported-observations-with-command-receipts', hookActivation: 'unverified', productReadiness: 'not-certified' };
1805
2222
  packet.artifacts.push({ path: verification.receiptPath, sha256: verification.receiptHash });
1806
2223
  const refs = a.semanticReview.receipts ?? [];
1807
2224
  for (const ref of refs) {
@@ -1817,7 +2234,7 @@ function bindEvidence(root, state, packet) {
1817
2234
  const covered = path => refs.some(id => { const r = state.reviewReceipts.find(x => x.id === id); return !r.scope.length || r.scope.some(p => path === p || path.startsWith(`${p}/`)); });
1818
2235
  if (changed.some(path => !covered(path))) throw new Error('Review receipts do not cover all changed source; record the missing self/fresh review scope.');
1819
2236
  if (state.reviewPolicy === 'fresh-required' && (!refs.some(id => state.reviewReceipts.find(r => r.id === id)?.reviewer === 'fresh-context') || changed.some(path => !refs.some(id => { const r = state.reviewReceipts.find(x => x.id === id); return r.reviewer === 'fresh-context' && (!r.scope.length || r.scope.some(p => path === p || path.startsWith(`${p}/`))); })))) throw new Error('fresh-required policy needs current fresh-context receipts covering every changed source path.');
1820
- if (reviewCoverage(state, a.semanticReview, sourceHash).status === 'stale') throw new Error('Review coverage is stale.');
2237
+ if (reviewCoverage(state, a.semanticReview, { ...snapshot, contextKey: state.reviewReceipts.some(r => r.contextMode === 'bounded') ? measurementInputs(root, []).key : undefined }).status === 'stale') throw new Error('Review coverage is stale.');
1821
2238
  }
1822
2239
  if (state.testProof && a.testProof?.status !== 'exempt') {
1823
2240
  assertArtifacts(root, [{ path: state.testProof.receiptPath, sha256: state.testProof.receiptHash }]);