fwdloop 0.19.1 → 0.21.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 (68) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +22 -13
  3. package/package.json +1 -1
  4. package/src/audit-fold.js +177 -0
  5. package/src/authoring.js +24 -4
  6. package/src/books.js +4 -3
  7. package/src/closers.js +49 -2
  8. package/src/ctx-tools.js +1 -1
  9. package/src/diary.js +49 -0
  10. package/src/flow.js +218 -2
  11. package/src/flowmodel.js +42 -5
  12. package/src/jobkey.js +25 -0
  13. package/src/jsonl-append.js +29 -0
  14. package/src/model-step.js +103 -5
  15. package/src/monthly.js +3 -2
  16. package/src/panel/author.js +44 -18
  17. package/src/panel/authorcard.js +7 -13
  18. package/src/panel/authorflows.js +118 -24
  19. package/src/panel/authorresume.js +8 -4
  20. package/src/panel/authorstart.js +63 -18
  21. package/src/panel/authortrigger.js +250 -125
  22. package/src/panel/authorvalues.js +13 -2
  23. package/src/panel/data.js +279 -43
  24. package/src/panel/index.html +547 -150
  25. package/src/panel/needsyou.js +29 -0
  26. package/src/panel/scheduler.js +21 -22
  27. package/src/panel/server.js +30 -6
  28. package/src/primitives.js +44 -2
  29. package/src/provider.js +3 -2
  30. package/src/runner.js +58 -22
  31. package/src/runvalues.js +10 -2
  32. package/src/schedule.js +135 -0
  33. package/src/setup.js +0 -21
  34. package/src/summary-words.js +180 -7
  35. package/src/thinking.js +39 -0
  36. package/src/trigger-clock.js +18 -16
  37. package/src/trigger-files.js +37 -24
  38. package/src/trigger-line.js +6 -15
  39. package/src/try-checks.js +62 -0
  40. package/src/types.js +2 -1
  41. package/types/audit-fold.d.ts +54 -0
  42. package/types/authoring.d.ts +33 -2
  43. package/types/books.d.ts +17 -0
  44. package/types/ctx-tools.d.ts +1 -0
  45. package/types/diary.d.ts +57 -0
  46. package/types/flow.d.ts +106 -0
  47. package/types/flowmodel.d.ts +25 -3
  48. package/types/jobkey.d.ts +11 -0
  49. package/types/jsonl-append.d.ts +6 -0
  50. package/types/model-step.d.ts +4 -1
  51. package/types/panel/author.d.ts +47 -17
  52. package/types/panel/authorcard.d.ts +3 -6
  53. package/types/panel/authorflows.d.ts +38 -10
  54. package/types/panel/authorstart.d.ts +15 -2
  55. package/types/panel/authortrigger.d.ts +73 -41
  56. package/types/panel/authorvalues.d.ts +6 -0
  57. package/types/panel/data.d.ts +101 -19
  58. package/types/panel/needsyou.d.ts +20 -0
  59. package/types/runvalues.d.ts +5 -0
  60. package/types/schedule.d.ts +69 -0
  61. package/types/setup.d.ts +0 -19
  62. package/types/summary-words.d.ts +105 -2
  63. package/types/thinking.d.ts +31 -0
  64. package/types/trigger-clock.d.ts +8 -7
  65. package/types/trigger-files.d.ts +17 -10
  66. package/types/trigger-line.d.ts +16 -8
  67. package/types/try-checks.d.ts +55 -0
  68. package/types/types.d.ts +10 -1
@@ -69,13 +69,6 @@ export function nextInWords(ms, now) {
69
69
  return hours < 48 ? `next in ${hours}h` : `next in ${Math.floor(hours / 24)}d`;
70
70
  }
71
71
 
