fwdloop 0.12.0 → 0.13.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 (56) hide show
  1. package/bin/fwdloop +136 -21
  2. package/package.json +1 -1
  3. package/src/ask.js +3 -0
  4. package/src/authoring.js +101 -13
  5. package/src/books.js +23 -2
  6. package/src/canrun.js +36 -0
  7. package/src/config.js +2 -1
  8. package/src/declaration.js +72 -2
  9. package/src/drafter.js +41 -3
  10. package/src/draftspend.js +70 -0
  11. package/src/flow.js +43 -0
  12. package/src/liveness.js +1 -1
  13. package/src/model-step.js +30 -4
  14. package/src/monthly.js +58 -13
  15. package/src/panel/author.js +482 -0
  16. package/src/panel/authorcard.js +297 -0
  17. package/src/panel/authorflows.js +312 -0
  18. package/src/panel/authorresume.js +149 -0
  19. package/src/panel/authorstart.js +257 -0
  20. package/src/panel/authorvalues.js +110 -0
  21. package/src/panel/data.js +228 -34
  22. package/src/panel/index.html +1745 -127
  23. package/src/panel/resume.js +6 -8
  24. package/src/panel/server.js +119 -119
  25. package/src/panel/settings.js +7 -5
  26. package/src/panel/spawn.js +77 -0
  27. package/src/provider.js +12 -17
  28. package/src/runner.js +639 -85
  29. package/src/runvalues.js +178 -0
  30. package/src/send.js +10 -3
  31. package/src/setup.js +120 -0
  32. package/types/authoring.d.ts +24 -2
  33. package/types/books.d.ts +14 -2
  34. package/types/canrun.d.ts +32 -0
  35. package/types/config.d.ts +1 -0
  36. package/types/declaration.d.ts +9 -1
  37. package/types/drafter.d.ts +15 -1
  38. package/types/draftspend.d.ts +21 -0
  39. package/types/flow.d.ts +23 -0
  40. package/types/liveness.d.ts +2 -2
  41. package/types/model-step.d.ts +3 -1
  42. package/types/monthly.d.ts +21 -0
  43. package/types/panel/author.d.ts +335 -0
  44. package/types/panel/authorcard.d.ts +120 -0
  45. package/types/panel/authorflows.d.ts +175 -0
  46. package/types/panel/authorresume.d.ts +32 -0
  47. package/types/panel/authorstart.d.ts +115 -0
  48. package/types/panel/authorvalues.d.ts +62 -0
  49. package/types/panel/data.d.ts +103 -12
  50. package/types/panel/server.d.ts +11 -33
  51. package/types/panel/spawn.d.ts +30 -0
  52. package/types/provider.d.ts +6 -9
  53. package/types/runner.d.ts +120 -5
  54. package/types/runvalues.d.ts +97 -0
  55. package/types/send.d.ts +5 -1
  56. package/types/setup.d.ts +83 -0
package/src/panel/data.js CHANGED
@@ -28,10 +28,15 @@ import {
28
28
  readFlow, listFlowNames, listRunIds, resolveRunDir, checkFlowName, readFileInside, readdirInside,
29
29
  } from '../flow.js';
30
30
  import {
31
- readAudit, readHistory, readPidRows, auditRowTokens, auditRowAt, auditRowTools,
31
+ readAudit, readHistory, endRow, readPidRows, auditRowTokens, auditRowAt, auditRowTools,
32
32
  } from '../books.js';
33
- import { readAsk, readRunState, readLog } from '../runner.js';
33
+ import {
34
+ readAsk, readRunState, readLog, readHaltRecord, stopPending,
35
+ } from '../runner.js';
34
36
  import { readSpendRows } from '../provider.js';
37
+ import { applyRunValues, parseWaitMs, pickRunValues, VALUES_FILE_RE } from '../runvalues.js';
38
+ import { readSetup } from '../setup.js';
39
+ import { MAX_STRUCTURE_RETRIES } from '../drafter.js';
35
40
  import {
36
41
  runLiveness, booksFresh, readResumeLock,
37
42
  } from '../liveness.js';
@@ -170,7 +175,10 @@ export const RESUME_REASON_UNKNOWN = 'reason unknown: the panel restarted, so it
170
175
  * @param {{savedAnswer: {askId:string, decision:string|null, answeredAt?:string|null}|null, attempt: any, ask?: any}} ctx
