cyc-stack 0.8.3 → 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.
@@ -0,0 +1,156 @@
1
+ import { digest } from './response-gate.mjs';
2
+ import { strictObject, text, identifier, strings, contextHash, renderContext, requireContextReady, touchContext, validateEvidence } from './task-context.mjs';
3
+
4
+ const finite = n => Number.isFinite(n) && n >= 0;
5
+ const positive = n => Number.isSafeInteger(n) && n > 0;
6
+ const within = (path, prefix) => path === prefix || path.startsWith(prefix + '/');
7
+ const sourceBasis = (source, paths) => Object.fromEntries(Object.entries(source).filter(([path]) => paths.some(prefix => within(path,prefix))).sort(([a],[b]) => a.localeCompare(b)));
8
+ const sourceDrift = (assignment, source) => digest(JSON.stringify(sourceBasis(source,assignment.paths))) !== assignment.basisHash;
9
+ export function delegationPolicy(input) {
10
+ strictObject(input, ['version','mode','maxWorkers','maxAssignments','budgetTokens','reserveTokens','maxResultBytes'], 'delegation');
11
+ if (input.version !== 1 || !['off','recommend','auto'].includes(input.mode ?? 'recommend')) throw Error('Delegation needs version 1 and off, recommend or auto mode.');
12
+ for (const key of ['budgetTokens','reserveTokens']) if (input[key] !== undefined && !positive(input[key])) throw Error('Invalid legacy token metadata.');
13
+ const { budgetTokens, reserveTokens, ...settings } = input;
14
+ const p = { version: 1, mode: 'recommend', maxWorkers: input.mode === 'auto' ? 2 : 1, maxAssignments: 4, maxResultBytes: 32768, ...settings };
15
+ if (!positive(p.maxWorkers) || p.maxWorkers > 8 || !positive(p.maxAssignments) || p.maxAssignments > 100 || !positive(p.maxResultBytes) || p.maxResultBytes > 262144) throw Error('Invalid delegation worker/result limits.');
16
+ return p;
17
+ }
18
+ export function initializeDelegation(policy) {
19
+ return { version: 1, policy, decision: null, assignments: [], accountedTokens: 0, usageReceipts: [], observedTokens: 0, usageUnknown: false };
20
+ }
21
+ function ledger(state) {
22
+ if (!state.delegation) throw Error('Delegation policy must be frozen at run start.');
23
+ return state.delegation;
24
+ }
25
+ export function decideDelegation(state, input) {
26
+ strictObject(input, ['version','objective','facts','capabilities','estimates'], 'delegation decision');
27
+ strictObject(input.facts, ['independent','sharedState','evidence'], 'task facts');
28
+ strictObject(input.capabilities, ['dispatch','evidence'], 'capabilities');
29
+ if (input.version !== 1 || !['tokens','spend','time'].includes(input.objective) || typeof input.facts.independent !== 'boolean' || typeof input.facts.sharedState !== 'boolean' || !text(input.facts.evidence) || typeof input.capabilities.dispatch !== 'boolean' || !text(input.capabilities.evidence)) throw Error('Decision needs explicit objective, dependency facts and capability evidence.');
30
+ if (input.estimates !== undefined) {
31
+ strictObject(input.estimates, ['solo','delegated','evidence'], 'estimates');
32
+ for (const k of ['solo','delegated']) {
33
+ strictObject(input.estimates[k], ['min','max'], 'estimate range');
34
+ if (!finite(input.estimates[k].min) || !finite(input.estimates[k].max) || input.estimates[k].max < input.estimates[k].min) throw Error('Invalid estimate range.');
35
+ }
36
+ if (!text(input.estimates.evidence)) throw Error('Estimate provenance is required.');
37
+ }
38
+ const d = ledger(state);
39
+ let route = 'solo', reason = 'Economic advantage is unknown or estimate ranges overlap.';
40
+ if (d.policy.mode === 'off') reason = 'Optional delegation is disabled; required review is unaffected.';
41
+ else if (!input.capabilities.dispatch) reason = 'Host dispatch is unavailable or not observed.';
42
+ else if (!input.facts.independent || input.facts.sharedState) reason = 'Shared or dependent decisions favor one owner.';
43
+ else if (input.objective === 'time') { route = 'delegate'; reason = 'Independent work can be delegated for time; token savings are not established.'; }
44
+ else if (input.estimates && input.estimates.delegated.max < input.estimates.solo.min) { route = 'delegate'; reason = 'Agent-reported full-route estimate ranges favor bounded delegation.'; }
45
+ d.decision = { version: 1, route, reason, ...structuredClone(input), origin: 'agent-reported; not host capability attestation or measured savings' };
46
+ return { route, reason, policy: d.policy, estimates: input.estimates ?? null, origin: d.decision.origin };
47
+ }
48
+ export function assignWorker(state, input, io) {
49
+ strictObject(input, ['version','id','objective','criteria','paths','writePaths','dependencies','contextRevision','contextHash','tokenBudget','stoppingRule','hostReference'], 'assignment');
50
+ const d = ledger(state); requireContextReady(state, io, { allowPending: true });
51
+ if (d.policy.mode === 'off' || d.decision?.route !== 'delegate') throw Error('A current bounded delegation decision is required.');
52
+ if (input.version !== 1 || !identifier(input.id) || !text(input.objective) || !text(input.stoppingRule) || input.tokenBudget !== undefined && !positive(input.tokenBudget)) throw Error('Invalid assignment identity/objective/stopping rule or legacy token metadata.');
53
+ for (const k of ['criteria','paths','writePaths','dependencies']) strings(input[k], k);
54
+ if (input.writePaths.length) throw Error('Initial delegation is read-only; worker writePaths must be empty.');
55
+ if (!input.paths.length || !input.criteria.length || input.criteria.some(id => !state.criteria.some(c => c.id === id))) throw Error('Assignment must cover declared criteria and a bounded source scope.');
56
+ if (input.contextRevision !== state.taskContext.revision || input.contextHash !== contextHash(state)) throw Error('Assignment needs the current acknowledged context revision/hash.');
57
+ if (input.hostReference !== undefined && !text(input.hostReference)) throw Error('Host reference must be observed nonempty text.');
58
+ if (d.assignments.some(a => a.id === input.id)) throw Error('Assignment IDs cannot be reused.');
59
+ if (d.assignments.length >= d.policy.maxAssignments) throw Error('Total assignment budget exhausted.');
60
+ const active = d.assignments.filter(a => ['active','cancelling'].includes(a.status));
61
+ if (active.length >= d.policy.maxWorkers) throw Error('Active worker limit reached; cancellation needs host acknowledgment.');
62
+ if (input.dependencies.some(id => id === input.id || !d.assignments.some(a => a.id === id && a.disposition === 'accepted'))) throw Error('Dependencies must be existing accepted assignments; cyclic/unknown dependencies are rejected.');
63
+ const paths = io.normalize(input.paths);
64
+ if (paths.some(path => state.allowedPaths.length && !state.allowedPaths.some(prefix => within(path, prefix)))) throw Error('Assignment scope exceeds parent authority.');
65
+ for (const path of paths) io.file(path);
66
+ const snapshot = io.source();
67
+ const basis = sourceBasis(snapshot,paths);
68
+ if (!Object.keys(basis).length || paths.some(p => !Object.keys(basis).some(file => within(file,p)))) throw Error('Each read scope needs current regular source files.');
69
+ const hash = contextHash(state);
70
+ const { tokenBudget, ...details } = input;
71
+ const assignment = { ...structuredClone(details), paths, basis, basisHash: digest(JSON.stringify(basis)), ...(d.policy.mode==='auto'?{contextDocument:renderContext(state)}:{}), status: 'active', stage: state.stages[state.stageIndex], attempt: state.attempt };
72
+ d.assignments.push(assignment); touchContext(state, hash);
73
+ return { runId: state.id, assignment: structuredClone(assignment), enforcement: 'Worker concurrency/scope limits; token usage is reporting only.' };
74
+ }
75
+ export function recordWorker(state, input, io) {
76
+ strictObject(input, ['version','assignmentId','resultId','status','contextRevision','contextHash','basisHash','summary','findings','failedApproaches','questions','checks','usage','hostStopped'], 'worker result');
77
+ const d = ledger(state), a = d.assignments.find(a => a.id === input.assignmentId);
78
+ if (!a) throw Error('Unknown assignment.');
79
+ if (Buffer.byteLength(JSON.stringify(input)) > d.policy.maxResultBytes) throw Error('Worker result exceeds maxResultBytes.');
80
+ const resultHash = digest(JSON.stringify(input));
81
+ if (a.result) {
82
+ if (a.resultHash === resultHash) return { runId: state.id, assignmentId: a.id, duplicate: true };
83
+ throw Error('Worker result replay differs from the recorded result.');
84
+ }
85
+ if (d.assignments.some(other => other.id !== a.id && other.result?.resultId === input.resultId)) throw Error('Result ID is already bound to another assignment.');
86
+ if (input.version !== 1 || !identifier(input.resultId) || !['passed','failed','cancelled'].includes(input.status) || input.hostStopped !== true || !text(input.summary)) throw Error('Result needs a terminal host acknowledgment, valid status and summary.');
87
+ if (input.contextRevision !== a.contextRevision || input.contextHash !== a.contextHash || input.basisHash !== a.basisHash) throw Error('Worker result has a foreign/stale assignment basis.');
88
+ if (!Array.isArray(input.findings) || new Set(input.findings.map(f=>f?.id)).size !== input.findings.length) throw Error('Worker findings need unique IDs.');
89
+ strings(input.failedApproaches, 'failedApproaches'); strings(input.questions, 'questions');
90
+ for (const f of input.findings) {
91
+ strictObject(f, ['id','text','evidence'], 'worker finding');
92
+ if (!identifier(f.id) || !text(f.text)) throw Error('Invalid worker finding.');
93
+ validateEvidence(state,f.evidence,io,{current:false});
94
+ if (f.evidence.some(e => { const path=io.normalize([e.path])[0]; return !a.paths.some(p => within(path,p)); })) throw Error('Worker evidence exceeds assignment scope.');
95
+ }
96
+ if (input.checks !== undefined) {
97
+ if (!Array.isArray(input.checks)) throw Error('checks needs an array.');
98
+ for (const c of input.checks) { strictObject(c,['command','result','evidence'],'reported check'); if (!text(c.command)||!['passed','failed','unverified'].includes(c.result)||!text(c.evidence)) throw Error('Invalid agent-reported check.'); }
99
+ }
100
+ const hash = contextHash(state);
101
+ recordUsage(d,input.usage);
102
+ const now = io.source();
103
+ a.result = structuredClone(input); a.resultHash = resultHash; a.status = 'returned';
104
+ a.stale = sourceDrift(a,now);
105
+ touchContext(state,hash);
106
+ return { runId: state.id, assignmentId: a.id, status: 'needs-reconciliation', stale: a.stale, accountedTokens: d.accountedTokens };
107
+ }
108
+ export function recordUsage(d,usage) {
109
+ let charge = 0;
110
+ if (usage !== undefined) {
111
+ strictObject(usage, ['receiptId','inputTokens','outputTokens','cachedInputTokens','model','origin'], 'usage');
112
+ const u = usage;
113
+ if (!identifier(u.receiptId) || !['host-reported','agent-estimated'].includes(u.origin) || !text(u.model) || !Number.isSafeInteger(u.inputTokens) || u.inputTokens < 0 || !Number.isSafeInteger(u.outputTokens) || u.outputTokens < 0 || u.cachedInputTokens !== undefined && (!Number.isSafeInteger(u.cachedInputTokens)||u.cachedInputTokens<0||u.cachedInputTokens>u.inputTokens)) throw Error('Invalid usage observation.');
114
+ if (d.usageReceipts.includes(u.receiptId)) throw Error('Usage receipt was already accounted.');
115
+ charge = u.inputTokens + u.outputTokens;
116
+ if (!Number.isSafeInteger(charge) || !Number.isSafeInteger(d.accountedTokens + charge)) throw Error('Usage exceeds safe integer accounting.');
117
+ if (u.origin === 'host-reported') d.observedTokens += charge;
118
+ else d.usageUnknown = true;
119
+ d.usageReceipts.push(u.receiptId);
120
+ } else d.usageUnknown = true;
121
+ d.accountedTokens += charge;
122
+ }
123
+ export function assignBatch(state,tasks,io) {
124
+ if (!Array.isArray(tasks)||!tasks.length||new Set(tasks.map(t=>t.id)).size!==tasks.length) throw Error('Batch needs unique assignments.');
125
+ const d=ledger(state), active=d.assignments.filter(a=>['active','cancelling'].includes(a.status)).length;
126
+ if(active+tasks.length>d.policy.maxWorkers||d.assignments.length+tasks.length>d.policy.maxAssignments)throw Error('Batch exceeds frozen worker/assignment limits.');
127
+ const source=JSON.stringify(io.source()),hash=contextHash(state);
128
+ const assignments=tasks.map(t=>assignWorker(structuredClone(state),t,io).assignment);
129
+ if(JSON.stringify(io.source())!==source)throw Error('Batch source changed during validation.');
130
+ d.assignments.push(...assignments);touchContext(state,hash);
131
+ return {assignments:structuredClone(assignments)};
132
+ }
133
+ export function cancelWorker(state, input) {
134
+ strictObject(input,['version','assignmentId','reason'],'cancellation');
135
+ const a = ledger(state).assignments.find(a=>a.id===input.assignmentId);
136
+ if (input.version!==1 || !a || a.status!=='active' || !text(input.reason)) throw Error('Cancellation needs an active assignment and reason.');
137
+ const hash=contextHash(state); a.status='cancelling'; a.cancelReason=input.reason; touchContext(state,hash);
138
+ return { runId:state.id,assignmentId:a.id,status:'cancelling',nextAction:'Cancel in the host, then record its terminal acknowledgment; capacity remains reserved.' };
139
+ }
140
+ export function reconcileWorkers(state, input, io) {
141
+ if (!Array.isArray(input.dispositions)) throw Error('Reconciliation needs contribution dispositions.');
142
+ const d=state.delegation;
143
+ if (!d && input.dispositions.length) throw Error('No worker contributions exist.');
144
+ const seen=new Set();
145
+ for (const item of input.dispositions) {
146
+ strictObject(item,['assignmentId','status','reason','findingIds','revalidation'],'worker disposition');
147
+ const a=d?.assignments.find(a=>a.id===item.assignmentId);
148
+ if (!a?.result || a.disposition || seen.has(a.id) || !['accepted','rejected'].includes(item.status) || !text(item.reason)) throw Error('Disposition needs an undisposed terminal result and evidence/reason.');
149
+ a.stale ||= sourceDrift(a,io.source());
150
+ strings(item.findingIds,'disposition findingIds');
151
+ if (item.status==='accepted' && (!item.findingIds.length || a.stale&&!text(item.revalidation) || item.findingIds.some(id=>!input.findings?.some(f=>f.id===id && f.origins?.includes(a.id) && !['stale','superseded'].includes(f.status))))) throw Error('Accepted results need retained findings with origin and explicit stale-source revalidation.');
152
+ for (const failure of a.result.failedApproaches) if (!input.failedApproaches?.includes(failure)) throw Error('Retain worker failed approaches as negative evidence.');
153
+ if (a.result.questions.length && !text(item.revalidation) && !input.conflicts?.length) throw Error('Resolve worker questions explicitly or retain an unresolved conflict.');
154
+ a.disposition=item.status; a.dispositionReason=item.reason; seen.add(a.id);
155
+ }
156
+ }
@@ -4,6 +4,7 @@ import { doctorProject } from './install.mjs';
4
4
  import { atomicJSON, configuration, projectFile, runCommands, sourceSnapshot } from './runtime.mjs';
