fwdloop 0.17.0 → 0.18.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, 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;
@@ -934,6 +941,7 @@ function loadRunContext(root, flowDir, runDir, flowName, runId, catalogue, attem
934
941
  // M4c exit walk: when the process that is working on the run started (its newest pid row's
935
942
  // own `startedAt`), so a `[▶]` run has a real time and never "parked or died". Not a book change.
936
943
  startedAt: historyRow ? null : lastPidStartedAt(runDir),
944
+ starting: !historyRow && !askJson && startingRun?.(flowName, runId) === true,
937
945
  };
938
946
  }
939
947
 
@@ -1039,11 +1047,11 @@ export function getRunControls({
1039
1047
  * null`, an explicit `why`) — no flow is silently missing from the list.
1040
1048
  * Ordered by `orderRuns` (waiting on you, running, then newest `at` first; a row
1041
1049
  * 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.
1050
+ * @param {{root: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any, startingRun?: (flow: string, runId: string) => boolean}} opts
1051
+ * `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
1052
  * @returns {any[]}
1045
1053
  */
1046
- export function listRuns({ root, catalogue, resumeAttempt }) {
1054
+ export function listRuns({ root, catalogue, resumeAttempt, startingRun }) {
1047
1055
  const rows = [];
1048
1056
  for (const flowName of listFlowNames(root)) {
1049
1057
  const flowDir = join(root, flowName);
@@ -1063,7 +1071,7 @@ export function listRuns({ root, catalogue, resumeAttempt }) {
1063
1071
  });
1064
1072
  continue;
1065
1073
  }
1066
- const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue, resumeAttempt?.(flowName, runId) ?? null);
1074
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flowName, runId, catalogue, resumeAttempt?.(flowName, runId) ?? null, startingRun);
1067
1075
  const { glyph, label } = computeGlyph(ctx);
1068
1076
  // M4c amendment 1 (c): the ask waiting on the human, by the same rule
1069
1077
  // listStops uses (deriveAskOpenFields) — the least time left if several.
@@ -1204,6 +1212,69 @@ function computeTryCount(closeClass, listAll) {
1204
1212
  return list.length;
1205
1213
  }
1206
1214
 
1215
+ /** 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. */
1216
+ function lineOfStep(ctx, emits) {
1217
+ if (!ctx.flowRead.ok || typeof emits !== 'string') return null;
1218
+ const st = (ctx.flowRead.declaration.steps ?? []).find((x) => x.emits === emits);
1219
+ return st && Number.isInteger(st.fromLine) ? st.fromLine : null;
1220
+ }
1221
+
1222
+ /** The job line of the ask a waiting run is parked at: its newest `paused` audit row's step. */
1223
+ function waitingLineOf(ctx) {
1224
+ let emits = null;
1225
+ for (const r of ctx.auditRows) if (r.verdict === 'paused') emits = r.step;
1226
+ return lineOfStep(ctx, emits);
1227
+ }
1228
+
1229
+ /**
1230
+ * 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
1231
+ * through the same `runControls` the Stop door uses (`atAsk`), so "waiting" is one decision.
1232
+ */
1233
+ function jobWaitingLine(root, flowDir, flow, catalogue) {
1234
+ const ids = listRunIds(flowDir).sort((a, b) => (Number(b.replace(/\D/g, '')) || 0) - (Number(a.replace(/\D/g, '')) || 0));
1235
+ for (const id of ids) {
1236
+ const run = resolveRunDir(flowDir, id);
1237
+ if (!run.ok || !readAsk(run.runDir)) continue; // eslint-disable-line no-continue
1238
+ const ctx = loadRunContext(root, flowDir, run.runDir, flow, id, catalogue, null);
1239
+ const g = computeGlyph(ctx);
1240
+ if (runControls(ctx, g.glyph, g.label).atAsk) return waitingLineOf(ctx);
1241
+ }
1242
+ return null;
1243
+ }
1244
+
1245
+ /**
1246
+ * 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
1247
+ * 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
1248
+ * is live; `scheduled` is null when the job has no trigger; `catchUp` is a fixed sentence when this run was started late (am2 item 1).
1249
+ * @returns {{ended: {reason: string, next: string}|null, scheduled: {text: string, next: string, nextRed: boolean}|null, catchUp: string|null}}
1250
+ */
1251
+ function runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }) {
1252
+ const died = !ctx.historyRow && glyph === '[?]';
1253
+ const outcome = ctx.historyRow ? ctx.historyRow.outcome ?? null : null;
1254
+ let line = null;
1255
+ if (outcome !== null && outcome !== 'complete') {
1256
+ let emits = null;
1257
+ for (const r of ctx.auditRows) if (isBlockedVerdict(r.verdict)) emits = r.step;
1258
+ line = lineOfStep(ctx, emits);
1259
+ }
1260
+ const send = ctx.arbiter && Array.isArray(ctx.arbiter.sends) ? ctx.arbiter.sends.find((x) => x.target && typeof x.target.path === 'string') : undefined;
1261
+ const ended = endedWords({
1262
+ outcome, died, line, destination: send ? send.target.path : null, canResume: ctx.resumable === true && ctx.sameJob === true, home,
1263
+ });
1264
+ let scheduled = null;
1265
+ const t = typeof triggerRead === 'function' ? triggerRead(ctx.flowName) : null;
1266
+ if (t && t.trigger) {
1267
+ const nx = scheduledNextFor({
1268
+ trigger: t.trigger, armed: t.armed, nextSlotMs: t.nextSlotMs, lastOutcome: t.lastOutcome, waitingLine: jobWaitingLine(root, ctx.flowDir, ctx.flowName, catalogue), now: now(),
1269
+ });
1270
+ scheduled = { text: String(scheduledWords(t.trigger, home)), next: nx.text, nextRed: nx.red };
1271
+ }
1272
+ let rec = null;
1273
+ const f = readFileInside(ctx.runDir, 'trigger.json');
1274
+ if (f.ok) { try { rec = JSON.parse(f.text); } catch { rec = null; } }
1275
+ return { ended, scheduled, catchUp: catchUpWords(rec) };
1276
+ }
1277
+
1207
1278
  /**
1208
1279
  * `GET /api/runs/:flow/:runId` — the Run tab (M4a scope item 2): the step
1209
1280
  * map from `declaration.steps`, step cards -> attempts from `audit.jsonl`
@@ -1211,17 +1282,17 @@ function computeTryCount(closeClass, listAll) {
1211
1282
  * `log.json`. `null` when the flow/runId doesn't resolve to a real run
1212
1283
  * directory at all (caller renders 404); a `red` field names why a
1213
1284
  * sub-derivation couldn't fill (never invented).
1214
- * @param {{root: string, flow: string, runId: string, catalogue: any, resumeAttempt?: (flow: string, runId: string) => any}} opts
1285
+ * @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
1286
  * @returns {any|null}
1216
1287
  */
