arbiterdesign 0.1.8 → 0.1.10

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 (42) hide show
  1. package/README.md +288 -242
  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 +198 -73
  11. package/dist/commands/invite.js +67 -0
  12. package/dist/commands/publish.js +4 -4
  13. package/dist/commands/record.js +133 -8
  14. package/dist/commands/remove.js +1 -1
  15. package/dist/commands/rename.js +25 -11
  16. package/dist/commands/review.js +458 -78
  17. package/dist/commands/rules.js +22 -3
  18. package/dist/commands/setup.js +1 -0
  19. package/dist/commands/snapshot.js +24 -2
  20. package/dist/commands/sweep.js +1 -1
  21. package/dist/commands/update.js +5 -0
  22. package/dist/comments.js +24 -0
  23. package/dist/format.js +112 -7
  24. package/dist/handoff.js +286 -0
  25. package/dist/hook.js +82 -0
  26. package/dist/hosted.js +50 -17
  27. package/dist/index.js +99 -37
  28. package/dist/localboard.js +219 -0
  29. package/dist/lock.js +134 -0
  30. package/dist/overlap.js +16 -0
  31. package/dist/pictures.js +4 -0
  32. package/dist/settings.js +107 -0
  33. package/dist/store.js +164 -8
  34. package/dist/verify.js +4 -2
  35. package/dist/work.js +110 -1
  36. package/package.json +3 -2
  37. package/templates/SKILL.md +146 -51
  38. package/templates/board/board.css +2 -0
  39. package/templates/board/board.js +25 -0
  40. package/templates/board/index.html +15 -0
  41. package/templates/hooks/arbiter-board.cjs +50 -0
  42. package/templates/review.html +0 -757
@@ -19,6 +19,8 @@ const hosted_1 = require("../hosted");
19
19
  const requests_1 = require("../requests");
20
20
  const update_1 = require("./update");
21
21
  const overlap_1 = require("../overlap");
