fwdloop 0.38.0 → 0.40.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 (129) hide show
  1. package/README.md +6 -9
  2. package/bin/fwdloop +21 -19
  3. package/package.json +1 -1
  4. package/src/ask.js +70 -148
  5. package/src/audit-fold.js +6 -5
  6. package/src/auditchecks.js +6 -4
  7. package/src/authoring.js +32 -60
  8. package/src/blockasks.js +2 -1
  9. package/src/blockassemble.js +15 -3
  10. package/src/blockdraft.js +2 -2
  11. package/src/blockpick.js +42 -16
  12. package/src/books.js +237 -12
  13. package/src/checkblock.js +24 -44
  14. package/src/checklistsign.js +25 -3
  15. package/src/checklook.js +3 -1
  16. package/src/checkpick.js +6 -77
  17. package/src/cited-source.js +4 -4
  18. package/src/citedcheck.js +6 -11
  19. package/src/citedwords.js +9 -8
  20. package/src/closers.js +9 -6
  21. package/src/declaration.js +14 -49
  22. package/src/diary.js +23 -1
  23. package/src/draft-steps.js +11 -1
  24. package/src/drafter.js +18 -12
  25. package/src/draftfiles.js +127 -0
  26. package/src/draftspend.js +165 -17
  27. package/src/flow.js +42 -87
  28. package/src/flowmodel.js +1 -1
  29. package/src/index.js +3 -2
  30. package/src/inside.js +106 -0
  31. package/src/jsonl-append.js +33 -1
  32. package/src/learn.js +1 -1
  33. package/src/learnstore.js +20 -22
  34. package/src/line-checks.js +1 -1
  35. package/src/liveness.js +3 -0
  36. package/src/mcp-use.js +8 -9
  37. package/src/memo.js +13 -16
  38. package/src/model-step.js +2 -2
  39. package/src/page-words.js +8 -0
  40. package/src/pageask.js +8 -3
  41. package/src/pagebits.js +8 -1
  42. package/src/pagedropwords.js +1 -1
  43. package/src/pagerules.js +6 -3
  44. package/src/panel/author.js +99 -75
  45. package/src/panel/authorcard.js +21 -8
  46. package/src/panel/authorflows.js +3 -3
  47. package/src/panel/authorresume.js +3 -3
  48. package/src/panel/authorstart.js +15 -16
  49. package/src/panel/authortrigger.js +43 -70
  50. package/src/panel/data.js +186 -188
  51. package/src/panel/index.html +139 -115
  52. package/src/panel/jobgrid.js +3 -7
  53. package/src/panel/result.js +7 -10
  54. package/src/panel/resume.js +4 -3
  55. package/src/panel/scheduler.js +9 -9
  56. package/src/panel/server.js +8 -4
  57. package/src/panel/spawn.js +22 -11
  58. package/src/panel/tickets.js +2 -2
  59. package/src/pickrecord.js +51 -31
  60. package/src/placerule.js +3 -4
  61. package/src/plain-checks.js +1 -1
  62. package/src/planrebuild.js +19 -19
  63. package/src/primitives.js +1 -1
  64. package/src/provider.js +1 -1
  65. package/src/reasons.js +25 -0
  66. package/src/runfile.js +26 -2
  67. package/src/runner.js +57 -105
  68. package/src/runvalues.js +47 -24
  69. package/src/schedule-choices.js +41 -0
  70. package/src/schedule-shape.js +39 -0
  71. package/src/schedule.js +9 -8
  72. package/src/setup.js +20 -36
  73. package/src/shaperows.js +2 -2
  74. package/src/sheetblock.js +2 -2
  75. package/src/sheetbuild.js +5 -5
  76. package/src/sheetrun.js +4 -5
  77. package/src/summary-words.js +2 -1
  78. package/src/thinking.js +5 -2
  79. package/src/ticketrows.js +7 -28
  80. package/src/trigger-clock.js +9 -23
  81. package/src/trigger-files.js +30 -22
  82. package/src/trigger-tickets.js +15 -14
  83. package/src/try-checks.js +2 -1
  84. package/src/types.js +2 -0
  85. package/types/ask.d.ts +25 -20
  86. package/types/authoring.d.ts +7 -42
  87. package/types/blockpick.d.ts +1 -1
  88. package/types/books.d.ts +380 -4
  89. package/types/checkblock.d.ts +1 -23
  90. package/types/checklist.d.ts +3 -3
  91. package/types/checklistsign.d.ts +7 -0
  92. package/types/checkpick.d.ts +0 -21
  93. package/types/citedwords.d.ts +7 -4
  94. package/types/closers.d.ts +1 -0
  95. package/types/declaration.d.ts +4 -14
  96. package/types/diary.d.ts +14 -1
  97. package/types/draft-steps.d.ts +7 -0
  98. package/types/drafter.d.ts +1 -1
  99. package/types/draftfiles.d.ts +89 -0
  100. package/types/draftspend.d.ts +74 -0
  101. package/types/flow.d.ts +32 -54
  102. package/types/index.d.ts +3 -3
  103. package/types/inside.d.ts +71 -0
  104. package/types/jsonl-append.d.ts +20 -0
  105. package/types/learnstore.d.ts +0 -2
  106. package/types/liveness.d.ts +1 -0
  107. package/types/page-words.d.ts +6 -0
  108. package/types/pageask.d.ts +2 -0
  109. package/types/pagebits.d.ts +3 -0
  110. package/types/pagerules.d.ts +1 -0
  111. package/types/panel/author.d.ts +7 -3
  112. package/types/panel/authorcard.d.ts +0 -6
  113. package/types/panel/authorflows.d.ts +4 -4
  114. package/types/panel/authortrigger.d.ts +16 -2
  115. package/types/panel/data.d.ts +50 -16
  116. package/types/panel/spawn.d.ts +18 -2
  117. package/types/pickrecord.d.ts +29 -0
  118. package/types/reasons.d.ts +23 -0
  119. package/types/runfile.d.ts +14 -0
  120. package/types/runner.d.ts +6 -38
  121. package/types/runvalues.d.ts +17 -2
  122. package/types/schedule-choices.d.ts +9 -0
  123. package/types/schedule-shape.d.ts +15 -0
  124. package/types/sheetbuild.d.ts +1 -1
  125. package/types/thinking.d.ts +1 -0
  126. package/types/ticketrows.d.ts +0 -9
  127. package/types/trigger-clock.d.ts +3 -2
  128. package/types/trigger-files.d.ts +15 -4
  129. package/types/types.d.ts +8 -0
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,106 @@
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
+ * `fast` (M20 am9f, change stamps only): skip the realpath checks, keep the symlink refusal. The caller only lists or stamps (never opens) what comes back.
20
+ * @param {string} baseDir
21
+ * @param {string} relPath
22
+ * @param {boolean} [fast]
23
+ * @returns {{ok:true, full:string, stat:{size:number, mtimeMs:number}}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
24
+ */
25
+ export function resolveInside(baseDir, relPath, fast = false) {
26
+ const full = path.join(baseDir, relPath);
27
+ let stat;
28
+ try {
29
+ stat = lstatSync(full);
30
+ } catch {
31
+ return { ok: false, missing: true };
32
+ }
33
+ if (stat.isSymbolicLink()) {
34
+ return { ok: false, missing: false, red: `"${relPath}" is a symlink, refused` };
35
+ }
36
+ if (fast) return { ok: true, full, stat };
37
+ let realBase;
38
+ let realFull;
39
+ try {
40
+ realBase = realpathSync(baseDir);
41
+ realFull = realpathSync(full);
42
+ } catch (err) {
43
+ return { ok: false, missing: false, red: `could not resolve "${relPath}" — ${err.message}` };
44
+ }
45
+ if (realFull !== realBase && !realFull.startsWith(realBase + path.sep)) {
46
+ return { ok: false, missing: false, red: `"${relPath}" resolves outside its directory — refused` };
47
+ }
48
+ return { ok: true, full, stat };
49
+ }
50
+
51
+ /**
52
+ * `resolveInside` plus the actual read — every raw-text book reader's one
53
+ * gateway. Same result shape as `resolveInside`, plus `{ok:true, text}`.
54
+ * @param {string} baseDir
55
+ * @param {string} relPath
56
+ * @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
57
+ */
58
+ export function readFileInside(baseDir, relPath) {
59
+ const resolved = resolveInside(baseDir, relPath);
60
+ if (!resolved.ok) return resolved;
61
+ try {
62
+ return { ok: true, text: readFileSync(resolved.full, 'utf8') };
63
+ } catch (err) {
64
+ return { ok: false, missing: false, red: `could not read "${relPath}" — ${err.message}` };
65
+ }
66
+ }
67
+
68
+
69
+ /**
70
+ * `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
71
+ * itself is a symlink or resolves outside `baseDir`, and skips (never
72
+ * follows) any individual entry that is itself a symlink — a directory
73
+ * listing must never hand a caller a name that, joined back onto `relDir`,
74
+ * would escape `baseDir`. `[]` when `relDir` doesn't exist.
75
+ * @param {string} baseDir
76
+ * @param {string} relDir
77
+ * @param {boolean} [fast] see `resolveInside`
78
+ * @returns {string[]}
79
+ */
80
+ export function readdirInside(baseDir, relDir, fast = false) {
81
+ const resolved = resolveInside(baseDir, relDir, fast);
82
+ if (!resolved.ok) return [];
83
+ let entries;
84
+ try {
85
+ entries = readdirSync(resolved.full, { withFileTypes: true });
86
+ } catch {
87
+ return [];
88
+ }
89
+ return entries.filter((e) => !e.isSymbolicLink()).map((e) => e.name);
90
+ }
91
+
92
+ /**
93
+ * M20 am9f: one string that changes when any file in `dirs` (folders of `baseDir`, `.` for itself) is written, replaced, renamed or removed: every entry's name, size and mtime.
94
+ * It only lists and stats through `resolveInside`'s `fast` form (a symlink reads `-`, nothing is opened); a missing folder adds nothing.
95
+ * @param {string} baseDir @param {string[]} dirs @returns {string}
96
+ */
97
+ export function stampsInside(baseDir, dirs) {
98
+ const out = [];
99
+ for (const dir of dirs) {
100
+ for (const n of readdirInside(baseDir, dir, true).sort()) {
101
+ const r = resolveInside(baseDir, path.join(dir, n), true);
102
+ out.push(`${dir}/${n}=${r.ok ? `${r.stat.size}:${r.stat.mtimeMs}` : '-'}`);
103
+ }
104
+ }
105
+ return out.join(',');
106
+ }
@@ -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,7 +4,7 @@
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
8
  import { isRec } from './isrec.js';
9
9
 
10
10
  /** the record's name in the run's own folder */
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/model-step.js CHANGED
@@ -29,7 +29,7 @@ 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
 
@@ -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] });
package/src/pageask.js CHANGED
@@ -3,7 +3,6 @@
3
3
  // borrowed-from: bareloop src/pagemap.js@v0.49.0 (d51a367) (stripAgreeLead, F240; adapted: literal regex, src/ bans new RegExp)
