fwdloop 0.9.0 → 0.11.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/src/panel/data.js CHANGED
@@ -28,20 +28,25 @@ import {
28
28
  readFlow, listFlowNames, listRunIds, resolveRunDir, checkFlowName, readFileInside, readdirInside,
29
29
  } from '../flow.js';
30
30
  import {
31
- readAudit, readHistory, auditRowTokens, auditRowAt, auditRowTools,
31
+ readAudit, readHistory, readPidRows, auditRowTokens, auditRowAt, auditRowTools,
32
32
  } from '../books.js';
33
33
  import { readAsk, readRunState, readLog } from '../runner.js';
34
34
  import { readSpendRows } from '../provider.js';
35
35
  import {
36
- readAskEvidence, listArchivedAsks, normalizeDecision, DECISION_STATUS,
36
+ runLiveness, booksFresh, readResumeLock,
37
+ } from '../liveness.js';
38
+ import {
39
+ readAskEvidence, listArchivedAsks, normalizeDecision, DECISION_STATUS, decisionStatus, answerTiming,
37
40
  } from '../ask.js';
38
41
 
39
42
  /** `{ ok:false, red }` result shape every exported function here can return
40
43
  * instead of throwing — the server maps this to a 4xx, never a crash.
44
+ * `why` is an optional machine reason the server can branch on (never matched from `red`).
41
45
  * @param {string} red
42
- * @returns {{ok:false, red:string}} */
43
- function refuse(red) {
44
- return { ok: false, red };
46
+ * @param {'outside-root'} [why]
47
+ * @returns {{ok:false, red:string, why?:'outside-root'}} */
48
+ function refuse(red, why) {
49
+ return why ? { ok: false, red, why } : { ok: false, red };
45
50
  }
46
51
 
47
52
  /**
@@ -60,9 +65,9 @@ function refuse(red) {
60
65
  * Returns the flow directory, or a refusal.
61
66
  * @param {string} root
62
67
  * @param {string} flowName
63
- * @returns {{ok:true, flowDir:string}|{ok:false, red:string}}
68
+ * @returns {{ok:true, flowDir:string}|{ok:false, red:string, why?:'outside-root'}}
64
69
  */
65
- function resolveFlowDir(root, flowName) {
70
+ export function resolveFlowDir(root, flowName) {
66
71
  const check = checkFlowName(flowName);
67
72
  if (!check.ok) return refuse(check.red);
68
73
  const flowDir = join(root, flowName);
@@ -72,11 +77,11 @@ function resolveFlowDir(root, flowName) {
72
77
  try {
73
78
  realFlowDir = realpathSync(flowDir);
74
79
  realRoot = realpathSync(root);
75
- } catch (err) {
76
- return refuse(`flow: could not resolve "${flowDir}" — ${err.message}`);
80
+ } catch {
81
+ return refuse(`flow: could not resolve "${flowName}"`);
77
82
  }
78
83
  if (realFlowDir !== realRoot && !realFlowDir.startsWith(realRoot + sep)) {
79
- return refuse(`flow: "${flowName}" is a symlink that resolves outside root (${realFlowDir}) — refused`);
84
+ return refuse(`flow: "${flowName}" is a symlink that resolves outside root — refused`, 'outside-root');
80
85
  }
81
86
  }
82
87
  return { ok: true, flowDir };
@@ -114,7 +119,7 @@ function resolveRunPath(root, flowName, runId) {
114
119
  * @param {string|null} askId the open ask's own askId
115
120
  * @returns {boolean}
116
121
  */
117
- function hasConsumedAnswer(runDir, askId) {
122
+ export function hasConsumedAnswer(runDir, askId) {
118
123
  if (!existsSync(runDir) || typeof askId !== 'string' || askId.length === 0) return false;
119
124
  // F48 round 3: `readdirInside` (`src/flow.js`) skips a symlinked entry
120
125
  // rather than reporting its name — a run dir cannot be made to show a
@@ -130,7 +135,7 @@ function hasConsumedAnswer(runDir, askId) {
130
135
  * through `readFileInside` (a symlinked file is "none"). `null` when there is
131
136
  * none or it is unreadable/unparseable or names no askId.
132
137
  * @param {string} runDir
133
- * @returns {{askId: string, decision: string|null}|null}
138
+ * @returns {{askId: string, decision: string|null, answeredAt: string|null}|null}
134
139
  */
135
140
  export function readSavedAnswer(runDir) {
136
141
  const r = readFileInside(runDir, 'answer.json');
@@ -138,7 +143,11 @@ export function readSavedAnswer(runDir) {
138
143
  try {
139
144
  const a = JSON.parse(r.text);
140
145
  if (a && typeof a.askId === 'string' && a.askId.length > 0) {
141
- return { askId: a.askId, decision: typeof a.decision === 'string' ? normalizeDecision(a.decision) : null };
146
+ return {
147
+ askId: a.askId,
148
+ decision: typeof a.decision === 'string' ? normalizeDecision(a.decision) : null,
149
+ answeredAt: typeof a.answeredAt === 'string' ? a.answeredAt : null,
150
+ };
142
151
  }
143
152
  } catch { /* unparseable: not a usable answer */ }
144
153
  return null;
@@ -150,30 +159,43 @@ export const RESUME_REASON_UNKNOWN = 'reason unknown: the panel restarted, so it
150
159
 
151
160
  /**
152
161
  * M4b amendment 1 scope 2: the ONE derivation of "answer saved, resume not
153
- * started". From the books: an answer saved (`answer.json` present) and so
154
- * unconsumed. From the panel's in-memory attempt record (`attempt`, may be
162
+ * started" (now worded "your answer is saved; the run stopped before using it" — M4c-fix amendment 3 (c)).
163
+ * From the books: an answer saved (`answer.json` present) and so unconsumed. From the panel's in-memory attempt record (`attempt`, may be
155
164
  * null): whether a resume is still being started, and the resume's own refusal.
156
165
  * `null` when there is nothing to say (no saved answer and no attempt).
157
- * @param {{savedAnswer: {askId:string, decision:string|null}|null, attempt: any}} ctx
158
- * @returns {{state: 'starting'|'not-started'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
166
+ * M4c amendment 3: `ask` (the run's open `ask.json`, may be null; its `expiresAt` is the effective deadline). A saved
167
+ * answer for that ask that was NOT saved in time, once the deadline has passed, is not a resumable answer: it reads
168
+ * as none, so the ask is expired and offers the reopen (M4c-fix amendment 1 (b)). One with no readable time, before
169
+ * the deadline, reads `broken` (amendment 1 (a)).
170
+ * @param {{savedAnswer: {askId:string, decision:string|null, answeredAt?:string|null}|null, attempt: any, ask?: any}} ctx
171
+ * @returns {{state: 'starting'|'not-started'|'broken'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
159
172
  */
160
- export function deriveResumeState({ savedAnswer, attempt }) {
173
+ export function deriveResumeState({ savedAnswer: saved, attempt, ask = null }) {
174
+ const pastDeadline = !!(ask && saved && ask.askId === saved.askId && Date.parse(ask.expiresAt) < Date.now());
175
+ if (saved && pastDeadline && answerTiming(saved.answeredAt, ask.expiresAt) !== 'on-time') return null;
161
176
  const tries = attempt ? attempt.tries : null;
162
177
  const maxTries = attempt ? attempt.maxTries : null;
163
- if (savedAnswer) {
164
- if (attempt && attempt.state === 'in-flight' && attempt.askId === savedAnswer.askId) {
178
+ if (saved) {
179
+ // M4c-fix amendment 1 (a): a saved answer with no readable time is broken — the resume would refuse it every
180
+ // time. It is not stuck, not "answer saved": the doors come back with a note, and answering again sets it aside.
181
+ if (Number.isNaN(Date.parse(saved.answeredAt ?? ''))) {
182
+ return {
183
+ state: 'broken', askId: saved.askId, tries: null, maxTries: null, reason: BROKEN_ANSWER_WHY, label: BROKEN_LABEL,
184
+ };
185
+ }
186
+ if (attempt && attempt.state === 'in-flight' && attempt.askId === saved.askId) {
165
187
  return {
166
- state: 'starting', askId: savedAnswer.askId, tries, maxTries, reason: null, label: 'answer saved, resume starting',
188
+ state: 'starting', askId: saved.askId, tries, maxTries, reason: null, label: 'your answer is saved; the run is picking it up',
167
189
  };
168
190
  }
169
- const mine = attempt && attempt.askId === savedAnswer.askId;
191
+ const mine = attempt && attempt.askId === saved.askId;
170
192
  return {
171
193
  state: 'not-started',
172
- askId: savedAnswer.askId,
194
+ askId: saved.askId,
173
195
  tries: mine ? tries : null,
174
196
  maxTries: mine ? maxTries : null,
175
197
  reason: mine && typeof attempt.refusal === 'string' && attempt.refusal.length > 0 ? attempt.refusal : RESUME_REASON_UNKNOWN,
176
- label: 'answer saved, resume not started',
198
+ label: 'your answer is saved; the run stopped before using it',
177
199
  };
178
200
  }
179
201
  if (attempt) {
@@ -184,6 +206,111 @@ export function deriveResumeState({ savedAnswer, attempt }) {
184
206
  return null;
185
207
  }
186
208
 
209
+ export const WAITING_LABEL = 'waiting on you (parked, unanswered)';
210
+ export const STUCK_LABEL = 'stuck — your answer is saved; the run stopped before using it';
211
+ export const STUCK_LOCK_LABEL = 'stuck — an old resume lock is in the way';
212
+ export const BROKEN_LABEL = 'Your saved answer could not be read.';
213
+ export const BROKEN_ANSWER_WHY = 'Please answer again; the broken one is kept aside.';
214
+ export const CRASHED_LABEL = 'crashed after taking your answer — start a fresh run';
215
+
216
+ /**
217
+ * M4c-fix amendment 2 (g): the ONE table from a sign to its bold word. Runs, the Inbox and the run header all show
218
+ * the word this table gives (the server stamps it on every row; the page never invents one).
219
+ * @type {Record<string, string>}
220
+ */
221
+ export const SIGN_WORDS = {
222
+ '[▶]': 'running', '[·]': 'waiting', '[II]': 'stuck', '[!]': 'expired', '[?]': 'crashed', '[✓]': 'passed', '[✗]': 'failed',
223
+ };
224
+
225
+ /**
226
+ * The sign's word and the plain line after the dash. The existing plain line is kept as is; only a line that already
227
+ * opens with the word ("stuck — …") or is the word itself ("passed") loses that repeat, so it is never said twice.
228
+ * `noWord`: a run the human ended on purpose with rerun wears `[✗]` but is never called "failed" (M4b amendment 3),
229
+ * so it shows its plain line alone.
230
+ * @param {string} glyph a `computeGlyph` sign @param {string} label its plain line @param {boolean} [noWord]
231
+ * @returns {{word: string|null, line: string|null}}
232
+ */
233
+ export function signParts(glyph, label, noWord = false) {
234
+ const word = noWord ? null : (SIGN_WORDS[glyph] ?? null);
235
+ if (word === null) return { word: null, line: label ?? null };
236
+ if (typeof label !== 'string' || label === word) return { word, line: null };
237
+ return { word, line: label.startsWith(`${word} — `) ? label.slice(word.length + 3) : label };
238
+ }
239
+
240
+ /** The sign an Inbox row wears (null for a past answer, which shows its status word instead). */
241
+ function stopGlyph(r) {
242
+ if (r.working) return '[▶]';
243
+ if (r.stuck) return '[II]';
244
+ if (r.waiting || r.resume) return '[·]';
245
+ return null;
246
+ }
247
+
248
+ /** The typed reasons a stuck run can have. `retry`: nothing is wrong that the books name, so trying again is the
249
+ * action. `lock-no-holder`: the resume lock has no recorded holder, so trying again can never work. */
250
+ export const STUCK_REASONS = {
251
+ retry: { label: STUCK_LABEL, why: null },
252
+ 'lock-no-holder': { label: STUCK_LOCK_LABEL, why: 'the resume lock has no recorded holder (a lock from before holders were recorded, or a torn write)' },
253
+ };
254
+
255
+ /**
256
+ * The ONE decision "is this run stuck, why, and what does it say" (M4c amendment 2 (a), amendment 3 (e), M4c-fix 15,
257
+ * 16). The answer is saved and not yet taken (`resume.state === 'not-started'`: `answer.json` is on disk; the
258
+ * panel's transient 'starting' and the `late` state are not stuck) and nothing is carrying the run on: the newest
259
+ * pid row's process is not alive AND the resume lock is not held by a live process, nor by one whose liveness
260
+ * cannot be told (`unknown`: never called stuck). The reason is typed, derived from the lock file and the saved
261
+ * answer themselves — never from a refusal string, so it is the same after a panel restart. Everything that shows
262
+ * "stuck" (computeGlyph, the Inbox, Runs, the Ask tab) reads this.
263
+ * @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx
264
+ * @returns {{stuck: false, reason: null, label: null, why: null}|{stuck: true, reason: 'retry'|'lock-no-holder', label: string, why: string|null}}
265
+ */
266
+ export function stuckState({ resume, liveness, lock }) {
267
+ if (!resume || resume.state !== 'not-started' || liveness === 'running' || lock === 'live' || lock === 'unknown') {
268
+ return {
269
+ stuck: false, reason: null, label: null, why: null,
270
+ };
271
+ }
272
+ // The runner takes the lock before it reads the answer, so a lock problem is what it would refuse on first.
273
+ const reason = lock === 'empty' ? 'lock-no-holder' : 'retry';
274
+ return { stuck: true, reason, ...STUCK_REASONS[reason] };
275
+ }
276
+
277
+ /** @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx @returns {boolean} */
278
+ export function isStuck(ctx) {
279
+ return stuckState(ctx).stuck;
280
+ }
281
+
282
+ /**
283
+ * The ONE filesystem read behind "stuck": the newest pid row's liveness and the resume lock, read together once.
284
+ * @param {string} runDir
285
+ * @returns {{liveness: 'running'|'gone'|'unknown', lock: 'none'|'live'|'dead'|'unknown'|'empty', lockPath: string}}
286
+ */
287
+ function readStuckInputs(runDir) {
288
+ const lock = readResumeLock(runDir);
289
+ return { liveness: runLiveness(runDir), lock: lock.state, lockPath: lock.path };
290
+ }
291
+
292
+ /**
293
+ * Read a run's stuck state: the inputs once, then `stuckState`. Used by the Ask tab and the Inbox; the run
294
+ * list's own read is `loadRunContext` (the same `readStuckInputs`).
295
+ * @param {string} runDir @param {any} resume the run's `deriveResumeState`
296
+ */
297
+ function runStuck(runDir, resume) {
298
+ const inputs = readStuckInputs(runDir);
299
+ return { ...inputs, ...stuckState({ resume, ...inputs }) };
300
+ }
301
+
302
+ /**
303
+ * M4c item 1: does this sign pulse? Only `[▶]` running and `[·]` WAITING ON YOU
304
+ * do, and `[II]` stuck (M4c amendment 2: it is not a final state). The other
305
+ * `[·]` states (answered not resumed, resume starting) are not waiting on the
306
+ * human, so they stay still. The one place that decides.
307
+ * @param {{glyph: string, label: string}} g a `computeGlyph` result
308
+ * @returns {boolean}
309
+ */
310
+ export function glyphPulses(g) {
311
+ return g.glyph === '[▶]' || g.glyph === '[II]' || (g.glyph === '[·]' && g.label === WAITING_LABEL);
312
+ }
313
+
187
314
  /**
188
315
  * The glyph + human-words label for one run — ported verbatim (in spirit,
189
316
  * from real derivation, not a shortcut) from `poc/m4/panel-data.mjs`'s
@@ -205,28 +332,44 @@ export function deriveResumeState({ savedAnswer, attempt }) {
205
332
  * - `[·]` answered, not resumed yet — parked, a consumed answer exists, but
206
333
  * no history row yet (resume hasn't finished) — always in words, never
207
334
  * the same line as "waiting on you", never `[?]`.
208
- * - `[?]` died / unknown — no history row, no open ask, no consumed answer:
209
- * `resume.lock` carries no pid and nothing checks liveness (M4a's own
210
- * open POC question), so a crashed resumer and a live one look the same
211
- * on disk. Never guessed into `[✗]` or `[✓]`.
212
- * - `[·]` answer saved, resume not started / starting (M4b amendment 1) —
335
+ * - `[?]` died / unknown — no history row, no open ask, and either the
336
+ * pid row's process is gone (M4c), or there is no pid row / no /proc and
337
+ * the books are older than 10 minutes. Never guessed into `[✗]` or `[✓]`.
338
+ * - `[·]` your answer is saved; the run stopped before using it / starting (M4b amendment 1) —
213
339
  * `answer.json` still on disk (`resume` = `deriveResumeState`): never
214
340
  * "waiting on you" (the human already answered) and never a success.
215
- * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any}} ctx
216
- * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[?]', label: string}}
341
+ * - `[▶]` running (M4c) — no end row, no open unanswered ask, and either the
342
+ * newest pid row's process is alive and is fwdloop (`liveness`, src/liveness.js)
343
+ * or (`liveness` unknown) the run's books changed in the last 10 minutes
344
+ * (`booksFresh`). A gone process is `[?]`. Absent `liveness`/`booksFresh`
345
+ * (a direct caller) reads as unknown / not fresh.
346
+ * - `[II]` stuck (M4c amendment 2, `isStuck`) — the answer is saved, not taken,
347
+ * and no live process (pid row or resume lock holder) carries the run on.
348
+ * A saved answer with a live process is `[▶]` working on your answer.
349
+ * - `[?]` crashed after taking your answer (amendment 2 (f)) — the answer was
350
+ * consumed, the process is gone, no end row: cannot be carried on.
351
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string}} ctx
352
+ * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[▶]'|'[?]'|'[II]', label: string}}
217
353
  */
218
354
  export function computeGlyph({
219
- historyRow, askJson, consumedAnswerExists, hasStateJson, resume,
355
+ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock,
220
356
  }) {
221
357
  if (historyRow) {
222
358
  if (historyRow.outcome === 'complete') return { glyph: '[✓]', label: 'passed' };
223
359
  // M4b amendment 3: a run the human ended on purpose with rerun is not a failure.
224
360
  if (historyRow.outcome === 'rerun') return { glyph: '[✗]', label: 'stopped by you (rerun), a fresh run was started' };
361
+ // M4c-fix amendment 1 (c): a run ended because its ask expired is `[!]` expired, never failed (it spent nothing more).
362
+ if (historyRow.outcome === 'ask-expired') return { glyph: '[!]', label: 'ask expired — nobody answered in time' };
225
363
  return { glyph: '[✗]', label: `failed (${historyRow.outcome ?? 'unknown outcome'})` };
226
364
  }
227
- if (askJson && resume && (resume.state === 'starting' || resume.state === 'not-started')) {
365
+ if (askJson && resume && resume.state === 'starting') {
228
366
  return { glyph: '[·]', label: resume.label };
229
367
  }
368
+ if (askJson && resume && resume.state === 'not-started') {
369
+ const stuck = stuckState({ resume, liveness, lock });
370
+ if (stuck.stuck) return { glyph: '[II]', label: stuck.label };
371
+ return { glyph: '[▶]', label: 'working on your answer' };
372
+ }
230
373
  // No history row. A park never writes one, and a consumed answer file
231
374
  // stays on disk until resume writes its own history row — "no history
232
375
  // row" alone never means died.
@@ -235,15 +378,24 @@ export function computeGlyph({
235
378
  if (Number.isFinite(expiresMs) && Date.now() > expiresMs) {
236
379
  return { glyph: '[!]', label: 'ask expired, not resumed yet' };
237
380
  }
238
- return { glyph: '[·]', label: 'waiting on you (parked, unanswered)' };
381
+ return { glyph: '[·]', label: WAITING_LABEL };
239
382
  }
240
383
  if (askJson && consumedAnswerExists) {
384
+ // M4c: the answer was consumed — a resume process took it. Alive = working on it.
385
+ if (liveness === 'running') return { glyph: '[▶]', label: 'working on your answer' };
386
+ if (liveness === 'gone') return { glyph: '[?]', label: CRASHED_LABEL };
241
387
  return { glyph: '[·]', label: 'answered, not resumed yet' };
242
388
  }
389
+ // M4c: no end row, no open ask — is a process still working? Pid row first
390
+ // (`liveness`, src/liveness.js); with no row or no /proc (`unknown`), the
391
+ // 10-minute books rule. Never `[▶]` off a parked ask (branches above).
392
+ if (liveness === 'running') return { glyph: '[▶]', label: 'running' };
393
+ if (liveness === 'gone') return { glyph: '[?]', label: 'the process working on this run is gone (no end row was written)' };
394
+ if (booksFresh) return { glyph: '[▶]', label: 'running (no pid record; its books changed in the last 10 minutes)' };
243
395
  if (hasStateJson && !askJson) {
244
396
  return { glyph: '[?]', label: 'running or died: unknown (parked state with no open ask and no history row)' };
245
397
  }
246
- return { glyph: '[?]', label: 'running or died: unknown (resume.lock has no pid, no liveness check)' };
398
+ return { glyph: '[?]', label: 'running or died: unknown (no pid record, books older than 10 minutes)' };
247
399
  }
248
400
 
249
401
  /**
@@ -489,7 +641,7 @@ export function isBlockedVerdict(verdict) {
489
641
  function markForVerdict(verdict, closeClass) {
490
642
  if (closeClass === 'hitl' && verdict === 'red') return '✗'; // the human's own redo
491
643
  if (verdict === 'green' || verdict === 'hitl') return '✓';
492
- if (verdict === 'paused' || verdict === 'refused' || verdict === 'ask-timeout' || verdict === 'ask-expired') return '·';
644
+ if (verdict === 'paused' || verdict === 'refused' || verdict === 'ask-timeout' || verdict === 'ask-expired' || verdict === 'ask-reopened' || verdict === 'lock-removed') return '·';
493
645
  return '✗';
494
646
  }
495
647
 
@@ -697,7 +849,8 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
697
849
  const stateJson = readRunState(runDir);
698
850
  const consumedAnswerExists = hasConsumedAnswer(runDir, askJson && typeof askJson.askId === 'string' ? askJson.askId : null);
699
851
  // A finished run has no resume to report (its history row says how it ended).
700
- const resume = historyRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(runDir), attempt });
852
+ const resume = historyRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(runDir), attempt, ask: askJson });
853
+ const stuckInputs = historyRow ? { liveness: 'unknown', lock: 'none' } : readStuckInputs(runDir);
701
854
 
702
855
  return {
703
856
  flowName,
@@ -714,16 +867,35 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
714
867
  consumedAnswerExists,
715
868
  hasStateJson: stateJson !== null,
716
869
  resume,
870
+ // M4c: only read for a run with no end row (an end row always wins).
871
+ liveness: stuckInputs.liveness,
872
+ lock: stuckInputs.lock,
873
+ booksFresh: historyRow ? false : booksFresh(runDir),
874
+ // M4c exit walk: when the process that is working on the run started (its newest pid row's
875
+ // own `startedAt`), so a `[▶]` run has a real time and never "parked or died". Not a book change.
876
+ startedAt: historyRow ? null : lastPidStartedAt(runDir),
717
877
  };
718
878
  }
719
879
 
880
+ /** @param {string} runDir @returns {string|null} */
881
+ function lastPidStartedAt(runDir) {
882
+ const rows = readPidRows(runDir);
883
+ const at = rows[rows.length - 1]?.startedAt;
884
+ return typeof at === 'string' && !Number.isNaN(Date.parse(at)) ? at : null;
885
+ }
886
+
887
+ /** The ONE running rule for wording is the glyph's own (`computeGlyph` -> `[▶]`, which already
888
+ * folds in `runLiveness`): a run with no end row whose glyph is `[▶]` is running. */
889
+ const RUNNING_WHY = 'still running — not finished yet';
890
+ /** @param {any} ctx @param {string} glyph */
891
+ const isRunningNow = (ctx, glyph) => !ctx.historyRow && glyph === '[▶]';
892
+
720
893
  /**
721
894
  * `GET /api/runs` — every flow under `root`, every run under each flow
722
895
  * (M4a scope item 2). A flow with zero runs still gets one row (`runId:
723
896
  * null`, an explicit `why`) — no flow is silently missing from the list.
724
- * Newest-first by history `at` where known; a row with no history row (died
725
- * or still parked) sorts after every row that has one, in flow/run order
726
- * (a real ordering, never `Date.now()` guessed in for a missing `at`).
897
+ * Ordered by `orderRuns` (waiting on you, running, then newest `at` first; a row
898
+ * with no `at` is never given a guessed one).
727
899
  * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
728
900
  * `resumeAttempt`: the panel's in-memory resume-attempt lookup (M4b piece 2); absent = none.
729
901
  * @returns {any[]}
@@ -750,6 +922,12 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
750
922
  }
751
923
  const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue, resumeAttempt?.(flowName, runId) ?? null);
752
924
  const { glyph, label } = computeGlyph(ctx);
925
+ // M4c amendment 1 (c): the ask waiting on the human, by the same rule
926
+ // listStops uses (deriveAskOpenFields) — the least time left if several.
927
+ const waitingAsk = runAsksInOrder(run.runDir, !!ctx.historyRow)
928
+ .map((ask) => ({ ask, ...deriveAskOpenFields(ask, !!ctx.historyRow, ctx.resume) }))
929
+ .filter((r) => r.waiting)
930
+ .reduce((best, r) => (best === null || (r.timeLeftMs ?? Infinity) < (best.timeLeftMs ?? Infinity) ? r : best), /** @type {any} */ (null));
753
931
  let spend;
754
932
  if (ctx.historyRow) {
755
933
  const cd = costDisplay(ctx.historyRow.spentUsd, ctx.historyRow.spendComplete);
@@ -771,25 +949,61 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
771
949
  runId,
772
950
  glyph,
773
951
  label,
952
+ ...signParts(glyph, label, ctx.historyRow?.outcome === 'rerun'),
953
+ pulse: glyphPulses({ glyph, label }),
954
+ stuck: glyph === '[II]',
774
955
  resume: ctx.resume,
775
956
  spend,
776
- spendWhy: (!ctx.historyRow && spend === null) ? 'no history row yet and no priced spend.jsonl rows — nothing to floor' : null,
957
+ spendWhy: (!ctx.historyRow && spend === null)
958
+ ? (isRunningNow(ctx, glyph) ? 'running — no priced spend yet' : 'no history row yet and no priced spend.jsonl rows — nothing to floor')
959
+ : null,
960
+ waiting: waitingAsk !== null,
961
+ waitingAskId: waitingAsk ? waitingAsk.ask.askId : null,
962
+ timeLeftMs: waitingAsk ? waitingAsk.timeLeftMs : null,
777
963
  at: ctx.historyRow ? ctx.historyRow.at : null,
778
964
  askedAt,
779
- atWhy: (ctx.historyRow || askedAt) ? null : 'no history row yet (parked or died before one was written)',
965
+ startedAt: isRunningNow(ctx, glyph) ? ctx.startedAt : null,
966
+ atWhy: (ctx.historyRow || askedAt) ? null
967
+ : isRunningNow(ctx, glyph)
968
+ ? (ctx.startedAt ? null : 'running — start time not recorded (no pid record)')
969
+ : 'no history row yet (parked or died before one was written)',
780
970
  });
781
971
  }
782
972
  }
783
- // Newest first by `at` where present; rows with no `at` keep flow/run
784
- // order (already alphabetical from listFlowNames/listRunIds) at the end.
973
+ return orderRuns(rows);
974
+ }
975
+
976
+ /**
977
+ * The ONE ordering of Runs — History and Workflows both render the list in the
978
+ * order given (M4c amendment 1 (c)); a flow's top row is therefore the first
979
+ * run of that flow here, so a waiting run is the parent with no second rule:
980
+ * 1 waiting on you — least time left first; a stuck run (`[II]`, amendment 2)
981
+ * after the ones with a timer;
982
+ * 2 running (`[▶]`, the glyph's own liveness rule);
983
+ * 3 everything else — finish time `at`, newest first.
984
+ * A row with no known time keeps input order at the end of its section.
985
+ * @param {any[]} rows
986
+ * @returns {any[]}
987
+ */
988
+ export function orderRuns(rows) {
989
+ const sectionOf = (r) => ((r.waiting || r.stuck) ? 1 : r.glyph === '[▶]' ? 2 : 3);
785
990
  return rows
786
991
  .map((row, index) => ({ row, index }))
787
992
  .sort((a, b) => {
993
+ const sa = sectionOf(a.row);
994
+ const sb = sectionOf(b.row);
995
+ if (sa !== sb) return sa - sb;
996
+ if (sa === 1) {
997
+ if (!!a.row.stuck !== !!b.row.stuck) return a.row.stuck ? 1 : -1;
998
+ const at = typeof a.row.timeLeftMs === 'number' ? a.row.timeLeftMs : Infinity;
999
+ const bt = typeof b.row.timeLeftMs === 'number' ? b.row.timeLeftMs : Infinity;
1000
+ return at !== bt ? at - bt : a.index - b.index;
1001
+ }
788
1002
  const am = typeof a.row.at === 'string' ? Date.parse(a.row.at) : NaN;
789
1003
  const bm = typeof b.row.at === 'string' ? Date.parse(b.row.at) : NaN;
790
1004
  const aKnown = Number.isFinite(am);
791
1005
  const bKnown = Number.isFinite(bm);
792
- if (aKnown && bKnown) return bm - am;
1006
+ if (aKnown && bKnown && am !== bm) return bm - am;
793
1007
  if (aKnown !== bKnown) return aKnown ? -1 : 1;
794
1008
  return a.index - b.index;
795
1009
  })
@@ -1046,7 +1260,8 @@ export function getRunDetail({
1046
1260
  const wallMs = ctx.historyRow && typeof ctx.historyRow.wallMs === 'number' ? ctx.historyRow.wallMs : null;
1047
1261
  const wallMsWhy = wallMs !== null
1048
1262
  ? null
1049
- : (ctx.historyRow ? 'history row has no wallMs recorded' : 'no history row yet (parked or died before completion)');
1263
+ : (ctx.historyRow ? 'history row has no wallMs recorded'
1264
+ : isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row yet (parked or died before completion)');
1050
1265
 
1051
1266
  let spend;
1052
1267
  if (ctx.historyRow) {
@@ -1069,9 +1284,12 @@ export function getRunDetail({
1069
1284
  runId,
1070
1285
  glyph,
1071
1286
  label,
1287
+ ...signParts(glyph, label, ctx.historyRow?.outcome === 'rerun'),
1288
+ signWords: SIGN_WORDS,
1289
+ pulse: glyphPulses({ glyph, label }),
1072
1290
  resume: ctx.resume,
1073
1291
  outcome: ctx.historyRow ? ctx.historyRow.outcome : null,
1074
- outcomeWhy: ctx.historyRow ? null : 'no history row (parked or died before completion)',
1292
+ outcomeWhy: ctx.historyRow ? null : (isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row (parked or died before completion)'),
1075
1293
  capUsd: ctx.historyRow ? ctx.historyRow.capUsd : (ctx.flowRead.ok ? ctx.flowRead.arbiter.capUsd : null),
1076
1294
  spend,
1077
1295
  model,
@@ -1092,9 +1310,12 @@ export function getRunDetail({
1092
1310
  askedAt: (!ctx.historyRow && ctx.askJson && typeof ctx.askJson.askedAt === 'string')
1093
1311
  ? ctx.askJson.askedAt
1094
1312
  : null,
1313
+ startedAt: isRunningNow(ctx, glyph) ? ctx.startedAt : null,
1095
1314
  atWhy: (ctx.historyRow || (ctx.askJson && typeof ctx.askJson.askedAt === 'string'))
1096
1315
  ? null
1097
- : 'no history row yet (parked or died before completion)',
1316
+ : isRunningNow(ctx, glyph)
1317
+ ? (ctx.startedAt ? null : 'running — start time not recorded (no pid record)')
1318
+ : 'no history row yet (parked or died before completion)',
1098
1319
  };
1099
1320
  }
1100
1321
 
@@ -1333,7 +1554,11 @@ function isOpenStatus(status) {
1333
1554
  * @returns {{open: boolean, waiting: boolean, resume: any, timeLeftMs: number|null}}
1334
1555
  */
1335
1556
  function deriveAskOpenFields(ask, hasHistoryRow, resume = null) {
1336
- const open = isOpenStatus(ask.status) && !hasHistoryRow;
1557
+ // M4c amendment 3: an ask past its deadline reads `expired`, but one whose answer was saved in time
1558
+ // (`resume` is null for a late/unreadable one, `deriveResumeState`) is still open: it can be carried on.
1559
+ const answerSaved = resume != null && resume.askId === ask.askId
1560
+ && (resume.state === 'starting' || resume.state === 'not-started');
1561
+ const open = (isOpenStatus(ask.status) || (ask.status === 'expired' && answerSaved)) && !hasHistoryRow;
1337
1562
  // M4b fix: the ONE decision "is this ask waiting on the human". An open ask
1338
1563
  // whose answer is already saved (`resume` = `deriveResumeState` for THIS
1339
1564
  // ask, the run's own label) is open but not waiting: the human answered.
@@ -1349,6 +1574,25 @@ function deriveAskOpenFields(ask, hasHistoryRow, resume = null) {
1349
1574
  };
1350
1575
  }
1351
1576
 
1577
+ /**
1578
+ * M4c-fix amendment 1 (b): does this ask offer the human's "Reopen"? Only the run's current open ask (`ask.json`),
1579
+ * only once its deadline has passed with no usable answer waiting (`resume` is null for it: a late or unreadable saved
1580
+ * answer reads as none, an in-time one is resumed, not reopened), only while the run has not ended. `waitMs` is the
1581
+ * signed wait it repeats; `late` says an answer was saved but came after the deadline. The Run's end row is the caller's `openAskJson === null`.
1582
+ * @param {any} ask one row from `runAsksInOrder` @param {any} openAskJson `readAsk` of the run, or null (ended)
1583
+ * @param {any} resume the run's `deriveResumeState`
1584
+ * @returns {{waitMs: number, late: boolean, why: string}|null}
1585
+ */
1586
+ function reopenOffer(ask, openAskJson, resume, lateAnswerSaved = false) {
1587
+ if (!openAskJson || openAskJson.askId !== ask.askId || ask.status !== 'expired') return null;
1588
+ if (resume && resume.askId === ask.askId && (resume.state === 'starting' || resume.state === 'not-started')) return null;
1589
+ // `late`: an answer was saved but came after the deadline (the page says so, instead of "nobody answered");
1590
+ // `why` is that line, the one the Ask tab and the Inbox row both draw.
1591
+ return Number.isFinite(openAskJson.waitMs)
1592
+ ? { waitMs: openAskJson.waitMs, late: lateAnswerSaved, why: lateAnswerSaved ? LATE_ANSWER_WHY : NO_ANSWER_WHY }
1593
+ : null;
1594
+ }
1595
+
1352
1596
  /**
1353
1597
  * `readAskEvidence`'s own return shape (`src/ask.js`) carries the draft as
1354
1598
  * `{ text: string } | null` (never a bare string) so a caller can tell "no
@@ -1385,6 +1629,7 @@ function normalizeArchivedRow(a) {
1385
1629
  reason: a.answer.reason ?? null,
1386
1630
  answeredAt: a.answer.answeredAt ?? null,
1387
1631
  archived: true,
1632
+ emits: typeof a.emits === 'string' ? a.emits : null,
1388
1633
  evidence: flattenEvidence(a.evidence),
1389
1634
  };
1390
1635
  }
@@ -1396,6 +1641,11 @@ function normalizeArchivedRow(a) {
1396
1641
  * quarantined stale answer for a real consumed one). */
1397
1642
  const CONSUMED_ANSWER_RE = /^answer\.(.+)\.consumed\.json$/;
1398
1643
 
1644
+ /** The line under an ask that ended expired though an answer was saved: the answer came too late. */
1645
+ const LATE_ANSWER_WHY = 'Your answer came after the deadline.';
1646
+ /** The line under an expired ask nobody answered. */
1647
+ const NO_ANSWER_WHY = 'Nobody answered in time.';
1648
+
1399
1649
  /**
1400
1650
  * The pre-M4a-1 fallback reader (M4a-1 scope item 1): for a run with no
1401
1651
  * `asks/` archive directory at all, reconstructs what the books STILL hold —
@@ -1443,6 +1693,7 @@ function legacyRunAsks(runDir, hasHistoryRow) {
1443
1693
  } catch {
1444
1694
  continue; // eslint-disable-line no-continue -- a torn write is skipped, never invented
1445
1695
  }
1696
+ if (parsed === null || typeof parsed !== 'object') continue; // eslint-disable-line no-continue -- valid JSON that is no answer (`null`, a number) is skipped like a torn write
1446
1697
  // A consumed legacy row never recovers question/askedAt/expiresAt from
1447
1698
  // the CURRENT ask.json, even when its askId happens to still match it —
1448
1699
  // the single mutable slot is not a reliable append log for a past ask
@@ -1455,7 +1706,7 @@ function legacyRunAsks(runDir, hasHistoryRow) {
1455
1706
  questionWhy: 'question not kept (before M4a-1)',
1456
1707
  askedAt: null,
1457
1708
  expiresAt: null,
1458
- status: DECISION_STATUS[normalizeDecision(parsed.decision)] ?? `unrecognised: ${parsed.decision}`,
1709
+ status: decisionStatus(parsed.decision) ?? `unrecognised: ${parsed.decision}`,
1459
1710
  reason: typeof parsed.reason === 'string' ? parsed.reason : null,
1460
1711
  answeredAt: typeof parsed.answeredAt === 'string' ? parsed.answeredAt : null,
1461
1712
  archived: false,
@@ -1523,12 +1774,12 @@ function legacyRunAsks(runDir, hasHistoryRow) {
1523
1774
  * (hamr's 2026-09-27 live check).
1524
1775
  * @returns {any[]}
1525
1776
  */
1526
- function runAsksInOrder(runDir, hasHistoryRow) {
1777
+ function runAsksInOrder(runDir, hasHistoryRow, endedExpired = false) {
1527
1778
  const archivedResult = listArchivedAsks(runDir);
1528
1779
  const rows = archivedResult.archived
1529
1780
  ? archivedResult.asks.map(normalizeArchivedRow)
1530
1781
  : legacyRunAsks(runDir, hasHistoryRow);
1531
- return rows
1782
+ const ordered = rows
1532
1783
  .map((row, index) => ({ row, index }))
1533
1784
  .sort((a, b) => {
1534
1785
  const am = typeof a.row.askedAt === 'string' ? Date.parse(a.row.askedAt) : NaN;
@@ -1540,6 +1791,13 @@ function runAsksInOrder(runDir, hasHistoryRow) {
1540
1791
  return a.index - b.index;
1541
1792
  })
1542
1793
  .map(({ row }) => row);
1794
+ // M4c-fix amendment 1 (c): a run ended because its ask expired reads expired, never accepted. The late answer the
1795
+ // terminal resume consumed was refused, so the newest ask carries `expired` (and says why), not the answer's word.
1796
+ const last = ordered[ordered.length - 1];
1797
+ if (endedExpired && last && (last.status === 'accepted' || last.status === 'redo' || last.status === 'reran')) {
1798
+ ordered[ordered.length - 1] = { ...last, status: 'expired', reason: null, why: LATE_ANSWER_WHY };
1799
+ }
1800
+ return ordered;
1543
1801
  }
1544
1802
 
1545
1803
  /**
@@ -1584,6 +1842,54 @@ export function deriveAskStepInfo(orderedAsks, auditRows, declSteps) {
1584
1842
  });
1585
1843
  }
1586
1844
 
1845
+ /**
1846
+ * M4c item 5 — the Ask tab's ONE grouping function: one block per signed ask
1847
+ * line. Key = the archive's recorded `emits`, else the step the ask's own "paused" audit row names (`stepName`,
1848
+ * `deriveAskStepInfo`); when the books cannot name a step (count mismatch, a
1849
+ * pre-M4a-1 run) the key falls back to the question text, then to one shared
1850
+ * "unknown" key — never a guessed pairing. Draft numbers are the ask's 1-based
1851
+ * position within its own block (how many times this line has parked).
1852
+ * `current` is the newest draft; `answers` is one row per draft that has a
1853
+ * recorded decision (the newest draft only when it is not itself open),
1854
+ * decision word via `DECISION_STATUS` (old `reject` files already read `redo`).
1855
+ * @param {any[]} asks rows as built by `getRunAsks` (oldest first)
1856
+ * @returns {any[]}
1857
+ */
1858
+ export function groupAskBlocks(asks) {
1859
+ const decisionWord = (status) => Object.keys(DECISION_STATUS).find((k) => DECISION_STATUS[k] === status) ?? status;
1860
+ const byKey = new Map();
1861
+ for (const ask of asks) {
1862
+ let key = 'unknown';
1863
+ if (typeof ask.emits === 'string') key = `step:${ask.emits}`;
1864
+ else if (typeof ask.stepName === 'string') key = `step:${ask.stepName}`;
1865
+ else if (typeof ask.question === 'string') key = `q:${ask.question}`;
1866
+ if (!byKey.has(key)) byKey.set(key, []);
1867
+ byKey.get(key).push(ask);
1868
+ }
1869
+ return [...byKey.entries()].map(([key, drafts]) => {
1870
+ const current = drafts[drafts.length - 1];
1871
+ const answers = [];
1872
+ drafts.forEach((d, i) => {
1873
+ if (d === current && d.open) return;
1874
+ if (d.status === 'unanswered' || d.status === 'open') return;
1875
+ answers.push({
1876
+ draft: i + 1, askId: d.askId, decision: decisionWord(d.status), reason: d.reason ?? null, answeredAt: d.answeredAt ?? null,
1877
+ });
1878
+ });
1879
+ return {
1880
+ key,
1881
+ stepName: current.emits ?? current.stepName ?? null,
1882
+ stepLine: current.stepLine ?? null,
1883
+ question: current.question ?? null,
1884
+ questionWhy: current.questionWhy ?? null,
1885
+ draftNo: drafts.length,
1886
+ askIds: drafts.map((d) => d.askId),
1887
+ current,
1888
+ answers,
1889
+ };
1890
+ });
1891
+ }
1892
+
1587
1893
  /**
1588
1894
  * `GET /api/runs/:flow/:runId/asks` — the Ask tab (M4a-1 scope item 1):
1589
1895
  * every ask this run's books can name, in order, each carrying full
@@ -1599,7 +1905,7 @@ export function deriveAskStepInfo(orderedAsks, auditRows, declSteps) {
1599
1905
  * detail carries, `null` for a finished run or nothing to say) so the Ask tab
1600
1906
  * can tell "open, answerable" from "answer saved" without a second fetch.
1601
1907
  * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
1602
- * @returns {{flow:string, runId:string, asks:any[], resume: any}|null}
1908
+ * @returns {{flow:string, runId:string, asks:any[], resume: any, blocks: any[]}|null}
1603
1909
  */
1604
1910
  export function getRunAsks({
1605
1911
  root, flow, runId, catalogue, resumeAttempt,
@@ -1607,23 +1913,41 @@ export function getRunAsks({
1607
1913
  const run = resolveRunPath(root, flow, runId);
1608
1914
  if (!run.ok) return null;
1609
1915
  if (!existsSync(run.runDir)) return null;
1610
- const hasHistoryRow = readHistory(run.flowDir).some((r) => r && r.runId === runId);
1916
+ const histRow = readHistory(run.flowDir).find((r) => r && r.runId === runId);
1917
+ const hasHistoryRow = !!histRow;
1611
1918
  // hamr's 2026-09-27 browser-walk bug #4: the Ask tab's own asks must carry
1612
1919
  // the SAME `open`/`timeLeftMs` fields listStops already computes for the
1613
1920
  // Inbox — otherwise an open ask's Ask-tab header/body falls back to the
1614
1921
  // raw status word "unanswered" and no time-left, disagreeing with the
1615
1922
  // Inbox row for that exact same ask.
1616
- const ordered = runAsksInOrder(run.runDir, hasHistoryRow);
1923
+ const ordered = runAsksInOrder(run.runDir, hasHistoryRow, histRow?.outcome === 'ask-expired');
1617
1924
  const auditRows = readAudit(run.runDir);
1618
1925
  const flowRead = readFlow({
1619
1926
  root, name: flow, catalogue,
1620
1927
  });
1621
1928
  const declSteps = flowRead.ok ? flowRead.declaration.steps : null;
1622
1929
  const stepInfo = deriveAskStepInfo(ordered, auditRows, declSteps);
1623
- const resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flow, runId) ?? null });
1930
+ let resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flow, runId) ?? null, ask: readAsk(run.runDir) });
1931
+ // M4c amendment 2: the Ask tab says what the run list says — stuck, by the one rule (`stuckState`).
1932
+ let runStuckNow = false;
1933
+ if (resume) {
1934
+ const st = runStuck(run.runDir, resume);
1935
+ if (st.stuck) {
1936
+ resume = {
1937
+ ...resume,
1938
+ label: st.label,
1939
+ ...(resume.reason === RESUME_REASON_UNKNOWN && st.why ? { reason: st.why } : {}),
1940
+ ...(st.reason === 'lock-no-holder' ? { lockPath: st.lockPath } : {}),
1941
+ };
1942
+ runStuckNow = true;
1943
+ }
1944
+ }
1945
+ const openAskJson = hasHistoryRow ? null : readAsk(run.runDir);
1624
1946
  const asks = ordered.map((ask, i) => ({
1625
1947
  ...ask,
1626
1948
  ...deriveAskOpenFields(ask, hasHistoryRow, resume),
1949
+ reopen: reopenOffer(ask, openAskJson, resume, readSavedAnswer(run.runDir)?.askId === ask.askId),
1950
+ stuck: runStuckNow && resume?.askId === ask.askId,
1627
1951
  index: i + 1,
1628
1952
  total: ordered.length,
1629
1953
  stepName: stepInfo[i].step,
@@ -1631,7 +1955,7 @@ export function getRunAsks({
1631
1955
  stepWhy: stepInfo[i].why,
1632
1956
  }));
1633
1957
  return {
1634
- flow, runId, asks, resume,
1958
+ flow, runId, asks, resume, blocks: groupAskBlocks(asks),
1635
1959
  };
1636
1960
  }
1637
1961
 
@@ -1657,39 +1981,107 @@ export function listStops({ root, resumeAttempt }) {
1657
1981
  const rows = [];
1658
1982
  for (const flowName of listFlowNames(root)) {
1659
1983
  const flowDir = join(root, flowName);
1660
- const historyRunIds = new Set(readHistory(flowDir).filter((r) => r && typeof r.runId === 'string').map((r) => r.runId));
1984
+ const historyRows = readHistory(flowDir).filter((r) => r && typeof r.runId === 'string');
1985
+ const historyRunIds = new Set(historyRows.map((r) => r.runId));
1986
+ const expiredEnds = new Set(historyRows.filter((r) => r.outcome === 'ask-expired').map((r) => r.runId));
1661
1987
  for (const runId of listRunIds(flowDir)) {
1662
1988
  const run = resolveRunPath(root, flowName, runId);
1663
1989
  if (!run.ok) continue;
1664
1990
  const hasHistoryRow = historyRunIds.has(runId);
1665
- const resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flowName, runId) ?? null });
1666
- for (const ask of runAsksInOrder(run.runDir, hasHistoryRow)) {
1667
- rows.push({
1668
- flow: flowName,
1669
- runId,
1670
- ...ask,
1671
- ...deriveAskOpenFields(ask, hasHistoryRow, resume),
1672
- });
1991
+ const resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flowName, runId) ?? null, ask: readAsk(run.runDir) });
1992
+ // M4c amendment 2: stuck by the ONE rule (`stuckState`), marked on the ask whose answer is saved.
1993
+ const st = runStuck(run.runDir, resume);
1994
+ const stuckAskId = !hasHistoryRow && st.stuck ? (resume?.askId ?? null) : null;
1995
+ const openAskJson = hasHistoryRow ? null : readAsk(run.runDir);
1996
+ const savedAskId = readSavedAnswer(run.runDir)?.askId;
1997
+ const runAsks = runAsksInOrder(run.runDir, hasHistoryRow, expiredEnds.has(runId)).map((ask) => ({
1998
+ flow: flowName,
1999
+ runId,
2000
+ ...ask,
2001
+ ...deriveAskOpenFields(ask, hasHistoryRow, resume),
2002
+ // an expired ask still open to Reopen says why, by the same offer (and line) its Ask tab draws
2003
+ ...(ask.why ? {} : { why: reopenOffer(ask, openAskJson, resume, savedAskId === ask.askId)?.why }),
2004
+ stuck: stuckAskId !== null && ask.askId === stuckAskId,
2005
+ stuckLabel: stuckAskId !== null && ask.askId === stuckAskId ? st.label : null,
2006
+ stuckLine: stuckAskId !== null && ask.askId === stuckAskId ? signParts('[II]', st.label ?? '').line : null,
2007
+ }));
2008
+ // M4c item 4: a run with no end row, no ask waiting on the human and no
2009
+ // saved-but-unresumed answer, whose newest pid row is alive, is "working
2010
+ // on your <decision>" — marked on that run's newest answered ask (the
2011
+ // one the live process took). `runLiveness` is the ONE liveness rule.
2012
+ const nothingWaiting = !runAsks.some((r) => r.waiting || r.resume);
2013
+ if (!hasHistoryRow && nothingWaiting && st.liveness === 'running') {
2014
+ const answered = runAsks.filter((r) => WORKING_WORD[r.status]);
2015
+ const newest = answered.reduce((best, r) => (best === null || sortMs(r.answeredAt) >= sortMs(best.answeredAt) ? r : best), null);
2016
+ if (newest) newest.working = WORKING_WORD[newest.status];
1673
2017
  }
2018
+ for (const r of runAsks) rows.push(r);
1674
2019
  }
1675
2020
  }
2021
+ return orderStops(rows).map((r) => {
2022
+ const glyph = stopGlyph(r);
2023
+ return glyph === null ? r : { ...r, glyph, word: SIGN_WORDS[glyph] };
2024
+ });
2025
+ }
2026
+
2027
+ /** ask status -> the answer's own word, for "working on your <word>…". */
2028
+ const WORKING_WORD = { accepted: 'accept', redo: 'redo', reran: 'rerun' };
2029
+
2030
+ /** ms for sorting; NaN when the stamp is absent/unparseable. */
2031
+ function sortMs(iso) {
2032
+ return typeof iso === 'string' ? Date.parse(iso) : NaN;
2033
+ }
2034
+
2035
+ /**
2036
+ * The ONE ordering of the Inbox (M4c item 4, hamr 2026-09-30); the page renders
2037
+ * in the order given and stamps each row's `section`:
2038
+ * 1 waiting on you — least time left first ("runs out first"); a stuck run
2039
+ * (amendment 2: answer saved, nobody carrying it on) after the timed asks;
2040
+ * 2 working on an answer you gave (`working`), or answer saved and resume not
2041
+ * started (`resume`) — newest answer first;
2042
+ * 3 answered and expired asks — newest first (answeredAt, else expiresAt).
2043
+ * A row with no known time sorts last within its section, ties by input order.
2044
+ * @param {any[]} rows
2045
+ * @returns {any[]}
2046
+ */
2047
+ export function orderStops(rows) {
2048
+ const sectionOf = (r) => ((r.waiting || r.stuck) ? 1 : (r.working || r.resume) ? 2 : 3);
2049
+ const key = (r) => {
2050
+ const t = sectionOf(r) === 3 ? (sortMs(r.answeredAt) || sortMs(r.expiresAt)) : sortMs(r.answeredAt);
2051
+ return Number.isFinite(t) ? t : NaN;
2052
+ };
1676
2053
  return rows
1677
- .map((row, index) => ({ row, index }))
2054
+ .map((row, index) => ({ row: { ...row, section: sectionOf(row) }, index }))
1678
2055
  .sort((a, b) => {
1679
- if (a.row.waiting !== b.row.waiting) return a.row.waiting ? -1 : 1;
1680
- if (a.row.waiting && b.row.waiting) {
2056
+ const sa = a.row.section;
2057
+ const sb = b.row.section;
2058
+ if (sa !== sb) return sa - sb;
2059
+ if (sa === 1) {
2060
+ if (!!a.row.stuck !== !!b.row.stuck) return a.row.stuck ? 1 : -1;
1681
2061
  const at = typeof a.row.timeLeftMs === 'number' ? a.row.timeLeftMs : Infinity;
1682
2062
  const bt = typeof b.row.timeLeftMs === 'number' ? b.row.timeLeftMs : Infinity;
1683
- if (at !== bt) return at - bt;
1684
- return a.index - b.index;
2063
+ return at !== bt ? at - bt : a.index - b.index;
1685
2064
  }
1686
- const am = typeof a.row.answeredAt === 'string' ? Date.parse(a.row.answeredAt) : NaN;
1687
- const bm = typeof b.row.answeredAt === 'string' ? Date.parse(b.row.answeredAt) : NaN;
1688
- const aKnown = Number.isFinite(am);
1689
- const bKnown = Number.isFinite(bm);
1690
- if (aKnown && bKnown) return bm - am;
2065
+ const ak = key(a.row);
2066
+ const bk = key(b.row);
2067
+ const aKnown = Number.isFinite(ak);
2068
+ const bKnown = Number.isFinite(bk);
2069
+ if (aKnown && bKnown && ak !== bk) return bk - ak;
1691
2070
  if (aKnown !== bKnown) return aKnown ? -1 : 1;
1692
2071
  return a.index - b.index;
1693
2072
  })
1694
2073
  .map(({ row }) => row);
1695
2074
  }
2075
+
2076
+ /**
2077
+ * N for `Inbox (N)` (M4c item 3): asks open and not expired, across every flow
2078
+ * and run, plus stuck runs (amendment 2: the human must act). An answered ask
2079
+ * whose resume is carried on is not `waiting`, so not counted; a crashed one
2080
+ * (answer taken, process gone) is not stuck and not counted;
2081
+ * an expired ask is not `open`. The page only shows this number.
2082
+ * @param {any[]} rows `listStops` rows
2083
+ * @returns {number}
2084
+ */
2085
+ export function inboxOpenCount(rows) {
2086
+ return rows.filter((r) => r.waiting || r.stuck).length;
2087
+ }