opencode-self-improvement 0.23.0 → 0.24.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/init/run.ts CHANGED
@@ -1,18 +1,14 @@
1
1
  // run — split from src/init.ts (#168 domain restructure). Declaration bodies are unchanged.
2
2
  // Repository init: re-derive build/test command memories through the write gate
3
- // and store an init stamp keyed on git HEAD. Deterministic (no model calls):
3
+ // and record an init stamp keyed on git HEAD. Deterministic (no model calls):
4
4
  // manifests are parsed locally and every write goes through the 4-gate pipeline
5
5
  // with the `trusted` flag (plugin-authored bookkeeping, not model claims).
6
6
  // Degrades gracefully when git is absent, so install-from-scratch still writes
7
7
  // script memories. The codebase-memory graph integration was removed (#231).
8
+ // The stamp is a file under the memory root, not a memory row (#374): see
9
+ // src/init/stamp.ts for why a row was forgeable.
8
10
  import { basename } from "node:path";
9
- import { loadAll } from "../store/files/load.ts";
10
- import { markSuperseded } from "../store/files/supersede.ts";
11
- import {
12
- isVisibleTo,
13
- readerFromSid,
14
- type Reader,
15
- } from "../store/model/visibility.ts";
11
+ import { readerFromSid } from "../store/model/visibility.ts";
16
12
  import { runWriteGate, type GateContext } from "../gate/gate.ts";
17
13
  import { captureEvidenceContext, record } from "../evidence/record.ts";
18
14
  import { writeEvidence, hasGateCheck } from "../capture/triggers.ts";
@@ -25,6 +21,8 @@ import {
25
21
  gitHead,
26
22
  gitRootOf,
27
23
  } from "./detect.ts";
24
+ import { type RetagResult, retagQuarantinedRows } from "./retag.ts";
25
+ import { readStamp, writeStampFile } from "./stamp.ts";
28
26
 
29
27
  export interface InitArgs {
30
28
  liveRoot: string;
@@ -47,33 +45,18 @@ export interface InitSummary {
47
45
  blocked: number;
48
46
  /** Written rows whose write_promoted audit line fell (#155 review). */
49
47
  unaudited?: number;
50
- }
51
-
52
- export interface InitStamp {
53
- ts: string;
54
- head: string;
55
- }
56
-
57
- export async function initStamp(
58
- scope: string,
59
- sid?: string,
60
- reader: Reader = readerFromSid(sid),
61
- ): Promise<InitStamp | null> {
62
- // Scope is a basename, so two different repos can share one
63
- // ("api" next to "api", a fork beside its upstream). Visibility filtering
64
- // makes each repo see only its own stamp — basename collisions no longer
65
- // alias init state between repos. The reader comes from the CALLER's
66
- // session, not from the global current after this await (#127).
67
- const mems = (await loadAll()).filter(
68
- (m) => !m.superseded_by && isVisibleTo(m, reader),
69
- );
70
- for (const m of mems) {
71
- if (m.type !== "context" || m.scope !== scope) continue;
72
- if (!m.tags?.some((t) => t === "init-stamp")) continue;
73
- const head = /head=([^ ,]+)/.exec(m.content)?.[1] ?? "-";
74
- return { ts: m.ts, head };
75
- }
76
- return null;
48
+ /** The stamp file could not be written; init must be re-run (#374). */
49
+ stampError?: string;
50
+ /** True when a pre-#374 store row was honoured and copied to the file. */
51
+ stampMigrated?: boolean;
52
+ /**
53
+ * A honoured pre-#374 row is still active: its retirement did not land
54
+ * (#376 review). The migration itself is durable; the row is inert either
55
+ * way, and the operator hears about it instead of reading a clean migration.
56
+ */
57
+ stampRetireError?: string;
58
+ /** Pre-#372 rows re-tagged by the injection screen (#375). */
59
+ retag?: RetagResult;
77
60
  }
78
61
 
79
62
  export async function runInit(args: InitArgs): Promise<InitSummary> {
@@ -98,11 +81,43 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
98
81
  trusted: true,
99
82
  };
100
83
 
101
- const prior = await initStamp(scope, args.sessionID, reader);
84
+ // #375: repair rows written before #372 screened init's output. This runs
85
+ // BEFORE the stamp check on purpose — the common poisoned store belongs to a
86
+ // repository init has already stamped, and returning early would leave the
87
+ // poisoned row live forever. The scan is one store read and five regexes per
88
+ // row; writes happen only on a hit.
89
+ const retag = await retagQuarantinedRows(gateCtx);
90
+
91
+ // The stamp is read from (and written to) a file named for the repository
92
+ // identity key, never from a row a model could write (#374). The write target
93
+ // already holds that identity, so the common path spends no git probes here.
94
+ // Scope is still a basename, so two "api" checkouts stay apart: the key, not
95
+ // the name, decides which stamp a repository reads.
96
+ const stampKeyHint = writeAt.ok ? writeAt.scope?.key : undefined;
97
+ const {
98
+ stamp: prior,
99
+ key: stampKey,
100
+ migrated,
101
+ stampError: migrateStampError,
102
+ retireError,
103
+ } = await readStamp(scope, root, stampKeyHint, args.sessionID, reader);
102
104
  if (prior && !force && prior.head === head) {
103
105
  await record(
104
106
  "init_skip",
105
- { scope, head, since: prior.ts },
107
+ {
108
+ scope,
109
+ head,
110
+ since: prior.ts,
111
+ migrated: migrated || undefined,
112
+ // #376 review: a migration that honoured the row but could not write the
113
+ // file, or could not retire it, is a fault the skip line has to carry.
114
+ // Without it every later init re-migrates and re-claims success with no
115
+ // audit trail saying the file was never there.
116
+ stamp_error: migrateStampError,
117
+ stamp_retire_error: retireError,
118
+ retagged: retag.retagged || undefined,
119
+ retag_blocked: retag.blocked || undefined,
120
+ },
106
121
  false,
107
122
  args.sessionID,
108
123
  evidenceContext,
@@ -117,6 +132,10 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
117
132
  written: 0,
118
133
  collapsed: 0,
119
134
  blocked: 0,
135
+ stampError: migrateStampError,
136
+ stampMigrated: migrated || undefined,
137
+ stampRetireError: retireError,
138
+ retag,
120
139
  };
121
140
  }
122
141
 
@@ -159,31 +178,12 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
159
178
  else blocked++;
160
179
  }
