fwdloop 0.19.0 → 0.20.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 (52) hide show
  1. package/bin/fwdloop +22 -13
  2. package/package.json +1 -1
  3. package/src/authoring.js +23 -3
  4. package/src/books.js +3 -2
  5. package/src/flow.js +218 -2
  6. package/src/jobkey.js +25 -0
  7. package/src/jsonl-append.js +29 -0
  8. package/src/monthly.js +3 -2
  9. package/src/panel/author.js +44 -18
  10. package/src/panel/authorcard.js +7 -13
  11. package/src/panel/authorflows.js +118 -24
  12. package/src/panel/authorresume.js +8 -4
  13. package/src/panel/authorstart.js +63 -18
  14. package/src/panel/authortrigger.js +252 -128
  15. package/src/panel/authorvalues.js +13 -2
  16. package/src/panel/data.js +233 -36
  17. package/src/panel/index.html +330 -124
  18. package/src/panel/needsyou.js +29 -0
  19. package/src/panel/scheduler.js +23 -23
  20. package/src/panel/server.js +30 -6
  21. package/src/primitives.js +5 -6
  22. package/src/provider.js +3 -2
  23. package/src/runner.js +10 -10
  24. package/src/runvalues.js +10 -2
  25. package/src/schedule.js +135 -0
  26. package/src/setup.js +0 -21
  27. package/src/summary-words.js +180 -12
  28. package/src/trigger-clock.js +18 -16
  29. package/src/trigger-files.js +40 -27
  30. package/src/trigger-line.js +6 -15
  31. package/src/types.js +1 -1
  32. package/types/authoring.d.ts +32 -2
  33. package/types/flow.d.ts +106 -0
  34. package/types/jobkey.d.ts +11 -0
  35. package/types/jsonl-append.d.ts +6 -0
  36. package/types/panel/author.d.ts +48 -38
  37. package/types/panel/authorcard.d.ts +3 -6
  38. package/types/panel/authorflows.d.ts +38 -10
  39. package/types/panel/authorstart.d.ts +15 -2
  40. package/types/panel/authortrigger.d.ts +75 -63
  41. package/types/panel/authorvalues.d.ts +6 -0
  42. package/types/panel/data.d.ts +101 -19
  43. package/types/panel/needsyou.d.ts +20 -0
  44. package/types/primitives.d.ts +5 -0
  45. package/types/runvalues.d.ts +5 -0
  46. package/types/schedule.d.ts +69 -0
  47. package/types/setup.d.ts +0 -19
  48. package/types/summary-words.d.ts +105 -4
  49. package/types/trigger-clock.d.ts +8 -7
  50. package/types/trigger-files.d.ts +17 -10
  51. package/types/trigger-line.d.ts +16 -8
  52. package/types/types.d.ts +1 -1
