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/sweep.js ADDED
@@ -0,0 +1,128 @@
1
+ "use strict";
2
+ /**
3
+ * Sweep: apply a mechanical rule backwards. Search existing source for the
4
+ * rule's forbidden strings (`expect.absent`). Read-only; reports, never edits.
5
+ * Only mechanical rules with `absent` needles can sweep — judgment rules
6
+ * inform generation and nothing more.
7
+ */
8
+ var __importDefault = (this && this.__importDefault) || function (mod) {
9
+ return (mod && mod.__esModule) ? mod : { "default": mod };
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.sweep = sweep;
13
+ exports.globToRegex = globToRegex;
14
+ exports.summarize = summarize;
15
+ const node_fs_1 = __importDefault(require("node:fs"));
16
+ const node_path_1 = __importDefault(require("node:path"));
17
+ const schema_1 = require("./schema");
18
+ const verify_1 = require("./verify");
19
+ const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', 'coverage', '.arbiter', '.turbo', '.cache', 'vendor']);
20
+ const SOURCE_EXT = new Set(['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs', '.vue', '.svelte', '.astro', '.css', '.scss', '.less', '.html']);
21
+ const MAX_FILES = 5000;
22
+ const MAX_BYTES = 1_000_000;
23
+ function sweep(root, rule, opts = {}) {
24
+ const needles = rule.expect?.absent ?? [];
25
+ const excluded = opts.exclude ?? [];
26
+ const none = (reason) => ({ sweepable: false, reason, needles, filesScanned: 0, violations: [], scanned: 'project', excluded });
27
+ if (rule.class !== 'mechanical')
28
+ return none('judgment rules cannot sweep — they inform, they never enforce');
29
+ if (!needles.length)
30
+ return none('rule has no expect.absent strings to search for');
31
+ const { files: candidates, scanned } = targetFiles(root, rule);
32
+ const skip = excluded.map(globToRegex);
33
+ const files = candidates.filter((f) => !skip.some((re) => re.test(f)));
34
+ const violations = [];
35
+ for (const f of files) {
36
+ const abs = node_path_1.default.join(root, f);
37
+ let text;
38
+ try {
39
+ if (node_fs_1.default.statSync(abs).size > MAX_BYTES)
40
+ continue;
41
+ text = node_fs_1.default.readFileSync(abs, 'utf8');
42
+ }
43
+ catch {
44
+ continue;
45
+ }
46
+ const finders = needles.map((n) => [n, (0, verify_1.matcher)(n)]);
47
+ if (!finders.some(([, find]) => find(text) >= 0))
48
+ continue;
49
+ const lines = text.split('\n');
50
+ lines.forEach((line, i) => {
51
+ for (const [n, find] of finders)
52
+ if (find(line) >= 0)
53
+ violations.push({ file: f, line: i + 1, needle: n, text: line.trim().slice(0, 120) });
54
+ });
55
+ }
56
+ return { sweepable: true, needles, filesScanned: files.length, violations, scanned, excluded };
57
+ }
58
+ /**
59
+ * The scan set, narrowest first: the rule's `paths` (files or directories)
60
+ * if it has any; else a file: scope; else every source file in the project.
61
+ * A pattern: rule with no `paths` sweeps the whole project — name the
62
+ * directories it applies to if that's too wide.
63
+ */
64
+ function targetFiles(root, rule) {
65
+ const expand = (p) => {
66
+ const abs = node_path_1.default.resolve(root, p);
67
+ if (!abs.startsWith(node_path_1.default.resolve(root)) || !node_fs_1.default.existsSync(abs))
68
+ return [];
69
+ return node_fs_1.default.statSync(abs).isFile() ? [node_path_1.default.relative(root, abs)] : walk(abs, root);
70
+ };
71
+ if (rule.paths.length)
72
+ return { files: [...new Set(rule.paths.flatMap(expand))], scanned: 'rule.paths' };
73
+ const scope = (0, schema_1.parseScope)(rule.scope);
74
+ if (scope.kind === 'file')
75
+ return { files: expand(scope.target), scanned: 'scope' };
76
+ return { files: walk(root, root), scanned: 'project' };
77
+ }
78
+ function walk(dir, root, out = []) {
79
+ if (out.length >= MAX_FILES)
80
+ return out;
81
+ let entries;
82
+ try {
83
+ entries = node_fs_1.default.readdirSync(dir, { withFileTypes: true });
84
+ }
85
+ catch {
86
+ return out;
87
+ }
88
+ for (const e of entries) {
89
+ if (out.length >= MAX_FILES)
90
+ break;
91
+ if (e.isDirectory()) {
92
+ if (!SKIP_DIRS.has(e.name) && !e.name.startsWith('.'))
93
+ walk(node_path_1.default.join(dir, e.name), root, out);
94
+ }
95
+ else if (e.isFile() && SOURCE_EXT.has(node_path_1.default.extname(e.name))) {
96
+ out.push(node_path_1.default.relative(root, node_path_1.default.join(dir, e.name)));
97
+ }
98
+ }
99
+ return out;
100
+ }
101
+ /** Minimal glob: `**` any depth, `*` within a segment, `?` one char. Anchored to the relative path. */
102
+ function globToRegex(glob) {
103
+ let out = '';
104
+ const g = glob.replace(/\\/g, '/');
105
+ for (let i = 0; i < g.length; i++) {
106
+ const ch = g[i];
107
+ if (ch === '*' && g[i + 1] === '*') {
108
+ if (g[i + 2] === '/') {
109
+ out += '(?:.*/)?';
110
+ i += 2;
111
+ }
112
+ else {
113
+ out += '.*';
114
+ i += 1;
115
+ }
116
+ }
117
+ else if (ch === '*')
118
+ out += '[^/]*';
119
+ else if (ch === '?')
120
+ out += '[^/]';
121
+ else
122
+ out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
123
+ }
124
+ return new RegExp(`^${out}$`);
125
+ }
126
+ function summarize(r) {
127
+ return { violations: r.violations.length, files: new Set(r.violations.map((v) => v.file)).size };
128
+ }
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_test_1 = require("node:test");
7
+ const strict_1 = __importDefault(require("node:assert/strict"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const node_http_1 = __importDefault(require("node:http"));
12
+ const candidate_1 = require("../commands/candidate");
13
+ const record_1 = require("../commands/record");
14
+ const publish_1 = require("../commands/publish");
15
+ const pull_1 = require("../commands/pull");
16
+ const snapshot_1 = require("../commands/snapshot");
17
+ const hosted_1 = require("../hosted");
18
+ const store_1 = require("../store");
19
+ const tmp = () => node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'arbiter-hosted-'));
20
+ const write = (cwd, rel, data) => { node_fs_1.default.mkdirSync(node_path_1.default.join(cwd, node_path_1.default.dirname(rel)), { recursive: true }); node_fs_1.default.writeFileSync(node_path_1.default.join(cwd, rel), data); };
21
+ const PNG = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==', 'base64');
22
+ /** A stand-in for hosted/: same three routes, same shapes, in memory. */
23
+ function fakeService() {
24
+ const state = { boards: {}, comments: [], tokens: {} };
25
+ return new Promise((resolve) => {
26
+ const server = node_http_1.default.createServer(async (req, res) => {
27
+ const body = await new Promise((r) => { let d = ''; req.on('data', (c) => (d += c)); req.on('end', () => r(d)); });
28
+ const send = (status, obj) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(obj)); };
29
+ const url = new URL(req.url, 'http://x');
30
+ const auth = req.headers.authorization?.replace('Bearer ', '');
31
+ if (req.method === 'POST' && url.pathname === '/api/projects') {
32
+ const id = 'p1';
33
+ state.tokens[id] = 'tok-secret';
34
+ return send(201, { id, slug: 'abc123', token: 'tok-secret', url: 'http://x/p/abc123' });
35
+ }
36
+ const m = /^\/api\/projects\/([^/]+)\/(board|comments|snapshots\/(?:C-\d+|W-[a-z0-9-]+))$/.exec(url.pathname);
37
+ if (!m)
38
+ return send(404, {});
39
+ if (state.tokens[m[1]] !== auth)
40
+ return send(401, { error: 'bad token' });
41
+ if (m[2].startsWith('snapshots/') && req.method === 'PUT') {
42
+ const type = req.headers['content-type'] ?? '';
43
+ if (!/^image\/(png|jpeg|webp|gif)$/.test(type))
44
+ return send(400, { error: 'type' });
45
+ if (!body.length)
46
+ return send(400, { error: 'empty' });
47
+ return send(200, { ok: true, url: `http://x/snap/${m[2].slice(10)}.png` });
48
+ }
49
+ if (m[2] === 'board' && req.method === 'PUT') {
50
+ const b = JSON.parse(body);
51
+ for (const c of b.candidates)
52
+ if (c.snapshot && typeof c.snapshot !== 'string')
53
+ return send(400, { error: 'bytes inline — upload through the snapshots route' });
54
+ state.boards[m[1]] = b;
55
+ return send(200, { ok: true, candidates: b.candidates.length, url: 'http://x/p/abc123' });
56
+ }
57
+ if (m[2] === 'comments' && req.method === 'GET') {
58
+ const since = url.searchParams.get('since');
59
+ const list = state.comments.filter((c) => !since || c.created_at > since);
60
+ return send(200, { comments: list, fetched_at: new Date().toISOString() });
61
+ }
62
+ send(405, {});
63
+ });
64
+ server.listen(0, '127.0.0.1', () => {
65
+ const { port } = server.address();
66
+ resolve({ url: `http://127.0.0.1:${port}`, state, close: () => server.close() });
67
+ });
68
+ });
69
+ }
70
+ (0, node_test_1.test)('publish --to creates the project once, uploads the board, pull merges comments', async () => {
71
+ const cwd = tmp();
72
+ const o = { cwd, author: 'test' };
73
+ write(cwd, 'shot.png', PNG);
74
+ write(cwd, 'shot.svg', '<svg xmlns="http://www.w3.org/2000/svg"/>');
75
+ (0, candidate_1.addCandidate)('Billing v2', { ...o, feature: 'billing', snapshot: 'shot.png' });
76
+ (0, candidate_1.addCandidate)('Billing v1', { ...o, feature: 'billing', snapshot: 'shot.svg' });
77
+ (0, record_1.record)(JSON.stringify({ change: 'Plan and card side by side', decision: 'Two half-width cards', rationale: 'r', trigger: 'Billing', scope: 'file:b.tsx', dimension: 'structure', class: 'judgment', verdict: 'accept', level: 'feature' }), { ...o, candidate: 'C-0001' });
78
+ (0, record_1.record)(JSON.stringify({ decision: 'h-9', rationale: 'r', trigger: 'Billing', scope: 'file:b.tsx', dimension: 'visual', class: 'mechanical', verdict: 'accept', level: 'polish' }), { ...o, candidate: 'C-0001' });
79
+ (0, candidate_1.updateCandidate)('C-0001', { ...o, state: 'approved', why: 'card was below the fold' });
80
+ // Ordinary work, no candidate: still reaches the board, as a card named for the piece of work — with a picture if one was attached.
81
+ (0, record_1.record)(JSON.stringify({ change: 'Filters apply as you pick them', decision: 'Report filters apply immediately', rationale: 'r', trigger: 'Reports filters', scope: 'pattern:filters', dimension: 'interaction', class: 'judgment', verdict: 'accept', level: 'pattern' }), o);
82
+ strict_1.default.equal((0, snapshot_1.snapshotWork)('reports filters', { cwd, file: 'shot.png' }).exitCode, 0, 'name matching is forgiving');
83
+ const svc = await fakeService();
84
+ try {
85
+ const { manifest, skipped } = (0, hosted_1.buildManifest)((0, store_1.resolvePaths)(cwd));
86
+ const cands = manifest.candidates;
87
+ strict_1.default.equal(cands[0].decisions.length, 1, 'polish left out');
88
+ const work = cands.find((c) => c.id === 'W-reports-filters');
89
+ strict_1.default.ok(work, 'screenless decision rides as a work card');
90
+ strict_1.default.ok(work.snapshot, 'its picture rides too');
91
+ strict_1.default.equal(work.name, 'Reports filters');
92
+ strict_1.default.equal(work.state, 'recorded');
93
+ strict_1.default.equal(work.work, true);
94
+ strict_1.default.equal(work.decisions.length, 1);
95
+ strict_1.default.ok(cands[0].snapshot, 'png included');
96
+ strict_1.default.equal(cands[1].snapshot, null, 'svg not uploaded');
97
+ strict_1.default.equal(skipped.length, 1);
98
+ const r1 = await (0, publish_1.publish)({ cwd, to: svc.url });
99
+ strict_1.default.ok(r1.ok, JSON.stringify(r1.steps));
100
+ strict_1.default.equal(r1.url, 'http://x/p/abc123');
101
+ strict_1.default.ok(r1.steps.some((s) => s.step === 'project' && s.outcome === 'done'));
102
+ const link = (0, hosted_1.readLink)((0, store_1.resolvePaths)(cwd));
103
+ strict_1.default.equal(link.token, undefined, 'no secret in the shareable file');
104
+ strict_1.default.equal((0, hosted_1.readToken)((0, store_1.resolvePaths)(cwd)), 'tok-secret');
105
+ const gi = node_fs_1.default.readFileSync(node_path_1.default.join(cwd, '.arbiter', '.gitignore'), 'utf8');
106
+ strict_1.default.ok(gi.includes('hosted.token') && !gi.includes('hosted.json'), 'token file ignored, link file shareable');
107
+ const r2 = await (0, publish_1.publish)({ cwd, to: svc.url });
108
+ strict_1.default.ok(!r2.steps.some((s) => s.step === 'project'), 'second publish reuses the project');
109
+ const board = svc.state.boards.p1;
110
+ strict_1.default.equal(board.candidates[0].state, 'approved');
111
+ strict_1.default.equal(board.candidates[0].snapshot, 'http://x/snap/C-0001.png', 'manifest carries the uploaded URL, not bytes');
112
+ strict_1.default.equal(board.candidates[1].snapshot, null);
113
+ strict_1.default.equal(board.candidates.find((c) => c.id === 'W-reports-filters').snapshot, 'http://x/snap/W-reports-filters.png');
114
+ // A PM says something.
115
+ svc.state.comments.push({ id: 'c1', candidate_id: 'C-0001', decision_id: null, kind: 'approve', author_name: 'Sam', author_email: 's@x', body: '', created_at: '2026-09-16T10:00:00.000Z' });
116
+ svc.state.comments.push({ id: 'c2', candidate_id: 'C-0001', decision_id: null, kind: 'comment', author_name: 'Sam', author_email: 's@x', body: 'Why not a sheet?', created_at: '2026-09-16T10:01:00.000Z' });
117
+ const out = await (0, pull_1.pull)({ cwd });
118
+ strict_1.default.ok(out.includes('✓ Sam — looks good'));
119
+ strict_1.default.ok(out.includes('Sam: Why not a sheet?'));
120
+ strict_1.default.equal((0, hosted_1.readComments)((0, store_1.resolvePaths)(cwd)).length, 2);
121
+ const again = await (0, pull_1.pull)({ cwd });
122
+ strict_1.default.ok(again.startsWith('Nothing new'));
123
+ strict_1.default.equal((0, hosted_1.readComments)((0, store_1.resolvePaths)(cwd)).length, 2, 'no duplicates');
124
+ }
125
+ finally {
126
+ svc.close();
127
+ }
128
+ });
129
+ (0, node_test_1.test)('publish --to fails cleanly when the service is down', async () => {
130
+ const cwd = tmp();
131
+ const r = await (0, publish_1.publish)({ cwd, to: 'http://127.0.0.1:1' });
132
+ strict_1.default.equal(r.ok, false);
133
+ strict_1.default.equal(r.steps[0].outcome, 'failed');
134
+ });
135
+ (0, node_test_1.test)('a teammate with hosted.json and ARBITER_PUBLISH_TOKEN updates the same project; without the token gets told what to do', async () => {
136
+ const cwd = tmp();
137
+ const o = { cwd, author: 'test' };
138
+ (0, candidate_1.addCandidate)('X', { ...o, feature: 'f' });
139
+ const svc = await fakeService();
140
+ try {
141
+ await (0, publish_1.publish)({ cwd, to: svc.url });
142
+ // Simulate a clone: link file present, token file absent.
143
+ node_fs_1.default.rmSync(node_path_1.default.join(cwd, '.arbiter', 'hosted.token'));
144
+ const r = await (0, publish_1.publish)({ cwd, to: svc.url });
145
+ strict_1.default.equal(r.ok, false);
146
+ strict_1.default.ok(r.steps[0].note.includes('ARBITER_PUBLISH_TOKEN'));
147
+ process.env.ARBITER_PUBLISH_TOKEN = 'tok-secret';
148
+ try {
149
+ const r2 = await (0, publish_1.publish)({ cwd, to: svc.url });
150
+ strict_1.default.ok(r2.ok, JSON.stringify(r2.steps));
151
+ strict_1.default.ok(!r2.steps.some((s) => s.step === 'project'), 'same project, not a second one');
152
+ }
153
+ finally {
154
+ delete process.env.ARBITER_PUBLISH_TOKEN;
155
+ }
156
+ }
157
+ finally {
158
+ svc.close();
159
+ }
160
+ });
161
+ (0, node_test_1.test)('a site with an admin token refuses project creation without it, with a clear message', async () => {
162
+ const cwd = tmp();
163
+ (0, candidate_1.addCandidate)('X', { cwd, author: 'test', feature: 'f' });
164
+ const server = node_http_1.default.createServer((req, res) => {
165
+ req.resume();
166
+ if (req.method === 'PUT') {
167
+ res.writeHead(200, { 'content-type': 'application/json' });
168
+ return res.end('{"ok":true,"candidates":1,"url":"http://x/p/s"}');
169
+ }
170
+ if (req.headers['x-admin-token'] !== 'admin-1') {
171
+ res.writeHead(401, { 'content-type': 'application/json' });
172
+ return res.end('{"error":"admin token required"}');
173
+ }
174
+ res.writeHead(201, { 'content-type': 'application/json' });
175
+ res.end(JSON.stringify({ id: 'p', slug: 's', token: 't', url: 'http://x/p/s' }));
176
+ });
177
+ await new Promise((r) => server.listen(0, '127.0.0.1', () => r()));
178
+ const url = `http://127.0.0.1:${server.address().port}`;
179
+ try {
180
+ const r = await (0, publish_1.publish)({ cwd, to: url });
181
+ strict_1.default.equal(r.ok, false);
182
+ strict_1.default.ok(r.steps[0].note.includes('ARBITER_ADMIN_TOKEN'));
183
+ const r2 = await (0, publish_1.publish)({ cwd, to: url, admin: 'admin-1' });
184
+ strict_1.default.ok(r2.steps.some((s) => s.step === 'project' && s.outcome === 'done'));
185
+ }
186
+ finally {
187
+ server.close();
188
+ }
189
+ });
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_test_1 = require("node:test");
7
+ const strict_1 = __importDefault(require("node:assert/strict"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const init_1 = require("../commands/init");
12
+ const record_1 = require("../commands/record");
13
+ const store_1 = require("../store");
14
+ const tmp = () => node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'arbiter-init-'));
15
+ (0, node_test_1.test)('init is idempotent and merges AGENTS.md', async () => {
16
+ const cwd = tmp();
17
+ node_fs_1.default.mkdirSync(node_path_1.default.join(cwd, '.claude'));
18
+ node_fs_1.default.writeFileSync(node_path_1.default.join(cwd, 'AGENTS.md'), '# Rules\n\nUse pnpm.\n');
19
+ const first = await (0, init_1.init)({ cwd, yes: true, skipInstall: true, author: 'test' });
20
+ strict_1.default.deepEqual(first.map((s) => [s.file, s.outcome]), [
21
+ ['arbiter.json', 'created'],
22
+ ['DECISIONS.md', 'created'],
23
+ ['.arbiter/.gitignore', 'created'],
24
+ ['.arbiter/archive.md', 'created'],
25
+ ['.claude/skills/arbiter/SKILL.md', 'created'],
26
+ ['AGENTS.md', 'updated'],
27
+ ['CLAUDE.md', 'created'],
28
+ ['package.json', 'skipped'],
29
+ ]);
30
+ strict_1.default.equal((node_fs_1.default.readFileSync(node_path_1.default.join(cwd, 'CLAUDE.md'), 'utf8').match(/<!-- arbiter -->/g) ?? []).length, 1);
31
+ const agents = node_fs_1.default.readFileSync(node_path_1.default.join(cwd, 'AGENTS.md'), 'utf8');
32
+ strict_1.default.ok(agents.startsWith('# Rules\n\nUse pnpm.\n'), 'existing content kept');
33
+ strict_1.default.equal((agents.match(/<!-- arbiter -->/g) ?? []).length, 1);
34
+ // Record a rule between runs — a second init must not clobber it.
35
+ (0, record_1.record)(JSON.stringify({ decision: 'Keep me', rationale: 'r', trigger: 't', scope: 'global', dimension: 'content', class: 'judgment', verdict: 'rule' }), { cwd, author: 'test' });
36
+ const second = await (0, init_1.init)({ cwd, yes: true, skipInstall: true });
37
+ strict_1.default.ok(second.every((s) => s.outcome === 'unchanged' || s.outcome === 'skipped'), JSON.stringify(second));
38
+ strict_1.default.equal((node_fs_1.default.readFileSync(node_path_1.default.join(cwd, 'AGENTS.md'), 'utf8').match(/<!-- arbiter -->/g) ?? []).length, 1);
39
+ strict_1.default.equal((0, store_1.readActive)((0, store_1.resolvePaths)(cwd)).length, 1, 'DECISIONS.md not overwritten');
40
+ const config = JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(cwd, 'arbiter.json'), 'utf8'));
41
+ strict_1.default.equal(config.destination, 'local');
42
+ strict_1.default.equal(config.author, 'test');
43
+ strict_1.default.equal(config.client, 'claude-code');
44
+ });
45
+ (0, node_test_1.test)('init writes a Cursor rule when told to', async () => {
46
+ const cwd = tmp();
47
+ await (0, init_1.init)({ cwd, yes: true, skipInstall: true, client: 'cursor', author: 'test' });
48
+ const mdc = node_fs_1.default.readFileSync(node_path_1.default.join(cwd, '.cursor', 'rules', 'arbiter.mdc'), 'utf8');
49
+ strict_1.default.ok(mdc.startsWith('---\ndescription: '));
50
+ strict_1.default.ok(mdc.includes('alwaysApply: false'));
51
+ strict_1.default.ok(mdc.includes('# Arbiter'));
52
+ strict_1.default.ok(node_fs_1.default.existsSync(node_path_1.default.join(cwd, '.cursor', 'commands', 'arbiter.md')));
53
+ strict_1.default.ok(!node_fs_1.default.existsSync(node_path_1.default.join(cwd, 'CLAUDE.md')), 'no CLAUDE.md for a Cursor project');
54
+ });
@@ -0,0 +1,198 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ const node_test_1 = require("node:test");
7
+ const strict_1 = __importDefault(require("node:assert/strict"));
8
+ const node_fs_1 = __importDefault(require("node:fs"));
9
+ const node_os_1 = __importDefault(require("node:os"));
10
+ const node_path_1 = __importDefault(require("node:path"));
11
+ const node_http_1 = __importDefault(require("node:http"));
12
+ const record_1 = require("../commands/record");
13
+ const rules_1 = require("../commands/rules");
14
+ const review_1 = require("../commands/review");
15
+ const store_1 = require("../store");
16
+ const tmp = () => node_fs_1.default.mkdtempSync(node_path_1.default.join(node_os_1.default.tmpdir(), 'arbiter-pending-'));
17
+ const input = (over = {}) => JSON.stringify({
18
+ decision: 'Sheets put the primary action bottom-right',
19
+ rationale: 'Header actions collide with close on mobile.',
20
+ trigger: 'Settings build',
21
+ scope: 'pattern:sheet-actions',
22
+ dimension: 'interaction',
23
+ class: 'judgment',
24
+ verdict: 'rule',
25
+ ...over,
26
+ });
27
+ (0, node_test_1.test)('queue writes to pending only; ids are P-', () => {
28
+ const cwd = tmp();
29
+ // The agent queues before anyone has judged — no verdict in the payload.
30
+ const r1 = (0, record_1.queue)(input({ verdict: undefined }), { cwd, author: 'test' });
31
+ const r2 = (0, record_1.queue)(input({ decision: 'Empty states are one line', scope: 'pattern:empty-state', dimension: 'states' }), { cwd, author: 'test' });
32
+ strict_1.default.equal(r1.output.id, 'P-0001');
33
+ strict_1.default.equal(r2.output.id, 'P-0002');
34
+ const p = (0, store_1.resolvePaths)(cwd);
35
+ strict_1.default.equal((0, store_1.readPending)(p).length, 2);
36
+ strict_1.default.equal((0, store_1.readArchive)(p).length, 0);
37
+ strict_1.default.equal((0, store_1.readActive)(p).length, 0);
38
+ strict_1.default.equal((0, store_1.readPending)(p)[0].verdict, 'pending');
39
+ });
40
+ (0, node_test_1.test)('judge: rule, accept, skip, fix', () => {
41
+ const cwd = tmp();
42
+ const o = { cwd, author: 'test' };
43
+ (0, record_1.queue)(input(), o);
44
+ (0, record_1.queue)(input({ decision: 'Two', scope: 'pattern:two' }), o);
45
+ (0, record_1.queue)(input({ decision: 'Three', scope: 'pattern:three' }), o);
46
+ (0, record_1.queue)(input({ decision: 'Four', scope: 'pattern:four' }), o);
47
+ const p = (0, store_1.resolvePaths)(cwd);
48
+ const r = (0, record_1.judge)('P-0001', { ...o, as: 'rule' });
49
+ strict_1.default.equal(r.exitCode, 0);
50
+ strict_1.default.equal(r.output.id, 'D-0001');
51
+ strict_1.default.equal(r.output.judged, 'P-0001');
52
+ strict_1.default.equal((0, store_1.readActive)(p).length, 1);
53
+ const a = (0, record_1.judge)('P-0002', { ...o, as: 'accept' });
54
+ strict_1.default.equal(a.output.verdict, 'accept');
55
+ strict_1.default.equal((0, store_1.readActive)(p).length, 1);
56
+ const s = (0, record_1.judge)('P-0003', { ...o, as: 'skip' });
57
+ strict_1.default.equal(s.output.status, 'skipped');
58
+ const f = (0, record_1.judge)('P-0004', { ...o, as: 'fix', to: 'Four, corrected' });
59
+ strict_1.default.equal(f.output.verdict, 'fix');
60
+ const fixed = (0, store_1.readArchive)(p).find((d) => d.id === f.output.id);
61
+ strict_1.default.equal(fixed.decision, 'Four, corrected');
62
+ strict_1.default.ok(fixed.rejected[0].startsWith('Four — corrected by test'));
63
+ strict_1.default.equal((0, store_1.readPending)(p).length, 0);
64
+ strict_1.default.equal((0, store_1.readArchive)(p).length, 3, 'skip is recorded nowhere');
65
+ });
66
+ (0, node_test_1.test)('judge as rule with overlap leaves it pending until answered', () => {
67
+ const cwd = tmp();
68
+ const o = { cwd, author: 'test' };
69
+ (0, record_1.record)(input(), o);
70
+ (0, record_1.queue)(input({ decision: 'Sheets put the primary action bottom-right and sticky' }), o);
71
+ const p = (0, store_1.resolvePaths)(cwd);
72
+ const r = (0, record_1.judge)('P-0001', { ...o, as: 'rule' });
73
+ strict_1.default.equal(r.exitCode, 2);
74
+ strict_1.default.equal((0, store_1.readPending)(p).length, 1, 'still pending');
75
+ const r2 = (0, record_1.judge)('P-0001', { ...o, as: 'rule', supersedes: 'D-0001' });
76
+ strict_1.default.equal(r2.exitCode, 0);
77
+ strict_1.default.equal((0, store_1.readPending)(p).length, 0);
78
+ strict_1.default.deepEqual((0, store_1.readActive)(p).map((d) => d.id), ['D-0002']);
79
+ });
80
+ (0, node_test_1.test)('judge rejects unknown or malformed ids and fix without --to', () => {
81
+ const cwd = tmp();
82
+ const o = { cwd, author: 'test' };
83
+ (0, record_1.queue)(input(), o);
84
+ strict_1.default.equal((0, record_1.judge)('P-0009', { ...o, as: 'rule' }).exitCode, 1);
85
+ strict_1.default.equal((0, record_1.judge)('D-0001', { ...o, as: 'rule' }).exitCode, 1);
86
+ strict_1.default.equal((0, record_1.judge)('P-0001', { ...o, as: 'fix' }).exitCode, 1);
87
+ strict_1.default.equal((0, store_1.readPending)((0, store_1.resolvePaths)(cwd)).length, 1);
88
+ });
89
+ (0, node_test_1.test)('review server: state, judge, done', async () => {
90
+ const cwd = tmp();
91
+ (0, record_1.queue)(input(), { cwd, author: 'test' });
92
+ const port = 47000 + Math.floor(Math.random() * 1000);
93
+ const done = (0, review_1.review)({ cwd, port, open: false });
94
+ await new Promise((r) => setTimeout(r, 200));
95
+ const state = await get(port, '/api/state');
96
+ strict_1.default.equal(state.pending.length, 1);
97
+ strict_1.default.equal(state.pending[0].id, 'P-0001');
98
+ const judged = await post(port, '/api/judge', { id: 'P-0001', as: 'rule' });
99
+ strict_1.default.equal(judged.exitCode, 0);
100
+ strict_1.default.equal(judged.id, 'D-0001');
101
+ strict_1.default.equal((await get(port, '/api/state')).pending.length, 0);
102
+ await post(port, '/api/done', {});
103
+ await done;
104
+ });
105
+ function get(port, p) {
106
+ return new Promise((resolve, reject) => {
107
+ node_http_1.default.get({ host: '127.0.0.1', port, path: p }, (res) => {
108
+ let d = '';
109
+ res.on('data', (c) => (d += c));
110
+ res.on('end', () => resolve(JSON.parse(d)));
111
+ }).on('error', reject);
112
+ });
113
+ }
114
+ function post(port, p, body) {
115
+ return new Promise((resolve, reject) => {
116
+ const req = node_http_1.default.request({ host: '127.0.0.1', port, path: p, method: 'POST', headers: { 'content-type': 'application/json' } }, (res) => {
117
+ let d = '';
118
+ res.on('data', (c) => (d += c));
119
+ res.on('end', () => resolve(JSON.parse(d)));
120
+ });
121
+ req.on('error', reject);
122
+ req.end(JSON.stringify(body));
123
+ });
124
+ }
125
+ (0, node_test_1.test)('judgeAll: --level polish confirms only polish; --trigger scopes to one piece of work', () => {
126
+ const cwd = tmp();
127
+ const o = { cwd, author: 'test' };
128
+ const q = (over) => (0, record_1.queue)(input({ verdict: undefined, ...over }), o);
129
+ q({ decision: 'Shell', level: 'feature', trigger: 'Settings build', scope: 'file:a.tsx' });
130
+ q({ decision: 'h-9', level: 'polish', trigger: 'Settings build', scope: 'file:a.tsx', change: 'Buttons match at h-9' });
131
+ q({ decision: 'chevron', level: 'polish', trigger: 'Audit page', scope: 'file:b.tsx', change: 'Dropped the chevron' });
132
+ q({ decision: 'Cards', level: 'pattern', trigger: 'Audit page', scope: 'pattern:cards' });
133
+ const p = (0, store_1.resolvePaths)(cwd);
134
+ const r = (0, record_1.judgeAll)({ ...o, as: 'accept', level: 'polish', trigger: 'Settings build' });
135
+ strict_1.default.equal(r.exitCode, 0);
136
+ strict_1.default.equal(r.output.judged.length, 1);
137
+ strict_1.default.deepEqual((0, store_1.readPending)(p).map((d) => d.decision), ['Shell', 'chevron', 'Cards']);
138
+ const r2 = (0, record_1.judgeAll)({ ...o, as: 'accept', level: 'polish' });
139
+ strict_1.default.deepEqual((0, store_1.readPending)(p).map((d) => d.decision), ['Shell', 'Cards']);
140
+ strict_1.default.equal(r2.output.pending, 2);
141
+ strict_1.default.equal((0, record_1.judgeAll)({ ...o, as: 'fix' }).exitCode, 1, 'fix is never bulk');
142
+ strict_1.default.equal((0, record_1.judgeAll)({ ...o, as: 'accept', level: 'polish' }).output.status, 'nothing-to-judge');
143
+ const r3 = (0, record_1.judgeAll)({ ...o, as: 'rule', level: 'pattern' });
144
+ strict_1.default.deepEqual(r3.output.judged, ['D-0003']);
145
+ strict_1.default.equal((0, store_1.readActive)(p).length, 1);
146
+ strict_1.default.deepEqual((0, store_1.readPending)(p).map((d) => d.decision), ['Shell']);
147
+ });
148
+ (0, node_test_1.test)('groupByTrigger keeps first-appearance order and splits polish', () => {
149
+ const cwd = tmp();
150
+ const o = { cwd, author: 'test' };
151
+ const q = (over) => (0, record_1.queue)(input({ verdict: undefined, ...over }), o);
152
+ q({ decision: 'b1', trigger: 'B', scope: 'pattern:b1' });
153
+ q({ decision: 'a1', trigger: 'A', scope: 'pattern:a1', level: 'polish' });
154
+ q({ decision: 'b2', trigger: 'B', scope: 'pattern:b2', level: 'polish' });
155
+ q({ decision: 'a2', trigger: 'A', scope: 'pattern:a2', level: 'feature' });
156
+ const groups = (0, rules_1.groupByTrigger)((0, store_1.readPending)((0, store_1.resolvePaths)(cwd)));
157
+ strict_1.default.deepEqual(groups.map((g) => g.trigger), ['B', 'A']);
158
+ strict_1.default.deepEqual(groups[0].items.map((d) => d.decision), ['b1']);
159
+ strict_1.default.deepEqual(groups[0].polish.map((d) => d.decision), ['b2']);
160
+ strict_1.default.deepEqual(groups[1].items.map((d) => d.decision), ['a2']);
161
+ strict_1.default.deepEqual(groups[1].polish.map((d) => d.decision), ['a1']);
162
+ strict_1.default.ok((0, rules_1.rules)(undefined, { cwd, pending: true }).includes('confirm all with'));
163
+ });
164
+ (0, node_test_1.test)('archive entries written before level/change existed still parse', () => {
165
+ const cwd = tmp();
166
+ const p = (0, store_1.resolvePaths)(cwd);
167
+ node_fs_1.default.mkdirSync(p.archiveDir, { recursive: true });
168
+ node_fs_1.default.writeFileSync(p.archive, `# Decision archive
169
+
170
+ ### D-0001 · Old rule
171
+
172
+ - **Rationale:** because
173
+ - **Trigger:** old build
174
+ - **Scope:** global · **Dimension:** visual · **Class:** mechanical · **Verdict:** rule
175
+ - **Author:** t · **Date:** 2026-09-01T00:00:00Z · **Commit:** — · **Supersedes:** —
176
+ `);
177
+ const [d] = (0, store_1.readArchive)(p);
178
+ strict_1.default.equal(d.level, 'pattern');
179
+ strict_1.default.equal(d.change, null);
180
+ strict_1.default.equal(d.decision, 'Old rule');
181
+ });
182
+ (0, node_test_1.test)('a ticket ref rides from the flag or the payload through queue and judge', () => {
183
+ const cwd = tmp();
184
+ const p = (0, store_1.resolvePaths)(cwd);
185
+ // --ref on the command wins over the payload; a bare key is fine.
186
+ (0, record_1.queue)(input({ verdict: undefined, ref: 'https://linear.app/acme/issue/ENG-1' }), { cwd, author: 'test', ref: 'ENG-2' });
187
+ // Payload only.
188
+ (0, record_1.queue)(input({ verdict: undefined, decision: 'Empty states are one line', scope: 'pattern:empty-state', dimension: 'states', ref: 'https://github.com/acme/app/issues/42' }), { cwd, author: 'test' });
189
+ // None mentioned.
190
+ (0, record_1.queue)(input({ verdict: undefined, decision: 'Toasts sit bottom-left', scope: 'pattern:toast', dimension: 'states' }), { cwd, author: 'test' });
191
+ strict_1.default.deepEqual((0, store_1.readPending)(p).map((d) => d.ref), ['ENG-2', 'https://github.com/acme/app/issues/42', null]);
192
+ // Judging keeps it; a bulk judge can stamp one on everything left.
193
+ strict_1.default.equal((0, record_1.judge)('P-0001', { cwd, author: 'test', as: 'rule' }).exitCode, 0);
194
+ strict_1.default.equal((0, record_1.judgeAll)({ cwd, author: 'test', as: 'accept', ref: 'ENG-9' }).exitCode, 0);
195
+ strict_1.default.deepEqual((0, store_1.readArchive)(p).map((d) => [d.id, d.ref]), [['D-0001', 'ENG-2'], ['D-0002', 'ENG-9'], ['D-0003', 'ENG-9']]);
196
+ // And it's in the file as its own line, so a URL never collides with the separator.
197
+ strict_1.default.match(node_fs_1.default.readFileSync(p.archive, 'utf8'), /^- \*\*Ref:\*\* ENG-2$/m);
198
+ });