fwdloop 0.26.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/bin/fwdloop +46 -7
  2. package/package.json +2 -2
  3. package/src/authoring.js +21 -1
  4. package/src/canrun.js +23 -0
  5. package/src/config.js +18 -0
  6. package/src/declaration.js +129 -3
  7. package/src/drafter.js +38 -10
  8. package/src/flow.js +2 -1
  9. package/src/launcher.js +4 -2
  10. package/src/learnstore.js +3 -2
  11. package/src/mcp-checks.js +50 -0
  12. package/src/mcp-pick.js +33 -0
  13. package/src/mcp-sources.js +84 -0
  14. package/src/mcp-use.js +54 -0
  15. package/src/natural.js +23 -0
  16. package/src/panel/author.js +17 -1
  17. package/src/panel/authorcard.js +35 -0
  18. package/src/panel/authorflows.js +15 -6
  19. package/src/panel/authorstart.js +10 -6
  20. package/src/panel/authortrigger.js +263 -82
  21. package/src/panel/data.js +127 -9
  22. package/src/panel/index.html +945 -94
  23. package/src/panel/jobgrid.js +127 -0
  24. package/src/panel/scheduler.js +48 -6
  25. package/src/panel/server.js +33 -8
  26. package/src/panel/settings.js +119 -4
  27. package/src/panel/tickets.js +118 -0
  28. package/src/primitives.js +34 -5
  29. package/src/runner.js +129 -15
  30. package/src/schedule.js +5 -0
  31. package/src/summary-words.js +27 -7
  32. package/src/ticket-draft.js +85 -0
  33. package/src/ticket-labels.js +75 -0
  34. package/src/ticket-mcp.js +89 -0
  35. package/src/ticket-next.js +33 -0
  36. package/src/ticket-shape.js +33 -0
  37. package/src/trigger-clock.js +4 -4
  38. package/src/trigger-files.js +4 -4
  39. package/src/trigger-line.js +2 -1
  40. package/src/trigger-tickets.js +238 -0
  41. package/types/authoring.d.ts +5 -1
  42. package/types/canrun.d.ts +7 -0
  43. package/types/config.d.ts +6 -0
  44. package/types/declaration.d.ts +8 -0
  45. package/types/drafter.d.ts +552 -21
  46. package/types/mcp-checks.d.ts +8 -0
  47. package/types/mcp-pick.d.ts +23 -0
  48. package/types/mcp-sources.d.ts +51 -0
  49. package/types/mcp-use.d.ts +12 -0
  50. package/types/natural.d.ts +2 -0
  51. package/types/panel/author.d.ts +44 -0
  52. package/types/panel/authorcard.d.ts +11 -0
  53. package/types/panel/authorflows.d.ts +11 -1
  54. package/types/panel/authorstart.d.ts +3 -1
  55. package/types/panel/authortrigger.d.ts +83 -7
  56. package/types/panel/data.d.ts +78 -5
  57. package/types/panel/jobgrid.d.ts +109 -0
  58. package/types/panel/scheduler.d.ts +7 -2
  59. package/types/panel/server.d.ts +13 -2
  60. package/types/panel/settings.d.ts +3 -2
  61. package/types/panel/tickets.d.ts +103 -0
  62. package/types/primitives.d.ts +15 -2
  63. package/types/runner.d.ts +133 -75
  64. package/types/summary-words.d.ts +24 -4
  65. package/types/ticket-draft.d.ts +104 -0
  66. package/types/ticket-labels.d.ts +42 -0
  67. package/types/ticket-mcp.d.ts +57 -0
  68. package/types/ticket-next.d.ts +23 -0
  69. package/types/ticket-shape.d.ts +30 -0
  70. package/types/trigger-clock.d.ts +4 -3
  71. package/types/trigger-files.d.ts +3 -1
  72. package/types/trigger-line.d.ts +7 -0
  73. package/types/trigger-tickets.d.ts +105 -0
@@ -23,15 +23,20 @@ import { basename, dirname, isAbsolute, join } from 'node:path';
23
23
  import { flowValues, valuesHash } from '../runvalues.js';
24
24
  import { destinationRefusal, checkInputRows, runInputRows } from './authorcard.js';
25
25
  import { endRow, readHistory } from '../books.js';
26
+ import { readRunInputs } from '../runfile.js';
26
27
  import { appendRow } from '../jsonl-append.js';
27
28
  import { loadCatalogue } from '../catalogue.js';
28
29
  import { canFlowRun, willNotRunSay } from '../canrun.js';
29
30
  import {
30
31
  FLOW_FILES, checkFlowName, listFlowNames, listRunIds, planForReuse, readFileInside, readFlow, readRunJobCopy, resolveRunDir,
31
32
  } from '../flow.js';
32
- import { scheduleHead, scheduledWords } from '../summary-words.js';
33
+ import { SCHEDULE_WAITING_SAY, scheduleHead, scheduledWords } from '../summary-words.js';
33
34
  import { armTrigger, nextSlot, readRows, validateSchedule } from '../trigger-clock.js';
34
- import { checkTarget, createFileTrigger } from '../trigger-files.js';
35
+ import { checkTarget, createFileTrigger, readSeen } from '../trigger-files.js';
36
+ import { lookProblemOf } from '../trigger-tickets.js';
37
+ import { WATCHABLE, ticketListsOf } from '../ticket-shape.js';
38
+ import { LOOK_TOOL } from '../ticket-draft.js';
39
+ import { flowTypeOf } from '../declaration.js';
35
40
  import { readModelRecord } from '../flowmodel.js';
