arbiterdesign 0.1.8 → 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.
@@ -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,70 +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
+ }
30
55
  // Geist, as on arbiter.design. Shipped with the package: the page never loads anything from the network.
31
56
  const FONTS = node_path_1.default.join(__dirname, '..', '..', 'templates', 'fonts');
32
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' };
33
62
  function review(opts = {}) {
34
63
  const root = (0, store_1.findRoot)(opts.cwd);
35
64
  const paths = (0, store_1.resolvePaths)(root);
36
65
  const cwd = root;
37
- const state = () => {
38
- const comments = (0, hosted_1.readComments)(paths);
39
- const candidates = (0, candidates_1.readCandidates)(paths).map((c) => ({
40
- ...c,
41
- snapshotUrl: c.snapshot ? `/snapshots/${c.snapshot}` : null,
42
- decisions: (0, candidates_1.decisionsFor)(paths, c.id).map((d) => ({ id: d.id, decision: d.decision, verdict: d.verdict })),
43
- comments: comments.filter((x) => x.candidate_id === c.id),
44
- }));
45
- const byId = new Map(candidates.map((c) => [c.id, c]));
46
- const version = (0, hosted_1.readLinkOrNull)(paths)?.boardVersion ?? null;
47
- const archive = (0, store_1.readArchive)(paths);
48
- // The card a request was made on: its picture, a candidate's or a piece of work's.
49
- const shotOf = (screen) => {
50
- if (screen.startsWith('C-'))
51
- return byId.get(screen)?.snapshotUrl ?? null;
52
- const f = (0, work_1.workSnapshot)(paths, screen);
53
- return f ? `/snapshots/${node_path_1.default.basename(f)}` : null;
54
- };
55
- const active = (0, store_1.readActive)(paths);
56
- return {
57
- project: node_path_1.default.basename(root),
58
- pending: (0, store_1.readPending)(paths).map((d) => ({
59
- ...d,
60
- // The rule a clash is with, while it's still in force: the page offers Follow / Replace / Keep as exception.
61
- againstRule: d.against ? active.filter((r) => r.id === d.against).map((r) => ({ id: r.id, decision: r.decision }))[0] ?? null : null,
62
- candidateName: d.candidate ? byId.get(d.candidate)?.name ?? null : null,
63
- snapshotUrl: d.candidate ? byId.get(d.candidate)?.snapshotUrl ?? null : null,
64
- picture: (0, pictures_1.missingPictures)(paths, [d], candidates)[0] ?? null,
65
- })),
66
- // Open ones to answer; approved ones waiting on the agent — shown so it's clear nothing is lost.
67
- requests: (0, requests_1.readRequests)(paths)
68
- .filter((r) => r.status === 'open' || r.status === 'approved')
69
- .map((r) => ({ ...(0, requests_1.describe)(paths, r, version, archive), snapshotUrl: shotOf(r.screen) })),
70
- candidates,
71
- hosted: (0, hosted_1.readLinkOrNull)(paths)?.shareUrl ?? null,
72
- boardVersion: (0, hosted_1.readLinkOrNull)(paths)?.boardVersion ?? null,
73
- // The rules in force, for the Rules tab: what's already settled before you make another.
74
- rules: active,
75
- active: active.length,
76
- cap: (0, store_1.readConfig)(paths)?.activeCap ?? store_1.ACTIVE_CAP,
77
- };
78
- };
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');
79
70
  // Judging twenty items shouldn't mean twenty publishes, so the board is updated once, at the
80
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
+ };
81
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
+ };
82
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();
83
141
  const server = node_http_1.default.createServer(async (req, res) => {
84
142
  try {
85
- 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);
86
151
  }
87
152
  catch (e) {
88
153
  // A broken requests.json, say: the page shows the message instead of the server dying.
@@ -102,9 +167,16 @@ function review(opts = {}) {
102
167
  return;
103
168
  }
104
169
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
105
- if (req.method === 'GET' && url.pathname === '/') {
106
- res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
107
- 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();
108
180
  return;
109
181
  }
110
182
  // Every write is JSON from this page. A form or a plain-text POST from another site in the same
@@ -118,30 +190,130 @@ function review(opts = {}) {
118
190
  json(res, 200, state());
119
191
  return;
120
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
+ }
121
204
  if (req.method === 'POST' && url.pathname === '/api/judge') {
122
205
  const body = JSON.parse(await readBody(req));
123
- const result = (0, record_1.judge)(body.id, { as: body.as, to: body.to, supersedes: body.supersedes, keepBoth: body.keepBoth, cwd });
124
- 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) {
125
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
+ }
126
218
  json(res, 200, { exitCode: result.exitCode, ...result.output });
127
219
  return;
128
220
  }
129
221
  if (req.method === 'POST' && url.pathname === '/api/judge-all') {
130
222
  const body = JSON.parse(await readBody(req));
223
+ const queued = (0, store_1.readPending)(paths);
131
224
  const result = (0, record_1.judgeAll)({ as: body.as, level: body.level, trigger: body.trigger, cwd });
132
225
  if (result.exitCode === 0)
133
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
+ });
134
238
  json(res, 200, { exitCode: result.exitCode, ...result.output });
