bareloop 0.50.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,36 @@ 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
+
23
+ ## [0.51.0] - 2026-10-29
24
+
25
+ ### Added
26
+
27
+ - **A handoff note: later workers are told which files earlier workers read (F253).** The next step or fix ask of a run (a retry of the same step too) gets a code-written map appended to its first prompt: one line per file an earlier ask read, with its line count and, from the LiteCtx index, its function names and line ranges. Capped at 8,000 characters (oldest paths dropped first, with a marker); arbiter books, `.git` and anything outside the job root are never named; scout and drafter prompts are unchanged. On by default; a signed spec's optional `handoffNote: false` turns it off (absent keeps the old hash). One report-only `handoff-note` spine record per note given. A resumed leg starts with an empty map.
28
+ - **An online/offline dot in the panel header, left of Settings.** When the panel's node process dies the open page used to look exactly like a live one; the Runs list read (already polled every 10 s) now paints a green "online" on any HTTP reply, even an error, and a red "offline" only when the read fails with no HTTP status. No new endpoint or timer. `getJSON` now tags its HTTP error with `.status` (message unchanged).
29
+
30
+ ### Fixed
31
+
32
+ - **A page render error no longer paints the online dot offline.** If drawing the Runs list threw after the fetch had succeeded, the error fell into the same handler as a failed read and the header showed "offline" while the panel was up. The render now has its own guard that logs the error to the browser console; only a real fetch failure (no HTTP reply) paints offline.
33
+ - **A command check now names its own command in the panel (F256).** Every check that runs a command used to read "does the test suite pass?", so a whole-repo `npx tsc --noEmit --strict` check and the real test suite read the same question. It now quotes the signed command: `does "npm test" exit clean?`, `does "npx tsc --noEmit --strict" exit clean?`. A check with no command falls back to its own name, as before.
34
+ - **The drafter is told to count one file with scope, never a path in `lineMatch` or a region anchor, with an example (F255).** The author prompt's parser description now says: to count lines about one file or folder, keep `lineMatch` general (e.g. `error TS\d+`) and put the file or folder in `scope.includePrefixes`, because a path in `lineMatch` stops matching once that file is clean and the check becomes a broken instrument instead of reading zero; it shows one legal `count-not-worse` example. Prompt-only; the validator is unchanged. Proven in a $0.73 drafter POC (path-in-parser 8/10 before, 0/10 after), not yet in a live run.
35
+ - **The planner is told `exit` is required on every step, with a legal example (F254).** The plan prompt called `exit` "1..2 form checks" and never said every step needs one, and a redraft got only the validator's rule. The prompt now says `REQUIRED on EVERY step` and shows two legal `exit` shapes, and the missing-exit red carries the same example. On deepseek-flash first drafts refused 8 of 23 before and 1 of 24 after; plan-red 1 before, 0 after.
36
+ - **The read shim no longer tells a later attempt it already holds a file it never received.** Every `ask()` builds a fresh Loop with a fresh transcript, but the shim's delivered-ledger lived for the whole worker, so attempt 2 re-reading a file attempt 1 had fully received got "unchanged since you read it, you already hold all N bytes" about bytes its model never saw. The ledger now resets at the start of each `ask()` (not at `askFrom`, which continues the same transcript); the run-level MEMORY-CACHE counts are untouched. (F252)
37
+
8
38
  ## [0.50.0] - 2026-10-28
9
39
 
10
40
  ### 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,6 +159,7 @@ 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
