bareloop 0.51.0 → 0.53.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,40 @@ 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.53.0] - 2026-11-02
9
+
10
+ ### Added
11
+
12
+ - **EXPERIMENTAL, default off: a first-read map (`readMap`, docs/logs/MAP-PREREG.md).** With the signed spec field `readMap: true`, the first `shell_read` of a 200+ line non-test file in an ask returns a map of its named parts (`symbol start-end`, openable with `ctx_get`) instead of file bytes; the second read of that path is today's read, and the file is never marked delivered by the map. No `ctx_get` in the step's grant, no index or no named chunk: today's read plus a report-only `read-map-skip` record. One report-only `read-map` spine record per map. Absent = off and byte-identical; the switch enters the signed hash only when present. Not proven: the pre-registered battery decides. Tested 2026-10-31: FAIL, stays off (F263).
13
+
14
+ ### Changed
15
+
16
+ - **The carry memo is always on: no switch (hamr 2026-11-01).** The `carryNote` key in `config.json` is retired (ignored on read, dropped on any config write), a job spec's `handoffNote` is still accepted and hashed (old signed specs verify) but has no effect, and `runJob`/`runPlan` no longer take a `carryNote` option. A live OLD-vs-NEW check of the fold on one job found no regression (F264).
17
+ - **The handoff note is folded into the carry memo.** One block (the memo's files-read lines now carry the function line ranges, dropped first at the cap) (the switch this fold left behind, `carryNote`, was removed the next day: see above); a job spec's `handoffNote` is legacy; the `handoff-note` spine record is no longer written (old spines replay unchanged).
18
+
19
+ - **Seed note ON by default, part of the carry-over memory (`seedNote`, F262, docs/logs/SEEDGAP-PREREG.md).** The planner's first draft (its own block) and, through the carry memo's "Earlier failures (folded):" section labelled `at start`, every step and fix worker are told, read-only, what the job's own `count-not-worse` check said on the untouched tree ("At start, the job's own check said:" plus that stage's text, secret-masked). Absent = on; `seedNote: false` turns it off and is byte-identical to before; the switch enters the signed hash only when present, so old signed jobs get it with no re-sign. Result: on the big-file job 3 of 3 ON runs wrote to the culprit file vs 1 of 3 OFF (n=3, one job, one patient; carry note on in all six). The battery tested planner + first worker of step 1; the shipped delivery to workers is the memo (every worker; seen live once, run u-mvwok8nk, all 4 memos carried it).
20
+
21
+ - **The carry note is bigger and says more about failures (F261).** Its cap rises from 3,000 to 12,000 characters (7 of 8 notes in a live run were capped). Each try line now says how the try ended and what its check said ("Ran out of calls (24 of 24). Its check failed."; "Check not run." when no check ran). A new "Earlier failures (folded):" section, after "Earlier tries (folded):", carries each failed check's whole text (secrets masked, kept in `state.json` so a resume has it), folded by the learnings rule with the newest member shown; the last try's failure is left out only when that try failed (its retry prompt already carries it); a failure from a try that was later passed stays. Over the cap the order is files, searches, earlier tries, earlier failures (oldest group first), then diff hunks. The `carry-note` spine record's `sections` gains a `failures` count.
22
+
23
+ ### Fixed
24
+
25
+ - **The carry note no longer says an earlier try's check passed when it failed or never ran.** A try's outcome was guessed from whether the NEXT prompt carried the retry marker, so a step's last red try followed by a replan or a new step (no marker) read "Its check passed." The engine now hands the store the check result it already knows (green, red, or unknown on an instrument fault) as each try is judged; a try with no result says "No check result was recorded for it." Note shape and the OFF path are unchanged.
26
+
27
+ ## [0.52.0] - 2026-10-30
28
+
29
+ ### Added
30
+
31
+ - **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`.
32
+
33
+ ### Security
34
+
35
+ - **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.
36
+
37
+ ### Changed
38
+
39
+ - **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.
40
+ - **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.
41
+
8
42
  ## [0.51.0] - 2026-10-29
9
43
 
10
44
  ### 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.
@@ -159,7 +159,9 @@ minting claim, or the shell-owned retry cap — all unknown-field reds.
159
159
  | `closeTimeoutMs` | optional integer ms `>= CLOSE_TIMEOUT_FLOOR_MS` (120,000 — hamr's arbiter floor, 2026-09-07) | PRD item 27/M3's SIGNED override for the close's own per-stage wall-clock cap. Absent (the normal case): the run autosets it from a $0 seed timing pass — `max(FLOOR, K × slowest measured stage)`, `K = 5` (hamr, 2026-09-07: "2 and 5 are fine"). Present: the operator's own number wins outright and may legally sit ABOVE *or below* the autoset estimate (the rates-passthrough shape, F113 — never tighten-only). Arbiter territory exactly like `budgetUsd`/`maxWallMs`/`close[].sha256`: the authoring pipeline's `assembleSpec` refuses a draft carrying it |
160
160
  | `model` | optional non-empty string, the exact model id of a line ticked in Settings > Providers | the WORKER's model. A job carries its own model (P8: bareloop has no default); a spec signed before that (no `model`, perhaps no `baseUrl`) runs on the line `--model <id>` names (plus `--provider <KEY>` when two keys tick it) — the signed hash is untouched. Present, it wins over a `--model` flag outright, and a flag naming a different id is refused (`resolveWorkerModel`, `src/job.js`) rather than silently overridden. Part of the signed hash like every other field. Worker only — the JUDGE's model comes from the `judge` row below, which DEFAULTS to this same worker model |
161
161
  | `thinking` | optional boolean | the job's "Thinking on" tick (P8): absent = off, and an old spec keeps the hash it always had; present it is signed like `model`. Covers DRAFTING and the rubric JUDGE, and makes every WORKER call think (see "Thinking on" below) |
162
- | `handoffNote` | optional boolean | the handoff note switch: absent = ON, only an explicit `false` turns it off; an old spec keeps the hash it always had, and a present value is signed (the switch enters `jobSpecHash` and `workflowKey`; the note's text never does). Not shown in the panel. See "Handoff note" below |
162
+ | `handoffNote` | optional boolean | LEGACY and IGNORED (the handoff note was folded into the carry memo, which is always on): either value has no effect. Still accepted and signed so an old spec keeps its hash; new drafts never write it. Not shown in the panel. See "Carry note" below |
163
+ | `seedNote` | optional boolean | Default ON (part of the carry-over memory): absent = on, only `false` turns it off; on, it hands the planner's first draft (its own block) and, through the carry memo's "Earlier failures (folded):" section labelled `at start`, every step/fix worker what the job's own `count-not-worse` check said on the untouched tree (see "Seed note" below). An old spec keeps the hash it always had; a present value is signed (the switch enters `jobSpecHash` and `workflowKey`; the text never does). Not shown in the panel |
164
+ | `readMap` | optional boolean | EXPERIMENTAL, default OFF: absent = off, `true` makes the FIRST `shell_read` of a file of 200+ lines (not a test file) in an ask return a map of the file's named parts instead of its bytes; the second read of that path in the ask is today's read (see "First-read map" below). Only `true`/`false` are legal (anything else is an `invalid-value` red). An old spec keeps the hash it always had; a present value is signed. Not shown in the panel |
163
165
  | `judge` | optional `{provider, model}`, both non-empty; `provider` from the `PROVIDERS` menu | the signed JUDGE override (PRD item 32). Absent, the judge resolves to this job's own `provider`/`model` (`resolveJudge`) — which is what lets a non-Anthropic job judge without a second account. Present, it pins a judge deliberately different from the worker (an independent reader). Both halves are required together: a judge with a provider and no model is an identity nobody signed. Part of the signed hash, so changing it kills the signature and forces recalibration. Unknown nested keys red — no smuggling level exists in a signed spec. The drafting agent cannot express it: naming your own examiner is arbiter territory |
164
166
  | `writeScope` | array of contained globs | the operator's outer fence; the plan's own scopes must fit inside it, same containment code |
165
167
  | `steps` | RETIRED | operator-authored `steps[]` was deleted (PRD v1.32); a spec carrying it reds `shape-retired:steps` by name rather than half-running |
@@ -192,7 +194,7 @@ ships with the grant (`COMPONENT_STRATEGIES` — capability without strategy is
192
194
  | component | verbs | class |
193
195
  |---|---|---|
194
196
  | 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 |
197
+ | 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
198
  | compress | `compress` · `peek` | read-only (a signature tier; a stash's head/tail) |
197
199
  | 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
200
 
@@ -645,7 +647,12 @@ plan with the first leg's spend carried as prior spend and `offerQuestions: fals
645
647
  plan's open questions) are a separate, unchanged mechanism: they are asked before drafting, about the plan; try-3 questions
646
648
  are asked after two failed drafts, about a job line.
647
649
 
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).
650
+
651
+ **Seed note (default ON; docs/logs/SEEDGAP-PREREG.md).** Code writes, from the preflight's own stage results (no extra close run, no model call, no verdict change), a block headed `At start, the job's own check said:` followed by the gap text of each close stage that was red at seed AND is a `count-not-worse` stage (the stage's declared kind, never its name; a command close has none). `command-exit` text (capped, cannot carry the failure) and `changed-from-seed` text are never used. The text is passed as the stage rendered it, run through the one secret mask. It goes to the planner's first draft (after the hints, before the survey) as its own block, and to EVERY step and fix worker as the oldest entry of the carry memo's "Earlier failures (folded):" section, labelled `at start` (persisted in the carry state, so a resume keeps it; the memo's "leave out the last try's failure" rule never applies to it because it is never in a prompt gap; it folds with a later identical failure by the usual rule, labelled `at start` only when it is the newest member). Never the scout. **Delivery changed AFTER the battery:** the pre-registered battery tested planner + first worker of step 1 (hand-delivered block); what ships is planner + the memo to every worker; the memo form was seen live once (F262, run u-mvwok8nk, 2026-10-31: all four workers carried the `at start` entry). No qualifying stage red at seed = no block, no record. Switch: the signed spec's optional boolean `seedNote`, absent = on, `false` = off; OFF is byte-identical to a build without the feature. The planner use is one report-only spine record (catalogue entry `seed-note`); the worker side is counted in the `carry-note` record's `sections.failures`. The planted-marker (culprit-leak) scan of the prereg is an experiment-side check, not product code.
652
+
653
+ **First-read map (EXPERIMENTAL, default off; docs/logs/MAP-PREREG.md).** With `readMap: true` the read shim answers the FIRST `shell_read` of a file in an ask with a map, not the file: header `<path> (<N> lines) — map, not the file:`, one line per named chunk of the LiteCtx index as `symbol start-end` (0-based inclusive, the space `ctx_get` takes; a chunk that contains another named chunk is left out), and a footer saying how to open a part with `ctx_get` or read again for the whole file. Capped at 4,000 characters with a `+N more` line. Only files of 200+ lines that are not test files (`test/`, `tests/`, `__tests__/` segment or `*.test.*`/`*.spec.*` name). The map delivers nothing, so the shim never marks the file delivered; the second read of the same path in the same ask (a new ask resets) is today's read, paged as before. No map, today's read plus a report-only `read-map-skip` record, when: the worker's step lacks `ctx_get` (`no-ctx_get`), the read shim is off (`shim-off`), the file has no index node (`no-index`) or no named chunk (`no-named-chunks`), or the index is older than the file (`stale-index`). The index is built at run start when the switch is on. Off is byte-identical to a build without it.
654
+
655
+ **Carry note (hamr 2026-10-30, M1, F258).** The one note (the former separate handoff note is folded in, 2026-10-31), written by code from the run's own record and appended to the first prompt of every step and fix ask that has something to say (never the scout or the drafter; the first step ask of a run has something to say only when the seed note found a start failure, which rides in as the `at start` entry). 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 (the bound, if any, then its check result: "Its check failed.", "Its check passed.", "Check not run.") and what it changed; where earlier workers looked (path, line count, times read, line ranges, and ` · functions: <name> <a>-<b>, ...` from the LiteCtx index's named chunks, kept only while the index is fresh for that file, refreshed before each note; 500 characters per file; 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, then `Earlier failures (folded):` (each earlier failed check's whole text, masked, indented 4 spaces under `- step "x" try 1 · N similar:`; the last try's failure is left out only when that try failed, since its retry prompt carries it; a failure from a try that was later passed stays). Repeats fold by the learnings Jaccard rule or a shared 6-character prefix. Capped at 12,000 characters (`CAP`, src/carrynote.js), cut in this order: the function ranges on every file line first, then file lines (edited files last), search lines, earlier tries, earlier failures (oldest group first, whole group), 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,failures}}` (counts only). Always on, no switch (hamr 2026-11-01): the `carryNote` key in `config.json` is retired (ignored on read, dropped on any config write), a job spec's `handoffNote` is accepted and hashed but has no effect, and `runJob`/`runPlan` take no `carryNote` option; every run builds the store, writes its state and emits its records.
649
656
 
