@@ -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
3737export 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 . */
7575const 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+
7787async 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}
112130let 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. */
137162const 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. */
195228export 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 " +
0 commit comments