arbiterdesign 0.1.2 → 0.1.4

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.
@@ -10,8 +10,13 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
10
10
  return (mod && mod.__esModule) ? mod : { "default": mod };
11
11
  };
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.skillMarker = exports.SKILL_MARKER = exports.PKG_ROOT = void 0;
14
+ exports.selfVersion = selfVersion;
15
+ exports.skillPath = skillPath;
13
16
  exports.init = init;
14
17
  exports.detectClient = detectClient;
18
+ exports.detectPm = detectPm;
19
+ exports.addDevDependency = addDevDependency;
15
20
  const node_fs_1 = __importDefault(require("node:fs"));
16
21
  const node_os_1 = __importDefault(require("node:os"));
17
22
  const node_path_1 = __importDefault(require("node:path"));
@@ -21,8 +26,24 @@ const format_1 = require("../format");
21
26
  const prompt_1 = require("./prompt");
22
27
  const AGENTS_MARKER = '<!-- arbiter -->';
23
28
  const AGENTS_LINE = `Before any UI work, read \`DECISIONS.md\` — the design decisions this project has already made. Follow them; don't re-decide them. Record new ones with the \`arbiter\` skill. ${AGENTS_MARKER}`;
24
- const PKG_ROOT = node_path_1.default.join(__dirname, '..', '..');
25
- const SKILL_TEMPLATE = node_path_1.default.join(PKG_ROOT, 'templates', 'SKILL.md');
29
+ exports.PKG_ROOT = node_path_1.default.join(__dirname, '..', '..');
30
+ const SKILL_TEMPLATE = node_path_1.default.join(exports.PKG_ROOT, 'templates', 'SKILL.md');
31
+ /** The version of the package that's running. */
32
+ function selfVersion() {
33
+ return JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(exports.PKG_ROOT, 'package.json'), 'utf8')).version;
34
+ }
35
+ /**
36
+ * The skill file is a copy: it goes stale when the package moves on and nobody re-runs init.
37
+ * A comment on its first body line says which version wrote it, so `update` can tell without
38
+ * touching the network. A skill file with no marker predates 0.1.3 — always stale.
39
+ */
40
+ exports.SKILL_MARKER = /<!-- arbiter skill (\S+) -->/;
41
+ const skillMarker = (version) => `<!-- arbiter skill ${version} -->`;
42
+ exports.skillMarker = skillMarker;
43
+ /** Where the skill lives for a client. */
44
+ function skillPath(client) {
45
+ return client === 'cursor' ? node_path_1.default.join('.cursor', 'rules', 'arbiter.mdc') : node_path_1.default.join('.claude', 'skills', 'arbiter', 'SKILL.md');
46
+ }
26
47
  async function init(opts = {}) {
27
48
  const root = node_path_1.default.resolve(opts.cwd ?? process.cwd());
28
49
  const paths = (0, store_1.resolvePaths)(root);
@@ -52,7 +73,7 @@ async function init(opts = {}) {
52
73
  if (!author) {
53
74
  const guess = (0, store_1.gitUserName)(root) ?? node_os_1.default.userInfo().username;
54
75
  if (ask) {
55
- const a = (await ask.question(`Who decides rules? (author on every record) (${guess}): `)).trim();
76
+ const a = (await ask.question(`Who decides rules? (the author when git has no user.name) (${guess}): `)).trim();
56
77
  author = a || guess;
57
78
  }
58
79
  else {
@@ -122,25 +143,30 @@ function detectClient(root) {
122
143
  }
123
144
  const label = (c) => (c === 'cursor' ? 'Cursor' : 'Claude Code');
124
145
  function skillFor(client) {
125
- const template = node_fs_1.default.readFileSync(SKILL_TEMPLATE, 'utf8');
146
+ // A Windows checkout with autocrlf hands us CRLF; the frontmatter regex and the marker line assume LF.
147
+ const template = node_fs_1.default.readFileSync(SKILL_TEMPLATE, 'utf8').replace(/\r\n/g, '\n');
148
+ const m = /^---\n([\s\S]*?)\n---\n/.exec(template);
149
+ // The version marker is the first body line, under the frontmatter, so both clients carry it.
150
+ const body = (0, exports.skillMarker)(selfVersion()) + '\n' + template.slice(m?.[0].length ?? 0);
126
151
  if (client === 'claude-code') {
127
- return { file: node_path_1.default.join('.claude', 'skills', 'arbiter', 'SKILL.md'), content: template };
152
+ return { file: skillPath(client), content: (m?.[0] ?? '') + body };
128
153
  }
129
154
  // Cursor: same body, Cursor's rule frontmatter. "Agent requested" — picked by description.
130
- const m = /^---\n([\s\S]*?)\n---\n/.exec(template);
131
155
  const desc = /^description:\s*(.*)$/m.exec(m?.[1] ?? '')?.[1] ?? 'Record design decisions made during UI work.';
132
- const body = template.slice(m?.[0].length ?? 0);
133
156
  const front = `---\ndescription: ${desc}\nglobs:\nalwaysApply: false\n---\n`;
134
- return { file: node_path_1.default.join('.cursor', 'rules', 'arbiter.mdc'), content: front + body };
157
+ return { file: skillPath(client), content: front + body };
135
158
  }
136
159
  function writeIfChanged(root, rel, content) {
137
160
  const abs = node_path_1.default.join(root, rel);
161
+ // The label is written with `/` on every platform, like the literals above it and
162
+ // updateStatus's file. Only the name shown changes; abs is the platform's own path.
163
+ const name = rel.split(node_path_1.default.sep).join('/');
138
164
  const before = node_fs_1.default.existsSync(abs) ? node_fs_1.default.readFileSync(abs, 'utf8') : null;
139
165
  if (before === content)
140
- return { file: rel, outcome: 'unchanged' };
166
+ return { file: name, outcome: 'unchanged' };
141
167
  node_fs_1.default.mkdirSync(node_path_1.default.dirname(abs), { recursive: true });
142
168
  node_fs_1.default.writeFileSync(abs, content);
143
- return { file: rel, outcome: before === null ? 'created' : 'updated' };
169
+ return { file: name, outcome: before === null ? 'created' : 'updated' };
144
170
  }
145
171
  function mergeAgentsLine(root, file, createIfMissing) {
146
172
  const abs = node_path_1.default.join(root, file);
@@ -157,13 +183,36 @@ function mergeAgentsLine(root, file, createIfMissing) {
157
183
  node_fs_1.default.writeFileSync(abs, before + sep + AGENTS_LINE + '\n');
158
184
  return { file, outcome: 'updated', note: 'one line appended' };
159
185
  }
160
- const CURSOR_COMMAND = `# Arbiter — review queued design decisions
161
-
162
- Run \`npx arbiter rules --pending --json\` and present every queued decision, grouped by dimension, one line each with what it was chosen over. Ask the user to reply per number: confirm · rule · skip · or type what it should be. Then judge each with \`npx arbiter record P-xxxx --as accept|rule|skip|fix --to "…"\`. If the user wrote something after the command, treat it as "record that" and run \`npx arbiter record\` with it as a rule. Follow the arbiter rule file for the full protocol.
186
+ const CURSOR_COMMAND = `# Arbiter — review queued design decisions
187
+
188
+ Run \`npx arbiter rules --pending --json\` and present every queued decision, grouped by dimension, one line each with what it was chosen over. Ask the user to reply per number: confirm · rule · skip · or type what it should be. Then judge each with \`npx arbiter record P-xxxx --as accept|rule|skip|fix --to "…"\`. If the user wrote something after the command, treat it as "record that" and run \`npx arbiter record\` with it as a rule. Follow the arbiter rule file for the full protocol.
163
189
  `;
190
+ /** Which package manager the host uses, by lockfile. */
191
+ function detectPm(root) {
192
+ return node_fs_1.default.existsSync(node_path_1.default.join(root, 'pnpm-lock.yaml')) ? 'pnpm' : node_fs_1.default.existsSync(node_path_1.default.join(root, 'yarn.lock')) ? 'yarn' : 'npm';
193
+ }
194
+ /**
195
+ * Add a dev dependency. Quiet; true on success.
196
+ *
197
+ * On Windows the package managers are .cmd shims, which execFile can't run on its own — it
198
+ * raises ENOENT. `shell: true` fixes that but makes Node warn about unescaped arguments
199
+ * (DEP0190) on every install, which is the first thing a new user would see. Going through
200
+ * cmd.exe resolves the shim with the arguments still a real array, so neither happens.
201
+ */
202
+ function addDevDependency(root, pm, spec) {
203
+ const args = pm === 'npm' ? ['install', '--save-dev', '--no-audit', '--no-fund', spec] : ['add', '-D', spec];
204
+ const win = process.platform === 'win32';
205
+ try {
206
+ (0, node_child_process_1.execFileSync)(win ? 'cmd.exe' : pm, win ? ['/c', pm, ...args] : args, { cwd: root, stdio: ['ignore', 'ignore', 'ignore'] });
207
+ return true;
208
+ }
209
+ catch {
210
+ return false;
211
+ }
212
+ }
164
213
  /** Add this package to the host's devDependencies so `npx arbiter` resolves locally. */
165
214
  function installSelf(root) {
166
- const self = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(PKG_ROOT, 'package.json'), 'utf8'));
215
+ const self = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(exports.PKG_ROOT, 'package.json'), 'utf8'));
167
216
  const hostPkgPath = node_path_1.default.join(root, 'package.json');
168
217
  if (!node_fs_1.default.existsSync(hostPkgPath)) {
169
218
  return { file: 'package.json', outcome: 'skipped', note: `no package.json here — add ${self.name} as a dev dependency yourself` };
@@ -172,23 +221,14 @@ function installSelf(root) {
172
221
  if (host.devDependencies?.[self.name] || host.dependencies?.[self.name]) {
173
222
  return { file: 'package.json', outcome: 'unchanged', note: `${self.name} already a dependency` };
174
223
  }
175
- const pm = node_fs_1.default.existsSync(node_path_1.default.join(root, 'pnpm-lock.yaml')) ? 'pnpm' : node_fs_1.default.existsSync(node_path_1.default.join(root, 'yarn.lock')) ? 'yarn' : 'npm';
176
- const add = (spec) => {
177
- const args = pm === 'npm' ? ['install', '--save-dev', '--no-audit', '--no-fund', spec] : ['add', '-D', spec];
178
- try {
179
- (0, node_child_process_1.execFileSync)(pm, args, { cwd: root, stdio: ['ignore', 'ignore', 'ignore'] });
180
- return true;
181
- }
182
- catch {
183
- return false;
184
- }
185
- };
224
+ const pm = detectPm(root);
225
+ const add = (spec) => addDevDependency(root, pm, spec);
186
226
  // Registry first; fall back to the copy we're running from (unpublished / local dev).
187
227
  if (add(`${self.name}@^${self.version}`)) {
188
228
  return { file: 'package.json', outcome: 'updated', note: `${self.name} added to devDependencies (${pm})` };
189
229
  }
190
- if (add(PKG_ROOT)) {
191
- return { file: 'package.json', outcome: 'updated', note: `${self.name} added from ${PKG_ROOT} (registry unavailable)` };
230
+ if (add(exports.PKG_ROOT)) {
231
+ return { file: 'package.json', outcome: 'updated', note: `${self.name} added from ${exports.PKG_ROOT} (registry unavailable)` };
192
232
  }
193
233
  return { file: 'package.json', outcome: 'skipped', note: `could not install — run: ${pm} ${pm === 'npm' ? 'install --save-dev' : 'add -D'} ${self.name}` };
194
234
  }
@@ -11,16 +11,24 @@
11
11
  * 4. git push
12
12
  * 5. print the link
13
13
  */
14
+ var __importDefault = (this && this.__importDefault) || function (mod) {
15
+ return (mod && mod.__esModule) ? mod : { "default": mod };
16
+ };
14
17
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.DEFAULT_HOST = void 0;
18
+ exports.WORKFLOW_FILE = exports.DEFAULT_HOST = void 0;
16
19
  exports.publish = publish;
20
+ const node_fs_1 = __importDefault(require("node:fs"));
21
+ const node_path_1 = __importDefault(require("node:path"));
17
22
  const node_child_process_1 = require("node:child_process");
18
23
  const candidates_1 = require("../candidates");
19
24
  const destination_1 = require("../destination");
20
25
  const store_1 = require("../store");
21
26
  const hosted_1 = require("../hosted");
27
+ const init_1 = require("./init");
22
28
  /** Where `arbiter publish` goes when nothing says otherwise. */
23
29
  exports.DEFAULT_HOST = 'https://arbiter.design';
30
+ /** The GitHub Actions workflow `--on-push` writes. `update` re-pins the version in it. */
31
+ exports.WORKFLOW_FILE = node_path_1.default.join('.github', 'workflows', 'arbiter.yml');
24
32
  async function publish(opts = {}) {
25
33
  const root = (0, store_1.findRoot)(opts.cwd);
26
34
  const paths = (0, store_1.resolvePaths)(root);
@@ -39,7 +47,17 @@ async function publish(opts = {}) {
39
47
  done('board', `${r.candidates} screen${r.candidates === 1 ? '' : 's'} published${r.snapshots ? `, ${r.snapshots} image${r.snapshots === 1 ? '' : 's'}` : ''}`);
40
48
  for (const s of r.skipped)
41
49
  skip('snapshot', s);
42
- return { ok: true, steps, url: r.link.shareUrl };
50
+ if (opts.onPush)
51
+ for (const s of onPush(root, paths))
52
+ steps.push(s);
53
+ if (opts.auto !== undefined) {
54
+ const config = (0, store_1.readConfig)(paths) ?? { version: 1, destination: 'local' };
55
+ (0, store_1.writeConfig)(paths, { ...config, hosted: { ...config.hosted, auto: opts.auto } });
56
+ done('auto', opts.auto
57
+ ? 'on — the board republishes whenever the record changes (arbiter.json, commit it)'
58
+ : 'off — publish by hand from now on');
59
+ }
60
+ return { ok: steps.every((s) => s.outcome !== 'failed'), steps, url: r.link.shareUrl };
43
61
  }
44
62
  catch (e) {
45
63
  fail('hosted', e.message);
@@ -108,6 +126,90 @@ async function publish(opts = {}) {
108
126
  const ok = steps.every((s) => s.outcome !== 'failed');
109
127
  return { ok, steps, url };
110
128
  }
129
+ /**
130
+ * Keep the board current without anyone remembering to publish: a workflow that runs `publish`
131
+ * when decisions land on the default branch. The publish token becomes a repository secret —
132
+ * set through `gh` when it's signed in, otherwise a one-line instruction. The workflow itself
133
+ * is committed by the user; Arbiter only commits under `destination: git`.
134
+ */
135
+ function onPush(root, paths) {
136
+ const steps = [];
137
+ // A GitHub Actions file is worthless anywhere but GitHub, and writing one anyway used to report
138
+ // success for automation that could never run. Say what will actually work here instead.
139
+ const inRepo = !!git(root, ['rev-parse', '--is-inside-work-tree']);
140
+ const remote = inRepo ? git(root, ['remote', 'get-url', 'origin']) : null;
141
+ const gh = remote && /github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/.exec(remote);
142
+ if (!gh) {
143
+ const why = !inRepo ? 'this project is not a git repository' : !remote ? 'there is no remote named origin' : `${remote.replace(/^.*@/, '')} is not GitHub`;
144
+ steps.push({
145
+ step: 'on-push',
146
+ outcome: 'skipped',
147
+ note: `${why}, and --on-push writes a GitHub Actions workflow. For a board that keeps itself current without GitHub: npx arbiter publish --auto`,
148
+ });
149
+ return steps;
150
+ }
151
+ const branch = git(root, ['rev-parse', '--abbrev-ref', 'HEAD']) || 'main';
152
+ const file = node_path_1.default.join(root, exports.WORKFLOW_FILE);
153
+ const content = workflow(branch, (0, init_1.selfVersion)());
154
+ if (!node_fs_1.default.existsSync(file)) {
155
+ node_fs_1.default.mkdirSync(node_path_1.default.dirname(file), { recursive: true });
156
+ node_fs_1.default.writeFileSync(file, content);
157
+ steps.push({ step: 'workflow', outcome: 'done', note: `${exports.WORKFLOW_FILE} — commit it with .arbiter/hosted.json` });
158
+ }
159
+ else if (node_fs_1.default.readFileSync(file, 'utf8') === content) {
160
+ steps.push({ step: 'workflow', outcome: 'skipped', note: `${exports.WORKFLOW_FILE} already there` });
161
+ }
162
+ else {
163
+ steps.push({ step: 'workflow', outcome: 'skipped', note: `${exports.WORKFLOW_FILE} exists and differs — leaving your edits` });
164
+ }
165
+ const token = (0, hosted_1.readToken)(paths);
166
+ const manual = `once, on github.com: Settings → Secrets and variables → Actions → New repository secret → ${hosted_1.TOKEN_ENV} = the contents of .arbiter/hosted.token`;
167
+ if (!token)
168
+ steps.push({ step: 'secret', outcome: 'skipped', note: `no publish token here — ${manual}` });
169
+ else if (!has('gh') || !ghOk(root))
170
+ steps.push({ step: 'secret', outcome: 'skipped', note: `gh not ${has('gh') ? 'signed in' : 'installed'} — ${manual}` });
171
+ else {
172
+ try {
173
+ // The token goes in on stdin, not argv, so it never shows in a process list.
174
+ (0, node_child_process_1.execFileSync)('gh', ['secret', 'set', hosted_1.TOKEN_ENV, '--repo', `${gh[1]}/${gh[2]}`], { cwd: root, input: token, stdio: ['pipe', 'ignore', 'ignore'] });
175
+ steps.push({ step: 'secret', outcome: 'done', note: `${hosted_1.TOKEN_ENV} set on ${gh[1]}/${gh[2]}` });
176
+ }
177
+ catch {
178
+ steps.push({ step: 'secret', outcome: 'failed', note: `gh could not set the secret — ${manual}` });
179
+ }
180
+ }
181
+ return steps;
182
+ }
183
+ function workflow(branch, version) {
184
+ return [
185
+ '# Written by `npx arbiter publish --on-push`. Republishes the board when decisions land.',
186
+ '# Needs one repository secret, ARBITER_PUBLISH_TOKEN: the contents of .arbiter/hosted.token.',
187
+ '# `npx arbiter update` re-pins the version below.',
188
+ 'name: Arbiter',
189
+ 'on:',
190
+ ' push:',
191
+ ` branches: [${branch}]`,
192
+ ' paths:',
193
+ " - '.arbiter/**'",
194
+ " - 'DECISIONS.md'",
195
+ " - 'CANDIDATES.md'",
196
+ 'concurrency:',
197
+ ' group: arbiter-publish',
198
+ ' cancel-in-progress: true',
199
+ 'jobs:',
200
+ ' publish:',
201
+ ' runs-on: ubuntu-latest',
202
+ ' steps:',
203
+ ' - uses: actions/checkout@v4',
204
+ ' - uses: actions/setup-node@v4',
205
+ ' with:',
206
+ ' node-version: 20',
207
+ ` - run: npx --yes arbiterdesign@${version} publish`,
208
+ ' env:',
209
+ ' ARBITER_PUBLISH_TOKEN: ${{ secrets.ARBITER_PUBLISH_TOKEN }}',
210
+ '',
211
+ ].join('\n');
212
+ }
111
213
  function git(root, args) {
112
214
  try {
113
215
  return (0, node_child_process_1.execFileSync)('git', args, { cwd: root, stdio: ['ignore', 'pipe', 'ignore'] }).toString().trim();
@@ -41,6 +41,7 @@ const findings_1 = require("../findings");
41
41
  const prompt_1 = require("./prompt");
42
42
  const node_fs_1 = __importDefault(require("node:fs"));
43
43
  const candidate_1 = require("./candidate");
44
+ const update_1 = require("./update");
44
45
  // ── Parse + record ─────────────────────────────────────────────────────────
45
46
  function record(rawJson, opts = {}) {
46
47
  const parsed = parse(rawJson);
@@ -73,6 +74,8 @@ function queue(rawJson, opts = {}) {
73
74
  pending: pending.length + 1,
74
75
  checkin: (0, store_1.readConfig)(paths)?.checkin ?? 'feature',
75
76
  review: 'npx arbiter review',
77
+ // Present only when the project's skill file is from an older Arbiter than this one.
78
+ ...(0, update_1.updateNotice)(paths),
76
79
  },
77
80
  };
78
81
  }
@@ -344,7 +347,9 @@ function fill(input, opts, root) {
344
347
  const config = (0, store_1.readConfig)((0, store_1.resolvePaths)(root));
345
348
  return {
346
349
  date: input.date ?? (0, store_1.now)(),
347
- author: opts.author ?? input.author ?? config?.author ?? (0, store_1.gitUserName)(root) ?? node_os_1.default.userInfo().username,
350
+ // Whoever is at the keyboard. arbiter.json's author is committed, so in a shared repo it names
351
+ // whoever ran init — it's the fallback for a machine with no git identity, not the default.
352
+ author: opts.author ?? input.author ?? (0, store_1.gitUserName)(root) ?? config?.author ?? node_os_1.default.userInfo().username,
348
353
  class: input.class,
349
354
  dimension: input.dimension,
350
355
  decision: input.decision,
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ /**
3
+ * `arbiter remove` and `arbiter unlink` — the exits Arbiter was missing.
4
+ *
5
+ * Three verbs, and they mean different things:
6
+ *
7
+ * retire it was real, it's over → the rule leaves DECISIONS.md, the archive keeps it
8
+ * remove it was never real → it leaves the record entirely
9
+ * unlink it was real, wrongly attached → the decision stays, its screen doesn't
10
+ *
11
+ * Append-only is right for judgments: a call you changed your mind about is superseded, and that
12
+ * history is the point. It's wrong for mistakes. A test entry, an agent misfire, or a screen
13
+ * invented to work around a bug isn't history — it's a record that says something false, and
14
+ * keeping it forever makes the archive less trustworthy, not more.
15
+ *
16
+ * So `remove` deletes. Git holds the history for anyone who has it, and the output prints what
17
+ * went, in full, for anyone who doesn't. Nothing is removed while something still points at it.
18
+ */
19
+ var __importDefault = (this && this.__importDefault) || function (mod) {
20
+ return (mod && mod.__esModule) ? mod : { "default": mod };
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.remove = remove;
24
+ exports.removeSnapshot = removeSnapshot;
25
+ exports.unlink = unlink;
26
+ const node_fs_1 = __importDefault(require("node:fs"));
27
+ const node_path_1 = __importDefault(require("node:path"));
28
+ const schema_1 = require("../schema");
29
+ const format_1 = require("../format");
30
+ const store_1 = require("../store");
31
+ const candidates_1 = require("../candidates");
32
+ const destination_1 = require("../destination");
33
+ const work_1 = require("../work");
34
+ const fail = (errors) => ({ exitCode: 1, output: { status: 'invalid', errors } });
35
+ // ── remove ─────────────────────────────────────────────────────────────────
36
+ function remove(id, opts = {}) {
37
+ const raw = id?.trim() ?? '';
38
+ if (schema_1.DECISION_ID.test(raw))
39
+ return removeDecision(raw, opts);
40
+ if (schema_1.CANDIDATE_ID.test(raw))
41
+ return removeCandidate(raw, opts);
42
+ if (/^P-\d{4,}$/.test(raw))
43
+ return fail([`${raw} is still in the queue — drop it with: npx arbiter record ${raw} --as skip`]);
44
+ return fail([`not something that can be removed: ${raw} (a decision like D-0004, a candidate like C-0001, or a piece of work by name)`]);
45
+ }
46
+ function removeDecision(id, opts) {
47
+ const paths = (0, store_1.resolvePaths)((0, store_1.findRoot)(opts.cwd));
48
+ const archive = (0, store_1.readArchive)(paths);
49
+ const entry = archive.find((d) => d.id === id);
50
+ if (!entry)
51
+ return fail([`${id} is not in the archive`]);
52
+ const active = (0, store_1.readActive)(paths);
53
+ const isActive = active.some((d) => d.id === id);
54
+ if (isActive && !opts.force) {
55
+ return fail([
56
+ `${id} is an active rule. If the rule is real and simply over, retiring keeps it in the record: npx arbiter record --retire ${id} --why "<reason>"`,
57
+ `If it was never a real rule, take it out of both: npx arbiter remove ${id} --force`,
58
+ ]);
59
+ }
60
+ const later = archive.find((d) => d.supersedes === id);
61
+ if (later) {
62
+ return fail([`${later.id} supersedes ${id} — removing it would leave ${later.id} pointing at nothing. Remove ${later.id} first if neither is real.`]);
63
+ }
64
+ (0, store_1.writeArchive)(paths, archive.filter((d) => d.id !== id));
65
+ if (isActive) {
66
+ const config = (0, store_1.readConfig)(paths);
67
+ (0, store_1.writeActive)(paths, active.filter((d) => d.id !== id), config?.activeCap ?? store_1.ACTIVE_CAP);
68
+ }
69
+ const touched = refreshLinked(paths, entry.candidate);
70
+ // Removing a rule doesn't bring back the one it replaced: that one may have been real, and
71
+ // guessing would put a rule back the user never re-confirmed. Say so rather than lose it quietly.
72
+ const replaced = entry.supersedes && archive.find((d) => d.id === entry.supersedes);
73
+ // Ids come from the highest in the file, so taking the last one out frees it for the next
74
+ // decision. Locally that's harmless; on a board already published, comments point at the id.
75
+ const reused = archive.every((d) => d.id <= id) ? id : null;
76
+ return {
77
+ exitCode: 0,
78
+ output: {
79
+ status: 'removed',
80
+ id,
81
+ decision: entry.decision,
82
+ ...(replaced ? { note: `${replaced.id} — which ${id} replaced — is still inactive. Record it again if it should apply.` } : {}),
83
+ ...(reused ? { idReuse: `${id} was the newest, so the next decision recorded will take that id again. If this board is published, comments on the old ${id} will read as if they were about the new one — republish after recording.` } : {}),
84
+ wrote: ['.arbiter/archive.md', ...(isActive ? ['DECISIONS.md'] : []), ...touched],
85
+ // Printed in full so it can be put back by hand — not everyone has git.
86
+ removed: (0, format_1.formatEntry)(entry).trimEnd(),
87
+ },
88
+ };
89
+ }
90
+ function removeCandidate(id, opts) {
91
+ const root = (0, store_1.findRoot)(opts.cwd);
92
+ const paths = (0, store_1.resolvePaths)(root);
93
+ const all = (0, candidates_1.readCandidates)(paths);
94
+ const c = all.find((x) => x.id === id);
95
+ if (!c)
96
+ return fail([`${id} is not a candidate here`]);
97
+ const by = all.find((x) => x.supersededBy === id);
98
+ if (by)
99
+ return fail([`${by.id} says it was superseded by ${id} — clear that first: npx arbiter candidate ${by.id} --state generated`]);
100
+ const archive = (0, store_1.readArchive)(paths);
101
+ const pending = (0, store_1.readPending)(paths);
102
+ const linked = [...archive, ...pending].filter((d) => d.candidate === id);
103
+ if (linked.length && !opts.force) {
104
+ return fail([
105
+ `${linked.length} decision${linked.length === 1 ? '' : 's'} still linked to ${id}: ${linked.map((d) => d.id).join(', ')}.`,
106
+ `Detach them and keep them: npx arbiter unlink ${linked.map((d) => d.id).join(' ')}`,
107
+ `Or remove the screen and detach them in one go: npx arbiter remove ${id} --force`,
108
+ ]);
109
+ }
110
+ if (linked.length)
111
+ unlinkAll(paths, linked.map((d) => d.id));
112
+ const file = (0, candidates_1.candidateFile)(paths, id);
113
+ const shot = c.snapshot ? node_path_1.default.join((0, candidates_1.candidatesDir)(paths), c.snapshot) : null;
114
+ const before = node_fs_1.default.existsSync(file) ? node_fs_1.default.readFileSync(file, 'utf8') : '';
115
+ node_fs_1.default.rmSync(file, { force: true });
116
+ if (shot)
117
+ node_fs_1.default.rmSync(shot, { force: true });
118
+ const config = (0, store_1.readConfig)(paths);
119
+ const delivered = (0, destination_1.deliver)(paths, config, [], `remove ${id}`);
120
+ return {
121
+ exitCode: 0,
122
+ output: {
123
+ status: 'removed',
124
+ id,
125
+ name: c.name,
126
+ ...(linked.length ? { unlinked: linked.map((d) => d.id) } : {}),
127
+ ...(all.every((x) => x.id <= id) ? { idReuse: `${id} was the newest, so the next screen added will take that id again.` } : {}),
128
+ wrote: [node_path_1.default.relative(root, file), ...(shot ? [node_path_1.default.relative(root, shot)] : [])].map((p) => p.split(node_path_1.default.sep).join('/')),
129
+ removed: before.trimEnd(),
130
+ ...(delivered.destination === 'git' ? { destination: 'git', committed: delivered.committed } : {}),
131
+ },
132
+ };
133
+ }
134
+ /** `arbiter remove --snapshot "<piece of work>"` — the picture goes, the work stays. */
135
+ function removeSnapshot(name, opts = {}) {
136
+ const root = (0, store_1.findRoot)(opts.cwd);
137
+ const paths = (0, store_1.resolvePaths)(root);
138
+ const trigger = name?.trim() ?? '';
139
+ if (!trigger)
140
+ return fail(['name the piece of work, as the decisions did: npx arbiter remove --snapshot "Settings — billing"']);
141
+ // A candidate's picture belongs to the candidate; take it off there.
142
+ const cand = (0, candidates_1.readCandidates)(paths).find((c) => c.id === trigger || c.name === trigger);
143
+ if (cand) {
144
+ if (!cand.snapshot)
145
+ return fail([`${cand.id} has no picture`]);
146
+ const shot = node_path_1.default.join((0, candidates_1.candidatesDir)(paths), cand.snapshot);
147
+ node_fs_1.default.rmSync(shot, { force: true });
148
+ (0, candidates_1.writeCandidate)(paths, { ...cand, snapshot: null });
149
+ const delivered = (0, destination_1.deliver)(paths, (0, store_1.readConfig)(paths), [{ ...cand, snapshot: null }], `remove snapshot ${cand.id}`);
150
+ return {
151
+ exitCode: 0,
152
+ output: { status: 'removed', id: cand.id, wrote: [node_path_1.default.relative(root, shot).split(node_path_1.default.sep).join('/')], ...(delivered.destination === 'git' ? { committed: delivered.committed } : {}) },
153
+ };
154
+ }
155
+ const id = (0, work_1.workId)(trigger);
156
+ const file = (0, work_1.workSnapshot)(paths, id);
157
+ if (!file)
158
+ return fail([`no picture attached to "${trigger}"`]);
159
+ node_fs_1.default.rmSync(file, { force: true });
160
+ return {
161
+ exitCode: 0,
162
+ output: {
163
+ status: 'removed',
164
+ work: trigger,
165
+ id,
166
+ wrote: [node_path_1.default.relative(root, file).split(node_path_1.default.sep).join('/')],
167
+ note: 'the board keeps the old picture until the next `npx arbiter publish`',
168
+ },
169
+ };
170
+ }
171
+ // ── unlink ─────────────────────────────────────────────────────────────────
172
+ /** Detach recorded decisions from their screen. The decisions stay exactly as they are. */
173
+ function unlink(ids, opts = {}) {
174
+ const paths = (0, store_1.resolvePaths)((0, store_1.findRoot)(opts.cwd));
175
+ const wanted = (ids ?? []).map((i) => i.trim()).filter(Boolean);
176
+ if (!wanted.length)
177
+ return fail(['name at least one decision: npx arbiter unlink D-0004']);
178
+ const bad = wanted.filter((i) => !schema_1.DECISION_ID.test(i) && !/^P-\d{4,}$/.test(i));
179
+ if (bad.length)
180
+ return fail([`not decision ids: ${bad.join(', ')} (D-0004, or P-0003 while queued)`]);
181
+ const archive = (0, store_1.readArchive)(paths);
182
+ const pending = (0, store_1.readPending)(paths);
183
+ const known = new Map([...archive, ...pending].map((d) => [d.id, d]));
184
+ const missing = wanted.filter((i) => !known.has(i));
185
+ if (missing.length)
186
+ return fail([`not found: ${missing.join(', ')}`]);
187
+ const unattached = wanted.filter((i) => !known.get(i).candidate);
188
+ if (unattached.length === wanted.length)
189
+ return fail([`already attached to no screen: ${unattached.join(', ')}`]);
190
+ const changed = wanted.filter((i) => known.get(i).candidate);
191
+ const from = new Set(changed.map((i) => known.get(i).candidate));
192
+ unlinkAll(paths, changed);
193
+ return {
194
+ exitCode: 0,
195
+ output: {
196
+ status: 'unlinked',
197
+ ids: changed,
198
+ from: [...from],
199
+ ...(unattached.length ? { alreadyLoose: unattached } : {}),
200
+ wrote: ['.arbiter/archive.md', ...refreshMany(paths, from)],
201
+ },
202
+ };
203
+ }
204
+ // ── shared ─────────────────────────────────────────────────────────────────
205
+ /** Clear `candidate` on the named decisions, wherever they live, and refresh the screens they left. */
206
+ function unlinkAll(paths, ids) {
207
+ const set = new Set(ids);
208
+ const archive = (0, store_1.readArchive)(paths);
209
+ if (archive.some((d) => set.has(d.id))) {
210
+ (0, store_1.writeArchive)(paths, archive.map((d) => (set.has(d.id) ? { ...d, candidate: null } : d)));
211
+ }
212
+ const pending = (0, store_1.readPending)(paths);
213
+ if (pending.some((d) => set.has(d.id))) {
214
+ (0, store_1.writePending)(paths, pending.map((d) => (set.has(d.id) ? { ...d, candidate: null } : d)));
215
+ }
216
+ }
217
+ /** A screen's file lists its decisions, so it has to be rewritten when that list changes. */
218
+ function refreshLinked(paths, candidate) {
219
+ if (!candidate)
220
+ return [];
221
+ return refreshMany(paths, new Set([candidate]));
222
+ }
223
+ function refreshMany(paths, ids) {
224
+ const wrote = [];
225
+ for (const c of (0, candidates_1.readCandidates)(paths)) {
226
+ if (!ids.has(c.id))
227
+ continue;
228
+ (0, candidates_1.writeCandidate)(paths, c);
229
+ wrote.push(`.arbiter/candidates/${c.id}.md`);
230
+ }
231
+ return wrote;
232
+ }
@@ -20,6 +20,7 @@ const candidate_1 = require("./candidate");
20
20
  const candidates_1 = require("../candidates");
21
21
  const hosted_1 = require("../hosted");
22
22
  const store_1 = require("../store");
23
+ const autopublish_1 = require("../autopublish");
23
24
  const PAGE = node_path_1.default.join(__dirname, '..', '..', 'templates', 'review.html');
24
25
  function review(opts = {}) {
25
26
  const root = (0, store_1.findRoot)(opts.cwd);
@@ -44,6 +45,9 @@ function review(opts = {}) {
44
45
  cap: (0, store_1.readConfig)(paths)?.activeCap ?? store_1.ACTIVE_CAP,
45
46
  };
46
47
  };
48
+ // Judging twenty items shouldn't mean twenty publishes, so the board is updated once, at the
49
+ // end. The page writes the same files the CLI does, but doesn't go through its handlers.
50
+ let changed = false;
47
51
  return new Promise((resolve) => {
48
52
  const server = node_http_1.default.createServer(async (req, res) => {
49
53
  const url = new URL(req.url ?? '/', 'http://127.0.0.1');
@@ -59,12 +63,16 @@ function review(opts = {}) {
59
63
  if (req.method === 'POST' && url.pathname === '/api/judge') {
60
64
  const body = JSON.parse(await readBody(req));
61
65
  const result = (0, record_1.judge)(body.id, { as: body.as, to: body.to, supersedes: body.supersedes, keepBoth: body.keepBoth, cwd });
66
+ if (result.exitCode === 0)
67
+ changed = true;
62
68
  json(res, 200, { exitCode: result.exitCode, ...result.output });
63
69
  return;
64
70
  }
65
71
  if (req.method === 'POST' && url.pathname === '/api/judge-all') {
66
72
  const body = JSON.parse(await readBody(req));
67
73
  const result = (0, record_1.judgeAll)({ as: body.as, level: body.level, trigger: body.trigger, cwd });
74
+ if (result.exitCode === 0)
75
+ changed = true;
68
76
  json(res, 200, { exitCode: result.exitCode, ...result.output });
69
77
  return;
70
78
  }
@@ -84,6 +92,8 @@ function review(opts = {}) {
84
92
  if (req.method === 'POST' && url.pathname === '/api/candidate') {
85
93
  const body = JSON.parse(await readBody(req));
86
94
  const result = (0, candidate_1.updateCandidate)(body.id, { state: body.state, why: body.why, keepOthers: body.keepOthers, cwd });
95
+ if (result.exitCode === 0)
96
+ changed = true;
87
97
  json(res, 200, { exitCode: result.exitCode, ...result.output });
88
98
  return;
89
99
  }
@@ -105,7 +115,14 @@ function review(opts = {}) {
105
115
  });
106
116
  // Browsers keep connections alive; close() alone would wait on them forever.
107
117
  const stop = () => {
108
- server.close(() => resolve());
118
+ server.close(async () => {
119
+ if (changed) {
120
+ const line = await (0, autopublish_1.autoPublish)(cwd);
121
+ if (line)
122
+ process.stdout.write(line + '\n');
123
+ }
124
+ resolve();
125
+ });
109
126
  server.closeAllConnections();
110
127
  };
111
128
  process.on('SIGINT', stop);
@@ -15,6 +15,7 @@ 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 update_1 = require("./update");
18
19
  function rules(id, opts = {}) {
19
20
  const paths = (0, store_1.resolvePaths)((0, store_1.findRoot)(opts.cwd));
20
21
  opts = { ...opts, config: (0, store_1.readConfig)(paths) };
@@ -24,7 +25,7 @@ function rules(id, opts = {}) {
24
25
  if (opts.archive)
25
26
  return archive((0, store_1.readArchive)(paths), (0, store_1.readActive)(paths), opts);
26
27
  if (opts.pending)
27
- return pendingList((0, store_1.readPending)(paths), opts);
28
+ return pendingList((0, store_1.readPending)(paths), opts, paths);
28
29
  let active = (0, store_1.readActive)(paths);
29
30
  if (opts.dimension) {
30
31
  if (!schema_1.DIMENSIONS.includes(opts.dimension)) {
@@ -56,12 +57,13 @@ function rules(id, opts = {}) {
56
57
  * Pattern Half-width cards use icon-only action buttons
57
58
  * Rejected A labelled button — wrapped under the text on mobile
58
59
  */
59
- function pendingList(pending, opts) {
60
+ function pendingList(pending, opts, paths) {
60
61
  const groups = groupByTrigger(pending);
61
62
  if (opts.json) {
62
63
  return JSON.stringify({
63
64
  firstRun: !opts.config?.onboarded,
64
65
  checkin: opts.config?.checkin ?? 'feature',
66
+ ...(0, update_1.updateNotice)(paths),
65
67
  count: pending.length,
66
68
  polish: pending.filter((d) => d.level === 'polish').length,
67
69
  groups: groups.map((g) => ({ trigger: g.trigger, items: g.items, polish: g.polish })),