fwdloop 0.16.0 → 0.18.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 (64) hide show
  1. package/README.md +2 -0
  2. package/bin/fwdloop +10 -7
  3. package/package.json +1 -1
  4. package/src/authoring.js +6 -6
  5. package/src/books.js +6 -1
  6. package/src/catalogue.json +9 -3
  7. package/src/ctx-tools.js +245 -0
  8. package/src/draft-steps.js +89 -30
  9. package/src/drafter.js +28 -4
  10. package/src/draftspend.js +109 -3
  11. package/src/liveness.js +34 -10
  12. package/src/panel/author.js +125 -37
  13. package/src/panel/authorcard.js +15 -10
  14. package/src/panel/authorflows.js +9 -3
  15. package/src/panel/authorresume.js +5 -4
  16. package/src/panel/authorstart.js +21 -9
  17. package/src/panel/authortrigger.js +384 -0
  18. package/src/panel/authorvalues.js +5 -3
  19. package/src/panel/data.js +104 -16
  20. package/src/panel/index.html +257 -44
  21. package/src/panel/scheduler.js +125 -0
  22. package/src/panel/server.js +24 -10
  23. package/src/panel/settings.js +2 -2
  24. package/src/plain-checks.js +51 -0
  25. package/src/primitives.js +34 -3
  26. package/src/provider.js +17 -8
  27. package/src/run-store.js +47 -0
  28. package/src/runner.js +2 -0
  29. package/src/runvalues.js +5 -3
  30. package/src/setup.js +24 -0
  31. package/src/signed-text.js +26 -0
  32. package/src/summary-words.js +155 -0
  33. package/src/trigger-clock.js +142 -0
  34. package/src/trigger-files.js +212 -0
  35. package/src/trigger-line.js +86 -0
  36. package/src/types.js +1 -0
  37. package/src/version.js +13 -0
  38. package/types/authoring.d.ts +1 -3
  39. package/types/ctx-tools.d.ts +18 -0
  40. package/types/draft-steps.d.ts +38 -5
  41. package/types/drafter.d.ts +3 -3
  42. package/types/draftspend.d.ts +56 -0
  43. package/types/liveness.d.ts +7 -1
  44. package/types/panel/author.d.ts +149 -146
  45. package/types/panel/authorcard.d.ts +12 -2
  46. package/types/panel/authorflows.d.ts +11 -3
  47. package/types/panel/authorstart.d.ts +7 -4
  48. package/types/panel/authortrigger.d.ts +210 -0
  49. package/types/panel/authorvalues.d.ts +3 -1
  50. package/types/panel/data.d.ts +14 -7
  51. package/types/panel/scheduler.d.ts +15 -0
  52. package/types/panel/server.d.ts +11 -3
  53. package/types/plain-checks.d.ts +22 -0
  54. package/types/primitives.d.ts +0 -6
  55. package/types/provider.d.ts +7 -1
  56. package/types/run-store.d.ts +11 -0
  57. package/types/runvalues.d.ts +1 -1
  58. package/types/setup.d.ts +27 -0
  59. package/types/summary-words.d.ts +53 -0
  60. package/types/trigger-clock.d.ts +60 -0
  61. package/types/trigger-files.d.ts +90 -0
  62. package/types/trigger-line.d.ts +44 -0
  63. package/types/types.d.ts +4 -0
  64. package/types/version.d.ts +2 -0