4
4
  // The words of the asks and of the answers to them. M17 am4 (A1): the asks themselves come from the list (src/blockasks.js); the page-look ask path that sat here is gone.
5
5
  import { redactSecrets } from './redact.js';
6
- import { HOW_TO_ANSWER } from './checkpick.js';
7
6
  import { columnTail } from './sheetfind.js';
8
7
 
9
8
  /** the most asks before drafting; more than this is a job to rewrite, not a questionnaire (am1) */
@@ -133,14 +132,20 @@ export function ruleOfAnswer(q, typed, choice) {
133
132
  // M17 am9 item 4: a column picked from a tie is the reading the tie carried for that column (the rule's words are rewritten in place by applyAnswers); anything not on the list never reaches here (the door refuses it)
134
133
  if (choice === 'column') return { rule: q.readings?.[typedText] ?? null, left: q.readings?.[typedText] === undefined };
135
134
  if (choice !== undefined) { // M10 am29: a typed choice decides, never the words; the box (`rule`) keeps its words whole
136
- const shapeC = q.ask === 'check' || q.ask === 'no-check';
135
+ const shapeC = isShapeAsk(q.ask);
137
136
  if (choice === 'agree' && typeof q.proposal === 'string' && (q.ask === 'reading' || q.ask === 'check')) return { rule: q.proposal, left: false, ...(q.ask === 'check' && q.check ? { check: q.check } : {}) };
138
137
  if (choice === 'drop') return { rule: null, left: true };
139
138
  return { rule: typedText, left: false, ...(shapeC ? { own: true } : {}) };
140
139
  }
141
140
  const text = stripAgreeLead(typedText); // F240: "yes, check it as ..." is the person's own words minus the leading "yes,"
142
- const shape = q.ask === 'check' || q.ask === 'no-check';
141
+ const shape = isShapeAsk(q.ask);
143
142
  if ((q.ask === 'reading' || q.ask === 'check') && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false, ...(q.ask === 'check' && q.check ? { check: q.check } : {}) };
144
143
  if ((q.ask === 'cant-check' || shape) && isDropIt(text)) return { rule: null, left: true };
145
144
  return { rule: text, left: false, ...(shape ? { own: true } : {}) };
146
145
  }
