arbiterdesign 0.1.7 → 0.1.9

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 (44) hide show
  1. package/README.md +38 -40
  2. package/dist/area-names.js +120 -0
  3. package/dist/areas.js +131 -0
  4. package/dist/board-types.js +9 -0
  5. package/dist/candidates.js +7 -1
  6. package/dist/commands/areas.js +153 -0
  7. package/dist/commands/candidate.js +4 -2
  8. package/dist/commands/decision.js +100 -0
  9. package/dist/commands/export.js +88 -125
  10. package/dist/commands/init.js +89 -2
  11. package/dist/commands/prompt.js +12 -4
  12. package/dist/commands/publish.js +18 -1
  13. package/dist/commands/record.js +152 -3
  14. package/dist/commands/rename.js +123 -0
  15. package/dist/commands/review.js +469 -76
  16. package/dist/commands/rules.js +8 -1
  17. package/dist/commands/setup.js +1 -0
  18. package/dist/commands/snapshot.js +24 -2
  19. package/dist/commands/sweep.js +1 -1
  20. package/dist/commands/unpublish.js +88 -0
  21. package/dist/comments.js +24 -0
  22. package/dist/handoff.js +283 -0
  23. package/dist/hook.js +80 -0
  24. package/dist/hosted.js +117 -20
  25. package/dist/index.js +93 -24
  26. package/dist/localboard.js +219 -0
  27. package/dist/lock.js +134 -0
  28. package/dist/overlap.js +16 -0
  29. package/dist/pictures.js +4 -0
  30. package/dist/settings.js +107 -0
  31. package/dist/store.js +6 -5
  32. package/dist/verify.js +4 -2
  33. package/dist/wording.js +65 -0
  34. package/dist/work.js +139 -1
  35. package/package.json +3 -2
  36. package/templates/SKILL.md +169 -50
  37. package/templates/board/board.css +2 -0
  38. package/templates/board/board.js +25 -0
  39. package/templates/board/index.html +15 -0
  40. package/templates/fonts/Geist-Variable.woff2 +0 -0
  41. package/templates/fonts/GeistMono-Variable.woff2 +0 -0
  42. package/templates/fonts/OFL.txt +92 -0
  43. package/templates/hooks/arbiter-board.cjs +50 -0
  44. package/templates/review.html +0 -600
@@ -1,17 +1,26 @@
1
1
  "use strict";
2
2
  /**
3
- * `arbiter review` — a local page for judging pending decisions.
3
+ * `arbiter review` — the local board: what's waiting for review, and everything decided.
4
4
  *
5
- * Plain node:http on 127.0.0.1, one HTML file, no framework. Reads and writes
6
- * the same files the CLI does; the page has no state of its own. Stops when
7
- * the user presses Done or Ctrl-C.
5
+ * Plain node:http on 127.0.0.1. The page is built from board/ into templates/board, and its data from
6
+ * the project's files (src/localboard.ts); it reads and writes the same files the CLI does and has no
7
+ * state of its own. It's meant to stay open beside the work: the page redraws when the files
8
+ * change, whoever changed them. Stops a few seconds after its last tab closes, or on Ctrl-C.
9
+ * Each project gets the same address every time (steadyPort), so a tab you kept picks up again
10
+ * when the board restarts, and running it twice opens the one already running.
11
+ *
12
+ * Every answer is added to the handoff (src/handoff.ts) as it's given: what's left for the agent
13
+ * to do in the code, which it takes with your next message or at the next /arbiter. With `json`,
14
+ * an agent is waiting on the page instead, and gets the handoff when the last tab closes.
8
15
  */
9
16
  var __importDefault = (this && this.__importDefault) || function (mod) {
10
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
11
18
  };
12
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.steadyPort = steadyPort;
13
21
  exports.review = review;
14
22
  exports.fromHere = fromHere;
23
+ const node_crypto_1 = __importDefault(require("node:crypto"));
15
24
  const node_fs_1 = __importDefault(require("node:fs"));
16
25
  const node_http_1 = __importDefault(require("node:http"));
17
26
  const node_path_1 = __importDefault(require("node:path"));
@@ -19,65 +28,126 @@ const node_child_process_1 = require("node:child_process");
19
28
  const record_1 = require("./record");
20
29
  const candidate_1 = require("./candidate");
21
30
  const candidates_1 = require("../candidates");
22
- const hosted_1 = require("../hosted");
23
31
  const store_1 = require("../store");
32
+ const lock_1 = require("../lock");
24
33
  const autopublish_1 = require("../autopublish");
25
- const pictures_1 = require("../pictures");
26
- const requests_1 = require("../requests");
27
34
  const work_1 = require("../work");
