bareloop 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/carrystore.js CHANGED
@@ -1,35 +1,22 @@
1
1
  // The carry note's store (M1, F258): the run-level record behind src/carrynote.js. It captures the worker's read-class tool
2
- // calls AT THE SOURCE (the same seam the handoff note uses: the worker's tool objects, result SUMMARIES only, never file
3
- // content), reads the run's edits from the WORKING TREE (git diff against the run's start commit, never the spine), renders
2
+ // calls AT THE SOURCE (the worker's tool objects, result SUMMARIES only, never file
3
+ // content), reads the run's edits from the WORKING TREE (git diff against the run's start commit, never the spine), renders
4
4
  // the note and persists its state under `<workdir>/.smoke/carry/state.json` (an arbiter book: the worker's fs.deny covers
5
- // `.smoke`, so it cannot read it; the gate audit, spine and bridges live there too). The switch is `carryNote` in
6
- // config.json (absent = on; only `false` turns it off), read once per run by the engine's caller.
5
+ // `.smoke`, so it cannot read it; the gate audit, spine and bridges live there too). There is no switch: the memo is
6
+ // always on (hamr 2026-11-01).
7
7
  import { execFile } from 'node:child_process';
8
8
  import { promisify } from 'node:util';
9
9
  import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
10
10
  import { isAbsolute, join, relative, resolve } from 'node:path';
11
11
  import { SMOKE_STORE } from './kinds.js';
12
- import { isHandoffExcluded } from './handoff.js';
13
12
  import { redactSecrets } from './validate.js';
14
- import { render, HUNK_LINES } from './carrynote.js';
15
- import { readConfig } from './config.js';
13
+ import { render, isCarryExcluded, HUNK_LINES } from './carrynote.js';
16
14
 
17
15
  const exec = promisify(execFile);
18
16
  export const CARRY_DIR = 'carry';
19
- /** the next prompt of a retried step / fix try carries this when the previous ask's check failed */
17
+ /** the retry marker the next prompt of a retried step / fix try carries; kept as a pinned fact about the prompts, no longer read to decide an outcome */
20
18
  export const RED_MARKER = /Previous attempt failed (this step's checks|the verification):/;
21
19
 
22
- /**
23
- * The ONE setting: `carryNote` in config.json, read exactly like `learningHints` (src/learnstore.js `learningHintsOn`).
24
- * Absent = on; only an explicit `false` turns it off. An unreadable config reads as OFF (the safe side).
25
- * @param {string} [home]
26
- * @returns {boolean}
27
- */
28
- export function carryNoteOn(home) {
29
- const c = readConfig({ home });
30
- return c.problem === null && c.config.carryNote !== false;
31
- }
32
-
33
20
  const lineCount = (/** @type {string} */ s) => (s === '' ? 0 : s.split('\n').length - (s.endsWith('\n') ? 1 : 0));
34
21
  const clip = (/** @type {unknown} */ s, n = 200) => redactSecrets(String(s ?? '')).slice(0, n);
35
22
 
@@ -46,7 +33,7 @@ export async function workingEdits(workdir, base) {
46
33
  try {
47
34
  const { stdout: names } = await g(['diff', '--name-only', '-z', base]);
48
35
  for (const p of names.split('\0').filter(Boolean)) {
49
- if (isHandoffExcluded(p)) continue;
36
+ if (isCarryExcluded(p)) continue;
50
37
  const { stdout } = await g(['diff', '-U1', '--no-color', '--no-ext-diff', base, '--', `:(literal)${p}`]);
51
38
  if (/^(Binary files .* differ|GIT binary patch)$/m.test(stdout)) { out.push({ path: p, lines: 0, hunks: ['(binary file changed)'] }); continue; }
52
39
  const body = stdout.split('\n').filter((l) => !/^(diff --git|index |--- |\+\+\+ |new file mode|deleted file mode)/.test(l));
@@ -54,7 +41,7 @@ export async function workingEdits(workdir, base) {
54
41
  }
55
42
  const { stdout: un } = await g(['ls-files', '--others', '--exclude-standard', '-z']);
56
43
  for (const p of un.split('\0').filter(Boolean)) {
57
- if (isHandoffExcluded(p)) continue;
44
+ if (isCarryExcluded(p)) continue;
58
45
  try {
59
46
  const abs = resolve(workdir, p);
60
47
  if (!statSync(abs).isFile() || statSync(abs).size > 262144) continue;
@@ -93,11 +80,13 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume = false })
93
80
  /** @type {any[]} one per WORK ask (step/fix): {n, kind, step, iteration, bounded, red, changed, startSnap} */
94
81
  let asks = [];
95
82
  let loaded = false;
83
+ /** @type {string|null} the job's own count-check text at start (the seed note's body), the oldest entry of the memo's earlier failures */
84
+ let startFailure = null;
96
85
  if (resume && existsSync(stateFile)) {
97
- try { const s = JSON.parse(readFileSync(stateFile, 'utf8')); n = s.n ?? 0; events = s.events ?? []; asks = s.asks ?? []; base = s.base ?? null; loaded = true; } catch { /* a bad file starts empty */ }
86
+ try { const s = JSON.parse(readFileSync(stateFile, 'utf8')); n = s.n ?? 0; events = s.events ?? []; asks = s.asks ?? []; base = s.base ?? null; startFailure = s.startFailure ?? null; loaded = true; } catch { /* a bad file starts empty */ }
98
87
  }
99
88
  const save = () => {
100
- try { mkdirSync(dir, { recursive: true }); writeFileSync(stateFile, JSON.stringify({ n, base, events, asks })); } catch { /* a record, never a verdict: a failed save never breaks a run */ }
89
+ try { mkdirSync(dir, { recursive: true }); writeFileSync(stateFile, JSON.stringify({ n, base, events, asks, startFailure })); } catch { /* a record, never a verdict: a failed save never breaks a run */ }
101
90
  };
102
91
  const rel = (/** @type {string} */ p) => (isAbsolute(p) ? relative(workdir, p) : p).split('\\').join('/') || '.';
103
92
  const diskLines = (/** @type {string} */ r, /** @type {string|undefined} */ fallback) => { try { return lineCount(readFileSync(resolve(workdir, r), 'utf8')); } catch { return fallback === undefined ? null : lineCount(fallback); } };
@@ -161,24 +150,57 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume = false })
161
150
  }
162
151
  };