1217
1288
  export function getRunDetail({
1218
- root, flow, runId, catalogue, resumeAttempt,
1289
+ root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead, now = Date.now, home,
1219
1290
  }) {
1220
1291
  const run = resolveRunPath(root, flow, runId);
1221
1292
  if (!run.ok) return null;
1222
1293
  if (!existsSync(run.runDir)) return null;
1223
1294
 
1224
- const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue, resumeAttempt?.(flow, runId) ?? null);
1295
+ const ctx = loadRunContext(root, run.flowDir, run.runDir, flow, runId, catalogue, resumeAttempt?.(flow, runId) ?? null, startingRun);
1225
1296
  const { glyph, label } = computeGlyph(ctx);
1226
1297
 
1227
1298
  // hamr's 2026-09-27 step-card review: the Run tab's step cards reuse the
@@ -1438,6 +1509,8 @@ export function getRunDetail({
1438
1509
  signWords: SIGN_WORDS,
1439
1510
  pulse: glyphPulses({ glyph, label }),
1440
1511
  controls: runControls(ctx, glyph, label),
1512
+ // M9 piece 6: the block at the top of the run page (ENDED / NEXT, SCHEDULED / NEXT), words set by code
1513
+ summary: runSummary(ctx, glyph, { root, catalogue, triggerRead, now, home }),
1441
1514
  resume: ctx.resume,
1442
1515
  outcome: ctx.historyRow ? ctx.historyRow.outcome : null,
1443
1516
  outcomeWhy: ctx.historyRow ? null : (isRunningNow(ctx, glyph) ? RUNNING_WHY : 'no history row (parked or died before completion)'),
@@ -1656,7 +1729,10 @@ function buildJobPlan(declaration, asks, flowDir, flowHash = null) {
1656
1729
  };
1657
1730
  });
1658
1731
  const setup = readSetup(flowDir);
1659
- const signRow = setup.present ? setup.rows.find((r) => r.kind === 'sign') : undefined;
1732
+ // 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)
1733
+ const signRow = setup.present
1734
+ ? (setup.rows.findLast((r) => (r.kind === 'sign' || r.kind === 'trigger-resign') && flowHash !== null && r.flowHash === flowHash) ?? setup.rows.find((r) => r.kind === 'sign'))
1735
+ : undefined;
1660
1736
  const ofThisJob = !!signRow && (typeof signRow.flowHash !== 'string' || flowHash === null || signRow.flowHash === flowHash);
1661
1737
  const nc = ofThisJob ? signRow?.notChecked : undefined;
1662
1738
  const recorded = !!nc && Array.isArray(nc.items);
