fwdloop 0.20.0 → 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.
package/README.md CHANGED
@@ -64,6 +64,8 @@ Work in progress. Nothing here is ready to install yet.
64
64
 
65
65
  The in-run `impact` tool needs ripgrep (`rg`) on PATH; without it the tool is refused with a message, never a wrong answer.
66
66
 
67
+ The panel test `test/m11-am20.test.js` forces symbol fonts to prove the ◷ chip is sized by measurement, and fails on purpose when fewer than two of Symbola, FreeSans, Noto Sans Mono Condensed and Adwaita Mono are installed. On Debian/Ubuntu: `sudo apt-get install fonts-symbola fonts-freefont-ttf` (CI installs the same two).
68
+
67
69
  ## License
68
70
 
69
71
  Apache-2.0. See `LICENSE` and `NOTICE`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.20.0",
3
+ "version": "0.21.0",
4
4
  "description": "Describe a job as steps and guardrails; an agent builds the workflow, pauses for humans where you said, checks every step happened, and reruns it under budgets it cannot touch.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -0,0 +1,177 @@
1
+ // M4d am29 items 4-8: the Audit step fold, the Run summary's two lines and the step card's one line, all derived HERE from the run's files on disk
2
+ // (audit.jsonl's try rows + the three diaries in src/diary.js). Nothing here calls a model ($0 replay), and the page only draws what this returns,
3
+ // so the Audit rows, the summary and the cards can only agree. A run from before am29 has no diaries: no fold, `—` on the new lines, nothing made up.
4
+ import { readCalls, readTools, readChecks } from './diary.js';
5
+
6
+ /** A Stop's notes are not tries: the asked/not-honoured rows, and a `stopped` row that cut no try (no attempt number). @param {any} r */
7
+ export function isTryRow(r) {
8
+ return r.verdict !== 'stop-asked' && r.verdict !== 'stop-not-honoured' && !(r.verdict === 'stopped' && !Number.isInteger(r.attempt));
9
+ }
10
+
11
+ /** @param {string} runDir */
12
+ export function loadDiaries(runDir) {
13
+ const calls = readCalls(runDir);
14
+ const tools = readTools(runDir);
15
+ const checks = readChecks(runDir);
16
+ // a diary file only ever exists with a row in it, so "this run has diaries" is "a diary holds a row" (read through the safe gateway, no fs here)
17
+ return {
18
+ present: calls.length + tools.length + checks.length > 0, calls, tools, checks,
19
+ };
20
+ }
21
+
22
+ const money = (n) => (typeof n === 'number' ? `$${n.toFixed(4)}` : 'cost unknown');
23
+ const plural = (n, one, many) => `${n} ${n === 1 ? one : many}`;
24
+
25
+ /** The Decision words of a model call row. @param {any} c */
26
+ function callDecision(c) {
27
+ const bits = [money(c.costUsd)];
28
+ if (c.tokens) bits.push(`${c.tokens.in + c.tokens.out + c.tokens.cache} tokens`);
29
+ if (typeof c.ms === 'number') bits.push(`${(c.ms / 1000).toFixed(1)}s`);
30
+ return bits.join(' · ');
31
+ }
32
+
33
+ /** The Decision words of a tool row: allow, deny and the rule that said so, or `no check`. @param {any} t */
34
+ const toolDecision = (t) => (t.decision === 'deny' ? `deny (${t.rule ?? 'no rule recorded'})` : t.decision);
35
+
36
+ /** The Decision words of a try's check row. @param {Array<{n:number, ok:boolean}>} checks */
37
+ function checkDecision(checks) {
38
+ const failed = checks.filter((c) => !c.ok);
39
+ return failed.length === 0 ? `✓ all ${checks.length} passed` : `✗ ${failed.map((c) => `#${c.n}`).join(' ')} failed`;
40
+ }
41
+
42
+ /** What the human did, in the signed words, from the ask step's own audit row; `null` for a row that is not an answer. @param {any} r */
43
+ export function humanWords(r) {
44
+ if (r.verdict === 'paused') return 'paused for you';
45
+ if (r.verdict === 'green') return 'you accepted';
46
+ if (r.verdict === 'red') return `you said redo: "${r.gap ?? ''}"`;
47
+ if (r.verdict === 'stopped') return 'you cancelled';
48
+ if (r.verdict === 'refused') return String(r.gap ?? 'refused');
49
+ if (r.verdict === 'ask-timeout') return 'the ask timed out';
50
+ if (r.verdict === 'ask-expired') return 'the ask expired';
51
+ return null;
52
+ }
53
+
54
+ /** The short answer for a card: `accepted`, `redo: "<text>"`, `cancelled`. @param {any} r */
55
+ function answerShort(r) {
56
+ const w = humanWords(r);
57
+ return w === null ? null : w.replace(/^you said /, '').replace(/^you /, '');
58
+ }
59
+
60
+ /**
61
+ * The fold of one step, or `null` for a step with nothing new to show (an old run, or a step that is neither a model step with records nor an ask).
62
+ * @param {{rows:any[], tryMarks:string[], closeClass:string|null}} group `deriveAuditGroups`' group for the step
63
+ * @param {ReturnType<typeof loadDiaries>} d
64
+ * @param {{about?: string|null}} [info] `about`: the file an ask is about
65
+ */
66
+ export function deriveFold(group, d, info = {}) {
67
+ const step = group.rows[0]?.step ?? null;
68
+ const human = group.rows.some((r) => Object.prototype.hasOwnProperty.call(r, 'unjudgedCount'));
69
+ const calls = d.calls.filter((r) => r.step === step);
70
+ const tools = d.tools.filter((r) => r.step === step);
71
+ const checkRows = d.checks.filter((r) => r.step === step);
72
+ if (human ? !d.present : (calls.length + tools.length + checkRows.length === 0)) return null;
73
+
74
+ const tryRows = group.rows.filter(isTryRow);
75
+ const tries = [];
76
+ const rows = [];
77
+ if (human) {
78
+ // a try is a pause and the answer that followed it; an ask answered on the spot (no pause row) is one try per answer. A refusal is a re-ask, not an answer.
79
+ /** @type {any} */
80
+ let open = null;
81
+ for (const r of tryRows) {
82
+ if (r.verdict === 'paused') {
83
+ open = {
84
+ n: r.attempt, mark: '·', thinking: null, gap: null, answer: null, about: info.about ?? null, checks: [], output: null,
85
+ };
86
+ tries.push(open);
87
+ } else if (r.verdict !== 'refused' && humanWords(r) !== null) {
88
+ if (open === null || open.answer !== null) {
89
+ open = {
90
+ n: r.attempt, mark: '·', thinking: null, gap: null, answer: null, about: info.about ?? null, checks: [], output: null,
91
+ };
92
+ tries.push(open);
93
+ }
94
+ open.answer = humanWords(r);
95
+ open.mark = r.verdict === 'green' ? '✓' : (r.verdict === 'red' || r.verdict === 'stopped' ? '✗' : '·');
96
+ }
97
+ }
98
+ for (const r of group.rows) {
99
+ const words = r.verdict === 'paused' || isTryRow(r) ? humanWords(r) : null;
100
+ if (words === null) continue;
101
+ rows.push({
102
+ round: null, try: Number.isInteger(r.attempt) ? r.attempt : null, action: 'human', path: r.verdict === 'paused' ? (info.about ?? null) : null, decision: words, at: r.at ?? null,
103
+ });
104
+ }
105
+ } else {
106
+ const seen = new Map();
107
+ tryRows.forEach((r, i) => {
108
+ const k = seen.get(r.attempt) ?? 0;
109
+ seen.set(r.attempt, k + 1);
110
+ const rec = checkRows.filter((c) => c.try === r.attempt)[k] ?? null;
111
+ tries.push({
112
+ n: r.attempt, mark: group.tryMarks[i] ?? '·', thinking: r.thinkingPhrase ?? null, gap: r.gap || null, answer: null, about: null, checks: rec?.checks ?? [], output: rec?.output ?? null,
113
+ });
114
+ });
115
+ // rounds count on through all of a step's tries, so they order the calls and tool calls; a try's check row goes after the last round it saw
116
+ const items = [];
117
+ calls.forEach((c, i) => items.push({ k: c.round * 2, i, row: { round: c.round, try: c.try, action: 'model call', path: null, decision: callDecision(c), at: c.at } }));
118
+ tools.forEach((t, i) => items.push({ k: t.round * 2 + 1, i: 1e6 + i, row: { round: t.round, try: t.try, action: `model · ${t.tool}`, path: t.path ?? null, decision: toolDecision(t), at: t.at } }));
119
+ checkRows.forEach((c, i) => items.push({ k: (c.lastRound ?? 0) * 2 + 1.5, i: 2e6 + i, row: { round: null, try: c.try, action: 'check', path: c.output?.file ?? null, decision: checkDecision(c.checks), at: c.at } }));
120
+ items.sort((a, b) => a.k - b.k || a.i - b.i);
121
+ for (const it of items) rows.push(it.row);
122
+ }
123
+
124
+ const tally = {};
125
+ for (const t of tools) tally[t.tool] = (tally[t.tool] ?? 0) + 1;
126
+ const tallyWords = Object.entries(tally).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([k, v]) => `${k} ${v}`).join(', ');
127
+ const lastChecks = checkRows.length ? checkRows[checkRows.length - 1].checks : null;
128
+ const answered = human ? group.rows.filter((r) => r.verdict !== 'paused' && isTryRow(r) && humanWords(r) !== null) : [];
129
+ const lastAnswerRow = answered.length ? answered[answered.length - 1] : null;
130
+ return {
131
+ who: human ? 'human' : 'model',
132
+ tally: tallyWords || null,
133
+ tries,
134
+ rows,
135
+ counts: {
136
+ rounds: calls.length,
137
+ tools: tools.length,
138
+ denied: tools.filter((t) => t.decision === 'deny').length,
139
+ checksRun: checkRows.reduce((n, c) => n + c.checks.length, 0),
140
+ checksFailed: checkRows.reduce((n, c) => n + c.checks.filter((x) => !x.ok).length, 0),
141
+ lastTry: lastChecks ? { run: lastChecks.length, passed: lastChecks.filter((x) => x.ok).length } : null,
142
+ },
143
+ lastAnswer: lastAnswerRow ? { words: answerShort(lastAnswerRow), at: lastAnswerRow.at ?? null } : null,
144
+ };
145
+ }
146
+
147
+ /** The step card's one new line (item 6) minus the human step's time (the page formats that); `—` when there is no record. @param {ReturnType<typeof deriveFold>} fold */
148
+ export function cardLine(fold) {
149
+ if (fold === null) return '—';
150
+ if (fold.who === 'human') return fold.lastAnswer ? `last answer: ${fold.lastAnswer.words}` : '—';
151
+ const lt = fold.counts.lastTry;
152
+ const checks = lt ? `${lt.passed}/${lt.run} ${lt.passed === lt.run ? '✓' : '✗'}` : '—';
153
+ return `${plural(fold.counts.rounds, 'round', 'rounds')} · checks on the last try ${checks}`;
154
+ }
155
+
156
+ /**
157
+ * The Run summary's two new lines (item 5), from the same diary rows the folds read; `—` for a run with no diaries.
158
+ * @param {ReturnType<typeof loadDiaries>} d
159
+ */
160
+ export function summaryLines(d) {
161
+ if (!d.present) return { calls: '—', checks: '—' };
162
+ const denied = d.tools.filter((t) => t.decision === 'deny').length;
163
+ const run = d.checks.reduce((n, c) => n + c.checks.length, 0);
164
+ const failed = d.checks.reduce((n, c) => n + c.checks.filter((x) => !x.ok).length, 0);
165
+ const byStep = new Map();
166
+ for (const c of d.checks) {
167
+ if (c.checks.every((x) => x.ok)) continue;
168
+ if (!byStep.has(c.step)) byStep.set(c.step, []);
169
+ byStep.get(c.step).push(c.try);
170
+ }
171
+ const list = (ns) => (ns.length === 1 ? `try ${ns[0]}` : `tries ${ns.length === 2 ? ns.join(' and ') : `${ns.slice(0, -1).join(', ')} and ${ns[ns.length - 1]}`}`);
172
+ const where = [...byStep].map(([step, ns]) => `${step} ${list(ns)}`).join('; ');
173
+ return {
174
+ calls: `${d.calls.length} model · ${d.tools.length} tool · ${denied} denied`,
175
+ checks: `${run} run · ${run - failed} passed · ${failed} failed${where ? ` (${where})` : ''}`,
176
+ };
177
+ }
package/src/authoring.js CHANGED
@@ -327,7 +327,7 @@ export async function draftToDir({
327
327
  files['target.json'] = targetText;
328
328
  // M4d am6 item 6: the pick is remembered beside the draft (written below as model.json, outside the signed files) so the signed job runs with it.
329
329
  const recordModel = model ?? result.modelId ?? modelId;
330
- const pick = typeof slot === 'string' && typeof recordModel === 'string' && recordModel !== '' ? { slot, model: recordModel } : null;
330
+ const pick = typeof slot === 'string' && typeof recordModel === 'string' && recordModel !== '' ? { slot, model: recordModel, ...(draftThinking === 'on' ? { thinking: true } : {}) } : null;
331
331
  // Amendments 24/25: the questions and the drafter's own "not checked" reading are written BEFORE log.json/spec.hash (the panel reads those
332
332
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
333
333
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
package/src/books.js CHANGED
@@ -66,7 +66,7 @@ export function readPidRows(runDir) {
66
66
  * @param {string} relPath - the book's own file name, relative to baseDir
67
67
  * @returns {any[]}
68
68
  */
69
- function readLines(baseDir, relPath) {
69
+ export function readLines(baseDir, relPath) {
70
70
  const result = readFileInside(baseDir, relPath);
71
71
  if (!result.ok) return [];
72
72
  const rows = [];
package/src/closers.js CHANGED
@@ -338,6 +338,52 @@ export function renderSoftgreenGaps(gaps, shape) {
338
338
  return { red: reds.join('; '), reds };
339
339
  }
340
340
 
341
+ /** The words each softgreen check is listed under (M4d am29 item 2), by its rubric id; the numbers and names come from the signed shape. @param {Record<string, any>} c a check of `softgreenSpec` */
342
+ function softgreenCheckText(c) {
343
+ if (c.id === 'keys') return 'the answer has only a "text" field';
344
+ if (c.id === 'words') return `at most ${c.value} words`;
345
+ if (c.id === 'sections') return `the sections are there, in order: ${c.names.join(', ')}`;
346
+ if (c.id === 'perSection') return `each section is about ${c.wordsPerSection} words`;
347
+ return `${c.size ?? 'its'} lines per block, each carrying: ${(c.phrases ?? []).join(', ')}`;
348
+ }
349
+
350
+ /**
351
+ * How many words bareguard counts in `text`, asked of bareguard itself (a `minWords` check no text can meet, whose gap carries the measured count) so the
352
+ * number listed beside a passing `maxWords` check is the one the check used. `null` when it cannot be read.
353
+ * @param {string} text @returns {Promise<number|null>}
354
+ */
355
+ async function countWordsWithBareguard(text) {
356
+ try {
357
+ const rubric = createRubric({ schema: 1, goal: 'count', checkpoints: { count: { gating: true, checks: [{ id: 'n', rule: 'minWords', field: 'text', value: 100_000_000 }] } } });
358
+ const res = await checkStep(rubric, 'count', { text });
359
+ const measured = res.gaps?.[0]?.measured;
360
+ return typeof measured === 'number' ? measured : null;
361
+ } catch { return null; }
362
+ }
363
+
364
+ /**
365
+ * M4d am29 item 2: every check the softgreen close ran, in the order of `softgreenSpec`, each `{ id, text, ok, result }`. `result` is the word count beside the
366
+ * words check (met or not), the plain-English reason beside any other check that failed, and `null` beside a check that passed with nothing to measure.
367
+ * @param {Record<string, any>} shape @param {any[]} gaps bareguard's gaps (empty when green) @param {string} text
368
+ */
369
+ async function softgreenCheckResults(shape, gaps, text) {
370
+ const out = [];
371
+ for (const c of softgreenSpec(shape).checkpoints.close.checks) {
372
+ const mine = gaps.filter((g) => g.id === c.id);
373
+ let result = null;
374
+ if (c.id === 'words') {
375
+ const n = mine[0]?.measured ?? await countWordsWithBareguard(text);
376
+ result = typeof n === 'number' ? `${n} words` : null;
377
+ } else if (mine.length > 0) {
378
+ result = renderSoftgreenGaps(mine, shape).reds.join('; ');
379
+ }
380
+ out.push({
381
+ id: c.id, text: softgreenCheckText(c), ok: mine.length === 0, result,
382
+ });
383
+ }
384
+ return out;
385
+ }
386
+
341
387
  /** What the artifact looks like in a message, without ever throwing on a hostile object. */
342
388
  function describeArtifact(artifact) {
343
389
  try { return JSON.stringify(artifact); } catch { return '[an object that cannot be read]'; }
@@ -372,8 +418,9 @@ export async function closeSoftgreen(artifact, shape) {
372
418
  const fault = /** @type {NonNullable<typeof res.fault>} */ (res.fault);
373
419
  return { verdict: 'crash', red: `softgreen close crashed: the ${fault.id} check stopped (${fault.kind}${fault.detail ? `: ${fault.detail}` : ''})` };
374
420
  }
375
- if (res.verdict === 'red') return { verdict: 'red', ...renderSoftgreenGaps(res.gaps, shape) };
376
- return { verdict: 'green', red: null, reds: [] };
421
+ const checks = await softgreenCheckResults(shape, res.verdict === 'red' ? res.gaps : [], text);
422
+ if (res.verdict === 'red') return { verdict: 'red', ...renderSoftgreenGaps(res.gaps, shape), checks };
423
+ return { verdict: 'green', red: null, reds: [], checks };
377
424
  } catch (err) {
378
425
  return { verdict: 'crash', red: `softgreen close crashed: ${err.message}` };
379
426
  }
package/src/ctx-tools.js CHANGED
@@ -38,7 +38,7 @@ const SECRET_PATTERNS = [
38
38
  ];
39
39
 
40
40
  /** Mask known secret shapes. @param {unknown} raw */
41
- const redactSecrets = (raw) => redact(String(raw ?? ''), { patterns: SECRET_PATTERNS });
41
+ export const redactSecrets = (raw) => redact(String(raw ?? ''), { patterns: SECRET_PATTERNS });
42
42
 
43
43
  const LINE_SPACE = 'Line numbers are 0-based; copy them between recall and get as printed.';
44
44
 
package/src/diary.js ADDED
@@ -0,0 +1,49 @@
1
+ // M4d am29 item 1-3: the run's three add-only diaries, in the run's own folder, the way bareloop keeps its gate audit sidecar
2
+ // (src/planrun.js: `new Gate({ audit: { path } })`, the path denied to the worker with `fs.deny`).
3
+ // calls.jsonl one row per MODEL CALL: step, try, round, cost, tokens, time, stop reason, thinking asked and status
4
+ // tools.jsonl one row per TOOL CALL: step, try, round, tool, path, the guard's decision (allow / deny + rule / no check)
5
+ // checks.jsonl one row per TRY that ran checks: each check numbered, ✓/✗, its result, where it comes from, and the output it judged
6
+ // Never saved: what the model said, what was in any file (a tool row names a path, never its content). Every string is scrubbed with the
7
+ // ONE secret inventory (`redactSecrets`, src/ctx-tools.js) before the row is written. The model can never read these files: the step's
8
+ // bareguard Gate denies them (src/primitives.js) and a grep over the run folder drops their hits.
9
+ // Rounds count from 1 in EACH STEP (they keep counting across that step's tries); `nextRound` reads the count off the diary.
10
+ //
11
+ // borrowed-from: bareloop src/planrun.js@fd78723 (the gate audit sidecar + fs.deny of its path; the per-round rows emitted from the onLlmResult wrapper)
12
+ import { join } from 'node:path';
13
+ import { appendRow } from './jsonl-append.js';
14
+ import { readLines } from './books.js';
15
+ import { redactSecrets } from './ctx-tools.js';
16
+
17
+ export const DIARY_FILES = Object.freeze({ calls: 'calls.jsonl', tools: 'tools.jsonl', checks: 'checks.jsonl' });
18
+
19
+ /** Every diary's absolute path for a run, for the model's deny list. @param {string} runDir @returns {string[]} */
20
+ export const diaryPaths = (runDir) => Object.values(DIARY_FILES).map((f) => join(runDir, f));
21
+
22
+ /** A copy of a JSON value with every string scrubbed. @param {any} v @returns {any} */
23
+ function scrub(v) {
24
+ if (typeof v === 'string') return redactSecrets(v);
25
+ if (Array.isArray(v)) return v.map(scrub);
26
+ if (v !== null && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, scrub(x)]));
27
+ return v;
28
+ }
29
+
30
+ /** The ONE writer of a diary row. @param {string} runDir @param {keyof typeof DIARY_FILES} kind @param {Record<string, any>} row */
31
+ function write(runDir, kind, row) { appendRow(join(runDir, DIARY_FILES[kind]), scrub(row)); }
32
+
33
+ /** @param {string} runDir @param {{step:string|null, try:number|null, round:number, at:string, model:string|null, costUsd:number|null, tokens:{in:number,out:number,cache:number}|null, ms:number|null, stopReason:string|null, thinking:{asked:string|null,status:string|null}}} row */
34
+ export const appendCall = (runDir, row) => write(runDir, 'calls', row);
35
+ /** @param {string} runDir @param {{step:string|null, try:number|null, round:number, at:string, tool:string, path:string|null, decision:'allow'|'deny'|'no check', rule:string|null}} row */
36
+ export const appendTool = (runDir, row) => write(runDir, 'tools', row);
37
+ /** @param {string} runDir @param {{step:string|null, try:number, at:string, lastRound:number, checks:Array<{n:number, text:string, ok:boolean, result:string|null, source:string}>, output:{file:string, bytes:number, sha256:string}|null}} row */
38
+ export const appendChecks = (runDir, row) => write(runDir, 'checks', row);
39
+
40
+ /** @param {string} runDir @returns {any[]} */
41
+ export const readCalls = (runDir) => readLines(runDir, DIARY_FILES.calls);
42
+ /** @param {string} runDir @returns {any[]} */
43
+ export const readTools = (runDir) => readLines(runDir, DIARY_FILES.tools);
44
+ /** @param {string} runDir @returns {any[]} */
45
+ export const readChecks = (runDir) => readLines(runDir, DIARY_FILES.checks);
46
+
47
+ /** The round number of this step's next model call: one more than the highest round it has in the diary, so it counts on across tries and across resumes.
48
+ * Read off the file each time (the diary is the one record), never a copy held in memory. @param {string} runDir @param {string|null} step */
49
+ export const nextRound = (runDir, step) => readCalls(runDir).filter((r) => r.step === step).reduce((m, r) => Math.max(m, r.round), 0) + 1;
package/src/flowmodel.js CHANGED
@@ -11,20 +11,57 @@ export const MODEL_FILE = 'model.json';
11
11
 
12
12
  /**
13
13
  * @param {string} dir a draft folder or a flow folder
14
- * @returns {{ slot: string, model: string }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
14
+ * M4d am25: `thinking: true` is the Chat "Thinking on" box as it was when the job was signed; the key is absent when the box was off.
15
+ * @returns {{ slot: string, model: string, thinking?: true }|null} null when there is no usable record (missing, unreadable, or not a name and a model id)
15
16
  */
16
17
  export function readModelRecord(dir) {
17
18
  const r = readFileInside(dir, MODEL_FILE);
18
19
  if (!r.ok) return null;
19
20
  try {
20
21
  const j = JSON.parse(r.text);
21
- return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model } : null;
22
+ return isKeyName(j?.slot) && typeof j?.model === 'string' && j.model !== '' ? { slot: j.slot, model: j.model, ...(j.thinking === true ? { thinking: true } : {}) } : null;
22
23
  } catch { return null; }
23
24
  }
24
25
 
25
26
  /**
26
- * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string }} pick
27
+ * Write the record once (never over an existing one). @param {string} dir @param {{ slot: string, model: string, thinking?: boolean }} pick
27
28
  */
28
- export function writeModelRecord(dir, { slot, model }) {
29
- writeFileSync(join(dir, MODEL_FILE), `${JSON.stringify({ slot, model }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
29
+ export function writeModelRecord(dir, { slot, model, thinking }) {
30
+ writeOnce(join(dir, MODEL_FILE), { slot, model, ...(thinking === true ? { thinking: true } : {}) });
31
+ }
32
+
33
+ /** The one file write of this module: JSON, 0600, never over an existing file. */
34
+ function writeOnce(file, obj) {
35
+ writeFileSync(file, `${JSON.stringify(obj, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
36
+ }
37
+
38
+ /** M4d am25: the file in a run's folder that keeps the box as the run started with it (outside `job/`, which holds the three signed files only). */
39
+ export const RUN_THINKING_FILE = 'thinking.json';
40
+
41
+ /**
42
+ * M4d am25: the ONE reader of the job's "Thinking on" box for a run. A run reads its OWN record (`<run>/thinking.json`, written once when the run
43
+ * started) when it has one; otherwise the flow folder's `model.json`. No record, an unreadable one, or one without `thinking` is box OFF: a job
44
+ * signed before am25 stored nothing, and it must not start thinking on every try.
45
+ * @param {string} flowDir @param {string|null} runDir @returns {boolean}
46
+ */
47
+ export function readJobThinking(flowDir, runDir) {
48
+ return readRunThinking(runDir) ?? (readModelRecord(flowDir)?.thinking === true);
49
+ }
50
+
51
+ /**
52
+ * M4d am26: the run's OWN record of the box (`<run>/thinking.json`) and nothing else: `true`/`false`, or `null` when the run has none (a run from before am25).
53
+ * An unreadable record is box off, as `readJobThinking` has always read it. @param {string|null} runDir @returns {boolean|null}
54
+ */
55
+ export function readRunThinking(runDir) {
56
+ const own = typeof runDir === 'string' ? readFileInside(runDir, RUN_THINKING_FILE) : null;
57
+ if (!own?.ok) return null;
58
+ try { return JSON.parse(own.text)?.thinking === true; } catch { return false; }
59
+ }
60
+
61
+ /**
62
+ * M4d am25: a run keeps the box as the job had it when the run started (write-once, so an Edit of the job never changes a run already going).
63
+ * Written for every fresh run, ticked or not. @param {string} flowDir @param {string} runDir
64
+ */
65
+ export function writeRunThinking(flowDir, runDir) {
66
+ writeOnce(join(runDir, RUN_THINKING_FILE), { thinking: readModelRecord(flowDir)?.thinking === true });
30
67
  }
package/src/model-step.js CHANGED
@@ -24,9 +24,12 @@
24
24
  // (green/softgreen/anything else) — never from the step's `shape` — the
25
25
  // executor context (M2 scope item 3) carries neither.
26
26
 
27
+ import { dirname } from 'node:path';
27
28
  import { Loop, HaltError } from 'bare-agent';
28
29
  import { GateRefusal } from './primitives.js';
30
+ import { appendCall, appendTool, nextRound } from './diary.js';
29
31
  import { ConfigError } from './config.js';
32
+ import { worstThinkingStatus } from './thinking.js';
30
33
 
31
34
  import {
32
35
  makeProvider, ModelRefusal, sumMeterings, appendSpendRow, classifyModelId, priceRecord,
@@ -173,7 +176,7 @@ function addMeter(cumulative, metered) {
173
176
  // faulted — caught live: `toolFields` threw on `cumulative.ungranted`
174
177
  // being undefined the very first time a transport fault hit round 1.
175
178
  return {
176
- costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused,
179
+ costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking,
177
180
  };
178
181
  }
179
182
 
@@ -223,6 +226,7 @@ function toolFields(cumulative) {
223
226
  // M4e amendment 7 item 8: model calls (turns) this attempt made, so a Stop can say "after turn T of try K".
224
227
  turns: cumulative.rounds,
225
228
  tools: cumulative.tools,
229
+ thinking: cumulative.thinking,
226
230
  // Gate refusals this attempt — always present (empty array when none) so
227
231
  // absence can never be confused with "none".
228
232
  refused: cumulative.refused,
@@ -230,6 +234,42 @@ function toolFields(cumulative) {
230
234
  };
231
235
  }
232
236
 
237
+ /**
238
+ * M4d am29 item 1: the thinking status of ONE provider result, read the way bare-agent's Loop reads it for the whole run (`thinkingStatus`; a custom
239
+ * provider's legacy `thinkingApplied` true/false/null maps to applied/ignored/unknown); `null` when the result carried neither.
240
+ * @param {any} r
241
+ */
242
+ function thinkingStatusOf(r) {
243
+ if (typeof r?.thinkingStatus === 'string') return r.thinkingStatus;
244
+ if (r?.thinkingApplied === true) return 'applied';
245
+ if (r?.thinkingApplied === false) return 'ignored';
246
+ if (r?.thinkingApplied === null) return 'unknown';
247
+ return null;
248
+ }
249
+
250
+ /**
251
+ * The provider with one addition: each `generate` result is handed to `seen` before the Loop meters that call, so the call's diary row can say what bare-agent
252
+ * reported for THAT call (thinking status, the tool names it asked for); the Loop's own `onLlmResult` payload carries neither. Everything else reads through.
253
+ * @param {any} provider @param {(result: any) => void} seen
254
+ */
255
+ function watchCalls(provider, seen) {
256
+ const watched = Object.create(provider);
257
+ watched.generate = async (...a) => {
258
+ const r = await provider.generate(...a);
259
+ seen(r);
260
+ return r;
261
+ };
262
+ return watched;
263
+ }
264
+
265
+ /** The path a tool call's diary row names: the path it was given, else the frozen input role, else the stash key. Never a query, a text or a symbol. @param {any} args */
266
+ function toolRowPath(args) {
267
+ if (typeof args?.path === 'string') return args.path;
268
+ if (typeof args?.role === 'string') return args.role;
269
+ if (typeof args?.id === 'string') return `stash: ${args.id}`;
270
+ return null;
271
+ }
272
+
233
273
  const STOP_RULE = 'stop-requested';
234
274
 
235
275
  /** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
@@ -248,7 +288,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
248
288
  * @param {{in:number,out:number}} [opts.rates]
249
289
  * @param {string} [opts.modelId]
250
290
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
251
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
291
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
252
292
  */
253
293
  export function makeLiveModelStep({
254
294
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -285,7 +325,12 @@ export function makeLiveModelStep({
285
325
  }
286
326
  }
287
327
 
328
+ // M4d am29: the three diaries live in the run's own folder, beside spend.jsonl; a row names its step and try from the runner's `stepMeta`
329
+ const runDir = dirname(spendPath);
330
+ const diaryStep = stepMeta.step ?? null;
331
+ const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
288
332
  const toolSchema = buildEmitArtifactSchema(stepMeta.class);
333
+ const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
289
334
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
290
335
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
291
336
  + 'reads you were handed or the tools you were granted — never invent a figure.';
@@ -303,12 +348,32 @@ export function makeLiveModelStep({
303
348
  // wrapped so a typed GateRefusal is recorded, then rethrown unchanged so
304
349
  // the model still sees the refusal as its tool result.
305
350
  const refused = /** @type {Array<{verb:string, path:string, rule:string}>} */ ([]);
351
+ // M4d am29 item 1: every call a granted tool takes also gets its diary row - the guard's decision (`allow`, the `deny` and its rule, or `no check` for a
352
+ // call that never reached the gate) - written whether the call worked or not. `round` is the model call that asked for it (set by onLlmResult below).
353
+ let currentRound = 0;
306
354
  const primitiveTools = Object.values(grantedTools ?? {}).filter(Boolean).map((tool) => ({
307
355
  ...tool,
308
356
  execute: async (...a) => {
357
+ const askedBefore = tool.gateSeen?.n ?? 0;
358
+ /** @type {GateRefusal|null} */
359
+ let refusal = null;
309
360
  try { return await tool.execute(...a); } catch (err) {
310
- if (err instanceof GateRefusal) refused.push({ verb: err.verb, path: err.path, rule: err.rule });
361
+ if (err instanceof GateRefusal) {
362
+ refusal = err;
363
+ refused.push({ verb: err.verb, path: err.path, rule: err.rule });
364
+ }
311
365
  throw err;
366
+ } finally {
367
+ appendTool(runDir, {
368
+ step: diaryStep,
369
+ try: diaryTry,
370
+ round: currentRound,
371
+ at: new Date().toISOString(),
372
+ tool: tool.name,
373
+ path: toolRowPath(a[0]),
374
+ decision: refusal ? 'deny' : ((tool.gateSeen?.n ?? 0) > askedBefore ? 'allow' : 'no check'),
375
+ rule: refusal ? refusal.rule : null,
376
+ });
312
377
  }
313
378
  },
314
379
  }));
@@ -329,6 +394,9 @@ export function makeLiveModelStep({
329
394
  tools: /** @type {Record<string, number>} */ ({}),
330
395
  ungranted: /** @type {string[]} */ ([]),
331
396
  refused,
397
+ // M4d am25 item 4: what this attempt asked of thinking (the runner's decision, `stepMeta.thinkingMode`; null = it asked nothing) and the WORST status
398
+ // bareagent reported across its rounds (null = none reported). The ONE place this record is built; `toolFields` hands it to every return.
399
+ thinking: /** @type {{asked: string|null, status: string|null}} */ ({ asked: thinkingMode ?? null, status: null }),
332
400
  };
333
401
  let noToolCallStreak = 0;
334
402
 
@@ -342,17 +410,46 @@ export function makeLiveModelStep({
342
410
  };
343
411
  const tools = [...primitiveTools, emitTool];
344
412
  const roundMeterings = [];
413
+ let lastCall = /** @type {any} */ (null);
345
414
  const stopRequested = seam?.stopRequested;
346
415
  const stopSeam = typeof stopRequested === 'function'
347
416
  ? { assemble: async (msgs) => { if (stopRequested()) throw new HaltError('stop requested', { rule: STOP_RULE }); return msgs; } }
348
417
  : {};
349
- const loop = new Loop({ provider, rates, onLlmResult: async (ev) => { roundMeterings.push(ev); }, ...stopSeam });
418
+ // M4d am29 item 1: each model call gets its diary row the moment it is metered (round = this step's next, counted across its tries)
419
+ const onLlmResult = async (ev) => {
420
+ roundMeterings.push(ev);
421
+ currentRound = nextRound(runDir, diaryStep);
422
+ appendCall(runDir, {
423
+ step: diaryStep,
424
+ try: diaryTry,
425
+ round: currentRound,
426
+ at: new Date().toISOString(),
427
+ model: typeof ev?.model === 'string' ? ev.model : null,
428
+ costUsd: typeof ev?.costUsd === 'number' ? ev.costUsd : null, // an unpriced call stays null, never 0
429
+ tokens: ev?.usage ? { in: ev.usage.inputTokens ?? 0, out: ev.usage.outputTokens ?? 0, cache: ev.usage.cacheReadTokens ?? 0 } : null,
430
+ ms: typeof ev?.durationMs === 'number' ? ev.durationMs : null,
431
+ stopReason: typeof ev?.stopReason === 'string' ? ev.stopReason : null,
432
+ thinking: { asked: thinkingMode, status: thinkingStatusOf(lastCall) },
433
+ });
434
+ // a name the model asked for that was never offered reaches no tool (the Loop answers "Unknown tool"): it still gets its own denied row.
435
+ // A call cut at the output cap runs none of its tool calls, so it gets none.
436
+ if (ev?.stopReason !== 'max_tokens') {
437
+ for (const tc of lastCall?.toolCalls ?? []) {
438
+ if (tc?.name === 'emit_artifact' || primitiveTools.some((t) => t.name === tc?.name)) continue;
439
+ appendTool(runDir, {
440
+ step: diaryStep, try: diaryTry, round: currentRound, at: new Date().toISOString(), tool: String(tc?.name), path: null, decision: 'deny', rule: 'not granted',
441
+ });
442
+ }
443
+ }
444
+ };
445
+ const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }), rates, onLlmResult, ...stopSeam });
350
446
 
351
447
  const startedAt = Date.now();
352
448
  let result;
353
449
  try {
354
450
  // eslint-disable-next-line no-await-in-loop
355
- result = await loop.run(messages, tools, { maxTokens: 16000 });
451
+ // M4d am25: the thinking switch is the runner's decision (`stepMeta.thinkingMode`, 'on' | 'off'); bareagent sends it. Absent = send none (a caller that decides nothing).
452
+ result = await loop.run(messages, tools, { maxTokens: 16000, ...(thinkingMode ? { thinkingMode } : {}) });
356
453
  } catch (err) {
357
454
  const wallMs = Date.now() - startedAt;
358
455
  const partial = sumMeterings(roundMeterings);
@@ -419,6 +516,7 @@ export function makeLiveModelStep({
419
516
  const metered = sumMeterings(roundMeterings);
420
517
  cumulative = addMeter(cumulative, metered);
421
518
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
519
+ if (result.thinkingStatus !== undefined) cumulative.thinking = { asked: cumulative.thinking.asked, status: worstThinkingStatus([cumulative.thinking.status, result.thinkingStatus]) };
422
520
  appendSpendRow(spendPath, {
423
521
  provider: slot ?? null,
424
522
  price: priceRecord(prices, rates),