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
@@ -0,0 +1,51 @@
1
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
2
+ import { relative, resolve, isAbsolute, sep } from 'node:path';
3
+ import { digest } from './response-gate.mjs';
4
+
5
+ export const executionModes = ['native-codex', 'native-claude', 'cursor', 'standalone'];
6
+ export const conversationIdentity = (env = process.env) => [env.CYC_SESSION, env.CLAUDE_CODE_SESSION_ID, env.CODEX_THREAD_ID].find(v => /^[A-Za-z0-9_-]{4,80}$/.test(v ?? ''));
7
+ function setup(message) {
8
+ const error = new Error(message);
9
+ error.setup = { action: 'select-execution', modes: executionModes, instruction: 'Supply executionMode (CLI --mode) and the real conversationId when known; standalone is explicit no-hook work and cannot downgrade a live native request.' };
10
+ throw error;
11
+ }
12
+ export function resolveExecution(root, { executionMode, conversationId, session } = {}, env = process.env) {
13
+ if (executionMode !== undefined && !executionModes.includes(executionMode)) setup(`Unknown executionMode ${executionMode}.`);
14
+ const caller = conversationIdentity(env);
15
+ for (const value of [conversationId, session]) if (value !== undefined && !/^[A-Za-z0-9_-]{4,80}$/.test(value)) setup('Session must be 4-80 letters, digits, underscores or dashes; conversationId uses the same safe identity shape.');
16
+ const native = id => {
17
+ if (!id) return null;
18
+ for (const host of ['codex', 'claude', 'cursor']) {
19
+ const key = /^[a-f0-9]{32}$/.test(id) ? id : digest(`${host}:${id}`).slice(0, 32);
20
+ const path = resolve(root, '.cyc/runtime', `${key}.state.json`);
21
+ if (existsSync(path)) {
22
+ const state = JSON.parse(readFileSync(path, 'utf8').replace(/^\uFEFF/, ''));
23
+ const observedHost = state.host ?? state.activation?.host;
24
+ if (observedHost && observedHost !== host) continue;
25
+ return { mode: host === 'cursor' ? 'cursor' : `native-${host}`, gateSession: key };
26
+ }
27
+ }
28
+ return null;
29
+ };
30
+ const active = native(caller);
31
+ if (active && executionMode && executionMode !== active.mode) setup(`Active ${active.mode} request cannot use ${executionMode}.`);
32
+ if (active && conversationId && conversationId !== caller && native(conversationId)?.gateSession !== active.gateSession) setup('conversationId does not identify the active native request.');
33
+ const identity = conversationId ?? caller;
34
+ const observed = active ?? native(conversationId) ?? native(session) ?? native(caller);
35
+ if (observed && executionMode === 'standalone') setup(`Active ${observed.mode} context cannot use standalone.`);
36
+ const mode = executionMode ?? observed?.mode;
37
+ if (!mode) setup(/^[a-f0-9]{32}$/.test(session ?? '') ? `No hook state for session ${session}. Provide the current native context or choose an explicitly authorized execution mode.` : 'Execution capability is unknown; choose --mode standalone for explicitly authorized no-hook work, or provide the current native context.');
38
+ if (mode.startsWith('native-') && (!observed || observed.mode !== mode)) setup(`${mode} needs current native hook state for the supplied conversationId/session. Reload the host and use its injected context.`);
39
+ return { mode, conversationId: identity ?? null, workflowSession: session ?? null, gateSession: observed?.gateSession ?? null, hookActivation: 'unverified' };
40
+ }
41
+ export function artifactFiles(root, paths, label = 'Artifact') {
42
+ return paths.map(path => {
43
+ if (typeof path !== 'string' || !path) throw new Error(`${label} needs a regular-file path.`);
44
+ const absolute = resolve(root, path), realRoot = realpathSync(root);
45
+ const inside = target => { const rel = relative(realRoot, target); return rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel); };
46
+ if (!inside(absolute)) throw new Error(`${label} leaves project: ${path}`);
47
+ const info = lstatSync(absolute);
48
+ if (!info.isFile() || !inside(realpathSync(absolute))) throw new Error(`${label} ${path} must be a regular file; directories are not expanded. List concrete files individually.`);
49
+ return { path, sha256: digest(readFileSync(absolute)) };
50
+ });
51
+ }
@@ -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
  }