72
- /** am1, said before a human signs an edit of a job that has a trigger. @param {Trigger|null} t @param {string} [home] */
73
- export function editClearsWords(t, home) {
74
- const w = scheduledWords(t, home);
75
- if (w === null) return null;
76
- return `This job runs by itself (${w}). Signing this edit clears that back to By hand. You can set it again once the new job has had one good run.`;
77
- }
78
-
79
72
  /**
80
73
  * NEXT of a job with a trigger. One sentence, first match wins:
81
74
  * 1. a run of this job is waiting at its ask (the next run waits too);
@@ -169,3 +162,183 @@ export function endedWords(f) {
169
162
  }
170
163
  }
171
164
  }
165
+
166
+ // ---------------------------------------------------------------------------
167
+ // M9 am6 / am7 (docs/wiki/the-module-ladder.md): the words of "how did this run begin", "what schedule does the workflow have", the Audit's schedule rows and
168
+ // the Run tab's SCHEDULE block. ONE owner: the Job tab's Schedule field and the Run tab's SCHEDULE line 1 are built by `scheduleHead`, the run's
169
+ // Started line and the Audit's first row by `startedParts`. Pure: typed facts in, a fixed sentence out; no model text reaches any of it.
170
+ // ---------------------------------------------------------------------------
171
+
172
+ /** "MM/DD HH:MM", local time: the same form as the run cards' `rlShortDate`. @param {number|string} when epoch ms or an ISO string */
173
+ export function shortStamp(when) {
174
+ const d = new Date(typeof when === 'string' ? Date.parse(when) : when);
175
+ if (Number.isNaN(d.getTime())) return '';
176
+ return `${two(d.getMonth() + 1)}/${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`;
177
+ }
178
+
179
+ /** "Tue 10/20 09:05": the day name then the short stamp. @param {number} ms */
180
+ export function dayStamp(ms) {
181
+ return `${DAY_SHORT[new Date(ms).getDay()]} ${shortStamp(ms)}`;
182
+ }
183
+
184
+ /**
185
+ * The schedule in words, lower-case first ("every day at 08:15"): the SINGLE line-1 of the Run tab's SCHEDULE block and the first part of the Job tab's
186
+ * Schedule field. `null` (no schedule) has no sentence. @param {Trigger|null} t @param {string} [home]
187
+ */
188
+ export function scheduleHead(t, home) {
189
+ const w = scheduledWords(t, home);
190
+ return w === null ? null : `${w.charAt(0).toLowerCase()}${w.slice(1)}`;
191
+ }
192
+
193
+ /**
194
+ * The Job tab's "Schedule" field: the workflow's schedule now and what it is bound to, parts joined by " · ", or `none`.
195
+ * @param {{trigger: Trigger|null, from?: string|null, model?: string|null, destination?: string|null, inputs?: string[]|null, home?: string}} f
196
+ */
197
+ export function scheduleFieldWords(f) {
198
+ const head = scheduleHead(f.trigger, f.home);
199
+ if (head === null) return 'none';
200
+ return [head, f.from ? `from ${f.from}` : null, f.model || null, f.destination ? tilde(f.destination, f.home) : null, f.inputs && f.inputs.length > 0 ? f.inputs.join(', ') : null]
201
+ .filter((x) => x !== null).join(' · ');
202
+ }
203
+
204
+ /** A run's `trigger.json` record -> the typed pieces of "how it began", or `null` for a hand run. @param {any} rec */
205
+ function startedKind(rec) {
206
+ if (!rec || typeof rec !== 'object') return null;
207
+ return rec.kind === 'file' || rec.kind === 'clock' ? rec.kind : null;
208
+ }
209
+
210
+ /**
211
+ * The Job tab's Started line: `By hand · 10/15 13:46`, `By the schedule: every day at 08:15 · catch-up, 10 min late · 10/15 08:16`,
212
+ * `By a new file: aging-oct.csv · …`, `By a file update: aging.csv · …`. The trailing stamp is the run's start (am7 item 5); absent when the books do not hold one.
213
+ * @param {any} rec the run's trigger.json or null @param {number|null} startMs @param {string} [home]
214
+ */
215
+ export function startedWords(rec, startMs, home) {
216
+ const stamp = startMs === null || startMs === undefined ? null : shortStamp(startMs);
217
+ const kind = startedKind(rec);
218
+ let head = 'By hand';
219
+ if (kind === 'clock') {
220
+ const late = rec.catchUp === true ? (Number.isFinite(rec.lateMin) ? `catch-up, ${rec.lateMin} min late` : 'catch-up') : null;
221
+ head = `By the schedule: ${rec.words ?? rec.trigger ?? 'a schedule'}${late ? ` · ${late}` : ''}`;
222
+ } else if (kind === 'file') {
223
+ const name = typeof rec.file === 'string' ? basename(rec.file) : '';
224
+ const updated = rec.triggerKind === 'file-updated';
225
+ head = `${updated ? 'By a file update' : 'By a new file'}${name ? `: ${name}` : ''}`;
226
+ }
227
+ return stamp ? `${head} · ${stamp}` : head;
228
+ }
229
+
230
+ /** M9 am8 item 3: the busy sentence, in the busy row of `triggers.jsonl` and in the SCHEDULE block. One owner; the scheduler writes it, the words read it. */
231
+ export const SCHEDULE_BUSY_SAY = 'a run of this job was still working';
232
+
233
+ /** A month-used-up fire in the SCHEDULE block's words (am8 item 5): `month used up: $0.01 left, needs $0.50`. @param {any} row */
234
+ function monthUsedUpWords(row) {
235
+ const left = typeof row.leftUsd === 'number' ? `${row.atLeast === true ? 'at most ' : ''}${money(row.leftUsd)} left` : 'not enough left';
236
+ return `month used up: ${left}${typeof row.needUsd === 'number' ? `, needs ${money(row.needUsd)}` : ''}`;
237
+ }
238
+
239
+ /**
240
+ * The Run tab's SCHEDULE block (am7 item 3, am8 items 2-8): `{line1, line2, red}`. Line 1 = the schedule words or `By hand`. Line 2 (only with a schedule):
241
+ * `no run yet` before any fire; else `last <stamp> · ` then the newest fire's words, then `next ...`:
242
+ * - a start: `<run-N> · <outcome>[ · catch-up]` (a run waiting at its ask: `<run-N> · waiting for your answer (the next run does not wait)`), normal;
243
+ * - busy: `busy: a run of this job was still working`, normal (it clears by itself);
244
+ * - month used up: `month used up: $0.01 left, needs $0.50 · next: raise the limit in Settings, or it starts on the 1st`, red only while `nowMs` is still that month;
245
+ * - refused: `refused: <why> · next: fix it in Cancel / modify schedule`, red until a later good start.
246
+ * `next` otherwise: `next <day stamp>`, `next: waiting for a new file` (file schedule) or `next: not armed yet`.
247
+ * @param {{trigger: Trigger|null, home?: string, last: {at: string, runId: string, outcome: string, catchUp: boolean}|null, nextSlotMs: number|null, armed: boolean, problem: any, nowMs?: number}} f
248
+ * `problem`: the newest fire when it started nothing (busy, monthly-exhausted, refused), else null.
249
+ * @returns {{line1: string, line2: string|null, red: boolean}}
250
+ */
251
+ export function scheduleBlockWords(f) {
252
+ const head = scheduleHead(f.trigger, f.home);
253
+ const tr = f.trigger;
254
+ if (head === null || tr === null) return { line1: 'By hand', line2: null, red: false };
255
+ const file = tr.kind === 'new-file' || tr.kind === 'file-updated';
256
+ const next = file ? 'next: waiting for a new file' : (f.nextSlotMs !== null && f.armed ? `next ${dayStamp(f.nextSlotMs)}` : 'next: not armed yet');
257
+ const p = f.problem;
258
+ if (p) {
259
+ const stamp = `last ${shortStamp(p.at)}`;
260
+ if (p.outcome === 'busy') return { line1: head, line2: `${stamp} · busy: ${SCHEDULE_BUSY_SAY} · ${next}`, red: false };
261
+ if (p.outcome === 'monthly-exhausted') {
262
+ const month = (/** @type {number} */ ms) => { const d = new Date(ms); return d.getFullYear() * 12 + d.getMonth(); };
263
+ const still = month(Date.parse(p.at)) === month(f.nowMs ?? Date.now());
264
+ return { line1: head, line2: `${stamp} · ${monthUsedUpWords(p)} · ${still ? 'next: raise the limit in Settings, or it starts on the 1st' : next}`, red: still };
265
+ }
266
+ return { line1: head, line2: `${stamp} · refused: ${String(p.why ?? 'it was refused').trim()} · next: fix it in Cancel / modify schedule`, red: true };
267
+ }
268
+ if (!f.last) return { line1: head, line2: `no run yet · ${next}`, red: false };
269
+ const outcome = f.last.outcome === 'waiting' ? 'waiting for your answer (the next run does not wait)' : `${f.last.outcome}${f.last.catchUp ? ' · catch-up' : ''}`;
270
+ return { line1: head, line2: `last ${shortStamp(f.last.at)} · ${f.last.runId} · ${outcome} · ${next}`, red: false };
271
+ }
272
+
273
+ /** M9 am9 item 3: a `refused` fire's reason ends `Nothing started.` once, whether the scheduler already said so or not. @param {unknown} why */
274
+ function refusedWords(why) {
275
+ const w = String(why ?? 'it was refused').trim().replace(/\s*Nothing started\.?$/, '').replace(/\.$/, '');
276
+ return `refused: ${w || 'it was refused'}. Nothing started.`;
277
+ }
278
+
279
+ /** Fires that started nothing (the three outcomes of am8), the only rows `tries` may hold. @param {any} row */
280
+ export const startedNothing = (row) => row && (row.outcome === 'busy' || row.outcome === 'monthly-exhausted' || row.outcome === 'refused');
281
+
282
+ /** M9 am16/am18: a file that waited when the schedule changed and so will not run; its row carries the signed sentence in `say`. @param {any} row */
283
+ const droppedByChange = (row) => !!row && row.outcome === 'schedule-changed' && typeof row.say === 'string';
284
+
285
+ /** M9 am9 item 3: one `tries` row's words, after its stamp; the am8 owners' sentences. @param {any} row a triggers.jsonl row that started nothing */
286
+ function triesRowWords(row) {
287
+ if (droppedByChange(row)) return row.say;
288
+ if (row.outcome === 'busy') return `busy: ${String(row.say ?? SCHEDULE_BUSY_SAY).replace(/\.$/, '')}. Nothing started.`;
289
+ if (row.outcome === 'monthly-exhausted') return `${monthUsedUpWords(row)}. Nothing started.`;
290
+ return refusedWords(row.why);
291
+ }
292
+
293
+ /** M9 am9 item 4: at most this many `tries` show. */
294
+ export const SCHEDULE_TRIES_SHOWN = 7;
295
+
296
+ /**
297
+ * M9 am9 / am11: a run's Audit `schedule` section (one for every run of a job that has a schedule NOW; `null` when it has none). Folded head
298
+ * `<sign> <schedule words> · from run-7 · 2 tries started nothing`; unfolded rows `this run` and `tries` (stamp + words each).
299
+ * The schedule words are the SAME `line1` the Run tab's SCHEDULE block carries; the sign is `[▶]` while a run of the job is running, `[✗]` when that block is red, else `[·]` (am11).
300
+ * @param {{trigger: Trigger|null, runId: string, from: string|null, rec: any, startMs: number|null, block: {line1: string, red: boolean}, running: boolean, fires: any[]}} f
301
+ * `rec`: this run's trigger.json or null (a hand run); `fires`: every triggers.jsonl row of the job, across every signing.
302
+ * @returns {{sign: string, head: string, rows: Array<{label: string, stamp: string, text: string}>}|null}
303
+ */
304
+ export function scheduleAuditWords(f) {
305
+ // M9 am18: the am16 `schedule-changed` rows are listed with the tries, also after the schedule is cancelled (no trigger now, such rows exist)
306
+ if (f.trigger === null && !f.fires.some(droppedByChange)) return null;
307
+ const tries = f.fires.filter(startedNothing).reverse();
308
+ const listed = f.fires.filter((r) => startedNothing(r) || droppedByChange(r)).reverse();
309
+ const sign = f.running ? '[\u25B6]' : (f.block.red ? '[\u2717]' : '[\u00B7]');
310
+ const k = tries.length;
311
+ const head = [f.block.line1, f.from ? `from ${f.from}` : null, k > 0 ? `${k} ${k === 1 ? 'try' : 'tries'} started nothing` : null].filter((x) => x !== null).join(' \u00b7 ');
312
+ const kind = startedKind(f.rec);
313
+ let what = 'by hand.';
314
+ if (kind === 'clock') what = `started by the schedule \u00b7 ${f.rec.words ?? f.rec.trigger ?? 'a schedule'}${f.rec.catchUp === true ? ' \u00b7 catch-up' : ''}`;
315
+ else if (kind === 'file') {
316
+ const name = typeof f.rec.file === 'string' ? basename(f.rec.file) : '';
317
+ what = `started by the schedule \u00b7 ${f.rec.triggerKind === 'file-updated' ? 'file update' : 'new file'}${name ? ` ${name}` : ''}`;
318
+ }
319
+ if (f.from !== null && f.from === f.runId) what += kind === null ? ' The schedule was set from this run.' : '. The schedule was set from this run.';
320
+ /** @type {Array<{label: string, stamp: string, text: string}>} */
321
+ const rows = [{ label: 'this run', stamp: f.startMs === null ? '' : shortStamp(f.startMs), text: what }];
322
+ const shown = listed.slice(0, SCHEDULE_TRIES_SHOWN);
323
+ if (shown.length === 0) rows.push({ label: 'tries', stamp: '', text: 'none' });
324
+ else shown.forEach((r, i) => rows.push({ label: i === 0 ? 'tries' : '', stamp: shortStamp(r.at), text: triesRowWords(r) }));
325
+ return { sign, head, rows };
326
+ }
327
+
328
+ /**
329
+ * M11 am11 items 3-4: the Audit row that says why a card left Needs you: `removed from Needs you by you · 10/15 08:15`, or `removed from Needs you after 7 days`. `null` when it did not.
330
+ * @param {{by: 'you', at: string}|{by: 'age'}|null} left
331
+ */
332
+ export function needsLeftWords(left) {
333
+ if (left === null) return null;
334
+ return left.by === 'you' ? `removed from Needs you by you \u00b7 ${shortStamp(left.at)}` : 'removed from Needs you after 7 days';
335
+ }
336
+
337
+ /** ENDED (am7 item 1): `10/14 08:16 · passed · Goal met.`. The stamp is the run's local end time; the word is the run's outcome word (none for a run ended on purpose). @param {string|null} at ISO @param {string|null} word @param {string} reason */
338
+ export function endedLineWords(at, word, reason) {
339
+ const stamp = at ? shortStamp(at) : '';
340
+ return [stamp || null, word || null, reason].filter((x) => x !== null).join(' · ');
341
+ }
342
+
343
+ /** M9 am12: what a stopped run with no kept copy of its job says where Resume would be (a run made before runs kept one). The one owner of these words. */
344
+ export const NO_COPY_SAY = 'This run started before runs kept their own copy of the job, so it cannot carry on. Start a new run.';
package/src/thinking.js CHANGED
@@ -53,3 +53,42 @@ export function thinkingSay(status) {
53
53
  if (status === 'unknown') return 'thinking off (not confirmed)';
54
54
  return null;
55
55
  }
