Skip to content

Commit 1ce2878

Browse files
saravmajesticclaude
andcommitted
fix(workspace): close three ways around the snapshot account gate
Review of the gate added in the previous commit found three paths that walked around it. All three are real; each has a test and each test was checked by mutation. 1. `scan` follows symlinks, so a link from any other scanned skill directory into `_workspace` produced a match whose own path carried no managed component — read straight past the gate. Attribution is now decided on the REAL path. The cost is one `realpath` per match, against a discovery pass that goes on to read and parse every one of them; the "costs nothing" line that is no longer true is gone. 2. `at > 0` skipped index 0, so a project opened AT the filesystem root was read as "no managed project" and served without consulting its manifest. Both the collection loop and the filter now go through one `snapshotProjectOf`, so they cannot drift apart again. 3. `registryStale` keyed on the manifest's mtime alone. An account switch changes nothing on disk, so a registry that had already loaded the previous account's skills looked current: discovery never re-ran, and the gate inside it was never asked, while the purge was still in flight. The registry identity now carries the account too, so a credential switch invalidates it. An unreadable credential contributes an empty account, which differs from every real one, so it refreshes rather than sticks; the "nothing applied yet" branch still short-circuits before the credential read, so a project with no snapshot pays one `stat` and no file parse. `registryStale` and `markRegistryApplied` are async as a result, and `session/prompt.ts` awaits them. Both awaits are inside a function that path already awaits, so the opted-out branch's synchronous `existsSync` gate — which exists to keep a tick off that path — is untouched. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Claude-Session: https://claude.ai/code/session_01Tneq4MLNoRLsX7htV6fGZC
1 parent 71ebd25 commit 1ce2878

5 files changed

Lines changed: 189 additions & 35 deletions

File tree

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