135
239
  return;
136
240
  }
137
- if (req.method === 'POST' && url.pathname === '/api/request') {
241
+ if (req.method === 'POST' && url.pathname === '/api/undo') {
138
242
  const body = JSON.parse(await readBody(req));
139
- const result = (0, request_1.judgeRequest)(body.id, { as: body.as, to: body.to, why: body.why, cwd });
140
- 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) {
141
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
+ }
142
257
  json(res, 200, { exitCode: result.exitCode, ...result.output });
143
258
  return;
144
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) {
265
+ changed = true;
266
+ answer({ kind: 'reword', id: body.id, to: String(result.output.decision) });
267
+ }
268
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
269
+ return;
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
+ }
145
317
  if (req.method === 'GET' && url.pathname.startsWith('/snapshots/')) {
146
318
  const file = node_path_1.default.basename(url.pathname);
147
319
  const abs = node_path_1.default.join(file.startsWith('W-') ? (0, work_1.workDir)(paths) : (0, candidates_1.candidatesDir)(paths), file);
@@ -151,7 +323,7 @@ function review(opts = {}) {
151
323
  return;
152
324
  }
153
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';
154
- res.writeHead(200, { 'content-type': type, 'cache-control': 'no-cache' });
326
+ res.writeHead(200, { 'content-type': type, 'cache-control': 'no-cache', ...PICTURE });
155
327
  node_fs_1.default.createReadStream(abs).pipe(res);
156
328
  return;
157
329
  }
@@ -169,50 +341,202 @@ function review(opts = {}) {
169
341
  if (req.method === 'POST' && url.pathname === '/api/candidate') {
170
342
  const body = JSON.parse(await readBody(req));
171
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 });
172
381
  if (result.exitCode === 0)
173
382
  changed = true;
174
383
  json(res, 200, { exitCode: result.exitCode, ...result.output });
175
384
  return;
176
385
  }
177
- 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);
178
450
  json(res, 200, { ok: true });
179
- stop();
180
451
  return;
181
452
  }
182
453
  res.writeHead(404);
183
454
  res.end();
184
455
  };
185
- 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 = () => {
186
480
  const addr = server.address();
187
481
  const url = `http://127.0.0.1:${addr.port}/`;
188
482
  let s;
483
+ let candidates;
189
484
  try {
190
485
  s = state();
486
+ candidates = (0, candidates_1.readCandidates)(paths).length;
191
487
  }
192
488
  catch (e) {
193
489
  process.stderr.write(`arbiter: ${e.message}\n`);
194
490
  process.exitCode = 1;
195
- stop();
491
+ stop('closed');
196
492
  return;
197
493
  }
198
- const asks = s.requests.filter((r) => r.status === 'open').length;
199
- 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.
200
497
  if (opts.open !== false)
201
- 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');
202
504
  });
505
+ const say = (text) => (opts.json ? process.stderr : process.stdout).write(text);
203
506
  // Browsers keep connections alive; close() alone would wait on them forever.
204
- 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);
205
515
  server.close(async () => {
206
516
  if (changed) {
207
517
  const line = await (0, autopublish_1.autoPublish)(cwd);
208
518
  if (line)
209
- process.stdout.write(line + '\n');
519
+ say(line + '\n');
210
520
  }
211
- 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));
212
534
  });
213
535
  server.closeAllConnections();
214
536
  };
215
- process.on('SIGINT', stop);
537
+ finish = stop;
538
+ const onSigint = () => stop('closed');
539
+ process.on('SIGINT', onSigint);
216
540
  });
217
541
  }
218
542
  const LOCAL = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
@@ -230,17 +554,70 @@ function fromHere(req) {
230
554
  return false;
231
555
  }
232
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' };
233
603
  function json(res, status, body) {
234
604
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
235
605
  res.end(JSON.stringify(body));
236
606
  }
607
+ /** A request's body, read once: the write queue reads it before its turn, the handler after. */
608
+ const bodies = new WeakMap();
237
609
  function readBody(req) {
238
- return new Promise((resolve) => {
239
- let data = '';
240
- req.setEncoding('utf8');
241
- req.on('data', (c) => (data += c));
242
- req.on('end', () => resolve(data));
243
- });
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;
244
621
  }
245
622
  function openBrowser(url) {
246
623
  const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open';