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,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
+ }
@@ -0,0 +1,86 @@
1
+ // M9 piece 3 (docs/wiki/the-module-ladder.md, "M9" item 1, am1): the trigger as typed data in the signed arbiter block.
2
+ // Pure text: the grammar of the one `guardrail: trigger ...` line, and the ONE place a prose text gains, changes or loses it.
3
+ //
4
+ // guardrail: trigger daily 09:00
5
+ // guardrail: trigger weekdays 09:00
6
+ // guardrail: trigger weekly mon 09:00
7
+ // guardrail: trigger file-updated <role> = file:<path>
8
+ // guardrail: trigger new-file <role> = file:<folder>
9
+ //
10
+ // No trigger line = By hand (`trigger: null`), so a job signed before M9 parses and hashes exactly as it did. Never cron text.
11
+ // Every regex is a fixed literal, anchored, with no nested quantifiers (signed-text.js's ReDoS rule).
12
+ import { createHash } from 'node:crypto';
13
+
14
+ import { validateSchedule } from './trigger-clock.js';
15
+
16
+ /** @typedef {import('./trigger-clock.js').Schedule} Schedule */
17
+ /** @typedef {Schedule | {kind:'file-updated', role:string, path:string} | {kind:'new-file', role:string, folder:string}} Trigger */
18
+
19
+ const LINE_RE = /^\s*guardrail:\s*trigger\b/i;
20
+ const CLOCK_RE = /^(daily|weekdays) (\d{2}):(\d{2})$/;
21
+ const WEEKLY_RE = /^weekly ([a-z]{3}) (\d{2}):(\d{2})$/;
22
+ const FILE_RE = /^(file-updated|new-file) ([a-z][a-z0-9_-]*) = file:(.*)$/;
23
+
24
+ /**
25
+ * The text after `trigger ` on a guardrail line, as a typed trigger. Never throws.
26
+ * @param {string} text
27
+ * @returns {{ok: true, trigger: Trigger} | {ok: false, error: string}}
28
+ */
29
+ export function parseTrigger(text) {
30
+ const t = String(text).trim();
31
+ const clock = CLOCK_RE.exec(t);
32
+ const weekly = clock ? null : WEEKLY_RE.exec(t);
33
+ const file = clock || weekly ? null : FILE_RE.exec(t);
34
+ try {
35
+ if (clock) return { ok: true, trigger: validateSchedule({ kind: clock[1], hour: Number(clock[2]), minute: Number(clock[3]) }) };
36
+ if (weekly) return { ok: true, trigger: validateSchedule({ kind: 'weekly', day: weekly[1], hour: Number(weekly[2]), minute: Number(weekly[3]) }) };
37
+ } catch (e) {
38
+ return { ok: false, error: /** @type {Error} */ (e).message };
39
+ }
40
+ if (file) {
41
+ const where = file[3].trim();
42
+ if (where === '') return { ok: false, error: 'has an empty path' };
43
+ return { ok: true, trigger: file[1] === 'new-file' ? { kind: 'new-file', role: file[2], folder: where } : { kind: 'file-updated', role: file[2], path: where } };
44
+ }
45
+ return { ok: false, error: `is not "daily HH:MM", "weekdays HH:MM", "weekly <day> HH:MM", "file-updated <role> = file:<path>" or "new-file <role> = file:<folder>": "${t}"` };
46
+ }
47
+
48
+ /** The signed-text line for a trigger. @param {Trigger} t */
49
+ export function triggerLine(t) {
50
+ const hhmm = (/** @type {Schedule} */ s) => `${String(s.hour).padStart(2, '0')}:${String(s.minute).padStart(2, '0')}`;
51
+ if (t.kind === 'daily' || t.kind === 'weekdays') return `guardrail: trigger ${t.kind} ${hhmm(t)}`;
52
+ if (t.kind === 'weekly') return `guardrail: trigger weekly ${t.day} ${hhmm(t)}`;
53
+ if (t.kind === 'file-updated') return `guardrail: trigger file-updated ${t.role} = file:${t.path}`;
54
+ const f = /** @type {{role: string, folder: string}} */ (t);
55
+ return `guardrail: trigger new-file ${f.role} = file:${f.folder}`;
56
+ }
57
+
58
+ /** Is this signed-text line a trigger line (so the grammar sees it, and `stripTrigger` removes it)? @param {string} line */
59
+ export const isTriggerLine = (line) => LINE_RE.test(line);
60
+
61
+ /** The prose without any trigger line. Everything else is byte-for-byte what it was. @param {string} prose */
62
+ export function stripTrigger(prose) {
63
+ return prose.split('\n').filter((l) => !LINE_RE.test(l)).join('\n');
64
+ }
65
+
66
+ /**
67
+ * The ONE writer of the trigger line: the prose with its trigger line replaced by this trigger's (or removed for null). With no trigger
68
+ * in and none asked for, the text is returned unchanged. The arbiter block is last in a signed text, so the line goes at the end.
69
+ * @param {string} prose @param {Trigger|null} trigger
70
+ */
71
+ export function proseWithTrigger(prose, trigger) {
72
+ const stripped = stripTrigger(prose);
73
+ if (trigger === null) return stripped;
74
+ return `${stripped.replace(/\s*$/, '')}\n${triggerLine(trigger)}\n`;
75
+ }
76
+
77
+ /**
78
+ * What the human's second click carries: binds the job, the exact signature it was shown at and the trigger.
79
+ * @param {{flow: string, flowSignatureHash: string, trigger: Trigger|null}} a
80
+ */
81
+ export function triggerHash({ flow, flowSignatureHash, trigger }) {
82
+ return createHash('sha256').update(JSON.stringify({ m9: 'trigger', flow, flowSignatureHash, trigger })).digest('hex');
83
+ }
84
+
85
+ /** M9: the file a triggered start writes (once, before the spawn) into the run's own folder: why this run started. `appendHistory` copies it into the run's history row. */
86
+ export const TRIGGER_RECORD_FILE = 'trigger.json';
package/src/types.js CHANGED
@@ -49,6 +49,7 @@
49
49
  * @property {string[]} skills - `skills <name>[, <name>...]`. Default ['core'].
50
50
  * @property {SourceSlot[]} sources - zero or more `source <role> = file:<path>`.
51
51
  * @property {number} roundBudgetMs - `round budget <int><s|m|h>`. Default 120000.
52
+ * @property {import("./trigger-line.js").Trigger|null} trigger - `trigger <kind> ...` (M9). Default null = By hand.
52
53
  */
53
54
 
54
55
  /**