fwdloop 0.38.0 → 0.40.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 (129) hide show
  1. package/README.md +6 -9
  2. package/bin/fwdloop +21 -19
  3. package/package.json +1 -1
  4. package/src/ask.js +70 -148
  5. package/src/audit-fold.js +6 -5
  6. package/src/auditchecks.js +6 -4
  7. package/src/authoring.js +32 -60
  8. package/src/blockasks.js +2 -1
  9. package/src/blockassemble.js +15 -3
  10. package/src/blockdraft.js +2 -2
  11. package/src/blockpick.js +42 -16
  12. package/src/books.js +237 -12
  13. package/src/checkblock.js +24 -44
  14. package/src/checklistsign.js +25 -3
  15. package/src/checklook.js +3 -1
  16. package/src/checkpick.js +6 -77
  17. package/src/cited-source.js +4 -4
  18. package/src/citedcheck.js +6 -11
  19. package/src/citedwords.js +9 -8
  20. package/src/closers.js +9 -6
  21. package/src/declaration.js +14 -49
  22. package/src/diary.js +23 -1
  23. package/src/draft-steps.js +11 -1
  24. package/src/drafter.js +18 -12
  25. package/src/draftfiles.js +127 -0
  26. package/src/draftspend.js +165 -17
  27. package/src/flow.js +42 -87
  28. package/src/flowmodel.js +1 -1
  29. package/src/index.js +3 -2
  30. package/src/inside.js +106 -0
  31. package/src/jsonl-append.js +33 -1
  32. package/src/learn.js +1 -1
  33. package/src/learnstore.js +20 -22
  34. package/src/line-checks.js +1 -1
  35. package/src/liveness.js +3 -0
  36. package/src/mcp-use.js +8 -9
  37. package/src/memo.js +13 -16
  38. package/src/model-step.js +2 -2
  39. package/src/page-words.js +8 -0
  40. package/src/pageask.js +8 -3
  41. package/src/pagebits.js +8 -1
  42. package/src/pagedropwords.js +1 -1
  43. package/src/pagerules.js +6 -3
  44. package/src/panel/author.js +99 -75
  45. package/src/panel/authorcard.js +21 -8
  46. package/src/panel/authorflows.js +3 -3
  47. package/src/panel/authorresume.js +3 -3
  48. package/src/panel/authorstart.js +15 -16
  49. package/src/panel/authortrigger.js +43 -70
  50. package/src/panel/data.js +186 -188
  51. package/src/panel/index.html +139 -115
  52. package/src/panel/jobgrid.js +3 -7
  53. package/src/panel/result.js +7 -10
  54. package/src/panel/resume.js +4 -3
  55. package/src/panel/scheduler.js +9 -9
  56. package/src/panel/server.js +8 -4
  57. package/src/panel/spawn.js +22 -11
  58. package/src/panel/tickets.js +2 -2
  59. package/src/pickrecord.js +51 -31
  60. package/src/placerule.js +3 -4
  61. package/src/plain-checks.js +1 -1
  62. package/src/planrebuild.js +19 -19
  63. package/src/primitives.js +1 -1
  64. package/src/provider.js +1 -1
  65. package/src/reasons.js +25 -0
  66. package/src/runfile.js +26 -2
  67. package/src/runner.js +57 -105
  68. package/src/runvalues.js +47 -24
  69. package/src/schedule-choices.js +41 -0
  70. package/src/schedule-shape.js +39 -0
  71. package/src/schedule.js +9 -8
  72. package/src/setup.js +20 -36
  73. package/src/shaperows.js +2 -2
  74. package/src/sheetblock.js +2 -2
  75. package/src/sheetbuild.js +5 -5
  76. package/src/sheetrun.js +4 -5
  77. package/src/summary-words.js +2 -1
  78. package/src/thinking.js +5 -2
  79. package/src/ticketrows.js +7 -28
  80. package/src/trigger-clock.js +9 -23
  81. package/src/trigger-files.js +30 -22
  82. package/src/trigger-tickets.js +15 -14
  83. package/src/try-checks.js +2 -1
  84. package/src/types.js +2 -0
  85. package/types/ask.d.ts +25 -20
  86. package/types/authoring.d.ts +7 -42
  87. package/types/blockpick.d.ts +1 -1
  88. package/types/books.d.ts +380 -4
  89. package/types/checkblock.d.ts +1 -23
  90. package/types/checklist.d.ts +3 -3
  91. package/types/checklistsign.d.ts +7 -0
  92. package/types/checkpick.d.ts +0 -21
  93. package/types/citedwords.d.ts +7 -4
  94. package/types/closers.d.ts +1 -0
  95. package/types/declaration.d.ts +4 -14
  96. package/types/diary.d.ts +14 -1
  97. package/types/draft-steps.d.ts +7 -0
  98. package/types/drafter.d.ts +1 -1
  99. package/types/draftfiles.d.ts +89 -0
  100. package/types/draftspend.d.ts +74 -0
  101. package/types/flow.d.ts +32 -54
  102. package/types/index.d.ts +3 -3
  103. package/types/inside.d.ts +71 -0
  104. package/types/jsonl-append.d.ts +20 -0
  105. package/types/learnstore.d.ts +0 -2
  106. package/types/liveness.d.ts +1 -0
  107. package/types/page-words.d.ts +6 -0
  108. package/types/pageask.d.ts +2 -0
  109. package/types/pagebits.d.ts +3 -0
  110. package/types/pagerules.d.ts +1 -0
  111. package/types/panel/author.d.ts +7 -3
  112. package/types/panel/authorcard.d.ts +0 -6
  113. package/types/panel/authorflows.d.ts +4 -4
  114. package/types/panel/authortrigger.d.ts +16 -2
  115. package/types/panel/data.d.ts +50 -16
  116. package/types/panel/spawn.d.ts +18 -2
  117. package/types/pickrecord.d.ts +29 -0
  118. package/types/reasons.d.ts +23 -0
  119. package/types/runfile.d.ts +14 -0
  120. package/types/runner.d.ts +6 -38
  121. package/types/runvalues.d.ts +17 -2
  122. package/types/schedule-choices.d.ts +9 -0
  123. package/types/schedule-shape.d.ts +15 -0
  124. package/types/sheetbuild.d.ts +1 -1
  125. package/types/thinking.d.ts +1 -0
  126. package/types/ticketrows.d.ts +0 -9
  127. package/types/trigger-clock.d.ts +3 -2
  128. package/types/trigger-files.d.ts +15 -4
  129. package/types/types.d.ts +8 -0
