Skip to content

Commit 4323056

Browse files
sahrizviclaude
andcommitted
fix(workspace): a sync only withdraws the known-empty record it wrote (review)
The record now carries a per-write id (`<key>\n<write id>`). A sync that finds the project unlinked after writing removes the record only if it still holds that exact write, so a newer record from another thread's sync survives. Clears on "this workspace has skills" (list seen, snapshot published) only remove a record about that same workspace and account. An unlink still clears unconditionally. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018fJ3X7pcGT4R9yzjsJnqsV
1 parent c600aca commit 4323056

2 files changed

Lines changed: 67 additions & 10 deletions

File tree

‎packages/opencode/src/altimate/workspace/skill-sync.ts‎

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -584,33 +584,57 @@ function emptyRecordPath(canon: string): string {
584584
return path.join(Global.Path.state, "altimate-workspace-empty", id)
585585
}
586586

587-
async function readEmptyRecord(canon: string): Promise<string | null> {
587+
/** The record as written: `<key>\n<write id>`. The write id tells one sync's record from another
588+
* sync's record for the same key, so a sync only ever withdraws the record it wrote itself. */
589+
async function readEmptyRecordRaw(canon: string): Promise<string | null> {
588590
try {
589591
return await fs.readFile(emptyRecordPath(canon), "utf8")
590592
} catch {
591593
return null
592594
}
593595
}
594596

595-
/** Atomic, so a reader in another thread never sees a half-written key. */
596-
async function writeEmptyRecord(canon: string, key: string): Promise<void> {
597+
async function readEmptyRecord(canon: string): Promise<string | null> {
598+
return (await readEmptyRecordRaw(canon))?.split("\n")[0] ?? null
599+
}
600+
601+
/** Atomic, so a reader in another thread never sees a half-written key. Returns the content
602+
* written, for `withdrawEmptyRecord`; null when nothing was written. */
603+
async function writeEmptyRecord(canon: string, key: string): Promise<string | null> {
597604
const file = emptyRecordPath(canon)
598605
const tmp = `${file}.${process.pid}-${REALM_ID}.tmp`
606+
const content = `${key}\n${process.pid}-${REALM_ID}-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`
599607
try {
600608
await fs.mkdir(path.dirname(file), { recursive: true })
601-
await fs.writeFile(tmp, key, { mode: 0o600 })
609+
await fs.writeFile(tmp, content, { mode: 0o600 })
602610
await fs.rename(tmp, file)
611+
return content
603612
} catch (err) {
604613
// Without the record an empty workspace reads "not synced": less precise, never wrong.
605614
log.warn("could not record that the workspace has no skills", { err: String(err) })
606615
await fs.rm(tmp, { force: true }).catch(() => {})
616+
return null
607617
}
608618
}
609619

620+
/** Unconditional: for an unlink, which ends whatever any sync recorded for this project. */
610621
async function clearEmptyRecord(canon: string): Promise<void> {
611622
await fs.rm(emptyRecordPath(canon), { force: true }).catch(() => {})
612623
}
613624

625+
/** Remove the record only while it still holds `content`, so a sync never deletes a newer record
626+
* another thread's sync wrote in the meantime. */
627+
async function withdrawEmptyRecord(canon: string, content: string): Promise<void> {
628+
if ((await readEmptyRecordRaw(canon)) === content) await clearEmptyRecord(canon)
629+
}
630+
631+
/** Remove the record only while it is about workspace `key`: news about one workspace says
632+
* nothing about another's record. */
633+
async function clearEmptyRecordFor(canon: string, key: string): Promise<void> {
634+
const raw = await readEmptyRecordRaw(canon)
635+
if (raw !== null && raw.split("\n")[0] === key) await withdrawEmptyRecord(canon, raw)
636+
}
637+
614638
function emptyKey(accountKey: string, datamateId: number): string {
615639
return `${accountKey}\u0000${datamateId}`
616640
}
@@ -1218,8 +1242,9 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12181242
const account = credentialDigest(creds.altimateUrl, creds.altimateInstanceName, creds.altimateApiKey)
12191243
// A "known empty" record for another link or account no longer describes this project.
12201244
const currentEmptyKey = emptyKey(accountKeyOf(creds.altimateInstanceName, creds.altimateUrl, account), binding.datamateId)
1221-
const recordedEmpty = await readEmptyRecord(canon)
1222-
if (recordedEmpty !== null && recordedEmpty !== currentEmptyKey) await clearEmptyRecord(canon)
1245+
const recordedEmpty = await readEmptyRecordRaw(canon)
1246+
if (recordedEmpty !== null && recordedEmpty.split("\n")[0] !== currentEmptyKey)
1247+
await withdrawEmptyRecord(canon, recordedEmpty)
12231248

12241249
const manifest = await readManifest(canon)
12251250

@@ -1252,7 +1277,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12521277
sawRemote = true
12531278
syncedFor.set(canon, accountKeyOf(creds.altimateInstanceName, creds.altimateUrl, account))
12541279
// The workspace has skills now, even if installing them fails below.
1255-
if (remote.length > 0) await clearEmptyRecord(canon)
1280+
if (remote.length > 0) await clearEmptyRecordFor(canon, currentEmptyKey)
12561281

12571282
if (!foreign && (await upToDate(canon, manifest, remote))) {
12581283
// Remembered for the stamp below, which runs after this block settles.
@@ -1265,12 +1290,13 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12651290

12661291
if (remote.length === 0) {
12671292
await removeManaged(canon)
1268-
await writeEmptyRecord(canon, currentEmptyKey)
1293+
const written = await writeEmptyRecord(canon, currentEmptyKey)
12691294
// Not serialized with an unlink in another thread. An unlink forgets the binding before it
12701295
// clears this record, so confirming the link after the write means an unlink that cleared
12711296
// it first is seen here, and the write is undone rather than outliving the link.
12721297
const after = await resolveBindingOutcome(canon).catch(() => null)
1273-
if (after?.status !== "bound" || after.binding.datamateId !== binding.datamateId) await clearEmptyRecord(canon)
1298+
if (written && (after?.status !== "bound" || after.binding.datamateId !== binding.datamateId))
1299+
await withdrawEmptyRecord(canon, written)
12741300
changed = true
12751301
log.info("workspace has no custom skills; removed the local snapshot")
12761302
return
@@ -1484,7 +1510,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
14841510
throw err
14851511
}
14861512
await fs.rm(retired, { recursive: true, force: true }).catch(() => {})
1487-
await clearEmptyRecord(canon)
1513+
await clearEmptyRecordFor(canon, currentEmptyKey)
14881514
changed = true
14891515
log.info("workspace skills synced", {
14901516
datamateId: binding.datamateId,

‎packages/opencode/test/altimate/workspace/skill-sync.test.ts‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -323,6 +323,37 @@ describe("workspace skill sync", () => {
323323
expect(await snapshotKnownEmpty(project, 1)).toBe(false)
324324
})
325325

326+
test("a sync withdrawing its record after an unlink never deletes a newer sync's record", async () => {
327+
// A writes its record, then finds the project unlinked. Before it withdraws, another
328+
// thread links and syncs a different empty workspace and writes that record. A must leave it.
329+
serve({})
330+
const record = path.join(
331+
Global.Path.state,
332+
"altimate-workspace-empty",
333+
createHash("sha256").update(path.resolve(project)).digest("hex").slice(0, 32),
334+
)
335+
const newer = "another-account\u00002\nwritten-by-another-thread"
336+
const inner = globalThis.fetch
337+
let unlinked = false
338+
let replaced = false
339+
globalThis.fetch = (async (input: string | URL, init?: RequestInit) => {
340+
const url = String(input)
341+
if (!unlinked && url.includes("datamate_id")) {
342+
unlinked = true
343+
unbind()
344+
}
345+
// A's re-check after its write consults the server for the binding: the newer sync lands here.
346+
if (unlinked && !replaced && url.includes("/datamate-project-bindings/by-") && existsSync(record)) {
347+
replaced = true
348+
writeFileSync(record, newer)
349+
}
350+
return inner(input as never, init as never)
351+
}) as unknown as typeof fetch
352+
await syncSkills(project)
353+
expect(replaced).toBe(true)
354+
expect(readFileSync(record, "utf8")).toBe(newer)
355+
})
356+
326357
test("the known-empty record is shared on disk, so another thread's unlink clears it here", async () => {
327358
// Threads do not share `globalThis`. The record must live where an unlink in the TUI thread
328359
// and a sync in the prompt worker both see it: the state directory, not the repository.

0 commit comments

Comments
 (0)