opencode-self-improvement 0.33.11 → 0.34.1

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.
@@ -1,6 +1,6 @@
1
1
  # ADR 0008 — Availability verdicts tag rows; they never refuse them
2
2
 
3
- Status: accepted (2026-11). Code: `src/capture/available.ts`.
3
+ Status: superseded by [ADR 0009](0009-availability-refusals-under-the-hardened-matcher.md) (2026-11). Code: `src/capture/available.ts`.
4
4
 
5
5
  ## Decision
6
6
 
@@ -0,0 +1,95 @@
1
+ # ADR 0009 — Availability verdicts refuse capture candidates, under the hardened matcher
2
+
3
+ Status: accepted (2026-11). Supersedes [ADR 0008](0008-availability-tags-not-refusals.md).
4
+ Code: `src/capture/available.ts` (the predicate), applied in `src/capture/runtime.ts` (the refusal).
5
+
6
+ ## Decision
7
+
8
+ A capture candidate whose every assertion the working tree states verbatim —
9
+ modulo case, wrapping and markup — or whose only content is a command the
10
+ project's own gates declare, is REFUSED at capture time and logged on the
11
+ `auto_capture_restatable` evidence line, which names the file or the gate.
12
+ The figure-subset invariant bounds both paths: a refusal claims the passage it
13
+ cites states EVERY figure the candidate states, as whole tokens (`1.5`,
14
+ `1.4.3`, `10.20.30.40` are single figures) — on the text path that passage is
15
+ the region the match covered, not the tree at large, since a figure in another
16
+ sentence is another sentence's business — and on the gate path the figures are
17
+ compared against the declared command, never against the candidate's own
18
+ spans. Contiguity bounds the text path: the claims must be found in the
19
+ candidate's order with nothing between one and the next but assertion
20
+ punctuation and whitespace, so a label from one line cannot be joined to a
21
+ value from another and the tree, not the session, owns every pairing it is
22
+ credited with stating. On the gate path the same relation asks about operands:
23
+ what a span adds to the command must be a contiguous token run in the
24
+ declaration that vouches for it — the script name and its command for a
25
+ per-script declaration, the matched step alone for a step-kind one — so the
26
+ bare invocation (empty operand) and a declared prefix stay refusals while
27
+ swapped values, stripped values and reorders keep their rows. Word membership
28
+ is not enough: `--target staging --fallback canary` declared against
29
+ `--target canary --fallback staging` has every word present and the pairing
30
+ wrong. One relation, both paths.
31
+
32
+ Atomicity is the spine, not another guard. A figure is one token wherever the
33
+ matcher reads it — `tokens()` treats `.` as a word character, so `1.5`, `1.4.3`
34
+ and the `11.` of a sentence ending on one are single figures — therefore the
35
+ claim splitter never cuts inside a figure and a match is admitted only when no
36
+ figure run crosses either edge of it. Half-figures are what every earlier round
37
+ kept meeting from a different angle: a claim ending at the `3` of `3.12` is cut,
38
+ then re-tokenized by the region slice as a figure the tree never states. Judging
39
+ the boundary makes that shape unrepresentable rather than merely unvouched. The
40
+ subset, region and contiguity checks stay: they cost nothing on the fail-open
41
+ side and catch what atomicity cannot reach.
42
+
43
+ The refusal is scoped to the auto-capture path. `memory_remember`, updates,
44
+ imports and consolidation write what their callers ask for; a user may store a
45
+ restatement on purpose, capture may not. Capture refuses guided candidates on
46
+ the same terms: the recall layer's exemption of guided rows from the budget
47
+ demotion does not extend upstream, and a guided verbatim copy — refused, and
48
+ logged with `guided=true` so the decision stays visible — never becomes a row
49
+ that rides every injection block at full rank. Nothing is deleted from an
50
+ existing store, and the retrieval demotion of `restatable`-tagged rows stays
51
+ for rows written while the tag policy shipped.
52
+
53
+ ## Why
54
+
55
+ ADR 0008 retired refusal because the rule of the day matched fragments: it
56
+ rejected 30 of 1,166 real captured rows and 29 of those refusals were wrong.
57
+ The matcher built during the tagging work is a different predicate — every
58
+ claim restatable, word-bounded, polarity-matched, warning-checked, no new
59
+ figure — and the policy bench measures it against the same alternatives: it
60
+ keeps 10 of 10 transport facts and refuses 6 of 6 restatable ones, where the
61
+ original rule destroyed 4 of 10 transport facts on a command mention alone.
62
+
63
+ The cost side then got a direct measurement. With one plausible wrong row in
64
+ the store, an agent shipped a wrong artifact in 4 of 5 runs; an empty store
65
+ failed honestly and invented nothing. A restatable row is the milder member of
66
+ that family — true, but redundant with a file the session can read — and the
67
+ store's only measured benefit (transport: empty store 0/5, seeded 5/5) comes
68
+ from facts the tree does not hold. At roughly a third of a session's own
69
+ generation per pass, budget spent on restatements buys nothing measurable.
70
+
71
+ ## Consequences
72
+
73
+ - Capture writes fewer rows. Its model-call cost is unchanged — candidates
74
+ come from the model, so the check can only run after the call — while the
75
+ store and every later injection block shrink.
76
+ - The predicate fails open. No git, no repo, unreadable files, a capped scan,
77
+ a dropped negation or a single new clause all keep the candidate. A wrong
78
+ refusal costs a fact the next session cannot rebuild; a wrong keep costs one
79
+ redundant row. The matcher's veto-only shape exists to keep the first rare.
80
+ - Refusal precedes the write gate, so a restatable candidate never becomes a
81
+ supersession contender, and the gate's checks never see it. The refusal line
82
+ carries the whole candidate, so a wrong refusal is replayable from the log.
83
+ - The `restatable` tag is no longer written by capture. `RESTATABLE_TAG`
84
+ remains for legacy rows and for reserved-tag stripping; retiring it is a
85
+ separate decision, taken once no tagged row survives in a store.
86
+ - Read-time dropping stays rejected: the row would still be written, and a
87
+ wrong verdict would hide it with no refusal log naming the file.
88
+
89
+ ## Evidence
90
+
91
+ `bench/availability-results.md` (the policy arms, including `delete-hardened`,
92
+ which is the shipped policy), `test/capture/capture-available.test.ts` (the
93
+ runtime consequence), `test/capture/availability-case-bank.test.ts` (every
94
+ adversarial verdict the matcher has been found guilty of), and the transport
95
+ and precision benchmarks reported on the epic.
@@ -13,4 +13,5 @@ opening the file.
13
13
  | 0005 | [Two-phase teardown for capture passes](0005-capture-teardown-phases.md) | accepted (2026-11) | — | — |
14
14
  | 0006 | [Capture prompt integrity: redaction order and faithful citation](0006-capture-prompt-integrity.md) | accepted (2026-11) | — | — |
15
15
  | 0007 | [Symptom-first opening for learning and blocker rows](0007-symptom-first-capture.md) | accepted (2026-11) | — | — |
16
- | 0008 | [Availability verdicts tag rows; they never refuse them](0008-availability-tags-not-refusals.md) | accepted (2026-11) | — | — |
16
+ | 0008 | [Availability verdicts tag rows; they never refuse them](0008-availability-tags-not-refusals.md) | superseded (2026-11) | — | [0009](0009-availability-refusals-under-the-hardened-matcher.md) |
17
+ | 0009 | [Availability verdicts refuse capture candidates, under the hardened matcher](0009-availability-refusals-under-the-hardened-matcher.md) | accepted (2026-11) | [0008](0008-availability-tags-not-refusals.md) | — |
@@ -23,7 +23,9 @@ What is established, from tests and fixtures (no live store involved):
23
23
 
24
24
  - **The host abandons a turn-end handler that awaits; tying that to the original #406 misses is a hypothesis, not an observation.** Measured 2026-11-21 on opencode v2.3.0 (macOS) with a probe plugin over the same harness: the turn-end event reaches `event.subscribe` in 10 of 10 turns at every handler length, but a handler that awaits a timer records its completion in 0 of 10, and the plugin's cleanup fires 10 of 10. A reviewer's sweep put the abandonment boundary below 50 ms — a 50 ms, 200 ms and 2000 ms handler are all lost, RECV 10/10 throughout — so the claim is if anything understated. A write made synchronously as the handler's first action lands regardless. That is the measured mechanism: the host dispatches turn-end and exits without awaiting the handler. What is NOT measured is the identification of the issue's original natural misses (6 of 8, recorded 2026-11-13 on an older host) with this mechanism. Neither this work (45/45 before, 30/30 after) nor the reviewer (1 miss in 75 turns on v2.3.0, 24/24 under load) could reproduce a natural miss on the current host. So this repo adds observability to TEST the hypothesis rather than assert a cause: the pass writes `auto_capture_start` synchronously before the model call, so a pass that reached the model call but never recorded `capture_cost` is a visible cut; disposal writes `auto_capture_dispose` when an armed instance observed no turn-end event — a PREDICTIVE line, since the event is delivered in every measured run and an idle restart between turns produces it too. A deliberate skip writes `auto_capture_skipped` and no start line, so `memory_status` renders skip, cut, and never-fired apart. These are NOT all the states: a pass cut during the context read or the known-rows read — the awaited `loadAll()` before the receipt — still writes nothing, so that band stays silent exactly as the original failure did. The receipt trades that band (measured 0.72 ms at 200 rows, 2.08 ms at 2000, warm) for not misreporting a healthy skip as a cut. Natural misses, when they recur, are then classified against these lines. `test/capture/capture-start-observable.test.ts` pins the receipt, the skip, the disposal flush, and the cut-outranks-dispose ordering.