163
  | `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 |
163
164
  | `writeScope` | array of contained globs | the operator's outer fence; the plan's own scopes must fit inside it, same containment code |
164
165
  | `steps` | RETIRED | operator-authored `steps[]` was deleted (PRD v1.32); a spec carrying it reds `shape-retired:steps` by name rather than half-running |
@@ -191,7 +192,7 @@ ships with the grant (`COMPONENT_STRATEGIES` — capability without strategy is
191
192
  | component | verbs | class |
192
193
  |---|---|---|
193
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 |
194
- | 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 |
195
196
  | compress | `compress` · `peek` | read-only (a signature tier; a stash's head/tail) |
196
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** |
197
198
 
@@ -363,7 +364,7 @@ middle writes; `validatePlan` gates it against the SIGNED job spec before tokens
363
364
  | `steps[].model` | optional; `sonnet` (`STEP_MODELS`) | the step's model TIER — a menu, never a model string the agent spells (`sonnet` is a schema token meaning this job's worker model; the runner maps it, there is no tier table). `opus` is deliberately absent: reserved for work the human assigns, never plan-selectable; `haiku` was removed 2026-08-06 as a reversible ATTRIBUTION PROBE (F87, see `STEP_MODELS`), so the menu is one entry deep and the field is no longer offered in the drafting prompt. The field and its validator branch STAY: `model: "sonnet"` still validates, a stored bridge declaring it still loads, and restoring haiku is a one-token edit — this is not a finding that haiku is incapable. **The narrowing binds only what the AGENT may express.** Which real model a tier maps to, and what the caller runs as its own default worker model, stay the OPERATOR's: `providerFor` is yours, and the in-repo runner's `--model haiku` probe knob is untouched (PRD v1.36) — the runner's tier map is deliberately WIDER than the plan menu. Off-menu reds `invalid-value`. A step naming a tier when the caller supplied no `providerFor` factory is an `interpreter-red` STOP, never a silent run on the default tier |
364
365
  | `steps[].attempts` | optional; int `>= 1` | **RETIRED and INERT (F79) — it bounds nothing.** A step's iterations are governed by the STRIKE LADDER (below), which is shell-owned and inexpressible from the plan. The field is no longer offered in the drafting prompt and the runner ignores it; it is deliberately still ACCEPTED, because stored bridge plans carry it and a plan minted under one runner's number must not red under another's. The shape is still checked (a known field holding garbage stays a `bounds` red); the old `<= capRuns` ceiling is gone with the cap it named. It was previously TIGHTEN-only — which meant a step that needed MORE iterations could not ask, and drafters measurably tightened it instead (F77) |
365
366
  | `steps[].scope` | optional; one value from the SAME menu `tree-changed` uses | narrows this step's live WRITE fence to a subset of the signed `writeScope` — chosen from the offered scope menu (below), never authored. Off-menu reds `invalid-value` carrying the menu |
366
- | `steps[].exit` | 1..2 items (`MAX_EXITS_PER_STEP`), ALL must pass (AND-only, no OR/NOT) | closed menu (`EXIT_TYPES`): `artifact-written(path, pattern?)` · `tree-changed(scope)` · `json-valid(path)` · `check-passes(name)`. **`tree-changed.scope` is a MENU, not a glob the agent authors** — the runner enumerates the signed fence entries plus the real directories beneath them (shallowest-first, capped at `MAX_SCOPE_MENU`=24; `legalScopes` in `src/plan.js`), `planPrompt` lists them verbatim, and `validatePlan` accepts membership only — the SAME array on both sides, so what was offered is what is accepted; omitted, it derives from `writeScope` alone — never a free-text fallback. An off-menu value that escapes the fence still reds `scope-escape` (the ledger's attribution class), an in-fence unoffered value reds `invalid-value` carrying the menu. `runPlan` emits `scope-menu {offered, truncated, offerableCount?, cap?}` so a capped menu is never silently complete. `check-passes` must name a stage on the close's DERIVED menu (`check-unknown` red names the offered menu — no operator authors this list, it comes straight from `checkMenu(close)`); on a write-granted step it must be paired with `tree-changed` (`exit-illegal` — the seed tree is green, a lone check would pass untouched, F17/F46). **`check-passes` also requires a write-class verb (`write`/`edit`) on the SAME step** (`exit-illegal` — BREAKING for plan authors: a read-only "verify" step carrying a check used to validate and no longer does). A failing check's gap is re-delivered to that step's OWN worker, so a step holding a check must be able to act on it; a read-only one is a mailbox with no hands and stalls to cap on a byte-identical gap (measured on 4 of 4 drafted plans). The check belongs on the step that fixes; the run's final verification is the operator's close, which the agent never authors. The rule is stated identically in the drafter prompt and the validator, so the two can never disagree — and it is suppressed when `tools` failed to parse (the step's hands are unknowable then, and the real defect already redded: one defect, one red). `artifact-written.pattern` must compile AND survive a ReDoS shape check — an unbounded quantifier over a group that itself repeats unboundedly (`(a+)+`, `(\d*)*`, even wrapped: `((a+))+`) is an `invalid-value` red (F49, catastrophic-backtracking footgun; rewrite without a repeated group inside a repeat). Exits verify FORM, not truth — progress gates; the operator's close stays the one arbiter |
367
+ | `steps[].exit` | 1..2 items (`MAX_EXITS_PER_STEP`), ALL must pass (AND-only, no OR/NOT) | closed menu (`EXIT_TYPES`): `artifact-written(path, pattern?)` · `tree-changed(scope)` · `json-valid(path)` · `check-passes(name)`. **`tree-changed.scope` is a MENU, not a glob the agent authors** — the runner enumerates the signed fence entries plus the real directories beneath them (shallowest-first, capped at `MAX_SCOPE_MENU`=24; `legalScopes` in `src/plan.js`), `planPrompt` lists them verbatim, and `validatePlan` accepts membership only — the SAME array on both sides, so what was offered is what is accepted; omitted, it derives from `writeScope` alone — never a free-text fallback. `exit` is REQUIRED on every step: the planner prompt says so and shows one legal example (`EXIT_EXAMPLE`, `src/plan.js`), and the `missing-required` red carries the same example (F254). An off-menu value that escapes the fence still reds `scope-escape` (the ledger's attribution class), an in-fence unoffered value reds `invalid-value` carrying the menu. `runPlan` emits `scope-menu {offered, truncated, offerableCount?, cap?}` so a capped menu is never silently complete. `check-passes` must name a stage on the close's DERIVED menu (`check-unknown` red names the offered menu — no operator authors this list, it comes straight from `checkMenu(close)`); on a write-granted step it must be paired with `tree-changed` (`exit-illegal` — the seed tree is green, a lone check would pass untouched, F17/F46). **`check-passes` also requires a write-class verb (`write`/`edit`) on the SAME step** (`exit-illegal` — BREAKING for plan authors: a read-only "verify" step carrying a check used to validate and no longer does). A failing check's gap is re-delivered to that step's OWN worker, so a step holding a check must be able to act on it; a read-only one is a mailbox with no hands and stalls to cap on a byte-identical gap (measured on 4 of 4 drafted plans). The check belongs on the step that fixes; the run's final verification is the operator's close, which the agent never authors. The rule is stated identically in the drafter prompt and the validator, so the two can never disagree — and it is suppressed when `tools` failed to parse (the step's hands are unknowable then, and the real defect already redded: one defect, one red). `artifact-written.pattern` must compile AND survive a ReDoS shape check — an unbounded quantifier over a group that itself repeats unboundedly (`(a+)+`, `(\d*)*`, even wrapped: `((a+))+`) is an `invalid-value` red (F49, catastrophic-backtracking footgun; rewrite without a repeated group inside a repeat). Exits verify FORM, not truth — progress gates; the operator's close stays the one arbiter |
367
368
 
368
369
  **A step has exactly ONE check slot — plan for it.** The three exit rules above compose into
369
370
  a ceiling worth stating on its own, because it decides what a plan can enforce *during* a
@@ -644,6 +645,10 @@ plan with the first leg's spend carried as prior spend and `offerQuestions: fals
644
645
  plan's open questions) are a separate, unchanged mechanism: they are asked before drafting, about the plan; try-3 questions
