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.
@@ -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
+ }
@@ -59,9 +59,10 @@ import { readHistory, endRow } from '../books.js';
59
59
  import { resolveRunDir } from '../flow.js';
60
60
  import { readAsk, requestStop, stopParkedRun } from '../runner.js';
61
61
  import {
62
- listRuns, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
62
+ listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
63
63
  } from './data.js';
64
64
  import { createResumer } from './resume.js';
65
+ import { createScheduler } from './scheduler.js';
65
66
  import { createAuthor } from './author.js';
66
67
  import { keysForDoor } from '../keysfile.js';
67
68
  import { configDoorHome } from '../config.js';
@@ -321,7 +322,7 @@ function resumeRoute(res, body, root, resumer) {
321
322
  }
322
323
 
323
324
  /**
324
- * `POST /api/author/{draft,run,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/answer,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
325
+ * `POST /api/author/{draft,run,trigger-prepare,trigger,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/answer,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
325
326
  * Anything else under `/api/author/` is a 404 by name.
326
327
  * @param {any} res @param {string} url @param {any} body @param {ReturnType<typeof createAuthor>} author
327
328
  */
@@ -330,6 +331,8 @@ function authorPost(res, url, body, author) {
330
331
  if (url === '/api/author/draft') { send(author.start(body)); return; }
331
332
  if (url === '/api/author/run') { send(author.run(body)); return; }
332
333
  if (url === '/api/author/run-prepare') { send(author.runPrepare(body)); return; }
334
+ if (url === '/api/author/trigger-prepare') { send(author.trigger.prepare(body)); return; }
335
+ if (url === '/api/author/trigger') { send(author.trigger.set(body)); return; }
333
336
  if (url === '/api/author/resume-prepare') { send(author.resumePrepare(body)); return; }
334
337
  if (url === '/api/author/resume') { send(author.resume(body)); return; }
335
338
  const sp = /^\/api\/author\/([^/]+)\/sign-prepare$/.exec(url);
@@ -353,7 +356,7 @@ function authorPost(res, url, body, author) {
353
356
  * real listening socket where that is simpler.
354
357
  * @param {import('node:http').IncomingMessage} req
355
358
  * @param {import('node:http').ServerResponse} res
356
- * @param {{ root: string, port: number, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
359
+ * @param {{ root: string, port: number, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor>, now?: () => number }} opts
357
360
  */
358
361
  export function handleRequest(req, res, opts) {
359
362
  const method = req.method ?? 'GET';
@@ -505,9 +508,18 @@ export function handleRequest(req, res, opts) {
505
508
  }
506
509
  const catalogue = loaded.primitives;
507
510
  const resumeAttempt = (f, r) => opts.resumer.get(f, r);
511
+ const startingRun = (f, r) => opts.author?.startingRun?.(f, r) === true;
508
512
 
509
513
  if (pathname === '/api/runs') {
510
- send(200, { rows: listRuns({ root: opts.root, catalogue, resumeAttempt }) });
514
+ // M11: the page is given every state; it works none out. `jobs` is the order and the quiet split, `scheduled` the Scheduled cards, `limits` the two named numbers.
515
+ const now = opts.now ?? Date.now;
516
+ const rows = listRuns({ root: opts.root, catalogue, resumeAttempt, startingRun, now });
517
+ send(200, {
518
+ rows,
519
+ jobs: summarizeJobs(rows, now()),
520
+ scheduled: listScheduled({ root: opts.root, triggerRead: (f) => opts.author?.trigger?.read(f) ?? null, now, rows }),
521
+ limits: RUNS_LIST_LIMITS,
522
+ });
511
523
  return;
512
524
  }
513
525
 
@@ -559,7 +571,7 @@ export function handleRequest(req, res, opts) {
559
571
  return;
560
572
  }
561
573
  const result = getRunDetail({
562
- root: opts.root, flow, runId, catalogue, resumeAttempt,
574
+ root: opts.root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead: (f) => opts.author?.trigger?.read(f) ?? null, now: opts.now,
563
575
  });
564
576
  if (!result) { sendText(res, 404, 'no such run'); return; }
565
577
  send(200, result);
@@ -575,9 +587,9 @@ export function handleRequest(req, res, opts) {
575
587
  * header). Resolves once actually listening; rejects on a bind error
576
588
  * (including `EADDRINUSE`) with a `.port` field on the error for the
577
589
  * caller's message.
578
- * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
590
+ * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string, now?: () => number }, scheduler?: { intervalMs?: number } }} opts
579
591
  * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
580
- * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
592
+ * @returns {Promise<{ server: import('node:http').Server, port: number, tick: () => void, close: () => Promise<void> }>}
581
593
  */
582
594
  export function createPanelServer(opts) {
583
595
  if (typeof opts?.root !== 'string' || opts.root.length === 0) {
@@ -594,6 +606,9 @@ export function createPanelServer(opts) {
594
606
  const author = createAuthor({
595
607
  root, home: opts.settings?.home ?? door.home, skipMonthly: opts.settings?.home === undefined && door.skip, loadEnv: () => keysForDoor({ env: opts.author?.env }), ...opts.author,
596
608
  });
609
+ // M9: the scheduler runs the clock and the file watch while this server is up (item 3). The clock is the author's `now` (tests inject one);
610
+ // `scheduler.intervalMs` 0 = no timer, a test calls `tick`. Stopped on close.
611
+ const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs });
597
612
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
598
613
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
599
614
  const settings = createSettings({
@@ -609,7 +624,7 @@ export function createPanelServer(opts) {
609
624
  const server = createServer((req, res) => {
610
625
  try {
611
626
  handleRequest(req, res, {
612
- root, port: boundPort, resumer, settings, author, packagePath: opts.packagePath,
627
+ root, port: boundPort, resumer, settings, author, packagePath: opts.packagePath, now: opts.author?.now,
613
628
  });
614
629
  } catch (e) {
615
630
  sendText(res, 500, 'internal error');
@@ -623,10 +638,12 @@ export function createPanelServer(opts) {
623
638
  server.listen(requestedPort, '127.0.0.1', () => {
624
639
  const addr = server.address();
625
640
  boundPort = typeof addr === 'object' && addr !== null ? addr.port : requestedPort;
641
+ scheduler.start();
626
642
  resolve({
627
643
  server,
628
644
  port: boundPort,
629
- close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
645
+ tick: scheduler.tick,
646
+ close: () => new Promise((res2) => { scheduler.stop(); server.close(() => res2(undefined)); }),
630
647
  });
631
648
  });
632
649
  });
package/src/runvalues.js CHANGED
@@ -18,6 +18,7 @@ import { unlinkSync, writeFileSync } from 'node:fs';
18
18
  import { join } from 'node:path';
19
19
 
20
20
  import { readFileInside, readdirInside } from './flow.js';
21
+ import { TRIGGER_RECORD_FILE } from './trigger-line.js';
21
22
 
22
23
  export const VALUES_FILE_RE = /^signed-values(?:-r(\d+))?\.json$/;
23
24
 
@@ -168,11 +169,12 @@ export function applyRunValues(arbiter, flow, flowSignatureHash, picked) {
168
169
 
169
170
  /**
170
171
  * A start that refused before the run began (monthly limit, empty key ...) leaves a run folder holding nothing but its signed values
171
- * file: remove that one file so the folder can be removed too and the run name is not burned. Never touches a folder with anything else.
172
+ * file and/or its trigger record: remove those so the folder can be removed too and the run name is not burned. Never touches a folder with anything else.
172
173
  * @param {string} runDir @returns {boolean} true when the file was removed
173
174
  */
174
175
  export function dropUnstartedValues(runDir) {
175
176
  const names = readdirInside(runDir, '.');
176
- if (names.length !== 1 || names[0] !== valuesFileName(0)) return false;
177
- try { unlinkSync(join(runDir, names[0])); return true; } catch { return false; }
177
+ const own = [valuesFileName(0), TRIGGER_RECORD_FILE]; // M9: a triggered start also writes its reason file before the spawn
178
+ if (names.length === 0 || names.some((n) => !own.includes(n))) return false;
179
+ try { for (const n of names) unlinkSync(join(runDir, n)); return true; } catch { return false; }
178
180
  }
package/src/setup.js CHANGED
@@ -112,6 +112,27 @@ export function writeSetup({ flowDir, secrets = [], ...rest }) {
112
112
  }
113
113
  }
114
114
 
115
+ /**
116
+ * M9 item 2: a trigger-only re-sign signs the same plan under a new flow hash. The old `setup.jsonl` bytes are written back untouched (append-only)
117
+ * and ONE row is added: kind `trigger-resign`, the record of the signing it continues (its plan hash and "Not checked" list, copied) under the new
118
+ * `flowHash`, naming the old one in `resignOf`. A reader that wants this job's record looks for the row whose `flowHash` is the job's. Never throws.
119
+ * @param {{ flowDir: string, oldText: string, oldFlowHash: string, newFlowHash: string, at: string }} a
120
+ * @returns {{ ok: true } | { ok: false, red: string }}
121
+ */
122
+ export function carrySetup({ flowDir, oldText, oldFlowHash, newFlowHash, at }) {
123
+ try {
124
+ const rows = oldText.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
125
+ const signs = rows.filter((r) => r.kind === 'sign' || r.kind === 'trigger-resign');
126
+ const from = signs.findLast((r) => r.flowHash === oldFlowHash) ?? signs.at(-1);
127
+ const keep = oldText.endsWith('\n') ? oldText : `${oldText}\n`;
128
+ const extra = from ? `${JSON.stringify({ ...from, kind: 'trigger-resign', at, flowHash: newFlowHash, resignOf: oldFlowHash })}\n` : '';
129
+ writeFileSync(join(flowDir, SETUP_FILE), keep + extra, { flag: 'wx', mode: 0o600 });
130
+ return { ok: true };
131
+ } catch (err) {
132
+ return { ok: false, red: `setup: could not carry ${SETUP_FILE} over (${err.code ?? err.message})` };
133
+ }
134
+ }
135
+
115
136
  /**
116
137
  * The flow's setup rows, through the one safe gateway. `present:false` = a flow signed before amendment 6 (or a file that cannot be read).
117
138
  * @param {string} flowDir
@@ -16,6 +16,8 @@
16
16
  // is only ever matched against these fixed patterns — never used to build a
17
17
  // pattern. This file never constructs a RegExp dynamically at runtime.
18
18
 
19
+ import { parseTrigger, isTriggerLine } from './trigger-line.js';
20
+
19
21
  /** @typedef {import('./types.js').SignedTextResult} SignedTextResult */
20
22
 
21
23
  /** The arbiter fields this grammar defines — kept in sync with the parser
@@ -28,6 +30,7 @@ export const ARBITER_FIELDS = Object.freeze([
28
30
  'skills',
29
31
  'sources',
30
32
  'roundBudgetMs',
33
+ 'trigger',
31
34
  ]);
32
35
 
33
36
  const HEADING_RE = /^arbiter guardrails\b/i;
@@ -243,6 +246,9 @@ function parseArbiter(arbiterRawLines, lineNumbers, reds, asks) {
243
246
  const sourceRolesSeen = new Set();
244
247
  let roundBudgetMs;
245
248
  let roundSeen = 0;
249
+ // M9: the trigger (By hand = null). One line at most; typed by `parseTrigger`.
250
+ let trigger = null;
251
+ let triggerSeen = 0;
246
252
 
247
253
  for (const { fileLine, text } of arbiterRawLines) {
248
254
  const lower = text.toLowerCase();
@@ -385,6 +391,21 @@ function parseArbiter(arbiterRawLines, lineNumbers, reds, asks) {
385
391
  continue;
386
392
  }
387
393
 
394
+ if (isTriggerLine(`guardrail: ${text}`)) {
395
+ triggerSeen += 1;
396
+ const m = parseTrigger(text.replace(/^trigger\b/i, ''));
397
+ if (!m.ok) {
398
+ reds.push(`arbiter: line ${fileLine} field "trigger" ${m.error}: "${text}"`);
399
+ continue;
400
+ }
401
+ if (triggerSeen > 1) {
402
+ reds.push(`arbiter: line ${fileLine} field "trigger" is duplicated (allowed at most once)`);
403
+ continue;
404
+ }
405
+ trigger = m.trigger;
406
+ continue;
407
+ }
408
+
388
409
  if (lower.startsWith('round budget')) {
389
410
  roundSeen += 1;
390
411
  const m = ROUND_RE.exec(text);
@@ -407,6 +428,10 @@ function parseArbiter(arbiterRawLines, lineNumbers, reds, asks) {
407
428
  reds.push('arbiter: field "capUsd" is required ("cap $<decimal> per run") and is missing');
408
429
  }
409
430
 
431
+ if (trigger && 'role' in trigger && !sourceRolesSeen.has(trigger.role)) {
432
+ reds.push(`arbiter: field "trigger" names the input "${trigger.role}", which is not one of the job's inputs (inputs: [${[...sourceRolesSeen].join(', ')}])`);
433
+ }
434
+
410
435
  for (const s of sends) {
411
436
  if (!asks.some((a) => a.line < s.line)) {
412
437
  reds.push(`arbiter: field "sends" send at line ${s.line} has no ask at an earlier line (asks: [${asks.map((a) => a.line).join(', ')}])`);
@@ -421,6 +446,7 @@ function parseArbiter(arbiterRawLines, lineNumbers, reds, asks) {
421
446
  skills: skills ?? DEFAULT_SKILLS.slice(),
422
447
  sources,
423
448
  roundBudgetMs: roundBudgetMs ?? DEFAULT_ROUND_BUDGET_MS,
449
+ trigger,
424
450
  };
425
451
  }
426
452
 
@@ -0,0 +1,176 @@
1
+ // M9 piece 5 and 6 (docs/wiki/the-module-ladder.md, "M9" item 7, am1, am2): the words of the summary block and of the trigger card.
2
+ // ONE WRITER of these strings. Every function is pure: typed facts in, a fixed sentence out. No model text ever reaches a sentence
3
+ // (the only slot-fills are numbers, a line number, a file or folder name, the human's own destination, and a code from the books).
4
+ //
5
+ // ENDED / NEXT shape borrowed from bareloop's ENDED block (P5) — `endedFor` in bareloop src/panel/server.js:
6
+ // borrowed-from: bareloop src/panel/server.js@f845ee7 (the reason/next pair per ending, and the honest fixed fallback).
7
+ // The table here is fwdloop's own: it is keyed by the outcomes fwdloop's history row can hold.
8
+ import { homedir } from 'node:os';
9
+ import { basename } from 'node:path';
10
+
11
+ /** @typedef {import('./trigger-line.js').Trigger} Trigger */
12
+
13
+ const DAY_PLURAL = { mon: 'Mondays', tue: 'Tuesdays', wed: 'Wednesdays', thu: 'Thursdays', fri: 'Fridays', sat: 'Saturdays', sun: 'Sundays' };
14
+ const DAY_SHORT = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
15
+ const MONTH_SHORT = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
16
+
17
+ /** @param {number} n */
18
+ const two = (n) => String(n).padStart(2, '0');
19
+ /** @param {{hour: number, minute: number}} s */
20
+ const hhmm = (s) => `${two(s.hour)}:${two(s.minute)}`;
21
+ /** @param {number} usd */
22
+ const money = (usd) => `$${usd.toFixed(2)}`;
23
+
24
+ /** A path with the home folder shown as `~`. @param {string} p @param {string} [home] */
25
+ function tilde(p, home = homedir()) {
26
+ if (home && (p === home || p.startsWith(`${home}/`))) return `~${p.slice(home.length)}`;
27
+ return p;
28
+ }
29
+
30
+ /**
31
+ * SCHEDULED: what starts the job, in words. `null` (By hand) has no sentence.
32
+ * @param {Trigger|null} t @param {string} [home]
33
+ * @returns {string|null}
34
+ */
35
+ export function scheduledWords(t, home) {
36
+ if (t === null) return null;
37
+ if (t.kind === 'daily') return `Every day at ${hhmm(t)}`;
38
+ if (t.kind === 'weekdays') return `Weekdays at ${hhmm(t)}`;
39
+ if (t.kind === 'weekly') return `${DAY_PLURAL[/** @type {keyof typeof DAY_PLURAL} */ (t.day)] ?? t.day} at ${hhmm(t)}`;
40
+ if (t.kind === 'file-updated') return `When ${basename(t.path)} is updated`;
41
+ const folder = tilde(/** @type {{folder: string}} */ (t).folder, home);
42
+ return `When a new file arrives in ${folder.endsWith('/') ? folder : `${folder}/`}`;
43
+ }
44
+
45
+ /** "Mon 13 Oct, 09:00" — local time, fixed English names (never the machine's locale). @param {number} ms */
46
+ export function slotWords(ms) {
47
+ const d = new Date(ms);
48
+ return `${DAY_SHORT[d.getDay()]} ${d.getDate()} ${MONTH_SHORT[d.getMonth()]}, ${two(d.getHours())}:${two(d.getMinutes())}`;
49
+ }
50
+
51
+ /**
52
+ * M11 am1 item 3, the Scheduled card's first line: "today 17:00", "tomorrow 09:00", else the date the NEXT line already says ("Tue 20 Oct, 09:05").
53
+ * Local time, by calendar day. @param {number} ms the next run @param {number} now
54
+ */
55
+ export function nextTimeWords(ms, now) {
56
+ const d = new Date(ms);
57
+ const day = (/** @type {Date} */ x) => new Date(x.getFullYear(), x.getMonth(), x.getDate()).getTime();
58
+ const apart = Math.round((day(d) - day(new Date(now))) / 86_400_000);
59
+ if (apart === 0) return `today ${two(d.getHours())}:${two(d.getMinutes())}`;
60
+ if (apart === 1) return `tomorrow ${two(d.getHours())}:${two(d.getMinutes())}`;
61
+ return slotWords(ms);
62
+ }
63
+
64
+ /** M11 am1 item 3, the Scheduled card's second line start: "next in 20m" / "next in 3h" / "next in 3d" (whole units, rounded down, never "0m"). @param {number} ms @param {number} now */
65
+ export function nextInWords(ms, now) {
66
+ const mins = Math.max(1, Math.floor((ms - now) / 60_000));
67
+ if (mins < 60) return `next in ${mins}m`;
68
+ const hours = Math.floor(mins / 60);
69
+ return hours < 48 ? `next in ${hours}h` : `next in ${Math.floor(hours / 24)}d`;
70
+ }
71
+
72
+ /** am1, said before a human signs an edit of a job that has a trigger. @param {Trigger|null} t @param {string} [home] */
73
+ export function editClearsWords(t, home) {
74
+ const w = scheduledWords(t, home);
75
+ if (w === null) return null;
76
+ return `This job runs by itself (${w}). Signing this edit clears that back to By hand. You can set it again once the new job has had one good run.`;
77
+ }
78
+
79
+ /**
80
+ * NEXT of a job with a trigger. One sentence, first match wins:
81
+ * 1. a run of this job is waiting at its ask (the next run waits too);
82
+ * 2. the latest outcome this month is `monthly-exhausted` (the signed sentence, amounts from the row);
83
+ * 3. a clock kind with a next slot; 4. a file kind that is armed; 5. not armed yet.
84
+ * A last outcome of `refused` goes in front of 3-5, so a trigger that cannot start is never silent.
85
+ * `red` is the typed flag for "the human must act": monthly-exhausted and the refused lead. The page paints it; it never guesses from the text.
86
+ * @param {{trigger: Trigger, armed: boolean, nextSlotMs: number|null, lastOutcome: any, waitingLine: number|null, now: number}} f
87
+ * @returns {{text: string, red: boolean}}
88
+ */
89
+ export function scheduledNextFor(f) {
90
+ const { trigger, armed, nextSlotMs, lastOutcome, waitingLine, now } = f;
91
+ /** @param {string} text @param {boolean} [red] */
92
+ const say = (text, red = false) => ({ text, red });
93
+ if (waitingLine !== null) return say(`Waiting for your answer at line ${waitingLine}; the next run waits too.`);
94
+ const last = lastOutcome && typeof lastOutcome === 'object' ? lastOutcome : null;
95
+ const sameMonth = last !== null && typeof last.at === 'string' && Number.isFinite(Date.parse(last.at))
96
+ && new Date(Date.parse(last.at)).getFullYear() === new Date(now).getFullYear() && new Date(Date.parse(last.at)).getMonth() === new Date(now).getMonth();
97
+ if (last !== null && last.outcome === 'monthly-exhausted' && sameMonth && typeof last.leftUsd === 'number' && typeof last.needUsd === 'number') {
98
+ const left = last.atLeast === true ? `at most ${money(last.leftUsd)} left` : `${money(last.leftUsd)} left`;
99
+ return say(`Paused: not enough money left this month (${left}, a run needs up to ${money(last.needUsd)}). Raise the monthly limit in Settings, or it starts again on the 1st.`, true);
100
+ }
101
+ const lead = last !== null && last.outcome === 'refused' && typeof last.why === 'string' && last.why !== '' ? `The last try did not start: ${last.why} ` : '';
102
+ const red = lead !== '';
103
+ if (!armed) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
104
+ if (trigger.kind === 'file-updated') return say(`${lead}Watching for it. A run starts when its contents change.`, red);
105
+ if (trigger.kind === 'new-file') return say(`${lead}Watching for it. A run starts for each new file.`, red);
106
+ if (nextSlotMs === null) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
107
+ return say(`${lead}Next run ${slotWords(nextSlotMs)}.`, red);
108
+ }
109
+
110
+ /** The NEXT sentence alone. @param {Parameters<typeof scheduledNextFor>[0]} f */
111
+ export function scheduledNext(f) {
112
+ return scheduledNextFor(f).text;
113
+ }
114
+
115
+ /** Fixed catch-up sentence (am2 item 1) from a run's `trigger.json`. @param {any} rec */
116
+ export function catchUpWords(rec) {
117
+ return rec && typeof rec === 'object' && rec.catchUp === true ? 'This run was a catch-up: it started more than 2 minutes after its set time (the panel was off).' : null;
118
+ }
119
+
120
+ /** @param {number|null} line @param {string} rest "Stopped at line 4: <rest>" or "Stopped: <rest>" */
121
+ const stoppedAt = (line, rest) => (line === null ? `Stopped: ${rest}` : `Stopped at line ${line}: ${rest}`);
122
+
123
+ const RERUN_NEXT = 'Run it again from the Chat card.';
124
+
125
+ /**
126
+ * ENDED / NEXT of a finished run. Every outcome the history row can hold has a fixed sentence; an unknown one gets an honest fixed fallback
127
+ * that names the code and guesses nothing. `null` when there is no ending (still running, waiting, or no history row and not died).
128
+ * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string}} f
129
+ * @returns {{reason: string, next: string}|null}
130
+ */
131
+ export function endedWords(f) {
132
+ const {
133
+ outcome, died = false, line, destination, canResume, home,
134
+ } = f;
135
+ const resumeOrAgain = canResume ? 'Resume from the Chat card.' : RERUN_NEXT;
136
+ if (died) return { reason: 'It stopped with no ending recorded.', next: 'See the Audit / logs tab for the last thing it did.' };
137
+ if (outcome === null || outcome === undefined) return null;
138
+ switch (outcome) {
139
+ case 'complete':
140
+ return { reason: 'Goal met.', next: destination ? `The result is in ${tilde(destination, home)}.` : 'The result is in the step cards below.' };
141
+ case 'stopped':
142
+ return { reason: 'Stopped by you.', next: resumeOrAgain };
143
+ case 'cap-halt':
144
+ return { reason: stoppedAt(line, 'the next try could not fit under the money cap.'), next: canResume ? 'Raise the cap and Resume from the Chat card.' : RERUN_NEXT };
145
+ case 'redo-halt':
146
+ return { reason: stoppedAt(line, 'you rejected it.'), next: RERUN_NEXT };
147
+ case 'ask-expired':
148
+ case 'ask-timeout':
149
+ return { reason: stoppedAt(line, 'nobody answered in time.'), next: 'Reopen it from the Ask tab, or run it again from the Chat card.' };
150
+ case 'not-done':
151
+ return { reason: stoppedAt(line, 'the step said it did not finish.'), next: RERUN_NEXT };
152
+ case 'struck-out':
153
+ return { reason: stoppedAt(line, 'the checks kept failing and it ran out of strikes.'), next: RERUN_NEXT };
154
+ case 'attempt-fallback':
155
+ return { reason: stoppedAt(line, 'it used up its tries without passing the check.'), next: RERUN_NEXT };
156
+ case 'close-casualty':
157
+ return { reason: stoppedAt(line, 'the check itself could not be run.'), next: RERUN_NEXT };
158
+ case 'provider-red':
159
+ return { reason: stoppedAt(line, 'the model provider failed.'), next: RERUN_NEXT };
160
+ case 'pricing-red':
161
+ return { reason: stoppedAt(line, 'the model returned no cost, so the run stopped rather than guess.'), next: RERUN_NEXT };
162
+ case 'red':
163
+ return { reason: stoppedAt(line, 'a step or its check failed.'), next: RERUN_NEXT };
164
+ case 'rerun':
165
+ return { reason: 'You ended this run on purpose; a fresh run was started.', next: 'Look at the newest run of this job.' };
166
+ case 'preflight-red':
167
+ return { reason: 'It did not start: the job could not pass its pre-run checks. Nothing was spent.', next: 'Fix what the Audit / logs tab names, then run it again from the Chat card.' };
168
+ case 'refused':
169
+ return { reason: 'It did not start: the run was refused. Nothing was spent.', next: 'The Audit / logs tab says why. Fix that, then run it again from the Chat card.' };
170
+ default: {
171
+ // an unknown code: say so, name the code (from the books, capped), guess nothing
172
+ const code = String(outcome).replace(/[^\w-]/g, '').slice(0, 40);
173
+ return { reason: `It ended with "${code}", which this panel has no sentence for.`, next: 'See the Audit / logs tab for what happened.' };
174
+ }
175
+ }
176
+ }