Skip to content

Commit 9af3726

Browse files
sahrizviclaude
andcommitted
fix(workspace): pin the contents block to one snapshot and one account (review)
- Skills are read only from the snapshot that was validated: the managed root's inode is compared before the manifest check and after the read, and a swap in between answers "could not be read just now". - The known-empty record is consulted only when there is no snapshot, so a foreign snapshot is "not synced", never "none". - The parsed-snapshot cache stamp includes every `SKILL.md`'s mtime and size, so an in-place edit is picked up. - One credential read serves the cache key and every request of a fetch: `getDatamate`, `listDatamates` and `getKnowledgeDocument` take optional pinned credentials. - Documents past the 20-id lookup cap are no longer counted as existing; the block shows the verified names and "N more selected, not checked". - skill-sync clears the known-empty record when a purge finds no tree (the empty-workspace case returned early before), when a non-empty list is seen even if installing fails, and when the binding or account changes. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_018fJ3X7pcGT4R9yzjsJnqsV
1 parent 62eff06 commit 9af3726

5 files changed

Lines changed: 207 additions & 55 deletions

File tree

‎packages/opencode/src/altimate/api/client.ts‎

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -265,23 +265,24 @@ export namespace AltimateApi {
265265
// altimate_change end
266266
}
267267

268-
export async function listDatamates() {
269-
const creds = await getCredentials()
268+
export async function listDatamates(creds?: AltimateCredentials) {
269+
creds ??= await getCredentials()
270270
const data = await request(creds, "GET", "/datamates/")
271271
const list = Array.isArray(data) ? data : (data.datamates ?? data.data ?? [])
272272
return list.map((d: unknown) => DatamateSummary.parse(d)) as z.infer<typeof DatamateSummary>[]
273273
}
274274

275-
export async function getDatamate(id: string) {
276-
const creds = await getCredentials()
275+
/** `creds` pins the account for callers that cache the answer per account. */
276+
export async function getDatamate(id: string, creds?: AltimateCredentials) {
277+
creds ??= await getCredentials()
277278
try {
278279
const data = await request(creds, "GET", `/datamates/${id}/summary`)
279280
const raw = data.datamate ?? data
280281
return DatamateSummary.parse(raw)
281282
} catch (e) {
282283
// Fallback to list if single-item endpoint is unavailable (404)
283284
if (e instanceof Error && e.message.includes("status 404")) {
284-
const all = await listDatamates()
285+
const all = await listDatamates(creds)
285286
const found = all.find((d) => d.id === id)
286287
if (!found) {
287288
throw new Error(`Datamate with ID ${id} not found`)
@@ -297,8 +298,11 @@ export namespace AltimateApi {
297298
* (404). Fetched by id rather than listing the hub, whose list returns every document's full
298299
* text. A response that is not a document is an error, never "no document".
299300
*/
300-
export async function getKnowledgeDocument(id: number): Promise<{ id: number; name: string; deleted: boolean } | null> {
301-
const creds = await getCredentials()
301+
export async function getKnowledgeDocument(
302+
id: number,
303+
creds?: AltimateCredentials,
304+
): Promise<{ id: number; name: string; deleted: boolean } | null> {
305+
creds ??= await getCredentials()
302306
let data: unknown
303307
try {
304308
data = await request(creds, "GET", `/knowledge_bases/${id}`)

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

Lines changed: 67 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -29,10 +29,10 @@ export type WorkspaceKnowledge =
2929
| { kind: "off" }
3030
| { kind: "all" }
3131
/**
32-
* `count` is the number of selected documents that exist, or are not yet checked beyond the
33-
* listing cap. `names` holds the ones resolved, sorted; null when they could not be read.
32+
* `selected`: ids the workspace selected. `names`: the checked ones that exist, sorted; null
33+
* when they could not be read. `unchecked`: ids beyond the lookup cap, never verified to exist.
3434
*/
35-
| { kind: "selected"; count: number; names: string[] | null }
35+
| { kind: "selected"; selected: number; names: string[] | null; unchecked: number }
3636

3737
export interface WorkspaceContents {
3838
/**
@@ -70,25 +70,42 @@ function clean(text: unknown, max: number): string {
7070
// Skills (snapshot on disk)
7171
// ---------------------------------------------------------------------------
7272

73-
/** Parsed snapshot per root, keyed on the root's identity: a sync publishes by swapping the
74-
* whole directory in, so a changed snapshot always has a new inode or mtime. */
73+
/** Parsed snapshot per root. The stamp covers the root (a sync swaps the whole directory in) and
74+
* each SKILL.md (the TUI can edit one in place), so only an unchanged tree is served from here. */
7575
const parsedSnapshots = new Map<string, { stamp: string; skills: WorkspaceSkill[] }>()
7676

77+
/** The root's inode, or null when there is no snapshot. A publish renames a new tree in, so a
78+
* different inode means a different snapshot generation. */
79+
async function rootGeneration(root: string): Promise<number | null> {
80+
try {
81+
return (await fs.stat(root)).ino
82+
} catch {
83+
return null
84+
}
85+
}
86+
7787
async function readSnapshot(root: string): Promise<WorkspaceSkill[] | null> {
7888
let stamp: string
7989
let entries: string[]
8090
try {
8191
const st = await fs.stat(root)
82-
stamp = `${st.ino}:${st.mtimeMs}`
92+
entries = (await fs.readdir(root)).filter((e) => !e.startsWith(".")).sort()
93+
const files = await Promise.all(
94+
entries.map((e) =>
95+
fs.stat(path.join(root, e, "SKILL.md")).then(
96+
(f) => `${e}:${f.mtimeMs}:${f.size}`,
97+
() => `${e}:-`,
98+
),
99+
),
100+
)
101+
stamp = `${st.ino}:${st.mtimeMs}|${files.join("|")}`
83102
const hit = parsedSnapshots.get(root)
84103
if (hit?.stamp === stamp) return hit.skills
85-
entries = await fs.readdir(root)
86104
} catch {
87105
return null
88106
}
89107
const skills: WorkspaceSkill[] = []
90108
for (const entry of entries) {
91-
if (entry.startsWith(".")) continue
92109
try {
93110
const md = await ConfigMarkdown.parse(path.join(root, entry, "SKILL.md"))
94111
const name = clean((md.data as Record<string, unknown>)?.name, 80)
@@ -108,6 +125,7 @@ const defaultSnapshot = {
108125
workspaceId: (dir: string) => SkillSync.snapshotWorkspaceId(dir),
109126
knownEmpty: (dir: string, id: number) => SkillSync.snapshotKnownEmpty(dir, id),
110127
root: (dir: string) => SkillSync.snapshotRoot(dir),
128+
generation: rootGeneration,
111129
}
112130
let snapshot = defaultSnapshot
113131

@@ -116,12 +134,19 @@ export function setSnapshotForTests(overrides: Partial<typeof defaultSnapshot>):
116134
}
117135

118136
/** The workspace's own skills, sorted so every ask sees the same list. [] for a workspace the
119-
* last sync found empty (an empty workspace leaves no snapshot); null when not synced. */
120-
export async function workspaceSkills(directory: string, datamateId: number): Promise<WorkspaceSkill[] | null> {
121-
if ((await snapshot.workspaceId(directory)) !== datamateId) {
122-
return (await snapshot.knownEmpty(directory, datamateId)) ? [] : null
123-
}
124-
return readSnapshot(snapshot.root(directory))
137+
* last sync found empty (an empty workspace leaves no snapshot); null when not synced;
138+
* "unknown" when a sync swapped the snapshot while it was being read. */
139+
export async function workspaceSkills(directory: string, datamateId: number): Promise<WorkspaceSkill[] | null | "unknown"> {
140+
const root = snapshot.root(directory)
141+
// The manifest lives inside the root, so the same inode before validation and after the read
142+
// means the skills read belong to the snapshot that was validated.
143+
const before = await snapshot.generation(root)
144+
const id = await snapshot.workspaceId(directory)
145+
if (id === null) return (await snapshot.knownEmpty(directory, datamateId)) ? [] : null
146+
if (id !== datamateId) return null
147+
const skills = await readSnapshot(root)
148+
if (before === null || (await snapshot.generation(root)) !== before) return "unknown"
149+
return skills
125150
}
126151

127152
// ---------------------------------------------------------------------------
@@ -136,46 +161,54 @@ type Fetched = { value: Summary; complete: boolean }
136161
* same id must never be answered from this cache. */
137162
const summaries = new Map<string, { at: number; value?: Summary; pending?: Promise<Fetched> }>()
138163

139-
/** The account in use now, as a short digest; null when there is no usable credential. */
140-
async function accountKey(): Promise<string | null> {
164+
type Credentials = Awaited<ReturnType<typeof AltimateApi.getCredentials>>
165+
166+
/** The account in use now, read once: the cache key and every request of a fetch use this same
167+
* credential, so a switch mid-fetch cannot file one account's answer under another's key. */
168+
async function currentAccount(): Promise<{ key: string; creds: Credentials } | null> {
141169
try {
142170
const c = await AltimateApi.getCredentials()
143171
if (!c.altimateApiKey) return null
144-
return createHash("sha256").update(`${c.altimateUrl}\u0000${c.altimateInstanceName}\u0000${c.altimateApiKey}`).digest("hex").slice(0, 16)
172+
const key = createHash("sha256").update(`${c.altimateUrl}\u0000${c.altimateInstanceName}\u0000${c.altimateApiKey}`).digest("hex").slice(0, 16)
173+
return { key, creds: c }
145174
} catch {
146175
return null
147176
}
148177
}
149178

150179
/** Selected documents that exist, resolved by id (at most MAX_LISTED_DOCUMENTS fetched). */
151-
async function selectedDocuments(ids: number[]): Promise<WorkspaceKnowledge> {
180+
async function selectedDocuments(ids: number[], creds: Credentials): Promise<WorkspaceKnowledge> {
152181
const head = ids.slice(0, MAX_LISTED_DOCUMENTS)
153182
const unchecked = ids.length - head.length
154183
try {
155-
const docs = await Promise.all(head.map((id) => AltimateApi.getKnowledgeDocument(id)))
184+
const docs = await Promise.all(head.map((id) => AltimateApi.getKnowledgeDocument(id, creds)))
156185
const names = docs
157186
.filter((d): d is NonNullable<typeof d> => d !== null && !d.deleted)
158187
.map((d) => clean(d.name, 80))
159188
.sort((a, b) => a.localeCompare(b))
160-
return { kind: "selected", count: names.length + unchecked, names }
189+
return { kind: "selected", selected: ids.length, names, unchecked }
161190
} catch {
162-
return { kind: "selected", count: ids.length, names: null }
191+
return { kind: "selected", selected: ids.length, names: null, unchecked }
163192
}
164193
}
165194

166-
async function knowledgeOf(engineEnabled: boolean | undefined, ids: number[] | null | undefined): Promise<WorkspaceKnowledge | null> {
195+
async function knowledgeOf(
196+
engineEnabled: boolean | undefined,
197+
ids: number[] | null | undefined,
198+
creds: Credentials,
199+
): Promise<WorkspaceKnowledge | null> {
167200
if (engineEnabled === undefined) return null
168201
if (!engineEnabled) return { kind: "off" }
169202
// Only an explicit empty selection means "every document"; a missing one is unknown.
170203
if (!Array.isArray(ids)) return null
171204
if (ids.length === 0) return { kind: "all" }
172-
return selectedDocuments(ids)
205+
return selectedDocuments(ids, creds)
173206
}
174207

175-
async function fetchSummary(datamateId: number): Promise<Fetched> {
208+
async function fetchSummary(datamateId: number, creds: Credentials): Promise<Fetched> {
176209
try {
177-
const s = await AltimateApi.getDatamate(String(datamateId))
178-
const knowledge = await knowledgeOf(s.knowledge_engine_enabled, s.knowledge_bases)
210+
const s = await AltimateApi.getDatamate(String(datamateId), creds)
211+
const knowledge = await knowledgeOf(s.knowledge_engine_enabled, s.knowledge_bases, creds)
179212
return {
180213
value: {
181214
integrations: Array.isArray(s.integrations) ? s.integrations.map((i) => i.id).sort() : null,
@@ -193,14 +226,14 @@ async function fetchSummary(datamateId: number): Promise<Fetched> {
193226
/** Integrations, memory setting and knowledge, cached per account and workspace; a slow service
194227
* yields "not known" this step. */
195228
export async function workspaceSummary(datamateId: number, now = Date.now()): Promise<Summary> {
196-
const account = await accountKey()
229+
const account = await currentAccount()
197230
if (account === null) return UNKNOWN
198-
const key = `${account}:${datamateId}`
231+
const key = `${account.key}:${datamateId}`
199232
const hit = summaries.get(key)
200233
if (hit?.value && now - hit.at < SUMMARY_TTL_MS) return hit.value
201234
let pending = hit?.pending
202235
if (!pending) {
203-
pending = fetchSummary(datamateId).then((fetched) => {
236+
pending = fetchSummary(datamateId, account.creds).then((fetched) => {
204237
// An incomplete fetch is kept for this step only, so the next step retries.
205238
summaries.set(key, { at: fetched.complete ? Date.now() : 0, value: fetched.value })
206239
return fetched
@@ -264,13 +297,12 @@ function renderWith(contents: WorkspaceContents, detail: SkillDetail): string {
264297
else if (k?.kind === "all")
265298
lines.push("Knowledge: every document in the organization's knowledge hub (the workspace is not limited to specific documents).")
266299
else if (k?.kind === "selected" && k.names === null)
267-
lines.push(`Knowledge: ${k.count} selected document${k.count === 1 ? "" : "s"} (their names could not be loaded).`)
300+
lines.push(`Knowledge: ${k.selected} selected document${k.selected === 1 ? "" : "s"} (their names could not be loaded).`)
268301
else if (k?.kind === "selected" && k.names) {
269-
if (k.count === 0) lines.push("Knowledge: none — the documents this workspace selected no longer exist.")
270-
else {
271-
const more = k.count - k.names.length
272-
lines.push(`Knowledge documents (${k.count}): ${k.names.join(", ")}${more > 0 ? `, …and ${more} more` : ""}.`)
273-
}
302+
const more = k.unchecked > 0 ? `${k.unchecked} more selected, not checked` : ""
303+
if (k.names.length > 0) lines.push(`Knowledge documents (${k.names.length}): ${k.names.join(", ")}${more ? `; ${more}` : ""}.`)
304+
else if (more) lines.push(`Knowledge: the first selected documents no longer exist; ${more}.`)
305+
else lines.push("Knowledge: none — the documents this workspace selected no longer exist.")
274306
}
275307
lines.push(
276308
"When the user asks what skills, knowledge or integrations THIS workspace has, answer from this " +

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

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -958,9 +958,15 @@ async function hasBindingEvidence(directory: string): Promise<boolean> {
958958
* Only removes a tree this client owns, for the same reason the sync does. */
959959
async function deactivate(directory: string, why: string): Promise<boolean> {
960960
const root = managedRoot(directory)
961+
// An empty workspace leaves no tree, so its "known empty" record and sync stamps are cleared
962+
// here, before the early return: relinking must sync again rather than repeat a stale "none".
963+
const canon = path.resolve(directory)
964+
emptyFor.delete(canon)
961965
try {
962966
await fs.stat(root)
963967
} catch {
968+
lastSyncedAt.delete(canon)
969+
syncedFor.delete(canon)
964970
return false // nothing published here
965971
}
966972
if (!(await ownsManagedDir(directory))) return false
@@ -970,10 +976,8 @@ async function deactivate(directory: string, why: string): Promise<boolean> {
970976
// describe anything. Left behind, a purge that is not followed by a
971977
// successful sync — an account switch to a project this user has not bound —
972978
// made the next run skip for a whole poll interval with nothing on disk.
973-
const canon = path.resolve(directory)
974979
lastSyncedAt.delete(canon)
975980
syncedFor.delete(canon)
976-
emptyFor.delete(canon)
977981
log.info("removed the workspace skill snapshot", { why, path: root })
978982
return true
979983
}
@@ -1178,6 +1182,9 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
11781182
return
11791183
}
11801184
const account = credentialDigest(creds.altimateUrl, creds.altimateInstanceName, creds.altimateApiKey)
1185+
// A "known empty" record for another link or account no longer describes this project.
1186+
const currentEmptyKey = emptyKey(accountKeyOf(creds.altimateInstanceName, creds.altimateUrl, account), binding.datamateId)
1187+
if (emptyFor.has(canon) && emptyFor.get(canon) !== currentEmptyKey) emptyFor.delete(canon)
11811188

11821189
const manifest = await readManifest(canon)
11831190

@@ -1209,6 +1216,8 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12091216
}
12101217
sawRemote = true
12111218
syncedFor.set(canon, accountKeyOf(creds.altimateInstanceName, creds.altimateUrl, account))
1219+
// The workspace has skills now, even if installing them fails below.
1220+
if (remote.length > 0) emptyFor.delete(canon)
12121221

12131222
if (!foreign && (await upToDate(canon, manifest, remote))) {
12141223
// Remembered for the stamp below, which runs after this block settles.
@@ -1221,7 +1230,7 @@ export async function syncSkills(directory: string): Promise<SyncResult> {
12211230

12221231
if (remote.length === 0) {
12231232
await removeManaged(canon)
1224-
emptyFor.set(canon, emptyKey(accountKeyOf(creds.altimateInstanceName, creds.altimateUrl, account), binding.datamateId))
1233+
emptyFor.set(canon, currentEmptyKey)
12251234
changed = true
12261235
log.info("workspace has no custom skills; removed the local snapshot")
12271236
return

0 commit comments

Comments
 (0)