56
+
57
+ /**
58
+ * M4d am26 items 1-2: the words after a try line in the Audit, from that try's audit-row `thinking` {asked, status} (am25). bareagent confirmed it
59
+ * ('applied'): `thinking on` / `thinking off`. Any other status: `thinkingSay`'s words above, the same ones Chat uses. A row with no `thinking` (before am25,
60
+ * or no model call) has no words: nothing is guessed.
61
+ * M4d am27: a row with a `thinking` record but no status (the model sent no reply: an error, the time limit, a Stop before the first reply) reads
62
+ * `thinking <asked> (no reply)`, from what was ASKED; the words never say thinking happened. Nothing asked (asked null) has no words.
63
+ * @param {{asked?: unknown, status?: unknown}|null|undefined} thinking @returns {string|null}
64
+ */
65
+ export function thinkingTryWords(thinking) {
66
+ if (thinking === null || typeof thinking !== 'object') return null;
67
+ const status = typeof thinking.status === 'string' ? thinking.status : null;
68
+ if (status === null) return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked} (no reply)` : null;
69
+ if (status === 'applied') return thinking.asked === 'on' || thinking.asked === 'off' ? `thinking ${thinking.asked}` : null;
70
+ return thinkingSay(status);
71
+ }
72
+
73
+ /**
74
+ * M4d am28 items 2-4 (replaces am26 item 3's words and the hidden row): the Job tab's Thinking value, from the run's own record
75
+ * (`boxOn` = the Chat "Thinking on" box as the run started). A run with no record (before am25) is `null` and reads `—`, never a guess from model.json.
76
+ * Words: bareloop's `thinkingJobText`.
77
+ * // borrowed-from: bareloop src/thinking.js@b79e7d9
78
+ * @param {boolean|null} boxOn
79
+ */
80
+ export function thinkingRuleWords(boxOn) {
81
+ if (boxOn === null) return '—';
82
+ return boxOn ? 'always on' : 'on retries';
83
+ }
84
+
85
+ /**
86
+ * M4d am25 item 1/2: the ONE owner of what thinking a step's model call asks for. Code decides, never the model.
87
+ * Box ticked (the job's Chat "Thinking on" box, kept with the job): every try 'on'. Box off: the 1st try 'off'; the 2nd and later tries 'on'.
88
+ * A step redone after a human Redo is numbered from its redo count (the runner's `attemptOffset`), so it is always a 2nd-or-later try and thinks 'on'.
89
+ * @param {{boxOn: boolean, attempt: number}} a the runner's 1-based attempt number for this step
90
+ * @returns {'on'|'off'}
91
+ */
92
+ export function stepThinkingMode({ boxOn, attempt }) {
93
+ return boxOn === true || (Number.isInteger(attempt) && attempt >= 2) ? 'on' : 'off';
94
+ }
@@ -12,12 +12,14 @@
12
12
  // { id:'fire:<slotMs>', kind:'fire', slot, at, catchUp, missed } one run started for that slot
13
13
  // Starting a run is NOT this file; the caller does it after `recordFire`.
14
14
  import {
15
- appendFileSync, existsSync, mkdirSync, readFileSync,
15
+ mkdirSync,
16
16
  } from 'node:fs';
17
17
  import { dirname } from 'node:path';
18
18
 
19
+ import { appendRow, ledgerText } from './jsonl-append.js';
20
+
19
21
  /** @typedef {{kind:'daily'|'weekdays', hour:number, minute:number} | {kind:'weekly', day:string, hour:number, minute:number}} Schedule */
20
- /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number}} ClockRow */
22
+ /** @typedef {{id:string, kind:'armed'|'fire', at:number, slot?:number, catchUp?:boolean, missed?:number, sig?:string}} ClockRow */
21
23
  /** @typedef {{fire:boolean, catchUp:boolean, missed:number, slot?:number}} Due */
22
24
 
23
25
  /** A slot seen MORE than this after its set time is a catch-up (M9 am2 item 1). Exactly this late is on time. */
@@ -114,29 +116,29 @@ export function nextSlot(schedule, afterMs) {
114
116
  return /** @type {number} */ (found);
115
117
  }
116
118
 
117
- /** @param {string} file @returns {ClockRow[]} every row on disk, oldest first; a missing file is no rows. */
118
- export function readRows(file) {
119
- if (!existsSync(file)) return [];
120
- return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
119
+ /** @param {string} file @param {string} [sig] M9 am20: only the rows of that schedule signing (the one schedule ledger carries every signing's rows); absent = every row @returns {ClockRow[]} every row on disk that parses, oldest first; a missing file is no rows; a line a crash tore mid-append is skipped (`appendOnce` starts each append on a fresh line, so it never glues onto the next row). */
120
+ export function readRows(file, sig) {
121
+ const rows = ledgerText(file).split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
122
+ return sig === undefined ? rows : rows.filter((r) => r.sig === sig);
121
123
  }
122
124
 
123
- /** Append one row; a row whose id is already on disk is refused (write-once). @param {string} file @param {ClockRow} row */
124
- function appendOnce(file, row) {
125
- if (readRows(file).some((r) => r.id === row.id)) throw new Error(`ledger row ${row.id} already written`);
125
+ /** Append one row; a row whose id is already on disk (under the same signing) is refused (write-once). @param {string} file @param {ClockRow} row @param {string} [sig] stamped on the row (M9 am20) */
126
+ function appendOnce(file, row, sig) {
127
+ if (readRows(file, sig).some((r) => r.id === row.id)) throw new Error(`ledger row ${row.id} already written`);
126
128
  mkdirSync(dirname(file), { recursive: true });
127
- appendFileSync(file, `${JSON.stringify(row)}\n`);
129
+ appendRow(file, sig === undefined ? row : { ...row, sig });
128
130
  }
129
131
 
130
- /** The trigger was set at `now`: no slot before this ever fires. @param {string} file @param {number} now */
131
- export function armTrigger(file, now) {
132
- appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now });
132
+ /** The trigger was set at `now`: no slot before this ever fires. @param {string} file @param {number} now @param {string} [sig] */
133
+ export function armTrigger(file, now, sig) {
134
+ appendOnce(file, { id: `armed:${now}`, kind: 'armed', at: now }, sig);
133
135
  }
134
136
 
135
137
  /**
136
138
  * Record that the run for this due slot is starting. Call BEFORE starting the run: a crash loses a run, never doubles one.
137
- * @param {string} file @param {Due} d the result of `due` with fire true @param {number} now
139
+ * @param {string} file @param {Due} d the result of `due` with fire true @param {number} now @param {string} [sig]
138
140
  */
139
- export function recordFire(file, d, now) {
141
+ export function recordFire(file, d, now, sig) {
140
142
  if (!d.fire || d.slot === undefined) throw new Error('recordFire needs a due result with fire true');
141
- appendOnce(file, { id: `fire:${d.slot}`, kind: 'fire', slot: d.slot, at: now, catchUp: d.catchUp, missed: d.missed });
143
+ appendOnce(file, { id: `fire:${d.slot}`, kind: 'fire', slot: d.slot, at: now, catchUp: d.catchUp, missed: d.missed }, sig);
142
144
  }
@@ -14,29 +14,31 @@
14
14
  // one. 'dropped' = it was deleted / changed before its turn. A sha with a `ran` row never arrives again, whatever its name or mtime; see `arrives` for baseline / queued / dropped.
15
15
  // poll() writes nothing: it only reports finished files whose sha is new.
16
16
  import {
17
- appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync,
17
+ existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, realpathSync,
18
18
  } from 'node:fs';
19
19
  import { basename, dirname, join } from 'node:path';
20
20
  import { createHash } from 'node:crypto';
21
21
 
22
- /** @typedef {{id:string, kind:'baseline'|'arrived'|'ran'|'dropped', sha:string, name:string, size:number, at:number, path?:string, why?:string, of?:string}} SeenRow */
22
+ import { appendRow, ledgerText } from './jsonl-append.js';
23
+
24
+ /** @typedef {{id:string, kind:'baseline'|'arrived'|'ran'|'dropped', sha:string, name:string, size:number, at:number, path?:string, why?:string, of?:string, sig?:string}} SeenRow */
23
25
  /** @typedef {{path:string, sha:string, size:number}} ToRun */
24
26
  /** @typedef {{path:string, why:string}} Refused */
25
27
 
26
28
  /** Consecutive polls with the same size and mtime before a file is taken. (Two matches in a row = taken on the third sighting.) */
27
29
  export const STABLE_POLLS = 2;
28
30
 
29
- /** @param {string} file @returns {SeenRow[]} */
30
- export function readSeen(file) {
31
- if (!existsSync(file)) return [];
32
- return readFileSync(file, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l));
31
+ /** Every row that parses; a line a crash tore mid-append is skipped (it counts as not written). `appendSeen` starts each append on a fresh line, so a torn line can never glue onto the next row. @param {string} file @param {string} [sig] M9 am20: only the rows of that schedule signing (the one schedule ledger carries every signing's rows); absent = every row @returns {SeenRow[]} */
32
+ export function readSeen(file, sig) {
33
+ const rows = ledgerText(file).split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l)]; } catch { return []; } });
34
+ return sig === undefined ? rows : rows.filter((r) => r.sig === sig);
33
35
  }
34
36
 
35
- /** The ONE appender: write-once by id (a second row with the same id is not written). @param {string} file @param {SeenRow} row @returns {boolean} written */
36
- function appendSeen(file, row) {
37
- if (readSeen(file).some((r) => r.id === row.id)) return false;
37
+ /** The ONE appender: write-once by id within a signing (a second row with the same id is not written). Starts on a fresh line when the file does not end in a newline (a torn last line). @param {string} file @param {SeenRow} row @param {string} [sig] stamped on the row @returns {boolean} written */
38
+ function appendSeen(file, row, sig) {
39
+ if (readSeen(file, sig).some((r) => r.id === row.id)) return false;
38
40
  mkdirSync(dirname(file), { recursive: true });
39
- appendFileSync(file, `${JSON.stringify(row)}\n`);
41
+ appendRow(file, sig === undefined ? row : { ...row, sig });
40
42
  return true;
41
43
  }
42
44
 
@@ -57,22 +59,22 @@ function arrives(rows, it, mode) {
57
59
  if (mine.some((r) => r.kind === 'ran' || waiting(rows, r))) return false;
58
60
  const bi = rows.findLastIndex((r) => r.kind === 'baseline' && r.sha === it.sha);
59
61
  if (bi < 0) return true;
60
- return mode === 'updated' && rows.slice(bi + 1).some((r) => r.kind !== 'baseline' && r.sha !== it.sha);
62
+ return mode === 'updated' && rows.slice(bi + 1).some((r) => (r.kind === 'arrived' || r.kind === 'ran' || r.kind === 'dropped') && r.sha !== it.sha); // file rows only: the ledger also holds `armed` / `fire` / `cancelled` rows (M9 am20)
61
63
  }
62
64
 
63
- /** Arrived rows are never overwritten: the 2nd arrival of a sha (after a drop) gets its own id. @param {string} ledger @param {ToRun & {name?:string}} item @param {number} at the scheduler's clock, never the file's mtime */
64
- export function recordArrived(ledger, item, at) {
65
- const rows = readSeen(ledger);
65
+ /** Arrived rows are never overwritten: the 2nd arrival of a sha (after a drop) gets its own id. @param {string} ledger @param {ToRun & {name?:string}} item @param {number} at the scheduler's clock, never the file's mtime @param {string} [sig] */
66
+ export function recordArrived(ledger, item, at, sig) {
67
+ const rows = readSeen(ledger, sig);
66
68
  if (rows.some((r) => r.sha === item.sha && (r.kind === 'ran' || waiting(rows, r)))) return false; // one writer decides: ran or already queued
67
69
  const n = rows.filter((r) => r.kind === 'arrived' && r.sha === item.sha).length;
68
- return appendSeen(ledger, { id: n ? `arrived:${item.sha}:${n}` : `arrived:${item.sha}`, kind: 'arrived', sha: item.sha, name: basename(item.path), size: item.size, path: item.path, at });
70
+ return appendSeen(ledger, { id: n ? `arrived:${item.sha}:${n}` : `arrived:${item.sha}`, kind: 'arrived', sha: item.sha, name: basename(item.path), size: item.size, path: item.path, at }, sig);
69
71
  }
70
- /** Call immediately before the run is started. @param {string} ledger @param {{sha:string, path:string, size:number}} item @param {number} at */
71
- export const recordRan = (ledger, item, at) => appendSeen(ledger, { id: `ran:${item.sha}`, kind: 'ran', sha: item.sha, name: basename(item.path), size: item.size, at });
72
- /** `of` = the arrived row it cancels (item.id when a queue row is passed). @param {string} ledger @param {{sha:string, path:string, size:number, id?:string}} item @param {'deleted'|'changed'} why @param {number} at */
73
- export function recordDropped(ledger, item, why, at) {
72
+ /** Call immediately before the run is started. @param {string} ledger @param {{sha:string, path:string, size:number}} item @param {number} at @param {string} [sig] */
73
+ export const recordRan = (ledger, item, at, sig) => appendSeen(ledger, { id: `ran:${item.sha}`, kind: 'ran', sha: item.sha, name: basename(item.path), size: item.size, at }, sig);
74
+ /** `of` = the arrived row it cancels (item.id when a queue row is passed). @param {string} ledger @param {{sha:string, path:string, size:number, id?:string}} item @param {'deleted'|'changed'|'schedule-changed'|'carried'} why @param {number} at @param {string} [sig] */
75
+ export function recordDropped(ledger, item, why, at, sig) {
74
76
  const of = item.id ?? `arrived:${item.sha}`;
75
- return appendSeen(ledger, { id: `dropped:${of}`, kind: 'dropped', sha: item.sha, name: basename(item.path), size: item.size, why, at, of });
77
+ return appendSeen(ledger, { id: `dropped:${of}`, kind: 'dropped', sha: item.sha, name: basename(item.path), size: item.size, why, at, of }, sig);
76
78
  }
77
79
 
78
80
  /**
@@ -123,9 +125,20 @@ export function checkTarget(mode, target) {
123
125
  }
124
126
 
125
127
  /**
126
- * @param {{mode:'new'|'updated', target:string, ledger:string}} opts target = folder (new) or file (updated)
128
+ * M9 am16: does a trigger on this target still watch this file? New: the file sits directly in the same (real) folder. Updated: it is the same (real) file. False when the target cannot be resolved.
129
+ * @param {'new'|'updated'} mode @param {string} target @param {string} filePath a queued file's path as the watcher recorded it (a real path)
130
+ */
131
+ export function watches(mode, target, filePath) {
132
+ try {
133
+ if (mode === 'new') return realpathSync(target) === dirname(filePath);
134
+ return join(realpathSync(dirname(target)), basename(target)) === filePath;
135
+ } catch { return false; }
136
+ }
137
+
138
+ /**
139
+ * @param {{mode:'new'|'updated', target:string, ledger:string, sig?:string}} opts target = folder (new) or file (updated); `sig` (M9 am20) = the schedule signing every row this trigger reads and writes belongs to
127
140
  */
128
- export function createFileTrigger({ mode, target, ledger }) {
141
+ export function createFileTrigger({ mode, target, ledger, sig }) {
129
142
  if (mode !== 'new' && mode !== 'updated') throw new Error(`file trigger mode "${mode}" is not one of new, updated`);
130
143
  /** @type {Map<string, {key:string, same:number, takenKey:string|null}>} */
131
144
  const track = new Map();
@@ -166,7 +179,7 @@ export function createFileTrigger({ mode, target, ledger }) {
166
179
  for (const p of candidates().files) {
167
180
  const buf = readFileSync(p);
168
181
  const sha = sha256(buf);
169
- appendSeen(ledger, { id: `baseline:${sha}:${basename(p)}`, kind: 'baseline', sha, name: basename(p), size: buf.length, at: Date.now() }); // write-once: re-arming adds nothing
182
+ appendSeen(ledger, { id: `baseline:${sha}:${basename(p)}`, kind: 'baseline', sha, name: basename(p), size: buf.length, at: Date.now() }, sig); // write-once: re-arming adds nothing
170
183
  }
171
184
  }
172
185
 
@@ -176,7 +189,7 @@ export function createFileTrigger({ mode, target, ledger }) {
176
189
  const st2 = lstatSync(p);
177
190
  if (`${st2.size}:${st2.mtimeMs}` !== t.key) return 'changed'; // changed while reading: retry next poll
178
191
  const sha = sha256(buf);
179
- if (!arrives(readSeen(ledger), { sha }, mode)) return null; // ran, still queued, or still the starting point
192
+ if (!arrives(readSeen(ledger, sig), { sha }, mode)) return null; // ran, still queued, or still the starting point
180
193
  return { path: p, sha, size: buf.length };
181
194
  }
182
195
 
@@ -1,5 +1,6 @@
1
1
  // M9 piece 3 (docs/wiki/the-module-ladder.md, "M9" item 1, am1): the trigger as typed data in the signed arbiter block.
2
- // Pure text: the grammar of the one `guardrail: trigger ...` line, and the ONE place a prose text gains, changes or loses it.
2
+ // Pure text: the grammar of the one `guardrail: trigger ...` line. M9 am20: a schedule is its own signed file (src/schedule.js); NOTHING writes this line any more.
3
+ // The signed-text parser still accepts it so a job signed before am20 still reads and verifies, but nothing acts on it: such a job is By hand.
3
4
  //
4
5
  // guardrail: trigger daily 09:00
5
6
  // guardrail: trigger weekdays 09:00
@@ -63,23 +64,13 @@ export function stripTrigger(prose) {
63
64
  return prose.split('\n').filter((l) => !LINE_RE.test(l)).join('\n');
64
65
  }
65
66
 
66
- /**
67
- * The ONE writer of the trigger line: the prose with its trigger line replaced by this trigger's (or removed for null). With no trigger
68
- * in and none asked for, the text is returned unchanged. The arbiter block is last in a signed text, so the line goes at the end.
69
- * @param {string} prose @param {Trigger|null} trigger
70
- */
71
- export function proseWithTrigger(prose, trigger) {
72
- const stripped = stripTrigger(prose);
73
- if (trigger === null) return stripped;
74
- return `${stripped.replace(/\s*$/, '')}\n${triggerLine(trigger)}\n`;
75
- }
76
-
77
67
  /**
78
68
  * What the human's second click carries: binds the job, the exact signature it was shown at and the trigger.
79
- * @param {{flow: string, flowSignatureHash: string, trigger: Trigger|null}} a
69
+ * @param {{flow: string, flowSignatureHash: string, trigger: Trigger|null, model?: {slot: string, model: string}|null, destination?: string|null, inputs?: {role: string, path: string}[]|null, plan?: {run: string, flowHash: string, declSha: string}|null}} a
80
70
  */
81
- export function triggerHash({ flow, flowSignatureHash, trigger }) {
82
- return createHash('sha256').update(JSON.stringify({ m9: 'trigger', flow, flowSignatureHash, trigger })).digest('hex');
71
+ export function triggerHash({ flow, flowSignatureHash, trigger, model = null, destination = null, inputs = null, plan = null }) {
72
+ // M6 am5 item 3: the scheduled model is part of what the click signs; absent = the exact bytes (and hashes) a trigger had before
73
+ return createHash('sha256').update(JSON.stringify({ m9: 'trigger', flow, flowSignatureHash, trigger, ...(model ? { model } : {}), ...(destination ? { destination } : {}), ...(inputs ? { inputs } : {}), ...(plan ? { plan } : {}) })).digest('hex');
83
74
  }
84
75
 
85
76
  /** M9: the file a triggered start writes (once, before the spawn) into the run's own folder: why this run started. `appendHistory` copies it into the run's history row. */
@@ -0,0 +1,62 @@
1
+ // M4d am29 item 2: what one try saves about its checks. The runner runs the checks (done, happened, the close); this module only words them
2
+ // and records the output they judged. Numbers are identities, not run order: #1 the output exists, #2 the model said done, #3 and up the close's
3
+ // checks. A check that did not run (the done check halts before the others) is not listed. A hitl close has no mechanical check, so it adds none.
4
+ import { createHash } from 'node:crypto';
5
+ import { serializeArtifact } from './ask.js';
6
+
7
+ export const EVERY_STEP = 'every step';
8
+
9
+ /** The size words of a byte count: `412 B`, `7.9 KB`, `1.2 MB`. @param {number} n */
10
+ export function sizeWords(n) {
11
+ if (n < 1024) return `${n} B`;
12
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
13
+ return `${(n / 1024 / 1024).toFixed(1)} MB`;
14
+ }
15
+
16
+ /** Where a guardrail check comes from: the job line it belongs to (guardrail n belongs to job line n). @param {{fromLine?: unknown}} step */
17
+ export const lineSource = (step) => (Number.isInteger(step?.fromLine) ? `line ${step.fromLine} ~` : 'the step\'s guardrail');
18
+
19
+ /** #2, the model's own `done`. @param {{verdict: 'done'|'not-done'}} doneCheck @param {unknown} artifact */
20
+ export function doneRecord(doneCheck, artifact) {
21
+ const said = /** @type {any} */ (artifact)?.done;
22
+ return {
23
+ n: 2, text: 'the model said done: true', ok: doneCheck.verdict === 'done', result: doneCheck.verdict === 'done' ? null : (typeof said === 'boolean' ? 'it said done: false' : 'no true/false done'), source: EVERY_STEP,
24
+ };
25
+ }
26
+
27
+ /** #1, the happened check: the output exists and is not empty. @param {{verdict: string, red?: string}} happened @param {unknown} artifact */
28
+ export function happenedRecord(happened, artifact) {
29
+ const ok = happened.verdict !== 'red';
30
+ return {
31
+ n: 1, text: 'the output exists and isn\'t empty', ok, result: ok ? sizeWords(Buffer.byteLength(serializeArtifact(artifact), 'utf8')) : String(happened.red ?? '').replace(/^.*? produced /, ''), source: EVERY_STEP,
32
+ };
33
+ }
34
+
35
+ /** The output a try judged: the file it is saved as when the step closes, with the size and sha256 of those exact bytes. Never its content. @param {{emits?: string}} step @param {unknown} artifact */
36
+ export function outputRecord(step, artifact) {
37
+ const bytes = serializeArtifact(artifact);
38
+ return { file: `artifacts/${step?.emits ?? 'step'}.json`, bytes: Buffer.byteLength(bytes, 'utf8'), sha256: createHash('sha256').update(Buffer.from(bytes, 'utf8')).digest('hex') };
39
+ }
40
+
41
+ /**
42
+ * #3 and up: the close's own checks. A softgreen close carries each of its checks; a green close is one check over all its cited fields; a close that
43
+ * judged nothing (`unparseable`, `crash`) is one check that could not run, with that third outcome as its result.
44
+ * @param {any} step @param {any} artifact @param {{verdict: string, red?: string|null, checks?: Array<{text:string, ok:boolean, result:string|null}>}} closed
45
+ */
46
+ export function closeRecords(step, artifact, closed) {
47
+ const source = lineSource(step);
48
+ if (closed.verdict === 'unparseable' || closed.verdict === 'crash') {
49
+ return [{
50
+ n: 3, text: 'the close could run', ok: false, result: closed.verdict, source,
51
+ }];
52
+ }
53
+ if (step?.close?.class === 'green') {
54
+ const n = Object.keys(artifact?.fields ?? {}).length;
55
+ return [{
56
+ n: 3, text: 'every cited field matches its source', ok: closed.verdict === 'green', result: `${n} field${n === 1 ? '' : 's'}`, source,
57
+ }];
58
+ }
59
+ return (closed.checks ?? []).map((c, i) => ({
60
+ n: 3 + i, text: c.text, ok: c.ok, result: c.result, source,
61
+ }));
62
+ }
package/src/types.js CHANGED
@@ -49,7 +49,7 @@
49
49
  * @property {string[]} skills - `skills <name>[, <name>...]`. Default ['core'].
50
50
  * @property {SourceSlot[]} sources - zero or more `source <role> = file:<path>`.
51
51
  * @property {number} roundBudgetMs - `round budget <int><s|m|h>`. Default 120000.
52
- * @property {import("./trigger-line.js").Trigger|null} trigger - `trigger <kind> ...` (M9). Default null = By hand.
52
+ * @property {import("./trigger-line.js").Trigger|null} trigger - `trigger <kind> ...` (M9). Default null = By hand. M9 am20: read for jobs signed before, NEVER acted on (a schedule is `schedule.json`).
53
53
  */
54
54
 
55
55
  /**
@@ -261,6 +261,7 @@
261
261
  * @property {'green'|'red'|'hitl'|'unparseable'|'crash'} verdict
262
262
  * @property {string|null} [red]
263
263
  * @property {string[]} [reds]
264
+ * @property {Array<{id:string, text:string, ok:boolean, result:string|null}>} [checks] a softgreen close: every check it ran (M4d am29 item 2)
264
265
  */
265
266
 
266
267
  /**
@@ -0,0 +1,54 @@
1
+ /** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). @param {any} r */
2
+ export function isTryRow(r: any): boolean;
3
+ /** @param {string} runDir */
4
+ export function loadDiaries(runDir: string): {
5
+ present: boolean;
6
+ calls: any[];
7
+ tools: any[];
8
+ checks: any[];
9
+ };
10
+ /** What the human did, in the signed words, from the ask step's own audit row; `null` for a row that is not an answer. @param {any} r */
11
+ export function humanWords(r: any): string | null;
12
+ /**
13
+ * The fold of one step, or `null` for a step with nothing new to show (an old run, or a step that is neither a model step with records nor an ask).
14
+ * @param {{rows:any[], tryMarks:string[], closeClass:string|null}} group `deriveAuditGroups`' group for the step
15
+ * @param {ReturnType<typeof loadDiaries>} d
16
+ * @param {{about?: string|null}} [info] `about`: the file an ask is about
17
+ */
18
+ export function deriveFold(group: {
19
+ rows: any[];
20
+ tryMarks: string[];
21
+ closeClass: string | null;
22
+ }, d: ReturnType<typeof loadDiaries>, info?: {
23
+ about?: string | null;
24
+ }): {
25
+ who: string;
26
+ tally: string | null;
27
+ tries: any[];
28
+ rows: any[];
29
+ counts: {
30
+ rounds: number;
31
+ tools: number;
32
+ denied: number;
33
+ checksRun: any;
34
+ checksFailed: any;
35
+ lastTry: {
36
+ run: any;
37
+ passed: any;
38
+ } | null;
39
+ };
40
+ lastAnswer: {
41
+ words: string | null;
42
+ at: any;
43
+ } | null;
44
+ } | null;
45
+ /** The step card's one new line (item 6) minus the human step's time (the page formats that); `—` when there is no record. @param {ReturnType<typeof deriveFold>} fold */
46
+ export function cardLine(fold: ReturnType<typeof deriveFold>): string;
47
+ /**
48
+ * The Run summary's two new lines (item 5), from the same diary rows the folds read; `—` for a run with no diaries.
49
+ * @param {ReturnType<typeof loadDiaries>} d
50
+ */
51
+ export function summaryLines(d: ReturnType<typeof loadDiaries>): {
52
+ calls: string;
53
+ checks: string;
54
+ };