cyc-stack 0.9.1 → 0.11.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 (48) 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 +3 -2
  5. package/bin/cyc.mjs +72 -20
  6. package/docs/README.md +2 -0
  7. package/docs/context.md +18 -10
  8. package/docs/project-tools.md +2 -12
  9. package/docs/runtime.md +5 -1
  10. package/docs/work-assessments.md +4 -4
  11. package/docs/work-queue.md +187 -0
  12. package/methods/cyc-build/SKILL.md +1 -1
  13. package/methods/cyc-context/SKILL.md +28 -20
  14. package/methods/cyc-context/references/evidence.md +1 -1
  15. package/methods/cyc-context/references/templates.md +30 -18
  16. package/methods/cyc-design/frontend-design/SKILL.md +132 -21
  17. package/methods/cyc-design/frontend-design/references/color.md +43 -56
  18. package/methods/cyc-design/frontend-design/references/craft-rules.md +17 -14
  19. package/methods/cyc-design/frontend-design/references/decision-sheet.md +95 -93
  20. package/methods/cyc-design/frontend-design/references/experience-review.md +15 -6
  21. package/methods/cyc-design/frontend-design/references/field-guide.md +439 -0
  22. package/methods/cyc-design/frontend-design/references/generic-tells.md +83 -32
  23. package/methods/cyc-design/frontend-design/references/layout-archetypes.md +5 -5
  24. package/methods/cyc-design/frontend-design/references/patterns.md +108 -0
  25. package/methods/cyc-design/frontend-design/references/reference-standards.md +118 -22
  26. package/methods/cyc-design/frontend-design/references/typography.md +59 -44
  27. package/methods/cyc-design/frontend-design/references/ux-foundations.md +2 -1
  28. package/methods/cyc-design/frontend-design/references/visual-material.md +43 -8
  29. package/methods/cyc-design/frontend-design/scripts/contrast.mjs +39 -0
  30. package/methods/cyc-design/frontend-design/scripts/first-screen.mjs +911 -0
  31. package/methods/cyc-design/frontend-design/scripts/photo-text.mjs +230 -0
  32. package/methods/cyc-verify/SKILL.md +1 -1
  33. package/package.json +6 -1
  34. package/plugin.json +1 -1
  35. package/scripts/catalog.mjs +5 -3
  36. package/scripts/context-review.mjs +364 -261
  37. package/scripts/hub-page.mjs +275 -0
  38. package/scripts/hub.mjs +139 -0
  39. package/scripts/project-tools.mjs +14 -6
  40. package/scripts/queue-board.mjs +287 -0
  41. package/scripts/queue.mjs +283 -0
  42. package/scripts/run-gate.mjs +8 -5
  43. package/scripts/runtime.mjs +270 -19
  44. package/scripts/source-snapshot.mjs +20 -2
  45. package/scripts/work-review.mjs +4 -3
  46. package/skills/cyc/SKILL.md +12 -4
  47. package/skills/cyc/references/playbooks/experience.md +2 -0
  48. package/skills/cyc/references/playbooks/plan.md +2 -0
@@ -2,7 +2,7 @@ import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync } from '
2
2
  import { dirname, relative, resolve, sep } from 'node:path';
3
3
  import { spawnSync } from 'node:child_process';
4
4
  import { digest } from './response-gate.mjs';
5
- import { controllerPath, sourceSnapshot } from './source-snapshot.mjs';
5
+ import { controllerPath, recordMatcher, sourceSnapshot } from './source-snapshot.mjs';
6
6
 
7
7
  // Connects the delivery gate to controller runs. A run counts only if this session owns it
8
8
  // (or it is an unowned legacy run) and it was touched during the current request, so parallel
@@ -79,8 +79,10 @@ export function changeFingerprint(root, { deadlineMs = changeCheckDeadlineMs } =
79
79
  else if (entry.startsWith('u ')) tracked.push(entry.split(' ').slice(10).join(' '));
80
80
  else if (entry.startsWith('? ')) untracked.push(entry.slice(2));
81
81
  }
82
- // Porcelain paths are relative to the repository root, not to this project.
83
- const local = paths => paths.map(path => [projectPath(root, top, path), resolve(top, path)]).filter(([path]) => !controllerPath(path));
82
+ // Porcelain paths are relative to the repository root, not to this project. Controller bookkeeping
83
+ // and published change records are not project edits.
84
+ const record = recordMatcher(root);
85
+ const local = paths => paths.map(path => [projectPath(root, top, path), resolve(top, path)]).filter(([path]) => !controllerPath(path) && !record(path));
84
86
  const files = {};
