diff --git a/README.md b/README.md index 33a7e2d..893127c 100644 --- a/README.md +++ b/README.md @@ -202,7 +202,7 @@ One `./server` entry serves both OpenCode generations: 1.x calls its `server()` | `honcho_*` tools | `tool` | `tool.transform` | | Session start, assistant capture, cleanup | `event` | `event.subscribe()` (`session.created`, `session.text.ended`, `session.step.ended`, `session.execution.*`, `session.deleted`) | -On 2.x, prompt-specific recall rides in the request context instead of a synthetic message part, because 2.x persists prompt-hook edits as the user's message. +On 2.x, prompt-specific recall rides in the request context instead of a synthetic message part, because 2.x persists prompt-hook edits as the user's message. Each recall is inserted right after the prompt it was retrieved for, on every step, so earlier history never changes and provider prompt caches stay valid. ### How hooks drive memory diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index d7f4f0f..705164c 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -57,6 +57,20 @@ const nextGeneration = (location: string) => { } const isCurrentGeneration = (location: string, generation: number) => generations().get(location) === generation +// Recall blocks per location, session and prompt message ID. They live outside setup() because +// OpenCode reloads a location's plugins when it reboots that location's services, which happens +// after it sits idle. A reload must not drop the recalls already shown after earlier prompts: +// that rewrites history and costs the prompt cache (claude-agent replays the whole conversation). +type SessionRecalls = Map> +const RECALLS = Symbol.for("@honcho-ai/opencode-honcho.v2.recall") +const recallStore = (location: string): SessionRecalls => { + const g = globalThis as Record | undefined> + const all = (g[RECALLS] ??= new Map()) + let recalls = all.get(location) + if (!recalls) all.set(location, (recalls = new Map())) + return recalls +} + export const setup = async (ctx: PluginContext) => { const location = ctx.location.directory const generation = nextGeneration(location) @@ -65,9 +79,14 @@ export const setup = async (ctx: PluginContext) => { const core = createHonchoCore(consoleHost(ctx.location.directory, ctx.location.project?.directory), configPath) core.setHostVersion(ctx.app.version) - // Prompt-specific recall per session. The v1 path appends it to the user message; on v2 the - // prompt hook's edits become the persisted user text, so it rides in the request context instead. - const pendingRecall = new Map() + // Prompt-specific recall, per session and prompt message ID. The v1 path appends it to the user + // message; on v2 the prompt hook's edits become the persisted user text, so it rides in the + // request context instead. That context is rebuilt every step, so each recall goes back in right + // after its own prompt: appending at the tail moved it every step, which broke prompt caching + // and made claude-agent restart its Claude Code session. + // Every prompt is recorded, with undefined when Honcho returned no new recall for it. The store + // outlives this generation (see recallStore). + const pendingRecall = recallStore(location) const here = ctx.location.directory const sessionDirectories = new Map() @@ -87,7 +106,8 @@ export const setup = async (ctx: PluginContext) => { timestampToIso(Date.now()), "session.prompt", ) - if (block) pendingRecall.set(event.sessionID, block) + const recalls = pendingRecall.get(event.sessionID) ?? new Map() + pendingRecall.set(event.sessionID, recalls.set(event.messageID, block ?? undefined)) await core.log("debug", "Honcho captured user prompt.", { sessionId: event.sessionID, recall: Boolean(block) }) }) @@ -96,8 +116,20 @@ export const setup = async (ctx: PluginContext) => { const blocks = await core.systemBlocks({ sessionID: event.sessionID }) if (blocks.length === 0) return for (const text of blocks) event.system.push({ type: "text", text }) - const recall = pendingRecall.get(event.sessionID) - if (recall) event.messages.push({ role: "user", content: [{ type: "text", text: recall }] }) + // Prompts arrive in order, so a missing prompt followed by a present one was removed (compaction + // or a revert), not queued. Its recall moves to the next prompt that has none: Honcho skips + // repeating a block it believes is still shown. + let orphan: string | undefined + for (const [messageID, recall] of pendingRecall.get(event.sessionID) ?? []) { + const at = event.messages.findIndex((message) => message.id === messageID) + if (at === -1) { + orphan = recall ?? orphan + continue + } + const text = recall ?? orphan + orphan = undefined + if (text) event.messages.splice(at + 1, 0, { role: "user", content: [{ type: "text", text }] }) + } }) await ctx.session.hook("compaction", async (event) => { diff --git a/tests/v2-wire.test.js b/tests/v2-wire.test.js index d3351f9..bdc406b 100644 --- a/tests/v2-wire.test.js +++ b/tests/v2-wire.test.js @@ -217,3 +217,93 @@ describe("OpenCode 2 event scoping", () => { } }) }) + +describe("OpenCode 2 recall placement", () => { + // Honcho API stub: creates echo their id, and the session context carries a recall per search query. + const honchoFetch = async (url, init = {}) => { + const target = new URL(url) + if (/\/sessions\/[^/]+\/context$/.test(target.pathname)) + return Response.json({ messages: [], summary: null, peer_representation: `Recall for ${target.searchParams.get("search_query")}`, peer_card: null }) + if (target.pathname.endsWith("/messages")) return Response.json([]) + const body = typeof init.body === "string" ? JSON.parse(init.body) : {} + return Response.json({ id: body.id, metadata: {}, configuration: {}, created_at: new Date(0).toISOString() }) + } + + test("recall stays right after its prompt on every step and turn", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "honcho-v2-")) + const configPath = path.join(home, "config.json") + await writeFile(configPath, JSON.stringify({ apiKey: "test-key", peerName: "wire", hosts: { opencode: { recallMode: "hybrid" } } })) + const realFetch = globalThis.fetch + globalThis.fetch = honchoFetch + try { + const { ctx, hooks, find } = fakeContext({ directory: home }) + ctx.options = { configPath } + const mod = await import("../dist/server.js") + const cleanup = await mod.default.setup(ctx) + const prompt = (message) => find(hooks.session, "prompt")({ sessionID: "ses_place", messageID: message.id, prompt: { text: message.content[0].text } }) + const request = async (...messages) => { + const event = { sessionID: "ses_place", model: { providerID: "anthropic", id: "claude" }, system: [], messages } + await find(hooks.session, "context")(event) + return event.messages.map((message) => message.id ?? message.content[0].text) + } + const user = (id, text) => ({ id, role: "user", content: [{ type: "text", text }] }) + const first = user("msg_1", "fix memory injection") + const second = user("msg_2", "now add tests for placement") + const reply = [{ id: "msg_a", role: "assistant", content: [] }, { id: "msg_t", role: "tool", content: [] }] + const recall = expect.stringContaining("Recall for") + + await prompt(first) + expect(await request(first)).toEqual(["msg_1", recall]) + // Later steps only append: the recall must not move to the tail. + expect(await request(first, ...reply)).toEqual(["msg_1", recall, "msg_a", "msg_t"]) + // A queued prompt's recall waits until the prompt is in the history. + await prompt(second) + expect(await request(first, ...reply)).toEqual(["msg_1", recall, "msg_a", "msg_t"]) + expect(await request(first, ...reply, second)).toEqual(["msg_1", recall, "msg_a", "msg_t", "msg_2", recall]) + // Removed by a revert: the same topic gets no new block from Honcho, so the old recall moves to it. + const third = user("msg_3", "now add tests for placement") + await prompt(third) + expect(await request(first, ...reply, third)).toEqual(["msg_1", recall, "msg_a", "msg_t", "msg_3", recall]) + + await cleanup() + } finally { + globalThis.fetch = realFetch + } + }) + + test("recall survives a plugin reload for the same location", async () => { + const home = await mkdtemp(path.join(os.tmpdir(), "honcho-v2-")) + const configPath = path.join(home, "config.json") + await writeFile(configPath, JSON.stringify({ apiKey: "test-key", peerName: "wire", hosts: { opencode: { recallMode: "hybrid" } } })) + const realFetch = globalThis.fetch + globalThis.fetch = honchoFetch + try { + const mod = await import("../dist/server.js") + const load = async () => { + const { ctx, hooks, find } = fakeContext({ directory: home }) + ctx.options = { configPath } + return { cleanup: await mod.default.setup(ctx), hooks, find } + } + const user = (id, text) => ({ id, role: "user", content: [{ type: "text", text }] }) + const first = user("msg_1", "fix memory injection") + const request = async ({ hooks, find }, ...messages) => { + const event = { sessionID: "ses_reload", model: { providerID: "anthropic", id: "claude" }, system: [], messages } + await find(hooks.session, "context")(event) + return event.messages.map((message) => message.id ?? message.content[0].text) + } + const recall = expect.stringContaining("Recall for") + + const before = await load() + await before.find(before.hooks.session, "prompt")({ sessionID: "ses_reload", messageID: first.id, prompt: { text: first.content[0].text } }) + expect(await request(before, first)).toEqual(["msg_1", recall]) + await before.cleanup() + + // OpenCode reloads the location's plugins after it idles; the next request must look the same. + const after = await load() + expect(await request(after, first)).toEqual(["msg_1", recall]) + await after.cleanup() + } finally { + globalThis.fetch = realFetch + } + }) +})