fwdloop 0.23.0 → 0.25.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.
Files changed (71) hide show
  1. package/bin/fwdloop +62 -32
  2. package/package.json +1 -1
  3. package/src/ask.js +15 -1
  4. package/src/attemptdiff.js +118 -0
  5. package/src/audit-fold.js +2 -0
  6. package/src/authoring.js +32 -2
  7. package/src/cited-record.js +3 -22
  8. package/src/cited-source.js +5 -6
  9. package/src/citedwords.js +36 -2
  10. package/src/config.js +5 -1
  11. package/src/diary.js +21 -17
  12. package/src/drafter.js +6 -2
  13. package/src/flowmodel.js +52 -28
  14. package/src/keysfile.js +1 -1
  15. package/src/launcher.js +552 -0
  16. package/src/learn.js +952 -0
  17. package/src/learnstore.js +348 -0
  18. package/src/line-checks.js +55 -0
  19. package/src/model-step.js +2 -0
  20. package/src/opener.js +33 -0
  21. package/src/pagedry.js +3 -4
  22. package/src/pagefetch.js +9 -2
  23. package/src/pagerules.js +28 -5
  24. package/src/panel/author.js +2 -0
  25. package/src/panel/authorflows.js +9 -9
  26. package/src/panel/authorresume.js +4 -3
  27. package/src/panel/data.js +63 -14
  28. package/src/panel/index.html +162 -16
  29. package/src/panel/result.js +7 -12
  30. package/src/panel/server.js +53 -5
  31. package/src/panel/settings.js +4 -18
  32. package/src/panel/spawn.js +0 -9
  33. package/src/prompts.js +33 -0
  34. package/src/redact.js +6 -6
  35. package/src/runfile.js +60 -0
  36. package/src/runner.js +144 -33
  37. package/src/sheet-record.js +15 -35
  38. package/src/sheetblock.js +3 -3
  39. package/src/sheetrun.js +6 -6
  40. package/src/summary-words.js +13 -5
  41. package/src/thinking.js +11 -0
  42. package/src/tty-colour.js +29 -0
  43. package/types/ask.d.ts +7 -2
  44. package/types/attemptdiff.d.ts +38 -0
  45. package/types/cited-record.d.ts +0 -2
  46. package/types/citedwords.d.ts +14 -0
  47. package/types/diary.d.ts +2 -5
  48. package/types/drafter.d.ts +6 -1
  49. package/types/flowmodel.d.ts +37 -20
  50. package/types/keysfile.d.ts +7 -0
  51. package/types/launcher.d.ts +307 -0
  52. package/types/learn.d.ts +576 -0
  53. package/types/learnstore.d.ts +168 -0
  54. package/types/line-checks.d.ts +26 -0
  55. package/types/opener.d.ts +12 -0
  56. package/types/pagerules.d.ts +7 -0
  57. package/types/panel/author.d.ts +2 -0
  58. package/types/panel/data.d.ts +2 -1
  59. package/types/panel/result.d.ts +2 -4
  60. package/types/panel/server.d.ts +24 -3
  61. package/types/panel/settings.d.ts +2 -2
  62. package/types/panel/spawn.d.ts +0 -6
  63. package/types/prompts.d.ts +14 -0
  64. package/types/runfile.d.ts +48 -0
  65. package/types/runner.d.ts +14 -5
  66. package/types/sheet-record.d.ts +0 -2
  67. package/types/sheetblock.d.ts +2 -2
  68. package/types/sheetrun.d.ts +1 -1
  69. package/types/summary-words.d.ts +2 -1
  70. package/types/thinking.d.ts +11 -0
  71. package/types/tty-colour.d.ts +33 -0
