arbiterdesign 0.1.3 → 0.1.6

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.
@@ -11,6 +11,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.review = review;
14
+ exports.fromHere = fromHere;
14
15
  const node_fs_1 = __importDefault(require("node:fs"));
15
16
  const node_http_1 = __importDefault(require("node:http"));
16
17
  const node_path_1 = __importDefault(require("node:path"));
@@ -20,6 +21,11 @@ const candidate_1 = require("./candidate");
20
21
  const candidates_1 = require("../candidates");
21
22
  const hosted_1 = require("../hosted");
22
23
  const store_1 = require("../store");
24
+ const autopublish_1 = require("../autopublish");
25
+ const pictures_1 = require("../pictures");
26
+ const requests_1 = require("../requests");
27
+ const work_1 = require("../work");
28
+ const request_1 = require("./request");
23
29
  const PAGE = node_path_1.default.join(__dirname, '..', '..', 'templates', 'review.html');
24
30
  function review(opts = {}) {
25
31
  const root = (0, store_1.findRoot)(opts.cwd);
@@ -34,24 +40,72 @@ function review(opts = {}) {
34
40
  comments: comments.filter((x) => x.candidate_id === c.id),
35
41
  }));
36
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
+ };
37
52
  return {
38
53
  project: node_path_1.default.basename(root),
39
- pending: (0, store_1.readPending)(paths).map((d) => ({ ...d, candidateName: d.candidate ? byId.get(d.candidate)?.name ?? null : null, snapshotUrl: d.candidate ? byId.get(d.candidate)?.snapshotUrl ?? null : null })),
54
+ pending: (0, store_1.readPending)(paths).map((d) => ({
55
+ ...d,
56
+ candidateName: d.candidate ? byId.get(d.candidate)?.name ?? null : null,
57
+ snapshotUrl: d.candidate ? byId.get(d.candidate)?.snapshotUrl ?? null : null,
58
+ picture: (0, pictures_1.missingPictures)(paths, [d], candidates)[0] ?? null,
59
+ })),
60
+ // Open ones to answer; approved ones waiting on the agent — shown so it's clear nothing is lost.
61
+ requests: (0, requests_1.readRequests)(paths)
62
+ .filter((r) => r.status === 'open' || r.status === 'approved')
63
+ .map((r) => ({ ...(0, requests_1.describe)(paths, r, version, archive), snapshotUrl: shotOf(r.screen) })),
40
64
  candidates,
41
- hosted: (0, hosted_1.readLink)(paths)?.shareUrl ?? null,
42
- boardVersion: (0, hosted_1.readLink)(paths)?.boardVersion ?? null,
65
+ hosted: (0, hosted_1.readLinkOrNull)(paths)?.shareUrl ?? null,
66
+ boardVersion: (0, hosted_1.readLinkOrNull)(paths)?.boardVersion ?? null,
43
67
  active: (0, store_1.readActive)(paths).length,
44
68
  cap: (0, store_1.readConfig)(paths)?.activeCap ?? store_1.ACTIVE_CAP,
45
69
  };
46
70
  };