146
+
147
+ /** M20 am8: the one question "is this a shape guardrail's ask" (`check` proposes a check, `no-check` found none) @param {unknown} ask @returns {boolean} */
148
+ export const isShapeAsk = (ask) => ask === 'check' || ask === 'no-check';
149
+
150
+ /** how every answer is told, once (am2 item 2's words) */
151
+ export const HOW_TO_ANSWER = (/** @type {number} */ line, /** @type {boolean} */ agree) => `${agree ? 'Answer "agree" to use it, or type your own words' : 'Type your own words'} (your answer replaces that ~ rule on line ${line}), or answer "drop it" to leave it Not checked.`;
package/src/pagebits.js CHANGED
@@ -7,7 +7,14 @@ export const MAX_CURRENCIES = 3;
7
7
  export const MAX_UNITS = 10;
8
8
  export const MAX_UNIT_CHARS = 100;
9
9
  export const asList = (/** @type {unknown} */ v) => (Array.isArray(v) ? v.map(String) : (typeof v === 'string' ? [v] : []));
10
- export const boundOk = (/** @type {string} */ shape, /** @type {unknown} */ v) => (shape === 'number' || shape === 'money' ? typeof v === 'number' && Number.isFinite(v) : typeof v === 'string' && v !== '');
10
+ /** M20 am8: the one question "is this fact shape phrase-like" (the words of a phrase or a place are looked for on the page) @param {unknown} shape @returns {boolean} */
11
+ export const isPhraseShape = (shape) => shape === 'phrase' || shape === 'place';
12
+ /** M20 am8: the one question "is this a legal result count": `{min, max}` only, at least one of them, whole numbers 1 or more, min no more than max (each caller keeps its own words for a refusal) @param {any} c @returns {boolean} */
13
+ export const isLegalCount = (c) => isRec(c) && Object.keys(c).every((k) => k === 'min' || k === 'max') && (c.min !== undefined || c.max !== undefined)
14
+ && ['min', 'max'].every((k) => c[k] === undefined || (Number.isInteger(c[k]) && c[k] >= 1)) && (c.min === undefined || c.max === undefined || c.min <= c.max);
15
+ /** M20 am8: the one question "is this fact shape an amount" (money or number: read as a plain number, carries the decimal mark, its bounds are numbers) @param {unknown} shape @returns {boolean} */
16
+ export const isAmountShape = (shape) => shape === 'money' || shape === 'number';
17
+ export const boundOk = (/** @type {string} */ shape, /** @type {unknown} */ v) => (isAmountShape(shape) ? typeof v === 'number' && Number.isFinite(v) : typeof v === 'string' && v !== '');
11
18
 
