fwdloop 0.28.0 → 0.29.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 (56) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/ask.js +1 -1
  5. package/src/audit-fold.js +9 -1
  6. package/src/authoring.js +11 -4
  7. package/src/checked.js +5 -2
  8. package/src/checkpick.js +257 -0
  9. package/src/checkwords.js +24 -0
  10. package/src/closers.js +8 -1
  11. package/src/declaration.js +53 -3
  12. package/src/drafter.js +114 -33
  13. package/src/learn.js +1 -1
  14. package/src/learnstore.js +6 -6
  15. package/src/memo.js +120 -0
  16. package/src/model-step.js +89 -17
  17. package/src/pageask.js +9 -6
  18. package/src/pagedropwords.js +9 -0
  19. package/src/panel/author.js +31 -9
  20. package/src/panel/authorcard.js +51 -2
  21. package/src/panel/data.js +12 -7
  22. package/src/panel/index.html +137 -59
  23. package/src/panel/result.js +28 -7
  24. package/src/panel/server.js +2 -1
  25. package/src/pickrecord.js +146 -0
  26. package/src/plain-checks.js +1 -0
  27. package/src/provider.js +4 -1
  28. package/src/runfile.js +4 -2
  29. package/src/runner.js +82 -30
  30. package/src/send.js +71 -4
  31. package/src/setup.js +13 -1
  32. package/types/ask.d.ts +2 -1
  33. package/types/audit-fold.d.ts +13 -2
  34. package/types/authoring.d.ts +6 -2
  35. package/types/checked.d.ts +7 -2
  36. package/types/checkpick.d.ts +149 -0
  37. package/types/checkwords.d.ts +14 -0
  38. package/types/closers.d.ts +2 -1
  39. package/types/declaration.d.ts +9 -0
  40. package/types/drafter.d.ts +12 -25
  41. package/types/learn.d.ts +1 -0
  42. package/types/learnstore.d.ts +2 -3
  43. package/types/memo.d.ts +15 -0
  44. package/types/model-step.d.ts +5 -0
  45. package/types/pageask.d.ts +9 -2
  46. package/types/pagedropwords.d.ts +1 -0
  47. package/types/panel/author.d.ts +1 -1
  48. package/types/panel/authorcard.d.ts +41 -0
  49. package/types/panel/result.d.ts +9 -3
  50. package/types/pickrecord.d.ts +88 -0
  51. package/types/runfile.d.ts +7 -2
  52. package/types/runner.d.ts +16 -5
  53. package/types/send.d.ts +10 -2
  54. package/types/setup.d.ts +1 -56
  55. package/src/attemptdiff.js +0 -118
  56. package/types/attemptdiff.d.ts +0 -38
