Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 6 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -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,
)
Expand Down
3 changes: 2 additions & 1 deletion src/services/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -462,6 +462,7 @@ export async function settleAuth(): Promise<void> {
export async function clearCredentials(): Promise<Credentials | null> {
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), {
Expand Down
4 changes: 2 additions & 2 deletions src/services/capture.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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. */
Expand Down
20 changes: 16 additions & 4 deletions src/services/local-dedupe.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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." },
Expand All @@ -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);
Expand All @@ -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);
Expand Down
10 changes: 7 additions & 3 deletions src/services/local-dedupe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,11 +52,13 @@ function newest<T>(entries: Entries<T>, 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,
) {}
Expand All @@ -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 {
Expand Down
4 changes: 2 additions & 2 deletions src/v2/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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()`. */
Expand Down