fwdloop 0.38.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 (127) hide show
  1. package/bin/fwdloop +21 -19
  2. package/package.json +1 -1
  3. package/src/ask.js +70 -148
  4. package/src/audit-fold.js +5 -4
  5. package/src/auditchecks.js +6 -4
  6. package/src/authoring.js +32 -60
  7. package/src/blockasks.js +2 -1
  8. package/src/blockassemble.js +3 -2
  9. package/src/blockdraft.js +2 -2
  10. package/src/blockpick.js +5 -5
  11. package/src/books.js +217 -12
  12. package/src/checkblock.js +20 -41
  13. package/src/checklistsign.js +25 -3
  14. package/src/checklook.js +3 -1
  15. package/src/checkpick.js +5 -76
  16. package/src/cited-source.js +4 -4
  17. package/src/citedcheck.js +6 -11
  18. package/src/citedwords.js +9 -8
  19. package/src/closers.js +9 -6
  20. package/src/declaration.js +14 -49
  21. package/src/diary.js +23 -1
  22. package/src/draft-steps.js +11 -1
  23. package/src/drafter.js +13 -9
  24. package/src/draftfiles.js +127 -0
  25. package/src/draftspend.js +165 -17
  26. package/src/flow.js +42 -87
  27. package/src/flowmodel.js +1 -1
  28. package/src/index.js +3 -2
  29. package/src/inside.js +86 -0
  30. package/src/jsonl-append.js +33 -1
  31. package/src/learn.js +1 -1
  32. package/src/learnstore.js +20 -22
  33. package/src/line-checks.js +1 -1
  34. package/src/liveness.js +3 -0
  35. package/src/mcp-use.js +8 -9
  36. package/src/memo.js +13 -16
  37. package/src/model-step.js +2 -2
  38. package/src/page-words.js +8 -0
  39. package/src/pageask.js +8 -3
  40. package/src/pagebits.js +8 -1
  41. package/src/pagedropwords.js +1 -1
  42. package/src/pagerules.js +6 -3
  43. package/src/panel/author.js +99 -75
  44. package/src/panel/authorcard.js +21 -8
  45. package/src/panel/authorflows.js +3 -3
  46. package/src/panel/authorresume.js +3 -3
  47. package/src/panel/authorstart.js +15 -16
  48. package/src/panel/authortrigger.js +43 -70
  49. package/src/panel/data.js +125 -168
  50. package/src/panel/index.html +122 -61
  51. package/src/panel/jobgrid.js +3 -7
  52. package/src/panel/result.js +7 -10
  53. package/src/panel/resume.js +4 -3
  54. package/src/panel/scheduler.js +9 -9
  55. package/src/panel/server.js +8 -4
  56. package/src/panel/spawn.js +22 -11
  57. package/src/panel/tickets.js +2 -2
  58. package/src/pickrecord.js +51 -31
  59. package/src/placerule.js +3 -4
  60. package/src/planrebuild.js +19 -19
  61. package/src/primitives.js +1 -1
  62. package/src/provider.js +1 -1
  63. package/src/reasons.js +25 -0
  64. package/src/runfile.js +26 -2
  65. package/src/runner.js +57 -105
  66. package/src/runvalues.js +47 -24
  67. package/src/schedule-choices.js +41 -0
  68. package/src/schedule-shape.js +39 -0
  69. package/src/schedule.js +9 -8
  70. package/src/setup.js +20 -36
  71. package/src/shaperows.js +2 -2
  72. package/src/sheetblock.js +2 -2
  73. package/src/sheetbuild.js +5 -5
  74. package/src/sheetrun.js +4 -5
  75. package/src/summary-words.js +2 -1
  76. package/src/thinking.js +5 -2
  77. package/src/ticketrows.js +7 -28
  78. package/src/trigger-clock.js +9 -23
  79. package/src/trigger-files.js +30 -22
  80. package/src/trigger-tickets.js +15 -14
  81. package/src/try-checks.js +2 -1
  82. package/src/types.js +2 -0
  83. package/types/ask.d.ts +25 -20
  84. package/types/authoring.d.ts +7 -42
  85. package/types/blockpick.d.ts +1 -1
  86. package/types/books.d.ts +256 -4
  87. package/types/checkblock.d.ts +1 -23
  88. package/types/checklist.d.ts +3 -3
  89. package/types/checklistsign.d.ts +7 -0
  90. package/types/checkpick.d.ts +0 -21
  91. package/types/citedwords.d.ts +7 -4
  92. package/types/closers.d.ts +1 -0
  93. package/types/declaration.d.ts +4 -14
  94. package/types/diary.d.ts +14 -1
  95. package/types/draft-steps.d.ts +7 -0
  96. package/types/drafter.d.ts +1 -1
  97. package/types/draftfiles.d.ts +89 -0
  98. package/types/draftspend.d.ts +74 -0
  99. package/types/flow.d.ts +32 -54
  100. package/types/index.d.ts +3 -3
  101. package/types/inside.d.ts +58 -0
  102. package/types/jsonl-append.d.ts +20 -0
  103. package/types/learnstore.d.ts +0 -2
  104. package/types/liveness.d.ts +1 -0
  105. package/types/page-words.d.ts +6 -0
  106. package/types/pageask.d.ts +2 -0
  107. package/types/pagebits.d.ts +3 -0
  108. package/types/pagerules.d.ts +1 -0
  109. package/types/panel/author.d.ts +7 -3
  110. package/types/panel/authorcard.d.ts +0 -6
  111. package/types/panel/authorflows.d.ts +4 -4
  112. package/types/panel/authortrigger.d.ts +16 -2
  113. package/types/panel/data.d.ts +36 -11
  114. package/types/panel/spawn.d.ts +18 -2
  115. package/types/pickrecord.d.ts +29 -0
  116. package/types/reasons.d.ts +23 -0
  117. package/types/runfile.d.ts +14 -0
  118. package/types/runner.d.ts +6 -38
  119. package/types/runvalues.d.ts +17 -2
  120. package/types/schedule-choices.d.ts +9 -0
  121. package/types/schedule-shape.d.ts +15 -0
  122. package/types/sheetbuild.d.ts +1 -1
  123. package/types/thinking.d.ts +1 -0
  124. package/types/ticketrows.d.ts +0 -9
  125. package/types/trigger-clock.d.ts +3 -2
  126. package/types/trigger-files.d.ts +15 -4
  127. package/types/types.d.ts +8 -0
