fwdloop 0.37.0 → 0.39.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 (140) hide show
  1. package/README.md +5 -19
  2. package/bin/fwdloop +51 -29
  3. package/package.json +1 -1
  4. package/src/ask.js +70 -148
  5. package/src/audit-fold.js +5 -4
  6. package/src/auditchecks.js +6 -4
  7. package/src/authoring.js +36 -64
  8. package/src/blockasks.js +2 -1
  9. package/src/blockassemble.js +7 -9
  10. package/src/blockdraft.js +2 -2
  11. package/src/blockpick.js +5 -5
  12. package/src/books.js +217 -12
  13. package/src/checkblock.js +25 -55
  14. package/src/checked.js +2 -3
  15. package/src/checklistsign.js +26 -5
  16. package/src/checklook.js +3 -1
  17. package/src/checkpick.js +5 -76
  18. package/src/cited-source.js +4 -4
  19. package/src/citedcheck.js +6 -11
  20. package/src/citedwords.js +9 -8
  21. package/src/closers.js +9 -6
  22. package/src/declaration.js +22 -55
  23. package/src/diary.js +23 -1
  24. package/src/draft-steps.js +11 -1
  25. package/src/drafter.js +28 -23
  26. package/src/draftfiles.js +127 -0
  27. package/src/draftspend.js +165 -17
  28. package/src/flow.js +42 -87
  29. package/src/flowmodel.js +1 -1
  30. package/src/index.js +3 -2
  31. package/src/inside.js +86 -0
  32. package/src/isrec.js +2 -0
  33. package/src/jsonl-append.js +33 -1
  34. package/src/learn.js +1 -1
  35. package/src/learnstore.js +20 -22
  36. package/src/line-checks.js +2 -3
  37. package/src/liveness.js +3 -0
  38. package/src/mcp-use.js +8 -9
  39. package/src/memo.js +13 -16
  40. package/src/minrule.js +16 -0
  41. package/src/model-step.js +3 -3
  42. package/src/page-words.js +8 -0
  43. package/src/pageask.js +8 -3
  44. package/src/pagebits.js +8 -1
  45. package/src/pagedropwords.js +1 -1
  46. package/src/pagerules.js +6 -3
  47. package/src/panel/author.js +121 -78
  48. package/src/panel/authorcard.js +21 -8
  49. package/src/panel/authorflows.js +3 -3
  50. package/src/panel/authorresume.js +3 -3
  51. package/src/panel/authorstart.js +15 -16
  52. package/src/panel/authortrigger.js +43 -70
  53. package/src/panel/data.js +125 -168
  54. package/src/panel/index.html +154 -63
  55. package/src/panel/jobgrid.js +3 -7
  56. package/src/panel/result.js +7 -10
  57. package/src/panel/resume.js +4 -3
  58. package/src/panel/scheduler.js +9 -9
  59. package/src/panel/server.js +8 -4
  60. package/src/panel/spawn.js +22 -11
  61. package/src/panel/tickets.js +2 -2
  62. package/src/pickrecord.js +51 -31
  63. package/src/placerule.js +3 -4
  64. package/src/planrebuild.js +19 -19
  65. package/src/primitives.js +1 -1
  66. package/src/provider.js +1 -1
  67. package/src/reasons.js +25 -0
  68. package/src/report.js +2 -1
  69. package/src/runfile.js +26 -2
  70. package/src/runner.js +57 -105
  71. package/src/runvalues.js +47 -24
  72. package/src/schedule-choices.js +41 -0
  73. package/src/schedule-shape.js +39 -0
  74. package/src/schedule.js +9 -8
  75. package/src/setup.js +20 -36
  76. package/src/shaperows.js +2 -2
  77. package/src/sheet-record.js +1 -2
  78. package/src/sheetblock.js +3 -4
  79. package/src/sheetbuild.js +5 -5
  80. package/src/sheetchecks.js +1 -2
  81. package/src/sheetclaims.js +1 -2
  82. package/src/sheetoffer.js +1 -1
  83. package/src/sheetrun.js +5 -7
  84. package/src/summary-words.js +2 -1
  85. package/src/thinking.js +5 -2
  86. package/src/ticketrows.js +8 -30
  87. package/src/trigger-clock.js +9 -23
  88. package/src/trigger-files.js +30 -22
  89. package/src/trigger-tickets.js +15 -14
  90. package/src/try-checks.js +2 -1
  91. package/src/types.js +2 -0
  92. package/types/ask.d.ts +25 -20
  93. package/types/authoring.d.ts +8 -42
  94. package/types/blockassemble.d.ts +0 -1
  95. package/types/blockpick.d.ts +1 -1
  96. package/types/books.d.ts +256 -4
  97. package/types/checkblock.d.ts +2 -25
  98. package/types/checklist.d.ts +3 -3
  99. package/types/checklistsign.d.ts +7 -0
  100. package/types/checkpick.d.ts +0 -21
  101. package/types/citedwords.d.ts +7 -4
  102. package/types/closers.d.ts +1 -0
  103. package/types/declaration.d.ts +4 -14
  104. package/types/diary.d.ts +14 -1
  105. package/types/draft-steps.d.ts +7 -0
  106. package/types/drafter.d.ts +3 -2
  107. package/types/draftfiles.d.ts +89 -0
  108. package/types/draftspend.d.ts +74 -0
  109. package/types/flow.d.ts +32 -54
  110. package/types/index.d.ts +3 -3
  111. package/types/inside.d.ts +58 -0
  112. package/types/isrec.d.ts +1 -0
  113. package/types/jsonl-append.d.ts +20 -0
  114. package/types/learnstore.d.ts +0 -2
  115. package/types/liveness.d.ts +1 -0
  116. package/types/minrule.d.ts +6 -0
  117. package/types/page-words.d.ts +6 -0
  118. package/types/pageask.d.ts +2 -0
  119. package/types/pagebits.d.ts +3 -0
  120. package/types/pagerules.d.ts +1 -0
  121. package/types/panel/author.d.ts +7 -3
  122. package/types/panel/authorcard.d.ts +0 -6
  123. package/types/panel/authorflows.d.ts +4 -4
  124. package/types/panel/authortrigger.d.ts +16 -2
  125. package/types/panel/data.d.ts +36 -11
  126. package/types/panel/spawn.d.ts +18 -2
  127. package/types/pickrecord.d.ts +29 -0
  128. package/types/reasons.d.ts +23 -0
  129. package/types/runfile.d.ts +14 -0
  130. package/types/runner.d.ts +6 -38
  131. package/types/runvalues.d.ts +17 -2
  132. package/types/schedule-choices.d.ts +9 -0
  133. package/types/schedule-shape.d.ts +15 -0
  134. package/types/sheetbuild.d.ts +1 -1
  135. package/types/sheetclaims.d.ts +0 -1
  136. package/types/thinking.d.ts +1 -0
  137. package/types/ticketrows.d.ts +0 -9
  138. package/types/trigger-clock.d.ts +3 -2
  139. package/types/trigger-files.d.ts +15 -4
  140. package/types/types.d.ts +8 -0
