bareloop 0.52.0 → 0.54.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/readshim.js CHANGED
@@ -40,6 +40,7 @@
40
40
 
41
41
  import { createHash } from 'node:crypto';
42
42
  import { readFileSync } from 'node:fs';
43
+ import { relative, resolve, sep } from 'node:path';
43
44
 
44
45
  /** The delivery cap, in bytes. Equal to `NATIVE_READ_CAP` by construction — the
45
46
  * native path's CLI display bound and this cap bound the SAME seam, so one
@@ -324,6 +325,58 @@ const stalePastEofNotice = (path, startLine, endLine, lines, detail) =>
324
325
  /** @typedef {{file: string, path: string, startLine: number, endLine: number, detail: string}} StaleReq */
325
326
  /** @typedef {{text: string, outcome: 'stale-served'|'stale-absent'|'stale-past-eof'}} StaleServe */
326
327
 
328
+ // ── THE FIRST-READ MAP (EXPERIMENTAL, default off; docs/logs/MAP-PREREG.md) ─────────────────────────────────────────
329
+ // With the signed spec field `readMap: true`, the FIRST shell_read of a big non-test file in an ask returns a map (one line
330
+ // per named part: symbol and line range) instead of the file's bytes, so the worker can copy exact `ctx_get` handles instead
331
+ // of computing a range ($0 archive read: 41% of ctx_get calls on a big-file job came back no-chunk). It delivers nothing, so
332
+ // it never touches the delivery ledger: the SECOND read of the same path in the same ask is today's read, whole.
333
+
334
+ /** a file this long (in lines) or longer gets a map on its first read in an ask */
335
+ export const READ_MAP_MIN_LINES = 200;
336
+ /** the map's size bound, in characters (header, parts, `+N more` line and footer together) */
337
+ export const READ_MAP_CAP = 4000;
338
+
339
+ /** a test file: a `test/`, `tests/` or `__tests__/` path segment, or a name `*.test.*` / `*.spec.*` */
340
+ const isTestPath = (/** @type {string} */ rel) => rel.split('/').some((seg, i, a) => (i < a.length - 1 && (seg === 'test' || seg === 'tests' || seg === '__tests__')) || (i === a.length - 1 && /\.(test|spec)\./.test(seg)));
341
+
342
+ /**
343
+ * The map text for one file, from the index's chunks. Pure. A chunk that CONTAINS another named chunk is left out (a class
344
+ * chunk would hand the whole class to `ctx_get`); the rest are listed by start line as `symbol start-end` in the index's own
345
+ * 0-based inclusive line space, the one `ctx_get` takes. Cut to READ_MAP_CAP characters with a `+N more` line.
346
+ * @param {{rel: string, lines: number, chunks: {symbol?: string|null, startLine: number, endLine: number}[]}} o
347
+ * @returns {{text: string, symbols: number}|null} null when the file has no named part
348
+ */
349
+ export function buildReadMap({ rel, lines, chunks }) {
350
+ const named = chunks.filter((c) => typeof c.symbol === 'string' && c.symbol !== '' && Number.isInteger(c.startLine) && Number.isInteger(c.endLine));
351
+ const kept = named
352
+ .filter((c) => !named.some((d) => d !== c && c.startLine <= d.startLine && d.endLine <= c.endLine && (c.startLine !== d.startLine || c.endLine !== d.endLine)))
353
+ .sort((a, b) => a.startLine - b.startLine || a.endLine - b.endLine);
354
+ if (kept.length === 0) return null;
355
+ const head = `${rel} (${lines} lines) — map, not the file:`;
356
+ const foot = `Line numbers are 0-based, as ctx_recall prints them; copy them as printed. Open one part with ctx_get(path="${rel}", startLine=<start>, endLine=<end>) using a range from this list, or read the file again to get the whole file.`;
357
+ const rows = kept.map((c) => `${c.symbol} ${c.startLine}-${c.endLine}`);
358
+ const moreLine = (/** @type {number} */ n) => `+${n} more`;
359
+ let used = head.length + 1 + foot.length;
360
+ const shown = [];
361
+ for (let i = 0; i < rows.length; i++) {
362
+ // room for the `+N more` line is reserved while parts remain after this one
363
+ const reserve = i < rows.length - 1 ? moreLine(rows.length).length + 1 : 0;
364
+ if (used + rows[i].length + 1 + reserve > READ_MAP_CAP) break;
365
+ shown.push(rows[i]);
366
+ used += rows[i].length + 1;
367
+ }
368
+ const cut = rows.length - shown.length;
369
+ const text = [head, ...shown, ...(cut > 0 ? [moreLine(cut)] : []), foot].join('\n');
370
+ return { text, symbols: shown.length };
371
+ }
372
+
373
+ /**
374
+ * @typedef {{root: string, hasGet: boolean, getNode: (rel: string) => any, refresh?: (() => Promise<unknown>)|null, emit: (type: string, data: object) => void}} ReadMapOpts
375
+ * `root`: the job root (paths are made relative to it); `hasGet`: this worker holds `ctx_get` (a map hands out handles only that tool opens);
376
+ * `getNode`: the LiteCtx index's node for a path (its `chunks`); `refresh`: re-index first so the ranges are true to the file as it now is;
377
+ * `emit`: the spine channel, for the report-only `read-map` / `read-map-skip` records (counts and a reason, never text).
378
+ */
379
+
327
380
  /**
328
381
  * Create the shim: one delivery ledger, and the two seams that speak for it.
329
382
  *
@@ -332,7 +385,7 @@ const stalePastEofNotice = (path, startLine, endLine, lines, detail) =>
332
385
  * reference to the ledger — see its own note. Both live in one object because
333
386
  * they are one worker's shim: the read seam and the retrieval seam the cap
334
387
  * steers a capped worker towards.
335
- * @param {{cap?: number, arm?: ReadShimArm, onCount?: ((kind: 'pointered'|'capped', bytesWithheld: number) => void)|null}} [opts]
388
+ * @param {{cap?: number, arm?: ReadShimArm, onCount?: ((kind: 'pointered'|'capped', bytesWithheld: number) => void)|null, readMap?: ReadMapOpts|null}} [opts]
336
389
  * `cap`: delivery bound in bytes (the shipped value is `READ_SHIM_CAP`; the option
337
390
  * exists so the native path can pin the two bounds to one number rather than two
338
391
  * constants drifting apart). `arm`: which levers are live (`readShimArm`). Defaults to
@@ -343,7 +396,10 @@ const stalePastEofNotice = (path, startLine, endLine, lines, detail) =>
343
396
  * for a diff response (L2 is its own lever, uncounted here) or a first read under the
344
397
  * cap (nothing was withheld).
345
398
  */