@@ -3,16 +3,20 @@ import { randomUUID } from 'node:crypto';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { checkPacket, checkResponse, digest, normalize } from './response-gate.mjs';
5
5
  import { advisoryReason, blockingRuns, checkRuns, validateRequestWindow } from './run-gate.mjs';
6
+ import { resolveExecution, artifactFiles } from './execution.mjs';
6
7
 
7
8
  // Write the delivery review packet for this session and run the same check the Stop hook runs,
8
9
  // so a review that would be bounced is caught before the turn ends. The token comes from the
9
10
  // session's own hook state; the agent never copies it. Claude and Codex Stop events carry the
10
11
  // final reply, so the reply file is optional there: without it the gate checks the reply itself.
11
- export function writePacket(root, { session, responseFile, status, blocker, advisory, passed = [], unmet = [], artifacts = [], reviewed = false }) {
12
+ export function writePacket(root, { session, executionMode, conversationId, responseFile, status, blocker, advisory, passed = [], unmet = [], artifacts = [], reviewed = false }) {
12
13
  if (!session) throw new Error('--session is required: use the CYC session ID from the gate context (Cursor: your session tag).');
13
14
  if (status !== undefined && !['ready', 'blocked'].includes(status)) throw new Error('--status must be ready or blocked.');
14
15
  const runtime = resolve(root, '.cyc/runtime');
15
- const cursor = !/^[a-f0-9]{32}$/.test(session);
16
+ const execution = resolveExecution(root, { executionMode, conversationId, session });
17
+ if (execution.mode === 'standalone') throw new Error('Standalone delivery is generated by run finish; use --run ID and its delivery record instead of a native packet.');
18
+ const cursor = execution.mode === 'cursor';
19
+ if (!cursor) session = execution.gateSession;
16
20
  if (cursor && !/^[a-z0-9-]{4,40}$/.test(session)) throw new Error('Session must be the 32-character CYC session ID or a Cursor tag of 4-40 lowercase letters, digits, or hyphens.');
17
21
  // Under project presentation the Stop hook skips CYC's reply checks, so this does too.
18
22
  // Cursor still needs the exact reply to find its session's packet.
@@ -40,6 +44,8 @@ export function writePacket(root, { session, responseFile, status, blocker, advi
40
44
  if (!criterion?.trim() || !rest.join('::').trim()) throw new Error(`Check "${entry}" must be "criterion :: evidence".`);
41
45
  return { criterion: criterion.trim(), result, evidence: rest.join('::').trim() };
42
46
  });
47
+ const files = artifactFiles(root, artifacts);
48
+ if (responseFile) artifactFiles(root, [responseFile], 'Response file');
43
49
  const response = responseFile ? normalize(readFileSync(resolve(root, responseFile), 'utf8')) : undefined;
44
50
  // Without an explicit status the controller's record decides: a run of this request that ended
45
51
  // short of complete makes this a blocked handoff, as does a blocker the agent names.
@@ -52,7 +58,7 @@ export function writePacket(root, { session, responseFile, status, blocker, advi
52
58
  ...(advisory !== undefined ? { advisory: advisory.trim() } : {}),
53
59
  checks: [...parse(passed, 'passed'), ...parse(unmet, 'unmet')],
54
60
  ...(reviewed ? { humanReview: { answersRequest: true, understandable: true, visualAddsInformation: true, limitationsDisclosed: true }, reviewedAt: new Date().toISOString() } : {}),
55
- artifacts: artifacts.map(path => ({ path, sha256: digest(readFileSync(resolve(root, path))) }))
61
+ artifacts: files
56
62
  };
57
63
  const path = resolve(runtime, cursor ? `cursor-${session}.review.json` : `${session}.review.json`);
58
64
  publish(path, packet);
@@ -80,7 +86,16 @@ function publish(path, packet) {
80
86
  // completed in this request. Cursor finds its packet by the exact reply, so it still uses cyc packet.
81
87
  // recorded(packet): whether the run the packet names recorded exactly this packet. An earlier packet
82
88
  // is merged only then, so a hand-written one cannot ride along with a genuine finish.
83
- export function writeRunPacket(root, { session, runId, checks, artifacts, recorded = () => false }) {
89
+ export function writeRunPacket(root, { session, execution, evidence, runId, checks, artifacts, recorded = () => false }) {
90
+ const files = artifactFiles(root, artifacts);
91
+ if (execution?.mode === 'cursor') return { written: false, reason: `Cursor requires the exact reply: packet --mode cursor --session ${execution.workflowSession ?? session} --response FILE --reviewed.` };
92
+ if (execution?.mode === 'standalone') {
93
+ resolveExecution(root, { executionMode: 'standalone', conversationId: execution.conversationId ?? undefined, session: execution.workflowSession ?? undefined });
94
+ const packet = { version: 1, runId, execution, status: 'complete', checks, ...(evidence ? { evidence } : {}), artifacts: files, provenance: 'recorded-workflow-evidence', hookActivation: 'unverified', productReadiness: 'not-certified', writtenAt: new Date().toISOString() };
95
+ const path = `.cyc/runs/${runId}/delivery.json`;
96
+ publish(resolve(root, path), packet);
97
+ return { written: true, path, digest: runPacketDigest(packet), mode: 'standalone', reply: 'Standalone delivery evidence generated. No native packet or hook activation is claimed.' };
98
+ }
84
99
  if (!/^[a-f0-9]{32}$/.test(session ?? '')) return { written: false, reason: 'This run has no Claude Code or Codex session; write the review with cyc packet.' };
85
100
  const statePath = resolve(root, '.cyc/runtime', `${session}.state.json`);
86
101
  if (!existsSync(statePath)) return { written: false, reason: `No hook state for session ${session}; write the review with cyc packet.` };
@@ -90,11 +105,11 @@ export function writeRunPacket(root, { session, runId, checks, artifacts, record
90
105
  let earlier = null;
91
106
  try { earlier = JSON.parse(readFileSync(path, 'utf8')); } catch { /* none yet */ }
92
107
  const kept = earlier?.token === token && earlier.writtenBy === 'run finish' && recorded(earlier) ? earlier : null;
93
- const files = artifacts.filter(file => { try { return statSync(resolve(root, file)).isFile(); } catch { return false; } });
94
108
  const packet = {
95
109
  token, status: 'ready', writtenBy: 'run finish', runId, runIds: [...new Set([...(kept?.runIds ?? []), runId])],
110
+ ...(evidence ? { evidence } : {}),
96
111
  checks: [...(kept?.checks ?? []).filter(check => !checks.some(item => item.criterion === check.criterion)), ...checks],
97
- artifacts: [...(kept?.artifacts ?? []).filter(item => !files.includes(item.path)), ...files.map(file => ({ path: file, sha256: digest(readFileSync(resolve(root, file))) }))],
112
+ artifacts: [...(kept?.artifacts ?? []).filter(item => !files.some(file => file.path === item.path)), ...files],
98
113
  writtenAt: new Date().toISOString()
99
114
  };
100
115
  publish(path, packet);
@@ -4,6 +4,8 @@ import { fileURLToPath } from 'node:url';
4
4
  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
+ import { runBrowserAudit, validateBrowserPlan } from './browser-audit.mjs';
8
+ import { canonicalPattern, matches, contextLocation, parseDoc } from './context-review.mjs';
7
9
 
8
10
  const registryName = 'docs/context/recipes.json';
9
11
  const indexName = 'docs/context/INDEX.md';
@@ -14,8 +16,7 @@ const idPattern = /^[a-z][a-z0-9-]{0,63}$/;
14
16
  const recipeKinds = ['investigation', 'verification'];
15
17
 
16
18
  function canonical(path, patterns = false) {
17
- if (!text(path) || /[\\:\0]/.test(path) || (!patterns && /[*?\[\]{}]/.test(path)) || /[\[\]{}]/.test(path) || path.split('/').some(p => !p || p === '.' || p === '..')) throw Error(`Use canonical project-relative ${patterns ? 'patterns' : 'paths'}: ${path}`);
18
- return path;
19
+ return canonicalPattern(path, { patterns });
19
20
  }
20
21
 
21
22
  // Reject linked ancestors even inside the project: receipts must remain excluded
@@ -31,19 +32,6 @@ function local(root, path) {
31
32
  return current;
32
33
  }
33
34
 
34
- function matches(pattern, path) {
35
- canonical(pattern, true); canonical(path);
36
- let regex = '';
37
- for (let i = 0; i < pattern.length; i++) {
38
- if (pattern[i] === '*' && pattern[i + 1] === '*') { i++; if (pattern[i + 1] === '/') { i++; regex += '(?:.*/)?'; } else regex += '.*'; }
39
- else if (pattern[i] === '*') regex += '[^/]*';
40
- else if (pattern[i] === '?') regex += '[^/]';
41
- else regex += pattern[i].replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
42
- }
43
- const prefix = pattern.split(/[?*]/)[0].replace(/\/$/, '');
44
- return new RegExp(`^${regex}$`).test(path) || (prefix && (prefix === path || prefix.startsWith(path + '/'))) || (!/[?*]/.test(pattern) && path.startsWith(pattern + '/'));
45
- }
46
-
47
35
  function selection(root, { paths = [], goal = '', run } = {}) {
48
36
  if (!Array.isArray(paths)) throw Error('Paths must be an array.');
49
37
  if (run) {
@@ -58,7 +46,7 @@ function selection(root, { paths = [], goal = '', run } = {}) {
58
46
  }
59
47
  paths = [...new Set(paths.map(p => canonical(p)))];
60
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)) ?? [];
61
- 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)) };
62
50
  }
63
51
 
64
52
  function registry(root) {
@@ -72,6 +60,7 @@ function registry(root) {
72
60
  ids.add(recipe.id);
73
61
  if (recipe.command.includes('\0') || recipe.args.some(arg => arg.includes('\0'))) throw Error('Recipe command/args cannot contain null bytes.');
74
62
  recipe.covers.forEach(p => canonical(p, true));
63
+ if (recipe.browser !== undefined) { validateBrowserPlan(recipe.browser); recipe.browser.prerequisiteFiles.forEach(p => canonical(p)); }
75
64
  for (const name of recipe.references) if (!lstatSync(local(root, name)).isFile()) throw Error(`Recipe reference is not a regular file: ${name}`);
76
65
  if (recipe.timeoutMs !== undefined && (!Number.isSafeInteger(recipe.timeoutMs) || recipe.timeoutMs <= 0 || recipe.timeoutMs > 2147483647)) throw Error('Recipe timeoutMs must be between 1 and 2147483647.');
77
66
  }
@@ -89,6 +78,7 @@ function receiptStatus(root, recipe, loaded, environment) {
89
78
  const result = receipt.results?.[0];
90
79
  const current = environment();
91
80
  if (receipt.schemaVersion !== 1 || receipt.recipeHash !== hash(JSON.stringify(recipe)) || receipt.registryHash !== loaded.hash || receipt.sourceHash !== current.sourceHash || receipt.configHash !== current.configHash) return { status: 'stale', receiptPath };
81
+ if (recipe.browser) return { status: receipt.passed && receipt.browser?.status === 'passed' && receipt.sourceStable && receipt.definitionStable && receipt.configStable ? 'passed' : receipt.browser?.status ?? 'failed', receiptPath, checkedAt: receipt.checkedAt };
92
82
  const passed = receipt.passed === true && receipt.sourceStable === true && receipt.definitionStable === true && receipt.configStable === true && receipt.results.length === 1 && result.id === recipe.id && result.command === recipe.command && JSON.stringify(result.args) === JSON.stringify(recipe.args) && result.passed === true && result.exitCode === 0 && !result.error;
93
83
  return { status: passed ? 'passed' : 'failed', receiptPath, checkedAt: receipt.checkedAt };
94
84
  } catch { return { status: 'invalid', receiptPath }; }
@@ -128,7 +118,27 @@ export function contextLinks(cell) {
128
118
  }).filter(Boolean);
129
119
  }
130
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
+
131
140
  export function investigateProject(target, options = {}) {
141
+ const { index: indexName } = contextLocation(realpathSync(target));
132
142
  validateRecipeKind(options.kind);
133
143
  const root = realpathSync(target), selected = selection(root, options), limit = options.limit ?? 8;
134
144
  if (!Number.isSafeInteger(limit) || limit < 1 || limit > 50) throw Error('Limit must be between 1 and 50.');
@@ -150,12 +160,14 @@ export function investigateProject(target, options = {}) {
150
160
  try {
151
161
  covers.forEach(p => canonical(p === 'all' ? '**' : p, true));
152
162
  if (!selected.relevant(covers.map(p => p === 'all' ? '**' : p), cells.join(' '))) continue;
153
- 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')]) : [] });
154
166
  } catch (error) { warnings.push(error.message); }
155
167
  }
156
168
  }
157
- const evidenceChecks = new Map();
158
- 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 => {
159
171
  if (!e.exists || !e.path.endsWith('.json')) return e;
160
172
  if (!evidenceChecks.has(e.path)) {
161
173
  const checked = spawnSync(process.execPath, [helper, 'check', '--project', root, '--manifest', e.path], { encoding: 'utf8', windowsHide: true, timeout: 10000, maxBuffer: 1024 * 1024 });
@@ -172,10 +184,21 @@ export function investigateProject(target, options = {}) {
172
184
  note: 'Paths and records are leads, not an exhaustive dependency map. Read matched records and inspect current consumers. Matching bytes do not establish semantic correctness. Project commands were not executed.' };
173
185
  }
174
186
 
175
- export function runRecipe(target, id, { run } = {}) {
187
+ export function runRecipe(target, id, { run, driver, scanner, signal } = {}) {
176
188
  const root = realpathSync(target), loaded = registry(root), recipe = loaded.recipes.find(r => r.id === id);
177
189
  if (!recipe) throw Error(`Unknown recipe: ${id}`);
178
190
  if (run && readRun(root, run).status !== 'running') throw Error('Recipe execution associated with a run needs that run to be running.');
191
+ if (recipe.browser) {
192
+ const before = sourceSnapshot(root), configBefore = configHash(root);
193
+ return runBrowserAudit(root, recipe.browser, { driver, scanner, signal }).then(browser => {
194
+ const after = sourceSnapshot(root), configAfter = configHash(root), definitionStable = registry(root).hash === loaded.hash;
195
+ const receipt = { schemaVersion: 1, recipe: id, kind: recipe.kind, runId: run ?? null, checkedAt: new Date().toISOString(), registryHash: loaded.hash, recipeHash: hash(JSON.stringify(recipe)), sourceHash: after.hash, configHash: configAfter, sourceStable: before.hash === after.hash, definitionStable, configStable: configBefore === configAfter, browser };
196
+ receipt.passed = browser.ok && receipt.sourceStable && definitionStable && receipt.configStable;
197
+ const receiptPath = `.cyc/runtime/recipes/${id}/${Date.now()}-${randomUUID()}.json`;
198
+ atomicJSON(local(root, receiptPath), receipt);
199
+ return { ...browser, ok: receipt.passed, recipe: id, receiptPath, expected: recipe.expected, note: 'Named external browser/scanner observations; no command receipt or native activation is inferred.' };
200
+ });
201
+ }
179
202
  local(root, `.cyc/runtime/recipes/${id}`); // Validate receipt ancestors before execution.
180
203
  const before = sourceSnapshot(root), configBefore = configHash(root);
181
204
  if (before.skipped.length) throw Error('Recipe verification cannot cover linked source; inspect the links first.');
@@ -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
+ }
@@ -0,0 +1,4 @@
1
+ // Same isolated worker pattern as baseline-worker; owns the existing controller operations.
2
+ import { executeOperation } from './runtime.mjs';
3
+ const [root, id, operationId] = process.argv.slice(2);
4
+ if (root && id && operationId) executeOperation(root, id, operationId);