Skip to content

Commit d5cd388

Browse files
saravmajesticclaude
andcommitted
fix(workspace): route warehouse tools at the pinned workspace
The IDE extension's pin outranks the project's stored binding inside `resolveBindingOutcome`, so identity, skills and memory all follow the panel's selection. Warehouse tool routing did not: `precedence.currentBinding` and `engine-probes.resolveBinding` read the on-disk binding cache directly, and the pin is deliberately never persisted, so routing could not see it. In a pinned session that left one turn naming two workspaces — the identity section said the pinned one while the routing section named whatever the project was linked to, with nothing telling the model which governs execution. With no prior local link, routing settled `unbound` and every warehouse call went to the local tools instead. Both readers now consult the pin first, through a single exported arm of the same resolver the other consumers use, so there is one precedence rule rather than two implementations of it. Exposed as the pin arm alone rather than pointing these callers at `resolveBindingOutcome`, because the rest of that function is not equivalent to the strict cache read they do today: with no credentials configured it answers `unknown` where the strict read answers "no binding", and the engine overlay treats those differently — one refuses and holds the datamate key, the other hands it back. Layering only the pin keeps every unpinned session on exactly the path it has now. A pin that cannot be honoured — malformed, outside its root, unresolvable credentials, or naming a workspace the account cannot see — fails closed rather than falling through to the project's link. Falling through is precisely the mismatch this fixes, and it would otherwise resurface whenever validation could not complete. Fixes #1337. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
1 parent 04b8f76 commit d5cd388

4 files changed

Lines changed: 243 additions & 5 deletions

File tree

‎packages/opencode/src/altimate/workspace/engine-probes.ts‎

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { AltimateApi } from "@/altimate/api/client"
1111
import { AppRuntime } from "@/effect/app-runtime"
1212
import { EventV2Bridge } from "@/event-v2-bridge"
1313
import { TuiEvent } from "@/server/tui-event"
14-
import { readLocalBindingScopedStrict } from "./state"
14+
import { currentScope, readLocalBindingScopedStrict, resolvePinnedBindingForRouting } from "./state"
1515
import { log, syncInternals, type BindingRead, type ScopedBinding } from "./engine-seams"
1616
import type { Declared, DeclaredExtension, Toast } from "./engine-types"
1717