163
152
 
153
+ /** the per-entry cap on one file's function ranges, so one huge file cannot eat the memo */
154
+ const FN_CAP = 500;
155
+ /**
156
+ * Function line ranges per read file, from the LiteCtx index's named chunks (`name a-b, ...`). Fresh index only: a node whose
157
+ * last chunk ends past the file's current end is stale, and that file gets no ranges. Never throws.
158
+ * @param {any[]} evs @param {(rel: string) => any} getNode @returns {Record<string, string>}
159
+ */
160
+ const fnRangesOf = (evs, getNode) => {
161
+ /** @type {Record<string, string>} */ const out = {};
162
+ for (const p of new Set(evs.filter((e) => (e.tool === 'read' || e.tool === 'get') && !e.dir && e.path && !isCarryExcluded(e.path)).map((e) => e.path))) {
163
+ let node = null;
164
+ try { node = getNode(p); } catch { node = null; }
165
+ const n = diskLines(p, undefined);
166
+ const named = (node?.chunks ?? []).filter((/** @type {any} */ c) => c.symbol);
167
+ if (n === null || !named.length || !named.every((/** @type {any} */ c) => c.endLine <= n)) continue;
168
+ let map = ''; let more = 0;
169
+ for (let i = 0; i < named.length; i++) {
170
+ const piece = `${named[i].symbol} ${named[i].startLine}-${named[i].endLine}`;
171
+ if ((map ? map.length + 2 : 0) + piece.length > FN_CAP) { more = named.length - i; break; }
172
+ map += (map ? ', ' : '') + piece;
173
+ }
174
+ out[p] = map + (more ? `, +${more} more` : '');
175
+ }
176
+ return out;
177
+ };
178
+
164
179
  const snapOf = (/** @type {{path: string, lines: number}[]} */ edits) => Object.fromEntries(edits.map((e) => [e.path, e.lines]));
165
180
  const tryLabel = (/** @type {any} */ a) => (a.kind === 'fix' ? `fix loop try ${a.iteration}` : `step "${a.step}" try ${a.iteration}`);
