Skip to content

Commit 8797774

Browse files
saravmajesticclaude
andcommitted
feat(workspace): expose /workspace Refresh and Sync over serve HTTP
- Add `POST /altimate/workspace/refresh` (optional `{ sessionID }`) and `POST /altimate/workspace/sync`, returning the `Manage` reports as is. Refused with 409 outside the workspace pilot. - `Manage.sync` honours the IDE extension's pin before the on-disk link, as the per-write mirror already does; an unhonourable pin stays gated. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent 282e784 commit 8797774

4 files changed

Lines changed: 325 additions & 1 deletion

File tree

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

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ import {
3333
peekRowUnscoped,
3434
readLocalBinding,
3535
resolveBinding,
36+
resolvePinnedBindingForRouting,
3637
type CachedBinding,
3738
} from "./state"
3839

@@ -226,7 +227,17 @@ export async function sync(directory: string): Promise<SyncReport> {
226227
deferred: 0,
227228
})
228229
if (!MemorySync.isEnabled()) return gated("flag-off")
229-
const binding = await readLocalBinding(directory).catch(() => null)
230+
// altimate_change — the IDE extension's pin outranks the project's own link, as it does for
231+
// the per-write mirror (`memory-sync.resolveBinding`). Without it an extension-launched `serve`
232+
// answered "not linked" for the workspace it was pinned to. Only the pin arm is layered, so an
233+
// unpinned session keeps the cache-only read, and a pin that cannot be honoured stays gated
234+
// rather than falling through to the project's link.
235+
const pinned = await resolvePinnedBindingForRouting(directory).catch(() => ({ status: "unknown" as const }))
236+
const binding = pinned
237+
? pinned.status === "bound"
238+
? pinned.binding
239+
: null
240+
: await readLocalBinding(directory).catch(() => null)
230241
if (!binding) return gated("no-binding")
231242

