Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix: address OpenCode Bugbot findings

Cursor Agent0c6323ff5ce6
diff --git a/cli/beacon-hooks/internal/logging/endpoint_event_test.go b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
index daa726ab..066fbfc8 100644
--- a/cli/beacon-hooks/internal/logging/endpoint_event_test.go
+++ b/cli/beacon-hooks/internal/logging/endpoint_event_test.go
@@ -50,6 +50,7 @@ func TestEndpointEventCompactsOversizedRetainedContent(t *testing.T) {
large[i] = strings.Repeat("x", 4096)
}
fields := map[string]interface{}{
+ "extra": large,
"session": map[string]interface{}{"id": "ses_large"},
"gen_ai": map[string]interface{}{
"tool": map[string]interface{}{
diff --git a/cli/beacon-hooks/internal/logging/logging.go b/cli/beacon-hooks/internal/logging/logging.go
index 1a9eab06..b47920d2 100644
--- a/cli/beacon-hooks/internal/logging/logging.go
+++ b/cli/beacon-hooks/internal/logging/logging.go
@@ -238,7 +238,14 @@ func writeEndpointJSON(path string, event map[string]interface{}) error {
}
}
if len(data) > 64*1024 {
- return fmt.Errorf("endpoint event exceeds 64 KiB after content compaction")
+ event = minimalEndpointEvent(event)
+ data, err = json.Marshal(sanitizeEndpointMap(event))
+ if err != nil {
+ return err
+ }
+ }
+ if len(data) > 64*1024 {
+ return fmt.Errorf("endpoint event exceeds 64 KiB after metadata fallback")
}
return appendEndpointJSONL(path, append(data, '\n'), defaultEndpointRotateBytes, defaultEndpointRotateArchives)
}
@@ -266,6 +273,41 @@ func compactEndpointContent(event map[string]interface{}) {
}
}
+func minimalEndpointEvent(event map[string]interface{}) map[string]interface{} {
+ out := map[string]interface{}{"field_truncated": true}
+ for _, key := range []string{
+ "timestamp", "vendor", "product", "schema_version", "event", "severity",
+ "endpoint", "user", "harness", "origin", "run", "session", "trace",
+ "error", "tool", "file", "command", "mcp", "approval", "policy",
+ "content", "destination", "health", "model", "repository",
+ "branch", "message",
+ } {
+ if value, ok := event[key]; ok && value != nil {
+ out[key] = value
+ }
+ }
+ if genAI, ok := event["gen_ai"].(map[string]interface{}); ok {
+ summary := map[string]interface{}{}
+ for _, key := range []string{"operation", "usage", "response", "provider"} {
+ if value := genAI[key]; value != nil {
+ summary[key] = value
+ }
+ }
+ if tool, ok := genAI["tool"].(map[string]interface{}); ok {
+ toolSummary := map[string]interface{}{"name": tool["name"], "type": tool["type"]}
+ if call, ok := tool["call"].(map[string]interface{}); ok {
+ toolSummary["call"] = map[string]interface{}{"id": call["id"]}
+ }
+ summary["tool"] = toolSummary
+ }
+ if len(summary) > 0 {
+ out["gen_ai"] = summary
+ }
+ }
+ out["message"] = truncateEndpoint(fmt.Sprint(out["message"]), 1024)
+ return out
+}
+
func endpointLogPath() string {
if path := firstEnv("BEACON_ENDPOINT_LOG", "BEACON_CLOUD_LOG_PATH", "BEACON_LOG_PATH", "BEACON_RUNTIME_LOG"); path != "" {
return path
diff --git a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
index da6593f4..260d0912 100644
--- a/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
+++ b/cli/beacon/internal/endpoint/hooks/assets/opencode/beacon.ts
@@ -68,6 +68,7 @@ async function sendToBeacon(client, payload) {
])
if ("timeout" in outcome) {
proc.kill()
+ await Promise.race([proc.exited.catch(() => undefined), Bun.sleep(250)])
await debugLog(client, "Beacon hook command timed out", { type: payload?.type })
return
}
@@ -122,7 +123,8 @@ function shellMutationPaths(tool, args) {
if (name !== "bash" && !name.includes("shell")) return []
const command = String(args?.command || args?.cmd || "")
const paths = []
- const pattern = /\b(?:rm|unlink)\s+(?:-[^\s]+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))/g
+ const pattern =
+ /(?:^|(?:&&|\|\||;|\n)\s*)(?:sudo\s+)?(?:command\s+)?(?:\/bin\/)?(?:rm|unlink)\s+(?:-[^\s]+\s+)*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/g
for (const match of command.matchAll(pattern)) {
const path = match[1] || match[2] || match[3]
if (path) paths.push(path)
@@ -133,12 +135,13 @@ function shellMutationPaths(tool, args) {
export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {
const context = { project, directory, worktree }
const activeCalls = new Map()
- const completedCalls = new Set()
+ const completedCalls = new Map()
const emittedParts = new Set()
const pendingParts = new Map()
const partDeltas = new Map()
const messageModels = new Map()
const messageRoles = new Map()
+ const messageSessions = new Map()
const completedMessages = new Set()
const permissionRequests = new Map()
const sessionStates = new Map()
@@ -204,10 +207,40 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
emitPart(part, sid, item.model)
}
}
+ const flushMessageParts = (messageID, sid, model, completedAt) => {
+ for (const [key, item] of pendingParts) {
+ if (item.part?.messageID !== messageID) continue
+ const part = { ...item.part, time: { ...(item.part.time || {}), end: completedAt || Date.now() } }
+ pendingParts.delete(key)
+ emitPart(part, sid, model || item.model)
+ }
+ }
+ const cleanupSession = (sid) => {
+ for (const [callID, item] of activeCalls) if (item.session_id === sid) activeCalls.delete(callID)
+ for (const [callID, session] of completedCalls) if (session === sid) completedCalls.delete(callID)
+ for (const key of emittedParts) if (key.startsWith(`${sid}:`)) emittedParts.delete(key)
+ for (const [key, item] of pendingParts) if (item.session_id === sid) pendingParts.delete(key)
+ for (const key of partDeltas.keys()) if (key.startsWith(`${sid}:`)) partDeltas.delete(key)
+ for (const [messageID, session] of messageSessions) {
+ if (session !== sid) continue
+ messageSessions.delete(messageID)
+ messageModels.delete(messageID)
+ messageRoles.delete(messageID)
+ completedMessages.delete(messageID)
+ }
+ for (const [requestID, request] of permissionRequests) {
+ if (request.sessionID === sid) permissionRequests.delete(requestID)
+ }
+ sessionStates.delete(sid)
+ for (const [path, item] of recentFilePaths) if (item.sessionID === sid) recentFilePaths.delete(path)
+ }
return {
"chat.message": async (input, output) => {
- if (output?.message?.id) messageRoles.set(output.message.id, "user")
+ if (output?.message?.id) {
+ messageRoles.set(output.message.id, "user")
+ messageSessions.set(output.message.id, sessionID(input))
+ }
await enqueue({
type: "chat.message",
session_id: sessionID(input),
@@ -261,7 +294,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
}),
)
activeCalls.delete(input?.callID)
- completedCalls.add(input?.callID)
+ completedCalls.set(input?.callID, sessionID(input))
},
event: async ({ event }) => {
const type = event?.type || "event"
@@ -271,11 +304,15 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const sid = sessionID(properties)
const info = properties?.info || {}
if (type === "message.updated") {
- if (info?.id && info?.role) messageRoles.set(info.id, info.role)
+ if (info?.id) {
+ if (info?.role) messageRoles.set(info.id, info.role)
+ messageSessions.set(info.id, sid)
+ }
if (info?.role !== "assistant") return
const model = modelName(info)
if (info?.id && model) messageModels.set(info.id, model)
if (!info?.time?.completed && !info?.error) return
+ flushMessageParts(info.id, sid, model, info?.time?.completed)
if (info?.id) {
if (completedMessages.has(info.id)) return
completedMessages.add(info.id)
@@ -302,9 +339,14 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
if (sessionStates.get(sid) === "idle") return
sessionStates.set(sid, "idle")
}
+ if (type === "session.deleted") flushParts(sid)
if (type === "permission.asked" || type === "permission.v2.asked") {
if (properties?.id) {
- permissionRequests.set(properties.id, { tool: properties?.tool, permission: properties?.permission })
+ permissionRequests.set(properties.id, {
+ tool: properties?.tool,
+ permission: properties?.permission,
+ sessionID: sid,
+ })
}
}
if (type === "permission.replied" || type === "permission.v2.replied") {
@@ -331,14 +373,15 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
if (seen && Date.now() - seen.time < 5000) return
if (!sid) return
}
- void enqueue(
+ const queued = enqueue(
payload(type, {
session_id: sessionID(properties) || sid,
- model: modelName(info || properties),
+ model: modelName(Object.keys(info).length > 0 ? info : properties),
properties,
event,
}),
)
+ if (type === "session.deleted") void queued.finally(() => cleanupSession(sid))
},
}
}
diff --git a/plugins/opencode-beacon/src/beacon.test.ts b/plugins/opencode-beacon/src/beacon.test.ts
index c6bd1325..d493b262 100644
--- a/plugins/opencode-beacon/src/beacon.test.ts
+++ b/plugins/opencode-beacon/src/beacon.test.ts
@@ -220,4 +220,97 @@ describe("BeaconEndpointPlugin", () => {
file_mutations: [{ path, operation: "delete" }],
})
})
+
+ test("drains completed assistant parts when the message role arrives later", async () => {
+ const hooks = await plugin()
+ await hooks.event!({
+ event: {
+ type: "message.part.updated",
+ properties: {
+ sessionID: "ses_1",
+ part: {
+ id: "prt_late",
+ messageID: "msg_late",
+ sessionID: "ses_1",
+ type: "text",
+ text: "late role",
+ time: { start: 1, end: 2 },
+ },
+ },
+ },
+ } as any)
+ await hooks.event!({
+ event: {
+ type: "message.updated",
+ properties: {
+ sessionID: "ses_1",
+ info: {
+ id: "msg_late",
+ role: "assistant",
+ providerID: "moonshotai",
+ modelID: "kimi-k3",
+ time: { completed: 3 },
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ },
+ },
+ },
+ } as any)
+ await Bun.sleep(20)
+
+ expect(payloads.map((item) => item.type)).toEqual(["message.part.updated", "message.updated"])
+ expect(payloads[0].part.text).toBe("late role")
+ })
+
+ test("cleans session state after deletion", async () => {
+ const hooks = await plugin()
+ const completed = (sessionID: string) => ({
+ event: {
+ type: "message.updated",
+ properties: {
+ sessionID,
+ info: {
+ id: "msg_reused",
+ role: "assistant",
+ providerID: "moonshotai",
+ modelID: "kimi-k3",
+ time: { completed: 2 },
+ tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
+ },
+ },
+ },
+ })
+ await hooks.event!(completed("ses_1") as any)
+ await hooks.event!({ event: { type: "session.deleted", properties: { sessionID: "ses_1" } } } as any)
+ await Bun.sleep(20)
+ await hooks.event!(completed("ses_2") as any)
+ await Bun.sleep(20)
+
+ expect(payloads.map((item) => item.type)).toEqual(["message.updated", "session.deleted", "message.updated"])
+ })
+
+ test("does not infer deletes from quoted rm text and preserves root model metadata", async () => {
+ const hooks = await plugin()
+ await hooks["tool.execute.before"]!(
+ { tool: "bash", sessionID: "ses_1", callID: "call_echo" },
+ { args: { command: "echo rm /tmp/not-deleted" } },
+ )
+ await hooks["tool.execute.after"]!(
+ { tool: "bash", sessionID: "ses_1", callID: "call_echo", args: { command: "echo rm /tmp/not-deleted" } },
+ { title: "echo", output: "rm /tmp/not-deleted", metadata: { exit: 0 } },
+ )
+ await hooks.event!({
+ event: {
+ type: "session.status",
+ properties: {
+ sessionID: "ses_1",
+ status: { type: "busy" },
+ model: { providerID: "moonshotai", modelID: "kimi-k3" },
+ },
+ },
+ } as any)
+ await Bun.sleep(20)
+
+ expect(payloads[1].file_mutations).toEqual([])
+ expect(payloads[2].model).toBe("moonshotai/kimi-k3")
+ })
})
diff --git a/plugins/opencode-beacon/src/beacon.ts b/plugins/opencode-beacon/src/beacon.ts
index da6593f4..260d0912 100644
--- a/plugins/opencode-beacon/src/beacon.ts
+++ b/plugins/opencode-beacon/src/beacon.ts
@@ -68,6 +68,7 @@ async function sendToBeacon(client, payload) {
])
if ("timeout" in outcome) {
proc.kill()
+ await Promise.race([proc.exited.catch(() => undefined), Bun.sleep(250)])
await debugLog(client, "Beacon hook command timed out", { type: payload?.type })
return
}
@@ -122,7 +123,8 @@ function shellMutationPaths(tool, args) {
if (name !== "bash" && !name.includes("shell")) return []
const command = String(args?.command || args?.cmd || "")
const paths = []
- const pattern = /\b(?:rm|unlink)\s+(?:-[^\s]+\s+)*(?:"([^"]+)"|'([^']+)'|(\S+))/g
+ const pattern =
+ /(?:^|(?:&&|\|\||;|\n)\s*)(?:sudo\s+)?(?:command\s+)?(?:\/bin\/)?(?:rm|unlink)\s+(?:-[^\s]+\s+)*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/g
for (const match of command.matchAll(pattern)) {
const path = match[1] || match[2] || match[3]
if (path) paths.push(path)
@@ -133,12 +135,13 @@ function shellMutationPaths(tool, args) {
export const BeaconEndpointPlugin = async ({ project, directory, worktree, client }) => {
const context = { project, directory, worktree }
const activeCalls = new Map()
- const completedCalls = new Set()
+ const completedCalls = new Map()
const emittedParts = new Set()
const pendingParts = new Map()
const partDeltas = new Map()
const messageModels = new Map()
const messageRoles = new Map()
+ const messageSessions = new Map()
const completedMessages = new Set()
const permissionRequests = new Map()
const sessionStates = new Map()
@@ -204,10 +207,40 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
emitPart(part, sid, item.model)
}
}
+ const flushMessageParts = (messageID, sid, model, completedAt) => {
+ for (const [key, item] of pendingParts) {
+ if (item.part?.messageID !== messageID) continue
+ const part = { ...item.part, time: { ...(item.part.time || {}), end: completedAt || Date.now() } }
+ pendingParts.delete(key)
+ emitPart(part, sid, model || item.model)
+ }
+ }
+ const cleanupSession = (sid) => {
+ for (const [callID, item] of activeCalls) if (item.session_id === sid) activeCalls.delete(callID)
+ for (const [callID, session] of completedCalls) if (session === sid) completedCalls.delete(callID)
+ for (const key of emittedParts) if (key.startsWith(`${sid}:`)) emittedParts.delete(key)
+ for (const [key, item] of pendingParts) if (item.session_id === sid) pendingParts.delete(key)
+ for (const key of partDeltas.keys()) if (key.startsWith(`${sid}:`)) partDeltas.delete(key)
+ for (const [messageID, session] of messageSessions) {
+ if (session !== sid) continue
+ messageSessions.delete(messageID)
+ messageModels.delete(messageID)
+ messageRoles.delete(messageID)
+ completedMessages.delete(messageID)
+ }
+ for (const [requestID, request] of permissionRequests) {
+ if (request.sessionID === sid) permissionRequests.delete(requestID)
+ }
+ sessionStates.delete(sid)
+ for (const [path, item] of recentFilePaths) if (item.sessionID === sid) recentFilePaths.delete(path)
+ }
return {
"chat.message": async (input, output) => {
- if (output?.message?.id) messageRoles.set(output.message.id, "user")
+ if (output?.message?.id) {
+ messageRoles.set(output.message.id, "user")
+ messageSessions.set(output.message.id, sessionID(input))
+ }
await enqueue({
type: "chat.message",
session_id: sessionID(input),
@@ -261,7 +294,7 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
}),
)
activeCalls.delete(input?.callID)
- completedCalls.add(input?.callID)
+ completedCalls.set(input?.callID, sessionID(input))
},
event: async ({ event }) => {
const type = event?.type || "event"
@@ -271,11 +304,15 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
const sid = sessionID(properties)
const info = properties?.info || {}
if (type === "message.updated") {
- if (info?.id && info?.role) messageRoles.set(info.id, info.role)
+ if (info?.id) {
+ if (info?.role) messageRoles.set(info.id, info.role)
+ messageSessions.set(info.id, sid)
+ }
if (info?.role !== "assistant") return
const model = modelName(info)
if (info?.id && model) messageModels.set(info.id, model)
if (!info?.time?.completed && !info?.error) return
+ flushMessageParts(info.id, sid, model, info?.time?.completed)
if (info?.id) {
if (completedMessages.has(info.id)) return
completedMessages.add(info.id)
@@ -302,9 +339,14 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
if (sessionStates.get(sid) === "idle") return
sessionStates.set(sid, "idle")
}
+ if (type === "session.deleted") flushParts(sid)
if (type === "permission.asked" || type === "permission.v2.asked") {
if (properties?.id) {
- permissionRequests.set(properties.id, { tool: properties?.tool, permission: properties?.permission })
+ permissionRequests.set(properties.id, {
+ tool: properties?.tool,
+ permission: properties?.permission,
+ sessionID: sid,
+ })
}
}
if (type === "permission.replied" || type === "permission.v2.replied") {
@@ -331,14 +373,15 @@ export const BeaconEndpointPlugin = async ({ project, directory, worktree, clien
if (seen && Date.now() - seen.time < 5000) return
if (!sid) return
}
- void enqueue(
+ const queued = enqueue(
payload(type, {
session_id: sessionID(properties) || sid,
- model: modelName(info || properties),
+ model: modelName(Object.keys(info).length > 0 ? info : properties),
properties,
event,
}),
)
+ if (type === "session.deleted") void queued.finally(() => cleanupSession(sid))
},
}
}