28
- const request_1 = require("./request");
29
- const PAGE = node_path_1.default.join(__dirname, '..', '..', 'templates', 'review.html');
35
+ const localboard_1 = require("../localboard");
36
+ const areas_1 = require("../areas");
37
+ const settings_1 = require("../settings");
38
+ const rename_1 = require("./rename");
39
+ const decision_1 = require("./decision");
40
+ const remove_1 = require("./remove");
41
+ const handoff_1 = require("../handoff");
42
+ const hook_1 = require("../hook");
43
+ const GRACE = 10_000;
44
+ // Where projects' boards live: below the ports Windows and macOS hand out for outgoing connections,
45
+ // and clear of the usual dev servers. A project whose port is taken tries the next few.
46
+ const STEADY_FROM = 47000;
47
+ const STEADY_SPAN = 1000;
48
+ const STEADY_TRIES = 10;
49
+ /** The same folder on Windows, whatever its case. */
50
+ const sameFolder = (dir) => (process.platform === 'win32' ? node_path_1.default.resolve(dir).toLowerCase() : node_path_1.default.resolve(dir));
51
+ /** This project's board's port: the same every time for the same folder, so its address doesn't change. */
52
+ function steadyPort(root) {
53
+ return STEADY_FROM + (node_crypto_1.default.createHash('sha1').update(sameFolder(root)).digest().readUInt32BE(0) % STEADY_SPAN);
54
+ }
55
+ // Geist, as on arbiter.design. Shipped with the package: the page never loads anything from the network.
56
+ const FONTS = node_path_1.default.join(__dirname, '..', '..', 'templates', 'fonts');
57
+ const FONT_FILES = new Set(['Geist-Variable.woff2', 'GeistMono-Variable.woff2']);
58
+ // The local board's page, built from board/ by `npm run build`.
59
+ const BOARD = node_path_1.default.join(__dirname, '..', '..', 'templates', 'board');
60
+ const BOARD_FILES = { '/': 'index.html', '/board.js': 'board.js', '/board.css': 'board.css' };
61
+ const TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' };
30
62
  function review(opts = {}) {
31
63
  const root = (0, store_1.findRoot)(opts.cwd);
32
64
  const paths = (0, store_1.resolvePaths)(root);
33
65
  const cwd = root;
34
- const state = () => {
35
- const comments = (0, hosted_1.readComments)(paths);
36
- const candidates = (0, candidates_1.readCandidates)(paths).map((c) => ({
37
- ...c,
38
- snapshotUrl: c.snapshot ? `/snapshots/${c.snapshot}` : null,
39
- decisions: (0, candidates_1.decisionsFor)(paths, c.id).map((d) => ({ id: d.id, decision: d.decision, verdict: d.verdict })),
40
- comments: comments.filter((x) => x.candidate_id === c.id),
41
- }));
42
- const byId = new Map(candidates.map((c) => [c.id, c]));
43
- const version = (0, hosted_1.readLinkOrNull)(paths)?.boardVersion ?? null;
44
- const archive = (0, store_1.readArchive)(paths);
45
- // The card a request was made on: its picture, a candidate's or a piece of work's.
46
- const shotOf = (screen) => {
47
- if (screen.startsWith('C-'))
48
- return byId.get(screen)?.snapshotUrl ?? null;
49
- const f = (0, work_1.workSnapshot)(paths, screen);
50
- return f ? `/snapshots/${node_path_1.default.basename(f)}` : null;
51
- };
52
- const active = (0, store_1.readActive)(paths);
53
- return {
54
- project: node_path_1.default.basename(root),
55
- pending: (0, store_1.readPending)(paths).map((d) => ({
56
- ...d,
57
- // The rule a clash is with, while it's still in force: the page offers Follow / Replace / Keep as exception.
58
- againstRule: d.against ? active.filter((r) => r.id === d.against).map((r) => ({ id: r.id, decision: r.decision }))[0] ?? null : null,
59
- candidateName: d.candidate ? byId.get(d.candidate)?.name ?? null : null,
60
- snapshotUrl: d.candidate ? byId.get(d.candidate)?.snapshotUrl ?? null : null,
61
- picture: (0, pictures_1.missingPictures)(paths, [d], candidates)[0] ?? null,
62
- })),
63
- // Open ones to answer; approved ones waiting on the agent — shown so it's clear nothing is lost.
64
- requests: (0, requests_1.readRequests)(paths)
65
- .filter((r) => r.status === 'open' || r.status === 'approved')
66
- .map((r) => ({ ...(0, requests_1.describe)(paths, r, version, archive), snapshotUrl: shotOf(r.screen) })),
67
- candidates,
68
- hosted: (0, hosted_1.readLinkOrNull)(paths)?.shareUrl ?? null,
69
- boardVersion: (0, hosted_1.readLinkOrNull)(paths)?.boardVersion ?? null,
70
- active: active.length,
71
- cap: (0, store_1.readConfig)(paths)?.activeCap ?? store_1.ACTIVE_CAP,
72
- };
73
- };
66
+ // The review queue, and when the agent makes a code change you ask for: when the last tab closes if
67
+ // it's waiting on the page, with your next message if the Claude Code hook is installed, else at the
68
+ // next /arbiter.
69
+ const state = () => (0, localboard_1.reviewState)(paths, opts.json ? 'waiting' : (0, hook_1.hookInstalled)(root) ? 'next-message' : 'arbiter');
74
70
  // Judging twenty items shouldn't mean twenty publishes, so the board is updated once, at the
75
71
  // end. The page writes the same files the CLI does, but doesn't go through its handlers.
72
+ const boardData = () => (0, localboard_1.liveBoard)(paths);
73
+ // What the board is drawn from, as one value that changes when any of it does: the page checks it
74
+ // every few seconds and redraws only then, so work the agent records shows up without a reload.
75
+ // The handoff isn't part of the board, and changes with every answer anyway; nor is .gitignore,
76
+ // which the first answer adds the handoff to.
77
+ const stamp = () => {
78
+ let files = 0;
79
+ let bytes = 0;
80
+ let latest = 0;
81
+ const visit = (f) => {
82
+ let st;
83
+ try {
84
+ st = node_fs_1.default.statSync(f);
85
+ }
86
+ catch {
87
+ return;
88
+ }
89
+ if (st.isDirectory()) {
90
+ for (const e of node_fs_1.default.readdirSync(f))
91
+ if (e !== handoff_1.HANDOFF_NAME && e !== '.gitignore')
92
+ visit(node_path_1.default.join(f, e));
93
+ return;
94
+ }
95
+ files++;
96
+ bytes += st.size;
97
+ latest = Math.max(latest, st.mtimeMs);
98
+ };
99
+ for (const f of [paths.decisions, paths.archiveDir, paths.config])
100
+ visit(f);
101
+ return `${files}.${bytes}.${latest}`;
102
+ };
76
103
  let changed = false;
104
+ // Every answer that went through, in order: the terminal's line about this sitting.
105
+ const answers = [];
106
+ // Decisions removed on a change's page, with where each was, so Undo can put them back while the board is open.
107
+ const removedDecisions = new Map();
108
+ // Each one is handed over as it's given, so the agent can take it while the board stays open.
109
+ const answer = (a) => {
110
+ answers.push(a);
111
+ (0, handoff_1.saveAnswer)(paths, a);
112
+ };
113
+ // What each judgement on the page did, by its queued id, so a misclick can be taken back while the board is open.
114
+ const judged = new Map();
115
+ const judgedAs = (j, a) => {
116
+ judged.set(j.item.id, { j, a });
117
+ answer(a);
118
+ };
119
+ // Each rule removed on the Design rules page, as it was, so Undo can put it back.
120
+ const retired = new Map();
121
+ // The tabs showing the board. Each one says it's there whenever it checks for changes, and says
122
+ // goodbye as it closes; when the last one has gone and none comes back (a reload does), the board stops.
123
+ const pages = new Set();
124
+ let closing = null;
125
+ let finish = () => { };
126
+ const seen = (page) => {
127
+ pages.add(page);
128
+ if (closing)
129
+ clearTimeout(closing);
130
+ closing = null;
131
+ };
132
+ const gone = (page) => {
133
+ pages.delete(page);
134
+ if (!pages.size && !closing)
135
+ closing = setTimeout(() => finish('done'), opts.grace ?? GRACE);
136
+ };
77
137
  return new Promise((resolve) => {
138
+ // One write at a time: the board's own in the order they came, and each against any `arbiter`
139
+ // command the agent runs meanwhile (.arbiter/.lock), so neither writes over the other.
140
+ let writing = Promise.resolve();
78
141
  const server = node_http_1.default.createServer(async (req, res) => {
79
142
  try {
80
- await handle(req, res);
143
+ if (req.method === 'POST' && fromHere(req) && req.url !== '/api/bye') {
144
+ await readBody(req); // read before its turn: the handler gets the same body back
145
+ const turn = writing.then(() => (0, lock_1.withLockAsync)(paths, () => handle(req, res)));
146
+ writing = turn.catch(() => { });
147
+ await turn;
148
+ }
149
+ else
150
+ await handle(req, res);
81
151
  }
82
152
  catch (e) {
83
153
  // A broken requests.json, say: the page shows the message instead of the server dying.
@@ -97,9 +167,16 @@ function review(opts = {}) {
97
167
  return;
98
168
  }
99
169
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
100
- if (req.method === 'GET' && url.pathname === '/') {
101
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
102
- res.end(node_fs_1.default.readFileSync(PAGE, 'utf8'));
170
+ if (req.method === 'GET' && BOARD_FILES[url.pathname]) {
171
+ const file = node_path_1.default.join(BOARD, BOARD_FILES[url.pathname]);
172
+ res.writeHead(200, { 'content-type': TYPES[node_path_1.default.extname(file)], 'cache-control': 'no-cache' });
173
+ node_fs_1.default.createReadStream(file).pipe(res);
174
+ return;
175
+ }
176
+ // Where the board was before the review queue moved into it.
177
+ if (req.method === 'GET' && (url.pathname === '/board' || url.pathname === '/board/')) {
178
+ res.writeHead(301, { location: '/' });
179
+ res.end();
103
180
  return;
104
181
  }
105
182
  // Every write is JSON from this page. A form or a plain-text POST from another site in the same
@@ -113,30 +190,130 @@ function review(opts = {}) {
113
190
  json(res, 200, state());
114
191
  return;
115
192
  }
193
+ if (req.method === 'GET' && url.pathname === '/api/board') {
194
+ json(res, 200, boardData());
195
+ return;
196
+ }
197
+ // DECISIONS.md as it is, for Download on Design rules: the file the agent reads, not a copy of it.
198
+ if (req.method === 'GET' && url.pathname === '/api/decisions') {
199
+ const text = node_fs_1.default.existsSync(paths.decisions) ? node_fs_1.default.readFileSync(paths.decisions, 'utf8') : '';
200
+ res.writeHead(200, { 'content-type': 'text/markdown; charset=utf-8', 'content-disposition': 'attachment; filename="DECISIONS.md"', 'cache-control': 'no-store' });
201
+ res.end(text);
202
+ return;
203
+ }
116
204
  if (req.method === 'POST' && url.pathname === '/api/judge') {
117
205
  const body = JSON.parse(await readBody(req));
118
- const result = (0, record_1.judge)(body.id, { as: body.as, to: body.to, supersedes: body.supersedes, keepBoth: body.keepBoth, cwd });
119
- if (result.exitCode === 0)
206
+ // Read before judging: judging takes it off the queue, and a rule it replaces out of DECISIONS.md.
207
+ const queued = (0, store_1.readPending)(paths);
208
+ const at = queued.findIndex((d) => d.id === body.id);
209
+ const item = queued[at];
210
+ const active = (0, store_1.readActive)(paths);
211
+ const was = active.findIndex((d) => d.id === body.supersedes);
212
+ const result = (0, record_1.judge)(body.id, { as: body.as, to: body.to, supersedes: body.supersedes, keepBoth: body.keepBoth, unverified: body.unverified === true, cwd });
213
+ if (result.exitCode === 0 && item) {
120
214
  changed = true;
215
+ const id = body.as === 'skip' ? undefined : String(result.output.id);
216
+ judgedAs({ item, at, id, ...(was !== -1 && result.output.supersedes === body.supersedes && { replaced: { rule: active[was], at: was } }) }, { kind: 'decision', pending: body.id, as: body.as, id, change: item.change ?? item.decision, to: body.to, follows: body.follows });
217
+ }
121
218
  json(res, 200, { exitCode: result.exitCode, ...result.output });
122
219
  return;
123
220
  }
124
221
  if (req.method === 'POST' && url.pathname === '/api/judge-all') {
125
222
  const body = JSON.parse(await readBody(req));
223
+ const queued = (0, store_1.readPending)(paths);
126
224
  const result = (0, record_1.judgeAll)({ as: body.as, level: body.level, trigger: body.trigger, cwd });
127
225
  if (result.exitCode === 0)
128
226
  changed = true;
227
+ // A partial run still recorded some: each one that went through is an answer. They went in
228
+ // queue order, so the ones that didn't fail line up with what they were recorded as.
229
+ const failed = new Set((result.output.failed ?? []).map((f) => f.id));
230
+ const through = queued.filter((d) => (!body.level || d.level === body.level) && (!body.trigger || d.trigger === body.trigger) && !failed.has(d.id));
231
+ (result.output.judged ?? []).forEach((judgedId, k) => {
232
+ const item = through[k];
233
+ if (!item)
234
+ return;
235
+ const id = body.as === 'skip' ? undefined : judgedId;
236
+ judgedAs({ item, at: queued.indexOf(item), id }, { kind: 'decision', pending: item.id, as: body.as, id, change: item.change ?? item.decision });
237
+ });
129
238
  json(res, 200, { exitCode: result.exitCode, ...result.output });
130
239
  return;
131
240
  }
132
- if (req.method === 'POST' && url.pathname === '/api/request') {
241
+ if (req.method === 'POST' && url.pathname === '/api/undo') {
133
242
  const body = JSON.parse(await readBody(req));
134
- const result = (0, request_1.judgeRequest)(body.id, { as: body.as, to: body.to, why: body.why, cwd });
135
- if (result.exitCode === 0)
243
+ const was = judged.get(body.id);
244
+ if (!was) {
245
+ json(res, 200, { exitCode: 1, status: 'invalid', errors: [`Only what was judged on this board since it started can be undone`] });
246
+ return;
247
+ }
248
+ const result = (0, record_1.unjudge)(was.j, { cwd });
249
+ if (result.exitCode === 0) {
250
+ changed = true;
251
+ judged.delete(body.id);
252
+ answers.splice(answers.indexOf(was.a), 1);
253
+ // A fix the agent has taken may be in the code already: the record is back, the code may not be.
254
+ if (!(0, handoff_1.withdrawAnswer)(paths, was.a) && was.a.as === 'fix')
255
+ result.output.taken = true;
256
+ }
257
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
258
+ return;
259
+ }
260
+ if (req.method === 'POST' && url.pathname === '/api/reword') {
261
+ const body = JSON.parse(await readBody(req));
262
+ const result = (0, record_1.reword)(body.id, body.to, { cwd });
263
+ // The agent may have read the old words already: it hears the new ones as it hears a fix.
264
+ if (result.exitCode === 0) {
136
265
  changed = true;
266
+ answer({ kind: 'reword', id: body.id, to: String(result.output.decision) });
267
+ }
137
268
  json(res, 200, { exitCode: result.exitCode, ...result.output });
138
269
  return;
139
270
  }
271
+ if (req.method === 'POST' && url.pathname === '/api/retire') {
272
+ const body = JSON.parse(await readBody(req));
273
+ const rule = (0, store_1.readActive)(paths).find((d) => d.id === body.id);
274
+ const result = (0, record_1.retire)(body.id, body.why, { cwd });
275
+ if (result.exitCode === 0 && rule) {
276
+ changed = true;
277
+ const a = { kind: 'retire', id: body.id, rule: rule.decision, why: body.why.trim() };
278
+ retired.set(body.id, { rule, id: String(result.output.id), a });
279
+ answer(a);
280
+ }
281
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
282
+ return;
283
+ }
284
+ if (req.method === 'POST' && url.pathname === '/api/unretire') {
285
+ const body = JSON.parse(await readBody(req));
286
+ const was = retired.get(body.id);
287
+ if (!was) {
288
+ json(res, 200, { exitCode: 1, status: 'invalid', errors: [`Only a rule removed on this board since it started can be put back`] });
289
+ return;
290
+ }
291
+ const result = (0, record_1.unretire)(was, { cwd });
292
+ if (result.exitCode === 0) {
293
+ changed = true;
294
+ retired.delete(body.id);
295
+ // Not heard of yet: the agent never hears of it. Heard of: it hears the rule is back.
296
+ if ((0, handoff_1.withdrawRemoval)(paths, body.id))
297
+ answers.splice(answers.indexOf(was.a), 1);
298
+ else
299
+ answer({ kind: 'restore', id: body.id });
300
+ }
301
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
302
+ return;
303
+ }
304
+ // An earlier picture of a piece of work, by its place under .arbiter/work/history/.
305
+ if (req.method === 'GET' && url.pathname.startsWith('/snapshots/history/')) {
306
+ const abs = (0, work_1.historyFile)(paths, decodeURIComponent(url.pathname.slice('/snapshots/'.length)));
307
+ if (!abs) {
308
+ res.writeHead(404);
309
+ res.end();
310
+ return;
311
+ }
312
+ const type = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.svg': 'image/svg+xml' }[node_path_1.default.extname(abs)] ?? 'application/octet-stream';
313
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'max-age=86400', ...PICTURE });
314
+ node_fs_1.default.createReadStream(abs).pipe(res);
315
+ return;
316
+ }
140
317
  if (req.method === 'GET' && url.pathname.startsWith('/snapshots/')) {
141
318
  const file = node_path_1.default.basename(url.pathname);
142
319
  const abs = node_path_1.default.join(file.startsWith('W-') ? (0, work_1.workDir)(paths) : (0, candidates_1.candidatesDir)(paths), file);
@@ -146,57 +323,220 @@ function review(opts = {}) {
146
323
  return;
147
324
  }
148
325
  const type = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.svg': 'image/svg+xml' }[node_path_1.default.extname(file)] ?? 'application/octet-stream';
149
- res.writeHead(200, { 'content-type': type, 'cache-control': 'no-cache' });
326
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-cache', ...PICTURE });
150
327
  node_fs_1.default.createReadStream(abs).pipe(res);
151
328
  return;
152
329
  }
330
+ if (req.method === 'GET' && url.pathname.startsWith('/fonts/')) {
331
+ const file = node_path_1.default.basename(url.pathname);
332
+ if (!FONT_FILES.has(file)) {
333
+ res.writeHead(404);
334
+ res.end();
335
+ return;
336
+ }
337
+ res.writeHead(200, { 'content-type': 'font/woff2', 'cache-control': 'max-age=86400' });
338
+ node_fs_1.default.createReadStream(node_path_1.default.join(FONTS, file)).pipe(res);
339
+ return;
340
+ }
153
341
  if (req.method === 'POST' && url.pathname === '/api/candidate') {
154
342
  const body = JSON.parse(await readBody(req));
155
343
  const result = (0, candidate_1.updateCandidate)(body.id, { state: body.state, why: body.why, keepOthers: body.keepOthers, cwd });
344
+ if (result.exitCode === 0) {
345
+ changed = true;
346
+ const c = (0, candidates_1.readCandidates)(paths).find((x) => x.id === body.id);
347
+ answer({ kind: 'option', id: body.id, name: c?.name ?? body.id, state: body.state });
348
+ }
349
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
350
+ return;
351
+ }
352
+ // Folders in the side nav's Areas. They only arrange the board, so the agent isn't told and the
353
+ // team board isn't republished: the file is saved, and every open tab redraws from it.
354
+ if (req.method === 'POST' && url.pathname === '/api/areas') {
355
+ const r = (0, areas_1.cleanArrangement)(JSON.parse(await readBody(req)));
356
+ if (!r.ok) {
357
+ json(res, 200, { exitCode: 1, status: 'invalid', errors: r.errors });
358
+ return;
359
+ }
360
+ (0, areas_1.writeArrangement)(paths, r.value);
361
+ json(res, 200, { exitCode: 0, arrangement: r.value });
362
+ return;
363
+ }
364
+ // Rename on a change's page: the work and everything filed under it move to the new name, as
365
+ // `arbiter rename` does. The agent hears the new name, so its next decisions don't start a second card.
366
+ if (req.method === 'POST' && url.pathname === '/api/rename') {
367
+ const body = JSON.parse(await readBody(req));
368
+ const result = (0, rename_1.renameWork)(String(body.from ?? ''), String(body.to ?? ''), { cwd, merge: body.merge === true });
369
+ if (result.exitCode === 0) {
370
+ changed = true;
371
+ answer({ kind: 'rename', from: String(result.output.from), to: String(result.output.to) });
372
+ }
373
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
374
+ return;
375
+ }
376
+ // A change's page, on one of its decisions: new words for its Change line; remove it, with Undo while
377
+ // the board is open; or make it a rule. A rule's own words and its removal go through reword and retire.
378
+ if (req.method === 'POST' && url.pathname === '/api/edit-change') {
379
+ const body = JSON.parse(await readBody(req));
380
+ const result = (0, decision_1.editChange)(String(body.id ?? ''), String(body.to ?? ''), { cwd });
156
381
  if (result.exitCode === 0)
157
382
  changed = true;
158
383
  json(res, 200, { exitCode: result.exitCode, ...result.output });
159
384
  return;
160
385
  }
161
- if (req.method === 'POST' && url.pathname === '/api/done') {
386
+ if (req.method === 'POST' && url.pathname === '/api/remove-decision') {
387
+ const body = JSON.parse(await readBody(req));
388
+ const before = (0, store_1.readArchive)(paths);
389
+ const index = before.findIndex((d) => d.id === body.id);
390
+ const result = (0, remove_1.remove)(String(body.id ?? ''), { cwd });
391
+ if (result.exitCode === 0 && index >= 0) {
392
+ changed = true;
393
+ removedDecisions.set(body.id, { entry: before[index], index });
394
+ }
395
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
396
+ return;
397
+ }
398
+ if (req.method === 'POST' && url.pathname === '/api/restore-decision') {
399
+ const body = JSON.parse(await readBody(req));
400
+ const was = removedDecisions.get(body.id);
401
+ if (!was) {
402
+ json(res, 200, { exitCode: 1, status: 'invalid', errors: ['Only a decision removed on this board since it started can be put back'] });
403
+ return;
404
+ }
405
+ const result = (0, decision_1.restoreDecision)(was, { cwd });
406
+ if (result.exitCode === 0) {
407
+ changed = true;
408
+ removedDecisions.delete(body.id);
409
+ }
410
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
411
+ return;
412
+ }
413
+ if (req.method === 'POST' && url.pathname === '/api/promote') {
414
+ const body = JSON.parse(await readBody(req));
415
+ const replacing = body.supersedes ? (0, store_1.readActive)(paths).find((d) => d.id === body.supersedes)?.decision ?? '' : '';
416
+ const result = (0, decision_1.promote)(String(body.id ?? ''), { cwd, keepBoth: body.keepBoth === true, supersedes: body.supersedes || undefined });
417
+ if (result.exitCode === 0) {
418
+ changed = true;
419
+ answer({ kind: 'rule', id: String(result.output.id) });
420
+ // A rule it replaced is out of force: the agent hears that as it hears a rule removed.
421
+ if (result.output.replaced)
422
+ answer({ kind: 'retire', id: String(result.output.replaced), rule: replacing, why: `Replaced by ${result.output.id}` });
423
+ }
424
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
425
+ return;
426
+ }
427
+ // Preferences: written to arbiter.json, which the CLI reads each time it acts, so nothing needs
428
+ // telling. Every open tab redraws from the file.
429
+ if (req.method === 'POST' && url.pathname === '/api/settings') {
430
+ const r = (0, settings_1.saveSettings)(paths, JSON.parse(await readBody(req)));
431
+ json(res, 200, r.ok ? { exitCode: 0, settings: r.settings } : { exitCode: 1, status: 'invalid', errors: r.errors });
432
+ return;
433
+ }
434
+ if (req.method === 'GET' && url.pathname === '/api/stamp') {
435
+ const page = url.searchParams.get('page');
436
+ if (page)
437
+ seen(page);
438
+ json(res, 200, { stamp: stamp() });
439
+ return;
440
+ }
441
+ // Which project's board this is: a second `arbiter review` asks, to open this one instead.
442
+ if (req.method === 'GET' && url.pathname === '/api/who') {
443
+ json(res, 200, { board: 'arbiter', root });
444
+ return;
445
+ }
446
+ if (req.method === 'POST' && url.pathname === '/api/bye') {
447
+ const body = JSON.parse(await readBody(req));
448
+ if (body.page)
449
+ gone(body.page);
162
450
  json(res, 200, { ok: true });
163
- stop();
164
451
  return;
165
452
  }
166
453
  res.writeHead(404);
167
454
  res.end();
168
455
  };
169
- server.listen(opts.port ?? 0, '127.0.0.1', () => {
456
+ // This project's own port, or the next free one after it. Already running there: open that one,
457
+ // unless an agent is waiting on this sitting's handoff, which only a board of its own can give it.
458
+ const place = async () => {
459
+ const steady = steadyPort(root);
460
+ const ports = opts.port !== undefined ? [opts.port] : Array.from({ length: STEADY_TRIES }, (_, i) => steady + i);
461
+ for (const port of ports) {
462
+ if (await listen(server, port))
463
+ return started();
464
+ const there = await whoIsAt(port);
465
+ if (there && sameFolder(there) === sameFolder(root) && !opts.json) {
466
+ const url = `http://127.0.0.1:${port}/`;
467
+ say(`Arbiter review is already open for this project.\n${url}#/review\n`);
468
+ if (opts.open !== false)
469
+ openBrowser(`${url}#/review`);
470
+ return stop('closed');
471
+ }
472
+ }
473
+ if (opts.port === undefined && (await listen(server, 0)))
474
+ return started();
475
+ process.stderr.write(`arbiter: port ${opts.port} is in use.\n`);
476
+ process.exitCode = 1;
477
+ stop('closed');
478
+ };
479
+ const started = () => {
170
480
  const addr = server.address();
171
481
  const url = `http://127.0.0.1:${addr.port}/`;
172
482
  let s;
483
+ let candidates;
173
484
  try {
174
485
  s = state();
486
+ candidates = (0, candidates_1.readCandidates)(paths).length;
175
487
  }
176
488
  catch (e) {
177
489
  process.stderr.write(`arbiter: ${e.message}\n`);
178
490
  process.exitCode = 1;
179
- stop();
491
+ stop('closed');
180
492
  return;
181
493
  }
182
- const asks = s.requests.filter((r) => r.status === 'open').length;
183
- process.stdout.write(`Arbiter review — ${s.pending.length} pending${asks ? ` · ${asks} request${asks === 1 ? '' : 's'}` : ''} · ${s.candidates.length} candidate${s.candidates.length === 1 ? '' : 's'} · ${s.active} of ${s.cap} rules\n${url}\nPress Done in the page, or Ctrl-C here, to stop.\n`);
494
+ // With --json, stdout is the handoff and nothing else; the agent reads it whole.
495
+ say(`Arbiter review — ${s.pending.length} pending · ${candidates} candidate${candidates === 1 ? '' : 's'} · ${s.active} of ${s.cap} rules\n${url}#/review\nClose the tab, or press Ctrl-C here, to stop.\n`);
496
+ // Straight to what's waiting: that's what `review` is opened for.
184
497
  if (opts.open !== false)
185
- openBrowser(url);
498
+ openBrowser(`${url}#/review`);
499
+ };
500
+ place().catch((e) => {
501
+ process.stderr.write(`arbiter: ${e.message}\n`);
502
+ process.exitCode = 1;
503
+ stop('closed');
186
504
  });
505
+ const say = (text) => (opts.json ? process.stderr : process.stdout).write(text);
187
506
  // Browsers keep connections alive; close() alone would wait on them forever.
188
- const stop = () => {
507
+ let stopping = false;
508
+ const stop = (how) => {
509
+ if (stopping)
510
+ return;
511
+ stopping = true;
512
+ if (closing)
513
+ clearTimeout(closing);
514
+ process.removeListener('SIGINT', onSigint);
189
515
  server.close(async () => {
190
516
  if (changed) {
191
517
  const line = await (0, autopublish_1.autoPublish)(cwd);
192
518
  if (line)
193
- process.stdout.write(line + '\n');
519
+ say(line + '\n');
194
520
  }
195
- resolve();
521
+ // An agent waiting on the page gets everything waiting for it, this sitting's and any before,
522
+ // so it's not kept for later as well. Stopped any other way, it may not have been there to
523
+ // read it: it stays. Nobody waiting: the terminal hears about this sitting, and it all stays.
524
+ const waiting = (0, lock_1.withLock)(paths, () => {
525
+ const h = (0, handoff_1.readHandoff)(paths);
526
+ if (opts.json && h && how === 'done')
527
+ (0, handoff_1.clearHandoff)(paths);
528
+ return h;
529
+ });
530
+ if (opts.json && waiting)
531
+ resolve({ ...waiting, finished: how });
532
+ else
533
+ resolve((0, handoff_1.summarize)(answers, how));
196
534
  });
197
535
  server.closeAllConnections();
198
536
  };
199
- process.on('SIGINT', stop);
537
+ finish = stop;
538
+ const onSigint = () => stop('closed');
539
+ process.on('SIGINT', onSigint);
200
540
  });
201
541
  }
202
542
  const LOCAL = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
@@ -214,17 +554,70 @@ function fromHere(req) {
214
554
  return false;
215
555
  }
216
556
  }
557
+ /** Listens on the port if it's free: false when something else has it, or the system keeps it back. */
558
+ function listen(server, port) {
559
+ return new Promise((resolve, reject) => {
560
+ const failed = (e) => {
561
+ server.removeListener('listening', ok);
562
+ if (e.code === 'EADDRINUSE' || e.code === 'EACCES')
563
+ resolve(false);
564
+ else
565
+ reject(e);
566
+ };
567
+ const ok = () => {
568
+ server.removeListener('error', failed);
569
+ resolve(true);
570
+ };
571
+ server.once('error', failed);
572
+ server.once('listening', ok);
573
+ server.listen(port, '127.0.0.1');
574
+ });
575
+ }
576
+ /** The project folder of the Arbiter board on this port, or null if it's something else or nothing answers. */
577
+ function whoIsAt(port) {
578
+ return new Promise((resolve) => {
579
+ const req = node_http_1.default.get({ host: '127.0.0.1', port, path: '/api/who', timeout: 1000 }, (res) => {
580
+ let data = '';
581
+ res.setEncoding('utf8');
582
+ res.on('data', (c) => (data += c));
583
+ res.on('end', () => {
584
+ try {
585
+ const body = JSON.parse(data);
586
+ resolve(res.statusCode === 200 && body.board === 'arbiter' && body.root ? body.root : null);
587
+ }
588
+ catch {
589
+ resolve(null);
590
+ }
591
+ });
592
+ });
593
+ req.on('timeout', () => req.destroy());
594
+ req.on('error', () => resolve(null));
595
+ });
596
+ }
597
+ /**
598
+ * A picture is only ever a picture. An SVG opened in a tab of its own would otherwise run its scripts as
599
+ * the board, and a planted one could reach the API (reword a rule, which the hook then hands the agent).
600
+ * Sandboxed, it runs nothing and has no origin; in the board's <img> it draws as before.
601
+ */
602
+ const PICTURE = { 'content-security-policy': "sandbox; default-src 'none'; img-src data:; style-src 'unsafe-inline'", 'x-content-type-options': 'nosniff' };
217
603
  function json(res, status, body) {
218
604
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
219
605
  res.end(JSON.stringify(body));
220
606
  }
607
+ /** A request's body, read once: the write queue reads it before its turn, the handler after. */
608
+ const bodies = new WeakMap();
221
609
  function readBody(req) {
222
- return new Promise((resolve) => {
223
- let data = '';
224
- req.setEncoding('utf8');
225
- req.on('data', (c) => (data += c));
226
- req.on('end', () => resolve(data));
227
- });
610
+ let body = bodies.get(req);
611
+ if (!body) {
612
+ body = new Promise((resolve) => {
613
+ let data = '';
614
+ req.setEncoding('utf8');
615
+ req.on('data', (c) => (data += c));
616
+ req.on('end', () => resolve(data));
617
+ });
618
+ bodies.set(req, body);
619
+ }
620
+ return body;
228
621
  }
229
622
  function openBrowser(url) {
230
623
  const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';