fwdloop 0.8.1 → 0.10.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,11 +28,16 @@ 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
- import { readAskEvidence, listArchivedAsks } from '../ask.js';
35
+ import {
36
+ runLiveness, booksFresh, readResumeLock, LOCK_NO_HOLDER,
37
+ } from '../liveness.js';
38
+ import {
39
+ readAskEvidence, listArchivedAsks, normalizeDecision, DECISION_STATUS, answerTiming,
40
+ } from '../ask.js';
36
41
 
37
42
  /** `{ ok:false, red }` result shape every exported function here can return
38
43
  * instead of throwing — the server maps this to a 4xx, never a crash.
@@ -99,23 +104,140 @@ function resolveRunPath(root, flowName, runId) {
99
104
  }
100
105
 
101
106
  /**
102
- * A consumed-answer marker exists for this run — `answerAsk`'s own write
107
+ * A consumed-answer marker exists for THIS ask (`askId`) — `answerAsk`'s own write
103
108
  * (`src/ask.js`) renames to `answer.<askId>.consumed.json` on accept, and
104
109
  * `resumeRun` (`src/runner.js`) does the same when it consumes an in-place
105
110
  * `answer.json`. A directory-naming-convention check, not a "book" with its
106
111
  * own single-row shape, so it lives here rather than growing a one-off
107
- * reader in either writer's module.
112
+ * reader in either writer's module. Per the signed rule (ladder M4a scope
113
+ * item 4) it is per the OPEN ask's askId: after redo -> re-park the old
114
+ * ask's marker stays on disk and must not answer the new ask. An ask with no
115
+ * askId (pre-M3) can be paired with no marker: false.
108
116
  * @param {string} runDir
117
+ * @param {string|null} askId the open ask's own askId
109
118
  * @returns {boolean}
110
119
  */
