Skip to content

Commit da00c37

Browse files
saravmajesticclaude
andcommitted
feat(workspace): honour a workspace pinned by the IDE extension
`altimate-code serve` is launched by the VS Code / Cursor extension, which knows which datamate the user picked in its panel. Until now nothing carried that across, so skills and memory followed whatever binding the project had on the backend rather than the selection on screen. `resolveBindingOutcome` is the single place both consumers funnel through (`skill-sync.ts` and `memory-sync.ts`), so honouring the pin there is all that is needed — neither module changes. - `pin.ts` — parse `ALTIMATE_PINNED_WORKSPACE_{ID,NAME,ROOT}` into a tagged `absent | invalid | valid`. A present-but-broken pin is `invalid` and fails closed, because falling through can resolve a DIFFERENT workspace. - A deliberately separate namespace from `ALTIMATE_RESOLVED_WORKSPACE_*`: `launch-resolve.ts` sets only `..._ID` for the TUI's `--workspace` flag, so sharing the namespace would read as a partial pin and fail that flow closed. `readPin` also stands down unless `ALTIMATE_CODE_SERVE` is set. - `state.ts` — the pin outranks the cached binding and server auto-adoption, is validated against `listDatamates()` (memoized on `REVALIDATE_MS`, since this runs per turn and per memory write), is scoped to the launch root, and is never persisted. `pinned` is stripped from anything read off disk. - Offline splits on whether this process ever validated: never-validated is `unknown`, previously-validated keeps serving, matching what this module already does for a cached binding. 23 tests covering the parser, precedence, fail-closed paths, root scoping, the offline split and memoization. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 236e73c commit da00c37

4 files changed

Lines changed: 466 additions & 0 deletions