645
646
  are asked after two failed drafts, about a job line.
646
647
 
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
+
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
+
647
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
648
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
649
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
@@ -685,6 +690,8 @@ call (plan, scout, replan, a one-attempt step) carries it on its header line (`p
685
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
686
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.
687
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
+
688
695
 
689
696
  **D5 — the mandatory guards are SHOWN and FIXED, and the battery keys off the VERDICT
690
697
  CLASS** (PRD v1.57 §2 — what a battery is FOR is the class of dishonesty that class of
@@ -1362,7 +1369,7 @@ measured correctness point); and `validatePlan` reds `read-blind` on any step gr
1362
1369
  without `recall` and `get`. Where only the DIFF runs, nothing is capped (a first read delivers
1363
1370
  whole, whatever the size), an unchanged re-read re-delivers rather than pointing, and G1 does not
1364
1371
  exist — G1 is the cap's compensation, and an arm that caps nothing has nothing to compensate for.
1365
- The ledger is per worker, so it resets with every step. On the native (clipipe) surface a CAPPING
1372
+ The ledger is per `ask()`, not per worker: every `ask()` builds a fresh transcript, so the ledger resets at the start of each one (F252; a later attempt's re-read gets the bytes, never a pointer for bytes its model never saw), while an `askFrom` continuation keeps the same transcript and its ledger. The run-level MEMORY-CACHE counts do not reset. On the native (clipipe) surface a CAPPING
1366
1373
  arm replaces the CLI-display cap rather than stacking on it; a non-capping arm leaves that wrapper
1367
1374
  installed *inside* the shim, so native never loses its bound. Default-flip pending a paid contrast;
1368
1375
  see CHANGELOG for the replay numbers behind it.
@@ -1936,7 +1943,7 @@ hand them to the one `Loop` that drives worker, scout and planner rounds; the ru
1936
1943
  them once. No price on the row = no `rates` key anywhere = the guesstimate above, byte-identical to
1937
1944
  before. bareloop keeps no price list of its own, ever.
1938
1945
 
1939
- **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`)
1940
1947
  carries it on every metering payload, and bareloop forwards it VERBATIM (`rateSourceFields`,
1941
1948
  `src/planrun.js`): every API `worker-round` (worker, scout, planner, fix loop) carries it beside
