fwdloop 0.17.0 → 0.19.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
@@ -38,6 +38,9 @@ import { readSpendRows } from '../provider.js';
38
38
  import { applyRunValues, parseWaitMs, pickRunValues, VALUES_FILE_RE } from '../runvalues.js';
39
39
  import { readSetup } from '../setup.js';
40
40
  import { checkedLines, notCheckedBlock, NOT_CHECKED_LABEL } from '../checked.js';
41
+ import {
42
+ catchUpWords, endedWords, nextInWords, nextTimeWords, scheduledNextFor, scheduledWords,
43
+ } from '../summary-words.js';
41
44
  import { MAX_STRUCTURE_RETRIES } from '../drafter.js';
42
45
  import {
43
46
  runLiveness, booksFresh, readResumeLock,
@@ -360,13 +363,14 @@ export function glyphPulses(g) {
360
363
  * - `[II]` stuck (M4c amendment 2, `isStuck`) — the answer is saved, not taken,
361
364
  * and no live process (pid row or resume lock holder) carries the run on.
362
365
  * A saved answer with a live process is `[▶]` working on your answer.
366
+ * - `[▶]` starting (live-walk fix) — no end row, no open ask, no pid row yet, and the starter reads this run's start folder as phase `starting` (`ctx.starting`).
363
367
  * - `[?]` crashed after taking your answer (amendment 2 (f)) — the answer was
364
368
  * consumed, the process is gone, no end row: cannot be carried on.
365
- * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string, resumable?: boolean, stoppedAtAsk?: string|null, jobEdited?: boolean}} ctx
369
+ * @param {{historyRow: any, askJson: any, consumedAnswerExists: boolean, hasStateJson: boolean, resume?: any, liveness?: 'running'|'gone'|'unknown', booksFresh?: boolean, lock?: string, resumable?: boolean, stoppedAtAsk?: string|null, jobEdited?: boolean, starting?: boolean}} ctx
366
370
  * @returns {{glyph: '[✓]'|'[✗]'|'[·]'|'[!]'|'[▶]'|'[?]'|'[II]'|'[■]', label: string}}
367
371
  */
