fwdloop 0.28.0 → 0.30.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 (74) hide show
  1. package/README.md +1 -1
  2. package/bin/fwdloop +27 -5
  3. package/package.json +3 -3
  4. package/src/added-end.js +60 -0
  5. package/src/ask.js +1 -1
  6. package/src/audit-fold.js +9 -1
  7. package/src/authoring.js +18 -7
  8. package/src/checked.js +14 -9
  9. package/src/checkpick.js +318 -0
  10. package/src/checkwords.js +29 -0
  11. package/src/citedcheck.js +14 -0
  12. package/src/closers.js +40 -3
  13. package/src/declaration.js +102 -5
  14. package/src/draft-steps.js +3 -3
  15. package/src/drafter.js +151 -38
  16. package/src/jobkey.js +3 -1
  17. package/src/learn.js +1 -1
  18. package/src/learnstore.js +6 -6
  19. package/src/memo.js +120 -0
  20. package/src/model-step.js +103 -25
  21. package/src/pageask.js +12 -6
  22. package/src/pagedropwords.js +9 -0
  23. package/src/panel/author.js +33 -10
  24. package/src/panel/authorcard.js +59 -6
  25. package/src/panel/data.js +16 -10
  26. package/src/panel/index.html +151 -59
  27. package/src/panel/result.js +28 -7
  28. package/src/panel/server.js +2 -1
  29. package/src/pickrecord.js +146 -0
  30. package/src/plain-checks.js +16 -3
  31. package/src/provider.js +4 -1
  32. package/src/repairs.js +38 -0
  33. package/src/runfile.js +4 -2
  34. package/src/runner.js +129 -40
  35. package/src/send.js +71 -4
  36. package/src/setup.js +13 -1
  37. package/src/sheetblock.js +2 -1
  38. package/src/ticket-draft.js +2 -2
  39. package/src/ticket-labels.js +2 -2
  40. package/src/try-checks.js +13 -3
  41. package/src/whole-job.js +71 -0
  42. package/types/added-end.d.ts +62 -0
  43. package/types/ask.d.ts +2 -1
  44. package/types/audit-fold.d.ts +13 -2
  45. package/types/authoring.d.ts +6 -2
  46. package/types/checked.d.ts +7 -2
  47. package/types/checkpick.d.ts +183 -0
  48. package/types/checkwords.d.ts +18 -0
  49. package/types/citedcheck.d.ts +6 -0
  50. package/types/closers.d.ts +6 -3
  51. package/types/declaration.d.ts +12 -0
  52. package/types/drafter.d.ts +28 -25
  53. package/types/learn.d.ts +1 -0
  54. package/types/learnstore.d.ts +2 -3
  55. package/types/memo.d.ts +15 -0
  56. package/types/model-step.d.ts +23 -3
  57. package/types/pageask.d.ts +9 -2
  58. package/types/pagedropwords.d.ts +1 -0
  59. package/types/panel/author.d.ts +1 -1
  60. package/types/panel/authorcard.d.ts +41 -0
  61. package/types/panel/data.d.ts +1 -1
  62. package/types/panel/jobgrid.d.ts +1 -1
  63. package/types/panel/result.d.ts +9 -3
  64. package/types/pickrecord.d.ts +88 -0
  65. package/types/plain-checks.d.ts +9 -1
  66. package/types/repairs.d.ts +13 -0
  67. package/types/runfile.d.ts +7 -2
  68. package/types/runner.d.ts +16 -5
  69. package/types/send.d.ts +10 -2
  70. package/types/setup.d.ts +1 -56
  71. package/types/try-checks.d.ts +1 -7
  72. package/types/whole-job.d.ts +70 -0
  73. package/src/attemptdiff.js +0 -118
  74. package/types/attemptdiff.d.ts +0 -38
