fwdloop 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/fwdloop +2 -1
- package/package.json +1 -1
- package/src/books.js +6 -1
- package/src/panel/author.js +24 -4
- package/src/panel/authorcard.js +2 -1
- package/src/panel/authorflows.js +6 -0
- package/src/panel/authorstart.js +21 -9
- package/src/panel/authortrigger.js +384 -0
- package/src/panel/data.js +87 -11
- package/src/panel/index.html +183 -2
- package/src/panel/scheduler.js +125 -0
- package/src/panel/server.js +17 -8
- package/src/runvalues.js +5 -3
- package/src/setup.js +21 -0
- package/src/signed-text.js +26 -0
- package/src/summary-words.js +155 -0
- package/src/trigger-clock.js +142 -0
- package/src/trigger-files.js +212 -0
- package/src/trigger-line.js +86 -0
- package/src/types.js +1 -0
- package/types/panel/author.d.ts +146 -143
- package/types/panel/authorflows.d.ts +8 -0
- package/types/panel/authorstart.d.ts +7 -4
- package/types/panel/authortrigger.d.ts +210 -0
- package/types/panel/data.d.ts +14 -7
- package/types/panel/scheduler.d.ts +15 -0
- package/types/panel/server.d.ts +9 -3
- package/types/runvalues.d.ts +1 -1
- package/types/setup.d.ts +19 -0
- package/types/summary-words.d.ts +53 -0
- package/types/trigger-clock.d.ts +60 -0
- package/types/trigger-files.d.ts +90 -0
- package/types/trigger-line.d.ts +44 -0
- package/types/types.d.ts +4 -0
package/src/panel/server.js
CHANGED
|
@@ -62,6 +62,7 @@ import {
|
|
|
62
62
|
listRuns, 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
|
|
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,10 @@ 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
|
+
send(200, { rows: listRuns({ root: opts.root, catalogue, resumeAttempt, startingRun }) });
|
|
511
515
|
return;
|
|
512
516
|
}
|
|
513
517
|
|
|
@@ -559,7 +563,7 @@ export function handleRequest(req, res, opts) {
|
|
|
559
563
|
return;
|
|
560
564
|
}
|
|
561
565
|
const result = getRunDetail({
|
|
562
|
-
root: opts.root, flow, runId, catalogue, resumeAttempt,
|
|
566
|
+
root: opts.root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead: (f) => opts.author?.trigger?.read(f) ?? null, now: opts.now,
|
|
563
567
|
});
|
|
564
568
|
if (!result) { sendText(res, 404, 'no such run'); return; }
|
|
565
569
|
send(200, result);
|
|
@@ -575,9 +579,9 @@ export function handleRequest(req, res, opts) {
|
|
|
575
579
|
* header). Resolves once actually listening; rejects on a bind error
|
|
576
580
|
* (including `EADDRINUSE`) with a `.port` field on the error for the
|
|
577
581
|
* 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
|
|
582
|
+
* @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
583
|
* `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> }>}
|
|
584
|
+
* @returns {Promise<{ server: import('node:http').Server, port: number, tick: () => void, close: () => Promise<void> }>}
|
|
581
585
|
*/
|
|
582
586
|
export function createPanelServer(opts) {
|
|
583
587
|
if (typeof opts?.root !== 'string' || opts.root.length === 0) {
|
|
@@ -594,6 +598,9 @@ export function createPanelServer(opts) {
|
|
|
594
598
|
const author = createAuthor({
|
|
595
599
|
root, home: opts.settings?.home ?? door.home, skipMonthly: opts.settings?.home === undefined && door.skip, loadEnv: () => keysForDoor({ env: opts.author?.env }), ...opts.author,
|
|
596
600
|
});
|
|
601
|
+
// 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);
|
|
602
|
+
// `scheduler.intervalMs` 0 = no timer, a test calls `tick`. Stopped on close.
|
|
603
|
+
const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs });
|
|
597
604
|
// Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
|
|
598
605
|
// process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
|
|
599
606
|
const settings = createSettings({
|
|
@@ -609,7 +616,7 @@ export function createPanelServer(opts) {
|
|
|
609
616
|
const server = createServer((req, res) => {
|
|
610
617
|
try {
|
|
611
618
|
handleRequest(req, res, {
|
|
612
|
-
root, port: boundPort, resumer, settings, author, packagePath: opts.packagePath,
|
|
619
|
+
root, port: boundPort, resumer, settings, author, packagePath: opts.packagePath, now: opts.author?.now,
|
|
613
620
|
});
|
|
614
621
|
} catch (e) {
|
|
615
622
|
sendText(res, 500, 'internal error');
|
|
@@ -623,10 +630,12 @@ export function createPanelServer(opts) {
|
|
|
623
630
|
server.listen(requestedPort, '127.0.0.1', () => {
|
|
624
631
|
const addr = server.address();
|
|
625
632
|
boundPort = typeof addr === 'object' && addr !== null ? addr.port : requestedPort;
|
|
633
|
+
scheduler.start();
|
|
626
634
|
resolve({
|
|
627
635
|
server,
|
|
628
636
|
port: boundPort,
|
|
629
|
-
|
|
637
|
+
tick: scheduler.tick,
|
|
638
|
+
close: () => new Promise((res2) => { scheduler.stop(); server.close(() => res2(undefined)); }),
|
|
630
639
|
});
|
|
631
640
|
});
|
|
632
641
|
});
|
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
|
|
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
|
-
|
|
177
|
-
|
|
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
|
package/src/signed-text.js
CHANGED
|
@@ -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
|
+
}
|