@@ -25,9 +25,32 @@ export const DECLARED_TIMEOUT_MS = 4_000
2525
* same path a production one does. */
2626
export async function resolveBinding(directory: string): Promise<BindingRead> {
2727
try {
28-
const binding = syncInternals.resolveBinding
29-
? await syncInternals.resolveBinding(directory)
30-
: await readScoped(directory)
28+
if (syncInternals.resolveBinding) {
29+
const seam = await syncInternals.resolveBinding(directory)
30+
return seam ? { kind: "bound", binding: seam } : { kind: "unbound" }
31+
}
32+
// altimate_change — honour the IDE extension's pin before the project's own link, so the
33+
// engine overlay claims the key for the workspace the panel selected rather than the one the
34+
// project happens to be linked to (#1337). Same precedence `resolveBindingOutcome` applies
35+
// for identity, skills and memory.
36+
const pinned = await resolvePinnedBindingForRouting(directory)
37+
if (pinned) {
38+
if (pinned.status !== "bound") {
39+
// Fail closed: a pin that cannot be honoured must not silently hand the overlay back to
40+
// the project's link, which is the mismatch this prevents. `failed` holds the key and
41+
// retries at the next turn boundary rather than releasing it as `unbound` would.
42+
return { kind: "failed", error: "the workspace pin could not be honoured" }
43+
}
44+
const scope = await currentScope()
45+
return {
46+
kind: "bound",
47+
binding: {
48+
...pinned.binding,
49+
scope: scope ? `${scope.tenant}|${scope.apiUrl}` : undefined,
50+
},
51+
}
52+
}
53+
const binding = await readScoped(directory)
3154
return binding ? { kind: "bound", binding } : { kind: "unbound" }
3255
} catch (err) {
3356
log.warn("could not read the workspace binding", { err: String(err) })

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

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@ import {
6666
type EntryLike,
6767
type Outcome,
6868
} from "./engine-overlay"
69-
import { readLocalBindingScopedStrict } from "./state"
69+
import { readLocalBindingScopedStrict, resolvePinnedBindingForRouting } from "./state"
7070
import { liveBridge } from "./engine-probes"
7171
import { syncInternals } from "./engine-seams"
7272
import { canonicalType } from "../native/connections/registry"
@@ -438,6 +438,23 @@ async function currentBinding(): Promise<BindingRead> {
438438
}
439439
const directory = Instance.directory
440440
if (!directory) return { kind: "unbound" }
441+
// altimate_change — the IDE extension's pin outranks the project's own link, as it already
442+
// does for identity, skills and memory. Without this the identity section named the pinned
443+
// workspace while these tools routed at whatever the project was linked to (#1337).
444+
const pinned = await resolvePinnedBindingForRouting(directory)
445+
if (pinned) {
446+
if (pinned.status === "bound") {
447+
return {
448+
kind: "bound",
449+
datamateId: pinned.binding.datamateId,
450+
datamateName: pinned.binding.datamateName,
451+
}
452+
}
453+
// A pin that could not be honoured is not a licence to route at the project's link — that
454+
// is the mismatch this exists to prevent. `unreadable` disables routing without claiming
455+
// the project is unbound.
456+
return { kind: "unreadable", error: "the workspace pin could not be honoured" }
457+
}
441458
const { binding } = await readLocalBindingScopedStrict(directory)
442459
return binding
443460
? { kind: "bound", datamateId: binding.datamateId, datamateName: binding.datamateName }

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

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -651,6 +651,35 @@ async function resolvePinnedBinding(directory: string, pin: ValidPin): Promise<B
651651
}
652652
}
653653

