bareloop 0.55.0 → 0.56.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 (56) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/bareloop.context.md +4 -2
  3. package/package.json +2 -2
  4. package/src/authorflow.js +141 -264
  5. package/src/authoring.js +2 -3
  6. package/src/authorjob.js +117 -88
  7. package/src/authorreadout.js +9 -15
  8. package/src/authorrun.js +13 -4
  9. package/src/behaviour.js +14 -0
  10. package/src/blockasks.js +43 -0
  11. package/src/checkblock.js +772 -0
  12. package/src/checklist.js +128 -0
  13. package/src/checkpick.js +30 -312
  14. package/src/checkwords.js +3 -1
  15. package/src/declaredclose.js +30 -1
  16. package/src/destpoint.js +3 -1
  17. package/src/draftspend.js +46 -0
  18. package/src/facts.js +8 -1
  19. package/src/fitcheck.js +5 -3
  20. package/src/pagemap.js +15 -3
  21. package/src/panel/authorroutes.js +15 -3
  22. package/src/panel/authorsession.js +133 -46
  23. package/src/panel/index.html +194 -22
  24. package/src/panel/jobplan.js +85 -33
  25. package/src/panel/server.js +52 -7
  26. package/src/pickrecord.js +19 -1
  27. package/src/placerule.js +355 -0
  28. package/src/promptregisters.js +11 -0
  29. package/src/questionbox.js +112 -0
  30. package/src/rowedit.js +115 -0
  31. package/src/rubricstep.js +212 -125
  32. package/src/run.js +10 -2
  33. package/src/userrun.js +46 -1
  34. package/types/authorflow.d.ts +32 -139
  35. package/types/authorjob.d.ts +24 -6
  36. package/types/authorreadout.d.ts +4 -10
  37. package/types/behaviour.d.ts +12 -0
  38. package/types/blockasks.d.ts +37 -0
  39. package/types/checkblock.d.ts +361 -0
  40. package/types/checklist.d.ts +134 -0
  41. package/types/checkpick.d.ts +3 -140
  42. package/types/declaredclose.d.ts +4 -0
  43. package/types/destpoint.d.ts +2 -0
  44. package/types/draftspend.d.ts +21 -0
  45. package/types/fitcheck.d.ts +7 -1
  46. package/types/pagemap.d.ts +4 -0
  47. package/types/panel/authorsession.d.ts +13 -2
  48. package/types/panel/jobgrid.d.ts +8 -8
  49. package/types/panel/jobplan.d.ts +48 -10
  50. package/types/panel/server.d.ts +14 -13
  51. package/types/pickrecord.d.ts +12 -0
  52. package/types/placerule.d.ts +194 -0
  53. package/types/questionbox.d.ts +87 -0
  54. package/types/rowedit.d.ts +32 -0
  55. package/types/rubricstep.d.ts +91 -48
  56. package/types/run.d.ts +10 -1
@@ -39,7 +39,7 @@ import { checkExportable } from '../runexport.js';
39
39
  import { sourceNearSpine, signedSpecForRun } from '../runfiles.js';
40
40
  import { webFetchState } from '../source.js';
41
41
  import { isWebUrl } from '../pagefetch.js';
42
- import { draftingPartFor, sessionDirForRow, readDraftSteps } from '../draftspend.js';
42
+ import { draftingPartFor, sessionDirForRow, readDraftSteps, readDraftLedger } from '../draftspend.js';
43
43
  import { readingOfQuestion, isAgree } from '../pagemap.js';
