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.
- package/.claude-plugin/plugin.json +1 -1
- package/.codex-plugin/plugin.json +1 -1
- package/.cursor-plugin/plugin.json +1 -1
- package/bin/cyc.mjs +55 -7
- package/docs/README.md +2 -0
- package/docs/runtime.md +4 -0
- package/docs/work-queue.md +187 -0
- package/methods/cyc-build/SKILL.md +1 -1
- package/methods/cyc-design/frontend-design/SKILL.md +125 -28
- package/methods/cyc-design/frontend-design/references/color.md +42 -50
- package/methods/cyc-design/frontend-design/references/craft-rules.md +13 -10
- package/methods/cyc-design/frontend-design/references/decision-sheet.md +94 -98
- package/methods/cyc-design/frontend-design/references/experience-review.md +10 -2
- package/methods/cyc-design/frontend-design/references/field-guide.md +439 -0
- package/methods/cyc-design/frontend-design/references/generic-tells.md +82 -33
- package/methods/cyc-design/frontend-design/references/layout-archetypes.md +5 -5
- package/methods/cyc-design/frontend-design/references/patterns.md +108 -0
- package/methods/cyc-design/frontend-design/references/reference-standards.md +118 -22
- package/methods/cyc-design/frontend-design/references/typography.md +59 -44
- package/methods/cyc-design/frontend-design/references/visual-material.md +40 -7
- package/methods/cyc-design/frontend-design/scripts/contrast.mjs +1 -1
- package/methods/cyc-design/frontend-design/scripts/first-screen.mjs +911 -0
- package/methods/cyc-design/frontend-design/scripts/photo-text.mjs +230 -0
- package/methods/cyc-verify/SKILL.md +1 -1
- package/package.json +6 -1
- package/plugin.json +1 -1
- package/scripts/hub-page.mjs +275 -0
- package/scripts/hub.mjs +139 -0
- package/scripts/queue-board.mjs +287 -0
- package/scripts/queue.mjs +283 -0
- package/scripts/run-gate.mjs +1 -1
- package/scripts/runtime.mjs +248 -13
- package/scripts/source-snapshot.mjs +1 -1
- package/scripts/work-review.mjs +1 -1
- package/skills/cyc/SKILL.md +8 -0
- package/skills/cyc/references/playbooks/plan.md +2 -0
package/scripts/hub.mjs
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { connect } from 'node:net';
|
|
3
|
+
import { createHash } from 'node:crypto';
|
|
4
|
+
import { existsSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
|
|
5
|
+
import { basename, resolve } from 'node:path';
|
|
6
|
+
import { queueCommand, readRun } from './runtime.mjs';
|
|
7
|
+
import { hubPage } from './hub-page.mjs';
|
|
8
|
+
|
|
9
|
+
// The hub: a page on this machine where a person watches a work queue being worked. It reads what
|
|
10
|
+
// the controller already records (queue status, the board, run histories) each time it is asked,
|
|
11
|
+
// through commands that take no lock, and writes nothing. Reasoning and limits:
|
|
12
|
+
// docs/context/work-queue.md.
|
|
13
|
+
|
|
14
|
+
// A run's history in words a person follows. Events with no entry here are bookkeeping.
|
|
15
|
+
const events = {
|
|
16
|
+
started: () => 'started work',
|
|
17
|
+
handoff: event => event.status === 'passed' ? `finished ${{ scout: 'planning', build: 'building', verify: 'checking', deliver: 'the handoff' }[event.stage] ?? event.stage}` : `stopped at ${event.stage}: ${event.status}`,
|
|
18
|
+
'test-proof': event => event.passed ? 'proved its new tests fail on the old code' : 'could not prove its new tests',
|
|
19
|
+
verification: event => `ran the project's checks: ${event.passed ? 'passed' : 'failed'}`,
|
|
20
|
+
'review-recorded': event => `recorded a ${event.reviewer === 'peer' ? 'review by another agent' : 'review'}`,
|
|
21
|
+
'guard-halt': event => `halted: files outside its area changed${event.outOfScope?.length ? ` (${event.outOfScope.slice(0, 3).join(', ')})` : ''}`,
|
|
22
|
+
'attempt-failed': event => `an attempt failed${event.stage ? ` at ${event.stage}` : ''}`,
|
|
23
|
+
exhausted: () => 'ran out of attempts',
|
|
24
|
+
blocked: () => 'is blocked and needs a person',
|
|
25
|
+
retry: event => `went back to ${event.stage}`,
|
|
26
|
+
pause: () => 'was paused', resume: () => 'was resumed', stop: () => 'was stopped',
|
|
27
|
+
complete: () => 'completed'
|
|
28
|
+
};
|
|
29
|
+
const stages = { scout: 'planning', build: 'building', verify: 'checking', deliver: 'handing off' };
|
|
30
|
+
const queueId = /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/, runId = /\brun [a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}\b/g;
|
|
31
|
+
|
|
32
|
+
// The queues this project holds: a folder named by a queue ID whose record carries the same ID.
|
|
33
|
+
function queuesIn(root) {
|
|
34
|
+
const folder = resolve(root, '.cyc/queues');
|
|
35
|
+
if (!existsSync(folder)) return [];
|
|
36
|
+
return readdirSync(folder, { withFileTypes: true }).filter(entry => entry.isDirectory() && queueId.test(entry.name)).flatMap(entry => {
|
|
37
|
+
try {
|
|
38
|
+
const queue = JSON.parse(readFileSync(resolve(folder, entry.name, 'queue.json'), 'utf8'));
|
|
39
|
+
return queue.id === entry.name ? [{ id: queue.id, goal: String(queue.definition.goal), createdAt: String(queue.createdAt), cancelled: queue.status === 'cancelled' }] : [];
|
|
40
|
+
} catch { return []; }
|
|
41
|
+
}).sort((a, b) => a.createdAt < b.createdAt ? -1 : 1);
|
|
42
|
+
}
|
|
43
|
+
// With no queue named: the open one. When several are open or one cannot be read, the one being
|
|
44
|
+
// worked, then a halted one, then a ready one; otherwise the last one created.
|
|
45
|
+
function chosen(root, queues) {
|
|
46
|
+
try { return queueCommand(root, 'status', {}).queueId; } catch { /* none open, several open, or one unreadable */ }
|
|
47
|
+
const lines = queues.filter(queue => !queue.cancelled).map(queue => { try { return [queue.id, queueCommand(root, 'status', { queue: queue.id }).line]; } catch { return [queue.id, null]; } });
|
|
48
|
+
for (const line of ['in-progress', 'halted', 'ready']) { const hit = lines.findLast(item => item[1] === line); if (hit) return hit[0]; }
|
|
49
|
+
return (queues.findLast(queue => !queue.cancelled) ?? queues.at(-1)).id;
|
|
50
|
+
}
|
|
51
|
+
// Who a board label names. The board prints these labels; the hub turns them back into a speaker.
|
|
52
|
+
function speaker(label) {
|
|
53
|
+
const reviewer = /^reviewer of (\S+)/.exec(label), unit = /^unit (\S+)/.exec(label), relayed = /relayed by (.+)$/.exec(label);
|
|
54
|
+
return reviewer ? { role: 'reviewer', unit: reviewer[1] } : unit ? { role: 'builder', unit: unit[1] } : { role: 'person', ...(relayed ? { relayedBy: relayed[1] } : {}) };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// Everything the page shows, read fresh. `wanted` picks a queue.
|
|
58
|
+
export function hubState(root, wanted) {
|
|
59
|
+
root = realpathSync(root);
|
|
60
|
+
const queues = queuesIn(root), base = { project: basename(root), at: new Date().toISOString(), queues };
|
|
61
|
+
if (!queues.length) return { ...base, queue: null };
|
|
62
|
+
const id = wanted ?? chosen(root, queues), known = queues.find(queue => queue.id === id);
|
|
63
|
+
let status;
|
|
64
|
+
try { status = queueCommand(root, 'status', { queue: id }); } catch (error) { return { ...base, queue: { id, goal: known?.goal ?? null, error: error.message } }; }
|
|
65
|
+
let board = { messages: [], seats: [] }, boardError = status.board?.error ?? null;
|
|
66
|
+
if (!boardError) try { board = queueCommand(root, 'board', { queue: id }); } catch (error) { boardError = error.message; }
|
|
67
|
+
const seats = board.seats.filter(seat => ['active', 'done'].includes(seat.state));
|
|
68
|
+
const addressee = to => to === 'person' ? { role: 'person' } : to === 'all' ? { role: 'all' } : to.startsWith('seat:') ? { role: 'reviewer', unit: board.seats.find(seat => seat.seat === to.slice(5))?.unit ?? null } : { role: 'builder', unit: to };
|
|
69
|
+
const activity = [];
|
|
70
|
+
const units = status.units.map(unit => {
|
|
71
|
+
// The run that decides the unit: one that has not ended, whichever attempt it is.
|
|
72
|
+
const run = unit.runs.find(attempt => attempt.runId === unit.latest) ?? unit.runs.at(-1), seat = seats.find(entry => entry.unit === unit.id), working = unit.status === 'in-progress';
|
|
73
|
+
for (const attempt of unit.runs) {
|
|
74
|
+
try { for (const event of readRun(root, attempt.runId).history ?? []) if (events[event.type]) activity.push({ at: event.time, unit: unit.id, text: events[event.type](event) }); }
|
|
75
|
+
catch { /* a run whose record cannot be read shows as missing in its unit's status */ }
|
|
76
|
+
}
|
|
77
|
+
return { id: unit.id, outcome: unit.outcome, status: unit.status, ...(unit.reason ? { reason: unit.reason.replace(runId, 'its run') } : {}), ...(unit.waitsOn ? { waitsOn: unit.waitsOn } : {}),
|
|
78
|
+
...(working && run?.stage ? { doing: stages[run.stage] ?? run.stage } : {}), ...(working && run?.status === 'paused' ? { paused: true } : {}), attempts: unit.runs.length, ...(seat ? { reviewer: seat.state === 'done' ? 'signed off' : 'reviewing' } : {}) };
|
|
79
|
+
});
|
|
80
|
+
const messages = board.messages.map(message => ({ id: message.id, at: message.at, from: speaker(message.from), to: addressee(message.to), kind: message.kind, text: message.text,
|
|
81
|
+
...Object.fromEntries(['replyTo', 'disposition', 'topic', 'about', 'closed', 'answeredLater'].filter(key => message[key] !== undefined).map(key => [key, message[key]])),
|
|
82
|
+
...(message.open !== undefined ? { open: message.open, ...(message.for ? { for: message.for } : {}) } : {}) }));
|
|
83
|
+
// What agents wait on the person for. The person's own question, left open because its unit is
|
|
84
|
+
// gone, is not theirs to answer; nothing waits in a cancelled queue.
|
|
85
|
+
const own = new Set(messages.filter(message => message.from.role === 'person').map(message => message.id));
|
|
86
|
+
return { ...base,
|
|
87
|
+
queue: { id, goal: status.goal, line: status.line, done: status.done, total: status.total, ...(boardError ? { boardError } : {}) },
|
|
88
|
+
units, messages,
|
|
89
|
+
waitingOnYou: status.line === 'cancelled' ? [] : (status.board?.forPerson ?? []).map(message => message.id).filter(item => !own.has(item)),
|
|
90
|
+
activity: activity.sort((a, b) => a.at < b.at ? 1 : -1).slice(0, 40) };
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const headers = type => ({ 'Content-Type': type, 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'no-referrer',
|
|
94
|
+
'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'; img-src data:; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" });
|
|
95
|
+
// Whether something on this machine already answers on the port under a local address. On Windows
|
|
96
|
+
// a listener on every address does not stop a second one on 127.0.0.1, which would then take the
|
|
97
|
+
// first one's local traffic. A closed port can take seconds to refuse there, so silence is free.
|
|
98
|
+
const answers = (port, host) => new Promise(done => {
|
|
99
|
+
const socket = connect({ port, host }), end = taken => { socket.destroy(); done(taken); };
|
|
100
|
+
socket.setTimeout(250, () => end(false)); socket.once('connect', () => end(true)); socket.once('error', () => end(false));
|
|
101
|
+
});
|
|
102
|
+
|
|
103
|
+
// Serves the page and its state on this machine only. Without a port it takes the first free one
|
|
104
|
+
// from 4780 to 4799; a port that was asked for and is taken is an error.
|
|
105
|
+
export function startHub(root, { port } = {}) {
|
|
106
|
+
root = realpathSync(root);
|
|
107
|
+
if (port !== undefined && (!Number.isInteger(port) || port < 0 || port > 65535)) throw new Error('--port is a whole number from 0 to 65535.');
|
|
108
|
+
const text = 'text/plain; charset=utf-8', json = 'application/json; charset=utf-8';
|
|
109
|
+
const server = createServer((request, response) => {
|
|
110
|
+
const send = (code, type, body, more = {}) => { response.writeHead(code, { ...headers(type), ...more }); response.end(body); };
|
|
111
|
+
try {
|
|
112
|
+
// Only this machine's own address: a page elsewhere cannot point a browser's name lookup at the hub.
|
|
113
|
+
const local = [`127.0.0.1:${server.address().port}`, `localhost:${server.address().port}`];
|
|
114
|
+
if (!local.includes(request.headers.host ?? '')) return send(403, text, 'The hub answers only on this machine.');
|
|
115
|
+
if (request.method !== 'GET' && request.method !== 'HEAD') return send(405, text, 'The hub is read-only.', { Allow: 'GET, HEAD' });
|
|
116
|
+
// The address is compared as it was sent and never parsed as a URL: anything else is not found.
|
|
117
|
+
const mark = request.url.indexOf('?'), path = mark < 0 ? request.url : request.url.slice(0, mark);
|
|
118
|
+
if (path === '/') return send(200, 'text/html; charset=utf-8', hubPage);
|
|
119
|
+
if (path !== '/api/state') return send(404, text, 'Not found.');
|
|
120
|
+
const { at, ...state } = hubState(root, (mark < 0 ? null : new URLSearchParams(request.url.slice(mark + 1)).get('queue')) ?? undefined);
|
|
121
|
+
// The tag names what is shown, not when it was read, so a page that already has it is told so.
|
|
122
|
+
const body = JSON.stringify(state), tag = `"${createHash('sha256').update(body).digest('base64url').slice(0, 27)}"`;
|
|
123
|
+
if (request.headers['if-none-match'] === tag) return send(304, json, '', { ETag: tag });
|
|
124
|
+
return send(200, json, `{"at":${JSON.stringify(at)},${body.slice(1)}`, { ETag: tag });
|
|
125
|
+
} catch (error) {
|
|
126
|
+
if (response.headersSent) return response.destroy();
|
|
127
|
+
return send(500, json, JSON.stringify({ error: error.message }));
|
|
128
|
+
}
|
|
129
|
+
});
|
|
130
|
+
return new Promise((done, fail) => {
|
|
131
|
+
const listen = async (candidate, last) => {
|
|
132
|
+
const next = () => candidate < last ? listen(candidate + 1, last) : fail(new Error(port === undefined ? 'Ports 4780 to 4799 are all in use on this machine. Pass a free one with --port.' : `Port ${candidate} is in use. Pass another --port, or leave it out to take a free one.`));
|
|
133
|
+
if (candidate && (await Promise.all(['127.0.0.1', '::1'].map(host => answers(candidate, host)))).some(Boolean)) return next();
|
|
134
|
+
server.once('error', error => error.code === 'EADDRINUSE' ? next() : fail(error));
|
|
135
|
+
server.listen(candidate, '127.0.0.1', () => { server.removeAllListeners('error'); const { address, port: bound } = server.address(); done({ url: `http://127.0.0.1:${bound}/`, host: address, port: bound, project: root, close: () => new Promise(closed => server.close(closed)) }); });
|
|
136
|
+
};
|
|
137
|
+
port === undefined ? listen(4780, 4799) : listen(port, port);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
@@ -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
|
+
}
|