Skip to content

Commit 89abd4b

Browse files
committed
fix(memory-worth): read user text from event bus instead of empty output.parts
Upstream anomalyco/opencode#22831 proves chat.message output.parts is always empty live, so digest retrieval and capture silently no-op. Subscribe to message.updated (role) + message.part.updated (text) on the existing event hook, accumulate per session, and consume via getSessionUserText in chat.message. Guards: text parts only, skip synthetic/ignored, user-role gate, per-session prune on delete.
1 parent 1a45efb commit 89abd4b

3 files changed

Lines changed: 157 additions & 7 deletions

File tree

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import { describe, it } from "node:test";
2+
import assert from "node:assert/strict";
3+
import { getSessionUserText, pruneSession, recordMessageInfo, recordPart } from "./message-events.js";
4+
5+
function userTextPart(sessionID: string, messageID: string, text: string, extra: Record<string, unknown> = {}) {
6+
return { id: `part-${messageID}`, sessionID, messageID, type: "text", text, ...extra };
7+
}
8+
9+
describe("message-events", () => {
10+
it("returns user-role text and skips assistant messages", () => {
11+
const session = "msg-events-s1";
12+
recordMessageInfo({ id: "m-assistant", sessionID: session, role: "assistant" });
13+
recordPart(userTextPart(session, "m-assistant", "Remember to handle errors gracefully"));
14+
recordMessageInfo({ id: "m-user", sessionID: session, role: "user" });
15+
recordPart(userTextPart(session, "m-user", "always use zod for validation"));
16+
assert.equal(getSessionUserText(session), "always use zod for validation");
17+
pruneSession(session);
18+
});
19+
20+
it("resolves text recorded before the role arrives", () => {
21+
const session = "msg-events-s2";
22+
recordPart(userTextPart(session, "m-late-role", "avoid try/catch in handlers"));
23+
assert.equal(getSessionUserText(session), "");
24+
recordMessageInfo({ id: "m-late-role", sessionID: session, role: "user" });
25+
assert.equal(getSessionUserText(session), "avoid try/catch in handlers");
26+
pruneSession(session);
27+
});
28+
29+
it("skips synthetic, ignored, empty, and non-text parts", () => {
30+
const session = "msg-events-s3";
31+
recordMessageInfo({ id: "m-skip", sessionID: session, role: "user" });
32+
recordPart(userTextPart(session, "m-skip", "injected digest text", { synthetic: true }));
33+
recordPart(userTextPart(session, "m-skip", "ignored fragment", { ignored: true }));
34+
recordPart(userTextPart(session, "m-skip", ""));
35+
recordPart({ id: "p-tool", sessionID: session, messageID: "m-skip", type: "tool" });
36+
assert.equal(getSessionUserText(session), "");
37+
recordPart(userTextPart(session, "m-skip", "real user words here"));
38+
assert.equal(getSessionUserText(session), "real user words here");
39+
pruneSession(session);
40+
});
41+
42+
it("prefers the latest user message and prunes on session end", () => {
43+
const session = "msg-events-s4";
44+
recordMessageInfo({ id: "m-first", sessionID: session, role: "user" });
45+
recordPart(userTextPart(session, "m-first", "first directive here"));
46+
recordMessageInfo({ id: "m-second", sessionID: session, role: "user" });
47+
recordPart(userTextPart(session, "m-second", "second directive here"));
48+
assert.equal(getSessionUserText(session), "second directive here");
49+
pruneSession(session);
50+
assert.equal(getSessionUserText(session), "");
51+
});
52+
53+
it("ignores unknown roles", () => {
54+
const session = "msg-events-s5";
55+
recordMessageInfo({ id: "m-weird", sessionID: session, role: "system" });
56+
recordPart(userTextPart(session, "m-weird", "system prompt content here"));
57+
assert.equal(getSessionUserText(session), "");
58+
pruneSession(session);
59+
});
60+
});
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
// User-text accumulation from the opencode event bus.
2+
//
3+
// Why this exists instead of reading output.parts in the chat.message hook:
4+
// upstream anomalyco/opencode#22831 proves the runtime always delivers an
5+
// empty parts array to that hook, so capture and FTS retrieval silently
6+
// no-op live. Bus events carry the actual content: message.updated reports
7+
// the message role, message.part.updated carries full text parts.
8+
type Role = "user" | "assistant";
9+
10+
interface MessageInfo {
11+
id: string;
12+
sessionID: string;
13+
role: string;
14+
}
15+
16+
interface TextPartShape {
17+
id: string;
18+
sessionID: string;
19+
messageID: string;
20+
type: string;
21+
text?: string;
22+
synthetic?: boolean;
23+
ignored?: boolean;
24+
}
25+
26+
const roles = new Map<string, Role>();
27+
const texts = new Map<string, string[]>();
28+
const sessionMessages = new Map<string, string[]>();
29+
30+
const MAX_MESSAGES_PER_SESSION = 50;
31+
32+
function trackMessage(sessionID: string, messageID: string): void {
33+
const list = sessionMessages.get(sessionID) ?? [];
34+
if (!list.includes(messageID)) {
35+
list.push(messageID);
36+
sessionMessages.set(sessionID, list.slice(-MAX_MESSAGES_PER_SESSION));
37+
}
38+
}
39+
40+
export function recordMessageInfo(info: MessageInfo): void {
41+
if (info.role !== "user" && info.role !== "assistant") return;
42+
roles.set(info.id, info.role);
43+
trackMessage(info.sessionID, info.id);
44+
}
45+
46+
export function recordPart(part: TextPartShape): void {
47+
if (part.type !== "text") return;
48+
if (part.synthetic === true || part.ignored === true) return;
49+
const text = part.text ?? "";
50+
if (!text) return;
51+
const chunks = texts.get(part.messageID) ?? [];
52+
chunks.push(text);
53+
texts.set(part.messageID, chunks);
54+
trackMessage(part.sessionID, part.messageID);
55+
}
56+
57+
export function getSessionUserText(sessionID: string): string {
58+
const list = sessionMessages.get(sessionID) ?? [];
59+
for (let i = list.length - 1; i >= 0; i--) {
60+
const messageID = list[i] as string;
61+
if (roles.get(messageID) !== "user") continue;
62+
const chunks = texts.get(messageID) ?? [];
63+
if (chunks.length > 0) return chunks.join("\n");
64+
}
65+
return "";
66+
}
67+
68+
export function pruneSession(sessionID: string): void {
69+
const list = sessionMessages.get(sessionID) ?? [];
70+
for (const messageID of list) {
71+
roles.delete(messageID);
72+
texts.delete(messageID);
73+
}
74+
sessionMessages.delete(sessionID);
75+
}

