Skip to content

Commit 3a88c4d

Browse files
sahrizviclaude
andcommitted
fix(workspace): outage is not "not linked", sanitize names, idempotent link --create, handler tests (review)
Consensus review fixes: status/refresh/sync/unlink resolve the link first (service unreachable exits 1, a confirmed unlink exits 3); sync refuses an adopted link; names stripped of control characters; unlink that leaves skills behind exits 1; `--json` ok matches exit 0; `link --create` is a no-op when already linked to that name and refuses an existing namesake unless `--allow-duplicate`; headless create does not open a browser; `workspace` recorded in telemetry; handler-level tests. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018fJ3X7pcGT4R9yzjsJnqsV
1 parent 544c333 commit 3a88c4d

5 files changed

Lines changed: 523 additions & 145 deletions

File tree

‎docs/docs/usage/cli.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,10 @@ Workspace features are off unless `ALTIMATE_WORKSPACE=1` is set. With it:
5353

5454
- `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.
5555
- From a shell, script or CI job, without the TUI:
56-
- `altimate-code link --workspace <name|id>` links to an existing workspace, 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.
56+
- `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.
5757
- `altimate-code workspace status [--json]` shows the linked workspace, how many saved memories have not reached it, and when skills last synced.
58-
- `altimate-code workspace refresh` pulls the workspace's skills and memory; `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).
58+
- `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).
59+
- 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`.
5960
- 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.
6061
- `/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.
6162
- `altimate-code skill publish <name>` uploads a project skill to the linked workspace; see [Skills](../configure/skills.md#cli-commands).

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

Lines changed: 104 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,7 @@ export const LinkCommand = cmd({
196196
// altimate_change start — non-interactive link for scripts, devcontainers and CI
197197
.option("workspace", {
198198
alias: "w",
199-
describe: "Link to this existing workspace (name or id) without prompting",
199+
describe: "Link to this existing workspace without prompting: an id, or an exact name (an id is matched first)",
200200
type: "string",
201201
})
202202
.option("create", {
@@ -208,12 +208,23 @@ export const LinkCommand = cmd({
208208
describe: "Allow replacing an existing link when --workspace or --create is used",
209209
type: "boolean",
210210
default: false,
211+
})
212+
.option("allow-duplicate", {
213+
describe: "With --create, create the workspace even if one with that name already exists",
214+
type: "boolean",
215+
default: false,
211216
}),
212217
// altimate_change end
213218
handler: async (args) => {
214219
// altimate_change start — non-interactive link
215220
if (args.workspace !== undefined || args.create !== undefined) {
216-
await linkHeadless({ directory: args.directory, workspace: args.workspace, create: args.create, yes: args.yes })
221+
await linkHeadless({
222+
directory: args.directory,
223+
workspace: args.workspace,
224+
create: args.create,
225+
yes: args.yes,
226+
allowDuplicate: args["allow-duplicate"],
227+
})
217228
return
218229
}
219230
// altimate_change end
@@ -568,6 +579,8 @@ export async function createThenBindOrRebind(
568579
name: string,
569580
directory: string,
570581
existing: ProjectBindingLookup | null,
582+
/** False for a headless run: print the manage URL, but there is nobody at a browser to look at it. */
583+
opts: { openBrowser?: boolean } = {},
571584
): Promise<void> {
572585
// The account this bind acts as; the seed refuses (account-changed) if it switches mid-way.
573586
// Unreadable credentials cannot link anyway, and must not leave the bind unguarded.
@@ -714,7 +727,9 @@ export async function createThenBindOrRebind(
714727
// delegates to the OS handler, so a rogue value could launch an unrelated
715728
// application. Log a warning and skip the auto-open rather than trusting
716729
// whatever protocol the URL parses to.
717-
if (isSafeHttpUrl(manageUrl)) {
730+
if (opts.openBrowser === false) {
731+
// printed above; nothing to open
732+
} else if (isSafeHttpUrl(manageUrl)) {
718733
await open(manageUrl).catch(() => undefined)
719734
} else {
720735
prompts.log.warn(`Skipped auto-open: manage_url is not an http/https URL.`)
@@ -966,14 +981,39 @@ export function matchWorkspace(
966981
return { kind: "none" }
967982
}
968983

969-
async function linkHeadless(args: { directory: string; workspace?: string; create?: string; yes: boolean }): Promise<void> {
984+
/** What `linkHeadless` needs from the service; replaced in tests so its guards can be checked without one. */
985+
export interface LinkHeadlessDeps {
986+
isConfigured(): Promise<boolean>
987+
getBindingForProject(identifier: ProjectIdentifier): Promise<ProjectBindingLookup | null>
988+
captureCredentials(): ReturnType<typeof WorkspaceApi.captureCredentials>
989+
listDatamates(actAs: NonNullable<Awaited<ReturnType<typeof WorkspaceApi.captureCredentials>>>): Promise<DatamateRef[]>
990+
bindOrRebind(
991+
identifier: ProjectIdentifier,
992+
datamateId: number,
993+
existing: ProjectBindingLookup | null,
994+
actAs: NonNullable<Awaited<ReturnType<typeof WorkspaceApi.captureCredentials>>>,
995+
): Promise<void>
996+
create(identifier: ProjectIdentifier, name: string, existing: ProjectBindingLookup | null): Promise<void>
997+
print(line: string): void
998+
printError(line: string): void
999+
}
1000+
1001+
export async function linkHeadless(
1002+
args: { directory: string; workspace?: string; create?: string; yes: boolean; allowDuplicate?: boolean },
1003+
deps: LinkHeadlessDeps = linkHeadlessDeps(args.directory),
1004+
): Promise<void> {
9701005
if (args.workspace !== undefined && args.create !== undefined) {
971-
UI.error("Use either --workspace or --create, not both.")
1006+
deps.printError("Use either --workspace or --create, not both.")
1007+
process.exitCode = EXIT_USAGE
1008+
return
1009+
}
1010+
if (args.workspace !== undefined && !args.workspace.trim()) {
1011+
deps.printError("--workspace needs a workspace id or name.")
9721012
process.exitCode = EXIT_USAGE
9731013
return
9741014
}
975-
if (!(await AltimateApi.isConfigured())) {
976-
UI.error("Not signed in to Altimate. Run altimate-code, sign in, then re-run `altimate-code link`.")
1015+
if (!(await deps.isConfigured())) {
1016+
deps.printError("Not signed in to Altimate. Run altimate-code, sign in, then re-run `altimate-code link`.")
9771017
process.exitCode = EXIT_USAGE
9781018
return
9791019
}
@@ -984,70 +1024,100 @@ async function linkHeadless(args: { directory: string; workspace?: string; creat
9841024
// the caller having asked for it.
9851025
let existing: ProjectBindingLookup | null
9861026
try {
987-
existing = await WorkspaceApi.getBindingForProject(identifier)
1027+
existing = await deps.getBindingForProject(identifier)
9881028
} catch (err) {
989-
UI.error(
990-
`Could not check which workspace this project is linked to, so nothing was changed: ${err instanceof Error ? err.message : String(err)}`,
1029+
deps.printError(
1030+
`Could not check which workspace this project is linked to, so nothing was changed: ${stripControlChars(err instanceof Error ? err.message : String(err))}`,
9911031
)
9921032
process.exitCode = 1
9931033
return
9941034
}
9951035
const currentName = existing ? stripControlChars(existing.datamate.name) : undefined
9961036

997-
if (args.create !== undefined) {
998-
const name =
999-
args.create.trim() ||
1000-
(identifier.repoRemote ? projectNameFromRemote(identifier.repoRemote) : projectNameFromPath(identifier.projectPath))
1001-
if (existing && !args.yes) {
1002-
UI.error(`This project is already linked to "${currentName}". Pass --yes to create "${name}" and re-link to it.`)
1003-
process.exitCode = EXIT_USAGE
1004-
return
1005-
}
1006-
await createThenBindOrRebind(identifier, name, args.directory, existing)
1007-
return
1008-
}
1009-
10101037
// Same rule as the picker: the list and the bind run as one captured credential, so an
10111038
// account switch in between cannot bind a workspace id read from another tenant.
1012-
const actAs = await WorkspaceApi.captureCredentials()
1039+
const actAs = await deps.captureCredentials()
10131040
if (!actAs) {
1014-
UI.error("Could not read your Altimate credentials. Check /connect and try again.")
1041+
deps.printError("Could not read your Altimate credentials. Check /connect and try again.")
10151042
process.exitCode = 1
10161043
return
10171044
}
10181045
let list: DatamateRef[]
10191046
try {
1020-
list = await WorkspaceApi.listDatamates(actAs)
1047+
list = await deps.listDatamates(actAs)
10211048
} catch (err) {
1022-
UI.error(`Could not load workspaces: ${err instanceof Error ? err.message : String(err)}`)
1049+
deps.printError(`Could not load workspaces: ${stripControlChars(err instanceof Error ? err.message : String(err))}`)
10231050
process.exitCode = 1
10241051
return
10251052
}
1053+
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+
}
1063+
if (existing && !args.yes) {
1064+
deps.printError(`This project is already linked to "${currentName}". Pass --yes to create "${stripControlChars(name)}" and re-link to it.`)
1065+
process.exitCode = EXIT_USAGE
1066+
return
1067+
}
1068+
// The picker asks before creating a second workspace with a name in use; headless cannot ask, so it refuses.
1069+
const twins = findNamesakes(list, name, undefined).all
1070+
if (twins.length > 0 && !args.allowDuplicate) {
1071+
const ids = twins.map((dm) => dm.id).join(", ")
1072+
deps.printError(
1073+
`A workspace named "${stripControlChars(name)}" already exists (id ${ids}). Link to it with --workspace ${twins[0].id}, ` +
1074+
`or pass --allow-duplicate to create another.`,
1075+
)
1076+
process.exitCode = EXIT_USAGE
1077+
return
1078+
}
1079+
await deps.create(identifier, name, existing)
1080+
return
1081+
}
1082+
10261083
const match = matchWorkspace(list, args.workspace ?? "")
10271084
if (match.kind === "none") {
10281085
const names = list.map((dm) => `${stripControlChars(dm.name)} (id ${dm.id})`).join(", ")
1029-
UI.error(`No workspace named or numbered "${args.workspace}". ${names ? `Available: ${names}.` : "This account has no workspaces."}`)
1086+
deps.printError(
1087+
`No workspace named or numbered "${stripControlChars(args.workspace ?? "")}". ${names ? `Available: ${names}.` : "This account has no workspaces."}`,
1088+
)
10301089
process.exitCode = 1
10311090
return
10321091
}
10331092
if (match.kind === "many") {
10341093
const ids = match.matches.map((dm) => dm.id).join(", ")
1035-
UI.error(`More than one workspace is named "${args.workspace}" (ids ${ids}). Pass the id instead.`)
1094+
deps.printError(`More than one workspace is named "${stripControlChars(args.workspace ?? "")}" (ids ${ids}). Pass the id instead.`)
10361095
process.exitCode = EXIT_USAGE
10371096
return
10381097
}
10391098
const target = match.workspace
10401099
if (existing?.datamate.id === target.id) {
1041-
UI.println(`Already linked to "${stripControlChars(target.name)}" — nothing changed.`)
1100+
deps.print(`Already linked to "${stripControlChars(target.name)}" — nothing changed.`)
10421101
return
10431102
}
10441103
if (existing && !args.yes) {
1045-
UI.error(
1046-
`This project is already linked to "${currentName}". Pass --yes to re-link it to "${stripControlChars(target.name)}".`,
1047-
)
1104+
deps.printError(`This project is already linked to "${currentName}". Pass --yes to re-link it to "${stripControlChars(target.name)}".`)
10481105
process.exitCode = EXIT_USAGE
10491106
return
10501107
}
1051-
await bindOrRebind(identifier, target.id, existing, true, args.directory, actAs)
1108+
await deps.bindOrRebind(identifier, target.id, existing, actAs)
1109+
}
1110+
1111+
function linkHeadlessDeps(directory: string): LinkHeadlessDeps {
1112+
return {
1113+
isConfigured: () => AltimateApi.isConfigured(),
1114+
getBindingForProject: (identifier) => WorkspaceApi.getBindingForProject(identifier),
1115+
captureCredentials: () => WorkspaceApi.captureCredentials(),
1116+
listDatamates: (actAs) => WorkspaceApi.listDatamates(actAs),
1117+
bindOrRebind: (identifier, datamateId, existing, actAs) => bindOrRebind(identifier, datamateId, existing, true, directory, actAs),
1118+
create: (identifier, name, existing) => createThenBindOrRebind(identifier, name, directory, existing, { openBrowser: false }),
1119+
print: (line) => UI.println(line),
1120+
printError: (line) => UI.error(line),
1121+
}
10521122
}
10531123
// altimate_change end

0 commit comments

Comments
 (0)