654+
/** The pin's verdict for callers that otherwise read the local cache directly, or `null` when
655+
* there is no pin to honour.
656+
*
657+
* altimate_change — `resolveBindingOutcome` consults the pin before anything else, so identity,
658+
* skills and memory all follow the IDE extension's selection. Warehouse tool routing does not go
659+
* through it: `precedence.currentBinding` and `engine-probes.resolveBinding` read the on-disk
660+
* binding, which the pin is deliberately never written to. That let one turn name the pinned
661+
* workspace in the identity section and route warehouse calls at the project's own link — two
662+
* different ids in one prompt, with nothing saying which governs execution (#1337).
663+
*
664+
* Exposed as the pin arm alone, rather than pointing those callers at `resolveBindingOutcome`,
665+
* because the rest of that function is not equivalent to the strict cache read they do today: with
666+
* no credentials configured it answers `unknown` where the strict read answers "no binding", and
667+
* the overlay treats those differently — one refuses and holds the datamate key, the other hands
668+
* it back. Layering only the pin keeps every unpinned session on exactly the path it has now.
669+
*
670+
* Returns `unknown` for a pin that cannot be honoured (malformed, outside its root, unresolvable
671+
* credentials, or naming a workspace this account cannot see). Routing must fail closed there
672+
* rather than fall through to the project's link: falling through is precisely the confusion this
673+
* fixes, and it would resurface whenever validation could not complete. */
674+
export async function resolvePinnedBindingForRouting(
675+
directory: string,
676+
): Promise<BindingOutcome | null> {
677+
const pin = readPinLogged()
678+
if (pin.kind === "absent") return null
679+
if (pin.kind === "invalid") return { status: "unknown" }
680+
return resolvePinnedBinding(directory, pin)
681+
}
682+
654683
export async function resolveBindingOutcome(directory: string): Promise<BindingOutcome> {
655684
// altimate_change — the IDE extension's selection outranks whatever binding this project carries.
656685
// Checked before the local cache and before any server lookup: the whole point is that the panel,
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
// altimate_change - new file
2+
//
3+
// The IDE extension's pin governs warehouse tool ROUTING, not just identity, skills and memory.
4+
//
5+
// `state-pin.test.ts` covers the pin inside `resolveBindingOutcome`, which is what skills, memory
6+
// and the identity section read. Routing reads elsewhere — `engine-probes.resolveBinding` and
7+
// `precedence.currentBinding` went straight to the on-disk cache — so a pinned session could name
8+
// one workspace in the identity section and route warehouse calls at another (#1337). These cover
9+
// the routing side of that precedence, and the refusal, which is where the damage would be.
10+
import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"
11+
import { mkdirSync, rmSync } from "node:fs"
12+
import path from "node:path"
13+
import os from "node:os"
14+
15+
const ORIGINAL_XDG_STATE_HOME = process.env.XDG_STATE_HOME
16+
const SANDBOX = path.join(os.tmpdir(), `altimate-routing-pin-test-${process.pid}-${Date.now()}`)
17+
mkdirSync(path.join(SANDBOX, "state"), { recursive: true })
18+
process.env.XDG_STATE_HOME = path.join(SANDBOX, "state")
19+
20+
const { resolvePinnedBindingForRouting, recordApprovedBinding, __resetPinValidation } = await import(
21+
"../../../src/altimate/workspace/state"
22+
)
23+
const { resolveBinding } = await import("../../../src/altimate/workspace/engine-probes")
24+
const { AltimateApi } = await import("../../../src/altimate/api/client")
25+
const { WorkspaceApi } = await import("../../../src/altimate/workspace/api-client")
26+
27+
const ROOT = path.join(SANDBOX, "project")
28+
mkdirSync(ROOT, { recursive: true })
29+
30+
const originalIsConfigured = AltimateApi.isConfigured
31+
const originalGetCreds = AltimateApi.getCredentials
32+
const originalList = WorkspaceApi.listDatamates
33+
type Creds = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
34+
35+
function stubCreds() {
36+
;(AltimateApi as unknown as { isConfigured: () => Promise<boolean> }).isConfigured = async () => true
37+
;(AltimateApi as unknown as { getCredentials: () => Promise<Creds> }).getCredentials = async () =>
38+
({ altimateInstanceName: "acme", altimateUrl: "https://api.test", altimateApiKey: "k" }) as Creds
39+
}
40+
41+
function stubList(rows: { id: number; name: string }[]) {
42+
;(WorkspaceApi as unknown as { listDatamates: () => Promise<unknown> }).listDatamates = async () => rows
43+
}
44+
45+
const PIN_VARS = [
46+
"ALTIMATE_CODE_SERVE",
47+
"ALTIMATE_PINNED_WORKSPACE_ID",
48+
"ALTIMATE_PINNED_WORKSPACE_NAME",
49+
"ALTIMATE_PINNED_WORKSPACE_ROOT",
50+
]
51+
52+
function setPin(over: Record<string, string | undefined> = {}) {
53+
const base: Record<string, string | undefined> = {
54+
ALTIMATE_CODE_SERVE: "1",
55+
ALTIMATE_PINNED_WORKSPACE_ID: "42",
56+
ALTIMATE_PINNED_WORKSPACE_NAME: "pinned-workspace",
57+
ALTIMATE_PINNED_WORKSPACE_ROOT: ROOT,
58+
...over,
59+
}
60+
for (const [k, v] of Object.entries(base)) {
61+
if (v === undefined) delete process.env[k]
62+
else process.env[k] = v
63+
}
64+
}
65+
66+
function clearPin() {
67+
for (const k of PIN_VARS) delete process.env[k]
68+
}
69+
70+
/** The project's own link, naming a DIFFERENT workspace than the pin — the returning-user case
71+
* from the report, where identity said one id and routing said another. */
72+
async function seedLocalLink(datamateId = 7, datamateName = "project-link") {
73+
await recordApprovedBinding(ROOT, {
74+
datamateId,
75+
datamateName,
76+
linkedAt: Date.now(),
77+
repoRemote: "[email protected]:acme/project.git",
78+
// Both identity keys are written explicitly: the strict reader rejects a row where either is
79+
// `undefined` (it accepts `string | null`), so omitting one produces a cache the routing read
80+
// cannot parse — which looks like a product failure in a test that is only mis-seeded.
81+
projectPath: null,
82+
} as never)
83+
}
84+
85+
beforeEach(() => {
86+
__resetPinValidation()
87+
stubCreds()
88+
stubList([
89+
{ id: 42, name: "pinned-workspace" },
90+
{ id: 7, name: "project-link" },
91+
])
92+
clearPin()
93+
})
94+
95+
afterEach(() => {
96+
clearPin()
97+
__resetPinValidation()
98+
})
99+
100+
afterAll(() => {
101+
;(AltimateApi as unknown as { isConfigured: unknown }).isConfigured = originalIsConfigured
102+
;(AltimateApi as unknown as { getCredentials: unknown }).getCredentials = originalGetCreds
103+
;(WorkspaceApi as unknown as { listDatamates: unknown }).listDatamates = originalList
104+
if (ORIGINAL_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME
105+
else process.env.XDG_STATE_HOME = ORIGINAL_XDG_STATE_HOME
106+
rmSync(SANDBOX, { recursive: true, force: true })
107+
})
108+
109+
describe("resolvePinnedBindingForRouting", () => {
110+
test("answers null with no pin, so unpinned sessions keep reading their own link", async () => {
111+
expect(await resolvePinnedBindingForRouting(ROOT)).toBeNull()
112+
})
113+
114+
test("returns the pinned workspace when the account can see it", async () => {
115+
setPin()
116+
const outcome = await resolvePinnedBindingForRouting(ROOT)
117+
expect(outcome?.status).toBe("bound")
118+
expect(outcome?.status === "bound" && outcome.binding.datamateId).toBe(42)
119+
})
120+
121+
test("refuses a malformed pin rather than falling through to the project's link", async () => {
122+
setPin({ ALTIMATE_PINNED_WORKSPACE_ID: "not-a-number" })
123+
expect((await resolvePinnedBindingForRouting(ROOT))?.status).toBe("unknown")
124+
})
125+
126+
test("refuses a pin naming a workspace this account cannot see", async () => {
127+
stubList([{ id: 7, name: "project-link" }])
128+
setPin()
129+
expect((await resolvePinnedBindingForRouting(ROOT))?.status).toBe("unknown")
130+
})
131+
132+
test("refuses a pin for a directory outside the pinned root", async () => {
133+
setPin()
134+
expect((await resolvePinnedBindingForRouting(path.join(SANDBOX, "elsewhere")))?.status).toBe("unknown")
135+
})
136+
})
137+
138+
describe("engine-probes.resolveBinding — the routing read", () => {
139+
test("routes at the pin, not the project's own link", async () => {
140+
await seedLocalLink(7)
141+
setPin()
142+
const read = await resolveBinding(ROOT)
143+
expect(read.kind).toBe("bound")
144+
// The regression: this returned 7 — the identity section said 42 in the same prompt.
145+
expect(read.kind === "bound" && read.binding.datamateId).toBe(42)
146+
})
147+
148+
test("still reads the project's own link when nothing is pinned", async () => {
149+
await seedLocalLink(7)
150+
const read = await resolveBinding(ROOT)
151+
expect(read.kind).toBe("bound")
152+
expect(read.kind === "bound" && read.binding.datamateId).toBe(7)
153+
})
154+
155+
test("fails closed when the pin cannot be honoured, rather than routing at the project's link", async () => {
156+
await seedLocalLink(7)
157+
stubList([{ id: 7, name: "project-link" }])
158+
setPin()
159+
const read = await resolveBinding(ROOT)
160+
// Not `bound` at 7: falling back to the project's link is the confusion this prevents.
161+
expect(read.kind).toBe("failed")
162+
})
163+
164+
test("carries the credential scope so the engine key stays account-partitioned", async () => {
165+
setPin()
166+
const read = await resolveBinding(ROOT)
167+
expect(read.kind === "bound" && read.binding.scope).toBe("acme|https://api.test")
168+
})
169+
})

0 commit comments

Comments
 (0)