cyc-stack 0.7.1 → 0.9.0

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.
Files changed (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.codex-plugin/plugin.json +1 -1
  3. package/.cursor-plugin/plugin.json +1 -1
  4. package/README.md +25 -254
  5. package/bin/cyc.mjs +61 -23
  6. package/docs/assets/cyc-method-library.svg +1 -39
  7. package/docs/assets/cyc-overview.svg +1 -44
  8. package/docs/assets/cyc-workflow-diagram.svg +1 -415
  9. package/docs/context.md +13 -23
  10. package/docs/cyc-workflow.md +31 -84
  11. package/docs/installation.md +66 -124
  12. package/docs/onboarding-recovery.md +31 -37
  13. package/docs/project-tools.md +16 -10
  14. package/docs/response-standard.md +16 -32
  15. package/docs/runtime.md +22 -224
  16. package/docs/skill-contract.md +13 -56
  17. package/docs/task-context.md +56 -0
  18. package/docs/validation.md +2 -0
  19. package/docs/work-assessments.md +25 -92
  20. package/methods/cyc-build/SKILL.md +8 -53
  21. package/methods/cyc-challenge/SKILL.md +4 -0
  22. package/methods/cyc-context/SKILL.md +20 -53
  23. package/methods/cyc-context/references/evidence.md +1 -1
  24. package/methods/cyc-context/references/templates.md +4 -11
  25. package/methods/cyc-deliver/SKILL.md +6 -42
  26. package/methods/cyc-remember/SKILL.md +1 -1
  27. package/methods/cyc-scout/SKILL.md +17 -51
  28. package/methods/cyc-setup/SKILL.md +7 -19
  29. package/methods/cyc-verify/SKILL.md +15 -66
  30. package/methods/cyc-verify/references/recipe.md +2 -0
  31. package/package.json +9 -1
  32. package/plugin.json +1 -1
  33. package/rules/cyc-delivery.mdc +33 -33
  34. package/scripts/browser-audit.mjs +53 -0
  35. package/scripts/catalog.mjs +9 -2
  36. package/scripts/codex-host.mjs +178 -0
  37. package/scripts/context-review.mjs +212 -29
  38. package/scripts/delegation.mjs +156 -0
  39. package/scripts/execution.mjs +51 -0
  40. package/scripts/onboarding.mjs +14 -1
  41. package/scripts/packet.mjs +21 -6
  42. package/scripts/project-tools.mjs +43 -20
  43. package/scripts/recovery.mjs +20 -1
  44. package/scripts/response-mode.mjs +8 -0
  45. package/scripts/run-worker.mjs +4 -0
  46. package/scripts/runtime.mjs +648 -68
  47. package/scripts/swarm.mjs +154 -0
  48. package/scripts/task-context.mjs +164 -0
  49. package/scripts/work-review.mjs +32 -10
  50. package/skills/cyc/SKILL.md +29 -70
@@ -7,10 +7,15 @@ 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 { strictObject, contextPolicy, initializeContext, contextView, contextHash, contextPath, checkContextSize, checkProjection, publishContext, acknowledgeContext, requireContextReady, reconcileContext, touchContext } from './task-context.mjs';
16
+ import { delegationPolicy, initializeDelegation, decideDelegation, assignWorker, recordWorker, cancelWorker, reconcileWorkers } from './delegation.mjs';
17
+ import {startSwarm,swarmPhase,applySwarmPlan,assignSwarm,commitSwarm,cancelSwarm} from './swarm.mjs';
18
+ import { planRetention, retentionOf, prepareRetention, checkRetention, contextLocation, isComponentDoc, parseDoc } from './context-review.mjs';
14
19
  export { sourceSnapshot } from './source-snapshot.mjs';
15
20
 
16
21
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -30,6 +35,7 @@ const slash = path => path.split(sep).join('/');
30
35
  let cacheStage = null;
31
36
  // The operation lock this process holds, so a running check can record how long it may last.
32
37
  let activeOwnership = null;
38
+ let activeProgress = null;
33
39
  const inspectSource = (root, options) => inspectSourceFiles(root, { ...options, writeCache: cacheStage ?? false });
34
40
  const sourceSnapshot = (root, options) => inspectSource(root, options).snapshot;
35
41
  // Views between checks reuse cached hashes. Snapshots that record evidence, at run start, around
@@ -41,7 +47,14 @@ export function atomicJSON(path, value) {
41
47
  mkdirSync(dirname(path), { recursive: true });
42
48
  const temp = `${path}.${randomUUID()}.tmp`;
43
49
  writeFileSync(temp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
44
- renameSync(temp, path);
50
+ // Windows readers can briefly hold a replacement target; retry only this rename.
51
+ for(let attempt=0;;attempt++) {
52
+ try {renameSync(temp,path);break;}
53
+ catch(error) {
54
+ if(process.platform!=='win32'||!['EPERM','EBUSY'].includes(error.code)||attempt>=2)throw error;
55
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,20*(attempt+1));
56
+ }
57
+ }
45
58
  }
46
59
 
47
60
  // Resolve an existing ancestor and keep any missing suffix, so prospective files
@@ -156,6 +169,7 @@ export function configuration(root) {
156
169
  if (!limitKeys.includes(key) || !Number.isSafeInteger(value) || value <= 0) throw new Error(`Invalid run limit: ${key}`);
157
170
  }
158
171
  const commands = config.verification?.commands ?? [];
172
+ validateCommands(commands, 'verification.commands');
159
173
  if (!Array.isArray(commands)) throw new Error('verification.commands must be an array.');
160
174
  const ids = new Set();
161
175
  for (const command of commands) {
@@ -167,6 +181,35 @@ export function configuration(root) {
167
181
  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
182
  return { limits, commands, ledgerPath, baseline: config.verification?.baseline === true, protectedPaths: normalizePaths(root, ['.cyc/config.json', ...(config.protectedPaths ?? [])], 'protectedPaths') };
169
183
  }
184
+ function validateCommands(commands, label) {
185
+ 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.`);
186
+ 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.`);
187
+ }
188
+ // This is a compatibility key, not a second cache. Environment values are hashed, never logged.
189
+ // Unknown executables, links or an excessive dependency tree disable reuse conservatively.
190
+ function measurementInputs(root, commands) {
191
+ const files = {}; let count = 0, bytes = 0, limitation = null;
192
+ const visit = (path, key) => {
193
+ const info = lstatSync(path);
194
+ if (info.isSymbolicLink()) throw new Error(`Linked dependency: ${key}`);
195
+ if (info.isDirectory()) { files[key] = 'directory'; for (const name of readdirSync(path).sort()) visit(resolve(path, name), `${key}/${name}`); }
196
+ 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)); }
197
+ else throw new Error(`Nonregular input: ${key}`);
198
+ };
199
+ try {
200
+ files.node = digest(readFileSync(process.execPath));
201
+ if (existsSync(resolve(root, 'node_modules'))) visit(resolve(root, 'node_modules'), 'node_modules');
202
+ for (const command of commands) {
203
+ 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())) : [])])];
204
+ const executable = candidates.find(path => { try { return lstatSync(path).isFile(); } catch { return false; } });
205
+ if (!executable) throw new Error(`Cannot bound executable ${command.command}`);
206
+ files[`executable:${command.id}`] = digest(readFileSync(realpathSync(executable)));
207
+ for (const path of command.reuse?.inputs ?? []) visit(projectFile(root, path), path);
208
+ }
209
+ } catch (error) { limitation = error.message; }
210
+ 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())) }));
211
+ return { key, bounded: limitation === null, suitable: !limitation && commands.every(c => c.reuse?.kind === 'local-deterministic'), limitation };
212
+ }
170
213
 