166
- const endedOf = (/** @type {any} */ a) => a.boundedText || (a.red ? 'Its check failed.' : 'Its check passed.');
181
+ // how the try ended AND what its check said: a bounded try says both (the bound hides nothing)
182
+ const endedOf = (/** @type {any} */ a) => {
183
+ const res = a.result === 'red' ? 'Its check failed.' : a.result === 'green' ? 'Its check passed.' : null;
184
+ if (a.boundedText) return `${a.boundedText} ${res ?? 'Check not run.'}`;
185
+ return res ?? 'No check result was recorded for it.';
186
+ };
167
187
 
168
188
  /**
169
189
  * Called at the start of EVERY ask (scout and drafter included, so their finds feed the store).
170
190
  * Returns the note text for step/fix asks, '' otherwise.
171
- * @param {{phase: string, iteration: number|string|undefined, prompt: string}} o
191
+ * `getNode`: the LiteCtx index's node for a path (its `chunks`), for the function ranges; absent = no ranges.
192
+ * @param {{phase: string, iteration: number|string|undefined, prompt: string, getNode?: (rel: string) => any}} o
172
193
  */
173
- const beginAsk = async ({ phase, iteration, prompt }) => {
194
+ const beginAsk = async ({ phase, iteration, prompt, getNode }) => {
174
195
  n++;
175
196
  const work = phase === 'fix' || phase.startsWith('step:');
176
197
  if (!work) { save(); return ''; }
177
198
  const edits = await workingEdits(workdir, base);
178
199
  const prev = asks[asks.length - 1];
179
200
  if (prev && prev.red === undefined) {
180
- // settle the previous work ask: red = this prompt says the last attempt failed; changed = files whose changed-line count moved
181
- prev.red = RED_MARKER.test(prompt);
201
+ // settle the previous work ask: red = the check result the engine handed to settleAsk (never this prompt's wording);
202
+ // changed = files whose changed-line count moved
203
+ prev.red = prev.result === 'red';
182
204
  const now = snapOf(edits);
183
205
  prev.changed = [...new Set([...Object.keys(now), ...Object.keys(prev.startSnap)])].filter((p) => now[p] !== prev.startSnap[p]).sort();
184
206
  for (const e of events) if (e.ask === prev.n) e.noFix = prev.changed.length === 0 && prev.red;
@@ -192,14 +214,22 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume = false })
192
214
  lastCheck: null, // the failed check's text is already in the prompt today; one copy
193
215
  events: events.map((e) => ({ ...e })),
194
216
  edits: orderEditsByRecency(edits, settled),
217
+ // every failed check's whole text, oldest first; the newest is left out only when it belongs to the last settled try
218
+ // (a red try being retried: the prompt carries it, one copy). A failure from a try that was later passed is in no prompt.
219
+ // plus the start failure, oldest of all: it is never in a prompt gap, so it is never the one left out
220
+ failures: [...(startFailure ? [{ label: 'at start', text: startFailure }] : []), ...settled.filter((a) => a.failure && a !== lt).map((a) => ({ label: tryLabel(a), text: a.failure }))],
195
221
  earlier: settled.slice(0, -1).map((a) => `${tryLabel(a)}: ${endedOf(a)} ${a.changed.length ? `Changed ${a.changed.join(', ')}.` : 'Changed nothing.'}`),
196
222
  lastAsk: lt ? lt.n : undefined,
223
+ fnRanges: getNode ? fnRangesOf(events, getNode) : {},
197
224
  };
198
225
  asks.push({ n, kind, step, iteration, startSnap: snapOf(edits) });
199
- const hasAny = notes.events.length || edits.length || notes.earlier.length || notes.lastTry;
226
+ const hasAny = notes.events.length || edits.length || notes.earlier.length || notes.failures.length || notes.lastTry;
200
227
  if (!hasAny) { save(); return ''; }
201
228
  const r = render(/** @type {any} */ (notes));
202
- emit('carry-note', { phase, iteration, chars: r.text.length, capped: r.capped, sections: r.sections }); // counts only
229
+ // counts plus the note text itself (F274, so the Audit can show it where it was handed). `render` masked the whole text with the one
230
+ // inventory; the second pass here is idempotent. `chars` = the length of this saved (masked) text.
231
+ const saved = redactSecrets(r.text);
232
+ emit('carry-note', { phase, iteration, chars: saved.length, capped: r.capped, sections: r.sections, text: saved });
203
233
  save();
