@sabaiway/agent-workflow-kit 10.0.0 → 10.2.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,310 @@
1
+ #!/usr/bin/env node
2
+ // The STATUS GRAMMAR of a queue row: what one row says about its own state, and the literal evidence
3
+ // for saying it. The DOCUMENT pass — which rows exist, which section they live in, what the caps say
4
+ // — is queue-audit.mjs, and the argv/fs half is queue-audit-cli.mjs. Split at the seam the source-size
5
+ // practice asks for: a module you can hold whole is the unit of review.
6
+ //
7
+ // Five classes, and the boundaries between them are deliberately conservative, because the consumer
8
+ // of a `terminal` verdict is a DELETION:
9
+ //
10
+ // live no status marker decides otherwise — the default, and what a queue should hold.
11
+ // terminal the row is DEAD — done, closed, superseded, moot, declined: a marker in the TITLE, or
12
+ // a marker OPENING a bold status line in the body (`**CLOSED 2026-07-20 …**`). The body
13
+ // decides when the title is silent — the real shape of a row that was closed in place.
14
+ // parked the row is FROZEN, not dead: `PARKED` / `STOPPED` carry a stated resume condition, so
15
+ // deleting one loses work that is only waiting. Reported, never deleted, never a refusal.
16
+ // record the row is not work at all: a TALLY counter or a SEQUENCING note.
17
+ // ambiguous the row declares two states, or names a status word outside a status position.
18
+ // REPORTED, never auto-deleted.
19
+ //
20
+ // A terminal WORD in ordinary prose is NOT a status: rows routinely cite a sibling that was CLOSED or
21
+ // explain why something was CUT, and reading that as the row's own state would delete live work. Only
22
+ // the title and a bold status line are status positions.
23
+ //
24
+ // Pure string functions. No IO, no argv, no side effects on import. Dependency-free, Node >= 22.
25
+
26
+ // The closed list the queue actually uses. `DONE` and `CLOSED` are the two fold-scope already knows
27
+ // (its CLOSED_MARKERS); the rest are the states this corpus grew on its own. The check mark is a
28
+ // marker in its own right because the file's DONE-entry convention leads with it.
29
+ export const TERMINAL_MARKERS = ['✅', 'DONE', 'CLOSED', 'RESOLVED', 'DECIDED', 'SUPERSEDED', 'MOOT', 'DECLINED'];
30
+
31
+ // FROZEN, not dead: each of these carries a stated condition under which the work resumes (measured:
32
+ // "costs nothing until one is adopted again", "do NOT open tranche 4", "do NOT schedule without
33
+ // recurring incidents"). They are classified apart precisely so a deletion pass cannot take them.
34
+ export const FROZEN_MARKERS = ['PARKED', 'STOPPED'];
35
+
36
+ // A title marker that declares the row still OPEN. Only these two: they are the ones the corpus
37
+ // writes deliberately, and a wider list would turn ordinary words into status.
38
+ export const LIVE_MARKERS = ['QUEUED', 'PENDING'];
39
+
40
+ // Not work: a counter and an ordering note. Matched at the START of the title only.
41
+ export const RECORD_PREFIXES = ['TALLY', 'SEQUENCING'];
42
+
43
+ export const CLASSES = ['live', 'terminal', 'parked', 'record', 'ambiguous'];
44
+
45
+ // The classes that still carry work, and therefore still cost a reader attention: both caps judge
46
+ // exactly these.
47
+ export const CARRY_WORK = new Set(['live', 'parked', 'ambiguous']);
48
+
49
+ export const DEFAULTS = { maxRows: 60, maxRowLines: 12 };
50
+
51
+ // A row is judged on the text it DECLARES, never on the text it QUOTES, and this is the ONE place
52
+ // that distinction is made. Every quotation this grammar can recognise is removed before any marker
53
+ // is looked for, and each is replaced by a SPACE so the tokens around it never become neighbours:
54
+ //
55
+ // inline code `` `DONE 2026-01-01` is parser input `` names a literal. Stripping the backticks and
56
+ // keeping the text turned a row ABOUT the parser into a closed row — a deletion.
57
+ // indented a body line indented past the row's own continuation (2 spaces here, plus Markdown's
58
+ // code block 4) is a code block, so ` **DONE 2026-02-01:** sample` is sample output, not this
59
+ // row's status.
60
+ //
61
+ // A fenced region is handled one level up, by the block scan, and reaches here as a `gaps` boundary.
62
+ // What remains is deliberately NOT exhaustive: this is a hand-written reader over a corpus, so the
63
+ // residue is stated in the contract rather than guessed at, and the classes it can still misread are
64
+ // reported (`ambiguous`), never deleted.
65
+ const INLINE_CODE = /`[^`\n]*`/g;
66
+ const CODE_INDENT = /^\s{6,}\S/;
67
+ const quoteFree = (line) => String(line ?? '').replace(/\r/g, '').replace(INLINE_CODE, ' ');
68
+ const judgeable = (line) => (CODE_INDENT.test(String(line ?? '')) ? '' : quoteFree(line));
69
+
70
+ // The TITLE is the row's first bold span — `- **… — queued 2026-08-26.** prose` — and it ENDS where
71
+ // that span closes, even when it wraps over several lines. Both halves matter: taking the whole first
72
+ // line would read a sibling named in the prose after the title (`Its sibling was CLOSED …`) as this
73
+ // row's own status, and taking only the first line would lose the marker of a title that wraps — the
74
+ // common shape here, since a named row puts its id and `queued <date>` on the second line. A row with
75
+ // no bold span falls back to its first line.
76
+ export const titleOf = (blockLines, gaps = new Set()) => {
77
+ // A title never closes ACROSS a code block: the fenced lines a row absorbs are elided from its
78
+ // lines, so without this bound an opener above a fence and a `:**` below it become adjacent and a
79
+ // title assembles itself out of two halves the document never joined.
80
+ const upTo = [...gaps].filter((at) => at >= 0).sort((a, b) => a - b)[0];
81
+ const reach = upTo === undefined ? blockLines.length : upTo + 1;
82
+ const span = (render) => {
83
+ const first = render(String(blockLines[0] ?? ''));
84
+ const joined = blockLines.slice(0, reach).map(render).join('\n');
85
+ const open = first.indexOf('**');
86
+ const close = open === -1 ? -1 : joined.indexOf('**', open + 2);
87
+ return {
88
+ raw: close === -1 ? first : joined.slice(open + 2, close),
89
+ endLine: close === -1 ? 0 : joined.slice(0, close).split('\n').length - 1,
90
+ };
91
+ };
92
+ const flatten = (raw) => raw.replace(/^\s*[-*]\s+/, '').replace(/[*_]/g, '').replace(/\s+/g, ' ').trim();
93
+ // TWO renderings of one title, and the split is the point. `text` is what a HUMAN reads in the
94
+ // manifest, so it keeps every word the row wrote — eliding quoted code there turned readable titles
95
+ // into gaps ("codex and") in the very document a deletion is driven by. `judged` is what the
96
+ // MARKERS are looked for in, with quotations removed, so a row that names a literal is never
97
+ // mistaken for a row that declares a state.
98
+ const display = span((line) => String(line ?? '').replace(/\r/g, ''));
99
+ const judged = span(quoteFree);
100
+ return { text: flatten(display.raw).replace(/`/g, ''), judged: flatten(judged.raw), endLine: display.endLine };
101
+ };
102
+
103
+ // A word-boundary match that survives punctuation the corpus writes (`— CLOSED 2026-08-21 ·`), and
104
+ // that never fires inside a longer word (`UNDECIDED`, `PARKED-ish`). The HYPHEN is a boundary that
105
+ // does NOT count: every row id here is a kebab slug, so `IS-A-CLOSED-LIST` carries the word CLOSED as
106
+ // part of a NAME, and reading that as the row's own status would delete live work (measured — it was
107
+ // the only false positive in the 272-row corpus). The check mark is not a word character, so it is
108
+ // matched literally.
109
+ //
110
+ // CASE is asymmetric, and the asymmetry is measured, not stylistic. A real status here is SHOUTED
111
+ // (`QUEUED` · `DONE` · `CLOSED` · `PARKED`), while the same words in lower case are ordinary prose:
112
+ // matching terminal markers case-insensitively flipped EIGHT live rows to terminal in one pass —
113
+ // "(decided 2026-07-22)", "…is DEFERRED until resolved", "the class gets asked for … done" — every
114
+ // one a false positive, every one a deletion. Live markers are the opposite: the corpus writes
115
+ // `queued 2026-08-26` in lower case, so a case-sensitive live marker never fires and the
116
+ // contradiction arm that PROTECTS a row goes dead. So: terminal and frozen are case-sensitive, live
117
+ // is not. The cost of the split is a non-standard lower-case dead row staying `live` — visible, and
118
+ // far cheaper than deleting work.
119
+ // ONE identifier-aware boundary, used by every marker test here: a marker glued to any identifier
120
+ // character — letter, DIGIT, underscore or hyphen — belongs to a NAME, not to a status. Measured
121
+ // misses when it was letters-and-hyphen only: `DONE2-STATE-IS-UNREACHABLE` and
122
+ // `CLOSED_LOOP-DESIGN-IS-UNDOCUMENTED` are live rows named after the thing they fix.
123
+ // A TOP-LEVEL list item the row grammar does not take: a `*` or `+` bullet — with content or EMPTY,
124
+ // since an empty one still opens a list whose indented content the audit would then never judge — or
125
+ // a `-` with nothing after it. Indented items are nested content of a row and are read as its body.
126
+ export const UNREAD_ITEM = /^(?:[*+](?:\s+\S|\s*$)|-\s*$)/;
127
+
128
+ const IDENT = '[A-Za-z0-9_-]';
129
+ const carries = (text, marker, { anyCase = false } = {}) =>
130
+ /^[A-Za-z]+$/.test(marker)
131
+ ? new RegExp(`(?<!${IDENT})${marker}(?!${IDENT})`, anyCase ? 'i' : '').test(text)
132
+ : text.includes(marker);
133
+
134
+ const markersIn = (text, list, options) => list.filter((marker) => carries(text, marker, options));
135
+
136
+ // A BOLD status line: `**CLOSED 2026-07-20 (…):** the story`. Anchored at the start of the line
137
+ // (indent allowed) so a bold phrase mid-sentence is never a status, and requiring the marker to open
138
+ // the bold span so `**Fix (small canon change):**` cannot become one.
139
+ // A bold status may WRAP: the opener sits on one line and the `:**` on the next — two rows of the
140
+ // live corpus are written that way, and a per-line matcher called both of them live, which is a
141
+ // false GREEN from the gate that authorises deletions. So the span is read across continuation
142
+ // lines, bounded so a `**` that never closes cannot swallow the rest of the row.
143
+ const BOLD_OPEN = /^\s*\*\*\s*(.*)$/;
144
+ const BOLD_SPAN_LINES = 4;
145
+
146
+ // A span never reaches ACROSS a code block. The fenced lines a row absorbs are elided from its
147
+ // lines, so without the gap set an opener above a fence and a `:**` below it become adjacent and
148
+ // assemble into one claim that the document never made.
149
+ const boldSpanAt = (blockLines, index, gaps = new Set()) => {
150
+ const first = BOLD_OPEN.exec(judgeable(blockLines[index]));
151
+ if (!first) return null;
152
+ let span = first[1];
153
+ for (let step = 0; step < BOLD_SPAN_LINES; step += 1) {
154
+ const close = span.indexOf('**');
155
+ if (close !== -1) return span.slice(0, close).replace(/:\s*$/, '');
156
+ const next = blockLines[index + step + 1];
157
+ if (next === undefined || gaps.has(index + step)) return null;
158
+ span += ` ${judgeable(next).trim()}`;
159
+ }
160
+ return null;
161
+ };
162
+ // The marker must OPEN the bold span, as a WHOLE token. A QUALIFIED closure closes a PART of the row,
163
+ // not the row: `**PART (2) IS CLOSED …**`, `**SECOND FACE CLOSED …**`, `**+ bare-lane DECIDED …**`,
164
+ // `**DISPOSITION DECIDED …**` all leave work behind, and five of the six body-decided rows in the live
165
+ // corpus were exactly that shape. The token boundary matters too — `**CLOSED-loop design:**` is a
166
+ // subheading about a loop, not a closure. A bare check mark with no word after it (`**✅ 2026-08-20:**`)
167
+ // IS a status: the corpus leads its done entries with it.
168
+ const LEAD_WORD = new RegExp(`^([A-Za-z]+)(?!${IDENT})`);
169
+ const DATE = /^\d{4}-\d{2}-\d{2}/;
170
+ // A real status carries its DATE, and that is measured, not stylistic: across the 272-row corpus the
171
+ // status forms are `DONE 2026-08-21 ·`, `CLOSED 2026-07-20 (…)`, `SUPERSEDED 2026-08-21 by the row
172
+ // above`, `PARKED 2026-08-21 by AD-105`, `RESOLVED 2026-08-25 —`; the same words in prose never do —
173
+ // `STOPPED. That is`, `PARKED rather than`, `RESOLVED; the npm-pack`, `SUPERSEDED by a`. Requiring
174
+ // the date is what keeps a row NAMED after the machinery it fixes (`CLOSED STATUS PARSER DROPS ROWS`,
175
+ // `**DONE criteria:**`) out of the deletion set. A marker without one is not ignored — it makes the
176
+ // row `ambiguous`, for a human.
177
+ // The date is ADJACENT to the marker. A 40-character window of arbitrary text between the two was
178
+ // measured wrong: `**DONE criteria due 2026-09-01:**` — a live row stating when its criteria are due
179
+ // — read as a closure, and this verdict authorises a DELETION. The only gap the corpus actually
180
+ // writes is a SECOND shouted status word introduced by `+`: `DONE + SHIPPED 2026-07-09`,
181
+ // `DONE + PUBLISHED 2026-08-25` (measured — those three rows and nothing else in 6900 lines). So the
182
+ // gap is exactly that, never prose: a `+` must introduce every extra word, which is what keeps
183
+ // `DONE criteria due <date>` and `DONE CRITERIA <date>` out of the deletion set.
184
+ const DATED_STATUS = /^(?:\s*\+\s*[A-Z][A-Z-]*)*\s*\d{4}-\d{2}-\d{2}/;
185
+
186
+ // The markers OPENING a span, as whole tokens. A leading check mark alone declares NOTHING: the
187
+ // corpus writes `**✅ ENTRY GATE OPEN:**` for a live gate, so the mark must be followed by a terminal
188
+ // word or by a date — the form its done entries actually use (`**✅ 2026-08-20 (AD-100):**`).
189
+ // `requireDate: false` answers the WEAKER question — does this span OPEN with a status word at all —
190
+ // which is what separates "no status here" from "a status word with no date beside it". The second
191
+ // is not silence: it is a row a human has to settle.
192
+ export const leadMarkers = (span, list = TERMINAL_MARKERS, { requireDate = true } = {}) => {
193
+ let rest = String(span).replace(/\r/g, '').trimStart();
194
+ const tick = rest.startsWith('✅');
195
+ if (tick) rest = rest.slice(1).trimStart();
196
+ const word = LEAD_WORD.exec(rest);
197
+ const named = word ? list.filter((m) => m === word[1]) : [];
198
+ if (named.length && (!requireDate || DATED_STATUS.test(rest.slice(word[1].length)))) {
199
+ return tick ? ['✅', ...named] : named;
200
+ }
201
+ // A BARE check mark declares nothing on its own — the corpus writes `**✅ ENTRY GATE OPEN …**` for
202
+ // a LIVE gate — so it counts only in its DATED form, and the weaker question never takes it.
203
+ // Measured: dropping that guard turned three live rows into ambiguous, this one among them.
204
+ if (!named.length && tick && list.includes('✅') && requireDate && DATE.test(rest)) return ['✅'];
205
+ return [];
206
+ };
207
+
208
+ // A STATUS sits at the head of the title or at the head of one of its segments — `✅ DONE 2026-…`,
209
+ // `A-ROW — ✅ CLOSED 2026-…`, `SUPERSEDED 2026-… by the row above`. A marker anywhere else is a
210
+ // MENTION: `THE CLOSED state drops live work` is a defect report about closed state, not a closed
211
+ // row, and deleting it would take live work. ONLY the documented separators split a segment — the
212
+ // spaced dash family the corpus writes its status after. A bare hyphen would cut every kebab id into
213
+ // pieces; a bracket or a colon would make `(CLOSED is an input)` and `note: DONE is a token` into
214
+ // status heads, which is a row ABOUT status words being deleted for containing them.
215
+ const SEGMENT_SPLIT = /\s+[—–]\s+/;
216
+ const statusMarkersIn = (title, list) => [
217
+ ...new Set(
218
+ String(title)
219
+ .split(SEGMENT_SPLIT)
220
+ .flatMap((segment) => leadMarkers(segment, list)),
221
+ ),
222
+ ];
223
+
224
+ const boldStatusMarkers = (blockLines, from, { list = TERMINAL_MARKERS, gaps, ...options } = {}) => {
225
+ for (let offset = from + 1; offset < blockLines.length; offset += 1) {
226
+ const span = boldSpanAt(blockLines, offset, gaps);
227
+ if (span === null) continue;
228
+ const found = leadMarkers(span, list, options);
229
+ if (found.length) return { markers: found, offset };
230
+ }
231
+ return null;
232
+ };
233
+
234
+ const evidenceOf = (parts) => parts.filter(Boolean).join(' + ');
235
+
236
+ // classifyRow(blockLines) -> { klass, evidence }. The order of the arms IS the rule: a record is
237
+ // judged before any status, a contradiction before the state it contradicts, and `live` is what
238
+ // survives when nothing else decided.
239
+ export const classifyRow = (blockLines, gaps) => {
240
+ const { judged: title, endLine } = titleOf(blockLines, gaps);
241
+ // The prefix must be a whole token: `TALLYING-FAILURES-HAS-NO-RUNG` and `SEQUENCING-BUG-IN-THE-
242
+ // DISPATCHER` are work, and a bare `startsWith` would have the checker demand their deletion.
243
+ const record = RECORD_PREFIXES.find((prefix) => new RegExp(`^${prefix}(?!${IDENT})`).test(title));
244
+ if (record) return { klass: 'record', evidence: `title opens with ${record}` };
245
+
246
+ // EVERY status of every class is gathered BEFORE anything is decided. Deciding as they were found
247
+ // made two states unreachable: a frozen title returned before the contradiction arms could see a
248
+ // live marker beside it, so `PARKED … — QUEUED …` read as simply parked, and the body was scanned
249
+ // for terminal markers only, so a dated `**PARKED 2026-08-21 …**` closing a row in place was not a
250
+ // state at all.
251
+ const titleFrozen = statusMarkersIn(title, FROZEN_MARKERS);
252
+ const titleTerminal = statusMarkersIn(title, TERMINAL_MARKERS);
253
+ const titleLive = markersIn(title, LIVE_MARKERS, { anyCase: true });
254
+ const bodyTerminal = boldStatusMarkers(blockLines, endLine, { gaps });
255
+ const bodyFrozen = boldStatusMarkers(blockLines, endLine, { gaps, list: FROZEN_MARKERS });
256
+ // The body declares LIVE too, and leaving it out of the table was the dangerous half: a row whose
257
+ // body said `**QUEUED 2026-08-20:**` and then `**CLOSED 2026-01-01:**` was read as simply closed —
258
+ // a contradiction handed to a deletion as a verdict. A live marker never needs its date here (the
259
+ // corpus writes `queued` in lower case, and the arm that reads it PROTECTS the row).
260
+ const bodyLive = boldStatusMarkers(blockLines, endLine, { gaps, list: LIVE_MARKERS, requireDate: false });
261
+ // A marker the title carries somewhere OTHER than a status head. It cannot decide the row, and it
262
+ // cannot be ignored either — a human settles it. The check mark STAYS in this path, and the
263
+ // asymmetry with the body side is measured, not an oversight: in a TITLE the corpus writes
264
+ // `✅ Plan 3 / 3 — …` as a done marker (ten such rows), so dropping it turned ten reported rows
265
+ // silent; in a BOLD BODY span it writes `**✅ ENTRY GATE OPEN …**` for a gate that OPENED. Same
266
+ // glyph, two positions, two meanings — and the position is what this module already reads.
267
+ const mentioned = markersIn(title, [...TERMINAL_MARKERS, ...FROZEN_MARKERS]).filter(
268
+ (marker) => !titleTerminal.includes(marker) && !titleFrozen.includes(marker),
269
+ );
270
+ if (!titleTerminal.length && !titleFrozen.length && mentioned.length) {
271
+ return { klass: 'ambiguous', evidence: `title mentions ${mentioned.join(', ')} outside a status position` };
272
+ }
273
+ // A row that declares two states declares none: it is REPORTED, and a human settles it. The title
274
+ // and the body are read into ONE table and reduced by CLASS, never by position — an earlier version
275
+ // let the title's own state hide the body's, so a terminal title above a `**PARKED <date>:**` body
276
+ // stayed terminal and kept authorising a deletion while the row declared two things. Two sightings
277
+ // of the SAME class are one state (a title and a body that agree do not contradict).
278
+ const sightings = [
279
+ titleTerminal.length && { klass: 'terminal', evidence: `title: ${titleTerminal.join(', ')}` },
280
+ titleFrozen.length && { klass: 'parked', evidence: `title: ${titleFrozen.join(', ')}` },
281
+ titleLive.length && { klass: 'live', evidence: `title: ${titleLive.join(', ')}` },
282
+ bodyTerminal && { klass: 'terminal', evidence: `body +${bodyTerminal.offset}: ${bodyTerminal.markers.join(', ')}` },
283
+ bodyFrozen && { klass: 'parked', evidence: `body +${bodyFrozen.offset}: ${bodyFrozen.markers.join(', ')}` },
284
+ bodyLive && { klass: 'live', evidence: `body +${bodyLive.offset}: ${bodyLive.markers.join(', ')}` },
285
+ ].filter(Boolean);
286
+ const declared = [...new Set(sightings.map((s) => s.klass))];
287
+ if (declared.length > 1) return { klass: 'ambiguous', evidence: evidenceOf(sightings.map((s) => s.evidence)) };
288
+ if (declared.length === 1 && declared[0] !== 'live') {
289
+ return { klass: declared[0], evidence: evidenceOf(sightings.map((s) => s.evidence)) };
290
+ }
291
+
292
+ // A bold body span that OPENS with a status word but carries no date beside it is the residue of
293
+ // the date rule, and silence is the wrong answer for it: `**DONE criteria due 2026-09-01:**` used
294
+ // to be read as a closure, and the fix must not turn it into "nothing to see". It is REPORTED as
295
+ // ambiguous — visible to a human, never deletable by a machine. Measured: with the bare-check-mark
296
+ // guard in place, zero rows in the live 314-row corpus and zero in the 62-row purge archive take
297
+ // this arm, so it closes a door without moving a single existing verdict.
298
+ const undated = boldStatusMarkers(blockLines, endLine, { gaps, requireDate: false })
299
+ ?? boldStatusMarkers(blockLines, endLine, { gaps, list: FROZEN_MARKERS, requireDate: false });
300
+ if (undated) {
301
+ return {
302
+ klass: 'ambiguous',
303
+ evidence: `body +${undated.offset}: ${undated.markers.join(', ')} with no date beside it`,
304
+ };
305
+ }
306
+
307
+ return { klass: 'live', evidence: 'no status marker' };
308
+ };
309
+
310
+ // The `[from, to)` body-line window a `--section` names: it opens after that heading and closes at
@@ -0,0 +1,164 @@
1
+ #!/usr/bin/env node
2
+ // The backlog queue as a CLASSIFIED corpus, not a prose pile.
3
+ //
4
+ // `docs/plans/queue.md` is the one long-lived surface in this family with no type, cap, rotation or
5
+ // exit event: rows accumulate, a closed row stays listed because its 26 lines of measurements have
6
+ // nowhere else to live, and a heading can say one thing while its body says another. The file's own
7
+ // header already asked for the discipline in prose ("a DONE entry is <=5 lines") and it did not hold.
8
+ // This module is the half prose cannot do — it says, per row and with the literal evidence, whether
9
+ // the row is still WORK.
10
+ //
11
+ // Four classes, and the boundaries between them are deliberately conservative, because the consumer
12
+ // of a `terminal` verdict is a DELETION:
13
+ //
14
+ // live no status marker decides otherwise — the default, and what a queue should hold.
15
+ // terminal the row is DEAD — done, closed, superseded, moot, declined: a marker in the TITLE, or
16
+ // a marker OPENING a bold status line in the body (`**CLOSED 2026-07-20 …**`). The body
17
+ // decides when the title is silent — the real shape of a row that was closed in place.
18
+ // parked the row is FROZEN, not dead: `PARKED` / `STOPPED` carry a stated resume condition, so
19
+ // deleting one loses work that is only waiting. Reported, never deleted, never a refusal.
20
+ // record the row is not work at all: a TALLY counter or a SEQUENCING note.
21
+ // ambiguous the row contradicts itself (a terminal AND a live marker in the title, or a bold
22
+ // terminal body under an explicitly QUEUED title). REPORTED, never auto-deleted.
23
+ //
24
+ // A terminal WORD in ordinary prose is NOT a status: rows routinely cite a sibling that was CLOSED or
25
+ // explain why something was CUT, and reading that as the row's own state would delete live work. Only
26
+ // the title and a bold status line are status positions.
27
+ //
28
+ // Markdown is read through the family's ONE block model (references/scripts/markdown-blocks.mjs) and
29
+ // the ONE bullet scan the other queue reader uses (fold-scope.mjs) — fences, CRLF, indented headings
30
+ // and the backtick-info-string rule are THEIR problem, never a second hand-rolled grammar here. A
31
+ // document either of them refuses is a loud refusal, never a silent empty read.
32
+ //
33
+ // Pure string functions plus a thin CLI. Read-only: it reads the file it is pointed at and writes
34
+ // nothing. Dependency-free, Node >= 22. No side effects on import.
35
+
36
+
37
+ import { tokenizeMarkdown, fail } from '../references/scripts/markdown-blocks.mjs';
38
+ import { bulletBlocks } from './fold-scope.mjs';
39
+ import { CARRY_WORK, CLASSES, DEFAULTS, UNREAD_ITEM, classifyRow, titleOf } from './queue-audit-rows.mjs';
40
+
41
+ // The row grammar is re-exported so one import names the whole reader: the CLI, the tests and any
42
+ // consumer ask this module, and the split into a rules half stays an implementation detail.
43
+ export { CLASSES, DEFAULTS, TERMINAL_MARKERS, FROZEN_MARKERS, LIVE_MARKERS, RECORD_PREFIXES, classifyRow, leadMarkers } from './queue-audit-rows.mjs';
44
+
45
+ // The `[from, to)` body-line window a `--section` names: it opens after that heading and closes at
46
+ // the next heading of the SAME level or higher, so a level-3 subheading stays inside. An absent
47
+ // section is a named refusal — auditing the whole file when the caller asked for one section would
48
+ // report rows the caller never meant to judge, and a deletion would follow.
49
+ // `frontLines` is not decoration: every line number this module reports is a FILE line, frontmatter
50
+ // included (the row manifest already adds it), so a refusal that named body-relative lines would send
51
+ // a reader to the wrong place in the very file it is refusing.
52
+ // ATX allows an optional CLOSING run of `#`, so `## Pending ##` and `## Pending` are the SAME
53
+ // heading. Comparing raw text made them two: the audit took one, and every row under the other left
54
+ // the domain silently — a section full of dead rows reported as zero rows and exit 0.
55
+ const canonicalHeading = (text) =>
56
+ String(text ?? '')
57
+ .replace(/\r/g, '')
58
+ .replace(/\s+#+\s*$/, '')
59
+ .replace(/\s+/g, ' ')
60
+ .trim();
61
+
62
+ const sectionWindow = (headings, lines, section, frontLines = 0) => {
63
+ if (!section) return { from: 0, to: lines.length };
64
+ const wanted = canonicalHeading(section);
65
+ const matches = headings.filter((heading) => canonicalHeading(heading.text) === wanted);
66
+ // A usage error, not a document refusal: what is wrong is the ARGUMENT, and the CLI contract
67
+ // promises 2 for that. AMBIGUITY refuses on the same footing as absence: taking the first of two
68
+ // same-named headings would leave every row under the second one outside the audit — invisible to
69
+ // the caps, absent from the report a deletion is driven by, and silently so.
70
+ if (matches.length === 0) throw fail(2, `no section heading "${wanted}" in the queue — the audit refuses to guess its domain.`);
71
+ if (matches.length > 1) {
72
+ throw fail(2, `${matches.length} section headings read "${wanted}" (lines ${matches.map((h) => frontLines + h.index + 1).join(', ')}) — the audit refuses to pick one and leave the rest unjudged.`);
73
+ }
74
+ const [open] = matches;
75
+ const next = headings.find((heading) => heading.index > open.index && heading.level <= open.level);
76
+ return { from: open.index + 1, to: next ? next.index : lines.length };
77
+ };
78
+
79
+ // auditQueue(text, { section, label }) -> { rows, counts }. Each row carries its 1-based FILE line
80
+ // (frontmatter included), the title as written, its class and the literal evidence for that class.
81
+ export const auditQueue = (text, { section = null, label = 'the queue' } = {}) => {
82
+ const { lines, headings, fencedLines, frontLines } = tokenizeMarkdown(String(text ?? ''), label);
83
+ const { from, to } = sectionWindow(headings, lines, section, frontLines);
84
+ // A fence CONTINUES a queue row rather than ending it, and the cap judges the row's PHYSICAL span.
85
+ // Both halves are the same defect: a row carrying a code block reported one line and hid whatever
86
+ // followed the fence — its length from the cap, and a closure from the classifier.
87
+ // A list item this grammar cannot read is a REFUSAL, never a silence. `*` and `+` open a list in
88
+ // every Markdown dialect and a bare `-` is an empty item; none of them is a row here, and dropping
89
+ // them made a section of dead work report "0 rows" and exit 0 — a gate answering about a domain it
90
+ // never looked at. The queue writes `-` rows; anything else is corrected by hand, not guessed at.
91
+ for (let index = from; index < to; index += 1) {
92
+ if (fencedLines.has(index) || !UNREAD_ITEM.test(lines[index])) continue;
93
+ throw fail(2, `line ${frontLines + index + 1} opens a list item this audit does not read ("${lines[index].trim().slice(0, 40)}") — a queue row is a "- " bullet, and judging around this one would report a domain that was never looked at.`);
94
+ }
95
+ const rows = bulletBlocks(lines, fencedLines, from, to, { fenceContinues: true }).map((block) => {
96
+ const { klass, evidence } = classifyRow(block.lines, block.gaps);
97
+ return {
98
+ line: frontLines + block.start + 1,
99
+ lines: block.span,
100
+ title: titleOf(block.lines, block.gaps).text,
101
+ klass,
102
+ evidence,
103
+ };
104
+ });
105
+ const counts = Object.fromEntries(CLASSES.map((klass) => [klass, rows.filter((row) => row.klass === klass).length]));
106
+ return { rows, counts, total: rows.length };
107
+ };
108
+
109
+ // checkQueue(text, options) -> { ok, problems, notes }. A problem is a REFUSAL and every one of them
110
+ // names a location: the family's bar is locations, never counts. An ambiguous row is a NOTE — it is
111
+ // exactly the case a human must settle, and failing on it would make the cap unpassable by anyone
112
+ // who did not already know the answer.
113
+ export const checkQueue = (text, options = {}) => {
114
+ const { maxRows = DEFAULTS.maxRows, maxRowLines = DEFAULTS.maxRowLines, label = 'the queue' } = options;
115
+ const { rows, counts, total } = auditQueue(text, { section: options.section ?? null, label });
116
+ const problems = [];
117
+ const notes = [];
118
+
119
+ for (const row of rows) {
120
+ if (row.klass === 'terminal' || row.klass === 'record') {
121
+ problems.push(
122
+ `${label}:${row.line}: a ${row.klass} row is still listed (${row.evidence}) — its story belongs to the ` +
123
+ `ADR or the changelog, and the row leaves the queue in the same commit: ${row.title.slice(0, 80)}`,
124
+ );
125
+ }
126
+ if (row.klass === 'ambiguous') {
127
+ notes.push(`${label}:${row.line}: ambiguous (${row.evidence}) — settle it by hand: ${row.title.slice(0, 80)}`);
128
+ }
129
+ if (row.klass === 'parked') {
130
+ notes.push(`${label}:${row.line}: parked (${row.evidence}) — frozen, not dead: ${row.title.slice(0, 80)}`);
131
+ }
132
+ if (CARRY_WORK.has(row.klass) && row.lines > maxRowLines) {
133
+ problems.push(
134
+ `${label}:${row.line}: the row is ${row.lines} lines, over the ${maxRowLines}-line cap — a row names the ` +
135
+ `work; the measurements belong to a record or an ADR: ${row.title.slice(0, 80)}`,
136
+ );
137
+ }
138
+ }
139
+
140
+ // Both caps count EVERY row that still carries work, frozen and ambiguous included. Counting only
141
+ // `live` would let the queue grow without limit through the Frozen bucket — moving a row there, or
142
+ // leaving it self-contradicting, would buy room the cap is there to deny.
143
+ const working = rows.filter((row) => CARRY_WORK.has(row.klass)).length;
144
+ if (working > maxRows) {
145
+ problems.push(
146
+ `${label}: ${working} rows carry work, over the ${maxRows}-row cap — a backlog nobody can read is a dump. ` +
147
+ 'Close, delete or fold rows before filing another.',
148
+ );
149
+ }
150
+
151
+ return { ok: problems.length === 0, problems, notes, counts, total };
152
+ };
153
+
154
+ // One tab-separated line per row: line, class, row-length, title. Deterministic and stable, so it can
155
+ // be diffed between runs and used as the manifest a deletion is driven by.
156
+ export const formatReport = (audit, { label = 'the queue' } = {}) => {
157
+ const head = [
158
+ `# queue-audit — ${label}`,
159
+ `# ${audit.total} rows: ${CLASSES.map((klass) => `${audit.counts[klass]} ${klass}`).join(' · ')}`,
160
+ '# line\tclass\tlines\ttitle\tevidence',
161
+ ];
162
+ const body = audit.rows.map((row) => [row.line, row.klass, row.lines, row.title, row.evidence].join('\t'));
163
+ return [...head, ...body].join('\n');
164
+ };
@@ -43,7 +43,17 @@ const dirOf = (rel) => rel.slice(0, rel.lastIndexOf('/'));
43
43
  const leafOf = (rel) => rel.slice(rel.lastIndexOf('/') + 1);
44
44
  const bare = (rel) => (rel.endsWith('/') ? rel.slice(0, -1) : rel);
45
45
  const lineCount = (text) => text.replace(/\n$/, '').split('\n').length;
46
- const occurrences = (text, needle) => text.split(needle).length - 1;
46
+ // A marker is counted as a WHOLE ordinal, never as a prefix of a longer one. A plain substring count
47
+ // makes `spec:…/S1` occur twice the moment `spec:…/S11` is written in the same file — so a store
48
+ // that reaches ten scenarios starts refusing bindings that are perfectly correct, and the refusal
49
+ // names the wrong scenario. Measured here at S11.
50
+ const occurrences = (text, needle) => {
51
+ let found = 0;
52
+ for (let at = text.indexOf(needle); at !== -1; at = text.indexOf(needle, at + needle.length)) {
53
+ if (!/[0-9]/.test(text[at + needle.length] ?? '')) found += 1;
54
+ }
55
+ return found;
56
+ };
47
57
  // Containment is a question about path COMPONENTS, and only the platform's own path model answers
48
58
  // it. A textual prefix test reads "/repo\outside" as a child of "/repo" on a POSIX host — where the
49
59
  // backslash is an ordinary filename character — and it mis-reads a filesystem root ("/" or "C:\")