fwdloop 0.16.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.
Files changed (64) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +10 -7
  3. package/package.json +1 -1
  4. package/src/authoring.js +6 -6
  5. package/src/books.js +6 -1
  6. package/src/catalogue.json +9 -3
  7. package/src/ctx-tools.js +245 -0
  8. package/src/draft-steps.js +89 -30
  9. package/src/drafter.js +28 -4
  10. package/src/draftspend.js +109 -3
  11. package/src/liveness.js +34 -10
  12. package/src/panel/author.js +125 -37
  13. package/src/panel/authorcard.js +15 -10
  14. package/src/panel/authorflows.js +9 -3
  15. package/src/panel/authorresume.js +5 -4
  16. package/src/panel/authorstart.js +21 -9
  17. package/src/panel/authortrigger.js +384 -0
  18. package/src/panel/authorvalues.js +5 -3
  19. package/src/panel/data.js +104 -16
  20. package/src/panel/index.html +257 -44
  21. package/src/panel/scheduler.js +125 -0
  22. package/src/panel/server.js +24 -10
  23. package/src/panel/settings.js +2 -2
  24. package/src/plain-checks.js +51 -0
  25. package/src/primitives.js +34 -3
  26. package/src/provider.js +17 -8
  27. package/src/run-store.js +47 -0
  28. package/src/runner.js +2 -0
  29. package/src/runvalues.js +5 -3
  30. package/src/setup.js +24 -0
  31. package/src/signed-text.js +26 -0
  32. package/src/summary-words.js +155 -0
  33. package/src/trigger-clock.js +142 -0
  34. package/src/trigger-files.js +212 -0
  35. package/src/trigger-line.js +86 -0
  36. package/src/types.js +1 -0
  37. package/src/version.js +13 -0
  38. package/types/authoring.d.ts +1 -3
  39. package/types/ctx-tools.d.ts +18 -0
  40. package/types/draft-steps.d.ts +38 -5
  41. package/types/drafter.d.ts +3 -3
  42. package/types/draftspend.d.ts +56 -0
  43. package/types/liveness.d.ts +7 -1
  44. package/types/panel/author.d.ts +149 -146
  45. package/types/panel/authorcard.d.ts +12 -2
  46. package/types/panel/authorflows.d.ts +11 -3
  47. package/types/panel/authorstart.d.ts +7 -4
  48. package/types/panel/authortrigger.d.ts +210 -0
  49. package/types/panel/authorvalues.d.ts +3 -1
  50. package/types/panel/data.d.ts +14 -7
  51. package/types/panel/scheduler.d.ts +15 -0
  52. package/types/panel/server.d.ts +11 -3
  53. package/types/plain-checks.d.ts +22 -0
  54. package/types/primitives.d.ts +0 -6
  55. package/types/provider.d.ts +7 -1
  56. package/types/run-store.d.ts +11 -0
  57. package/types/runvalues.d.ts +1 -1
  58. package/types/setup.d.ts +27 -0
  59. package/types/summary-words.d.ts +53 -0
  60. package/types/trigger-clock.d.ts +60 -0
  61. package/types/trigger-files.d.ts +90 -0
  62. package/types/trigger-line.d.ts +44 -0
  63. package/types/types.d.ts +4 -0
  64. package/types/version.d.ts +2 -0