package/src/authoring.js CHANGED
@@ -31,7 +31,8 @@ import { sheetLineBlocks } from './sheetblock.js';
31
31
  import { loadCatalogue } from './catalogue.js';
32
32
  import { WIRED_VERBS } from './primitives.js';
33
33
  import { canonicalBytes } from './signature.js';
34
- import { writeFlow, writeRunPlan, readFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
34
+ import { writeFlow, writeRunPlan, readFlow, readJsonFile, checkFlowName, readDraftLog } from './flow.js';
35
+ import { readFileInside, readdirInside } from './inside.js';
35
36
  import { jobKeyOfSigned } from './jobkey.js';
36
37
  import { checkSendDestination } from './runner.js';
37
38
  import { checkKeyPreflight, appendSpendRow } from './provider.js';
@@ -40,28 +41,25 @@ import { readModelRecord, writeModelRecord, writeLearningsRecord, writeLearnings
40
41
  import { configDoorHome } from './config.js';
41
42
  import { hintsForRun, placeSpecOf } from './learnstore.js';
42
43
  import { redactSecrets } from './redact.js';
43
- import { sessionPriorSpend, writeDraftSpend } from './draftspend.js';
44
+ import { makeStepWriter, sessionPriorSpend, writeDraftSpend } from './draftspend.js';
44
45
  import { writeSetup } from './setup.js';
45
- import { RECORD_FILE } from './pickrecord.js';
46
+ import { RECORD_FILE, readKept, readRowChoices, recordPath, addedCountsOf } from './pickrecord.js';
46
47
  import { planMatchesCard, numbersWords } from './checkrows.js';
47
48
  import { csvRolesOf } from './sheetblock.js';
48
49
  import { mcpPickHere } from './mcp-pick.js';
49
50
  import { hitlWords, notCheckedView } from './checked.js';
51
+ import {
52
+ SPEC_HASH_FILE, LEAK_MARKER_FILE, draftVerdict, QUESTIONS_FILE, ANSWER_FILE, NOT_CHECKED_FILE, readNotCheckedFile, readQuestions, scrub, readCard, cardFileName, readRedraftMarker, redraftFileName, readPlanTexts,
53
+ } from './draftfiles.js';
50
54
 
51
- export const SPEC_HASH_FILE = 'spec.hash';
52
55
  /** The one folder under the flows root where the panel keeps its draft folders (M4e). Starts with a dot, so it is never a flow name. */
53
56
  export const PANEL_DRAFTS_DIR = '.drafts';
54
- /** Written when the end sweep finds a key in the draft dir; sign refuses a dir that has it. */
55
- export const LEAK_MARKER_FILE = 'scrub-leak.red';
56
57
  /** M4e amendments 24/25: the drafter's questions (written once by `fwdloop draft`), each human answer (`answer-<k>.json`, written once by the panel),
57
58
  * and the drafter's own "not checked" reading (information only; never in the readout, so never in the hash). */
58
- export const QUESTIONS_FILE = 'questions.json';
59
- export const NOT_CHECKED_FILE = 'not-checked.json';
60
59
  /** M10: the drafting copy of each web page input is kept in this folder of the draft folder (a run freezes its own, never this one). */
61
60
  export const PAGES_DIR = 'pages';
62
61
  /** M10 item 3: what the page-word look kept and dropped, per page input (the map the AI named, the kept facts with their readings, every drop). Not signed. */
63
62
  export const PAGE_LOOK_FILE = 'page-look.json';
64
- export const ANSWER_FILE = (k) => `answer-${k}.json`;
65
63
  export const SIGN_LINE = (dir, hash) => `DRAFTED — NOT SIGNED. To sign: fwdloop sign ${dir} --approve ${hash}`;
66
64
 
67
65
  const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
@@ -91,42 +89,13 @@ export function specHash({
91
89
  }
92
90
 
93
91
  /**
94
- * The questions a plan folder raised and the answers on disk, READ from its files — the ONE reader (the panel's phase reader, the sign
95
- * checks and the page all use it). `questions` = [{ k, line, question, answer|null }], `open` = those with no answer. A blank or unreadable
96
- * answer file counts as no answer. No questions file = `{ questions: [], open: [] }`.
97
- * @param {string} planDir
98
- * A question the page look raised (M10 piece 3) also carries `source: 'look'`, `ask` ('reading' | 'cant-check'), `ruleNo`, `ruleText` and `proposal`; an answer file carries `at`.
99
- * @returns {{ questions: {k:number, line:number, question:string, answer:string|null, at?:string, rule?:string|null, choice?:'agree'|'drop'|'rule'|'column', source?:string, ask?:string, ruleNo?:number, ruleText?:string, proposal?:string|null, check?:Record<string, any>, pairRule?:number, columns?:string[], readings?:Record<string,string>}[], open: {k:number, line:number, question:string, answer:null}[] }}
92
+ * The flow name a draft will sign as: the `name` in `target.json` of a plan folder (`planDir`, read through the safe gateway). A string that is not empty,
93
+ * else null (no file, not JSON, not an object, no name, a name that is empty or not a string).
94
+ * @param {string} planDir @returns {string|null}
100
95
  */
101
- export function readQuestions(planDir) {
102
- const none = { questions: [], open: [] };
103
- const f = readFileInside(planDir, QUESTIONS_FILE);
104
- if (!f.ok) return none;
105
- let list;
106
- try { list = JSON.parse(f.text)?.questions; } catch { return none; }
107
- if (!Array.isArray(list)) return none;
108
- const questions = list.map((q, i) => {
109
- const k = i + 1;
110
- const a = readFileInside(planDir, ANSWER_FILE(k));
111
- let answer = null;
112
- let at;
113
- /** @type {string|null|undefined} the `~` rule the answer added (null = it left the rule Not checked), as the answer file recorded it */
114
- let rule;
115
- /** @type {'agree'|'drop'|'rule'|'column'|undefined} M10 am29: which one the answer used (`agree`, `drop` or `rule`), when the file records it */
116
- let choice;
117
- if (a.ok) {
118
- try {
119
- const j = JSON.parse(a.text);
120
- const t = j?.answer;
121
- if (typeof t === 'string' && t.trim() !== '') { answer = t; if (typeof j.at === 'string') at = j.at; if (j.rule === null || typeof j.rule === 'string') rule = j.rule; if (j.choice === 'agree' || j.choice === 'drop' || j.choice === 'rule' || j.choice === 'column') choice = j.choice; }
122
- } catch { /* unreadable = unanswered */ }
123
- }
124
- return {
125
- k, line: q.line, question: String(q.question), answer, ...(at === undefined ? {} : { at }), ...(rule === undefined ? {} : { rule }), ...(choice === undefined ? {} : { choice }),
126
- ...(q.source === 'look' ? { source: 'look', ask: q.ask, ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: typeof q.proposal === 'string' ? q.proposal : null, ...(q.check && typeof q.check === 'object' ? { check: q.check } : {}), ...(Number.isInteger(q.pairRule) ? { pairRule: q.pairRule } : {}), ...(Array.isArray(q.columns) && q.columns.length > 0 && q.readings && typeof q.readings === 'object' ? { columns: q.columns.map(String), readings: q.readings } : {}) } : {}),
127
- };
128
- });
129
- return { questions, open: /** @type {any} */ (questions.filter((q) => q.answer === null)) };
96
+ export function readTargetName(planDir) {
97
+ const name = readJsonFile(planDir, 'target.json')?.name;
98
+ return typeof name === 'string' && name !== '' ? name : null;
130
99
  }
131
100
 
132
101
  export const OPEN_QUESTION_SAY = 'A question the plan raised is still open. Answer it in the panel (fwdloop panel), then sign the plan it drafts after your answers. Nothing was signed.';
@@ -139,13 +108,6 @@ export function questionsRefusal(planDir) {
139
108
  return q.open.length > 0 ? OPEN_QUESTION_SAY : ANSWERED_QUESTION_SAY;
140
109
  }
141
110
 
142
- /** Literal (never RegExp) key scrub; a secret under 8 chars is skipped so it can't blank ordinary text. */
143
- export function scrub(text, secrets) {
144
- let out = text;
145
- for (const s of secrets) if (typeof s === 'string' && s.length >= 8) out = out.split(s).join('[redacted-key]');
146
- return out;
147
- }
148
-
149
111
  /** Count files directly inside `dir` that contain a secret literally. */
150
112
  export function sweepForSecrets(dir, secrets) {
151
113
  const live = secrets.filter((s) => typeof s === 'string' && s.length >= 8);
@@ -385,7 +347,7 @@ export function writePlanFiles(dir, files, opts = {}) {
385
347
  * `onResult({ ok })` (M4d am32): called once, after the spend is booked and just before the result files are written (the CLI gives its monthly hold back there).
386
348
  */
387
349
  export async function draftToDir({
388
- proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, fetchPage, leftRules, columnAnswers, carriedColumns, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, carriedShapeDropped, proseRead,
350
+ proseFile, dir, root, name, slot, model, draftThinking = /** @type {'on'|'off'} */ ('off'), keyNames, env = process.env, provider, rates, modelId, noQuestions = false, onResult, onStepLine, fetchPage, leftRules, columnAnswers, carriedColumns, checkPicks, carriedPicks, carriedChoices, carriedSheetDropped, carriedShapeDropped, proseRead,
389
351
  flowType = /** @type {'plain'|'mcp'|'tickets'} */ ('plain'), mcpServer = /** @type {string|undefined} */ (undefined), mcpPick = /** @type {any} */ (undefined), mcpServers = /** @type {string[]|undefined} */ (undefined),
390
352
  // M13 am11: what the card's tentative send line is (see draft()); null = the prose file is the truth
391
353
  actionMode = /** @type {null|'check'|'known'} */ (null),
@@ -428,9 +390,14 @@ export async function draftToDir({
428
390
  // Spend is booked per call into `<dir>/draft-spend.json` (src/draftspend.js), so a draft stopped between rounds
429
391
  // keeps what it paid. The first write is the mark that a call is in flight: if that cannot be written, the call is not made.
430
392
  let startedAt = null;
393
+ // M20 am1 item 5 (+ am2): the step lines, written by the CLI's `onStepLine` into the draft's existing child.log; none when nothing listens
394
+ const stepWriter = typeof onStepLine === 'function' ? makeStepWriter(onStepLine) : null;
431
395
  const onBook = ({
432
- inFlight, calls, unmetered, metered, modelId: usedModel, price,
396
+ inFlight, calls, unmetered, metered, modelId: usedModel, price, partial,
433
397
  }) => {
398
+ if (stepWriter !== null && typeof partial === 'function') {
399
+ try { stepWriter(partial(), null, false); } catch { /* progress only: a failed line never fails the draft */ }
400
+ }
434
401
  const now = new Date().toISOString();
435
402
  startedAt ??= now;
436
403
  try {
@@ -522,6 +489,10 @@ export async function draftToDir({
522
489
  // M13 am11: the job's action (the last line the AI named, or the person agreed or typed), or null: the plan card's row `› line <n> writes everything before it`
523
490
  action: result.action ?? null,
524
491
  }), secrets);
492
+ // M20 am1 item 5: the last step lines (every step ended, final labels) are written before the result files, so a draft the panel sees finished already has them
493
+ if (stepWriter !== null) {
494
+ try { stepWriter(JSON.parse(files['log.json']), result.declaration ?? null, true); } catch { /* progress only */ }
495
+ }
525
496
  let hash = null;
526
497
  if (result.ok) {
527
498
  const declarationText = scrub(dj(result.declaration), secrets);
@@ -595,7 +566,8 @@ export function signDraft({
595
566
  dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, keyNames, sessionDir, replaces, asRunOf,
596
567
  }) {
597
568
  const refuse = (...reds) => ({ ok: false, reds });
598
- if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
569
+ const dv = draftVerdict(dir);
570
+ if (dv.leak.ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
599
571
  const openQuestion = questionsRefusal(dir);
600
572
  if (openQuestion !== null) return refuse(`sign: ${openQuestion}`);
601
573
  // Sign is $0 and takes no key, so it can only sweep for the keys it is told of (`keyNames`, the rows set up in Settings).
@@ -606,7 +578,7 @@ export function signDraft({
606
578
  const read = (f) => readFileInside(dir, f);
607
579
  const parts = {};
608
580
  for (const f of ['prose.txt', 'declaration.json', 'input-facts.json', 'readout.txt', SPEC_HASH_FILE, 'target.json']) {
609
- const r = read(f);
581
+ const r = f === SPEC_HASH_FILE ? dv.hashFile : read(f);
610
582
  if (!r.ok) return refuse(`sign: "${dir}" is not a green draft — ${f} ${r.missing ? 'is missing' : `is refused (${r.red})`}`);
611
583
  parts[f] = r.text;
612
584
  }
@@ -633,18 +605,18 @@ export function signDraft({
633
605
  if (!cat.ok) return refuse(`sign: catalogue: ${cat.reds.join('; ')}`);
634
606
  const verdict = validateDeclaration(declaration, {
635
607
  arbiter: signed.arbiter, lines: signed.lines, catalogue: cat.primitives, wired: WIRED_VERBS, verbatimGoals: true, fitJobLine: true,
608
+ addedCounts: addedCountsOf(readRowChoices(recordPath(dir)), signed.lines),
636
609
  });
637
610
  if (!verdict.ok) return { ok: false, reds: verdict.reds };
638
611
  // M19 am6 item 3 (bareloop `planMatchesClose`): the card a draft saved must equal the checks the signed plan runs, line by line; a difference refuses the sign at $0, naming the line.
639
612
  // Only a card saved with its own Not checked list (this build) is compared; an older saved card is drawn from the plan and not held to it.
640
613
  const cardReds = (() => {
641
614
  if (!Array.isArray(declaration.checkList)) return [];
642
- const lg = read('log.json');
643
- const rec = read(RECORD_FILE);
644
- /** @type {any} */ let log = null; /** @type {any} */ let record = null;
645
- try { log = lg.ok ? JSON.parse(lg.text) : null; record = rec.ok ? JSON.parse(rec.text) : null; } catch { return []; }
615
+ const keptRead = readKept(dir);
616
+ const log = readDraftLog(dir);
617
+ if (keptRead.torn) return []; // an unreadable record: the check skips
646
618
  if (!log?.checkCard || !Array.isArray(log.checkCard.notChecked)) return [];
647
- const kept = Array.isArray(record?.kept) ? record.kept.filter((/** @type {any} */ k) => k && Number.isInteger(k.line)) : [];
619
+ const kept = (keptRead.kept ?? []).filter((/** @type {any} */ k) => k && Number.isInteger(k.line));
648
620
  return planMatchesCard({ declaration, lines: signed.lines, csvRoles: csvRolesOf(signed.arbiter), kept, log: log.log }, log.checkCard);
649
621
  })();
650
622
  if (cardReds.length) return { ok: false, reds: cardReds };
package/src/blockasks.js CHANGED
@@ -3,7 +3,8 @@
3
3
  // The questions of the check block, as the answer gate reads them (`answerQuestions`, src/questionbox.js): ONE spelling of the question words, written by code from a row that
4
4
  // code could not settle (reading | check). The block's `open` list is the source; the person's CHOICE (agree | drop | rule) goes back through `block.applyAnswer`.
5
5
  import { readingQuestion } from './pageask.js';
6
- import { plainWords, HOW_TO_ANSWER } from './checkpick.js';
6
+ import { plainWords } from './checkpick.js';
7
+ import { HOW_TO_ANSWER } from './pageask.js';
7
8
 
8
9
  /** @typedef {{key: string, rowKey: string, line: number, rule: number, source: 'look', ask: 'reading'|'check', ruleText: string, question: string, counted: boolean, reading?: string, check?: Record<string, any>}} BlockAsk */
9
10
 
@@ -18,8 +18,9 @@ export const ASK_LINE_REASON = 'you judge it at the Ask';
18
18
  */
19
19
  export const SHAPE_ONLY_CLASS = 'green';
20
20
 
21
- import { REASON } from './checkblock.js';
21
+ import { REASON } from './reasons.js';
22
22
  import { KEPT_WORDS } from './pickrecord.js';
23
+ import { tagOf } from './checkwords.js';
23
24
  import { lineRules } from './pagebits.js';
24
25
  import { isListedNotChecked, notCheckedItem, ruleTextOf } from './checkrows.js';
25
26
  import { isRec } from './isrec.js';
@@ -123,7 +124,7 @@ export function assembleFromBlock({ declaration, block, lines, lineSet, askLines
123
124
  if (own?.hidden) return null;
124
125
  // the reason is the signed row's own `reason` (src/checkblock.js REASON, the one table); M10 am17 (6): `kept` words
125
126
  const line = notCheckedItem(r, ruleTextOf(lines, r) ?? own?.text, own ? (own.name ? [own.name] : own.words) : undefined, own?.keptFromLast === true);
126
- if (r.by === 'you' || r.by === 'agent' || r.by === 'default') notCheckedBy[line] = r.by;
127
+ if (tagOf(r.by) !== '') notCheckedBy[line] = r.by;
127
128
  return line;
128
129
  }).filter((x) => x !== null);
129
130
  for (const l of lines) {
package/src/blockdraft.js CHANGED
@@ -4,7 +4,7 @@
4
4
  import { redactSecrets } from './redact.js';
5
5
  import { newJobBlock } from './blocklines.js';
6
6
  import { EDIT_OPS } from './checkblock.js';
7
- import { isCountGuardrail } from './declaration.js';
7
+ import { isCountable } from './blockpick.js';
8
8
  import { ticketRuleField } from './ticketrows.js';
9
9
 
10
10
  /** the cap of refusals one revise turn carries (bareloop REVISE_RED_CAP) */
@@ -84,5 +84,5 @@ export const editRecord = (rec) => rec.edits.map((e) => ({ op: e?.op, accepted:
84
84
  */
85
85
  export function ticketLeaveOut(flowType, jobLines) {
86
86
  if (flowType !== 'tickets') return [];
87
- return jobLines.flatMap((l) => (l.rules ?? []).map((t, i) => ({ line: l.n, rule: i + 1, t })).filter((x) => ticketRuleField(x.t) !== null && !isCountGuardrail(x.t)).map((x) => ({ line: x.line, rule: x.rule })));
87
+ return jobLines.flatMap((l) => (l.rules ?? []).map((t, i) => ({ line: l.n, rule: i + 1, t })).filter((x) => ticketRuleField(x.t) !== null && !isCountable(x.t)).map((x) => ({ line: x.line, rule: x.rule })));
88
88
  }
package/src/blockpick.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // borrowed-from: bareloop src/checkpick.js@v0.57.0 (c18df406)
2
+ // fwd changed (M20 am8 item 2): guardrailItemCount keeps fwd's lookbehind (a number right after $ € £ . , is not an item count), and these readers are the one copy fwd's src/declaration.js re-exports.
2
3
  // first ported from: bareloop src/checkpick.js@v0.56.0 (3383cce) (isCountable, keepOrDrop, countCheck, partOfPick, sameRuleWords and what they call; HOW_TO_ANSWER and CANT_CHECK_WORDS are fwd's own, src/checkpick.js, the same words)
3
- // This file is bareloop's checkpick.js. fwd already has a src/checkpick.js (the M10 am16 pick path, whose keepOrDrop and countCheck differ from these); the check block calls THESE,
4
- // so they live here under another name and the am16 module is left as it is.
4
+ // This file is bareloop's checkpick.js. fwd's src/checkpick.js (the M10 am16 pick path) calls THESE keepOrDrop and countCheck (M20 am8 item 3: its own two are gone), as does the check block.
5
5
  // The pick vocabulary and its keep-or-drop: a suggested check is kept only if its rule is on bareguard's list and offered here, it carries only that rule's own fields, and every
6
6
  // number is one the person's rule names.
7
7
  import { rubricVocabulary } from 'bareguard';
@@ -18,7 +18,7 @@ const NUM_FIELDS = ['value', 'size', 'wordsPerSection'];
18
18
 
19
19
  const WORD_FIELDS = ['names', 'phrases'];
20
20
 
21
- // ---- the guardrail readers (fwd src/declaration.js@v0.29.0) ------------------------------------------------------------------------------
21
+ // ---- the guardrail readers: THE one copy (M20 am8 item 2; src/declaration.js re-exports them) ------------------------------------------------------------------------------
22
22
  const readNumber = (/** @type {string} */ t) => Number(t.replace(/,/g, ''));
23
23
 
24
24
  /** every whole-output word number in a guardrail ("under 600 words" -> [600]); a "<n> words each" / "per section" size is never listed here @param {unknown} g @returns {number[]} */
@@ -48,9 +48,9 @@ export function guardrailSectionCount(g) {
48
48
  return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
49
49
  }
50
50
 
51
- /** the first "<N> bullets / list items / items / lines / points" in a guardrail (digits, or one..ten), or null @param {unknown} g @returns {number|null} */
51
+ /** the first "<N> bullets / list items / items / lines / points" in a guardrail (digits, or one..ten; not a price like "$5 per item" or a decimal), or null @param {unknown} g @returns {number|null} */
52
52
  export function guardrailItemCount(g) {
53
- const m = typeof g === 'string' ? /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?(?:bullets?|bullet\s+points?|list\s+items?|items?|lines?|points?)\b/i.exec(g) : null;
53
+ const m = typeof g === 'string' ? /(?<![$€£\d.,])\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten)\s+(?:\w+\s+)?(?:bullets?|bullet\s+points?|list\s+items?|items?|lines?|points?)\b/i.exec(g) : null;
54
54
  if (!m) return null;
55
55
  return /^\d+$/.test(m[1]) ? Number(m[1]) : NUMBER_WORDS[m[1].toLowerCase()];
56
56
  }
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
+ }