dsh-version-manager 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,346 @@
1
+ /**
2
+ * Putting one skill directory back to a snapshot that was taken of it.
3
+ *
4
+ * This is the only module in the plugin that writes into a user's skill
5
+ * directory, so it is written to fail closed and to leave a way back:
6
+ *
7
+ * 1. the snapshot must be about *this* skill and *this* directory;
8
+ * 2. the stored copy is re-fingerprinted and must still match its manifest,
9
+ * because a snapshot whose bytes drifted is not a baseline;
10
+ * 3. the directory as it stands right now is snapshotted first, so the
11
+ * restore itself can be undone;
12
+ * 4. the replacement is assembled in a sibling staging directory, verified
13
+ * against the same digest, and only then swapped in — same volume, two
14
+ * renames, with the old directory parked beside it rather than deleted.
15
+ *
16
+ * Two things this module deliberately never does:
17
+ *
18
+ * - It never runs a Git command. Not `checkout`, not `reset`, not `clean`. The
19
+ * snapshot store already holds the exact bytes, so there is nothing a
20
+ * checkout could add and plenty it could ruin.
21
+ * - It refuses to write into a directory that belongs to a Git checkout, and
22
+ * into the host's own `.system` tree. A restore that silently rewrites
23
+ * tracked files, or that edits the skills shipped with the host, is not a
24
+ * restore a user can reason about.
25
+ *
26
+ * @module dsh-version-manager/lib/host/skill-restore
27
+ */
28
+
29
+ import { randomUUID } from 'node:crypto'
30
+ import { cp, mkdir, readFile, readdir, rename, rm } from 'node:fs/promises'
31
+ import { dirname, join, sep } from 'node:path'
32
+
33
+ import { fingerprintTree } from './snapshot-store.js'
34
+ import { directoryState, listSkillSnapshots, readGitState, snapshotSkill } from './skills.js'
35
+
36
+ /**
37
+ * @param {string} dshHome
38
+ * @param {string} profileId
39
+ * @param {string} name
40
+ * @returns {string}
41
+ */
42
+ function skillRoot(dshHome, profileId, name) {
43
+ return join(dshHome, 'version-manager', 'skills', profileId, name)
44
+ }
45
+
46
+ /**
47
+ * True when a path contains a `.system` segment.
48
+ *
49
+ * The host's filesystem provider skips `.system` when it discovers skills, so a
50
+ * skill can never legitimately live there; a path that reaches it came from
51
+ * somewhere other than the catalog.
52
+ *
53
+ * @param {string} path
54
+ * @returns {boolean}
55
+ */
56
+ export function isSystemPath(path) {
57
+ const parts = String(path).split(/[\\/]+/)
58
+ return parts.some((part) => part === '.system')
59
+ }
60
+
61
+ /**
62
+ * Read one stored manifest and confirm it still describes its own copy.
63
+ *
64
+ * @param {object} input
65
+ * @param {string} input.dshHome
66
+ * @param {string} input.profileId
67
+ * @param {string} input.name
68
+ * @param {string} input.file - a manifest file name from listSkillSnapshots
69
+ * @returns {Promise<{ ok: boolean, reason: string | null, document: object | null, copy: string | null }>}
70
+ */
71
+ export async function readSkillSnapshot(input) {
72
+ const { dshHome, profileId, name, file } = input
73
+ if (typeof file !== 'string' || file === '' || file.includes('/') || file.includes('\\') || file.includes('..')) {
74
+ return { ok: false, reason: 'bad-snapshot-file', document: null, copy: null }
75
+ }
76
+ const root = skillRoot(dshHome, profileId, name)
77
+ let document
78
+ try {
79
+ document = JSON.parse(await readFile(join(root, file), 'utf8'))
80
+ } catch {
81
+ return { ok: false, reason: 'snapshot-unreadable', document: null, copy: null }
82
+ }
83
+ if (document?.kind !== 'skill' || document?.skill?.name !== name) {
84
+ return { ok: false, reason: 'snapshot-mismatch', document: null, copy: null }
85
+ }
86
+ const copy = typeof document.copy === 'string' && document.copy !== '' ? join(root, document.copy) : null
87
+ if (copy === null) return { ok: false, reason: 'snapshot-copy-missing', document: null, copy: null }
88
+ const state = await directoryState(copy)
89
+ if (state !== 'directory') return { ok: false, reason: 'snapshot-copy-missing', document: null, copy: null }
90
+ return { ok: true, reason: null, document, copy }
91
+ }
92
+
93
+ /**
94
+ * Whether a catalog row may be written at all, independent of any snapshot.
95
+ *
96
+ * The panel asks this once per row so a restore button is disabled for a
97
+ * reason the user can read, instead of failing after the click.
98
+ *
99
+ * @param {{ directory: string | null, source?: string | null, git?: { managed?: boolean } | null }} skill
100
+ * @returns {string | null} a reason code, or null when a restore is allowed
101
+ */
102
+ export function skillRestoreRefusal(skill) {
103
+ if (skill.directory === null || skill.directory === undefined) return 'no-directory'
104
+ if (isSystemPath(skill.directory)) return 'system-skill'
105
+ if (skill.git?.managed === true) return 'inside-git-checkout'
106
+ if (skill.source === 'bundled') return 'bundled-skill'
107
+ return null
108
+ }
109
+
110
+ /**
111
+ * Everything a restore would do, without doing it.
112
+ *
113
+ * The panel calls this before showing its confirmation bar: a restore that is
114
+ * going to be refused should say so while the user is reading, not after they
115
+ * click.
116
+ *
117
+ * @param {object} input
118
+ * @param {string} input.dshHome
119
+ * @param {string} input.profileId
120
+ * @param {string} input.name
121
+ * @param {string} input.directory
122
+ * @param {string | null} [input.source]
123
+ * @param {string} input.file
124
+ * @returns {Promise<{ ok: boolean, reason: string | null, detail: object | null }>}
125
+ */
126
+ export async function previewSkillRestore(input) {
127
+ const { dshHome, profileId, name, directory, file } = input
128
+ const read = await readSkillSnapshot({ dshHome, profileId, name, file })
129
+ if (!read.ok) return { ok: false, reason: read.reason, detail: null }
130
+
131
+ const document = read.document
132
+ if (document.skill.directory !== directory) {
133
+ // A snapshot of a different directory can never be the baseline for this
134
+ // one, even when both happen to carry the same skill name.
135
+ return { ok: false, reason: 'snapshot-directory-mismatch', detail: null }
136
+ }
137
+ // The catalog's own source travels with the request: judging a bundled skill
138
+ // by its directory alone would let a snapshot of DSH's own files be written
139
+ // back over them.
140
+ const refusal = skillRestoreRefusal({
141
+ directory,
142
+ source: input.source ?? null,
143
+ git: await readGitState(directory),
144
+ })
145
+ if (refusal !== null) return { ok: false, reason: refusal, detail: null }
146
+
147
+ const recordedDigest = typeof document.skill.digest === 'string' ? document.skill.digest : null
148
+ const copyFingerprint = await fingerprintTree(read.copy)
149
+ if (recordedDigest === null || copyFingerprint === null || copyFingerprint.digest !== recordedDigest) {
150
+ return { ok: false, reason: 'snapshot-copy-corrupt', detail: null }
151
+ }
152
+
153
+ const current = await fingerprintTree(directory)
154
+ return {
155
+ ok: true,
156
+ reason: null,
157
+ detail: {
158
+ recordedDigest,
159
+ currentDigest: current === null ? null : current.digest,
160
+ // `sameFiles` is evidence, not a gate: a restore exists precisely because
161
+ // the directory moved away from the snapshot.
162
+ sameFiles: current === null ? null : current.digest === recordedDigest,
163
+ digestVerified: true,
164
+ files: copyFingerprint.files,
165
+ bytes: copyFingerprint.bytes,
166
+ takenAt: document.takenAt ?? null,
167
+ revision: document.git?.revision ?? null,
168
+ },
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Put one skill directory back to a stored snapshot.
174
+ *
175
+ * @param {object} input
176
+ * @param {string} input.dshHome
177
+ * @param {string} input.profileId
178
+ * @param {string} input.name
179
+ * @param {string} input.directory
180
+ * @param {string | null} [input.source]
181
+ * @param {string} input.file
182
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null,
183
+ * evidence: object | null, restoredTo: string | null, undo: string | null }>}
184
+ */
185
+ export async function restoreSkillSnapshot(input) {
186
+ const { dshHome, profileId, name, directory, file, source = null } = input
187
+ const preview = await previewSkillRestore({ dshHome, profileId, name, directory, file, source })
188
+ if (!preview.ok) {
189
+ return { ok: false, reason: preview.reason, message: null, evidence: null, restoredTo: null, undo: null }
190
+ }
191
+
192
+ const read = await readSkillSnapshot({ dshHome, profileId, name, file })
193
+ if (!read.ok || read.copy === null) {
194
+ return { ok: false, reason: read.reason, message: null, evidence: null, restoredTo: null, undo: null }
195
+ }
196
+ const target = directory
197
+ const witness = 'version-manager restore'
198
+ const parent = dirname(target)
199
+ const base = target.slice(parent.length).replace(/^[\\/]+/, '')
200
+ const suffix = randomUUID().slice(0, 8)
201
+ const staging = join(parent, `.${base}.${witness}-${suffix}`)
202
+ const parked = join(parent, `.${base}.${witness}-old-${suffix}`)
203
+
204
+ const state = await directoryState(target)
205
+ if (state !== 'directory' && state !== 'missing') {
206
+ return { ok: false, reason: 'not-a-directory', message: null, evidence: null, restoredTo: null, undo: null }
207
+ }
208
+
209
+ // Keep a way back before touching anything. A directory that is already gone
210
+ // has nothing worth keeping, and reporting a snapshot that does not exist
211
+ // would be worse than reporting none.
212
+ let undo = null
213
+ if (state === 'directory') {
214
+ try {
215
+ const saved = await snapshotSkill({
216
+ dshHome,
217
+ profileId,
218
+ name,
219
+ directory: target,
220
+ git: null,
221
+ reason: 'before-restore',
222
+ })
223
+ undo = saved.manifest.skill.digest
224
+ } catch (error) {
225
+ return {
226
+ ok: false,
227
+ reason: 'undo-snapshot-failed',
228
+ message: error instanceof Error ? error.message : String(error),
229
+ evidence: null,
230
+ restoredTo: null,
231
+ undo: null,
232
+ }
233
+ }
234
+ }
235
+
236
+ const cleanup = async () => {
237
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
238
+ }
239
+
240
+ try {
241
+ await mkdir(staging, { recursive: true })
242
+ await cp(read.copy, staging, { recursive: true, dereference: false, force: true, errorOnExist: false })
243
+ } catch (error) {
244
+ await cleanup()
245
+ return {
246
+ ok: false,
247
+ reason: 'staging-failed',
248
+ message: error instanceof Error ? error.message : String(error),
249
+ evidence: null,
250
+ restoredTo: null,
251
+ undo,
252
+ }
253
+ }
254
+
255
+ const staged = await fingerprintTree(staging)
256
+ const expected = read.document.skill.digest
257
+ if (staged === null || staged.digest !== expected) {
258
+ await cleanup()
259
+ return {
260
+ ok: false,
261
+ reason: 'staged-copy-corrupt',
262
+ message: null,
263
+ evidence: null,
264
+ restoredTo: null,
265
+ undo,
266
+ }
267
+ }
268
+
269
+ let parkedOk = state === 'missing'
270
+ try {
271
+ if (state === 'directory') {
272
+ await rename(target, parked)
273
+ parkedOk = true
274
+ }
275
+ await rename(staging, target)
276
+ } catch (error) {
277
+ // Put the original back if the swap did not complete. If even that fails,
278
+ // say so with the parked path rather than claiming a clean failure.
279
+ if (parkedOk && state === 'directory') {
280
+ await rename(parked, target).catch(() => {})
281
+ }
282
+ await cleanup()
283
+ return {
284
+ ok: false,
285
+ reason: 'swap-failed',
286
+ message: error instanceof Error ? error.message : String(error),
287
+ evidence: { parked },
288
+ restoredTo: null,
289
+ undo,
290
+ }
291
+ }
292
+
293
+ const placed = await fingerprintTree(target)
294
+ if (placed === null || placed.digest !== expected) {
295
+ return {
296
+ ok: false,
297
+ reason: 'verification-failed',
298
+ message: null,
299
+ evidence: { parked: parkedOk ? parked : null, placedDigest: placed === null ? null : placed.digest },
300
+ restoredTo: null,
301
+ undo,
302
+ }
303
+ }
304
+
305
+ if (parkedOk && state === 'directory') {
306
+ await rm(parked, { recursive: true, force: true }).catch(() => {})
307
+ }
308
+
309
+ return {
310
+ ok: true,
311
+ reason: null,
312
+ message: null,
313
+ evidence: {
314
+ digest: placed.digest,
315
+ files: placed.files,
316
+ recordedDigest: expected,
317
+ previousDigest: preview.detail?.currentDigest ?? null,
318
+ directoryExisted: state === 'directory',
319
+ },
320
+ restoredTo: read.document.takenAt ?? null,
321
+ undo,
322
+ }
323
+ }
324
+
325
+ /**
326
+ * The snapshot files for one skill, for a caller that wants to offer undo.
327
+ *
328
+ * @param {string} dshHome
329
+ * @param {string} profileId
330
+ * @param {string} name
331
+ * @returns {Promise<object[]>}
332
+ */
333
+ export async function listRestorableSnapshots(dshHome, profileId, name) {
334
+ const rows = await listSkillSnapshots(dshHome, profileId, name)
335
+ return rows.filter((row) => row.unreadable !== true && row.digest !== null)
336
+ }
337
+
338
+ /**
339
+ * Path segments of a directory, used by tests to assert nothing escaped.
340
+ *
341
+ * @param {string} path
342
+ * @returns {string[]}
343
+ */
344
+ export function segments(path) {
345
+ return String(path).split(sep)
346
+ }
@@ -0,0 +1,327 @@
1
+ /**
2
+ * Skill inventory.
3
+ *
4
+ * Skills are directories, not packages: the host discovers them from a fixed
5
+ * list of roots and there is no version field anywhere. So this module reports
6
+ * only what it can prove — which root a skill came from, where its files live,
7
+ * what a Git checkout says about it, and a content fingerprint. Nothing here
8
+ * claims a version, because nothing on disk records one.
9
+ *
10
+ * Everything is read-only. `snapshotSkill` copies a directory into the
11
+ * snapshot store and re-reads the copy to prove the bytes match; it never
12
+ * writes inside the skill itself.
13
+ */
14
+
15
+ import { execFile } from 'node:child_process'
16
+ import { cp, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'
17
+ import { join, relative } from 'node:path'
18
+
19
+ import { fingerprintTree } from './snapshot-store.js'
20
+
21
+ const GIT_TIMEOUT_MS = 5000
22
+ const MAX_SKILL_FILES = 5000
23
+
24
+ /**
25
+ * Run a bounded Git command.
26
+ *
27
+ * @param {string[]} args
28
+ * @param {string} cwd
29
+ * @returns {Promise<{ ok: boolean, stdout: string, code: string | null }>}
30
+ */
31
+ function runGit(args, cwd) {
32
+ return new Promise((resolve) => {
33
+ execFile(
34
+ 'git',
35
+ args,
36
+ {
37
+ cwd,
38
+ timeout: GIT_TIMEOUT_MS,
39
+ windowsHide: true,
40
+ shell: false,
41
+ encoding: 'utf8',
42
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', LC_ALL: 'C' },
43
+ maxBuffer: 1024 * 1024,
44
+ },
45
+ (error, stdout, stderr) => {
46
+ if (error) {
47
+ // A missing git binary and a directory that is not a repository both
48
+ // land here; the caller only needs "not a checkout I can describe".
49
+ const code = error.code === 'ENOENT' ? 'git-not-found' : 'not-a-repository'
50
+ resolve({ ok: false, stdout: '', code, stderr: String(stderr ?? '').slice(0, 400) })
51
+ return
52
+ }
53
+ resolve({ ok: true, stdout: String(stdout ?? '').trim(), code: null })
54
+ },
55
+ )
56
+ })
57
+ }
58
+
59
+ /**
60
+ * Describe the Git checkout that owns a skill directory, if there is one.
61
+ *
62
+ * The question "is this skill managed by a checkout" cannot be answered from a
63
+ * path alone: a skill can sit inside a larger repository. `rev-parse
64
+ * --show-toplevel` answers it without touching the working tree.
65
+ *
66
+ * @param {string} directory
67
+ * @returns {Promise<{ managed: boolean, reason: string | null, root: string | null,
68
+ * revision: string | null, remote: string | null, subpath: string | null,
69
+ * dirty: boolean | null, changes: number | null }>}
70
+ */
71
+ export async function readGitState(directory) {
72
+ const empty = {
73
+ managed: false,
74
+ reason: null,
75
+ root: null,
76
+ revision: null,
77
+ remote: null,
78
+ subpath: null,
79
+ dirty: null,
80
+ changes: null,
81
+ }
82
+ const top = await runGit(['rev-parse', '--show-toplevel'], directory)
83
+ if (!top.ok) {
84
+ return {
85
+ ...empty,
86
+ reason: top.code === 'git-not-found' ? 'Git is not installed on this machine.' : 'Not inside a Git checkout.',
87
+ }
88
+ }
89
+ const root = top.stdout
90
+ const revision = await runGit(['rev-parse', '--short', 'HEAD'], directory)
91
+ const remote = await runGit(['remote', 'get-url', 'origin'], directory)
92
+ // `status --porcelain -- .` counts only changes under this skill, so a dirty
93
+ // sibling directory does not make this skill look modified.
94
+ const status = await runGit(['status', '--porcelain', '--', '.'], directory)
95
+ const lines = status.ok && status.stdout !== '' ? status.stdout.split('\n').filter(Boolean) : []
96
+ return {
97
+ managed: true,
98
+ reason: null,
99
+ root,
100
+ revision: revision.ok ? revision.stdout : null,
101
+ remote: remote.ok ? remote.stdout : null,
102
+ subpath: relative(root, directory).split('\\').join('/') || '.',
103
+ dirty: status.ok ? lines.length > 0 : null,
104
+ changes: status.ok ? lines.length : null,
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Walk a skill directory to count files without following links out of it.
110
+ *
111
+ * @param {string} root
112
+ * @returns {Promise<{ files: number, truncated: boolean }>}
113
+ */
114
+ async function countFiles(root) {
115
+ let files = 0
116
+ let truncated = false
117
+ const queue = [root]
118
+ while (queue.length > 0) {
119
+ const current = queue.shift()
120
+ let entries
121
+ try {
122
+ entries = await readdir(current, { withFileTypes: true })
123
+ } catch {
124
+ continue
125
+ }
126
+ for (const entry of entries) {
127
+ if (files >= MAX_SKILL_FILES) {
128
+ truncated = true
129
+ break
130
+ }
131
+ if (entry.isDirectory()) queue.push(join(current, entry.name))
132
+ else if (entry.isFile()) files += 1
133
+ }
134
+ if (truncated) break
135
+ }
136
+ return { files, truncated }
137
+ }
138
+
139
+ /**
140
+ * Read the skill catalog the host itself serves.
141
+ *
142
+ * The `skills` service is the only supported view: it applies root priority and
143
+ * reports `complete`, which says whether discovery finished. When it is absent
144
+ * the answer is "cannot be read here", never an empty list.
145
+ *
146
+ * @param {import('@deepseek-ai/cordis').Context} ctx
147
+ * @param {{ cwd?: string }} [options]
148
+ */
149
+ export async function readSkills(ctx, options = {}) {
150
+ const service = ctx.get('skills')
151
+ if (service === undefined || service === null) {
152
+ return {
153
+ available: false,
154
+ reason: 'The host exposes no skills service in this process.',
155
+ provider: null,
156
+ complete: null,
157
+ skills: [],
158
+ }
159
+ }
160
+ const view = options.cwd === undefined ? {} : { cwd: options.cwd }
161
+ let snapshot
162
+ try {
163
+ snapshot = await service.snapshot(view)
164
+ } catch (error) {
165
+ return {
166
+ available: false,
167
+ reason: `The skills service refused the request: ${String(error?.message ?? error)}`,
168
+ provider: null,
169
+ complete: null,
170
+ skills: [],
171
+ }
172
+ }
173
+ const list = Array.isArray(snapshot?.skills) ? snapshot.skills : []
174
+ const rows = []
175
+ for (const skill of list) {
176
+ const directory = skill.resourceBase?.path ?? null
177
+ const kind = skill.resourceBase?.kind ?? null
178
+ const files = directory === null ? null : await countFiles(directory)
179
+ const git = directory === null ? null : await readGitState(directory)
180
+ rows.push({
181
+ name: skill.name,
182
+ description: skill.description ?? null,
183
+ whenToUse: skill.whenToUse ?? null,
184
+ source: skill.source ?? null,
185
+ provider: skill.provider ?? null,
186
+ // A skill can be a single `<name>.md` file; then there is no directory to
187
+ // fingerprint and the panel says so instead of showing an empty tree.
188
+ directory,
189
+ resourceKind: kind,
190
+ fileCount: files === null ? null : files.files,
191
+ fileCountTruncated: files === null ? null : files.truncated,
192
+ git: git === null ? { managed: false, reason: 'This skill has no directory.', ...emptyGit() } : git,
193
+ invocable: {
194
+ model: skill.invocation?.modelInvocable ?? null,
195
+ user: skill.invocation?.userInvocable ?? null,
196
+ },
197
+ })
198
+ }
199
+ return {
200
+ available: true,
201
+ reason: null,
202
+ provider: rows.length > 0 ? rows[0].provider : null,
203
+ complete: snapshot?.complete ?? null,
204
+ skills: rows.sort((left, right) => left.name.localeCompare(right.name)),
205
+ }
206
+ }
207
+
208
+ function emptyGit() {
209
+ return { root: null, revision: null, remote: null, subpath: null, dirty: null, changes: null }
210
+ }
211
+
212
+ /**
213
+ * Copy one skill directory into the snapshot store and prove the copy matches.
214
+ *
215
+ * @param {object} input
216
+ * @param {string} input.dshHome
217
+ * @param {string} input.profileId
218
+ * @param {string} input.name
219
+ * @param {string} input.directory
220
+ * @param {object} [input.git]
221
+ * @returns {Promise<{ path: string, manifest: object }>}
222
+ */
223
+ export async function snapshotSkill(input) {
224
+ const { dshHome, profileId, name, directory, git, reason } = input
225
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
226
+ const root = join(dshHome, 'version-manager', 'skills', profileId, name)
227
+ const directoryCopy = join(root, `${stamp}-files`)
228
+ await mkdir(root, { recursive: true })
229
+
230
+ const before = await fingerprintTree(directory)
231
+ if (before === null) throw new Error(`The skill directory disappeared: ${directory}`)
232
+ await cp(directory, directoryCopy, { recursive: true, dereference: false, force: false, errorOnExist: true })
233
+ const after = await fingerprintTree(directoryCopy)
234
+ if (after === null || after.digest !== before.digest || after.files !== before.files) {
235
+ throw new Error('The copied skill does not match what was read, so the snapshot was discarded.')
236
+ }
237
+
238
+ const manifest = {
239
+ schemaVersion: 1,
240
+ kind: 'skill',
241
+ takenAt: new Date().toISOString(),
242
+ profile: { id: profileId },
243
+ skill: {
244
+ name,
245
+ directory,
246
+ fileCount: before.files,
247
+ bytes: before.bytes,
248
+ digest: before.digest,
249
+ },
250
+ git: git ?? null,
251
+ // `before-restore` marks the copies this plugin takes of a directory it is
252
+ // about to replace, so an undo candidate is never mistaken for a baseline
253
+ // the user chose.
254
+ reason: typeof reason === 'string' ? reason : 'manual',
255
+ copy: relative(root, directoryCopy).split('\\').join('/'),
256
+ // Not a version: skills carry no version field, so a snapshot records the
257
+ // bytes and the checkout revision and nothing else.
258
+ note: 'A skill has no version field; this snapshot records its files and Git revision.',
259
+ }
260
+ const manifestPath = join(root, `${stamp}.json`)
261
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, { encoding: 'utf8', flag: 'wx' })
262
+ return { path: manifestPath, manifest }
263
+ }
264
+
265
+ /**
266
+ * List previous skill snapshots for one skill.
267
+ *
268
+ * @param {string} dshHome
269
+ * @param {string} profileId
270
+ * @param {string} name
271
+ */
272
+ export async function listSkillSnapshots(dshHome, profileId, name) {
273
+ const root = join(dshHome, 'version-manager', 'skills', profileId, name)
274
+ let entries
275
+ try {
276
+ entries = await readdir(root)
277
+ } catch {
278
+ return []
279
+ }
280
+ const found = []
281
+ for (const entry of entries) {
282
+ if (!entry.endsWith('.json')) continue
283
+ try {
284
+ const text = await readFile(join(root, entry), 'utf8')
285
+ const manifest = JSON.parse(text)
286
+ found.push({
287
+ file: entry,
288
+ takenAt: manifest.takenAt ?? null,
289
+ reason: manifest.reason ?? null,
290
+ digest: manifest.skill?.digest ?? null,
291
+ fileCount: manifest.skill?.fileCount ?? null,
292
+ revision: manifest.git?.revision ?? null,
293
+ })
294
+ } catch {
295
+ found.push({ file: entry, takenAt: null, reason: null, digest: null, fileCount: null, revision: null, unreadable: true })
296
+ }
297
+ }
298
+ return found.sort((left, right) => String(right.takenAt ?? '').localeCompare(String(left.takenAt ?? '')))
299
+ }
300
+
301
+ /**
302
+ * Check that a skill directory is still the one a snapshot described.
303
+ *
304
+ * @param {string} directory
305
+ * @param {string} digest
306
+ */
307
+ export async function skillUnchanged(directory, digest) {
308
+ const current = await fingerprintTree(directory)
309
+ if (current === null) return { same: false, reason: 'The skill directory is gone.' }
310
+ if (current.digest !== digest) return { same: false, reason: 'The skill files changed since the snapshot.' }
311
+ return { same: true, reason: null }
312
+ }
313
+
314
+ /**
315
+ * Report whether a directory exists, for callers that need to distinguish
316
+ * "no such skill" from "exists but unreadable".
317
+ *
318
+ * @param {string} path
319
+ */
320
+ export async function directoryState(path) {
321
+ try {
322
+ const info = await stat(path)
323
+ return info.isDirectory() ? 'directory' : 'not-a-directory'
324
+ } catch {
325
+ return 'missing'
326
+ }
327
+ }