fwdloop 0.20.0 → 0.22.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 (92) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +85 -34
  3. package/package.json +4 -3
  4. package/src/audit-fold.js +181 -0
  5. package/src/authoring.js +33 -7
  6. package/src/books.js +1 -1
  7. package/src/checked.js +18 -1
  8. package/src/cited-record.js +138 -0
  9. package/src/cited-source.js +49 -0
  10. package/src/citedcheck.js +306 -0
  11. package/src/citedwords.js +197 -0
  12. package/src/closers.js +105 -9
  13. package/src/ctx-tools.js +2 -14
  14. package/src/declaration.js +85 -5
  15. package/src/diary.js +49 -0
  16. package/src/docx.js +16 -2
  17. package/src/draft-steps.js +1 -1
  18. package/src/drafter.js +292 -25
  19. package/src/flow.js +33 -7
  20. package/src/flowmodel.js +63 -5
  21. package/src/input-facts.js +20 -3
  22. package/src/model-step.js +132 -9
  23. package/src/pageask.js +136 -0
  24. package/src/pagebits.js +107 -0
  25. package/src/pagedropwords.js +171 -0
  26. package/src/pagedry.js +120 -0
  27. package/src/pagefetch.js +164 -0
  28. package/src/pagelook.js +155 -0
  29. package/src/pagemap.js +55 -0
  30. package/src/pageplace.js +103 -0
  31. package/src/pagerules.js +318 -0
  32. package/src/panel/author.js +41 -20
  33. package/src/panel/authorcard.js +11 -1
  34. package/src/panel/authorflows.js +21 -15
  35. package/src/panel/authorstart.js +2 -4
  36. package/src/panel/authortrigger.js +14 -4
  37. package/src/panel/data.js +130 -10
  38. package/src/panel/index.html +499 -41
  39. package/src/panel/result.js +295 -0
  40. package/src/panel/server.js +27 -3
  41. package/src/primitives.js +43 -2
  42. package/src/provider.js +5 -2
  43. package/src/redact.js +17 -0
  44. package/src/runner.js +128 -21
  45. package/src/schedule.js +3 -3
  46. package/src/setup.js +16 -1
  47. package/src/sheetfind.js +50 -0
  48. package/src/sheetlook.js +157 -0
  49. package/src/signed-text.js +11 -1
  50. package/src/thinking.js +39 -0
  51. package/src/try-checks.js +68 -0
  52. package/src/types.js +4 -2
  53. package/types/audit-fold.d.ts +54 -0
  54. package/types/authoring.d.ts +20 -2
  55. package/types/books.d.ts +17 -0
  56. package/types/checked.d.ts +10 -0
  57. package/types/cited-record.d.ts +21 -0
  58. package/types/cited-source.d.ts +18 -0
  59. package/types/citedcheck.d.ts +95 -0
  60. package/types/citedwords.d.ts +97 -0
  61. package/types/closers.d.ts +55 -3
  62. package/types/declaration.d.ts +15 -1
  63. package/types/diary.d.ts +57 -0
  64. package/types/docx.d.ts +14 -0
  65. package/types/drafter.d.ts +244 -2
  66. package/types/flow.d.ts +21 -0
  67. package/types/flowmodel.d.ts +40 -3
  68. package/types/input-facts.d.ts +12 -2
  69. package/types/model-step.d.ts +38 -3
  70. package/types/pageask.d.ts +75 -0
  71. package/types/pagebits.d.ts +32 -0
  72. package/types/pagedropwords.d.ts +40 -0
  73. package/types/pagedry.d.ts +38 -0
  74. package/types/pagefetch.d.ts +86 -0
  75. package/types/pagelook.d.ts +75 -0
  76. package/types/pagemap.d.ts +31 -0
  77. package/types/pageplace.d.ts +22 -0
  78. package/types/pagerules.d.ts +86 -0
  79. package/types/panel/authorcard.d.ts +2 -0
  80. package/types/panel/authorflows.d.ts +2 -0
  81. package/types/panel/data.d.ts +26 -0
  82. package/types/panel/result.d.ts +156 -0
  83. package/types/provider.d.ts +3 -1
  84. package/types/redact.d.ts +1 -0
  85. package/types/runner.d.ts +156 -7
  86. package/types/schedule.d.ts +0 -11
  87. package/types/setup.d.ts +13 -0
  88. package/types/sheetfind.d.ts +46 -0
  89. package/types/sheetlook.d.ts +120 -0
  90. package/types/thinking.d.ts +31 -0
  91. package/types/try-checks.d.ts +55 -0
  92. package/types/types.d.ts +20 -3
@@ -15,6 +15,7 @@ import {
15
15
  import { isAbsolute, join } from 'node:path';
16
16
 
17
17
  import { checkFlowName } from '../flow.js';
18
+ import { isWebUrl } from '../pagefetch.js';
18
19
  import { checkSendDestination } from '../runner.js';
19
20
  import { parseSignedText } from '../signed-text.js';
20
21
  import { capTooSmallText } from '../draftspend.js';
@@ -177,6 +178,11 @@ export function cardFields(body) {
177
178
  };
178
179
  }
179
180
 
