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.
package/bin/fwdloop CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  runFlow, resumeRun, continueRun, auditSpend, makeParkingAskStep, readAsk, readRunState,
31
31
  } from '../src/runner.js';
32
32
  import { applyRunValues, pickRunValues, dropUnstartedValues } from '../src/runvalues.js';
33
+ import { TRIGGER_RECORD_FILE } from '../src/trigger-line.js';
33
34
  import { makeLiveModelStep } from '../src/model-step.js';
34
35
  import { sendViaPrimitive } from '../src/send.js';
35
36
  import { resolvePrimitives } from '../src/primitives.js';
@@ -352,7 +353,7 @@ async function cmdRun(rest) {
352
353
  if (!runIdCheck.ok) fail(runIdCheck.red);
353
354
  runDir = runIdCheck.runDir;
354
355
  // M4e amendment 5: the panel's Sign & run puts the run's signed values in the folder BEFORE the start; that one file is not "a run".
355
- if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json').length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
356
+ if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE).length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
356
357
  }
357
358
  // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's) is what the monthly hold is for.
358
359
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.17.0",
3
+ "version": "0.19.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
package/src/books.js CHANGED
@@ -22,6 +22,7 @@ import { appendFileSync, mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
24
  import { readFileInside, readdirInside } from './flow.js';
25
+ import { TRIGGER_RECORD_FILE } from './trigger-line.js';
25
26
 
26
27
  function appendLine(filePath, row) {
27
28
  mkdirSync(dirname(filePath), { recursive: true });
@@ -288,7 +289,11 @@ export function readAudit(runDir) {
288
289
  */
289
290
  export function appendHistory(flowDir, row) {
290
291
  checkCostField(row, 'spentUsd', 'appendHistory');
291
- appendLine(join(flowDir, 'history.jsonl'), row);
292
+ // M9 (am2 item 1): a run a trigger started says so in its history row, read from the record the start wrote into the run's own folder
293
+ const rec = typeof row.runId === 'string' && row.trigger === undefined ? readFileInside(join(flowDir, 'runs', row.runId), TRIGGER_RECORD_FILE) : null;
294
+ let trigger;
295
+ if (rec !== null && rec.ok) { try { trigger = JSON.parse(rec.text); } catch { trigger = undefined; } }
296
+ appendLine(join(flowDir, 'history.jsonl'), trigger === undefined ? row : { ...row, trigger });
292
297
  }
293
298
 
294
299
  /**
@@ -60,6 +60,7 @@ import {
60
60
  import { flowValues, valuesHash } from '../runvalues.js';
61
61
  import { leastResumeCapUsd } from './authorvalues.js';
62
62
  import { createFlowsDoor } from './authorflows.js';
63
+ import { createTriggerDoor } from './authortrigger.js';
63
64
  import { createResumeDoor } from './authorresume.js';
64
65
  import { createStarter } from './authorstart.js';
65
66
  import {
@@ -93,13 +94,13 @@ const KILL_HARD_WAIT_MS = 2000;
93
94
  const sleep = (ms) => new Promise((r) => { setTimeout(r, ms); });
94
95
 
95
96
  /**
96
- * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, childRunning?: (dir: string) => boolean, thinkingSupport?: typeof bareagentThinkingSupport }} opts
97
+ * @param {{ root: string, home?: string, skipMonthly?: boolean, loadEnv: () => { ok: boolean, env: Record<string, string|undefined>, refusal: string|null, keyNames?: string[] }, bin?: string, childRunning?: (dir: string) => boolean, thinkingSupport?: typeof bareagentThinkingSupport, now?: () => number }} opts
97
98
  * `loadEnv` is the keys-file door (`keysForDoor`): called before EVERY spawn and every reply that quotes a log, so editing
98
99
  * the file needs no restart. Its `env` is BOTH the child's spawn env AND the scrub list (POC (a), M4d wiring rule).
99
100
  */
100
101
  export function createAuthor(opts) {
101
102
  const {
102
- root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow, thinkingSupport = bareagentThinkingSupport,
103
+ root, loadEnv, home, skipMonthly = false, bin = BIN, childRunning = childRunningNow, thinkingSupport = bareagentThinkingSupport, now = Date.now,
103
104
  } = opts;
104
105
  // the ONE run-start path (sign and run both end in `starter.start`) and the Run-a-signed-flow door built on it
105
106
  const starter = createStarter({ root, bin });
@@ -107,6 +108,11 @@ export function createAuthor(opts) {
107
108
  root, home, skipMonthly, loadEnv, starter, monthlyClaim: (usd) => monthlyClaim(usd), modelRefusal: (card, loaded) => modelRefusal(card, loaded),
108
109
  });
109
110
 
111
+ // M9: the trigger door (set the signed trigger, read it) and the one fire path the panel's scheduler calls
112
+ const triggerDoor = createTriggerDoor({
113
+ root, flowsDoor, starter, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), modelRefusal: (card, loaded) => modelRefusal(card, loaded), now,
114
+ });
115
+
110
116
  /** The ONE monthly check, defined below (a function declaration, so the doors above may take it now). */
111
117
  const resumeDoor = createResumeDoor({
112
118
  root, home, loadEnv, monthlyClaim: (usd) => monthlyClaim(usd), starter,
@@ -376,10 +382,21 @@ export function createAuthor(opts) {
376
382
  }
377
383
 
378
384
  return {
379
- flows: flowsDoor.flows,
380
- runAgain: flowsDoor.runAgain,
385
+ /** `GET /api/author/flows`, each listed job carrying its trigger card (M9 piece 5): the typed trigger, its words, and why it cannot be set (no good run yet). */
386
+ flows() {
387
+ const r = flowsDoor.flows();
388
+ if (r.status !== 200 || !Array.isArray(r.body.flows)) return r;
389
+ return { ...r, body: { ...r.body, flows: r.body.flows.map((f) => ({ ...f, trigger: triggerDoor.card(f.flow) })) } };
390
+ },
391
+ /** `GET /api/author/run-again`, its flow entry carrying the trigger card like the list's entries do. @param {string|null} flow @param {string|null} runId */
392
+ runAgain(flow, runId) {
393
+ const r = /** @type {any} */ (flowsDoor.runAgain(flow, runId));
394
+ if (r.status !== 200 || !r.body.flow) return r;
395
+ return { ...r, body: { ...r.body, flow: { ...r.body.flow, trigger: triggerDoor.card(r.body.flow.flow) } } };
396
+ },
381
397
  run: flowsDoor.run,
382
398
  runPrepare: flowsDoor.runPrepare,
399
+ trigger: triggerDoor,
383
400
  resumePrepare: resumeDoor.prepare,
384
401
  resumeForm: resumeDoor.form,
385
402
  resume: resumeDoor.resume,
@@ -430,6 +447,9 @@ export function createAuthor(opts) {
430
447
  return { status: 200, body: { ok: true, lines, say: lines.length === 0 ? 'Tick a model in Settings > Providers.' : '' } };
431
448
  },
432
449
 
450
+ /** The starter's "this run's start is in phase `starting`" for the Runs list and a run's page (`startingFor`, the ONE rule). @param {string} flow @param {string} runId */
451
+ startingRun(flow, runId) { return starter.startingFor(flow, keysNow().keys, runId) !== null; },
452
+
433
453
  /** `GET /api/author/start/:startId`: the start's phase, read from its files. @param {string} id */
434
454
  startGet(id) { return starter.get(id, keysNow().keys); },
435
455
 
@@ -238,7 +238,8 @@ export function cardFromSigned({ lines, arbiter }) {
238
238
  askWait: firstWait ?? '1h',
239
239
  };
240
240
  const again = parseSignedText(cardToProse(cardFields({ ...card, flowName: 'x' })));
241
- const norm = (a) => JSON.stringify({ ...a, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
241
+ // M9 am1: the trigger is not a box on the card, and signing an Edit clears it (By hand again), so it is not part of the fidelity check
242
+ const norm = (a) => JSON.stringify({ ...a, trigger: null, asks: (a.asks ?? []).map(({ ttlSigned, ...rest }) => rest) });
242
243
  const sameLines = again.ok && JSON.stringify(again.lines) === JSON.stringify(lines);
243
244
  if (!sameLines || norm(again.arbiter) !== norm(arbiter)) return no();
244
245
  return { ok: true, card };
@@ -266,6 +266,12 @@ export function createFlowsDoor(opts) {
266
266
  return realRoot === null ? null : editBlockOf(realRoot, name);
267
267
  },
268
268
 
269
+ /** M9: the source paths the newest run of this job used, role -> path (blank = none), for a start a trigger fires. @param {string} name @param {string[]} roles */
270
+ lastSourcesOf(name, roles) {
271
+ const realRoot = realRootOrNull();
272
+ return realRoot === null ? { runId: null, sources: Object.fromEntries(roles.map((r) => [r, ''])) } : lastSources(join(realRoot, name), roles);
273
+ },
274
+
269
275
  /** `GET /api/author/flows`. */
270
276
  flows() {
271
277
  const realRoot = realRootOrNull();
@@ -34,6 +34,7 @@ import {
34
34
  } from '../flow.js';
35
35
  import { booksFresh, runLiveness } from '../liveness.js';
36
36
  import { dropUnstartedValues, writeRunValues } from '../runvalues.js';
37
+ import { TRIGGER_RECORD_FILE } from '../trigger-line.js';
37
38
  import {
38
39
  childRunning, providerKeys, readJsonFile, spawnDetached, writePidFile,
39
40
  } from './spawn.js';
@@ -106,13 +107,17 @@ export function createStarter(opts) {
106
107
  return d === null ? null : readStart(join(d, id), id, keys);
107
108
  };
108
109
 
109
- /** M6 amendment 3: the ONE rule for "a run of this flow is starting": the newest start folder of the flow in phase `starting`, or null. @param {string} flow @param {string[]} keys */
110
- function startingFor(flow, keys) {
110
+ /**
111
+ * M6 amendment 3: the ONE rule for "a run of this flow is starting": the newest start folder of the flow in phase `starting`, or null.
112
+ * With `runId`, only a start of that run (the Runs list reads a run folder as `[▶]` starting by this same rule).
113
+ * @param {string} flow @param {string[]} keys @param {string} [runId]
114
+ */
115
+ function startingFor(flow, keys, runId) {
111
116
  const sd = startsDir();
112
117
  if (sd === null) return null;
113
118
  for (const id of readdirInside(sd, '.').filter((n) => ID_RE.test(n)).sort().reverse()) {
114
119
  const v = readStart(join(sd, id), id, keys);
115
- if (v && v.flow === flow && v.phase === 'starting') return id;
120
+ if (v && v.flow === flow && (runId === undefined || v.runId === runId) && v.phase === 'starting') return id;
116
121
  }
117
122
  return null;
118
123
  }
@@ -127,12 +132,14 @@ export function createStarter(opts) {
127
132
  * `runId` '' = no typed id: the start CLAIMS the next `run-<n>` itself (claimRunId, folder created exclusively; amendment 3).
128
133
  * `values` (M4e amendment 5 item 3): the human's signed values for THIS run (the page's second click), written once into the run's own
129
134
  * folder as `signed-values.json` BEFORE the spawn; the run then uses them (`pickRunValues`). None = the flow's own.
130
- * @param {{ kind: 'run'|'sign', flow: string, runId: string, sources: {role: string, path: string}[], values?: any, pick?: {slot: string, model: string}|null }} a
135
+ * `trigger` (M9): `{kind, reason, catchUp, ...}` for a start a trigger fired (kind 'trigger'): written once into the run's own folder as `trigger.json`
136
+ * BEFORE the spawn; `appendHistory` copies it into the run's history row (the catch-up mark, am2 item 1).
137
+ * @param {{ kind: 'run'|'sign'|'trigger', flow: string, runId: string, sources: {role: string, path: string}[], values?: any, pick?: {slot: string, model: string}|null, trigger?: Record<string, any>|null }} a
131
138
  * @param {{ env: Record<string, string|undefined>, keyNames?: string[] }} loaded the keys load: its env is the child's env AND (with its key names) the scrub list
132
139
  * @returns {{ status: number, body: any }}
133
140
  */
134
141
  start({
135
- kind, flow, runId, sources, values = null, pick = null,
142
+ kind, flow, runId, sources, values = null, pick = null, trigger = null,
136
143
  }, loaded) {
137
144
  const { env } = loaded;
138
145
  const sd = startsDir();
@@ -150,17 +157,22 @@ export function createStarter(opts) {
150
157
  }
151
158
  const runDirOf = () => claimedDir ?? join(realpathSync(root), flow, 'runs', runId);
152
159
  const unclaim = () => {
153
- if (claimedDir === null && values === null) return;
160
+ if (claimedDir === null && values === null && trigger === null) return;
154
161
  dropUnstartedValues(runDirOf());
155
162
  try { rmdirSync(runDirOf()); } catch { /* not empty / gone */ }
156
163
  };
157
- if (values !== null) {
158
- // the run folder holds its signed values from before the first step: a claimed one already exists, a typed id's is made here
159
- // (exclusively: a folder that appeared meanwhile refuses)
164
+ if (values !== null || trigger !== null) {
165
+ // the run folder holds its signed values (and a triggered start's reason) from before the first step: a claimed one already exists,
166
+ // a typed id's is made here (exclusively: a folder that appeared meanwhile refuses)
160
167
  try { if (claimedDir === null) mkdirSync(runDirOf()); } catch { return { status: 400, body: { ok: false, refused: 'run-id', say: `There is already a run "${runId}" of this flow. Use a new run id.` } }; }
168
+ }
169
+ if (values !== null) {
161
170
  const w = writeRunValues(runDirOf(), { ...values, runId });
162
171
  if (!w.ok) { unclaim(); return { status: 500, body: { ok: false, refused: 'values', say: `The signed values could not be saved. ${NOTHING_SPENT}` } }; }
163
172
  }
173
+ if (trigger !== null) {
174
+ try { writeFileSync(join(runDirOf(), TRIGGER_RECORD_FILE), `${JSON.stringify(trigger)}\n`, { flag: 'wx', mode: 0o600 }); } catch { unclaim(); return { status: 500, body: { ok: false, refused: 'trigger', say: `The reason this run started could not be saved. ${NOTHING_SPENT}` } }; }
175
+ }
164
176
  const keys = providerKeys(loaded);
165
177
  // one start at a time while one is still spawning for this flow (a double click, two tabs)
166
178
  const startingId = startingFor(flow, keys);
@@ -0,0 +1,384 @@
1
+ // M9 pieces 3 and 4 (docs/wiki/the-module-ladder.md, "M9" items 1-6, am1, am2): the TRIGGER door of the panel's backend.
2
+ //
3
+ // prepare(body) POST /api/author/trigger-prepare { flow, trigger } the first click: every $0 check, signs nothing, returns the hash
4
+ // set(body) POST /api/author/trigger { flow, trigger, hash } the second click: re-signs the SAME plan with only the trigger line
5
+ // changed (the M6 replace path), then arms it
6
+ // read(flow) the one read function the cards use: the trigger, whether it is armed, the next slot, the last outcome. No words.
7
+ // fire(...) one fire's outcome, in order: busy -> monthly -> sources -> the ONE start. Every outcome is a `triggers.jsonl` row.
8
+ //
9
+ // ONE WRITER PER FIELD: `set` writes the trigger line (through `proseWithTrigger` and `writeFlow`); `armFor` writes the armed row and the
10
+ // baseline; `recordFire` / the file trigger's `poll` write the fire / ran rows BEFORE a start (a crash loses a run, never doubles one);
11
+ // `appendOutcome` writes `triggers.jsonl`. Nothing here is read from a model: the trigger is typed data in the signed arbiter block.
12
+ //
13
+ // Files, per job, under `<flowDir>/`:
14
+ // triggers.jsonl append-only history of every fire outcome (all signed triggers of the job)
15
+ // triggers/<flowSignatureHash>/ the ledgers of ONE signed trigger. A new signing (a changed trigger, an Edit) is a new hash, so a
16
+ // clock.jsonl new folder: an older trigger's rows can never carry over (a fresh folder per signature, not rows
17
+ // seen.jsonl tagged by hash: nothing to filter, nothing to forget to filter). `clock.jsonl`'s `armed` row is
18
+ // the one "this trigger was set" fact for BOTH kinds; `seen.jsonl` is the file kinds' sha ledger.
19
+ import {
20
+ appendFileSync, mkdirSync, realpathSync,
21
+ } from 'node:fs';
22
+ import { userInfo } from 'node:os';
23
+ import { dirname, isAbsolute, join } from 'node:path';
24
+
25
+ import { scrub } from '../authoring.js';
26
+ import { endRow, readHistory } from '../books.js';
27
+ import { loadCatalogue } from '../catalogue.js';
28
+ import {
29
+ FLOW_FILES, checkFlowName, listFlowNames, listRunIds, readFileInside, readFlow, resolveRunDir, writeFlow,
30
+ } from '../flow.js';
31
+ import { parseSignedText } from '../signed-text.js';
32
+ import { editClearsWords, scheduledWords } from '../summary-words.js';
33
+ import { armTrigger, nextSlot, readRows, validateSchedule } from '../trigger-clock.js';
34
+ import { checkTarget, createFileTrigger } from '../trigger-files.js';
35
+ import { readModelRecord } from '../flowmodel.js';
36
+ import { carrySetup, readSetup } from '../setup.js';
37
+ import {
38
+ proseWithTrigger, stripTrigger, triggerHash, triggerLine,
39
+ } from '../trigger-line.js';
40
+
41
+ /** @typedef {import('../trigger-line.js').Trigger} Trigger */
42
+
43
+ /** A trigger in the words a row and a run reason use: `daily 09:00`, `new-file jd = file:/home/you/inbox`. @param {Trigger} t */
44
+ const describe = (t) => triggerLine(t).replace('guardrail: trigger ', '');
45
+
46
+ export const NO_GREEN_SAY = 'This job has not had a good run yet. Run it once by hand and get it right first; then you can set when it runs. Nothing was changed.';
47
+ const HISTORY_FILE = 'triggers.jsonl';
48
+ const HASH_RE = /^[0-9a-f]{64}$/;
49
+
50
+ /** The folder holding the ledgers of ONE signed trigger. @param {string} flowDir @param {string} flowHash */
51
+ export function triggerLedgerDir(flowDir, flowHash) {
52
+ if (!HASH_RE.test(flowHash)) throw new Error('trigger ledger: the flow signature hash is not a sha256');
53
+ return join(flowDir, 'triggers', flowHash);
54
+ }
55
+
56
+ /** Every fire outcome of a job, oldest first, through the safe gateway. @param {string} flowDir @returns {any[]} */
57
+ export function readOutcomes(flowDir) {
58
+ const f = readFileInside(flowDir, HISTORY_FILE);
59
+ if (!f.ok) return [];
60
+ return f.text.split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
61
+ }
62
+
63
+ /** The ONE writer of `triggers.jsonl`: append-only, one line per fire outcome. @param {string} flowDir @param {Record<string, any>} row */
64
+ export function appendOutcome(flowDir, row) {
65
+ appendFileSync(join(flowDir, HISTORY_FILE), `${JSON.stringify(row)}\n`, { mode: 0o600 });
66
+ }
67
+
68
+ /**
69
+ * The signature hashes that are this job: the current one plus every one it is a trigger-only re-sign of (the `trigger-resign` rows `set` appends to
70
+ * setup.jsonl, followed back by `resignOf`). A real Edit writes a new setup.jsonl with no such rows, so it starts a new chain (am1).
71
+ * @param {string} flowDir @param {string} sig
72
+ */
73
+ function signingsOf(flowDir, sig) {
74
+ const out = new Set([sig]);
75
+ const s = readSetup(flowDir);
76
+ if (!s.present) return out;
77
+ for (let h = sig; ;) {
78
+ const prev = s.rows.findLast((r) => r.kind === 'trigger-resign' && r.flowHash === h)?.resignOf;
79
+ if (typeof prev !== 'string' || out.has(prev)) return out;
80
+ out.add(prev); h = prev;
81
+ }
82
+ }
83
+
84
+ /**
85
+ * M9 item 1 and 2: does this job have "one green run"? The ONE function that decides it. A passed run counts when the job it ran (its own
86
+ * `job/` copy) is the current job WITHOUT its trigger line: so changing only the trigger keeps the run (item 2), and an Edit that changes
87
+ * the steps, a guardrail or the cap does not (am1). A run from before runs kept a job copy has none to compare, so it counts only when its
88
+ * history row's signature is the job's current one (a job signed since then is not the job it ran, unless that signing only added or changed its trigger line: see signingsOf).
89
+ * @param {string} flowDir
90
+ */
91
+ export function hasGreenRunForJob(flowDir) {
92
+ const cur = {};
93
+ for (const f of FLOW_FILES) {
94
+ const r = readFileInside(flowDir, f);
95
+ if (!r.ok) return false;
96
+ cur[f] = r.text;
97
+ }
98
+ let sig;
99
+ try { sig = JSON.parse(cur['signature.json']).flow; } catch { return false; }
100
+ const key = (/** @type {string} */ prose, /** @type {string} */ decl) => `${stripTrigger(prose).trimEnd()}\n\u0000${decl}`;
101
+ const want = key(cur['prose.txt'], cur['declaration.json']);
102
+ const signings = signingsOf(flowDir, sig);
103
+ const history = readHistory(flowDir);
104
+ for (const id of listRunIds(flowDir)) {
105
+ const r = resolveRunDir(flowDir, id);
106
+ if (!r.ok) continue;
107
+ const end = endRow(history, r.runDir, id);
108
+ if (end === null || end.outcome !== 'complete') continue;
109
+ const prose = readFileInside(r.runDir, 'job/prose.txt');
110
+ const decl = readFileInside(r.runDir, 'job/declaration.json');
111
+ if (prose.ok && decl.ok) { if (key(prose.text, decl.text) === want) return true; } else if (!prose.ok && prose.missing && signings.has(end.signatureHash)) return true;
112
+ }
113
+ return false;
114
+ }
115
+
116
+ /**
117
+ * The ONE writer of "this trigger was set": the starting point (am2 item 2). Idempotent. A file kind records what is already there first
118
+ * (never runs), then the armed row, so a failure between the two leaves it unarmed and the next call finishes it. Throws, naming why, when
119
+ * the target is not usable now.
120
+ * @param {string} flowDir @param {string} flowHash @param {Trigger} trigger @param {number} now epoch ms
121
+ * @returns {{armed: boolean, already: boolean}}
122
+ */
123
+ export function armFor(flowDir, flowHash, trigger, now) {
124
+ const dir = triggerLedgerDir(flowDir, flowHash);
125
+ const clock = join(dir, 'clock.jsonl');
126
+ if (readRows(clock).some((r) => r.kind === 'armed')) return { armed: true, already: true };
127
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
128
+ if (trigger.kind === 'file-updated') createFileTrigger({ mode: 'updated', target: trigger.path, ledger: join(dir, 'seen.jsonl') }).arm();
129
+ else if (trigger.kind === 'new-file') createFileTrigger({ mode: 'new', target: trigger.folder, ledger: join(dir, 'seen.jsonl') }).arm();
130
+ armTrigger(clock, now);
131
+ return { armed: true, already: false };
132
+ }
133
+
134
+ /**
135
+ * The trigger a body asks for, checked as data: null (By hand) or exactly one of the five shapes, the role one of the job's inputs, a full
136
+ * path. Returns the typed trigger or the sentence that says what to fix.
137
+ * @param {unknown} t @param {string[]} roles
138
+ * @returns {{ok: true, trigger: Trigger|null} | {ok: false, say: string}}
139
+ */
140
+ function shapeOf(t, roles) {
141
+ if (t === null) return { ok: true, trigger: null };
142
+ if (!t || typeof t !== 'object' || Array.isArray(t)) return { ok: false, say: 'Pick when it runs from the choices. A schedule is not typed as text. Nothing was changed.' };
143
+ const o = /** @type {Record<string, unknown>} */ (t);
144
+ if (o.kind === 'file-updated' || o.kind === 'new-file') {
145
+ const where = o.kind === 'new-file' ? 'folder' : 'path';
146
+ const extra = Object.keys(o).filter((k) => !['kind', 'role', where].includes(k));
147
+ if (extra.length > 0) return { ok: false, say: `A "${o.kind}" trigger takes a kind, a role and a ${where}, not "${extra[0]}". Nothing was changed.` };
148
+ if (typeof o.role !== 'string' || !roles.includes(o.role)) return { ok: false, say: `This job has no input named "${String(o.role)}" (it takes: ${roles.join(', ') || 'none'}). Pick one of those. Nothing was changed.` };
149
+ const p = o[where];
150
+ // eslint-disable-next-line no-control-regex
151
+ if (typeof p !== 'string' || p === '' || !isAbsolute(p) || /[\x00-\x1f\x7f]/.test(p)) return { ok: false, say: `The ${where} must be a full path on one line, like /home/you/inbox. Nothing was changed.` };
152
+ return { ok: true, trigger: /** @type {Trigger} */ (o.kind === 'new-file' ? { kind: 'new-file', role: o.role, folder: p } : { kind: 'file-updated', role: o.role, path: p }) };
153
+ }
154
+ try { return { ok: true, trigger: validateSchedule(t) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was changed.` }; }
155
+ }
156
+
157
+ /**
158
+ * @param {{ root: string, flowsDoor: ReturnType<typeof import('./authorflows.js').createFlowsDoor>, starter: ReturnType<typeof import('./authorstart.js').createStarter>, loadEnv: () => any, monthlyClaim: (usd: number) => any, modelRefusal: (card: any, loaded: any) => { field: string, say: string }[], now?: () => number }} opts
159
+ */
160
+ export function createTriggerDoor(opts) {
161
+ const {
162
+ root, flowsDoor, starter, loadEnv, monthlyClaim, modelRefusal, now = Date.now,
163
+ } = opts;
164
+
165
+ const realRootOrNull = () => { try { return realpathSync(root); } catch { return null; } };
166
+
167
+ /** @param {string} realRoot @param {string} name */
168
+ function readSigned(realRoot, name) {
169
+ const cat = loadCatalogue();
170
+ if (!cat.ok) return { ok: /** @type {false} */ (false), reds: [`catalogue: ${cat.reds.join('; ')}`] };
171
+ return readFlow({ root: realRoot, name, catalogue: cat.primitives });
172
+ }
173
+
174
+ /**
175
+ * Every $0 check of a trigger change, shared by both clicks. `{ok:false, reply}` or the facts a change needs.
176
+ * @param {any} body
177
+ */
178
+ function inspect(body) {
179
+ const reply = (/** @type {number} */ status, /** @type {Record<string, any>} */ b) => ({ ok: /** @type {false} */ (false), reply: { status, body: { ok: false, ...b } } });
180
+ const realRoot = realRootOrNull();
181
+ if (realRoot === null) return reply(400, { refused: 'root', say: 'The flows folder this panel serves does not exist.' });
182
+ const flow = typeof body?.flow === 'string' ? body.flow : '';
183
+ const named = checkFlowName(flow);
184
+ if (!named.ok) return reply(400, { refused: 'flow', say: `${named.red}.` });
185
+ const read = readSigned(realRoot, flow);
186
+ if (!read.ok) return reply(400, { refused: 'flow', say: `"${flow}" is not a signed flow that passes its checks, so its trigger cannot be set. Nothing was changed.` });
187
+ const roles = (read.arbiter.sources ?? []).map((s) => s.role);
188
+ const shaped = shapeOf(body?.trigger === undefined ? 'missing' : body.trigger, roles);
189
+ if (!shaped.ok) return reply(400, { refused: 'bad-trigger', say: shaped.say });
190
+ const { trigger } = shaped;
191
+ const flowDir = join(realRoot, flow);
192
+ if (trigger !== null && !hasGreenRunForJob(flowDir)) return reply(409, { refused: 'no-green-run', say: NO_GREEN_SAY });
193
+ const blocked = flowsDoor.editBlock(flow); // the same rule Edit uses: a run starting, running or waiting at its ask
194
+ if (blocked !== null) return reply(409, { refused: 'run-live', say: `${blocked}. Nothing was changed.` });
195
+ if (trigger !== null && 'role' in trigger) {
196
+ try {
197
+ checkTarget(trigger.kind === 'new-file' ? 'new' : 'updated', trigger.kind === 'new-file' ? trigger.folder : trigger.path);
198
+ } catch (e) {
199
+ return reply(400, { refused: 'bad-trigger', say: `${/** @type {Error} */ (e).message}. Nothing was changed.` });
200
+ }
201
+ // a file that does not exist yet may arrive (checkTarget allows it), but its folder must be there: a typo is caught now, not never
202
+ if (trigger.kind === 'file-updated') {
203
+ try { realpathSync(dirname(trigger.path)); } catch { return reply(400, { refused: 'bad-trigger', say: `The folder of ${trigger.path} does not exist. Nothing was changed.` }); }
204
+ }
205
+ }
206
+ const proseNow = readFileInside(flowDir, 'prose.txt');
207
+ const declNow = readFileInside(flowDir, 'declaration.json');
208
+ if (!proseNow.ok || !declNow.ok) return reply(400, { refused: 'flow', say: `"${flow}" cannot be read. Nothing was changed.` });
209
+ const proseText = proseWithTrigger(proseNow.text, trigger);
210
+ const parsed = parseSignedText(proseText);
211
+ if (!parsed.ok) return reply(400, { refused: 'bad-trigger', say: `That trigger does not fit the signed text (${parsed.reds[0]}). Nothing was changed.` });
212
+ return {
213
+ ok: /** @type {true} */ (true), flow, read, trigger, flowDir, realRoot, proseText, declaration: JSON.parse(declNow.text),
214
+ hash: triggerHash({ flow, flowSignatureHash: read.signature.flow, trigger }),
215
+ };
216
+ }
217
+
218
+ return {
219
+ inspect,
220
+ now,
221
+
222
+ /** `POST /api/author/trigger-prepare`: the first click. Checks, signs and writes nothing. @param {any} body */
223
+ prepare(body) {
224
+ const s = inspect(body);
225
+ if (!s.ok) return s.reply;
226
+ return { status: 200, body: { ok: true, flow: s.flow, trigger: s.trigger, words: scheduledWords(s.trigger), hash: s.hash } };
227
+ },
228
+
229
+ /**
230
+ * `POST /api/author/trigger`: the second click, carrying the hash it was shown. Re-signs the SAME plan (declaration.json byte for byte,
231
+ * prose.txt with only its trigger line changed) through the M6 replace path, then arms the trigger. $0: no drafter, no run.
232
+ * @param {any} body
233
+ */
234
+ set(body) {
235
+ const s = inspect(body);
236
+ if (!s.ok) return s.reply;
237
+ if (typeof body.hash !== 'string' || body.hash !== s.hash) {
238
+ return { status: 409, body: { ok: false, refused: 'stale-hash', say: 'What you were shown is not what is on the card now (its hash differs). Nothing was signed. Look again, then sign.' } };
239
+ }
240
+ const cat = loadCatalogue();
241
+ if (!cat.ok) return { status: 500, body: { ok: false, refused: 'catalogue', say: 'The catalogue could not be read. Nothing was changed.' } };
242
+ // the setup record of how the job was made is not part of the three signed files: carry it over unchanged
243
+ const setup = readFileInside(s.flowDir, 'setup.jsonl');
244
+ const signedBy = userInfo().username;
245
+ const written = writeFlow({
246
+ root: s.realRoot, name: s.flow, proseText: s.proseText, declaration: s.declaration, signedBy, signedAt: new Date(now()).toISOString(), catalogue: cat.primitives, replaces: { flowHash: s.read.signature.flow },
247
+ });
248
+ if (!written.ok) return { status: 409, body: { ok: false, refused: 'sign-refused', say: 'The trigger was not signed. Nothing was changed.', reds: written.reds.map((r) => scrub(String(r), [])) } };
249
+ if (setup.ok) carrySetup({ flowDir: s.flowDir, oldText: setup.text, oldFlowHash: s.read.signature.flow, newFlowHash: written.signature.flow, at: new Date(now()).toISOString() }); // the record is a courtesy; the job is signed
250
+ let armed = true; let armSay = null;
251
+ if (s.trigger !== null) {
252
+ try { armFor(s.flowDir, written.signature.flow, s.trigger, now()); } catch (e) { armed = false; armSay = /** @type {Error} */ (e).message; }
253
+ }
254
+ return { status: 200, body: { ok: true, flow: s.flow, trigger: s.trigger, words: scheduledWords(s.trigger), flowHash: written.signature.flow, armed, ...(armSay === null ? {} : { say: `The trigger is signed but not armed yet: ${armSay}.` }) } };
255
+ },
256
+
257
+ /** Every signed job that has a trigger, as the scheduler needs it: `{flow, flowDir, read, trigger}`. Reads each job the way the CLI will (signature verified). */
258
+ scan() {
259
+ const realRoot = realRootOrNull();
260
+ if (realRoot === null) return [];
261
+ const jobs = [];
262
+ for (const flow of listFlowNames(realRoot)) {
263
+ const read = readSigned(realRoot, flow);
264
+ if (read.ok && read.arbiter.trigger !== null) jobs.push({ flow, flowDir: join(realRoot, flow), read, trigger: /** @type {Trigger} */ (read.arbiter.trigger) });
265
+ }
266
+ return jobs;
267
+ },
268
+
269
+ /** Arm this job's signed trigger if it is not armed yet (a crash between the sign and the arm). Idempotent; throws naming why. @param {{flowDir: string, read: any, trigger: Trigger}} job */
270
+ ensureArmed(job) {
271
+ return armFor(job.flowDir, job.read.signature.flow, job.trigger, now());
272
+ },
273
+
274
+ /** M9 am3: is a run of this job starting, running or waiting at an ask? (the same check `fire` makes first) @param {{flow: string}} job */
275
+ busy(job) {
276
+ return flowsDoor.editBlock(job.flow) !== null;
277
+ },
278
+
279
+ /** M9 am3: one row for a queued file that is not a fire (deleted / changed before its turn). @param {{flow: string, flowDir: string, trigger: Trigger}} job @param {Record<string, any>} row */
280
+ note(job, row) {
281
+ appendOutcome(job.flowDir, { at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), ...row });
282
+ },
283
+
284
+ /**
285
+ * One row in `triggers.jsonl` that is not a fire (the trigger could not be watched). @param {{flow: string, flowDir: string, trigger: Trigger}} job @param {string} why
286
+ */
287
+ refuse(job, why) {
288
+ appendOutcome(job.flowDir, {
289
+ at: new Date(now()).toISOString(), flow: job.flow, trigger: describe(job.trigger), outcome: 'refused', why,
290
+ });
291
+ },
292
+
293
+ /**
294
+ * M9 item 3-5: one fire, in this order, each outcome ONE row in `triggers.jsonl`: busy -> monthly-exhausted -> refused (an input or the keys
295
+ * are missing) -> started through the ONE start path (kind `trigger`; the reason and the catch-up mark go into the run's own folder first).
296
+ * The fire / ran ledger row was written by the caller BEFORE this, so a crash loses a run and never doubles one.
297
+ * @param {{flow: string, flowDir: string, read: any, trigger: Trigger}} job
298
+ * @param {{kind: 'clock', slot: number, catchUp: boolean, missed: number} | {kind: 'file', path: string, sha: string}} cause
299
+ * @param {{ told?: (outcome: string) => boolean, beforeStart?: () => void }} [hooks] M9 am3 (a queued file): `told(outcome)` true = this file
300
+ * already has a row for that outcome, so none is written again (the outcome is still returned); `beforeStart` runs right before the ONE
301
+ * start, once every check has passed: the scheduler writes the file's `ran` row there.
302
+ */
303
+ fire(job, cause, hooks = {}) {
304
+ const { flow, flowDir, read, trigger } = job;
305
+ const desc = describe(trigger);
306
+ const base = {
307
+ at: new Date(now()).toISOString(), flow, trigger: desc,
308
+ ...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), catchUp: cause.catchUp, missed: cause.missed } : { file: cause.path, sha: cause.sha, catchUp: false }),
309
+ };
310
+ const done = (/** @type {Record<string, any>} */ r) => { const row = /** @type {Record<string, any>} */ ({ ...base, ...r }); if (!(row.outcome !== 'started' && hooks.told?.(row.outcome))) appendOutcome(flowDir, row); return row; };
311
+ const busy = flowsDoor.editBlock(flow); // one run at a time per job: starting, running, or waiting at its ask
312
+ if (busy !== null) return done({ outcome: 'busy', say: busy });
313
+ const claim = monthlyClaim(read.arbiter.capUsd); // the same check the Run door decides on
314
+ if (claim && 'problem' in claim) return done({ outcome: 'refused', why: `${claim.problem}. Nothing spent.` });
315
+ if (claim && !claim.ok) return done({ outcome: 'monthly-exhausted', leftUsd: claim.room.leftUsd, needUsd: claim.room.needUsd, atLeast: claim.room.atLeast === true });
316
+ const roles = (read.arbiter.sources ?? []).map((x) => x.role);
317
+ const last = flowsDoor.lastSourcesOf(flow, roles).sources;
318
+ const sources = [];
319
+ for (const role of roles) {
320
+ const p = 'role' in trigger && trigger.role === role && cause.kind === 'file' ? cause.path : last[role];
321
+ if (!p) return done({ outcome: 'refused', why: `There is no earlier run of this job to take the input "${role}" from. Run it by hand once with that input. Nothing started.` });
322
+ try { sources.push({ role, path: realpathSync(p) }); } catch { return done({ outcome: 'refused', why: `The input "${role}" is not there (${p}). Nothing started.` }); }
323
+ }
324
+ const loaded = loadEnv();
325
+ if (!loaded.ok) return done({ outcome: 'refused', why: String(loaded.refusal) });
326
+ // the Run door's model check (its one `modelRefusal`), on the job's recorded model: a trigger picks no model, so a job without a record, or whose
327
+ // line is no longer ticked / priced / keyed in Settings, is refused here at $0, never started
328
+ const rec = readModelRecord(flowDir);
329
+ if (rec === null) return done({ outcome: 'refused', why: 'This job has no model recorded, so it cannot start by itself. Run it by hand once from the Chat card and pick a model. Nothing started.' });
330
+ const modelSays = modelRefusal({ provider: rec.slot, model: rec.model }, loaded);
331
+ if (modelSays.length > 0) return done({ outcome: 'refused', why: modelSays[0].say.replace(/ Nothing was spent\.$/, '. Nothing started.') });
332
+ const catchUp = base.catchUp === true;
333
+ const record = {
334
+ kind: cause.kind, trigger: desc, reason: `Started by the trigger: ${desc}${catchUp ? ' (catch-up)' : ''}`, catchUp, ...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), missed: cause.missed } : { file: cause.path, sha: cause.sha }),
335
+ };
336
+ hooks.beforeStart?.();
337
+ const started = starter.start({
338
+ kind: 'trigger', flow, runId: '', sources, trigger: record,
339
+ }, loaded);
340
+ if (started.status !== 202) return done({ outcome: 'refused', why: String(started.body.say ?? 'The run did not start.') });
341
+ return done({ outcome: 'started', runId: started.body.runId, startId: started.body.startId });
342
+ },
343
+
344
+ /**
345
+ * What a card shows of a job's trigger, as data (no words): the signed trigger, whether it is armed, the next slot (clock kinds), the last
346
+ * fire outcome. `null` when the job is not a readable signed job.
347
+ * @param {string} flow
348
+ */
349
+ read(flow) {
350
+ const realRoot = realRootOrNull();
351
+ if (realRoot === null || !checkFlowName(flow).ok) return null;
352
+ const r = readSigned(realRoot, flow);
353
+ if (!r.ok) return null;
354
+ const flowDir = join(realRoot, flow);
355
+ const { trigger } = r.arbiter;
356
+ const clock = readRows(join(triggerLedgerDir(flowDir, r.signature.flow), 'clock.jsonl'));
357
+ const armed = clock.find((x) => x.kind === 'armed');
358
+ const outcomes = readOutcomes(flowDir);
359
+ const clockKind = trigger !== null && (trigger.kind === 'daily' || trigger.kind === 'weekdays' || trigger.kind === 'weekly');
360
+ return {
361
+ flow, trigger, flowHash: r.signature.flow, armed: armed !== undefined, armedAt: armed ? armed.at : null,
362
+ nextSlotMs: clockKind && armed ? nextSlot(/** @type {any} */ (trigger), now()) : null,
363
+ lastOutcome: outcomes.length > 0 ? outcomes[outcomes.length - 1] : null,
364
+ hasGreenRun: hasGreenRunForJob(flowDir),
365
+ };
366
+ },
367
+
368
+ /**
369
+ * What the Run card's dropdown needs of one job (M9 piece 5): the typed trigger, its words, whether it is armed, and, when the job has had
370
+ * no good run, the server's refusal sentence (the page shows it and disables the dropdown; it invents no words). `editNote` is am1's
371
+ * warning, set only when the job has a trigger. `null` when the job is not a readable signed job.
372
+ * @param {string} flow
373
+ */
374
+ card(flow) {
375
+ const r = this.read(flow);
376
+ if (r === null) return null;
377
+ return {
378
+ trigger: r.trigger, words: scheduledWords(r.trigger), armed: r.armed, hasGreenRun: r.hasGreenRun,
379
+ refusal: r.hasGreenRun ? null : NO_GREEN_SAY, editNote: editClearsWords(r.trigger),
380
+ };
381
+ },
382
+ };
383
+ }
384
+