71
+ // Judging twenty items shouldn't mean twenty publishes, so the board is updated once, at the
72
+ // end. The page writes the same files the CLI does, but doesn't go through its handlers.
73
+ let changed = false;
47
74
  return new Promise((resolve) => {
48
75
  const server = node_http_1.default.createServer(async (req, res) => {
76
+ try {
77
+ await handle(req, res);
78
+ }
79
+ catch (e) {
80
+ // A broken requests.json, say: the page shows the message instead of the server dying.
81
+ if (!res.headersSent)
82
+ json(res, 500, { exitCode: 1, errors: [e.message] });
83
+ else
84
+ res.end();
85
+ }
86
+ });
87
+ const handle = async (req, res) => {
88
+ // This machine, by its own name, and nothing else. A site that points a domain of its own at
89
+ // 127.0.0.1 (DNS rebinding) is same-origin to the browser, so the JSON check below can't stop
90
+ // it, but its requests carry that domain as their Host.
91
+ if (!fromHere(req)) {
92
+ res.writeHead(403);
93
+ res.end();
94
+ return;
95
+ }
49
96
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
50
97
  if (req.method === 'GET' && url.pathname === '/') {
51
98
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
52
99
  res.end(node_fs_1.default.readFileSync(PAGE, 'utf8'));
53
100
  return;
54
101
  }
102
+ // Every write is JSON from this page. A form or a plain-text POST from another site in the same
103
+ // browser can't set that header without asking first — and nothing here answers when it asks.
104
+ if (req.method === 'POST' && !String(req.headers['content-type'] ?? '').startsWith('application/json')) {
105
+ res.writeHead(415);
106
+ res.end();
107
+ return;
108
+ }
55
109
  if (req.method === 'GET' && url.pathname === '/api/state') {
56
110
  json(res, 200, state());
57
111
  return;
@@ -59,19 +113,31 @@ function review(opts = {}) {
59
113
  if (req.method === 'POST' && url.pathname === '/api/judge') {
60
114
  const body = JSON.parse(await readBody(req));
61
115
  const result = (0, record_1.judge)(body.id, { as: body.as, to: body.to, supersedes: body.supersedes, keepBoth: body.keepBoth, cwd });
116
+ if (result.exitCode === 0)
117
+ changed = true;
62
118
  json(res, 200, { exitCode: result.exitCode, ...result.output });
63
119
  return;
64
120
  }
65
121
  if (req.method === 'POST' && url.pathname === '/api/judge-all') {
66
122
  const body = JSON.parse(await readBody(req));
67
123
  const result = (0, record_1.judgeAll)({ as: body.as, level: body.level, trigger: body.trigger, cwd });
124
+ if (result.exitCode === 0)
125
+ changed = true;
126
+ json(res, 200, { exitCode: result.exitCode, ...result.output });
127
+ return;
128
+ }
129
+ if (req.method === 'POST' && url.pathname === '/api/request') {
130
+ const body = JSON.parse(await readBody(req));
131
+ const result = (0, request_1.judgeRequest)(body.id, { as: body.as, to: body.to, why: body.why, cwd });
132
+ if (result.exitCode === 0)
133
+ changed = true;
68
134
  json(res, 200, { exitCode: result.exitCode, ...result.output });
69
135
  return;
70
136
  }
71
137
  if (req.method === 'GET' && url.pathname.startsWith('/snapshots/')) {
72
138
  const file = node_path_1.default.basename(url.pathname);
73
- const abs = node_path_1.default.join((0, candidates_1.candidatesDir)(paths), file);
74
- if (!/^C-\d{4,}\.(png|jpe?g|webp|gif|svg)$/.test(file) || !node_fs_1.default.existsSync(abs)) {
139
+ const abs = node_path_1.default.join(file.startsWith('W-') ? (0, work_1.workDir)(paths) : (0, candidates_1.candidatesDir)(paths), file);
140
+ if (!/^(C-\d{4,}|W-[a-z0-9-]{1,48})\.(png|jpe?g|webp|gif|svg)$/.test(file) || !node_fs_1.default.existsSync(abs)) {
75
141
  res.writeHead(404);
76
142
  res.end();
77
143
  return;
@@ -84,6 +150,8 @@ function review(opts = {}) {
84
150
  if (req.method === 'POST' && url.pathname === '/api/candidate') {
85
151
  const body = JSON.parse(await readBody(req));
86
152
  const result = (0, candidate_1.updateCandidate)(body.id, { state: body.state, why: body.why, keepOthers: body.keepOthers, cwd });
153
+ if (result.exitCode === 0)
154
+ changed = true;
87
155
  json(res, 200, { exitCode: result.exitCode, ...result.output });
88
156
  return;
89
157
  }
@@ -94,23 +162,55 @@ function review(opts = {}) {
94
162
  }
95
163
  res.writeHead(404);
96
164
  res.end();
97
- });
165
+ };
98
166
  server.listen(opts.port ?? 0, '127.0.0.1', () => {
99
167
  const addr = server.address();
100
168
  const url = `http://127.0.0.1:${addr.port}/`;
101
- const s = state();
102
- process.stdout.write(`Arbiter review — ${s.pending.length} pending · ${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`);
169
+ let s;
170
+ try {
171
+ s = state();
172
+ }
173
+ catch (e) {
174
+ process.stderr.write(`arbiter: ${e.message}\n`);
175
+ process.exitCode = 1;
176
+ stop();
177
+ return;
178
+ }
179
+ const asks = s.requests.filter((r) => r.status === 'open').length;
180
+ 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`);
103
181
  if (opts.open !== false)
104
182
  openBrowser(url);
105
183
  });
106
184
  // Browsers keep connections alive; close() alone would wait on them forever.
107
185
  const stop = () => {
108
- server.close(() => resolve());
186
+ server.close(async () => {
187
+ if (changed) {
188
+ const line = await (0, autopublish_1.autoPublish)(cwd);
189
+ if (line)
190
+ process.stdout.write(line + '\n');
191
+ }
192
+ resolve();
193
+ });
109
194
  server.closeAllConnections();
110
195
  };
111
196
  process.on('SIGINT', stop);
112
197
  });
113
198
  }
199
+ const LOCAL = /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i;
200
+ /** Addressed to this machine, and, when a page sent it, sent by a page on this machine. */
201
+ function fromHere(req) {
202
+ if (!LOCAL.test(String(req.headers.host ?? '')))
203
+ return false;
204
+ const origin = req.headers.origin;
205
+ if (!origin)
206
+ return true;
207
+ try {
208
+ return LOCAL.test(new URL(origin).host);
209
+ }
210
+ catch {
211
+ return false;
212
+ }
213
+ }
114
214
  function json(res, status, body) {
115
215
  res.writeHead(status, { 'content-type': 'application/json; charset=utf-8' });
116
216
  res.end(JSON.stringify(body));
@@ -5,8 +5,8 @@
5
5
  * arbiter rules active rules, grouped by dimension
6
6
  * arbiter rules --dimension x one dimension
7
7
  * arbiter rules --archive everything ever: accepts, fixes, superseded, in order
8
- * arbiter rules --pending queued, not yet judged
9
- * arbiter rules D-0003 one decision in full, wherever it lives
8
+ * arbiter rules --pending queued, not yet judged — and requests from the board waiting on an answer
9
+ * arbiter rules D-0003 one decision in full, wherever it lives (R-0001: one request)
10
10
  * arbiter rules --json any of the above as JSON
11
11
  */
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -15,11 +15,16 @@ exports.groupByTrigger = groupByTrigger;
15
15
  const schema_1 = require("../schema");
16
16
  const format_1 = require("../format");
17
17
  const store_1 = require("../store");
18
+ const hosted_1 = require("../hosted");
19
+ const requests_1 = require("../requests");
18
20
  const update_1 = require("./update");
21
+ const overlap_1 = require("../overlap");
19
22
  function rules(id, opts = {}) {
20
23
  const paths = (0, store_1.resolvePaths)((0, store_1.findRoot)(opts.cwd));
21
24
  opts = { ...opts, config: (0, store_1.readConfig)(paths) };
22
25
  const cap = (0, store_1.readConfig)(paths)?.activeCap ?? store_1.ACTIVE_CAP;
26
+ if (id && requests_1.REQUEST_ID.test(id))
27
+ return oneRequest(id, paths, opts.json);
23
28
  if (id)
24
29
  return one(id, paths, opts.json);
25
30
  if (opts.archive)
@@ -59,23 +64,48 @@ function rules(id, opts = {}) {
59
64
  */
60
65
  function pendingList(pending, opts, paths) {
61
66
  const groups = groupByTrigger(pending);
67
+ // Requests from the board: open ones wait on the owner's answer; approved ones on the agent.
68
+ const archiveAll = (0, store_1.readArchive)(paths);
69
+ // Only for "asked about an earlier version": a hosted.json in a merge conflict mustn't stop the queue.
70
+ const version = (0, hosted_1.readLinkOrNull)(paths)?.boardVersion ?? null;
71
+ const requests = (0, requests_1.readRequests)(paths);
72
+ const show = (status) => requests.filter((r) => r.status === status).map((r) => (0, requests_1.describe)(paths, r, version, archiveAll));
73
+ const open = show('open');
74
+ const approved = show('approved');
62
75
  if (opts.json) {
76
+ const active = (0, store_1.readActive)(paths);
77
+ const ignore = opts.config?.overlap?.ignore;
63
78
  return JSON.stringify({
64
79
  firstRun: !opts.config?.onboarded,
65
80
  checkin: opts.config?.checkin ?? 'feature',
66
81
  ...(0, update_1.updateNotice)(paths),
82
+ requests: { open, approved },
67
83
  count: pending.length,
68
84
  polish: pending.filter((d) => d.level === 'polish').length,
69
- groups: groups.map((g) => ({ trigger: g.trigger, items: g.items, polish: g.polish })),
85
+ groups: groups.map((g) => ({ trigger: g.trigger, items: g.items.map((d) => withOverlaps(d, active, ignore)), polish: g.polish })),
86
+ // The active rules, short, so the review can check every item for a clash without another read.
87
+ rules: active.map((d) => ({ id: d.id, decision: d.decision, scope: d.scope, dimension: d.dimension })),
70
88
  pending,
71
89
  }, null, 2);
72
90
  }
73
- if (!pending.length)
91
+ if (!pending.length && !open.length && !approved.length)
74
92
  return 'Nothing pending. All caught up.';
93
+ const lines = [];
94
+ if (open.length || approved.length) {
95
+ lines.push(`Requests from the board — ${[open.length ? `${open.length} to answer` : '', approved.length ? `${approved.length} approved, not yet made` : ''].filter(Boolean).join(', ')}`);
96
+ for (const r of [...open, ...approved]) {
97
+ lines.push(` ${r.id} ${r.author}${r.screenName ? `, on ${r.screenName}` : ''}${r.decision ? ` (${r.decision})` : ''}: ${(0, requests_1.oneLine)(r.body)}${r.earlierVersion ? ' (earlier version)' : ''}`);
98
+ if (r.status === 'approved')
99
+ lines.push(` approved${r.instead ? ` — do instead: ${r.instead}` : ''}`);
100
+ }
101
+ if (open.length)
102
+ lines.push(` answer: npx arbiter record ${open[0].id} --as apply · --as apply --to "<instead>" · --as decline --why "<reason>"`);
103
+ if (!pending.length)
104
+ return lines.join('\n');
105
+ lines.push('');
106
+ }
75
107
  const polish = pending.filter((d) => d.level === 'polish').length;
76
- const lines = [
77
- `${pending.length} pending${polish ? ` (${polish} polish)` : ''} — review with \`npx arbiter review\` or /arbiter in chat`,
78
- ];
108
+ lines.push(`${pending.length} pending${polish ? ` (${polish} polish)` : ''} — review with \`npx arbiter review\` or /arbiter in chat`);
79
109
  for (const g of groups) {
80
110
  lines.push('', g.trigger);
81
111
  for (const d of g.items)
@@ -88,6 +118,15 @@ function pendingList(pending, opts, paths) {
88
118
  }
89
119
  return lines.join('\n');
90
120
  }
121
+ /**
122
+ * A feature/pattern item with `overlaps` — active rules it may repeat or contradict — so the
123
+ * review can spot a clash. Word and scope matches only: the agent reads both sides and decides.
124
+ * The key is there only when there's a hit.
125
+ */
126
+ function withOverlaps(d, active, ignore) {
127
+ const overlaps = (0, overlap_1.findOverlaps)(d, active, { ignore });
128
+ return overlaps.length ? { ...d, overlaps } : d;
129
+ }
91
130
  /** Queue order of first appearance; each trigger once. */
92
131
  function groupByTrigger(pending) {
93
132
  const out = [];
@@ -111,6 +150,21 @@ function reviewLines(d) {
111
150
  lines.push(`${pad}${d.level} · ${d.dimension} · ${d.scope}`);
112
151
  return lines;
113
152
  }
153
+ function oneRequest(id, paths, json) {
154
+ const found = (0, requests_1.findRequest)((0, requests_1.readRequests)(paths), id);
155
+ if (found.error)
156
+ throw new Error(found.error);
157
+ const r = found.request;
158
+ if (!r)
159
+ throw new Error(`${id} not found`);
160
+ if (json)
161
+ return JSON.stringify(r, null, 2);
162
+ const answer = r.status === 'open' ? 'open — waiting on the owner'
163
+ : r.status === 'declined' ? `declined by ${r.judgedBy}: ${r.reason}`
164
+ : r.status === 'approved' ? `approved by ${r.judgedBy}${r.instead ? ` — do instead: ${r.instead}` : ''}`
165
+ : `applied${r.instead ? ` differently (${r.instead})` : ''} — ${r.decisions.join(', ')}`;
166
+ return [`${r.id} ${r.author} on ${(0, requests_1.screenName)(paths, r.screen) ?? r.screen}${r.decision ? ` (${r.decision})` : ''}, ${String(r.date ?? '').slice(0, 10)}`, ` ${r.body}`, ` ${answer}`].join('\n');
167
+ }
114
168
  function one(id, paths, json) {
115
169
  if (!schema_1.ID_PATTERN.test(id))
116
170
  throw new Error(`not a decision id: ${id} (looks like D-0003 or P-0003)`);
@@ -3,6 +3,10 @@
3
3
  * `arbiter setup --checkin <feature|quiet|every>` — the one preference the first `/arbiter` asks
4
4
  * for, written to arbiter.json. Running it also marks the project as onboarded, so the intro
5
5
  * never shows twice. Later: "be quieter" → the agent runs it again.
6
+ *
7
+ * `arbiter setup --app <url>` — where the app runs, so the agent has an address to open for a
8
+ * screenshot instead of assuming localhost. On its own it saves only that: the agent can learn
9
+ * the address before the first /arbiter, and that mustn't skip the intro.
6
10
  */
7
11
  Object.defineProperty(exports, "__esModule", { value: true });
8
12
  exports.CHECKINS = void 0;
@@ -14,10 +18,43 @@ function setup(opts) {
14
18
  const config = (0, store_1.readConfig)(paths);
15
19
  if (!config)
16
20
  return { exitCode: 1, output: { status: 'invalid', errors: ['no arbiter.json here — run `npx arbiter init` first'] } };
21
+ let app = config.app;
22
+ if (opts.app !== undefined) {
23
+ const url = appUrl(opts.app);
24
+ if (url === 'credentials')
25
+ return { exitCode: 1, output: { status: 'invalid', errors: ['--app goes in arbiter.json, which is committed — give the address without a username or password'] } };
26
+ if (!url)
27
+ return { exitCode: 1, output: { status: 'invalid', errors: ['--app must be the address the app runs at, like http://localhost:3000'] } };
28
+ app = { url };
29
+ }
30
+ // --app on its own goes before the check-in is read, so a hand-edited arbiter.json can't stop it.
31
+ if (opts.app !== undefined && opts.checkin === undefined) {
32
+ (0, store_1.writeConfig)(paths, { ...config, app });
33
+ return { exitCode: 0, output: { status: 'saved', app: app.url } };
34
+ }
17
35
  const checkin = (opts.checkin ?? config.checkin ?? 'feature');
18
36
  if (!exports.CHECKINS.includes(checkin))
19
37
  return { exitCode: 1, output: { status: 'invalid', errors: [`--checkin must be one of ${exports.CHECKINS.join(' | ')}`] } };
20
- const next = { ...config, checkin, onboarded: config.onboarded ?? (0, store_1.now)() };
38
+ const next = { ...config, checkin, onboarded: config.onboarded ?? (0, store_1.now)(), ...(app && { app }) };
21
39
  (0, store_1.writeConfig)(paths, next);
22
- return { exitCode: 0, output: { status: 'saved', checkin, onboarded: next.onboarded } };
40
+ return { exitCode: 0, output: { status: 'saved', checkin, onboarded: next.onboarded, ...(app && { app: app.url }) } };
41
+ }
42
+ /**
43
+ * An http(s) address a route can go on the end of: no query or fragment, no trailing slash.
44
+ * One with a username or password is refused rather than written to a committed file.
45
+ */
46
+ function appUrl(raw) {
47
+ try {
48
+ const u = new URL(raw.trim());
49
+ if (u.protocol !== 'http:' && u.protocol !== 'https:')
50
+ return null;
51
+ if (u.username || u.password)
52
+ return 'credentials';
53
+ u.search = '';
54
+ u.hash = '';
55
+ return u.href.replace(/\/+$/, '');
56
+ }
57
+ catch {
58
+ return null;
59
+ }
23
60
  }
@@ -11,6 +11,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
11
11
  exports.snapshotWork = snapshotWork;
12
12
  const node_path_1 = __importDefault(require("node:path"));
13
13
  const store_1 = require("../store");
14
+ const hosted_1 = require("../hosted");
14
15
  const work_1 = require("../work");
15
16
  function snapshotWork(name, opts) {
16
17
  const root = (0, store_1.findRoot)(opts.cwd);
@@ -21,12 +22,26 @@ function snapshotWork(name, opts) {
21
22
  if (!opts.file && !opts.capture)
22
23
  return { exitCode: 1, output: { status: 'invalid', errors: ['pass --file <image> or --capture'] } };
23
24
  const id = (0, work_1.workId)(trigger);
24
- const known = [...(0, store_1.readArchive)(paths), ...(0, store_1.readPending)(paths)].some((d) => (0, work_1.workId)(d.trigger) === id);
25
+ // A work card is built from judged, non-polish decisions only, so a picture for anything else has
26
+ // nothing to hang on yet. Counting the queue or polish here would report success for a board that stays empty.
27
+ const mine = (d) => (0, work_1.workId)(d.trigger) === id;
28
+ const archive = (0, store_1.readArchive)(paths);
29
+ const pending = (0, store_1.readPending)(paths);
30
+ const judged = archive.some((d) => mine(d) && (0, hosted_1.publishable)(d));
31
+ const queued = pending.filter((d) => mine(d) && d.level !== 'polish').length;
32
+ const polish = [...archive, ...pending].some((d) => mine(d) && d.level === 'polish' && d.verdict !== 'retire');
25
33
  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);
26
34
  if (!r.ok)
27
35
  return { exitCode: 1, output: { status: 'failed', error: r.error } };
36
+ const note = judged
37
+ ? null
38
+ : queued
39
+ ? `"${trigger}" has ${queued} decision${queued === 1 ? '' : 's'} still in the queue — the picture shows on the board once they're judged (/arbiter, or npx arbiter review)`
40
+ : polish
41
+ ? `"${trigger}" only has polish so far, and polish never reaches the board — the picture shows once a feature or pattern decision lands`
42
+ : `no decisions mention "${trigger}" yet — the picture shows once some do`;
28
43
  return {
29
44
  exitCode: 0,
30
- 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)), ...(known ? {} : { note: `no decisions mention "${trigger}" yet — the picture shows once some do` }) },
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 } : {}) },
31
46
  };
32
47
  }
package/dist/findings.js CHANGED
@@ -14,6 +14,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  return (mod && mod.__esModule) ? mod : { "default": mod };
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.isFinding = void 0;
17
18
  exports.parseFindings = parseFindings;
18
19
  exports.toDecisionInput = toDecisionInput;
19
20
  const node_path_1 = __importDefault(require("node:path"));
@@ -50,6 +51,14 @@ function parseFindings(raw) {
50
51
  }
51
52
  return out;
52
53
  }
54
+ /** The piece of work a finding is queued under: the rule that fired, and where. */
55
+ const findingTrigger = (rule, where) => `finding${rule ? ` ${rule}` : ''} at ${where}`;
56
+ /**
57
+ * A scanner finding, known by the shape `toDecisionInput` gives it. It's one line in one file,
58
+ * not a screen, so nothing asks for its picture.
59
+ */
60
+ const isFinding = (d) => d.class === 'mechanical' && /^finding(?: \S+)? at \S/.test(d.trigger);
61
+ exports.isFinding = isFinding;
53
62
  /** Turn a finding into the decision the reviewer will judge. */
54
63
  function toDecisionInput(f, root, tool) {
55
64
  const rel = node_path_1.default.isAbsolute(f.file) ? node_path_1.default.relative(root, f.file) : f.file;
@@ -58,7 +67,7 @@ function toDecisionInput(f, root, tool) {
58
67
  decision: f.suggestion ? f.suggestion : f.message,
59
68
  rationale: `${tool} flagged: ${f.message}`,
60
69
  rejected: [],
61
- trigger: `finding${f.rule ? ` ${f.rule}` : ''} at ${where}`,
70
+ trigger: findingTrigger(f.rule, where),
62
71
  scope: `file:${rel}`,
63
72
  dimension: 'visual',
64
73
  class: 'mechanical',
package/dist/format.js CHANGED
@@ -31,19 +31,26 @@ const NONE = '—';
31
31
  const HEADING = /^#{2,3} ([DP]-\d{4,}) · (.*)$/;
32
32
  const REJECTED_ITEM = /^ {2}- (.*)$/;
33
33
  const FIELD = /\*\*([A-Za-z]+):\*\* (.*?)(?=\s·\s\*\*|$)/g;
34
+ /**
35
+ * A value as an entry may hold it: one line, with no `**Field:**` marker of its own. Input is
36
+ * checked before it gets here, but some of it comes from outside the project (a board request's
37
+ * author and words, a scanner's message), and one line break would let it write a whole entry,
38
+ * a rule included.
39
+ */
40
+ const text = (s) => s.replace(/\s*[\r\n]+\s*/g, ' ').replace(/\*\*([A-Za-z]+):\*\*/g, '$1:');
34
41
  function formatEntry(d) {
35
42
  return [
36
- `### ${d.id}${SEP}${d.decision}`,
43
+ `### ${d.id}${SEP}${text(d.decision)}`,
37
44
  '',
38
- ...(d.change ? [`- **Change:** ${d.change}`] : []),
39
- `- **Rationale:** ${d.rationale}`,
40
- ...(d.rejected.length ? ['- **Rejected:**', ...d.rejected.map((r) => ` - ${r}`)] : []),
41
- `- **Trigger:** ${d.trigger}`,
42
- `- **Scope:** ${d.scope}${SEP}**Dimension:** ${d.dimension}${SEP}**Level:** ${d.level}${SEP}**Class:** ${d.class}${SEP}**Verdict:** ${d.verdict}`,
43
- `- **Author:** ${d.author}${SEP}**Date:** ${d.date}${SEP}**Commit:** ${d.commit ?? NONE}${SEP}**Supersedes:** ${d.supersedes ?? NONE}${d.candidate ? `${SEP}**Candidate:** ${d.candidate}` : ''}`,
44
- ...(d.ref ? [`- **Ref:** ${d.ref}`] : []),
45
- ...(d.files.length ? [`- **Files:** ${d.files.join(SEP)}`] : []),
46
- ...(d.paths.length ? [`- **Paths:** ${d.paths.join(SEP)}`] : []),
45
+ ...(d.change ? [`- **Change:** ${text(d.change)}`] : []),
46
+ `- **Rationale:** ${text(d.rationale)}`,
47
+ ...(d.rejected.length ? ['- **Rejected:**', ...d.rejected.map((r) => ` - ${text(r)}`)] : []),
48
+ `- **Trigger:** ${text(d.trigger)}`,
49
+ `- **Scope:** ${text(d.scope)}${SEP}**Dimension:** ${d.dimension}${SEP}**Level:** ${d.level}${SEP}**Class:** ${d.class}${SEP}**Verdict:** ${d.verdict}`,
50
+ `- **Author:** ${text(d.author)}${SEP}**Date:** ${text(d.date)}${SEP}**Commit:** ${d.commit ?? NONE}${SEP}**Supersedes:** ${d.supersedes ?? NONE}${d.candidate ? `${SEP}**Candidate:** ${d.candidate}` : ''}`,
51
+ ...(d.ref ? [`- **Ref:** ${text(d.ref)}`] : []),
52
+ ...(d.files.length ? [`- **Files:** ${d.files.map(text).join(SEP)}`] : []),
53
+ ...(d.paths.length ? [`- **Paths:** ${d.paths.map(text).join(SEP)}`] : []),
47
54
  ...(d.expect ? [`- **Expect:** ${JSON.stringify(d.expect)}${SEP}**Verified:** ${d.verified === null ? NONE : d.verified ? 'yes' : 'no'}`] : []),
48
55
  '',
49
56
  ].join('\n');
@@ -229,9 +236,10 @@ function archiveHeader() {
229
236
  return [
230
237
  '# Decision archive',
231
238
  '',
232
- 'Every decision ever recorded, in order. Append-only — nothing here is edited or removed.',
233
- 'Active rules live in `DECISIONS.md`; this file is for traceability and is never loaded',
234
- 'into agent context.',
239
+ 'Every decision ever recorded, in order. A decision you changed your mind about is superseded,',
240
+ 'never rewritten; only `npx arbiter remove` takes an entry out, for a record of something that',
241
+ 'never happened. Active rules live in `DECISIONS.md`; this file is for traceability and is never',
242
+ 'loaded into agent context.',
235
243
  '',
236
244
  ].join('\n');
237
245
  }
package/dist/hosted.js CHANGED
@@ -12,7 +12,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.ADMIN_ENV = exports.TOKEN_ENV = void 0;
15
+ exports.publishable = exports.ADMIN_ENV = exports.TOKEN_ENV = void 0;
16
+ exports.readLinkOrNull = readLinkOrNull;
16
17
  exports.readLink = readLink;
17
18
  exports.writeLink = writeLink;
18
19
  exports.readToken = readToken;
@@ -27,6 +28,16 @@ const node_path_1 = __importDefault(require("node:path"));
27
28
  const candidates_1 = require("./candidates");
28
29
  const store_1 = require("./store");
29
30
  const work_1 = require("./work");
31
+ const requests_1 = require("./requests");
32
+ /** The link for places that only want to know about the board, where a broken hosted.json shouldn't stop the command. */
33
+ function readLinkOrNull(paths) {
34
+ try {
35
+ return readLink(paths);
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ }
30
41
  const LINK_FILE = 'hosted.json';
31
42
  const TOKEN_FILE = 'hosted.token';
32
43
  const COMMENTS_FILE = 'comments.json';
@@ -72,10 +83,13 @@ function readComments(paths) {
72
83
  const f = node_path_1.default.join(paths.archiveDir, COMMENTS_FILE);
73
84
  return node_fs_1.default.existsSync(f) ? JSON.parse(node_fs_1.default.readFileSync(f, 'utf8')) : [];
74
85
  }
86
+ /** Every comment on file, minus email addresses: nothing here needs them, and the file is committed. */
75
87
  function writeComments(paths, comments) {
76
- node_fs_1.default.writeFileSync(node_path_1.default.join(paths.archiveDir, COMMENTS_FILE), JSON.stringify(comments, null, 2) + '\n');
88
+ const kept = comments.map(({ author_email: _email, ...c }) => c);
89
+ node_fs_1.default.writeFileSync(node_path_1.default.join(paths.archiveDir, COMMENTS_FILE), JSON.stringify(kept, null, 2) + '\n');
77
90
  }
78
91
  const publishable = (d) => d.verdict !== 'pending' && d.verdict !== 'retire' && d.level !== 'polish';
92
+ exports.publishable = publishable;
79
93
  const wire = (d) => ({ id: d.id, change: d.change, decision: d.decision, rejected: d.rejected, verdict: d.verdict, dimension: d.dimension, scope: d.scope, ref: d.ref });
80
94
  /**
81
95
  * The upload manifest: every judged, non-polish decision, and the rules. A decision attached to a
@@ -109,12 +123,13 @@ function buildManifest(paths, opts = {}) {
109
123
  supersededBy: c.supersededBy,
110
124
  url: null,
111
125
  snapshot,
112
- decisions: (0, candidates_1.decisionsFor)(paths, c.id).filter(publishable).map(wire),
126
+ decisions: (0, candidates_1.decisionsFor)(paths, c.id).filter(exports.publishable).map(wire),
113
127
  };
114
128
  });
115
129
  // Screenless decisions: one card per piece of work.
116
130
  const ids = new Set(known.map((c) => c.id));
117
- const loose = (0, store_1.readArchive)(paths).filter((d) => publishable(d) && (!d.candidate || !ids.has(d.candidate)));
131
+ const archive = (0, store_1.readArchive)(paths);
132
+ const loose = archive.filter((d) => (0, exports.publishable)(d) && (!d.candidate || !ids.has(d.candidate)));
118
133
  const byWork = new Map();
119
134
  for (const d of loose)
120
135
  byWork.set(d.trigger, [...(byWork.get(d.trigger) ?? []), d]);
@@ -138,8 +153,27 @@ function buildManifest(paths, opts = {}) {
138
153
  decisions: ds.map(wire),
139
154
  });
140
155
  }
141
- const rules = opts.includeRules ? (0, store_1.readActive)(paths).map((r) => ({ id: r.id, dimension: r.dimension, decision: r.decision, rationale: r.rationale, candidate: r.candidate ?? null })) : null;
142
- return { manifest: { project: node_path_1.default.basename(paths.root), exported: new Date().toISOString().slice(0, 10), candidates, rules }, skipped };
156
+ // The day each became a rule, for the board's Design rules page.
157
+ const rules = opts.includeRules ? (0, store_1.readActive)(paths).map((r) => ({ id: r.id, dimension: r.dimension, decision: r.decision, rationale: r.rationale, candidate: r.candidate ?? null, date: r.date.slice(0, 10) })) : null;
158
+ // The owner's answers to requests made on the board, matched there by comment. An open request
159
+ // needs nothing sent — the board already has it. What happened is the recorded change itself,
160
+ // polish included, so the requester reads it even when no card shows that decision.
161
+ const requests = (0, requests_1.readRequests)(paths)
162
+ .filter((r) => r.status !== 'open')
163
+ .map((r) => ({
164
+ comment: r.comment,
165
+ id: r.id,
166
+ status: r.status,
167
+ instead: r.instead,
168
+ reason: r.reason,
169
+ by: r.judgedBy,
170
+ at: r.appliedAt ?? r.judgedAt,
171
+ decisions: r.decisions.flatMap((id) => {
172
+ const d = archive.find((x) => x.id === id);
173
+ return d ? [{ id: d.id, change: d.change ?? d.decision, card: (0, requests_1.cardOf)(paths, d, ids) }] : [];
174
+ }),
175
+ }));
176
+ return { manifest: { project: node_path_1.default.basename(paths.root), exported: new Date().toISOString().slice(0, 10), candidates, rules, requests }, skipped };
143
177
  }
144
178
  async function api(url, init = {}) {
145
179
  const headers = { 'content-type': 'application/json', ...init.headers };
@@ -207,7 +241,11 @@ async function publishHosted(paths, serviceUrl, opts = {}) {
207
241
  throw new Error(`publish failed: ${r.body.error ?? r.status}`);
208
242
  return { link, candidates: Number(r.body.candidates ?? 0), snapshots, skipped, created };
209
243
  }
210
- /** Fetch comments since the last pull; merge into .arbiter/comments.json. */
244
+ /**
245
+ * Fetch every comment on the board; merge the new ones into .arbiter/comments.json. All of them,
246
+ * not only those since last time: it's how a request deleted on the board is noticed, and a
247
+ * cursor could skip a comment that landed mid-pull. `current` is what the board holds now.
248
+ */
211
249
  async function pullHosted(paths) {
212
250
  const link = readLink(paths);
213
251
  if (!link)
@@ -215,15 +253,24 @@ async function pullHosted(paths) {
215
253
  const token = readToken(paths);
216
254
  if (!token)
217
255
  throw new Error(`no publish token for ${link.shareUrl}. Get it from whoever first published, then: ${exports.TOKEN_ENV}=<token> npx arbiter pull`);
218
- const q = link.lastPull ? `?since=${encodeURIComponent(link.lastPull)}` : '';
219
- const r = await api(`${link.url}/api/projects/${link.projectId}/comments${q}`, { token });
256
+ const r = await api(`${link.url}/api/projects/${link.projectId}/comments`, { token });
220
257
  if (!r.ok)
221
258
  throw new Error(`pull failed: ${r.body.error ?? r.status}`);
222
- const fresh = r.body.comments ?? [];
259
+ // An empty list would read as every request withdrawn, so a reply without one is a failure.
260
+ if (!Array.isArray(r.body.comments))
261
+ throw new Error('pull failed: the board sent no comment list');
262
+ const current = r.body.comments;
223
263
  const existing = readComments(paths);
224
264
  const seen = new Set(existing.map((c) => c.id));
225
- const merged = [...existing, ...fresh.filter((c) => !seen.has(c.id))].sort((a, b) => a.created_at.localeCompare(b.created_at));
265
+ const fresh = current.filter((c) => !seen.has(c.id));
266
+ const merged = [...existing, ...fresh].sort((a, b) => String(a.created_at ?? '').localeCompare(String(b.created_at ?? '')));
226
267
  writeComments(paths, merged);
227
- writeLink(paths, { ...link, lastPull: String(r.body.fetched_at ?? new Date().toISOString()), boardVersion: r.body.board_version ?? link.boardVersion ?? null });
228
- return { link, fresh, total: merged.length };
268
+ // hosted.json is committed: rewrite it only when the board has moved on, or every pull on every
269
+ // machine would leave it changed, and two of them would conflict.
270
+ const boardVersion = r.body.board_version ?? link.boardVersion ?? null;
271
+ if (boardVersion !== (link.boardVersion ?? null)) {
272
+ const { lastPull: _old, ...rest } = link;
273
+ writeLink(paths, { ...rest, boardVersion });
274
+ }
275
+ return { link, fresh, current, total: merged.length };
229
276
  }