@@ -0,0 +1,146 @@
1
+ // M10 am17 + am18: the ONE record of check picks, carried from plan to plan. A pick is tied to its job line's WORDS (plus its order among lines with the same words)
2
+ // and to its guardrail's exact words, never to a line or rule number: both are recomputed on the new card. This file is the only writer of a record's entries
3
+ // (`entriesFromAnswers`) and the only reader that decides keep-or-ask (`matchRecord`); the logic is the one F146 / F146b proved (poc/m10-am17/keep-picks-am18.mjs).
4
+ // Throws away: line and rule numbers (recomputed), the model's words (it never sees a pick), a pick whose line or guardrail words no longer match.
5
+ import path from 'node:path';
6
+ import { readFileInside } from './flow.js';
7
+
8
+ /** the record's file, inside a drafting folder only (never a run folder) */
9
+ export const RECORD_FILE = 'picks-record.json';
10
+ /** the exact words a kept pick is marked with in the draft log, the Audit and the plan card (M10 am17 (6)) */
11
+ export const KEPT_WORDS = 'kept from last draft';
12
+
13
+ /** @typedef {{lineWords: string, occurrence: number, ruleText: string, added: string|null, check: Record<string, any>|null, own: boolean, left: boolean}} Entry */
14
+ /** @typedef {{line: number, rule: number, text: string}} Rule */
15
+
16
+ const norm = (/** @type {unknown} */ t) => String(t).toLowerCase().replace(/\s+/g, ' ').trim();
17
+ /** @param {unknown} a @param {unknown} b the two texts are the same words (case and spacing aside) */
18
+ export const sameWords = (a, b) => norm(a) === norm(b);
19
+ const id = (/** @type {Rule} */ r) => `${r.line}:${r.rule}`;
20
+
21
+ /**
22
+ * The key of every job line: its own words, plus how many lines before it have the same words (equal lines match in their order).
23
+ * @param {{n: number, text: string}[]} lines @returns {Map<number, {lineWords: string, occurrence: number}>}
24
+ */
25
+ export function lineKeys(lines) {
26
+ /** @type {Map<string, number>} */
27
+ const seen = new Map();
28
+ return new Map(lines.map((l) => {
29
+ const w = norm(l.text);
30
+ const occurrence = seen.get(w) ?? 0;
31
+ seen.set(w, occurrence + 1);
32
+ return [l.n, { lineWords: w, occurrence }];
33
+ }));
34
+ }
35
+
36
+ /**
37
+ * The entries for answers just given, numbered on THIS card (the answer redraft's card: its line and rule numbers are the ones the asks carried).
38
+ * @param {{n: number, text: string}[]} lines @param {Rule[]} rules
39
+ * @param {{line: number, rule: number, check?: Record<string, any>|null, added?: string|null, own?: boolean}[]} picks @param {{line: number, rule: number}[]} left
40
+ * @returns {Entry[]}
41
+ */
42
+ export function entriesFromAnswers(lines, rules, picks, left) {
43
+ const keys = lineKeys(lines);
44
+ /** @param {number} line @param {number} rule */
45
+ const base = (line, rule) => {
46
+ const r = rules.find((x) => x.line === line && x.rule === rule);
47
+ const k = keys.get(line);
48
+ return r === undefined || k === undefined ? null : { ...k, ruleText: r.text };
49
+ };
50
+ /** @type {Entry[]} */
51
+ const out = [];
52
+ for (const p of picks) {
53
+ const b = base(p.line, p.rule);
54
+ if (b) out.push({ ...b, added: typeof p.added === 'string' ? p.added : null, check: p.check ?? null, own: p.own === true, left: false });
55
+ }
56
+ for (const l of left) {
57
+ const b = base(l.line, l.rule);
58
+ if (b) out.push({ ...b, added: null, check: null, own: false, left: true });
59
+ }
60
+ return out;
61
+ }
62
+
63
+ /**
64
+ * Decide, for the card in hand, which stored picks are kept and which guardrails must be asked.
65
+ * A pick is KEPT when the job line with its words (same order among equal lines) still has its source guardrail with the exact words and, if the pick wrote a `~` line,
66
+ * that line with its exact words too. Otherwise the pick is dropped (never partly kept) and its guardrails are asked: a pair broken on one side is ONE ask, so the
67
+ * partner left on the card is folded (neither asked nor given the old check) - except an EDITED added line (M10 am21): that one is asked (`pairRule` = its source's number) and the source is folded. Pure.
68
+ * @param {Entry[]} entries @param {{n: number, text: string}[]} lines @param {Rule[]} rules every guardrail the call settles
69
+ * @returns {{picks: {line: number, rule: number, check: Record<string, any>|null, added?: string, own?: boolean}[], left: {line: number, rule: number}[],
70
+ * kept: {line: number, rule: number, entry: Entry}[], askRules: (Rule & {pairRule?: number})[]}}
71
+ */
72
+ export function matchRecord(entries, lines, rules) {
73
+ const byKey = new Map([...lineKeys(lines)].map(([n, k]) => [`${k.lineWords}#${k.occurrence}`, n]));
74
+ /** @type {Set<string>} */
75
+ const claimed = new Set();
76
+ /** @type {Set<string>} */
77
+ const folded = new Set();
78
+ /** @type {Map<string, number>} an edited added line (by id) -> the rule number of the source it was paired with (M10 am21) */
79
+ const edited = new Map();
80
+ const free = (/** @type {number} */ n, /** @type {string} */ text) => rules.find((r) => r.line === n && !claimed.has(id(r)) && !folded.has(id(r)) && norm(r.text) === norm(text));
81
+ const kept = [];
82
+ /** @type {{e: Entry, n: number|undefined}[]} */
83
+ const broken = [];
84
+ for (const e of Array.isArray(entries) ? entries : []) {
85
+ const n = byKey.get(`${e.lineWords}#${e.occurrence}`);
86
+ const src = n === undefined ? undefined : free(n, e.ruleText);
87
+ if (src) claimed.add(id(src)); // held while the partner is looked for, so a pair never takes one rule twice
88
+ const add = n === undefined || !src || e.added === null ? undefined : free(n, e.added);
89
+ if (n !== undefined && src && (e.added === null || add)) {
90
+ if (add) claimed.add(id(add));
91
+ kept.push({ line: n, rule: src.rule, entry: e });
92
+ } else {
93
+ if (src) claimed.delete(id(src));
94
+ broken.push({ e, n });
95
+ }
96
+ }
97
+ // a pair broken on one side is ONE pick, so ONE ask: the partner that is left folds into it (it keeps no old check and is not asked on its own)
98
+ for (const { e, n } of broken) {
99
+ if (e.added === null) continue;
100
+ if (n === undefined) {
101
+ // the line's own words changed: it is a new line, all its guardrails are asked; its old `~` line with its source still there rides the source's ask
102
+ for (const l of lines) {
103
+ const s = free(l.n, e.ruleText);
104
+ const a = s ? rules.find((r) => r.line === l.n && r !== s && !claimed.has(id(r)) && !folded.has(id(r)) && norm(r.text) === norm(e.added ?? '')) : undefined;
105
+ if (a) { folded.add(id(a)); break; }
106
+ }
107
+ continue;
108
+ }
109
+ const src = free(n, e.ruleText);
110
+ const add = free(n, e.added);
111
+ if (src && !add) {
112
+ // the added line was edited (or deleted): the unclaimed rule right after the source on that line is it. M10 am21: the ONE ask is about THAT line's words
113
+ // (it carries the source's number as `pairRule`, the rule its pick is kept under); the source rides it and is not asked on its own
114
+ const p = rules.find((r) => r.line === n && r.rule > src.rule && !claimed.has(id(r)) && !folded.has(id(r)));
115
+ if (p) { folded.add(id(src)); edited.set(id(p), src.rule); }
116
+ } else if (add && !src) {
117
+ // the source was edited: the unclaimed rule right before the added line is it; the old added line rides that ask
118
+ const p = [...rules].reverse().find((r) => r.line === n && r.rule < add.rule && !claimed.has(id(r)) && !folded.has(id(r)));
119
+ if (p) folded.add(id(add));
120
+ }
121
+ }
122
+ const picks = [];
123
+ const left = [];
124
+ for (const k of kept) {
125
+ const e = k.entry;
126
+ if (e.left) left.push({ line: k.line, rule: k.rule });
127
+ else picks.push({ line: k.line, rule: k.rule, check: e.check, ...(e.added === null ? {} : { added: e.added }), ...(e.own ? { own: true } : {}) });
128
+ }
129
+ return { picks, left, kept, askRules: rules.filter((r) => !claimed.has(id(r)) && !folded.has(id(r))).map((r) => (edited.has(id(r)) ? { ...r, pairRule: edited.get(id(r)) } : r)) };
130
+ }
131
+
132
+ /**
133
+ * Read a carried record (the folder's file). A missing or unreadable file is no record (a plan from before am17 has none).
134
+ * @param {string} file @returns {Entry[]|null}
135
+ */
136
+ export function readRecordFile(file) {
137
+ try {
138
+ const g = readFileInside(path.dirname(file), path.basename(file));
139
+ if (!g.ok) return null;
140
+ const j = JSON.parse(g.text);
141
+ return Array.isArray(j?.picks) ? j.picks.filter((/** @type {any} */ e) => e && typeof e.lineWords === 'string' && Number.isInteger(e.occurrence) && typeof e.ruleText === 'string') : null;
142
+ } catch { return null; }
143
+ }
144
+
145
+ /** where a plan folder keeps its record @param {string} planDir */
146
+ export const recordPath = (planDir) => path.join(planDir, RECORD_FILE);
@@ -28,6 +28,7 @@ export const PLAN_CHECK_RULES = Object.freeze([
28
28
  { re: /picks|inputFacts|invented name/, say: 'The plan names a field that is not in your input.', fix: 'Check the names in your Inputs and job line, then Draft again.' },
29
29
  { re: /guardrailClasses|unjudgeable|refused/, say: "The AI's notes on which lines it can check are not in a form the checker accepts.", fix: 'Draft again.' },
30
30
  { re: /^line \d+'s (guardrail|check)|can't write files/, say: null, fix: 'Change the guardrail on that line the way the sentence says, then Draft again.' },
31
+ { re: /^Input ".+" is read by no step\.$/, say: null, fix: 'Draft again.' },
31
32
  { re: /must be an? |is required|must name|does not name/, say: 'The plan the AI wrote is not in the shape the checker needs.', fix: 'Draft again.' },
32
33
  ]);
