fwdloop 0.6.0 → 0.8.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/types/flow.d.ts CHANGED
@@ -10,6 +10,141 @@
10
10
  * @returns {CheckFlowNameResult}
11
11
  */
12
12
  export function checkFlowName(name: unknown): CheckFlowNameResult;
13
+ /**
14
+ * Check a runId against the allowed shape: 1..128 characters, letters
15
+ * (upper or lower), digits, `.`, `_`, `-`, starting with a letter or digit.
16
+ * Walked character by character — never a regex — same reasoning as
17
+ * `checkFlowName`: a runId that would escape the flow's runs directory
18
+ * (`..`, a `/` or `\` segment, a NUL byte, an absolute path) is refused by
19
+ * the same loop that refuses a bad character, not a separate ad-hoc check.
20
+ *
21
+ * One writer: every caller that turns an externally-supplied runId into a
22
+ * path (`bin/fwdloop`'s `run`/`resume`, `runFlow`, `resumeRun`) goes through
23
+ * this function (via `resolveRunDir`, below) — a runId is never trusted
24
+ * enough to be joined onto a path any other way. Fixes the path escape a
25
+ * branch review found: `--run-id ../../../../tmp/pwned`.
26
+ *
27
+ * @param {unknown} runId
28
+ * @returns {{ok:true}|{ok:false,red:string}}
29
+ */
30
+ export function checkRunId(runId: unknown): {
31
+ ok: true;
32
+ } | {
33
+ ok: false;
34
+ red: string;
35
+ };
36
+ /**
37
+ * Turn a checked runId into its run directory under `flowDir/runs/`, then
38
+ * confirm the built path actually resolves INSIDE that runs directory —
39
+ * belt and braces alongside `checkRunId`'s character allow-list (mirrors
40
+ * `src/runner.js`'s own `checkSendDestination` shape: lexical containment,
41
+ * checked after the path is built, never trusted from the allow-list
42
+ * alone).
43
+ *
44
+ * Lexical containment (`path.resolve` plus a prefix compare) only catches a
45
+ * bad runId string — it does not catch a runId that *passes* the allow-list
46
+ * but names a symlink pointing outside `flowDir/runs/` (F36 fixed `runs/`
47
+ * itself being a symlink; this is the same class one level down, for an
48
+ * entry inside it). So once the lexical check passes, anything that
49
+ * actually EXISTS on disk is re-checked with `realpathSync`: `runs/` itself
50
+ * must realpath inside `flowDir` (mirrors F36's `readFlow` check), and — if
51
+ * the run dir exists — it must realpath inside the real `runs/` dir. A
52
+ * not-yet-existing run dir (a new run being created) has nothing to
53
+ * realpath yet, so only the lexical result is returned for it; the check
54
+ * holds at use time (here, on every call), not only at some earlier
55
+ * preflight.
56
+ *
57
+ * @param {string} flowDir
58
+ * @param {unknown} runId
59
+ * @returns {{ok:true, runDir:string}|{ok:false, red:string}}
60
+ */
61
+ export function resolveRunDir(flowDir: string, runId: unknown): {
62
+ ok: true;
63
+ runDir: string;
64
+ } | {
65
+ ok: false;
66
+ red: string;
67
+ };
68
+ /**
69
+ * Every flow name that has a real, readable directory under `root` — M4a
70
+ * piece 2 (docs/wiki/the-module-ladder.md M4a scope item 2: "every flow
71
+ * under --root"). A directory entry that fails `checkFlowName` (should not
72
+ * happen for anything `writeFlow` itself created, but a hand-placed or
73
+ * legacy directory is possible) is skipped rather than crashing the whole
74
+ * listing — this is a best-effort enumeration, not a validator; a caller
75
+ * that wants to know a flow is well-formed calls `readFlow` on it.
76
+ * `[]` when `root` doesn't exist or has no entries — never a thrown error.
77
+ * Sorted so a caller gets a stable, deterministic order.
78
+ * @param {string} root
79
+ * @returns {string[]}
80
+ */
81
+ export function listFlowNames(root: string): string[];
82
+ /**
83
+ * Every runId with a real, readable directory under a flow's own `runs/`
84
+ * (M4a scope item 2: "every run"). Same best-effort posture as {@link
85
+ * listFlowNames} — a malformed entry is skipped, never thrown on.
86
+ * @param {string} flowDir
87
+ * @returns {string[]}
88
+ */
89
+ export function listRunIds(flowDir: string): string[];
90
+ /**
91
+ * F48 round 3 (docs/logs/FINDINGS.md): the ONE mechanism every book reader
92
+ * in src/ and bin/ routes through to read a file that lives inside a run
93
+ * dir or flow dir — closing the symlink-escape class at the source instead
94
+ * of patching each reader a second time. `resolveInside(baseDir, relPath)`
95
+ * requires the target to both (a) not itself be a symlink and (b) realpath
96
+ * to somewhere inside `realpath(baseDir)` — the second check alone also
97
+ * catches a symlinked ANCESTOR directory partway down `relPath` (e.g.
98
+ * `asks/` itself replaced by a symlink to an outside directory), the same
99
+ * shape `readFlow`'s own `runs/` check and `resolveRunDir` already apply one
100
+ * level up. A path that does not exist yet is reported as `missing: true`
101
+ * (never a red) so every existing caller keeps its own "not written yet"
102
+ * behaviour unchanged.
103
+ *
104
+ * @param {string} baseDir
105
+ * @param {string} relPath
106
+ * @returns {{ok:true, full:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
107
+ */
108
+ export function resolveInside(baseDir: string, relPath: string): {
109
+ ok: true;
110
+ full: string;
111
+ } | {
112
+ ok: false;
113
+ missing: true;
114
+ } | {
115
+ ok: false;
116
+ missing: false;
117
+ red: string;
118
+ };
119
+ /**
120
+ * `resolveInside` plus the actual read — every raw-text book reader's one
121
+ * gateway. Same result shape as `resolveInside`, plus `{ok:true, text}`.
122
+ * @param {string} baseDir
123
+ * @param {string} relPath
124
+ * @returns {{ok:true, text:string}|{ok:false, missing:true}|{ok:false, missing:false, red:string}}
125
+ */
126
+ export function readFileInside(baseDir: string, relPath: string): {
127
+ ok: true;
128
+ text: string;
129
+ } | {
130
+ ok: false;
131
+ missing: true;
132
+ } | {
133
+ ok: false;
134
+ missing: false;
135
+ red: string;
136
+ };
137
+ /**
138
+ * `readdirSync` guarded the same way: refuses (returns `[]`) when `relDir`
139
+ * itself is a symlink or resolves outside `baseDir`, and skips (never
140
+ * follows) any individual entry that is itself a symlink — a directory
141
+ * listing must never hand a caller a name that, joined back onto `relDir`,
142
+ * would escape `baseDir`. `[]` when `relDir` doesn't exist.
143
+ * @param {string} baseDir
144
+ * @param {string} relDir
145
+ * @returns {string[]}
146
+ */
147
+ export function readdirInside(baseDir: string, relDir: string): string[];
13
148
  /**
14
149
  * Write a signed flow to `<root>/<name>/`. Refuses (writing nothing) if the
15
150
  * flow name is invalid, if `proseText`/`declaration` don't parse/validate,
package/types/index.d.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  export { closeByClass } from "./closers.js";
2
+ export { readSpendRows } from "./provider.js";
2
3
  export { parseSignedText, ARBITER_FIELDS } from "./signed-text.js";
3
4
  export { signFlow, verifyFlow, canonicalBytes, SIGNATURE_FIELDS } from "./signature.js";
4
5
  export { validateDeclaration, DECLARATION_FIELDS } from "./declaration.js";
5
6
  export { parseCatalogue, loadCatalogue, menu, primitiveFor, resolveEntry, CATALOGUE_FIELDS } from "./catalogue.js";
6
- export { checkFlowName, writeFlow, readFlow, FLOW_FILES } from "./flow.js";
7
- export { runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS } from "./runner.js";
8
- export { makeFileAskStep, answerAsk } from "./ask.js";
7
+ export { checkFlowName, checkRunId, resolveRunDir, writeFlow, readFlow, listFlowNames, listRunIds, FLOW_FILES } from "./flow.js";
8
+ export { runFlow, resumeRun, makeParkingAskStep, STRIKE_LIMIT, MAX_ATTEMPTS, readAsk, readRunState, readLog } from "./runner.js";
9
+ export { makeFileAskStep, answerAsk, readAskEvidence, writeAskArchive, listArchivedAsks } from "./ask.js";
10
+ export { appendAudit, appendHistory, readAudit, readHistory, auditRowTokens, auditRowTools } from "./books.js";
@@ -0,0 +1,14 @@
1
+ /**
2
+ * @param {Array<{kind?:string, role:string, path:string}>} sources arbiter.sources
3
+ * @returns {{ok:boolean, inputFacts:Record<string,string[]>, info:string[], reds:string[]}}
4
+ */
5
+ export function readInputFacts(sources: Array<{
6
+ kind?: string;
7
+ role: string;
8
+ path: string;
9
+ }>): {
10
+ ok: boolean;
11
+ inputFacts: Record<string, string[]>;
12
+ info: string[];
13
+ reds: string[];
14
+ };
@@ -0,0 +1,433 @@
1
+ /**
2
+ * The glyph + human-words label for one run — ported verbatim (in spirit,
3
+ * from real derivation, not a shortcut) from `poc/m4/panel-data.mjs`'s
4
+ * `computeGlyph`, the derivation the M4a POC proved against every real run
5
+ * on disk. Ladder wording (M4a scope item 4):
6
+ * - `[✓]` passed — a history row with `outcome:'complete'`.
7
+ * - `[✗]` failed — a history row with any other outcome (never `[?]`).
8
+ * - `[·]` waiting on you — parked (`ask.json` present), no consumed answer,
9
+ * NOT past its own `expiresAt`.
10
+ * - `[!]` ask expired, not resumed yet — parked, no consumed answer, but
11
+ * its own `expiresAt` is already past (hamr's 2026-09-27 browser-walk bug
12
+ * #3: the runs list/header glyph disagreed with the Inbox, which already
13
+ * reports `expired` correctly off the exact same `askJson.expiresAt` —
14
+ * `[!]` is not in the ladder's signed M4a vocabulary; picked here as an
15
+ * honest fourth state, distinct from every signed glyph, pending a
16
+ * ruling — see the report). Never `[·]` waiting (nobody can still answer
17
+ * it in time), never `[✗]` (the run itself never failed a check), never
18
+ * `[?]` (the books DO know what happened here).
19
+ * - `[·]` answered, not resumed yet — parked, a consumed answer exists, but
20
+ * no history row yet (resume hasn't finished) — always in words, never
21
+ * the same line as "waiting on you", never `[?]`.
22
+ * - `[?]` died / unknown — no history row, no open ask, no consumed answer:
23
+ * `resume.lock` carries no pid and nothing checks liveness (M4a's own
24
+ * open POC question), so a crashed resumer and a live one look the same
25
+ * on disk. Never guessed into `[✗]` or `[✓]`.
26
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean}} ctx
27
+ * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[?]', label: string}}
28
+ */
29
+ export function computeGlyph({ historyRow, askJson, consumedAnswerExists, hasStateJson, }: {
30
+ historyRow: any;
31
+ askJson: any;
32
+ consumedAnswerExists: boolean;
33
+ hasStateJson: boolean;
34
+ }): {
35
+ glyph: "[\u2713]" | "[\u2717]" | "[\u00B7]" | "[!]" | "[?]";
36
+ label: string;
37
+ };
38
+ /**
39
+ * "$X.XXXX" or, when the book itself says the number is a floor
40
+ * (`spendComplete:false`), "at least $X.XXXX" — never a bare total presented
41
+ * as complete when it isn't (negative scenario iv), and never `$0` standing
42
+ * in for a missing/unknown number (project rule).
43
+ * @param {number|null|undefined} spentUsd
44
+ * @param {boolean|undefined} spendComplete
45
+ * @returns {{ok:true, display:string}|{ok:false, why:string}}
46
+ */
47
+ export function costDisplay(spentUsd: number | null | undefined, spendComplete: boolean | undefined): {
48
+ ok: true;
49
+ display: string;
50
+ } | {
51
+ ok: false;
52
+ why: string;
53
+ };
54
+ /**
55
+ * The model this run's own book rows actually name — hamr's review #1/#7:
56
+ * no `declaration.json`/`signature.json` field records a model at all (the
57
+ * flow's steps carry primitives and a close class, never a model choice),
58
+ * so `audit.jsonl`'s own per-attempt `model` field (`src/books.js`'s
59
+ * `appendAudit` row shape) is the ONLY book that can answer "what model did
60
+ * this run use" — never invented, never defaulted to a catalogue/provider
61
+ * default the run may not have actually hit. Reads book order BACKWARDS and
62
+ * returns the LAST row that names a model (the most recent attempt's own
63
+ * choice), so a run that changed model slot mid-run (would show as a
64
+ * `modelMatch:"substituted"` row) still reports what actually ran last,
65
+ * never a stale first-attempt value. `null` (never a guess) when no row in
66
+ * this run ever named one (e.g. every step is `hitl`, no model step ran).
67
+ * No provider/API-kind field exists in ANY book (`src/provider.js`'s
68
+ * `PROVIDER_SLOTS` maps a slot name to a model, but nothing writes which
69
+ * slot served a given run back to `audit.jsonl`/`spend.jsonl`) — provider is
70
+ * never shown alongside it (hamr's own instruction: "if the provider isn't
71
+ * in any book, show model only").
72
+ * @param {any[]} auditRows
73
+ * @returns {string|null}
74
+ */
75
+ export function deriveRunModel(auditRows: any[]): string | null;
76
+ /**
77
+ * The Audit tab's "Action" column (hamr's review #6, tightened by hamr's
78
+ * 2026-09-27 live check): exactly three words, derived STRICTLY from a
79
+ * row's own fields — never the step name/id, never a model name, never
80
+ * "unknown action":
81
+ * - "model call" — a row with a non-empty `model` field (the model itself
82
+ * still shows in the Cost/Verdict area elsewhere; this column names only
83
+ * the KIND of action).
84
+ * - "human" — an ask-slot row: `src/runner.js`'s `runAskSlot` is the ONLY
85
+ * place that ever passes a third argument (`unjudgedCount`) into
86
+ * `recordAudit`, so `Object.prototype.hasOwnProperty.call(row,
87
+ * 'unjudgedCount')` is true for exactly that step's own rows (paused,
88
+ * and the human's own accept/reject/rerun/refused answers) and false for
89
+ * every other row shape in the book — a real, always-present marker
90
+ * (`unjudgedCount` is a number, 0 included, never omitted on an ask row),
91
+ * never the step's close class (a NON-ask hitl step, e.g. a plain write
92
+ * step, is ALSO `class:'hitl'` — that was the exact bug this replaces:
93
+ * class alone can't tell "the ask" apart from "any other hitl step").
94
+ * - "no model call" — everything else: a mechanical green/not-done/red
95
+ * close, a cap-halt, a send confirmation, a non-ask hitl pass-through
96
+ * (e.g. a write step) — no model ran and no human answered THIS row.
97
+ * @param {any} row one `audit.jsonl` row
98
+ * @returns {'model call'|'human'|'no model call'}
99
+ */
100
+ export function deriveAuditAction(row: any): "model call" | "human" | "no model call";
101
+ /**
102
+ * The Audit tab's Cost cell token phrase (hamr's 2026-09-27 review item c):
103
+ * a per-ROW token total, read through `auditRowTokens` (`src/books.js`) so
104
+ * this module never re-derives "was this row written before M4a-2" itself.
105
+ * Three honest outcomes, never folded into one another:
106
+ * - `{kind:'total', total}` — a real (post-M4a-2) model-call row: `total`
107
+ * sums ALL three fields the row's own `tokens` object carries
108
+ * (`inputTokens + outputTokens + cacheReadTokens`) — every token this
109
+ * row's call actually touched, cache-read included (labelled plainly as
110
+ * "N tokens", never split out here; a cache-read token is still a token
111
+ * the call processed, so folding it into the total is the honest sum,
112
+ * not a hidden discount).
113
+ * - `{kind:'not-recorded'}` — a row written before Amendment M4a-2 (no
114
+ * `tokens` key at all) — shown as "tokens not recorded", never a 0 or a
115
+ * blank.
116
+ * - `{kind:'no-model'}` — a post-M4a-2 row that genuinely carries no model
117
+ * call (`tokens:null`, `model:null` — an ask/hitl row) — the tokens
118
+ * phrase is omitted entirely rather than shown as "0 tokens" or "not
119
+ * recorded" (there was never anything to record).
120
+ * @param {any} row one `audit.jsonl` row
121
+ * @returns {{kind:'total', total:number}|{kind:'not-recorded'}|{kind:'no-model'}}
122
+ */
123
+ export function deriveAuditTokensDisplay(row: any): {
124
+ kind: "total";
125
+ total: number;
126
+ } | {
127
+ kind: "not-recorded";
128
+ } | {
129
+ kind: "no-model";
130
+ };
131
+ /**
132
+ * hamr's request (Amendment M4a-3): the Audit tab's Action cell gets a
133
+ * one-line tool tally appended for a MODEL-call row whose own `tools` was
134
+ * actually recorded (Amendment M4a-3) — `", read 3, write 1"` — read
135
+ * straight through `auditRowTools` (`src/books.js`), never re-derived. Three
136
+ * honest outcomes, matching `deriveAuditTokensDisplay`'s own shape exactly:
137
+ * `null` for a non-model row (nothing to append — a human/no-model-call row
138
+ * never claims a tool tally), `null` for a pre-M4a-3 model row (`why` set —
139
+ * appending nothing beats guessing a tally that was never recorded), and a
140
+ * real phrase, sorted by count desc then name, for a model row that DOES
141
+ * carry `tools` (including `{}` — zero tool calls that round — which still
142
+ * returns `null`: there is nothing to list, so nothing is appended).
143
+ * @param {any} row one `audit.jsonl` row
144
+ * @returns {string|null}
145
+ */
146
+ export function deriveAuditToolsPhrase(row: any): string | null;
147
+ /**
148
+ * The Audit tab's new Time column (hamr's 2026-09-27 review item d): this
149
+ * row's own `why` when `at` predates Amendment M4a-2, else `null` (the row
150
+ * DOES carry a real `at` — the client formats it with `readableDateTime`,
151
+ * the same local-time formatter every other timestamp on this page already
152
+ * uses; formatting to the viewer's own locale belongs in the browser, not
153
+ * here). Read through `auditRowAt` (`src/books.js`) — never re-derived.
154
+ * @param {any} row one `audit.jsonl` row
155
+ * @returns {string|null}
156
+ */
157
+ export function deriveAuditAtWhy(row: any): string | null;
158
+ export function isBlockedVerdict(verdict: any): boolean;
159
+ /**
160
+ * One mark per try, in try order — mirrors `computeTryCount`'s own pairing
161
+ * exactly (a `hitl` step's `paused` row plus its next resolving row is ONE
162
+ * try; every other step's own row is ONE try each) so a group header's
163
+ * `tryMarks.length` always equals its own `tryCount`. A `paused` row with no
164
+ * resolution yet in this run's own book order keeps its `·` mark (still
165
+ * open, not resolved).
166
+ * @param {string|null} closeClass
167
+ * @param {Array<{verdict:string}>} rows one step's own audit rows, book order
168
+ * @returns {Array<'✓'|'✗'|'·'>}
169
+ */
170
+ export function deriveStepTryMarks(closeClass: string | null, rows: Array<{
171
+ verdict: string;
172
+ }>): Array<"\u2713" | "\u2717" | "\u00B7">;
173
+ /**
174
+ * A step group's own state word for the Audit tab's collapsed header —
175
+ * the SAME rule `src/panel/index.html`'s client-side `stepBoxState` already
176
+ * applies to the Run tab's map/cards (ported here so the Audit header can
177
+ * be computed server-side too, off the SAME last-row-wins logic): `waiting`
178
+ * (the run is currently parked on this step — its last attempt's verdict is
179
+ * `paused`/`refused`), `done` (the last attempt passed — `green`/`hitl`),
180
+ * `stopped` (the last attempt failed for any other reason). A group only
181
+ * ever exists for a step with at least one row, so `pending` never appears
182
+ * here (unlike the Run tab's map, which also covers never-attempted steps).
183
+ * @param {Array<{verdict:string}>} rows one step's own audit rows, book order
184
+ * @returns {'done'|'waiting'|'stopped'}
185
+ */
186
+ export function deriveStepGroupState(rows: Array<{
187
+ verdict: string;
188
+ }>): "done" | "waiting" | "stopped";
189
+ /**
190
+ * hamr's 2026-09-27 exit-check review #1: the Audit tab's grouped-by-step
191
+ * header pieces, computed HERE (server-side) so `src/panel/index.html` only
192
+ * ever renders them, never re-derives them. One entry per step, first-seen
193
+ * order preserved (never re-sorted): `step` (the emits id, the header IS the
194
+ * step's own name — no separate Step column in Grouped view), `state`
195
+ * (`deriveStepGroupState`), `closeClass`, `timeMs` (this step's own attempts'
196
+ * `wallMs` summed — "total time from wallMs", never a guess), `cost`/
197
+ * `costWhy` (a bare `$X` sum when every priced row is complete, `"at least
198
+ * $X"` when any priced row in this step is a floor, `null`+why when no row
199
+ * in this step has ever priced), `tokensTotal` (the sum of every row's own
200
+ * token total, ONLY when every row in the step either carries real
201
+ * (post-M4a-2) tokens or genuinely made no model call — one row missing
202
+ * tokens (a pre-M4a-2 row) means the WHOLE step's total is withheld, never a
203
+ * partial sum shown as complete; `null` also when the step made no model
204
+ * call at all, nothing to sum), `toolsTotal`/`toolsWhy`/`ungranted`
205
+ * (Amendment M4a-3, `summarizeStepTools` — the same "no partial sum" honesty
206
+ * rule as `tokensTotal`, plus the deduped union of every row's own
207
+ * `ungranted` calls), `tryCount`/`tryMarks` (`deriveStepTryMarks`),
208
+ * `rows` (this step's own enriched audit rows, for the group's own table —
209
+ * never a second, separately-filtered copy on the client).
210
+ * @param {any[]} enrichedRows `getRunAudit`'s own rows, already carrying
211
+ * `action`/`tokensDisplay`/`atWhy`/`blocked` (this function never
212
+ * re-derives any of those, only groups and sums them)
213
+ * @returns {any[]}
214
+ */
215
+ export function deriveAuditGroups(enrichedRows: any[]): any[];
216
+ /**
217
+ * Run-level totals from `spend.jsonl` (hamr's review #1): rounds, input/
218
+ * output/cache-read tokens — shown ONLY as a run-wide sum, never attributed
219
+ * to a step (a spend row carries no `step` field at all — `src/model-step.js`
220
+ * appends it before any step identity is threaded through, so per-step
221
+ * attribution would be invented, not read). Honest about partial data: a
222
+ * field this run's rows never populated (e.g. no row ever carried
223
+ * `tokens.cacheReadTokens`) is `null` with its own `*Why`, never folded into
224
+ * a 0. `null` `rows`/`empty:true` (with a why) when spend.jsonl has no rows
225
+ * at all yet.
226
+ * @param {any[]} spendRows
227
+ * @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}}
228
+ */
229
+ export function summarizeSpendRows(spendRows: any[]): {
230
+ empty: true;
231
+ why: string;
232
+ } | {
233
+ empty: false;
234
+ rounds: number;
235
+ tokensIn: number | null;
236
+ tokensInWhy: string | null;
237
+ tokensOut: number | null;
238
+ tokensOutWhy: string | null;
239
+ cacheReadTokens: number | null;
240
+ cacheReadTokensWhy: string | null;
241
+ };
242
+ /**
243
+ * `GET /api/runs` — every flow under `root`, every run under each flow
244
+ * (M4a scope item 2). A flow with zero runs still gets one row (`runId:
245
+ * null`, an explicit `why`) — no flow is silently missing from the list.
246
+ * Newest-first by history `at` where known; a row with no history row (died
247
+ * or still parked) sorts after every row that has one, in flow/run order
248
+ * (a real ordering, never `Date.now()` guessed in for a missing `at`).
249
+ * @param {{root: string, catalogue: any}} opts
250
+ * @returns {any[]}
251
+ */
252
+ export function listRuns({ root, catalogue }: {
253
+ root: string;
254
+ catalogue: any;
255
+ }): any[];
256
+ /**
257
+ * `GET /api/runs/:flow/:runId` — the Run tab (M4a scope item 2): the step
258
+ * map from `declaration.steps`, step cards -> attempts from `audit.jsonl`
259
+ * (verdict, gap, cost, model, strike), and what the model wrote from
260
+ * `log.json`. `null` when the flow/runId doesn't resolve to a real run
261
+ * directory at all (caller renders 404); a `red` field names why a
262
+ * sub-derivation couldn't fill (never invented).
263
+ * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
264
+ * @returns {any|null}
265
+ */
266
+ export function getRunDetail({ root, flow, runId, catalogue, }: {
267
+ root: string;
268
+ flow: string;
269
+ runId: string;
270
+ catalogue: any;
271
+ }): any | null;
272
+ /**
273
+ * `GET /api/runs/:flow/:runId/audit` — the Audit/logs tab (M4a scope item
274
+ * 2): the raw `audit.jsonl` rows, scoped strictly to this run (each run's
275
+ * own `audit.jsonl` file already carries only its own rows — there is no
276
+ * shared-sidecar contamination risk here the way bareloop's gate-audit
277
+ * sidecar had). `null` when the flow/runId doesn't resolve (404).
278
+ * @param {{root: string, flow: string, runId: string}} opts
279
+ * @returns {{flow:string, runId:string, rows:any[], groups:any[], empty:boolean, why:string|null}|null}
280
+ */
281
+ export function getRunAudit({ root, flow, runId }: {
282
+ root: string;
283
+ flow: string;
284
+ runId: string;
285
+ }): {
286
+ flow: string;
287
+ runId: string;
288
+ rows: any[];
289
+ groups: any[];
290
+ empty: boolean;
291
+ why: string | null;
292
+ } | null;
293
+ /**
294
+ * `GET /api/runs/:flow/:runId/job` — the Job tab (M4a scope item 2): the
295
+ * signed prose, the arbiter block (cap, asks with TTL, redo cap, sends,
296
+ * sources), and the signature (who, when, hash). Derived purely from the
297
+ * flow's own signed files (`readFlow`) — fwdloop always has exactly one
298
+ * signed `declaration.json` + `signature.json` per flow, so there is no
299
+ * multi-source provenance chain to resolve (unlike bareloop's `getRunJob` —
300
+ * DROPPED per the fit-check). `runId` is only used to confirm the run
301
+ * exists at all; `null` when it doesn't (404).
302
+ * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
303
+ * @returns {any|null}
304
+ */
305
+ /**
306
+ * hamr's 2026-09-27 exit-check review #5: one plain-words sentence for a
307
+ * declared step's own close rule — the Job tab's "Success" field. Derived
308
+ * STRICTLY from `step.close` (and, for the "your accept" wording, whether
309
+ * this step is the one line `arbiter.asks[]` itself binds to) — never a
310
+ * fabricated cite/shape value:
311
+ * - `hitl`: "human check", or "human check (your accept)" when this step's
312
+ * own `fromLine` is a signed ask line (the ask step itself — the one a
313
+ * human pauses a run on, distinct from an ordinary hitl pass-through
314
+ * step with no ask binding).
315
+ * - `softgreen`: "shape: N headings (a / b / c)" when `close.shape.sections`
316
+ * is signed, "max W words" appended when `close.shape.maxWords` is
317
+ * signed, "blocks of L lines" / "must carry: a, b" for the invoice-block
318
+ * shape keys (`linesPerInvoice`/`mustCarry`) — every signed shape key
319
+ * shown, nothing invented; "shape (no shape rules signed)" when a
320
+ * softgreen step signs no `close.shape` at all (declaration.js allows
321
+ * this — an empty/absent shape is not itself a red).
322
+ * - `green`: "cited" — `CLOSE_ALLOWED` (`src/declaration.js`) never lets a
323
+ * step declare WHAT it cites ahead of time (that's the drafted
324
+ * artifact's own per-run field data, not signed prose), so there is
325
+ * never anything honest to append here.
326
+ * - anything else: the raw class name, named as unknown, never silently
327
+ * dropped or guessed into one of the three above; no class at all names
328
+ * that plainly too.
329
+ * @param {{close?: {class?: string, shape?: any}, fromLine?: number|null}} step one `declaration.steps` entry
330
+ * @param {Array<{line:number}>} arbiterAsks `arbiter.asks`, for the "your accept" check
331
+ * @returns {string}
332
+ */
333
+ export function deriveStepSuccessText(step: {
334
+ close?: {
335
+ class?: string;
336
+ shape?: any;
337
+ };
338
+ fromLine?: number | null;
339
+ }, arbiterAsks: Array<{
340
+ line: number;
341
+ }>): string;
342
+ /**
343
+ * `GET /api/runs/:flow/:runId/job` — the Job tab (hamr's 2026-09-27
344
+ * exit-check review #5: bareloop-style one-field-per-piece layout,
345
+ * replacing the old split asks/sends/sources/signed-lines blocks). Every
346
+ * field is read straight off `readFlow`'s own signed declaration.json/
347
+ * signature.json/prose lines — nothing invented; a piece the books can't
348
+ * name carries its own why, never a blank or a guess. Field order (server
349
+ * order matches the page's own render order): prose, asks, model, cap
350
+ * (+redo cap), sources, sends, guardrails, success (one row per step, off
351
+ * `deriveStepSuccessText`), signature.
352
+ * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
353
+ * @returns {any|null}
354
+ */
355
+ export function getRunJob({ root, flow, runId, catalogue, }: {
356
+ root: string;
357
+ flow: string;
358
+ runId: string;
359
+ catalogue: any;
360
+ }): any | null;
361
+ /**
362
+ * hamr's 2026-09-27 exit-check review #3: which declared step (and its
363
+ * signed prose line) each ask in `orderedAsks` belongs to — no book field
364
+ * names this directly (`ask.json`/the archive carry only question/evidence,
365
+ * never a step id), so this is derived by POSITION, the same honest
366
+ * correlation technique this module already uses for `afterReject`
367
+ * (`getRunDetail`, above): `src/runner.js`'s `runAskSlot` writes exactly one
368
+ * `verdict:'paused'` audit row per park, in the SAME real-time order the
369
+ * asks themselves were parked in, and that row's own `step` field (set by
370
+ * `makeAuditRow` from the step object's `emits`) names the real step. Paired
371
+ * 1:1, in order, with `orderedAsks` (already sorted oldest-askedAt-first) —
372
+ * NEVER when the counts disagree (a crash between the ask.json/archive write
373
+ * and the audit-row write, or a pre-M4a-1 run with no paused rows at all
374
+ * left to correlate): every entry gets `step:null, line:null` with a stated
375
+ * why, rather than a guessed pairing. `line` is read off the matching
376
+ * `declaration.steps` entry's own `fromLine` (`src/declaration.js`) — never
377
+ * invented when no step matches the paused row's name.
378
+ * @param {any[]} orderedAsks `runAsksInOrder`'s own return, oldest-first
379
+ * @param {any[]} auditRows this run's own `audit.jsonl` rows, book order
380
+ * @param {any[]|null} declSteps `readFlow(...).declaration.steps`, or null
381
+ * when the flow itself didn't resolve
382
+ * @returns {Array<{step:string|null, line:number|null, why:string|null}>}
383
+ */
384
+ export function deriveAskStepInfo(orderedAsks: any[], auditRows: any[], declSteps: any[] | null): Array<{
385
+ step: string | null;
386
+ line: number | null;
387
+ why: string | null;
388
+ }>;
389
+ /**
390
+ * `GET /api/runs/:flow/:runId/asks` — the Ask tab (M4a-1 scope item 1):
391
+ * every ask this run's books can name, in order, each carrying full
392
+ * evidence (`readAskEvidence`'s draft + unjudged, or the pre-M4a-1 `why`).
393
+ * `null` when the flow/runId doesn't resolve (caller renders 404).
394
+ *
395
+ * hamr's 2026-09-27 exit-check review #3: each ask also carries `index`/
396
+ * `total` (its own 1-based position among this run's own asks, e.g. "2 of
397
+ * 3" — a plain array position, not derived from any book) and `stepName`/
398
+ * `stepLine`/`stepWhy` (`deriveAskStepInfo`) so the Ask tab's header can
399
+ * name which ask is open without the client re-deriving any of it.
400
+ * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
401
+ * @returns {{flow:string, runId:string, asks:any[]}|null}
402
+ */
403
+ export function getRunAsks({ root, flow, runId, catalogue, }: {
404
+ root: string;
405
+ flow: string;
406
+ runId: string;
407
+ catalogue: any;
408
+ }): {
409
+ flow: string;
410
+ runId: string;
411
+ asks: any[];
412
+ } | null;
413
+ /**
414
+ * `GET /api/inbox` — every stop (parked ask, open or past) across every
415
+ * flow under `root` (M4a-1 scope item 1), read-only, no answer controls
416
+ * (those are M4b). Sorted open-first (soonest-expiring first — the most
417
+ * urgent), then every past stop newest-answered-first; a row with neither a
418
+ * known time-left nor a known answeredAt sorts last within its group rather
419
+ * than being guessed into either end.
420
+ *
421
+ * hamr's 2026-09-27 live check: a run that has ended (its flow's own
422
+ * history.jsonl carries a row for it) never contributes an open/unanswered
423
+ * stop, no matter what its own ask.json/archive says — `legacyRunAsks`
424
+ * already refuses to rebuild a stale slot into one, but `open` is ALSO
425
+ * force-`false` here as a second, independent check (belt-and-braces on the
426
+ * one thing the brief calls out by name: "the Inbox tab's open count counts
427
+ * only truly open asks — parked run, no history row, unexpired, unanswered").
428
+ * @param {{root: string}} opts
429
+ * @returns {any[]}
430
+ */
431
+ export function listStops({ root }: {
432
+ root: string;
433
+ }): any[];
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Handle one request against the read-only API + the page. Exported
3
+ * separately from {@link createPanelServer} so tests can drive it without a
4
+ * real listening socket where that is simpler.
5
+ * @param {import('node:http').IncomingMessage} req
6
+ * @param {import('node:http').ServerResponse} res
7
+ * @param {{ root: string, port: number }} opts
8
+ */
9
+ export function handleRequest(req: import("node:http").IncomingMessage, res: import("node:http").ServerResponse, opts: {
10
+ root: string;
11
+ port: number;
12
+ }): void;
13
+ /**
14
+ * Start the panel server. Binds `127.0.0.1` ONLY. A taken port is a LOUD,
15
+ * non-zero-exit failure — this never falls back to another port (see file
16
+ * header). Resolves once actually listening; rejects on a bind error
17
+ * (including `EADDRINUSE`) with a `.port` field on the error for the
18
+ * caller's message.
19
+ * @param {{ port?: number, root: string }} opts
20
+ * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
21
+ */
22
+ export function createPanelServer(opts: {
23
+ port?: number;
24
+ root: string;
25
+ }): Promise<{
26
+ server: import("node:http").Server;
27
+ port: number;
28
+ close: () => Promise<void>;
29
+ }>;
30
+ /**
31
+ * `fwdloop panel [--port N] [--root <dir>]` — the CLI entry (`bin/fwdloop`
32
+ * dispatch). Never picks a different port on collision (see file header):
33
+ * prints a loud, named error to stderr and returns 1.
34
+ * @param {string[]} argv
35
+ * @param {{ out: (s: string) => void, err: (s: string) => void }} ctx
36
+ * @returns {Promise<number>}
37
+ */
38
+ export function panelMain(argv: string[], ctx: {
39
+ out: (s: string) => void;
40
+ err: (s: string) => void;
41
+ }): Promise<number>;
42
+ /** Default bind port. Ruling, hamr 2026-09-27: fwdloop's panel default port
43
+ * is 4800 — bareloop owns 4700, and the two panels must be able to run
44
+ * side by side. */
45
+ export const DEFAULT_PORT: 4800;