@@ -283,6 +283,20 @@
283
283
  .counters{display:block;padding:9px 12px;border:none;border-bottom:2px solid var(--border-strong);background:var(--panel2);color:var(--text-dim);margin:-12px -12px 14px;font-size:12px;font-weight:700;white-space:normal;overflow-wrap:break-word;}
284
284
  .counters b,.counters span{color:var(--accent);}
285
285
 
286
+ /* borrowed-from: bareloop src/panel/index.html@f845ee7 (the ENDED block, P5); amber added for stopped/expired, a SCHEDULED twin */
287
+ .ended-block{position:relative;border:1px solid var(--border-strong);padding:12px;margin-bottom:12px;background:var(--panel2);font-size:13px;}
288
+ .ended-block.magenta{border-color:var(--magenta);}
289
+ .ended-block.red{border-color:var(--red);}
290
+ .ended-text.is-red{color:var(--red);}
291
+ .ended-block.green{border-color:var(--green);}
292
+ .ended-block.amber{border-color:var(--amber);}
293
+ .ended-row{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap;margin-bottom:6px;}
294
+ .ended-row:last-child{margin-bottom:0;}
295
+ .ended-label{color:var(--text-faint);font-size:11px;letter-spacing:0.08em;min-width:84px;}
296
+ .ended-text{flex:1 1 220px;min-width:0;overflow-wrap:anywhere;}
297
+ .when-sub{display:flex;gap:8px;flex-wrap:wrap;margin-top:6px;}
298
+ .when-sub > *{flex:1 1 120px;min-width:0;}
299
+ .when-sub[hidden]{display:none;}
286
300
  .summary-box{position:relative;border:1px solid var(--border-strong);padding:16px 12px 12px;margin-top:16px;background:var(--panel2);font-size:12px;}
287
301
  .summary-box.red{border-color:var(--red);}
288
302
  .summary-box.amber{border-color:var(--amber);}
@@ -961,6 +975,30 @@
961
975
  <div id="jf-run-inputs" data-testid="jf-run-inputs"></div>
962
976
  <div class="jf-err" id="jf-err-run-inputs" data-testid="jf-err-run-inputs"></div>
963
977
  </div>
978
+ <div class="field" id="jf-when-field" data-testid="jf-when-field">
979
+ <label for="jf-when">When</label>
980
+ <select id="jf-when" data-testid="jf-when" aria-label="When this job runs">
981
+ <option value="hand">By hand</option>
982
+ <option value="daily">Every day at HH:MM</option>
983
+ <option value="weekdays">Weekdays at HH:MM</option>
984
+ <option value="weekly">Every &lt;day&gt; at HH:MM</option>
985
+ <option value="file-updated">When &lt;file&gt; is updated</option>
986
+ <option value="new-file">When a new file arrives in &lt;folder&gt;</option>
987
+ </select>
988
+ <div class="when-sub" id="jf-when-clock" hidden>
989
+ <select id="jf-when-day" data-testid="jf-when-day" aria-label="Day of the week">
990
+ <option value="mon">Monday</option><option value="tue">Tuesday</option><option value="wed">Wednesday</option><option value="thu">Thursday</option>
991
+ <option value="fri">Friday</option><option value="sat">Saturday</option><option value="sun">Sunday</option>
992
+ </select>
993
+ <input id="jf-when-time" type="time" value="09:00" data-testid="jf-when-time" aria-label="Time, HH:MM">
994
+ </div>
995
+ <div class="when-sub" id="jf-when-filebox" hidden>
996
+ <select id="jf-when-role" data-testid="jf-when-role" aria-label="Which of the job's inputs"></select>
997
+ <input id="jf-when-path" type="text" autocomplete="off" spellcheck="false" data-testid="jf-when-path" aria-label="File or folder">
998
+ </div>
999
+ <div class="hint" id="jf-when-now" data-testid="jf-when-now"></div>
1000
+ <div class="jf-err" id="jf-err-when" data-testid="jf-err-when"></div>
1001
+ </div>
964
1002
  <div class="cap-row">
965
1003
  <div class="cap-field">
966
1004
  <label for="jf-run-cap">Cap $</label>
@@ -1091,6 +1129,11 @@
1091
1129
  <section id="panel-run" class="tabpanel active" role="tabpanel" aria-labelledby="tab-run">
1092
1130
  <div id="run-empty" class="hint" style="font-size:13px;padding:24px 0;">select a run from Workflows or History</div>
1093
1131
  <div id="run-content" hidden>
1132
+ <div id="summary-blocks" data-testid="summary-blocks">
1133
+ <div id="ended-block" class="ended-block" data-testid="ended-block" hidden></div>
1134
+ <div id="sched-block" class="ended-block" data-testid="sched-block" hidden></div>
1135
+ <div class="hint" id="catchup-note" data-testid="catchup-note" hidden></div>
1136
+ </div>
1094
1137
  <div class="run-actions" id="run-actions" data-testid="run-actions" hidden></div>
