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
59 changes: 37 additions & 22 deletions packages/opencode/src/plugin/observer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<SessionLearning[]> => {
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
Expand Down Expand Up @@ -493,14 +489,10 @@ class SessionObserverManager {
public async listLearnings(
workspaceDir?: string,
): Promise<Array<SessionLearning & { origin: "global" | "project"; injected: boolean }>> {
// #212: the same row check as a forget, so a malformed row cannot throw in isLive.
const read = async (file?: string): Promise<SessionLearning[]> => {
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)
Expand All @@ -522,11 +514,25 @@ 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<number> {
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, 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"; restored?: boolean }> {
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))
Expand All @@ -538,22 +544,31 @@ 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<string>()
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.
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)
}
return forgotten.size
return { forgotten: forgotten.size }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})
}

Expand Down Expand Up @@ -608,8 +623,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<SessionLearning[] | undefined | "unreadable"> {
let raw: string
Expand Down
13 changes: 10 additions & 3 deletions packages/opencode/src/plugin/synapse.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2041,9 +2041,16 @@ 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 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.'
},
}), synapse_buddy_review: tool({
Expand Down
94 changes: 94 additions & 0 deletions packages/opencode/test/plugin/observer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,100 @@ 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)) {
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
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()
Expand Down
Loading