12
19
  // borrowed-from: bareloop src/factwords.js@18ab77c (squash, loose, countExact, countPhrase - rewritten without a built pattern, same count, see test/m10-pagebits.test.js)
13
20
  const WS = /[\s   ]+/g;
@@ -8,7 +8,7 @@
8
8
 
9
9
  // borrowed-from: bareloop src/pagedropwords.js@v0.56.0 (3383cce) (the four reasons the block's drops carry, and the sign-twice sentence by `d.other`; FACT_LANGS lives with the facts in src/citedcheck.js)
10
10
  import { FACT_LANGS } from './citedcheck.js';
11
- import { REASON } from './checkblock.js';
11
+ import { REASON } from './reasons.js';
12
12
 
13
13
  /** the two ways a sign listed twice can be used once (v0.56.0 spells the sentence from `d.other`; no other -> "currency", the sentence fwd has always written) */
14
14
  const SIGN_TWICE_AS = ['currency', 'unit'];
package/src/pagerules.js CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  import { lineRules } from './pagebits.js';
9
9
  import { MAX_CURRENCIES, MAX_UNITS, MAX_UNIT_CHARS, FACT_OPS, boundOk } from './pagebits.js';
10
- import { countExact, countPhrase, squash, normLabel } from './pagebits.js';
10
+ import { countExact, countPhrase, squash, normLabel, isAmountShape } from './pagebits.js';
11
11
 
