Skip to content

Commit ba98c93

Browse files
Merge branch 'main' into fix/memory-key-url-forms
Brings in the workspace sync state (#1429), which records what each memory load served, keyed by cloud record id. Resolved in `loadWorkspaceMemory`: the load still serves the newest record per copy key, and the sync-state items are those served records, after the expiry check. Two live records of one block are one item, keyed by the record served. Test: main's "two teammates' blocks with the same block id are two items" listed two global records with one block id. The listing holds only the caller's own records, so that pair is two copies of one block, which this branch serves once. The test now lists two projects' blocks with one block id (still two items), and a new test covers two copies of one block (one item, unchanged once the older copy is archived). Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01LmLXkY5NUqPL7nH2exe9zb
2 parents dd48f2b + 9281c22 commit ba98c93

27 files changed

Lines changed: 3224 additions & 152 deletions

‎.opencode/skills/altimate-setup/SKILL.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
---
22
name: altimate-setup
3-
description: Configure Altimate platform credentials for datamate and API access
3+
description: Configure Altimate platform credentials for API and workspace access
44
---
55

66
# Altimate Setup
@@ -28,4 +28,4 @@ Guide the user through configuring their Altimate platform credentials.
2828
```
2929
Then set permissions to owner-only: `chmod 600 ~/.altimate/altimate.json`
3030

31-
4. **Validate**: Call the `datamate_manager` tool with `operation: "list"` to verify the credentials work. Report success or failure to the user.
31+
4. **Validate**: If the `datamate_manager` tool is available, call it with `operation: "list"` to verify the credentials work, and report success or failure to the user. If it is not (it is turned off in a project linked to an Altimate workspace), ask the user to run `/workspace` → Refresh instead, which calls the Altimate API with these credentials and reports an error if they don't work.

‎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: 95 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,9 @@ import { Instance } from "../../project/instance"
1515
import { Global } from "../../global"
1616
import { Log } from "@/altimate/util/log"
1717
import { DATAMATE_KEY, DATAMATE_PROVENANCE, readDatamateTransportFromIde, TRANSPORT_IDENTITY_FIELDS } from "../datamate-transport"
18-
// altimate_change - workspace mode owns the datamate key
19-
import { managedWorkspaceLoaded } from "../workspace/engine-overlay"
18+
// altimate_change - in a project linked to a workspace the tool is off
19+
import { disablingWorkspace, refusal } from "../workspace/datamate-manager-gate"
20+
import { holdDirectoryLock } from "../workspace/engine-overlay"
2021
// altimate_change - extension-type rows depend on a live IDE bridge
2122
import { liveBridge } from "../workspace/engine-probes"
2223

@@ -79,6 +80,14 @@ export const DatamateManagerTool = Tool.define("datamate_manager", {
7980
.describe("Server name to remove (for 'remove'). Use 'list-config' or 'status' to find names."),
8081
}),
8182
async execute(args): Promise<{ title: string; metadata: Record<string, unknown>; output: string }> {
83+
// altimate_change start — a linked project gets its integrations from the
84+
// workspace's own engine only. The tool is kept out of the model's catalog
85+
// there (datamate-manager-gate.ts); this covers callers that run it
86+
// directly. Every operation is refused before anything is looked up or
87+
// written, so the refusal does not depend on the API being reachable.
88+
const workspace = await disablingWorkspace()
89+
if (workspace) return refusal(args.operation, workspace)
90+
// altimate_change end
8291
if (args.operation !== "status" && args.operation !== "list-config") {
8392
const configured = await AltimateApi.isConfigured()
8493
if (!configured) {
@@ -238,7 +247,10 @@ function mergeRefreshedEntry(
238247
return Object.assign(merged, mcpConfig, { enabled: true }, updatedAtField, provenanceFields)
239248
}
240249

241-
async function handleAdd(args: { datamate_id?: string; name?: string; scope?: "project" | "global" }) {
250+
async function handleAdd(
251+
args: { datamate_id?: string; name?: string; scope?: "project" | "global" },
252+
operation = "add",
253+
) {
242254
if (!args.datamate_id) {
243255
return {
244256
title: "Datamate add: FAILED",
@@ -251,26 +263,6 @@ async function handleAdd(args: { datamate_id?: string; name?: string; scope?: "p
251263
// reuse the same process the extension already manages, not a second one.
252264
const transport = await readDatamateTransportFromIde(projectRoot())
253265

254-
// altimate_change start — in workspace mode the shared `datamate` key is the
255-
// bound workspace's own engine, derived at config load. The add goes under
256-
// that key on two routes — an IDE transport, or an explicit `name` of
257-
// "datamate" — and both are refused, with the reason, before anything is
258-
// looked up: the refusal must not depend on the API being reachable.
259-
// Standalone `datamate-<name>` entries are a different key and stay the user's.
260-
const wantsManagedKey = transport !== null || args.name === DATAMATE_KEY
261-
const managed = wantsManagedKey ? await managedWorkspaceLoaded() : null
262-
if (managed) {
263-
return {
264-
title: `Datamate add: '${DATAMATE_KEY}' is managed by workspace "${managed.name}"`,
265-
metadata: { serverName: DATAMATE_KEY, managedBy: managed.id, datamateId: args.datamate_id },
266-
output:
267-
`This project is linked to workspace "${managed.name}", whose integrations are served by the ` +
268-
`workspace's own engine under the '${DATAMATE_KEY}' MCP server. Adding datamate '${args.datamate_id}' ` +
269-
`there is not applied. Unlink the project, or restart with ALTIMATE_DISABLE_WORKSPACE=1, to manage that entry by hand.`,
270-
}
271-
}
272-
// altimate_change end
273-
274266
const datamate = await AltimateApi.getDatamate(args.datamate_id)
275267