‎.opencode/plugins/memory-worth/index.ts‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createConnection, getDbPath } from "./db/connection.js";
22
import { buildInjectionTexts, detectAndCaptureMemory } from "./hooks/chat-message.js";
3+
import { getSessionUserText, pruneSession, recordMessageInfo, recordPart } from "./hooks/message-events.js";
34
import { buildCompactionContext } from "./hooks/compacting.js";
45
import { handleSessionCreated, handleSessionIdle, handleForgetCommand } from "./hooks/session-events.js";
56
import { resolveSessionOutcome } from "./hooks/tool-execute-after.js";
@@ -57,7 +58,24 @@ const MemoryWorthPlugin = async ({ client, directory }: { client: any; directory
5758
}
5859
if (evt.type === "session.deleted") {
5960
const sessionId = readSessionId(evt.properties);
60-
if (sessionId) injectedSessions.delete(sessionId);
61+
if (sessionId) {
62+
injectedSessions.delete(sessionId);
63+
pruneSession(sessionId);
64+
}
65+
return;
66+
}
67+
if (evt.type === "message.updated") {
68+
const info = (evt.properties as { info?: { id?: unknown; sessionID?: unknown; role?: unknown } } | undefined)?.info;
69+
if (info && typeof info.id === "string" && typeof info.sessionID === "string" && typeof info.role === "string") {
70+
recordMessageInfo({ id: info.id, sessionID: info.sessionID, role: info.role });
71+
}
72+
return;
73+
}
74+
if (evt.type === "message.part.updated") {
75+
const part = (evt.properties as { part?: { id?: unknown; sessionID?: unknown; messageID?: unknown; type?: unknown; text?: unknown; synthetic?: unknown; ignored?: unknown } } | undefined)?.part;
76+
if (part && typeof part.messageID === "string" && typeof part.sessionID === "string" && typeof part.type === "string") {
77+
recordPart({ id: typeof part.id === "string" ? part.id : "", sessionID: part.sessionID, messageID: part.messageID, type: part.type, text: typeof part.text === "string" ? part.text : undefined, synthetic: part.synthetic === true, ignored: part.ignored === true });
78+
}
6179
return;
6280
}
6381
if (evt.type === "session.idle") {
@@ -75,12 +93,9 @@ const MemoryWorthPlugin = async ({ client, directory }: { client: any; directory
7593
const sessionId = input.sessionID;
7694
if (!sessionId) return;
7795
const isFirst = !injectedSessions.has(sessionId);
78-
// The digest retrieves against the user's own words, so the request text
79-
// has to reach buildInjectionTexts rather than a fixed placeholder.
80-
const userText = (output.parts ?? [])
81-
.filter((p: any) => p?.type === "text" && typeof p.text === "string")
82-
.map((p: any) => p.text)
83-
.join("\n");
96+
// Upstream anomalyco/opencode#22831: output.parts is always empty live,
97+
// so user text comes from bus-accumulated message parts instead.
98+
const userText = getSessionUserText(sessionId);
8499

85100
// Handle "forget that rule" command first
86101
const forgot = await handleForgetCommand(db, sessionId, userText);

0 commit comments

Comments
 (0)