22
+ const handoff_1 = require("../handoff");
23
+ const lock_1 = require("../lock");
22
24
  function rules(id, opts = {}) {
23
25
  const paths = (0, store_1.resolvePaths)((0, store_1.findRoot)(opts.cwd));
24
26
  opts = { ...opts, config: (0, store_1.readConfig)(paths) };
@@ -75,10 +77,27 @@ function pendingList(pending, opts, paths) {
75
77
  if (opts.json) {
76
78
  const active = (0, store_1.readActive)(paths);
77
79
  const ignore = opts.config?.overlap?.ignore;
80
+ // A Review Board sitting nobody was waiting on: its fixes and approved requests are still to make.
81
+ // Handed over as it is now: once it's made, `done` clears this much, and keeps anything judged since.
82
+ const lastReview = (0, handoff_1.takeHandoff)(paths);
83
+ // The intro, once, at the first /arbiter: until it's been handed out, and while nothing has been judged.
84
+ // Judged decisions mean someone has been through a review, whatever arbiter.json says: the stamp
85
+ // lives in a committed file, and a branch that never merged takes it along.
86
+ const firstRun = !opts.config?.introduced && !archiveAll.length && !active.length;
87
+ // Read again under the lock: a record running at the same time may have just written arbiter.json
88
+ // (where the rules moved to, say), and writing back the copy read earlier would undo it.
89
+ if (firstRun && opts.config) {
90
+ (0, lock_1.withLock)(paths, () => {
91
+ const fresh = (0, store_1.readConfig)(paths);
92
+ if (fresh && !fresh.introduced)
93
+ (0, store_1.writeConfig)(paths, { ...fresh, introduced: (0, store_1.now)() });
94
+ });
95
+ }
78
96
  return JSON.stringify({
79
- // Judged decisions mean someone has been through a review, whatever arbiter.json says: the
80
- // stamp lives in a committed file, and a branch that never merged takes it along.
81
- firstRun: !opts.config?.onboarded && !archiveAll.length && !active.length,
97
+ ...(lastReview && { lastReview: { ...lastReview, file: handoff_1.HANDOFF_FILE, done: 'npx arbiter review --done' } }),
98
+ firstRun,
99
+ // Install couldn't ask (an agent ran it, and the question never got relayed): ask it after the intro.
100
+ askCheckin: !opts.config?.onboarded,
82
101
  checkin: opts.config?.checkin ?? 'feature',
83
102
  ...(0, update_1.updateNotice)(paths),
84
103
  requests: { open, approved },
@@ -11,6 +11,7 @@
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.CHECKINS = void 0;
13
13
  exports.setup = setup;
14
+ exports.appUrl = appUrl;
14
15
  const store_1 = require("../store");
15
16
  exports.CHECKINS = ['feature', 'quiet', 'every'];
16
17
  function setup(opts) {
@@ -9,6 +9,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
9
9
  };
10
10
  Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.snapshotWork = snapshotWork;
12
+ const node_fs_1 = __importDefault(require("node:fs"));
12
13
  const node_path_1 = __importDefault(require("node:path"));
13
14
  const store_1 = require("../store");
14
15
  const hosted_1 = require("../hosted");
@@ -30,9 +31,19 @@ function snapshotWork(name, opts) {
30
31
  const judged = archive.some((d) => mine(d) && (0, hosted_1.publishable)(d));
31
32
  const queued = pending.filter((d) => mine(d) && d.level !== 'polish').length;
32
33
  const polish = [...archive, ...pending].some((d) => mine(d) && d.level === 'polish' && d.verdict !== 'retire');
34
+ // The picture it had becomes an earlier version, so the board can show how the work got here. The same
35
+ // picture attached again isn't a new version.
36
+ const cur = (0, work_1.workSnapshot)(paths, id);
37
+ const same = !opts.capture && !!cur && sameFile(cur, node_path_1.default.resolve(root, opts.file));
38
+ const moved = same ? null : (0, work_1.keepEarlier)(paths, id);
33
39
  const r = opts.capture ? (0, work_1.captureImage)((0, work_1.workDir)(paths), id) : (0, work_1.copyImage)(root, (0, work_1.workDir)(paths), id, opts.file);
34
- if (!r.ok)
40
+ if (!r.ok) {
41
+ (0, work_1.restoreEarlier)(moved);
35
42
  return { exitCode: 1, output: { status: 'failed', error: r.error } };
43
+ }
44
+ // Dated when it was attached: a copy keeps the source file's own time on some systems.
45
+ const now = new Date();
46
+ node_fs_1.default.utimesSync(node_path_1.default.join((0, work_1.workDir)(paths), r.file), now, now);
36
47
  const note = judged
37
48
  ? null
38
49
  : queued
@@ -42,6 +53,17 @@ function snapshotWork(name, opts) {
42
53
  : `no decisions mention "${trigger}" yet — the picture shows once some do`;
43
54
  return {
44
55
  exitCode: 0,
45
- output: { status: 'saved', work: trigger, id, file: node_path_1.default.relative(root, node_path_1.default.join((0, work_1.workDir)(paths), r.file)), ...(note ? { note } : {}) },
56
+ output: { status: 'saved', work: trigger, id, file: node_path_1.default.relative(root, node_path_1.default.join((0, work_1.workDir)(paths), r.file)), ...(moved ? { earlier: node_path_1.default.relative(root, moved.to) } : {}), ...(note ? { note } : {}) },
46
57
  };
47
58
  }
59
+ /** Byte for byte the same image. */
60
+ function sameFile(a, b) {
61
+ try {
62
+ if (node_fs_1.default.statSync(a).size !== node_fs_1.default.statSync(b).size)
63
+ return false;
64
+ return node_fs_1.default.readFileSync(a).equals(node_fs_1.default.readFileSync(b));
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ }
@@ -33,7 +33,7 @@ function sweepCommand(id, opts = {}) {
33
33
  author: opts.author ?? rule.author,
34
34
  class: 'mechanical',
35
35
  change: null,
36
- level: 'polish',
36
+ level: 'pattern',
37
37
  dimension: rule.dimension,
38
38
  decision: rule.decision,
39
39
  rejected: [],
@@ -74,6 +74,7 @@ async function update(opts = {}) {
74
74
  fail('package', `${pm} could not install arbiterdesign@latest — check the network, then re-run`);
75
75
  }
76
76
  // 2. the skill — from the copy that was just installed, so a new template lands, not this one's
77
+ const rulesBefore = (0, store_1.readConfig)(paths)?.decisions;
77
78
  try {
78
79
  if (installed && installed.version !== (0, init_1.selfVersion)()) {
79
80
  (0, node_child_process_1.execFileSync)(process.execPath, [installed.bin, 'init', '--yes', '--skip-install'], { cwd: root, stdio: ['ignore', 'ignore', 'pipe'] });
@@ -87,6 +88,10 @@ async function update(opts = {}) {
87
88
  catch (e) {
88
89
  fail('skill', `init failed: ${e.message.split('\n')[0]}`);
89
90
  }
91
+ // An install from before 0.1.10 took the project's own DECISIONS.md as the rules file; init moves the rules out.
92
+ const rulesAfter = (0, store_1.readConfig)((0, store_1.resolvePaths)(root))?.decisions;
93
+ if (rulesAfter && rulesAfter !== rulesBefore)
94
+ done('rules', (0, store_1.rulesMovedLine)(rulesAfter, true));
90
95
  // 3. the publish workflow, if publish --on-push wrote one: it pins a version
91
96
  const wf = node_path_1.default.join(root, publish_1.WORKFLOW_FILE);
92
97
  if (node_fs_1.default.existsSync(wf)) {
@@ -0,0 +1,24 @@
1
+ "use strict";
2
+ /**
3
+ * The team board's comments, as `arbiter pull` keeps them: .arbiter/comments.json, committed. Pull
4
+ * writes the file (src/hosted.ts); requests and the local board read it. Kept here, apart from the
5
+ * publish code, so reading them doesn't mean depending on it.
6
+ */
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ Object.defineProperty(exports, "__esModule", { value: true });
11
+ exports.readComments = readComments;
12
+ exports.writeComments = writeComments;
13
+ const node_fs_1 = __importDefault(require("node:fs"));
14
+ const node_path_1 = __importDefault(require("node:path"));
15
+ const COMMENTS_FILE = 'comments.json';
16
+ function readComments(paths) {
17
+ const f = node_path_1.default.join(paths.archiveDir, COMMENTS_FILE);
18
+ return node_fs_1.default.existsSync(f) ? JSON.parse(node_fs_1.default.readFileSync(f, 'utf8')) : [];
19
+ }
20
+ /** Every comment on file, minus email addresses: nothing here needs them, and the file is committed. */
21
+ function writeComments(paths, comments) {
22
+ const kept = comments.map(({ author_email: _email, ...c }) => c);
23
+ node_fs_1.default.writeFileSync(node_path_1.default.join(paths.archiveDir, COMMENTS_FILE), JSON.stringify(kept, null, 2) + '\n');
24
+ }
package/dist/format.js CHANGED
@@ -25,6 +25,9 @@ exports.formatEntry = formatEntry;
25
25
  exports.formatGrouped = formatGrouped;
26
26
  exports.parseEntries = parseEntries;
27
27
  exports.activeHeader = activeHeader;
28
+ exports.isRulesFile = isRulesFile;
29
+ exports.notesOf = notesOf;
30
+ exports.formatActive = formatActive;
28
31
  exports.archiveHeader = archiveHeader;
29
32
  exports.pendingHeader = pendingHeader;
30
33
  const schema_1 = require("./schema");
@@ -95,7 +98,8 @@ function parseEntries(md) {
95
98
  cur = null;
96
99
  };
97
100
  for (const raw of lines) {
98
- const line = raw.replace(/\r$/, '');
101
+ // Trailing spaces too (an editor's, or a "- **Rejected:** " typed by hand), as notesOf reads it.
102
+ const line = raw.replace(/\s+$/, '');
99
103
  const h = HEADING.exec(line);
100
104
  if (h) {
101
105
  flush();
@@ -230,9 +234,13 @@ function complete(p) {
230
234
  reworded: p.reworded ?? [],
231
235
  };
232
236
  }
237
+ const HEADER_TITLE = '# Decisions';
238
+ const HEADER_COUNT = /^Active design rules for this project/;
239
+ /** The header's last line starts this way in every version, so a rewrite finds where it ends. */
240
+ const HEADER_LAST = 'Add entries with `npx arbiter record`.';
233
241
  function activeHeader(count, cap) {
234
242
  return [
235
- '# Decisions',
243
+ HEADER_TITLE,
236
244
  '',
237
245
  `Active design rules for this project — ${count} of ${cap}.`,
238
246
  '',
@@ -241,27 +249,124 @@ function activeHeader(count, cap) {
241
249
  'what lost, and why; `Trigger` is the case that prompted it. Superseded rules drop out of',
242
250
  'here and stay in `.arbiter/archive.md`.',
243
251
  '',
244
- 'Add entries with `npx arbiter record`. Edit by hand if you must — the format round-trips.',
252
+ `${HEADER_LAST} Edit by hand if you must: the format round-trips, and notes of your own are kept.`,
245
253
  '',
246
254
  ].join('\n');
247
255
  }
248
- function archiveHeader() {
256
+ /**
257
+ * Whether a rules file is Arbiter's to rewrite: empty, or carrying Arbiter's header or an entry it
258
+ * can read. Anything else (a project's own decision log, say) belongs to someone else.
259
+ */
260
+ function isRulesFile(md) {
261
+ if (!md.trim())
262
+ return true;
263
+ if (md.replace(/\r\n/g, '\n').split('\n').some((l) => HEADER_COUNT.test(l)))
264
+ return true;
265
+ try {
266
+ return parseEntries(md).length > 0;
267
+ }
268
+ catch {
269
+ return false;
270
+ }
271
+ }
272
+ /** A field an entry carries, as it's written. These are re-written from the entry; any other line in it is a note. */
273
+ const ENTRY_LINE = /^- \*\*(Change|Rationale|Rejected|Reworded|Trigger|Scope|Author|Ref|Files|Paths|Expect):\*\*/;
274
+ const DIMENSION_HEADING = new RegExp(`^## (${Object.values(exports.DIMENSION_LABELS).join('|')})$`);
275
+ const ANY_HEADING = /^#{1,6} /;
276
+ /** The lines of Arbiter's header, as every version wrote them. Written fresh, so never kept as notes. */
277
+ const HEADER_LINES = new Set(activeHeader(0, 0).split('\n').filter((l) => l.trim()));
278
+ const isHeaderLine = (l) => HEADER_LINES.has(l) || HEADER_COUNT.test(l) || l.startsWith(HEADER_LAST);
279
+ /**
280
+ * What a person wrote in the rules file, so a rewrite can put it back word for word. It reads the file
281
+ * the way parseEntries does: an entry runs from its heading to the next heading. Its fields are written
282
+ * fresh from the entry; any other line inside it (a remark, a wrapped line, a comment) is a note and
283
+ * moves below the rules, so it can never be read into another rule. Text above the first rule stays
284
+ * above, wherever it sits around Arbiter's header; anything after one goes below. Left out: Arbiter's
285
+ * own header lines, its `## <Dimension>` headings and the entries.
286
+ */
287
+ function notesOf(md) {
288
+ const lines = md.replace(/^/, '').replace(/\r\n/g, '\n').split('\n');
289
+ const top = [];
290
+ const bottom = [];
291
+ let afterRules = false;
292
+ let inEntry = false;
293
+ // An indented item belongs to an entry only under its Rejected or Reworded line, as parseEntries reads it.
294
+ let inList = false;
295
+ let inNotes = false;
296
+ for (let i = 0; i < lines.length; i++) {
297
+ const raw = lines[i];
298
+ const line = raw.replace(/\s+$/, '');
299
+ if (HEADING.test(line)) {
300
+ inEntry = true;
301
+ inList = false;
302
+ afterRules = true;
303
+ inNotes = false;
304
+ continue;
305
+ }
306
+ if (ANY_HEADING.test(line)) {
307
+ inEntry = false;
308
+ inList = false;
309
+ if (DIMENSION_HEADING.test(line)) {
310
+ // Only Arbiter's own: one with a rule under it. A person's "## Content" over their notes stays theirs.
311
+ const next = lines.slice(i + 1).find((l) => l.trim());
312
+ if (next !== undefined && HEADING.test(next.replace(/\s+$/, ''))) {
313
+ afterRules = true;
314
+ inNotes = false;
315
+ continue;
316
+ }
317
+ }
318
+ }
319
+ if (!afterRules && isHeaderLine(line))
320
+ continue;
321
+ const into = afterRules ? bottom : top;
322
+ if (inEntry && line) {
323
+ if (ENTRY_LINE.test(line)) {
324
+ inList = line === '- **Rejected:**' || line === '- **Reworded:**';
325
+ inNotes = false;
326
+ continue;
327
+ }
328
+ if (inList && LIST_ITEM.test(line))
329
+ continue;
330
+ inList = false;
331
+ }
332
+ if (!line) {
333
+ if (inNotes)
334
+ into.push('');
335
+ continue;
336
+ }
337
+ // Notes from two places between the rules come out as two paragraphs, not run together.
338
+ if (!inNotes && into.length && into[into.length - 1] !== '')
339
+ into.push('');
340
+ into.push(raw);
341
+ inNotes = true;
342
+ }
343
+ const trim = (a) => a.join('\n').replace(/^\n+|\n+$/g, '');
344
+ return { top: trim(top), bottom: trim(bottom) };
345
+ }
346
+ /** The rules file as written: header, notes above the rules, the rules, notes below. No notes: as it always was. */
347
+ function formatActive(decisions, cap, notes = { top: '', bottom: '' }) {
348
+ return activeHeader(decisions.length, cap)
349
+ + (notes.top ? '\n' + notes.top + '\n' : '')
350
+ + '\n' + formatGrouped(decisions)
351
+ + (notes.bottom ? (decisions.length ? '\n' : '') + notes.bottom + '\n' : '');
352
+ }
353
+ function archiveHeader(rules = 'DECISIONS.md') {
249
354
  return [
250
355
  '# Decision archive',
251
356
  '',
252
357
  'Every decision ever recorded, in order. A decision you changed your mind about is superseded,',
253
358
  'never rewritten; only `npx arbiter remove` takes an entry out, for a record of something that',
254
- 'never happened. Active rules live in `DECISIONS.md`; this file is for traceability and is never',
359
+ `never happened. Active rules live in \`${rules}\`; this file is for traceability and is never`,
255
360
  'loaded into agent context.',
256
361
  '',
257
362
  ].join('\n');
258
363
  }
259
- function pendingHeader() {
364
+ function pendingHeader(rules = 'DECISIONS.md') {
260
365
  return [
261
366
  '# Pending decisions',
262
367
  '',
263
368
  'Queued by the agent, not yet judged. Review with `npx arbiter review` or `/arbiter` in chat.',
264
- 'Judged entries move to `.arbiter/archive.md` (and `DECISIONS.md` if made a rule); skipped',
369
+ `Judged entries move to \`.arbiter/archive.md\` (and \`${rules}\` if made a rule); skipped`,
265
370
  'entries are dropped. Nothing here is in agent context.',
266
371
  '',
267
372
  ].join('\n');
@@ -0,0 +1,286 @@
1
+ "use strict";
2
+ /**
3
+ * The handoff: what you decided on the local board, for the agent to act on.
4
+ *
5
+ * The page records each answer as you give it. What it can't do is change code, so a Fix, a
6
+ * "Follow D-0009" and an approved request wait on the agent, in .arbiter/last-review.json, added to
7
+ * as you go. So does a rule edited or removed on Design rules, since the agent may have read
8
+ * DECISIONS.md before you changed it. The agent takes it with your next message in Claude Code (a
9
+ * hook tells it: see templates/hooks), or at the next /arbiter anywhere. What it was told is kept
10
+ * beside it (last-review.seen.json), and once it's made, `arbiter review --done` clears just that:
11
+ * anything you judged while it worked stays for next time. An agent waiting on the page
12
+ * (`review --json`) gets it when the last tab closes instead.
13
+ */
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ exports.HANDOFF_NAME = exports.HANDOFF_FILE = exports.decidedAnything = exports.SEEN = exports.FILE = void 0;
19
+ exports.summarize = summarize;
20
+ exports.handoffLine = handoffLine;
21
+ exports.mergeHandoffs = mergeHandoffs;
22
+ exports.saveHandoff = saveHandoff;
23
+ exports.takeHandoff = takeHandoff;
24
+ exports.handoffDone = handoffDone;
25
+ exports.saveAnswer = saveAnswer;
26
+ exports.withdrawAnswer = withdrawAnswer;
27
+ exports.withdrawRemoval = withdrawRemoval;
28
+ exports.clearHandoff = clearHandoff;
29
+ exports.readHandoff = readHandoff;
30
+ const node_fs_1 = __importDefault(require("node:fs"));
31
+ const node_path_1 = __importDefault(require("node:path"));
32
+ const lock_1 = require("./lock");
33
+ exports.FILE = 'last-review.json';
34
+ /** What the agent was told, as it was told it: what `review --done` clears, and nothing judged since. */
35
+ exports.SEEN = 'last-review.seen.json';
36
+ function summarize(answers, finished, at = new Date().toISOString()) {
37
+ const h = { finished, at, confirmed: [], rules: [], fixed: [], skipped: [], declined: [], options: [], reworded: [], removed: [], renamed: [], todo: [], next: '' };
38
+ for (const a of answers) {
39
+ if (a.kind === 'option')
40
+ h.options.push({ id: a.id, name: a.name, state: a.state });
41
+ else if (a.kind === 'rename')
42
+ h.renamed = renames(h.renamed ?? [], [{ from: a.from, to: a.to }]);
43
+ // A rule back in DECISIONS.md after the agent heard it was gone is in force again, as a new one is.
44
+ else if (a.kind === 'restore' || a.kind === 'rule')
45
+ h.rules.push(a.id);
46
+ else if (a.kind === 'reword' || a.kind === 'retire')
47
+ rulesChanged(h, a.kind === 'reword' ? [{ id: a.id, to: a.to }] : [], a.kind === 'retire' ? [{ id: a.id, rule: a.rule, why: a.why }] : []);
48
+ else if (a.kind === 'request') {
49
+ if (a.status === 'declined')
50
+ h.declined.push({ id: a.id, author: a.author, reason: a.reason ?? '' });
51
+ else
52
+ h.todo.push({ kind: 'request', id: a.id, author: a.author, screen: a.screenName, do: a.do ?? '' });
53
+ }
54
+ else if (a.as === 'skip')
55
+ h.skipped.push(a.pending);
56
+ else if (a.as === 'accept')
57
+ h.confirmed.push(a.id ?? a.pending);
58
+ else if (a.as === 'rule')
59
+ h.rules.push(a.id ?? a.pending);
60
+ else {
61
+ h.fixed.push(a.id ?? a.pending);
62
+ const id = a.id ?? a.pending;
63
+ if (a.follows)
64
+ h.todo.push({ kind: 'follow', id, rule: a.follows, to: a.to ?? '' });
65
+ else
66
+ h.todo.push({ kind: 'fix', id, change: a.change ?? '', to: a.to ?? '' });
67
+ }
68
+ }
69
+ h.next = nextStep(h);
70
+ return h;
71
+ }
72
+ /**
73
+ * Only a rule's latest words count, and none for a rule removed since. Those go with the removal,
74
+ * so a removal put back brings them back too.
75
+ */
76
+ function rulesChanged(h, reworded, removed) {
77
+ const was = h.reworded ?? [];
78
+ const later = new Set([...reworded, ...removed].map((r) => r.id));
79
+ h.reworded = [...was.filter((r) => !later.has(r.id)), ...reworded];
80
+ // Made a rule and removed again: the removal is what's true now.
81
+ h.rules = h.rules.filter((id) => !removed.some((r) => r.id === id));
82
+ h.removed = [...(h.removed ?? []), ...removed.map((r) => {
83
+ const edited = was.find((x) => x.id === r.id)?.to;
84
+ return edited ? { ...r, edited } : r;
85
+ })];
86
+ }
87
+ /** Renamed twice, A to B then B to C: one rename, A to C. Renamed back: none. */
88
+ function renames(was, next) {
89
+ let out = [...was];
90
+ for (const r of next) {
91
+ const before = out.find((x) => x.to === r.from);
92
+ out = out.filter((x) => x !== before);
93
+ const from = before ? before.from : r.from;
94
+ if (from !== r.to)
95
+ out.push({ from, to: r.to });
96
+ }
97
+ return out;
98
+ }
99
+ function nextStep(h) {
100
+ const rules = (h.reworded?.length || h.removed?.length ? ' Rules were edited or removed on Design rules: follow DECISIONS.md as it is now.' : '')
101
+ + (h.renamed?.length ? ' Work was renamed on the board: use each new name as the trigger from now on.' : '');
102
+ if (!h.todo.length)
103
+ return `Nothing to change in the code.${rules}`;
104
+ return `Make each change in todo. They're recorded already, so don't judge or record them again. An approved request is the exception: record its change with --request <id> once it's made.${rules}`;
105
+ }
106
+ /** Anything decided at all. A sitting where nothing was answered hands nothing over. */
107
+ const decidedAnything = (h) => !!(h.confirmed.length || h.rules.length || h.fixed.length || h.skipped.length || h.declined.length || h.options.length || h.reworded?.length || h.removed?.length || h.renamed?.length || h.todo.length);
108
+ exports.decidedAnything = decidedAnything;
109
+ /** One line for the person at the terminal, when nobody's waiting on the JSON. `when` is when the agent hears of it. */
110
+ function handoffLine(h, when = 'at the next /arbiter') {
111
+ if (!(0, exports.decidedAnything)(h))
112
+ return null;
113
+ const parts = [
114
+ h.confirmed.length && `${h.confirmed.length} confirmed`,
115
+ h.rules.length && `${h.rules.length} made ${h.rules.length === 1 ? 'a rule' : 'rules'}`,
116
+ h.fixed.length && `${h.fixed.length} fixed`,
117
+ h.skipped.length && `${h.skipped.length} skipped`,
118
+ h.reworded?.length && `${h.reworded.length} ${h.reworded.length === 1 ? 'rule' : 'rules'} edited`,
119
+ h.removed?.length && `${h.removed.length} ${h.removed.length === 1 ? 'rule' : 'rules'} removed`,
120
+ h.renamed?.length && `${h.renamed.length} renamed`,
121
+ ].filter(Boolean);
122
+ const said = parts.length ? `Recorded: ${parts.join(', ')}.` : 'Recorded.';
123
+ if (!h.todo.length)
124
+ return said;
125
+ return `${said} ${h.todo.length} ${h.todo.length === 1 ? 'change waits' : 'changes wait'} for your agent, which picks ${h.todo.length === 1 ? 'it' : 'them'} up ${when}.`;
126
+ }
127
+ /**
128
+ * An earlier sitting nobody acted on, then this one: a second sitting adds to the first rather
129
+ * than replacing it, so nothing waiting on the agent is lost.
130
+ */
131
+ function mergeHandoffs(earlier, h) {
132
+ if (!earlier)
133
+ return h;
134
+ const merged = {
135
+ ...h,
136
+ confirmed: [...earlier.confirmed, ...h.confirmed],
137
+ rules: [...earlier.rules, ...h.rules],
138
+ fixed: [...earlier.fixed, ...h.fixed],
139
+ skipped: [...earlier.skipped, ...h.skipped],
140
+ declined: [...earlier.declined, ...h.declined],
141
+ options: [...earlier.options, ...h.options],
142
+ reworded: earlier.reworded ?? [],
143
+ removed: earlier.removed ?? [],
144
+ renamed: renames(earlier.renamed ?? [], h.renamed ?? []),
145
+ todo: [...earlier.todo, ...h.todo],
146
+ };
147
+ rulesChanged(merged, h.reworded ?? [], h.removed ?? []);
148
+ merged.next = nextStep(merged);
149
+ return merged;
150
+ }
151
+ /**
152
+ * Saved for the next /arbiter, which reads it with the queue. Kept out of git: it's one person's
153
+ * sitting, and a teammate's agent mustn't make it.
154
+ */
155
+ function saveHandoff(paths, h) {
156
+ node_fs_1.default.mkdirSync(paths.archiveDir, { recursive: true });
157
+ // The next step names the rules file as DECISIONS.md; a project whose rules are elsewhere hears its own.
158
+ const rules = node_path_1.default.basename(paths.decisions);
159
+ const named = rules === 'DECISIONS.md' || !h.next ? h : { ...h, next: h.next.split('DECISIONS.md').join(rules) };
160
+ (0, lock_1.writeAtomic)(node_path_1.default.join(paths.archiveDir, exports.FILE), JSON.stringify(named, null, 2) + '\n');
161
+ const gi = node_path_1.default.join(paths.archiveDir, '.gitignore');
162
+ const lines = (node_fs_1.default.existsSync(gi) ? node_fs_1.default.readFileSync(gi, 'utf8') : '').split(/\r?\n/).filter(Boolean);
163
+ const missing = [exports.FILE, exports.SEEN].filter((x) => !lines.includes(x));
164
+ if (missing.length)
165
+ node_fs_1.default.writeFileSync(gi, [...lines, ...missing].join('\n') + '\n');
166
+ }
167
+ /**
168
+ * What's waiting, handed to the agent: kept as it was given (SEEN), so `review --done` clears that and
169
+ * no more. The Claude Code hook keeps the same copy when it speaks.
170
+ */
171
+ function takeHandoff(paths) {
172
+ const h = readHandoff(paths);
173
+ if (h)
174
+ (0, lock_1.writeAtomic)(node_path_1.default.join(paths.archiveDir, exports.SEEN), JSON.stringify(h, null, 2) + '\n');
175
+ return h;
176
+ }
177
+ /**
178
+ * The agent has made what it was told: that comes out of the file. Anything judged on the board since
179
+ * stays, for the hook to say at the next message. Nothing handed over yet: nothing is cleared.
180
+ */
181
+ function handoffDone(paths) {
182
+ const h = readHandoff(paths);
183
+ const seenFile = node_path_1.default.join(paths.archiveDir, exports.SEEN);
184
+ let seen = null;
185
+ try {
186
+ seen = JSON.parse(node_fs_1.default.readFileSync(seenFile, 'utf8'));
187
+ }
188
+ catch { /* never handed over */ }
189
+ if (!h) {
190
+ node_fs_1.default.rmSync(seenFile, { force: true });
191
+ return { status: 'nothing', left: 0 };
192
+ }
193
+ if (!seen)
194
+ return { status: 'not-taken', left: h.todo.length, errors: ['Nothing was handed over yet, so nothing was cleared: read it first with npx arbiter rules --pending --json'] };
195
+ const key = (x) => JSON.stringify(x);
196
+ const minus = (now, was) => {
197
+ const gone = new Set((was ?? []).map(key));
198
+ return (now ?? []).filter((x) => !gone.has(key(x)));
199
+ };
200
+ const { told: _told, ...rest } = h;
201
+ const left = {
202
+ ...rest,
203
+ confirmed: minus(h.confirmed, seen.confirmed),
204
+ rules: minus(h.rules, seen.rules),
205
+ fixed: minus(h.fixed, seen.fixed),
206
+ skipped: minus(h.skipped, seen.skipped),
207
+ declined: minus(h.declined, seen.declined),
208
+ options: minus(h.options, seen.options),
209
+ reworded: minus(h.reworded, seen.reworded),
210
+ removed: minus(h.removed, seen.removed),
211
+ renamed: minus(h.renamed, seen.renamed),
212
+ todo: minus(h.todo, seen.todo),
213
+ };
214
+ left.next = nextStep(left);
215
+ if ((0, exports.decidedAnything)(left))
216
+ saveHandoff(paths, left);
217
+ else
218
+ clearHandoff(paths);
219
+ node_fs_1.default.rmSync(seenFile, { force: true });
220
+ return { status: 'done', left: left.todo.length };
221
+ }
222
+ /**
223
+ * One answer, added to what's already waiting. Added, never rewritten from the sitting: the agent
224
+ * may have taken the file and made it while the board was still open, and a rewrite would hand
225
+ * those changes over a second time.
226
+ */
227
+ function saveAnswer(paths, a) {
228
+ const h = mergeHandoffs(readHandoff(paths), summarize([a], 'closed'));
229
+ if ((0, exports.decidedAnything)(h))
230
+ saveHandoff(paths, h);
231
+ }
232
+ /**
233
+ * An answer taken back on the page: out of what's waiting, so the agent never acts on it. False when
234
+ * the agent has taken it already, and may have made the change.
235
+ */
236
+ function withdrawAnswer(paths, a) {
237
+ const h = readHandoff(paths);
238
+ const id = a.as === 'skip' ? a.pending : a.id ?? a.pending;
239
+ const list = a.as === 'skip' ? 'skipped' : a.as === 'accept' ? 'confirmed' : a.as === 'rule' ? 'rules' : 'fixed';
240
+ if (!h?.[list].includes(id))
241
+ return false;
242
+ // Rewritten as it is otherwise, `told` and all: taking one back is nothing new for the hook to say.
243
+ const next = { ...h, [list]: h[list].filter((x) => x !== id), todo: h.todo.filter((t) => t.kind === 'request' || t.id !== id) };
244
+ next.next = nextStep(next);
245
+ if ((0, exports.decidedAnything)(next))
246
+ saveHandoff(paths, next);
247
+ else
248
+ clearHandoff(paths);
249
+ return true;
250
+ }
251
+ /** A removal put back on the page: out of what's waiting. False when the agent has heard of it already. */
252
+ function withdrawRemoval(paths, id) {
253
+ const h = readHandoff(paths);
254
+ const gone = h?.removed?.find((r) => r.id === id);
255
+ if (!h || !gone)
256
+ return false;
257
+ const next = {
258
+ ...h,
259
+ removed: h.removed.filter((r) => r.id !== id),
260
+ ...(gone.edited && { reworded: [...(h.reworded ?? []), { id, to: gone.edited }] }),
261
+ };
262
+ next.next = nextStep(next);
263
+ if ((0, exports.decidedAnything)(next))
264
+ saveHandoff(paths, next);
265
+ else
266
+ clearHandoff(paths);
267
+ return true;
268
+ }
269
+ /** Handed over: the agent has it, so the next /arbiter mustn't make it a second time. */
270
+ function clearHandoff(paths) {
271
+ node_fs_1.default.rmSync(node_path_1.default.join(paths.archiveDir, exports.FILE), { force: true });
272
+ node_fs_1.default.rmSync(node_path_1.default.join(paths.archiveDir, exports.SEEN), { force: true });
273
+ }
274
+ function readHandoff(paths) {
275
+ const f = node_path_1.default.join(paths.archiveDir, exports.FILE);
276
+ if (!node_fs_1.default.existsSync(f))
277
+ return null;
278
+ try {
279
+ return JSON.parse(node_fs_1.default.readFileSync(f, 'utf8'));
280
+ }
281
+ catch {
282
+ return null;
283
+ }
284
+ }
285
+ exports.HANDOFF_FILE = `.arbiter/${exports.FILE}`;
286
+ exports.HANDOFF_NAME = exports.FILE;