bareloop 0.51.0 → 0.52.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/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ All notable changes to bareloop are documented here. Format:
5
5
  [SemVer](https://semver.org/spec/v2.0.0.html). Pre-1.0: **minor** = a ladder rung or
6
6
  feature lands, **patch** = docs, fixes, scaffolding.
7
7
 
8
+ ## [0.52.0] - 2026-10-30
9
+
10
+ ### Added
11
+
12
+ - **A carry note: each new step or fix worker is told what earlier workers of the run read, searched and changed (M1, F258).** Code writes it from the run's own record (facts only, never file content, never a worker's words, secrets masked): where earlier workers looked (files with times read and line ranges, listings and config reads counted not shown), what they searched and what it matched, the edits made in the run with their diff hunks taken from the working tree, how the last and earlier tries ended, and a "looked here, no fix made" mark on a file read 3 or more times in a try that ended red with no change. It is appended after the handoff note, capped at 3,000 characters with diffs cut LAST (files, then searches, then earlier tries, then hunks one edit at a time, oldest first), and its state lives in `<workdir>/.smoke/carry/state.json` so a resumed leg keeps it. One report-only `carry-note` spine record (counts only) per note. ON by default; `carryNote: false` in `config.json` gives today's behaviour exactly (the handoff note only). Tested live in 2 rounds, underpowered: a leaning, not proof (see FINDINGS F258). Library callers opt in with `runJob(..., { carryNote: true })`; the engine reads the config switch once per run, like `learningHints`.
13
+
14
+ ### Security
15
+
16
+ - **A root `shell_grep` no longer reads the arbiter's books (F259, BG-3).** The loop gate judged a directory grep once, on the root path it named, so the walk read `.smoke/` (spine, attempt-diff), `gate-audit.jsonl` and `.litectx/` that a direct `shell_read` is denied. `bare-agent` is now `^0.55.0`, and the worker's and the authoring scout's shell tools are built with `canRead` (the gate's own `allows()` on the same read action, asked for every directory and file the walk would enter; a denied one is skipped) and `noFollowSymlinks: true`. One owner: `gatedShellOptions` in `src/tools.js`. Whole-call grep `timeout` (5000 ms default) now includes the walk.
17
+
18
+ ### Changed
19
+
20
+ - **Settings > Providers: the model row you are typing in is highlighted, and every key starts folded.** While focus is inside a model row (tick box or the IN/OUT price boxes) the whole row takes the Runs list's selected look (`--rl-accent-bg-strong` fill and an `--accent` edge); hover keeps the faint fill. A key with ticked models no longer opens on first paint; the summary line shows while folded.
21
+ - **The Audit tab's fix loop and plan steps draw as a check grid (PRD v1.119).** Data first: each fix try now carries the failing check's own output lines (`reasons`), where it came from (`source`: the opening close or a fix try) and, for a try no close ended, what ended it (`stop`); the panel words them (`noVerdict`: "provider dropped (socket hang up), no check ran", "you stopped it, no check ran", "died, no check ran"). The rounds endpoint also serves a step's cut-off try. The Audit body: one grid per part (rows = the part's checks in declared order, columns = tries), an errors list under it (one row per red or verdict-less try, the last red try open on load, first 8 lines per open row), and the rounds folded per try; it replaces the boxed fix-attempt view, the stacked step try blocks and the step's single Round table (the `?all=1` endpoint stays). Fix and step tries carry their model-call count (`rounds`) for the fold label. A try no close ended reads `?` in the part header and the map chip as in its grid column; fix-part error lines drop their `close:` prefix and keep file paths; a rubric step's `output judged:` line returns, one faint line per try under the errors list.
22
+
8
23
  ## [0.51.0] - 2026-10-29
9
24
 
10
25
  ### Added
package/README.md CHANGED
@@ -28,6 +28,18 @@ The harness (budget, time, what it may touch) and the judge both sit **outside**
28
28
  <img src="https://raw.githubusercontent.com/hamr0/bareloop/main/docs/media/panel-walkthrough.gif" alt="The bareloop panel: write a job, the runs list, a rubric run waiting for Accept, its Result, Audit and signed Job, then a repo run ready to merge" width="900">
29
29
  </p>
30
30
 
31
+ ## The machine that makes machines
32
+
33
+ Like a CNC machine, bareloop builds the thing that does the work, then lets a gauge it can't touch decide if the work is good. Trust needs four things. Miss one and trust is zero. bareloop has all four.
34
+
35
+ **Intent.** You write the job as plain numbered steps, and a `~` line under each says what success means and what it must never do. Every step gets a check or a written reason why not. You sign before a dollar is spent.
36
+
37
+ **Guide rails, not just guardrails.** Guardrails stop the agent going off the road: a money cap, a time cap, and a read/write fence it can't move. Guide rails keep it on the road: each new worker hears what earlier tries read, searched and changed, diffs included; two misses redraw the plan; past lessons go to the planner; an unclear job gets up to 3 questions, not a guess.
38
+
39
+ **Verification.** The check sits outside the agent's loop: code first, a judge only where code can't decide, and the judge only points while code makes the call. A red goes back with the real error to be fixed, until it's green or out of budget.
40
+
41
+ **Evidence.** Every call, every allowed or blocked read and write, every check result and every cent is recorded. You can audit it in the panel and replay it at $0. Research facts are quoted from saved sources.
42
+
31
43
  ## Two kinds of jobs
32
44
 
33
45
  **Deterministic (code)**: code decides. Tests pass, the linter is quiet, the build exits clean. If no check exists yet, say what you need and the agent builds that check first.