File tree

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,108 @@
1+
// altimate_change - new file
2+
//
3+
// The IDE extension's workspace pin.
4+
//
5+
// `altimate-code serve` is launched by the VS Code / Cursor extension, which already knows which
6+
// datamate the user picked in its panel. That selection is what should govern the session's skills
7+
// and memory — not whatever binding this project happens to carry on the backend. The extension
8+
// hands it over in the child's environment and this module turns it back into a `CachedBinding`
9+
// for `state.ts`'s `resolveBindingOutcome` to return.
10+
//
11+
// Why the environment, and not a `serve` argument: `resolveBindingOutcome` is reached from
12+
// per-turn prompt assembly and from every memory write, neither of which has a path back to the
13+
// command's parsed `args`. `session-context.ts` and `serve.ts`'s `ALTIMATE_CODE_SERVE` both made
14+
// the same call, for the same reason — it has to be readable from every module realm. A `serve`
15+
// flag can still be added as sugar, so long as its handler writes these vars before anything else
16+
// runs.
17+
//
18+
// Why NOT the existing `ALTIMATE_RESOLVED_WORKSPACE_*` namespace, which looks like the obvious
19+
// home: `launch-resolve.ts` sets `ALTIMATE_RESOLVED_WORKSPACE_ID` **alone** for the TUI's
20+
// `--workspace <name>` flag — no name, no root. Reusing that namespace would make every such TUI
21+
// session look like a half-populated pin, and the fail-closed rule below would then break
22+
// `--workspace` outright. The two mechanisms are kept apart deliberately, and `readPin` additionally
23+
// stands down outside `serve`.
24+
import { realpathSync } from "node:fs"
25+
import path from "node:path"
26+
import { Log } from "@/altimate/util/log"
27+
28+
const log = Log.create({ service: "workspace-pin" })
29+
30+
const ENV_ID = "ALTIMATE_PINNED_WORKSPACE_ID"
31+
const ENV_NAME = "ALTIMATE_PINNED_WORKSPACE_NAME"
32+
const ENV_ROOT = "ALTIMATE_PINNED_WORKSPACE_ROOT"
33+
34+
export interface ValidPin {
35+
kind: "valid"
36+
datamateId: number
37+
datamateName: string
38+
/** The directory `serve` was launched for. The pin applies to this tree and nothing else. */
39+
root: string
40+
}
41+
42+
/**
43+
* `absent` and `invalid` are deliberately NOT the same answer.
44+
*
45+
* Collapsing them — the shape `getResolvedWorkspaceId` uses, where anything unparseable returns
46+
* `null` — would make a malformed pin fall through to ordinary cache/server resolution, which can
47+
* legitimately return a DIFFERENT workspace. Silently doing work against a workspace the user did
48+
* not pick is the one outcome this feature must never produce, so a pin that is present but broken
49+
* fails closed instead.
50+
*/
51+
export type PinState = { kind: "absent" } | { kind: "invalid"; reason: string } | ValidPin
52+
53+
/** Canonicalize for comparison: `realpath` where it resolves (macOS `/tmp` -> `/private/tmp`),
54+
* otherwise the normalized absolute path, so a not-yet-created directory still compares sanely. */
55+
export function canonical(dir: string): string {
56+
try {
57+
return realpathSync(dir)
58+
} catch {
59+
return path.resolve(dir)
60+
}
61+
}
62+
63+
/** Whether `directory` is the pinned root or lives underneath it. */
64+
export function withinRoot(directory: string, root: string): boolean {
65+
const d = canonical(directory)
66+
const r = canonical(root)
67+
if (d === r) return true
68+
return d.startsWith(r.endsWith(path.sep) ? r : r + path.sep)
69+
}
70+
71+
/**
72+
* Read the pin out of the environment.
73+
*
74+
* Returns `absent` outside `serve`: the pin is the extension's channel, and the TUI has its own
75+
* (`--workspace`, via `launch-resolve.ts`). Keeping them from ever being live in the same process
76+
* is cheaper than reasoning about what should win.
77+
*/
78+
export function readPin(env: NodeJS.ProcessEnv = process.env): PinState {
79+
if (env["ALTIMATE_CODE_SERVE"] !== "1") return { kind: "absent" }
80+
81+
const rawId = env[ENV_ID]
82+
const name = env[ENV_NAME]
83+
const root = env[ENV_ROOT]
84+
if (!rawId && !name && !root) return { kind: "absent" }
85+
86+
// Partial is invalid, never "good enough". The extension sets all three or none; anything else
87+
// means something rewrote the environment and we no longer know what was intended.
88+
if (!rawId || !name || !root) {
89+
return { kind: "invalid", reason: "pin is partially set" }
90+
}
91+
92+
const datamateId = Number(rawId)
93+
if (!Number.isSafeInteger(datamateId) || datamateId <= 0) {
94+
return { kind: "invalid", reason: `datamate id ${JSON.stringify(rawId)} is not a positive integer` }
95+
}
96+
if (!path.isAbsolute(root)) {
97+
return { kind: "invalid", reason: "pinned root is not an absolute path" }
98+
}
99+
100+
return { kind: "valid", datamateId, datamateName: name, root }
101+
}
102+
103+
/** `readPin`, with the refusal logged once at the point it is taken. */
104+
export function readPinLogged(env: NodeJS.ProcessEnv = process.env): PinState {
105+
const pin = readPin(env)
106+
if (pin.kind === "invalid") log.warn("ignoring workspace pin and failing closed", { reason: pin.reason })
107+
return pin
108+
}

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

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,9 @@ import { Log } from "@/altimate/util/log"
1919
// Type-only: the value side is imported dynamically in resolveBinding to keep
2020
// this module's import graph free of the API client at load time.
2121
import type { Binding, ProjectBindingLookup } from "./api-client"
22+
// altimate_change — the IDE extension's workspace pin; see ./pin.ts
23+
import { readPinLogged, withinRoot, type ValidPin } from "./pin"
24+
import { resolveProjectIdentifier } from "./detect"
2225

2326
const CACHE_VERSION = 1
2427

@@ -42,6 +45,12 @@ export interface CachedBinding {
4245
* seed has not run, errored, or was skipped because memory was off — all of
4346
* which must stay retryable, so a later warm sweeps again. */
4447
seededAt?: number
48+
/** altimate_change — this binding came from the IDE extension's workspace pin
49+
* (see ./pin.ts), not from disk or the server. Ephemeral for the life of the
50+
* process: it is never written to the cache, and `readCache` strips it back
51+
* off anything that claims it on disk. Callers use it to tell an explicit,
52+
* user-made selection apart from a binding the server volunteered. */
53+
pinned?: boolean
4554
}
4655

