Skip to content

Commit d96803c

Browse files
authored
feat(plugin): expose agent operating rules and allow forgetting them (#32)
* feat(plugin): expose agent operating rules and allow forgetting them Add sessionObserver.listLearnings/forgetLearning plus synapse_list_rules and synapse_forget_rule plugin tools, so users can see which rules an agent follows (and whether each is actually injected) and remove one by text. * fix(plugin): align rule listing with real injection, harden rule writes - Derive injected from the same selection used to build the prompt, so the flag cannot drift from behaviour. - Serialise record and forget writes on a shared store; write via temp file + rename so a crash cannot leave half-written JSON. - Count a removal only after the write lands, and count distinct rules once when a rule exists in both stores. * fix(plugin): key injected rules by text and serialise the injection read - Match the injected set by normalized lesson text: memory and the file can hold the same rule under different ids, which id-matching missed. - Read the injection source through the mutation queue so a read cannot reload a rule a queued forget is still removing. * fix(plugin): merge loaded rules into the injection cache instead of replacing it A rule recorded while the cache-load read was pending was clobbered by the older file contents; merging (deduped by text) keeps both.
1 parent e85de64 commit d96803c

3 files changed

Lines changed: 268 additions & 42 deletions

File tree

‎packages/opencode/src/plugin/observer.ts‎

Lines changed: 152 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -302,59 +302,159 @@ class SessionObserverManager {
302302
this.sessionLearnings.unshift(entry)
303303
if (this.sessionLearnings.length > 100) this.sessionLearnings.pop()
304304

305-
// Persist to central learnings.json with disk-level deduplication
306-
try {
307-
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
308-
if (homeDir) {
309-
const centralDir = path.join(homeDir, ".local", "share", "opencode")
310-
await fs.mkdir(centralDir, { recursive: true })
311-
const centralFile = path.join(centralDir, "learnings.json")
312-
let existing: SessionLearning[] = []
305+
// Persist to the central and workspace stores, serialised against forgetLearning.
306+
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
307+
const files = [
308+
homeDir ? path.join(homeDir, ".local", "share", "opencode", "learnings.json") : undefined,
309+
workspaceDir ? path.join(workspaceDir, ".system_generated", "logs", "learnings.json") : undefined,
310+
].filter((file): file is string => Boolean(file))
311+
await this.mutate(async () => {
312+
for (const file of files) {
313313
try {
314-
existing = JSON.parse(await fs.readFile(centralFile, "utf8"))
314+
await fs.mkdir(path.dirname(file), { recursive: true })
315+
let existing: SessionLearning[] = []
316+
try {
317+
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
318+
if (Array.isArray(parsed)) existing = parsed
319+
} catch {}
320+
if (!existing.some((e) => e.lesson.trim().toLowerCase() === normalizedText)) {
321+
await writeJsonAtomic(file, [entry, ...existing].slice(0, 100))
322+
}
315323
} catch {}
316-
if (!existing.some((e) => e.lesson.trim().toLowerCase() === normalizedText)) {
317-
existing.unshift(entry)
318-
await fs.writeFile(centralFile, JSON.stringify(existing.slice(0, 100), null, 2), "utf8")
319-
}
320324
}
321-
} catch {}
322-
323-
// Persist to workspace if available with deduplication
324-
if (workspaceDir) {
325-
try {
326-
const wsDir = path.join(workspaceDir, ".system_generated", "logs")
327-
await fs.mkdir(wsDir, { recursive: true })
328-
const wsFile = path.join(wsDir, "learnings.json")
329-
let existing: SessionLearning[] = []
330-
try {
331-
existing = JSON.parse(await fs.readFile(wsFile, "utf8"))
332-
} catch {}
333-
if (!existing.some((e) => e.lesson.trim().toLowerCase() === normalizedText)) {
334-
existing.unshift(entry)
335-
await fs.writeFile(wsFile, JSON.stringify(existing.slice(0, 100), null, 2), "utf8")
336-
}
337-
} catch {}
338-
}
325+
})
339326
return entry
340327
}
341328

342-
public async getRecentLearnings(limit = 5): Promise<SessionLearning[]> {
329+
/**
330+
* The rules actually selected for injection, in the same order the prompt
331+
* builder uses. Shared so the listed `injected` flag cannot drift from reality.
332+
*/
333+
private async selectInjected(limit: number): Promise<SessionLearning[]> {
343334
if (this.sessionLearnings.length > 0) {
344335
return this.sessionLearnings.slice(0, limit)
345336
}
346-
try {
347-
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
348-
if (homeDir) {
337+
// Read through the mutation queue: a read that starts while a forget is still
338+
// writing must not reload the store it is about to forget from.
339+
const loaded = await this.mutate(async () => {
340+
try {
341+
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
342+
if (!homeDir) return [] as SessionLearning[]
349343
const centralFile = path.join(homeDir, ".local", "share", "opencode", "learnings.json")
350344
const content = JSON.parse(await fs.readFile(centralFile, "utf8"))
351-
if (Array.isArray(content)) {
352-
this.sessionLearnings = content
353-
return this.sessionLearnings.slice(0, limit)
345+
return Array.isArray(content) ? (content as SessionLearning[]) : []
346+
} catch {
347+
return [] as SessionLearning[]
348+
}
349+
})
350+
if (loaded.length > 0) {
351+
// Merge, never clobber: a rule recorded while the read was pending must not
352+
// be dropped from the cache by the older file contents.
353+
const seen = new Set(loaded.map(learningKey))
354+
this.sessionLearnings = [
355+
...this.sessionLearnings.filter((l) => !seen.has(learningKey(l))),
356+
...loaded,
357+
]
358+
}
359+
return this.sessionLearnings.slice(0, limit)
360+
}
361+
362+
public async getRecentLearnings(limit = 5): Promise<SessionLearning[]> {
363+
return this.selectInjected(limit)
364+
}
365+
366+
private mutation: Promise<unknown> = Promise.resolve()
367+
368+
/** Serialise file mutations so a record and a forget cannot interleave on one file. */
369+
private mutate<T>(fn: () => Promise<T>): Promise<T> {
370+
const run = this.mutation.then(fn, fn)
371+
this.mutation = run.catch(() => {})
372+
return run
373+
}
374+
375+
/**
376+
* Every persisted rule, with where it was found and whether it is one of the
377+
* most-recent rules actually injected into a session's system prompt. This is
378+
* the honest answer to "what rules is the agent using?" - recorded rules that
379+
* fall outside the injection window are shown as `stored`, not `injected`.
380+
*/
381+
public async listLearnings(
382+
workspaceDir?: string,
383+
): Promise<Array<SessionLearning & { origin: "central" | "workspace"; injected: boolean }>> {
384+
const read = async (file: string): Promise<SessionLearning[]> => {
385+
try {
386+
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
387+
return Array.isArray(parsed) ? (parsed as SessionLearning[]) : []
388+
} catch {
389+
return []
390+
}
391+
}
392+
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
393+
const central = homeDir
394+
? await read(path.join(homeDir, ".local", "share", "opencode", "learnings.json"))
395+
: []
396+
const workspace = workspaceDir
397+
? await read(path.join(workspaceDir, ".system_generated", "logs", "learnings.json"))
398+
: []
399+
const centralKeys = new Set(central.map((l) => l.lesson.trim().toLowerCase()))
400+
const merged = [
401+
...central.map((l) => ({ ...l, origin: "central" as const })),
402+
...workspace
403+
.filter((l) => !centralKeys.has(l.lesson.trim().toLowerCase()))
404+
.map((l) => ({ ...l, origin: "workspace" as const })),
405+
].sort((a, b) => (a.timestamp < b.timestamp ? 1 : -1))
406+
const injectedKeys = new Set((await this.selectInjected(INJECTED_LEARNINGS_LIMIT)).map(learningKey))
407+
return merged.map((l) => ({ ...l, injected: injectedKeys.has(learningKey(l)) }))
408+
}
409+
410+
/**
411+
* Remove rules whose text matches (case-insensitive substring) from memory and
412+
* from both persisted stores. Returns the number of distinct rules removed; a
413+
* rule present in both stores is counted once.
414+
*/
415+
public async forgetLearning(lessonText: string, workspaceDir?: string): Promise<number> {
416+
const needle = lessonText.trim().toLowerCase()
417+
if (!needle) return 0
418+
const matches = (l: SessionLearning) => String(l.lesson ?? "").toLowerCase().includes(needle)
419+
this.sessionLearnings = this.sessionLearnings.filter((l) => !matches(l))
420+
const homeDir = process.env.USERPROFILE || process.env.HOME || ""
421+
const files = [
422+
homeDir ? path.join(homeDir, ".local", "share", "opencode", "learnings.json") : undefined,
423+
workspaceDir ? path.join(workspaceDir, ".system_generated", "logs", "learnings.json") : undefined,
424+
].filter((file): file is string => Boolean(file))
425+
const removed = new Set<string>()
426+
for (const file of files) {
427+
for (const key of await this.dropRules(file, matches)) removed.add(key)
428+
}
429+
return removed.size
430+
}
431+
432+
/**
433+
* Remove matching rules from one store atomically and count them. A removal is
434+
* only reported when the write landed; a failed write returns nothing and the
435+
* file is left untouched.
436+
*/
437+
private dropRules(file: string, matches: (l: SessionLearning) => boolean): Promise<Set<string>> {
438+
return this.mutate(async () => {
439+
const found = new Set<string>()
440+
try {
441+
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
442+
if (!Array.isArray(parsed)) return found
443+
const kept: SessionLearning[] = []
444+
for (const row of parsed as SessionLearning[]) {
445+
if (matches(row)) {
446+
found.add(String(row.lesson ?? "").trim().toLowerCase())
447+
continue
448+
}
449+
kept.push(row)
354450
}
451+
if (found.size === 0) return found
452+
await writeJsonAtomic(file, kept.slice(0, 100))
453+
} catch {
454+
return new Set<string>()
355455
}
356-
} catch {}
357-
return []
456+
return found
457+
})
358458
}
359459

360460
public getLatestRetrospectives(): SessionRetrospective[] {
@@ -366,6 +466,18 @@ class SessionObserverManager {
366466
}
367467
}
368468

469+
/** How many of the most-recent rules are injected into a session system prompt. */
470+
export const INJECTED_LEARNINGS_LIMIT = 5
471+
472+
const learningKey = (l: SessionLearning) => String(l.lesson ?? "").trim().toLowerCase()
473+
474+
/** Write JSON via a temp file + rename so a reader never sees a half-written file. */
475+
async function writeJsonAtomic(file: string, rows: SessionLearning[]): Promise<void> {
476+
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 7)}.tmp`
477+
await fs.writeFile(tmp, JSON.stringify(rows, null, 2), "utf8")
478+
await fs.rename(tmp, file)
479+
}
480+
369481
export interface SessionLearning {
370482
id: string
371483
timestamp: string

‎packages/opencode/src/plugin/synapse.ts‎

Lines changed: 46 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ import * as fs from "fs/promises"
66
import open from "open"
77
import { OauthCallbackPage } from "@opencode-ai/core/oauth/page"
88
import { InstallationVersion } from "@opencode-ai/core/installation/version"
9-
import { sessionObserver, sanitizeJsonSchemaForOpenAI } from "./observer"
9+
import { INJECTED_LEARNINGS_LIMIT, sessionObserver, sanitizeJsonSchemaForOpenAI } from "./observer"
1010
import { EscalationTracker, declaredTier, classifyFailure, malformedToolCallFromEvent } from "./synapse-escalation"
1111

1212
export const KEYSTONE_ISSUER = "https://identity.alterspective.com.au"
@@ -1514,7 +1514,51 @@ export async function SynapseAuthPlugin(input: PluginInput, options?: SynapsePlu
15141514
return `✅ Successfully recorded rule: "${args.lesson}". This knowledge is stored and will automatically guide future sessions.`
15151515
},
15161516
}),
1517-
synapse_buddy_review: tool({
1517+
synapse_list_rules: tool({
1518+
description:
1519+
"List the operating rules (learnings) this agent follows, showing where each is stored and whether it is actually injected into the system prompt. Use when the user asks what rules you are following, or to audit a behaviour such as a language preference.",
1520+
args: {},
1521+
async execute() {
1522+
const rules = await sessionObserver.listLearnings(input.directory)
1523+
if (rules.length === 0) return "No operating rules are recorded."
1524+
const injected = rules.filter((r) => r.injected).length
1525+
return [
1526+
injected + " of " + rules.length + " recorded rule(s) are injected into this session (the most recent " + INJECTED_LEARNINGS_LIMIT + ").",
1527+
...rules.map(
1528+
(r, i) =>
1529+
(i + 1) +
1530+
". " +
1531+
(r.injected ? "[injected]" : "[stored] ") +
1532+
" " +
1533+
r.lesson +
1534+
" (source: " +
1535+
r.source +
1536+
", store: " +
1537+
r.origin +
1538+
", recorded: " +
1539+
r.timestamp +
1540+
")",
1541+
),
1542+
].join("\n")
1543+
},
1544+
}),
1545+
synapse_forget_rule: tool({
1546+
description:
1547+
"Remove an operating rule (learning) by matching text, so the agent stops applying it. Use when the user asks to stop doing something previously recorded, e.g. 'stop greeting me in French'.",
1548+
args: {
1549+
lesson: tool.schema
1550+
.string()
1551+
.describe("Text identifying the rule to remove (case-insensitive substring match)."),
1552+
},
1553+
async execute(args) {
1554+
const needle = (args.lesson || "").trim()
1555+
if (!needle) return "Please provide the rule text to remove."
1556+
const removed = await sessionObserver.forgetLearning(needle, input.directory)
1557+
return removed > 0
1558+
? 'Removed ' + removed + ' rule(s) matching "' + needle + '". They will not be applied in future sessions.'
1559+
: 'No rule matched "' + needle + '". Use synapse_list_rules to see the recorded rules.'
1560+
},
1561+
}), synapse_buddy_review: tool({
15181562
description:
15191563
"Run an instant, $0-cost on-premises code review using the Synapse Coder specialist. Checks code snippets or files for syntax errors, SQL injection, broken imports, and security defects.",
15201564
args: {

‎packages/opencode/test/plugin/observer.test.ts‎

Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { describe, expect, test } from "bun:test"
22
import { sessionObserver } from "../../src/plugin/observer"
3+
import * as fs from "fs/promises"
4+
import * as os from "os"
5+
import * as path from "path"
36

47
describe("SessionObserverManager.onToolAfter", () => {
58
test("records a tool call with string output", async () => {
@@ -74,3 +77,70 @@ describe("SessionObserverManager.onToolAfter", () => {
7477
})
7578
})
7679

80+
81+
describe("rule visibility", () => {
82+
// Declared before any other learning test so the observer's in-memory cache is
83+
// still empty and the real "read from file" injection path actually runs.
84+
test("reports the real injection window and counts a rule once across both stores", async () => {
85+
const central = await fs.mkdtemp(path.join(os.tmpdir(), "oc-central-"))
86+
const ws = await fs.mkdtemp(path.join(os.tmpdir(), "oc-ws-"))
87+
const prev = process.env.USERPROFILE
88+
process.env.USERPROFILE = central
89+
const centralFile = path.join(central, ".local", "share", "opencode", "learnings.json")
90+
const wsFile = path.join(ws, ".system_generated", "logs", "learnings.json")
91+
try {
92+
await fs.mkdir(path.dirname(centralFile), { recursive: true })
93+
const rows = Array.from({ length: 7 }, (_, i) => ({
94+
id: "r" + (i + 1),
95+
timestamp: "2026-09-" + String(i + 1).padStart(2, "0") + "T00:00:00.000Z",
96+
lesson: "rule " + (i + 1),
97+
source: "user_feedback",
98+
}))
99+
await fs.writeFile(centralFile, JSON.stringify(rows), "utf8")
100+
await fs.mkdir(path.dirname(wsFile), { recursive: true })
101+
await fs.writeFile(wsFile, JSON.stringify([rows[0]]), "utf8")
102+
103+
const listed = await sessionObserver.listLearnings(ws)
104+
expect(listed.length).toBe(7)
105+
const injected = Object.fromEntries(listed.map((r) => [r.lesson, r.injected]))
106+
expect(injected["rule 1"]).toBe(true)
107+
expect(injected["rule 5"]).toBe(true)
108+
// newest by timestamp, but outside the first-five window the prompt actually uses
109+
expect(injected["rule 6"]).toBe(false)
110+
expect(injected["rule 7"]).toBe(false)
111+
expect(listed.find((r) => r.lesson === "rule 1")!.origin).toBe("central")
112+
113+
expect(await sessionObserver.forgetLearning("rule 1", ws)).toBe(1)
114+
const after = await sessionObserver.listLearnings(ws)
115+
expect(after.map((r) => r.lesson)).not.toContain("rule 1")
116+
expect(await sessionObserver.forgetLearning("rule 1", ws)).toBe(0)
117+
} finally {
118+
process.env.USERPROFILE = prev
119+
await fs.rm(central, { recursive: true, force: true })
120+
await fs.rm(ws, { recursive: true, force: true })
121+
}
122+
})
123+
124+
test("reports a rule injected when memory and the file disagree on its id", async () => {
125+
const dir = await fs.mkdtemp(path.join(os.tmpdir(), "oc-mix-"))
126+
const prev = process.env.USERPROFILE
127+
process.env.USERPROFILE = dir
128+
try {
129+
const file = path.join(dir, ".local", "share", "opencode", "learnings.json")
130+
await fs.mkdir(path.dirname(file), { recursive: true })
131+
await fs.writeFile(
132+
file,
133+
JSON.stringify([{ id: "A", timestamp: "2026-09-23T00:00:00.000Z", lesson: "shared rule", source: "user_feedback" }]),
134+
"utf8",
135+
)
136+
// The same text already exists on disk, so the file keeps id A while memory
137+
// holds a freshly recorded id B. Matching must be by text.
138+
await sessionObserver.recordLearning({ lesson: "shared rule", source: "user_feedback" }, dir)
139+
const listed = await sessionObserver.listLearnings(dir)
140+
expect(listed.find((r) => r.lesson === "shared rule")!.injected).toBe(true)
141+
} finally {
142+
process.env.USERPROFILE = prev
143+
await fs.rm(dir, { recursive: true, force: true })
144+
}
145+
})
146+
})

0 commit comments

Comments
 (0)