@houserules/payload 0.0.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.
@@ -0,0 +1,545 @@
1
+ import { gzipSync, gunzipSync } from 'node:zlib';
2
+ import { appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync, mkdirSync, readdirSync, renameSync, } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, relative, resolve } from 'node:path';
5
+ import { ENTRY_HEAD } from './backlog-id.mjs';
6
+ export const SEPARATOR = '---';
7
+ const TRANSCRIPT_TAIL_BYTES = 16384;
8
+ const METADATA_LINE = /^\*\*([A-Za-z][A-Za-z ]*):\*\*\s+(.+)$/;
9
+ const METADATA_JOIN = ' · ';
10
+ export const nowIso = () => new Date().toISOString();
11
+ export const todayDate = () => nowIso().slice(0, 10);
12
+ export const encodeBody = (s) => gzipSync(Buffer.from(s ?? '', 'utf8')).toString('base64');
13
+ export const decodeBody = (s) => gunzipSync(Buffer.from(s, 'base64')).toString('utf8');
14
+ function readLastJsonRecord(file) {
15
+ let fd;
16
+ try {
17
+ fd = openSync(file, 'r');
18
+ }
19
+ catch {
20
+ return null;
21
+ }
22
+ try {
23
+ const { size } = fstatSync(fd);
24
+ if (size === 0)
25
+ return null;
26
+ const chunkSize = Math.min(size, TRANSCRIPT_TAIL_BYTES);
27
+ const buf = Buffer.alloc(chunkSize);
28
+ readSync(fd, buf, 0, chunkSize, size - chunkSize);
29
+ const lines = buf.toString('utf8').split('\n').filter(Boolean);
30
+ for (let i = lines.length - 1; i >= 0; i--) {
31
+ const line = lines[i];
32
+ if (line === undefined)
33
+ continue;
34
+ try {
35
+ return JSON.parse(line);
36
+ }
37
+ catch {
38
+ // Partial JSON at the buffer head, or a malformed line — keep walking back.
39
+ }
40
+ }
41
+ return null;
42
+ }
43
+ finally {
44
+ closeSync(fd);
45
+ }
46
+ }
47
+ /**
48
+ * The active Claude Code session, from `CLAUDE_SESSION_ID` or the freshest transcript tail.
49
+ * Transcripts live at `~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`, where encoded-cwd
50
+ * is the absolute repo path with `/` replaced by `-`. mtime alone is not reliable when several
51
+ * sessions share one project at once, so this compares the last record's timestamp.
52
+ *
53
+ * @returns null in any harness that is not Claude Code, which callers report as `chat: null`.
54
+ */
55
+ function detectChatId(repoRoot) {
56
+ if (process.env.CLAUDE_SESSION_ID)
57
+ return process.env.CLAUDE_SESSION_ID;
58
+ const dir = resolve(homedir(), '.claude/projects', repoRoot.replaceAll('/', '-'));
59
+ if (!existsSync(dir))
60
+ return null;
61
+ let entries;
62
+ try {
63
+ entries = readdirSync(dir, { withFileTypes: true });
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ let best = null;
69
+ for (const e of entries) {
70
+ if (!e.isFile() || !e.name.endsWith('.jsonl'))
71
+ continue;
72
+ const rec = readLastJsonRecord(resolve(dir, e.name));
73
+ if (!rec?.sessionId || !rec?.timestamp)
74
+ continue;
75
+ const ts = Date.parse(rec.timestamp);
76
+ if (!Number.isFinite(ts))
77
+ continue;
78
+ if (!best || ts > best.ts)
79
+ best = { ts, sessionId: rec.sessionId };
80
+ }
81
+ return best?.sessionId ?? null;
82
+ }
83
+ /** Splices `--chat <id>` / `--chat=<id>` out of `argv` in place. */
84
+ export function takeChatFlag(argv) {
85
+ for (let i = 0; i < argv.length; i++) {
86
+ const a = argv[i];
87
+ if (a === '--chat') {
88
+ const v = argv[i + 1];
89
+ argv.splice(i, 2);
90
+ return v ?? null;
91
+ }
92
+ if (a?.startsWith('--chat=')) {
93
+ argv.splice(i, 1);
94
+ return a.slice('--chat='.length) || null;
95
+ }
96
+ }
97
+ return null;
98
+ }
99
+ /** `--chat=none` suppresses provenance. Any other flag wins over detection. */
100
+ export function resolveChat(flag, repoRoot) {
101
+ if (flag === 'none')
102
+ return null;
103
+ return flag ?? detectChatId(repoRoot);
104
+ }
105
+ export function appendEvent(logFile, record) {
106
+ appendFileSync(logFile, JSON.stringify(record) + '\n');
107
+ }
108
+ /** Every parseable record in log order. Unparseable lines are skipped, never fatal. */
109
+ export function readLog(logFile) {
110
+ if (!existsSync(logFile))
111
+ return [];
112
+ const out = [];
113
+ for (const line of readFileSync(logFile, 'utf8').split('\n')) {
114
+ if (!line)
115
+ continue;
116
+ try {
117
+ out.push(JSON.parse(line));
118
+ }
119
+ catch {
120
+ // A truncated write or a hand-edit. One bad line must not blind the whole ledger.
121
+ }
122
+ }
123
+ return out;
124
+ }
125
+ /**
126
+ * The append-only ledger for `name`, at `.claude/ledgers/<name>.jsonl`.
127
+ *
128
+ * Its own directory rather than `.claude/state/`, which the changesets module already owns for
129
+ * ephemeral cache and self-gitignores with `*` because none of it needs to survive being
130
+ * deleted. The ledger is a local write-ahead queue that `projects-sync.mjs push` drains to
131
+ * GitHub Projects, so an entry not yet pushed exists nowhere else, and the two directories need
132
+ * different ignore rules and cannot share one. `.jsonl` and not `.log`, because `*.log` is a
133
+ * common ignore pattern this file must avoid.
134
+ *
135
+ * Older trees are migrated in place, newest layout first, so there is one path afterward and
136
+ * never a split ledger. A rename that fails leaves the older file authoritative rather than
137
+ * starting a second one.
138
+ */
139
+ export function ledgerPath(repoRoot, name, configuredDir) {
140
+ const current = resolve(ledgerDir(repoRoot, configuredDir), `${name}.jsonl`);
141
+ if (existsSync(current))
142
+ return current;
143
+ // Unconditionally, not only when migrating. A fresh install has no legacy file to move, and
144
+ // the first append would otherwise fail with ENOENT on a directory nothing had created.
145
+ try {
146
+ mkdirSync(dirname(current), { recursive: true });
147
+ }
148
+ catch {
149
+ // A caller that cannot create the directory also cannot write the ledger. Let the write
150
+ // report that, rather than failing here with less context.
151
+ }
152
+ for (const legacy of [
153
+ resolve(repoRoot, `.claude/${name}.jsonl`),
154
+ resolve(repoRoot, `.claude/${name}.log`),
155
+ ]) {
156
+ if (!existsSync(legacy))
157
+ continue;
158
+ try {
159
+ renameSync(legacy, current);
160
+ return current;
161
+ }
162
+ catch {
163
+ return legacy;
164
+ }
165
+ }
166
+ return current;
167
+ }
168
+ /**
169
+ * Whether replacing `file` with `nextContent` would drop entries the file already holds and
170
+ * the ledger does not account for.
171
+ *
172
+ * A rebuild reads the ledger and overwrites the surface, so a missing ledger silently destroys
173
+ * the only remaining copy. Measured, not assumed: a checkout carrying the surface without its
174
+ * ledger turned four recorded decisions into one.
175
+ *
176
+ * Compares id SETS, not counts. A count check cannot tell a legitimate removal from the loss
177
+ * of a different entry, and it misses the case where one entry vanishes as another appears.
178
+ * `intentionallyDropped` is the ids the ledger records as removed, which a backlog removal
179
+ * produces and a decision never does, since superseding leaves the entry rendered.
180
+ */
181
+ export function rebuildWouldDropEntries(file, nextContent, intentionallyDropped = new Set()) {
182
+ const before = parseEntries(readSurface(file));
183
+ if (before.length === 0)
184
+ return false;
185
+ const after = new Set(parseEntries(nextContent).map((e) => e.id));
186
+ return before.some((e) => !after.has(e.id) && !intentionallyDropped.has(e.id));
187
+ }
188
+ export function readSurface(file) {
189
+ return existsSync(file) ? readFileSync(file, 'utf8') : '';
190
+ }
191
+ /** Reads the body from the argument, or from stdin when it was omitted and stdin is a pipe. */
192
+ export function readContentArg(content) {
193
+ if (content !== undefined)
194
+ return content;
195
+ if (process.stdin.isTTY)
196
+ return '';
197
+ return readFileSync(0, 'utf8').trimEnd();
198
+ }
199
+ export function relativeToRoot(repoRoot, p) {
200
+ return relative(repoRoot, resolve(p));
201
+ }
202
+ const DEFAULT_LEDGER_DIR = '.claude/ledgers';
203
+ /**
204
+ * The ledger directory, from `ledgers.dir` or the default.
205
+ *
206
+ * Falls back to the default for a path that escapes the repo, and for the repo root itself. The
207
+ * root is refused because houserules self-ignores this directory with `*.md`, and that rule at the
208
+ * repo root would hide README.md, CLAUDE.md, and every other document in the project.
209
+ */
210
+ export function ledgerDir(repoRoot, configured) {
211
+ const root = resolve(repoRoot);
212
+ const fallback = resolve(root, DEFAULT_LEDGER_DIR);
213
+ const dir = resolve(root, configured || DEFAULT_LEDGER_DIR);
214
+ if (dir === root)
215
+ return fallback;
216
+ return dir.startsWith(`${root}/`) ? dir : fallback;
217
+ }
218
+ /**
219
+ * Where one area's rendered surface lives, as `<dir>/<target>.<basename>`.
220
+ *
221
+ * A monorepo separates areas by filename inside one ledger directory rather than by nesting a
222
+ * ledger beside each package. One directory per repo means one place to find, ignore, and
223
+ * reconcile, and the record's own `file` field already says which surface an entry belongs to.
224
+ * The root area has no prefix, so it stays `BACKLOG.md`.
225
+ */
226
+ export function surfacePath(dir, basename, target) {
227
+ return resolve(dir, target ? `${target}.${basename}` : basename);
228
+ }
229
+ /**
230
+ * Whether a surface with zero live entries should be deleted rather than left as a bare header.
231
+ *
232
+ * A surface is written for any area the ledger has ever recorded against, so an area whose
233
+ * entries were all removed kept rendering as a header-only stub that no `remove` could ever
234
+ * clear. The repo-root area collects every entry logged without an `<area>`, which makes it the
235
+ * one that accumulates stubs by accident.
236
+ *
237
+ * A configured target is exempt. Its surface is declared in `houserules.config.json`, so an empty one
238
+ * reads as "this area has nothing open" rather than as residue, and deleting it would churn a
239
+ * file the repo means to have. An area with no target and no entries is residue, so it goes.
240
+ */
241
+ export function surfaceIsResidue(file, basename, entryCount, targets) {
242
+ if (entryCount > 0)
243
+ return false;
244
+ const name = file.split('/').pop() ?? '';
245
+ if (name === basename)
246
+ return true;
247
+ const target = name.slice(0, -(basename.length + 1));
248
+ return !targets.some((t) => t.name === target);
249
+ }
250
+ /**
251
+ * The area a rendered surface covers, for its header. Reads the target out of the filename and
252
+ * maps it through the configured targets, so a file named `studio.BACKLOG.md` renders as
253
+ * `Backlog — Studio` rather than naming the directory it happens to sit in.
254
+ *
255
+ * The target's `label` wins over its `pathPrefix`. A surface named for a target does not have to
256
+ * hold only that target's entries: a repo whose whole product is one target files everything
257
+ * there, and rendering `pathPrefix` then claims a scope narrower than the entries below it. The
258
+ * label is the name the user chose for the area, so it stays true either way. `pathPrefix`
259
+ * remains the fallback for a target that somehow carries no label.
260
+ */
261
+ export function surfaceScope(file, basename, targets) {
262
+ const name = file.split('/').pop() ?? '';
263
+ if (name === basename)
264
+ return 'repo root';
265
+ const target = name.slice(0, -(basename.length + 1));
266
+ const match = targets.find((t) => t.name === target);
267
+ return match?.label || match?.pathPrefix?.replace(/\/$/, '') || target;
268
+ }
269
+ /**
270
+ * The path recorded on each entry's `file`, and matched against when rebuilding a surface.
271
+ *
272
+ * Relative to the LEDGER DIRECTORY, never the repo root. Two reasons, both load-bearing. A
273
+ * record written when the surface sat at the repo root says `BACKLOG.md`, and that keeps
274
+ * matching once the surface moves into the ledger directory, so no migration is needed. And
275
+ * moving the directory later through `ledgers.dir` does not orphan every existing record.
276
+ *
277
+ * Recording this against the repo root instead silently renders an empty surface: the filter
278
+ * compares `.claude/ledgers/BACKLOG.md` to a stored `BACKLOG.md` and matches nothing.
279
+ */
280
+ export function surfaceRelFile(dir, file) {
281
+ return relative(dir, resolve(file));
282
+ }
283
+ /**
284
+ * Collapses a surface name that carries its basename more than once down to a single copy.
285
+ *
286
+ * `tower-push.DECISIONS.md` is the surface for the `tower-push` area, so passing that whole
287
+ * name where an area was expected glued a second basename on and produced
288
+ * `tower-push.DECISIONS.md.DECISIONS.md`. Nothing rejected it, the name has no separator, and
289
+ * a name with no separator reads as a legitimate area, so the doubled surface rendered as a
290
+ * distinct file and split one area's entries across two.
291
+ *
292
+ * Only a genuine repeat is collapsed. A name carrying the basename once is already canonical,
293
+ * and a bare area name is left alone for the caller to glue.
294
+ */
295
+ function collapseRepeatedSuffix(name, basename) {
296
+ const suffix = `.${basename}`;
297
+ let collapsed = name;
298
+ while (collapsed.endsWith(`${suffix}${suffix}`))
299
+ collapsed = collapsed.slice(0, -suffix.length);
300
+ return collapsed;
301
+ }
302
+ /**
303
+ * The ledger-dir-relative surface name a recorded `file` value refers to today.
304
+ *
305
+ * Ledgers written before the surfaces moved into the ledger directory recorded a repo-relative
306
+ * path such as `games/tower-push/BACKLOG.md`. Nothing can equal that today, because
307
+ * {@link surfaceRelFile} now yields `tower-push.BACKLOG.md`, so every such entry silently stops
308
+ * matching its surface and the ledger renders empty.
309
+ *
310
+ * Normalizing on READ rather than rewriting the ledger is deliberate. The ledger is append-only,
311
+ * so a migration that rewrote historical `file` fields would edit records already appended and
312
+ * possibly already pushed to the board. This is a pure projection instead, it is idempotent,
313
+ * and a repo can roll back to an older houserules without its history having been altered.
314
+ *
315
+ * The area is taken from the configured targets first, since that is authoritative. The trailing
316
+ * directory name is the fallback, which is what makes an area the config no longer lists still
317
+ * resolve rather than vanish.
318
+ *
319
+ * @param recorded The `file` value as stored on the entry.
320
+ * @param basename The surface basename, `BACKLOG.md` or `DECISIONS.md`.
321
+ */
322
+ export function normalizeSurfaceRef(recorded, basename, targets) {
323
+ const clean = collapseRepeatedSuffix(recorded.replace(/^\.\//, ''), basename);
324
+ if (!clean.includes('/'))
325
+ return clean;
326
+ if (!clean.endsWith(`/${basename}`))
327
+ return clean;
328
+ const dir = clean.slice(0, -(basename.length + 1));
329
+ const match = targets.find((target) => (target.pathPrefix ?? '').replace(/\/+$/, '') === dir);
330
+ const area = match?.name ?? dir.split('/').filter(Boolean).pop();
331
+ return area ? `${area}.${basename}` : clean;
332
+ }
333
+ /**
334
+ * Resolves the `<area>` argument the ledger commands accept, one rule for every ledger.
335
+ *
336
+ * Omitted, or the basename itself, means the repo-root surface inside the ledger directory. A
337
+ * bare word names an area. A path ending in the surface basename names an area too, and routes
338
+ * to the same canonical file the bare word would. So does an area's own surface filename, so
339
+ * `tower-push` and `tower-push.BACKLOG.md` are one area rather than two.
340
+ *
341
+ * That last rule is why this takes `targets`. The argument goes through
342
+ * {@link normalizeSurfaceRef}, the same projection the rebuild uses to decide which entries
343
+ * belong to a surface, so the file written is always the file the projection matched. While the
344
+ * two disagreed, `remove <id> games/tower-push/BACKLOG.md` rebuilt the surface into a stray file
345
+ * and left the canonical one still carrying the entry it had just removed, at exit code 0.
346
+ *
347
+ * Anything else with a separator stays an explicit path, resolved against the repo root rather
348
+ * than the process cwd, so a hook invoked from a subdirectory writes where the caller meant. A
349
+ * literal path that escapes the repo falls back to the root surface, the way {@link ledgerDir}
350
+ * refuses an escaping `ledgers.dir`, since no ledger command has reason to write outside the
351
+ * repo it is recording.
352
+ *
353
+ * Lives here rather than in each script because the two ledgers diverged when they each owned a
354
+ * copy: one sent the bare basename to the repo root and the other to the ledger directory, so the
355
+ * same argument meant two different files.
356
+ */
357
+ export function resolveSurfaceArg(repoRoot, dir, basename, targets, arg) {
358
+ if (!arg || arg === basename)
359
+ return surfacePath(dir, basename, null);
360
+ if (!arg.includes('/')) {
361
+ const collapsed = collapseRepeatedSuffix(arg, basename);
362
+ return collapsed.endsWith(`.${basename}`)
363
+ ? resolve(dir, collapsed)
364
+ : surfacePath(dir, basename, collapsed);
365
+ }
366
+ const normalized = normalizeSurfaceRef(arg, basename, targets);
367
+ if (!normalized.includes('/'))
368
+ return resolve(dir, normalized);
369
+ const root = resolve(repoRoot);
370
+ const literal = resolve(root, arg);
371
+ return literal.startsWith(`${root}/`)
372
+ ? literal
373
+ : surfacePath(dir, basename, null);
374
+ }
375
+ /**
376
+ * The bare area name an `<area>` argument refers to, or null when {@link resolveSurfaceArg} would
377
+ * not resolve it against a per-target surface at all: the repo-root surface, or a literal path
378
+ * escape hatch, meaning a path with a separator that does not name a configured target's area.
379
+ *
380
+ * Mirrors {@link resolveSurfaceArg}'s branching on the same argument, so a name checked here is the
381
+ * name the surface would actually resolve to.
382
+ */
383
+ export function resolveAreaName(arg, basename, targets) {
384
+ if (!arg || arg === basename)
385
+ return null;
386
+ const normalized = normalizeSurfaceRef(arg, basename, targets);
387
+ if (normalized === basename)
388
+ return null;
389
+ if (normalized.includes('/'))
390
+ return null;
391
+ return normalized.endsWith(`.${basename}`)
392
+ ? normalized.slice(0, -(basename.length + 1))
393
+ : normalized;
394
+ }
395
+ /**
396
+ * The area names a list of surface files stands for, skipping the repo-root surface.
397
+ *
398
+ * Takes the file list rather than reading the directory, so this stays pure and the script that
399
+ * already knows its surfaces is the one that supplies them.
400
+ */
401
+ export function areaNamesOf(surfaceFiles, dir, basename, targets) {
402
+ const names = new Set();
403
+ for (const file of surfaceFiles) {
404
+ const area = resolveAreaName(surfaceRelFile(dir, file), basename, targets);
405
+ if (area !== null)
406
+ names.add(area);
407
+ }
408
+ return names;
409
+ }
410
+ /**
411
+ * Why this `<area>` argument cannot be used, or null when it names an area that exists.
412
+ *
413
+ * Every ledger command that takes an area calls this BEFORE it appends or renders anything. An area
414
+ * nothing knows about is not a harmless typo. It renders a surface file nobody asked for, and the
415
+ * ledger then carries entries filed against a surface no board is configured for, so the mistake
416
+ * surfaces one or more pushes later as `no board configured for surface "<area>.BACKLOG.md"`, far
417
+ * from the command that caused it.
418
+ *
419
+ * An area counts as existing if a target configures it OR a surface for it is already on disk.
420
+ * `existingAreas` is what carries the second half, and dropping it would break the fallback
421
+ * {@link normalizeSurfaceRef} exists for: an area whose target the config no longer lists still
422
+ * has its entries, and `render <that area>` has to keep resolving rather than being called a typo.
423
+ * A genuine typo matches neither half.
424
+ *
425
+ * Returns the message rather than exiting, because the two ledger scripts own their own exits. It
426
+ * returns the message rather than a boolean so the wording cannot drift between them, which is the
427
+ * same reason {@link resolveSurfaceArg} lives here.
428
+ */
429
+ export function unknownAreaMessage(arg, basename, targets, existingAreas) {
430
+ if (!arg)
431
+ return null;
432
+ const area = resolveAreaName(arg, basename, targets);
433
+ if (area === null || existingAreas.has(area))
434
+ return null;
435
+ if (targets.some((target) => target.name === area))
436
+ return null;
437
+ const valid = [
438
+ '(repo root)',
439
+ ...new Set([...targets.map((target) => target.name), ...existingAreas]),
440
+ ];
441
+ return (`Unknown area "${arg}". No target named "${area}" is configured in houserules.config.json, ` +
442
+ `and no surface for it exists yet.\n` +
443
+ `Valid areas: ${valid.join(', ')}.`);
444
+ }
445
+ /**
446
+ * Every surface the ledger implies, union'd with every surface already on disk.
447
+ *
448
+ * The `.jsonl` is the source of truth and the markdown is a generated view, so a freshly
449
+ * migrated ledger, one whose entries moved into `.claude/ledgers/` but was never rendered,
450
+ * has zero files on disk and would otherwise look empty to `list` and `render`. Deriving the
451
+ * surface set from the ledger's own recorded `file` values instead means a surface with no
452
+ * live entries still gets its header, and a surface every entry was removed from does not
453
+ * silently vanish just because nothing wrote it since.
454
+ *
455
+ * On-disk names go through the same projection as the recorded ones. A file left behind under
456
+ * a name that no longer projects to itself, such as a doubled `x.BACKLOG.md.BACKLOG.md`, would
457
+ * otherwise be rebuilt on every render with the content of the area it collapses to, leaving
458
+ * two files holding the same entries.
459
+ *
460
+ * @param recordedFiles The raw `file` value off every ledger record, in any order, possibly
461
+ * holding `undefined` for records that predate the field.
462
+ */
463
+ export function impliedSurfaceFiles(dir, basename, recordedFiles, targets) {
464
+ const names = new Set();
465
+ for (const recorded of recordedFiles) {
466
+ if (recorded)
467
+ names.add(normalizeSurfaceRef(recorded, basename, targets));
468
+ }
469
+ for (const file of findSurfaceFiles(dir, basename)) {
470
+ names.add(normalizeSurfaceRef(relative(dir, file), basename, targets));
471
+ }
472
+ return [...new Set([...names].map((name) => resolve(dir, name)))].sort();
473
+ }
474
+ /** Every rendered surface with this basename in the ledger directory. */
475
+ export function findSurfaceFiles(dir, basename) {
476
+ let entries;
477
+ try {
478
+ entries = readdirSync(dir, { withFileTypes: true });
479
+ }
480
+ catch (e) {
481
+ // A read failure looks identical to "nothing rendered yet" to this function's return
482
+ // shape, so the diagnostic goes to stderr, distinguishable from a fresh ledger directory.
483
+ console.error(`houserules: could not read ledger directory ${dir}: ${e.message}`);
484
+ return [];
485
+ }
486
+ return entries
487
+ .filter((e) => e.isFile() && (e.name === basename || e.name.endsWith(`.${basename}`)))
488
+ .map((e) => resolve(dir, e.name))
489
+ .sort();
490
+ }
491
+ /** `**Label:** value` pairs on one line, which may carry several joined by ` · `. */
492
+ function metadataOf(line) {
493
+ const pairs = [];
494
+ for (const segment of line.split(METADATA_JOIN)) {
495
+ const m = segment.trim().match(METADATA_LINE);
496
+ // METADATA_LINE has two non-optional capture groups, so a match always fills both.
497
+ if (m)
498
+ pairs.push([m[1], m[2].trim()]);
499
+ }
500
+ return pairs;
501
+ }
502
+ export function renderMetadata(fields) {
503
+ return Object.entries(fields)
504
+ .filter(([, v]) => v)
505
+ .map(([k, v]) => `**${k}:** ${v}`)
506
+ .join('\n');
507
+ }
508
+ /**
509
+ * Every entry in a rendered surface. A metadata line is consumed into `meta` rather than the
510
+ * body, and the first occurrence of a label wins, so prose below the header that happens to
511
+ * look like metadata cannot displace the real header value.
512
+ */
513
+ export function parseEntries(text) {
514
+ const entries = [];
515
+ let current = null;
516
+ for (const line of text.split('\n')) {
517
+ const m = line.match(ENTRY_HEAD);
518
+ if (m) {
519
+ if (current)
520
+ entries.push(current);
521
+ // ENTRY_HEAD has two non-optional capture groups, so a match always fills both.
522
+ current = { id: m[1], title: m[2], meta: {}, body: [] };
523
+ continue;
524
+ }
525
+ if (!current)
526
+ continue;
527
+ if (line.trim() === SEPARATOR) {
528
+ entries.push(current);
529
+ current = null;
530
+ continue;
531
+ }
532
+ const pairs = metadataOf(line);
533
+ if (pairs.length && pairs.some(([label]) => !(label in current.meta))) {
534
+ for (const [label, value] of pairs) {
535
+ if (!(label in current.meta))
536
+ current.meta[label] = value;
537
+ }
538
+ continue;
539
+ }
540
+ current.body.push(line);
541
+ }
542
+ if (current)
543
+ entries.push(current);
544
+ return entries.map((e) => ({ ...e, body: e.body.join('\n').trim() }));
545
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * What a checker reports, and how it prints.
3
+ *
4
+ * Two shapes already existed when this was written and neither was sufficient.
5
+ * `@houserules/api`'s `Finding` carries a level but no location, because a doctor check
6
+ * reports about the install rather than about a line. `design-checks.mts` carries a line
7
+ * but no level and no rule id, because it was written for one script that only ever had
8
+ * one severity. A checker that reports a rule-clause violation needs all three: the
9
+ * location so a reader can go there, the level so severity is not guessed, and the clause
10
+ * id so coverage can be verified per clause rather than per checker.
11
+ *
12
+ * This is deliberately NOT the api type. The payload is a copy target that runs on bare
13
+ * node in a user's repo, so it cannot import from a published package at runtime, and the
14
+ * two shapes answer different questions anyway.
15
+ */
16
+ /**
17
+ * `error` means the checker decided and a finding is a defect.
18
+ *
19
+ * `warn` means the checker found a CANDIDATE and a model still has to rule on it. This is
20
+ * the whole distinction between a mechanical clause and a hybrid one. A rule that says
21
+ * "past 20 to 30 lines, look again" produces candidates, not defects, and shipping those
22
+ * at `error` misreads the clause it is enforcing.
23
+ */
24
+ export type Level = 'error' | 'warn';
25
+ export interface Finding {
26
+ /**
27
+ * The clause this violates, not the checker that found it. Several checkers may report
28
+ * the same clause and one checker usually reports several, so keying on the checker
29
+ * makes coverage unverifiable.
30
+ */
31
+ rule: string;
32
+ level: Level;
33
+ /** Repo-relative. Absolute paths leak the author's home directory into shared output. */
34
+ file: string;
35
+ /** Null when the finding is about the file itself, such as a missing file. */
36
+ line: number | null;
37
+ msg: string;
38
+ }
39
+ /**
40
+ * A checker's whole result, including what it did not look at.
41
+ *
42
+ * `declined` generalises the scope note `design.mts` prints on every run. A checker that
43
+ * hides its own boundary is how a standard gets silently dropped: a reader sees a clean
44
+ * report and concludes the rule is satisfied, when the checker never examined the half
45
+ * that was broken. Every checker states what it skipped, every run, whether or not it
46
+ * found anything.
47
+ */
48
+ export interface Report {
49
+ findings: Finding[];
50
+ declined: string[];
51
+ }
52
+ export declare function emptyReport(): Report;
53
+ /**
54
+ * Sorts by file, then line, then rule. Null lines sort ahead of numbered ones, since a
55
+ * finding about the whole file belongs above findings inside it.
56
+ *
57
+ * Stable ordering is not cosmetic here. A checker that emits the same findings in a
58
+ * different order on two runs cannot be diffed between runs, and reproducibility is the
59
+ * property this whole layer exists to provide.
60
+ */
61
+ export declare function sortFindings(findings: Finding[]): Finding[];
62
+ /** True when anything in the report is a decided defect rather than a candidate. */
63
+ export declare function hasErrors(report: Report): boolean;
64
+ /**
65
+ * Exit 1 when the report carries a decided defect, otherwise 0.
66
+ *
67
+ * Warnings never move the exit code. A candidate list that failed a build would force
68
+ * every hybrid clause to become a gate it cannot honestly be.
69
+ */
70
+ export declare function exitCodeFor(report: Report): number;
71
+ /**
72
+ * One finding per line, `file:line LEVEL [rule] message`, then the declined list.
73
+ *
74
+ * The location leads so the line is clickable in a terminal. The declined section prints
75
+ * even when there are no findings, because that is exactly when a reader is most likely to
76
+ * conclude the rule is fully satisfied.
77
+ */
78
+ export declare function renderReport(report: Report): string;
@@ -0,0 +1,67 @@
1
+ /**
2
+ * What a checker reports, and how it prints.
3
+ *
4
+ * Two shapes already existed when this was written and neither was sufficient.
5
+ * `@houserules/api`'s `Finding` carries a level but no location, because a doctor check
6
+ * reports about the install rather than about a line. `design-checks.mts` carries a line
7
+ * but no level and no rule id, because it was written for one script that only ever had
8
+ * one severity. A checker that reports a rule-clause violation needs all three: the
9
+ * location so a reader can go there, the level so severity is not guessed, and the clause
10
+ * id so coverage can be verified per clause rather than per checker.
11
+ *
12
+ * This is deliberately NOT the api type. The payload is a copy target that runs on bare
13
+ * node in a user's repo, so it cannot import from a published package at runtime, and the
14
+ * two shapes answer different questions anyway.
15
+ */
16
+ export function emptyReport() {
17
+ return { findings: [], declined: [] };
18
+ }
19
+ /**
20
+ * Sorts by file, then line, then rule. Null lines sort ahead of numbered ones, since a
21
+ * finding about the whole file belongs above findings inside it.
22
+ *
23
+ * Stable ordering is not cosmetic here. A checker that emits the same findings in a
24
+ * different order on two runs cannot be diffed between runs, and reproducibility is the
25
+ * property this whole layer exists to provide.
26
+ */
27
+ export function sortFindings(findings) {
28
+ return [...findings].sort((a, b) => a.file.localeCompare(b.file) ||
29
+ (a.line ?? -1) - (b.line ?? -1) ||
30
+ a.rule.localeCompare(b.rule));
31
+ }
32
+ /** True when anything in the report is a decided defect rather than a candidate. */
33
+ export function hasErrors(report) {
34
+ return report.findings.some((finding) => finding.level === 'error');
35
+ }
36
+ /**
37
+ * Exit 1 when the report carries a decided defect, otherwise 0.
38
+ *
39
+ * Warnings never move the exit code. A candidate list that failed a build would force
40
+ * every hybrid clause to become a gate it cannot honestly be.
41
+ */
42
+ export function exitCodeFor(report) {
43
+ return hasErrors(report) ? 1 : 0;
44
+ }
45
+ function formatLocation(finding) {
46
+ return finding.line === null
47
+ ? finding.file
48
+ : `${finding.file}:${finding.line}`;
49
+ }
50
+ /**
51
+ * One finding per line, `file:line LEVEL [rule] message`, then the declined list.
52
+ *
53
+ * The location leads so the line is clickable in a terminal. The declined section prints
54
+ * even when there are no findings, because that is exactly when a reader is most likely to
55
+ * conclude the rule is fully satisfied.
56
+ */
57
+ export function renderReport(report) {
58
+ const lines = sortFindings(report.findings).map((finding) => `${formatLocation(finding)} ${finding.level.toUpperCase()} [${finding.rule}] ${finding.msg}`);
59
+ if (lines.length === 0)
60
+ lines.push('No findings.');
61
+ if (report.declined.length > 0) {
62
+ lines.push('', 'Not checked by this checker:');
63
+ for (const item of report.declined)
64
+ lines.push(` - ${item}`);
65
+ }
66
+ return lines.join('\n');
67
+ }