From 5541164f83672265ec2471b6c78592c435e73e5c Mon Sep 17 00:00:00 2001 From: MaheshtheDev <38828053+MaheshtheDev@users.noreply.github.com> Date: Fri, 13 Nov 2026 08:32:49 +0000 Subject: [PATCH] Scope opening-prompt dedupe to backend and credential and clear it on logout 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()`. */