Skip to content

Commit 4c14c5f

Browse files
fix(workspace): take back a standalone add that a link overtook, and roll back with the create-time account
From Codex round 9, cubic's fourth run and Kilo: - A standalone `datamate-<name>` server connects without the directory lock. If a boundary links the project meanwhile, `add` checks again under the lock afterwards, removes the client and the entry it just wrote, and refuses. - `create` and its rollback use the same credentials, read once before the POST: datamate ids are per tenant, so a credential switch while the request runs must not send the DELETE to another account. `createDatamate` and `deleteDatamate` take optional credentials, as other client calls do. - The race tests' disk check matches `datamate-<name>` entries too. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01HRUhVhg6XwxSKJs1iTufiA
1 parent eb3980f commit 4c14c5f

3 files changed

Lines changed: 112 additions & 28 deletions

File tree

‎packages/opencode/src/altimate/api/client.ts‎

Lines changed: 13 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -311,14 +311,17 @@ export namespace AltimateApi {
311311
return parsed.data.knowledge_bases.filter((d) => d.is_deleted !== true).map((d) => ({ id: d.id, name: d.name }))
312312
}
313313

314-
export async function createDatamate(payload: {
315-
name: string
316-
description?: string
317-
integrations?: Array<{ id: string; tools: Array<{ key: string }> }>
318-
memory_enabled?: boolean
319-
privacy?: string
320-
}) {
321-
const creds = await getCredentials()
314+
export async function createDatamate(
315+
payload: {
316+
name: string
317+
description?: string
318+
integrations?: Array<{ id: string; tools: Array<{ key: string }> }>
319+
memory_enabled?: boolean
320+
privacy?: string
321+
},
322+
creds?: AltimateCredentials,
323+
) {
324+
creds ??= await getCredentials()
322325
const data = await request(creds, "POST", "/datamates/", payload)
323326
// Backend returns { id: number } for create
324327
const id = String(data.id ?? data.datamate?.id)
@@ -341,8 +344,8 @@ export namespace AltimateApi {
341344
return DatamateSummary.parse(raw)
342345
}
343346

344-
export async function deleteDatamate(id: string) {
345-
const creds = await getCredentials()
347+
export async function deleteDatamate(id: string, creds?: AltimateCredentials) {
348+
creds ??= await getCredentials()
346349
await request(creds, "DELETE", `/datamates/${id}`)
347350
}
348351

‎packages/opencode/src/altimate/tools/datamate.ts‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -436,6 +436,18 @@ async function handleAdd(
436436
await addMcpToConfig(serverName, { ...mcpConfig, enabled: true }, configPath)
437437
if (serverName !== DATAMATE_KEY) lock.release() // altimate_change — see the lock above
438438
await MCP.add(serverName, mcpConfig)
439+
// altimate_change start — the connection ran without the lock: if a boundary
440+
// linked the project meanwhile, the entry and its client are taken back out.
441+
if (serverName !== DATAMATE_KEY) {
442+
using _again = await holdDirectoryLock()
443+
const linked = await disablingWorkspace()
444+
if (linked) {
445+
await MCP.remove(serverName).catch(() => {})
446+
await removeMcpFromConfig(serverName, configPath)
447+
return refusal(operation, linked)
448+
}
449+
}
450+
// altimate_change end
439451
}
440452
lock.release() // altimate_change — writes done
441453

@@ -495,14 +507,20 @@ async function handleCreate(args: {
495507
// boundary may have linked the project since the check in `execute`.
496508
const off = await disablingWorkspace()
497509
if (off) return refusal("create", off)
510+
// The account the datamate is created in, kept for deleting it again: ids
511+
// are per tenant, and the credentials can change while the request runs.
512+
const creds = await AltimateApi.getCredentials()
498513
// altimate_change end
499-
const created = await AltimateApi.createDatamate({
500-
name: args.name,
501-
description: args.description,
502-
integrations,
503-
memory_enabled: args.memory_enabled ?? true,
504-
privacy: args.privacy,
505-
})
514+
const created = await AltimateApi.createDatamate(
515+
{
516+
name: args.name,
517+
description: args.description,
518+
integrations,
519+
memory_enabled: args.memory_enabled ?? true,
520+
privacy: args.privacy,
521+
},
522+
creds,
523+
)
506524
// altimate_change start — a link that landed while the datamate was being
507525
// created refuses the add; the datamate is deleted again, so nothing is left
508526
// that this project cannot connect.
@@ -511,7 +529,7 @@ async function handleCreate(args: {
511529
"create",
512530
)
513531
if (!("managedBy" in added.metadata)) return added
514-
const rolledBack = await AltimateApi.deleteDatamate(created.id).then(
532+
const rolledBack = await AltimateApi.deleteDatamate(created.id, creds).then(
515533
() => true,
516534
(err) => {
517535
log.warn("could not delete a datamate created as the project was linked", { id: created.id, err: String(err) })

‎packages/opencode/test/altimate/workspace/datamate-manager-gate.test.ts‎

Lines changed: 73 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -253,14 +253,14 @@ describe("a datamate_manager write that races the link", () => {
253253
calls = []
254254
api.isConfigured = async () => true
255255
api.getDatamate = async () => ({ id: "5", name: "ops" })
256-
api.getCredentials = async () => ({})
256+
api.getCredentials = async () => ({ tenant: "acme" })
257257
api.buildMcpConfig = () => ({ type: "remote", url: "https://mcpserver.example.invalid/sse" })
258-
api.createDatamate = async () => {
259-
calls.push("createDatamate")
258+
api.createDatamate = async (_payload: unknown, creds: { tenant?: string }) => {
259+
calls.push(`createDatamate ${creds?.tenant}`)
260260
return { id: "77", name: "ops" }
261261
}
262-
api.deleteDatamate = async (id: string) => {
263-
calls.push(`deleteDatamate ${id}`)
262+
api.deleteDatamate = async (id: string, creds: { tenant?: string }) => {
263+
calls.push(`deleteDatamate ${id} ${creds?.tenant}`)
264264
}
265265
})
266266
afterEach(() => Object.assign(api, saved))
@@ -280,14 +280,14 @@ describe("a datamate_manager write that races the link", () => {
280280
return { atCall, resume }
281281
}
282282

283-
/** `datamate` entries in any config file the tool could write. */
284-
async function sharedKeyOnDisk(dir: string): Promise<string[]> {
283+
/** Files with a `datamate` or `datamate-<name>` entry, of those the tool could write. */
284+
async function datamateEntriesOnDisk(dir: string): Promise<string[]> {
285285
const found: string[] = []
286286
for (const sub of ["", ".altimate-code", ".opencode"]) {
287287
for (const name of await fs.readdir(path.join(dir, sub)).catch(() => [] as string[])) {
288288
if (!/\.jsonc?$/.test(name)) continue
289289
const text = await fs.readFile(path.join(dir, sub, name), "utf8")
290-
if (/"datamate"\s*:/.test(text)) found.push(path.join(sub, name))
290+
if (/"datamate(?:-[^"]+)?"\s*:/.test(text)) found.push(path.join(sub, name))
291291
}
292292
}
293293
return found
@@ -299,7 +299,7 @@ describe("a datamate_manager write that races the link", () => {
299299
// Linked before the datamate is created: nothing is created.
300300
["create, linked before the POST", { operation: "create", name: "ops" }, "isConfigured", []],
301301
// Linked while it is being created: it is deleted again.
302-
["create, linked during the POST", { operation: "create", name: "ops" }, "createDatamate", ["createDatamate", "deleteDatamate 77"]],
302+
["create, linked during the POST", { operation: "create", name: "ops" }, "createDatamate", ["createDatamate acme", "deleteDatamate 77 acme"]],
303303
]
304304
for (const [label, args, pausedAt, expectedCalls] of rows) {
305305
test(`${label}: started unlinked, refused once a boundary links the project, and nothing is left written`, async () => {
@@ -338,12 +338,75 @@ describe("a datamate_manager write that races the link", () => {
338338
}
339339
expect(mcpCalls).toEqual([])
340340
expect(calls).toEqual(expectedCalls)
341-
expect(await sharedKeyOnDisk(tmp.path)).toEqual([])
341+
expect(await datamateEntriesOnDisk(tmp.path)).toEqual([])
342342
// The workspace engine is still the one connected.
343343
expect(await syncInternals.mcp!.status()).toHaveProperty(DATAMATE_KEY)
344344
})
345345
}
346346

347+
test("a link that lands during a standalone server's connection takes the entry back out", async () => {
348+
await using tmp = await tmpdir()
349+
const state: State = { link: "unlinked" }
350+
arrange(tmp.path, state)
351+
await beforeTurn("ses_a")
352+
let connected!: () => void
353+
const connecting = new Promise<void>((resolve) => (connected = resolve))
354+
let reached!: () => void
355+
const atConnect = new Promise<void>((resolve) => (reached = resolve))
356+
const removed: string[] = []
357+
const add = spyOn(MCP, "add").mockImplementation(async () => {
358+
reached()
359+
await connecting
360+
return {} as Awaited<ReturnType<typeof MCP.add>>
361+
})
362+
const remove = spyOn(MCP, "remove").mockImplementation(async (name) => {
363+
removed.push(name)
364+
})
365+
try {
366+
const result = await Instance.provide({
367+
directory: tmp.path,
368+
fn: async () => {
369+
const call = (await initTool(DatamateManagerTool)).execute({ operation: "add", datamate_id: "5" }, ctx as any)
370+
await atConnect
371+
state.link = "linked"
372+
await beforeTurn("ses_b")
373+
connected()
374+
return call
375+
},
376+
})
377+
expect(result.title).toBe("Datamate add: off in a project linked to a workspace")
378+
expect(removed).toEqual(["datamate-ops"])
379+
expect(await datamateEntriesOnDisk(tmp.path)).toEqual([])
380+
} finally {
381+
connected()
382+
add.mockRestore()
383+
remove.mockRestore()
384+
}
385+
})
386+
387+
test("a raced create is deleted with the account it was created in, after a credential switch", async () => {
388+
await using tmp = await tmpdir()
389+
const state: State = { link: "unlinked" }
390+
arrange(tmp.path, state)
391+
await beforeTurn("ses_a")
392+
const { atCall, resume } = pauseAt("createDatamate")
393+
const result = await Instance.provide({
394+
directory: tmp.path,
395+
fn: async () => {
396+
const call = (await initTool(DatamateManagerTool)).execute({ operation: "create", name: "ops" }, ctx as any)
397+
await atCall
398+
// The user signs into another tenant, and the project is linked, while the POST runs.
399+
api.getCredentials = async () => ({ tenant: "globex" })
400+
state.link = "linked"
401+
await beforeTurn("ses_b")
402+
resume()
403+
return call
404+
},
405+
})
406+
expect(result.title).toBe("Datamate create: off in a project linked to a workspace")
407+
expect(calls).toEqual(["createDatamate acme", "deleteDatamate 77 acme"])
408+
})
409+
347410
test("a standalone server's connection does not hold up the directory's turn boundaries", async () => {
348411
await using tmp = await tmpdir()
349412
arrange(tmp.path, { link: "unlinked" })

0 commit comments

Comments
 (0)