111
- function hasConsumedAnswer(runDir) {
112
- if (!existsSync(runDir)) return false;
120
+ function hasConsumedAnswer(runDir, askId) {
121
+ if (!existsSync(runDir) || typeof askId !== 'string' || askId.length === 0) return false;
113
122
  // F48 round 3: `readdirInside` (`src/flow.js`) skips a symlinked entry
114
123
  // rather than reporting its name — a run dir cannot be made to show a
115
124
  // consumed answer that isn't really there by planting a symlink named to
116
125
  // match the pattern.
117
126
  const names = readdirInside(runDir, '.');
118
- return names.some((n) => /^answer\..*\.consumed\.json$/.test(n));
127
+ return names.includes(`answer.${askId}.consumed.json`);
128
+ }
129
+
130
+ /**
131
+ * M4b piece 2: a SAVED, not-yet-consumed answer — `answer.json` (what
132
+ * `answerAsk` writes; the resume consumes it by renaming it away, F44). Read
133
+ * through `readFileInside` (a symlinked file is "none"). `null` when there is
134
+ * none or it is unreadable/unparseable or names no askId.
135
+ * @param {string} runDir
136
+ * @returns {{askId: string, decision: string|null, answeredAt: string|null}|null}
137
+ */
138
+ export function readSavedAnswer(runDir) {
139
+ const r = readFileInside(runDir, 'answer.json');
140
+ if (!r.ok) return null;
141
+ try {
142
+ const a = JSON.parse(r.text);
143
+ if (a && typeof a.askId === 'string' && a.askId.length > 0) {
144
+ return {
145
+ askId: a.askId,
146
+ decision: typeof a.decision === 'string' ? normalizeDecision(a.decision) : null,
147
+ answeredAt: typeof a.answeredAt === 'string' ? a.answeredAt : null,
148
+ };
149
+ }
150
+ } catch { /* unparseable: not a usable answer */ }
151
+ return null;
152
+ }
153
+
154
+ /** What the `resume` field says when the panel has no attempt record for a run
155
+ * (it restarted since the answer was saved) — said so, never blank. */
156
+ export const RESUME_REASON_UNKNOWN = 'reason unknown: the panel restarted, so it has no record of the resume attempt';
157
+
158
+ /**
159
+ * M4b amendment 1 scope 2: the ONE derivation of "answer saved, resume not
160
+ * started". From the books: an answer saved (`answer.json` present) and so
161
+ * unconsumed. From the panel's in-memory attempt record (`attempt`, may be
162
+ * null): whether a resume is still being started, and the resume's own refusal.
163
+ * `null` when there is nothing to say (no saved answer and no attempt).
164
+ * M4c amendment 3: `ask` (the run's open `ask.json`, may be null). A saved answer for that ask that was
165
+ * NOT saved in time (`answerTiming`) once the deadline has passed is not a resumable answer: it reads as
166
+ * none, so the run is `[!]` expired, the same as an ask nobody answered.
167
+ * @param {{savedAnswer: {askId:string, decision:string|null, answeredAt?:string|null}|null, attempt: any, ask?: any}} ctx
168
+ * @returns {{state: 'starting'|'not-started'|'took-over', askId: string|null, tries: number|null, maxTries: number|null, reason: string|null, label: string}|null}
169
+ */
170
+ export function deriveResumeState({ savedAnswer: saved, attempt, ask = null }) {
171
+ const pastDeadline = ask && saved && ask.askId === saved.askId && Date.parse(ask.expiresAt) < Date.now();
172
+ const savedAnswer = pastDeadline && answerTiming(saved.answeredAt, ask.expiresAt) !== 'on-time' ? null : saved;
173
+ const tries = attempt ? attempt.tries : null;
174
+ const maxTries = attempt ? attempt.maxTries : null;
175
+ if (savedAnswer) {
176
+ if (attempt && attempt.state === 'in-flight' && attempt.askId === savedAnswer.askId) {
177
+ return {
178
+ state: 'starting', askId: savedAnswer.askId, tries, maxTries, reason: null, label: 'answer saved, resume starting',
179
+ };
180
+ }
181
+ const mine = attempt && attempt.askId === savedAnswer.askId;
182
+ return {
183
+ state: 'not-started',
184
+ askId: savedAnswer.askId,
185
+ tries: mine ? tries : null,
186
+ maxTries: mine ? maxTries : null,
187
+ reason: mine && typeof attempt.refusal === 'string' && attempt.refusal.length > 0 ? attempt.refusal : RESUME_REASON_UNKNOWN,
188
+ label: 'answer saved, resume not started',
189
+ };
190
+ }
191
+ if (attempt) {
192
+ return {
193
+ state: 'took-over', askId: attempt.askId, tries, maxTries, reason: null, label: 'resume took over the answer',
194
+ };
195
+ }
196
+ return null;
197
+ }
198
+
199
+ export const WAITING_LABEL = 'waiting on you (parked, unanswered)';
200
+ export const STUCK_LABEL = 'stuck — answer saved, click try the resume again';
201
+ export const STUCK_LOCK_LABEL = 'stuck — remove the old resume lock by hand, then try again';
202
+ export const CRASHED_LABEL = 'crashed after taking your answer — start a fresh run';
203
+
204
+ /**
205
+ * M4c amendment 2 (a): the ONE rule for "stuck". The answer is saved and not yet
206
+ * taken (`resume.state === 'not-started'`: `answer.json` is on disk; the panel's
207
+ * transient 'starting' is not stuck) and nothing is carrying the run on: the
208
+ * newest pid row's process is not alive AND the resume lock is not held by a
209
+ * live process (`readResumeLock`, src/liveness.js). computeGlyph, the Inbox
210
+ * (`listStops`) and Runs (`listRuns`) all read this, never a second copy.
211
+ * @param {{resume?: any, liveness?: 'running'|'gone'|'unknown', lock?: string}} ctx
212
+ * @returns {boolean}
213
+ */
214
+ export function isStuck({ resume, liveness, lock }) {
215
+ return !!resume && resume.state === 'not-started' && liveness !== 'running' && lock !== 'live';
216
+ }
217
+
218
+ /**
219
+ * M4c amendment 3 (e): the ONE choice of the stuck label. After a "Try the resume again" the runner
220
+ * refused for a lock with no recorded holder (`LOCK_NO_HOLDER`, src/liveness.js) and that lock is
221
+ * still there unreadable (`lock === 'empty'`), trying again can never work: the label says to remove
222
+ * the file by hand. Every other stuck run keeps `STUCK_LABEL`.
223
+ * @param {{resume?: any, lock?: string}} ctx
224
+ * @returns {string}
225
+ */
226
+ export function stuckLabelFor({ resume, lock }) {
227
+ return lock === 'empty' && typeof resume?.reason === 'string' && resume.reason.includes(LOCK_NO_HOLDER)
228
+ ? STUCK_LOCK_LABEL : STUCK_LABEL;
229
+ }
230
+
231
+ /**
232
+ * M4c item 1: does this sign pulse? Only `[▶]` running and `[·]` WAITING ON YOU
233
+ * do, and `[II]` stuck (M4c amendment 2: it is not a final state). The other
234
+ * `[·]` states (answered not resumed, resume starting) are not waiting on the
235
+ * human, so they stay still. The one place that decides.
236
+ * @param {{glyph: string, label: string}} g a `computeGlyph` result
237
+ * @returns {boolean}
238
+ */
239
+ export function glyphPulses(g) {
240
+ return g.glyph === '[▶]' || g.glyph === '[II]' || (g.glyph === '[·]' && g.label === WAITING_LABEL);
119
241
  }
120
242
 
121
243
  /**
@@ -139,20 +261,41 @@ function hasConsumedAnswer(runDir) {
139
261
  * - `[·]` answered, not resumed yet — parked, a consumed answer exists, but
140
262
  * no history row yet (resume hasn't finished) — always in words, never
141
263
  * 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}}
264
+ * - `[?]` died / unknown — no history row, no open ask, and either the
265
+ * pid row's process is gone (M4c), or there is no pid row / no /proc and
266
+ * the books are older than 10 minutes. Never guessed into `[✗]` or `[✓]`.
267
+ * - `[·]` answer saved, resume not started / starting (M4b amendment 1) —
268
+ * `answer.json` still on disk (`resume` = `deriveResumeState`): never
269
+ * "waiting on you" (the human already answered) and never a success.
270
+ * - `[▶]` running (M4c) — no end row, no open unanswered ask, and either the
271
+ * newest pid row's process is alive and is fwdloop (`liveness`, src/liveness.js)
272
+ * or (`liveness` unknown) the run's books changed in the last 10 minutes
273
+ * (`booksFresh`). A gone process is `[?]`. Absent `liveness`/`booksFresh`
274
+ * (a direct caller) reads as unknown / not fresh.
275
+ * - `[II]` stuck (M4c amendment 2, `isStuck`) — the answer is saved, not taken,
276
+ * and no live process (pid row or resume lock holder) carries the run on.
277
+ * A saved answer with a live process is `[▶]` working on your answer.
278
+ * - `[?]` crashed after taking your answer (amendment 2 (f)) — the answer was
279
+ * consumed, the process is gone, no end row: cannot be carried on.
280
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string}} ctx
281
+ * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[▶]'|'[?]'|'[II]', label: string}}
148
282
  */
149
283
  export function computeGlyph({
150
- historyRow, askJson, consumedAnswerExists, hasStateJson,
284
+ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock,
151
285
  }) {
152
286
  if (historyRow) {
153
287
  if (historyRow.outcome === 'complete') return { glyph: '[✓]', label: 'passed' };
288
+ // M4b amendment 3: a run the human ended on purpose with rerun is not a failure.
289
+ if (historyRow.outcome === 'rerun') return { glyph: '[✗]', label: 'stopped by you (rerun), a fresh run was started' };
154
290
  return { glyph: '[✗]', label: `failed (${historyRow.outcome ?? 'unknown outcome'})` };
155
291
  }
292
+ if (askJson && resume && resume.state === 'starting') {
293
+ return { glyph: '[·]', label: resume.label };
294
+ }
295
+ if (askJson && resume && resume.state === 'not-started') {
296
+ if (isStuck({ resume, liveness, lock })) return { glyph: '[II]', label: stuckLabelFor({ resume, lock }) };
297
+ return { glyph: '[▶]', label: 'working on your answer' };
298
+ }
156
299
  // No history row. A park never writes one, and a consumed answer file
157
300
  // stays on disk until resume writes its own history row — "no history
158
301
  // row" alone never means died.
@@ -161,15 +304,24 @@ export function computeGlyph({
161
304
  if (Number.isFinite(expiresMs) && Date.now() > expiresMs) {
162
305
  return { glyph: '[!]', label: 'ask expired, not resumed yet' };
163
306
  }
164
- return { glyph: '[·]', label: 'waiting on you (parked, unanswered)' };
307
+ return { glyph: '[·]', label: WAITING_LABEL };
165
308
  }
166
309
  if (askJson && consumedAnswerExists) {
310
+ // M4c: the answer was consumed — a resume process took it. Alive = working on it.
311
+ if (liveness === 'running') return { glyph: '[▶]', label: 'working on your answer' };
312
+ if (liveness === 'gone') return { glyph: '[?]', label: CRASHED_LABEL };
167
313
  return { glyph: '[·]', label: 'answered, not resumed yet' };
168
314
  }
315
+ // M4c: no end row, no open ask — is a process still working? Pid row first
316
+ // (`liveness`, src/liveness.js); with no row or no /proc (`unknown`), the
317
+ // 10-minute books rule. Never `[▶]` off a parked ask (branches above).
318
+ if (liveness === 'running') return { glyph: '[▶]', label: 'running' };
319
+ if (liveness === 'gone') return { glyph: '[?]', label: 'the process working on this run is gone (no end row was written)' };
320
+ if (booksFresh) return { glyph: '[▶]', label: 'running (no pid record; its books changed in the last 10 minutes)' };
169
321
  if (hasStateJson && !askJson) {
170
322
  return { glyph: '[?]', label: 'running or died: unknown (parked state with no open ask and no history row)' };
171
323
  }
172
- return { glyph: '[?]', label: 'running or died: unknown (resume.lock has no pid, no liveness check)' };
324
+ return { glyph: '[?]', label: 'running or died: unknown (no pid record, books older than 10 minutes)' };
173
325
  }
174
326
 
175
327
  /**
@@ -247,7 +399,7 @@ export function deriveRunModel(auditRows) {
247
399
  * place that ever passes a third argument (`unjudgedCount`) into
248
400
  * `recordAudit`, so `Object.prototype.hasOwnProperty.call(row,
249
401
  * '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
402
+ * and the human's own accept/redo/rerun/refused answers) and false for
251
403
  * every other row shape in the book — a real, always-present marker
252
404
  * (`unjudgedCount` is a number, 0 included, never omitted on an ask row),
253
405
  * never the step's close class (a NON-ask hitl step, e.g. a plain write
@@ -380,8 +532,8 @@ export function deriveAuditAtWhy(row) {
380
532
  * ONE server-side function naming exactly which verdicts count as "did not
381
533
  * pass", derived strictly from a row's own `verdict` string (never a second,
382
534
  * 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
535
+ * a human's own redo on a hitl step — both are "this attempt did not
536
+ * pass"), `refused` (a blank redo/rerun reason), `ask-timeout` and
385
537
  * `ask-expired` (the human never answered in time), `cap-halt`,
386
538
  * `provider-red`, `pricing-red`, `close-casualty` (every other halt shape
387
539
  * `src/runner.js` records). NOT blocked: `green`/`hitl` (passed), `paused`
@@ -402,7 +554,7 @@ export function isBlockedVerdict(verdict) {
402
554
  * audit row — a `hitl`-classed ask step's `paused` row and its own
403
555
  * resolution row are the SAME try, the same pairing `computeTryCount`
404
556
  * already applies) for the Audit tab's grouped-by-step header. `✓` passed
405
- * (`green`/`hitl`), `✗` failed/rejected/blocked (everything
557
+ * (`green`/`hitl`), `✗` failed/redone/blocked (everything
406
558
  * `isBlockedVerdict` names, plus any other non-passing verdict), `·` still
407
559
  * open (`paused`/`refused`/`ask-timeout`/`ask-expired` — waiting, not yet
408
560
  * resolved either way). A `refused` (blank-reason) row is its own re-ask,
@@ -413,7 +565,7 @@ export function isBlockedVerdict(verdict) {
413
565
  * @returns {'✓'|'✗'|'·'}
414
566
  */
415
567
  function markForVerdict(verdict, closeClass) {
416
- if (closeClass === 'hitl' && verdict === 'red') return '✗'; // the human's own reject
568
+ if (closeClass === 'hitl' && verdict === 'red') return '✗'; // the human's own redo
417
569
  if (verdict === 'green' || verdict === 'hitl') return '✓';
418
570
  if (verdict === 'paused' || verdict === 'refused' || verdict === 'ask-timeout' || verdict === 'ask-expired') return '·';
419
571
  return '✗';
@@ -609,9 +761,10 @@ export function summarizeSpendRows(spendRows) {
609
761
  * @param {string} flowName
610
762
  * @param {string} runId
611
763
  * @param {any} catalogue
764
+ * @param {any} [attempt] the panel's in-memory resume-attempt record for this run, or null
612
765
  * @returns {any}
613
766
  */
614
- function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue) {
767
+ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attempt = null) {
615
768
  const flowRead = readFlow({ root, name: flowName, catalogue });
616
769
  const historyRows = readHistory(flowDir);
617
770
  const historyRow = historyRows.find((r) => r && r.runId === runId) ?? null;
@@ -620,7 +773,9 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue) {
620
773
  const logJson = readLog(runDir);
621
774
  const askJson = readAsk(runDir);
622
775
  const stateJson = readRunState(runDir);
623
- const consumedAnswerExists = hasConsumedAnswer(runDir);
776
+ const consumedAnswerExists = hasConsumedAnswer(runDir, askJson && typeof askJson.askId === 'string' ? askJson.askId : null);
777
+ // A finished run has no resume to report (its history row says how it ended).
778
+ const resume = historyRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(runDir), attempt, ask: askJson });
624
779
 
625
780
  return {
626
781
  flowName,
@@ -636,20 +791,41 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue) {
636
791
  stateJson,
637
792
  consumedAnswerExists,
638
793
  hasStateJson: stateJson !== null,
794
+ resume,
795
+ // M4c: only read for a run with no end row (an end row always wins).
796
+ liveness: historyRow ? 'unknown' : runLiveness(runDir),
797
+ lock: historyRow ? 'none' : readResumeLock(runDir).state,
798
+ booksFresh: historyRow ? false : booksFresh(runDir),
799
+ // M4c exit walk: when the process that is working on the run started (its newest pid row's
800
+ // own `startedAt`), so a `[▶]` run has a real time and never "parked or died". Not a book change.
801
+ startedAt: historyRow ? null : lastPidStartedAt(runDir),
639
802
  };
640
803
  }
641
804
 
805
+ /** @param {string} runDir @returns {string|null} */
806
+ function lastPidStartedAt(runDir) {
807
+ const rows = readPidRows(runDir);
808
+ const at = rows[rows.length - 1]?.startedAt;
809
+ return typeof at === 'string' && !Number.isNaN(Date.parse(at)) ? at : null;
810
+ }
811
+
812
+ /** The ONE running rule for wording is the glyph's own (`computeGlyph` -> `[▶]`, which already
813
+ * folds in `runLiveness`): a run with no end row whose glyph is `[▶]` is running. */
814
+ const RUNNING_WHY = 'still running — not finished yet';
815
+ /** @param {any} ctx @param {string} glyph */
816
+ const isRunningNow = (ctx, glyph) => !ctx.historyRow && glyph === '[▶]';
817
+
642
818
  /**
643
819
  * `GET /api/runs` — every flow under `root`, every run under each flow
644
820
  * (M4a scope item 2). A flow with zero runs still gets one row (`runId:
645
821
  * 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
822
+ * Ordered by `orderRuns` (waiting on you, running, then newest `at` first; a row
823
+ * with no `at` is never given a guessed one).
824
+ * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
825
+ * `resumeAttempt`: the panel's in-memory resume-attempt lookup (M4b piece 2); absent = none.
650
826
  * @returns {any[]}
651
827
  */
652
- export function listRuns({ root, catalogue }) {
828
+ export function listRuns({ root, catalogue, resumeAttempt }) {
653
829
  const rows = [];
654
830
  for (const flowName of listFlowNames(root)) {
655
831
  const flowDir = join(root, flowName);
@@ -669,8 +845,14 @@ export function listRuns({ root, catalogue }) {
669
845
  });
670
846
  continue;
671
847
  }
672
- const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue);
848
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue, resumeAttempt?.(flowName, runId) ?? null);
673
849
  const { glyph, label } = computeGlyph(ctx);