@@ -192,7 +192,7 @@ ships with the grant (`COMPONENT_STRATEGIES` — capability without strategy is
192
192
  | component | verbs | class |
193
193
  |---|---|---|
194
194
  | write | `write` · `edit` | tree writes, judged by the signed `writeScope` fence — `edit` (BA-13) is the anchored exact-once replace and goes through that SAME fence, not a weaker one |
195
- | select | `read` · `grep` · `recall` · `get` · `impact` · `related` · `recent` | read-only; every one is judged as a `read` action by that same fence, so the deny list applies through every door |
195
+ | select | `read` · `grep` · `recall` · `get` · `impact` · `related` · `recent` | read-only; every one is judged as a `read` action by that same fence, so the deny list applies through every door. A walking `grep` is judged per path too (F259): the worker's and the authoring scout's shell tools are built with `gatedShellOptions` (`src/tools.js`: bare-agent `canRead` = the gate's own `allows()`, plus `noFollowSymlinks`), so a root grep skips the arbiter's books instead of reading them |
196
196
  | compress | `compress` · `peek` | read-only (a signature tier; a stash's head/tail) |
197
197
  | isolate | `stash` · `remember` · `forget` | STORE writes (the `.litectx` store, never the tree) — their own gate action types, so a store park can never be counted as a tree write by the F32 `workerWrites` instrument. **Not read-capable** |
198
198
 
@@ -647,6 +647,8 @@ are asked after two failed drafts, about a job line.
647
647
 
648
648
  **Handoff note (per job; hamr 2026-10-28, F253).** When a worker's ask ends, code records the files it READ (the allowed `shell_read` and `ctx_get` calls; scout, step and fix asks all feed it). The NEXT step or fix ask of the same run, a retry of the same step included, gets a note appended to its first user prompt under the fixed heading `== Files earlier workers in this run read (a map only; contents are not included; line ranges as ctx_recall prints them) ==`, one line per file: `- <path> (<N> lines): <symbol> <a>-<b>, ...`. Code writes it, never a model; it names files and carries no content. The symbol map is the LiteCtx index's named chunks, refreshed before the note is built when the worker holds a retrieval verb, and dropped for a plain line count when the index is missing (LiteCtx indexes git-tracked files only) or older than the file. The scout and the drafter are never handed a note. Capped at 8,000 characters (`HANDOFF_CAP`, src/handoff.js): the oldest paths go first with a `[trimmed: N older path(s)]` marker. The arbiter's books (`.smoke`, `.litectx`, the gate audit), `.git`, `.bareloop` and anything outside the job root are never named. The store lives in memory for one leg: a resumed leg starts empty, so its first ask gets no note and later ones do. Each note given is one report-only spine record `{type:'handoff-note', phase, iteration, chars, paths}` (a path COUNT, never a name; catalogue entry `handoff-note` under the spine records). Switch: the signed spec's optional boolean `handoffNote`, absent = on, `false` = off (no note, no record).
649
649
 
650
+ **Carry note (hamr 2026-10-30, M1, F258).** A second note, written by code from the run's own record and appended AFTER the handoff note to the first prompt of every step and fix ask that has something to say (never the scout or the drafter, and not the first ask of a run). It carries facts only, never file content and never a worker's own words, and secrets are masked by the one secret-shape inventory. Under the fixed heading `== What earlier workers in this run did (facts from the record, written by code) ==`: how the last try ended and what it changed; where earlier workers looked (path, line count, times read, line ranges; listings, manifests, docs and config reads are counted in one line, not shown; a file read 3 or more times in a try that ended red with no change carries ` · looked here, no fix made`); searches and what they matched; the edits made in the run (per file, changed-line count and diff hunks, taken from the working tree against the run's start commit, never from the spine); earlier tries folded to one line each. Repeats fold by the learnings Jaccard rule or a shared 6-character prefix. Capped at 3,000 characters, cut in this order: file lines (edited files last), search lines, earlier tries, then diff hunks one edit at a time, oldest edit first (to 12 lines, then to none), the newest edit's hunk last. The state lives in `<workdir>/.smoke/carry/state.json` (an arbiter book the worker's `fs.deny` covers) and a resumed leg loads it. Each note given is one report-only spine record `{type:'carry-note', phase, iteration, chars, capped, sections:{reads,searches,edits,earlier}}` (counts only). Switch: `carryNote` in `config.json`, read once per run exactly like `learningHints`: absent = on, only an explicit `false` turns it off, an unreadable config reads off; off builds no store, writes no state and emits no record, and the worker prompt is the handoff-note-only prompt byte for byte. Library callers of `runJob`/`runPlan` get it only with `carryNote: true` (default off); the shared engine (`src/userrun.js`: panel, CLI and bundle runner) reads the config switch.
651
+
650
652
  **Thinking on (per job; hamr 2026-10-11).** The New job card has a "Thinking on" tick under Model, unticked by default, saved in the SIGNED job as the optional
651
653
  boolean `thinking` (absent = off; an old spec and any unticked job keep the hash they would have had; a ticked job's `jobSpecHash` and `workflowKey` differ). It
652
654
  covers DRAFTING (scout, confirm, author, revise, structure retries) AND the rubric JUDGE, and as the think-everywhere override it makes every WORKER call think too (below). A Reuse card does not
@@ -688,6 +690,8 @@ call (plan, scout, replan, a one-attempt step) carries it on its header line (`p
688
690
  opening precheck) and every part of a run from before the records show no thinking word. `GET /api/runs/:runid/job` adds `thinking` (`thinkingJobText(tick, recorded)`: `on retries`, or `always on` when
689
691
  the signed spec carries the tick (an unreadable tick counts as not ticked), but `—` for a run whose spine holds no `thinking-decision`, never a guess from the tick) for EVERY run; the Job tab draws it as the `Thinking` row, beside Model on one row like the caps. The page types none of these words. The Job tab's "AI's summary" (`GET /api/runs/:id/job` plan `goal`) is only the sentence the person confirmed: for a rubric job (`RUBRIC_GOAL_HEAD`) `confirmedGoalOf` reads it out of the worker brief, none when the brief has no such line; a code job's goal is unchanged.
690
692
 
693
+ **Fix tries in the panel's Audit grid (PRD v1.119).** `replayRun`'s fix part (`parts[].kind === 'fix'`) carries, on each `attempts[]` entry, three fields read from the spine, nothing computed: `source` (`'outer-close'` for the opening close, `'iteration'` for a fix try), `reasons` (the failing stage's own output lines from the close record's `gap`, the `close stage "X" failed:` header line removed, each line as the spine holds it, so still carrying its `close: ` prefix; `[]` when the try passed or no close ended it) and `stop` (`null` when a close ended the try; else `{by: 'escalation'|'run-end', what: <the escalation category or the run-end outcome>, detail: <the escalation's detail, e.g. 'socket hang up'>|null}`: a try that has no verdict). The panel server words them for the page: `attempt.reasons` with only the `close: ` prefix (and, on the first line, the failing stage's name) cut, so a file path stays (a step's reasons are cut further and drop it), and `attempt.noVerdict` (`provider dropped (<detail>), no check ran`, `you stopped it, no check ran`, `died, no check ran`, else `cut off before its checks ran`). `GET /api/runs/:runid/rounds?part=&attempt=` also serves a step's cut-off try as `attempt = <graded tries> + 1` (its `check` is `null`).
694
+
691
695
 
692
696
  **D5 — the mandatory guards are SHOWN and FIXED, and the battery keys off the VERDICT
693
697
  CLASS** (PRD v1.57 §2 — what a battery is FOR is the class of dishonesty that class of
@@ -1939,7 +1943,7 @@ hand them to the one `Loop` that drives worker, scout and planner rounds; the ru
1939
1943
  them once. No price on the row = no `rates` key anywhere = the guesstimate above, byte-identical to
1940
1944
  before. bareloop keeps no price list of its own, ever.
1941
1945
 
1942
- **The provenance is on the record, per round (`rateSource`).** The pinned bare-agent (`^0.52.0`)
1946
+ **The provenance is on the record, per round (`rateSource`).** The pinned bare-agent (`^0.55.0`)
1943
1947
  carries it on every metering payload, and bareloop forwards it VERBATIM (`rateSourceFields`,
1944
1948
  `src/planrun.js`): every API `worker-round` (worker, scout, planner, fix loop) carries it beside
1945
1949
  `pricing` today — `'caller'` when a customer price is on the key's row, else `'tier'`/`'default'`
@@ -2750,6 +2754,10 @@ ask with nothing yet read gets no note and no record, and the scout and the draf
2750
2754
  carries no cost fields (not a spend record) and no verdict. The switch is the signed spec's optional boolean
2751
2755
  `handoffNote`: absent = on, `false` = off (no note, no record). The prose rules are under "Handoff note".
2752
2756
 
2757
+ #### `carry-note` — a carry note handed to a worker ask (`src/carrystore.js`, `src/planrun.js`)
2758
+
2759
+ One report-only spine record per carry note given: `{type:'carry-note', phase, iteration, chars, capped, sections}`. `phase` is `step:<id>` or `fix`; `chars` is the note's length (at most 3,000); `capped` is true when the cap cut anything; `sections` is `{reads, searches, edits, earlier}`, the COUNT of entries shown in each part, never a name or any text. Written right before the ask runs, only for an ask that receives a note; no cost fields, no verdict. Absent entirely when `carryNote` is `false` in `config.json`. The prose rules are under "Carry note".
2760
+
2753
2761
  ### `replayRun(spineEvents, auditEvents?, { runId? })` / `formatReplay(summary)` / `summarizeForAllLine(summary)` / `formatAllLines(entries)` — `src/replay.js`
2754
2762
 
2755
2763
  `summarizeForAllLine(summary)` reduces one `replayRun` summary to one `--all`/directory-
@@ -3960,7 +3968,7 @@ Two files in `~/.config/bareloop/`, outside any repo:
3960
3968
  real one). The CLI (`run-u`, `interview`, `author`) and the panel both use it.
3961
3969
  - **`config.json` — every setting, never a key value.** `readConfig({ home })` /
3962
3970
  `updateConfig(patch, { home })` (atomic tmp + rename, mode 600, unknown fields kept).
3963
- Fields: `learningHints` (true/false; absent = on; see "Cross-run learnings"), `monthlyLimitUsd` (number above 0; absent or `null` = no limit; any other value present
3971
+ Fields: `learningHints` (true/false; absent = on; see "Cross-run learnings"), `carryNote` (true/false; absent = on; see "Carry note"), `monthlyLimitUsd` (number above 0; absent or `null` = no limit; any other value present
3964
3972
  is a `ConfigError`, refused like an unreadable file), `keys.<ENV NAME>` = `{ shape, baseUrl, legacyMaxTokens }` (the Providers rows' settings: an API shape id, the typed Base URL,
3965
3973
  the "old max_tokens" tick), `models.<ENV NAME>` = a list of `{ model, use, inPerM?, outPerM? }` lines (replaced WHOLE on every save; the customer's own price below). Nothing is built
3966
3974
  in: a row with nothing saved is shape `openai-api`, no address, no lines. A secret-shaped
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bareloop",
3
- "version": "0.51.0",
3
+ "version": "0.52.0",
4
4
  "description": "Workflows that earn their own design, with receipts — agent-authored workflows for repeated, long, verifiable jobs that improve across runs under an un-gameable gate.",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -27,7 +27,7 @@
27
27
  "check:lockfile": "node scripts/check-lockfile.mjs"
28
28
  },
29
29
  "dependencies": {
30
- "bare-agent": "^0.52.0",
30
+ "bare-agent": "^0.55.0",
31
31
  "barebrowse": "^0.25.0",
32
32
  "bareguard": "^0.27.0",
33
33
  "litectx": "^0.32.0"
@@ -52,7 +52,7 @@ import { Gate } from 'bareguard';
52
52
  import { LiteCtx } from 'litectx';
53
53
  import { seedListing, GATE_AUDIT_FILE, ARBITER_BOOK_STORES } from './kinds.js';
54
54
  import { TOOL_MENU, WRITE_VERBS, STORE_VERBS } from './job.js';
55
- import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, strategyFor } from './tools.js';
55
+ import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, strategyFor } from './tools.js';
56
56
  import { redactSecrets, SECRET_PATTERNS } from './validate.js';
57
57
  import { extractArtifact, priceOf, scrubRaw, stampRaw, tallyCalls, capStop, callCasualty } from './text.js';
58
58
  import { PROVIDER_TIMEOUT_MS } from './clock.js';
@@ -331,7 +331,7 @@ export async function defaultSurveyor({ workdir, granted, auditPath = join(workd
331
331
  });
332
332
 
333
333
  const names = new Set(granted.map((v) => /** @type {Record<string,string>} */ (TOOL_BY_VERB)[v]));
334
- const shell = createShellTools().tools.filter((/** @type {{name: string}} */ t) => names.has(t.name));
334
+ const shell = createShellTools(gatedShellOptions(gate, workdir)).tools.filter((/** @type {{name: string}} */ t) => names.has(t.name));
335
335
  /** @type {any[]} */
336
336
  let ctxTools = [];
337
337
  if (ctx && [...CTX_TOOLS].some((t) => names.has(t))) {
@@ -0,0 +1,262 @@
1
+ // The carry note: a code-written, facts-only note handed to the next step or fix worker of the SAME run (M1, F258).
2
+ // It says where earlier workers looked, what they searched, what they changed (with the diff hunks) and how earlier tries
3
+ // ended. Never file content, never a worker's own words. PURE render: no I/O; the store that feeds it is src/carrystore.js.
4
+ // Reuses `jaccard` (src/learn.js, the learnings fold rule), `redactSecrets` (src/validate.js, the one secret-shape
5
+ // inventory) and `isHandoffExcluded` (src/handoff.js: arbiter books, .git, .bareloop, outside the root).
6
+ import { jaccard, JACCARD_MIN } from './learn.js';
7
+ import { redactSecrets } from './validate.js';
8
+ import { isHandoffExcluded } from './handoff.js';
9
+
10
+ export const CAP = 3000;
11
+ export const HUNK_LINES = 40;
12
+ export const HUNK_SHOW = 12;
13
+ export const GAP_LINES = 8;
14
+ export const GAP_CHARS = 600;
15
+ export const MATCH_SHOW = 3;
16
+ export const PREFIX_MIN = 6;
17
+ export const CONTAINS_MIN = 4;
18
+ export const HEADING = '== What earlier workers in this run did (facts from the record, written by code) ==';
19
+ export const NO_FIX_MIN_READS = 3;
20
+ export const NO_FIX = ' · looked here, no fix made';
21
+
22
+ /**
23
+ * One record per tool call (no content, no worker words).
24
+ * @typedef {object} Ev
25
+ * @property {number} ask
26
+ * @property {'read'|'get'|'grep'|'recall'} tool
27
+ * @property {string} [path]
28
+ * @property {number|null} [lines]
29
+ * @property {boolean} [dir]
30
+ * @property {boolean} [linesStale]
31
+ * @property {[number,number]|null} [range]
32
+ * @property {string} [pattern]
33
+ * @property {string} [scope]
34
+ * @property {number} [matches]
35
+ * @property {string[]} [firstMatches]
36
+ * @property {string} [query]
37
+ * @property {string[]} [hitPaths]
38
+ * @property {string[]} [hitRanges]
39
+ * @property {boolean} [noFix] the try that made this call ended with no change and a red check
40
+ */
41
+
42
+ /** token set, same tokenisation as src/learn.js flaggedTokens: lowercase [a-z0-9_]{2,} */
43
+ export function tokens(s) { const t = new Set(); for (const m of String(s).toLowerCase().matchAll(/[a-z0-9_]{2,}/g)) t.add(m[0]); return [...t].sort(); }
44
+
45
+ /**
46
+ * Files that are neither source nor test: manifests, lockfiles, docs, config. Dropped from "where looked" unless edited.
47
+ * @param {string} p repo-relative path
48
+ */
49
+ export function isNonSource(p) {
50
+ const base = p.split('/').pop() ?? p;
51
+ if (/^(package(-lock)?\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|bun\.lockb?|Cargo\.(toml|lock)|go\.(mod|sum)|Pipfile(\.lock)?|poetry\.lock|requirements.*\.txt|LICENSE.*|NOTICE.*|CHANGELOG.*|Makefile|Dockerfile)$/i.test(base)) return true;
52
+ if (/\.(md|markdown|mdx|txt|rst|lock|json|jsonc|ya?ml|toml|ini|cfg|conf|env|properties)$/i.test(base)) return true;
53
+ if (/^\.[^/]*(rc|ignore|attributes|editorconfig|nvmrc)$/i.test(base)) return true;
54
+ if (/^(tsconfig|jsconfig|eslint|prettier|babel|jest|vitest|rollup|webpack|vite)[^/]*\.(js|cjs|mjs|ts|json)$/i.test(base) || /\.config\.(js|cjs|mjs|ts)$/i.test(base)) return true;
55
+ return false;
56
+ }
57
+
58
+ /**
59
+ * Fold rule for two search keys (added beside Jaccard): same string prefix of >= PREFIX_MIN chars, or one
60
+ * contains the other (shorter side >= CONTAINS_MIN chars so "a" cannot swallow everything). Case-insensitive.
61
+ * @param {string|undefined} a @param {string|undefined} b
62
+ */
63
+ export function similarName(a, b) {
64
+ if (!a || !b) return false;
65
+ const x = a.toLowerCase(); const y = b.toLowerCase();
66
+ if (x === y) return true;
67
+ let n = 0; while (n < x.length && n < y.length && x[n] === y[n]) n++;
68
+ if (n >= PREFIX_MIN) return true;
69
+ const [s, l] = x.length <= y.length ? [x, y] : [y, x];
70
+ return s.length >= CONTAINS_MIN && l.includes(s);
71
+ }
72
+
73
+ /**
74
+ * Group items (newest first). An item joins the first group whose representative (the newest member) matches:
75
+ * Jaccard >= JACCARD_MIN on key tokens (the learnings rule), or `near(rep, item)`.
76
+ * @template T @param {T[]} items @param {(x:T)=>string} keyOf @param {(a:T,b:T)=>boolean} [near]
77
+ * @returns {{rep:T, members:T[]}[]}
78
+ */
79
+ export function fold(items, keyOf, near) {
80
+ /** @type {{rep:T, members:T[], tk:string[]}[]} */
81
+ const groups = [];
82
+ for (const it of items) {
83
+ const tk = tokens(keyOf(it));
84
+ const g = groups.find((x) => jaccard(x.tk, tk) >= JACCARD_MIN || (!x.tk.length && !tk.length && keyOf(x.rep) === keyOf(it)) || (near ? near(x.rep, it) : false));
85
+ if (g) g.members.push(it); else groups.push({ rep: it, members: [it], tk });
86
+ }
87
+ return groups.map(({ rep, members }) => ({ rep, members }));
88
+ }
89
+
90
+ const q = (v) => (v === undefined || v === null ? '?' : String(v));
91
+ const ok = (p) => p != null && !isHandoffExcluded(p);
92
+
93
+ /** merge overlapping / adjacent [a,b] line ranges, ascending; returns 'a-b' strings */
94
+ export function mergeRanges(rs) {
95
+ const s = rs.map(([a, b]) => [Math.min(a, b), Math.max(a, b)]).sort((x, y) => x[0] - y[0]);
96
+ const out = [];
97
+ for (const [a, b] of s) { const l = out[out.length - 1]; if (l && a <= l[1] + 1) l[1] = Math.max(l[1], b); else out.push([a, b]); }
98
+ return out.map(([a, b]) => `${a}-${b}`);
99
+ }
100
+
101
+ /**
102
+ * @typedef {object} Entry
103
+ * @property {string} text
104
+ * @property {string[]} keys
105
+ * @property {0|1|2} tier 0 = last try's own fact, 1 = edited file, 2 = the rest
106
+ * @property {number} count times read / searched
107
+ * @property {number} recency index of the newest call
108
+ */
109
+
110
+ /** @param {Ev[]} events @param {Set<string>} editedPaths @param {number|undefined} lastAsk */
111
+ function filesSection(events, editedPaths, lastAsk) {
112
+ /** @type {Map<string, {es: Ev[], last: number}>} */
113
+ const byPath = new Map();
114
+ let dropped = 0;
115
+ /** @type {Set<string>} */
116
+ const summarized = new Set();
117
+ events.forEach((e, i) => {
118
+ if (!(e.tool === 'read' || e.tool === 'get') || !ok(e.path)) return;
119
+ const p = /** @type {string} */ (e.path);
120
+ if (e.dir || (isNonSource(p) && !editedPaths.has(p))) { dropped++; summarized.add(`F\0${p}`); return; }
121
+ const g = byPath.get(p) ?? { es: [], last: -1 };
122
+ g.es.push(e); g.last = i; byPath.set(p, g);
123
+ });
124
+ /** @type {Entry[]} */
125
+ const entries = [];
126
+ for (const [p, { es, last }] of byPath) {
127
+ const newest = es[es.length - 1];
128
+ const ranges = mergeRanges(es.filter((e) => e.tool === 'get' && e.range).map((e) => /** @type {[number,number]} */ (e.range)));
129
+ const lc = newest.lines == null ? '' : ` (${newest.lines} lines${newest.linesStale ? ' at run start' : ''})`;
130
+ const edited = editedPaths.has(p);
131
+ const noFix = !edited && es.length >= NO_FIX_MIN_READS && es.some((e) => e.noFix); // hamr: only a file read 3+ times
132
+ const text = `- ${p}${lc} · read ${es.length}x${ranges.length ? ` · lines ${ranges.join(', ')}` : ''}${noFix ? NO_FIX : ''}`;
133
+ const inLast = lastAsk !== undefined && es.some((e) => e.ask === lastAsk);
134
+ entries.push({ text, keys: [`F\0${p}`], tier: inLast ? 0 : edited ? 1 : 2, count: es.length, recency: last });
135
+ }
136
+ entries.sort(rank);
137
+ return { entries, dropped, summarized };
138
+ }
139
+
140
+ /** @param {Entry} a @param {Entry} b */
141
+ function rank(a, b) { return b.count - a.count || b.recency - a.recency; }
142
+
143
+ /** @param {Ev[]} events @param {number|undefined} lastAsk */
144
+ function searchSection(events, lastAsk) {
145
+ /** @type {Entry[]} */
146
+ const out = [];
147
+ const idx = new Map(events.map((e, i) => [e, i]));
148
+ const newestFirst = (/** @type {string} */ t) => events.filter((e) => e.tool === t).reverse();
149
+ const greps = newestFirst('grep').filter((e) => ok(e.scope));
150
+ for (const g of fold(greps, (e) => `${e.scope} ${e.pattern ?? ''}`, (a, b) => a.scope === b.scope && similarName(a.pattern, b.pattern))) {
151
+ const r = g.rep; const k = g.members.length;
152
+ const fm = r.firstMatches === undefined ? '?' : (r.firstMatches.slice(0, MATCH_SHOW).join(', ') + (r.firstMatches.length > MATCH_SHOW ? ` (+${r.firstMatches.length - MATCH_SHOW})` : '')) || 'none';
153
+ out.push({ text: `- grep "${q(r.pattern)}" in ${r.scope} → ${q(r.matches)} matches: ${fm}${k > 1 ? ` · ${k - 1} similar` : ''}`, keys: [`G\0${r.scope}`], tier: lastAsk !== undefined && g.members.some((m) => m.ask === lastAsk) ? 0 : 2, count: k, recency: /** @type {number} */ (idx.get(r)) });
154
+ }
155
+ const recs = newestFirst('recall').filter((e) => e.query != null);
156
+ for (const g of fold(recs, (e) => /** @type {string} */ (e.query), (a, b) => similarName(a.query, b.query))) {
157
+ const r = g.rep; const k = g.members.length;
158
+ const hp = (r.hitPaths ?? []).filter(ok);
159
+ const hr = r.hitRanges === undefined ? '' : ` (${r.hitRanges.slice(0, MATCH_SHOW).join(', ')})`;
160
+ out.push({ text: `- recall "${r.query}" → ${hp.length ? hp.slice(0, 4).join(', ') + (hp.length > 4 ? ` (+${hp.length - 4})` : '') : 'no hits'}${r.hitRanges === undefined && hp.length ? ' · hit ranges ?' : hr}${k > 1 ? ` · ${k - 1} similar` : ''}`, keys: [`Q\0${r.query}`], tier: lastAsk !== undefined && g.members.some((m) => m.ask === lastAsk) ? 0 : 2, count: k, recency: /** @type {number} */ (idx.get(r)) });
161
+ }
162
+ return out.sort(rank);
163
+ }
164
+
165
+ function editLines(e, hunkCap) {
166
+ const head = `- ${e.path}: ${e.lines} lines changed`;
167
+ const hs = e.hunks ?? [];
168
+ const h = hs.slice(0, hunkCap).map((l) => ' ' + l);
169
+ const more = hs.length > hunkCap ? [` (+${hs.length - hunkCap} more diff lines)`] : [];
170
+ return [head, ...(hunkCap > 0 ? h : []), ...(hunkCap > 0 ? more : [])].join('\n');
171
+ }
172
+
173
+ /**
174
+ * Render the carry note. PURE.
175
+ * @param {{lastTry?: {step:string|null, kind:'step'|'fix', n:number|string|undefined, of?:number, ended:string, changed:string[]}|null,
176
+ * lastCheck?: string|null, events: Ev[], edits?: {path:string, lines:number, hunks:string[]}[],
177
+ * earlier?: string[], lastAsk?: number}} notes
178
+ * @param {number} [cap]
179
+ */
180
+ export function render(notes, cap = CAP) {
181
+ const events = (notes.events ?? []).filter((e) => e);
182
+ const edits = (notes.edits ?? []).filter((e) => ok(e.path)).slice().reverse(); // newest first
183
+ const editedPaths = new Set(edits.map((e) => e.path));
184
+ const { entries: files, dropped, summarized } = filesSection(events, editedPaths, notes.lastAsk);
185
+ const searches = searchSection(events, notes.lastAsk);
186
+ const earlierG = fold((notes.earlier ?? []).slice().reverse(), (s) => s);
187
+ /** @type {Entry[]} */
188
+ const earlier = earlierG.map((g, i) => ({ text: '- ' + g.rep + (g.members.length > 1 ? ` · ${g.members.length - 1} similar` : ''), keys: [], tier: 2, count: 0, recency: -i }));
189
+ const rawEntries = events.filter((e) => ['read', 'get', 'grep', 'recall'].includes(e.tool)).length + edits.length + (notes.earlier ?? []).length;
190
+ const foldedEntries = files.length + searches.length + edits.length + earlier.length + (dropped ? 1 : 0);
191
+
192
+ const lt = notes.lastTry;
193
+ const head = [HEADING];
194
+ if (lt) head.push(`Last try: ${lt.kind === 'fix' ? 'fix loop' : `step "${lt.step}"`}, try ${lt.n}${lt.of ? ` of ${lt.of}` : ''}. ${lt.ended} ${lt.changed.length ? `Changed: ${lt.changed.join(', ')}.` : 'Changed nothing.'}`);
195
+ const gapFull = notes.lastCheck ? notes.lastCheck.split('\n').slice(0, GAP_LINES).join('\n') : null;
196
+
197
+ // Cap order (hamr, 2026-10-30): diffs matter most, so they are cut LAST.
198
+ // 1 file lines (edited files protected, dropped last in the section), 2 search lines, 3 earlier tries oldest first,
199
+ // 4 diff hunks, one edit at a time oldest first: to HUNK_SHOW lines each, then to 0 each (newest edit's hunk is the last thing cut).
200
+ // `notes.edits` must be ordered oldest to newest (the store does this: orderEditsByRecency in carrystore.js).
201
+ // The last-try line and the heading are never dropped.
202
+ const dropOrder = (/** @type {Entry[]} */ arr, /** @type {(e: Entry) => boolean} */ protect = () => false) =>
203
+ arr.slice().sort((a, b) => Number(protect(a)) - Number(protect(b)) || b.tier - a.tier || a.count - b.count || a.recency - b.recency);
204
+ const isEditedFile = (/** @type {Entry} */ e) => e.keys.some((k) => k.startsWith('F\0') && editedPaths.has(k.slice(2)));
205
+ /** @type {Set<Entry>} */
206
+ const gone = new Set();
207
+ const goneEdits = new Set();
208
+ const hunkCaps = edits.map(() => HUNK_LINES); let gapCap = GAP_CHARS;
209
+ const gapText = () => (gapFull ? 'Last check said: ' + (gapFull.length > gapCap ? gapFull.slice(0, gapCap) + '…' : gapFull) : null);
210
+ const build = () => {
211
+ const L = [...head];
212
+ const g = gapText(); if (g) L.push(g);
213
+ const kept = (/** @type {Entry[]} */ arr) => arr.filter((x) => !gone.has(x));
214
+ const sec = (/** @type {string} */ title, /** @type {Entry[]} */ arr, /** @type {string[]} */ extra = []) => {
215
+ const k = kept(arr);
216
+ if (!k.length && !extra.length) return;
217
+ L.push(title); k.forEach((x) => L.push(x.text)); extra.forEach((x) => L.push(x));
218
+ if (k.length < arr.length) L.push(`- (+${arr.length - k.length} lower-ranked not shown)`);
219
+ };
220
+ sec(`Where earlier workers looked (${files.length} file${files.length === 1 ? '' : 's'}):`, files, dropped ? [`- +${dropped} listings/config reads not shown`] : []);
221
+ sec('Searches and what they matched:', searches);
222
+ const ke = edits.filter((_, i) => !goneEdits.has(i));
223
+ if (edits.length) { L.push('Edits made in this run:'); edits.forEach((e, i) => { if (!goneEdits.has(i)) L.push(editLines(e, hunkCaps[i])); }); if (ke.length < edits.length) L.push(`- (+${edits.length - ke.length} older not shown)`); } else L.push('Edits made in this run: none');
224
+ sec('Earlier tries (folded):', earlier);
225
+ return L.join('\n');
226
+ };
227
+ let text = build();
228
+ const rawChars = text.length;
229
+ let capped = false;
230
+ /** @type {(() => void)[]} */
231
+ const steps = [
232
+ ...dropOrder(files, isEditedFile).map((e) => () => { gone.add(e); }),
233
+ ...dropOrder(searches).map((e) => () => { gone.add(e); }),
234
+ ...dropOrder(earlier).map((e) => () => { gone.add(e); }),
235
+ // 4: one edit at a time, oldest first (edits[] is newest first, so walk from the end): to HUNK_SHOW, then every edit to 0
236
+ ...edits.map((_, i) => i).reverse().map((i) => () => { hunkCaps[i] = Math.min(hunkCaps[i], HUNK_SHOW); }),
237
+ ...edits.map((_, i) => i).reverse().map((i) => () => { hunkCaps[i] = 0; }), // oldest edit first, newest last
238
+ () => { gapCap = 300; },
239
+ ...edits.map((_, i) => i).reverse().map((i) => () => { goneEdits.add(i); }),
240
+ ];
241
+ let si = 0;
242
+ while (text.length > cap) {
243
+ capped = true;
244
+ if (si >= steps.length) break;
245
+ steps[si++]();
246
+ text = build();
247
+ }
248
+ if (text.length > cap) text = text.slice(0, cap - 1) + '…';
249
+ text = redactSecrets(text);
250
+
251
+ const named = new Set();
252
+ files.filter((x) => !gone.has(x)).forEach((x) => x.keys.forEach((k) => named.add(k)));
253
+ searches.filter((x) => !gone.has(x)).forEach((x) => x.keys.forEach((k) => named.add(k)));
254
+ edits.filter((_, i) => !goneEdits.has(i)).forEach((e) => named.add(`F\0${e.path}`));
255
+ const sections = {
256
+ reads: files.filter((x) => !gone.has(x)).length,
257
+ searches: searches.filter((x) => !gone.has(x)).length,
258
+ edits: edits.length - goneEdits.size,
259
+ earlier: earlier.filter((x) => !gone.has(x)).length,
260
+ };
261
+ return { text, capped, rawChars, rawEntries, foldedEntries, named, summarized, sections };
262
+ }
@@ -0,0 +1,220 @@
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
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.
7
+ import { execFile } from 'node:child_process';
8
+ import { promisify } from 'node:util';
9
+ import { existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
10
+ import { isAbsolute, join, relative, resolve } from 'node:path';
11
+ import { SMOKE_STORE } from './kinds.js';
12
+ import { isHandoffExcluded } from './handoff.js';
13
+ import { redactSecrets } from './validate.js';
14
+ import { render, HUNK_LINES } from './carrynote.js';
15
+ import { readConfig } from './config.js';
16
+
17
+ const exec = promisify(execFile);
18
+ export const CARRY_DIR = 'carry';
19
+ /** the next prompt of a retried step / fix try carries this when the previous ask's check failed */
20
+ export const RED_MARKER = /Previous attempt failed (this step's checks|the verification):/;
21
+
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
+ const lineCount = (/** @type {string} */ s) => (s === '' ? 0 : s.split('\n').length - (s.endsWith('\n') ? 1 : 0));
34
+ const clip = (/** @type {unknown} */ s, n = 200) => redactSecrets(String(s ?? '')).slice(0, n);
35
+
36
+ /**
37
+ * The run's edits from the working tree against the start commit: tracked (git diff) plus untracked (no diff exists).
38
+ * Arbiter books / .git / .bareloop are excluded. Never throws; [] on any git failure.
39
+ * @param {string} workdir @param {string|null} base
40
+ * @returns {Promise<{path: string, lines: number, hunks: string[]}[]>}
41
+ */
42
+ export async function workingEdits(workdir, base) {
43
+ if (!base) return [];
44
+ const g = (/** @type {string[]} */ a) => exec('git', ['-c', 'core.quotepath=false', ...a], { cwd: workdir, maxBuffer: 1 << 26 });
45
+ const out = [];
46
+ try {
47
+ const { stdout: names } = await g(['diff', '--name-only', '-z', base]);
48
+ for (const p of names.split('\0').filter(Boolean)) {
49
+ if (isHandoffExcluded(p)) continue;
50
+ const { stdout } = await g(['diff', '-U1', '--no-color', '--no-ext-diff', base, '--', `:(literal)${p}`]);
51
+ if (/^(Binary files .* differ|GIT binary patch)$/m.test(stdout)) { out.push({ path: p, lines: 0, hunks: ['(binary file changed)'] }); continue; }
52
+ const body = stdout.split('\n').filter((l) => !/^(diff --git|index |--- |\+\+\+ |new file mode|deleted file mode)/.test(l));
53
+ out.push({ path: p, lines: body.filter((l) => /^[+-]/.test(l)).length, hunks: body.slice(0, HUNK_LINES * 2) });
54
+ }
55
+ const { stdout: un } = await g(['ls-files', '--others', '--exclude-standard', '-z']);
56
+ for (const p of un.split('\0').filter(Boolean)) {
57
+ if (isHandoffExcluded(p)) continue;
58
+ try {
59
+ const abs = resolve(workdir, p);
60
+ if (!statSync(abs).isFile() || statSync(abs).size > 262144) continue;
61
+ const text = readFileSync(abs, 'utf8');
62
+ if (text.includes('\0')) continue;
63
+ const ls = text.split('\n'); if (ls.at(-1) === '') ls.pop();
64
+ out.push({ path: p, lines: ls.length, hunks: ls.slice(0, HUNK_LINES * 2).map((l) => '+' + l) });
65
+ } catch { /* unreadable: not shown */ }
66
+ }
67
+ } catch { return out; }
68
+ return out;
69
+ }
70
+
71
+ /**
72
+ * Order edits oldest to newest by when they last changed: a file's recency is the latest settled ask whose `changed`
73
+ * list names it; a file in no `changed` list is oldest. Ties keep their incoming (alphabetical) order. PURE.
74
+ * @param {{path: string}[]} edits @param {{changed?: string[]}[]} settled asks settled so far, oldest first
75
+ */
76
+ export function orderEditsByRecency(edits, settled) {
77
+ const last = (/** @type {string} */ p) => { for (let i = settled.length - 1; i >= 0; i--) if ((settled[i].changed ?? []).includes(p)) return i; return -1; };
78
+ return edits.map((e, k) => ({ e, k, r: last(e.path) })).sort((a, b) => a.r - b.r || a.k - b.k).map((x) => x.e);
79
+ }
80
+
81
+ /**
82
+ * Run-level store. Asks are sequential, so "the current ask" is one counter.
83
+ * @param {{workdir: string, emit: (type: string, rec: any) => void, strikeLimit?: number, resume?: boolean}} o
84
+ */
85
+ export function createCarryStore({ workdir, emit, strikeLimit, resume = false }) {
86
+ workdir = resolve(workdir);
87
+ const dir = join(workdir, SMOKE_STORE, CARRY_DIR);
88
+ const stateFile = join(dir, 'state.json');
89
+ /** @type {string|null} */
90
+ let base = null;
91
+ let n = 0;
92
+ /** @type {any[]} */ let events = [];
93
+ /** @type {any[]} one per WORK ask (step/fix): {n, kind, step, iteration, bounded, red, changed, startSnap} */
94
+ let asks = [];
95
+ let loaded = false;
96
+ 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 */ }
98
+ }
99
+ 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 */ }
101
+ };
102
+ const rel = (/** @type {string} */ p) => (isAbsolute(p) ? relative(workdir, p) : p).split('\\').join('/') || '.';
103
+ const diskLines = (/** @type {string} */ r, /** @type {string|undefined} */ fallback) => { try { return lineCount(readFileSync(resolve(workdir, r), 'utf8')); } catch { return fallback === undefined ? null : lineCount(fallback); } };
104
+
105
+ /** Wrap the worker's read-class tools in place; records tool, args and a result SUMMARY - never file content. @param {{name: string, execute: Function}[]} tools */
106
+ const wrapTools = (tools) => {
107
+ for (const t of tools) {
108
+ const inner = t.execute;
109
+ if (t.name === 'shell_read') {
110
+ t.execute = async (/** @type {any} */ args) => {
111
+ const r = await inner(args);
112
+ try {
113
+ if (typeof r === 'string' && typeof args?.path === 'string') {
114
+ const p = rel(args.path);
115
+ const dirRead = /^dir /.test(r);
116
+ events.push({ ask: n, tool: 'read', path: p, ...(dirRead ? { dir: true } : { lines: diskLines(p, r) }) });
117
+ }
118
+ } catch { /* never break the worker */ }
119
+ return r;
120
+ };
121
+ } else if (t.name === 'ctx_get') {
122
+ t.execute = async (/** @type {any} */ args) => {
123
+ const r = await inner(args);
124
+ try {
125
+ if (typeof r === 'string' && typeof args?.path === 'string' && !/^(ctx_get failed|no chunk|stale)/.test(r)) {
126
+ const p = rel(args.path);
127
+ const a = Number(args.startLine); const b = Number(args.endLine);
128
+ events.push({ ask: n, tool: 'get', path: p, lines: diskLines(p, undefined), range: Number.isFinite(a) && Number.isFinite(b) ? [a, b] : null });
129
+ }
130
+ } catch { /* never break the worker */ }
131
+ return r;
132
+ };
133
+ } else if (t.name === 'shell_grep') {
134
+ t.execute = async (/** @type {any} */ args) => {
135
+ const r = await inner(args);
136
+ try {
137
+ const hits = Array.isArray(r?.hits) ? r.hits : null;
138
+ events.push({
139
+ ask: n, tool: 'grep', pattern: clip(args?.pattern), scope: rel(String(args?.path ?? '.')),
140
+ ...(hits ? { matches: hits.length, firstMatches: hits.slice(0, 3).map((/** @type {any} */ h) => `${rel(String(h.file))}:${h.line}`) } : {}),
141
+ });
142
+ } catch { /* never break the worker */ }
143
+ return r;
144
+ };
145
+ } else if (t.name === 'ctx_recall') {
146
+ t.execute = async (/** @type {any} */ args) => {
147
+ const r = await inner(args);
148
+ try {
149
+ if (typeof r === 'string') {
150
+ /** @type {string[]} */ const hitPaths = []; /** @type {string[]} */ const hitRanges = [];
151
+ for (const line of r.split('\n')) {
152
+ const m = /^([^\t]+)\t[^\t]*\t[^\t]*\tlines (\d+-\d+)$/.exec(line);
153
+ if (m) { hitPaths.push(m[1]); hitRanges.push(`${m[1]} ${m[2]}`); }
154
+ }
155
+ events.push({ ask: n, tool: 'recall', query: clip(args?.query), hitPaths: [...new Set(hitPaths)], hitRanges });
156
+ }
157
+ } catch { /* never break the worker */ }
158
+ return r;
159
+ };
160
+ }
161
+ }
162
+ };
163
+
164
+ const snapOf = (/** @type {{path: string, lines: number}[]} */ edits) => Object.fromEntries(edits.map((e) => [e.path, e.lines]));
165
+ 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.');
167
+
168
+ /**
169
+ * Called at the start of EVERY ask (scout and drafter included, so their finds feed the store).
170
+ * Returns the note text for step/fix asks, '' otherwise.
171
+ * @param {{phase: string, iteration: number|string|undefined, prompt: string}} o
172
+ */
173
+ const beginAsk = async ({ phase, iteration, prompt }) => {
174
+ n++;
175
+ const work = phase === 'fix' || phase.startsWith('step:');
176
+ if (!work) { save(); return ''; }
177
+ const edits = await workingEdits(workdir, base);
178
+ const prev = asks[asks.length - 1];
179
+ 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);
182
+ const now = snapOf(edits);
183
+ prev.changed = [...new Set([...Object.keys(now), ...Object.keys(prev.startSnap)])].filter((p) => now[p] !== prev.startSnap[p]).sort();
184
+ for (const e of events) if (e.ask === prev.n) e.noFix = prev.changed.length === 0 && prev.red;
185
+ }
186
+ const kind = phase === 'fix' ? 'fix' : 'step';
187
+ const step = kind === 'step' ? phase.slice('step:'.length) : null;
188
+ const settled = asks.filter((a) => a.red !== undefined);
189
+ const lt = settled[settled.length - 1];
190
+ const notes = {
191
+ lastTry: lt ? { step: lt.step, kind: lt.kind, n: lt.iteration, of: lt.kind === 'step' ? strikeLimit : undefined, ended: endedOf(lt), changed: lt.changed } : null,
192
+ lastCheck: null, // the failed check's text is already in the prompt today; one copy
193
+ events: events.map((e) => ({ ...e })),
194
+ edits: orderEditsByRecency(edits, settled),
195
+ earlier: settled.slice(0, -1).map((a) => `${tryLabel(a)}: ${endedOf(a)} ${a.changed.length ? `Changed ${a.changed.join(', ')}.` : 'Changed nothing.'}`),
196
+ lastAsk: lt ? lt.n : undefined,
197
+ };
198
+ asks.push({ n, kind, step, iteration, startSnap: snapOf(edits) });
199
+ const hasAny = notes.events.length || edits.length || notes.earlier.length || notes.lastTry;
200
+ if (!hasAny) { save(); return ''; }
201
+ const r = render(/** @type {any} */ (notes));
202
+ emit('carry-note', { phase, iteration, chars: r.text.length, capped: r.capped, sections: r.sections }); // counts only
203
+ save();
204
+ return r.text;
205
+ };
206
+
207
+ /** Called when the ask returns (finally). @param {{bounded?: {iteration: any, cause: string}|undefined, iteration: any, rounds: number}} o */
208
+ const endAsk = ({ bounded, iteration, rounds }) => {
209
+ const a = asks[asks.length - 1];
210
+ if (!a || a.n !== n) return;
211
+ if (bounded && bounded.iteration === iteration) {
212
+ a.boundedText = bounded.cause === 'rounds' ? `Ran out of calls (${rounds} of ${rounds}).`
213
+ : bounded.cause === 'wall' ? 'Stopped by the wall clock.'
214
+ : bounded.cause === 'denied' ? 'Stopped after repeated denied calls.' : 'Output cut at the token limit.';
215
+ }
216
+ save();
217
+ };
218
+
219
+ return { wrapTools, beginAsk, endAsk, setBase: (/** @type {string|null|undefined} */ b) => { if (!base && b) base = b; }, loaded: () => loaded, _state: () => ({ n, events, asks, base }) };
220
+ }