Skip to content

Commit b1992aa

Browse files
committed
fix(workspace): skip the seed on a cache warm, label sibling training entries
**A cache warm re-ran the whole seed.** `recordApprovedBinding` started `backfillOnBind` on every call, including flows that only refresh the binding already on disk. That cost a full read of local memory and a round trip per block for no new information — and since `link` now awaits the seed, the user paid it synchronously. The sweep runs only when the workspace or project identity actually changes; an unreadable cache still seeds, because a missed seed is worse than a redundant one. **A sibling project's training entry was injected unlabelled.** `formatBlock` labels a block that came from another project in the workspace, but training blocks go through `formatTrainingEntry`, which did not. `mergeOverlay` deliberately keeps both when a sibling shares an id with this project's block, so the model saw two identical headings it could not tell apart — the exact mis-reading the label exists to prevent. Both mutation-checked, and verified against the live service: the tag and sibling-archive behaviour this depends on round-trips through mem0 intact. Tests: 27 across the two affected files; full suite 11280 pass.
1 parent b03f648 commit b1992aa

4 files changed

Lines changed: 100 additions & 3 deletions

File tree

‎packages/opencode/src/altimate/workspace/state.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,16 @@ export async function readLocalBinding(directory: string): Promise<CachedBinding
201201
return null
202202
}
203203

