opencode-self-improvement 0.20.0 → 0.22.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 +3 -0
- package/package.json +1 -1
- package/src/capture/candidates.ts +13 -0
- package/src/capture/guided-rules.ts +198 -0
- package/src/capture/lag.ts +11 -1
- package/src/capture/policy.ts +254 -0
- package/src/capture/prompt.ts +15 -0
- package/src/capture/runtime.ts +331 -24
- package/src/capture/transcript.ts +42 -0
- package/src/core/hooks.ts +18 -0
- package/src/index.ts +6 -0
- package/src/inject/epochs.ts +47 -1
- package/src/inject/format.ts +8 -1
- package/src/store/blocklist.ts +1 -1
- package/src/store/files/append.ts +86 -57
- package/src/store/files/deletions.ts +1 -1
- package/src/store/files/load.ts +90 -2
- package/src/store/files/prune.ts +14 -7
- package/src/store/files/snapshots.ts +3 -3
- package/src/store/files/supersede.ts +125 -74
- package/src/store/lock.ts +17 -1
- package/src/store/model/memory.ts +25 -0
- package/src/store/model/predicates.ts +1 -1
- package/src/store/model/visibility.ts +4 -4
- package/src/store/prune.ts +2 -2
- package/src/store/quarantine/quarantine.ts +12 -3
- package/src/store/quarantine/release.ts +34 -17
- package/src/store/tombstones/rejection.ts +3 -3
- package/src/store/tombstones/tombstone.ts +9 -8
- package/src/store/undo.ts +4 -4
- package/src/tools/update.ts +19 -7
package/README.md
CHANGED
|
@@ -72,6 +72,7 @@ Zero configuration is the default. To tune, use the object form of the plugin en
|
|
|
72
72
|
| `captureModel` | — | `"provider/id"` model used for auto-capture. Required when `autoCapture` is on; missing or invalid disables capture with a startup warning. |
|
|
73
73
|
| `captureMax` | `3` | Maximum candidates proposed per capture pass. |
|
|
74
74
|
| `captureOnCompact` | `true` | When `autoCapture` is on, also mine the transcript at compaction, before the summarizer replaces it. Its 5-minute cooldown is separate from the turn-end one, so the two triggers' hit-rates stay measurable. Setting it while `autoCapture` is off does nothing and reports a startup warning. |
|
|
75
|
+
| `captureGuidedRules` | `false` | POC: deterministic guided-candidate pre-pass. The user's own lines decide which stated values or rules are guided (numbers, rates, currency, explicit rule assertions) and attach the verbatim quote; the capture model may phrase such a row but cannot clear the flag or the quote, and a guided quote the user never wrote is refused at the write boundary instead of silently stripped. Fires alongside the model pass only — no extra model calls. |
|
|
75
76
|
| `notifyBlocked` | `true` | Terminal (TUI) only: toast when a write gate blocks a write. Blocks are always in `memory_evidence` either way. |
|
|
76
77
|
|
|
77
78
|
### Environment variables
|
|
@@ -99,6 +100,8 @@ What is established, from tests and fixtures (no live store involved):
|
|
|
99
100
|
- **The path runs under simulated host traffic** — unit tests hand the plugin the recorded envelopes and assert a candidate lands through the write gate, including conservation (a near-duplicate collapses at the gate instead of writing a second row): `test/capture.test.ts`, `test/capture-compaction.test.ts`. No terminal e2e scenario covers the trigger, so the simulated envelope is the strongest evidence that exists — and fabricating the envelope is exactly what passed while this feature was dead.
|
|
100
101
|
- **Identity triggers have their own recording check.** `test/event-fidelity.test.ts` checks `IDENTITY_EVENT_TYPES` against the original 2.1.4 recording plus `test/fixtures/host-session-move.json`, a normalized one-frame extract from a separate 2.2.2 move capture. The extract must declare nonempty provenance and its retained envelopes must round-trip through the lockfile-pinned `@opencode/schema` 2.0.32 decoder. These checks reject missing metadata and malformed envelopes; they do not authenticate the capture. The identity replay uses the plugin subscription, but live plugin rebinding remains unverified. The recording version is distinct from the CI host pin (2.0.26).
|
|
101
102
|
|
|
103
|
+
- **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).
|
|
104
|
+
|
|
102
105
|
What is not established:
|
|
103
106
|
|
|
104
107
|
- That a live host emits those events in the shape the subscription reads, end to end. 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); a live trial armed on 2026-10-26 was stood down on 2026-10-29 without ever firing, so it answered nothing.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-self-improvement",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.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": {
|
|
@@ -116,12 +116,25 @@ export function parseCandidates(raw: string, max: number): CaptureCandidate[] {
|
|
|
116
116
|
: {}),
|
|
117
117
|
}
|
|
118
118
|
: {};
|
|
119
|
+
// Verbatim user utterance: shape-checked here, substring-verified by the
|
|
120
|
+
// runtime against the transcript the model saw. A failed verification
|
|
121
|
+
// drops the field, never the row.
|
|
122
|
+
const original =
|
|
123
|
+
guided && typeof o.original === "string"
|
|
124
|
+
? (() => {
|
|
125
|
+
const s = o.original.trim();
|
|
126
|
+
return s && s.length <= 300 && flattenMemoryText(s) === s
|
|
127
|
+
? s
|
|
128
|
+
: undefined;
|
|
129
|
+
})()
|
|
130
|
+
: undefined;
|
|
119
131
|
out.push({
|
|
120
132
|
...(status
|
|
121
133
|
? { type, scope, content, status }
|
|
122
134
|
: { type, scope, content }),
|
|
123
135
|
...(kw ? { kw } : {}),
|
|
124
136
|
...(guided ? { guided: true, ...conflict } : {}),
|
|
137
|
+
...(original ? { original } : {}),
|
|
125
138
|
});
|
|
126
139
|
}
|
|
127
140
|
return out;
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// guided-rules — deterministic guided-candidate pre-pass (POC, FINDINGS
|
|
2
|
+
// 2026-11-08 §4). Plugin option `captureGuidedRules`, default OFF.
|
|
3
|
+
//
|
|
4
|
+
// Mystery 2's last stochastic link is capture EMISSION: the capture model
|
|
5
|
+
// flagged the user-stated fact guided in 5 of 7 runs (attr + ARM F). The
|
|
6
|
+
// field's convergent fix is "LLM proposes, rules dispose" (arXiv 2604.27906
|
|
7
|
+
// schema-grounded memory; neuro-symbolic extraction, Nat. Comm. Med. 2025;
|
|
8
|
+
// MEDIQA-SYNUR 2026 exact-evidence grounding): decide WHAT must be guided
|
|
9
|
+
// deterministically from the user's own lines, let the model only PHRASE it,
|
|
10
|
+
// and validate the quote on the write path so a miss becomes a retriable
|
|
11
|
+
// event, not a silent omission.
|
|
12
|
+
//
|
|
13
|
+
// Contract:
|
|
14
|
+
// - findGuidedQuotes scans user text (the REQUESTS prose plus transcript
|
|
15
|
+
// user: lines) sentence by sentence; a sentence stating a value or a rule
|
|
16
|
+
// yields its VERBATIM text (whitespace-normalised, capped).
|
|
17
|
+
// - mergeGuidedCandidates lets the model phrase a pre-pass quote (matched by
|
|
18
|
+
// its own verbatim original or by numeric overlap) but never clear the
|
|
19
|
+
// guided flag or drop the quote: an unmatched quote gets a deterministic
|
|
20
|
+
// fallback row.
|
|
21
|
+
// - All functions are TOTAL like the rest of capture: junk input yields
|
|
22
|
+
// []/passthrough, never a throw.
|
|
23
|
+
import type { CaptureCandidate } from "./prompt.ts";
|
|
24
|
+
|
|
25
|
+
/** Same normalisation the runtime quote check uses. */
|
|
26
|
+
export function normWs(s: string): string {
|
|
27
|
+
return s.replace(/\s+/g, " ").trim();
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Cap mirrors the store's original field; a quote is a substring, so a
|
|
31
|
+
* truncation at a space boundary stays verbatim. */
|
|
32
|
+
export const GUIDED_QUOTE_CHARS = 300;
|
|
33
|
+
|
|
34
|
+
// Decidable stated-fact shapes (the class the bench's guidance lives in):
|
|
35
|
+
// a number/rate/currency, or an explicit rule assertion. Deliberately
|
|
36
|
+
// narrow — the guided lane is capped and budgeted, but a rule that flags
|
|
37
|
+
// ordinary prose would still be noise by construction.
|
|
38
|
+
const VALUE_RE = /\d+(?:[.,]\d+)?\s*%|\d+\.\d+|[$€£]\s*\d/;
|
|
39
|
+
const RULE_RE =
|
|
40
|
+
/\b(must be|must equal|must include|has to be|is set to|is exactly|the correct\b|is inclusive|not only\b|always|never|the rule is)\b/i;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Verbatim sentences from the user's own text that state a value or a rule.
|
|
44
|
+
* `userText` is the REQUESTS prose plus the transcript's user: lines — never
|
|
45
|
+
* assistant output, so a stored quote can only be what the user said.
|
|
46
|
+
*/
|
|
47
|
+
export function findGuidedQuotes(userText: string): string[] {
|
|
48
|
+
const out: string[] = [];
|
|
49
|
+
for (const raw of userText.split(/(?<=[.!?])\s+|\n/)) {
|
|
50
|
+
const s = normWs(raw.replace(/^\s*user:\s*/i, ""));
|
|
51
|
+
if (s.length < 12 || s.length > 2000) continue;
|
|
52
|
+
if (!VALUE_RE.test(s) && !RULE_RE.test(s)) continue;
|
|
53
|
+
// Imperatives scoping THIS job are instructions, not stated facts
|
|
54
|
+
// ("do not create tests"); the capture contract expires them with the task.
|
|
55
|
+
if (/^(do|don't|dont|never create|only touch)\b/i.test(s)) continue;
|
|
56
|
+
const quote =
|
|
57
|
+
s.length > GUIDED_QUOTE_CHARS
|
|
58
|
+
? normWs(s.slice(0, GUIDED_QUOTE_CHARS).replace(/\s\S*$/, ""))
|
|
59
|
+
: s;
|
|
60
|
+
if (quote.length >= 12 && !out.includes(quote)) out.push(quote);
|
|
61
|
+
// Bound the lane the way injection bounds it (GUIDED_INJECT_CAP): a user
|
|
62
|
+
// message that states five facts is a fixture, not a session.
|
|
63
|
+
if (out.length === 3) break;
|
|
64
|
+
}
|
|
65
|
+
return out;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const NUMBERS_RE = /\d+(?:[.,]\d+)?/g;
|
|
69
|
+
|
|
70
|
+
function numbers(s: string): Set<string> {
|
|
71
|
+
return new Set(s.match(NUMBERS_RE) ?? []);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The connective prose a guidance sentence is full of. Kept small on purpose:
|
|
75
|
+
// the point is only to stop a sentence's grammar from counting as topical
|
|
76
|
+
// overlap with everything else in the store.
|
|
77
|
+
const WORD_STOP = new Set([
|
|
78
|
+
"the",
|
|
79
|
+
"and",
|
|
80
|
+
"for",
|
|
81
|
+
"with",
|
|
82
|
+
"that",
|
|
83
|
+
"this",
|
|
84
|
+
"from",
|
|
85
|
+
"have",
|
|
86
|
+
"has",
|
|
87
|
+
"was",
|
|
88
|
+
"were",
|
|
89
|
+
"are",
|
|
90
|
+
"not",
|
|
91
|
+
"only",
|
|
92
|
+
"must",
|
|
93
|
+
"should",
|
|
94
|
+
"would",
|
|
95
|
+
"could",
|
|
96
|
+
"will",
|
|
97
|
+
"shall",
|
|
98
|
+
"then",
|
|
99
|
+
"than",
|
|
100
|
+
"per",
|
|
101
|
+
"via",
|
|
102
|
+
"its",
|
|
103
|
+
]);
|
|
104
|
+
|
|
105
|
+
/** Content words (length >= 3, letter-initial, so "5.0" never qualifies). */
|
|
106
|
+
function topicWords(s: string): Set<string> {
|
|
107
|
+
return new Set(
|
|
108
|
+
(s.toLowerCase().match(/[a-z][a-z0-9_-]{2,}/g) ?? []).filter(
|
|
109
|
+
(w) => !WORD_STOP.has(w),
|
|
110
|
+
),
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function sharesTopic(a: Set<string>, b: Set<string>): boolean {
|
|
115
|
+
for (const w of a) if (b.has(w)) return true;
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* One row per pre-pass quote. A model candidate that already carries the
|
|
121
|
+
* verbatim quote keeps its phrasing; one that states the same numbers keeps
|
|
122
|
+
* its phrasing and gains the quote + the guided flag EVEN IF the model left
|
|
123
|
+
* the flag off — clearing guidance by omission is exactly the measured miss
|
|
124
|
+
* mode. An unmatched quote becomes a deterministic fallback row, so the
|
|
125
|
+
* emission the model skipped still lands.
|
|
126
|
+
*/
|
|
127
|
+
export function mergeGuidedCandidates(
|
|
128
|
+
quotes: string[],
|
|
129
|
+
candidates: CaptureCandidate[],
|
|
130
|
+
): CaptureCandidate[] {
|
|
131
|
+
const out = [...candidates];
|
|
132
|
+
for (const quote of quotes) {
|
|
133
|
+
const nums = numbers(quote);
|
|
134
|
+
const topics = topicWords(quote);
|
|
135
|
+
// Two boundaries the first version lacked (#364 review):
|
|
136
|
+
// - ONE quote per candidate. Re-matching a candidate that already carries a
|
|
137
|
+
// quote overwrote the first fact, so three user sentences all stating
|
|
138
|
+
// 10.0 stored a single row.
|
|
139
|
+
// - a shared number plus a shared CONTENT word. A number alone matches a
|
|
140
|
+
// version label as happily as a measurement, which marked an unrelated
|
|
141
|
+
// "Release 5.0" row with a refill-threshold quote.
|
|
142
|
+
// The cost is deliberate: a model phrasing that shares no word with the
|
|
143
|
+
// user's sentence now yields an extra fallback row instead of a merge. The
|
|
144
|
+
// fact survives either way; a merge that quotes the wrong fact does not.
|
|
145
|
+
const match = out.find((c) => {
|
|
146
|
+
if (c.original !== undefined) return normWs(c.original) === quote;
|
|
147
|
+
if (normWs(c.content) === quote) return true;
|
|
148
|
+
return (
|
|
149
|
+
nums.size > 0 &&
|
|
150
|
+
[...numbers(c.content)].some((n) => nums.has(n)) &&
|
|
151
|
+
sharesTopic(topicWords(c.content), topics)
|
|
152
|
+
);
|
|
153
|
+
});
|
|
154
|
+
if (match) {
|
|
155
|
+
match.guided = true;
|
|
156
|
+
match.original = quote;
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const content = `User-stated guidance: "${quote}"`.slice(0, 600);
|
|
160
|
+
out.push({
|
|
161
|
+
type: "context",
|
|
162
|
+
scope: "user-guidance",
|
|
163
|
+
content,
|
|
164
|
+
guided: true,
|
|
165
|
+
original: quote,
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
return out;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* The write-path validator (design §4.3): a guided candidate carrying a
|
|
173
|
+
* quote the user never wrote is refused, not silently stripped — the
|
|
174
|
+
* deterministic pre-pass re-offers the fact with the true quote on the same
|
|
175
|
+
* pass, which makes the miss a retriable event. A guided candidate with NO
|
|
176
|
+
* quote is the model's own judgment and passes (unchanged behavior).
|
|
177
|
+
* Returns the survivors plus the refused quotes for evidence.
|
|
178
|
+
*/
|
|
179
|
+
export function validateGuidedQuotes(
|
|
180
|
+
candidates: CaptureCandidate[],
|
|
181
|
+
userText: string,
|
|
182
|
+
): { kept: CaptureCandidate[]; refused: string[] } {
|
|
183
|
+
const hay = normWs(userText);
|
|
184
|
+
const kept: CaptureCandidate[] = [];
|
|
185
|
+
const refused: string[] = [];
|
|
186
|
+
for (const c of candidates) {
|
|
187
|
+
if (c.guided === true && c.original !== undefined) {
|
|
188
|
+
const q = normWs(c.original);
|
|
189
|
+
if (!hay.includes(q)) {
|
|
190
|
+
refused.push(q);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
c.original = q;
|
|
194
|
+
}
|
|
195
|
+
kept.push(c);
|
|
196
|
+
}
|
|
197
|
+
return { kept, refused };
|
|
198
|
+
}
|
package/src/capture/lag.ts
CHANGED
|
@@ -9,7 +9,17 @@ export function lagSince(messages: unknown, now = Date.now()): number | null {
|
|
|
9
9
|
let newest = 0;
|
|
10
10
|
for (const raw of Array.isArray(messages) ? messages : []) {
|
|
11
11
|
const m = raw as Record<string, any>;
|
|
12
|
-
|
|
12
|
+
// The real 2.2.x session context carries time.created/time.completed
|
|
13
|
+
// (fixtures/host-session-context-2.2.5.json); time.updated was the only
|
|
14
|
+
// time.* field read, so every live capture_lag line recorded no lag at
|
|
15
|
+
// all. Read the whole family; the legacy flat names stay for old shapes.
|
|
16
|
+
const at =
|
|
17
|
+
m?.time?.updated ??
|
|
18
|
+
m?.time?.completed ??
|
|
19
|
+
m?.time?.created ??
|
|
20
|
+
m?.createdAt ??
|
|
21
|
+
m?.created ??
|
|
22
|
+
m?.timestamp;
|
|
13
23
|
const ms =
|
|
14
24
|
typeof at === "number"
|
|
15
25
|
? at
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
// Capture policy: WHEN a capture is worth paying for (#334).
|
|
2
|
+
//
|
|
3
|
+
// Today every turn end triggers a capture (throttled by a fixed cooldown), and
|
|
4
|
+
// every capture re-mines the WHOLE transcript. Two costs follow. The first is
|
|
5
|
+
// the number of passes: a two-hour session with a turn every six minutes is
|
|
6
|
+
// ~20 passes. The second is worse — each pass re-reads everything mined before,
|
|
7
|
+
// pays full generation price for it, and the gate then dedups most of the
|
|
8
|
+
// result away. You pay to produce rows you throw away.
|
|
9
|
+
//
|
|
10
|
+
// Both are fixable with facts the plugin already holds in-process at zero token
|
|
11
|
+
// cost, so neither gate needs a model call to decide.
|
|
12
|
+
import type { SessionState } from "../core/state.ts";
|
|
13
|
+
import { conversationTurns, flattenTranscript } from "./transcript.ts";
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* How many messages of a session's context a capture has already mined. The
|
|
17
|
+
* delta window is everything after this index; a session that has never been
|
|
18
|
+
* captured starts at 0 and mines the whole context, which is correct.
|
|
19
|
+
*/
|
|
20
|
+
interface Cursor {
|
|
21
|
+
/** Message count at the last completed capture. */
|
|
22
|
+
msgs: number;
|
|
23
|
+
/** Turn index at that capture; the signal window is turns after this. */
|
|
24
|
+
turn: number;
|
|
25
|
+
/**
|
|
26
|
+
* Identity of the messages that capture consumed — the flattened prefix, not
|
|
27
|
+
* its last message (#366 review, round 4). A count says how many messages were
|
|
28
|
+
* consumed; it cannot say WHICH ones, and a host that replaces the transcript
|
|
29
|
+
* and then lets it grow again hands back an array longer than the cursor that
|
|
30
|
+
* shares nothing with it.
|
|
31
|
+
*/
|
|
32
|
+
fp?: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Two 32-bit accumulators plus the length: FNV-1a and a djb2-style rolling
|
|
36
|
+
// hash. Deterministic across restarts (a cursor is only ever compared with the
|
|
37
|
+
// store of the same process family), allocation-light, and strong enough for
|
|
38
|
+
// what it is: an equality test on the text of messages already read, never a
|
|
39
|
+
// security decision. Length is in the digest so two different-length prefixes
|
|
40
|
+
// can never agree even if both accumulators did.
|
|
41
|
+
function fingerprintOf(text: string): string {
|
|
42
|
+
let fnv = 0x811c9dc5;
|
|
43
|
+
let djb = 0x811c9dc5;
|
|
44
|
+
for (let i = 0; i < text.length; i++) {
|
|
45
|
+
const c = text.charCodeAt(i);
|
|
46
|
+
fnv = Math.imul(fnv ^ c, 0x01000193);
|
|
47
|
+
djb = (Math.imul(djb, 33) + c) | 0;
|
|
48
|
+
}
|
|
49
|
+
return `${text.length}:${(fnv >>> 0).toString(36)}:${(djb >>> 0).toString(36)}`;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Identity of the FIRST `count` messages — everything the cursor claims to have
|
|
54
|
+
* consumed. Undefined when there is nothing to fingerprint: not an array, a
|
|
55
|
+
* count this array cannot supply, or messages that decode to no text at all.
|
|
56
|
+
*
|
|
57
|
+
* The WHOLE prefix, not its last message (round 4 [P2]): an ordinary assistant
|
|
58
|
+
* reply repeated at the boundary position makes a replaced transcript look
|
|
59
|
+
* unchanged, and no hash collision is required for that.
|
|
60
|
+
*
|
|
61
|
+
* Cost is one flatten of text the pass has already flattened once, in-process.
|
|
62
|
+
* What the delta exists to avoid paying is the capture MODEL call, not this.
|
|
63
|
+
*/
|
|
64
|
+
export function prefixFingerprint(
|
|
65
|
+
msgs: unknown,
|
|
66
|
+
count: number,
|
|
67
|
+
): string | undefined {
|
|
68
|
+
if (!Array.isArray(msgs) || count <= 0 || msgs.length < count)
|
|
69
|
+
return undefined;
|
|
70
|
+
const text = flattenTranscript(msgs.slice(0, count));
|
|
71
|
+
return text ? fingerprintOf(text) : undefined;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Bounded like every other session-keyed ledger, so a resident server cannot
|
|
75
|
+
// grow it. A lost cursor costs one wider capture, never a wrong row.
|
|
76
|
+
const MAX_CURSORS = 500;
|
|
77
|
+
const cursors = new Map<string, Cursor>();
|
|
78
|
+
|
|
79
|
+
export function captureCursor(sid: string): Cursor {
|
|
80
|
+
return cursors.get(sid) ?? { msgs: 0, turn: 0 };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function advanceCaptureCursor(
|
|
84
|
+
sid: string,
|
|
85
|
+
msgs: number,
|
|
86
|
+
turn: number,
|
|
87
|
+
fp?: string,
|
|
88
|
+
): void {
|
|
89
|
+
if (cursors.size >= MAX_CURSORS && !cursors.has(sid)) {
|
|
90
|
+
const oldest = cursors.keys().next().value;
|
|
91
|
+
if (oldest !== undefined) cursors.delete(oldest);
|
|
92
|
+
}
|
|
93
|
+
cursors.set(sid, { msgs, turn, fp });
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function resetCaptureCursors(): void {
|
|
97
|
+
cursors.clear();
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Is this array still the transcript the cursor was counting (#366 review)?
|
|
102
|
+
*
|
|
103
|
+
* Two shapes say it is not. SHORTER than the count: compaction replaced the
|
|
104
|
+
* transcript, so `since` names an index that no longer exists — a normal event,
|
|
105
|
+
* not a corrupted store. LONG ENOUGH BUT A DIFFERENT PREFIX: the transcript was
|
|
106
|
+
* replaced and then grew past the old count before the next capture observed the
|
|
107
|
+
* swap, which a length check reads as an ordinary append while the new user rule
|
|
108
|
+
* sits below the cursor at index 0.
|
|
109
|
+
*
|
|
110
|
+
* The prefix, message for message, is the invariant: if the first `msgs` entries
|
|
111
|
+
* are the ones the last pass mined, then mining from `msgs` is correct, whatever
|
|
112
|
+
* has been appended after it. Told apart from "nothing new was appended"
|
|
113
|
+
* (`since` equal to the length and an unchanged prefix), which stays an empty
|
|
114
|
+
* window. A cursor with no fingerprint — written before this existed, or left by
|
|
115
|
+
* a pass that mined a payload with no message array behind it — falls back to the
|
|
116
|
+
* length check, so an upgrade never restarts a window on its own.
|
|
117
|
+
*/
|
|
118
|
+
export function transcriptReplaced(
|
|
119
|
+
msgs: unknown,
|
|
120
|
+
cursor: { msgs: number; fp?: string },
|
|
121
|
+
): boolean {
|
|
122
|
+
if (!Array.isArray(msgs)) return false;
|
|
123
|
+
if (cursor.msgs === 0) return false;
|
|
124
|
+
if (msgs.length < cursor.msgs) return true;
|
|
125
|
+
if (cursor.fp === undefined) return false;
|
|
126
|
+
return prefixFingerprint(msgs, cursor.msgs) !== cursor.fp;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Slice the message array down to what has not been mined yet. Returns the
|
|
131
|
+
* input unchanged when it is not an array (a seeded compaction payload of
|
|
132
|
+
* unknown shape) or when nothing was consumed, so the caller's existing
|
|
133
|
+
* thin-check still applies.
|
|
134
|
+
*/
|
|
135
|
+
export function deltaMessages(msgs: unknown, since: number): unknown {
|
|
136
|
+
if (!Array.isArray(msgs) || since <= 0) return msgs;
|
|
137
|
+
// A context that shrank past the cursor is a REPLACED transcript (compaction),
|
|
138
|
+
// not a window that has been fully mined (#366 review). Mine what is there:
|
|
139
|
+
// an empty window here was skipped by the thin-check WITHOUT advancing the
|
|
140
|
+
// cursor, so every later turn was skipped as well until the array grew past
|
|
141
|
+
// the stale count.
|
|
142
|
+
if (since > msgs.length) return msgs;
|
|
143
|
+
return msgs.slice(since);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Did the USER state a rule or spec in the window? The signal gate reads the
|
|
148
|
+
* tool ledger, so a session that only talks — "TAX_RATE must be 0.0825", no
|
|
149
|
+
* edits, no gate commands — would skip the capture and lose the hint channel
|
|
150
|
+
* (#339) for good when the session ends. A declarative marker in a user
|
|
151
|
+
* message is the cheap stand-in for "this window can hold a durable fact".
|
|
152
|
+
*
|
|
153
|
+
* Deliberately loose in the SAFE direction: a false positive costs one
|
|
154
|
+
* capture we would have paid for anyway; a false negative loses the user's
|
|
155
|
+
* stated spec. Unknown message shapes fire.
|
|
156
|
+
*/
|
|
157
|
+
const GUIDED_MARKER =
|
|
158
|
+
/\b(must|never|always|shall|rule|spec|requirement|mandatory|forbidden)\b/i;
|
|
159
|
+
|
|
160
|
+
export function guidedStatementInWindow(
|
|
161
|
+
msgs: unknown,
|
|
162
|
+
sinceMsgs: number,
|
|
163
|
+
): boolean {
|
|
164
|
+
if (!Array.isArray(msgs)) return true;
|
|
165
|
+
const window = msgs.slice(Math.max(0, sinceMsgs));
|
|
166
|
+
if (window.length === 0) return false;
|
|
167
|
+
// The SAME decode the transcript uses (#366 review): roles come from
|
|
168
|
+
// `info.role` / `role` / `type`, text from `parts[]` / `content[]` / `text` /
|
|
169
|
+
// a string `content`. Reading one narrow shape here meant a genuine user rule
|
|
170
|
+
// in any other accepted shape got a no-signal skip before generation — the
|
|
171
|
+
// exact loss this guard exists to prevent.
|
|
172
|
+
const turns = conversationTurns(window);
|
|
173
|
+
if (turns.length === 0) {
|
|
174
|
+
// Nothing in the window decoded to a conversation turn. That is either a
|
|
175
|
+
// window of non-conversation records or a message shape this build has
|
|
176
|
+
// never seen, and the two are indistinguishable from here — so it fires.
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
return turns.some((t) => t.role === "user" && GUIDED_MARKER.test(t.text));
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export interface SignalVerdict {
|
|
183
|
+
ok: boolean;
|
|
184
|
+
/** What justified the capture, or why it did not. Logged, never injected. */
|
|
185
|
+
why: string;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const EDIT_TOOLS = new Set(["edit", "write", "patch", "multiedit"]);
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Did this session produce anything durable since the last capture?
|
|
192
|
+
*
|
|
193
|
+
* Three signals, all read off the tool ledger the plugin already keeps:
|
|
194
|
+
*
|
|
195
|
+
* - `edited` — a file was written. Most durable rows describe a
|
|
196
|
+
* change; a turn that only read has never produced one.
|
|
197
|
+
* - `gateRecovered` — a gate command (build/test/lint/typecheck) failed and
|
|
198
|
+
* a later one of the same kind passed. This is the
|
|
199
|
+
* FAIL->PASS pair `t4_learning` already records, and it
|
|
200
|
+
* is the single most lesson-shaped event available.
|
|
201
|
+
* - `newCommandPassed`— a command passed that had never passed in this
|
|
202
|
+
* session. The first `bun test ./src` is a fact worth
|
|
203
|
+
* keeping; the tenth is not.
|
|
204
|
+
*
|
|
205
|
+
* Deliberately conservative in the SAFE direction: an unknown tool name or a
|
|
206
|
+
* trimmed ledger tail can only cause a MISSED capture, and a missed capture
|
|
207
|
+
* costs nothing the next signal-bearing turn cannot recover, because the
|
|
208
|
+
* cursor does not advance on a skip.
|
|
209
|
+
*/
|
|
210
|
+
export function captureSignalSince(
|
|
211
|
+
s: SessionState,
|
|
212
|
+
sinceTurn: number,
|
|
213
|
+
): SignalVerdict {
|
|
214
|
+
// Turn tracking never ran (no session.prompt observed), so the window is
|
|
215
|
+
// meaningless rather than empty. Capture: a policy that silently stops
|
|
216
|
+
// storing is the failure mode this file exists to avoid, and this is the
|
|
217
|
+
// one case where "no evidence" does not mean "nothing happened".
|
|
218
|
+
if (s.turns === 0) return { ok: true, why: "no-turn-tracking" };
|
|
219
|
+
const inWindow = s.calls.filter((c) => (c.turn ?? 0) > sinceTurn);
|
|
220
|
+
if (inWindow.some((c) => EDIT_TOOLS.has(c.tool)))
|
|
221
|
+
return { ok: true, why: "edited" };
|
|
222
|
+
const gates = inWindow.filter((c) => c.gateCheck);
|
|
223
|
+
const failed = new Set(
|
|
224
|
+
gates.filter((c) => c.status === "FAIL").map((c) => c.cmd),
|
|
225
|
+
);
|
|
226
|
+
if (
|
|
227
|
+
failed.size &&
|
|
228
|
+
gates.some((c) => c.status === "PASS" && failed.has(c.cmd))
|
|
229
|
+
)
|
|
230
|
+
return { ok: true, why: "gateRecovered" };
|
|
231
|
+
const passedBefore = new Set(
|
|
232
|
+
s.calls
|
|
233
|
+
.filter(
|
|
234
|
+
(c) =>
|
|
235
|
+
(c.turn ?? 0) <= sinceTurn &&
|
|
236
|
+
c.status === "PASS" &&
|
|
237
|
+
(c.tool === "bash" || c.tool === "shell"),
|
|
238
|
+
)
|
|
239
|
+
.map((c) => c.cmd ?? c.arg ?? ""),
|
|
240
|
+
);
|
|
241
|
+
if (
|
|
242
|
+
inWindow.some(
|
|
243
|
+
(c) =>
|
|
244
|
+
(c.tool === "bash" || c.tool === "shell") &&
|
|
245
|
+
c.status === "PASS" &&
|
|
246
|
+
!passedBefore.has(c.cmd ?? c.arg ?? ""),
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
return { ok: true, why: "newCommandPassed" };
|
|
250
|
+
// The window is real and held tool calls, none of them durable: reads,
|
|
251
|
+
// greps, a repeated command. Skip, and leave the cursor alone so the next
|
|
252
|
+
// signal-bearing turn still mines this one too.
|
|
253
|
+
return { ok: false, why: "no-signal" };
|
|
254
|
+
}
|
package/src/capture/prompt.ts
CHANGED
|
@@ -21,6 +21,14 @@ export interface CaptureCandidate {
|
|
|
21
21
|
ref?: string;
|
|
22
22
|
claim?: string;
|
|
23
23
|
klass?: "spec" | "behavior";
|
|
24
|
+
/**
|
|
25
|
+
* Verbatim user utterance behind a guided row (bench mystery 2, candidate
|
|
26
|
+
* 4): the capture model's paraphrase of a hint made the bench's exact-text
|
|
27
|
+
* needle miss a row that actually rode. The runtime verifies this against
|
|
28
|
+
* the transcript the model saw — a quote that is not a substring is dropped,
|
|
29
|
+
* so a stored original is the user's own words.
|
|
30
|
+
*/
|
|
31
|
+
original?: string;
|
|
24
32
|
}
|
|
25
33
|
|
|
26
34
|
// Keywords are the vocabulary bridge for the strict-paraphrase wall, mined from
|
|
@@ -65,6 +73,13 @@ export function buildCapturePrompt(
|
|
|
65
73
|
'- Worked example (only when the user actually states this requirement): user says "The constant TAX_RATE in src/pricing.ts must be 0.0825." Emit:',
|
|
66
74
|
'{"type":"context","scope":"pricing","content":"The constant TAX_RATE in src/pricing.ts must be 0.0825.","kw":["TAX_RATE","sales tax"],"guided":true,"ref":"TAX_RATE","claim":"0.0825","klass":"spec"}',
|
|
67
75
|
"- A guided row states the user's value or rule and NOTHING more: never claim what hidden tests, graders or suites 'encode' — you cannot see them, and the claim makes the row impossible to check.",
|
|
76
|
+
// Mystery 2 (FINDINGS §3): the guided hint reached pass 2 on the wire in
|
|
77
|
+
// 3 of 4 t3 runs, and the miss could not be attributed — capture may have
|
|
78
|
+
// paraphrased the hint, so the bench's exact-text needle missed a row that
|
|
79
|
+
// actually rode. Storing the user's verbatim words makes the needle match
|
|
80
|
+
// deterministic; the runtime drops any quote that is not a transcript
|
|
81
|
+
// substring, so this field can only ever carry what the user actually said.
|
|
82
|
+
'- When guided, also output "original": the user\'s own words for this fact, copied VERBATIM from a user: line or the REQUESTS block — no paraphrase, no reordering, at most 300 characters. Omit original when no single user line states the fact.',
|
|
68
83
|
"- Keep: decisions made, working commands, user preferences, blockers hit, durable context, conventions.",
|
|
69
84
|
"- Skip: anything derivable from the code or git history, small talk, and details that only mattered inside this conversation.",
|
|
70
85
|
...(knownList
|