Skip to content

Commit 1a22075

Browse files
anandgupta42claude
andcommitted
fix(learn): tighten recurrence attribution boundaries
- Synthetic continuation user messages no longer count as the corrected request boundary. - An earlier lesson version shown alongside another matching lesson no longer counts as ambiguity evidence for the current text. - Skip signal reads when no session snapshots exist and keep only signals from analyzed sessions. - Look up session history once per correction message. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 43f6b8b commit 1a22075

4 files changed

Lines changed: 46 additions & 6 deletions

File tree

‎packages/opencode/src/altimate/learn/capture.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,11 @@ export interface MessageLike {
9292
time?: { created?: number; completed?: number }
9393
}
9494

95-
export function correctedTurnStart(messages: readonly MessageLike[], messageID: string): number | undefined {
95+
/** Start of the agent's response to the request the correction answers; synthetic continuations are not requests. */
96+
export function correctedTurnStart(messages: readonly (MessageLike & { synthetic?: boolean })[], messageID: string): number | undefined {
9697
const end = messages.findIndex((message) => message.id === messageID && message.role === "user")
9798
if (end < 0) return
98-
const previous = messages.slice(0, end).findLastIndex((message) => message.role === "user")
99+
const previous = messages.slice(0, end).findLastIndex((message) => message.role === "user" && !message.synthetic)
99100
if (previous < 0) return
100101
return messages.slice(previous + 1, end).find((message) => message.role === "assistant")?.time?.created
101102
}
@@ -123,6 +124,7 @@ export class Capture {
123124
private messages = new Map<string, MessageLike>()
124125
private pendingParts = new Map<string, PartLike>()
125126
private sessionsWithAssistant = new Map<string, number>()
127+
private corrected = new Set<string>()
126128
private trackers = new Map<string, ToolRetryTracker>()
127129
private pending = new Set<Promise<unknown>>()
128130

@@ -182,6 +184,9 @@ export class Capture {
182184
const prior = this.sessionsWithAssistant.get(part.sessionID)
183185
const known = prior !== undefined && message.time?.created !== undefined && prior < message.time.created
184186
if (!known && !(await this.deps.hasPriorAssistant(part.sessionID, part.messageID))) return
187+
// Later updates of the same message deduplicate to the first signal; skip their history reads.
188+
if (this.corrected.has(part.messageID)) return
189+
remember(this.corrected, part.messageID, RECENT_ID_CAP)
185190
const start = await this.deps.turnStart?.(part.sessionID, part.messageID).catch((error) => {
186191
log.warn("learn turn start unavailable", { error })
187192
return undefined
@@ -255,7 +260,10 @@ export async function startCapture(ctx: { directory: string; worktree: string })
255260
record: (signal) => appendSignal(root, signal),
256261
turnStart: async (sessionID, messageID) => {
257262
const messages = await Session.messages({ sessionID: SessionID.make(sessionID) })
258-
return correctedTurnStart(messages.map((message) => message.info), messageID)
263+
return correctedTurnStart(messages.map((message) => {
264+
const text = message.parts.filter((part) => part.type === "text")
265+
return { ...message.info, synthetic: text.length > 0 && text.every((part) => part.synthetic) }
266+
}), messageID)
259267
},
260268
hasPriorAssistant: async (sessionID, beforeMessageID) => {
261269
const messages = await Session.messages({ sessionID: SessionID.make(sessionID) })

‎packages/opencode/src/altimate/learn/recurrence.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,14 +76,14 @@ export function attribute(signals: readonly Signal[], snapshots: readonly ShownS
7676
for (const lesson of matches) {
7777
const counts = rows.get(key(lesson.name, lesson.id, lesson.textHash))?.counts
7878
if (!counts) continue
79-
const shown = sessions.get(signal.sessionID)!.filter((entry) => entry.name === lesson.name && entry.id === lesson.id)
79+
const shown = sessions.get(signal.sessionID)!.filter((entry) =>
80+
entry.name === lesson.name && entry.id === lesson.id && entry.textHash === lesson.textHash)
8081
if (!shown.length) continue
8182
if (matches.length > 1) {
8283
counts.ambiguous.add(signal.sessionID)
8384
continue
8485
}
8586
for (const entry of shown) {
86-
if (entry.textHash !== lesson.textHash) continue
8787
const at = Date.parse(entry.at)
8888
const start = Date.parse(signal.turnStartedAt ?? "")
8989
const correction = Date.parse(signal.at)
@@ -115,10 +115,11 @@ export async function analyzeRecurrence(root: string, options: { limit?: number
115115
})
116116
const lessons: NamedLesson[] = []
117117
const signals: Signal[] = []
118+
const sessions = new Set(snapshots.map((snapshot) => snapshot.session))
118119
for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
119120
if (!entry.isDirectory()) continue
120121
try { validateName(entry.name) } catch { continue }
121-
signals.push(...await readSignalsSnapshot(root, entry.name))
122+
if (sessions.size) signals.push(...(await readSignalsSnapshot(root, entry.name)).filter((signal) => sessions.has(signal.sessionID)))
122123
const file = Store.paths(root, entry.name).approved
123124
try {
124125
await SafeFS.assertSafePath(root, file)

‎packages/opencode/test/altimate/learn/capture.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -349,6 +349,28 @@ describe("correction turn start", () => {
349349
expect(correctedTurnStart([history[0], history[3]], "correction")).toBeUndefined()
350350
expect(correctedTurnStart(history.slice(1), "correction")).toBeUndefined()
351351
})
352+
test("a synthetic continuation is not the corrected request's boundary", () => {
353+
const continued = [
354+
history[0], history[1],
355+
{ id: "continue", sessionID: "s", role: "user", synthetic: true, time: { created: 3000 } },
356+
history[2], history[3],
357+
]
358+
expect(correctedTurnStart(continued, "correction")).toBe(2000)
359+
expect(correctedTurnStart(continued.map((m) => ({ ...m, synthetic: false })), "correction")).toBe(4000)
360+
})
361+
test("repeated updates of one correction look up history once", async () => {
362+
let lookups = 0
363+
const capture = new Capture({
364+
hasPriorAssistant: async () => true,
365+
turnStart: async (_, id) => { lookups++; return correctedTurnStart(history, id) },
366+
record: async () => undefined,
367+
})
368+
for (const info of history) capture.onMessage(info)
369+
for (const text of ["No, use UTC", "No, use UTC instead."])
370+
await capture.onPart({ id: "part", messageID: "correction", sessionID: "s", type: "text", text })
371+
await capture.flush()
372+
expect(lookups).toBe(1)
373+
})
352374
test("records the resolved turn start while preserving the eligibility shortcut", async () => {
353375
const recorded: Signals.NewSignal[] = []
354376
let lookups = 0

‎packages/opencode/test/altimate/learn/recurrence.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,15 @@ describe("recurrence attribution", () => {
9393
expect(result.lessons.find((row) => row.name === other.name)?.recurred).toBe(0)
9494
})
9595

96+
test("an earlier version shown with another matching lesson is not ambiguity evidence", () => {
97+
const other = { ...lesson, name: "other-store" }
98+
const shown = snapshot("s1", { textHash: lessonTextHash("Earlier text") })
99+
shown.shown.push({ ...snapshot().shown[0], name: other.name })
100+
const result = run([signal()], [shown], [lesson, other])
101+
expect(result.lessons.find((row) => row.name === lesson.name)).toMatchObject({ ambiguous: 0, earlier_version: 1 })
102+
expect(result.lessons.find((row) => row.name === other.name)).toMatchObject({ ambiguous: 1 })
103+
})
104+
96105
test("earlier lesson version cannot supply current evidence", () => {
97106
expect(run([signal()], [snapshot("s1", { textHash: lessonTextHash("Earlier text") })]).lessons[0])
98107
.toMatchObject({ earlier_version: 1, recurred: 0 })

0 commit comments

Comments
 (0)