@jjanczur/tyran 0.1.13 → 0.1.15

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.
@@ -0,0 +1,1005 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * mistakes — the repository's incident ledger, and the ONLY writer of the
4
+ * `tyran:rules` fence in the host `CLAUDE.md`.
5
+ *
6
+ * `MISTAKES.md` answers one question no other Tyran store answers:
7
+ * **recurrence**. A journal `finding` dies with its initiative; a knowledge
8
+ * entry says what an agent should know before touching a path; this file says
9
+ * what has gone WRONG here and how often. The count is the whole contribution,
10
+ * which is why promotion never deletes an entry — deleting it would destroy
11
+ * the evidence that earned the rule.
12
+ *
13
+ * It is an AUTHORED file, not a projection. `project.mjs --check` would report
14
+ * a hand edit as drift and the next render would destroy it, and a human
15
+ * correcting a wrong root cause is the single most valuable edit this file
16
+ * will ever receive. The cost is stated rather than discovered: nothing checks
17
+ * these entries against the journal byte for byte, so drift is auditable by a
18
+ * human (every entry cites its initiative and its proof) but not enforced by a
19
+ * gate. `docs/self-improvement.md` says so in those words.
20
+ *
21
+ * THE CLOCK. This is the one writer in the core that reads the wall clock: a
22
+ * dated ledger of incidents is the artefact, and a date invented by a caller
23
+ * is a date nobody can check. `--date` exists so tests are deterministic —
24
+ * it is not an invitation to make the default deterministic later.
25
+ *
26
+ * THE FENCE. `promote --law` edits the operator's `CLAUDE.md` between
27
+ * `<!-- tyran:rules start -->` and `<!-- tyran:rules end -->` and nowhere
28
+ * else. That write is autonomous on purpose: a rule that has been paid for
29
+ * five times, with an entry per occurrence, is evidence rather than opinion,
30
+ * and the operator learns about it from the journal and the diff the same way
31
+ * they learn about every other autonomous act. The boundary is not "agents may
32
+ * not change the law" — it is "the law changes only through the mechanism that
33
+ * requires evidence", which is why the shipped policy classes `CLAUDE.md`
34
+ * GATED (a free-hand `Write` from a subagent is denied) while a `Bash` command
35
+ * running THIS script passes.
36
+ *
37
+ * CLI:
38
+ * node mistakes.mjs add --signature S --what W --cause C
39
+ * --consequence Q --prevention P
40
+ * [--file F] [--title T] [--initiative SLUG]
41
+ * [--actor A] [--proof F-12] [--date YYYY-MM-DD]
42
+ * node mistakes.mjs repeats [--file F] [--threshold 3] [--json]
43
+ * node mistakes.mjs promote --signature S --status knowledge:<id>|wontfix [--file F]
44
+ * node mistakes.mjs promote --signature S --law --rule TEXT [--file F]
45
+ * [--claude-md PATH] [--dry-run]
46
+ * [--journal PATH] [--init SLUG] [--actor A]
47
+ * Exit: 0 ok · 1 nothing matched (no signature at the threshold; no entry
48
+ * changed; the signature has not earned law; the rule could not be put
49
+ * in force, so no status moved) · 2 usage / IO / a field that violates
50
+ * a cap
51
+ */
52
+ import { existsSync, lstatSync, readFileSync, realpathSync } from 'node:fs';
53
+ import { join, resolve, dirname } from 'node:path';
54
+ import { fileURLToPath } from 'node:url';
55
+ import { escapeInvisible } from './invisible.mjs';
56
+ import { writeAtomic } from './project.mjs';
57
+ import { append as appendEvent, nextId } from './journal.mjs';
58
+
59
+ /** The ledger's home. Repo ROOT, not `.tyran/`: a human, a reviewer on
60
+ * GitHub and a session that has never heard of Tyran all have to find it. */
61
+ export const MISTAKES_FILE = 'MISTAKES.md';
62
+
63
+ /** The operator's prose, loaded into every session in the repository. */
64
+ export const CLAUDE_MD_FILE = 'CLAUDE.md';
65
+
66
+ /**
67
+ * Per-field ceiling in codepoints, REJECTED and never truncated — the same
68
+ * doctrine as the journal's `CAPPED_DATA_KEYS`. A silently shortened root
69
+ * cause loses exactly the half that mattered. Long material belongs in
70
+ * NOTES.md or a doc, with a pointer here.
71
+ *
72
+ * Measured against the INPUT, not the escaped output: `escapeInvisible` turns
73
+ * one hostile codepoint into eight visible ones, and a cap counted after
74
+ * escaping would reject a legal field for containing a character the author
75
+ * cannot see.
76
+ */
77
+ export const MISTAKE_FIELD_MAX = 1000;
78
+
79
+ /** Signatures are matched as literals, so the grammar has to be tight. */
80
+ export const SIGNATURE_RE = /^[a-z0-9]+(-[a-z0-9]+)*$/;
81
+ export const SIGNATURE_MAX = 60;
82
+
83
+ /**
84
+ * Titles are one line of a heading; longer than this and a reader skims past.
85
+ *
86
+ * The two paths differ on purpose and the difference is not a loophole: a
87
+ * DERIVED title is cut with an ellipsis because nobody chose its length, while
88
+ * an explicit `--title` is REJECTED over the cap — the same reject-never-
89
+ * truncate doctrine as `MISTAKE_FIELD_MAX`, applied where an author is the one
90
+ * who decided.
91
+ */
92
+ export const TITLE_MAX = 100;
93
+
94
+ /**
95
+ * Three open entries under one signature graduate the lesson into
96
+ * `.tyran/knowledge/`; five open-or-promoted earn a line in `CLAUDE.md`.
97
+ *
98
+ * The GAP is the diagnostic, not an accident of taste: a signature that
99
+ * reaches five has already been delivered in every handoff touching those
100
+ * paths and broke anyway, which is the strongest argument for law there is.
101
+ */
102
+ export const KNOWLEDGE_THRESHOLD = 3;
103
+ export const LAW_THRESHOLD = 5;
104
+
105
+ export const FENCE_START = '<!-- tyran:rules start -->';
106
+ export const FENCE_END = '<!-- tyran:rules end -->';
107
+
108
+ /**
109
+ * Markers are matched as WHOLE LINES. An `includes` test would let a rule
110
+ * whose text quotes the end marker truncate the fence, and the next promotion
111
+ * would then write outside it — into the operator's own prose.
112
+ */
113
+ const FENCE_START_RE = /^[ \t]*<!--[ \t]*tyran:rules[ \t]+start[ \t]*-->[ \t]*$/;
114
+ const FENCE_END_RE = /^[ \t]*<!--[ \t]*tyran:rules[ \t]+end[ \t]*-->[ \t]*$/;
115
+
116
+ /** The heading the fence is introduced by, wherever the fence is created. */
117
+ export const FENCE_HEADING = '## Rules earned by repeated failures';
118
+
119
+ /** Field label -> key, in the order an entry states them. */
120
+ const FIELDS = Object.freeze([
121
+ ['what', 'What happened'],
122
+ ['cause', 'Root cause'],
123
+ ['consequence', 'Consequence'],
124
+ ['prevention', 'Prevention'],
125
+ ]);
126
+
127
+ const FIELD_LINE_RE = /^-\s+\*\*(What happened|Root cause|Consequence|Prevention):\*\*\s*(.*)$/;
128
+ const TRAILER_RE = /^-\s+\*\*Signature:\*\*\s*(.*)$/;
129
+ const HEADING_RE = /^## (.*)$/;
130
+ const CODE_FENCE_RE = /^[ \t]{0,3}(`{3,}|~{3,})/;
131
+
132
+ class UsageError extends Error {}
133
+ class IOError extends Error {}
134
+
135
+ // ------------------------------------------------------------------ text
136
+
137
+ /**
138
+ * One untrusted value on its way into a file agents read.
139
+ *
140
+ * Escaped rather than stripped (ADR-19): a value made entirely of TAG
141
+ * characters must not render identically to an empty one. Whitespace is a
142
+ * separate normalization — a newline is perfectly visible and is folded, not
143
+ * banned — and folding it is what makes a forged `## ` heading impossible:
144
+ * every field is written as exactly one line.
145
+ */
146
+ export function clean(value) {
147
+ return escapeInvisible(String(value)).replace(/\s+/g, ' ').trim();
148
+ }
149
+
150
+ const cpLength = (s) => Array.from(String(s)).length;
151
+
152
+ function eolOf(text) {
153
+ const crlf = (text.match(/\r\n/g) ?? []).length;
154
+ const total = (text.match(/\n/g) ?? []).length;
155
+ return crlf * 2 > total ? '\r\n' : '\n';
156
+ }
157
+
158
+ /**
159
+ * Split a document into lines while remembering how to put it back byte for
160
+ * byte. Both facts are load-bearing when the file belongs to the operator: a
161
+ * writer that normalizes CRLF to LF, or adds a final newline that was not
162
+ * there, rewrites every line of a file it was asked to append one line to.
163
+ */
164
+ function splitDoc(text) {
165
+ const eol = eolOf(text);
166
+ const finalNewline = text.endsWith('\n');
167
+ const body = finalNewline ? text.slice(0, -1).replace(/\r$/, '') : text;
168
+ const lines = body === '' && finalNewline === false ? [] : body.split(/\r?\n/);
169
+ return { lines, eol, finalNewline };
170
+ }
171
+
172
+ function joinDoc({ lines, eol, finalNewline }) {
173
+ return lines.join(eol) + (finalNewline ? eol : '');
174
+ }
175
+
176
+ // ---------------------------------------------------------------- parsing
177
+
178
+ /**
179
+ * The lines of a document that are TEXT rather than a fenced code sample, and
180
+ * the fence that was never closed.
181
+ *
182
+ * One answer, one place: `parseMistakes` must not count an example entry
183
+ * pasted into a fenced block, and `fenceState` must not mistake a
184
+ * `tyran:rules` marker inside an operator's ```markdown block — the shipped
185
+ * documentation contains exactly that snippet — for the real fence. Same
186
+ * blindness, so the same tracking.
187
+ *
188
+ * `danglingFence` is the line index of a fence nothing closed, or `null`.
189
+ * Everything below such a line is invisible to both readers, and a ledger that
190
+ * silently reads as smaller than it is undercounts the recurrence this file
191
+ * exists to count — so the state is returned rather than absorbed.
192
+ */
193
+ function scanOutsideCodeFences(lines) {
194
+ const outside = [];
195
+ let openedAt = null;
196
+ let marker = null;
197
+ for (const [index, line] of lines.entries()) {
198
+ const fence = CODE_FENCE_RE.exec(line);
199
+ if (fence) {
200
+ if (openedAt === null) {
201
+ openedAt = index;
202
+ marker = fence[1][0];
203
+ } else if (fence[1][0] === marker) {
204
+ openedAt = null;
205
+ marker = null;
206
+ }
207
+ continue;
208
+ }
209
+ if (openedAt !== null) continue;
210
+ outside.push([index, line]);
211
+ }
212
+ return { outside, danglingFence: openedAt };
213
+ }
214
+
215
+ /**
216
+ * Every entry of a `MISTAKES.md`, newest first, plus the counts of what could
217
+ * not be classified.
218
+ *
219
+ * FENCE-AWARE, and that is not fussiness. The shipped header shows the entry
220
+ * shape as an example; a parser blind to code fences would count a pasted
221
+ * example as entry number one and the recurrence count would be wrong from
222
+ * birth. Headings are also anchored at column 0 for the same reason — the
223
+ * shipped template indents its example four spaces.
224
+ *
225
+ * Nothing is dropped silently. An entry with no signature, an entry whose
226
+ * status is not in the grammar, and a code fence nobody closed — which hides
227
+ * every entry below it — are all COUNTED and reported: a typo that removed an
228
+ * entry from the count with no trace is the failure this file's whole value
229
+ * rests on not having.
230
+ */
231
+ export function parseMistakes(text) {
232
+ const { lines } = splitDoc(String(text));
233
+ const { outside, danglingFence } = scanOutsideCodeFences(lines);
234
+ const headings = outside.filter(([, line]) => HEADING_RE.test(line)).map(([index]) => index);
235
+
236
+ const entries = [];
237
+ for (const [n, start] of headings.entries()) {
238
+ const end = n + 1 < headings.length ? headings[n + 1] : lines.length;
239
+ entries.push(parseEntry(lines, start, end));
240
+ }
241
+ return {
242
+ entries,
243
+ firstEntryLine: headings.length > 0 ? headings[0] : null,
244
+ withoutSignature: entries.filter((e) => e.signature === null).length,
245
+ unknownStatus: entries.filter((e) => e.statusKind === 'unknown').length,
246
+ danglingFence,
247
+ };
248
+ }
249
+
250
+ function parseEntry(lines, start, end) {
251
+ const heading = HEADING_RE.exec(lines[start])[1].trim();
252
+ const date = /^(\d{4}-\d{2}-\d{2})/.exec(heading)?.[1] ?? null;
253
+ const fields = Object.create(null);
254
+ let signature = null;
255
+ let initiative = null;
256
+ let actor = null;
257
+ let proof = null;
258
+ let status = null;
259
+ let trailerLine = null;
260
+ for (let i = start + 1; i < end; i += 1) {
261
+ const field = FIELD_LINE_RE.exec(lines[i]);
262
+ if (field) {
263
+ const key = FIELDS.find(([, label]) => label === field[1])[0];
264
+ fields[key] = field[2].trim();
265
+ continue;
266
+ }
267
+ const trailer = TRAILER_RE.exec(lines[i]);
268
+ if (trailer && trailerLine === null) {
269
+ trailerLine = i;
270
+ const rest = trailer[1];
271
+ signature = /^`([^`]*)`/.exec(rest)?.[1] ?? null;
272
+ initiative = /\binitiative\s+`([^`]*)`/.exec(rest)?.[1] ?? null;
273
+ actor = /\bactor\s+`([^`]*)`/.exec(rest)?.[1] ?? null;
274
+ proof = /\bproof\s+`([^`]*)`/.exec(rest)?.[1] ?? null;
275
+ status = /\bstatus\s+`([^`]*)`/.exec(rest)?.[1] ?? null;
276
+ }
277
+ }
278
+ return {
279
+ heading,
280
+ date,
281
+ headingLine: start,
282
+ endLine: end,
283
+ fields,
284
+ signature,
285
+ initiative,
286
+ actor,
287
+ proof,
288
+ status,
289
+ statusKind: statusKindOf(status),
290
+ trailerLine,
291
+ };
292
+ }
293
+
294
+ /** `open` · `knowledge:<id>` · `law` · `wontfix` — anything else is reported. */
295
+ export function statusKindOf(status) {
296
+ if (status === null || status === undefined || status === '') return 'missing';
297
+ if (status === 'open') return 'open';
298
+ if (status === 'law') return 'law';
299
+ if (status === 'wontfix') return 'wontfix';
300
+ if (/^knowledge:\S+$/.test(status)) return 'knowledge';
301
+ return 'unknown';
302
+ }
303
+
304
+ // --------------------------------------------------------------- rendering
305
+
306
+ /**
307
+ * One entry, five bullets, every field on exactly ONE line.
308
+ *
309
+ * Cleaning here rather than only at the CLI boundary: this function is
310
+ * exported, and a second caller that forgot would forge a heading out of a
311
+ * field value — caller discipline is the mechanism class this repo distrusts.
312
+ */
313
+ export function renderEntry(entry) {
314
+ const {
315
+ date,
316
+ title,
317
+ signature,
318
+ initiative = '-',
319
+ actor = '-',
320
+ proof = '-',
321
+ status = 'open',
322
+ } = entry;
323
+ const bullets = FIELDS.map(([key, label]) => `- **${label}:** ${clean(entry[key] ?? '')}`);
324
+ return [
325
+ `## ${clean(date)} — ${clean(title)}`,
326
+ '',
327
+ ...bullets,
328
+ `- **Signature:** \`${clean(signature)}\` · initiative \`${clean(initiative)}\` · ` +
329
+ `actor \`${clean(actor)}\` · proof \`${clean(proof)}\` · status \`${clean(status)}\``,
330
+ ].join('\n');
331
+ }
332
+
333
+ /**
334
+ * Insert a rendered entry NEWEST FIRST: immediately before the first entry
335
+ * heading, or — when there is none yet — after the header, at end of file.
336
+ *
337
+ * The insertion point is a heading rather than a marker comment on purpose. A
338
+ * human who deletes the hint comment, or reorders two entries, keeps a working
339
+ * file; a parser anchored on a comment would silently start appending at the
340
+ * wrong end of a file whose whole contract is "newest first".
341
+ */
342
+ export function insertEntry(text, rendered) {
343
+ const doc = splitDoc(String(text));
344
+ const { firstEntryLine } = parseMistakes(text);
345
+ const block = rendered.split('\n');
346
+ if (firstEntryLine !== null) {
347
+ doc.lines.splice(firstEntryLine, 0, ...block, '');
348
+ return joinDoc(doc);
349
+ }
350
+ while (doc.lines.length > 0 && doc.lines.at(-1).trim() === '') doc.lines.pop();
351
+ if (doc.lines.length > 0) doc.lines.push('');
352
+ doc.lines.push(...block);
353
+ // A file that had no final newline keeps not having one; a file that had one
354
+ // keeps exactly one. Both halves are the operator's formatting, not ours.
355
+ return joinDoc({ ...doc, finalNewline: doc.finalNewline || text === '' });
356
+ }
357
+
358
+ /**
359
+ * Rewrite ONLY the `status` token of every matching entry's trailer.
360
+ *
361
+ * The trailer is edited in place, as text, rather than re-rendered from the
362
+ * parsed parts: re-rendering would silently normalise — and on an entry a
363
+ * human had annotated, LOSE — the initiative, actor and proof of exactly the
364
+ * entries that mattered enough to be promoted.
365
+ *
366
+ * The replacement is a FUNCTION, never a template string: `knowledge:<id>`
367
+ * admits `$&`, `` $` `` and `$'`, and String.replace would expand them into
368
+ * the surrounding trailer — corruption outside the status token, which is the
369
+ * one thing this function promises not to do.
370
+ */
371
+ export function promoteStatus(text, signature, newStatus, fromKinds) {
372
+ const doc = splitDoc(String(text));
373
+ const { entries } = parseMistakes(text);
374
+ let changed = 0;
375
+ for (const entry of entries) {
376
+ if (entry.signature !== signature || entry.trailerLine === null) continue;
377
+ if (!fromKinds.includes(entry.statusKind)) continue;
378
+ const line = doc.lines[entry.trailerLine];
379
+ const rewritten = line.replace(/(status\s+`)([^`]*)(`)/, (_match, open, _old, close) => open + newStatus + close);
380
+ if (rewritten === line) continue;
381
+ doc.lines[entry.trailerLine] = rewritten;
382
+ changed += 1;
383
+ }
384
+ return { text: joinDoc(doc), changed };
385
+ }
386
+
387
+ // ------------------------------------------------------------- the fence
388
+
389
+ /**
390
+ * Where Tyran's region of a `CLAUDE.md` is, or what is wrong with it.
391
+ *
392
+ * Returns `{start, end, problem, indent}` with line indices. A malformed fence
393
+ * is NEVER guessed at: this file belongs to the operator, and a writer that
394
+ * picked the likeliest interpretation of a broken marker pair would edit prose
395
+ * nobody asked it to touch.
396
+ *
397
+ * CODE-FENCE-AWARE, for the same reason `parseMistakes` is and with more force:
398
+ * `docs/self-improvement.md` ships the marker pair inside a ```markdown block,
399
+ * so an operator documenting the mechanism in their own CLAUDE.md would
400
+ * otherwise have the rule written into their example — or, with a real fence
401
+ * as well, be told forever that their fence has "2 start markers".
402
+ *
403
+ * `indent` is the start marker's own leading whitespace, so a fence nested
404
+ * under a list item gets its rule at the list's indentation instead of a line
405
+ * at column 0 that terminates the list early.
406
+ */
407
+ export function fenceState(text) {
408
+ const { lines } = splitDoc(String(text));
409
+ const { outside } = scanOutsideCodeFences(lines);
410
+ const starts = [];
411
+ const ends = [];
412
+ for (const [index, line] of outside) {
413
+ if (FENCE_START_RE.test(line)) starts.push(index);
414
+ else if (FENCE_END_RE.test(line)) ends.push(index);
415
+ }
416
+ const broken = (problem) => ({ start: null, end: null, problem, indent: '' });
417
+ if (starts.length > 1) return broken(`${starts.length} start markers`);
418
+ if (ends.length > 1) return broken(`${ends.length} end markers`);
419
+ if (starts.length === 1 && ends.length === 0) return broken('a start marker with no end marker');
420
+ if (ends.length === 1 && starts.length === 0) return broken('an end marker with no start marker');
421
+ if (starts.length === 0) return broken(null);
422
+ if (ends[0] < starts[0]) return broken('the end marker comes before the start marker');
423
+ return { start: starts[0], end: ends[0], problem: null, indent: /^[ \t]*/.exec(lines[starts[0]])[0] };
424
+ }
425
+
426
+ /** The fence block, identical wherever it is created — one shape, one answer. */
427
+ function fenceBlock() {
428
+ return [
429
+ FENCE_HEADING,
430
+ '',
431
+ 'Written by `mistakes.mjs promote --law` from `MISTAKES.md`, one line per',
432
+ 'failure that recurred often enough to be a rule. Only the region between',
433
+ 'the markers is machine-written; delete a line to reject its rule.',
434
+ '',
435
+ FENCE_START,
436
+ FENCE_END,
437
+ ];
438
+ }
439
+
440
+ /**
441
+ * Add one rule line inside the fence, creating the fence when it is absent.
442
+ *
443
+ * Appended at the END of the region rather than the top: `MISTAKES.md` is
444
+ * newest-first because a reader wants the recent incident, and a rule list is
445
+ * read as law where a stable order costs a reader nothing and a reshuffled
446
+ * diff costs them a review.
447
+ *
448
+ * Throws `UsageError` on a malformed fence — the caller turns that into exit 2
449
+ * naming the problem, because the alternative is writing into prose whose
450
+ * shape this function does not understand.
451
+ */
452
+ export function writeRuleToFence(text, ruleLine) {
453
+ const state = fenceState(text);
454
+ if (state.problem !== null) {
455
+ throw new UsageError(`the tyran:rules fence is malformed (${state.problem}) — repair it by hand; nothing was written`);
456
+ }
457
+ const doc = splitDoc(String(text));
458
+ if (state.start === null) {
459
+ // Appended once, at the end, with its heading. Existing prose is never
460
+ // reflowed, reordered or rewritten — only added after.
461
+ while (doc.lines.length > 0 && doc.lines.at(-1).trim() === '') doc.lines.pop();
462
+ const block = fenceBlock();
463
+ if (doc.lines.length > 0) doc.lines.push('');
464
+ doc.lines.push(...block);
465
+ doc.lines.splice(doc.lines.length - 1, 0, ruleLine);
466
+ return joinDoc({ ...doc, finalNewline: doc.finalNewline || text === '' });
467
+ }
468
+ // The fence's own indentation, not column 0: an operator who nested the
469
+ // markers under a list item gets a rule inside that list rather than a line
470
+ // that ends it.
471
+ doc.lines.splice(state.end, 0, state.indent + ruleLine);
472
+ return joinDoc(doc);
473
+ }
474
+
475
+ /** The rule lines currently inside the fence (empty when there is no fence). */
476
+ export function fenceRules(text) {
477
+ const state = fenceState(text);
478
+ if (state.problem !== null || state.start === null) return [];
479
+ const { lines } = splitDoc(String(text));
480
+ return lines.slice(state.start + 1, state.end).filter((line) => line.trim() !== '');
481
+ }
482
+
483
+ /**
484
+ * The one line a promotion writes: the rule, then the evidence that earned it.
485
+ *
486
+ * The evidence is not decoration. An operator who disagrees deletes the line,
487
+ * and the only way to disagree well is to be able to read what it cost.
488
+ */
489
+ export function ruleLineFor({ rule, signature, count, dates }) {
490
+ const pointer = dates.length > 0 ? ` — ${MISTAKES_FILE} entries ${dates.join(', ')}` : '';
491
+ return `- ${clean(rule)} (\`${clean(signature)}\`, ${count} occurrences${pointer})`;
492
+ }
493
+
494
+ /**
495
+ * The evidence parenthetical `ruleLineFor` writes, anchored where it writes it.
496
+ * Whitespace after it is tolerated; a rule's human text is not searched.
497
+ */
498
+ const RULE_EVIDENCE_RE = /\(`([a-z0-9]+(?:-[a-z0-9]+)*)`, \d+ occurrences(?: — [^`)]*)?\)$/;
499
+
500
+ /**
501
+ * The signature a rule line's MACHINE-WRITTEN evidence names, or `null`.
502
+ *
503
+ * Read from the tail rather than looked for anywhere in the line, because rule
504
+ * text naming another signature in backticks is the normal case — signatures
505
+ * are kebab-case slugs for repo concepts. A substring test let one such rule
506
+ * block that signature's own rule forever while its entries were still flipped
507
+ * to `law`: a trailer claiming law with no rule anywhere, which is the one
508
+ * state nothing downstream detects.
509
+ */
510
+ export function signatureOfRuleLine(line) {
511
+ return RULE_EVIDENCE_RE.exec(String(line).trimEnd())?.[1] ?? null;
512
+ }
513
+
514
+ /** Whether the fence carries a rule whose evidence names this signature. */
515
+ export function fenceCarriesSignature(text, signature) {
516
+ return fenceRules(text).some((line) => signatureOfRuleLine(line) === signature);
517
+ }
518
+
519
+ // ------------------------------------------------------------- validation
520
+
521
+ function checkField(name, value) {
522
+ if (typeof value !== 'string' || value.trim() === '') {
523
+ throw new UsageError(`--${name} is required and must not be empty`);
524
+ }
525
+ if (cpLength(value) > MISTAKE_FIELD_MAX) {
526
+ throw new UsageError(
527
+ `--${name} is ${cpLength(value)} codepoints, over the ${MISTAKE_FIELD_MAX} cap — ` +
528
+ 'shorten it or put the long material in NOTES.md and point at it here. It is NOT truncated',
529
+ );
530
+ }
531
+ return value;
532
+ }
533
+
534
+ function checkSignature(value) {
535
+ if (typeof value !== 'string' || !SIGNATURE_RE.test(value) || value.length > SIGNATURE_MAX) {
536
+ throw new UsageError(
537
+ `--signature ${JSON.stringify(escapeInvisible(String(value)))} is not a signature — ` +
538
+ `lower-case words joined by single hyphens, at most ${SIGNATURE_MAX} characters`,
539
+ );
540
+ }
541
+ return value;
542
+ }
543
+
544
+ /**
545
+ * The trailer's own fields live inside backticks, so a backtick in one of them
546
+ * would close its span early and hand the rest of the value to the parser as
547
+ * structure. Rejected rather than escaped: these are identifiers, and an
548
+ * identifier nobody can type back is not a useful one.
549
+ */
550
+ function checkTrailerField(name, value) {
551
+ if (value === undefined || value === null) return '-';
552
+ const text = clean(value);
553
+ if (text === '') return '-';
554
+ if (text.includes('`')) throw new UsageError(`--${name} must not contain a backtick`);
555
+ if (cpLength(value) > MISTAKE_FIELD_MAX) {
556
+ throw new UsageError(`--${name} is over the ${MISTAKE_FIELD_MAX}-codepoint cap`);
557
+ }
558
+ return text;
559
+ }
560
+
561
+ function checkDate(value) {
562
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(String(value))) {
563
+ throw new UsageError(`--date ${JSON.stringify(escapeInvisible(String(value)))} is not YYYY-MM-DD`);
564
+ }
565
+ return value;
566
+ }
567
+
568
+ /**
569
+ * An explicit title: the field checks, then the heading's own ceiling.
570
+ *
571
+ * Measured against the INPUT for the same reason as `MISTAKE_FIELD_MAX` —
572
+ * `escapeInvisible` turns one hostile codepoint into eight visible ones, and a
573
+ * cap counted after escaping would reject a legal title over a character its
574
+ * author cannot see.
575
+ */
576
+ function checkTitle(value) {
577
+ checkField('title', value);
578
+ if (cpLength(value) > TITLE_MAX) {
579
+ throw new UsageError(
580
+ `--title is ${cpLength(value)} codepoints, over the ${TITLE_MAX} cap — ` +
581
+ 'a heading is one line. It is NOT truncated',
582
+ );
583
+ }
584
+ return clean(value);
585
+ }
586
+
587
+ /** First sentence of `what`, cut at TITLE_MAX with an ellipsis. */
588
+ export function titleFrom(what) {
589
+ const text = clean(what);
590
+ const sentence = /^(.*?[.!?])(\s|$)/.exec(text)?.[1] ?? text;
591
+ const cps = Array.from(sentence);
592
+ return cps.length > TITLE_MAX ? cps.slice(0, TITLE_MAX - 1).join('') + '…' : sentence;
593
+ }
594
+
595
+ // ---------------------------------------------------------------- counting
596
+
597
+ /**
598
+ * Per-signature recurrence.
599
+ *
600
+ * The knowledge threshold counts `open` ONLY — a promoted signature stops
601
+ * counting toward its own re-promotion, which is double-promotion prevention
602
+ * number one and is mechanical rather than a rule anybody has to remember.
603
+ * The law threshold counts `open` PLUS already-promoted, because the argument
604
+ * for law is precisely "it kept happening after the knowledge entry shipped".
605
+ */
606
+ export function countSignatures(entries) {
607
+ const bySignature = new Map();
608
+ for (const entry of entries) {
609
+ if (entry.signature === null || entry.signature === '') continue;
610
+ let row = bySignature.get(entry.signature);
611
+ if (row === undefined) {
612
+ row = { signature: entry.signature, open: 0, knowledge: 0, law: 0, wontfix: 0, unknown: 0, missing: 0, dates: [] };
613
+ bySignature.set(entry.signature, row);
614
+ }
615
+ row[entry.statusKind] += 1;
616
+ if (entry.date !== null) row.dates.push(entry.date);
617
+ }
618
+ for (const row of bySignature.values()) {
619
+ row.dates.sort();
620
+ row.lawCount = row.open + row.knowledge;
621
+ }
622
+ return [...bySignature.values()].sort((a, b) => (a.signature < b.signature ? -1 : a.signature > b.signature ? 1 : 0));
623
+ }
624
+
625
+ // --------------------------------------------------------------------- IO
626
+
627
+ function readMistakes(path) {
628
+ if (!existsSync(path)) {
629
+ throw new IOError(
630
+ `no ${MISTAKES_FILE} at ${escapeInvisible(path)} — deleting the file is this feature's whole opt-out, ` +
631
+ 'so nothing here puts it back. `scan-repo.mjs --ensure-policy` seeds it again if you want one',
632
+ );
633
+ }
634
+ return readText(path);
635
+ }
636
+
637
+ /**
638
+ * Every read this CLI makes, with the failure named.
639
+ *
640
+ * An EISDIR or EACCES escaping as an uncaught exception is a stack trace and
641
+ * exit 1 — the code this CLI's contract reserves for "nothing matched", which
642
+ * an automated caller reads as "the signature has not earned law" and moves on
643
+ * from. IO belongs on exit 2 with the path in the message.
644
+ */
645
+ function readText(path) {
646
+ try {
647
+ return readFileSync(path, 'utf8');
648
+ } catch (error) {
649
+ throw new IOError(`could not read ${escapeInvisible(path)}: ${error.message}`);
650
+ }
651
+ }
652
+
653
+ /**
654
+ * Every write this CLI makes, THROUGH a symlink rather than over it.
655
+ *
656
+ * `writeAtomic` renames a temp file onto the target, and a rename replaces a
657
+ * symlink with a regular file: an operator whose `CLAUDE.md` links to a shared
658
+ * or global instructions file would lose the link while the file they meant
659
+ * never received the rule — silent on both halves. So the link is resolved and
660
+ * the file it names is written, which is what every editor does with the same
661
+ * path; refusing instead would make an ordinary monorepo layout unpromotable.
662
+ * A link pointing nowhere is the one case that IS refused: there is no file to
663
+ * write, and replacing the link would destroy the operator's only record of
664
+ * where it pointed.
665
+ */
666
+ function writeThroughLinks(path, text) {
667
+ let target = path;
668
+ let link = null;
669
+ try {
670
+ link = lstatSync(path).isSymbolicLink();
671
+ } catch {
672
+ link = false; // no such path yet: the write creates it
673
+ }
674
+ if (link) {
675
+ try {
676
+ target = realpathSync(path);
677
+ } catch (error) {
678
+ throw new IOError(
679
+ `${escapeInvisible(path)} is a symlink to a path that does not exist (${error.message}) — ` +
680
+ 'repair the link; nothing was written',
681
+ );
682
+ }
683
+ }
684
+ try {
685
+ writeAtomic(target, text);
686
+ } catch (error) {
687
+ throw new IOError(`could not write ${escapeInvisible(target)}: ${error.message}`);
688
+ }
689
+ }
690
+
691
+ // ---------------------------------------------------------------- the CLI
692
+
693
+ const VALUE_FLAGS = [
694
+ 'file', 'signature', 'what', 'cause', 'consequence', 'prevention', 'title',
695
+ 'initiative', 'actor', 'proof', 'date', 'threshold', 'status', 'rule',
696
+ 'claude-md', 'journal', 'init',
697
+ ];
698
+ const BOOLEAN_FLAGS = ['json', 'law', 'dry-run'];
699
+
700
+ const USAGE = [
701
+ 'usage:',
702
+ ' mistakes.mjs add --signature S --what W --cause C --consequence Q --prevention P',
703
+ ' [--file F] [--title T] [--initiative SLUG] [--actor A]',
704
+ ' [--proof F-12] [--date YYYY-MM-DD]',
705
+ ' mistakes.mjs repeats [--file F] [--threshold N] [--json]',
706
+ ' mistakes.mjs promote --signature S --status knowledge:<id>|wontfix [--file F]',
707
+ ' mistakes.mjs promote --signature S --law --rule TEXT [--file F] [--claude-md PATH]',
708
+ ' [--dry-run] [--journal PATH] [--init SLUG] [--actor A]',
709
+ ].join('\n');
710
+
711
+ function parseArgs(argv) {
712
+ const flags = Object.create(null);
713
+ for (let i = 0; i < argv.length; i += 1) {
714
+ const arg = argv[i];
715
+ if (!arg.startsWith('--')) throw new UsageError(`unexpected argument ${JSON.stringify(escapeInvisible(arg))}`);
716
+ const name = arg.slice(2);
717
+ if (BOOLEAN_FLAGS.includes(name)) {
718
+ flags[name] = true;
719
+ continue;
720
+ }
721
+ if (!VALUE_FLAGS.includes(name)) throw new UsageError(`unknown flag --${escapeInvisible(name)}`);
722
+ const value = argv[i + 1];
723
+ if (value === undefined) throw new UsageError(`flag --${name} needs a value`);
724
+ flags[name] = value;
725
+ i += 1;
726
+ }
727
+ return flags;
728
+ }
729
+
730
+ function cmdAdd(flags) {
731
+ const path = resolve(flags.file ?? MISTAKES_FILE);
732
+ const signature = checkSignature(flags.signature);
733
+ const entry = {
734
+ date: checkDate(flags.date ?? new Date().toISOString().slice(0, 10)),
735
+ signature,
736
+ initiative: checkTrailerField('initiative', flags.initiative),
737
+ actor: checkTrailerField('actor', flags.actor),
738
+ proof: checkTrailerField('proof', flags.proof),
739
+ status: 'open',
740
+ };
741
+ for (const [key] of FIELDS) entry[key] = checkField(key, flags[key]);
742
+ entry.title = flags.title === undefined ? titleFrom(entry.what) : checkTitle(flags.title);
743
+
744
+ const before = readMistakes(path);
745
+ const after = insertEntry(before, renderEntry(entry));
746
+ writeThroughLinks(path, after);
747
+ console.error(`mistakes: added \`${signature}\` to ${escapeInvisible(path)} (${entry.date})`);
748
+ return 0;
749
+ }
750
+
751
+ function cmdRepeats(flags) {
752
+ const path = resolve(flags.file ?? MISTAKES_FILE);
753
+ const threshold = Number(flags.threshold ?? KNOWLEDGE_THRESHOLD);
754
+ if (!Number.isInteger(threshold) || threshold < 1) throw new UsageError('--threshold must be a positive integer');
755
+ const parsed = parseMistakes(readMistakes(path));
756
+ const rows = countSignatures(parsed.entries).filter(
757
+ (row) => row.open >= threshold || row.lawCount >= LAW_THRESHOLD,
758
+ );
759
+
760
+ if (flags.json) {
761
+ console.log(JSON.stringify(
762
+ {
763
+ threshold,
764
+ law_threshold: LAW_THRESHOLD,
765
+ entries: parsed.entries.length,
766
+ without_signature: parsed.withoutSignature,
767
+ unknown_status: parsed.unknownStatus,
768
+ dangling_code_fence_line: parsed.danglingFence === null ? null : parsed.danglingFence + 1,
769
+ signatures: rows.map((row) => ({ ...row, recommendation: recommendationFor(row, threshold) })),
770
+ },
771
+ null,
772
+ 2,
773
+ ));
774
+ return rows.length > 0 ? 0 : 1;
775
+ }
776
+
777
+ const width = Math.max(0, ...rows.map((row) => row.signature.length));
778
+ for (const row of rows) {
779
+ const counted = row.lawCount >= LAW_THRESHOLD
780
+ ? `${row.lawCount} open+promoted (${row.dates.join(', ')})`
781
+ : `${row.open} open (${row.dates.join(', ')})`;
782
+ console.log(`${row.signature.padEnd(width)} ${counted} -> ${recommendationFor(row, threshold)}`);
783
+ }
784
+ // Omission is never silent: an entry nobody gave a signature, an entry whose
785
+ // status was typo'd, and a code fence nobody closed are the three ways this
786
+ // file quietly reads as smaller than it is.
787
+ const notes = [`${rows.length} signature(s) at or above the threshold`, `${parsed.entries.length} entries scanned`];
788
+ if (parsed.withoutSignature > 0) notes.push(`${parsed.withoutSignature} without a signature`);
789
+ if (parsed.unknownStatus > 0) notes.push(`${parsed.unknownStatus} with an unrecognised status`);
790
+ if (parsed.danglingFence !== null) notes.push(danglingFenceNote(parsed));
791
+ console.log(notes.join('; '));
792
+ return rows.length > 0 ? 0 : 1;
793
+ }
794
+
795
+ /** An unclosed ``` swallows every entry below it — said, never absorbed. */
796
+ function danglingFenceNote(parsed) {
797
+ return `a code fence opened at line ${parsed.danglingFence + 1} is never closed, so every entry below it was NOT counted`;
798
+ }
799
+
800
+ function recommendationFor(row, threshold) {
801
+ if (row.lawCount >= LAW_THRESHOLD) return 'promote to CLAUDE.md law (mistakes.mjs promote --law)';
802
+ if (row.open >= threshold) return 'promote to .tyran/knowledge/';
803
+ return 'below both thresholds';
804
+ }
805
+
806
+ function cmdPromote(flags) {
807
+ const path = resolve(flags.file ?? MISTAKES_FILE);
808
+ const signature = checkSignature(flags.signature);
809
+ if (flags.law) return promoteLaw(flags, path, signature);
810
+
811
+ if (flags.rule !== undefined) throw new UsageError('--rule belongs to --law; a status promotion writes no rule');
812
+ const status = String(flags.status ?? '');
813
+ if (status === 'law') {
814
+ throw new UsageError(
815
+ 'status `law` is written by --law, which puts the rule in the CLAUDE.md fence in the same run — ' +
816
+ 'a trailer that says `law` while no rule exists is the one state nothing can detect',
817
+ );
818
+ }
819
+ // `wontfix` is the demotion, so it must be able to reach an entry at ANY
820
+ // status; `knowledge:<id>` promotes `open` only, which is what stops a
821
+ // promoted signature being promoted again on every retro forever.
822
+ let fromKinds;
823
+ if (status === 'wontfix') fromKinds = ['open', 'knowledge', 'law', 'unknown', 'missing'];
824
+ else if (/^knowledge:\S+$/.test(status)) fromKinds = ['open'];
825
+ else throw new UsageError(`--status must be knowledge:<id> or wontfix (got ${JSON.stringify(escapeInvisible(status))})`);
826
+ // The trailer writes the status inside a backtick span, so a backtick in the
827
+ // id would close it early and hand the rest of the id to the parser as
828
+ // structure — refused here for the same reason `checkTrailerField` refuses
829
+ // it, rather than written and read back as something shorter.
830
+ if (status.includes('`')) throw new UsageError('--status must not contain a backtick');
831
+
832
+ const { text, changed } = promoteStatus(readMistakes(path), signature, status, fromKinds);
833
+ if (changed === 0) {
834
+ console.error(`mistakes: no entry with signature \`${signature}\` was eligible for status \`${status}\` — nothing written`);
835
+ return 1;
836
+ }
837
+ writeThroughLinks(path, text);
838
+ console.error(`mistakes: ${changed} entr${changed === 1 ? 'y' : 'ies'} moved to status \`${status}\``);
839
+ return 0;
840
+ }
841
+
842
+ /**
843
+ * The law step: the rule goes into the operator's CLAUDE.md fence, and the
844
+ * entries that earned it move to `law`.
845
+ *
846
+ * ORDER MATTERS, and the crash window decides it. CLAUDE.md is written first:
847
+ * if the process dies between the two writes the statuses are still eligible,
848
+ * the fence already carries the line, and a re-run heals — it skips the
849
+ * duplicate and flips the trailers. Written the other way round, a crash would
850
+ * leave entries claiming `law` with no rule anywhere and no run able to
851
+ * produce one.
852
+ */
853
+ function promoteLaw(flags, path, signature) {
854
+ const rule = checkField('rule', flags.rule);
855
+ const claudePath = resolve(flags['claude-md'] ?? join(dirname(path), CLAUDE_MD_FILE));
856
+
857
+ const parsed = parseMistakes(readMistakes(path));
858
+ if (parsed.danglingFence !== null) console.error(`mistakes: ${danglingFenceNote(parsed)}`);
859
+ const row = countSignatures(parsed.entries).find((r) => r.signature === signature);
860
+ const count = row?.lawCount ?? 0;
861
+ if (count === 0) {
862
+ console.error(`mistakes: no entry with signature \`${signature}\` is eligible for law — nothing written`);
863
+ return 1;
864
+ }
865
+ // The threshold is EVIDENCE, not opinion, and it has no override flag on
866
+ // purpose: a switch that lowered it would make the guarantee a preference.
867
+ if (count < LAW_THRESHOLD) {
868
+ console.error(
869
+ `mistakes: \`${signature}\` has ${count} open-or-promoted entr${count === 1 ? 'y' : 'ies'}, ` +
870
+ `below the law threshold of ${LAW_THRESHOLD} — nothing written`,
871
+ );
872
+ return 1;
873
+ }
874
+
875
+ const claudeText = existsSync(claudePath) ? readText(claudePath) : '';
876
+ const state = fenceState(claudeText);
877
+ if (state.problem !== null) {
878
+ throw new UsageError(
879
+ `${escapeInvisible(claudePath)}: the tyran:rules fence is malformed (${state.problem}) — ` +
880
+ 'repair it by hand; nothing was written',
881
+ );
882
+ }
883
+ const line = ruleLineFor({ rule, signature, count, dates: row.dates });
884
+ // The signature this line's EVIDENCE names, never a substring of the rule's
885
+ // prose: see `signatureOfRuleLine`.
886
+ const already = fenceCarriesSignature(claudeText, signature);
887
+
888
+ if (flags['dry-run']) {
889
+ console.log(line);
890
+ console.error(
891
+ `mistakes: --dry-run — ${already ? 'the fence already carries this signature; ' : ''}` +
892
+ `nothing was written to ${escapeInvisible(claudePath)} or ${escapeInvisible(path)}`,
893
+ );
894
+ return 0;
895
+ }
896
+
897
+ // The status flip and the rule line are ONE decision, checked before either
898
+ // is made: entries that say `law` while the rule is in no fence — because an
899
+ // unclosed code fence in the operator's document swallowed the block we would
900
+ // append — is the one state nothing downstream detects, so it is refused
901
+ // rather than produced.
902
+ const nextClaudeText = already ? claudeText : writeRuleToFence(claudeText, line);
903
+ if (!fenceCarriesSignature(nextClaudeText, signature)) {
904
+ console.error(
905
+ `mistakes: ${escapeInvisible(claudePath)} would carry no rule for \`${signature}\` after the write ` +
906
+ '(an unclosed ``` code fence swallowing the tyran:rules block?) — nothing written, no status moved',
907
+ );
908
+ return 1;
909
+ }
910
+
911
+ if (!already) writeThroughLinks(claudePath, nextClaudeText);
912
+ const { text, changed } = promoteStatus(readMistakes(path), signature, 'law', ['open', 'knowledge']);
913
+ writeThroughLinks(path, text);
914
+ console.error(
915
+ already
916
+ ? `mistakes: ${escapeInvisible(claudePath)} already carried \`${signature}\`; ${changed} entr${changed === 1 ? 'y' : 'ies'} moved to status \`law\``
917
+ : `mistakes: wrote the rule into ${escapeInvisible(claudePath)} and moved ${changed} entr${changed === 1 ? 'y' : 'ies'} to status \`law\``,
918
+ );
919
+ journalDecision(flags, { signature, count, line, claudePath });
920
+ return 0;
921
+ }
922
+
923
+ /**
924
+ * The record of an autonomous act — not a request for permission.
925
+ *
926
+ * A failure here never fails the command. The irreversible half already
927
+ * happened, a re-run exits 1 by design, and a non-zero exit would send a
928
+ * caller into a retry that cannot succeed; so the remedy is printed as a
929
+ * command the operator or the retro can paste, and the omission is loud.
930
+ */
931
+ function journalDecision(flags, { signature, count, line, claudePath }) {
932
+ if (flags.journal === undefined || flags.init === undefined) {
933
+ console.error(
934
+ 'mistakes: no --journal/--init given, so this promotion is in no initiative\'s record — ' +
935
+ 'append a `decision` event by hand if this ran inside one',
936
+ );
937
+ return;
938
+ }
939
+ const file = resolve(flags.journal);
940
+ try {
941
+ appendEvent(file, {
942
+ ev: 'decision',
943
+ init: flags.init,
944
+ actor: flags.actor ?? 'retro',
945
+ data: {
946
+ id: nextId(file, 'D'),
947
+ text: `promoted a rule into ${CLAUDE_MD_FILE}: ${clean(line)}`,
948
+ signature,
949
+ occurrences: count,
950
+ path: claudePath,
951
+ },
952
+ });
953
+ } catch (error) {
954
+ console.error(`mistakes: the promotion succeeded but the journal did NOT record it (${error.message})`);
955
+ console.error(
956
+ `mistakes: node scripts/journal.mjs append ${escapeInvisible(file)} decision ${escapeInvisible(String(flags.init))} ` +
957
+ '--actor retro --data \'{"text":"promoted a rule into CLAUDE.md"}\'',
958
+ );
959
+ }
960
+ }
961
+
962
+ function main() {
963
+ const [command, ...rest] = process.argv.slice(2);
964
+ let code;
965
+ try {
966
+ const flags = parseArgs(rest);
967
+ if (command === 'add') code = cmdAdd(flags);
968
+ else if (command === 'repeats') code = cmdRepeats(flags);
969
+ else if (command === 'promote') code = cmdPromote(flags);
970
+ else throw new UsageError(command === undefined ? 'no subcommand' : `unknown subcommand ${JSON.stringify(escapeInvisible(command))}`);
971
+ } catch (error) {
972
+ if (error instanceof UsageError) {
973
+ console.error(`mistakes: ${error.message}`);
974
+ console.error(USAGE);
975
+ process.exitCode = 2;
976
+ return;
977
+ }
978
+ if (error instanceof IOError) {
979
+ console.error(`mistakes: ${error.message}`);
980
+ process.exitCode = 2;
981
+ return;
982
+ }
983
+ throw error;
984
+ }
985
+ // exitCode, never process.exit(): exit() does not wait for stdout to drain,
986
+ // and `repeats --json` into a pipe is exactly the consumer that would be
987
+ // truncated at the moment its output matters.
988
+ process.exitCode = code;
989
+ }
990
+
991
+ function canonicalPath(path) {
992
+ const abs = resolve(path);
993
+ try {
994
+ return realpathSync(abs);
995
+ } catch {
996
+ return abs;
997
+ }
998
+ }
999
+
1000
+ function isMainModule(moduleUrl) {
1001
+ if (!process.argv[1]) return false;
1002
+ return canonicalPath(process.argv[1]) === canonicalPath(fileURLToPath(moduleUrl));
1003
+ }
1004
+
1005
+ if (isMainModule(import.meta.url)) main();