Skip to content

Commit b193a5c

Browse files
sahrizviclaude
andcommitted
feat(workspace): --workspace <name> launch flag (AI-8504 item 1)
Add a top-level `--workspace <name>` yargs option to `altimate-code` that pins the session to the workspace this directory is linked to, by name. Groundwork for AI-8397 / AI-8434 (memory RW to mem0 scoped to Workspace), where the resolved workspace id becomes the input to "which workspace am I in?" lookups. **Files:** - `altimate/workspace/session-context.ts` — env-var handoff so the main-thread resolver's result reaches the TUI worker subprocess. Same mechanism `ALTIMATE_LAUNCH_ID` uses (the existing worker-spawn `env: { ...process.env, ... }` spread in `cli/cmd/tui.ts` carries the resolved workspace id across for free). Guards against a malformed env-var value poisoning callers with NaN. - `altimate/workspace/launch-resolve.ts` — the resolver. `nameMatches(name, binding)` is case-insensitive + whitespace-trimmed, exact match only, no fuzzy match, no backend name search (same-directory-only per the AI-8504 spec and Path A reference on `feature/workspace-link-onboarding`). Missing binding → prints an error and returns without setting the env var. Wrong name against an existing binding → prints a note and attaches to the linked workspace anyway (ticket's explicit choice: "print a note and continue with the currently-linked one"). The flag is gated on `Flag.ALTIMATE_WORKSPACE` so it's invisible to non-pilot users. - `cli/cmd/tui.ts` — adds the yargs option and calls the resolver after `cwd` is resolved but before `new Worker(...)`. Wrapped in a try/catch that logs and continues so a resolver failure can never block launch. - `test/altimate/workspace/launch-resolve.test.ts` — 13 unit tests covering `nameMatches` (exact / case / whitespace / mismatch / substring), `resolveWorkspaceForLaunch` (no arg, flag off, matching name, case-insensitive match, mismatch-still-attaches, unlinked dir), and the session-context env-var round trip (set/get/clear, malformed value returns null). **Manual smoke:** Rebuilt binary, seeded a test binding, ran end-to-end against a temp directory: matching name prints `Attached to workspace "Growth"`, wrong name prints the note + attaches to the linked workspace, unlinked dir errors cleanly, and `ALTIMATE_WORKSPACE=0` makes the flag silent-no-op. All observed as designed. **No consumer on #1099** — the sidebar tile that reads "current workspace" lives on the #1100 branch. This PR ships the flag + resolver + env-var infrastructure; a follow-up commit on #1100 wires the sidebar to prefer `getResolvedWorkspaceId()` over its current on-disk binding read. **Drift resolver (AI-8504 item 2) is NOT included** — it needs a backend PATCH-binding endpoint that doesn't exist yet, plus a conflict-of-interest to think through with the post-scan drift prompt already shipped in `workspace.tsx`. Tracked separately. Co-Authored-By: Claude Opus 4.7 <[email protected]> Claude-Session: https://claude.ai/code/session_016H42Vt4pt5dcD7opRqckeM
1 parent cbcfe85 commit b193a5c

4 files changed

Lines changed: 318 additions & 0 deletions

