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,1133 @@
1
+ /**
2
+ * Skills whose content comes from a Git tree the user named.
3
+ *
4
+ * A Skill is a directory with no version field, so "update this Skill" has no
5
+ * meaning until someone says where its bytes should come from. This module is
6
+ * that statement, and nothing more:
7
+ *
8
+ * - the user registers a name, a remote and the exact subpath inside it;
9
+ * - the plugin keeps its own bare cache of that remote under its own storage,
10
+ * and runs every Git command with `--git-dir <cache>`. It never runs a Git
11
+ * command inside the Skill directory, so the user's checkout — branch,
12
+ * index and worktree — is not something this plugin can touch;
13
+ * - an update exports the tree of a commit into a sibling staging directory,
14
+ * fingerprints it, and only then swaps it in with two renames;
15
+ * - a Skill whose files no longer match the digest recorded at the last apply
16
+ * has local modifications, and it is refused rather than overwritten.
17
+ *
18
+ * What it deliberately refuses to do: guess a remote, fetch into a repository
19
+ * the user owns, write anywhere but the registered directory, or claim that a
20
+ * Skill has a version. Nothing here runs `checkout`, `reset`, `clean` or any
21
+ * other command that changes a working tree.
22
+ *
23
+ * @module dsh-version-manager/lib/host/git-skill
24
+ */
25
+
26
+ import { execFile } from 'node:child_process'
27
+ import { randomUUID } from 'node:crypto'
28
+ import { createHash } from 'node:crypto'
29
+ import { chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from 'node:fs/promises'
30
+ import { dirname, join, relative, resolve, sep } from 'node:path'
31
+ import { tmpdir } from 'node:os'
32
+
33
+ import { fingerprintTree } from './snapshot-store.js'
34
+ import { isSystemPath } from './skill-restore.js'
35
+ import { readGitState, snapshotSkill } from './skills.js'
36
+
37
+ const GIT_TIMEOUT_MS = 20000
38
+ const MAX_HISTORY = 30
39
+
40
+ /**
41
+ * Run a bounded Git command that cannot prompt and cannot colour its output.
42
+ *
43
+ * @param {string[]} args
44
+ * @param {{ cwd?: string, timeout?: number }} [options]
45
+ * @returns {Promise<{ ok: boolean, stdout: string, stderr: string, code: string | null }>}
46
+ */
47
+ function runGit(args, options = {}) {
48
+ return new Promise((done) => {
49
+ execFile(
50
+ 'git',
51
+ args,
52
+ {
53
+ cwd: options.cwd,
54
+ timeout: options.timeout ?? GIT_TIMEOUT_MS,
55
+ windowsHide: true,
56
+ shell: false,
57
+ encoding: 'utf8',
58
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: 'echo', LC_ALL: 'C' },
59
+ maxBuffer: 8 * 1024 * 1024,
60
+ },
61
+ (error, stdout, stderr) => {
62
+ if (error) {
63
+ const code = error.code === 'ENOENT' ? 'git-not-found' : error.killed ? 'git-timeout' : 'git-failed'
64
+ done({ ok: false, stdout: String(stdout ?? '').trim(), stderr: String(stderr ?? '').trim().slice(0, 800), code })
65
+ return
66
+ }
67
+ done({ ok: true, stdout: String(stdout ?? '').trim(), stderr: '', code: null })
68
+ },
69
+ )
70
+ })
71
+ }
72
+
73
+ /**
74
+ * Run a bounded Git command whose stdout must stay bytes, not text.
75
+ *
76
+ * `git cat-file blob` returns file content, so decoding it would corrupt every
77
+ * non-UTF-8 file in a Skill. This variant keeps the buffer.
78
+ *
79
+ * @param {string[]} args
80
+ * @returns {Promise<{ ok: boolean, stdout: Buffer, stderr: string, code: string | null }>}
81
+ */
82
+ function runGitBytes(args) {
83
+ return new Promise((done) => {
84
+ execFile(
85
+ 'git',
86
+ args,
87
+ {
88
+ timeout: GIT_TIMEOUT_MS,
89
+ windowsHide: true,
90
+ shell: false,
91
+ encoding: 'buffer',
92
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: 'echo', LC_ALL: 'C' },
93
+ maxBuffer: 64 * 1024 * 1024,
94
+ },
95
+ (error, stdout, stderr) => {
96
+ if (error) {
97
+ const code = error.code === 'ENOENT' ? 'git-not-found' : error.killed ? 'git-timeout' : 'git-failed'
98
+ done({
99
+ ok: false,
100
+ stdout: Buffer.alloc(0),
101
+ stderr: String(stderr ?? '').trim().slice(0, 800),
102
+ code,
103
+ })
104
+ return
105
+ }
106
+ done({ ok: true, stdout: stdout, stderr: '', code: null })
107
+ },
108
+ )
109
+ })
110
+ }
111
+
112
+ /**
113
+ * Where the registry for one profile lives.
114
+ *
115
+ * @param {string} dshHome
116
+ * @param {string} profileId
117
+ * @returns {string}
118
+ */
119
+ function registryPath(dshHome, profileId) {
120
+ return join(dshHome, 'version-manager', 'git-skills', `${profileId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`)
121
+ }
122
+
123
+ /**
124
+ * A stable cache directory name for a remote.
125
+ *
126
+ * The name is derived from the remote so two Skills from one repository share
127
+ * one cache, and so the directory never contains a URL that could be mistaken
128
+ * for something to execute.
129
+ *
130
+ * @param {string} dshHome
131
+ * @param {string} remote
132
+ * @returns {string}
133
+ */
134
+ function cachePath(dshHome, remote) {
135
+ const digest = createHash('sha256').update(remote).digest('hex').slice(0, 32)
136
+ return join(dshHome, 'version-manager', 'git-cache', `${digest}.git`)
137
+ }
138
+
139
+ /**
140
+ * Read the registered Skills for a profile.
141
+ *
142
+ * A missing or unreadable registry is an empty registry: this file is a record
143
+ * of what the user asked for, and guessing entries would be worse than having
144
+ * none.
145
+ *
146
+ * @param {string} dshHome
147
+ * @param {string} profileId
148
+ * @returns {Promise<Array<object>>}
149
+ */
150
+ export async function readRegistry(dshHome, profileId) {
151
+ let text
152
+ try {
153
+ text = await readFile(registryPath(dshHome, profileId), 'utf8')
154
+ } catch {
155
+ return []
156
+ }
157
+ try {
158
+ const parsed = JSON.parse(text)
159
+ return Array.isArray(parsed?.skills) ? parsed.skills : []
160
+ } catch {
161
+ return []
162
+ }
163
+ }
164
+
165
+ /**
166
+ * Write the registry atomically.
167
+ *
168
+ * @param {string} dshHome
169
+ * @param {string} profileId
170
+ * @param {Array<object>} skills
171
+ * @returns {Promise<void>}
172
+ */
173
+ async function writeRegistry(dshHome, profileId, skills) {
174
+ const path = registryPath(dshHome, profileId)
175
+ await mkdir(dirname(path), { recursive: true })
176
+ const body = { schemaVersion: 1, updatedAt: new Date().toISOString(), skills }
177
+ const temporary = `${path}.${process.pid}.${Date.now()}.tmp`
178
+ await writeFile(temporary, `${JSON.stringify(body, null, 2)}\n`, 'utf8')
179
+ await rename(temporary, path)
180
+ }
181
+
182
+ /**
183
+ * Which remotes this module is willing to fetch from.
184
+ *
185
+ * A local path is accepted because a Skill may be authored on the same machine
186
+ * and tested from a directory; anything else has to name its transport, so a
187
+ * typo cannot be interpreted as another kind of URL.
188
+ *
189
+ * @param {string} remote
190
+ * @returns {boolean}
191
+ */
192
+ export function isFetchableRemote(remote) {
193
+ if (typeof remote !== 'string' || remote.trim() === '') return false
194
+ const value = remote.trim()
195
+ if (/^https?:\/\/[^\s]+$/i.test(value)) return true
196
+ if (/^ssh:\/\/[^\s]+$/i.test(value)) return true
197
+ if (/^git@[^\s:]+:[^\s]+$/.test(value)) return true
198
+ if (/^file:\/\/[^\s]+$/i.test(value)) return true
199
+ // A plain absolute path is a local repository; it must still look like one.
200
+ if (/^[A-Za-z]:[\\/]/.test(value) || value.startsWith('/')) return true
201
+ return false
202
+ }
203
+
204
+ /**
205
+ * Normalise the subpath a Skill occupies inside its repository.
206
+ *
207
+ * `''` means the repository root is the Skill. Anything that escapes the
208
+ * repository is rejected here, before it reaches a staging directory.
209
+ *
210
+ * @param {string} subpath
211
+ * @returns {string | null} the normalised subpath, or null when it is unsafe
212
+ */
213
+ export function normaliseSubpath(subpath) {
214
+ if (subpath === undefined || subpath === null || subpath === '') return ''
215
+ if (typeof subpath !== 'string') return null
216
+ const value = subpath.trim().replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '')
217
+ if (value === '') return ''
218
+ if (value.startsWith('/')) return null
219
+ const parts = value.split('/')
220
+ if (parts.some((part) => part === '..' || part === '.' || part === '')) return null
221
+ if (parts.some((part) => part === '.git')) return null
222
+ return value
223
+ }
224
+
225
+ /**
226
+ * Why a registered entry cannot be updated right now, or null.
227
+ *
228
+ * @param {object} entry
229
+ * @param {{ digest: string | null, exists: boolean, inCheckout?: boolean }} current
230
+ * @returns {string | null}
231
+ */
232
+ export function gitUpdateRefusal(entry, current) {
233
+ if (!entry || typeof entry.directory !== 'string' || entry.directory === '') return 'no-directory'
234
+ if (isSystemPath(entry.directory)) return 'system-skill'
235
+ if (!isFetchableRemote(entry.remote)) return 'unsupported-remote'
236
+ if (entry.subpath === null) return 'bad-subpath'
237
+ // A directory that is itself part of a checkout belongs to that repository's
238
+ // working tree. Rewriting it would silently dirty someone else's branch, so
239
+ // this plugin manages deployed copies and leaves checkouts to Git.
240
+ if (current.inCheckout === true) return 'inside-git-checkout'
241
+ if (current.exists === false) return null
242
+ if (entry.populated === false) {
243
+ // The registration was made against an empty directory and nothing has been
244
+ // written yet, so there is no baseline to compare against. The only thing
245
+ // to protect is the directory staying empty: anything appearing there was
246
+ // put there by something else, and the first apply would delete it.
247
+ if ((current.files ?? 0) > 0) return 'local-modifications'
248
+ return null
249
+ }
250
+ if (current.digest !== null && entry.baselineDigest !== null && current.digest !== entry.baselineDigest) {
251
+ // The files on disk are not the ones this plugin last wrote, so something
252
+ // else edited them. Replacing that is a data loss, not an update.
253
+ return 'local-modifications'
254
+ }
255
+ return null
256
+ }
257
+
258
+ /**
259
+ * Whether a restore may write into this directory.
260
+ *
261
+ * Restore is the way back, and it takes a snapshot before it writes, so local
262
+ * edits are not by themselves a reason to refuse: refusing here would strand a
263
+ * user whose directory was edited by hand in a state where neither an update
264
+ * nor a restore is possible. What still has to hold is that the directory is the
265
+ * one this plugin is allowed to write at all (not a checkout, not a system
266
+ * Skill, not a source it cannot read), and that it is not something it has never
267
+ * populated -- restoring into a non-empty directory it did not write would
268
+ * delete files it has no record of.
269
+ *
270
+ * @param {object} entry
271
+ * @param {{ exists: boolean, digest: string | null, files: number | null, inCheckout: boolean }} current
272
+ * @returns {string | null}
273
+ */
274
+ export function gitRestoreRefusal(entry, current) {
275
+ if (!entry || typeof entry.directory !== 'string' || entry.directory === '') return 'no-directory'
276
+ if (isSystemPath(entry.directory)) return 'system-skill'
277
+ if (!isFetchableRemote(entry.remote)) return 'unsupported-remote'
278
+ if (entry.subpath === null) return 'bad-subpath'
279
+ if (current.inCheckout === true) return 'inside-git-checkout'
280
+ if (current.exists === false) return null
281
+ if (entry.populated === false && (current.files ?? 0) > 0) {
282
+ // Never written by this plugin and not empty now: those files belong to
283
+ // something else, and a restore would replace them.
284
+ return 'local-modifications'
285
+ }
286
+ return null
287
+ }
288
+
289
+ /**
290
+ * Describe the directory a registration points at, once.
291
+ *
292
+ * @param {string} directory
293
+ * @returns {Promise<{ exists: boolean, digest: string | null, files: number | null, inCheckout: boolean }>}
294
+ */
295
+ export async function inspectTarget(directory) {
296
+ const fingerprint = await fingerprintTree(directory).catch(() => null)
297
+ if (fingerprint === null) return { exists: false, digest: null, files: null, inCheckout: false }
298
+ const git = await readGitState(directory)
299
+ return { exists: true, digest: fingerprint.digest, files: fingerprint.files, inCheckout: git.managed === true }
300
+ }
301
+
302
+ /**
303
+ * Make sure a bare cache exists for a remote.
304
+ *
305
+ * @param {string} dshHome
306
+ * @param {string} remote
307
+ * @returns {Promise<{ path: string, created: boolean }>}
308
+ */
309
+ async function ensureCache(dshHome, remote) {
310
+ const path = cachePath(dshHome, remote)
311
+ try {
312
+ const info = await stat(join(path, 'HEAD'))
313
+ if (info.isFile()) return { path, created: false }
314
+ } catch {
315
+ // fall through and create it
316
+ }
317
+ await mkdir(path, { recursive: true })
318
+ const init = await runGit(['init', '--bare', '--quiet', path])
319
+ if (!init.ok) throw new Error(`The Git cache could not be created: ${init.stderr || init.code}`)
320
+ return { path, created: true }
321
+ }
322
+
323
+ /**
324
+ * Fetch one remote ref into the cache and report the commit it resolved to.
325
+ *
326
+ * The fetch happens against the cache, never against a repository the user
327
+ * owns, and it writes only remote-tracking state — no branch, index or working
328
+ * tree is involved.
329
+ *
330
+ * @param {object} input
331
+ * @param {string} input.dshHome
332
+ * @param {string} input.remote
333
+ * @param {string} [input.ref]
334
+ * @returns {Promise<{ ok: boolean, reason: string | null, cache: string | null,
335
+ * revision: string | null, subject: string | null, message: string | null }>}
336
+ */
337
+ export async function fetchRevision(input) {
338
+ const { dshHome, remote, ref = 'HEAD' } = input
339
+ if (!isFetchableRemote(remote)) {
340
+ return { ok: false, reason: 'unsupported-remote', cache: null, revision: null, subject: null, message: null }
341
+ }
342
+ let cache
343
+ try {
344
+ cache = (await ensureCache(dshHome, remote)).path
345
+ } catch (error) {
346
+ return {
347
+ ok: false,
348
+ reason: 'cache-unavailable',
349
+ cache: null,
350
+ revision: null,
351
+ subject: null,
352
+ message: error instanceof Error ? error.message : String(error),
353
+ }
354
+ }
355
+ const fetched = await runGit(['--git-dir', cache, 'fetch', '--quiet', '--no-tags', remote, ref])
356
+ if (!fetched.ok) {
357
+ return {
358
+ ok: false,
359
+ reason: fetched.code === 'git-not-found' ? 'git-not-found' : 'fetch-failed',
360
+ cache,
361
+ revision: null,
362
+ subject: null,
363
+ message: fetched.stderr || null,
364
+ }
365
+ }
366
+ const resolved = await runGit(['--git-dir', cache, 'rev-parse', 'FETCH_HEAD^{commit}'])
367
+ if (!resolved.ok) {
368
+ return { ok: false, reason: 'ref-unresolved', cache, revision: null, subject: null, message: resolved.stderr || null }
369
+ }
370
+ const revision = resolved.stdout
371
+ const subject = await runGit(['--git-dir', cache, 'log', '-1', '--format=%s', revision])
372
+ return {
373
+ ok: true,
374
+ reason: null,
375
+ cache,
376
+ revision,
377
+ subject: subject.ok && subject.stdout !== '' ? subject.stdout : null,
378
+ message: null,
379
+ }
380
+ }
381
+
382
+ /**
383
+ * The files under `subpath` in one commit, as `git` reports a diff.
384
+ *
385
+ * @param {object} input
386
+ * @param {string} input.cache
387
+ * @param {string} input.fromRevision
388
+ * @param {string} input.toRevision
389
+ * @param {string} input.subpath
390
+ * @returns {Promise<Array<{ status: string, path: string }>>}
391
+ */
392
+ export async function diffRevisions(input) {
393
+ const { cache, fromRevision, toRevision, subpath } = input
394
+ const args = ['--git-dir', cache, 'diff', '--name-status', '--no-renames', fromRevision, toRevision]
395
+ if (subpath !== '') args.push('--', subpath)
396
+ const result = await runGit(args)
397
+ if (!result.ok) return []
398
+ const rows = []
399
+ for (const line of result.stdout.split('\n')) {
400
+ if (line.trim() === '') continue
401
+ const [status, ...rest] = line.split('\t')
402
+ const path = rest.join('\t')
403
+ if (path === '') continue
404
+ rows.push({ status: status === '' ? '?' : status.slice(0, 1), path })
405
+ }
406
+ return rows
407
+ }
408
+
409
+ /**
410
+ * Every blob under one subpath of one commit, read straight from the object
411
+ * database.
412
+ *
413
+ * This walks `git ls-tree` instead of asking `git archive` to produce a tar and
414
+ * hoping an external `tar` binary exists to unpack it. `tar` is not guaranteed
415
+ * on Windows, and on some Git-for-Windows builds `git -xf` is not a command at
416
+ * all. Reading the objects directly means the export depends on nothing but the
417
+ * `git` binary that is already required to fetch them.
418
+ *
419
+ * @param {object} input
420
+ * @param {string} input.cache
421
+ * @param {string} input.revision
422
+ * @param {string} input.subpath
423
+ * @param {string} input.into
424
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null,
425
+ * files: number | null }>}
426
+ */
427
+ export async function exportRevision(input) {
428
+ const { cache, revision, subpath, into } = input
429
+ const known = await runGit(['--git-dir', cache, 'cat-file', '-e', `${revision}^{commit}`])
430
+ if (!known.ok) {
431
+ return { ok: false, reason: 'revision-not-in-cache', message: null, files: null }
432
+ }
433
+
434
+ // `--full-tree` makes the paths relative to the repository root regardless of
435
+ // where Git was invoked, so they can be trimmed against `subpath` reliably.
436
+ const treeArgs = ['--git-dir', cache, 'ls-tree', '-r', '-z', '--full-tree', revision]
437
+ if (subpath !== '') treeArgs.push('--', subpath)
438
+ const listed = await runGitBytes(treeArgs)
439
+ if (!listed.ok) {
440
+ return { ok: false, reason: 'archive-failed', message: listed.stderr || null, files: null }
441
+ }
442
+
443
+ const prefix = subpath === '' ? '' : `${subpath}/`
444
+ const blobs = []
445
+ for (const record of listed.stdout.toString('utf8').split('\0')) {
446
+ if (record === '') continue
447
+ // "<mode> SP <type> SP <sha> TAB <path>"
448
+ const tab = record.indexOf('\t')
449
+ if (tab === -1) continue
450
+ const meta = record.slice(0, tab).split(' ')
451
+ const path = record.slice(tab + 1)
452
+ const [mode, type, sha] = meta
453
+ if (type !== 'blob') continue
454
+ if (prefix !== '' && !path.startsWith(prefix)) continue
455
+ const relativePath = prefix === '' ? path : path.slice(prefix.length)
456
+ if (relativePath === '') continue
457
+ blobs.push({ path, relativePath, mode, sha })
458
+ }
459
+ if (blobs.length === 0) {
460
+ // An empty directory cannot be represented in a tree, so "no blobs" means
461
+ // either the path is not there or it holds nothing this plugin can write.
462
+ // Either way it is not something to offer as an update.
463
+ return { ok: false, reason: 'subpath-missing', message: null, files: null }
464
+ }
465
+
466
+ const target = resolve(into)
467
+ for (const blob of blobs) {
468
+ const parts = blob.relativePath.split('/')
469
+ if (parts.some((part) => part === '' || part === '.' || part === '..')) {
470
+ // A tree entry that would escape the target is not written. Git cannot
471
+ // normally produce one, but this is the boundary that matters.
472
+ return { ok: false, reason: 'path-escapes-target', message: null, files: null }
473
+ }
474
+ if (blob.mode === '120000') {
475
+ // A symlink cannot be written on Windows without extra privileges, and
476
+ // writing its target as a regular file would silently change what the
477
+ // Skill is. A Skill made of links is refused rather than approximated.
478
+ return { ok: false, reason: 'unsupported-entry', message: `symlink: ${blob.relativePath}`, files: null }
479
+ }
480
+ if (blob.mode !== '100644' && blob.mode !== '100755') {
481
+ // Submodules and other tree types have no content to export.
482
+ return { ok: false, reason: 'unsupported-entry', message: `${blob.mode}: ${blob.relativePath}`, files: null }
483
+ }
484
+ const destination = join(target, ...parts)
485
+ const content = await runGitBytes(['--git-dir', cache, 'cat-file', 'blob', blob.sha])
486
+ if (!content.ok) {
487
+ return { ok: false, reason: 'blob-unreadable', message: content.stderr || null, files: null }
488
+ }
489
+ await mkdir(dirname(destination), { recursive: true })
490
+ // Bytes, not text: a Skill may ship an image, a font or a zip.
491
+ await writeFile(destination, content.stdout)
492
+ await chmod(destination, blob.mode === '100755' ? 0o755 : 0o644).catch(() => {})
493
+ }
494
+ return { ok: true, reason: null, message: null, files: blobs.length }
495
+ }
496
+
497
+ /**
498
+ * Replace a directory with a prepared one, leaving a way back.
499
+ *
500
+ * The replacement is assembled beside the target and swapped in with two
501
+ * renames on the same volume. The old directory is parked, not deleted, until
502
+ * the new one has been verified.
503
+ *
504
+ * @param {object} input
505
+ * @param {string} input.target
506
+ * @param {(staging: string) => Promise<{ ok: boolean, reason?: string, message?: string }>} input.prepare
507
+ * @param {string} [input.expectedDigest]
508
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null,
509
+ * evidence: object | null }>}
510
+ */
511
+ export async function replaceDirectory(input) {
512
+ const { target, prepare, expectedDigest } = input
513
+ const parent = dirname(target)
514
+ const base = target.slice(parent.length).replace(/^[\\/]+/, '')
515
+ const suffix = randomUUID().slice(0, 8)
516
+ const staging = join(parent, `.${base}.version-manager git-${suffix}`)
517
+ const parked = join(parent, `.${base}.version-manager git-old-${suffix}`)
518
+ let existed = false
519
+ try {
520
+ const info = await stat(target)
521
+ existed = info.isDirectory()
522
+ if (!existed) return { ok: false, reason: 'target-not-a-directory', message: null, evidence: null }
523
+ } catch {
524
+ existed = false
525
+ }
526
+
527
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
528
+ const prepared = await prepare(staging)
529
+ if (!prepared.ok) {
530
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
531
+ return { ok: false, reason: prepared.reason ?? 'prepare-failed', message: prepared.message ?? null, evidence: null }
532
+ }
533
+ const staged = await fingerprintTree(staging)
534
+ if (staged === null || (expectedDigest !== undefined && staged.digest !== expectedDigest)) {
535
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
536
+ return { ok: false, reason: 'staged-copy-corrupt', message: null, evidence: { stagedDigest: staged?.digest ?? null } }
537
+ }
538
+
539
+ let parkedOk = false
540
+ try {
541
+ if (existed) {
542
+ await rename(target, parked)
543
+ parkedOk = true
544
+ }
545
+ await rename(staging, target)
546
+ } catch (error) {
547
+ if (parkedOk) await rename(parked, target).catch(() => {})
548
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
549
+ return {
550
+ ok: false,
551
+ reason: 'swap-failed',
552
+ message: error instanceof Error ? error.message : String(error),
553
+ evidence: { parked: parkedOk ? parked : null },
554
+ }
555
+ }
556
+
557
+ const placed = await fingerprintTree(target)
558
+ if (placed === null || placed.digest !== staged.digest) {
559
+ return {
560
+ ok: false,
561
+ reason: 'verification-failed',
562
+ message: null,
563
+ evidence: { parked: parkedOk ? parked : null, placedDigest: placed?.digest ?? null },
564
+ }
565
+ }
566
+ if (parkedOk) await rm(parked, { recursive: true, force: true }).catch(() => {})
567
+
568
+ return {
569
+ ok: true,
570
+ reason: null,
571
+ message: null,
572
+ evidence: {
573
+ digest: placed.digest,
574
+ files: placed.files,
575
+ bytes: placed.bytes,
576
+ created: existed === false,
577
+ },
578
+ }
579
+ }
580
+
581
+ /**
582
+ * The digest of one commit's subtree, computed by exporting it out of the cache.
583
+ *
584
+ * This is how a registration checks that its claimed baseline is real: the
585
+ * directory on disk must already hold exactly these bytes, or the claim is a
586
+ * guess and guessing is what this module refuses to do.
587
+ *
588
+ * @param {{ cache: string, revision: string, subpath: string }} input
589
+ * @returns {Promise<{ ok: boolean, reason: string | null, digest: string | null, files: number | null }>}
590
+ */
591
+ export async function treeDigest(input) {
592
+ const { cache, revision, subpath } = input
593
+ const scratch = await mkdtemp(join(tmpdir(), 'dsh-vm-tree-'))
594
+ try {
595
+ const exported = await exportRevision({ cache, revision, subpath, into: join(scratch, 'tree') })
596
+ if (!exported.ok) return { ok: false, reason: exported.reason, digest: null, files: null }
597
+ const fingerprint = await fingerprintTree(join(scratch, 'tree'))
598
+ if (fingerprint === null) return { ok: false, reason: 'subpath-missing', digest: null, files: null }
599
+ return { ok: true, reason: null, digest: fingerprint.digest, files: fingerprint.files }
600
+ } finally {
601
+ await rm(scratch, { recursive: true, force: true }).catch(() => {})
602
+ }
603
+ }
604
+
605
+ /**
606
+ * Register one Skill as coming from a Git tree.
607
+ *
608
+ * Registration is a claim about intent, so it does not touch the Skill
609
+ * directory: it records where future content should come from and pins the
610
+ * revision the directory currently corresponds to.
611
+ *
612
+ * @param {object} input
613
+ * @param {string} input.dshHome
614
+ * @param {string} input.profileId
615
+ * @param {string} input.name
616
+ * @param {string} input.remote
617
+ * @param {string} [input.subpath]
618
+ * @param {string} [input.ref]
619
+ * @param {string | null} [input.directory]
620
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null, entry: object | null }>}
621
+ */
622
+ export async function registerGitSkill(input) {
623
+ const { dshHome, profileId, name, remote, subpath, ref = 'HEAD', directory = null } = input
624
+ if (typeof name !== 'string' || name.trim() === '') {
625
+ return { ok: false, reason: 'missing-name', message: null, entry: null }
626
+ }
627
+ if (!isFetchableRemote(remote)) {
628
+ return { ok: false, reason: 'unsupported-remote', message: null, entry: null }
629
+ }
630
+ const normalised = normaliseSubpath(subpath)
631
+ if (normalised === null) return { ok: false, reason: 'bad-subpath', message: null, entry: null }
632
+ if (directory === null) {
633
+ return { ok: false, reason: 'no-directory', message: null, entry: null }
634
+ }
635
+ if (isSystemPath(directory)) return { ok: false, reason: 'system-skill', message: null, entry: null }
636
+
637
+ const registry = await readRegistry(dshHome, profileId)
638
+ const existing = registry.find((entry) => entry.name === name)
639
+ if (existing !== undefined && (existing.remote !== remote.trim() || existing.subpath !== normalised)) {
640
+ // Re-pointing a Skill at another repository silently would make its history
641
+ // fictional, so the caller has to remove the old registration first. This is
642
+ // checked before any fetch: a refusal should not cost a network round trip.
643
+ return { ok: false, reason: 'already-registered', message: null, entry: null }
644
+ }
645
+
646
+ const pinned = await fetchRevision({ dshHome, remote, ref })
647
+ if (!pinned.ok) {
648
+ return { ok: false, reason: pinned.reason, message: pinned.message, entry: null }
649
+ }
650
+
651
+ const current = await inspectTarget(directory)
652
+ const expected = await treeDigest({ cache: pinned.cache, revision: pinned.revision, subpath: normalised })
653
+ if (!expected.ok) {
654
+ return { ok: false, reason: expected.reason, message: null, entry: null }
655
+ }
656
+ // The baseline is the tree the registration names, not whatever happened to be
657
+ // on disk: "the revision this directory corresponds to" is only a fact if the
658
+ // bytes agree. A directory that already holds exactly that tree is populated;
659
+ // an empty one is a placeholder waiting for its first update.
660
+ const populated = current.digest === expected.digest
661
+ if (current.exists && current.digest !== expected.digest && (current.files ?? 0) > 0) {
662
+ // Something is there and it is not this revision. Guessing which commit it
663
+ // came from would make every later refusal meaningless.
664
+ return { ok: false, reason: 'baseline-unknown', message: null, entry: null }
665
+ }
666
+
667
+ const entry = {
668
+ name,
669
+ remote: remote.trim(),
670
+ subpath: normalised,
671
+ ref,
672
+ directory: resolve(directory),
673
+ revision: pinned.revision,
674
+ revisionSubject: pinned.subject,
675
+ baselineDigest: expected.digest,
676
+ files: expected.files,
677
+ // `false` means the directory has never been written by this plugin, so the
678
+ // next update fills it instead of reporting nothing to apply.
679
+ populated,
680
+ registeredAt: existing?.registeredAt ?? new Date().toISOString(),
681
+ updatedAt: existing?.updatedAt ?? null,
682
+ history: Array.isArray(existing?.history) ? existing.history : [],
683
+ }
684
+ const next = [...registry.filter((row) => row.name !== name), entry]
685
+ await writeRegistry(dshHome, profileId, next)
686
+ return { ok: true, reason: null, message: null, entry }
687
+ }
688
+
689
+ /**
690
+ * Forget one registration. The files are left exactly as they are.
691
+ *
692
+ * @param {object} input
693
+ * @param {string} input.dshHome
694
+ * @param {string} input.profileId
695
+ * @param {string} input.name
696
+ * @returns {Promise<{ ok: boolean, reason: string | null }>}
697
+ */
698
+ export async function unregisterGitSkill(input) {
699
+ const { dshHome, profileId, name } = input
700
+ const registry = await readRegistry(dshHome, profileId)
701
+ const next = registry.filter((entry) => entry.name !== name)
702
+ if (next.length === registry.length) return { ok: false, reason: 'not-registered' }
703
+ await writeRegistry(dshHome, profileId, next)
704
+ return { ok: true, reason: null }
705
+ }
706
+
707
+ /**
708
+ * Everything an update would change, without changing it.
709
+ *
710
+ * @param {object} input
711
+ * @param {string} input.dshHome
712
+ * @param {string} input.profileId
713
+ * @param {string} input.name
714
+ * @param {string} [input.ref]
715
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null, detail: object | null }>}
716
+ */
717
+ export async function previewGitUpdate(input) {
718
+ const { dshHome, profileId, name, ref } = input
719
+ const registry = await readRegistry(dshHome, profileId)
720
+ const entry = registry.find((row) => row.name === name)
721
+ if (entry === undefined) return { ok: false, reason: 'not-registered', message: null, detail: null }
722
+
723
+ const current = await inspectTarget(entry.directory)
724
+ const refusal = gitUpdateRefusal(entry, current)
725
+ if (refusal !== null) return { ok: false, reason: refusal, message: null, detail: null }
726
+
727
+ const target = await fetchRevision({ dshHome, remote: entry.remote, ref: ref ?? entry.ref ?? 'HEAD' })
728
+ if (!target.ok) {
729
+ return { ok: false, reason: target.reason, message: target.message, detail: null }
730
+ }
731
+ // A directory this plugin has never written holds no revision at all, so
732
+ // "already at that revision" would be false comfort: the tree still has to be
733
+ // exported once. `populated === false` is the record that says so.
734
+ const populated = entry.populated !== false
735
+ const changes =
736
+ target.revision === entry.revision
737
+ ? []
738
+ : await diffRevisions({
739
+ cache: target.cache,
740
+ fromRevision: entry.revision,
741
+ toRevision: target.revision,
742
+ subpath: entry.subpath,
743
+ })
744
+ return {
745
+ ok: true,
746
+ reason: null,
747
+ message: null,
748
+ detail: {
749
+ name,
750
+ directory: entry.directory,
751
+ remote: entry.remote,
752
+ subpath: entry.subpath,
753
+ from: { revision: entry.revision, subject: entry.revisionSubject ?? null },
754
+ to: { revision: target.revision, subject: target.subject },
755
+ populated,
756
+ // `alreadyAtRevision` is evidence, not an error: the panel says "nothing
757
+ // to apply" instead of offering a no-op update.
758
+ alreadyAtRevision: populated && target.revision === entry.revision,
759
+ changes,
760
+ changeCount: changes.length,
761
+ localFiles: { digest: current.digest, files: current.files, baselineDigest: entry.baselineDigest },
762
+ },
763
+ }
764
+ }
765
+
766
+ /**
767
+ * Apply the fetched revision to the Skill directory.
768
+ *
769
+ * @param {object} input
770
+ * @param {string} input.dshHome
771
+ * @param {string} input.profileId
772
+ * @param {string} input.name
773
+ * @param {string} [input.ref]
774
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null,
775
+ * evidence: object | null, fromRevision: string | null, toRevision: string | null,
776
+ * snapshot: object | null }>}
777
+ */
778
+ export async function applyGitUpdate(input) {
779
+ const { dshHome, profileId, name, ref } = input
780
+ const preview = await previewGitUpdate({ dshHome, profileId, name, ref })
781
+ if (!preview.ok) {
782
+ return {
783
+ ok: false,
784
+ reason: preview.reason,
785
+ message: preview.message,
786
+ evidence: null,
787
+ fromRevision: null,
788
+ toRevision: null,
789
+ snapshot: null,
790
+ }
791
+ }
792
+ const { detail } = preview
793
+ if (detail.alreadyAtRevision) {
794
+ return {
795
+ ok: false,
796
+ reason: 'already-at-revision',
797
+ message: null,
798
+ evidence: detail,
799
+ fromRevision: detail.from.revision,
800
+ toRevision: detail.to.revision,
801
+ snapshot: null,
802
+ }
803
+ }
804
+
805
+ const registry = await readRegistry(dshHome, profileId)
806
+ const entry = registry.find((row) => row.name === name)
807
+ if (entry === undefined) {
808
+ return { ok: false, reason: 'not-registered', message: null, evidence: null, fromRevision: null, toRevision: null, snapshot: null }
809
+ }
810
+
811
+ // Keep the bytes that are about to be replaced, so the update itself has a
812
+ // documented way back even after the directory has changed.
813
+ let snapshot = null
814
+ const exists = (await inspectTarget(entry.directory)).exists
815
+ if (exists) {
816
+ try {
817
+ const saved = await snapshotSkill({
818
+ dshHome,
819
+ profileId,
820
+ name,
821
+ directory: entry.directory,
822
+ git: {
823
+ managed: true,
824
+ reason: null,
825
+ root: entry.remote,
826
+ revision: entry.revision,
827
+ remote: entry.remote,
828
+ subpath: entry.subpath,
829
+ dirty: false,
830
+ changes: 0,
831
+ },
832
+ reason: `before git update to ${detail.to.revision.slice(0, 7)}`,
833
+ })
834
+ snapshot = { file: saved.path, digest: saved.manifest.skill.digest }
835
+ } catch (error) {
836
+ return {
837
+ ok: false,
838
+ reason: 'undo-snapshot-failed',
839
+ message: error instanceof Error ? error.message : String(error),
840
+ evidence: null,
841
+ fromRevision: entry.revision,
842
+ toRevision: detail.to.revision,
843
+ snapshot: null,
844
+ }
845
+ }
846
+ }
847
+
848
+ const cache = (await ensureCache(dshHome, entry.remote)).path
849
+ const applied = await replaceDirectory({
850
+ target: entry.directory,
851
+ prepare: async (staging) => exportRevision({ cache, revision: detail.to.revision, subpath: entry.subpath, into: staging }),
852
+ })
853
+ if (!applied.ok) {
854
+ return {
855
+ ok: false,
856
+ reason: applied.reason,
857
+ message: applied.message,
858
+ evidence: applied.evidence,
859
+ fromRevision: entry.revision,
860
+ toRevision: detail.to.revision,
861
+ snapshot,
862
+ }
863
+ }
864
+
865
+ const updated = {
866
+ ...entry,
867
+ revision: detail.to.revision,
868
+ revisionSubject: detail.to.subject,
869
+ baselineDigest: applied.evidence.digest,
870
+ files: applied.evidence.files,
871
+ // The tree on disk is now this revision's tree, so the record can say so.
872
+ populated: true,
873
+ updatedAt: new Date().toISOString(),
874
+ history: [
875
+ {
876
+ revision: detail.to.revision,
877
+ subject: detail.to.subject ?? null,
878
+ at: new Date().toISOString(),
879
+ reason: 'update',
880
+ previous: entry.revision,
881
+ },
882
+ ...(Array.isArray(entry.history) ? entry.history : []),
883
+ ].slice(0, MAX_HISTORY),
884
+ }
885
+ await writeRegistry(dshHome, profileId, [...registry.filter((row) => row.name !== name), updated])
886
+
887
+ return {
888
+ ok: true,
889
+ reason: null,
890
+ message: null,
891
+ evidence: applied.evidence,
892
+ fromRevision: entry.revision,
893
+ toRevision: detail.to.revision,
894
+ snapshot,
895
+ }
896
+ }
897
+
898
+ /**
899
+ * Put a Skill directory back to an earlier revision of its own Git tree.
900
+ *
901
+ * The bytes come from the plugin's cache, not from the user's repository, so
902
+ * no branch or worktree is consulted. When the cache no longer holds that
903
+ * commit the caller is told so and can restore a snapshot instead.
904
+ *
905
+ * @param {object} input
906
+ * @param {string} input.dshHome
907
+ * @param {string} input.profileId
908
+ * @param {string} input.name
909
+ * @param {string} input.revision
910
+ * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null,
911
+ * evidence: object | null, fromRevision: string | null, toRevision: string | null,
912
+ * snapshot: object | null }>}
913
+ */
914
+ export async function restoreGitRevision(input) {
915
+ const { dshHome, profileId, name, revision } = input
916
+ if (typeof revision !== 'string' || !/^[0-9a-f]{4,40}$/i.test(revision)) {
917
+ return { ok: false, reason: 'bad-revision', message: null, evidence: null, fromRevision: null, toRevision: null, snapshot: null }
918
+ }
919
+ const registry = await readRegistry(dshHome, profileId)
920
+ const entry = registry.find((row) => row.name === name)
921
+ if (entry === undefined) {
922
+ return { ok: false, reason: 'not-registered', message: null, evidence: null, fromRevision: null, toRevision: null, snapshot: null }
923
+ }
924
+ const current = await inspectTarget(entry.directory)
925
+ const refusal = gitRestoreRefusal(entry, current)
926
+ if (refusal !== null) {
927
+ return { ok: false, reason: refusal, message: null, evidence: null, fromRevision: entry.revision, toRevision: revision, snapshot: null }
928
+ }
929
+
930
+ const cache = (await ensureCache(dshHome, entry.remote)).path
931
+ const known = await runGit(['--git-dir', cache, 'cat-file', '-e', `${revision}^{commit}`])
932
+ if (!known.ok) {
933
+ return {
934
+ ok: false,
935
+ reason: 'revision-not-in-cache',
936
+ message: null,
937
+ evidence: null,
938
+ fromRevision: entry.revision,
939
+ toRevision: revision,
940
+ snapshot: null,
941
+ }
942
+ }
943
+ const resolved = await runGit(['--git-dir', cache, 'rev-parse', `${revision}^{commit}`])
944
+ const full = resolved.ok ? resolved.stdout : revision
945
+ const subject = await runGit(['--git-dir', cache, 'log', '-1', '--format=%s', full])
946
+
947
+ let snapshot = null
948
+ if (current.exists) {
949
+ try {
950
+ const saved = await snapshotSkill({
951
+ dshHome,
952
+ profileId,
953
+ name,
954
+ directory: entry.directory,
955
+ git: null,
956
+ reason: `before git restore to ${full.slice(0, 7)}`,
957
+ })
958
+ snapshot = { file: saved.path, digest: saved.manifest.skill.digest }
959
+ } catch (error) {
960
+ return {
961
+ ok: false,
962
+ reason: 'undo-snapshot-failed',
963
+ message: error instanceof Error ? error.message : String(error),
964
+ evidence: null,
965
+ fromRevision: entry.revision,
966
+ toRevision: full,
967
+ snapshot: null,
968
+ }
969
+ }
970
+ }
971
+
972
+ const applied = await replaceDirectory({
973
+ target: entry.directory,
974
+ prepare: async (staging) => exportRevision({ cache, revision: full, subpath: entry.subpath, into: staging }),
975
+ })
976
+ if (!applied.ok) {
977
+ return {
978
+ ok: false,
979
+ reason: applied.reason,
980
+ message: applied.message,
981
+ evidence: applied.evidence,
982
+ fromRevision: entry.revision,
983
+ toRevision: full,
984
+ snapshot,
985
+ }
986
+ }
987
+
988
+ const updated = {
989
+ ...entry,
990
+ revision: full,
991
+ revisionSubject: subject.ok && subject.stdout !== '' ? subject.stdout : null,
992
+ baselineDigest: applied.evidence.digest,
993
+ files: applied.evidence.files,
994
+ // Restoring writes a tree too, so the directory is populated afterwards.
995
+ populated: true,
996
+ updatedAt: new Date().toISOString(),
997
+ history: [
998
+ {
999
+ revision: full,
1000
+ subject: subject.ok && subject.stdout !== '' ? subject.stdout : null,
1001
+ at: new Date().toISOString(),
1002
+ reason: 'restore',
1003
+ previous: entry.revision,
1004
+ },
1005
+ ...(Array.isArray(entry.history) ? entry.history : []),
1006
+ ].slice(0, MAX_HISTORY),
1007
+ }
1008
+ await writeRegistry(dshHome, profileId, [...registry.filter((row) => row.name !== name), updated])
1009
+
1010
+ return {
1011
+ ok: true,
1012
+ reason: null,
1013
+ message: null,
1014
+ evidence: applied.evidence,
1015
+ fromRevision: entry.revision,
1016
+ toRevision: full,
1017
+ snapshot,
1018
+ }
1019
+ }
1020
+
1021
+ /**
1022
+ * A directory's path relative to a skill root, for display and assertions.
1023
+ *
1024
+ * @param {string} root
1025
+ * @param {string} path
1026
+ * @returns {string}
1027
+ */
1028
+ export function relativeTo(root, path) {
1029
+ return relative(root, path).split(sep).join('/')
1030
+ }
1031
+
1032
+ /**
1033
+ * The revisions this plugin has recorded for one Skill, newest first.
1034
+ *
1035
+ * @param {object} entry
1036
+ * @returns {Array<{ revision: string, subject: string | null, at: string | null, reason: string }>}
1037
+ */
1038
+ export function revisionHistory(entry) {
1039
+ if (!entry) return []
1040
+ const seen = new Set()
1041
+ const rows = []
1042
+ for (const item of Array.isArray(entry.history) ? entry.history : []) {
1043
+ if (typeof item?.revision !== 'string' || seen.has(item.revision)) continue
1044
+ seen.add(item.revision)
1045
+ rows.push({
1046
+ revision: item.revision,
1047
+ subject: item.subject ?? null,
1048
+ at: item.at ?? null,
1049
+ reason: item.reason ?? 'update',
1050
+ })
1051
+ }
1052
+ if (typeof entry.revision === 'string' && !seen.has(entry.revision)) {
1053
+ rows.unshift({ revision: entry.revision, subject: entry.revisionSubject ?? null, at: entry.updatedAt ?? null, reason: 'current' })
1054
+ }
1055
+ return rows
1056
+ }
1057
+
1058
+ /**
1059
+ * Entries whose registry row has no usable directory any more.
1060
+ *
1061
+ * @param {Array<object>} registry
1062
+ * @returns {Promise<Array<object>>}
1063
+ */
1064
+ export async function describeRegistry(registry) {
1065
+ const rows = []
1066
+ for (const entry of registry) {
1067
+ const current = await inspectTarget(entry.directory)
1068
+ const refusal = gitUpdateRefusal(entry, current)
1069
+ const restoreRefusal = gitRestoreRefusal(entry, current)
1070
+ rows.push({
1071
+ name: entry.name,
1072
+ remote: entry.remote,
1073
+ subpath: entry.subpath,
1074
+ ref: entry.ref,
1075
+ directory: entry.directory,
1076
+ revision: entry.revision,
1077
+ revisionSubject: entry.revisionSubject ?? null,
1078
+ registeredAt: entry.registeredAt ?? null,
1079
+ updatedAt: entry.updatedAt ?? null,
1080
+ baselineDigest: entry.baselineDigest ?? null,
1081
+ files: current.files,
1082
+ currentDigest: current.digest,
1083
+ inCheckout: current.inCheckout,
1084
+ // `false` means the registration was made against an empty directory and
1085
+ // the tree has not been written yet, so the panel offers a first apply
1086
+ // instead of saying the Skill is already at that revision.
1087
+ populated: entry.populated !== false,
1088
+ // Read off the refusal rather than compared again here. Two copies of the
1089
+ // same rule drift: this one used to call an empty, never-written directory
1090
+ // "modified" because its digest differs from the commit tree, while the
1091
+ // update path allowed it -- so the row warned about a refusal that would
1092
+ // not happen.
1093
+ localModifications: refusal === 'local-modifications',
1094
+ refusal,
1095
+ // Restore has its own, narrower rule: it snapshots before writing, so a
1096
+ // hand-edited directory is recoverable rather than blocked. Reported
1097
+ // separately so the panel can offer the way back while still refusing the
1098
+ // way forward.
1099
+ restoreRefusal,
1100
+ history: revisionHistory(entry),
1101
+ })
1102
+ }
1103
+ return rows
1104
+ }
1105
+
1106
+ /**
1107
+ * Whether a directory listing exists, used before offering to create one.
1108
+ *
1109
+ * @param {string} path
1110
+ * @returns {Promise<boolean>}
1111
+ */
1112
+ export async function directoryExists(path) {
1113
+ try {
1114
+ const info = await stat(path)
1115
+ return info.isDirectory()
1116
+ } catch {
1117
+ return false
1118
+ }
1119
+ }
1120
+
1121
+ /**
1122
+ * Read a directory's entries, or `[]`.
1123
+ *
1124
+ * @param {string} path
1125
+ * @returns {Promise<string[]>}
1126
+ */
1127
+ export async function entriesOf(path) {
1128
+ try {
1129
+ return await readdir(path)
1130
+ } catch {
1131
+ return []
1132
+ }
1133
+ }