@@ -0,0 +1,29 @@
1
+ // M11 amendment 11 item 3: the human's "Remove from Needs you". The ONE writer of the removal marker; the reading, the episode key and the 7-day rule are `data.js`'s
2
+ // (`getRunNeeds`, `needsYouOf`), so the runs list, this route and the Audit can never disagree. It changes nothing else about the run.
3
+ // The marker is written like the refused-start dismiss (`cleared.json`, authorstart.js): 0600, once (`wx`), the run folder realpathed at use time.
4
+
5
+ import { realpathSync, writeFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+
8
+ import { getRunNeeds, needsRemovedFile } from './data.js';
9
+
10
+ /**
11
+ * Write the marker for the episode the card is in now. Refused unless the run is in Needs you with a removable tag (`Reopen` or `Resume`, never `Answer`) right now.
12
+ * @param {{root: string, flow: string, runId: string, catalogue: any, nowMs?: number, at?: string, resumeAttempt?: (flow: string, runId: string) => any}} o
13
+ * @returns {{ok: true}|{ok: false, refused: 'no-such-run'|'not-in-needs-you', say: string}}
14
+ */
15
+ export function removeFromNeedsYou({
16
+ root, flow, runId, catalogue, nowMs = Date.now(), at = new Date(nowMs).toISOString(), resumeAttempt,
17
+ }) {
18
+ const n = getRunNeeds({
19
+ root, flow, runId, catalogue, nowMs, resumeAttempt,
20
+ });
21
+ if (n === null) return { ok: false, refused: 'no-such-run', say: 'there is no such run' };
22
+ if (!n.removable || n.key === null) return { ok: false, refused: 'not-in-needs-you', say: 'this run is not in Needs you with a card that can be removed' };
23
+ try {
24
+ writeFileSync(join(realpathSync(n.runDir), needsRemovedFile(n.key)), `${JSON.stringify({ key: n.key, at })}\n`, { mode: 0o600, flag: 'wx' });
25
+ } catch (e) {
26
+ if (/** @type {any} */ (e)?.code !== 'EEXIST') throw e;
27
+ }
28
+ return { ok: true };
29
+ }
@@ -8,18 +8,18 @@
8
8
  // each job's signed files (small, hash-checked) and does no more.
9
9
  // No leaked timer: `start` is idempotent, the timer is unref'd, and the server's close calls `stop`.
10
10
  //
11
- // What a tick does for one job with a signed trigger (the trigger itself is read from the job, never from here):
12
- // 1. arm it if it is not armed yet (a crash between the sign and the arm);
13
- // 2. clock kinds: `due` against the clock ledger; a due slot is written to the ledger (`recordFire`) BEFORE the fire;
14
- // 3. file kinds: `poll` of this job's file trigger; each file taken is already in the seen ledger (`ran`) BEFORE the fire.
11
+ // What a tick does for one job with a signed schedule (M9 am20: the schedule is the job's own `schedule.json`, read by the door, never a line in the job):
12
+ // 0. a schedule whose job was Edited since is cancelled the way Cancel does it (`retireStale`);
13
+ // 1. clock kinds: `due` against this signing's rows of the job's one schedule ledger; a due slot is written to the ledger (`recordFire`) BEFORE the fire;
14
+ // 2. file kinds: `poll` of this job's file trigger; each file taken is already in the ledger (`ran`) BEFORE the fire.
15
+ // A schedule change or a Cancel settles the queue in its own click (src/schedule.js `dropQueue` / `carryQueue`): no tick settles anything.
15
16
  // A failure on one job (a folder that went away) is written once to `triggers.jsonl` as `refused` and never stops the other jobs.
16
- import { join } from 'node:path';
17
-
18
17
  import { due, readRows, recordFire } from '../trigger-clock.js';
19
18
  import {
20
19
  createFileTrigger, queueOf, readSeen, recheck, recordArrived, recordDropped, recordRan,
21
20
  } from '../trigger-files.js';
22
- import { readOutcomes, triggerLedgerDir } from './authortrigger.js';
21
+ import { ledgerOf } from '../schedule.js';
22
+ import { readOutcomes } from './authortrigger.js';
23
23
 
24
24
  /**
25
25
  * @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number }} opts
@@ -37,15 +37,17 @@ export function createScheduler(opts) {
37
37
  /**
38
38
  * M9 am3: the queue of a file trigger (arrived minus ran, oldest first). Busy: every queued file is told ONCE (`busy`) and waits. Free: the
39
39
  * head is looked at again at use time (deleted / changed -> one row, dropped, the next head), then goes through the fire checks; `ran` is
40
- * written right before the start. A head that is not started (month, keys, input) stays queued, told once, and blocks the ones behind it.
40
+ * written right before the start. A head refused BEFORE `ran` is written (month, keys, input) stays queued, told once, and blocks the ones behind it; a refusal by the starter itself lands after `ran`, so that file is then marked run and leaves the queue.
41
41
  * @param {any} job @param {string} ledger @param {number} nowMs
42
42
  */
43
43
  function runQueue(job, ledger, nowMs) {
44
- let queue = queueOf(readSeen(ledger));
44
+ const { sig } = job;
45
+ let queue = queueOf(readSeen(ledger, sig));
45
46
  if (queue.length === 0) return;
46
- const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string').map((r) => `${r.sha}|${r.outcome}`));
47
+ const key = (/** @type {string} */ sha, /** @type {Record<string, any>} */ r) => `${sha}|${r.outcome}|${r.why ?? ''}`; // a refusal is told once PER REASON; busy / monthly carry no `why`
48
+ const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string' && r.sig === sig).map((r) => key(r.sha, r)));
47
49
  const cause = (/** @type {any} */ q) => ({ kind: /** @type {'file'} */ ('file'), path: q.path, sha: q.sha });
48
- const told = (/** @type {any} */ q) => (/** @type {string} */ outcome) => { const k = `${q.sha}|${outcome}`; const had = spoken.has(k); spoken.add(k); return had; };
50
+ const told = (/** @type {any} */ q) => (/** @type {Record<string, any>} */ row) => { const k = key(q.sha, row); const had = spoken.has(k); spoken.add(k); return had; };
49
51
  if (door.busy(job)) {
50
52
  for (const q of queue) door.fire(job, cause(q), { told: told(q) });
51
53
  return;
@@ -55,14 +57,14 @@ export function createScheduler(opts) {
55
57
  const seen = recheck(q);
56
58
  if (seen.state !== 'ok') {
57
59
  const why = seen.state === 'deleted' ? 'deleted' : 'changed';
58
- recordDropped(ledger, q, why, nowMs);
60
+ recordDropped(ledger, q, why, nowMs, sig);
59
61
  door.note(job, {
60
62
  outcome: why, file: q.path, sha: q.sha, say: seen.state === 'deleted' ? `${q.name} did not run: ${seen.say}.` : `${q.name} did not run: it changed before its turn; the new version arrives again.`,
61
63
  });
62
64
  queue = queue.slice(1);
63
65
  continue;
64
66
  }
65
- door.fire(job, cause({ ...q, path: seen.path }), { told: told(q), beforeStart: () => recordRan(ledger, seen, nowMs) });
67
+ door.fire(job, cause({ ...q, path: seen.path }), { told: told(q), holdIfCannotStart: true, beforeStart: () => recordRan(ledger, seen, nowMs, sig) });
66
68
  return;
67
69
  }
68
70
  }
@@ -70,32 +72,30 @@ export function createScheduler(opts) {
70
72
  function tick() {
71
73
  const nowMs = now();
72
74
  const live = new Set();
75
+ try { door.retireStale(); } catch { /* one job's files never stop the others; tried again next tick */ }
73
76
  for (const job of door.scan()) {
74
- const hash = job.read.signature.flow;
75
- const key = `${job.flow}|${hash}`;
77
+ const { sig } = job;
78
+ const key = `${job.flow}|${sig}`;
76
79
  live.add(key);
77
80
  try {
78
- door.ensureArmed(job);
79
- const dir = triggerLedgerDir(job.flowDir, hash);
81
+ const ledger = ledgerOf(job.flowDir);
80
82
  const { trigger } = job;
81
83
  if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
82
84
  let w = watchers.get(key);
83
85
  if (!w) {
84
86
  w = createFileTrigger({
85
- mode: trigger.kind === 'new-file' ? 'new' : 'updated', target: trigger.kind === 'new-file' ? trigger.folder : trigger.path, ledger: join(dir, 'seen.jsonl'),
87
+ mode: trigger.kind === 'new-file' ? 'new' : 'updated', target: trigger.kind === 'new-file' ? trigger.folder : trigger.path, ledger, sig,
86
88
  });
87
89
  watchers.set(key, w);
88
90
  }
89
- const ledger = join(dir, 'seen.jsonl');
90
91
  const { arrived, refused } = w.poll();
91
92
  for (const r of refused) door.refuse(job, `${r.path}: ${r.why}`);
92
- for (const f of arrived) recordArrived(ledger, f, nowMs); // THE writer of the file ledger: arrival time is this clock, never the file's mtime
93
+ for (const f of arrived) recordArrived(ledger, f, nowMs, sig); // THE writer of the file ledger: arrival time is this clock, never the file's mtime
93
94
  runQueue(job, ledger, nowMs);
94
95
  } else {
95
- const clock = join(dir, 'clock.jsonl');
96
- const d = due(trigger, readRows(clock), nowMs);
96
+ const d = due(trigger, readRows(ledger, sig), nowMs);
97
97
  if (d.fire) {
98
- recordFire(clock, d, nowMs); // BEFORE the fire: a crash loses a run, never doubles one
98
+ recordFire(ledger, d, nowMs, sig); // BEFORE the fire: a crash loses a run, never doubles one
99
99
  door.fire(job, {
100
100
  kind: 'clock', slot: /** @type {number} */ (d.slot), catchUp: d.catchUp, missed: d.missed,
101
101
  });
@@ -58,6 +58,7 @@ import { answerAsk, reopenAsk, normalizeDecision } from '../ask.js';
58
58
  import { readHistory, endRow } from '../books.js';
59
59
  import { resolveRunDir } from '../flow.js';
60
60
  import { readAsk, requestStop, stopParkedRun } from '../runner.js';
61
+ import { removeFromNeedsYou } from './needsyou.js';
61
62
  import {
62
63
  listRuns, listScheduled, summarizeJobs, RUNS_LIST_LIMITS, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
63
64
  } from './data.js';
@@ -296,6 +297,24 @@ async function stopRoute(res, body, root) {
296
297
  sendJson(res, 202, { ok: true, stopping: true, already: written === 'exists' });
297
298
  }
298
299
 
300
+ /**
301
+ * `POST /api/needs-remove` — runs after the same gates as the answer. The human's "Remove from Needs you" (M11 am11 item 3): writes the removal marker for the card's
302
+ * current episode, once, and nothing else. Refused 409 for a run that is not in Needs you with a removable card (a run waiting at a live ask is never removable).
303
+ * @param {any} res @param {any} body @param {string} root @param {ReturnType<typeof createResumer>} resumer @param {(() => number)|undefined} now
304
+ */
305
+ function needsRemoveRoute(res, body, root, resumer, now) {
306
+ const b = body !== null && typeof body === 'object' ? body : {};
307
+ const { flow, runId } = b;
308
+ if (resolveRun(res, root, flow, runId) === null) return;
309
+ const loaded = loadCatalogue();
310
+ if (!loaded.ok) { refuse(res, 500, 'catalogue', 'the catalogue failed to load'); return; }
311
+ const r = removeFromNeedsYou({
312
+ root, flow, runId, catalogue: loaded.primitives, nowMs: (now ?? Date.now)(), resumeAttempt: (f, id) => resumer.get(f, id),
313
+ });
314
+ if (!r.ok) { sendJson(res, r.refused === 'no-such-run' ? 404 : 409, { ok: false, refused: r.refused, say: r.say }); return; }
315
+ sendJson(res, 200, { ok: true });
316
+ }
317
+
299
318
  /**
300
319
  * `POST /api/resume` — runs after the same gates as the answer. Starts a
301
320
  * resume ONLY for a run that has a saved, unconsumed answer; it takes no
@@ -330,6 +349,7 @@ function authorPost(res, url, body, author) {
330
349
  const send = (r) => sendJson(res, r.status, r.body);
331
350
  if (url === '/api/author/draft') { send(author.start(body)); return; }
332
351
  if (url === '/api/author/run') { send(author.run(body)); return; }
352
+ if (url === '/api/author/reuse-check') { send(author.reuseCheck(body)); return; }
333
353
  if (url === '/api/author/run-prepare') { send(author.runPrepare(body)); return; }
334
354
  if (url === '/api/author/trigger-prepare') { send(author.trigger.prepare(body)); return; }
335
355
  if (url === '/api/author/trigger') { send(author.trigger.set(body)); return; }
@@ -382,11 +402,12 @@ export function handleRequest(req, res, opts) {
382
402
  const isSettingsPost = method === 'POST' && String(req.url).startsWith('/api/settings/');
383
403
  // M4e piece 2a: every `/api/author/...` POST goes through the SAME door (own Host, own Origin, body cap) — no second guard.
384
404
  const isAuthorPost = method === 'POST' && String(req.url).startsWith('/api/author/');
385
- if (method === 'POST' && (isSettingsPost || isAuthorPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock' || req.url === '/api/stop')) {
405
+ if (method === 'POST' && (isSettingsPost || isAuthorPost || req.url === '/api/answer' || req.url === '/api/resume' || req.url === '/api/reopen' || req.url === '/api/remove-lock' || req.url === '/api/stop' || req.url === '/api/needs-remove')) {
386
406
  const isResume = req.url === '/api/resume';
387
407
  const isReopen = req.url === '/api/reopen';
388
408
  const isRemoveLock = req.url === '/api/remove-lock';
389
409
  const isStop = req.url === '/api/stop';
410
+ const isNeedsRemove = req.url === '/api/needs-remove';
390
411
  const origin = req.headers.origin;
391
412
  if (origin !== `http://127.0.0.1:${opts.port}` && origin !== `http://localhost:${opts.port}`) {
392
413
  refuse(res, 403, 'origin-not-own', String(origin));
@@ -417,6 +438,7 @@ export function handleRequest(req, res, opts) {
417
438
  if (isResume) resumeRoute(res, body, opts.root, opts.resumer);
418
439
  else if (isReopen) reopenRoute(res, body, opts.root, opts.resumer);
419
440
  else if (isRemoveLock) removeLockRoute(res, body, opts.root, opts.resumer);
441
+ else if (isNeedsRemove) needsRemoveRoute(res, body, opts.root, opts.resumer, opts.now);
420
442
  else if (isStop) {
421
443
  stopRoute(res, body, opts.root).catch(() => {
422
444
  if (!res.headersSent) sendJson(res, 500, { ok: false, refused: 'internal', red: 'internal error' });
@@ -431,7 +453,7 @@ export function handleRequest(req, res, opts) {
431
453
  }
432
454
 
433
455
  if (method !== 'GET' && method !== 'HEAD') {
434
- sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer, POST /api/resume, POST /api/reopen, POST /api/remove-lock, POST /api/stop, POST /api/settings/... and POST /api/author/...');
456
+ sendText(res, 405, 'method not allowed — GET/HEAD for reads; the only writes are POST /api/answer, POST /api/resume, POST /api/reopen, POST /api/remove-lock, POST /api/stop, POST /api/needs-remove, POST /api/settings/... and POST /api/author/...');
435
457
  return;
436
458
  }
437
459
 
@@ -549,14 +571,16 @@ export function handleRequest(req, res, opts) {
549
571
  if (!fd.ok && fd.why === 'outside-root') { refuse(res, 403, 'flow-outside-root', cleanPaths(fd.red, opts.root)); return; }
550
572
 
551
573
  if (sub === 'audit') {
552
- const result = getRunAudit({ root: opts.root, flow, runId });
574
+ const result = getRunAudit({
575
+ root: opts.root, flow, runId, scheduleRead: (f) => opts.author?.trigger?.facts(f) ?? null, catalogue, resumeAttempt, startingRun, now: opts.now,
576
+ });
553
577
  if (!result) { sendText(res, 404, 'no such run'); return; }
554
578
  send(200, result);
555
579
  return;
556
580
  }
557
581
  if (sub === 'job') {
558
582
  const result = getRunJob({
559
- root: opts.root, flow, runId, catalogue,
583
+ root: opts.root, flow, runId, catalogue, scheduleRead: (f) => opts.author?.trigger?.facts(f) ?? null,
560
584
  });
561
585
  if (!result) { sendText(res, 404, 'no such run'); return; }
562
586
  send(200, result);
@@ -564,14 +588,14 @@ export function handleRequest(req, res, opts) {
564
588
  }
565
589
  if (sub === 'asks') {
566
590
  const result = getRunAsks({
567
- root: opts.root, flow, runId, catalogue, resumeAttempt,
591
+ root: opts.root, flow, runId, catalogue, resumeAttempt, now: opts.now,
568
592
  });
569
593
  if (!result) { sendText(res, 404, 'no such run'); return; }
570
594
  send(200, result);
571
595
  return;
572
596
  }
573
597
  const result = getRunDetail({
574
- root: opts.root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead: (f) => opts.author?.trigger?.read(f) ?? null, now: opts.now,
598
+ root: opts.root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead: (f) => opts.author?.trigger?.facts(f) ?? null, now: opts.now,
575
599
  });
576
600
  if (!result) { sendText(res, 404, 'no such run'); return; }
577
601
  send(200, result);
package/src/primitives.js CHANGED
@@ -269,16 +269,15 @@ function addressCellsPrimitiveTool(inputsByRole) {
269
269
  };
270
270
  }
271
271
 
272
- /** The verbs this piece actually implements (the switch below, as data) —
273
- * one writer for "is this verb wired": `resolvePrimitives`'s own reds use
274
- * it, and `src/runner.js`'s preflight (F46: a step granted a
275
- * catalogue-present-but-unwired verb, e.g. litectx's `compress`, must
276
- * refuse before any model call or spend) imports this SAME set rather than
277
- * keeping a second copy of the list. */
278
272
  /** M7: the in-run tools over this run's own store (src/ctx-tools.js). `remember`/`forget` are
279
273
  * deliberately absent: memory lasts one run (PRD: no learning between flows). */
280
274
  const CTX_VERBS = Object.freeze(['recall', 'get', 'recent', 'related', 'impact', 'compress', 'peek', 'stash']);
281
275
 
276
+ /** The verbs this piece actually implements (the switch below, as data) —
277
+ * one writer for "is this verb wired": `resolvePrimitives`'s own reds use
278
+ * it, and `src/runner.js`'s preflight (F46: a step granted a
279
+ * catalogue-present-but-unwired verb must refuse before any model call or
280
+ * spend) imports this SAME set rather than keeping a second copy of the list. */
282
281
  export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'edit', 'readDocx', 'addressCells', ...CTX_VERBS]);
283
282
 
284
283
  /** The wired menu, one place: the catalogue entries whose verb is in
package/src/provider.js CHANGED
@@ -16,10 +16,11 @@
16
16
  // against src/'s ESM style; src never imports from poc/.
17
17
 
18
18
  import {
19
- appendFileSync, mkdirSync,
19
+ mkdirSync,
20
20
  } from 'node:fs';
21
21
  import { dirname, basename } from 'node:path';
22
22
  import { readFileInside } from './flow.js';
23
+ import { appendRow } from './jsonl-append.js';
23
24
  import { readConfig, configDoorHome } from './config.js';
24
25
  import { isKeyName } from './keysfile.js';
25
26
  import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
@@ -273,7 +274,7 @@ export function appendSpendRow(path, row) {
273
274
  }
274
275
  // M4d piece 3: the writer stamps `at` (after the spread: a caller can never set it) so month spend can be read
275
276
  // off each run's own books. Rows written before M4d carry none.
276
- appendFileSync(path, `${JSON.stringify({ ...row, at: new Date().toISOString(), modelMatch })}\n`);
277
+ appendRow(path, { ...row, at: new Date().toISOString(), modelMatch });
277
278
  }
278
279
 
279
280
  // F48 round 3: both readers below take a full path (`<runDir>/spend.jsonl`,
package/src/runner.js CHANGED
@@ -48,7 +48,7 @@ import { resetRunStore } from './run-store.js';
48
48
  import { fileURLToPath } from 'node:url';
49
49
 
50
50
  import {
51
- readFlow, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
51
+ readPlan, readRunPlan, runOwnsPlan, resolveRunDir, readFileInside, readdirInside, resolveInside, FLOW_FILES, PANEL_STARTS_DIR, writeRunJobCopy,
52
52
  } from './flow.js';
53
53
  import {
54
54
  writeAskArchive, readAcceptedHashesByEmits, serializeArtifact, normalizeDecision, answerTiming, effectiveExpiresAt, withReopen, setAsideAnswer,
@@ -993,7 +993,7 @@ export async function runFlow({
993
993
  return { outcome: 'refused', red: runIdCheck.red };
994
994
  }
995
995
 
996
- const read = readFlow({ root, name, catalogue });
996
+ const read = readPlan({ root, name, catalogue, runDir: runIdCheck.runDir });
997
997
  if (!read.ok) {
998
998
  // Negative iv: a flow whose files don't hash to the signature (or is
999
999
  // otherwise unreadable) is refused by name, at $0. No run dir exists to
@@ -1065,7 +1065,7 @@ export async function runFlow({
1065
1065
  mkdirSync(runDir, { recursive: true });
1066
1066
 
1067
1067
  // M6: the run keeps a write-once copy of the job it runs, from before its first step (its Job tab shows this, not the flow's later versions)
1068
- const jobCopy = writeRunJobCopy(flowDir, runDir, signature.flow);
1068
+ const jobCopy = runOwnsPlan(runDir) ? { ok: /** @type {true} */ (true) } : writeRunJobCopy(flowDir, runDir, signature.flow); // am9: a run that keeps its own plan already holds its verified copy
1069
1069
  if (!jobCopy.ok) {
1070
1070
  return haltRun({
1071
1071
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: jobCopy.red, spent: { value: 0 },
@@ -1886,7 +1886,7 @@ export async function resumeRun({
1886
1886
  // below (inside the lock): if this pre-read itself fails, that failure is
1887
1887
  // reported properly by the definitive read further down, under the lock,
1888
1888
  // exactly as before this check existed.
1889
- const preflightRead = readFlow({ root, name, catalogue });
1889
+ const preflightRead = readRunPlan({ root, name, catalogue, runDir });
1890
1890
  if (preflightRead.ok) {
1891
1891
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
1892
1892
  if (unwiredVerb) {
@@ -1949,7 +1949,7 @@ export async function resumeRun({
1949
1949
  };
1950
1950
  }
1951
1951
 
1952
- const read = readFlow({ root, name, catalogue });
1952
+ const read = readRunPlan({ root, name, catalogue, runDir });
1953
1953
  if (!read.ok) {
1954
1954
  return { outcome: 'refused', red: `resume: flow re-read failed for run "${runId}": ${read.reds.join('; ')}` };
1955
1955
  }
@@ -1960,7 +1960,7 @@ export async function resumeRun({
1960
1960
  const { arbiter } = applied;
1961
1961
 
1962
1962
  if (signature.flow !== state.signatureHash) {
1963
- return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — the flow changed while parked` };
1963
+ return { outcome: 'refused', red: `resume: signature mismatch for run "${runId}" — its saved copy of the job is not the job it was parked under` };
1964
1964
  }
1965
1965
 
1966
1966
  for (const entry of state.inputsManifest ?? []) {
@@ -2410,7 +2410,7 @@ export async function continueRun({
2410
2410
  if (!runIdCheck.ok) return { outcome: 'refused', red: runIdCheck.red };
2411
2411
  const runDir = runIdCheck.runDir;
2412
2412
 
2413
- const preflightRead = readFlow({ root, name, catalogue });
2413
+ const preflightRead = readRunPlan({ root, name, catalogue, runDir });
2414
2414
  if (preflightRead.ok) {
2415
2415
  const unwiredVerb = findUnwiredVerbStep(preflightRead.declaration);
2416
2416
  if (unwiredVerb) return refused(unwiredRed(unwiredVerb));
@@ -2437,10 +2437,10 @@ export async function continueRun({
2437
2437
  }
2438
2438
  if (!Number.isInteger(halt.stepIndex) || halt.stepIndex < 0) return refused(`run "${runId}" halt.json field "stepIndex" is not a step number`);
2439
2439
 
2440
- const read = readFlow({ root, name, catalogue });
2440
+ const read = readRunPlan({ root, name, catalogue, runDir });
2441
2441
  if (!read.ok) return refused(`flow re-read failed for run "${runId}": ${read.reds.join('; ')}`);
2442
2442
  const { declaration, signature } = read;
2443
- if (signature.flow !== halt.signatureHash) return refused(`signature mismatch for run "${runId}" — the flow changed while it was halted`);
2443
+ if (signature.flow !== halt.signatureHash) return refused(`signature mismatch for run "${runId}" — its saved copy of the job is not the job it was halted under`);
2444
2444
  // the human's signed values for this run (its highest version): the new cap is read from here, nowhere else
2445
2445
  const applied = applyRunValues(read.arbiter, name, signature.flow, pickRunValues(runDir));
2446
2446
  if (!applied.ok) return refused(`run "${runId}" — ${applied.red}`);
@@ -2638,7 +2638,7 @@ export async function stopParkedRun({
2638
2638
  const audit = auditSpend(runDir);
2639
2639
  if (!audit.ok) return refused(`run "${runId}" ${audit.red}`);
2640
2640
  requestStop(runDir); // 'exists' when the door (or a race) wrote it already
2641
- const read = readFlow({ root, name, catalogue });
2641
+ const read = readRunPlan({ root, name, catalogue, runDir });
2642
2642
  let capUsd = null;
2643
2643
  if (read.ok) {
2644
2644
  const applied = applyRunValues(read.arbiter, name, read.signature.flow, pickRunValues(runDir));
package/src/runvalues.js CHANGED
@@ -53,12 +53,14 @@ export function flowValues(arbiter) {
53
53
  return { capUsd: arbiter.capUsd, destination, askWaits };
54
54
  }
55
55
 
56
- /** @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>}} v the values in canonical key order */
56
+ /** @param {{capUsd: number, destination: string|null, askWaits: Record<string,string>, model?: {slot: string, model: string}|null}} v the values in canonical key order */
57
57
  function canonValues(v) {
58
58
  return {
59
59
  capUsd: v.capUsd,
60
60
  destination: v.destination ?? null,
61
61
  askWaits: Object.fromEntries(Object.entries(v.askWaits ?? {}).sort(([a], [b]) => Number(a) - Number(b))),
62
+ // M6 am5/am6: the model THIS run uses, only when it differs from the flow's recorded one. Absent = no key at all, so every record signed before this keeps its hash.
63
+ ...(v.model ? { model: { slot: v.model.slot, model: v.model.model } } : {}),
62
64
  };
63
65
  }
64
66
 
@@ -79,6 +81,11 @@ export function sameValues(a, b) {
79
81
  return JSON.stringify(canonValues(a)) === JSON.stringify(canonValues(b));
80
82
  }
81
83
 
84
+ /** The model a run was signed to use instead of its flow's recorded one, or null (the flow's). The ONE reader. @param {ReturnType<typeof pickRunValues>} picked */
85
+ export function runModelOf(picked) {
86
+ return picked.ok && !picked.none && picked.record.values.model ? { slot: picked.record.values.model.slot, model: picked.record.values.model.model } : null;
87
+ }
88
+
82
89
  /** File name of a version. @param {number} version */
83
90
  export const valuesFileName = (version) => (version === 0 ? 'signed-values.json' : `signed-values-r${version}.json`);
84
91
 
@@ -126,7 +133,8 @@ export function pickRunValues(runDir) {
126
133
  const shaped = record && typeof record === 'object' && record.version === best.version && typeof record.flow === 'string' && typeof record.flowSignatureHash === 'string'
127
134
  && typeof record.hash === 'string' && v && typeof v === 'object' && Number.isFinite(v.capUsd) && v.capUsd > 0
128
135
  && (v.destination === null || (typeof v.destination === 'string' && v.destination !== ''))
129
- && v.askWaits && typeof v.askWaits === 'object' && Object.values(v.askWaits).every((w) => parseWaitMs(w) !== null);
136
+ && v.askWaits && typeof v.askWaits === 'object' && Object.values(v.askWaits).every((w) => parseWaitMs(w) !== null)
137
+ && (v.model === undefined || (v.model && typeof v.model.slot === 'string' && v.model.slot !== '' && typeof v.model.model === 'string' && v.model.model !== ''));
130
138
  if (!shaped) return { ok: false, red: `signed values: ${best.name} does not have the shape of a signed values record` };
131
139
  const want = valuesHash({
132
140
  flow: record.flow, flowSignatureHash: record.flowSignatureHash, runId: best.version === 0 ? null : (record.runId ?? null), version: best.version, values: v,
@@ -0,0 +1,135 @@
1
+ // M9 amendment 20 (docs/wiki/the-module-ladder.md, SIGNED 2026-10-16): a job's schedule lives in its OWN signed file, `<flow>/schedule.json`,
2
+ // and its queue in ONE file, `<flow>/schedule-ledger.jsonl`, for as long as the job exists. Setting, changing or cancelling a schedule never
3
+ // touches the job or its signature (prose.txt, declaration.json, signature.json are not opened here).
4
+ //
5
+ // borrowed-from: bareloop src/panel/schedules.js@73809db (readSchedule / writeSchedule / dropQueue / sameTarget / removeSchedule), adapted:
6
+ // fwdloop keeps a job's fire OUTCOMES in `triggers.jsonl` (the Audit's words are built from it), so this file's ledger holds only the clock and file rows.
7
+ //
8
+ // ONE WRITER PER FIELD: `writeSchedule` is the only function that writes `schedule.json` (temp + rename: a reader sees the old file or the new one,
9
+ // never half); `removeSchedule` the only one that removes it. `dropQueue` / `carryQueue` are the only places a waiting file leaves a queue because
10
+ // the schedule changed. The signing id (`sig`) is `sha256(bound + signedAt)`: the same schedule signed again after a Cancel is a NEW signing, so rows
11
+ // of the earlier one can never carry over. Every ledger row carries the `sig` that wrote it; "since this signing" is a filter on `sig`.
12
+ import { createHash } from 'node:crypto';
13
+ import { renameSync, rmSync, writeFileSync } from 'node:fs';
14
+ import { isAbsolute, join } from 'node:path';
15
+
16
+ import { readFileInside } from './flow.js';
17
+ import { appendRow } from './jsonl-append.js';
18
+ import { queueOf, readSeen, recordDropped } from './trigger-files.js';
19
+ import { readRows, validateSchedule } from './trigger-clock.js';
20
+ import { triggerHash } from './trigger-line.js';
21
+
22
+ /** @typedef {import('./trigger-line.js').Trigger} Trigger */
23
+ /**
24
+ * @typedef {{
25
+ * v: 1, flow: string, trigger: Trigger, flowSignatureHash: string, bound: string, sig: string, signedBy: string, signedAt: string,
26
+ * model: {slot: string, model: string}|null, destination: string|null, inputs: {role: string, path: string}[]|null,
27
+ * plan: {run: string, flowHash: string, declSha: string}|null, from: string|null,
28
+ * }} Schedule
29
+ */
30
+
31
+ export const SCHEDULE_FILE = 'schedule.json';
32
+ export const LEDGER_FILE = 'schedule-ledger.jsonl';
33
+ /** The words of the am16 row (also for a Cancel): signed text, M9 am16. @param {string} name */
34
+ export const droppedSay = (name) => `${name} was waiting when the schedule changed, so it will not run. Drop it in again to run it.`;
35
+
36
+ /** @param {string} flowDir */
37
+ export const scheduleFileOf = (flowDir) => join(flowDir, SCHEDULE_FILE);
38
+ /** @param {string} flowDir */
39
+ export const ledgerOf = (flowDir) => join(flowDir, LEDGER_FILE);
40
+
41
+ /** @param {string} bound @param {string} signedAt */
42
+ export const sigOf = (bound, signedAt) => createHash('sha256').update(`${bound}\n${signedAt}`).digest('hex');
43
+
44
+ const isFile = (/** @type {any} */ t) => t?.kind === 'new-file' || t?.kind === 'file-updated';
45
+ const str = (/** @type {unknown} */ v) => typeof v === 'string' && v !== '';
46
+
47
+ /** Is this a typed trigger of the five shapes? (the same shapes `trigger-line.js` parses; the schedule file never carries a line) @param {any} t */
48
+ function triggerOk(t) {
49
+ if (!t || typeof t !== 'object') return false;
50
+ if (isFile(t)) return str(t.role) && isAbsolute(String(t.kind === 'new-file' ? t.folder : t.path));
51
+ try { validateSchedule(t); return true; } catch { return false; }
52
+ }
53
+
54
+ /**
55
+ * The job's schedule, or null (no file, unreadable, not the shape, or a file whose own hashes do not check: it was changed after it was signed, so it
56
+ * is not the schedule a human signed and nothing acts on it). Read through the safe gateway.
57
+ * @param {string} flowDir @returns {Schedule|null}
58
+ */
59
+ export function readSchedule(flowDir) {
60
+ const f = readFileInside(flowDir, SCHEDULE_FILE);
61
+ if (!f.ok) return null;
62
+ let o;
63
+ try { o = JSON.parse(f.text); } catch { return null; }
64
+ if (!o || typeof o !== 'object' || o.v !== 1 || !str(o.flow) || !triggerOk(o.trigger) || !str(o.flowSignatureHash) || !str(o.bound) || !str(o.sig) || !str(o.signedBy) || !str(o.signedAt)) return null;
65
+ const optStr = (/** @type {unknown} */ v) => v === null || str(v);
66
+ if (!optStr(o.destination) || !optStr(o.from)) return null;
67
+ if (o.model !== null && !(o.model && str(o.model.slot) && str(o.model.model))) return null;
68
+ if (o.inputs !== null && !(Array.isArray(o.inputs) && o.inputs.every((/** @type {any} */ r) => str(r?.role) && str(r?.path)))) return null;
69
+ if (o.plan !== null && !(o.plan && str(o.plan.run) && str(o.plan.flowHash) && str(o.plan.declSha))) return null;
70
+ const want = triggerHash({
71
+ flow: o.flow, flowSignatureHash: o.flowSignatureHash, trigger: o.trigger, model: o.model, destination: o.destination, inputs: o.inputs, plan: o.plan,
72
+ });
73
+ if (want !== o.bound || sigOf(o.bound, o.signedAt) !== o.sig) return null;
74
+ return /** @type {Schedule} */ (o);
75
+ }
76
+
77
+ /** THE writer of `schedule.json`: atomic (temp file, then rename). @param {string} flowDir @param {Schedule} schedule */
78
+ export function writeSchedule(flowDir, schedule) {
79
+ const file = scheduleFileOf(flowDir);
80
+ const tmp = `${file}.${process.pid}.tmp`;
81
+ writeFileSync(tmp, `${JSON.stringify(schedule, null, 2)}\n`, { mode: 0o600 });
82
+ renameSync(tmp, file);
83
+ }
84
+
85
+ /** The only remover of `schedule.json`. @param {string} flowDir */
86
+ export function removeSchedule(flowDir) {
87
+ rmSync(scheduleFileOf(flowDir), { force: true });
88
+ }
89
+
90
+ /** Does a re-sign keep the same kind and the same folder/file (so the queue and the baseline stand)? @param {Trigger|null|undefined} cur @param {Trigger|null} next */
91
+ export function sameTarget(cur, next) {
92
+ if (!cur || !next || !isFile(cur) || !isFile(next) || cur.kind !== next.kind) return false;
93
+ return cur.kind === 'new-file' ? cur.folder === /** @type {any} */ (next).folder : /** @type {any} */ (cur).path === /** @type {any} */ (next).path;
94
+ }
95
+
96
+ /** Is this signing armed (its `armed` row is in the ledger)? @param {string} flowDir @param {string} sig */
97
+ export const isArmed = (flowDir, sig) => readRows(ledgerOf(flowDir), sig).some((r) => r.kind === 'armed');
98
+
99
+ /**
100
+ * Every file waiting under signing `sig` leaves its queue: one `dropped` row (under `sig`) and ONE row in the outcome file with am16's words. The drop is written
101
+ * BEFORE the row: a crash loses a row, never doubles one. @param {string} flowDir @param {string} sig
102
+ * @param {number} nowMs @param {(row: Record<string, any>) => void} note writes one outcome row
103
+ */
104
+ export function dropQueue(flowDir, sig, nowMs, note) {
105
+ const ledger = ledgerOf(flowDir);
106
+ for (const q of queueOf(readSeen(ledger, sig))) {
107
+ recordDropped(ledger, q, 'schedule-changed', nowMs, sig);
108
+ note({ outcome: 'schedule-changed', file: q.path, sha: q.sha, say: droppedSay(q.name) });
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The folder is the same: signing `to` takes over everything `from` knew about the files (baseline, arrived, ran, dropped, in order), so the queue and
114
+ * the starting point stand. Written BEFORE the new `schedule.json`; the old signing's waiting files are marked `carried` after it (`finishCarry`).
115
+ * @param {string} flowDir @param {string} from @param {string} to
116
+ */
117
+ export function carryQueue(flowDir, from, to) {
118
+ const ledger = ledgerOf(flowDir);
119
+ for (const r of readSeen(ledger, from)) {
120
+ if (!['baseline', 'arrived', 'ran', 'dropped'].includes(r.kind)) continue;
121
+ const { sig: _old, ...row } = r;
122
+ appendRow(ledger, { ...row, sig: to });
123
+ }
124
+ }
125
+
126
+ /** The old signing's files that `carryQueue` copied are no longer its own to run. @param {string} flowDir @param {string} from @param {number} nowMs */
127
+ export function finishCarry(flowDir, from, nowMs) {
128
+ const ledger = ledgerOf(flowDir);
129
+ for (const q of queueOf(readSeen(ledger, from))) recordDropped(ledger, q, 'carried', nowMs, from);
130
+ }
131
+
132
+ /** Cancel's own row in the ledger. @param {string} flowDir @param {string} sig @param {number} nowMs */
133
+ export function recordCancelled(flowDir, sig, nowMs) {
134
+ appendRow(ledgerOf(flowDir), { id: `cancelled:${nowMs}`, kind: 'cancelled', sig, at: nowMs });
135
+ }
package/src/setup.js CHANGED
@@ -112,27 +112,6 @@ export function writeSetup({ flowDir, secrets = [], ...rest }) {
112
112
  }
113
113
  }
114
114
 
115
- /**
116
- * M9 item 2: a trigger-only re-sign signs the same plan under a new flow hash. The old `setup.jsonl` bytes are written back untouched (append-only)
117
- * and ONE row is added: kind `trigger-resign`, the record of the signing it continues (its plan hash and "Not checked" list, copied) under the new
118
- * `flowHash`, naming the old one in `resignOf`. A reader that wants this job's record looks for the row whose `flowHash` is the job's. Never throws.
119
- * @param {{ flowDir: string, oldText: string, oldFlowHash: string, newFlowHash: string, at: string }} a
120
- * @returns {{ ok: true } | { ok: false, red: string }}
121
- */
122
- export function carrySetup({ flowDir, oldText, oldFlowHash, newFlowHash, at }) {
123
- try {
124
- const rows = oldText.split('\n').filter(Boolean).map((l) => { try { return JSON.parse(l); } catch { return null; } }).filter(Boolean);
125
- const signs = rows.filter((r) => r.kind === 'sign' || r.kind === 'trigger-resign');
126
- const from = signs.findLast((r) => r.flowHash === oldFlowHash) ?? signs.at(-1);
127
- const keep = oldText.endsWith('\n') ? oldText : `${oldText}\n`;
128
- const extra = from ? `${JSON.stringify({ ...from, kind: 'trigger-resign', at, flowHash: newFlowHash, resignOf: oldFlowHash })}\n` : '';
129
- writeFileSync(join(flowDir, SETUP_FILE), keep + extra, { flag: 'wx', mode: 0o600 });
130
- return { ok: true };
131
- } catch (err) {
132
- return { ok: false, red: `setup: could not carry ${SETUP_FILE} over (${err.code ?? err.message})` };
133
- }
134
- }
135
-
136
115
  /**
137
116
  * The flow's setup rows, through the one safe gateway. `present:false` = a flow signed before amendment 6 (or a file that cannot be read).
138
117
  * @param {string} flowDir