161
180
 
162
- const stampContent = `Init stamp: repo=${scope}, head=${head}, scripts=${scripts.length}`;
163
- const stampOutcome = await runWriteGate(
164
- // Same screen as the script rows: the stamp interpolates the directory
165
- // basename, so an injection-shaped checkout name matches here too. Withheld
166
- // from recall, still readable by initStamp(), so idempotency is unaffected.
167
- quarantineCandidate({
168
- type: "context",
169
- scope,
170
- content: stampContent,
171
- tags: ["init-stamp"],
172
- }),
173
- gateCtx,
174
- );
175
- const stampTs = stampOutcome.ts ?? prior?.ts;
176
- if (stampOutcome.action === "promoted" && prior && stampOutcome.ts) {
177
- await markSuperseded(prior.ts, {
178
- superseded_by: stampOutcome.ts,
179
- reason: "init",
180
- });
181
- }
182
- if (
183
- stampOutcome.action === "promoted" &&
184
- stampOutcome.evidenceError !== undefined
185
- )
186
- unaudited++;
181
+ // The stamp is bookkeeping about this run, not a claim for the model to read,
182
+ // so it is a file rather than a gated row (#374). A fault is reported, never
183
+ // swallowed: the honest consequence is "init will run again", and saying so
184
+ // beats a stamp the operator believes was written.
185
+ const stampTs = new Date().toISOString();
186
+ const stampError = writeStampFile(stampKey, scope, root, head, stampTs);
187
187
 
188
188
  await record(
189
189
  "init_complete",
@@ -196,7 +196,21 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
196
196
  collapsed,
197
197
  blocked,
198
198
  unaudited,
199
- stamp: stampTs ?? "-",
199
+ stamp: stampError ? "-" : stampTs,
200
+ stamp_error: stampError,
201
+ // A migration that copied the row but could not retire it (#376 review).
202
+ stamp_retire_error: retireError,
203
+ migrated: migrated || undefined,
204
+ retagged: retag.retagged || undefined,
205
+ retag_blocked: retag.blocked || undefined,
206
+ retag_partial: retag.partial || undefined,
207
+ retag_failures: retag.failures.length
208
+ ? retag.failures.join("; ")
209
+ : undefined,
210
+ retag_remaining: retag.remaining || undefined,
211
+ retag_collateral: retag.collateral.length
212
+ ? retag.collateral.join(",")
213
+ : undefined,
200
214
  },
