dsh-version-manager 0.1.3 → 0.1.4

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/lib/client.js CHANGED
@@ -43,6 +43,12 @@ window.__ModuleLoader__.load({
43
43
  soft: 'rgba(128,128,128,0.10)',
44
44
  }
45
45
 
46
+ // The tab strip is one widget: left/right move between tabs, the ends wrap.
47
+ // Home and End are the convention for a strip, and skipping them is how a
48
+ // keyboard user gets stuck on the last tab. Keys only — the label comes
49
+ // from the active language, so it cannot live in a module constant.
50
+ const TABS = ['plugins', 'skills']
51
+
46
52
  const TEXT = {
47
53
  zh: {
48
54
  panel: '版本管理',
@@ -177,7 +183,10 @@ window.__ModuleLoader__.load({
177
183
  staleWarning: '这些数据来自上一次读取,可能已经过期',
178
184
  tabPlugins: '插件',
179
185
  tabSkills: 'Skill',
186
+ expandRow: '展开详情',
187
+ collapseRow: '收起详情',
180
188
  skillsTitle: 'Skill 目录',
189
+ refreshSkills: '刷新 Skill 目录',
181
190
  skillsSubtitle: '宿主实际扫描到的 Skill;快照记录文件指纹与 Git 版本,Skill 本身没有版本号',
182
191
  skillsUnavailable: '这个宿主进程没有 skills 服务,因此无法列出 Skill。',
183
192
  skillsEmpty: '没有发现 Skill。',
@@ -442,7 +451,10 @@ window.__ModuleLoader__.load({
442
451
  staleWarning: 'This data came from an earlier read and may be out of date',
443
452
  tabPlugins: 'Plugins',
444
453
  tabSkills: 'Skills',
454
+ expandRow: 'Show details',
455
+ collapseRow: 'Hide details',
445
456
  skillsTitle: 'Skill directories',
457
+ refreshSkills: 'Refresh the Skill catalog',
446
458
  skillsSubtitle:
447
459
  'The skills this host actually scanned; a snapshot records file fingerprints and a Git revision, because a skill has no version number',
448
460
  skillsUnavailable: 'This host process has no skills service, so skills cannot be listed.',
@@ -1203,6 +1215,10 @@ window.__ModuleLoader__.load({
1203
1215
  type: 'button',
1204
1216
  onClick: onToggle,
1205
1217
  'aria-expanded': expanded,
1218
+ // The visible label is the package name and the glyph is decoration.
1219
+ // Without this the button is announced as "▸ dsh-update-checker",
1220
+ // which is a triangle, not a state.
1221
+ 'aria-label': `${expanded ? t.collapseRow : t.expandRow}: ${row.targetId}`,
1206
1222
  style: {
1207
1223
  font: 'inherit',
1208
1224
  background: 'none',
@@ -1258,10 +1274,21 @@ window.__ModuleLoader__.load({
1258
1274
  onClick: loadVersions,
1259
1275
  disabled: !writable || versionsBusy,
1260
1276
  title: writable ? undefined : refusalLabel(row.updateRefusal, t) ?? '',
1277
+ // Every row renders the same words, so the label alone leaves
1278
+ // eight identical "检查更新" buttons in the accessibility tree.
1279
+ ariaLabel: `${t.checkVersions}: ${row.targetId}`,
1261
1280
  },
1262
1281
  versionsBusy ? t.checking : t.checkVersions,
1263
1282
  ),
1264
- h(Button, { onClick: takeSnapshot, disabled: snapshotBusy || row.loadState === 'failed' }, snapshotBusy ? t.snapshotting : t.takeSnapshot),
1283
+ h(
1284
+ Button,
1285
+ {
1286
+ onClick: takeSnapshot,
1287
+ disabled: snapshotBusy || row.loadState === 'failed',
1288
+ ariaLabel: `${t.takeSnapshot}: ${row.targetId}`,
1289
+ },
1290
+ snapshotBusy ? t.snapshotting : t.takeSnapshot,
1291
+ ),
1265
1292
  ),
1266
1293
  ),
1267
1294
  )
@@ -1624,7 +1651,11 @@ window.__ModuleLoader__.load({
1624
1651
  ? '—'
1625
1652
  : h(
1626
1653
  Button,
1627
- { onClick: () => setExpanded(!expanded), small: true },
1654
+ {
1655
+ onClick: () => setExpanded(!expanded),
1656
+ small: true,
1657
+ ariaLabel: `${t.skillSnapshotCount(snapshots.length)}: ${skill.name}`,
1658
+ },
1628
1659
  t.skillSnapshotCount(snapshots.length),
1629
1660
  expanded === true ? ' ▲' : ' ▼',
1630
1661
  ),
@@ -1644,6 +1675,7 @@ window.__ModuleLoader__.load({
1644
1675
  {
1645
1676
  onClick: runSnapshot,
1646
1677
  disabled: pending === true || skill.directory === null,
1678
+ ariaLabel: `${t.skillSnapshot}: ${skill.name}`,
1647
1679
  title: skill.directory === null ? t.skillNoDirectory : refusal === null ? undefined : t.skillRestoreRefusals[refusal] ?? refusal,
1648
1680
  },
1649
1681
  pending ? t.refreshing : t.skillSnapshot,
@@ -1816,7 +1848,11 @@ window.__ModuleLoader__.load({
1816
1848
  const path = kind === 'update' ? '/skills/git/update' : '/skills/git/restore'
1817
1849
  const body = await request(path, {
1818
1850
  method: 'POST',
1819
- body: revision === null ? { name: row.name, confirm: true } : { name: row.name, revision, confirm: true },
1851
+ body: revision === null ? { name: row.name, confirm: true,
1852
+ expectedRevision: preview?.detail?.to?.revision,
1853
+ expectedFromRevision: preview?.detail?.from?.revision,
1854
+ expectedDigest: preview?.detail?.localFiles?.digest,
1855
+ } : { name: row.name, revision, confirm: true },
1820
1856
  })
1821
1857
  if (body.ok === true) {
1822
1858
  setMessage(
@@ -2055,7 +2091,14 @@ window.__ModuleLoader__.load({
2055
2091
  h('div', { style: { fontSize: 13, fontWeight: 600 } }, t.skillsTitle),
2056
2092
  h('div', { style: { fontSize: 12, opacity: 0.7, marginTop: 2 } }, t.skillsSubtitle),
2057
2093
  ),
2058
- h(Button, { onClick: onReload, disabled: loading === true }, loading === true ? t.refreshing : t.refresh),
2094
+ h(
2095
+ Button,
2096
+ // Two buttons called "刷新" on one screen: this one reloads the Skill
2097
+ // catalog, the one above reloads the plugin list. The visible text
2098
+ // stays short, so the distinction lives in the accessible name.
2099
+ { onClick: onReload, disabled: loading === true, ariaLabel: `${t.refreshSkills}` },
2100
+ loading === true ? t.refreshing : t.refresh,
2101
+ ),
2059
2102
  )
2060
2103
 
2061
2104
  if (data === null) {
@@ -2175,6 +2218,26 @@ window.__ModuleLoader__.load({
2175
2218
 
2176
2219
  useEffect(() => () => skillsAbortRef.current?.abort(), [])
2177
2220
 
2221
+ // Focus follows selection, which is what a tab strip is expected to do:
2222
+ // the arrow moves the selection, so the focus has to land on the tab that
2223
+ // is now selected. Everything here is keyboard-only — a click already
2224
+ // focuses the button it landed on.
2225
+ const onTabKeyDown = useCallback((event) => {
2226
+ const index = TABS.indexOf(tab)
2227
+ if (index < 0) return
2228
+ let next = null
2229
+ if (event.key === 'ArrowRight') next = (index + 1) % TABS.length
2230
+ else if (event.key === 'ArrowLeft') next = (index - 1 + TABS.length) % TABS.length
2231
+ else if (event.key === 'Home') next = 0
2232
+ else if (event.key === 'End') next = TABS.length - 1
2233
+ if (next === null) return
2234
+ event.preventDefault()
2235
+ const key = TABS[next]
2236
+ setTab(key)
2237
+ const node = event.currentTarget?.ownerDocument?.getElementById(`vm-tab-${key}`)
2238
+ node?.focus()
2239
+ }, [tab])
2240
+
2178
2241
  const rows = state.data?.plugins ?? []
2179
2242
  const visible = useMemo(() => {
2180
2243
  const needle = query.trim().toLowerCase()
@@ -2320,19 +2383,29 @@ window.__ModuleLoader__.load({
2320
2383
  state.status === 'idle' ? h('div', { style: { fontSize: 12, opacity: 0.7 } }, t.started) : null,
2321
2384
  h(
2322
2385
  'div',
2323
- { style: { display: 'flex', gap: 6, marginTop: 12, borderBottom: `1px solid ${COLORS.line}` }, role: 'tablist' },
2324
- ...[
2325
- ['plugins', t.tabPlugins],
2326
- ['skills', t.tabSkills],
2327
- ].map(([key, label]) =>
2386
+ {
2387
+ style: { display: 'flex', gap: 6, marginTop: 12, borderBottom: `1px solid ${COLORS.line}` },
2388
+ role: 'tablist',
2389
+ 'aria-label': t.title,
2390
+ },
2391
+ ...TABS.map((key) =>
2328
2392
  h(
2329
2393
  'button',
2330
2394
  {
2331
2395
  key,
2396
+ id: `vm-tab-${key}`,
2332
2397
  type: 'button',
2333
2398
  role: 'tab',
2334
2399
  'aria-selected': tab === key ? 'true' : 'false',
2400
+ // A tablist is one stop in the tab order, not two: arrows move
2401
+ // between tabs. Leaving both tabs tabbable is the common slip —
2402
+ // it reads as two unrelated buttons to a screen reader.
2403
+ tabIndex: tab === key ? 0 : -1,
2404
+ // One panel, one address: it renders whichever tab is selected,
2405
+ // so every tab's aria-controls resolves to a real element.
2406
+ 'aria-controls': 'vm-panel',
2335
2407
  onClick: () => setTab(key),
2408
+ onKeyDown: onTabKeyDown,
2336
2409
  style: {
2337
2410
  font: 'inherit',
2338
2411
  fontSize: 12,
@@ -2345,36 +2418,45 @@ window.__ModuleLoader__.load({
2345
2418
  opacity: tab === key ? 1 : 0.65,
2346
2419
  },
2347
2420
  },
2348
- label,
2421
+ key === 'plugins' ? t.tabPlugins : t.tabSkills,
2349
2422
  ),
2350
2423
  ),
2351
2424
  ),
2352
- tab === 'skills'
2353
- ? h(SkillsView, {
2354
- t,
2355
- language,
2356
- state: skills.data,
2357
- loading: skills.status === 'loading',
2358
- onReload: loadSkills,
2359
- })
2360
- : toolbar,
2361
- tab !== 'plugins'
2362
- ? skills.error === null
2363
- ? null
2364
- : h(Notice, { tone: 'fail', title: t.errorLabel }, describeError(skills.error, t))
2365
- : state.data === null
2425
+ h(
2426
+ 'div',
2427
+ {
2428
+ id: 'vm-panel',
2429
+ role: 'tabpanel',
2430
+ 'aria-labelledby': `vm-tab-${tab}`,
2431
+ style: { marginTop: 2 },
2432
+ },
2433
+ tab === 'skills'
2434
+ ? h(SkillsView, {
2435
+ t,
2436
+ language,
2437
+ state: skills.data,
2438
+ loading: skills.status === 'loading',
2439
+ onReload: loadSkills,
2440
+ })
2441
+ : toolbar,
2442
+ tab !== 'plugins'
2443
+ ? skills.error === null
2444
+ ? null
2445
+ : h(Notice, { tone: 'fail', title: t.errorLabel }, describeError(skills.error, t))
2446
+ : state.data === null
2447
+ ? null
2448
+ : visible.length === 0
2449
+ ? h('div', { style: { fontSize: 12, opacity: 0.7, padding: '12px 0' } }, t.noNewerVersions)
2450
+ : table,
2451
+ tab !== 'plugins' || state.data === null
2366
2452
  ? null
2367
- : visible.length === 0
2368
- ? h('div', { style: { fontSize: 12, opacity: 0.7, padding: '12px 0' } }, t.noNewerVersions)
2369
- : table,
2370
- tab !== 'plugins' || state.data === null
2371
- ? null
2372
- : h(
2373
- 'div',
2374
- { style: { marginTop: 18 } },
2375
- h('div', { style: { fontSize: 12, fontWeight: 600, marginBottom: 4 } }, t.operations),
2376
- h(OperationsList, { t, language, operations: state.data.operations ?? [] }),
2377
- ),
2453
+ : h(
2454
+ 'div',
2455
+ { style: { marginTop: 18 } },
2456
+ h('div', { style: { fontSize: 12, fontWeight: 600, marginBottom: 4 } }, t.operations),
2457
+ h(OperationsList, { t, language, operations: state.data.operations ?? [] }),
2458
+ ),
2459
+ ),
2378
2460
  )
2379
2461
  }
2380
2462
 
@@ -222,6 +222,10 @@ export async function previewGitRoute(profile, body) {
222
222
  export async function updateGitRoute(profile, body) {
223
223
  const name = typeof body.name === 'string' ? body.name.trim() : ''
224
224
  if (name === '') return { status: 400, body: { error: 'missing-name' } }
225
+ const expectedRevision = body.expectedRevision
226
+ if (typeof expectedRevision !== 'string' || !/^[0-9a-f]{40}$/i.test(expectedRevision)) {
227
+ return { status: 400, body: { error: 'missing-preview-revision' } }
228
+ }
225
229
  const ref = typeof body.ref === 'string' && body.ref.trim() !== '' ? body.ref.trim() : undefined
226
230
  let record
227
231
  try {
@@ -230,6 +234,11 @@ export async function updateGitRoute(profile, body) {
230
234
  return { status: 409, body: { error: preview.reason, message: preview.message, detail: null } }
231
235
  }
232
236
  const { detail } = preview
237
+ if (detail.to.revision !== expectedRevision
238
+ || (body.expectedFromRevision !== undefined && body.expectedFromRevision !== detail.from.revision)
239
+ || (body.expectedDigest !== undefined && body.expectedDigest !== detail.localFiles.digest)) {
240
+ return { status: 409, body: { error: 'preview-changed', message: 'Preview the current revision and local files again.', detail: null } }
241
+ }
233
242
  if (detail.alreadyAtRevision) {
234
243
  return { status: 200, body: { ok: false, error: 'already-at-revision', message: null, detail } }
235
244
  }
@@ -246,7 +255,8 @@ export async function updateGitRoute(profile, body) {
246
255
  toVersion: detail.to.revision,
247
256
  })
248
257
  await transition(profile.home, profile.id, record, 'applying')
249
- const result = await applyGitUpdate({ dshHome: profile.home, profileId: profile.id, name, ref })
258
+ const result = await applyGitUpdate({ dshHome: profile.home, profileId: profile.id, name,
259
+ ref: expectedRevision, expectedRevision, expectedFromRevision: detail.from.revision, expectedDigest: detail.localFiles.digest })
250
260
  if (!result.ok) {
251
261
  await transition(profile.home, profile.id, record, 'failed', { error: result.reason })
252
262
  return {
@@ -33,6 +33,7 @@ import { tmpdir } from 'node:os'
33
33
  import { fingerprintTree } from './snapshot-store.js'
34
34
  import { isSystemPath } from './skill-restore.js'
35
35
  import { readGitState, snapshotSkill } from './skills.js'
36
+ import { withFileLock, withMutationLock } from './mutation-lock.js'
36
37
 
37
38
  const GIT_TIMEOUT_MS = 20000
38
39
  const MAX_HISTORY = 30
@@ -222,11 +223,16 @@ export function normaliseSubpath(subpath) {
222
223
  if (value === '') return ''
223
224
  if (value.startsWith('/')) return null
224
225
  const parts = value.split('/')
225
- if (parts.some((part) => part === '..' || part === '.' || part === '')) return null
226
- if (parts.some((part) => part === '.git')) return null
226
+ if (parts.some((part) => !portableSegment(part))) return null
227
227
  return value
228
228
  }
229
229
 
230
+ function portableSegment(part) {
231
+ return part !== '' && part !== '.' && part !== '..' && part.toLowerCase() !== '.git'
232
+ && !/[\\<>:"|?*\x00-\x1f]/.test(part) && !/[. ]$/.test(part)
233
+ && !/^(con|prn|aux|nul|conin\$|conout\$|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/i.test(part)
234
+ }
235
+
230
236
  /**
231
237
  * Why a registered entry cannot be updated right now, or null.
232
238
  *
@@ -340,6 +346,13 @@ async function ensureCache(dshHome, remote) {
340
346
  * revision: string | null, subject: string | null, message: string | null }>}
341
347
  */
342
348
  export async function fetchRevision(input) {
349
+ if (!isFetchableRemote(input.remote)) {
350
+ return { ok: false, reason: 'unsupported-remote', cache: null, revision: null, subject: null, message: null }
351
+ }
352
+ return withFileLock(`${cachePath(input.dshHome, input.remote)}.fetch.lock`, () => fetchRevisionUnlocked(input))
353
+ }
354
+
355
+ async function fetchRevisionUnlocked(input) {
343
356
  const { dshHome, remote, ref = 'HEAD' } = input
344
357
  if (!isFetchableRemote(remote)) {
345
358
  return { ok: false, reason: 'unsupported-remote', cache: null, revision: null, subject: null, message: null }
@@ -455,10 +468,10 @@ export async function exportRevision(input) {
455
468
  const meta = record.slice(0, tab).split(' ')
456
469
  const path = record.slice(tab + 1)
457
470
  const [mode, type, sha] = meta
458
- if (type !== 'blob') continue
459
471
  if (prefix !== '' && !path.startsWith(prefix)) continue
460
472
  const relativePath = prefix === '' ? path : path.slice(prefix.length)
461
473
  if (relativePath === '') continue
474
+ if (type !== 'blob') return { ok: false, reason: 'unsupported-entry', message: `${mode}: ${relativePath}`, files: null }
462
475
  blobs.push({ path, relativePath, mode, sha })
463
476
  }
464
477
  if (blobs.length === 0) {
@@ -469,9 +482,10 @@ export async function exportRevision(input) {
469
482
  }
470
483
 
471
484
  const target = resolve(into)
485
+ const destinations = new Set()
472
486
  for (const blob of blobs) {
473
487
  const parts = blob.relativePath.split('/')
474
- if (parts.some((part) => part === '' || part === '.' || part === '..')) {
488
+ if (parts.some((part) => !portableSegment(part))) {
475
489
  // A tree entry that would escape the target is not written. Git cannot
476
490
  // normally produce one, but this is the boundary that matters.
477
491
  return { ok: false, reason: 'path-escapes-target', message: null, files: null }
@@ -486,7 +500,16 @@ export async function exportRevision(input) {
486
500
  // Submodules and other tree types have no content to export.
487
501
  return { ok: false, reason: 'unsupported-entry', message: `${blob.mode}: ${blob.relativePath}`, files: null }
488
502
  }
489
- const destination = join(target, ...parts)
503
+ const destination = resolve(target, ...parts)
504
+ if (!destination.startsWith(`${target}${sep}`) || destinations.has(destination.toLowerCase())) {
505
+ return { ok: false, reason: 'path-escapes-target', message: null, files: null }
506
+ }
507
+ destinations.add(destination.toLowerCase())
508
+ blob.destination = destination
509
+ }
510
+ // Validate the whole tree before writing even its first ordinary file.
511
+ for (const blob of blobs) {
512
+ const destination = blob.destination
490
513
  const content = await runGitBytes(['--git-dir', cache, 'cat-file', 'blob', blob.sha])
491
514
  if (!content.ok) {
492
515
  return { ok: false, reason: 'blob-unreadable', message: content.stderr || null, files: null }
@@ -541,6 +564,14 @@ export async function replaceDirectory(input) {
541
564
  return { ok: false, reason: 'staged-copy-corrupt', message: null, evidence: { stagedDigest: staged?.digest ?? null } }
542
565
  }
543
566
 
567
+ if (Object.hasOwn(input, 'expectedCurrentDigest')) {
568
+ const current = await fingerprintTree(target)
569
+ if ((current?.digest ?? null) !== input.expectedCurrentDigest) {
570
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
571
+ return { ok: false, reason: 'local-modifications', message: 'The directory changed while staging.', evidence: null }
572
+ }
573
+ }
574
+
544
575
  let parkedOk = false
545
576
  try {
546
577
  if (existed) {
@@ -625,6 +656,10 @@ export async function treeDigest(input) {
625
656
  * @returns {Promise<{ ok: boolean, reason: string | null, message: string | null, entry: object | null }>}
626
657
  */
627
658
  export async function registerGitSkill(input) {
659
+ return withMutationLock(input, registerGitSkillUnlocked)
660
+ }
661
+
662
+ async function registerGitSkillUnlocked(input) {
628
663
  const { dshHome, profileId, name, remote, subpath, ref = 'HEAD', directory = null } = input
629
664
  if (typeof name !== 'string' || name.trim() === '') {
630
665
  return { ok: false, reason: 'missing-name', message: null, entry: null }
@@ -701,6 +736,10 @@ export async function registerGitSkill(input) {
701
736
  * @returns {Promise<{ ok: boolean, reason: string | null }>}
702
737
  */
703
738
  export async function unregisterGitSkill(input) {
739
+ return withMutationLock(input, unregisterGitSkillUnlocked)
740
+ }
741
+
742
+ async function unregisterGitSkillUnlocked(input) {
704
743
  const { dshHome, profileId, name } = input
705
744
  const registry = await readRegistry(dshHome, profileId)
706
745
  const next = registry.filter((entry) => entry.name !== name)
@@ -781,7 +820,11 @@ export async function previewGitUpdate(input) {
781
820
  * snapshot: object | null }>}
782
821
  */
783
822
  export async function applyGitUpdate(input) {
784
- const { dshHome, profileId, name, ref } = input
823
+ return withMutationLock(input, applyGitUpdateUnlocked)
824
+ }
825
+
826
+ async function applyGitUpdateUnlocked(input) {
827
+ const { dshHome, profileId, name, ref, expectedRevision, expectedFromRevision, expectedDigest } = input
785
828
  const preview = await previewGitUpdate({ dshHome, profileId, name, ref })
786
829
  if (!preview.ok) {
787
830
  return {
@@ -795,6 +838,11 @@ export async function applyGitUpdate(input) {
795
838
  }
796
839
  }
797
840
  const { detail } = preview
841
+ if ((expectedRevision !== undefined && expectedRevision !== detail.to.revision)
842
+ || (expectedFromRevision !== undefined && expectedFromRevision !== detail.from.revision)
843
+ || (expectedDigest !== undefined && expectedDigest !== detail.localFiles.digest)) {
844
+ return { ok: false, reason: 'preview-changed', message: 'Preview the current revision and local files again.', evidence: null, fromRevision: detail.from.revision, toRevision: detail.to.revision, snapshot: null }
845
+ }
798
846
  if (detail.alreadyAtRevision) {
799
847
  return {
800
848
  ok: false,
@@ -853,6 +901,7 @@ export async function applyGitUpdate(input) {
853
901
  const cache = (await ensureCache(dshHome, entry.remote)).path
854
902
  const applied = await replaceDirectory({
855
903
  target: entry.directory,
904
+ expectedCurrentDigest: detail.localFiles.digest,
856
905
  prepare: async (staging) => exportRevision({ cache, revision: detail.to.revision, subpath: entry.subpath, into: staging }),
857
906
  })
858
907
  if (!applied.ok) {
@@ -917,6 +966,10 @@ export async function applyGitUpdate(input) {
917
966
  * snapshot: object | null }>}
918
967
  */
919
968
  export async function restoreGitRevision(input) {
969
+ return withMutationLock(input, restoreGitRevisionUnlocked)
970
+ }
971
+
972
+ async function restoreGitRevisionUnlocked(input) {
920
973
  const { dshHome, profileId, name, revision } = input
921
974
  if (typeof revision !== 'string' || !/^[0-9a-f]{4,40}$/i.test(revision)) {
922
975
  return { ok: false, reason: 'bad-revision', message: null, evidence: null, fromRevision: null, toRevision: null, snapshot: null }
@@ -976,6 +1029,7 @@ export async function restoreGitRevision(input) {
976
1029
 
977
1030
  const applied = await replaceDirectory({
978
1031
  target: entry.directory,
1032
+ expectedCurrentDigest: current.digest,
979
1033
  prepare: async (staging) => exportRevision({ cache, revision: full, subpath: entry.subpath, into: staging }),
980
1034
  })
981
1035
  if (!applied.ok) {
@@ -0,0 +1,26 @@
1
+ import { mkdir, open, unlink } from 'node:fs/promises'
2
+ import { dirname, join, resolve } from 'node:path'
3
+
4
+ /** Atomic across host processes. Never steal a lock whose owner may still write. */
5
+ export async function withFileLock(path, operation) {
6
+ await mkdir(dirname(path), { recursive: true })
7
+ let handle
8
+ try {
9
+ handle = await open(path, 'wx')
10
+ } catch (error) {
11
+ if (error.code !== 'EEXIST') throw error
12
+ return { ok: false, reason: 'operation-in-progress', message: 'Another operation owns the write lock.', entry: null, evidence: null, snapshot: null, cache: null, revision: null }
13
+ }
14
+ try {
15
+ await handle.writeFile(JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }))
16
+ return await operation()
17
+ } finally {
18
+ await handle.close()
19
+ await unlink(path)
20
+ }
21
+ }
22
+
23
+ /** Registry edits, Git swaps and snapshot restores share one home-wide lock. */
24
+ export function withMutationLock(input, operation) {
25
+ return withFileLock(join(resolve(input.dshHome), 'version-manager', 'git-skills', '.write.lock'), () => operation(input))
26
+ }
@@ -33,6 +33,7 @@ import { dirname, join, sep } from 'node:path'
33
33
  import { fingerprintTree } from './snapshot-store.js'
34
34
  import { encodeSegment, safeSegment } from './segment.js'
35
35
  import { directoryState, listSkillSnapshots, readGitState, snapshotSkill } from './skills.js'
36
+ import { withMutationLock } from './mutation-lock.js'
36
37
 
37
38
  /**
38
39
  * @param {string} dshHome
@@ -188,6 +189,10 @@ export async function previewSkillRestore(input) {
188
189
  * evidence: object | null, restoredTo: string | null, undo: string | null }>}
189
190
  */
190
191
  export async function restoreSkillSnapshot(input) {
192
+ return withMutationLock(input, restoreSkillSnapshotUnlocked)
193
+ }
194
+
195
+ async function restoreSkillSnapshotUnlocked(input) {
191
196
  const { dshHome, profileId, name, directory, file, source = null } = input
192
197
  const preview = await previewSkillRestore({ dshHome, profileId, name, directory, file, source })
193
198
  if (!preview.ok) {
@@ -271,6 +276,12 @@ export async function restoreSkillSnapshot(input) {
271
276
  }
272
277
  }
273
278
 
279
+ const latest = await fingerprintTree(target)
280
+ if ((latest?.digest ?? null) !== (preview.detail.currentDigest ?? null)) {
281
+ await cleanup()
282
+ return { ok: false, reason: 'local-modifications', message: 'The directory changed while staging.', evidence: null, restoredTo: null, undo }
283
+ }
284
+
274
285
  let parkedOk = state === 'missing'
275
286
  try {
276
287
  if (state === 'directory') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-version-manager",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "description": "Version management for DSH plugins and skills: an honest inventory of what is installed, a preview of what an update would change, a verifiable snapshot taken before the change, and a recovery path that is only offered when it can actually work.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -8,14 +8,23 @@
8
8
  ".": "./lib/index.js",
9
9
  "./client": "./lib/client.js",
10
10
  "./cordis.patch.yml": "./cordis.patch.yml",
11
- "./package.json": "./package.json"
11
+ "./package.json": "./package.json",
12
+ "./icon": "./assets/logo.webp"
12
13
  },
13
14
  "files": [
14
15
  "lib",
15
16
  "cordis.patch.yml",
16
17
  "docs/baseline.md",
17
18
  "README.md",
18
- "LICENSE"
19
+ "LICENSE",
20
+ "assets/logo.webp",
21
+ "assets/NOTICE.md",
22
+ "assets/LICENSE-WHALE-ARTWORK",
23
+ "README.zh-CN.md",
24
+ "docs/assets",
25
+ "docs/git-write-safety.md",
26
+ "docs/guide.en.md",
27
+ "docs/release-notes-0.1.4.md"
19
28
  ],
20
29
  "keywords": [
21
30
  "deepseek",
@@ -58,5 +67,6 @@
58
67
  "platform": "web",
59
68
  "immediately": true
60
69
  }
61
- }
70
+ },
71
+ "icon": "./assets/logo.webp"
62
72
  }