From a3438edd5bcebad6349c0811321df79697245176 Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:06:14 +0000 Subject: [PATCH 1/5] 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> --- src/index.ts | 26 +++++----- src/services/local-dedupe.test.ts | 68 ++++++++++++++++++++----- src/services/local-dedupe.ts | 84 ++++++++++++++++++++++--------- src/services/recall.ts | 4 +- src/v2/runtime.ts | 28 +++++------ 5 files changed, 145 insertions(+), 65 deletions(-) diff --git a/src/index.ts b/src/index.ts index e222379..064b30b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,7 +25,7 @@ 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"; @@ -109,7 +109,17 @@ 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().wrap(tags.canonical, searchForRecall) + : searchForRecall; log("Plugin init", { directory, tags, configured: isConfigured() }); if (!isConfigured()) { @@ -228,14 +238,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 +246,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/local-dedupe.test.ts b/src/services/local-dedupe.test.ts index da0f3d2..1b08db0 100644 --- a/src/services/local-dedupe.test.ts +++ b/src/services/local-dedupe.test.ts @@ -3,17 +3,21 @@ import { mkdtempSync } 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,59 @@ 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 tag within the window and retries failures", async () => { + let now = 0; + const cache = new RecallQueryCache(tempFile("recall.json"), 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", search); + + const first = await repoA("How do we deploy?"); + now = 500; + expect(await repoA("how do we deploy?")).toEqual(first); + expect(calls).toHaveLength(1); + await cache.wrap("repo_b", 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); }); }); diff --git a/src/services/local-dedupe.ts b/src/services/local-dedupe.ts index 7c8d00f..3ab926f 100644 --- a/src/services/local-dedupe.ts +++ b/src/services/local-dedupe.ts @@ -4,6 +4,7 @@ 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; @@ -45,11 +48,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 +69,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 +92,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 +102,58 @@ 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 for a normalized query against one container tag within the window. */ +export class RecallQueryCache { constructor( 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 { + wrap( + containerTag: string, + search: (query: string) => Promise, + ): (query: string) => Promise { + return async (query) => { 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; - } + 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/v2/runtime.ts b/src/v2/runtime.ts index 1cea676..27ea44c 100644 --- a/src/v2/runtime.ts +++ b/src/v2/runtime.ts @@ -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() : null, }; /** Minimal shape of an OpenCode 2 event as read from `ctx.event.subscribe()`. */ @@ -955,20 +955,23 @@ 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, searchForRecall) + : searchForRecall, suppressTexts: isFirstMessage ? profileRequest.then((result) => result?.success && result.profile @@ -976,9 +979,6 @@ export class V2Runtime { : [], ) : undefined, - skipQuery: this.#deps.recallQueries - ? (query) => this.#deps.recallQueries?.isRepeat(tags.canonical, query) ?? false - : undefined, }) : Promise.resolve(skipped); From 6aaa67dc7428fa71e00c54f531d9ad64fa06040d Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:06:14 +0000 Subject: [PATCH 2/5] 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> --- src/services/session-scope.test.ts | 23 ++++++++++++++ src/services/session-scope.ts | 48 +++++++++++++++++++++++++----- 2 files changed, 63 insertions(+), 8 deletions(-) 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; From b623c0f3b797ccb9cc2d684522f3a20dff6028fd Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Thu, 12 Nov 2026 00:06:14 +0000 Subject: [PATCH 3/5] 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> --- CHANGELOG.md | 3 ++- README.md | 42 +++++++++++++++++++++++++++--------------- src/config.ts | 6 +++--- 3 files changed, 32 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 78dc647..4c3cf4b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,8 @@ - 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..2e5cd85 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,20 @@ 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. 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 +364,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 +456,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/src/config.ts b/src/config.ts index 24071ad..3f7e33a 100644 --- a/src/config.ts +++ b/src/config.ts @@ -122,9 +122,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; } From bcb4c5734eb92ebca09d71c9e0aceab4b5a4bf27 Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Thu, 12 Nov 2026 01:54:16 +0000 Subject: [PATCH 4/5] 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> --- README.md | 6 ++++-- src/config.ts | 15 +++++++++++++++ src/index.ts | 7 +++++-- src/services/auth.ts | 2 ++ src/services/local-dedupe.test.ts | 24 +++++++++++++++++++----- src/services/local-dedupe.ts | 21 +++++++++++++++------ src/v2/runtime.ts | 9 ++++++--- 7 files changed, 66 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 2e5cd85..a381b35 100644 --- a/README.md +++ b/README.md @@ -220,8 +220,10 @@ indexes under `~/.supermemory-opencode/` keep those repeats from being re-sent: - **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. Set `SUPERMEMORY_DEDUPE_RECALL_QUERIES=false` to - opt out. + 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. diff --git a/src/config.ts b/src/config.ts index 3f7e33a..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"; @@ -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 064b30b..683a000 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, 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"; @@ -118,7 +118,10 @@ export const SupermemoryPlugin: Plugin = async (ctx: PluginInput) => { { timeoutMs: DIRECT_RECALL_TIMEOUT_MS }, ); const recallSearch = CONFIG.dedupeRecallQueries - ? new RecallQueryCache().wrap(tags.canonical, searchForRecall) + ? new RecallQueryCache(getRecallCacheScope).wrap( + [tags.canonical, ...tags.personalReads, ...tags.projectReads], + searchForRecall, + ) : searchForRecall; log("Plugin init", { directory, tags, configured: isConfigured() }); 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 1b08db0..3132f5b 100644 --- a/src/services/local-dedupe.test.ts +++ b/src/services/local-dedupe.test.ts @@ -1,5 +1,5 @@ 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"; @@ -60,9 +60,11 @@ describe("local dedupe indexes", () => { expect(index.prepare("repo_a", "worker-2", batch).messages).toEqual(batch); }); - test("re-serves a successful recall search per tag within the window and retries failures", async () => { + test("re-serves a successful recall search per credential and tags within the window and retries failures", async () => { let now = 0; - const cache = new RecallQueryCache(tempFile("recall.json"), 1_000, () => now); + 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 => { @@ -71,13 +73,14 @@ describe("local dedupe indexes", () => { ? { success: false, error: "unavailable" } : { success: true, results: [{ id: `m${calls.length}`, memory: "deploy with wrangler" }] }; }; - const repoA = cache.wrap("repo_a", search); + 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); - await cache.wrap("repo_b", search)("How do we deploy?"); + 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; @@ -89,5 +92,16 @@ describe("local dedupe indexes", () => { 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 3ab926f..9a862e5 100644 --- a/src/services/local-dedupe.ts +++ b/src/services/local-dedupe.ts @@ -1,5 +1,5 @@ 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"; @@ -35,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 { @@ -116,20 +120,25 @@ export class OpeningPromptIndex { } } -/** Re-serves the last successful recall search for a normalized query against one container tag within the window. */ +/** 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, ) {} wrap( - containerTag: string, + containerTags: readonly string[], search: (query: string) => Promise, ): (query: string) => Promise { return async (query) => { - const hash = sha256(`${containerTag}\n${query.toLowerCase().replace(/\s+/g, " ").trim()}`); + const scope = this.scope(); + if (!scope) return search(query); + const hash = sha256( + [scope, ...containerTags, query.toLowerCase().replace(/\s+/g, " ").trim()].join("\n"), + ); const cached = this.#fresh()[hash]; if (cached) return cached.response; diff --git a/src/v2/runtime.ts b/src/v2/runtime.ts index 27ea44c..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, @@ -152,7 +152,7 @@ const DEFAULT_DEPENDENCIES: V2RuntimeDependencies = { checkUpdate: () => checkNpmUpdate("opencode-supermemory", PLUGIN_VERSION, UPDATE_COMMAND), openingPrompts: defaultOpeningPromptIndex(), - recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryCache() : null, + recallQueries: CONFIG.dedupeRecallQueries ? new RecallQueryCache(getRecallCacheScope) : null, }; /** Minimal shape of an OpenCode 2 event as read from `ctx.event.subscribe()`. */ @@ -970,7 +970,10 @@ export class V2Runtime { sessionID, cache: this.#recall, search: this.#deps.recallQueries - ? this.#deps.recallQueries.wrap(tags.canonical, searchForRecall) + ? this.#deps.recallQueries.wrap( + [tags.canonical, ...tags.personalReads, ...tags.projectReads], + searchForRecall, + ) : searchForRecall, suppressTexts: isFirstMessage ? profileRequest.then((result) => From c77bee9e1f422e44f03bc2ce793044bd790eaf16 Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Fri, 13 Nov 2026 00:50:52 +0000 Subject: [PATCH 5/5] chore(release): 2.2.0 Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> --- CHANGELOG.md | 2 +- package.json | 2 +- src/version.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c3cf4b..c74ebf9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # 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. 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/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";