232243
const blocks = await MemoryStore.listAll({ directory }).catch((err) => {

‎packages/opencode/src/server/server.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,8 @@ import { FreeTierConsent } from "../altimate/free/consent"
4545
import { InstanceStore } from "@/project/instance-store"
4646
import { AppRuntime } from "@/effect/app-runtime"
4747
// altimate_change end
48+
// altimate_change - `/workspace` Refresh and Sync are gated on the workspace pilot flag
49+
import { Flag as CoreFlag } from "@opencode-ai/core/flag/flag"
4850
// altimate_change end
4951
import { FileRoutes } from "./routes/file"
5052
import { ConfigRoutes } from "./routes/config"
@@ -949,6 +951,44 @@ export namespace Server {
949951
}
950952
})
951953
// altimate_change end
954+
// altimate_change start — POST /altimate/workspace/{refresh,sync}
955+
// The `/workspace` menu's Refresh and Sync for the IDE extension, which runs this CLI
956+
// headless and cannot reach the TUI slash command. Both act on the request's instance
957+
// directory and return the `Manage` report as is; wording is the caller's job.
958+
// Refused outside the workspace pilot: with the flag off, a skill sync purges the snapshot.
959+
.post("/altimate/workspace/refresh", async (c) => {
960+
if (!CoreFlag.ALTIMATE_WORKSPACE) {
961+
return c.json({ ok: false, error: "Workspace mode is not enabled for this server." }, 409)
962+
}
963+
try {
964+
const body = await c.req.json().catch(() => ({}))
965+
const sessionID = typeof body?.sessionID === "string" && body.sessionID ? body.sessionID : undefined
966+
const Manage = await import("../altimate/workspace/manage")
967+
// A changed skill snapshot reaches the registry at the start of the next turn
968+
// (`refreshSkillRegistry` in session/prompt.ts), so nothing is invalidated here.
969+
const report = await Manage.refresh(Instance.directory, sessionID)
970+
return c.json({ ok: true as const, ...report })
971+
} catch (err) {
972+
const error = err instanceof Error ? err.message : String(err)
973+
log.error("workspace refresh: failed", { error })
974+
return c.json({ ok: false, error }, 500)
975+
}
976+
})
977+
.post("/altimate/workspace/sync", async (c) => {
978+
if (!CoreFlag.ALTIMATE_WORKSPACE) {
979+
return c.json({ ok: false, error: "Workspace mode is not enabled for this server." }, 409)
980+
}
981+
try {
982+
const Manage = await import("../altimate/workspace/manage")
983+
const report = await Manage.sync(Instance.directory)
984+
return c.json({ ok: true as const, ...report })
985+
} catch (err) {
986+
const error = err instanceof Error ? err.message : String(err)
987+
log.error("workspace sync: failed", { error })
988+
return c.json({ ok: false, error }, 500)
989+
}
990+
})
991+
// altimate_change end
952992
.all("/*", async (c) => {
953993
const path = c.req.path
954994

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
// altimate_change - new file
2+
//
3+
// `/workspace` Sync follows the IDE extension's pin. `Manage.sync` read only the on-disk link, so a
4+
// `serve` pinned by the extension answered "not linked" for the workspace it was pinned to, while
5+
// the per-write mirror (which resolves through the pin) sent to it. These cover which binding the
6+
// sweep runs against; the sweep itself is covered by manage.test.ts and memory-sync.test.ts.
7+
import { afterAll, afterEach, beforeEach, describe, expect, test } from "bun:test"
8+
import { mkdirSync, rmSync } from "node:fs"
9+
import path from "node:path"
10+
import os from "node:os"
11+
12+
const ORIGINAL_XDG_STATE_HOME = process.env.XDG_STATE_HOME
13+
const ORIGINAL_PILOT = process.env.ALTIMATE_WORKSPACE
14+
const SANDBOX = path.join(os.tmpdir(), `altimate-manage-pin-test-${process.pid}-${Date.now()}`)
15+
mkdirSync(path.join(SANDBOX, "state"), { recursive: true })
16+
process.env.XDG_STATE_HOME = path.join(SANDBOX, "state")
17+
18+
const { recordApprovedBinding, __resetPinValidation } = await import("../../../src/altimate/workspace/state")
19+
const { sync } = await import("../../../src/altimate/workspace/manage")
20+
const { resetEnablementMemoForTests } = await import("../../../src/altimate/workspace/memory-sync")
21+
const { AltimateApi } = await import("../../../src/altimate/api/client")
22+
const { WorkspaceApi } = await import("../../../src/altimate/workspace/api-client")
23+
24+
const ROOT = path.join(SANDBOX, "project")
25+
const OUTSIDE = path.join(SANDBOX, "elsewhere")
26+
mkdirSync(ROOT, { recursive: true })
27+
mkdirSync(OUTSIDE, { recursive: true })
28+
29+
const originalIsConfigured = AltimateApi.isConfigured
30+
const originalGetCreds = AltimateApi.getCredentials
31+
const originalList = WorkspaceApi.listDatamates
32+
type Creds = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
33+
34+
const PIN_VARS = [
35+
"ALTIMATE_CODE_SERVE",
36+
"ALTIMATE_PINNED_WORKSPACE_ID",
37+
"ALTIMATE_PINNED_WORKSPACE_NAME",
38+
"ALTIMATE_PINNED_WORKSPACE_ROOT",
39+
]
40+
41+
/** The pinned workspace has memory ON and the project's own link has it OFF, so the gate reason
42+
* says which of the two the sweep ran against. */
43+
const WORKSPACES = [
44+
{ id: 42, name: "pinned-workspace", memoryEnabled: true },
45+
{ id: 7, name: "project-link", memoryEnabled: false },
46+
]
47+
48+
function setPin(id = "42") {
49+
process.env.ALTIMATE_CODE_SERVE = "1"
50+
process.env.ALTIMATE_PINNED_WORKSPACE_ID = id
51+
process.env.ALTIMATE_PINNED_WORKSPACE_NAME = "pinned-workspace"
52+
process.env.ALTIMATE_PINNED_WORKSPACE_ROOT = ROOT
53+
}
54+
55+
function clearPin() {
56+
for (const k of PIN_VARS) delete process.env[k]
57+
}
58+
59+
async function seedLocalLink(directory = ROOT) {
60+
await recordApprovedBinding(directory, {
61+
datamateId: 7,
62+
datamateName: "project-link",
63+
linkedAt: Date.now(),
64+
repoRemote: "[email protected]:acme/project.git",
65+
projectPath: null,
66+
} as never)
67+
}
68+
69+
beforeEach(() => {
70+
process.env.ALTIMATE_WORKSPACE = "1"
71+
__resetPinValidation()
72+
resetEnablementMemoForTests()
73+
;(AltimateApi as unknown as { isConfigured: () => Promise<boolean> }).isConfigured = async () => true
74+
;(AltimateApi as unknown as { getCredentials: () => Promise<Creds> }).getCredentials = async () =>
75+
({ altimateInstanceName: "acme", altimateUrl: "https://api.test", altimateApiKey: "k" }) as Creds
76+
;(WorkspaceApi as unknown as { listDatamates: () => Promise<unknown> }).listDatamates = async () => WORKSPACES
77+
clearPin()
78+
})
79+
80+
afterEach(() => {
81+
clearPin()
82+
})
83+
84+
afterAll(() => {
85+
;(AltimateApi as unknown as { isConfigured: typeof originalIsConfigured }).isConfigured = originalIsConfigured
86+
;(AltimateApi as unknown as { getCredentials: typeof originalGetCreds }).getCredentials = originalGetCreds
87+
;(WorkspaceApi as unknown as { listDatamates: typeof originalList }).listDatamates = originalList
88+
if (ORIGINAL_XDG_STATE_HOME === undefined) delete process.env.XDG_STATE_HOME
89+
else process.env.XDG_STATE_HOME = ORIGINAL_XDG_STATE_HOME
90+
if (ORIGINAL_PILOT === undefined) delete process.env.ALTIMATE_WORKSPACE
91+
else process.env.ALTIMATE_WORKSPACE = ORIGINAL_PILOT
92+
rmSync(SANDBOX, { recursive: true, force: true })
93+
})
94+
95+
describe("sync under an IDE pin", () => {
96+
test("runs against the pinned workspace in a project that was never linked", async () => {
97+
setPin()
98+
const report = await sync(ROOT)
99+
expect(report.gated).toBe(false)
100+
expect(report.gatedBecause).toBeUndefined()
101+
})
102+
103+
test("the pin outranks the project's own link", async () => {
104+
await seedLocalLink()
105+
setPin()
106+
// The local link (7) has memory off and would gate; the pin (42) has it on.
107+
expect((await sync(ROOT)).gated).toBe(false)
108+
})
109+
110+
test("a pin naming a workspace this account cannot see fails closed, not onto the local link", async () => {
111+
await seedLocalLink()
112+
setPin("99")
113+
const report = await sync(ROOT)
114+
expect(report.gated).toBe(true)
115+
expect(report.gatedBecause).toBe("no-binding")
116+
})
117+
118+
test("a directory outside the pinned root is not treated as pinned", async () => {
119+
setPin()
120+
const report = await sync(OUTSIDE)
121+
expect(report.gated).toBe(true)
122+
expect(report.gatedBecause).toBe("no-binding")
123+
})
124+
})
125+
126+
describe("sync without a pin", () => {
127+
test("still reads the project's own link", async () => {
128+
await seedLocalLink()
129+
const report = await sync(ROOT)
130+
// Reached the sweep with link 7, whose memory is off.
131+
expect(report.gated).toBe(true)
132+
expect(report.gatedBecause).toBe("memory-off")
133+
})
134+
135+
test("an unlinked project is still gated on the missing binding", async () => {
136+
// A directory no test links: the binding cache is process-memoized, so `ROOT` may still hold one.
137+
const report = await sync(OUTSIDE)
138+
expect(report.gatedBecause).toBe("no-binding")
139+
})
140+
})
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
// altimate_change - new file
2+
//
3+
// `/altimate/workspace/{refresh,sync}`: the `/workspace` menu's Refresh and Sync for the IDE
4+
// extension. These cover the ROUTE only — the flag gate, argument passthrough and report shape —
5+
// with `Manage` stubbed; the operations themselves are covered by test/altimate/workspace/manage.test.ts.
6+
import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test"
7+
import { Server } from "../../src/server/server"
8+
import * as Manage from "../../src/altimate/workspace/manage"
9+
import { resetDatabase } from "./db"
10+
import { disposeAllInstances } from "../fixture/fixture"
11+
12+
const ORIGINAL_FLAG = process.env.ALTIMATE_WORKSPACE
13+
let spies: Array<{ mockRestore: () => void }> = []
14+
15+
function post(path: string, body?: unknown) {
16+
return Server.Default().request(path, {
17+
method: "POST",
18+
headers: { "content-type": "application/json" },
19+
body: body === undefined ? undefined : JSON.stringify(body),
20+
})
21+
}
22+
23+
beforeEach(() => {
24+
process.env.ALTIMATE_WORKSPACE = "1"
25+
})
26+
27+
afterEach(async () => {
28+
for (const spy of spies) spy.mockRestore()
29+
spies = []
30+
if (ORIGINAL_FLAG === undefined) delete process.env.ALTIMATE_WORKSPACE
31+
else process.env.ALTIMATE_WORKSPACE = ORIGINAL_FLAG
32+
await disposeAllInstances()
33+
await resetDatabase()
34+
})
35+
36+
describe("POST /altimate/workspace/refresh", () => {
37+
test("returns the refresh report and passes the session through", async () => {
38+
const refresh = spyOn(Manage, "refresh").mockResolvedValue({
39+
skillsChanged: true,
40+
memory: { ok: true, status: "reloaded", blocks: 4 } as unknown as Manage.RefreshReport["memory"],
41+
errors: [],
42+
})
43+
spies.push(refresh)
44+
45+
const response = await post("/altimate/workspace/refresh", { sessionID: "ses_123" })
46+
expect(response.status).toBe(200)
47+
const body = (await response.json()) as Record<string, unknown>
48+
expect(body.ok).toBe(true)
49+
expect(body.skillsChanged).toBe(true)
50+
expect(body.errors).toEqual([])
51+
expect(refresh).toHaveBeenCalledTimes(1)
52+
expect(refresh.mock.calls[0][1]).toBe("ses_123")
53+
})
54+
55+
test("works without a body, leaving the memory overlay to reload on the next turn", async () => {
56+
const refresh = spyOn(Manage, "refresh").mockResolvedValue({
57+
skillsChanged: false,
58+
memoryInvalidated: true,
59+
errors: [],
60+
})
61+
spies.push(refresh)
62+
63+
const response = await post("/altimate/workspace/refresh")
64+
expect(response.status).toBe(200)
65+
expect(((await response.json()) as Record<string, unknown>).memoryInvalidated).toBe(true)
66+
expect(refresh.mock.calls[0][1]).toBeUndefined()
67+
})
68+
69+
test("ignores a session id that is not a string", async () => {
70+
const refresh = spyOn(Manage, "refresh").mockResolvedValue({ skillsChanged: false, errors: [] })
71+
spies.push(refresh)
72+
73+
await post("/altimate/workspace/refresh", { sessionID: 42 })
74+
expect(refresh.mock.calls[0][1]).toBeUndefined()
75+
})
76+
77+
test("is refused outside the workspace pilot, without touching the snapshot", async () => {
78+
delete process.env.ALTIMATE_WORKSPACE
79+
const refresh = spyOn(Manage, "refresh")
80+
spies.push(refresh)
81+
82+
const response = await post("/altimate/workspace/refresh")
83+
expect(response.status).toBe(409)
84+
expect(((await response.json()) as Record<string, unknown>).ok).toBe(false)
85+
expect(refresh).not.toHaveBeenCalled()
86+
})
87+
88+
test("reports a thrown error as a 500 with its message", async () => {
89+
spies.push(spyOn(Manage, "refresh").mockRejectedValue(new Error("boom")))
90+
91+
const response = await post("/altimate/workspace/refresh")
92+
expect(response.status).toBe(500)
93+
expect(await response.json()).toEqual({ ok: false, error: "boom" })
94+
})
95+
})
96+
97+
describe("POST /altimate/workspace/sync", () => {
98+
test("returns the sync report", async () => {
99+
const report: Manage.SyncReport = { gated: false, sent: 2, failed: 0, skipped: 5, declined: 0, deferred: 1 }
100+
spies.push(spyOn(Manage, "sync").mockResolvedValue(report))
101+
102+
const response = await post("/altimate/workspace/sync")
103+
expect(response.status).toBe(200)
104+
expect(await response.json()).toEqual({ ok: true, ...report })
105+
})
106+
107+
test("passes a gated sweep through with its reason", async () => {
108+
spies.push(
109+
spyOn(Manage, "sync").mockResolvedValue({
110+
gated: true,
111+
gatedBecause: "memory-off",
112+
sent: 0,
113+
failed: 0,
114+
skipped: 0,
115+
declined: 0,
116+
deferred: 0,
117+
}),
118+
)
119+
120+
const body = (await (await post("/altimate/workspace/sync")).json()) as Record<string, unknown>
121+
expect(body.gated).toBe(true)
122+
expect(body.gatedBecause).toBe("memory-off")
123+
})
124+
125+
test("is refused outside the workspace pilot", async () => {
126+
delete process.env.ALTIMATE_WORKSPACE
127+
const sync = spyOn(Manage, "sync")
128+
spies.push(sync)
129+
130+
expect((await post("/altimate/workspace/sync")).status).toBe(409)
131+
expect(sync).not.toHaveBeenCalled()
132+
})
133+
})

0 commit comments

Comments
 (0)