1095
1138
  <div class="counters" id="run-counters" data-testid="live-counters"></div>
1096
1139
  <div class="summary-box" id="run-summary" data-testid="run-summary"></div>
@@ -2177,6 +2220,32 @@
2177
2220
  // (ruling A, 2026-09-26: "no per-round parts") — built off getRunDetail's
2178
2221
  // `steps[]` (declaration.steps joined with audit.jsonl attempts), never a
2179
2222
  // second client-side re-derivation of the step list. ----
2223
+ // ---- M9 piece 6: the summary block, first thing on the run page. The sentences are CODE-OWNED on the server (`summary` of the run detail,
2224
+ // src/summary-words.js); this only paints them. ENDED / NEXT while a finished run; SCHEDULED / NEXT for a job with a trigger.
2225
+ // borrowed-from: bareloop src/panel/index.html@f845ee7 (renderEnded)
2226
+ function summaryRows(a, b){
2227
+ return '<div class="ended-row"><span class="ended-label">' + a[0] + '</span><span class="ended-text" data-testid="' + a[2] + '">' + escapeXml(a[1]) + '</span></div>' +
2228
+ '<div class="ended-row"><span class="ended-label">' + b[0] + '</span><span class="ended-text" data-testid="' + b[2] + '">' + escapeXml(b[1]) + '</span></div>';
2229
+ }
2230
+ function renderSummary(detail){
2231
+ var sm = detail.summary || {};
2232
+ var ended = document.getElementById("ended-block");
2233
+ var sched = document.getElementById("sched-block");
2234
+ var note = document.getElementById("catchup-note");
2235
+ if(sm.ended){
2236
+ ended.hidden = false;
2237
+ ended.className = "ended-block " + (detail.glyph === "[✓]" ? "green" : (detail.glyph === "[?]" ? "magenta" : ((detail.glyph === "[■]" || detail.glyph === "[!]") ? "amber" : "red")));
2238
+ ended.innerHTML = summaryRows(["ENDED", sm.ended.reason, "ended-reason"], ["NEXT", sm.ended.next, "ended-next"]);
2239
+ } else { ended.hidden = true; ended.innerHTML = ""; }
2240
+ if(sm.scheduled){
2241
+ sched.hidden = false;
2242
+ sched.className = "ended-block" + (sm.scheduled.nextRed === true ? " red" : "");
2243
+ sched.innerHTML = summaryRows(["SCHEDULED", sm.scheduled.text, "sched-text"], ["NEXT", sm.scheduled.next, "sched-next"]);
2244
+ if(sm.scheduled.nextRed === true) sched.querySelector('[data-testid="sched-next"]').classList.add("is-red");
2245
+ } else { sched.hidden = true; sched.innerHTML = ""; }
2246
+ note.hidden = !sm.catchUp;
2247
+ note.textContent = sm.catchUp || "";
2248
+ }
2180
2249
  function renderRun(detail){
2181
2250
  var name = document.getElementById("active-wf-name");
2182
2251
  var dot = document.getElementById("active-wf-dot");
@@ -2196,6 +2265,7 @@
2196
2265
 
2197
2266
  document.getElementById("run-empty").hidden = true;
2198
2267
  document.getElementById("run-content").hidden = false;
2268
+ renderSummary(detail);
2199
2269
 
2200
2270
  // "took Xs" for a finished run, straight off the history row's own
2201
2271
  // wallMs (never derived/guessed) — a died/parked run or one whose
@@ -2287,6 +2357,8 @@
2287
2357
  el.innerHTML = "";
2288
2358
  // amendment 7 item 6: Run again sits first, with Stop and Resume — every run control in this one row
2289
2359
  el.appendChild(makeButton("Run again", "run-again", function(){ if(window.fwdloopRunAgain) window.fwdloopRunAgain(detail); }));
2360
+ // M9 am5 item 3: a scheduled job's Run tab offers the schedule's own door, next to Run again: the same route, the Run card showing When
2361
+ if(detail.summary && detail.summary.scheduled) el.appendChild(makeButton("Cancel / modify schedule", "run-cancel-schedule", function(){ if(window.fwdloopRunAgain) window.fwdloopRunAgain(detail); }));
2290
2362
  if(stopSay && stopSay.key !== detail.flow + "/" + detail.runId) stopSay = null;
2291
2363
  if(c.canStop){
2292
2364
  var stopBtn = makeButton(c.stopRequested ? "stopping after this step\u2026" : "Stop", "run-stop", function(){
@@ -4010,6 +4082,12 @@
4010
4082
  var spends = (cap !== undefined && cap !== null && cap !== "") ? " — spends up to $" + cap : "";
4011
4083
  var blocked = !st.startOk || !!st.busy;
4012
4084
  if(st.mode === "run"){
4085
+ // M9 am5: When changed from the signed value = the one button is Sign schedule (or Cancel schedule when the choice is By hand), two clicks, $0,
4086
+ // starts nothing; after click 1 it reads "Confirm: <words>". It never reaches the run routes.
4087
+ if(st.whenChanged){
4088
+ var whenText = st.whenConfirm ? "Confirm: " + st.whenConfirm : (st.whenCancel ? "Cancel schedule" : "Sign schedule");
4089
+ return {text: whenText, action: st.whenSigning ? "when-sign" : "when-sign-prepare", disabled: !!st.whenBusy || !!st.busy || !!st.whenLocked};
4090
+ }
4013
4091
  // amendment 5 item 3: inputs alone = Run (one click); a Destination, Cap $ or ask wait different from the flow's = Sign & run (two clicks, bound to a hash)
4014
4092
  if(st.runDiffers){
4015
4093
  if(st.runSignClicked){
@@ -4018,7 +4096,7 @@
4018
4096
  }
4019
4097
  return {text: "Sign & run", action: "run-sign-prepare", disabled: blocked};
4020
4098
  }
4021
- return {text: "Run" + spends, action: "run", disabled: blocked};
4099
+ return {text: "Run now" + spends, action: "run", disabled: blocked || !!st.whenLocked};
4022
4100
  }
4023
4101
  if(st.mode === "resume"){
4024
4102
  if(st.runSignClicked){
@@ -4448,6 +4526,7 @@
4448
4526
  }
4449
4527
  function syncCardLock(){
4450
4528
  var on = cardLocked();
4529
+ whenSyncButton();
4451
4530
  card.querySelectorAll("input[type=text], textarea").forEach(function(el){ el.readOnly = on; el.classList.toggle("locked", on); });
4452
4531
  if(editOf !== null){ byId("jf-name").readOnly = true; byId("jf-name").classList.add("locked"); } // M6: an edit keeps its job's name
4453
4532
  runFlowSel.disabled = on;
@@ -4510,7 +4589,8 @@
4510
4589
  setMode("new");
4511
4590
  setVal("jf-name", f.flow); setVal("jf-job", c.job); setVal("jf-cap-money", c.capUsd);
4512
4591
  setVal("jf-dest-folder", c.destination); setVal("jf-inputs", c.inputs); setVal("jf-ask-wait", c.askWait || "1h");
4513
- editBannerEl.textContent = "Editing \u201c" + f.flow + "\u201d. Draft it, read the new plan, then sign: signing replaces this job. Clear leaves it exactly as it was.";
4592
+ // M9 am1: a job with a trigger is told, before it signs, that the edit clears the trigger back to By hand (the sentence is the server's)
4593
+ editBannerEl.textContent = "Editing \u201c" + f.flow + "\u201d. Draft it, read the new plan, then sign: signing replaces this job. Clear leaves it exactly as it was." + (f.trigger && f.trigger.editNote ? " " + f.trigger.editNote : "");
4514
4594
  editBannerEl.hidden = false;
4515
4595
  chatActionOk();
4516
4596
  refreshCapNote(); fitCardBoxes(); refreshStartEnabled();
@@ -4553,7 +4633,101 @@
4553
4633
  clearFieldErrors();
4554
4634
  refreshCapNote();
4555
4635
  syncEditBtn();
4636
+ paintWhen();
4637
+ }
4638
+ // ---- M9 piece 5: When [By hand v] on the Run card (ladder M9 item 1, item 2). One dropdown, no cron text. Changing it asks the server what
4639
+ // would be signed (click 1, signs nothing, returns a hash), click 2 signs it with that hash: the Run door's two clicks. $0, no drafter.
4640
+ // A job with no good run gets the dropdown refused with the SERVER's sentence (`trigger.refusal`); the page writes no sentence of its own.
4641
+ var whenHash = null;
4642
+ var whenBusy = false;
4643
+ var whenConfirmText = ""; // the words the button shows after click 1 ("every day at 13:15", "cancel schedule"); read only while whenHash is set
4644
+ var whenLocked = false; // ~1.5 s after a successful sign the main button is disabled, so a fast extra click cannot start a run
4645
+ var whenReady = false; // the lock sync can run before this block has
4646
+ function whenCanon(t){ return t === null ? "null" : JSON.stringify(Object.keys(t).sort().map(function(k){ return [k, t[k]]; })); }
4647
+ function whenTriggerFromBoxes(){
4648
+ var kind = byId("jf-when").value;
4649
+ if(kind === "hand") return null;
4650
+ if(kind === "daily" || kind === "weekdays" || kind === "weekly"){
4651
+ var m = /^(\d{2}):(\d{2})$/.exec(byId("jf-when-time").value);
4652
+ var o = m ? {kind: kind, hour: Number(m[1]), minute: Number(m[2])} : {kind: kind}; // an empty time goes to the server, which says so
4653
+ if(kind === "weekly") o.day = byId("jf-when-day").value;
4654
+ return o;
4655
+ }
4656
+ var q = {kind: kind, role: byId("jf-when-role").value};
4657
+ q[kind === "new-file" ? "folder" : "path"] = byId("jf-when-path").value.trim();
4658
+ return q;
4659
+ }
4660
+ function whenShowSubs(){
4661
+ var kind = byId("jf-when").value;
4662
+ byId("jf-when-clock").hidden = !(kind === "daily" || kind === "weekdays" || kind === "weekly");
4663
+ byId("jf-when-day").hidden = kind !== "weekly";
4664
+ byId("jf-when-filebox").hidden = !(kind === "file-updated" || kind === "new-file");
4665
+ byId("jf-when-path").placeholder = kind === "new-file" ? "/full/path/to/folder" : "/full/path/to/file";
4666
+ }
4667
+ // M9 am4: is When changed from the signed value? The ONE reader; the main button turns into Sign schedule while it is.
4668
+ function whenChanged(){
4669
+ if(!whenReady) return false;
4670
+ var f = selectedFlow();
4671
+ var c = f && f.trigger;
4672
+ return !!c && !c.refusal && whenCanon(whenTriggerFromBoxes()) !== whenCanon(c.trigger);
4673
+ }
4674
+ function whenSyncButton(){
4675
+ if(!whenReady) return;
4676
+ renderMain();
4677
+ }
4678
+ function paintWhen(){
4679
+ var f = selectedFlow();
4680
+ var c = f ? f.trigger : null;
4681
+ var sel = byId("jf-when");
4682
+ whenHash = null; whenBusy = false;
4683
+ byId("jf-err-when").textContent = "";
4684
+ var roleSel = byId("jf-when-role");
4685
+ roleSel.innerHTML = "";
4686
+ ((f && f.roles) || []).forEach(function(r){ var o = document.createElement("option"); o.value = r; o.textContent = r; roleSel.appendChild(o); });
4687
+ var t = c ? c.trigger : null;
4688
+ sel.querySelector('option[value="hand"]').textContent = t ? "Cancel schedule" : "By hand"; // M9 am5: on a scheduled job, By hand reads Cancel schedule
4689
+ sel.value = t ? t.kind : "hand";
4690
+ if(t && t.hour !== undefined){ byId("jf-when-time").value = ("0" + t.hour).slice(-2) + ":" + ("0" + t.minute).slice(-2); }
4691
+ if(t && t.day) byId("jf-when-day").value = t.day;
4692
+ if(t && t.role) roleSel.value = t.role;
4693
+ byId("jf-when-path").value = t ? (t.path || t.folder || "") : "";
4694
+ var refused = !f || !c || !!c.refusal;
4695
+ sel.disabled = refused;
4696
+ byId("jf-when-day").disabled = byId("jf-when-time").disabled = roleSel.disabled = byId("jf-when-path").disabled = refused;
4697
+ byId("jf-when-now").textContent = !c ? "" : (c.refusal ? c.refusal : (c.words ? "Now: " + c.words : ""));
4698
+ whenShowSubs(); whenSyncButton();
4699
+ }
4700
+ function whenEdited(){ whenHash = null; byId("jf-err-when").textContent = ""; whenShowSubs(); whenSyncButton(); }
4701
+ ["jf-when", "jf-when-day", "jf-when-time", "jf-when-role"].forEach(function(id){ document.getElementById(id).addEventListener("change", whenEdited); });
4702
+ document.getElementById("jf-when-path").addEventListener("input", whenEdited);
4703
+ function doWhenSign(){
4704
+ var f = selectedFlow();
4705
+ if(!f || whenBusy || cardLocked()) return;
4706
+ var body = {flow: f.flow, trigger: whenTriggerFromBoxes()};
4707
+ var second = whenHash !== null;
4708
+ if(second) body.hash = whenHash;
4709
+ whenBusy = true; whenSyncButton();
4710
+ authorPost(second ? "/api/author/trigger" : "/api/author/trigger-prepare", body).then(function(r){
4711
+ whenBusy = false;
4712
+ if(!(r.status >= 200 && r.status < 300 && r.body && r.body.ok === true)){
4713
+ whenHash = null; byId("jf-err-when").textContent = refusalText(r); whenSyncButton(); return;
4714
+ }
4715
+ var words = typeof r.body.words === "string" ? r.body.words : "";
4716
+ if(!second){
4717
+ whenHash = r.body.hash;
4718
+ whenConfirmText = words ? words.charAt(0).toLowerCase() + words.slice(1) : "cancel schedule";
4719
+ byId("jf-err-when").textContent = ""; whenSyncButton(); return;
4720
+ }
4721
+ // M9 am5: after click 2 the card clears (like Clear) and nothing runs; the signed schedule is read back by the flows list
4722
+ whenHash = null;
4723
+ whenLocked = true; setTimeout(function(){ whenLocked = false; renderMain(); }, 1500);
4724
+ var say = typeof r.body.say === "string" ? r.body.say : "";
4725
+ resetCard();
4726
+ setMode("new"); // the default empty card a fresh page load shows, not Run a signed flow with the pick emptied
4727
+ if(say) chatActionFailed(say);
4728
+ }).catch(function(){ whenBusy = false; whenHash = null; byId("jf-err-when").textContent = NETWORK_SAY; whenSyncButton(); });
4556
4729
  }
4730
+ whenReady = true;
4557
4731
  // borrowed-from: bareloop src/panel/index.html@b5e37b8 — the Reuse workflow picker: ONE function shows the search box + list before a pick and the
4558
4732
  // picked box after; a row is the name (the typed part marked) over the flow's track record line.
4559
4733
  function rwMark(name, q){
@@ -4785,6 +4959,12 @@
4785
4959
  st.runDiffers = runDiffers();
4786
4960
  st.runSignClicked = !!runSignInfo;
4787
4961
  st.hash = runSignInfo ? runSignInfo.hash : "";
4962
+ st.whenChanged = whenChanged();
4963
+ st.whenSigning = whenHash !== null;
4964
+ st.whenConfirm = whenHash !== null ? whenConfirmText : "";
4965
+ st.whenCancel = whenTriggerFromBoxes() === null;
4966
+ st.whenBusy = whenBusy;
4967
+ st.whenLocked = whenLocked;
4788
4968
  } else if(mode === "resume"){
4789
4969
  st.capUsd = resumeCapEl.value.trim();
4790
4970
  st.runSignClicked = !!resumeSignInfo;
@@ -5207,6 +5387,7 @@
5207
5387
  mainBtn.addEventListener("click", function(){
5208
5388
  if(mainBtn.disabled) return;
5209
5389
  if(mainAction === "draft") doDraft(mainStartOver ? sessionId : null);
5390
+ else if(mainAction === "when-sign-prepare" || mainAction === "when-sign") doWhenSign();
5210
5391
  else if(mainAction === "run") doRun();
5211
5392
  else if(mainAction === "run-sign-prepare" || mainAction === "run-sign") doRunSign();
5212
5393
  else if(mainAction === "resume-sign-prepare" || mainAction === "resume-sign") doResumeSign();
@@ -0,0 +1,125 @@
1
+ // M9 piece 4 (docs/wiki/the-module-ladder.md, "M9" item 3): the panel's scheduler. The panel's server runs the clock and the file watch; with
2
+ // the panel off, nothing fires, and the times missed run ONCE when it comes back (`due` collapses them, marked catch-up).
3
+ //
4
+ // ONE `tick()` does everything and is synchronous; the tests call it by hand with an injected clock. The real timer only calls it.
5
+ // tick period 500 ms: the file watch needs a file's size and mtime to hold for STABLE_POLLS (2) polls before it is taken, so a drop is
6
+ // seen about 1.5 s after it stops changing; the proof of piece 2 polled at 250 ms and found nothing that needed faster. The clock fires
7
+ // to the minute and would do with a tick a minute apart, but one timer is one fewer moving part; a tick that finds no trigger set reads
8
+ // each job's signed files (small, hash-checked) and does no more.
9
+ // No leaked timer: `start` is idempotent, the timer is unref'd, and the server's close calls `stop`.
10
+ //
11
+ // What a tick does for one job with a signed trigger (the trigger itself is read from the job, never from here):
12
+ // 1. arm it if it is not armed yet (a crash between the sign and the arm);
13
+ // 2. clock kinds: `due` against the clock ledger; a due slot is written to the ledger (`recordFire`) BEFORE the fire;
14
+ // 3. file kinds: `poll` of this job's file trigger; each file taken is already in the seen ledger (`ran`) BEFORE the fire.
15
+ // A failure on one job (a folder that went away) is written once to `triggers.jsonl` as `refused` and never stops the other jobs.
16
+ import { join } from 'node:path';
17
+
18
+ import { due, readRows, recordFire } from '../trigger-clock.js';
19
+ import {
20
+ createFileTrigger, queueOf, readSeen, recheck, recordArrived, recordDropped, recordRan,
21
+ } from '../trigger-files.js';
22
+ import { readOutcomes, triggerLedgerDir } from './authortrigger.js';
23
+
24
+ /**
25
+ * @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number }} opts
26
+ * `intervalMs` 0 = no timer (a test drives `tick`).
27
+ */
28
+ export function createScheduler(opts) {
29
+ const { door, now = Date.now, intervalMs = 500 } = opts;
30
+ /** @type {Map<string, ReturnType<typeof createFileTrigger>>} */
31
+ const watchers = new Map();
32
+ /** @type {Set<string>} refusals already written, so a folder that stays gone is told once, not every tick */
33
+ const told = new Set();
34
+ /** @type {ReturnType<typeof setInterval>|null} */
35
+ let timer = null;
36
+
37
+ /**
38
+ * M9 am3: the queue of a file trigger (arrived minus ran, oldest first). Busy: every queued file is told ONCE (`busy`) and waits. Free: the
39
+ * head is looked at again at use time (deleted / changed -> one row, dropped, the next head), then goes through the fire checks; `ran` is
40
+ * written right before the start. A head that is not started (month, keys, input) stays queued, told once, and blocks the ones behind it.
41
+ * @param {any} job @param {string} ledger @param {number} nowMs
42
+ */
43
+ function runQueue(job, ledger, nowMs) {
44
+ let queue = queueOf(readSeen(ledger));
45
+ if (queue.length === 0) return;
46
+ const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string').map((r) => `${r.sha}|${r.outcome}`));
47
+ const cause = (/** @type {any} */ q) => ({ kind: /** @type {'file'} */ ('file'), path: q.path, sha: q.sha });
48
+ const told = (/** @type {any} */ q) => (/** @type {string} */ outcome) => { const k = `${q.sha}|${outcome}`; const had = spoken.has(k); spoken.add(k); return had; };
49
+ if (door.busy(job)) {
50
+ for (const q of queue) door.fire(job, cause(q), { told: told(q) });
51
+ return;
52
+ }
53
+ while (queue.length > 0) {
54
+ const q = queue[0];
55
+ const seen = recheck(q);
56
+ if (seen.state !== 'ok') {
57
+ const why = seen.state === 'deleted' ? 'deleted' : 'changed';
58
+ recordDropped(ledger, q, why, nowMs);
59
+ door.note(job, {
60
+ outcome: why, file: q.path, sha: q.sha, say: seen.state === 'deleted' ? `${q.name} did not run: ${seen.say}.` : `${q.name} did not run: it changed before its turn; the new version arrives again.`,
61
+ });
62
+ queue = queue.slice(1);
63
+ continue;
64
+ }
65
+ door.fire(job, cause({ ...q, path: seen.path }), { told: told(q), beforeStart: () => recordRan(ledger, seen, nowMs) });
66
+ return;
67
+ }
68
+ }
69
+
70
+ function tick() {
71
+ const nowMs = now();
72
+ const live = new Set();
73
+ for (const job of door.scan()) {
74
+ const hash = job.read.signature.flow;
75
+ const key = `${job.flow}|${hash}`;
76
+ live.add(key);
77
+ try {
78
+ door.ensureArmed(job);
79
+ const dir = triggerLedgerDir(job.flowDir, hash);
80
+ const { trigger } = job;
81
+ if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
82
+ let w = watchers.get(key);
83
+ if (!w) {
84
+ w = createFileTrigger({
85
+ mode: trigger.kind === 'new-file' ? 'new' : 'updated', target: trigger.kind === 'new-file' ? trigger.folder : trigger.path, ledger: join(dir, 'seen.jsonl'),
86
+ });
87
+ watchers.set(key, w);
88
+ }
89
+ const ledger = join(dir, 'seen.jsonl');
90
+ const { arrived, refused } = w.poll();
91
+ for (const r of refused) door.refuse(job, `${r.path}: ${r.why}`);
92
+ for (const f of arrived) recordArrived(ledger, f, nowMs); // THE writer of the file ledger: arrival time is this clock, never the file's mtime
93
+ runQueue(job, ledger, nowMs);
94
+ } else {
95
+ const clock = join(dir, 'clock.jsonl');
96
+ const d = due(trigger, readRows(clock), nowMs);
97
+ if (d.fire) {
98
+ recordFire(clock, d, nowMs); // BEFORE the fire: a crash loses a run, never doubles one
99
+ door.fire(job, {
100
+ kind: 'clock', slot: /** @type {number} */ (d.slot), catchUp: d.catchUp, missed: d.missed,
101
+ });
102
+ }
103
+ }
104
+ } catch (e) {
105
+ const why = /** @type {Error} */ (e).message;
106
+ if (!told.has(`${key}|${why}`)) { told.add(`${key}|${why}`); door.refuse(job, why); }
107
+ }
108
+ }
109
+ for (const k of [...watchers.keys()]) if (!live.has(k)) watchers.delete(k);
110
+ }
111
+
112
+ return {
113
+ tick,
114
+ /** Start the real timer (idempotent). */
115
+ start() {
116
+ if (intervalMs <= 0 || timer !== null) return;
117
+ timer = setInterval(() => { try { tick(); } catch { /* one bad tick never stops the next */ } }, intervalMs);
118
+ timer.unref();
119
+ },
120
+ /** Stop it (idempotent). The server's close calls this. */
121
+ stop() {
122
+ if (timer !== null) { clearInterval(timer); timer = null; }
123
+ },
124
+ };
125
+ }