850
+ // M4c amendment 1 (c): the ask waiting on the human, by the same rule
851
+ // listStops uses (deriveAskOpenFields) — the least time left if several.
852
+ const waitingAsk = runAsksInOrder(run.runDir, !!ctx.historyRow)
853
+ .map((ask) => ({ ask, ...deriveAskOpenFields(ask, !!ctx.historyRow, ctx.resume) }))
854
+ .filter((r) => r.waiting)
855
+ .reduce((best, r) => (best === null || (r.timeLeftMs ?? Infinity) < (best.timeLeftMs ?? Infinity) ? r : best), /** @type {any} */ (null));
674
856
  let spend;
675
857
  if (ctx.historyRow) {
676
858
  const cd = costDisplay(ctx.historyRow.spentUsd, ctx.historyRow.spendComplete);
@@ -692,24 +874,60 @@ export function listRuns({ root, catalogue }) {
692
874
  runId,
693
875
  glyph,
694
876
  label,
877
+ pulse: glyphPulses({ glyph, label }),
878
+ stuck: glyph === '[II]',
879
+ resume: ctx.resume,
695
880
  spend,
696
- spendWhy: (!ctx.historyRow && spend === null) ? 'no history row yet and no priced spend.jsonl rows — nothing to floor' : null,
881
+ spendWhy: (!ctx.historyRow && spend === null)
882
+ ? (isRunningNow(ctx, glyph) ? 'running — no priced spend yet' : 'no history row yet and no priced spend.jsonl rows — nothing to floor')
883
+ : null,
884
+ waiting: waitingAsk !== null,
885
+ waitingAskId: waitingAsk ? waitingAsk.ask.askId : null,
886
+ timeLeftMs: waitingAsk ? waitingAsk.timeLeftMs : null,
697
887
  at: ctx.historyRow ? ctx.historyRow.at : null,
698
888
  askedAt,
699
- atWhy: (ctx.historyRow || askedAt) ? null : 'no history row yet (parked or died before one was written)',
889
+ startedAt: isRunningNow(ctx, glyph) ? ctx.startedAt : null,
890
+ atWhy: (ctx.historyRow || askedAt) ? null
891
+ : isRunningNow(ctx, glyph)
892
+ ? (ctx.startedAt ? null : 'running — start time not recorded (no pid record)')
893
+ : 'no history row yet (parked or died before one was written)',
700
894
  });
