fwdloop 0.6.0 → 0.7.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.
- package/bin/fwdloop +143 -64
- package/package.json +3 -3
- package/src/ask.js +260 -6
- package/src/books.js +209 -2
- package/src/flow.js +247 -2
- package/src/index.js +9 -3
- package/src/model-step.js +151 -12
- package/src/panel/data.js +1589 -0
- package/src/panel/index.html +2377 -0
- package/src/panel/server.js +268 -0
- package/src/primitives.js +136 -41
- package/src/provider.js +57 -41
- package/src/runner.js +393 -54
- package/src/send.js +20 -1
- package/src/types.js +18 -0
- package/types/ask.d.ts +77 -0
- package/types/books.d.ts +70 -2
- package/types/flow.d.ts +135 -0
- package/types/index.d.ts +5 -3
- package/types/panel/data.d.ts +433 -0
- package/types/panel/server.d.ts +45 -0
- package/types/primitives.d.ts +29 -0
- package/types/provider.d.ts +11 -0
- package/types/runner.d.ts +66 -5
- package/types/types.d.ts +41 -0
|
@@ -0,0 +1,1589 @@
|
|
|
1
|
+
// M4a piece 2 (docs/wiki/the-module-ladder.md, "M4a — read-only panel —
|
|
2
|
+
// SIGNED", scope item 2): the panel's data layer. Every function here is a
|
|
3
|
+
// pure reader — it takes `--root` plus a flow/run identity, reads fwdloop's
|
|
4
|
+
// own books through the readers `src/` already owns (`readFlow`, `readAudit`,
|
|
5
|
+
// `readHistory`, `readAsk`, `readRunState`, `readLog`, `readSpendRows`,
|
|
6
|
+
// `readAskEvidence`, `loadCatalogue`), and returns plain JSON-able data. No
|
|
7
|
+
// function here ever writes anything, and none reaches into `process.env`
|
|
8
|
+
// for a key/secret.
|
|
9
|
+
//
|
|
10
|
+
// Field derivations (the glyph rules, the cost-floor display) are ported
|
|
11
|
+
// from the M4a POC (poc/m4/panel-data.mjs, proven at F47 to hit the POC bar:
|
|
12
|
+
// 114 FILLED, 11 EMPTY-WITH-WHY, 0 GAP across every real run on disk) —
|
|
13
|
+
// never re-derived ad hoc, and the POC itself is never shipped (project
|
|
14
|
+
// rule: "never ship the POC" — this is the clean rebuild in `src/`).
|
|
15
|
+
//
|
|
16
|
+
// PATH SAFETY: every flow name is checked with `checkFlowName` and every
|
|
17
|
+
// runId is resolved with `resolveRunDir` (both `src/flow.js`) before this
|
|
18
|
+
// module touches a filesystem path for it — `src/panel/server.js` checks the
|
|
19
|
+
// same things at the route level, but this module refuses on its own too
|
|
20
|
+
// (negative scenario v: nothing outside `--root` is ever read).
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
existsSync, realpathSync,
|
|
24
|
+
} from 'node:fs';
|
|
25
|
+
import { join, basename, sep } from 'node:path';
|
|
26
|
+
|
|
27
|
+
import {
|
|
28
|
+
readFlow, listFlowNames, listRunIds, resolveRunDir, checkFlowName, readFileInside, readdirInside,
|
|
29
|
+
} from '../flow.js';
|
|
30
|
+
import {
|
|
31
|
+
readAudit, readHistory, auditRowTokens, auditRowAt, auditRowTools,
|
|
32
|
+
} from '../books.js';
|
|
33
|
+
import { readAsk, readRunState, readLog } from '../runner.js';
|
|
34
|
+
import { readSpendRows } from '../provider.js';
|
|
35
|
+
import { readAskEvidence, listArchivedAsks } from '../ask.js';
|
|
36
|
+
|
|
37
|
+
/** `{ ok:false, red }` result shape every exported function here can return
|
|
38
|
+
* instead of throwing — the server maps this to a 4xx, never a crash.
|
|
39
|
+
* @param {string} red
|
|
40
|
+
* @returns {{ok:false, red:string}} */
|
|
41
|
+
function refuse(red) {
|
|
42
|
+
return { ok: false, red };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Resolve `<root>/<flowName>` safely — `checkFlowName` first (never a raw
|
|
47
|
+
* string joined into a path). `checkFlowName` rules out a flowName that
|
|
48
|
+
* escapes `root` lexically (no `/`, `\`, `..`), but a flow directory named
|
|
49
|
+
* by URL is not required to have come from `listFlowNames` first — a
|
|
50
|
+
* request can name a flow directly. So if `<root>/<flowName>` actually
|
|
51
|
+
* exists, it is re-checked with `realpathSync`: it must resolve inside the
|
|
52
|
+
* real `root`, same class of hole `resolveRunDir` closes for a run dir one
|
|
53
|
+
* level down (a symlinked flow directory would never show up in a
|
|
54
|
+
* `listFlowNames` listing, since a symlink dirent never reports
|
|
55
|
+
* `isDirectory()`, but a direct request naming it by its allow-list-legal
|
|
56
|
+
* name must still be refused). A not-yet-existing flow directory has
|
|
57
|
+
* nothing to realpath, so only the lexical result applies to it.
|
|
58
|
+
* Returns the flow directory, or a refusal.
|
|
59
|
+
* @param {string} root
|
|
60
|
+
* @param {string} flowName
|
|
61
|
+
* @returns {{ok:true, flowDir:string}|{ok:false, red:string}}
|
|
62
|
+
*/
|
|
63
|
+
function resolveFlowDir(root, flowName) {
|
|
64
|
+
const check = checkFlowName(flowName);
|
|
65
|
+
if (!check.ok) return refuse(check.red);
|
|
66
|
+
const flowDir = join(root, flowName);
|
|
67
|
+
if (existsSync(flowDir)) {
|
|
68
|
+
let realFlowDir;
|
|
69
|
+
let realRoot;
|
|
70
|
+
try {
|
|
71
|
+
realFlowDir = realpathSync(flowDir);
|
|
72
|
+
realRoot = realpathSync(root);
|
|
73
|
+
} catch (err) {
|
|
74
|
+
return refuse(`flow: could not resolve "${flowDir}" — ${err.message}`);
|
|
75
|
+
}
|
|
76
|
+
if (realFlowDir !== realRoot && !realFlowDir.startsWith(realRoot + sep)) {
|
|
77
|
+
return refuse(`flow: "${flowName}" is a symlink that resolves outside root (${realFlowDir}) — refused`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return { ok: true, flowDir };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Resolve `<root>/<flowName>/runs/<runId>` safely — `resolveFlowDir` then
|
|
85
|
+
* `resolveRunDir` (character allow-list plus a lexical-containment re-check,
|
|
86
|
+
* same posture `src/flow.js` already applies everywhere else a runId
|
|
87
|
+
* reaches a path). Neither check trusts the URL beyond what it verifies.
|
|
88
|
+
* @param {string} root
|
|
89
|
+
* @param {string} flowName
|
|
90
|
+
* @param {string} runId
|
|
91
|
+
* @returns {{ok:true, flowDir:string, runDir:string}|{ok:false, red:string}}
|
|
92
|
+
*/
|
|
93
|
+
function resolveRunPath(root, flowName, runId) {
|
|
94
|
+
const flow = resolveFlowDir(root, flowName);
|
|
95
|
+
if (!flow.ok) return flow;
|
|
96
|
+
const run = resolveRunDir(flow.flowDir, runId);
|
|
97
|
+
if (!run.ok) return run;
|
|
98
|
+
return { ok: true, flowDir: flow.flowDir, runDir: run.runDir };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* A consumed-answer marker exists for this run — `answerAsk`'s own write
|
|
103
|
+
* (`src/ask.js`) renames to `answer.<askId>.consumed.json` on accept, and
|
|
104
|
+
* `resumeRun` (`src/runner.js`) does the same when it consumes an in-place
|
|
105
|
+
* `answer.json`. A directory-naming-convention check, not a "book" with its
|
|
106
|
+
* own single-row shape, so it lives here rather than growing a one-off
|
|
107
|
+
* reader in either writer's module.
|
|
108
|
+
* @param {string} runDir
|
|
109
|
+
* @returns {boolean}
|
|
110
|
+
*/
|
|
111
|
+
function hasConsumedAnswer(runDir) {
|
|
112
|
+
if (!existsSync(runDir)) return false;
|
|
113
|
+
// F48 round 3: `readdirInside` (`src/flow.js`) skips a symlinked entry
|
|
114
|
+
// rather than reporting its name — a run dir cannot be made to show a
|
|
115
|
+
// consumed answer that isn't really there by planting a symlink named to
|
|
116
|
+
// match the pattern.
|
|
117
|
+
const names = readdirInside(runDir, '.');
|
|
118
|
+
return names.some((n) => /^answer\..*\.consumed\.json$/.test(n));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* The glyph + human-words label for one run — ported verbatim (in spirit,
|
|
123
|
+
* from real derivation, not a shortcut) from `poc/m4/panel-data.mjs`'s
|
|
124
|
+
* `computeGlyph`, the derivation the M4a POC proved against every real run
|
|
125
|
+
* on disk. Ladder wording (M4a scope item 4):
|
|
126
|
+
* - `[✓]` passed — a history row with `outcome:'complete'`.
|
|
127
|
+
* - `[✗]` failed — a history row with any other outcome (never `[?]`).
|
|
128
|
+
* - `[·]` waiting on you — parked (`ask.json` present), no consumed answer,
|
|
129
|
+
* NOT past its own `expiresAt`.
|
|
130
|
+
* - `[!]` ask expired, not resumed yet — parked, no consumed answer, but
|
|
131
|
+
* its own `expiresAt` is already past (hamr's 2026-09-27 browser-walk bug
|
|
132
|
+
* #3: the runs list/header glyph disagreed with the Inbox, which already
|
|
133
|
+
* reports `expired` correctly off the exact same `askJson.expiresAt` —
|
|
134
|
+
* `[!]` is not in the ladder's signed M4a vocabulary; picked here as an
|
|
135
|
+
* honest fourth state, distinct from every signed glyph, pending a
|
|
136
|
+
* ruling — see the report). Never `[·]` waiting (nobody can still answer
|
|
137
|
+
* it in time), never `[✗]` (the run itself never failed a check), never
|
|
138
|
+
* `[?]` (the books DO know what happened here).
|
|
139
|
+
* - `[·]` answered, not resumed yet — parked, a consumed answer exists, but
|
|
140
|
+
* no history row yet (resume hasn't finished) — always in words, never
|
|
141
|
+
* the same line as "waiting on you", never `[?]`.
|
|
142
|
+
* - `[?]` died / unknown — no history row, no open ask, no consumed answer:
|
|
143
|
+
* `resume.lock` carries no pid and nothing checks liveness (M4a's own
|
|
144
|
+
* open POC question), so a crashed resumer and a live one look the same
|
|
145
|
+
* on disk. Never guessed into `[✗]` or `[✓]`.
|
|
146
|
+
* @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean}} ctx
|
|
147
|
+
* @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[?]', label: string}}
|
|
148
|
+
*/
|
|
149
|
+
export function computeGlyph({
|
|
150
|
+
historyRow, askJson, consumedAnswerExists, hasStateJson,
|
|
151
|
+
}) {
|
|
152
|
+
if (historyRow) {
|
|
153
|
+
if (historyRow.outcome === 'complete') return { glyph: '[✓]', label: 'passed' };
|
|
154
|
+
return { glyph: '[✗]', label: `failed (${historyRow.outcome ?? 'unknown outcome'})` };
|
|
155
|
+
}
|
|
156
|
+
// No history row. A park never writes one, and a consumed answer file
|
|
157
|
+
// stays on disk until resume writes its own history row — "no history
|
|
158
|
+
// row" alone never means died.
|
|
159
|
+
if (askJson && !consumedAnswerExists) {
|
|
160
|
+
const expiresMs = typeof askJson.expiresAt === 'string' ? Date.parse(askJson.expiresAt) : NaN;
|
|
161
|
+
if (Number.isFinite(expiresMs) && Date.now() > expiresMs) {
|
|
162
|
+
return { glyph: '[!]', label: 'ask expired, not resumed yet' };
|
|
163
|
+
}
|
|
164
|
+
return { glyph: '[·]', label: 'waiting on you (parked, unanswered)' };
|
|
165
|
+
}
|
|
166
|
+
if (askJson && consumedAnswerExists) {
|
|
167
|
+
return { glyph: '[·]', label: 'answered, not resumed yet' };
|
|
168
|
+
}
|
|
169
|
+
if (hasStateJson && !askJson) {
|
|
170
|
+
return { glyph: '[?]', label: 'running or died: unknown (parked state with no open ask and no history row)' };
|
|
171
|
+
}
|
|
172
|
+
return { glyph: '[?]', label: 'running or died: unknown (resume.lock has no pid, no liveness check)' };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* "$X.XXXX" or, when the book itself says the number is a floor
|
|
177
|
+
* (`spendComplete:false`), "at least $X.XXXX" — never a bare total presented
|
|
178
|
+
* as complete when it isn't (negative scenario iv), and never `$0` standing
|
|
179
|
+
* in for a missing/unknown number (project rule).
|
|
180
|
+
* @param {number|null|undefined} spentUsd
|
|
181
|
+
* @param {boolean|undefined} spendComplete
|
|
182
|
+
* @returns {{ok:true, display:string}|{ok:false, why:string}}
|
|
183
|
+
*/
|
|
184
|
+
export function costDisplay(spentUsd, spendComplete) {
|
|
185
|
+
if (typeof spentUsd !== 'number') {
|
|
186
|
+
return { ok: false, why: 'spentUsd is not a number' };
|
|
187
|
+
}
|
|
188
|
+
if (spendComplete === false) {
|
|
189
|
+
return { ok: true, display: `at least $${spentUsd.toFixed(4)}` };
|
|
190
|
+
}
|
|
191
|
+
return { ok: true, display: `$${spentUsd.toFixed(4)}` };
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* A floor summed from whatever priced rows a run's own `spend.jsonl`
|
|
196
|
+
* already recorded — used ONLY when there is no history row yet (died or
|
|
197
|
+
* still parked) to show "at least $X" rather than nothing/zero. `null`
|
|
198
|
+
* (never `$0`) when zero rows are priced yet.
|
|
199
|
+
* @param {any[]} spendRows
|
|
200
|
+
* @returns {string|null}
|
|
201
|
+
*/
|
|
202
|
+
function spendFloorDisplay(spendRows) {
|
|
203
|
+
const priced = spendRows.filter((r) => typeof r.costUsd === 'number' && Number.isFinite(r.costUsd));
|
|
204
|
+
if (priced.length === 0) return null;
|
|
205
|
+
const sum = priced.reduce((acc, r) => acc + r.costUsd, 0);
|
|
206
|
+
return `at least $${sum.toFixed(4)}`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* The model this run's own book rows actually name — hamr's review #1/#7:
|
|
211
|
+
* no `declaration.json`/`signature.json` field records a model at all (the
|
|
212
|
+
* flow's steps carry primitives and a close class, never a model choice),
|
|
213
|
+
* so `audit.jsonl`'s own per-attempt `model` field (`src/books.js`'s
|
|
214
|
+
* `appendAudit` row shape) is the ONLY book that can answer "what model did
|
|
215
|
+
* this run use" — never invented, never defaulted to a catalogue/provider
|
|
216
|
+
* default the run may not have actually hit. Reads book order BACKWARDS and
|
|
217
|
+
* returns the LAST row that names a model (the most recent attempt's own
|
|
218
|
+
* choice), so a run that changed model slot mid-run (would show as a
|
|
219
|
+
* `modelMatch:"substituted"` row) still reports what actually ran last,
|
|
220
|
+
* never a stale first-attempt value. `null` (never a guess) when no row in
|
|
221
|
+
* this run ever named one (e.g. every step is `hitl`, no model step ran).
|
|
222
|
+
* No provider/API-kind field exists in ANY book (`src/provider.js`'s
|
|
223
|
+
* `PROVIDER_SLOTS` maps a slot name to a model, but nothing writes which
|
|
224
|
+
* slot served a given run back to `audit.jsonl`/`spend.jsonl`) — provider is
|
|
225
|
+
* never shown alongside it (hamr's own instruction: "if the provider isn't
|
|
226
|
+
* in any book, show model only").
|
|
227
|
+
* @param {any[]} auditRows
|
|
228
|
+
* @returns {string|null}
|
|
229
|
+
*/
|
|
230
|
+
export function deriveRunModel(auditRows) {
|
|
231
|
+
for (let i = auditRows.length - 1; i >= 0; i -= 1) {
|
|
232
|
+
const m = auditRows[i]?.model;
|
|
233
|
+
if (typeof m === 'string' && m.length > 0) return m;
|
|
234
|
+
}
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* The Audit tab's "Action" column (hamr's review #6, tightened by hamr's
|
|
240
|
+
* 2026-09-27 live check): exactly three words, derived STRICTLY from a
|
|
241
|
+
* row's own fields — never the step name/id, never a model name, never
|
|
242
|
+
* "unknown action":
|
|
243
|
+
* - "model call" — a row with a non-empty `model` field (the model itself
|
|
244
|
+
* still shows in the Cost/Verdict area elsewhere; this column names only
|
|
245
|
+
* the KIND of action).
|
|
246
|
+
* - "human" — an ask-slot row: `src/runner.js`'s `runAskSlot` is the ONLY
|
|
247
|
+
* place that ever passes a third argument (`unjudgedCount`) into
|
|
248
|
+
* `recordAudit`, so `Object.prototype.hasOwnProperty.call(row,
|
|
249
|
+
* 'unjudgedCount')` is true for exactly that step's own rows (paused,
|
|
250
|
+
* and the human's own accept/reject/rerun/refused answers) and false for
|
|
251
|
+
* every other row shape in the book — a real, always-present marker
|
|
252
|
+
* (`unjudgedCount` is a number, 0 included, never omitted on an ask row),
|
|
253
|
+
* never the step's close class (a NON-ask hitl step, e.g. a plain write
|
|
254
|
+
* step, is ALSO `class:'hitl'` — that was the exact bug this replaces:
|
|
255
|
+
* class alone can't tell "the ask" apart from "any other hitl step").
|
|
256
|
+
* - "no model call" — everything else: a mechanical green/not-done/red
|
|
257
|
+
* close, a cap-halt, a send confirmation, a non-ask hitl pass-through
|
|
258
|
+
* (e.g. a write step) — no model ran and no human answered THIS row.
|
|
259
|
+
* @param {any} row one `audit.jsonl` row
|
|
260
|
+
* @returns {'model call'|'human'|'no model call'}
|
|
261
|
+
*/
|
|
262
|
+
export function deriveAuditAction(row) {
|
|
263
|
+
if (row && Object.prototype.hasOwnProperty.call(row, 'unjudgedCount')) return 'human';
|
|
264
|
+
if (typeof row?.model === 'string' && row.model.length > 0) return 'model call';
|
|
265
|
+
return 'no model call';
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The Audit tab's Cost cell token phrase (hamr's 2026-09-27 review item c):
|
|
270
|
+
* a per-ROW token total, read through `auditRowTokens` (`src/books.js`) so
|
|
271
|
+
* this module never re-derives "was this row written before M4a-2" itself.
|
|
272
|
+
* Three honest outcomes, never folded into one another:
|
|
273
|
+
* - `{kind:'total', total}` — a real (post-M4a-2) model-call row: `total`
|
|
274
|
+
* sums ALL three fields the row's own `tokens` object carries
|
|
275
|
+
* (`inputTokens + outputTokens + cacheReadTokens`) — every token this
|
|
276
|
+
* row's call actually touched, cache-read included (labelled plainly as
|
|
277
|
+
* "N tokens", never split out here; a cache-read token is still a token
|
|
278
|
+
* the call processed, so folding it into the total is the honest sum,
|
|
279
|
+
* not a hidden discount).
|
|
280
|
+
* - `{kind:'not-recorded'}` — a row written before Amendment M4a-2 (no
|
|
281
|
+
* `tokens` key at all) — shown as "tokens not recorded", never a 0 or a
|
|
282
|
+
* blank.
|
|
283
|
+
* - `{kind:'no-model'}` — a post-M4a-2 row that genuinely carries no model
|
|
284
|
+
* call (`tokens:null`, `model:null` — an ask/hitl row) — the tokens
|
|
285
|
+
* phrase is omitted entirely rather than shown as "0 tokens" or "not
|
|
286
|
+
* recorded" (there was never anything to record).
|
|
287
|
+
* @param {any} row one `audit.jsonl` row
|
|
288
|
+
* @returns {{kind:'total', total:number}|{kind:'not-recorded'}|{kind:'no-model'}}
|
|
289
|
+
*/
|
|
290
|
+
export function deriveAuditTokensDisplay(row) {
|
|
291
|
+
const result = auditRowTokens(row);
|
|
292
|
+
if (result.tokens === null) {
|
|
293
|
+
return result.why ? { kind: 'not-recorded' } : { kind: 'no-model' };
|
|
294
|
+
}
|
|
295
|
+
const { inputTokens, outputTokens, cacheReadTokens } = result.tokens;
|
|
296
|
+
return { kind: 'total', total: inputTokens + outputTokens + cacheReadTokens };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* hamr's request (Amendment M4a-3): the Audit tab's Action cell gets a
|
|
301
|
+
* one-line tool tally appended for a MODEL-call row whose own `tools` was
|
|
302
|
+
* actually recorded (Amendment M4a-3) — `", read 3, write 1"` — read
|
|
303
|
+
* straight through `auditRowTools` (`src/books.js`), never re-derived. Three
|
|
304
|
+
* honest outcomes, matching `deriveAuditTokensDisplay`'s own shape exactly:
|
|
305
|
+
* `null` for a non-model row (nothing to append — a human/no-model-call row
|
|
306
|
+
* never claims a tool tally), `null` for a pre-M4a-3 model row (`why` set —
|
|
307
|
+
* appending nothing beats guessing a tally that was never recorded), and a
|
|
308
|
+
* real phrase, sorted by count desc then name, for a model row that DOES
|
|
309
|
+
* carry `tools` (including `{}` — zero tool calls that round — which still
|
|
310
|
+
* returns `null`: there is nothing to list, so nothing is appended).
|
|
311
|
+
* @param {any} row one `audit.jsonl` row
|
|
312
|
+
* @returns {string|null}
|
|
313
|
+
*/
|
|
314
|
+
export function deriveAuditToolsPhrase(row) {
|
|
315
|
+
if (!(typeof row?.model === 'string' && row.model.length > 0)) return null;
|
|
316
|
+
const { tools, why } = auditRowTools(row);
|
|
317
|
+
if (why || !tools) return null;
|
|
318
|
+
const entries = Object.entries(tools).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
|
|
319
|
+
if (entries.length === 0) return null;
|
|
320
|
+
return entries.map(([name, count]) => `${name} ${count}`).join(', ');
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Amendment M4a-3's own step-level tool tally, the same honesty rules
|
|
325
|
+
* `deriveAuditGroups` already applies to `tokensTotal`: sums `auditRowTools`
|
|
326
|
+
* over every row in one step's own group. `toolsTotal` is `null` (never a
|
|
327
|
+
* guessed `{}`) when the step made no model call at all (nothing to sum) OR
|
|
328
|
+
* when ANY model-call row in the step predates Amendment M4a-3 (`why` set on
|
|
329
|
+
* that row) — a partial sum is never shown as if it were the whole step's
|
|
330
|
+
* total, mirroring the tokens rule exactly. `ungranted` unions every row's
|
|
331
|
+
* own `ungranted` list (deduped, insertion order) regardless of whether the
|
|
332
|
+
* total itself could be summed — an ungranted call is never hidden just
|
|
333
|
+
* because an earlier row in the same step predates M4a-3.
|
|
334
|
+
* @param {any[]} rows one step's own audit rows (book order)
|
|
335
|
+
* @returns {{toolsTotal: Record<string, number>|null, toolsWhy: string|null, ungranted: string[]}}
|
|
336
|
+
*/
|
|
337
|
+
function summarizeStepTools(rows) {
|
|
338
|
+
let sawModelRow = false;
|
|
339
|
+
let anyNotRecorded = false;
|
|
340
|
+
const totals = {};
|
|
341
|
+
const ungrantedSeen = [];
|
|
342
|
+
const ungrantedSet = new Set();
|
|
343
|
+
for (const r of rows) {
|
|
344
|
+
const hasModel = typeof r.model === 'string' && r.model.length > 0;
|
|
345
|
+
const { tools, ungranted, why } = auditRowTools(r);
|
|
346
|
+
for (const u of ungranted) {
|
|
347
|
+
if (!ungrantedSet.has(u)) { ungrantedSet.add(u); ungrantedSeen.push(u); }
|
|
348
|
+
}
|
|
349
|
+
if (!hasModel) continue;
|
|
350
|
+
sawModelRow = true;
|
|
351
|
+
if (why) { anyNotRecorded = true; continue; }
|
|
352
|
+
if (tools) {
|
|
353
|
+
for (const [name, count] of Object.entries(tools)) totals[name] = (totals[name] ?? 0) + count;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
if (!sawModelRow) return { toolsTotal: null, toolsWhy: null, ungranted: ungrantedSeen };
|
|
357
|
+
if (anyNotRecorded) {
|
|
358
|
+
return { toolsTotal: null, toolsWhy: 'not recorded (before M4a-3)', ungranted: ungrantedSeen };
|
|
359
|
+
}
|
|
360
|
+
const sorted = Object.entries(totals).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
|
|
361
|
+
return { toolsTotal: Object.fromEntries(sorted), toolsWhy: null, ungranted: ungrantedSeen };
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* The Audit tab's new Time column (hamr's 2026-09-27 review item d): this
|
|
366
|
+
* row's own `why` when `at` predates Amendment M4a-2, else `null` (the row
|
|
367
|
+
* DOES carry a real `at` — the client formats it with `readableDateTime`,
|
|
368
|
+
* the same local-time formatter every other timestamp on this page already
|
|
369
|
+
* uses; formatting to the viewer's own locale belongs in the browser, not
|
|
370
|
+
* here). Read through `auditRowAt` (`src/books.js`) — never re-derived.
|
|
371
|
+
* @param {any} row one `audit.jsonl` row
|
|
372
|
+
* @returns {string|null}
|
|
373
|
+
*/
|
|
374
|
+
export function deriveAuditAtWhy(row) {
|
|
375
|
+
return auditRowAt(row).why ?? null;
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* hamr's 2026-09-27 exit-check review #2: the Audit tab's Blocked filter —
|
|
380
|
+
* ONE server-side function naming exactly which verdicts count as "did not
|
|
381
|
+
* pass", derived strictly from a row's own `verdict` string (never a second,
|
|
382
|
+
* client-side guess). Blocked: `not-done`, `red` (a mechanical close miss OR
|
|
383
|
+
* a human's own reject on a hitl step — both are "this attempt did not
|
|
384
|
+
* pass"), `refused` (a blank reject/rerun reason), `ask-timeout` and
|
|
385
|
+
* `ask-expired` (the human never answered in time), `cap-halt`,
|
|
386
|
+
* `provider-red`, `pricing-red`, `close-casualty` (every other halt shape
|
|
387
|
+
* `src/runner.js` records). NOT blocked: `green`/`hitl` (passed), `paused`
|
|
388
|
+
* (still open — waiting, not yet failed), `stale-answer-ignored` (a book
|
|
389
|
+
* hygiene note about a late answer, not an attempt outcome).
|
|
390
|
+
* @param {string|null|undefined} verdict
|
|
391
|
+
* @returns {boolean}
|
|
392
|
+
*/
|
|
393
|
+
const BLOCKED_VERDICTS = new Set([
|
|
394
|
+
'not-done', 'red', 'refused', 'ask-timeout', 'ask-expired', 'cap-halt', 'provider-red', 'pricing-red', 'close-casualty',
|
|
395
|
+
]);
|
|
396
|
+
export function isBlockedVerdict(verdict) {
|
|
397
|
+
return typeof verdict === 'string' && BLOCKED_VERDICTS.has(verdict);
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* hamr's 2026-09-27 exit-check review #1: one mark per TRY (never per raw
|
|
402
|
+
* audit row — a `hitl`-classed ask step's `paused` row and its own
|
|
403
|
+
* resolution row are the SAME try, the same pairing `computeTryCount`
|
|
404
|
+
* already applies) for the Audit tab's grouped-by-step header. `✓` passed
|
|
405
|
+
* (`green`/`hitl`), `✗` failed/rejected/blocked (everything
|
|
406
|
+
* `isBlockedVerdict` names, plus any other non-passing verdict), `·` still
|
|
407
|
+
* open (`paused`/`refused`/`ask-timeout`/`ask-expired` — waiting, not yet
|
|
408
|
+
* resolved either way). A `refused` (blank-reason) row is its own re-ask,
|
|
409
|
+
* not a resolution, so it reads as `·` like `paused` — the try it belongs to
|
|
410
|
+
* is still open.
|
|
411
|
+
* @param {string|null|undefined} verdict
|
|
412
|
+
* @param {string|null|undefined} closeClass
|
|
413
|
+
* @returns {'✓'|'✗'|'·'}
|
|
414
|
+
*/
|
|
415
|
+
function markForVerdict(verdict, closeClass) {
|
|
416
|
+
if (closeClass === 'hitl' && verdict === 'red') return '✗'; // the human's own reject
|
|
417
|
+
if (verdict === 'green' || verdict === 'hitl') return '✓';
|
|
418
|
+
if (verdict === 'paused' || verdict === 'refused' || verdict === 'ask-timeout' || verdict === 'ask-expired') return '·';
|
|
419
|
+
return '✗';
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* One mark per try, in try order — mirrors `computeTryCount`'s own pairing
|
|
424
|
+
* exactly (a `hitl` step's `paused` row plus its next resolving row is ONE
|
|
425
|
+
* try; every other step's own row is ONE try each) so a group header's
|
|
426
|
+
* `tryMarks.length` always equals its own `tryCount`. A `paused` row with no
|
|
427
|
+
* resolution yet in this run's own book order keeps its `·` mark (still
|
|
428
|
+
* open, not resolved).
|
|
429
|
+
* @param {string|null} closeClass
|
|
430
|
+
* @param {Array<{verdict:string}>} rows one step's own audit rows, book order
|
|
431
|
+
* @returns {Array<'✓'|'✗'|'·'>}
|
|
432
|
+
*/
|
|
433
|
+
export function deriveStepTryMarks(closeClass, rows) {
|
|
434
|
+
if (!rows || !rows.length) return [];
|
|
435
|
+
if (closeClass === 'hitl') {
|
|
436
|
+
const pausedIdxs = [];
|
|
437
|
+
rows.forEach((r, i) => { if (r.verdict === 'paused') pausedIdxs.push(i); });
|
|
438
|
+
if (pausedIdxs.length === 0) {
|
|
439
|
+
// No paused row at all is not a shape this step produces in practice
|
|
440
|
+
// (guarded the same way `computeTryCount` already is) — one mark per
|
|
441
|
+
// row rather than hiding that a try happened.
|
|
442
|
+
return rows.map((r) => markForVerdict(r.verdict, closeClass));
|
|
443
|
+
}
|
|
444
|
+
return pausedIdxs.map((idx, i) => {
|
|
445
|
+
// The resolving row is the LAST row before the next `paused` boundary
|
|
446
|
+
// (or the end of the run), never the first non-paused row after this
|
|
447
|
+
// one: a blank-reason `refused` re-ask (`src/runner.js`'s redo loop
|
|
448
|
+
// never writes a new `paused` row for it — it just re-asks in place)
|
|
449
|
+
// can sit BETWEEN a `paused` row and its real resolution, and taking
|
|
450
|
+
// the first non-paused row would wrongly read that in-progress re-ask
|
|
451
|
+
// as the try's own outcome.
|
|
452
|
+
const nextPausedIdx = pausedIdxs[i + 1] ?? rows.length;
|
|
453
|
+
const lastIdx = nextPausedIdx - 1;
|
|
454
|
+
if (lastIdx === idx) return '·'; // still paused, no resolution row yet in this run's book
|
|
455
|
+
return markForVerdict(rows[lastIdx].verdict, closeClass);
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
return rows.map((r) => markForVerdict(r.verdict, closeClass));
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* A step group's own state word for the Audit tab's collapsed header —
|
|
463
|
+
* the SAME rule `src/panel/index.html`'s client-side `stepBoxState` already
|
|
464
|
+
* applies to the Run tab's map/cards (ported here so the Audit header can
|
|
465
|
+
* be computed server-side too, off the SAME last-row-wins logic): `waiting`
|
|
466
|
+
* (the run is currently parked on this step — its last attempt's verdict is
|
|
467
|
+
* `paused`/`refused`), `done` (the last attempt passed — `green`/`hitl`),
|
|
468
|
+
* `stopped` (the last attempt failed for any other reason). A group only
|
|
469
|
+
* ever exists for a step with at least one row, so `pending` never appears
|
|
470
|
+
* here (unlike the Run tab's map, which also covers never-attempted steps).
|
|
471
|
+
* @param {Array<{verdict:string}>} rows one step's own audit rows, book order
|
|
472
|
+
* @returns {'done'|'waiting'|'stopped'}
|
|
473
|
+
*/
|
|
474
|
+
export function deriveStepGroupState(rows) {
|
|
475
|
+
const last = rows[rows.length - 1];
|
|
476
|
+
if (last.verdict === 'paused' || last.verdict === 'refused') return 'waiting';
|
|
477
|
+
return (last.verdict === 'green' || last.verdict === 'hitl') ? 'done' : 'stopped';
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/**
|
|
481
|
+
* hamr's 2026-09-27 exit-check review #1: the Audit tab's grouped-by-step
|
|
482
|
+
* header pieces, computed HERE (server-side) so `src/panel/index.html` only
|
|
483
|
+
* ever renders them, never re-derives them. One entry per step, first-seen
|
|
484
|
+
* order preserved (never re-sorted): `step` (the emits id, the header IS the
|
|
485
|
+
* step's own name — no separate Step column in Grouped view), `state`
|
|
486
|
+
* (`deriveStepGroupState`), `closeClass`, `timeMs` (this step's own attempts'
|
|
487
|
+
* `wallMs` summed — "total time from wallMs", never a guess), `cost`/
|
|
488
|
+
* `costWhy` (a bare `$X` sum when every priced row is complete, `"at least
|
|
489
|
+
* $X"` when any priced row in this step is a floor, `null`+why when no row
|
|
490
|
+
* in this step has ever priced), `tokensTotal` (the sum of every row's own
|
|
491
|
+
* token total, ONLY when every row in the step either carries real
|
|
492
|
+
* (post-M4a-2) tokens or genuinely made no model call — one row missing
|
|
493
|
+
* tokens (a pre-M4a-2 row) means the WHOLE step's total is withheld, never a
|
|
494
|
+
* partial sum shown as complete; `null` also when the step made no model
|
|
495
|
+
* call at all, nothing to sum), `toolsTotal`/`toolsWhy`/`ungranted`
|
|
496
|
+
* (Amendment M4a-3, `summarizeStepTools` — the same "no partial sum" honesty
|
|
497
|
+
* rule as `tokensTotal`, plus the deduped union of every row's own
|
|
498
|
+
* `ungranted` calls), `tryCount`/`tryMarks` (`deriveStepTryMarks`),
|
|
499
|
+
* `rows` (this step's own enriched audit rows, for the group's own table —
|
|
500
|
+
* never a second, separately-filtered copy on the client).
|
|
501
|
+
* @param {any[]} enrichedRows `getRunAudit`'s own rows, already carrying
|
|
502
|
+
* `action`/`tokensDisplay`/`atWhy`/`blocked` (this function never
|
|
503
|
+
* re-derives any of those, only groups and sums them)
|
|
504
|
+
* @returns {any[]}
|
|
505
|
+
*/
|
|
506
|
+
export function deriveAuditGroups(enrichedRows) {
|
|
507
|
+
const order = [];
|
|
508
|
+
const byStep = {};
|
|
509
|
+
for (const r of enrichedRows) {
|
|
510
|
+
if (!Object.prototype.hasOwnProperty.call(byStep, r.step)) { byStep[r.step] = []; order.push(r.step); }
|
|
511
|
+
byStep[r.step].push(r);
|
|
512
|
+
}
|
|
513
|
+
return order.map((step) => {
|
|
514
|
+
const rows = byStep[step];
|
|
515
|
+
const closeClass = rows[0].class ?? null;
|
|
516
|
+
const timeMs = rows.reduce((acc, r) => acc + (typeof r.wallMs === 'number' ? r.wallMs : 0), 0);
|
|
517
|
+
|
|
518
|
+
const priced = rows.filter((r) => typeof r.usd === 'number' && Number.isFinite(r.usd));
|
|
519
|
+
let cost = null;
|
|
520
|
+
let costWhy = null;
|
|
521
|
+
if (priced.length === 0) {
|
|
522
|
+
costWhy = 'no row in this step has a known cost yet';
|
|
523
|
+
} else {
|
|
524
|
+
const sum = priced.reduce((acc, r) => acc + r.usd, 0);
|
|
525
|
+
const partial = priced.some((r) => r.spendComplete === false);
|
|
526
|
+
const cd = costDisplay(sum, partial ? false : true);
|
|
527
|
+
cost = cd.ok ? cd.display : null;
|
|
528
|
+
if (!cd.ok) costWhy = cd.why;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
let anyNotRecorded = false;
|
|
532
|
+
let anyTotal = false;
|
|
533
|
+
let tokensTotal = 0;
|
|
534
|
+
for (const r of rows) {
|
|
535
|
+
const td = r.tokensDisplay;
|
|
536
|
+
if (td && td.kind === 'not-recorded') anyNotRecorded = true;
|
|
537
|
+
else if (td && td.kind === 'total') { anyTotal = true; tokensTotal += td.total; }
|
|
538
|
+
}
|
|
539
|
+
const tokensTotalValue = (anyNotRecorded || !anyTotal) ? null : tokensTotal;
|
|
540
|
+
|
|
541
|
+
const tryMarks = deriveStepTryMarks(closeClass, rows);
|
|
542
|
+
const { toolsTotal, toolsWhy, ungranted } = summarizeStepTools(rows);
|
|
543
|
+
return {
|
|
544
|
+
step,
|
|
545
|
+
state: deriveStepGroupState(rows),
|
|
546
|
+
closeClass,
|
|
547
|
+
timeMs,
|
|
548
|
+
cost,
|
|
549
|
+
costWhy,
|
|
550
|
+
tokensTotal: tokensTotalValue,
|
|
551
|
+
toolsTotal,
|
|
552
|
+
toolsWhy,
|
|
553
|
+
ungranted,
|
|
554
|
+
tryCount: tryMarks.length,
|
|
555
|
+
tryMarks,
|
|
556
|
+
rows,
|
|
557
|
+
};
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/**
|
|
562
|
+
* Run-level totals from `spend.jsonl` (hamr's review #1): rounds, input/
|
|
563
|
+
* output/cache-read tokens — shown ONLY as a run-wide sum, never attributed
|
|
564
|
+
* to a step (a spend row carries no `step` field at all — `src/model-step.js`
|
|
565
|
+
* appends it before any step identity is threaded through, so per-step
|
|
566
|
+
* attribution would be invented, not read). Honest about partial data: a
|
|
567
|
+
* field this run's rows never populated (e.g. no row ever carried
|
|
568
|
+
* `tokens.cacheReadTokens`) is `null` with its own `*Why`, never folded into
|
|
569
|
+
* a 0. `null` `rows`/`empty:true` (with a why) when spend.jsonl has no rows
|
|
570
|
+
* at all yet.
|
|
571
|
+
* @param {any[]} spendRows
|
|
572
|
+
* @returns {{empty:true, why:string}|{empty:false, rounds:number, tokensIn:number|null, tokensInWhy:string|null, tokensOut:number|null, tokensOutWhy:string|null, cacheReadTokens:number|null, cacheReadTokensWhy:string|null}}
|
|
573
|
+
*/
|
|
574
|
+
export function summarizeSpendRows(spendRows) {
|
|
575
|
+
if (!Array.isArray(spendRows) || spendRows.length === 0) {
|
|
576
|
+
return { empty: true, why: 'spend.jsonl has no rows yet (no model round has been priced)' };
|
|
577
|
+
}
|
|
578
|
+
const rounds = spendRows.reduce((acc, r) => acc + (typeof r.rounds === 'number' ? r.rounds : 0), 0);
|
|
579
|
+
const sumTokenField = (field) => {
|
|
580
|
+
let any = false;
|
|
581
|
+
let total = 0;
|
|
582
|
+
for (const r of spendRows) {
|
|
583
|
+
const v = r?.tokens?.[field];
|
|
584
|
+
if (typeof v === 'number' && Number.isFinite(v)) { any = true; total += v; }
|
|
585
|
+
}
|
|
586
|
+
return any ? total : null;
|
|
587
|
+
};
|
|
588
|
+
const tokensIn = sumTokenField('inputTokens');
|
|
589
|
+
const tokensOut = sumTokenField('outputTokens');
|
|
590
|
+
const cacheReadTokens = sumTokenField('cacheReadTokens');
|
|
591
|
+
return {
|
|
592
|
+
empty: false,
|
|
593
|
+
rounds,
|
|
594
|
+
tokensIn,
|
|
595
|
+
tokensInWhy: tokensIn === null ? 'no spend.jsonl row recorded input tokens' : null,
|
|
596
|
+
tokensOut,
|
|
597
|
+
tokensOutWhy: tokensOut === null ? 'no spend.jsonl row recorded output tokens' : null,
|
|
598
|
+
cacheReadTokens,
|
|
599
|
+
cacheReadTokensWhy: cacheReadTokens === null ? 'no spend.jsonl row recorded cache-read tokens' : null,
|
|
600
|
+
};
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Read every book fwdloop can hold for one run, once. The shared context
|
|
605
|
+
* every deriver below (and the POC before it) builds its fields from.
|
|
606
|
+
* @param {string} root
|
|
607
|
+
* @param {string} flowDir
|
|
608
|
+
* @param {string} runDir
|
|
609
|
+
* @param {string} flowName
|
|
610
|
+
* @param {string} runId
|
|
611
|
+
* @param {any} catalogue
|
|
612
|
+
* @returns {any}
|
|
613
|
+
*/
|
|
614
|
+
function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue) {
|
|
615
|
+
const flowRead = readFlow({ root, name: flowName, catalogue });
|
|
616
|
+
const historyRows = readHistory(flowDir);
|
|
617
|
+
const historyRow = historyRows.find((r) => r && r.runId === runId) ?? null;
|
|
618
|
+
const auditRows = readAudit(runDir);
|
|
619
|
+
const spendRows = readSpendRows(join(runDir, 'spend.jsonl'));
|
|
620
|
+
const logJson = readLog(runDir);
|
|
621
|
+
const askJson = readAsk(runDir);
|
|
622
|
+
const stateJson = readRunState(runDir);
|
|
623
|
+
const consumedAnswerExists = hasConsumedAnswer(runDir);
|
|
624
|
+
|
|
625
|
+
return {
|
|
626
|
+
flowName,
|
|
627
|
+
runId,
|
|
628
|
+
flowDir,
|
|
629
|
+
runDir,
|
|
630
|
+
flowRead,
|
|
631
|
+
historyRow,
|
|
632
|
+
auditRows,
|
|
633
|
+
spendRows,
|
|
634
|
+
logJson,
|
|
635
|
+
askJson,
|
|
636
|
+
stateJson,
|
|
637
|
+
consumedAnswerExists,
|
|
638
|
+
hasStateJson: stateJson !== null,
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* `GET /api/runs` — every flow under `root`, every run under each flow
|
|
644
|
+
* (M4a scope item 2). A flow with zero runs still gets one row (`runId:
|
|
645
|
+
* null`, an explicit `why`) — no flow is silently missing from the list.
|
|
646
|
+
* Newest-first by history `at` where known; a row with no history row (died
|
|
647
|
+
* or still parked) sorts after every row that has one, in flow/run order
|
|
648
|
+
* (a real ordering, never `Date.now()` guessed in for a missing `at`).
|
|
649
|
+
* @param {{root: string, catalogue: any}} opts
|
|
650
|
+
* @returns {any[]}
|
|
651
|
+
*/
|
|
652
|
+
export function listRuns({ root, catalogue }) {
|
|
653
|
+
const rows = [];
|
|
654
|
+
for (const flowName of listFlowNames(root)) {
|
|
655
|
+
const flowDir = join(root, flowName);
|
|
656
|
+
const runIds = listRunIds(flowDir);
|
|
657
|
+
if (runIds.length === 0) {
|
|
658
|
+
rows.push({
|
|
659
|
+
flow: flowName, runId: null, glyph: null, label: null, spend: null, at: null,
|
|
660
|
+
why: 'this flow has no runs yet',
|
|
661
|
+
});
|
|
662
|
+
continue;
|
|
663
|
+
}
|
|
664
|
+
for (const runId of runIds) {
|
|
665
|
+
const run = resolveRunPath(root, flowName, runId);
|
|
666
|
+
if (!run.ok) {
|
|
667
|
+
rows.push({
|
|
668
|
+
flow: flowName, runId, glyph: null, label: null, spend: null, at: null, why: run.red,
|
|
669
|
+
});
|
|
670
|
+
continue;
|
|
671
|
+
}
|
|
672
|
+
const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue);
|
|
673
|
+
const { glyph, label } = computeGlyph(ctx);
|
|
674
|
+
let spend;
|
|
675
|
+
if (ctx.historyRow) {
|
|
676
|
+
const cd = costDisplay(ctx.historyRow.spentUsd, ctx.historyRow.spendComplete);
|
|
677
|
+
spend = cd.ok ? cd.display : null;
|
|
678
|
+
} else {
|
|
679
|
+
spend = spendFloorDisplay(ctx.spendRows);
|
|
680
|
+
}
|
|
681
|
+
// browser re-walk bug #4: a parked run's ask.json holds a real,
|
|
682
|
+
// book-held timestamp (`askedAt`) — a run with an open ask is never
|
|
683
|
+
// "unknown", even with no history row yet. `atWhy`'s generic "no
|
|
684
|
+
// history row" text is reserved for the case that's ACTUALLY true of
|
|
685
|
+
// it: no history row AND no ask either (e.g. died before ever
|
|
686
|
+
// parking) — never rendered when the books do hold a date.
|
|
687
|
+
const askedAt = (!ctx.historyRow && ctx.askJson && typeof ctx.askJson.askedAt === 'string')
|
|
688
|
+
? ctx.askJson.askedAt
|
|
689
|
+
: null;
|
|
690
|
+
rows.push({
|
|
691
|
+
flow: flowName,
|
|
692
|
+
runId,
|
|
693
|
+
glyph,
|
|
694
|
+
label,
|
|
695
|
+
spend,
|
|
696
|
+
spendWhy: (!ctx.historyRow && spend === null) ? 'no history row yet and no priced spend.jsonl rows — nothing to floor' : null,
|
|
697
|
+
at: ctx.historyRow ? ctx.historyRow.at : null,
|
|
698
|
+
askedAt,
|
|
699
|
+
atWhy: (ctx.historyRow || askedAt) ? null : 'no history row yet (parked or died before one was written)',
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
// Newest first by `at` where present; rows with no `at` keep flow/run
|
|
704
|
+
// order (already alphabetical from listFlowNames/listRunIds) at the end.
|
|
705
|
+
return rows
|
|
706
|
+
.map((row, index) => ({ row, index }))
|
|
707
|
+
.sort((a, b) => {
|
|
708
|
+
const am = typeof a.row.at === 'string' ? Date.parse(a.row.at) : NaN;
|
|
709
|
+
const bm = typeof b.row.at === 'string' ? Date.parse(b.row.at) : NaN;
|
|
710
|
+
const aKnown = Number.isFinite(am);
|
|
711
|
+
const bKnown = Number.isFinite(bm);
|
|
712
|
+
if (aKnown && bKnown) return bm - am;
|
|
713
|
+
if (aKnown !== bKnown) return aKnown ? -1 : 1;
|
|
714
|
+
return a.index - b.index;
|
|
715
|
+
})
|
|
716
|
+
.map(({ row }) => row);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* hamr's 2026-09-27 step-card review: the ONE place raw `audit.jsonl` rows
|
|
721
|
+
* get their server-derived fields (`action`/`tokensDisplay`/`atWhy`/
|
|
722
|
+
* `blocked`) added — called by BOTH `getRunAudit` (the Audit tab) and
|
|
723
|
+
* `getRunDetail` (the Run tab's step cards), off the SAME raw rows, so
|
|
724
|
+
* `deriveAuditGroups` run on this output always produces identical numbers
|
|
725
|
+
* for both tabs. Never mutates `rawRows`.
|
|
726
|
+
* @param {any[]} rawRows `readAudit`'s own rows for one run
|
|
727
|
+
* @returns {any[]}
|
|
728
|
+
*/
|
|
729
|
+
function enrichAuditRows(rawRows) {
|
|
730
|
+
return rawRows.map((row) => ({
|
|
731
|
+
...row,
|
|
732
|
+
action: deriveAuditAction(row),
|
|
733
|
+
tokensDisplay: deriveAuditTokensDisplay(row),
|
|
734
|
+
toolsPhrase: deriveAuditToolsPhrase(row),
|
|
735
|
+
atWhy: deriveAuditAtWhy(row),
|
|
736
|
+
blocked: isBlockedVerdict(row.verdict),
|
|
737
|
+
}));
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
/**
|
|
741
|
+
* "try N" (map node / step-card badge) counts different things for
|
|
742
|
+
* different close classes, and must never just be `attempts.length` (browser
|
|
743
|
+
* re-walk bug #2): an ask (`hitl`-classed) step's audit rows are
|
|
744
|
+
* paused/answer PAIRS — a `paused` row starts one ask shown to the human,
|
|
745
|
+
* and its very next resolution row (the reject or the accept) is that SAME
|
|
746
|
+
* try, never a second one. So a paused, reject, paused, accept shape (4
|
|
747
|
+
* rows) is 2 tries, not 4. A model-classed step has no pause/answer
|
|
748
|
+
* pairing at all — each row IS one model attempt, so try N stays
|
|
749
|
+
* `list.length` there, unchanged from before this fix.
|
|
750
|
+
* @param {string|null} closeClass
|
|
751
|
+
* @param {Array<{verdict:string}>} list
|
|
752
|
+
* @returns {number}
|
|
753
|
+
*/
|
|
754
|
+
function computeTryCount(closeClass, list) {
|
|
755
|
+
if (!list || !list.length) return 0;
|
|
756
|
+
if (closeClass === 'hitl') {
|
|
757
|
+
const pausedCount = list.filter((a) => a.verdict === 'paused').length;
|
|
758
|
+
// No paused row at all is not a shape this step ever produces in
|
|
759
|
+
// practice, but falls back to the row count rather than 0 — a missing
|
|
760
|
+
// pause is never grounds to hide that a try happened.
|
|
761
|
+
return pausedCount > 0 ? pausedCount : list.length;
|
|
762
|
+
}
|
|
763
|
+
return list.length;
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/**
|
|
767
|
+
* `GET /api/runs/:flow/:runId` — the Run tab (M4a scope item 2): the step
|
|
768
|
+
* map from `declaration.steps`, step cards -> attempts from `audit.jsonl`
|
|
769
|
+
* (verdict, gap, cost, model, strike), and what the model wrote from
|
|
770
|
+
* `log.json`. `null` when the flow/runId doesn't resolve to a real run
|
|
771
|
+
* directory at all (caller renders 404); a `red` field names why a
|
|
772
|
+
* sub-derivation couldn't fill (never invented).
|
|
773
|
+
* @param {{root: string, flow: string, runId: string, catalogue: any}} opts
|
|
774
|
+
* @returns {any|null}
|
|
775
|
+
*/
|
|
776
|
+
export function getRunDetail({
|
|
777
|
+
root, flow, runId, catalogue,
|
|
778
|
+
}) {
|
|
779
|
+
const run = resolveRunPath(root, flow, runId);
|
|
780
|
+
if (!run.ok) return null;
|
|
781
|
+
if (!existsSync(run.runDir)) return null;
|
|
782
|
+
|
|
783
|
+
const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue);
|
|
784
|
+
const { glyph, label } = computeGlyph(ctx);
|
|
785
|
+
|
|
786
|
+
// hamr's 2026-09-27 step-card review: the Run tab's step cards reuse the
|
|
787
|
+
// EXACT SAME per-step group numbers (timeMs/cost/tokensTotal/tryMarks/
|
|
788
|
+
// state) the Audit tab's own group headers show — computed here off the
|
|
789
|
+
// SAME enriched rows `getRunAudit` builds (via the shared
|
|
790
|
+
// `enrichAuditRows`/`deriveAuditGroups` pair), never a second, separately
|
|
791
|
+
// summed copy. A step with no audit rows at all (never attempted) has no
|
|
792
|
+
// entry here — its card falls back to "not started", same as before.
|
|
793
|
+
const auditGroupsByStep = {};
|
|
794
|
+
for (const g of deriveAuditGroups(enrichAuditRows(ctx.auditRows))) auditGroupsByStep[g.step] = g;
|
|
795
|
+
|
|
796
|
+
let steps = null;
|
|
797
|
+
let stepsWhy = null;
|
|
798
|
+
if (!ctx.flowRead.ok) {
|
|
799
|
+
stepsWhy = `readFlow refused: ${ctx.flowRead.reds.join('; ')}`;
|
|
800
|
+
} else {
|
|
801
|
+
const declSteps = ctx.flowRead.declaration.steps;
|
|
802
|
+
if (!Array.isArray(declSteps) || declSteps.length === 0) {
|
|
803
|
+
stepsWhy = 'declaration.json has no steps array';
|
|
804
|
+
} else {
|
|
805
|
+
const byStep = {};
|
|
806
|
+
const byStepAuditIdx = {}; // step -> this row's index in ctx.auditRows, parallel to byStep[step]
|
|
807
|
+
ctx.auditRows.forEach((row, auditIdx) => {
|
|
808
|
+
(byStep[row.step] ??= []).push({
|
|
809
|
+
attempt: row.attempt,
|
|
810
|
+
verdict: row.verdict,
|
|
811
|
+
gap: row.gap,
|
|
812
|
+
cost: row.usd,
|
|
813
|
+
spendComplete: row.spendComplete,
|
|
814
|
+
model: row.model,
|
|
815
|
+
modelMatch: row.modelMatch,
|
|
816
|
+
strike: row.strike,
|
|
817
|
+
afterReject: null,
|
|
818
|
+
});
|
|
819
|
+
(byStepAuditIdx[row.step] ??= []).push(auditIdx);
|
|
820
|
+
});
|
|
821
|
+
// A step's own attempt numbers can repeat/restart in book order after
|
|
822
|
+
// a human reject (src/runner.js's redo path numbers a redo from the
|
|
823
|
+
// reject count, not the previous attempt counter — M4a piece 3 fix
|
|
824
|
+
// #6). Never renumber or hide a row; instead name the boundary, but
|
|
825
|
+
// ONLY on a non-ask step: an ask (`hitl`-classed) step's OWN rows
|
|
826
|
+
// legitimately repeat the same attempt number for a paused row
|
|
827
|
+
// followed by its own resolution (paused N, then red/green N) — that
|
|
828
|
+
// pairing is the normal shape, never a restart, and must never be
|
|
829
|
+
// mislabelled (coordinator's re-walk: labelling both rows of an ask
|
|
830
|
+
// step's pause+reject pair was the exact bug this guards against). A
|
|
831
|
+
// restart whose interleaved reject can't be found gets NO label at
|
|
832
|
+
// all — a missing hint beats a wrong one.
|
|
833
|
+
for (const s of declSteps) {
|
|
834
|
+
if (s.close?.class === 'hitl') continue;
|
|
835
|
+
const list = byStep[s.emits];
|
|
836
|
+
const idxs = byStepAuditIdx[s.emits];
|
|
837
|
+
if (!list) continue;
|
|
838
|
+
for (let i = 1; i < list.length; i += 1) {
|
|
839
|
+
if (list[i].attempt > list[i - 1].attempt) continue;
|
|
840
|
+
let rejectRow = null;
|
|
841
|
+
for (let j = idxs[i - 1] + 1; j < idxs[i]; j += 1) {
|
|
842
|
+
const r = ctx.auditRows[j];
|
|
843
|
+
if (r.class === 'hitl' && r.verdict === 'red') rejectRow = r;
|
|
844
|
+
}
|
|
845
|
+
if (rejectRow) list[i].afterReject = rejectRow.gap;
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
steps = declSteps.map((s) => {
|
|
849
|
+
const group = auditGroupsByStep[s.emits] ?? null;
|
|
850
|
+
return {
|
|
851
|
+
emits: s.emits,
|
|
852
|
+
goal: s.goal,
|
|
853
|
+
primitives: s.primitives ?? null,
|
|
854
|
+
closeClass: s.close?.class ?? null,
|
|
855
|
+
attempts: byStep[s.emits] ?? [],
|
|
856
|
+
attemptsWhy: byStep[s.emits] ? null : 'no audit.jsonl rows yet for this step',
|
|
857
|
+
tryCount: computeTryCount(s.close?.class ?? null, byStep[s.emits] ?? []),
|
|
858
|
+
// The step card's own actions line (hamr's 2026-09-27 review):
|
|
859
|
+
// `group` is `null` only for a step with no audit rows at all
|
|
860
|
+
// (never attempted) — every field below stays `null`/empty rather
|
|
861
|
+
// than a guessed 0, matching `deriveAuditGroups`'s own honesty
|
|
862
|
+
// rules exactly (it's the SAME group object).
|
|
863
|
+
groupState: group ? group.state : null,
|
|
864
|
+
timeMs: group ? group.timeMs : null,
|
|
865
|
+
cost: group ? group.cost : null,
|
|
866
|
+
costWhy: group ? group.costWhy : null,
|
|
867
|
+
tokensTotal: group ? group.tokensTotal : null,
|
|
868
|
+
toolsTotal: group ? group.toolsTotal : null,
|
|
869
|
+
toolsWhy: group ? group.toolsWhy : null,
|
|
870
|
+
ungranted: group ? group.ungranted : [],
|
|
871
|
+
tryMarks: group ? group.tryMarks : [],
|
|
872
|
+
// Filled below, ONLY on the one step that actually stopped this
|
|
873
|
+
// run (never guessed onto every step) — see stoppedStepEmits.
|
|
874
|
+
stoppedReason: null,
|
|
875
|
+
};
|
|
876
|
+
});
|
|
877
|
+
}
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
let modelWrote = null;
|
|
881
|
+
let modelWroteWhy = null;
|
|
882
|
+
if (!ctx.logJson) {
|
|
883
|
+
modelWroteWhy = ctx.historyRow
|
|
884
|
+
? `run "${runId}" completed (history row present) but log.json is missing`
|
|
885
|
+
: 'log.json has not been written yet (parked before any close, or still running)';
|
|
886
|
+
} else {
|
|
887
|
+
modelWrote = { artifacts: ctx.logJson.artifacts ?? null, attempts: ctx.logJson.attempts ?? null };
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// A run that completed clean never shows a stop reason, full stop — an
|
|
891
|
+
// earlier attempt on some step can carry a superseded not-done/red row
|
|
892
|
+
// (a human rejected a draft, or a first pass missed the shape, and a
|
|
893
|
+
// later attempt on the SAME step went on to pass) even though the run as
|
|
894
|
+
// a whole finished clean. Checking `historyRow.outcome === 'complete'`
|
|
895
|
+
// FIRST, before ever looking at `auditRows`, is what keeps a passed run
|
|
896
|
+
// from reporting a stale, superseded failure as its own "why" (found live
|
|
897
|
+
// against `flows/`, M4a piece 3 fix #1 — a real run, not a synthetic
|
|
898
|
+
// fixture, is what caught this).
|
|
899
|
+
//
|
|
900
|
+
// hamr's 2026-09-27 browser-walk bug #1: the SAME staleness bug also hit a
|
|
901
|
+
// run that's genuinely still PARKED (waiting on you) — an earlier step's
|
|
902
|
+
// superseded gap (e.g. a first draft that missed the shape, redone and
|
|
903
|
+
// accepted before the run went on to park on its own ask) was surfacing
|
|
904
|
+
// as "why" even though the run hasn't stopped at all, it's just waiting.
|
|
905
|
+
// Checked SECOND (right after the completed-clean case, before ever
|
|
906
|
+
// looking at `auditRows` for a redRow): a run with an open, unanswered ask
|
|
907
|
+
// (`askJson` present, no consumed answer — the same test `computeGlyph`
|
|
908
|
+
// uses for "waiting on you") reports the ask's own question as its whole
|
|
909
|
+
// "why", never an unrelated earlier attempt's gap.
|
|
910
|
+
let stopReason = null;
|
|
911
|
+
let stopReasonWhy = null;
|
|
912
|
+
if (ctx.historyRow && ctx.historyRow.outcome === 'complete') {
|
|
913
|
+
stopReasonWhy = 'run completed clean — there is no stop reason to show';
|
|
914
|
+
} else if (!ctx.historyRow && ctx.askJson && !ctx.consumedAnswerExists) {
|
|
915
|
+
stopReasonWhy = `waiting on you: ${typeof ctx.askJson.question === 'string' && ctx.askJson.question.length > 0 ? ctx.askJson.question : 'no question recorded'}`;
|
|
916
|
+
} else if (ctx.logJson && typeof ctx.logJson.red === 'string' && ctx.logJson.red.length > 0) {
|
|
917
|
+
stopReason = ctx.logJson.red;
|
|
918
|
+
} else {
|
|
919
|
+
// The LAST matching row, not the first — a step can fail, then redo and
|
|
920
|
+
// fail again differently (or fail on a later step entirely); the most
|
|
921
|
+
// recent stop is the one that actually describes where the run sits now.
|
|
922
|
+
let redRow = null;
|
|
923
|
+
for (const r of ctx.auditRows) {
|
|
924
|
+
if (r.verdict === 'not-done' || r.verdict === 'red') redRow = r;
|
|
925
|
+
}
|
|
926
|
+
if (redRow) {
|
|
927
|
+
stopReason = `${redRow.step}: ${redRow.gap}`;
|
|
928
|
+
} else {
|
|
929
|
+
stopReasonWhy = 'run has not stopped on a red/not-done step (still parked, waiting, or clean so far)';
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// hamr's 2026-09-27 step-card review: which declared step is the one that
|
|
934
|
+
// actually stopped the run, so exactly ONE card (never every card, never a
|
|
935
|
+
// passed one) can show `stopReason`'s full text. This is safe to derive
|
|
936
|
+
// even for the `logJson.red` branch above (not just the `redRow` fallback
|
|
937
|
+
// branch): every halt path in src/runner.js's own step loop calls
|
|
938
|
+
// `recordAudit` for its own step in the SAME return that produces the red
|
|
939
|
+
// text which becomes either `logJson.red` or `redRow.gap` — so whenever
|
|
940
|
+
// `stopReason` is non-null, the LAST blocked-verdict row in book order
|
|
941
|
+
// names the real step, never a text-matched guess. Left `null` (no card
|
|
942
|
+
// gets a reason) for a clean or still-waiting run, matching stopReason's
|
|
943
|
+
// own `null` in both those cases.
|
|
944
|
+
let stoppedStepEmits = null;
|
|
945
|
+
if (stopReason !== null) {
|
|
946
|
+
for (const r of ctx.auditRows) {
|
|
947
|
+
if (isBlockedVerdict(r.verdict)) stoppedStepEmits = r.step;
|
|
948
|
+
}
|
|
949
|
+
}
|
|
950
|
+
if (steps && stoppedStepEmits !== null) {
|
|
951
|
+
const stoppedStep = steps.find((s) => s.emits === stoppedStepEmits);
|
|
952
|
+
if (stoppedStep) stoppedStep.stoppedReason = stopReason;
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
// "took Xs" for a finished run (M4a piece 3 fix #5) — straight off the
|
|
956
|
+
// history row's own `wallMs` (never derived/guessed); a died/parked run
|
|
957
|
+
// (no history row) or a history row predating this field both say why
|
|
958
|
+
// rather than showing nothing.
|
|
959
|
+
const wallMs = ctx.historyRow && typeof ctx.historyRow.wallMs === 'number' ? ctx.historyRow.wallMs : null;
|
|
960
|
+
const wallMsWhy = wallMs !== null
|
|
961
|
+
? null
|
|
962
|
+
: (ctx.historyRow ? 'history row has no wallMs recorded' : 'no history row yet (parked or died before completion)');
|
|
963
|
+
|
|
964
|
+
let spend;
|
|
965
|
+
if (ctx.historyRow) {
|
|
966
|
+
const cd = costDisplay(ctx.historyRow.spentUsd, ctx.historyRow.spendComplete);
|
|
967
|
+
spend = cd.ok ? cd.display : null;
|
|
968
|
+
} else {
|
|
969
|
+
spend = spendFloorDisplay(ctx.spendRows);
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// hamr's review #1 (Summary tab): model + spend.jsonl totals — read here
|
|
973
|
+
// ONCE, off the same auditRows/spendRows this function already loaded, so
|
|
974
|
+
// the Run tab's summary box and the step cards can never disagree about
|
|
975
|
+
// what model ran or what spend.jsonl actually holds.
|
|
976
|
+
const model = deriveRunModel(ctx.auditRows);
|
|
977
|
+
const modelWhy = model === null ? 'no audit.jsonl row in this run has ever named a model (no model step has run yet)' : null;
|
|
978
|
+
const spendSummary = summarizeSpendRows(ctx.spendRows);
|
|
979
|
+
|
|
980
|
+
return {
|
|
981
|
+
flow,
|
|
982
|
+
runId,
|
|
983
|
+
glyph,
|
|
984
|
+
label,
|
|
985
|
+
outcome: ctx.historyRow ? ctx.historyRow.outcome : null,
|
|
986
|
+
outcomeWhy: ctx.historyRow ? null : 'no history row (parked or died before completion)',
|
|
987
|
+
capUsd: ctx.historyRow ? ctx.historyRow.capUsd : (ctx.flowRead.ok ? ctx.flowRead.arbiter.capUsd : null),
|
|
988
|
+
spend,
|
|
989
|
+
model,
|
|
990
|
+
modelWhy,
|
|
991
|
+
spendSummary,
|
|
992
|
+
wallMs,
|
|
993
|
+
wallMsWhy,
|
|
994
|
+
steps,
|
|
995
|
+
stepsWhy,
|
|
996
|
+
modelWrote,
|
|
997
|
+
modelWroteWhy,
|
|
998
|
+
stopReason,
|
|
999
|
+
stopReasonWhy,
|
|
1000
|
+
at: ctx.historyRow ? ctx.historyRow.at : null,
|
|
1001
|
+
// browser re-walk bug #4: same "the books hold a date, so never say
|
|
1002
|
+
// unknown" rule as listRuns above — a parked run's own ask.json
|
|
1003
|
+
// `askedAt` is a real timestamp, shown ahead of the generic `atWhy`.
|
|
1004
|
+
askedAt: (!ctx.historyRow && ctx.askJson && typeof ctx.askJson.askedAt === 'string')
|
|
1005
|
+
? ctx.askJson.askedAt
|
|
1006
|
+
: null,
|
|
1007
|
+
atWhy: (ctx.historyRow || (ctx.askJson && typeof ctx.askJson.askedAt === 'string'))
|
|
1008
|
+
? null
|
|
1009
|
+
: 'no history row yet (parked or died before completion)',
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
/**
|
|
1014
|
+
* `GET /api/runs/:flow/:runId/audit` — the Audit/logs tab (M4a scope item
|
|
1015
|
+
* 2): the raw `audit.jsonl` rows, scoped strictly to this run (each run's
|
|
1016
|
+
* own `audit.jsonl` file already carries only its own rows — there is no
|
|
1017
|
+
* shared-sidecar contamination risk here the way bareloop's gate-audit
|
|
1018
|
+
* sidecar had). `null` when the flow/runId doesn't resolve (404).
|
|
1019
|
+
* @param {{root: string, flow: string, runId: string}} opts
|
|
1020
|
+
* @returns {{flow:string, runId:string, rows:any[], groups:any[], empty:boolean, why:string|null}|null}
|
|
1021
|
+
*/
|
|
1022
|
+
export function getRunAudit({ root, flow, runId }) {
|
|
1023
|
+
const run = resolveRunPath(root, flow, runId);
|
|
1024
|
+
if (!run.ok) return null;
|
|
1025
|
+
if (!existsSync(run.runDir)) return null;
|
|
1026
|
+
const rawRows = readAudit(run.runDir);
|
|
1027
|
+
// hamr's review #6: the Audit tab's "Action" column is derived server-side
|
|
1028
|
+
// (never guessed client-side from partial data) — `action` is added to
|
|
1029
|
+
// each row here, off that SAME row's own fields, book order preserved.
|
|
1030
|
+
// hamr's 2026-09-27 review items (c)/(d): the Cost cell's token phrase
|
|
1031
|
+
// (`tokensDisplay`) and the new Time column's old-row "why" (`atWhy`) are
|
|
1032
|
+
// likewise derived here, off this same row, never client-side.
|
|
1033
|
+
const rows = enrichAuditRows(rawRows);
|
|
1034
|
+
return {
|
|
1035
|
+
flow,
|
|
1036
|
+
runId,
|
|
1037
|
+
rows,
|
|
1038
|
+
// hamr's 2026-09-27 exit-check review #1: the Audit tab's grouped-by-
|
|
1039
|
+
// step header pieces, computed here off these SAME enriched rows —
|
|
1040
|
+
// never a second, client-side re-grouping.
|
|
1041
|
+
groups: deriveAuditGroups(rows),
|
|
1042
|
+
empty: rows.length === 0,
|
|
1043
|
+
why: rows.length === 0 ? 'audit.jsonl is empty or missing — no attempt has been made yet' : null,
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
/**
|
|
1048
|
+
* `GET /api/runs/:flow/:runId/job` — the Job tab (M4a scope item 2): the
|
|
1049
|
+
* signed prose, the arbiter block (cap, asks with TTL, redo cap, sends,
|
|
1050
|
+
* sources), and the signature (who, when, hash). Derived purely from the
|
|
1051
|
+
* flow's own signed files (`readFlow`) — fwdloop always has exactly one
|
|
1052
|
+
* signed `declaration.json` + `signature.json` per flow, so there is no
|
|
1053
|
+
* multi-source provenance chain to resolve (unlike bareloop's `getRunJob` —
|
|
1054
|
+
* DROPPED per the fit-check). `runId` is only used to confirm the run
|
|
1055
|
+
* exists at all; `null` when it doesn't (404).
|
|
1056
|
+
* @param {{root: string, flow: string, runId: string, catalogue: any}} opts
|
|
1057
|
+
* @returns {any|null}
|
|
1058
|
+
*/
|
|
1059
|
+
/**
|
|
1060
|
+
* hamr's 2026-09-27 exit-check review #5: one plain-words sentence for a
|
|
1061
|
+
* declared step's own close rule — the Job tab's "Success" field. Derived
|
|
1062
|
+
* STRICTLY from `step.close` (and, for the "your accept" wording, whether
|
|
1063
|
+
* this step is the one line `arbiter.asks[]` itself binds to) — never a
|
|
1064
|
+
* fabricated cite/shape value:
|
|
1065
|
+
* - `hitl`: "human check", or "human check (your accept)" when this step's
|
|
1066
|
+
* own `fromLine` is a signed ask line (the ask step itself — the one a
|
|
1067
|
+
* human pauses a run on, distinct from an ordinary hitl pass-through
|
|
1068
|
+
* step with no ask binding).
|
|
1069
|
+
* - `softgreen`: "shape: N headings (a / b / c)" when `close.shape.sections`
|
|
1070
|
+
* is signed, "max W words" appended when `close.shape.maxWords` is
|
|
1071
|
+
* signed, "blocks of L lines" / "must carry: a, b" for the invoice-block
|
|
1072
|
+
* shape keys (`linesPerInvoice`/`mustCarry`) — every signed shape key
|
|
1073
|
+
* shown, nothing invented; "shape (no shape rules signed)" when a
|
|
1074
|
+
* softgreen step signs no `close.shape` at all (declaration.js allows
|
|
1075
|
+
* this — an empty/absent shape is not itself a red).
|
|
1076
|
+
* - `green`: "cited" — `CLOSE_ALLOWED` (`src/declaration.js`) never lets a
|
|
1077
|
+
* step declare WHAT it cites ahead of time (that's the drafted
|
|
1078
|
+
* artifact's own per-run field data, not signed prose), so there is
|
|
1079
|
+
* never anything honest to append here.
|
|
1080
|
+
* - anything else: the raw class name, named as unknown, never silently
|
|
1081
|
+
* dropped or guessed into one of the three above; no class at all names
|
|
1082
|
+
* that plainly too.
|
|
1083
|
+
* @param {{close?: {class?: string, shape?: any}, fromLine?: number|null}} step one `declaration.steps` entry
|
|
1084
|
+
* @param {Array<{line:number}>} arbiterAsks `arbiter.asks`, for the "your accept" check
|
|
1085
|
+
* @returns {string}
|
|
1086
|
+
*/
|
|
1087
|
+
export function deriveStepSuccessText(step, arbiterAsks) {
|
|
1088
|
+
const cls = step?.close?.class ?? null;
|
|
1089
|
+
if (cls === null) return 'no close class recorded';
|
|
1090
|
+
if (cls === 'hitl') {
|
|
1091
|
+
const isAskStep = Array.isArray(arbiterAsks) && arbiterAsks.some((a) => a.line === step.fromLine);
|
|
1092
|
+
return isAskStep ? 'human check (your accept)' : 'human check';
|
|
1093
|
+
}
|
|
1094
|
+
if (cls === 'green') return 'cited';
|
|
1095
|
+
if (cls === 'softgreen') {
|
|
1096
|
+
const shape = step?.close?.shape;
|
|
1097
|
+
if (!shape || typeof shape !== 'object') return 'shape (no shape rules signed)';
|
|
1098
|
+
const parts = [];
|
|
1099
|
+
if (Array.isArray(shape.sections) && shape.sections.length > 0) {
|
|
1100
|
+
parts.push(`${shape.sections.length} heading${shape.sections.length === 1 ? '' : 's'} (${shape.sections.join(' / ')})`);
|
|
1101
|
+
}
|
|
1102
|
+
if (typeof shape.maxWords === 'number') parts.push(`max ${shape.maxWords} words`);
|
|
1103
|
+
if (typeof shape.linesPerInvoice === 'number') parts.push(`blocks of ${shape.linesPerInvoice} lines`);
|
|
1104
|
+
if (Array.isArray(shape.mustCarry) && shape.mustCarry.length > 0) parts.push(`must carry: ${shape.mustCarry.join(', ')}`);
|
|
1105
|
+
return parts.length > 0 ? `shape: ${parts.join(', ')}` : 'shape (no shape rules signed)';
|
|
1106
|
+
}
|
|
1107
|
+
return `unknown close class "${cls}"`;
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
/**
|
|
1111
|
+
* `GET /api/runs/:flow/:runId/job` — the Job tab (hamr's 2026-09-27
|
|
1112
|
+
* exit-check review #5: bareloop-style one-field-per-piece layout,
|
|
1113
|
+
* replacing the old split asks/sends/sources/signed-lines blocks). Every
|
|
1114
|
+
* field is read straight off `readFlow`'s own signed declaration.json/
|
|
1115
|
+
* signature.json/prose lines — nothing invented; a piece the books can't
|
|
1116
|
+
* name carries its own why, never a blank or a guess. Field order (server
|
|
1117
|
+
* order matches the page's own render order): prose, asks, model, cap
|
|
1118
|
+
* (+redo cap), sources, sends, guardrails, success (one row per step, off
|
|
1119
|
+
* `deriveStepSuccessText`), signature.
|
|
1120
|
+
* @param {{root: string, flow: string, runId: string, catalogue: any}} opts
|
|
1121
|
+
* @returns {any|null}
|
|
1122
|
+
*/
|
|
1123
|
+
export function getRunJob({
|
|
1124
|
+
root, flow, runId, catalogue,
|
|
1125
|
+
}) {
|
|
1126
|
+
const run = resolveRunPath(root, flow, runId);
|
|
1127
|
+
if (!run.ok) return null;
|
|
1128
|
+
if (!existsSync(run.runDir)) return null;
|
|
1129
|
+
|
|
1130
|
+
const flowRead = readFlow({ root, name: flow, catalogue });
|
|
1131
|
+
if (!flowRead.ok) {
|
|
1132
|
+
return {
|
|
1133
|
+
flow, runId, resolved: false, why: `readFlow refused: ${flowRead.reds.join('; ')}`,
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
const sig = flowRead.signature;
|
|
1137
|
+
// hamr's review #7: the Job tab is missing the model name entirely — the
|
|
1138
|
+
// signed declaration/signature never record one (checked: no module in
|
|
1139
|
+
// `src/` writes a `model` field into either), so this reads the SAME
|
|
1140
|
+
// per-attempt `audit.jsonl` field the Run tab's summary uses
|
|
1141
|
+
// (`deriveRunModel`) and says so plainly when it does, rather than
|
|
1142
|
+
// pretending the signed prose named it.
|
|
1143
|
+
const auditRows = readAudit(run.runDir);
|
|
1144
|
+
const model = deriveRunModel(auditRows);
|
|
1145
|
+
const a = flowRead.arbiter ?? {};
|
|
1146
|
+
const asks = a.asks ?? [];
|
|
1147
|
+
const sends = a.sends ?? [];
|
|
1148
|
+
const sources = a.sources ?? [];
|
|
1149
|
+
const declSteps = Array.isArray(flowRead.declaration?.steps) ? flowRead.declaration.steps : [];
|
|
1150
|
+
return {
|
|
1151
|
+
flow,
|
|
1152
|
+
runId,
|
|
1153
|
+
resolved: true,
|
|
1154
|
+
model,
|
|
1155
|
+
// `model` is read from this run's own audit.jsonl rows, never the signed
|
|
1156
|
+
// prose/declaration (neither records one) — the page says so in words
|
|
1157
|
+
// ("model used: X (from this run's rows)") rather than implying it came
|
|
1158
|
+
// from the signed job itself.
|
|
1159
|
+
modelWhy: model === null ? 'no audit.jsonl row for this run has ever named a model' : null,
|
|
1160
|
+
// review #5: "Job (prose)" — the signed lines WITHOUT their guardrail
|
|
1161
|
+
// mixed in (guardrails get their own field below).
|
|
1162
|
+
prose: flowRead.lines.map((l) => ({ line: l.n, text: l.text })),
|
|
1163
|
+
// review #5: "Ask" — one row per signed ask line; `waitMs` is the raw
|
|
1164
|
+
// signed ttlMs, formatted client-side by the SAME `duration()` every
|
|
1165
|
+
// other elapsed-time field on this page already uses.
|
|
1166
|
+
asks: asks.map((ak) => ({ line: ak.line, question: ak.question, waitMs: ak.ttlMs })),
|
|
1167
|
+
capUsd: typeof a.capUsd === 'number' ? a.capUsd : null,
|
|
1168
|
+
redoCap: typeof a.redoCap === 'number' ? a.redoCap : null,
|
|
1169
|
+
// review #5: "Source" — role -> basename only (never the full signed
|
|
1170
|
+
// path, even though sources are themselves signed input — hamr's own
|
|
1171
|
+
// "to be safe" instruction).
|
|
1172
|
+
sources: sources.map((s) => ({
|
|
1173
|
+
role: s.role, kind: s.kind, path: s.path, basename: basename(s.path),
|
|
1174
|
+
})),
|
|
1175
|
+
// review #5: "Destination" — one row per send.
|
|
1176
|
+
sends: sends.map((s) => ({ line: s.line, kind: s.target?.kind ?? null, target: s.target?.path ?? null })),
|
|
1177
|
+
// review #5: "Guardrails" — ONE field, one row per NUMBERED-LINE
|
|
1178
|
+
// guardrail (never the separate "Arbiter guardrails" block, already
|
|
1179
|
+
// covered by cap/asks/sends/sources above); empty guardrails skipped.
|
|
1180
|
+
guardrails: flowRead.lines
|
|
1181
|
+
.filter((l) => typeof l.guardrail === 'string' && l.guardrail.length > 0)
|
|
1182
|
+
.map((l) => ({ line: l.n, guardrail: l.guardrail })),
|
|
1183
|
+
// review #5: "Success" — one row per declared step, in declaration order.
|
|
1184
|
+
success: declSteps.map((s) => ({ step: s.emits, text: deriveStepSuccessText(s, asks) })),
|
|
1185
|
+
signature: (sig && typeof sig.signedBy === 'string' && typeof sig.signedAt === 'string' && typeof sig.flow === 'string')
|
|
1186
|
+
? { signedBy: sig.signedBy, signedAt: sig.signedAt, hash: sig.flow }
|
|
1187
|
+
: null,
|
|
1188
|
+
signatureWhy: (sig && typeof sig.signedBy === 'string' && typeof sig.signedAt === 'string' && typeof sig.flow === 'string')
|
|
1189
|
+
? null
|
|
1190
|
+
: 'signature.json is missing signedBy/signedAt/flow (hash)',
|
|
1191
|
+
};
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
// ---------------------------------------------------------------------------
|
|
1195
|
+
// M4a Amendment M4a-1 — the panel's Inbox/Ask surface (docs/wiki/the-module-
|
|
1196
|
+
// ladder.md, "M4a" section, signed 2026-09-27). Every stop (parked ask) this
|
|
1197
|
+
// panel can name is read through ONE reader per run —
|
|
1198
|
+
// `listArchivedAsks(runDir)` (`src/ask.js`) for a run that has an `asks/`
|
|
1199
|
+
// archive, or `legacyRunAsks` (below, THIS module's own reader) for a run
|
|
1200
|
+
// that predates M4a-1 (no `asks/` directory at all) — never a third,
|
|
1201
|
+
// ad-hoc reconstruction. Status vocabulary, used everywhere in the panel
|
|
1202
|
+
// (Inbox list, Ask tab, both API responses), is exactly the words
|
|
1203
|
+
// `listArchivedAsks` itself already returns from the books' own decision
|
|
1204
|
+
// field: `accepted` / `rejected` / `reran` / `expired` / `unanswered` (a
|
|
1205
|
+
// parked, not-yet-expired ask with no consumed answer — this IS "open" in
|
|
1206
|
+
// the UI) / `open` (the rare case `listArchivedAsks` falls back to when an
|
|
1207
|
+
// archived ask.json itself fails to parse — no question/evidence can be
|
|
1208
|
+
// read for it either). Nothing here invents a question, a draft, or a
|
|
1209
|
+
// decision that no book actually recorded.
|
|
1210
|
+
// ---------------------------------------------------------------------------
|
|
1211
|
+
|
|
1212
|
+
/**
|
|
1213
|
+
* An ask row is "open" (still waiting on a human, right now) exactly when
|
|
1214
|
+
* its book-derived status is `unanswered` (parked, not yet answered, not
|
|
1215
|
+
* expired — `listArchivedAsks` already applies the expiry check at read
|
|
1216
|
+
* time) or the rare unparseable-archive fallback `open`. Every other status
|
|
1217
|
+
* (`accepted`/`rejected`/`reran`/`expired`, or an `unrecognised: X` decision
|
|
1218
|
+
* value) is a PAST stop.
|
|
1219
|
+
* @param {string} status
|
|
1220
|
+
* @returns {boolean}
|
|
1221
|
+
*/
|
|
1222
|
+
function isOpenStatus(status) {
|
|
1223
|
+
return status === 'unanswered' || status === 'open';
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
/**
|
|
1227
|
+
* `open` + `timeLeftMs` for one ask row — the ONE place both are computed,
|
|
1228
|
+
* shared by `listStops` (the Inbox) and `getRunAsks` (the Ask tab), so a
|
|
1229
|
+
* given ask can never read "open, no time-left" in one surface and
|
|
1230
|
+
* something else in the other (hamr's 2026-09-27 browser-walk bug #4: the
|
|
1231
|
+
* Ask tab's own asks never carried these fields at all — only `listStops`
|
|
1232
|
+
* computed them — so an open ask's Ask-tab header/body fell back to the raw
|
|
1233
|
+
* `status` word "unanswered" and no time-left, while the Inbox row for the
|
|
1234
|
+
* SAME ask correctly showed a dot and "time left: …").
|
|
1235
|
+
* - `open`: this ask's own status reads as open (`isOpenStatus`) AND the
|
|
1236
|
+
* run hasn't already ended (`!hasHistoryRow` — the same rule
|
|
1237
|
+
* `legacyRunAsks` itself already applies when building the row, repeated
|
|
1238
|
+
* here as the same belt-and-braces `listStops` already had).
|
|
1239
|
+
* - `timeLeftMs`: only meaningful while `open` — the real ms remaining
|
|
1240
|
+
* until `expiresAt`, floored at 0, `null` when not open or `expiresAt`
|
|
1241
|
+
* can't be parsed (never a guessed number).
|
|
1242
|
+
* @param {any} ask one row from `runAsksInOrder`
|
|
1243
|
+
* @param {boolean} hasHistoryRow
|
|
1244
|
+
* @returns {{open: boolean, timeLeftMs: number|null}}
|
|
1245
|
+
*/
|
|
1246
|
+
function deriveAskOpenFields(ask, hasHistoryRow) {
|
|
1247
|
+
const open = isOpenStatus(ask.status) && !hasHistoryRow;
|
|
1248
|
+
const expiresMs = open && typeof ask.expiresAt === 'string' ? Date.parse(ask.expiresAt) : NaN;
|
|
1249
|
+
return { open, timeLeftMs: open && Number.isFinite(expiresMs) ? Math.max(0, expiresMs - Date.now()) : null };
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
/**
|
|
1253
|
+
* `readAskEvidence`'s own return shape (`src/ask.js`) carries the draft as
|
|
1254
|
+
* `{ text: string } | null` (never a bare string) so a caller can tell "no
|
|
1255
|
+
* draft" apart from "a draft with an empty string" — this panel's UI wants
|
|
1256
|
+
* a flat, renderable string instead. The ONE place that unwraps `.text`, so
|
|
1257
|
+
* every row this module produces (archived or legacy) carries the same
|
|
1258
|
+
* flat `{ draft: string|null, unjudged, why }` shape.
|
|
1259
|
+
* @param {ReturnType<typeof readAskEvidence>} evidence
|
|
1260
|
+
* @returns {{draft: string|null, unjudged: any[], why?: string}}
|
|
1261
|
+
*/
|
|
1262
|
+
function flattenEvidence(evidence) {
|
|
1263
|
+
return {
|
|
1264
|
+
draft: evidence.draft ? evidence.draft.text : null,
|
|
1265
|
+
unjudged: evidence.unjudged,
|
|
1266
|
+
why: evidence.why,
|
|
1267
|
+
};
|
|
1268
|
+
}
|
|
1269
|
+
|
|
1270
|
+
/**
|
|
1271
|
+
* Flattens one `listArchivedAsks` entry (its nested `answer` object) into
|
|
1272
|
+
* this module's own flat row shape, shared by both the archived and
|
|
1273
|
+
* pre-M4a-1 legacy paths so callers (the Inbox list, the Ask tab, both
|
|
1274
|
+
* routes) never have to branch on which reader produced a row.
|
|
1275
|
+
* @param {any} a one entry of `listArchivedAsks(runDir).asks`
|
|
1276
|
+
* @returns {any}
|
|
1277
|
+
*/
|
|
1278
|
+
function normalizeArchivedRow(a) {
|
|
1279
|
+
return {
|
|
1280
|
+
askId: a.askId,
|
|
1281
|
+
question: a.question ?? null,
|
|
1282
|
+
askedAt: a.askedAt ?? null,
|
|
1283
|
+
expiresAt: a.expiresAt ?? null,
|
|
1284
|
+
status: a.answer.status,
|
|
1285
|
+
reason: a.answer.reason ?? null,
|
|
1286
|
+
answeredAt: a.answer.answeredAt ?? null,
|
|
1287
|
+
archived: true,
|
|
1288
|
+
evidence: flattenEvidence(a.evidence),
|
|
1289
|
+
};
|
|
1290
|
+
}
|
|
1291
|
+
|
|
1292
|
+
/** `^answer\.<askId>\.consumed\.json$` — deliberately excludes
|
|
1293
|
+
* `answer.stale.<n>.json` (no capture group would match "stale" as a real
|
|
1294
|
+
* askId; the stale-quarantine writer in `src/ask.js` uses that different
|
|
1295
|
+
* name specifically so this convention-based scan never mistakes a
|
|
1296
|
+
* quarantined stale answer for a real consumed one). */
|
|
1297
|
+
const CONSUMED_ANSWER_RE = /^answer\.(.+)\.consumed\.json$/;
|
|
1298
|
+
|
|
1299
|
+
/**
|
|
1300
|
+
* The pre-M4a-1 fallback reader (M4a-1 scope item 1): for a run with no
|
|
1301
|
+
* `asks/` archive directory at all, reconstructs what the books STILL hold —
|
|
1302
|
+
* the current (single-slot, mutable) `ask.json`, if any, plus every
|
|
1303
|
+
* `answer.<askId>.consumed.json` marker still on disk. A past askId's own
|
|
1304
|
+
* question/draft can never be recovered (the single ask.json slot was
|
|
1305
|
+
* overwritten by the next park) — those fields come back `null` with the
|
|
1306
|
+
* fixed `why` the brief specifies, never guessed from the CURRENT ask.json
|
|
1307
|
+
* (which may name a completely different, later question).
|
|
1308
|
+
* hamr's 2026-09-27 live check: a run that has a history row has ENDED —
|
|
1309
|
+
* the single mutable `ask.json` slot left on disk is a stale leftover from
|
|
1310
|
+
* whatever it last held, and the answer to it (if any) is already
|
|
1311
|
+
* represented by its own `answer.<id>.consumed.json` marker, read above.
|
|
1312
|
+
* Never rebuilt as a second, "still open" row for an ended run — that
|
|
1313
|
+
* double-counts one real ask as two stops and inflates the Inbox's open
|
|
1314
|
+
* count with something no human can actually act on any more.
|
|
1315
|
+
* @param {string} runDir
|
|
1316
|
+
* @param {boolean} hasHistoryRow whether this run's flow-level history.jsonl
|
|
1317
|
+
* already carries a row for it (the run ended, one way or another)
|
|
1318
|
+
* @returns {any[]}
|
|
1319
|
+
*/
|
|
1320
|
+
function legacyRunAsks(runDir, hasHistoryRow) {
|
|
1321
|
+
const rows = [];
|
|
1322
|
+
// F48 round 3: `readdirInside` (`src/flow.js`) — a symlinked entry is
|
|
1323
|
+
// skipped, never followed, so a legacy consumed-answer row can never be
|
|
1324
|
+
// synthesised off a planted symlink's outside content.
|
|
1325
|
+
const names = readdirInside(runDir, '.');
|
|
1326
|
+
|
|
1327
|
+
const askJson = readAsk(runDir);
|
|
1328
|
+
const currentAskId = askJson && typeof askJson.askId === 'string' ? askJson.askId : null;
|
|
1329
|
+
|
|
1330
|
+
const consumedFiles = names.filter((n) => CONSUMED_ANSWER_RE.test(n)).sort();
|
|
1331
|
+
const decisionToStatus = { accept: 'accepted', reject: 'rejected', rerun: 'reran' };
|
|
1332
|
+
|
|
1333
|
+
for (const file of consumedFiles) {
|
|
1334
|
+
const match = CONSUMED_ANSWER_RE.exec(file);
|
|
1335
|
+
if (!match) continue; // eslint-disable-line no-continue -- filtered by the same regex above; never actually null
|
|
1336
|
+
const askId = match[1];
|
|
1337
|
+
const fileRead = readFileInside(runDir, file);
|
|
1338
|
+
if (!fileRead.ok) {
|
|
1339
|
+
continue; // eslint-disable-line no-continue -- missing/symlink-refused, same as a torn write: skipped, never invented
|
|
1340
|
+
}
|
|
1341
|
+
let parsed;
|
|
1342
|
+
try {
|
|
1343
|
+
parsed = JSON.parse(fileRead.text);
|
|
1344
|
+
} catch {
|
|
1345
|
+
continue; // eslint-disable-line no-continue -- a torn write is skipped, never invented
|
|
1346
|
+
}
|
|
1347
|
+
// A consumed legacy row never recovers question/askedAt/expiresAt from
|
|
1348
|
+
// the CURRENT ask.json, even when its askId happens to still match it —
|
|
1349
|
+
// the single mutable slot is not a reliable append log for a past ask
|
|
1350
|
+
// (a later park would silently overwrite it), so this deliberately
|
|
1351
|
+
// shows only what a consumed-answer marker itself can prove: askId,
|
|
1352
|
+
// decision, reason, answeredAt (brief, M4a-1 scope item 1).
|
|
1353
|
+
rows.push({
|
|
1354
|
+
askId,
|
|
1355
|
+
question: null,
|
|
1356
|
+
questionWhy: 'question not kept (before M4a-1)',
|
|
1357
|
+
askedAt: null,
|
|
1358
|
+
expiresAt: null,
|
|
1359
|
+
status: decisionToStatus[parsed.decision] ?? `unrecognised: ${parsed.decision}`,
|
|
1360
|
+
reason: typeof parsed.reason === 'string' ? parsed.reason : null,
|
|
1361
|
+
answeredAt: typeof parsed.answeredAt === 'string' ? parsed.answeredAt : null,
|
|
1362
|
+
archived: false,
|
|
1363
|
+
evidence: { draft: null, unjudged: [], why: 'draft not kept (before M4a-1)' },
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
// The currently open ask, when its own askId has no consumed marker yet —
|
|
1368
|
+
// and only when the run hasn't already ended. A history row means the run
|
|
1369
|
+
// is over; the leftover `ask.json` slot is never rebuilt into a second
|
|
1370
|
+
// "still open" stop at that point, no matter what its own askId says.
|
|
1371
|
+
if (askJson && !hasHistoryRow) {
|
|
1372
|
+
const hasConsumed = currentAskId !== null
|
|
1373
|
+
&& consumedFiles.includes(`answer.${currentAskId}.consumed.json`);
|
|
1374
|
+
if (!hasConsumed) {
|
|
1375
|
+
if (currentAskId === null) {
|
|
1376
|
+
// A genuine pre-M3 ask.json: no askId/expiresAt at all — cannot be
|
|
1377
|
+
// paired with a future answer or timed, shown for visibility only.
|
|
1378
|
+
rows.push({
|
|
1379
|
+
askId: null,
|
|
1380
|
+
question: askJson.question ?? null,
|
|
1381
|
+
askedAt: askJson.askedAt ?? null,
|
|
1382
|
+
expiresAt: null,
|
|
1383
|
+
status: 'unanswered',
|
|
1384
|
+
reason: null,
|
|
1385
|
+
answeredAt: null,
|
|
1386
|
+
archived: false,
|
|
1387
|
+
evidence: flattenEvidence(readAskEvidence(askJson)),
|
|
1388
|
+
why: 'pre-M3 ask.json (no askId/expiresAt) — not answerable, shown for visibility only',
|
|
1389
|
+
});
|
|
1390
|
+
} else {
|
|
1391
|
+
const expiresMs = typeof askJson.expiresAt === 'string' ? Date.parse(askJson.expiresAt) : NaN;
|
|
1392
|
+
const expired = !Number.isNaN(expiresMs) && Date.now() > expiresMs;
|
|
1393
|
+
rows.push({
|
|
1394
|
+
askId: currentAskId,
|
|
1395
|
+
question: askJson.question ?? null,
|
|
1396
|
+
askedAt: askJson.askedAt ?? null,
|
|
1397
|
+
expiresAt: askJson.expiresAt ?? null,
|
|
1398
|
+
status: expired ? 'expired' : 'unanswered',
|
|
1399
|
+
reason: null,
|
|
1400
|
+
answeredAt: null,
|
|
1401
|
+
archived: false,
|
|
1402
|
+
evidence: flattenEvidence(readAskEvidence(askJson)),
|
|
1403
|
+
});
|
|
1404
|
+
}
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
return rows;
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
/**
|
|
1412
|
+
* Every ask (open or past) this run's own books can name, oldest first —
|
|
1413
|
+
* archived (`asks/<askId>.json`, M4a-1) when the run has that directory,
|
|
1414
|
+
* else the pre-M4a-1 fallback (`legacyRunAsks`). `listArchivedAsks` orders
|
|
1415
|
+
* its own entries by askId (a UUID, not chronological) — re-sorted here by
|
|
1416
|
+
* `askedAt` so the Ask tab reads as a real timeline; a row with no readable
|
|
1417
|
+
* `askedAt` (a legacy past entry — the field was never recoverable) sorts
|
|
1418
|
+
* after every row that has one, in the order `listArchivedAsks`/
|
|
1419
|
+
* `legacyRunAsks` themselves returned it.
|
|
1420
|
+
* @param {string} runDir
|
|
1421
|
+
* @param {boolean} hasHistoryRow whether this run's flow-level history.jsonl
|
|
1422
|
+
* already carries a row for it — threaded into `legacyRunAsks` so an ended
|
|
1423
|
+
* run's stale `ask.json` slot is never rebuilt into a fake "still open" row
|
|
1424
|
+
* (hamr's 2026-09-27 live check).
|
|
1425
|
+
* @returns {any[]}
|
|
1426
|
+
*/
|
|
1427
|
+
function runAsksInOrder(runDir, hasHistoryRow) {
|
|
1428
|
+
const archivedResult = listArchivedAsks(runDir);
|
|
1429
|
+
const rows = archivedResult.archived
|
|
1430
|
+
? archivedResult.asks.map(normalizeArchivedRow)
|
|
1431
|
+
: legacyRunAsks(runDir, hasHistoryRow);
|
|
1432
|
+
return rows
|
|
1433
|
+
.map((row, index) => ({ row, index }))
|
|
1434
|
+
.sort((a, b) => {
|
|
1435
|
+
const am = typeof a.row.askedAt === 'string' ? Date.parse(a.row.askedAt) : NaN;
|
|
1436
|
+
const bm = typeof b.row.askedAt === 'string' ? Date.parse(b.row.askedAt) : NaN;
|
|
1437
|
+
const aKnown = Number.isFinite(am);
|
|
1438
|
+
const bKnown = Number.isFinite(bm);
|
|
1439
|
+
if (aKnown && bKnown) return am - bm;
|
|
1440
|
+
if (aKnown !== bKnown) return aKnown ? -1 : 1;
|
|
1441
|
+
return a.index - b.index;
|
|
1442
|
+
})
|
|
1443
|
+
.map(({ row }) => row);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
/**
|
|
1447
|
+
* hamr's 2026-09-27 exit-check review #3: which declared step (and its
|
|
1448
|
+
* signed prose line) each ask in `orderedAsks` belongs to — no book field
|
|
1449
|
+
* names this directly (`ask.json`/the archive carry only question/evidence,
|
|
1450
|
+
* never a step id), so this is derived by POSITION, the same honest
|
|
1451
|
+
* correlation technique this module already uses for `afterReject`
|
|
1452
|
+
* (`getRunDetail`, above): `src/runner.js`'s `runAskSlot` writes exactly one
|
|
1453
|
+
* `verdict:'paused'` audit row per park, in the SAME real-time order the
|
|
1454
|
+
* asks themselves were parked in, and that row's own `step` field (set by
|
|
1455
|
+
* `makeAuditRow` from the step object's `emits`) names the real step. Paired
|
|
1456
|
+
* 1:1, in order, with `orderedAsks` (already sorted oldest-askedAt-first) —
|
|
1457
|
+
* NEVER when the counts disagree (a crash between the ask.json/archive write
|
|
1458
|
+
* and the audit-row write, or a pre-M4a-1 run with no paused rows at all
|
|
1459
|
+
* left to correlate): every entry gets `step:null, line:null` with a stated
|
|
1460
|
+
* why, rather than a guessed pairing. `line` is read off the matching
|
|
1461
|
+
* `declaration.steps` entry's own `fromLine` (`src/declaration.js`) — never
|
|
1462
|
+
* invented when no step matches the paused row's name.
|
|
1463
|
+
* @param {any[]} orderedAsks `runAsksInOrder`'s own return, oldest-first
|
|
1464
|
+
* @param {any[]} auditRows this run's own `audit.jsonl` rows, book order
|
|
1465
|
+
* @param {any[]|null} declSteps `readFlow(...).declaration.steps`, or null
|
|
1466
|
+
* when the flow itself didn't resolve
|
|
1467
|
+
* @returns {Array<{step:string|null, line:number|null, why:string|null}>}
|
|
1468
|
+
*/
|
|
1469
|
+
export function deriveAskStepInfo(orderedAsks, auditRows, declSteps) {
|
|
1470
|
+
const pausedRows = auditRows.filter((r) => r.verdict === 'paused');
|
|
1471
|
+
if (pausedRows.length !== orderedAsks.length) {
|
|
1472
|
+
const why = `ask count (${orderedAsks.length}) does not match this run's own "paused" audit rows (${pausedRows.length}) — step/line not determinable without guessing`;
|
|
1473
|
+
return orderedAsks.map(() => ({ step: null, line: null, why }));
|
|
1474
|
+
}
|
|
1475
|
+
return orderedAsks.map((ask, i) => {
|
|
1476
|
+
const stepEmits = typeof pausedRows[i].step === 'string' ? pausedRows[i].step : null;
|
|
1477
|
+
if (stepEmits === null) {
|
|
1478
|
+
return { step: null, line: null, why: 'this ask\'s paused audit row names no step' };
|
|
1479
|
+
}
|
|
1480
|
+
const declStep = Array.isArray(declSteps) ? declSteps.find((s) => s.emits === stepEmits) : undefined;
|
|
1481
|
+
if (!declStep || typeof declStep.fromLine !== 'number') {
|
|
1482
|
+
return { step: stepEmits, line: null, why: 'no declared step with a numbered line matches this ask\'s own step' };
|
|
1483
|
+
}
|
|
1484
|
+
return { step: stepEmits, line: declStep.fromLine, why: null };
|
|
1485
|
+
});
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/**
|
|
1489
|
+
* `GET /api/runs/:flow/:runId/asks` — the Ask tab (M4a-1 scope item 1):
|
|
1490
|
+
* every ask this run's books can name, in order, each carrying full
|
|
1491
|
+
* evidence (`readAskEvidence`'s draft + unjudged, or the pre-M4a-1 `why`).
|
|
1492
|
+
* `null` when the flow/runId doesn't resolve (caller renders 404).
|
|
1493
|
+
*
|
|
1494
|
+
* hamr's 2026-09-27 exit-check review #3: each ask also carries `index`/
|
|
1495
|
+
* `total` (its own 1-based position among this run's own asks, e.g. "2 of
|
|
1496
|
+
* 3" — a plain array position, not derived from any book) and `stepName`/
|
|
1497
|
+
* `stepLine`/`stepWhy` (`deriveAskStepInfo`) so the Ask tab's header can
|
|
1498
|
+
* name which ask is open without the client re-deriving any of it.
|
|
1499
|
+
* @param {{root: string, flow: string, runId: string, catalogue: any}} opts
|
|
1500
|
+
* @returns {{flow:string, runId:string, asks:any[]}|null}
|
|
1501
|
+
*/
|
|
1502
|
+
export function getRunAsks({
|
|
1503
|
+
root, flow, runId, catalogue,
|
|
1504
|
+
}) {
|
|
1505
|
+
const run = resolveRunPath(root, flow, runId);
|
|
1506
|
+
if (!run.ok) return null;
|
|
1507
|
+
if (!existsSync(run.runDir)) return null;
|
|
1508
|
+
const hasHistoryRow = readHistory(run.flowDir).some((r) => r && r.runId === runId);
|
|
1509
|
+
// hamr's 2026-09-27 browser-walk bug #4: the Ask tab's own asks must carry
|
|
1510
|
+
// the SAME `open`/`timeLeftMs` fields listStops already computes for the
|
|
1511
|
+
// Inbox — otherwise an open ask's Ask-tab header/body falls back to the
|
|
1512
|
+
// raw status word "unanswered" and no time-left, disagreeing with the
|
|
1513
|
+
// Inbox row for that exact same ask.
|
|
1514
|
+
const ordered = runAsksInOrder(run.runDir, hasHistoryRow);
|
|
1515
|
+
const auditRows = readAudit(run.runDir);
|
|
1516
|
+
const flowRead = readFlow({
|
|
1517
|
+
root, name: flow, catalogue,
|
|
1518
|
+
});
|
|
1519
|
+
const declSteps = flowRead.ok ? flowRead.declaration.steps : null;
|
|
1520
|
+
const stepInfo = deriveAskStepInfo(ordered, auditRows, declSteps);
|
|
1521
|
+
const asks = ordered.map((ask, i) => ({
|
|
1522
|
+
...ask,
|
|
1523
|
+
...deriveAskOpenFields(ask, hasHistoryRow),
|
|
1524
|
+
index: i + 1,
|
|
1525
|
+
total: ordered.length,
|
|
1526
|
+
stepName: stepInfo[i].step,
|
|
1527
|
+
stepLine: stepInfo[i].line,
|
|
1528
|
+
stepWhy: stepInfo[i].why,
|
|
1529
|
+
}));
|
|
1530
|
+
return { flow, runId, asks };
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
/**
|
|
1534
|
+
* `GET /api/inbox` — every stop (parked ask, open or past) across every
|
|
1535
|
+
* flow under `root` (M4a-1 scope item 1), read-only, no answer controls
|
|
1536
|
+
* (those are M4b). Sorted open-first (soonest-expiring first — the most
|
|
1537
|
+
* urgent), then every past stop newest-answered-first; a row with neither a
|
|
1538
|
+
* known time-left nor a known answeredAt sorts last within its group rather
|
|
1539
|
+
* than being guessed into either end.
|
|
1540
|
+
*
|
|
1541
|
+
* hamr's 2026-09-27 live check: a run that has ended (its flow's own
|
|
1542
|
+
* history.jsonl carries a row for it) never contributes an open/unanswered
|
|
1543
|
+
* stop, no matter what its own ask.json/archive says — `legacyRunAsks`
|
|
1544
|
+
* already refuses to rebuild a stale slot into one, but `open` is ALSO
|
|
1545
|
+
* force-`false` here as a second, independent check (belt-and-braces on the
|
|
1546
|
+
* one thing the brief calls out by name: "the Inbox tab's open count counts
|
|
1547
|
+
* only truly open asks — parked run, no history row, unexpired, unanswered").
|
|
1548
|
+
* @param {{root: string}} opts
|
|
1549
|
+
* @returns {any[]}
|
|
1550
|
+
*/
|
|
1551
|
+
export function listStops({ root }) {
|
|
1552
|
+
const rows = [];
|
|
1553
|
+
for (const flowName of listFlowNames(root)) {
|
|
1554
|
+
const flowDir = join(root, flowName);
|
|
1555
|
+
const historyRunIds = new Set(readHistory(flowDir).filter((r) => r && typeof r.runId === 'string').map((r) => r.runId));
|
|
1556
|
+
for (const runId of listRunIds(flowDir)) {
|
|
1557
|
+
const run = resolveRunPath(root, flowName, runId);
|
|
1558
|
+
if (!run.ok) continue;
|
|
1559
|
+
const hasHistoryRow = historyRunIds.has(runId);
|
|
1560
|
+
for (const ask of runAsksInOrder(run.runDir, hasHistoryRow)) {
|
|
1561
|
+
rows.push({
|
|
1562
|
+
flow: flowName,
|
|
1563
|
+
runId,
|
|
1564
|
+
...ask,
|
|
1565
|
+
...deriveAskOpenFields(ask, hasHistoryRow),
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
return rows
|
|
1571
|
+
.map((row, index) => ({ row, index }))
|
|
1572
|
+
.sort((a, b) => {
|
|
1573
|
+
if (a.row.open !== b.row.open) return a.row.open ? -1 : 1;
|
|
1574
|
+
if (a.row.open && b.row.open) {
|
|
1575
|
+
const at = typeof a.row.timeLeftMs === 'number' ? a.row.timeLeftMs : Infinity;
|
|
1576
|
+
const bt = typeof b.row.timeLeftMs === 'number' ? b.row.timeLeftMs : Infinity;
|
|
1577
|
+
if (at !== bt) return at - bt;
|
|
1578
|
+
return a.index - b.index;
|
|
1579
|
+
}
|
|
1580
|
+
const am = typeof a.row.answeredAt === 'string' ? Date.parse(a.row.answeredAt) : NaN;
|
|
1581
|
+
const bm = typeof b.row.answeredAt === 'string' ? Date.parse(b.row.answeredAt) : NaN;
|
|
1582
|
+
const aKnown = Number.isFinite(am);
|
|
1583
|
+
const bKnown = Number.isFinite(bm);
|
|
1584
|
+
if (aKnown && bKnown) return bm - am;
|
|
1585
|
+
if (aKnown !== bKnown) return aKnown ? -1 : 1;
|
|
1586
|
+
return a.index - b.index;
|
|
1587
|
+
})
|
|
1588
|
+
.map(({ row }) => row);
|
|
1589
|
+
}
|