opencode-self-improvement 0.15.12 → 0.15.14
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/runtime.ts +271 -0
- package/src/core/hooks.ts +9 -0
- package/src/core/host.ts +34 -0
- package/src/events.ts +223 -0
- package/src/identity/session-context.ts +150 -0
- package/src/index.ts +24 -621
- package/src/store/model/visibility.ts +24 -7
- package/src/tools/forget.ts +6 -1
- package/src/tools/merge-review.ts +7 -1
- package/src/tools/undo.ts +7 -1
package/src/index.ts
CHANGED
|
@@ -7,39 +7,40 @@
|
|
|
7
7
|
// OpenCode V2 session/tool API. Slash commands are installed as markdown by
|
|
8
8
|
// src/command.ts. The default export `{ id, setup(ctx) }` is checked against
|
|
9
9
|
// the SDK's Plugin type using a type-only import (see the note on `plugin`).
|
|
10
|
+
import { registerHooks } from "./events.ts";
|
|
11
|
+
import { guarded } from "./core/hooks.ts";
|
|
12
|
+
import type { PluginCtx } from "./core/host.ts";
|
|
10
13
|
import type { Cleanup, Plugin } from "@opencode/plugin/promise/plugin";
|
|
11
14
|
import { basename, join } from "node:path";
|
|
12
15
|
import { frontierBudget, injectBudget } from "./core/config/budgets.ts"
|
|
13
16
|
import { memoryRoot } from "./core/config/paths.ts";
|
|
14
|
-
import { unresolvedWriteMessage } from "./store/files/append.ts"
|
|
15
17
|
import { loadAll, malformedCount } from "./store/files/load.ts"
|
|
16
18
|
import { snapshotFiles } from "./store/files/snapshots.ts"
|
|
17
19
|
import { clearSuperseded, markManySuperseded, markSuperseded } from "./store/files/supersede.ts"
|
|
18
20
|
import { resolveMemoryTarget } from "./store/files/target.ts"
|
|
19
21
|
import { type Memory } from "./store/model/memory.ts"
|
|
20
22
|
import { isActive, isInjectable } from "./store/model/predicates.ts"
|
|
21
|
-
import { evidenceVisibleTo, isVisibleTo
|
|
22
|
-
import { auditCaveat,
|
|
23
|
+
import { evidenceVisibleTo, isVisibleTo } from "./store/model/visibility.ts";
|
|
24
|
+
import { auditCaveat, sameStrList, type WriteCandidate } from "./gate/gate.ts";
|
|
23
25
|
import { withStoreLock } from "./store/lock.ts";
|
|
24
|
-
import { isQuarantined,
|
|
26
|
+
import { isQuarantined, quarantineReasons } from "./store/quarantine/quarantine.ts";
|
|
25
27
|
import { pruneMemory } from "./store/prune.ts";
|
|
26
28
|
import { findStaleOpen } from "./portable/decay.ts"
|
|
27
29
|
import { exportMemories } from "./portable/export.ts"
|
|
28
30
|
import { importMemories } from "./portable/import.ts";
|
|
29
31
|
import { listSnapshots, restoreSnapshot } from "./store/undo.ts";
|
|
30
|
-
import {
|
|
31
|
-
import { captureEvidenceContext, evidenceFileFor, record, recordCaptureLag } from "./evidence/record.ts";
|
|
32
|
+
import { evidenceFileFor, record } from "./evidence/record.ts";
|
|
32
33
|
import { proposeConsolidations } from "./consolidate/propose.ts"
|
|
33
34
|
import { renderProposals } from "./consolidate/render.ts";
|
|
34
35
|
import { readReads } from "./hits/ledger.ts";
|
|
35
|
-
import { compactionAnchor } from "./inject/anchor.ts"
|
|
36
36
|
import { formatMemory } from "./inject/format.ts"
|
|
37
|
-
import { contextualPull } from "./inject/pull.ts"
|
|
38
|
-
import { pullQuery } from "./recall/relevant.ts"
|
|
39
37
|
import { sharedTerms } from "./recall/shared-terms.ts";
|
|
38
|
+
import { configureAutoCapture, CAPTURE_EVENT_TYPES } from "./capture/runtime.ts";
|
|
39
|
+
export { resetCaptureCooldowns, TURN_END_EVENTS, CAPTURE_EVENT_TYPES, captureTriggerFor } from "./capture/runtime.ts";
|
|
40
40
|
import { createInjectionEpochs } from "./inject/epochs.ts";
|
|
41
|
+
import { createSessionContext } from "./identity/session-context.ts";
|
|
41
42
|
import { registerMemoryTools } from "./tools/registry.ts";
|
|
42
|
-
import { readLedger, neverRetrieved, recordHits,
|
|
43
|
+
import { readLedger, neverRetrieved, recordHits, type HitSource } from "./hits/ledger.ts";
|
|
43
44
|
import { formatInit } from "./init/format.ts"
|
|
44
45
|
import { runInit } from "./init/run.ts";
|
|
45
46
|
import { ensureInitCommand, ensureMemoryReportCommand } from "./command/ensure.ts";
|
|
@@ -48,35 +49,16 @@ import { type Measured, type StoreCounts } from "./status/payload.ts"
|
|
|
48
49
|
import { renderMemoryReport } from "./status/report.ts"
|
|
49
50
|
import { blockedRecent } from "./status/write.ts";
|
|
50
51
|
import {
|
|
51
|
-
afterTool,
|
|
52
|
-
checkNewSession,
|
|
53
|
-
writeEvidence,
|
|
54
52
|
firstFrontierTap,
|
|
55
|
-
hasEngagement,
|
|
56
|
-
hasGateCheck,
|
|
57
53
|
markFrontierTap,
|
|
58
|
-
markTurn,
|
|
59
|
-
onCompacting,
|
|
60
54
|
} from "./capture/triggers.ts";
|
|
61
|
-
import {
|
|
62
|
-
import { resolveRepo, setRepoScope, rememberSessionDir,
|
|
55
|
+
import { setCurrent } from "./core/state.ts";
|
|
56
|
+
import { resolveRepo, setRepoScope, rememberSessionDir, bindSessionProvisional, writeTarget } from "./identity/repokey.ts";
|
|
63
57
|
import { parseLine } from "./core/logfmt/format.ts"
|
|
64
58
|
import { readLines } from "./core/logfmt/read.ts";
|
|
65
|
-
import {
|
|
66
|
-
import { lagSince } from "./capture/lag.ts"
|
|
67
|
-
import { buildCapturePrompt } from "./capture/prompt.ts"
|
|
68
|
-
import { flattenTranscript } from "./capture/transcript.ts";
|
|
69
|
-
import { redactSecrets } from "./store/secrets.ts";
|
|
59
|
+
import { parseModelRef } from "./capture/candidates.ts"
|
|
70
60
|
import { flattenMemoryText } from "./store/sanitize.ts";
|
|
71
61
|
import { bunFloorWarning } from "./core/runtime.ts";
|
|
72
|
-
import {
|
|
73
|
-
captureSessionID,
|
|
74
|
-
sessionDirectoryFromMessages,
|
|
75
|
-
sessionDirectoryFromRow,
|
|
76
|
-
sessionIdentityEvent,
|
|
77
|
-
sessionUsageEvent,
|
|
78
|
-
toolIdentity,
|
|
79
|
-
} from "./identity/host-events.ts";
|
|
80
62
|
|
|
81
63
|
// Tool/input boundaries are zod schemas (src/schema.ts): the JSON Schema the
|
|
82
64
|
// host sees is GENERATED from them, and raw args are re-parsed at execution.
|
|
@@ -97,133 +79,12 @@ import {
|
|
|
97
79
|
validated,
|
|
98
80
|
} from "./tools/schema.ts";
|
|
99
81
|
|
|
100
|
-
// --- OpenCode V2 runtime shapes (loose: we only read a few fields) ----------
|
|
101
|
-
interface ToolDef {
|
|
102
|
-
name: string;
|
|
103
|
-
description: string;
|
|
104
|
-
input: Record<string, unknown>;
|
|
105
|
-
options?: { codemode?: boolean; namespace?: string };
|
|
106
|
-
execute: (args: any, context: any) => Promise<{ content: string }>;
|
|
107
|
-
}
|
|
108
|
-
interface ToolEditorLike {
|
|
109
|
-
add: (tool: ToolDef) => void;
|
|
110
|
-
}
|
|
111
|
-
interface HookReg {
|
|
112
|
-
dispose?: () => Promise<void> | void;
|
|
113
|
-
}
|
|
114
|
-
interface PluginCtx {
|
|
115
|
-
location?: { directory?: string };
|
|
116
|
-
options?: Record<string, unknown>;
|
|
117
|
-
tool?: {
|
|
118
|
-
transform: (cb: (editor: ToolEditorLike) => void) => Promise<unknown>;
|
|
119
|
-
hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
|
|
120
|
-
};
|
|
121
|
-
session?: {
|
|
122
|
-
hook: (name: string, cb: (event: any) => Promise<void> | void) => Promise<HookReg | void>;
|
|
123
|
-
context?: (input: { sessionID: string }) => Promise<unknown>;
|
|
124
|
-
get?: (input: { sessionID: string }) => Promise<unknown>;
|
|
125
|
-
};
|
|
126
|
-
event?: {
|
|
127
|
-
subscribe: (o?: { signal?: AbortSignal }) => AsyncIterable<unknown>;
|
|
128
|
-
};
|
|
129
|
-
generate?: {
|
|
130
|
-
text: (input: unknown) => Promise<{ text?: string } | string>;
|
|
131
|
-
};
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
// Best-effort extraction of a tool's textual output + metadata from the V2
|
|
135
|
-
// execute.after `result` payload, whose exact encoding varies by tool.
|
|
136
|
-
function resultText(result: unknown): string {
|
|
137
|
-
if (typeof result === "string") return result;
|
|
138
|
-
if (!result || typeof result !== "object") return "";
|
|
139
|
-
const r = result as Record<string, unknown>;
|
|
140
|
-
for (const k of ["output", "text", "content", "stdout"]) {
|
|
141
|
-
const v = r[k];
|
|
142
|
-
if (typeof v === "string") return v;
|
|
143
|
-
}
|
|
144
|
-
if (Array.isArray(r.content)) {
|
|
145
|
-
return (r.content as Array<Record<string, unknown>>)
|
|
146
|
-
.map((c) => (typeof c?.text === "string" ? c.text : ""))
|
|
147
|
-
.filter(Boolean)
|
|
148
|
-
.join("\n");
|
|
149
|
-
}
|
|
150
|
-
return "";
|
|
151
|
-
}
|
|
152
|
-
function resultMeta(result: unknown): Record<string, unknown> {
|
|
153
|
-
if (result && typeof result === "object") {
|
|
154
|
-
const m = (result as Record<string, unknown>).metadata;
|
|
155
|
-
if (m && typeof m === "object") return m as Record<string, unknown>;
|
|
156
|
-
}
|
|
157
|
-
return {};
|
|
158
|
-
}
|
|
159
|
-
|
|
160
82
|
const PLUGIN_ID = "opencode-self-improvement";
|
|
161
83
|
|
|
162
|
-
// Tag on store rows captured by the COMPACTION trigger (issue #41). Rows keep
|
|
163
|
-
// the shared "auto-capture" provenance tag (src/inject.ts renders it) and add
|
|
164
|
-
// this one so decay/status can tell which trigger wrote them — the same
|
|
165
|
-
// distinction the auto_capture_compaction_* evidence lines carry.
|
|
166
|
-
const CAPTURE_COMPACT_TAG = "auto_capture_compaction";
|
|
167
|
-
|
|
168
84
|
// The setup-time Bun-floor warning fires once per process (setup can run for
|
|
169
85
|
// more than one location).
|
|
170
86
|
let bunFloorChecked = false;
|
|
171
87
|
|
|
172
|
-
// Auto-capture cooldown, shared by EVERY setup() registration (#108): setup
|
|
173
|
-
// runs for more than one location, and per-closure cooldown maps made those
|
|
174
|
-
// registrations strangers - one compaction could pay for two model calls on
|
|
175
|
-
// one transcript. Same module-level shape as `turns` in src/lock.ts; the key
|
|
176
|
-
// names the trigger, so measuring one trigger is still not confounded by the
|
|
177
|
-
// other having fired moments ago.
|
|
178
|
-
const lastCaptureRun = new Map<string, number>();
|
|
179
|
-
|
|
180
|
-
const CAPTURE_COOLDOWN_MS = 5 * 60_000;
|
|
181
|
-
|
|
182
|
-
/** True if this trigger may fire for this session now; records the fire. */
|
|
183
|
-
function captureCooldownPasses(trigger: "idle" | "compaction", sid: string, now: number): boolean {
|
|
184
|
-
const key = `${trigger}:${sid}`;
|
|
185
|
-
if (now - (lastCaptureRun.get(key) ?? 0) < CAPTURE_COOLDOWN_MS) return false;
|
|
186
|
-
// Sessions churn and a long-lived server must not grow one entry per
|
|
187
|
-
// session forever; oldest-inserted go first (the ledger throttle's rule).
|
|
188
|
-
if (lastCaptureRun.size > 2000) {
|
|
189
|
-
for (const k of [...lastCaptureRun.keys()].slice(0, 1000)) lastCaptureRun.delete(k);
|
|
190
|
-
}
|
|
191
|
-
lastCaptureRun.set(key, now);
|
|
192
|
-
return true;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
/** Clear the cooldown windows (tests; also what a process restart does). */
|
|
196
|
-
export function resetCaptureCooldowns(): void {
|
|
197
|
-
lastCaptureRun.clear();
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
// ---- capture trigger vocabulary (#136) -------------------------------------
|
|
201
|
-
// Single source of truth for capture subscriptions. Both turn-end events were
|
|
202
|
-
// observed on the desktop service (test/fixtures/host-events.jsonl).
|
|
203
|
-
// test/event-fidelity.test.ts requires every trigger to appear in both that
|
|
204
|
-
// recording and the installed @opencode/schema manifest: a declared event
|
|
205
|
-
// alone is insufficient evidence that the host emits it (#78, #136).
|
|
206
|
-
// Identity triggers have a separate observed check in that test, combining
|
|
207
|
-
// this recording with the 2.2.2 move extract in host-session-move.json (#176).
|
|
208
|
-
export const TURN_END_EVENTS = ["session.execution.succeeded", "session.execution.interrupted"] as const;
|
|
209
|
-
|
|
210
|
-
/** Every event type the capture subscription reacts to (fidelity-tested). */
|
|
211
|
-
export const CAPTURE_EVENT_TYPES: readonly string[] = [...TURN_END_EVENTS];
|
|
212
|
-
|
|
213
|
-
// `session.idle`, `session.status`, and `session.execution.failed` are declared
|
|
214
|
-
// but absent from that recording, so they deliberately do not trigger capture.
|
|
215
|
-
// Adding a trigger requires a recording; status would also need idle filtering.
|
|
216
|
-
|
|
217
|
-
/**
|
|
218
|
-
* True when a host event means "this session just went quiet". The internal
|
|
219
|
-
* trigger name stays "idle" (cooldown keys, `auto_capture_*` evidence lines and
|
|
220
|
-
* the historical idle-vs-compaction bench all use it).
|
|
221
|
-
*/
|
|
222
|
-
export function captureTriggerFor(event: unknown): boolean {
|
|
223
|
-
const type = (event as { type?: unknown } | null)?.type;
|
|
224
|
-
return typeof type === "string" && (TURN_END_EVENTS as readonly string[]).includes(type);
|
|
225
|
-
}
|
|
226
|
-
|
|
227
88
|
// The real setup implementation, written against the loose local PluginCtx
|
|
228
89
|
// (the only members of the V2 context this plugin actually touches).
|
|
229
90
|
const impl = {
|
|
@@ -262,140 +123,8 @@ const impl = {
|
|
|
262
123
|
await ensureInitCommand();
|
|
263
124
|
await ensureMemoryReportCommand();
|
|
264
125
|
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
async function guarded(name: string, fn: () => Promise<void>): Promise<void> {
|
|
268
|
-
try {
|
|
269
|
-
await fn();
|
|
270
|
-
} catch (err) {
|
|
271
|
-
console.warn(`[opencode-self-improvement] ${name} hook failed (ignored):`, err);
|
|
272
|
-
}
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
const gateContext = (sid?: string): GateContext => {
|
|
276
|
-
// Every session-scoped member resolves for the CALLER's session when it
|
|
277
|
-
// knows one (#116): capture awaits a model call between setCurrent and
|
|
278
|
-
// persistence, and on a multi-session server the global current moves
|
|
279
|
-
// during that await. Falling back to getCurrent() is exactly today's
|
|
280
|
-
// behavior for callers whose current IS their session (tool hooks).
|
|
281
|
-
const bound = sid ?? getCurrent().sid;
|
|
282
|
-
return {
|
|
283
|
-
sessionID: sid,
|
|
284
|
-
reader: readerFromSid(sid),
|
|
285
|
-
writeAt: writeTarget(bound),
|
|
286
|
-
evidenceContext: captureEvidenceContext(sid),
|
|
287
|
-
// NOTE (re-review): this one lookup is intentionally NON-firm — a
|
|
288
|
-
// provisional binding may supply the gate's verification TREE. The
|
|
289
|
-
// tree is where a referenced file is checked to exist, not who the
|
|
290
|
-
// caller is: "as far as the flow can know" is the right confidence
|
|
291
|
-
// level, and a wrong guess fails a code-reference gate loudly rather
|
|
292
|
-
// than leaking across repositories. Identity itself never resolves
|
|
293
|
-
// through here (readers and stamps use the firm-or-provisional split
|
|
294
|
-
// in repokey/memory); do not mistake this for one.
|
|
295
|
-
liveRoot: sessionDir(bound) ?? liveRoot,
|
|
296
|
-
...writeEvidence(bound),
|
|
297
|
-
hasGateCheck: hasGateCheck(bound),
|
|
298
|
-
hasEngagement: hasEngagement(bound),
|
|
299
|
-
};
|
|
300
|
-
};
|
|
301
|
-
|
|
302
|
-
// A durable write needs an OWNER (#152). Reads already fail closed for a
|
|
303
|
-
// session whose repository never resolved — it sees global rows and nothing
|
|
304
|
-
// else — so such a session may not write either: the alternatives were the
|
|
305
|
-
// last setup's repository or an unstamped (hence global) row. This answers
|
|
306
|
-
// at the entry, where the model can be told what to do, and records the
|
|
307
|
-
// refusal so "why is nothing stored" is answerable from memory_evidence.
|
|
308
|
-
// appendMemory throws the same rule at the choke point; the two share one
|
|
309
|
-
// message so they cannot drift.
|
|
310
|
-
const ownerlessWriter = (sid: string | undefined): string | null => {
|
|
311
|
-
const target = writeTarget(sid);
|
|
312
|
-
return target.ok ? null : target.sid;
|
|
313
|
-
};
|
|
314
|
-
|
|
315
|
-
const refuseOwnerlessWrite = async (sid: string, op: string): Promise<{ content: string }> => {
|
|
316
|
-
await record("write_refused", { op }, true, sid);
|
|
317
|
-
return { content: unresolvedWriteMessage(sid) };
|
|
318
|
-
};
|
|
319
|
-
|
|
320
|
-
// Identity of a tool call, captured SYNCHRONOUSLY at the tool's entry —
|
|
321
|
-
// the first await of the call comes after this. The V2 host hands every
|
|
322
|
-
// execute a per-call ToolContext carrying sessionID; the harness and any
|
|
323
|
-
// host that omits it fall back to the ambient current, which is correct
|
|
324
|
-
// exactly because execute.before ran immediately before this tool with
|
|
325
|
-
// no await between (#116's documented fallback). Never re-read the global
|
|
326
|
-
// after an await to learn who is calling (#127).
|
|
327
|
-
const toolIds = (context?: unknown): { sid: string; call: string } => {
|
|
328
|
-
const { sessionID: fromCtx, callID: call } = toolIdentity(context);
|
|
329
|
-
// Entry binding: a session this instance has never seen is resolved to
|
|
330
|
-
// THIS workspace (provisional — a firm event/API identity still
|
|
331
|
-
// replaces it), so the tool's reader partitions by the repository the
|
|
332
|
-
// call reached, not by the last setup's module scope (#127).
|
|
333
|
-
if (fromCtx && fromCtx !== "?") {
|
|
334
|
-
bindSessionProvisional(fromCtx, instanceDir);
|
|
335
|
-
}
|
|
336
|
-
return {
|
|
337
|
-
sid: fromCtx ?? getCurrent().sid,
|
|
338
|
-
call: call ?? getCurrent().call,
|
|
339
|
-
};
|
|
340
|
-
};
|
|
341
|
-
|
|
342
|
-
// Identity-event race backstop: a resumed session's FIRST turn can write
|
|
343
|
-
// before the subscription has delivered its execution.started, and the
|
|
344
|
-
// module-scope fallback is the last setup instance — possibly another
|
|
345
|
-
// workspace. Bind once from the session context API for unmapped sids —
|
|
346
|
-
// but note host 2.1.4 sends message payloads WITHOUT any location field,
|
|
347
|
-
// so this path is a legacy-shape best-effort; the session-row fallback
|
|
348
|
-
// below is what actually resolves serve-host sessions.
|
|
349
|
-
// One-shot: never overwrites an event-bound entry.
|
|
350
|
-
const bindingSids = new Set<string>();
|
|
351
|
-
async function bindSessionFromMessages(sid: string | undefined): Promise<void> {
|
|
352
|
-
if (!sid || sid === "?" || sessionDirFirm(sid) || bindingSids.has(sid)) return;
|
|
353
|
-
bindingSids.add(sid);
|
|
354
|
-
try {
|
|
355
|
-
const msgs = await ctx.session?.context?.({ sessionID: sid });
|
|
356
|
-
const dir = sessionDirectoryFromMessages(msgs);
|
|
357
|
-
if (dir !== undefined) rememberSessionDir(sid, dir);
|
|
358
|
-
} catch {
|
|
359
|
-
// no context access or host error: the event stream still binds later
|
|
360
|
-
} finally {
|
|
361
|
-
bindingSids.delete(sid);
|
|
362
|
-
}
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
// Serve-host reality (recorded on 2.1.4 `serve --service`): the plugin
|
|
366
|
-
// instance loads AFTER the session was created, so `session.created` — the
|
|
367
|
-
// only event carrying a location — is never delivered; `execution.started`
|
|
368
|
-
// arrives with just {sessionID}. The session ROW is the remaining source
|
|
369
|
-
// of truth: the host's session get returns `location.directory`. One
|
|
370
|
-
// lookup per session; a miss is remembered so a host without the API is
|
|
371
|
-
// not re-asked on every turn (bounded LRU, same cap as the scope cache).
|
|
372
|
-
const apiBindTried = new Set<string>();
|
|
373
|
-
const apiBindOrder = new SessionLru(SESSION_CAP, (evicted) => apiBindTried.delete(evicted));
|
|
374
|
-
async function bindSessionFromApi(sid: string | undefined): Promise<void> {
|
|
375
|
-
if (!sid || sid === "?" || sessionDirFirm(sid) || apiBindTried.has(sid)) return;
|
|
376
|
-
apiBindTried.add(sid);
|
|
377
|
-
apiBindOrder.touch(sid);
|
|
378
|
-
try {
|
|
379
|
-
const got = await ctx.session?.get?.({ sessionID: sid });
|
|
380
|
-
const dir = sessionDirectoryFromRow(got);
|
|
381
|
-
if (dir !== undefined) rememberSessionDir(sid, dir);
|
|
382
|
-
} catch {
|
|
383
|
-
// no session.get on this host (or unknown session): stay unbound
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
// Identity must resolve BEFORE a row is stamped or a read is partitioned:
|
|
388
|
-
// try the (legacy) message payloads, then the session row. A session the
|
|
389
|
-
// host cannot describe (fresh, or a host without the lookup) is bound to
|
|
390
|
-
// THIS instance's workspace — the caller's repository as the flow knows
|
|
391
|
-
// it, and strictly better than an unbound read inheriting the module
|
|
392
|
-
// scope of whoever loaded last (#127's multi-setup residue).
|
|
393
|
-
async function bindSessionIdentity(sid: string | undefined): Promise<void> {
|
|
394
|
-
if (!sid || sid === "?" || sessionDirFirm(sid)) return;
|
|
395
|
-
await bindSessionFromMessages(sid);
|
|
396
|
-
if (!sessionDirFirm(sid)) await bindSessionFromApi(sid);
|
|
397
|
-
bindSessionProvisional(sid, instanceDir);
|
|
398
|
-
}
|
|
126
|
+
const { gateContext, ownerlessWriter, refuseOwnerlessWrite, toolIds, bindSessionFromApi, bindSessionIdentity } =
|
|
127
|
+
createSessionContext(ctx, { instanceDir, liveRoot });
|
|
399
128
|
|
|
400
129
|
// ---- tools --------------------------------------------------------------
|
|
401
130
|
// Use ledger (#42). `query` is what retrieval was asked with; what gets
|
|
@@ -438,165 +167,11 @@ const impl = {
|
|
|
438
167
|
// means "off". Declared here because the hook registers before capture.
|
|
439
168
|
let onCompactCapture: ((sid: string, messages: unknown) => void) | undefined;
|
|
440
169
|
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
callID: event?.callID ?? event?.id,
|
|
447
|
-
tool: event?.tool,
|
|
448
|
-
});
|
|
449
|
-
}),
|
|
450
|
-
);
|
|
451
|
-
|
|
452
|
-
await ctx.tool?.hook("execute.after", (event: any) =>
|
|
453
|
-
guarded("tool.execute.after", async () => {
|
|
454
|
-
const input = {
|
|
455
|
-
tool: event?.tool,
|
|
456
|
-
sessionID: event?.sessionID,
|
|
457
|
-
callID: event?.callID ?? event?.id,
|
|
458
|
-
args: event?.input,
|
|
459
|
-
};
|
|
460
|
-
setCurrent(input);
|
|
461
|
-
// Evidence lines written below stamp the RECORDING repository. Bind
|
|
462
|
-
// an unbound caller to this instance first (SYNC provisional; the
|
|
463
|
-
// prompt hook / events bind firmly in production) so a tool_result
|
|
464
|
-
// can never carry another instance's stamp (#127).
|
|
465
|
-
if (typeof event?.sessionID === "string") {
|
|
466
|
-
bindSessionProvisional(event.sessionID, instanceDir);
|
|
467
|
-
}
|
|
468
|
-
const out = { output: resultText(event?.result), metadata: resultMeta(event?.result) };
|
|
469
|
-
await afterTool(input, out);
|
|
470
|
-
const pulled = await contextualPull(input, out as { output?: unknown }, budget, await useSignals());
|
|
471
|
-
if (pulled.length) await noteHits("pull", String(event?.sessionID ?? ""), pulled, pullQuery(input.args));
|
|
472
|
-
// Write a contextual-pull append back when the tool result is text we own.
|
|
473
|
-
if (event?.result && typeof event.result === "object" && typeof event.result.content === "string") {
|
|
474
|
-
const text = resultText(event.result);
|
|
475
|
-
if (out.output && out.output !== text) event.result.content = out.output;
|
|
476
|
-
}
|
|
477
|
-
}),
|
|
478
|
-
);
|
|
479
|
-
|
|
480
|
-
// Tiny system digest + open-thread frontier block, injected into the system prompt.
|
|
481
|
-
await ctx.session?.hook("context", (event: any) =>
|
|
482
|
-
guarded("session.context (systemDigest)", async () => {
|
|
483
|
-
// Route store reads in this hook through the right session's scope:
|
|
484
|
-
// the sid is captured from the event BEFORE any await and carried
|
|
485
|
-
// explicitly — the global current set here is legacy bookkeeping
|
|
486
|
-
// only, never the identity this flow filters with (#127).
|
|
487
|
-
const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
|
|
488
|
-
setCurrent({ sessionID: event?.sessionID });
|
|
489
|
-
if (typeof sid === "string") sessions.touch(sid);
|
|
490
|
-
// Resolve WHOSE repository this injection reads before the store
|
|
491
|
-
// read below: an unbound session would otherwise fall to global-only
|
|
492
|
-
// and silently lose its own frontier rows. SYNC provisional bind to
|
|
493
|
-
// this instance's workspace — the prompt hook (or an event) has
|
|
494
|
-
// already bound firmly in production, so no host lookup belongs in
|
|
495
|
-
// this hot path (#127).
|
|
496
|
-
if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
|
|
497
|
-
await sessions.deliver(sid, (text) => event?.system?.push?.({ type: "text", text }));
|
|
498
|
-
}),
|
|
499
|
-
);
|
|
500
|
-
|
|
501
|
-
// Memory-first injection, frozen per epoch (cache-safe). Remember the
|
|
502
|
-
// latest user prompt here; the request-time context hook builds or
|
|
503
|
-
// invalidates the epoch immediately before delivery. Relevance staleness
|
|
504
|
-
// is accepted while the injectable rows stay unchanged, preserving a
|
|
505
|
-
// stable system prefix across ordinary turns.
|
|
506
|
-
// Never mutate event.prompt.text — it is stored verbatim and rendered in
|
|
507
|
-
// the UI.
|
|
508
|
-
await ctx.session?.hook("prompt", (event: any) =>
|
|
509
|
-
guarded("session.prompt (inject)", async () => {
|
|
510
|
-
setCurrent({ sessionID: event?.sessionID });
|
|
511
|
-
const sid = event?.sessionID;
|
|
512
|
-
if (typeof sid === "string") {
|
|
513
|
-
sessions.touch(sid);
|
|
514
|
-
markTurn(sid);
|
|
515
|
-
await checkNewSession(sid);
|
|
516
|
-
await bindSessionIdentity(sid);
|
|
517
|
-
await sessions.prompt(sid, event?.prompt?.text ?? "");
|
|
518
|
-
}
|
|
519
|
-
}),
|
|
520
|
-
);
|
|
521
|
-
|
|
522
|
-
// Session-convergence rollup at compaction. The epoch is dropped so the
|
|
523
|
-
// next prompt re-scores against the post-compaction store. Memory-aware
|
|
524
|
-
// compaction: the durable-memory anchor is pushed onto the hook's system
|
|
525
|
-
// parts (visible to the summarizer model, which runs AFTER hooks) so the
|
|
526
|
-
// summary preserves the facts. Never sets event.result — that would skip
|
|
527
|
-
// the summarizer call entirely. Also fires the context-death auto-capture
|
|
528
|
-
// (issue #41, opt-in; see the capture section): the transcript is mined
|
|
529
|
-
// while it still exists, BEFORE the summarizer replaces it.
|
|
530
|
-
await ctx.session?.hook("compaction", (event: any) =>
|
|
531
|
-
guarded("session.compaction (onCompacting)", async () => {
|
|
532
|
-
const sid = typeof event?.sessionID === "string" ? event.sessionID : undefined;
|
|
533
|
-
setCurrent({ sessionID: event?.sessionID });
|
|
534
|
-
// The anchor read and the capture pass below partition by the session's
|
|
535
|
-
// repository; SYNC provisional bind only — a host lookup from this
|
|
536
|
-
// hook would violate the zero-token promise (#127, see capture).
|
|
537
|
-
if (typeof sid === "string") bindSessionProvisional(sid, instanceDir);
|
|
538
|
-
await onCompacting({ sessionID: event?.sessionID });
|
|
539
|
-
if (typeof event?.sessionID === "string") {
|
|
540
|
-
sessions.invalidate(event.sessionID);
|
|
541
|
-
}
|
|
542
|
-
const anchor = await compactionAnchor(12, sid);
|
|
543
|
-
if (anchor) event?.system?.push?.({ type: "text", text: anchor });
|
|
544
|
-
// Fire-and-forget: a capture model call must never delay the compaction
|
|
545
|
-
// the user is waiting for, and failures stay inside the guarded path.
|
|
546
|
-
// The payload's own messages ride along so the mining sees the
|
|
547
|
-
// pre-compaction transcript even if the store moves under it.
|
|
548
|
-
if (onCompactCapture && sid) {
|
|
549
|
-
onCompactCapture(sid, event.messages);
|
|
550
|
-
}
|
|
551
|
-
}),
|
|
552
|
-
);
|
|
553
|
-
|
|
554
|
-
// ---- measured prompt-cache health (usage events) -----------------------
|
|
555
|
-
// Zero-model by design: usage arrives on `session.usage.updated` (v2 hosts)
|
|
556
|
-
// or `message.updated` assistant info (older hosts), carrying tokens
|
|
557
|
-
// {input, output, reasoning, cache.read/write}; the session-wide
|
|
558
|
-
// read/(read+input+write) share is the honest receipt behind the
|
|
559
|
-
// byte-stability proxy. Streaming updates arrive repeatedly — overwriting
|
|
560
|
-
// with the latest is correct because the final update carries the complete
|
|
561
|
-
// usage. Flushes the per-session status file so the TUI badge refreshes
|
|
562
|
-
// once per turn instead of per step. Degrades to "not measured" when the
|
|
563
|
-
// host exposes no event stream.
|
|
564
|
-
const measuredController = new AbortController();
|
|
565
|
-
if (ctx.event?.subscribe) {
|
|
566
|
-
const eventApi = ctx.event;
|
|
567
|
-
void (async () => {
|
|
568
|
-
try {
|
|
569
|
-
for await (const raw of eventApi.subscribe({ signal: measuredController.signal })) {
|
|
570
|
-
// Session identity: created fires for new sessions, execution.started
|
|
571
|
-
// every turn (covers sessions resumed across a restart), moved on a
|
|
572
|
-
// workspace change. Stamps and visibility resolve through this.
|
|
573
|
-
const identity = sessionIdentityEvent(raw);
|
|
574
|
-
if (identity) {
|
|
575
|
-
const { sessionID: sid, directory: dir } = identity;
|
|
576
|
-
if (dir !== undefined) rememberSessionDir(sid, dir);
|
|
577
|
-
// 2.1.4 serve sends execution.started with no location at all:
|
|
578
|
-
// resolve the session row instead of leaving the session unbound.
|
|
579
|
-
else void guarded("session bind (api)", () => bindSessionFromApi(sid));
|
|
580
|
-
continue;
|
|
581
|
-
}
|
|
582
|
-
const usage = sessionUsageEvent(raw);
|
|
583
|
-
if (!usage) continue;
|
|
584
|
-
const { sessionID, input, read, write } = usage;
|
|
585
|
-
sessions.touch(sessionID);
|
|
586
|
-
measuredTurns.set(sessionID, {
|
|
587
|
-
at: new Date().toISOString(),
|
|
588
|
-
input,
|
|
589
|
-
read,
|
|
590
|
-
write,
|
|
591
|
-
});
|
|
592
|
-
await guarded("status flush (measured)", () => flushStatus(sessionID));
|
|
593
|
-
}
|
|
594
|
-
} catch {
|
|
595
|
-
// the subscription ended (abort or host error); nothing to do
|
|
596
|
-
}
|
|
597
|
-
})();
|
|
598
|
-
}
|
|
599
|
-
|
|
170
|
+
const measuredController = await registerHooks(ctx, {
|
|
171
|
+
guarded, sessions, instanceDir, budget, noteHits, bindSessionIdentity,
|
|
172
|
+
bindSessionFromApi, measuredTurns, flushStatus,
|
|
173
|
+
getCompactCapture: () => onCompactCapture,
|
|
174
|
+
});
|
|
600
175
|
// ---- opt-in auto-capture (idle + compaction triggers) ------------------
|
|
601
176
|
// Default OFF: capture never reads sessions and never calls a model. (The
|
|
602
177
|
// measured-cache listener above does subscribe to the event stream by
|
|
@@ -612,181 +187,9 @@ const impl = {
|
|
|
612
187
|
// so decay/status — and bench/capture-trigger-compare.ts — can measure
|
|
613
188
|
// which trigger earns its tokens. Every failure is swallowed: capture must
|
|
614
189
|
// never be able to break a session.
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
typeof ctx.options.captureModel === "string" ? ctx.options.captureModel : "";
|
|
619
|
-
const captureMax = Number(ctx.options.captureMax) || 3;
|
|
620
|
-
const captureOnCompact = ctx.options?.captureOnCompact !== false;
|
|
621
|
-
const modelRef = parseModelRef(captureModel);
|
|
622
|
-
if (!modelRef) {
|
|
623
|
-
// Invalid/missing model: skip registering the whole subscription
|
|
624
|
-
// rather than guess (and warn once, at setup).
|
|
625
|
-
console.warn(
|
|
626
|
-
`[opencode-self-improvement] autoCapture is on but captureModel ${JSON.stringify(captureModel)} is invalid (expected "provider/id"); auto-capture disabled.`,
|
|
627
|
-
);
|
|
628
|
-
} else if (!ctx.event?.subscribe || !ctx.generate?.text || !ctx.session?.context) {
|
|
629
|
-
console.warn(
|
|
630
|
-
"[opencode-self-improvement] autoCapture is on but this OpenCode context lacks event.subscribe/generate.text/session.context; auto-capture disabled.",
|
|
631
|
-
);
|
|
632
|
-
} else {
|
|
633
|
-
const controller = new AbortController();
|
|
634
|
-
const eventApi = ctx.event;
|
|
635
|
-
const generateApi = ctx.generate;
|
|
636
|
-
// Arrow wrapper: keep the receiver bound. The harness fakes are closures,
|
|
637
|
-
// but a real client method that reads `this` would break if detached —
|
|
638
|
-
// and the fail-closed catch below would hide it. Optional call: the
|
|
639
|
-
// setup guard proves it exists, but property narrowing does not survive
|
|
640
|
-
// into the closure, and undefined degrades safely (empty transcript).
|
|
641
|
-
const contextFn = (input: { sessionID: string }) => ctx.session?.context?.(input);
|
|
642
|
-
|
|
643
|
-
// ONE capture pass, shared by both triggers. `seeded` is a transcript
|
|
644
|
-
// already in hand — the compaction hook carries the PRE-compaction
|
|
645
|
-
// messages, which is the whole point (Compaction Cliff: one round
|
|
646
|
-
// retains 53% of exact-wording rules); when it is absent (older host
|
|
647
|
-
// shapes) or too thin, the session context is read instead, the same
|
|
648
|
-
// source the idle trigger mines.
|
|
649
|
-
async function captureSession(
|
|
650
|
-
sid: string,
|
|
651
|
-
seeded: string,
|
|
652
|
-
trigger: "idle" | "compaction",
|
|
653
|
-
seededMsgs?: unknown,
|
|
654
|
-
): Promise<void> {
|
|
655
|
-
// Bind the capturing session for the synchronous stretches of this
|
|
656
|
-
// path - but NOT as a promise: the awaits below let another session
|
|
657
|
-
// move current, so the gate context and the persisted rows thread
|
|
658
|
-
// `sid` explicitly instead of reading it back from the global (#116).
|
|
659
|
-
setCurrent({ sessionID: sid });
|
|
660
|
-
// The capture's dedup reads and the rows it writes partition by the
|
|
661
|
-
// CAPTURED session's repository — an unbound sid would otherwise
|
|
662
|
-
// read global-only and mine duplicates into the store (#127; in
|
|
663
|
-
// production the prompt hook already bound it firmly, so this is a
|
|
664
|
-
// no-op there). SYNC only: a lookup call here would break the
|
|
665
|
-
// zero-token promise of the capture tests.
|
|
666
|
-
bindSessionProvisional(sid, instanceDir);
|
|
667
|
-
const captureGate = gateContext(sid);
|
|
668
|
-
// #152: an instance with no workspace cannot say which repository the
|
|
669
|
-
// mined rows belong to, and rows with no owner are exactly what the
|
|
670
|
-
// store refuses. Skip BEFORE the model call — no tokens spent on a
|
|
671
|
-
// capture that cannot be stored — and leave the reason in evidence.
|
|
672
|
-
if (!writeTarget(sid).ok) {
|
|
673
|
-
await record("auto_capture_refused", { session: sid, trigger }, true, sid, captureGate.evidenceContext);
|
|
674
|
-
return;
|
|
675
|
-
}
|
|
676
|
-
let transcript = seeded;
|
|
677
|
-
let msgs = seededMsgs;
|
|
678
|
-
if (transcript.length < 200) {
|
|
679
|
-
msgs = await contextFn({ sessionID: sid });
|
|
680
|
-
transcript = flattenTranscript(msgs);
|
|
681
|
-
}
|
|
682
|
-
if (transcript.length < 200) return; // too thin to mine reliably
|
|
683
|
-
// #44: how stale is a capture? Distance from the newest message of
|
|
684
|
-
// the mined transcript to this instant - measured on whatever the
|
|
685
|
-
// trigger actually mined (the hook payload for compaction, the
|
|
686
|
-
// session context for idle), so both triggers' lag is comparable.
|
|
687
|
-
const lagMs = lagSince(msgs);
|
|
688
|
-
const out = await generateApi.text({
|
|
689
|
-
model: modelRef,
|
|
690
|
-
// Redact the COMPLETE transcript, THEN apply the character budget
|
|
691
|
-
// (#132). Cropping first can start the window INSIDE a credential:
|
|
692
|
-
// a PEM body whose BEGIN marker fell off, or a token whose prefix
|
|
693
|
-
// fell off, matches no pattern — buildCapturePrompt's own scrub
|
|
694
|
-
// (kept, defense in depth) cannot recognize a fragment.
|
|
695
|
-
prompt: buildCapturePrompt(redactSecrets(transcript).slice(-8000), captureMax),
|
|
696
|
-
});
|
|
697
|
-
const text = typeof out === "string" ? out : out?.text ?? "";
|
|
698
|
-
const candidates = parseCandidates(text, captureMax);
|
|
699
|
-
for (const c of candidates) {
|
|
700
|
-
const durable: string[] = [];
|
|
701
|
-
let outcome: Awaited<ReturnType<typeof runWriteGate>>;
|
|
702
|
-
try {
|
|
703
|
-
outcome = await runWriteGate(
|
|
704
|
-
quarantineCandidate({
|
|
705
|
-
...c,
|
|
706
|
-
tags:
|
|
707
|
-
trigger === "compaction"
|
|
708
|
-
? ["auto-capture", CAPTURE_COMPACT_TAG]
|
|
709
|
-
: ["auto-capture"],
|
|
710
|
-
}),
|
|
711
|
-
{ ...captureGate, durable },
|
|
712
|
-
);
|
|
713
|
-
} catch (err) {
|
|
714
|
-
// A refused write must not disappear into the hook's fail-soft
|
|
715
|
-
// wrapper. Preserve any earlier gate retirements in the receipt.
|
|
716
|
-
await record(durable.length ? "auto_capture_partial" : "auto_capture_refused", {
|
|
717
|
-
session: sid, trigger, type: c.type, scope: redactSecrets(c.scope),
|
|
718
|
-
reason: String(err), retired: durable.join(",") || undefined,
|
|
719
|
-
}, false, sid, captureGate.evidenceContext);
|
|
720
|
-
continue;
|
|
721
|
-
}
|
|
722
|
-
await record(
|
|
723
|
-
trigger === "compaction"
|
|
724
|
-
? `auto_capture_compaction_${outcome.action}`
|
|
725
|
-
: `auto_capture_${outcome.action}`,
|
|
726
|
-
// A blocked credential-shaped scope must not reach the evidence log either.
|
|
727
|
-
// The promoted line also carries the audit fault when the
|
|
728
|
-
// write_promoted line fell (#155 review — capture has no
|
|
729
|
-
// reply to caveat, so this line is the trail's only note).
|
|
730
|
-
{
|
|
731
|
-
session: sid,
|
|
732
|
-
trigger,
|
|
733
|
-
type: c.type,
|
|
734
|
-
scope: redactSecrets(c.scope),
|
|
735
|
-
reason: outcome.reason ?? "",
|
|
736
|
-
audit_error: outcome.evidenceError,
|
|
737
|
-
},
|
|
738
|
-
false,
|
|
739
|
-
sid,
|
|
740
|
-
captureGate.evidenceContext,
|
|
741
|
-
);
|
|
742
|
-
}
|
|
743
|
-
await recordCaptureLag(sid, lagMs, candidates.length ? "candidates" : "empty", captureGate.evidenceContext);
|
|
744
|
-
}
|
|
745
|
-
|
|
746
|
-
void (async () => {
|
|
747
|
-
try {
|
|
748
|
-
for await (const raw of eventApi.subscribe({ signal: controller.signal })) {
|
|
749
|
-
if (!captureTriggerFor(raw)) continue;
|
|
750
|
-
const sid = captureSessionID(raw);
|
|
751
|
-
if (sid === undefined) continue;
|
|
752
|
-
setCurrent({ sessionID: sid });
|
|
753
|
-
const now = Date.now();
|
|
754
|
-
if (!captureCooldownPasses("idle", sid, now)) continue; // 5-min cooldown, shared across setups
|
|
755
|
-
try {
|
|
756
|
-
await captureSession(sid, "", "idle");
|
|
757
|
-
} catch {
|
|
758
|
-
// fail-closed: a broken capture attempt is invisible to the session
|
|
759
|
-
}
|
|
760
|
-
}
|
|
761
|
-
} catch {
|
|
762
|
-
// the subscription itself ended (abort or host error); nothing to do
|
|
763
|
-
}
|
|
764
|
-
})();
|
|
765
|
-
captureCleanup = () => controller.abort();
|
|
766
|
-
|
|
767
|
-
// The compaction trigger needs no extra subscription: the session
|
|
768
|
-
// compaction hook (registered above) calls through this seam. The
|
|
769
|
-
// cooldown names the trigger, so measuring a compaction capture is
|
|
770
|
-
// not confounded by an idle fire moments before - and lives at
|
|
771
|
-
// module level, so a second setup() cannot double-pay one
|
|
772
|
-
// compaction (#108).
|
|
773
|
-
if (captureOnCompact) {
|
|
774
|
-
onCompactCapture = (sid, messages) => {
|
|
775
|
-
if (controller.signal.aborted) return;
|
|
776
|
-
const now = Date.now();
|
|
777
|
-
if (!captureCooldownPasses("compaction", sid, now)) return; // 5-min cooldown
|
|
778
|
-
void guarded("session.compaction (auto-capture)", () =>
|
|
779
|
-
captureSession(sid, flattenTranscript(messages), "compaction", messages),
|
|
780
|
-
);
|
|
781
|
-
};
|
|
782
|
-
}
|
|
783
|
-
}
|
|
784
|
-
} else if (ctx.options?.captureOnCompact === true) {
|
|
785
|
-
// autoCapture is the master switch (zero-token default preserved).
|
|
786
|
-
console.warn(
|
|
787
|
-
"[opencode-self-improvement] captureOnCompact is on but autoCapture is off; compaction capture stays disabled (autoCapture is the master switch).",
|
|
788
|
-
);
|
|
789
|
-
}
|
|
190
|
+
const capture = configureAutoCapture(ctx, { instanceDir, gateContext, guarded });
|
|
191
|
+
onCompactCapture = capture.onCompactCapture;
|
|
192
|
+
const captureCleanup = capture.cleanup;
|
|
790
193
|
// ---- startup heartbeat (#138) ------------------------------------------
|
|
791
194
|
// Every other evidence line is written BY something that already worked,
|
|
792
195
|
// so "capture is off", "capture is misconfigured" and "capture is armed and
|