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/draftspend.js CHANGED
@@ -19,7 +19,8 @@
19
19
  import { renameSync, writeFileSync } from 'node:fs';
20
20
  import { basename, dirname, join, resolve } from 'node:path';
21
21
 
22
- import { readdirInside, readFileInside } from './flow.js';
22
+ import { readdirInside, readFileInside } from './inside.js';
23
+ import { draftStepList, DRAFT_LOG_RE } from './draft-steps.js';
23
24
  import { readSpendRows, rowCeilingUsd, spendRowCost, unmeteredCalls } from './provider.js';
24
25
  import { parseSignedText } from './signed-text.js';
25
26
 
@@ -78,6 +79,17 @@ export const EARLIER_MISSING_SAY = "An earlier draft of this job is missing, so
78
79
  export const STARTED_OVER_FILE = 'started-over-from.json';
79
80
  const SESSION_ID_RE = /^d-[0-9a-z]{10}-[0-9a-f]{4}$/;
80
81
 
82
+ /**
83
+ * M20 am3 item 12: the ONE reader of a session folder's `started-over-from.json`: the `startedOverFrom` value it holds, or null when
84
+ * there is no file, it is unreadable, or it holds none. (A value that is not a session id is the caller's to judge.)
85
+ * @param {string} sessionDir @returns {unknown}
86
+ */
87
+ export function readStartedOverFrom(sessionDir) {
88
+ const so = readFileInside(sessionDir, STARTED_OVER_FILE);
89
+ if (!so.ok) return null;
90
+ try { return JSON.parse(so.text)?.startedOverFrom ?? null; } catch { return null; }
91
+ }
92
+
81
93
  /**
82
94
  * M4d amendment 16 item 1: what ALL of a job's drafting spent — the one writer of that total. A panel draft's session folder holds one plan
83
95
  * folder per draft (`draft/`, `draft-<n>/` for each revise and the redraft after answers); each is read by `readDirSpendRows` and priced by
@@ -108,22 +120,18 @@ export function draftingSpent(sessionDir, { ceilingUsd = 0, exclude } = {}, seen
108
120
  }
109
121
  // M4d am19 item 3: a Start over opens a new session folder that names the one it started over from (`started-over-from.json`, written once by the panel):
110
122
  // what the earlier session spent is still this job's drafting, so the chain is followed (a name that points back at a folder already counted is not).
111
- const so = readFileInside(sessionDir, STARTED_OVER_FILE);
112
- if (so.ok) {
113
- let from = null;
114
- try { from = JSON.parse(so.text)?.startedOverFrom; } catch { /* unreadable: no chain */ }
115
- if (typeof from === 'string' && SESSION_ID_RE.test(from) && !seen.has(resolve(dirname(sessionDir), from))) {
116
- const prev = join(dirname(sessionDir), from);
117
- // M4d am21 item 2: a link naming a folder that is gone is NOT $0: what it spent cannot be counted (`missingEarlier`, never a clean figure)
118
- if (!readFileInside(prev, 'card.json').ok) missingEarlier = true;
119
- else {
120
- const before = draftingSpent(prev, { ceilingUsd }, seen);
121
- usd += before.usd;
122
- notPriced += before.notPriced;
123
- missingEarlier = before.missingEarlier;
124
- }
125
- } else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
126
- }
123
+ const from = readStartedOverFrom(sessionDir);
124
+ if (typeof from === 'string' && SESSION_ID_RE.test(from) && !seen.has(resolve(dirname(sessionDir), from))) {
125
+ const prev = join(dirname(sessionDir), from);
126
+ // M4d am21 item 2: a link naming a folder that is gone is NOT $0: what it spent cannot be counted (`missingEarlier`, never a clean figure)
127
+ if (!readFileInside(prev, 'card.json').ok) missingEarlier = true;
128
+ else {
129
+ const before = draftingSpent(prev, { ceilingUsd }, seen);
130
+ usd += before.usd;
131
+ notPriced += before.notPriced;
132
+ missingEarlier = before.missingEarlier;
133
+ }
134
+ } else if (typeof from === 'string' && !SESSION_ID_RE.test(from)) missingEarlier = true;
127
135
  return { usd, notPriced, complete: notPriced === 0 && !missingEarlier, missingEarlier };
128
136
  }
129
137
 