package/src/learnstore.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // borrowed-from: bareloop src/learnstore.js@v0.47.0 (66dc2b0)
2
- // Adaptations: M8 item 3: the ledger home is fwdloop's configHome() (src/config.js) in place of bareloop's keysHome, so the file is <configHome>/learn/ledger.json (mode 600, as bareloop); with no explicit home under a test process and no FWDLOOP_CONFIG_HOME, ledgerPath throws, so a test can never reach the real ~/.config/fwdloop; hintsForRun is copied at the bottom (M8 item 5a) with a ledger problem THROWN (the caller records why and hands nothing), and with `path.resolve` for the place in place of bareloop's realpathSync (the F48 guard keeps realpathSync out of this file), the same place learnAtRunEnd records; stageQuestionsByName is not copied (see learnAtRunEnd: a card's `meaning` is the failing check's own text from the run's diary.jsonl); learnAtRunEnd reads fwdloop's run folder through eventsOfRun (adapted from fwdloop poc/learn/adapter.mjs, F79) because fwdloop has no bareloop spine; imports trimmed to match. F83 bug 2: learnAtRunEnd (the one run-end and seed path) folds with specHash null, so a lesson matches by workflow name alone, the same as the read side (M8 am7 item 1; a redraft's new plan hash no longer opens a new row); its `specHash` argument is accepted and unused. Nothing else changed. Known gap, kept on purpose (M8 item 7): foldRunIntoLedger and releaseRun read, change and replace the file, so two runs ending together can lose a note.
2
+ // Adaptations: M8 item 3: the ledger home is fwdloop's configHome() (src/config.js) in place of bareloop's keysHome, so the file is <configHome>/learn/ledger.json (mode 600, as bareloop); with no explicit home under a test process and no FWDLOOP_CONFIG_HOME, ledgerPath throws, so a test can never reach the real ~/.config/fwdloop; hintsForRun is copied at the bottom (M8 item 5a) with a ledger problem THROWN (the caller records why and hands nothing), and with `path.resolve` for the place in place of bareloop's realpathSync (the F48 guard keeps realpathSync out of this file), the same place learnAtRunEnd records; stageQuestionsByName is not copied (see learnAtRunEnd: a card's `meaning` is the failing check's own text from the run's diary.jsonl); learnAtRunEnd reads fwdloop's run folder through eventsOfRun (adapted from fwdloop poc/learn/adapter.mjs, F79) because fwdloop has no bareloop spine; imports trimmed to match. F83 bug 2: learnAtRunEnd (the one run-end and seed path) folds with specHash null, so a lesson matches by workflow name alone, the same as the read side (M8 am7 item 1; a redraft's new plan hash no longer opens a new row). Nothing else changed. Known gap, kept on purpose (M8 item 7): foldRunIntoLedger and releaseRun read, change and replace the file, so two runs ending together can lose a note.
3
3
  // The thin reader/writer around src/learn.js (cross-run learnings, ITEM33-BUILD.md rev 2). All file IO lives here and
4
4
  // the pure rules live in learn.js; nothing in either file can reach a model.
5
5
  //
