Skip to content

Commit ed1298a

Browse files
sahrizviclaude
andcommitted
fix(workspace): confirm an existing link on this machine, and sync only to the verified one (review)
- `link --workspace`/`--create` for the workspace already linked records the link as confirmed here instead of returning with it still unconfirmed, so `workspace sync` accepts it - `link`'s pre-check looks up the binding with the same captured credential as the list and the bind - The same-name `--create` no-op runs before the workspace list is fetched, and `--allow-duplicate` skips it - `workspace sync` passes the binding it verified to the memory sweep, which refuses an unconfirmed one, and refuses a link the service could not confirm just now (exit 1) - `workspace unlink` of a project the service already detached still clears local workspace state - `status` says when a "not linked" answer came from the recent-miss cache, when a link is not confirmed on this machine, and when memory could not be read (instead of "off") - A bootstrap failure after the command already reported goes to stderr only; the directory in that message is stripped of control characters - Docs: exit-code bullets merged; `status` details described as available when known - Tests restore the prior `process.exitCode` Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018fJ3X7pcGT4R9yzjsJnqsV
1 parent fea2b04 commit ed1298a

6 files changed

Lines changed: 213 additions & 60 deletions

File tree

‎docs/docs/usage/cli.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,11 +54,10 @@ Workspace features are off unless `ALTIMATE_WORKSPACE=1` is set. With it:
5454