85
87
  for (const [path, absolute] of local(tracked)) {
86
88
  if (Date.now() > deadline) return unavailable('hashing the changed files');
@@ -104,7 +106,8 @@ function committedPaths(root, from, to) {
104
106
  ? git(root, ['ls-tree', '-r', '-z', '--name-only', '--full-name', to, '--', '.'])
105
107
  : git(root, ['diff', '--no-relative', '--name-only', '-z', from, to, '--', '.']);
106
108
  if (result.status !== 0) return [`commits ${from.slice(0, 7)}..${to.slice(0, 7)}`];
107
- return result.stdout.split('\0').filter(Boolean).map(path => projectPath(root, top, path)).filter(path => !controllerPath(path));
109
+ const record = recordMatcher(root);
110
+ return result.stdout.split('\0').filter(Boolean).map(path => projectPath(root, top, path)).filter(path => !controllerPath(path) && !record(path));
108
111
  }
109
112
 
110
113
  function changedPaths(root, before, after) {
@@ -186,7 +189,7 @@ const unfinished = (run, now) => run.status !== 'complete' && !(run.status === '
186
189
  const endedAs = run => run.status === 'running' ? 'past its time budget' : run.status;
187
190
  // Why a run stopped, in the controller's record: the reason and files logged by the latest status
188
191
  // change. Pause and stop log no reason, and a resume clears an earlier one.
189
- function stopReason(run) {
192
+ export function stopReason(run) {
190
193
  const event = run.history?.findLast(item => ['blocked', 'guard-halt', 'exhausted', 'pause', 'stop', 'resume'].includes(item.type));
191
194
  if (!event || event.type === 'resume') return null;
192
195
  const files = [...(event?.protectedChanges ?? []), ...(event?.outOfScope ?? [])];
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, unlinkSync, writeFileSync } from 'node:fs';
2
+ import { appendFileSync, closeSync, existsSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
3
3
  import { dirname, isAbsolute, relative, resolve, sep } from 'node:path';
4
4
  import { spawn, spawnSync } from 'node:child_process';
5
5
  import { fileURLToPath } from 'node:url';
@@ -15,7 +15,9 @@ import { artifactFiles, resolveExecution } from './execution.mjs';
15
15
  import { strictObject, contextPolicy, initializeContext, contextView, contextHash, contextPath, checkContextSize, checkProjection, publishContext, acknowledgeContext, requireContextReady, reconcileContext, touchContext } from './task-context.mjs';
16
16
  import { delegationPolicy, initializeDelegation, decideDelegation, assignWorker, recordWorker, cancelWorker, reconcileWorkers } from './delegation.mjs';
17
17
  import {startSwarm,swarmPhase,applySwarmPlan,assignSwarm,commitSwarm,cancelSwarm} from './swarm.mjs';
18
- import { planRetention, retentionOf, prepareRetention, checkRetention, contextLocation, isComponentDoc, parseDoc } from './context-review.mjs';
18
+ import { planRetention, retentionOf, prepareRetention, checkRetention, contextLocation, isComponentDoc, parseDoc, publishChange } from './context-review.mjs';
19
+ import { queueFolder, queuePath, createQueue, queueStatus, queueNext, decideQueue, bindUnit, noteStart, dropStart, queueAdvice, lineOf } from './queue.mjs';
20
+ import { postMessage, deliver, callerKeys, boardHolds, hasBoard, boardSummary, assumptions, readBoard, seatView, takeSeat, releaseSeat, boardReview } from './queue-board.mjs';
19
21
  export { sourceSnapshot } from './source-snapshot.mjs';
20
22
 
21
23
  const text = value => typeof value === 'string' && value.trim().length > 0;
@@ -1112,19 +1114,39 @@ export function proveRun(root, id, { tests, measureOriginal = false } = {}) {
1112
1114
  return [...now.failing].filter(([key, entry]) => entry.count > (then.failing.get(key)?.count ?? 0) && inChangedTests(entry.file)
1113
1115
  && !old.some(item => item.file === entry.file && item.leaf === entry.leaf)).map(([, entry]) => entry.path.join(' > '));
1114
1116
  };
1115
- const named = mode === 'red' ? added ?? Object.fromEntries(treatment.map(result => [result.id, newlyFailing(result)]).filter(([, names]) => names.length)) : {};
1117
+ // A control can also fail without running a test. A proof command that names only test files
1118
+ // this change adds finds no file on the run-start code, and the runner exits non-zero for want
1119
+ // of one. That exit says nothing about the code, so it is read as nothing to run, not as an
1120
+ // earlier failure, when the control printed no test results at all and every failing test with
1121
+ // the new tests added is in a test file this change added: those tests did not exist at run
1122
+ // start. Excluded: a change that deletes or moves a test file, because a test that already
1123
+ // failed at its old path would look new; a control that timed out or could not start; and a
1124
+ // control whose output was cut off, which may have lost its results. Maps such a check to its
1125
+ // failing tests (testsOf gives none for a treatment whose results are incomplete).
1126
+ const addedTestFiles = testFiles.filter(path => originals.get(path) === null && currentBytes.get(path) !== null);
1127
+ const nothingToRun = Object.fromEntries(mode === 'red' && control && !testsDeleted ? treatment.flatMap(result => {
1128
+ const before = control.find(item => item.id === result.id);
1129
+ if (result.passed || !before || before.passed || before.errorCode || cutOff(before) || testsOf(before)) return [];
1130
+ const entries = [...(testsOf(result)?.failing.values() ?? [])];
1131
+ return entries.length && entries.every(entry => addedTestFiles.includes(projectRelative(entry.file))) ? [[result.id, entries]] : [];
1132
+ }) : []);
1133
+ const named = mode === 'red' ? added ?? Object.fromEntries(treatment.map(result => [result.id, nothingToRun[result.id]?.map(entry => entry.path.join(' > ')) ?? newlyFailing(result)]).filter(([, names]) => names.length)) : {};
1116
1134
  const caught = mode === 'red' ? added ? Object.keys(added) : treatment.filter(result => !result.passed && (control.find(item => item.id === result.id)?.passed || named[result.id])).map(result => result.id) : [];
1117
1135
  const passed = mode === 'red' ? caught.length > 0 : treatment.every(result => result.passed);
1118
1136
  const alreadyFailing = mode === 'red' && treatment.some(result => !result.passed) && !caught.length;
1119
1137
  const failingNames = caught.flatMap(check => named[check] ?? []);
1120
1138
  const listed = failingNames.length ? `${failingNames.slice(0, 5).join('; ')}${failingNames.length > 5 ? `; and ${failingNames.length - 5} more` : ''}` : null;
1121
- const preexisting = added ? [] : caught.filter(check => !control.find(item => item.id === check)?.passed);
1139
+ const preexisting = added ? [] : caught.filter(check => !nothingToRun[check] && !control.find(item => item.id === check)?.passed);
1140
+ const ranNothing = Object.keys(nothingToRun).length ? ` On the run-start code alone, check ${Object.keys(nothingToRun).join(', ')} printed no test results, so no test failed there before and its exit is read as nothing to run; why it exited non-zero was not examined. Its failing tests with the new tests added are all in test files this change added.` : '';
1141
+ // A control that printed no test results and still could not be read as nothing to run: say what would settle it.
1142
+ const unread = alreadyFailing ? treatment.filter(result => { const before = control.find(item => item.id === result.id); return !result.passed && before && !before.passed && !before.errorCode && !cutOff(before) && !testsOf(before); }).map(result => result.id) : [];
1143
+ const unreadHint = unread.length ? ` On the run-start code alone, check ${unread.join(', ')} printed no test results the proof can read. That is read as nothing to run only when every failing test with the new tests added is named and is in a test file this change added, and no test file was deleted or moved (TAP, Jest or Mocha output; for node, --test-reporter=tap).` : '';
1122
1144
  const verdict = mode === 'red'
1123
1145
  // State only what the proof shows. Agents repeat this sentence; "the new tests fail" was
1124
1146
  // reported as "every new test fails", which a check-level result cannot establish.
1125
- ? (passed ? listed ? `With the new tests added, these tests fail on the run-start code: ${listed} (check ${caught.join(', ')}).${preexisting.length ? ` Check ${preexisting.join(', ')} already failed there for other tests, which still fail and are not attributed to this change.` : ''} Other new tests pass there; they may guard existing behavior.`
1147
+ ? (passed ? listed ? `With the new tests added, these tests fail on the run-start code: ${listed} (check ${caught.join(', ')}).${preexisting.length ? ` Check ${preexisting.join(', ')} already failed there for other tests, which still fail and are not attributed to this change.` : ''} New tests not named here did not fail there; they may guard existing behavior.${ranNothing}`
1126
1148
  : `With the new tests added, check ${caught.join(', ')} fails on the run-start code, which otherwise passes it, so at least one new test catches this change. This does not show that every new test fails there; some may guard existing behavior. Report it as "at least one new test fails without the fix" unless you ran the tests individually.`
1127
- : alreadyFailing ? `Inconclusive: the run-start code already fails ${treatment.filter(result => !result.passed).map(result => result.id).join(', ')}, so the failure cannot be attributed to the new tests. The proof needs a check that passes on the run-start code, such as the test runner on its own.`
1149
+ : alreadyFailing ? `Inconclusive: the run-start code already fails ${treatment.filter(result => !result.passed).map(result => result.id).join(', ')}, so the failure cannot be attributed to the new tests. The proof needs a check that passes on the run-start code, such as the test runner on its own.${unreadHint}`
1128
1150
  : 'The new tests pass on the run-start code, so they would not catch a regression of this change. Strengthen them.')
1129
1151
  : (passed ? 'The tests pass on the run-start code, so they pin behavior the original already had.'
1130
1152
  : 'The tests fail on the run-start code, so they assert new behavior. A refactor must preserve behavior; fix the tests or reclassify the work.');
@@ -1155,7 +1177,7 @@ export function proveRun(root, id, { tests, measureOriginal = false } = {}) {
1155
1177
  });
1156
1178
  });
1157
1179
  const commandPlanHash = digest(JSON.stringify(proofCommands)), broadCommandsHash = digest(JSON.stringify(state.commands));
1158
- atomicJSON(projectFile(root, receiptPath), { mode, passed, verdict, claim, failures, roles: { treatment: 'original-plus-new-tests', control: control ? 'original-only' : 'not-executed', broadControl: broadControl ? 'original-only-broad' : 'not-executed' }, commandPlanHash, broadCommandsHash, focused: commandPlanHash !== broadCommandsHash, inputs: proofInputs, broadInputs, broadControl, ...(reusedTreatmentFrom ? { reusedTreatmentFrom } : {}), base: state.base?.commit ?? null, originalSourceHash: state.initialSource.hash, testFiles, sourceFiles, treatment, control, ...(controlSource ? { controlSource } : {}), checkedAt: new Date().toISOString() });
1180
+ atomicJSON(projectFile(root, receiptPath), { mode, passed, verdict, claim, failures, roles: { treatment: 'original-plus-new-tests', control: control ? 'original-only' : 'not-executed', broadControl: broadControl ? 'original-only-broad' : 'not-executed' }, commandPlanHash, broadCommandsHash, focused: commandPlanHash !== broadCommandsHash, inputs: proofInputs, broadInputs, broadControl, ...(reusedTreatmentFrom ? { reusedTreatmentFrom } : {}), base: state.base?.commit ?? null, originalSourceHash: state.initialSource.hash, testFiles, sourceFiles, treatment, control, ...(controlSource ? { controlSource } : {}), ...(Object.keys(nothingToRun).length ? { controlWithoutTests: Object.fromEntries(Object.entries(nothingToRun).map(([check, entries]) => [check, [...new Set(entries.map(entry => projectRelative(entry.file)))]])) } : {}), checkedAt: new Date().toISOString() });
1159
1181
  state.testProof = { mode, passed, verdict, claim, failures, commandPlanHash, inputs: proofInputs, testFiles: Object.fromEntries(testFiles.map(path => [path, before.files[path]])), sourceFiles, receiptPath, receiptHash: digest(readFileSync(projectFile(root, receiptPath))), checkedAt: new Date().toISOString() };
1160
1182
  log(state, 'test-proof', { mode, passed, receipt: receiptPath });
1161
1183
  return { runId: id, mode, passed, verdict, failures, ...(state.evidenceVersion === 1 && passed && mode === 'red' ? { proofReviewTemplate: { receipt: 'current-proof', cases: failures.map(f => ({ id: f.id, category: 'behavioral | new-interface | setup | unclassified', reason: '<why this failure establishes the selected category>', boundary: '' })) } } : {}), ...(claim ? { proofClaim: claim } : {}), testFiles, sourceFiles, treatment: summary(treatment), control: summary(control), receiptPath };
@@ -1231,7 +1253,7 @@ function declaredChecks(root) {
1231
1253
  return { source: commands.length > 1 ? `${found[0].source}, run as ${commands.map(command => command.id).join(', ')}` : found[0].source, commands };
1232
1254
  }
1233
1255
 
1234
- export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy, executionMode, conversationId, proofCommands, contextRetention, taskContext: taskPolicy, delegation }) {
1256
+ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], session, scout, plan, baselineMode = 'background', evidenceVersion, requirements, reviewPolicy, executionMode, conversationId, proofCommands, contextRetention, taskContext: taskPolicy, delegation, queue: binding }) {
1235
1257
  root = realpathSync(root);
1236
1258
  if (!text(goal)) throw new Error('A nonempty goal is required.');
1237
1259
  const selected = getPlaybook(playbook ?? routeTask(goal).playbook);
@@ -1259,6 +1281,8 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1259
1281
  // creates nothing and the agent fixes one file instead of repairing a half-started run.
1260
1282
  const workContractVersion = selected.stages.includes('build') ? 1 : null;
1261
1283
  allowedPaths = normalizePaths(root, allowedPaths, 'allowedPaths');
1284
+ // A queue unit limits what the agent asked for; the context docs added below are the controller's.
1285
+ const requestedPaths = allowedPaths;
1262
1286
  const retention = planRetention(root, { goal, build: !!workContractVersion, allowedPaths, explicit: contextRetention ?? scout?.context?.retention });
1263
1287
  const contextScope = retention.disposition === 'required' ? [retention.index, ...retention.features.map(f => f.doc)] : [];
1264
1288
  const protectedContext = contextScope.filter(path => protectedPathMatcher(root, config.protectedPaths)(path));
@@ -1276,6 +1300,8 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1276
1300
  if (protectedPath(`.cyc/runs/${id}`)) throw new Error('Run storage is protected; error history and original-source capture cannot be written.');
1277
1301
  const mode = process.env.CYC_BASELINE_MODE ?? baselineMode;
1278
1302
  const state = withWorkspaceLock(root, `start run ${id}`, config.protectedPaths, () => {
1303
+ // The start rules of a queue unit are checked under the lock, before anything is written.
1304
+ const bound = binding === undefined ? null : bindUnit(queueIO(root), binding, { playbook: selected.id, criteria, inferredCriteria, allowedPaths: requestedPaths });
1279
1305
  const ledger = selectLedger(root, id, config, allowedPaths, protectedPath);
1280
1306
  const { snapshot: initialSource, recoverableTracked } = inspectSource(root);
1281
1307
  const base = gitBase(root);
@@ -1294,15 +1320,23 @@ export function startRun(root, { goal, playbook, criteria, allowedPaths = [], se
1294
1320
  schemaVersion: 1, engineVersion, id, goal, playbook: selected.id, stages: selected.stages, requiresChecks: selected.requiresChecks,
1295
1321
  ...(taskContextPolicy ? { taskContextPolicy } : {}), ...(workerPolicy ? { delegation: initializeDelegation(workerPolicy) } : {}),
1296
1322
  workContractVersion, contextRetention: retention, ...(evidenceVersion === 1 ? { evidenceVersion, reviewPolicy: reviewPolicy ?? 'self-allowed', requirements: { text: requirements, sha256: digest(requirements) }, criteriaHash: digest(JSON.stringify(criteria)) } : {}), ...ledger,
1297
- criteria, inferredCriteria, session: session ?? null, ...(execution ? { execution } : {}), status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1323
+ criteria, inferredCriteria, session: session ?? null, ...(execution ? { execution } : {}), ...(bound ? { queue: { ...bound.binding, drift: bound.drift(initialSource) } } : {}), status: 'running', stageIndex: 0, attempt: 1, failures: 0, noProgress: 0,
1298
1324
  startedAt: new Date().toISOString(), limits: config.limits, commands, ...(declared ? { verificationSource: `declared by ${declared.source}` } : {}),
1299
1325
  ...(proofCommands ? { proofCommands: structuredClone(proofCommands) } : {}),
1300
1326
  protectedPaths: config.protectedPaths, protectedFiles: protectedSnapshot(root, config.protectedPaths), allowedPaths,
1301
1327
  initialSource, base, ...(capture ? { sourceCapture: capture.metadata } : {}), testProof: null, baseline, acceptedFailures: [], handoffs: [], verification: null, history: []
1302
1328
  };
1303
- log(state, 'started', { playbook: selected.id, inferredCriteria, session: state.session, baseline: baseline ? (baseline.reused ? 'reused' : 'measuring') : 'none', ...(declared ? { verificationSource: state.verificationSource } : {}) });
1329
+ log(state, 'started', { playbook: selected.id, inferredCriteria, session: state.session, baseline: baseline ? (baseline.reused ? 'reused' : 'measuring') : 'none', ...(declared ? { verificationSource: state.verificationSource } : {}), ...(bound ? { queue: bound.binding.id, unit: bound.binding.unit } : {}) });
1304
1330
  if (capture) storeOriginals(root, id, capture);
1305
- atomicJSON(runPath(root, id), state);
1331
+ // The queue notes the run before its record exists, so a record lost later still holds its unit.
1332
+ // A start whose record cannot be written takes the note back; if that fails too, the unit reads
1333
+ // halted with a missing run, which a person can decide about.
1334
+ if (bound) noteStart(queueIO(root), state.queue, id);
1335
+ try { atomicJSON(runPath(root, id), state); }
1336
+ catch (error) {
1337
+ if (bound) { try { dropStart(queueIO(root), state.queue, id); } catch { error.message += ` The queue's note of this start could not be removed either, so unit ${state.queue.unit} reads halted with a missing run; a retry decision lets it start again.`; } }
1338
+ throw error;
1339
+ }
1306
1340
  writeReview(root, state);
1307
1341
  return state;
1308
1342
  });
@@ -1860,7 +1894,7 @@ export function controlRun(root, id, action) {
1860
1894
  }
1861
1895
 
1862
1896
  export function completeRun(root, id) {
1863
- return transact(root, id, state => {
1897
+ return publishRunChange(root, transact(root, id, state => {
1864
1898
  requireActive(state);
1865
1899
  if (!budget(state) || !guard(root, state)) return state;
1866
1900
  if (current(state) !== null) throw new Error(`Unfinished stage: ${current(state)}`);
@@ -1868,12 +1902,34 @@ export function completeRun(root, id) {
1868
1902
  if (delivery?.stage !== 'deliver' || delivery.status !== 'passed' || delivery.criteria.some(item => item.result !== 'passed')) throw new Error('A passing delivery handoff covering every criterion is required.');
1869
1903
  assertArtifacts(root, delivery.artifacts);
1870
1904
  // Completion is evidence: every file is read, not taken from the cache.
1871
- if (sourceSnapshot(root).hash !== delivery.sourceHash) throw new Error('Project changed after the delivery review. Retry the affected stage.');
1905
+ const snapshot = sourceSnapshot(root);
1906
+ if (snapshot.hash !== delivery.sourceHash) throw new Error('Project changed after the delivery review. Retry the affected stage.');
1872
1907
  requireVerification(root, state);
1908
+ // An item that lands after this check finds the unit done and goes to the person.
1909
+ const held = completionHolds(root, state);
1910
+ if (held.length) throw new Error(`The queue board holds this unit: ${holdText(held)}. Clear each with queue post, then finish again.`);
1873
1911
  state.status = 'complete';
1912
+ // Where a queue's line stood when this unit completed, so the next unit can name later edits.
1913
+ if (state.queue) state.queue.completed = { hash: snapshot.hash, files: snapshot.files };
1874
1914
  log(state, 'complete', { verification: state.requiresChecks ? 'recorded-command-results-and-agent-review' : 'agent-reviewed-evidence', sourceHash: delivery.sourceHash, acceptedPreexistingFailures: (state.acceptedFailures ?? []).map(item => item.id) });
1875
1915
  return state;
1876
- });
1916
+ }));
1917
+ }
1918
+
1919
+ // A completed run with planned context publishes its change record. Only completion can state how
1920
+ // the checks ended, so it is written here and is not verified source; a failed write is retried by
1921
+ // the next finish and never undoes completion.
1922
+ function publishRunChange(root, state) {
1923
+ if (state.status !== 'complete' || retentionOf(state)?.disposition !== 'required' || state.changeRecord?.path) return state;
1924
+ let record;
1925
+ try {
1926
+ // The record binds the bytes completion accepted: a file changed since then is not recorded.
1927
+ const snapshot = cachedSnapshot(root);
1928
+ if (snapshot.hash !== state.handoffs.at(-1)?.sourceHash) throw new Error('Source changed after the run completed, so its record would bind bytes the checks did not see.');
1929
+ record = { path: publishChange(root, state, snapshot.files).path };
1930
+ }
1931
+ catch (error) { record = { error: error.message }; }
1932
+ return transact(root, state.id, saved => { saved.changeRecord = record; log(saved, 'change-record', record); return saved; });
1877
1933
  }
1878
1934
 
1879
1935
  // Files that differ from the run-start snapshot and still exist: what this run changed.
@@ -1960,6 +2016,9 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1960
2016
  let state = readRun(root, id);
1961
2017
  assertRunOwner(root, state);
1962
2018
  requireTaskReady(root, state);
2019
+ // Asked before any check is spent: the unit cannot complete while the board holds it.
2020
+ const held = state.status === 'running' ? completionHolds(root, state) : [];
2021
+ if (held.length) return { runId: id, status: 'needs-answer', finished: false, steps: [], board: { hold: held }, nextAction: { action: 'answer', command: `queue post --queue ${state.queue.id} --run ${id} --file MESSAGE.json`, instruction: 'Clear each hold, then run finish again. Nothing was checked or recorded.' } };
1963
2022
  if (current(state) === null && ['running', 'complete'].includes(state.status)) {
1964
2023
  const delivery = state.handoffs.at(-1);
1965
2024
  if (delivery?.stage !== 'deliver' || delivery.status !== 'passed') throw new Error('No confirmed delivery to resume.');
@@ -1970,8 +2029,8 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
1970
2029
  const gate = json(projectFile(root, `.cyc/runtime/${state.session}.state.json`));
1971
2030
  if (!(Date.parse(delivery.recordedAt) >= Date.parse(gate.updatedAt))) throw new Error('Delivery is outside the current native request window.');
1972
2031
  }
1973
- if (state.status === 'running') state = completeRun(root, id);
1974
- return { runId: id, status: state.status, finished: true, steps: ['resume delivery'], packet: projectDelivery(root, state) };
2032
+ state = state.status === 'running' ? completeRun(root, id) : publishRunChange(root, state);
2033
+ return { runId: id, status: state.status, finished: true, steps: ['resume delivery'], ...(state.changeRecord ? { changeRecord: state.changeRecord } : {}), packet: projectDelivery(root, state) };
1975
2034
  }
1976
2035
  if (artifacts !== undefined) artifactFiles(root, artifacts.map(path => inputPath(root, path)));
1977
2036
  if (continuation) {
@@ -2124,7 +2183,7 @@ export function finishRun(root, id, { summary, artifacts, passedEvidence, criter
2124
2183
  const packet = completed.status === 'complete' ? projectDelivery(root, completed) : null;
2125
2184
  // What the reply may state: the proof's scope and any pre-existing failure it must disclose.
2126
2185
  return { runId: id, status: completed.status, finished: completed.status === 'complete', steps, reviewPath: reviewPath(completed),
2127
- ...(packet ? { packet } : {}),
2186
+ ...(completed.changeRecord ? { changeRecord: completed.changeRecord } : {}), ...(packet ? { packet } : {}),
2128
2187
  ...(completed.testProof?.claim && testProofStatus(root, completed)?.status === 'proven' ? { proofClaim: completed.testProof.claim } : {}),
2129
2188
  ...(completed.verification?.acceptedPreexistingFailures?.length ? { acceptedPreexistingFailures: (completed.acceptedFailures ?? []).filter(item => completed.verification.acceptedPreexistingFailures.includes(item.id)).map(({ id: check, reason }) => ({ check, reason })) } : {}),
2130
2189
  ...(dropped.length ? { droppedAcceptFailures: dropped } : {}) };
@@ -2223,7 +2282,7 @@ function checkedReview(root, state, id, sourceHash) {
2223
2282
  return record;
2224
2283
  }
2225
2284
 
2226
- export function recordReview(root, id, { reviewId, evidence, identity = null, findings = [] } = {}) {
2285
+ export function recordReview(root, id, { reviewId, evidence, identity = null, findings = [], led } = {}) {
2227
2286
  const invalid = !text(evidence) || /^<.*>$/.test(evidence.trim()) ? 'evidence' : identity !== null && (!text(identity) || /^<.*>$/.test(identity.trim())) ? 'identity' : null;
2228
2287
  if (invalid) { const error = new Error(`Review ${invalid} needs ${invalid === 'identity' ? 'observed text or null' : 'actual non-placeholder evidence'}.`); error.field = invalid; error.repairTemplate = `.cyc/runs/${id}/reviews/${reviewId}-record.json`; throw error; }
2229
2288
  return transact(root, id, state => {
@@ -2233,7 +2292,8 @@ export function recordReview(root, id, { reviewId, evidence, identity = null, fi
2233
2292
  if (!text(evidence) || (identity !== null && !text(identity))) throw new Error('Review needs actual evidence; identity is text or null when unknown.');
2234
2293
  if (!Array.isArray(findings) || new Set(findings.map(f => f?.id)).size !== findings.length || findings.some(f => !text(f?.id) || !text(f.evidence) || !['resolved', 'dismissed', 'open'].includes(f.status))) throw new Error('Review findings need unique ids, status and evidence.');
2235
2294
  if (record.status === 'recorded') throw new Error('Review already recorded; capture a new receipt for another review.');
2236
- const { sha256, ...receipt } = { ...record, status: 'recorded', evidence, identity, findings, recordedAt: new Date().toISOString() };
2295
+ // `led` marks a review that a seat led on the queue board; only recordBoardReview supplies it.
2296
+ const { sha256, ...receipt } = { ...record, status: 'recorded', evidence, identity, findings, ...(led ? { led } : {}), recordedAt: new Date().toISOString() };
2237
2297
  atomicJSON(projectFile(root, record.path), receipt);
2238
2298
  Object.assign(record, receipt, { sha256: digest(readFileSync(projectFile(root, record.path))) });
2239
2299
  log(state, 'review-recorded', { reviewId, reviewer: receipt.reviewer });
@@ -2410,3 +2470,194 @@ export function workerHost(root, id, action, input) {
2410
2470
  return {runId:id,assignment:structuredClone(a)};
2411
2471
  });
2412
2472
  }
2473
+
2474
+ // Work queue (scripts/queue.mjs, docs/work-queue.md): the controller supplies files and the
2475
+ // project lock. A unit's status always comes from the runs that carry its binding.
2476
+ function queueIO(root, given) {
2477
+ const folder = projectFile(root, queueFolder), runsFolder = projectFile(root, '.cyc/runs');
2478
+ const folders = directory => existsSync(directory) ? readdirSync(directory, { withFileTypes: true }).filter(entry => entry.isDirectory()).map(entry => entry.name) : [];
2479
+ let bound;
2480
+ return {
2481
+ engineVersion, session: callerSession(), given,
2482
+ read: id => json(projectFile(root, queuePath(id))),
2483
+ write: (id, queue) => {
2484
+ // The folder ignores itself, so queues stay local without editing the project's ignore file.
2485
+ if (!existsSync(resolve(folder, '.gitignore'))) { mkdirSync(folder, { recursive: true }); writeFileSync(resolve(folder, '.gitignore'), '*\n'); }
2486
+ atomicJSON(projectFile(root, queuePath(id)), queue);
2487
+ },
2488
+ list: () => folders(folder).filter(name => existsSync(resolve(folder, name, 'queue.json'))),
2489
+ runs: () => bound ??= folders(runsFolder).filter(name => /^[a-z0-9-]{1,80}$/.test(name)).map(name => { try { return json(resolve(runsFolder, name, 'state.json')); } catch { return null; } }).filter(run => run?.queue),
2490
+ normalize: paths => normalizePaths(root, paths, 'paths'),
2491
+ source: () => cachedSnapshot(root),
2492
+ exists: path => existsSync(projectFile(root, path)),
2493
+ put: (path, value) => atomicJSON(projectFile(root, path), value),
2494
+ readBoard: id => readBoardFile(root, id),
2495
+ writeBoard: (id, board) => atomicJSON(resolve(boardFolder(root, id), 'board.json'), board),
2496
+ lockBoard: (id, work) => withBoardLock(root, id, work),
2497
+ now: () => Date.now(),
2498
+ keysOf: id => [id, gateSession(root, id)],
2499
+ sourceHash: () => cachedSnapshot(root).hash
2500
+ };
2501
+ }
2502
+ // Found through the queue's folder: looking up the lock file itself races with its removal.
2503
+ const boardFolder = (root, id) => { queuePath(id); return projectFile(root, `${queueFolder}/${id}`); };
2504
+ const pause = ms => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
2505
+ // Held for one read and one write. A caller gives up after five seconds; a lock older than ten
2506
+ // is cleared by the one waiter that holds the claim; a holder removes only its own.
2507
+ function withBoardLock(root, id, work) {
2508
+ const path = resolve(boardFolder(root, id), 'board.lock'), deadline = Date.now() + 5000, mark = randomUUID();
2509
+ let fd;
2510
+ for (;;) {
2511
+ try { fd = openSync(path, 'wx', 0o600); break; } catch (error) {
2512
+ // Windows reports a lock file that is being removed as EPERM or EBUSY.
2513
+ if (!['EEXIST', 'EPERM', 'EBUSY', 'EACCES', 'EISDIR'].includes(error.code)) throw error;
2514
+ if (Date.now() > deadline) { const busy = new Error('The queue board is busy. Try again.'); busy.code = 'CYC_BOARD_BUSY'; throw busy; }
2515
+ let age = 0;
2516
+ try { age = Date.now() - statSync(path).mtimeMs; } catch { /* gone or going */ }
2517
+ if (age > 10000) {
2518
+ const claim = `${path}.claim`;
2519
+ try {
2520
+ const held = openSync(claim, 'wx', 0o600);
2521
+ try { if (Date.now() - statSync(path).mtimeMs > 10000) rmSync(path, { recursive: true, force: true }); } catch { /* gone */ } finally { closeSync(held); unlinkSync(claim); }
2522
+ continue;
2523
+ } catch { try { if (Date.now() - statSync(claim).mtimeMs > 10000) unlinkSync(claim); } catch { /* another waiter has it */ } }
2524
+ }
2525
+ pause(25);
2526
+ }
2527
+ }
2528
+ try { writeFileSync(fd, mark); return work(); }
2529
+ finally { closeSync(fd); try { if (readFileSync(path, 'utf8') === mark) unlinkSync(path); } catch { /* claimed as left behind */ } }
2530
+ }
2531
+ // On Windows a reader can briefly be refused while a writer replaces the file.
2532
+ function readBoardFile(root, id) {
2533
+ for (let attempt = 0; ; attempt++) {
2534
+ try { return json(resolve(boardFolder(root, id), 'board.json')); } catch (error) {
2535
+ if (error.code === 'ENOENT') return null;
2536
+ if (!['EPERM', 'EBUSY', 'EACCES'].includes(error.code) || attempt >= 4) throw new Error(`The board of queue ${id} cannot be read: ${error.message}`);
2537
+ pause(15 * (attempt + 1));
2538
+ }
2539
+ }
2540
+ }
2541
+ // A run with no execution record passes assertRunOwner for anyone; here it is held to its session.
2542
+ function speaksFor(root, state, io) {
2543
+ assertRunOwner(root, state);
2544
+ // The queue noted which session its host reported when the run started: a run started under a
2545
+ // label of its own is still its starter's.
2546
+ let starter;
2547
+ try { starter = state.queue && io.read(state.queue.id).started?.find(entry => entry.runId === state.id)?.by; } catch { /* the queue cannot be read; its own check says so */ }
2548
+ if (!state.execution && state.session && !callerKeys(io).some(key => [state.session, starter].includes(key))) throw new Error(`Run ${state.id} belongs to conversation ${state.session}; another conversation does not speak for it.`);
2549
+ }
2550
+ // Who speaks: a bound run, a review seat, or neither: the person.
2551
+ function boardAuthor(root, io, input) {
2552
+ if (input.run !== undefined && input.seat !== undefined) throw new Error('Pass --run or --seat, not both.');
2553
+ if (input.run === undefined) {
2554
+ const line = lineOf(io, input.queue);
2555
+ return input.seat === undefined ? { line, author: {} } : { line, author: { seat: input.seat }, who: seatView(io, line, input.seat).who };
2556
+ }
2557
+ const state = readRun(root, input.run);
2558
+ speaksFor(root, state, io);
2559
+ if (!state.queue) throw new Error(`Run ${state.id} is not bound to a queue, so it has no board.`);
2560
+ if (input.queue !== undefined && input.queue !== state.queue.id) throw new Error(`Run ${state.id} is bound to queue ${state.queue.id}, not ${input.queue}.`);
2561
+ return { line: lineOf(io, state.queue.id), author: { run: state }, who: { unit: state.queue.unit, runId: state.id } };
2562
+ }
2563
+ const withSeat = (io, line, author, result) => author.seat === undefined ? result : { ...result, seat: seatView(io, line, author.seat).seat };
2564
+ const boardActions = {
2565
+ post(root, io, input) {
2566
+ const { line, author, who } = boardAuthor(root, io, input), result = postMessage(io, line, input.message, author);
2567
+ const board = who ? deliver(io, line, who, { mark: true, run: author.run }) : null;
2568
+ return withSeat(io, line, author, board ? { ...result, board } : result);
2569
+ },
2570
+ board(root, io, input) {
2571
+ const line = lineOf(io, input.queue), result = readBoard(io, line, { unit: input.unit, open: input.open });
2572
+ if (input.seat === undefined) return result;
2573
+ const author = { seat: input.seat }, board = deliver(io, line, seatView(io, line, input.seat).who, { mark: true });
2574
+ return withSeat(io, line, author, board ? { ...result, board } : result);
2575
+ },
2576
+ // How an agent waits for an answer, for at most a minute.
2577
+ wait(root, io, input) {
2578
+ if (input.run === undefined && input.seat === undefined) throw new Error('queue wait needs --run or --seat: whose messages to wait for.');
2579
+ const limit = waitLimit(input.waitMs, 55000), deadline = Date.now() + limit;
2580
+ const { line, author, who } = boardAuthor(root, io, input);
2581
+ let board = deliver(io, line, who, { mark: true, run: author.run }), now = line;
2582
+ const gone = () => author.seat !== undefined && !['active', 'done'].includes(seatView(io, now, author.seat).seat.state);
2583
+ while (!board?.new && !gone() && Date.now() < deadline) {
2584
+ pause(Math.min(500, Math.max(1, deadline - Date.now())));
2585
+ now = { queue: line.queue, view: lineOf(queueIO(root), line.queue.id).view };
2586
+ if (author.seat !== undefined && !['active', 'done'].includes(seatView(io, now, author.seat).seat.state)) break;
2587
+ if (deliver(io, now, who, { run: author.run })?.new) board = deliver(io, now, who, { mark: true, run: author.run });
2588
+ }
2589
+ if (!board?.new) board = deliver(io, now, who, { run: author.run && readRun(root, author.run.id) });
2590
+ return withSeat(io, now, author, { queueId: line.queue.id, waited: limit - Math.max(0, deadline - Date.now()), board, ...(board?.new ? {} : { note: 'Nothing new arrived. Wait again, or go on with other work.' }) });
2591
+ },
2592
+ release(root, io, input) {
2593
+ if (input.seat === undefined) throw new Error('queue release needs --seat ID.');
2594
+ return releaseSeat(io, lineOf(io, input.queue), { seat: input.seat });
2595
+ }
2596
+ };
2597
+ function waitLimit(value, fallback) {
2598
+ const limit = value === undefined ? fallback : /^\d+$/.test(String(value)) ? Number(value) : NaN;
2599
+ if (!Number.isInteger(limit) || limit > 60000) throw new Error('--wait-ms is a whole number of milliseconds up to 60000.');
2600
+ return limit;
2601
+ }
2602
+ function withBoard(io, result) {
2603
+ if (!result?.queueId) return result;
2604
+ try {
2605
+ const line = lineOf(io, result.queueId), board = boardSummary(io, line);
2606
+ const assumed = result.dependencies?.length ? assumptions(io, line, result.dependencies.map(entry => entry.unit)) : [];
2607
+ return { ...result, ...(assumed.length ? { assumed } : {}), ...(board ? { board } : {}) };
2608
+ } catch (error) { return { ...result, board: { error: error.message } }; }
2609
+ }
2610
+ const queueActions = { create: createQueue, status: queueStatus, next: queueNext, decide: decideQueue };
2611
+ export function queueCommand(root, action, input = {}) {
2612
+ root = realpathSync(root);
2613
+ if (Object.hasOwn(boardActions, action)) return boardActions[action](root, queueIO(root, input.session), input);
2614
+ if (!Object.hasOwn(queueActions, action)) throw new Error('Use queue create, status, next or decide; the board takes queue post, board, wait and release.');
2615
+ if (action === 'next' && input.seat !== undefined) {
2616
+ // A reviewer may arrive before the unit starts.
2617
+ for (const deadline = Date.now() + waitLimit(input.waitMs, 0); ;) {
2618
+ const io = queueIO(root);
2619
+ try { return takeSeat(io, lineOf(io, input.queue), { seat: input.seat, session: input.session }); }
2620
+ catch (error) { if (error.code !== 'CYC_NO_UNIT' || Date.now() >= deadline) throw error; }
2621
+ pause(Math.min(500, Math.max(1, deadline - Date.now())));
2622
+ }
2623
+ }
2624
+ if (input.waitMs !== undefined) throw new Error('--wait-ms goes with queue wait, or with queue next --seat review.');
2625
+ // Reading the line takes no lock, so it still answers while a long check holds the project lock.
2626
+ if (['status', 'next'].includes(action)) { const io = queueIO(root); return withBoard(io, queueActions[action](io, { queue: input.queue })); }
2627
+ return withWorkspaceLock(root, `queue ${action}`, configuration(root).protectedPaths, () => queueActions[action](queueIO(root), input));
2628
+ }
2629
+ // A bound run's board entry. The mark moves only at a checkpoint, for its own conversation.
2630
+ export function boardOf(root, id, checkpoint = true, session) {
2631
+ let state;
2632
+ try { state = readRun(root, id); } catch { return null; }
2633
+ if (!state?.queue) return null;
2634
+ try {
2635
+ const io = queueIO(root, session);
2636
+ let owner = true;
2637
+ try { speaksFor(root, state, io); } catch { owner = false; }
2638
+ return deliver(io, lineOf(io, state.queue.id), { unit: state.queue.unit, runId: state.id }, { mark: owner && checkpoint, run: state });
2639
+ } catch (error) { return { error: error.message }; }
2640
+ }
2641
+ // With a board, a queue or board that cannot be read is an error: what is held is unknown.
2642
+ function completionHolds(root, state) {
2643
+ if (!state.queue) return [];
2644
+ const io = queueIO(root);
2645
+ if (!hasBoard(io, state.queue.id)) return [];
2646
+ return boardHolds(io, lineOf(io, state.queue.id), state);
2647
+ }
2648
+ const holdText = held => held.map(entry => entry.message ? `${entry.kind} ${entry.message} from ${entry.from}` : `review seat ${entry.seat}`).join('; ');
2649
+ // One peer receipt for a review a seat led, captured and recorded in one call.
2650
+ export function recordBoardReview(root, id, session) {
2651
+ const state = readRun(root, id), io = queueIO(root, session);
2652
+ speaksFor(root, state, io);
2653
+ if (!state.queue) throw new Error(`Run ${id} is not bound to a queue, so it has no board.`);
2654
+ const line = lineOf(io, state.queue.id);
2655
+ const review = boardReview(io, line, state, cachedSnapshot(root).hash);
2656
+ if ((state.reviewReceipts ?? []).some(item => item.status === 'recorded' && item.led?.seat === review.led.seat && item.led.signedOff === review.led.signedOff)) throw new Error(`The review that seat ${review.led.seat} signed off as message ${review.led.signedOff} is already recorded for run ${id}.`);
2657
+ const capture = captureReview(root, id, { reviewer: 'peer' });
2658
+ // A run the guard halted returns its state, not a capture.
2659
+ if (!capture.sourceHash) throw new Error(`Run ${id} is ${capture.status}; the review was not captured.`);
2660
+ return recordReview(root, id, { reviewId: capture.id, ...boardReview(io, line, state, capture.sourceHash) });
2661
+ }
2662
+ // Where the line stands, for a bound run's results. Presentation only; null for an unbound run.
2663
+ export const queueOf = (root, state) => state?.queue ? queueAdvice(queueIO(root), state.queue) : null;
@@ -9,10 +9,27 @@ const hash = value => createHash('sha256').update(value).digest('hex');
9
9
  // Defaults for the selected source; a project can set its own in source.maxFiles and source.maxBytes.
10
10
  export const sourceLimits = Object.freeze({ maxFiles: 200000, maxBytes: 2 * 1024 * 1024 * 1024 });
11
11
  const ignored = new Set(['.git', 'node_modules', '.next', 'dist', 'build', 'coverage']);
12
- const internal = ['.cyc/runtime', '.cyc/runs', '.cyc/engine'];
12
+ const internal = ['.cyc/runtime', '.cyc/runs', '.cyc/engine', '.cyc/queues'];
13
13
  const within = (path, parent) => path === parent || path.startsWith(`${parent}/`);
14
14
  // Controller bookkeeping inside the project, never project source.
15
15
  export const controllerPath = path => internal.some(p => within(path, p));
16
+ // Change records published after verification, in <context folder>/changes: kept with the project,
17
+ // never verified source. Only these names; any other file there is source.
18
+ export const changeFile = /^(?:\d{4}-\d{2}-\d{2}-[A-Za-z0-9][A-Za-z0-9._-]{3,}|\d{4}-\d{2})\.md$/;
19
+ export function recordMatcher(root) {
20
+ let folder = 'docs/context';
21
+ // Read the folder as the controller does (trimmed, no backticks), and as Windows names it.
22
+ try { const value = JSON.parse(readFileSync(resolve(root, '.cyc/config.json'), 'utf8').replace(/^/, '')).context?.directory; if (typeof value === 'string' && value.trim()) folder = value.trim().replaceAll('`', ''); }
23
+ catch { /* no readable configuration: the default folder */ }
24
+ const fold = process.platform === 'win32' ? text => text.toLowerCase() : text => text, prefix = `${folder}/changes/`;
25
+ // Only a regular file is exempt: a folder, link or submodule under a record name is source. A
26
+ // record that is gone (folded into its digest) is not a project edit either.
27
+ return path => {
28
+ if (fold(path.slice(0, prefix.length)) !== fold(prefix) || !changeFile.test(path.slice(prefix.length))) return false;
29
+ try { return lstatSync(resolve(root, path)).isFile(); } catch (error) { return error.code === 'ENOENT'; }
30
+ };
31
+ }
32
+
16
33
  const secret = path => /(^|\/)\.env(?:$|\.)/.test(path) && !/\.(example|sample|template)$/.test(path);
17
34
  function paths(root, value, label) {
18
35
  if (!Array.isArray(value) || value.some(p => typeof p !== 'string' || !p || isAbsolute(p) || p.includes('\\') || p.split('/').some(x => !x || x === '.' || x === '..'))) throw new Error(`source.${label} must contain literal project-relative paths, not globs.`);
@@ -301,8 +318,9 @@ export function inspectSource(project, { signatures = 'content', useCache = fals
301
318
  const probe = git(['rev-parse', '--is-inside-work-tree']);
302
319
  const gitAware = probe.status === 0 && probe.stdout.trim() === 'true';
303
320
  if (!gitAware && existsSync(resolve(root, '.git'))) throw new Error('Cannot inspect Git file selection; repair Git access before starting CYC.');
321
+ const record = recordMatcher(root);
304
322
  function excluded(path, forced = false) {
305
- if (controllerPath(path) || path.split('/').includes('.git')) return true;
323
+ if (controllerPath(path) || record(path) || path.split('/').includes('.git')) return true;
306
324
  if (tracked.has(path)) return false;
307
325
  if (secret(path)) return true;
308
326
  if (forced) return false;
@@ -47,7 +47,7 @@ export function validateProofReview(state, review) {
47
47
  requireChoice(item.category, ['behavioral', 'new-interface', 'setup', 'unclassified'], 'Proof category');
48
48
  requireText(item.reason, 'Proof reason');
49
49
  if (/^<.*>$/.test(item.reason.trim())) throw new Error('Replace the proof reason placeholder with actual evidence.');
50
- if (item.category === 'behavioral') requireText(item.boundary, 'Existing observable boundary');
50
+ if (item.category === 'behavioral' && !text(item.boundary)) throw new Error('A behavioral proof case needs boundary: the thing that already existed and answered wrongly, such as a function or command and what it returned. If what the test calls did not exist before this change, the category is new-interface, which needs no boundary.');
51
51
  if (item.category === 'behavioral' && state.testProof.failures.find(f => f.id === item.id)?.hint === 'module-load') throw new Error('A module-load failure cannot establish an existing behavioral boundary; classify the absent interface or setup honestly.');
52
52
  if (item.category === 'behavioral' && state.testProof.failures.find(f => f.id === item.id)?.error === 'test failed') throw new Error('A generic test-file failure has no decisive behavioral assertion; retain diagnostic uncertainty or provide focused evidence.');
53
53
  }
@@ -87,7 +87,7 @@ export function assessmentTemplate(state, stage) {
87
87
  semanticReview: { reviewer: 'self | fresh-context | peer', intent: '<does the diff do what was asked, nothing more>', consumers: '<are dependents still correct>', conventions: '<does it match project style>', findings: [] },
88
88
  consumerChecks: (scoutConsumers.length ? scoutConsumers : [{ id: 'direct' }]).map(item => ({ id: item.id, result: 'passed', evidence: '<the command or observation that showed it works>' })),
89
89
  criterionChecks: criterionClauses(state).map(item => ({ ...item, scenario: '<named scenario for this original outcome/clause>', check: '<configured command id>', receipt: 'current-verification', result: 'passed', origin: 'agent-reported', evidence: '<what this scenario established; not a suite count>' })),
90
- learning: retention?.disposition === 'required' ? { status: 'recorded', reason: '<actual feature knowledge and limits retained>', artifacts: retention.features.map(f => f.doc), context: retention.features.map(f => ({ id: f.id, currentView: '<Describe capability, contracts, decisions, checks and limits; or author the canonical file and remove this context input.>' })) } : { status: 'none | recorded | pending-acceptance', reason: '<why nothing is reusable, or what was recorded>', artifacts: [] },
90
+ learning: retention?.disposition === 'required' ? { status: 'recorded', reason: '<actual feature knowledge and limits retained>', artifacts: retention.features.map(f => f.doc), context: retention.features.map(f => ({ id: f.id, currentView: '<Describe capability, contracts, decisions, checks and limits; or author the canonical file and remove this context input.>', changed: '<One line: what this run changed for this component.>' })) } : { status: 'none | recorded | pending-acceptance', reason: '<why nothing is reusable, or what was recorded>', artifacts: [] },
91
91
  errorHistory: { status: state.playbook === 'bug-fix' || state.failures > 0 ? 'recorded' : 'none | recorded', reason: '<what failed and how it was resolved, or why there was no error>', artifacts: state.playbook === 'bug-fix' || state.failures > 0 ? [state.ledgerPath ?? 'docs/context/error-ledger.md'] : [] }
92
92
  };
93
93
  return Object.fromEntries(required.map(key => [key, templates[key]]));
@@ -329,7 +329,8 @@ export function renderReview(state, currentSourceHash, artifactIssues = [], curr
329
329
  const entry = state.workContractVersion === 1 ? delivery?.assessment?.[name] : null;
330
330
  lines.push(entry ? `- ${name} (${safe(entry.status)}): ${safe(entry.reason)}${entry.artifacts.length ? ` — ${entry.artifacts.map(safe).join(', ')}` : ''}` : `- ${name}: not yet recorded.`);
331
331
  }
332
- if (delivery) lines.push(`- Context docs touched: ${delivery.contextDocs?.length ? delivery.contextDocs.map(safe).join(', ') : 'none'}. ${retentionOf(state) ? 'Canonical retention was checked under this run’s actual contract.' : `Historical catch-up requires a new scoped update: cyc context review --run ${safe(state.id)} --write --update-run UPDATE_ID.`}`);
332
+ if (delivery) lines.push(`- Context docs touched: ${delivery.contextDocs?.length ? delivery.contextDocs.map(safe).join(', ') : 'none'}. ${retentionOf(state) ? 'Canonical retention was checked under this run’s actual contract.' : `This run planned no context: cyc context review --run ${safe(state.id)} --write publishes its change record.`}`);
333
+ if (state.changeRecord) lines.push(`- Change record: ${state.changeRecord.path ? safe(state.changeRecord.path) : `not written (${safe(state.changeRecord.error)}); cyc context review --run ${safe(state.id)} --write publishes it`}.`);
333
334
  lines.push('', '## Recovery, remaining risks, and decisions', '');
334
335
  for (const conflict of state.proofRecovery?.conflicts ?? []) lines.push(`- Proof conflict ${safe(conflict.path)}: ${safe(conflict.reason)}${conflict.savedUnexpected ? ` Unexpected bytes saved at ${safe(conflict.savedUnexpected)}.` : ''}${conflict.preservationError ? ` ${safe(conflict.preservationError)}` : ''}`);
335
336
  if (state.proofRecovery?.preservationError) lines.push(`- Proof recovery record: ${safe(state.proofRecovery.preservationError)}`);
@@ -11,7 +11,7 @@ You own the outcome. Keep normal work short without dropping context reuse, revi
11
11
 
12
12
  ## Frontend work
13
13
 
14
- For new websites/composed redesigns use the [frontend design method](../../methods/cyc-design/frontend-design/SKILL.md) and its three gates: before markup, design/decisions.md names archetype, typeface pair, seven subject-derived colors, signature and rejection condition (plus multi-site divergence); Build renders/scores the signature before expansion (three generic tells fails); Verify checks desktop/phone and experience. Keep it within the original criteria even on fast routes. Combine host/platform guidance into that sheet. Narrow repairs preserve identity; review-only stays review-only.
14
+ “Make my homepage look better” is enough to start a visual redesign. Use the [frontend design method](../../methods/cyc-design/frontend-design/SKILL.md) for new sites and composed redesigns, including fast routes. The assistant owns art direction, accessible interaction and rendered comparison. Check the main action before extending a design, then verify the finished journey on desktop and phone. Apply the same sheet to host/platform requirements and the original criteria. Narrow repairs preserve identity. A request for critique or concepts stays within that scope.
15
15
 
16
16
  ## The flow
17
17
 
@@ -19,15 +19,15 @@ Select the playbook by the requested outcome and permissions using the table bel
19
19
 
20
20
  scout → build → finish/proof judgment → verify → deliver
21
21
 
22
- Read the project's context index first, `docs/context/INDEX.md`, and then only the component docs whose Covers match affected paths. Plan canonical feature context before Build and retain it before final verification. Completed-run catch-up needs a new scoped update; see [Context](../../methods/cyc-context/SKILL.md).
22
+ Read the project's context index first, `docs/context/INDEX.md`, and then only the component docs whose Covers match affected paths. Plan canonical feature context before Build and retain it before final verification; the controller publishes the run's change record at completion. See [Context](../../methods/cyc-context/SKILL.md).
23
23
 
24
- 1. **Scout.** Read docs/context/INDEX.md, matched component history and the relevant error ledger before code. Use investigate with affected paths to discover context/recipes; confirm freshness against actual files and the dirty diff. Reuse, extend, repair or create with a short reason. Trace authoritative state and affected consumers; for a new protected consumer execute the existing writer/status and new protected reads/writes together. Retain every original outcome and material clause. Ask only about consequential unknowns; do not manufacture approval.
24
+ 1. **Scout.** Read docs/context/INDEX.md, matched component docs and the relevant error ledger before code. Use investigate with affected paths to discover context/recipes; confirm freshness against actual files and the dirty diff. Reuse, extend, repair or create with a short reason. Trace authoritative state and affected consumers; for a new protected consumer execute the existing writer/status and new protected reads/writes together. Retain every original outcome and material clause. Ask only about consequential unknowns; do not manufacture approval.
25
25
  2. **Start once.** Save START.json under .cyc/runtime with goal, playbook, explicit criteria/clauses, literal allowedPaths, evidenceVersion:1, original requirements text, reviewPolicy, plan and scout. Scout contains context, approach, alignment and named consumers; the [assessment contract](../../docs/work-assessments.md) defines fields. Include contextRetention: {version:1, disposition:"required", features:[{id,doc,paths}]} for each new/changed feature and affected shared owner. Use the target project’s focused canonical docs and index, creating them when missing; the controller includes these paths before scope freezes. Inspect the inferred plan if omitted. Generic handoffs, recipes and runtime logs do not satisfy feature retention. Explicit documentation restrictions remain pending without unauthorized writes. Pass it to run start --file START.json before edits. Scout supplied at start is already recorded; do not record it twice. Use the returned exact runId and generated template paths, never another conversation's sole run. Allowed paths are literal files/directory prefixes; translate brief globs without broadening authorization. Advisory wording-only work can use packet --advisory with the actual reason no run applies.
26
26
  3. **Bind actual capability.** Set executionMode to native-codex, native-claude, cursor or explicitly authorized standalone. conversationId is the actual host conversation; session is a separate workflow label. Native modes need actual hook context; standalone neither creates hook state nor certifies activation and cannot downgrade a live native request. Unknown capability returns one setup action. Do not invent Cursor identity, tokens or host observations. Legacy callers retain their documented limits. The CLI is .cyc/engine/bin/cyc.mjs for copied installs or bin/cyc.mjs in this checkout.
27
27
  4. **Build and record failures.** Follow the relevant [Build method](../../methods/cyc-build/SKILL.md). Write meaningful boundary tests, then the smallest coherent implementation. Feature/bug proof must fail on originals; refactor characterization must pass there. Preserve imported fields, references and access metadata when recreating records. Keep consumer policies coherent and server authorization separate from client response checks. Record failed fixes promptly in the selected ledger; run-local history is valid when shared history is outside scope. Finalize authorized source/context/ledger edits before final checks. Never clear proof ownership, overwrite unexpected edits or manually swap source to obtain proof.
28
28
  5. **Review once, then affected changes.** Follow Rigor below. Capture before dispatch, fill recordTemplate with actual evidence and identity:null or observed text, then record it. Open findings block. Finish reuses current records; do not transcribe provenance. For bounded scopes inspect dependencies and declare contextPaths/contextEvidence; static imports/configuration bind coverage, unknown impact falls back to whole source. FollowupPath lists changes/contracts/findings; affected paths need new review. Matching provenance is not correctness.
29
29
  6. **Finish with generated input.** Fill finishTemplate with summary, semantic judgments and one scenarioEvidence per original criterion/clause: named scenario, configured check, receipt:current-verification, result:passed, origin:agent-reported, actual evidence and consumers mapped to Scout IDs. Exact legacy views are derived; unavailable journeys stay unverified. Existing criterion/consumer evidence remains compatible.
30
- Run finish --run ID --file FINISH.json --wait-ms 30000. It prepares required canonical context before proof/final checks, completes stages and generates delivery evidence. Fill learning.context {id,currentView} or author planned docs; needs-context supplies remaining input until authored knowledge/index/current History/source binding pass. Learning:none cannot waive a feature; restrictions remain pending. Later context edits need fresh checks, never only a new packet.
30
+ Run finish --run ID --file FINISH.json --wait-ms 30000. It prepares required canonical context before proof/final checks, completes stages and generates delivery evidence. Fill learning.context {id,currentView} or author planned docs; needs-context supplies remaining input until authored knowledge, index and source binding pass. Learning:none cannot waive a feature; restrictions remain pending. Later context edits need fresh checks, never only a new packet.
31
31
  Needs-proof-review supplies failure IDs, diagnostics and an exact bound continuation. Judge actual category/reason then invoke its command; module-load/setup is not a behavioral defect, unknown boundaries stay unknown. Bug fixes need decisive existing behavior; features may establish a missing interface. Do not inspect low-level files just to discover IDs or build a second packet. Truthful non-testable exemptions retain their limits. See [assessments](../../docs/work-assessments.md).
32
32
  7. **Bound check work, preserve coverage.** Optional proofCommands at start freezes focused red/green execution. --tests chooses swapped files, not command scope. Final candidate checks remain broad. Pre-existing broad failures need compatible measured original broad evidence; finish measures it when an acceptance decision requires it, retaining focused results when valid. The existing baseline cache and candidate receipts reuse only compatible, explicitly local-deterministic checks; unknown inputs, external/freshness checks rerun. Never change config/tests to pass. A running operation returns phase/check/elapsed/latest available output, logs and an exact operation handle. Use run wait with that handle for 30–60 seconds when permitted; do not inspect lock files for ordinary progress. Silence, failure and interruption are distinct; honor user stop controls.
33
33
  8. **Deliver.** Use the generated review and canonical run evidence; name decisive checks and disclose failures, unavailable services and unverified host activation. Native Codex/Claude finish writes its request-bound packet; standalone writes run-local delivery.json without a native claim. Cursor still needs its exact-response packet with explicit mode. Recheck the concise reply with check-reply; standalone uses --mode standalone instead of nonexistent hook-state reads. Follow the [response standard](../../docs/response-standard.md), including its visual and length rules. A stage, fingerprint or model-authored score never certifies product readiness. Retain pending proposals as pending; do not invent human acceptance.
@@ -82,6 +82,14 @@ Use the [project tools](../../docs/project-tools.md) automatically when relevant
82
82
  | Extract supported lessons | [Reflect](references/playbooks/reflect.md) |
83
83
  | Compare skill or workflow effectiveness | [Evaluate](references/playbooks/evaluate.md) |
84
84
 
85
+ ## Work queue
86
+
87
+ A plan with several ordered units can run as a [work queue](../../docs/work-queue.md). When the user says "next" or "continue the queue", or `run next`/`run finish` shows a `queue` entry, call `queue next`. For a ready unit: read the listed dependency change records, recheck any drifted file, and tell the user about files under `drift.outsideUnit` before building on them. Follow the returned instruction: a Scout playbook adds scout and plan to the start file, another playbook starts it as written. Then `run start --file` it; keep its criteria, playbook and queue field as written. Work one unit per run, and after it completes tell the user which unit is next. A halted line needs the user: report the unit, its recorded reason and the files under `drift`, and record retry, skip or cancel with `queue decide` only after they choose. Never start a queue's work as an unbound run to get around a refusal.
88
+
89
+ The queue's [board](../../docs/work-queue.md#the-board) carries messages between agents and the user. When a `run` result starts with `board`, read it first. Read the code before asking; ask with `queue post --run ID` only what another unit or `person` owns. Wait with `queue wait`, or close your own question with disposition `assumed`; an answer given later still reaches you, so act on it or tell the user. `run finish` returning `needs-answer` lists what holds the unit: answer each finding `fixed` or `declined`. Never post as the person: show the user what waits for them and post only their answer. To review a unit another session builds: `queue next --seat review --session ID`, change no file, post findings, end with `review-done`. Under review: settle context records, post `ready-for-review`, wait, then `run review-record --from-board`. What holds a unit shows the message to post. When several sessions share a folder, draft your reply in a file of your own under `.cyc/runtime` and give that file to `check-reply`.
90
+
91
+ A person cannot see any of this from a chat. When you start working a queue, run `cyc hub` in the background and give the user the address it prints: the page shows the line, what the agents say to each other and what waits on the user, as it happens. Say that it is there; do not assume they are watching it.
92
+
85
93
  ## Autonomy
86
94
 
87
95
  Just do: read, search, run tests, edit files in scope, build prototypes. Always ask first: commits and pushes (unless asked), publishing, deleting user data, global installs, sending messages. The delivery gate won't let you finish while your run is still open; a run that ends blocked is reported as blocked, never as done.