201
215
  false,
202
216
  args.sessionID,
@@ -208,11 +222,15 @@ export async function runInit(args: InitArgs): Promise<InitSummary> {
208
222
  root,
209
223
  head,
210
224
  scripts,
211
- stampTs,
225
+ stampTs: stampError ? (prior?.ts ?? undefined) : stampTs,
226
+ stampError,
227
+ stampMigrated: migrated || undefined,
228
+ stampRetireError: retireError,
212
229
  skipped: false,
213
230
  written,
214
231
  collapsed,
215
232
  blocked,
216
233
  unaudited,
234
+ retag,
217
235
  };
218
236
  }
@@ -0,0 +1,306 @@
1
+ // The init stamp: plugin-internal bookkeeping for /repo-init idempotency.
2
+ //
3
+ // It deliberately does NOT live in the memory store (#374). A store row is
4
+ // reachable through `memory_remember` and `memory_import`, and nothing reserved
5
+ // the `init-stamp` tag, so any session could write a `context` row naming the
6
+ // current short HEAD and make every later `memory_init` answer "Already
7
+ // initialized" for that commit — silently, with no line saying why. Moving the
8
+ // stamp to a file under the memory root that only src/init/ reads and writes
9
+ // closes that door, and it takes the row out of `memory_recall`, export and the
10
+ // viewer, where internal state was never meant to be read.
11
+ //
12
+ // A one-time migration keeps checkouts initialized by an older release from
13
+ // re-running init. Honouring "any row that looks like a stamp" is exactly the
14
+ // forgery this ticket removes, so the migration honours a legacy row only when an
15
+ // `init_complete` evidence line names its ts. Evidence is written only by the
16
+ // plugin's own record() — no tool hands a session a write path to it — so the
17
+ // pairing says a real init audited that row. A legacy row with no matching audit
18
+ // is ignored, and init re-runs: idempotent, cheap, and the safe answer to a
19
+ // provenance the plugin cannot check. A row that passes the pairing is copied to
20
+ // the file and then retired, and the head it is copied at is the head that
21
+ // evidence line names — never the head the row's own prose claims (#376 review).
22
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
23
+ import { join } from "node:path";
24
+ import { memoryRoot } from "../core/config/paths.ts";
25
+ import { INIT_STAMP_TAG } from "../core/tags.ts";
26
+ import { preparePrivateFile, tightenDirectory } from "../core/permissions.ts";
27
+ import { parseLine } from "../core/logfmt/format.ts";
28
+ import { readLines } from "../core/logfmt/read.ts";
29
+ import { evidenceFileFor } from "../evidence/record.ts";
30
+ import { resolveRepo } from "../identity/repokey.ts";
31
+ import { loadAll } from "../store/files/load.ts";
32
+ import { markSuperseded } from "../store/files/supersede.ts";
33
+ import {
34
+ isVisibleTo,
35
+ readerFromSid,
36
+ type Reader,
37
+ } from "../store/model/visibility.ts";
38
+
39
+ export interface InitStamp {
40
+ ts: string;
41
+ head: string;
42
+ }
43
+
44
+ /** Where the stamps live. A sibling directory of the day files, never one of them. */
45
+ export function stampDir(): string {
46
+ return join(memoryRoot(), "init-stamps");
47
+ }
48
+
49
+ // The file name is the repository identity key: a 12-hex-char token derived from
50
+ // the normalized origin (or the normalized path when there is no origin), so it
51
+ // survives a re-clone and never aliases two checkouts that merely share a
52
+ // directory basename. Validated anyway — a component the plugin did not mint is
53
+ // not authority to write outside the stamp directory.
54
+ function stampPath(key: string): string | null {
55
+ if (!/^[0-9a-f]{12}$/.test(key)) return null;
56
+ return join(stampDir(), `${key}.json`);
57
+ }
58
+
59
+ /**
60
+ * A stamp file's contents, checked against the file it came from.
61
+ *
62
+ * `key` must equal the file name: the name is the repository identity, so a file
63
+ * that landed in the wrong slot (a hand-edited store, a copy from another
64
+ * checkout) is not this repository's stamp. `scope` and `path` are descriptive
65
+ * only — nothing here locates state from them — so they are not validated.
66
+ */
67
+ function parseStamp(raw: string, key: string): InitStamp | null {
68
+ let data: unknown;
69
+ try {
70
+ data = JSON.parse(raw);
71
+ } catch {
72
+ return null;
73
+ }
74
+ if (typeof data !== "object" || data === null) return null;
75
+ const {
76
+ ts,
77
+ head,
78
+ key: fileKey,
79
+ } = data as {
80
+ ts?: unknown;
81
+ head?: unknown;
82
+ key?: unknown;
83
+ };
84
+ if (typeof ts !== "string" || typeof head !== "string") return null;
85
+ if (!ts || !head) return null;
86
+ if (fileKey !== key) return null;
87
+ return { ts, head };
88
+ }
89
+
90
+ function readStampFile(key: string): InitStamp | null {
91
+ const path = stampPath(key);
92
+ if (!path) return null;
93
+ let raw: string;
94
+ try {
95
+ raw = readFileSync(path, "utf8");
96
+ } catch {
97
+ // Absent, unreadable, or a directory. A file that cannot be read is treated
98
+ // like no stamp at all: init is idempotent, so re-running it is cheap, while
99
+ // trusting a stamp the plugin cannot parse is not.
100
+ return null;
101
+ }
102
+ return parseStamp(raw, key);
103
+ }
104
+
105
+ /**
106
+ * The day files an `init_complete` line for this row could live in.
107
+ *
108
+ * `appendMemory` stamps the row with the millisecond it mints; `record()` writes
109
+ * the evidence line to whatever day it is when the line lands. An init that
110
+ * starts at 23:59:59.999 and finishes after midnight splits the pair across two
111
+ * day files, so the row's own day is not enough — the following day has to be
112
+ * read too, or that migration is silently lost every night around midnight
113
+ * (#376 review).
114
+ */
115
+ function auditDays(ts: string): string[] {
116
+ const day = /^(\d{4}-\d{2}-\d{2})T/.exec(ts)?.[1];
117
+ if (!day) return [];
118
+ const next = new Date(`${day}T12:00:00.000Z`);
119
+ if (Number.isNaN(next.getTime())) return [day];
120
+ next.setUTCDate(next.getUTCDate() + 1);
121
+ return [day, next.toISOString().slice(0, 10)];
122
+ }
123
+
124
+ /**
125
+ * Did a real init audit this row, and at which head? The pre-#374 run wrote
126
+ * `stamp=<row ts>` and `head=<head>` into its `init_complete` evidence line, so
127
+ * the pairing is the provenance the row itself cannot supply. Parsed
128
+ * field-by-field: a value that merely contains the text cannot satisfy it.
129
+ *
130
+ * The head comes from the EVIDENCE LINE, never from the row's prose (#376
131
+ * review). `appendMemory` mints `ts` at millisecond resolution and `runInit`
132
+ * mints its stamp timestamp the same way, so two concurrent writes can land on
133
+ * the same millisecond — 42 of 480 rows did in the review's probe. Pairing on
134
+ * `stamp === ts` alone would then let a row that names one head retire a
135
+ * repository's idempotency at a different head, which is the forgery #374 was
136
+ * opened to close. Returns null when no line names this ts with a usable head.
137
+ */
138
+ async function initAuditHead(ts: string): Promise<string | null> {
139
+ for (const day of auditDays(ts)) {
140
+ const file = evidenceFileFor(day);
141
+ if (!file) continue;
142
+ let lines: string[];
143
+ try {
144
+ lines = await readLines(file);
145
+ } catch {
146
+ continue;
147
+ }
148
+ for (const line of lines) {
149
+ const fields = parseLine(line);
150
+ if (!fields) continue;
151
+ if (fields.ev !== "init_complete" || fields.stamp !== ts) continue;
152
+ const head = fields.head;
153
+ if (typeof head !== "string" || !head) continue;
154
+ return head;
155
+ }
156
+ }
157
+ return null;
158
+ }
159
+
160
+ /** The pre-#374 stamp: a `context` row in this scope tagged `init-stamp`. */
161
+ async function legacyStampRow(
162
+ scope: string,
163
+ reader: Reader,
164
+ ): Promise<InitStamp | null> {
165
+ const mems = (await loadAll()).filter(
166
+ (m) => !m.superseded_by && isVisibleTo(m, reader),
167
+ );
168
+ for (const m of mems) {
169
+ if (m.type !== "context" || m.scope !== scope) continue;
170
+ if (!m.tags?.some((t) => t === INIT_STAMP_TAG)) continue;
171
+ const head = await initAuditHead(m.ts);
172
+ if (head === null) continue;
173
+ return { ts: m.ts, head };
174
+ }
175
+ return null;
176
+ }
177
+
178
+ export interface StampRead {
179
+ stamp: InitStamp | null;
180
+ /** The repository identity key the stamp file is (or would be) named for. */
181
+ key: string;
182
+ /** True when a pre-#374 store row was honoured and copied to the file. */
183
+ migrated: boolean;
184
+ /**
185
+ * The migration copy could not be written (#376 review). The row was still
186
+ * honoured, so init stays idempotent for this run, but nothing was recorded:
187
+ * the caller must report it the way a failed stamp write is reported, or every
188
+ * later init re-migrates and re-claims success.
189
+ */
190
+ stampError?: string;
191
+ /**
192
+ * The honoured row is still active (#376 review): its retirement was refused
193
+ * or threw. The migration is not lost — the file answers the next read — but
194
+ * the store keeps a row the operator should hear about.
195
+ */
196
+ retireError?: string;
197
+ }
198
+
199
+ /**
200
+ * The stamp for one repository.
201
+ *
202
+ * `root` is the repository root init resolved. `keyHint` is the identity the
203
+ * caller already holds (its write target), so a normal init pays no second pair
204
+ * of git probes; with neither, identity is resolved from `root`.
205
+ *
206
+ * Order: the file, then one audited legacy row (honoured once, then migrated).
207
+ * Returns `stamp: null` when neither applies.
208
+ */
209
+ export async function readStamp(
210
+ scope: string,
211
+ root: string,
212
+ keyHint?: string,
213
+ sid?: string,
214
+ reader: Reader = readerFromSid(sid),
215
+ ): Promise<StampRead> {
216
+ const key =
217
+ keyHint && /^[0-9a-f]{12}$/.test(keyHint) ? keyHint : resolveRepo(root).key;
218
+ const file = readStampFile(key);
219
+ if (file) return { stamp: file, key, migrated: false };
220
+ const legacy = await legacyStampRow(scope, reader);
221
+ if (!legacy) return { stamp: null, key, migrated: false };
222
+ const stampError = writeStampFile(key, scope, root, legacy.head, legacy.ts);
223
+ return {
224
+ stamp: legacy,
225
+ key,
226
+ migrated: true,
227
+ ...(stampError ? { stampError } : {}),
228
+ ...(await retireLegacyStampRow(legacy.ts)),
229
+ };
230
+ }
231
+
232
+ /**
233
+ * Retire the row a migration just copied (#376 review). The stamp lives in the
234
+ * file now, so leaving the row active would keep a piece of plugin bookkeeping in
235
+ * the store as an ordinary row; `isInjectable` already withholds the tag from
236
+ * every model-facing read, and this takes it out of the store's active set too.
237
+ *
238
+ * A refusal never undoes the migration: the copy above is what makes init
239
+ * idempotent, and the row is inert either way. The reason is returned for the
240
+ * caller to report, in the same shape retag.ts uses for a retirement that did
241
+ * not land — the operator hears which half failed instead of reading a clean
242
+ * migration.
243
+ */
244
+ async function retireLegacyStampRow(
245
+ ts: string,
246
+ ): Promise<{ retireError?: string }> {
247
+ try {
248
+ const retired = await markSuperseded(ts, {
249
+ superseded_by: "init-stamp-file",
250
+ reason: "init",
251
+ });
252
+ if (retired) return {};
253
+ // Idempotence means the row was already retired out of band, or it is gone.
254
+ // Either way the store did not take the retirement this run asked for.
255
+ return { retireError: `${ts}: retirement did not land` };
256
+ } catch (err) {
257
+ return {
258
+ retireError: `${ts}: ${
259
+ err instanceof Error && err.message ? err.message : String(err)
260
+ }`,
261
+ };
262
+ }
263
+ }
264
+
265
+ /**
266
+ * Record that `scope` was initialized at `head`.
267
+ *
268
+ * Best-effort by contract: a store on a read-only mount must not fail an init
269
+ * whose command rows already landed, so a fault is returned for the caller to
270
+ * report rather than thrown. The consequence of a fault is one re-run of an
271
+ * idempotent command, never a silently skipped init.
272
+ */
273
+ export function writeStampFile(
274
+ key: string,
275
+ scope: string,
276
+ root: string,
277
+ head: string,
278
+ ts: string,
279
+ ): string | undefined {
280
+ const path = stampPath(key);
281
+ if (!path) return "stamp key is not a repository identity token";
282
+ try {
283
+ mkdirSync(stampDir(), { recursive: true, mode: 0o700 });
284
+ tightenDirectory(stampDir());
285
+ preparePrivateFile(path);
286
+ // Per-call temp name (#89): two inits on one store must never rename each
287
+ // other's half-written temp over a stamp.
288
+ const tmp = `${path}.${process.pid}.${Date.now()}.tmp`;
289
+ writeFileSync(
290
+ tmp,
291
+ `${JSON.stringify({ key, scope, path: root, head, ts })}\n`,
292
+ {
293
+ mode: 0o600,
294
+ },
295
+ );
296
+ renameSync(tmp, path);
297
+ return undefined;
298
+ } catch (err) {
299
+ return err instanceof Error && err.message ? err.message : String(err);
300
+ }
301
+ }
302
+
303
+ /** The identity key init stamps a repository under (exported for tests). */
304
+ export function stampKey(root: string): string {
305
+ return resolveRepo(root).key;
306
+ }
@@ -38,6 +38,8 @@ interface InjectionEpochOptions {
38
38
  // The host listener records usage. Eviction must still drop it with the
39
39
  // epoch and request counters, so no measurement outlives its tracked session.
40
40
  measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
41
+ /** Evict the per-message usage ledger (#394) with the session. */
42
+ forgetUsage?: (sid: string) => void;
41
43
  noteHits: (sid: string, rows: Memory[], query: string) => Promise<void>;
42
44
  }