@@ -0,0 +1,125 @@
1
+ // M9 piece 4 (docs/wiki/the-module-ladder.md, "M9" item 3): the panel's scheduler. The panel's server runs the clock and the file watch; with
2
+ // the panel off, nothing fires, and the times missed run ONCE when it comes back (`due` collapses them, marked catch-up).
3
+ //
4
+ // ONE `tick()` does everything and is synchronous; the tests call it by hand with an injected clock. The real timer only calls it.
5
+ // tick period 500 ms: the file watch needs a file's size and mtime to hold for STABLE_POLLS (2) polls before it is taken, so a drop is
6
+ // seen about 1.5 s after it stops changing; the proof of piece 2 polled at 250 ms and found nothing that needed faster. The clock fires
7
+ // to the minute and would do with a tick a minute apart, but one timer is one fewer moving part; a tick that finds no trigger set reads
8
+ // each job's signed files (small, hash-checked) and does no more.
9
+ // No leaked timer: `start` is idempotent, the timer is unref'd, and the server's close calls `stop`.
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.
15
+ // 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
+ import { due, readRows, recordFire } from '../trigger-clock.js';
19
+ import {
20
+ createFileTrigger, queueOf, readSeen, recheck, recordArrived, recordDropped, recordRan,
21
+ } from '../trigger-files.js';
22
+ import { readOutcomes, triggerLedgerDir } from './authortrigger.js';
23
+
24
+ /**
25
+ * @param {{ door: ReturnType<typeof import('./authortrigger.js').createTriggerDoor>, now?: () => number, intervalMs?: number }} opts
26
+ * `intervalMs` 0 = no timer (a test drives `tick`).
27
+ */
28
+ export function createScheduler(opts) {
29
+ const { door, now = Date.now, intervalMs = 500 } = opts;
30
+ /** @type {Map<string, ReturnType<typeof createFileTrigger>>} */
31
+ const watchers = new Map();
32
+ /** @type {Set<string>} refusals already written, so a folder that stays gone is told once, not every tick */
33
+ const told = new Set();
34
+ /** @type {ReturnType<typeof setInterval>|null} */
35
+ let timer = null;
36
+
37
+ /**
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
+ * 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.
41
+ * @param {any} job @param {string} ledger @param {number} nowMs
42
+ */
43
+ function runQueue(job, ledger, nowMs) {
44
+ let queue = queueOf(readSeen(ledger));
45
+ 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 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; };
49
+ if (door.busy(job)) {
50
+ for (const q of queue) door.fire(job, cause(q), { told: told(q) });
51
+ return;
52
+ }
53
+ while (queue.length > 0) {
54
+ const q = queue[0];
55
+ const seen = recheck(q);
56
+ if (seen.state !== 'ok') {
57
+ const why = seen.state === 'deleted' ? 'deleted' : 'changed';
58
+ recordDropped(ledger, q, why, nowMs);
59
+ door.note(job, {
60
+ 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
+ });
62
+ queue = queue.slice(1);
63
+ continue;
64
+ }
65
+ door.fire(job, cause({ ...q, path: seen.path }), { told: told(q), beforeStart: () => recordRan(ledger, seen, nowMs) });
66
+ return;
67
+ }
68
+ }
69
+
70
+ function tick() {
71
+ const nowMs = now();
72
+ const live = new Set();
73
+ for (const job of door.scan()) {
74
+ const hash = job.read.signature.flow;
75
+ const key = `${job.flow}|${hash}`;
76
+ live.add(key);
77
+ try {
78
+ door.ensureArmed(job);
79
+ const dir = triggerLedgerDir(job.flowDir, hash);
80
+ const { trigger } = job;
81
+ if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
82
+ let w = watchers.get(key);
83
+ if (!w) {
84
+ w = createFileTrigger({
85
+ mode: trigger.kind === 'new-file' ? 'new' : 'updated', target: trigger.kind === 'new-file' ? trigger.folder : trigger.path, ledger: join(dir, 'seen.jsonl'),
86
+ });
87
+ watchers.set(key, w);
88
+ }
89
+ const ledger = join(dir, 'seen.jsonl');
90
+ const { arrived, refused } = w.poll();
91
+ 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
+ runQueue(job, ledger, nowMs);
94
+ } else {
95
+ const clock = join(dir, 'clock.jsonl');
96
+ const d = due(trigger, readRows(clock), nowMs);
97
+ if (d.fire) {
98
+ recordFire(clock, d, nowMs); // BEFORE the fire: a crash loses a run, never doubles one
99
+ door.fire(job, {
100
+ kind: 'clock', slot: /** @type {number} */ (d.slot), catchUp: d.catchUp, missed: d.missed,
101
+ });
102
+ }
103
+ }
104
+ } catch (e) {
105
+ const why = /** @type {Error} */ (e).message;
106
+ if (!told.has(`${key}|${why}`)) { told.add(`${key}|${why}`); door.refuse(job, why); }
107
+ }
108
+ }
109
+ for (const k of [...watchers.keys()]) if (!live.has(k)) watchers.delete(k);
110
+ }
111
+
112
+ return {
113
+ tick,
114
+ /** Start the real timer (idempotent). */
115
+ start() {
116
+ if (intervalMs <= 0 || timer !== null) return;
117
+ timer = setInterval(() => { try { tick(); } catch { /* one bad tick never stops the next */ } }, intervalMs);
118
+ timer.unref();
119
+ },
120
+ /** Stop it (idempotent). The server's close calls this. */
121
+ stop() {
122
+ if (timer !== null) { clearInterval(timer); timer = null; }
123
+ },
124
+ };
125
+ }
@@ -48,6 +48,8 @@
48
48
 
49
49
  import { createServer } from 'node:http';
50
50
  import { readFileSync, realpathSync } from 'node:fs';
51
+ import { pageRules } from '../plain-checks.js';
52
+ import { readOwnVersion } from '../version.js';
51
53
  import path, { dirname, join } from 'node:path';
52
54
  import { fileURLToPath } from 'node:url';
53
55
 
@@ -60,6 +62,7 @@ import {
60
62
  listRuns, getRunDetail, getRunControls, getRunAudit, getRunJob, listStops, inboxOpenCount, getRunAsks, readSavedAnswer, hasConsumedAnswer, resolveFlowDir,
61
63
  } from './data.js';
62
64
  import { createResumer } from './resume.js';
65
+ import { createScheduler } from './scheduler.js';
63
66
  import { createAuthor } from './author.js';
64
67
  import { keysForDoor } from '../keysfile.js';
65
68
  import { configDoorHome } from '../config.js';
@@ -319,7 +322,7 @@ function resumeRoute(res, body, root, resumer) {
319
322
  }
320
323
 
321
324
  /**
322
- * `POST /api/author/{draft,run,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/answer,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
325
+ * `POST /api/author/{draft,run,trigger-prepare,trigger,resume-prepare,resume,<id>/sign-prepare,<id>/sign,<id>/revise,<id>/answer,<id>/abandon,start/<id>/clear}` — run after the same gates as every other POST.
323
326
  * Anything else under `/api/author/` is a 404 by name.
324
327
  * @param {any} res @param {string} url @param {any} body @param {ReturnType<typeof createAuthor>} author
325
328
  */
