fwdloop 0.27.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 (105) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +54 -13
  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 +22 -5
  7. package/src/canrun.js +19 -16
  8. package/src/checked.js +5 -2
  9. package/src/checkpick.js +257 -0
  10. package/src/checkwords.js +24 -0
  11. package/src/closers.js +8 -1
  12. package/src/config.js +18 -0
  13. package/src/declaration.js +85 -5
  14. package/src/drafter.js +143 -47
  15. package/src/flow.js +2 -1
  16. package/src/launcher.js +4 -2
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +8 -7
  19. package/src/mcp-checks.js +50 -0
  20. package/src/mcp-pick.js +33 -0
  21. package/src/mcp-sources.js +84 -0
  22. package/src/mcp-use.js +54 -0
  23. package/src/memo.js +120 -0
  24. package/src/model-step.js +89 -17
  25. package/src/natural.js +23 -0
  26. package/src/pageask.js +9 -6
  27. package/src/pagedropwords.js +9 -0
  28. package/src/panel/author.js +50 -28
  29. package/src/panel/authorcard.js +86 -2
  30. package/src/panel/authorflows.js +18 -14
  31. package/src/panel/authortrigger.js +241 -84
  32. package/src/panel/data.js +99 -11
  33. package/src/panel/index.html +683 -210
  34. package/src/panel/jobgrid.js +127 -0
  35. package/src/panel/result.js +28 -7
  36. package/src/panel/scheduler.js +8 -2
  37. package/src/panel/server.js +17 -7
  38. package/src/panel/settings.js +119 -4
  39. package/src/panel/tickets.js +12 -7
  40. package/src/pickrecord.js +146 -0
  41. package/src/plain-checks.js +1 -0
  42. package/src/primitives.js +34 -5
  43. package/src/provider.js +4 -1
  44. package/src/runfile.js +4 -2
  45. package/src/runner.js +170 -45
  46. package/src/send.js +71 -4
  47. package/src/setup.js +13 -1
  48. package/src/summary-words.js +15 -3
  49. package/src/ticket-draft.js +40 -42
  50. package/src/ticket-labels.js +10 -0
  51. package/src/ticket-mcp.js +33 -10
  52. package/src/ticket-next.js +33 -0
  53. package/src/ticket-shape.js +9 -0
  54. package/src/trigger-clock.js +4 -4
  55. package/src/trigger-files.js +3 -3
  56. package/src/trigger-tickets.js +41 -12
  57. package/types/ask.d.ts +2 -1
  58. package/types/audit-fold.d.ts +13 -2
  59. package/types/authoring.d.ts +10 -2
  60. package/types/canrun.d.ts +5 -12
  61. package/types/checked.d.ts +7 -2
  62. package/types/checkpick.d.ts +149 -0
  63. package/types/checkwords.d.ts +14 -0
  64. package/types/closers.d.ts +2 -1
  65. package/types/config.d.ts +6 -0
  66. package/types/declaration.d.ts +17 -0
  67. package/types/drafter.d.ts +446 -50
  68. package/types/learn.d.ts +1 -0
  69. package/types/learnstore.d.ts +2 -3
  70. package/types/mcp-checks.d.ts +8 -0
  71. package/types/mcp-pick.d.ts +23 -0
  72. package/types/mcp-sources.d.ts +51 -0
  73. package/types/mcp-use.d.ts +12 -0
  74. package/types/memo.d.ts +15 -0
  75. package/types/model-step.d.ts +5 -0
  76. package/types/natural.d.ts +2 -0
  77. package/types/pageask.d.ts +9 -2
  78. package/types/pagedropwords.d.ts +1 -0
  79. package/types/panel/author.d.ts +37 -1
  80. package/types/panel/authorcard.d.ts +52 -0
  81. package/types/panel/authorflows.d.ts +9 -1
  82. package/types/panel/authortrigger.d.ts +73 -7
  83. package/types/panel/data.d.ts +56 -2
  84. package/types/panel/jobgrid.d.ts +109 -0
  85. package/types/panel/result.d.ts +9 -3
  86. package/types/panel/server.d.ts +5 -1
  87. package/types/panel/settings.d.ts +3 -2
  88. package/types/panel/tickets.d.ts +26 -4
  89. package/types/pickrecord.d.ts +88 -0
  90. package/types/primitives.d.ts +15 -2
  91. package/types/runfile.d.ts +7 -2
  92. package/types/runner.d.ts +128 -77
  93. package/types/send.d.ts +10 -2
  94. package/types/setup.d.ts +1 -56
  95. package/types/summary-words.d.ts +22 -3
  96. package/types/ticket-draft.d.ts +40 -32
  97. package/types/ticket-labels.d.ts +6 -0
  98. package/types/ticket-mcp.d.ts +18 -1
  99. package/types/ticket-next.d.ts +23 -0
  100. package/types/ticket-shape.d.ts +5 -0
  101. package/types/trigger-clock.d.ts +4 -3
  102. package/types/trigger-files.d.ts +1 -1
  103. package/types/trigger-tickets.d.ts +18 -4
  104. package/src/attemptdiff.js +0 -118
  105. package/types/attemptdiff.d.ts +0 -38