43
45
 
@@ -46,6 +48,7 @@ export function createInjectionEpochs({
46
48
  frontierBudget: openBudget,
47
49
  contradictionSurface = true,
48
50
  measuredTurns,
51
+ forgetUsage,
49
52
  noteHits,
50
53
  }: InjectionEpochOptions) {
51
54
  // Per-session frozen injection epochs: the whole memory section (digest +
@@ -106,6 +109,7 @@ export function createInjectionEpochs({
106
109
  latestPrompt.delete(sid);
107
110
  sessionStats.delete(sid);
108
111
  measuredTurns.delete(sid);
112
+ forgetUsage?.(sid);
109
113
  });
110
114
  const statsFor = (sid: string): SessionStats => {
111
115
  let st = sessionStats.get(sid);
@@ -203,6 +207,11 @@ export function createInjectionEpochs({
203
207
  undefined,
204
208
  {
205
209
  guidedCap: 3,
210
+ // #388: budget the RIDING set by priority here, before the block is
211
+ // rendered in canonical order. Capping the rendered string (the old
212
+ // path) made recency decide who got dropped, because the newest row is
213
+ // now always first.
214
+ budget,
206
215
  ...(contradictionSurface
207
216
  ? {
208
217
  conflictCheck: true,
@@ -211,6 +220,14 @@ export function createInjectionEpochs({
211
220
  : {}),
212
221
  },
213
222
  );
223
+ // UNREACHABLE today, not a guard: `selectRelevant` was handed the same
224
+ // `budget` and builds the block as header + Σ(1 + line) over lines it
225
+ // accepted while that running sum stayed ≤ budget, and every line length is
226
+ // non-negative. So a non-empty `sel.block` is already ≤ budget, capToBudget
227
+ // keeps every line, and this call returns its argument unchanged. No test
228
+ // can reach a different result; it stays only as a byte bound on the text
229
+ // that rides the prompt if a future caller stops budgeting inside the
230
+ // selector.
214
231
  const block = sel.block ? capToBudget(sel.block, budget) : "";
215
232
  // Refs the ACTUALLY-injected rows assert (paths + commands), the join key
216
233
  // for attribution. Derived from the budget-surviving rows, not the wider
@@ -328,7 +345,8 @@ export function createInjectionEpochs({
328
345
  // Hint-channel attribution (mystery 2): a wire miss is one grep away.
329
346
  // guidedSeen=0 -> capture never wrote the row. guidedSeen>0 with the
330
347
  // id absent from `guided` -> the cap (newest-first, 3) dropped it.
331
- // In `guided` but absent from `guidedRode` -> capToBudget dropped it.
348
+ // In `guided` but absent from `guidedRode` -> the budget inside
349
+ // selectRelevant dropped it (#388 moved the cap there from capToBudget).
332
350
  // In `guidedRode` yet absent from the wire -> render/transport, or a
333
351
  // paraphrased needle (now impossible for rows carrying `orig=true`).
334
352
  ...(built.guidedSeen ? { guidedSeen: built.guidedSeen } : {}),