opencode-self-improvement 0.14.18 → 0.14.19
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 +2 -0
- package/package.json +1 -1
- package/src/capture.ts +3 -16
- package/src/gates.ts +14 -4
- package/src/host.ts +97 -0
- package/src/index.ts +65 -388
- package/src/init.ts +3 -3
- package/src/inject.ts +5 -8
- package/src/injection-epochs.ts +313 -0
- package/src/resolver.ts +2 -4
- package/src/state.ts +8 -0
- package/src/triggers.ts +41 -3
- package/src/types.ts +2 -2
package/src/inject.ts
CHANGED
|
@@ -1,12 +1,9 @@
|
|
|
1
|
-
// Context surfaces
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
// results. Evidence is never injected. Open threads (status=
|
|
6
|
-
// "open") get a single capped frontier block in the digest so planning sessions
|
|
7
|
-
// start at the previous session's frontier instead of re-deriving it.
|
|
1
|
+
// Context surfaces: a small system digest, a capped open-thread frontier, and
|
|
2
|
+
// relevance-ranked memory frozen per epoch by src/index.ts. These ride the
|
|
3
|
+
// session context hook's system parts. Contextual pull appends relevant memory
|
|
4
|
+
// to grep/glob/read results. Evidence is never injected.
|
|
8
5
|
import { createHash } from "node:crypto";
|
|
9
|
-
import { isActive, loadAll, readerFromSid, visibleTo,
|
|
6
|
+
import { isActive, loadAll, readerFromSid, visibleTo, type Memory } from "./memory.ts";
|
|
10
7
|
import { record } from "./evidence.ts";
|
|
11
8
|
import { dateStr, frontierBudget, injectBudget } from "./config.ts";
|
|
12
9
|
import { bracketList } from "./logfmt.ts";
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// Per-setup injection epochs. Host event parsing and identity binding stay in
|
|
2
|
+
// index.ts; this module owns frozen bytes, refresh decisions, and their status.
|
|
3
|
+
import { isActive, isVisibleTo, loadAll, malformedCount, readerFromSid, type Memory } from "./memory.ts";
|
|
4
|
+
import { SESSION_CAP, SessionLru } from "./sessions.ts";
|
|
5
|
+
import { record } from "./evidence.ts";
|
|
6
|
+
import {
|
|
7
|
+
capToBudget,
|
|
8
|
+
injectedRows,
|
|
9
|
+
selectRelevant,
|
|
10
|
+
storeVersion,
|
|
11
|
+
systemDigest,
|
|
12
|
+
} from "./inject.ts";
|
|
13
|
+
import { attributeSession, deriveMemoryRefs, type MemoryRefs } from "./attribution.ts";
|
|
14
|
+
import { neverRetrieved, readLedger, useSignals } from "./hits.ts";
|
|
15
|
+
import { emptyStats, writeStatus, type Measured, type SessionStats, type StatusPayload } from "./status.ts";
|
|
16
|
+
import { callsFor } from "./triggers.ts";
|
|
17
|
+
import { authoredFor } from "./state.ts";
|
|
18
|
+
|
|
19
|
+
interface InjectionEpochOptions {
|
|
20
|
+
budget: number;
|
|
21
|
+
frontierBudget: number;
|
|
22
|
+
// The host listener records usage. Eviction must still drop it with the
|
|
23
|
+
// epoch and request counters, so no measurement outlives its tracked session.
|
|
24
|
+
measuredTurns: Pick<Map<string, Measured>, "get" | "delete">;
|
|
25
|
+
noteHits: (sid: string, rows: Memory[], query: string) => Promise<void>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createInjectionEpochs({
|
|
29
|
+
budget,
|
|
30
|
+
frontierBudget: openBudget,
|
|
31
|
+
measuredTurns,
|
|
32
|
+
noteHits,
|
|
33
|
+
}: InjectionEpochOptions) {
|
|
34
|
+
// Per-session frozen injection epochs: the whole memory section (digest +
|
|
35
|
+
// frontier + relevance) plus the store fingerprint it was rendered from.
|
|
36
|
+
// Recomputed on the first prompt of a tracked session, when injectable rows
|
|
37
|
+
// change, or after a compaction (see the prompt/context/compaction hooks).
|
|
38
|
+
// The RENDERED BYTES, not the fingerprint, decide whether the epoch moved
|
|
39
|
+
// (issue #162): a write that changes nothing the model is shown must not
|
|
40
|
+
// cost the next request a full re-prefill. And a pure addition the session
|
|
41
|
+
// wrote itself does not move them either (#165) — see refreshEpoch. The
|
|
42
|
+
// shared LRU below may evict the whole session state; a later prompt starts
|
|
43
|
+
// it fresh.
|
|
44
|
+
const epoch = new Map<
|
|
45
|
+
string,
|
|
46
|
+
{
|
|
47
|
+
version: string;
|
|
48
|
+
/** Frozen standing digest + frontier + convergence parts, in push order. */
|
|
49
|
+
parts: string[];
|
|
50
|
+
/** The budgeted relevance block the surfaces report against injectBudget. */
|
|
51
|
+
block: string;
|
|
52
|
+
/** Comparison key: every byte of the memory section, joined. */
|
|
53
|
+
prefix: string;
|
|
54
|
+
/**
|
|
55
|
+
* Rows THIS session had already authored when these bytes were rendered
|
|
56
|
+
* (#165). The riding-bytes test subtracts everything authored after this
|
|
57
|
+
* snapshot; if what remains renders identically, the whole difference is
|
|
58
|
+
* the session's own additions and the bytes keep riding.
|
|
59
|
+
*/
|
|
60
|
+
ownRows: Set<string>;
|
|
61
|
+
/**
|
|
62
|
+
* The prompt these bytes were scored against. The counterfactual below
|
|
63
|
+
* has to re-score the SAME inputs, or a topic change between the freeze
|
|
64
|
+
* and the next write would look like a content change — and the epoch
|
|
65
|
+
* would pay for a refresh it deliberately refuses to do on a prompt.
|
|
66
|
+
*/
|
|
67
|
+
prompt: string;
|
|
68
|
+
at: string;
|
|
69
|
+
reason: "first" | "store_changed";
|
|
70
|
+
refs: MemoryRefs;
|
|
71
|
+
}
|
|
72
|
+
>();
|
|
73
|
+
// Latest user prompt per tracked session. A changed store is re-scored
|
|
74
|
+
// against it even when the change happened during a tool loop with no new
|
|
75
|
+
// prompt. It is evicted together with the epoch and session ledgers.
|
|
76
|
+
const latestPrompt = new Map<string, string>();
|
|
77
|
+
// Recomputes since server start: every one invalidated a prompt cache, so
|
|
78
|
+
// it is the honest cost number the surfaces show (status files / tools).
|
|
79
|
+
let epochRecomputes = 0;
|
|
80
|
+
|
|
81
|
+
// Per-session ledger, incremented at the injection decision below. Status
|
|
82
|
+
// combines it with the host listener's measured usage, either on disk (TUI)
|
|
83
|
+
// or directly through memory_status.
|
|
84
|
+
const sessionStats = new Map<string, SessionStats>();
|
|
85
|
+
// Epoch, prompt, counters, and host measurements are evicted together.
|
|
86
|
+
const sessions = new SessionLru(SESSION_CAP, (sid) => {
|
|
87
|
+
epoch.delete(sid);
|
|
88
|
+
latestPrompt.delete(sid);
|
|
89
|
+
sessionStats.delete(sid);
|
|
90
|
+
measuredTurns.delete(sid);
|
|
91
|
+
});
|
|
92
|
+
const statsFor = (sid: string): SessionStats => {
|
|
93
|
+
let st = sessionStats.get(sid);
|
|
94
|
+
if (!st) {
|
|
95
|
+
st = emptyStats();
|
|
96
|
+
sessionStats.set(sid, st);
|
|
97
|
+
}
|
|
98
|
+
return st;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// Build the full status snapshot for one session, or null before its first
|
|
102
|
+
// epoch. Store counts are computed fresh so every flush is current.
|
|
103
|
+
const buildPayload = async (sid: string): Promise<StatusPayload | null> => {
|
|
104
|
+
const ep = epoch.get(sid);
|
|
105
|
+
if (!ep) return null;
|
|
106
|
+
const all = await loadAll();
|
|
107
|
+
const act = all.filter(isActive);
|
|
108
|
+
const led = await readLedger();
|
|
109
|
+
return {
|
|
110
|
+
at: ep.at,
|
|
111
|
+
sessionID: sid,
|
|
112
|
+
reason: ep.reason,
|
|
113
|
+
recomputes: epochRecomputes,
|
|
114
|
+
block: ep.block,
|
|
115
|
+
blockChars: ep.block.length,
|
|
116
|
+
sectionChars: ep.prefix.length,
|
|
117
|
+
budget,
|
|
118
|
+
store: {
|
|
119
|
+
active: act.length,
|
|
120
|
+
superseded: all.length - act.length,
|
|
121
|
+
open: act.filter((m) => m.status === "open").length,
|
|
122
|
+
scopes: new Set(act.map((m) => m.scope)).size,
|
|
123
|
+
malformed: malformedCount(),
|
|
124
|
+
neverRetrieved: neverRetrieved(act, led).length,
|
|
125
|
+
ledgerSince: led.since,
|
|
126
|
+
},
|
|
127
|
+
stats: statsFor(sid),
|
|
128
|
+
measured: measuredTurns.get(sid) ?? null,
|
|
129
|
+
attribution: attributeSession(callsFor(sid), ep.refs),
|
|
130
|
+
};
|
|
131
|
+
};
|
|
132
|
+
const flushStatus = (sid: string): Promise<void> =>
|
|
133
|
+
buildPayload(sid).then((p) => (p ? writeStatus(p) : undefined));
|
|
134
|
+
|
|
135
|
+
// Called when a prompt arrives (to keep status surfaces current) and again
|
|
136
|
+
// at the injection decision on every model request. The latter keeps
|
|
137
|
+
// removals fail-closed: an out-of-band redaction or a block during a tool
|
|
138
|
+
// loop cannot ride one more request waiting for another user prompt.
|
|
139
|
+
// The caller's sid is resolved to an immutable Reader BEFORE the store
|
|
140
|
+
// read (#127): while loadAll awaits, another session's hooks may dispatch
|
|
141
|
+
// and move the ambient current; filtering with THAT leaks the other
|
|
142
|
+
// session's repo into this one's system prompt.
|
|
143
|
+
const injectableRows = async (sid?: string): Promise<Memory[]> => {
|
|
144
|
+
const reader = readerFromSid(sid);
|
|
145
|
+
return (await loadAll()).filter((m) => isActive(m) && isVisibleTo(m, reader));
|
|
146
|
+
};
|
|
147
|
+
// Render the COMPLETE memory section for one request: the standing digest,
|
|
148
|
+
// the open-thread frontier and the convergence line (all from systemDigest),
|
|
149
|
+
// followed by this epoch's relevance block. The parts are exactly what gets
|
|
150
|
+
// pushed onto `event.system`; their join is the byte key the epoch compares
|
|
151
|
+
// against, so "did the cache-critical prefix change?" is answered by the
|
|
152
|
+
// bytes the model would actually see and never by a proxy (issue #162).
|
|
153
|
+
const buildMemorySection = async (
|
|
154
|
+
sid: string | undefined,
|
|
155
|
+
mems: Memory[],
|
|
156
|
+
promptOverride?: string,
|
|
157
|
+
): Promise<{ parts: string[]; block: string; prefix: string; rode: Memory[]; refs: MemoryRefs }> => {
|
|
158
|
+
const parts: string[] = [];
|
|
159
|
+
await systemDigest(
|
|
160
|
+
{ sessionID: sid },
|
|
161
|
+
{ system: parts },
|
|
162
|
+
{ rows: mems, frontierBudget: openBudget },
|
|
163
|
+
);
|
|
164
|
+
const prompt = promptOverride ?? (sid === undefined ? "" : latestPrompt.get(sid) ?? "");
|
|
165
|
+
// Widen the candidate pool, then cap: the budget decides what rides.
|
|
166
|
+
const sel = await selectRelevant(prompt, 5, mems, await useSignals());
|
|
167
|
+
const block = sel.block ? capToBudget(sel.block, budget) : "";
|
|
168
|
+
// Refs the ACTUALLY-injected rows assert (paths + commands), the join key
|
|
169
|
+
// for attribution. Derived from the budget-surviving rows, not the wider
|
|
170
|
+
// candidate pool — crediting paths the model never saw would overclaim.
|
|
171
|
+
const rode = injectedRows(block, sel.selected);
|
|
172
|
+
const prefix = [...parts, block].join("\u0000");
|
|
173
|
+
return { parts, block, prefix, rode, refs: deriveMemoryRefs(rode) };
|
|
174
|
+
};
|
|
175
|
+
const refreshEpoch = async (sid: string, rows?: Memory[]): Promise<void> => {
|
|
176
|
+
if (!latestPrompt.has(sid)) return;
|
|
177
|
+
const mems = rows ?? (await injectableRows(sid));
|
|
178
|
+
const version = await storeVersion(mems);
|
|
179
|
+
const cached = epoch.get(sid);
|
|
180
|
+
// Cheap pre-check: no injectable row moved, so the frozen bytes still
|
|
181
|
+
// stand. Skips re-scoring and the use-ledger write on ordinary turns.
|
|
182
|
+
if (cached?.version === version) return;
|
|
183
|
+
const built = await buildMemorySection(sid, mems);
|
|
184
|
+
// The store moved. A write that changes nothing RENDERED — a row that is
|
|
185
|
+
// not relevant to this prompt, supersession elsewhere, a scope the reader
|
|
186
|
+
// never sees rendered identically — must not cost this session a prompt
|
|
187
|
+
// cache. Adopt the new fingerprint, keep riding the same bytes, emit
|
|
188
|
+
// nothing: an invalidation has to mean bytes actually moved.
|
|
189
|
+
if (cached && cached.prefix === built.prefix) {
|
|
190
|
+
epoch.set(sid, { ...cached, version });
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
// Riding bytes (#165): a pure addition this session wrote itself is
|
|
194
|
+
// information it already has — the model produced it, it is in the
|
|
195
|
+
// transcript. Re-render the section with every row authored SINCE these
|
|
196
|
+
// bytes were frozen taken back out: if it comes back byte-identical, the
|
|
197
|
+
// entire difference is attributable to the session's own additions and
|
|
198
|
+
// the frozen bytes keep riding. Everything else survives into that render
|
|
199
|
+
// and still busts — a riding row removed or rewritten (blocklist,
|
|
200
|
+
// hand-redaction, forget, supersession, decay), another session's row, a
|
|
201
|
+
// viewer edit, an import, a moved convergence line.
|
|
202
|
+
if (cached) {
|
|
203
|
+
const mine = authoredFor(sid);
|
|
204
|
+
const extra = mems.filter((m) => mine.has(m.ts) && !cached.ownRows.has(m.ts));
|
|
205
|
+
if (extra.length) {
|
|
206
|
+
const back = await buildMemorySection(
|
|
207
|
+
sid,
|
|
208
|
+
mems.filter((m) => !extra.some((e) => e.ts === m.ts)),
|
|
209
|
+
cached.prompt,
|
|
210
|
+
);
|
|
211
|
+
if (back.prefix === cached.prefix) {
|
|
212
|
+
epoch.set(sid, { ...cached, version });
|
|
213
|
+
return;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const prompt = latestPrompt.get(sid) ?? "";
|
|
218
|
+
// Use ledger (#42): the rows that actually rode the block, credited with
|
|
219
|
+
// the terms the prompt and those rows shared (never the prompt itself).
|
|
220
|
+
// Only once the build is ADOPTED — a discarded rebuild must not credit
|
|
221
|
+
// rows that were already offered under the frozen epoch.
|
|
222
|
+
await noteHits(sid, built.rode, prompt);
|
|
223
|
+
const at = new Date().toISOString();
|
|
224
|
+
const reason: "first" | "store_changed" = cached ? "store_changed" : "first";
|
|
225
|
+
epoch.set(sid, {
|
|
226
|
+
version,
|
|
227
|
+
parts: built.parts,
|
|
228
|
+
block: built.block,
|
|
229
|
+
prefix: built.prefix,
|
|
230
|
+
ownRows: new Set(mems.filter((m) => authoredFor(sid).has(m.ts)).map((m) => m.ts)),
|
|
231
|
+
prompt,
|
|
232
|
+
at,
|
|
233
|
+
reason,
|
|
234
|
+
refs: built.refs,
|
|
235
|
+
});
|
|
236
|
+
await record(
|
|
237
|
+
"epoch_recompute",
|
|
238
|
+
{
|
|
239
|
+
session: sid,
|
|
240
|
+
reason,
|
|
241
|
+
chars: built.block.length,
|
|
242
|
+
},
|
|
243
|
+
false,
|
|
244
|
+
);
|
|
245
|
+
epochRecomputes++;
|
|
246
|
+
// Ledger: a store_changed recompute of a live epoch is an
|
|
247
|
+
// invalidation (the first epoch of a session busts nothing). The
|
|
248
|
+
// epoch request count restarts with the new block.
|
|
249
|
+
const st = statsFor(sid);
|
|
250
|
+
st.epochRequests = 0;
|
|
251
|
+
if (reason === "store_changed") {
|
|
252
|
+
st.invalidations++;
|
|
253
|
+
st.lastInvalidation = { at, reason };
|
|
254
|
+
}
|
|
255
|
+
// Status hand-off for the terminal panel (src/tui.tsx) and any
|
|
256
|
+
// out-of-process surface. Best-effort; never breaks injection.
|
|
257
|
+
await flushStatus(sid);
|
|
258
|
+
};
|
|
259
|
+
|
|
260
|
+
// Push each part in the original order. Accounting follows delivery so a
|
|
261
|
+
// throwing host callback leaves request accounting unchanged.
|
|
262
|
+
const deliver = async (sid: string | undefined, push: (text: string) => void): Promise<void> => {
|
|
263
|
+
const mems = await injectableRows(sid);
|
|
264
|
+
if (typeof sid === "string") await refreshEpoch(sid, mems);
|
|
265
|
+
// Deliver the FROZEN memory section. Every byte pushed onto the system
|
|
266
|
+
// prompt comes from the epoch, so between busts the provider sees an
|
|
267
|
+
// identical prefix and serves the conversation from cache (issue #162).
|
|
268
|
+
// A session with no epoch yet (no prompt recorded, or evicted from the
|
|
269
|
+
// LRU) still gets the standing digest, built fresh and uncached.
|
|
270
|
+
const ep = typeof sid === "string" ? epoch.get(sid) : undefined;
|
|
271
|
+
if (ep) {
|
|
272
|
+
for (const text of ep.parts) push(text);
|
|
273
|
+
} else {
|
|
274
|
+
const parts: string[] = [];
|
|
275
|
+
await systemDigest(
|
|
276
|
+
{ sessionID: sid },
|
|
277
|
+
{ system: parts },
|
|
278
|
+
{ rows: mems, frontierBudget: openBudget },
|
|
279
|
+
);
|
|
280
|
+
for (const text of parts) push(text);
|
|
281
|
+
}
|
|
282
|
+
// This epoch's relevance-ranked memory, also on the system channel —
|
|
283
|
+
// the UI never renders system parts, unlike appended prompt text.
|
|
284
|
+
const knowledge = ep?.block;
|
|
285
|
+
if (knowledge) push(knowledge);
|
|
286
|
+
// Count AT THE INJECTION DECISION so badge/panel numbers match exactly
|
|
287
|
+
// what rode this request (a later abort still rode the bytes — known
|
|
288
|
+
// and documented). Abstained = the epoch exists but its block is empty.
|
|
289
|
+
if (typeof sid === "string") {
|
|
290
|
+
const st = statsFor(sid);
|
|
291
|
+
st.requests++;
|
|
292
|
+
st.epochRequests++;
|
|
293
|
+
if (knowledge) st.cumChars += knowledge.length;
|
|
294
|
+
else if (epoch.has(sid)) st.abstained++;
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
|
|
298
|
+
return {
|
|
299
|
+
// Setup touches the LRU at the same points as identity/usage handling.
|
|
300
|
+
touch: (sid: string): void => sessions.touch(sid),
|
|
301
|
+
async prompt(sid: string, text: string): Promise<void> {
|
|
302
|
+
latestPrompt.set(sid, text);
|
|
303
|
+
await refreshEpoch(sid);
|
|
304
|
+
},
|
|
305
|
+
deliver,
|
|
306
|
+
invalidate(sid: string): void {
|
|
307
|
+
epoch.delete(sid);
|
|
308
|
+
latestPrompt.delete(sid);
|
|
309
|
+
},
|
|
310
|
+
buildPayload,
|
|
311
|
+
flushStatus,
|
|
312
|
+
};
|
|
313
|
+
}
|
package/src/resolver.ts
CHANGED
|
@@ -229,9 +229,8 @@ export function displayCall(name: string, argsText: string): string {
|
|
|
229
229
|
return `${name}(${normalizeArgs(argsText)})`;
|
|
230
230
|
}
|
|
231
231
|
|
|
232
|
-
// Deterministic
|
|
233
|
-
//
|
|
234
|
-
// carry empty or spread args), build output (dist/lib), and VCS dirs. Prefers
|
|
232
|
+
// Deterministic GATE-1 source scan excludes dependencies, VCS dirs, and .d.ts
|
|
233
|
+
// declarations (which often carry empty or spread args). Prefers
|
|
235
234
|
// files under src/ over build output, .ts/.tsx sources over compiled .js, and
|
|
236
235
|
// case-insensitively ranks basenames matching the call's fileHint first so
|
|
237
236
|
// `MeshBuilder.CreateBox` resolves to `meshbuilder.pure.ts` instead of a
|
|
@@ -245,7 +244,6 @@ function relRank(rel: string): number {
|
|
|
245
244
|
if (rel.endsWith(".d.ts")) return Infinity;
|
|
246
245
|
let rank = 0;
|
|
247
246
|
if (seg.includes("src")) rank -= 100;
|
|
248
|
-
if (rel.endsWith(".d.ts")) rank += 1000;
|
|
249
247
|
if (seg.some((s) => ["dist", "build", "out", "lib"].includes(s))) rank += 50;
|
|
250
248
|
if (/\.(js|mjs|cjs)$/.test(rel)) rank += 10;
|
|
251
249
|
return rank;
|
package/src/state.ts
CHANGED
|
@@ -35,6 +35,14 @@ export interface SessionState {
|
|
|
35
35
|
cmd: string;
|
|
36
36
|
chain: ToolResult[];
|
|
37
37
|
} | null;
|
|
38
|
+
// Bounded provenance for write telemetry (#163), independent of the full
|
|
39
|
+
// calls ledger used by grounding, attribution, and convergence.
|
|
40
|
+
writeEvidence?: {
|
|
41
|
+
recent: string[];
|
|
42
|
+
gateCheck?: string;
|
|
43
|
+
gateRecovery?: [string, string, string];
|
|
44
|
+
toolRecovery?: [string, string];
|
|
45
|
+
};
|
|
38
46
|
// Session-convergence tracking (time-to-frontier): completed-message count,
|
|
39
47
|
// first activity time, and the first memory_recall that surfaced an open
|
|
40
48
|
// thread. Deterministic: derived only from queued messages and tool results.
|
package/src/triggers.ts
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
session,
|
|
11
11
|
setLastSeenSid,
|
|
12
12
|
lastSeenSid,
|
|
13
|
+
type SessionState,
|
|
13
14
|
type ToolResult,
|
|
14
15
|
} from "./state.ts";
|
|
15
16
|
|
|
@@ -31,6 +32,21 @@ export interface AfterOutput {
|
|
|
31
32
|
// running commands. Empirical behavior substitutes for hand-copied refs.
|
|
32
33
|
const ENGAGEMENT_TOOLS = new Set(["grep", "glob", "read", "edit", "write", "bash", "shell"]);
|
|
33
34
|
|
|
35
|
+
const RECENT_EVIDENCE_CALLS = 10;
|
|
36
|
+
// Recent engagement + latest gate check + FAIL/fix/PASS + tool FAIL/PASS.
|
|
37
|
+
export const MAX_WRITE_EVIDENCE_REFS = RECENT_EVIDENCE_CALLS + 1 + 3 + 2;
|
|
38
|
+
|
|
39
|
+
function trackCall(s: SessionState, rec: ToolResult): void {
|
|
40
|
+
s.calls.push(rec);
|
|
41
|
+
s.writeEvidence ??= { recent: [] };
|
|
42
|
+
const evidence = s.writeEvidence;
|
|
43
|
+
if (ENGAGEMENT_TOOLS.has(rec.tool)) {
|
|
44
|
+
evidence.recent.push(rec.call);
|
|
45
|
+
if (evidence.recent.length > RECENT_EVIDENCE_CALLS) evidence.recent.shift();
|
|
46
|
+
}
|
|
47
|
+
if (rec.gateCheck) evidence.gateCheck = rec.call;
|
|
48
|
+
}
|
|
49
|
+
|
|
34
50
|
// True once the session has exercised the codebase (the FAIL->PASS signals use
|
|
35
51
|
// the same whitelist, so engagement == "a tool_result was recorded for a code
|
|
36
52
|
// tool").
|
|
@@ -153,17 +169,19 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
|
|
|
153
169
|
false,
|
|
154
170
|
sid,
|
|
155
171
|
);
|
|
172
|
+
s.writeEvidence ??= { recent: [] };
|
|
173
|
+
s.writeEvidence.gateRecovery = [pend.call, fix, call];
|
|
156
174
|
s.pendingGate = null;
|
|
157
175
|
} else if (s.pendingGate) {
|
|
158
176
|
s.pendingGate.chain.push(rec);
|
|
159
177
|
}
|
|
160
|
-
s
|
|
178
|
+
trackCall(s, rec);
|
|
161
179
|
return;
|
|
162
180
|
}
|
|
163
181
|
|
|
164
182
|
// Keep the pending gate chain (grep/read/edit between FAIL and PASS).
|
|
165
183
|
if (s.pendingGate) s.pendingGate.chain.push(rec);
|
|
166
|
-
s
|
|
184
|
+
trackCall(s, rec);
|
|
167
185
|
|
|
168
186
|
// ---- Failed -> fixed retry (non-gate tools) -------------------------------
|
|
169
187
|
if (["grep", "glob", "read"].includes(tool)) {
|
|
@@ -181,6 +199,8 @@ export async function afterTool(input: AfterInput, out: AfterOutput): Promise<vo
|
|
|
181
199
|
false,
|
|
182
200
|
sid,
|
|
183
201
|
);
|
|
202
|
+
s.writeEvidence ??= { recent: [] };
|
|
203
|
+
s.writeEvidence.toolRecovery = [prev.call, call];
|
|
184
204
|
}
|
|
185
205
|
s.lastByTool.set(tool, { status, call, emitted: prev?.emitted ?? false });
|
|
186
206
|
}
|
|
@@ -201,10 +221,28 @@ export async function onCompacting(input: AfterInput): Promise<void> {
|
|
|
201
221
|
await finalizeSession(sid);
|
|
202
222
|
}
|
|
203
223
|
|
|
224
|
+
// Full IDs for callers that explicitly need the ledger. Production write
|
|
225
|
+
// contexts use writeEvidence so they do not allocate this growing list.
|
|
204
226
|
export function evidenceCalls(sid: string): string[] {
|
|
205
227
|
return session(sid).calls.map((c) => c.call);
|
|
206
228
|
}
|
|
207
229
|
|
|
230
|
+
// A detached, bounded snapshot for GateContext. Do not map the entire ledger
|
|
231
|
+
// on each write: it grows throughout the session. Pin the actual trigger
|
|
232
|
+
// witnesses when recorded rather than trying to reconstruct a FAIL->PASS
|
|
233
|
+
// pairing from a cropped tail. The full ledger remains available above.
|
|
234
|
+
export function writeEvidence(sid: string): { evidenceCalls: string[]; evidenceCallsCount: number } {
|
|
235
|
+
const s = session(sid);
|
|
236
|
+
const evidence = s.writeEvidence;
|
|
237
|
+
const refs = new Set([
|
|
238
|
+
...(evidence?.gateRecovery ?? []),
|
|
239
|
+
...(evidence?.toolRecovery ?? []),
|
|
240
|
+
...(evidence?.gateCheck !== undefined ? [evidence.gateCheck] : []),
|
|
241
|
+
...(evidence?.recent ?? []),
|
|
242
|
+
]);
|
|
243
|
+
return { evidenceCalls: [...refs], evidenceCallsCount: s.calls.length };
|
|
244
|
+
}
|
|
245
|
+
|
|
208
246
|
// The full per-session tool ledger, for memory attribution (src/attribution.ts).
|
|
209
247
|
export function callsFor(sid: string): ToolResult[] {
|
|
210
248
|
return session(sid).calls;
|
|
@@ -264,7 +302,7 @@ export async function finalizeSession(sid: string): Promise<void> {
|
|
|
264
302
|
);
|
|
265
303
|
}
|
|
266
304
|
|
|
267
|
-
// Called from
|
|
305
|
+
// Called from the session prompt hook: opening a new session closes the previous one
|
|
268
306
|
// (the host has no session-end hook, so a push handoff — new session in the
|
|
269
307
|
// same process — is the closest deterministic close).
|
|
270
308
|
export async function checkNewSession(sid: string): Promise<void> {
|
package/src/types.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Shared memory-row enums. Lives outside index.ts so the pure capture core
|
|
2
2
|
// (src/capture.ts) can reference the admissible values without importing the
|
|
3
|
-
// plugin entry.
|
|
4
|
-
//
|
|
3
|
+
// plugin entry. schema.ts uses these in tool schemas; capture.ts uses TYPES
|
|
4
|
+
// to prompt and validate.
|
|
5
5
|
export const TYPES = ["decision", "learning", "preference", "blocker", "context", "pattern"] as const;
|
|
6
6
|
export const STATUSES = ["open", "settled"] as const;
|