650
657
  **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
658
  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
@@ -688,6 +695,8 @@ call (plan, scout, replan, a one-attempt step) carries it on its header line (`p
688
695
  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
696
  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
697
 
698
+ **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`).
699
+
691
700
 
692
701
  **D5 — the mandatory guards are SHOWN and FIXED, and the battery keys off the VERDICT
693
702
  CLASS** (PRD v1.57 §2 — what a battery is FOR is the class of dishonesty that class of
@@ -1939,7 +1948,7 @@ hand them to the one `Loop` that drives worker, scout and planner rounds; the ru
1939
1948
  them once. No price on the row = no `rates` key anywhere = the guesstimate above, byte-identical to
1940
1949
  before. bareloop keeps no price list of its own, ever.
1941
1950
 
1942
- **The provenance is on the record, per round (`rateSource`).** The pinned bare-agent (`^0.52.0`)
1951
+ **The provenance is on the record, per round (`rateSource`).** The pinned bare-agent (`^0.55.0`)
1943
1952
  carries it on every metering payload, and bareloop forwards it VERBATIM (`rateSourceFields`,
1944
1953
  `src/planrun.js`): every API `worker-round` (worker, scout, planner, fix loop) carries it beside
1945
1954
  `pricing` today — `'caller'` when a customer price is on the key's row, else `'tier'`/`'default'`
@@ -2740,15 +2749,23 @@ unreferenced loose objects are left. Gitignored files inside the fence are seen
2740
2749
  changed nothing in scope emits nothing, and a failed capture emits `gitError` with empty lists: a record,
2741
2750
  never a verdict, and it never throws. No prompt carries it; the learnings cards read it ("What changed").
2742
2751
 
2743
- #### `handoff-note` — a note handed to a worker ask (`src/handoff.js`, `src/planrun.js`)
2752
+ #### `handoff-note` — LEGACY, no longer written (the handoff note was folded into the carry memo)
2753
+
2754
+ Old spines carry `{type:'handoff-note', phase, iteration, chars, paths}` records; nothing in the library reads them (replay, the Audit and the analysis ignore the type), so old runs replay unchanged. A new run writes a `carry-note` record instead (below).
2755
+
2756
+ #### `seed-note` — the seed note handed to the planner (the worker side is the carry memo) (`src/seednote.js`, `src/planrun.js`)
2757
+
2758
+ One report-only spine record per use: `{type:'seed-note', to, chars, stages}`. `to` is `'planner'` (the first draft, once; the worker side is the `carry-note` record's `sections.failures`); `chars` is the block's length; `stages` is the list of stage NAMES whose
2759
+ text it carries. Counts and names only, never the text. No cost fields, no verdict. Written only when the signed spec's
2760
+ `seedNote` is not `false` and a `count-not-worse` stage was red at seed. The prose rules are under "Seed note".
2761
+
2762
+ #### `read-map` and `read-map-skip` — the first-read map (`src/readshim.js`, `src/planrun.js`)
2763
+
2764
+ Report-only, counts and a reason, never text, no cost fields, not rounds (spend and analysis readers ignore them). `{type:'read-map', path, lines, symbols, chars}` is one per map served; `{type:'read-map-skip', path, reason}` is one per fallback (`reason` as listed under "First-read map"; the run-level `shim-off` skip carries no `path`). Written only when the signed spec's `readMap` is `true`.
2765
+
2766
+ #### `carry-note` — a carry note handed to a worker ask (`src/carrystore.js`, `src/planrun.js`)
2744
2767
 
2745
- One report-only spine record per handoff note given: `{type:'handoff-note', phase, iteration, chars, paths}`.
2746
- `phase` is `step:<id>` or `fix`; `iteration` is the round iteration at the ask; `chars` is the note's length in
2747
- characters (at most 8,000); `paths` is a COUNT of the files the note lists after any trimming, never a name.
2748
- `runPlan` writes it right before the ask runs, once per step or close-fix ask that actually receives a note: an
2749
- ask with nothing yet read gets no note and no record, and the scout and the drafter are never handed one. It
2750
- carries no cost fields (not a spend record) and no verdict. The switch is the signed spec's optional boolean
2751
- `handoffNote`: absent = on, `false` = off (no note, no record). The prose rules are under "Handoff note".
2768
+ 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 12,000); `capped` is true when the cap cut anything; `sections` is `{reads, searches, edits, earlier, failures}`, 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 only for an ask that has no note to give; there is no switch (the carry memo is always on). The prose rules are under "Carry note".
2752
2769
 
2753
2770
  ### `replayRun(spineEvents, auditEvents?, { runId? })` / `formatReplay(summary)` / `summarizeForAllLine(summary)` / `formatAllLines(entries)` — `src/replay.js`
2754
2771
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bareloop",
3
- "version": "0.51.0",
3
+ "version": "0.53.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,288 @@
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 `isCarryExcluded` (below: arbiter books, .git, .bareloop, outside the root).
6
+ import { jaccard, JACCARD_MIN } from './learn.js';
7
+ import { redactSecrets } from './validate.js';
8
+ import { isAbsolute } from 'node:path';
9
+ import { isArbiterBook } from './kinds.js';
10
+
11
+ export const CAP = 12000;
12
+
13
+ /**
14
+ * Is this repo-relative path off limits to the memo: outside the job root, an arbiter book (the one list,
15
+ * `isArbiterBook`: .smoke — spine, attempt-diff, bridges — .litectx, the gate audit), or inside `.git` / `.bareloop`.
16
+ * @param {string} rel
17
+ */
18
+ export function isCarryExcluded(rel) {
19
+ if (rel === '' || rel === '..' || rel.startsWith('../') || isAbsolute(rel)) return true;
20
+ if (isArbiterBook(rel) !== null) return true;
21
+ return rel.split('/').some((seg) => seg === '.git' || seg === '.bareloop');
22
+ }
23
+ export const HUNK_LINES = 40;
24
+ export const HUNK_SHOW = 12;
25
+ export const GAP_LINES = 8;
26
+ export const GAP_CHARS = 600;
27
+ export const MATCH_SHOW = 3;
28
+ export const PREFIX_MIN = 6;
29
+ export const CONTAINS_MIN = 4;
30
+ export const HEADING = '== What earlier workers in this run did (facts from the record, written by code) ==';
31
+ export const NO_FIX_MIN_READS = 3;
32
+ export const NO_FIX = ' · looked here, no fix made';
33
+
34
+ /**
35
+ * One record per tool call (no content, no worker words).
36
+ * @typedef {object} Ev
37
+ * @property {number} ask
38
+ * @property {'read'|'get'|'grep'|'recall'} tool
39
+ * @property {string} [path]
40
+ * @property {number|null} [lines]
41
+ * @property {boolean} [dir]
42
+ * @property {boolean} [linesStale]
43
+ * @property {[number,number]|null} [range]
44
+ * @property {string} [pattern]
45
+ * @property {string} [scope]
46
+ * @property {number} [matches]
47
+ * @property {string[]} [firstMatches]
48
+ * @property {string} [query]
49
+ * @property {string[]} [hitPaths]
50
+ * @property {string[]} [hitRanges]
51
+ * @property {boolean} [noFix] the try that made this call ended with no change and a red check
52
+ */
53
+
54
+ /** token set, same tokenisation as src/learn.js flaggedTokens: lowercase [a-z0-9_]{2,} */
55
+ 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(); }
56
+
57
+ /**
58
+ * Files that are neither source nor test: manifests, lockfiles, docs, config. Dropped from "where looked" unless edited.
59
+ * @param {string} p repo-relative path
60
+ */
61
+ export function isNonSource(p) {
62
+ const base = p.split('/').pop() ?? p;
63
+ 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;
64
+ if (/\.(md|markdown|mdx|txt|rst|lock|json|jsonc|ya?ml|toml|ini|cfg|conf|env|properties)$/i.test(base)) return true;
65
+ if (/^\.[^/]*(rc|ignore|attributes|editorconfig|nvmrc)$/i.test(base)) return true;
66
+ 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;
67
+ return false;
68
+ }
69
+
70
+ /**
71
+ * Fold rule for two search keys (added beside Jaccard): same string prefix of >= PREFIX_MIN chars, or one
72
+ * contains the other (shorter side >= CONTAINS_MIN chars so "a" cannot swallow everything). Case-insensitive.
73
+ * @param {string|undefined} a @param {string|undefined} b
74
+ */
75
+ export function similarName(a, b) {
76
+ if (!a || !b) return false;
77
+ const x = a.toLowerCase(); const y = b.toLowerCase();
78
+ if (x === y) return true;
79
+ let n = 0; while (n < x.length && n < y.length && x[n] === y[n]) n++;
80
+ if (n >= PREFIX_MIN) return true;
81
+ const [s, l] = x.length <= y.length ? [x, y] : [y, x];
82
+ return s.length >= CONTAINS_MIN && l.includes(s);
83
+ }
84
+
85
+ /**
86
+ * Group items (newest first). An item joins the first group whose representative (the newest member) matches:
87
+ * Jaccard >= JACCARD_MIN on key tokens (the learnings rule), or `near(rep, item)`.
88
+ * @template T @param {T[]} items @param {(x:T)=>string} keyOf @param {(a:T,b:T)=>boolean} [near]
89
+ * @returns {{rep:T, members:T[]}[]}
90
+ */
91
+ export function fold(items, keyOf, near) {
92
+ /** @type {{rep:T, members:T[], tk:string[]}[]} */
93
+ const groups = [];
94
+ for (const it of items) {
95
+ const tk = tokens(keyOf(it));
96
+ 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));
97
+ if (g) g.members.push(it); else groups.push({ rep: it, members: [it], tk });
98
+ }
99
+ return groups.map(({ rep, members }) => ({ rep, members }));
100
+ }
101
+
102
+ const q = (v) => (v === undefined || v === null ? '?' : String(v));
103
+ const ok = (p) => p != null && !isCarryExcluded(p);
104
+
105
+ /** merge overlapping / adjacent [a,b] line ranges, ascending; returns 'a-b' strings */
106
+ export function mergeRanges(rs) {
107
+ const s = rs.map(([a, b]) => [Math.min(a, b), Math.max(a, b)]).sort((x, y) => x[0] - y[0]);
108
+ const out = [];
109
+ 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]); }
110
+ return out.map(([a, b]) => `${a}-${b}`);
111
+ }
112
+
113
+ /**
114
+ * @typedef {object} Entry
115
+ * @property {string} text
116
+ * @property {string[]} keys
117
+ * @property {0|1|2} tier 0 = last try's own fact, 1 = edited file, 2 = the rest
118
+ * @property {number} count times read / searched
119
+ * @property {number} recency index of the newest call
120
+ * @property {string} [fn] the file's function line ranges (` · functions: a 1-5, b 7-9`), the FIRST thing the cap drops
121
+ */
122
+
123
+ /** @param {Ev[]} events @param {Set<string>} editedPaths @param {number|undefined} lastAsk @param {Record<string, string>} fnRanges */
124
+ function filesSection(events, editedPaths, lastAsk, fnRanges) {
125
+ /** @type {Map<string, {es: Ev[], last: number}>} */
126
+ const byPath = new Map();
127
+ let dropped = 0;
128
+ /** @type {Set<string>} */
129
+ const summarized = new Set();
130
+ events.forEach((e, i) => {
131
+ if (!(e.tool === 'read' || e.tool === 'get') || !ok(e.path)) return;
132
+ const p = /** @type {string} */ (e.path);
133
+ if (e.dir || (isNonSource(p) && !editedPaths.has(p))) { dropped++; summarized.add(`F\0${p}`); return; }
134
+ const g = byPath.get(p) ?? { es: [], last: -1 };
135
+ g.es.push(e); g.last = i; byPath.set(p, g);
136
+ });
137
+ /** @type {Entry[]} */
138
+ const entries = [];
139
+ for (const [p, { es, last }] of byPath) {
140
+ const newest = es[es.length - 1];
141
+ const ranges = mergeRanges(es.filter((e) => e.tool === 'get' && e.range).map((e) => /** @type {[number,number]} */ (e.range)));
142
+ const lc = newest.lines == null ? '' : ` (${newest.lines} lines${newest.linesStale ? ' at run start' : ''})`;
143
+ const edited = editedPaths.has(p);
144
+ const noFix = !edited && es.length >= NO_FIX_MIN_READS && es.some((e) => e.noFix); // hamr: only a file read 3+ times
145
+ const text = `- ${p}${lc} · read ${es.length}x${ranges.length ? ` · lines ${ranges.join(', ')}` : ''}${noFix ? NO_FIX : ''}`;
146
+ const inLast = lastAsk !== undefined && es.some((e) => e.ask === lastAsk);
147
+ entries.push({ text, keys: [`F\0${p}`], tier: inLast ? 0 : edited ? 1 : 2, count: es.length, recency: last, ...(fnRanges[p] ? { fn: fnRanges[p] } : {}) });
148
+ }
149
+ entries.sort(rank);
150
+ return { entries, dropped, summarized };
151
+ }
152
+
153
+ /** @param {Entry} a @param {Entry} b */
154
+ function rank(a, b) { return b.count - a.count || b.recency - a.recency; }
155
+
156
+ /** @param {Ev[]} events @param {number|undefined} lastAsk */
157
+ function searchSection(events, lastAsk) {
158
+ /** @type {Entry[]} */
159
+ const out = [];
160
+ const idx = new Map(events.map((e, i) => [e, i]));
161
+ const newestFirst = (/** @type {string} */ t) => events.filter((e) => e.tool === t).reverse();
162
+ const greps = newestFirst('grep').filter((e) => ok(e.scope));
163
+ for (const g of fold(greps, (e) => `${e.scope} ${e.pattern ?? ''}`, (a, b) => a.scope === b.scope && similarName(a.pattern, b.pattern))) {
164
+ const r = g.rep; const k = g.members.length;
165
+ const fm = r.firstMatches === undefined ? '?' : (r.firstMatches.slice(0, MATCH_SHOW).join(', ') + (r.firstMatches.length > MATCH_SHOW ? ` (+${r.firstMatches.length - MATCH_SHOW})` : '')) || 'none';
166
+ 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)) });
167
+ }
168
+ const recs = newestFirst('recall').filter((e) => e.query != null);
169
+ for (const g of fold(recs, (e) => /** @type {string} */ (e.query), (a, b) => similarName(a.query, b.query))) {
170
+ const r = g.rep; const k = g.members.length;
171
+ const hp = (r.hitPaths ?? []).filter(ok);
172
+ const hr = r.hitRanges === undefined ? '' : ` (${r.hitRanges.slice(0, MATCH_SHOW).join(', ')})`;
173
+ 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)) });
174
+ }
175
+ return out.sort(rank);
176
+ }
177
+
178
+ function editLines(e, hunkCap) {
179
+ const head = `- ${e.path}: ${e.lines} lines changed`;
180
+ const hs = e.hunks ?? [];
181
+ const h = hs.slice(0, hunkCap).map((l) => ' ' + l);
182
+ const more = hs.length > hunkCap ? [` (+${hs.length - hunkCap} more diff lines)`] : [];
183
+ return [head, ...(hunkCap > 0 ? h : []), ...(hunkCap > 0 ? more : [])].join('\n');
184
+ }
185
+
186
+ /**
187
+ * Render the carry note. PURE.
188
+ * @param {{lastTry?: {step:string|null, kind:'step'|'fix', n:number|string|undefined, of?:number, ended:string, changed:string[]}|null,
189
+ * lastCheck?: string|null, events: Ev[], edits?: {path:string, lines:number, hunks:string[]}[],
190
+ * earlier?: string[], failures?: {label:string, text:string}[], lastAsk?: number,
191
+ * fnRanges?: Record<string, string>}} notes `fnRanges`: path to its function line ranges (`a 1-5, b 7-9`), made by the store from the index
192
+ * @param {number} [cap]
193
+ */
194
+ export function render(notes, cap = CAP) {
195
+ const events = (notes.events ?? []).filter((e) => e);
196
+ const edits = (notes.edits ?? []).filter((e) => ok(e.path)).slice().reverse(); // newest first
197
+ const editedPaths = new Set(edits.map((e) => e.path));
198
+ const { entries: files, dropped, summarized } = filesSection(events, editedPaths, notes.lastAsk, notes.fnRanges ?? {});
199
+ const searches = searchSection(events, notes.lastAsk);
200
+ const earlierG = fold((notes.earlier ?? []).slice().reverse(), (s) => s);
201
+ /** @type {Entry[]} */
202
+ 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 }));
203
+ // failed checks' whole texts, oldest first in; folded newest first with the SAME rule, the newest member represents its group
204
+ const failG = fold((notes.failures ?? []).slice().reverse(), (f) => f.text);
205
+ /** @type {Entry[]} */
206
+ const failures = failG.map((g, i) => ({ text: `- ${g.rep.label}${g.members.length > 1 ? ` · ${g.members.length - 1} similar` : ''}:\n` + String(g.rep.text).split('\n').map((l) => ' ' + l).join('\n'), keys: [], tier: 2, count: 0, recency: -i }));
207
+ const rawEntries = events.filter((e) => ['read', 'get', 'grep', 'recall'].includes(e.tool)).length + edits.length + (notes.earlier ?? []).length + (notes.failures ?? []).length;
208
+ const foldedEntries = files.length + searches.length + edits.length + earlier.length + failures.length + (dropped ? 1 : 0);
209
+
210
+ const lt = notes.lastTry;
211
+ const head = [HEADING];
212
+ 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.'}`);
213
+ const gapFull = notes.lastCheck ? notes.lastCheck.split('\n').slice(0, GAP_LINES).join('\n') : null;
214
+
215
+ // Cap order (hamr, 2026-10-30): diffs matter most, so they are cut LAST.
216
+ // 1 file lines (edited files protected, dropped last in the section), 2 search lines, 3 earlier tries oldest first,
217
+ // 3b earlier failures, the OLDEST group first (whole group), then
218
+ // 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).
219
+ // `notes.edits` must be ordered oldest to newest (the store does this: orderEditsByRecency in carrystore.js).
220
+ // 0 (before all of those, hamr 2026-10-31): the function line ranges on the file lines.
221
+ // The last-try line and the heading are never dropped.
222
+ const dropOrder = (/** @type {Entry[]} */ arr, /** @type {(e: Entry) => boolean} */ protect = () => false) =>
223
+ arr.slice().sort((a, b) => Number(protect(a)) - Number(protect(b)) || b.tier - a.tier || a.count - b.count || a.recency - b.recency);
224
+ const isEditedFile = (/** @type {Entry} */ e) => e.keys.some((k) => k.startsWith('F\0') && editedPaths.has(k.slice(2)));
225
+ /** @type {Set<Entry>} */
226
+ const gone = new Set();
227
+ const goneEdits = new Set();
228
+ let showFns = true;
229
+ const tx = (/** @type {Entry} */ x) => (showFns && x.fn ? `${x.text} · functions: ${x.fn}` : x.text);
230
+ const hunkCaps = edits.map(() => HUNK_LINES); let gapCap = GAP_CHARS;
231
+ const gapText = () => (gapFull ? 'Last check said: ' + (gapFull.length > gapCap ? gapFull.slice(0, gapCap) + '…' : gapFull) : null);
232
+ const build = () => {
233
+ const L = [...head];
234
+ const g = gapText(); if (g) L.push(g);
235
+ const kept = (/** @type {Entry[]} */ arr) => arr.filter((x) => !gone.has(x));
236
+ const sec = (/** @type {string} */ title, /** @type {Entry[]} */ arr, /** @type {string[]} */ extra = []) => {
237
+ const k = kept(arr);
238
+ if (!k.length && !extra.length) return;
239
+ L.push(title); k.forEach((x) => L.push(tx(x))); extra.forEach((x) => L.push(x));
240
+ if (k.length < arr.length) L.push(`- (+${arr.length - k.length} lower-ranked not shown)`);
241
+ };
242
+ sec(`Where earlier workers looked (${files.length} file${files.length === 1 ? '' : 's'}):`, files, dropped ? [`- +${dropped} listings/config reads not shown`] : []);
243
+ sec('Searches and what they matched:', searches);
244
+ const ke = edits.filter((_, i) => !goneEdits.has(i));
245
+ 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');
246
+ sec('Earlier tries (folded):', earlier);
247
+ sec('Earlier failures (folded):', failures);
248
+ return L.join('\n');
249
+ };
250
+ let text = build();
251
+ const rawChars = text.length;
252
+ let capped = false;
253
+ /** @type {(() => void)[]} */
254
+ const steps = [
255
+ () => { showFns = false; },
256
+ ...dropOrder(files, isEditedFile).map((e) => () => { gone.add(e); }),
257
+ ...dropOrder(searches).map((e) => () => { gone.add(e); }),
258
+ ...dropOrder(earlier).map((e) => () => { gone.add(e); }),
259
+ ...dropOrder(failures).map((e) => () => { gone.add(e); }),
260
+ // 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
261
+ ...edits.map((_, i) => i).reverse().map((i) => () => { hunkCaps[i] = Math.min(hunkCaps[i], HUNK_SHOW); }),
262
+ ...edits.map((_, i) => i).reverse().map((i) => () => { hunkCaps[i] = 0; }), // oldest edit first, newest last
263
+ () => { gapCap = 300; },
264
+ ...edits.map((_, i) => i).reverse().map((i) => () => { goneEdits.add(i); }),
265
+ ];
266
+ let si = 0;
267
+ while (text.length > cap) {
268
+ capped = true;
269
+ if (si >= steps.length) break;
270
+ steps[si++]();
271
+ text = build();
272
+ }
273
+ if (text.length > cap) text = text.slice(0, cap - 1) + '…';
274
+ text = redactSecrets(text);
275
+
276
+ const named = new Set();
277
+ files.filter((x) => !gone.has(x)).forEach((x) => x.keys.forEach((k) => named.add(k)));
278
+ searches.filter((x) => !gone.has(x)).forEach((x) => x.keys.forEach((k) => named.add(k)));
279
+ edits.filter((_, i) => !goneEdits.has(i)).forEach((e) => named.add(`F\0${e.path}`));
280
+ const sections = {
281
+ reads: files.filter((x) => !gone.has(x)).length,
282
+ searches: searches.filter((x) => !gone.has(x)).length,
283
+ edits: edits.length - goneEdits.size,
284
+ earlier: earlier.filter((x) => !gone.has(x)).length,
285
+ failures: failures.filter((x) => !gone.has(x)).length,
286
+ };
287
+ return { text, capped, rawChars, rawEntries, foldedEntries, named, summarized, sections };
288
+ }