@@ -0,0 +1,84 @@
1
+ // M13 piece 3 (docs/wiki/the-module-ladder.md, M13 scope items 1 and 2): the ONE place that decides where fwdloop's MCP servers come from.
2
+ // Sources, in order: the 4 places bare-agent reads, then the paths the person added on Settings > MCP (config.json `mcpPaths`, in the order added).
3
+ // A project folder's `.mcp.json` is never read: every path here is explicit, bare-agent's default discovery is never called (F108 c).
4
+ // bare-agent's `discoverServers` is called once PER PATH (it merges silently and keeps no file of origin, F108 a); the merge, "first wins" and the shadow mark are done here.
5
+ // A server with no `command` (a remote one) is listed and marked `remote`: it is never started. This file only READS the config files and
6
+ // returns names, flags and file paths; a command, its args and its env are never copied out of `discoverServers`' result.
7
+ import { discoverServers } from 'bare-agent/mcp';
8
+ import { existsSync, readFileSync } from 'node:fs';
9
+ import { homedir } from 'node:os';
10
+ import { join } from 'node:path';
11
+ import { readConfig, configDoorHome, ConfigError } from './config.js';
12
+
13
+ export { mcpPathProblem } from './config.js';
14
+
15
+ /** the 4 places bare-agent reads, in its order (absolute) */
16
+ export const DEFAULT_MCP_PLACES = () => {
17
+ const h = homedir();
18
+ return [join(h, '.mcp.json'), join(h, '.claude', 'mcp_servers.json'), join(h, '.config', 'Claude', 'claude_desktop_config.json'), join(h, '.cursor', 'mcp.json')];
19
+ };
20
+
21
+ /** a typed path as a real one: `~/` is the home folder @param {string} p */
22
+ export const expandMcpPath = (p) => (p === '~' ? homedir() : p.startsWith('~/') ? join(homedir(), p.slice(2)) : p);
23
+
24
+ /** a path as the page shows it: the home folder written `~` @param {string} p */
25
+ export const showMcpPath = (p) => { const h = homedir(); return p === h ? '~' : p.startsWith(`${h}/`) ? `~${p.slice(h.length)}` : p; };
26
+
27
+ /** the added paths in config.json (typed form); none under a test process with no config home, or when config.json is broken (the page says so) @param {string} [home] */
28
+ export function addedMcpPaths(home) {
29
+ let h = home;
30
+ if (h === undefined) { const door = configDoorHome(); if (door.skip) return { paths: [], problem: null }; h = door.home; }
31
+ try {
32
+ const c = readConfig({ home: h });
33
+ return { paths: Array.isArray(c.mcpPaths) ? /** @type {string[]} */ (c.mcpPaths) : [], problem: null };
34
+ } catch (e) {
35
+ if (!(e instanceof ConfigError)) throw e;
36
+ return { paths: [], problem: 'Your settings file (config.json) cannot be read, so added paths are not shown.' };
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Every place, in order, with the servers found in it.
42
+ * `status`: 'found' (a readable file), 'missing' (no file) or 'not-json' (a file that is not JSON; bare-agent skips it silently).
43
+ * A server: `{name, remote, shadowedBy}`; `shadowedBy` is the shown path of the earlier place that has the same name (the earlier one wins), or null.
44
+ * @param {{ home?: string }} [o] `home` the config home (tests); undefined = the door's
45
+ * @returns {{ places: Array<{ path: string, file: string, added: boolean, status: 'found'|'missing'|'not-json', servers: Array<{name: string, remote: boolean, shadowedBy: string|null}> }>, problem: string|null }}
46
+ */
47
+ export function mcpSources(o = {}) {
48
+ const added = addedMcpPaths(o.home);
49
+ const typed = [...DEFAULT_MCP_PLACES().map((p) => ({ path: showMcpPath(p), added: false })), ...added.paths.map((p) => ({ path: p, added: true }))];
50
+ /** @type {Map<string, string>} */
51
+ const first = new Map();
52
+ const places = typed.map(({ path, added: isAdded }) => {
53
+ const file = expandMcpPath(path);
54
+ if (!existsSync(file)) return { path, file, added: isAdded, status: /** @type {const} */ ('missing'), servers: [] };
55
+ try { JSON.parse(readFileSync(file, 'utf8')); } catch { return { path, file, added: isAdded, status: /** @type {const} */ ('not-json'), servers: [] }; }
56
+ const found = discoverServers([file]);
57
+ const servers = [...found].map(([name, def]) => {
58
+ const shadowedBy = first.get(name) ?? null;
59
+ if (shadowedBy === null) first.set(name, path);
60
+ return { name, remote: typeof def?.command !== 'string' || def.command === '', shadowedBy };
61
+ });
62
+ return { path, file, added: isAdded, status: /** @type {const} */ ('found'), servers };
63
+ });
64
+ return { places, problem: added.problem };
65
+ }
66
+
67
+ /**
68
+ * The file that holds the WINNING `server` (the first place in the list that has the name), whether it is remote, or null when no place has it.
69
+ * Every place fwdloop starts an MCP from takes its config file from here.
70
+ * @param {string} server @param {{ home?: string }} [o]
71
+ * @returns {{ file: string, remote: boolean } | null}
72
+ */
73
+ export function mcpConfigFor(server, o = {}) {
74
+ for (const p of mcpSources(o).places) {
75
+ const s = p.servers.find((x) => x.name === server);
76
+ if (s) return { file: p.file, remote: s.remote };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ /** the names of the servers that can be started (winners only, remote left out) @param {{ home?: string }} [o] @returns {string[]} */
82
+ export function startableMcpServers(o = {}) {
83
+ return mcpSources(o).places.flatMap((p) => p.servers.filter((s) => !s.remote && s.shadowedBy === null).map((s) => s.name));
84
+ }
package/src/mcp-use.js ADDED
@@ -0,0 +1,54 @@
1
+ // M13 piece 3 (docs/wiki/the-module-ladder.md, M13 scope item 2 "Use counts come from what runs already record"; FINDINGS F113): how often each MCP server's tools were used,
2
+ // read from what runs already keep. No new run-folder file, nothing is written.
3
+ // - a ticket read: `run.json` `inputs[].mcp.calls` (server + tool; the file holds no time, so `last` is the file's mtime);
4
+ // - a step's tool call: a `kind:"tool"` row of `diary.jsonl` whose tool is `<server>_<tool>` (M13 piece 2); `decision:"deny"` is a denied call, counted apart and not as a use.
5
+ // A torn or unreadable file is skipped, row by row (its rows go missing from the count; it never breaks the page).
6
+ import { readdirSync, readFileSync, statSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+
9
+ const safeDir = (/** @type {string} */ p) => { try { return readdirSync(p); } catch { return []; } };
10
+
11
+ /**
12
+ * @param {string} root the jobs folder (`<root>/<flow>/runs/run-<n>/`)
13
+ * @param {string[]} servers the server names to count for; a step tool row belongs to the LONGEST name that prefixes it with `_`
14
+ * @returns {Map<string, { calls: number, runs: number, last: string|null, denied: number, tools: Map<string, number> }>}
15
+ */
16
+ export function countMcpUse(root, servers) {
17
+ const byLength = [...servers].sort((a, b) => b.length - a.length);
18
+ /** @type {Map<string, { calls: number, runSet: Set<string>, last: string, denied: number, tools: Map<string, number> }>} */
19
+ const acc = new Map(servers.map((s) => [s, { calls: 0, runSet: new Set(), last: '', denied: 0, tools: new Map() }]));
20
+ const use = (/** @type {string} */ server, /** @type {string} */ tool, /** @type {string} */ run, /** @type {string} */ at, /** @type {boolean} */ denied) => {
21
+ const a = acc.get(server);
22
+ if (!a) return;
23
+ if (denied) { a.denied++; return; }
24
+ a.calls++; a.runSet.add(run); a.tools.set(tool, (a.tools.get(tool) ?? 0) + 1);
25
+ if (at && at > a.last) a.last = at;
26
+ };
27
+ for (const flow of safeDir(root)) {
28
+ for (const name of safeDir(join(root, flow, 'runs'))) {
29
+ if (!name.startsWith('run-')) continue;
30
+ const dir = join(root, flow, 'runs', name);
31
+ const key = `${flow}/${name}`;
32
+ try {
33
+ const j = JSON.parse(readFileSync(join(dir, 'run.json'), 'utf8'));
34
+ const mtime = statSync(join(dir, 'run.json')).mtime.toISOString();
35
+ for (const i of Array.isArray(j?.inputs) ? j.inputs : []) {
36
+ const m = i?.mcp;
37
+ if (!m || typeof m.server !== 'string') continue;
38
+ for (const c of Array.isArray(m.calls) ? m.calls : []) if (typeof c?.tool === 'string') use(m.server, c.tool, key, mtime, false);
39
+ }
40
+ } catch { /* no run.json, or torn: nothing counted from it */ }
41
+ let text;
42
+ try { text = readFileSync(join(dir, 'diary.jsonl'), 'utf8'); } catch { continue; }
43
+ for (const line of text.split('\n')) {
44
+ if (!line.includes('"kind":"tool"')) continue;
45
+ let r;
46
+ try { r = JSON.parse(line); } catch { continue; }
47
+ if (r?.kind !== 'tool' || typeof r.tool !== 'string') continue;
48
+ const server = byLength.find((s) => r.tool.startsWith(`${s}_`) && r.tool.length > s.length + 1);
49
+ if (server) use(server, r.tool.slice(server.length + 1), key, typeof r.at === 'string' ? r.at : '', r.decision === 'deny');
50
+ }
51
+ }
52
+ }
53
+ return new Map([...acc].map(([s, a]) => [s, { calls: a.calls, runs: a.runSet.size, last: a.last || null, denied: a.denied, tools: a.tools }]));
54
+ }
package/src/memo.js ADDED
@@ -0,0 +1,120 @@
1
+ // M14 items 1-6 (docs/wiki/the-module-ladder.md, "M14 — memory improvements", and "M14 amendment 1" item 2): the carry memo, "what happened so far in this run".
2
+ // Plain code, no AI, built fresh before each model try from the run's OWN files only: audit.jsonl (the tries and how each ended), the consumed answers and
3
+ // `asks/<id>.json` (the human's words, by `listArchivedAsks`), `job/declaration.json` (step order) and `run.json`'s `rerun` section. It writes nothing: the exact
4
+ // text a try was handed is kept by that try's audit row (`memoText`, runner.js `makeAuditRow`), so no new run-folder file. Pure over those files, so it survives a
5
+ // pause, a resume and a restart. It never carries money or time (no cost, no duration); gap texts are the closer's own words, kept as they are (cut at GAP_CHARS).
6
+ import { readAudit } from './books.js';
7
+ import { readFileInside } from './flow.js';
8
+ import { listArchivedAsks, DECISION_STATUS } from './ask.js';
9
+ import { readRunRecord } from './runfile.js';
10
+ import {
11
+ foldCards, nameOf, errorKinds, flaggedTokens, quoteLines,
12
+ } from './learn.js';
13
+
14
+ /** M14 am1 item 2: the memo's fixed words */
15
+ export const MEMO_HEADING = 'What happened so far in this run (written by code, from the record)';
16
+ export const MEMO_CUT_NOTE = '(older lines cut to fit)';
17
+ /** M14 item 5 */
18
+ export const MEMO_CAP = 4000;
19
+ /** one gap text is cut here (with an ellipsis), so a single long red cannot eat the whole cap */
20
+ const GAP_CHARS = 300;
21
+
22
+ /** a try that closed well; every other verdict of a model try is a failure the memo names */
23
+ const WELL = new Set(['green', 'hitl']);
24
+ const DECISION_OF = Object.fromEntries(Object.entries(DECISION_STATUS).map(([k, v]) => [v, k]));
25
+
26
+ const oneLine = (/** @type {unknown} */ t) => (typeof t === 'string' ? t.replace(/\s+/g, ' ').trim() : '');
27
+ const cutGap = (/** @type {string} */ g) => (g.length > GAP_CHARS ? `${g.slice(0, GAP_CHARS)}…` : g);
28
+ const says = (/** @type {string} */ words) => (words === '' ? '' : ` — user says "${words}"`);
29
+
30
+ /** step names in the job's own order, from the run's copy of the job (`[]` when it cannot be read) @param {string} runDir @returns {string[]} */
31
+ function stepOrder(runDir) {
32
+ const r = readFileInside(runDir, 'job/declaration.json');
33
+ if (!r.ok) return [];
34
+ try {
35
+ const steps = JSON.parse(r.text)?.steps;
36
+ return Array.isArray(steps) ? steps.map((s) => s?.emits).filter((e) => typeof e === 'string') : [];
37
+ } catch { return []; }
38
+ }
39
+
40
+ /** the human lines: the rerun line first (this run began as a rerun), then one per answered ask in the order they were asked (N counts every ask of this run) @param {string} runDir @param {string[]} order @returns {string[]} */
41
+ function humanLines(runDir, order) {
42
+ /** @type {string[]} */
43
+ const lines = [];
44
+ const rec = readRunRecord(runDir);
45
+ const rr = rec.ok ? rec.rec.rerun : null;
46
+ if (rr && typeof rr === 'object' && rr.decision === 'rerun' && typeof rr.words === 'string') lines.push(`rerun${says(oneLine(rr.words))}`);
47
+ const listed = listArchivedAsks(runDir);
48
+ if (!listed.archived) return lines;
49
+ const asks = [...listed.asks].sort((a, b) => String(a.askedAt ?? '').localeCompare(String(b.askedAt ?? '')));
50
+ asks.forEach((ask, i) => {
51
+ const decision = DECISION_OF[ask.answer.status];
52
+ if (!decision) return;
53
+ const at = order.indexOf(ask.emits ?? '');
54
+ const after = at > 0 ? order[at - 1] : 'the start';
55
+ lines.push(`ask ${i + 1} (after step ${after}): ${decision}${says(oneLine(ask.answer.reason))}`);
56
+ });
57
+ return lines;
58
+ }
59
+
60
+ /**
61
+ * Fold repeated failures into one line each, by the learnings fold rule (`foldCards`: same check, an agreeing error kind, 60% token overlap), here with the step and
62
+ * verdict as the "job" so only the same step failing the same way folds. Returns the groups in first-seen order.
63
+ * @template {{step: string, verdict: string, gap: string}} T @param {T[]} items @returns {T[][]}
64
+ */
65
+ function foldRepeats(items) {
66
+ const cards = items.map((it) => {
67
+ const quote = quoteLines(it.gap).join('\n');
68
+ return { it, job: `${it.step}|${it.verdict}`, check: nameOf(it.gap), kinds: errorKinds(quote).kinds, tokens: flaggedTokens(quote) };
69
+ });
70
+ // `foldCards` only reads job, check, kinds and tokens of a card
71
+ return foldCards(/** @type {any} */ (cards)).map((g) => g.map((c) => /** @type {any} */ (c).it));
72
+ }
73
+
74
+ /**
75
+ * The memo for the try about to run, as text; `''` when nothing has happened yet in this run (no human line, no earlier try).
76
+ * @param {string|null} runDir the run's folder (null = no record = nothing happened)
77
+ * @param {{step: string|null, cap?: number}} o `step` = the step the try belongs to (names its earlier tries and tells a retry from a later step's first try)
78
+ * @returns {string}
79
+ */
80
+ export function buildMemo(runDir, { step, cap = MEMO_CAP }) {
81
+ if (typeof runDir !== 'string') return '';
82
+ const order = stepOrder(runDir);
83
+ const human = humanLines(runDir, order);
84
+ // the model tries so far, in file order; a try is labelled by its count within its step (the audit `attempt` restarts after a redo, F130)
85
+ /** @type {Map<string, number>} */
86
+ const seen = new Map();
87
+ const tries = readAudit(runDir)
88
+ .filter((r) => r && r.model != null && typeof r.step === 'string' && r.verdict !== 'stopped')
89
+ .map((r) => {
90
+ const n = (seen.get(r.step) ?? 0) + 1;
91
+ seen.set(r.step, n);
92
+ return { step: /** @type {string} */ (r.step), n, verdict: String(r.verdict), gap: oneLine(r.gap) };
93
+ });
94
+ if (human.length === 0 && tries.length === 0) return '';
95
+
96
+ const last = tries.at(-1) ?? null;
97
+ // item 6: the newest failure's words are left out when the retry (the same step, straight after a failure) already gets them as its gap
98
+ const retryGetsGap = last !== null && last.step === step && !WELL.has(last.verdict);
99
+ const earlier = tries.slice(0, -1);
100
+ const sameStep = earlier.filter((t) => t.step === step);
101
+ const failures = earlier.filter((t) => t.step !== step && !WELL.has(t.verdict));
102
+ const label = (/** @type {{step: string, n: number, verdict: string, gap: string}} */ t) => `step ${t.step} try ${t.n} — result: ${t.verdict}`;
103
+ const gapOf = (/** @type {{gap: string}} */ t) => (t.gap === '' ? '' : ` — ${cutGap(t.gap)}`);
104
+ const foldLine = (/** @type {string} */ kind, /** @type {any[]} */ g) => ({ kind, text: `${kind}: ${label(g[0])}${gapOf(g[0])}${g.length > 1 ? ` (x${g.length})` : ''}` });
105
+
106
+ const lastLine = last === null ? [] : [{ kind: 'last', text: `last try: ${label(last)}${retryGetsGap ? '' : gapOf(last)}` }];
107
+ const tryLines = foldRepeats(sameStep).map((g) => foldLine('earlier try', g));
108
+ const failLines = foldRepeats(failures).map((g) => foldLine('earlier failure', g));
109
+ let work = [...lastLine, ...tryLines, ...failLines];
110
+ let cut = false;
111
+ const text = () => [MEMO_HEADING, ...human, ...work.map((w) => w.text), ...(cut ? [MEMO_CUT_NOTE] : [])].join('\n');
112
+ // item 5: oldest tries first, then oldest failures; the heading, the human lines and the last-try line stay
113
+ while (text().length > cap) {
114
+ const drop = work.find((w) => w.kind === 'earlier try') ?? work.find((w) => w.kind === 'earlier failure');
115
+ if (!drop) break;
116
+ work = work.filter((w) => w !== drop);
117
+ cut = true;
118
+ }
119
+ return text();
120
+ }
package/src/model-step.js CHANGED
@@ -189,7 +189,7 @@ function addMeter(cumulative, metered) {
189
189
  // faulted — caught live: `toolFields` threw on `cumulative.ungranted`
190
190
  // being undefined the very first time a transport fault hit round 1.
191
191
  return {
192
- costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking,
192
+ costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking, badCalls: cumulative.badCalls, forcedRefused: cumulative.forcedRefused,
193
193
  };
194
194
  }
195
195
 
@@ -244,6 +244,10 @@ function toolFields(cumulative) {
244
244
  // absence can never be confused with "none".
245
245
  refused: cumulative.refused,
246
246
  ...(cumulative.ungranted.length > 0 ? { ungranted: cumulative.ungranted } : {}),
247
+ // M14 item 10: bare-agent's facts about calls that went wrong (`r.badCalls`, whole attempt, in order); left off once empty, like `ungranted`
248
+ ...(cumulative.badCalls.length > 0 ? { badCalls: cumulative.badCalls } : {}),
249
+ // ruling A: a forced call refused before anything was metered is said on the row, never silently dropped
250
+ ...(cumulative.forcedRefused ? { forcedRefused: FORCED_REFUSED_SAY } : {}),
247
251
  };
248
252
  }
249
253
 
@@ -263,12 +267,15 @@ function thinkingStatusOf(r) {
263
267
  /**
264
268
  * 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
265
269
  * reported for THAT call (thinking status, the tool names it asked for); the Loop's own `onLlmResult` payload carries neither. Everything else reads through.
266
- * @param {any} provider @param {(result: any) => void} seen
270
+ * @param {any} provider @param {(result: any) => void} seen @param {{on: boolean}|null} [force] - M4d am37: while `on`, the next call carries `toolChoice: {name: 'emit_artifact'}`
267
271
  */
268
- function watchCalls(provider, seen) {
272
+ function watchCalls(provider, seen, force = null) {
269
273
  const watched = Object.create(provider);
270
- watched.generate = async (...a) => {
271
- const r = await provider.generate(...a);
274
+ watched.generate = async (messages, tools, options = {}) => {
275
+ // M4d am37: the forced round forces `emit_artifact` on its FIRST call only (forcing every call would make the Loop save again and again)
276
+ const forced = force !== null && force.on;
277
+ if (forced) force.on = false;
278
+ const r = await provider.generate(messages, tools, forced ? { ...options, toolChoice: { name: 'emit_artifact' } } : options);
272
279
  seen(r);
273
280
  return r;
274
281
  };
@@ -285,7 +292,29 @@ function toolRowPath(args) {
285
292
 
286
293
  const STOP_RULE = 'stop-requested';
287
294
 
295
+ /** M4d am37: the one fixed line a step that answered in text is sent, from code; the model never writes it and it never changes. */
296
+ export const NUDGE = 'You answered in text. Call emit_artifact now with that answer; do not reply in text.';
297
+
298
+ /** M4d am37: a provider that says it does not send `toolChoice` (`makeProvider` sets the flag from the row's shape) ignores a forced call; round 2 then sends the line unforced and a save there is the fallback. */
299
+ /** Ruling A (hamr 2026-11-03): the fixed say on the audit row of a try whose forced call was refused with no usage returned; it books $0. */
300
+ export const FORCED_REFUSED_SAY = 'refused, no bill returned';
301
+
302
+ const IGNORES_TOOL_CHOICE = (provider) => provider?.honoursToolChoice === false;
303
+
288
304
  /** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
305
+ /**
306
+ * M14 item 9: the retry's gap for a try cut off at the output limit, from bare-agent's own facts (`r.cutOff`): the output tokens, how many of them were thinking, and the limit.
307
+ * A fact bare-agent did not report is said so, never a number. `null` when the run carries no `cutOff` (the caller keeps its older words).
308
+ * @param {{outputTokens: number|null, reasoningTokens: number|null, maxTokensRequested: number|null}|undefined} c
309
+ */
310
+ function cutOffRed(c) {
311
+ if (!c || typeof c !== 'object') return null;
312
+ const out = Number.isFinite(c.outputTokens) ? `${c.outputTokens} output tokens` : 'an output size that was not reported';
313
+ const thinking = Number.isFinite(c.reasoningTokens) ? `${c.reasoningTokens} of them thinking` : 'thinking tokens not reported';
314
+ const limit = Number.isFinite(c.maxTokensRequested) ? `the limit was ${c.maxTokensRequested}` : 'no limit was reported';
315
+ return `truncated: cut off at the output limit with no tool call — ${out}, ${thinking}; ${limit}`;
316
+ }
317
+
289
318
  function stoppedResult(cumulative, modelId, modelMatch) {
290
319
  return {
291
320
  ok: false, stopped: true, red: 'stopped by you', costUsd: cumulative.costUsd, tokens: cumulative.tokens, ...toolFields(cumulative), model: modelId, modelMatch,
@@ -353,12 +382,15 @@ export function makeLiveModelStep({
353
382
  gap: executorContext.gap,
354
383
  // M8 am7: on a retry, redo or rerun try only - the earlier runs' block, whole, the same text the drafter's block is made of; it leans the model, the close alone judges
355
384
  ...(typeof executorContext.hints === 'string' && executorContext.hints !== '' ? { fromEarlierRuns: executorContext.hints } : {}),
385
+ // M14 item 2: what happened so far in this run (src/memo.js), whole, on every try that has any; absent = nothing has happened yet. Text only, it leans the model, the close alone judges
386
+ ...(typeof executorContext.memo === 'string' && executorContext.memo !== '' ? { fromThisRun: executorContext.memo } : {}),
356
387
  // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold
357
388
  ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
358
389
  // M10b piece 2: a step that reads a sheet is told the shape of each claim box (bareguard's worked example), never the check
359
390
  ...(stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? { answering: sheetBrief(stepMeta.sheet) } : {}),
360
391
  });
361
- const messages = [
392
+ /** @type {any[]} */
393
+ let messages = [
362
394
  { role: 'system', content: systemPrompt },
363
395
  { role: 'user', content: userContent },
364
396
  ];
@@ -412,14 +444,25 @@ export function makeLiveModelStep({
412
444
  tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 },
413
445
  tools: /** @type {Record<string, number>} */ ({}),
414
446
  ungranted: /** @type {string[]} */ ([]),
447
+ badCalls: /** @type {any[]} */ ([]),
448
+ forcedRefused: false,
415
449
  refused,
416
450
  // M4d am25 item 4: what this attempt asked of thinking (the runner's decision, `stepMeta.thinkingMode`; null = it asked nothing) and the WORST status
417
451
  // bareagent reported across its rounds (null = none reported). The ONE place this record is built; `toolFields` hands it to every return.
418
452
  thinking: /** @type {{asked: string|null, status: string|null}} */ ({ asked: thinkingMode ?? null, status: null }),
419
453
  };
420
- let noToolCallStreak = 0;
421
-
422
- for (let round = 1; round <= 2; round += 1) {
454
+ // M4d am37: round 1 runs as today. A round 1 that ended in text (no save, no malformed call) sends round 2 the conversation so far plus the fixed line, with
455
+ // `emit_artifact` forced on its first call; a refused or unsaved round 2 sends round 3 the same line unforced. A malformed tool call keeps today's one fresh retry.
456
+ let freshRetry = false;
457
+ let forcedAsked = false;
458
+ const force = { on: false };
459
+ /** @type {'first'|'forced'|'fallback'} */
460
+ let savedBy = 'first';
461
+ // hamr's ask 2026-11-03: the text round 1 ended with, kept so a later round's save can be compared with what the model said (bounded like raw arguments)
462
+ /** @type {string|undefined} */
463
+ let firstText;
464
+
465
+ for (let round = 1; round <= 3; round += 1) {
423
466
  let capturedArtifact;
424
467
  const emitTool = {
425
468
  name: 'emit_artifact',
@@ -461,15 +504,24 @@ export function makeLiveModelStep({
461
504
  }
462
505
  }
463
506
  };
464
- const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }), rates, onLlmResult, ...stopSeam });
507
+ // M14 item 10: `checkArgs` - a call whose top-level arguments do not fit the tool's declared parameters (a wrong type, a missing required value) never runs the tool; bare-agent hands the model the refusal and reports it in `badCalls`
508
+ const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }, force), rates, onLlmResult, checkArgs: true, ...stopSeam });
465
509
 
466
510
  const startedAt = Date.now();
467
511
  let result;
512
+ force.on = round === 2 && !freshRetry && !IGNORES_TOOL_CHOICE(provider);
513
+ forcedAsked = force.on;
468
514
  try {
469
515
  // eslint-disable-next-line no-await-in-loop
470
516
  // 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).
471
517
  result = await loop.run(messages, tools, { maxTokens: 16000, ...(thinkingMode ? { thinkingMode } : {}) });
472
518
  } catch (err) {
519
+ // M4d am37: the same refused forced call, when the Loop threw it instead of reporting it (see below)
520
+ if (forcedAsked && round === 2 && roundMeterings.length === 0 && !isTransportFailure(err) && err?.code !== 'EDEADLINE') {
521
+ cumulative.forcedRefused = true;
522
+ // eslint-disable-next-line no-continue
523
+ continue;
524
+ }
473
525
  const wallMs = Date.now() - startedAt;
474
526
  const partial = sumMeterings(roundMeterings);
475
527
  cumulative = addMeter(cumulative, partial);
@@ -529,12 +581,20 @@ export function makeLiveModelStep({
529
581
 
530
582
  const wallMs = Date.now() - startedAt;
531
583
  const stoppedByYou = result.error === `halt:${STOP_RULE}`;
584
+ // M4d am37: a forced call the provider refused before it answered anything (no call metered) is not the end: round 3 sends the same line unforced. It books nothing - the
585
+ // request was refused, no answer was priced - so it adds no unknown to the step's cost. Anything metered, a Stop, and a thrown transport fault or deadline stay as they were.
586
+ if (forcedAsked && round === 2 && roundMeterings.length === 0 && result.error && !stoppedByYou) {
587
+ cumulative.forcedRefused = true;
588
+ // eslint-disable-next-line no-continue
589
+ continue;
590
+ }
532
591
  // A Stop read before this Loop's first call: no call ran, so there is nothing to meter or book — and an empty metering
533
592
  // must never be added as "cost unknown" onto the calls an earlier round already made.
534
593
  if (stoppedByYou && roundMeterings.length === 0) return stoppedResult(cumulative, modelId, null);
535
594
  const metered = sumMeterings(roundMeterings);
536
595
  cumulative = addMeter(cumulative, metered);
537
596
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
597
+ if (Array.isArray(result.badCalls)) cumulative = { ...cumulative, badCalls: [...cumulative.badCalls, ...result.badCalls] };
538
598
  if (result.thinkingStatus !== undefined) cumulative.thinking = { asked: cumulative.thinking.asked, status: worstThinkingStatus([cumulative.thinking.status, result.thinkingStatus]) };
539
599
  appendSpendRow(spendPath, {
540
600
  provider: slot ?? null,
@@ -559,7 +619,7 @@ export function makeLiveModelStep({
559
619
  // bigger cap), never a transient fault a retry could fix.
560
620
  return {
561
621
  ok: false,
562
- red: `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
622
+ red: cutOffRed(result.cutOff) ?? `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
563
623
  costUsd: cumulative.costUsd,
564
624
  tokens: cumulative.tokens,
565
625
  ...toolFields(cumulative),
@@ -569,9 +629,14 @@ export function makeLiveModelStep({
569
629
  }
570
630
 
571
631
  if (capturedArtifact === undefined) {
572
- noToolCallStreak += 1;
573
- if (noToolCallStreak >= 2) {
574
- const malformed = provider?.lastMalformedToolCall ?? null;
632
+ const malformed = provider?.lastMalformedToolCall ?? null;
633
+ // today's path: a malformed tool call on round 1 is retried once fresh; a second round without a save ends the step
634
+ if (round === 1 && (malformed || result.error)) {
635
+ freshRetry = true;
636
+ // eslint-disable-next-line no-continue
637
+ continue;
638
+ }
639
+ if (freshRetry || round === 3) {
575
640
  if (malformed) {
576
641
  // bare-agent >=0.50 delivers the FULL `rawArguments` (verbatim, uncapped; `rawTruncated` is never set), and only when the provider was
577
642
  // built with `exposeMalformedArgs: true`. We bound what is logged and shown, with the cut said out loud. Absent -> no "; raw:" suffix.
@@ -586,9 +651,10 @@ export function makeLiveModelStep({
586
651
  modelMatch,
587
652
  };
588
653
  }
654
+ const tried = freshRetry ? 'twice in a row' : 'after the forced save and the fallback were tried';
589
655
  return {
590
656
  ok: false,
591
- red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool twice in a row. Text: ${JSON.stringify(result.text)}`,
657
+ red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool ${tried}. Text: ${JSON.stringify(result.text)}`,
592
658
  costUsd: cumulative.costUsd,
593
659
  tokens: cumulative.tokens,
594
660
  ...toolFields(cumulative),
@@ -596,8 +662,11 @@ export function makeLiveModelStep({
596
662
  modelMatch,
597
663
  };
598
664
  }
665
+ if (round === 1 && !result.error && typeof result.text === 'string' && result.text !== '') firstText = boundRaw(result.text);
666
+ // round 1 ended in text (round 2 then continues it, forced) or round 2 ended unsaved (round 3 sends the line again); a round that ended in an error continues from the messages it was sent
667
+ if (!result.error) messages = [...result.msgs, { role: 'user', content: NUDGE }];
599
668
  // eslint-disable-next-line no-continue
600
- continue; // retry once, same attempt
669
+ continue;
601
670
  }
602
671
 
603
672
  if (cumulative.costUsd === null) {
@@ -606,8 +675,11 @@ export function makeLiveModelStep({
606
675
  };
607
676
  }
608
677
 
678
+ // M4d am37: which way it saved - round 1 (or the malformed-call retry, as today), the forced call, or the unforced fallback
679
+ if (!freshRetry && round === 2) savedBy = forcedAsked ? 'forced' : 'fallback';
680
+ if (round === 3) savedBy = 'fallback';
609
681
  return {
610
- ok: true, artifact: capturedArtifact, costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
682
+ ok: true, artifact: capturedArtifact, savedBy, ...(savedBy !== 'first' && firstText !== undefined ? { firstText } : {}), costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
611
683
  };
612
684
  }
613
685
 
package/src/natural.js ADDED
@@ -0,0 +1,23 @@
1
+ // M13 item 9.6: the ONE place that orders names with numbers in them (`run-9` before `run-10`, `#8` before `#10`, `run-3-rerun-1` before `run-25`).
2
+ // Digit runs compare as numbers (by length after leading zeros, then by text, so a long number never loses digits); everything else compares as text.
3
+
4
+ /** @param {string} a @param {string} b digit strings */
5
+ const digits = (a, b) => {
6
+ const x = a.replace(/^0+/, '');
7
+ const y = b.replace(/^0+/, '');
8
+ return x.length - y.length || (x < y ? -1 : x > y ? 1 : 0);
9
+ };
10
+
11
+ /** @param {unknown} x @param {unknown} y @returns {number} negative, 0 or positive, like a sort callback */
12
+ export function compareNatural(x, y) {
13
+ const tx = String(x).match(/\d+|\D+/g) ?? [];
14
+ const ty = String(y).match(/\d+|\D+/g) ?? [];
15
+ for (let i = 0; i < Math.min(tx.length, ty.length); i++) {
16
+ const a = tx[i];
17
+ const b = ty[i];
18
+ if (a === b) continue; // eslint-disable-line no-continue
19
+ const c = /^\d/.test(a) && /^\d/.test(b) ? digits(a, b) : (a < b ? -1 : 1);
20
+ if (c !== 0) return c;
21
+ }
22
+ return tx.length - ty.length;
23
+ }
package/src/pageask.js CHANGED
@@ -22,7 +22,7 @@ export const DROP_IT = 'drop it';
22
22
  /** @param {unknown} text @returns {boolean} */
23
23
  export const isDropIt = (text) => String(text ?? '').trim().replace(/\.$/, '').toLowerCase() === DROP_IT;
24
24
  /** the answers that accept the code's reading of a rule; anything else the person types is their own reading */
25
- const AGREE_WORDS = ['agree', 'yes'];
25
+ export const AGREE_WORDS = ['agree', 'yes'];
26
26
  /** @param {unknown} text @returns {boolean} */
27
27
  export const isAgree = (text) => AGREE_WORDS.includes(String(text ?? '').trim().replace(/[.!]$/, '').toLowerCase());
28
28
 
@@ -139,14 +139,17 @@ export function tooManyAsksText(asks) {
139
139
  * What a typed answer to a look ask does, the ONE place that decides (the panel's answer route, the setup record and the Result tab all read it).
140
140
  * `agree` / `yes` to a reading ask takes the code's reading; `drop it` to a can't-check ask leaves the rule Not checked (no `~` line); anything else is the
141
141
  * person's own words, taken word for word with newlines folded to spaces. A question that is not a look ask is never changed: its answer is its rule.
142
- * @param {{source?: string, ask?: string, proposal?: string|null}} q @param {unknown} typed
143
- * @returns {{rule: string|null, left: boolean}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
142
+ * M10 am16: a shape guardrail's ask (`ask: 'check'` proposes a check, `'no-check'` found none) takes the same words: `agree` takes the proposal (and the check it
143
+ * carries, `check`), `drop it` leaves the rule Not checked (either kind), anything else is the person's own words (`own`: a `~` rule on the line, no check).
144
+ * @param {{source?: string, ask?: string, proposal?: string|null, check?: Record<string, any>}} q @param {unknown} typed
145
+ * @returns {{rule: string|null, left: boolean, check?: Record<string, any>, own?: boolean}} `rule` = the words written as a new `~` rule (null when the rule is left Not checked)
144
146
  */
145
147
  export function ruleOfAnswer(q, typed) {
146
148
  const typedText = String(typed ?? '').replace(/\s*\n\s*/g, ' ').trim();
147
149
  if (q.source !== 'look') return { rule: typedText, left: false };
148
150
  const text = stripAgreeLead(typedText); // F240: "yes, check it as ..." is the person's own words minus the leading "yes,"
149
- if (q.ask === 'reading' && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false };
150
- if (q.ask === 'cant-check' && isDropIt(text)) return { rule: null, left: true };
151
- return { rule: text, left: false };
151
+ const shape = q.ask === 'check' || q.ask === 'no-check';
152
+ if ((q.ask === 'reading' || q.ask === 'check') && typeof q.proposal === 'string' && isAgree(text)) return { rule: q.proposal, left: false, ...(q.ask === 'check' && q.check ? { check: q.check } : {}) };
153
+ if ((q.ask === 'cant-check' || shape) && isDropIt(text)) return { rule: null, left: true };
154
+ return { rule: text, left: false, ...(shape ? { own: true } : {}) };
152
155
  }
@@ -26,6 +26,9 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
26
26
  // borrowed-from: bareloop src/pagedropwords.js@c550dc8 (the phrase dry read's sentence)
27
27
  'phrase-no-result': (d) => `"${d.other}" is on the page but in none of its results, so it is not checked.`,
28
28
  'person-left': () => 'You chose to leave it Not checked.',
29
+ // M10 am16 (items 4, 5): a shape guardrail with no check picked is Not checked, and you judge it at the Ask
30
+ 'no-pick': () => 'No check was picked for it, so you judge it at the Ask.',
31
+ 'own-words': () => 'Your own words are on the line; the machine has no check for them, so you judge it at the Ask.',
29
32
  // M10 piece 5 (item 7, am8 item 1): the signed Not-checked reasons for a job word that is not a column. `fact` = the job's word.
30
33
  'no-column': (d) => `there is no column '${d.fact}'`,
31
34
  'no-fit': (d) => `no column fits '${d.fact}'`,
@@ -45,6 +48,12 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
45
48
  */
46
49
  export const leftRuleLine = (rule) => `not checked · "${rule}" — ${WORDS['person-left'](/** @type {Dropped} */ ({}))}`;
47
50
 
51
+ /**
52
+ * M10 am16 (item 5): the plan card row for a shape guardrail that has no picked check, in the same form as {@link leftRuleLine}: `not checked · "<rule>" — <reason>`.
53
+ * @param {string} rule @param {'no-pick'|'own-words'} reason @returns {string}
54
+ */
55
+ export const pickNoteLine = (rule, reason) => `not checked · "${rule}" — ${WORDS[reason](/** @type {Dropped} */ ({}))}`;
56
+
48
57
  /** @param {Dropped} d @returns {string} the plain sentence for one drop */
49
58
  export function dropSentence(d) {
50
59
  const f = WORDS[d.reason];