346
- export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = null } = {}) {
399
+ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = null, readMap = null } = {}) {
400
+ /** the paths (absolute) this ask has had its map decision for: the second read of one is today's read
401
+ * @type {Set<string>} */
402
+ const mapTried = new Set();
347
403
  /** path → what the worker has been handed of the CURRENT content. `full` is
348
404
  * the delivered text itself, kept ONLY while the worker holds the whole file
349
405
  * (null otherwise) because that is the only state a diff is legal from.
@@ -456,6 +512,38 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
456
512
  * @param {{name: string, execute: (args: any) => Promise<any>}} tool the read tool
457
513
  * @returns {{name: string, execute: (args: any) => Promise<any>}} the same tool
458
514
  */
515
+ /** @param {string} path the path as the worker spelled it @returns {Promise<string|null>} the map text, or null for today's read */
516
+ const firstReadMap = async (path) => {
517
+ const o = /** @type {ReadMapOpts} */ (readMap);
518
+ const abs = resolve(o.root, path);
519
+ if (mapTried.has(abs)) return null;
520
+ mapTried.add(abs);
521
+ const rel = relative(resolve(o.root), abs).split(sep).join('/');
522
+ if (rel === '' || rel.startsWith('..') || isTestPath(rel)) return null;
523
+ let lines;
524
+ try {
525
+ const text = readFileSync(abs, 'utf8');
526
+ lines = text.split('\n').length - (text.endsWith('\n') ? 1 : 0);
527
+ } catch { return null; }
528
+ if (lines < READ_MAP_MIN_LINES) return null;
529
+ /** @param {string} reason */
530
+ const skip = (reason) => { o.emit('read-map-skip', { path: rel, reason }); return null; };
531
+ if (!o.hasGet) return skip('no-ctx_get');
532
+ let chunks;
533
+ try {
534
+ if (o.refresh) await o.refresh();
535
+ chunks = o.getNode(rel)?.chunks;
536
+ } catch { return skip('no-index'); }
537
+ if (!Array.isArray(chunks)) return skip('no-index');
538
+ if (!chunks.some((/** @type {any} */ c) => c?.symbol)) return skip('no-named-chunks');
539
+ // an index older than the file: a named chunk ending past the file's last line
540
+ if (chunks.some((/** @type {any} */ c) => c?.symbol && c.endLine >= lines)) return skip('stale-index');
541
+ const built = buildReadMap({ rel, lines, chunks });
542
+ if (!built) return skip('no-named-chunks');
543
+ o.emit('read-map', { path: rel, lines, symbols: built.symbols, chars: built.text.length });
544
+ return built.text;
545
+ };
546
+
459
547
  const wrapRead = (tool) => {
460
548
  // An OFF arm wraps nothing at all — not a wrapper that passes through, which
461
549
  // would still be a `tool.execute` this module owns. A0 has to be the seam
@@ -471,6 +559,13 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
471
559
  // path nobody ever received bytes for.
472
560
  if (path === null || typeof r !== 'string') return r;
473
561
 
562
+ // THE FIRST-READ MAP (experimental): the first read of a big non-test file in this ask returns the map, delivers nothing, and
563
+ // leaves the ledger untouched; every other read falls through to the code below unchanged.
564
+ if (readMap) {
565
+ const m = await firstReadMap(path);
566
+ if (m !== null) return m;
567
+ }
568
+
474
569
  const buf = Buffer.from(r, 'utf8');
475
570
  const total = buf.length;
476
571
  const hash = createHash('sha256').update(buf).digest('hex');
@@ -569,7 +664,7 @@ export function createReadShim({ cap = READ_SHIM_CAP, arm = ARM_ALL, onCount = n
569
664
  * Not called for a continuation (`askFrom` re-runs the SAME transcript — the model still
570
665
  * holds everything, so its ledger stays true).
571
666
  */
572
- const reset = () => { ledger.clear(); };
667
+ const reset = () => { ledger.clear(); mapTried.clear(); };
573
668
 
574
669
  return { arm, cap, wrapRead, serveStale, summary, reset };
575
670
  }
package/src/run.js CHANGED
@@ -261,9 +261,6 @@ async function primitiveSmoke(workdir) {
261
261
  * round-boundary seam (where the money cap binds) and ends the leg `stopped`. `null` = no stop surface.
262
262
  * @param {{text: string, ids: string[]}|null} [opts.learnHints=null] cross-run learnings for the PLANNER only (the draft and the
263
263
  * first replan); forwarded verbatim to the plan flow, which records what it handed over as a `learnings` spine record.
264
- * @param {boolean} [opts.carryNote=false] THE CARRY NOTE (src/carrynote.js): hand each step/fix worker a facts-only note of what earlier
265
- * workers of this run looked at, searched and changed. The caller reads the one switch (`carryNote` in config.json, src/carrystore.js
266
- * `carryNoteOn`) once; the library default is off, exactly like `learnHints`. Forwarded verbatim to the plan flow.
267
264
  * @returns {Promise<string>} outcome: 'green' | 'already-green' | 'escalated' |
268
265
  * 'unapproved-spec' | 'job-red' | 'smoke-red' | 'plan-red' | 'check-red' |
269
266
  * 'close-red' | 'close-unsupported' | 'recipe-stale' | 'branch-red' | 'pricing-red' | 'provider-red' |
@@ -278,7 +275,7 @@ async function primitiveSmoke(workdir) {
278
275
  * deliberately NOT in the resumable/checkpoint set (`src/reuse.js`) — an
279
276
  * unknown in-flight state is not a known-safe resume point.
280
277
  */
281
- export async function runJob(rawSpec, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, capRuns = 3, strikeLimit, shellCapUsd = 2, closeTimeoutMs, closeDir = null, layerRoot = false, readShim = false, scout = true, bridge = null, draftSpentUsd = 0, draftSpendComplete = true, priorSpentUsd = 0, priorSpendComplete = true, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null, carryNote = false }) {
278
+ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProvider, providerFor, judgeProvider = null, judgeModel = null, rates = null, judgeRates = null, emit, capRuns = 3, strikeLimit, shellCapUsd = 2, closeTimeoutMs, closeDir = null, layerRoot = false, readShim = false, scout = true, bridge = null, draftSpentUsd = 0, draftSpendComplete = true, priorSpentUsd = 0, priorSpendComplete = true, priorWallMs = 0, resumeSeed = null, resumeGrades = [], resumeReplans = null, resumeBranch = null, humanRuling = null, heldRuling = null, reviewDoor = null, doorRerun = null, resumable = true, stopFile = null, learnHints = null }) {
282
279
  // THE READ SHIM's ARM, resolved at the door — the FIRST thing this entry does,
283
280
  // before the ledger, before the approval gate, before a byte of the spec is read.
284
281
  // An unrecognised spelling throws here at zero cost instead of being coerced by
@@ -545,7 +542,7 @@ export async function runJob(rawSpec, { approvals, workdir, provider, nativeProv
545
542
  // accounts it natively (F12) and the job-end money contract is unchanged.
546
543
  {
547
544
  const outcome = await runPlan(job, {
548
- workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit: meter, capRuns, ...(strikeLimit !== undefined ? { strikeLimit } : {}), closeTimeoutMs, closeDir, layerRoot, readShim, scout, bridge, priorWallMs: chainWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, reviewDoor, doorRerun, priorSpentUsd: chainFoldUsd, resumable, stopFile, learnHints, carryNote,
545
+ workdir, provider, nativeProvider, providerFor, judgeProvider, judgeModel, rates, judgeRates, emit: meter, capRuns, ...(strikeLimit !== undefined ? { strikeLimit } : {}), closeTimeoutMs, closeDir, layerRoot, readShim, scout, bridge, priorWallMs: chainWallMs, resumeSeed, resumeGrades, resumeReplans, resumeBranch, humanRuling, heldRuling, reviewDoor, doorRerun, priorSpentUsd: chainFoldUsd, resumable, stopFile, learnHints,
549
546
  // hamr's ruling 2026-09-28 — ONE cap covers drafting + run: the run's
550
547
  // enforced ceiling is the signed `budgetUsd` (unchanged, still in the
551
548
  // spec hash) MINUS whatever drafting already spent on this job before
@@ -0,0 +1,28 @@
1
+ // THE SEED NOTE (default ON; docs/logs/SEEDGAP-PREREG.md): what the job's own check said on the untouched tree.
2
+ // Built by code from the preflight's own stage results — no extra close run, no model call, no verdict change. Read-only text for the
3
+ // planner's first draft; every step/fix worker gets it through the carry memo's "Earlier failures (folded):" section, labelled `at start`
4
+ // (src/carrystore.js `setStartFailure`). The switch is the signed spec's `seedNote` (absent = on, only `false` turns it off).
5
+ // Only a count-not-worse stage red at seed qualifies: a command-exit gap is capped noise that cannot carry the failure, and
6
+ // changed-from-seed is the "nothing changed yet" fact every run starts with. The stage text is passed as the stage rendered it, masked.
7
+
8
+ export const SEED_NOTE_HEADING = "At start, the job's own check said:";
9
+ /** the one stage kind whose text qualifies */
10
+ export const SEED_NOTE_KIND = 'count-not-worse';
11
+
12
+ /**
13
+ * @param {{stage: string|null|undefined, kind: string|null|undefined, gap: string|null|undefined}[]} reds one entry per preflight verdict
14
+ * that was RED at seed (stage = the stage that rendered it, kind = that stage's declared kind, gap = the verdict's gap text)
15
+ * @param {(s: string) => string} scrub the run's secret mask
16
+ * @returns {{ text: string, body: string, stages: string[] }|null} null when no qualifying stage was red (nothing to say)
17
+ */
18
+ export function buildSeedNote(reds, scrub) {
19
+ /** @type {Map<string, string>} */
20
+ const kept = new Map();
21
+ for (const r of reds) {
22
+ if (r.kind !== SEED_NOTE_KIND || typeof r.stage !== 'string' || typeof r.gap !== 'string' || !r.gap.trim()) continue;
23
+ if (!kept.has(r.stage)) kept.set(r.stage, scrub(r.gap));
24
+ }
25
+ if (kept.size === 0) return null;
26
+ const body = [...kept.values()].join('\n');
27
+ return { text: `${SEED_NOTE_HEADING}\n${body}`, body, stages: [...kept.keys()] };
28
+ }
package/src/tools.js CHANGED
@@ -13,7 +13,8 @@
13
13
  // axis goes blind (F3). The consumer (planrun) wires it at construction.
14
14
 
15
15
  import { createRequire } from 'node:module';
16
- import { join, resolve, sep } from 'node:path';
16
+ import { join, resolve, sep, dirname, basename } from 'node:path';
17
+ import { realpath } from 'node:fs/promises';
17
18
  import { homedir } from 'node:os';
18
19
 
19
20
  const require = createRequire(import.meta.url);
@@ -57,9 +58,9 @@ export const PERSONA_TOOLS = 'You are a senior engineer working in a repository
57
58
  + `The repository root also holds the arbiter's own books — ${GATE_AUDIT_FILE}, ${ARBITER_BOOK_STORES.join(', ')}, and this run's spine. `
58
59
  + 'They are ALWAYS denied and record how you are being judged, never anything about the task: never read them, and never try to route around the denial. '
59
60
  + 'You are ONE attempt inside an automated loop: when you finish, a test suite runs and, if it still fails, you are called again with its output. '
60
- + 'So do not try to be certain before acting. Read only what you need to form your best hypothesis, make the change with the write tool, and stop. '
61
+ + 'So do not try to be certain before acting. Read only what you need to form your best hypothesis, make the change with the file-changing tool you were given, and stop. '
61
62
  + 'A wrong cheap attempt is corrected by the next round; exhaustive reading is not — every file you read is re-sent on every later round and the run has a hard budget it can exhaust before you ever write. '
62
- + 'Make the required changes with the write tool, then reply with a short summary of what you changed. Never put file contents in your reply.';
63
+ + 'Make the required changes with your file-changing tool, then reply with a short summary of what you changed. Never put file contents in your reply.';
63
64
 
64
65
  // The retrieval verbs only pay if the worker reaches for them INSTEAD of paging a file.
65
66
  // F18 measured the failure they exist to fix: the worker read one 117 KB file NINE times
@@ -616,14 +617,27 @@ export function createCtxTools(lc, workdir, emit, { onStalePointer = null } = {}
616
617
  // cwd and reds at the fence, and the deny reason teaches the retry.
617
618
  /** @param {string} p */
618
619
  const expandHome = (p) => (p === '~' || p.startsWith('~/')) ? join(homedir(), p.slice(1)) : p;
620
+ /**
621
+ * F267 — what the audit records for a write/edit payload: its JSON type and its UTF-8 BYTE length. The old
622
+ * `String(x).length` read an object as "[object Object]" (15) and counted UTF-16 units, so a refused object
623
+ * write looked like a real 15-byte write. A non-string is measured as the JSON it was sent as.
624
+ * @param {any} v
625
+ * @returns {{bytes: number, valueType: string}}
626
+ */
627
+ function valueSize(v) {
628
+ const valueType = v === null ? 'null' : Array.isArray(v) ? 'array' : typeof v;
629
+ if (v === undefined) return { bytes: 0, valueType };
630
+ const text = typeof v === 'string' ? v : (JSON.stringify(v) ?? '');
631
+ return { bytes: Buffer.byteLength(text), valueType };
632
+ }
619
633
  /** @param {string} name @param {any} args @param {string} [workdir] */
620
634
  export const toolAction = (name, args, workdir) => {
621
- if (name === 'shell_write') return { type: 'write', path: resolve(expandHome(String(args?.path ?? ''))), args: { bytes: String(args?.content ?? '').length } };
635
+ if (name === 'shell_write') return { type: 'write', path: resolve(expandHome(String(args?.path ?? ''))), args: valueSize(args?.content) };
622
636
  // shell_edit (BA-13) is judged as bareguard's own 'edit' action type — the SAME
623
637
  // fs.writeScope fence as write, decided upstream (bareguard FS_TYPES). `bytes` is
624
638
  // the replacement's size so the audit can read the edit economy (a 40-byte splice
625
639
  // vs an 8KB rewrite is the variable BA-13 exists to move — F18 blindness rule).
626
- if (name === 'shell_edit') return { type: 'edit', path: resolve(expandHome(String(args?.path ?? ''))), args: { bytes: String(args?.newText ?? '').length } };
640
+ if (name === 'shell_edit') return { type: 'edit', path: resolve(expandHome(String(args?.path ?? ''))), args: valueSize(args?.newText) };
627
641
  // `tool` rides the action so the AUDIT can tell the read tools apart. Without it every
628
642
  // read tool collapses to {type:'read', path} and a whole-file shell_read is
629
643
  // indistinguishable from a bounded ctx_get chunk — the ledger cannot see the one
@@ -664,8 +678,53 @@ export const toolAction = (name, args, workdir) => {
664
678
  * `noFollowSymlinks` closes the swap-after-vetting window bare-agent documents.
665
679
  * @param {{allows: (action: any) => Promise<boolean>}} gate
666
680
  * @param {string} workdir
681
+ * @param {(absPath: string) => boolean|Promise<boolean>} [guardPath] BA-30: true for a path tracked at the seed (`trackedAtSeedGuard`)
667
682
  */
668
- export const gatedShellOptions = (gate, workdir) => ({
683
+ export const gatedShellOptions = (gate, workdir, guardPath) => ({
669
684
  noFollowSymlinks: true,
670
685
  canRead: (/** @type {string} */ p, /** @type {{tool: string}} */ { tool }) => gate.allows(toolAction(tool, { path: p }, workdir)),
686
+ // BA-30 (F272): a whole-file write that would gut a file tracked at the seed is refused,
687
+ // file unchanged. Opt-in per worker; the scout has no write tool and passes no guardPath.
688
+ ...(guardPath ? { shrinkGuard: { guardPath } } : {}),
671
689
  });
690
+
691
+ /**
692
+ * The REAL path of `p`, for a path that may not exist yet: realpath the deepest existing
693
+ * ancestor and append the rest. bare-agent's guard hands its predicate the LEXICAL absolute
694
+ * path (it stays lexical by its own ruling), so a symlinked parent directory would otherwise
695
+ * read as "not tracked" and fail the guard open (F276 gap a).
696
+ * @param {string} p an absolute path
697
+ * @returns {Promise<string>}
698
+ */
699
+ export async function realPathOrAncestor(p) {
700
+ /** @type {string[]} */ const rest = [];
701
+ let cur = p;
702
+ for (;;) {
703
+ try {
704
+ return join(await realpath(cur), ...rest);
705
+ } catch (e) {
706
+ const code = /** @type {NodeJS.ErrnoException} */ (e).code;
707
+ if (code !== 'ENOENT' && code !== 'ENOTDIR') throw e; // a fault is not "untracked": the guard throws and the write is refused
708
+ const up = dirname(cur);
709
+ if (up === cur) return p;
710
+ rest.unshift(basename(cur));
711
+ cur = up;
712
+ }
713
+ }
714
+ }
715
+
716
+ /**
717
+ * BA-30's `guardPath`: true only for a path tracked at the seed. Both sides are compared in
718
+ * the REAL form: the set is `realpath(workdir)` + each seed-listed name (a tracked path cannot
719
+ * lie beyond a symlink, git refuses it, so the join is already real), the candidate goes through
720
+ * `realPathOrAncestor`. Files the worker creates later are not in the set, so the guard is off
721
+ * for them (a rubric step file's own rewrite is not a gutting).
722
+ * @param {string} workdir the WORKER tree (panel worktree or hidden-git copy), never the source repo
723
+ * @param {string[]} files the seed listing (`seedListing().files`, repo-relative)
724
+ * @returns {Promise<(absPath: string) => Promise<boolean>>}
725
+ */
726
+ export async function trackedAtSeedGuard(workdir, files) {
727
+ const root = await realpath(workdir);
728
+ const tracked = new Set(files.map((f) => join(root, f)));
729
+ return async (absPath) => tracked.has(await realPathOrAncestor(absPath));
730
+ }
package/src/userrun.js CHANGED
@@ -83,7 +83,6 @@ import { parseJsonl } from './replayio.js';
83
83
  import { claimRun, monthlyRefusalText, legSpend, chainSpend } from './monthly.js';
84
84
  import { ConfigError } from './config.js';
85
85
  import { learnAtRunEnd, handedHints, releaseRun } from './learnstore.js';
86
- import { carryNoteOn } from './carrystore.js';
87
86
  import { commandFor } from './invoke.js';
88
87
  import { judgeRatesFor, keyNameFor, keyValueOf, priceReadout, ratesFor, ratesOfLine, resolveWorker, judgeRowFor, rowsForHome, REFUSE_NAME_MODEL } from './providerrows.js';
89
88
  // the banner's wall arithmetic, extracted so it is reachable by a test (F83): the
@@ -1917,8 +1916,6 @@ async function execute(ctx) {
1917
1916
  outcome = await runJob(spec, {
1918
1917
  stopFile,
1919
1918
  ...(learnHints === null ? {} : { learnHints }),
1920
- // the carry note's one switch, read once here exactly like `learningHints` above (absent = on, only `false` turns it off)
1921
- carryNote: cfgOn && carryNoteOn(cfgHome),
1922
1919
  // PRD item 27/M3 — the SAME `emit` the pre-run close-timing reading above
1923
1920
  // used (never a second `makeSpine(spineFile)` here: two independent
1924
1921
  // emitters against one file would both start their seq counter at 0 and
@@ -218,6 +218,32 @@ export function declarationSchema(catalogue?: Record<string, any>, { verdictType
218
218
  };
219
219
  description: string;
220
220
  };
221
+ guardLines: {
222
+ type: string;
223
+ items: {
224
+ type: string;
225
+ properties: {
226
+ guard: {
227
+ type: string;
228
+ minLength: number;
229
+ description: string;
230
+ };
231
+ lines: {
232
+ type: string;
233
+ minItems: number;
234
+ uniqueItems: boolean;
235
+ items: {
236
+ type: string;
237
+ minimum: number;
238
+ };
239
+ description: string;
240
+ };
241
+ };
242
+ required: string[];
243
+ additionalProperties: boolean;
244
+ };
245
+ description: string;
246
+ };
221
247
  };
222
248
  required: string[];
223
249
  additionalProperties: boolean;
@@ -333,6 +359,32 @@ export function declarationTool(box: {
333
359
  };
334
360
  description: string;
335
361
  };
362
+ guardLines: {
363
+ type: string;
364
+ items: {
365
+ type: string;
366
+ properties: {
367
+ guard: {
368
+ type: string;
369
+ minLength: number;
370
+ description: string;
371
+ };
372
+ lines: {
373
+ type: string;
374
+ minItems: number;
375
+ uniqueItems: boolean;
376
+ items: {
377
+ type: string;
378
+ minimum: number;
379
+ };
380
+ description: string;
381
+ };
382
+ };
383
+ required: string[];
384
+ additionalProperties: boolean;
385
+ };
386
+ description: string;
387
+ };
336
388
  };
337
389
  required: string[];
338
390
  additionalProperties: boolean;
@@ -441,8 +493,9 @@ export function confirmedBlock(confirmed: {
441
493
  * names the ONE numbered job line it serves, or the line is refused with a reason; the mandatory guards serve no line.
442
494
  * The $0 validator (validateDeclaration, `jobLines`) enforces it and the revise loop feeds a miss back.
443
495
  * @param {number} count how many numbered job lines the person wrote
496
+ * @param {string[]} [guardNames] the mandatory guards' names; present = the block also tells how a line they already cover is covered
444
497
  */
445
- export function jobLineTagBlock(count: number): string;
498
+ export function jobLineTagBlock(count: number, guardNames?: string[]): string;
446
499
  /**
447
500
  * The whole authoring prompt, as one string.
448
501
  *
@@ -1,3 +1,9 @@
1
+ /**
2
+ * Is this repo-relative path off limits to the memo: outside the job root, an arbiter book (the one list,
3
+ * `isArbiterBook`: .smoke — spine, attempt-diff, bridges — .litectx, the gate audit), or inside `.git` / `.bareloop`.
4
+ * @param {string} rel
5
+ */
6
+ export function isCarryExcluded(rel: string): boolean;
1
7
  /**
2
8
  * One record per tool call (no content, no worker words).
3
9
  * @typedef {object} Ev
@@ -46,7 +52,8 @@ export function mergeRanges(rs: any): string[];
46
52
  * Render the carry note. PURE.
47
53
  * @param {{lastTry?: {step:string|null, kind:'step'|'fix', n:number|string|undefined, of?:number, ended:string, changed:string[]}|null,
48
54
  * lastCheck?: string|null, events: Ev[], edits?: {path:string, lines:number, hunks:string[]}[],
49
- * earlier?: string[], lastAsk?: number}} notes
55
+ * earlier?: string[], failures?: {label:string, text:string}[], lastAsk?: number,
56
+ * 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
50
57
  * @param {number} [cap]
51
58
  */
52
59
  export function render(notes: {
@@ -66,7 +73,12 @@ export function render(notes: {
66
73
  hunks: string[];
67
74
  }[];
68
75
  earlier?: string[];
76
+ failures?: {
77
+ label: string;
78
+ text: string;
79
+ }[];
69
80
  lastAsk?: number;
81
+ fnRanges?: Record<string, string>;
70
82
  }, cap?: number): {
71
83
  text: string;
72
84
  capped: boolean;
@@ -80,9 +92,10 @@ export function render(notes: {
80
92
  searches: number;
81
93
  edits: number;
82
94
  earlier: number;
95
+ failures: number;
83
96
  };
84
97
  };
85
- export const CAP: 3000;
98
+ export const CAP: 12000;
86
99
  export const HUNK_LINES: 40;
87
100
  export const HUNK_SHOW: 12;
88
101
  export const GAP_LINES: 8;
@@ -131,4 +144,8 @@ export type Entry = {
131
144
  * index of the newest call
132
145
  */
133
146
  recency: number;
147
+ /**
148
+ * the file's function line ranges (` · functions: a 1-5, b 7-9`), the FIRST thing the cap drops
149
+ */
150
+ fn?: string | undefined;
134
151
  };
@@ -1,10 +1,3 @@
1
- /**
2
- * The ONE setting: `carryNote` in config.json, read exactly like `learningHints` (src/learnstore.js `learningHintsOn`).
3
- * Absent = on; only an explicit `false` turns it off. An unreadable config reads as OFF (the safe side).
4
- * @param {string} [home]
5
- * @returns {boolean}
6
- */
7
- export function carryNoteOn(home?: string): boolean;
8
1
  /**
9
2
  * The run's edits from the working tree against the start commit: tracked (git diff) plus untracked (no diff exists).
10
3
  * Arbiter books / .git / .bareloop are excluded. Never throws; [] on any git failure.
@@ -42,11 +35,13 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume }: {
42
35
  name: string;
43
36
  execute: Function;
44
37
  }[]) => void;
45
- beginAsk: ({ phase, iteration, prompt }: {
38
+ beginAsk: ({ phase, iteration, prompt, getNode }: {
46
39
  phase: string;
47
40
  iteration: number | string | undefined;
48
41
  prompt: string;
42
+ getNode?: (rel: string) => any;
49
43
  }) => Promise<string>;
44
+ setStartFailure: (text: string) => void;
50
45
  endAsk: ({ bounded, iteration, rounds }: {
51
46
  bounded?: {
52
47
  iteration: any;
@@ -55,6 +50,7 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume }: {
55
50
  iteration: any;
56
51
  rounds: number;
57
52
  }) => void;
53
+ settleAsk: (result: "green" | "red" | "unknown", text?: string) => void;
58
54
  setBase: (b: string | null | undefined) => void;
59
55
  loaded: () => boolean;
60
56
  _state: () => {
@@ -65,5 +61,5 @@ export function createCarryStore({ workdir, emit, strikeLimit, resume }: {
65
61
  };
66
62
  };
67
63
  export const CARRY_DIR: "carry";
68
- /** the next prompt of a retried step / fix try carries this when the previous ask's check failed */
64
+ /** the retry marker the next prompt of a retried step / fix try carries; kept as a pinned fact about the prompts, no longer read to decide an outcome */
69
65
  export const RED_MARKER: RegExp;
package/types/config.d.ts CHANGED
@@ -36,10 +36,10 @@ export function modelsProblem(list: unknown): string | null;
36
36
  * `keys` merges per key variable name, then per field; `models.<ENV>` is REPLACED WHOLE (`null`
37
37
  * clears it). Validated before anything is written; nothing is written on a refusal.
38
38
  *
39
- * Patch fields understood: `monthlyLimitUsd` (finite > 0), `learningHints` (true | false), `carryNote` (true | false), `keys.<ENV>.{shape,baseUrl,legacyMaxTokens}`,
39
+ * Patch fields understood: `monthlyLimitUsd` (finite > 0), `learningHints` (true | false), `keys.<ENV>.{shape,baseUrl,legacyMaxTokens}`,
40
40
  * `models.<ENV>` (a list judged by {@link modelsProblem}). The first write of a row's `models` list
41
41
  * removes that row's older `name` / `priceInPerM` / `priceOutPerM` in the SAME write (never two
42
- * sources); a retired top-level `anthropicBalanceNote` is dropped on any write. Any other field is
42
+ * sources); the retired top-level `anthropicBalanceNote` and `carryNote` (the carry memo is always on, 2026-11-01) are dropped on any write. Any other field is
43
43
  * kept, but the whole document is swept for secret-shaped strings first.
44
44
  * @param {Record<string, any>} patch
45
45
  * @param {{ home?: string }} [opts]
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Every step part's and fix part's tries (and a cut-off try) gain `memo`: the carry-note record handed to that try, or null; a try whose text-only ending was nudged (spine `worker-text-only`, `nudged: true`) also gains `nudged: true`.
3
+ * Parts and tries are copied, never mutated. An outer-close try (no model call) never has one.
4
+ * @param {any[]|null|undefined} parts @param {any[]} records the run's spine records
5
+ */
6
+ export function attachMemos(parts: any[] | null | undefined, records: any[]): any[] | null | undefined;
7
+ /**
8
+ * The learnings the planner was handed, by injection: `draft` and `replan` (the first replan), each `{phase, text, chars, ids, hints}` or
9
+ * null, plus `error` (the plain line when the learnings file could not be read, else null).
10
+ * @param {any[]} records
11
+ */
12
+ export function learningsHanded(records: any[]): {
13
+ draft: {
14
+ phase: string;
15
+ text: any;
16
+ chars: any;
17
+ ids: any;
18
+ hints: import("../learn.js").HintParts[];
19
+ } | null;
20
+ replan: {
21
+ phase: string;
22
+ text: any;
23
+ chars: any;
24
+ ids: any;
25
+ hints: import("../learn.js").HintParts[];
26
+ } | null;
27
+ error: string | null;
28
+ };
29
+ /**
30
+ * Put the learnings on the parts that received them: the draft block (and the error line) on the drafting part, else the `plan` part;
31
+ * the first-replan block on the first `replan` part. `drafting` is the drafting part or null. Copies, never mutates.
32
+ * @param {any[]|null|undefined} parts the spine's own parts @param {any|null} drafting @param {ReturnType<typeof learningsHanded>} l
33
+ * @returns {{parts: any[]|null|undefined, drafting: any|null}}
34
+ */
35
+ export function attachLearnings(parts: any[] | null | undefined, drafting: any | null, l: ReturnType<typeof learningsHanded>): {
36
+ parts: any[] | null | undefined;
37
+ drafting: any | null;
38
+ };
@@ -1,5 +1,5 @@
1
1
  /** @typedef {{name: string, cls: 'machine check'|'judge'|null}} PlanCheck */
2
- /** @typedef {{n: number, text: string, rule: string, rules: string[], checks: PlanCheck[], refused: string[]}} PlanLine */
2
+ /** @typedef {{n: number, text: string, rule: string, rules: string[], checks: PlanCheck[], refused: string[], always?: string[]}} PlanLine */
3
3
  /** @typedef {{lines: PlanLine[], loose: PlanCheck[], notChecked: string[], readNotes: string[], alwaysOn: string[], older: boolean, goal?: string}} JobPlan */
4
4
  /**
5
5
  * `machine check` for a kind a command decides, `judge` for one that needs judgement; `null` for a stage whose kind is
@@ -57,6 +57,7 @@ export type PlanLine = {
57
57
  rules: string[];
58
58
  checks: PlanCheck[];
59
59
  refused: string[];
60
+ always?: string[];
60
61
  };
61
62
  export type JobPlan = {
62
63
  lines: PlanLine[];
package/types/plan.d.ts CHANGED
@@ -116,6 +116,24 @@ export function validatePlan(input: object | string, { job, maxStepRounds, scope
116
116
  reds: Red[];
117
117
  plan: object | null;
118
118
  };
119
+ /**
120
+ * F271 (B2) — pair a `write` grant with `edit`. A look-around step the drafter gave `write` but not `edit`, whose exits force a
121
+ * change to an existing big file, can pass only by a whole-file `write` (u-mvy4cd0d: src/gate.js 2433 lines to 1). Code adds the
122
+ * verb; the agent never asks for it, and it is added only when the SIGNED ceiling (`job.tools`, absent = the full menu) already
123
+ * offers `edit`, so the agent still cannot widen its own menu. `edit` is judged by the same `writeScope` fence as `write`: no
124
+ * authority a whole-file write did not have. No signed hash covers a plan, so none moves.
125
+ *
126
+ * A rubric step-file step is exempt: every path it declares (`target` plus the `artifact-written`/`json-valid` paths) lies under
127
+ * `newFileDir` (`output/steps`, the engine-owned always-new-file directory), so there is nothing to edit.
128
+ *
129
+ * Pure: never mutates `plan`; returns the SAME reference when nothing changes. `validatePlan` is untouched — the runner applies this
130
+ * to the validated plan, so `plan-accepted` records the plan as executed.
131
+ * @param {any} plan a validated plan (`validatePlan(...).plan`)
132
+ * @param {any} job the validateJob-green plan shape spec (its `tools` is the signed ceiling)
133
+ * @param {string|null} [newFileDir] the always-new-file directory whose steps are exempt, or null for none
134
+ * @returns {any} the plan with `edit` appended to each write-without-edit step, or `plan` itself
135
+ */
136
+ export function pairEditGrant(plan: any, job: any, newFileDir?: string | null): any;
119
137
  /** the closed exit menu (PRD v1.12 §3 + decision 1's `check-passes`): the
120
138
  * shell evaluates every form with its own fixed code, never a command — the
121
139
  * same both-directions inexpressibility guard as the two-validator split */
@@ -126,7 +144,7 @@ export const MAX_EXITS_PER_STEP: 2;
126
144
  /** a legal-example sentence for the exit menu — shown in the planner prompt and
127
145
  * appended to the missing-required exit red, so a redraft sees a legal shape,
128
146
  * not only the rule (F254: `exit` is required on EVERY step) */
129
- export const EXIT_EXAMPLE: "Legal exit examples: a step with no check uses [{\"type\":\"artifact-written\",\"path\":\"<its target>\"},{\"type\":\"tree-changed\",\"scope\":\"<an offered scope>\"}]; a step with a check uses [{\"type\":\"tree-changed\",\"scope\":\"<an offered scope>\"},{\"type\":\"check-passes\",\"name\":\"<a check name>\"}].";
147
+ export const EXIT_EXAMPLE: "Legal exit examples: a read-only look-around step (tools read, grep) uses [{\"type\":\"artifact-written\",\"path\":\"<an existing file the step reads>\"}]; a step that changes files and has no check uses [{\"type\":\"artifact-written\",\"path\":\"<its target>\"},{\"type\":\"tree-changed\",\"scope\":\"<an offered scope>\"}]; a step with a check uses [{\"type\":\"tree-changed\",\"scope\":\"<an offered scope>\"},{\"type\":\"check-passes\",\"name\":\"<a check name>\"}].";
130
148
  /** plan size bound — per-step rounds bound the spend, but an unbounded step
131
149
  * COUNT is still an unbounded claim on the wallet; same 8 as loop.maxIterations */
132
150
  export const MAX_PLAN_STEPS: 8;