171
176
  * @returns {{state: 'starting'|'not-started'|'broken'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
172
177
  */
173
- export function deriveResumeState({ savedAnswer: saved, attempt, ask = null }) {
178
+ export function deriveResumeState({ savedAnswer: savedOnDisk, attempt, ask = null }) {
179
+ // An answer.json naming another ask than the open one is not this run's answer (answerAsk refuses to write one; a
180
+ // hand-placed file can): the run reads as what it is, waiting at the open ask. Readers never move the file.
181
+ const saved = savedOnDisk && ask && typeof ask.askId === 'string' && savedOnDisk.askId !== ask.askId ? null : savedOnDisk;
174
182
  const pastDeadline = !!(ask && saved && ask.askId === saved.askId && Date.parse(ask.expiresAt) < Date.now());
175
183
  if (saved && pastDeadline && answerTiming(saved.answeredAt, ask.expiresAt) !== 'on-time') return null;
176
184
  const tries = attempt ? attempt.tries : null;
@@ -219,7 +227,7 @@ export const CRASHED_LABEL = 'crashed after taking your answer — start a fresh
219
227
  * @type {Record<string, string>}
220
228
  */
221
229
  export const SIGN_WORDS = {
222
- '[▶]': 'running', '[·]': 'waiting', '[II]': 'stuck', '[!]': 'expired', '[?]': 'crashed', '[✓]': 'passed', '[✗]': 'failed',
230
+ '[▶]': 'running', '[·]': 'waiting', '[II]': 'stuck', '[!]': 'expired', '[?]': 'crashed', '[✓]': 'passed', '[✗]': 'failed', '[■]': 'stopped',
223
231
  };
224
232
 
225
233
  /**
@@ -317,6 +325,7 @@ export function glyphPulses(g) {
317
325
  * `computeGlyph`, the derivation the M4a POC proved against every real run
318
326
  * on disk. Ladder wording (M4a scope item 4):
319
327
  * - `[✓]` passed — a history row with `outcome:'complete'`.
328
+ * - `[■]` stopped (M4e amendment 4) — a history row `stopped`, or `cap-halt` with a halt record to continue from.
320
329
  * - `[✗]` failed — a history row with any other outcome (never `[?]`).
321
330
  * - `[·]` waiting on you — parked (`ask.json` present), no consumed answer,
322
331
  * NOT past its own `expiresAt`.
@@ -348,14 +357,17 @@ export function glyphPulses(g) {
348
357
  * A saved answer with a live process is `[▶]` working on your answer.
349
358
  * - `[?]` crashed after taking your answer (amendment 2 (f)) — the answer was
350
359
  * consumed, the process is gone, no end row: cannot be carried on.
351
- * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string}} ctx
352
- * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[▶]'|'[?]'|'[II]', label: string}}
360
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string, resumable?: boolean}} ctx
361
+ * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[▶]'|'[?]'|'[II]'|'[■]', label: string}}
353
362
  */
354
363
  export function computeGlyph({
355
- historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock,
364
+ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock, resumable,
356
365
  }) {
357
366
  if (historyRow) {
358
367
  if (historyRow.outcome === 'complete') return { glyph: '[✓]', label: 'passed' };
368
+ // M4e amendment 4 item 4: a run the human stopped, or one that hit its money cap and can be continued, is `[■]` stopped — never "failed".
369
+ if (historyRow.outcome === 'stopped') return { glyph: '[■]', label: 'stopped — after the step that was running; Resume to go on' };
370
+ if (historyRow.outcome === 'cap-halt' && resumable) return { glyph: '[■]', label: 'stopped — the money cap was reached; raise it and Resume' };
359
371
  // M4b amendment 3: a run the human ended on purpose with rerun is not a failure.
360
372
  if (historyRow.outcome === 'rerun') return { glyph: '[✗]', label: 'stopped by you (rerun), a fresh run was started' };
361
373
  // M4c-fix amendment 1 (c): a run ended because its ask expired is `[!]` expired, never failed (it spent nothing more).
@@ -641,7 +653,7 @@ export function isBlockedVerdict(verdict) {
641
653
  function markForVerdict(verdict, closeClass) {
642
654
  if (closeClass === 'hitl' && verdict === 'red') return '✗'; // the human's own redo
643
655
  if (verdict === 'green' || verdict === 'hitl') return '✓';
644
- if (verdict === 'paused' || verdict === 'refused' || verdict === 'ask-timeout' || verdict === 'ask-expired' || verdict === 'ask-reopened' || verdict === 'lock-removed') return '·';
656
+ if (verdict === 'paused' || verdict === 'refused' || verdict === 'ask-timeout' || verdict === 'ask-expired' || verdict === 'ask-reopened' || verdict === 'lock-removed' || verdict === 'stop-asked' || verdict === 'stopped' || verdict === 'stop-not-honoured') return '·';
645
657
  return '✗';
646
658
  }
647
659
 
@@ -684,22 +696,37 @@ export function deriveStepTryMarks(closeClass, rows) {
684
696
  return rows.map((r) => markForVerdict(r.verdict, closeClass));
685
697
  }
686
698
 
699
+ /** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). */
700
+ function isTryRow(r) {
701
+ return r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && !(r.verdict === 'stopped' && !Number.isInteger(r.attempt));
702
+ }
703
+
704
+ /** The name of the one group for audit rows that name no step. */
705
+ const RUN_GROUP = 'run';
706
+ /** The one decider of a row's step name for the Audit tab: its step, else the run's own group name. */
707
+ function auditStepName(step) {
708
+ return typeof step === 'string' && step.length > 0 ? step : RUN_GROUP;
709
+ }
710
+
687
711
  /**
688
712
  * A step group's own state word for the Audit tab's collapsed header —
689
- * the SAME rule `src/panel/index.html`'s client-side `stepBoxState` already
690
- * applies to the Run tab's map/cards (ported here so the Audit header can
691
- * be computed server-side too, off the SAME last-row-wins logic): `waiting`
713
+ * the ONE decider of a step's state: the Run tab's map and cards read it too
714
+ * (`groupState` on each step; the page keeps no rule of its own), last-row-wins: `waiting`
692
715
  * (the run is currently parked on this step — its last attempt's verdict is
693
716
  * `paused`/`refused`), `done` (the last attempt passed — `green`/`hitl`),
694
- * `stopped` (the last attempt failed for any other reason). A group only
717
+ * `user-stopped` (M4e amendment 10: the step's own last row is `stopped`, a Stop
718
+ * the human asked), `stopped` (the last attempt failed for any other reason). A group only
695
719
  * ever exists for a step with at least one row, so `pending` never appears
696
720
  * here (unlike the Run tab's map, which also covers never-attempted steps).
697
721
  * @param {Array<{verdict:string}>} rows one step's own audit rows, book order
698
- * @returns {'done'|'waiting'|'stopped'}
722
+ * @returns {'done'|'waiting'|'stopped'|'user-stopped'}
699
723
  */
700
724
  export function deriveStepGroupState(rows) {
701
- const last = rows[rows.length - 1];
725
+ // a Stop's notes (asked / not honoured) say nothing about the step's own state; a step with only notes reads as stopped
726
+ const own = rows.filter((r) => r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured');
727
+ const last = own.length > 0 ? own[own.length - 1] : rows[rows.length - 1];
702
728
  if (last.verdict === 'paused' || last.verdict === 'refused') return 'waiting';
729
+ if (last.verdict === 'stopped') return 'user-stopped';
703
730
  return (last.verdict === 'green' || last.verdict === 'hitl') ? 'done' : 'stopped';
704
731
  }
705
732
 
@@ -731,13 +758,16 @@ export function deriveStepGroupState(rows) {
731
758
  */
732
759
  export function deriveAuditGroups(enrichedRows) {
733
760
  const order = [];
734
- const byStep = {};
761
+ const byStep = new Map();
762
+ // a row naming no step (a Stop before step 1) is the run's own: one group, `run: true`, never a null id
735
763
  for (const r of enrichedRows) {
736
- if (!Object.prototype.hasOwnProperty.call(byStep, r.step)) { byStep[r.step] = []; order.push(r.step); }
737
- byStep[r.step].push(r);
764
+ const key = typeof r.step === 'string' && r.step.length > 0 ? r.step : null;
765
+ if (!byStep.has(key)) { byStep.set(key, []); order.push(key); }
766
+ byStep.get(key).push(r);
738
767
  }
739
- return order.map((step) => {
740
- const rows = byStep[step];
768
+ return order.map((key) => {
769
+ const rows = byStep.get(key);
770
+ const step = auditStepName(key);
741
771
  const closeClass = rows[0].class ?? null;
742
772
  const timeMs = rows.reduce((acc, r) => acc + (typeof r.wallMs === 'number' ? r.wallMs : 0), 0);
743
773
 
@@ -764,7 +794,7 @@ export function deriveAuditGroups(enrichedRows) {
764
794
  }
765
795
  const tokensTotalValue = (anyNotRecorded || !anyTotal) ? null : tokensTotal;
766
796
 
767
- const tryMarks = deriveStepTryMarks(closeClass, rows);
797
+ const tryMarks = deriveStepTryMarks(closeClass, rows.filter(isTryRow));
768
798
  const { toolsTotal, toolsWhy, ungranted } = summarizeStepTools(rows);
769
799
  return {
770
800
  step,
@@ -777,8 +807,9 @@ export function deriveAuditGroups(enrichedRows) {
777
807
  toolsTotal,
778
808
  toolsWhy,
779
809
  ungranted,
780
- tryCount: tryMarks.length,
781
- tryMarks,
810
+ tryCount: key === null ? 0 : tryMarks.length,
811
+ tryMarks: key === null ? [] : tryMarks,
812
+ ...(key === null ? { run: true } : {}),
782
813
  rows,
783
814
  };
784
815
  });
@@ -840,8 +871,11 @@ export function summarizeSpendRows(spendRows) {
840
871
  */
841
872
  function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attempt = null) {
842
873
  const flowRead = readFlow({ root, name: flowName, catalogue });
874
+ // M4e amendment 5 item 3 / amendment 4 item 6: the run's own signed values (its newest version) lie over the flow's
875
+ const inForce = flowRead.ok ? applyRunValues(flowRead.arbiter, flowName, flowRead.signature.flow, pickRunValues(runDir)) : null;
843
876
  const historyRows = readHistory(flowDir);
844
- const historyRow = historyRows.find((r) => r && r.runId === runId) ?? null;
877
+ const historyRow = endRow(historyRows, runDir, runId);
878
+ const halt = readHaltRecord(runDir);
845
879
  const auditRows = readAudit(runDir);
846
880
  const spendRows = readSpendRows(join(runDir, 'spend.jsonl'));
847
881
  const logJson = readLog(runDir);
@@ -858,7 +892,11 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
858
892
  flowDir,
859
893
  runDir,
860
894
  flowRead,
895
+ // the arbiter this run executes under (the flow's own unless the run has signed values), or null when the flow does not read
896
+ arbiter: inForce && inForce.ok ? inForce.arbiter : (flowRead.ok ? flowRead.arbiter : null),
861
897
  historyRow,
898
+ // M4e amendment 4 item 4: a cap-halted or stopped run that can be continued (`halt.json` is the runner's record)
899
+ resumable: halt.ok && historyRow !== null && historyRow.outcome === halt.halt.outcome,
862
900
  auditRows,
863
901
  spendRows,
864
902
  logJson,
@@ -890,6 +928,46 @@ const RUNNING_WHY = 'still running — not finished yet';
890
928
  /** @param {any} ctx @param {string} glyph */
891
929
  const isRunningNow = (ctx, glyph) => !ctx.historyRow && glyph === '[▶]';
892
930
 
931
+ /**
932
+ * M4e amendment 4 item 4: the ONE decision for the Run tab's Stop and Resume buttons (the Stop and Resume doors read the
933
+ * same object, so the page never offers what the door would refuse). `running` is the glyph's own rule (`isRunningNow`);
934
+ * a run with no process record yet is `starting`; a parked run (`[·]`/`[!]`, an open ask) is neither.
935
+ * @param {any} ctx `loadRunContext`'s result @param {string} glyph `computeGlyph`'s sign
936
+ * @returns {{canStop: boolean, atAsk: boolean, stopRequested: boolean, starting: boolean, canResume: boolean, resumeOutcome: string|null, spentUsd: number|null, spendComplete: boolean|null, capUsd: number|null}}
937
+ */
938
+ export function runControls(ctx, glyph, label = '') {
939
+ const running = isRunningNow(ctx, glyph) && !ctx.askJson;
940
+ // M4e amendment 13: a run waiting at its ask (open, unanswered, not expired) shows Stop too; it stops the run at the ask.
941
+ const atAsk = !ctx.historyRow && !!ctx.askJson && glyph === '[·]' && label === WAITING_LABEL;
942
+ const starting = !ctx.historyRow && !ctx.askJson && readPidRows(ctx.runDir).length === 0;
943
+ const canResume = ctx.resumable === true;
944
+ return {
945
+ canStop: running || atAsk,
946
+ atAsk,
947
+ stopRequested: running && stopPending(ctx.runDir),
948
+ starting,
949
+ canResume,
950
+ resumeOutcome: canResume ? ctx.historyRow.outcome : null,
951
+ spentUsd: canResume && typeof ctx.historyRow.spentUsd === 'number' ? ctx.historyRow.spentUsd : null,
952
+ spendComplete: canResume ? ctx.historyRow.spendComplete !== false : null,
953
+ capUsd: canResume && typeof ctx.historyRow.capUsd === 'number' ? ctx.historyRow.capUsd : null,
954
+ };
955
+ }
956
+
957
+ /**
958
+ * `runControls` for one run read straight from the books (the Stop door's own read). `null` when the run does not resolve.
959
+ * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
960
+ */
961
+ export function getRunControls({
962
+ root, flow, runId, catalogue,
963
+ }) {
964
+ const run = resolveRunPath(root, flow, runId);
965
+ if (!run.ok || !existsSync(run.runDir)) return null;
966
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue, null);
967
+ const g = computeGlyph(ctx);
968
+ return runControls(ctx, g.glyph, g.label);
969
+ }
970
+
893
971
  /**
894
972
  * `GET /api/runs` — every flow under `root`, every run under each flow
895
973
  * (M4a scope item 2). A flow with zero runs still gets one row (`runId:
@@ -952,6 +1030,7 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
952
1030
  ...signParts(glyph, label, ctx.historyRow?.outcome === 'rerun'),
953
1031
  pulse: glyphPulses({ glyph, label }),
954
1032
  stuck: glyph === '[II]',
1033
+ controls: runControls(ctx, glyph, label),
955
1034
  resume: ctx.resume,
956
1035
  spend,
957
1036
  spendWhy: (!ctx.historyRow && spend === null)
@@ -961,6 +1040,7 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
961
1040
  waitingAskId: waitingAsk ? waitingAsk.ask.askId : null,
962
1041
  timeLeftMs: waitingAsk ? waitingAsk.timeLeftMs : null,
963
1042
  at: ctx.historyRow ? ctx.historyRow.at : null,
1043
+ wallMs: ctx.historyRow && typeof ctx.historyRow.wallMs === 'number' ? ctx.historyRow.wallMs : null,
964
1044
  askedAt,
965
1045
  startedAt: isRunningNow(ctx, glyph) ? ctx.startedAt : null,
966
1046
  atWhy: (ctx.historyRow || askedAt) ? null
@@ -1023,6 +1103,7 @@ export function orderRuns(rows) {
1023
1103
  function enrichAuditRows(rawRows) {
1024
1104
  return rawRows.map((row) => ({
1025
1105
  ...row,
1106
+ stepName: auditStepName(row.step),
1026
1107
  action: deriveAuditAction(row),
1027
1108
  tokensDisplay: deriveAuditTokensDisplay(row),
1028
1109
  toolsPhrase: deriveAuditToolsPhrase(row),
@@ -1042,11 +1123,12 @@ function enrichAuditRows(rawRows) {
1042
1123
  * pairing at all — each row IS one model attempt, so try N stays
1043
1124
  * `list.length` there, unchanged from before this fix.
1044
1125
  * @param {string|null} closeClass
1045
- * @param {Array<{verdict:string}>} list
1126
+ * @param {Array<{verdict:string}>} listAll
1046
1127
  * @returns {number}
1047
1128
  */
1048
- function computeTryCount(closeClass, list) {
1049
- if (!list || !list.length) return 0;
1129
+ function computeTryCount(closeClass, listAll) {
1130
+ const list = (listAll ?? []).filter(isTryRow);
1131
+ if (!list.length) return 0;
1050
1132
  if (closeClass === 'hitl') {
1051
1133
  const pausedCount = list.filter((a) => a.verdict === 'paused').length;
1052
1134
  // No paused row at all is not a shape this step ever produces in
@@ -1209,6 +1291,9 @@ export function getRunDetail({
1209
1291
  // M4b amendment 3: the human ended this run on purpose; an earlier redo's
1210
1292
  // audit row is not "why it stopped".
1211
1293
  stopReasonWhy = 'stopped by you (rerun), a fresh run was started — there is no failure to show';
1294
+ } else if (ctx.historyRow && ctx.historyRow.outcome === 'stopped') {
1295
+ // M4e amendment 4: the human's Stop is not a failure on any step; no step card carries it.
1296
+ stopReasonWhy = typeof ctx.logJson?.red === 'string' && ctx.logJson.red.length > 0 ? ctx.logJson.red : 'stopped by you';
1212
1297
  } else if (ctx.resume && (ctx.resume.state === 'starting' || ctx.resume.state === 'not-started')) {
1213
1298
  // M4b amendment 1: the human already answered — never "waiting on you".
1214
1299
  stopReasonWhy = ctx.resume.reason ? `${ctx.resume.label}: ${ctx.resume.reason}` : ctx.resume.label;
@@ -1287,10 +1372,11 @@ export function getRunDetail({
1287
1372
  ...signParts(glyph, label, ctx.historyRow?.outcome === 'rerun'),
1288
1373
  signWords: SIGN_WORDS,
1289
1374
  pulse: glyphPulses({ glyph, label }),
1375
+ controls: runControls(ctx, glyph, label),
1290
1376
  resume: ctx.resume,
1291
1377
  outcome: ctx.historyRow ? ctx.historyRow.outcome : null,
1292
1378
  outcomeWhy: ctx.historyRow ? null : (isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row (parked or died before completion)'),
1293
- capUsd: ctx.historyRow ? ctx.historyRow.capUsd : (ctx.flowRead.ok ? ctx.flowRead.arbiter.capUsd : null),
1379
+ capUsd: ctx.historyRow ? ctx.historyRow.capUsd : (ctx.arbiter ? ctx.arbiter.capUsd : null),
1294
1380
  spend,
1295
1381
  model,
1296
1382
  modelWhy,
@@ -1299,6 +1385,8 @@ export function getRunDetail({
1299
1385
  wallMsWhy,
1300
1386
  steps,
1301
1387
  stepsWhy,
1388
+ // M4e amendment 7 item 2: the Draft is the run's first step on the Map and under it — one summary, read from the same function the Audit group uses
1389
+ draft: ((b) => ({ ...b.summary, rows: b.rows }))(getDraftBlock(ctx.flowDir, ctx.runDir)),
1302
1390
  modelWrote,
1303
1391
  modelWroteWhy,
1304
1392
  stopReason,
@@ -1319,6 +1407,110 @@ export function getRunDetail({
1319
1407
  };
1320
1408
  }
1321
1409
 
1410
+ /** The words the Draft says for a flow with no `setup.jsonl` (M4e amendment 6 item 4; renamed Draft by amendment 7 item 2). */
1411
+ export const NO_DRAFT_WORDS = 'no draft record';
1412
+
1413
+ /**
1414
+ * What the Draft adds up to, ONE place (the Map box, the first step card and the Audit group all read it, so the three can never disagree).
1415
+ * M4e amendment 9: `timeMs` is the card row's `at` to the sign row's `at` (the whole drafting, human time included), `null` when either has no
1416
+ * usable `at`; never a sum of the model rows' `wallMs`. `calls` sums the rows' `calls`, a row with none counts 1 and sets `callsAtLeast`, so an
1417
+ * unknown never shows as a smaller exact number; no model rows = `null`. `humanChecks` = the note rows + the sign row + the run's signed-values
1418
+ * rows (the card is not a check), given by the caller as `ctx.humanChecks`. Money follows `costDisplay` ("at least $X" for a floor).
1419
+ * @param {any[]} modelRows the draft and change rows (`kind` draft | change) of `setup.jsonl`
1420
+ * @param {{cardAt?: any, signAt?: any, humanChecks?: number|null}} [ctx]
1421
+ * @returns {{calls: number|null, callsAtLeast: boolean, timeMs: number|null, humanChecks: number|null, usd: number|null, spendComplete: boolean, cost: string|null, modelRows: number}}
1422
+ */
1423
+ export function draftTotals(modelRows, ctx = {}) {
1424
+ const priced = modelRows.filter((r) => typeof r.costUsd === 'number');
1425
+ const usd = priced.length > 0 ? priced.reduce((a, r) => a + r.costUsd, 0) : null;
1426
+ const spendComplete = modelRows.length > 0 && priced.length === modelRows.length && modelRows.every((r) => r.spendComplete === true);
1427
+ const cd = usd === null ? null : costDisplay(usd, spendComplete);
1428
+ const t0 = typeof ctx.cardAt === 'string' ? Date.parse(ctx.cardAt) : NaN;
1429
+ const t1 = typeof ctx.signAt === 'string' ? Date.parse(ctx.signAt) : NaN;
1430
+ const timeMs = Number.isFinite(t0) && Number.isFinite(t1) && t1 >= t0 ? t1 - t0 : null;
1431
+ const calls = modelRows.length > 0 ? modelRows.reduce((a, r) => a + (typeof r.calls === 'number' ? r.calls : 1), 0) : null;
1432
+ return {
1433
+ calls, callsAtLeast: modelRows.some((r) => typeof r.calls !== 'number'), timeMs,
1434
+ humanChecks: typeof ctx.humanChecks === 'number' && Number.isInteger(ctx.humanChecks) ? ctx.humanChecks : null,
1435
+ usd, spendComplete, cost: cd && cd.ok ? cd.display : null, modelRows: modelRows.length,
1436
+ };
1437
+ }
1438
+
1439
+ /**
1440
+ * M4e amendment 6 item 4 / amendment 7 item 2: the Draft of a run — the flow's own `setup.jsonl` (card, drafts, changes, notes, sign), then this
1441
+ * run's own signed-values rows (amendment 5: "Sign & run" for version 0, "Sign & resume" for a later version), every row in the SAME shape
1442
+ * as the run's audit rows so the page draws both with one row builder. Reads only through the safe gateways; never throws.
1443
+ * @param {string} flowDir @param {string} runDir
1444
+ * @returns {{present: boolean, why: string|null, rows: any[], summary: {present: boolean, why?: string, calls?: number|null, callsAtLeast?: boolean, humanChecks?: number|null, timeMs?: number|null, usd?: number|null, spendComplete?: boolean, cost?: string|null, modelRows?: number}}}
1445
+ */
1446
+ export function getDraftBlock(flowDir, runDir) {
1447
+ const setup = readSetup(flowDir);
1448
+ const rows = [];
1449
+ const human = (r, attempt, extra) => ({
1450
+ attempt, step: 'drafting', class: 'hitl', verdict: 'hitl', at: r.at ?? null, setup: true, blocked: false, action: 'human', tokensDisplay: { kind: 'no-model' }, ...extra,
1451
+ });
1452
+ const model = (r, attempt, label) => ({
1453
+ attempt, step: 'drafting', class: null, verdict: r.verdict === 'green' ? 'green' : (r.verdict === 'red' ? 'red' : 'not-done'), gap: r.gap ?? '', at: r.at ?? null, setup: true, blocked: false,
1454
+ action: `${label} · ${r.model ?? 'model not recorded'}${r.hash ? ` · plan ${String(r.hash).slice(0, 8)}` : ''}`,
1455
+ usd: typeof r.costUsd === 'number' ? r.costUsd : undefined, spendComplete: r.spendComplete === true, tokensDisplay: { kind: 'no-model' },
1456
+ ...(typeof r.wallMs === 'number' ? { wallMs: r.wallMs } : {}),
1457
+ });
1458
+ // M4e amendment 8 item 1, line 4: one short phrase per Draft row, in order (the drafting card joins them with ` · `)
1459
+ const happened = [];
1460
+ const retry = (r) => (Number.isInteger(r.structureRetries) && r.structureRetries >= 1 ? ` (retry ${r.structureRetries} of ${MAX_STRUCTURE_RETRIES})` : '');
1461
+ if (setup.present) {
1462
+ setup.rows.forEach((r, i) => {
1463
+ const n = i + 1;
1464
+ if (r.kind === 'card') happened.push('your card');
1465
+ else if (r.kind === 'note') happened.push('your note');
1466
+ else if (r.kind === 'draft') happened.push(r.verdict === 'green' ? `drafting${retry(r)}` : 'draft red');
1467
+ else if (r.kind === 'change') happened.push(r.verdict === 'red' ? 'change red' : `changing${retry(r)}`);
1468
+ else if (r.kind === 'sign') happened.push(`signed (${r.signedBy ?? 'you'})`);
1469
+ if (r.kind === 'card') {
1470
+ const c = r.card && typeof r.card === 'object' ? r.card : {};
1471
+ const gap = [`flow ${c.flowName ?? '?'}`, `cap $${c.capUsd ?? '?'}`, c.destination ? `destination ${c.destination}` : null, c.askWait ? `ask wait ${c.askWait}` : null,
1472
+ 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(' · ');
1473
+ rows.push(human(r, n, { action: 'card (you)', gap }));
1474
+ } else if (r.kind === 'note') rows.push(human(r, n, { action: 'note (you)', gap: String(r.text ?? '') }));
1475
+ else if (r.kind === 'draft') rows.push(model(r, n, 'draft'));
1476
+ else if (r.kind === 'change') rows.push(model(r, n, `change ${r.n}`));
1477
+ else if (r.kind === 'sign') rows.push(human(r, n, { action: `sign (${r.signedBy ?? 'you'})`, gap: `plan ${String(r.hash ?? '').slice(0, 12)}` }));
1478
+ });
1479
+ }
1480
+ const versions = [];
1481
+ for (const f of readdirInside(runDir, '.')) {
1482
+ const m = VALUES_FILE_RE.exec(f);
1483
+ if (m !== null) versions.push({ file: f, version: m[1] === undefined ? 0 : Number(m[1]) });
1484
+ }
1485
+ versions.sort((a, b) => a.version - b.version);
1486
+ for (const { file, version } of versions) {
1487
+ const t = readFileInside(runDir, file);
1488
+ let rec = null;
1489
+ try { rec = t.ok ? JSON.parse(t.text) : null; } catch { rec = null; }
1490
+ const v = rec && typeof rec === 'object' ? rec.values : null;
1491
+ const waits = v && typeof v === 'object' && v.askWaits && typeof v.askWaits === 'object'
1492
+ ? Object.entries(v.askWaits).map(([line, wait]) => ({ line, wait: String(wait), waitMs: parseWaitMs(wait) })) : [];
1493
+ const head = v && typeof v === 'object' ? [`cap $${v.capUsd}`, v.destination ? `destination ${v.destination}` : null].filter(Boolean) : [];
1494
+ const gap = v && typeof v === 'object'
1495
+ ? [...head, waits.length ? `ask waits ${waits.map((w) => `line ${w.line}: ${w.wait}`).join(', ')}` : null].filter(Boolean).join(' · ')
1496
+ : `${file} could not be read`;
1497
+ happened.push(`${version === 0 ? 'signed to run' : 'signed to resume'} (${rec?.signedBy ?? 'you'})`);
1498
+ rows.push(human({ at: rec?.at }, rows.length + 1, { action: `${version === 0 ? 'Sign & run' : 'Sign & resume'} (${rec?.signedBy ?? 'you'})`, gap, ...(waits.length ? { gapHead: head, gapWaits: waits } : {}) }));
1499
+ }
1500
+ const lastSign = setup.present ? [...setup.rows].reverse().find((r) => r.kind === 'sign') : undefined;
1501
+ const humanChecks = setup.present ? setup.rows.filter((r) => r.kind === 'note' || r.kind === 'sign').length + versions.length : null;
1502
+ const totals = setup.present
1503
+ ? draftTotals(setup.rows.filter((r) => r.kind === 'draft' || r.kind === 'change'), { cardAt: setup.rows.find((r) => r.kind === 'card')?.at, signAt: lastSign?.at, humanChecks })
1504
+ : null;
1505
+ // the group the Audit tab draws as a normal card (collapsed by default) and the box the Map and the first step card read
1506
+ // `ended` = how the drafting ended: `done` only with a sign row, else `not signed` (no `red` state: a red change shows on line 4 only)
1507
+ const ended = setup.present && setup.rows.some((r) => r.kind === 'sign') ? 'done' : 'not signed';
1508
+ const summary = setup.present && totals ? { present: true, ...totals, ended, happened } : { present: false, why: NO_DRAFT_WORDS };
1509
+ return {
1510
+ present: setup.present, why: setup.present ? null : NO_DRAFT_WORDS, rows, summary,
1511
+ };
1512
+ }
1513
+
1322
1514
  /**
1323
1515
  * `GET /api/runs/:flow/:runId/audit` — the Audit/logs tab (M4a scope item
1324
1516
  * 2): the raw `audit.jsonl` rows, scoped strictly to this run (each run's
@@ -1326,7 +1518,7 @@ export function getRunDetail({
1326
1518
  * shared-sidecar contamination risk here the way bareloop's gate-audit
1327
1519
  * sidecar had). `null` when the flow/runId doesn't resolve (404).
1328
1520
  * @param {{root: string, flow: string, runId: string}} opts
1329
- * @returns {{flow:string, runId:string, rows:any[], groups:any[], empty:boolean, why:string|null}|null}
1521
+ * @returns {{flow:string, runId:string, rows:any[], groups:any[], draft:ReturnType<typeof getDraftBlock>, empty:boolean, why:string|null}|null}
1330
1522
  */
1331
1523
  export function getRunAudit({ root, flow, runId }) {
1332
1524
  const run = resolveRunPath(root, flow, runId);
@@ -1348,6 +1540,7 @@ export function getRunAudit({ root, flow, runId }) {
1348
1540
  // step header pieces, computed here off these SAME enriched rows —
1349
1541
  // never a second, client-side re-grouping.
1350
1542
  groups: deriveAuditGroups(rows),
1543
+ draft: getDraftBlock(run.flowDir, run.runDir),
1351
1544
  empty: rows.length === 0,
1352
1545
  why: rows.length === 0 ? 'audit.jsonl is empty or missing — no attempt has been made yet' : null,
1353
1546
  };
@@ -1451,7 +1644,9 @@ export function getRunJob({
1451
1644
  // pretending the signed prose named it.
1452
1645
  const auditRows = readAudit(run.runDir);
1453
1646
  const model = deriveRunModel(auditRows);
1454
- const a = flowRead.arbiter ?? {};
1647
+ // the run's own signed values (cap, send folder, ask waits) when it has them; the flow's own otherwise
1648
+ const applied = applyRunValues(flowRead.arbiter, flow, sig.flow, pickRunValues(run.runDir));
1649
+ const a = (applied.ok ? applied.arbiter : flowRead.arbiter) ?? {};
1455
1650
  const asks = a.asks ?? [];
1456
1651
  const sends = a.sends ?? [];
1457
1652
  const sources = a.sources ?? [];
@@ -1913,7 +2108,7 @@ export function getRunAsks({
1913
2108
  const run = resolveRunPath(root, flow, runId);
1914
2109
  if (!run.ok) return null;
1915
2110
  if (!existsSync(run.runDir)) return null;
1916
- const histRow = readHistory(run.flowDir).find((r) => r && r.runId === runId);
2111
+ const histRow = endRow(readHistory(run.flowDir), run.runDir, runId) ?? undefined;
1917
2112
  const hasHistoryRow = !!histRow;
1918
2113
  // hamr's 2026-09-27 browser-walk bug #4: the Ask tab's own asks must carry
1919
2114
  // the SAME `open`/`timeLeftMs` fields listStops already computes for the
@@ -1982,19 +2177,18 @@ export function listStops({ root, resumeAttempt }) {
1982
2177
  for (const flowName of listFlowNames(root)) {
1983
2178
  const flowDir = join(root, flowName);
1984
2179
  const historyRows = readHistory(flowDir).filter((r) => r && typeof r.runId === 'string');
1985
- const historyRunIds = new Set(historyRows.map((r) => r.runId));
1986
- const expiredEnds = new Set(historyRows.filter((r) => r.outcome === 'ask-expired').map((r) => r.runId));
1987
2180
  for (const runId of listRunIds(flowDir)) {
1988
2181
  const run = resolveRunPath(root, flowName, runId);
1989
2182
  if (!run.ok) continue;
1990
- const hasHistoryRow = historyRunIds.has(runId);
2183
+ const end = endRow(historyRows, run.runDir, runId);
2184
+ const hasHistoryRow = end !== null;
1991
2185
  const resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flowName, runId) ?? null, ask: readAsk(run.runDir) });
1992
2186
  // M4c amendment 2: stuck by the ONE rule (`stuckState`), marked on the ask whose answer is saved.
1993
2187
  const st = runStuck(run.runDir, resume);
1994
2188
  const stuckAskId = !hasHistoryRow && st.stuck ? (resume?.askId ?? null) : null;
1995
2189
  const openAskJson = hasHistoryRow ? null : readAsk(run.runDir);
1996
2190
  const savedAskId = readSavedAnswer(run.runDir)?.askId;
1997
- const runAsks = runAsksInOrder(run.runDir, hasHistoryRow, expiredEnds.has(runId)).map((ask) => ({
2191
+ const runAsks = runAsksInOrder(run.runDir, hasHistoryRow, end?.outcome === 'ask-expired').map((ask) => ({
1998
2192
  flow: flowName,
1999
2193
  runId,
2000
2194
  ...ask,