368
372
  export function computeGlyph({
369
- historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock, resumable, stoppedAtAsk, jobEdited,
373
+ historyRow, askJson, consumedAnswerExists, hasStateJson, resume, liveness, booksFresh, lock, resumable, stoppedAtAsk, jobEdited, starting,
370
374
  }) {
371
375
  if (historyRow) {
372
376
  if (historyRow.outcome === 'complete') return { glyph: '[✓]', label: 'passed' };
@@ -411,6 +415,8 @@ export function computeGlyph({
411
415
  // (`liveness`, src/liveness.js); with no row or no /proc (`unknown`), the
412
416
  // 10-minute books rule. Never `[▶]` off a parked ask (branches above).
413
417
  if (liveness === 'running') return { glyph: '[▶]', label: 'running' };
418
+ // The starter's own word (`startingFor`): the start folder is alive and the run has no pid row yet — not a crash.
419
+ if (starting === true && liveness !== 'gone') return { glyph: '[▶]', label: 'starting' };
414
420
  if (liveness === 'gone') return { glyph: '[?]', label: 'the process working on this run is gone (no end row was written)' };
415
421
  if (booksFresh) return { glyph: '[▶]', label: 'running (no pid record; its books changed in the last 10 minutes)' };
416
422
  if (hasStateJson && !askJson) {
@@ -883,9 +889,10 @@ const JOB_EDITED_LINE = 'stopped — the job was edited; start a new run';
883
889
  * @param {string} runId
884
890
  * @param {any} catalogue
885
891
  * @param {any} [attempt] the panel's in-memory resume-attempt record for this run, or null
892
+ * @param {(flow: string, runId: string) => boolean} [startingRun] the starter's "this run's start is in phase `starting`" (absent = no)
886
893
  * @returns {any}
887
894
  */
888
- function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attempt = null) {
895
+ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attempt = null, startingRun = undefined) {
889
896
  const flowRead = readFlow({ root, name: flowName, catalogue });
890
897
  // M4e amendment 5 item 3 / amendment 4 item 6: the run's own signed values (its newest version) lie over the flow's
891
898
  const inForce = flowRead.ok ? applyRunValues(flowRead.arbiter, flowName, flowRead.signature.flow, pickRunValues(runDir)) : null;
@@ -899,7 +906,8 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
899
906
  const stateJson = readRunState(runDir);
900
907
  const consumedAnswerExists = hasConsumedAnswer(runDir, askJson && typeof askJson.askId === 'string' ? askJson.askId : null);
901
908
  // A finished run has no resume to report (its history row says how it ended).
902
- const resume = historyRow ? null : deriveResumeState({ savedAnswer: readSavedAnswer(runDir), attempt, ask: askJson });
909
+ const savedAnswer = historyRow ? null : readSavedAnswer(runDir);
910
+ const resume = historyRow ? null : deriveResumeState({ savedAnswer, attempt, ask: askJson });
903
911
  const stuckInputs = historyRow ? { liveness: 'unknown', lock: 'none' } : readStuckInputs(runDir);
904
912
 
905
913
  return {
@@ -927,6 +935,8 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
927
935
  consumedAnswerExists,
928
936
  hasStateJson: stateJson !== null,
929
937
  resume,
938
+ // M11 am4 item 1: when the saved answer was written (a stuck run has no stop time; its 7 days in Needs you count from here), or null
939
+ savedAnswerAt: savedAnswer ? savedAnswer.answeredAt : null,
930
940
  // M4c: only read for a run with no end row (an end row always wins).
931
941
  liveness: stuckInputs.liveness,
932
942
  lock: stuckInputs.lock,
@@ -934,6 +944,7 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
934
944
  // M4c exit walk: when the process that is working on the run started (its newest pid row's
935
945
  // own `startedAt`), so a `[▶]` run has a real time and never "parked or died". Not a book change.
936
946
  startedAt: historyRow ? null : lastPidStartedAt(runDir),
947
+ starting: !historyRow && !askJson && startingRun?.(flowName, runId) === true,
937
948
  };
938
949
  }
939
950
 
@@ -1039,11 +1050,11 @@ export function getRunControls({
1039
1050
  * null`, an explicit `why`) — no flow is silently missing from the list.
1040
1051
  * Ordered by `orderRuns` (waiting on you, running, then newest `at` first; a row
1041
1052
  * with no `at` is never given a guessed one).
1042
- * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
1043
- * `resumeAttempt`: the panel's in-memory resume-attempt lookup (M4b piece 2); absent = none.
1053
+ * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any, startingRun?: (flow: string, runId: string) => boolean, now?: () => number}} opts
1054
+ * `now`: the clock for Needs you's 7-day rule (absent = Date.now). `startingRun`: the starter's phase-`starting` rule for one run (absent = no). `resumeAttempt`: the panel's in-memory resume-attempt lookup (M4b piece 2); absent = none.
1044
1055
  * @returns {any[]}
1045
1056
  */
1046
- export function listRuns({ root, catalogue, resumeAttempt }) {
1057
+ export function listRuns({ root, catalogue, resumeAttempt, startingRun, now = Date.now }) {
1047
1058
  const rows = [];
1048
1059
  for (const flowName of listFlowNames(root)) {
1049
1060
  const flowDir = join(root, flowName);
@@ -1063,8 +1074,9 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
1063
1074
  });
1064
1075
  continue;
1065
1076
  }
1066
- const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue, resumeAttempt?.(flowName, runId) ?? null);
1077
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue, resumeAttempt?.(flowName, runId) ?? null, startingRun);
1067
1078
  const { glyph, label } = computeGlyph(ctx);
1079
+ const controls = runControls(ctx, glyph, label);
1068
1080
  // M4c amendment 1 (c): the ask waiting on the human, by the same rule
1069
1081
  // listStops uses (deriveAskOpenFields) — the least time left if several.
1070
1082
  const waitingAsk = runAsksInOrder(run.runDir, !!ctx.historyRow)
@@ -1095,7 +1107,10 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
1095
1107
  ...signParts(glyph, label, ctx.historyRow?.outcome === 'rerun'),
1096
1108
  pulse: glyphPulses({ glyph, label }),
1097
1109
  stuck: glyph === '[II]',
1098
- controls: runControls(ctx, glyph, label),
1110
+ controls,
1111
+ needs: needsYouTag(glyph, controls, glyph === '[II]' ? ctx.savedAnswerAt : (ctx.historyRow ? ctx.historyRow.at : null), now()),
1112
+ live: isRunningNow(ctx, glyph),
1113
+ model: deriveRunModel(ctx.auditRows),
1099
1114
  resume: ctx.resume,
1100
1115
  spend,
1101
1116
  spendWhy: (!ctx.historyRow && spend === null)
@@ -1155,6 +1170,83 @@ export function orderRuns(rows) {
1155
1170
  .map(({ row }) => row);
1156
1171
  }
1157
1172
 
1173
+ /**
1174
+ * M11 am1 item 2 + am2: the ONE rule for a run's Needs-you tag, read off the sign and `runControls` (no second rule). `Accept`: waiting at an open ask.
1175
+ * `Resume`: stuck `[II]`, or stopped `[■]` whose Run tab shows the Resume button. An expired ask `[!]` is never here (it stays in the Inbox).
1176
+ * M11 am3 item 5: a Resume run leaves Needs you once its stop time (`at`, the history row's) is `RUNS_LIST_LIMITS.needsYouDays` old; exactly that old is out.
1177
+ * M11 am4 item 1: a stuck `[II]` run has no stop time; the caller passes the time its saved answer was written. A run with no readable time stays in. An Accept run is never dropped by age (its ask has its own wait).
1178
+ * @param {string} glyph a `computeGlyph` sign @param {{atAsk: boolean, canResume: boolean}} controls `runControls`' answer
1179
+ * @param {string|null} [at] the run's stop time from the books @param {number} [nowMs]
1180
+ * @returns {'Accept'|'Resume'|null}
1181
+ */
1182
+ export function needsYouTag(glyph, controls, at = null, nowMs = Date.now()) {
1183
+ if (glyph === '[·]' && controls.atAsk) return 'Accept';
1184
+ if (glyph !== '[II]' && !(glyph === '[■]' && controls.canResume)) return null;
1185
+ const t = typeof at === 'string' ? Date.parse(at) : NaN;
1186
+ if (Number.isFinite(t) && nowMs - t >= RUNS_LIST_LIMITS.needsYouDays * 86_400_000) return null;
1187
+ return 'Resume';
1188
+ }
1189
+
1190
+ /** M11 scope item 2.5/2.6 and rules, am3 item 5: the named limits of the runs list, in ONE place (30 quiet days, 7 older runs, 7 days in Needs you for a Resume run). The page reads them from `GET /api/runs`. */
1191
+ export const RUNS_LIST_LIMITS = Object.freeze({ quietDays: 30, olderRuns: 7, needsYouDays: 7 });
1192
+
1193
+ /**
1194
+ * M11: one entry per job (flow), newest activity first. A job's activity is its newest KNOWN run time (`at`, else `askedAt`, else `startedAt`);
1195
+ * `quiet` only when that time is known and older than the quiet limit: an unknown age is never guessed into quiet, and a job with no runs is not quiet.
1196
+ * @param {any[]} rows `listRuns` rows @param {number} nowMs
1197
+ * @returns {{flow: string, quiet: boolean, activityMs: number|null}[]}
1198
+ */
1199
+ export function summarizeJobs(rows, nowMs) {
1200
+ /** @type {Map<string, number|null>} */
1201
+ const byFlow = new Map();
1202
+ for (const r of rows) {
1203
+ if (!byFlow.has(r.flow)) byFlow.set(r.flow, null);
1204
+ if (r.runId === null) continue; // eslint-disable-line no-continue
1205
+ const t = [r.at, r.askedAt, r.startedAt].map((x) => (typeof x === 'string' ? Date.parse(x) : NaN)).find((x) => Number.isFinite(x));
1206
+ if (t !== undefined && (byFlow.get(r.flow) === null || t > /** @type {number} */ (byFlow.get(r.flow)))) byFlow.set(r.flow, t);
1207
+ }
1208
+ const quietMs = RUNS_LIST_LIMITS.quietDays * 86_400_000;
1209
+ return [...byFlow.entries()]
1210
+ .map(([flow, activityMs]) => ({ flow, quiet: activityMs !== null && nowMs - activityMs > quietMs, activityMs }))
1211
+ .sort((a, b) => {
1212
+ if (a.activityMs !== b.activityMs) {
1213
+ if (a.activityMs === null) return 1;
1214
+ if (b.activityMs === null) return -1;
1215
+ return b.activityMs - a.activityMs;
1216
+ }
1217
+ return a.flow < b.flow ? -1 : a.flow > b.flow ? 1 : 0;
1218
+ });
1219
+ }
1220
+
1221
+ /**
1222
+ * M11 am1 item 3: every job with a trigger, soonest next run first (a job with no clock slot — a file trigger, or not armed yet — after those that
1223
+ * have one, by name). Built from the owners the run page's SCHEDULED block uses (`triggerRead`, `scheduledWords`); `at` / `in` are null when
1224
+ * there is no next time (nothing is invented). A job that cannot be read, or has no trigger, is absent.
1225
+ * M11 am4 item 2: each card carries `runId`, the job's newest run (the first row `listRuns` gives that job, the one the runs list heads its job card with), or null when it has none.
1226
+ * @param {{root: string, triggerRead: (flow: string) => any, now?: () => number, home?: string, rows?: {flow: string, runId: string|null}[]}} opts
1227
+ * @returns {{flow: string, at: string|null, in: string|null, words: string, runId: string|null}[]}
1228
+ */
1229
+ export function listScheduled({
1230
+ root, triggerRead, now = Date.now, home, rows = [],
1231
+ }) {
1232
+ const t0 = now();
1233
+ const out = [];
1234
+ for (const flow of listFlowNames(root)) {
1235
+ const t = triggerRead(flow);
1236
+ if (!t || !t.trigger) continue; // eslint-disable-line no-continue
1237
+ const ms = t.armed && typeof t.nextSlotMs === 'number' ? t.nextSlotMs : null;
1238
+ out.push({
1239
+ ms, flow, at: ms === null ? null : nextTimeWords(ms, t0), in: ms === null ? null : nextInWords(ms, t0), words: String(scheduledWords(t.trigger, home)),
1240
+ runId: rows.find((r) => r.flow === flow)?.runId ?? null,
1241
+ });
1242
+ }
1243
+ out.sort((a, b) => {
1244
+ if (a.ms !== b.ms) return a.ms === null ? 1 : b.ms === null ? -1 : a.ms - b.ms;
1245
+ return a.flow < b.flow ? -1 : a.flow > b.flow ? 1 : 0;
1246
+ });
1247
+ return out.map(({ ms, ...card }) => card);
1248
+ }
1249
+
1158
1250
  /**
1159
1251
  * hamr's 2026-09-27 step-card review: the ONE place raw `audit.jsonl` rows
1160
1252
  * get their server-derived fields (`action`/`tokensDisplay`/`atWhy`/
@@ -1204,6 +1296,69 @@ function computeTryCount(closeClass, listAll) {
1204
1296
  return list.length;
1205
1297
  }
1206
1298
 
1299
+ /** The job line a step of this run came from (`fromLine` of the declared step that emits `emits`), or null when the books cannot say. */
1300
+ function lineOfStep(ctx, emits) {
1301
+ if (!ctx.flowRead.ok || typeof emits !== 'string') return null;
1302
+ const st = (ctx.flowRead.declaration.steps ?? []).find((x) => x.emits === emits);
1303
+ return st && Number.isInteger(st.fromLine) ? st.fromLine : null;
1304
+ }
1305
+
1306
+ /** The job line of the ask a waiting run is parked at: its newest `paused` audit row's step. */
1307
+ function waitingLineOf(ctx) {
1308
+ let emits = null;
1309
+ for (const r of ctx.auditRows) if (r.verdict === 'paused') emits = r.step;
1310
+ return lineOfStep(ctx, emits);
1311
+ }
1312
+
1313
+ /**
1314
+ * M9 piece 6: the line of the ask this JOB is waiting at (any of its runs, the newest first), or null. Reads each run that holds an ask
1315
+ * through the same `runControls` the Stop door uses (`atAsk`), so "waiting" is one decision.
1316
+ */
1317
+ function jobWaitingLine(root, flowDir, flow, catalogue) {
1318
+ const ids = listRunIds(flowDir).sort((a, b) => (Number(b.replace(/\D/g, '')) || 0) - (Number(a.replace(/\D/g, '')) || 0));
1319
+ for (const id of ids) {
1320
+ const run = resolveRunDir(flowDir, id);
1321
+ if (!run.ok || !readAsk(run.runDir)) continue; // eslint-disable-line no-continue
1322
+ const ctx = loadRunContext(root, flowDir, run.runDir, flow, id, catalogue, null);
1323
+ const g = computeGlyph(ctx);
1324
+ if (runControls(ctx, g.glyph, g.label).atAsk) return waitingLineOf(ctx);
1325
+ }
1326
+ return null;
1327
+ }
1328
+
1329
+ /**
1330
+ * M9 piece 6 (ladder M9 item 7): the summary block at the top of a run page, as data. Words come from `src/summary-words.js` only, built
1331
+ * from typed facts (the history row's outcome, the declared step's line, the signed trigger and its ledger). `ended` is null while the run
1332
+ * is live; `scheduled` is null when the job has no trigger; `canSchedule` (am3 item 1) is the trigger door's own `hasGreenRun` answer; `catchUp` is a fixed sentence when this run was started late (am2 item 1).
1333
+ * @returns {{ended: {reason: string, next: string}|null, scheduled: {text: string, next: string, nextRed: boolean}|null, canSchedule: boolean, catchUp: string|null}}
1334
+ */
1335
+ function runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }) {
1336
+ const died = !ctx.historyRow && glyph === '[?]';
1337
+ const outcome = ctx.historyRow ? ctx.historyRow.outcome ?? null : null;
1338
+ let line = null;
1339
+ if (outcome !== null && outcome !== 'complete') {
1340
+ let emits = null;
1341
+ for (const r of ctx.auditRows) if (isBlockedVerdict(r.verdict)) emits = r.step;
1342
+ line = lineOfStep(ctx, emits);
1343
+ }
1344
+ const send = ctx.arbiter && Array.isArray(ctx.arbiter.sends) ? ctx.arbiter.sends.find((x) => x.target && typeof x.target.path === 'string') : undefined;
1345
+ const ended = endedWords({
1346
+ outcome, died, line, destination: send ? send.target.path : null, canResume: ctx.resumable === true && ctx.sameJob === true, home,
1347
+ });
1348
+ let scheduled = null;
1349
+ const t = typeof triggerRead === 'function' ? triggerRead(ctx.flowName) : null;
1350
+ if (t && t.trigger) {
1351
+ const nx = scheduledNextFor({
1352
+ trigger: t.trigger, armed: t.armed, nextSlotMs: t.nextSlotMs, lastOutcome: t.lastOutcome, waitingLine: jobWaitingLine(root, ctx.flowDir, ctx.flowName, catalogue), now: now(),
1353
+ });
1354
+ scheduled = { text: String(scheduledWords(t.trigger, home)), next: nx.text, nextRed: nx.red };
1355
+ }
1356
+ let rec = null;
1357
+ const f = readFileInside(ctx.runDir, 'trigger.json');
1358
+ if (f.ok) { try { rec = JSON.parse(f.text); } catch { rec = null; } }
1359
+ return { ended, scheduled, canSchedule: !!(t && t.hasGreenRun), catchUp: catchUpWords(rec) };
1360
+ }
1361
+
1207
1362
  /**
1208
1363
  * `GET /api/runs/:flow/:runId` — the Run tab (M4a scope item 2): the step
1209
1364
  * map from `declaration.steps`, step cards -> attempts from `audit.jsonl`
@@ -1211,17 +1366,17 @@ function computeTryCount(closeClass, listAll) {
1211
1366
  * `log.json`. `null` when the flow/runId doesn't resolve to a real run
1212
1367
  * directory at all (caller renders 404); a `red` field names why a
1213
1368
  * sub-derivation couldn't fill (never invented).
1214
- * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
1369
+ * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any, startingRun?: (flow: string, runId: string) => boolean, triggerRead?: (flow: string) => any, now?: () => number, home?: string}} opts
1215
1370
  * @returns {any|null}
1216
1371
  */
1217
1372
  export function getRunDetail({
1218
- root, flow, runId, catalogue, resumeAttempt,
1373
+ root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead, now = Date.now, home,
1219
1374
  }) {
1220
1375
  const run = resolveRunPath(root, flow, runId);
1221
1376
  if (!run.ok) return null;
1222
1377
  if (!existsSync(run.runDir)) return null;
1223
1378
 
1224
- const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue, resumeAttempt?.(flow, runId) ?? null);
1379
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue, resumeAttempt?.(flow, runId) ?? null, startingRun);
1225
1380
  const { glyph, label } = computeGlyph(ctx);
1226
1381
 
1227
1382
  // hamr's 2026-09-27 step-card review: the Run tab's step cards reuse the
@@ -1438,6 +1593,8 @@ export function getRunDetail({
1438
1593
  signWords: SIGN_WORDS,
1439
1594
  pulse: glyphPulses({ glyph, label }),
1440
1595
  controls: runControls(ctx, glyph, label),
1596
+ // M9 piece 6: the block at the top of the run page (ENDED / NEXT, SCHEDULED / NEXT), words set by code
1597
+ summary: runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }),
1441
1598
  resume: ctx.resume,
1442
1599
  outcome: ctx.historyRow ? ctx.historyRow.outcome : null,
1443
1600
  outcomeWhy: ctx.historyRow ? null : (isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row (parked or died before completion)'),
@@ -1656,7 +1813,10 @@ function buildJobPlan(declaration, asks, flowDir, flowHash = null) {
1656
1813
  };
1657
1814
  });
1658
1815
  const setup = readSetup(flowDir);
1659
- const signRow = setup.present ? setup.rows.find((r) => r.kind === 'sign') : undefined;
1816
+ // the signing of THIS job: the sign / trigger-only re-sign row carrying its flow hash; else the first sign row (which then reads as another signing)
1817
+ const signRow = setup.present
1818
+ ? (setup.rows.findLast((r) => (r.kind === 'sign' || r.kind === 'trigger-resign') && flowHash !== null && r.flowHash === flowHash) ?? setup.rows.find((r) => r.kind === 'sign'))
1819
+ : undefined;
1660
1820
  const ofThisJob = !!signRow && (typeof signRow.flowHash !== 'string' || flowHash === null || signRow.flowHash === flowHash);
1661
1821
  const nc = ofThisJob ? signRow?.notChecked : undefined;
1662
1822
  const recorded = !!nc && Array.isArray(nc.items);