dsh-skill-pool 0.0.0-stage → 0.3.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.js ADDED
@@ -0,0 +1,1233 @@
1
+ /**
2
+ * Durable resource-pool state (v4): one global pool, which *is* the user's
3
+ * resource library.
4
+ *
5
+ * The document keeps five maps:
6
+ * - `skills` / `mcp`: resource name -> membership (`enabled`, `modes`,
7
+ * `workspaces`) plus provenance (`sourceId`, `digest`, `installedAt`). A
8
+ * resource is in the pool exactly when it has an entry: an import writes the
9
+ * entry in the same transaction, there is no separate "add to pool" step.
10
+ * An `mcp` member also keeps its `definition` (URL/command/headers), which is
11
+ * what a Host restart re-mounts the `mcp-client` row from — see remount.js.
12
+ * A skill additionally carries `modesFrom` / `workspacesFrom`: `group` means
13
+ * "use the group of its source", `self` means "use my own list".
14
+ * - `groups`: one scope per *repository* (`repo:<project>`) or, for imports
15
+ * without a repository, per import (`import:<sourceId>`). Members inherit it
16
+ * unless they opt out, so one edit scopes a whole repository.
17
+ * - `sources`: where installed skills came from (git repository, ZIP archive or
18
+ * an uploaded file set), used to check for updates, update, or remove what a
19
+ * source installed.
20
+ * - `settings`: the switches the panel exposes (§2.1).
21
+ *
22
+ * A v3 document is migrated (see `migrateV3`), not dropped: groups are derived
23
+ * from what the members already do, so gating is identical before and after.
24
+ * Any other version is reset to an empty document: v1/v2 used a different
25
+ * membership model (a separate library and pool), and guessing a mapping would
26
+ * silently change what is gated.
27
+ *
28
+ * Writes are atomic and serialized; the module has no Cordis imports so
29
+ * `node --test` can load it directly.
30
+ *
31
+ * @module dsh-skill-pool/store
32
+ */
33
+
34
+ import { AsyncLocalStorage } from 'node:async_hooks'
35
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
36
+ import { dirname, join, resolve as resolvePath } from 'node:path'
37
+ import { homedir } from 'node:os'
38
+ import { groupKeyOfSource } from './rules.js'
39
+
40
+ /** Current document version. */
41
+ export const STATE_VERSION = 4
42
+
43
+ /**
44
+ * Absolute state-file paths this Node process has observed.
45
+ *
46
+ * A new `StateStore` (for example after an in-process plugin reload) must not
47
+ * forget that a file existed and mistake its disappearance for a first run.
48
+ * This is an in-memory set: it creates no file, survives module reloads in the
49
+ * same process through `globalThis`, and intentionally cannot survive a Host
50
+ * restart (a deleted file and a genuine first run are then indistinguishable).
51
+ */
52
+ const OBSERVED_STATE_FILES_KEY = Symbol.for('dsh-skill-pool.observed-state-files')
53
+ const observedStateFiles =
54
+ globalThis[OBSERVED_STATE_FILES_KEY] instanceof Set
55
+ ? globalThis[OBSERVED_STATE_FILES_KEY]
56
+ : (globalThis[OBSERVED_STATE_FILES_KEY] = new Set())
57
+
58
+ /** Group keys that would mutate the normalized map's prototype. */
59
+ const FORBIDDEN_GROUP_KEYS = new Set(['__proto__', 'prototype', 'constructor'])
60
+
61
+ /** The one older version this module upgrades instead of discarding. */
62
+ export const LEGACY_VERSION = 3
63
+
64
+ /** Group records keyed by `repo:<project>` or `import:<sourceId>`. */
65
+ export const GROUP_KINDS = ['repo', 'import']
66
+
67
+ /** Default file name under the DSH home. */
68
+ export const STATE_FILE_NAME = 'resource-pool/state.json'
69
+
70
+ /** Namespaces that hold pool members. */
71
+ export const KINDS = ['skill', 'mcp']
72
+
73
+ /** Provenance kinds a source record may have. */
74
+ export const SOURCE_KINDS = ['git', 'zip', 'files']
75
+
76
+ /** Git providers supported by the library (self-hosted GitLab is out of scope). */
77
+ export const GIT_PROVIDERS = ['github', 'gitlab']
78
+
79
+ /** Outcomes of one "check for updates" run, stored on the source (§2.1). */
80
+ export const CHECK_STATUSES = ['up-to-date', 'update-available', 'error']
81
+
82
+ /** Switches the panel may patch. */
83
+ export const SETTING_KEYS = ['enabled', 'mcpGate', 'injectSummary', 'gateDefaultSkills']
84
+
85
+ /** Conservative identifier grammar for resource names and mode ids. */
86
+ const NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,159}$/
87
+
88
+ /** Resolve the DSH home directory (env override, else `~/.dsh`). */
89
+ export function dshHome() {
90
+ const fromEnv = process.env.DSH_HOME
91
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
92
+ return join(homedir(), '.dsh')
93
+ }
94
+
95
+ /** Absolute path of the state document. */
96
+ export function statePath() {
97
+ return join(dshHome(), STATE_FILE_NAME)
98
+ }
99
+
100
+ /** Generate a short, collision-resistant id. */
101
+ export function newId(prefix) {
102
+ return `${prefix}_${Date.now().toString(36)}${Math.random().toString(36).slice(2, 8)}`
103
+ }
104
+
105
+ /** Whether a value is a plain object (not an array, not null). */
106
+ function isObject(value) {
107
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
108
+ }
109
+
110
+ /** Trim a candidate name, returning '' when unusable. */
111
+ function cleanName(value) {
112
+ if (typeof value !== 'string') return ''
113
+ const name = value.trim()
114
+ return NAME_RE.test(name) ? name : ''
115
+ }
116
+
117
+ /**
118
+ * Normalize a resource/mode name.
119
+ * @param {unknown} value - candidate name.
120
+ * @returns {string} the name when it satisfies the identifier grammar, else ''.
121
+ */
122
+ export function normalizeItemName(value) {
123
+ return cleanName(value)
124
+ }
125
+
126
+ /** Trim an optional string, returning '' when absent. */
127
+ function optionalString(value, limit = 4096) {
128
+ if (typeof value !== 'string') return ''
129
+ return value.trim().slice(0, limit)
130
+ }
131
+
132
+ /** Timestamp helper: keep a stored value, else use now. */
133
+ function timestamp(value) {
134
+ const text = optionalString(value, 64)
135
+ return text.length > 0 ? text : new Date().toISOString()
136
+ }
137
+
138
+ /** Deduplicate strings, preserving order. */
139
+ function unique(values) {
140
+ const seen = new Set()
141
+ const out = []
142
+ for (const value of values) {
143
+ if (seen.has(value)) continue
144
+ seen.add(value)
145
+ out.push(value)
146
+ }
147
+ return out
148
+ }
149
+
150
+ /**
151
+ * Normalize one filesystem path for workspace matching (lexical, no realpath).
152
+ * @param {unknown} value - candidate path.
153
+ * @returns {string} absolute path with forward slashes and no trailing slash.
154
+ */
155
+ export function normalizePath(value) {
156
+ if (typeof value !== 'string') return ''
157
+ let path = value.trim().replace(/\\/g, '/')
158
+ if (path.length === 0) return ''
159
+ const windowsDrive = /^[A-Za-z]:\//.test(path)
160
+ if (!path.startsWith('/') && !windowsDrive) return ''
161
+ path = path.replace(/\/{2,}/g, '/')
162
+ while (path.length > 1 && path.endsWith('/')) path = path.slice(0, -1)
163
+ return path
164
+ }
165
+
166
+ /** Normalize a list of resource/mode names. */
167
+ function cleanNameList(value) {
168
+ if (!Array.isArray(value)) return []
169
+ const names = []
170
+ for (const item of value) {
171
+ const name = cleanName(item)
172
+ if (name.length > 0) names.push(name)
173
+ }
174
+ return unique(names)
175
+ }
176
+
177
+ /** Normalize a list of workspace paths. */
178
+ function cleanPathList(value) {
179
+ if (!Array.isArray(value)) return []
180
+ const paths = []
181
+ for (const item of value) {
182
+ const path = normalizePath(item)
183
+ if (path.length > 0) paths.push(path)
184
+ }
185
+ return unique(paths)
186
+ }
187
+
188
+ /** Normalize a source's repository subdirectory. */
189
+ function cleanSubdir(value) {
190
+ const text = optionalString(value, 512).replace(/\\/g, '/')
191
+ return text.replace(/^\/+|\/+$/g, '').replace(/\/{2,}/g, '/')
192
+ }
193
+
194
+ /** Default settings of a fresh document (§2.1). */
195
+ export function defaultSettings() {
196
+ return { enabled: true, mcpGate: true, injectSummary: true, gateDefaultSkills: false }
197
+ }
198
+
199
+ /** A fresh, empty document. */
200
+ export function defaultState() {
201
+ return { version: STATE_VERSION, settings: defaultSettings(), skills: {}, mcp: {}, sources: {}, groups: {} }
202
+ }
203
+
204
+ /**
205
+ * Normalize one activation scope.
206
+ * @param {unknown} raw - candidate scope.
207
+ * @returns {{enabled: boolean, modes: string[], workspaces: string[]}|null} scope, or null when unusable.
208
+ */
209
+ export function normalizeScope(raw) {
210
+ if (!isObject(raw)) return null
211
+ return {
212
+ enabled: raw.enabled !== false,
213
+ modes: cleanNameList(raw.modes),
214
+ workspaces: cleanPathList(raw.workspaces),
215
+ }
216
+ }
217
+
218
+ /**
219
+ * Normalize the provenance fields of one member (`sourceId`/`digest`/`installedAt`).
220
+ * Empty optional values are omitted; `installedAt` is always present.
221
+ *
222
+ * @param {'skill'|'mcp'} kind - member namespace.
223
+ * @param {unknown} extra - values supplied by an install/update.
224
+ * @param {unknown} base - the member's previous entry, if any.
225
+ * @returns {object} provenance fields to merge over the scope.
226
+ */
227
+ function itemExtras(kind, extra, base) {
228
+ const provided = isObject(extra) ? extra : {}
229
+ const previous = isObject(base) ? base : {}
230
+ const pick = (key) => {
231
+ if (typeof provided[key] === 'string') return provided[key].trim()
232
+ if (typeof previous[key] === 'string') return previous[key]
233
+ return ''
234
+ }
235
+ const out = {}
236
+ if (kind === 'skill') {
237
+ const sourceId = pick('sourceId')
238
+ if (sourceId.length > 0) out.sourceId = sourceId
239
+ const digest = pick('digest')
240
+ if (digest.length > 0) out.digest = digest
241
+ // Inheritance is a member choice, not provenance: carry whichever side of
242
+ // the write supplies it, so a scope edit never resets it to a default.
243
+ for (const key of ['modesFrom', 'workspacesFrom']) {
244
+ const value = provided[key]
245
+ if (value === 'self' || value === 'group') out[key] = value
246
+ else if (previous[key] === 'self' || previous[key] === 'group') out[key] = previous[key]
247
+ }
248
+ }
249
+ if (kind === 'mcp') {
250
+ // A scope-only edit (enable/disable, mode or workspace change) must not drop
251
+ // the connection definition that makes the member survive a Host restart.
252
+ const defined = cleanMcpDefinition(provided.definition) ?? cleanMcpDefinition(previous.definition)
253
+ if (defined !== undefined) out.definition = defined
254
+ }
255
+ out.installedAt = pick('installedAt') || new Date().toISOString()
256
+ return out
257
+ }
258
+
259
+ /** Transports a stored MCP definition may name. */
260
+ const MCP_TRANSPORTS = ['stdio', 'streamable-http']
261
+
262
+ /**
263
+ * Normalize the stored connection definition of one MCP member.
264
+ *
265
+ * The definition is what lets a Host restart rebuild the `mcp-client` Loader
266
+ * row: without it the member survived a restart while its connection did not,
267
+ * leaving a pool entry that lists zero tools. Only the fields the mcp-client
268
+ * plugin understands are kept, every value is length-capped, and an empty
269
+ * result is dropped so the document never grows junk.
270
+ *
271
+ * @param {unknown} raw - candidate definition (`{url|command, ...}`).
272
+ * @returns {object|undefined} cleaned definition, or undefined when unusable.
273
+ */
274
+ export function cleanMcpDefinition(raw) {
275
+ if (!isObject(raw)) return undefined
276
+ const out = {}
277
+ const serverName = optionalString(raw.serverName, 64)
278
+ if (serverName.length > 0) out.serverName = serverName
279
+ if (MCP_TRANSPORTS.includes(raw.transport)) out.transport = raw.transport
280
+ const url = optionalString(raw.url, 2048)
281
+ if (url.length > 0) out.url = url
282
+ const command = optionalString(raw.command, 2048)
283
+ if (command.length > 0) out.command = command
284
+ if (Array.isArray(raw.args)) {
285
+ const args = raw.args.filter((arg) => typeof arg === 'string').slice(0, 64).map((arg) => arg.slice(0, 2048))
286
+ if (args.length > 0) out.args = args
287
+ }
288
+ for (const key of ['headers', 'env']) {
289
+ if (!isObject(raw[key])) continue
290
+ const table = {}
291
+ for (const [name, value] of Object.entries(raw[key])) {
292
+ if (typeof value !== 'string') continue
293
+ if (name.length === 0 || name.length > 256) continue
294
+ table[name] = value.slice(0, 4096)
295
+ }
296
+ if (Object.keys(table).length > 0) out[key] = table
297
+ }
298
+ const cwd = optionalString(raw.cwd, 2048)
299
+ if (cwd.length > 0) out.cwd = cwd
300
+ return Object.keys(out).length > 0 ? out : undefined
301
+ }
302
+
303
+ /** Normalize one pool member entry (deterministic: never invents a timestamp). */
304
+ function normalizeMember(kind, raw) {
305
+ const scope = normalizeScope(raw)
306
+ if (scope === null) return null
307
+ const member = { ...scope }
308
+ if (kind === 'skill') {
309
+ const sourceId = optionalString(raw.sourceId, 128)
310
+ if (sourceId.length > 0) member.sourceId = sourceId
311
+ const digest = optionalString(raw.digest, 128)
312
+ if (digest.length > 0) member.digest = digest
313
+ // A member with its own non-empty list is "custom" unless it says otherwise:
314
+ // that keeps documents written before v4 gating exactly the same.
315
+ member.modesFrom = raw.modesFrom === 'self' ? 'self' : raw.modesFrom === 'group' ? 'group' : member.modes.length > 0 ? 'self' : 'group'
316
+ member.workspacesFrom =
317
+ raw.workspacesFrom === 'self' ? 'self' : raw.workspacesFrom === 'group' ? 'group' : member.workspaces.length > 0 ? 'self' : 'group'
318
+ }
319
+ if (kind === 'mcp') {
320
+ const definition = cleanMcpDefinition(raw.definition)
321
+ if (definition !== undefined) member.definition = definition
322
+ }
323
+ const installedAt = optionalString(raw.installedAt, 64)
324
+ member.installedAt = installedAt
325
+ return member
326
+ }
327
+
328
+ /** Normalize one member map (`skills` or `mcp`). */
329
+ function normalizeMembers(raw, kind) {
330
+ if (!isObject(raw)) return {}
331
+ const out = {}
332
+ for (const [key, value] of Object.entries(raw)) {
333
+ const name = cleanName(key)
334
+ if (name.length === 0) continue
335
+ const member = normalizeMember(kind, value)
336
+ if (member === null) continue
337
+ out[name] = member
338
+ }
339
+ return out
340
+ }
341
+
342
+ /** Normalize one `lastCheck` record (§2.1). */
343
+ function normalizeLastCheck(raw) {
344
+ if (!isObject(raw)) return undefined
345
+ const status = CHECK_STATUSES.includes(raw.status) ? raw.status : 'error'
346
+ return {
347
+ at: timestamp(raw.at),
348
+ status,
349
+ remote: optionalString(raw.remote, 128),
350
+ error: optionalString(raw.error, 1024),
351
+ }
352
+ }
353
+
354
+ /**
355
+ * Derive the Git identity of a source from either the explicit fields or its
356
+ * URL. The library re-parses `source.url` on check/update, so the URL is always
357
+ * stored for Git sources.
358
+ *
359
+ * @param {object} raw - candidate source record.
360
+ * @returns {{url: string, provider: string, project: string}|null} identity, or null.
361
+ */
362
+ function deriveGit(raw) {
363
+ const url = optionalString(raw.url, 2048)
364
+ let provider = GIT_PROVIDERS.includes(raw.provider) ? raw.provider : ''
365
+ let project = optionalString(raw.project, 512).replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '')
366
+ let parsedUrl = url
367
+
368
+ if (provider.length === 0 || project.split('/').length < 2) {
369
+ if (url.length === 0) return null
370
+ let text = url
371
+ const ssh = /^git@([^:]+):(.+)$/.exec(text)
372
+ if (ssh !== null) text = `https://${ssh[1]}/${ssh[2]}`
373
+ let parsed
374
+ try {
375
+ parsed = new URL(text)
376
+ } catch {
377
+ return null
378
+ }
379
+ const host = parsed.hostname.toLowerCase()
380
+ const derivedProvider = host.endsWith('github.com') ? 'github' : host.endsWith('gitlab.com') ? 'gitlab' : ''
381
+ const derivedProject = parsed.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '')
382
+ if (derivedProvider.length === 0 || derivedProject.split('/').length < 2) return null
383
+ provider = derivedProvider
384
+ project = derivedProject
385
+ parsedUrl = `${parsed.protocol}//${parsed.hostname}${parsed.pathname}`.replace(/\.git$/i, '')
386
+ }
387
+ if (parsedUrl.length === 0) {
388
+ const host = provider === 'gitlab' ? 'gitlab.com' : 'github.com'
389
+ parsedUrl = `https://${host}/${project}`
390
+ }
391
+ return { url: parsedUrl, provider, project }
392
+ }
393
+
394
+ /** Normalize one skill source record. */
395
+ function normalizeSource(raw) {
396
+ if (!isObject(raw)) return null
397
+ const kind = SOURCE_KINDS.includes(raw.kind) ? raw.kind : ''
398
+ if (kind.length === 0) return null
399
+ const id = cleanName(raw.id) || newId('src')
400
+ const label = optionalString(raw.label, 160) || defaultLabel(kind)
401
+ const source = {
402
+ id,
403
+ kind,
404
+ label,
405
+ skills: cleanNameList(raw.skills),
406
+ // Names the user deleted from this source: an update must not reinstall
407
+ // them. Kept apart from `skills` so "installed" stays the truth.
408
+ excluded: cleanNameList(raw.excluded),
409
+ createdAt: timestamp(raw.createdAt ?? raw.installedAt ?? raw.updatedAt),
410
+ }
411
+ const digest = optionalString(raw.digest, 128)
412
+ if (digest.length > 0) source.digest = digest
413
+ if (kind === 'git') {
414
+ const git = deriveGit(raw)
415
+ if (git === null) return null
416
+ source.url = git.url
417
+ source.provider = git.provider
418
+ source.project = git.project
419
+ source.branch = optionalString(raw.branch, 256) || 'main'
420
+ source.subdir = cleanSubdir(raw.subdir)
421
+ const sha = optionalString(raw.sha, 128)
422
+ if (sha.length > 0) source.sha = sha
423
+ const tokenCredential = optionalString(raw.tokenCredential, 128)
424
+ if (tokenCredential.length > 0) source.tokenCredential = tokenCredential
425
+ const lastCheck = normalizeLastCheck(raw.lastCheck)
426
+ if (lastCheck !== undefined) source.lastCheck = lastCheck
427
+ }
428
+ return source
429
+ }
430
+
431
+ /** Fallback display label for one source kind. */
432
+ function defaultLabel(kind) {
433
+ if (kind === 'git') return 'Git source'
434
+ if (kind === 'zip') return 'ZIP import'
435
+ return 'File upload'
436
+ }
437
+
438
+ /** Normalize one group record (`repo:<project>` / `import:<sourceId>`). */
439
+ function normalizeGroup(raw, fallbackKey) {
440
+ if (!isObject(raw)) return null
441
+ const key = optionalString(raw.key, 512) || optionalString(fallbackKey, 512)
442
+ if (key.length === 0) return null
443
+ const kind = GROUP_KINDS.includes(raw.kind) ? raw.kind : key.startsWith('import:') ? 'import' : 'repo'
444
+ return {
445
+ key,
446
+ kind,
447
+ // One switch for the whole repository: off means every member is off,
448
+ // without rewriting the per-member flags (they keep their own state).
449
+ enabled: raw.enabled !== false,
450
+ modes: cleanNameList(raw.modes),
451
+ workspaces: cleanPathList(raw.workspaces),
452
+ }
453
+ }
454
+
455
+ /** Normalize the `groups` map. */
456
+ function normalizeGroups(raw) {
457
+ if (!isObject(raw)) return {}
458
+ const out = {}
459
+ for (const [key, value] of Object.entries(raw)) {
460
+ const group = normalizeGroup(value, key)
461
+ if (group === null) continue
462
+ out[group.key] = group
463
+ }
464
+ return out
465
+ }
466
+
467
+ /** Whether two name lists hold the same values in the same order. */
468
+ function sameNames(left, right) {
469
+ if (!Array.isArray(left) || !Array.isArray(right)) return false
470
+ if (left.length !== right.length) return false
471
+ return left.every((value, index) => value === right[index])
472
+ }
473
+
474
+ /**
475
+ * Derive v4 groups from a v3 document: one group per repository (or per
476
+ * non-git import), seeded with the value its members already share. A mixed
477
+ * group starts empty, so the members that differ keep their own list.
478
+ */
479
+ function deriveGroups(sources, skills) {
480
+ const membersByKey = new Map()
481
+ for (const member of Object.values(skills)) {
482
+ const source = member.sourceId === undefined ? undefined : sources[member.sourceId]
483
+ const key = groupKeyOfSource(source)
484
+ if (key.length === 0) continue
485
+ if (!membersByKey.has(key)) membersByKey.set(key, [])
486
+ membersByKey.get(key).push(member)
487
+ }
488
+ const groups = {}
489
+ for (const [key, members] of membersByKey) {
490
+ const first = members[0]
491
+ const uniformModes = members.every((member) => sameNames(member.modes, first.modes))
492
+ const uniformWorkspaces = members.every((member) => sameNames(member.workspaces, first.workspaces))
493
+ groups[key] = {
494
+ key,
495
+ kind: key.startsWith('import:') ? 'import' : 'repo',
496
+ modes: uniformModes ? [...first.modes] : [],
497
+ workspaces: uniformWorkspaces ? [...first.workspaces] : [],
498
+ }
499
+ }
500
+ return groups
501
+ }
502
+
503
+ /**
504
+ * Upgrade a v3 document to v4.
505
+ *
506
+ * Groups are inferred so that every member keeps the exact scope it had: a
507
+ * repository whose members all agree gives that shared value to the group and
508
+ * the members inherit it; a mixed repository starts empty and only the members
509
+ * that already said something stay `self`. Nothing becomes more or less
510
+ * visible.
511
+ *
512
+ * @param {object} source - raw v3 document.
513
+ * @returns {object} v4 document.
514
+ */
515
+ function migrateV3(source) {
516
+ const rawSettings = isObject(source.settings) ? source.settings : {}
517
+ const settings = {
518
+ enabled: rawSettings.enabled !== false,
519
+ mcpGate: rawSettings.mcpGate !== false,
520
+ injectSummary: rawSettings.injectSummary !== false,
521
+ gateDefaultSkills: rawSettings.gateDefaultSkills === true,
522
+ }
523
+ const sources = {}
524
+ if (isObject(source.sources)) {
525
+ for (const value of Object.values(source.sources)) {
526
+ const normalized = normalizeSource(value)
527
+ if (normalized === null) continue
528
+ sources[normalized.id] = normalized
529
+ }
530
+ }
531
+ const skills = normalizeMembers(source.skills, 'skill')
532
+ const groups = deriveGroups(sources, skills)
533
+ for (const member of Object.values(skills)) {
534
+ const key = groupKeyOfSource(member.sourceId === undefined ? undefined : sources[member.sourceId])
535
+ const group = groups[key]
536
+ if (group === undefined) {
537
+ member.modesFrom = 'self'
538
+ member.workspacesFrom = 'self'
539
+ continue
540
+ }
541
+ member.modesFrom = sameNames(member.modes, group.modes) ? 'group' : 'self'
542
+ member.workspacesFrom = sameNames(member.workspaces, group.workspaces) ? 'group' : 'self'
543
+ }
544
+ return {
545
+ version: STATE_VERSION,
546
+ settings,
547
+ skills,
548
+ mcp: normalizeMembers(source.mcp, 'mcp'),
549
+ sources,
550
+ groups,
551
+ }
552
+ }
553
+
554
+ /**
555
+ * Normalize one group patch over the stored record (create when absent).
556
+ *
557
+ * @param {object} state - normalized document.
558
+ * @param {unknown} patch - `{key, modes?, workspaces?}`.
559
+ * @returns {object} normalized document (unchanged when the key is unusable).
560
+ */
561
+ export function upsertGroup(state, patch) {
562
+ const provided = isObject(patch) ? patch : {}
563
+ const key = optionalString(provided.key, 512)
564
+ if (key.length === 0) return state
565
+ const existing = isObject(state.groups) ? state.groups[key] : undefined
566
+ const group = normalizeGroup({ ...existing, ...provided, key }, key)
567
+ if (group === null) return state
568
+ return normalizeState({ ...state, groups: { ...state.groups, [key]: group } })
569
+ }
570
+
571
+ /**
572
+ * Normalize a complete document.
573
+ * @param {unknown} raw - candidate document.
574
+ * @returns {object} normalized v4 document.
575
+ */
576
+ export function normalizeState(raw) {
577
+ const source = isObject(raw) ? raw : {}
578
+ if (source.version === LEGACY_VERSION) return normalizeState(migrateV3(source))
579
+ if (source.version !== STATE_VERSION) return defaultState()
580
+
581
+ const rawSettings = isObject(source.settings) ? source.settings : {}
582
+ const settings = {
583
+ enabled: rawSettings.enabled !== false,
584
+ mcpGate: rawSettings.mcpGate !== false,
585
+ injectSummary: rawSettings.injectSummary !== false,
586
+ gateDefaultSkills: rawSettings.gateDefaultSkills === true,
587
+ }
588
+
589
+ const sources = {}
590
+ if (isObject(source.sources)) {
591
+ for (const value of Object.values(source.sources)) {
592
+ const normalized = normalizeSource(value)
593
+ if (normalized === null) continue
594
+ sources[normalized.id] = normalized
595
+ }
596
+ }
597
+
598
+ return {
599
+ version: STATE_VERSION,
600
+ settings,
601
+ skills: normalizeMembers(source.skills, 'skill'),
602
+ mcp: normalizeMembers(source.mcp, 'mcp'),
603
+ sources,
604
+ groups: normalizeGroups(source.groups),
605
+ }
606
+ }
607
+
608
+ /** Top-level sections every complete v4 document must carry as plain objects. */
609
+ const STATE_SECTIONS = ['settings', 'skills', 'mcp', 'sources', 'groups']
610
+
611
+ /**
612
+ * A state document that cannot be used safely.
613
+ *
614
+ * The code is intentionally stable for the HTTP/status surfaces; the message is
615
+ * a fixed explanation and never contains file bytes, member definitions or
616
+ * credentials. Callers either keep their previous gate (an already-live Agent)
617
+ * or fail closed (a new Agent).
618
+ */
619
+ export class StateReadError extends Error {
620
+ /**
621
+ * @param {string} code - stable error code such as `resource-pool/state-invalid-json`.
622
+ * @param {string} message - safe explanation, never document content.
623
+ */
624
+ constructor(code, message) {
625
+ // Keep diagnostics fixed, single-line and bounded: map keys and version
626
+ // values come from the file and may contain secrets or newlines.
627
+ super(String(message).replace(/[\r\n]+/g, ' ').slice(0, 240))
628
+ this.name = 'StateReadError'
629
+ this.code = code
630
+ this.status = 500
631
+ }
632
+ }
633
+
634
+ /** Throw the one "this document cannot be trusted" error. */
635
+ function invalidDocument(detail) {
636
+ throw new StateReadError(
637
+ 'resource-pool/state-invalid-document',
638
+ `state file is not a valid resource-pool document (${detail}); refusing to overwrite or use it`,
639
+ )
640
+ }
641
+
642
+ /** Require a plain object. */
643
+ function requireObject(value, what) {
644
+ if (!isObject(value)) invalidDocument(`${what} must be an object`)
645
+ }
646
+
647
+ /** Require a boolean when the property is present. */
648
+ function optionalBoolean(value, what) {
649
+ if (value !== undefined && typeof value !== 'boolean') invalidDocument(`${what} must be a boolean`)
650
+ }
651
+
652
+ /** Require a string when the property is present. */
653
+ function optionalStringField(value, what, limit = 4096) {
654
+ if (value === undefined) return
655
+ if (typeof value !== 'string' || value.length > limit) invalidDocument(`${what} must be a string of at most ${limit} characters`)
656
+ }
657
+
658
+ /** Require an array of conservative names. */
659
+ function requireNameList(value, what) {
660
+ if (!Array.isArray(value)) invalidDocument(`${what} must be an array of names`)
661
+ for (const item of value) {
662
+ if (typeof item !== 'string' || cleanName(item) !== item) invalidDocument(`${what} contains an invalid name`)
663
+ }
664
+ }
665
+
666
+ /** Require an array of absolute workspace paths. */
667
+ function requirePathList(value, what) {
668
+ if (!Array.isArray(value)) invalidDocument(`${what} must be an array of workspace paths`)
669
+ for (const item of value) {
670
+ if (typeof item !== 'string' || normalizePath(item).length === 0) invalidDocument(`${what} contains an invalid workspace path`)
671
+ }
672
+ }
673
+
674
+ /** Validate the settings switches. v3 allowed some switches to be absent. */
675
+ function validateSettings(raw, { requireAll }) {
676
+ requireObject(raw, 'settings')
677
+ for (const key of SETTING_KEYS) {
678
+ if (requireAll && !Object.hasOwn(raw, key)) invalidDocument(`settings.${key} is missing`)
679
+ optionalBoolean(raw[key], `settings.${key}`)
680
+ }
681
+ if (typeof raw.enabled !== 'boolean') invalidDocument('settings.enabled must be a boolean')
682
+ }
683
+
684
+ /** Validate the optional inheritance markers of a v4 skill member. */
685
+ function validateInheritance(raw, what) {
686
+ for (const key of ['modesFrom', 'workspacesFrom']) {
687
+ if (raw[key] !== undefined && raw[key] !== 'group' && raw[key] !== 'self') {
688
+ invalidDocument(`${what}.${key} must be 'group' or 'self'`)
689
+ }
690
+ }
691
+ }
692
+
693
+ /** Validate one stored MCP connection definition without echoing it. */
694
+ function validateDefinition(raw, what) {
695
+ requireObject(raw, what)
696
+ if (raw.transport !== undefined && !MCP_TRANSPORTS.includes(raw.transport)) invalidDocument(`${what}.transport is unsupported`)
697
+ for (const key of ['serverName', 'url', 'command', 'cwd']) optionalStringField(raw[key], `${what}.${key}`, 4096)
698
+ if (raw.args !== undefined) {
699
+ if (!Array.isArray(raw.args) || raw.args.some((arg) => typeof arg !== 'string')) {
700
+ invalidDocument(`${what}.args must be an array of strings`)
701
+ }
702
+ }
703
+ for (const key of ['headers', 'env']) {
704
+ if (raw[key] === undefined) continue
705
+ requireObject(raw[key], `${what}.${key}`)
706
+ for (const [name, value] of Object.entries(raw[key])) {
707
+ if (typeof name !== 'string' || name.length === 0 || name.length > 256 || typeof value !== 'string') {
708
+ invalidDocument(`${what}.${key} contains an invalid entry`)
709
+ }
710
+ }
711
+ }
712
+ }
713
+
714
+ /** Validate one pool member (`skills` / `mcp`). */
715
+ function validateMember(raw, what, { version, kind, sources }) {
716
+ requireObject(raw, what)
717
+ if (typeof raw.enabled !== 'boolean') invalidDocument(`${what}.enabled must be a boolean`)
718
+ requireNameList(raw.modes, `${what}.modes`)
719
+ requirePathList(raw.workspaces, `${what}.workspaces`)
720
+ optionalStringField(raw.installedAt, `${what}.installedAt`, 64)
721
+ if (version === STATE_VERSION) validateInheritance(raw, what)
722
+ if (kind === 'skill') {
723
+ optionalStringField(raw.sourceId, `${what}.sourceId`, 128)
724
+ optionalStringField(raw.digest, `${what}.digest`, 128)
725
+ if (
726
+ version === STATE_VERSION &&
727
+ typeof raw.sourceId === 'string' &&
728
+ raw.sourceId.length > 0 &&
729
+ isObject(sources) &&
730
+ !Object.hasOwn(sources, raw.sourceId) &&
731
+ (raw.modesFrom !== 'self' || raw.workspacesFrom !== 'self')
732
+ ) {
733
+ invalidDocument(`${what}.sourceId references a missing source while its scope inherits; refusing to resolve the inheritance`)
734
+ }
735
+ }
736
+ if (kind === 'mcp') {
737
+ if (raw.definition !== undefined) validateDefinition(raw.definition, `${what}.definition`)
738
+ }
739
+ }
740
+
741
+ /** Validate one member map. */
742
+ function validateMembers(raw, what, options) {
743
+ requireObject(raw, what)
744
+ for (const [key, value] of Object.entries(raw)) {
745
+ if (cleanName(key) !== key) invalidDocument(`${what} contains an invalid member key`)
746
+ validateMember(value, `${what} member`, options)
747
+ }
748
+ }
749
+
750
+ /** Validate the optional `lastCheck` record of a Git source. */
751
+ function validateLastCheck(raw, what) {
752
+ requireObject(raw, what)
753
+ if (!CHECK_STATUSES.includes(raw.status)) invalidDocument(`${what}.status is unsupported`)
754
+ for (const key of ['at', 'remote', 'error']) optionalStringField(raw[key], `${what}.${key}`, 1024)
755
+ }
756
+
757
+ /** Validate one source record. */
758
+ function validateSource(raw, key, what) {
759
+ requireObject(raw, what)
760
+ if (typeof raw.id !== 'string' || cleanName(raw.id) !== raw.id || raw.id !== key) {
761
+ invalidDocument(`${what}.id must be a valid name matching its map key`)
762
+ }
763
+ if (!SOURCE_KINDS.includes(raw.kind)) invalidDocument(`${what}.kind is unsupported`)
764
+ optionalStringField(raw.label, `${what}.label`, 160)
765
+ if (raw.skills !== undefined) requireNameList(raw.skills, `${what}.skills`)
766
+ if (raw.excluded !== undefined) requireNameList(raw.excluded, `${what}.excluded`)
767
+ optionalStringField(raw.digest, `${what}.digest`, 128)
768
+ optionalStringField(raw.createdAt, `${what}.createdAt`, 64)
769
+ if (raw.kind !== 'git') return
770
+ if (deriveGit(raw) === null) invalidDocument(`${what} does not name a usable Git repository`)
771
+ if (raw.provider !== undefined && !GIT_PROVIDERS.includes(raw.provider)) invalidDocument(`${what}.provider is unsupported`)
772
+ for (const sub of ['url', 'project', 'branch', 'subdir', 'sha', 'tokenCredential']) {
773
+ optionalStringField(raw[sub], `${what}.${sub}`, 2048)
774
+ }
775
+ if (raw.lastCheck !== undefined) validateLastCheck(raw.lastCheck, `${what}.lastCheck`)
776
+ }
777
+
778
+ /** Validate the `sources` map. */
779
+ function validateSources(raw) {
780
+ requireObject(raw, 'sources')
781
+ for (const [key, value] of Object.entries(raw)) validateSource(value, key, 'sources entry')
782
+ }
783
+
784
+ /** Validate one group record (`repo:<project>` / `import:<sourceId>`). */
785
+ function validateGroup(raw, key, what) {
786
+ requireObject(raw, what)
787
+ if (raw.key !== undefined && raw.key !== key) invalidDocument(`${what}.key must match its map key`)
788
+ if (raw.kind !== undefined && !GROUP_KINDS.includes(raw.kind)) invalidDocument(`${what}.kind is unsupported`)
789
+ if (typeof raw.enabled !== 'boolean') invalidDocument(`${what}.enabled must be a boolean`)
790
+ requireNameList(raw.modes, `${what}.modes`)
791
+ requirePathList(raw.workspaces, `${what}.workspaces`)
792
+ if (
793
+ typeof key !== 'string' ||
794
+ key.length === 0 ||
795
+ key.length > 512 ||
796
+ /[\u0000-\u001f\u007f]/.test(key) ||
797
+ FORBIDDEN_GROUP_KEYS.has(key) ||
798
+ key in Object.prototype
799
+ ) {
800
+ invalidDocument(`${what} has an invalid group key`)
801
+ }
802
+ const repoKey = key.startsWith('repo:')
803
+ const importKey = key.startsWith('import:')
804
+ if (repoKey && key.length <= 'repo:'.length) invalidDocument(`${what} has an invalid group key`)
805
+ if (importKey && key.length <= 'import:'.length) invalidDocument(`${what} has an invalid group key`)
806
+ if (raw.kind !== undefined && repoKey && raw.kind !== 'repo') invalidDocument(`${what}.kind does not match its key`)
807
+ if (raw.kind !== undefined && importKey && raw.kind !== 'import') invalidDocument(`${what}.kind does not match its key`)
808
+ }
809
+
810
+ /** Validate the `groups` map. */
811
+ function validateGroups(raw) {
812
+ requireObject(raw, 'groups')
813
+ for (const [key, value] of Object.entries(raw)) validateGroup(value, key, 'groups entry')
814
+ }
815
+
816
+ /**
817
+ * Validate a stored document before it is trusted for gating.
818
+ *
819
+ * `normalizeState` is deliberately lenient for pure migration/write helpers;
820
+ * reading a file is different: silently repairing a damaged document can widen
821
+ * what an Agent may reach. This function accepts exactly the complete v4 shape
822
+ * (and the v3 shape the explicit migration understands) and rejects anything it
823
+ * would otherwise have to invent, drop, or reinterpret.
824
+ *
825
+ * @param {unknown} raw - parsed JSON document.
826
+ * @returns {object} normalized v4 document.
827
+ * @throws {StateReadError} when the document is invalid or unsupported.
828
+ */
829
+ export function normalizeReadableState(raw) {
830
+ if (!isObject(raw)) {
831
+ throw new StateReadError('resource-pool/state-not-object', 'state file is not a JSON object; refusing to overwrite or use it')
832
+ }
833
+ if (raw.version === LEGACY_VERSION) {
834
+ validateSettings(raw.settings, { requireAll: false })
835
+ if (raw.groups !== undefined) {
836
+ if (!isObject(raw.groups)) invalidDocument('v3 document has a non-object "groups" section')
837
+ if (Object.keys(raw.groups).length > 0) {
838
+ invalidDocument('v3 document contains v4-only groups; refusing to migrate away their scope')
839
+ }
840
+ }
841
+ for (const section of ['skills', 'mcp']) {
842
+ if (!isObject(raw[section])) continue
843
+ for (const member of Object.values(raw[section])) {
844
+ if (!isObject(member)) continue
845
+ if (member.modesFrom !== undefined || member.workspacesFrom !== undefined) {
846
+ invalidDocument('v3 document contains v4-only inheritance markers; refusing to reinterpret its scope')
847
+ }
848
+ }
849
+ }
850
+ validateSources(raw.sources)
851
+ validateMembers(raw.skills, 'skills', { version: LEGACY_VERSION, kind: 'skill', sources: raw.sources })
852
+ validateMembers(raw.mcp, 'mcp', { version: LEGACY_VERSION, kind: 'mcp', sources: raw.sources })
853
+ return normalizeState(migrateV3(raw))
854
+ }
855
+ if (raw.version !== STATE_VERSION) {
856
+ throw new StateReadError(
857
+ 'resource-pool/state-unsupported-version',
858
+ 'state file uses an unsupported version; refusing to overwrite or use it',
859
+ )
860
+ }
861
+ for (const section of STATE_SECTIONS) {
862
+ if (!isObject(raw[section])) invalidDocument(`missing or invalid "${section}" section`)
863
+ }
864
+ validateSettings(raw.settings, { requireAll: true })
865
+ validateSources(raw.sources)
866
+ validateGroups(raw.groups)
867
+ validateMembers(raw.skills, 'skills', { version: STATE_VERSION, kind: 'skill', sources: raw.sources })
868
+ validateMembers(raw.mcp, 'mcp', { version: STATE_VERSION, kind: 'mcp', sources: raw.sources })
869
+ return normalizeState(raw)
870
+ }
871
+
872
+ /**
873
+ * Validate the document an update mutator returned.
874
+ *
875
+ * `normalizeState` treats anything that is not a complete v4 document as an
876
+ * empty default, so persisting an accidental `undefined` result (a mutation
877
+ * that forgot to return, or an async mutator that resolved to nothing) — or a
878
+ * fragment such as `{version: 4}` — would silently erase every stored member
879
+ * and credential. Refuse anything incomplete before it can reach the file.
880
+ *
881
+ * @param {unknown} next - mutation result.
882
+ * @returns {object} the same document when it is acceptable.
883
+ * @throws {TypeError} when the result is not a complete v4 document.
884
+ */
885
+ function assertStateDocument(next) {
886
+ if (!isObject(next) || next.version !== STATE_VERSION) {
887
+ throw new TypeError('StateStore.update(mutate) must return a complete v4 state document')
888
+ }
889
+ for (const section of STATE_SECTIONS) {
890
+ if (!isObject(next[section])) {
891
+ throw new TypeError(
892
+ `StateStore.update(mutate) must return a complete v4 state document: "${section}" must be an object`,
893
+ )
894
+ }
895
+ }
896
+ return next
897
+ }
898
+
899
+ /**
900
+ * Merge a settings patch over a normalized document.
901
+ * Unknown keys (including the retired `enforcePool`) are ignored.
902
+ *
903
+ * @param {object} state - normalized document.
904
+ * @param {unknown} patch - partial settings object.
905
+ * @returns {object} normalized document.
906
+ */
907
+ export function applySettingsPatch(state, patch) {
908
+ const provided = isObject(patch) ? patch : {}
909
+ const merged = { ...state.settings }
910
+ for (const key of SETTING_KEYS) {
911
+ if (typeof provided[key] === 'boolean') merged[key] = provided[key]
912
+ }
913
+ return normalizeState({ ...state, settings: merged })
914
+ }
915
+
916
+ /**
917
+ * Add or update one pool member. Passing a null scope removes it, so the same
918
+ * helper serves both edits and deletions.
919
+ *
920
+ * @param {object} state - normalized document.
921
+ * @param {'skill'|'mcp'} kind - member namespace.
922
+ * @param {unknown} name - resource name.
923
+ * @param {unknown} scope - `{enabled,modes,workspaces}`, or null to remove from the pool.
924
+ * @param {unknown} [extra] - provenance (`sourceId`, `digest`, `installedAt`); omitted values keep the stored ones.
925
+ * @returns {object} normalized document.
926
+ */
927
+ export function upsertItem(state, kind, name, scope, extra) {
928
+ if (!KINDS.includes(kind)) return state
929
+ const key = cleanName(name)
930
+ if (key.length === 0) return state
931
+ const bucket = kind === 'skill' ? 'skills' : 'mcp'
932
+ const currentBucket = isObject(state[bucket]) ? state[bucket] : {}
933
+ const next = { ...currentBucket }
934
+ if (scope === null || scope === undefined) {
935
+ delete next[key]
936
+ } else {
937
+ const normalized = normalizeScope(scope)
938
+ if (normalized === null) return state
939
+ next[key] = { ...normalized, ...itemExtras(kind, extra, currentBucket[key]) }
940
+ }
941
+ return normalizeState({ ...state, [bucket]: next })
942
+ }
943
+
944
+ /**
945
+ * Remove one pool member (membership only; callers remove files/loader rows).
946
+ * @param {object} state - normalized document.
947
+ * @param {'skill'|'mcp'} kind - member namespace.
948
+ * @param {unknown} name - resource name.
949
+ * @returns {object} normalized document.
950
+ */
951
+ export function removeItem(state, kind, name) {
952
+ if (!KINDS.includes(kind)) return state
953
+ const key = cleanName(name)
954
+ if (key.length === 0) return state
955
+ const bucket = kind === 'skill' ? 'skills' : 'mcp'
956
+ const currentBucket = isObject(state[bucket]) ? state[bucket] : {}
957
+ if (!Object.hasOwn(currentBucket, key)) return state
958
+ const next = { ...currentBucket }
959
+ delete next[key]
960
+ return normalizeState({ ...state, [bucket]: next })
961
+ }
962
+
963
+ /** Upsert one skill source. */
964
+ export function upsertSource(state, source) {
965
+ const normalized = normalizeSource(source)
966
+ if (normalized === null) return state
967
+ return normalizeState({ ...state, sources: { ...state.sources, [normalized.id]: normalized } })
968
+ }
969
+
970
+ /**
971
+ * Remove one skill source, and its group when it was the repository's last
972
+ * source: an empty repository has no members left to scope.
973
+ *
974
+ * @param {object} state - normalized document.
975
+ * @param {unknown} id - source id.
976
+ * @returns {object} normalized document.
977
+ */
978
+ export function removeSource(state, id) {
979
+ const key = cleanName(id)
980
+ if (key.length === 0) return state
981
+ const removed = isObject(state.sources) ? state.sources[key] : undefined
982
+ const next = { ...state.sources }
983
+ delete next[key]
984
+ const groups = isObject(state.groups) ? { ...state.groups } : {}
985
+ const groupKey = groupKeyOfSource(removed)
986
+ if (groupKey.length > 0 && !Object.values(next).some((source) => groupKeyOfSource(source) === groupKey)) {
987
+ delete groups[groupKey]
988
+ }
989
+ return normalizeState({ ...state, sources: next, groups })
990
+ }
991
+
992
+ /**
993
+ * Record that one skill was deleted by the user: drop it from every source that
994
+ * installed it and remember it as excluded, so a later update skips it.
995
+ *
996
+ * @param {object} state - normalized document.
997
+ * @param {unknown} name - skill name.
998
+ * @returns {object} normalized document.
999
+ */
1000
+ export function excludeSourceSkill(state, name) {
1001
+ const key = cleanName(name)
1002
+ if (key.length === 0) return state
1003
+ let next = state
1004
+ for (const source of Object.values(isObject(state.sources) ? state.sources : {})) {
1005
+ if (!Array.isArray(source.skills) || !source.skills.includes(key)) continue
1006
+ next = upsertSource(next, {
1007
+ ...source,
1008
+ skills: source.skills.filter((skill) => skill !== key),
1009
+ excluded: [...(Array.isArray(source.excluded) ? source.excluded : []), key],
1010
+ })
1011
+ }
1012
+ return next
1013
+ }
1014
+
1015
+ /**
1016
+ * Names one source may install again: its excluded list removed.
1017
+ *
1018
+ * @param {Array<string>} names - candidate names.
1019
+ * @param {Array<string>} excluded - excluded names.
1020
+ * @returns {Array<string>} names that are not excluded.
1021
+ */
1022
+ export function withoutExcluded(names, excluded) {
1023
+ const blocked = new Set(Array.isArray(excluded) ? excluded : [])
1024
+ return (Array.isArray(names) ? names : []).filter((name) => !blocked.has(name))
1025
+ }
1026
+
1027
+ /**
1028
+ * Durable JSON document with atomic, serialized writes.
1029
+ */
1030
+ export class StateStore {
1031
+ constructor({ file, logger, version = '0.3.0' } = {}) {
1032
+ this.file = typeof file === 'string' && file.length > 0 ? file : statePath()
1033
+ this.key = resolvePath(this.file)
1034
+ this.logger = logger
1035
+ this.version = version
1036
+ this.cached = undefined
1037
+ this.writeChain = Promise.resolve()
1038
+ // Marks the async context of a task currently running on `writeChain`, so a
1039
+ // nested write/update can be rejected instead of waiting on itself forever.
1040
+ this.taskContext = new AsyncLocalStorage()
1041
+ // Whether this Store instance has ever successfully read or written the
1042
+ // document. A later ENOENT is then a failure, not a fresh first run. A new
1043
+ // process cannot distinguish a deleted file from a genuine first run; that
1044
+ // boundary is documented in README/CONTRACTS.
1045
+ this.everLoaded = false
1046
+ // Whether the path was ever observed to exist (even if its bytes failed to
1047
+ // parse). Deleting it afterwards is still abnormal.
1048
+ this.everObserved = false
1049
+ }
1050
+
1051
+ /**
1052
+ * Decode and validate one state text.
1053
+ *
1054
+ * @param {string} text - raw file contents.
1055
+ * @returns {object} normalized v4 document.
1056
+ * @throws {StateReadError} when the bytes are not a readable state document.
1057
+ */
1058
+ #decode(text) {
1059
+ let raw
1060
+ try {
1061
+ raw = JSON.parse(text)
1062
+ } catch {
1063
+ throw new StateReadError('resource-pool/state-invalid-json', 'state file is not valid JSON; refusing to overwrite or use it')
1064
+ }
1065
+ const state = normalizeReadableState(raw)
1066
+ this.everLoaded = true
1067
+ return state
1068
+ }
1069
+
1070
+ /**
1071
+ * Read the document, caching the normalized result.
1072
+ *
1073
+ * A missing file is a valid first run only until this Store has seen the
1074
+ * document. Every other failure throws a {@link StateReadError}; returning
1075
+ * defaults here would silently widen the pool (an empty pool does not gate).
1076
+ *
1077
+ * @param {{fresh?: boolean}} [options] - force a disk read.
1078
+ * @returns {Promise<object>} normalized v4 document.
1079
+ * @throws {StateReadError} when the file is missing after a successful read,
1080
+ * unreadable, corrupt, unsupported or semantically invalid.
1081
+ */
1082
+ async read({ fresh = false } = {}) {
1083
+ if (!fresh && this.cached !== undefined) return this.cached
1084
+ let text
1085
+ try {
1086
+ text = await readFile(this.file, 'utf8')
1087
+ } catch (error) {
1088
+ if (error?.code !== 'ENOENT') {
1089
+ this.everObserved = true
1090
+ observedStateFiles.add(this.key)
1091
+ throw new StateReadError('resource-pool/state-unreadable', 'state file could not be read; refusing to overwrite or use it')
1092
+ }
1093
+ if (this.everLoaded || this.everObserved || observedStateFiles.has(this.key)) {
1094
+ throw new StateReadError(
1095
+ 'resource-pool/state-missing',
1096
+ 'state file disappeared after it was known to exist; refusing to treat it as a first run',
1097
+ )
1098
+ }
1099
+ this.cached = defaultState()
1100
+ return this.cached
1101
+ }
1102
+ this.everObserved = true
1103
+ observedStateFiles.add(this.key)
1104
+ this.cached = this.#decode(text)
1105
+ return this.cached
1106
+ }
1107
+
1108
+ /**
1109
+ * Queue one operation behind every write/update already scheduled.
1110
+ *
1111
+ * A rejection settles only the operation's own promise: the queue itself is
1112
+ * reset to a fulfilled promise, so one failed save never wedges later ones.
1113
+ *
1114
+ * A call made from inside a queued task's async context (typically `await
1115
+ * store.write(...)` inside an `update` mutator) is rejected immediately: it
1116
+ * would queue behind the very task awaiting it and deadlock the store.
1117
+ * AsyncLocalStorage distinguishes those descendants from independent callers
1118
+ * that merely arrive while the queue is busy — a process-wide "busy" flag
1119
+ * would wrongly reject those external calls too.
1120
+ *
1121
+ * @param {() => Promise<object>} task - operation to run once its turn comes.
1122
+ * @returns {Promise<object>} the operation's result.
1123
+ */
1124
+ #enqueue(task) {
1125
+ if (this.taskContext.getStore() === true) {
1126
+ return Promise.reject(
1127
+ new Error(
1128
+ 'StateStore.write/update cannot be called from inside an update mutator: it would wait on the same queue',
1129
+ ),
1130
+ )
1131
+ }
1132
+ const run = this.writeChain.then(() => this.taskContext.run(true, task))
1133
+ this.writeChain = run.then(
1134
+ () => undefined,
1135
+ () => undefined,
1136
+ )
1137
+ return run
1138
+ }
1139
+
1140
+ /**
1141
+ * Read the document for a queued read-modify-write, failing instead of
1142
+ * guessing.
1143
+ *
1144
+ * An update is about to overwrite the file, so it uses the same fail-closed
1145
+ * validation as `read()`: a JSON parse error, unsupported version, semantic
1146
+ * invalidity or I/O error must abort the save instead of replacing
1147
+ * credential-bearing state with defaults. Only a missing file (ENOENT)
1148
+ * legitimately starts from defaults, and only before this store has observed
1149
+ * the document.
1150
+ *
1151
+ * @returns {Promise<object>} normalized on-disk document.
1152
+ */
1153
+ async #readStrict() {
1154
+ let text
1155
+ try {
1156
+ text = await readFile(this.file, 'utf8')
1157
+ } catch (error) {
1158
+ if (error?.code === 'ENOENT') {
1159
+ if (this.everLoaded || this.everObserved || observedStateFiles.has(this.key)) {
1160
+ throw new StateReadError(
1161
+ 'resource-pool/state-missing',
1162
+ 'state file disappeared after it was known to exist; refusing to overwrite it',
1163
+ )
1164
+ }
1165
+ this.cached = defaultState()
1166
+ return this.cached
1167
+ }
1168
+ this.everObserved = true
1169
+ observedStateFiles.add(this.key)
1170
+ throw new StateReadError('resource-pool/state-unreadable', 'state file could not be read; refusing to overwrite it')
1171
+ }
1172
+ this.everObserved = true
1173
+ observedStateFiles.add(this.key)
1174
+ this.cached = this.#decode(text)
1175
+ return this.cached
1176
+ }
1177
+
1178
+ /**
1179
+ * Persist one normalized document atomically, then update the cache.
1180
+ *
1181
+ * Only the queue may call this: `write`/`update` enqueue, so calling them from
1182
+ * inside a queued task would wait on itself and deadlock.
1183
+ *
1184
+ * @param {object} normalized - normalized document.
1185
+ * @returns {Promise<object>} the persisted document.
1186
+ */
1187
+ async #persist(normalized) {
1188
+ await mkdir(dirname(this.file), { recursive: true })
1189
+ const temporary = `${this.file}.${process.pid}.${Date.now()}.tmp`
1190
+ // 0600: an MCP member may carry an `Authorization` header, so the pool
1191
+ // document holds the same secrets a profile patch would.
1192
+ await writeFile(temporary, `${JSON.stringify(normalized, null, 2)}\n`, { encoding: 'utf8', mode: 0o600 })
1193
+ await rename(temporary, this.file)
1194
+ this.cached = normalized
1195
+ this.everLoaded = true
1196
+ this.everObserved = true
1197
+ observedStateFiles.add(this.key)
1198
+ return normalized
1199
+ }
1200
+
1201
+ /** Persist a complete, readable document, queued behind earlier writes/updates. */
1202
+ async write(state) {
1203
+ // Validate before queueing: a direct write must not be able to replace a
1204
+ // credential-bearing document with a fragment or a semantically broken one.
1205
+ const normalized = normalizeReadableState(state)
1206
+ return this.#enqueue(() => this.#persist(normalized))
1207
+ }
1208
+
1209
+ /**
1210
+ * Apply one mutation to a fresh read and persist the result as one queued
1211
+ * read-modify-write.
1212
+ *
1213
+ * The strict fresh read happens inside the queue, after every earlier
1214
+ * write/update has settled. Two concurrent updates therefore see each other's
1215
+ * result instead of overwriting it, and direct `write` calls keep their call
1216
+ * order. `mutate` may be async, but must resolve to a complete v4 document;
1217
+ * an invalid result is rejected before anything is written. A nested
1218
+ * `store.write`/`store.update` inside `mutate` is rejected instead of
1219
+ * enqueueing behind itself, which would deadlock the queue.
1220
+ *
1221
+ * @param {(state: object) => object|Promise<object>} mutate - pure mutation.
1222
+ * @returns {Promise<object>} the persisted document.
1223
+ */
1224
+ async update(mutate) {
1225
+ return this.#enqueue(async () => {
1226
+ const current = await this.#readStrict()
1227
+ const next = assertStateDocument(await mutate(current))
1228
+ // Validate the mutation's result with the same fail-closed rules as a
1229
+ // disk read: never persist a document we would refuse to read back.
1230
+ return this.#persist(normalizeReadableState(next))
1231
+ })
1232
+ }
1233
+ }