171
214
  function runPath(root, id) {
172
215
  if (!/^[a-z0-9-]{1,80}$/.test(id ?? '')) throw new Error('A valid --run ID is required.');
@@ -188,7 +231,7 @@ export function activeRun(root, session = callerSession()) {
188
231
  .map(entry => { try { return json(resolve(directory, entry.name, 'state.json')); } catch { return null; } })
189
232
  .filter(run => run && ['running', 'paused', 'blocked'].includes(run.status));
190
233
  const key = session === undefined ? undefined : gateSession(root, session);
191
- const candidates = key === undefined ? runs : runs.filter(run => run.session === key || !run.session);
234
+ 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
235
  if (candidates.length === 1) return candidates[0].id;
193
236
  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
237
  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 +378,9 @@ function withWorkspaceLock(root, operation, protectedPaths, work) {
335
378
  }
336
379
 
337
380
  function transact(root, id, work) {
381
+ if (operationCancelled() && !activeProgress.stopping) throw new Error('Operation cancelled; no further workflow stages will advance.');
338
382
  const path = runPath(root, id);
383
+ assertRunOwner(root, json(path));
339
384
  return withWorkspaceLock(root, `update run ${id}`, json(path).protectedPaths, ownership => {
340
385
  const lock = `${path}.lock`;
341
386
  // The run lock is taken only while holding the workspace lock, so one left behind belongs to an
@@ -355,7 +400,13 @@ function transact(root, id, work) {
355
400
  committing = true;
356
401
  atomicJSON(path, state);
357
402
  committed = true;
403
+ let contextPublication = null;
404
+ if (state.taskContext) {
405
+ try { publishContext(state, taskIO(root, state)); }
406
+ catch (error) { contextPublication = { status: 'needs-context-sync', error: error.message }; }
407
+ }
358
408
  writeReview(root, state);
409
+ if (contextPublication) return { ...(result ?? {}), status: 'needs-context-sync', contextPublication };
359
410
  return result ?? state;
360
411
  } catch (error) {
361
412
  if (committing || ownership.inFlightBackup) {
@@ -376,6 +427,14 @@ function requireActive(state) {
376
427
  if (state.status !== 'running') throw new Error(`Run is ${state.status}; it cannot advance.`);
377
428
  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
429
  }
430
+ export function assertRunOwner(root, state) {
431
+ if (!state.execution) return;
432
+ const execution = state.execution, caller = callerSession();
433
+ if (execution.conversationId && execution.conversationId !== caller) throw new Error(`Run ${state.id} belongs to conversation ${execution.conversationId}; the current conversation cannot mutate it.`);
434
+ if (execution.gateSession && !caller) throw new Error(`Run ${state.id} needs its current conversation context before mutation.`);
435
+ const observed = resolveExecution(root, { executionMode: execution.mode, conversationId: execution.gateSession ? caller : execution.conversationId ?? undefined, ...(execution.gateSession ? {} : { session: execution.workflowSession ?? undefined }) });
436
+ 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.`);
437
+ }
379
438
  function budget(state) {
380
439
  if (!state.limits.maxDurationMs || Date.now() - Date.parse(state.startedAt) < state.limits.maxDurationMs) return true;
381
440
  state.status = 'exhausted';
@@ -454,7 +513,14 @@ const tailBytes = outputLimit * 4;
454
513
  export function runCheckProcess(spec, io) {
455
514
  return new Promise(finish => {
456
515
  const streams = {};
457
- let child, timedOut = false, failure = null, done = false, grace, drain, watch;
516
+ let child, timedOut = false, failure = null, done = false, grace, drain, watch, progressTimer, lastOutputAt = null, lastProgressAt = 0;
517
+ const report = status => {
518
+ if (!spec.progressPath) return;
519
+ lastProgressAt = Date.now();
520
+ const latestOutput = Object.values(streams).map(s => Buffer.concat(s.tail).toString('utf8')).join('\n').slice(-2000);
521
+ 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() };
522
+ 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 */ }
523
+ };
458
524
  const stop = () => {
459
525
  if (!child?.pid) return;
460
526
  if (process.platform === 'win32') {
@@ -466,25 +532,30 @@ export function runCheckProcess(spec, io) {
466
532
  const end = status => {
467
533
  if (done) return;
468
534
  done = true;
469
- clearTimeout(timer); clearTimeout(grace); clearTimeout(drain); clearInterval(watch);
535
+ clearTimeout(timer); clearTimeout(grace); clearTimeout(drain); clearInterval(watch); clearInterval(progressTimer);
470
536
  const bytes = {}, stored = {}, tailPeak = {};
471
537
  for (const [name, stream] of Object.entries(streams)) {
472
538
  io.closeSync(stream.fd);
473
539
  io.writeFileSync(`${spec[name]}.tail`, Buffer.concat(stream.tail).subarray(-spec.tailBytes));
474
540
  bytes[name] = stream.bytes; stored[name] = stream.stored; tailPeak[name] = stream.tailPeak;
475
541
  }
542
+ report(timedOut ? 'timeout' : failure?.code === 'CYC_CHECK_CANCELLED' ? 'cancelled' : failure?.code === 'CYC_CONTROLLER_ENDED' ? 'interrupted' : failure ? 'crashed' : 'check-complete');
476
543
  finish({ status: timedOut ? null : status, timedOut, error: failure, bytes, stored, tailPeak });
477
544
  };
478
545
  // A process that ignores the kill and keeps its output open must not hold the controller.
479
546
  const timer = setTimeout(() => { timedOut = true; stop(); grace = setTimeout(() => end(null), 5000); }, spec.timeoutMs);
480
- if (spec.parentPid) {
547
+ if (spec.parentPid || spec.cancelPath) {
481
548
  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);
549
+ if (spec.cancelPath && io.existsSync(spec.cancelPath)) { failure = { code: 'CYC_CHECK_CANCELLED', message: 'Check cancelled by the owned stop request.' }; stop(); end(null); return; }
550
+ 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); } }
551
+ }, 200);
484
552
  }
485
- if (spec.forwardSignals) for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => { stop(); process.exit(1); });
553
+ 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
554
  for (const name of ['stdout', 'stderr']) streams[name] = { fd: io.openSync(spec[name], 'w'), bytes: 0, stored: 0, tail: [], tailLength: 0, tailPeak: 0 };
555
+ report('running');
556
+ if (spec.progressPath) progressTimer = setInterval(() => report('running'), 1000);
487
557
  const env = { ...process.env };
558
+ delete env.CODEX_TOOL_CALL_ID; // invocation transport metadata is neither a check input nor a reusable context
488
559
  if (spec.nodeOptions === null) delete env.NODE_OPTIONS; else if (spec.nodeOptions !== undefined) env.NODE_OPTIONS = spec.nodeOptions;
489
560
  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
561
  catch (error) { failure = { code: error.code ?? null, message: error.message }; end(null); return; }
@@ -496,10 +567,13 @@ export function runCheckProcess(spec, io) {
496
567
  // A write that fails (a full disk) stops storing; the stream then counts as cut off.
497
568
  try { stream.stored += io.writeSync(stream.fd, chunk, 0, Math.min(chunk.length, spec.limit - stream.stored)); } catch { /* stored stays short of bytes */ }
498
569
  }
570
+ const firstOutput = lastOutputAt === null;
499
571
  stream.bytes += chunk.length;
572
+ lastOutputAt = new Date().toISOString();
500
573
  stream.tail.push(chunk); stream.tailLength += chunk.length;
501
574
  while (stream.tailLength - stream.tail[0].length >= spec.tailBytes) stream.tailLength -= stream.tail.shift().length;
502
575
  stream.tailPeak = Math.max(stream.tailPeak, stream.tailLength);
576
+ if (firstOutput || Date.now() - lastProgressAt >= 250) report('running');
503
577
  });
504
578
  }
505
579
  child.on('error', error => { failure = { code: error.code ?? null, message: error.message }; if (!child.pid) end(null); });
@@ -544,18 +618,21 @@ function readOutput(path, bytes, stored, limit) {
544
618
  return { whole: null, tail: keepTail(readFileSync(`${path}.tail`).toString('utf8')) };
545
619
  }
546
620
 
547
- export function runCommands(root, commands, remaining = () => Infinity, { readLimit = outputReadLimit } = {}) {
621
+ export function runCommands(root, commands, remaining = () => Infinity, { readLimit = outputReadLimit, phase = 'candidate' } = {}) {
548
622
  const results = [];
549
623
  for (const command of commands) {
624
+ if (operationCancelled()) throw Object.assign(new Error('Operation cancelled before the next check; proof restoration still runs.'), { code: 'CYC_OPERATION_CANCELLED' });
550
625
  const left = remaining();
551
626
  if (left <= 0) break;
552
627
  const timeoutMs = Math.min(command.timeoutMs ?? defaultCheckTimeoutMs, left);
553
- const folder = checkFolder(root);
628
+ const logsRoot = activeProgress ? projectFile(root, `.cyc/runs/${activeProgress.runId}/check-logs`) : null;
629
+ if (logsRoot) mkdirSync(logsRoot, { recursive: true });
630
+ const folder = logsRoot ? mkdtempSync(resolve(logsRoot, 'check-')) : checkFolder(root);
554
631
  let run, stdout = '', stderr = '', tests = null;
555
632
  try {
556
633
  const file = name => resolve(folder, name);
557
634
  // 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 };
635
+ 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
636
  writeFileSync(file('runner.cjs'), checkRunnerSource);
560
637
  writeFileSync(file('spec.json'), JSON.stringify(spec));
561
638
  const { NODE_OPTIONS, ...env } = process.env;
@@ -577,7 +654,7 @@ export function runCommands(root, commands, remaining = () => Infinity, { readLi
577
654
  } finally {
578
655
  // A scanner can still hold the files open on Windows; a folder left in the temp directory
579
656
  // 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 */ }
657
+ if (!activeProgress) try { rmSync(folder, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }); } catch { /* left for the system's temp cleanup */ }
581
658
  }
582
659
  // A check cut short by the run's own deadline needs a longer budget, not a longer timeout.
583
660
  const error = !run.timedOut ? run.error?.message ?? null
@@ -585,6 +662,7 @@ export function runCommands(root, commands, remaining = () => Infinity, { readLi
585
662
  : `Check timed out after ${timeoutMs} ms. If it needs longer, give it a larger timeoutMs; a check without one gets ${defaultCheckTimeoutMs / 60000} minutes.`;
586
663
  results.push({ id: command.id, command: command.command, args: command.args, exitCode: run.status,
587
664
  passed: run.status === 0 && !run.error && !run.timedOut, stdout, stderr, ...(tests ? { tests } : {}), error, errorCode: run.timedOut ? 'ETIMEDOUT' : run.error?.code ?? null, timeoutMs });
665
+ if (run.error?.code === 'CYC_CHECK_CANCELLED') break;
588
666
  }
589
667
  return results;
590
668
  }
@@ -618,7 +696,7 @@ export function measureBaseline(root, id) {
618
696
  try { atomicJSON(path, record); } catch { /* the run may have been removed */ }
619
697
  return record;
620
698
  }
621
- const base = { cacheKey: state.baseline.cacheKey, sourceHash: state.baseline.sourceHash, startedAt: new Date().toISOString() };
699
+ const base = { role: 'original-only', inputs: state.baseline.inputs, cacheKey: state.baseline.cacheKey, sourceHash: state.baseline.sourceHash, startedAt: new Date().toISOString() };
622
700
  let record;
623
701
  try {
624
702
  // The agent's first command and this measurement both take the operation lock. The measurement
@@ -630,12 +708,13 @@ export function measureBaseline(root, id) {
630
708
  const results = runCommands(root, state.commands).map(measuredResult);
631
709
  const after = sourceSnapshot(root);
632
710
  // 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;
711
+ const inputs = state.baseline.inputs ? measurementInputs(root, state.commands) : null;
712
+ const clean = before.hash === state.baseline.sourceHash && after.hash === state.baseline.sourceHash && (!inputs || inputs.bounded && inputs.key === state.baseline.inputs.key);
634
713
  return clean
635
714
  ? { ...base, status: 'complete', checkedAt: new Date().toISOString(), results }
636
715
  : { ...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
716
  }));
638
- if (record.status === 'complete') cacheBaseline(root, record);
717
+ if (record.status === 'complete' && state.baseline.inputs?.suitable) cacheBaseline(root, record);
639
718
  } catch (error) {
640
719
  record = { ...base, status: 'error', reason: error.message };
641
720
  }
@@ -655,6 +734,78 @@ function retryWhileBusy(work, { attempts = 40, delayMs = 250 } = {}) {
655
734
  }
656
735
  }
657
736
 
737
+ const progressPath = (root, id) => projectFile(root, `.cyc/runs/${id}/progress.json`);
738
+ const cancellationPath = (root, id, operationId) => projectFile(root, `.cyc/runs/${id}/operations/${operationId}.cancel.json`);
739
+ const operationCancelled = () => Boolean(activeProgress?.cancelPath && existsSync(activeProgress.cancelPath));
740
+ const sameLockIdentity = owner => Object.entries(lockIdentity()).every(([key, value]) => (owner[key] ?? null) === value);
741
+ function operationView(root, id, operationId) {
742
+ const record = json(progressPath(root, id));
743
+ if (record.operationId !== operationId) throw new Error('Unknown or superseded operation handle; use the exact run/operation IDs returned by the controller.');
744
+ 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.' } };
745
+ return { ...record, elapsedSeconds: (Date.now() - Date.parse(record.startedAt)) / 1000 };
746
+ }
747
+ export function waitOperation(root, id, operationId, waitMs = 30000) {
748
+ assertRunOwner(root, readRun(root, id));
749
+ 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.');
750
+ const deadline = Date.now() + waitMs;
751
+ let view;
752
+ do {
753
+ view = operationView(root, id, operationId);
754
+ if (view.result || view.error || Date.now() >= deadline) break;
755
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.min(200, deadline - Date.now()));
756
+ } while (true);
757
+ const { path, ...safe } = view;
758
+ 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.' }) };
759
+ }
760
+ export function startOperation(root, id, { action, input = {}, waitMs = 30000 } = {}) {
761
+ const state = readRun(root, id); assertRunOwner(root, state); requireActive(state);
762
+ if (!['finish', 'verify', 'prove-red'].includes(action)) throw new Error('Background operation must be finish, verify or prove-red.');
763
+ if (!Number.isInteger(waitMs) || waitMs < 0 || waitMs > 60000) throw new Error('waitMs must be 0-60000.');
764
+ let pending;
765
+ try { pending = json(progressPath(root, id)); } catch { /* no active handle */ }
766
+ if (pending && !pending.result && !pending.error && pending.workerPid && processAlive(pending.workerPid)) return waitOperation(root, id, pending.operationId, waitMs);
767
+ const operationId = withWorkspaceLock(root, `launch ${action} run ${id}`, state.protectedPaths, () => {
768
+ const operationId = randomUUID(), requestPath = projectFile(root, `.cyc/runs/${id}/operations/${operationId}.json`);
769
+ atomicJSON(requestPath, { action, input });
770
+ const record = { runId: id, operationId, action, phase: 'starting', status: 'running', startedAt: new Date().toISOString(), latestOutput: '', lastOutputAt: null, ...lockIdentity() };
771
+ 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' });
772
+ record.workerPid = worker.pid ?? null;
773
+ if (!worker.pid) record.error = { message: 'Operation worker could not start.' };
774
+ atomicJSON(progressPath(root, id), record);
775
+ worker.on('error', error => atomicJSON(progressPath(root, id), { ...record, status: 'crashed', error: { message: error.message } })); worker.unref();
776
+ return operationId;
777
+ });
778
+ return waitOperation(root, id, operationId, waitMs);
779
+ }
780
+ export function executeOperation(root, id, operationId) {
781
+ if (!/^[a-f0-9-]{36}$/.test(operationId ?? '')) throw new Error('Invalid operation ID.');
782
+ const path = progressPath(root, id), initial = operationView(root, id, operationId);
783
+ if (initial.workerPid !== process.pid) throw new Error('Operation belongs to a different worker.');
784
+ const request = json(projectFile(root, `.cyc/runs/${id}/operations/${operationId}.json`));
785
+ activeProgress = { ...initial, path, cancelPath: cancellationPath(root, id, operationId), phase: request.action };
786
+ const acknowledgeStop = () => {
787
+ if (!operationCancelled()) return false;
788
+ const state = readRun(root, id);
789
+ activeProgress.stopping = true;
790
+ try { if (!terminal.has(state.status)) controlRun(root, id, 'stop'); }
791
+ finally { activeProgress.stopping = false; }
792
+ return true;
793
+ };
794
+ try {
795
+ if (operationCancelled()) throw new Error('Operation cancelled before starting.');
796
+ const result = retryWhileBusy(() => request.action === 'finish' ? finishRun(root, id, request.input) : request.action === 'prove-red' ? proveRun(root, id, request.input) : verifyRun(root, id));
797
+ const cancelled = acknowledgeStop();
798
+ if (cancelled) Object.assign(result, { cancelled: true, passed: false, finished: false, status: readRun(root, id).status });
799
+ if (result.results) result.results = result.results.map(({ stdout, stderr, ...r }) => ({ ...r, outputTail: `${stdout ?? ''}\n${stderr ?? ''}`.slice(-2000) }));
800
+ const latest = json(path);
801
+ atomicJSON(path, { ...latest, status: cancelled ? 'cancelled' : 'finished', completedAt: new Date().toISOString(), result });
802
+ } catch (error) {
803
+ const cancelled = acknowledgeStop();
804
+ const latest = json(path);
805
+ atomicJSON(path, { ...latest, status: cancelled ? 'cancelled' : 'failed', completedAt: new Date().toISOString(), error: { message: error.message, field: error.field, repairTemplate: error.repairTemplate, setup: error.setup } });
806
+ } finally { activeProgress = null; }
807
+ }
808
+
658
809
  // The background worker's process, recorded at start so a worker that ended without writing its
659
810
  // result is noticed, instead of leaving the baseline pending for the rest of the run.
660
811
  const baselineWorkerFile = (root, id) => projectFile(root, `.cyc/runs/${id}/baseline-worker.json`);
@@ -745,6 +896,8 @@ function originalContent(root, state, path) {
745
896
  // Latin-1 preserves every byte; only an exact original hash permits this candidate.
746
897
  const crlf = Buffer.from(shown.stdout.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1');
747
898
  if (digest(crlf) === expected) return crlf;
899
+ const finalCRLF = Buffer.from(shown.stdout.toString('latin1').replace(/\r?\n$/, '\r\n'), 'latin1');
900
+ if (digest(finalCRLF) === expected) return finalCRLF;
748
901
  }
749
902
  throw new Error(`Cannot recover the run-start version of ${path} (untracked when the run started, or changed outside Git). Record a testProof exemption with this reason instead.`);
750
903
  }
@@ -761,6 +914,7 @@ function testProofStatus(root, state, snapshot = null) {
761
914
  const proof = state.testProof;
762
915
  if (!proof?.passed) return { required: true, mode, status: proof ? 'failed' : 'missing', command: `run prove-red --run ${state.id}`, ...(proof ? { verdict: proof.verdict } : {}) };
763
916
  const files = (snapshot ?? cachedSnapshot(root)).files;
917
+ 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
918
  const stale = Object.entries(proof.testFiles).filter(([path, hash]) => files[path] !== hash).map(([path]) => path);
765
919
  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
920
  }
@@ -770,7 +924,7 @@ function testProofStatus(root, state, snapshot = null) {
770
924
  // project must pass, so the failure comes from the new tests. Refactors must stay green, which
771
925
  // shows the tests pin behavior the original code already had. Files are restored afterwards; a
772
926
  // backup stays until the restored tree matches the pre-proof snapshot exactly.
773
- export function proveRun(root, id, { tests } = {}) {
927
+ export function proveRun(root, id, { tests, measureOriginal = false } = {}) {
774
928
  return transact(root, id, (state, ownership) => {
775
929
  requireActive(state);
776
930
  if (!budget(state) || !guard(root, state)) return state;
@@ -780,6 +934,9 @@ export function proveRun(root, id, { tests } = {}) {
780
934
  const baseline = currentBaseline(root, state);
781
935
  if (baseline?.status === 'pending') throw new Error('The baseline is still measuring in the background. Try again when run next shows it complete.');
782
936
  const mode = state.playbook === 'refactor' ? 'green' : 'red';
937
+ const proofCommands = state.proofCommands ?? state.commands;
938
+ const proofInputs = measurementInputs(root, proofCommands);
939
+ if (typeof measureOriginal !== 'boolean') throw new Error('measureOriginal must be boolean.');
783
940
  const before = sourceSnapshot(root);
784
941
  const initial = state.initialSource.files;
785
942
  const changed = [...new Set([...Object.keys(initial), ...Object.keys(before.files)])].filter(path => initial[path] !== before.files[path]);
@@ -845,11 +1002,19 @@ export function proveRun(root, id, { tests } = {}) {
845
1002
  // A failure's file as an exact project-relative path. Runners report absolute paths (node --test)
846
1003
  // or paths relative to the project (tap, jest); a suffix match would let an old failure in
847
1004
  // legacy/test/x.test.mjs pass for a new test/x.test.mjs. Anything outside the project is null.
848
- const realRoot = realpathSync(root);
1005
+ const realRoot = realpathSync.native(root);
849
1006
  const projectRelative = file => {
850
1007
  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(/^\.\//, '');
1008
+ let value;
1009
+ try { value = (file.startsWith('file:') ? fileURLToPath(file) : file).split(String.fromCharCode(92)).join('/'); }
1010
+ catch { return null; }
1011
+ let path = value.replace(/^\.\//, '');
1012
+ if (isAbsolute(value) || /^[A-Za-z]:\//.test(value)) {
1013
+ // Reject foreign roots before lookup; native realpath expands Windows 8.3 aliases.
1014
+ if (isAbsolute(relative(realRoot, resolve(value)))) return null;
1015
+ try { path = slash(relative(realRoot, realpathSync.native(value))); }
1016
+ catch { return null; }
1017
+ }
853
1018
  return !path || path === '..' || path.startsWith('../') || isAbsolute(path) ? null : path;
854
1019
  };
855
1020
  const failuresInNewTestFiles = results => {
@@ -868,10 +1033,16 @@ export function proveRun(root, id, { tests } = {}) {
868
1033
  }
869
1034
  return added;
870
1035
  };
871
- let treatment; let control = null; let controlSource = null; let added = null; let failure;
1036
+ let treatment; let control = null; let broadControl = null; let broadInputs = null; let controlSource = null; let added = null; let failure; let reusedTreatmentFrom = null;
1037
+ let previous = null;
1038
+ 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) {
1039
+ assertArtifacts(root, [{ path: state.testProof.receiptPath, sha256: state.testProof.receiptHash }]);
1040
+ previous = json(projectFile(root, state.testProof.receiptPath)); reusedTreatmentFrom = state.testProof.receiptPath;
1041
+ }
872
1042
  try {
873
1043
  apply(sourceFiles, originals);
874
- if (!conflicts.size) treatment = runCommands(root, state.commands);
1044
+ if (!conflicts.size) treatment = previous?.treatment ?? runCommands(root, proofCommands, undefined, { phase: 'original-plus-new-tests' });
1045
+ if (operationCancelled()) throw Object.assign(new Error('Original-source proof cancelled.'), { code: 'CYC_OPERATION_CANCELLED' });
875
1046
  inspect();
876
1047
  if (!conflicts.size && mode === 'red') {
877
1048
  // The control run measures the run-start code, to tell a failure the new tests cause from
@@ -879,10 +1050,15 @@ export function proveRun(root, id, { tests } = {}) {
879
1050
  // check (the new tests would not catch the change), or when every failure is in a new file.
880
1051
  added = treatment.every(result => result.passed) ? {} : failuresInNewTestFiles(treatment);
881
1052
  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'; } }
1053
+ else if (previous?.control) { control = previous.control; controlSource = `reused original-only from ${reusedTreatmentFrom}`; }
1054
+ 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'; }
1055
+ else { apply(testFiles, originals); if (!conflicts.size) { control = runCommands(root, proofCommands, undefined, { phase: 'original-only' }); controlSource = 'in place'; } }
1056
+ }
1057
+ if (!conflicts.size && measureOriginal && digest(JSON.stringify(proofCommands)) !== digest(JSON.stringify(state.commands))) {
1058
+ apply(testFiles, originals); broadInputs = measurementInputs(root, state.commands);
1059
+ if (!conflicts.size) broadControl = runCommands(root, state.commands, undefined, { phase: 'original-only-broad' });
884
1060
  }
885
- } catch (error) { failure = error.message; }
1061
+ } catch (error) { if (error.code !== 'CYC_OPERATION_CANCELLED') failure = error.message; }
886
1062
  finally {
887
1063
  inspect();
888
1064
  // Restore owned paths independently: one I/O failure must not abandon the
@@ -912,6 +1088,13 @@ export function proveRun(root, id, { tests } = {}) {
912
1088
  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
1089
  }
914
1090
  rmSync(backup, { recursive: true, force: true });
1091
+ if (operationCancelled()) {
1092
+ const receiptPath = `.cyc/runs/${id}/checks/proof-cancelled-${randomUUID()}.json`;
1093
+ atomicJSON(projectFile(root, receiptPath), { passed: false, cancelled: true, restored: true, treatment: treatment ?? [], control, checkedAt: new Date().toISOString() });
1094
+ state.testProof = null; state.verification = null;
1095
+ log(state, 'proof-cancelled', { receipt: receiptPath, restored: true });
1096
+ return { runId: id, passed: false, cancelled: true, restored: true, receiptPath };
1097
+ }
915
1098
  const summary = results => results?.map(({ id: check, passed, exitCode }) => ({ id: check, passed, exitCode })) ?? null;
916
1099
  // With test runner output (TAP, mocha, jest) the proof sees test names: treatment and control
917
1100
  // differ only by the new tests, so a failing test that the control run did not have is one of
@@ -956,10 +1139,24 @@ export function proveRun(root, id, { tests } = {}) {
956
1139
  const parsed = testsOf(result);
957
1140
  const selected = [...(parsed?.failing.values() ?? [])].filter(entry => !named[result.id]?.length || named[result.id].includes(entry.path.join(' > ')));
958
1141
  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) }));
1142
+ const loads = new Map(); let headerFile = null;
1143
+ for (const line of parsed.other?.values() ?? []) {
1144
+ const header = line.match(/^# (file:\/\/\/.+?):\d+(?::\d+)?$/);
1145
+ if (header) headerFile = projectRelative(header[1]);
1146
+ const importer = projectRelative(line.split(' imported from ')[1]?.trim()) ?? (/does not provide an export/.test(line) ? headerFile : null);
1147
+ if (importer && /Cannot find (?:module|package)|does not provide an export/.test(line)) loads.set(importer, [...(loads.get(importer) ?? []), line]);
1148
+ }
1149
+ return selected.map(entry => {
1150
+ // Node reports a load failure outside its generic file-level "test failed" wrapper.
1151
+ // Associate only an explicit matching importer, never another test's suite diagnostic.
1152
+ const diagnostics = loads.get(projectRelative(entry.file)) ?? [];
1153
+ const observed = diagnostics.length ? { ...entry, error: diagnostics.join('\n'), details: [...(entry.details ?? []), ...diagnostics] } : entry;
1154
+ 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 };
1155
+ });
960
1156
  });
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() };
1157
+ const commandPlanHash = digest(JSON.stringify(proofCommands)), broadCommandsHash = digest(JSON.stringify(state.commands));
1158
+ 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() });
1159
+ 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
1160
  log(state, 'test-proof', { mode, passed, receipt: receiptPath });
964
1161
  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
1162
  });
@@ -1034,13 +1231,16 @@ function declaredChecks(root) {
1034
1231
  return { source: commands.length > 1 ? `${found[0].source}, run as ${commands.map(command => command.id).join(', ')}` : found[0].source, commands };
1035
1232
  }
1036
1233
 
1037
- export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy }) {
1234
+ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy, executionMode, conversationId, proofCommands, contextRetention, taskContext: taskPolicy, delegation }) {
1038
1235
  root = realpathSync(root);
1039
1236
  if (!text(goal)) throw new Error('A nonempty goal is required.');
1040
1237
  const selected = getPlaybook(playbook ?? routeTask(goal).playbook);
1041
1238
  const config = configuration(root);
1239
+ const taskContextPolicy = taskPolicy === undefined ? undefined : contextPolicy(taskPolicy);
1240
+ const workerPolicy = delegation === undefined ? undefined : delegationPolicy(delegation);
1042
1241
  const declared = selected.requiresChecks && !config.commands.length ? declaredChecks(root) : null;
1043
1242
  const commands = declared?.commands ?? config.commands;
1243
+ 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
1244
  // Checks are frozen into the run and the config is protected while it runs, so a run that
1045
1245
  // starts without them can never verify. Refuse before any run record exists.
1046
1246
  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 +1252,22 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1052
1252
  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
1253
  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
1254
  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);
1255
+ const execution = executionMode !== undefined || conversationId !== undefined ? resolveExecution(root, { executionMode, conversationId, session }) : null;
1256
+ session = execution ? execution.gateSession ?? execution.conversationId ?? undefined : gateSession(root, session);
1056
1257
  const id = randomUUID();
1057
1258
  // Scout can be recorded with the start. Check it before any run exists, so a bad assessment
1058
1259
  // creates nothing and the agent fixes one file instead of repairing a half-started run.
1059
1260
  const workContractVersion = selected.stages.includes('build') ? 1 : null;
1261
+ allowedPaths = normalizePaths(root, allowedPaths, 'allowedPaths');
1262
+ const retention = planRetention(root, { goal, build: !!workContractVersion, allowedPaths, explicit: contextRetention ?? scout?.context?.retention });
1263
+ const contextScope = retention.disposition === 'required' ? [retention.index, ...retention.features.map(f => f.doc)] : [];
1264
+ const protectedContext = contextScope.filter(path => protectedPathMatcher(root, config.protectedPaths)(path));
1265
+ if (protectedContext.length) { retention.disposition = 'restricted'; retention.reason = `Context is protected: ${protectedContext.join(', ')}. Retention remains pending.`; }
1266
+ else if (allowedPaths.length) allowedPaths = [...new Set([...allowedPaths, ...contextScope])];
1060
1267
  if (scout !== undefined) {
1061
1268
  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
1269
  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: [] };
1270
+ const draft = { id, playbook: selected.id, workContractVersion, contextRetention: retention, handoffs: [] };
1064
1271
  fillDerived(root, draft, 'scout', scout);
1065
1272
  validateAssessment(draft, { stage: 'scout', status: 'passed', assessment: assessmentPaths(root, scout) }, path => readFileSync(projectFile(root, path)));
1066
1273
  }
@@ -1077,16 +1284,19 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1077
1284
  // still prevent completion. Reuse a matching earlier measurement; otherwise measure in the
1078
1285
  // background while the agent does read-only work.
1079
1286
  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;
1287
+ const inputs = wanted ? measurementInputs(root, commands) : null;
1288
+ const cacheKey = wanted ? digest(`${initialSource.hash}:${inputs.key}`) : null;
1289
+ const cached = wanted && inputs.suitable ? readBaselineCache(root)[cacheKey] : null;
1082
1290
  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() };
1291
+ : cached ? { status: 'complete', reused: true, cacheKey, inputs, sourceHash: initialSource.hash, checkedAt: cached.checkedAt, results: cached.results }
1292
+ : { status: 'pending', cacheKey, inputs, sourceHash: initialSource.hash, requestedAt: new Date().toISOString() };
1085
1293
  const state = {
1086
1294
  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,
1295
+ ...(taskContextPolicy ? { taskContextPolicy } : {}), ...(workerPolicy ? { delegation: initializeDelegation(workerPolicy) } : {}),
1296
+ workContractVersion, contextRetention: retention, ...(evidenceVersion === 1 ? { evidenceVersion, reviewPolicy: reviewPolicy ?? 'self-allowed', requirements: { text: requirements, sha256: digest(requirements) }, criteriaHash: digest(JSON.stringify(criteria)) } : {}), ...ledger,
1297
+ criteria, inferredCriteria, session: session ?? null, ...(execution ? { execution } : {}), status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1089
1298
  startedAt: new Date().toISOString(), limits: config.limits, commands, ...(declared ? { verificationSource: `declared by ${declared.source}` } : {}),
1299
+ ...(proofCommands ? { proofCommands: structuredClone(proofCommands) } : {}),
1090
1300
  protectedPaths: config.protectedPaths, protectedFiles: protectedSnapshot(root, config.protectedPaths), allowedPaths,
1091
1301
  initialSource, base, ...(capture ? { sourceCapture: capture.metadata } : {}), testProof: null, baseline, acceptedFailures: [], handoffs: [], verification: null, history: []
1092
1302
  };
@@ -1137,7 +1347,15 @@ function stageTemplate(root, state) {
1137
1347
  // reason it is unrelated, or delete the entry and fix the check. The placeholder cannot pass.
1138
1348
  const failureHints = baseline => (baseline?.status === 'complete' ? baseline.results : []).filter(result => !result.passed)
1139
1349
  .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';
1350
+ const finishTemplateContent = (root, state, acceptFailures) => {
1351
+ const assessment = finishAssessmentTemplate(root, state);
1352
+ if (state.evidenceVersion === 1) {
1353
+ const scenarioEvidence = assessment.criterionChecks.map(row => ({ ...row, consumers: [] }));
1354
+ delete assessment.criterionChecks; delete assessment.consumerChecks;
1355
+ return JSON.stringify({ runId: state.id, summary: '<result and limits>', scenarioEvidence, assessment, acceptFailures }, null, 2) + '\n';
1356
+ }
1357
+ 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';
1358
+ };
1141
1359
  const finishTemplatePath = state => `.cyc/runs/${state.id}/finish-template.json`;
1142
1360
 
1143
1361
  // The finish input, written once next to the run so the agent copies a file instead of asking
@@ -1150,6 +1368,11 @@ function writeFinishTemplate(root, state) {
1150
1368
  return path;
1151
1369
  } catch { return null; }
1152
1370
  }
1371
+ function writeHandoffTemplate(root, state) {
1372
+ const stage = current(state), path = `.cyc/runs/${state.id}/handoff-${stage}-${state.attempt}.json`;
1373
+ 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>' })) });
1374
+ return path;
1375
+ }
1153
1376
 
1154
1377
  // A background measurement that finds failing checks adds them to the template, but only while
1155
1378
  // the file is still exactly what CYC wrote; a template the agent has started editing is left alone.
@@ -1174,19 +1397,37 @@ function fillDerived(root, state, stage, assessment) {
1174
1397
  if (!assessment || typeof assessment !== 'object') return assessment;
1175
1398
  const derived = derivedAssessment(state, stage, { contextHistory: hasContextHistory(root, state) });
1176
1399
  for (const [key, value] of Object.entries(derived)) if (!(key in assessment)) assessment[key] = structuredClone(value);
1400
+ if (stage === 'scout' && assessment.context && state.contextRetention) {
1401
+ const declared = assessment.context.retention;
1402
+ 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.');
1403
+ assessment.context.retention = structuredClone(state.contextRetention);
1404
+ }
1177
1405
  return assessment;
1178
1406
  }
1179
1407
 
1180
1408
  export function nextRun(root, id) {
1181
1409
  const state = readRun(root, id);
1182
1410
  const finishTemplate = finishing(state) && state.status === 'running' ? writeFinishTemplate(root, state) : null;
1411
+ const handoffTemplate = !finishing(state) && current(state) && state.status === 'running' ? writeHandoffTemplate(root, state) : null;
1412
+ let swarmAction;
1413
+ if(state.status==='running'&&['scout','understand','impact','build'].includes(current(state))&&state.delegation?.policy.mode==='auto'&&!state.delegation.swarm&&!state.verification?.passed) {
1414
+ const path=`.cyc/runs/${id}/swarm-input.json`,file=projectFile(root,path);
1415
+ if(!existsSync(file))atomicJSON(file,{version:1,objective:'time'});
1416
+ swarmAction={action:'swarm',inputTemplate:path,command:`delegate swarm --run ${id} --file ${path}`,purpose:'Automatically assess independence/economics, execute parallel workers and merge one task context before dependent work.'};
1417
+ }
1183
1418
  return {
1184
1419
  runId: state.id, engineVersion: state.engineVersion ?? 'unknown (legacy run)', status: state.status, goal: state.goal, playbook: state.playbook,
1420
+ ...(state.execution ? { execution: state.execution } : {}),
1421
+ ...(state.taskContext ? { taskContext: taskContextStatus(root, state) } : {}),
1422
+ ...(swarmAction?{swarmAction}:{}),
1423
+ ...(state.delegation ? { delegation: { route: state.delegation.decision?.route ?? 'undecided', reason: state.delegation.decision?.reason, assignments: state.delegation.assignments.map(a => ({id:a.id,status:a.status,disposition:a.disposition ?? null})), accountedTokens: state.delegation.accountedTokens, policy: state.delegation.policy, ...(state.delegation.swarm?{swarm:{id:state.delegation.swarm.id,status:state.delegation.swarm.status,phases:Object.fromEntries(Object.entries(state.delegation.swarm.jobs).map(([k,j])=>[k,j.status]))}}:{}) } } : {}),
1424
+ ...(retentionOf(state) ? { contextRetention: retentionOf(state), contextPreparation: state.contextPreparation ? { docs: state.contextPreparation.docs, status: state.contextPreparation.status } : null } : {}),
1425
+ 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
1426
  stage: current(state), attempt: state.attempt, criteria: state.criteria,
1186
1427
  workContractVersion: state.workContractVersion ?? null, assessmentRequired: Object.keys(stageTemplate(root, state) ?? {}),
1187
1428
  ...(state.evidenceVersion === 1 ? { evidenceVersion: 1, reviewPolicy: state.reviewPolicy, requirements: state.requirements } : {}),
1188
1429
  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` } : {}),
1430
+ ...(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
1431
  ...(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
1432
  ...(state.verificationSource ? { verificationSource: state.verificationSource } : {}),
1192
1433
  ...(state.commands?.length ? { verificationCommands: state.commands.map(item => `${item.id}: ${[item.command, ...item.args].join(' ')}`) } : {}),
@@ -1256,8 +1497,8 @@ function assertArtifacts(root, artifacts) {
1256
1497
  if (!Array.isArray(artifacts)) throw new Error('artifacts must be an array (empty for no file deliverables).');
1257
1498
  for (const artifact of artifacts) {
1258
1499
  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}`);
1500
+ projectFile(root, artifact.path);
1501
+ if (artifactFiles(root, [artifact.path])[0].sha256 !== artifact.sha256) throw new Error(`Artifact changed after review: ${artifact.path}`);
1261
1502
  }
1262
1503
  }
1263
1504
  function validatePacket(root, state, packet) {
@@ -1286,11 +1527,64 @@ function validatePacket(root, state, packet) {
1286
1527
  packet.artifacts = [...packet.artifacts, ...assessmentArtifacts.filter(item => !packet.artifacts.some(existing => existing.path === item.path))];
1287
1528
  }
1288
1529
  function requireVerification(root, state) {
1530
+ requireTaskReady(root, state);
1531
+ requireRetention(root, state);
1289
1532
  if (!state.requiresChecks) return;
1290
1533
  if (!state.verification?.passed) throw new Error('Run project verification successfully before passing this stage.');
1534
+ if (state.taskContext && (state.verification.taskContext?.revision !== state.taskContext.revision || state.verification.taskContext?.hash !== contextHash(state))) throw new Error('Task context changed after verification; fresh verification is required.');
1535
+ 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
1536
  const snapshot = cachedSnapshot(root);
1292
1537
  if (snapshot.skipped.length) throw new Error('Executable verification cannot cover symlink dependencies; use a project without linked source.');
1293
1538
  if (snapshot.hash !== state.verification.sourceHash) throw new Error('Source changed after verification; run verification again.');
1539
+ 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.');
1540
+ }
1541
+
1542
+ function requireRetention(root, state) {
1543
+ const checked = checkRetention(root, state, cachedSnapshot(root).files);
1544
+ if (!checked.ok) {
1545
+ const error = new Error(`Feature context is incomplete: ${checked.issues.map(i => `${i.doc ?? ''} ${i.rule}: ${i.message}`).join('; ')}`);
1546
+ error.retention = checked;
1547
+ throw error;
1548
+ }
1549
+ return checked;
1550
+ }
1551
+
1552
+ export function contextUpdate(root, id, paths, work) {
1553
+ return transact(root, id, state => {
1554
+ requireActive(state);
1555
+ if (!budget(state) || !guard(root, state)) return state;
1556
+ 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.');
1557
+ for (const path of paths) {
1558
+ projectFile(root, path);
1559
+ 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.`);
1560
+ }
1561
+ const result = work(state);
1562
+ if (!guard(root, state)) return state;
1563
+ log(state, 'context-update', { paths });
1564
+ return result;
1565
+ });
1566
+ }
1567
+
1568
+ export function prepareRunContext(root, id, input = {}) {
1569
+ const before = readRun(root, id), raw = retentionOf(before);
1570
+ assertRunOwner(root, before);
1571
+ if (!raw) return { runId: id, ...checkRetention(root, before, cachedSnapshot(root).files) };
1572
+ const plan = before.contextRetention ?? planRetention(root, { goal: before.goal, build: !!before.workContractVersion, allowedPaths: before.allowedPaths, explicit: raw });
1573
+ const paths = plan.disposition === 'required' ? [plan.index, ...plan.features.map(f => f.doc)] : [];
1574
+ return contextUpdate(root, id, paths, state => {
1575
+ if (!state.contextRetention) {
1576
+ for (const f of plan.features) {
1577
+ const original = originalContent(root, state, f.doc);
1578
+ if (original) f.baselineViewHash = digest(parseDoc(original.toString('utf8'), f.doc.split('/').at(-1)).currentView);
1579
+ }
1580
+ state.contextRetention = plan;
1581
+ }
1582
+ const prepared = prepareRetention(root, state, input, cachedSnapshot(root).files, () => {});
1583
+ state.contextPreparation = { ...prepared };
1584
+ const checked = checkRetention(root, state, cachedSnapshot(root).files);
1585
+ Object.assign(state.contextPreparation, { docs: checked.docs, status: checked.status });
1586
+ return { runId: id, status: checked.ok ? 'context-ready' : 'needs-context', ...checked, changed: prepared.paths };
1587
+ });
1294
1588
  }
1295
1589
 
1296
1590
  // Shorthand for the common case: the agent states the outcome in one line and names changed
@@ -1308,7 +1602,7 @@ export function quickHandoff(root, id, { status = 'passed', summary, artifacts =
1308
1602
  runId: id, stage, attempt: state.attempt, status, summary,
1309
1603
  ...(assessment !== undefined ? { assessment: assessmentPaths(root, assessment) } : {}),
1310
1604
  evidence: [{ kind: 'observation', detail: summary }],
1311
- artifacts: artifacts.map(path => inputPath(root, path)).map(path => ({ path, sha256: digest(readFileSync(projectFile(root, path))) })),
1605
+ artifacts: artifactFiles(root, artifacts.map(path => inputPath(root, path))),
1312
1606
  criteria: state.criteria.map(item => criterionEvidence || text(passedEvidence)
1313
1607
  ? { id: item.id, result: 'passed', evidence: criterionEvidence?.[item.id] ?? passedEvidence }
1314
1608
  : { id: item.id, result: 'unverified', evidence: `Not verified yet; checked at verify.` }),
@@ -1316,7 +1610,7 @@ export function quickHandoff(root, id, { status = 'passed', summary, artifacts =
1316
1610
  };
1317
1611
  // Deliver records which component context docs this change touched, so the context review can
1318
1612
  // 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();
1613
+ 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
1614
  return recordHandoff(root, packet);
1321
1615
  }
1322
1616
 
@@ -1324,6 +1618,7 @@ export function recordHandoff(root, packet) {
1324
1618
  return transact(root, packet.runId, state => {
1325
1619
  requireActive(state);
1326
1620
  if (!budget(state) || !guard(root, state)) return state;
1621
+ if (packet.status === 'passed') requireTaskReady(root, state);
1327
1622
  validatePacket(root, state, packet);
1328
1623
  if (packet.status === 'passed' && ['verify', 'deliver'].includes(current(state))) requireVerification(root, state);
1329
1624
  if (packet.status === 'passed' && current(state) === 'verify' && provable(state)) requireTestProof(root, state, packet.assessment?.testProof);
@@ -1336,7 +1631,8 @@ export function recordHandoff(root, packet) {
1336
1631
  for (const artifact of reviewed.artifacts) if (!packet.artifacts.some(a => a.path === artifact.path)) packet.artifacts.push(artifact);
1337
1632
  }
1338
1633
  }
1339
- const entry = { ...packet, recordedAt: new Date().toISOString(), sourceHash: cachedSnapshot(root).hash };
1634
+ 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();
1635
+ const entry = { ...packet, ...(state.taskContext ? { taskContext: { revision: state.taskContext.revision, hash: contextHash(state) } } : {}), recordedAt: new Date().toISOString(), sourceHash: cachedSnapshot(root).hash };
1340
1636
  state.handoffs.push(entry);
1341
1637
  log(state, 'handoff', { stage: packet.stage, status: packet.status, summary: packet.summary });
1342
1638
  if (packet.status === 'blocked') { state.status = 'blocked'; log(state, 'blocked', { reason: packet.nextAction ?? packet.summary }); }
@@ -1349,15 +1645,25 @@ export function recordHandoff(root, packet) {
1349
1645
  export function verifyRun(root, id) {
1350
1646
  return transact(root, id, state => {
1351
1647
  requireActive(state);
1648
+ requireTaskReady(root, state);
1352
1649
  if (!budget(state) || !guard(root, state)) return state;
1650
+ const retained = checkRetention(root, state, cachedSnapshot(root).files);
1651
+ 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
1652
  if (!state.stages.includes('verify')) throw new Error('This playbook has no executable verification stage.');
1354
1653
  if (!['verify', 'deliver'].includes(current(state)) && current(state) !== null) throw new Error('Record prerequisite skill handoffs before running verification.');
1355
1654
  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
1655
  // A stale cached hash here can only make the check look unstable; the full snapshot after it decides.
1357
- const before = cachedSnapshot(root);
1656
+ const before = sourceSnapshot(root);
1657
+ const inputsBefore = measurementInputs(root, state.commands);
1658
+ if (state.verification?.passed && (!state.taskContext || state.verification.taskContext?.hash === contextHash(state)) && state.verification.reusable === true && state.verification.role === 'candidate' && before.hash === state.verification.sourceHash && inputsBefore.suitable && state.verification.inputs?.key === inputsBefore.key) {
1659
+ assertArtifacts(root, [{ path: state.verification.receiptPath, sha256: state.verification.receiptHash }]);
1660
+ log(state, 'verification-reused', { receipt: state.verification.receiptPath, sourceHash: before.hash });
1661
+ return { runId: id, status: state.status, ...state.verification, reused: true };
1662
+ }
1358
1663
  if (before.skipped.length) throw new Error('Executable verification cannot cover symlink dependencies; use a project without linked source.');
1359
1664
  const results = runCommands(root, state.commands, () => state.limits.maxDurationMs ? state.limits.maxDurationMs - (Date.now() - Date.parse(state.startedAt)) : Infinity);
1360
1665
  const after = sourceSnapshot(root);
1666
+ const inputsAfter = measurementInputs(root, state.commands);
1361
1667
  // A check that already failed on the run-start code, and was accepted with a reason, does not
1362
1668
  // block completion if it fails exactly as it did then: the same exit code and error, the same
1363
1669
  // output lines (timings and timestamps aside), neither output cut short, and no file this run
@@ -1410,7 +1716,7 @@ export function verifyRun(root, id) {
1410
1716
  const excused = failing.filter(item => !item.changed).map(item => item.id);
1411
1717
  // Something must still be verified: a passing check, or passing tests inside an excused suite.
1412
1718
  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;
1719
+ 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
1720
  const changedPaths = [...new Set([...Object.keys(before.files), ...Object.keys(after.files)])].filter(path => before.files[path] !== after.files[path]);
1415
1721
  // Failing checks that also failed in the run-start measurement and are not accepted yet: the
1416
1722
  // agent decides whether they are unrelated, and says why, instead of retrying unchanged.
@@ -1422,8 +1728,9 @@ export function verifyRun(root, id) {
1422
1728
  const awaitingAcceptance = !passed && !state.awaitedAcceptance && failedAtRunStart.length > 0 && results.every(excusable) && before.hash === after.hash
1423
1729
  && results.some(result => result.passed || (testsOf(result)?.passingCount ?? 0) > 0);
1424
1730
  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 };
1731
+ Object.assign(receipt, { ...(state.taskContext ? { taskContext: { revision: state.taskContext.revision, hash: contextHash(state) } } : {}), role: 'candidate', inputs: inputsAfter, inputsStable: inputsBefore.bounded && inputsAfter.bounded ? inputsBefore.key === inputsAfter.key : null, reusable: passed && inputsBefore.suitable && inputsAfter.suitable });
1425
1732
  // Every command reads and writes the run state, so test summaries of long output stay in the receipt file.
1426
- state.verification = { ...receipt, results: results.map(({ tests, ...result }) => result) };
1733
+ state.verification = { ...receipt, ...(state.taskContext ? { taskContext: { revision: state.taskContext.revision, hash: contextHash(state) } } : {}), results: results.map(({ tests, ...result }) => result) };
1427
1734
  const receiptPath = `.cyc/runs/${id}/checks/${randomUUID()}.json`;
1428
1735
  atomicJSON(projectFile(root, receiptPath), receipt);
1429
1736
  state.verification.receiptPath = receiptPath;
@@ -1450,6 +1757,7 @@ export function verifyRun(root, id) {
1450
1757
  // shadow a proof control that exists.
1451
1758
  function runStartMeasurement(root, state) {
1452
1759
  const measured = currentBaseline(root, state);
1760
+ 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
1761
  return measured?.status === 'complete' ? measured : proofBaseline(root, state) ?? measured;
1454
1762
  }
1455
1763
  function runStartResults(root, state) {
@@ -1464,7 +1772,7 @@ function proofSkippedControl(root, state) {
1464
1772
  if (!path) return false;
1465
1773
  try {
1466
1774
  const receipt = json(projectFile(root, path));
1467
- return receipt.originalSourceHash === state.initialSource.hash && receipt.control === null && /^not needed/.test(receipt.controlSource ?? '');
1775
+ return !receipt.focused && receipt.originalSourceHash === state.initialSource.hash && receipt.control === null && /^not needed/.test(receipt.controlSource ?? '');
1468
1776
  } catch { return false; }
1469
1777
  }
1470
1778
  const passedAtRunStart = (root, state, check) => runStartResults(root, state)?.find(result => result.id === check)?.passed ?? (proofSkippedControl(root, state) ? true : null);
@@ -1474,7 +1782,9 @@ function proofBaseline(root, state) {
1474
1782
  if (!path) return null;
1475
1783
  try {
1476
1784
  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;
1785
+ 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 };
1786
+ 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);
1787
+ return compatible && receipt.originalSourceHash === state.initialSource.hash && Array.isArray(receipt.control) ? { status: 'complete', role: 'original-only', source: 'proof control', results: receipt.control } : null;
1478
1788
  } catch { return null; }
1479
1789
  }
1480
1790
 
@@ -1522,6 +1832,17 @@ export function retryRun(root, id, { stage, reason }) {
1522
1832
  }
1523
1833
 
1524
1834
  export function controlRun(root, id, action) {
1835
+ if (action === 'stop') {
1836
+ const state = readRun(root, id); assertRunOwner(root, state);
1837
+ if (terminal.has(state.status)) throw new Error(`Run is terminal: ${state.status}. Start a new run rather than resetting its budget.`);
1838
+ let pending;
1839
+ try { pending = json(progressPath(root, id)); } catch { /* synchronous run */ }
1840
+ if (pending && !pending.result && !pending.error && pending.workerPid !== process.pid && processAlive(pending.workerPid)) {
1841
+ if (!sameLockIdentity(pending)) throw new Error('Operation belongs to another controller context; retain its ownership and recovery handle.');
1842
+ atomicJSON(cancellationPath(root, id, pending.operationId), { operationId: pending.operationId, requestedAt: new Date().toISOString(), ...lockIdentity() });
1843
+ 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` } };
1844
+ }
1845
+ }
1525
1846
  return transact(root, id, state => {
1526
1847
  if (terminal.has(state.status)) throw new Error(`Run is terminal: ${state.status}. Start a new run rather than resetting its budget.`);
1527
1848
  if (action === 'pause') { requireActive(state); state.status = 'paused'; }
@@ -1593,12 +1914,83 @@ function proofOutdated(root, state) {
1593
1914
  return changed.some(path => state.testProof.testFiles[path] !== files[path]) || Object.keys(state.testProof.testFiles).some(path => !changed.includes(path));
1594
1915
  }
1595
1916
 
1917
+ // One scenario observation can project to multiple exact criterion/consumer views. Its origin
1918
+ // remains agent-reported; passing a command never invents a named assertion observation.
1919
+ function scenarioViews(state, rows) {
1920
+ 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')]));
1921
+ const consumers = state.handoffs.findLast(h => h.stage === 'scout' && h.status === 'passed')?.assessment?.consumers ?? [];
1922
+ const consumerChecks = consumers.map(c => {
1923
+ const matched = rows.filter(row => row.consumers?.includes(c.id));
1924
+ 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.' };
1925
+ });
1926
+ return { criterionEvidence, consumerChecks };
1927
+ }
1928
+ function importReviews(root, state, assessment) {
1929
+ const review = assessment.semanticReview;
1930
+ if (!review) return;
1931
+ if (review.receipts === undefined) review.receipts = (state.reviewReceipts ?? []).filter(r => {
1932
+ if (r.status !== 'recorded') return false;
1933
+ try { checkedReview(root, state, r.id, cachedSnapshot(root).hash); return true; } catch { return false; }
1934
+ }).map(r => r.id);
1935
+ if (review.receipts.length) review.findings ??= [];
1936
+ for (const id of review.receipts) {
1937
+ const receipt = state.reviewReceipts?.find(r => r.id === id);
1938
+ for (const finding of receipt?.findings ?? []) if (!review.findings.some(f => f.reviewId === id && f.id === finding.id)) review.findings.push({ ...finding, reviewId: id });
1939
+ }
1940
+ }
1941
+ 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 }));
1942
+ function needsProofReview(root, state, input, steps) {
1943
+ const binding = continuationBinding(root, state);
1944
+ let continuation = state.finishContinuation;
1945
+ if (!continuation || continuation.binding !== binding) {
1946
+ continuation = { token: randomUUID(), binding, attempts: 0 };
1947
+ transact(root, state.id, saved => { saved.finishContinuation = continuation; });
1948
+ }
1949
+ const inputTemplate = `.cyc/runs/${state.id}/finish-proof-${continuation.token}.json`;
1950
+ 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 }));
1951
+ 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 ?? '' })) } } });
1952
+ 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.' } };
1953
+ }
1954
+
1596
1955
  // From Build or Verify to complete in one call: record Build, prove the new tests, verify, record
1597
1956
  // Verify and Deliver, and complete. Each step is its own transaction, so a failure stops at a
1598
1957
  // defined point: a failed proof or check is reported as such, a failed check is recorded as a
1599
1958
  // 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 = [] }) {
1959
+ export function finishRun(root, id, { summary, artifacts, passedEvidence, criterionEvidence, assessment = {}, acceptFailures = [], scenarioEvidence, continuation }) {
1601
1960
  let state = readRun(root, id);
1961
+ assertRunOwner(root, state);
1962
+ requireTaskReady(root, state);
1963
+ if (current(state) === null && ['running', 'complete'].includes(state.status)) {
1964
+ const delivery = state.handoffs.at(-1);
1965
+ if (delivery?.stage !== 'deliver' || delivery.status !== 'passed') throw new Error('No confirmed delivery to resume.');
1966
+ assertArtifacts(root, delivery.artifacts);
1967
+ if (sourceSnapshot(root).hash !== delivery.sourceHash) throw new Error('Source changed after delivery; completed evidence cannot be republished.');
1968
+ requireVerification(root, state);
1969
+ if (state.execution?.mode.startsWith('native-') || !state.execution && /^[a-f0-9]{32}$/.test(state.session ?? '')) {
1970
+ const gate = json(projectFile(root, `.cyc/runtime/${state.session}.state.json`));
1971
+ if (!(Date.parse(delivery.recordedAt) >= Date.parse(gate.updatedAt))) throw new Error('Delivery is outside the current native request window.');
1972
+ }
1973
+ if (state.status === 'running') state = completeRun(root, id);
1974
+ return { runId: id, status: state.status, finished: true, steps: ['resume delivery'], packet: projectDelivery(root, state) };
1975
+ }
1976
+ if (artifacts !== undefined) artifactFiles(root, artifacts.map(path => inputPath(root, path)));
1977
+ if (continuation) {
1978
+ const saved = state.finishContinuation;
1979
+ 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.');
1980
+ 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.');
1981
+ transact(root, id, current => { current.finishContinuation.attempts++; });
1982
+ }
1983
+ if (scenarioEvidence !== undefined) {
1984
+ if (!Array.isArray(scenarioEvidence)) throw new Error('scenarioEvidence needs named criterion/clause observations.');
1985
+ if (assessment.criterionChecks && digest(JSON.stringify(assessment.criterionChecks)) !== digest(JSON.stringify(scenarioEvidence))) throw new Error('Supply one canonical scenarioEvidence record, not conflicting criterionChecks.');
1986
+ assessment.criterionChecks = structuredClone(scenarioEvidence);
1987
+ }
1988
+ if (assessment.criterionChecks) {
1989
+ const views = scenarioViews(state, assessment.criterionChecks);
1990
+ criterionEvidence ??= views.criterionEvidence;
1991
+ assessment.consumerChecks ??= views.consumerChecks;
1992
+ }
1993
+ importReviews(root, state, assessment);
1602
1994
  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
1995
  let stage = current(state);
1604
1996
  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 +2013,10 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1621
2013
  if (!criterionEvidence && state.criteria.length > 1) throw new Error('Multiple criteria need criterionEvidence mapping each criterion ID to its evidence.');
1622
2014
  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
2015
  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)));
2016
+ validateAssessment(state, { stage: name, status: 'passed', assessment: part(name) }, path => {
2017
+ const plannedContext = retentionOf(state)?.features?.some(f => f.doc === path);
2018
+ return generatesLedger && path === state.ledgerPath || plannedContext && !existsSync(projectFile(root, path)) ? null : artifactFiles(root, [path])[0];
2019
+ }, { proofPending: true });
1625
2020
  }
1626
2021
  const steps = [];
1627
2022
  const dropped = [];
@@ -1654,15 +2049,30 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1654
2049
  state = readRun(root, id);
1655
2050
  stage = current(state);
1656
2051
  }
2052
+ if (retentionOf(state)) {
2053
+ let retained = checkRetention(root, state, cachedSnapshot(root).files);
2054
+ if (!retained.ok) {
2055
+ retained = prepareRunContext(root, id, { records: assessment.learning?.context ?? [], summary, reason: assessment.learning?.reason ?? '' });
2056
+ state = readRun(root, id);
2057
+ if (!retained.ok) {
2058
+ const inputTemplate = `.cyc/runs/${id}/finish-context.json`;
2059
+ atomicJSON(projectFile(root, inputTemplate), { runId: id, summary, artifacts, passedEvidence, criterionEvidence, assessment, acceptFailures });
2060
+ 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.' } };
2061
+ }
2062
+ steps.push('prepare context');
2063
+ }
2064
+ const contextArtifacts = [...retained.docs, ...(retentionOf(state).disposition === 'required' ? [retentionOf(state).index] : [])];
2065
+ if (artifacts) artifacts = [...new Set([...artifacts, ...contextArtifacts])];
2066
+ }
1657
2067
  // Listed artifacts win; otherwise the controller names what this run changed.
1658
2068
  artifacts ??= changedArtifacts(root, state);
1659
2069
  if (stage === 'verify') {
1660
2070
  if (provable(state)) {
1661
2071
  const exemption = part('verify')?.testProof;
1662
2072
  // Prove here rather than refuse: a missing or outdated proof is one more step, not a retry.
1663
- if (exemption === undefined && proofOutdated(root, state)) {
2073
+ if (exemption === undefined && (proofOutdated(root, state) || acceptFailures.length > 0 && runStartMeasurement(root, state)?.status !== 'complete')) {
1664
2074
  let proof;
1665
- try { proof = proveRun(root, id); }
2075
+ try { proof = proveRun(root, id, { measureOriginal: acceptFailures.length > 0 }); }
1666
2076
  catch (error) { throw new Error(`Finish stopped at prove-red: ${error.message}`); }
1667
2077
  const stop = !proof.passed && stoppedBy('prove-red', proof);
1668
2078
  if (stop) return stop;
@@ -1671,6 +2081,10 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1671
2081
  state = readRun(root, id);
1672
2082
  }
1673
2083
  requireTestProof(root, state, exemption);
2084
+ if (state.evidenceVersion === 1 && exemption === undefined) {
2085
+ if (!assessment.proofReview) return needsProofReview(root, state, { summary, artifacts, passedEvidence, criterionEvidence, assessment, acceptFailures }, steps);
2086
+ validateProofReview(state, assessment.proofReview);
2087
+ }
1674
2088
  }
1675
2089
  // The proof's control run has now measured the run-start code, so listed pre-existing failures
1676
2090
  // can be checked against it. A check that passed there has nothing to accept: the entry is
@@ -1707,15 +2121,7 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1707
2121
  const completed = completeRun(root, id);
1708
2122
  steps.push('complete');
1709
2123
  // 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
- }
2124
+ const packet = completed.status === 'complete' ? projectDelivery(root, completed) : null;
1719
2125
  // What the reply may state: the proof's scope and any pre-existing failure it must disclose.
1720
2126
  return { runId: id, status: completed.status, finished: completed.status === 'complete', steps, reviewPath: reviewPath(completed),
1721
2127
  ...(packet ? { packet } : {}),
@@ -1724,6 +2130,16 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1724
2130
  ...(dropped.length ? { droppedAcceptFailures: dropped } : {}) };
1725
2131
  }
1726
2132
 
2133
+ function projectDelivery(root, state) {
2134
+ try {
2135
+ const delivery = state.handoffs.at(-1);
2136
+ const recorded = earlier => { try { return readRun(root, earlier.runId).reviewPacket?.digest === runPacketDigest(earlier); } catch { return false; } };
2137
+ 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 });
2138
+ if (packet.written) transact(root, state.id, saved => { saved.reviewPacket = { digest: packet.digest, writtenAt: new Date().toISOString() }; log(saved, 'review-packet', { digest: packet.digest }); });
2139
+ return packet;
2140
+ } catch (error) { return { written: false, reason: `Delivery evidence publication failed (${error.message}); resume finish after repairing the path/context.` }; }
2141
+ }
2142
+
1727
2143
  function writeReview(root, state) {
1728
2144
  const path = projectFile(root, reviewPath(state));
1729
2145
  const temporary = `${path}.${randomUUID()}.tmp`;
@@ -1739,7 +2155,8 @@ function writeReview(root, state) {
1739
2155
  try { if (!receipt) throw new Error('Missing registered review receipt.'); assertArtifacts(root, [{ path: receipt.path, sha256: receipt.sha256 }]); }
1740
2156
  catch (error) { artifactIssues.push(`Review ${id}: ${error.message}`); }
1741
2157
  }
1742
- writeFileSync(temporary, renderReview(state, cachedSnapshot(root).hash, artifactIssues), { mode: 0o600 });
2158
+ const source = cachedSnapshot(root), contextKey = state.reviewReceipts?.some(r => r.contextMode === 'bounded') ? measurementInputs(root, []).key : undefined;
2159
+ writeFileSync(temporary, renderReview(state, source.hash, artifactIssues, source.files, contextKey), { mode: 0o600 });
1743
2160
  renameSync(temporary, path);
1744
2161
  return reviewPath(state);
1745
2162
  }
@@ -1748,7 +2165,31 @@ export function reviewRun(root, id) {
1748
2165
  return transact(root, id, state => ({ runId: id, status: state.status, reviewPath: reviewPath(state) }));
1749
2166
  }
1750
2167
 
1751
- export function captureReview(root, id, { reviewer, scope = [] } = {}) {
2168
+ function reviewContext(root, scope, files, explicit, evidence) {
2169
+ if (explicit === undefined || !scope.length) return { contextMode: 'whole-source', contextPaths: [], contextEvidence: 'Dependency impact not bounded; whole-source freshness required.' };
2170
+ 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.');
2171
+ const paths = normalizePaths(root, explicit, 'review context');
2172
+ const covered = path => scope.some(prefix => isWithin(path, prefix));
2173
+ const pending = Object.keys(files).filter(covered), visited = new Set(); let unknown = false;
2174
+ while (pending.length) {
2175
+ const path = pending.pop(); if (visited.has(path)) continue; visited.add(path);
2176
+ if (!/\.[cm]?[jt]sx?$/.test(path)) continue;
2177
+ const body = readFileSync(projectFile(root, path), 'utf8');
2178
+ if (/\b(?:import|require)\s*\(\s*[^'"\s]/.test(body)) unknown = true;
2179
+ 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]);
2180
+ for (const specifier of imports) {
2181
+ if (specifier.startsWith('node:')) continue;
2182
+ if (specifier.startsWith('.')) {
2183
+ const base = slash(relative(root, resolve(root, dirname(path), specifier)));
2184
+ const target = [base, ...['.mjs', '.js', '.ts', '.tsx', '/index.mjs', '/index.js', '/index.ts', '/index.tsx'].map(ext => base + ext)].find(p => files[p]);
2185
+ if (!target) unknown = true; else { paths.push(target); pending.push(target); }
2186
+ } else if (specifier.startsWith('@/') || specifier.startsWith('#') || !files['package-lock.json']) unknown = true;
2187
+ }
2188
+ }
2189
+ const contextInputs = measurementInputs(root, []);
2190
+ 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 };
2191
+ }
2192
+ export function captureReview(root, id, { reviewer, scope = [], contextPaths, contextEvidence } = {}) {
1752
2193
  return transact(root, id, state => {
1753
2194
  requireActive(state);
1754
2195
  if (!['self', 'fresh-context', 'peer'].includes(reviewer)) throw new Error('Review reviewer must be self, fresh-context or peer.');
@@ -1758,11 +2199,18 @@ export function captureReview(root, id, { reviewer, scope = [] } = {}) {
1758
2199
  if (source.skipped.length) throw new Error('Review capture cannot cover symlink source dependencies.');
1759
2200
  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
2201
  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 };
2202
+ const context = reviewContext(root, paths, source.files, contextPaths, contextEvidence);
2203
+ const previous = (state.reviewReceipts ?? []).at(-1);
2204
+ 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]);
2205
+ const followupPath = `.cyc/runs/${id}/reviews/${reviewId}-followup.json`;
2206
+ 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.' });
2207
+ 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
2208
  atomicJSON(projectFile(root, path), receipt);
2209
+ const recordTemplate = `.cyc/runs/${id}/reviews/${reviewId}-record.json`;
2210
+ atomicJSON(projectFile(root, recordTemplate), { reviewId, identity: null, evidence: '<actual observations from the captured review>', findings: [] });
1763
2211
  (state.reviewReceipts ??= []).push({ ...receipt, sha256: digest(readFileSync(projectFile(root, path))) });
1764
2212
  log(state, 'review-captured', { reviewId, sourceHash: source.hash });
1765
- return receipt;
2213
+ return { ...receipt, recordTemplate, followupPath, nextAction: { action: 'review-record', runId: id, command: `run review-record --run ${id} --file ${recordTemplate}` } };
1766
2214
  });
1767
2215
  }
1768
2216
 
@@ -1770,11 +2218,14 @@ function checkedReview(root, state, id, sourceHash) {
1770
2218
  const record = state.reviewReceipts?.find(r => r.id === id);
1771
2219
  if (!record) throw new Error(`Unknown review ${id}.`);
1772
2220
  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.`);
2221
+ const source = cachedSnapshot(root);
2222
+ 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
2223
  return record;
1775
2224
  }
1776
2225
 
1777
2226
  export function recordReview(root, id, { reviewId, evidence, identity = null, findings = [] } = {}) {
2227
+ const invalid = !text(evidence) || /^<.*>$/.test(evidence.trim()) ? 'evidence' : identity !== null && (!text(identity) || /^<.*>$/.test(identity.trim())) ? 'identity' : null;
2228
+ 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
2229
  return transact(root, id, state => {
1779
2230
  requireActive(state);
1780
2231
  if (!budget(state) || !guard(root, state)) return state;
@@ -1802,6 +2253,7 @@ function bindEvidence(root, state, packet) {
1802
2253
  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
2254
  row.receipt = verification.receiptPath;
1804
2255
  }
2256
+ 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
2257
  packet.artifacts.push({ path: verification.receiptPath, sha256: verification.receiptHash });
1806
2258
  const refs = a.semanticReview.receipts ?? [];
1807
2259
  for (const ref of refs) {
@@ -1817,7 +2269,7 @@ function bindEvidence(root, state, packet) {
1817
2269
  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
2270
  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
2271
  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.');
2272
+ 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
2273
  }
1822
2274
  if (state.testProof && a.testProof?.status !== 'exempt') {
1823
2275
  assertArtifacts(root, [{ path: state.testProof.receiptPath, sha256: state.testProof.receiptHash }]);
@@ -1830,3 +2282,131 @@ function bindEvidence(root, state, packet) {
1830
2282
  state.testProof.claim = `Reason-reviewed baseline evidence (agent-reported interpretation): behavioral cases [${names('behavioral').join('; ')}]; new-interface cases [${names('new-interface').join('; ')}]. Setup and unclassified failures do not establish the intended behavior defect. This is not a repaired-defect count.`;
1831
2283
  }
1832
2284
  }
2285
+
2286
+ function taskContextStatus(root, state) {
2287
+ let publication = 'current';
2288
+ try { checkProjection(state, taskIO(root, state)); } catch { publication = 'needs-context-sync'; }
2289
+ return { path: contextPath(state), revision: state.taskContext.revision, publication,
2290
+ needsAcknowledgment: state.taskContext.acknowledgment?.revision !== state.taskContext.revision,
2291
+ nextAction: { command: `context task --run ${state.id}`, instruction: 'Read the current shared view; preserve unexpected edits if synchronization is blocked.' } };
2292
+ }
2293
+ function taskIO(root, state) {
2294
+ return { file: path => projectFile(root, path), source: () => sourceSnapshot(root).files,
2295
+ normalize: paths => normalizePaths(root, paths, 'assignment paths') };
2296
+ }
2297
+ function assertTaskOwner(root, state) {
2298
+ assertRunOwner(root, state);
2299
+ const caller = callerSession();
2300
+ if (!caller || !state.session || gateSession(root, caller) !== state.session) throw new Error('Task context belongs to its recorded parent conversation; the current owner is required.');
2301
+ }
2302
+ function requireTaskReady(root, state, options) {
2303
+ if (!state.taskContext) return;
2304
+ assertTaskOwner(root, state);
2305
+ requireContextReady(state, taskIO(root, state), options);
2306
+ }
2307
+ export function taskContext(root, id, action, input = {}) {
2308
+ return transact(root, id, state => {
2309
+ assertTaskOwner(root, state);
2310
+ if (action === 'task') {
2311
+ strictObject(input, [], 'task context read');
2312
+ if (!state.taskContext && state.status !== 'running') throw new Error('A terminal run cannot initialize task context.');
2313
+ return contextView(state, taskIO(root, state), callerSession());
2314
+ }
2315
+ requireActive(state);
2316
+ if (!budget(state) || !guard(root, state)) return { runId: id, status: state.status, nextAction: 'Inspect run recover; source/remaining budget prevents context changes.' };
2317
+ if (action !== 'ack') throw new Error('Use context task or context ack.');
2318
+ return acknowledgeContext(state, input, taskIO(root, state), callerSession());
2319
+ });
2320
+ }
2321
+ export function delegateRun(root, id, action, input) {
2322
+ return transact(root, id, state => {
2323
+ assertTaskOwner(root, state); requireActive(state);
2324
+ if (!budget(state) || !guard(root, state)) return { runId: id, status: state.status, nextAction: 'Inspect run recover; source/remaining budget prevents delegation.' };
2325
+ if (state.verification?.passed) throw new Error('New task context or worker evidence after verification requires retry and fresh verification.');
2326
+ const io = taskIO(root, state);
2327
+ initializeContext(state); checkProjection(state, io, action === 'decide');
2328
+ let result;
2329
+ if (action === 'decide') {
2330
+ const priorHash = contextHash(state);
2331
+ result = decideDelegation(state, input);
2332
+ touchContext(state, priorHash);
2333
+ } else if (action === 'assign') result = assignWorker(state, input, io);
2334
+ else if (action === 'record') {
2335
+ if (state.delegation?.assignments.find(a=>a.id===input.assignmentId)?.host) throw Error('Host-claimed assignments require the correlated host receipt path.');
2336
+ result = recordWorker(state, input, io);
2337
+ if (!result.duplicate && input.status === 'failed') failedAttempt(state, input.summary, digest(JSON.stringify(input.findings)));
2338
+ } else if (action === 'cancel') result = cancelWorker(state, input);
2339
+ else if (action === 'reconcile') {
2340
+ const reconciled = structuredClone(state);
2341
+ reconcileWorkers(reconciled, input, io);
2342
+ result = reconcileContext(state, input, io);
2343
+ if (reconciled.delegation) state.delegation = reconciled.delegation;
2344
+ checkContextSize(state);
2345
+ result.hash = contextHash(state);
2346
+ } else if(action==='swarm-start') result=startSwarm(state,input,io);
2347
+ else if(action==='swarm-plan') result=applySwarmPlan(state,input,io);
2348
+ else if(action==='swarm-batch') result=assignSwarm(state,input,io);
2349
+ else if(action==='swarm-commit') result=commitSwarm(state,input,io);
2350
+ else if(action==='cancel-swarm') result=cancelSwarm(state,input);
2351
+ else if(action==='swarm-error') {
2352
+ strictObject(input,['version','swarmId','reason'],'swarm failure');
2353
+ if(input.version!==1||input.swarmId!==state.delegation?.swarm?.id||!text(input.reason))throw Error('Foreign swarm failure.');
2354
+ state.delegation.swarm.status='needs-reconciliation';state.delegation.swarm.error=input.reason;
2355
+ failedAttempt(state,input.reason,digest(input.reason));result={runId:id,status:state.status};
2356
+ } else throw new Error('Unknown delegation action.');
2357
+ log(state, 'task-' + action, { revision: state.taskContext.revision });
2358
+ return result;
2359
+ });
2360
+ }
2361
+
2362
+ export function swarmHost(root,id,action,input) {
2363
+ return transact(root,id,state=>{
2364
+ assertTaskOwner(root,state);
2365
+ if(action==='claim') {
2366
+ requireActive(state);checkProjection(state,taskIO(root,state));
2367
+ if(!budget(state)||!guard(root,state))return {runId:id,status:state.status,nextAction:'Inspect run recover; dispatch refused.'};
2368
+ if(state.verification?.passed)throw Error('New swarm evidence requires retry and fresh verification.');
2369
+ }
2370
+ const result=swarmPhase(state,action,input,taskIO(root,state));
2371
+ if(action==='record'&&!result.duplicate&&input.result.status==='failed'&&state.status==='running')failedAttempt(state,input.result.summary,digest(JSON.stringify(input.result)));
2372
+ log(state,'swarm-host-'+action,{swarmId:input.swarmId,phase:input.phase});return result;
2373
+ });
2374
+ }
2375
+
2376
+ // Owned terminal cleanup survives parent stop without advancing/reopening it.
2377
+ export function workerHost(root, id, action, input) {
2378
+ return transact(root, id, state => {
2379
+ assertTaskOwner(root, state);
2380
+ strictObject(input, ['version','assignmentId','hostId','threadId','turnId','terminalStatus','result'], 'host receipt');
2381
+ const a = state.delegation?.assignments.find(a => a.id === input.assignmentId);
2382
+ if (input.version !== 1 || !a || !text(input.hostId)) throw Error('Unknown host assignment.');
2383
+ if (action === 'claim') {
2384
+ requireActive(state);
2385
+ checkProjection(state,taskIO(root,state));
2386
+ if (!budget(state) || !guard(root,state)) return {runId:id,status:state.status,nextAction:'Inspect run recover; dispatch was refused.'};
2387
+ if (state.delegation.policy.mode !== 'auto' || state.delegation.decision?.route !== 'delegate' || a.status !== 'active' || a.host || state.verification?.passed) throw Error('Auto dispatch needs an unclaimed active assignment and current delegation decision.');
2388
+ if (digest(JSON.stringify(Object.fromEntries(Object.entries(sourceSnapshot(root).files).filter(([p])=>a.paths.some(s=>p===s||p.startsWith(s+'/'))).sort(([x],[y])=>x.localeCompare(y))))) !== a.basisHash) throw Error('Assignment source changed before dispatch.');
2389
+ a.host = { id: input.hostId, claimedAt: new Date().toISOString() };
2390
+ } else {
2391
+ if (a.host?.id !== input.hostId) throw Error('Foreign host attempt.');
2392
+ if (action === 'bind') {
2393
+ if (!text(input.threadId) || !text(input.turnId) || a.host.turnId && (a.host.turnId !== input.turnId || a.host.threadId !== input.threadId)) throw Error('Host thread/turn binding mismatch.');
2394
+ Object.assign(a.host,{threadId:input.threadId,turnId:input.turnId});
2395
+ } else if (action === 'record') {
2396
+ const notStarted = input.terminalStatus === 'not-started' && !a.host.turnId && !input.turnId;
2397
+ if (!notStarted && (!a.host.turnId || input.threadId !== a.host.threadId || input.turnId !== a.host.turnId || !['completed','interrupted','failed'].includes(input.terminalStatus))) throw Error('Correlated terminal acknowledgment is required.');
2398
+ const expected = notStarted ? ['failed','cancelled'] : input.terminalStatus === 'completed' ? ['passed','failed'] : [input.terminalStatus === 'interrupted' ? 'cancelled' : 'failed'];
2399
+ if (a.result && a.host.terminalStatus !== input.terminalStatus) throw Error('Terminal envelope replay differs from its recorded status.');
2400
+ if (input.result?.assignmentId !== a.id || !expected.includes(input.result?.status)) throw Error('Terminal result disagrees with host acknowledgment.');
2401
+ const result = recordWorker(state,input.result,taskIO(root,state));
2402
+ if (result.duplicate) return result;
2403
+ Object.assign(a.host,{terminalStatus:input.terminalStatus,stoppedAt:new Date().toISOString()});
2404
+ if (!result.duplicate && input.result.status === 'failed' && state.status === 'running') failedAttempt(state,input.result.summary,digest(JSON.stringify(input.result.findings)));
2405
+ log(state,'worker-terminal',{assignmentId:a.id,hostId:input.hostId,terminalStatus:input.terminalStatus});
2406
+ return result;
2407
+ } else throw Error('Unknown host action.');
2408
+ }
2409
+ log(state,'worker-'+action,{assignmentId:a.id,hostId:input.hostId});
2410
+ return {runId:id,assignment:structuredClone(a)};
2411
+ });
2412
+ }