Skip to content

Commit 93fe816

Browse files
fix(workspace): scope the binding cache and skill snapshot to the account (#1377)
Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
1 parent 8fe2e0c commit 93fe816

14 files changed

Lines changed: 1230 additions & 149 deletions

File tree

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@
2323
// pedantically re-qualifying every casual mention of one. Neither is this feature's
2424
// job — resolving "this/current/active workspace" is.
2525
import { createHash } from "node:crypto"
26-
import { onBindingChanged, readLocalBindingScoped, resolveBindingOutcome, type BindingOutcome } from "./state"
26+
import { onBindingChanged, readLocalBindingScoped, resolveBindingOutcome, type BindingOutcome, currentScope, scopeStringOf} from "./state"
2727
import { readPin, resolveWithinRoot } from "./pin"
2828
import { workspaceLabel } from "./workspace-name"
2929
import { isEnabled } from "./engine-seams"
@@ -378,7 +378,12 @@ async function lastKnown(key: string, directory: string): Promise<BindingOutcome
378378
// rather than the workspace the pin exists to override.
379379
if (readPin().kind !== "absent") return { status: "unknown" }
380380
const local = await readLocalBindingScoped(directory).catch(() => ({ binding: null, scope: null }))
381-
if (local.binding && local.scope === `${scope.tenant}|${scope.apiUrl}`) {
381+
// Compared through the same builder the read uses. `accountScope()` here and
382+
// the cache's own key digest the credential differently, so reconstructing
383+
// the string from this scope silently stopped matching once the cache began
384+
// carrying an account.
385+
const cacheScope = await currentScope().catch(() => null)
386+
if (local.binding && cacheScope && local.scope === scopeStringOf(cacheScope)) {
382387
return { status: "bound", binding: local.binding, stale: true }
383388
}
384389
return { status: "unknown" }

‎packages/opencode/src/altimate/workspace/memory-index.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ interface Scope {
118118
}
119119

120120
async function currentScope(): Promise<Scope | null> {
121-
// Defensive for the same reason as state.ts::tenantKey — a corrupt
121+
// Defensive for the same reason as state.ts::accountKey — a corrupt
122122
// credentials file or schema drift must read as "no credentials", never as a
123123
// rejection into a fire-and-forget mirror call.
124124
try {

‎packages/opencode/src/altimate/workspace/skill-sync.ts‎

Lines changed: 215 additions & 34 deletions
Large diffs are not rendered by default.

‎packages/opencode/src/altimate/workspace/snapshot-path.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,23 @@ import path from "path"
88

99
const SNAPSHOT_SEGMENTS = [".altimate-code", "skill", "_workspace"]
1010

11-
export function isInWorkspaceSnapshot(location: string): boolean {
11+
/** The project a path belongs to, if the path lies inside that project's managed snapshot; `null`
12+
* otherwise.
13+
*
14+
* A project opened AT the filesystem root puts the snapshot's first segment at index 0, which is a
15+
* project of `/` and not "no project" — the difference decides whether discovery gates the file or
16+
* serves it, so it is spelled out rather than left to a truthiness test. (review) */
17+
export function snapshotProjectOf(location: string): string | null {
1218
const parts = path.resolve(location).split(path.sep)
1319
for (let i = 0; i + SNAPSHOT_SEGMENTS.length <= parts.length; i++) {
14-
if (SNAPSHOT_SEGMENTS.every((segment, j) => parts[i + j] === segment)) return true
20+
if (SNAPSHOT_SEGMENTS.every((segment, j) => parts[i + j] === segment))
21+
return parts.slice(0, i).join(path.sep) || path.sep
1522
}
16-
return false
23+
return null
24+
}
25+
26+
export function isInWorkspaceSnapshot(location: string): boolean {
27+
return snapshotProjectOf(location) !== null
1728
}
1829

1930
/** Whether `location` lies inside `root`, by path segments. */

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

Lines changed: 154 additions & 51 deletions
Large diffs are not rendered by default.

‎packages/opencode/src/session/prompt.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,11 +130,11 @@ export namespace SessionPrompt {
130130
* snapshot and needs the registry refreshed exactly as adding one does. */
131131
async function refreshSkillRegistry(dir: string): Promise<void> {
132132
const skillSync = await import("../altimate/workspace/skill-sync")
133-
if (!skillSync.registryStale(dir)) return
133+
if (!(await skillSync.registryStale(dir))) return
134134
// Marked BEFORE the work, not after: a refresh that throws must not be
135135
// retried on every subsequent turn forever, and the next real snapshot
136136
// change re-arms this anyway.
137-
skillSync.markRegistryApplied(dir)
137+
await skillSync.markRegistryApplied(dir)
138138
const { Skill } = await import("../skill")
139139
// Both drops go through the in-context services rather than the imperative
140140
// facades. Discovery re-derives its roots from `Config.directories()`, which

‎packages/opencode/src/skill/index.ts‎

Lines changed: 95 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node"
33
import { makeRuntime } from "@/effect/run-service"
44
// altimate_change end
55
// altimate_change start — workspace snapshot precedence in `add`
6-
import { snapshotCopyYields } from "@/altimate/workspace/snapshot-path"
6+
import { snapshotCopyYields, snapshotProjectOf } from "@/altimate/workspace/snapshot-path"
77
// altimate_change end
88
import path from "path"
9+
// altimate_change — realpath for workspace snapshot attribution
10+
import fsp from "fs/promises"
911
import { pathToFileURL } from "url"
1012
import { Effect, Layer, Context, Schema } from "effect"
1113
import { NamedError } from "@opencode-ai/core/util/error"
@@ -286,12 +288,102 @@ const discoverSkills = Effect.fnUntraced(function* (
286288
}
287289
}
288290

291+
// altimate_change start — a workspace snapshot is served only to the account
292+
// that fetched it. `syncSkills` deletes a foreign snapshot, but it cannot be
293+
// relied on to get there first: the prompt path refreshes this registry
294+
// BEFORE it polls, and two processes sharing one checkout have no ordering
295+
// between them at all. Asking here is what actually keeps one user's private
296+
// workspace skills out of another user's session.
297+
const matches = yield* withoutForeignSnapshots(Array.from(state.matches))
289298
return {
290-
matches: Array.from(state.matches),
291-
dirs: Array.from(state.dirs),
299+
// Rebuilt from the surviving matches rather than filtered out of
300+
// `state.dirs`: that set holds exactly these dirnames (`scan` is its only
301+
// writer), and a withheld skill must not leave its directory behind.
302+
matches,
303+
dirs: Array.from(new Set(matches.map((match) => path.dirname(match)))),
292304
}
305+
// altimate_change end
293306
})
294307

308+
// altimate_change start — workspace snapshot attribution
309+
/** Drop matches under a managed workspace snapshot this account did not fetch.
310+
*
311+
* Attribution is decided on the real path as well as the matched one. `scan`
312+
* follows symlinks, so a link from another scanned skill directory into
313+
* `_workspace` yields a match whose own path carries no managed component, and
314+
* a link the other way out of `_workspace` yields one whose resolved path does
315+
* not. (review) The cost is one `realpath` per match, against a discovery pass
316+
* that goes on to read and parse every one of them.
317+
*
318+
* One attribution question per project, not per skill file. Fails CLOSED: if
319+
* the manifest or the credentials cannot be read the snapshot is withheld,
320+
* which costs a poll interval, where serving it cannot be taken back. */
321+
const withoutForeignSnapshots = Effect.fnUntraced(function* (matches: string[]) {
322+
// `null` means "could not be resolved", and it is withheld rather than
323+
// served. Falling back to the matched path would answer "ordinary skill" for
324+
// an alias whose target merely happened to be unreadable at this instant,
325+
// such as during a concurrent snapshot swap — and if the target became
326+
// readable again before `add` ran, its content loaded with no account check
327+
// at all. A path that cannot be resolved cannot be attributed. (review)
328+
const real = yield* Effect.promise(() =>
329+
Promise.all(
330+
matches.map((match) =>
331+
fsp.realpath(match).then(
332+
(resolved) => resolved as string | null,
333+
() => null,
334+
),
335+
),
336+
),
337+
)
338+
339+
const unresolved = matches.filter((_, i) => !real[i])
340+
if (unresolved.length > 0)
341+
yield* Effect.logWarning("withholding skills whose paths could not be resolved", { paths: unresolved })
342+
343+
// BOTH ends, because a symlink crosses the boundary in either direction: one
344+
// pointing INTO a snapshot has no managed component in its matched path, and
345+
// one INSIDE a snapshot pointing out has none in its resolved path. Checking
346+
// only the resolved end traded the first bypass for the second. A match that
347+
// touches any managed project is served only if every one of them is ours.
348+
// (review)
349+
const projectsOf = (match: string, resolved: string | null): string[] => {
350+
const found = new Set<string>()
351+
for (const candidate of [match, resolved]) {
352+
if (!candidate) continue
353+
const project = snapshotProjectOf(candidate)
354+
if (project !== null) found.add(project)
355+
}
356+
return [...found]
357+
}
358+
359+
const projects = new Set<string>()
360+
matches.forEach((match, i) => {
361+
for (const project of projectsOf(match, real[i] ?? null)) projects.add(project)
362+
})
363+
if (projects.size === 0 && unresolved.length === 0) return matches
364+
365+
const ours = new Map<string, boolean>()
366+
for (const project of projects) {
367+
const ok = yield* Effect.promise(async () => {
368+
try {
369+
const m = await import("@/altimate/workspace/skill-sync")
370+
return await m.snapshotIsOurs(project)
371+
} catch {
372+
return false
373+
}
374+
})
375+
if (!ok) yield* Effect.logInfo("withholding a workspace skill snapshot fetched by another account", { project })
376+
ours.set(project, ok)
377+
}
378+
379+
return matches.filter((match, i) => {
380+
const resolved = real[i]
381+
if (!resolved) return false
382+
return projectsOf(match, resolved).every((project) => ours.get(project) === true)
383+
})
384+
})
385+
// altimate_change end
386+
295387
// altimate_change start — `loadSkills` passes the project boundary through to `add`
296388
const loadSkills = Effect.fnUntraced(function* (
297389
state: State,

‎packages/opencode/test/altimate/workspace/identity-section.test.ts‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,11 +42,20 @@ const {
4242
} = await import(
4343
"../../../src/altimate/workspace/identity",
4444
)
45-
const { recordApprovedBinding, clearLocalBinding, __resetPinValidation } = await import(
45+
const { recordApprovedBinding, clearLocalBinding, credentialDigest, __resetPinValidation } = await import(
4646
"../../../src/altimate/workspace/state"
4747
)
4848
const { Instance } = await import("../../../src/project/instance")
4949

50+
/** The credential scope the stub credentials below resolve to. Built from the
51+
* same digest the cache uses, so a change to how an account is identified
52+
* shows up here rather than silently leaving these clears pointed at nothing. */
53+
const ACME_SCOPE = {
54+
tenant: "acme",
55+
apiUrl: "https://api.example.com",
56+
account: credentialDigest("https://api.example.com", "acme", "k"),
57+
}
58+
5059
type Creds = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
5160
const originalIsConfigured = AltimateApi.isConfigured
5261
const originalGetCreds = AltimateApi.getCredentials
@@ -237,7 +246,7 @@ describe("systemSection", () => {
237246
linkedAt: Date.now(),
238247
})
239248
expect(await inProject(systemSection)).toContain('is "analytics"')
240-
await clearLocalBinding(projectDir, { scope: { tenant: "acme", apiUrl: "https://api.example.com" } })
249+
await clearLocalBinding(projectDir, { scope: ACME_SCOPE })
241250
globalThis.fetch = (async () =>
242251
new Response(JSON.stringify({ detail: "not found" }), {
243252
status: 404,
@@ -281,7 +290,7 @@ describe("systemSection", () => {
281290
globalThis.fetch = (async () => {
282291
if (!unlinkedMidFlight) {
283292
unlinkedMidFlight = true
284-
await clearLocalBinding(projectDir, { scope: { tenant: "acme", apiUrl: "https://api.example.com" } })
293+
await clearLocalBinding(projectDir, { scope: ACME_SCOPE })
285294
}
286295
throw new Error("offline")
287296
}) as unknown as typeof fetch
@@ -506,7 +515,7 @@ describe("systemSection", () => {
506515
}) as unknown as typeof fetch
507516
const first = inProject(systemSection)
508517
await firstOnWire // step 1's request is out and parked on the gate
509-
await clearLocalBinding(projectDir, { scope: { tenant: "acme", apiUrl: "https://api.example.com" } })
518+
await clearLocalBinding(projectDir, { scope: ACME_SCOPE })
510519
const second = inProject(systemSection)
511520
await secondOnWire // step 2 made its OWN request while step 1 was still pending
512521
release()

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

Lines changed: 38 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,12 @@ const {
4949
expireValidationForTests,
5050
cachePath,
5151
} = await import("../../../src/altimate/workspace/state")
52+
const { credentialDigest: manifestDigest } = await import("../../../src/altimate/workspace/state")
53+
/** Accounts these fixtures belong to. A manifest with no account cannot be
54+
* attributed, so it is rejected rather than trusted — the same rule a real one
55+
* written by another user meets. */
56+
const ACME_ACCOUNT = manifestDigest("https://api.example.com", "acme", "key-a")
57+
const OTHER_ACCOUNT = manifestDigest("https://api.example.com", "other", "key-b")
5258
const { resolveProjectIdentifier } = await import("../../../src/altimate/workspace/detect")
5359
const { resetPollMemoForTests, resetEnablementMemoForTests, pendingCount, memoryEnabledCache, memoryEnabledForPoller } =
5460
await import("../../../src/altimate/workspace/memory-sync")
@@ -390,7 +396,7 @@ describe("what unlink leaves on disk", () => {
390396
writeFileSync(path.join(snapshot, "pub-x", "SKILL.md"), "theirs now")
391397
writeFileSync(
392398
path.join(snapshot, ".manifest.json"),
393-
JSON.stringify({ version: 1, tenant: "acme", apiUrl: "https://api.example.com", datamateId: to, skills: {} }),
399+
JSON.stringify({ version: 2, tenant: "acme", apiUrl: "https://api.example.com", account: ACME_ACCOUNT, datamateId: to, skills: {} }),
394400
)
395401
return new Response(null, { status: 204 })
396402
}
@@ -555,7 +561,7 @@ describe("what unlink leaves on disk", () => {
555561
writeFileSync(path.join(snapshot, "pub-x", "SKILL.md"), "theirs now")
556562
writeFileSync(
557563
path.join(snapshot, ".manifest.json"),
558-
JSON.stringify({ version: 1, tenant: "acme", apiUrl: "https://api.example.com", datamateId: 99, skills: {} }),
564+
JSON.stringify({ version: 2, tenant: "acme", apiUrl: "https://api.example.com", account: ACME_ACCOUNT, datamateId: 99, skills: {} }),
559565
)
560566
return new Response(JSON.stringify({ detail: "gone" }), {
561567
status: 404,
@@ -595,7 +601,7 @@ describe("what unlink leaves on disk", () => {
595601
writeFileSync(path.join(snapshot, "pub-x", "SKILL.md"), "theirs now")
596602
writeFileSync(
597603
path.join(snapshot, ".manifest.json"),
598-
JSON.stringify({ version: 1, tenant: "other", apiUrl: "https://api.example.com", datamateId: 77, skills: {} }),
604+
JSON.stringify({ version: 2, tenant: "other", apiUrl: "https://api.example.com", account: OTHER_ACCOUNT, datamateId: 77, skills: {} }),
599605
)
600606
return new Response(null, { status: 204 })
601607
}
@@ -631,7 +637,7 @@ describe("what unlink leaves on disk", () => {
631637
writeFileSync(path.join(snapshot, "pub-x", "SKILL.md"), "stale")
632638
writeFileSync(
633639
path.join(snapshot, ".manifest.json"),
634-
JSON.stringify({ version: 1, tenant: "other", apiUrl: "https://api.example.com", datamateId: 77, skills: {} }),
640+
JSON.stringify({ version: 2, tenant: "other", apiUrl: "https://api.example.com", account: OTHER_ACCOUNT, datamateId: 77, skills: {} }),
635641
)
636642

637643
const report = await unlink(projectDir)
@@ -959,11 +965,37 @@ describe("what /workspace status may cost and claim (review round 2)", () => {
959965
})
960966

961967
const manifestFor = (datamateId: number) =>
962-
JSON.stringify({ version: 1, tenant: "acme", apiUrl: "https://api.example.com", datamateId, skills: {} })
968+
JSON.stringify({ version: 2, tenant: "acme", apiUrl: "https://api.example.com", account: ACME_ACCOUNT, datamateId, skills: {} })
963969
const markerFor = (datamateId: number, at: number) =>
964-
JSON.stringify({ at, datamateId, tenant: "acme", apiUrl: "https://api.example.com" })
970+
JSON.stringify({ at, datamateId, tenant: "acme", apiUrl: "https://api.example.com", account: ACME_ACCOUNT })
965971

966972
describe("the sidebar's skills-synced age", () => {
973+
test("a marker left by another account is not this one's sync", async () => {
974+
// Raised in review. The marker began carrying an account, but the age check
975+
// still compared only the workspace, tenant and host — so on a shared
976+
// tenant the second user was shown the first user's sync time for a
977+
// snapshot that is not theirs.
978+
await bind(projectDir)
979+
const managed = path.join(projectDir, ".altimate-code", "skill", "_workspace")
980+
mkdirSync(managed, { recursive: true })
981+
writeFileSync(path.join(managed, ".manifest.json"), manifestFor(42))
982+
writeFileSync(
983+
path.join(managed, ".synced-at"),
984+
JSON.stringify({
985+
at: Date.now() - 5 * 60_000,
986+
datamateId: 42,
987+
tenant: "acme",
988+
apiUrl: "https://api.example.com",
989+
account: OTHER_ACCOUNT,
990+
}),
991+
)
992+
993+
const report = await status(projectDir)
994+
995+
expect(report.skillsSyncedAt).toBeNull()
996+
})
997+
998+
967999
test("comes from the snapshot on disk, not a per-thread map", async () => {
9681000
// The per-message sync stamps its map in the server worker; the sidebar
9691001
// reads on the main thread, which has its own `globalThis` and so its own

‎packages/opencode/test/altimate/workspace/skill-publish.test.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -852,6 +852,13 @@ describe("the published-id ledger survives a key rotation", () => {
852852
// name, and "published from somewhere else". The user is the identity.
853853
await publish()
854854
stubCreds({ altimateApiKey: "k-rotated" })
855+
// The binding cache is scoped to the credential, so a rotation invalidates
856+
// it and the project re-binds — that is the point of the scoping, and it is
857+
// not what this test is about. The ledger is keyed on the user, so the
858+
// published id must survive the rotation even though the cache did not.
859+
// 42, not 1: only the ids in `workspaceOwners` resolve in the stub, so a
860+
// re-bind to an unknown workspace would pass for the wrong reason.
861+
await link(42, "Ops")
855862
requests = []
856863

857864
const report = await publish()

0 commit comments

Comments
 (0)