cyc-stack 0.10.0 → 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 (36) 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/bin/cyc.mjs +55 -7
  5. package/docs/README.md +2 -0
  6. package/docs/runtime.md +4 -0
  7. package/docs/work-queue.md +187 -0
  8. package/methods/cyc-build/SKILL.md +1 -1
  9. package/methods/cyc-design/frontend-design/SKILL.md +125 -28
  10. package/methods/cyc-design/frontend-design/references/color.md +42 -50
  11. package/methods/cyc-design/frontend-design/references/craft-rules.md +13 -10
  12. package/methods/cyc-design/frontend-design/references/decision-sheet.md +94 -98
  13. package/methods/cyc-design/frontend-design/references/experience-review.md +10 -2
  14. package/methods/cyc-design/frontend-design/references/field-guide.md +439 -0
  15. package/methods/cyc-design/frontend-design/references/generic-tells.md +82 -33
  16. package/methods/cyc-design/frontend-design/references/layout-archetypes.md +5 -5
  17. package/methods/cyc-design/frontend-design/references/patterns.md +108 -0
  18. package/methods/cyc-design/frontend-design/references/reference-standards.md +118 -22
  19. package/methods/cyc-design/frontend-design/references/typography.md +59 -44
  20. package/methods/cyc-design/frontend-design/references/visual-material.md +40 -7
  21. package/methods/cyc-design/frontend-design/scripts/contrast.mjs +1 -1
  22. package/methods/cyc-design/frontend-design/scripts/first-screen.mjs +911 -0
  23. package/methods/cyc-design/frontend-design/scripts/photo-text.mjs +230 -0
  24. package/methods/cyc-verify/SKILL.md +1 -1
  25. package/package.json +6 -1
  26. package/plugin.json +1 -1
  27. package/scripts/hub-page.mjs +275 -0
  28. package/scripts/hub.mjs +139 -0
  29. package/scripts/queue-board.mjs +287 -0
  30. package/scripts/queue.mjs +283 -0
  31. package/scripts/run-gate.mjs +1 -1
  32. package/scripts/runtime.mjs +248 -13
  33. package/scripts/source-snapshot.mjs +1 -1
  34. package/scripts/work-review.mjs +1 -1
  35. package/skills/cyc/SKILL.md +8 -0
  36. package/skills/cyc/references/playbooks/plan.md +2 -0