25
25
 
26
- - **The availability policy is measured against its alternatives, and against its own measuring stick.** `bun run bench:availability` (`bench/availability-results.md`) runs one capture pass over a 197-row store five times — no check, tag (as shipped), drop-at-read (the P3 preview), drop-hardened, and the original rule replayed from the pinned `362655c` module — with the byte budget swept over five sizes and the background resampled at 0/30/90/180 rows, because a claim measured at one budget or one store size is a claim about that budget. Tagging keeps all 10 new transport facts and retrieves 14 of 14 retrievable queries at every budget and every store size, where the original rule keeps 6 of 10 and retrieves 7 at every budget: that rule deleted four of ten new facts on a command mention alone, and a deleted fact cannot be retrieved. The ceiling is stated next to every recall figure and measured on the exact rows the arms retrieve: 14 of the 21 curated transport queries retrieve their own gold when that gold is the ONLY row in the store, so the tag arm's 14 is the achievable maximum and 9/21 was never 43% recall. The counterfactual is printed beside it — strip the keywords the capture reply carries and the ceiling falls to 9/21, because five of these pairs are retrievable only through the keyword list. A 25-case bank of every adversarial verdict this matcher has been found guilty of is re-decided on every run, one repo per case, and asserted in `bun test` because CI runs no bench. Writing those controls found two defects in the bench itself — verdicts keyed on `ts`, which is not unique when a pass writes rows in one millisecond, and a byte column summed across 21 queries and labelled per-block — and the corrected numbers are in the file. The report also states what it cannot measure: the check marks 6 of 16 rows a pass writes and 0 of 180 background rows, and that 0 is a fixture artefact rather than a base rate, because no seeded row quotes the tracked tree. It also tests the tag's justification directly: empty the tracked text and all 6 verdicts disappear, which is the property a read-time policy would keep and a delete would not.
26
+ - **The availability policy is measured against its alternatives, and against its own measuring stick.** `bun run bench:availability` (`bench/availability-results.md`) runs one capture pass over a 197-row store five times — no check, tag, drop-at-read (the P3 preview), delete-hardened (as shipped), and the original rule replayed from the pinned `362655c` module — with the byte budget swept over five sizes and the background resampled at 0/30/90/180 rows, because a claim measured at one budget or one store size is a claim about that budget. Tagging keeps all 10 new transport facts and retrieves 14 of 14 retrievable queries at every budget and every store size, where the original rule keeps 6 of 10 and retrieves 7 at every budget: that rule deleted four of ten new facts on a command mention alone, and a deleted fact cannot be retrieved. The ceiling is stated next to every recall figure and measured on the exact rows the arms retrieve: 14 of the 21 curated transport queries retrieve their own gold when that gold is the ONLY row in the store, so the tag arm's 14 is the achievable maximum and 9/21 was never 43% recall. The counterfactual is printed beside it — strip the keywords the capture reply carries and the ceiling falls to 9/21, because five of these pairs are retrievable only through the keyword list. A 25-case bank of every adversarial verdict this matcher has been found guilty of is re-decided on every run, one repo per case, and asserted in `bun test` because CI runs no bench. Writing those controls found two defects in the bench itself — verdicts keyed on `ts`, which is not unique when a pass writes rows in one millisecond, and a byte column summed across 21 queries and labelled per-block — and the corrected numbers are in the file. The report also states what it cannot measure: the check marks 6 of 16 rows a pass writes and 0 of 180 background rows, and that 0 is a fixture artefact rather than a base rate, because no seeded row quotes the tracked tree. It also tests the tag's justification directly: empty the tracked text and all 6 verdicts disappear, which is the property a read-time policy would keep and a delete would not.
27
+
28
+ - **The shipped availability consequence moved from tag to refusal.** A candidate whose every assertion the tracked tree states verbatim — modulo case, wrapping and markup — or whose only content is a command the project's gates declare, is refused at capture time and logged on `auto_capture_restatable` with the file or the gate named. The tag survives only as the retrieval demotion for rows written before the move; capture no longer writes it, and no refusal deletes anything from an existing store. The bench's `delete-hardened` arm is this policy: 10 of 10 transport facts kept, 6 of 6 restatable ones refused. `test/capture/capture-available.test.ts` pins the runtime consequence both ways — refusal lines with no row for the provable forms, kept rows for every veto the matcher owes — and the predicate fails open on every uncertainty (no git, unreadable file, capped scan, one new clause, one new figure), so the transport case is protected by construction. A pass's model-call cost is unchanged; what shrinks is the store and every later injection block. Decision: docs/adr/0009, superseding docs/adr/0008.
27
29
 
28
30
  ## What has not been established
29
31
 
@@ -11,7 +11,7 @@ rules and links here.
11
11
 