@@ -28,23 +28,26 @@ import { dirname, join } from 'node:path';
28
28
  import { fileURLToPath } from 'node:url';
29
29
 
30
30
  import { loadCatalogue } from '../catalogue.js';
31
- import { scrub } from '../authoring.js';
32
- import { readHistory, readPidRows } from '../books.js';
33
- import {
34
- PANEL_STARTS_DIR, checkRunId, claimRunId, freeRunId, readFileInside, readdirInside, resolveRunDir, runOwnsPlan, copyRunPlan, RUN_PLAN_MARKER,
35
- } from '../flow.js';
31
+ import { scrub } from '../draftfiles.js';
32
+ import { LOG_TAIL_CHARS } from '../draft-steps.js';
33
+ import { endRow, haltFileExists, readHistory, processStarted } from '../books.js';
34
+ import { PANEL_STARTS_DIR, checkRunId, claimRunId, freeRunId, readJsonFile, resolveRunDir, runOwnsPlan, copyRunPlan, RUN_PLAN_MARKER } from '../flow.js';
35
+ import { readFileInside, readdirInside } from '../inside.js';
36
36
  import { booksFresh, runLiveness } from '../liveness.js';
37
37
  import { dropUnstartedValues, writeRunValues } from '../runvalues.js';
38
38
  import { TRIGGER_RECORD_FILE } from '../trigger-line.js';
39
39
  import {
40
- childRunning, providerKeys, readJsonFile, spawnDetached, writePidFile,
40
+ childRunning, providerKeys, spawnDetached, writePidFile,
41
41
  } from './spawn.js';
42
42
 
43
43
  const HERE = dirname(fileURLToPath(import.meta.url));
44
44
  const BIN = join(HERE, '..', '..', 'bin', 'fwdloop');
45
45
  const ID_RE = /^s-[0-9a-z]{10}-[0-9a-f]{4}$/;
46
46
  const newId = () => `s-${Date.now().toString(36).padStart(10, '0')}-${randomBytes(2).toString('hex')}`;
47
- const LOG_TAIL_CHARS = 1500;
47
+ /** the one writer of a start folder's `start.json`: the caller's fields, then when the start was made @param {string} dir @param {Record<string, any>} rec */
48
+ function writeStartRecord(dir, rec) {
49
+ writeFileSync(join(dir, 'start.json'), `${JSON.stringify({ ...rec, startedAt: new Date().toISOString() }, null, 2)}\n`, { mode: 0o600 });
50
+ }
48
51
  const NOTHING_SPENT = 'Nothing spent.';