File tree

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
// altimate_change - new file
2+
//
3+
// Launch-time --workspace <name> resolver. Runs once per process, on the
4+
// TUI's main thread (from ``cli/cmd/tui.ts``) before the worker subprocess
5+
// starts, so its ``UI.println`` messages reach the user's terminal cleanly.
6+
//
7+
// Contract (matches AI-8504 Item #1 wording):
8+
// - The flag is same-directory-only. Resolution walks THIS directory's
9+
// local binding and nothing else — no backend-wide workspace-name search,
10+
// no fuzzy match. An unresolvable name is an honest printed error, never
11+
// a silent fallback to a different workspace.
12+
// - If the requested name doesn't match this directory's linked workspace,
13+
// print a note and continue with the currently-linked one anyway (the
14+
// ticket calls this out explicitly). A mismatch is a warning, not a
15+
// session abort.
16+
// - MUST NEVER block launch. Every failure path (missing binding, network
17+
// failure inside readLocalBinding, malformed cache) prints and returns —
18+
// nothing here calls ``process.exit`` or throws past the caller.
19+
//
20+
// Drift detection at launch (AI-8504 Item #2) is deliberately NOT
21+
// implemented here; that ships separately once the backend PATCH-binding
22+
// endpoint lands.
23+
import { Flag } from "@opencode-ai/core/flag/flag"
24+
import { UI } from "@/cli/ui"
25+
import { readLocalBinding, type CachedBinding } from "@/altimate/workspace/state"
26+
import { setResolvedWorkspaceId } from "@/altimate/workspace/session-context"
27+
28+
/** Case-insensitive, whitespace-trimmed match of the CLI's ``--workspace``
29+
* argument against the binding's stored workspace name. No fuzzy match; a
30+
* shorter substring is not a hit. */
31+
export function nameMatches(name: string, binding: CachedBinding): boolean {
32+
const needle = name.trim().toLowerCase()
33+
return binding.datamateName.toLowerCase() === needle
34+
}
35+
36+
export async function resolveWorkspaceForLaunch(
37+
directory: string,
38+
explicitName: string | undefined,
39+
): Promise<void> {
40+
// Gate on the pilot flag so the flag is invisible to non-opted-in users
41+
// even if they discover it via ``--help``. Silent when opted out — no
42+
// error message that would leak the pilot's existence.
43+
if (!Flag.ALTIMATE_WORKSPACE) return
44+
if (explicitName === undefined) return
45+
46+
const binding = await readLocalBinding(directory).catch(() => null)
47+
if (!binding) {
48+
// Can't attach to what isn't linked. Fail-fast with a message pointing at
49+
// the fix; do NOT set the env var (consumers will fall through to their
50+
// default resolution).
51+
UI.error(
52+
`No workspace is linked in this directory. Run \`altimate-code link\` ` +
53+
`first, or drop --workspace to continue with default resolution.`,
54+
)
55+
return
56+
}
57+
58+
if (!nameMatches(explicitName, binding)) {
59+
// Per AI-8504 spec: print a note and continue with the currently-linked
60+
// workspace rather than aborting. The flag is a sanity check, not a
61+
// hard override.
62+
UI.println(
63+
`Note: --workspace "${explicitName}" was requested, but this directory ` +
64+
`is linked to "${binding.datamateName}" — attaching to ` +
65+
`"${binding.datamateName}" since that's what's linked here.`,
66+
)
67+
}
68+
69+
setResolvedWorkspaceId(binding.datamateId)
70+
UI.println(`Attached to workspace "${binding.datamateName}".`)
71+
}
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
// altimate_change - new file
2+
//
3+
// Env-var handoff for the launch-time --workspace resolution result.
4+
//
5+
// The launch resolver runs on the TUI's MAIN thread (``cli/cmd/tui.ts``,
6+
// before ``new Worker(...)`` — it prints via ``UI.println`` and would need
7+
// stdout the worker owns). Consumers of "which workspace is this session
8+
// pinned to?" run inside the TUI worker subprocess (its own JS heap; a
9+
// module-level variable set on the main thread is invisible there).
10+
//
11+
// This codebase already solves the same problem for ``ALTIMATE_LAUNCH_ID``:
12+
// ``tui.ts`` spawns the worker with ``env: { ...process.env, ... }`` and
13+
// telemetry reads it back from ``process.env.ALTIMATE_LAUNCH_ID`` on either
14+
// side. Same mechanism here — ``setResolvedWorkspaceId`` mutates
15+
// ``process.env`` on the main thread; the existing worker-spawn env spread
16+
// carries it across for free; ``getResolvedWorkspaceId`` reads it back from
17+
// whichever thread calls it.
18+
const ENV_WORKSPACE_ID = "ALTIMATE_RESOLVED_WORKSPACE_ID"
19+
20+
export function setResolvedWorkspaceId(id: number | null): void {
21+
if (id === null) {
22+
delete process.env[ENV_WORKSPACE_ID]
23+
return
24+
}
25+
process.env[ENV_WORKSPACE_ID] = String(id)
26+
}
27+
28+
/** Returns the launch-flag-selected workspace id when the session was
29+
* started with ``--workspace <name>`` and the name resolved, else null.
30+
* Consumers should fall back to the local binding cache
31+
* (``readLocalBinding``) when this returns null. */
32+
export function getResolvedWorkspaceId(): number | null {
33+
const raw = process.env[ENV_WORKSPACE_ID]
34+
if (!raw) return null
35+
// Guard against a malformed env var — a NaN would silently poison callers
36+
// that then bind against workspace id NaN. Return null so callers fall
37+
// through to their default resolution path.
38+
const parsed = Number(raw)
39+
if (!Number.isInteger(parsed) || parsed <= 0) return null
40+
return parsed
41+
}

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,14 @@ export const TuiThreadCommand = cmd({
113113
.option("agent", {
114114
type: "string",
115115
describe: "agent to use",
116+
})
117+
// altimate_change — AI-8504 item 1: launch flag that pins this session
118+
// to the workspace this directory is linked to. Resolved same-directory-
119+
// only (no backend name search, no fuzzy match) — see
120+
// altimate/workspace/launch-resolve.ts.
121+
.option("workspace", {
122+
type: "string",
123+
describe: "attach this session to the workspace linked in this directory, by name",
116124
}),
117125
handler: async (args) => {
118126
const unguard = win32InstallCtrlCGuard()
@@ -136,6 +144,27 @@ export const TuiThreadCommand = cmd({
136144
}
137145
const cwd = Filesystem.resolve(process.cwd())
138146

147+
// altimate_change start — AI-8504 item 1: launch-time --workspace resolver.
148+
// Runs BEFORE the worker starts (needs stdout on this main thread for its
149+
// native prompts and info messages). MUST NEVER block launch — a failure
150+
// here (missing binding, unreadable cache, credentials-parse failure) is
151+
// logged and swallowed; the session still starts. The resolver mutates
152+
// ``process.env`` on this thread; the existing worker-spawn env spread
153+
// below carries the resolved workspace id across for free — same
154+
// mechanism as ``ALTIMATE_LAUNCH_ID``.
155+
try {
156+
const { resolveWorkspaceForLaunch } = await import(
157+
"@/altimate/workspace/launch-resolve"
158+
)
159+
await resolveWorkspaceForLaunch(cwd, args.workspace)
160+
} catch (err) {
161+
UI.error(
162+
`workspace resolution failed (continuing without a pinned workspace): ` +
163+
`${err instanceof Error ? err.message : String(err)}`,
164+
)
165+
}
166+
// altimate_change end
167+
139168
// altimate_change start — hand the launch correlation id to the worker explicitly. A Bun
140169
// Worker does not see runtime mutations to process.env, so without this the worker mints its
141170
// own and the TUI-thread and worker-thread halves of the onboarding funnel cannot be joined.
Lines changed: 177 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
// altimate_change - new file
2+
//
3+
// Unit coverage for the --workspace launch resolver. Exercises the pure
4+
// name-match helper directly, and the wired-up resolveWorkspaceForLaunch
5+
// with the local binding cache + ALTIMATE_WORKSPACE flag stubbed. Does
6+
// NOT exercise the tui.ts wiring or the worker subprocess env-var pickup
7+
// — those are integration territory.
8+
import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"
9+
import { mkdirSync, rmSync } from "node:fs"
10+
import path from "node:path"
11+
import os from "node:os"
12+
13+
// Redirect Global.Path.state BEFORE importing state.ts so cachePath()
14+
// resolves inside the sandbox. Same isolation pattern as workspace.test.ts.
15+
const ORIGINAL_XDG_STATE_HOME = process.env.XDG_STATE_HOME
16+
const SANDBOX = path.join(
17+
os.tmpdir(),
18+
`altimate-launch-resolve-test-${process.pid}-${Date.now()}`,
19+
)
20+
mkdirSync(path.join(SANDBOX, "state"), { recursive: true })
21+
process.env.XDG_STATE_HOME = path.join(SANDBOX, "state")
22+
afterAll(() => {
23+
if (ORIGINAL_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME
24+
else process.env.XDG_STATE_HOME = ORIGINAL_XDG_STATE_HOME
25+
try {
26+
rmSync(SANDBOX, { recursive: true, force: true })
27+
} catch {
28+
/* best effort */
29+
}
30+
})
31+
32+
const { nameMatches, resolveWorkspaceForLaunch } = await import(
33+
"../../../src/altimate/workspace/launch-resolve"
34+
)
35+
const { getResolvedWorkspaceId, setResolvedWorkspaceId } = await import(
36+
"../../../src/altimate/workspace/session-context"
37+
)
38+
const { recordApprovedBinding, cachePath } = await import(
39+
"../../../src/altimate/workspace/state"
40+
)
41+
42+
// Stub credentials so state.ts's tenant/apiUrl scoping is deterministic.
43+
import { AltimateApi } from "../../../src/altimate/api/client"
44+
type Creds = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
45+
const originalIsConfigured = AltimateApi.isConfigured
46+
const originalGetCreds = AltimateApi.getCredentials
47+
function stubCreds() {
48+
;(AltimateApi as unknown as { isConfigured: () => Promise<boolean> }).isConfigured = async () =>
49+
true
50+
;(AltimateApi as unknown as { getCredentials: () => Promise<Creds> }).getCredentials =
51+
async () =>
52+
({
53+
altimateInstanceName: "altimate2",
54+
altimateUrl: "http://localhost:5001",
55+
altimateApiKey: "dummy",
56+
}) as Creds
57+
}
58+
function unstubCreds() {
59+
;(AltimateApi as unknown as { isConfigured: typeof originalIsConfigured }).isConfigured =
60+
originalIsConfigured
61+
;(AltimateApi as unknown as { getCredentials: typeof originalGetCreds }).getCredentials =
62+
originalGetCreds
63+
}
64+
65+
beforeEach(() => {
66+
stubCreds()
67+
setResolvedWorkspaceId(null)
68+
// Clean cache file between tests so state doesn't leak across cases.
69+
try {
70+
rmSync(cachePath(), { force: true })
71+
} catch {
72+
/* best effort */
73+
}
74+
// Explicitly enable the pilot flag for every test. Restored per-test in
75+
// afterEach so the "flag off" test can override.
76+
process.env.ALTIMATE_WORKSPACE = "1"
77+
})
78+
afterEach(() => {
79+
unstubCreds()
80+
setResolvedWorkspaceId(null)
81+
delete process.env.ALTIMATE_WORKSPACE
82+
})
83+
84+
describe("nameMatches", () => {
85+
const binding = {
86+
datamateId: 42,
87+
datamateName: "Growth",
88+
repoRemote: "ssh://[email protected]/foo/bar",
89+
projectPath: "/tmp/foo",
90+
linkedAt: 0,
91+
}
92+
93+
test("exact match", () => {
94+
expect(nameMatches("Growth", binding)).toBe(true)
95+
})
96+
test("case-insensitive match", () => {
97+
expect(nameMatches("GROWTH", binding)).toBe(true)
98+
expect(nameMatches("growth", binding)).toBe(true)
99+
})
100+
test("whitespace-trimmed match", () => {
101+
expect(nameMatches(" Growth ", binding)).toBe(true)
102+
})
103+
test("mismatch", () => {
104+
expect(nameMatches("Other", binding)).toBe(false)
105+
})
106+
test("substring is not a hit (no fuzzy match)", () => {
107+
expect(nameMatches("Grow", binding)).toBe(false)
108+
expect(nameMatches("Growthy", binding)).toBe(false)
109+
})
110+
})
111+
112+
describe("resolveWorkspaceForLaunch", () => {
113+
const DIRECTORY = path.join(SANDBOX, "project")
114+
115+
beforeEach(async () => {
116+
mkdirSync(DIRECTORY, { recursive: true })
117+
await recordApprovedBinding(DIRECTORY, {
118+
datamateId: 42,
119+
datamateName: "Growth",
120+
repoRemote: null,
121+
projectPath: DIRECTORY,
122+
linkedAt: 0,
123+
})
124+
})
125+
126+
test("no --workspace arg → no env var set, no-op", async () => {
127+
await resolveWorkspaceForLaunch(DIRECTORY, undefined)
128+
expect(getResolvedWorkspaceId()).toBeNull()
129+
})
130+
131+
test("ALTIMATE_WORKSPACE flag off → no env var set even when --workspace given", async () => {
132+
delete process.env.ALTIMATE_WORKSPACE
133+
await resolveWorkspaceForLaunch(DIRECTORY, "Growth")
134+
expect(getResolvedWorkspaceId()).toBeNull()
135+
})
136+
137+
test("matching name → env var set to the binding's datamateId", async () => {
138+
await resolveWorkspaceForLaunch(DIRECTORY, "Growth")
139+
expect(getResolvedWorkspaceId()).toBe(42)
140+
})
141+
142+
test("case-insensitive matching name → env var set", async () => {
143+
await resolveWorkspaceForLaunch(DIRECTORY, "growth")
144+
expect(getResolvedWorkspaceId()).toBe(42)
145+
})
146+
147+
test("mismatched name → env var STILL set (attaches to linked workspace with a note per AI-8504 spec)", async () => {
148+
await resolveWorkspaceForLaunch(DIRECTORY, "Other")
149+
expect(getResolvedWorkspaceId()).toBe(42)
150+
})
151+
152+
test("no binding for this directory → env var NOT set (fail-fast)", async () => {
153+
const unlinkedDir = path.join(SANDBOX, "unlinked")
154+
mkdirSync(unlinkedDir, { recursive: true })
155+
await resolveWorkspaceForLaunch(unlinkedDir, "Growth")
156+
expect(getResolvedWorkspaceId()).toBeNull()
157+
})
158+
})
159+
160+
describe("session-context env-var round trip", () => {
161+
test("set/get/clear cycle", () => {
162+
setResolvedWorkspaceId(123)
163+
expect(getResolvedWorkspaceId()).toBe(123)
164+
setResolvedWorkspaceId(null)
165+
expect(getResolvedWorkspaceId()).toBeNull()
166+
})
167+
168+
test("malformed env value returns null (defense against poisoned env)", () => {
169+
process.env.ALTIMATE_RESOLVED_WORKSPACE_ID = "not-a-number"
170+
expect(getResolvedWorkspaceId()).toBeNull()
171+
process.env.ALTIMATE_RESOLVED_WORKSPACE_ID = "0"
172+
expect(getResolvedWorkspaceId()).toBeNull()
173+
process.env.ALTIMATE_RESOLVED_WORKSPACE_ID = "-5"
174+
expect(getResolvedWorkspaceId()).toBeNull()
175+
delete process.env.ALTIMATE_RESOLVED_WORKSPACE_ID
176+
})
177+
})

0 commit comments

Comments
 (0)