204
234
  return r.text;
205
235
  };
@@ -216,5 +246,22 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume = false })
216
246
  save();
217
247
  };
218
248
 
219
- return { wrapTools, beginAsk, endAsk, setBase: (/** @type {string|null|undefined} */ b) => { if (!base && b) base = b; }, loaded: () => loaded, _state: () => ({ n, events, asks, base }) };
249
+ /**
250
+ * The engine's own check result for the ask that just returned: 'green' (every check passed), 'red' (one failed) or
251
+ * 'unknown' (the check hit an instrument fault, so no honest answer). Only the first result per ask counts.
252
+ * A red also hands over the check's WHOLE failing text (the gap the next prompt carries); it is stored masked, never clipped.
253
+ * @param {'green'|'red'|'unknown'} result @param {string} [text]
254
+ */
255
+ const settleAsk = (result, text) => {
256
+ const a = asks[asks.length - 1];
257
+ if (!a || a.n !== n || a.result !== undefined) return;
258
+ a.result = result;
259
+ if (result === 'red' && typeof text === 'string' && text !== '') a.failure = redactSecrets(text);
260
+ save();
261
+ };
262
+
263
+ /** The seed note's body (already secret-masked), set once per run; a resume keeps the one it persisted. @param {string} text */
264
+ const setStartFailure = (text) => { if (!startFailure && text) { startFailure = text; save(); } };
265
+
266
+ return { wrapTools, beginAsk, setStartFailure, endAsk, settleAsk, setBase: (/** @type {string|null|undefined} */ b) => { if (!base && b) base = b; }, loaded: () => loaded, _state: () => ({ n, events, asks, base }) };
220
267
  }
package/src/config.js CHANGED
@@ -10,7 +10,6 @@
10
10
  // Shape (unknown fields are kept, never dropped):
11
11
  // { "monthlyLimitUsd": <number > 0>, // absent = no limit, no check
12
12
  // "learningHints": true|false, // absent = true (ON by default; only false turns it off): the planner is handed cross-run learnings (src/learn.js); the tally is kept either way
13
- // "carryNote": true|false, // absent = true (ON by default; only false turns it off): a step/fix worker is handed a code-written, facts-only note of what earlier workers of the same run looked at, searched and changed (src/carrynote.js); off = the worker prompt is exactly as before
14
13
  // "keys": { "<ENV NAME>": { "shape": "<shape id>", "baseUrl": "http(s)://…", "legacyMaxTokens": true|false } },
15
14
  // "models": { "<ENV NAME>": [ { "model": "<id>", "use": true|false, "inPerM": n, "outPerM": n } ] } }
16
15
  // An older file's `keys.<ENV>.{name,priceInPerM,priceOutPerM}` is tolerated and read as ONE model