1942
1949
  `pricing` today — `'caller'` when a customer price is on the key's row, else `'tier'`/`'default'`
@@ -2737,6 +2744,20 @@ unreferenced loose objects are left. Gitignored files inside the fence are seen
2737
2744
  changed nothing in scope emits nothing, and a failed capture emits `gitError` with empty lists: a record,
2738
2745
  never a verdict, and it never throws. No prompt carries it; the learnings cards read it ("What changed").
2739
2746
 
2747
+ #### `handoff-note` — a note handed to a worker ask (`src/handoff.js`, `src/planrun.js`)
2748
+
2749
+ One report-only spine record per handoff note given: `{type:'handoff-note', phase, iteration, chars, paths}`.
2750
+ `phase` is `step:<id>` or `fix`; `iteration` is the round iteration at the ask; `chars` is the note's length in
2751
+ characters (at most 8,000); `paths` is a COUNT of the files the note lists after any trimming, never a name.
2752
+ `runPlan` writes it right before the ask runs, once per step or close-fix ask that actually receives a note: an
2753
+ ask with nothing yet read gets no note and no record, and the scout and the drafter are never handed one. It
2754
+ carries no cost fields (not a spend record) and no verdict. The switch is the signed spec's optional boolean
2755
+ `handoffNote`: absent = on, `false` = off (no note, no record). The prose rules are under "Handoff note".
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
+
2740
2761
  ### `replayRun(spineEvents, auditEvents?, { runId? })` / `formatReplay(summary)` / `summarizeForAllLine(summary)` / `formatAllLines(entries)` — `src/replay.js`
2741
2762
 
2742
2763
  `summarizeForAllLine(summary)` reduces one `replayRun` summary to one `--all`/directory-
@@ -3539,7 +3560,7 @@ key you want first (the panel picks the row by the Model menu).
3539
3560
  lowered from the original 2s per F195 — `listRuns()` re-replays every archived spine on
3540
3561
  every call, ~457ms CPU at 250 rows, open/escalated), except the tick right after the open
3541
3562
  run stops being live, which forces one immediate list refresh so that row's glyph doesn't
3542
- wait up to 10s. Both fetches skip re-rendering when the payload's JSON is byte-identical to
3563
+ wait up to 10s. The Runs list read is also the panel's heartbeat for the topbar online dot (see "Panel topbar"). Both fetches skip re-rendering when the payload's JSON is byte-identical to
3543
3564
  the last one, restore each pane's scroll position across a poll-driven rebuild, and pause
3544
3565
  while the tab is hidden (`document.hidden`), catching up immediately on
3545
3566
  `visibilitychange`. The Audit tab does **not** join this loop — it refetches only when
@@ -3947,7 +3968,7 @@ Two files in `~/.config/bareloop/`, outside any repo:
3947
3968
  real one). The CLI (`run-u`, `interview`, `author`) and the panel both use it.
3948
3969
  - **`config.json` — every setting, never a key value.** `readConfig({ home })` /
3949
3970
  `updateConfig(patch, { home })` (atomic tmp + rename, mode 600, unknown fields kept).
3950
- 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
3951
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,
3952
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
3953
3974
  in: a row with nothing saved is shape `openai-api`, no address, no lines. A secret-shaped