12
12
  /**
13
13
  * @typedef {{op: string, value?: string|number, lo?: string|number, hi?: string|number}} Reading what a `~` rule means as a limit (PRD v1.107 Part 5b): the same shape as a signed fact rule
@@ -40,13 +40,16 @@ export function tieOf(from, jobLines) {
40
40
  return out;
41
41
  }
42
42
 
43
+ /** M20 am8: the one question "can CODE read a limit from the person's words for this fact shape" (money or time: readLimit reads those two) @param {unknown} shape @returns {shape is 'money'|'time'} */
44
+ export const canReadLimit = (shape) => shape === 'money' || shape === 'time';
45
+
43
46
  /**
44
47
  * Is this a legal `reading` for a fact of this shape? Only a time or money fact carries one, with the op set and the bound types of a signed
45
48
  * fact rule (src/facts.js): no other key, no missing bound. A malformed one makes the whole map answer malformed (no repair).
46
49
  * @param {unknown} shape @param {unknown} r @returns {boolean}
47
50
  */
48
51
  export function validReading(shape, r) {
49
- if (shape !== 'time' && shape !== 'money') return false;
52
+ if (!canReadLimit(shape)) return false;
50
53
  if (!isRec(r) || !FACT_OPS.includes(r.op)) return false;
51
54
  const keys = Object.keys(r).sort().join();
52
55
  return r.op === 'between' ? keys === 'hi,lo,op' && boundOk(shape, r.lo) && boundOk(shape, r.hi) : keys === 'op,value' && boundOk(shape, r.value);
@@ -220,7 +223,7 @@ export function applyPageRules(text, mapping, jobLines) {
220
223
  }
221
224
  pending.push({ f, kept, cur: [], uni: [] });
222
225
  } else if (VALUE_SHAPES.includes(String(f.shape))) {
223
- const amount = f.shape === 'money' || f.shape === 'number';
226
+ const amount = isAmountShape(f.shape);
224
227
  /** labels the page holds (and, for an amount, that have a number right after them) */
225
228
  const labels = [];
226
229
  /** the AI's labels as U1 leaves them, a word the page does not hold included: the first of these is R1's reference */