@@ -131,7 +130,6 @@ export function modelsProblem(list) {
131
130
  function docProblem(doc) {
132
131
  // monthlyLimitUsd is NOT judged here: `monthlyLimitOf` (src/monthly.js) owns its read-time sentence
133
132
  if (doc.learningHints !== undefined && typeof doc.learningHints !== 'boolean') return 'learningHints must be true or false';
134
- if (doc.carryNote !== undefined && typeof doc.carryNote !== 'boolean') return 'carryNote must be true or false';
135
133
  if (doc.keys !== undefined) {
136
134
  if (doc.keys === null || typeof doc.keys !== 'object' || Array.isArray(doc.keys)) return 'keys must be an object of key variable names';
137
135
  for (const [env, row] of Object.entries(doc.keys)) {
@@ -160,10 +158,10 @@ function docProblem(doc) {
160
158
  * `keys` merges per key variable name, then per field; `models.<ENV>` is REPLACED WHOLE (`null`
161
159
  * clears it). Validated before anything is written; nothing is written on a refusal.
162
160
  *
163
- * Patch fields understood: `monthlyLimitUsd` (finite > 0), `learningHints` (true | false), `carryNote` (true | false), `keys.<ENV>.{shape,baseUrl,legacyMaxTokens}`,
161
+ * Patch fields understood: `monthlyLimitUsd` (finite > 0), `learningHints` (true | false), `keys.<ENV>.{shape,baseUrl,legacyMaxTokens}`,
164
162
  * `models.<ENV>` (a list judged by {@link modelsProblem}). The first write of a row's `models` list
165
163
  * removes that row's older `name` / `priceInPerM` / `priceOutPerM` in the SAME write (never two
166
- * sources); a retired top-level `anthropicBalanceNote` is dropped on any write. Any other field is
164
+ * sources); the retired top-level `anthropicBalanceNote` and `carryNote` (the carry memo is always on, 2026-11-01) are dropped on any write. Any other field is
167
165
  * kept, but the whole document is swept for secret-shaped strings first.
168
166
  * @param {Record<string, any>} patch
169
167
  * @param {{ home?: string }} [opts]
@@ -181,10 +179,10 @@ export function updateConfig(patch, opts = {}) {
181
179
  throw new ConfigError('monthlyLimitUsd must be a number above 0 (remove the limit to have none)');
182
180
  }
183
181
  if (k === 'learningHints' && typeof v !== 'boolean') throw new ConfigError('learningHints must be true or false');
184
- if (k === 'carryNote' && typeof v !== 'boolean') throw new ConfigError('carryNote must be true or false');
185
182
  next[k] = v;
186
183
  }
187
184
  delete next.anthropicBalanceNote;
185
+ delete next.carryNote;
188
186
  if (patch.keys !== undefined) {
189
187
  if (patch.keys === null || typeof patch.keys !== 'object' || Array.isArray(patch.keys)) {
190
188
  throw new ConfigError('keys must be an object of key variable names');
@@ -102,7 +102,7 @@ export const DECLARED_GENRES = Object.freeze([TYPES_GENRE.name, TEXT_GENRE]);
102
102
  * constrained to the names the genre OWNS, so it can never become an environment
103
103
  * channel of its own.
104
104
  */
105
- export const CLOSE_DECL_FIELDS = Object.freeze(['genre', 'lang', 'stages', 'notes', 'refused', 'genreEnv', 'calibration']);
105
+ export const CLOSE_DECL_FIELDS = Object.freeze(['genre', 'lang', 'stages', 'notes', 'refused', 'guardLines', 'genreEnv', 'calibration']);
106
106
 
107
107
  /** what a stored calibration set carries, ENUMERATED: the frozen cases and the judge
108
108
  * tier that graded them. Both are inside the spec, so `jobSpecHash` covers both — which
package/src/job.js CHANGED
@@ -170,7 +170,7 @@ export const CONDITION_KEYS = Object.freeze(['providerPath', 'closeVerbosity', '
170
170
  // `steps` stays in the field list ONLY so a retired spec reds by name
171
171
  // (`shape-retired`) instead of falling through to a generic unknown-field —
172
172
  // the operator gets told what happened, not just that something is wrong.
173
- const JOB_FIELDS = ['schema', 'job', 'description', 'provider', 'baseUrl', 'conditions', 'cadence', 'trigger', 'budgetUsd', 'maxWallMs', 'closeTimeoutMs', 'model', 'thinking', 'handoffNote', 'judge', 'writeScope', 'steps', 'escalation', 'goal', 'verdictType', 'close', 'closeDecl', 'checks', 'tools', 'jobLines', 'inputs'];
173
+ const JOB_FIELDS = ['schema', 'job', 'description', 'provider', 'baseUrl', 'conditions', 'cadence', 'trigger', 'budgetUsd', 'maxWallMs', 'closeTimeoutMs', 'model', 'thinking', 'handoffNote', 'seedNote', 'readMap', 'judge', 'writeScope', 'steps', 'escalation', 'goal', 'verdictType', 'close', 'closeDecl', 'checks', 'tools', 'jobLines', 'inputs'];
174
174
  /** the exact fields of a signed `judge` override — nested objects red unknown
175
175
  * keys too, because no smuggling level exists in a signed spec */
176
176
  const JUDGE_FIELDS = ['provider', 'model'];
@@ -349,10 +349,22 @@ export function validateJob(input, { shellCapUsd = 2 } = {}) {
349
349
  if (spec.thinking !== undefined && typeof spec.thinking !== 'boolean') {
350
350
  red('invalid-value', 'thinking', 'true or false — the job\'s "Thinking on" tick (absent = off)');
351
351
  }
352
- // THE HANDOFF NOTE (src/handoff.js): a declared job condition, signed like `thinking`. A boolean; ABSENT = on (an old spec keeps its
353
- // bytes, so its hash), only an explicit `false` turns the note off. The switch is hashed; the note's text never is.
352
+ // LEGACY `handoffNote` (the handoff note was folded into the carry memo, 2026-10-31): still accepted and hashed so an old signed spec
353
+ // verifies; it has NO effect since 2026-11-01 (the carry memo is always on). A boolean if present. New specs and drafts never write it.
354
354
  if (spec.handoffNote !== undefined && typeof spec.handoffNote !== 'boolean') {
355
- red('invalid-value', 'handoffNote', 'true or false (absent = on): whether the next step/fix worker is handed a map of the files earlier workers read');
355
+ red('invalid-value', 'handoffNote', 'true or false (legacy, ignored: the carry memo is always on)');
356
+ }
357
+
358
+ // THE SEED NOTE (src/seednote.js): a declared job condition, signed like `thinking`. A boolean; ABSENT = on (an old spec keeps its
359
+ // bytes, so its hash), only an explicit `false` turns off handing the planner and the first worker what the job's own check said at start. The switch is hashed; the text never is.
360
+ if (spec.seedNote !== undefined && typeof spec.seedNote !== 'boolean') {
361
+ red('invalid-value', 'seedNote', 'true or false (absent = on): whether the planner and the first worker are told what the job\'s own count check said on the untouched tree');
362
+ }
363
+
364
+ // THE FIRST-READ MAP (src/readshim.js, EXPERIMENTAL): a declared job condition, signed like `thinking`. A boolean; ABSENT = off (an old spec keeps
365
+ // its bytes, so its hash), `true` makes the first shell_read of a big non-test file in an ask return a map of its parts. The switch is hashed.
366
+ if (spec.readMap !== undefined && typeof spec.readMap !== 'boolean') {
367
+ red('invalid-value', 'readMap', 'true or false (absent = off, experimental): whether the first read of a big file in an ask returns a map of its parts instead of the file');
356
368
  }
357
369
 
358
370
  // JUDGE — PRD item 32.1 (hamr, 2026-09-10: the judge "defaults to whatever
package/src/kinds.js CHANGED
@@ -541,11 +541,13 @@ export async function seedAtHead(workdir) {
541
541
  * @returns {Promise<{stop: string, files: null}|{stop: null, files: string[]}>}
542
542
  */
543
543
  export async function seedListing(workdir, seedRef) {
544
- const r = await git(workdir, ['ls-tree', '-r', '--name-only', seedRef]);
544
+ // `-z`: NUL-separated, names raw. Without it git C-quotes any name with a non-ASCII byte
545
+ // (`"caf\303\251.js"`), so a listing entry would never equal the path on disk (F276 gap c).
546
+ const r = await git(workdir, ['ls-tree', '-r', '-z', '--name-only', seedRef]);
545
547
  if (!r.ok) {
546
548
  return { stop: `INSTRUMENT: git ls-tree -r ${seedRef} failed in ${workdir}: ${String(r.err).trim()}`, files: null };
547
549
  }
548
- return { stop: null, files: r.out.split('\n').map((s) => s.trim()).filter(Boolean) };
550
+ return { stop: null, files: r.out.split('\0').filter(Boolean) };
549
551
  }
550
552
 
551
553
  // ── contract (c): the changed-set primitive ──────────────────────────────────
@@ -7,6 +7,9 @@ import { FACT_LANGS } from './facts.js';
7
7
 
8
8
  /** @typedef {import('./pagerules.js').Dropped} Dropped */
9
9
 
10
+ /** the two ways a sign listed twice can be used once; the sentence below and the read-note probes (SENTENCE_RE) both read this one list */
11
+ const SIGN_TWICE_AS = ['currency', 'unit'];
12
+
10
13
  /** reason code -> the plain sentence (`d.word` = the page's word, `d.fact` = the fact's name, `d.other` = what it was compared to) */
11
14
  const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
12
15
  'not-on-page': (d) => `"${d.word}" is not written on the page.`,
@@ -14,7 +17,7 @@ const WORDS = /** @type {Record<string, (d: Dropped) => string>} */ ({
14
17
  'reads-no-amount': (d) => `The page never shows an amount next to "${d.word}", so it was not used to write the price.`,
15
18
  'n2': (d) => `"${d.word}" is written more than once inside one line of the page, so one result cannot show it once.`,
16
19
  'r1': (d) => `"${d.word}" does not show the same values as "${d.other}", so it was not used as a second way to read it.`,
17
- 'sign-twice': (d) => `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the ${d.other === 'unit' ? 'unit' : 'currency'}.`,
20
+ 'sign-twice': (d) => `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the ${SIGN_TWICE_AS.find((kind) => kind === d.other) ?? 'currency'}.`,
18
21
  'r1l': (d) => d.word === d.other
19
22
  ? `"${d.word}" was listed twice, as a unit and as a currency; it is used once, as the first way to write the price.`
20
23
  : `"${d.word}" does not show the same amounts as "${d.other}", so it was not used as a second way to write the price.`,
@@ -81,7 +84,7 @@ const SENTENCE_RE = (() => {
81
84
  /** @type {string[]} */
82
85
  const alts = [];
83
86
  for (const reason of WORD_REASONS) {
84
- const probes = reason === 'r1l' ? [{ word: W, other: W }, { word: W, other: O }] : reason === 'sign-twice' ? [{ word: W, other: 'currency' }, { word: W, other: 'unit' }] : [{ word: W, other: O }];
87
+ const probes = reason === 'r1l' ? [{ word: W, other: W }, { word: W, other: O }] : reason === 'sign-twice' ? SIGN_TWICE_AS.map((other) => ({ word: W, other })) : [{ word: W, other: O }];
85
88
  for (const p of probes) alts.push(esc(WORDS[reason](/** @type {any} */ ({ ...p, reason, line: 0, fact: 'f' }))).split(esc(W)).join('[^"]+').split(esc(O)).join('[^"]+'));
86
89
  }
87
90
  return new RegExp(`^(?:(?:${alts.join('|')})(?: |$))+$`);
@@ -0,0 +1,92 @@
1
+ // Where the memory and the learnings were passed on (ITEM33-BUILD addendum 2026-11-02): the Audit shows the carry memo under the
2
+ // worker try that received it, and the learnings text under the planner part that received it. READ-ONLY and pure: the spine's own
3
+ // `carry-note` / `learnings` records, matched by their RECORDED phase and iteration (never by a timestamp window).
4
+ import { parseHintBlock, hintsErrorLine } from '../learn.js';
5
+
6
+ /**
7
+ * One carry-note record as the Audit shows it: `{text, chars, capped}`, or `{missing:true, chars, capped}` for a record from before the
8
+ * text was saved (older run).
9
+ * @param {any} rec @returns {{text: string, chars: number, capped: boolean}|{missing: true, chars: number, capped: boolean}}
10
+ */
11
+ function memoOf(rec) {
12
+ const chars = typeof rec.chars === 'number' ? rec.chars : 0;
13
+ const capped = rec.capped === true;
14
+ return typeof rec.text === 'string' ? { text: rec.text, chars, capped } : { missing: true, chars, capped };
15
+ }
16
+
17
+ /**
18
+ * The carry-note record that belongs to one try. Match = the recorded phase (`step:<id>` is the part's own label, `fix` the fix part),
19
+ * the recorded iteration equal to the try's, and the record's spine order (`seq`) inside the try's own window. The window is needed
20
+ * because a step re-entered after a replan restarts at iteration 1; a try with no iteration (a whole-part fallback) takes the first
21
+ * record of its phase in its window.
22
+ * @param {any[]} recs the run's carry-note records @param {string} phase @param {any} a a try: {iteration?, startSeq, endSeq}
23
+ */
24
+ function recFor(recs, phase, a) {
25
+ const lo = typeof a.startSeq === 'number' ? a.startSeq : -Infinity;
26
+ const hi = typeof a.endSeq === 'number' ? a.endSeq : Infinity;
27
+ const hit = recs.filter((r) => r.phase === phase && typeof r.seq === 'number' && r.seq > lo && r.seq <= hi
28
+ && (typeof a.iteration !== 'number' || r.iteration === a.iteration));
29
+ return hit[0] ?? null;
30
+ }
31
+
32
+ /**
33
+ * Every step part's and fix part's tries (and a cut-off try) gain `memo`: the carry-note record handed to that try, or null; a try whose text-only ending was nudged (spine `worker-text-only`, `nudged: true`) also gains `nudged: true`.
34
+ * Parts and tries are copied, never mutated. An outer-close try (no model call) never has one.
35
+ * @param {any[]|null|undefined} parts @param {any[]} records the run's spine records
36
+ */
37
+ export function attachMemos(parts, records) {
38
+ if (!Array.isArray(parts)) return parts;
39
+ const recs = records.filter((r) => r?.type === 'carry-note');
40
+ const nudges = records.filter((r) => r?.type === 'worker-text-only' && r.nudged === true);
41
+ if (recs.length === 0 && nudges.length === 0) return parts.map((p) => (p.kind === 'step' || p.kind === 'fix' ? { ...p, attempts: (p.attempts ?? []).map((a) => ({ ...a, memo: null })) } : p));
42
+ return parts.map((p) => {
43
+ if (p.kind !== 'step' && p.kind !== 'fix') return p;
44
+ const phase = p.kind === 'fix' ? 'fix' : `step:${p.label}`;
45
+ const one = (/** @type {any} */ a) => {
46
+ if (a.source === 'outer-close') return { ...a, memo: null };
47
+ const r = recFor(recs, phase, a);
48
+ return { ...a, memo: r ? memoOf(r) : null, ...(recFor(nudges, phase, a) ? { nudged: true } : {}) };
49
+ };
50
+ return {
51
+ ...p,
52
+ attempts: (p.attempts ?? []).map(one),
53
+ ...(p.cutOffTry ? { cutOffTry: one(p.cutOffTry) } : {}),
54
+ };
55
+ });
56
+ }
57
+
58
+ /**
59
+ * The learnings the planner was handed, by injection: `draft` and `replan` (the first replan), each `{phase, text, chars, ids, hints}` or
60
+ * null, plus `error` (the plain line when the learnings file could not be read, else null).
61
+ * @param {any[]} records
62
+ */
63
+ export function learningsHanded(records) {
64
+ const pick = (/** @type {string} */ phase) => {
65
+ const e = records.find((r) => r?.type === 'learnings' && r.phase === phase && typeof r.text === 'string');
66
+ return e ? { phase, text: e.text, chars: e.text.length, ids: Array.isArray(e.ids) ? e.ids : [], hints: parseHintBlock(e.text) } : null;
67
+ };
68
+ const er = records.find((r) => r?.type === 'learnings' && typeof r.hintsError === 'string');
69
+ return { draft: pick('draft'), replan: pick('replan'), error: er ? hintsErrorLine(String(er.hintsError)) : null };
70
+ }
71
+
72
+ /**
73
+ * Put the learnings on the parts that received them: the draft block (and the error line) on the drafting part, else the `plan` part;
74
+ * the first-replan block on the first `replan` part. `drafting` is the drafting part or null. Copies, never mutates.
75
+ * @param {any[]|null|undefined} parts the spine's own parts @param {any|null} drafting @param {ReturnType<typeof learningsHanded>} l
76
+ * @returns {{parts: any[]|null|undefined, drafting: any|null}}
77
+ */
78
+ export function attachLearnings(parts, drafting, l) {
79
+ const draftExtra = { ...(l.draft ? { learnings: l.draft } : {}), ...(l.error ? { learningsError: l.error } : {}) };
80
+ const hasDraft = Object.keys(draftExtra).length > 0;
81
+ const toDrafting = hasDraft && drafting ? { ...drafting, ...draftExtra } : drafting;
82
+ if (!Array.isArray(parts)) return { parts, drafting: toDrafting };
83
+ let draftDone = !hasDraft || !!drafting;
84
+ let replanDone = !l.replan;
85
+ const out = parts.map((p) => {
86
+ if (!draftDone && p.kind === 'plan') { draftDone = true; return { ...p, ...draftExtra }; }
87
+ if (!replanDone && p.kind === 'replan') { replanDone = true; return { ...p, learnings: l.replan }; }
88
+ return p;
89
+ });
90
+ if (!draftDone && out.length > 0) out[0] = { ...out[0], ...draftExtra }; // no drafting or plan part: the first part, never lost
91
+ return { parts: out, drafting: toDrafting };
92
+ }