5555
- `altimate-code link` links the current project to a workspace (or creates one). The sidebar then names the workspace and shows how many memories are not yet synced and when skills last synced.
5656
- From a shell, script or CI job, without the TUI:
57-
- `altimate-code link --workspace <name|id>` links to an existing workspace (an id is matched before a name), and `altimate-code link --create [name]` creates one (named after the repo by default) and links to it. Neither prompts. If the project is already linked to a different workspace they refuse unless `--yes` is passed. Running `--create` again when the project is already linked to a workspace of that name changes nothing, so it is safe in a devcontainer's setup command; if another workspace already has that name it refuses and names its id, unless `--allow-duplicate` is passed.
58-
- `altimate-code workspace status [--json]` shows the linked workspace, how many saved memories have not reached it, and when skills last synced.
57+
- `altimate-code link --workspace <name|id>` links to an existing workspace (an id is matched before a name), and `altimate-code link --create [name]` creates one (named after the repo by default) and links to it. Neither prompts. If the project is already linked to a different workspace they refuse unless `--yes` is passed. Running `--create` again when the project is already linked to a workspace of that name creates nothing, so it is safe in a devcontainer's setup command; if another workspace already has that name it refuses and names its id, unless `--allow-duplicate` is passed. Linking to the workspace the project is already linked to confirms that link on this machine, which a fresh clone needs before `workspace sync` sends its memory.
58+
- `altimate-code workspace status [--json]` shows the linked workspace and, when known, how many saved memories have not reached it and when skills last synced.
5959
- `altimate-code workspace refresh` pulls the workspace's skills (memory is loaded by the next session started in the project); `altimate-code workspace sync` sends memory the workspace has not received; `altimate-code workspace unlink [--yes]` detaches the project (`--yes` is required without a terminal).
60-
- Exit codes: `0` done, `1` failed (including when the workspace service could not be reached), `2` needs a different request (not signed in, or `--yes` missing), `3` the project is not linked. With `--json`, `ok` is `true` exactly when the exit code is `0`.
61-
- These commands accept `--directory` and exit `0` on success, `1` on failure, `2` for a request to change (not signed in, or a re-link or unlink without `--yes`), and `3` when the project is not linked.
60+
- These commands accept `--directory`. Exit codes: `0` done, `1` failed (including when the workspace service could not be reached), `2` a request to change (not signed in, a re-link or unlink without `--yes` and no terminal to confirm on, or a `sync` to a link not yet confirmed on this machine), `3` the project is not linked. With `--json`, `ok` is `true` exactly when the exit code is `0`.
6261
- `/workspace` in the TUI opens a menu: **Refresh** pulls the workspace's skills and memory into this project, **Sync** re-sends local memory the workspace never received, **Open in browser** (when a web URL is available) shows the workspace on the web, **Switch workspace** relinks the project, **Unlink** detaches it. In a project that is not linked yet, it offers **Link to a workspace** instead.
6362
- `altimate-code skill publish <name>` uploads a project skill to the linked workspace; see [Skills](../configure/skills.md#cli-commands).
6463
- In an ordinary session the agent is told every turn which workspace the project is linked to — or that none is, or that the link could not be verified just now. In an extension-pinned session it is told the pinned workspace instead, and that it differs from the project's own link. Either way "which workspace am I in?" has an answer, and the agent is told not to confuse it with a Databricks workspace or an IDE workspace folder.

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

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -378,9 +378,9 @@ export { req as altimateRequest }
378378

379379
export namespace WorkspaceApi {
380380
/** Server-authoritative pre-check by git remote. Returns null on 404. */
381-
export async function getBindingForRemote(remote: string): Promise<GetBindingResponse | null> {
381+
export async function getBindingForRemote(remote: string, actAs?: ActAs): Promise<GetBindingResponse | null> {
382382
try {
383-
return await req<GetBindingResponse>("GET", "/by-remote", { query: { repo_remote: remote } })
383+
return await req<GetBindingResponse>("GET", "/by-remote", { query: { repo_remote: remote }, ...(actAs ? { actAs } : {}) })
384384
} catch (err) {
385385
if (err instanceof NotFoundError) return null
386386
throw err
@@ -389,9 +389,9 @@ export namespace WorkspaceApi {
389389

390390
/** Symmetric pre-check by absolute project directory path (for projects
391391
* without a git remote). Returns null on 404. */
392-
export async function getBindingForPath(projectPath: string): Promise<GetBindingResponse | null> {
392+
export async function getBindingForPath(projectPath: string, actAs?: ActAs): Promise<GetBindingResponse | null> {
393393
try {
394-
return await req<GetBindingResponse>("GET", "/by-path", { query: { project_path: projectPath } })
394+
return await req<GetBindingResponse>("GET", "/by-path", { query: { project_path: projectPath }, ...(actAs ? { actAs } : {}) })
395395
} catch (err) {
396396
if (err instanceof NotFoundError) return null
397397
throw err
@@ -403,13 +403,13 @@ export namespace WorkspaceApi {
403403
* picks the right endpoint even if the current identifier's remote has
404404
* changed since the binding was created (M3). Both fields on the
405405
* identifier are optional but at least one must be present. */
406-
export async function getBindingForProject(id: ProjectIdentifier): Promise<ProjectBindingLookup | null> {
406+
export async function getBindingForProject(id: ProjectIdentifier, actAs?: ActAs): Promise<ProjectBindingLookup | null> {
407407
if (id.repoRemote) {
408-
const hit = await getBindingForRemote(id.repoRemote)
408+
const hit = await getBindingForRemote(id.repoRemote, actAs)
409409
if (hit) return { ...hit, matchedBy: "remote" }
410410
}
411411
if (id.projectPath) {
412-
const hit = await getBindingForPath(id.projectPath)
412+
const hit = await getBindingForPath(id.projectPath, actAs)
413413
if (hit) return { ...hit, matchedBy: "path" }
414414
}
415415
return null

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

Lines changed: 32 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,9 @@ export interface StatusReport {
5050
* sidebar, when the service could not be reached. Rendering that as
5151
* 0 would tell the user their memory is current when nobody knows. */
5252
memory: { local: number; unsynced: number | null } | null
53+
/** Set when memory is on but the local store or its index could not be read: `memory` is then null, which
54+
* alone would read as "off". */
55+
memoryUnreadable?: true
5356
skillsEnabled: boolean
5457
/** When workspace skills last synced successfully, or null if they have not in
5558
* this process. Null is genuinely "unknown", not "never" — the store is
@@ -85,7 +88,14 @@ export interface SyncReport {
8588
* and only one of them is the workspace's memory toggle; a toast that said
8689
* "memory is off" for a failed local read sent the user to a setting that was
8790
* fine. */
88-
gatedBecause?: "flag-off" | "no-binding" | "pin-unresolved" | "memory-off" | "read-failed" | "setting-unavailable"
91+
gatedBecause?:
92+
| "flag-off"
93+
| "no-binding"
94+
| "pin-unresolved"
95+
| "memory-off"
96+
| "read-failed"
97+
| "setting-unavailable"
98+
| "not-approved"
8999
sent: number
90100
failed: number
91101
/** Already present in the workspace at their current payload. */
@@ -139,9 +149,11 @@ export async function status(
139149
? await resolveBinding(directory).catch(() => null)
140150
: ((await readLocalBinding(directory).catch(() => null)) ??
141151
(await resolveBinding(directory).catch(() => null)))
152+
const memory = await memoryCounts(directory, binding, opts.poll === true)
142153
return {
143154
binding,
144-
memory: await memoryCounts(directory, binding, opts.poll === true),
155+
memory: memory === "unreadable" ? null : memory,
156+
...(memory === "unreadable" ? { memoryUnreadable: true as const } : {}),
145157
skillsEnabled: SkillSync.isEnabled(),
146158
skillsSyncedAt: await skillsSyncedAt(directory, binding),
147159
}
@@ -223,7 +235,13 @@ export async function refresh(directory: string, sessionID?: string): Promise<Re
223235
* `backfill` is throttled and resumable — blocks already present at their current
224236
* payload are skipped — so running this when there is nothing to do costs an index
225237
* read, not uploads. */
226-
export async function sync(directory: string): Promise<SyncReport> {
238+
export async function sync(
239+
directory: string,
240+
/** A binding the caller has already verified. Used as given rather than re-read from the shared cache, which another
241+
* process can replace between the caller's check and the sweep; one never approved on this machine is refused here,
242+
* where the memory is actually sent. */
243+
opts: { binding?: CachedBinding } = {},
244+
): Promise<SyncReport> {
227245
const gated = (why: NonNullable<SyncReport["gatedBecause"]>): SyncReport => ({
228246
gated: true,
229247
gatedBecause: why,
@@ -240,9 +258,15 @@ export async function sync(directory: string): Promise<SyncReport> {
240258
// unpinned session keeps the cache-only read, and a pin that cannot be honoured stays gated —
241259
// under its own reason, since "nothing is linked" would misdescribe a workspace that exists —
242260
// rather than falling through to the project's link.
243-
const pinned = await resolvePinnedBindingForRouting(directory).catch(() => ({ status: "unknown" as const }))
244-
if (pinned && pinned.status !== "bound") return gated("pin-unresolved")
245-
const binding = pinned ? pinned.binding : await readLocalBinding(directory).catch(() => null)
261+
let binding: CachedBinding | null
262+
if (opts.binding) {
263+
if (opts.binding.adopted) return gated("not-approved")
264+
binding = opts.binding
265+
} else {
266+
const pinned = await resolvePinnedBindingForRouting(directory).catch(() => ({ status: "unknown" as const }))
267+
if (pinned && pinned.status !== "bound") return gated("pin-unresolved")
268+
binding = pinned ? pinned.binding : await readLocalBinding(directory).catch(() => null)
269+
}
246270
if (!binding) return gated("no-binding")
247271

248272
const blocks = await MemoryStore.listAll({ directory }).catch((err) => {
@@ -300,7 +324,7 @@ async function memoryCounts(
300324
directory: string,
301325
binding: CachedBinding | null,
302326
poll: boolean,
303-
): Promise<{ local: number; unsynced: number | null } | null> {
327+
): Promise<{ local: number; unsynced: number | null } | null | "unreadable"> {
304328
if (!MemorySync.isEnabled()) return null
305329
try {
306330
const blocks = await MemoryStore.listAll({ directory })
@@ -317,7 +341,7 @@ async function memoryCounts(
317341
return { local: blocks.length, unsynced: await MemorySync.pendingCount(blocks, binding, { network: false }) }
318342
} catch (err) {
319343
log.warn("could not count local memory for the workspace status", { err: String(err) })
320-
return null
344+
return "unreadable"
321345
}
322346
}
323347

‎packages/opencode/src/cli/cmd/link.ts‎

Lines changed: 54 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -984,8 +984,13 @@ export function matchWorkspace(
984984
/** What `linkHeadless` needs from the service; replaced in tests so its guards can be checked without one. */
985985
export interface LinkHeadlessDeps {
986986
isConfigured(): Promise<boolean>
987-
getBindingForProject(identifier: ProjectIdentifier): Promise<ProjectBindingLookup | null>
987+
getBindingForProject(
988+
identifier: ProjectIdentifier,
989+
actAs: NonNullable<Awaited<ReturnType<typeof WorkspaceApi.captureCredentials>>>,
990+
): Promise<ProjectBindingLookup | null>
988991
captureCredentials(): ReturnType<typeof WorkspaceApi.captureCredentials>
992+
/** Record on this machine that the user approved a link the service already has; no server call. */
993+
approve(identifier: ProjectIdentifier, existing: ProjectBindingLookup): Promise<void>
989994
listDatamates(actAs: NonNullable<Awaited<ReturnType<typeof WorkspaceApi.captureCredentials>>>): Promise<DatamateRef[]>
990995
bindOrRebind(
991996
identifier: ProjectIdentifier,
@@ -1019,12 +1024,21 @@ export async function linkHeadless(
10191024
}
10201025
const identifier = resolveProjectIdentifier(args.directory)
10211026

1027+
// Same rule as the picker: the pre-check, the list and the bind all run as one captured credential, so an
1028+
// account switch in between cannot pair one tenant's link with another tenant's workspace ids.
1029+
const actAs = await deps.captureCredentials()
1030+
if (!actAs) {
1031+
deps.printError("Could not read your Altimate credentials. Check /connect and try again.")
1032+
process.exitCode = 1
1033+
return
1034+
}
1035+
10221036
// Unlike the interactive picker, a failed pre-check stops here: the picker can
10231037
// fall back to retrying a conflict as a re-link, which must not happen without
10241038
// the caller having asked for it.
10251039
let existing: ProjectBindingLookup | null
10261040
try {
1027-
existing = await deps.getBindingForProject(identifier)
1041+
existing = await deps.getBindingForProject(identifier, actAs)
10281042
} catch (err) {
10291043
deps.printError(
10301044
`Could not check which workspace this project is linked to, so nothing was changed: ${stripControlChars(err instanceof Error ? err.message : String(err))}`,
@@ -1034,14 +1048,25 @@ export async function linkHeadless(
10341048
}
10351049
const currentName = existing ? stripControlChars(existing.datamate.name) : undefined
10361050

1037-
// Same rule as the picker: the list and the bind run as one captured credential, so an
1038-
// account switch in between cannot bind a workspace id read from another tenant.
1039-
const actAs = await deps.captureCredentials()
1040-
if (!actAs) {
1041-
deps.printError("Could not read your Altimate credentials. Check /connect and try again.")
1042-
process.exitCode = 1
1051+
// An explicit `link` for the workspace the service already has: record the user's approval here (a fresh clone
1052+
// only knows the link as discovered, which `workspace sync` refuses), without a redundant server rebind.
1053+
const alreadyLinked = async (lookup: ProjectBindingLookup): Promise<void> => {
1054+
await deps.approve(identifier, lookup)
1055+
deps.print(`Already linked to "${stripControlChars(lookup.datamate.name)}" — link confirmed on this machine.`)
1056+
}
1057+
1058+
// Re-running the same `link --create` (a devcontainer rebuild) finds the workspace it made last time; checked
1059+
// before listing workspaces, so a rebuild does not depend on the list being available.
1060+
const createName =
1061+
args.create === undefined
1062+
? undefined
1063+
: args.create.trim() ||
1064+
(identifier.repoRemote ? projectNameFromRemote(identifier.repoRemote) : projectNameFromPath(identifier.projectPath))
1065+
if (createName !== undefined && !args.allowDuplicate && existing && findNamesakes([existing.datamate], createName, undefined).all.length > 0) {
1066+
await alreadyLinked(existing)
10431067
return
10441068
}
1069+
10451070
let list: DatamateRef[]
10461071
try {
10471072
list = await deps.listDatamates(actAs)
@@ -1051,15 +1076,8 @@ export async function linkHeadless(
10511076
return
10521077
}
10531078

1054-
if (args.create !== undefined) {
1055-
const name =
1056-
args.create.trim() ||
1057-
(identifier.repoRemote ? projectNameFromRemote(identifier.repoRemote) : projectNameFromPath(identifier.projectPath))
1058-
// Re-running the same `link --create` (a devcontainer rebuild) finds the workspace it made last time.
1059-
if (existing && findNamesakes([existing.datamate], name, undefined).all.length > 0) {
1060-
deps.print(`Already linked to "${currentName}" — nothing changed.`)
1061-
return
1062-
}
1079+
if (createName !== undefined) {
1080+
const name = createName
10631081
if (existing && !args.yes) {
10641082
deps.printError(`This project is already linked to "${currentName}". Pass --yes to create "${stripControlChars(name)}" and re-link to it.`)
10651083
process.exitCode = EXIT_USAGE
@@ -1097,7 +1115,7 @@ export async function linkHeadless(
10971115
}
10981116
const target = match.workspace
10991117
if (existing?.datamate.id === target.id) {
1100-
deps.print(`Already linked to "${stripControlChars(target.name)}" — nothing changed.`)
1118+
await alreadyLinked(existing)
11011119
return
11021120
}
11031121
if (existing && !args.yes) {
@@ -1111,8 +1129,25 @@ export async function linkHeadless(
11111129
function linkHeadlessDeps(directory: string): LinkHeadlessDeps {
11121130
return {
11131131
isConfigured: () => AltimateApi.isConfigured(),
1114-
getBindingForProject: (identifier) => WorkspaceApi.getBindingForProject(identifier),
1132+
getBindingForProject: (identifier, actAs) => WorkspaceApi.getBindingForProject(identifier, actAs),
11151133
captureCredentials: () => WorkspaceApi.captureCredentials(),
1134+
approve: async (identifier, existing) => {
1135+
// Pinned to the account that confirmed the link: the record is refused if the account changed meanwhile.
1136+
const account = await accountDigest()
1137+
if (account === null) throw new Error("Could not read your Altimate credentials")
1138+
const seed = await recordApprovedBinding(
1139+
identifier.projectPath ?? directory,
1140+
{
1141+
datamateId: existing.datamate.id,
1142+
datamateName: existing.datamate.name,
1143+
repoRemote: existing.binding.repo_remote,
1144+
projectPath: existing.binding.project_path ?? identifier.projectPath ?? null,
1145+
linkedAt: Date.now(),
1146+
},
1147+
{ awaitBackfill: true, account },
1148+
)
1149+
UI.println(seedMessage(seed))
1150+
},
11161151
listDatamates: (actAs) => WorkspaceApi.listDatamates(actAs),
11171152
bindOrRebind: (identifier, datamateId, existing, actAs) => bindOrRebind(identifier, datamateId, existing, true, directory, actAs),
11181153
create: (identifier, name, existing) => createThenBindOrRebind(identifier, name, directory, existing, { openBrowser: false }),

0 commit comments

Comments
 (0)