5
5
  import { digest } from './response-gate.mjs';
6
6
  import { inspectHostActivation } from './host-activation.mjs';
7
+ import { responseGuidance } from './response-mode.mjs';
7
8
 
8
9
  const receiptName = '.cyc/runtime/onboarding-checks.json';
9
10
  const configName = '.cyc/config.json';
@@ -59,7 +60,7 @@ function inspectChecks(root, config, verify) {
59
60
 
60
61
  export function onboardProject(target, { verify = false, host = 'auto', session, token, env = process.env } = {}) {
61
62
  const root = resolve(target);
62
- const report = { ok: true, projectRoot: root, installation: 'missing', steps: [], evidenceSources: [], commands: [] };
63
+ const report = { ok: true, projectRoot: root, environment: { node: process.version, platform: process.platform, arch: process.arch }, installation: 'missing', steps: [], evidenceSources: [], commands: [] };
63
64
  const add = (id, status, detail, action, extra = {}) => {
64
65
  report.steps.push({ id, status, detail, action, ...extra });
65
66
  if (['missing', 'failed'].includes(status)) report.ok = false;
@@ -105,6 +106,18 @@ export function onboardProject(target, { verify = false, host = 'auto', session,
105
106
  'Use the user’s requested bounded task, or recommend one from inspected project evidence. Explain success criteria and use the normal Scout → Build → Verify → Deliver flow. Ask before selecting unrelated product changes.');
106
107
  const next = report.steps.find(step => step.status !== 'passed');
107
108
  report.nextAction = { step: next.id, instruction: next.action };
109
+ report.guidance = { outcome: report.ready ? 'setup-checked' : report.canStartTask ? 'task-can-start' : 'setup-needed',
110
+ summary: report.ready ? 'Setup has matching local checks and current host observations. Continue the authorized task; its outcome still needs verification.' : report.canStartTask ? 'This prompt hook was observed. Continue the authorized task and observe completion after the turn ends.' : next.detail,
111
+ nextAction: report.nextAction };
112
+ report.identity = {engineVersion:JSON.parse(readFileSync(new URL('../package.json',import.meta.url),'utf8')).version,hostVersion:null,hostVersionSource:'Unavailable; a CLI on PATH is not the running host.'};
113
+ let preference={},presentation;
114
+ if(activation.canStartTask && activation.evidencePath) try { preference=JSON.parse(readFileSync(projectFile(root,activation.evidencePath),'utf8')); } catch { /* unknown, never synthesize state */ }
115
+ try { presentation=JSON.parse(readFileSync(projectFile(root,configName),'utf8')).delivery?.presentation; } catch { /* the configuration step already reports the error */ }
116
+ report.experience={purpose:'Use relevant project knowledge, check the change and retain consequential decisions for the next chat.',
117
+ before:'Explain the requested outcome and the existing behavior to preserve; continue an authorized task, otherwise suggest one from inspected project evidence.',
118
+ during:'Connect a discovered rule to the decision it changes and its check. Report actual failures and uncertainty, not routine command counts.',
119
+ after:'Link actual checks, remaining limits and the target project context saved for the next chat. A stage pass does not prove understanding or usefulness.',understanding:'unverified'};
120
+ report.responseChoices=responseGuidance({...preference,presentation});
108
121
  report.note = 'Inspection is read-only. --verify explicitly executes configured commands, which may have project-defined side effects, and saves a diagnostic receipt. The host agent recommends checks and confirms actual live observations.';
109
122
  return report;
110
123
  }
@@ -5,7 +5,7 @@ import { createHash, randomUUID } from 'node:crypto';
5
5
  import { spawnSync } from 'node:child_process';
6
6
  import { atomicJSON, configuration, readRun, runCommands, sourceSnapshot } from './runtime.mjs';
7
7
  import { runBrowserAudit, validateBrowserPlan } from './browser-audit.mjs';
8
- import { canonicalPattern, matches, contextLocation } from './context-review.mjs';
8
+ import { canonicalPattern, matches, contextLocation, parseDoc } from './context-review.mjs';
9
9
 
10
10
  const registryName = 'docs/context/recipes.json';
11
11
  const indexName = 'docs/context/INDEX.md';
@@ -46,7 +46,7 @@ function selection(root, { paths = [], goal = '', run } = {}) {
46
46
  }
47
47
  paths = [...new Set(paths.map(p => canonical(p)))];
48
48
  const words = String(goal).toLowerCase().match(/[a-z0-9-]{3,}/g)?.filter(w => !['the', 'and', 'for', 'with', 'this', 'that', 'add', 'fix', 'change'].includes(w)) ?? [];
49
- return { paths, goal, relevant: (covers, description) => paths.length ? covers.some(p => paths.some(path => matches(p, path))) : words.some(w => description.toLowerCase().includes(w)) };
49
+ return { paths, goal, words, relevant: (covers, description) => paths.length ? covers.some(p => paths.some(path => matches(p, path))) : words.some(w => description.toLowerCase().includes(w)) };
50
50
  }
51
51
 
52
52
  function registry(root) {
@@ -118,6 +118,25 @@ export function contextLinks(cell) {
118
118
  }).filter(Boolean);
119
119
  }
120
120
 
121
+ function recordFreshness(root,record,limit) {
122
+ const base={coverage:'selected-files-only',gitFreshness:'not-inspected',semanticCorrectness:'unverified'};
123
+ if(!record.exists)return {...base,status:'missing'};
124
+ try {
125
+ const path=local(root,record.path);
126
+ if(!lstatSync(path).isFile())return {...base,status:'invalid',reason:'Context link is not a regular file.'};
127
+ const parsed=parseDoc(readFileSync(path,'utf8'),path.split(/[\\/]/).at(-1));
128
+ if(parsed.issues.length)return {...base,status:'unverified',reason:'No valid canonical source binding; inspect this reference against current code.'};
129
+ const selected=parsed.history[0]?.files??[];
130
+ if(!selected.length)return {...base,status:'unverified',checkedFiles:0};
131
+ const files=selected.slice(0,limit).map(item=>{
132
+ if(!/^sha256:[a-f0-9]{64}$/i.test(item.hash)||item.path.startsWith('.cyc/')||item.path===record.path||!parsed.covers.some(pattern=>matches(pattern,item.path)))return {path:item.path,status:'unverified'};
133
+ try { const source=local(root,item.path);return {path:item.path,status:!existsSync(source)?'missing':lstatSync(source).isFile()&&hash(readFileSync(source))===item.hash.slice(7)?'matches':'changed'}; }
134
+ catch {return {path:item.path,status:'unverified'};}
135
+ });
136
+ return {...base,status:files.some(f=>['changed','missing'].includes(f.status))?'drifted':selected.length>limit||files.some(f=>f.status==='unverified')?'unverified':'matches',checkedFiles:files.length,totalBindings:selected.length,truncated:selected.length>limit,files};
137
+ } catch(error){return {...base,status:'unverified',reason:error.message};}
138
+ }
139
+
121
140
  export function investigateProject(target, options = {}) {
122
141
  const { index: indexName } = contextLocation(realpathSync(target));
123
142
  validateRecipeKind(options.kind);
@@ -141,12 +160,14 @@ export function investigateProject(target, options = {}) {
141
160
  try {
142
161
  covers.forEach(p => canonical(p === 'all' ? '**' : p, true));
143
162
  if (!selected.relevant(covers.map(p => p === 'all' ? '**' : p), cells.join(' '))) continue;
144
- found.push({ area: cells[0], covers, records: links(cells[header.indexOf('record') >= 0 ? header.indexOf('record') : header.indexOf('doc')]), evidence: header.includes('evidence') ? links(cells[header.indexOf('evidence')]) : [] });
163
+ const patterns=covers.map(p=>p==='all'?'**':p);
164
+ const match={kind:selected.paths.length?'path':'goal',paths:selected.paths.map(path=>({path,patterns:patterns.filter(p=>matches(p,path))})).filter(p=>p.patterns.length),words:selected.paths.length?[]:selected.words.filter(w=>cells.join(' ').toLowerCase().includes(w))};
165
+ found.push({ area: cells[0], covers, match, records: links(cells[header.indexOf('record') >= 0 ? header.indexOf('record') : header.indexOf('doc')]), evidence: header.includes('evidence') ? links(cells[header.indexOf('evidence')]) : [] });
145
166
  } catch (error) { warnings.push(error.message); }
146
167
  }
147
168
  }
148
- const evidenceChecks = new Map();
149
- const contexts = found.slice(0, limit).map(entry => ({ ...entry, evidence: entry.evidence.map(e => {
169
+ const evidenceChecks = new Map(), recordChecks=new Map();
170
+ const contexts = found.slice(0, limit).map(entry => ({ ...entry, recordEvidence:entry.records.map(record=>{if(!recordChecks.has(record.path))recordChecks.set(record.path,recordFreshness(root,record,limit));return {path:record.path,...recordChecks.get(record.path)};}), evidence: entry.evidence.map(e => {
150
171
  if (!e.exists || !e.path.endsWith('.json')) return e;
151
172
  if (!evidenceChecks.has(e.path)) {
152
173
  const checked = spawnSync(process.execPath, [helper, 'check', '--project', root, '--manifest', e.path], { encoding: 'utf8', windowsHide: true, timeout: 10000, maxBuffer: 1024 * 1024 });
@@ -1,5 +1,20 @@
1
1
  // Presentation only: the controller owns transitions and completion decisions.
2
2
  // Historical observations must never be promoted to current verification here.
3
+ export function completionGuidance(result, { executionMode } = {}) {
4
+ const report = result.result ?? result, id = result.runId ?? report.runId;
5
+ const inspect = { action: 'recover', command: `run recover --run ${id}`, instruction: 'Inspect this run before changing files or retrying; preserve its existing evidence and budget.' };
6
+ if (result.operationId && !result.operationComplete && !result.error) return { outcome: 'in-progress', summary: `The ${result.action ?? 'check'} operation is active at ${result.phase ?? 'its recorded phase'}. Completion has not been established.`, nextAction: result.nextAction };
7
+ if (result.error) return { outcome: 'blocked', summary: result.error.message, nextAction: inspect };
8
+ if (['needs-context', 'needs-proof-review'].includes(report.status)) return { outcome: 'needs-input', summary: report.status === 'needs-context' ? 'Your changes remain in place. Finish needs the listed context corrections before checks can establish completion.' : 'Original-source proof ran. Judge the listed failures before finish can continue; no completion is claimed.', nextAction: report.nextAction };
9
+ if (report.finished === true && report.status === 'complete') {
10
+ if (report.packet?.written === false && executionMode === 'cursor' && report.packet.reason?.startsWith('Cursor requires the exact reply:')) return { outcome: 'needs-input', summary: 'Work is recorded. Cursor still needs its exact-response delivery packet.', nextAction: { action: 'packet', instruction: report.packet.reason } };
11
+ if (report.packet?.written === false) return { outcome: 'needs-repair', summary: `Run completion is recorded, but delivery evidence was not published: ${report.packet.reason}`, nextAction: inspect };
12
+ return { outcome: 'complete', summary: 'Completion is recorded. Use the review and delivery evidence for the checked scope and remaining limits; this does not certify host activation or product readiness.', nextAction: null };
13
+ }
14
+ if (report.passed === true) return { outcome: 'in-progress', summary: 'This check passed. The remaining workflow still needs its recorded judgments and completion conditions.', nextAction: report.nextAction ?? { action: 'next', command: `run next --run ${id}` } };
15
+ return { outcome: ['halted', 'exhausted', 'blocked', 'stopped'].includes(report.status) ? 'blocked' : 'needs-repair', summary: report.reason ?? `The ${report.failedAt ?? result.action ?? 'check'} step did not establish completion. Inspect the recorded result before retrying.`, nextAction: report.recovery?.nextAction ?? report.nextAction ?? inspect };
16
+ }
17
+
3
18
  export function recoveryGuidance(state, { sourceHash, guardIssues, inspectionError, lastCheck, engineVersion, workspaceOperation }) {
4
19
  const stage = state.stages[state.stageIndex] ?? null;
5
20
  const issues = guardIssues.protectedChanges.length || guardIssues.outOfScope.length;
@@ -48,6 +63,9 @@ export function recoveryGuidance(state, { sourceHash, guardIssues, inspectionErr
48
63
  else if (state.requiresChecks && !current && ['verify', 'deliver', null].includes(stage)) action('verify',
49
64
  'Current files do not have passing executable evidence. If a Verify handoff already passed, retry the affected stage with a reason first; then run verification and refresh the semantic review. Preserve the existing failure budget.');
50
65
  else action('continue', stage ? `Continue the ${stage} stage with the original criteria. Inspect the existing handoff and current diff before editing; a stage result is not task completion.` : 'All stages are recorded. Use run complete to let the controller check freshness and completion conditions.');
66
+ nextAction.command = nextAction.kind === 'resume' ? `run resume --run ${state.id}` : nextAction.kind === 'continue' || nextAction.kind === 'verify' ? `run next --run ${state.id}` : null;
67
+ const outcome = nextAction.kind === 'resume' ? 'paused' : nextAction.kind === 'review-complete' ? 'recorded-complete' : nextAction.kind === 'continue' ? 'in-progress' : ['inspect-check', 'inspect-failure', 'verify', 'refresh-review', 'inspect-source-change'].includes(nextAction.kind) ? 'needs-repair' : 'blocked';
68
+ const summary = outcome === 'recorded-complete' ? 'This run has recorded completion. Recheck its evidence against current files before relying on it.' : `Your changes remain in place. ${outcome === 'paused' ? 'This run is paused; inspect the diff before resuming.' : outcome === 'in-progress' ? 'Continue the recorded stage using the original criteria.' : 'The run needs attention before it can finish.'}`;
51
69
  return {
52
70
  runId: state.id, status: state.status, goal: state.goal, stage, criteria: state.criteria,
53
71
  remainingAttempts: Math.max(0, state.limits.maxAttempts - state.failures),
@@ -61,6 +79,7 @@ export function recoveryGuidance(state, { sourceHash, guardIssues, inspectionErr
61
79
  reviewPath: `.cyc/runs/${state.id}/review.md`,
62
80
  acceptedFailures: state.acceptedFailures ?? [],
63
81
  preservation: 'Recovery inspection changed no source files, run state, receipts or budgets. Existing files remain in place; this is not a backup or a claim that earlier commands had no side effects.',
64
- nextAction
82
+ nextAction, guidance: { outcome, summary, nextAction },
83
+ effort:{recordedFailures:state.failures,recordedNoProgress:state.noProgress,modelRequests:null,journeyDurationSeconds:null,note:'Failure counts are recorded events, not time or resource savings. Bounded operation views report their own elapsed time.'}
65
84
  };
66
85
  }
@@ -10,3 +10,11 @@ export function lengthCommand(prompt) {
10
10
  export function allowsLongResponse(state) {
11
11
  return state.characterLimitEnabled === false || state.expanded === true;
12
12
  }
13
+
14
+ // A view of observed preferences, never a writer or a claim of hook activation.
15
+ export function responseGuidance({characterLimitEnabled,expanded=false,presentation}={}) {
16
+ const mode=presentation==='project'?'project':typeof characterLimitEnabled!=='boolean'?'unverified':!characterLimitEnabled?'unlimited':expanded?'expanded':'concise';
17
+ return {mode,footer:mode==='concise'?'Say expand for more detail once, or limit off to allow longer replies in this chat. Use limit on to bring back short replies.':null,
18
+ controls:mode==='project'?null:{expand:'One response; send expand as its own message.',off:'limit off',on:'limit on',status:'limit status'},
19
+ note:'Length preference only; workflow and evidence requirements remain. Unknown state is not a preference change.'};
20
+ }
@@ -12,6 +12,9 @@ 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
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';
15
18
  import { planRetention, retentionOf, prepareRetention, checkRetention, contextLocation, isComponentDoc, parseDoc } from './context-review.mjs';
16
19
  export { sourceSnapshot } from './source-snapshot.mjs';
17
20
 
@@ -44,7 +47,14 @@ export function atomicJSON(path, value) {
44
47
  mkdirSync(dirname(path), { recursive: true });
45
48
  const temp = `${path}.${randomUUID()}.tmp`;
46
49
  writeFileSync(temp, JSON.stringify(value, null, 2) + '\n', { mode: 0o600 });
47
- 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
+ }
48
58
  }
49
59
 
50
60
  // Resolve an existing ancestor and keep any missing suffix, so prospective files
@@ -390,7 +400,13 @@ function transact(root, id, work) {
390
400
  committing = true;
391
401
  atomicJSON(path, state);
392
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
+ }
393
408
  writeReview(root, state);
409
+ if (contextPublication) return { ...(result ?? {}), status: 'needs-context-sync', contextPublication };
394
410
  return result ?? state;
395
411
  } catch (error) {
396
412
  if (committing || ownership.inFlightBackup) {
@@ -880,6 +896,8 @@ function originalContent(root, state, path) {
880
896
  // Latin-1 preserves every byte; only an exact original hash permits this candidate.
881
897
  const crlf = Buffer.from(shown.stdout.toString('latin1').replace(/\r?\n/g, '\r\n'), 'latin1');
882
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;
883
901
  }
884
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.`);
885
903
  }
@@ -1213,11 +1231,13 @@ function declaredChecks(root) {
1213
1231
  return { source: commands.length > 1 ? `${found[0].source}, run as ${commands.map(command => command.id).join(', ')}` : found[0].source, commands };
1214
1232
  }
1215
1233
 
1216
- export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy, executionMode, conversationId, proofCommands, contextRetention }) {
1234
+ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy, executionMode, conversationId, proofCommands, contextRetention, taskContext: taskPolicy, delegation }) {
1217
1235
  root = realpathSync(root);
1218
1236
  if (!text(goal)) throw new Error('A nonempty goal is required.');
1219
1237
  const selected = getPlaybook(playbook ?? routeTask(goal).playbook);
1220
1238
  const config = configuration(root);
1239
+ const taskContextPolicy = taskPolicy === undefined ? undefined : contextPolicy(taskPolicy);
1240
+ const workerPolicy = delegation === undefined ? undefined : delegationPolicy(delegation);
1221
1241
  const declared = selected.requiresChecks && !config.commands.length ? declaredChecks(root) : null;
1222
1242
  const commands = declared?.commands ?? config.commands;
1223
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.'); }
@@ -1272,6 +1292,7 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1272
1292
  : { status: 'pending', cacheKey, inputs, sourceHash: initialSource.hash, requestedAt: new Date().toISOString() };
1273
1293
  const state = {
1274
1294
  schemaVersion: 1, engineVersion, id, goal, playbook: selected.id, stages: selected.stages, requiresChecks: selected.requiresChecks,
1295
+ ...(taskContextPolicy ? { taskContextPolicy } : {}), ...(workerPolicy ? { delegation: initializeDelegation(workerPolicy) } : {}),
1275
1296
  workContractVersion, contextRetention: retention, ...(evidenceVersion === 1 ? { evidenceVersion, reviewPolicy: reviewPolicy ?? 'self-allowed', requirements: { text: requirements, sha256: digest(requirements) }, criteriaHash: digest(JSON.stringify(criteria)) } : {}), ...ledger,
1276
1297
  criteria, inferredCriteria, session: session ?? null, ...(execution ? { execution } : {}), status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1277
1298
  startedAt: new Date().toISOString(), limits: config.limits, commands, ...(declared ? { verificationSource: `declared by ${declared.source}` } : {}),
@@ -1388,9 +1409,18 @@ export function nextRun(root, id) {
1388
1409
  const state = readRun(root, id);
1389
1410
  const finishTemplate = finishing(state) && state.status === 'running' ? writeFinishTemplate(root, state) : null;
1390
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
+ }
1391
1418
  return {
1392
1419
  runId: state.id, engineVersion: state.engineVersion ?? 'unknown (legacy run)', status: state.status, goal: state.goal, playbook: state.playbook,
1393
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]))}}:{}) } } : {}),
1394
1424
  ...(retentionOf(state) ? { contextRetention: retentionOf(state), contextPreparation: state.contextPreparation ? { docs: state.contextPreparation.docs, status: state.contextPreparation.status } : null } : {}),
1395
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,
1396
1426
  stage: current(state), attempt: state.attempt, criteria: state.criteria,
@@ -1497,9 +1527,11 @@ function validatePacket(root, state, packet) {
1497
1527
  packet.artifacts = [...packet.artifacts, ...assessmentArtifacts.filter(item => !packet.artifacts.some(existing => existing.path === item.path))];
1498
1528
  }
1499
1529
  function requireVerification(root, state) {
1530
+ requireTaskReady(root, state);
1500
1531
  requireRetention(root, state);
1501
1532
  if (!state.requiresChecks) return;
1502
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.');
1503
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.');
1504
1536
  const snapshot = cachedSnapshot(root);
1505
1537
  if (snapshot.skipped.length) throw new Error('Executable verification cannot cover symlink dependencies; use a project without linked source.');
@@ -1586,6 +1618,7 @@ export function recordHandoff(root, packet) {
1586
1618
  return transact(root, packet.runId, state => {
1587
1619
  requireActive(state);
1588
1620
  if (!budget(state) || !guard(root, state)) return state;
1621
+ if (packet.status === 'passed') requireTaskReady(root, state);
1589
1622
  validatePacket(root, state, packet);
1590
1623
  if (packet.status === 'passed' && ['verify', 'deliver'].includes(current(state))) requireVerification(root, state);
1591
1624
  if (packet.status === 'passed' && current(state) === 'verify' && provable(state)) requireTestProof(root, state, packet.assessment?.testProof);
@@ -1599,7 +1632,7 @@ export function recordHandoff(root, packet) {
1599
1632
  }
1600
1633
  }
1601
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();
1602
- const entry = { ...packet, recordedAt: new Date().toISOString(), sourceHash: cachedSnapshot(root).hash };
1635
+ const entry = { ...packet, ...(state.taskContext ? { taskContext: { revision: state.taskContext.revision, hash: contextHash(state) } } : {}), recordedAt: new Date().toISOString(), sourceHash: cachedSnapshot(root).hash };
1603
1636
  state.handoffs.push(entry);
1604
1637
  log(state, 'handoff', { stage: packet.stage, status: packet.status, summary: packet.summary });
1605
1638
  if (packet.status === 'blocked') { state.status = 'blocked'; log(state, 'blocked', { reason: packet.nextAction ?? packet.summary }); }
@@ -1612,6 +1645,7 @@ export function recordHandoff(root, packet) {
1612
1645
  export function verifyRun(root, id) {
1613
1646
  return transact(root, id, state => {
1614
1647
  requireActive(state);
1648
+ requireTaskReady(root, state);
1615
1649
  if (!budget(state) || !guard(root, state)) return state;
1616
1650
  const retained = checkRetention(root, state, cachedSnapshot(root).files);
1617
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.' } }; }
@@ -1621,7 +1655,7 @@ export function verifyRun(root, id) {
1621
1655
  // A stale cached hash here can only make the check look unstable; the full snapshot after it decides.
1622
1656
  const before = sourceSnapshot(root);
1623
1657
  const inputsBefore = measurementInputs(root, state.commands);
1624
- if (state.verification?.passed && state.verification.reusable === true && state.verification.role === 'candidate' && before.hash === state.verification.sourceHash && inputsBefore.suitable && state.verification.inputs?.key === inputsBefore.key) {
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) {
1625
1659
  assertArtifacts(root, [{ path: state.verification.receiptPath, sha256: state.verification.receiptHash }]);
1626
1660
  log(state, 'verification-reused', { receipt: state.verification.receiptPath, sourceHash: before.hash });
1627
1661
  return { runId: id, status: state.status, ...state.verification, reused: true };
@@ -1694,9 +1728,9 @@ export function verifyRun(root, id) {
1694
1728
  const awaitingAcceptance = !passed && !state.awaitedAcceptance && failedAtRunStart.length > 0 && results.every(excusable) && before.hash === after.hash
1695
1729
  && results.some(result => result.passed || (testsOf(result)?.passingCount ?? 0) > 0);
1696
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 };
1697
- Object.assign(receipt, { role: 'candidate', inputs: inputsAfter, inputsStable: inputsBefore.bounded && inputsAfter.bounded ? inputsBefore.key === inputsAfter.key : null, reusable: passed && inputsBefore.suitable && inputsAfter.suitable });
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 });
1698
1732
  // Every command reads and writes the run state, so test summaries of long output stay in the receipt file.
1699
- 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) };
1700
1734
  const receiptPath = `.cyc/runs/${id}/checks/${randomUUID()}.json`;
1701
1735
  atomicJSON(projectFile(root, receiptPath), receipt);
1702
1736
  state.verification.receiptPath = receiptPath;
@@ -1925,6 +1959,7 @@ function needsProofReview(root, state, input, steps) {
1925
1959
  export function finishRun(root, id, { summary, artifacts, passedEvidence, criterionEvidence, assessment = {}, acceptFailures = [], scenarioEvidence, continuation }) {
1926
1960
  let state = readRun(root, id);
1927
1961
  assertRunOwner(root, state);
1962
+ requireTaskReady(root, state);
1928
1963
  if (current(state) === null && ['running', 'complete'].includes(state.status)) {
1929
1964
  const delivery = state.handoffs.at(-1);
1930
1965
  if (delivery?.stage !== 'deliver' || delivery.status !== 'passed') throw new Error('No confirmed delivery to resume.');
@@ -2247,3 +2282,131 @@ function bindEvidence(root, state, packet) {
2247
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.`;
2248
2283
  }
2249
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
+ }