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/flow.js CHANGED
@@ -31,6 +31,7 @@ import { signFlow, verifyFlow } from './signature.js';
31
31
  import { validateDeclaration } from './declaration.js';
32
32
  import { describeChange } from './signed-diff.js';
33
33
  import { stripTrigger } from './trigger-line.js';
34
+ import { readFileInside } from './inside.js';
34
35
 
35
36
  /** @typedef {import('./types.js').WriteFlowResult} WriteFlowResult */
36
37
  /** @typedef {import('./types.js').ReadFlowResult} ReadFlowResult */
@@ -313,85 +314,24 @@ export function claimRunId(flowDir) {
313
314
  }
314
315
 
315
316
  /**
316
- * F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
317
- * in src/ and bin/ routes through to read a file that lives inside a run
318
- * dir or flow dir — closing the symlink-escape class at the source instead
319
- * of patching each reader a second time. `resolveInside(baseDir, relPath)`
320
- * requires the target to both (a) not itself be a symlink and (b) realpath
321
- * to somewhere inside `realpath(baseDir)` — the second check alone also
322
- * catches a symlinked ANCESTOR directory partway down `relPath` (e.g.
323
- * `asks/` itself replaced by a symlink to an outside directory), the same
324
- * shape `readFlow`'s own `runs/` check and `resolveRunDir` already apply one
325
- * level up. A path that does not exist yet is reported as `missing: true`
326
- * (never a red) so every existing caller keeps its own "not written yet"
327
- * behaviour unchanged.
328
- *
329
- * @param {string} baseDir
330
- * @param {string} relPath
331
- * @returns {{ok:true, full:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
317
+ * M20 am1 item 4: the ONE reader of a DRAFT's `log.json` (`<dir>/<rel>/log.json`, or `<dir>/log.json` with no `rel`): what the drafter kept of its rounds,
318
+ * its `checkCard` and its `action`. The run's `log.json` is another file, read only by `readLog` (src/books.js). `null` when missing, refused by the
319
+ * gateway, unparseable or not an object (a torn write), never a thrown error.
320
+ * @param {string} dir @param {string} [rel] a plan folder under `dir` (`draft`, `draft-<n>`)
321
+ * @returns {any|null}
332
322
  */
