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
@@ -0,0 +1,287 @@
1
+ import { randomBytes } from 'node:crypto';
2
+ import { strictObject, text } from './task-context.mjs';
3
+
4
+ // The queue board: where the agents on a queue, and the person, ask, answer and report. An item
5
+ // (question or finding) is open until an answer names it; who it is for is read from the unit's
6
+ // status each time. Reasoning and limits: docs/context/work-queue.md.
7
+ export const seatLapseMs = 30 * 60 * 1000;
8
+ const limits = { text: 2000, items: 500, about: 20, shown: 20 };
9
+ const kinds = ['question', 'finding', 'answer', 'notice'], topics = ['ready-for-review', 'review-done'];
10
+ const openRun = ['running', 'paused', 'blocked'], gone = ['done', 'skipped', 'cancelled'];
11
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ const item = message => message.kind === 'question' || message.kind === 'finding';
13
+ const builder = from => !!from.unit && !from.seat;
14
+ const time = value => typeof value === 'string' && !Number.isNaN(Date.parse(value));
15
+
16
+ function load(io, id) {
17
+ const board = io.readBoard(id) ?? { schemaVersion: 1, queueId: id, messages: [], seats: [], seen: {} };
18
+ const list = (value, check) => Array.isArray(value) && value.every((entry, index) => record(entry) && check(entry, value[index - 1]));
19
+ if (!record(board) || board.schemaVersion !== 1 || board.queueId !== id || !record(board.seen)
20
+ || !list(board.messages, (entry, before) => Number.isInteger(entry.id) && entry.id > (before?.id ?? 0) && kinds.includes(entry.kind) && record(entry.from) && typeof entry.to === 'string' && typeof entry.text === 'string' && time(entry.at))
21
+ || !list(board.seats, entry => typeof entry.id === 'string' && typeof entry.runId === 'string' && typeof entry.unit === 'string' && Array.isArray(entry.keys) && time(entry.takenAt) && (entry.seenAt === undefined || time(entry.seenAt)))) throw Error(`The board of queue ${id} is not a version 1 board record.`);
22
+ return board;
23
+ }
24
+ const answers = (board, message) => board.messages.filter(entry => entry.kind === 'answer' && entry.replyTo === message.id);
25
+ const closing = (board, message) => answers(board, message)[0];
26
+ // A question its asker closed with an assumption still takes the answer it was waiting for, once:
27
+ // a person often answers after an agent has gone on. It holds no unit meanwhile.
28
+ const awaitsLate = (board, message) => { const given = answers(board, message); return message.kind === 'question' && given.length === 1 && given[0].disposition === 'assumed'; };
29
+ const lateAnswer = (board, message) => { const given = answers(board, message); return given[0]?.disposition === 'assumed' ? given[1] : undefined; };
30
+ const isOpen = (board, message) => item(message) && !closing(board, message);
31
+ const unitNamed = (view, id) => ['person', 'all'].includes(id) ? undefined : view.units.find(entry => entry.id === id);
32
+ // Nobody answers for a unit that is done, skipped or cancelled: the person does.
33
+ function forWhom(message, view) {
34
+ const unit = unitNamed(view, message.to);
35
+ return unit && gone.includes(unit.status) ? 'person' : message.to;
36
+ }
37
+ const label = from => from.person ? `person${from.relayedBy ? `, relayed by ${from.relayedBy}` : ''}` : from.seat ? `reviewer of ${from.unit} (seat ${from.seat})` : `unit ${from.unit}`;
38
+ const brief = (message, board) => {
39
+ const answer = board && item(message) ? closing(board, message) : null;
40
+ return { id: message.id, kind: message.kind, from: label(message.from), to: message.to, text: message.text,
41
+ ...Object.fromEntries(['about', 'replyTo', 'disposition', 'topic', 'sourceHash', 'at'].filter(key => message[key] !== undefined).map(key => [key, message[key]])),
42
+ ...(answer ? { closed: { by: label(answer.from), text: answer.text, ...(answer.disposition ? { disposition: answer.disposition } : {}) } } : {}),
43
+ ...(answer && lateAnswer(board, message) ? { answeredLater: { by: label(lateAnswer(board, message).from), text: lateAnswer(board, message).text } } : {}) };
44
+ };
45
+
46
+ // The reviewer's sign-off stands until the builder asks for another look.
47
+ function signedOff(board, seat) {
48
+ const signed = board.messages.findLast(entry => entry.from.seat === seat.id && entry.topic === 'review-done'), asked = board.messages.findLast(entry => entry.topic === 'ready-for-review' && entry.to === `seat:${seat.id}`);
49
+ return { signed: signed && (!asked || signed.id > asked.id) ? signed : null, asked };
50
+ }
51
+ // Active until the reviewer signs off, gives it up, goes quiet for 30 minutes, or the run ends.
52
+ function seatState(board, seat, view, now) {
53
+ if (seat.releasedAt) return { state: 'released' };
54
+ const run = view.runs.find(entry => entry.id === seat.runId);
55
+ if (!run || !openRun.includes(run.status)) return { state: 'ended' };
56
+ const { signed, asked } = signedOff(board, seat);
57
+ if (signed) return { state: 'done' };
58
+ const last = Math.max(Date.parse(seat.takenAt), Date.parse(seat.seenAt ?? seat.takenAt), ...board.messages.filter(entry => entry.from.seat === seat.id).map(entry => Date.parse(entry.at)), asked ? Date.parse(asked.at) : 0);
59
+ return now - last > seatLapseMs ? { state: 'lapsed' } : { state: 'active', lapsesAt: new Date(last + seatLapseMs).toISOString() };
60
+ }
61
+ const heldSeat = (board, runId, view, now) => board.seats.findLast(seat => seat.runId === runId && ['active', 'done'].includes(seatState(board, seat, view, now).state));
62
+ // Who is calling: the session the host reports, or --session when the host reports none.
63
+ export const callerKeys = io => io.session ? io.keysOf(io.session) : io.given ? io.keysOf(io.given) : [];
64
+ const ownersOf = run => [run.session, run.execution?.conversationId, run.execution?.gateSession].filter(Boolean);
65
+ // A seat belongs to the conversation that took it.
66
+ function seatOf(io, board, queue, id) {
67
+ const seat = board.seats.find(entry => entry.id === id);
68
+ if (!seat) throw Error(`Queue ${queue.id} has no seat ${JSON.stringify(id)}.`);
69
+ if (!callerKeys(io).some(key => seat.keys.includes(key))) throw Error(`Seat ${seat.id} belongs to conversation ${seat.session}; only it uses the seat.`);
70
+ return seat;
71
+ }
72
+
73
+ // With neither run nor seat it is the person; a conversation working here is marked as relaying.
74
+ function authorOf(io, board, queue, view, author, now) {
75
+ if (author.run) {
76
+ const run = author.run;
77
+ if (run.queue?.id !== queue.id) throw Error(`Run ${run.id} is not bound to queue ${queue.id}.`);
78
+ if (!openRun.includes(run.status)) throw Error(`Run ${run.id} is ${run.status}; only a run that has not ended posts for its unit.`);
79
+ return { unit: run.queue.unit, runId: run.id };
80
+ }
81
+ if (author.seat !== undefined) {
82
+ const seat = seatOf(io, board, queue, author.seat), { state } = seatState(board, seat, view, now);
83
+ if (!['active', 'done'].includes(state)) throw Error(`Seat ${seat.id} is ${state}; take a new one with queue next --seat review.`);
84
+ return { unit: seat.unit, seat: seat.id, runId: seat.runId };
85
+ }
86
+ const keys = callerKeys(io), mine = list => list.some(key => keys.includes(key));
87
+ const run = view.runs.find(entry => openRun.includes(entry.status) && mine(ownersOf(entry))), seat = board.seats.find(entry => mine(entry.keys) && ['active', 'done'].includes(seatState(board, entry, view, now).state));
88
+ return { person: true, ...(run ? { relayedBy: `unit ${run.queue.unit}` } : seat ? { relayedBy: `reviewer of ${seat.unit}` } : {}) };
89
+ }
90
+ // Whether a unit builds on another, directly or through other units.
91
+ const buildsOn = (view, id, other, seen = new Set()) => { const unit = view.units.find(entry => entry.id === id); return !!unit && !seen.has(id) && (seen.add(id), unit.dependsOn.some(next => next === other || buildsOn(view, next, other, seen))); };
92
+ // An answer given after an assumption, when the unit that assumed is no longer running: the units
93
+ // that build on that unit's work are the ones who need it.
94
+ const lateForGone = (board, view, message) => { const question = message.kind === 'answer' && board.messages.find(entry => entry.id === message.replyTo); return !!question && lateAnswer(board, question) === message && forWhom(message, view) === 'person' && message.to !== 'person'; };
95
+ const sameAuthor = (a, b) => a.person ? !!b.person : a.seat ? a.seat === b.seat : builder(b) && a.unit === b.unit;
96
+
97
+ export function postMessage(io, { queue, view }, input, author = {}) {
98
+ strictObject(input, ['version', 'to', 'kind', 'text', 'about', 'replyTo', 'disposition', 'topic', 'sourceHash'], 'board message');
99
+ if (input.version !== 1 || !kinds.includes(input.kind)) throw Error(`A message needs version 1 and a kind: ${kinds.join(', ')}.`);
100
+ if (!text(input.text) || input.text.length > limits.text) throw Error(`A message needs text of at most ${limits.text} characters. Point to a file for more.`);
101
+ if (input.about !== undefined && (!Array.isArray(input.about) || input.about.length > limits.about || input.about.some(path => !text(path)))) throw Error(`about lists up to ${limits.about} file paths.`);
102
+ const absent = (...keys) => { const extra = keys.filter(key => input[key] !== undefined); if (extra.length) throw Error(`A ${input.kind}${input.topic ? ` (${input.topic})` : ''} does not take ${extra.join(' or ')}.`); };
103
+ const unitOf = id => unitNamed(view, id);
104
+ const sourceHash = author.seat !== undefined || input.topic ? io.sourceHash() : undefined;
105
+ return io.lockBoard(queue.id, () => {
106
+ const board = load(io, queue.id), now = io.now(), from = authorOf(io, board, queue, view, author, now);
107
+ let to = input.to;
108
+ if (input.topic !== 'review-done') absent('sourceHash');
109
+ if (from.relayedBy && input.kind !== 'answer') throw Error(`This conversation works on this queue as ${from.relayedBy}. Post with --run or --seat.`);
110
+ if (input.kind === 'question') {
111
+ absent('replyTo', 'disposition', 'topic');
112
+ if (to !== 'person' && !unitOf(to)) throw Error('A question needs one addressee: a unit of this queue, or person.');
113
+ if (builder(from) && to === from.unit) throw Error('A unit does not ask itself. Address another unit or person.');
114
+ } else if (input.kind === 'finding') {
115
+ absent('replyTo', 'disposition', 'topic');
116
+ if (builder(from)) throw Error('A finding comes from a review seat or from the person. A builder asks a question or posts a notice.');
117
+ if (!unitOf(to) || from.seat && to !== from.unit) throw Error(from.seat ? `Seat ${from.seat} reviews unit ${from.unit}; its findings are addressed to that unit.` : 'A finding is addressed to one unit of this queue.');
118
+ } else if (input.kind === 'notice') {
119
+ absent('replyTo', 'disposition');
120
+ if (input.topic !== undefined && !topics.includes(input.topic)) throw Error(`A notice's topic is ${topics.join(' or ')}, or left out.`);
121
+ if (input.topic === 'review-done') {
122
+ if (!from.seat) throw Error('Only a review seat posts review-done.');
123
+ if (input.sourceHash !== sourceHash) throw Error(`review-done needs sourceHash: the source you read. ${input.sourceHash ? 'It changed since then' : 'It is missing'}; the source is now ${sourceHash}.`);
124
+ to = from.unit;
125
+ } else if (input.topic === 'ready-for-review') {
126
+ const seat = builder(from) ? heldSeat(board, from.runId, view, now) : null;
127
+ if (!seat) throw Error(builder(from) ? 'No reviewer holds a seat on this unit. A second session takes one with queue next --seat review.' : 'Only the unit\'s builder posts ready-for-review.');
128
+ to = `seat:${seat.id}`;
129
+ } else if (!['person', 'all'].includes(to) && !unitOf(to)) throw Error('A notice is addressed to a unit of this queue, person, or all.');
130
+ } else {
131
+ absent('topic', 'to');
132
+ const target = board.messages.find(entry => entry.id === input.replyTo);
133
+ const late = !!target && awaitsLate(board, target);
134
+ if (!target || !isOpen(board, target) && !late) throw Error(`Message ${JSON.stringify(input.replyTo)} is not an open question or finding of this queue.`);
135
+ const owner = forWhom(target, view);
136
+ if (late && (sameAuthor(target.from, from) || from.relayedBy === `unit ${target.from.unit}`)) throw Error(`You closed question ${target.id} with an assumption. Whoever it was for may still answer it; you cannot close it again, or answer it for them. If the person told you their answer, say so in a notice.`);
137
+ if (from.relayedBy && (target.kind !== 'question' || owner !== 'person')) throw Error(`This conversation works on this queue as ${from.relayedBy}. As the person it may only relay their answer to a question that waits for them; message ${target.id} is not one.`);
138
+ if (sameAuthor(target.from, from)) {
139
+ const allowed = target.kind === 'question' ? ['assumed', 'withdrawn'] : ['withdrawn'];
140
+ if (!allowed.includes(input.disposition)) throw Error(`Closing your own ${target.kind} needs disposition ${allowed.join(' or ')}.`);
141
+ } else if (from.person || builder(from) && owner === from.unit) {
142
+ if (target.kind === 'finding' ? !['fixed', 'declined'].includes(input.disposition) : input.disposition !== undefined) throw Error(target.kind === 'finding' ? 'An answer to a finding needs disposition fixed or declined.' : 'An answer to a question takes no disposition.');
143
+ } else throw Error(`Message ${target.id} is for ${owner === 'person' ? 'the person' : `unit ${owner}`}. Only they, or whoever posted it, may close it.`);
144
+ to = target.from.person ? 'person' : target.from.seat ? `seat:${target.from.seat}` : target.from.unit;
145
+ }
146
+ // A full board still takes answers and the two review notices.
147
+ if (input.kind !== 'answer' && !input.topic && board.messages.filter(entry => entry.kind !== 'answer').length >= limits.items) throw Error(`This board holds ${limits.items} messages. Answers are still accepted; new questions, findings and notices are not.`);
148
+ const message = { id: (board.messages.at(-1)?.id ?? 0) + 1, at: new Date(now).toISOString(), from, to, kind: input.kind, text: input.text,
149
+ ...Object.fromEntries(['about', 'replyTo', 'disposition', 'topic'].filter(key => input[key] !== undefined).map(key => [key, input[key]])), ...(sourceHash ? { sourceHash } : {}) };
150
+ board.messages.push(message);
151
+ io.writeBoard(queue.id, board);
152
+ const owner = forWhom(message, view);
153
+ return { queueId: queue.id, posted: brief(message), ...(owner !== message.to ? { note: lateForGone(board, view, message) ? `Unit ${message.to} is ${unitOf(message.to).status}. This answer is shown to the units that build on it, and on the board.` : `Unit ${message.to} is ${unitOf(message.to).status}, so this is for the person. It shows in queue status.` } : {}) };
154
+ });
155
+ }
156
+
157
+ function inbox(board, view, who) {
158
+ const key = who.seat ? `seat:${who.seat}` : `run:${who.runId}`, seen = board.seen[key] ?? 0;
159
+ const own = from => who.seat ? from.seat === who.seat : builder(from) && from.unit === who.unit;
160
+ const mine = message => !own(message.from) && (message.to === 'all' || (who.seat ? message.to === key : forWhom(message, view) === who.unit || lateForGone(board, view, message) && buildsOn(view, who.unit, message.to)));
161
+ const fresh = board.messages.filter(message => message.id > seen && mine(message) && !(item(message) && closing(board, message) && own(closing(board, message).from)));
162
+ return { key, fresh, last: board.messages.at(-1)?.id ?? 0 };
163
+ }
164
+ // `mark` moves the read mark; without it nothing is written.
165
+ export function deliver(io, { queue, view }, who, { mark = false, run } = {}) {
166
+ const read = board => {
167
+ const { key, fresh, last } = inbox(board, view, who);
168
+ const hold = run && openRun.includes(run.status) ? holds(board, view, run, io.now()) : [];
169
+ return { key, last, moved: (board.seen[key] ?? 0) !== last, result: fresh.length || hold.length ? {
170
+ ...(fresh.length ? { new: fresh.slice(-limits.shown).map(message => brief(message, board)), ...(fresh.length > limits.shown ? { earlier: fresh.length - limits.shown } : {}) } : {}),
171
+ ...(hold.length ? { hold } : {}),
172
+ note: `${fresh.length ? 'Read these before going on. ' : ''}${hold.length ? 'This unit cannot complete until each hold is cleared. ' : ''}Answer with queue post --queue ${queue.id} ${who.seat ? `--seat ${who.seat}` : `--run ${who.runId}`} --file MESSAGE.json.` } : null };
173
+ };
174
+ const first = read(load(io, queue.id));
175
+ if (!mark || !first.moved && !who.seat) return first.result;
176
+ return io.lockBoard(queue.id, () => {
177
+ const board = load(io, queue.id), again = read(board);
178
+ board.seen[again.key] = again.last;
179
+ // Reading keeps a held seat; it does not bring back a lapsed one.
180
+ const seat = who.seat && board.seats.find(entry => entry.id === who.seat);
181
+ if (seat && seatState(board, seat, view, io.now()).state === 'active') seat.seenAt = new Date(io.now()).toISOString();
182
+ io.writeBoard(queue.id, board);
183
+ return again.result;
184
+ });
185
+ }
186
+
187
+ // What keeps a bound run from completing.
188
+ export function holds(board, view, run, now) {
189
+ const unit = run.queue.unit, out = [];
190
+ for (const message of board.messages) {
191
+ if (!isOpen(board, message)) continue;
192
+ const own = builder(message.from) && message.from.unit === unit;
193
+ if (!own && forWhom(message, view) === unit) out.push({ message: message.id, kind: message.kind, from: label(message.from), text: message.text, clear: `Post {"version":1,"kind":"answer","replyTo":${message.id},${message.kind === 'finding' ? '"disposition":"fixed" or "declined",' : ''}"text":"..."}` });
194
+ else if (own && message.kind === 'question') out.push({ message: message.id, kind: 'question', from: 'this unit', text: message.text, clear: `Wait for the answer with queue wait, or go on: post {"version":1,"kind":"answer","replyTo":${message.id},"disposition":"assumed","text":"what you assumed"}. An answer given later still reaches you.` });
195
+ }
196
+ for (const seat of board.seats) {
197
+ if (seat.runId !== run.id) continue;
198
+ const { state, lapsesAt } = seatState(board, seat, view, now);
199
+ if (state === 'active') out.push({ seat: seat.id, from: `reviewer of ${unit}`, text: 'A reviewer holds the review seat and has not posted review-done.', lapsesAt, clear: 'When the work is ready, post {"version":1,"kind":"notice","topic":"ready-for-review","text":"..."}, then queue wait. The seat also clears on release or after 30 quiet minutes.' });
200
+ }
201
+ return out;
202
+ }
203
+ export const boardHolds = (io, { queue, view }, run) => holds(load(io, queue.id), view, run, io.now());
204
+ export const hasBoard = (io, id) => io.readBoard(id) !== null;
205
+
206
+ export function boardSummary(io, { queue, view }) {
207
+ const board = load(io, queue.id), now = io.now();
208
+ if (!board.messages.length && !board.seats.length) return null;
209
+ const open = board.messages.filter(message => isOpen(board, message)), theirs = message => forWhom(message, view) === 'person';
210
+ const seats = board.seats.map(seat => ({ seat: seat.id, unit: seat.unit, runId: seat.runId, takenAt: seat.takenAt, ...seatState(board, seat, view, now) })).filter(seat => ['active', 'done'].includes(seat.state));
211
+ const said = board.messages.filter(message => message.kind === 'notice' && theirs(message) || message.kind === 'answer' && !message.from.person && (theirs(message) && message.to !== message.from.unit || message.disposition === 'assumed' && theirs(board.messages.find(entry => entry.id === message.replyTo)))).slice(-5).map(message => brief(message));
212
+ return { messages: board.messages.length, open: open.length, forPerson: open.filter(theirs).map(message => brief(message)), ...(said.length ? { latestForPerson: said } : {}), ...(seats.length ? { seats } : {}),
213
+ ...(open.some(theirs) ? { note: 'These wait for the person. Show them to the user and post only their answer. Do not answer for them.' } : {}) };
214
+ }
215
+
216
+ export function assumptions(io, { queue }, units) {
217
+ const board = load(io, queue.id);
218
+ return board.messages.filter(message => message.disposition === 'assumed' && builder(message.from) && units.includes(message.from.unit))
219
+ .map(message => { const question = board.messages.find(entry => entry.id === message.replyTo), later = question && lateAnswer(board, question); return { unit: message.from.unit, question: question?.text ?? null, assumed: message.text, ...(later ? { answeredLater: { by: label(later.from), text: later.text } } : {}) }; });
220
+ }
221
+
222
+ export function readBoard(io, { queue, view }, { unit, open = false } = {}) {
223
+ if (unit !== undefined && !view.units.some(entry => entry.id === unit)) throw Error(`Queue ${queue.id} has no unit ${JSON.stringify(unit)}.`);
224
+ const board = load(io, queue.id), now = io.now();
225
+ const about = message => unit === undefined || message.to === unit || message.from.unit === unit;
226
+ const shown = board.messages.filter(message => about(message) && (!open || isOpen(board, message)));
227
+ return { queueId: queue.id, messages: shown.map(message => ({ ...brief(message, board), ...(item(message) ? { open: isOpen(board, message), ...(isOpen(board, message) && forWhom(message, view) !== message.to ? { for: forWhom(message, view) } : {}) } : {}) })),
228
+ seats: board.seats.map(seat => ({ seat: seat.id, unit: seat.unit, runId: seat.runId, takenAt: seat.takenAt, ...seatState(board, seat, view, now) })) };
229
+ }
230
+ export function seatView(io, { queue, view }, id) {
231
+ const board = load(io, queue.id), seat = seatOf(io, board, queue, id);
232
+ return { who: { seat: seat.id, unit: seat.unit }, seat: { id: seat.id, unit: seat.unit, ...seatState(board, seat, view, io.now()), sourceHash: io.sourceHash() } };
233
+ }
234
+
235
+ export function takeSeat(io, { queue, view }, { seat, session }) {
236
+ if (seat !== 'review') throw Error('The only seat is review: queue next --seat review.');
237
+ if (session !== undefined && !/^[A-Za-z0-9_-]{4,80}$/.test(session)) throw Error('--session is 4 to 80 letters, digits, underscores or dashes.');
238
+ const sessions = [...new Set([session, io.session].filter(Boolean))];
239
+ if (!sessions.length) throw Error('A seat needs the conversation\'s session: pass --session ID.');
240
+ const unit = view.units.find(entry => entry.status === 'in-progress');
241
+ if (!unit) throw Object.assign(Error(`No unit of queue ${queue.id} is in progress, so there is nothing to review. --wait-ms N waits for one.`), { code: 'CYC_NO_UNIT' });
242
+ const run = view.runs.find(entry => entry.id === unit.latest), keys = callerKeys({ ...io, given: session });
243
+ if (sessions.flatMap(io.keysOf).some(key => ownersOf(run).includes(key))) throw Error(`This session builds unit ${unit.id}. Its review seat is for another session.`);
244
+ const source = io.source(), started = run.initialSource?.files ?? {};
245
+ const changed = [...new Set([...Object.keys(started), ...Object.keys(source.files)])].filter(path => started[path] !== source.files[path]).sort();
246
+ const taken = io.lockBoard(queue.id, () => {
247
+ const board = load(io, queue.id), now = io.now(), held = heldSeat(board, run.id, view, now);
248
+ if (held) {
249
+ if (keys.some(key => held.keys.includes(key))) return held;
250
+ throw Error(`The review seat on unit ${unit.id} is held (seat ${held.id}, taken ${held.takenAt}). It frees when its reviewer gives it up${seatState(board, held, view, now).state === 'done' ? '' : ' or goes quiet for 30 minutes'}, or the run ends.`);
251
+ }
252
+ const entry = { id: randomBytes(4).toString('hex'), seat: 'review', unit: unit.id, runId: run.id, session: io.session ?? session, keys, takenAt: new Date(now).toISOString() };
253
+ board.seats.push(entry);
254
+ io.writeBoard(queue.id, board);
255
+ return entry;
256
+ });
257
+ const definition = queue.definition.units.find(entry => entry.id === unit.id);
258
+ return { queueId: queue.id, seat: taken.id, unit: { id: unit.id, outcome: definition.outcome, criteria: definition.criteria, paths: definition.paths }, runId: run.id, sourceHash: source.hash, changed: changed.slice(0, 200), changedTotal: changed.length,
259
+ post: `queue post --queue ${queue.id} --seat ${taken.id}${io.session ? '' : ` --session ${session}`} --file MESSAGE.json`, wait: `queue wait --queue ${queue.id} --seat ${taken.id}${io.session ? '' : ` --session ${session}`}`,
260
+ instruction: `You review unit ${unit.id} while another session builds it. Read the changed files against the criteria. Change no file and start no run. Post each defect as {"version":1,"kind":"finding","to":"${unit.id}","text":"..."}; read answers with queue wait. End with {"version":1,"kind":"notice","topic":"review-done","sourceHash":"<the one you last read>","text":"..."}. To stop early: queue release.` };
261
+ }
262
+
263
+ export function releaseSeat(io, { queue }, { seat: id }) {
264
+ return io.lockBoard(queue.id, () => {
265
+ const board = load(io, queue.id), seat = seatOf(io, board, queue, id);
266
+ if (seat.releasedAt) throw Error(`Seat ${seat.id} was already given up.`);
267
+ seat.releasedAt = new Date(io.now()).toISOString();
268
+ io.writeBoard(queue.id, board);
269
+ return { queueId: queue.id, seat: seat.id, unit: seat.unit, released: true };
270
+ });
271
+ }
272
+
273
+ // The input of one peer receipt for the review a seat led.
274
+ export function boardReview(io, { queue, view }, run, sourceHash) {
275
+ const board = load(io, queue.id), busy = board.seats.find(entry => entry.runId === run.id && seatState(board, entry, view, io.now()).state === 'active');
276
+ if (busy) throw Error(`A reviewer holds the seat on this unit (seat ${busy.id}) and has not signed off. Record the review after its review-done.`);
277
+ const seat = board.seats.findLast(entry => entry.runId === run.id && signedOff(board, entry).signed);
278
+ if (!seat) throw Error(`No reviewer has signed off run ${run.id}. A reviewer ends with a review-done notice; a later ready-for-review needs a new one.`);
279
+ const { signed } = signedOff(board, seat);
280
+ const findings = board.messages.filter(message => message.kind === 'finding' && message.from.seat === seat.id), unanswered = findings.filter(message => isOpen(board, message));
281
+ if (unanswered.length) throw Error(`Findings ${unanswered.map(message => message.id).join(', ')} have no answer. Answer each with disposition fixed or declined first.`);
282
+ if (signed.sourceHash !== sourceHash) throw Error(`The source changed after the reviewer posted review-done (message ${signed.id}). Post ready-for-review and wait for a new review-done.`);
283
+ return { evidence: `Peer review led through the queue board by seat ${seat.id} (session ${seat.session}): ${findings.length} finding${findings.length === 1 ? '' : 's'}, each closed on the board as listed; the reviewer signed off as message ${signed.id} on source ${sourceHash.slice(0, 12)}: ${signed.text}`.slice(0, 4000),
284
+ identity: `review seat ${seat.id}, session ${seat.session}`,
285
+ findings: findings.map(message => { const answer = closing(board, message); return { id: `board-${message.id}`, status: answer.disposition === 'fixed' ? 'resolved' : 'dismissed', evidence: `Finding: ${message.text} | ${answer.disposition} by ${label(answer.from)}: ${answer.text}`.slice(0, 4000) }; }),
286
+ led: { by: 'queue-board', queue: queue.id, seat: seat.id, session: seat.session, signedOff: signed.id, findings: findings.map(message => message.id) } };
287
+ }
@@ -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
+ }