@@ -174,3 +182,143 @@ export function draftHoldUsd(proseText, outDir, ceilingUsd) {
174
182
  export function capTooSmallText(kind, capUsd, minUsd, modelId) {
175
183
  return `Cap ${usdText(capUsd)} is below one ${kind} round's worst case for ${modelId}, $${minUsd.toFixed(4)}. Raise Cap $ or pick another model.`;
176
184
  }
185
+
186
+ // M20 am1 items 5-6 + am2: the drafting step lines. The `fwdloop draft` child writes them into the draft's existing child.log (as `fwdloop: refusal-record`, M19 am14b):
187
+ // `fwdloop: step-start {no, id, label, at}` and `fwdloop: step-end {no, status, label, at}`.
188
+ // `id` and `label` are `draftStepList`'s own (src/draft-steps.js) for the step; the `thinking` line and a `Fix:` note get no line (they have no time).
189
+ // Throws away: the model's replies and every per-round figure but what the label carries. Third outcomes: a torn or unparseable line is skipped; no lines = no times.
190
+ export const STEP_LINE_RE = /^fwdloop: (step-start|step-end) (\{.*\})$/;
191
+ export const STEP_LINE_PREFIXES = ['fwdloop: step-start ', 'fwdloop: step-end '];
192
+
193
+ /**
194
+ * The ONE writer of the step lines. `emit(kind, record)` prints one line (the CLI passes stderr). Each call is given the result so far
195
+ * (`log`, as log.json will hold it) and writes a start for every step not yet started, and an end for every step but the last (the running one);
196
+ * `final` ends them all. A step is keyed by its `id`: written once.
197
+ * @param {(kind: 'step-start'|'step-end', rec: Record<string, any>) => void} emit
198
+ */
199
+ export function makeStepWriter(emit) {
200
+ /** @type {string[]} */
201
+ const started = [];
202
+ const ended = new Set();
203
+ return (/** @type {any} */ log, /** @type {any} */ declaration, final) => {
204
+ const list = draftStepList({ log, declaration, questionOpen: !final });
205
+ const items = (list ?? []).filter((st) => st.note !== true && st.id !== 'thinking');
206
+ items.forEach((st, i) => {
207
+ const at = new Date().toISOString();
208
+ if (!started.includes(st.id)) { started.push(st.id); emit('step-start', { no: started.length - 1, id: st.id, label: st.label, at }); }
209
+ if ((final || i < items.length - 1) && !ended.has(st.id)) {
210
+ ended.add(st.id);
211
+ emit('step-end', { no: started.indexOf(st.id), status: st.status === 'failed' ? 'failed' : 'done', label: st.label, at });
212
+ }
213
+ });
214
+ };
215
+ }
216
+
217
+ /**
218
+ * Fold the step lines of `<dir>/child.log` into one record per step, oldest first. A line that cannot be parsed is skipped.
219
+ * @param {string} dir the draft folder @param {string} [file] the child's log: `child.log` (the first draft), `revise-<n>.log` or `redraft-<n>.log`
220
+ * @returns {{no: number, id: string, label: string, status: 'running'|'done'|'failed', startedAt: string, endedAt: string|null, wallMs: number|null}[]}
221
+ */
222
+ export function readDraftSteps(dir, file = 'child.log') {
223
+ const r = readFileInside(dir, file);
224
+ if (!r.ok) return [];
225
+ /** @type {Map<number, any>} */
226
+ const byNo = new Map();
227
+ for (const line of r.text.split('\n')) {
228
+ const m = STEP_LINE_RE.exec(line);
229
+ if (!m) continue;
230
+ let ev;
231
+ try { ev = JSON.parse(m[2]); } catch { continue; }
232
+ if (!ev || typeof ev !== 'object' || !Number.isInteger(ev.no)) continue;
233
+ if (m[1] === 'step-start') {
234
+ byNo.set(ev.no, { no: ev.no, id: String(ev.id), label: String(ev.label), status: 'running', startedAt: ev.at, endedAt: null, wallMs: null });
235
+ } else if (byNo.has(ev.no)) {
236
+ const x = byNo.get(ev.no);
237
+ x.status = ev.status === 'failed' ? 'failed' : 'done';
238
+ x.endedAt = ev.at;
239
+ if (typeof ev.label === 'string') x.label = ev.label;
240
+ }
241
+ }
242
+ const steps = [...byNo.values()].sort((a, b) => a.no - b.no);
243
+ for (const x of steps) {
244
+ const a = Date.parse(x.startedAt);
245
+ const b = x.endedAt === null ? NaN : Date.parse(x.endedAt);
246
+ x.wallMs = Number.isFinite(a) && Number.isFinite(b) ? Math.max(0, b - a) : null;
247
+ }
248
+ return steps;
249
+ }
250
+
251
+ // borrowed-from: bareloop src/draftspend.js@v0.63.0 (7bc2719b): TIME_STEP_MS, mmss, stepped, draftWallMs, withDraftTimes, draftedLine
252
+ /** a running time moves in 30 s steps, never a ticking clock (the page polls often; the words change every 30 s) */
253
+ export const TIME_STEP_MS = 30_000;
254
+
255
+ /** M:SS, the ONE spelling of a drafting time ("took 0:42", "Drafting so far: 2:00"). @param {number} ms @returns {string} */
256
+ export function mmss(ms) {
257
+ const s = Math.max(0, Math.floor(ms / 1000));
258
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
259
+ }
260
+
261
+ /** a running time floored to its 30 s step @param {number} ms @returns {number} */
262
+ export const stepped = (ms) => Math.floor(Math.max(0, ms) / TIME_STEP_MS) * TIME_STEP_MS;
263
+
264
+ /**
265
+ * The drafting's whole time: the first step's start to the last step's end; `null` when no step has both times.
266
+ * @param {{startedAt: string, endedAt: string|null}[]} steps `readDraftSteps`' records
267
+ * @returns {number|null}
268
+ */
269
+ export function draftWallMs(steps) {
270
+ const starts = steps.map((x) => Date.parse(x.startedAt)).filter(Number.isFinite);
271
+ const ends = steps.map((x) => (x.endedAt === null ? NaN : Date.parse(x.endedAt))).filter(Number.isFinite);
272
+ return starts.length && ends.length ? Math.max(0, Math.max(...ends) - Math.min(...starts)) : null;
273
+ }
274
+
275
+ /**
276
+ * The ONE owner of the times on the chat's drafting list. While the draft runs the list is the started steps (`no` order, latest label), each `time` "M:SS so far"
277
+ * (a finished one "took M:SS") and `draftSoFar` is "Drafting so far: M:SS". After it ends `list` is `draftStepList`'s list unchanged, each line taking the times of the
278
+ * step line with the same `id` (the first unused, in order); a line no step line matches (thinking, a Fix note) has no time. No lines = no times, `draftSoFar` null.
279
+ * A revise or answer redraft is read from its own log (`file`); its one `plan` line (`reviseStepList`) takes the draft's whole time (`wholeId`).
280
+ * @param {{dir: string, running: boolean, list: any[]|null, nowMs?: number, file?: string, wholeId?: string}} p `dir` = the draft folder, `file` = the child's log in it, `list` = draftStepList's (or reviseStepList's) list or null
281
+ * @returns {{list: any[]|null, draftSoFar: string|null}}
282
+ */
283
+ export function withDraftTimes({ dir, running, list, nowMs = Date.now(), file = 'child.log', wholeId }) {
284
+ const logged = readDraftSteps(dir, file);
285
+ const timeOf = (/** @type {any} */ x) => {
286
+ const a = Date.parse(x.startedAt);
287
+ if (!Number.isFinite(a)) return null;
288
+ if (x.status === 'running') return `${mmss(stepped(nowMs - a))} so far`;
289
+ return x.wallMs !== null ? `took ${mmss(x.wallMs)}` : null;
290
+ };
291
+ const starts = logged.map((x) => Date.parse(x.startedAt)).filter(Number.isFinite);
292
+ const draftSoFar = running && logged.some((x) => x.status === 'running') && starts.length ? `Drafting so far: ${mmss(stepped(nowMs - Math.min(...starts)))}` : null;
293
+ if (running) {
294
+ return { list: logged.length ? logged.map((x) => ({ id: x.id, label: x.label, status: x.status === 'failed' ? 'failed' : (x.status === 'running' ? 'running' : 'done'), details: [], time: timeOf(x) })) : list, draftSoFar };
295
+ }
296
+ if (list === null) return { list, draftSoFar: null };
297
+ const used = new Set();
298
+ const whole = wholeId !== undefined ? draftWallMs(logged) : null;
299
+ return {
300
+ list: list.map((st) => {
301
+ if (st.id === wholeId) return { ...st, time: whole === null ? null : `took ${mmss(whole)}` };
302
+ const x = logged.find((l) => l.id === st.id && !used.has(l.no));
303
+ if (x) used.add(x.no);
304
+ return { ...st, time: x ? timeOf(x) : null };
305
+ }),
306
+ draftSoFar: null,
307
+ };
308
+ }
309
+
310
+ /** the logs of every draft of a session folder: the first draft's `child.log`, then each revise's and answer redraft's own */
311
+ const draftLogFiles = (/** @type {string} */ dir) => ['child.log', ...readdirInside(dir, '.').filter((n) => DRAFT_LOG_RE.test(n))];
312
+
313
+ /**
314
+ * The plan card's one line: "Drafted in M:SS · $X". The time is the session's first step start to its last step end across ALL its drafts (the first, each revise,
315
+ * each answer redraft); the money is the session's drafting spend (`draftingSpent`, handed in as `spentUsd`; "at least" when `complete` is false). `null` when no
316
+ * step line has a time or the spend is not a number (a Reuse, an old draft, a session that never knew its cost): nothing is made up.
317
+ * @param {{dir: string, spentUsd: number|null, complete: boolean}} p `dir` = the session's draft folder
318
+ * @returns {string|null}
319
+ */
320
+ export function draftedLine({ dir, spentUsd, complete }) {
321
+ const ms = draftWallMs(draftLogFiles(dir).flatMap((f) => readDraftSteps(dir, f)));
322
+ if (ms === null || typeof spentUsd !== 'number') return null;
323
+ return `Drafted in ${mmss(ms)} \u00B7 ${complete ? '' : 'at least '}${usdText(spentUsd)}`;
324
+ }
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
+ }
@@ -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
  }