701
895
  }
702
896
  }
703
- // Newest first by `at` where present; rows with no `at` keep flow/run
704
- // order (already alphabetical from listFlowNames/listRunIds) at the end.
897
+ return orderRuns(rows);
898
+ }
899
+
900
+ /**
901
+ * The ONE ordering of Runs — History and Workflows both render the list in the
902
+ * order given (M4c amendment 1 (c)); a flow's top row is therefore the first
903
+ * run of that flow here, so a waiting run is the parent with no second rule:
904
+ * 1 waiting on you — least time left first; a stuck run (`[II]`, amendment 2)
905
+ * after the ones with a timer;
906
+ * 2 running (`[▶]`, the glyph's own liveness rule);
907
+ * 3 everything else — finish time `at`, newest first.
908
+ * A row with no known time keeps input order at the end of its section.
909
+ * @param {any[]} rows
910
+ * @returns {any[]}
911
+ */
912
+ export function orderRuns(rows) {
913
+ const sectionOf = (r) => ((r.waiting || r.stuck) ? 1 : r.glyph === '[▶]' ? 2 : 3);
705
914
  return rows
706
915
  .map((row, index) => ({ row, index }))
707
916
  .sort((a, b) => {
917
+ const sa = sectionOf(a.row);
918
+ const sb = sectionOf(b.row);
919
+ if (sa !== sb) return sa - sb;
920
+ if (sa === 1) {
921
+ if (!!a.row.stuck !== !!b.row.stuck) return a.row.stuck ? 1 : -1;
922
+ const at = typeof a.row.timeLeftMs === 'number' ? a.row.timeLeftMs : Infinity;
923
+ const bt = typeof b.row.timeLeftMs === 'number' ? b.row.timeLeftMs : Infinity;
924
+ return at !== bt ? at - bt : a.index - b.index;
925
+ }
708
926
  const am = typeof a.row.at === 'string' ? Date.parse(a.row.at) : NaN;
709
927
  const bm = typeof b.row.at === 'string' ? Date.parse(b.row.at) : NaN;
710
928
  const aKnown = Number.isFinite(am);
711
929
  const bKnown = Number.isFinite(bm);
712
- if (aKnown && bKnown) return bm - am;
930
+ if (aKnown && bKnown && am !== bm) return bm - am;
713
931
  if (aKnown !== bKnown) return aKnown ? -1 : 1;
714
932
  return a.index - b.index;
715
933
  })
@@ -770,17 +988,17 @@ function computeTryCount(closeClass, list) {
770
988
  * `log.json`. `null` when the flow/runId doesn't resolve to a real run
771
989
  * directory at all (caller renders 404); a `red` field names why a
772
990
  * sub-derivation couldn't fill (never invented).
773
- * @param {{root: string, flow: string, runId: string, catalogue: any}} opts
991
+ * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
774
992
  * @returns {any|null}
775
993
  */
776
994
  export function getRunDetail({
777
- root, flow, runId, catalogue,
995
+ root, flow, runId, catalogue, resumeAttempt,
778
996
  }) {
779
997
  const run = resolveRunPath(root, flow, runId);
780
998
  if (!run.ok) return null;
781
999
  if (!existsSync(run.runDir)) return null;
782
1000
 
783
- const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue);
1001
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue, resumeAttempt?.(flow, runId) ?? null);
784
1002
  const { glyph, label } = computeGlyph(ctx);
785
1003
 
786
1004
  // hamr's 2026-09-27 step-card review: the Run tab's step cards reuse the
@@ -911,6 +1129,13 @@ export function getRunDetail({
911
1129
  let stopReasonWhy = null;
912
1130
  if (ctx.historyRow && ctx.historyRow.outcome === 'complete') {
913
1131
  stopReasonWhy = 'run completed clean — there is no stop reason to show';
1132
+ } else if (ctx.historyRow && ctx.historyRow.outcome === 'rerun') {
1133
+ // M4b amendment 3: the human ended this run on purpose; an earlier redo's
1134
+ // audit row is not "why it stopped".
1135
+ stopReasonWhy = 'stopped by you (rerun), a fresh run was started — there is no failure to show';
1136
+ } else if (ctx.resume && (ctx.resume.state === 'starting' || ctx.resume.state === 'not-started')) {
1137
+ // M4b amendment 1: the human already answered — never "waiting on you".
1138
+ stopReasonWhy = ctx.resume.reason ? `${ctx.resume.label}: ${ctx.resume.reason}` : ctx.resume.label;
914
1139
  } else if (!ctx.historyRow && ctx.askJson && !ctx.consumedAnswerExists) {
915
1140
  stopReasonWhy = `waiting on you: ${typeof ctx.askJson.question === 'string' && ctx.askJson.question.length > 0 ? ctx.askJson.question : 'no question recorded'}`;
916
1141
  } else if (ctx.logJson && typeof ctx.logJson.red === 'string' && ctx.logJson.red.length > 0) {
@@ -959,7 +1184,8 @@ export function getRunDetail({
959
1184
  const wallMs = ctx.historyRow && typeof ctx.historyRow.wallMs === 'number' ? ctx.historyRow.wallMs : null;
960
1185
  const wallMsWhy = wallMs !== null
961
1186
  ? null
962
- : (ctx.historyRow ? 'history row has no wallMs recorded' : 'no history row yet (parked or died before completion)');
1187
+ : (ctx.historyRow ? 'history row has no wallMs recorded'
1188
+ : isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row yet (parked or died before completion)');
963
1189
 
964
1190
  let spend;
965
1191
  if (ctx.historyRow) {
@@ -982,8 +1208,10 @@ export function getRunDetail({
982
1208
  runId,
983
1209
  glyph,
984
1210
  label,
1211
+ pulse: glyphPulses({ glyph, label }),
1212
+ resume: ctx.resume,
985
1213
  outcome: ctx.historyRow ? ctx.historyRow.outcome : null,
986
- outcomeWhy: ctx.historyRow ? null : 'no history row (parked or died before completion)',
1214
+ outcomeWhy: ctx.historyRow ? null : (isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row (parked or died before completion)'),
987
1215
  capUsd: ctx.historyRow ? ctx.historyRow.capUsd : (ctx.flowRead.ok ? ctx.flowRead.arbiter.capUsd : null),
988
1216
  spend,
989
1217
  model,
@@ -1004,9 +1232,12 @@ export function getRunDetail({
1004
1232
  askedAt: (!ctx.historyRow && ctx.askJson && typeof ctx.askJson.askedAt === 'string')
1005
1233
  ? ctx.askJson.askedAt
1006
1234
  : null,
1235
+ startedAt: isRunningNow(ctx, glyph) ? ctx.startedAt : null,
1007
1236
  atWhy: (ctx.historyRow || (ctx.askJson && typeof ctx.askJson.askedAt === 'string'))
1008
1237
  ? null
1009
- : 'no history row yet (parked or died before completion)',
1238
+ : isRunningNow(ctx, glyph)
1239
+ ? (ctx.startedAt ? null : 'running — start time not recorded (no pid record)')
1240
+ : 'no history row yet (parked or died before completion)',
1010
1241
  };
1011
1242
  }
1012
1243
 
@@ -1201,7 +1432,7 @@ export function getRunJob({
1201
1432
  // ad-hoc reconstruction. Status vocabulary, used everywhere in the panel
1202
1433
  // (Inbox list, Ask tab, both API responses), is exactly the words
1203
1434
  // `listArchivedAsks` itself already returns from the books' own decision
1204
- // field: `accepted` / `rejected` / `reran` / `expired` / `unanswered` (a
1435
+ // field: `accepted` / `redo` / `reran` / `expired` / `unanswered` (a
1205
1436
  // parked, not-yet-expired ask with no consumed answer — this IS "open" in
1206
1437
  // the UI) / `open` (the rare case `listArchivedAsks` falls back to when an
1207
1438
  // archived ask.json itself fails to parse — no question/evidence can be
@@ -1214,7 +1445,7 @@ export function getRunJob({
1214
1445
  * its book-derived status is `unanswered` (parked, not yet answered, not
1215
1446
  * expired — `listArchivedAsks` already applies the expiry check at read
1216
1447
  * time) or the rare unparseable-archive fallback `open`. Every other status
1217
- * (`accepted`/`rejected`/`reran`/`expired`, or an `unrecognised: X` decision
1448
+ * (`accepted`/`redo`/`reran`/`expired`, or an `unrecognised: X` decision
1218
1449
  * value) is a PAST stop.
1219
1450
  * @param {string} status
1220
1451
  * @returns {boolean}
@@ -1241,12 +1472,28 @@ function isOpenStatus(status) {
1241
1472
  * can't be parsed (never a guessed number).
1242
1473
  * @param {any} ask one row from `runAsksInOrder`
1243
1474
  * @param {boolean} hasHistoryRow
1244
- * @returns {{open: boolean, timeLeftMs: number|null}}
1475
+ * @param {any} [resume] the run's `deriveResumeState` result, or null
1476
+ * @returns {{open: boolean, waiting: boolean, resume: any, timeLeftMs: number|null}}
1245
1477
  */
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 };
1478
+ function deriveAskOpenFields(ask, hasHistoryRow, resume = null) {
1479
+ // M4c amendment 3: an ask past its deadline reads `expired`, but one whose answer was saved in time
1480
+ // (`resume` is null for a late/unreadable one, `deriveResumeState`) is still open: it can be carried on.
1481
+ const answerSaved = resume != null && resume.askId === ask.askId
1482
+ && (resume.state === 'starting' || resume.state === 'not-started');
1483
+ const open = (isOpenStatus(ask.status) || (ask.status === 'expired' && answerSaved)) && !hasHistoryRow;
1484
+ // M4b fix: the ONE decision "is this ask waiting on the human". An open ask
1485
+ // whose answer is already saved (`resume` = `deriveResumeState` for THIS
1486
+ // ask, the run's own label) is open but not waiting: the human answered.
1487
+ const answered = open && resume != null && resume.askId === ask.askId
1488
+ && (resume.state === 'starting' || resume.state === 'not-started');
1489
+ const waiting = open && !answered;
1490
+ const expiresMs = waiting && typeof ask.expiresAt === 'string' ? Date.parse(ask.expiresAt) : NaN;
1491
+ return {
1492
+ open,
1493
+ waiting,
1494
+ resume: answered ? resume : null,
1495
+ timeLeftMs: waiting && Number.isFinite(expiresMs) ? Math.max(0, expiresMs - Date.now()) : null,
1496
+ };
1250
1497
  }
1251
1498
 
1252
1499
  /**
@@ -1285,6 +1532,7 @@ function normalizeArchivedRow(a) {
1285
1532
  reason: a.answer.reason ?? null,
1286
1533
  answeredAt: a.answer.answeredAt ?? null,
1287
1534
  archived: true,
1535
+ emits: typeof a.emits === 'string' ? a.emits : null,
1288
1536
  evidence: flattenEvidence(a.evidence),
1289
1537
  };
1290
1538
  }
@@ -1328,7 +1576,6 @@ function legacyRunAsks(runDir, hasHistoryRow) {
1328
1576
  const currentAskId = askJson && typeof askJson.askId === 'string' ? askJson.askId : null;
1329
1577
 
1330
1578
  const consumedFiles = names.filter((n) => CONSUMED_ANSWER_RE.test(n)).sort();
1331
- const decisionToStatus = { accept: 'accepted', reject: 'rejected', rerun: 'reran' };
1332
1579
 
1333
1580
  for (const file of consumedFiles) {
1334
1581
  const match = CONSUMED_ANSWER_RE.exec(file);
@@ -1356,7 +1603,7 @@ function legacyRunAsks(runDir, hasHistoryRow) {
1356
1603
  questionWhy: 'question not kept (before M4a-1)',
1357
1604
  askedAt: null,
1358
1605
  expiresAt: null,
1359
- status: decisionToStatus[parsed.decision] ?? `unrecognised: ${parsed.decision}`,
1606
+ status: DECISION_STATUS[normalizeDecision(parsed.decision)] ?? `unrecognised: ${parsed.decision}`,
1360
1607
  reason: typeof parsed.reason === 'string' ? parsed.reason : null,
1361
1608
  answeredAt: typeof parsed.answeredAt === 'string' ? parsed.answeredAt : null,
1362
1609
  archived: false,
@@ -1485,6 +1732,54 @@ export function deriveAskStepInfo(orderedAsks, auditRows, declSteps) {
1485
1732
  });
1486
1733
  }
1487
1734
 
1735
+ /**
1736
+ * M4c item 5 — the Ask tab's ONE grouping function: one block per signed ask
1737
+ * line. Key = the archive's recorded `emits`, else the step the ask's own "paused" audit row names (`stepName`,
1738
+ * `deriveAskStepInfo`); when the books cannot name a step (count mismatch, a
1739
+ * pre-M4a-1 run) the key falls back to the question text, then to one shared
1740
+ * "unknown" key — never a guessed pairing. Draft numbers are the ask's 1-based
1741
+ * position within its own block (how many times this line has parked).
1742
+ * `current` is the newest draft; `answers` is one row per draft that has a
1743
+ * recorded decision (the newest draft only when it is not itself open),
1744
+ * decision word via `DECISION_STATUS` (old `reject` files already read `redo`).
1745
+ * @param {any[]} asks rows as built by `getRunAsks` (oldest first)
1746
+ * @returns {any[]}
1747
+ */
1748
+ export function groupAskBlocks(asks) {
1749
+ const decisionWord = (status) => Object.keys(DECISION_STATUS).find((k) => DECISION_STATUS[k] === status) ?? status;
1750
+ const byKey = new Map();
1751
+ for (const ask of asks) {
1752
+ let key = 'unknown';
1753
+ if (typeof ask.emits === 'string') key = `step:${ask.emits}`;
1754
+ else if (typeof ask.stepName === 'string') key = `step:${ask.stepName}`;
1755
+ else if (typeof ask.question === 'string') key = `q:${ask.question}`;
1756
+ if (!byKey.has(key)) byKey.set(key, []);
1757
+ byKey.get(key).push(ask);
1758
+ }
1759
+ return [...byKey.entries()].map(([key, drafts]) => {
1760
+ const current = drafts[drafts.length - 1];
1761
+ const answers = [];
1762
+ drafts.forEach((d, i) => {
1763
+ if (d === current && d.open) return;
1764
+ if (d.status === 'unanswered' || d.status === 'open') return;
1765
+ answers.push({
1766
+ draft: i + 1, askId: d.askId, decision: decisionWord(d.status), reason: d.reason ?? null, answeredAt: d.answeredAt ?? null,
1767
+ });
1768
+ });
1769
+ return {
1770
+ key,
1771
+ stepName: current.emits ?? current.stepName ?? null,
1772
+ stepLine: current.stepLine ?? null,
1773
+ question: current.question ?? null,
1774
+ questionWhy: current.questionWhy ?? null,
1775
+ draftNo: drafts.length,
1776
+ askIds: drafts.map((d) => d.askId),
1777
+ current,
1778
+ answers,
1779
+ };
1780
+ });
1781
+ }
1782
+
1488
1783
  /**
1489
1784
  * `GET /api/runs/:flow/:runId/asks` — the Ask tab (M4a-1 scope item 1):
1490
1785
  * every ask this run's books can name, in order, each carrying full
@@ -1496,11 +1791,14 @@ export function deriveAskStepInfo(orderedAsks, auditRows, declSteps) {
1496
1791
  * 3" — a plain array position, not derived from any book) and `stepName`/
1497
1792
  * `stepLine`/`stepWhy` (`deriveAskStepInfo`) so the Ask tab's header can
1498
1793
  * 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}
1794
+ * M4b piece 4: also carries `resume` (the SAME `deriveResumeState` the run
1795
+ * detail carries, `null` for a finished run or nothing to say) so the Ask tab
1796
+ * can tell "open, answerable" from "answer saved" without a second fetch.
1797
+ * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
1798
+ * @returns {{flow:string, runId:string, asks:any[], resume: any, blocks: any[]}|null}
1501
1799
  */
1502
1800
  export function getRunAsks({
1503
- root, flow, runId, catalogue,
1801
+ root, flow, runId, catalogue, resumeAttempt,
1504
1802
  }) {
1505
1803
  const run = resolveRunPath(root, flow, runId);
1506
1804
  if (!run.ok) return null;
@@ -1518,16 +1816,28 @@ export function getRunAsks({
1518
1816
  });
1519
1817
  const declSteps = flowRead.ok ? flowRead.declaration.steps : null;
1520
1818
  const stepInfo = deriveAskStepInfo(ordered, auditRows, declSteps);
1819
+ let resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flow, runId) ?? null, ask: readAsk(run.runDir) });
1820
+ // M4c amendment 2: the Ask tab says what the run list says — stuck, by the one rule (`isStuck`).
1821
+ let runStuck = false;
1822
+ const lockRead = readResumeLock(run.runDir);
1823
+ if (resume && isStuck({ resume, liveness: runLiveness(run.runDir), lock: lockRead.state })) {
1824
+ const label = stuckLabelFor({ resume, lock: lockRead.state });
1825
+ resume = { ...resume, label, ...(label === STUCK_LOCK_LABEL ? { lockPath: lockRead.path } : {}) };
1826
+ runStuck = true;
1827
+ }
1521
1828
  const asks = ordered.map((ask, i) => ({
1522
1829
  ...ask,
1523
- ...deriveAskOpenFields(ask, hasHistoryRow),
1830
+ ...deriveAskOpenFields(ask, hasHistoryRow, resume),
1831
+ stuck: runStuck && resume?.askId === ask.askId,
1524
1832
  index: i + 1,
1525
1833
  total: ordered.length,
1526
1834
  stepName: stepInfo[i].step,
1527
1835
  stepLine: stepInfo[i].line,
1528
1836
  stepWhy: stepInfo[i].why,
1529
1837
  }));
1530
- return { flow, runId, asks };
1838
+ return {
1839
+ flow, runId, asks, resume, blocks: groupAskBlocks(asks),
1840
+ };
1531
1841
  }
1532
1842
 
1533
1843
  /**
@@ -1545,10 +1855,10 @@ export function getRunAsks({
1545
1855
  * force-`false` here as a second, independent check (belt-and-braces on the
1546
1856
  * one thing the brief calls out by name: "the Inbox tab's open count counts
1547
1857
  * only truly open asks — parked run, no history row, unexpired, unanswered").
1548
- * @param {{root: string}} opts
1858
+ * @param {{root: string, resumeAttempt?: (flow: string, runId: string) => any}} opts
1549
1859
  * @returns {any[]}
1550
1860
  */
1551
- export function listStops({ root }) {
1861
+ export function listStops({ root, resumeAttempt }) {
1552
1862
  const rows = [];
1553
1863
  for (const flowName of listFlowNames(root)) {
1554
1864
  const flowDir = join(root, flowName);
@@ -1557,33 +1867,94 @@ export function listStops({ root }) {
1557
1867
  const run = resolveRunPath(root, flowName, runId);
1558
1868
  if (!run.ok) continue;
1559
1869
  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
- });
1870
+ const resume = hasHistoryRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(run.runDir), attempt: resumeAttempt?.(flowName, runId) ?? null, ask: readAsk(run.runDir) });
1871
+ // M4c amendment 2: stuck by the ONE rule (`isStuck`), marked on the ask whose answer is saved.
1872
+ const lockState = readResumeLock(run.runDir).state;
1873
+ const stuckAskId = !hasHistoryRow && isStuck({ resume, liveness: runLiveness(run.runDir), lock: lockState })
1874
+ ? (resume?.askId ?? null) : null;
1875
+ const stuckLabel = stuckLabelFor({ resume, lock: lockState });
1876
+ const runAsks = runAsksInOrder(run.runDir, hasHistoryRow).map((ask) => ({
1877
+ flow: flowName,
1878
+ runId,
1879
+ ...ask,
1880
+ ...deriveAskOpenFields(ask, hasHistoryRow, resume),
1881
+ stuck: stuckAskId !== null && ask.askId === stuckAskId,
1882
+ stuckLabel: stuckAskId !== null && ask.askId === stuckAskId ? stuckLabel : null,
1883
+ }));
1884
+ // M4c item 4: a run with no end row, no ask waiting on the human and no
1885
+ // saved-but-unresumed answer, whose newest pid row is alive, is "working
1886
+ // on your <decision>" — marked on that run's newest answered ask (the
1887
+ // one the live process took). `runLiveness` is the ONE liveness rule.
1888
+ const nothingWaiting = !runAsks.some((r) => r.waiting || r.resume);
1889
+ if (!hasHistoryRow && nothingWaiting && runLiveness(run.runDir) === 'running') {
1890
+ const answered = runAsks.filter((r) => WORKING_WORD[r.status]);
1891
+ const newest = answered.reduce((best, r) => (best === null || sortMs(r.answeredAt) >= sortMs(best.answeredAt) ? r : best), null);
1892
+ if (newest) newest.working = WORKING_WORD[newest.status];
1567
1893
  }
1894
+ for (const r of runAsks) rows.push(r);
1568
1895
  }
1569
1896
  }
1897
+ return orderStops(rows);
1898
+ }
1899
+
1900
+ /** ask status -> the answer's own word, for "working on your <word>…". */
1901
+ const WORKING_WORD = { accepted: 'accept', redo: 'redo', reran: 'rerun' };
1902
+
1903
+ /** ms for sorting; NaN when the stamp is absent/unparseable. */
1904
+ function sortMs(iso) {
1905
+ return typeof iso === 'string' ? Date.parse(iso) : NaN;
1906
+ }
1907
+
1908
+ /**
1909
+ * The ONE ordering of the Inbox (M4c item 4, hamr 2026-09-30); the page renders
1910
+ * in the order given and stamps each row's `section`:
1911
+ * 1 waiting on you — least time left first ("runs out first"); a stuck run
1912
+ * (amendment 2: answer saved, nobody carrying it on) after the timed asks;
1913
+ * 2 working on an answer you gave (`working`), or answer saved and resume not
1914
+ * started (`resume`) — newest answer first;
1915
+ * 3 answered and expired asks — newest first (answeredAt, else expiresAt).
1916
+ * A row with no known time sorts last within its section, ties by input order.
1917
+ * @param {any[]} rows
1918
+ * @returns {any[]}
1919
+ */
1920
+ export function orderStops(rows) {
1921
+ const sectionOf = (r) => ((r.waiting || r.stuck) ? 1 : (r.working || r.resume) ? 2 : 3);
1922
+ const key = (r) => {
1923
+ const t = sectionOf(r) === 3 ? (sortMs(r.answeredAt) || sortMs(r.expiresAt)) : sortMs(r.answeredAt);
1924
+ return Number.isFinite(t) ? t : NaN;
1925
+ };
1570
1926
  return rows
1571
- .map((row, index) => ({ row, index }))
1927
+ .map((row, index) => ({ row: { ...row, section: sectionOf(row) }, index }))
1572
1928
  .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) {
1929
+ const sa = a.row.section;
1930
+ const sb = b.row.section;
1931
+ if (sa !== sb) return sa - sb;
1932
+ if (sa === 1) {
1933
+ if (!!a.row.stuck !== !!b.row.stuck) return a.row.stuck ? 1 : -1;
1575
1934
  const at = typeof a.row.timeLeftMs === 'number' ? a.row.timeLeftMs : Infinity;
1576
1935
  const bt = typeof b.row.timeLeftMs === 'number' ? b.row.timeLeftMs : Infinity;
1577
- if (at !== bt) return at - bt;
1578
- return a.index - b.index;
1936
+ return at !== bt ? at - bt : a.index - b.index;
1579
1937
  }
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;
1938
+ const ak = key(a.row);
1939
+ const bk = key(b.row);
1940
+ const aKnown = Number.isFinite(ak);
1941
+ const bKnown = Number.isFinite(bk);
1942
+ if (aKnown && bKnown && ak !== bk) return bk - ak;
1585
1943
  if (aKnown !== bKnown) return aKnown ? -1 : 1;
1586
1944
  return a.index - b.index;
1587
1945
  })
1588
1946
  .map(({ row }) => row);
1589
1947
  }
1948
+
1949
+ /**
1950
+ * N for `Inbox (N)` (M4c item 3): asks open and not expired, across every flow
1951
+ * and run, plus stuck runs (amendment 2: the human must act). An answered ask
1952
+ * whose resume is carried on is not `waiting`, so not counted; a crashed one
1953
+ * (answer taken, process gone) is not stuck and not counted;
1954
+ * an expired ask is not `open`. The page only shows this number.
1955
+ * @param {any[]} rows `listStops` rows
1956
+ * @returns {number}
1957
+ */
1958
+ export function inboxOpenCount(rows) {
1959
+ return rows.filter((r) => r.waiting || r.stuck).length;
1960
+ }