From 4a573a8da97332ae8c0f125a856e17ea2428c0ed Mon Sep 17 00:00:00 2001 From: Dhravya Date: Sat, 7 Nov 2026 02:43:08 +0000 Subject: [PATCH 1/5] feat: skip Supermemory for subagents, headless runs and helper prompts by default Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 7 ++ README.md | 63 ++++++++++++++- bunfig.toml | 2 + scripts/test-preload.mjs | 10 +++ src/config.ts | 42 ++++++++++ src/index.ts | 39 +++++++++ src/services/capture.ts | 30 ++++++- src/services/local-dedupe.test.ts | 49 ++++++++++++ src/services/local-dedupe.ts | 121 ++++++++++++++++++++++++++++ src/services/recall.ts | 4 +- src/services/session-scope.test.ts | 71 +++++++++++++++++ src/services/session-scope.ts | 124 +++++++++++++++++++++++++++++ src/services/tags.ts | 50 +++++++++++- src/v2/runtime.test.ts | 39 +++++++++ src/v2/runtime.ts | 52 +++++++++++- 15 files changed, 693 insertions(+), 10 deletions(-) create mode 100644 bunfig.toml create mode 100644 scripts/test-preload.mjs create mode 100644 src/services/local-dedupe.test.ts create mode 100644 src/services/local-dedupe.ts create mode 100644 src/services/session-scope.test.ts create mode 100644 src/services/session-scope.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ff5087e..f73778a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## Unreleased + +- Skip automatic recall, capture and compaction memory for subagent sessions (any session with a `parentID`) and, on OpenCode V1, for `opencode run` / `opencode github run`. Opt back in with `captureSubagents` / `captureHeadless` or `SUPERMEMORY_CAPTURE_SUBAGENTS=true` / `SUPERMEMORY_CAPTURE_HEADLESS=true`. +- Treat Conductor and Vibe Kanban sessions as interactive; `captureOrchestrated: false` skips them. +- Replace an opening prompt already captured from this machine for the same container with a one-line marker (`dedupeOpeningPrompt`), and skip recall for exact query repeats within 10 minutes (`dedupeRecallQueries`). +- Linked worktrees of a bare repository without an origin remote now share the bare repository's container instead of getting one per worktree. + ## 2.1.2 - Keep `login` waiting for the callback when no browser can be opened, and print the URL to open instead of failing (#72). diff --git a/README.md b/README.md index b18e38d..0b63e7b 100644 --- a/README.md +++ b/README.md @@ -175,6 +175,45 @@ Completed conversations are captured automatically: - Synthetic plugin context is excluded and `` content is redacted. - Stable capture IDs retain batch identity across repeated lifecycle events; they do not guarantee exactly-once processing or billing after an ambiguous response. +### Sessions without automatic memory + +Automatic recall, capture and compaction memory run only for sessions you drive yourself. +By default the plugin makes no Supermemory calls from its hooks for: + +- **Subagent sessions.** Any session with a `parentID`, which OpenCode sets on child sessions + spawned by the `task` (V1) or `subagent` (OpenCode 2) tool. Set `captureSubagents: true` or + `SUPERMEMORY_CAPTURE_SUBAGENTS=true` to restore recall and capture for them. +- **Headless runs (OpenCode V1).** `opencode run` and `opencode github run`, which host the + server and plugins in the CLI process. Set `captureHeadless: true` or + `SUPERMEMORY_CAPTURE_HEADLESS=true` to restore them. OpenCode 2 gives plugins no signal for + `opencode run` (it may share the background server with interactive sessions), so headless + OpenCode 2 runs are still treated as interactive. `opencode run --attach` on V1 is the same. + +OpenCode's title generation never reaches the plugin's hooks, so it makes no Supermemory calls. +Compaction only runs [Compaction Memory](#compaction-memory) for the session being summarised, +which is skipped for subagent and headless sessions like everything else. + +Sessions started by Conductor (`CONDUCTOR_WORKSPACE_PATH`, `CONDUCTOR_SESSION_ID`) or Vibe Kanban +(`VK_WORKSPACE_ID`) are real user work and always count as interactive, even through +`opencode run`. Set `captureOrchestrated: false` or `SUPERMEMORY_CAPTURE_ORCHESTRATED=false` to +skip them. Orchestrators without an environment variable (Crystal, Claude Squad) are not +recognised. On OpenCode 2 the variables are read from the server process, so they only apply +when it was started from the orchestrator's environment (for example `--standalone` or `run` +without a background service). + +### Repeated prompts + +Swarms of one-shot workers often send the same task prompt many times. Two small local +indexes under `~/.supermemory-opencode/` keep those repeats from being re-sent: + +- **Opening prompt** (`dedupeOpeningPrompt`, default `true`). When a session's first prompt + matches one this machine already captured for the same container tag, the capture is sent + with a one-line `[Opening prompt omitted: ...]` marker in its place. The rest of the + conversation is captured as usual. Set `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` to opt out. +- **Recall query** (`dedupeRecallQueries`, default `true`). Direct recall is skipped when the + exact same normalized query was already searched against the same container tag in the last + 10 minutes. Set `SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to opt out. + ### Keyword Detection Say "remember", "save this", "don't forget" etc. and the agent auto-saves to memory. @@ -287,7 +326,9 @@ shared repository container. The repository hash comes from the normalized Git `origin` remote, so Claude Code, Codex, Cursor, and OpenCode use the same container for the same repository. Repositories with the same name but different remotes remain isolated. Without an -origin remote, OpenCode falls back to the repository's real filesystem path. +origin remote, OpenCode falls back to the repository's real filesystem path. Linked Git +worktrees (including worktrees of a bare repository) use the main repository's path, so +parallel worktrees share one container. OpenCode also reads previous `user_project_*`, `repo_`, `claudecode_project_*`, `codex_user_*`, `codex_project_*`, `opencode_user_*`, @@ -309,6 +350,11 @@ does not require a migration. | `SUPERMEMORY_REPO_TAG` | Explicit project-container override, checked before the config value. | | `SUPERMEMORY_ISOLATE_WORKTREES` | Set to `true` to key the project container on the worktree path instead of the Git remote. | | `SUPERMEMORY_DEBUG` | Set to show `[recall-decision]` lines and enable debug logging. | +| `SUPERMEMORY_CAPTURE_SUBAGENTS` | `true` restores recall and capture for subagent sessions (overrides `captureSubagents`). | +| `SUPERMEMORY_CAPTURE_HEADLESS` | `true` restores recall and capture for `opencode run` (overrides `captureHeadless`). | +| `SUPERMEMORY_CAPTURE_ORCHESTRATED` | `false` skips sessions started by Conductor or Vibe Kanban (overrides `captureOrchestrated`). | +| `SUPERMEMORY_DEDUPE_OPENING_PROMPT` | `false` always sends repeated opening prompts (overrides `dedupeOpeningPrompt`). | +| `SUPERMEMORY_DEDUPE_RECALL_QUERIES` | `false` always runs recall for repeated queries (overrides `dedupeRecallQueries`). | ### `~/.config/opencode/supermemory.jsonc` @@ -390,6 +436,21 @@ scope, not from a different or malformed response. // Override the directive used in advisory mode "recallDirective": null, + + // Recall and capture subagent (child) sessions too + "captureSubagents": false, + + // OpenCode V1: recall and capture `opencode run` / `opencode github run` too + "captureHeadless": false, + + // Recall and capture sessions started by Conductor or Vibe Kanban + "captureOrchestrated": true, + + // Replace an opening prompt already captured from this machine with a marker + "dedupeOpeningPrompt": true, + + // Skip recall for an exact repeat of a query made in the last 10 minutes + "dedupeRecallQueries": true, } ``` diff --git a/bunfig.toml b/bunfig.toml new file mode 100644 index 0000000..8962bbb --- /dev/null +++ b/bunfig.toml @@ -0,0 +1,2 @@ +[test] +preload = ["./scripts/test-preload.mjs"] diff --git a/scripts/test-preload.mjs b/scripts/test-preload.mjs new file mode 100644 index 0000000..ba32c00 --- /dev/null +++ b/scripts/test-preload.mjs @@ -0,0 +1,10 @@ +import { mock } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import os from "node:os"; +import { join } from "node:path"; + +// Keep tests away from the developer's Supermemory config and local dedupe state. +const home = mkdtempSync(join(os.tmpdir(), "opencode-supermemory-test-")); +const homedir = () => home; +mock.module("node:os", () => ({ ...os, default: { ...os, homedir }, homedir })); +mock.module("os", () => ({ ...os, default: { ...os, homedir }, homedir })); diff --git a/src/config.ts b/src/config.ts index 9edc348..24071ad 100644 --- a/src/config.ts +++ b/src/config.ts @@ -43,6 +43,11 @@ interface SupermemoryConfig { captureEveryNTurns?: number; recallDirective?: string | null; recallMode?: RecallMode; + captureSubagents?: boolean; + captureHeadless?: boolean; + captureOrchestrated?: boolean; + dedupeOpeningPrompt?: boolean; + dedupeRecallQueries?: boolean; } const DEFAULT_KEYWORD_PATTERNS = [ @@ -77,6 +82,11 @@ const DEFAULTS: Required { const injectedSessions = new Set(); const recallSessions = new RecallSessionCache(); const activity = createMemoryActivityReporter(ctx.client); + const scope = new SessionScope({ + headless: isHeadlessCommand(), + lookupParent: async (id) => { + const response = await ctx.client.session.get({ path: { id } }); + if (!response.data) throw new Error(`Unable to read OpenCode session ${id}`); + return response.data.parentID; + }, + }); + const recallQueries = CONFIG.dedupeRecallQueries ? new RecallQueryIndex() : null; log("Plugin init", { directory, tags, configured: isConfigured() }); if (!isConfigured()) { @@ -130,6 +157,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { return { "chat.message": async (input, output) => { if (!isConfigured()) return; + if (await scope.skipReason(input.sessionID)) return; const start = Date.now(); @@ -215,6 +243,9 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { : [], ) : undefined, + skipQuery: recallQueries + ? (query) => recallQueries.isRepeat(tags.canonical, query) + : undefined, }) : Promise.resolve({ context: "", @@ -359,6 +390,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { event: async (input: { event: { type: string; properties?: unknown } }) => { const props = input.event.properties as Record | undefined; + if (input.event.type === "session.created" || input.event.type === "session.updated") { + const info = props?.info as { id?: string; parentID?: string } | undefined; + scope.note(info?.id, info?.parentID); + } if (input.event.type === "session.deleted") { const sessionID = (props?.info as { id?: string } | undefined)?.id; if (sessionID) { @@ -371,6 +406,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { } if (!isConfigured()) return; + const sessionID = eventSessionID(input.event); + const skip = sessionID ? await scope.skipReason(sessionID) : scope.processSkipReason; + if (sessionID && input.event.type === "session.deleted") scope.forget(sessionID); + if (skip) return; if (compactionHook) { await compactionHook.event(input); } diff --git a/src/services/capture.ts b/src/services/capture.ts index aaa2af4..11bc620 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -5,6 +5,7 @@ import { CONFIG } from "../config.js"; import type { ConversationMessage } from "../types/index.js"; import { supermemoryClient } from "./client.js"; import { AGENT_ENTITY_CONTEXT } from "./entity-context.js"; +import { OpeningPromptIndex } from "./local-dedupe.js"; import { log } from "./logger.js"; import { isFullyPrivate, stripPrivateContent } from "./privacy.js"; import type { ResolvedTags } from "./tags.js"; @@ -67,6 +68,23 @@ export interface CaptureOptions { captureEveryNTurns?: number; memoryClient?: ConversationWriter; onSaved?: () => void; + openingPrompts?: OpeningPromptIndex | null; +} + +export function defaultOpeningPromptIndex(): OpeningPromptIndex | null { + return CONFIG.dedupeOpeningPrompt ? new OpeningPromptIndex() : null; +} + +/** Replaces an opening prompt this machine already captured for the tag with a marker. */ +export function prepareCaptureMessages( + index: OpeningPromptIndex | null, + containerTag: string, + sessionID: string, + batch: CaptureBatch, +): { messages: ConversationMessage[]; commit: () => void } { + const messages = batch.turns.flatMap((turn) => turn.messages); + if (!index || batch.startTurn !== 1) return { messages, commit: () => {} }; + return index.prepare(containerTag, sessionID, messages); } function extractText(parts: Part[] | undefined): string { @@ -217,6 +235,10 @@ export function createCaptureHook( const captureEveryNTurns = options?.captureEveryNTurns ?? CONFIG.captureEveryNTurns; const memoryClient = options?.memoryClient ?? supermemoryClient; + const openingPrompts = + options?.openingPrompts !== undefined + ? options.openingPrompts + : defaultOpeningPromptIndex(); const snapshots = new Map(); const activeSessions = new Set(); const completedCaptureIds = new Set(); @@ -245,7 +267,12 @@ export function createCaptureHook( const captureId = getCaptureId(sessionID, batch); if (completedCaptureIds.has(captureId)) return true; - const messages = batch.turns.flatMap((turn) => turn.messages); + const { messages, commit } = prepareCaptureMessages( + openingPrompts, + tags.canonical, + sessionID, + batch, + ); if (messages.length === 0) { completedCaptureIds.add(captureId); return true; @@ -282,6 +309,7 @@ export function createCaptureHook( if (result.success) { completedCaptureIds.add(captureId); + commit(); options?.onSaved?.(); log("[capture] conversation batch saved", { sessionID, diff --git a/src/services/local-dedupe.test.ts b/src/services/local-dedupe.test.ts new file mode 100644 index 0000000..da0f3d2 --- /dev/null +++ b/src/services/local-dedupe.test.ts @@ -0,0 +1,49 @@ +import { describe, expect, test } from "bun:test"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { OpeningPromptIndex, RecallQueryIndex } from "./local-dedupe.js"; + +function tempFile(name: string): string { + return join(mkdtempSync(join(tmpdir(), "supermemory-dedupe-")), name); +} + +describe("local dedupe indexes", () => { + test("sends an opening prompt once per container tag and keeps the owner session intact", () => { + const index = new OpeningPromptIndex(tempFile("opening.json")); + const batch = [ + { role: "user" as const, content: "Run the nightly migration task" }, + { role: "assistant" as const, content: "Done." }, + ]; + + const first = index.prepare("repo_a", "worker-1", batch); + expect(first.messages).toEqual(batch); + first.commit(); + + expect(index.prepare("repo_a", "worker-1", batch).messages).toEqual(batch); + const repeat = index.prepare("repo_a", "worker-2", [ + { role: "user", content: "Run the nightly migration task" }, + { role: "assistant", content: "Done again." }, + ]); + expect(repeat.messages[0]?.content).toMatch(/^\[Opening prompt omitted: .*sha256:[0-9a-f]{12}\)\]$/); + expect(repeat.messages[1]).toEqual({ role: "assistant", content: "Done again." }); + expect(index.prepare("repo_b", "worker-3", batch).messages).toEqual(batch); + }); + + test("an uncommitted capture does not mark the prompt as sent", () => { + const index = new OpeningPromptIndex(tempFile("opening.json")); + const batch = [{ role: "user" as const, content: "same task" }]; + index.prepare("repo_a", "worker-1", batch); + expect(index.prepare("repo_a", "worker-2", batch).messages).toEqual(batch); + }); + + test("skips exact recall query repeats per tag within the window", () => { + const index = new RecallQueryIndex(tempFile("recall.json"), 1_000); + expect(index.isRepeat("repo_a", "How do we deploy?", 0)).toBe(false); + expect(index.isRepeat("repo_a", "how do we deploy?", 500)).toBe(true); + expect(index.isRepeat("repo_b", "How do we deploy?", 500)).toBe(false); + expect(index.isRepeat("repo_a", "How do we deploy to prod?", 500)).toBe(false); + expect(index.isRepeat("repo_a", "How do we deploy?", 1_500)).toBe(false); + }); +}); diff --git a/src/services/local-dedupe.ts b/src/services/local-dedupe.ts new file mode 100644 index 0000000..7c8d00f --- /dev/null +++ b/src/services/local-dedupe.ts @@ -0,0 +1,121 @@ +import { createHash, randomBytes } from "node:crypto"; +import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; + +import type { ConversationMessage } from "../types/index.js"; + +const STATE_DIR = join(homedir(), ".supermemory-opencode"); +export const OPENING_PROMPTS_FILE = join(STATE_DIR, "opening-prompts.json"); +export const RECALL_QUERIES_FILE = join(STATE_DIR, "recall-queries.json"); +const MAX_OPENING_PROMPTS = 1_000; +const MAX_RECALL_QUERIES = 500; +export const RECALL_REPEAT_WINDOW_MS = 10 * 60 * 1000; + +type Entries = Record; + +function sha256(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} + +function readEntries(file: string): Entries { + try { + const parsed = JSON.parse(readFileSync(file, "utf-8")) as unknown; + return parsed && typeof parsed === "object" && !Array.isArray(parsed) + ? (parsed as Entries) + : {}; + } catch { + return {}; + } +} + +function writeEntries(file: string, entries: Entries): void { + mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); + const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; + writeFileSync(temporary, JSON.stringify(entries), { mode: 0o600 }); + renameSync(temporary, file); +} + +function newest(entries: Entries, limit: number, at: (value: T) => number): Entries { + return Object.fromEntries( + Object.entries(entries) + .sort(([, left], [, right]) => at(right) - at(left)) + .slice(0, limit), + ); +} + +/** + * Remembers which session first captured each opening prompt per container tag, + * so repeated one-shot workers do not re-send the same task prompt. + */ +export class OpeningPromptIndex { + constructor(private readonly file = OPENING_PROMPTS_FILE) {} + + /** Returns the batch to send and a commit to call once the capture is accepted. */ + prepare( + containerTag: string, + sessionID: string, + messages: ConversationMessage[], + ): { messages: ConversationMessage[]; commit: () => void } { + const unchanged = { messages, commit: () => {} }; + const opening = messages[0]; + if (opening?.role !== "user" || typeof opening.content !== "string" || !opening.content.trim()) { + return unchanged; + } + + try { + const hash = sha256(`${containerTag}\n${opening.content.replace(/\s+/g, " ").trim()}`); + const owner = readEntries<{ sessionId: string; at: number }>(this.file)[hash]; + if (owner && owner.sessionId !== sessionID) { + return { + messages: [ + { + role: "user", + content: `[Opening prompt omitted: identical to one already captured from this machine (sha256:${hash.slice(0, 12)})]`, + }, + ...messages.slice(1), + ], + commit: () => {}, + }; + } + if (owner) return unchanged; + return { + messages, + commit: () => { + try { + const entries = readEntries<{ sessionId: string; at: number }>(this.file); + entries[hash] ??= { sessionId: sessionID, at: Date.now() }; + writeEntries(this.file, newest(entries, MAX_OPENING_PROMPTS, (entry) => entry.at)); + } catch {} + }, + }; + } catch { + return unchanged; + } + } +} + +/** Exact repeats of a normalized recall query against one container tag within the window. */ +export class RecallQueryIndex { + constructor( + private readonly file = RECALL_QUERIES_FILE, + private readonly windowMs = RECALL_REPEAT_WINDOW_MS, + ) {} + + isRepeat(containerTag: string, query: string, now = Date.now()): boolean { + try { + const hash = sha256(`${containerTag}\n${query.toLowerCase().replace(/\s+/g, " ").trim()}`); + const entries = Object.fromEntries( + Object.entries(readEntries(this.file)).filter( + ([, at]) => typeof at === "number" && now - at < this.windowMs, + ), + ); + if (entries[hash] !== undefined) return true; + entries[hash] = now; + writeEntries(this.file, newest(entries, MAX_RECALL_QUERIES, (at) => at)); + return false; + } catch { + return false; + } + } +} diff --git a/src/services/recall.ts b/src/services/recall.ts index 37ec1f6..ec0f02a 100644 --- a/src/services/recall.ts +++ b/src/services/recall.ts @@ -136,9 +136,11 @@ export async function buildDirectRecallResult(options: { cache: RecallSessionCache; search: (query: string) => Promise; suppressTexts?: Iterable | Promise>; + skipQuery?: (query: string) => boolean; }): Promise { try { - const query = prepareRecallQuery(options.prompt); + const prepared = prepareRecallQuery(options.prompt); + const query = prepared && options.skipQuery?.(prepared) ? null : prepared; // Begin the search before waiting for first-turn profile suppression. Both // reads have the same timeout, so a cold prompt pays one network window. const searchPromise = query diff --git a/src/services/session-scope.test.ts b/src/services/session-scope.test.ts new file mode 100644 index 0000000..7f62964 --- /dev/null +++ b/src/services/session-scope.test.ts @@ -0,0 +1,71 @@ +import { describe, expect, test } from "bun:test"; + +import { + getProcessSkipReason, + isHeadlessCommand, + SessionScope, + type SessionScopeConfig, +} from "./session-scope.js"; + +const defaults: SessionScopeConfig = { + captureSubagents: false, + captureHeadless: false, + captureOrchestrated: true, +}; + +describe("session scope", () => { + test("detects OpenCode V1 headless commands from the host argv", () => { + const argv = (...args: string[]) => ["bun", "/$bunfs/root/opencode", ...args]; + expect(isHeadlessCommand(argv("run", "fix the bug"))).toBe(true); + expect(isHeadlessCommand(argv("--log-level", "INFO", "run", "hi"))).toBe(true); + expect(isHeadlessCommand(argv("--print-logs", "run"))).toBe(true); + expect(isHeadlessCommand(argv("github", "run"))).toBe(true); + expect(isHeadlessCommand(argv())).toBe(false); + expect(isHeadlessCommand(argv("./project"))).toBe(false); + expect(isHeadlessCommand(argv("serve"))).toBe(false); + expect(isHeadlessCommand(argv("github", "install"))).toBe(false); + }); + + test("orchestrated sessions count as interactive unless opted out", () => { + const conductor = { CONDUCTOR_WORKSPACE_PATH: "/w/tokyo" }; + expect(getProcessSkipReason({ config: defaults, headless: true, env: {} })).toBe("headless"); + expect(getProcessSkipReason({ config: defaults, headless: true, env: conductor })).toBeNull(); + expect( + getProcessSkipReason({ config: { ...defaults, captureHeadless: true }, headless: true, env: {} }), + ).toBeNull(); + expect( + getProcessSkipReason({ + config: { ...defaults, captureOrchestrated: false }, + headless: false, + env: { VK_WORKSPACE_ID: "ws" }, + }), + ).toBe("orchestrated"); + }); + + test("skips child sessions unless captureSubagents is set", async () => { + const lookups: string[] = []; + const parents: Record = { child: "root" }; + const lookupParent = async (id: string) => { + lookups.push(id); + if (id === "broken") throw new Error("unavailable"); + return parents[id]; + }; + const scope = new SessionScope({ lookupParent, headless: false, config: defaults, env: {} }); + + expect(await scope.skipReason("root")).toBeNull(); + expect(await scope.skipReason("child")).toBe("subagent"); + expect(await scope.skipReason("child")).toBe("subagent"); + scope.note("noted", "root"); + expect(await scope.skipReason("noted")).toBe("subagent"); + expect(await scope.skipReason("broken")).toBeNull(); + expect(lookups).toEqual(["root", "child", "broken"]); + + const optedIn = new SessionScope({ + lookupParent, + headless: true, + config: { ...defaults, captureSubagents: true, captureHeadless: true }, + env: {}, + }); + expect(await optedIn.skipReason("child")).toBeNull(); + }); +}); diff --git a/src/services/session-scope.ts b/src/services/session-scope.ts new file mode 100644 index 0000000..930f6ab --- /dev/null +++ b/src/services/session-scope.ts @@ -0,0 +1,124 @@ +import { CONFIG } from "../config.js"; +import { log } from "./logger.js"; + +export type SessionSkipReason = "subagent" | "headless" | "orchestrated"; + +export type SessionScopeConfig = Pick< + typeof CONFIG, + "captureSubagents" | "captureHeadless" | "captureOrchestrated" +>; + +// Conductor (conductor.build/docs/reference/environment-variables) and Vibe Kanban +// (BloopAI/vibe-kanban crates/local-deployment/src/container.rs) set these for agents they run. +const ORCHESTRATOR_ENV_VARS = [ + "CONDUCTOR_WORKSPACE_PATH", + "CONDUCTOR_SESSION_ID", + "VK_WORKSPACE_ID", +] as const; + +export function isOrchestrated(env: NodeJS.ProcessEnv = process.env): boolean { + return ORCHESTRATOR_ENV_VARS.some((name) => Boolean(env[name]?.trim())); +} + +/** + * OpenCode V1 runs `opencode run` and `opencode github run` with the server and + * plugins in the CLI process (packages/opencode/src/cli/cmd/run.ts, github.ts). + */ +export function isHeadlessCommand(argv: readonly string[] = process.argv): boolean { + const positionals: string[] = []; + const args = argv.slice(2); + for (let index = 0; index < args.length && positionals.length < 2; index += 1) { + const arg = args[index] ?? ""; + if (arg === "--") break; + if (arg === "--log-level") { + index += 1; + continue; + } + if (!arg.startsWith("-")) positionals.push(arg); + } + return ( + positionals[0] === "run" || + (positionals[0] === "github" && positionals[1] === "run") + ); +} + +export function getProcessSkipReason(options: { + config: SessionScopeConfig; + headless: boolean; + env?: NodeJS.ProcessEnv; +}): SessionSkipReason | null { + if (isOrchestrated(options.env)) { + return options.config.captureOrchestrated ? null : "orchestrated"; + } + return options.headless && !options.config.captureHeadless ? "headless" : null; +} + +/** + * Decides whether a session gets automatic recall and capture. Child sessions + * (`parentID` set by the host's task/subagent tool) and headless runs are + * skipped unless the matching opt-in flag is set. + */ +export class SessionScope { + readonly #config: SessionScopeConfig; + readonly #processReason: SessionSkipReason | null; + readonly #lookupParent: (sessionID: string) => Promise; + readonly #children = new Map>(); + readonly #logged = new Set(); + + constructor(options: { + lookupParent: (sessionID: string) => Promise; + headless: boolean; + config?: SessionScopeConfig; + env?: NodeJS.ProcessEnv; + }) { + this.#config = options.config ?? CONFIG; + this.#lookupParent = options.lookupParent; + this.#processReason = getProcessSkipReason({ + config: this.#config, + headless: options.headless, + env: options.env, + }); + if (this.#processReason) { + log("Automatic memory disabled for this process", { reason: this.#processReason }); + } + } + + get processSkipReason(): SessionSkipReason | null { + return this.#processReason; + } + + note(sessionID: string | undefined, parentID: string | undefined): void { + if (sessionID && !this.#children.has(sessionID)) { + this.#children.set(sessionID, Promise.resolve(Boolean(parentID))); + } + } + + forget(sessionID: string): void { + this.#children.delete(sessionID); + this.#logged.delete(sessionID); + } + + async skipReason(sessionID: string): Promise { + if (this.#processReason) return this.#processReason; + if (this.#config.captureSubagents) return null; + + let isChild = this.#children.get(sessionID); + if (!isChild) { + isChild = this.#lookupParent(sessionID).then( + (parentID) => Boolean(parentID), + () => { + this.#children.delete(sessionID); + return false; + }, + ); + this.#children.set(sessionID, isChild); + } + if (!(await isChild)) return null; + + if (!this.#logged.has(sessionID)) { + this.#logged.add(sessionID); + log("Automatic memory skipped for subagent session", { sessionID }); + } + return "subagent"; + } +} diff --git a/src/services/tags.ts b/src/services/tags.ts index e520f10..69011b4 100644 --- a/src/services/tags.ts +++ b/src/services/tags.ts @@ -66,6 +66,45 @@ function getProjectBasePath(directory: string): string { return getGitRoot(directory) || resolve(directory); } +const bareRepositoryCache = new Map(); + +// Linked worktrees of a bare repository have no main checkout, so they share the bare repository's identity. +function getBareRepositoryPath(directory: string): string | null { + if (process.env.SUPERMEMORY_ISOLATE_WORKTREES === "true") return null; + const cached = bareRepositoryCache.get(directory); + if (cached !== undefined) return cached; + let result: string | null = null; + try { + const [commonDir, gitDir] = execSync( + "git rev-parse --path-format=absolute --git-common-dir --git-dir", + { + cwd: directory, + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, + }, + ) + .trim() + .split(/\r?\n/); + if (commonDir && gitDir && commonDir !== gitDir) { + const bare = execSync("git config --bool core.bare", { + cwd: directory, + encoding: "utf-8", + stdio: ["pipe", "pipe", "pipe"], + windowsHide: true, + }).trim(); + if (bare === "true") result = commonDir; + } + } catch {} + bareRepositoryCache.set(directory, result); + return result; +} + +function getBareRepositoryName(bareRepositoryPath: string): string { + const name = basename(bareRepositoryPath).replace(/\.git$/i, ""); + return name && !name.startsWith(".") ? name : basename(dirname(bareRepositoryPath)); +} + function getGitEmail(directory: string): string | null { try { const email = execSync("git config user.email", { @@ -259,9 +298,10 @@ export function getProjectIdentity(directory: string): string { const basePath = getProjectBasePath(directory); const { normalizedRemote } = getGitRepoInfo(basePath); const isolateWorktrees = process.env.SUPERMEMORY_ISOLATE_WORKTREES === "true"; - let localIdentity = basePath; + const localPath = getBareRepositoryPath(basePath) ?? basePath; + let localIdentity = localPath; try { - localIdentity = realpathSync.native(basePath); + localIdentity = realpathSync.native(localPath); } catch {} return sha256( !isolateWorktrees && normalizedRemote @@ -272,7 +312,11 @@ export function getProjectIdentity(directory: string): string { export function getGeneratedProjectTag(directory: string): string { const basePath = getProjectBasePath(directory); - const repoName = getGitRepoName(basePath) || basename(basePath) || "unknown"; + const bareRepositoryPath = getBareRepositoryPath(basePath); + const repoName = + getGitRepoName(basePath) || + (bareRepositoryPath ? getBareRepositoryName(bareRepositoryPath) : basename(basePath)) || + "unknown"; const shortName = sanitizeRepoName(repoName).slice(0, 72).replace(/_+$/g, ""); return `repo_${shortName || "unknown"}__${getProjectIdentity(directory)}`; } diff --git a/src/v2/runtime.test.ts b/src/v2/runtime.test.ts index bb05a5a..073b592 100644 --- a/src/v2/runtime.test.ts +++ b/src/v2/runtime.test.ts @@ -179,6 +179,7 @@ function harness( get: async ({ sessionID }: { sessionID: string }) => ({ id: sessionID, location: { directory: "/repo" }, + ...(sessionID.startsWith("child") ? { parentID: "s1" } : {}), }), context: async () => state.transcript, }, @@ -375,6 +376,44 @@ describe("OpenCode 2 runtime", () => { h.runtime.cleanup(); }); + test("leaves subagent sessions alone unless captureSubagents is set", async () => { + const h = harness(); + await h.runtime.register(); + h.transcript = [user("u1", "explore the repo"), assistant("a1", "found it")]; + + const message = request("m1", "Find where the auth middleware lives"); + await h.runtime.handleContext({ sessionID: "child-1", messages: [message] }); + await h.runtime.handleCompaction({ sessionID: "child-1", system: [] }); + await h.runtime.handleEvent({ + id: "c1", + type: "session.execution.succeeded", + data: { sessionID: "child-1" }, + }); + await h.runtime.handleEvent({ id: "c2", type: "session.deleted", data: { sessionID: "child-1" } }); + await h.runtime.idle(); + expect(texts(message)).toEqual(["Find where the auth middleware lives"]); + expect(h.queries).toEqual([]); + expect(h.writes).toEqual([]); + h.runtime.cleanup(); + + const optedIn = harness({ captureSubagents: true }); + await optedIn.runtime.register(); + optedIn.transcript = [user("u1", "explore the repo"), assistant("a1", "found it")]; + await optedIn.runtime.handleContext({ + sessionID: "child-2", + messages: [request("m2", "Find where the auth middleware lives")], + }); + await optedIn.runtime.handleEvent({ + id: "c3", + type: "session.execution.succeeded", + data: { sessionID: "child-2" }, + }); + await optedIn.runtime.idle(); + expect(optedIn.queries).toHaveLength(1); + expect(optedIn.writes).toHaveLength(1); + optedIn.runtime.cleanup(); + }); + test("captures completed turns idempotently and saves compaction summaries", async () => { const h = harness(); await h.runtime.register(); diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index f422023..1cea676 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -13,7 +13,9 @@ import { AUTOMATIC_CAPTURE_TIMEOUT_MS, buildCadenceBatches, buildSessionEndBatch, + defaultOpeningPromptIndex, getCaptureId, + prepareCaptureMessages, type CaptureBatch, type CaptureTurn, } from "../services/capture.js"; @@ -47,6 +49,8 @@ import { type DirectRecallResult, } from "../services/recall.js"; import { getTags, type ResolvedTags } from "../services/tags.js"; +import { OpeningPromptIndex, RecallQueryIndex } from "../services/local-dedupe.js"; +import { SessionScope, type SessionScopeConfig } from "../services/session-scope.js"; import { checkNpmUpdate, type UpdateInfo } from "../services/version-check.js"; import { SUPERMEMORY_RPC } from "../rpc.js"; @@ -122,7 +126,8 @@ type RuntimeConfig = Pick< | "compactionEnabled" | "keywordPatterns" | "maxProjectMemories" ->; +> & + Partial; export interface V2RuntimeDependencies { /** Auth state; a function is re-checked per hook so login/logout apply live. */ @@ -133,6 +138,8 @@ export interface V2RuntimeDependencies { resolveTags: typeof getTags; logger: typeof log; checkUpdate: () => Promise; + openingPrompts: OpeningPromptIndex | null; + recallQueries: RecallQueryIndex | null; } const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { @@ -144,6 +151,8 @@ const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { logger: log, checkUpdate: () => checkNpmUpdate("opencode-supermemory", PLUGIN_VERSION, UPDATE_COMMAND), + openingPrompts: defaultOpeningPromptIndex(), + recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryIndex() : null, }; /** Minimal shape of an OpenCode 2 event as read from `ctx.event.subscribe()`. */ @@ -445,6 +454,7 @@ export class V2Runtime { readonly #deduper = new EventDeduper(); readonly #registrations: Registration[] = []; readonly #abortController = new AbortController(); + readonly #scope: SessionScope; #emitActivity: ((notice: MemoryActivityNotice) => void) | undefined; #activity: MemoryActivityReporter; #active = true; @@ -457,6 +467,13 @@ export class V2Runtime { this.#ctx = ctx; this.#deps = mergeDependencies(options); this.#isOwner = isOwner; + // OpenCode 2 gives plugins no per-session signal for `opencode run`, so only child sessions are detected here. + this.#scope = new SessionScope({ + headless: false, + config: { ...CONFIG, ...this.#deps.config }, + lookupParent: async (sessionID) => + ((await ctx.session.get({ sessionID })) as { parentID?: string }).parentID, + }); this.#activity = createMemoryActivityReporterFromSink((notice) => { this.#deps.logger("[activity]", { kind: notice.kind, message: notice.message }); this.#emitActivity?.(notice); @@ -661,6 +678,7 @@ export class V2Runtime { messages: RequestMessage[]; }): Promise { if (!this.#configured) return; + if (await this.#scope.skipReason(event.sessionID)) return; const latestUser = event.messages.findLast((message) => message.role === "user"); if (!latestUser) return; const userText = extractMessageText(latestUser); @@ -695,6 +713,7 @@ export class V2Runtime { system: Array<{ type: "text"; text: string }>; }): Promise { if (!this.#configured || !this.#deps.config.compactionEnabled) return; + if (await this.#scope.skipReason(event.sessionID)) return; const memories = await this.#projectMemories(event.sessionID); event.system.push({ type: "text", text: createCompactionPrompt(memories) }); this.#deps.logger("v2 compaction context injected", { @@ -706,6 +725,13 @@ export class V2Runtime { async handleEvent(event: V2Event): Promise { if (!this.active || !this.#configured || this.#deduper.hasSeen(event.id)) return; const sessionID = this.#eventSessionID(event); + if (sessionID && (await this.#scope.skipReason(sessionID))) { + if (event.type === "session.deleted") { + this.#states.delete(sessionID); + this.#scope.forget(sessionID); + } + return; + } if (sessionID && event.type !== "session.compaction.ended") { void this.#retryPendingSummaries(sessionID); @@ -733,11 +759,15 @@ export class V2Runtime { if (!sessionID) return; const state = this.#states.get(sessionID); this.#recall.delete(sessionID); - if (!state) return; + if (!state) { + this.#scope.forget(sessionID); + return; + } await this.#runCaptureExclusive(sessionID, () => this.#captureSessionEnd(sessionID), ); this.#states.delete(sessionID); + this.#scope.forget(sessionID); return; } @@ -946,6 +976,9 @@ export class V2Runtime { : [], ) : undefined, + skipQuery: this.#deps.recallQueries + ? (query) => this.#deps.recallQueries?.isRepeat(tags.canonical, query) ?? false + : undefined, }) : Promise.resolve(skipped); @@ -1036,15 +1069,23 @@ export class V2Runtime { ): Promise { const captureId = getCaptureId(sessionID, batch); if (state.completedCaptureIds.has(captureId)) return true; - const messages = batch.turns.flatMap((turn) => turn.messages); - if (messages.length === 0) { + if (batch.turns.every((turn) => turn.messages.length === 0)) { state.completedCaptureIds.add(captureId); return true; } let result: { success: boolean; error?: string }; + let commit = () => {}; try { const tags = await this.#resolveSession(sessionID); + const prepared = prepareCaptureMessages( + this.#deps.openingPrompts, + tags.canonical, + sessionID, + batch, + ); + commit = prepared.commit; + const messages = prepared.messages; result = await this.#deps.memoryClient.ingestConversation( `${sessionID}:${batch.startTurn}-${batch.endTurn}`, messages, @@ -1074,6 +1115,7 @@ export class V2Runtime { if (result.success) { state.completedCaptureIds.add(captureId); + commit(); this.#activity.saved(); this.#deps.logger("[capture] conversation batch saved", { sessionID, @@ -1095,6 +1137,7 @@ export class V2Runtime { } async #captureCadence(sessionID: string): Promise { + if (await this.#scope.skipReason(sessionID)) return; const state = this.#state(sessionID); const turns = await this.#refreshTurns(sessionID, state); for (const batch of buildCadenceBatches( @@ -1106,6 +1149,7 @@ export class V2Runtime { } async #captureSessionEnd(sessionID: string): Promise { + if (await this.#scope.skipReason(sessionID)) return; const state = this.#state(sessionID); const turns = await this.#refreshTurns(sessionID, state); for (const batch of buildCadenceBatches( From 7d3338a449d1d8eebb8ce64f4329ed0ee9b85d73 Mon Sep 17 00:00:00 2001 From: Dhravya Date: Sat, 7 Nov 2026 02:56:02 +0000 Subject: [PATCH 2/5] Keep container tags unchanged for bare-repo worktrees Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 1 - README.md | 4 +--- src/services/tags.ts | 50 +++----------------------------------------- 3 files changed, 4 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f73778a..78dc647 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,6 @@ - Skip automatic recall, capture and compaction memory for subagent sessions (any session with a `parentID`) and, on OpenCode V1, for `opencode run` / `opencode github run`. Opt back in with `captureSubagents` / `captureHeadless` or `SUPERMEMORY_CAPTURE_SUBAGENTS=true` / `SUPERMEMORY_CAPTURE_HEADLESS=true`. - Treat Conductor and Vibe Kanban sessions as interactive; `captureOrchestrated: false` skips them. - Replace an opening prompt already captured from this machine for the same container with a one-line marker (`dedupeOpeningPrompt`), and skip recall for exact query repeats within 10 minutes (`dedupeRecallQueries`). -- Linked worktrees of a bare repository without an origin remote now share the bare repository's container instead of getting one per worktree. ## 2.1.2 diff --git a/README.md b/README.md index 0b63e7b..e6a800c 100644 --- a/README.md +++ b/README.md @@ -326,9 +326,7 @@ shared repository container. The repository hash comes from the normalized Git `origin` remote, so Claude Code, Codex, Cursor, and OpenCode use the same container for the same repository. Repositories with the same name but different remotes remain isolated. Without an -origin remote, OpenCode falls back to the repository's real filesystem path. Linked Git -worktrees (including worktrees of a bare repository) use the main repository's path, so -parallel worktrees share one container. +origin remote, OpenCode falls back to the repository's real filesystem path. OpenCode also reads previous `user_project_*`, `repo_`, `claudecode_project_*`, `codex_user_*`, `codex_project_*`, `opencode_user_*`, diff --git a/src/services/tags.ts b/src/services/tags.ts index 69011b4..e520f10 100644 --- a/src/services/tags.ts +++ b/src/services/tags.ts @@ -66,45 +66,6 @@ function getProjectBasePath(directory: string): string { return getGitRoot(directory) || resolve(directory); } -const bareRepositoryCache = new Map(); - -// Linked worktrees of a bare repository have no main checkout, so they share the bare repository's identity. -function getBareRepositoryPath(directory: string): string | null { - if (process.env.SUPERMEMORY_ISOLATE_WORKTREES === "true") return null; - const cached = bareRepositoryCache.get(directory); - if (cached !== undefined) return cached; - let result: string | null = null; - try { - const [commonDir, gitDir] = execSync( - "git rev-parse --path-format=absolute --git-common-dir --git-dir", - { - cwd: directory, - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - windowsHide: true, - }, - ) - .trim() - .split(/\r?\n/); - if (commonDir && gitDir && commonDir !== gitDir) { - const bare = execSync("git config --bool core.bare", { - cwd: directory, - encoding: "utf-8", - stdio: ["pipe", "pipe", "pipe"], - windowsHide: true, - }).trim(); - if (bare === "true") result = commonDir; - } - } catch {} - bareRepositoryCache.set(directory, result); - return result; -} - -function getBareRepositoryName(bareRepositoryPath: string): string { - const name = basename(bareRepositoryPath).replace(/\.git$/i, ""); - return name && !name.startsWith(".") ? name : basename(dirname(bareRepositoryPath)); -} - function getGitEmail(directory: string): string | null { try { const email = execSync("git config user.email", { @@ -298,10 +259,9 @@ export function getProjectIdentity(directory: string): string { const basePath = getProjectBasePath(directory); const { normalizedRemote } = getGitRepoInfo(basePath); const isolateWorktrees = process.env.SUPERMEMORY_ISOLATE_WORKTREES === "true"; - const localPath = getBareRepositoryPath(basePath) ?? basePath; - let localIdentity = localPath; + let localIdentity = basePath; try { - localIdentity = realpathSync.native(localPath); + localIdentity = realpathSync.native(basePath); } catch {} return sha256( !isolateWorktrees && normalizedRemote @@ -312,11 +272,7 @@ export function getProjectIdentity(directory: string): string { export function getGeneratedProjectTag(directory: string): string { const basePath = getProjectBasePath(directory); - const bareRepositoryPath = getBareRepositoryPath(basePath); - const repoName = - getGitRepoName(basePath) || - (bareRepositoryPath ? getBareRepositoryName(bareRepositoryPath) : basename(basePath)) || - "unknown"; + const repoName = getGitRepoName(basePath) || basename(basePath) || "unknown"; const shortName = sanitizeRepoName(repoName).slice(0, 72).replace(/_+$/g, ""); return `repo_${shortName || "unknown"}__${getProjectIdentity(directory)}`; } From 191b65b352087b2808b88682143bb0ac442dc624 Mon Sep 17 00:00:00 2001 From: Mahesh Sanikommu Date: Thu, 12 Nov 2026 16:52:31 -0800 Subject: [PATCH 3/5] fix: recall cache, argv value flags and bounded opening-prompt dedupe (#126) * Re-serve cached recall for repeat queries and expire opening-prompt dedupe after 24h Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Skip values of opencode value flags in headless detection and time out parent lookups Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Accept yes/on/no/off for env flags and document OpenCode 2 run and inherited orchestrator env Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * Scope the recall cache to backend and credential, clear it on logout, and write cache files 0600 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> * chore(release): 2.2.0 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --------- Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 5 +- README.md | 44 ++++++++----- package.json | 2 +- src/config.ts | 21 ++++++- src/index.ts | 31 +++++----- src/services/auth.ts | 2 + src/services/local-dedupe.test.ts | 84 +++++++++++++++++++++---- src/services/local-dedupe.ts | 99 ++++++++++++++++++++++-------- src/services/recall.ts | 4 +- src/services/session-scope.test.ts | 23 +++++++ src/services/session-scope.ts | 48 ++++++++++++--- src/v2/runtime.ts | 33 +++++----- src/version.ts | 2 +- 13 files changed, 297 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78dc647..c74ebf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,11 @@ # Changelog -## Unreleased +## 2.2.0 - Skip automatic recall, capture and compaction memory for subagent sessions (any session with a `parentID`) and, on OpenCode V1, for `opencode run` / `opencode github run`. Opt back in with `captureSubagents` / `captureHeadless` or `SUPERMEMORY_CAPTURE_SUBAGENTS=true` / `SUPERMEMORY_CAPTURE_HEADLESS=true`. - Treat Conductor and Vibe Kanban sessions as interactive; `captureOrchestrated: false` skips them. -- Replace an opening prompt already captured from this machine for the same container with a one-line marker (`dedupeOpeningPrompt`), and skip recall for exact query repeats within 10 minutes (`dedupeRecallQueries`). +- Replace an opening prompt of 200+ characters already captured from this machine for the same container in the last 24 hours with a one-line marker (`dedupeOpeningPrompt`), and re-serve the last successful recall for exact query repeats within 10 minutes instead of searching again (`dedupeRecallQueries`). +- `SUPERMEMORY_CAPTURE_*` / `SUPERMEMORY_DEDUPE_*` accept `true/1/yes/on` and `false/0/no/off`; OpenCode V1 headless detection skips the values of value-taking flags (`--port 4096 run` is headless, `--prompt run` is not); the parent-session lookup fails open after 2 seconds. ## 2.1.2 diff --git a/README.md b/README.md index e6a800c..a381b35 100644 --- a/README.md +++ b/README.md @@ -185,9 +185,12 @@ By default the plugin makes no Supermemory calls from its hooks for: `SUPERMEMORY_CAPTURE_SUBAGENTS=true` to restore recall and capture for them. - **Headless runs (OpenCode V1).** `opencode run` and `opencode github run`, which host the server and plugins in the CLI process. Set `captureHeadless: true` or - `SUPERMEMORY_CAPTURE_HEADLESS=true` to restore them. OpenCode 2 gives plugins no signal for - `opencode run` (it may share the background server with interactive sessions), so headless - OpenCode 2 runs are still treated as interactive. `opencode run --attach` on V1 is the same. + `SUPERMEMORY_CAPTURE_HEADLESS=true` to restore them. `opencode run --attach` on V1 runs the + plugin in the attached server, so it is treated as interactive. + +**OpenCode 2 `opencode run` is not detected as headless.** OpenCode 2 gives plugins no signal for +it (it may share the background server with interactive sessions), so OpenCode 2 runs get recall +and capture like any interactive session. Only subagent sessions are skipped on OpenCode 2. OpenCode's title generation never reaches the plugin's hooks, so it makes no Supermemory calls. Compaction only runs [Compaction Memory](#compaction-memory) for the session being summarised, @@ -196,8 +199,10 @@ which is skipped for subagent and headless sessions like everything else. Sessions started by Conductor (`CONDUCTOR_WORKSPACE_PATH`, `CONDUCTOR_SESSION_ID`) or Vibe Kanban (`VK_WORKSPACE_ID`) are real user work and always count as interactive, even through `opencode run`. Set `captureOrchestrated: false` or `SUPERMEMORY_CAPTURE_ORCHESTRATED=false` to -skip them. Orchestrators without an environment variable (Crystal, Claude Squad) are not -recognised. On OpenCode 2 the variables are read from the server process, so they only apply +skip them. The variables are inherited, so any `opencode run` started inside a Conductor or +Vibe Kanban workspace (a script, or an agent shelling out to OpenCode) also counts as +orchestrated and is captured. Orchestrators without an environment variable (Crystal, Claude +Squad) are not recognised; Claude Squad runs the interactive TUI, which is captured as usual. On OpenCode 2 the variables are read from the server process, so they only apply when it was started from the orchestrator's environment (for example `--standalone` or `run` without a background service). @@ -206,13 +211,22 @@ without a background service). Swarms of one-shot workers often send the same task prompt many times. Two small local indexes under `~/.supermemory-opencode/` keep those repeats from being re-sent: -- **Opening prompt** (`dedupeOpeningPrompt`, default `true`). When a session's first prompt - matches one this machine already captured for the same container tag, the capture is sent - with a one-line `[Opening prompt omitted: ...]` marker in its place. The rest of the - conversation is captured as usual. Set `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` to opt out. -- **Recall query** (`dedupeRecallQueries`, default `true`). Direct recall is skipped when the - exact same normalized query was already searched against the same container tag in the last - 10 minutes. Set `SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to opt out. +- **Opening prompt** (`dedupeOpeningPrompt`, default `true`). When a session's first prompt is + at least 200 characters and matches one this machine successfully captured for the same + container tag in the last 24 hours, the capture is sent with a one-line + `[Opening prompt omitted: ...]` marker in its place. The rest of the conversation is captured + as usual. Older entries are ignored and pruned. Set `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` + to opt out. +- **Recall query** (`dedupeRecallQueries`, default `true`). When the same normalized query is + recalled against the same container tag within 10 minutes, the result of the first successful + search is re-served without another API call, so a new session still gets the same context. A + failed or timed-out search is never cached. Entries are keyed on a hash of the API base URL, + the credential, the container tags and the query, so another account or backend never reuses + them; nothing is cached without a credential, and `logout` deletes the file. Set + `SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to opt out. + +The `SUPERMEMORY_CAPTURE_*` and `SUPERMEMORY_DEDUPE_*` variables accept `true`/`1`/`yes`/`on` +and `false`/`0`/`no`/`off` (any case) and override the config file in both directions. ### Keyword Detection @@ -352,7 +366,7 @@ does not require a migration. | `SUPERMEMORY_CAPTURE_HEADLESS` | `true` restores recall and capture for `opencode run` (overrides `captureHeadless`). | | `SUPERMEMORY_CAPTURE_ORCHESTRATED` | `false` skips sessions started by Conductor or Vibe Kanban (overrides `captureOrchestrated`). | | `SUPERMEMORY_DEDUPE_OPENING_PROMPT` | `false` always sends repeated opening prompts (overrides `dedupeOpeningPrompt`). | -| `SUPERMEMORY_DEDUPE_RECALL_QUERIES` | `false` always runs recall for repeated queries (overrides `dedupeRecallQueries`). | +| `SUPERMEMORY_DEDUPE_RECALL_QUERIES` | `false` always searches for repeated recall queries instead of re-serving the cached result (overrides `dedupeRecallQueries`). | ### `~/.config/opencode/supermemory.jsonc` @@ -444,10 +458,10 @@ scope, not from a different or malformed response. // Recall and capture sessions started by Conductor or Vibe Kanban "captureOrchestrated": true, - // Replace an opening prompt already captured from this machine with a marker + // Replace a 200+ character opening prompt captured from this machine in the last 24h with a marker "dedupeOpeningPrompt": true, - // Skip recall for an exact repeat of a query made in the last 10 minutes + // Re-serve the last successful recall for a repeat of a query made in the last 10 minutes "dedupeRecallQueries": true, } ``` diff --git a/package.json b/package.json index 7daa459..2891406 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-supermemory", - "version": "2.1.2", + "version": "2.2.0", "description": "OpenCode plugin that gives coding agents persistent memory using Supermemory", "type": "module", "main": "dist/index.js", diff --git a/src/config.ts b/src/config.ts index 24071ad..d4b03fe 100644 --- a/src/config.ts +++ b/src/config.ts @@ -1,3 +1,4 @@ +import { createHash } from "node:crypto"; import { existsSync, readFileSync, writeFileSync } from "node:fs"; import { join } from "node:path"; import { homedir } from "node:os"; @@ -122,9 +123,9 @@ function validateCaptureEveryNTurns( } function resolveFlag(envName: string, value: unknown, fallback: boolean): boolean { - const env = process.env[envName]?.trim().toLowerCase(); - if (env === "true" || env === "1") return true; - if (env === "false" || env === "0") return false; + const env = process.env[envName]?.trim().toLowerCase() ?? ""; + if (["true", "1", "yes", "on"].includes(env)) return true; + if (["false", "0", "no", "off"].includes(env)) return false; return typeof value === "boolean" ? value : fallback; } @@ -166,6 +167,20 @@ export function getApiKey(): string | undefined { return loadCredentials(); } +/** Hash of the backend URL and credential that scopes local recall caching; null without a credential. */ +export function getRecallCacheScope(): string | null { + try { + const apiKey = getApiKey(); + const saved = apiKey ? null : loadCredentialData(); + const credential = + apiKey ?? (saved?.type === "oauth" ? (saved.refreshToken ?? saved.accessToken) : undefined); + if (!credential) return null; + return createHash("sha256").update(`${getApiBaseUrl()}\n${credential}`).digest("hex"); + } catch { + return null; + } +} + function normalizeBaseUrl(baseUrl: unknown): string | null { if (typeof baseUrl !== "string" || !baseUrl.trim()) return null; diff --git a/src/index.ts b/src/index.ts index e222379..683a000 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,10 +25,10 @@ import { } from "./services/memory-tool.js"; import { getTags } from "./services/tags.js"; import { isHeadlessCommand, SessionScope } from "./services/session-scope.js"; -import { RecallQueryIndex } from "./services/local-dedupe.js"; +import { RecallQueryCache } from "./services/local-dedupe.js"; import { createCompactionHook, type CompactionContext } from "./services/compaction.js"; -import { isConfigured, CONFIG, PLUGIN_VERSION } from "./config.js"; +import { isConfigured, CONFIG, getRecallCacheScope, PLUGIN_VERSION } from "./config.js"; import { log } from "./services/logger.js"; import { checkNpmUpdate } from "./services/version-check.js"; @@ -109,7 +109,20 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { return response.data.parentID; }, }); - const recallQueries = CONFIG.dedupeRecallQueries ? new RecallQueryIndex() : null; + const searchForRecall = (query: string) => + supermemoryClient.searchMemoriesForRecall( + query, + tags.canonical, + tags.personalReads, + tags.projectReads, + { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, + ); + const recallSearch = CONFIG.dedupeRecallQueries + ? new RecallQueryCache(getRecallCacheScope).wrap( + [tags.canonical, ...tags.personalReads, ...tags.projectReads], + searchForRecall, + ) + : searchForRecall; log("Plugin init", { directory, tags, configured: isConfigured() }); if (!isConfigured()) { @@ -228,14 +241,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { prompt: userMessage, sessionID: input.sessionID, cache: recallSessions, - search: (query) => - supermemoryClient.searchMemoriesForRecall( - query, - tags.canonical, - tags.personalReads, - tags.projectReads, - { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, - ), + search: recallSearch, suppressTexts: isFirstMessage ? profileRequest.then((result) => result?.success && result.profile @@ -243,9 +249,6 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { : [], ) : undefined, - skipQuery: recallQueries - ? (query) => recallQueries.isRepeat(tags.canonical, query) - : undefined, }) : Promise.resolve({ context: "", diff --git a/src/services/auth.ts b/src/services/auth.ts index 2c1c266..8e6b767 100644 --- a/src/services/auth.ts +++ b/src/services/auth.ts @@ -3,6 +3,7 @@ import { join } from "node:path"; import { homedir } from "node:os"; import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { createServer, type Server } from "node:http"; +import { RECALL_QUERIES_FILE } from "./local-dedupe.js"; import { openUrl } from "./openUrl.js"; import { PLUGIN_VERSION } from "../version.js"; @@ -460,6 +461,7 @@ export async function settleAuth(): Promise { export async function clearCredentials(): Promise { return withAuthLock(async (remaining) => { + fs.rmSync(RECALL_QUERIES_FILE, { force: true }); const credentials = loadCredentialData(); if (credentials?.type === "oauth" && credentials.refreshToken) { await oauthRequest(issuerEndpoint(credentials.revocationEndpoint, credentials.issuer), { diff --git a/src/services/local-dedupe.test.ts b/src/services/local-dedupe.test.ts index da0f3d2..3132f5b 100644 --- a/src/services/local-dedupe.test.ts +++ b/src/services/local-dedupe.test.ts @@ -1,19 +1,23 @@ import { describe, expect, test } from "bun:test"; -import { mkdtempSync } from "node:fs"; +import { mkdtempSync, statSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { OpeningPromptIndex, RecallQueryIndex } from "./local-dedupe.js"; +import type { SearchResponse } from "./client.js"; +import { OPENING_PROMPT_TTL_MS, OpeningPromptIndex, RecallQueryCache } from "./local-dedupe.js"; function tempFile(name: string): string { return join(mkdtempSync(join(tmpdir(), "supermemory-dedupe-")), name); } +const TASK = + "Run the nightly migration task against the staging database, verify every table row count matches the snapshot taken before the run, then write a short report with any mismatches and the exact SQL you used."; + describe("local dedupe indexes", () => { - test("sends an opening prompt once per container tag and keeps the owner session intact", () => { + test("sends a long opening prompt once per container tag and keeps the owner session intact", () => { const index = new OpeningPromptIndex(tempFile("opening.json")); const batch = [ - { role: "user" as const, content: "Run the nightly migration task" }, + { role: "user" as const, content: TASK }, { role: "assistant" as const, content: "Done." }, ]; @@ -23,7 +27,7 @@ describe("local dedupe indexes", () => { expect(index.prepare("repo_a", "worker-1", batch).messages).toEqual(batch); const repeat = index.prepare("repo_a", "worker-2", [ - { role: "user", content: "Run the nightly migration task" }, + { role: "user", content: TASK.replace(" ", " ") }, { role: "assistant", content: "Done again." }, ]); expect(repeat.messages[0]?.content).toMatch(/^\[Opening prompt omitted: .*sha256:[0-9a-f]{12}\)\]$/); @@ -31,19 +35,73 @@ describe("local dedupe indexes", () => { expect(index.prepare("repo_b", "worker-3", batch).messages).toEqual(batch); }); + test("leaves short opening prompts and prompts captured over 24 hours ago untouched", () => { + let now = 0; + const index = new OpeningPromptIndex(tempFile("opening.json"), () => now); + const short = [{ role: "user" as const, content: "fix the failing tests" }]; + index.prepare("repo_a", "worker-1", short).commit(); + expect(index.prepare("repo_a", "worker-2", short).messages).toEqual(short); + + const long = [{ role: "user" as const, content: TASK }]; + index.prepare("repo_a", "worker-1", long).commit(); + now = OPENING_PROMPT_TTL_MS - 1; + expect(index.prepare("repo_a", "worker-2", long).messages).not.toEqual(long); + now = OPENING_PROMPT_TTL_MS; + const stale = index.prepare("repo_a", "worker-2", long); + expect(stale.messages).toEqual(long); + stale.commit(); + expect(index.prepare("repo_a", "worker-3", long).messages).not.toEqual(long); + }); + test("an uncommitted capture does not mark the prompt as sent", () => { const index = new OpeningPromptIndex(tempFile("opening.json")); - const batch = [{ role: "user" as const, content: "same task" }]; + const batch = [{ role: "user" as const, content: TASK }]; index.prepare("repo_a", "worker-1", batch); expect(index.prepare("repo_a", "worker-2", batch).messages).toEqual(batch); }); - test("skips exact recall query repeats per tag within the window", () => { - const index = new RecallQueryIndex(tempFile("recall.json"), 1_000); - expect(index.isRepeat("repo_a", "How do we deploy?", 0)).toBe(false); - expect(index.isRepeat("repo_a", "how do we deploy?", 500)).toBe(true); - expect(index.isRepeat("repo_b", "How do we deploy?", 500)).toBe(false); - expect(index.isRepeat("repo_a", "How do we deploy to prod?", 500)).toBe(false); - expect(index.isRepeat("repo_a", "How do we deploy?", 1_500)).toBe(false); + test("re-serves a successful recall search per credential and tags within the window and retries failures", async () => { + let now = 0; + let scope: string | null = "backend-a:key-1"; + const file = tempFile("recall.json"); + const cache = new RecallQueryCache(() => scope, file, 1_000, () => now); + const calls: string[] = []; + let fail = false; + const search = async (query: string): Promise => { + calls.push(query); + return fail + ? { success: false, error: "unavailable" } + : { success: true, results: [{ id: `m${calls.length}`, memory: "deploy with wrangler" }] }; + }; + const repoA = cache.wrap(["repo_a", "user_a"], search); + + const first = await repoA("How do we deploy?"); + now = 500; + expect(await repoA("how do we deploy?")).toEqual(first); + expect(calls).toHaveLength(1); + expect(statSync(file).mode & 0o777).toBe(0o600); + await cache.wrap(["repo_b", "user_a"], search)("How do we deploy?"); + await repoA("How do we deploy to prod?"); + expect(calls).toHaveLength(3); + now = 1_500; + await repoA("How do we deploy?"); + expect(calls).toHaveLength(4); + + fail = true; + expect((await repoA("What is pending?")).success).toBe(false); + fail = false; + expect((await repoA("What is pending?")).success).toBe(true); + expect(calls).toHaveLength(6); + + scope = "backend-a:key-2"; + await repoA("What is pending?"); + expect(calls).toHaveLength(7); + scope = "backend-a:key-1"; + await repoA("What is pending?"); + expect(calls).toHaveLength(7); + scope = null; + await repoA("What is pending?"); + await repoA("What is pending?"); + expect(calls).toHaveLength(9); }); }); diff --git a/src/services/local-dedupe.ts b/src/services/local-dedupe.ts index 7c8d00f..9a862e5 100644 --- a/src/services/local-dedupe.ts +++ b/src/services/local-dedupe.ts @@ -1,9 +1,10 @@ import { createHash, randomBytes } from "node:crypto"; -import { mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; +import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; import { homedir } from "node:os"; import { dirname, join } from "node:path"; import type { ConversationMessage } from "../types/index.js"; +import type { SearchResponse } from "./client.js"; const STATE_DIR = join(homedir(), ".supermemory-opencode"); export const OPENING_PROMPTS_FILE = join(STATE_DIR, "opening-prompts.json"); @@ -11,6 +12,8 @@ export const RECALL_QUERIES_FILE = join(STATE_DIR, "recall-queries.json"); const MAX_OPENING_PROMPTS = 1_000; const MAX_RECALL_QUERIES = 500; export const RECALL_REPEAT_WINDOW_MS = 10 * 60 * 1000; +export const OPENING_PROMPT_MIN_CHARS = 200; +export const OPENING_PROMPT_TTL_MS = 24 * 60 * 60 * 1000; type Entries = Record; @@ -32,8 +35,12 @@ function readEntries(file: string): Entries { function writeEntries(file: string, entries: Entries): void { mkdirSync(dirname(file), { recursive: true, mode: 0o700 }); const temporary = `${file}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`; - writeFileSync(temporary, JSON.stringify(entries), { mode: 0o600 }); - renameSync(temporary, file); + try { + writeFileSync(temporary, JSON.stringify(entries), { mode: 0o600, flag: "wx" }); + renameSync(temporary, file); + } finally { + rmSync(temporary, { force: true }); + } } function newest(entries: Entries, limit: number, at: (value: T) => number): Entries { @@ -45,11 +52,14 @@ function newest(entries: Entries, limit: number, at: (value: T) => number) } /** - * Remembers which session first captured each opening prompt per container tag, - * so repeated one-shot workers do not re-send the same task prompt. + * Remembers which session first captured each long opening prompt per container + * tag in the last 24 hours, so repeated one-shot workers do not re-send it. */ export class OpeningPromptIndex { - constructor(private readonly file = OPENING_PROMPTS_FILE) {} + constructor( + private readonly file = OPENING_PROMPTS_FILE, + private readonly now: () => number = Date.now, + ) {} /** Returns the batch to send and a commit to call once the capture is accepted. */ prepare( @@ -63,9 +73,12 @@ export class OpeningPromptIndex { return unchanged; } + const prompt = opening.content.replace(/\s+/g, " ").trim(); + if (prompt.length < OPENING_PROMPT_MIN_CHARS) return unchanged; + try { - const hash = sha256(`${containerTag}\n${opening.content.replace(/\s+/g, " ").trim()}`); - const owner = readEntries<{ sessionId: string; at: number }>(this.file)[hash]; + const hash = sha256(`${containerTag}\n${prompt}`); + const owner = this.#fresh()[hash]; if (owner && owner.sessionId !== sessionID) { return { messages: [ @@ -83,8 +96,8 @@ export class OpeningPromptIndex { messages, commit: () => { try { - const entries = readEntries<{ sessionId: string; at: number }>(this.file); - entries[hash] ??= { sessionId: sessionID, at: Date.now() }; + const entries = this.#fresh(); + entries[hash] ??= { sessionId: sessionID, at: this.now() }; writeEntries(this.file, newest(entries, MAX_OPENING_PROMPTS, (entry) => entry.at)); } catch {} }, @@ -93,29 +106,63 @@ export class OpeningPromptIndex { return unchanged; } } + + #fresh(): Entries<{ sessionId: string; at: number }> { + const now = this.now(); + return Object.fromEntries( + Object.entries(readEntries<{ sessionId: string; at: number }>(this.file)).filter( + ([, entry]) => + typeof entry?.at === "number" && + typeof entry.sessionId === "string" && + now - entry.at < OPENING_PROMPT_TTL_MS, + ), + ); + } } -/** Exact repeats of a normalized recall query against one container tag within the window. */ -export class RecallQueryIndex { +/** Re-serves the last successful recall search per backend, credential, container tags and normalized query within the window. */ +export class RecallQueryCache { constructor( + private readonly scope: () => string | null, private readonly file = RECALL_QUERIES_FILE, private readonly windowMs = RECALL_REPEAT_WINDOW_MS, + private readonly now: () => number = Date.now, ) {} - isRepeat(containerTag: string, query: string, now = Date.now()): boolean { - try { - const hash = sha256(`${containerTag}\n${query.toLowerCase().replace(/\s+/g, " ").trim()}`); - const entries = Object.fromEntries( - Object.entries(readEntries(this.file)).filter( - ([, at]) => typeof at === "number" && now - at < this.windowMs, - ), + wrap( + containerTags: readonly string[], + search: (query: string) => Promise, + ): (query: string) => Promise { + return async (query) => { + const scope = this.scope(); + if (!scope) return search(query); + const hash = sha256( + [scope, ...containerTags, query.toLowerCase().replace(/\s+/g, " ").trim()].join("\n"), ); - if (entries[hash] !== undefined) return true; - entries[hash] = now; - writeEntries(this.file, newest(entries, MAX_RECALL_QUERIES, (at) => at)); - return false; - } catch { - return false; - } + const cached = this.#fresh()[hash]; + if (cached) return cached.response; + + const response = await search(query); + if (response.success) { + try { + const entries = this.#fresh(); + entries[hash] = { at: this.now(), response }; + writeEntries(this.file, newest(entries, MAX_RECALL_QUERIES, (entry) => entry.at)); + } catch {} + } + return response; + }; + } + + #fresh(): Entries<{ at: number; response: SearchResponse }> { + const now = this.now(); + return Object.fromEntries( + Object.entries(readEntries<{ at: number; response: SearchResponse }>(this.file)).filter( + ([, entry]) => + typeof entry?.at === "number" && + entry.response?.success === true && + now - entry.at < this.windowMs, + ), + ); } } diff --git a/src/services/recall.ts b/src/services/recall.ts index ec0f02a..37ec1f6 100644 --- a/src/services/recall.ts +++ b/src/services/recall.ts @@ -136,11 +136,9 @@ export async function buildDirectRecallResult(options: { cache: RecallSessionCache; search: (query: string) => Promise; suppressTexts?: Iterable | Promise>; - skipQuery?: (query: string) => boolean; }): Promise { try { - const prepared = prepareRecallQuery(options.prompt); - const query = prepared && options.skipQuery?.(prepared) ? null : prepared; + const query = prepareRecallQuery(options.prompt); // Begin the search before waiting for first-turn profile suppression. Both // reads have the same timeout, so a cold prompt pays one network window. const searchPromise = query diff --git a/src/services/session-scope.test.ts b/src/services/session-scope.test.ts index 7f62964..99c6b1b 100644 --- a/src/services/session-scope.test.ts +++ b/src/services/session-scope.test.ts @@ -24,6 +24,12 @@ describe("session scope", () => { expect(isHeadlessCommand(argv("./project"))).toBe(false); expect(isHeadlessCommand(argv("serve"))).toBe(false); expect(isHeadlessCommand(argv("github", "install"))).toBe(false); + expect(isHeadlessCommand(argv("--port", "4096", "run", "x"))).toBe(true); + expect(isHeadlessCommand(argv("-m", "p/m", "run", "x"))).toBe(true); + expect(isHeadlessCommand(argv("--prompt", "run"))).toBe(false); + expect(isHeadlessCommand(argv("--agent", "run"))).toBe(false); + expect(isHeadlessCommand(argv("-s", "run"))).toBe(false); + expect(isHeadlessCommand(argv("--port", "4096"))).toBe(false); }); test("orchestrated sessions count as interactive unless opted out", () => { @@ -68,4 +74,21 @@ describe("session scope", () => { }); expect(await optedIn.skipReason("child")).toBeNull(); }); + + test("treats a hung parent lookup as a root session and retries it later", async () => { + let calls = 0; + const scope = new SessionScope({ + lookupParent: (id) => { + calls += 1; + return calls === 1 ? new Promise(() => {}) : Promise.resolve(id); + }, + headless: false, + config: defaults, + env: {}, + lookupTimeoutMs: 20, + }); + expect(await scope.skipReason("slow")).toBeNull(); + expect(await scope.skipReason("slow")).toBe("subagent"); + expect(calls).toBe(2); + }); }); diff --git a/src/services/session-scope.ts b/src/services/session-scope.ts index 930f6ab..8bf6519 100644 --- a/src/services/session-scope.ts +++ b/src/services/session-scope.ts @@ -16,6 +16,24 @@ const ORCHESTRATOR_ENV_VARS = [ "VK_WORKSPACE_ID", ] as const; +// Global and default-command flags of opencode V1 (1.19) that take a value. +const VALUE_FLAGS = new Set([ + "--log-level", + "--port", + "--hostname", + "--mdns-domain", + "--cors", + "-m", + "--model", + "-s", + "--session", + "--prompt", + "--agent", + "--replay-limit", +]); + +export const PARENT_LOOKUP_TIMEOUT_MS = 2_000; + export function isOrchestrated(env: NodeJS.ProcessEnv = process.env): boolean { return ORCHESTRATOR_ENV_VARS.some((name) => Boolean(env[name]?.trim())); } @@ -30,7 +48,7 @@ export function isHeadlessCommand(argv: readonly string[] = process.argv): boole for (let index = 0; index < args.length && positionals.length < 2; index += 1) { const arg = args[index] ?? ""; if (arg === "--") break; - if (arg === "--log-level") { + if (VALUE_FLAGS.has(arg)) { index += 1; continue; } @@ -62,6 +80,7 @@ export class SessionScope { readonly #config: SessionScopeConfig; readonly #processReason: SessionSkipReason | null; readonly #lookupParent: (sessionID: string) => Promise; + readonly #lookupTimeoutMs: number; readonly #children = new Map>(); readonly #logged = new Set(); @@ -70,9 +89,11 @@ export class SessionScope { headless: boolean; config?: SessionScopeConfig; env?: NodeJS.ProcessEnv; + lookupTimeoutMs?: number; }) { this.#config = options.config ?? CONFIG; this.#lookupParent = options.lookupParent; + this.#lookupTimeoutMs = options.lookupTimeoutMs ?? PARENT_LOOKUP_TIMEOUT_MS; this.#processReason = getProcessSkipReason({ config: this.#config, headless: options.headless, @@ -104,13 +125,24 @@ export class SessionScope { let isChild = this.#children.get(sessionID); if (!isChild) { - isChild = this.#lookupParent(sessionID).then( - (parentID) => Boolean(parentID), - () => { - this.#children.delete(sessionID); - return false; - }, - ); + let timer: ReturnType | undefined; + isChild = Promise.race([ + Promise.resolve().then(() => this.#lookupParent(sessionID)), + new Promise((_, reject) => { + timer = setTimeout( + () => reject(new Error("OpenCode session lookup timed out")), + this.#lookupTimeoutMs, + ); + }), + ]) + .finally(() => clearTimeout(timer)) + .then( + (parentID) => Boolean(parentID), + () => { + this.#children.delete(sessionID); + return false; + }, + ); this.#children.set(sessionID, isChild); } if (!(await isChild)) return null; diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index 1cea676..3abe69b 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import type { Plugin } from "@opencode/plugin"; import type { SessionHooks } from "@opencode/plugin/promise/session"; -import { CONFIG, isConfigured, PLUGIN_VERSION } from "../config.js"; +import { CONFIG, getRecallCacheScope, isConfigured, PLUGIN_VERSION } from "../config.js"; import { createMemoryActivityReporterFromSink, type MemoryActivityNotice, @@ -49,7 +49,7 @@ import { type DirectRecallResult, } from "../services/recall.js"; import { getTags, type ResolvedTags } from "../services/tags.js"; -import { OpeningPromptIndex, RecallQueryIndex } from "../services/local-dedupe.js"; +import { OpeningPromptIndex, RecallQueryCache } from "../services/local-dedupe.js"; import { SessionScope, type SessionScopeConfig } from "../services/session-scope.js"; import { checkNpmUpdate, type UpdateInfo } from "../services/version-check.js"; import { SUPERMEMORY_RPC } from "../rpc.js"; @@ -139,7 +139,7 @@ export interface V2RuntimeDependencies { logger: typeof log; checkUpdate: () => Promise; openingPrompts: OpeningPromptIndex | null; - recallQueries: RecallQueryIndex | null; + recallQueries: RecallQueryCache | null; } const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { @@ -152,7 +152,7 @@ const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { checkUpdate: () => checkNpmUpdate("opencode-supermemory", PLUGIN_VERSION, UPDATE_COMMAND), openingPrompts: defaultOpeningPromptIndex(), - recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryIndex() : null, + recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryCache(getRecallCacheScope) : null, }; /** Minimal shape of an OpenCode 2 event as read from `ctx.event.subscribe()`. */ @@ -955,20 +955,26 @@ export class V2Runtime { count: 0, tokens: 0, }; + const searchForRecall = (query: string) => + memoryClient.searchMemoriesForRecall( + query, + tags.canonical, + tags.personalReads, + tags.projectReads, + { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, + ); const directRecall = config.recallMode === "direct" ? buildDirectRecallResult({ prompt: userText, sessionID, cache: this.#recall, - search: (query) => - memoryClient.searchMemoriesForRecall( - query, - tags.canonical, - tags.personalReads, - tags.projectReads, - { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, - ), + search: this.#deps.recallQueries + ? this.#deps.recallQueries.wrap( + [tags.canonical, ...tags.personalReads, ...tags.projectReads], + searchForRecall, + ) + : searchForRecall, suppressTexts: isFirstMessage ? profileRequest.then((result) => result?.success && result.profile @@ -976,9 +982,6 @@ export class V2Runtime { : [], ) : undefined, - skipQuery: this.#deps.recallQueries - ? (query) => this.#deps.recallQueries?.isRepeat(tags.canonical, query) ?? false - : undefined, }) : Promise.resolve(skipped); diff --git a/src/version.ts b/src/version.ts index 16d28d6..57237f3 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,3 +1,3 @@ // AUTO-GENERATED by scripts/sync-version.mjs — do not edit by hand. // Sourced from package.json "version" so the two cannot drift. -export const PLUGIN_VERSION = "2.1.2"; +export const PLUGIN_VERSION = "2.2.0"; From 01c323358299663a1c221f4a111d4fdd43cd2359 Mon Sep 17 00:00:00 2001 From: Mahesh Sanikommu Date: Fri, 13 Nov 2026 00:50:49 -0800 Subject: [PATCH 4/5] Scope opening-prompt dedupe to backend and credential and clear it on logout (#127) Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- README.md | 11 ++++++----- src/config.ts | 4 ++-- src/index.ts | 4 ++-- src/services/auth.ts | 3 ++- src/services/capture.ts | 4 ++-- src/services/local-dedupe.test.ts | 20 ++++++++++++++++---- src/services/local-dedupe.ts | 10 +++++++--- src/v2/runtime.ts | 4 ++-- 8 files changed, 39 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index a381b35..9af8df8 100644 --- a/README.md +++ b/README.md @@ -212,11 +212,12 @@ Swarms of one-shot workers often send the same task prompt many times. Two small indexes under `~/.supermemory-opencode/` keep those repeats from being re-sent: - **Opening prompt** (`dedupeOpeningPrompt`, default `true`). When a session's first prompt is - at least 200 characters and matches one this machine successfully captured for the same - container tag in the last 24 hours, the capture is sent with a one-line - `[Opening prompt omitted: ...]` marker in its place. The rest of the conversation is captured - as usual. Older entries are ignored and pruned. Set `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` - to opt out. + at least 200 characters and matches one this machine successfully captured for the same API + base URL, credential and container tag in the last 24 hours, the capture is sent with a + one-line `[Opening prompt omitted: ...]` marker in its place. The rest of the conversation is + captured as usual. Older entries are ignored and pruned, nothing is deduped without a + credential, and `logout` deletes the index. Set `SUPERMEMORY_DEDUPE_OPENING_PROMPT=false` to + opt out. - **Recall query** (`dedupeRecallQueries`, default `true`). When the same normalized query is recalled against the same container tag within 10 minutes, the result of the first successful search is re-served without another API call, so a new session still gets the same context. A diff --git a/src/config.ts b/src/config.ts index d4b03fe..3841354 100644 --- a/src/config.ts +++ b/src/config.ts @@ -167,8 +167,8 @@ export function getApiKey(): string | undefined { return loadCredentials(); } -/** Hash of the backend URL and credential that scopes local recall caching; null without a credential. */ -export function getRecallCacheScope(): string | null { +/** Hash of the backend URL and credential that scopes local dedupe and recall caching; null without a credential. */ +export function getDedupeScope(): string | null { try { const apiKey = getApiKey(); const saved = apiKey ? null : loadCredentialData(); diff --git a/src/index.ts b/src/index.ts index 683a000..9514a57 100644 --- a/src/index.ts +++ b/src/index.ts @@ -28,7 +28,7 @@ import { isHeadlessCommand, SessionScope } from "./services/session-scope.js"; import { RecallQueryCache } from "./services/local-dedupe.js"; import { createCompactionHook, type CompactionContext } from "./services/compaction.js"; -import { isConfigured, CONFIG, getRecallCacheScope, PLUGIN_VERSION } from "./config.js"; +import { isConfigured, CONFIG, getDedupeScope, PLUGIN_VERSION } from "./config.js"; import { log } from "./services/logger.js"; import { checkNpmUpdate } from "./services/version-check.js"; @@ -118,7 +118,7 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, ); const recallSearch = CONFIG.dedupeRecallQueries - ? new RecallQueryCache(getRecallCacheScope).wrap( + ? new RecallQueryCache(getDedupeScope).wrap( [tags.canonical, ...tags.personalReads, ...tags.projectReads], searchForRecall, ) diff --git a/src/services/auth.ts b/src/services/auth.ts index 8e6b767..1e65115 100644 --- a/src/services/auth.ts +++ b/src/services/auth.ts @@ -3,7 +3,7 @@ import { join } from "node:path"; import { homedir } from "node:os"; import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { createServer, type Server } from "node:http"; -import { RECALL_QUERIES_FILE } from "./local-dedupe.js"; +import { OPENING_PROMPTS_FILE, RECALL_QUERIES_FILE } from "./local-dedupe.js"; import { openUrl } from "./openUrl.js"; import { PLUGIN_VERSION } from "../version.js"; @@ -462,6 +462,7 @@ export async function settleAuth(): Promise { export async function clearCredentials(): Promise { return withAuthLock(async (remaining) => { fs.rmSync(RECALL_QUERIES_FILE, { force: true }); + fs.rmSync(OPENING_PROMPTS_FILE, { force: true }); const credentials = loadCredentialData(); if (credentials?.type === "oauth" && credentials.refreshToken) { await oauthRequest(issuerEndpoint(credentials.revocationEndpoint, credentials.issuer), { diff --git a/src/services/capture.ts b/src/services/capture.ts index 11bc620..9b3b79e 100644 --- a/src/services/capture.ts +++ b/src/services/capture.ts @@ -1,7 +1,7 @@ import { createHash } from "node:crypto"; import type { Part } from "@opencode-ai/sdk"; -import { CONFIG } from "../config.js"; +import { CONFIG, getDedupeScope } from "../config.js"; import type { ConversationMessage } from "../types/index.js"; import { supermemoryClient } from "./client.js"; import { AGENT_ENTITY_CONTEXT } from "./entity-context.js"; @@ -72,7 +72,7 @@ export interface CaptureOptions { } export function defaultOpeningPromptIndex(): OpeningPromptIndex | null { - return CONFIG.dedupeOpeningPrompt ? new OpeningPromptIndex() : null; + return CONFIG.dedupeOpeningPrompt ? new OpeningPromptIndex(getDedupeScope) : null; } /** Replaces an opening prompt this machine already captured for the tag with a marker. */ diff --git a/src/services/local-dedupe.test.ts b/src/services/local-dedupe.test.ts index 3132f5b..6540afc 100644 --- a/src/services/local-dedupe.test.ts +++ b/src/services/local-dedupe.test.ts @@ -14,8 +14,10 @@ const TASK = "Run the nightly migration task against the staging database, verify every table row count matches the snapshot taken before the run, then write a short report with any mismatches and the exact SQL you used."; describe("local dedupe indexes", () => { - test("sends a long opening prompt once per container tag and keeps the owner session intact", () => { - const index = new OpeningPromptIndex(tempFile("opening.json")); + test("sends a long opening prompt once per credential and container tag and keeps the owner session intact", () => { + let scope: string | null = "backend-a:key-1"; + const file = tempFile("opening.json"); + const index = new OpeningPromptIndex(() => scope, file); const batch = [ { role: "user" as const, content: TASK }, { role: "assistant" as const, content: "Done." }, @@ -33,11 +35,21 @@ describe("local dedupe indexes", () => { expect(repeat.messages[0]?.content).toMatch(/^\[Opening prompt omitted: .*sha256:[0-9a-f]{12}\)\]$/); expect(repeat.messages[1]).toEqual({ role: "assistant", content: "Done again." }); expect(index.prepare("repo_b", "worker-3", batch).messages).toEqual(batch); + expect(statSync(file).mode & 0o777).toBe(0o600); + + scope = "backend-b:key-1"; + expect(index.prepare("repo_a", "worker-4", batch).messages).toEqual(batch); + scope = null; + const anonymous = index.prepare("repo_a", "worker-5", batch); + expect(anonymous.messages).toEqual(batch); + anonymous.commit(); + scope = "backend-a:key-1"; + expect(index.prepare("repo_a", "worker-6", batch).messages).not.toEqual(batch); }); test("leaves short opening prompts and prompts captured over 24 hours ago untouched", () => { let now = 0; - const index = new OpeningPromptIndex(tempFile("opening.json"), () => now); + const index = new OpeningPromptIndex(() => "backend-a:key-1", tempFile("opening.json"), () => now); const short = [{ role: "user" as const, content: "fix the failing tests" }]; index.prepare("repo_a", "worker-1", short).commit(); expect(index.prepare("repo_a", "worker-2", short).messages).toEqual(short); @@ -54,7 +66,7 @@ describe("local dedupe indexes", () => { }); test("an uncommitted capture does not mark the prompt as sent", () => { - const index = new OpeningPromptIndex(tempFile("opening.json")); + const index = new OpeningPromptIndex(() => "backend-a:key-1", tempFile("opening.json")); const batch = [{ role: "user" as const, content: TASK }]; index.prepare("repo_a", "worker-1", batch); expect(index.prepare("repo_a", "worker-2", batch).messages).toEqual(batch); diff --git a/src/services/local-dedupe.ts b/src/services/local-dedupe.ts index 9a862e5..0f95518 100644 --- a/src/services/local-dedupe.ts +++ b/src/services/local-dedupe.ts @@ -52,11 +52,13 @@ function newest(entries: Entries, limit: number, at: (value: T) => number) } /** - * Remembers which session first captured each long opening prompt per container - * tag in the last 24 hours, so repeated one-shot workers do not re-send it. + * Remembers which session first captured each long opening prompt per backend, + * credential and container tag in the last 24 hours, so repeated one-shot workers + * do not re-send it. */ export class OpeningPromptIndex { constructor( + private readonly scope: () => string | null, private readonly file = OPENING_PROMPTS_FILE, private readonly now: () => number = Date.now, ) {} @@ -77,7 +79,9 @@ export class OpeningPromptIndex { if (prompt.length < OPENING_PROMPT_MIN_CHARS) return unchanged; try { - const hash = sha256(`${containerTag}\n${prompt}`); + const scope = this.scope(); + if (!scope) return unchanged; + const hash = sha256([scope, containerTag, prompt].join("\n")); const owner = this.#fresh()[hash]; if (owner && owner.sessionId !== sessionID) { return { diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index 3abe69b..c790d70 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -3,7 +3,7 @@ import { createHash } from "node:crypto"; import type { Plugin } from "@opencode/plugin"; import type { SessionHooks } from "@opencode/plugin/promise/session"; -import { CONFIG, getRecallCacheScope, isConfigured, PLUGIN_VERSION } from "../config.js"; +import { CONFIG, getDedupeScope, isConfigured, PLUGIN_VERSION } from "../config.js"; import { createMemoryActivityReporterFromSink, type MemoryActivityNotice, @@ -152,7 +152,7 @@ const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { checkUpdate: () => checkNpmUpdate("opencode-supermemory", PLUGIN_VERSION, UPDATE_COMMAND), openingPrompts: defaultOpeningPromptIndex(), - recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryCache(getRecallCacheScope) : null, + recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryCache(getDedupeScope) : null, }; /** Minimal shape of an OpenCode 2 event as read from `ctx.event.subscribe()`. */ From 3a2fe543518a108a81e4bec485ce429c75ca22be Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Tue, 24 Nov 2026 22:03:09 +0000 Subject: [PATCH 5/5] chore(release): 2.3.0 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- package.json | 2 +- src/version.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/package.json b/package.json index 2891406..72de33b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-supermemory", - "version": "2.2.0", + "version": "2.3.0", "description": "OpenCode plugin that gives coding agents persistent memory using Supermemory", "type": "module", "main": "dist/index.js", diff --git a/src/version.ts b/src/version.ts index 57237f3..4be058f 100644 --- a/src/version.ts +++ b/src/version.ts @@ -1,3 +1,3 @@ // AUTO-GENERATED by scripts/sync-version.mjs — do not edit by hand. // Sourced from package.json "version" so the two cannot drift. -export const PLUGIN_VERSION = "2.2.0"; +export const PLUGIN_VERSION = "2.3.0";