@@ -328,6 +331,8 @@ function authorPost(res, url, body, author) {
328
331
  if (url === '/api/author/draft') { send(author.start(body)); return; }
329
332
  if (url === '/api/author/run') { send(author.run(body)); return; }
330
333
  if (url === '/api/author/run-prepare') { send(author.runPrepare(body)); return; }
334
+ if (url === '/api/author/trigger-prepare') { send(author.trigger.prepare(body)); return; }
335
+ if (url === '/api/author/trigger') { send(author.trigger.set(body)); return; }
331
336
  if (url === '/api/author/resume-prepare') { send(author.resumePrepare(body)); return; }
332
337
  if (url === '/api/author/resume') { send(author.resume(body)); return; }
333
338
  const sp = /^\/api\/author\/([^/]+)\/sign-prepare$/.exec(url);
@@ -351,7 +356,7 @@ function authorPost(res, url, body, author) {
351
356
  * real listening socket where that is simpler.
352
357
  * @param {import('node:http').IncomingMessage} req
353
358
  * @param {import('node:http').ServerResponse} res
354
- * @param {{ root: string, port: number, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor> }} opts
359
+ * @param {{ root: string, port: number, packagePath?: string, resumer: ReturnType<typeof createResumer>, settings: ReturnType<typeof createSettings>, author: ReturnType<typeof createAuthor>, now?: () => number }} opts
355
360
  */
356
361
  export function handleRequest(req, res, opts) {
357
362
  const method = req.method ?? 'GET';
@@ -456,7 +461,7 @@ export function handleRequest(req, res, opts) {
456
461
  if (pathname === '/api/author/live') r = opts.author.live();
457
462
  else if (pathname === '/api/author/flows') r = opts.author.flows();
458
463
  else if (pathname === '/api/author/run-again') r = opts.author.runAgain(url.searchParams.get('flow'), url.searchParams.get('runId'));
459
- else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'), { provider: url.searchParams.get('provider') ?? undefined, model: url.searchParams.get('model') ?? undefined, flow: url.searchParams.get('flow') ?? undefined });
464
+ else if (pathname === '/api/author/monthly-check') r = opts.author.monthlyCheck(url.searchParams.get('cap'), url.searchParams.get('spent'), { provider: url.searchParams.get('provider') ?? undefined, model: url.searchParams.get('model') ?? undefined, flow: url.searchParams.get('flow') ?? undefined }, url.searchParams.get('kind') ?? 'drafting', url.searchParams.get('draft'));
460
465
  else if (pathname === '/api/author/models') r = opts.author.models();
461
466
  else if (pathname === '/api/author/resume-form') r = opts.author.resumeForm(url.searchParams.get('flow'), url.searchParams.get('runId'));
462
467
  else if (sm) r = opts.author.startGet(sm[1]);
@@ -483,6 +488,9 @@ export function handleRequest(req, res, opts) {
483
488
  return;
484
489
  }
485
490
  html = html.replace(/__FWDLOOP_PANEL_PORT__/g, String(opts.port));
491
+ const version = readOwnVersion(opts.packagePath); // M4d am17: the header's number, read from fwdloop's own package.json at serve time
492
+ html = version === null ? html.replace(/v__FWDLOOP_VERSION__/g, 'version unknown').replace(/__FWDLOOP_VERSION__/g, '') : html.replace(/__FWDLOOP_VERSION__/g, version);
493
+ html = html.replace(/__FWDLOOP_PLAN_CHECK_RULES__/g, () => JSON.stringify(pageRules())); // M4d am15: the one copy of the plain words
486
494
  if (method === 'HEAD') {
487
495
  res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'content-length': Buffer.byteLength(html) });
488
496
  res.end();
@@ -500,15 +508,16 @@ export function handleRequest(req, res, opts) {
500
508
  }
501
509
  const catalogue = loaded.primitives;
502
510
  const resumeAttempt = (f, r) => opts.resumer.get(f, r);
511
+ const startingRun = (f, r) => opts.author?.startingRun?.(f, r) === true;
503
512
 
504
513
  if (pathname === '/api/runs') {
505
- send(200, { rows: listRuns({ root: opts.root, catalogue, resumeAttempt }) });
514
+ send(200, { rows: listRuns({ root: opts.root, catalogue, resumeAttempt, startingRun }) });
506
515
  return;
507
516
  }
508
517
 
509
518
  if (pathname === '/api/inbox') {
510
519
  const rows = listStops({ root: opts.root, resumeAttempt, catalogue });
511
- send(200, { rows, openCount: inboxOpenCount(rows) });
520
+ send(200, { rows, openCount: inboxOpenCount(rows), version: readOwnVersion(opts.packagePath) }); // M4d am18: the page compares it with the version it was served with
512
521
  return;
513
522
  }
514
523
 
@@ -554,7 +563,7 @@ export function handleRequest(req, res, opts) {
554
563
  return;
555
564
  }
556
565
  const result = getRunDetail({
557
- root: opts.root, flow, runId, catalogue, resumeAttempt,
566
+ root: opts.root, flow, runId, catalogue, resumeAttempt, startingRun, triggerRead: (f) => opts.author?.trigger?.read(f) ?? null, now: opts.now,
558
567
  });
559
568
  if (!result) { sendText(res, 404, 'no such run'); return; }
560
569
  send(200, result);
@@ -570,9 +579,9 @@ export function handleRequest(req, res, opts) {
570
579
  * header). Resolves once actually listening; rejects on a bind error
571
580
  * (including `EADDRINUSE`) with a `.port` field on the error for the
572
581
  * caller's message.
573
- * @param {{ port?: number, root: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string } }} opts
582
+ * @param {{ port?: number, root: string, packagePath?: string, settings?: { home?: string, env?: Record<string,string|undefined>, fetch?: typeof fetch, now?: () => number, openFolderSpawn?: Function, platform?: string }, resume?: { env?: Record<string,string|undefined>, bin?: string, logDir?: string, maxTries?: number, windowMs?: number, slotMs?: number }, author?: { env?: Record<string,string|undefined>, loadEnv?: () => any, bin?: string, now?: () => number }, scheduler?: { intervalMs?: number } }} opts
574
583
  * `resume` and `author` are for tests only (a fake env/bin, a short retry window); the CLI passes none.
575
- * @returns {Promise<{ server: import('node:http').Server, port: number, close: () => Promise<void> }>}
584
+ * @returns {Promise<{ server: import('node:http').Server, port: number, tick: () => void, close: () => Promise<void> }>}
576
585
  */
577
586
  export function createPanelServer(opts) {
578
587
  if (typeof opts?.root !== 'string' || opts.root.length === 0) {
@@ -589,6 +598,9 @@ export function createPanelServer(opts) {
589
598
  const author = createAuthor({
590
599
  root, home: opts.settings?.home ?? door.home, skipMonthly: opts.settings?.home === undefined && door.skip, loadEnv: () => keysForDoor({ env: opts.author?.env }), ...opts.author,
591
600
  });
601
+ // M9: the scheduler runs the clock and the file watch while this server is up (item 3). The clock is the author's `now` (tests inject one);
602
+ // `scheduler.intervalMs` 0 = no timer, a test calls `tick`. Stopped on close.
603
+ const scheduler = createScheduler({ door: author.trigger, now: opts.author?.now, intervalMs: opts.scheduler?.intervalMs });
592
604
  // Settings reads and writes only under the one config home: an injected one (tests), else the door's — under a test
593
605
  // process with no FWDLOOP_CONFIG_HOME, Settings is switched off rather than touch the real ~/.config/fwdloop.
594
606
  const settings = createSettings({
@@ -604,7 +616,7 @@ export function createPanelServer(opts) {
604
616
  const server = createServer((req, res) => {
605
617
  try {
606
618
  handleRequest(req, res, {
607
- root, port: boundPort, resumer, settings, author,
619
+ root, port: boundPort, resumer, settings, author, packagePath: opts.packagePath, now: opts.author?.now,
608
620
  });
609
621
  } catch (e) {
610
622
  sendText(res, 500, 'internal error');
@@ -618,10 +630,12 @@ export function createPanelServer(opts) {
618
630
  server.listen(requestedPort, '127.0.0.1', () => {
619
631
  const addr = server.address();
620
632
  boundPort = typeof addr === 'object' && addr !== null ? addr.port : requestedPort;
633
+ scheduler.start();
621
634
  resolve({
622
635
  server,
623
636
  port: boundPort,
624
- close: () => new Promise((res2) => { server.close(() => res2(undefined)); }),
637
+ tick: scheduler.tick,
638
+ close: () => new Promise((res2) => { scheduler.stop(); server.close(() => res2(undefined)); }),
625
639
  });
626
640
  });
627
641
  });
@@ -53,8 +53,8 @@ export function createSettings(cfg) {
53
53
  const notKeyName = (slot) => (typeof slot === 'string' && slot !== '' && !isKeyName(slot)
54
54
  ? refuse('not-a-key-name', `${slot} is not a key name. A key name ends in _KEY, like MY_API_KEY. Nothing was saved.`) : null);
55
55
 
56
- /** The row named by a request, or null: only a key that is in the keys file (or the shell) is a row. @param {unknown} slot */
57
- const slotOf = (slot) => (isKeyName(slot) && rowNames(keys()).includes(slot) ? slot : null);
56
+ /** The row named by a request, or null: only a key that is in the keys file (or the shell) is a row. @param {any} slot */
57
+ const slotOf = (slot) => (rowNames(keys()).includes(slot) ? slot : null);
58
58
 
59
59
  /** config.json, or `{problem}` in plain words when it is broken (never read as "nothing set"). */
60
60
  function config() {
@@ -0,0 +1,51 @@
1
+ // M4d amendment 15: the plain words for a plan-check refusal. ONE copy of them: the Chat list (src/draft-steps.js), the Audit Draft rows
2
+ // (src/panel/data.js) and the page (the server hands it the same rules in index.html, see src/panel/server.js) all read this file.
3
+ // Moved here from the page's `plainPlanCheck` (M4e am41 item 7), sentences unchanged.
4
+ //
5
+ // `say` is the plain sentence(s) the page's revise lines show. `reason` is `say` without its fix. `fix` is the one short sentence that tells the human what to
6
+ // change (the job line, the guardrail, the inputs, the destination) or to Draft again when it is the AI's own form error; every rule has one (am15 item 3).
7
+ // The first two rules' `say` already ends with their fix, as the page has always shown them.
8
+
9
+ /** @type {ReadonlyArray<{re: RegExp, say: string|null, fix: string}>} `say` null = the checker's own sentence, as it is without its "declaration: " prefix */
10
+ export const PLAN_CHECK_RULES = Object.freeze([
11
+ { re: /which is not in the job line's words/, say: "A section name in the plan's check is not in your job line. Change the job line to use the section words you want.", fix: 'Change the job line to use the section words you want.' },
12
+ { re: /the job line says .*; the check says/, say: "The sections in the plan's check come in a different order than your job line. Change the job line to change the order.", fix: 'Change the job line to change the order.' },
13
+ { re: /the guardrail says \d+ sections; the check has/, say: "The number of sections in your guardrail is not the number in the plan's check.", fix: 'Make the guardrail and the job line say the same number of sections, then Draft again.' },
14
+ { re: /section name is a short phrase|which is the job line or most of it/, say: "A section name in the plan's check is too long; it must be a short phrase from your job line.", fix: 'Use a short phrase from your job line for each section, then Draft again.' },
15
+ { re: /one section name may not contain another/, say: 'One section name in the plan\'s check contains another, which cannot be checked.', fix: 'Rename the sections in your job line so none contains another, then Draft again.' },
16
+ { re: /wordsPerSection/, say: "The words for each section in your guardrail and in the plan's check do not match.", fix: 'Give each section one clear number of words in your guardrail, then Draft again.' },
17
+ { re: /work as a pair/, say: "The plan's check has one part of a pair without the other, so it cannot be checked.", fix: 'Draft again; if it repeats, simplify the guardrail on that line.' },
18
+ { re: /is blank|characters; the most one entry|ends in ":"/, say: "A name in the plan's check is empty, too long or ends in a colon, so it cannot be matched.", fix: 'Shorten the section names in your job line, then Draft again.' },
19
+ { re: /cannot be built into a check/, say: "The plan's check cannot be built from what the AI wrote.", fix: 'Draft again; if it repeats, simplify the guardrail on that line.' },
20
+ { re: /is not its signed line/, say: 'A step does not use your job line word for word as its goal.', fix: 'Draft again.' },
21
+ { re: /not in the catalogue|not wired|which is not signed|checkpoint/, say: 'A step uses a tool that is not available for this job.', fix: 'Draft again; if it repeats, say in the job line what that step should do.' },
22
+ { re: /reads artifact|is a duplicate|\.reads must|\.emits must/, say: 'The steps do not pass their results to each other in a workable order.', fix: 'Draft again.' },
23
+ { re: /ask at line \d+|signed ask at line|ask slot/, say: 'The ask on one of your lines is not set up as a plain stop where you decide.', fix: 'Check the line that starts with Ask in your job, then Draft again.' },
24
+ { re: /send at line \d+|signed send at line|send slot/, say: 'The send step is not set up to follow your accept and write only to your destination.', fix: 'Check the Destination on the card, then Draft again.' },
25
+ { re: /hitl after the last signed ask/, say: 'A step after your last ask would leave without your seeing it, so it is refused.', fix: 'Move the lines you want to check before your last Ask line, then Draft again.' },
26
+ { re: /is a pause .* unsigned line/, say: 'A step pauses at a line you did not sign as an ask.', fix: 'Mark the line you want to stop at with Ask, then Draft again.' },
27
+ { re: /neither served by any step/, say: 'A line of your job is not covered by any step.', fix: 'Make every line of your job say one thing to do, then Draft again.' },
28
+ { re: /picks|inputFacts|invented name/, say: 'The plan names a field that is not in your input.', fix: 'Check the names in your Inputs and job line, then Draft again.' },
29
+ { re: /guardrailClasses|unjudgeable|refused/, say: "The AI's notes on which lines it can check are not in a form the checker accepts.", fix: 'Draft again.' },
30
+ { re: /^line \d+'s (guardrail|check)|can't write files/, say: null, fix: 'Change the guardrail on that line the way the sentence says, then Draft again.' },
31
+ { re: /must be an? |is required|must name|does not name/, say: 'The plan the AI wrote is not in the shape the checker needs.', fix: 'Draft again.' },
32
+ ]);
33
+
34
+ export const GENERIC_SAY = 'One of the checks on the plan failed.';
35
+ export const GENERIC_FIX = 'Draft again.';
36
+
37
+ /** The rules as the page takes them: JSON, the regex as its source text. */
38
+ export const pageRules = () => PLAN_CHECK_RULES.map((r) => ({ re: r.re.source, say: r.say }));
39
+
40
+ /**
41
+ * @param {unknown} raw one raw refusal text
42
+ * @returns {{ say: string, reason: string, fix: string, raw: string }}
43
+ */
44
+ export function plainPlanCheck(raw) {
45
+ const text = typeof raw === 'string' ? raw : '';
46
+ const rule = PLAN_CHECK_RULES.find((r) => r.re.test(text));
47
+ const say = rule === undefined ? GENERIC_SAY : (rule.say === null ? text.replace(/^declaration: /, '') : rule.say);
48
+ const fix = rule === undefined ? GENERIC_FIX : rule.fix;
49
+ const reason = (say.endsWith(fix) ? say.slice(0, -fix.length) : say).trim().replace(/\.$/, '');
50
+ return { say, reason, fix, raw: text };
51
+ }
package/src/primitives.js CHANGED
@@ -31,6 +31,7 @@ import { Gate } from 'bareguard';
31
31
  import { primitiveFor, loadCatalogue } from './catalogue.js';
32
32
  import { readDocxText } from './docx.js';
33
33
  import { parseCsv } from './csv.js';
34
+ import { makeCtxTools } from './ctx-tools.js';
34
35
 
35
36
  // bare-agent >=0.47.0: `noFollowSymlinks: true` makes shell_read/write/edit/
36
37
  // grep throw `err.code === 'ELOOP'` when the path's FINAL component is a
@@ -80,7 +81,8 @@ async function resolveAndGate(gate, verb, tool, runDir, rawPath) {
80
81
  }
81
82
  const joined = (rawPath.startsWith('~') || path.isAbsolute(rawPath)) ? rawPath : path.join(runDir, rawPath);
82
83
  const resolved = resolveToolPath(joined);
83
- const type = verb === 'write' ? 'write' : 'read';
84
+ // `edit` is judged as bareguard's own 'edit' action type: the SAME fs.writeScope fence as `write` (M7 item 3)
85
+ const type = verb === 'write' || verb === 'edit' ? verb : 'read';
84
86
  const decision = await gate.check({ type, tool, path: resolved });
85
87
  if (decision.outcome !== 'allow') {
86
88
  throw new GateRefusal(verb, resolved, decision.rule);
@@ -214,6 +216,20 @@ function sandboxedWriteTool(gate, runDir, outDir) {
214
216
  };
215
217
  }
216
218
 
219
+ function sandboxedEditTool(gate, runDir) {
220
+ const real = shellTool('shell_edit');
221
+ return {
222
+ name: 'edit',
223
+ description: `${real.description} Sandboxed exactly like write: only files under <runDir>/out can be edited; `
224
+ + 'the run records and the frozen inputs are never editable.',
225
+ parameters: real.parameters,
226
+ execute: async (args) => {
227
+ const resolvedPath = await resolveAndGate(gate, 'edit', 'edit', runDir, args?.path);
228
+ return real.execute({ ...args, path: resolvedPath });
229
+ },
230
+ };
231
+ }
232
+
217
233
  /** `readDocx`/`addressCells` take a `role` naming one of the run's frozen
218
234
  * inputs (never a raw path — the model is never handed a filesystem path
219
235
  * to type back, so there is nothing to sandbox-check on the way in). */
@@ -259,7 +275,11 @@ function addressCellsPrimitiveTool(inputsByRole) {
259
275
  * catalogue-present-but-unwired verb, e.g. litectx's `compress`, must
260
276
  * refuse before any model call or spend) imports this SAME set rather than
261
277
  * keeping a second copy of the list. */
262
- export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'readDocx', 'addressCells']);
278
+ /** M7: the in-run tools over this run's own store (src/ctx-tools.js). `remember`/`forget` are
279
+ * deliberately absent: memory lasts one run (PRD: no learning between flows). */
280
+ const CTX_VERBS = Object.freeze(['recall', 'get', 'recent', 'related', 'impact', 'compress', 'peek', 'stash']);
281
+
282
+ export const WIRED_VERBS = new Set(['read', 'grep', 'write', 'edit', 'readDocx', 'addressCells', ...CTX_VERBS]);
263
283
 
264
284
  /** The wired menu, one place: the catalogue entries whose verb is in
265
285
  * WIRED_VERBS (and, when `skills` is given, in a signed skill). Absence,
@@ -308,6 +328,13 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
308
328
 
309
329
  const tools = {};
310
330
  const reds = [];
331
+ // Built on demand, once: nothing is opened or created here (the store is opened per call, inside a tool).
332
+ // A path a tool names goes through the SAME read gate as `read` before litectx sees it.
333
+ let ctxTools;
334
+ const ctxTool = (verb) => {
335
+ ctxTools ??= makeCtxTools({ runDir, gatePath: (v, rawPath) => resolveAndGate(gate, v, v, runDir, rawPath) });
336
+ return ctxTools[verb];
337
+ };
311
338
 
312
339
  for (const verb of grantedVerbs ?? []) {
313
340
  const entry = primitiveFor(catalogue, verb);
@@ -338,6 +365,9 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
338
365
  // even for a run `runFlow` goes on to refuse.
339
366
  tools.write = sandboxedWriteTool(gate, runDir, outDir);
340
367
  break;
368
+ case 'edit':
369
+ tools.edit = sandboxedEditTool(gate, runDir);
370
+ break;
341
371
  case 'readDocx':
342
372
  tools.readDocx = readDocxPrimitiveTool(inputsByRole);
343
373
  break;
@@ -345,7 +375,8 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
345
375
  tools.addressCells = addressCellsPrimitiveTool(inputsByRole);
346
376
  break;
347
377
  default:
348
- reds.push(`primitives: verb "${verb}" is in the catalogue but has no M2 implementation yet`);
378
+ if (CTX_VERBS.includes(verb)) tools[verb] = ctxTool(verb);
379
+ else reds.push(`primitives: verb "${verb}" is in the catalogue but has no M2 implementation yet`);
349
380
  }
350
381
  }
351
382
 
package/src/provider.js CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  import { dirname, basename } from 'node:path';
22
22
  import { readFileInside } from './flow.js';
23
23
  import { readConfig, configDoorHome } from './config.js';
24
+ import { isKeyName } from './keysfile.js';
24
25
  import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
25
26
 
26
27
  /**
@@ -54,9 +55,11 @@ class MalformedToolCallTolerantOpenAI extends OpenAI {
54
55
  /** The API shape a row has until one is picked in Settings: the wire protocol most providers speak (a shape is a protocol, not a provider). */
55
56
  const DEFAULT_SHAPE = 'openai-api';
56
57
 
57
- /** A provider row is named by its key's env name (M4d amendment 6): letters, digits, underscore; not a place, not a model. */
58
- const KEY_NAME_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
59
- export const isKeyName = (v) => typeof v === 'string' && KEY_NAME_RE.test(v);
58
+ /** A provider row is named by its key's env name (M4d amendment 6). M4d am21 item 4: ONE rule for what that name may be, `isKeyName` in src/keysfile.js (`…_KEY` in
59
+ * capitals): the same gate the keys file, the env pass-through and the log scrubber use, so a key a run can use is always one the scrubber knows. */
60
+ export { isKeyName };
61
+ /** The sentence part every refusal of a non-key name carries, so the rule is named wherever it is refused. */
62
+ export const KEY_NAME_RULE_SAY = 'a key name is written in capitals and ends in _KEY';
60
63
 
61
64
  /**
62
65
  * THE one lookup of a row's API shape, address and legacy-token tick (M4d amendment 6). A row IS its key's env name, so the slot name and the
@@ -68,7 +71,7 @@ export const isKeyName = (v) => typeof v === 'string' && KEY_NAME_RE.test(v);
68
71
  * @returns {{ slot: string, envVar: string, legacyMaxTokens: boolean, shape: string, baseUrl: string }}
69
72
  */
70
73
  export function resolveSlot(slotName, { config = {} } = {}) {
71
- if (!isKeyName(slotName)) throw new Error(`unknown provider "${slotName}" — a provider is the name of a key in your keys file`);
74
+ if (!isKeyName(slotName)) throw new Error(`unknown provider "${slotName}" — a provider is the name of a key in your keys file; ${KEY_NAME_RULE_SAY}`);
72
75
  const saved = (config.providers && Object.hasOwn(config.providers, slotName)) ? config.providers[slotName] : {};
73
76
  const shape = saved.shape ?? DEFAULT_SHAPE;
74
77
  return {
@@ -284,7 +287,7 @@ export function appendSpendRow(path, row) {
284
287
  // (M4d: forward only — today's Settings price never re-prices an old row). A row that recorded no price at all (an
285
288
  // old row; the code table that once priced it is gone, M4d amendment 5) has no ceiling to add: 0 here, and the row
286
289
  // stays `complete: false`, so every total that holds it reads "at least", never as a clean figure.
287
- function rowCeilingUsd(row) {
290
+ export function rowCeilingUsd(row) {
288
291
  const p = row.price;
289
292
  if (p && typeof p === 'object' && Number.isFinite(p.inPerM) && p.inPerM > 0 && Number.isFinite(p.outPerM) && p.outPerM > 0) {
290
293
  return (CEILING_INPUT_TOKENS / 1e6) * p.inPerM + (CEILING_OUTPUT_TOKENS / 1e6) * p.outPerM;
@@ -292,6 +295,11 @@ function rowCeilingUsd(row) {
292
295
  return 0;
293
296
  }
294
297
 
298
+ /** How many calls of an incomplete row were never metered (at least one). @param {any} row */
299
+ export function unmeteredCalls(row) {
300
+ return Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
301
+ }
302
+
295
303
  /**
296
304
  * The one rule for what a spend row costs: `usd` and whether it is `complete`. An incomplete row (a call
297
305
  * died unmetered, or a round was left unpriced) counts its priced floor PLUS one ceiling per unmetered call
@@ -301,7 +309,7 @@ function rowCeilingUsd(row) {
301
309
  */
302
310
  export function spendRowCost(row) {
303
311
  if (row.spendComplete === false) {
304
- const unmetered = Number.isInteger(row.calls) && Number.isInteger(row.rounds) ? Math.max(1, row.calls - row.rounds) : 1;
312
+ const unmetered = unmeteredCalls(row);
305
313
  return { usd: (row.costUsd ?? 0) + unmetered * rowCeilingUsd(row), complete: false };
306
314
  }
307
315
  if (row.costUsd === null || row.costUsd === undefined) return { usd: rowCeilingUsd(row), complete: false };
@@ -359,7 +367,7 @@ export function assertUnderGlobalCap(path, capUsd) {
359
367
  * @param {Record<string,string|undefined>} [env]
360
368
  */
361
369
  export function checkKeyPreflight(slotName, env = process.env) {
362
- if (!isKeyName(slotName)) return { ok: false, message: `key: unknown provider "${slotName}"` };
370
+ if (!isKeyName(slotName)) return { ok: false, message: `key: unknown provider "${slotName}" — ${KEY_NAME_RULE_SAY}` };
363
371
  const varName = slotName;
364
372
  const value = env[varName];
365
373
  if (value === undefined || value === '') {
@@ -426,7 +434,8 @@ export function makeProvider(slotName, options = {}) {
426
434
  ...common,
427
435
  legacyMaxTokens: slot.legacyMaxTokens,
428
436
  // bare-agent >=0.48: opt in to the raw broken tool-call arguments on
429
- // `malformedToolCall` (capped upstream at 500 chars). Not exposeErrorBody.
437
+ // `malformedToolCall` (bare-agent >=0.50 hands over the full uncapped string; model-step.js
438
+ // bounds it, RAW_ARGS_BOUND). Not exposeErrorBody.
430
439
  exposeMalformedArgs: true,
431
440
  });
432
441
 
@@ -0,0 +1,47 @@
1
+ // M7 piece 2 (docs/wiki/the-module-ladder.md, "M7 scope — SIGNED", item 2): memory
2
+ // lasts one run only. Each run gets its own fresh litectx store and nothing carries
3
+ // into the next run.
4
+ //
5
+ // One function decides where a run's store lives (`runStoreDir`); everything else
6
+ // asks it. The store is a sibling of the run folder, under `<runs>/.stores/<runId>/`,
7
+ // so it is OUTSIDE the run dir and therefore outside every `readScope` the gate hands
8
+ // a step (read reaches the run dir and its frozen inputs' dirs, nothing above). A
9
+ // granted `read` cannot open the store's sqlite file as raw bytes. `.stores` is not a
10
+ // valid run id (a run id must start with a letter or digit), so run listings skip it.
11
+ //
12
+ // The store is opened per call and closed in `finally`: no handle outlives a tool
13
+ // call, so a restarted process (resume) finds the same run's store on disk and a
14
+ // different run never shares one.
15
+
16
+ import { rmSync } from 'node:fs';
17
+ import path from 'node:path';
18
+ import { createRequire } from 'node:module';
19
+
20
+ const require = createRequire(import.meta.url);
21
+ const { LiteCtx } = require('litectx');
22
+
23
+ /** The folder holding THIS run's store. A different run dir is a different folder.
24
+ * @param {string} runDir */
25
+ export function runStoreDir(runDir) {
26
+ const resolved = path.resolve(runDir);
27
+ return path.join(path.dirname(resolved), '.stores', path.basename(resolved));
28
+ }
29
+
30
+ /** Open this run's store, run `fn(lc)`, close it. `root` is the run dir: litectx indexes
31
+ * only its own extensions (.md .js .py ...) there, never the run's json/jsonl records.
32
+ * @template T @param {string} runDir @param {(lc: any) => Promise<T>|T} fn @returns {Promise<T>} */
33
+ export async function withRunStore(runDir, fn) {
34
+ const lc = new LiteCtx({ root: path.resolve(runDir), dbPath: path.join(runStoreDir(runDir), 'index.db') });
35
+ try {
36
+ return await fn(lc);
37
+ } finally {
38
+ lc.close();
39
+ }
40
+ }
41
+
42
+ /** A run STARTS with an empty store, never an inherited one: a run id can be reused (the next id is max+1, so deleting the last run
43
+ * folder hands its id to the next run) and the store sits beside the run folder, not in it. Called by the one place a fresh run
44
+ * begins (`runFlow`); resume and continue keep the run's own store. @param {string} runDir */
45
+ export function resetRunStore(runDir) {
46
+ rmSync(runStoreDir(runDir), { recursive: true, force: true });
47
+ }
package/src/runner.js CHANGED
@@ -44,6 +44,7 @@ import {
44
44
  basename, dirname, extname, isAbsolute, join, resolve, sep,
45
45
  } from 'node:path';
46
46
  import { parseCsv } from './csv.js';
47
+ import { resetRunStore } from './run-store.js';
47
48
  import { fileURLToPath } from 'node:url';
48
49
 
49
50
  import {
@@ -1060,6 +1061,7 @@ export async function runFlow({
1060
1061
  flowDir, runDir, runId, capUsd, startedAt, now, nowMs: getNowMs, signatureHash: signature.flow, outcome: 'preflight-red', red: fresh.red, spent: { value: 0 },
1061
1062
  });
1062
1063
  }
1064
+ resetRunStore(runDir); // M7: a fresh run never inherits a store left by an earlier run of the same id
1063
1065
  mkdirSync(runDir, { recursive: true });
1064
1066
 
1065
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)
package/src/runvalues.js CHANGED
@@ -18,6 +18,7 @@ import { unlinkSync, writeFileSync } from 'node:fs';
18
18
  import { join } from 'node:path';
19
19
 
20
20
  import { readFileInside, readdirInside } from './flow.js';
21
+ import { TRIGGER_RECORD_FILE } from './trigger-line.js';
21
22
 
22
23
  export const VALUES_FILE_RE = /^signed-values(?:-r(\d+))?\.json$/;
23
24
 
@@ -168,11 +169,12 @@ export function applyRunValues(arbiter, flow, flowSignatureHash, picked) {
168
169
 
169
170
  /**
170
171
  * A start that refused before the run began (monthly limit, empty key ...) leaves a run folder holding nothing but its signed values
171
- * file: remove that one file so the folder can be removed too and the run name is not burned. Never touches a folder with anything else.
172
+ * file and/or its trigger record: remove those so the folder can be removed too and the run name is not burned. Never touches a folder with anything else.
172
173
  * @param {string} runDir @returns {boolean} true when the file was removed
173
174
  */
174
175
  export function dropUnstartedValues(runDir) {
175
176
  const names = readdirInside(runDir, '.');
176
- if (names.length !== 1 || names[0] !== valuesFileName(0)) return false;
177
- try { unlinkSync(join(runDir, names[0])); return true; } catch { return false; }
177
+ const own = [valuesFileName(0), TRIGGER_RECORD_FILE]; // M9: a triggered start also writes its reason file before the spawn
178
+ if (names.length === 0 || names.some((n) => !own.includes(n))) return false;
179
+ try { for (const n of names) unlinkSync(join(runDir, n)); return true; } catch { return false; }
178
180
  }
package/src/setup.js CHANGED
@@ -8,6 +8,7 @@
8
8
  // carry `note` / `change` kinds; they are only ever READ back, from the flow's own setup.jsonl.
9
9
  // Third outcomes: a draft with no result is `stopped`; a cost nobody booked is `null` (shown "unknown", never $0).
10
10
  import { lstatSync, writeFileSync } from 'node:fs';
11
+ import { triesOf } from './draft-steps.js';
11
12
  import { join } from 'node:path';
12
13
 
13
14
  import { scrub } from './authoring.js';
@@ -52,6 +53,8 @@ function planRow(sessionDir, rel, kind, n) {
52
53
  // retries the drafter spent on structure (log.json); null = not recorded (a plan from before it), never 0
53
54
  structureRetries: Number.isInteger(log?.structureRetries) ? log.structureRetries : null,
54
55
  verdict, hash, gap,
56
+ // M4d am15: every try of this plan (label, passed, the checker's raw refusals, the round's words), for the Audit Draft group; only when a retry happened
57
+ ...(Array.isArray(log?.log) && log.log.length > 1 ? { tries: triesOf(log.log) } : {}),
55
58
  };
56
59
  }
57
60
 
@@ -109,6 +112,27 @@ export function writeSetup({ flowDir, secrets = [], ...rest }) {
109
112
  }
110
113
  }
111
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
+
112
136
  /**
113
137
  * 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).
114
138
  * @param {string} flowDir