333
- export function resolveInside(baseDir, relPath) {
334
- const full = path.join(baseDir, relPath);
335
- let stat;
336
- try {
337
- stat = lstatSync(full);
338
- } catch {
339
- return { ok: false, missing: true };
340
- }
341
- if (stat.isSymbolicLink()) {
342
- return { ok: false, missing: false, red: `"${relPath}" is a symlink, refused` };
343
- }
344
- let realBase;
345
- let realFull;
346
- try {
347
- realBase = realpathSync(baseDir);
348
- realFull = realpathSync(full);
349
- } catch (err) {
350
- return { ok: false, missing: false, red: `could not resolve "${relPath}" — ${err.message}` };
351
- }
352
- if (realFull !== realBase && !realFull.startsWith(realBase + path.sep)) {
353
- return { ok: false, missing: false, red: `"${relPath}" resolves outside its directory — refused` };
354
- }
355
- return { ok: true, full };
323
+ export function readDraftLog(dir, rel = '') {
324
+ return readJsonFile(dir, rel === '' ? 'log.json' : `${rel}/log.json`);
356
325
  }
357
326
 
358
327
  /**
359
- * `resolveInside` plus the actual read — every raw-text book reader's one
360
- * gateway. Same result shape as `resolveInside`, plus `{ok:true, text}`.
361
- * @param {string} baseDir
362
- * @param {string} relPath
363
- * @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
328
+ * M20 am3 item 12: the ONE tolerant JSON read of a file in a folder, through the gateway: the parsed object, or null when the file is missing, refused,
329
+ * unparseable (a torn write) or not an object. Never throws. @param {string} dir @param {string} rel @returns {any|null}
364
330
  */
365
- export function readFileInside(baseDir, relPath) {
366
- const resolved = resolveInside(baseDir, relPath);
367
- if (!resolved.ok) return resolved;
368
- try {
369
- return { ok: true, text: readFileSync(resolved.full, 'utf8') };
370
- } catch (err) {
371
- return { ok: false, missing: false, red: `could not read "${relPath}" — ${err.message}` };
372
- }
373
- }
374
-
375
- /**
376
- * `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
377
- * itself is a symlink or resolves outside `baseDir`, and skips (never
378
- * follows) any individual entry that is itself a symlink — a directory
379
- * listing must never hand a caller a name that, joined back onto `relDir`,
380
- * would escape `baseDir`. `[]` when `relDir` doesn't exist.
381
- * @param {string} baseDir
382
- * @param {string} relDir
383
- * @returns {string[]}
384
- */
385
- export function readdirInside(baseDir, relDir) {
386
- const resolved = resolveInside(baseDir, relDir);
387
- if (!resolved.ok) return [];
388
- let entries;
389
- try {
390
- entries = readdirSync(resolved.full, { withFileTypes: true });
391
- } catch {
392
- return [];
393
- }
394
- return entries.filter((e) => !e.isSymbolicLink()).map((e) => e.name);
331
+ export function readJsonFile(dir, rel) {
332
+ const r = readFileInside(dir, rel);
333
+ if (!r.ok) return null;
334
+ try { const j = JSON.parse(r.text); return j !== null && typeof j === 'object' && !Array.isArray(j) ? j : null; } catch { return null; }
395
335
  }
396
336
 
397
337
  function readTextFile(filePath, label, reds) {
@@ -709,19 +649,31 @@ function replaceSigned({
709
649
  export function planForReuse({
710
650
  root, name, runDir, catalogue,
711
651
  }) {
712
- const kept = readRunJobCopy(runDir, catalogue);
713
- if (!kept.present) return { ok: true, same: true };
652
+ const job = sameJob({ flowDir: path.join(root, name), runDir, catalogue });
653
+ if (!job.present) return { ok: true, same: true };
714
654
  const runId = path.basename(runDir);
715
- if (!kept.ok) return { ok: false, red: `The plan ${runId} kept does not match its signature (${kept.reds[0]}), so it cannot be reused. Nothing was started.` };
716
- const flowDir = path.join(root, name);
717
- const a = readFileInside(runDir, `${RUN_JOB_DIR}/declaration.json`);
655
+ if (!job.ok) return { ok: false, red: `The plan ${runId} kept does not match its signature (${job.reds[0]}), so it cannot be reused. Nothing was started.` };
656
+ if (job.same) return { ok: true, same: true };
657
+ const { present, same, ...rest } = job;
658
+ void present; void same;
659
+ return { ok: true, same: false, read: /** @type {any} */ (rest) };
660
+ }
661
+
662
+ /**
663
+ * M20 am3 item 1 (as am3a): the ONE rule for "this run ran the job the flow holds now": the run's verified job copy (`readRunJobCopy`), the exact
664
+ * declaration, the prose without its trigger line. `{present:false}` = the run kept no copy (before M6); `{present:true, ok:false, reds}` = a copy that
665
+ * fails its signature; `{present:true, ok:true, same, ...copy}` otherwise.
666
+ * @param {{flowDir: string, runDir: string, catalogue: unknown}} a
667
+ * @returns {{present: false} | {present: true, ok: false, reds: string[]} | ({present: true, same: boolean} & ReadFlowResult & {ok: true})}
668
+ */
669
+ export function sameJob({ flowDir, runDir, catalogue }) {
670
+ const kept = readRunJobCopy(runDir, catalogue);
671
+ if (!kept.present) return { present: false };
672
+ if (!kept.ok) return /** @type {any} */ ({ present: true, ok: false, reds: kept.reds });
718
673
  const b = readFileInside(flowDir, 'declaration.json');
719
- const ap = readFileInside(runDir, `${RUN_JOB_DIR}/prose.txt`);
720
674
  const bp = readFileInside(flowDir, 'prose.txt');
721
- if (a.ok && b.ok && ap.ok && bp.ok && a.text === b.text && stripTrigger(ap.text) === stripTrigger(bp.text)) return { ok: true, same: true };
722
- const { present, ...rest } = kept;
723
- void present;
724
- return { ok: true, same: false, read: /** @type {any} */ (rest) };
675
+ const same = b.ok && bp.ok && kept.declarationText === b.text && stripTrigger(kept.proseText ?? '') === stripTrigger(bp.text);
676
+ return /** @type {any} */ ({ ...kept, same });
725
677
  }
726
678
 
727
679
  /**
@@ -1024,11 +976,14 @@ export function readRunJobCopy(runDir, catalogue) {
1024
976
  if (reds.length > 0) return { present: true, ok: false, reds };
1025
977
  const verified = verifyFlow({ proseText, declarationText, signature: signatureJson });
1026
978
  if (!verified.ok) return { present: true, ok: false, reds: [...verified.reds] };
979
+ const read = interpretSigned({
980
+ proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
981
+ });
982
+ // a good read carries the verified bytes, so no caller reads `job/` a second time (M20 am3 item 2)
1027
983
  return {
1028
984
  present: /** @type {true} */ (true),
1029
- ...interpretSigned({
1030
- proseText: /** @type {string} */ (proseText), declarationJson, signatureJson, catalogue, dir,
1031
- }),
985
+ ...read,
986
+ ...(read.ok ? { proseText: /** @type {string} */ (proseText), declarationText: /** @type {string} */ (declarationText) } : {}),
1032
987
  };
1033
988
  }
1034
989
 
package/src/flowmodel.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // One writer (`writeModelRecord`), one reader (`readModelRecord`); both go through the safe gateway.
5
5
  import { writeFileSync, renameSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
- import { readFileInside } from './flow.js';
7
+ import { readFileInside } from './inside.js';
8
8
  import { readRunRecord, readRunThinking } from './runfile.js';
9
9
  import { isKeyName } from './provider.js';
10
10
 
package/src/index.js CHANGED
@@ -11,11 +11,12 @@ export {
11
11
  checkFlowName, checkRunId, resolveRunDir, writeFlow, readFlow, listFlowNames, listRunIds, FLOW_FILES,
12
12
  } from './flow.js';
13
13
  export {
14
- runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS, readAsk, readRunState, readLog,
14
+ runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS, readAsk,
15
15
  } from './runner.js';
16
+ export { readRunState, readLog } from './books.js';
16
17
  export { closeByClass } from './closers.js';
17
18
  export {
18
- makeFileAskStep, answerAsk, readAskEvidence, writeAskArchive, listArchivedAsks,
19
+ answerAsk, readAskEvidence, writeAskArchive, listArchivedAsks,
19
20
  } from './ask.js';
20
21
  export {
21
22
  appendAudit, appendHistory, readAudit, readHistory, auditRowTokens, auditRowTools,
package/src/inside.js ADDED
@@ -0,0 +1,86 @@
1
+ // M20 am3b item 2 (loop map): the ONE gateway every book reader routes through, moved verbatim out of src/flow.js so the readers it serves (placerule, runfile, sheetrun) need not import the flow file.
2
+ import { lstatSync, readdirSync, readFileSync, realpathSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /**
6
+ * F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
7
+ * in src/ and bin/ routes through to read a file that lives inside a run
8
+ * dir or flow dir — closing the symlink-escape class at the source instead
9
+ * of patching each reader a second time. `resolveInside(baseDir, relPath)`
10
+ * requires the target to both (a) not itself be a symlink and (b) realpath
11
+ * to somewhere inside `realpath(baseDir)` — the second check alone also
12
+ * catches a symlinked ANCESTOR directory partway down `relPath` (e.g.
13
+ * `asks/` itself replaced by a symlink to an outside directory), the same
14
+ * shape `readFlow`'s own `runs/` check and `resolveRunDir` already apply one
15
+ * level up. A path that does not exist yet is reported as `missing: true`
16
+ * (never a red) so every existing caller keeps its own "not written yet"
17
+ * behaviour unchanged.
18
+ *
19
+ * @param {string} baseDir
20
+ * @param {string} relPath
21
+ * @returns {{ok:true, full:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
22
+ */
23
+ export function resolveInside(baseDir, relPath) {
24
+ const full = path.join(baseDir, relPath);
25
+ let stat;
26
+ try {
27
+ stat = lstatSync(full);
28
+ } catch {
29
+ return { ok: false, missing: true };
30
+ }
31
+ if (stat.isSymbolicLink()) {
32
+ return { ok: false, missing: false, red: `"${relPath}" is a symlink, refused` };
33
+ }
34
+ let realBase;
35
+ let realFull;
36
+ try {
37
+ realBase = realpathSync(baseDir);
38
+ realFull = realpathSync(full);
39
+ } catch (err) {
40
+ return { ok: false, missing: false, red: `could not resolve "${relPath}" — ${err.message}` };
41
+ }
42
+ if (realFull !== realBase && !realFull.startsWith(realBase + path.sep)) {
43
+ return { ok: false, missing: false, red: `"${relPath}" resolves outside its directory — refused` };
44
+ }
45
+ return { ok: true, full };
46
+ }
47
+
48
+ /**
49
+ * `resolveInside` plus the actual read — every raw-text book reader's one
50
+ * gateway. Same result shape as `resolveInside`, plus `{ok:true, text}`.
51
+ * @param {string} baseDir
52
+ * @param {string} relPath
53
+ * @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
54
+ */
55
+ export function readFileInside(baseDir, relPath) {
56
+ const resolved = resolveInside(baseDir, relPath);
57
+ if (!resolved.ok) return resolved;
58
+ try {
59
+ return { ok: true, text: readFileSync(resolved.full, 'utf8') };
60
+ } catch (err) {
61
+ return { ok: false, missing: false, red: `could not read "${relPath}" — ${err.message}` };
62
+ }
63
+ }
64
+
65
+
66
+ /**
67
+ * `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
68
+ * itself is a symlink or resolves outside `baseDir`, and skips (never
69
+ * follows) any individual entry that is itself a symlink — a directory
70
+ * listing must never hand a caller a name that, joined back onto `relDir`,
71
+ * would escape `baseDir`. `[]` when `relDir` doesn't exist.
72
+ * @param {string} baseDir
73
+ * @param {string} relDir
74
+ * @returns {string[]}
75
+ */
76
+ export function readdirInside(baseDir, relDir) {
77
+ const resolved = resolveInside(baseDir, relDir);
78
+ if (!resolved.ok) return [];
79
+ let entries;
80
+ try {
81
+ entries = readdirSync(resolved.full, { withFileTypes: true });
82
+ } catch {
83
+ return [];
84
+ }
85
+ return entries.filter((e) => !e.isSymbolicLink()).map((e) => e.name);
86
+ }
package/src/isrec.js ADDED
@@ -0,0 +1,2 @@
1
+ // one owner for the plain-object predicate (fwd's own files; borrowed copies keep theirs)
2
+ export const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
@@ -2,8 +2,9 @@
2
2
  // next row must not glue onto those bytes (the glued line would fail to parse, be skipped, and the row would be lost). Readers skip an unparseable line;
3
3
  // this is its other half, and the two only work together.
4
4
  import {
5
- appendFileSync, closeSync, existsSync, fstatSync, openSync, readFileSync, readSync,
5
+ appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync,
6
6
  } from 'node:fs';
7
+ import { dirname } from 'node:path';
7
8
 
8
9
  /** The ledger's text, '' when there is no file yet. @param {string} file */
9
10
  export function ledgerText(file) {
@@ -27,3 +28,34 @@ function endsTorn(file) {
27
28
  export function appendRow(file, row, options) {
28
29
  appendFileSync(file, `${endsTorn(file) ? '\n' : ''}${JSON.stringify(row)}\n`, options);
29
30
  }
31
+
32
+ /** M20 am3 item 12: the ONE tolerant JSONL parse: every line of the text that parses, in order; a blank, torn or unparseable line is skipped. @param {string} text @returns {any[]} */
33
+ export function parseJsonl(text) {
34
+ return text.split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
35
+ }
36
+
37
+ /**
38
+ * The ONE reader of a trigger ledger (the files ledger and the schedule ledger): every row on disk that parses, oldest first; a missing file is no rows;
39
+ * a line a crash tore mid-append is skipped (it counts as not written; `appendTriggerLedger` starts each append on a fresh line, so it never glues onto the next row).
40
+ * @param {string} file @param {string} [sig] M9 am20: only the rows of that schedule signing (the one schedule ledger carries every signing's rows); absent = every row
41
+ * @returns {any[]}
42
+ */
43
+ export function readTriggerLedger(file, sig) {
44
+ const rows = parseJsonl(ledgerText(file));
45
+ return sig === undefined ? rows : rows.filter((r) => r.sig === sig);
46
+ }
47
+
48
+ /**
49
+ * The ONE appender of a trigger ledger: write-once by id within a signing (a second row with the same id is not written). `sig` is stamped on the row.
50
+ * @param {string} file @param {{id: string, [k: string]: any}} row @param {string} [sig] @param {{throwIfWritten?: boolean}} [o] `throwIfWritten`: a row already on disk is an error, not `false`
51
+ * @returns {boolean} written
52
+ */
53
+ export function appendTriggerLedger(file, row, sig, { throwIfWritten = false } = {}) {
54
+ if (readTriggerLedger(file, sig).some((r) => r.id === row.id)) {
55
+ if (throwIfWritten) throw new Error(`ledger row ${row.id} already written`);
56
+ return false;
57
+ }
58
+ mkdirSync(dirname(file), { recursive: true });
59
+ appendRow(file, sig === undefined ? row : { ...row, sig });
60
+ return true;
61
+ }
package/src/learn.js CHANGED
@@ -260,7 +260,7 @@ export function quoteLines(gap) {
260
260
  }
261
261
 
262
262
  /** terminal words that mean the run ended well */
263
- const isGreen = (/** @type {unknown} */ o) => o === 'green' || o === 'already-green';
263
+ const isGreen = (/** @type {unknown} */ o) => o === 'green';
264
264
  /** escalation categories that make a run NOISE: the instrument, not the work, failed */
265
265
  const NOISE_CATEGORIES = new Set(['provider-red', 'close-crashed']);
266
266
 
package/src/learnstore.js CHANGED
@@ -13,10 +13,14 @@ import { homedir } from 'node:os';
13
13
  import { compareNatural } from './natural.js';
14
14
  import { configHome, configDoorHome, readConfig } from './config.js';
15
15
  import { emptyLedger, redactDeep, countLedger, releasePending, recordHealth, buildCards, placeOf, renderHints } from './learn.js';
16
- import { readAudit, readHistory } from './books.js';
16
+ import {
17
+ readAudit, readHistory, readLog, endRow, isTryVerdict, isRedTry, isNoiseEnding, isNotRunEnd,
18
+ } from './books.js';
17
19
  import { readChecks } from './diary.js';
18
20
  import { readRunInputs } from './runfile.js';
19
- import { readFileInside, readdirInside, listFlowNames, listRunIds } from './flow.js';
21
+ import { listFlowNames, listRunIds, readRunJobCopy } from './flow.js';
22
+ import { readFileInside, readdirInside } from './inside.js';
23
+ import { loadCatalogue } from './catalogue.js';
20
24
 
21
25
  /**
22
26
  * M8 item 5a (loose end): the ONE function that turns a source as written into a place. The run-end notes (`learnAtRunEnd`: a path the panel/CLI gave the run) and
@@ -184,15 +188,8 @@ function unifiedDiff(a, b, ctx = 1) {
184
188
  return out.join('\n');
185
189
  }
186
190
 
187
- /** @param {string} runDir @param {string} rel @returns {any} the parsed JSON file inside the run folder, or null when absent / unreadable */
188
- function jsonIn(runDir, rel) {
189
- const r = readFileInside(runDir, rel);
190
- if (!r.ok) return null;
191
- try { return JSON.parse(r.text); } catch { return null; }
192
- }
193
-
194
191
  /** audit.jsonl rows that are a step's TRY with a verdict on its output; a human redo (class hitl + red), a pause, a stop and a funding halt are not one. */
195
- const isTry = (/** @type {any} */ r) => Number.isInteger(r.attempt) && ['green', 'hitl', 'softgreen', 'red', 'not-done'].includes(r.verdict) && !(r.class === 'hitl' && r.verdict === 'red');
192
+ const isTry = (/** @type {any} */ r) => Number.isInteger(r.attempt) && isTryVerdict(r.verdict) && !(r.class === 'hitl' && r.verdict === 'red');
196
193
 
197
194
  /**
198
195
  * One finished run's folder -> the event list buildCards reads, plus the check texts and the model. ONE adapter, map never invent
@@ -207,11 +204,13 @@ export function eventsOfRun(runDir, workflow) {
207
204
  const audit = readAudit(runDir);
208
205
  const rows = audit.filter(isTry);
209
206
  if (!rows.length) return null;
210
- const log = jsonIn(runDir, 'log.json') ?? {};
211
- const decl = jsonIn(runDir, 'job/declaration.json') ?? { steps: [] };
207
+ const log = readLog(runDir) ?? {};
208
+ const cat = loadCatalogue();
209
+ const job = cat.ok ? readRunJobCopy(runDir, cat.primitives) : { present: /** @type {false} */ (false) }; // M20 am3 item 2: a copy that fails its signature is no job
210
+ const decl = job.present && job.ok ? job.declaration : { steps: [] };
212
211
  const frozen = readRunInputs(runDir);
213
212
  const inputs = frozen.ok ? frozen.entries : null;
214
- const prose = (() => { const r = readFileInside(runDir, 'job/prose.txt'); return r.ok ? r.text : ''; })();
213
+ const prose = job.present && job.ok ? (job.proseText ?? '') : '';
215
214
  const checks = readChecks(runDir);
216
215
  const made = new Set(readdirInside(runDir, 'artifacts'));
217
216
  const outBy = new Map((log.attempts || []).map((/** @type {any} */ a) => [`${a.step}#${a.attempt}`, a.modelOutput]));
@@ -239,7 +238,7 @@ export function eventsOfRun(runDir, workflow) {
239
238
  let diff = '';
240
239
  if (mo !== undefined) { const after = JSON.stringify(mo, null, 2); diff = unifiedDiff(prevOut.has(a.step) ? /** @type {string} */ (prevOut.get(a.step)) : '', after); prevOut.set(a.step, after); }
241
240
  if (made.has(`${a.step}.json`)) push({ type: 'attempt-diff', files: [{ path: `artifacts/${a.step}.json`, diff: diff.slice(0, 4096), truncated: diff.length > 4096 }], binary: [], truncated: false });
242
- if ((a.verdict === 'red' || a.verdict === 'not-done') && typeof a.gap === 'string' && a.gap !== '') {
241
+ if (isRedTry(a.verdict) && typeof a.gap === 'string' && a.gap !== '') {
243
242
  const f = checks.find((c) => c.step === a.step && c.try === a.attempt)?.checks?.find((/** @type {any} */ x) => !x.ok);
244
243
  if (f && !questions.has(name)) questions.set(name, String(f.text));
245
244
  push({ type: 'exit-eval', step: a.step, results: [{ type: name, pass: false, detail: a.gap }] });
@@ -251,7 +250,7 @@ export function eventsOfRun(runDir, workflow) {
251
250
  // M8 am4 item 3: the two noise categories bareloop's buildCards reads off an `escalation` event, seen here in the audit: a provider red
252
251
  // (verdict 'provider-red', the transport fault twice) and a closer that crashed or was unparseable (verdict 'close-casualty'). Both end
253
252
  // the run, so a row of either is the run's last word. Neither is a try (isTry), so it never makes a red moment of its own.
254
- const noiseRow = audit.findLast((r) => r.verdict === 'provider-red' || r.verdict === 'close-casualty');
253
+ const noiseRow = audit.findLast((r) => isNoiseEnding(r.verdict));
255
254
  if (noiseRow) push({ type: 'escalation', category: noiseRow.verdict === 'provider-red' ? 'provider-red' : 'close-crashed' });
256
255
  push({ type: 'job-end', outcome: log.outcome === 'complete' ? 'green' : String(log.outcome) });
257
256
  return { events, questions, model, source: typeof inputs?.[0]?.source === 'string' ? inputs[0].source : null };
@@ -276,8 +275,6 @@ export function learnAtRunEnd({ home, workflow, runId, runDir, now = new Date()
276
275
  return { ...r, noise: build.noise, cards: build.cards.length };
277
276
  }
278
277
 
279
- /** M8 am4 item 2: a run waiting at an ask has not ended ('paused', or a Stop whose set-aside failed). ONE decider: the runner's run-end tally and the seed both read it. */
280
- export const NOT_A_RUN_END = new Set(['paused', 'stop-failed', 'skipped']); // M12 p3: a skipped ticket is not a job run with anything to learn from
281
278
 
282
279
  /**
283
280
  * M8 am6: seed the ledger from every run already recorded under `root` (every job, every ended run), oldest first by the run's own end time
@@ -307,13 +304,14 @@ export function seedLedger({ root, home }) {
307
304
  out.read += 1;
308
305
  const runDir = join(flowDir, 'runs', runId);
309
306
  try {
310
- const log = jsonIn(runDir, 'log.json');
311
- if (log && NOT_A_RUN_END.has(log.outcome)) { out.skipped['still-waiting'] += 1; continue; }
307
+ const log = readLog(runDir);
308
+ if (log && isNotRunEnd(log.outcome)) { out.skipped['still-waiting'] += 1; continue; }
312
309
  if (history === null) { out.skipped.unreadable += 1; continue; }
313
- const endRow = history.findLast((r) => r?.runId === runId && !NOT_A_RUN_END.has(r.outcome) && Number.isFinite(Date.parse(r.at)));
314
- if (!endRow) { out.skipped['no-end'] += 1; continue; }
310
+ const last = endRow(history, runDir, runId);
311
+ const end = last && !isNotRunEnd(last.outcome) && Number.isFinite(Date.parse(last.at)) ? last : null;
312
+ if (!end) { out.skipped['no-end'] += 1; continue; }
315
313
  if (!log) { out.skipped.unreadable += 1; continue; }
316
- todo.push({ workflow, runId, runDir, end: new Date(endRow.at) });
314
+ todo.push({ workflow, runId, runDir, end: new Date(end.at) });
317
315
  } catch { out.skipped.unreadable += 1; }
318
316
  }
319
317
  }
@@ -4,15 +4,14 @@
4
4
  // its lines are. The write is a temporary file, then a rename, so a reader sees the old file or the new one; the other section is carried over untouched.
5
5
  import { writeFileSync, renameSync } from 'node:fs';
6
6
  import { join } from 'node:path';
7
- import { readFileInside } from './flow.js';
7
+ import { readFileInside } from './inside.js';
8
+ import { isRec } from './isrec.js';
8
9
 
9
10
  /** the record's name in the run's own folder */
10
11
  export const LINE_CHECKS_FILE = 'line-checks.json';
11
12
 
12
13
  /** @typedef {'cited'|'sheet'} LineSection */
13
14
 
14
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
15
-
16
15
  /** The whole file as parsed, or why not. @param {string} runDir @returns {{ok: true, rec: Record<string, any>}|{ok: false, missing: boolean, red: string}} */
17
16
  function readWhole(runDir) {
18
17
  const r = readFileInside(runDir, LINE_CHECKS_FILE);
package/src/liveness.js CHANGED
@@ -160,6 +160,9 @@ export function readResumeLock(runDir) {
160
160
  return { state: alive === true ? 'live' : alive === false ? 'dead' : 'unknown', pid: h.pid, procStart, path };
161
161
  }
162
162
 
163
+ /** M20 am8: the one question "may someone still hold this run's resume lock": a live holder, or one whose liveness cannot be told (never treated as dead) @param {unknown} state a `readResumeLock` state @returns {boolean} */
164
+ export const lockMayBeHeld = (state) => state === 'live' || state === 'unknown';
165
+
163
166
  /** The run's books, for the 10-minute fallback: state, audit, model log, spend ledger, and the pid file itself. */
164
167
  const BOOK_FILES = ['state.json', 'audit.jsonl', 'log.json', 'spend.jsonl', 'pids.jsonl'];
165
168
  const FRESH_MS = 10 * 60 * 1000;
package/src/mcp-use.js CHANGED
@@ -3,8 +3,10 @@
3
3
  // - a ticket read: `run.json` `inputs[].mcp.calls` (server + tool; the file holds no time, so `last` is the file's mtime);
4
4
  // - a step's tool call: a `kind:"tool"` row of `diary.jsonl` whose tool is `<server>_<tool>` (M13 piece 2); `decision:"deny"` is a denied call, counted apart and not as a use.
5
5
  // A torn or unreadable file is skipped, row by row (its rows go missing from the count; it never breaks the page).
6
- import { readdirSync, readFileSync, statSync } from 'node:fs';
6
+ import { readdirSync, statSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
+ import { readRunRecord } from './runfile.js';
9
+ import { readTools } from './diary.js';
8
10
 
9
11
  const safeDir = (/** @type {string} */ p) => { try { return readdirSync(p); } catch { return []; } };
10
12
 
@@ -30,7 +32,9 @@ export function countMcpUse(root, servers) {
30
32
  const dir = join(root, flow, 'runs', name);
31
33
  const key = `${flow}/${name}`;
32
34
  try {
33
- const j = JSON.parse(readFileSync(join(dir, 'run.json'), 'utf8'));
35
+ const rr = readRunRecord(dir);
36
+ if (!rr.ok) throw new Error(rr.red);
37
+ const j = rr.rec;
34
38
  const mtime = statSync(join(dir, 'run.json')).mtime.toISOString();
35
39
  for (const i of Array.isArray(j?.inputs) ? j.inputs : []) {
36
40
  const m = i?.mcp;
@@ -38,13 +42,8 @@ export function countMcpUse(root, servers) {
38
42
  for (const c of Array.isArray(m.calls) ? m.calls : []) if (typeof c?.tool === 'string') use(m.server, c.tool, key, mtime, false);
39
43
  }
40
44
  } catch { /* no run.json, or torn: nothing counted from it */ }
41
- let text;
42
- try { text = readFileSync(join(dir, 'diary.jsonl'), 'utf8'); } catch { continue; }
43
- for (const line of text.split('\n')) {
44
- if (!line.includes('"kind":"tool"')) continue;
45
- let r;
46
- try { r = JSON.parse(line); } catch { continue; }
47
- if (r?.kind !== 'tool' || typeof r.tool !== 'string') continue;
45
+ for (const r of readTools(dir)) {
46
+ if (typeof r?.tool !== 'string') continue;
48
47
  const server = byLength.find((s) => r.tool.startsWith(`${s}_`) && r.tool.length > s.length + 1);
49
48
  if (server) use(server, r.tool.slice(server.length + 1), key, typeof r.at === 'string' ? r.at : '', r.decision === 'deny');
50
49
  }
package/src/memo.js CHANGED
@@ -3,10 +3,12 @@
3
3
  // `asks/<id>.json` (the human's words, by `listArchivedAsks`), `job/declaration.json` (step order) and `run.json`'s `rerun` section. It writes nothing: the exact
4
4
  // text a try was handed is kept by that try's audit row (`memoText`, runner.js `makeAuditRow`), so no new run-folder file. Pure over those files, so it survives a
5
5
  // pause, a resume and a restart. It never carries money or time (no cost, no duration); gap texts are the closer's own words, kept as they are (cut at GAP_CHARS).
6
- import { readAudit } from './books.js';
7
- import { readFileInside } from './flow.js';
6
+ import { readAudit, isGoodEnding } from './books.js';
7
+ import { readRunJobCopy } from './flow.js';
8
+ import { readFileInside } from './inside.js';
9
+ import { loadCatalogue } from './catalogue.js';
8
10
  import { listArchivedAsks, DECISION_STATUS } from './ask.js';
9
- import { readRunRecord } from './runfile.js';
11
+ import { readRerunWords } from './runfile.js';
10
12
  import {
11
13
  foldCards, nameOf, errorKinds, flaggedTokens, quoteLines,
12
14
  } from './learn.js';
@@ -19,8 +21,6 @@ export const MEMO_CAP = 4000;
19
21
  /** one gap text is cut here (with an ellipsis), so a single long red cannot eat the whole cap */
20
22
  const GAP_CHARS = 300;
21
23
 
22
- /** a try that closed well; every other verdict of a model try is a failure the memo names */
23
- const WELL = new Set(['green', 'hitl']);
24
24
  const DECISION_OF = Object.fromEntries(Object.entries(DECISION_STATUS).map(([k, v]) => [v, k]));
25
25
 
26
26
  const oneLine = (/** @type {unknown} */ t) => (typeof t === 'string' ? t.replace(/\s+/g, ' ').trim() : '');
@@ -29,21 +29,18 @@ const says = (/** @type {string} */ words) => (words === '' ? '' : ` — user sa
29
29
 
30
30
  /** step names in the job's own order, from the run's copy of the job (`[]` when it cannot be read) @param {string} runDir @returns {string[]} */
31
31
  function stepOrder(runDir) {
32
- const r = readFileInside(runDir, 'job/declaration.json');
33
- if (!r.ok) return [];
34
- try {
35
- const steps = JSON.parse(r.text)?.steps;
36
- return Array.isArray(steps) ? steps.map((s) => s?.emits).filter((e) => typeof e === 'string') : [];
37
- } catch { return []; }
32
+ const cat = loadCatalogue();
33
+ const job = cat.ok ? readRunJobCopy(runDir, cat.primitives) : { present: /** @type {false} */ (false) }; // M20 am3 item 2: a copy that fails its signature is no job
34
+ const steps = job.present && job.ok ? job.declaration?.steps : null;
35
+ return Array.isArray(steps) ? steps.map((s) => s?.emits).filter((e) => typeof e === 'string') : [];
38
36
  }
39
37
 
40
38
  /** the human lines: the rerun line first (this run began as a rerun), then one per answered ask in the order they were asked (N counts every ask of this run) @param {string} runDir @param {string[]} order @returns {string[]} */
41
39
  function humanLines(runDir, order) {
42
40
  /** @type {string[]} */
43
41
  const lines = [];
44
- const rec = readRunRecord(runDir);
45
- const rr = rec.ok ? rec.rec.rerun : null;
46
- if (rr && typeof rr === 'object' && rr.decision === 'rerun' && typeof rr.words === 'string') lines.push(`rerun${says(oneLine(rr.words))}`);
42
+ const rerunWords = readRerunWords(runDir);
43
+ if (rerunWords !== null) lines.push(`rerun${says(oneLine(rerunWords))}`);
47
44
  const listed = listArchivedAsks(runDir);
48
45
  if (!listed.archived) return lines;
49
46
  const asks = [...listed.asks].sort((a, b) => String(a.askedAt ?? '').localeCompare(String(b.askedAt ?? '')));
@@ -95,10 +92,10 @@ export function buildMemo(runDir, { step, cap = MEMO_CAP }) {
95
92
 
96
93
  const last = tries.at(-1) ?? null;
97
94
  // item 6: the newest failure's words are left out when the retry (the same step, straight after a failure) already gets them as its gap
98
- const retryGetsGap = last !== null && last.step === step && !WELL.has(last.verdict);
95
+ const retryGetsGap = last !== null && last.step === step && !isGoodEnding(last.verdict);
99
96
  const earlier = tries.slice(0, -1);
100
97
  const sameStep = earlier.filter((t) => t.step === step);
101
- const failures = earlier.filter((t) => t.step !== step && !WELL.has(t.verdict));
98
+ const failures = earlier.filter((t) => t.step !== step && !isGoodEnding(t.verdict));
102
99
  const label = (/** @type {{step: string, n: number, verdict: string, gap: string}} */ t) => `step ${t.step} try ${t.n} — result: ${t.verdict}`;
103
100
  const gapOf = (/** @type {{gap: string}} */ t) => (t.gap === '' ? '' : ` — ${cutGap(t.gap)}`);
104
101
  const foldLine = (/** @type {string} */ kind, /** @type {any[]} */ g) => ({ kind, text: `${kind}: ${label(g[0])}${gapOf(g[0])}${g.length > 1 ? ` (x${g.length})` : ''}` });
package/src/minrule.js ADDED
@@ -0,0 +1,16 @@
1
+ // M19 amendment 13: a job needs at least one `~` rule of the person's. The ONE writer of the refusal words; the ONE count is the drafter's own reader
2
+ // (parseSignedText) with the block's own splitter (rulesOfLine). `!` and `$` rows are never in the prose, so only typed `~` lines count.
3
+ import { parseSignedText } from './signed-text.js';
4
+ import { rulesOfLine } from './sheetblock.js';
5
+
6
+ export const MIN_RULE_REFUSAL = 'Add at least one rule (~) for this job — for example what the result must include, or what must stay true.';
7
+
8
+ /**
9
+ * @param {string} prose the job prose `fwdloop draft` reads
10
+ * @returns {string|null} the refusal words, or null when the prose carries at least one `~` rule. Prose the reader cannot parse is not this gate's to refuse (the drafter's own red wins).
11
+ */
12
+ export function minRuleRefusal(prose) {
13
+ const p = parseSignedText(prose);
14
+ if (!p.ok) return null;
15
+ return p.lines.reduce((n, l) => n + rulesOfLine(l).length, 0) === 0 ? MIN_RULE_REFUSAL : null;
16
+ }
package/src/model-step.js CHANGED
@@ -29,16 +29,16 @@ import { Loop, HaltError } from 'bare-agent';
29
29
  import { GateRefusal } from './primitives.js';
30
30
  import { appendCall, appendTool, nextRound } from './diary.js';
31
31
  import { ConfigError } from './config.js';
32
- import { worstThinkingStatus } from './thinking.js';
32
+ import { worstThinkingStatus, isThinkingMode } from './thinking.js';
33
33
  import { citedBrief, toldPicks } from './citedcheck.js';
34
34
  import { shapeBriefOf, shapeLineBrief } from './rubricstep.js';
35
35
 
36
- const isRec = (/** @type {unknown} */ v) => v !== null && typeof v === 'object' && !Array.isArray(v);
37
36
  import { sheetAnswerProps, sheetBrief } from './sheetclaims.js';
38
37
 
39
38
  import {
40
39
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
41
40
  } from './provider.js';
41
+ import { isRec } from './isrec.js';
42
42
 
43
43
  // F27: a provider's `chat/completions` can send HTTP 200 + headers + one byte
44
44
  // then nothing — a "zombie stream" that `timeoutMs`'s idle bound never
@@ -392,7 +392,7 @@ export function makeLiveModelStep({
392
392
  const diaryStep = stepMeta.step ?? null;
393
393
  const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
394
394
  const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : null, stepMeta.class === 'green' && stepMeta.withText === true, isRec(stepMeta.itemShape));
395
- const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
395
+ const thinkingMode = isThinkingMode(stepMeta.thinkingMode) ? /** @type {'on'|'off'} */ (stepMeta.thinkingMode) : null;
396
396
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
397
397
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
398
398
  + 'reads you were handed or the tools you were granted — never invent a figure.';
@@ -0,0 +1,8 @@
1
+ // M20 am8a item 1: the words the page asks instead of spelling them itself, built from the modules that own the facts (the panel injects the constant like the schedule choices: src/schedule-choices.js).
2
+ // The page is a classic script and cannot import; its client-made states (phase "revising" set by the page itself) have no server data to carry a flag, so it asks this list.
3
+ import { TAG } from './checkwords.js';
4
+ import { REASON_DECISIONS } from './ask.js';
5
+ import { REVISE_PHASES, NOT_GREEN_PHASES } from './panel/author.js';
6
+
7
+ /** @returns {{tags: Record<string,string>, reasonDecisions: string[], reviseRunning: string[], notGreen: string[]}} tags: origin -> tag word; reasonDecisions: the decisions that need a reason; reviseRunning: phases where a revise or redraft runs; notGreen: phases where the draft ended red or stopped */
8
+ export const pageWords = () => ({ tags: { ...TAG }, reasonDecisions: [...REASON_DECISIONS], reviseRunning: [...REVISE_PHASES], notGreen: [...NOT_GREEN_PHASES] });