package/src/books.js CHANGED
@@ -21,7 +21,7 @@
21
21
  import { mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
- import { readFileInside, readdirInside } from './flow.js';
24
+ import { readFileInside, readdirInside } from './inside.js';
25
25
  import { appendRow } from './jsonl-append.js';
26
26
  import { TRIGGER_RECORD_FILE } from './trigger-line.js';
27
27
 
@@ -30,6 +30,15 @@ function appendLine(filePath, row) {
30
30
  appendRow(filePath, row);
31
31
  }
32
32
 
33
+ /**
34
+ * M20 am3 item 5: the ONE place the consumed-answer file name is spelled: `answer.<askId>.consumed.json`, what the resume
35
+ * renames `answer.json` to (F44). `askIdOfConsumedName` is its inverse (null for any other name, `answer.stale.<n>.json` included).
36
+ * @param {string} askId
37
+ */
38
+ export const consumedAnswerName = (askId) => `answer.${askId}.consumed.json`;
39
+ /** @param {string} name @returns {string|null} */
40
+ export const askIdOfConsumedName = (name) => /^answer\.(.+)\.consumed\.json$/.exec(name)?.[1] ?? null;
41
+
33
42
  /**
34
43
  * M4c piece 1: the ONE writer of a run dir's `pids.jsonl` — append-only, never
35
44
  * rewritten, not a book the arbiter reads. One row per process that works on
@@ -50,6 +59,39 @@ export function readPidRows(runDir) {
50
59
  return readLines(runDir, 'pids.jsonl');
51
60
  }
52
61
 
62
+ /**
63
+ * M20 am3b item 1: the ONE reader of a run's saved answer, `answer.json` (what `answerAsk` writes; the resume consumes it by renaming it away). Through the safe
64
+ * gateway (a symlink or a file outside the folder is refused). It parses nothing else's words: each caller keeps its own refusal sentence and reads these fields.
65
+ * `broken` = no JSON object, no `askId`, or no readable `answeredAt`: the file is not a usable answer for any ask. `value` is the parsed JSON as it is (any shape),
66
+ * `parseError` the parser's message when the text is not JSON, `isObject` says `value` is a plain JSON object. `decision` is the file's own word, not normalised.
67
+ * @param {string} runDir
68
+ * @returns {{ok: false, missing: boolean, red: string}
69
+ * | {ok: true, value: any, parseError: string|null, isObject: boolean, askId: string|null, decision: string|null, answeredAt: string|null, broken: boolean}}
70
+ */
71
+ export function readSavedAnswer(runDir) {
72
+ const r = readFileInside(runDir, 'answer.json');
73
+ if (!r.ok) return r.missing ? { ok: false, missing: true, red: 'answer.json is missing' } : { ok: false, missing: false, red: r.red };
74
+ const text = r.text;
75
+ let value;
76
+ try { value = JSON.parse(text); } catch (err) {
77
+ return { ok: true, value: undefined, parseError: err.message, isObject: false, askId: null, decision: null, answeredAt: null, broken: true };
78
+ }
79
+ const isObject = value !== null && typeof value === 'object' && !Array.isArray(value);
80
+ const askId = isObject && typeof value.askId === 'string' && value.askId.length > 0 ? value.askId : null;
81
+ const answeredAt = isObject && typeof value.answeredAt === 'string' ? value.answeredAt : null;
82
+ return {
83
+ ok: true, value, parseError: null, isObject, askId,
84
+ decision: isObject && typeof value.decision === 'string' ? value.decision : null,
85
+ answeredAt,
86
+ broken: !isObject || askId === null || Number.isNaN(Date.parse(answeredAt ?? '')),
87
+ };
88
+ }
89
+
90
+ /** Has a process started on this run? (the run wrote its first pid row; a run with none is still starting, or never started) @param {string} runDir */
91
+ export function processStarted(runDir) {
92
+ return readPidRows(runDir).length > 0;
93
+ }
94
+
53
95
  /**
54
96
  * Raw read-back of one JSONL book, one writer's own sibling reader (M4a
55
97
  * piece 2, docs/wiki/the-module-ladder.md M4a scope item 2: "one reader per
@@ -274,11 +316,33 @@ export function auditRowAt(row) {
274
316
  * Read back every row `appendAudit` has written for one run, in file order
275
317
  * (append order — never re-sorted). `[]` when the file doesn't exist yet
276
318
  * (a run that hasn't made an attempt), never a thrown error.
319
+ * `{ strict: true }` is the one named mode for the money sum: `{ok:true, rows}` or `{ok:false, red}` on a torn line.
277
320
  * @param {string} runDir
278
- * @returns {any[]}
321
+ * @param {{strict?: boolean}} [opts]
322
+ * @returns {any}
279
323
  */
280
- export function readAudit(runDir) {
281
- return readLines(runDir, 'audit.jsonl');
324
+ export function readAudit(runDir, { strict = false } = {}) {
325
+ if (!strict) return readLines(runDir, 'audit.jsonl');
326
+ // strict mode (M20 am3 item 11): the money sum must balance, so a torn line is a red, never skipped; a missing or refused file is no rows
327
+ const result = readFileInside(runDir, 'audit.jsonl');
328
+ if (!result.ok) return { ok: true, rows: [] };
329
+ const rows = [];
330
+ for (const line of result.text.split('\n')) {
331
+ if (line.trim().length === 0) continue;
332
+ try { rows.push(JSON.parse(line)); } catch (err) { return { ok: false, red: `audit.jsonl line is not valid JSON — ${err.message}` }; }
333
+ }
334
+ return { ok: true, rows };
335
+ }
336
+
337
+ /**
338
+ * The one reader of a run's `trigger.json` (why it started): an object, or `null` (a hand run, a missing, refused or unreadable file, a non-object).
339
+ * @param {string} runDir
340
+ * @returns {Record<string, any>|null}
341
+ */
342
+ export function readTriggerRecord(runDir) {
343
+ const f = readFileInside(runDir, TRIGGER_RECORD_FILE);
344
+ if (!f.ok) return null;
345
+ try { const j = JSON.parse(f.text); return j && typeof j === 'object' ? j : null; } catch { return null; }
282
346
  }
283
347
 
284
348
  /**
@@ -291,10 +355,8 @@ export function readAudit(runDir) {
291
355
  export function appendHistory(flowDir, row) {
292
356
  checkCostField(row, 'spentUsd', 'appendHistory');
293
357
  // M9 (am2 item 1): a run a trigger started says so in its history row, read from the record the start wrote into the run's own folder
294
- const rec = typeof row.runId === 'string' && row.trigger === undefined ? readFileInside(join(flowDir, 'runs', row.runId), TRIGGER_RECORD_FILE) : null;
295
- let trigger;
296
- if (rec !== null && rec.ok) { try { trigger = JSON.parse(rec.text); } catch { trigger = undefined; } }
297
- appendLine(join(flowDir, 'history.jsonl'), trigger === undefined ? row : { ...row, trigger });
358
+ const trigger = typeof row.runId === 'string' && row.trigger === undefined ? readTriggerRecord(join(flowDir, 'runs', row.runId)) : null;
359
+ appendLine(join(flowDir, 'history.jsonl'), trigger === null ? row : { ...row, trigger });
298
360
  }
299
361
 
300
362
  /**
@@ -308,8 +370,92 @@ export function readHistory(flowDir) {
308
370
  return readLines(flowDir, 'history.jsonl');
309
371
  }
310
372
 
311
- /** The two outcomes a run can be continued from (M4e amendment 4 item 4): the runner leaves `halt.json` for them. */
312
- export const HALT_OUTCOMES = Object.freeze(['cap-halt', 'stopped']);
373
+ export const HALT_FILE = 'halt.json';
374
+
375
+ /**
376
+ * M20 am1 item 1: the ONE table of endings. Every history outcome and every audit verdict fwd writes is a key; the flags say what it
377
+ * means, and every reader asks a helper below (never its own list of words):
378
+ * good the run or try passed resumable `halt.json` is left, the run can be continued
379
+ * notFailed not a failure of the job (complete, a stop, a cap halt, a rerun, an expired ask, a skipped ticket)
380
+ * noise the instrument failed, not the work (learnings set the run aside)
381
+ * blocked a verdict that stopped a step, the Run tab's "blocked" line
382
+ * open the Audit's `·` mark: waiting / a human note, not yet resolved either way
383
+ * waiting a step whose last row is this is parked stopNote a Stop's own note row, never a try
384
+ * humanNo the human's own no (the ask fold's `✗`) redTry a try that said the output was wrong
385
+ * tryVerdict a step's try with a verdict on its output spendFloor a halt whose spend can be a floor
386
+ * draftRow a verdict a drafting row of the Audit can carry (anything else reads not-done)
387
+ * notRunEnd not an end of a run (a pause, a failed stop, a skipped ticket): learnings wait
388
+ * word the Runs list's bold word for it (`null` = none: a run the human ended with rerun)
389
+ * wordUnresumed its word when the run cannot be continued (M20 am1 item 9: a cap-halt with no usable halt.json reads "capped")
390
+ * Outcome (history.jsonl) and verdict (audit.jsonl) are not split: one word means one thing on either book.
391
+ * Not here, by design: the scheduler's own words (busy, monthly-exhausted, refused fire), the closers' verdicts (done, crash,
392
+ * unparseable), and the Run tab's ending sentences (src/summary-words.js stays their one owner).
393
+ */
394
+ export const ENDINGS = Object.freeze({
395
+ complete: { good: true, notFailed: true, word: 'passed' },
396
+ skipped: { notFailed: true, notRunEnd: true, word: 'skipped' },
397
+ stopped: { resumable: true, notFailed: true, open: true, humanNo: true, word: 'stopped' },
398
+ 'cap-halt': { resumable: true, notFailed: true, blocked: true, spendFloor: true, word: 'stopped', wordUnresumed: 'capped' },
399
+ rerun: { notFailed: true, word: null },
400
+ 'ask-expired': { notFailed: true, blocked: true, open: true, word: 'expired' },
401
+ 'ask-timeout': { blocked: true, open: true, word: 'failed' },
402
+ refused: { blocked: true, open: true, waiting: true, word: 'failed' },
403
+ red: { blocked: true, humanNo: true, redTry: true, tryVerdict: true, draftRow: true, word: 'failed' },
404
+ 'not-done': { blocked: true, redTry: true, tryVerdict: true, word: 'failed' },
405
+ 'provider-red': { blocked: true, noise: true, spendFloor: true, word: 'failed' },
406
+ 'pricing-red': { blocked: true, spendFloor: true, word: 'failed' },
407
+ 'close-casualty': { blocked: true, noise: true, word: 'failed' },
408
+ 'preflight-red': { word: 'failed' },
409
+ 'struck-out': { word: 'failed' },
410
+ 'attempt-fallback': { word: 'failed' },
411
+ 'redo-halt': { word: 'failed' },
412
+ 'stop-failed': { notRunEnd: true, word: 'failed' },
413
+ green: { good: true, tryVerdict: true, draftRow: true },
414
+ hitl: { good: true, tryVerdict: true },
415
+ softgreen: { tryVerdict: true }, // fwd writes no such verdict today; the learnings read audits shaped like bareloop's, so it stays a try
416
+ paused: { open: true, waiting: true, notRunEnd: true },
417
+ 'ask-reopened': { open: true },
418
+ 'lock-removed': { open: true },
419
+ 'stop-asked': { open: true, stopNote: true },
420
+ 'stop-not-honoured': { open: true, stopNote: true },
421
+ 'stale-answer-ignored': {},
422
+ 'answer-after-run': {},
423
+ });
424
+
425
+ /** @param {unknown} word @param {string} flag */
426
+ const endingHas = (word, flag) => typeof word === 'string' && Object.hasOwn(ENDINGS, word) && /** @type {any} */ (ENDINGS)[word][flag] === true;
427
+ export const isGoodEnding = (/** @type {unknown} */ w) => endingHas(w, 'good');
428
+ /** a history outcome that is a failure of the job; a word the table does not know counts as one */
429
+ export const isFailedEnding = (/** @type {unknown} */ w) => !endingHas(w, 'notFailed');
430
+ export const isNoiseEnding = (/** @type {unknown} */ w) => endingHas(w, 'noise');
431
+ export const isBlockedEnding = (/** @type {unknown} */ w) => endingHas(w, 'blocked');
432
+ export const isOpenEnding = (/** @type {unknown} */ w) => endingHas(w, 'open');
433
+ export const isWaitingEnding = (/** @type {unknown} */ w) => endingHas(w, 'waiting');
434
+ export const isStopNote = (/** @type {unknown} */ w) => endingHas(w, 'stopNote');
435
+ export const isHumanNo = (/** @type {unknown} */ w) => endingHas(w, 'humanNo');
436
+ export const isRedTry = (/** @type {unknown} */ w) => endingHas(w, 'redTry');
437
+ /**
438
+ * M20 am3g item 22: the ONE rule for why a run is red: the log's own `red` when it is a non-empty string, else the LAST red audit row as `<step>: <gap>` (a step can fail,
439
+ * redo and fail again differently; the most recent stop is where the run sits now), else null. The Run tab and the Result tab ask it and keep their own guards and words.
440
+ * @param {any} logJson the run's log.json (or null) @param {any[]} auditRows @returns {string|null}
441
+ */
442
+ export function redWhyOf(logJson, auditRows) {
443
+ if (typeof logJson?.red === 'string' && logJson.red.length > 0) return logJson.red;
444
+ const row = auditRows.findLast((r) => isRedTry(r.verdict));
445
+ return row ? `${row.step}: ${row.gap}` : null;
446
+ }
447
+ export const isTryVerdict = (/** @type {unknown} */ w) => endingHas(w, 'tryVerdict');
448
+ export const isSpendFloorEnding = (/** @type {unknown} */ w) => endingHas(w, 'spendFloor');
449
+ export const isDraftRowVerdict = (/** @type {unknown} */ w) => endingHas(w, 'draftRow');
450
+ export const isNotRunEnd = (/** @type {unknown} */ w) => endingHas(w, 'notRunEnd');
451
+ /** The outcomes a run can be continued from (M4e amendment 4 item 4): the runner leaves `halt.json` for them. */
452
+ export const isResumableEnding = (/** @type {unknown} */ w) => endingHas(w, 'resumable');
453
+ /** the Runs list's bold word for an ending (`null` for none); `resumable` false asks the word of a run that cannot be continued @param {string} w @param {boolean} [resumable] @returns {string|null} */
454
+ export function endingWord(w, resumable = true) {
455
+ if (!Object.hasOwn(ENDINGS, w)) return null;
456
+ const e = /** @type {any} */ (ENDINGS)[w];
457
+ return resumable === false && typeof e.wordUnresumed === 'string' ? e.wordUnresumed : e.word ?? null;
458
+ }
313
459
 
314
460
  /**
315
461
  * The ONE rule for "how did this run end": the LAST history row of the run (a run that was stopped or cap-halted and
@@ -323,8 +469,67 @@ export const HALT_OUTCOMES = Object.freeze(['cap-halt', 'stopped']);
323
469
  export function endRow(historyRows, runDir, runId) {
324
470
  let last = null;
325
471
  for (const r of historyRows) if (r && r.runId === runId) last = r;
326
- if (last === null || !HALT_OUTCOMES.includes(last.outcome)) return last;
472
+ if (last === null || !isResumableEnding(last.outcome)) return last;
327
473
  const names = readdirInside(runDir, '.');
328
- const continuing = !names.includes('halt.json') && names.some((n) => /^halt\.\d+\.consumed\.json$/.test(n));
474
+ const continuing = !names.includes('halt.json') && haltConsumedCount(runDir) > 0;
329
475
  return continuing ? null : last;
330
476
  }
477
+
478
+ /** The one place `halt.<n>.consumed.json` is named: how many a run holds, and the name the next continue renames halt.json to. @param {string} runDir */
479
+ export function haltConsumedCount(runDir) {
480
+ return readdirInside(runDir, '.').filter((n) => /^halt\.\d+\.consumed\.json$/.test(n)).length;
481
+ }
482
+ /** @param {string} runDir */
483
+ export function nextHaltConsumedName(runDir) {
484
+ return `halt.${haltConsumedCount(runDir) + 1}.consumed.json`;
485
+ }
486
+
487
+ /** The one reader of halt.json (the run is waiting = the file EXISTS, parse or not: see {@link haltFileExists}): `{ok:true, halt}`, `{ok:false, missing:true}` (not resumable), or `{ok:false, red}`. @param {string} runDir */
488
+ export function readHaltRecord(runDir) {
489
+ const r = readFileInside(runDir, HALT_FILE);
490
+ if (!r.ok) return r.missing ? { ok: false, missing: true } : { ok: false, red: `halt.json — ${r.red}` };
491
+ try { return { ok: true, halt: JSON.parse(r.text) }; } catch (err) { return { ok: false, red: `halt.json is not valid JSON — ${err.message}` }; }
492
+ }
493
+
494
+ /**
495
+ * `writeLog`'s own sibling reader (M4a piece 2, docs/wiki/the-module-
496
+ * ladder.md M4a scope item 2: "one reader per book") — `null` when the run
497
+ * hasn't reached an exit path yet (still running, or parked before any
498
+ * halt/complete), or the file is present but not valid JSON (a torn write),
499
+ * never a thrown error.
500
+ * @param {string} runDir
501
+ * @returns {any|null}
502
+ */
503
+ export function readLog(runDir) {
504
+ const result = readFileInside(runDir, 'log.json');
505
+ if (!result.ok) return null;
506
+ try { return JSON.parse(result.text); } catch { return null; }
507
+ }
508
+
509
+ /**
510
+ * `state.json`'s own sibling reader (same rule as {@link readLog}) — `null`
511
+ * when the run has never parked, or the file is present but not valid JSON. `{ strict: true }` (Resume) returns
512
+ * `{ok:true, state}`, `{ok:false, missing:true}` or `{ok:false, red}` instead.
513
+ * @param {string} runDir
514
+ * @param {{strict?: boolean}} [opts]
515
+ * @returns {any}
516
+ */
517
+ export function readRunState(runDir, { strict = false } = {}) {
518
+ const result = readFileInside(runDir, 'state.json');
519
+ if (strict) {
520
+ // strict mode (M20 am3 item 11, Resume): missing, refused and torn stay three different words
521
+ if (!result.ok) return result.missing ? { ok: false, missing: true } : { ok: false, red: result.red };
522
+ try { return { ok: true, state: JSON.parse(result.text) }; } catch (err) { return { ok: false, red: `is not valid JSON — ${err.message}` }; }
523
+ }
524
+ if (!result.ok) return null;
525
+ try { return JSON.parse(result.text); } catch { return null; }
526
+ }
527
+
528
+ /**
529
+ * "Is this run waiting to be resumed?" as the panel's start watcher has always read it: a `halt.json` that EXISTS means
530
+ * waiting, even when it does not parse (unlike {@link readHaltRecord}, where a torn file is a red). One name for that rule.
531
+ * @param {string} runDir
532
+ */
533
+ export function haltFileExists(runDir) {
534
+ return readFileInside(runDir, HALT_FILE).ok;
535
+ }
package/src/checkblock.js CHANGED
@@ -15,15 +15,16 @@
15
15
  // counts built into rubric-step parts; a repo job (`repo` option) holds `~` rule rows the write fence keeps (or that the person answers about), `!` rows for the drafter's catalogue work stages, and the same `$` rows.
16
16
  // The same rows store, the same asks, the same Drop/carry, the same signedRows and closeView serve both.
17
17
  import { globToPrefix } from './globprefix.js';
18
- import { countExact, countPhrase } from './pagebits.js';
18
+ import { countExact, countPhrase, isAmountShape, isPhraseShape, isLegalCount } from './pagebits.js';
19
19
  import { checkFactWords, keptSetOf } from './factwords.js';
20
20
  import { isCountable, keepOrDrop, countCheck, obviousCheck, partOfPick, plainWords } from './blockpick.js';
21
21
  import { dropRows, dropSentence } from './pagedropwords.js';
22
22
  import { phraseInNoResult, asSeenOf } from './pagedry.js';
23
23
  import { boundInWords, rubricStepShapeReds, stageKeyOf, guardKeyOf, FENCE_KEY, defaultCitedText, defaultNoteText, readLimit, holdsManyBounds, NEGATING_RE, WHY_OTHER_CURRENCY } from './rubricstep.js';
24
- import { validReading } from './pagerules.js';
24
+ import { validReading, canReadLimit } from './pagerules.js';
25
25
  import { weekOnly, weekTokens, WEEK_ONLY_WORDS, MAX_BANG } from './checklist.js';
26
26
  import { fitPlacePhrase } from './placerule.js';
27
+ import { isRowChoice } from './pickrecord.js';
27
28
  import { ruleWords } from './pageask.js';
28
29
  import { SIGNED_ROW_FIELDS } from './declaredclose.js';
29
30
  import { factSentence, countSentence, factsOfLook } from './citedcheck.js';
@@ -33,6 +34,7 @@ import { sheetCheckName, sheetPlainText, coversWords } from './sheetblock.js';
33
34
  import { sheetCheckBody, sheetRowKey } from './sheetrows.js';
34
35
  import { shapeRowKey, shapeDefaultKey, shapeFieldText, buildShapePart, itemCountOf } from './shaperows.js';
35
36
  import { fieldSpec } from './shapebuild.js';
37
+ import { REASON } from './reasons.js';
36
38
 
37
39
  /**
38
40
  * A row. `kind`: rule, fact, phrase, count, cited, numbers, floor. `by`: you (`~`), agent (`!`), default (`$`). A `~` row may carry `links` (the look's facts tied to it),
@@ -44,6 +46,8 @@ import { fieldSpec } from './shapebuild.js';
44
46
 
45
47
  /** the four row edits an AI reply may hold */
46
48
  export const EDIT_OPS = Object.freeze(['add', 'reading', 'pick', 'not-checkable', 'fence']);
49
+ /** M20 am8: the one question "is this check row's kind a fact or a phrase" (a page-word row, not a count) @param {unknown} kind @returns {boolean} */
50
+ export const isFactKind = (kind) => kind === 'fact' || kind === 'phrase';
47
51
 
48
52
  const norm = (/** @type {unknown} */ t) => String(t ?? '').toLowerCase().replace(/\s+/g, ' ').trim();
49
53
  const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -76,33 +80,6 @@ const numberIn = (text, n) => {
76
80
  };
77
81
  const wordSet = (/** @type {unknown} */ t) => new Set(norm(t).match(/[\p{L}\p{N}]+/gu) ?? []);
78
82
 
79
- // fwd (F251): what a row says when its check cannot ride a line that has no guardrail of its own (the class of a line comes from its guardrail); one writer, here (blockassemble.js re-exports it)
80
- export const NO_GUARDRAIL_WORDS = 'This line has no guardrail of yours, so a check on it cannot be signed; you judge it at Accept.';
81
-
82
- /** the plain reasons code gives, in one place (the card, the Job tab and the Audit read them from the row) */
83
- export const REASON = Object.freeze({
84
- left: 'You chose to leave it Not checked, so you judge it at Accept.',
85
- nothingOnPage: 'Your own words are on the line; the machine has no check for them, so you judge it at Accept.',
86
- noRule: 'No rule can check this, so you judge it at Accept.',
87
- waitingPick: 'waiting for your answer on the proposed check',
88
- waitingReading: 'waiting for your answer on the reading',
89
- onePerLine: 'this line finds facts, so it has no text to quote',
90
- manyInputs: 'the job has more than one input and code cannot pick which one the claims quote',
91
- oneSidedTime: 'a time limit the AI proposes must be a range, so you judge it at Accept.',
92
- countNeedsFact: 'a result count needs a fact to count; this line has none',
93
- countNeedsSuggested: 'a result count needs a fact to count; add the suggested fact on this line to count its results',
94
- lookNoWords: "the page does not hold the words of the look's fact for this rule",
95
- afterLast: 'no more tries: Start over (rows are never changed by the AI after the last try)',
96
- noPick: 'No check was picked for it, so you judge it at Accept.',
97
- itemCountByRule: 'your rule on this line sets the item count',
98
- negated: 'it says what is not needed, so there is nothing to check',
99
- dropped: 'You dropped it.',
100
- suggested: 'Suggested: not in your job, so it is not checked unless you add it.',
101
- sheetLine: 'this line reads a sheet and its rules are checked by the sheet checks, so a row edit about it is not used',
102
- sheetFacts: 'this line reads a sheet, so it is checked by its sheet checks and not by page facts',
103
- columnRule: "this rule only names a column; the agent's checks on this line use it",
104
- });
105
-
106
83
  /** the card's rows: which rows show, and their key, line, tag, state and reason. NO words: the words of a row are the plan reader's (src/checkrows.js `planCard`), one writer (M19 am6 item 4). @param {Row[]} rows */
107
84
  export function renderCard(rows) {
108
85
  // fwd keeps: the card draws no floor row (and there is no prose row) today
@@ -410,7 +387,7 @@ export class CheckBlock {
410
387
  match() {
411
388
  // live draft 3 (hamr 2026-11-13: "anything not in your original job that code can check goes to Suggested"): a `!` fact whose page words are longer than what the job says ("Boston Logan International
412
389
  // Airport" for the job's "Boston") says the JOB's word; the row is then job-derived (inJob below, the one owner) and its phrase check uses that word
413
- if (this.split) for (const r of this.rows) if (this.isBang(r) && (r.kind === 'fact' || r.kind === 'phrase')) this.takeJobWord(r);
390
+ if (this.split) for (const r of this.rows) if (this.isBang(r) && isFactKind(r.kind)) this.takeJobWord(r);
414
391
  for (const r of this.rows) {
415
392
  r.can = null;
416
393
  if (r.kind === 'floor') continue;
@@ -418,7 +395,7 @@ export class CheckBlock {
418
395
  else if (r.lookWhy && r.kind === 'fact' && !r.words.length) r.can = { ok: false, why: r.lookWhy };
419
396
  else if (r.kind === 'stage') r.can = r.refusal ? { ok: false, why: r.said } : { ok: true, how: 'stage' };
420
397
  else if (r.kind === 'rule') this.matchRule(r);
421
- else if (r.kind === 'fact' || r.kind === 'phrase') this.matchBang(r);
398
+ else if (isFactKind(r.kind)) this.matchBang(r);
422
399
  else if (r.kind === 'count') this.matchCount(r);
423
400
  else if (r.kind === 'sheet') r.can = { ok: true, how: 'sheet' };
424
401
  }
@@ -469,7 +446,7 @@ export class CheckBlock {
469
446
  if (r.kind === 'count') return [r.min, r.max].filter((x) => Number.isInteger(x)).some((n) => numberIn(said, n));
470
447
  // a money, time, number or date fact the person asked for BY NAME ("the release heading") is in the job too: the look's page words rarely echo the job's own words. A phrase or place is job-derived
471
448
  // only when its own words are in the person's text: a name the AI gave it is no proof (hamr 2026-11-15, live run mwi76vh8: "friendly" for "Select flight")
472
- return (r.words ?? []).some((/** @type {string} */ w) => inText(said, w)) || (r.kind === 'fact' && r.shape !== 'phrase' && r.shape !== 'place' && typeof r.name === 'string' && inText(said, r.name));
449
+ return (r.words ?? []).some((/** @type {string} */ w) => inText(said, w)) || (r.kind === 'fact' && !isPhraseShape(r.shape) && typeof r.name === 'string' && inText(said, r.name));
473
450
  }
474
451
 
475
452
  /**
@@ -512,7 +489,7 @@ export class CheckBlock {
512
489
  if (isCountable(r.text)) { this.matchCountRule(r); return; }
513
490
  // F-a (hamr 2026-11-13): a rule that carries a negation ("nonstop is not mandatory") says what is NOT needed; its words can never give a phrase bound ("must say"). The one negation reader is NEGATING_RE.
514
491
  const negated = NEGATING_RE.test(r.text);
515
- const isPhrase = (/** @type {any} */ l) => l.shape === 'phrase' || l.shape === 'place';
492
+ const isPhrase = (/** @type {any} */ l) => isPhraseShape(l.shape);
516
493
  if (negated && (r.links ?? []).length && (r.links ?? []).every(isPhrase)) { r.can = { ok: false, why: REASON.negated }; return; }
517
494
  const links = (r.links ?? []).filter((/** @type {any} */ l) => !(negated && isPhrase(l)) && l.words.some((/** @type {string} */ w) => proved(this.textOf(l.source), w)));
518
495
  const said = this.said(r.line);
@@ -521,7 +498,7 @@ export class CheckBlock {
521
498
  for (const l of links) {
522
499
  let reading = l.reading;
523
500
  let ownWords = false;
524
- if (l.shape === 'money' || l.shape === 'time') {
501
+ if (canReadLimit(l.shape)) {
525
502
  // the person's words win (hamr 2026-11-13): code's reading of the `~` words beats the look's and the AI's; theirs is used only when code cannot read the words
526
503
  const rd = this.wordsReading(l, r.text);
527
504
  // fwdloop run walk-m16-flights run-1: "under $150" on a euro fact fell back to the look's reading and checked 150 euros; a bound in another currency than the page fact is never replaced by the look's or the AI's reading
@@ -645,7 +622,7 @@ export class CheckBlock {
645
622
  }
646
623
  // a suggestion code has not built stays off the card (Audit only, F-b); a held one is trialled: shown under Suggested only when code has proved it builds (hamr 2026-11-13)
647
624
  for (const r of this.rows.filter((x) => x.held && x.kind !== 'sheet' && x.kind !== 'shape')) this.trialOffer(r);
648
- if (this.split) for (const r of this.rows) r.hidden = this.isBang(r) && r.state === 'not-checked' && !r.lookWhy && r.reason !== NO_GUARDRAIL_WORDS;
625
+ if (this.split) for (const r of this.rows) r.hidden = this.isBang(r) && r.state === 'not-checked' && !r.lookWhy;
649
626
  this.closeCache = { stages, parts, map };
650
627
  return this.closeCache;
651
628
  }
@@ -659,7 +636,7 @@ export class CheckBlock {
659
636
  r.held = false;
660
637
  /** @type {any[]} */ const parts = [];
661
638
  /** @type {string[][]} */ const rows = [];
662
- this.buildLine(l, parts, rows, new Set(), true);
639
+ this.buildLine(l, parts, rows, new Set());
663
640
  const ok = r.state === 'built';
664
641
  const reason = r.reason;
665
642
  const i = rows.findIndex((k) => k.includes(r.key));
@@ -672,11 +649,8 @@ export class CheckBlock {
672
649
  else { r.offer = null; r.held = false; r.state = 'not-checked'; r.reason = String(reason ?? 'not checked'); }
673
650
  }
674
651
 
675
- // fwd (F251): `offer` = the Suggested trial (trialOffer): it asks whether code can build the row, not whether the line can sign it, so the no-guardrail gate below is skipped
676
652
  /** one line's parts: a pick part per count rule, ONE fact part carrying every fact row of the line (and its result count), then the `$` defaults */
677
- buildLine(/** @type {{n: number, text: string}} */ l, /** @type {any[]} */ lineParts, /** @type {string[][]} */ lineRows, /** @type {Set<number>} */ factLines, /** @type {boolean} */ offer = false) {
678
- // fwd (F251): a line with no ~ guardrail of the person's own holds no signable check; one decider, here
679
- const unguarded = this.ruleRows(l.n).length === 0 && !this.isSheetLine(l.n);
653
+ buildLine(/** @type {{n: number, text: string}} */ l, /** @type {any[]} */ lineParts, /** @type {string[][]} */ lineRows, /** @type {Set<number>} */ factLines) {
680
654
  let foundFact = false;
681
655
  /** @type {any[]} */ const facts = [];
682
656
  /** @type {{r: Row, src: string}[]} */ const factRows = [];
@@ -734,15 +708,12 @@ export class CheckBlock {
734
708
  return k ? factsOfLook(k) : null;
735
709
  };
736
710
  lineParts.push({ ...part, facts: facts.flatMap((f) => grownOf(f) ?? [f]) }); lineRows.push([...factRows.map((f) => f.r.key), ...(countRow ? [countRow.key] : [])]); foundFact = true; if (countRow) { countRow.state = 'built'; countRow.reason = null; } }
737
- } else if (countRow) { countRow.state = 'not-checked'; countRow.reason = this.rowsOn(l.n).some((x) => x.held && (x.kind === 'fact' || x.kind === 'phrase')) ? REASON.countNeedsSuggested : REASON.countNeedsFact; }
711
+ } else if (countRow) { countRow.state = 'not-checked'; countRow.reason = this.rowsOn(l.n).some((x) => x.held && isFactKind(x.kind)) ? REASON.countNeedsSuggested : REASON.countNeedsFact; }
738
712
  // facts+shape: the shape part follows the fact part (the same `results` list); its fields are the rules no truth check could take
739
713
  if (shapeRows.length > 0) this.buildShapePartOf(l, shapeRows, lineParts, lineRows);
740
714
  for (const { p, key } of pickParts) { lineParts.push(p); lineRows.push([key]); }
741
- // fwd (F251): the one decider. A line with no ~ guardrail keeps no fact, pick or shape part: its built rows are Not checked in the words the Accept reads, and it is never a fact line (so no numbers tie points at it)
742
- if (unguarded && !offer) {
743
- for (const k of lineRows.flat()) { const row = this.rows.find((x) => x.key === k); if (row) { row.state = 'not-checked'; row.reason = NO_GUARDRAIL_WORDS; row.part = null; } }
744
- lineParts.length = 0; lineRows.length = 0;
745
- } else if (foundFact) factLines.add(l.n);
715
+ // M19 am15 (F257): a line with no ~ of the person's own keeps the parts of the `!` rows the person Added (nothing else builds one there: match() holds every `!` row of such a line), so it may be a fact line
716
+ if (foundFact) factLines.add(l.n);
746
717
  this.buildDefaults(l, lineParts, lineRows, factLines);
747
718
  }
748
719
 
@@ -803,7 +774,7 @@ export class CheckBlock {
803
774
  const mk = (/** @type {string} */ name, /** @type {any} */ extra) => ({ name: cleanName(name), ...extra });
804
775
  const kindFields = (/** @type {any} */ f, /** @type {string} */ anchor, /** @type {any} */ extra) => mk(f.name, {
805
776
  shape: f.shape, anchor, ...(f.unit ? { unit: f.unit } : {}), ...(f.currency ? { currency: f.currency } : {}),
806
- ...(f.decimal && (f.shape === 'money' || f.shape === 'number') ? { decimal: f.decimal } : {}), ...(f.lang && f.shape === 'date' ? { lang: f.lang } : {}), ...extra,
777
+ ...(f.decimal && isAmountShape(f.shape) ? { decimal: f.decimal } : {}), ...(f.lang && f.shape === 'date' ? { lang: f.lang } : {}), ...extra,
807
778
  });
808
779
  /** @type {any[]} */ let fs;
809
780
  if (r.kind === 'rule') {
@@ -1145,7 +1116,7 @@ export class CheckBlock {
1145
1116
 
1146
1117
  editAdd(/** @type {any} */ e) {
1147
1118
  if (e.kind === 'count') return this.addCount(e);
1148
- if (e.kind !== 'fact' && e.kind !== 'phrase') return { refusedBecause: 'an add is a fact, a phrase or a count' };
1119
+ if (!isFactKind(e.kind)) return { refusedBecause: 'an add is a fact, a phrase or a count' };
1149
1120
  // an input the job does not have is refused alone (it would otherwise reach the draft gate as a red on code's own plan and stop the whole draft)
1150
1121
  if (e.source !== undefined && e.source !== null && !this.labels.includes(e.source)) return { refusedBecause: `"${String(e.source).slice(0, 60)}" is not one of the inputs` };
1151
1122
  // a job with more than one input never guesses which one an add quotes (code fills a missing source only when there is exactly one)
@@ -1174,13 +1145,12 @@ export class CheckBlock {
1174
1145
  const rs = wordSet(rr.text);
1175
1146
  if (wset.size && [...wset].every((w) => rs.has(w))) return `already on the list: a ~ rule says it (line ${line} rule ${rr.rule})`;
1176
1147
  }
1177
- if (this.rows.some((r) => (r.kind === 'fact' || r.kind === 'phrase') && r.line === line && (norm(r.name) === norm(name) || norm(r.words?.[0]) === norm(words[0])))) return 'already on the list';
1148
+ if (this.rows.some((r) => isFactKind(r.kind) && r.line === line && (norm(r.name) === norm(name) || norm(r.words?.[0]) === norm(words[0])))) return 'already on the list';
1178
1149
  return null;
1179
1150
  }
1180
1151
 
1181
1152
  addCount(/** @type {any} */ e) {
1182
- const ok = (/** @type {unknown} */ x) => Number.isInteger(x) && /** @type {number} */ (x) >= 1;
1183
- if (![e.min, e.max].some(Number.isInteger) || [e.min, e.max].some((x) => x !== undefined && !ok(x)) || (Number.isInteger(e.min) && Number.isInteger(e.max) && e.min > e.max)) return { refusedBecause: 'no legal number given' };
1153
+ if (!isLegalCount({ min: e.min, max: e.max })) return { refusedBecause: 'no legal number given' };
1184
1154
  if (this.rowsOn(e.line, 'count').length) return { refusedBecause: 'already on the list: this line has a result count' };
1185
1155
  const row = this.addRow({ key: `L${e.line}.count.${e.min ?? ''}-${e.max ?? ''}`, line: e.line, kind: 'count', by: 'agent', from: 'agent', min: e.min, max: e.max });
1186
1156
  return { accepted: true, landedKey: row.key };
@@ -1193,7 +1163,7 @@ export class CheckBlock {
1193
1163
 
1194
1164
  /** the one owner of "what do the person's own words say": code's reading of a `~` rule for a money/time fact, or undefined when it cannot read it */
1195
1165
  wordsReading(/** @type {any} */ l, /** @type {string} */ text) {
1196
- if (l.shape !== 'money' && l.shape !== 'time') return undefined;
1166
+ if (!canReadLimit(l.shape)) return undefined;
1197
1167
  const own = readLimit(l.shape, text, l);
1198
1168
  const rd = 'reading' in own ? own.reading : undefined;
1199
1169
  return rd && validReading(l.shape, rd) && (rd.op === 'between' ? [rd.lo, rd.hi] : [rd.value]).every((b) => boundInWords(b, text)) ? rd : undefined;
@@ -1343,7 +1313,7 @@ export class CheckBlock {
1343
1313
  }
1344
1314
  if (r.by === 'you') return { ok: false, why: 'that check comes from a rule you wrote; edit the job to change it' };
1345
1315
  if (r.by !== 'agent' || !this.droppable(r)) return { ok: false, why: 'that check is code\'s own and stays' };
1346
- if (choice !== 'drop' && choice !== 'add') return { ok: false, why: 'not one of the choices' };
1316
+ if (!isRowChoice(choice)) return { ok: false, why: 'not one of the choices' };
1347
1317
  if (r.kind === 'stage') {
1348
1318
  // a repo work stage: Drop takes it out of the close (never the last check on its line), Add puts it back
1349
1319
  if (choice === 'drop' && r.state !== 'built') return { ok: false, why: 'only a check that is on the card can be dropped' };
@@ -1364,7 +1334,7 @@ export class CheckBlock {
1364
1334
 
1365
1335
  /** the person's Drop/Add choices, tied to the line's words (not its number) and the row's own name, so a Revise keeps them @returns {{lineWords: string, occurrence: number, tail: string, choice: string}[]} */
1366
1336
  choicesRecord() {
1367
- return choiceEntries(this.lines, this.rows.filter((r) => r.kind !== 'sheet' && r.kind !== 'shape' && (r.choice === 'drop' || r.choice === 'add')).map((r) => ({ line: r.line, key: r.key, choice: String(r.choice) })));
1337
+ return choiceEntries(this.lines, this.rows.filter((r) => r.kind !== 'sheet' && r.kind !== 'shape' && isRowChoice(r.choice)).map((r) => ({ line: r.line, key: r.key, choice: String(r.choice) })));
1368
1338
  }
1369
1339
 
1370
1340
  /** a Revise keeps the last draft's Drop/Add choices on the rows that are still there (same line words, same row); code still judges every one @param {{lineWords: string, occurrence: number, tail: string, choice: string}[]} rec */
@@ -1372,7 +1342,7 @@ export class CheckBlock {
1372
1342
  const seen = new Map();
1373
1343
  const lines = this.lines.map((l) => { const w = norm(l.text); const o = seen.get(w) ?? 0; seen.set(w, o + 1); return { n: l.n, w, o }; });
1374
1344
  for (const c of Array.isArray(rec) ? rec : []) {
1375
- if (!c || (c.choice !== 'drop' && c.choice !== 'add')) continue;
1345
+ if (!c || !isRowChoice(c.choice)) continue;
1376
1346
  const line = lines.find((l) => l.w === c.lineWords && l.o === c.occurrence);
1377
1347
  const r = line ? this.rows.find((x) => x.line === line.n && this.droppable(x) && x.key.replace(/^L\d+\./, '') === c.tail) : undefined;
1378
1348
  if (r) { r.choice = c.choice; r.keptFromLast = true; }
package/src/checked.js CHANGED
@@ -70,10 +70,9 @@ export function checkedLines(declaration, { hasAsk = true, askLines, lines, csvR
70
70
  // M10b piece 1: the signed sheet checks, one row each, written by code from the typed fields
71
71
  lead = 'The machine recomputes each of these from the saved sheet and compares it with what the step gave:';
72
72
  out.push(...(sheet ? [] : sheetCheckRows(st.close.sheet).map((r) => labelled(r, 'agent'))));
73
- } else if (cls === 'green' && st.close.itemShape && typeof st.close.itemShape === 'object') {
74
- // M19 am11 item 6: a list line states no lead sentence; its checks are the rows below (listPartRows)
75
73
  } else if (cls === 'green') {
76
- lead = 'Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.';
74
+ // M19 am11 item 6: a list line (itemShape) states no lead sentence; its checks are the rows below (listPartRows)
75
+ if (!(st.close.itemShape && typeof st.close.itemShape === 'object')) lead = 'Every figure must cite its source cell, or a formula over cells, and the machine recomputes it and compares it with its source.';
77
76
  } else if (cls === 'softgreen') {
78
77
  lead = 'The reply is checked as plain text only.';
79
78
  if (Number.isInteger(shape.maxWords)) out.push(labelled(`The whole output is under ${shape.maxWords} words.`, 'agent'));
@@ -1,8 +1,8 @@
1
1
  // M16 (docs/wiki/the-module-ladder.md, "M16" item 2, "a check that reaches the plan is not on the list"): the sign-time and run-start proof that the checks of a plan's list lines are the list's.
2
2
  // Equivalent of bareloop src/rubricstep.js@v0.56.0 (3383cce) `listMatchesClose`, read over fwdloop's close fields instead of a rubric-step stage: the checks of one line, in the order the check block
3
3
  // builds them, are [close.cited (the fact part)], [close.itemShape (the shape part, M19 S5)], then each entry of close.picked / close.shape.picked, then close.numbersFrom (the numbers tie). A signed row points at one of them by `part: {line, part: <index>}`.
4
-
5
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
4
+ import { isRec } from './isrec.js';
5
+ import { tagOf } from './checkwords.js';
6
6
 
7
7
  /**
8
8
  * The checks of one step's close in the block's part order. M16 am4: with `withSheet` (a plan whose list has sheet rows) each `close.sheet` check is a part too, after the others.
@@ -78,17 +78,38 @@ const builtOn = (declaration, line) => (isRec(declaration) && Array.isArray(decl
78
78
  */
79
79
  export function partByOf(declaration, line, idx) {
80
80
  const r = builtOn(declaration, line).find((x) => isRec(x.part) && x.part.part === idx);
81
- return r && (r.by === 'you' || r.by === 'agent' || r.by === 'default') ? r.by : null;
81
+ return r && tagOf(r.by) !== '' ? r.by : null;
82
82
  }
83
83
 
84
84
  /** who made the fact named `name` of a list line's quote check (the row that built it), else null @param {any} declaration @param {number} line @param {string} name @returns {'you'|'agent'|'default'|null} */
85
85
  export function factByOf(declaration, line, name) {
86
86
  const r = builtOn(declaration, line).find((x) => Array.isArray(x.facts) && x.facts.includes(name));
87
- return r && (r.by === 'you' || r.by === 'agent' || r.by === 'default') ? r.by : null;
87
+ return r && tagOf(r.by) !== '' ? r.by : null;
88
88
  }
89
89
 
90
90
  /** who made the result count of a list line's quote check, else null @param {any} declaration @param {number} line @returns {'you'|'agent'|'default'|null} */
91
91
  export function countByOf(declaration, line) {
92
92
  const r = builtOn(declaration, line).find((x) => x.kind === 'count');
93
- return r && (r.by === 'you' || r.by === 'agent' || r.by === 'default') ? r.by : null;
93
+ return r && tagOf(r.by) !== '' ? r.by : null;
94
94
  }
95
+
96
+ /**
97
+ * The proof of a plan whose list has ticket rows (a plan with none is not examined): a built ticket row needs the declaration's field, and a field the declaration holds needs a built row for it.
98
+ * @param {any} declaration @returns {string[]}
99
+ */
100
+ export function ticketListReds(declaration) {
101
+ const list = isRec(declaration) && Array.isArray(declaration.checkList) ? declaration.checkList.filter((/** @type {any} */ r) => isRec(r) && r.kind === 'ticket') : [];
102
+ if (list.length === 0) return [];
103
+ /** @type {string[]} */
104
+ const reds = [];
105
+ for (const f of TICKET_FIELDS) {
106
+ const built = list.some((/** @type {any} */ r) => r.field === f && r.state === 'built');
107
+ const has = Object.hasOwn(declaration, f);
108
+ if (built && !has) reds.push(`declaration: checkList: a row says "${f}" is its check, but the plan has no "${f}". Nothing was signed - draft again.`);
109
+ if (has && !built) reds.push(`declaration: "${f}" is not the check of any rule on the list. Nothing was signed - draft again.`);
110
+ }
111
+ return reds;
112
+ }
113
+
114
+ /** @type {readonly ('ticketFilter'|'ticketWatch')[]} */
115
+ export const TICKET_FIELDS = Object.freeze(['ticketFilter', 'ticketWatch']);
package/src/checklook.js CHANGED
@@ -3,6 +3,8 @@
3
3
  // The card (src/cardlist.js), the Audit (src/auditchecks.js), the draft readout (src/authoring.js) and the page all take their kind word and their Not-checked split from these.
4
4
  // What this throws away: a Not checked item's own quotes round a whole rule and the reason "you judge it at Accept" (the group title says it).
5
5
 
6
+ import { tagOf } from './checkwords.js';
7
+
6
8
  /** the group titles and the tail of the Not checked one (section 3.7, copied unchanged) */
7
9
  export const LOOK = Object.freeze({
8
10
  checked: 'CHECKED', notChecked: 'NOT CHECKED', notCheckedTail: 'you judge these at Accept', suggested: 'SUGGESTED · add if you want it', everyLine: 'Every line',
@@ -40,6 +42,6 @@ export function ncRowsOf(items, by = {}) {
40
42
  const m = /^line (\d+): ([\s\S]*)$/.exec(raw);
41
43
  const body = (m ? m[2] : raw).replace(/^not checked · /, '');
42
44
  const tag = by[raw];
43
- return { line: m ? Number(m[1]) : 0, ...splitNotChecked(body), ...(tag === 'you' || tag === 'agent' || tag === 'default' ? { by: tag } : {}) };
45
+ return { line: m ? Number(m[1]) : 0, ...splitNotChecked(body), ...(tagOf(tag) !== '' ? { by: /** @type {'you'|'agent'|'default'} */ (tag) } : {}) };
44
46
  });
45
47
  }