204+
/** Same workspace and same project identity — i.e. nothing to re-seed.
205+
* ``linkedAt`` is deliberately ignored: it moves on every warm. */
206+
function sameBinding(a: CachedBinding, b: CachedBinding): boolean {
207+
return (
208+
a.datamateId === b.datamateId &&
209+
(a.repoRemote ?? null) === (b.repoRemote ?? null) &&
210+
(a.projectPath ?? null) === (b.projectPath ?? null)
211+
)
212+
}
213+
204214
export async function recordApprovedBinding(
205215
directory: string,
206216
binding: CachedBinding,
@@ -214,15 +224,26 @@ export async function recordApprovedBinding(
214224
// duplicate retries against a workspace that IS bound server-side.
215225
// (cubic round 3.) canonicalizeKey resolves symlinks so writes and reads
216226
// funnel through the same key (macOS ``/tmp`` → ``/private/tmp``).
227+
// Whether this call actually changes the binding. A flow that merely warms
228+
// the cache with the binding already on disk must not trigger a sweep: the
229+
// seed exists for a NEW or CHANGED bind, and re-running it on every warm
230+
// costs a full read of local memory and a round trip per block -- now paid
231+
// synchronously on the `link` path, which awaits the seed.
232+
let bindingChanged = true
217233
try {
218234
const existing = readCache()
219235
const cache: CacheFile =
220236
existing && existing.tenant === key.tenant && existing.apiUrl === key.apiUrl
221237
? existing
222238
: { version: CACHE_VERSION, tenant: key.tenant, apiUrl: key.apiUrl, bindings: {} }
239+
const prior = cache.bindings[canonicalizeKey(directory)]
240+
bindingChanged = !prior || !sameBinding(prior, binding)
223241
cache.bindings[canonicalizeKey(directory)] = binding
224242
writeCache(cache)
225243
} catch (err) {
244+
// An unreadable cache means the prior binding is unknown, so fall back to
245+
// seeding: a missed seed is worse than a redundant one.
246+
bindingChanged = true
226247
log.warn("could not persist workspace binding cache", {
227248
code: (err as NodeJS.ErrnoException)?.code,
228249
err: String(err),
@@ -239,6 +260,7 @@ export async function recordApprovedBinding(
239260
// as a command handler returns (src/index.ts): a detached sweep is killed
240261
// mid-flight there, so a bind that reported success could seed nothing. The
241262
// TUI stays resident and leaves it detached so the dialog closes at once.
263+
if (!bindingChanged) return
242264
const seeded = import("./memory-backfill")
243265
.then((m) => m.backfillOnBind(canonicalizeKey(directory), binding))
244266
.catch((err) => {

‎packages/opencode/src/memory/prompt.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
trainingKind,
1515
parseTrainingMeta,
1616
type TrainingKind,
17+
TRAINING_META_COMMENT,
1718
} from "@/altimate/training/types"
1819
import { TrainingStore } from "@/altimate/training/store"
1920
// altimate_change - workspace memory overlay (read side of the cloud mirror)
@@ -107,13 +108,18 @@ export namespace MemoryPrompt {
107108
}
108109

109110
/** Format a training entry for display (with applied count). */
110-
function formatTrainingEntry(block: MemoryBlock): string {
111+
function formatTrainingEntry(block: MemoryBlock & { origin?: string }): string {
111112
const meta = parseTrainingMeta(block.content)
112113
const appliedStr = meta && meta.applied > 0 ? ` (applied ${meta.applied}x)` : ""
113114
// Strip the training metadata comment from content for display
114-
const content = block.content.replace(/^<!--\s*training\n[\s\S]*?-->\n*/, "").trim()
115+
const content = block.content.replace(TRAINING_META_COMMENT, "").trim()
115116
const name = block.id.split("/").slice(2).join("/") || block.id
116-
return `#### ${name}${appliedStr}\n${content}`
117+
// altimate_change - label a sibling project's entry, exactly as formatBlock
118+
// does. mergeOverlay deliberately keeps both blocks when a sibling shares an
119+
// id with this project's, so without this the model sees two identical
120+
// headings it cannot tell apart — the mis-reading the label exists to stop.
121+
const originStr = block.origin ? ` — from workspace project \`${block.origin}\`` : ""
122+
return `#### ${name}${appliedStr}${originStr}\n${content}`
117123
}
118124

119125
/** Score a block for relevance to the current agent context. */

‎packages/opencode/test/altimate/plugin/workspace.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,56 @@ describe("workspace binding cache", () => {
203203
}
204204
})
205205

206+
test("re-recording an unchanged binding does not re-seed", async () => {
207+
// A flow that merely warms the cache must not sweep: the seed is for a new
208+
// or changed bind. `link` now awaits the seed, so a redundant one is paid
209+
// synchronously by the user.
210+
const ORIGINAL_FLAG = process.env.ALTIMATE_WORKSPACE
211+
process.env.ALTIMATE_WORKSPACE = "1"
212+
const proj = path.join(SANDBOX, "warm-proj")
213+
mkdirSync(path.join(proj, ".altimate-code", "memory"), { recursive: true })
214+
const now = new Date().toISOString()
215+
writeFileSync(
216+
path.join(proj, ".altimate-code", "memory", "warm.md"),
217+
["---", "id: warm", "scope: project", `created: ${now}`, `updated: ${now}`, "---", "", "A fact.", ""].join("\n"),
218+
)
219+
const binding = {
220+
datamateId: 9,
221+
datamateName: "Warm",
222+
repoRemote: null,
223+
projectPath: proj,
224+
linkedAt: 1,
225+
}
226+
227+
let calls = 0
228+
const originalFetch = globalThis.fetch
229+
globalThis.fetch = (async (_input?: unknown, _init?: unknown) => {
230+
calls++
231+
return new Response(JSON.stringify({ datamates: [] }), {
232+
status: 200,
233+
headers: { "Content-Type": "application/json" },
234+
})
235+
}) as typeof fetch
236+
237+
try {
238+
await recordApprovedBinding(proj, binding, { awaitBackfill: true })
239+
const afterFirst = calls
240+
expect(afterFirst).toBeGreaterThan(0)
241+
242+
// Same workspace, same project, later timestamp: a warm, not a rebind.
243+
await recordApprovedBinding(proj, { ...binding, linkedAt: 2 }, { awaitBackfill: true })
244+
expect(calls).toBe(afterFirst)
245+
246+
// A genuine rebind to another workspace must still seed.
247+
await recordApprovedBinding(proj, { ...binding, datamateId: 10 }, { awaitBackfill: true })
248+
expect(calls).toBeGreaterThan(afterFirst)
249+
} finally {
250+
globalThis.fetch = originalFetch
251+
if (ORIGINAL_FLAG === undefined) delete process.env.ALTIMATE_WORKSPACE
252+
else process.env.ALTIMATE_WORKSPACE = ORIGINAL_FLAG
253+
}
254+
})
255+
206256
test("chmods the cache file to 0o600 after write", async () => {
207257
await recordApprovedBinding("/work/proj-a", {
208258
datamateId: 1,

‎packages/opencode/test/memory/overlay-merge.test.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,25 @@ describe("workspace memory in the injected prompt", () => {
171171
expect(injected).not.toContain("REMOTE ONLY")
172172
})
173173

174+
test("a sibling project's training entry is labelled with its origin", async () => {
175+
// mergeOverlay deliberately keeps both when a sibling shares an id with
176+
// this project's block, so an unlabelled entry leaves the model with two
177+
// identical headings it cannot tell apart. formatBlock labels these;
178+
// formatTrainingEntry has to as well.
179+
listResponse = [
180+
remote("training/rule/shared", "Partition by event_date.", {
181+
block_scope: "project",
182+
datamate_id: "7",
183+
repo_remote: "ssh://[email protected]/acme/other.git",
184+
block_tags: '["training","rule"]',
185+
}),
186+
]
187+
await hydrate(SES)
188+
const injected = await MemoryPrompt.inject(20000, { sessionID: SES })
189+
expect(injected).toContain("Partition by event_date.")
190+
expect(injected).toContain("from workspace project")
191+
})
192+
174193
test("a remote training block never drives the local applied counter", async () => {
175194
// incrementApplied writes to the LOCAL store; firing it for a block this
176195
// machine never had would fabricate a file from the cloud copy.

0 commit comments

Comments
 (0)