33
34
 
package/src/provider.js CHANGED
@@ -41,7 +41,7 @@ import { OpenAI, Anthropic, Gemini } from 'bare-agent/providers';
41
41
  * marker on the instance (`this.lastMalformedToolCall`, reset at the top of
42
42
  * every `generate()` call) — the one channel `runModelStepOnPrimitives`
43
43
  * (same provider reference) can read after `loop.run()` returns. We require
44
- * bare-agent >=0.50 (package.json `^0.52.0`) and never patch around its
44
+ * bare-agent >=0.50 (package.json `^0.57.0`) and never patch around its
45
45
  * private response internals.
46
46
  */
47
47
  class MalformedToolCallTolerantOpenAI extends OpenAI {
@@ -443,6 +443,9 @@ export function makeProvider(slotName, options = {}) {
443
443
  exposeMalformedArgs: true,
444
444
  });
445
445
 
446
+ // M4d am37: only the OpenAI-shaped provider sends `toolChoice`; the other shapes ignore it, so a forced call there would be a force that was never sent
447
+ /** @type {any} */ (provider).honoursToolChoice = slot.shape === DEFAULT_SHAPE;
448
+
446
449
  return {
447
450
  provider, rates, modelId, slot: slotName, prices,
448
451
  };
package/src/runfile.js CHANGED
@@ -50,10 +50,12 @@ export function readRunInputs(runDir) {
50
50
  * M8b item 1: the ONE writer of `run.json`, called once when a fresh run has frozen its inputs (`runFlow`); never over an existing record. `model` is the pick
51
51
  * the run started on (M4d am33; null = the section is left out), `thinking` the job's "Thinking on" box as it was at the start (M4d am25: written for every fresh
52
52
  * run, ticked or not), `inputs` the manifest `freezeInputs` returned. A fresh run always has `thinking` and `inputs`.
53
- * @param {string} runDir @param {{ model: { slot: string, model: string }|null, thinking: boolean, inputs: any[] }} start
53
+ * @param {string} runDir @param {{ model: { slot: string, model: string }|null, thinking: boolean, inputs: any[], rerun?: {decision: 'rerun', words: string, afterStep: string|null}|null }} start
54
54
  */
