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
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/bin/fwdloop CHANGED
@@ -23,13 +23,13 @@ import { draftHoldUsd } from '../src/draftspend.js';
23
23
  import { pathToFileURL } from 'node:url';
24
24
 
25
25
  import {
26
- readFlow, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside, claimRunId,
26
+ readPlan, readRunPlan, checkFlowName, resolveRunDir, listFlowNames, listRunIds, readFileInside, claimRunId,
27
27
  } from '../src/flow.js';
28
28
  import { loadCatalogue } from '../src/catalogue.js';
29
29
  import {
30
30
  runFlow, resumeRun, continueRun, auditSpend, makeParkingAskStep, readAsk, readRunState,
31
31
  } from '../src/runner.js';
32
- import { applyRunValues, pickRunValues, dropUnstartedValues } from '../src/runvalues.js';
32
+ import { applyRunValues, pickRunValues, dropUnstartedValues, runModelOf } from '../src/runvalues.js';
33
33
  import { TRIGGER_RECORD_FILE } from '../src/trigger-line.js';
34
34
  import { makeLiveModelStep } from '../src/model-step.js';
35
35
  import { sendViaPrimitive } from '../src/send.js';
@@ -160,7 +160,7 @@ function today() {
160
160
  * be hit by a user typing `--something`. This is how the test suite drives
161
161
  * every CLI scenario at $0 with zero chance of a real network call.
162
162
  */
163
- async function resolveModelStep(spendPath, env, flowDir, named = {}) {
163
+ async function resolveModelStep(spendPath, env, flowDir, named = {}, runModel = null) {
164
164
  if (process.env.NODE_ENV === 'test' && process.env.FWDLOOP_TEST_MODEL_STEP) {
165
165
  const modulePath = resolve(process.env.FWDLOOP_TEST_MODEL_STEP);
166
166
  const mod = await import(pathToFileURL(modulePath).href);
@@ -172,7 +172,7 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}) {
172
172
  const modelStep = await mod.default({ spendPath });
173
173
  let usable = null;
174
174
  try {
175
- const rec = configDoorHome().skip ? null : readModelRecord(flowDir);
175
+ const rec = configDoorHome().skip ? null : (runModel ?? readModelRecord(flowDir));
176
176
  usable = rec === null ? null : resolveUsableModel(rec.slot, { config: readPriceConfig(), model: rec.model });
177
177
  } catch (err) {
178
178
  if (!(err instanceof ConfigError)) throw err; // a broken config is refused by name at the monthly hold, right after this
@@ -187,7 +187,7 @@ async function resolveModelStep(spendPath, env, flowDir, named = {}) {
187
187
  let slot;
188
188
  try {
189
189
  const config = readPriceConfig();
190
- const rec = readModelRecord(flowDir);
190
+ const rec = runModel ?? readModelRecord(flowDir); // M6 am5/am6: the model signed for THIS run, else the one recorded with the job
191
191
  if (rec !== null && named.model !== undefined && (named.model !== rec.model || (named.provider !== undefined && named.provider !== rec.slot))) {
192
192
  throw new Error(`This job already has its model recorded (${rec.slot} · ${rec.model}); --model cannot change it.`);
193
193
  }
@@ -311,7 +311,8 @@ async function cmdRun(rest) {
311
311
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
312
312
  const catalogue = loaded.primitives;
313
313
 
314
- const read = readFlow({ root, name: flowName, catalogue });
314
+ const planRunDir = (id) => { if (typeof id !== 'string') return null; const c = resolveRunDir(join(root, flowName), id); return c.ok ? c.runDir : null; }; // am9: a run that keeps its own plan reads it
315
+ const read = readPlan({ root, name: flowName, catalogue, runDir: planRunDir(values['run-id']) });
315
316
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
316
317
  const { declaration } = read;
317
318
 
@@ -353,7 +354,7 @@ async function cmdRun(rest) {
353
354
  if (!runIdCheck.ok) fail(runIdCheck.red);
354
355
  runDir = runIdCheck.runDir;
355
356
  // M4e amendment 5: the panel's Sign & run puts the run's signed values in the folder BEFORE the start; that one file is not "a run".
356
- if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE).length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
357
+ if (existsSync(runDir) && readdirSync(runDir).filter((n) => n !== 'signed-values.json' && n !== TRIGGER_RECORD_FILE && n !== 'job' && n !== 'plan.json' && n !== 'setup.jsonl').length > 0) fail(`run: run dir "${runDir}" already exists — use a new --run-id`);
357
358
  }
358
359
  // M4e amendment 5 item 3: the cap this run was signed with (its own values file, else the flow's) is what the monthly hold is for.
359
360
  const applied = applyRunValues(read.arbiter, flowName, read.signature.flow, pickRunValues(runDir));
@@ -368,7 +369,7 @@ async function cmdRun(rest) {
368
369
  let modelStep;
369
370
  let ceilingUsd;
370
371
  try {
371
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
372
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
372
373
  } catch (err) {
373
374
  fail(err.message);
374
375
  return;
@@ -607,7 +608,8 @@ async function cmdResume(rest) {
607
608
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
608
609
  const catalogue = loaded.primitives;
609
610
 
610
- const read = readFlow({ root, name: flowName, catalogue });
611
+ const planRunDir = (id) => { if (typeof id !== 'string') return null; const c = resolveRunDir(join(root, flowName), id); return c.ok ? c.runDir : null; }; // am9: a run that keeps its own plan reads it
612
+ const read = planRunDir(runId) === null ? readPlan({ root, name: flowName, catalogue, runDir: null }) : readRunPlan({ root, name: flowName, catalogue, runDir: /** @type {string} */ (planRunDir(runId)) }); // M9 am12: the run's own saved job (a bad runId is refused by name just below)
611
613
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
612
614
  const { declaration } = read;
613
615
 
@@ -624,7 +626,7 @@ async function cmdResume(rest) {
624
626
  let modelStep;
625
627
  let ceilingUsd;
626
628
  try {
627
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
629
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
628
630
  } catch (err) {
629
631
  fail(err.message);
630
632
  return;
@@ -709,7 +711,8 @@ async function cmdContinue(rest) {
709
711
  if (!loaded.ok) fail(`catalogue: ${loaded.reds.join('; ')}`);
710
712
  const catalogue = loaded.primitives;
711
713
 
712
- const read = readFlow({ root, name: flowName, catalogue });
714
+ const planRunDir = (id) => { if (typeof id !== 'string') return null; const c = resolveRunDir(join(root, flowName), id); return c.ok ? c.runDir : null; }; // am9: a run that keeps its own plan reads it
715
+ const read = planRunDir(runId) === null ? readPlan({ root, name: flowName, catalogue, runDir: null }) : readRunPlan({ root, name: flowName, catalogue, runDir: /** @type {string} */ (planRunDir(runId)) }); // M9 am12: the run's own saved job (a bad runId is refused by name just below)
713
716
  if (!read.ok) fail(`flow "${flowName}": ${read.reds.join('; ')}`);
714
717
  const { declaration } = read;
715
718
 
@@ -724,7 +727,7 @@ async function cmdContinue(rest) {
724
727
  let modelStep;
725
728
  let ceilingUsd;
726
729
  try {
727
- ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values));
730
+ ({ modelStep, ceilingUsd } = await resolveModelStep(spendPath, env, join(root, flowName), values, runModelOf(pickRunValues(runDir))));
728
731
  } catch (err) {
729
732
  fail(err.message);
730
733
  return;
@@ -904,7 +907,7 @@ async function cmdDraft(rest) {
904
907
  async function cmdSign(rest) {
905
908
  const { values, positionals } = parseArgs({
906
909
  args: rest,
907
- options: { approve: { type: 'string' }, 'signed-by': { type: 'string' } },
910
+ options: { approve: { type: 'string' }, 'signed-by': { type: 'string' }, 'run-of': { type: 'string' } },
908
911
  allowPositionals: true,
909
912
  });
910
913
  const keysLoad = keyedLoad(); // sign takes no key, but its leak sweep must know the file's keys too
@@ -925,8 +928,14 @@ async function cmdSign(rest) {
925
928
  if (!typed.ok) fail(`sign refused — ${typed.red}`);
926
929
  const result = signDraft({
927
930
  dir: resolve(dir), approve: values.approve, signedBy: values['signed-by'] ?? userInfo().username, env, keyNames: keysLoad.keyNames,
931
+ // M6 am9: a red run's redraft of an unchanged job is signed as the plan of a new run of that workflow (--run-of <workflow>); the same TTY and typed name above
932
+ ...(values['run-of'] ? { asRunOf: { flow: values['run-of'] } } : {}),
928
933
  });
929
934
  if (!result.ok) fail(`sign refused — ${result.reds.join('; ')}`);
935
+ if (result.runId) {
936
+ process.stdout.write(`signed: ${result.runDir} as ${result.runId} of ${values['run-of']} (by ${result.signature.signedBy})\nrun it: fwdloop run ${values['run-of']} --root <dir> --run-id ${result.runId} --source <role>=<path> ...\n`);
937
+ return;
938
+ }
930
939
  process.stdout.write(`signed: ${result.flowDir} (by ${result.signature.signedBy})\n`);
931
940
  }
932
941
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fwdloop",
3
- "version": "0.19.1",
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
@@ -25,7 +25,8 @@ import { validateDeclaration } from './declaration.js';
25
25
  import { loadCatalogue } from './catalogue.js';
26
26
  import { WIRED_VERBS } from './primitives.js';
27
27
  import { canonicalBytes } from './signature.js';
28
- import { writeFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
28
+ import { writeFlow, writeRunPlan, readFlow, readFileInside, readdirInside, checkFlowName } from './flow.js';
29
+ import { jobKeyOfSigned } from './jobkey.js';
29
30
  import { checkSendDestination } from './runner.js';
30
31
  import { checkKeyPreflight, appendSpendRow } from './provider.js';
31
32
  import { keyValues } from './keysfile.js';
@@ -326,7 +327,7 @@ export async function draftToDir({
326
327
  files['target.json'] = targetText;
327
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.
328
329
  const recordModel = model ?? result.modelId ?? modelId;
329
- 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;
330
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
331
332
  // two as "the draft finished"), as their own files: never in the readout, so never in the hash.
332
333
  if (result.questions?.length) files[QUESTIONS_FILE] = scrub(dj({ questions: result.questions }), secrets);
@@ -398,10 +399,12 @@ export async function draftToDir({
398
399
  * `sessionDir` (the panel's draft folder: card, notes, every change) widens the setup record; the CLI has none, so its record is the one plan folder.
399
400
  * M6: `replaces: {flowHash}` (a draft opened from an existing signed job, carrying that job's signature hash) makes this sign REPLACE that job
400
401
  * (`writeFlow` checks the hash is still the job's); without it a taken name is refused as ever.
401
- * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, keyNames?: string[], sessionDir?: string, replaces?: {flowHash: string}}} a
402
+ * M6 am9: `asRunOf: {flow}` (a red run's redraft of an UNCHANGED job) signs the plan as the plan of a NEW run of that existing workflow: the workflow's own files are
403
+ * never written (`writeRunPlan`), and a plan whose job key is not the workflow's is refused here, at sign time.
404
+ * @param {{dir: any, approve?: any, signedBy: any, signedAt?: string, env?: Record<string, string|undefined>, keyNames?: string[], sessionDir?: string, replaces?: {flowHash: string}, asRunOf?: {flow: string}}} a
402
405
  */
403
406
  export function signDraft({
404
- dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, keyNames, sessionDir, replaces,
407
+ dir, approve, signedBy, signedAt = new Date().toISOString(), env = process.env, keyNames, sessionDir, replaces, asRunOf,
405
408
  }) {
406
409
  const refuse = (...reds) => ({ ok: false, reds });
407
410
  if (readFileInside(dir, LEAK_MARKER_FILE).ok) return refuse(`sign: "${dir}" carries a key-leak marker (${LEAK_MARKER_FILE}) — never signed`);
@@ -455,6 +458,23 @@ export function signDraft({
455
458
  }
456
459
  if (reds.length) return { ok: false, reds };
457
460
 
461
+ if (asRunOf !== undefined) {
462
+ if (target.name !== asRunOf.flow) return refuse(`sign: this draft is named "${target.name}", not the workflow "${asRunOf.flow}" it was drafted as a run of — nothing signed`);
463
+ const existing = readFlow({ root: target.root, name: asRunOf.flow, catalogue: cat.primitives });
464
+ if (!existing.ok) return refuse(`sign: the workflow "${asRunOf.flow}" is not a signed flow that reads (${existing.reds[0]}) — nothing signed`);
465
+ if (jobKeyOfSigned(signed) !== jobKeyOfSigned(existing)) return refuse(`sign: the job in this plan is not the job of "${asRunOf.flow}", so it cannot be a run of it (a changed job is a new workflow) — nothing signed`);
466
+ const ran = writeRunPlan({
467
+ root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives,
468
+ });
469
+ if (!ran.ok) return { ok: false, reds: ran.reds };
470
+ const runSetup = writeSetup({
471
+ flowDir: ran.runDir, sessionDir, planDir: dir, hash: h.hash, signedBy, signedAt, flowHash: ran.signature?.flow, secrets: /** @type {string[]} */ (keys.filter((k) => typeof k === 'string' && k.length >= 8)),
472
+ });
473
+ // the draft's model pick is NOT written to the workflow (its files stay untouched): it is returned for the run that follows (`--model/--provider`)
474
+ return {
475
+ ok: true, flowDir: path.join(target.root, target.name), runId: ran.runId, runDir: ran.runDir, signature: ran.signature, setup: runSetup, modelRecord: { ok: true, recorded: false }, modelPick: readModelRecord(dir),
476
+ };
477
+ }
458
478
  const written = writeFlow({
459
479
  root: target.root, name: target.name, proseText: parts['prose.txt'], declaration, signedBy, signedAt, catalogue: cat.primitives, replaces,
460
480
  });
package/src/books.js CHANGED
@@ -18,15 +18,16 @@
18
18
  // history); both throw (never silently coerce) on a violation, so a bad
19
19
  // caller fails loudly at the one place that would otherwise hide it.
20
20
 
21
- import { appendFileSync, mkdirSync } from 'node:fs';
21
+ import { mkdirSync } from 'node:fs';
22
22
  import { dirname, join } from 'node:path';
23
23
 
24
24
  import { readFileInside, readdirInside } from './flow.js';
25
+ import { appendRow } from './jsonl-append.js';
25
26
  import { TRIGGER_RECORD_FILE } from './trigger-line.js';
26
27
 
27
28
  function appendLine(filePath, row) {
28
29
  mkdirSync(dirname(filePath), { recursive: true });
29
- appendFileSync(filePath, `${JSON.stringify(row)}\n`);
30
+ appendRow(filePath, row);
30
31
  }
31
32
 
32
33
  /**
@@ -65,7 +66,7 @@ export function readPidRows(runDir) {
65
66
  * @param {string} relPath - the book's own file name, relative to baseDir
66
67
  * @returns {any[]}
67
68
  */
68
- function readLines(baseDir, relPath) {
69
+ export function readLines(baseDir, relPath) {
69
70
  const result = readFileInside(baseDir, relPath);
70
71
  if (!result.ok) return [];
71
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;