@@ -0,0 +1,283 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { digest } from './response-gate.mjs';
3
+ import { getPlaybook } from './catalog.mjs';
4
+ import { stopReason } from './run-gate.mjs';
5
+ import { strictObject, text } from './task-context.mjs';
6
+
7
+ // A work queue is an ordered set of units, each an ordinary run. The queue file holds the frozen
8
+ // units, the recorded decisions and a note of each run it admitted. How a unit ended is never
9
+ // stored: it is read from the runs bound to it. A note gives the order of admission and stands in
10
+ // for a run only when its record cannot be read. `io` comes from the controller (scripts/runtime.mjs).
11
+ // Reasoning and limits: docs/context/work-queue.md.
12
+ export const queueFolder = '.cyc/queues';
13
+ export function queuePath(id) {
14
+ if (typeof id !== 'string' || !/^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/.test(id)) throw Error('A valid --queue ID is required.');
15
+ return `${queueFolder}/${id}/queue.json`;
16
+ }
17
+ const unitName = /^[a-z0-9][a-z0-9-]{0,39}$/, criterionName = /^[a-zA-Z0-9_-]+$/;
18
+ const named = (pattern, value) => typeof value === 'string' && pattern.test(value);
19
+ const within = (path, parent) => path === parent || path.startsWith(`${parent}/`);
20
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
21
+ // Statuses that end a run short of complete. `missing`: an admitted run whose record cannot be read.
22
+ const ended = ['halted', 'exhausted', 'stopped', 'missing'], open = ['running', 'paused', 'blocked'];
23
+ const clean = (items, label) => {
24
+ if (!Array.isArray(items) || !items.length || new Set(items.map(item => item?.id)).size !== items.length || items.some(item => !named(criterionName, item?.id) || !text(item.description))) throw Error(`${label} must be a nonempty array of unique {id, description} records.`);
25
+ return items.map(item => ({ id: item.id, description: item.description, ...(item.clauses === undefined ? {} : { clauses: clean(item.clauses, `${label} ${item.id} clauses`) }) }));
26
+ };
27
+ // Field order in a file is not part of what was agreed.
28
+ const sameCriteria = (a, b) => { try { return digest(JSON.stringify(clean(a, 'criteria'))) === digest(JSON.stringify(clean(b, 'criteria'))); } catch { return false; } };
29
+
30
+ export function queueDefinition(input, io) {
31
+ strictObject(input, ['version', 'goal', 'requirements', 'units'], 'queue');
32
+ if (input.version !== 1 || !text(input.goal) || !text(input.requirements)) throw Error('A queue needs version 1, a goal and the original requirements text.');
33
+ if (!Array.isArray(input.units) || !input.units.length || input.units.length > 50) throw Error('A queue needs 1 to 50 units.');
34
+ const seen = new Set();
35
+ const units = input.units.map(unit => {
36
+ strictObject(unit, ['id', 'outcome', 'playbook', 'criteria', 'paths', 'dependsOn'], 'queue unit');
37
+ if (!named(unitName, unit.id) || seen.has(unit.id)) throw Error(`Unit ids must be unique lowercase names of letters, digits and dashes: ${JSON.stringify(unit.id)}`);
38
+ if (['person', 'all'].includes(unit.id)) throw Error(`A unit cannot be named ${unit.id}: the queue board uses that name for who a message is for.`);
39
+ seen.add(unit.id);
40
+ if (!text(unit.outcome)) throw Error(`Unit ${unit.id} needs an outcome: what is true when it is done.`);
41
+ if (!Array.isArray(unit.paths) || !unit.paths.length) throw Error(`Unit ${unit.id} needs paths: the files or folders its run may change.`);
42
+ const dependsOn = unit.dependsOn ?? [];
43
+ if (!Array.isArray(dependsOn) || dependsOn.some(id => typeof id !== 'string') || new Set(dependsOn).size !== dependsOn.length) throw Error(`Unit ${unit.id} dependsOn must list unique unit ids.`);
44
+ return { id: unit.id, outcome: unit.outcome, playbook: getPlaybook(unit.playbook).id, criteria: clean(unit.criteria, `Unit ${unit.id} criteria`), paths: io.normalize(unit.paths), dependsOn };
45
+ });
46
+ for (const unit of units) for (const id of unit.dependsOn) if (!seen.has(id) || id === unit.id) throw Error(`Unit ${unit.id} depends on ${id === unit.id ? 'itself' : `${id}, which is not a unit of this queue`}.`);
47
+ // A cycle would leave its units waiting on each other forever.
48
+ const state = new Map();
49
+ const visit = (unit, trail) => {
50
+ if (state.get(unit.id) === 'done') return;
51
+ if (state.get(unit.id) === 'open') throw Error(`Units depend on each other in a cycle: ${[...trail.slice(trail.indexOf(unit.id)), unit.id].join(' -> ')}.`);
52
+ state.set(unit.id, 'open');
53
+ for (const id of unit.dependsOn) visit(units.find(item => item.id === id), [...trail, unit.id]);
54
+ state.set(unit.id, 'done');
55
+ };
56
+ for (const unit of units) visit(unit, []);
57
+ return { goal: input.goal, requirements: input.requirements, units };
58
+ }
59
+
60
+ // The stored record, checked for shape only. Enough to cancel a queue whose units were edited.
61
+ function stored(io, id) {
62
+ let queue;
63
+ try { queue = io.read(id); } catch (error) { throw Error(error.code === 'ENOENT' ? `No queue ${id} in this project.` : `Queue ${id} cannot be read: ${error.message}`); }
64
+ const entries = (list, check) => Array.isArray(list) && list.every(item => record(item) && check(item));
65
+ if (!record(queue) || queue.schemaVersion !== 1 || queue.id !== id || !['open', 'cancelled'].includes(queue.status) || !record(queue.definition) || !Array.isArray(queue.definition.units)
66
+ || !entries(queue.decisions, item => ['retry', 'skip', 'cancel'].includes(item.action)) || !entries(queue.started ?? [], item => typeof item.unit === 'string' && typeof item.runId === 'string')) throw Error(`Queue ${id} is not a version 1 queue record.`);
67
+ return queue;
68
+ }
69
+ const editedNote = 'Its units no longer match what was agreed; criteria are not changed in place. Cancel it with queue decide --queue ID and create a new queue.';
70
+ const edited = (queue, detail = '') => Error(`Queue ${queue.id} was edited after it was created${detail}. ${queue.status === 'cancelled' ? 'It is cancelled and kept only as a record.' : editedNote}`);
71
+ function load(io, id) {
72
+ const queue = stored(io, id);
73
+ if (digest(JSON.stringify(queue.definition)) !== queue.definitionHash) throw edited(queue);
74
+ return queue;
75
+ }
76
+
77
+ // Why a unit's run stopped. A run stopped after it was blocked or halted keeps that reason; a
78
+ // resume clears it.
79
+ function endReason(run) {
80
+ if (run.status === 'missing') return `The record of run ${run.id} is missing or unreadable, so how it ended is unknown.`;
81
+ const direct = stopReason(run);
82
+ if (direct) return direct;
83
+ const history = Array.isArray(run.history) ? run.history : [], stop = history.findLastIndex(item => item?.type === 'stop');
84
+ for (let index = stop - 1; index >= 0 && history[index]?.type !== 'resume'; index--) {
85
+ const earlier = ['blocked', 'guard-halt', 'exhausted'].includes(history[index]?.type) ? stopReason({ history: history.slice(0, index + 1) }) : null;
86
+ if (earlier) return `Stopped after: ${earlier}`;
87
+ }
88
+ return `Run ${run.id} ended ${run.status}.`;
89
+ }
90
+
91
+ // Every unit's status, derived from the runs bound to it and the recorded decisions.
92
+ export function queueView(queue, runs) {
93
+ const time = value => Date.parse(value) || 0;
94
+ const mine = runs.filter(run => run.queue?.id === queue.id);
95
+ const foreign = mine.find(run => run.queue.definitionHash !== queue.definitionHash);
96
+ if (foreign) throw edited(queue, `: run ${foreign.id} was admitted under different units`);
97
+ // The order of admission, from notes written under the project lock: it holds when the clock
98
+ // steps back.
99
+ const noted = new Map((queue.started ?? []).map((entry, index) => [entry.runId, index]));
100
+ const seq = run => noted.get(run.id) ?? Number.MAX_SAFE_INTEGER;
101
+ const admitted = (a, b) => seq(a) - seq(b) || time(a.startedAt) - time(b.startedAt);
102
+ // A noted run whose record is gone still holds its place.
103
+ for (const entry of queue.started ?? []) if (!mine.some(run => run.id === entry.runId)) mine.push({ id: entry.runId, status: 'missing', startedAt: entry.time, queue: { id: queue.id, unit: entry.unit, attempt: entry.attempt, definitionHash: queue.definitionHash } });
104
+ mine.sort(admitted);
105
+ const units = queue.definition.units.map(unit => {
106
+ const attempts = mine.filter(run => run.queue.unit === unit.id).sort((a, b) => (a.queue.attempt ?? 0) - (b.queue.attempt ?? 0) || admitted(a, b));
107
+ // A run that has not ended decides the unit, whichever attempt it is.
108
+ const latest = attempts.findLast(run => open.includes(run.status)) ?? attempts.at(-1);
109
+ // A decision speaks for a run as it stood, not for one that reads differently now.
110
+ const decision = latest ? queue.decisions.findLast(item => item.unit === unit.id && item.afterRun === latest.id && item.afterStatus === latest.status) : undefined;
111
+ let status = 'pending', reason;
112
+ if (latest?.status === 'complete') status = 'done';
113
+ else if (latest && ['running', 'paused'].includes(latest.status)) status = 'in-progress';
114
+ else if (decision?.action === 'skip') status = 'skipped';
115
+ else if (latest && decision?.action !== 'retry') { status = 'halted'; reason = endReason(latest); }
116
+ return { id: unit.id, outcome: unit.outcome, playbook: unit.playbook, dependsOn: unit.dependsOn, status, ...(reason ? { reason } : {}), ...(decision ? { decision: { action: decision.action, reason: decision.reason } } : {}), latest: latest?.id ?? null,
117
+ runs: attempts.map(run => ({ runId: run.id, status: run.status, stage: run.stages?.[run.stageIndex] ?? null, startedAt: run.startedAt ?? null })) };
118
+ });
119
+ for (const unit of units) {
120
+ if (queue.status === 'cancelled' && unit.status !== 'done') { unit.status = 'cancelled'; continue; }
121
+ if (unit.status !== 'pending') continue;
122
+ const waitsOn = unit.dependsOn.filter(id => units.find(item => item.id === id).status !== 'done');
123
+ unit.status = waitsOn.length ? 'waiting' : 'ready';
124
+ if (waitsOn.length) unit.waitsOn = waitsOn;
125
+ }
126
+ const has = status => units.some(unit => unit.status === status);
127
+ const line = queue.status === 'cancelled' ? 'cancelled' : has('halted') ? 'halted' : has('in-progress') ? 'in-progress' : units.every(unit => unit.status === 'done') ? 'complete' : has('ready') ? 'ready' : 'ended';
128
+ // Where the line last stood: the unit that completed last, or where its first run started.
129
+ const last = mine.findLast(run => run.status === 'complete' && record(run.queue.completed?.files)) ?? null;
130
+ const first = last ? null : mine.find(run => record(run.initialSource?.files)) ?? null;
131
+ const from = last ?? first;
132
+ return { line, units, next: line === 'ready' ? units.find(unit => unit.status === 'ready').id : null, runs: mine,
133
+ position: from ? { run: from.id, unit: from.queue.unit, event: last ? 'completed' : 'started', ...(last ? last.queue.completed : { hash: from.initialSource.hash, files: from.initialSource.files }) } : null,
134
+ since: from ? mine.slice(mine.indexOf(from)).filter(run => run.status !== 'complete') : mine.filter(run => run.status !== 'complete'),
135
+ lost: last ? [] : mine.slice(0, first ? mine.indexOf(first) : mine.length).filter(run => run.status === 'missing') };
136
+ }
137
+
138
+ // Files that differ from where the line last stood: left by an attempt that ended short of
139
+ // complete, or edited outside the line. A retry starts from them, so they are named.
140
+ function drift(view, source, paths) {
141
+ const from = view.position;
142
+ if ((!from || from.hash === source.hash) && !view.lost.length) return null;
143
+ const changed = from ? [...new Set([...Object.keys(from.files), ...Object.keys(source.files)])].filter(path => from.files[path] !== source.files[path]).sort() : [];
144
+ const outside = changed.filter(path => !paths.some(prefix => within(path, prefix)));
145
+ return { sinceRun: from?.run ?? null, sinceUnit: from?.unit ?? null, since: from?.event ?? 'unknown', changed: changed.slice(0, 50), total: changed.length, outsideUnit: outside.slice(0, 50), outsideTotal: outside.length,
146
+ unfinishedAttempts: view.since.map(run => ({ runId: run.id, unit: run.queue.unit, status: run.status })),
147
+ ...(view.lost.length ? { lostRuns: view.lost.map(run => run.id), note: 'The record of an earlier run is missing, so where the line started is unknown and files that run changed may not be listed.' } : {}) };
148
+ }
149
+
150
+ function resolve(io, id) {
151
+ if (id !== undefined) return load(io, id);
152
+ const live = [], broken = [], finished = [];
153
+ for (const item of io.list()) {
154
+ try {
155
+ if (stored(io, item).status === 'cancelled') continue;
156
+ const queue = load(io, item);
157
+ (queueView(queue, io.runs()).line === 'complete' ? finished : live).push(queue);
158
+ } catch (error) { broken.push(`${item}: ${error.message}`); }
159
+ }
160
+ if (live.length === 1 && !broken.length) return live[0];
161
+ const last = finished.sort((a, b) => a.createdAt < b.createdAt ? -1 : 1).at(-1);
162
+ if (!live.length && !broken.length) throw Error(`No open queue in this project.${last ? ` The last one, ${last.id} (${last.definition.goal.slice(0, 60)}), is complete: add --queue ${last.id} to read it.` : ''} Create one with queue create --file QUEUE.json, or pass --queue ID for a finished one.`);
163
+ throw Error(`${live.length > 1 ? `Several queues are open: ${live.map(queue => `${queue.id} (${queue.definition.goal.slice(0, 60)})`).join('; ')}. ` : ''}${broken.length ? `Unreadable: ${broken.join('; ')}. ` : ''}Pass --queue ID.`);
164
+ }
165
+
166
+ export function lineOf(io, id) {
167
+ const queue = resolve(io, id);
168
+ return { queue, view: queueView(queue, io.runs()) };
169
+ }
170
+
171
+ const summary = (queue, view) => ({ queueId: queue.id, goal: queue.definition.goal, line: view.line, done: view.units.filter(unit => unit.status === 'done').length, total: view.units.length });
172
+
173
+ export function createQueue(io, input) {
174
+ const definition = queueDefinition(input, io);
175
+ const queue = { schemaVersion: 1, id: randomUUID(), engineVersion: io.engineVersion, createdAt: new Date().toISOString(), createdBy: io.session ?? null, status: 'open', definition, definitionHash: digest(JSON.stringify(definition)), decisions: [], started: [] };
176
+ io.write(queue.id, queue);
177
+ return { ...statusOf(queue, io), created: true, nextAction: { action: 'next', command: `queue next --queue ${queue.id}` } };
178
+ }
179
+
180
+ function statusOf(queue, io) {
181
+ const view = queueView(queue, io.runs());
182
+ return { ...summary(queue, view), next: view.next, units: view.units.map(({ latest, ...unit }) => unit), decisions: queue.decisions,
183
+ note: 'Status is read from each unit\'s runs. A done unit means its run completed; it does not certify the product, and nothing here was committed or published.' };
184
+ }
185
+ export const queueStatus = (io, { queue: id } = {}) => statusOf(resolve(io, id), io);
186
+
187
+ export function queueNext(io, { queue: id } = {}) {
188
+ const queue = resolve(io, id), view = queueView(queue, io.runs()), head = summary(queue, view);
189
+ const decide = `queue decide --queue ${queue.id} --file DECISION.json`;
190
+ const paths = unit => io.normalize(queue.definition.units.find(item => item.id === unit).paths);
191
+ if (view.line === 'halted') {
192
+ const unit = view.units.find(item => item.status === 'halted'), run = unit.runs.find(item => item.runId === unit.latest);
193
+ // What a retry would start from is shown before the decision.
194
+ let changed;
195
+ try { changed = drift(view, io.source(), paths(unit.id)); } catch (error) { changed = { error: error.message }; }
196
+ return { ...head, halted: { unit: unit.id, runId: run.runId, status: run.status, reason: unit.reason }, drift: changed,
197
+ nextAction: open.includes(run.status)
198
+ ? { action: 'recover', command: `run recover --run ${run.runId}`, instruction: `Run ${run.runId} is ${run.status}, not ended. Resume and finish it, or stop it; a stopped run then needs a recorded decision. No other unit starts meanwhile.` }
199
+ : { action: 'decide', command: decide, input: { version: 1, unit: unit.id, action: 'retry | skip', reason: '<why>' }, instruction: 'The line is halted. A person decides: retry starts this unit again from the files as they are now and keeps the earlier run listed; skip leaves units that depend on it waiting; {"version":1,"action":"cancel","reason":"..."} closes the queue. Show the user the reason and the files under drift, above all drift.outsideUnit, before they choose. Do not record a decision the user has not made.' } };
200
+ }
201
+ if (view.line === 'in-progress') { const unit = view.units.find(item => item.status === 'in-progress'); return { ...head, inProgress: { unit: unit.id, runId: unit.latest }, nextAction: { action: 'next', command: `run next --run ${unit.latest}` } }; }
202
+ if (view.line !== 'ready') return { ...head, unfinished: view.units.filter(unit => unit.status !== 'done').map(unit => ({ unit: unit.id, status: unit.status, ...(unit.waitsOn ? { waitsOn: unit.waitsOn } : {}) })),
203
+ nextAction: view.line === 'ended' ? { action: 'decide', command: decide, input: { version: 1, action: 'cancel', reason: '<why>' }, instruction: 'Nothing more can start: what remains was skipped or waits on a skipped unit. When the user agrees, cancel this queue and create a new one for what is left.' } : null };
204
+ const unit = queue.definition.units.find(item => item.id === view.next), attempt = view.units.find(item => item.id === unit.id).runs.length + 1;
205
+ const stages = getPlaybook(unit.playbook).stages;
206
+ const template = `${queueFolder}/${queue.id}/start-${unit.id}-${attempt}.json`;
207
+ // Written once: the agent adds Scout to it, so a later call must not replace its work.
208
+ if (!io.exists(template)) io.put(template, { goal: unit.outcome, playbook: unit.playbook, ...(stages.includes('build') ? { evidenceVersion: 1, reviewPolicy: 'self-allowed', requirements: `${queue.definition.requirements}\n\nUnit ${unit.id}: ${unit.outcome}` } : {}), criteria: unit.criteria, allowedPaths: unit.paths, queue: { id: queue.id, unit: unit.id } });
209
+ const records = unit.dependsOn.map(id => { const run = view.runs.findLast(item => item.queue.unit === id && item.status === 'complete'); return { unit: id, runId: run.id, changeRecord: run.changeRecord?.path ?? null }; });
210
+ const first = stages[0] === 'scout'
211
+ ? 'Scout this unit first: read the dependency change records and recheck every drifted file. Add scout and plan (and contextRetention for a playbook that builds) to the start file, narrow allowedPaths if less is needed, then start.'
212
+ : `Read the dependency change records and recheck every drifted file. The ${unit.playbook} playbook starts with ${stages[0]}, not Scout: start the file as written, then record ${stages[0]} with run record.`;
213
+ return { ...head, unit: { ...unit, position: queue.definition.units.indexOf(unit) + 1, attempt }, dependencies: records, drift: drift(view, io.source(), paths(unit.id)), startTemplate: template,
214
+ nextAction: { action: 'start', command: `run start --file ${template}`, instruction: `${first} Criteria, playbook and the queue field stay as written; paths outside this unit need a new queue. Files under drift.outsideUnit changed outside this unit's paths: tell the user about them before building on them.` } };
215
+ }
216
+
217
+ // The start rules, checked before a run record exists.
218
+ export function bindUnit(io, binding, { playbook, criteria, inferredCriteria, allowedPaths }) {
219
+ strictObject(binding, ['id', 'unit'], 'queue binding');
220
+ const queue = load(io, binding.id), view = queueView(queue, io.runs());
221
+ const unit = queue.definition.units.find(item => item.id === binding.unit), current = view.units.find(item => item.id === binding.unit);
222
+ if (!unit) throw Error(`Queue ${queue.id} has no unit ${JSON.stringify(binding.unit)}.`);
223
+ if (view.line === 'cancelled') throw Error(`Queue ${queue.id} was cancelled; its units no longer start.`);
224
+ const busy = view.units.find(item => item.id !== unit.id && ['in-progress', 'halted'].includes(item.status));
225
+ if (busy) throw Error(`Unit ${busy.id} is ${busy.status} (run ${busy.latest}). One unit runs at a time, and a halted unit needs a recorded decision before the line moves. See queue next --queue ${queue.id}.`);
226
+ if (current.status !== 'ready') throw Error({ waiting: `Unit ${unit.id} waits on ${current.waitsOn?.join(', ')}; a unit starts only after every unit it depends on is done.`, 'in-progress': `Unit ${unit.id} already has run ${current.latest} in progress.`, done: `Unit ${unit.id} is done.`, skipped: `Unit ${unit.id} was skipped.`, halted: `Unit ${unit.id} is halted (run ${current.latest}: ${current.reason}). It starts again only after a recorded retry decision: queue decide --queue ${queue.id}.` }[current.status]);
227
+ if (playbook !== unit.playbook) throw Error(`Unit ${unit.id} was agreed as a ${unit.playbook} run, not ${playbook}.`);
228
+ if (inferredCriteria || !sameCriteria(criteria, unit.criteria)) throw Error(`The criteria differ from the ones agreed for unit ${unit.id}. Copy them from queue next; criteria are not changed in place.`);
229
+ const ceiling = io.normalize(unit.paths), outside = allowedPaths.filter(path => !ceiling.some(prefix => within(path, prefix)));
230
+ if (!allowedPaths.length || outside.length) throw Error(`Unit ${unit.id} may change only ${ceiling.join(', ')}. ${allowedPaths.length ? `Outside that: ${outside.join(', ')}.` : 'Name allowedPaths inside it.'} Paths beyond the unit need a new queue.`);
231
+ return { binding: { id: queue.id, unit: unit.id, definitionHash: queue.definitionHash, attempt: current.runs.length + 1 }, drift: source => drift(view, source, ceiling) };
232
+ }
233
+
234
+ // A run is noted before its record is written, so a lost record still holds its unit's place. A
235
+ // start that fails takes the note back; if that fails too, the unit reads halted.
236
+ export function noteStart(io, binding, runId) {
237
+ const queue = load(io, binding.id);
238
+ (queue.started ??= []).push({ unit: binding.unit, runId, attempt: binding.attempt, time: new Date().toISOString(), by: io.session ?? null });
239
+ io.write(queue.id, queue);
240
+ }
241
+ export function dropStart(io, binding, runId) {
242
+ const queue = load(io, binding.id);
243
+ queue.started = (queue.started ?? []).filter(entry => entry.runId !== runId);
244
+ io.write(queue.id, queue);
245
+ }
246
+
247
+ export function decideQueue(io, { queue: id, ...input }) {
248
+ strictObject(input, ['version', 'unit', 'action', 'reason'], 'queue decision');
249
+ if (input.version !== 1 || !['retry', 'skip', 'cancel'].includes(input.action)) throw Error('A decision needs version 1 and action retry, skip or cancel.');
250
+ if (!text(input.reason)) throw Error('A decision needs a reason.');
251
+ const entry = { action: input.action, reason: input.reason, time: new Date().toISOString(), session: io.session ?? null };
252
+ if (input.action === 'cancel') {
253
+ if (input.unit !== undefined) throw Error('cancel closes the whole queue; it takes no unit.');
254
+ // Cancel by ID works for an edited queue: it is the remedy.
255
+ const queue = id === undefined ? resolve(io, id) : stored(io, id);
256
+ if (queue.status === 'cancelled') throw Error(`Queue ${queue.id} is already cancelled.`);
257
+ const active = io.runs().find(run => run.queue?.id === queue.id && open.includes(run.status));
258
+ if (active) throw Error(`Run ${active.id} (unit ${active.queue.unit}) is ${active.status}. Finish or stop it before cancelling the queue.`);
259
+ queue.status = 'cancelled';
260
+ queue.decisions.push(entry);
261
+ io.write(queue.id, queue);
262
+ try { return { ...statusOf(load(io, queue.id), io), recorded: entry }; } catch { return { queueId: queue.id, line: 'cancelled', recorded: entry }; }
263
+ }
264
+ const queue = resolve(io, id), view = queueView(queue, io.runs());
265
+ if (queue.status === 'cancelled') throw Error(`Queue ${queue.id} is already cancelled.`);
266
+ const unit = view.units.find(item => item.id === input.unit), run = unit?.runs.find(item => item.runId === unit.latest);
267
+ if (!unit) throw Error(`Queue ${queue.id} has no unit ${JSON.stringify(input.unit)}.`);
268
+ if (unit.status !== 'halted') throw Error(`Unit ${unit.id} is ${unit.status}; only a halted unit takes a ${input.action} decision.`);
269
+ if (!ended.includes(run.status)) throw Error(`Run ${run.runId} is ${run.status}, not ended. Resume and finish it, or stop it, before deciding.`);
270
+ // The decision is about this run as it stands now.
271
+ Object.assign(entry, { unit: unit.id, afterRun: run.runId, afterStatus: run.status });
272
+ queue.decisions.push(entry);
273
+ io.write(queue.id, queue);
274
+ return { ...statusOf(queue, io), recorded: entry };
275
+ }
276
+
277
+ // For a bound run's results: where the line stands.
278
+ export function queueAdvice(io, binding) {
279
+ try {
280
+ const queue = load(io, binding.id), view = queueView(queue, io.runs()), unit = view.units.find(item => item.id === binding.unit);
281
+ return { ...summary(queue, view), unit: binding.unit, unitStatus: unit?.status ?? 'unknown', next: view.next, command: `queue next --queue ${queue.id}` };
282
+ } catch (error) { return { queueId: binding?.id, unit: binding?.unit, error: error.message }; }
283
+ }
@@ -189,7 +189,7 @@ const unfinished = (run, now) => run.status !== 'complete' && !(run.status === '
189
189
  const endedAs = run => run.status === 'running' ? 'past its time budget' : run.status;
190
190
  // Why a run stopped, in the controller's record: the reason and files logged by the latest status
191
191
  // change. Pause and stop log no reason, and a resume clears an earlier one.
192
- function stopReason(run) {
192
+ export function stopReason(run) {
193
193
  const event = run.history?.findLast(item => ['blocked', 'guard-halt', 'exhausted', 'pause', 'stop', 'resume'].includes(item.type));
194
194
  if (!event || event.type === 'resume') return null;
195
195
  const files = [...(event?.protectedChanges ?? []), ...(event?.outOfScope ?? [])];