@@ -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,155 @@
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
+ /** am1, said before a human signs an edit of a job that has a trigger. @param {Trigger|null} t @param {string} [home] */
52
+ export function editClearsWords(t, home) {
53
+ const w = scheduledWords(t, home);
54
+ if (w === null) return null;
55
+ 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.`;
56
+ }
57
+
58
+ /**
59
+ * NEXT of a job with a trigger. One sentence, first match wins:
60
+ * 1. a run of this job is waiting at its ask (the next run waits too);
61
+ * 2. the latest outcome this month is `monthly-exhausted` (the signed sentence, amounts from the row);
62
+ * 3. a clock kind with a next slot; 4. a file kind that is armed; 5. not armed yet.
63
+ * A last outcome of `refused` goes in front of 3-5, so a trigger that cannot start is never silent.
64
+ * `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.
65
+ * @param {{trigger: Trigger, armed: boolean, nextSlotMs: number|null, lastOutcome: any, waitingLine: number|null, now: number}} f
66
+ * @returns {{text: string, red: boolean}}
67
+ */
68
+ export function scheduledNextFor(f) {
69
+ const { trigger, armed, nextSlotMs, lastOutcome, waitingLine, now } = f;
70
+ /** @param {string} text @param {boolean} [red] */
71
+ const say = (text, red = false) => ({ text, red });
72
+ if (waitingLine !== null) return say(`Waiting for your answer at line ${waitingLine}; the next run waits too.`);
73
+ const last = lastOutcome && typeof lastOutcome === 'object' ? lastOutcome : null;
74
+ const sameMonth = last !== null && typeof last.at === 'string' && Number.isFinite(Date.parse(last.at))
75
+ && new Date(Date.parse(last.at)).getFullYear() === new Date(now).getFullYear() && new Date(Date.parse(last.at)).getMonth() === new Date(now).getMonth();
76
+ if (last !== null && last.outcome === 'monthly-exhausted' && sameMonth && typeof last.leftUsd === 'number' && typeof last.needUsd === 'number') {
77
+ const left = last.atLeast === true ? `at most ${money(last.leftUsd)} left` : `${money(last.leftUsd)} left`;
78
+ 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);
79
+ }
80
+ const lead = last !== null && last.outcome === 'refused' && typeof last.why === 'string' && last.why !== '' ? `The last try did not start: ${last.why} ` : '';
81
+ const red = lead !== '';
82
+ if (!armed) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
83
+ if (trigger.kind === 'file-updated') return say(`${lead}Watching for it. A run starts when its contents change.`, red);
84
+ if (trigger.kind === 'new-file') return say(`${lead}Watching for it. A run starts for each new file.`, red);
85
+ if (nextSlotMs === null) return say(`${lead}Not armed yet: the panel arms it on its next check.`, red);
86
+ return say(`${lead}Next run ${slotWords(nextSlotMs)}.`, red);
87
+ }
88
+
89
+ /** The NEXT sentence alone. @param {Parameters<typeof scheduledNextFor>[0]} f */
90
+ export function scheduledNext(f) {
91
+ return scheduledNextFor(f).text;
92
+ }
93
+
94
+ /** Fixed catch-up sentence (am2 item 1) from a run's `trigger.json`. @param {any} rec */
95
+ export function catchUpWords(rec) {
96
+ 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;
97
+ }
98
+
99
+ /** @param {number|null} line @param {string} rest "Stopped at line 4: <rest>" or "Stopped: <rest>" */
100
+ const stoppedAt = (line, rest) => (line === null ? `Stopped: ${rest}` : `Stopped at line ${line}: ${rest}`);
101
+
102
+ const RERUN_NEXT = 'Run it again from the Chat card.';
103
+
104
+ /**
105
+ * 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
106
+ * that names the code and guesses nothing. `null` when there is no ending (still running, waiting, or no history row and not died).
107
+ * @param {{outcome: string|null, died?: boolean, line: number|null, destination: string|null, canResume: boolean, home?: string}} f
108
+ * @returns {{reason: string, next: string}|null}
109
+ */
110
+ export function endedWords(f) {
111
+ const {
112
+ outcome, died = false, line, destination, canResume, home,
113
+ } = f;
114
+ const resumeOrAgain = canResume ? 'Resume from the Chat card.' : RERUN_NEXT;
115
+ if (died) return { reason: 'It stopped with no ending recorded.', next: 'See the Audit / logs tab for the last thing it did.' };
116
+ if (outcome === null || outcome === undefined) return null;
117
+ switch (outcome) {
118
+ case 'complete':
119
+ return { reason: 'Goal met.', next: destination ? `The result is in ${tilde(destination, home)}.` : 'The result is in the step cards below.' };
120
+ case 'stopped':
121
+ return { reason: 'Stopped by you.', next: resumeOrAgain };
122
+ case 'cap-halt':
123
+ 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 };
124
+ case 'redo-halt':
125
+ return { reason: stoppedAt(line, 'you rejected it.'), next: RERUN_NEXT };
126
+ case 'ask-expired':
127
+ case 'ask-timeout':
128
+ return { reason: stoppedAt(line, 'nobody answered in time.'), next: 'Reopen it from the Ask tab, or run it again from the Chat card.' };
129
+ case 'not-done':
130
+ return { reason: stoppedAt(line, 'the step said it did not finish.'), next: RERUN_NEXT };
131
+ case 'struck-out':
132
+ return { reason: stoppedAt(line, 'the checks kept failing and it ran out of strikes.'), next: RERUN_NEXT };
133
+ case 'attempt-fallback':
134
+ return { reason: stoppedAt(line, 'it used up its tries without passing the check.'), next: RERUN_NEXT };
135
+ case 'close-casualty':
136
+ return { reason: stoppedAt(line, 'the check itself could not be run.'), next: RERUN_NEXT };
137
+ case 'provider-red':
138
+ return { reason: stoppedAt(line, 'the model provider failed.'), next: RERUN_NEXT };
139
+ case 'pricing-red':
140
+ return { reason: stoppedAt(line, 'the model returned no cost, so the run stopped rather than guess.'), next: RERUN_NEXT };
141
+ case 'red':
142
+ return { reason: stoppedAt(line, 'a step or its check failed.'), next: RERUN_NEXT };
143
+ case 'rerun':
144
+ return { reason: 'You ended this run on purpose; a fresh run was started.', next: 'Look at the newest run of this job.' };
145
+ case 'preflight-red':
146
+ 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.' };
147
+ case 'refused':
148
+ 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.' };
149
+ default: {
150
+ // an unknown code: say so, name the code (from the books, capped), guess nothing
151
+ const code = String(outcome).replace(/[^\w-]/g, '').slice(0, 40);
152
+ return { reason: `It ended with "${code}", which this panel has no sentence for.`, next: 'See the Audit / logs tab for what happened.' };
153
+ }
154
+ }
155
+ }
@@ -0,0 +1,142 @@
1
+ // M9 piece 1 (docs/wiki/the-module-ladder.md, "M9" items 1 and 3, amendment 2 item 1): the clock trigger.
2
+ // Pure schedule maths plus an append-only ledger. Proven first in poc/m9 (ported, not imported).
3
+ //
4
+ // A schedule is a typed object, never cron text:
5
+ // { kind:'daily', hour, minute } | { kind:'weekdays', hour, minute } | { kind:'weekly', day:'mon'|..., hour, minute }
6
+ // Times are LOCAL. One slot per calendar day at most (built with the local Date constructor), so a DST
7
+ // change day can neither lose nor double a slot: a 02:30 that does not exist shifts to 03:30, one that
8
+ // happens twice is the first.
9
+ //
10
+ // Ledger: append-only JSONL, write-once rows keyed by `id`, re-read from disk every time (no process state).
11
+ // { id:'armed:<ms>', kind:'armed', at } the trigger was set: the starting point
12
+ // { id:'fire:<slotMs>', kind:'fire', slot, at, catchUp, missed } one run started for that slot
13
+ // Starting a run is NOT this file; the caller does it after `recordFire`.
14
+ import {
15
+ appendFileSync, existsSync, mkdirSync, readFileSync,
16
+ } from 'node:fs';
17
+ import { dirname } from 'node:path';
18
+
19
+ /** @typedef {{kind:'daily'|'weekdays', hour:number, minute:number} | {kind:'weekly', day:string, hour:number, minute:number}} Schedule */
20
+ /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number}} ClockRow */
21
+ /** @typedef {{fire:boolean, catchUp:boolean, missed:number, slot?:number}} Due */
22
+
23
+ /** A slot seen MORE than this after its set time is a catch-up (M9 am2 item 1). Exactly this late is on time. */
24
+ export const GRACE_MS = 120_000;
25
+
26
+ const DAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
27
+
28
+ /**
29
+ * The only way a schedule enters the system. Refuses anything else, naming the field.
30
+ * @param {unknown} s
31
+ * @returns {Schedule}
32
+ */
33
+ export function validateSchedule(s) {
34
+ if (!s || typeof s !== 'object' || Array.isArray(s)) throw new Error('schedule must be an object like { kind, hour, minute }, not text');
35
+ const o = /** @type {Record<string, unknown>} */ (s);
36
+ const kinds = ['daily', 'weekdays', 'weekly'];
37
+ if (!kinds.includes(/** @type {string} */ (o.kind))) throw new Error(`schedule kind "${o.kind}" is not one of ${kinds.join(', ')}`);
38
+ const allowed = o.kind === 'weekly' ? ['kind', 'day', 'hour', 'minute'] : ['kind', 'hour', 'minute'];
39
+ for (const k of Object.keys(o)) if (!allowed.includes(k)) throw new Error(`schedule field "${k}" is not allowed on a ${o.kind} schedule`);
40
+ const hour = o.hour; const minute = o.minute;
41
+ if (!Number.isInteger(hour) || /** @type {number} */ (hour) < 0 || /** @type {number} */ (hour) > 23) throw new Error('schedule hour must be a whole number 0-23');
42
+ if (!Number.isInteger(minute) || /** @type {number} */ (minute) < 0 || /** @type {number} */ (minute) > 59) throw new Error('schedule minute must be a whole number 0-59');
43
+ if (o.kind === 'weekly') {
44
+ if (typeof o.day !== 'string' || !DAYS.includes(o.day)) throw new Error(`schedule day must be one of ${DAYS.join(', ')}`);
45
+ return { kind: 'weekly', day: o.day, hour: /** @type {number} */ (hour), minute: /** @type {number} */ (minute) };
46
+ }
47
+ return { kind: /** @type {'daily'|'weekdays'} */ (o.kind), hour: /** @type {number} */ (hour), minute: /** @type {number} */ (minute) };
48
+ }
49
+
50
+ /**
51
+ * Slots (epoch ms) in (afterMs, untilMs], oldest first.
52
+ * @param {Schedule} sc
53
+ * @param {number} afterMs
54
+ * @param {number} untilMs
55
+ * @returns {number[]}
56
+ */
57
+ function slotsBetween(sc, afterMs, untilMs) {
58
+ const out = [];
59
+ const s = new Date(afterMs);
60
+ for (let i = 0; ; i++) {
61
+ const d = new Date(s.getFullYear(), s.getMonth(), s.getDate() + i);
62
+ if (d.getTime() > untilMs) break;
63
+ const dow = d.getDay();
64
+ const ok = sc.kind === 'daily'
65
+ || (sc.kind === 'weekdays' && dow >= 1 && dow <= 5)
66
+ || (sc.kind === 'weekly' && dow === DAYS.indexOf(/** @type {{day:string}} */ (sc).day));
67
+ if (!ok) continue;
68
+ const slot = new Date(d.getFullYear(), d.getMonth(), d.getDate(), sc.hour, sc.minute).getTime();
69
+ if (slot > afterMs && slot <= untilMs) out.push(slot);
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /**
75
+ * The starting point: the latest of the arm time(s) and every recorded fire slot. No arm row = null.
76
+ * @param {ClockRow[]} rows
77
+ */
78
+ function lastPoint(rows) {
79
+ let armed = false; let last = -Infinity;
80
+ for (const r of rows) {
81
+ if (r.kind === 'armed') { armed = true; last = Math.max(last, r.at); } else if (r.kind === 'fire') last = Math.max(last, /** @type {number} */ (r.slot));
82
+ }
83
+ return armed ? last : null;
84
+ }
85
+
86
+ /**
87
+ * Is a run due at `now`? Slots missed (panel off) collapse to ONE fire, for the latest slot, marked catch-up.
88
+ * Catch-up = more than one slot was missed, or the latest slot is more than GRACE_MS old.
89
+ * @param {Schedule} schedule
90
+ * @param {ClockRow[]} rows
91
+ * @param {number} now epoch ms
92
+ * @returns {Due}
93
+ */
94
+ export function due(schedule, rows, now) {
95
+ const last = lastPoint(rows);
96
+ if (last === null) return { fire: false, catchUp: false, missed: 0 };
97
+ const slots = slotsBetween(validateSchedule(schedule), last, now);
98
+ if (!slots.length) return { fire: false, catchUp: false, missed: 0 };
99
+ const slot = slots[slots.length - 1];
100
+ const catchUp = slots.length > 1 || now - slot > GRACE_MS;
101
+ return { fire: true, catchUp, missed: catchUp ? slots.length : 0, slot };
102
+ }
103
+
104
+ /**
105
+ * The next slot time strictly after `afterMs` (epoch ms). Words ("Next run Mon 13 Oct, 09:00.") are the caller's.
106
+ * @param {Schedule} schedule
107
+ * @param {number} afterMs
108
+ * @returns {number}
109
+ */
110
+ export function nextSlot(schedule, afterMs) {
111
+ const sc = validateSchedule(schedule);
112
+ // a week plus a day always holds a slot of any kind
113
+ const found = slotsBetween(sc, afterMs, afterMs + 9 * 86_400_000)[0];
114
+ return /** @type {number} */ (found);
115
+ }
116
+
117
+ /** @param {string} file @returns {ClockRow[]} every row on disk, oldest first; a missing file is no rows. */
118
+ export function readRows(file) {
119
+ if (!existsSync(file)) return [];
120
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
121
+ }
122
+
123
+ /** Append one row; a row whose id is already on disk is refused (write-once). @param {string} file @param {ClockRow} row */
124
+ function appendOnce(file, row) {
125
+ if (readRows(file).some((r) => r.id === row.id)) throw new Error(`ledger row ${row.id} already written`);
126
+ mkdirSync(dirname(file), { recursive: true });
127
+ appendFileSync(file, `${JSON.stringify(row)}\n`);
128
+ }
129
+
130
+ /** The trigger was set at `now`: no slot before this ever fires. @param {string} file @param {number} now */
131
+ export function armTrigger(file, now) {
132
+ appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now });
133
+ }
134
+
135
+ /**
136
+ * Record that the run for this due slot is starting. Call BEFORE starting the run: a crash loses a run, never doubles one.
137
+ * @param {string} file @param {Due} d the result of `due` with fire true @param {number} now
138
+ */
139
+ export function recordFire(file, d, now) {
140
+ if (!d.fire || d.slot === undefined) throw new Error('recordFire needs a due result with fire true');
141
+ appendOnce(file, { id: `fire:${d.slot}`, kind: 'fire', slot: d.slot, at: now, catchUp: d.catchUp, missed: d.missed });
142
+ }
@@ -0,0 +1,212 @@
1
+ // M9 piece 2 (docs/wiki/the-module-ladder.md, "M9" item 6, amendment 2 item 2): the file triggers.
2
+ // Poll-based, NOT fs.watch (it throws EMFILE on the dev machine and misses atomic renames; poc/m9 report).
3
+ // Proven first in poc/m9 (ported, not imported). This file only says WHAT to run ({path, sha, size});
4
+ // starting the run, pinning the input (frozen copy + sha256) and busy/monthly checks are the caller's.
5
+ //
6
+ // Modes: 'updated' — one file; 'new' — one folder, top level only, regular files only.
7
+ // Symlinks are refused, checked at use time (realpathSync on the folder, lstat on the file), never lexically.
8
+ // A file is taken only after its size AND mtime were unchanged for STABLE_POLLS consecutive polls.
9
+ // Seen ledger (append-only JSONL, write-once rows keyed by id, re-read from disk, so it survives restart). M9 am3: THE SCHEDULER is its only
10
+ // writer after `arm`; this file only says what the rows are and how to read the queue out of them:
11
+ // { id, kind:'baseline'|'arrived'|'ran'|'dropped', sha, name, size, at } (+ `path` on arrived, `why` and `of` (the arrived id it cancels) on dropped)
12
+ // 'baseline' = present when the trigger was set (am2 item 2): never runs. 'arrived' = a finished file with a never-seen sha was seen
13
+ // (`at` = the scheduler's clock; a 2nd arrival of a dropped sha gets id `arrived:<sha>:<n>`). 'ran' = written immediately BEFORE that file's run is started, so a crash loses a run and never doubles
14
+ // one. 'dropped' = it was deleted / changed before its turn. A sha with a `ran` row never arrives again, whatever its name or mtime; see `arrives` for baseline / queued / dropped.
15
+ // poll() writes nothing: it only reports finished files whose sha is new.
16
+ import {
17
+ appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync,
18
+ } from 'node:fs';
19
+ import { basename, dirname, join } from 'node:path';
20
+ import { createHash } from 'node:crypto';
21
+
22
+ /** @typedef {{id:string, kind:'baseline'|'arrived'|'ran'|'dropped', sha:string, name:string, size:number, at:number, path?:string, why?:string, of?:string}} SeenRow */
23
+ /** @typedef {{path:string, sha:string, size:number}} ToRun */
24
+ /** @typedef {{path:string, why:string}} Refused */
25
+
26
+ /** Consecutive polls with the same size and mtime before a file is taken. (Two matches in a row = taken on the third sighting.) */
27
+ export const STABLE_POLLS = 2;
28
+
29
+ /** @param {string} file @returns {SeenRow[]} */
30
+ export function readSeen(file) {
31
+ if (!existsSync(file)) return [];
32
+ return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
33
+ }
34
+
35
+ /** The ONE appender: write-once by id (a second row with the same id is not written). @param {string} file @param {SeenRow} row @returns {boolean} written */
36
+ function appendSeen(file, row) {
37
+ if (readSeen(file).some((r) => r.id === row.id)) return false;
38
+ mkdirSync(dirname(file), { recursive: true });
39
+ appendFileSync(file, `${JSON.stringify(row)}\n`);
40
+ return true;
41
+ }
42
+
43
+ /** Rows of one sha, file order. @param {SeenRow[]} rows @param {string} sha */
44
+ const ofSha = (rows, sha) => rows.filter((r) => r.sha === sha);
45
+ /** An arrived row is still waiting: neither its sha ran nor a dropped row names it. @param {SeenRow[]} rows @param {SeenRow} a */
46
+ const waiting = (rows, a) => a.kind === 'arrived'
47
+ && !rows.some((r) => (r.kind === 'ran' && r.sha === a.sha) || (r.kind === 'dropped' && ((/** @type {any} */ (r)).of ?? `arrived:${r.sha}`) === a.id));
48
+
49
+ /**
50
+ * Does this finished version arrive? Item 6 + am2: only a sha that already RAN never arrives again; one already arrived and still queued does not
51
+ * arrive twice; one that was dropped (never ran) may. A `baseline` blocks only while it is still the starting point: file-updated = until the file
52
+ * has changed away (any later arrived/ran/dropped row of ANOTHER sha); new-file = for that name + sha (a copy under a new name is a new file).
53
+ * @param {SeenRow[]} rows @param {{sha:string, name:string}} it @param {'new'|'updated'} mode
54
+ */
55
+ function arrives(rows, it, mode) {
56
+ const mine = ofSha(rows, it.sha);
57
+ if (mine.some((r) => r.kind === 'ran' || waiting(rows, r))) return false;
58
+ const bi = rows.findLastIndex((r) => r.kind === 'baseline' && r.sha === it.sha && (mode === 'updated' || r.name === it.name));
59
+ if (bi < 0) return true;
60
+ return mode === 'updated' && rows.slice(bi + 1).some((r) => r.kind !== 'baseline' && r.sha !== it.sha);
61
+ }
62
+
63
+ /** Arrived rows are never overwritten: the 2nd arrival of a sha (after a drop) gets its own id. @param {string} ledger @param {ToRun & {name?:string}} item @param {number} at the scheduler's clock, never the file's mtime */
64
+ export function recordArrived(ledger, item, at) {
65
+ const rows = readSeen(ledger);
66
+ if (rows.some((r) => r.sha === item.sha && (r.kind === 'ran' || waiting(rows, r)))) return false; // one writer decides: ran or already queued
67
+ const n = rows.filter((r) => r.kind === 'arrived' && r.sha === item.sha).length;
68
+ return appendSeen(ledger, { id: n ? `arrived:${item.sha}:${n}` : `arrived:${item.sha}`, kind: 'arrived', sha: item.sha, name: basename(item.path), size: item.size, path: item.path, at });
69
+ }
70
+ /** Call immediately before the run is started. @param {string} ledger @param {{sha:string, path:string, size:number}} item @param {number} at */
71
+ export const recordRan = (ledger, item, at) => appendSeen(ledger, { id: `ran:${item.sha}`, kind: 'ran', sha: item.sha, name: basename(item.path), size: item.size, at });
72
+ /** `of` = the arrived row it cancels (item.id when a queue row is passed). @param {string} ledger @param {{sha:string, path:string, size:number, id?:string}} item @param {'deleted'|'changed'} why @param {number} at */
73
+ export function recordDropped(ledger, item, why, at) {
74
+ const of = item.id ?? `arrived:${item.sha}`;
75
+ return appendSeen(ledger, { id: `dropped:${of}`, kind: 'dropped', sha: item.sha, name: basename(item.path), size: item.size, why, at, of });
76
+ }
77
+
78
+ /**
79
+ * The queue: arrived and neither ran nor dropped, oldest arrival first. Identical arrival times: by name, then by sha (deterministic).
80
+ * @param {SeenRow[]} rows @returns {(SeenRow & {path:string})[]}
81
+ */
82
+ export function queueOf(rows) {
83
+ const cmp = (/** @type {string} */ x, /** @type {string} */ y) => (x < y ? -1 : x > y ? 1 : 0);
84
+ return /** @type {any} */ (rows.filter((r) => waiting(rows, r)))
85
+ .sort((x, y) => x.at - y.at || cmp(x.name, y.name) || cmp(x.sha, y.sha));
86
+ }
87
+
88
+ /**
89
+ * At a queued file's turn, look at it again, at use time: lstat (no symlink, a regular file), realpath of its folder, re-hash.
90
+ * @param {{path:string, sha:string}} item
91
+ * @returns {{state:'ok', path:string, sha:string, size:number} | {state:'deleted', say:string} | {state:'changed', sha:string}}
92
+ */
93
+ export function recheck(item) {
94
+ let parent;
95
+ try { parent = realpathSync(dirname(item.path)); } catch { return { state: 'deleted', say: 'its folder is gone' }; }
96
+ const p = join(parent, basename(item.path));
97
+ let st;
98
+ try { st = lstatSync(p); } catch { return { state: 'deleted', say: 'it was deleted' }; }
99
+ if (st.isSymbolicLink() || !st.isFile()) return { state: 'deleted', say: 'it is no longer a regular file (a symlink is refused)' };
100
+ let buf;
101
+ try { buf = readFileSync(p); } catch { return { state: 'deleted', say: 'it was deleted' }; }
102
+ const sha = sha256(buf);
103
+ return sha === item.sha ? { state: 'ok', path: p, sha, size: buf.length } : { state: 'changed', sha };
104
+ }
105
+
106
+ /** @param {Buffer} buf */
107
+ const sha256 = (buf) => createHash('sha256').update(buf).digest('hex');
108
+
109
+ /**
110
+ * The target is usable NOW, or an Error naming why: a file that is not a symlink and not something else (a file that does not exist yet
111
+ * is allowed: it may arrive), a folder that exists, resolved with realpathSync. The one rule `arm` and a door's set-time check share.
112
+ * @param {'new'|'updated'} mode @param {string} target
113
+ */
114
+ export function checkTarget(mode, target) {
115
+ if (mode === 'updated') {
116
+ if (existsSync(target) && lstatSync(target).isSymbolicLink()) throw new Error(`file to watch ${target} is a symlink; a symlink is refused`);
117
+ if (existsSync(target) && !lstatSync(target).isFile()) throw new Error(`${target} is not a file`);
118
+ } else {
119
+ let real;
120
+ try { real = realpathSync(target); } catch { throw new Error(`folder to watch ${target} does not exist`); }
121
+ if (!lstatSync(real).isDirectory()) throw new Error(`${target} is not a folder`);
122
+ }
123
+ }
124
+
125
+ /**
126
+ * @param {{mode:'new'|'updated', target:string, ledger:string}} opts target = folder (new) or file (updated)
127
+ */
128
+ export function createFileTrigger({ mode, target, ledger }) {
129
+ if (mode !== 'new' && mode !== 'updated') throw new Error(`file trigger mode "${mode}" is not one of new, updated`);
130
+ /** @type {Map<string, {key:string, same:number, takenKey:string|null}>} */
131
+ const track = new Map();
132
+ const toldRefused = new Set();
133
+
134
+ /**
135
+ * The regular-file candidates right now, re-resolved at use time.
136
+ * @returns {{files:string[], refused:Refused[]}}
137
+ */
138
+ function candidates() {
139
+ /** @type {Refused[]} */ const refused = [];
140
+ if (mode === 'updated') {
141
+ let parent;
142
+ try { parent = realpathSync(dirname(target)); } catch { return { files: [], refused }; }
143
+ const p = join(parent, basename(target));
144
+ let st;
145
+ try { st = lstatSync(p); } catch { return { files: [], refused }; }
146
+ if (st.isSymbolicLink()) return { files: [], refused: [{ path: p, why: 'a symlink is refused' }] };
147
+ if (!st.isFile()) return { files: [], refused: [{ path: p, why: 'not a regular file' }] };
148
+ return { files: [p], refused };
149
+ }
150
+ let real;
151
+ try { real = realpathSync(target); } catch { return { files: [], refused }; }
152
+ const files = [];
153
+ for (const name of readdirSync(real)) {
154
+ const p = join(real, name);
155
+ let st;
156
+ try { st = lstatSync(p); } catch { continue; }
157
+ if (st.isSymbolicLink()) refused.push({ path: p, why: 'a symlink is refused' });
158
+ else if (st.isFile()) files.push(p);
159
+ }
160
+ return { files, refused };
161
+ }
162
+
163
+ /** Validate the target now and record what is already there as the baseline: it never runs. */
164
+ function arm() {
165
+ checkTarget(mode, target);
166
+ for (const p of candidates().files) {
167
+ const buf = readFileSync(p);
168
+ const sha = sha256(buf);
169
+ appendSeen(ledger, { id: `baseline:${sha}:${basename(p)}`, kind: 'baseline', sha, name: basename(p), size: buf.length, at: Date.now() }); // write-once: re-arming adds nothing
170
+ }
171
+ }
172
+
173
+ /** @param {string} p @param {{key:string}} t @returns {ToRun|null|'changed'} null = this sha already ran */
174
+ function take(p, t) {
175
+ const buf = readFileSync(p);
176
+ const st2 = lstatSync(p);
177
+ if (`${st2.size}:${st2.mtimeMs}` !== t.key) return 'changed'; // changed while reading: retry next poll
178
+ const sha = sha256(buf);
179
+ if (!arrives(readSeen(ledger), { sha, name: basename(p) }, mode)) return null; // ran, still queued, or still the starting point
180
+ return { path: p, sha, size: buf.length };
181
+ }
182
+
183
+ /**
184
+ * One poll. Synchronous, so a caller drives it from setInterval and a test drives it by hand.
185
+ * @returns {{arrived: ToRun[], refused: Refused[]}} finished files with a never-seen sha (the caller records them); refused paths are told once per trigger object
186
+ */
187
+ function poll() {
188
+ const { files, refused } = candidates();
189
+ const arrived = [];
190
+ const present = new Set(files);
191
+ for (const p of [...track.keys()]) if (!present.has(p)) track.delete(p);
192
+ for (const p of files) {
193
+ let st;
194
+ try { st = lstatSync(p); } catch { continue; }
195
+ const key = `${st.size}:${st.mtimeMs}`;
196
+ let t = track.get(p);
197
+ if (!t) { t = { key, same: 0, takenKey: null }; track.set(p, t); } else if (t.key !== key) { t.key = key; t.same = 0; } else t.same++;
198
+ if (t.same >= STABLE_POLLS && t.takenKey !== key) {
199
+ let got;
200
+ try { got = take(p, t); } catch { continue; } // vanished while reading
201
+ if (got === 'changed') continue;
202
+ t.takenKey = key;
203
+ if (got) arrived.push(got);
204
+ }
205
+ }
206
+ const told = refused.filter((r) => !toldRefused.has(r.path));
207
+ for (const r of told) toldRefused.add(r.path);
208
+ return { arrived, refused: told };
209
+ }
210
+
211
+ return { arm, poll };
212
+ }