opencode-self-improvement 0.24.2 → 0.26.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.
@@ -0,0 +1,767 @@
1
+ // #389: capture spends its budget on facts the next session cannot obtain any
2
+ // other way.
3
+ //
4
+ // Measured (FINDINGS 2026-11-10, base3 vs base4): reuse does not pay — six pairs,
5
+ // every arm 6/6, median L2/L0 0.98x — while transport does: an empty store 0/5,
6
+ // the same store seeded 5/5. The difference is not "interesting" and not
7
+ // "durable". It is whether the next session could get the fact by itself. Capture
8
+ // had no notion of that question, and at roughly a third of a session's own
9
+ // generation a row that changes nothing is not free.
10
+ //
11
+ // Two availability questions are answerable by a CODE PATH, with no prompt and no
12
+ // model call, which is what #389 criterion 1 demands:
13
+ //
14
+ // 1. Is this text already in the working tree? A row that restates a tracked
15
+ // file is readable there by the next session.
16
+ // 2. Is this command already declared by the project's own gates? A row that
17
+ // says "run `make deploy`" is answered by the Makefile.
18
+ //
19
+ // Both produce a TAG, not a refusal (#402). Four adversarial review rounds on
20
+ // #397 each found the same defect — text that was merely short or partly matched
21
+ // was read as already known — and each round patched one instance. Measured
22
+ // against this repo's live store: the original rule refused 30 of 1166 real
23
+ // captured rows and 29 of those were wrong (the note "OpenCode V2 (v2.0.26) does
24
+ // NOT run LSP servers" was refused because it contained the string `bun test` and
25
+ // this project declares a `test` script). The hardened rule refuses 0 of 1166. A
26
+ // check nobody can trust enough to delete with, and nobody can make cheap enough
27
+ // to skip, must not decide anything on its own.
28
+ //
29
+ // So the verdict is now evidence attached to a row that is stored anyway:
30
+ //
31
+ // - it cannot drop a row, so a wrong match costs a tag instead of a fact;
32
+ // - every claim is checked, not sampled: one unchecked clause is enough to make
33
+ // the row new, and the unchecked part is where the new fact lives;
34
+ // - polarity and numbers are VETOES, not evidence: they can only decline to
35
+ // tag, never create one. The number check is the house `numericTokens` set
36
+ // from `core/tokenize.ts`; see the two vetoes below for why the polarity
37
+ // check keeps its own cue list as well.
38
+ //
39
+ // The vetoes can only REMOVE a tag, never add one — which holds only because the
40
+ // one place that compares two texts, `findClause`, compares them on the narrow
41
+ // cue list. Widen that comparison and agreement gets easier, and an agreement is
42
+ // what creates a tag; see VETO 1. Saltzer & Schroeder's fail-safe principle,
43
+ // applied to a suppression filter: the default is keep, and a bug must surface as
44
+ // a visible duplicate rather than as content that is gone.
45
+ //
46
+ // A wrong tag is not free either. The row survives, but `fitOrder` gives it up
47
+ // first when the injection budget binds, so a false positive costs the row its
48
+ // slot for the queries that needed it. That is the real price of a bad verdict,
49
+ // and it is why the matcher is still held to the veto-only shape.
50
+ //
51
+ // Storing instead of deleting has a second consequence, and it is not a tag
52
+ // effect. A stored row is a live GATE-3 contender, so a later write at >=0.9
53
+ // overlap is now refused `superseded_overlap` where the delete policy would have
54
+ // let it promote. Measured: an ordinary-tagged seed blocks the same write with
55
+ // the same reason, so the tag changes nothing in the gate — the row being there
56
+ // does. That is the gate working as designed on a genuine near-duplicate, with a
57
+ // hint naming the row to `memory_update`, and it is the cost of no longer
58
+ // destroying facts. P5 decides whether the check earns its keep at all.
59
+ //
60
+ // Fail-open is the rule throughout. A missing git, an unreadable file, a repo
61
+ // that is not a repo, or a budget that ran out is NOT evidence that a fact is
62
+ // available — refusing on those would lose the transport win, which is the one
63
+ // measured benefit capture has. Every uncertainty keeps the candidate.
64
+ import { lstatSync, readFileSync } from "node:fs";
65
+ import { join, relative } from "node:path";
66
+ import { POL_NEG, numericTokens, polaritySigns } from "../core/tokenize.ts";
67
+ import { redactSecrets } from "../store/secrets.ts";
68
+
69
+ /** What made a candidate restatable, and where the next session can get it. */
70
+ export type AvailabilityVerdict = {
71
+ reason: "in_tracked_file" | "declared_gate";
72
+ /** Repo-relative file, or the gate's location (`package.json scripts.test`). */
73
+ where: string;
74
+ /** The span that matched, for the evidence line. */
75
+ matched: string;
76
+ };
77
+
78
+ // Tokens that carry no claim of their own: function words, and the handful of
79
+ // verbs whose whole meaning is "this command gets run". A fragment made of
80
+ // nothing but these is a MENTION, and a mention is what the manifest already
81
+ // declares. Everything else is a claim, however short it is — `never` is five
82
+ // characters and it is the entire fact (#397 round 4, WhollyMindless: the length
83
+ // cutoff dropped `Never` and refused the prohibition).
84
+ //
85
+ // This is a whitelist for FILLER, which is the only direction a word list can
86
+ // safely go: a word left off it is read as a claim and the row is kept. The
87
+ // RESTRICTION list this replaces whitelisted what counted as NEW, so every word
88
+ // missing from it lost a fact — that is the defect round 3 reported.
89
+ //
90
+ // Temporal and conditional words (before, after, until, unless, when, if, only,
91
+ // once) and every modal are deliberately absent: they state a condition, and a
92
+ // manifest declares THAT a command exists, never when it may be run.
93
+ const FILLER = new Set([
94
+ // function words
95
+ "a",
96
+ "an",
97
+ "the",
98
+ "this",
99
+ "that",
100
+ "these",
101
+ "those",
102
+ "and",
103
+ "or",
104
+ "but",
105
+ "so",
106
+ "of",
107
+ "to",
108
+ "in",
109
+ "on",
110
+ "at",
111
+ "by",
112
+ "for",
113
+ "with",
114
+ "from",
115
+ "as",
116
+ "than",
117
+ "it",
118
+ "its",
119
+ "us",
120
+ "we",
121
+ "our",
122
+ "you",
123
+ "your",
124
+ "they",
125
+ "their",
126
+ "them",
127
+ "he",
128
+ "she",
129
+ "i",
130
+ "me",
131
+ "my",
132
+ "is",
133
+ "are",
134
+ "am",
135
+ "was",
136
+ "were",
137
+ "be",
138
+ "been",
139
+ "being",
140
+ "do",
141
+ "does",
142
+ "did",
143
+ "have",
144
+ "has",
145
+ "had",
146
+ // mention verbs: "ship with X", "run X", "use X" say only that X is there
147
+ "run",
148
+ "runs",
149
+ "running",
150
+ "use",
151
+ "uses",
152
+ "using",
153
+ "ship",
154
+ "ships",
155
+ "shipping",
156
+ "deploy",
157
+ "deploys",
158
+ "deploying",
159
+ "call",
160
+ "calls",
161
+ "calling",
162
+ "invoke",
163
+ "invokes",
164
+ "invoking",
165
+ "execute",
166
+ "executes",
167
+ "executing",
168
+ ]);
169
+
170
+ // Assertion boundaries: the edges of the one sentence a match is judged inside.
171
+ // The candidate is split on these, and the text in the tree is walked back to
172
+ // them (#397 round 3). Code 0 is the joiner the scan puts between tracked
173
+ // files, so a clause can never match across two of them.
174
+ function isBoundary(code: number): boolean {
175
+ return (
176
+ code === 46 || // .
177
+ code === 59 || // ;
178
+ code === 58 || // :
179
+ code === 44 || // ,
180
+ code === 10 || // newline
181
+ code === 0 // the file joiner
182
+ );
183
+ }
184
+
185
+ // Words that reverse an assertion. This is deliberately NOT the RESTRICTION
186
+ // list it replaces. That list tried to decide whether a candidate says anything
187
+ // NEW, and an open vocabulary can never do that (#397 round 3, WhollyMindless):
188
+ // any word left off the list reopens the class. This one answers one closed
189
+ // question — does the sentence the tree states have the same POLARITY as the
190
+ // clause matched inside it? `We do not use tabs` and `Use tabs` are not the
191
+ // same assertion, and a gate that cannot tell them apart stores the reversal of
192
+ // the rule it was reading.
193
+ const NEGATION =
194
+ /\b(no|not|nor|never|none|cannot|can'?t|don'?t|doesn'?t|didn'?t|won'?t|isn'?t|aren'?t|without|lacks?|lacking|absent|avoid\w*|prohibit\w*|forbid\w*|disallow\w*|refrain\w*|refuses?|instead of|rather than)\b/;
195
+
196
+ /**
197
+ * VETO 1 (#402): is this sentence reversed?
198
+ *
199
+ * Two sources, unioned, because they answer different questions:
200
+ *
201
+ * - `NEGATION`, the cue list: "we do NOT use tabs" is negated prose.
202
+ * - `core/tokenize.ts`'s `polaritySigns`, which is NOT a negation detector and
203
+ * must not be used as one. It extracts the SIGNED PREDICATES a text asserts
204
+ * for the contradiction surface, so "we do not use tabs" returns `[]` —
205
+ * `use` is not a table term. Substituting it for the cue list would have
206
+ * compared `[]` with `[]`, matched, and re-opened the exact round-3 defect
207
+ * this regex was written to close. What it adds here is the part a cue list
208
+ * cannot see: the antonym pairs and the dual-role "never", so "must never
209
+ * disable" and "enable" do not read as the same claim.
210
+ *
211
+ * USE THIS ONLY WHERE THE ANSWER IS ABSOLUTE. `forbidsCommand` asks "does this
212
+ * sentence forbid the command?" and a yes declines to tag, so widening it can
213
+ * only ever decline — the fail-safe direction.
214
+ *
215
+ * The relative use, where one text's polarity is compared with another's, is
216
+ * `cueNegated`, and the difference is not academic. Equality gets EASIER as both
217
+ * predicates get broader, and in `findClause` an agreement is what CREATES the
218
+ * tag. Measured on the round-3 case: tree `Do not assume the cleaner removes
219
+ * unused rows.`, candidate `The cleaner removes unused rows.` — `polaritySigns`
220
+ * reads the dual-role `removes` as negative in BOTH strings, the union agrees,
221
+ * and the affirmative claim is tagged as restating the sentence that warns
222
+ * against it. The cue list alone sees `not` on one side and nothing on the other
223
+ * and declines. That is the defect this veto exists for, arriving from the
224
+ * opposite direction.
225
+ */
226
+ function negated(text: string): boolean {
227
+ return NEGATION.test(text) || polaritySigns(text).includes(POL_NEG);
228
+ }
229
+
230
+ /**
231
+ * Cue-list polarity, for the one place that COMPARES two texts. Narrow on
232
+ * purpose: a broader predicate here agrees more often, and every extra agreement
233
+ * is a tag.
234
+ */
235
+ function cueNegated(text: string): boolean {
236
+ return NEGATION.test(text);
237
+ }
238
+
239
+ /**
240
+ * VETO 2 (#402): a figure the matched declaration does not carry.
241
+ *
242
+ * `core/tokenize.ts` states the rule and `store/tombstones/tombstone.ts`
243
+ * measures it on this repo's own data: a correction scores HIGHER than an honest
244
+ * rewording, so overlap alone cannot separate "the same fact again" from "the
245
+ * fact has changed". On the declared-command path the manifest states only that
246
+ * a command exists, so any number the row asserts has to be in the command
247
+ * itself or the row is new.
248
+ */
249
+ function introducesNewNumber(text: string, matched: string): boolean {
250
+ const known = new Set(numericTokens(matched));
251
+ for (const n of numericTokens(text)) if (!known.has(n)) return true;
252
+ return false;
253
+ }
254
+ // The scan is bounded by bytes, not files: a monorepo's tracked list is huge and
255
+ // the point is a cheap check, not an index. One capture pass already pays for a
256
+ // model call, which costs far more than this.
257
+ const TOTAL_CAP = 2 * 1024 * 1024;
258
+ const MAX_FILE_BYTES = 256 * 1024;
259
+ const MAX_LIST_FILES = 20_000;
260
+ const LIST_TIMEOUT_MS = 2_000;
261
+
262
+ // Docs and config carry restated facts far more often than source does, so they
263
+ // are read first and are the first to consume the byte budget.
264
+ const PRIORITY = [
265
+ ".md",
266
+ ".mdx",
267
+ ".txt",
268
+ ".adoc",
269
+ ".json",
270
+ ".jsonc",
271
+ ".yaml",
272
+ ".yml",
273
+ ".toml",
274
+ ];
275
+ const TEXT_EXTENSIONS = new Set([
276
+ ...PRIORITY,
277
+ ".ts",
278
+ ".tsx",
279
+ ".js",
280
+ ".mjs",
281
+ ".cjs",
282
+ ".jsx",
283
+ ".go",
284
+ ".py",
285
+ ".rs",
286
+ ".rb",
287
+ ".java",
288
+ ".kt",
289
+ ".c",
290
+ ".h",
291
+ ".cc",
292
+ ".sh",
293
+ ".bash",
294
+ ".sql",
295
+ ".css",
296
+ ".html",
297
+ ]);
298
+ const SKIP_DIRS = new Set(["node_modules", ".git", "dist", "build", "vendor"]);
299
+
300
+ /**
301
+ * Normalise for a "same words, different wrapping" comparison: case, markdown
302
+ * emphasis and backticks, and runs of whitespace. This is verbatim modulo
303
+ * formatting, and the evidence line says so rather than claiming fuzzy matching.
304
+ */
305
+ function norm(s: string): string {
306
+ return s.toLowerCase().replace(/[*_`]/g, "").replace(/\s+/g, " ").trim();
307
+ }
308
+
309
+ function extOf(name: string): string {
310
+ const dot = name.lastIndexOf(".");
311
+ return dot >= 0 ? name.slice(dot).toLowerCase() : "";
312
+ }
313
+
314
+ function listed(repoDir: string): string[] | null {
315
+ let p: ReturnType<typeof Bun.spawnSync>;
316
+ try {
317
+ p = Bun.spawnSync(["git", "ls-files", "-z"], {
318
+ cwd: repoDir,
319
+ stdout: "pipe",
320
+ stderr: "pipe",
321
+ timeout: LIST_TIMEOUT_MS,
322
+ });
323
+ } catch {
324
+ return null;
325
+ }
326
+ if (p.exitCode !== 0) return null;
327
+ const out = p.stdout?.toString() ?? "";
328
+ if (!out.trim()) return [];
329
+ return out.split("\0").filter(Boolean).slice(0, MAX_LIST_FILES);
330
+ }
331
+
332
+ interface Slice {
333
+ file: string;
334
+ start: number;
335
+ end: number;
336
+ }
337
+
338
+ /** Declared gates: a command the project already runs, and where it is declared. */
339
+ interface Gate {
340
+ label: string;
341
+ where: string;
342
+ }
343
+
344
+ function readTracked(repoDir: string, file: string): string | null {
345
+ const p = join(repoDir, file);
346
+ try {
347
+ const st = lstatSync(p);
348
+ if (!st.isFile() || st.size > MAX_FILE_BYTES) return null;
349
+ return readFileSync(p, "utf8");
350
+ } catch {
351
+ return null;
352
+ }
353
+ }
354
+
355
+ function skipPath(file: string): boolean {
356
+ return file.split("/").some((seg) => SKIP_DIRS.has(seg));
357
+ }
358
+
359
+ function parseGates(repoDir: string, files: string[]): Gate[] {
360
+ const gates: Gate[] = [];
361
+ const add = (label: string, where: string) => {
362
+ const n = norm(label);
363
+ if (n.length >= 2 && n.length <= 80) gates.push({ label: n, where });
364
+ };
365
+ for (const file of files) {
366
+ if (skipPath(file)) continue;
367
+ const base = file.slice(file.lastIndexOf("/") + 1);
368
+ const text =
369
+ base === "package.json" ||
370
+ base === "Makefile" ||
371
+ base === "makefile" ||
372
+ base === "justfile" ||
373
+ /^\.github\/workflows\/.+\.ya?ml$/.test(file)
374
+ ? readTracked(repoDir, file)
375
+ : null;
376
+ if (text === null) continue;
377
+ if (base === "package.json") {
378
+ try {
379
+ const pkg = JSON.parse(text) as { scripts?: Record<string, string> };
380
+ for (const [name, cmd] of Object.entries(pkg.scripts ?? {})) {
381
+ add(name, `${file} scripts.${name}`);
382
+ if (typeof cmd === "string") add(cmd, `${file} scripts.${name}`);
383
+ }
384
+ } catch {
385
+ // An unparseable manifest is not evidence of absence.
386
+ }
387
+ continue;
388
+ }
389
+ if (base === "Makefile" || base === "makefile" || base === "justfile") {
390
+ for (const line of text.split("\n")) {
391
+ const target = /^([A-Za-z0-9_.%-]+)\s*:(?!=)/.exec(line);
392
+ if (target?.[1]) add(target[1], `${file} target ${target[1]}`);
393
+ const recipe = /^\t+([^\s].*)$/.exec(line);
394
+ if (recipe?.[1]) add(recipe[1], `${file} recipe`);
395
+ }
396
+ continue;
397
+ }
398
+ for (const line of text.split("\n")) {
399
+ const run = /^\s*-?\s*run:\s*["']?(.+?)["']?\s*$/.exec(line);
400
+ if (run?.[1]) add(run[1], `${file} run`);
401
+ }
402
+ }
403
+ return gates;
404
+ }
405
+
406
+ /** Commands a row states: the backticked spans, which is how this plugin writes them. */
407
+ function statedCommands(content: string): string[] {
408
+ const spans: string[] = [];
409
+ const re = /`([^`\n]{2,60})`/g;
410
+ let m = re.exec(content);
411
+ while (m) {
412
+ const span = m[1]?.trim();
413
+ if (span && /^[A-Za-z][A-Za-z0-9_.@:/-]*(?:[ =][^\s`]+)*$/.test(span))
414
+ spans.push(span);
415
+ m = re.exec(content);
416
+ }
417
+ return spans;
418
+ }
419
+
420
+ /** Strip the runner so `bun run test` and the script named `test` are the same thing. */
421
+ function runners(span: string): string[] {
422
+ const forms = [norm(span)];
423
+ const stripped = norm(span).replace(
424
+ /^(?:bun(?:x| run)?|npm (?:run|exec)|pnpm (?:run|exec)|yarn|make|task)\s+/,
425
+ "",
426
+ );
427
+ if (stripped && stripped !== forms[0]) forms.push(stripped);
428
+ return forms;
429
+ }
430
+
431
+ // Matching is positional, never substring. A gate named `all` must not refuse a
432
+ // row that says `install all deps`, and `test` must not refuse a row about
433
+ // "the test suite". So a single-word gate (a script name, a make target) only
434
+ // matches the OPERAND position — the first token after the runner is stripped —
435
+ // and a multi-word gate (a declared command) matches whole.
436
+ function gateHit(spans: string[], gates: Gate[]): Gate | null {
437
+ for (const span of spans) {
438
+ for (const form of runners(span)) {
439
+ const first = form.split(" ")[0] ?? "";
440
+ for (const g of gates) {
441
+ if (form === g.label) return g;
442
+ if (!g.label.includes(" ") && first === g.label) return g;
443
+ if (
444
+ g.label.includes(" ") &&
445
+ (form.startsWith(`${g.label} `) || form.endsWith(` ${g.label}`))
446
+ )
447
+ return g;
448
+ }
449
+ }
450
+ }
451
+ return null;
452
+ }
453
+
454
+ /**
455
+ * The assertions in a normalised text: the fragments left after splitting on the
456
+ * sentence boundaries, minus the ones that state nothing.
457
+ *
458
+ * "States nothing" is the FILLER test, not a length. #397 round 4
459
+ * (WhollyMindless): the cutoff here was 16 characters, so `Never` was dropped
460
+ * from `Never \`npm run deploy\`.` and an empty list was then read as proof that
461
+ * the whole candidate was restatable. A short fragment is where a prohibition, a
462
+ * window or a number lives; punctuation and "ship with" are what a fragment has
463
+ * to be before it is ignored.
464
+ */
465
+ function claims(text: string): string[] {
466
+ const out: string[] = [];
467
+ for (const part of text.split(/[.;:,\n]/)) {
468
+ const c = part.trim();
469
+ if (!c) continue;
470
+ const words = c.split(/[^a-z0-9']+/).filter(Boolean);
471
+ if (words.length === 0) continue;
472
+ if (words.every((w) => FILLER.has(w))) continue;
473
+ out.push(c);
474
+ }
475
+ return out;
476
+ }
477
+
478
+ /**
479
+ * Does a sentence that states one of `commands` also FORBID it? Judged on those
480
+ * sentences alone: the manifest says a command exists, so "Never run `x`" is a
481
+ * claim the manifest does not make, while a prohibition in an unrelated clause is
482
+ * that clause's business and the claim check handles it.
483
+ *
484
+ * The bare words are here because `polaritySigns` reads `never` as a modifier
485
+ * that needs a verb, and "Never `npm run deploy`." has the verb inside a code
486
+ * span. A closed list, answering one closed question, over a decision that can
487
+ * now only decline to tag.
488
+ */
489
+ function forbidsCommand(content: string, commands: string[]): boolean {
490
+ for (const sentence of content.split(/[.;:\n]+/)) {
491
+ if (!commands.some((c) => sentence.includes(c))) continue;
492
+ if (
493
+ negated(sentence) ||
494
+ /\b(never|avoid\w*|prohibit\w*|forbid\w*)\b/i.test(sentence)
495
+ )
496
+ return true;
497
+ }
498
+ return false;
499
+ }
500
+
501
+ /** The whole sentence around `start .. start+len`, with the offset it starts at. */
502
+ function sentenceSpan(
503
+ text: string,
504
+ start: number,
505
+ len: number,
506
+ ): { text: string; at: number } {
507
+ let a = start;
508
+ while (a > 0 && !isBoundary(text.charCodeAt(a - 1))) a--;
509
+ let b = start + len;
510
+ while (b < text.length && !isBoundary(text.charCodeAt(b))) b++;
511
+ return { text: text.slice(a, b), at: a };
512
+ }
513
+
514
+ /**
515
+ * VETO 1b (#403 review): does this prefix WARN AGAINST the claim that follows?
516
+ *
517
+ * `Stop assuming the cache supports TTL expiration.` contains the affirmative
518
+ * sentence `The cache supports TTL expiration.` as the object of `stop assuming`.
519
+ * A substring test plus cue equality merges a warning with the claim it warns
520
+ * against, because the cue list carries neither `stop` nor `drop` — and neither
521
+ * does `polaritySigns`, so widening it the way an earlier round tried does not
522
+ * catch this either. Measured on 05482ba: both `Stop assuming X` and `Drop the
523
+ * assumption that X` tagged `X` as restatable.
524
+ *
525
+ * The veto reads the words between the sentence start and the hit, not the whole
526
+ * sentence, and that is what keeps it cheap in tags. `The parser drops stale
527
+ * entries.` states its claim and keeps its tag, because `drops` there governs
528
+ * `stale entries`, not a following assertion; the ambiguous verbs are therefore
529
+ * veto words only when a claim noun follows them. Every veto declines to tag,
530
+ * which is the direction this file fails safe in.
531
+ */
532
+ const WARNS_AGAINST = new RegExp(
533
+ // One alternation, ONE shared tail. Written as three separate alternatives
534
+ // each ending in `$`, only the last would be anchored and the first would
535
+ // match any sentence that merely contains `stop` anywhere — measured, and it
536
+ // cost the tag from `The job stops at midnight and the cache supports TTL
537
+ // expiration.`, which states its claim plainly.
538
+ "(?:" +
539
+ // A deterrent verb needs no framing: what follows is being warned against.
540
+ "\\b(?:stop|stops|stopped|stopping|cease|ceases|ceased|quit|quits|quitting|beware|caution\\w*)\\b" +
541
+ // An ordinary verb becomes a deterrent only with a claim noun behind it.
542
+ "|\\b(?:drop|drops|dropped|dropping|discard\\w*|dismiss\\w*|reject\\w*|forget|forgets|forgot|forgetting|ignor\\w*|overlook\\w*)\\b\\s+(?:the|your|this|an|any)\\s+(?:assumption|assumptions|idea|ideas|notion|notions|belief|beliefs|thinking|fact)\\b" +
543
+ // Claim verbs govern whatever follows them, framed or not.
544
+ "|\\b(?:assume|assumes|assumed|assuming|believ\\w*|think|thinks|thought)\\b" +
545
+ // Optional `that`, then nothing: the claim starts here.
546
+ ")\\s*(?:that\\s*)?$",
547
+ "i",
548
+ );
549
+
550
+ function warnsAgainst(prefix: string): boolean {
551
+ return WARNS_AGAINST.test(prefix);
552
+ }
553
+
554
+ /**
555
+ * Where the tree states `clause` as its own words, in a sentence of the same
556
+ * polarity. -1 means "not available".
557
+ *
558
+ * #397 round 3 (WhollyMindless): a bare `indexOf` matches INSIDE the opposite
559
+ * assertion. With `We do not use tabs for indentation.` in the README, the
560
+ * candidate `Use tabs for indentation.` was refused as available, so the store
561
+ * would have held the reversal of the rule the gate had just read. A hit now
562
+ * has to
563
+ * - begin and end on a word boundary: `use tabs` is not a hit inside
564
+ * `abuse tabs`; and
565
+ * - sit in a sentence that shares the clause's polarity. Negation the tree
566
+ * carries and the clause drops is a reversal, not a restatement; and
567
+ * - not be the object of a warning. `Stop assuming X.` states `X` only to
568
+ * reject it, and no polarity test of any breadth sees that (VETO 1b).
569
+ * A reversed clause is not evidence of availability, and every uncertainty in
570
+ * this file keeps the candidate.
571
+ */
572
+ function findClause(hay: string, clause: string): number {
573
+ const reversed = cueNegated(clause);
574
+ for (let from = 0; ; ) {
575
+ const i = hay.indexOf(clause, from);
576
+ if (i < 0) return -1;
577
+ const before = i > 0 ? hay.charCodeAt(i - 1) : 32;
578
+ const after =
579
+ i + clause.length < hay.length ? hay.charCodeAt(i + clause.length) : 32;
580
+ const sentence = sentenceSpan(hay, i, clause.length);
581
+ if (
582
+ !/\w/.test(String.fromCharCode(before)) &&
583
+ !/\w/.test(String.fromCharCode(after)) &&
584
+ cueNegated(sentence.text) === reversed &&
585
+ // A later occurrence may state the claim plainly, so a vetoed hit is
586
+ // skipped rather than ending the search.
587
+ !warnsAgainst(hay.slice(sentence.at, i))
588
+ )
589
+ return i;
590
+ from = i + 1;
591
+ }
592
+ }
593
+
594
+ /** True when every assertion in `clauses` is restatable from `hay`. */
595
+ function allRestatable(hay: string, clauses: string[]): boolean {
596
+ return hay !== "" && clauses.every((c) => findClause(hay, c) >= 0);
597
+ }
598
+
599
+ export interface AvailabilityIndex {
600
+ /** Null means "cannot tell", which stores the row with no tag. */
601
+ check(content: string): AvailabilityVerdict | null;
602
+ /**
603
+ * For evidence: what the tree scan actually read. `capped` means the byte
604
+ * budget ran out before the tracked list did. It is telemetry only, never a
605
+ * verdict input: both rules assert PRESENCE ("the tree states this"), so a
606
+ * truncated scan can only lower the tag rate, never raise a false tag.
607
+ */
608
+ scanned(): {
609
+ files: number;
610
+ bytes: number;
611
+ tracked: boolean;
612
+ capped: boolean;
613
+ };
614
+ }
615
+
616
+ /**
617
+ * One index per capture pass: git is asked once, the byte budget is shared by
618
+ * every candidate in the pass, and the gate declarations are read once.
619
+ */
620
+ export function availabilityIndex(
621
+ repoDir: string | undefined,
622
+ ): AvailabilityIndex {
623
+ if (!repoDir) {
624
+ return {
625
+ check: () => null,
626
+ scanned: () => ({ files: 0, bytes: 0, tracked: false, capped: false }),
627
+ };
628
+ }
629
+ const files = listed(repoDir);
630
+ if (files === null) {
631
+ return {
632
+ check: () => null,
633
+ scanned: () => ({ files: 0, bytes: 0, tracked: false, capped: false }),
634
+ };
635
+ }
636
+ const gates = parseGates(repoDir, files);
637
+ const ranked = [...files]
638
+ .filter((f) => !skipPath(f) && TEXT_EXTENSIONS.has(extOf(f)))
639
+ .sort((a, b) => {
640
+ const pa = PRIORITY.indexOf(extOf(a));
641
+ const pb = PRIORITY.indexOf(extOf(b));
642
+ const ra = pa === -1 ? PRIORITY.length : pa;
643
+ const rb = pb === -1 ? PRIORITY.length : pb;
644
+ return ra - rb || (a < b ? -1 : 1);
645
+ });
646
+
647
+ let haystack = "";
648
+ const slices: Slice[] = [];
649
+ let bytes = 0;
650
+ let loaded = 0;
651
+ // Set only when a file is actually SKIPPED, which is what the field claims: a
652
+ // final file that pushes the total past the cap sets nothing, because nothing
653
+ // was left behind. `bytes` counts decoded characters, not octets on disk — the
654
+ // budget is a work bound, not a disk measurement.
655
+ let capped = false;
656
+ for (const file of ranked) {
657
+ if (bytes >= TOTAL_CAP) {
658
+ capped = true;
659
+ break;
660
+ }
661
+ const text = readTracked(repoDir, file);
662
+ if (text === null) continue;
663
+ const n = norm(text);
664
+ if (!n) continue;
665
+ const start = haystack.length;
666
+ haystack += n + "\u0000";
667
+ slices.push({ file, start, end: haystack.length });
668
+ bytes += text.length;
669
+ loaded++;
670
+ }
671
+
672
+ const fileAt = (offset: number): string => {
673
+ for (const s of slices)
674
+ if (offset >= s.start && offset < s.end) return s.file;
675
+ return "?";
676
+ };
677
+
678
+ return {
679
+ check(content: string): AvailabilityVerdict | null {
680
+ // #397 review (WhollyMindless): matching PART of a candidate does not
681
+ // establish the WHOLE fact is available. Both rules used to refuse on
682
+ // one hit, which lost new facts riding a restated fragment — exactly
683
+ // the rows this gate exists to preserve:
684
+ // - a README rule + "; Finance confirmed the supplier rate is 1900"
685
+ // refused on the old clause;
686
+ // - "Never run `npm run deploy` until finance confirms approval code
687
+ // BLUEBIRD" refused because the manifest declares `deploy`, although
688
+ // the restriction and the code appear nowhere.
689
+ // A tag requires EVERY assertion the candidate makes to be restatable.
690
+ const whole = norm(content);
691
+ const needed = claims(whole);
692
+ if (needed.length === 0) needed.push(whole);
693
+ const first = needed[0] ?? whole;
694
+ // Evidence mirror of `whole` and `first`, scrubbed WHILE THE TEXT STILL HAS
695
+ // ITS CASE. `norm()` lowercases, and the prefix scrubber in
696
+ // store/secrets.ts matches `AKIA[A-Z0-9]{16}` case-sensitively, so a span
697
+ // normalised before scrubbing keeps a fully recoverable access key: the
698
+ // logged `akia1234567890abcdef` uppercases straight back to the secret
699
+ // (#403 review). Redacting `avail.matched` later cannot recover what
700
+ // normalisation already destroyed, so this is the only place it can be
701
+ // done. Verdict logic reads `needed`/`first`, never these.
702
+ const safeWhole = norm(redactSecrets(content));
703
+ const safeFirst = claims(safeWhole)[0] ?? safeWhole;
704
+ if (haystack && allRestatable(haystack, needed)) {
705
+ return {
706
+ reason: "in_tracked_file",
707
+ where:
708
+ relative(
709
+ repoDir,
710
+ join(repoDir, fileAt(findClause(haystack, first))),
711
+ ) || "?",
712
+ matched: safeFirst.slice(0, 120),
713
+ };
714
+ }
715
+ // Declared gate. Round 3 (WhollyMindless) removed the LENGTH test: a short
716
+ // residual used to count as a restatement, so "`npm run deploy` wipes the
717
+ // staging database." was refused against a manifest that says only that
718
+ // `deploy` runs rsync. Round 4 found the same defect still open, in two
719
+ // places that both throw information away BEFORE deciding:
720
+ // - every command span was stripped after ONE declared gate was found,
721
+ // so "Before `npm run deploy`, run `aws sso login --profile prod`."
722
+ // refused with the undeclared AWS prerequisite erased from the row;
723
+ // - an EMPTY claim list counted as proof, so "Never `npm run deploy`."
724
+ // refused with its only claim — `never` — dropped as too short.
725
+ // A gate tag needs all three, each positively established:
726
+ // 1. every command span the row states is declared. An undeclared one is
727
+ // a fact the tree does not hold, whatever the rest of the row says;
728
+ // 2. what survives stripping them is nothing but FILLER — the bare
729
+ // mention "ship with X", which is what the manifest does declare; or
730
+ // 3. otherwise, every assertion left in it is one the tracked files
731
+ // state themselves.
732
+ const spans = statedCommands(content);
733
+ const gate = gateHit(spans, gates);
734
+ if (gate) {
735
+ // VETOES (#402). The manifest states that a command EXISTS. It does not
736
+ // state that the command is safe, allowed, or finished, and it carries
737
+ // no figure. So a sentence that forbids the command, or a number the
738
+ // command does not carry, is a claim the declaration cannot answer.
739
+ //
740
+ // These REMOVE a tag and never add one, and a removed tag costs the row
741
+ // nothing permanent: it is stored either way and a spare budget still
742
+ // shows it. That asymmetry is the whole point of the change — the round-3
743
+ // and round-4 arguments were really about a vocabulary that had to be
744
+ // perfect because a miss deleted a fact. Under a tag, a miss costs one
745
+ // injection slot.
746
+ if (forbidsCommand(content, spans)) return null;
747
+ if (introducesNewNumber(content, spans.join(" "))) return null;
748
+ const undeclared = spans.some((s) => gateHit([s], gates) === null);
749
+ let residual = content;
750
+ for (const span of spans) residual = residual.split(span).join(" ");
751
+ const rest = claims(norm(residual));
752
+ if (
753
+ !undeclared &&
754
+ (rest.length === 0 || allRestatable(haystack, rest))
755
+ ) {
756
+ return {
757
+ reason: "declared_gate",
758
+ where: gate.where,
759
+ matched: safeWhole.slice(0, 120),
760
+ };
761
+ }
762
+ }
763
+ return null;
764
+ },
765
+ scanned: () => ({ files: loaded, bytes, tracked: true, capped }),
766
+ };
767
+ }