12
12
  Daily memory writes publish a complete replacement file under that lock, so concurrent readers see the previous or new complete file rather than a partially appended record. Appending a row therefore rewrites the day file (in addition to the existing timestamp-uniqueness read). On Windows, a reader handle that prevents replacement can make the write refuse after the replacement retry window; the previous bytes remain intact and the caller can retry once the handle closes. This publication rule applies to daily memory files, not append-only evidence, use, rejection, or audit logs; [#198](https://github.com/abogartz/opencode-self-improvement/issues/198) tracks the broader read boundary.
13
13
 
14
- The lock covers one **file**, not the store directory. Two sessions writing different days of the same store therefore do not wait on each other. A directory-wide lock was tried first and lost writes: a whole-file publish waits up to two seconds on Windows for a reader to let go of the destination, and with one lock for the directory that wait stops every other writer in the store. Per file it stops only the writers of that file, which is what the publish's safety check needs. The cost is a database plus its write-ahead log per locked file; they exist only while a connection is open, and the number of open connections is bounded. A writer never holds two file locks at once, and batches that must serialize a whole read-then-supersede sequence (`memory_update`, `memory_merge_review`) take a separate named lock (`.store-batch.update-order.sqlite`), always before the file locks their steps take — so a batch never holds a file lock across its whole run.
14
+ The lock covers one **file**, not the store directory. Two sessions writing different days of the same store therefore do not wait on each other. A directory-wide lock was tried first and lost writes: a whole-file publish waits up to two seconds on Windows for a reader to let go of the destination, and with one lock for the directory that wait stops every other writer in the store. Per file it stops only the writers of that file, which is what the publish's safety check needs. The cost is a database plus its write-ahead log per locked file; they exist only while a connection is open, and the number of open connections is bounded. Updates, merge reviews, and snapshot restores share a named lock (`.store-batch.update-order.sqlite`) within a store. Each takes that lock before its day-file locks, so a restore cannot replace either row between consolidation validation and retirement. A writer holds at most one day-file lock at a time. Even a restore for another day can wait behind an update or merge. If the lock times out, the restore returns a busy error and can be retried.
15
15
 
16
16
  Two unsupported placements. The write-ahead log needs mmap'd shared memory, which SQLite does not provide on network filesystems, so a memory root on SMB, NFS or a OneDrive-mounted folder is **not supported**: writes there can report a disk I/O error rather than serialise. Configure `OPENCODE_MEMORY_DIR` on local disk. And during the update that introduced this lock, a session still running the previous release honours `<date>.logfmt.lock` while an updated session honours the SQLite lock, so those two do not exclude each other until every running session has restarted.
17
17
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-self-improvement",
3
- "version": "0.33.11",
3
+ "version": "0.34.1",
4
4
  "description": "Durable memory for opencode: remember facts, decisions, and commands across sessions, plus a one-command per-repo setup (/repo-init).",
5
5
  "main": "index.ts",
6
6
  "exports": {
@@ -16,45 +16,36 @@
16
16
  // 2. Is this command already declared by the project's own gates? A row that
17
17
  // says "run `make deploy`" is answered by the Makefile.
18
18
  //
19
- // Both produce a TAG, not a refusal. A refusal rule was measured here
20
- // first: it rejected 30 of 1,166 real captured rows and 29 of those were
21
- // wrong (the note "OpenCode V2 (v2.0.26) does NOT run LSP servers" was
22
- // refused because it contained the string `bun test` and
23
- // this project declares a `test` script). A check nobody can trust enough to
24
- // delete with, and nobody can make cheap enough to skip, must not decide
25
- // anything on its own. Partial-match and short-fragment traps are pinned by
26
- // tests; history: docs/adr/0008.
19
+ // Both questions now REFUSE the candidate at capture time: the next session
20
+ // reads the file named in the refusal line, so the row buys nothing. An
21
+ // earlier refusal rule was retired for matching fragments — it refused rows
22
+ // that were not restatements at all — and the matcher built in its place is
23
+ // the predicate that refuses now:
27
24
  //
28
- // So the verdict is now evidence attached to a row that is stored anyway:
29
- //
30
- // - it cannot drop a row, so a wrong match costs a tag instead of a fact;
31
- // - every claim is checked, not sampled: one unchecked clause is enough to make
32
- // the row new, and the unchecked part is where the new fact lives;
25
+ // - every claim is checked, not sampled: one unchecked clause is enough to
26
+ // make the row new, and the unchecked part is where the new fact lives;
33
27
  // - polarity and numbers are VETOES, not evidence: they can only decline to
34
- // tag, never create one. The number check is the house `numericTokens` set
35
- // from `core/tokenize.ts`; see the two vetoes below for why the polarity
36
- // check keeps its own cue list as well.
37
- //
38
- // The vetoes can only REMOVE a tag, never add one — which holds only because the
39
- // one place that compares two texts, `findClause`, compares them on the narrow
40
- // cue list. Widen that comparison and agreement gets easier, and an agreement is
41
- // what creates a tag; see VETO 1. Saltzer & Schroeder's fail-safe principle,
42
- // applied to a suppression filter: the default is keep, and a bug must surface as
43
- // a visible duplicate rather than as content that is gone.
28
+ // refuse, never create a refusal. The number check is the house
29
+ // `numericTokens` set from `core/tokenize.ts`; see the two vetoes below
30
+ // for why the polarity check keeps its own cue list as well.
44
31
  //
45
- // A wrong tag is not free either. The row survives, but `fitOrder` gives it up
46
- // first when the injection budget binds, so a false positive costs the row its
47
- // slot for the queries that needed it. That is the real price of a bad verdict,
48
- // and it is why the matcher is still held to the veto-only shape.
32
+ // The vetoes can only REMOVE a refusal, never add one — which holds only
33
+ // because the one place that compares two texts, `findClause`, compares them
34
+ // on the narrow cue list. Widen that comparison and agreement gets easier,
35
+ // and an agreement is what refuses; see VETO 1. Saltzer & Schroeder's
36
+ // fail-safe principle, applied to a suppression filter: the default is keep,
37
+ // and a bug must surface as a visible duplicate rather than as content that
38
+ // is gone.
49
39
  //
50
- // Storing instead of deleting has a second consequence, and it is not a tag
51
- // effect. A stored row is a live GATE-3 contender, so a later write at >=0.9
52
- // overlap is now refused `superseded_overlap` where the delete policy would have
53
- // let it promote. Measured: an ordinary-tagged seed blocks the same write with
54
- // the same reason, so the tag changes nothing in the gate — the row being there
55
- // does. That is the gate working as designed on a genuine near-duplicate, with a
56
- // hint naming the row to `memory_update`, and it is the cost of no longer
57
- // destroying facts. P5 decides whether the check earns its keep at all.
40
+ // The two error directions are not symmetric, and the shape follows that. A
41
+ // wrong keep costs one redundant row — a second copy of something readable
42
+ // in the tree. A wrong refusal costs a fact the next session cannot rebuild,
43
+ // and the transport benchmark says the store's only measured benefit is
44
+ // exactly those facts. So refusal demands the strictest evidence the check
45
+ // can hold — every assertion restatable verbatim modulo formatting, same
46
+ // polarity, no new figure — and abstains, keeping the candidate, on anything
47
+ // less. Refusal is scoped to auto-capture: direct writes, updates, imports
48
+ // and consolidation are not this filter's business. History: docs/adr/.
58
49
  //
59
50
  // Fail-open is the rule throughout. A missing git, an unreadable file, a repo
60
51
  // that is not a repo, or a budget that ran out is NOT evidence that a fact is
@@ -62,7 +53,12 @@
62
53
  // measured benefit capture has. Every uncertainty keeps the candidate.
63
54
  import { lstatSync, readFileSync } from "node:fs";
64
55
  import { join, relative } from "node:path";
65
- import { POL_NEG, numericTokens, polaritySigns } from "../core/tokenize.ts";
56
+ import {
57
+ POL_NEG,
58
+ numericTokens,
59
+ polaritySigns,
60
+ tokens,
61
+ } from "../core/tokenize.ts";
66
62
  import { redactSecrets } from "../store/secrets.ts";
67
63
 
68
64
  /** What made a candidate restatable, and where the next session can get it. */
@@ -208,19 +204,20 @@ const NEGATION =
208
204
  * disable" and "enable" do not read as the same claim.
209
205
  *
210
206
  * USE THIS ONLY WHERE THE ANSWER IS ABSOLUTE. `forbidsCommand` asks "does this
211
- * sentence forbid the command?" and a yes declines to tag, so widening it can
207
+ * sentence forbid the command?" and a yes declines to refuse, so widening it can
212
208
  * only ever decline — the fail-safe direction.
213
209
  *
214
210
  * The relative use, where one text's polarity is compared with another's, is
215
211
  * `cueNegated`, and the difference is not academic. Equality gets EASIER as both
216
212
  * predicates get broader, and in `findClause` an agreement is what CREATES the
217
- * tag. Measured on the round-3 case: tree `Do not assume the cleaner removes
218
- * unused rows.`, candidate `The cleaner removes unused rows.` — `polaritySigns`
219
- * reads the dual-role `removes` as negative in BOTH strings, the union agrees,
220
- * and the affirmative claim is tagged as restating the sentence that warns
221
- * against it. The cue list alone sees `not` on one side and nothing on the other
222
- * and declines. That is the defect this veto exists for, arriving from the
223
- * opposite direction.
213
+ * refusal. The union predicate must never be that comparison: on the tree
214
+ * `Do not assume the cleaner removes unused rows.` against the candidate
215
+ * `The cleaner removes unused rows.`, `polaritySigns` reads the dual-role
216
+ * `removes` as negative in BOTH strings, the union agrees, and the affirmative
217
+ * claim is refused as restating the sentence that warns against it. The cue
218
+ * list alone sees `not` on one side and nothing on the other and declines;
219
+ * `test/capture/availability-case-bank.test.ts` pins that shape. That is the
220
+ * defect this veto exists for, arriving from the opposite direction.
224
221
  */
225
222
  function negated(text: string): boolean {
226
223
  return NEGATION.test(text) || polaritySigns(text).includes(POL_NEG);
@@ -229,27 +226,48 @@ function negated(text: string): boolean {
229
226
  /**
230
227
  * Cue-list polarity, for the one place that COMPARES two texts. Narrow on
231
228
  * purpose: a broader predicate here agrees more often, and every extra agreement
232
- * is a tag.
229
+ * is a refusal.
233
230
  */
234
231
  function cueNegated(text: string): boolean {
235
232
  return NEGATION.test(text);
236
233
  }
237
234
 
238
235
  /**
239
- * VETO 2: a figure the matched declaration does not carry.
236
+ * VETO 2: a figure the matched DECLARATION does not carry.
240
237
  *
241
238
  * `core/tokenize.ts` states the rule and `store/tombstones/tombstone.ts`
242
239
  * measures it on this repo's own data: a correction scores HIGHER than an honest
243
240
  * rewording, so overlap alone cannot separate "the same fact again" from "the
244
241
  * fact has changed". On the declared-command path the manifest states only that
245
- * a command exists, so any number the row asserts has to be in the command
246
- * itself or the row is new.
242
+ * a command exists, so any number the row asserts has to be in the DECLARED
243
+ * command — `gate.label` — or the row is new. The comparison text is never the
244
+ * candidate's own spans: a row whose command span carries a flag value
245
+ * (`--timeout 5000`) would supply the figure that clears its own veto, and the
246
+ * declaration, not the row, is what must vouch for the number.
247
+ * `numericTokens` keeps dotted numbers whole, so versions and addresses are
248
+ * single figures and cannot be assembled out of separate integers.
247
249
  */
248
250
  function introducesNewNumber(text: string, matched: string): boolean {
249
251
  const known = new Set(numericTokens(matched));
250
252
  for (const n of numericTokens(text)) if (!known.has(n)) return true;
251
253
  return false;
252
254
  }
255
+
256
+ /**
257
+ * True when every figure `text` states appears in `known` as a whole token —
258
+ * the veto-2 rule, now aimed at the matched region. `claims()` no longer splits
259
+ * inside a figure and `findClause` admits no hit that cuts one, so a figure the
260
+ * tree never states (`1.5`, `1.4.3`, `10.20.30.40`) cannot reassemble from
261
+ * fragments of separate sentences; this check stays as the second net, because
262
+ * it costs nothing on the fail-open side and catches a figure in prose that no
263
+ * claim matched. A corrected figure is the transport class, the row the store
264
+ * exists to keep. Fails safe in both directions of uncertainty: a candidate
265
+ * with no figures has an empty set and stays restatable.
266
+ */
267
+ function figuresWithin(text: string, known: Set<string>): boolean {
268
+ for (const n of numericTokens(text)) if (!known.has(n)) return false;
269
+ return true;
270
+ }
253
271
  // The scan is bounded by bytes, not files: a monorepo's tracked list is huge and
254
272
  // the point is a cheap check, not an index. One capture pass already pays for a
255
273
  // model call, which costs far more than this.
@@ -338,6 +356,12 @@ interface Slice {
338
356
  interface Gate {
339
357
  label: string;
340
358
  where: string;
359
+ /**
360
+ * True for a step among siblings — a Makefile recipe, a workflow `run:` line.
361
+ * Those share one `where` across the whole file while stating nothing about
362
+ * each other, so the label is all the declaration it has.
363
+ */
364
+ solo?: boolean;
341
365
  }
342
366
 
343
367
  function readTracked(repoDir: string, file: string): string | null {
@@ -357,9 +381,9 @@ function skipPath(file: string): boolean {
357
381
 
358
382
  function parseGates(repoDir: string, files: string[]): Gate[] {
359
383
  const gates: Gate[] = [];
360
- const add = (label: string, where: string) => {
384
+ const add = (label: string, where: string, solo = false) => {
361
385
  const n = norm(label);
362
- if (n.length >= 2 && n.length <= 80) gates.push({ label: n, where });
386
+ if (n.length >= 2 && n.length <= 80) gates.push({ label: n, where, solo });
363
387
  };
364
388
  for (const file of files) {
365
389
  if (skipPath(file)) continue;
@@ -390,13 +414,13 @@ function parseGates(repoDir: string, files: string[]): Gate[] {
390
414
  const target = /^([A-Za-z0-9_.%-]+)\s*:(?!=)/.exec(line);
391
415
  if (target?.[1]) add(target[1], `${file} target ${target[1]}`);
392
416
  const recipe = /^\t+([^\s].*)$/.exec(line);
393
- if (recipe?.[1]) add(recipe[1], `${file} recipe`);
417
+ if (recipe?.[1]) add(recipe[1], `${file} recipe`, true);
394
418
  }
395
419
  continue;
396
420
  }
397
421
  for (const line of text.split("\n")) {
398
422
  const run = /^\s*-?\s*run:\s*["']?(.+?)["']?\s*$/.exec(line);
399
- if (run?.[1]) add(run[1], `${file} run`);
423
+ if (run?.[1]) add(run[1], `${file} run`, true);
400
424
  }
401
425
  }
402
426
  return gates;
@@ -427,6 +451,91 @@ function runners(span: string): string[] {
427
451
  return forms;
428
452
  }
429
453
 
454
+ /**
455
+ * The labels that vouch for a declaration: the matched one, plus those sharing
456
+ * its `where` when that `where` names ONE command. A script declaration states
457
+ * its name and its command together, so `--prod` written in the command vouches
458
+ * for `--prod` in the row. A step-kind `where` names a FILE — every recipe in a
459
+ * Makefile, every `run:` in a workflow — and siblings state nothing about each
460
+ * other, so there the matched label alone vouches.
461
+ */
462
+ function vouchLabels(gate: Gate, gates: Gate[]): string[] {
463
+ const out: string[] = [];
464
+ for (const g of gates) {
465
+ if (g.where !== gate.where) continue;
466
+ if (gate.solo && g.label !== gate.label) continue;
467
+ out.push(g.label);
468
+ }
469
+ return out;
470
+ }
471
+
472
+ /**
473
+ * What a span states around the command it names: the tokens left after the
474
+ * runner vocabulary and the matched label, one candidate per span form in which
475
+ * that label appears. An empty candidate is the bare invocation.
476
+ */
477
+ function operandCandidates(span: string, gate: Gate): string[][] {
478
+ const out: string[][] = [];
479
+ for (const form of runners(span)) {
480
+ const at = form.indexOf(gate.label);
481
+ if (at < 0) continue;
482
+ out.push(
483
+ tokens(`${form.slice(0, at)} ${form.slice(at + gate.label.length)}`),
484
+ );
485
+ }
486
+ return out;
487
+ }
488
+
489
+ /** Is `operand` a contiguous token run inside any vouching label? */
490
+ function contiguousIn(operand: string[], labels: string[]): boolean {
491
+ for (const label of labels) {
492
+ const decl = tokens(label);
493
+ for (let i = 0; i + operand.length <= decl.length; i++) {
494
+ if (operand.every((w, j) => decl[i + j] === w)) return true;
495
+ }
496
+ }
497
+ return false;
498
+ }
499
+
500
+ /**
501
+ * VETO 3: does every span add only a run the declaration states?
502
+ *
503
+ * Stripping the whole span before reading the residual hides what the span
504
+ * carried: with `deploy: "deploy-tool publish"` declared, `npm run deploy --
505
+ * --target canary` reduced to the same empty residual as the bare invocation,
506
+ * and the canary target — the session's only fact — was refused with the
507
+ * command it rode. Set membership of the span's words does not close that
508
+ * either: `--target staging --fallback canary` declared against `--target
509
+ * canary --fallback staging` has every word present and the pairing wrong, and
510
+ * a flag reorder or a stripped value reaches the same hole.
511
+ *
512
+ * So the gate path asks the tree path's question — contiguity, not presence.
513
+ * The operand must be a contiguous token run inside a vouching label; the empty
514
+ * operand is the bare invocation, which the declaration states on its own.
515
+ * Anything the check cannot establish — the label not located, values swapped,
516
+ * flags reordered, an operand broken by a word the declaration omits — keeps
517
+ * the row. Reordering valueless flags keeps too: order-irrelevance is not a
518
+ * thing a token comparison can prove, a wrong keep costs a row, and a wrong
519
+ * refusal costs a fact.
520
+ */
521
+ function operandsDeclared(spans: string[], gate: Gate, gates: Gate[]): boolean {
522
+ for (const span of spans) {
523
+ const matched = gateHit([span], gates) ?? gate;
524
+ // Each span vouches with its OWN declaration. One shared label set let a
525
+ // second, unrelated mention lend its operands to the first: with `build:
526
+ // "compiler"` and `deploy: "deploy-tool publish --target staging …"`, the
527
+ // row `Run \`npm run deploy\`. Run \`npm run build -- --target staging\`.`
528
+ // checked the build operand against the deploy command, which happens to
529
+ // contain it, and the bare deploy mention hid the build information.
530
+ const candidates = operandCandidates(span, matched);
531
+ if (candidates.length === 0) return false;
532
+ const labels = vouchLabels(matched, gates);
533
+ if (!candidates.some((o) => o.length === 0 || contiguousIn(o, labels)))
534
+ return false;
535
+ }
536
+ return true;
537
+ }
538
+
430
539
  // Matching is positional, never substring. A gate named `all` must not refuse a
431
540
  // row that says `install all deps`, and `test` must not refuse a row about
432
541
  // "the test suite". So a single-word gate (a script name, a make target) only
@@ -460,10 +569,19 @@ function gateHit(spans: string[], gates: Gate[]): Gate | null {
460
569
  * the whole candidate was restatable. A short fragment is where a prohibition, a
461
570
  * window or a number lives; punctuation and "ship with" are what a fragment has
462
571
  * to be before it is ignored.
572
+ *
573
+ * A split never falls inside a figure. Splitting `1.5` at its dot produced two
574
+ * claims that each matched their own sentence and reassembled into a figure the
575
+ * tree never states, and the same fragments let a claim end mid-number in the
576
+ * tree. `tokens()` reads `.` as a word character, so the boundary waits for the
577
+ * figure run to end — including the sentence dot a figure ends on, which belongs
578
+ * to that token (`numericTokens("The cost is 11.")` is `["11."]`). A claim that
579
+ * therefore spans a sentence boundary is fail-open: a longer claim is harder to
580
+ * match, so the rule can only remove refusals.
463
581
  */
464
582
  function claims(text: string): string[] {
465
583
  const out: string[] = [];
466
- for (const part of text.split(/[.;:,\n]/)) {
584
+ for (const part of splitClaims(text)) {
467
585
  const c = part.trim();
468
586
  if (!c) continue;
469
587
  const words = c.split(/[^a-z0-9']+/).filter(Boolean);
@@ -474,6 +592,21 @@ function claims(text: string): string[] {
474
592
  return out;
475
593
  }
476
594
 
595
+ /** The assertion boundaries, minus a `.` that sits inside a figure. */
596
+ function splitClaims(text: string): string[] {
597
+ const parts: string[] = [];
598
+ let from = 0;
599
+ for (let i = 0; i < text.length; i++) {
600
+ const c = text.charCodeAt(i);
601
+ if (c !== 46 && c !== 59 && c !== 58 && c !== 10) continue;
602
+ if (c === 46 && figureRun(text, i)) continue;
603
+ parts.push(text.slice(from, i));
604
+ from = i + 1;
605
+ }
606
+ parts.push(text.slice(from));
607
+ return parts;
608
+ }
609
+
477
610
  /**
478
611
  * Does a sentence that states one of `commands` also FORBID it? Judged on those
479
612
  * sentences alone: the manifest says a command exists, so "Never run `x`" is a
@@ -483,7 +616,7 @@ function claims(text: string): string[] {
483
616
  * The bare words are here because `polaritySigns` reads `never` as a modifier
484
617
  * that needs a verb, and "Never `npm run deploy`." has the verb inside a code
485
618
  * span. A closed list, answering one closed question, over a decision that can
486
- * now only decline to tag.
619
+ * now only decline to refuse.
487
620
  */
488
621
  function forbidsCommand(content: string, commands: string[]): boolean {
489
622
  for (const sentence of content.split(/[.;:\n]+/)) {
@@ -519,20 +652,20 @@ function sentenceSpan(
519
652
  * against, because the cue list carries neither `stop` nor `drop` — and neither
520
653
  * does `polaritySigns`, so widening it the way an earlier round tried does not
521
654
  * catch this either. Measured on 05482ba: both `Stop assuming X` and `Drop the
522
- * assumption that X` tagged `X` as restatable.
655
+ * assumption that X` matched `X` as restatable.
523
656
  *
524
657
  * The veto reads the words between the sentence start and the hit, not the whole
525
- * sentence, and that is what keeps it cheap in tags. `The parser drops stale
526
- * entries.` states its claim and keeps its tag, because `drops` there governs
658
+ * sentence, and that is what keeps it cheap in refusals. `The parser drops stale
659
+ * entries.` states its claim and keeps its refusal, because `drops` there governs
527
660
  * `stale entries`, not a following assertion; the ambiguous verbs are therefore
528
- * veto words only when a claim noun follows them. Every veto declines to tag,
661
+ * veto words only when a claim noun follows them. Every veto declines to refuse,
529
662
  * which is the direction this file fails safe in.
530
663
  */
531
664
  const WARNS_AGAINST = new RegExp(
532
665
  // One alternation, ONE shared tail. Written as three separate alternatives
533
666
  // each ending in `$`, only the last would be anchored and the first would
534
667
  // match any sentence that merely contains `stop` anywhere — measured, and it
535
- // cost the tag from `The job stops at midnight and the cache supports TTL
668
+ // cost the refusal from `The job stops at midnight and the cache supports TTL
536
669
  // expiration.`, which states its claim plainly.
537
670
  "(?:" +
538
671
  // A deterrent verb needs no framing: what follows is being warned against.
@@ -568,9 +701,58 @@ function warnsAgainst(prefix: string): boolean {
568
701
  * A reversed clause is not evidence of availability, and every uncertainty in
569
702
  * this file keeps the candidate.
570
703
  */
571
- function findClause(hay: string, clause: string): number {
704
+ function isTokenChar(code: number): boolean {
705
+ return (
706
+ (code >= 48 && code <= 57) || // 0-9
707
+ (code >= 97 && code <= 122) || // a-z, after norm()
708
+ code === 95 || // _
709
+ code === 46 // .
710
+ );
711
+ }
712
+
713
+ /**
714
+ * The extent of the token `tokens()` would read at `pos`, when that token
715
+ * states a digit. `tokens()` splits on `[^a-z0-9_.]+`, so a dot is a word
716
+ * character: `1.5`, `1.4.3` and `10.20.30.40` are single tokens, and so is the
717
+ * `11.` of a sentence that ends on one. Nothing else in this file may decide
718
+ * where a figure begins or ends, because the same definition is what the figure
719
+ * subset check compares with.
720
+ */
721
+ function figureRun(
722
+ text: string,
723
+ pos: number,
724
+ ): { start: number; end: number } | null {
725
+ if (pos < 0 || pos >= text.length || !isTokenChar(text.charCodeAt(pos)))
726
+ return null;
727
+ let start = pos;
728
+ while (start > 0 && isTokenChar(text.charCodeAt(start - 1))) start--;
729
+ let end = pos;
730
+ while (end + 1 < text.length && isTokenChar(text.charCodeAt(end + 1))) end++;
731
+ if (!/[0-9]/.test(text.slice(start, end + 1))) return null;
732
+ return { start, end: end + 1 };
733
+ }
734
+
735
+ /**
736
+ * Does a hit cover every figure it touches, whole? A clause ending at the `3`
737
+ * of `3.12`, or starting at the `5` of `30.5`, cuts a figure in half, and the
738
+ * half re-tokenizes as a whole figure the tree never states: `3` is not in a
739
+ * README that says `Requires Python 3.12`, it is what slicing leaves behind.
740
+ * Word boundaries do not settle this — `.` is a word character to the tokenizer
741
+ * and a sentence boundary to the claim splitter, and the two disagree exactly
742
+ * inside a number. So a hit is admitted only when no figure run crosses either
743
+ * edge, which makes a half-figure unrepresentable rather than merely unvouched.
744
+ */
745
+ function hitCoversFigures(hay: string, start: number, end: number): boolean {
746
+ for (const pos of [start - 1, end]) {
747
+ const run = figureRun(hay, pos);
748
+ if (run && (run.start < start || run.end > end)) return false;
749
+ }
750
+ return true;
751
+ }
752
+
753
+ function findClause(hay: string, clause: string, start = 0): number {
572
754
  const reversed = cueNegated(clause);
573
- for (let from = 0; ; ) {
755
+ for (let from = start; ; ) {
574
756
  const i = hay.indexOf(clause, from);
575
757
  if (i < 0) return -1;
576
758
  const before = i > 0 ? hay.charCodeAt(i - 1) : 32;
@@ -580,6 +762,7 @@ function findClause(hay: string, clause: string): number {
580
762
  if (
581
763
  !/\w/.test(String.fromCharCode(before)) &&
582
764
  !/\w/.test(String.fromCharCode(after)) &&
765
+ hitCoversFigures(hay, i, i + clause.length) &&
583
766
  cueNegated(sentence.text) === reversed &&
584
767
  // A later occurrence may state the claim plainly, so a vetoed hit is
585
768
  // skipped rather than ending the search.
@@ -590,19 +773,75 @@ function findClause(hay: string, clause: string): number {
590
773
  }
591
774
  }
592
775
 
593
- /** True when every assertion in `clauses` is restatable from `hay`. */
594
- function allRestatable(hay: string, clauses: string[]): boolean {
595
- return hay !== "" && clauses.every((c) => findClause(hay, c) >= 0);
776
+ /**
777
+ * Is the text between two matched claims nothing but assertion punctuation and
778
+ * whitespace? The file joiner breaks contiguity on purpose: two claims from two
779
+ * files are not one statement.
780
+ */
781
+ function gapIsPunctuation(text: string): boolean {
782
+ for (let i = 0; i < text.length; i++) {
783
+ const c = text.charCodeAt(i);
784
+ if (c === 0) return false;
785
+ if (isBoundary(c) || c === 32 || c === 9) continue;
786
+ return false;
787
+ }
788
+ return true;
789
+ }
790
+
791
+ /**
792
+ * The region where the tree states `clauses` as ONE contiguous assertion, or
793
+ * null: each in the candidate's order, with nothing between one and the next
794
+ * but assertion punctuation and whitespace. The region is part of the answer:
795
+ * the figures a refusal vouches for are the ones the cited passage states.
796
+ *
797
+ * Matching every claim somewhere in the tree is not enough — two sentences can
798
+ * conspire. With `Staging export pool: cobalt-workers.` and `Production export
799
+ * pool: ask operations at rollout.` tracked, both halves of the candidate
800
+ * `Production export pool: cobalt-workers.` exist, but the pairing is the
801
+ * candidate's and not the tree's, and the pairing is the fact the session
802
+ * brought. Reassembled figures fail the same way, one level down.
803
+ *
804
+ * Order is part of the claim: a later half found only BEFORE the earlier one is
805
+ * not the tree stating it. The search takes the earliest admissible hit and
806
+ * skips a hit the gap disqualifies instead of ending there, so every
807
+ * uncertainty — including this check's own greediness — declines a refusal,
808
+ * which is the direction this file fails safe in.
809
+ */
810
+ function restatedContiguously(
811
+ hay: string,
812
+ clauses: string[],
813
+ ): { start: number; end: number } | null {
814
+ if (hay === "") return null;
815
+ let prevEnd = -1;
816
+ let cursor = 0;
817
+ let start = -1;
818
+ for (const clause of clauses) {
819
+ let hit = -1;
820
+ for (let from = cursor; ; ) {
821
+ const i = findClause(hay, clause, from);
822
+ if (i < 0) break;
823
+ if (prevEnd < 0 || gapIsPunctuation(hay.slice(prevEnd, i))) {
824
+ hit = i;
825
+ break;
826
+ }
827
+ from = i + 1;
828
+ }
829
+ if (hit < 0) return null;
830
+ if (start < 0) start = hit;
831
+ cursor = hit + 1;
832
+ prevEnd = hit + clause.length;
833
+ }
834
+ return { start, end: prevEnd };
596
835
  }
597
836
 
598
837
  export interface AvailabilityIndex {
599
- /** Null means "cannot tell", which stores the row with no tag. */
838
+ /** Null means "cannot tell, or cannot prove": the candidate is kept. */
600
839
  check(content: string): AvailabilityVerdict | null;
601
840
  /**
602
841
  * For evidence: what the tree scan actually read. `capped` means the byte
603
842
  * budget ran out before the tracked list did. It is telemetry only, never a
604
843
  * verdict input: both rules assert PRESENCE ("the tree states this"), so a
605
- * truncated scan can only lower the tag rate, never raise a false tag.
844
+ * truncated scan can only lower the refusal rate, never raise a false refusal.
606
845
  */
607
846
  scanned(): {
608
847
  files: number;
@@ -685,29 +924,45 @@ export function availabilityIndex(
685
924
  // - "Never run `npm run deploy` until finance confirms approval code
686
925
  // BLUEBIRD" refused because the manifest declares `deploy`, although
687
926
  // the restriction and the code appear nowhere.
688
- // A tag requires EVERY assertion the candidate makes to be restatable.
927
+ // A refusal requires EVERY assertion the candidate makes to be restatable.
689
928
  const whole = norm(content);
690
929
  const needed = claims(whole);
691
930
  if (needed.length === 0) needed.push(whole);
692
- const first = needed[0] ?? whole;
693
- // Evidence mirror of `whole` and `first`, scrubbed WHILE THE TEXT STILL HAS
694
- // ITS CASE. `norm()` lowercases, and the prefix scrubber in
931
+ // Evidence mirror of `whole` and of its first claim, scrubbed WHILE THE
932
+ // TEXT STILL HAS ITS CASE. `norm()` lowercases, and the prefix scrubber in
695
933
  // store/secrets.ts matches `AKIA[A-Z0-9]{16}` case-sensitively, so a span
696
934
  // normalised before scrubbing keeps a fully recoverable access key: the
697
935
  // logged `akia1234567890abcdef` uppercases straight back to the secret
698
936
  //. Redacting `avail.matched` later cannot recover what
699
937
  // normalisation already destroyed, so this is the only place it can be
700
- // done. Verdict logic reads `needed`/`first`, never these.
938
+ // done. Verdict logic reads `needed`, never these.
701
939
  const safeWhole = norm(redactSecrets(content));
702
940
  const safeFirst = claims(safeWhole)[0] ?? safeWhole;
703
- if (haystack && allRestatable(haystack, needed)) {
941
+ // A refusal here claims the tree states EVERY figure the candidate
942
+ // states AND states the whole candidate as one contiguous assertion.
943
+ // Neither follows from matching each claim somewhere: `claims()` splits
944
+ // on `.` and `:` used to split `1.5 seconds` into `1` and `5`, and a label
945
+ // from one line could be joined to a value from another; the splitter now
946
+ // keeps a figure whole, so what remains to prove is that the tree states
947
+ // the claims as ONE contiguous assertion.
948
+ //
949
+ // The figures are checked against the MATCHED REGION, not the whole
950
+ // tree. `The budget is 1, 5 seconds of margin.` chains across its comma
951
+ // and matches a row saying `1.5 seconds`; a `Node 1.5` in another file —
952
+ // or another sentence of the same file, which is why the whole file is
953
+ // not the scope either — is not the passage being cited, and cannot
954
+ // vouch for the figure the refusal claims it states.
955
+ const region = haystack ? restatedContiguously(haystack, needed) : null;
956
+ if (
957
+ region &&
958
+ figuresWithin(
959
+ content,
960
+ new Set(numericTokens(haystack.slice(region.start, region.end))),
961
+ )
962
+ ) {
704
963
  return {
705
964
  reason: "in_tracked_file",
706
- where:
707
- relative(
708
- repoDir,
709
- join(repoDir, fileAt(findClause(haystack, first))),
710
- ) || "?",
965
+ where: relative(repoDir, join(repoDir, fileAt(region.start))) || "?",
711
966
  matched: safeFirst.slice(0, 120),
712
967
  };
713
968
  }
@@ -721,9 +976,12 @@ export function availabilityIndex(
721
976
  // refused with the undeclared AWS prerequisite erased from the row;
722
977
  // - an EMPTY claim list counted as proof, so "Never `npm run deploy`."
723
978
  // refused with its only claim — `never` — dropped as too short.
724
- // A gate tag needs all three, each positively established:
725
- // 1. every command span the row states is declared. An undeclared one is
726
- // a fact the tree does not hold, whatever the rest of the row says;
979
+ // A gate refusal needs all three, each positively established:
980
+ // 1. every command span the row states is declared AS A RUN — the
981
+ // script exists, AND the operands it adds are a contiguous token
982
+ // run in the declaration. An undeclared span, or operands the
983
+ // declaration states only in another order or pairing, is a fact
984
+ // the tree does not hold, whatever the rest of the row says;
727
985
  // 2. what survives stripping them is nothing but FILLER — the bare
728
986
  // mention "ship with X", which is what the manifest does declare; or
729
987
  // 3. otherwise, every assertion left in it is one the tracked files
@@ -736,21 +994,26 @@ export function availabilityIndex(
736
994
  // no figure. So a sentence that forbids the command, or a number the
737
995
  // command does not carry, is a claim the declaration cannot answer.
738
996
  //
739
- // These REMOVE a tag and never add one, and a removed tag costs the row
740
- // nothing permanent: it is stored either way and a spare budget still
741
- // shows it. That asymmetry is the whole point of the change — the round-3
742
- // and round-4 arguments were really about a vocabulary that had to be
743
- // perfect because a miss deleted a fact. Under a tag, a miss costs one
744
- // injection slot.
997
+ // These REMOVE a refusal and never add one. A removed refusal costs one
998
+ // redundant row; a refusal that should have been removed costs a fact
999
+ // the store cannot rebuild. That asymmetry is the whole point of the
1000
+ // veto-only shape: the vocabulary never has to be perfect, because a
1001
+ // miss keeps the row instead of deleting it.
745
1002
  if (forbidsCommand(content, spans)) return null;
746
- if (introducesNewNumber(content, spans.join(" "))) return null;
1003
+ // The comparison text is the DECLARED command, never the candidate's
1004
+ // spans: a span carrying `--timeout 5000` would vouch for its own
1005
+ // figure, and the manifest states no such number.
1006
+ if (introducesNewNumber(content, gate.label)) return null;
1007
+ // The strip below removes the ENTIRE span, so what the span carries has
1008
+ // to be settled here or it is erased before anything reads it.
1009
+ if (!operandsDeclared(spans, gate, gates)) return null;
747
1010
  const undeclared = spans.some((s) => gateHit([s], gates) === null);
748
1011
  let residual = content;
749
1012
  for (const span of spans) residual = residual.split(span).join(" ");
750
1013
  const rest = claims(norm(residual));
751
1014
  if (
752
1015
  !undeclared &&
753
- (rest.length === 0 || allRestatable(haystack, rest))
1016
+ (rest.length === 0 || restatedContiguously(haystack, rest) !== null)
754
1017
  ) {
755
1018
  return {
756
1019
  reason: "declared_gate",
@@ -8,7 +8,6 @@ import { session, setCurrent } from "../core/state.ts";
8
8
  import {
9
9
  AUTO_CAPTURE_TAG,
10
10
  CODE_CHECKED_TAG,
11
- RESTATABLE_TAG,
12
11
  USER_GUIDED_TAG,
13
12
  } from "../core/tags.ts";
14
13
  import { type GateContext, runWriteGate } from "../gate/gate.ts";
@@ -852,13 +851,11 @@ export function configureAutoCapture(
852
851
  // recall loss here.
853
852
  let lessonsKept = 0;
854
853
  let lessonsRefused = 0;
855
- // rows tagged `restatable` this pass. Counted, never dropped.
856
- // Two numbers, because they are two different facts and one field that
857
- // silently means "verdicts" reads as "rows". A
858
- // verdict lands on candidates the write gate then refuses — a dup, a
859
- // credential-shaped scope — and a refused row carries no tag, so the
860
- // verdict count is an upper bound on the tagged count, never equal by
861
- // construction.
854
+ // `availVerdicts` counts candidates the availability check matched;
855
+ // `restatements` counts candidates refused because of it. Two numbers
856
+ // because they answer different questions — one about the check, one
857
+ // about the store — and a future consequence that is not refusal must
858
+ // not silently reuse the count.
862
859
  let availVerdicts = 0;
863
860
  let restatements = 0;
864
861
  candidates = candidates.filter((c) => {
@@ -892,21 +889,27 @@ export function configureAutoCapture(
892
889
  // flag, not the signal: this loop only runs once the answer exists,
893
890
  // and cleanup stops abandoning such a pass.
894
891
  if (phase.abandoned) return;
895
- // the availability verdict TAGS the row. It used to `continue`
896
- // past the write. A lexical match was never strong enough to delete
897
- // a fact — 29 of the 30 rows a pure-conflict refusal rejected were
898
- // new facts, and a silently dropped candidate leaves no trace to
899
- // recover from.
892
+ // A candidate the working tree already states, or whose only content
893
+ // is a command the project already declares, is REFUSED here — before
894
+ // the gate, before the store. The next session can read it from the
895
+ // file named in the refusal line, so the row buys nothing, and a
896
+ // capture pass costs about a third of a session's own generation.
900
897
  //
901
- // The row now goes through the same write gate as every other row, and
902
- // the tag is what retrieval acts on: `restatable` rows sort last, so a
903
- // full injection block gives them up first and a spare one keeps them.
904
- // A wrong verdict costs one row. A right one saves a slot. That is the
905
- // first shape of this where BOTH error directions are survivable:
906
- // an earlier one lost facts silently instead of expensively.
898
+ // The refusal is the hardened matcher's, not the original rule's: it
899
+ // fires only when EVERY assertion in the candidate is restatable
900
+ // verbatim modulo formatting, in a sentence of the same polarity,
901
+ // with no figure the tree does not carry. Every uncertainty — no
902
+ // git, an unreadable file, a byte cap, a dropped negation, one new
903
+ // number, one new clause — keeps the candidate. Fail-open is what
904
+ // protects the transport case: a fact the tree does not hold cannot
905
+ // match, so the store keeps everything only the store can carry. A
906
+ // wrong keep costs one redundant row; a wrong refusal costs a fact,
907
+ // and that is the direction the matcher's vetoes exist to make rare.
908
+ // History: docs/adr/.
907
909
  const avail = availability().check(c.content);
908
910
  if (avail) {
909
911
  availVerdicts++;
912
+ restatements++;
910
913
  await recordBestEffort(
911
914
  "auto_capture_restatable",
912
915
  {
@@ -921,13 +924,12 @@ export function configureAutoCapture(
921
924
  // yields `matched` ending in the NUL. Flattened for the reason
922
925
  // below.
923
926
  matched: flattenMemoryText(avail.matched),
924
- // The whole candidate, so the audit line alone can rebuild a row
925
- // a later consolidation drops. It records the VERDICT, not proof
926
- // of storage: this line is written before the gate, so a
927
- // candidate the gate then refuses has one and no row. The row's
928
- // fate is the adjacent `auto_capture_<action>` line, same pass,
929
- // same type and scope; `restatements` on the scan line counts
930
- // only rows that were really tagged.
927
+ // The whole candidate: the refusal is a judgement about the
928
+ // tree, so the audit line alone must be able to replay or
929
+ // rebuild it. This line IS the refusal record — a restatable
930
+ // candidate never reaches the gate, so there is no adjacent
931
+ // `auto_capture_<action>` line for it, and `restatements` on
932
+ // the scan line counts exactly these.
931
933
  //
932
934
  // Both free-text fields here are flattened, which nothing else on
933
935
  // this path does: `candidates.ts` checks type and scope for control
@@ -948,6 +950,7 @@ export function configureAutoCapture(
948
950
  sid,
949
951
  captureGate.evidenceContext,
950
952
  );
953
+ continue;
951
954
  }
952
955
  // a numeric claim capture INFERRED (the user did not state
953
956
  // it) that names a constant the tree also names is checked before it
@@ -1001,8 +1004,6 @@ export function configureAutoCapture(
1001
1004
  ...(original ? { original } : {}),
1002
1005
  tags: [
1003
1006
  AUTO_CAPTURE_TAG,
1004
- // the tree states this too. Stored anyway, sorted last.
1005
- ...(avail ? [RESTATABLE_TAG] : []),
1006
1007
  // the ONE case that earns `[code-checked]` — an inferred
1007
1008
  // numeric claim that agreed with the tree. Absent everywhere
1008
1009
  // else, which is what makes `[unverified]` mean something
@@ -1034,10 +1035,6 @@ export function configureAutoCapture(
1034
1035
  );
1035
1036
  continue;
1036
1037
  }
1037
- // The tag exists only on a row the gate really wrote. `blocked` writes
1038
- // nothing and `collapsed` folds into an existing row whose tags are not
1039
- // these, so only `promoted` can carry `restatable` into the store.
1040
- if (avail && outcome.action === "promoted") restatements++;
1041
1038
  await recordBestEffort(
1042
1039
  trigger === "compaction"
1043
1040
  ? `auto_capture_compaction_${outcome.action}`
@@ -1093,24 +1090,33 @@ export function configureAutoCapture(
1093
1090
  }
1094
1091
  // The scan is visible in the trail. A synchronous tree read must
1095
1092
  // never run every pass with no record that it happened: one line per
1096
- // pass that actually built the index, naming files, bytes and
1097
- // milliseconds.
1098
- if (availableIndex) {
1099
- const scan = availableIndex.scanned();
1093
+ // pass that had candidates, naming how many it saw and what the index
1094
+ // read — files, bytes, milliseconds. `candidates` is the denominator
1095
+ // that separates a dead matcher from an honest one: `verdicts=0` at
1096
+ // `candidates>0`, across passes, is matcher death, and an empty
1097
+ // session — no candidates, no line — never produces it. When the
1098
+ // index was never built (a pass abandoned before its first
1099
+ // candidate), the read fields are zero and `tracked=false` says so.
1100
+ if (availableIndex || candidates.length) {
1101
+ const scan = availableIndex
1102
+ ? availableIndex.scanned()
1103
+ : { files: 0, bytes: 0, tracked: false, capped: false };
1100
1104
  await recordBestEffort(
1101
1105
  "auto_capture_scan",
1102
1106
  {
1103
1107
  session: sid,
1104
1108
  trigger,
1109
+ candidates: candidates.length,
1105
1110
  files: scan.files,
1106
1111
  bytes: scan.bytes,
1107
1112
  ms: availableMs,
1108
1113
  tracked: scan.tracked,
1109
1114
  capped: scan.capped,
1110
- // Two numbers on purpose: `verdicts` is how many candidates the
1111
- // check matched, `restatements` how many rows carry the tag. They
1112
- // differ exactly by the verdicts the write gate refused, and a
1113
- // reader who sees one number will assume it is the other.
1115
+ // `verdicts` counts candidates the check matched, `restatements`
1116
+ // candidates refused as restatements. Equal while refusal is the
1117
+ // verdict's only consequence; kept apart because they count the
1118
+ // check and the store's fate, and a future consequence that is
1119
+ // not refusal must not silently reuse the count.
1114
1120
  verdicts: availVerdicts,
1115
1121
  restatements,
1116
1122
  ...(modelTag ? { model: modelTag } : {}),
@@ -26,6 +26,7 @@
26
26
  // 3. PROPOSALS, not writes. Nothing here mutates the store. A human resolves a
27
27
  // proposal through memory_merge_review (supersede-not-delete, recoverable).
28
28
  // 4. The most recently used member is never a loser (the rule, inherited).
29
+ import { createHash } from "node:crypto";
29
30
  import {
30
31
  MAX_KEYWORDS,
31
32
  type Memory,
@@ -191,6 +192,20 @@ export function absorbAliases(survivor: Memory, loser: Memory): Memory {
191
192
  };
192
193
  }
193
194
 
195
+ /** Bind one resolve command to the retrieval state that its step would publish. */
196
+ export function consolidationStepKey(merged: Memory, loser: Memory): string {
197
+ const seats = [merged, loser].map((m) => [
198
+ m.ts,
199
+ m.repo ?? "global",
200
+ m.repoPath,
201
+ m.type,
202
+ m.scope,
203
+ m.content,
204
+ m.kw ?? [],
205
+ ]);
206
+ return createHash("sha256").update(JSON.stringify(seats)).digest("hex");
207
+ }
208
+
194
209
  /**
195
210
  * Replay the cluster's real reads against a store where the cluster has been
196
211
  * replaced by the merged row. `rows` is the whole active store; the function
@@ -1,6 +1,10 @@
1
1
  // render — split from src/consolidate.ts. Declaration bodies are unchanged.
2
2
 
3
- import { type ProposalReport } from "./propose.ts";
3
+ import {
4
+ absorbAliases,
5
+ consolidationStepKey,
6
+ type ProposalReport,
7
+ } from "./propose.ts";
4
8
  import { flattenMemoryText } from "../store/sanitize.ts";
5
9
 
6
10
  /** Human-readable proposal list. Ends with the exact command to resolve one. */
@@ -11,6 +15,12 @@ export function renderProposals(report: ProposalReport): string {
11
15
  return out.join("\n");
12
16
  }
13
17
  for (const p of report.plans) {
18
+ let projected = p.survivor;
19
+ const commands = p.losers.map((loser) => {
20
+ projected = absorbAliases(projected, loser);
21
+ const expected = consolidationStepKey(projected, loser);
22
+ return ` resolve: memory_merge_review(loser="${loser.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}", consolidate=true, expected="${expected}")`;
23
+ });
14
24
  out.push(
15
25
  `${p.id} ${p.type}/${p.scope} ${p.losers.length + 1} rows → 1`,
16
26
  ` keep ${p.survivor.ts}`,
@@ -23,10 +33,7 @@ export function renderProposals(report: ProposalReport): string {
23
33
  ),
24
34
  ` reads ${p.reads.length} logged · best member alone ${p.bestMemberBefore} · merged ${p.readsAfter}`,
25
35
  ` budget ${p.bytesBefore}c → ${p.bytesAfter}c for this cluster`,
26
- ...p.losers.map(
27
- (loser) =>
28
- ` resolve: memory_merge_review(loser="${loser.ts}", survivor="${p.survivor.ts}", reason="consolidate ${p.id}", consolidate=true)`,
29
- ),
36
+ ...commands,
30
37
  "",
31
38
  );
32
39
  }
package/src/core/tags.ts CHANGED
@@ -3,14 +3,15 @@ export const AUTO_CAPTURE_TAG = "auto-capture";
3
3
 
4
4
  /**
5
5
  * the working tree already states this fact, so the next session can read
6
- * it there. Captured from the availability check, which TAGS instead of
7
- * dropping: the original refusal rule rejected 30 of 1,166 real rows and 29
8
- * of those were wrong — so a wrong match costs a tag instead of a fact
9
- * (docs/adr/0008).
6
+ * it there. Legacy: capture wrote this tag when its availability check
7
+ * tagged restatements instead of refusing them; refusal is the policy now
8
+ * (docs/adr/0009), so nothing writes it and it survives only on rows stored
9
+ * while tagging shipped.
10
10
  *
11
- * Retrieval sorts these rows last within their score band: a restatement is the
12
- * first thing to give up budget when the block is full, and the last thing worth
13
- * a slot when it is not.
11
+ * Retrieval sorts these rows last within their score band: a restatement is
12
+ * the first thing to give up budget when the block is full, and the last
13
+ * thing worth a slot when it is not. The demotion stays for the legacy rows:
14
+ * a stored row is kept, and a wrong tag costs only a slot.
14
15
  */
15
16
  export const RESTATABLE_TAG = "restatable";
16
17
 
@@ -101,15 +101,15 @@ export function isUserGuided(m: Memory): boolean {
101
101
  }
102
102
 
103
103
  /**
104
- * the working tree already states this fact. Such a row is STORED (it used
105
- * to be dropped at capture, which is the defect this serves for), but it is the
106
- * first thing a tight injection budget gives up: the next session can read it in
107
- * the file, so a slot spent on it is a slot not spent on something the files do
108
- * not hold.
104
+ * the working tree already states this fact. Capture refuses restatements
105
+ * now, so this tag marks rows stored while the availability check tagged
106
+ * instead of refusing; they are kept, and they are the first thing a tight
107
+ * injection budget gives up: the next session can read the fact in the file,
108
+ * so a slot spent on such a row is a slot not spent on something the files
109
+ * do not hold.
109
110
  *
110
- * The guided lane is exempt. A user-stated row outranks an inferred one in this
111
- * codebase everywhere, and capture tags guided rows too when their words are
112
- * verbatim in the tree.
111
+ * The guided lane is exempt. A user-stated row outranks an inferred one in
112
+ * this codebase everywhere.
113
113
  */
114
114
  export function isRestatable(m: Memory): boolean {
115
115
  return m.tags?.includes(RESTATABLE_TAG) === true;
package/src/store/undo.ts CHANGED
@@ -39,7 +39,7 @@ import { readLines } from "../core/logfmt/read.ts";
39
39
  import { contentHash } from "../telemetry/record.ts";
40
40
  import { isWithin } from "./containment.ts";
41
41
  import { snapshotFiles } from "./files/snapshots.ts";
42
- import { LOCK_RESTORE, withStoreLock } from "./lock.ts";
42
+ import { LOCK_RESTORE, withStoreBatch, withStoreLock } from "./lock.ts";
43
43
  import {
44
44
  ADMIN_READER,
45
45
  lineVisibleTo,
@@ -217,6 +217,22 @@ export async function restoreSnapshot(
217
217
  reader: Reader = ADMIN_READER,
218
218
  ): Promise<RestoreResult> {
219
219
  const snap = await resolveSnapshot(snapshot, memoryRootDir);
220
+ // A restore can replace either seat of a merge. Join its outer lock before
221
+ // taking a day-file lock so both seats stay stable through retirement.
222
+ return withStoreBatch(
223
+ memoryRootDir,
224
+ "update-order",
225
+ () => restoreResolvedSnapshot(snap, memoryRootDir, mode, reader),
226
+ LOCK_RESTORE,
227
+ );
228
+ }
229
+
230
+ async function restoreResolvedSnapshot(
231
+ snap: Awaited<ReturnType<typeof resolveSnapshot>>,
232
+ memoryRootDir: string,
233
+ mode: RestoreMode,
234
+ reader: Reader,
235
+ ): Promise<RestoreResult> {
220
236
  const rootReal = await realpath(resolve(memoryRootDir));
221
237
  const realTarget = resolve(rootReal, snap.original);
222
238
  if (!isWithin(rootReal, realTarget)) {
@@ -9,6 +9,7 @@ import { stampRow } from "../store/files/snapshots.ts";
9
9
  import { formatLine } from "../core/logfmt/format.ts";
10
10
  import {
11
11
  absorbAliases,
12
+ consolidationStepKey,
12
13
  sameConsolidationScope,
13
14
  } from "../consolidate/propose.ts";
14
15
  import { clearSuperseded, markSuperseded } from "../store/files/supersede.ts";
@@ -22,7 +23,7 @@ export const register: ToolRegister = (editor, deps) => {
22
23
  validated(MergeReviewArgs, {
23
24
  name: "memory_merge_review",
24
25
  description:
25
- "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, either id names a missing or blocklisted row, the loser is already superseded or is the survivor itself, either seat names a foreign repository's row, or the survivor's supersession was written by a row other than this review's loser (a later update's marker is never erased). Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
26
+ "Resolve an open merge/review gate non-destructively: mark the loser as superseded_by the survivor, and clear any supersession the survivor itself carries so the canonical row stays recallable. Both rows stay active data (the loser is recoverable via memory_undo); nothing is deleted. A session may merge exactly the rows it may read: global rows are mergeable from anywhere, but a row belonging to another repository is refused in either seat. Refuses before writing when the reason or the survivor id is missing, either id names a missing or blocklisted row, the loser is already superseded or is the survivor itself, either seat names a foreign repository's row, or the survivor's supersession was written by a row other than this review's loser (a later update's marker is never erased). A consolidation command also refuses before writing if its expected digest is missing or no longer matches the store. Later lock or I/O failures can leave partial changes; the reply names the completed retirement and failure.",
26
27
  options: direct,
27
28
  async execute(args, context): Promise<{ content: string }> {
28
29
  const { sid } = toolIds(context);
@@ -38,6 +39,12 @@ export const register: ToolRegister = (editor, deps) => {
38
39
  "merge_review blocked: loser, survivor, and reason are all required (fail-closed).",
39
40
  };
40
41
  }
42
+ if (args.expected !== undefined && !args.consolidate) {
43
+ return {
44
+ content:
45
+ "Consolidation blocked: use the full command printed by memory_consolidate.",
46
+ };
47
+ }
41
48
  if (args.loser === args.survivor) {
42
49
  // (Same-row input would mark and then revive the same row: a
43
50
  // silent no-op that reports full success.)
@@ -150,7 +157,7 @@ export const register: ToolRegister = (editor, deps) => {
150
157
  }
151
158
  // Publish the aliases first. If retirement fails, the loser
152
159
  // remains searchable and reapplying the union is idempotent.
153
- consolidationStarted = true;
160
+ let stale = false;
154
161
  const present = await stampRow(
155
162
  survivorRow.file,
156
163
  survivorRow.ts,
@@ -169,12 +176,25 @@ export const register: ToolRegister = (editor, deps) => {
169
176
  throw new Error("survivor changed since the proposal");
170
177
  }
171
178
  const merged = absorbAliases(current, loserRow);
179
+ if (
180
+ consolidationStepKey(merged, loserRow) !== args.expected
181
+ ) {
182
+ stale = true;
183
+ return null;
184
+ }
185
+ consolidationStarted = true;
172
186
  const kw = merged.kw?.join(",");
173
187
  const tags = merged.tags!.join(",");
174
188
  if (fields.kw === kw && fields.tags === tags) return null;
175
189
  return formatLine({ ...fields, kw, tags });
176
190
  },
177
191
  );
192
+ if (stale) {
193
+ return {
194
+ content:
195
+ "Consolidation blocked: this command no longer matches the preview or is missing its expected value. Run memory_consolidate again and review the new read estimate before applying it.",
196
+ };
197
+ }
178
198
  if (present === null)
179
199
  throw new Error("survivor no longer exists");
180
200
  }
@@ -147,6 +147,12 @@ export const EvidenceArgs = z.object({
147
147
  });
148
148
 
149
149
  export const MergeReviewArgs = z.object({
150
+ expected: z
151
+ .string()
152
+ .optional()
153
+ .describe(
154
+ "Required with consolidate=true. Copy this step's expected value from the printed consolidation command.",
155
+ ),
150
156
  consolidate: z
151
157
  .boolean()
152
158
  .optional()