@@ -263,10 +263,10 @@ export function eventsOfRun(runDir, workflow) {
263
263
  * with a signed ask included; there is no hold. It runs whether `learningHints` is on or off. `questions` (bareloop's stageQuestionsByName) is, here, the failing check's own text from
264
264
  * the run's diary.jsonl, so a check with no checks row there (a run from before am29) has no `meaning`.
265
265
  * Borrowed-from: bareloop src/learnstore.js@v0.47.0:124 (learnAtRunEnd).
266
- * @param {{home?: string, workflow: string, runId: string, runDir: string, specHash: string|null, now?: Date}} o
266
+ * @param {{home?: string, workflow: string, runId: string, runDir: string, now?: Date}} o
267
267
  * @returns {{wrote: boolean, counted: number, held: number, problem: string|null, noise: string|null, cards: number}}
268
268
  */
269
- export function learnAtRunEnd({ home, workflow, runId, runDir, specHash, now = new Date() }) {
269
+ export function learnAtRunEnd({ home, workflow, runId, runDir, now = new Date() }) {
270
270
  const rec = eventsOfRun(runDir, workflow);
271
271
  if (!rec) return { wrote: false, counted: 0, held: 0, problem: null, noise: 'no-tries', cards: 0 };
272
272
  const runid = `${workflow}/${runId}`;
@@ -296,7 +296,7 @@ export function seedLedger({ root, home }) {
296
296
  if (door.skip) return { ...out, skippedNoDoor: true };
297
297
  home = door.home;
298
298
  }
299
- /** @type {{workflow: string, runId: string, runDir: string, end: Date, specHash: string|null}[]} */
299
+ /** @type {{workflow: string, runId: string, runDir: string, end: Date}[]} */
300
300
  const todo = [];
301
301
  for (const workflow of listFlowNames(root)) {
302
302
  const flowDir = join(root, workflow);
@@ -313,7 +313,7 @@ export function seedLedger({ root, home }) {
313
313
  const endRow = history.findLast((r) => r?.runId === runId && !NOT_A_RUN_END.has(r.outcome) && Number.isFinite(Date.parse(r.at)));
314
314
  if (!endRow) { out.skipped['no-end'] += 1; continue; }
315
315
  if (!log) { out.skipped.unreadable += 1; continue; }
316
- todo.push({ workflow, runId, runDir, end: new Date(endRow.at), specHash: typeof endRow.signatureHash === 'string' ? endRow.signatureHash : null });
316
+ todo.push({ workflow, runId, runDir, end: new Date(endRow.at) });
317
317
  } catch { out.skipped.unreadable += 1; }
318
318
  }
319
319
  }
@@ -323,7 +323,7 @@ export function seedLedger({ root, home }) {
323
323
  if (cur.problem) { out.problem = cur.problem; return out; }
324
324
  if (Object.hasOwn(cur.ledger.health, `${t.workflow}/${t.runId}`)) { out.skipped['already-in'] += 1; continue; }
325
325
  try {
326
- const r = learnAtRunEnd({ home, workflow: t.workflow, runId: t.runId, runDir: t.runDir, specHash: t.specHash, now: t.end });
326
+ const r = learnAtRunEnd({ home, workflow: t.workflow, runId: t.runId, runDir: t.runDir, now: t.end });
327
327
  if (r.problem) { out.problem = r.problem; return out; }
328
328
  if (r.noise) out.skipped.noise += 1;
329
329
  else out.added += r.counted;
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
@@ -30,7 +30,7 @@ import { GateRefusal } from './primitives.js';
30
30
  import { appendCall, appendTool, nextRound } from './diary.js';
31
31
  import { ConfigError } from './config.js';
32
32
  import { worstThinkingStatus } from './thinking.js';
33
- import { citedBrief } from './citedcheck.js';
33
+ import { citedBrief, toldPicks } from './citedcheck.js';
34
34
  import { sheetAnswerProps, sheetBrief } from './sheetclaims.js';
35
35
 
36
36
  import {
@@ -143,12 +143,16 @@ const CITED_SCHEMA = Object.freeze({
143
143
  * only (plus, for a green step that quotes a saved page, the form of its answer).
144
144
  * `stepClass` is `'green' | 'softgreen' | 'hitl' | null | undefined`; `cited` is true for that green step.
145
145
  */
146
- /** @param {string|null|undefined} stepClass @param {boolean} [cited] @param {any[]|null} [sheet] M10b piece 2: the step's `close.sheet` (its claim boxes become the answer) */
147
- export function buildEmitArtifactSchema(stepClass, cited = false, sheet = null) {
146
+ /** @param {string|null|undefined} stepClass @param {boolean} [cited] @param {any[]|null} [sheet] M10b piece 2: the step's `close.sheet` (its claim boxes become the answer) @param {boolean} [withText] M10 am22: a fact step with the person's picks also answers in `text` (the picks read it) */
147
+ export function buildEmitArtifactSchema(stepClass, cited = false, sheet = null, withText = false) {
148
+ const text = withText ? { text: { type: 'string' } } : {};
148
149
  if (stepClass === 'green' && Array.isArray(sheet)) {
149
150
  // M10b piece 2: a step that reads a sheet answers in one typed box per claim (bareguard's shapes), never a cite
150
151
  const { properties, required } = sheetAnswerProps(sheet);
151
- return { type: 'object', properties: { ...properties, ...DONE_PROPS }, required: [...required, 'done'], additionalProperties: false };
152
+ return { type: 'object', properties: { ...properties, ...text, ...DONE_PROPS }, required: [...required, ...(withText ? ['text'] : []), 'done'], additionalProperties: false };
153
+ }
154
+ if (stepClass === 'green' && cited && withText) {
155
+ return { ...CITED_SCHEMA, properties: { ...CITED_SCHEMA.properties, ...text }, required: ['results', 'text', 'done'] };
152
156
  }
153
157
  if (stepClass === 'green' && cited) return CITED_SCHEMA;
154
158
  if (stepClass === 'green') throw new Error('a green step answers in quotes (close.cited) or in claim boxes (close.sheet); the cell cite retired in M10b piece 5');
@@ -189,7 +193,7 @@ function addMeter(cumulative, metered) {
189
193
  // faulted — caught live: `toolFields` threw on `cumulative.ungranted`
190
194
  // being undefined the very first time a transport fault hit round 1.
191
195
  return {
192
- costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking,
196
+ costUsd, rounds, tokens, tools: cumulative.tools, ungranted: cumulative.ungranted, refused: cumulative.refused, thinking: cumulative.thinking, badCalls: cumulative.badCalls, forcedRefused: cumulative.forcedRefused,
193
197
  };
194
198
  }
195
199
 
@@ -244,6 +248,10 @@ function toolFields(cumulative) {
244
248
  // absence can never be confused with "none".
245
249
  refused: cumulative.refused,
246
250
  ...(cumulative.ungranted.length > 0 ? { ungranted: cumulative.ungranted } : {}),
251
+ // M14 item 10: bare-agent's facts about calls that went wrong (`r.badCalls`, whole attempt, in order); left off once empty, like `ungranted`
252
+ ...(cumulative.badCalls.length > 0 ? { badCalls: cumulative.badCalls } : {}),
253
+ // ruling A: a forced call refused before anything was metered is said on the row, never silently dropped
254
+ ...(cumulative.forcedRefused ? { forcedRefused: FORCED_REFUSED_SAY } : {}),
247
255
  };
248
256
  }
249
257
 
@@ -263,12 +271,15 @@ function thinkingStatusOf(r) {
263
271
  /**
264
272
  * 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
273
  * 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
274
+ * @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
275
  */
268
- function watchCalls(provider, seen) {
276
+ function watchCalls(provider, seen, force = null) {
269
277
  const watched = Object.create(provider);
270
- watched.generate = async (...a) => {
271
- const r = await provider.generate(...a);
278
+ watched.generate = async (messages, tools, options = {}) => {
279
+ // M4d am37: the forced round forces `emit_artifact` on its FIRST call only (forcing every call would make the Loop save again and again)
280
+ const forced = force !== null && force.on;
281
+ if (forced) force.on = false;
282
+ const r = await provider.generate(messages, tools, forced ? { ...options, toolChoice: { name: 'emit_artifact' } } : options);
272
283
  seen(r);
273
284
  return r;
274
285
  };
@@ -285,7 +296,29 @@ function toolRowPath(args) {
285
296
 
286
297
  const STOP_RULE = 'stop-requested';
287
298
 
299
+ /** 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. */
300
+ export const NUDGE = 'You answered in text. Call emit_artifact now with that answer; do not reply in text.';
301
+
302
+ /** 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. */
303
+ /** 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. */
304
+ export const FORCED_REFUSED_SAY = 'refused, no bill returned';
305
+
306
+ const IGNORES_TOOL_CHOICE = (provider) => provider?.honoursToolChoice === false;
307
+
288
308
  /** The attempt result for a Stop that landed mid-attempt: every call made is already summed into `cumulative`. */
309
+ /**
310
+ * 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.
311
+ * 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).
312
+ * @param {{outputTokens: number|null, reasoningTokens: number|null, maxTokensRequested: number|null}|undefined} c
313
+ */
314
+ function cutOffRed(c) {
315
+ if (!c || typeof c !== 'object') return null;
316
+ const out = Number.isFinite(c.outputTokens) ? `${c.outputTokens} output tokens` : 'an output size that was not reported';
317
+ const thinking = Number.isFinite(c.reasoningTokens) ? `${c.reasoningTokens} of them thinking` : 'thinking tokens not reported';
318
+ const limit = Number.isFinite(c.maxTokensRequested) ? `the limit was ${c.maxTokensRequested}` : 'no limit was reported';
319
+ return `truncated: cut off at the output limit with no tool call — ${out}, ${thinking}; ${limit}`;
320
+ }
321
+
289
322
  function stoppedResult(cumulative, modelId, modelMatch) {
290
323
  return {
291
324
  ok: false, stopped: true, red: 'stopped by you', costUsd: cumulative.costUsd, tokens: cumulative.tokens, ...toolFields(cumulative), model: modelId, modelMatch,
@@ -301,7 +334,7 @@ function stoppedResult(cumulative, modelId, modelMatch) {
301
334
  * @param {{in:number,out:number}} [opts.rates]
302
335
  * @param {string} [opts.modelId]
303
336
  * @param {Record<string,string|undefined>} [opts.env] - the merged shell+keys-file env the key is read from (default process.env).
304
- * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, sheet?:any[]|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
337
+ * @returns {(executorContext:object, grantedTools:Record<string,any>, stepMeta?:{class?:string, attempt?:number, step?:string|null, cited?:any, sheet?:any[]|null, withText?:boolean, picked?:any[]|null, thinkingMode?:'on'|'off'}, seam?:{stopRequested?:() => boolean}) => Promise<any>}
305
338
  */
306
339
  export function makeLiveModelStep({
307
340
  slot, model, spendPath, provider: injectedProvider, rates: injectedRates, modelId: injectedModelId, env,
@@ -342,7 +375,7 @@ export function makeLiveModelStep({
342
375
  const runDir = dirname(spendPath);
343
376
  const diaryStep = stepMeta.step ?? null;
344
377
  const diaryTry = typeof stepMeta.attempt === 'number' ? stepMeta.attempt : null;
345
- const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : null);
378
+ const toolSchema = buildEmitArtifactSchema(stepMeta.class, stepMeta.class === 'green' && Boolean(stepMeta.cited), stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? stepMeta.sheet : null, stepMeta.class === 'green' && stepMeta.withText === true);
346
379
  const thinkingMode = stepMeta.thinkingMode === 'on' || stepMeta.thinkingMode === 'off' ? stepMeta.thinkingMode : null;
347
380
  const systemPrompt = 'You are executing one step of a signed, human-authored automation. '
348
381
  + 'Call emit_artifact exactly once with this step\'s result. Ground every value in the '
@@ -353,12 +386,17 @@ export function makeLiveModelStep({
353
386
  gap: executorContext.gap,
354
387
  // 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
388
  ...(typeof executorContext.hints === 'string' && executorContext.hints !== '' ? { fromEarlierRuns: executorContext.hints } : {}),
356
- // 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
- ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: citedBrief(stepMeta.cited) } : {}),
389
+ // 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
390
+ ...(typeof executorContext.memo === 'string' && executorContext.memo !== '' ? { fromThisRun: executorContext.memo } : {}),
391
+ // M10 am7 item 3: a step that quotes a saved page is told the form of its answer and what each result must hold; M10 am28: and each pick on its line (values only)
392
+ ...(stepMeta.class === 'green' && stepMeta.cited ? { quoting: { ...citedBrief(stepMeta.cited), ...(Array.isArray(stepMeta.picked) && stepMeta.picked.length > 0 ? { yourTextHas: toldPicks(stepMeta.picked) } : {}) } } : {}),
358
393
  // 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
394
  ...(stepMeta.class === 'green' && Array.isArray(stepMeta.sheet) ? { answering: sheetBrief(stepMeta.sheet) } : {}),
395
+ // M10 am22: a fact step whose line carries the person's picks also writes the answer the job line asks for, in "text" (their sizes are in the job line)
396
+ ...(stepMeta.class === 'green' && stepMeta.withText === true ? { alsoWrite: 'Also give "text": the written answer the goal asks for, in your own words, grounded in what you found. Never leave it empty.' } : {}),
360
397
  });
361
- const messages = [
398
+ /** @type {any[]} */
399
+ let messages = [
362
400
  { role: 'system', content: systemPrompt },
363
401
  { role: 'user', content: userContent },
364
402
  ];
@@ -412,14 +450,25 @@ export function makeLiveModelStep({
412
450
  tokens: { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0 },
413
451
  tools: /** @type {Record<string, number>} */ ({}),
414
452
  ungranted: /** @type {string[]} */ ([]),
453
+ badCalls: /** @type {any[]} */ ([]),
454
+ forcedRefused: false,
415
455
  refused,
416
456
  // 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
457
  // bareagent reported across its rounds (null = none reported). The ONE place this record is built; `toolFields` hands it to every return.
418
458
  thinking: /** @type {{asked: string|null, status: string|null}} */ ({ asked: thinkingMode ?? null, status: null }),
419
459
  };
420
- let noToolCallStreak = 0;
421
-
422
- for (let round = 1; round <= 2; round += 1) {
460
+ // 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
461
+ // `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.
462
+ let freshRetry = false;
463
+ let forcedAsked = false;
464
+ const force = { on: false };
465
+ /** @type {'first'|'forced'|'fallback'} */
466
+ let savedBy = 'first';
467
+ // 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)
468
+ /** @type {string|undefined} */
469
+ let firstText;
470
+
471
+ for (let round = 1; round <= 3; round += 1) {
423
472
  let capturedArtifact;
424
473
  const emitTool = {
425
474
  name: 'emit_artifact',
@@ -461,15 +510,24 @@ export function makeLiveModelStep({
461
510
  }
462
511
  }
463
512
  };
464
- const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }), rates, onLlmResult, ...stopSeam });
513
+ // 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`
514
+ const loop = new Loop({ provider: watchCalls(provider, (r) => { lastCall = r; }, force), rates, onLlmResult, checkArgs: true, ...stopSeam });
465
515
 
466
516
  const startedAt = Date.now();
467
517
  let result;
518
+ force.on = round === 2 && !freshRetry && !IGNORES_TOOL_CHOICE(provider);
519
+ forcedAsked = force.on;
468
520
  try {
469
521
  // eslint-disable-next-line no-await-in-loop
470
522
  // 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
523
  result = await loop.run(messages, tools, { maxTokens: 16000, ...(thinkingMode ? { thinkingMode } : {}) });
472
524
  } catch (err) {
525
+ // M4d am37: the same refused forced call, when the Loop threw it instead of reporting it (see below)
526
+ if (forcedAsked && round === 2 && roundMeterings.length === 0 && !isTransportFailure(err) && err?.code !== 'EDEADLINE') {
527
+ cumulative.forcedRefused = true;
528
+ // eslint-disable-next-line no-continue
529
+ continue;
530
+ }
473
531
  const wallMs = Date.now() - startedAt;
474
532
  const partial = sumMeterings(roundMeterings);
475
533
  cumulative = addMeter(cumulative, partial);
@@ -529,12 +587,20 @@ export function makeLiveModelStep({
529
587
 
530
588
  const wallMs = Date.now() - startedAt;
531
589
  const stoppedByYou = result.error === `halt:${STOP_RULE}`;
590
+ // 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
591
+ // 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.
592
+ if (forcedAsked && round === 2 && roundMeterings.length === 0 && result.error && !stoppedByYou) {
593
+ cumulative.forcedRefused = true;
594
+ // eslint-disable-next-line no-continue
595
+ continue;
596
+ }
532
597
  // 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
598
  // must never be added as "cost unknown" onto the calls an earlier round already made.
534
599
  if (stoppedByYou && roundMeterings.length === 0) return stoppedResult(cumulative, modelId, null);
535
600
  const metered = sumMeterings(roundMeterings);
536
601
  cumulative = addMeter(cumulative, metered);
537
602
  cumulative = { ...cumulative, ...addToolCounts(cumulative, result.metrics?.byTool, grantedNames) };
603
+ if (Array.isArray(result.badCalls)) cumulative = { ...cumulative, badCalls: [...cumulative.badCalls, ...result.badCalls] };
538
604
  if (result.thinkingStatus !== undefined) cumulative.thinking = { asked: cumulative.thinking.asked, status: worstThinkingStatus([cumulative.thinking.status, result.thinkingStatus]) };
539
605
  appendSpendRow(spendPath, {
540
606
  provider: slot ?? null,
@@ -559,7 +625,7 @@ export function makeLiveModelStep({
559
625
  // bigger cap), never a transient fault a retry could fix.
560
626
  return {
561
627
  ok: false,
562
- red: `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
628
+ red: cutOffRed(result.cutOff) ?? `truncated: ${metered.tokens?.outputTokens ?? '?'} tokens, no tool call`,
563
629
  costUsd: cumulative.costUsd,
564
630
  tokens: cumulative.tokens,
565
631
  ...toolFields(cumulative),
@@ -569,9 +635,14 @@ export function makeLiveModelStep({
569
635
  }
570
636
 
571
637
  if (capturedArtifact === undefined) {
572
- noToolCallStreak += 1;
573
- if (noToolCallStreak >= 2) {
574
- const malformed = provider?.lastMalformedToolCall ?? null;
638
+ const malformed = provider?.lastMalformedToolCall ?? null;
639
+ // today's path: a malformed tool call on round 1 is retried once fresh; a second round without a save ends the step
640
+ if (round === 1 && (malformed || result.error)) {
641
+ freshRetry = true;
642
+ // eslint-disable-next-line no-continue
643
+ continue;
644
+ }
645
+ if (freshRetry || round === 3) {
575
646
  if (malformed) {
576
647
  // bare-agent >=0.50 delivers the FULL `rawArguments` (verbatim, uncapped; `rawTruncated` is never set), and only when the provider was
577
648
  // built with `exposeMalformedArgs: true`. We bound what is logged and shown, with the cut said out loud. Absent -> no "; raw:" suffix.
@@ -586,9 +657,10 @@ export function makeLiveModelStep({
586
657
  modelMatch,
587
658
  };
588
659
  }
660
+ const tried = freshRetry ? 'twice in a row' : 'after the forced save and the fallback were tried';
589
661
  return {
590
662
  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)}`,
663
+ red: `a FINISHED round (stopReason=${result.stopReason}) returned text instead of the tool ${tried}. Text: ${JSON.stringify(result.text)}`,
592
664
  costUsd: cumulative.costUsd,
593
665
  tokens: cumulative.tokens,
594
666
  ...toolFields(cumulative),
@@ -596,8 +668,11 @@ export function makeLiveModelStep({
596
668
  modelMatch,
597
669
  };
598
670
  }
671
+ if (round === 1 && !result.error && typeof result.text === 'string' && result.text !== '') firstText = boundRaw(result.text);
672
+ // 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
673
+ if (!result.error) messages = [...result.msgs, { role: 'user', content: NUDGE }];
599
674
  // eslint-disable-next-line no-continue
600
- continue; // retry once, same attempt
675
+ continue;
601
676
  }
602
677
 
603
678
  if (cumulative.costUsd === null) {
@@ -606,8 +681,11 @@ export function makeLiveModelStep({
606
681
  };
607
682
  }
608
683
 
684
+ // M4d am37: which way it saved - round 1 (or the malformed-call retry, as today), the forced call, or the unforced fallback
685
+ if (!freshRetry && round === 2) savedBy = forcedAsked ? 'forced' : 'fallback';
686
+ if (round === 3) savedBy = 'fallback';
609
687
  return {
610
- ok: true, artifact: capturedArtifact, costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
688
+ ok: true, artifact: capturedArtifact, savedBy, ...(savedBy !== 'first' && firstText !== undefined ? { firstText } : {}), costUsd: cumulative.costUsd, model: modelId, modelMatch, tokens: cumulative.tokens, ...toolFields(cumulative),
611
689
  };
612
690
  }
613
691
 
package/src/pageask.js CHANGED
@@ -10,10 +10,12 @@
10
10
  // READING: a kept fact carries it with a `reading` (a limit the page cannot hold in words, e.g. "not a red-eye"). Asked only when a bound of the
11
11
  // reading is NOT in the words the person wrote; a bound they wrote themselves is theirs and nothing is asked.
12
12
  // CAN'T CHECK: no kept fact carries it.
13
+ // A COUNT guardrail (declaration.js isCountGuardrail) is none of these: it is asked once, as a pick (M10 am24).
13
14
  // Throws away: a fact's name, words and source (only its reading and the rule it serves are used).
14
15
  import { redactSecrets } from './redact.js';
15
16
  import { lineRules, boundInWords, wordsSaidOn } from './pagebits.js';
16
17
  import { validReading } from './pagerules.js';
18
+ import { isCountGuardrail } from './declaration.js';
17
19
 
18
20
  /** the most asks before drafting; more than this is a job to rewrite, not a questionnaire (am1) */
19
21
  export const MAX_LOOK_ASKS = 3;
@@ -22,7 +24,7 @@ export const DROP_IT = 'drop it';
22
24
  /** @param {unknown} text @returns {boolean} */
23
25
  export const isDropIt = (text) => String(text ?? '').trim().replace(/\.$/, '').toLowerCase() === DROP_IT;
24
26
  /** 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'];
27
+ export const AGREE_WORDS = ['agree', 'yes'];
26
28
  /** @param {unknown} text @returns {boolean} */
27
29
  export const isAgree = (text) => AGREE_WORDS.includes(String(text ?? '').trim().replace(/[.!]$/, '').toLowerCase());
28
30
 
@@ -97,6 +99,7 @@ export function askableFromLook(look, jobLines) {
97
99
  for (const l of Array.isArray(jobLines) ? jobLines : []) {
98
100
  lineRules(l).forEach((rule, k) => {
99
101
  const n = k + 1;
102
+ if (isCountGuardrail(rule)) return; // M10 am24: a count guardrail is asked only as a pick (src/checkpick.js), never as a page question; its look facts stay
100
103
  const key = `${l.n}\u0000${rule.trim().toLowerCase()}`;
101
104
  const tied = facts.filter((f) => f.line === l.n && f.forRule === n);
102
105
  if (tied.length > 0) {
@@ -139,14 +142,17 @@ export function tooManyAsksText(asks) {
139
142
  * 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
143
  * `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
144
  * 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)
145
+ * 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
146
+ * 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).
147
+ * @param {{source?: string, ask?: string, proposal?: string|null, check?: Record<string, any>}} q @param {unknown} typed
148
+ * @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
149
  */
145
150
  export function ruleOfAnswer(q, typed) {
146
151
  const typedText = String(typed ?? '').replace(/\s*\n\s*/g, ' ').trim();
147
152
  if (q.source !== 'look') return { rule: typedText, left: false };
148
153
  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 };
154
+ const shape = q.ask === 'check' || q.ask === 'no-check';
155
+ 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 } : {}) };
156
+ if ((q.ask === 'cant-check' || shape) && isDropIt(text)) return { rule: null, left: true };
157
+ return { rule: text, left: false, ...(shape ? { own: true } : {}) };
152
158
  }
@@ -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];