4756
interface CacheFile {
@@ -84,6 +93,11 @@ function isValidCacheFile(raw: unknown): raw is CacheFile {
8493
(typeof b.projectPath === "string" && b.projectPath.length > 0)
8594
if (!hasIdentity) return false
8695
if (typeof b.linkedAt !== "number") return false
96+
// altimate_change — `pinned` is the IDE extension's in-process authorization marker and is
97+
// never written here. Anything on disk claiming it is corrupt or hand-edited, and honouring it
98+
// would let a file grant the write access a real selection is supposed to gate. Strip, don't
99+
// reject: the rest of the row is still usable.
100+
if ("pinned" in b) delete b.pinned
87101
// A corrupt marker must not read as "already seeded" and suppress the sweep.
88102
if (b.seededAt !== undefined && typeof b.seededAt !== "number") return false
89103
}
@@ -369,7 +383,111 @@ export type BindingOutcome =
369383
| { status: "unbound" }
370384
| { status: "unknown" }
371385

386+
/** How long a validated pin is trusted before its datamate is re-checked against the account.
387+
* Matches `REVALIDATE_MS` deliberately — this is the same question that rule answers, asked of a
388+
* different source of truth. */
389+
const PIN_VALIDATION_TTL_MS = REVALIDATE_MS
390+
391+
/** Memoized `listDatamates` verdicts, keyed by `tenant|apiUrl|datamateId`. `resolveBindingOutcome`
392+
* runs on every turn AND every memory write, so an unmemoized probe would put an HTTP round trip
393+
* on both hot paths. Only SUCCESSFUL verdicts are stored: caching a failure would turn one network
394+
* blip into five minutes of a dead workspace. */
395+
const pinValidation = new Map<string, { name: string; at: number }>()
396+
397+
/** Exposed for tests; production never calls it. */
398+
export function __resetPinValidation(): void {
399+
pinValidation.clear()
400+
}
401+
402+
/**
403+
* Resolve the extension's pin into a binding, or refuse.
404+
*
405+
* Refusals are `unknown`, never `unbound`: `unbound` is a positive statement that this project has
406+
* no workspace, which callers act on destructively (`skill-sync` takes a snapshot out of service on
407+
* it). "We could not confirm the pin" does not justify that.
408+
*/
409+
async function resolvePinnedBinding(directory: string, pin: ValidPin): Promise<BindingOutcome> {
410+
// The pin is scoped to the tree `serve` was launched for. `serve` resolves an instance per
411+
// request from the `x-opencode-directory` header and runs unsecured by default, so without this
412+
// any local caller could have an unrelated directory's memory attributed to the pinned workspace.
413+
if (!withinRoot(directory, pin.root)) {
414+
log.warn("ignoring workspace pin for a directory outside the pinned root", { directory })
415+
return { status: "unknown" }
416+
}
417+
418+
const key = await tenantKey()
419+
if (!key) {
420+
// Silent until now, which made a credential problem look identical to the pin never being read.
421+
log.warn("cannot honour the workspace pin: no Altimate credentials resolved")
422+
return { status: "unknown" }
423+
}
424+
const cacheKey = `${key.tenant}|${key.apiUrl}|${pin.datamateId}`
425+
426+
const memo = pinValidation.get(cacheKey)
427+
let datamateName = pin.datamateName
428+
if (memo && Date.now() - memo.at < PIN_VALIDATION_TTL_MS) {
429+
datamateName = memo.name
430+
} else {
431+
let accessible: { id: number; name: string }[] | null = null
432+
try {
433+
const { WorkspaceApi } = await import("./api-client")
434+
accessible = await WorkspaceApi.listDatamates()
435+
} catch (err) {
436+
// Unreachable, not unauthorized — these are different answers and must not collapse.
437+
accessible = null
438+
log.warn("could not verify the pinned workspace", { err: String(err) })
439+
}
440+
if (accessible) {
441+
const hit = accessible.find((d) => d.id === pin.datamateId)
442+
// The account genuinely cannot see this workspace. That is a real answer, so fail closed —
443+
// and do not let a previously-cached verdict keep it alive.
444+
if (!hit) {
445+
pinValidation.delete(cacheKey)
446+
log.warn("pinned workspace is not visible to this account", { datamateId: pin.datamateId })
447+
return { status: "unknown" }
448+
}
449+
// The server's name wins over the environment's, which can be stale if the workspace was
450+
// renamed after the extension spawned this process.
451+
datamateName = hit.name
452+
pinValidation.set(cacheKey, { name: hit.name, at: Date.now() })
453+
} else if (!memo) {
454+
// Never validated in this process and the account is unreachable: nothing was ever
455+
// established, so there is nothing to keep serving. The environment's name is a display
456+
// fallback, never an authorization one.
457+
return { status: "unknown" }
458+
}
459+
// Validated earlier and now unreachable: keep serving it, which is what this module already
460+
// does for a cached binding rather than tear a working setup down over a network blip.
461+
}
462+
463+
const ident = resolveProjectIdentifier(directory)
464+
// Logged on success as well as on every refusal: a silently-working pin is indistinguishable
465+
// from a pin that was never read, which is exactly the ambiguity that makes this hard to support.
466+
log.info("resolved the workspace pinned by the IDE extension", {
467+
datamateId: pin.datamateId,
468+
datamateName,
469+
})
470+
return {
471+
status: "bound",
472+
binding: {
473+
datamateId: pin.datamateId,
474+
datamateName,
475+
repoRemote: ident.repoRemote ?? null,
476+
projectPath: ident.projectPath,
477+
linkedAt: Date.now(),
478+
pinned: true,
479+
},
480+
}
481+
}
482+
372483
export async function resolveBindingOutcome(directory: string): Promise<BindingOutcome> {
484+
// altimate_change — the IDE extension's selection outranks whatever binding this project carries.
485+
// Checked before the local cache and before any server lookup: the whole point is that the panel,
486+
// not the project's history, decides which workspace this `serve` process works against.
487+
const pin = readPinLogged()
488+
if (pin.kind === "invalid") return { status: "unknown" }
489+
if (pin.kind === "valid") return resolvePinnedBinding(directory, pin)
490+
373491
const local = await readLocalBinding(directory).catch(() => null)
374492

375493
const key = await tenantKey()
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// altimate_change - new file
2+
//
3+
// Unit coverage for the IDE extension's workspace pin parser. Pure: no cache, no network, no
4+
// instance context — `readPin` reads an env bag it is handed, so every case is a plain assertion.
5+
import { describe, expect, test } from "bun:test"
6+
import path from "node:path"
7+
import { readPin, withinRoot } from "../../../src/altimate/workspace/pin"
8+
9+
const ROOT = path.resolve("/tmp/pin-root")
10+
11+
function env(over: Record<string, string | undefined> = {}): NodeJS.ProcessEnv {
12+
return {
13+
ALTIMATE_CODE_SERVE: "1",
14+
ALTIMATE_PINNED_WORKSPACE_ID: "42",
15+
ALTIMATE_PINNED_WORKSPACE_NAME: "Data Eng",
16+
ALTIMATE_PINNED_WORKSPACE_ROOT: ROOT,
17+
...over,
18+
}
19+
}
20+
21+
describe("readPin", () => {
22+
test("a fully-specified pin under serve is valid", () => {
23+
const pin = readPin(env())
24+
expect(pin.kind).toBe("valid")
25+
if (pin.kind !== "valid") return
26+
expect(pin.datamateId).toBe(42)
27+
expect(pin.datamateName).toBe("Data Eng")
28+
expect(pin.root).toBe(ROOT)
29+
})
30+
31+
test("stands down outside serve, so the TUI's --workspace flow is untouched", () => {
32+
// The regression this guards: `launch-resolve.ts` sets only an id for `--workspace`. If the
33+
// pin ever read that shape it would classify it invalid and fail the TUI closed.
34+
expect(readPin(env({ ALTIMATE_CODE_SERVE: undefined })).kind).toBe("absent")
35+
})
36+
37+
test("no pin variables at all is absent, not invalid", () => {
38+
const pin = readPin({ ALTIMATE_CODE_SERVE: "1" })
39+
expect(pin.kind).toBe("absent")
40+
})
41+
42+
test.each([
43+
["missing name", { ALTIMATE_PINNED_WORKSPACE_NAME: undefined }],
44+
["missing root", { ALTIMATE_PINNED_WORKSPACE_ROOT: undefined }],
45+
["missing id", { ALTIMATE_PINNED_WORKSPACE_ID: undefined }],
46+
])("a partial pin (%s) is invalid, never partially honoured", (_label, over) => {
47+
expect(readPin(env(over as Record<string, string | undefined>)).kind).toBe("invalid")
48+
})
49+
50+
test.each([["zero", "0"], ["negative", "-3"], ["non-numeric", "abc"], ["float", "4.5"]])(
51+
"a %s datamate id is invalid",
52+
(_label, id) => {
53+
expect(readPin(env({ ALTIMATE_PINNED_WORKSPACE_ID: id })).kind).toBe("invalid")
54+
},
55+
)
56+
57+
test("a relative root is invalid", () => {
58+
expect(readPin(env({ ALTIMATE_PINNED_WORKSPACE_ROOT: "relative/path" })).kind).toBe("invalid")
59+
})
60+
})
61+
62+
describe("withinRoot", () => {
63+
test("the root itself and its descendants are in scope", () => {
64+
expect(withinRoot(ROOT, ROOT)).toBe(true)
65+
expect(withinRoot(path.join(ROOT, "pkg", "src"), ROOT)).toBe(true)
66+
})
67+
68+
test("a sibling sharing a name prefix is NOT in scope", () => {
69+
// `startsWith` without the separator would call `/tmp/pin-root-other` a child of
70+
// `/tmp/pin-root`, which is how a directory outside the pin gets its memory attributed to the
71+
// pinned workspace.
72+
expect(withinRoot(`${ROOT}-other`, ROOT)).toBe(false)
73+
})
74+
75+
test("an unrelated directory is not in scope", () => {
76+
expect(withinRoot(path.resolve("/tmp/somewhere-else"), ROOT)).toBe(false)
77+
})
78+
})

0 commit comments

Comments
 (0)