49
52
  const ENDED_SAY = `The run process ended before it started. ${NOTHING_SPENT}`;
50
53
 
@@ -92,14 +95,14 @@ export function createStarter(opts) {
92
95
  // A Resume (M4e amendment 4): the run already has book rows from its first leg, so "took over" is read from the halt record
93
96
  // (`halt.json`), which only the continuing process consumes — still there means the child has not taken the run yet.
94
97
  if (st.kind === 'resume') {
95
- const waiting = readFileInside(resolved.runDir, 'halt.json').ok;
98
+ const waiting = haltFileExists(resolved.runDir);
96
99
  if (!waiting) return { ...base, phase: 'started', state: carriedOn() };
97
100
  if (alive) return { ...base, phase: 'starting' };
98
- } else if (readPidRows(resolved.runDir).length > 0) {
101
+ } else if (processStarted(resolved.runDir)) {
99
102
  return { ...base, phase: 'started', state: carriedOn() };
100
103
  } else if (alive) return { ...base, phase: 'starting' };
101
104
  // a SKIPPED run (hamr 2026-10-30) ends before its first pid row, but its history row is a real ending: a grey one, never a refusal
102
- if (readHistory(flowDir).some((h) => h.runId === st.runId && h.outcome === 'skipped')) return { ...base, phase: 'started', state: 'ended' };
105
+ if (endRow(readHistory(flowDir), resolved.runDir, st.runId)?.outcome === 'skipped') return { ...base, phase: 'started', state: 'ended' };
103
106
  const log = readFileInside(dir, 'child.log');
104
107
  const tail = log.ok ? scrub(log.text, keys).trim().slice(-LOG_TAIL_CHARS).replace(/^fwdloop: /, '') : '';
105
108
  const say = tail === '' ? ENDED_SAY : (tail.includes(NOTHING_SPENT) ? tail : `${tail}\n${NOTHING_SPENT}`);
@@ -230,9 +233,7 @@ export function createStarter(opts) {
230
233
  const dir = join(sd, id);
231
234
  mkdirSync(sd, { recursive: true, mode: 0o700 });
232
235
  mkdirSync(dir, { mode: 0o700 });
233
- writeFileSync(join(dir, 'start.json'), `${JSON.stringify({
234
- kind, flow, runId, sources, startedAt: new Date().toISOString(),
235
- }, null, 2)}\n`, { mode: 0o600 });
236
+ writeStartRecord(dir, { kind, flow, runId, sources });
236
237
  // M12: `--ticket N` (the one ticket of the list this run reads) follows the sources
237
238
  const argv = ['run', flow, '--root', realpathSync(root), ...sources.flatMap((s) => ['--source', `${s.role}=${s.path}`]), ...sources.flatMap((s) => (s.ticket === undefined ? [] : ['--ticket', String(s.ticket), ...(s.anyway === true ? ['--anyway'] : [])])), '--run-id', runId, ...(pick ? ['--model', pick.model, '--provider', pick.slot] : [])]; // M4d am7b: a flow with no record runs with the model picked in Chat
238
239
  let child;
@@ -267,9 +268,7 @@ export function createStarter(opts) {
267
268
  const dir = join(sd, id);
268
269
  mkdirSync(sd, { recursive: true, mode: 0o700 });
269
270
  mkdirSync(dir, { mode: 0o700 });
270
- writeFileSync(join(dir, 'start.json'), `${JSON.stringify({
271
- kind: 'resume', flow, runId, version, sources: [], startedAt: new Date().toISOString(),
272
- }, null, 2)}\n`, { mode: 0o600 });
271
+ writeStartRecord(dir, { kind: 'resume', flow, runId, version, sources: [] });
273
272
  let child;
274
273
  try {
275
274
  child = spawnDetached({
@@ -22,17 +22,17 @@ import { basename, dirname, isAbsolute, join } from 'node:path';
22
22
 
23
23
  import { flowValues, valuesHash } from '../runvalues.js';
24
24
  import { destinationRefusal, checkInputRows, runInputRows } from './authorcard.js';
25
- import { endRow, readHistory } from '../books.js';
25
+ import { endRow, readHistory, isGoodEnding } from '../books.js';
26
26
  import { readRunInputs } from '../runfile.js';
27
- import { appendRow } from '../jsonl-append.js';
27
+ import { appendRow, parseJsonl, readTriggerLedger } from '../jsonl-append.js';
28
28
  import { loadCatalogue } from '../catalogue.js';
29
29
  import { canFlowRun, willNotRunSay } from '../canrun.js';
30
- import {
31
- FLOW_FILES, checkFlowName, listFlowNames, listRunIds, planForReuse, readFileInside, readFlow, readRunJobCopy, resolveRunDir,
32
- } from '../flow.js';
30
+ import { FLOW_FILES, checkFlowName, listFlowNames, listRunIds, planForReuse, sameJob, readFlow, readRunJobCopy, resolveRunDir, signedHashOf } from '../flow.js';
31
+ import { readFileInside } from '../inside.js';
33
32
  import { SCHEDULE_WAITING_SAY, scheduleHead, scheduledWords } from '../summary-words.js';
34
- import { armTrigger, nextSlot, readRows, validateSchedule } from '../trigger-clock.js';
35
- import { checkTarget, createFileTrigger, readSeen } from '../trigger-files.js';
33
+ import { armTrigger, isClockKind, nextSlot, validateSchedule } from '../trigger-clock.js';
34
+ import { createFileTrigger, fileTriggerWhy, isFileKind } from '../trigger-files.js';
35
+ import { shapeOf } from '../schedule-shape.js';
36
36
  import { lookProblemOf } from '../trigger-tickets.js';
37
37
  import { WATCHABLE, ticketListsOf } from '../ticket-shape.js';
38
38
  import { LOOK_TOOL } from '../ticket-draft.js';
@@ -46,6 +46,7 @@ import { triggerHash, triggerLine } from '../trigger-line.js';
46
46
 
47
47
  /** @typedef {import('../trigger-line.js').Trigger} Trigger */
48
48
  /** @typedef {import('../schedule.js').Schedule} Schedule */
49
+ /** @typedef {Extract<Trigger, {kind: 'file-updated' | 'new-file'}>} FileTrigger */
49
50
 
50
51
  /** 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 */
51
52
  const describe = (t) => triggerLine(t).replace('guardrail: trigger ', '');
@@ -59,7 +60,7 @@ const HISTORY_FILE = 'triggers.jsonl';
59
60
  export function readOutcomes(flowDir) {
60
61
  const f = readFileInside(flowDir, HISTORY_FILE);
61
62
  if (!f.ok) return [];
62
- return f.text.split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
63
+ return parseJsonl(f.text);
63
64
  }
64
65
 
65
66
  /** The ONE writer of `triggers.jsonl`: append-only, one line per fire outcome. @param {string} flowDir @param {Record<string, any>} row */
@@ -73,27 +74,26 @@ export function appendOutcome(flowDir, row) {
73
74
  * 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.
74
75
  * @param {string} flowDir @returns {Generator<{runId: string, runDir: string, at: string}>}
75
76
  */
76
- function* greenRuns(flowDir) {
77
+ export function* greenRuns(flowDir) {
77
78
  const cur = {};
78
79
  for (const f of FLOW_FILES) {
79
80
  const r = readFileInside(flowDir, f);
80
81
  if (!r.ok) return;
81
82
  cur[f] = r.text;
82
83
  }
83
- let sig;
84
- try { sig = JSON.parse(cur['signature.json']).flow; } catch { return; }
85
- const key = (/** @type {string} */ prose, /** @type {string} */ decl) => `${prose.trimEnd()}\n\u0000${decl}`;
86
- const want = key(cur['prose.txt'], cur['declaration.json']);
84
+ const sig = signedHashOf(flowDir); // the one reader of the signature's `.flow`: none (no usable hash) counts no green run
85
+ if (sig === null) return;
86
+ const cat = loadCatalogue();
87
+ if (!cat.ok) return;
87
88
  const history = readHistory(flowDir);
88
89
  for (const id of listRunIds(flowDir)) {
89
90
  const r = resolveRunDir(flowDir, id);
90
91
  if (!r.ok) continue;
91
92
  const end = endRow(history, r.runDir, id);
92
- if (end === null || end.outcome !== 'complete') continue;
93
- const prose = readFileInside(r.runDir, 'job/prose.txt');
94
- const decl = readFileInside(r.runDir, 'job/declaration.json');
93
+ if (end === null || !isGoodEnding(end.outcome)) continue;
94
+ const job = sameJob({ flowDir, runDir: r.runDir, catalogue: cat.primitives }); // a copy that fails its signature reads as no job: not green
95
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 };
96
+ if (job.present) { if (job.ok && job.same) yield { runId: id, runDir: r.runDir, at }; } else if (end.signatureHash === sig) yield { runId: id, runDir: r.runDir, at };
97
97
  }
98
98
  }
99
99
 
@@ -156,37 +156,6 @@ function newTicketTrigger(read, trigger) {
156
156
  return { ok: true, trigger: { kind: 'new-ticket', role: trigger.role, list, server, tool: lookTool, ...(watch ? { watch } : {}) } };
157
157
  }
158
158
 
159
- /**
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
161
- * path. Returns the typed trigger or the sentence that says what to fix.
162
- * @param {unknown} t @param {string[]} roles
163
- * @returns {{ok: true, trigger: Trigger|null} | {ok: false, say: string}}
164
- */
165
- function shapeOf(t, roles) {
166
- if (t === null) return { ok: true, trigger: null };
167
- 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.' };
168
- const o = /** @type {Record<string, unknown>} */ (t);
169
- if (o.kind === 'file-updated' || o.kind === 'new-file') {
170
- const where = o.kind === 'new-file' ? 'folder' : 'path';
171
- const extra = Object.keys(o).filter((k) => !['kind', 'role', where].includes(k));
172
- 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.` };
173
- 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.` };
174
- const p = o[where];
175
- // eslint-disable-next-line no-control-regex
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.` };
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 }) };
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
- }
187
- try { return { ok: true, trigger: validateSchedule(t) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was changed.` }; }
188
- }
189
-
190
159
  /**
191
160
  * 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
161
  * @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
@@ -246,20 +215,13 @@ export function createTriggerDoor(opts) {
246
215
  if (trigger !== null && !hasGreenRunForJob(flowDir)) return reply(409, { refused: 'no-green-run', say: NO_GREEN_SAY });
247
216
  // 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
248
217
  // 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.)
249
- const fileTrigger = trigger !== null && (trigger.kind === 'file-updated' || trigger.kind === 'new-file') ? trigger : null;
218
+ const fileTrigger = trigger !== null && isFileKind(trigger.kind) ? /** @type {FileTrigger} */ (trigger) : null;
250
219
  if (fileTrigger !== null && Object.hasOwn(pageAddressesOf(read.arbiter), fileTrigger.role)) {
251
220
  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
252
221
  }
253
222
  if (fileTrigger !== null) {
254
- try {
255
- checkTarget(fileTrigger.kind === 'new-file' ? 'new' : 'updated', fileTrigger.kind === 'new-file' ? fileTrigger.folder : fileTrigger.path);
256
- } catch (e) {
257
- return reply(400, { refused: 'bad-trigger', say: `${/** @type {Error} */ (e).message}. Nothing was changed.` });
258
- }
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
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.` }); }
262
- }
223
+ const why = fileTriggerWhy(fileTrigger);
224
+ if (why !== null) return reply(400, { refused: 'bad-trigger', say: `${why} Nothing was changed.` });
263
225
  }
264
226
  // 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
265
227
  // the job's recorded model is no change (null). It is bound into the hash, written beside the trigger's ledger, and read by the fire.
@@ -311,9 +273,9 @@ export function createTriggerDoor(opts) {
311
273
  if (!pf.ok) return reply(409, { refused: 'plan', say: pf.red.replace('Nothing was started.', 'Nothing was changed.') });
312
274
  scheduledFrom = planOf;
313
275
  if (!pf.same) {
314
- const decl = readFileInside(rr.runDir, 'job/declaration.json');
315
- if (!decl.ok) return reply(409, { refused: 'plan', say: `The plan ${planOf} kept cannot be read. Nothing was changed.` });
316
- scheduledPlan = { run: planOf, flowHash: String(pf.read.signature.flow), declSha: createHash('sha256').update(decl.text).digest('hex') };
276
+ const declText = pf.read.declarationText;
277
+ if (typeof declText !== 'string') return reply(409, { refused: 'plan', say: `The plan ${planOf} kept cannot be read. Nothing was changed.` });
278
+ scheduledPlan = { run: planOf, flowHash: String(pf.read.signature.flow), declSha: createHash('sha256').update(declText).digest('hex') };
317
279
  }
318
280
  }
319
281
  return {
@@ -362,8 +324,7 @@ export function createTriggerDoor(opts) {
362
324
  const cat = loadCatalogue();
363
325
  const rr = resolveRunDir(flowDir, planRec.run);
364
326
  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;
327
+ const good = kept && kept.present && kept.ok && kept.signature.flow === planRec.flowHash && typeof kept.declarationText === 'string' && createHash('sha256').update(kept.declarationText).digest('hex') === planRec.declSha;
367
328
  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
329
  read = /** @type {any} */ (kept);
369
330
  planRun = planRec.run;
@@ -521,12 +482,24 @@ export function createTriggerDoor(opts) {
521
482
  * @returns {{ok: true, trigger: Trigger} | {ok: false, say: string}}
522
483
  */
523
484
  cardSchedule(spec, plan) {
485
+ // M20 am5 item 1: the card's choice is checked as the Run card checks its own (`shapeOf`, `fileTriggerWhy`, the web-page input refusal), on the plan about to be signed
486
+ const roles = (plan.arbiter.sources ?? []).map((/** @type {any} */ s) => s.role);
487
+ const unsigned = (/** @type {string} */ say) => ({ ok: /** @type {false} */ (false), say: say.replace(/ Nothing was changed\.$/, ' Nothing was signed.') });
524
488
  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] });
489
+ const lists = Object.keys(ticketListsOf(plan.arbiter));
490
+ if (lists.length !== 1) return { ok: false, say: 'When a new ticket arrives needs exactly one ticket list in Inputs. Nothing was signed.' };
491
+ return newTicketTrigger(plan, { role: lists[0] });
492
+ }
493
+ const shaped = shapeOf(spec, roles);
494
+ if (!shaped.ok) return unsigned(shaped.say);
495
+ const trigger = shaped.trigger;
496
+ if (trigger !== null && isFileKind(trigger.kind)) {
497
+ const fileTrigger = /** @type {FileTrigger} */ (trigger);
498
+ if (Object.hasOwn(pageAddressesOf(plan.arbiter), fileTrigger.role)) return { ok: false, say: `The input "${fileTrigger.role}" is a web page, not a file, so no file arrival can start a run from it. Nothing was signed.` };
499
+ const why = fileTriggerWhy(fileTrigger);
500
+ if (why !== null) return { ok: false, say: `${why} Nothing was signed.` };
528
501
  }
529
- try { return { ok: true, trigger: validateSchedule(spec) }; } catch (e) { return { ok: false, say: `${/** @type {Error} */ (e).message}. Nothing was signed.` }; }
502
+ return trigger === null ? { ok: false, say: 'Pick when it runs from the choices. Nothing was signed.' } : { ok: true, trigger };
530
503
  },
531
504
 
532
505
  /**
@@ -640,17 +613,17 @@ export function createTriggerDoor(opts) {
640
613
  const flowDir = join(realRoot, flow);
641
614
  const sc = liveSchedule(flowDir, r.signature.flow);
642
615
  const trigger = sc === null ? null : sc.trigger;
643
- const armedRow = sc === null ? undefined : readRows(ledgerOf(flowDir), sc.sig).find((x) => x.kind === 'armed');
616
+ const armedRow = sc === null ? undefined : readTriggerLedger(ledgerOf(flowDir), sc.sig).find((x) => x.kind === 'armed');
644
617
  const outcomes = sc === null ? [] : readOutcomes(flowDir).filter((o) => o.sig === sc.sig);
645
618
  const hasGreenRun = hasGreenRunForJob(flowDir);
646
- const clockKind = trigger !== null && (trigger.kind === 'daily' || trigger.kind === 'weekdays' || trigger.kind === 'weekly');
619
+ const clockKind = trigger !== null && isClockKind(trigger.kind);
647
620
  return {
648
621
  flow, trigger, flowHash: r.signature.flow, sig: sc === null ? null : sc.sig, armed: armedRow !== undefined, armedAt: armedRow ? armedRow.at : null,
649
622
  nextSlotMs: clockKind && armedRow ? nextSlot(/** @type {any} */ (trigger), now()) : null,
650
623
  lastOutcome: outcomes.length > 0 ? outcomes[outcomes.length - 1] : null,
651
624
  hasGreenRun,
652
625
  // 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,
626
+ lookProblem: sc !== null && trigger !== null && trigger.kind === 'new-ticket' ? lookProblemOf(readTriggerLedger(ledgerOf(flowDir), sc.sig)) : null,
654
627
  // 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
628
  waiting: sc !== null && armedRow === undefined && !hasGreenRun,
656
629
  };