package/src/learn.js ADDED
@@ -0,0 +1,952 @@
1
+ // borrowed-from: bareloop src/learn.js@v0.47.0 (66dc2b0)
2
+ // Adaptations: B1 (F79) flaggedText returns any non-empty trimmed line instead of null; redactSecrets imported from ./redact.js; line 17 names bareloop's proofs without its scratch path (E1 guard, test/m4d-am6-e.test.js); M8 am2 line 2 + am3 (buildCards push, src/learn.js:469): the too-thin drop applies to FIXED cards only, a step red on every try (NEVER FIXED) is kept and `thin` counts FIXED cards only; M8 am2 line 3 (hintText, src/learn.js:832): a What-changed line over 150 characters is left out whole, never cut; M8 am2 line 4 (hintText, src/learn.js:829): no "Fix touched" line is printed (fixTouched stays on the card and in the ledger; parseHintBlock unchanged, its touched field now always null for new text). Nothing else changed.
3
+ // Cross-run learnings, CODE ONLY (ITEM33-BUILD.md "Addendum 2026-10-22 (rev 2)"; hamr's RULING 1: no model call
4
+ // anywhere in learnings — not to label, fold, rephrase, rank, judge or render). A lesson is a HINT made entirely by
5
+ // code from a run's own record: every field below is COPIED from the spine / gate audit, never written by a model.
6
+ //
7
+ // This module is PURE: no file IO, no clock reads (the caller injects `now`), and it imports nothing that can reach
8
+ // a provider (a static test walks its whole import closure). The thin reader/writer and the run-end call live in
9
+ // src/learnstore.js.
10
+ //
11
+ // Shape of the whole thing:
12
+ // buildCards one run's spine (+ gate audit) -> captioned cards (FIXED / NEVER FIXED), minus noise, suspect, thin
13
+ // foldCards when are two cards one lesson (same job + check + a shared error kind + 60% token overlap)
14
+ // countLedger fold a run's cards into the ONE ledger (+1 per run per row), climbing, decay
15
+ // renderHints the one function that turns the ledger into the block the PLANNER reads (2,000 chars, one render)
16
+ //
17
+ // Graduated from bareloop's own proofs (pocA2 candidates, pocC cards, pocE2 fold) as a REWRITE.
18
+ // The 60% threshold is FITTED on known cards (a fit, not a proof; the unseen-card proof is OPEN 2).
19
+
20
+ import { redactSecrets } from './redact.js';
21
+
22
+ // ── constants (every number here is a ruling, not a tuning knob) ─────────────────────────────────
23
+ /** The block the planner reads is never longer than this many characters (RULING 7). */
24
+ export const HINT_CHARS_MAX = 2000;
25
+ /** MEMORY filter only (hamr 2026-10-23): a row untouched this long is not handed to the planner. The ledger keeps every row. */
26
+ export const DECAY_DAYS = 56;
27
+ /** A rubric lesson waits this long for the human Accept, then is dropped uncounted (ruling 7, = the door TTL). */
28
+ export const PENDING_DAYS = 60;
29
+ /** Fold threshold on flagged-text token overlap (FITTED on 87 known cards — see section 1 of the addendum). */
30
+ export const JACCARD_MIN = 0.6;
31
+ /** Climbing: this many distinct workflows on one place -> place; this many distinct places -> user. */
32
+ export const CLIMB_AT = 3;
33
+ /** How many "It said" lines a card keeps. */
34
+ export const SAID_LINES = 3;
35
+ /** CHECK-SUSPECT cards are listed (not folded); the list keeps this many newest. */
36
+ export const SUSPECT_KEEP = 100;
37
+
38
+ const DAY_MS = 86_400_000;
39
+
40
+ /**
41
+ * The no-suppressions tags an error kind may take (the closed list of `suppressions[].id` of the TYPES genre in
42
+ * src/authoring.js; a test fails if the two drift apart). Anything else in a bracket is NOT a kind.
43
+ */
44
+ export const ALLOWED_KINDS = Object.freeze([
45
+ 'ts-ignore', 'ts-expect-error', 'ts-nocheck', 'eslint-disable', 'any', 'any-star', 'cast', 'ignore', 'noqa', 'mypy-disable',
46
+ ]);
47
+
48
+ // ── small text helpers ───────────────────────────────────────────────────────────────────────────
49
+ /** @param {unknown} v @returns {v is string} */
50
+ const isStr = (v) => typeof v === 'string' && v !== '';
51
+ /** @template T @param {T[]} a @returns {T[]} */
52
+ const uniq = (a) => [...new Set(a)];
53
+
54
+ /** Path prefixes of a patient / worktree / hidden-git tree: stripped from every quote so a card names `src/a.js`. */
55
+ // The two leading lookarounds on the first two add no match and drop none. A start that directly follows a whole path segment ("/seg") is covered by the
56
+ // start at that segment's "/" (the chain reads "/seg" and goes on to the same end), so it is skipped - unless that "/" is the last character of a
57
+ // previous match's tail, which the global scan has already consumed (the inner lookbehind). Without them a long "/a/a/a/..." with no marker is quadratic.
58
+ const PREFIXES = [
59
+ /(?=\/)(?<!(?<!\/bareloop-patients\/[^/\s]+)\/[\w.@-]+)(?:\/[\w.@-]+)*\/bareloop-patients\/[^/\s]+\//g,
60
+ /(?:(?=\/)|(?=\.bareloop\/wt\/))(?<!(?<!\.bareloop\/wt\/[^/\s]+)\/[\w.@-]+)(?:\/[\w.@-]+)*\.bareloop\/wt\/[^/\s]+\//g,
61
+ /(?:\.\/)?out\/source-[^/\s]+\/tree\//g,
62
+ ];
63
+
64
+ /**
65
+ * Mask secrets and strip the working-tree prefix from a text. Pure.
66
+ * @param {string} text @param {string|null} workdir
67
+ * @returns {string}
68
+ */
69
+ export function cleanText(text, workdir) {
70
+ let s = redactSecrets(text);
71
+ if (workdir) s = s.split(`${workdir}/`).join('');
72
+ for (const r of PREFIXES) s = s.replace(r, '');
73
+ return s;
74
+ }
75
+
76
+ /**
77
+ * A card/audit path made relative to the run's tree, or null when it is not inside it. The workdir is the
78
+ * authority; the patient-prefix shapes are the fallback for a spine read without one.
79
+ * @param {string} abs @param {string|null} workdir
80
+ * @returns {string|null}
81
+ */
82
+ export function relPath(abs, workdir) {
83
+ if (typeof abs !== 'string') return null;
84
+ if (workdir && abs.startsWith(`${workdir}/`)) return abs.slice(workdir.length + 1);
85
+ let s = abs;
86
+ for (const r of PREFIXES) s = s.replace(r, '');
87
+ return s.startsWith('/') ? null : s;
88
+ }
89
+
90
+ /**
91
+ * Cut at a word / sentence edge, never mid-word where avoidable. Whitespace collapsed.
92
+ * @param {unknown} text @param {number} n @returns {string}
93
+ */
94
+ export function cutText(text, n) {
95
+ const s = String(text ?? '').replace(/\s+/g, ' ').trim();
96
+ if (s.length <= n) return s;
97
+ const sl = s.slice(0, n - 1);
98
+ const sp = sl.lastIndexOf(' ');
99
+ return `${(sp >= n * 0.5 ? sl.slice(0, sp) : sl).replace(/[\s,;:]+$/, '')}…`;
100
+ }
101
+
102
+ /**
103
+ * Deep-redact every string of a plain JSON value through the ONE secret inventory (a secret in a person's repo must
104
+ * not enter an append-only record). Pure; returns a new value.
105
+ * @template T @param {T} v @returns {T}
106
+ */
107
+ export function redactDeep(v) {
108
+ if (typeof v === 'string') return /** @type {any} */ (redactSecrets(v));
109
+ if (Array.isArray(v)) return /** @type {any} */ (v.map((x) => redactDeep(x)));
110
+ if (v && typeof v === 'object') {
111
+ /** @type {Record<string, any>} */
112
+ const o = {};
113
+ for (const [k, x] of Object.entries(v)) o[k] = redactDeep(x);
114
+ return /** @type {any} */ (o);
115
+ }
116
+ return v;
117
+ }
118
+
119
+ // ── error kinds, flagged text, tokens (pocE2 keyOf / stripFlag, ported) ─────────────────────────
120
+ /** `any` inside a `{...}` JSDoc type position: a real type use, not prose. */
121
+ function anyInBrace(/** @type {string} */ t) {
122
+ let d = 0;
123
+ const re = /[{}]|\bany\b/g;
124
+ let m;
125
+ while ((m = re.exec(t))) {
126
+ if (m[0] === '{') d += 1;
127
+ else if (m[0] === '}') d = Math.max(0, d - 1);
128
+ else if (d > 0) return true;
129
+ }
130
+ return false;
131
+ }
132
+
133
+ /**
134
+ * The flagged text of ONE quote line (wrapper stripped), or null when the line is not a flagged line.
135
+ * Flagged lines: `... added <id> - <text>` and `close: [<id>] <file>:<line>: <text>` (id in the allowed list), and
136
+ * lines with `error TS<digits>:` or `error:`.
137
+ * @param {string} line @returns {string|null}
138
+ */
139
+ export function flaggedText(line) {
140
+ let am = line.match(/: added ([a-z-]+) [—-] (.*)$/);
141
+ if (am && ALLOWED_KINDS.includes(am[1])) return am[2];
142
+ am = line.match(/^close:\s+\[([a-z-]+)\]\s+\S+?:\d+: (.*)$/);
143
+ if (am && ALLOWED_KINDS.includes(am[1])) return am[2];
144
+ if (/\berror TS\d+:|\berror:/.test(line)) {
145
+ return line.replace(/^.*?\berror TS\d+:/, '').replace(/^.*?\berror:/, '').replace(/\[[a-z]+(?:-[a-z]+)*\]\s*$/, '');
146
+ }
147
+ // B1 (F79): a fwdloop gap line IS the check's red line, so any non-empty line is flagged text.
148
+ return line.trim() !== '' ? line.trim() : null;
149
+ }
150
+
151
+ /**
152
+ * The error-kind set of a quote: TS codes; `[id]` of `added <id>` and `close: [id]` lines; a mypy trailing bracket
153
+ * code; empty -> `other`. Also the files named, the first symbol, and whether the card is CHECK-SUSPECT.
154
+ * @param {string} text the (path-stripped) quote @param {string} [fullGap] the whole gap, for the suspect read
155
+ * @returns {{kinds: string[], files: string[], symbol: string|null, suspect: boolean}}
156
+ */
157
+ export function errorKinds(text, fullGap = text) {
158
+ const kinds = [...text.matchAll(/\bTS\d+\b/g)].map((m) => m[0]);
159
+ for (const line of text.split('\n')) {
160
+ let am = line.match(/: added ([a-z-]+) [—-] (.*)$/);
161
+ if (!am) am = line.match(/^close:\s+\[([a-z-]+)\]\s+\S+?:\d+: (.*)$/);
162
+ if (am && ALLOWED_KINDS.includes(am[1])) kinds.push(`[${am[1]}]`);
163
+ if (/\berror:/.test(line)) {
164
+ const bm = line.match(/\[([a-z]+(?:-[a-z]+)*)\]\s*$/);
165
+ if (bm) kinds.push(`[${bm[1]}]`);
166
+ }
167
+ }
168
+ // CHECK-SUSPECT: a no-suppressions hit on `any`/`any-star` whose flagged text sits on a prose comment, not on a JSDoc
169
+ // type position. Read over the WHOLE gap (the quote is only a display cut), so a prose hit past the cut still counts.
170
+ let suspect = false;
171
+ for (const line of fullGap.split('\n')) {
172
+ let am = line.match(/: added ([a-z-]+) [—-] (.*)$/);
173
+ if (!am) am = line.match(/^close:\s+\[([a-z-]+)\]\s+\S+?:\d+: (.*)$/);
174
+ if (am && (am[1] === 'any' || am[1] === 'any-star') && /^(\/\/|\/\*|\*|#)/.test(am[2].trim()) && !anyInBrace(am[2])) suspect = true;
175
+ }
176
+ const kindSet = uniq(kinds).sort();
177
+ if (!kindSet.length) kindSet.push('other');
178
+ const files = uniq([...text.matchAll(PATH_RE)].map((m) => m[0].replace(/^\.\//, ''))).sort();
179
+ const sm = text.match(/(?:Variable|Parameter|Property) '([^']+)'/) || text.match(/Name "([^"]+)"/) || text.match(/'([^']+)' is of type/);
180
+ return { kinds: kindSet, files, symbol: sm ? sm[1] : null, suspect };
181
+ }
182
+
183
+ /**
184
+ * The token set of a quote's flagged lines: lowercase runs of `[a-z0-9_]` of length >= 2, union over flagged lines.
185
+ * File paths, line numbers, `added <id> -`, `error TS<n>:` and the trailing mypy code are already stripped.
186
+ * @param {string} text @returns {string[]} sorted
187
+ */
188
+ export function flaggedTokens(text) {
189
+ const s = new Set();
190
+ for (const line of text.split('\n')) {
191
+ const t = flaggedText(line);
192
+ if (t === null) continue;
193
+ for (const m of t.toLowerCase().matchAll(/[a-z0-9_]{2,}/g)) s.add(m[0]);
194
+ }
195
+ return [...s].sort();
196
+ }
197
+
198
+ // ── cards ────────────────────────────────────────────────────────────────────────────────────────
199
+ /**
200
+ * @typedef {object} Card
201
+ * @property {string} id `<runid>:<check>:<fixed|stuck>`
202
+ * @property {string} runid
203
+ * @property {string} at the run's end (ISO)
204
+ * @property {string} date YYYY-MM-DD of `at`
205
+ * @property {string} job the workflow key
206
+ * @property {string|null} model
207
+ * @property {string} check the check / close stage name
208
+ * @property {'FIXED'|'NEVER_FIXED'} kind
209
+ * @property {string} goal Job (as written), cut
210
+ * @property {string|null} stepId
211
+ * @property {string|null} stepAction Step (as planned), cut
212
+ * @property {string|null} meaning the check's own catalogue sentence (code-owned)
213
+ * @property {string[]} said It said: <= 3 lines, paths and prefixes stripped
214
+ * @property {number} saidMore lines left out
215
+ * @property {string[]} kinds error kinds, sorted; ['other'] when none
216
+ * @property {string[]} files files the quote names, sorted
217
+ * @property {string|null} symbol
218
+ * @property {string[]} tokens the flagged-text token set, sorted
219
+ * @property {string|null} nextCheck the next failing check after this moment, if any
220
+ * @property {string} ended how the run ended (job-end outcome, or its escalation word)
221
+ * @property {string[]} fixTouched files written by the passing try (the try that followed the red, for NEVER FIXED)
222
+ * @property {{files: {path: string, diff: string, truncated: boolean, cutLines?: number}[], binary: string[], truncated: boolean}|null} whatChanged
223
+ * the passing try's attempt-diff (FIXED only), as the spine capped it
224
+ * @property {string} key the one-line machine key
225
+ */
226
+
227
+ /**
228
+ * The one-line machine key of a card. Line numbers never appear in it.
229
+ * @param {{id: string, job: string, check: string, kinds: string[], files: string[], model: string|null, runid: string, date: string}} c
230
+ * @returns {string}
231
+ */
232
+ export function cardKey(c) {
233
+ return `card=${c.id} job=${c.job} check=${c.check} kinds=${c.kinds.join(',')} file=${c.files[0] ?? '-'} model=${c.model ?? '-'} run=${c.runid} date=${c.date}`;
234
+ }
235
+
236
+ /** the check name inside a gap text */
237
+ const nameOf = (/** @type {string} */ g) => (g.match(/check "([^"]+)"/)?.[1] ?? g.match(/close stage "([^"]+)"/)?.[1] ?? 'close');
238
+ const CODE = /\bTS\d+\b|\[[a-z][a-z-]+\]|\bE[A-Z]{2,}\b|\bERR_[A-Z_0-9]+\b/g;
239
+
240
+ /**
241
+ * The lines of a gap a card quotes: lines that carry a path:line or an error code come first, accumulated up to
242
+ * ~250 characters (the cut the fold was fitted on). Pure.
243
+ * @param {string} gap @returns {string[]}
244
+ */
245
+ export function quoteLines(gap) {
246
+ const ls = gap.split('\n').filter((l) => l.trim());
247
+ if (!ls.length) return [];
248
+ const pri = ls.filter((l) => /\.\w+[:(]\d+/.test(l) || (l.match(CODE) || []).length);
249
+ const pick = pri.length ? pri : ls;
250
+ /** @type {string[]} */
251
+ const out = [];
252
+ let len = 0;
253
+ for (const l of pick) {
254
+ if (len + l.length + 1 > 250) break;
255
+ out.push(l);
256
+ len += l.length + 1;
257
+ }
258
+ if (!out.length) out.push(pick[0].slice(0, 250));
259
+ return out;
260
+ }
261
+
262
+ /** terminal words that mean the run ended well */
263
+ const isGreen = (/** @type {unknown} */ o) => o === 'green' || o === 'already-green';
264
+ /** escalation categories that make a run NOISE: the instrument, not the work, failed */
265
+ const NOISE_CATEGORIES = new Set(['provider-red', 'close-crashed']);
266
+
267
+ /**
268
+ * @typedef {object} CardBuild
269
+ * @property {Card[]} cards foldable cards (FIXED and NEVER FIXED), suspect and too-thin removed
270
+ * @property {Card[]} suspect CHECK-SUSPECT cards: listed, never folded
271
+ * @property {number} thin TOO-THIN count of FIXED cards only (M8 am3): no error kind and no fix files; a NEVER FIXED card is never thin
272
+ * @property {string|null} noise why the whole run was set aside (provider-red, close-crashed, worker-crash, no-close-spoke, no-job-end), else null
273
+ */
274
+
275
+ /**
276
+ * Turn one run's record into cards. Every field is COPIED from the spine / gate audit; nothing is generated.
277
+ *
278
+ * Candidates: FIXED = a check red, then the SAME check passes later in the same run; NEVER FIXED = a check still red
279
+ * at run end. At most one of each per check per run (the last red before the pass; the last red). Excluded, counted:
280
+ * noise runs, CHECK-SUSPECT, TOO-THIN.
281
+ *
282
+ * Written files come from `attempt-diff` events (rubric `output/steps/<n>.json` included: the diff force-adds the
283
+ * fence) and the REAL gate audit's allow write/edit rows relative to `workdir` — never `git status`, and never a
284
+ * reader that drops a path it cannot place under a known patient prefix (the POC defect: a rubric job's writes read
285
+ * as none).
286
+ * `questions` is the check catalogue (stage name -> plain question, src/stagewords.js) the caller resolved from the signed
287
+ * spec; a check with none reads `(not in the record)`.
288
+ * @param {{runid: string, events: any[], audit?: any[]|null, workdir?: string|null, spec?: any, model?: string|null, questions?: Map<string, string|null>}} o
289
+ * @returns {CardBuild}
290
+ */
291
+ export function buildCards({ runid, events, audit = null, workdir = null, spec = null, model = null, questions = new Map() }) {
292
+ const ev = (Array.isArray(events) ? events : []).filter((e) => e && typeof e === 'object');
293
+ /** @type {CardBuild} */
294
+ const out = { cards: [], suspect: [], thin: 0, noise: null };
295
+ const jobEnd = ev.findLast((e) => e.type === 'job-end') ?? null;
296
+ if (!jobEnd) { out.noise = 'no-job-end'; return out; }
297
+ const jobStart = ev.find((e) => e.type === 'job-start' && isStr(e.goal)) ?? ev.find((e) => e.type === 'job-start') ?? null;
298
+ const job = isStr(spec?.job) ? spec.job : (isStr(jobStart?.job) ? jobStart.job : null);
299
+ if (job === null) { out.noise = 'no-job-start'; return out; }
300
+ const runModel = model ?? (isStr(jobStart?.model) ? jobStart.model : null);
301
+ const at = isStr(jobEnd.ts) ? jobEnd.ts : '';
302
+
303
+ // ── the walk: stage verdicts, red moments, red->pass pairs (pocA2, indexes instead of timestamps) ──
304
+ /** @type {Map<string, string>} */ const verdict = new Map();
305
+ /** @type {Map<string, any>} */ const gaps = new Map();
306
+ /** @type {Map<string, any>} */ const pend = new Map();
307
+ /** @type {Map<string, {red: any, pass: {i: number, note: string|null}}>} */ const pairs = new Map();
308
+ /** @type {{i: number, check: string}[]} */ const reds = [];
309
+ /** @type {[number, any[]][]} */ const plans = [];
310
+ /** @type {number[]} */ const iters = [];
311
+ let curStep = null;
312
+ let inFix = false;
313
+ for (let i = 0; i < ev.length; i += 1) {
314
+ const e = ev[i];
315
+ if (e.type === 'plan-accepted' && Array.isArray(e.plan?.steps)) plans.push([i, e.plan.steps]);
316
+ if (e.type === 'step-start') { curStep = isStr(e.step) ? e.step : null; inFix = false; }
317
+ if (e.type === 'fix-loop') inFix = true;
318
+ if (e.type === 'iteration-start') iters.push(i);
319
+ const sat = (/** @type {string} */ name, /** @type {unknown} */ note) => {
320
+ const g0 = pend.get(name);
321
+ if (g0) { pairs.set(name, { red: g0, pass: { i, note: isStr(note) ? note : null } }); pend.delete(name); }
322
+ };
323
+ const red = (/** @type {string} */ name, /** @type {any} */ g) => { pend.set(name, { ...g, i }); reds.push({ i, check: name }); };
324
+ if (e.type === 'check-run' && isStr(e.name)) {
325
+ verdict.set(e.name, e.verdict);
326
+ if (e.verdict === 'satisfied') sat(e.name, null);
327
+ }
328
+ if (e.type === 'close-verdict' || e.type === 'outer-close') {
329
+ const stageScoped = e.type === 'outer-close' || inFix;
330
+ if (Array.isArray(e.stages)) {
331
+ for (const st of e.stages) {
332
+ if (st && isStr(st.name)) {
333
+ verdict.set(st.name, st.verdict);
334
+ if (st.verdict === 'satisfied') sat(st.name, st.notes);
335
+ }
336
+ }
337
+ }
338
+ if (isStr(e.gap)) {
339
+ const n = nameOf(e.gap);
340
+ if (n === 'close' && !Array.isArray(e.stages)) verdict.set('close', e.verdict);
341
+ const gg = { gap: e.gap, step: stageScoped ? null : curStep, seq: e.seq };
342
+ gaps.set(n, gg);
343
+ red(n, gg);
344
+ } else if (!Array.isArray(e.stages)) {
345
+ verdict.set('close', e.verdict);
346
+ if (e.verdict === 'satisfied') sat('close', null);
347
+ }
348
+ }
349
+ if (e.type === 'exit-eval') {
350
+ for (const r of e.results || []) {
351
+ if (!r || typeof r !== 'object') continue;
352
+ if (r.type === 'check-passes') {
353
+ if (r.pass === false && isStr(r.detail)) {
354
+ const gg = { gap: r.detail, step: isStr(e.step) ? e.step : curStep, seq: e.seq };
355
+ gaps.set(nameOf(r.detail), gg);
356
+ red(nameOf(r.detail), gg);
357
+ }
358
+ } else if (isStr(r.type)) {
359
+ if (r.pass === true) { verdict.set(r.type, 'satisfied'); sat(r.type, null); }
360
+ else if (r.pass === false) {
361
+ verdict.set(r.type, 'needs_revision');
362
+ if (isStr(r.detail)) {
363
+ const gg = { gap: r.detail, step: isStr(e.step) ? e.step : curStep, seq: e.seq };
364
+ gaps.set(r.type, gg);
365
+ red(r.type, gg);
366
+ }
367
+ }
368
+ }
369
+ }
370
+ }
371
+ }
372
+
373
+ // ── noise runs: the instrument failed, so no lesson about the work can be read off them ──
374
+ const lastEsc = ev.findLast((e) => e.type === 'escalation') ?? null;
375
+ const cat = lastEsc && isStr(lastEsc.category) ? lastEsc.category : null;
376
+ if (cat !== null && NOISE_CATEGORIES.has(cat)) { out.noise = cat; return out; }
377
+ if (verdict.size === 0) { out.noise = cat === 'worker-crash' ? 'worker-crash' : 'no-close-spoke'; return out; }
378
+
379
+ const ended = isGreen(jobEnd.outcome) ? String(jobEnd.outcome) : (cat ?? (isStr(jobEnd.outcome) ? jobEnd.outcome : 'ended'));
380
+ const goal = isStr(jobStart?.goal) ? cutText(cleanText(jobStart.goal, workdir), 200) : '(not in the record)';
381
+ const date = at.slice(0, 10);
382
+
383
+ const writtenIn = (/** @type {{fromI: number, toI: number}} */ w) => {
384
+ /** @type {string[]} */
385
+ const files = [];
386
+ let diff = null;
387
+ for (let k = w.fromI; k <= w.toI && k < ev.length; k += 1) {
388
+ const e = ev[k];
389
+ if (e.type === 'attempt-diff') {
390
+ diff = e;
391
+ for (const f of e.files || []) if (f && isStr(f.path)) files.push(f.path);
392
+ for (const b of e.binary || []) if (isStr(b)) files.push(b);
393
+ }
394
+ }
395
+ if (Array.isArray(audit)) {
396
+ const t0 = Date.parse(ev[w.fromI]?.ts ?? '');
397
+ const t1 = Date.parse(ev[Math.min(w.toI, ev.length - 1)]?.ts ?? '');
398
+ if (Number.isFinite(t0) && Number.isFinite(t1)) {
399
+ for (const a of audit) {
400
+ if (!a || a.phase !== 'gate' || a.decision !== 'allow') continue;
401
+ if (a.action?.type !== 'write' && a.action?.type !== 'edit') continue;
402
+ const t = Date.parse(a.ts ?? '');
403
+ if (!Number.isFinite(t) || t < t0 || t > t1 + 1000) continue;
404
+ const p = relPath(a.action.path, workdir);
405
+ if (p !== null) files.push(p);
406
+ }
407
+ }
408
+ }
409
+ return { files: uniq(files), diff };
410
+ };
411
+
412
+ /**
413
+ * @param {string} check @param {any} g the red moment @param {'FIXED'|'NEVER_FIXED'} kind
414
+ * @param {{i: number, note: string|null}|null} pass
415
+ */
416
+ const mk = (check, g, kind, pass) => {
417
+ const lines = quoteLines(String(g.gap)).map((l) => cleanText(l, workdir));
418
+ const quote = lines.join('\n');
419
+ const full = cleanText(String(g.gap), workdir);
420
+ const k = errorKinds(quote, full);
421
+ // Step (as planned): the failing step's action text in the plan live at that moment
422
+ const stepId = isStr(g.step) ? g.step : null;
423
+ const plan = plans.filter(([pi]) => pi <= g.i).at(-1) ?? plans.at(-1) ?? null;
424
+ const step = stepId && plan ? plan[1].find((x) => x?.id === stepId) : null;
425
+ const stepAction = isStr(step?.action) ? cutText(cleanText(step.action, workdir), 300) : null;
426
+ // the passing try (FIXED) / the try that followed the red (NEVER FIXED)
427
+ let w;
428
+ if (kind === 'FIXED' && pass) {
429
+ const start = Math.max(iters.filter((x) => x <= pass.i).at(-1) ?? 0, g.i + 1);
430
+ w = { fromI: start, toI: pass.i };
431
+ } else {
432
+ const start = iters.find((x) => x > g.i);
433
+ const end = start === undefined ? -1 : (iters.find((x) => x > start) ?? ev.length) - 1;
434
+ w = start === undefined ? { fromI: 0, toI: -1 } : { fromI: start, toI: end };
435
+ }
436
+ const wr = writtenIn(w);
437
+ const fixTouched = wr.files.map((p) => cleanText(p, workdir));
438
+ const diffEv = kind === 'FIXED' ? wr.diff : null;
439
+ const afterI = kind === 'FIXED' && pass ? pass.i : g.i;
440
+ const nextRed = reds.find((r) => r.i > afterI && r.check !== check);
441
+ const said = lines.map((l) => l.replace(/^\s*close:\s*/, '').replace(/^[A-Z][A-Z0-9_-]* \| /, '').trim())
442
+ .filter((l) => l && !/^(check ".*" red: )?close stage ".*" failed:$/.test(l));
443
+ const id = `${runid}:${check}:${kind === 'FIXED' ? 'fixed' : 'stuck'}`;
444
+ const base = {
445
+ id, runid, at, date, job, model: runModel, check, kind, goal,
446
+ stepId, stepAction,
447
+ meaning: questions.get(check) ?? (check === 'tree-changed' ? 'did the step change a file in its scope?' : check === 'close' ? "does the job's close pass?" : null),
448
+ said: said.slice(0, SAID_LINES).map((l) => cutText(l, 220)), saidMore: Math.max(0, said.length - SAID_LINES),
449
+ kinds: k.kinds, files: k.files, symbol: k.symbol, tokens: flaggedTokens(quote),
450
+ nextCheck: nextRed ? nextRed.check : null, ended,
451
+ fixTouched,
452
+ whatChanged: diffEv
453
+ ? {
454
+ files: (diffEv.files || []).map((/** @type {any} */ f) => ({ path: String(f.path), diff: String(f.diff ?? ''), truncated: f.truncated === true, ...(Number.isInteger(f.cutLines) ? { cutLines: f.cutLines } : {}) })),
455
+ binary: (diffEv.binary || []).map(String),
456
+ truncated: diffEv.truncated === true,
457
+ }
458
+ : null,
459
+ };
460
+ /** @type {Card} */
461
+ const card = redactDeep({ ...base, key: cardKey(base) });
462
+ return { card, suspect: k.suspect };
463
+ };
464
+
465
+ /** @type {Card[]} */ const all = [];
466
+ /** @type {Card[]} */ const sus = [];
467
+ const push = (/** @type {{card: Card, suspect: boolean}} */ r) => {
468
+ if (r.suspect) sus.push(r.card);
469
+ else if (r.card.kind === 'FIXED' && r.card.kinds[0] === 'other' && r.card.fixTouched.length === 0) out.thin += 1; // M8 am3: a NEVER FIXED note is kept, thin or not
470
+ else all.push(r.card);
471
+ };
472
+ for (const [check, p] of pairs) push(mk(check, p.red, 'FIXED', p.pass));
473
+ for (const [check, g] of gaps) {
474
+ const v = verdict.get(check);
475
+ if (v === 'satisfied') continue;
476
+ if (v !== undefined || check === 'close') push(mk(check, pend.get(check) ?? { ...g, i: reds.findLast((r) => r.check === check)?.i ?? 0 }, 'NEVER_FIXED', null));
477
+ }
478
+ out.cards = all;
479
+ out.suspect = sus;
480
+ return out;
481
+ }
482
+
483
+ // ── fold ─────────────────────────────────────────────────────────────────────────────────────────
484
+ /** @param {{kinds: string[]}} a @param {{kinds: string[]}} b */
485
+ export function sharedKind(a, b) {
486
+ return a.kinds[0] !== 'other' && b.kinds[0] !== 'other' && a.kinds.some((x) => b.kinds.includes(x));
487
+ }
488
+
489
+ /**
490
+ * Do two cards agree on kind? A shared error code / kind, OR (RULED 2026-10-23 R1) both carry NO code (`other`) and both
491
+ * have a non-empty flagged-text token set, so the text rule alone decides. A coded card never matches a code-less one.
492
+ * The 60% was fitted on cards WITH codes; the code-less use is UNTESTED on real data.
493
+ * @param {{kinds: string[], tokens: string[]}} a @param {{kinds: string[], tokens: string[]}} b
494
+ */
495
+ export function kindAgrees(a, b) {
496
+ if (sharedKind(a, b)) return true;
497
+ return a.kinds[0] === 'other' && b.kinds[0] === 'other' && a.tokens.length > 0 && b.tokens.length > 0;
498
+ }
499
+
500
+ /** Jaccard of two token arrays; an empty side scores 0. @param {string[]} a @param {string[]} b */
501
+ export function jaccard(a, b) {
502
+ if (!a.length || !b.length) return 0;
503
+ const sb = new Set(b);
504
+ let n = 0;
505
+ for (const x of a) if (sb.has(x)) n += 1;
506
+ return n / (a.length + b.length - n);
507
+ }
508
+
509
+ /**
510
+ * Are two cards one lesson? Same check, kinds that agree ({@link kindAgrees}: a shared code, or both code-less with text
511
+ * on both sides) and Jaccard >= 60% on flagged-text tokens. `sameJob: false` drops the job test (RULING 1: the cross-job rule for climbing).
512
+ * @param {Card} a @param {Card} b @param {{sameJob?: boolean}} [o]
513
+ * @returns {{match: boolean, score: number}}
514
+ */
515
+ export function cardsMatch(a, b, { sameJob = true } = {}) {
516
+ if ((sameJob && a.job !== b.job) || a.check !== b.check || !kindAgrees(a, b)) return { match: false, score: 0 };
517
+ const score = jaccard(a.tokens, b.tokens);
518
+ return { match: score >= JACCARD_MIN, score };
519
+ }
520
+
521
+ /**
522
+ * Group cards into lessons: single-link components over eligible pairs; every pair INSIDE a component is re-checked
523
+ * for a shared kind, and a component with any pair lacking one splits back to singletons.
524
+ * @param {Card[]} cards
525
+ * @returns {Card[][]} groups, in first-card order; each group in input order
526
+ */
527
+ export function foldCards(cards) {
528
+ const n = cards.length;
529
+ const par = cards.map((_, i) => i);
530
+ const find = (/** @type {number} */ x) => { let r = x; while (par[r] !== r) r = par[r]; par[x] = r; return r; };
531
+ for (let i = 0; i < n; i += 1) for (let j = i + 1; j < n; j += 1) if (cardsMatch(cards[i], cards[j]).match) par[find(i)] = find(j);
532
+ /** @type {Map<number, number[]>} */
533
+ const comps = new Map();
534
+ for (let i = 0; i < n; i += 1) { const r = find(i); comps.set(r, [...(comps.get(r) ?? []), i]); }
535
+ /** @type {Card[][]} */
536
+ const groups = [];
537
+ for (const m of comps.values()) {
538
+ let ok = true;
539
+ for (let a = 0; a < m.length && ok; a += 1) for (let b = a + 1; b < m.length; b += 1) if (!kindAgrees(cards[m[a]], cards[m[b]])) { ok = false; break; }
540
+ if (ok) groups.push(m.map((i) => cards[i]));
541
+ else for (const i of m) groups.push([cards[i]]);
542
+ }
543
+ return groups.sort((x, y) => cards.indexOf(x[0]) - cards.indexOf(y[0]));
544
+ }
545
+
546
+ // ── the ledger ───────────────────────────────────────────────────────────────────────────────────
547
+ /**
548
+ * @typedef {object} Row
549
+ * @property {string} id
550
+ * @property {string} lesson ONE sentence, template-only (see {@link lessonOf})
551
+ * @property {number} count runs seen; STARTS AT 1
552
+ * @property {Card} sample the LATEST card
553
+ * @property {Record<string, number>} models per-model counts (read-only information; never a filter)
554
+ * @property {string} workflow
555
+ * @property {string|null} place
556
+ * @property {'workflow'|'place'|'user'} level STORED as 'workflow' only; the level a reader sees is derived by {@link readableRows} from the rows memory still shows (an older file's stored value is ignored and reset on the next write)
557
+ * @property {'deterministic'|'rubric'} trust
558
+ * @property {string[]} runIds
559
+ * @property {string} firstSeen
560
+ * @property {string} lastSeen
561
+ * @property {string|null} specHash the signed hash the lesson was last seen under (a workflow row of another hash is never matched or read)
562
+ * @property {string} key check + sorted kinds (job-independent); information only since R2 removed the check-wide set-aside
563
+ */
564
+ /**
565
+ * @typedef {object} Pending
566
+ * @property {string} runid @property {string} at @property {string} workflow @property {string|null} place
567
+ * @property {string|null} specHash @property {Card[]} cards
568
+ */
569
+ /**
570
+ * @typedef {object} Ledger
571
+ * @property {1} version
572
+ * @property {Row[]} rows
573
+ * @property {Pending[]} pending holds written by v0.46.x for rubric runs, released by the human Accept (NOT counted, NOT readable); new runs never write one
574
+ * @property {Card[]} suspect CHECK-SUSPECT cards, listed, newest last
575
+ * @property {Record<string, {at: string, noise: string|null, cards: number, suspect: number, thin: number}>} health per run (idempotent by run id)
576
+ */
577
+
578
+ /** @returns {Ledger} */
579
+ export function emptyLedger() {
580
+ return { version: 1, rows: [], pending: [], suspect: [], health: {} };
581
+ }
582
+
583
+ /** The job-independent key of a card: check + sorted kinds. @param {{check: string, kinds: string[]}} c */
584
+ export const keyOfCard = (c) => `${c.check}|${[...c.kinds].sort().join(',')}`;
585
+
586
+ /**
587
+ * ONE sentence, rendered by code from the card's own fields (RULING 5, template-only).
588
+ * @param {Card} c @returns {string}
589
+ */
590
+ export function lessonOf(c) {
591
+ const what = c.meaning ? ` (${c.meaning.replace(/[?.]+$/, '')})` : '';
592
+ const kinds = c.kinds[0] === 'other' ? '' : ` on ${c.kinds.join(' ')}`;
593
+ const file = c.files[0] ? ` in ${c.files.slice(0, 3).join(', ')}${c.files.length > 3 ? ` +${c.files.length - 3} more` : ''}` : '';
594
+ const end = c.kind === 'FIXED' ? 'fixed later in the same run' : 'got stuck here, never fixed';
595
+ return `check "${c.check}"${what} failed${kinds}${file}; ${end}.`;
596
+ }
597
+
598
+ const stem = (/** @type {string|undefined} */ f) => (f ?? '').split('/').at(-1)?.replace(/\.[^.]+$/, '') ?? '';
599
+
600
+ /** Stable row id from the fold's shared fields: job + check + kinds + file stem. @param {Card} c */
601
+ function rowId(c) {
602
+ return [c.job, c.check, [...c.kinds].sort().join('+'), stem(c.files[0]) || '-'].join('~').replace(/[^\w~+.@-]+/g, '_');
603
+ }
604
+
605
+ /**
606
+ * Memory filter: is this row older than 56 days at `now`? Decided from `lastSeen` alone, read-time, never stored.
607
+ * @param {Row} r @param {Date} now
608
+ */
609
+ export const isDecayed = (r, now) => { const t = Date.parse(r.lastSeen); return Number.isFinite(t) && now.getTime() - t > DECAY_DAYS * DAY_MS; };
610
+
611
+ /**
612
+ * Is this workflow row from another job version (a different signed hash than this run's)? Decided from the stored
613
+ * `specHash`, read-time, never stored. Unknown hash on either side is the same version.
614
+ * @param {Row} r @param {string} workflow @param {string|null} specHash
615
+ */
616
+ export const otherJobVersion = (r, workflow, specHash) => r.level === 'workflow' && r.workflow === workflow && r.specHash !== null && specHash !== null && r.specHash !== specHash;
617
+
618
+ /** Drop the retired stored `status`/`expiredBy` fields an older ledger file may carry, and reset a stored `level` (never read; stripped on the next write). @param {Row} r */
619
+ const stripLegacy = (r) => { const { status: _s, expiredBy: _e, ...rest } = /** @type {Row & {status?: unknown, expiredBy?: unknown}} */ (r); return /** @type {Row} */ ({ ...rest, level: 'workflow' }); };
620
+
621
+ /** Rank order for matching and reading: highest count, most recent lastSeen, then id. */
622
+ const byRank = (/** @type {Row} */ a, /** @type {Row} */ b) => b.count - a.count || (a.lastSeen < b.lastSeen ? 1 : a.lastSeen > b.lastSeen ? -1 : 0) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
623
+
624
+ /**
625
+ * Fold ONE run's cards into the ledger. Pure: returns a new ledger.
626
+ *
627
+ * +1 per RUN per row: the run's own cards are folded into lessons first, and a row whose `runIds` already holds the
628
+ * run id is never counted twice (a resumed run, one id, never double counts) but IS refreshed: the resumed leg's card
629
+ * replaces the sample, lesson, key, lastSeen, hash and place (a leg-1 NEVER FIXED row becomes the leg-2 FIXED one). A
630
+ * matching lesson replaces the row's sample, bumps the model count and appends the run id (a row last seen 56+ days ago counts +1 and is read again);
631
+ * otherwise it opens a new row at count 1. NEVER FIXED cards count like FIXED ones (RULING 3). A workflow row of
632
+ * another signed hash is never matched here: the new version opens its own rows. Nothing is ever deleted or stamped.
633
+ * @param {Ledger} ledger
634
+ * @param {{runid: string, cards: Card[], workflow: string, place: string|null, specHash: string|null, trust: 'deterministic'|'rubric', now: Date}} o
635
+ * @returns {Ledger}
636
+ */
637
+ export function countLedger(ledger, { runid, cards, workflow, place, specHash, trust, now }) {
638
+ const rows = ledger.rows.map((r) => ({ ...stripLegacy(r), runIds: [...r.runIds], models: { ...r.models } }));
639
+ for (const group of foldCards(cards)) {
640
+ const rep = group.reduce((a, c) => (c.at >= a.at ? c : a));
641
+ const hit = [...rows].sort(byRank).find((r) => r.workflow === workflow && !otherJobVersion(r, workflow, specHash) && cardsMatch(rep, r.sample).match);
642
+ if (hit) {
643
+ // A row already holding this run id is the run's OWN row (a resumed leg re-reads the whole spine): refresh it from
644
+ // the new card, but the count, the model tally and the run id stay one per run.
645
+ const own = hit.runIds.includes(runid);
646
+ if (!own) {
647
+ hit.count += 1;
648
+ hit.models[rep.model ?? 'unknown'] = (hit.models[rep.model ?? 'unknown'] ?? 0) + 1;
649
+ hit.runIds.push(runid);
650
+ }
651
+ // a refresh never steps the row back: re-folding an older run's cards must not replace a newer run's sample
652
+ if (!own || rep.at >= hit.lastSeen) {
653
+ hit.sample = rep;
654
+ hit.lesson = lessonOf(rep);
655
+ hit.key = keyOfCard(rep);
656
+ hit.lastSeen = rep.at;
657
+ hit.specHash = specHash;
658
+ hit.place = place ?? hit.place;
659
+ }
660
+ } else {
661
+ let id = rowId(rep);
662
+ for (let n = 2; rows.some((r) => r.id === id); n += 1) id = `${rowId(rep)}-${n}`;
663
+ rows.push({
664
+ id, lesson: lessonOf(rep), count: 1, sample: rep, models: { [rep.model ?? 'unknown']: 1 }, workflow, place, level: 'workflow',
665
+ trust, runIds: [runid], firstSeen: rep.at, lastSeen: rep.at, specHash, key: keyOfCard(rep),
666
+ });
667
+ }
668
+ }
669
+ return finish({ ...ledger, rows }, now);
670
+ }
671
+
672
+ /**
673
+ * Recompute the derived parts after any change: pending expiry. Ledger rows are never aged out or deleted, and carry no
674
+ * climbed level (that is decided at read time, see {@link readableRows}).
675
+ * @param {Ledger} L @param {Date} now @returns {Ledger}
676
+ */
677
+ function finish(L, now) {
678
+ const rows = L.rows.map(stripLegacy);
679
+ return {
680
+ ...L,
681
+ rows: rows.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)),
682
+ pending: L.pending.filter((p) => now.getTime() - Date.parse(p.at) <= PENDING_DAYS * DAY_MS),
683
+ };
684
+ }
685
+
686
+ const LEVEL_RANK = { workflow: 0, place: 1, user: 2 };
687
+
688
+ /**
689
+ * Climbing (RULING 1): the same lesson across workflows — the section-3 rule with "same job" dropped — seen in 3
690
+ * distinct workflows on one place climbs to `place`; in 3 distinct places, to `user`. Derived from the rows handed in
691
+ * alone (every row starts at `workflow`, a stored level is ignored): {@link readableRows} hands it only the rows memory
692
+ * still shows, so a level drops back when siblings age out. Returns copies; keeps every run id.
693
+ * @param {Row[]} rows @returns {Row[]}
694
+ */
695
+ export function climb(rows) {
696
+ const n = rows.length;
697
+ const par = rows.map((_, i) => i);
698
+ const find = (/** @type {number} */ x) => { let r = x; while (par[r] !== r) r = par[r]; par[x] = r; return r; };
699
+ for (let i = 0; i < n; i += 1) for (let j = i + 1; j < n; j += 1) if (cardsMatch(rows[i].sample, rows[j].sample, { sameJob: false }).match) par[find(i)] = find(j);
700
+ /** @type {Map<number, number[]>} */
701
+ const fam = new Map();
702
+ for (let i = 0; i < n; i += 1) { const r = find(i); fam.set(r, [...(fam.get(r) ?? []), i]); }
703
+ /** @type {Row[]} */
704
+ const out = rows.map((r) => ({ ...r, level: 'workflow' }));
705
+ for (const idx of fam.values()) {
706
+ if (idx.length < CLIMB_AT) continue;
707
+ /** @type {Map<string, Set<string>>} */
708
+ const perPlace = new Map();
709
+ for (const i of idx) {
710
+ const p = rows[i].place;
711
+ if (p !== null) perPlace.set(p, (perPlace.get(p) ?? new Set()).add(rows[i].workflow));
712
+ }
713
+ for (const i of idx) {
714
+ const p = rows[i].place;
715
+ /** @type {'workflow'|'place'|'user'} */
716
+ let level = out[i].level;
717
+ if (p !== null && (perPlace.get(p)?.size ?? 0) >= CLIMB_AT && LEVEL_RANK[level] < LEVEL_RANK.place) level = 'place';
718
+ if (perPlace.size >= CLIMB_AT && LEVEL_RANK[level] < LEVEL_RANK.user) level = 'user';
719
+ out[i].level = level;
720
+ }
721
+ }
722
+ return out;
723
+ }
724
+
725
+ /**
726
+ * Hold a run's cards until a human Accept. NO LONGER CALLED for new runs (v1.112: a rubric run's lessons count at run
727
+ * end); kept so a hold already in a ledger file still has a writer for tests and a reader in {@link releasePending}. Pure.
728
+ * @param {Ledger} ledger
729
+ * @param {{runid: string, cards: Card[], workflow: string, place: string|null, specHash: string|null, at: string}} o
730
+ * @param {Date} now @returns {Ledger}
731
+ */
732
+ export function holdPending(ledger, { runid, cards, workflow, place, specHash, at }, now) {
733
+ const pending = ledger.pending.filter((p) => p.runid !== runid);
734
+ if (cards.length) pending.push({ runid, at, workflow, place, specHash, cards });
735
+ return finish({ ...ledger, pending }, now);
736
+ }
737
+
738
+ /**
739
+ * The human Accept releases an OLD hold (written by v0.46.x; new runs write none): its cards count now (trust `rubric`). Only forward, only here. A hold
740
+ * older than 60 days is dropped uncounted. Idempotent (no hold = nothing to do; run ids stop a double count).
741
+ * @param {Ledger} ledger @param {string} runid @param {Date} now
742
+ * @returns {{ledger: Ledger, released: number}}
743
+ */
744
+ export function releasePending(ledger, runid, now) {
745
+ const p = ledger.pending.find((x) => x.runid === runid);
746
+ if (!p) return { ledger, released: 0 };
747
+ const rest = { ...ledger, pending: ledger.pending.filter((x) => x.runid !== runid) };
748
+ if (now.getTime() - Date.parse(p.at) > PENDING_DAYS * DAY_MS) return { ledger: finish(rest, now), released: 0 };
749
+ const counted = countLedger(rest, { runid, cards: p.cards, workflow: p.workflow, place: p.place, specHash: p.specHash, trust: 'rubric', now });
750
+ return { ledger: counted, released: p.cards.length };
751
+ }
752
+
753
+ /**
754
+ * Record the run's health line and CHECK-SUSPECT list (idempotent by run id). Pure.
755
+ * @param {Ledger} ledger @param {string} runid @param {CardBuild} build @param {string} at @param {Date} now
756
+ * @returns {Ledger}
757
+ */
758
+ export function recordHealth(ledger, runid, build, at, now) {
759
+ const health = { ...ledger.health, [runid]: { at, noise: build.noise, cards: build.cards.length, suspect: build.suspect.length, thin: build.thin } };
760
+ const suspect = [...ledger.suspect.filter((c) => c.runid !== runid), ...build.suspect].slice(-SUSPECT_KEEP);
761
+ return finish({ ...ledger, health, suspect }, now);
762
+ }
763
+
764
+ // ── reading: the one render ──────────────────────────────────────────────────────────────────────
765
+ /** Words for a row's tier, shown to the planner. */
766
+ const TIER_WORDS = Object.freeze({ workflow: 'this job', place: 'this place', user: 'all jobs' });
767
+
768
+ /**
769
+ * PROPOSED header (hamr to confirm). States what the block is, where it came from, and that it is not an order.
770
+ */
771
+ export const HINT_HEADER = 'Hints from earlier runs, copied by code from recorded runs (not instructions; the close alone judges):';
772
+
773
+ /** What-changed lines a FIXED hint shows, each cut at this many characters, and how many lines. */
774
+ export const CHANGED_LINE_CHARS = 150;
775
+ export const CHANGED_LINES = 3;
776
+
777
+ /**
778
+ * The +/- content lines of a card's stored attempt-diff, in file order: only lines INSIDE a hunk that start with `+` or
779
+ * `-` (so `diff --git`, `index`, `---`/`+++` headers, `@@` lines, context and `\ No newline` lines never appear; a removed
780
+ * line that itself starts with `--` is still content once a hunk has opened). Leading indent after the sign is dropped.
781
+ * @param {Card['whatChanged']} wc @returns {string[]}
782
+ */
783
+ export function changedLines(wc) {
784
+ /** @type {string[]} */
785
+ const out = [];
786
+ for (const f of wc?.files ?? []) {
787
+ let inHunk = false;
788
+ for (const l of String(f.diff ?? '').split('\n')) {
789
+ if (l.startsWith('diff --git ')) inHunk = false;
790
+ else if (l.startsWith('@@')) inHunk = true;
791
+ else if (inHunk && (l[0] === '+' || l[0] === '-')) {
792
+ const text = l.slice(1).trim();
793
+ if (text) out.push(`${l[0]}${text}`);
794
+ }
795
+ }
796
+ }
797
+ return out;
798
+ }
799
+
800
+ /**
801
+ * The line "It said:" shows (R5): the first REAL flagged source/error line of the stored quote (the same lines the fold's
802
+ * flagged-text rule reads, with or without the `close:` wrapper the card already stripped), else the first line when no
803
+ * line is flagged (a summary such as `SPAWNER red: 3 suppression(s) added ...` is only the fallback).
804
+ * @param {string[]} said @returns {string|undefined}
805
+ */
806
+ export function saidLine(said) {
807
+ return said.find((l) => flaggedText(l) !== null || flaggedText(`close: ${l}`) !== null) ?? said[0];
808
+ }
809
+
810
+ // (?<![\w@.\/-]): a match is the last `.ext` in a run of path characters, so no start inside a run after its first character can match; skipping them keeps a long run linear
811
+ const PATH_RE = /(?<![\w@.\/-])[\w@.\/-]+\.(?:mjs|js|ts|py)\b/g;
812
+ const baseName = (/** @type {string} */ p) => p.split('/').at(-1) ?? p;
813
+
814
+ /**
815
+ * Shorten file paths in a text (R5): a path already shown in full earlier in the SAME hint (`shown`, filled in reading
816
+ * order) is written by its basename; a first mention stays as written. Pure apart from filling `shown`.
817
+ * @param {string} text @param {Set<string>} shown @returns {string}
818
+ */
819
+ function shortenPaths(text, shown) {
820
+ return text.replace(PATH_RE, (p) => {
821
+ if (shown.has(p) && p.includes('/')) return baseName(p);
822
+ shown.add(p);
823
+ return p;
824
+ });
825
+ }
826
+
827
+ /** One hint, whole. @param {Row} r @param {number} n */
828
+ function hintText(r, n) {
829
+ const c = r.sample;
830
+ /** @type {Set<string>} */
831
+ const shown = new Set();
832
+ const lesson = `${n}. [${TIER_WORDS[r.level]}, seen ${r.count} time${r.count === 1 ? '' : 's'}] ${r.lesson}`;
833
+ for (const p of lesson.match(PATH_RE) ?? []) shown.add(p);
834
+ const L = [lesson];
835
+ const said = saidLine(c.said);
836
+ if (said) L.push(` It said: ${cutText(shortenPaths(said, shown), 150)}`);
837
+ // am2 line 4: no "Fix touched" line in the hint; fixTouched stays on the card and in the ledger.
838
+ if (c.kind === 'FIXED') {
839
+ // am2 line 3: a changed line longer than CHANGED_LINE_CHARS is left out whole, never cut.
840
+ const ch = changedLines(c.whatChanged).filter((l) => l.length <= CHANGED_LINE_CHARS);
841
+ if (ch.length) {
842
+ const pad = ' '.repeat(' What changed: '.length);
843
+ const show = ch.slice(0, CHANGED_LINES);
844
+ if (ch.length > CHANGED_LINES) show.push(`(+${ch.length - CHANGED_LINES} more)`);
845
+ L.push(` What changed: ${show[0]}`, ...show.slice(1).map((l) => `${pad}${l}`));
846
+ }
847
+ }
848
+ return L.join('\n');
849
+ }
850
+
851
+ /**
852
+ * Which rows may be read for this job, in reading order (THE memory filter; the ledger itself keeps every row).
853
+ * Excluded: pending rows, any row last seen more than 56 days ago, any row with no run id, a workflow row of another
854
+ * job or of another signed hash, a place row of another place. The level (this job / this place / all jobs) is
855
+ * derived HERE by {@link climb} over the rows not decayed at `now` only; the stored level is never read.
856
+ * Order: this job's, then this place's, then all-jobs LAST (R2: climbing wins, so an all-jobs hint only uses leftover
857
+ * room); inside each level highest count first (ties: most recent lastSeen, then id), so the order is total and stable.
858
+ * @param {Ledger} ledger @param {{workflow: string, place: string|null, specHash?: string|null, now: Date}} o
859
+ * @returns {Row[]}
860
+ */
861
+ export function readableRows(ledger, { workflow, place, specHash = null, now }) {
862
+ return climb(ledger.rows.filter((r) => !isDecayed(r, now))).filter((r) => {
863
+ if (r.runIds.length === 0) return false;
864
+ if (r.level === 'workflow') return r.workflow === workflow && !otherJobVersion(r, workflow, specHash);
865
+ if (r.level === 'place') return place !== null && r.place === place;
866
+ return true;
867
+ }).sort((a, b) => LEVEL_RANK[a.level] - LEVEL_RANK[b.level] || byRank(a, b));
868
+ }
869
+
870
+ /**
871
+ * THE one render: the block the PLANNER reads at draft and at the first replan. Byte-for-byte reproducible from the
872
+ * ledger as it stood. Stops at 2,000 characters; a hint is added whole or not at all; nothing readable -> empty text.
873
+ * @param {Ledger} ledger @param {{workflow: string, place: string|null, specHash?: string|null, now: Date}} o
874
+ * @returns {{text: string, ids: string[]}}
875
+ */
876
+ export function renderHints(ledger, o) {
877
+ /** @type {string[]} */
878
+ const ids = [];
879
+ let text = HINT_HEADER;
880
+ for (const r of readableRows(ledger, o)) {
881
+ const next = `${text}\n${hintText(r, ids.length + 1)}`;
882
+ if (next.length > HINT_CHARS_MAX) break;
883
+ text = next;
884
+ ids.push(r.id);
885
+ }
886
+ return ids.length ? { text, ids } : { text: '', ids: [] };
887
+ }
888
+
889
+ /**
890
+ * @typedef {object} HintParts one hint of a rendered block, split back into its fields (for the panel's Audit view)
891
+ * @property {number} n the hint's number in the block
892
+ * @property {string} level 'this job' | 'this place' | 'all jobs' (the words {@link renderHints} wrote)
893
+ * @property {number} count how many runs saw it
894
+ * @property {string} check the check's name
895
+ * @property {string[]} kinds the error codes (empty when the hint names none)
896
+ * @property {boolean} fixed true = fixed later in the same run, false = never fixed
897
+ * @property {string|null} said the "It said" line
898
+ * @property {string|null} touched the "Fix touched" text
899
+ * @property {string[]} changed the shown What-changed lines (+/- lines), without the "(+N more)" line
900
+ * @property {number} moreChanged N of "(+N more)", 0 when absent
901
+ */
902
+
903
+ const HINT_HEAD_RE = /^(\d+)\. \[(this job|this place|all jobs), seen (\d+) times?\] (.*)$/;
904
+
905
+ /**
906
+ * Split a block {@link renderHints} wrote back into its hints. The ONLY reader of that text: it lives beside the
907
+ * writer ({@link hintText}, {@link lessonOf}) and a test renders real blocks and parses them back. A hint it cannot
908
+ * read is returned with what it could read (never thrown, never invented). Pure.
909
+ * @param {string} text @returns {HintParts[]}
910
+ */
911
+ export function parseHintBlock(text) {
912
+ /** @type {HintParts[]} */
913
+ const out = [];
914
+ /** @type {HintParts|null} */
915
+ let cur = null;
916
+ let inChanged = false;
917
+ for (const line of String(text).split('\n')) {
918
+ const m = HINT_HEAD_RE.exec(line);
919
+ if (m) {
920
+ const lesson = m[4];
921
+ const check = /^check "([^"]*)"/.exec(lesson)?.[1] ?? '';
922
+ const kinds = /(?:"|\)) failed on (.+?)(?: in |;)/.exec(lesson)?.[1]?.split(' ') ?? [];
923
+ cur = { n: Number(m[1]), level: m[2], count: Number(m[3]), check, kinds, fixed: /; fixed later in the same run\.$/.test(lesson), said: null, touched: null, changed: [], moreChanged: 0 };
924
+ out.push(cur);
925
+ inChanged = false;
926
+ } else if (cur && line.startsWith(' It said: ')) { cur.said = line.slice(' It said: '.length); inChanged = false; }
927
+ else if (cur && line.startsWith(' Fix touched: ')) { cur.touched = line.slice(' Fix touched: '.length); inChanged = false; }
928
+ else if (cur && line.startsWith(' What changed: ')) { inChanged = true; cur.changed.push(line.slice(' What changed: '.length)); }
929
+ else if (cur && inChanged && line.startsWith(' '.repeat(' What changed: '.length))) {
930
+ const t = line.slice(' What changed: '.length);
931
+ const more = /^\(\+(\d+) more\)$/.exec(t);
932
+ if (more) cur.moreChanged = Number(more[1]); else cur.changed.push(t);
933
+ }
934
+ }
935
+ return out;
936
+ }
937
+
938
+ // ── the place of a job ───────────────────────────────────────────────────────────────────────────
939
+ /**
940
+ * Where a job lives, derived by code from the signed spec's inputs line 1: a website job = the URL host; a repo or
941
+ * plain folder/file job = that path (resolved by the caller). Null when the spec carries no inputs.
942
+ * @param {any} spec @param {(p: string) => string} [resolve] path resolver (the caller passes `realpath`)
943
+ * @returns {string|null}
944
+ */
945
+ export function placeOf(spec, resolve = (p) => p) {
946
+ const v = Array.isArray(spec?.inputs) ? spec.inputs[0]?.value : null;
947
+ if (!isStr(v)) return null;
948
+ if (/^https?:\/\//i.test(v)) {
949
+ try { return new URL(v).host; } catch { return null; }
950
+ }
951
+ return resolve(v);
952
+ }