@@ -4449,7 +4470,7 @@ A **Rubric** job whose first Input is the full path of a FILE (not a repo folder
4449
4470
  - **Panel wording.** `stageQuestionText` words a rubric-step stage "line N — does its output pass the line's checks?". The worker brief also tells the worker to copy every number, time and price in a claim exactly as the input writes it ("9:27 AM", not "09:27").
4450
4471
  - **Shown == run (run mv5bk400).** The plan card after drafting is built from the signed close (`checksOfClose`, code-written sentences), not from the confirm turn's prose. A countable part may list the confirmed checks it carries out in `covers` (the composer prompt numbers them `#n`); `reconcileRubricPlan` moves every confirmed check no part covers to Not checked ("... — nothing in this close counts it or checks it against a quote"). `signRun` calls `planMatchesClose(session.state.finalPlan.checkItems, closeDecl)` and refuses, spawning nothing, when the two differ. `minClaims` / `maxClaims` (parts with `value` + `source`) count the claims listed under an input: `flattenStep` takes the count from the file's own `cites.<label>` list as the field `claims:<label>` and bareguard's `min`/`max` compares it. A free-text note is never a check.
4451
4472
  - **Labels.** A text close carries `genre: "TEXT"` (`genreForLang`; `TYPES` is for code languages, and a genre must match its language); its spine records carry no `judgedCount` (no judge ran); the progress list words a file job's steps from `FILE_JOB_STEP_LABELS` ("copying input files", "reading input files").
4452
- - **Panel topbar.** `bareloop · v<version> · automate a job, verified`: the version is bareloop's own package.json, read once when the panel starts and templated into the page when it is served (`__BARELOOP_PANEL_VERSION__`), so it is the version the process runs, not what package.json says now.
4473
+ - **Panel topbar.** `bareloop · v<version> · automate a job, verified`: the version is bareloop's own package.json, read once when the panel starts and templated into the page when it is served (`__BARELOOP_PANEL_VERSION__`), so it is the version the process runs, not what package.json says now. Right of the host line and left of Settings sits the online dot (`#online-dot`): the Runs list read (the 10 s poll, no new endpoint or timer) paints green `online` on any HTTP reply, even an error status or a 200 whose body will not parse, and red `offline` only when the read fails with no HTTP status (the panel process is gone); a page render error after a good read never paints it offline.
4453
4474
  - **After drafting, the code-worded card is the only plan on screen (run mv5e1ktb).** The confirm turn's plan bubble is the drafter's own prose (written before any close existed) and used to stay in the thread above the code-worded card; when the rubric card is ready the earlier `kind:'plan'` messages are dropped. `partSentence` now reads "1 line" / "1 word" for a count of one.
4454
4475
  - **Each `~` guardrail is its own row on the plan card.** `planFromSpec` / `planFromConfirm` lines carry `rules: string[]` (the line's own `rules`, else the joined `rule` split on "; "); `renderJobPlan` draws one `~ rule` row per rule under its numbered line, in the plan card and the Job tab alike (one renderer). Gutter numbers stay on job lines only.
4455
4476
  - **The review door's held line is true for a no-judge close.** Credit is held by VERDICT CLASS (`quarantinesCredit`: soft-green), whether or not a judge ran; the door now says "this is a rubric (soft-green) job, so its green earns NO reuse and NO learning credit until you accept it, whether or not a judge ran". Wording only; `bridges.js`/`reuse.js`/the Reuse refusal still say "rendered by the judged floor".
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bareloop",
3
- "version": "0.50.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"
package/src/authorflow.js CHANGED
@@ -1072,7 +1072,16 @@ THE PARSER reads ONE number out of a command's output, as signed arithmetic over
1072
1072
  region "whole-output", or {anchor, capture} to search only inside the part of the output the
1073
1073
  anchor locates. A region that cannot be located is a broken instrument.
1074
1074
  sign ${SIGNS.join(' | ')}. Subtraction is how you exclude things that were reported but did
1075
- not actually happen.`;
1075
+ not actually happen.
1076
+
1077
+ To count lines about one file or folder, keep lineMatch general (match the error line itself, e.g.
1078
+ "error TS\\d+") and put the file or folder in scope.includePrefixes. Never put a file path inside
1079
+ lineMatch or inside a region anchor: once that file is clean the command still fails on other files,
1080
+ nothing matches, and the check stops as a broken instrument instead of reading zero.
1081
+
1082
+ {"kind": "count-not-worse", "params": {"cmd": "npm", "args": ["run", "typecheck", "--", "--strict"],
1083
+ "parser": {"terms": [{"lineMatch": "error TS\\\\d+", "capture": null, "sign": 1, "aggregate": "sum", "region": "whole-output"}]},
1084
+ "scope": {"includePrefixes": ["src/target.js"]}, "direction": "lower-is-better", "baseline": 0}}`;
1076
1085
  }
1077
1086
 
1078
1087
  /**
@@ -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
+ }