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
@@ -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,14 +37,15 @@ 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
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`
47
- const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string').map((r) => key(r.sha, r)));
48
+ const spoken = new Set(readOutcomes(job.flowDir).filter((r) => typeof r.sha === 'string' && r.sig === sig).map((r) => key(r.sha, r)));
48
49
  const cause = (/** @type {any} */ q) => ({ kind: /** @type {'file'} */ ('file'), path: q.path, sha: q.sha });
49
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; };
50
51
  if (door.busy(job)) {
@@ -56,14 +57,14 @@ export function createScheduler(opts) {
56
57
  const seen = recheck(q);
57
58
  if (seen.state !== 'ok') {
58
59
  const why = seen.state === 'deleted' ? 'deleted' : 'changed';
59
- recordDropped(ledger, q, why, nowMs);
60
+ recordDropped(ledger, q, why, nowMs, sig);
60
61
  door.note(job, {
61
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.`,
62
63
  });
63
64
  queue = queue.slice(1);
64
65
  continue;
65
66
  }
66
- 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) });
67
68
  return;
68
69
  }
69
70
  }
@@ -71,32 +72,30 @@ export function createScheduler(opts) {
71
72
  function tick() {
72
73
  const nowMs = now();
73
74
  const live = new Set();
75
+ try { door.retireStale(); } catch { /* one job's files never stop the others; tried again next tick */ }
74
76
  for (const job of door.scan()) {
75
- const hash = job.read.signature.flow;
76
- const key = `${job.flow}|${hash}`;
77
+ const { sig } = job;
78
+ const key = `${job.flow}|${sig}`;
77
79
  live.add(key);
78
80
  try {
79
- door.ensureArmed(job);
80
- const dir = triggerLedgerDir(job.flowDir, hash);
81
+ const ledger = ledgerOf(job.flowDir);
81
82
  const { trigger } = job;
82
83
  if (trigger.kind === 'file-updated' || trigger.kind === 'new-file') {
83
84
  let w = watchers.get(key);
84
85
  if (!w) {
85
86
  w = createFileTrigger({
86
- 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,
87
88
  });
88
89
  watchers.set(key, w);
89
90
  }
90
- const ledger = join(dir, 'seen.jsonl');
91
91
  const { arrived, refused } = w.poll();
92
92
  for (const r of refused) door.refuse(job, `${r.path}: ${r.why}`);
93
- 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
94
94
  runQueue(job, ledger, nowMs);
95
95
  } else {
96
- const clock = join(dir, 'clock.jsonl');
97
- const d = due(trigger, readRows(clock), nowMs);
96
+ const d = due(trigger, readRows(ledger, sig), nowMs);
98
97
  if (d.fire) {
99
- 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
100
99
  door.fire(job, {
101
100
  kind: 'clock', slot: /** @type {number} */ (d.slot), catchUp: d.catchUp, missed: d.missed,
102
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
@@ -32,6 +32,8 @@ import { primitiveFor, loadCatalogue } from './catalogue.js';
32
32
  import { readDocxText } from './docx.js';
33
33
  import { parseCsv } from './csv.js';
34
34
  import { makeCtxTools } from './ctx-tools.js';
35
+ import { diaryPaths } from './diary.js';
36
+ import { readdirInside } from './flow.js';
35
37
 
36
38
  // bare-agent >=0.47.0: `noFollowSymlinks: true` makes shell_read/write/edit/
37
39
  // grep throw `err.code === 'ELOOP'` when the path's FINAL component is a
@@ -172,6 +174,9 @@ function sandboxedReadTool(gate, runDir, inputsByRole) {
172
174
  };
173
175
  }
174
176
 
177
+ /** bare-agent's shell_grep default cap (DEFAULT_GREP_MAX_MATCHES, not exported) — mirrored for the entry-by-entry grep. */
178
+ const GREP_DEFAULT_MAX_MATCHES = 200;
179
+
175
180
  function sandboxedGrepTool(gate, runDir, inputsByRole) {
176
181
  const real = shellTool('shell_grep');
177
182
  const textRoles = Object.keys(inputsByRole).filter((r) => rolePrimitiveFor(inputsByRole[r]) === 'read');
@@ -181,7 +186,31 @@ function sandboxedGrepTool(gate, runDir, inputsByRole) {
181
186
  parameters: roleParameters(real, textRoles),
182
187
  execute: async (args) => {
183
188
  const resolvedPath = await resolveRoleOrPath(gate, 'grep', 'grep', runDir, args, inputsByRole, textRoles);
184
- return real.execute({ ...args, path: resolvedPath });
189
+ // M4d am29 item 3: the gate only denies the diaries by name, and bare-agent's grep stops at its cap with no exclude option. A folder that holds a diary
190
+ // (the run folder itself) is therefore grepped entry by entry, diaries left out BEFORE the cap, each entry through the same gate.
191
+ const diaries = new Set(diaryPaths(runDir).map((p) => path.resolve(p)));
192
+ const dir = path.resolve(resolvedPath);
193
+ let found;
194
+ if (dir === path.resolve(runDir)) {
195
+ const cap = args.maxMatches || GREP_DEFAULT_MAX_MATCHES;
196
+ const hits = [];
197
+ let fileCount = 0;
198
+ for (const name of readdirInside(runDir, '').sort()) {
199
+ const entry = path.join(dir, name);
200
+ if (diaries.has(entry) || hits.length >= cap) continue;
201
+ // not recursive: top-level files only; readdirInside lists a directory's entries and nothing for a file
202
+ if (args.recursive === false && readdirInside(runDir, name).length) continue;
203
+ const gated = await resolveAndGate(gate, 'grep', 'grep', runDir, entry);
204
+ const part = await real.execute({ ...args, path: gated, maxMatches: cap - hits.length });
205
+ hits.push(...(part?.hits ?? []));
206
+ fileCount += part?.fileCount ?? 0;
207
+ }
208
+ found = { hits, truncated: hits.length >= cap, fileCount };
209
+ } else {
210
+ found = await real.execute({ ...args, path: resolvedPath });
211
+ }
212
+ // safety net for any other path shape: a diary hit never reaches the model
213
+ return found && Array.isArray(found.hits) ? { ...found, hits: found.hits.filter((h) => !diaries.has(path.resolve(String(h?.file)))) } : found;
185
214
  },
186
215
  };
187
216
  }
@@ -320,11 +349,23 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
320
349
  // and a red naming bareguard's own message, so the caller refuses the run.
321
350
  let gate;
322
351
  try {
323
- gate = new Gate({ fs: { readScope, writeScope: [outDir] } });
352
+ // M4d am29 item 3: the diaries are denied to the model by name (bareloop's `fs.deny` of its audit sidecar path)
353
+ gate = new Gate({ fs: { readScope, writeScope: [outDir], deny: diaryPaths(runDir) } });
324
354
  } catch (err) {
325
355
  return { tools: {}, reds: [`primitives: bareguard refused the step's file scope — ${err.message}`] };
326
356
  }
327
357
 
358
+ // M4d am29 item 1: what the gate last decided and how many times it was asked, so a tool call's diary row can say `allow`, the deny and its rule,
359
+ // or `no check` (a call that never reached the gate: readDocx, addressCells, a litectx verb with no path). Every tool below carries it as `gateSeen`.
360
+ const gateSeen = { n: 0, last: /** @type {{outcome:string, rule:string|null}|null} */ (null) };
361
+ const askGate = gate.check.bind(gate);
362
+ gate.check = async (action) => {
363
+ const decision = await askGate(action);
364
+ gateSeen.n += 1;
365
+ gateSeen.last = { outcome: decision.outcome, rule: decision.rule ?? null };
366
+ return decision;
367
+ };
368
+
328
369
  const tools = {};
329
370
  const reds = [];
330
371
  // Built on demand, once: nothing is opened or created here (the store is opened per call, inside a tool).
@@ -379,5 +420,6 @@ export function resolvePrimitives(catalogue, grantedVerbs, ctx) {
379
420
  }
380
421
  }
381
422
 
423
+ for (const verb of Object.keys(tools)) tools[verb] = { ...tools[verb], gateSeen };
382
424
  return { tools, reds };
383
425
  }
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`,