From 93392a73c00469e858c36cdd2f15e23bfc3e04c8 Mon Sep 17 00:00:00 2001 From: Igor Jericevich Date: Sun, 18 Oct 2026 03:09:40 +1100 Subject: [PATCH 1/2] fix(opencode): a failed forget puts stores back and says why; rule reads check rows (#212) 1. Partial write: forgetLearning wrote the global store, then a failed project write returned 0 with the global copy already tombstoned. The stores already written are now put back. 2. forgetLearningResult returns why a forget was refused (unreadable or write_failed). synapse_forget_rule no longer says "No rule matched" for a refused forget; it says nothing was changed and the rule may still apply. forgetLearning still returns a count. 3. selectInjected and listLearnings read through readRuleStore, so a store holding a malformed row is skipped instead of throwing in isLive. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/plugin/observer.ts | 51 ++++++----- packages/opencode/src/plugin/synapse.ts | 11 ++- .../opencode/test/plugin/observer.test.ts | 90 +++++++++++++++++++ 3 files changed, 128 insertions(+), 24 deletions(-) diff --git a/packages/opencode/src/plugin/observer.ts b/packages/opencode/src/plugin/observer.ts index f8280d9d5c45..66b5dc38ae78 100644 --- a/packages/opencode/src/plugin/observer.ts +++ b/packages/opencode/src/plugin/observer.ts @@ -447,14 +447,10 @@ class SessionObserverManager { // Always read from disk, from the right stores for THIS workspace. One process // can serve several projects, so no cached list may be reused across them. return this.mutate(async () => { + // #212: the same row check as a forget, so a malformed row cannot throw in isLive. const read = async (file?: string): Promise => { - if (!file) return [] - try { - const parsed = JSON.parse(await fs.readFile(file, "utf8")) - return Array.isArray(parsed) ? (parsed as SessionLearning[]) : [] - } catch { - return [] - } + const rows = file ? await readRuleStore(file) : undefined + return Array.isArray(rows) ? rows : [] } const paths = learningStorePaths(workspaceDir) // Project rules first: a committed, reviewed repo rule outranks an ad-hoc @@ -493,14 +489,10 @@ class SessionObserverManager { public async listLearnings( workspaceDir?: string, ): Promise> { + // #212: the same row check as a forget, so a malformed row cannot throw in isLive. const read = async (file?: string): Promise => { - if (!file) return [] - try { - const parsed = JSON.parse(await fs.readFile(file, "utf8")) - return Array.isArray(parsed) ? (parsed as SessionLearning[]) : [] - } catch { - return [] - } + const rows = file ? await readRuleStore(file) : undefined + return Array.isArray(rows) ? rows : [] } const paths = learningStorePaths(workspaceDir) const global = (await read(paths.global)).filter(isLive) @@ -525,8 +517,20 @@ class SessionObserverManager { * store cannot be read, nothing is changed and 0 is returned (#38). */ public async forgetLearning(lessonText: string, workspaceDir?: string): Promise { + return (await this.forgetLearningResult(lessonText, workspaceDir)).forgotten + } + + /** + * `forgetLearning` with the reason a forget was refused (#212): `unreadable` (a store could not + * be read; nothing was changed) or `write_failed` (a write failed; stores already written were + * put back). A refused forget always reports 0 forgotten. + */ + public async forgetLearningResult( + lessonText: string, + workspaceDir?: string, + ): Promise<{ forgotten: number; refused?: "unreadable" | "write_failed" }> { const needle = lessonText.trim().toLowerCase() - if (!needle) return 0 + if (!needle) return { forgotten: 0 } const matches = (l: SessionLearning) => String(l.lesson ?? "").toLowerCase().includes(needle) const paths = learningStorePaths(workspaceDir) const files = [paths.global, paths.project].filter((file): file is string => Boolean(file)) @@ -538,22 +542,27 @@ class SessionObserverManager { const stores: Array<{ file: string; rows: SessionLearning[] }> = [] for (const file of files) { const read = await readRuleStore(file) - if (read === "unreadable") return 0 + if (read === "unreadable") return { forgotten: 0, refused: "unreadable" as const } if (read) stores.push({ file, rows: read }) } const forgotten = new Set() + const written: Array<{ file: string; before: SessionLearning[] }> = [] for (const store of stores) { + const before = structuredClone(store.rows) const keys = markForgotten(store.rows, matches) if (keys.size === 0) continue try { await writeJsonAtomic(store.file, trimRules(store.rows)) } catch { - // A failed write leaves that copy live; an earlier store may already be written. - return 0 + // #212: one store written and the next not would leave a rule half forgotten; put the + // written stores back (best effort) so a refused forget changes nothing here either. + for (const done of written) await writeJsonAtomic(done.file, done.before).catch(() => {}) + return { forgotten: 0, refused: "write_failed" as const } } + written.push({ file: store.file, before }) for (const key of keys) forgotten.add(key) } - return forgotten.size + return { forgotten: forgotten.size } }) } @@ -608,8 +617,8 @@ const isLive = (l: SessionLearning) => !l.deletedAt /** * One rule store's rows. `undefined`: the store does not exist, which is a real absence. - * `"unreadable"`: any other read error, bad JSON, or JSON that is not an array; we cannot know - * what the store holds. + * `"unreadable"`: any other read error, bad JSON, JSON that is not an array, or a row that is not + * a rule (an object with a string `lesson`); we cannot know what the store holds. */ async function readRuleStore(file: string): Promise { let raw: string diff --git a/packages/opencode/src/plugin/synapse.ts b/packages/opencode/src/plugin/synapse.ts index bd33c47b74c1..b964fee68635 100644 --- a/packages/opencode/src/plugin/synapse.ts +++ b/packages/opencode/src/plugin/synapse.ts @@ -2041,9 +2041,14 @@ export async function SynapseAuthPlugin(input: PluginInput, options?: SynapsePlu async execute(args) { const needle = (args.lesson || "").trim() if (!needle) return "Please provide the rule text to remove." - const removed = await sessionObserver.forgetLearning(needle, input.directory) - return removed > 0 - ? 'Removed ' + removed + ' rule(s) matching "' + needle + '". They will not be applied in future sessions.' + const result = await sessionObserver.forgetLearningResult(needle, input.directory) + // #212: a refused forget is not "no match"; the rule may still be there. + if (result.refused === "unreadable") + return 'Could not remove rules matching "' + needle + '": a rule store could not be read, so nothing was changed. The rule may still apply.' + if (result.refused === "write_failed") + return 'Could not remove rules matching "' + needle + '": a rule store could not be written, so nothing was changed. Try again.' + return result.forgotten > 0 + ? 'Removed ' + result.forgotten + ' rule(s) matching "' + needle + '". They will not be applied in future sessions.' : 'No rule matched "' + needle + '". Use synapse_list_rules to see the recorded rules.' }, }), synapse_buddy_review: tool({ diff --git a/packages/opencode/test/plugin/observer.test.ts b/packages/opencode/test/plugin/observer.test.ts index 4cfddb209927..5ffeb15aa714 100644 --- a/packages/opencode/test/plugin/observer.test.ts +++ b/packages/opencode/test/plugin/observer.test.ts @@ -454,6 +454,96 @@ describe("rule visibility", () => { } }) + test("a refused forget says why: an unreadable store (#212)", async () => { + await using home = await tmpdir() + await using ws = await tmpdir() + const prev = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home.path + try { + await sessionObserver.recordLearning({ lesson: "why refused", source: "user_feedback" }, ws.path) + await fs.writeFile(learningStorePaths(ws.path).project!, "[bad", "utf8") + expect(await sessionObserver.forgetLearningResult("why refused", ws.path)).toEqual({ forgotten: 0, refused: "unreadable" }) + expect(await sessionObserver.forgetLearningResult("no such rule", ws.path)).toEqual({ forgotten: 0, refused: "unreadable" }) + } finally { + restoreTestHome(prev) + } + }) + + // chmod does not stop writes on Windows. + test.skipIf(process.platform === "win32")( + "a forget whose second write fails puts the first store back (#212)", + async () => { + await using home = await tmpdir() + await using ws = await tmpdir() + const prev = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home.path + const projectDir = path.dirname(learningStorePaths(ws.path).project!) + try { + await sessionObserver.recordLearning({ lesson: "roll me back", source: "user_feedback" }, ws.path) + await fs.chmod(projectDir, 0o555) + // Root ignores the mode; then this case cannot be set up here. + const probe = path.join(projectDir, "probe") + if (await fs.writeFile(probe, "x").then(() => true, () => false)) return void (await fs.rm(probe)) + + expect(await sessionObserver.forgetLearningResult("roll me back", ws.path)).toEqual({ + forgotten: 0, + refused: "write_failed", + }) + const global = JSON.parse(await fs.readFile(learningStorePaths().global!, "utf8")) as Array<{ + lesson: string + deletedAt?: string + }> + expect(global.find((l) => l.lesson === "roll me back")?.deletedAt).toBeUndefined() + } finally { + await fs.chmod(projectDir, 0o755).catch(() => {}) + restoreTestHome(prev) + } + }, + ) + + test("listing and injection skip a store with a malformed row instead of throwing (#212)", async () => { + await using home = await tmpdir() + await using ws = await tmpdir() + const prev = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home.path + try { + await sessionObserver.recordLearning({ lesson: "global survives", source: "user_feedback" }) + const project = learningStorePaths(ws.path).project! + await fs.mkdir(path.dirname(project), { recursive: true }) + await fs.writeFile(project, JSON.stringify([null]), "utf8") + + expect((await sessionObserver.listLearnings(ws.path)).map((l) => l.lesson)).toContain("global survives") + expect((await sessionObserver.getRecentLearnings(5, ws.path)).map((l) => l.lesson)).toContain("global survives") + } finally { + restoreTestHome(prev) + } + }) + + test("synapse_forget_rule does not say 'No rule matched' when a store is unreadable (#212)", async () => { + await using home = await tmpdir() + await using ws = await tmpdir() + const prev = process.env.OPENCODE_TEST_HOME + process.env.OPENCODE_TEST_HOME = home.path + try { + await sessionObserver.recordLearning({ lesson: "still here", source: "user_feedback" }, ws.path) + await fs.writeFile(learningStorePaths(ws.path).project!, "[bad", "utf8") + const hooks = await SynapseAuthPlugin({ + client: {} as never, + project: {} as never, + directory: ws.path, + worktree: "", + experimental_workspace: { register() {} }, + serverUrl: new URL("https://example.com"), + $: {} as never, + } as never) + const reply = String(await hooks.tool?.synapse_forget_rule?.execute({ lesson: "still here" }, {} as never)) + expect(reply).toContain("could not be read") + expect(reply).not.toContain("No rule matched") + } finally { + restoreTestHome(prev) + } + }) + test("a rule recorded in a project is mirrored to the global store by design (#38)", async () => { await using home = await tmpdir() await using ws = await tmpdir() From 1f8fdeed08e1e9a9dcc619ba17c866950f0a15c3 Mon Sep 17 00:00:00 2001 From: Igor Jericevich Date: Sun, 18 Oct 2026 03:13:50 +1100 Subject: [PATCH 2/2] fix(opencode): a failed forget's reply says when putting a store back failed too (#212) QA and architect on PR #216: the put-back after a failed write swallowed its own failure, and the tool still said "nothing was changed". forgetLearningResult now reports `restored`; synapse_forget_rule says the rule may be removed in one store only when restored is false. Doc comments say best effort and name the failed-write case. Test lint fix. Co-Authored-By: Claude Opus 5.5 --- packages/opencode/src/plugin/observer.ts | 16 +++++++++++----- packages/opencode/src/plugin/synapse.ts | 4 +++- packages/opencode/test/plugin/observer.test.ts | 6 +++++- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/packages/opencode/src/plugin/observer.ts b/packages/opencode/src/plugin/observer.ts index 66b5dc38ae78..c74733209046 100644 --- a/packages/opencode/src/plugin/observer.ts +++ b/packages/opencode/src/plugin/observer.ts @@ -514,7 +514,8 @@ class SessionObserverManager { * forgotten; a rule present in both stores is counted once. A rule recorded in a project * lives in both stores (see `recordLearning`), so one forget from that workspace removes both * copies; from another workspace only the global copy is reached. If any - * store cannot be read, nothing is changed and 0 is returned (#38). + * store cannot be read, nothing is changed and 0 is returned (#38); if a write fails, the stores + * already written are put back where possible and 0 is returned (#212). */ public async forgetLearning(lessonText: string, workspaceDir?: string): Promise { return (await this.forgetLearningResult(lessonText, workspaceDir)).forgotten @@ -523,12 +524,13 @@ class SessionObserverManager { /** * `forgetLearning` with the reason a forget was refused (#212): `unreadable` (a store could not * be read; nothing was changed) or `write_failed` (a write failed; stores already written were - * put back). A refused forget always reports 0 forgotten. + * put back, best effort: `restored` is false when that put-back failed too, so a rule may be + * half forgotten). A refused forget always reports 0 forgotten. */ public async forgetLearningResult( lessonText: string, workspaceDir?: string, - ): Promise<{ forgotten: number; refused?: "unreadable" | "write_failed" }> { + ): Promise<{ forgotten: number; refused?: "unreadable" | "write_failed"; restored?: boolean }> { const needle = lessonText.trim().toLowerCase() if (!needle) return { forgotten: 0 } const matches = (l: SessionLearning) => String(l.lesson ?? "").toLowerCase().includes(needle) @@ -556,8 +558,12 @@ class SessionObserverManager { } catch { // #212: one store written and the next not would leave a rule half forgotten; put the // written stores back (best effort) so a refused forget changes nothing here either. - for (const done of written) await writeJsonAtomic(done.file, done.before).catch(() => {}) - return { forgotten: 0, refused: "write_failed" as const } + let restored = true + for (const done of written) + await writeJsonAtomic(done.file, done.before).catch(() => { + restored = false + }) + return { forgotten: 0, refused: "write_failed" as const, restored } } written.push({ file: store.file, before }) for (const key of keys) forgotten.add(key) diff --git a/packages/opencode/src/plugin/synapse.ts b/packages/opencode/src/plugin/synapse.ts index b964fee68635..e041ea4fe7de 100644 --- a/packages/opencode/src/plugin/synapse.ts +++ b/packages/opencode/src/plugin/synapse.ts @@ -2046,7 +2046,9 @@ export async function SynapseAuthPlugin(input: PluginInput, options?: SynapsePlu if (result.refused === "unreadable") return 'Could not remove rules matching "' + needle + '": a rule store could not be read, so nothing was changed. The rule may still apply.' if (result.refused === "write_failed") - return 'Could not remove rules matching "' + needle + '": a rule store could not be written, so nothing was changed. Try again.' + return result.restored === false + ? 'Could not remove rules matching "' + needle + '": a rule store could not be written, and putting the other store back failed too, so the rule may now be removed in one store only. Run synapse_list_rules, then try again.' + : 'Could not remove rules matching "' + needle + '": a rule store could not be written, so nothing was changed. Try again.' return result.forgotten > 0 ? 'Removed ' + result.forgotten + ' rule(s) matching "' + needle + '". They will not be applied in future sessions.' : 'No rule matched "' + needle + '". Use synapse_list_rules to see the recorded rules.' diff --git a/packages/opencode/test/plugin/observer.test.ts b/packages/opencode/test/plugin/observer.test.ts index 5ffeb15aa714..48ac289ac171 100644 --- a/packages/opencode/test/plugin/observer.test.ts +++ b/packages/opencode/test/plugin/observer.test.ts @@ -483,11 +483,15 @@ describe("rule visibility", () => { await fs.chmod(projectDir, 0o555) // Root ignores the mode; then this case cannot be set up here. const probe = path.join(projectDir, "probe") - if (await fs.writeFile(probe, "x").then(() => true, () => false)) return void (await fs.rm(probe)) + if (await fs.writeFile(probe, "x").then(() => true, () => false)) { + await fs.rm(probe) + return + } expect(await sessionObserver.forgetLearningResult("roll me back", ws.path)).toEqual({ forgotten: 0, refused: "write_failed", + restored: true, }) const global = JSON.parse(await fs.readFile(learningStorePaths().global!, "utf8")) as Array<{ lesson: string