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
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).


## [0.26.3] - 2026-11-30

### Fixed

- The fuzzy lesson recurrence: a paraphrased re-record no longer loses the heat. Before the exact-title lookup, a live lesson whose title is close enough (Jaccard 0.5, 0.3 with a shared anchored path; negations never merge) has its stored title substituted into the save — the exact-title branch rewrites THAT row (heat+1, endorsements, no new merge path). `distinct: true` forces a new lesson, non-lesson kinds never merge, the save text reports the merge (`merged into …, similarity …, heat …`) and drops the similar-entries suggestion. Calibration fixture: 45 SAME pairs merge, 25 NEAR-MISS pairs stay apart (the scores from the real lessons store).
- The INSERT `expires_at` bound `undefined` (the node:sqlite strict bind rejects it): `?? null`.

## [0.26.2] - 2026-11-30

### Fixed
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ sequenceDiagram
## Safety limits

- Results are capped: at most 50 entries per call, and each body is rendered as a 500-character preview. A tool result has a bounded size whatever the model asks for.
- `memory_save` rewrites an entry that repeats a scope and title instead of stacking duplicates, and purges expired rows.
- `memory_save` rewrites an entry that repeats a scope and title instead of stacking duplicates, and purges expired rows. A paraphrased lesson re-record merges too (0.26.3): a Jaccard-0.5 title match (0.3 with a shared anchored path) substitutes the stored title and heats the existing row — negations never merge, `distinct: true` keeps a new lesson apart, non-lesson kinds never merge.
- `memory_forget` by query only deletes inside the caller's scope (plus the shared `global` scope); by id it trashes the entry wherever it lives, since ids are globally unique. Either way it reports the titles and ids it removed, so a broad query delete is auditable.
- Entries that look like secrets (`sk-…`, `github_pat_…`, `gho_…`, `glpat-…`, `xoxb-…`, webhook URLs, …) are refused, in the title, kind, body and tags alike.

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@log0u7/opencode-memory",
"version": "0.26.2",
"version": "0.26.3",
"description": "Working memory for OpenCode: shared SQLite store with hybrid search, shared across all sessions on a machine.",
"type": "module",
"license": "Apache-2.0",
Expand Down
2 changes: 1 addition & 1 deletion scripts/smoke-dist.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function fail(message) {

// tsc emits ESM with double quotes; `import("x")` is dynamic, `from "x"` and
// `import "x"` are static.
const STATIC_SPEC = /(?:\bfrom\s*|\bimport\s*)(["'])((?:[^"'\\])+)\1/g;
const STATIC_SPEC = /(?:\bfrom\s*|\bimport\s*)(["'])((?:[^"'\\\n])+)\1/g;
const DYNAMIC_SPEC = /\bimport\s*\(\s*(["'])((?:[^"'\\])+)\1\s*\)/g;

// Hosts provide their own plugin API module; it must never be shipped or
Expand Down
10 changes: 8 additions & 2 deletions src/lib/memory-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ export type SaveArgs = {
/** Id of the entry this one replaces: the old row is kept as a superseded
* tombstone instead of stacking a near-duplicate. */
supersedes?: string | undefined;
/** Force a new lesson even when a similar live lesson exists (default false:
* a paraphrase re-records it and heats it). */
distinct?: boolean | undefined;
/** Publish without peer endorsement: the author vouches, and the save records the
* author's own endorsement in `endorsed_by`. */
shareable?: boolean | undefined;
Expand Down Expand Up @@ -141,7 +144,7 @@ export function createMemoryOps(
args.supersedes === undefined
? undefined
: (resolveIdPrefix(getDb(), args.supersedes) ?? args.supersedes);
const { entry, created, superseded } = saveEntry(getDb(), {
const { entry, created, superseded, merged } = saveEntry(getDb(), {
scope,
kind: args.kind,
title: args.title,
Expand All @@ -156,6 +159,7 @@ export function createMemoryOps(
...(supersedes !== undefined ? { supersedes: supersedes } : {}),
...(args.shareable !== undefined ? { shareable: args.shareable } : {}),
...(args.project !== undefined ? { project: args.project } : {}),
...(args.distinct !== undefined ? { distinct: args.distinct } : {}),
});
// Only a row that reached HOT re-injects: rebuilding the inventory changes
// the system prefix and misses the prompt cache, so ordinary lessons reach
Expand All @@ -165,7 +169,9 @@ export function createMemoryOps(
options.onLessonSaved?.();
}
let text = `saved ${entry.id} (${entry.scope}, ${created ? "created" : "updated"})`;
if (superseded !== undefined) {
if (merged) {
text += `saved ${entry.id} (${entry.scope}, merged into ${JSON.stringify(entry.title)}, similarity ${merged.similarity.toFixed(2)}, heat ${entry.heat ?? 0}) - distinct=true keeps a new lesson apart`;
} else if (superseded !== undefined) {
text += `; replaced ${superseded}`;
} else if (args.supersedes === undefined) {
// The store stays pure: without an explicit supersedes the answer only names
Expand Down
176 changes: 172 additions & 4 deletions src/lib/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -256,18 +256,28 @@ function changesOf(db: MemoryDb): number {
/** Whether a save inserted a row or rewrote the one already holding that scope and
* title, so a caller can tell the model what actually happened. `superseded` names the
* entry the save replaced through an explicit `supersedes`. */
export type SaveResult = { entry: Entry; created: boolean; superseded?: string };
export type SaveResult = {
entry: Entry;
created: boolean;
superseded?: string;
/** The fuzzy match the save merged into (the paraphrase re-record). */
merged?: { id: string; similarity: number };
};

export function save(db: MemoryDb, input: EntryInput, options: { now?: number } = {}): Entry {
return saveEntry(db, input, options).entry;
}

export function saveEntry(
db: MemoryDb,
input: EntryInput,
rawInput: EntryInput,
options: { now?: number } = {},
): SaveResult {
validateEntry(input);
validateEntry(rawInput);
// The fuzzy recurrence may rewrite the title (the paraphrase substitutes
// the stored one so the exact-match branch does everything); the input is
// rebound once, before any use.
let input = rawInput;
const scope = canonicalScope(input.scope);
const project = canonicalProject(input.project);
const now = options.now ?? Date.now();
Expand Down Expand Up @@ -307,6 +317,25 @@ export function saveEntry(
// different case is not deduped; and the read-then-write is not transactional, so two
// concurrent saves of the same title can both insert. Ceiling is a rare duplicate, not
// data loss. Upgrade path: a normalized key column plus BEGIN IMMEDIATE.
// The fuzzy recurrence (0.26.3): a paraphrased re-record must not lose the
// heat. Before the exact-title lookup, a close enough LIVE lesson has its
// stored title substituted into the input: the exact-title branch then
// rewrites THAT row (UPDATE, heat+1, endorsements) - no new merge path.
let merged: SaveResult["merged"];
if (input.kind === "lesson" && input.supersedes === undefined && input.distinct !== true) {
const exact = db.conn.get<{ id: string }>(
`SELECT id FROM entries WHERE scope = ? AND lower(trim(title)) = ? AND status = 'current' AND ${LIVE}`,
[scope, input.title.trim().toLowerCase()],
);
if (!exact) {
const match = findSimilarLesson(db, scope, input.title, input.paths ?? []);
if (match) {
input = { ...input, title: match.entry.title };
merged = { id: match.entry.id, similarity: match.similarity };
}
}
}

const existing =
input.supersedes === undefined
? db.conn.get<{ id: string; created_at: number; heat: number; endorsed_by: string | null }>(
Expand Down Expand Up @@ -362,6 +391,7 @@ export function saveEntry(
status: "current",
},
created: false,
...(merged ? { merged } : {}),
};
}

Expand Down Expand Up @@ -392,7 +422,7 @@ export function saveEntry(
JSON.stringify(input.tags),
now,
now,
input.expires_at,
input.expires_at ?? null,
input.source ?? null,
JSON.stringify(input.paths ?? []),
input.commit_sha ?? null,
Expand Down Expand Up @@ -499,6 +529,144 @@ export function isShareable(entry: Entry): boolean {
return (entry.endorsed_by ?? []).some((endorser) => endorserName(endorser) !== entry.source);
}

export const LESSON_MERGE_JACCARD = 0.5;
export const LESSON_MERGE_JACCARD_WITH_PATH = 0.3;

const STOPWORDS = new Set([
// EN
"the",
"an",
"and",
"or",
"of",
"to",
"in",
"on",
"for",
"with",
"is",
"are",
"be",
"it",
"its",
"this",
"that",
"these",
"those",
"by",
"from",
"as",
"at",
"when",
"then",
"than",
"do",
"does",
"into",
"via",
// FR (accents stripped)
"le",
"la",
"les",
"un",
"une",
"des",
"de",
"du",
"et",
"ou",
"en",
"au",
"aux",
"pour",
"par",
"sur",
"dans",
"avec",
"que",
"qui",
"est",
"sont",
"ce",
"cet",
"cette",
"ces",
"se",
"sa",
"son",
"ses",
"il",
"elle",
"on",
"quand",
"puis",
]);
// Negations are NEVER stopwords: "use X" vs "don't use X" must not merge.
const NEGATIONS = new Set([
"not",
"no",
"never",
"don",
"dont",
"doesn",
"didn",
"isn",
"aren",
"avoid",
"without",
"pas",
"jamais",
"ni",
"sans",
"evite",
"eviter",
"ne",
]);

export function titleTokens(title: string): Set<string> {
return new Set(
title
.normalize("NFD")
.replace(/\p{M}/gu, "")
.toLowerCase()
.split(/[^\p{L}\p{N}]+/u)
.filter((t) => t.length > 1 && !STOPWORDS.has(t)),
);
}

function jaccard(a: Set<string>, b: Set<string>): number {
let inter = 0;
for (const t of a) if (b.has(t)) inter += 1;
const union = a.size + b.size - inter;
return union === 0 ? 0 : inter / union;
}

const hasNegation = (tokens: Set<string>): boolean => [...tokens].some((t) => NEGATIONS.has(t));

/** The live lesson a paraphrased title re-records, or null. The Jaccard bar
* drops when an anchored path is shared: the same file = the same context. */
export function findSimilarLesson(
db: MemoryDb,
scope: string,
title: string,
paths: string[],
): { entry: Entry; similarity: number } | null {
const wanted = titleTokens(title);
if (wanted.size === 0) return null;
let best: { entry: Entry; similarity: number } | null = null;
for (const entry of suggestReplacements(db, { scope, kind: "lesson", title }, 10)) {
const tokens = titleTokens(entry.title);
if (hasNegation(tokens) !== hasNegation(wanted)) continue;
const similarity = jaccard(wanted, tokens);
const sharesPath = paths.some((p) => entry.paths?.includes(p) === true);
const bar = sharesPath ? LESSON_MERGE_JACCARD_WITH_PATH : LESSON_MERGE_JACCARD;
if (similarity >= bar && (best === null || similarity > best.similarity)) {
best = { entry, similarity };
}
}
return best;
}

/**
* Candidates an explicit `supersedes` could replace, for saves that do not name one:
* FTS over the title tokens (strict matches first, prefix matches fill the rest), same
Expand Down
6 changes: 6 additions & 0 deletions src/plugin-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,11 @@ export const MemoryV2 = Plugin.define({
description:
"Publish without peer endorsement: the author vouches for the entry (default false)",
},
distinct: {
type: "boolean",
description:
"Force a new lesson even when a similar live lesson exists (default false: a paraphrase re-records it and heats it)",
},
},
required: ["kind", "title", "body"],
additionalProperties: false,
Expand All @@ -267,6 +272,7 @@ export const MemoryV2 = Plugin.define({
paths?: string[];
supersedes?: string;
shareable?: boolean;
distinct?: boolean;
};
// The project scope: the explicit argument when given (the 'global'
// marker clears it), else the session's project.
Expand Down
6 changes: 6 additions & 0 deletions src/plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,12 @@ export const MemoryPlugin: Plugin = async (input, options?: PluginOptions) => {
.describe(
"Publish without peer endorsement: the author vouches for the entry (default false)",
),
distinct: tool.schema
.boolean()
.optional()
.describe(
"Force a new lesson even when a similar live lesson exists (default false: a paraphrase re-records it and heats it)",
),
},
execute: async (args, context) =>
ops.save(
Expand Down
2 changes: 2 additions & 0 deletions src/types/entry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,8 @@ export type EntryInput = {
repo_root?: string;
/** The entry this one replaces (saveEntry validates and marks the old row). */
supersedes?: string;
/** Force a new lesson even when a similar live lesson exists. */
distinct?: boolean;
/** Publish without peer endorsement: the author vouches, and the save records the
* author's own endorsement in `endorsed_by`. */
shareable?: boolean;
Expand Down
Loading