44
44
  import {
45
45
  replayOne, parseJsonl, resolveSiblings, isSidecarByName,
@@ -47,10 +47,11 @@ import {
47
47
  import { summarizeForAllLine, auditWindowsOf, replayRun } from '../replay.js';
48
48
  import { legsOf, legsWallMs, stopFilePath, capKindOf } from '../legs.js';
49
49
  import { chainSpend } from '../ledger.js';
50
- import { runBehaviour } from '../behaviour.js';
50
+ import { runBehaviour, writesBlocked } from '../behaviour.js';
51
51
  import { SPEND_RECORD_TYPES, floorsFromRecords } from '../ledger.js';
52
52
  import { jobSpecHash, workflowKey, flowTypeOf, FLOW_TYPE_LABELS } from '../job.js';
53
53
  import { attachMemos, learningsHanded, attachLearnings } from './handed.js';
54
+ import { placeRuleLines } from '../placerule.js';
54
55
  import { confirmProtections } from '../authorflow.js';
55
56
  import { createScheduleDoor } from './schedules.js';
56
57
  import { buildJobGrid } from './jobgrid.js';
@@ -81,7 +82,7 @@ import { filterUnsure } from '../ticketlabels.js';
81
82
  import { judgedFilesOf, lineRules, stepFileRel, proseNotCheckedItems } from '../rubricstep.js';
82
83
  import { factPartOf, factSentence, ruleWords, moneyAs } from '../facts.js';
83
84
  import { createSettingsRoutes } from './settingsroutes.js';
84
- import { planFromSpec } from './jobplan.js';
85
+ import { planFromSpec, auditChecksOf } from './jobplan.js';
85
86
  import { stageQuestionsByName } from '../stagewords.js';
86
87
 
87
88
  const HERE = dirname(fileURLToPath(import.meta.url));
@@ -1736,7 +1737,8 @@ export function getRunResult(runid, /** @type {{ home?: string, sessionsRoot?: s
1736
1737
  // Not checked, split by the line the SIGNED plan ties each item to: a refusal carries its line (closeDecl.refused[].line, planFromSpec's
1737
1738
  // `lines[].refused`), a prose step carries its stage's step. What the plan ties to no line stays in `notChecked` (the bottom). Together they are
1738
1739
  // exactly the Job tab's items (its per-line "not checked" rows plus its Not checked fold) — never a second spelling.
1739
- const plan = planFromSpec(spec);
1740
+ const ledgerDir = sessionDirForRow(row, opts);
1741
+ const plan = planFromSpec(spec, ledgerDir ? readDraftLedger(ledgerDir) : null);
1740
1742
  const proseByLine = proseNotCheckedItems(spec?.closeDecl);
1741
1743
  const prosePool = proseByLine.map((i) => i.text);
1742
1744
  const tiedToLine = (/** @type {number} */ n) => [...(plan.lines.find((l) => l.n === n)?.refused ?? []), ...proseByLine.filter((i) => i.line === n).map((i) => i.text)];
@@ -1753,6 +1755,7 @@ export function getRunResult(runid, /** @type {{ home?: string, sessionsRoot?: s
1753
1755
  /** @type {any} */
1754
1756
  const out = {
1755
1757
  notChecked: tiedToLine(n),
1758
+ ...(plan.notCheckedBy ? { notCheckedBy: plan.notCheckedBy } : {}),
1756
1759
  n, text: jl && typeof jl.text === 'string' ? jl.text : '', rules: jl ? lineRules(jl) : [], kind: fp ? 'facts' : 'text', passed,
1757
1760
  file: di ? { i: di.i, state: read[di.i].state, words: read[di.i].state === 'gone' ? RESULT_FILE_GONE : (read[di.i].state === 'changed' ? RESULT_FILE_CHANGED : null) } : null,
1758
1761
  };
@@ -1824,6 +1827,7 @@ export function getRunResult(runid, /** @type {{ home?: string, sessionsRoot?: s
1824
1827
  pages,
1825
1828
  pageNote: pages.length ? RESULT_PAGE_MAY_CHANGE : null,
1826
1829
  notChecked: bottom,
1830
+ ...(plan.notCheckedBy ? { notCheckedBy: plan.notCheckedBy } : {}),
1827
1831
  readNotes: plan.readNotes,
1828
1832
  // the door's words, from the one table (src/panel/status.js DOOR_WORDS); the page types none of them
1829
1833
  door: { head: DOOR_WORDS.waiting.head, ask: RESULT_DOOR_ASK },
@@ -2245,7 +2249,10 @@ function getRunDetailBody(runid, opts) {
2245
2249
  // PRD v1.106 Part 5 F: the two Run summary rows, worded here (the page prints them)
2246
2250
  callsLine: callsLineOf(rawSpineRecords, scopedBehaviour(row, rawSpineRecords)),
2247
2251
  checksLine: checksLineOf(rawSpineRecords, enrichedParts),
2252
+ auditChecks: auditChecksFor(row, rawSpineRecords, specForParts, opts),
2248
2253
  memoryCache: summary.memoryCache,
2254
+ // PLACE RULES: what the run start read for each place-rule check (plain lines from code), or null when the run has none; the Audit page's placement of it is not built yet
2255
+ placeRules: placeRuleLines(rawSpineRecords),
2249
2256
  // T Part 8: is this run waiting for the person's Accept? The SAME answer fills the runs list's Needs-you tag (`doorWaiting`, one owner)
2250
2257
  accept: !runIsAlive(row) && doorWaiting(rawSpineRecords),
2251
2258
  // PRD v1.107 Part 6: the Result tab shows for a rubric run whose signed close has a rubric-step stage, never otherwise; `delivered` is the
@@ -2419,11 +2426,22 @@ function resolveAuditPathsForRow(row, spineRecords) {
2419
2426
  * @returns {ReturnType<typeof runBehaviour>|null}
2420
2427
  */
2421
2428
  function scopedBehaviour(row, spineRecords) {
2429
+ const windowed = scopedAuditRows(row, spineRecords);
2430
+ return windowed === null ? null : runBehaviour(windowed);
2431
+ }
2432
+
2433
+ /**
2434
+ * The gate-audit rows inside this run's own ts window(s), the ONE scoping behind the Run tab's tools summary and the Audit's write-fence row; `null` when no
2435
+ * gate-audit sidecar was found for the run (never an empty list posing as a clean record).
2436
+ * @param {{spine: string, patient: string|null}} row
2437
+ * @param {any[]} spineRecords
2438
+ * @returns {any[]|null}
2439
+ */
2440
+ function scopedAuditRows(row, spineRecords) {
2422
2441
  const auditPaths = resolveAuditPathsForRow(row, spineRecords);
2423
2442
  if (auditPaths.length === 0) return null;
2424
2443
  const windows = runAuditWindows(spineRecords);
2425
- const windowed = auditPaths.flatMap((ap) => parseJsonl(ap).records).filter((r) => r && typeof r === 'object' && typeof r.ts === 'string' && inAnyWindow(r.ts, windows));
2426
- return runBehaviour(windowed);
2444
+ return auditPaths.flatMap((ap) => parseJsonl(ap).records).filter((r) => r && typeof r === 'object' && typeof r.ts === 'string' && inAnyWindow(r.ts, windows));
2427
2445
  }
2428
2446
 
2429
2447
  /**
@@ -3392,6 +3410,31 @@ function successFromSpec(spec) {
3392
3410
  return names.length > 0 ? names.join(' · ') : null;
3393
3411
  }
3394
3412
 
3413
+ /**
3414
+ * The Audit's check list (hamr ruling A): the card's own sections (planFromSpec for the checks and Not checked, confirmProtections for Always checked) with each row's
3415
+ * result read from the run's recorded stage verdicts ({@link checksOf}), never re-derived. `null` for a run with no signed spec (nothing to list).
3416
+ * @param {{spine: string, patient: string|null}} row @param {any[]} records @param {any} spec @param {{ home?: string, sessionsRoot?: string }} opts
3417
+ */
3418
+ function auditChecksFor(row, records, spec, opts) {
3419
+ if (!spec || typeof spec !== 'object') return null;
3420
+ const ledgerDir = sessionDirForRow(row, opts);
3421
+ const plan = planFromSpec(spec, ledgerDir ? readDraftLedger(ledgerDir) : null);
3422
+ /** @type {string[]} */
3423
+ let guards = [];
3424
+ if (spec.closeDecl && typeof spec.closeDecl.lang === 'string' && typeof spec.verdictType === 'string') {
3425
+ try {
3426
+ guards = confirmProtections({
3427
+ verdictType: spec.verdictType, lang: spec.closeDecl.lang, jobLines: Array.isArray(spec.jobLines) ? spec.jobLines : null,
3428
+ writeScope: Array.isArray(spec.writeScope) && spec.writeScope.every((/** @type {any} */ x) => typeof x === 'string') ? spec.writeScope : null,
3429
+ });
3430
+ } catch { guards = []; }
3431
+ }
3432
+ const got = checksOf(records, spec);
3433
+ const results = got ? new Map(got.stages.map((/** @type {any} */ x) => [x.name, x.passed === true])) : null;
3434
+ const rows = scopedAuditRows(row, records);
3435
+ return auditChecksOf(plan, guards, results, rows === null ? null : writesBlocked(rows));
3436
+ }
3437
+
3395
3438
  /**
3396
3439
  * The write fence plus the guard checks a close actually carries — reusing
3397
3440
  * {@link confirmProtections} (`src/authorflow.js`), the SAME function the
@@ -3630,10 +3673,12 @@ function getRunJobBody(runid, opts) {
3630
3673
  if (existsSync(row.spine)) {
3631
3674
  try { firstStart = parseJsonl(row.spine).records.find((r) => r && typeof r === 'object' && r.type === 'job-start') ?? null; } catch { firstStart = null; }
3632
3675
  }
3676
+ // the check list's rows as the drafting ended, from the run's own session folder (none for a CLI or imported run: the plan then names a row from its key)
3677
+ const ledgerOf = () => { const dir = sessionDirForRow(row, opts); return dir ? readDraftLedger(dir) : null; };
3633
3678
  /** @param {any} spec @param {boolean} resolved @param {string} resolvedFrom @param {string|null} note */
3634
3679
  const fromSpec = (spec, resolved, resolvedFrom, note) => ({
3635
3680
  // P7: the same plan model the chat's plan bubble is drawn from (src/panel/jobplan.js), read from the SIGNED spec
3636
- plan: planFromSpec(spec),
3681
+ plan: planFromSpec(spec, ledgerOf()),
3637
3682
  jobLines: Array.isArray(spec.jobLines) ? spec.jobLines : null,
3638
3683
  inputs: Array.isArray(spec.inputs) && spec.inputs.length ? spec.inputs : [{ n: 1, label: 'repo', value: sourceDisplay() }],
3639
3684
  signedAt: typeof firstStart?.ts === 'string' ? firstStart.ts : null,
package/src/pickrecord.js CHANGED
@@ -3,7 +3,7 @@
3
3
  // and to its guardrail's exact words, never to a line or rule number: both are recomputed on the new card. This file is the only writer of a record's entries
4
4
  // (`entriesFromAnswers`) and the only reader that decides keep-or-ask (`matchRecord`); the logic is the one F146 / F146b proved (poc/m10-am17/keep-picks-am18.mjs).
5
5
  // Throws away: line and rule numbers (recomputed), the model's words (it never sees a pick), a pick whose line or guardrail words no longer match.
6
- import { readFileSync } from 'node:fs';
6
+ import { readFileSync, writeFileSync } from 'node:fs';
7
7
  import path from 'node:path';
8
8
 
9
9
  /** the record's file, inside a drafting session folder only (never a run folder) */
@@ -143,3 +143,21 @@ export function readRecordFile(file) {
143
143
 
144
144
  /** where a drafting session folder keeps its record @param {string} planDir */
145
145
  export const recordPath = (planDir) => path.join(planDir, RECORD_FILE);
146
+
147
+ /**
148
+ * The Drop/Add choices a draft's person made on the confirm card (hamr 2026-11-13, N-2), carried the same way as the picks: tied to the line's words and the row's own name, never to a number.
149
+ * @param {string} file @returns {{lineWords: string, occurrence: number, tail: string, choice: string}[]|null}
150
+ */
151
+ export function readRowChoices(file) {
152
+ try {
153
+ const j = JSON.parse(readFileSync(file, 'utf8'));
154
+ return Array.isArray(j?.rowChoices) ? j.rowChoices.filter((/** @type {any} */ e) => e && typeof e.lineWords === 'string' && Number.isInteger(e.occurrence) && typeof e.tail === 'string' && (e.choice === 'drop' || e.choice === 'add')) : null;
155
+ } catch { return null; }
156
+ }
157
+
158
+ /** write a part of the record without losing the other: `patch` is `{picks}` or `{rowChoices}` @param {string} file @param {Record<string, any>} patch */
159
+ export function writeRecordPart(file, patch) {
160
+ let cur = {};
161
+ try { const j = JSON.parse(readFileSync(file, 'utf8')); if (j && typeof j === 'object' && !Array.isArray(j)) cur = j; } catch { /* no record yet */ }
162
+ writeFileSync(file, `${JSON.stringify({ ...cur, ...patch })}\n`, { mode: 0o600 });
163
+ }
@@ -0,0 +1,355 @@
1
+ // PLACE RULES (docs/product/ITEM33-BUILD.md, "Place rules build spec (hamr go 2026-11-11)").
2
+ //
3
+ // A check whose words hold a version or a date ("the newest release is 0.55.0") is true only while the input stays as it is, so code refuses
4
+ // it as week-only. A PLACE RULE keeps it: it names WHERE the value sits (the first heading at one level of a changelog) instead of WHAT the
5
+ // value is. The signed fact carries the rule; at run start, before any provider call, CODE reads the run's own copy of the input with the rule
6
+ // and the value it finds is bound, in memory only, as that fact's phrase for the planner and the close. No model chooses or reads anything here.
7
+ //
8
+ // This module is the graduation (a REWRITE, never a copy) of the round-3 POC (F321). Pure except `lastPlaceRead`, which reads earlier runs' spines.
9
+
10
+ import { existsSync, readFileSync } from 'node:fs';
11
+
12
+ /** the two rule kinds on the menu: the version in a heading, and the date on the same heading line */
13
+ export const PLACE_KINDS = Object.freeze(['headingBetween', 'headingDateAfter']);
14
+ /** the end-of-line end mark */
15
+ export const EOL = '$EOL';
16
+ /** the field a place rule may carry */
17
+ export const PLACE_FIELDS = Object.freeze(['kind', 'prefix', 'end', 'shape', 'skip']);
18
+ /** the closed list of reasons a read can end not found */
19
+ export const PLACE_REASONS = Object.freeze(['mixed-levels', 'no-heading-line', 'first-heading-mismatch', 'end-mark-missing', 'capture-not-shape', 'only-skipped-headings', 'no-date-on-line', 'no-file', 'empty-text']);
20
+ /** plain words for each reason, from code (the person never reads a raw code) */
21
+ export const PLAIN_REASONS = Object.freeze({
22
+ 'mixed-levels': 'the file writes its version headings at more than one level',
23
+ 'no-heading-line': 'the file has no heading at the level the rule reads',
24
+ 'first-heading-mismatch': 'the newest heading does not start the way the rule says',
25
+ 'end-mark-missing': 'the newest heading does not have the mark the rule reads up to',
26
+ 'capture-not-shape': 'the newest heading does not carry a version number',
27
+ 'only-skipped-headings': 'the file has only an Unreleased heading and no release after it',
28
+ 'no-date-on-line': 'the newest heading line carries no date',
29
+ 'no-file': 'the input could not be read',
30
+ 'empty-text': 'the input is empty',
31
+ });
32
+
33
+ const SHAPES = /** @type {Record<string, RegExp>} */ ({ semver: /^\d+\.\d+\.\d+$/, 'iso-date': /^\d{4}-\d{2}-\d{2}$/ });
34
+ const DATE_FIND = /\d{4}-\d{2}-\d{2}/;
35
+ const FENCE = /^\s{0,3}(```|~~~)/;
36
+ /** a heading carries a semver iff its text starts with an optional "[", an optional "v", then X.Y.Z (token-bounded) */
37
+ const SEMVER_HEADING = /^(#{1,6}) \[?v?(\d+\.\d+\.\d+)(?!\d|\.\d)/;
38
+
39
+ /**
40
+ * @typedef {{kind: 'headingBetween'|'headingDateAfter', prefix: string, end: string, shape: string, skip: string[]}} PlaceRule
41
+ * @typedef {{found: true, value: string, lineIndex: number}|{found: false, reason: string}} PlaceRead
42
+ */
43
+
44
+ /**
45
+ * Why a rule is not a legal place rule, or null when it is. Pure.
46
+ * @param {unknown} rule @returns {string|null}
47
+ */
48
+ export function placeRuleProblem(rule) {
49
+ if (rule === null || typeof rule !== 'object' || Array.isArray(rule)) return 'a place rule is {kind, prefix, end, shape, skip}';
50
+ const r = /** @type {Record<string, any>} */ (rule);
51
+ for (const k of Object.keys(r)) if (!PLACE_FIELDS.includes(k)) return `"${k}" is not a field of a place rule (fields: ${PLACE_FIELDS.join(', ')})`;
52
+ if (!PLACE_KINDS.includes(r.kind)) return `kind is one of ${PLACE_KINDS.join(' | ')}`;
53
+ if (typeof r.prefix !== 'string' || !/^#+ /.test(r.prefix)) return 'prefix starts with # marks and a space';
54
+ if (typeof r.end !== 'string' || r.end === '') return 'end is the mark the value is read up to (or $EOL)';
55
+ if (typeof r.shape !== 'string' || !Object.hasOwn(SHAPES, r.shape)) return `shape is one of ${Object.keys(SHAPES).join(' | ')}`;
56
+ if (!Array.isArray(r.skip) || r.skip.some((/** @type {unknown} */ s) => typeof s !== 'string')) return 'skip is a list of words';
57
+ return null;
58
+ }
59
+
60
+ /**
61
+ * Heading lines at the rule's level: lines outside ``` / ~~~ fences that start with the level mark (for example "## "). Pure.
62
+ * @param {string} text @param {string} prefix @returns {{i: number, line: string}[]}
63
+ */
64
+ export function levelLines(text, prefix) {
65
+ const mark = `${/^#+/.exec(prefix)?.[0] ?? '#'} `;
66
+ let fenced = false;
67
+ /** @type {{i: number, line: string}[]} */
68
+ const out = [];
69
+ text.split(/\r?\n/).forEach((line, i) => {
70
+ if (FENCE.test(line)) { fenced = !fenced; return; }
71
+ if (!fenced && line.startsWith(mark)) out.push({ i, line });
72
+ });
73
+ return out;
74
+ }
75
+
76
+ /**
77
+ * The mixed-level guard: every non-fenced heading line is scanned; semver-carrying headings at MORE THAN ONE level mean mixed. A heading with no
78
+ * semver (a "# Changelog" title, "### Fixed") is ignored. It only ever turns a read into not found, never into a value.
79
+ * @param {string} text @returns {boolean}
80
+ */
81
+ export function mixedLevels(text) {
82
+ let fenced = false;
83
+ /** @type {Set<number>} */
84
+ const levels = new Set();
85
+ for (const line of text.split(/\r?\n/)) {
86
+ if (FENCE.test(line)) { fenced = !fenced; continue; }
87
+ if (fenced) continue;
88
+ const m = SEMVER_HEADING.exec(line);
89
+ if (m) levels.add(m[1].length);
90
+ }
91
+ return levels.size > 1;
92
+ }
93
+
94
+ /** @param {string} reason @returns {{found: false, reason: string}} */
95
+ const nf = (reason) => ({ found: false, reason });
96
+
97
+ /**
98
+ * The STRICT first-heading read. It reads only the first heading line at the rule's level; it must match prefix + end + shape, else not found, and
99
+ * it never looks further down. One exception: a capture that is exactly a skip word ("Unreleased") moves to the NEXT heading at that level,
100
+ * ONCE (a second skip word is not found). Pure.
101
+ * @param {PlaceRule} rule @param {string} text
102
+ * @returns {{found: true, cap: string, after: string, lineIndex: number}|{found: false, reason: string}}
103
+ */
104
+ function selectFirst(rule, text) {
105
+ if (!text || !text.trim()) return nf('empty-text');
106
+ if (mixedLevels(text)) return nf('mixed-levels');
107
+ const hs = levelLines(text, rule.prefix);
108
+ if (!hs.length) return nf('no-heading-line');
109
+ let k = 0;
110
+ let skipped = false;
111
+ for (;;) {
112
+ const { i, line } = hs[k];
113
+ if (!line.startsWith(rule.prefix)) return nf('first-heading-mismatch');
114
+ const rest = line.slice(rule.prefix.length);
115
+ const e = rule.end === EOL ? rest.length : rest.indexOf(rule.end);
116
+ if (e < 0) return nf('end-mark-missing');
117
+ const cap = rest.slice(0, e).trim();
118
+ if (rule.skip.some((s) => s.toLowerCase() === cap.toLowerCase())) {
119
+ if (skipped) return nf('only-skipped-headings');
120
+ skipped = true;
121
+ k += 1;
122
+ if (k >= hs.length) return nf('only-skipped-headings');
123
+ continue;
124
+ }
125
+ if (!SHAPES[rule.shape].test(cap)) return nf('capture-not-shape');
126
+ return { found: true, cap, after: rule.end === EOL ? '' : rest.slice(e + rule.end.length), lineIndex: i };
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Read one rule against one input text: the run-start function, code only. A rule that is not legal throws (the signed spec was validated, so a bad one
132
+ * is a defect, never a read).
133
+ * @param {PlaceRule} rule @param {string} text @returns {PlaceRead}
134
+ */
135
+ export function readPlace(rule, text) {
136
+ const bad = placeRuleProblem(rule);
137
+ if (bad !== null) throw new Error(`place rule: ${bad}`);
138
+ const sel = selectFirst(rule, text);
139
+ if (!sel.found) return sel;
140
+ if (rule.kind === 'headingBetween') return { found: true, value: sel.cap, lineIndex: sel.lineIndex };
141
+ const m = DATE_FIND.exec(sel.after);
142
+ if (!m || !SHAPES['iso-date'].test(m[0])) return nf('no-date-on-line');
143
+ return { found: true, value: m[0], lineIndex: sel.lineIndex };
144
+ }
145
+
146
+ // ---- drafting: fit a rule ---------------------------------------------------------------------------------------------------------------
147
+
148
+ const CANDIDATE_PREFIXES = ['## [', '## v', '## ', '# [', '# v', '# ', '### [', '### v', '### '];
149
+ const CANDIDATE_ENDS = [']', ' ', EOL];
150
+ /** the frozen candidate list: 9 prefixes crossed with 3 ends, prefix-major (27) */
151
+ export const PLACE_CANDIDATES = Object.freeze(CANDIDATE_PREFIXES.flatMap((prefix) => CANDIDATE_ENDS.map((end) => Object.freeze({ prefix, end }))));
152
+ /** the one skip word of a fitted rule: an "Unreleased" heading above the newest release */
153
+ const FIT_SKIP = Object.freeze(['Unreleased']);
154
+
155
+ /**
156
+ * Fit a place rule to a fact's own words, by CODE, at drafting. The words must be exactly one version (X.Y.Z) or exactly one ISO date; the frozen
157
+ * candidates are walked in order, and the first whose strict first-heading read on the input's own text returns exactly those words wins. Null =
158
+ * no fit (a version and a date together, any other words, another date form, a mixed-level file, no text, or no candidate reading them): the caller
159
+ * refuses the words as week-only exactly as before. Only the two kinds are handled. Pure.
160
+ * @param {string} words @param {string|null|undefined} text
161
+ * @returns {PlaceRule|null}
162
+ */
163
+ export function fitPlaceRule(words, text) {
164
+ if (typeof text !== 'string' || text.trim() === '') return null;
165
+ const w = String(words ?? '').trim();
166
+ const kind = SHAPES.semver.test(w) ? 'headingBetween' : (SHAPES['iso-date'].test(w) ? 'headingDateAfter' : null);
167
+ if (kind === null) return null;
168
+ for (const c of PLACE_CANDIDATES) {
169
+ /** @type {PlaceRule} */
170
+ const rule = { kind, prefix: c.prefix, end: c.end, shape: 'semver', skip: [...FIT_SKIP] };
171
+ const r = readPlace(rule, text);
172
+ if (r.found && r.value === w) return rule;
173
+ }
174
+ return null;
175
+ }
176
+
177
+ /** the only marks a heading piece may carry around its value: heading hashes, brackets, a dash, parentheses and spaces */
178
+ const HEADING_FURNITURE = /^[\s#[\]()\-\u2013\u2014]*$/;
179
+
180
+ /**
181
+ * STRIP (P1b, hamr 2026-11-11): the words of a phrase fact that are a piece of the newest release heading ("## [0.54.1]", "[0.54.1] -", "0.54.1",
182
+ * "2026-11-04", "## [0.54.1] - 2026-11-04") are stripped by code to their value(s). The words hold exactly one version (X.Y.Z, an optional leading v) and/or
183
+ * exactly one ISO date and nothing else but heading marks; each value is fitted with {@link fitPlaceRule} on the input's own text, and when both are
184
+ * present both must sit on the SAME first release heading line. Returns the values (version first) each with its rule, or null: two versions, two dates,
185
+ * any other word, another date form, a value that is not at the first release heading, no text. Pure.
186
+ * @param {string} words @param {string|null|undefined} text
187
+ * @returns {{kind: 'version'|'date', value: string, rule: PlaceRule}[]|null}
188
+ */
189
+ export function fitPlacePhrase(words, text) {
190
+ if (typeof text !== 'string' || text.trim() === '') return null;
191
+ const w = String(words ?? '');
192
+ const dates = w.match(/(?<![\w.])\d{4}-\d{2}-\d{2}(?!\d)/g) ?? [];
193
+ const noDates = w.replace(/(?<![\w.])\d{4}-\d{2}-\d{2}(?!\d)/g, ' ');
194
+ const versions = [...noDates.matchAll(/(?<![\w.])v?(\d+\.\d+\.\d+)(?!\d|\.\d)/g)].map((m) => m[1]);
195
+ if (dates.length > 1 || versions.length > 1 || dates.length + versions.length === 0) return null;
196
+ if (!HEADING_FURNITURE.test(noDates.replace(/(?<![\w.])v?\d+\.\d+\.\d+(?!\d|\.\d)/g, ' '))) return null;
197
+ /** @type {{kind: 'version'|'date', value: string, rule: PlaceRule}[]} */
198
+ const out = [];
199
+ for (const [kind, value] of /** @type {['version'|'date', string][]} */ ([...versions.map((v) => ['version', v]), ...dates.map((d) => ['date', d])])) {
200
+ const rule = fitPlaceRule(value, text);
201
+ if (rule === null) return null;
202
+ out.push({ kind, value, rule });
203
+ }
204
+ if (out.length === 2) {
205
+ const [a, b] = out.map((x) => readPlace(x.rule, text));
206
+ if (!a.found || !b.found || a.lineIndex !== b.lineIndex) return null;
207
+ }
208
+ return out;
209
+ }
210
+
211
+ // ---- the facts a spec carries -----------------------------------------------------------------------------------------------------------
212
+
213
+ /** @param {unknown} v @returns {v is Record<string, any>} */
214
+ const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
215
+
216
+ /**
217
+ * @typedef {{key: string, name: string, source: string, stage: number, part: number, fact: number, place: PlaceRule, phrase: string}} PlaceFact
218
+ */
219
+
220
+ /**
221
+ * Every place-rule fact of a spec, in stage / part / fact order. The key is the stage's name and the fact's name (both stable across the runs of one
222
+ * workflow), so an earlier run's record finds the same fact. Pure.
223
+ * @param {any} spec @returns {PlaceFact[]}
224
+ */
225
+ export function placeFactsOf(spec) {
226
+ /** @type {PlaceFact[]} */
227
+ const out = [];
228
+ const stages = Array.isArray(spec?.closeDecl?.stages) ? spec.closeDecl.stages : [];
229
+ stages.forEach((/** @type {any} */ st, /** @type {number} */ si) => {
230
+ if (!isRec(st) || st.kind !== 'rubric-step' || !isRec(st.params) || !Array.isArray(st.params.parts)) return;
231
+ st.params.parts.forEach((/** @type {any} */ p, /** @type {number} */ pi) => {
232
+ if (!isRec(p) || p.class !== 'fact' || !Array.isArray(p.facts)) return;
233
+ p.facts.forEach((/** @type {any} */ f, /** @type {number} */ fi) => {
234
+ if (!isRec(f) || f.shape !== 'phrase' || !isRec(f.place)) return;
235
+ out.push({ key: `${String(st.name)}/${String(f.name)}`, name: String(f.name), source: String(p.source), stage: si, part: pi, fact: fi, place: /** @type {PlaceRule} */ (f.place), phrase: String(f.phrase) });
236
+ });
237
+ });
238
+ });
239
+ return out;
240
+ }
241
+
242
+ /**
243
+ * A copy of the spec with each place fact's phrase replaced by the value the run read. The input spec is never touched (the signed spec and its hash
244
+ * stay as signed); the copy is for this run's planner and close only. A key with no value is left as the signed drafting words.
245
+ * @param {any} spec @param {Record<string, string>} values place-fact key to the value read @returns {any}
246
+ */
247
+ export function bindPlaceValues(spec, values) {
248
+ const bound = structuredClone(spec);
249
+ for (const f of placeFactsOf(bound)) {
250
+ if (Object.hasOwn(values, f.key)) bound.closeDecl.stages[f.stage].params.parts[f.part].facts[f.fact].phrase = values[f.key];
251
+ }
252
+ return bound;
253
+ }
254
+
255
+ /**
256
+ * The value the drafting words themselves hold for this rule: the first version for headingBetween, the first ISO date for headingDateAfter. Null when
257
+ * the words hold none. Used as "last read" when no earlier run has one.
258
+ * @param {PlaceRule} rule @param {string} words @returns {string|null}
259
+ */
260
+ export function valueInWords(rule, words) {
261
+ const m = rule.kind === 'headingBetween' ? /(?<![\d.])\d+\.\d+\.\d+(?!\d|\.\d)/.exec(words) : /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/.exec(words);
262
+ return m === null ? null : m[0];
263
+ }
264
+
265
+ /**
266
+ * Re-read EVERY place fact against the run's own input text, one by one, before any spend. A row is same / new / notfound. Any notfound stops the run;
267
+ * otherwise the run proceeds with the new words.
268
+ * @param {{fact: PlaceFact, text: string|null, was: string|null}[]} items `text` null = the input could not be read
269
+ * @returns {{proceed: boolean, rows: {key: string, name: string, kind: string, found: boolean, value: string|null, was: string|null, reason: string|null}[], values: Record<string, string>}}
270
+ */
271
+ export function readPlaceRules(items) {
272
+ const rows = items.map(({ fact, text, was }) => {
273
+ const r = text === null ? /** @type {PlaceRead} */ ({ found: false, reason: 'no-file' }) : readPlace(fact.place, text);
274
+ return r.found
275
+ ? { key: fact.key, name: fact.name, kind: fact.place.kind, found: true, value: r.value, was, reason: null }
276
+ : { key: fact.key, name: fact.name, kind: fact.place.kind, found: false, value: null, was, reason: r.reason };
277
+ });
278
+ /** @type {Record<string, string>} */
279
+ const values = {};
280
+ for (const r of rows) if (r.found && r.value !== null) values[r.key] = r.value;
281
+ return { proceed: rows.every((r) => r.found), rows, values };
282
+ }
283
+
284
+ /** the end of the stop words: what the person can do, and that nothing ran or was spent */
285
+ export const STOP_TAIL = 'Reuse workflow and adjust the rules, or check the input. The run did not start. Nothing spent.';
286
+
287
+ /**
288
+ * The words of the $0 stop, plain words from code. Every rule is listed, found or not: "<name>: found <value>" (with "(was <last>)" when the value is
289
+ * new) or "<name>: not found (<plain reason>)", then the closing line. The reasons come only from the closed list.
290
+ * @param {{name: string, found: boolean, value: string|null, was: string|null, reason: string|null}[]} rows @returns {string}
291
+ */
292
+ export function stopWords(rows) {
293
+ const lines = rows.map((r) => {
294
+ if (!r.found) return `${r.name}: not found (${PLAIN_REASONS[/** @type {keyof typeof PLAIN_REASONS} */ (r.reason ?? 'no-file')] ?? 'the input could not be read'})`;
295
+ return `${r.name}: found ${r.value}${r.was !== null && r.was !== r.value ? ` (was ${r.was})` : ''}`;
296
+ });
297
+ return `${lines.join('\n')}\n${STOP_TAIL}`;
298
+ }
299
+
300
+ // ---- the record of a run: what was read, and what the last run read ---------------------------------------------------------------------
301
+
302
+ /** the plain words of the door's refusal when a place-rule run has no record of the values it read */
303
+ export const NO_PLACE_RECORD_WORDS = 'This run has no record of the values it read, so it cannot be checked again. Use Reuse workflow.';
304
+
305
+ /** the spine event a run writes, once, after job-start */
306
+ export const PLACE_EVENT = 'place-rules';
307
+
308
+ /**
309
+ * The values of the LAST `place-rules` record in a run's own events (key to value): what a RESUME of that run rebinds, since a resume does not re-read. Null when
310
+ * there is no record, or any of its rows was not found.
311
+ * @param {any[]} events @returns {Record<string, string>|null}
312
+ */
313
+ export function placeValuesOfEvents(events) {
314
+ const rec = Array.isArray(events) ? events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && Array.isArray(e.rows)) : undefined;
315
+ if (rec === undefined || rec.rows.length === 0 || rec.rows.some((/** @type {any} */ r) => !isRec(r) || r.found !== true || typeof r.value !== 'string')) return null;
316
+ return Object.fromEntries(rec.rows.map((/** @type {any} */ r) => [String(r.key), r.value]));
317
+ }
318
+
319
+ /**
320
+ * What the newest EARLIER run of the same workflow read, per fact key: "last read". `rows` are the run list's rows (file order, oldest first). Candidates are
321
+ * the rows of the same job, newest first, at most {@link LAST_READ_LOOK} of them; the first whose spine holds a `place-rules` record of the same workflow key
322
+ * answers. An unreadable spine is skipped. Empty when there is none (the caller falls back to the drafting words).
323
+ * @param {{rows: {runid: string, job: string, spine: string}[], job: string, workflowKey: string, runid: string}} o @returns {Record<string, string>}
324
+ */
325
+ export function lastPlaceRead({ rows, job, workflowKey, runid }) {
326
+ let looked = 0;
327
+ for (const row of [...rows].reverse()) {
328
+ if (row.runid === runid || row.job !== job || typeof row.spine !== 'string' || !existsSync(row.spine)) continue;
329
+ if (looked >= LAST_READ_LOOK) break;
330
+ looked += 1;
331
+ /** @type {any[]} */
332
+ let events = [];
333
+ try { events = readFileSync(row.spine, 'utf8').split('\n').filter((l) => l.includes(`"${PLACE_EVENT}"`)).map((l) => JSON.parse(l)); } catch { continue; }
334
+ const rec = events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && e.workflowKey === workflowKey && Array.isArray(e.rows));
335
+ if (rec !== undefined) return Object.fromEntries(rec.rows.filter((/** @type {any} */ r) => isRec(r) && r.found === true && typeof r.value === 'string').map((/** @type {any} */ r) => [String(r.key), r.value]));
336
+ }
337
+ return {};
338
+ }
339
+ /** how many earlier runs of the job are looked at for "last read" */
340
+ export const LAST_READ_LOOK = 25;
341
+
342
+ /**
343
+ * The Audit lines of a run's `place-rules` record, in plain words from code: "<name>: <value>" (with "(was <last>)" when the value is new) or
344
+ * "<name>: not found (<reason>)". Null when the run has no record.
345
+ * @param {any[]} events @returns {string[]|null}
346
+ */
347
+ export function placeRuleLines(events) {
348
+ const rec = Array.isArray(events) ? events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && Array.isArray(e.rows)) : undefined;
349
+ if (rec === undefined) return null;
350
+ return rec.rows.filter(isRec).map((/** @type {any} */ r) => {
351
+ const name = String(r.key).split('/').pop();
352
+ if (r.found !== true) return `${name}: not found (${PLAIN_REASONS[/** @type {keyof typeof PLAIN_REASONS} */ (r.reason)] ?? 'the input could not be read'})`;
353
+ return `${name}: ${r.value}${typeof r.was === 'string' && r.was !== r.value ? ` (was ${r.was})` : ''}`;
354
+ });
355
+ }
@@ -88,6 +88,17 @@ export const PROMPT_REGISTERS = Object.freeze([
88
88
  // (F198 item 2), built inline inside `middle` and appended to `w.ask([...])`
89
89
  Object.freeze({ file: 'src/planrun.js', name: 'middle()\'s facts-only "The close\'s own numbers so far" block (inline template, not a const)' }),
90
90
 
91
+ // src/checklist.js — the one check list of a rubric job: the list call's system text and schema descriptions, the drafter's list block, the code-written refusal words
92
+ Object.freeze({ file: 'src/checklist.js', name: 'LEDGER_SYSTEM' }),
93
+ Object.freeze({ file: 'src/checklist.js', name: 'LEDGER_SCHEMA (property descriptions)' }),
94
+ Object.freeze({ file: 'src/checklist.js', name: 'ledgerUserText() (inline template, not a const)' }),
95
+ Object.freeze({ file: 'src/checklist.js', name: 'WEEK_ONLY_WORDS, EMPTY_LIST_WORDS' }),
96
+
97
+ // src/rowedit.js — the drafter's row-edit turn of a rubric job (the check block): system text, the one user message, the revise line, the tool's description
98
+ Object.freeze({ file: 'src/rowedit.js', name: 'ROW_EDIT_SYSTEM' }),
99
+ Object.freeze({ file: 'src/rowedit.js', name: 'ROW_EDIT_REVISE, rowEditUserText() (inline template, not a const)' }),
100
+ Object.freeze({ file: 'src/rowedit.js', name: 'rowEditChannel() (tool description and instruction)' }),
101
+
91
102
  // src/authoring.js — the types-genre close template, interpolated verbatim
92
103
  // into the authoring prompt (src/authorflow.js's assembled system message,
93
104
  // "THE GENRE TEMPLATE" block) — model-facing law for a types-genre