276268
if (transport !== null) {
@@ -314,6 +306,18 @@ async function handleAdd(args: { datamate_id?: string; name?: string; scope?: "p
314306
const isGlobal = args.scope === "global"
315307
const configPath = await resolveConfigPath(isGlobal ? Global.Path.config : projectRoot(), isGlobal)
316308

309+
// altimate_change start — checked again for the writes below, under the
310+
// directory's turn-boundary lock: a boundary that linked the project while
311+
// the lookups above ran must not have its engine's key replaced, nor a
312+
// second route saved beside it. Released once the writes are done (the
313+
// connection checks after them need no lock), and before a standalone
314+
// server's connection; a live client under the shared key is started under
315+
// it, as a boundary starts the engine's, or it could replace the engine's.
316+
using lock = await holdDirectoryLock()
317+
const off = await disablingWorkspace()
318+
if (off) return refusal(operation, off)
319+
// altimate_change end
320+
317321
if (transport !== null) {
318322
// IDE/extension mode: check if DATAMATE_KEY is already wired up.
319323
// updatedAt is disk-only (the runtime config schema has no such field); the
@@ -366,6 +370,7 @@ async function handleAdd(args: { datamate_id?: string; name?: string; scope?: "p
366370
configPath,
367371
})
368372
}
373+
lock.release() // altimate_change — writes done
369374
const mcpTools = await MCP.tools()
370375
const toolCount = Object.keys(mcpTools).filter((k) =>
371376
k.startsWith(DATAMATE_KEY + "_"),
@@ -428,9 +433,31 @@ async function handleAdd(args: { datamate_id?: string; name?: string; scope?: "p
428433
serverName,
429434
type: mcpConfig.type,
430435
})
436+
// altimate_change start — the entry this add replaces, put back if a link overtakes it (below)
437+
const prior = serverName !== DATAMATE_KEY ? await readMcpEntryFromDisk(serverName, configPath) : undefined
438+
// altimate_change end
431439
await addMcpToConfig(serverName, { ...mcpConfig, enabled: true }, configPath)
440+
if (serverName !== DATAMATE_KEY) lock.release() // altimate_change — see the lock above
432441
await MCP.add(serverName, mcpConfig)
442+
// altimate_change start — the connection ran without the lock: if a boundary
443+
// linked the project meanwhile, the add is undone — its client stopped and
444+
// the entry it replaced (or none) put back, then that entry's client, if
445+
// enabled, started again outside the lock.
446+
if (serverName !== DATAMATE_KEY) {
447+
using again = await holdDirectoryLock()
448+
const linked = await disablingWorkspace()
449+
if (linked) {
450+
await MCP.remove(serverName).catch(() => {})
451+
if (prior) await addMcpToConfig(serverName, prior, configPath)
452+
else await removeMcpFromConfig(serverName, configPath)
453+
again.release()
454+
if (prior && prior.enabled !== false) await MCP.add(serverName, prior).catch(() => {})
455+
return refusal(operation, linked)
456+
}
457+
}
458+
// altimate_change end
433459
}
460+
lock.release() // altimate_change — writes done
434461

435462
// Check connection status
436463
const allStatus = await MCP.status()
@@ -481,34 +508,48 @@ async function handleCreate(args: {
481508
}
482509
}
483510
try {
484-
// altimate_change start — with an IDE transport the add that follows would go
485-
// under the shared `datamate` key; in workspace mode that add is refused, so
486-
// refuse here before creating an API datamate nothing would connect to.
487-
if ((await readDatamateTransportFromIde(projectRoot())) !== null) {
488-
const managedKey = await managedWorkspaceLoaded()
489-
if (managedKey) {
490-
return {
491-
title: `Datamate create: '${DATAMATE_KEY}' is managed by workspace "${managedKey.name}"`,
492-
metadata: { serverName: DATAMATE_KEY, managedBy: managedKey.id },
493-
output:
494-
`This project is linked to workspace "${managedKey.name}", whose integrations are served by the ` +
495-
`workspace's own engine under the '${DATAMATE_KEY}' MCP server. Creating datamate '${args.name}' ` +
496-
`here would not connect it. Unlink the project, or restart with ALTIMATE_DISABLE_WORKSPACE=1, first.`,
497-
}
498-
}
499-
}
500-
// altimate_change end
501511
const integrations = args.integration_ids
502512
? await AltimateApi.resolveIntegrations(args.integration_ids)
503513
: undefined
504-
const created = await AltimateApi.createDatamate({
505-
name: args.name,
506-
description: args.description,
507-
integrations,
508-
memory_enabled: args.memory_enabled ?? true,
509-
privacy: args.privacy,
510-
})
511-
return handleAdd({ datamate_id: created.id, name: `datamate-${slugify(args.name)}`, scope: args.scope })
514+
// altimate_change start — checked again before the datamate is created: a
515+
// boundary may have linked the project since the check in `execute`.
516+
const off = await disablingWorkspace()
517+
if (off) return refusal("create", off)
518+
// The account the datamate is created in, kept for deleting it again: ids
519+
// are per tenant, and the credentials can change while the request runs.
520+
const creds = await AltimateApi.getCredentials()
521+
// altimate_change end
522+
const created = await AltimateApi.createDatamate(
523+
{
524+
name: args.name,
525+
description: args.description,
526+
integrations,
527+
memory_enabled: args.memory_enabled ?? true,
528+
privacy: args.privacy,
529+
},
530+
creds,
531+
)
532+
// altimate_change start — a link that landed while the datamate was being
533+
// created refuses the add; the datamate is deleted again, so nothing is left
534+
// that this project cannot connect.
535+
const added = await handleAdd(
536+
{ datamate_id: created.id, name: `datamate-${slugify(args.name)}`, scope: args.scope },
537+
"create",
538+
)
539+
if (!("managedBy" in added.metadata)) return added
540+
const rolledBack = await AltimateApi.deleteDatamate(created.id, creds).then(
541+
() => true,
542+
(err) => {
543+
log.warn("could not delete a datamate created as the project was linked", { id: created.id, err: String(err) })
544+
return false
545+
},
546+
)
547+
if (rolledBack) return added
548+
return {
549+
...added,
550+
output: `${added.output}\n\nOne exception: the datamate '${args.name}' (ID: ${created.id}) had already been created in your Altimate account and could not be deleted again; delete it there if it is not wanted.`,
551+
}
552+
// altimate_change end
512553
} catch (e) {
513554
return {
514555
title: "Datamate create: ERROR",
@@ -660,21 +701,12 @@ async function handleRemove(args: { server_name?: string; scope?: "project" | "g
660701
}
661702
}
662703
try {
663-
// altimate_change start — the workspace-managed `datamate` key is not the
664-
// user's to remove either: it would stop the engine under a turn and delete
665-
// the entry that unlinking hands back. Standalone `datamate-<name>` entries
666-
// are unaffected.
667-
const managedKey = args.server_name === DATAMATE_KEY ? await managedWorkspaceLoaded() : null
668-
if (managedKey) {
669-
return {
670-
title: `Datamate remove: '${DATAMATE_KEY}' is managed by workspace "${managedKey.name}"`,
671-
metadata: { serverName: DATAMATE_KEY, managedBy: managedKey.id },
672-
output:
673-
`This project is linked to workspace "${managedKey.name}", whose integrations are served by the ` +
674-
`workspace's own engine under the '${DATAMATE_KEY}' MCP server. It is not removed. Unlink the project, ` +
675-
`or restart with ALTIMATE_DISABLE_WORKSPACE=1, to manage that entry by hand.`,
676-
}
677-
}
704+
// altimate_change start — checked again, under the directory's turn-boundary
705+
// lock, for the removal below: a boundary that linked the project since the
706+
// check at the top of `execute` must not have its engine's key removed.
707+
using _lock = await holdDirectoryLock()
708+
const off = await disablingWorkspace()
709+
if (off) return refusal("remove", off)
678710
// altimate_change end
679711
// Fully remove from runtime state (disconnect + purge from MCP list)
680712
// altimate_change start — MCP.remove (was disconnect): delete the status entry + publish

‎packages/opencode/src/altimate/tools/tool-lookup.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { Effect } from "effect"
33
import type { JSONSchema7, JSONSchema7Definition } from "@ai-sdk/provider"
44
import { Tool } from "../../tool/tool"
55
import { ToolRegistry } from "../../tool/registry"
6+
import { hiddenToolIds } from "../workspace/datamate-manager-gate"
67

78
export const ToolLookupTool = Tool.define("tool_lookup", {
89
description:
@@ -12,7 +13,10 @@ export const ToolLookupTool = Tool.define("tool_lookup", {
1213
tool_name: z.string().describe("Exact tool ID (e.g., 'sql_analyze', 'altimate_core_migration')"),
1314
}),
1415
async execute(args) {
15-
const infos = await ToolRegistry.allInfos()
16+
// A tool turned off for this project is not described either: a lookup that
17+
// finds it invites a call the model's catalog no longer carries.
18+
const hidden = await hiddenToolIds()
19+
const infos = (await ToolRegistry.allInfos()).filter((t) => !hidden.has(t.id))
1620
const info = infos.find((t) => t.id === args.tool_name)
1721
if (!info) {
1822
const ids = infos.map((t) => t.id).sort()

0 commit comments

Comments
 (0)