181
+ /** M10 am3: is this web address whole (a host after the scheme, no spaces)? The ONE reader of a typed page address. @param {string} v */
182
+ export function pageAddressOk(v) {
183
+ return /^https?:\/\/[^\s/?#]+\S*$/i.test(v);
184
+ }
185
+
180
186
  /** The Run-a-signed-flow door's rows (a role is fixed by the signed flow): what the page sent, as `{role, path}`. @param {any} v */
181
187
  export function runInputRows(v) {
182
188
  return (Array.isArray(v) ? v : []).map((r) => ({ role: str(r?.role).trim(), path: str(r?.path).trim() }));
@@ -193,7 +199,7 @@ export function cardToProse(card) {
193
199
  const out = [...jobFileLines(steps, card.askWait), '', ARBITER_HEADING];
194
200
  out.push(`guardrail: cap $${capText(Number(card.capUsd))} per run`);
195
201
  if (card.destination !== '') out.push(`guardrail: send at line ${steps.length} to file:${card.destination}`);
196
- for (const i of parseInputLines(card.inputs)) out.push(`guardrail: source ${i.role} = file:${i.path}`);
202
+ for (const i of parseInputLines(card.inputs)) out.push(`guardrail: source ${i.role} = ${isWebUrl(i.path) ? 'page' : 'file'}:${i.path}`); // M10 am3: a web address is a page
197
203
  return `${out.join('\n')}\n`;
198
204
  }
199
205
 
@@ -279,6 +285,10 @@ export function checkInputRows(rows) {
279
285
  seen.add(row.role);
280
286
  if (row.path === '') { no(`The input "${row.role}" has a role but no path.`); return; }
281
287
  if (CONTROL_RE.test(row.path)) { no(`The path for "${row.role}" has a character that cannot be in a path.`); return; }
288
+ if (isWebUrl(row.path)) { // M10 am3: a web page's address is signed with the job; there is no file to look at
289
+ if (!pageAddressOk(row.path)) no(`The address for "${row.role}" must be a full http:// or https:// address with no spaces.`);
290
+ return;
291
+ }
282
292
  if (!isAbsolute(row.path)) { no(`The path for "${row.role}" must be a full path starting with "/".`); return; }
283
293
  const why = fileProblem(row.path);
284
294
  if (why) no(`The path for "${row.role}" ${why}`);
@@ -34,6 +34,7 @@ import { checkValues } from './authorvalues.js';
34
34
  import { getRunControls, getRunGlyph } from './data.js';
35
35
  import { SCHEDULE_BUSY_SAY } from '../summary-words.js';
36
36
  import { providerKeys } from './spawn.js';
37
+ import { pageAddressesOf, pageAddressRefusal } from '../pagefetch.js';
37
38
  import { readModelRecord, writeModelRecord } from '../flowmodel.js';
38
39
 
39
40
  /** M6 amendment 1: the sentence the page shows and the sign route refuses with, for a job with a run running or waiting at its ask. @param {string} runId */
@@ -89,22 +90,22 @@ export function createFlowsDoor(opts) {
89
90
  };
90
91
  }
91
92
 
92
- /** The source paths one run froze: role -> path, from that run's `inputs.json`. Blank = none. @param {string} runDir @param {string[]} roles */
93
- function sourcesOf(runDir, roles) {
93
+ /** The source paths one run froze: role -> path, from that run's `inputs.json`. Blank = none. @param {string} runDir @param {string[]} roles @param {Record<string, string>} [pages] M10 am3: page role -> signed address */
94
+ function sourcesOf(runDir, roles, pages = {}) {
94
95
  /** @type {Record<string, string>} */
95
- const out = Object.fromEntries(roles.map((r) => [r, '']));
96
+ const out = Object.fromEntries(roles.map((r) => [r, pages[r] ?? ''])); // M10 am3: a page input shows its signed address, whatever a run froze
96
97
  if (runDir === '') return out;
97
98
  const f = readFileInside(runDir, 'inputs.json');
98
99
  let rows = [];
99
100
  try { rows = f.ok ? JSON.parse(f.text) : []; } catch { rows = []; }
100
101
  for (const row of Array.isArray(rows) ? rows : []) {
101
- if (row && typeof row.id === 'string' && roles.includes(row.id) && typeof row.source === 'string') out[row.id] = row.source;
102
+ if (row && typeof row.id === 'string' && roles.includes(row.id) && !Object.hasOwn(pages, row.id) && typeof row.source === 'string') out[row.id] = row.source;
102
103
  }
103
104
  return out;
104
105
  }
105
106
 
106
- /** The source paths the newest run of this flow used: role -> path, from that run's `inputs.json`. Blank = none. @param {string} flowDir @param {string[]} roles */
107
- function lastSources(flowDir, roles) {
107
+ /** The source paths the newest run of this flow used: role -> path, from that run's `inputs.json`. Blank = none. @param {string} flowDir @param {string[]} roles @param {Record<string, string>} [pages] */
108
+ function lastSources(flowDir, roles, pages = {}) {
108
109
  let newest = null;
109
110
  for (const id of listRunIds(flowDir)) {
110
111
  const r = resolveRunDir(flowDir, id);
@@ -113,8 +114,8 @@ export function createFlowsDoor(opts) {
113
114
  try { t = lstatSync(join(r.runDir, 'inputs.json')).mtimeMs; } catch { continue; }
114
115
  if (newest === null || t > newest.t || (t === newest.t && id > newest.id)) newest = { t, id, runDir: r.runDir };
115
116
  }
116
- if (newest === null) return { runId: null, sources: sourcesOf('', roles) };
117
- return { runId: newest.id, sources: sourcesOf(newest.runDir, roles) };
117
+ if (newest === null) return { runId: null, sources: sourcesOf('', roles, pages) };
118
+ return { runId: newest.id, sources: sourcesOf(newest.runDir, roles, pages) };
118
119
  }
119
120
 
120
121
  /** The values one run ran with: the flow's own, with the run's newest signed version laid over (`applyRunValues`). Unreadable = the flow's own. @param {any} read @param {string} name @param {string} runDir */
@@ -140,7 +141,7 @@ export function createFlowsDoor(opts) {
140
141
  if (end === null) continue; // not ended (running, parked, died): neither green nor not green
141
142
  if (end.outcome === 'complete') {
142
143
  green += 1;
143
- passed.push({ runId: id, ...runValuesOf(read, name, r.runDir), sources: sourcesOf(r.runDir, roles) });
144
+ passed.push({ runId: id, ...runValuesOf(read, name, r.runDir), sources: sourcesOf(r.runDir, roles, pageAddressesOf(read.arbiter)) });
144
145
  } else notGreen += 1;
145
146
  if (end.spendComplete === true && Number.isFinite(end.spentUsd) && end.spentUsd >= 0) { spendSum += end.spentUsd; spendN += 1; }
146
147
  if (Number.isFinite(end.wallMs) && end.wallMs > 0) { wallSum += end.wallMs; wallN += 1; }
@@ -220,11 +221,16 @@ export function createFlowsDoor(opts) {
220
221
  /** @type {{field: string, say: string}[]} */
221
222
  const refusals = checked.ok ? [...modelReds] : [...checked.refusals, ...modelReds];
222
223
  if (!checked.ok && checked.status === 409) return reply(409, { refused: 'monthly', say: checked.say });
223
- const rows = runInputRows(body?.inputs);
224
+ // M10 am3: a page input's address is the job's, signed; the page shows it read-only, a blank row is the signed one, and any other address is refused naming the input
225
+ const pages = pageAddressesOf(read.arbiter);
226
+ const rows = runInputRows(body?.inputs).map((r) => (Object.hasOwn(pages, r.role) && r.path === '' ? { ...r, path: pages[r.role] } : r));
224
227
  refusals.push(...checkInputRows(rows));
228
+ rows.forEach((r, n) => {
229
+ if (Object.hasOwn(pages, r.role) && r.path !== pages[r.role]) refusals.push({ field: `inputs.${n}`, say: pageAddressRefusal(r.role, pages[r.role]) });
230
+ });
225
231
  const declared = (read.arbiter.sources ?? []).map((s) => s.role);
226
232
  for (const role of declared) {
227
- if (!rows.some((r) => r.role === role)) refusals.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
233
+ if (!Object.hasOwn(pages, role) && !rows.some((r) => r.role === role)) refusals.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
228
234
  }
229
235
  rows.forEach((r, n) => {
230
236
  if (r.role !== '' && !declared.includes(r.role)) refusals.push({ field: `inputs.${n}`, say: `This flow has no input named "${r.role}" (it takes: ${declared.join(', ') || 'none'}).` });
@@ -240,7 +246,7 @@ export function createFlowsDoor(opts) {
240
246
  flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values,
241
247
  });
242
248
  return {
243
- ok: /** @type {true} */ (true), flow, read, declared, rows, runId, values, differs: checked.differs || runModel !== null, hash, newPick, flowDir: join(realRoot, flow), planFrom,
249
+ ok: /** @type {true} */ (true), flow, read, declared, rows: declared.map((role) => rows.find((r) => r.role === role) ?? { role, path: pages[role] }), runId, values, differs: checked.differs || runModel !== null, hash, newPick, flowDir: join(realRoot, flow), planFrom,
244
250
  };
245
251
  }
246
252
 
@@ -289,10 +295,10 @@ export function createFlowsDoor(opts) {
289
295
  function entryFor(realRoot, name, read, left) {
290
296
  const roles = (read.arbiter.sources ?? []).map((s) => s.role);
291
297
  const flowDir = join(realRoot, name);
292
- const last = lastSources(flowDir, roles);
298
+ const last = lastSources(flowDir, roles, pageAddressesOf(read.arbiter));
293
299
  const { passed, stats } = runsOf(flowDir, name, read, roles);
294
300
  return {
295
- flow: name, capUsd: read.arbiter.capUsd, roles, nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
301
+ flow: name, capUsd: read.arbiter.capUsd, roles, pages: pageAddressesOf(read.arbiter), nextRunId: nextRunId(flowDir), lastRunId: last.runId, lastSources: last.sources, leftThisMonth: left,
296
302
  runs: passed, stats,
297
303
  ...formFacts(read, home, flowDir),
298
304
  // M6 am5/am6: the job as the card Reuse workflow opens (`ok:true, card`), or why the card cannot hold it (`ok:false, say`). Nothing blocks it: a reuse never changes the job it is opened from.
@@ -411,7 +417,7 @@ export function createFlowsDoor(opts) {
411
417
  return {
412
418
  status: 200,
413
419
  body: {
414
- ok: true, flow: entryFor(realRoot, flow, read, leftThisMonth()), pick: { runId, ...runValuesOf(read, flow, rr.runDir), sources: sourcesOf(rr.runDir, roles) },
420
+ ok: true, flow: entryFor(realRoot, flow, read, leftThisMonth()), pick: { runId, ...runValuesOf(read, flow, rr.runDir), sources: sourcesOf(rr.runDir, roles, pageAddressesOf(read.arbiter)) },
415
421
  },
416
422
  };
417
423
  },
@@ -31,7 +31,7 @@ import { loadCatalogue } from '../catalogue.js';
31
31
  import { scrub } from '../authoring.js';
32
32
  import { readPidRows } from '../books.js';
33
33
  import {
34
- PANEL_STARTS_DIR, checkRunId, claimRunId, nextRunId, readFileInside, readdirInside, resolveRunDir, runOwnsPlan, copyRunPlan, RUN_PLAN_MARKER,
34
+ PANEL_STARTS_DIR, checkRunId, claimRunId, freeRunId, readFileInside, readdirInside, resolveRunDir, runOwnsPlan, copyRunPlan, RUN_PLAN_MARKER,
35
35
  } from '../flow.js';
36
36
  import { booksFresh, runLiveness } from '../liveness.js';
37
37
  import { dropUnstartedValues, writeRunValues } from '../runvalues.js';
@@ -146,10 +146,8 @@ export function createStarter(opts) {
146
146
  if (!planRun) {
147
147
  const flowDir = join(realpathSync(root), flow);
148
148
  if (runId === '') {
149
- const next = nextRunId(flowDir);
150
- const r = resolveRunDir(flowDir, next);
149
+ const r = freeRunId(flowDir); // the decider claimRunId uses: a stray file under a run name is skipped, not refused
151
150
  if (!r.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: `${r.red.replace(/^run: /, '')}.` } };
152
- if (existsSync(r.runDir)) return { status: 400, body: { ok: false, refused: 'run-id', say: `There is already a run "${next}" of this flow. Use a new run id.` } };
153
151
  } else {
154
152
  const run = checkRun(flow, runId);
155
153
  if (!run.ok) return { status: 400, body: { ok: false, refused: 'run-id', say: run.say } };
@@ -32,6 +32,7 @@ import { scheduleHead, scheduledWords } from '../summary-words.js';
32
32
  import { armTrigger, nextSlot, readRows, validateSchedule } from '../trigger-clock.js';
33
33
  import { checkTarget, createFileTrigger } from '../trigger-files.js';
34
34
  import { readModelRecord } from '../flowmodel.js';
35
+ import { pageAddressesOf, pageAddressRefusal } from '../pagefetch.js';
35
36
  import {
36
37
  carryQueue, dropQueue, finishCarry, isArmed, ledgerOf, readSchedule, recordCancelled, removeSchedule, sameTarget, sigOf, writeSchedule,
37
38
  } from '../schedule.js';
@@ -168,6 +169,9 @@ export function createTriggerDoor(opts) {
168
169
  if (trigger !== null && !hasGreenRunForJob(flowDir)) return reply(409, { refused: 'no-green-run', say: NO_GREEN_SAY });
169
170
  // M9 am20 item 3: neither Cancel nor a new schedule is refused because a run is starting, working or waiting: a run carries on from its own copy and
170
171
  // keeps its own signed values; the next fire uses the new schedule. (A schedule never touches the job, so there is nothing for a run to collide with.)
172
+ if (trigger !== null && 'role' in trigger && Object.hasOwn(pageAddressesOf(read.arbiter), trigger.role)) {
173
+ return reply(400, { refused: 'bad-trigger', say: `The input "${trigger.role}" is a web page, not a file, so no file arrival can start a run from it. Nothing was changed.` }); // M10 am3
174
+ }
171
175
  if (trigger !== null && 'role' in trigger) {
172
176
  try {
173
177
  checkTarget(trigger.kind === 'new-file' ? 'new' : 'updated', trigger.kind === 'new-file' ? trigger.folder : trigger.path);
@@ -203,13 +207,16 @@ export function createTriggerDoor(opts) {
203
207
  scheduledDestination = body.destination.trim();
204
208
  }
205
209
  if (Array.isArray(body?.inputs)) {
206
- const rows = runInputRows(body.inputs);
210
+ // M10 am3: a page input's address is the job's, signed: a blank row is the signed one, any other address is refused naming the input
211
+ const pages = pageAddressesOf(read.arbiter);
212
+ const rows = runInputRows(body.inputs).map((r) => (Object.hasOwn(pages, r.role) && r.path === '' ? { ...r, path: pages[r.role] } : r));
207
213
  const declared = roles;
208
214
  const bad = [...checkInputRows(rows)];
209
- for (const role of declared) if (!rows.some((r) => r.role === role)) bad.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
215
+ rows.forEach((r, n) => { if (Object.hasOwn(pages, r.role) && r.path !== pages[r.role]) bad.push({ field: `inputs.${n}`, say: pageAddressRefusal(r.role, pages[r.role]) }); });
216
+ for (const role of declared) if (!Object.hasOwn(pages, role) && !rows.some((r) => r.role === role)) bad.push({ field: 'inputs', say: `This flow needs an input named "${role}". Add it.` });
210
217
  for (const r of rows) if (!declared.includes(r.role)) bad.push({ field: 'inputs', say: `This flow has no input named "${r.role}" (it takes: ${declared.join(', ') || 'none'}).` });
211
218
  if (bad.length > 0) return reply(400, { refused: 'bad-inputs', say: `${bad[0].say} Nothing was changed.`, refusals: bad });
212
- scheduledInputs = declared.map((role) => ({ role, path: /** @type {{path: string}} */ (rows.find((r) => r.role === role)).path }));
219
+ scheduledInputs = declared.map((role) => ({ role, path: Object.hasOwn(pages, role) ? pages[role] : /** @type {{path: string}} */ (rows.find((r) => r.role === role)).path }));
213
220
  }
214
221
  }
215
222
  // M6 am9: the schedule uses the plan of the run it was set from. The workflow's own plan = nothing to bind; a different kept plan is verified now and
@@ -399,7 +406,9 @@ export function createTriggerDoor(opts) {
399
406
  let last = flowsDoor.lastSourcesOf(flow, roles).sources;
400
407
  if (schedule.inputs !== null) last = { ...last, ...Object.fromEntries(schedule.inputs.map((r) => [r.role, r.path])) };
401
408
  const sources = [];
409
+ const pages = pageAddressesOf(read.arbiter);
402
410
  for (const role of roles) {
411
+ if (Object.hasOwn(pages, role)) { sources.push({ role, path: pages[role] }); continue; } // M10 am3: a page input is its signed address, never an earlier run's or an arriving file
403
412
  const p = 'role' in trigger && trigger.role === role && cause.kind === 'file' ? cause.path : last[role];
404
413
  if (!p) return done({ outcome: 'refused', why: `There is no earlier run of this job to take the input "${role}" from. Run it by hand once with that input. Nothing started.` });
405
414
  try { sources.push({ role, path: realpathSync(p) }); } catch { return done({ outcome: 'refused', why: `The input "${role}" is not there (${p}). Nothing started.` }); }
@@ -485,7 +494,8 @@ export function createTriggerDoor(opts) {
485
494
  from: sc ? sc.from : null,
486
495
  model: sc && sc.model ? sc.model.model : (rec ? rec.model : null),
487
496
  destination: sc && sc.destination ? sc.destination : (read.ok ? flowValues(read.arbiter).destination : null),
488
- inputs: sources.map((p) => basename(String(p))),
497
+ // M10: a page input shows its FULL signed address (the page cuts it with an ellipsis, the whole on hover); a file shows its name
498
+ inputs: sources.map((p) => (Object.values(read.ok ? pageAddressesOf(read.arbiter) : {}).includes(String(p)) ? String(p) : basename(String(p)))),
489
499
  fires: base.sig === null ? [] : readOutcomes(flowDir).filter((o) => o.sig === base.sig),
490
500
  allFires: readOutcomes(flowDir), // M9 am9 item 4: the Audit's `tries` span every signing
491
501
  };
package/src/panel/data.js CHANGED
@@ -38,11 +38,17 @@ import {
38
38
  import { readSpendRows } from '../provider.js';
39
39
  import { applyRunValues, parseWaitMs, pickRunValues, VALUES_FILE_RE } from '../runvalues.js';
40
40
  import { readSetup } from '../setup.js';
41
- import { checkedLines, notCheckedBlock, NOT_CHECKED_LABEL } from '../checked.js';
41
+ import { checkedLines, notCheckedView, NOT_CHECKED_LABEL } from '../checked.js';
42
42
  import {
43
43
  NO_COPY_SAY, catchUpWords, endedLineWords, endedWords, needsLeftWords, nextInWords, nextTimeWords, scheduleAuditWords, scheduleBlockWords, scheduleFieldWords, scheduledNextFor, scheduledWords, startedWords,
44
44
  } from '../summary-words.js';
45
45
  import { MAX_STRUCTURE_RETRIES } from '../drafter.js';
46
+ import { isResultRun, checkTypeOf, buildResult, downloadOf } from './result.js';
47
+ import { thinkingRuleWords, thinkingTryWords } from '../thinking.js';
48
+ import { readRunThinking } from '../flowmodel.js';
49
+ import {
50
+ isTryRow, loadDiaries, deriveFold, cardLine, summaryLines,
51
+ } from '../audit-fold.js';
46
52
  import {
47
53
  runLiveness, booksFresh, readResumeLock,
48
54
  } from '../liveness.js';
@@ -712,11 +718,6 @@ export function deriveStepTryMarks(closeClass, rows) {
712
718
  return rows.map((r) => markForVerdict(r.verdict, closeClass));
713
719
  }
714
720
 
715
- /** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). */
716
- function isTryRow(r) {
717
- return r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && !(r.verdict === 'stopped' && !Number.isInteger(r.attempt));
718
- }
719
-
720
721
  /** The name of the one group for audit rows that name no step. */
721
722
  const RUN_GROUP = 'run';
722
723
  /** The one decider of a row's step name for the Audit tab: its step, else the run's own group name. */
@@ -1385,6 +1386,7 @@ function enrichAuditRows(rawRows) {
1385
1386
  action: deriveAuditAction(row),
1386
1387
  tokensDisplay: deriveAuditTokensDisplay(row),
1387
1388
  toolsPhrase: deriveAuditToolsPhrase(row),
1389
+ thinkingPhrase: thinkingTryWords(row.thinking), // M4d am26: null for a row that kept no thinking record
1388
1390
  atWhy: deriveAuditAtWhy(row),
1389
1391
  blocked: isBlockedVerdict(row.verdict),
1390
1392
  }));
@@ -1549,7 +1551,12 @@ export function getRunDetail({
1549
1551
  // summed copy. A step with no audit rows at all (never attempted) has no
1550
1552
  // entry here — its card falls back to "not started", same as before.
1551
1553
  const auditGroupsByStep = {};
1552
- for (const g of deriveAuditGroups(enrichAuditRows(ctx.auditRows))) auditGroupsByStep[g.step] = g;
1554
+ // M4d am29 items 5-6: the cards' marker and new line, and the summary's two lines, come from the SAME fold the Audit draws (src/audit-fold.js)
1555
+ const diaries = loadDiaries(run.runDir);
1556
+ for (const g of deriveAuditGroups(enrichAuditRows(ctx.auditRows))) {
1557
+ const fold = g.run ? null : deriveFold(g, diaries);
1558
+ auditGroupsByStep[g.step] = fold ? { ...g, fold } : g;
1559
+ }
1553
1560
 
1554
1561
  let steps = null;
1555
1562
  let stepsWhy = null;
@@ -1618,6 +1625,10 @@ export function getRunDetail({
1618
1625
  // (never attempted) — every field below stays `null`/empty rather
1619
1626
  // than a guessed 0, matching `deriveAuditGroups`'s own honesty
1620
1627
  // rules exactly (it's the SAME group object).
1628
+ // M4d am29 item 6: `[model]` / `[human · ask]` (null for a step with no record), and the one new line (`—` with no record); a human step's time is the page's
1629
+ who: group?.fold?.who ?? null,
1630
+ newLine: cardLine(group?.fold ?? null),
1631
+ lastAnswerAt: group?.fold?.lastAnswer?.at ?? null,
1621
1632
  groupState: group ? group.state : null,
1622
1633
  timeMs: group ? group.timeMs : null,
1623
1634
  cost: group ? group.cost : null,
@@ -1759,6 +1770,9 @@ export function getRunDetail({
1759
1770
  needsYou: (({ tag, removable }) => ({ tag, removable }))(needsYouOf({
1760
1771
  runDir: run.runDir, ctx, glyph, controls: runControls(ctx, glyph, label), nowMs: now(), reopenAt: reopenableAt(run.runDir, ctx),
1761
1772
  })),
1773
+ // M10 am4: the Result tab shows for a job that reads a page, a CSV or a .docx; `checkType` is its distinct close classes (the tab's top card)
1774
+ hasResult: isResultRun(ctx.arbiter),
1775
+ checkType: ctx.flowRead.ok ? checkTypeOf(ctx.flowRead.declaration) : '\u2014',
1762
1776
  // M9 piece 6: the block at the top of the run page (ENDED / NEXT, SCHEDULED / NEXT), words set by code
1763
1777
  summary: runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }),
1764
1778
  resume: ctx.resume,
@@ -1769,6 +1783,8 @@ export function getRunDetail({
1769
1783
  model,
1770
1784
  modelWhy,
1771
1785
  spendSummary,
1786
+ // M4d am29 item 5: `calls: …` and `checks: …` (`—` for a run with no diaries)
1787
+ runLines: summaryLines(diaries),
1772
1788
  wallMs,
1773
1789
  wallMsWhy,
1774
1790
  steps,
@@ -1869,6 +1885,7 @@ export function getDraftBlock(flowDir, runDir) {
1869
1885
  else if (r.kind === 'startover') happened.push(r.verdict === 'green' ? `starting over${retry(r)}` : 'start over red');
1870
1886
  else if (r.kind === 'revise') happened.push(r.verdict === 'red' ? 'revise red' : `revising${retry(r)}`);
1871
1887
  else if (r.kind === 'redraft') happened.push(r.verdict === 'red' ? 'redraft red' : `redrafting with your answers${retry(r)}`);
1888
+ else if (r.kind === 'human') happened.push('your answer');
1872
1889
  else if (r.kind === 'sign') happened.push(`signed (${r.signedBy ?? 'you'})`);
1873
1890
  if (r.kind === 'card') {
1874
1891
  const c = r.card && typeof r.card === 'object' ? r.card : {};
@@ -1876,6 +1893,8 @@ export function getDraftBlock(flowDir, runDir) {
1876
1893
  typeof c.inputs === 'string' && c.inputs.trim() ? `inputs: ${c.inputs.trim().replace(/\n+/g, ' / ')}` : null, `job: ${String(c.job ?? '').trim().replace(/\n+/g, ' / ')}`].filter(Boolean).join(' · ');
1877
1894
  rows.push(human(r, n, { action: 'card (you)', gap }));
1878
1895
  } else if (r.kind === 'note') rows.push(human(r, n, { action: 'note (you)', gap: String(r.text ?? '') }));
1896
+ // M10 am2 item 4: a question the page look raised and your answer, under the drafting step, in bareloop's words (`you were asked:` / `you said:`)
1897
+ else if (r.kind === 'human') rows.push(human(r, n, { action: `you were asked: ${r.question}`, gap: `you said: ${r.answer}` }));
1879
1898
  else if (r.kind === 'draft') { rows.push(model(r, n, 'draft')); rows.push(...tryRows(r, n)); }
1880
1899
  else if (r.kind === 'change') { rows.push(model(r, n, `change ${r.n}`)); rows.push(...tryRows(r, n)); }
1881
1900
  else if (r.kind === 'startover') { rows.push(model(r, n, 'start over')); rows.push(...tryRows(r, n)); }
@@ -1918,6 +1937,27 @@ export function getDraftBlock(flowDir, runDir) {
1918
1937
  };
1919
1938
  }
1920
1939
 
1940
+ /**
1941
+ * M4d am29 items 4-6: put each step group's `fold` (src/audit-fold.js) on it, in place. An ask step's fold names the file it asks about
1942
+ * (the artifact its first `reads` entry made), read from the run's own saved job when it can be read; otherwise the Path shows `—`.
1943
+ * @param {any[]} groups @param {string} runDir @param {string} flowDir @param {{root: string, flow: string, catalogue?: any}} o
1944
+ */
1945
+ function attachFolds(groups, runDir, flowDir, { root, flow, catalogue }) {
1946
+ const d = loadDiaries(runDir);
1947
+ let steps = null;
1948
+ if (catalogue) {
1949
+ const job = readRunJob({ root, name: flow, catalogue, runDir }).read;
1950
+ if (job.ok) steps = job.declaration.steps ?? [];
1951
+ }
1952
+ for (const g of groups) {
1953
+ if (g.run) continue;
1954
+ const decl = steps?.find((x) => x.emits === g.step);
1955
+ const read = Array.isArray(decl?.reads) ? decl.reads[0] : null;
1956
+ const fold = deriveFold(g, d, { about: typeof read === 'string' ? `artifacts/${read}.json` : null });
1957
+ if (fold) g.fold = fold;
1958
+ }
1959
+ }
1960
+
1921
1961
  /**
1922
1962
  * `GET /api/runs/:flow/:runId/audit` — the Audit/logs tab (M4a scope item
1923
1963
  * 2): the raw `audit.jsonl` rows, scoped strictly to this run (each run's
@@ -1941,6 +1981,9 @@ export function getRunAudit({
1941
1981
  // (`tokensDisplay`) and the new Time column's old-row "why" (`atWhy`) are
1942
1982
  // likewise derived here, off this same row, never client-side.
1943
1983
  const rows = enrichAuditRows(rawRows);
1984
+ // M4d am29 items 4 and 7: each step's fold is read off the run's files on disk ($0 replay); a step with no record (an older run) has none and draws as before
1985
+ const groups = deriveAuditGroups(rows);
1986
+ attachFolds(groups, run.runDir, run.flowDir, { root, flow, catalogue });
1944
1987
  return {
1945
1988
  flow,
1946
1989
  runId,
@@ -1948,7 +1991,7 @@ export function getRunAudit({
1948
1991
  // hamr's 2026-09-27 exit-check review #1: the Audit tab's grouped-by-
1949
1992
  // step header pieces, computed here off these SAME enriched rows —
1950
1993
  // never a second, client-side re-grouping.
1951
- groups: deriveAuditGroups(rows),
1994
+ groups,
1952
1995
  draft: getDraftBlock(run.flowDir, run.runDir),
1953
1996
  // M11 am11 items 3-4: the one row that says why the card left Needs you (by your Remove, or after 7 days); words: src/summary-words.js
1954
1997
  needsLeft: catalogue ? needsLeftWords(getRunNeeds({
@@ -1960,12 +2003,13 @@ export function getRunAudit({
1960
2003
  if (!t) return null; // no schedule now: scheduleAuditWords still answers for a cancelled job that has am16 rows (M9 am18), else null
1961
2004
  const rec = readTriggerRecord(run.runDir);
1962
2005
  const at = firstPidStartedAt(run.runDir) ?? (rec && typeof rec.at === 'string' ? rec.at : null); // the fire's own stamp when the run kept no pid row yet
1963
- return scheduleAuditWords({
2006
+ const sched = scheduleAuditWords({
1964
2007
  trigger: t.trigger, runId, from: t.from ?? null, rec, startMs: at === null || Number.isNaN(Date.parse(at)) ? null : Date.parse(at),
1965
2008
  block: scheduleBlockOf({ root, flowDir: run.flowDir, flow, catalogue, t, home, now }),
1966
2009
  running: jobHasRunningRun({ root, flow, catalogue, resumeAttempt, startingRun }),
1967
2010
  fires: Array.isArray(t.allFires) ? t.allFires : [],
1968
2011
  });
2012
+ return sched === null ? null : { ...sched, word: SIGN_WORDS[sched.sign] ?? null }; // M9 am23: the header's word, from the one sign->word table
1969
2013
  })(),
1970
2014
  empty: rows.length === 0,
1971
2015
  why: rows.length === 0 ? 'audit.jsonl is empty or missing — no attempt has been made yet' : null,
@@ -2005,7 +2049,8 @@ function buildJobPlan(declaration, asks, flowDir, flowHash = null) {
2005
2049
  const ofThisJob = !!signRow && (typeof signRow.flowHash !== 'string' || flowHash === null || signRow.flowHash === flowHash);
2006
2050
  const nc = ofThisJob ? signRow?.notChecked : undefined;
2007
2051
  const recorded = !!nc && Array.isArray(nc.items);
2008
- return { steps, notChecked: { label: NOT_CHECKED_LABEL, items: recorded ? notCheckedBlock(nc.items).items : [], recorded } };
2052
+ const view = recorded ? notCheckedView(nc.items, declaration) : { items: [], readNotes: [] };
2053
+ return { steps, notChecked: { label: NOT_CHECKED_LABEL, items: view.items, readNotes: view.readNotes, recorded } };
2009
2054
  }
2010
2055
 
2011
2056
  /**
@@ -2068,6 +2113,8 @@ export function getRunJob({
2068
2113
  trigger: f && f.trigger ? f.trigger : null, from: f?.from ?? null, model: f?.model ?? null, destination: f?.destination ?? null, inputs: f?.inputs ?? null, home,
2069
2114
  });
2070
2115
  })(),
2116
+ // M4d am28: the run's rule from its own thinking.json; a run with none (before am25) reads `—` (thinkingRuleWords(null)); the row always shows
2117
+ thinkingRule: thinkingRuleWords(readRunThinking(run.runDir)),
2071
2118
  jobFrom: copy.present ? 'run' : 'current',
2072
2119
  jobFromWhy: copy.present ? null : NO_JOB_COPY_WORDS,
2073
2120
  model,
@@ -2109,6 +2156,79 @@ export function getRunJob({
2109
2156
  };
2110
2157
  }
2111
2158
 
2159
+ /**
2160
+ * M10 am4: what `getRunResult` and `getRunDownload` both need of one run: its books and the signed job it ran. `null` = no such run, the job is
2161
+ * unreadable, or it is not an M10 job (the route answers 404 "no such run, or it has no result tab").
2162
+ * @param {{root: string, flow: string, runId: string, catalogue: any}} a
2163
+ */
2164
+ function resultContext({
2165
+ root, flow, runId, catalogue,
2166
+ }) {
2167
+ const run = resolveRunPath(root, flow, runId);
2168
+ if (!run.ok || !readdirInside(run.flowDir, 'runs').includes(runId)) return null; // the gateway lists real, non-symlink run folders only
2169
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue);
2170
+ if (!ctx.flowRead.ok || !isResultRun(ctx.arbiter)) return null;
2171
+ return { run, ctx };
2172
+ }
2173
+
2174
+ /**
2175
+ * M10 am5 item 2: does this run wait for the person's accept? The Ask tab's own rule (`answerControls` kind "doors"): the newest ask is open and either has no saved
2176
+ * answer or its saved answer could not be read. Read from `getRunAsks`, the Ask tab's one reader, so the two tabs can never disagree.
2177
+ * @param {ReturnType<typeof getRunAsks>} asks @returns {{askId: string, draftNo: number}|null}
2178
+ */
2179
+ function resultDoorOf(asks) {
2180
+ if (asks === null) return null;
2181
+ const block = asks.blocks.at(-1);
2182
+ const ask = block?.current;
2183
+ if (!ask || ask.open !== true) return null;
2184
+ if (asks.resume && asks.resume.askId === ask.askId && asks.resume.state !== 'broken') return null;
2185
+ return { askId: ask.askId, draftNo: block.draftNo };
2186
+ }
2187
+
2188
+ /**
2189
+ * `GET /api/runs/:flow/:runId/result` — the Result tab (M10 am4). The Not checked list is the Job tab's own (`buildJobPlan`), never a second spelling.
2190
+ * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any, now?: () => number}} a
2191
+ * @returns {any|null}
2192
+ */
2193
+ export function getRunResult({
2194
+ root, flow, runId, catalogue, resumeAttempt, now,
2195
+ }) {
2196
+ const got = resultContext({
2197
+ root, flow, runId, catalogue,
2198
+ });
2199
+ if (!got) return null;
2200
+ const { run, ctx } = got;
2201
+ const sig = ctx.flowRead.signature;
2202
+ const plan = buildJobPlan(ctx.flowRead.declaration, ctx.arbiter.asks ?? [], run.flowDir, typeof sig?.flow === 'string' ? sig.flow : null);
2203
+ return buildResult({
2204
+ flow, runId, runDir: run.runDir, root, flowRead: ctx.flowRead, arbiter: ctx.arbiter, historyRow: ctx.historyRow, auditRows: ctx.auditRows, logJson: ctx.logJson, notChecked: plan.notChecked.items, readNotes: plan.notChecked.readNotes,
2205
+ setupRows: (() => { const st = readSetup(run.flowDir); return st.present ? st.rows : []; })(),
2206
+ door: resultDoorOf(getRunAsks({
2207
+ root, flow, runId, catalogue, resumeAttempt, now,
2208
+ })),
2209
+ });
2210
+ }
2211
+
2212
+ /**
2213
+ * `GET /api/runs/:flow/:runId/download?i=<n>` (M10 am4): one saved file, or why not.
2214
+ * @param {{root: string, flow: string, runId: string, catalogue: any, index: unknown}} a
2215
+ * @returns {ReturnType<typeof downloadOf>}
2216
+ */
2217
+ export function getRunDownload({
2218
+ root, flow, runId, catalogue, index,
2219
+ }) {
2220
+ const got = resultContext({
2221
+ root, flow, runId, catalogue,
2222
+ });
2223
+ if (!got) return { ok: false, code: 404, error: 'no such run, or it has no result tab' };
2224
+ return downloadOf({
2225
+ index,
2226
+ ctx: {
2227
+ arbiter: got.ctx.arbiter, declaration: got.ctx.flowRead.declaration, runDir: got.run.runDir, root, flow, runId, auditRows: got.ctx.auditRows,
2228
+ },
2229
+ });
2230
+ }
2231
+
2112
2232
  // ---------------------------------------------------------------------------
2113
2233
  // M4a Amendment M4a-1 — the panel's Inbox/Ask surface (docs/wiki/the-module-
2114
2234
  // ladder.md, "M4a" section, signed 2026-09-27). Every stop (parked ask) this