36
41
  import { pageAddressesOf, pageAddressRefusal } from '../pagefetch.js';
37
42
  import {
@@ -45,6 +50,8 @@ import { triggerHash, triggerLine } from '../trigger-line.js';
45
50
  /** 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 */
46
51
  const describe = (t) => triggerLine(t).replace('guardrail: trigger ', '');
47
52
 
53
+ /** M12: the tool a ticket schedule's look uses. M13 piece 4: it must be in the job's signed `mcp.tools` (item 9b.1), and the schedule's two clicks sign it again. */
54
+ export const TICKET_LOOK_TOOL = LOOK_TOOL;
48
55
  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.';
49
56
  const HISTORY_FILE = 'triggers.jsonl';
50
57
 
@@ -61,20 +68,20 @@ export function appendOutcome(flowDir, row) {
61
68
  }
62
69
 
63
70
  /**
64
- * 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
71
+ * M9 item 1 and 2: the runs that count as "one green run" for this job, in run-name order. THE decider: a passed run counts when the job it ran (its own
65
72
  * `job/` copy) is the job as it is now (prose and declaration, byte for byte: a schedule is its own file, so setting one never changes the job).
66
73
  * A run from before runs kept a job copy has none to compare, so it counts only when its history row's signature is the job's current one.
67
- * @param {string} flowDir
74
+ * @param {string} flowDir @returns {Generator<{runId: string, runDir: string, at: string}>}
68
75
  */
69
- export function hasGreenRunForJob(flowDir) {
76
+ function* greenRuns(flowDir) {
70
77
  const cur = {};
71
78
  for (const f of FLOW_FILES) {
72
79
  const r = readFileInside(flowDir, f);
73
- if (!r.ok) return false;
80
+ if (!r.ok) return;
74
81
  cur[f] = r.text;
75
82
  }
76
83
  let sig;
77
- try { sig = JSON.parse(cur['signature.json']).flow; } catch { return false; }
84
+ try { sig = JSON.parse(cur['signature.json']).flow; } catch { return; }
78
85
  const key = (/** @type {string} */ prose, /** @type {string} */ decl) => `${prose.trimEnd()}\n\u0000${decl}`;
79
86
  const want = key(cur['prose.txt'], cur['declaration.json']);
80
87
  const history = readHistory(flowDir);
@@ -85,16 +92,33 @@ export function hasGreenRunForJob(flowDir) {
85
92
  if (end === null || end.outcome !== 'complete') continue;
86
93
  const prose = readFileInside(r.runDir, 'job/prose.txt');
87
94
  const decl = readFileInside(r.runDir, 'job/declaration.json');
88
- if (prose.ok && decl.ok) { if (key(prose.text, decl.text) === want) return true; } else if (!prose.ok && prose.missing && end.signatureHash === sig) return true;
95
+ const at = typeof end.at === 'string' ? end.at : '';
96
+ if (prose.ok && decl.ok) { if (key(prose.text, decl.text) === want) yield { runId: id, runDir: r.runDir, at }; } else if (!prose.ok && prose.missing && end.signatureHash === sig) yield { runId: id, runDir: r.runDir, at };
89
97
  }
90
- return false;
98
+ }
99
+
100
+ /** M9 item 1 and 2: does this job have "one green run"? @param {string} flowDir */
101
+ export function hasGreenRunForJob(flowDir) {
102
+ return !greenRuns(flowDir).next().done;
103
+ }
104
+
105
+ /**
106
+ * M13 piece 5: the first green run of this job (the earliest one to end), or null. A resume that ends green counts: the history row is the run's last. The one reader of
107
+ * "which run turned the schedule on".
108
+ * @param {string} flowDir @returns {{runId: string, runDir: string, at: string}|null}
109
+ */
110
+ export function firstGreenRunFor(flowDir) {
111
+ let first = null;
112
+ for (const g of greenRuns(flowDir)) if (first === null || g.at < first.at) first = g;
113
+ return first;
91
114
  }
92
115
 
93
116
  /**
94
117
  * The ONE writer of "this schedule was set": the starting point (am2 item 2). Idempotent per signing. A file kind records what is already there first
95
118
  * (never runs; `baseline: false` = the folder is the same as the earlier signing's, whose rows were carried), then the armed row. Throws, naming why,
96
119
  * when the target is not usable now.
97
- * @param {string} flowDir @param {Schedule} schedule @param {number} now epoch ms @param {{baseline?: boolean}} [o]
120
+ * M13 piece 5: `ticketN` (the first green run's ticket number) rides the armed row of a ticket schedule, for its first look's cut.
121
+ * @param {string} flowDir @param {Schedule} schedule @param {number} now epoch ms @param {{baseline?: boolean, ticketN?: number}} [o]
98
122
  * @returns {{armed: boolean, already: boolean}}
99
123
  */
100
124
  export function armFor(flowDir, schedule, now, o = {}) {
@@ -105,10 +129,33 @@ export function armFor(flowDir, schedule, now, o = {}) {
105
129
  if (trigger.kind === 'file-updated') createFileTrigger({ mode: 'updated', target: trigger.path, ledger, sig }).arm();
106
130
  else if (trigger.kind === 'new-file') createFileTrigger({ mode: 'new', target: trigger.folder, ledger, sig }).arm();
107
131
  }
108
- armTrigger(ledger, now, sig);
132
+ armTrigger(ledger, now, sig, o.ticketN);
109
133
  return { armed: true, already: false };
110
134
  }
111
135
 
136
+ /**
137
+ * A `new-ticket` trigger filled from the SIGNED job: the list address of its ticket input, the job's server, the look's tool (one of the job's signed tools) and the fields to watch.
138
+ * Both the Run card's two clicks and the New job card's sign build it here. `{ok:false, say}` names what is wrong, and says nothing was changed.
139
+ * @param {any} read the signed job @param {{role: string, watch?: string[]}} trigger
140
+ * @returns {{ok: true, trigger: Trigger} | {ok: false, say: string}}
141
+ */
142
+ function newTicketTrigger(read, trigger) {
143
+ const no = (/** @type {string} */ say) => ({ ok: /** @type {false} */ (false), say });
144
+ // M12 piece 2 (items 8; PRD ruling "a tool counts as used if a step or the signed schedule uses it"): the look's tool is `list_issues` on the server the job names
145
+ const list = ticketListsOf(read.arbiter)[trigger.role];
146
+ if (list === undefined) return no(`The input "${trigger.role}" is not a ticket list (a GitHub issues list address), so no new ticket can start a run from it. Nothing was changed.`);
147
+ const server = read.declaration?.mcp?.server;
148
+ if (typeof server !== 'string') return no('This job names no MCP server, so the ticket list cannot be looked at. Nothing was changed.');
149
+ if (flowTypeOf(read.declaration) !== 'tickets') return no('Only a Tickets MCP job can start on a new ticket. Nothing was changed.');
150
+ // M13 piece 4 (item 9b.1): the look's tool is one of the job's signed tools, like every other tool; a job whose list lacks it cannot be scheduled by "a new ticket arrives"
151
+ const lookTool = (Array.isArray(read.declaration.mcp.tools) ? read.declaration.mcp.tools : []).find((/** @type {string} */ t) => t === TICKET_LOOK_TOOL);
152
+ if (lookTool === undefined) return no(`This job's signed tools do not include ${TICKET_LOOK_TOOL}, the tool that looks for new tickets, so a new ticket cannot start a run. Draft the job again as a Tickets MCP job. Nothing was changed.`);
153
+ // signed M12 item 7: the fields to watch come from the signed job (`ticketWatch`) unless the click itself names them; a job that names none watches nothing
154
+ const jobWatch = read.declaration?.ticketWatch;
155
+ const watch = trigger.watch ?? (Array.isArray(jobWatch) && jobWatch.length > 0 ? jobWatch : undefined);
156
+ return { ok: true, trigger: { kind: 'new-ticket', role: trigger.role, list, server, tool: lookTool, ...(watch ? { watch } : {}) } };
157
+ }
158
+
112
159
  /**
113
160
  * 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
114
161
  * path. Returns the typed trigger or the sentence that says what to fix.
@@ -129,9 +176,33 @@ function shapeOf(t, roles) {
129
176
  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.` };
130
177
  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 }) };
131
178
  }
179
+ if (o.kind === 'new-ticket') {
180
+ // M12 piece 2: the person picks the input; the list address, the job's server and the look's tool are filled from the signed job (inspect), never typed here
181
+ const extra = Object.keys(o).filter((k) => !['kind', 'role', 'watch'].includes(k));
182
+ if (extra.length > 0) return { ok: false, say: `A "new-ticket" trigger takes a kind and a role, not "${extra[0]}". Nothing was changed.` };
183
+ 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.` };
184
+ if (o.watch !== undefined && !(Array.isArray(o.watch) && o.watch.every((w) => WATCHABLE.includes(w)))) return { ok: false, say: `A ticket schedule can watch only ${WATCHABLE.join(' and ')}. Nothing was changed.` };
185
+ return { ok: true, trigger: /** @type {Trigger} */ ({ kind: 'new-ticket', role: o.role, list: '', server: '', tool: '', ...(o.watch ? { watch: o.watch } : {}) }) };
186
+ }
132
187
  try { return { ok: true, trigger: validateSchedule(t) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was changed.` }; }
133
188
  }
134
189
 
190
+ /**
191
+ * THE builder of a Schedule record (the Run card's second click and the New job card's sign both call it): the hash binds exactly what the human was shown.
192
+ * @param {{flow: string, flowSignatureHash: string, trigger: Trigger, model: Schedule['model'], destination: string|null, inputs: Schedule['inputs'], plan: Schedule['plan'], from: string|null, signedBy: string, at: number}} o
193
+ * @returns {Schedule}
194
+ */
195
+ function buildSchedule(o) {
196
+ const signedAt = new Date(o.at).toISOString();
197
+ const bound = triggerHash({
198
+ flow: o.flow, flowSignatureHash: o.flowSignatureHash, trigger: o.trigger, model: o.model, destination: o.destination, inputs: o.inputs, plan: o.plan,
199
+ });
200
+ return {
201
+ v: 1, flow: o.flow, trigger: o.trigger, flowSignatureHash: o.flowSignatureHash, bound, sig: sigOf(bound, signedAt), signedBy: o.signedBy, signedAt,
202
+ model: o.model, destination: o.destination, inputs: o.inputs, plan: o.plan, from: o.from,
203
+ };
204
+ }
205
+
135
206
  /**
136
207
  * @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
137
208
  */
@@ -165,23 +236,29 @@ export function createTriggerDoor(opts) {
165
236
  const roles = (read.arbiter.sources ?? []).map((s) => s.role);
166
237
  const shaped = shapeOf(body?.trigger === undefined ? 'missing' : body.trigger, roles);
167
238
  if (!shaped.ok) return reply(400, { refused: 'bad-trigger', say: shaped.say });
168
- const { trigger } = shaped;
239
+ let { trigger } = shaped;
240
+ if (trigger !== null && trigger.kind === 'new-ticket') {
241
+ const filled = newTicketTrigger(read, trigger);
242
+ if (!filled.ok) return reply(400, { refused: 'bad-trigger', say: filled.say });
243
+ trigger = filled.trigger;
244
+ }
169
245
  const flowDir = join(realRoot, flow);
170
246
  if (trigger !== null && !hasGreenRunForJob(flowDir)) return reply(409, { refused: 'no-green-run', say: NO_GREEN_SAY });
171
247
  // M9 am20 item 3: neither Cancel nor a new schedule is refused because a run is starting, working or waiting: a run carries on from its own copy and
172
248
  // keeps its own signed values; the next fire uses the new schedule. (A schedule never touches the job, so there is nothing for a run to collide with.)
173
- if (trigger !== null && 'role' in trigger && Object.hasOwn(pageAddressesOf(read.arbiter), trigger.role)) {
174
- return reply(400, { refused: 'bad-trigger', say: `The input "${trigger.role}" is a web page, not a file, so no file arrival can start a run from it. Nothing was changed.` }); // M10 am3
249
+ const fileTrigger = trigger !== null && (trigger.kind === 'file-updated' || trigger.kind === 'new-file') ? trigger : null;
250
+ if (fileTrigger !== null && Object.hasOwn(pageAddressesOf(read.arbiter), fileTrigger.role)) {
251
+ return reply(400, { refused: 'bad-trigger', say: `The input "${fileTrigger.role}" is a web page, not a file, so no file arrival can start a run from it. Nothing was changed.` }); // M10 am3
175
252
  }
176
- if (trigger !== null && 'role' in trigger) {
253
+ if (fileTrigger !== null) {
177
254
  try {
178
- checkTarget(trigger.kind === 'new-file' ? 'new' : 'updated', trigger.kind === 'new-file' ? trigger.folder : trigger.path);
255
+ checkTarget(fileTrigger.kind === 'new-file' ? 'new' : 'updated', fileTrigger.kind === 'new-file' ? fileTrigger.folder : fileTrigger.path);
179
256
  } catch (e) {
180
257
  return reply(400, { refused: 'bad-trigger', say: `${/** @type {Error} */ (e).message}. Nothing was changed.` });
181
258
  }
182
259
  // 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
183
- if (trigger.kind === 'file-updated') {
184
- try { realpathSync(dirname(trigger.path)); } catch { return reply(400, { refused: 'bad-trigger', say: `The folder of ${trigger.path} does not exist. Nothing was changed.` }); }
260
+ if (fileTrigger.kind === 'file-updated') {
261
+ try { realpathSync(dirname(fileTrigger.path)); } catch { return reply(400, { refused: 'bad-trigger', say: `The folder of ${fileTrigger.path} does not exist. Nothing was changed.` }); }
185
262
  }
186
263
  }
187
264
  // M6 am5 item 3: a schedule may carry the model of the run it was made from (a run field). Checked now by the Run door's own model check; the same as
@@ -266,6 +343,73 @@ export function createTriggerDoor(opts) {
266
343
  removeSchedule(flowDir);
267
344
  }
268
345
 
346
+ /**
347
+ * Every check a start from a job's schedule makes, in the ONE order, shared by `fire` and `startAnyway` (the by-hand start of a named ticket): busy -> the kept plan ->
348
+ * canFlowRun -> monthly -> the sources -> the keys -> the model. A refusal is the outcome row's fields (`{outcome, ...}`); else what the ONE start needs.
349
+ * @param {{flow: string, flowDir: string, read: any, trigger: Trigger, schedule: Schedule}} job
350
+ * @param {{kind: string, role?: string, number?: number, anyway?: boolean, path?: string}} cause
351
+ * @returns {Record<string, any>}
352
+ */
353
+ function startChecks(job, cause) {
354
+ const { flow, flowDir, read: flowRead, trigger, schedule } = job;
355
+ let read = flowRead; // the plan this start runs: the workflow's own, or (M6 am9) the kept plan of the run the schedule was set from
356
+ const busy = flowsDoor.scheduleBusy(flow); // M9 am8: one WORKING run at a time per job; a run waiting at its ask does not block
357
+ if (busy !== null) return ({ outcome: 'busy', say: busy });
358
+ // M6 am9: a schedule set from a run that kept another plan runs THAT plan; it is re-verified now, against what the second click signed
359
+ let planRun = null;
360
+ const planRec = schedule.plan;
361
+ if (planRec !== null) {
362
+ const cat = loadCatalogue();
363
+ const rr = resolveRunDir(flowDir, planRec.run);
364
+ const kept = rr.ok && cat.ok ? readRunJobCopy(rr.runDir, cat.primitives) : null;
365
+ const decl = rr.ok ? readFileInside(rr.runDir, 'job/declaration.json') : null;
366
+ const good = kept && kept.present && kept.ok && kept.signature.flow === planRec.flowHash && decl && decl.ok && createHash('sha256').update(decl.text).digest('hex') === planRec.declSha;
367
+ if (!good) return ({ outcome: 'refused', why: `The plan of ${planRec.run} is no longer the one that was signed, so nothing started. Set the schedule again.` });
368
+ read = /** @type {any} */ (kept);
369
+ planRun = planRec.run;
370
+ }
371
+ // the Run door's own `canFlowRun` (a retired check form, an unwired verb), on the plan this fire runs, in the Run door's own sentence: refused at $0, nothing started
372
+ const can = canFlowRun(read);
373
+ if (!can.ok) return ({ outcome: 'refused', why: willNotRunSay(flow, String(can.red)) });
374
+ const claim = monthlyClaim(read.arbiter.capUsd); // the same check the Run door decides on
375
+ if (claim && 'problem' in claim) return ({ outcome: 'refused', why: `${claim.problem}. Nothing spent.` });
376
+ if (claim && !claim.ok) return ({ outcome: 'monthly-exhausted', leftUsd: claim.room.leftUsd, needUsd: claim.room.needUsd, atLeast: claim.room.atLeast === true });
377
+ const roles = (read.arbiter.sources ?? []).map((x) => x.role);
378
+ // M6 am5 item 3: the scheduled run's inputs, when the schedule carries them; else the newest run's (as before). A file trigger's own role is always the arriving file.
379
+ let last = flowsDoor.lastSourcesOf(flow, roles).sources;
380
+ if (schedule.inputs !== null) last = { ...last, ...Object.fromEntries(schedule.inputs.map((r) => [r.role, r.path])) };
381
+ const sources = [];
382
+ const pages = pageAddressesOf(read.arbiter);
383
+ for (const role of roles) {
384
+ if (cause.kind === 'ticket' && cause.role === role) { sources.push({ role, path: pages[role], ticket: cause.number, ...(cause.anyway === true ? { anyway: true } : {}) }); continue; } // M12: this run's input is ONE ticket of the signed list
385
+ if (Object.hasOwn(pages, role)) { sources.push({ role, path: pages[role] }); continue; } // M10 am3: a page input is its signed address, never an earlier run's or an arriving file
386
+ const p = 'role' in trigger && trigger.role === role && cause.kind === 'file' ? cause.path : last[role];
387
+ if (!p) return ({ 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.` });
388
+ try { sources.push({ role, path: realpathSync(p) }); } catch { return ({ outcome: 'refused', why: `The input "${role}" is not there (${p}). Nothing started.` }); }
389
+ }
390
+ const loaded = loadEnv();
391
+ if (!loaded.ok) return ({ outcome: 'refused', why: String(loaded.refusal) });
392
+ // 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
393
+ // line is no longer ticked / priced / keyed in Settings, is refused here at $0, never started
394
+ const jobRec = readModelRecord(flowDir);
395
+ if (jobRec === null) return ({ 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.' });
396
+ // M6 am5 item 3: the model this schedule was signed with (a run field) wins over the job's recorded one; it is signed into the run's own values
397
+ let rec = jobRec; let values = null;
398
+ if (schedule.model !== null) rec = schedule.model;
399
+ const destination = schedule.destination;
400
+ if (destination !== null) {
401
+ const why = destinationRefusal(destination, realpathSync(root)); // the Sign & run checks, again at the moment of use
402
+ if (why !== null) return ({ outcome: 'refused', why: `${why} Nothing started.` });
403
+ }
404
+ if (rec !== jobRec || destination !== null) {
405
+ const vals = { ...flowValues(read.arbiter), ...(destination !== null ? { destination } : {}), ...(rec !== jobRec ? { model: rec } : {}) };
406
+ values = { flow, flowSignatureHash: read.signature.flow, version: 0, values: vals, hash: valuesHash({ flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values: vals }), signedBy: userInfo().username, at: new Date(now()).toISOString() };
407
+ }
408
+ const modelSays = modelRefusal({ provider: rec.slot, model: rec.model }, loaded);
409
+ if (modelSays.length > 0) return ({ outcome: 'refused', why: modelSays[0].say.replace(/ Nothing was spent\.$/, '. Nothing started.') });
410
+ return { read, planRun, sources, loaded, values, rec, jobRec };
411
+ }
412
+
269
413
  return {
270
414
  /** `POST /api/author/trigger-prepare`: the first click. Checks, signs and writes nothing. @param {any} body */
271
415
  prepare(body) {
@@ -292,12 +436,9 @@ export function createTriggerDoor(opts) {
292
436
  }
293
437
  const at = now();
294
438
  const signedAt = new Date(at).toISOString();
295
- const bound = s.hash;
296
- /** @type {Schedule} */
297
- const schedule = {
298
- v: 1, flow: s.flow, trigger: s.trigger, flowSignatureHash: s.read.signature.flow, bound, sig: sigOf(bound, signedAt), signedBy: userInfo().username, signedAt,
299
- model: s.model, destination: s.destination, inputs: s.inputs, plan: s.plan, from: s.from,
300
- };
439
+ const schedule = buildSchedule({
440
+ flow: s.flow, flowSignatureHash: s.read.signature.flow, trigger: s.trigger, model: s.model, destination: s.destination, inputs: s.inputs, plan: s.plan, from: s.from, signedBy: userInfo().username, at,
441
+ });
301
442
  const keep = cur !== null && sameTarget(cur.trigger, s.trigger);
302
443
  try {
303
444
  if (cur !== null && keep) carryQueue(s.flowDir, cur.sig, schedule.sig);
@@ -330,6 +471,35 @@ export function createTriggerDoor(opts) {
330
471
  return jobs;
331
472
  },
332
473
 
474
+ /**
475
+ * M13 am3: `Run it anyway` on a skipped ticket while the job's ticket schedule is OFF (signed, waiting for its first green run): start that ticket's run at once, by hand
476
+ * (kind `run`, the job's normal cap), after the same checks `fire` makes (`startChecks`, the one function). `null` = not this door's case (no ticket schedule, or it is
477
+ * armed: the queue takes it, M12). Else `{ok, say}`; a refusal starts nothing and spends $0. It writes no ledger row: a skipped run never arms, a green one does (the existing path).
478
+ * @param {{flow: string, number: number}} a
479
+ * @returns {{ok: boolean, say: string} | null}
480
+ */
481
+ startAnyway({ flow, number }) {
482
+ const realRoot = realRootOrNull();
483
+ if (realRoot === null || !checkFlowName(flow).ok) return null;
484
+ const flowDir = join(realRoot, flow);
485
+ if (readSchedule(flowDir) === null) return null;
486
+ const read = readSigned(realRoot, flow);
487
+ if (!read.ok) return null;
488
+ const schedule = liveSchedule(flowDir, read.signature.flow);
489
+ if (schedule === null || schedule.trigger.kind !== 'new-ticket' || isArmed(flowDir, schedule.sig)) return null;
490
+ const trigger = schedule.trigger;
491
+ const prep = startChecks({ flow, flowDir, read, trigger, schedule }, { kind: 'ticket', role: trigger.role, number, anyway: true });
492
+ if ('outcome' in prep) {
493
+ const say = prep.outcome === 'busy' ? `${prep.say} Nothing started.`
494
+ : prep.outcome === 'monthly-exhausted' ? 'This month\'s limit has no room for this job\'s cap. Nothing started.'
495
+ : String(prep.why);
496
+ return { ok: false, say };
497
+ }
498
+ const started = starter.start({ kind: 'run', flow, runId: '', sources: prep.sources, values: prep.values, planOf: prep.planRun }, prep.loaded);
499
+ if (started.status !== 202) return { ok: false, say: String(started.body.say ?? 'The run did not start. Nothing started.') };
500
+ return { ok: true, say: `Ticket #${number} started now; the schedule is still off until a green run.` };
501
+ },
502
+
333
503
  /** A schedule whose job was Edited since (M9 am1: By hand again) is cancelled the way Cancel does it, once. Called at the top of every scheduler tick. */
334
504
  retireStale() {
335
505
  const realRoot = realRootOrNull();
@@ -343,6 +513,60 @@ export function createTriggerDoor(opts) {
343
513
  }
344
514
  },
345
515
 
516
+ /**
517
+ * M13 piece 5 (signed item 7), the $0 check of the New job card's Schedule row, before anything is signed: the trigger it becomes, built from the plan that is about to be
518
+ * signed (`arbiter` and `declaration` of the draft). Every day at HH:MM is the card's own data; a new ticket is filled from the plan (one ticket-list input, the job's
519
+ * server and signed look tool). `{ok:false, say}` names what is wrong. Writes nothing.
520
+ * @param {any} spec the card's `schedule` @param {{arbiter: any, declaration: any}} plan
521
+ * @returns {{ok: true, trigger: Trigger} | {ok: false, say: string}}
522
+ */
523
+ cardSchedule(spec, plan) {
524
+ if (spec.kind === 'new-ticket') {
525
+ const roles = Object.keys(ticketListsOf(plan.arbiter));
526
+ if (roles.length !== 1) return { ok: false, say: 'When a new ticket arrives needs exactly one ticket list in Inputs. Nothing was signed.' };
527
+ return newTicketTrigger(plan, { role: roles[0] });
528
+ }
529
+ try { return { ok: true, trigger: validateSchedule(spec) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was signed.` }; }
530
+ },
531
+
532
+ /**
533
+ * M13 piece 5 (signed item 7): the New job card's sign writes `schedule.json` for the job it just signed, in the same sign action. OFF: no `armed` row. The one turn-on is
534
+ * `armWaiting` (a green run); `from` = the run the sign started. The job and its signature are not touched. @param {{flow: string, flowSignatureHash: string, trigger: Trigger, from: string|null, signedBy: string}} o
535
+ */
536
+ signSchedule(o) {
537
+ const realRoot = realRootOrNull();
538
+ if (realRoot === null) return;
539
+ writeSchedule(join(realRoot, o.flow), buildSchedule({
540
+ flow: o.flow, flowSignatureHash: o.flowSignatureHash, trigger: o.trigger, model: null, destination: null, inputs: null, plan: null, from: o.from, signedBy: o.signedBy, at: now(),
541
+ }));
542
+ },
543
+
544
+ /**
545
+ * M13 piece 5 (signed item 7): THE turn-on. A schedule signed with the job is off until the job's first green run (`firstGreenRunFor`: a resume that ends green counts, a red
546
+ * run does not); the panel's next check then writes its one `armed` row through `armFor`. A ticket schedule keeps the ticket number that run read (`ticketN`), so its first
547
+ * look baselines only tickets up to it and a ticket that came in during the wait still runs (F114f). Called at the top of every scheduler tick; idempotent.
548
+ */
549
+ armWaiting() {
550
+ const realRoot = realRootOrNull();
551
+ if (realRoot === null) return;
552
+ for (const flow of listFlowNames(realRoot)) {
553
+ const flowDir = join(realRoot, flow);
554
+ const sc = readSchedule(flowDir);
555
+ if (sc === null || isArmed(flowDir, sc.sig)) continue;
556
+ const read = readSigned(realRoot, flow);
557
+ if (!read.ok || sc.flowSignatureHash !== read.signature.flow) continue; // an Edited job's schedule is retired, not turned on
558
+ const green = firstGreenRunFor(flowDir);
559
+ if (green === null) continue;
560
+ let ticketN;
561
+ if (sc.trigger.kind === 'new-ticket') {
562
+ const got = readRunInputs(green.runDir);
563
+ const n = got.ok ? got.entries.find((e) => Number.isInteger(e?.ticket?.number))?.ticket.number : undefined;
564
+ if (Number.isInteger(n)) ticketN = n;
565
+ }
566
+ try { armFor(flowDir, sc, now(), { ticketN }); } catch { /* the target is not usable now; tried again next tick */ }
567
+ }
568
+ },
569
+
346
570
  /** M9 am3/am8: is a run of this job starting or still working? A run waiting at its ask is not busy. (the same check `fire` makes first) @param {{flow: string}} job */
347
571
  busy(job) {
348
572
  return flowsDoor.scheduleBusy(job.flow) !== null;
@@ -367,7 +591,7 @@ export function createTriggerDoor(opts) {
367
591
  * 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).
368
592
  * The fire / ran ledger row was written by the caller BEFORE this, so a crash loses a run and never doubles one.
369
593
  * @param {{flow: string, flowDir: string, read: any, trigger: Trigger, schedule: Schedule}} job
370
- * @param {{kind: 'clock', slot: number, catchUp: boolean, missed: number} | {kind: 'file', path: string, sha: string}} cause
594
+ * @param {{kind: 'clock', slot: number, catchUp: boolean, missed: number} | {kind: 'file', path: string, sha: string} | {kind: 'ticket', number: number, sha: string, role: string, list: string, why?: string, anyway?: boolean}} cause
371
595
  * @param {{ told?: (row: Record<string, any>) => boolean, beforeStart?: () => void, holdIfCannotStart?: boolean }} [hooks] M9 am3 (a queued file): `told(row)` true = this file
372
596
  * already has a row for that outcome and reason (`why`), so none is written again (the outcome is still returned); `beforeStart` runs right before the ONE
373
597
  * start, once every check has passed: the scheduler writes the file's `ran` row there. `holdIfCannotStart` (a queued file, M9 am17): the starter's `canStart` is asked first, and a no writes nothing
@@ -381,65 +605,15 @@ export function createTriggerDoor(opts) {
381
605
  const desc = describe(trigger);
382
606
  const base = {
383
607
  at: new Date(now()).toISOString(), flow, trigger: desc, sig: schedule.sig,
384
- ...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), catchUp: cause.catchUp, missed: cause.missed } : { file: cause.path, sha: cause.sha, catchUp: false }),
608
+ ...(cause.kind === 'clock' ? { slot: new Date(cause.slot).toISOString(), catchUp: cause.catchUp, missed: cause.missed } : cause.kind === 'ticket' ? { ticket: cause.number, sha: cause.sha, catchUp: false } : { file: cause.path, sha: cause.sha, catchUp: false }),
385
609
  };
386
610
  const done = (/** @type {Record<string, any>} */ r) => { const row = /** @type {Record<string, any>} */ ({ ...base, ...r }); if (!(row.outcome !== 'started' && hooks.told?.(row))) appendOutcome(flowDir, row); return row; };
387
- const busy = flowsDoor.scheduleBusy(flow); // M9 am8: one WORKING run at a time per job; a run waiting at its ask does not block
388
- if (busy !== null) return done({ outcome: 'busy', say: busy });
389
- // M6 am9: a schedule set from a run that kept another plan runs THAT plan; it is re-verified now, against what the second click signed
390
- let planRun = null;
391
- const planRec = schedule.plan;
392
- if (planRec !== null) {
393
- const cat = loadCatalogue();
394
- const rr = resolveRunDir(flowDir, planRec.run);
395
- const kept = rr.ok && cat.ok ? readRunJobCopy(rr.runDir, cat.primitives) : null;
396
- const decl = rr.ok ? readFileInside(rr.runDir, 'job/declaration.json') : null;
397
- const good = kept && kept.present && kept.ok && kept.signature.flow === planRec.flowHash && decl && decl.ok && createHash('sha256').update(decl.text).digest('hex') === planRec.declSha;
398
- if (!good) return done({ outcome: 'refused', why: `The plan of ${planRec.run} is no longer the one that was signed, so nothing started. Set the schedule again.` });
399
- read = /** @type {any} */ (kept);
400
- planRun = planRec.run;
401
- }
402
- // the Run door's own `canFlowRun` (a retired check form, an unwired verb), on the plan this fire runs, in the Run door's own sentence: refused at $0, nothing started
403
- const can = canFlowRun(read);
404
- if (!can.ok) return done({ outcome: 'refused', why: willNotRunSay(flow, String(can.red)) });
405
- const claim = monthlyClaim(read.arbiter.capUsd); // the same check the Run door decides on
406
- if (claim && 'problem' in claim) return done({ outcome: 'refused', why: `${claim.problem}. Nothing spent.` });
407
- if (claim && !claim.ok) return done({ outcome: 'monthly-exhausted', leftUsd: claim.room.leftUsd, needUsd: claim.room.needUsd, atLeast: claim.room.atLeast === true });
408
- const roles = (read.arbiter.sources ?? []).map((x) => x.role);
409
- // M6 am5 item 3: the scheduled run's inputs, when the schedule carries them; else the newest run's (as before). A file trigger's own role is always the arriving file.
410
- let last = flowsDoor.lastSourcesOf(flow, roles).sources;
411
- if (schedule.inputs !== null) last = { ...last, ...Object.fromEntries(schedule.inputs.map((r) => [r.role, r.path])) };
412
- const sources = [];
413
- const pages = pageAddressesOf(read.arbiter);
414
- for (const role of roles) {
415
- if (Object.hasOwn(pages, role)) { sources.push({ role, path: pages[role] }); continue; } // M10 am3: a page input is its signed address, never an earlier run's or an arriving file
416
- const p = 'role' in trigger && trigger.role === role && cause.kind === 'file' ? cause.path : last[role];
417
- 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.` });
418
- try { sources.push({ role, path: realpathSync(p) }); } catch { return done({ outcome: 'refused', why: `The input "${role}" is not there (${p}). Nothing started.` }); }
419
- }
420
- const loaded = loadEnv();
421
- if (!loaded.ok) return done({ outcome: 'refused', why: String(loaded.refusal) });
422
- // 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
423
- // line is no longer ticked / priced / keyed in Settings, is refused here at $0, never started
424
- const jobRec = readModelRecord(flowDir);
425
- if (jobRec === 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.' });
426
- // M6 am5 item 3: the model this schedule was signed with (a run field) wins over the job's recorded one; it is signed into the run's own values
427
- let rec = jobRec; let values = null;
428
- if (schedule.model !== null) rec = schedule.model;
429
- const destination = schedule.destination;
430
- if (destination !== null) {
431
- const why = destinationRefusal(destination, realpathSync(root)); // the Sign & run checks, again at the moment of use
432
- if (why !== null) return done({ outcome: 'refused', why: `${why} Nothing started.` });
433
- }
434
- if (rec !== jobRec || destination !== null) {
435
- const vals = { ...flowValues(read.arbiter), ...(destination !== null ? { destination } : {}), ...(rec !== jobRec ? { model: rec } : {}) };
436
- values = { flow, flowSignatureHash: read.signature.flow, version: 0, values: vals, hash: valuesHash({ flow, flowSignatureHash: read.signature.flow, runId: null, version: 0, values: vals }), signedBy: userInfo().username, at: new Date(now()).toISOString() };
437
- }
438
- const modelSays = modelRefusal({ provider: rec.slot, model: rec.model }, loaded);
439
- if (modelSays.length > 0) return done({ outcome: 'refused', why: modelSays[0].say.replace(/ Nothing was spent\.$/, '. Nothing started.') });
611
+ const prep = startChecks(job, cause);
612
+ if ('outcome' in prep) return done(prep);
613
+ read = prep.read; const { planRun, sources, loaded, values } = prep;
440
614
  const catchUp = base.catchUp === true;
441
615
  const record = {
442
- 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 }),
616
+ 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 } : cause.kind === 'ticket' ? { ticket: cause.number, sha: cause.sha, ...(cause.why ? { why: cause.why } : {}) } : { file: cause.path, sha: cause.sha }),
443
617
  // M9 am6: typed facts for the run's Job tab and Audit (their words are built from these, in src/summary-words.js, never here)
444
618
  triggerKind: trigger.kind, words: scheduleHead(trigger), at: base.at, ...(cause.kind === 'clock' ? { lateMin: Math.max(0, Math.round((now() - cause.slot) / 60_000)) } : {}),
445
619
  sig: schedule.sig, ...(schedule.from ? { fromRun: schedule.from } : {}),
@@ -468,12 +642,17 @@ export function createTriggerDoor(opts) {
468
642
  const trigger = sc === null ? null : sc.trigger;
469
643
  const armedRow = sc === null ? undefined : readRows(ledgerOf(flowDir), sc.sig).find((x) => x.kind === 'armed');
470
644
  const outcomes = sc === null ? [] : readOutcomes(flowDir).filter((o) => o.sig === sc.sig);
645
+ const hasGreenRun = hasGreenRunForJob(flowDir);
471
646
  const clockKind = trigger !== null && (trigger.kind === 'daily' || trigger.kind === 'weekdays' || trigger.kind === 'weekly');
472
647
  return {
473
648
  flow, trigger, flowHash: r.signature.flow, sig: sc === null ? null : sc.sig, armed: armedRow !== undefined, armedAt: armedRow ? armedRow.at : null,
474
649
  nextSlotMs: clockKind && armedRow ? nextSlot(/** @type {any} */ (trigger), now()) : null,
475
650
  lastOutcome: outcomes.length > 0 ? outcomes[outcomes.length - 1] : null,
476
- hasGreenRun: hasGreenRunForJob(flowDir),
651
+ hasGreenRun,
652
+ // M13 item 9b.3: the cause when the newest look of a ticket schedule could not read (pass locked, a server error), else null
653
+ lookProblem: sc !== null && trigger !== null && trigger.kind === 'new-ticket' ? lookProblemOf(readSeen(ledgerOf(flowDir), sc.sig)) : null,
654
+ // M13 piece 5: signed with the job and still off, because no run has been green yet (a green run not yet turned on by the next check is not waiting for one)
655
+ waiting: sc !== null && armedRow === undefined && !hasGreenRun,
477
656
  };
478
657
  },
479
658
 
@@ -515,7 +694,9 @@ export function createTriggerDoor(opts) {
515
694
  if (r === null) return null;
516
695
  return {
517
696
  trigger: r.trigger, words: scheduledWords(r.trigger), armed: r.armed, hasGreenRun: r.hasGreenRun,
518
- refusal: r.hasGreenRun ? null : NO_GREEN_SAY,
697
+ // M13 piece 5: a schedule signed with the job waits for a green run; the card can still Cancel it, and says so in the signed grey words
698
+ refusal: r.hasGreenRun || r.waiting ? null : NO_GREEN_SAY,
699
+ ...(r.waiting ? { waitingSay: SCHEDULE_WAITING_SAY } : {}),
519
700
  };
520
701
  },
521
702
  };