Lines changed: 36 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ export function forgetAnnouncement(directory: string, problem: { title: string;
266266
interface SyncStore {
267267
inFlight: Map<string, Promise<SyncResult>>
268268
lastSyncedAt: Map<string, number>
269-
registryAppliedAt: Map<string, number>
269+
registryAppliedAt: Map<string, string>
270270
syncedFor: Map<string, string>
271271
/** The sync problem last announced per directory. Here rather than a module
272272
* Map for the same reason as the rest of the store: a second module record
@@ -334,26 +334,52 @@ function snapshotFingerprint(canon: string): number {
334334
}
335335
}
336336

337-
/** Does the skill registry still reflect a different snapshot than the one on
338-
* disk? True until `markRegistryApplied` records the current fingerprint. */
339-
export function registryStale(directory: string): boolean {
337+
/** What a refreshed registry is a refresh OF: the snapshot on disk AND the
338+
* account it is being served to.
339+
*
340+
* The account belongs here because a credential switch changes what may be
341+
* served without changing a single byte on disk. Fingerprinting the manifest
342+
* alone, the registry that had already loaded the previous account's skills
343+
* looked current, so nothing re-ran discovery and its account gate — the
344+
* cached entries were served for the rest of the turn while the purge was
345+
* still in flight. An unreadable credential contributes an empty account,
346+
* which differs from every real one, so it refreshes rather than sticks. */
347+
async function registryIdentity(canon: string): Promise<string> {
348+
let account = ""
349+
try {
350+
const creds = await AltimateApi.getCredentials()
351+
if (creds.altimateApiKey)
352+
account = credentialDigest(creds.altimateUrl, creds.altimateInstanceName, creds.altimateApiKey)
353+
} catch {
354+
/* no credentials resolved; the empty account is the honest answer */
355+
}
356+
return `${snapshotFingerprint(canon)}\u0000${account}`
357+
}
358+
359+
/** Does the skill registry still reflect a different snapshot, or a different
360+
* account, than the one in front of it? True until `markRegistryApplied`
361+
* records the current identity. */
362+
export async function registryStale(directory: string): Promise<boolean> {
340363
const canon = path.resolve(directory)
341-
const current = snapshotFingerprint(canon)
342364
const applied = registryAppliedAt.get(canon)
343365
// Nothing applied yet: stale only if there IS a snapshot. A project that has
344366
// never synced must not pay a config invalidation on the first turn of every
345367
// session. A bound project does pay one — this cannot tell a snapshot that
346368
// predates boot from one a bind just wrote, and refreshing a registry that
347369
// was already current is a cheap rescan, while missing a new one is the bug
348370
// this whole path exists to prevent.
349-
if (applied === undefined) return current !== 0
350-
return applied !== current
371+
//
372+
// Checked before the credential read, so the common case — no snapshot, and
373+
// nothing applied — still costs one `stat` and no file parse.
374+
if (applied === undefined) return snapshotFingerprint(canon) !== 0
375+
return applied !== (await registryIdentity(canon))
351376
}
352377

353-
/** Record that the caller has refreshed the registry for the current snapshot. */
354-
export function markRegistryApplied(directory: string): void {
378+
/** Record that the caller has refreshed the registry for the current snapshot
379+
* and the current account. */
380+
export async function markRegistryApplied(directory: string): Promise<void> {
355381
const canon = path.resolve(directory)
356-
registryAppliedAt.set(canon, snapshotFingerprint(canon))
382+
registryAppliedAt.set(canon, await registryIdentity(canon))
357383
}
358384

359385
/** Await every sync still in flight, so a short-lived process does not exit

‎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: 33 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import { LayerNode } from "@opencode-ai/core/effect/layer-node"
33
import { makeRuntime } from "@/effect/run-service"
44
// altimate_change end
55
import path from "path"
6+
// altimate_change — realpath for workspace snapshot attribution
7+
import fsp from "fs/promises"
68
import { pathToFileURL } from "url"
79
import { Effect, Layer, Context, Schema } from "effect"
810
import { NamedError } from "@opencode-ai/core/util/error"
@@ -263,10 +265,6 @@ const discoverSkills = Effect.fnUntraced(function* (
263265
// BEFORE it polls, and two processes sharing one checkout have no ordering
264266
// between them at all. Asking here is what actually keeps one user's private
265267
// workspace skills out of another user's session.
266-
//
267-
// Costs nothing unless a managed snapshot is among the matches — a project
268-
// that never used the feature has no such path, so the module is not even
269-
// loaded. Same shape as the opt-out gate in session/prompt.ts.
270268
const matches = yield* withoutForeignSnapshots(Array.from(state.matches))
271269
return {
272270
// Rebuilt from the surviving matches rather than filtered out of
@@ -284,16 +282,41 @@ const discoverSkills = Effect.fnUntraced(function* (
284282
* module. */
285283
const MANAGED_SNAPSHOT = `${path.sep}${path.join(".altimate-code", "skill", "_workspace")}${path.sep}`
286284

285+
/** The project a real path belongs to, if it is inside a managed snapshot.
286+
*
287+
* `null` for anything else. A project opened AT the filesystem root puts the
288+
* segment at index 0, which is a project of `/` and not "no project" — the
289+
* difference decides whether the file is gated or served, so it is spelled out
290+
* rather than left to a truthiness test. (review)
291+
*
292+
* @internal Exported for the focused regression test on that root case, which
293+
* cannot be staged as a real project. */
294+
export function snapshotProjectOf(real: string): string | null {
295+
const at = real.indexOf(MANAGED_SNAPSHOT)
296+
if (at < 0) return null
297+
return real.slice(0, at) || path.sep
298+
}
299+
287300
/** Drop matches under a managed workspace snapshot this account did not fetch.
301+
*
302+
* Attribution is decided on the REAL path. `scan` follows symlinks, so a link
303+
* from any other scanned skill directory into `_workspace` yields a match whose
304+
* own path carries no managed component — which read the snapshot straight past
305+
* this gate. (review) The cost is one `realpath` per match, against a discovery
306+
* pass that goes on to read and parse every one of them.
288307
*
289308
* One attribution question per project, not per skill file. Fails CLOSED: if
290309
* the manifest or the credentials cannot be read the snapshot is withheld,
291310
* which costs a poll interval, where serving it cannot be taken back. */
292311
const withoutForeignSnapshots = Effect.fnUntraced(function* (matches: string[]) {
312+
const real = yield* Effect.promise(() =>
313+
Promise.all(matches.map((match) => fsp.realpath(match).catch(() => match))),
314+
)
315+
293316
const projects = new Set<string>()
294-
for (const match of matches) {
295-
const at = match.indexOf(MANAGED_SNAPSHOT)
296-
if (at > 0) projects.add(match.slice(0, at))
317+
for (const candidate of real) {
318+
const project = snapshotProjectOf(candidate)
319+
if (project !== null) projects.add(project)
297320
}
298321
if (projects.size === 0) return matches
299322

@@ -311,10 +334,9 @@ const withoutForeignSnapshots = Effect.fnUntraced(function* (matches: string[])
311334
ours.set(project, ok)
312335
}
313336

314-
return matches.filter((match) => {
315-
const at = match.indexOf(MANAGED_SNAPSHOT)
316-
if (at <= 0) return true
317-
return ours.get(match.slice(0, at)) === true
337+
return matches.filter((_, i) => {
338+
const project = snapshotProjectOf(real[i]!)
339+
return project === null || ours.get(project) === true
318340
})
319341
})
320342
// altimate_change end

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

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1090,12 +1090,12 @@ describe("workspace skill sync", () => {
10901090
test("registryStale reports a snapshot the caller has not applied yet", async () => {
10911091
// A bind syncs with no instance context to refresh from; the next turn has
10921092
// to notice on its own, without re-fetching.
1093-
expect(registryStale(project)).toBe(false)
1093+
expect(await registryStale(project)).toBe(false)
10941094
serve({ "pub-1": { "SKILL.md": "one" } })
10951095
await syncSkills(project)
1096-
expect(registryStale(project)).toBe(true)
1097-
markRegistryApplied(project)
1098-
expect(registryStale(project)).toBe(false)
1096+
expect(await registryStale(project)).toBe(true)
1097+
await markRegistryApplied(project)
1098+
expect(await registryStale(project)).toBe(false)
10991099
})
11001100

11011101
test("registryStale follows the snapshot on disk, not an in-process stamp", async () => {
@@ -1108,26 +1108,57 @@ describe("workspace skill sync", () => {
11081108
// still be reported.
11091109
serve({ "pub-1": { "SKILL.md": "one" } })
11101110
await syncSkills(project)
1111-
markRegistryApplied(project)
1112-
expect(registryStale(project)).toBe(false)
1111+
await markRegistryApplied(project)
1112+
expect(await registryStale(project)).toBe(false)
11131113

11141114
const manifest = path.join(project, MANAGED, ".manifest.json")
11151115
const later = new Date(Date.now() + 5000)
11161116
utimesSync(manifest, later, later)
11171117

1118-
expect(registryStale(project)).toBe(true)
1118+
expect(await registryStale(project)).toBe(true)
11191119
})
11201120

11211121
test("registryStale reports a purge, so opting out refreshes too", async () => {
11221122
serve({ "pub-1": { "SKILL.md": "one" } })
11231123
await syncSkills(project)
1124-
markRegistryApplied(project)
1125-
expect(registryStale(project)).toBe(false)
1124+
await markRegistryApplied(project)
1125+
expect(await registryStale(project)).toBe(false)
11261126

11271127
// A deactivate removes the whole managed tree, manifest included. That is a
11281128
// registry change in the other direction and must refresh just the same.
11291129
rmSync(path.join(project, MANAGED), { recursive: true, force: true })
1130-
expect(registryStale(project)).toBe(true)
1130+
expect(await registryStale(project)).toBe(true)
1131+
})
1132+
1133+
test("registryStale reports a credential switch, with the snapshot untouched", async () => {
1134+
// The disclosure this guards: the registry had already loaded the previous
1135+
// account's skills, and an A-to-B switch changes nothing on disk. Keyed on
1136+
// the manifest alone the registry looked current, so discovery — and the
1137+
// account gate inside it — never re-ran, and the cached entries were served
1138+
// while the purge was still in flight. (review)
1139+
serve({ "pub-1": { "SKILL.md": "one" } })
1140+
await syncSkills(project)
1141+
await markRegistryApplied(project)
1142+
expect(await registryStale(project)).toBe(false)
1143+
1144+
const credsFile = path.join(SANDBOX, "home", ".altimate", "altimate.json")
1145+
const saved = readFileSync(credsFile, "utf8")
1146+
try {
1147+
writeFileSync(
1148+
credsFile,
1149+
JSON.stringify({
1150+
altimateUrl: API_URL,
1151+
altimateInstanceName: TENANT,
1152+
altimateApiKey: "someone-elses-key",
1153+
}),
1154+
)
1155+
expect(await registryStale(project)).toBe(true)
1156+
} finally {
1157+
writeFileSync(credsFile, saved)
1158+
}
1159+
// And switching back is not stale: this refreshes on a real change, it does
1160+
// not simply refuse to settle.
1161+
expect(await registryStale(project)).toBe(false)
11311162
})
11321163

11331164
test("flushPendingSyncs waits for a sync a short-lived process would abandon", async () => {

‎packages/opencode/test/skill/skill.test.ts‎

Lines changed: 77 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { describe, expect } from "bun:test"
1+
import { describe, expect, test } from "bun:test"
22
import { Effect, Layer } from "effect"
3-
import { Skill } from "../../src/skill"
3+
import { Skill, snapshotProjectOf } from "../../src/skill"
44
import { Discovery } from "../../src/skill/discovery"
55
import { RuntimeFlags } from "../../src/effect/runtime-flags"
66
import { EventV2Bridge } from "../../src/event-v2-bridge"
@@ -108,6 +108,27 @@ const withHome = <A, E, R>(home: string, self: Effect.Effect<A, E, R>) =>
108108
}),
109109
)
110110

111+
describe("workspace snapshot attribution", () => {
112+
// `at > 0` skipped index 0, so a project opened AT the filesystem root — its
113+
// snapshot living at `/.altimate-code/skill/_workspace/` — was read as "no
114+
// managed project" and served without consulting its manifest. (review)
115+
test("a project at the filesystem root is a project, not an absence of one", () => {
116+
expect(snapshotProjectOf(path.join(path.sep, ".altimate-code", "skill", "_workspace", "p", "SKILL.md"))).toBe(
117+
path.sep,
118+
)
119+
})
120+
121+
test("an ordinary skill belongs to no snapshot", () => {
122+
expect(snapshotProjectOf(path.join(path.sep, "proj", ".opencode", "skill", "s", "SKILL.md"))).toBeNull()
123+
})
124+
125+
test("a nested project keeps its own root", () => {
126+
expect(
127+
snapshotProjectOf(path.join(path.sep, "a", "b", ".altimate-code", "skill", "_workspace", "p", "SKILL.md")),
128+
).toBe(path.join(path.sep, "a", "b"))
129+
})
130+
})
131+
111132
describe("skill", () => {
112133
it.live("discovers skills from .opencode/skill/ directory", () =>
113134
provideTmpdirInstance(
@@ -734,6 +755,60 @@ description: A skill in the .opencode/skills directory.
734755
),
735756
)
736757

758+
// `scan` follows symlinks, so a link from any other scanned skill directory
759+
// into `_workspace` produces a match whose own path carries no managed
760+
// component. Attributing on the matched string rather than the real one read
761+
// the snapshot straight past the gate. (review)
762+
it.live("a symlink into another account's snapshot is not a way in", () =>
763+
provideTmpdirInstance(
764+
(dir) =>
765+
withHome(
766+
dir,
767+
Effect.gen(function* () {
768+
yield* Effect.promise(() => writeSnapshot(dir, credentialDigest(API_URL, TENANT, "someone-else")))
769+
yield* Effect.promise(async () => {
770+
await fs.mkdir(path.join(dir, ".opencode", "skill"), { recursive: true })
771+
await fs.symlink(
772+
path.join(dir, MANAGED, "pub-abc123"),
773+
path.join(dir, ".opencode", "skill", "alias"),
774+
"dir",
775+
)
776+
})
777+
778+
const skill = yield* Skill.Service
779+
expect((yield* skill.all()).find((s) => s.name === "workspace-synced")).toBeUndefined()
780+
}),
781+
),
782+
{ git: true },
783+
),
784+
)
785+
786+
// The same link, but to a snapshot that IS ours: the gate withholds what is
787+
// foreign, not everything it cannot recognise at a glance.
788+
it.live("a symlink into our own snapshot still resolves to a usable skill", () =>
789+
provideTmpdirInstance(
790+
(dir) =>
791+
withHome(
792+
dir,
793+
Effect.gen(function* () {
794+
yield* Effect.promise(() => writeSnapshot(dir, FIXTURE_ACCOUNT))
795+
yield* Effect.promise(async () => {
796+
await fs.mkdir(path.join(dir, ".opencode", "skill"), { recursive: true })
797+
await fs.symlink(
798+
path.join(dir, MANAGED, "pub-abc123"),
799+
path.join(dir, ".opencode", "skill", "alias"),
800+
"dir",
801+
)
802+
})
803+
804+
const skill = yield* Skill.Service
805+
expect((yield* skill.all()).find((s) => s.name === "workspace-synced")).toBeDefined()
806+
}),
807+
),
808+
{ git: true },
809+
),
810+
)
811+
737812
// A snapshot from before the manifest carried an account cannot be
738813
// attributed to anyone, so it is withheld rather than served to whoever
739814
// happens to be logged in. The sync drops and re-fetches it.

0 commit comments

Comments
 (0)