Skip to content

Commit 28a3c12

Browse files
committed
feat(plugin): tombstone forgotten rules and record their scope
Phase 0 of the central rules design (Alterspective-Intelligence PR anomalyco#1081): - forgetting a rule now marks it deleted (deletedAt/deletedBy) instead of removing the row, so a later merge or sync cannot resurrect it. - each record carries its scope (global | project). - re-recording a forgotten rule revives it in place, without duplicating. - listing and injection ignore tombstoned rows.
1 parent 10337a5 commit 28a3c12

2 files changed

Lines changed: 101 additions & 22 deletions

File tree

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

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -292,6 +292,7 @@ class SessionObserverManager {
292292
let stored = entry
293293
await this.mutate(async () => {
294294
for (const file of files) {
295+
const scope: "global" | "project" = file === paths.project ? "project" : "global"
295296
try {
296297
await fs.mkdir(path.dirname(file), { recursive: true })
297298
let existing: SessionLearning[] = []
@@ -302,13 +303,17 @@ class SessionObserverManager {
302303
const found = existing.find((e) => e.lesson.trim().toLowerCase() === normalizedText)
303304
if (found) {
304305
// Re-recording refreshes recency AND moves the rule to the front, so it
305-
// re-enters the injection window; it never duplicates.
306+
// re-enters the injection window; it never duplicates. It also clears any
307+
// tombstone, which is how a forgotten rule is restored.
306308
found.timestamp = new Date().toISOString()
309+
found.scope = scope
310+
found.deletedAt = undefined
311+
found.deletedBy = undefined
307312
stored = found
308313
await writeJsonAtomic(file, [found, ...existing.filter((e) => e !== found)].slice(0, 100))
309314
continue
310315
}
311-
await writeJsonAtomic(file, [entry, ...existing].slice(0, 100))
316+
await writeJsonAtomic(file, [{ ...entry, scope }, ...existing].slice(0, 100))
312317
} catch {}
313318
}
314319
})
@@ -337,7 +342,7 @@ class SessionObserverManager {
337342
// global note (AIMETH-008 - shared repo facts win). One entry per rule text.
338343
const seen = new Set<string>()
339344
const merged: SessionLearning[] = []
340-
for (const rule of [...(await read(paths.project)), ...(await read(paths.global))]) {
345+
for (const rule of [...(await read(paths.project)), ...(await read(paths.global))].filter(isLive)) {
341346
const key = learningKey(rule)
342347
if (seen.has(key)) continue
343348
seen.add(key)
@@ -379,8 +384,8 @@ class SessionObserverManager {
379384
}
380385
}
381386
const paths = learningStorePaths(workspaceDir)
382-
const global = await read(paths.global)
383-
const project = await read(paths.project)
387+
const global = (await read(paths.global)).filter(isLive)
388+
const project = (await read(paths.project)).filter(isLive)
384389
const globalKeys = new Set(global.map(learningKey))
385390
const merged = [
386391
...global.map((l) => ({ ...l, origin: "global" as const })),
@@ -393,9 +398,9 @@ class SessionObserverManager {
393398
}
394399

395400
/**
396-
* Remove rules whose text matches (case-insensitive substring) from memory and
397-
* from both persisted stores. Returns the number of distinct rules removed; a
398-
* rule present in both stores is counted once.
401+
* Forget rules whose text matches (case-insensitive substring): mark them deleted
402+
* (tombstone) in both persisted stores. Returns the number of distinct rules newly
403+
* forgotten; a rule present in both stores is counted once.
399404
*/
400405
public async forgetLearning(lessonText: string, workspaceDir?: string): Promise<number> {
401406
const needle = lessonText.trim().toLowerCase()
@@ -405,32 +410,33 @@ class SessionObserverManager {
405410
const files = [paths.global, paths.project].filter((file): file is string => Boolean(file))
406411
const removed = new Set<string>()
407412
for (const file of files) {
408-
for (const key of await this.dropRules(file, matches)) removed.add(key)
413+
for (const key of await this.tombstoneRules(file, matches)) removed.add(key)
409414
}
410415
return removed.size
411416
}
412417

413418
/**
414-
* Remove matching rules from one store atomically and count them. A removal is
415-
* only reported when the write landed; a failed write returns nothing and the
416-
* file is left untouched.
419+
* Mark matching live rules as deleted in one store, atomically. The rows are kept
420+
* as tombstones so a later merge or sync cannot resurrect them. A tombstone is only
421+
* reported when the write landed; a failed write returns nothing.
417422
*/
418-
private dropRules(file: string, matches: (l: SessionLearning) => boolean): Promise<Set<string>> {
423+
private tombstoneRules(file: string, matches: (l: SessionLearning) => boolean): Promise<Set<string>> {
419424
return this.mutate(async () => {
420425
const found = new Set<string>()
421426
try {
422427
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
423428
if (!Array.isArray(parsed)) return found
424-
const kept: SessionLearning[] = []
425-
for (const row of parsed as SessionLearning[]) {
426-
if (matches(row)) {
427-
found.add(String(row.lesson ?? "").trim().toLowerCase())
428-
continue
429-
}
430-
kept.push(row)
429+
const rows = parsed as SessionLearning[]
430+
let changed = false
431+
for (const row of rows) {
432+
if (!isLive(row) || !matches(row)) continue
433+
row.deletedAt = new Date().toISOString()
434+
row.deletedBy = process.env.USERNAME || process.env.USER || "local"
435+
found.add(learningKey(row))
436+
changed = true
431437
}
432-
if (found.size === 0) return found
433-
await writeJsonAtomic(file, kept.slice(0, 100))
438+
if (!changed) return found
439+
await writeJsonAtomic(file, rows.slice(0, 100))
434440
} catch {
435441
return new Set<string>()
436442
}
@@ -461,6 +467,9 @@ export function learningStorePaths(workspaceDir?: string): { global?: string; pr
461467

462468
const learningKey = (l: SessionLearning) => String(l.lesson ?? "").trim().toLowerCase()
463469

470+
/** A rule is live unless it carries a tombstone. */
471+
const isLive = (l: SessionLearning) => !l.deletedAt
472+
464473
/** Write JSON via a temp file + rename so a reader never sees a half-written file. */
465474
async function writeJsonAtomic(file: string, rows: SessionLearning[]): Promise<void> {
466475
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 7)}.tmp`
@@ -474,6 +483,11 @@ export interface SessionLearning {
474483
lesson: string
475484
context?: string
476485
source: "user_feedback" | "buddy_review" | "auto_correction" | "session_retro"
486+
/** Which store this row belongs to. */
487+
scope?: "global" | "project"
488+
/** Tombstone: set when the rule is forgotten, so a later merge cannot resurrect it. */
489+
deletedAt?: string
490+
deletedBy?: string
477491
}
478492

479493
export const sessionObserver = new SessionObserverManager()

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

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -168,4 +168,69 @@ describe("rule visibility", () => {
168168
restoreUserProfile(prev)
169169
}
170170
})
171+
172+
test("forgetting keeps the row as a tombstone instead of deleting it", async () => {
173+
await using home = await tmpdir()
174+
const prev = process.env.USERPROFILE
175+
process.env.USERPROFILE = home.path
176+
try {
177+
const file = path.join(home.path, ".local", "share", "opencode", "learnings.json")
178+
await sessionObserver.recordLearning({ lesson: "tombstone me", source: "user_feedback" })
179+
expect(await sessionObserver.forgetLearning("tombstone me")).toBe(1)
180+
181+
expect((await sessionObserver.listLearnings()).find((r) => r.lesson === "tombstone me")).toBeUndefined()
182+
183+
const rows = JSON.parse(await fs.readFile(file, "utf8"))
184+
const row = rows.find((r: { lesson: string }) => r.lesson === "tombstone me")
185+
expect(row).toBeDefined()
186+
expect(typeof row.deletedAt).toBe("string")
187+
expect(row.scope).toBe("global")
188+
} finally {
189+
restoreUserProfile(prev)
190+
}
191+
})
192+
193+
test("re-recording a forgotten rule revives it without duplicating", async () => {
194+
await using home = await tmpdir()
195+
const prev = process.env.USERPROFILE
196+
process.env.USERPROFILE = home.path
197+
try {
198+
const file = path.join(home.path, ".local", "share", "opencode", "learnings.json")
199+
await sessionObserver.recordLearning({ lesson: "revive me", source: "user_feedback" })
200+
expect(await sessionObserver.forgetLearning("revive me")).toBe(1)
201+
expect((await sessionObserver.listLearnings()).find((r) => r.lesson === "revive me")).toBeUndefined()
202+
203+
await sessionObserver.recordLearning({ lesson: "revive me", source: "user_feedback" })
204+
205+
expect((await sessionObserver.listLearnings()).find((r) => r.lesson === "revive me")!.injected).toBe(true)
206+
const rows = JSON.parse(await fs.readFile(file, "utf8"))
207+
const rowsForLesson = rows.filter((r: { lesson: string }) => r.lesson === "revive me")
208+
expect(rowsForLesson.length).toBe(1)
209+
expect(rowsForLesson[0].deletedAt).toBeUndefined()
210+
} finally {
211+
restoreUserProfile(prev)
212+
}
213+
})
214+
215+
test("records the scope of each rule", async () => {
216+
await using home = await tmpdir()
217+
await using ws = await tmpdir()
218+
const prev = process.env.USERPROFILE
219+
process.env.USERPROFILE = home.path
220+
try {
221+
await sessionObserver.recordLearning({ lesson: "global rule", source: "user_feedback" })
222+
await sessionObserver.recordLearning({ lesson: "project rule", source: "user_feedback" }, ws.path)
223+
224+
const global = JSON.parse(
225+
await fs.readFile(path.join(home.path, ".local", "share", "opencode", "learnings.json"), "utf8"),
226+
)
227+
const project = JSON.parse(
228+
await fs.readFile(path.join(ws.path, ".system_generated", "logs", "learnings.json"), "utf8"),
229+
)
230+
expect(global.find((r: { lesson: string }) => r.lesson === "global rule").scope).toBe("global")
231+
expect(project.find((r: { lesson: string }) => r.lesson === "project rule").scope).toBe("project")
232+
} finally {
233+
restoreUserProfile(prev)
234+
}
235+
})
171236
})

0 commit comments

Comments
 (0)