arbiterdesign 0.1.0

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.
package/dist/format.js ADDED
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ /**
3
+ * Markdown serialization for decisions. One format, two files.
4
+ *
5
+ * ### D-0001 · Destructive actions confirm in a modal, never inline
6
+ *
7
+ * - **Change:** The delete-project link now opens a confirm modal
8
+ * - **Rationale:** Inline confirms get clicked through; a modal forces the pause.
9
+ * - **Rejected:**
10
+ * - Inline confirm — clicked through without reading
11
+ * - **Trigger:** Delete-project flow used an inline "Are you sure?" link
12
+ * - **Scope:** pattern:destructive-confirm · **Dimension:** interaction · **Level:** pattern · **Class:** judgment · **Verdict:** rule
13
+ * - **Author:** edmond · **Date:** 2026-09-15T14:32:10Z · **Commit:** a1b2c3d · **Supersedes:** —
14
+ *
15
+ * DECISIONS.md groups entries under `## <Dimension>` headings; the archive is
16
+ * flat and chronological. Round-trip is lossless: parse(format(d)) deep-equals d.
17
+ * The separator ` · ` only joins fields that can't contain it (enums, ids, SHAs,
18
+ * dates, names).
19
+ */
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.DIMENSION_LABELS = void 0;
22
+ exports.formatEntry = formatEntry;
23
+ exports.formatGrouped = formatGrouped;
24
+ exports.parseEntries = parseEntries;
25
+ exports.activeHeader = activeHeader;
26
+ exports.archiveHeader = archiveHeader;
27
+ exports.pendingHeader = pendingHeader;
28
+ const schema_1 = require("./schema");
29
+ const SEP = ' · ';
30
+ const NONE = '—';
31
+ const HEADING = /^#{2,3} ([DP]-\d{4,}) · (.*)$/;
32
+ const REJECTED_ITEM = /^ {2}- (.*)$/;
33
+ const FIELD = /\*\*([A-Za-z]+):\*\* (.*?)(?=\s·\s\*\*|$)/g;
34
+ function formatEntry(d) {
35
+ return [
36
+ `### ${d.id}${SEP}${d.decision}`,
37
+ '',
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)}`] : []),
47
+ ...(d.expect ? [`- **Expect:** ${JSON.stringify(d.expect)}${SEP}**Verified:** ${d.verified === null ? NONE : d.verified ? 'yes' : 'no'}`] : []),
48
+ '',
49
+ ].join('\n');
50
+ }
51
+ exports.DIMENSION_LABELS = {
52
+ structure: 'Structure',
53
+ interaction: 'Interaction',
54
+ states: 'States',
55
+ content: 'Content',
56
+ visual: 'Visual',
57
+ motion: 'Motion',
58
+ access: 'Accessibility',
59
+ };
60
+ /** Entries grouped under `## <Dimension>` headings, in fixed dimension order, by id within. */
61
+ function formatGrouped(decisions) {
62
+ const blocks = [];
63
+ for (const dim of schema_1.DIMENSIONS) {
64
+ const group = decisions.filter((d) => d.dimension === dim).sort((a, b) => a.id.localeCompare(b.id));
65
+ if (!group.length)
66
+ continue;
67
+ blocks.push(`## ${exports.DIMENSION_LABELS[dim]}\n\n${group.map(formatEntry).join('\n')}`);
68
+ }
69
+ return blocks.join('\n');
70
+ }
71
+ /**
72
+ * Parse every `## D-xxxx` entry out of a markdown document. Anything before the
73
+ * first entry (headers, prose) is ignored, so files can carry a human preamble.
74
+ */
75
+ function parseEntries(md) {
76
+ const out = [];
77
+ const lines = md.split('\n');
78
+ let cur = null;
79
+ let inRejected = false;
80
+ const flush = () => {
81
+ if (!cur)
82
+ return;
83
+ out.push(complete(cur));
84
+ cur = null;
85
+ };
86
+ for (const raw of lines) {
87
+ const line = raw.replace(/\r$/, '');
88
+ const h = HEADING.exec(line);
89
+ if (h) {
90
+ flush();
91
+ cur = { id: h[1], decision: h[2].trim(), rejected: [] };
92
+ inRejected = false;
93
+ continue;
94
+ }
95
+ if (/^#{1,6} /.test(line)) {
96
+ // Some other heading — ends the current entry.
97
+ flush();
98
+ continue;
99
+ }
100
+ if (!cur)
101
+ continue;
102
+ if (inRejected) {
103
+ const item = REJECTED_ITEM.exec(line);
104
+ if (item) {
105
+ cur.rejected.push(item[1].trim());
106
+ continue;
107
+ }
108
+ inRejected = false;
109
+ }
110
+ if (!line.startsWith('- **'))
111
+ continue;
112
+ if (line === '- **Rejected:**') {
113
+ inRejected = true;
114
+ continue;
115
+ }
116
+ for (const m of line.slice(2).matchAll(FIELD)) {
117
+ const key = m[1].toLowerCase();
118
+ const val = m[2].trim();
119
+ switch (key) {
120
+ case 'change':
121
+ cur.change = val;
122
+ break;
123
+ case 'level':
124
+ cur.level = val;
125
+ break;
126
+ case 'rationale':
127
+ cur.rationale = val;
128
+ break;
129
+ case 'trigger':
130
+ cur.trigger = val;
131
+ break;
132
+ case 'scope':
133
+ cur.scope = val;
134
+ break;
135
+ case 'dimension':
136
+ cur.dimension = val;
137
+ break;
138
+ case 'class':
139
+ cur.class = val;
140
+ break;
141
+ case 'verdict':
142
+ cur.verdict = val;
143
+ break;
144
+ case 'author':
145
+ cur.author = val;
146
+ break;
147
+ case 'date':
148
+ cur.date = val;
149
+ break;
150
+ case 'commit':
151
+ cur.commit = val === NONE ? null : val;
152
+ break;
153
+ case 'supersedes':
154
+ cur.supersedes = val === NONE ? null : val;
155
+ break;
156
+ case 'ref':
157
+ cur.ref = val === NONE ? null : val;
158
+ break;
159
+ case 'candidate':
160
+ cur.candidate = val === NONE ? null : val;
161
+ break;
162
+ case 'files':
163
+ cur.files = val.split(SEP).map((f) => f.trim()).filter(Boolean);
164
+ break;
165
+ case 'paths':
166
+ cur.paths = val.split(SEP).map((f) => f.trim()).filter(Boolean);
167
+ break;
168
+ case 'expect':
169
+ cur.expect = JSON.parse(val);
170
+ break;
171
+ case 'verified':
172
+ cur.verified = val === NONE ? null : val === 'yes';
173
+ break;
174
+ }
175
+ }
176
+ }
177
+ flush();
178
+ return out;
179
+ }
180
+ function complete(p) {
181
+ const missing = ['id', 'decision', 'rationale', 'trigger', 'scope', 'dimension', 'class', 'verdict', 'author', 'date']
182
+ .filter((k) => p[k] === undefined);
183
+ if (missing.length) {
184
+ throw new Error(`entry ${p.id ?? '?'} is missing: ${missing.join(', ')}`);
185
+ }
186
+ if (!schema_1.ID_PATTERN.test(p.id))
187
+ throw new Error(`bad id: ${p.id}`);
188
+ return {
189
+ id: p.id,
190
+ decision: p.decision,
191
+ change: p.change ?? null,
192
+ // Entries written before levels existed read as pattern — the middle ground.
193
+ level: p.level ?? 'pattern',
194
+ rationale: p.rationale,
195
+ rejected: p.rejected ?? [],
196
+ trigger: p.trigger,
197
+ scope: p.scope,
198
+ dimension: p.dimension,
199
+ class: p.class,
200
+ verdict: p.verdict,
201
+ author: p.author,
202
+ date: p.date,
203
+ commit: p.commit ?? null,
204
+ supersedes: p.supersedes ?? null,
205
+ ref: p.ref ?? null,
206
+ files: p.files ?? [],
207
+ paths: p.paths ?? [],
208
+ expect: p.expect ?? null,
209
+ verified: p.expect ? (p.verified ?? null) : null,
210
+ candidate: p.candidate ?? null,
211
+ };
212
+ }
213
+ function activeHeader(count, cap) {
214
+ return [
215
+ '# Decisions',
216
+ '',
217
+ `Active design rules for this project — ${count} of ${cap}.`,
218
+ '',
219
+ 'Read before any UI work. Each entry is a call that was made once and should not be',
220
+ 're-made. `Change` is what happened in plain words; `Rationale` is the why; `Rejected` is',
221
+ 'what lost, and why; `Trigger` is the case that prompted it. Superseded rules drop out of',
222
+ 'here and stay in `.arbiter/archive.md`.',
223
+ '',
224
+ 'Add entries with `npx arbiter record`. Edit by hand if you must — the format round-trips.',
225
+ '',
226
+ ].join('\n');
227
+ }
228
+ function archiveHeader() {
229
+ return [
230
+ '# Decision archive',
231
+ '',
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.',
235
+ '',
236
+ ].join('\n');
237
+ }
238
+ function pendingHeader() {
239
+ return [
240
+ '# Pending decisions',
241
+ '',
242
+ 'Queued by the agent, not yet judged. Review with `npx arbiter review` or `/arbiter` in chat.',
243
+ 'Judged entries move to `.arbiter/archive.md` (and `DECISIONS.md` if made a rule); skipped',
244
+ 'entries are dropped. Nothing here is in agent context.',
245
+ '',
246
+ ].join('\n');
247
+ }
package/dist/hosted.js ADDED
@@ -0,0 +1,222 @@
1
+ "use strict";
2
+ /**
3
+ * Talking to a hosted board (the Next.js app in hosted/). The only network
4
+ * code in Arbiter, and it runs only for `publish --to` and `pull`.
5
+ *
6
+ * Two files: .arbiter/hosted.json (committed — which site, which project,
7
+ * the share link) and .arbiter/hosted.token (git-ignored — the publish
8
+ * token). Teammates get the first from git and the second from
9
+ * ARBITER_PUBLISH_TOKEN, so everyone updates the same board.
10
+ */
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.ADMIN_ENV = exports.TOKEN_ENV = void 0;
16
+ exports.readLink = readLink;
17
+ exports.writeLink = writeLink;
18
+ exports.readToken = readToken;
19
+ exports.writeToken = writeToken;
20
+ exports.readComments = readComments;
21
+ exports.writeComments = writeComments;
22
+ exports.buildManifest = buildManifest;
23
+ exports.publishHosted = publishHosted;
24
+ exports.pullHosted = pullHosted;
25
+ const node_fs_1 = __importDefault(require("node:fs"));
26
+ const node_path_1 = __importDefault(require("node:path"));
27
+ const candidates_1 = require("./candidates");
28
+ const store_1 = require("./store");
29
+ const work_1 = require("./work");
30
+ const LINK_FILE = 'hosted.json';
31
+ const TOKEN_FILE = 'hosted.token';
32
+ const COMMENTS_FILE = 'comments.json';
33
+ exports.TOKEN_ENV = 'ARBITER_PUBLISH_TOKEN';
34
+ exports.ADMIN_ENV = 'ARBITER_ADMIN_TOKEN';
35
+ const IMAGE_TYPES = { '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif' };
36
+ function readLink(paths) {
37
+ const f = node_path_1.default.join(paths.archiveDir, LINK_FILE);
38
+ if (!node_fs_1.default.existsSync(f))
39
+ return null;
40
+ const raw = JSON.parse(node_fs_1.default.readFileSync(f, 'utf8'));
41
+ // Older files carried the token inline; move it to the ignored file.
42
+ if (raw.token) {
43
+ writeToken(paths, raw.token);
44
+ delete raw.token;
45
+ writeLink(paths, raw);
46
+ }
47
+ return raw;
48
+ }
49
+ function writeLink(paths, link) {
50
+ node_fs_1.default.mkdirSync(paths.archiveDir, { recursive: true });
51
+ node_fs_1.default.writeFileSync(node_path_1.default.join(paths.archiveDir, LINK_FILE), JSON.stringify(link, null, 2) + '\n');
52
+ }
53
+ /** The publish token: env var first (how a team shares it), then the git-ignored file. */
54
+ function readToken(paths) {
55
+ const env = process.env[exports.TOKEN_ENV]?.trim();
56
+ if (env)
57
+ return env;
58
+ const f = node_path_1.default.join(paths.archiveDir, TOKEN_FILE);
59
+ return node_fs_1.default.existsSync(f) ? node_fs_1.default.readFileSync(f, 'utf8').trim() || null : null;
60
+ }
61
+ function writeToken(paths, token) {
62
+ node_fs_1.default.mkdirSync(paths.archiveDir, { recursive: true });
63
+ node_fs_1.default.writeFileSync(node_path_1.default.join(paths.archiveDir, TOKEN_FILE), token + '\n', { mode: 0o600 });
64
+ // Keep it out of git. (hosted.json used to be ignored too; it's shareable now.)
65
+ const gi = node_path_1.default.join(paths.archiveDir, '.gitignore');
66
+ const lines = (node_fs_1.default.existsSync(gi) ? node_fs_1.default.readFileSync(gi, 'utf8') : '').split('\n').filter((l) => l && l !== LINK_FILE);
67
+ if (!lines.includes(TOKEN_FILE))
68
+ lines.push(TOKEN_FILE);
69
+ node_fs_1.default.writeFileSync(gi, lines.join('\n') + '\n');
70
+ }
71
+ function readComments(paths) {
72
+ const f = node_path_1.default.join(paths.archiveDir, COMMENTS_FILE);
73
+ return node_fs_1.default.existsSync(f) ? JSON.parse(node_fs_1.default.readFileSync(f, 'utf8')) : [];
74
+ }
75
+ 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');
77
+ }
78
+ const publishable = (d) => d.verdict !== 'pending' && d.verdict !== 'retire' && d.level !== 'polish';
79
+ 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
+ /**
81
+ * The upload manifest: every judged, non-polish decision, and the rules. A decision attached to a
82
+ * candidate rides with that screen; the rest are grouped by the piece of work they came from
83
+ * (`trigger`) and become a card each — no picture, state `recorded`. Most work is one direction,
84
+ * iterated; the board shouldn't be empty for it.
85
+ */
86
+ function buildManifest(paths, opts = {}) {
87
+ const skipped = [];
88
+ const known = (0, candidates_1.readCandidates)(paths);
89
+ const candidates = known.map((c) => {
90
+ let snapshot = null;
91
+ if (c.snapshot) {
92
+ const ext = node_path_1.default.extname(c.snapshot).toLowerCase();
93
+ const type = IMAGE_TYPES[ext];
94
+ const file = node_path_1.default.join((0, candidates_1.candidatesDir)(paths), c.snapshot);
95
+ if (type && node_fs_1.default.existsSync(file))
96
+ snapshot = { type, data: node_fs_1.default.readFileSync(file).toString('base64') };
97
+ else
98
+ skipped.push(`${c.id}: ${c.snapshot} (${type ? 'missing' : 'svg/unsupported — hosted takes png, jpg, webp, gif'})`);
99
+ }
100
+ return {
101
+ id: c.id,
102
+ name: c.name,
103
+ feature: c.feature,
104
+ state: c.state,
105
+ author: c.author,
106
+ date: c.date,
107
+ reason: c.reason,
108
+ notes: c.notes,
109
+ supersededBy: c.supersededBy,
110
+ url: null,
111
+ snapshot,
112
+ decisions: (0, candidates_1.decisionsFor)(paths, c.id).filter(publishable).map(wire),
113
+ };
114
+ });
115
+ // Screenless decisions: one card per piece of work.
116
+ 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)));
118
+ const byWork = new Map();
119
+ for (const d of loose)
120
+ byWork.set(d.trigger, [...(byWork.get(d.trigger) ?? []), d]);
121
+ const areas = new Map(known.filter((c) => c.feature).map((c) => [c.feature.toLowerCase(), c.feature]));
122
+ for (const [trigger, ds] of byWork) {
123
+ const last = ds.reduce((a, b) => (a.date > b.date ? a : b));
124
+ const id = (0, work_1.workId)(trigger);
125
+ let snapshot = null;
126
+ const shot = (0, work_1.workSnapshot)(paths, id);
127
+ if (shot) {
128
+ const type = IMAGE_TYPES[node_path_1.default.extname(shot).toLowerCase()];
129
+ if (type)
130
+ snapshot = { type, data: node_fs_1.default.readFileSync(shot).toString('base64') };
131
+ else
132
+ skipped.push(`${id}: ${node_path_1.default.basename(shot)} (svg/unsupported — hosted takes png, jpg, webp, gif)`);
133
+ }
134
+ candidates.push({
135
+ // Work has no product area of its own; it joins one only when the trigger names an existing one.
136
+ id, name: trigger, feature: areas.get(trigger.toLowerCase()) ?? null, state: 'recorded', work: true,
137
+ author: last.author, date: last.date, reason: null, notes: '', supersededBy: null, url: null, snapshot,
138
+ decisions: ds.map(wire),
139
+ });
140
+ }
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 };
143
+ }
144
+ async function api(url, init = {}) {
145
+ const headers = { 'content-type': 'application/json', ...init.headers };
146
+ // Raw bytes go up as-is; everything else is JSON.
147
+ if (init.token)
148
+ headers.authorization = `Bearer ${init.token}`;
149
+ if (init.admin)
150
+ headers['x-admin-token'] = init.admin;
151
+ const res = await fetch(url, { ...init, headers });
152
+ let body = {};
153
+ try {
154
+ body = (await res.json());
155
+ }
156
+ catch { /* non-json error */ }
157
+ return { ok: res.ok, status: res.status, body };
158
+ }
159
+ /**
160
+ * Create the project on first publish; then the images, one request each; then the board.
161
+ * Keeps every request under Vercel's 4.5 MB body cap however many screens there are.
162
+ */
163
+ async function publishHosted(paths, serviceUrl, opts = {}) {
164
+ const base = serviceUrl.replace(/\/$/, '');
165
+ let link = readLink(paths);
166
+ let created = false;
167
+ if (!link || link.url !== base) {
168
+ const admin = opts.admin ?? process.env[exports.ADMIN_ENV];
169
+ const r = await api(`${base}/api/projects`, { method: 'POST', body: JSON.stringify({ name: node_path_1.default.basename(paths.root) }), admin });
170
+ if (r.status === 401)
171
+ throw new Error(`${base} needs an admin token to create projects. Ask whoever runs it, then: ${exports.ADMIN_ENV}=<token> npx arbiter publish --to ${base}`);
172
+ if (!r.ok)
173
+ throw new Error(`could not create project on ${base}: ${r.body.error ?? r.status}`);
174
+ link = { url: base, projectId: String(r.body.id), slug: String(r.body.slug), shareUrl: String(r.body.url) };
175
+ writeLink(paths, link);
176
+ writeToken(paths, String(r.body.token));
177
+ created = true;
178
+ }
179
+ const token = readToken(paths);
180
+ if (!token)
181
+ throw new Error(`no publish token for ${link.shareUrl}. Teammate? Get it from whoever first published, then: ${exports.TOKEN_ENV}=<token> npx arbiter publish`);
182
+ const config = (0, store_1.readConfig)(paths);
183
+ const { manifest, skipped } = buildManifest(paths, { includeRules: !!(config?.pages && config.pages.includeRules) });
184
+ let snapshots = 0;
185
+ for (const c of manifest.candidates) {
186
+ if (!c.snapshot || typeof c.snapshot === 'string')
187
+ continue;
188
+ const up = await api(`${base}/api/projects/${link.projectId}/snapshots/${c.id}`, { method: 'PUT', body: Buffer.from(c.snapshot.data, 'base64'), headers: { 'content-type': c.snapshot.type }, token });
189
+ if (up.status === 401)
190
+ throw new Error(`the publish token was refused by ${base} — wrong ${exports.TOKEN_ENV}, or the project was deleted`);
191
+ if (!up.ok)
192
+ throw new Error(`${c.id}: snapshot upload failed: ${up.body.error ?? up.status}`);
193
+ c.snapshot = String(up.body.url);
194
+ snapshots++;
195
+ }
196
+ const r = await api(`${base}/api/projects/${link.projectId}/board`, { method: 'PUT', body: JSON.stringify(manifest), token });
197
+ if (r.status === 401)
198
+ throw new Error(`the publish token was refused by ${base} — wrong ${exports.TOKEN_ENV}, or the project was deleted`);
199
+ if (!r.ok)
200
+ throw new Error(`publish failed: ${r.body.error ?? r.status}`);
201
+ return { link, candidates: Number(r.body.candidates ?? 0), snapshots, skipped, created };
202
+ }
203
+ /** Fetch comments since the last pull; merge into .arbiter/comments.json. */
204
+ async function pullHosted(paths) {
205
+ const link = readLink(paths);
206
+ if (!link)
207
+ throw new Error('no hosted board — run `npx arbiter publish --to <url>` first');
208
+ const token = readToken(paths);
209
+ if (!token)
210
+ throw new Error(`no publish token for ${link.shareUrl}. Get it from whoever first published, then: ${exports.TOKEN_ENV}=<token> npx arbiter pull`);
211
+ const q = link.lastPull ? `?since=${encodeURIComponent(link.lastPull)}` : '';
212
+ const r = await api(`${link.url}/api/projects/${link.projectId}/comments${q}`, { token });
213
+ if (!r.ok)
214
+ throw new Error(`pull failed: ${r.body.error ?? r.status}`);
215
+ const fresh = r.body.comments ?? [];
216
+ const existing = readComments(paths);
217
+ const seen = new Set(existing.map((c) => c.id));
218
+ const merged = [...existing, ...fresh.filter((c) => !seen.has(c.id))].sort((a, b) => a.created_at.localeCompare(b.created_at));
219
+ writeComments(paths, merged);
220
+ writeLink(paths, { ...link, lastPull: String(r.body.fetched_at ?? new Date().toISOString()), boardVersion: r.body.board_version ?? link.boardVersion ?? null });
221
+ return { link, fresh, total: merged.length };
222
+ }