55
- export function writeRunStart(runDir, { model, thinking, inputs }) {
55
+ export function writeRunStart(runDir, { model, thinking, inputs, rerun = null }) {
56
56
  writeFileSync(join(runDir, RUN_FILE), `${JSON.stringify({
57
57
  ...(model ? { model: { slot: model.slot, model: model.model } } : {}), thinking, inputs,
58
+ // M14 am1 item 1: a rerun keeps the reason it was started with (the decision, the human's words, the step the old run's ask followed); a fresh run has no such key
59
+ ...(rerun ? { rerun: { decision: rerun.decision, words: rerun.words, afterStep: rerun.afterStep } } : {}),
58
60
  }, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
59
61
  }
package/src/runner.js CHANGED
@@ -76,6 +76,7 @@ import {
76
76
  } from './try-checks.js';
77
77
  import { readJobThinking, readModelRecord, takeLearningsRecord } from './flowmodel.js';
78
78
  import { readRunInputs, writeRunStart } from './runfile.js';
79
+ import { buildMemo } from './memo.js';
79
80
  import { fetchPageText, isWebUrl } from './pagefetch.js';
80
81
  import { readTicketMcp, configForServer, remoteRefusal, mcpStartOpts, startRefusal, firstLine } from './ticket-mcp.js';
81
82
  import { createMCPBridge, discoverServers } from 'bare-agent/mcp';
@@ -226,9 +227,9 @@ const holdOf = (ceilingUsd) => (Number.isFinite(ceilingUsd) && /** @type {number
226
227
  // WITHOUT the cap (M2 scope item 3, the load-bearing invariant).
227
228
  // ---------------------------------------------------------------------------
228
229
 
229
- const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints']);
230
+ const EXECUTOR_FIELDS = Object.freeze(['goal', 'primitives', 'reads', 'gap', 'hints', 'memo']);
230
231
 
231
- /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try */
232
+ /** @param {{goal:string, primitives?:string[], reads?:Record<string,any>, gap?:string|null, hints?:string|null, memo?:string|null}} opts `hints` (M8 am7): the earlier runs' block, text only, for a retry / redo / rerun try; `memo` (M14): what happened so far in this run, text only, every try */
232
233
  export function buildExecutorContext(opts) {
233
234
  for (const key of Object.keys(opts ?? {})) {
234
235
  if (!EXECUTOR_FIELDS.includes(key)) {
@@ -236,7 +237,7 @@ export function buildExecutorContext(opts) {
236
237
  }
237
238
  }
238
239
  const {
239
- goal, primitives = [], reads = {}, gap = null, hints = null,
240
+ goal, primitives = [], reads = {}, gap = null, hints = null, memo = null,
240
241
  } = opts ?? {};
241
242
  return Object.freeze({
242
243
  goal,
@@ -244,6 +245,7 @@ export function buildExecutorContext(opts) {
244
245
  reads: Object.freeze({ ...reads }),
245
246
  gap: gap ?? null,
246
247
  hints: hints ?? null,
248
+ memo: memo ?? null,
247
249
  });
248
250
  }
249
251
 
@@ -251,7 +253,7 @@ export function buildExecutorContext(opts) {
251
253
  * construction test, negative vi). Walks any depth, any key, any array
252
254
  * entry; also catches a bare function value anywhere in the tree. */
253
255
  const FORBIDDEN_CONTEXT_KEYS = Object.freeze([
254
- 'close', 'shape', 'cap', 'strike', 'maxWords', 'sections', 'linesPerInvoice', 'mustCarry',
256
+ 'close', 'shape', 'cap', 'strike', 'maxWords', 'sections', 'linesPerInvoice', 'mustCarry', 'picked',
255
257
  ]);
256
258
 
257
259
  /**
@@ -738,17 +740,17 @@ function recordLateAnswerIfAny(runDir, now = () => new Date().toISOString()) {
738
740
  export const LEARN_ERROR_FILE = 'learn-error.jsonl';
739
741
 
740
742
  /**
741
- * @param {{flowName: string, runId: string, runDir: string, outcome: string, specHash: string|null, now: () => string}} o
743
+ * @param {{flowName: string, runId: string, runDir: string, outcome: string, now: () => string}} o
742
744
  */
743
745
  function recordRunNotes({
744
- flowName, runId, runDir, outcome, specHash, now,
746
+ flowName, runId, runDir, outcome, now,
745
747
  }) {
746
748
  if (NOT_A_RUN_END.has(outcome)) return;
747
749
  const door = configDoorHome();
748
750
  if (door.skip) return;
749
751
  try {
750
752
  const r = learnAtRunEnd({
751
- home: door.home, workflow: flowName, runId, runDir, specHash, now: new Date(now()),
753
+ home: door.home, workflow: flowName, runId, runDir, now: new Date(now()),
752
754
  });
753
755
  if (r.problem) throw new Error(r.problem);
754
756
  } catch (/** @type {any} */ e) {
@@ -819,6 +821,11 @@ function makeAuditRow({
819
821
  hintsText = /** @type {string|undefined} */ (undefined),
820
822
  hintIds = /** @type {string[]|undefined} */ (undefined),
821
823
  hintsError = /** @type {string|undefined} */ (undefined),
824
+ memoText = /** @type {string|undefined} */ (undefined),
825
+ badCalls = /** @type {any[]|undefined} */ (undefined),
826
+ sentSha256 = /** @type {string|undefined} */ (undefined),
827
+ savedBy = /** @type {string|undefined} */ (undefined),
828
+ forcedRefused = /** @type {string|undefined} */ (undefined),
822
829
  }) {
823
830
  const row = {
824
831
  step: step?.emits ?? step?.goal ?? null,
@@ -844,6 +851,16 @@ function makeAuditRow({
844
851
  // (this row, written after the call from what the try held in memory); a failed ask for the block is `hintsError`, the first line, secrets redacted.
845
852
  if (hints !== undefined) { row.hints = hints; row.hintsText = hintsText; row.hintIds = hintIds; }
846
853
  if (hintsError !== undefined) row.hintsError = hintsError;
854
+ // M14 item 7: the exact memo text this try was handed (what happened so far in the run); the key is absent when the try got none. The ONE place the text is kept.
855
+ if (memoText !== undefined) row.memoText = memoText;
856
+ // M14 item 10: bare-agent's facts about this try's calls that went wrong (`badCalls`), as the model step returned them; the key is absent when there were none. The ONE writer.
857
+ if (Array.isArray(badCalls) && badCalls.length > 0) row.badCalls = badCalls;
858
+ // M15 item 4: the sha256 of the plain-text file a send wrote; the key is only on a green send row. The ONE writer; the Result tab reads it to tell the file changed.
859
+ if (typeof sentSha256 === 'string') row.sentSha256 = sentSha256;
860
+ // M4d am37 item 5: which way the model step saved its artifact - `first` (round 1), `forced` (the forced call after the fixed line), `fallback` (the unforced call); absent when it did not save. The ONE writer.
861
+ if (savedBy === 'first' || savedBy === 'forced' || savedBy === 'fallback') row.savedBy = savedBy;
862
+ // M4d am37, ruling A: the fixed say of a try whose forced call the provider refused with no usage returned (it booked $0); absent otherwise. The ONE writer.
863
+ if (typeof forcedRefused === 'string') row.forcedRefused = forcedRefused;
847
864
  return row;
848
865
  }
849
866
 
@@ -956,13 +973,26 @@ async function runStepTries({
956
973
  }
957
974
  }
958
975
  // every row this try writes from here on carries how many hints it was handed, which, and what (none handed = no field)
959
- const rowOf = (/** @type {any} */ a) => makeAuditRow({
976
+ // M14 items 2 and 7: the memo is built fresh from the run's files before EVERY try (src/memo.js), handed whole, and kept on every row this try writes
977
+ const memo = buildMemo(runDir, { step: step?.emits ?? step?.goal ?? null });
978
+ // M14 item 10: this try's `badCalls` come back with the model step's result; every row the try writes carries them
979
+ /** @type {any[]|undefined} */
980
+ let badCalls;
981
+ // M4d am37: how this try's model step saved, as it returned it
982
+ let savedBy;
983
+ let forcedRefused;
984
+ let firstText;
985
+ const rowOf = (/** @type {any} */ a) => withFirstText(makeAuditRow({
960
986
  ...a,
987
+ ...(memo !== '' ? { memoText: memo } : {}),
988
+ ...(badCalls !== undefined ? { badCalls } : {}),
989
+ ...(savedBy !== undefined ? { savedBy } : {}),
990
+ ...(forcedRefused !== undefined ? { forcedRefused } : {}),
961
991
  ...(handed !== null ? { hints: handed.ids.length, hintsText: handed.text, hintIds: handed.ids } : {}),
962
992
  ...(handedError !== undefined ? { hintsError: handedError } : {}),
963
- });
993
+ }), firstText);
964
994
  const executorContext = buildExecutorContext({
965
- goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text,
995
+ goal: step.goal, primitives: step.primitives ?? [], reads: readsMap, gap, hints: handed === null ? null : handed.text, memo: memo === '' ? null : memo,
966
996
  });
967
997
 
968
998
  // `stepMeta` is a SEPARATE argument from `executorContext` — never a
@@ -1005,10 +1035,15 @@ async function runStepTries({
1005
1035
  const tools = first.tools || result.tools ? { ...(first.tools ?? {}) } : null;
1006
1036
  if (tools) for (const [k, v] of Object.entries(result.tools ?? {})) tools[k] = (tools[k] ?? 0) + v;
1007
1037
  const ungranted = [...new Set([...(first.ungranted ?? []), ...(result.ungranted ?? [])])].sort();
1008
- result = { ...result, refused, tools, ...(ungranted.length > 0 ? { ungranted } : {}) };
1038
+ const bad = [...(first.badCalls ?? []), ...(result.badCalls ?? [])];
1039
+ result = { ...result, refused, tools, ...(ungranted.length > 0 ? { ungranted } : {}), ...(bad.length > 0 ? { badCalls: bad } : {}) };
1009
1040
  }
1010
1041
  }
1011
1042
  const wallMs = Date.now() - startedAt;
1043
+ badCalls = Array.isArray(result?.badCalls) ? result.badCalls : undefined;
1044
+ savedBy = typeof result?.savedBy === 'string' ? result.savedBy : undefined;
1045
+ forcedRefused = typeof result?.forcedRefused === 'string' ? result.forcedRefused : undefined;
1046
+ firstText = typeof result?.firstText === 'string' ? result.firstText : undefined;
1012
1047
 
1013
1048
  // A Stop landed during this try: the call in flight finished and is booked here (its cost into the run's spend and onto the one
1014
1049
  // `stopped` row), no new call started. Unknown cost stays unknown (usd null, spend incomplete), never 0.
@@ -1226,13 +1261,14 @@ export async function runStepRalph({ mcpServer = null, ...opts }) {
1226
1261
  * @param {unknown} opts.catalogue - passed straight through to `readFlow`.
1227
1262
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<{ok:boolean, artifact?:unknown, costUsd:number|null, red?:string, transport?:boolean, model?:string, modelMatch?:boolean}>} opts.modelStep
1228
1263
  * @param {(opts:{question:string, evidence:unknown, runDir:string}) => Promise<{decision:'accept'|'redo'|'rerun'|'timeout'|'park', reason?:string, artifactSha256?:string}>} opts.askStep
1229
- * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
1264
+ * @param {(target:string, filename:string, content:unknown, acceptedSha256?:string|null) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
1230
1265
  * @param {Record<string, any>} [opts.primitives] - injected primitive implementations, keyed by catalogue verb.
1231
1266
  * @param {string[]} [opts.primitiveReds] - `resolvePrimitives`'s own `reds` (e.g. bareguard refusing a symlinked file scope); any entry refuses the run at $0 like an unwired verb, before the run dir exists.
1232
1267
  * @param {() => string} [opts.clock] - returns the current ISO timestamp; defaults to the wall clock.
1233
1268
  * @param {string} opts.businessDate - the run's explicit "as of today", never the wall clock.
1234
1269
  * @param {number} [opts.ceilingUsd] - per-attempt ceiling override; the model's hold from Settings prices (`ceilingCostUsd`); absent = no hold.
1235
1270
  * @param {{slot: string, model: string}} [opts.runModel] - M4d am33: the model this run started on; recorded once in the run folder (run.json) and kept by every resume/continue.
1271
+ * @param {{decision: 'rerun', words: string, afterStep: string|null}} [opts.rerunOf] - M14 am1 item 1: only `resumeRun`'s rerun path passes it; kept in the new run's run.json
1236
1272
  * @param {string|null} [opts.initialGap] - M3 scope item 7 (rerun as a fresh
1237
1273
  * run): a human's rerun reason, carried as the FIRST ordinary step's
1238
1274
  * starting gap. Never used by a plain `runFlow` call outside `resumeRun`'s
@@ -1244,6 +1280,8 @@ export async function runStepRalph({ mcpServer = null, ...opts }) {
1244
1280
  */
1245
1281
  export async function runFlow({
1246
1282
  root, name, runId, sources, catalogue, modelStep, askStep, sendStep, primitives, primitiveReds, clock, businessDate, ceilingUsd, initialGap, fetchPage,
1283
+ // M14 am1 item 1: set only by `resumeRun`'s rerun path ({decision, words, afterStep}); written once into run.json by `writeRunStart`
1284
+ rerunOf,
1247
1285
  // M4d am33: the model this run STARTED on ({ slot, model }); recorded once beside the run, kept by every resume/continue. Absent = nothing recorded.
1248
1286
  runModel,
1249
1287
  // F45 finding 3's test needs to advance wall time across a park/resume
@@ -1374,7 +1412,7 @@ export async function runFlow({
1374
1412
  });
1375
1413
  }
1376
1414
  // M8b item 1: the run's start record, written once: the model it started on (M4d am33), the "Thinking on" box (M4d am25) and the frozen inputs
1377
- writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest) });
1415
+ writeRunStart(runDir, { model: runModel ?? null, thinking: thinkingBox, inputs: /** @type {any[]} */ (frozen.manifest), rerun: rerunOf ?? null });
1378
1416
  // M12 piece 3 (item 9): a ticket the signed labels do not match, or a closed one, ends here: skipped, $0, nothing else runs
1379
1417
  if (frozen.skip) {
1380
1418
  return haltRun({
@@ -1408,9 +1446,7 @@ export async function runFlow({
1408
1446
  appendAudit(runDir, fullRow);
1409
1447
  if (row.spendComplete === false) spendComplete.value = false;
1410
1448
  if (modelOutput !== undefined) {
1411
- attemptsLog.push({
1412
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
1413
- });
1449
+ attemptsLog.push(attemptEntry(row, modelOutput));
1414
1450
  }
1415
1451
  };
1416
1452
  const spent = { value: 0 };
@@ -1478,7 +1514,7 @@ export async function runFlow({
1478
1514
  firstStepGap: initialGap ?? null,
1479
1515
  });
1480
1516
  recordRunNotes({
1481
- flowName: name, runId, runDir, outcome: result.outcome, specHash: signature.flow, now,
1517
+ flowName: name, runId, runDir, outcome: result.outcome, now,
1482
1518
  });
1483
1519
 
1484
1520
  if (result.outcome === 'complete') return { ...result, auditRows };
@@ -1880,11 +1916,12 @@ async function foldFromStep({
1880
1916
  });
1881
1917
  }
1882
1918
  const content = contentResult.value;
1883
- const filename = `${flowName}-${runId}-${step.emits}.json`;
1919
+ const filename = `${flowName}-${runId}-${step.emits}.md`;
1884
1920
  // eslint-disable-next-line no-await-in-loop
1885
1921
  const sendResult = await sendStep(target, filename, content, acceptedAskEmitsThisRun.get(askArtifactId), { root: flowRoot, runDir });
1886
1922
  const sendRow = makeAuditRow({
1887
1923
  step, attempt: 1, verdict: sendResult.ok ? 'green' : 'red', gap: sendResult.ok ? null : sendResult.red, usd: 0, spendComplete: true, wallMs: 0, strike: false, at: now(),
1924
+ ...(sendResult.ok && typeof sendResult.sha256 === 'string' ? { sentSha256: sendResult.sha256 } : {}),
1888
1925
  });
1889
1926
  recordAudit(sendRow);
1890
1927
  if (!sendResult.ok) {
@@ -2173,7 +2210,7 @@ function sameRoot(recorded, requested) {
2173
2210
  * @param {string} opts.runId
2174
2211
  * @param {unknown} opts.catalogue
2175
2212
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
2176
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
2213
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
2177
2214
  * @param {Record<string, any>} [opts.primitives]
2178
2215
  * @param {string[]} [opts.primitiveReds] - see `runFlow`'s own.
2179
2216
  * @param {() => string} [opts.clock]
@@ -2463,7 +2500,7 @@ export async function resumeRun({
2463
2500
  runId, at: now(), outcome: 'ask-expired', spentUsd: spent.value, spendComplete: spendComplete.value, capUsd: arbiter.capUsd ?? null, wallMs: getNowMs() - runStartedAt, signatureHash: state.signatureHash,
2464
2501
  });
2465
2502
  recordRunNotes({
2466
- flowName: name, runId, runDir, outcome: 'ask-expired', specHash: state.signatureHash, now,
2503
+ flowName: name, runId, runDir, outcome: 'ask-expired', now,
2467
2504
  });
2468
2505
  return { outcome: 'ask-expired', runDir, spentUsd: spent.value };
2469
2506
  }
@@ -2500,7 +2537,7 @@ export async function resumeRun({
2500
2537
  }
2501
2538
  // M8 am4: a rerun ends THIS run, so its notes count now (the new run, started below, makes its own).
2502
2539
  recordRunNotes({
2503
- flowName: name, runId, runDir, outcome: 'rerun', specHash: state.signatureHash, now,
2540
+ flowName: name, runId, runDir, outcome: 'rerun', now,
2504
2541
  });
2505
2542
 
2506
2543
  // Deterministic derived id (M3 scope item 7) — refused by name, never
@@ -2540,6 +2577,8 @@ export async function resumeRun({
2540
2577
  runModel,
2541
2578
  // Item 7: the reason becomes the new run's FIRST step's starting gap.
2542
2579
  initialGap: reason,
2580
+ // M14 am1 item 1: the new run keeps the reason in its own run.json (decision, words, the step the old run's ask followed; null = the ask was first)
2581
+ rerunOf: { decision: 'rerun', words: reason, afterStep: steps[state.stepIndex - 1]?.emits ?? null },
2543
2582
  });
2544
2583
 
2545
2584
  return {
@@ -2582,9 +2621,7 @@ export async function resumeRun({
2582
2621
  appendAudit(runDir, fullRow);
2583
2622
  if (row.spendComplete === false) spendComplete.value = false;
2584
2623
  if (modelOutput !== undefined) {
2585
- attemptsLog.push({
2586
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
2587
- });
2624
+ attemptsLog.push(attemptEntry(row, modelOutput));
2588
2625
  }
2589
2626
  };
2590
2627
 
@@ -2696,7 +2733,7 @@ export async function resumeRun({
2696
2733
  attemptsLog,
2697
2734
  });
2698
2735
  recordRunNotes({
2699
- flowName: name, runId, runDir, outcome: result.outcome, specHash: state.signatureHash, now,
2736
+ flowName: name, runId, runDir, outcome: result.outcome, now,
2700
2737
  });
2701
2738
 
2702
2739
  if (result.outcome === 'complete') return { ...result, auditRows };
@@ -2732,7 +2769,7 @@ export function auditSpend(runDir) {
2732
2769
  * @param {string} opts.runId
2733
2770
  * @param {unknown} opts.catalogue
2734
2771
  * @param {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class:string|null}) => Promise<any>} opts.modelStep
2735
- * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number}>} opts.sendStep
2772
+ * @param {(target:string, filename:string, content:unknown) => Promise<{ok:boolean, red?:string, bytes?:number, sha256?:string}>} opts.sendStep
2736
2773
  * @param {Record<string, any>} [opts.primitives]
2737
2774
  * @param {string[]} [opts.primitiveReds]
2738
2775
  * @param {() => string} [opts.clock]
@@ -2849,9 +2886,7 @@ export async function continueRun({
2849
2886
  appendAudit(runDir, fullRow);
2850
2887
  if (row.spendComplete === false) spendComplete.value = false;
2851
2888
  if (modelOutput !== undefined) {
2852
- attemptsLog.push({
2853
- step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput,
2854
- });
2889
+ attemptsLog.push(attemptEntry(row, modelOutput));
2855
2890
  }
2856
2891
  };
2857
2892
  const runStartedAt = typeof halt.startedAt === 'number' ? halt.startedAt : startedAt;
@@ -2905,7 +2940,7 @@ export async function continueRun({
2905
2940
  attemptsLog,
2906
2941
  });
2907
2942
  recordRunNotes({
2908
- flowName: name, runId, runDir, outcome: result.outcome, specHash: halt.signatureHash, now,
2943
+ flowName: name, runId, runDir, outcome: result.outcome, now,
2909
2944
  });
2910
2945
  if (result.outcome === 'complete') return { ...result, auditRows };
2911
2946
  return result;
@@ -3009,6 +3044,23 @@ export async function stopParkedRun({
3009
3044
  }
3010
3045
  }
3011
3046
 
3047
+ /** hamr's ask 2026-11-03: the round-1 text of a try a later round saved. Held beside the audit row (rows stay small), read by `attemptEntry` only. */
3048
+ const FIRST_TEXT = new WeakMap();
3049
+
3050
+ /** Registers a try's round-1 text against its audit row (the row itself is unchanged). */
3051
+ function withFirstText(row, firstText) {
3052
+ if (firstText !== undefined) FIRST_TEXT.set(row, firstText);
3053
+ return row;
3054
+ }
3055
+
3056
+ /** The ONE builder of a try's log.json entry (what the model said, per try), for the three `recordAudit`s; `firstText` is there only when a later round saved. */
3057
+ function attemptEntry(row, modelOutput) {
3058
+ const firstText = FIRST_TEXT.get(row);
3059
+ return {
3060
+ step: row.step, attempt: row.attempt, class: row.class, verdict: row.verdict, gap: row.gap, ...(row.refused ? { refused: row.refused } : {}), modelOutput, ...(firstText !== undefined ? { firstText } : {}),
3061
+ };
3062
+ }
3063
+
3012
3064
  /** log.json's one writer, called from every exit path (complete + every
3013
3065
  * halt) — M2 scope item 9 / the M0 ruling: what the model wrote, every
3014
3066
  * attempt, red runs included, never just the final artifacts. */
package/src/send.js CHANGED
@@ -11,6 +11,7 @@
11
11
  // in-memory content handed in — so a write that silently truncates to 0
12
12
  // bytes reds here, not upstream).
13
13
 
14
+ import { createHash } from 'node:crypto';
14
15
  import { lstatSync, readFileSync } from 'node:fs';
15
16
  import { join } from 'node:path';
16
17
  import { createShellTools } from 'bare-agent/tools';
@@ -23,15 +24,81 @@ const FOUND_WRITE_TOOL = SHELL_TOOLS.find((t) => t.name === 'shell_write');
23
24
  if (!FOUND_WRITE_TOOL) throw new Error('send: bare-agent/tools does not export a "shell_write" tool');
24
25
  const WRITE_TOOL = FOUND_WRITE_TOOL;
25
26
 
27
+ const SCALAR = ['string', 'number', 'boolean'];
28
+
29
+ /** one value as leaf lines `{parts, text}`: parts are the names on the way in; text is a string as it is, a number or boolean written out; a list of plain values joined by ", "; null as empty */
30
+ /** @param {string[]} parts @param {any} v @returns {{parts: string[], text: string}[]} */
31
+ function leaves(parts, v) {
32
+ if (v === null || v === undefined) return [{ parts, text: '' }];
33
+ if (SCALAR.includes(typeof v)) return [{ parts, text: `${v}` }];
34
+ if (Array.isArray(v) && v.every((x) => x === null || SCALAR.includes(typeof x))) return [{ parts, text: v.join(', ') }];
35
+ if (Array.isArray(v)) return v.flatMap((x, i) => leaves([...parts, `${i + 1}`], x));
36
+ return Object.entries(v).flatMap(([k, x]) => leaves([...parts, k], x));
37
+ }
38
+
39
+ /** @param {string} name split only at a lowercase-to-capital boundary, `_` and `-`, so `ID` stays one word */
40
+ const words = (name) => name.replace(/([a-z0-9])([A-Z])/g, '$1 $2').split(/[_\-\s]+/).filter(Boolean);
41
+
42
+ /** M15 am2 (1): the names as plain words; a last name of `value` or `rows` is left out; the first letter capital, the later words lowercase */
43
+ /** @param {string[]} parts */
44
+ function friendlyName(parts) {
45
+ const p = parts.length > 1 && (parts[parts.length - 1] === 'value' || parts[parts.length - 1] === 'rows') ? parts.slice(0, -1) : parts;
46
+ const w = p.flatMap(words).map((x) => x.toLowerCase());
47
+ if (!w.length) return parts.join('.');
48
+ return w[0][0].toUpperCase() + w[0].slice(1) + (w.length > 1 ? ` ${w.slice(1).join(' ')}` : '');
49
+ }
50
+
51
+ /** the lines of one block (the flat part, or one result); two lines with the same words both keep today's `a.b` form */
52
+ /** @param {{parts: string[], text: string}[]} ls */
53
+ function blockLines(ls) {
54
+ const f = ls.map((l) => friendlyName(l.parts));
55
+ /** @type {Record<string, number>} */
56
+ const n = {};
57
+ for (const x of f) n[x] = (n[x] || 0) + 1;
58
+ return ls.map((l, i) => `${n[f[i]] > 1 ? l.parts.join('.') : f[i]}: ${l.text}`);
59
+ }
60
+
61
+ /** a list of results: every item an object holding a `values` object (flights' `results`, with a `quote` written as its last line) */
62
+ /** @param {any} v */
63
+ const isResultList = (v) => Array.isArray(v) && v.length > 0 && v.every((r) => r && typeof r === 'object' && !Array.isArray(r) && r.values && typeof r.values === 'object' && !Array.isArray(r.values));
64
+
65
+ /**
66
+ * M15 items 3 and am1, am2: the accepted answer as the plain-text file the send writes. `{text}` alone is the text exactly; any other flat object is one
67
+ * `Name words: value` line per field; a list of results is one `## Result k` block per result with one line per value, in the order the answer holds
68
+ * them, then `from the page: "<quote>"`. Never JSON braces, never check marks. What it throws away: a result's keys other than `quote` and `values`.
69
+ * @param {Record<string, any>} content @returns {string}
70
+ */
71
+ export function renderSentMd(content) {
72
+ const keys = Object.keys(content);
73
+ if (keys.length === 1 && keys[0] === 'text' && typeof content.text === 'string') return content.text;
74
+ /** @type {string[]} */
75
+ const parts = [];
76
+ /** @type {{parts: string[], text: string}[]} */
77
+ let flat = [];
78
+ const flush = () => { if (flat.length) parts.push(blockLines(flat).join('\n')); flat = []; };
79
+ for (const [k, v] of Object.entries(content)) {
80
+ if (isResultList(v)) {
81
+ flush();
82
+ v.forEach((r, i) => {
83
+ const lines = blockLines(Object.entries(r.values).flatMap(([n, x]) => leaves([n], x)));
84
+ if (typeof r.quote === 'string') lines.push(`from the page: "${r.quote}"`);
85
+ parts.push([`## Result ${i + 1}`, ...lines].join('\n'));
86
+ });
87
+ } else flat.push(...leaves([k], v));
88
+ }
89
+ flush();
90
+ return parts.join('\n\n');
91
+ }
92
+
26
93
  /**
27
94
  * @param {string} target - a signed arbiter target, e.g. `file:poc/m0/out`.
28
95
  * @param {string} filename
29
- * @param {unknown} content - JSON-serialised before writing.
96
+ * @param {unknown} content - the accepted artifact; hash-checked as its JSON, written as plain text (`renderSentMd`).
30
97
  * @param {string|null} [acceptedSha256] - the sha256 the human's accept recorded
31
98
  * (`answerAsk`, M4b piece 3). Required: none recorded (an answer written by an
32
99
  * older version, or no accept in this process) refuses by name.
33
100
  * @param {{root?: string, runDir?: string}} [ctx] the flow root and this run's folder, for the destination refusals
34
- * @returns {Promise<{ok:true, path:string, bytes:number} | {ok:false, red:string}>}
101
+ * @returns {Promise<{ok:true, path:string, bytes:number, sha256:string} | {ok:false, red:string}>}
35
102
  */
36
103
  export async function sendViaPrimitive(target, filename, content, acceptedSha256, ctx = {}) {
37
104
  const destination = checkSendDestination(target, ctx);
@@ -77,11 +144,11 @@ export async function sendViaPrimitive(target, filename, content, acceptedSha256
77
144
  let present = true;
78
145
  try { lstatSync(path); } catch (err) { if (err.code === 'ENOENT') present = false; }
79
146
  if (present) return { ok: false, red: `send: "${path}" already exists — never overwritten (nothing shipped)` };
80
- await WRITE_TOOL.execute({ path, content: serialised });
147
+ await WRITE_TOOL.execute({ path, content: renderSentMd(/** @type {Record<string, unknown>} */ (content)) });
81
148
 
82
149
  const bytes = readFileSync(path);
83
150
  if (bytes.byteLength === 0) {
84
151
  return { ok: false, red: `send: "${path}" wrote 0 bytes` };
85
152
  }
86
- return { ok: true, path, bytes: bytes.byteLength };
153
+ return { ok: true, path, bytes: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') };
87
154
  }
package/src/setup.js CHANGED
@@ -16,6 +16,8 @@ import { notCheckedBlock } from './checked.js';
16
16
  import { readDraftSpend } from './draftspend.js';
17
17
  import { readFileInside, readdirInside } from './flow.js';
18
18
  import { readSpendRows } from './provider.js';
19
+ import { checkAsks } from './checkpick.js';
20
+ import { RECORD_FILE, KEPT_WORDS } from './pickrecord.js';
19
21
 
20
22
  export const SETUP_FILE = 'setup.jsonl';
21
23
  const CARD_RE = /^card-(\d+)\.json$/;
@@ -65,10 +67,20 @@ function planRow(sessionDir, rel, kind, n) {
65
67
  * @param {string} sessionDir @param {string} rel
66
68
  */
67
69
  function humanRows(sessionDir, rel) {
68
- return readQuestions(join(sessionDir, rel)).questions.filter((q) => q.source === 'look' && q.answer !== null).map((q) => ({
70
+ const answered = readQuestions(join(sessionDir, rel)).questions.filter((q) => q.source === 'look' && q.answer !== null).map((q) => ({
69
71
  kind: 'human', n: q.k, at: q.at ?? null, source: 'look', ask: q.ask, question: q.question, answer: q.answer, line: q.line,
70
72
  ruleNo: q.ruleNo, ruleText: q.ruleText, proposal: q.proposal ?? null, rule: q.rule ?? null,
71
73
  }));
74
+ // M10 am17 (6): a pick kept from the last draft is the same row, from this plan's picks record (not an answer file), its answer being the words `kept from last draft`
75
+ const kept = Array.isArray(readJson(join(sessionDir, rel), RECORD_FILE)?.kept) ? readJson(join(sessionDir, rel), RECORD_FILE).kept : [];
76
+ const keptRows = kept.map((k, i) => {
77
+ const [ask] = checkAsks([{ line: k.line, rule: k.rule, text: k.ruleText, check: k.check ?? null, why: null }]);
78
+ return {
79
+ kind: 'human', n: answered.length + i + 1, at: null, source: 'look', ask: ask.ask, question: ask.question, answer: KEPT_WORDS, line: k.line,
80
+ ruleNo: k.rule, ruleText: k.ruleText, proposal: ask.reading ?? null, rule: k.added ?? null,
81
+ };
82
+ });
83
+ return [...answered, ...keptRows];
72
84
  }
73
85
 
74
86
  /**