Skip to content

#1 Persistent memory for AI coding agents based on real-world benchmarks

fix(opencode): close OpenCode 2 capture gaps found in live sessions (#1476)

Rohit Ghumared03e88f6a08c
diff --git a/plugin/opencode/README.md b/plugin/opencode/README.md
index 6bcc4b32..817a20aa 100644
--- a/plugin/opencode/README.md
+++ b/plugin/opencode/README.md
@@ -11,6 +11,7 @@
<p align="center">
<img src="https://img.shields.io/badge/MCP-54_tools-1f6feb?style=flat-square" alt="54 MCP tools" />
<img src="https://img.shields.io/badge/Plugin-22_hooks-1f6feb?style=flat-square" alt="22 hooks" />
+ <img src="https://img.shields.io/badge/OpenCode-1.x_%2B_2.x-1f6feb?style=flat-square" alt="OpenCode 1.x and 2.x" />
<img src="https://img.shields.io/badge/Commands-2_slash-1f6feb?style=flat-square" alt="2 slash commands" />
<img src="https://img.shields.io/badge/[email protected]%25-00875f?style=flat-square" alt="95.2% R@5" />
</p>
@@ -45,20 +46,41 @@ Add to `~/.config/opencode/opencode.json` or your project's `.opencode/opencode.
### 3. Install the plugin
-Add to `~/.config/opencode/opencode.json`:
+Copy the plugin file:
+
+```bash
+mkdir -p ~/.config/opencode/plugins
+cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
+```
+
+That is the whole install. OpenCode loads every plugin file in
+`~/.config/opencode/plugins/` automatically, so there is nothing to register.
+
+> **Do not also add it to `opencode.json`.** Listing the file under
+> `"plugins"` on top of leaving it in the auto-loaded directory registers the
+> same plugin twice, and it then captures every event twice. If you see doubled
+> observations, remove the `"plugins"` entry and keep the file where it is.
+>
+> If you would rather keep plugins outside that directory, install the file
+> somewhere else and point the config key at it:
+>
+> ```json
+> {
+> "plugins": ["./my-plugins/agentmemory-capture.ts"]
+> }
+> ```
+>
+> Either location works. The two must not both be in effect at once.
+
+**OpenCode 1.x** — the same file works, using the V1 key instead:
```json
{
- "plugin": ["./plugins/agentmemory-capture.ts"]
+ "plugin": ["./my-plugins/agentmemory-capture.ts"]
}
```
-Copy the plugin file from this repo:
-
-```bash
-mkdir -p ~/.config/opencode/plugins
-cp plugin/opencode/agentmemory-capture.ts ~/.config/opencode/plugins/
-```
+See [OpenCode 1.x and 2.x](#opencode-1x-and-2x) below.
### 4. Add the slash commands
@@ -72,6 +94,213 @@ cp plugin/opencode/commands/remember.md ~/.config/opencode/commands/
Restart OpenCode or open a new session. The plugin auto-captures everything.
+## OpenCode 1.x and 2.x
+
+`agentmemory-capture.ts` supports both plugin APIs from a single file.
+
+OpenCode 2 replaced the V1 `Hooks`-object plugin shape: the default export must
+carry an `id` plus a `setup(ctx)`, and hooks are registered on the domain that
+owns the operation. The plugin therefore default-exports both:
+
+```ts
+export default {
+ id: "agentmemory-capture",
+ setup: v2Setup, // OpenCode 2.x
+ server: v1Hooks, // OpenCode 1.x (SDK 1.18.x era)
+}
+```
+
+- **OpenCode 2.x** reads `id` and `setup()`.
+- **OpenCode 1.17 and 1.18** call `server()` and use the returned hooks. They
+ also call `setup()`, with a context that has no `tool`, `session` or `event`.
+ `setup()` returns immediately when those are missing, so only the V1 hooks
+ run there.
+- The two implementations are separate on purpose. Sharing an export does not
+ translate V1 hooks into V2 hooks, and the payloads differ enough that a shared
+ core would overstate V2 coverage.
+- The named `export const AgentmemoryCapturePlugin` exists for direct imports
+ and for V1 releases older than 1.18.29, which expect a function as the
+ default export. A V1 loader that resolves `default` and calls `server()` on it
+ sees one plugin; the named export is not consulted unless a loader iterates
+ every export, which no observed version does.
+
+**V1 load, verified.** OpenCode 1.17.10 and 1.18.34 (the `opencode-ai` npm
+package) were run against this file in live sessions: one plugin instance,
+reads and shell calls captured through the V1 hooks, and one `config_loaded`
+per session.
+
+Validated against **OpenCode v2.0.22**, and re-checked on **v2.0.24**, by running the plugin inside a live
+session and logging the objects as they arrive, not by reading the generated
+SDK types. That distinction matters: `@opencode-ai/sdk` 1.4.10 declares
+`event.properties` and the V1 event names, and it is stale relative to the
+runtime. Where this README says a payload was observed, it was read off a
+running server.
+
+### What the V2 runtime actually does
+
+- **The payload is in `event.data`, not `event.properties`.** The envelope is
+ `created, data, id, location, type`. Reading `properties` yields `{}`.
+- **The V1 event names are gone.** They were not renamed one-for-one; the
+ stream is organised differently. `location` on the envelope is
+ process-level, so session identity comes from `data.sessionID`.
+- **`list()` returns `{ data, location }`.** `ctx.agent.list()`,
+ `ctx.provider.list()` and `ctx.mcp.list()` all resolve to that shape.
+- **`ctx.model.default()` is a promise.** Unawaited it is `{}`.
+- **`session.created` exists.** On v2.0.24 it carries `sessionID`,
+ `projectID`, `location`, `version`, `subpath` and `slug`. The title arrives
+ later in `session.renamed`, so a session registers on creation with its
+ directory in hand. The fallback to
+ "first event carrying an ID" remains for sessions that predate the plugin
+ load, which never emit the event. An earlier revision of this plugin claimed
+ `session.created` did not exist; that came from observing an already-open
+ session and never creating one, which is absence in a sample rather than
+ absence in the API.
+- **`ctx.session.hook("compaction")` registers, but its invocation is
+ unverified.** Calling `ctx.session.compact()` only *queues* a compaction
+ request; the hook would fire when the compaction actually runs. Forcing a
+ compaction in a running v2.0.22 emitted `session.compaction.started` and
+ `session.compaction.failed` immediately, with `Nothing to compact yet`,
+ because the session was empty. That proves the events fire and says nothing
+ about the hook, which never got a real compaction to run. The hook is kept
+ and the events are captured alongside it: if the hook is invoked it attaches
+ memory to the compaction prompt, and the events record that compaction
+ happened either way.
+- **`session.execution.succeeded` triggers `/summarize`.** It fires when a run
+ finishes and carries only `{ sessionID }`, so it adds no observation. V1
+ summarizes when a session goes idle; this is the V2 equivalent.
+- **`session.instructions.updated` carries `delta`, a map from instruction
+ source to content hash.** The plugin records the source names, not the
+ hashes.
+- **A standalone `opencode session delete` exits before the plugin sees
+ `session.deleted`.** The session then stays open in agentmemory. Summaries do
+ not depend on it, because they come from `session.execution.succeeded`.
+- **`parentID` is accepted by `ctx.session.create` but appears in no event
+ payload.** The `parentID` sent to `/session/start` is therefore always null;
+ the field is kept in case a future version populates it.
+
+### Hook mapping
+
+| V1 | V2 | Status |
+|---|---|---|
+| `event` | `ctx.event.subscribe()` | ported |
+| `tool.execute.before` | `ctx.tool.hook("execute.before")` | ported |
+| tool results (`message.part.updated`) | `ctx.tool.hook("execute.after")` | ported |
+| `chat.message` | `ctx.session.hook("prompt")` | ported |
+| `experimental.chat.system.transform` | `ctx.session.hook("context")` | ported |
+| `experimental.session.compacting` | `ctx.session.hook("compaction")` | ported, **unverified** |
+| `config` | *(no hook)* | snapshot at `setup`, refreshed on `*.updated` |
+| `chat.params` | *(no equivalent)* | not captured |
+
+`output.system` (a string array) became `event.system` (`SystemPart[]`), so
+injection pushes part objects rather than strings.
+
+### Event mapping
+
+| V1 event | V2 |
+|---|---|
+| `session.created` | `session.created` (or first event carrying `data.sessionID`) |
+| `session.deleted` | `session.deleted` |
+| `session.status`, `session.idle` | `session.step.started` / `session.step.ended`; `session.execution.succeeded` triggers `/summarize` |
+| `message.updated` | `session.text.ended` (`assistant_message`), `session.reasoning.ended` |
+| `message.part.updated` | `ctx.tool.hook("execute.after")` |
+| `command.executed` | the command arrives through `execute.after`; `shell.exited` records a non-zero exit |
+| `session.error` | `session.execution.failed` |
+| `file.edited` | `file.watcher.updated` |
+| `session.compacted` | `session.compaction.started` / `.failed` |
+| `permission.updated` | `permission.asked` (payload is a `PermissionRequest`) |
+| `todo.updated`, `session.diff` | *no V2 equivalent observed* |
+
+`permission.asked` and `permission.replied` were not seen firing during
+development. They are handled against the documented shape, reading both the
+V2 field names and the V1 fallbacks, and are not covered by the observed
+columns in the table below.
+
+### Injection happens on every call, fetched once per prompt
+
+`ctx.session.hook("context")` fires on every model call, so recalled memory is
+injected every time. The previous implementation injected once per session,
+which meant only the first prompt of a session carried memory.
+
+Because the hook also fires on each tool continuation, `/context` is requested
+at most once per prompt and then reused for the rest of the turn: the recalled
+set does not change while a prompt is being answered. A new prompt clears the
+cache. The `compaction` hook reuses the same turn cache.
+
+Compaction is also captured from the `session.compaction.started` / `.failed`
+events, which are observed.
+
+### What V2 cannot do
+
+- **`chat.params`** — V2's `context` hook exposes `options` with `maxTokens`
+ only; temperature and `topP` are absent, and `model` carries only
+ `id` / `providerID` / `variant`. Recorded `llm_params` would be wrong rather
+ than partial, so they are not recorded. The `model` on the hook is captured
+ in `step_start` instead, where it is real.
+
+### Why `ctx` is typed `any`
+
+The V2 setup signature is `async function v2Setup(ctx: any)`. That is
+deliberate, and worth explaining because it looks like a shortcut.
+
+Typing it properly would mean importing types from `@opencode-ai/plugin`. The
+generated types shipped for that package are **stale for V2**: SDK 1.4.10
+declares `EventSessionCreated = { type, properties: { sessionID, info } }` and
+enumerates the V1 event names, none of which the v2.0.22 runtime emits. A
+type-only import would therefore make the compiler reject correct code while
+accepting the shape that caused the original bug. Silence was the safer of the
+two failure modes, so `any` is used and the correctness burden moved to runtime
+verification.
+
+The known cost, stated plainly:
+
+- The compiler will not catch V2 payload drift. A renamed field becomes a
+ `undefined` at runtime instead of a type error.
+- Nothing checks that the event names in `handleEvent` are real. This branch
+ shipped a handler for fifteen V1 event names, none of which fire.
+- There is no compile-time guarantee that `ctx.session.hook(...)` takes a name
+ that exists. The loader accepts any string, so a typo registers nothing and
+ fails silently.
+
+That is why the verification suite drives the plugin with payloads captured
+from a live server instead of hand-built objects, and why the
+[Verification](#verification) section distinguishes observed from inferred. If a
+future release ships correct V2 types, this signature should be tightened and
+these three risks retired with it.
+
+### Verification
+
+- `test/opencode-plugin-v2.test.ts` — 38 cases driving the V2 path with payloads
+ captured from v2.0.22. It runs under the repo's existing vitest, so:
+
+ ```bash
+ npx vitest run test/opencode-plugin-v2.test.ts
+ ```
+
+ It covers session lifecycle, the tool hooks, memory injection on every model
+ call, compaction, the event switch, and the regression where an early
+ `return` ended the event subscription. Each case added with the compaction
+ change was checked against the previous commit: the three compaction cases
+ fail on it and pass here.
+- In a live session the plugin produced real observations for
+ `post_tool_use`, `config_loaded`, `step_start`, `step_finish`,
+ `reasoning`, `assistant_message` and `notification`, and requested
+ `/summarize` when the run finished.
+ `session.compaction.started` and `session.compaction.failed` were confirmed
+ by forcing a compaction in a running v2.0.22.
+
+`session.text.started`, `session.reasoning.started`, `session.inbox.delivered`,
+`shell.created` and `session.usage.updated` are read but not recorded. The
+first two carry no text yet, the inbox event carries only an ID, `shell.created`
+duplicates the command that `execute.after` already records, and usage
+duplicates the token and cost figures in `step_finish`. A config snapshot equal
+to the previous one is not recorded again.
+
+Earlier in this branch the V2 path loaded cleanly and captured almost nothing,
+because it was verified against a hand-built context object that agreed with
+its own assumptions. Verifying that the plugin loads is not verifying that it
+works, and the suite exists so that the next person does not have to learn that
+twice.
+
## What gets captured
### Session lifecycle
@@ -89,12 +318,12 @@ Restart OpenCode or open a new session. The plugin auto-captures everything.
### Messages & prompts
-| Event | Hook | agentmemory API |
-|---|---|---|
-| User prompt (rich) | `chat.message` | POST /observe |
-| User prompt metadata | `message.updated` (user) | POST /observe |
-| Assistant response | `message.updated` (assistant) | POST /observe |
-| Message removed (undo) | `message.removed` | POST /observe |
+| Event | V1 hook | V2 hook | agentmemory API |
+|---|---|---|---|
+| User prompt (rich) | `chat.message` | `ctx.session.hook("prompt")` | POST /observe |
+| User prompt metadata | `message.updated` (user) | `message.updated` (user) | POST /observe |
+| Assistant response | `message.updated` (assistant) | `message.updated` (assistant) | POST /observe |
+| Message removed (undo) | `message.removed` | `message.removed` | POST /observe |
### Parts & steps
@@ -112,20 +341,23 @@ Restart OpenCode or open a new session. The plugin auto-captures everything.
### File enrichment pipeline
-| Event | Hook | agentmemory API |
-|---|---|---|
-| File tool params | `tool.execute.before` → stash paths | — |
-| File edited | `file.edited` → stash paths | — |
-| File part attached | `message.part.updated` (file) → stash paths | — |
-| Enrichment inject | `experimental.chat.system.transform` | POST /enrich → `output.system[]` |
-| Memory context inject | `experimental.chat.system.transform` | POST /context → `output.system[]` |
+| Event | V1 hook | V2 hook | agentmemory API |
+|---|---|---|---|
+| File tool params | `tool.execute.before` → stash paths | `ctx.tool.hook("execute.before")` | - |
+| File edited | `file.edited` → stash paths | `file.edited` | - |
+| File part attached | `message.part.updated` (file) → stash paths | `message.part.updated` (file) | - |
+| Enrichment inject | `experimental.chat.system.transform` | `ctx.session.hook("context")` | POST /enrich → system prompt |
+| Memory context inject | `experimental.chat.system.transform` | `ctx.session.hook("context")` | POST /context → system prompt |
+
+On V1 the two injects land in `output.system[]`. On V2 they are pushed as
+`SystemPart` objects onto `event.system`.
### Permissions
-| Event | Hook | agentmemory API |
-|---|---|---|
-| Permission prompt | `permission.updated` | POST /observe |
-| Permission reply | `permission.replied` | POST /observe |
+| Event | V1 hook | V2 hook | agentmemory API |
+|---|---|---|---|
+| Permission prompt | `permission.updated` | `permission.asked` | POST /observe |
+| Permission reply | `permission.replied` | `permission.replied` | POST /observe |
### Tasks & commands
@@ -136,11 +368,15 @@ Restart OpenCode or open a new session. The plugin auto-captures everything.
### Model & config
-| Event | Hook | agentmemory API |
-|---|---|---|
-| LLM parameters | `chat.params` | POST /observe |
-| Config loaded | `config` | POST /observe |
-| Compaction (WIP) | `experimental.session.compacting` | POST /context → `output.context[]` |
+| Event | V1 hook | V2 | agentmemory API |
+|---|---|---|---|
+| LLM parameters | `chat.params` | not captured | POST /observe (V1 only) |
+| Config loaded | `config` | snapshot at setup | POST /observe |
+| Compaction context | `experimental.session.compacting` | `ctx.session.hook("compaction")`, unverified | POST /context → `event.system[]` |
+
+These three are the only differences between the V1 and V2 paths. Everything
+else in this document is captured identically on both. See
+[What V2 cannot do](#what-v2-cannot-do).
### File enrichment + memory injection (two-layer pipeline)
diff --git a/plugin/opencode/agentmemory-capture.ts b/plugin/opencode/agentmemory-capture.ts
index 0465bd58..870f7662 100644
--- a/plugin/opencode/agentmemory-capture.ts
+++ b/plugin/opencode/agentmemory-capture.ts
@@ -263,7 +263,7 @@ function extractErrorMessage(err: unknown): string {
return String(err ?? "");
}
-export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {
+const v1Hooks: Plugin = async (ctx) => {
defaultProjectCwd = ctx.worktree || ctx.project?.id || process.cwd();
defaultProjectName = resolveProjectName(defaultProjectCwd);
@@ -795,3 +795,522 @@ export const AgentmemoryCapturePlugin: Plugin = async (ctx) => {
},
};
};
+
+async function v2Setup(ctx: any) {
+ if (typeof ctx?.tool?.hook !== "function" || typeof ctx?.session?.hook !== "function" || typeof ctx?.event?.subscribe !== "function") {
+ return;
+ }
+ const location = ctx.location;
+ defaultProjectCwd = location?.directory ?? location?.project?.directory ?? process.cwd();
+ defaultProjectName = resolveProjectName(defaultProjectCwd);
+
+ async function observeV2(sessionId: string, hookType: string, data: Record<string, unknown>): Promise<void> {
+ await observe(sessionId, hookType, data);
+ }
+
+ const shellSessions = new Map<string, string>();
+ const turnContextCache = new Map<string, string>();
+
+ function stashAdd(sid: string, paths: Iterable<string>): void {
+ const stash = stashFor(sid);
+ for (const p of paths) stash.add(p);
+ if (stash.size > MAX_STASHED_FILES) {
+ const keep = [...stash].slice(-MAX_STASHED_FILES);
+ stash.clear();
+ for (const k of keep) stash.add(k);
+ }
+ }
+
+ const toolNames = new Map<string, string>();
+ const toolCallInputs = new Map<string, Record<string, unknown>>();
+ const reportedToolCalls = new Set<string>();
+ const registeredSessions = new Set<string>();
+
+ function namesFrom(result: unknown): string[] {
+ const arr = Array.isArray(result) ? result : (result as any)?.data;
+ if (!Array.isArray(arr)) return [];
+ return arr.map((x: any) => (typeof x === "string" ? x : x?.id ?? x?.name)).filter(Boolean);
+ }
+
+ let lastConfigSnapshot: string | null = null;
+
+ async function snapshotConfig(): Promise<void> {
+ const [agents, providers, mcp, modelDefault] = await Promise.all([
+ ctx.agent?.list?.().catch(() => null),
+ ctx.provider?.list?.().catch(() => null),
+ ctx.mcp?.list?.().catch(() => null),
+ Promise.resolve(ctx.model?.default?.()).catch(() => null),
+ ]);
+ const model = Array.isArray(modelDefault) ? modelDefault[0] : (modelDefault as any)?.data;
+ const payload = {
+ agents: namesFrom(agents),
+ providers: namesFrom(providers),
+ mcp_servers: namesFrom(mcp),
+ model: model ? `${model.providerID ?? ""}/${model.id ?? model.modelID ?? ""}` : null,
+ model_limits: model?.limit ?? null,
+ location: defaultProjectCwd,
+ };
+ const snapshot = JSON.stringify(payload);
+ if (snapshot === lastConfigSnapshot) return;
+ lastConfigSnapshot = snapshot;
+ if (activeSessionId) await observeV2(activeSessionId, "config_loaded", payload);
+ else pendingConfig = payload;
+ }
+
+ void snapshotConfig().catch((e) => {
+ if (DEBUG) console.error("[agentmemory] config snapshot failed:", (e as Error).message);
+ });
+
+ await ctx.tool.hook("execute.before", (event: any) => {
+ if (!FILE_TOOLS.has(String(event?.tool ?? "").toLowerCase())) return;
+ const sid = event?.sessionID || activeSessionId;
+ if (!sid) return;
+ const args = event?.input as Record<string, unknown> | undefined;
+ if (!args) return;
+ stashAdd(sid, extractFilePaths(args));
+ });
+
+ await ctx.tool.hook("execute.after", async (event: any) => {
+ const sid = event?.sessionID || activeSessionId;
+ if (!sid) return;
+ const tool = String(event?.tool ?? "");
+ const callId = (event?.id as string) || (event?.messageID as string) || null;
+ const status = String(event?.status ?? "");
+ const result = event?.result ?? {};
+ const metadata = (result?.metadata ?? {}) as Record<string, unknown>;
+ const output = result?.output as Record<string, unknown> | undefined;
+ const raw = output?.output ?? result?.content;
+ const text = Array.isArray(raw)
+ ? raw.map((p: any) => (typeof p === "string" ? p : (p?.text ?? ""))).join("\n")
+ : typeof raw === "string"
+ ? raw
+ : "";
+ const startMs = typeof metadata?.started === "number" ? metadata.started : null;
+ const endMs = typeof metadata?.ended === "number" ? metadata.ended : null;
+ const duration = startMs != null && endMs != null ? endMs - startMs : null;
+
+ if (status === "error") {
+ await observeV2(sid, "post_tool_failure", {
+ tool_name: tool,
+ call_id: callId,
+ tool_input: safeSlice(event?.input, 4000),
+ tool_output: safeSlice(text || extractErrorMessage(event?.error) || extractErrorMessage(metadata?.error), 8000),
+ duration_ms: duration,
+ });
+ if (callId) reportedToolCalls.add(`${sid}:${callId}`);
+ return;
+ }
+
+ await observeV2(sid, "post_tool_use", {
+ tool_name: tool,
+ call_id: callId,
+ tool_input: safeSlice(event?.input, 4000),
+ tool_output: safeSlice(text, 8000),
+ title: (output?.title as string) ?? null,
+ metadata: metadata,
+ duration_ms: duration,
+ attachments: Array.isArray(output?.attachments)
+ ? (output?.attachments as Array<Record<string, unknown>>).map((a) => a.filename || a.url)
+ : [],
+ });
+ if (callId) reportedToolCalls.add(`${sid}:${callId}`);
+ });
+
+ await ctx.session.hook("prompt", async (event: any) => {
+ const sid = event?.sessionID || activeSessionId;
+ if (!sid) return;
+ const files = (event?.prompt?.files ?? [])
+ .map((f: any) => (typeof f === "string" ? f : f?.uri ?? f?.filename ?? f?.url))
+ .filter(Boolean) as string[];
+ stashAdd(sid, files);
+ turnContextCache.delete(sid);
+ await observeV2(sid, "prompt_submit", {
+ prompt: (event?.prompt?.text ?? "").slice(0, 8000),
+ files: files.slice(0, 20),
+ agents: event?.prompt?.agents ?? [],
+ skills: event?.prompt?.skills ?? [],
+ delivery: event?.delivery ?? null,
+ });
+ });
+
+ await ctx.session.hook("context", async (event: any) => {
+ const sid = event?.sessionID || activeSessionId;
+ if (!sid) return;
+ if (!Array.isArray(event.system)) return;
+
+ if (!contextInjectedSessions.has(sid)) {
+ event.system.push({ type: "text", text: AGENTMEMORY_INSTRUCTIONS });
+ contextInjectedSessions.add(sid);
+ }
+
+ let ctxText = startContextCache.get(sid) ?? turnContextCache.get(sid);
+ if (typeof ctxText !== "string" || ctxText.length === 0) {
+ const result = await postJson("/context", { sessionId: sid, project: projectFor(sid).name });
+ ctxText = (result as any)?.context;
+ }
+ if (typeof ctxText === "string" && ctxText.length > 0) {
+ turnContextCache.set(sid, ctxText);
+ startContextCache.delete(sid);
+ event.system.push({ type: "text", text: ctxText });
+ }
+
+ const stash = stashFor(sid);
+ if (stash.size === 0) return;
+ const files = [...stash].slice(0, 10);
+ const enrichResult = await postJson("/enrich", { sessionId: sid, files, toolName: "enrich_inject" });
+ const enrichCtx = (enrichResult as any)?.context;
+ if (typeof enrichCtx === "string" && enrichCtx.length > 0) {
+ event.system.push({ type: "text", text: enrichCtx });
+ for (const f of files) stash.delete(f);
+ }
+ });
+
+ await ctx.session.hook("compaction", async (event: any) => {
+ const sid = event?.sessionID || activeSessionId;
+ if (!sid) return;
+ if (!Array.isArray(event?.system)) return;
+ let ctxText = turnContextCache.get(sid);
+ if (typeof ctxText !== "string" || ctxText.length === 0) {
+ const result = await postJson("/context", { sessionId: sid, project: projectFor(sid).name });
+ ctxText = (result as any)?.context;
+ if (typeof ctxText === "string" && ctxText.length > 0) turnContextCache.set(sid, ctxText);
+ }
+ if (typeof ctxText === "string" && ctxText.length > 0) {
+ event.system.push({ type: "text", text: ctxText });
+ }
+ });
+
+ const controller = new AbortController();
+
+ const handleEvent = async (event: any): Promise<void> => {
+ const type = String(event?.type ?? "");
+ const data: any = event?.data ?? {};
+ const eventSid = typeof data.sessionID === "string" && data.sessionID ? data.sessionID : null;
+ const sid0 = eventSid || activeSessionId;
+
+ if (eventSid && !registeredSessions.has(eventSid)) {
+ if (!activeSessionId) activeSessionId = eventSid;
+ stashedFiles.set(sid0, new Set());
+ seenSubtaskIds.delete(sid0);
+ seenToolCallIds.delete(sid0);
+ contextInjectedSessions.delete(sid0);
+ const dir = (data.location?.directory as string) || (event?.location?.directory as string) || null;
+ if (dir) {
+ sessionProjects.set(sid0, { cwd: dir, name: resolveProjectName(dir) });
+ }
+ const proj = projectFor(sid0);
+ const startResult = await postJson("/session/start", {
+ sessionId: sid0,
+ title: (data.title as string) ?? null,
+ parentID: (data.parentID as string) ?? null,
+ project: proj.name,
+ cwd: proj.cwd,
+ });
+
+ if (startResult === null) {
+ stashedFiles.delete(sid0);
+ contextInjectedSessions.delete(sid0);
+ if (activeSessionId === eventSid) activeSessionId = null;
+ if (DEBUG) {
+ console.error("[agentmemory] /session/start failed, will retry on the next event for", eventSid);
+ }
+ return;
+ }
+ registeredSessions.add(eventSid);
+
+ const startCtx = (startResult as any)?.context;
+ if (typeof startCtx === "string" && startCtx.length > 0) startContextCache.set(sid0, startCtx);
+ await observeV2(sid0, "session_started", {});
+ if (pendingConfig) {
+ await observeV2(sid0, "config_loaded", pendingConfig);
+ pendingConfig = null;
+ }
+ }
+
+ switch (type) {
+
+ case "session.execution.failed": {
+ if (!sid0) return;
+ await observeV2(sid0, "post_tool_failure", {
+ tool_name: "session.execution",
+ tool_input: "",
+ tool_output: safeSlice(extractErrorMessage(data.error ?? data), 8000),
+ });
+ return;
+ }
+
+ case "session.compaction.started": {
+ if (!sid0) return;
+ await observeV2(sid0, "compaction_event", {
+ state: "started",
+ reason: (data.reason as string) ?? null,
+ inputID: (data.inputID as string) ?? null,
+ recent: safeSlice(data.recent, 8000),
+ });
+ return;
+ }
+
+ case "session.compaction.failed": {
+ if (!sid0) return;
+ await observeV2(sid0, "compaction_event", {
+ state: "failed",
+ reason: (data.reason as string) ?? null,
+ inputID: (data.inputID as string) ?? null,
+ tool_output: safeSlice(extractErrorMessage(data.error ?? data.reason), 8000),
+ });
+ return;
+ }
+
+ case "session.step.started": {
+ if (!sid0) return;
+ await observeV2(sid0, "step_start", {
+ messageID: (data.assistantMessageID as string) ?? null,
+ agent: (data.agent as string) ?? null,
+ model: data.model ? `${data.model.providerID ?? ""}/${data.model.id ?? ""}` : null,
+ });
+ return;
+ }
+
+ case "session.step.ended": {
+ if (!sid0) return;
+ const tokens = (data.tokens ?? {}) as Record<string, any>;
+ await observeV2(sid0, "step_finish", {
+ messageID: (data.assistantMessageID as string) ?? null,
+ reason: (data.rawFinish as string) ?? (data.finish as string) ?? null,
+ cost: data.cost ?? 0,
+ input_tokens: tokens.input ?? 0,
+ output_tokens: tokens.output ?? 0,
+ reasoning_tokens: tokens.reasoning ?? 0,
+ cache_read: tokens.cache?.read ?? 0,
+ cache_write: tokens.cache?.write ?? 0,
+ });
+ return;
+ }
+
+ case "session.agent.selected": {
+ if (!sid0) return;
+ await observeV2(sid0, "agent_selected", {
+ name: (data.agent as string) ?? null,
+ previous: (data.previous as string) ?? null,
+ });
+ return;
+ }
+
+ case "session.reasoning.ended": {
+ if (!sid0) return;
+ await observeV2(sid0, "reasoning", {
+ messageID: (data.assistantMessageID as string) ?? null,
+ text: safeSlice(data.text, 4000),
+ });
+ return;
+ }
+
+ case "session.instructions.updated": {
+ if (!sid0) return;
+ const sources = data.delta && typeof data.delta === "object" ? Object.keys(data.delta) : [];
+ if (sources.length === 0) return;
+ await observeV2(sid0, "notification", {
+ notification_type: "instructions_updated",
+ sources: sources.slice(0, 50),
+ });
+ return;
+ }
+
+ case "session.text.ended": {
+ if (!sid0) return;
+ const text = typeof data.text === "string" ? data.text : "";
+ if (!text) return;
+ await observeV2(sid0, "assistant_message", {
+ messageID: (data.assistantMessageID as string) ?? null,
+ text: text.slice(0, 8000),
+ });
+ return;
+ }
+
+ case "session.execution.succeeded": {
+ if (!sid0) return;
+ await post("/summarize", { sessionId: sid0 });
+ return;
+ }
+
+ case "shell.created": {
+ const info = (data.info ?? {}) as Record<string, any>;
+ const shellSid = (info.metadata?.sessionID as string) || sid0;
+ if (!shellSid) return;
+ if (info.id) shellSessions.set(String(info.id), shellSid);
+ return;
+ }
+
+ case "shell.exited": {
+ const shellId = String(data.id ?? "");
+ const shellSid = shellSessions.get(shellId) || activeSessionId;
+ if (!shellSid) return;
+ const exit = Number(data.exit ?? 0);
+ if (exit !== 0) {
+ await observeV2(shellSid, "post_tool_failure", {
+ tool_name: "shell",
+ call_id: shellId,
+ tool_input: null,
+ tool_output: safeSlice(data.status, 4000),
+ duration_ms: null,
+ });
+ }
+ return;
+ }
+
+ case "shell.deleted": {
+ const shellId = String(data.id ?? "");
+ shellSessions.delete(shellId);
+ return;
+ }
+
+ case "file.watcher.updated":
+ case "filesystem.changed":
+ case "vcs.branch.updated": {
+ const sid = sid0 || activeSessionId;
+ if (!sid) return;
+ const file = (data.file as string) ?? (data.path as string) ?? null;
+ if (file) stashAdd(sid, [file]);
+ return;
+ }
+
+ case "session.tool.input.started": {
+ if (!sid0) return;
+ if (data.id) toolNames.set(String(data.id), String(data.name ?? ""));
+ return;
+ }
+
+ case "session.tool.input.ended": {
+ if (!sid0) return;
+ if (data.id && typeof data.text === "string" && !toolNames.has(String(data.id))) {
+ try {
+ const parsed = JSON.parse(data.text);
+ if (typeof parsed?.name === "string") toolNames.set(String(data.id), parsed.name);
+ } catch {
+ }
+ }
+ return;
+ }
+
+ case "session.tool.called": {
+ if (!sid0) return;
+ if (data.id) toolCallInputs.set(String(data.id), (data.input ?? {}) as Record<string, unknown>);
+ return;
+ }
+
+ case "session.tool.progress": {
+ if (!sid0) return;
+ const callId = String(data.id ?? "");
+ if (!callId || !FILE_TOOLS.has((toolNames.get(callId) ?? "").toLowerCase())) return;
+ const input = toolCallInputs.get(callId);
+ if (!input) return;
+ stashAdd(sid0, extractFilePaths(input));
+ return;
+ }
+
+ case "session.tool.success": {
+ const callId = String(data.id ?? "");
+ toolNames.delete(callId);
+ toolCallInputs.delete(callId);
+ if (sid0) reportedToolCalls.delete(`${sid0}:${callId}`);
+ return;
+ }
+
+ case "session.tool.failed": {
+ if (!sid0) return;
+ const callId = String(data.id ?? "");
+ if (callId && reportedToolCalls.has(`${sid0}:${callId}`)) return;
+ await observeV2(sid0, "post_tool_failure", {
+ tool_name: toolNames.get(callId) || null,
+ call_id: callId || null,
+ tool_input: safeSlice(toolCallInputs.get(callId), 4000),
+ tool_output: safeSlice(extractErrorMessage(data.error), 8000),
+ duration_ms: null,
+ });
+ if (callId) {
+ toolNames.delete(callId);
+ toolCallInputs.delete(callId);
+ }
+ return;
+ }
+
+ case "permission.asked": {
+ if (!sid0) return;
+ const resources = (data.resources ?? data.patterns ?? []) as unknown;
+ await observeV2(sid0, "notification", {
+ notification_type: "permission_prompt",
+ permission: (data.action as string) ?? (data.permission as string) ?? "unknown",
+ pattern: Array.isArray(resources) ? resources.join(", ") : String(resources ?? ""),
+ tool_call_id: (data.tool?.callID as string) ?? (data.callID as string) ?? null,
+ title: (data.action as string) ?? (data.permission as string) ?? "",
+ metadata: data.metadata ?? {},
+ });
+ return;
+ }
+
+ case "permission.replied": {
+ if (!sid0) return;
+ await observeV2(sid0, "permission_replied", {
+ permission_id: (data.requestID as string) ?? (data.permissionID as string) ?? "",
+ response: (data.reply as string) ?? (data.response as string) ?? "",
+ });
+ return;
+ }
+
+ case "session.deleted": {
+ const sid = (data.sessionID as string) || activeSessionId;
+ if (!sid) return;
+ await post("/session/end", { sessionId: sid });
+ void post("/crystals/auto", { olderThanDays: 7 }, 30000);
+ void post("/consolidate-pipeline", { tier: "all", force: true }, 30000);
+ if (sid === activeSessionId) activeSessionId = null;
+ registeredSessions.delete(sid);
+ pruneSessionMaps(sid);
+ startContextCache.delete(sid);
+ contextInjectedSessions.delete(sid);
+ for (const key of reportedToolCalls) {
+ if (key.startsWith(`${sid}:`)) reportedToolCalls.delete(key);
+ }
+ return;
+ }
+
+ case "config.updated":
+ case "agent.updated":
+ case "provider.updated":
+ case "model.updated":
+ case "mcp.status.changed": {
+ if (DEBUG) console.error("[agentmemory] config changed, re-snapshotting");
+ void snapshotConfig().catch(() => {});
+ return;
+ }
+ }
+ };
+
+ void (async () => {
+ try {
+ for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
+ try {
+ await handleEvent(event);
+ } catch (e) {
+ if (DEBUG) console.error("[agentmemory] event handler failed:", (e as Error).message);
+ }
+ }
+ } catch (e) {
+ if (DEBUG) console.error("[agentmemory] event stream failed:", (e as Error).message);
+ }
+ })();
+
+ return () => {
+ controller.abort();
+ startContextCache.clear();
+ contextInjectedSessions.clear();
+ };
+}
+
+export default {
+ id: "agentmemory-capture",
+ setup: v2Setup,
+ server: v1Hooks,
+};
+
+export const AgentmemoryCapturePlugin: Plugin = v1Hooks;
diff --git a/test/opencode-plugin-v2.test.ts b/test/opencode-plugin-v2.test.ts
new file mode 100644
index 00000000..9e1c696f
--- /dev/null
+++ b/test/opencode-plugin-v2.test.ts
@@ -0,0 +1,468 @@
+import { describe, expect, it, vi } from "vitest";
+import { resolve } from "node:path";
+const PLUGIN = resolve(__dirname, "../plugin/opencode/agentmemory-capture.ts");
+const SID = "ses_test";
+type Sent = { path: string; hook: string; body: any };
+interface Harness {
+ observed: Sent[];
+ posts: string[];
+ hooks: () => string;
+ push: (event: any) => void;
+ fire: (name: string, ev: any) => Promise<void>;
+ fireTool: (name: string, ev: any) => Promise<void>;
+ failNextStarts: (n: number) => void;
+ cleanup: () => Promise<void>;
+ hooksOf: Record<string, Function[]>;
+}
+async function loadPlugin(): Promise<any> {
+ vi.resetModules();
+ const mod: any = await import(PLUGIN);
+ return mod.default;
+}
+async function harness(): Promise<Harness> {
+ const def = await loadPlugin();
+ const observed: Sent[] = [];
+ const posts: string[] = [];
+ let failStarts = 0;
+ const fetchMock = vi.fn(async (url: any, init: any) => {
+ const path = String(url).split("/agentmemory/")[1]?.split("?")[0] ?? "";
+ if (path === "session/start" && failStarts > 0) {
+ failStarts--;
+ posts.push("session/start:failed");
+ throw new Error("agentmemory indisponivel");
+ }
+ let body: any = {};
+ try {
+ body = JSON.parse(String(init?.body ?? "{}"));
+ } catch {}
+ if (path.startsWith("observe")) observed.push({ path, hook: body.hookType ?? "", body });
+ else if (path) posts.push(path + (body.hookType ? ":" + body.hookType : ""));
+ return new Response(JSON.stringify({ ok: true, context: "MEMORIA" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ });
+ });
+ vi.stubGlobal("fetch", fetchMock);
+ const queue: any[] = [];
+ let waiter: ((r: any) => void) | null = null;
+ let done = false;
+ const push = (e: any) => {
+ if (waiter) {
+ const w = waiter;
+ waiter = null;
+ w({ value: e, done: false });
+ } else queue.push(e);
+ };
+ const sessionHooks: Record<string, Function[]> = {};
+ const toolHooks: Record<string, Function[]> = {};
+ const ctx: any = {
+ location: { directory: "C:/repos/projeto", project: { directory: "C:/repos/projeto" } },
+ agent: { list: async () => ({ data: [{ id: "build" }, { id: "plan" }], location: {} }) },
+ provider: { list: async () => ({ data: [{ id: "anthropic" }], location: {} }) },
+ mcp: { list: async () => ({ data: [{ id: "srv" }], location: {} }) },
+ model: {
+ default: async () => ({
+ data: { id: "sonnet", providerID: "anthropic", limit: { context: 200000, output: 8192 } },
+ location: {},
+ }),
+ },
+ tool: { hook: async (n: string, f: any) => void ((toolHooks[n] ??= []).push(f)) },
+ session: { hook: async (n: string, f: any) => void ((sessionHooks[n] ??= []).push(f)) },
+ event: {
+ subscribe: () => ({
+ [Symbol.asyncIterator]: () => ({
+ next: () =>
+ new Promise<any>((r) => {
+ if (queue.length) r({ value: queue.shift(), done: false });
+ else if (done) r({ value: undefined, done: true });
+ else waiter = r;
+ }),
+ return: () => {
+ done = true;
+ return Promise.resolve({ value: undefined, done: true });
+ },
+ }),
+ }),
+ },
+ };
+ const cleanup = await def.setup(ctx);
+ await new Promise((r) => setTimeout(r, 30));
+ return {
+ observed,
+ posts,
+ push,
+ hooks: () => Object.keys(sessionHooks).join(", "),
+ hooksOf: sessionHooks,
+ failNextStarts: (n: number) => {
+ failStarts = n;
+ },
+ fire: async (name, ev) => {
+ for (const f of sessionHooks[name] ?? []) await f(ev);
+ },
+ fireTool: async (name, ev) => {
+ for (const f of toolHooks[name] ?? []) await f(ev);
+ },
+ drain: (ms = 150) => new Promise((r) => setTimeout(r, ms)),
+ cleanup: async () => {
+ await cleanup?.();
+ vi.unstubAllGlobals();
+ },
+ };
+}
+const hooksOf = (h: Harness) => (name: string) => h.observed.filter((o) => o.hook === name).length;
+describe("OpenCode V2 capture — ciclo de vida e configuracao", () => {
+ it("registra a sessao no primeiro evento e envia config", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e1", location: {}, created: 1 });
+ await h.drain();
+ expect(h.observed.some((o) => o.hook === "session_started")).toBe(true);
+ expect(h.observed.some((o) => o.hook === "config_loaded")).toBe(true);
+ await h.cleanup();
+ });
+ it("registra session.created com title e location reais", async () => {
+ const h = await harness();
+ h.push({
+ type: "session.created",
+ data: {
+ sessionID: "ses_criada",
+ projectID: "proj_1",
+ location: { directory: "C:/repos/projeto" },
+ subpath: "",
+ slug: "s",
+ title: "titulo real",
+ version: "2.0.22",
+ },
+ id: "sc",
+ location: {},
+ created: 1,
+ });
+ await h.drain();
+ const start = h.posts.find((p) => p === "session/start");
+ expect(start).toBeDefined();
+ await h.cleanup();
+ });
+ it("registra uma segunda sessao, inclusive filha de subagente", async () => {
+ const h = await harness();
+ h.push({ type: "session.step.started", data: { sessionID: SID, agent: "build", model: { id: "m", providerID: "p" }, started: 1 }, id: "e1", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.step.started", data: { sessionID: "ses_segunda", agent: "build", model: { id: "m", providerID: "p" }, started: 1 }, id: "e2", location: {}, created: 2 });
+ await h.drain();
+ expect(h.observed.filter((o) => o.hook === "session_started").length).toBeGreaterThanOrEqual(2);
+ await h.cleanup();
+ });
+ it("reenvia /session/start quando ele falha, em vez de travar", async () => {
+ const h = await harness();
+ h.failNextStarts(2);
+ h.push({ type: "session.step.started", data: { sessionID: "ses_retry", agent: "build", model: { id: "m", providerID: "p" }, started: 1 }, id: "r1", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.step.started", data: { sessionID: "ses_retry", agent: "build", model: { id: "m", providerID: "p" }, started: 2 }, id: "r2", location: {}, created: 2 });
+ await h.drain();
+ h.push({ type: "session.step.started", data: { sessionID: "ses_retry", agent: "build", model: { id: "m", providerID: "p" }, started: 3 }, id: "r3", location: {}, created: 3 });
+ await h.drain();
+ expect(h.posts.filter((p) => p === "session/start:failed").length).toBeGreaterThanOrEqual(2);
+ await h.cleanup();
+ });
+});
+describe("OpenCode V2 capture — hooks", () => {
+ it("captura uso de ferramenta em execute.before e execute.after", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ await h.fireTool("execute.before", { tool: "read", sessionID: SID, input: { filePath: "C:/repos/a.ts" } });
+ await h.fireTool("execute.after", {
+ tool: "read",
+ sessionID: SID,
+ id: "c1",
+ status: "completed",
+ input: { filePath: "C:/repos/a.ts" },
+ result: { content: [{ type: "text", text: "conteudo" }], metadata: { started: 1, ended: 3 } },
+ });
+ await h.drain();
+ await h.cleanup();
+ });
+ it("reporta falha de ferramenta exatamente uma vez", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ await h.fireTool("execute.after", { tool: "bash", sessionID: SID, id: "c1", status: "error", input: { command: "x" }, result: { metadata: { status: "error" } } });
+ await h.drain();
+ expect(hooksOf(h)("post_tool_failure")).toBe(1);
+ await h.cleanup();
+ });
+ it("falha le o texto de event.error, a forma que a documentacao da V2 descreve", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ await h.fireTool("execute.after", {
+ tool: "bash",
+ sessionID: SID,
+ id: "c1",
+ status: "error",
+ input: { command: "false" },
+ error: { name: "BashError", message: "command exited with 1" },
+ result: { metadata: { exit: 1, status: "error", truncated: false } },
+ });
+ await h.drain();
+ const fail = h.observed.find((o) => o.hook === "post_tool_failure");
+ expect(fail, "post_tool_failure nao foi observado").toBeDefined();
+ expect(String(fail!.body.data.tool_output)).toContain("command exited with 1");
+ await h.cleanup();
+ });
+
+ it("session.tool.failed nao duplica o que execute.after ja reportou", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ await h.fireTool("execute.after", { tool: "bash", sessionID: SID, id: "dup", status: "error", input: { c: 1 }, result: { metadata: {} } });
+ await h.drain();
+ const before = hooksOf(h)("post_tool_failure");
+ h.push({ type: "session.tool.failed", data: { sessionID: SID, assistantMessageID: "m", id: "dup", error: { message: "x" }, executed: false }, id: "tf", location: {}, created: 2 });
+ await new Promise((r) => setTimeout(r, 60));
+ expect(hooksOf(h)("post_tool_failure")).toBe(before);
+ await h.cleanup();
+ });
+ it("session.tool.failed reporta quando o hook nao cobriu a chamada", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.tool.input.started", data: { sessionID: SID, assistantMessageID: "m", id: "s1", name: "bash" }, id: "ti", location: {}, created: 2 });
+ h.push({ type: "session.tool.called", data: { sessionID: SID, assistantMessageID: "m", id: "s1", input: { command: "f" }, executed: false }, id: "tc", location: {}, created: 3 });
+ await new Promise((r) => setTimeout(r, 40));
+ h.push({ type: "session.tool.failed", data: { sessionID: SID, assistantMessageID: "m", id: "s1", error: { message: "exit 1" }, executed: false }, id: "tf", location: {}, created: 4 });
+ await h.drain();
+ await h.cleanup();
+ });
+ it("shell.exited com exit != 0 vira falha; exit 0 nao vira nada", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "shell.created", data: { info: { command: "f", cwd: "C:/r", id: "sh_bad", metadata: { sessionID: SID }, shell: "pwsh", status: "running", time: { started: 1 } } }, id: "sc1", location: {}, created: 2 });
+ await h.drain();
+ const before = hooksOf(h)("post_tool_failure");
+ h.push({ type: "shell.exited", data: { id: "sh_bad", exit: 1, status: "failed" }, id: "se", location: {}, created: 3 });
+ await h.drain();
+ h.push({ type: "shell.created", data: { info: { command: "ls", cwd: "C:/r", id: "sh_ok", metadata: { sessionID: SID }, shell: "pwsh", status: "running", time: { started: 1 } } }, id: "sc2", location: {}, created: 4 });
+ await new Promise((r) => setTimeout(r, 40));
+ h.push({ type: "shell.exited", data: { id: "sh_ok", exit: 0, status: "completed" }, id: "se2", location: {}, created: 5 });
+ await new Promise((r) => setTimeout(r, 60));
+ expect(hooksOf(h)("post_tool_failure")).toBe(before + 1);
+ await h.cleanup();
+ });
+ it("injeta memoria em TODA chamada de modelo, nao so na primeira", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const sizes: number[] = [];
+ for (let i = 0; i < 3; i++) {
+ const ev: any = { sessionID: SID, agent: "build", model: { id: "m", providerID: "p" }, options: { maxTokens: 100 }, system: [{ type: "text", text: "sys" }], messages: [], tools: {} };
+ await h.fire("context", ev);
+ sizes.push(ev.system.length);
+ }
+ expect(sizes).toEqual([3, 2, 2]);
+ expect(h.posts.filter((p) => p === "context").length).toBeLessThanOrEqual(1);
+ await h.cleanup();
+ });
+ it("registra o hook compaction e injeta memoria quando invocado", async () => {
+ const h = await harness();
+ expect(h.hooksOf["compaction"]).toBeDefined();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const ev: any = { sessionID: SID, system: [{ type: "text", text: "sys" }] };
+ await h.fire("compaction", ev);
+ expect(ev.system.length).toBeGreaterThan(1);
+ await h.cleanup();
+ });
+
+ it("o hook compaction reaproveita o contexto do turno", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const ctx: any = { sessionID: SID, agent: "build", model: { id: "m", providerID: "p" }, options: {}, system: [{ type: "text", text: "sys" }], messages: [], tools: {} };
+ await h.fire("context", ctx);
+ const after = h.posts.filter((p) => p === "context").length;
+ const ev: any = { sessionID: SID, system: [{ type: "text", text: "sys" }] };
+ await h.fire("compaction", ev);
+ expect(h.posts.filter((p) => p === "context").length).toBe(after);
+ expect(ev.system.length).toBeGreaterThan(1);
+ await h.cleanup();
+ });
+});
+describe("OpenCode V2 capture — compactacao por eventos", () => {
+ it("session.compaction.started gera observation", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.compaction.started", data: { sessionID: SID, reason: "auto", recent: "texto", inputID: "in_1" }, id: "cs", location: {}, created: 2 });
+ await h.drain();
+ const ev = h.observed.find((o) => o.hook === "compaction_event")!;
+ expect(ev.body.data.state).toBe("started");
+ expect(ev.body.data.reason).toBe("auto");
+ await h.cleanup();
+ });
+ it("session.compaction.failed gera observation com o erro", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.compaction.failed", data: { sessionID: SID, reason: "auto", error: { message: "falhou" }, inputID: "in_2" }, id: "cf", location: {}, created: 2 });
+ await h.drain();
+ const ev = h.observed.find((o) => o.hook === "compaction_event")!;
+ expect(ev.body.data.state).toBe("failed");
+ expect(String(ev.body.data.tool_output)).toContain("falhou");
+ await h.cleanup();
+ });
+ it("session.execution.succeeded pede /summarize sem gerar observation", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const before = h.observed.length;
+ h.push({ type: "session.execution.succeeded", data: { sessionID: SID }, id: "es", location: {}, created: 2 });
+ await h.drain();
+ expect(h.observed.length).toBe(before);
+ expect(h.posts.filter((p) => p === "summarize").length).toBe(1);
+ await h.cleanup();
+ });
+});
+describe("OpenCode V2 capture — eventos do stream", () => {
+ const cases: Array<[string, any, string]> = [
+ ["session.step.started", { sessionID: SID, agent: "build", assistantMessageID: "m", model: { id: "m", providerID: "p" }, started: 1 }, "step_start"],
+ ["session.step.ended", { sessionID: SID, assistantMessageID: "m", cost: 0.1, rawFinish: "stop", tokens: { input: 1, output: 2, reasoning: 0, cache: { read: 3, write: 0 } } }, "step_finish"],
+ ["session.agent.selected", { sessionID: SID, agent: "build", previous: "plan" }, "agent_selected"],
+ ["session.reasoning.ended", { sessionID: SID, assistantMessageID: "m", ordinal: 0, text: "pensando" }, "reasoning"],
+ ["session.instructions.updated", { sessionID: SID, delta: { "core/date": "5c8d" } }, "notification"],
+ ["session.text.ended", { sessionID: SID, assistantMessageID: "m", ordinal: 0, text: "resposta final" }, "assistant_message"],
+ ["permission.asked", { sessionID: SID, action: "bash", resources: ["rm"], tool: { callID: "c1" } }, "notification"],
+ ["permission.replied", { sessionID: SID, requestID: "r1", reply: "once" }, "permission_replied"],
+ ["session.execution.failed", { sessionID: SID, error: { message: "boom" } }, "post_tool_failure"],
+ ];
+ for (const [type, data, expectHook] of cases) {
+ it(`${type} produz exatamente uma observation ${expectHook}`, async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type, data, id: "x", location: {}, created: 2 });
+ await h.drain();
+ expect(hooksOf(h)(expectHook)).toBe(1);
+ await h.cleanup();
+ });
+ }
+ const silent: Array<[string, any]> = [
+ ["session.reasoning.started", { sessionID: SID, assistantMessageID: "m", ordinal: 0, state: "streaming" }],
+ ["session.inbox.delivered", { sessionID: SID, inboxID: "i1" }],
+ ["shell.created", { info: { command: "git status", cwd: "C:/r", id: "sh1", metadata: { sessionID: SID }, shell: "pwsh", status: "running", time: { started: 1 } } }],
+ ];
+ for (const [type, data] of silent) {
+ it(`${type} nao gera observation`, async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const before = h.observed.length;
+ h.push({ type, data, id: "x", location: {}, created: 2 });
+ await h.drain();
+ expect(h.observed.length).toBe(before);
+ await h.cleanup();
+ });
+ }
+ it("session.instructions.updated grava as fontes alteradas, nao os hashes", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.instructions.updated", data: { sessionID: SID, delta: { "core/codemode": "3a6c", "core/date": "5c8d" } }, id: "iu", location: {}, created: 2 });
+ await h.drain();
+ const ev = h.observed.find((o) => o.hook === "notification");
+ expect(ev?.body.data.sources).toEqual(["core/codemode", "core/date"]);
+ expect(JSON.stringify(ev?.body.data)).not.toContain("3a6c");
+ await h.cleanup();
+ });
+ it("session.instructions.updated sem fontes nao gera observation", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const before = h.observed.length;
+ h.push({ type: "session.instructions.updated", data: { sessionID: SID, delta: {} }, id: "iu", location: {}, created: 2 });
+ await h.drain();
+ expect(h.observed.length).toBe(before);
+ await h.cleanup();
+ });
+ it("session.text.ended grava a resposta do assistente", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.text.ended", data: { sessionID: SID, assistantMessageID: "m1", ordinal: 0, text: "refresh devolve null" }, id: "te", location: {}, created: 2 });
+ await h.drain();
+ const ev = h.observed.find((o) => o.hook === "assistant_message");
+ expect(ev?.body.data.text).toBe("refresh devolve null");
+ expect(ev?.body.data.messageID).toBe("m1");
+ await h.cleanup();
+ });
+ it("session.deleted fecha a sessao e libera as chaves", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "session.deleted", data: { sessionID: SID }, id: "d", location: {}, created: 2 });
+ await h.drain();
+ expect(h.posts.some((p) => p.startsWith("crystals/auto"))).toBe(true);
+ expect(h.posts.some((p) => p.startsWith("consolidate-pipeline"))).toBe(true);
+ await h.cleanup();
+ });
+ it("model.updated re-snapshota a configuracao", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ const before = hooksOf(h)("config_loaded");
+ h.push({ type: "model.updated", data: {}, id: "mu", location: {}, created: 2 });
+ await h.drain();
+ expect(hooksOf(h)("config_loaded")).toBe(before);
+ await h.cleanup();
+ });
+});
+describe("OpenCode V2 capture — resiliência", () => {
+ it("a assinatura sobrevive a um evento desconhecido", async () => {
+ const h = await harness();
+ h.push({ type: "session.execution.started", data: { sessionID: SID }, id: "e", location: {}, created: 1 });
+ await h.drain();
+ h.push({ type: "message.updated", data: {}, id: "u1", location: {}, created: 2 });
+ h.push({ type: "evento.inventado", data: {}, id: "u2", location: {}, created: 3 });
+ await new Promise((r) => setTimeout(r, 40));
+ h.push({ type: "session.agent.selected", data: { sessionID: SID, agent: "x", previous: "y" }, id: "u3", location: {}, created: 4 });
+ await h.drain();
+ await h.cleanup();
+ });
+ it("cleanup nao lanca", async () => {
+ const h = await harness();
+ await expect(h.cleanup()).resolves.toBeUndefined();
+ });
+});
+describe("plugin/opencode — forma do export", () => {
+ it("exporta id + setup + server para V1 e V2", async () => {
+ const mod: any = await import(PLUGIN);
+ expect(mod.default.id).toBe("agentmemory-capture");
+ expect(typeof mod.default.setup).toBe("function");
+ expect(typeof mod.default.server).toBe("function");
+ expect(typeof mod.AgentmemoryCapturePlugin).toBe("function");
+ });
+ it("setup nao faz nada num contexto V1 sem tool, session e event", async () => {
+ const fetchMock = vi.fn(async () => new Response("{}", { status: 200 }));
+ vi.stubGlobal("fetch", fetchMock);
+ const def = await loadPlugin();
+ const v1ctx = { options: {}, agent: { list: async () => ({ data: [{ id: "build" }] }) }, catalog: {}, command: {}, skill: {} };
+ await expect(def.setup(v1ctx)).resolves.toBeUndefined();
+ await new Promise((r) => setTimeout(r, 30));
+ expect(fetchMock).not.toHaveBeenCalled();
+ vi.unstubAllGlobals();
+ });
+ it("o caminho V1 continua devolvendo os 7 hooks", async () => {
+ const mod: any = await import(PLUGIN);
+ const hooks = await mod.default.server({} as any);
+ expect(Object.keys(hooks).sort()).toEqual(
+ [
+ "chat.message",
+ "chat.params",
+ "config",
+ "event",
+ "experimental.chat.system.transform",
+ "experimental.session.compacting",
+ "tool.execute.before",
+ ].sort(),
+ );
+ });
+});