Skip to content

Commit 009b932

Browse files
committed
fix(plugin): keep tombstones past the cap and forget both stores atomically
- Trimming now keeps live rules and tombstones under separate caps, so the record limit can no longer evict a tombstone (which would let a merge resurrect the rule). - forgetLearning runs both stores' tombstone writes in one mutation, so a record cannot interleave between them.
1 parent 28a3c12 commit 009b932

2 files changed

Lines changed: 88 additions & 31 deletions

File tree

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

Lines changed: 47 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -310,10 +310,10 @@ class SessionObserverManager {
310310
found.deletedAt = undefined
311311
found.deletedBy = undefined
312312
stored = found
313-
await writeJsonAtomic(file, [found, ...existing.filter((e) => e !== found)].slice(0, 100))
313+
await writeJsonAtomic(file, trimRules([found, ...existing.filter((e) => e !== found)]))
314314
continue
315315
}
316-
await writeJsonAtomic(file, [{ ...entry, scope }, ...existing].slice(0, 100))
316+
await writeJsonAtomic(file, trimRules([{ ...entry, scope }, ...existing]))
317317
} catch {}
318318
}
319319
})
@@ -408,40 +408,42 @@ class SessionObserverManager {
408408
const matches = (l: SessionLearning) => String(l.lesson ?? "").toLowerCase().includes(needle)
409409
const paths = learningStorePaths(workspaceDir)
410410
const files = [paths.global, paths.project].filter((file): file is string => Boolean(file))
411-
const removed = new Set<string>()
412-
for (const file of files) {
413-
for (const key of await this.tombstoneRules(file, matches)) removed.add(key)
414-
}
415-
return removed.size
411+
// One mutation for both stores, so a record cannot interleave between them.
412+
return this.mutate(async () => {
413+
const removed = new Set<string>()
414+
for (const file of files) {
415+
for (const key of await this.applyTombstones(file, matches)) removed.add(key)
416+
}
417+
return removed.size
418+
})
416419
}
417420

418421
/**
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.
422+
* Mark matching live rules as deleted in one store. The rows are kept as
423+
* tombstones so a later merge or sync cannot resurrect them. Non-queuing: the
424+
* caller must already hold the mutation lock. A tombstone is only reported when
425+
* the write landed; a failed write returns nothing.
422426
*/
423-
private tombstoneRules(file: string, matches: (l: SessionLearning) => boolean): Promise<Set<string>> {
424-
return this.mutate(async () => {
425-
const found = new Set<string>()
426-
try {
427-
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
428-
if (!Array.isArray(parsed)) return found
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
437-
}
438-
if (!changed) return found
439-
await writeJsonAtomic(file, rows.slice(0, 100))
440-
} catch {
441-
return new Set<string>()
427+
private async applyTombstones(file: string, matches: (l: SessionLearning) => boolean): Promise<Set<string>> {
428+
const found = new Set<string>()
429+
try {
430+
const parsed = JSON.parse(await fs.readFile(file, "utf8"))
431+
if (!Array.isArray(parsed)) return found
432+
const rows = parsed as SessionLearning[]
433+
let changed = false
434+
for (const row of rows) {
435+
if (!isLive(row) || !matches(row)) continue
436+
row.deletedAt = new Date().toISOString()
437+
row.deletedBy = process.env.USERNAME || process.env.USER || "local"
438+
found.add(learningKey(row))
439+
changed = true
442440
}
443-
return found
444-
})
441+
if (!changed) return found
442+
await writeJsonAtomic(file, trimRules(rows))
443+
} catch {
444+
return new Set<string>()
445+
}
446+
return found
445447
}
446448

447449
public getLatestRetrospectives(): SessionRetrospective[] {
@@ -470,6 +472,20 @@ const learningKey = (l: SessionLearning) => String(l.lesson ?? "").trim().toLowe
470472
/** A rule is live unless it carries a tombstone. */
471473
const isLive = (l: SessionLearning) => !l.deletedAt
472474

475+
const MAX_LIVE_RULES = 100
476+
const MAX_TOMBSTONES = 100
477+
478+
/**
479+
* Bound file size without evicting tombstones: a dropped tombstone would let a
480+
* later merge resurrect the rule it records as deleted.
481+
*/
482+
function trimRules(rows: SessionLearning[]): SessionLearning[] {
483+
return [
484+
...rows.filter(isLive).slice(0, MAX_LIVE_RULES),
485+
...rows.filter((r) => !isLive(r)).slice(0, MAX_TOMBSTONES),
486+
]
487+
}
488+
473489
/** Write JSON via a temp file + rename so a reader never sees a half-written file. */
474490
async function writeJsonAtomic(file: string, rows: SessionLearning[]): Promise<void> {
475491
const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2, 7)}.tmp`

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

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,4 +233,45 @@ describe("rule visibility", () => {
233233
restoreUserProfile(prev)
234234
}
235235
})
236+
237+
test("a tombstone survives the record cap", async () => {
238+
await using home = await tmpdir()
239+
const prev = process.env.USERPROFILE
240+
process.env.USERPROFILE = home.path
241+
try {
242+
const file = path.join(home.path, ".local", "share", "opencode", "learnings.json")
243+
const rows: Array<{
244+
id: string
245+
timestamp: string
246+
lesson: string
247+
source: string
248+
deletedAt?: string
249+
deletedBy?: string
250+
}> = Array.from({ length: 100 }, (_, i) => ({
251+
id: "r" + i,
252+
timestamp: "2026-09-01T00:00:00.000Z",
253+
lesson: "rule " + i,
254+
source: "user_feedback",
255+
}))
256+
rows.push({
257+
id: "dead",
258+
timestamp: "2026-09-01T00:00:00.000Z",
259+
lesson: "tombstoned rule",
260+
source: "user_feedback",
261+
deletedAt: "2026-09-02T00:00:00.000Z",
262+
deletedBy: "test",
263+
})
264+
await fs.mkdir(path.dirname(file), { recursive: true })
265+
await fs.writeFile(file, JSON.stringify(rows), "utf8")
266+
267+
await sessionObserver.recordLearning({ lesson: "one more", source: "user_feedback" })
268+
269+
const after = JSON.parse(await fs.readFile(file, "utf8"))
270+
const tomb = after.find((r: { lesson: string }) => r.lesson === "tombstoned rule")
271+
expect(tomb).toBeDefined()
272+
expect(tomb.deletedAt).toBe("2026-09-02T00:00:00.000Z")
273+
} finally {
274+
restoreUserProfile(prev)
275+
}
276+
})
236277
})

0 commit comments

Comments
 (0)