opencode-self-improvement 0.24.2 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -3
- package/package.json +2 -1
- package/src/capture/available.ts +767 -0
- package/src/capture/runtime.ts +240 -13
- package/src/core/guidance.ts +23 -1
- package/src/core/tags.ts +14 -0
- package/src/recall/relevant.ts +32 -2
package/README.md
CHANGED
|
@@ -104,12 +104,16 @@ What is established, from tests and fixtures (no live store involved):
|
|
|
104
104
|
|
|
105
105
|
- **Teardown stops work that is still in flight.** `generate.text` does not take the abort signal, so a capture parked mid-model-call used to wake up after the host disposed the plugin and run the whole write gate against a store its caller had already removed. Cleanup now aborts the subscription, every pass re-checks the signal after the model call and between candidates (a gate already mutating is never cut in half), and cleanup drains the tracked passes under a one-second bound — teardown never waits on the model. `test/capture-dispose-drain.test.ts` parks a capture, disposes, releases, and asserts that no row and no evidence line carries a timestamp after disposal (#211).
|
|
106
106
|
|
|
107
|
+
- **The trigger is live on a real host, and the write now survives it.** An end-to-end scenario drives `opencode run` against a real turn with a scripted provider (`e2e/capture.test.ts`): the turn-end event fires and a capture pass starts, 12 of 12 runs. It used to reach the write gate in only some of them — 3 of 12 in one sample, 6 of 12 in a controlled A/B against the same script, 12 of 12 in two samples after the fix. `opencode run` disposes the plugin as the turn ends, and `captureCleanup` aborted every in-flight pass before its gate ran: the #211 contract, correct for the teardown it was written for and fatal here, because nothing is being torn down and the process simply exits. Cleanup now distinguishes the two cases — a pass still parked in the model call is abandoned, a pass that already holds its answer is drained, because its remaining work is local and milliseconds. All of #211's disposal assertions still pass unchanged. Fixed on this branch, #404.
|
|
108
|
+
|
|
109
|
+
- **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.
|
|
110
|
+
|
|
107
111
|
What is not established:
|
|
108
112
|
|
|
109
|
-
- That a live host
|
|
110
|
-
- Anything about quality. What auto-capture would write, how often it duplicates a memory you would have written yourself, and what it costs remain unmeasured. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor — its compaction world captured 0 rows and 4 of its 6 controls report FAIL. It answers "which moment is worth mining", not "does the shipped feature work".
|
|
113
|
+
- That a live host with a live model completes a capture end to end. The event and the pass are no longer in doubt — `e2e/capture.test.ts` shows a real `opencode run` turn firing a real pass — but no `auto_capture_*` line and no `capture_lag` line exists anywhere in the maintainer's evidence history (checked 2026-10-26 through 2026-10-29), and #404 found the mechanism by which a CLI session would produce none even when everything else works — the fix is on this branch, but no live store has been observed completing a pass yet. A live trial armed on 2026-10-26 was stood down on 2026-10-29 without ever firing, so it answered nothing.
|
|
114
|
+
- Anything about quality on a live store. What auto-capture would write, how often it duplicates a memory you would have written yourself, and what it costs remain unmeasured. `bench/capture-trigger-results.md` is a **bench** simulation of trigger *timing* with a scripted extractor — its compaction world captured 0 rows and 4 of its 6 controls report FAIL. It answers "which moment is worth mining", not "does the shipped feature work".
|
|
111
115
|
|
|
112
|
-
**Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=off` (the option is not on), `invalid_model` (`captureModel` is not `provider/id`), `no_capabilities` (the host did not expose what capture needs) or `capture=on`, next to `subscribed=[…]` listing the event types that subscription really reacts to. On desktop this needs `opencode service restart` after an edit — relaunching the app keeps the old service and its already-parsed options alive, so `capture=` can report a value your config no longer contains. `capture=on` plus no `auto_capture_*` line after a session
|
|
116
|
+
**Am I armed?** `memory_evidence` answers on the `plugin_load` line: `capture=off` (the option is not on), `invalid_model` (`captureModel` is not `provider/id`), `no_capabilities` (the host did not expose what capture needs) or `capture=on`, next to `subscribed=[…]` listing the event types that subscription really reacts to. On desktop this needs `opencode service restart` after an edit — relaunching the app keeps the old service and its already-parsed options alive, so `capture=` can report a value your config no longer contains. `capture=on` plus no `auto_capture_*` line after a session means the pass did not complete, not that your configuration is wrong; #404 is the known cause and its fix is on this branch.
|
|
113
117
|
|
|
114
118
|
## How memory is written
|
|
115
119
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.25.0",
|
|
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": {
|
|
@@ -65,6 +65,7 @@
|
|
|
65
65
|
"bench": "bun bench/runners/inject-cost.ts",
|
|
66
66
|
"bench:recall": "bun bench/runners/recall-quality.ts",
|
|
67
67
|
"bench:write": "bun bench/runners/write-latency.ts",
|
|
68
|
+
"bench:availability": "bun bench/runners/availability-policy-compare.ts",
|
|
68
69
|
"sweep:test": "bun scripts/test-sweep.ts",
|
|
69
70
|
"memory-view": "bun run src/viewer/server.ts",
|
|
70
71
|
"format": "biome format --write",
|
|
@@ -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
|
+
}
|
package/src/capture/runtime.ts
CHANGED
|
@@ -6,6 +6,7 @@ import { session, setCurrent } from "../core/state.ts";
|
|
|
6
6
|
import {
|
|
7
7
|
AUTO_CAPTURE_TAG,
|
|
8
8
|
CODE_CHECKED_TAG,
|
|
9
|
+
RESTATABLE_TAG,
|
|
9
10
|
USER_GUIDED_TAG,
|
|
10
11
|
} from "../core/tags.ts";
|
|
11
12
|
import { record, recordCaptureLag } from "../evidence/record.ts";
|
|
@@ -22,6 +23,7 @@ import {
|
|
|
22
23
|
import { quarantineCandidate } from "../store/quarantine/quarantine.ts";
|
|
23
24
|
import { flattenMemoryText } from "../store/sanitize.ts";
|
|
24
25
|
import { redactSecrets } from "../store/secrets.ts";
|
|
26
|
+
import { type AvailabilityIndex, availabilityIndex } from "./available.ts";
|
|
25
27
|
import { parseCandidates, parseModelRef } from "./candidates.ts";
|
|
26
28
|
import { claimVerdictFromContent } from "./checked.ts";
|
|
27
29
|
import {
|
|
@@ -235,30 +237,102 @@ export function configureAutoCapture(
|
|
|
235
237
|
// gate receipts, promoted rows, supersession. The contract is bounded
|
|
236
238
|
// and explicit:
|
|
237
239
|
// 1. cleanup aborts the subscription, so no NEW pass starts;
|
|
238
|
-
// 2. every pass checks
|
|
239
|
-
// candidates, and stops BEFORE the next gate run — a gate
|
|
240
|
-
// mutating is never cut in half, because a half-applied gate is
|
|
240
|
+
// 2. every pass checks its own abandonment flag after the model call and
|
|
241
|
+
// between candidates, and stops BEFORE the next gate run — a gate
|
|
242
|
+
// already mutating is never cut in half, because a half-applied gate is
|
|
241
243
|
// worse than a late one;
|
|
242
244
|
// 3. cleanup then drains the tracked passes up to DRAIN_LIMIT_MS, so
|
|
243
245
|
// a caller that removes the store right after cleanup sees nothing
|
|
244
|
-
// straggling. A
|
|
245
|
-
//
|
|
246
|
+
// straggling. A pass still working when the bound expires is abandoned
|
|
247
|
+
// there and then, so it stops at its next candidate boundary; a
|
|
248
|
+
// generate that outlives the bound is covered by (2), not by the
|
|
249
|
+
// drain: teardown never waits on the model.
|
|
250
|
+
//
|
|
251
|
+
// #404 changed (2) from one signal into two phases, because one signal
|
|
252
|
+
// conflated two different situations and the conflation killed the feature
|
|
253
|
+
// on the CLI. A pass PARKED in `generate.text` when the host disposes must
|
|
254
|
+
// never write — that is #211, and the caller may remove the store the
|
|
255
|
+
// moment cleanup resolves. A pass that already HOLDS its model answer is
|
|
256
|
+
// different work: the answer exists, the gate is milliseconds of local
|
|
257
|
+
// work, and on `opencode run` nothing is being removed at all — the process
|
|
258
|
+
// simply exits. Aborting that pass is why most real CLI passes recorded
|
|
259
|
+
// `capture_cost` and no row — 9 of 12 in one sample, 6 of 12 in a
|
|
260
|
+
// controlled A/B (#404): the abort fired on the healthy path, in the only
|
|
261
|
+
// window capture is allowed to run. Past-model passes are bounded by the
|
|
262
|
+
// drain instead, which is what the drain is for.
|
|
246
263
|
const DRAIN_LIMIT_MS = 1000;
|
|
264
|
+
type PassPhase = {
|
|
265
|
+
/** Set the instant `generate.text` resolves. */
|
|
266
|
+
pastModel: boolean;
|
|
267
|
+
/** Set by cleanup, and only for a pass that has not answered yet. */
|
|
268
|
+
abandoned: boolean;
|
|
269
|
+
};
|
|
247
270
|
const inFlight = new Set<Promise<unknown>>();
|
|
248
|
-
|
|
249
|
-
|
|
271
|
+
const passPhases = new Set<PassPhase>();
|
|
272
|
+
function newPhase(): PassPhase {
|
|
273
|
+
return { pastModel: false, abandoned: false };
|
|
274
|
+
}
|
|
275
|
+
function track<T>(pass: Promise<T>, phase?: PassPhase): Promise<T> {
|
|
276
|
+
const wrapped = pass.finally(() => {
|
|
277
|
+
inFlight.delete(wrapped);
|
|
278
|
+
if (phase) passPhases.delete(phase);
|
|
279
|
+
});
|
|
280
|
+
if (phase) passPhases.add(phase);
|
|
250
281
|
inFlight.add(wrapped);
|
|
251
282
|
return wrapped;
|
|
252
283
|
}
|
|
284
|
+
/**
|
|
285
|
+
* Teardown, in two phases (#404).
|
|
286
|
+
*
|
|
287
|
+
* 1. Abandon every pass that has not answered yet, then drain what is
|
|
288
|
+
* left, bounded. A parked `generate.text` can outlive any bound, so
|
|
289
|
+
* abandoning it is what makes the bound mean something: #211's caller
|
|
290
|
+
* may remove the store the moment cleanup resolves.
|
|
291
|
+
* 2. A pass that already holds its answer is never abandoned. It is
|
|
292
|
+
* drained instead, because its remaining work is the gate — local,
|
|
293
|
+
* milliseconds — and killing it is what lost most real CLI captures
|
|
294
|
+
* (#404: 9 of 12 in one sample, 6 of 12 in a controlled A/B).
|
|
295
|
+
*
|
|
296
|
+
* The residual risk is a stated constant, not an accident. If the bound
|
|
297
|
+
* expires while a past-model pass is still working, cleanup returns and at
|
|
298
|
+
* most the gate run already in progress can land afterwards — the drain
|
|
299
|
+
* abandons the pass so its remaining candidates stop at the next boundary.
|
|
300
|
+
* Before #404 that residual was unbounded in a different way: a generate
|
|
301
|
+
* that outlived the bound woke up and ran the whole gate, which is what
|
|
302
|
+
* #211 was filed about. Neither version ever cuts a gate in half.
|
|
303
|
+
*
|
|
304
|
+
* Nothing here writes. #211's tested contract is that a disposed instance
|
|
305
|
+
* leaves no trace at all after cleanup, and an abandonment receipt would
|
|
306
|
+
* break it in all four of that issue's cases — `appendLog` calls
|
|
307
|
+
* `ensureDir`, so the receipt resurrects a directory the caller deleted.
|
|
308
|
+
* An abandoned pass is instead identified by the gap it leaves: a
|
|
309
|
+
* `capture_cost` line with no later `capture_lag` for the same session is
|
|
310
|
+
* a pass that was cut, and both lines are already written.
|
|
311
|
+
*/
|
|
253
312
|
async function drainInFlight(): Promise<void> {
|
|
313
|
+
for (const phase of passPhases) {
|
|
314
|
+
if (!phase.pastModel) phase.abandoned = true;
|
|
315
|
+
}
|
|
254
316
|
if (!inFlight.size) return;
|
|
317
|
+
let timedOut = false;
|
|
255
318
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
256
319
|
const bound = new Promise<void>((resolve) => {
|
|
257
|
-
timer = setTimeout(
|
|
320
|
+
timer = setTimeout(() => {
|
|
321
|
+
timedOut = true;
|
|
322
|
+
resolve();
|
|
323
|
+
}, DRAIN_LIMIT_MS);
|
|
258
324
|
});
|
|
259
325
|
await Promise.race([Promise.allSettled([...inFlight]), bound]).finally(
|
|
260
326
|
() => clearTimeout(timer),
|
|
261
327
|
);
|
|
328
|
+
// The bound expired, so cleanup is returning while a pass still works.
|
|
329
|
+
// Abandon it now: it is past the model, so it may not be stopped inside a
|
|
330
|
+
// gate run, but it stops at the next candidate boundary instead of
|
|
331
|
+
// running an unbounded list against a process that is on its way out.
|
|
332
|
+
// That makes the residual risk a stated constant — at most the one gate
|
|
333
|
+
// run already in progress can land after cleanup returns — rather than a
|
|
334
|
+
// function of how many candidates the model returned.
|
|
335
|
+
if (timedOut) for (const phase of passPhases) phase.abandoned = true;
|
|
262
336
|
}
|
|
263
337
|
const eventApi = ctx.event;
|
|
264
338
|
const generateApi = ctx.generate;
|
|
@@ -328,6 +402,14 @@ export function configureAutoCapture(
|
|
|
328
402
|
// cannot re-stamp this operation's receipts. Optional for direct
|
|
329
403
|
// callers, which bind here instead.
|
|
330
404
|
gate?: GateContext,
|
|
405
|
+
// Teardown phase, owned by the caller that `track()`s this pass. Both
|
|
406
|
+
// production triggers pass one. The default is for direct callers —
|
|
407
|
+
// tests, and any future seam that runs a pass outside the subscription —
|
|
408
|
+
// and reads "not drainable, so not abandonable": an untracked pass is
|
|
409
|
+
// not in `inFlight`, so cleanup could neither wait for it nor stop it
|
|
410
|
+
// safely, and killing work the drain cannot bound is the failure mode
|
|
411
|
+
// this parameter exists to avoid.
|
|
412
|
+
phase: PassPhase = { pastModel: true, abandoned: false },
|
|
331
413
|
): Promise<void> {
|
|
332
414
|
const captureGate = gate ?? bindCapture(sid);
|
|
333
415
|
const captureReader = captureGate.reader ?? readerFromSid(sid);
|
|
@@ -539,13 +621,17 @@ export function configureAutoCapture(
|
|
|
539
621
|
model,
|
|
540
622
|
prompt: capturePrompt,
|
|
541
623
|
});
|
|
624
|
+
// The phase boundary. From here the answer exists, so cleanup stops
|
|
625
|
+
// abandoning this pass and drains it instead (#404). Set before the next
|
|
626
|
+
// await, so a disposal during anything below cannot be missed.
|
|
627
|
+
phase.pastModel = true;
|
|
542
628
|
const text = typeof out === "string" ? out : (out?.text ?? "");
|
|
543
|
-
// #211:
|
|
629
|
+
// #211: abandoned while the model call was in flight. Stop here — the
|
|
544
630
|
// gate, the rows and the receipts below all write to a store the
|
|
545
631
|
// caller may already have removed. Silent on purpose: a receipt here
|
|
546
632
|
// is the ENOENT teardown noise this check exists to eliminate, and
|
|
547
633
|
// the drain in cleanup means the pass is finished, not lost mid-air.
|
|
548
|
-
if (
|
|
634
|
+
if (phase.abandoned) return;
|
|
549
635
|
// #387: bill our own call. `generate.text` resolves to `{ text }` and
|
|
550
636
|
// nothing else — no `usage`, no `tokens` (probed against the running
|
|
551
637
|
// host) — and capture is not part of any session's event stream, so a
|
|
@@ -656,6 +742,31 @@ export function configureAutoCapture(
|
|
|
656
742
|
c.original = undefined;
|
|
657
743
|
}
|
|
658
744
|
}
|
|
745
|
+
// #389: availability before authority. A candidate that restates a
|
|
746
|
+
// tracked file, or names a command the project already declares, is
|
|
747
|
+
// readable by the next session without a row — and capture costs about a
|
|
748
|
+
// third of a session's own generation.
|
|
749
|
+
//
|
|
750
|
+
// #402 P0: built on FIRST USE, not on every pass. The build is a
|
|
751
|
+
// synchronous `git ls-files` plus a read of every tracked text file —
|
|
752
|
+
// measured here at 108 ms for 218 files and 2.11 MB — and the pass that
|
|
753
|
+
// needs it least is the one that used to pay for it: a model answer of
|
|
754
|
+
// `[]` still scanned the tree. One build per pass is kept, so the cost is
|
|
755
|
+
// now bounded by the candidates that exist.
|
|
756
|
+
let availableIndex: AvailabilityIndex | undefined;
|
|
757
|
+
let availableMs = 0;
|
|
758
|
+
const availability = (): AvailabilityIndex => {
|
|
759
|
+
if (!availableIndex) {
|
|
760
|
+
const t0 = Date.now();
|
|
761
|
+
availableIndex = availabilityIndex(
|
|
762
|
+
captureReader.kind === "repo"
|
|
763
|
+
? captureReader.scope.path
|
|
764
|
+
: undefined,
|
|
765
|
+
);
|
|
766
|
+
availableMs = Date.now() - t0;
|
|
767
|
+
}
|
|
768
|
+
return availableIndex;
|
|
769
|
+
};
|
|
659
770
|
// S1 (learn-from-failure): a row that CITES a failing command is
|
|
660
771
|
// claiming to be a lesson, and the claim is checked against the ledger,
|
|
661
772
|
// not against the model's retelling. ReMe (Findings ACL 2026) found
|
|
@@ -672,6 +783,15 @@ export function configureAutoCapture(
|
|
|
672
783
|
// recall loss here.
|
|
673
784
|
let lessonsKept = 0;
|
|
674
785
|
let lessonsRefused = 0;
|
|
786
|
+
// #402: rows tagged `restatable` this pass. Counted, never dropped.
|
|
787
|
+
// Two numbers, because they are two different facts and one field that
|
|
788
|
+
// silently means "verdicts" reads as "rows" (#403 review round 1). A
|
|
789
|
+
// verdict lands on candidates the write gate then refuses — a dup, a
|
|
790
|
+
// credential-shaped scope — and a refused row carries no tag, so the
|
|
791
|
+
// verdict count is an upper bound on the tagged count, never equal by
|
|
792
|
+
// construction.
|
|
793
|
+
let availVerdicts = 0;
|
|
794
|
+
let restatements = 0;
|
|
675
795
|
candidates = candidates.filter((c) => {
|
|
676
796
|
if (c.failure === undefined) return true;
|
|
677
797
|
const cite = normWs(c.failure).toLowerCase();
|
|
@@ -699,8 +819,67 @@ export function configureAutoCapture(
|
|
|
699
819
|
);
|
|
700
820
|
for (const c of candidates) {
|
|
701
821
|
// Between candidates, never inside a gate run: a supersession that
|
|
702
|
-
// half-applied is a store the next session cannot trust.
|
|
703
|
-
|
|
822
|
+
// half-applied is a store the next session cannot trust. The phase
|
|
823
|
+
// flag, not the signal: this loop only runs once the answer exists,
|
|
824
|
+
// and cleanup stops abandoning such a pass (#404).
|
|
825
|
+
if (phase.abandoned) return;
|
|
826
|
+
// #402: the availability verdict TAGS the row. It used to `continue`
|
|
827
|
+
// past the write, and that is the defect #402 exists for. A lexical
|
|
828
|
+
// match was never strong enough to delete a fact — 29 of the 30 rows
|
|
829
|
+
// the first version refused were new facts, and a silently dropped
|
|
830
|
+
// candidate leaves no trace to recover from.
|
|
831
|
+
//
|
|
832
|
+
// The row now goes through the same write gate as every other row, and
|
|
833
|
+
// the tag is what retrieval acts on: `restatable` rows sort last, so a
|
|
834
|
+
// full injection block gives them up first and a spare one keeps them.
|
|
835
|
+
// A wrong verdict costs one row. A right one saves a slot. That is the
|
|
836
|
+
// first version of this where the two error directions are both
|
|
837
|
+
// survivable, which is why four rounds of patches could not produce it.
|
|
838
|
+
const avail = availability().check(c.content);
|
|
839
|
+
if (avail) {
|
|
840
|
+
availVerdicts++;
|
|
841
|
+
await record(
|
|
842
|
+
"auto_capture_restatable",
|
|
843
|
+
{
|
|
844
|
+
session: sid,
|
|
845
|
+
trigger,
|
|
846
|
+
type: c.type,
|
|
847
|
+
scope: redactSecrets(c.scope),
|
|
848
|
+
reason: avail.reason,
|
|
849
|
+
where: avail.where,
|
|
850
|
+
// `matched` is a slice of the CANDIDATE, not of the tree, so it
|
|
851
|
+
// carries model prose too: measured, `Ship with \`npm run deploy\`.<NUL>`
|
|
852
|
+
// yields `matched` ending in the NUL. Flattened for the reason
|
|
853
|
+
// below.
|
|
854
|
+
matched: flattenMemoryText(avail.matched),
|
|
855
|
+
// The whole candidate, so the audit line alone can rebuild a row
|
|
856
|
+
// a later consolidation drops. It records the VERDICT, not proof
|
|
857
|
+
// of storage: this line is written before the gate, so a
|
|
858
|
+
// candidate the gate then refuses has one and no row. The row's
|
|
859
|
+
// fate is the adjacent `auto_capture_<action>` line, same pass,
|
|
860
|
+
// same type and scope; `restatements` on the scan line counts
|
|
861
|
+
// only rows that were really tagged.
|
|
862
|
+
//
|
|
863
|
+
// Both free-text fields here are flattened, which nothing else on
|
|
864
|
+
// this path does: `candidates.ts` checks type and scope for control
|
|
865
|
+
// characters but not content, `scrubFields` only redacts
|
|
866
|
+
// credentials, and the logfmt writer escapes `\ " \n \r \t` and
|
|
867
|
+
// nothing else. Without this, a NUL or U+2028 from model prose
|
|
868
|
+
// lands raw in the day log and `memory_evidence` hands it straight
|
|
869
|
+
// back to a model. Redact FIRST: flattening a PEM body would break
|
|
870
|
+
// the pattern that recognises it. The systemic version — flattening
|
|
871
|
+
// every string field in `scrubFields` — is deliberately NOT done
|
|
872
|
+
// here, because it would change the meaning of existing audit
|
|
873
|
+
// lines that carry multi-line values.
|
|
874
|
+
content: flattenMemoryText(redactSecrets(c.content)),
|
|
875
|
+
...(c.guided ? { guided: true } : {}),
|
|
876
|
+
...(modelTag ? { model: modelTag } : {}),
|
|
877
|
+
},
|
|
878
|
+
false,
|
|
879
|
+
sid,
|
|
880
|
+
captureGate.evidenceContext,
|
|
881
|
+
);
|
|
882
|
+
}
|
|
704
883
|
// #393 AC 2: a numeric claim capture INFERRED (the user did not state
|
|
705
884
|
// it) that names a constant the tree also names is checked before it
|
|
706
885
|
// is stored. Only a contradiction refuses; "undecidable" is the
|
|
@@ -753,6 +932,8 @@ export function configureAutoCapture(
|
|
|
753
932
|
...(original ? { original } : {}),
|
|
754
933
|
tags: [
|
|
755
934
|
AUTO_CAPTURE_TAG,
|
|
935
|
+
// #402: the tree states this too. Stored anyway, sorted last.
|
|
936
|
+
...(avail ? [RESTATABLE_TAG] : []),
|
|
756
937
|
// #393: the ONE case that earns `[code-checked]` — an inferred
|
|
757
938
|
// numeric claim that agreed with the tree. Absent everywhere
|
|
758
939
|
// else, which is what makes `[unverified]` mean something
|
|
@@ -784,6 +965,10 @@ export function configureAutoCapture(
|
|
|
784
965
|
);
|
|
785
966
|
continue;
|
|
786
967
|
}
|
|
968
|
+
// The tag exists only on a row the gate really wrote. `blocked` writes
|
|
969
|
+
// nothing and `collapsed` folds into an existing row whose tags are not
|
|
970
|
+
// these, so only `promoted` can carry `restatable` into the store.
|
|
971
|
+
if (avail && outcome.action === "promoted") restatements++;
|
|
787
972
|
await record(
|
|
788
973
|
trigger === "compaction"
|
|
789
974
|
? `auto_capture_compaction_${outcome.action}`
|
|
@@ -837,6 +1022,35 @@ export function configureAutoCapture(
|
|
|
837
1022
|
}
|
|
838
1023
|
}
|
|
839
1024
|
}
|
|
1025
|
+
// #402 P0: the scan is now visible in the trail. `scanned()` shipped
|
|
1026
|
+
// "for evidence" and was never called, so a synchronous tree read ran
|
|
1027
|
+
// every pass with no record that it happened. One line per pass that
|
|
1028
|
+
// actually built the index, naming files, bytes and milliseconds.
|
|
1029
|
+
if (availableIndex) {
|
|
1030
|
+
const scan = availableIndex.scanned();
|
|
1031
|
+
await record(
|
|
1032
|
+
"auto_capture_scan",
|
|
1033
|
+
{
|
|
1034
|
+
session: sid,
|
|
1035
|
+
trigger,
|
|
1036
|
+
files: scan.files,
|
|
1037
|
+
bytes: scan.bytes,
|
|
1038
|
+
ms: availableMs,
|
|
1039
|
+
tracked: scan.tracked,
|
|
1040
|
+
capped: scan.capped,
|
|
1041
|
+
// Two numbers on purpose: `verdicts` is how many candidates the
|
|
1042
|
+
// check matched, `restatements` how many rows carry the tag. They
|
|
1043
|
+
// differ exactly by the verdicts the write gate refused, and a
|
|
1044
|
+
// reader who sees one number will assume it is the other.
|
|
1045
|
+
verdicts: availVerdicts,
|
|
1046
|
+
restatements,
|
|
1047
|
+
...(modelTag ? { model: modelTag } : {}),
|
|
1048
|
+
},
|
|
1049
|
+
false,
|
|
1050
|
+
sid,
|
|
1051
|
+
captureGate.evidenceContext,
|
|
1052
|
+
);
|
|
1053
|
+
}
|
|
840
1054
|
await recordCaptureLag(
|
|
841
1055
|
sid,
|
|
842
1056
|
lagMs,
|
|
@@ -884,9 +1098,15 @@ export function configureAutoCapture(
|
|
|
884
1098
|
// another repository; resolving it there would stamp the failure
|
|
885
1099
|
// receipt of repo A's capture as repo B's evidence.
|
|
886
1100
|
let opGate: GateContext | undefined;
|
|
1101
|
+
// Created before the first await so cleanup can see this pass in the
|
|
1102
|
+
// window before the model call, where #211 still applies in full.
|
|
1103
|
+
const phase = newPhase();
|
|
887
1104
|
try {
|
|
888
1105
|
opGate = bindCapture(sid);
|
|
889
|
-
await track(
|
|
1106
|
+
await track(
|
|
1107
|
+
captureSession(sid, "", "idle", undefined, opGate, phase),
|
|
1108
|
+
phase,
|
|
1109
|
+
);
|
|
890
1110
|
} catch (err) {
|
|
891
1111
|
// Teardown is not a capture failure: after cleanup the store may
|
|
892
1112
|
// be gone, and a receipt here would be the ENOENT noise #211
|
|
@@ -916,6 +1136,10 @@ export function configureAutoCapture(
|
|
|
916
1136
|
}
|
|
917
1137
|
})();
|
|
918
1138
|
captureCleanup = async () => {
|
|
1139
|
+
// The signal stops NEW passes (the subscription checks it before
|
|
1140
|
+
// dispatch, and the compaction seam checks it before starting). Passes
|
|
1141
|
+
// already started are handled by drainInFlight in two phases: abandon
|
|
1142
|
+
// the unanswered ones, drain the answered ones (#404).
|
|
919
1143
|
controller.abort();
|
|
920
1144
|
await drainInFlight();
|
|
921
1145
|
};
|
|
@@ -936,6 +1160,7 @@ export function configureAutoCapture(
|
|
|
936
1160
|
const opGate = bindCapture(sid);
|
|
937
1161
|
// Tracked, not just fired: cleanup must be able to drain this pass
|
|
938
1162
|
// (#211), which is the only reason the seam keeps the promise.
|
|
1163
|
+
const phase = newPhase();
|
|
939
1164
|
void track(
|
|
940
1165
|
// The predicate, not just the checks inside the pass: a rejection
|
|
941
1166
|
// from the awaited model call skips every abort check that follows
|
|
@@ -950,9 +1175,11 @@ export function configureAutoCapture(
|
|
|
950
1175
|
"compaction",
|
|
951
1176
|
messages,
|
|
952
1177
|
opGate,
|
|
1178
|
+
phase,
|
|
953
1179
|
),
|
|
954
1180
|
() => !controller.signal.aborted,
|
|
955
1181
|
),
|
|
1182
|
+
phase,
|
|
956
1183
|
);
|
|
957
1184
|
};
|
|
958
1185
|
}
|
package/src/core/guidance.ts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { RESTATABLE_TAG } from "./tags.ts";
|
|
2
|
+
|
|
1
3
|
/** Capture-only provenance: grants always-ride priority in the hint channel. */
|
|
2
4
|
export const USER_GUIDED_TAG = "user-guided";
|
|
3
5
|
|
|
@@ -5,9 +7,29 @@ export const USER_GUIDED_TAG = "user-guided";
|
|
|
5
7
|
* Tool/import input cannot grant capture provenance. Split the storage
|
|
6
8
|
* delimiter first: ["ordinary,user-guided"] reads back as two tags too.
|
|
7
9
|
* Silently drop the reserved tag; ordinary prose still faces the write gate.
|
|
10
|
+
*
|
|
11
|
+
* `restatable` is dropped for the same reason it cannot be granted: it is a
|
|
12
|
+
* verdict about a SPECIFIC prose against a SPECIFIC working tree, and neither
|
|
13
|
+
* survives these paths.
|
|
14
|
+
*
|
|
15
|
+
* - `tools/update.ts` carries the target's tags onto the replacement row. A
|
|
16
|
+
* user correcting a restatable row would otherwise leave the corrected prose
|
|
17
|
+
* demoted in injection forever, on a verdict that described the superseded
|
|
18
|
+
* text — the one case where the demotion is guaranteed wrong rather than
|
|
19
|
+
* merely possible.
|
|
20
|
+
* - `portable/import.ts` moves a row between machines. The tag asserts "THIS
|
|
21
|
+
* tree states it"; an imported row keeps another machine's verdict and is
|
|
22
|
+
* demoted against a tree that was never scanned.
|
|
23
|
+
*
|
|
24
|
+
* A row that is genuinely restatable gets the tag again from the next capture
|
|
25
|
+
* pass, so dropping it costs a demotion and never a fact.
|
|
26
|
+
*
|
|
27
|
+
* The viewer's edit path deliberately does NOT go through here: #129 keeps tag
|
|
28
|
+
* provenance across a typo fix, where the verdict still describes the prose, and
|
|
29
|
+
* a human can clear the tag by hand.
|
|
8
30
|
*/
|
|
9
31
|
export function nonCaptureTags(tags?: string[]): string[] | undefined {
|
|
10
32
|
return tags
|
|
11
33
|
?.flatMap((tag) => tag.split(","))
|
|
12
|
-
.filter((tag) => tag !== USER_GUIDED_TAG);
|
|
34
|
+
.filter((tag) => tag !== USER_GUIDED_TAG && tag !== RESTATABLE_TAG);
|
|
13
35
|
}
|
package/src/core/tags.ts
CHANGED
|
@@ -1,6 +1,20 @@
|
|
|
1
1
|
/** Auto-capture provenance, shared by capture and retrieval. */
|
|
2
2
|
export const AUTO_CAPTURE_TAG = "auto-capture";
|
|
3
3
|
|
|
4
|
+
/**
|
|
5
|
+
* #402: the working tree already states this fact, so the next session can read
|
|
6
|
+
* it there. Captured from #389's availability check, which used to DROP these
|
|
7
|
+
* candidates. Measured on this repo's store, that check refused 0 of 1166 real
|
|
8
|
+
* rows after four review rounds, and the version before it refused 30 of which
|
|
9
|
+
* 29 were wrong — so the verdict is a tag now, and a wrong match costs a tag
|
|
10
|
+
* instead of a fact.
|
|
11
|
+
*
|
|
12
|
+
* Retrieval sorts these rows last within their score band: a restatement is the
|
|
13
|
+
* first thing to give up budget when the block is full, and the last thing worth
|
|
14
|
+
* a slot when it is not.
|
|
15
|
+
*/
|
|
16
|
+
export const RESTATABLE_TAG = "restatable";
|
|
17
|
+
|
|
4
18
|
/**
|
|
5
19
|
* #393: a capture candidate whose numeric claim was CHECKED against the working
|
|
6
20
|
* tree and agreed. Absent on every other row, which is what makes the injected
|
package/src/recall/relevant.ts
CHANGED
|
@@ -6,7 +6,7 @@ import { readerFromSid, visibleTo } from "../store/model/visibility.ts";
|
|
|
6
6
|
import { FRAME } from "../inject/budget.ts";
|
|
7
7
|
import { formatMemory } from "../inject/format.ts";
|
|
8
8
|
import { conflictLine, findConstant, valuesAgree } from "./conflicts.ts";
|
|
9
|
-
import { USER_GUIDED_TAG } from "../core/tags.ts";
|
|
9
|
+
import { RESTATABLE_TAG, USER_GUIDED_TAG } from "../core/tags.ts";
|
|
10
10
|
import { cmpTs } from "../core/cmp-ts.ts";
|
|
11
11
|
import { scoreMemories } from "./score.ts";
|
|
12
12
|
|
|
@@ -88,6 +88,21 @@ export function isUserGuided(m: Memory): boolean {
|
|
|
88
88
|
return m.tags?.includes(USER_GUIDED_TAG) === true;
|
|
89
89
|
}
|
|
90
90
|
|
|
91
|
+
/**
|
|
92
|
+
* #402: the working tree already states this fact. Such a row is STORED (it used
|
|
93
|
+
* to be dropped at capture, which is the defect #402 exists for), but it is the
|
|
94
|
+
* first thing a tight injection budget gives up: the next session can read it in
|
|
95
|
+
* the file, so a slot spent on it is a slot not spent on something the files do
|
|
96
|
+
* not hold.
|
|
97
|
+
*
|
|
98
|
+
* The guided lane is exempt. A user-stated row outranks an inferred one in this
|
|
99
|
+
* codebase everywhere, and capture tags guided rows too when their words are
|
|
100
|
+
* verbatim in the tree.
|
|
101
|
+
*/
|
|
102
|
+
export function isRestatable(m: Memory): boolean {
|
|
103
|
+
return m.tags?.includes(RESTATABLE_TAG) === true;
|
|
104
|
+
}
|
|
105
|
+
|
|
91
106
|
// Hint-channel caveat (#345). Measured: a WRONG user-guided row ("free
|
|
92
107
|
// shipping starts at $50 — the hidden suite encodes that") out-ranked correct
|
|
93
108
|
// code — the agent rewrote a correct threshold to match the memory. The
|
|
@@ -197,7 +212,22 @@ export async function selectRelevant(
|
|
|
197
212
|
// `shown` returns exactly what an explicit header check would.
|
|
198
213
|
let used = fitHeader.length;
|
|
199
214
|
shown = [];
|
|
200
|
-
|
|
215
|
+
// #402: PRIORITY decides who rides, and a restatement now sits last in that
|
|
216
|
+
// order — the tree already states it, so a slot spent here is a slot not
|
|
217
|
+
// spent on something the files do not hold. `merged` stays in score order:
|
|
218
|
+
// `selected` is the ledger's view of the ranking and a miss has to stay
|
|
219
|
+
// diagnosable, so the demotion is a separate WALK order, never a re-sort of
|
|
220
|
+
// the selection. The guided lane is exempt: a user-stated row outranks an
|
|
221
|
+
// inferred one in this codebase everywhere.
|
|
222
|
+
const demoted = (m: Memory | undefined): boolean =>
|
|
223
|
+
!!m && !guided.includes(m) && isRestatable(m);
|
|
224
|
+
const fitOrder = merged
|
|
225
|
+
.map((_, i) => i)
|
|
226
|
+
.sort(
|
|
227
|
+
(a, b) =>
|
|
228
|
+
(demoted(merged[a]) ? 1 : 0) - (demoted(merged[b]) ? 1 : 0) || a - b,
|
|
229
|
+
);
|
|
230
|
+
for (const i of fitOrder) {
|
|
201
231
|
const line = lines[i] ?? "";
|
|
202
232
|
if (used + 1 + line.length > budget) continue;
|
|
203
233
|
shown.push(i);
|