dsh-version-manager 0.1.1 → 0.1.3

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/README.md CHANGED
@@ -70,7 +70,7 @@ The summary line above the table counts entries the host would let this plugin w
70
70
 
71
71
  A snapshot records the profile identity, package name, original declared spec, installed version, source (including the registry host when the lockfile records one), enabled state, compatibility verdict, and a SHA-256 fingerprint of the package directory. It does **not** record tokens, credentials, environment variables or file contents.
72
72
 
73
- Snapshots live under `<DSH_HOME>/version-manager/snapshots/<profile>/<package>/`, are written through a temporary file and renamed into place, never overwrite an existing snapshot, and are retained at 20 per target (the oldest beyond that are listed, not silently deleted).
73
+ Snapshots live under `<DSH_HOME>/version-manager/snapshots/<profile>/<package>/`, are written through a temporary file and renamed into place, never overwrite an existing snapshot, and are kept at 20 per target. Anything older than that stays restorable and is labelled as past retention rather than deleted for you; see [Retention](#retention-is-visible-and-nothing-is-deleted-for-you).
74
74
 
75
75
  Restore is offered only when it can actually work, and only reports what happened:
76
76
 
@@ -143,17 +143,17 @@ Sources that are **not** supported, listed rather than implied: any directory th
143
143
 
144
144
  Three kinds of evidence, kept apart on purpose.
145
145
 
146
- **Unit and integration tests.** `npm test` runs 104 tests with no network and no host: spec classification, semver comparison, lockfile parsing, inventory merging, snapshot store, operation journal, Skill restore (including a swap that fails halfway), the Git-managed Skill flow against real throwaway repositories, and the HTTP routes wired against a fake host.
146
+ **Unit and integration tests.** `npm test` runs 141 tests with no network and no host: spec classification, semver comparison, lockfile parsing, inventory merging, snapshot store, snapshot retention and pruning, operation journal, path-segment encoding, host location, Skill restore (including a swap that fails halfway), the Git-managed Skill flow against real throwaway repositories, and the HTTP routes wired against a fake host.
147
147
 
148
148
  **CI.** `.github/workflows/check.yml` runs that suite on Ubuntu, Windows and macOS against Node 22 and 24 — six jobs, no install step, because the package has no dependencies. It also runs `npm pack --dry-run` so a broken `files` list fails the build.
149
149
 
150
- **A real host.** The flows below were run against DeepSeek Harness `0.2.2-rc.1` (Electron 44.7.0, Node 24.21.0) on Windows 11, installed from the packed tarball `dsh-version-manager-0.1.0.tgz` into a throwaway `DSH_HOME`. The point of a separate home is that a mistake here cannot touch the profile you work in.
150
+ **A real host.** The flows below were run against DeepSeek Harness `0.2.2-rc.1` (Electron 44.7.0, Node 24.21.0) on Windows 11, installed from the packed tarball into a throwaway `DSH_HOME`. The point of a separate home is that a mistake here cannot touch the profile you work in.
151
151
 
152
152
  What was exercised, and what it produced:
153
153
 
154
154
  | step | observed |
155
155
  | --- | --- |
156
- | fresh profile created by `dsh plugin --profile final add <tarball>` | `dsh: initialized profile final`, `+ dsh-version-manager 0.1.0`, 26 rows rendered |
156
+ | fresh profile created by `dsh plugin --profile final add <tarball>` | `dsh: initialized profile final`, the packaged version reported by the host, 26 rows rendered |
157
157
  | `GET /overview` | `profile=final`, `host=0.2.2-rc.1`, source `@deepseek-ai/dsh-app-boot/package.json` |
158
158
  | `POST /snapshot` without `confirm` | `400 {"error":"confirm required"}` |
159
159
  | `POST /snapshot` with `confirm` | `200`, snapshot written with `seq: 1` |
@@ -162,9 +162,11 @@ What was exercised, and what it produced:
162
162
  | `POST /skills/snapshot` | `200`, copy re-read and verified, `fileCount: 2` |
163
163
  | Skill restore on a bundled Skill | `409 bundled-skill`, directory unchanged |
164
164
  | Git-managed Skill: register, first apply, update A→B, restore A, hand-edit then restore | registered against an empty directory (`populated: false`), first update filled it, an update moved `8569b20 → c3d0909` with `M SKILL.md` / `A extra.md`, a restore put `8569b20` back and removed `extra.md`, a hand-edited file made the update refuse `local-modifications` while the restore still ran and left an undo snapshot holding the edited bytes |
165
+ | retention, driven from the panel of the **published** 0.1.2 | three snapshots past the limit made the row read `23 份快照,其中 3 份超出每个目标保留的 20 份。超出的不会自动删除,仍然可以恢复。` with three `超出保留数` badges and a `删除超出的快照` button; the confirmation named the target and the count; after confirming, the panel said `已删除 3 份超出保留数的快照,现在剩 20 份。`, `/overview` reported `{stored: 20, beyondLimit: 0}`, and exactly three files were gone from disk (oldest remaining `0006-…`) |
166
+ | lifecycle: install, disable, uninstall, reinstall | disabling needed `- id: version-manager` / `disabled: true` in the profile's `cordis.patch.yml` (the CLI has no enable/disable); after uninstall the sidebar entry was gone and the snapshot store was untouched; reinstalling brought back every snapshot and operation |
165
167
  | the Desktop shell | sidebar entry, panel, both tabs, confirmation bar, operation list and snapshot list all rendered and worked; a snapshot taken by clicking in the UI landed on disk |
166
168
 
167
- Two defects found this way and fixed rather than documented away: a nested-but-successful host reply was being classified as a failure, and a bundled Skill could be offered a restore the plugin would refuse everywhere else. A third was cosmetic but worse than cosmetic — one local path was compared in two spellings and reported as a change that never happened. A fourth came out of the Git flow: the panel reported a freshly registered, still-empty directory as "modified, update will be refused" because the empty directory's digest never equals the commit's, while the update path allowed it — the row now reads the same refusal function the update path uses, so the two cannot drift apart again. A fifth was found by installing the published package: the panel said "2 updatable" for two rows that had no newer version at all, because the number was counting rows the host would accept a write for. The field and its labels now say **writable** — what is actually measured.
169
+ Two defects found this way and fixed rather than documented away: a nested-but-successful host reply was being classified as a failure, and a bundled Skill could be offered a restore the plugin would refuse everywhere else. A third was cosmetic but worse than cosmetic — one local path was compared in two spellings and reported as a change that never happened. A fourth came out of the Git flow: the panel reported a freshly registered, still-empty directory as "modified, update will be refused" because the empty directory's digest never equals the commit's, while the update path allowed it — the row now reads the same refusal function the update path uses, so the two cannot drift apart again. A fifth was found by installing the published package: the panel said "2 updatable" for two rows that had no newer version at all, because the number was counting rows the host would accept a write for. The field and its labels now say **writable** — what is actually measured. A sixth came from asking which modules had no test at all: `operations.js` and `locate.js` had none, and writing the first test for the journal found that `encodeSegment('..')` returned `..`, so `path.join(root, '..')` climbed out of the plugin's own store. Four modules each had their own copy of that encoder. They now share one, which treats a name made only of dots as dots-that-are-not-a-path. The ordinary names are untouched — a test pins `desktop` → `desktop` and `team/blue` → `team%2Fblue`, because a stricter encoding would silently move every snapshot already on disk.
168
170
 
169
171
  Not verified: another DSH version, a Linux or macOS Desktop, and a non-bundled Skill provider.
170
172
 
@@ -201,6 +203,7 @@ All under `/dsh-version-manager`, same-origin, `Cache-Control: no-store`.
201
203
  | GET | `/skills/restore-preview?name=&file=` | — | what a restore would do, and every reason it would be refused |
202
204
  | GET | `/skills/git` | — | registered Git sources, their pinned revision, local drift, and separate `refusal` / `restoreRefusal` |
203
205
  | POST | `/snapshot` | `{targetId, confirm}` | snapshot one plugin |
206
+ | POST | `/snapshots/prune` | `{targetId, confirm}` | delete the snapshots past the per-target limit, listing every file removed |
204
207
  | POST | `/update` | `{targetId, toVersion, allowPrerelease?, confirm}` | snapshot, then ask the host to update |
205
208
  | POST | `/restore` | `{targetId, snapshotId, confirm}` | reinstall the version a snapshot recorded |
206
209
  | POST | `/skills/snapshot` | `{name, confirm}` | snapshot one Skill |
@@ -213,6 +216,107 @@ All under `/dsh-version-manager`, same-origin, `Cache-Control: no-store`.
213
216
 
214
217
  Error bodies carry a stable `error` code and, when useful, a `message`. The update and restore flows also return `operationId`, and the operation journal under `<DSH_HOME>/version-manager/operations/<profile>/` records each transition: `planned`, `snapshot_verified`, `applying`, `verifying`, then `succeeded`, `failed`, `cancelled` or `recovery_required`.
215
218
 
219
+ ## Performance and cache policy
220
+
221
+ Measured in a real Windows Desktop host (0.2.2-rc.1, Electron 44.7.0, Node 24.21.0) against a
222
+ profile with 26 plugin rows, 11 stored snapshots and 8 visible Skills. Timings are
223
+ `fetch()` round trips taken inside the panel's page, so they include the host's own
224
+ serialization:
225
+
226
+ | call | cold | warm |
227
+ | --- | --- | --- |
228
+ | `GET /overview` | 161 ms | 134 ms |
229
+ | `GET /skills` | 426 ms | 313 ms |
230
+
231
+ There is nothing slower here by design. What costs time, and why:
232
+
233
+ - **`/overview` reads the filesystem per row.** For each package it reads the installed
234
+ manifest, the profile manifest, the lockfile entry and the stored snapshot list. That is
235
+ why it is one call and not one call per row: the panel refreshes everything at once.
236
+ - **`/skills` is the slower one** because the host's skill catalog is scanned by the host
237
+ itself; the plugin only aggregates what the host already enumerated.
238
+ - **No caching of version lists anywhere.** `/versions?target=…` asks the registry through
239
+ the host every time it is pressed. A cached answer would be indistinguishable from a
240
+ fresh one in the panel, which is exactly the failure this plugin exists to avoid.
241
+ - **The only on-disk caches** are the snapshot store
242
+ (`<DSH_HOME>/version-manager/snapshots/<profile>/<pkg>/`) and, for Git-managed Skills, a
243
+ bare repository per remote (`<DSH_HOME>/version-manager/git-cache/<hash>.git`). Both are
244
+ yours to delete when the plugin is not running; the plugin recreates what it needs.
245
+
246
+ ### Retention is visible, and nothing is deleted for you
247
+
248
+ Every target keeps its snapshots. The panel states the numbers: how many exist, how many
249
+ are past the 20-per-target limit, and which ones. Rows past the limit are labelled
250
+ **超出保留数 / past retention** in the list.
251
+
252
+ They are **not** removed automatically. A version manager that silently deletes the way
253
+ back is worse than one that keeps too much, so removal is one explicit action with its own
254
+ confirmation, which states how many files it will delete before it does it:
255
+
256
+ ```
257
+ POST /snapshots/prune { targetId, confirm: true }
258
+ ```
259
+
260
+ The response lists every removed file, every file it failed to remove, and how many remain.
261
+ A snapshot still in the list can still be restored.
262
+
263
+ ## Troubleshooting
264
+
265
+ | symptom | what it means | what to do |
266
+ | --- | --- | --- |
267
+ | Sidebar has no **Version Manager** entry | the plugin did not activate | `dsh --profile <p> --no-open` prints the entries that did not activate; a fresh profile usually reports `pending (waiting for service: webServer)` — see [Install](#install) |
268
+ | Panel opens but every row says `unknown` compatibility | the installed manifest could not be read for those packages | the row's `加载状态` detail names the reason; `unknown` is deliberately not rendered as a pass |
269
+ | `registry 未知` on a package | pnpm's lockfile stored no tarball URL for it | nothing is broken; a version check still works, but this plugin will not guess which registry host to record |
270
+ | A row is read-only and offers no update | the host itself keeps that entry read-only (official bundles, or an `install` source the plugin must not rewrite) | the row shows the host's own reason; updates to those entries are not attempted |
271
+ | Update answers `not-updatable` | the row was writable at render time but not when the request arrived | press refresh; if it stays read-only, the host changed its mind and the panel is telling you |
272
+ | Update answers `already-installed` | the host reached the target without changing anything | this is reported as a failure on purpose: nothing was applied, so nothing is claimed as applied |
273
+ | Restore answers `409` | a precondition failed | the body's `error` is a stable code (`source-not-replayable`, `not-installed`, `snapshot-incomplete`, …) and `evidence` shows what was compared |
274
+ | `evidence.filesMatch: false` after a restore | the files on disk differ from the snapshot's recorded fingerprint | expected when the package's files change between versions; it is evidence, not a veto |
275
+ | Skill tab says the skills service is unavailable | the host exposes no skill provider in that process | the panel prints the host's own reason; the Git-managed section still works, because it does not need the catalog |
276
+ | Only bundled Skills are listed | `skill-filesystem` is `disabled: true` in a stock profile | enable that provider in the profile to see your own Skill directories |
277
+ | `git-not-found` | Git is not on `PATH` for the host process | install Git; the Git Skill flow refuses rather than copying files without it |
278
+ | `local-modifications` | files changed since the registered baseline | update refuses; `回到这个 commit` (restore) still works and snapshots the current bytes first |
279
+
280
+ ## Upgrade and uninstall
281
+
282
+ Upgrade in place — the profile manifest and the stored snapshots both survive:
283
+
284
+ ```bash
285
+ dsh plugin --profile <profile> add dsh-version-manager@<newer-version>
286
+ ```
287
+
288
+ Reinstalling the **same** version is the one case pnpm short-circuits
289
+ (`Already up to date`, files not replaced). Remove first, then add:
290
+
291
+ ```bash
292
+ dsh plugin --profile <profile> remove dsh-version-manager
293
+ dsh plugin --profile <profile> add dsh-version-manager@<version>
294
+ ```
295
+
296
+ Uninstall removes the code, not your data:
297
+
298
+ ```bash
299
+ dsh plugin --profile <profile> remove dsh-version-manager
300
+ ```
301
+
302
+ Verified in an isolated profile: after a remove, `node_modules/dsh-version-manager` was
303
+ gone and the `dependencies` / `dsh.profile.bundles` entries with it, while
304
+ `<DSH_HOME>/version-manager/` still held every snapshot and operation record (19 files
305
+ before and after). Reinstalling brought the panel back with the same 11 snapshots and 8
306
+ operations. Delete `<DSH_HOME>/version-manager/` yourself to remove that history.
307
+
308
+ Disabling without uninstalling uses the host's own patch file — add the row's `id` with
309
+ `disabled: true` to `<DSH_HOME>/profiles/<profile>/cordis.patch.yml`, then restart:
310
+
311
+ ```yaml
312
+ - id: version-manager
313
+ disabled: true
314
+ ```
315
+
316
+ The panel disappears from the sidebar and nothing runs. There is no enable/disable
317
+ subcommand in the DSH CLI (`dsh plugin` only forwards `add` / `remove`); the patch file is
318
+ the supported way. Verified in an isolated profile, both directions.
319
+
216
320
  ## Compatibility
217
321
 
218
322
  | DSH | status |
package/lib/client.js CHANGED
@@ -126,6 +126,22 @@ window.__ModuleLoader__.load({
126
126
  snapshots: '快照',
127
127
  noSnapshots: '还没有快照',
128
128
  restore: '恢复此版本',
129
+ snapshotBeyond: '超出保留数',
130
+ retentionOk: (stored, limit) => `${stored} 份快照,未超过每个目标保留的 ${limit} 份。`,
131
+ retentionOver: (stored, limit, beyond) =>
132
+ `${stored} 份快照,其中 ${beyond} 份超出每个目标保留的 ${limit} 份。超出的不会自动删除,仍然可以恢复。`,
133
+ pruneAction: '删除超出的快照',
134
+ pruneBusy: '删除中…',
135
+ pruneDone: (removed, remaining) => `已删除 ${removed} 份超出保留数的快照,现在剩 ${remaining} 份。`,
136
+ pruneNothing: '没有超出保留数的快照,未删除任何文件。',
137
+ pruneConfirmTitle: '确认删除超出的快照',
138
+ pruneConfirmBody: (target, count, limit) =>
139
+ `将从 ${target} 删除 ${count} 份最早的快照,保留最近 ${limit} 份。删除后这些快照不能再用来恢复。`,
140
+ pruneConfirmNotes: [
141
+ '只删除超出保留数的部分,最近的那些不受影响。',
142
+ '删除的是快照文件本身,已安装的包和 Skill 目录不会被改动。',
143
+ '插件不会自行删除;这一步只在你按下确认时发生。',
144
+ ],
129
145
  restoreConfirm: (v) => `将把版本恢复到 ${v}。只恢复版本,不恢复配置。`,
130
146
  restoring: '恢复中…',
131
147
  restoreRefused: '无法安全恢复',
@@ -375,6 +391,22 @@ window.__ModuleLoader__.load({
375
391
  snapshots: 'Snapshots',
376
392
  noSnapshots: 'No snapshots yet',
377
393
  restore: 'Restore this version',
394
+ snapshotBeyond: 'Past retention',
395
+ retentionOk: (stored, limit) => `${stored} snapshot(s), within the ${limit} kept per target.`,
396
+ retentionOver: (stored, limit, beyond) =>
397
+ `${stored} snapshot(s), ${beyond} of them past the ${limit} kept per target. The extras are not deleted automatically and still restore.`,
398
+ pruneAction: 'Delete the extra snapshots',
399
+ pruneBusy: 'Deleting…',
400
+ pruneDone: (removed, remaining) => `Removed ${removed} snapshot(s) past the limit; ${remaining} remain.`,
401
+ pruneNothing: 'Nothing is past the retention limit, so no file was removed.',
402
+ pruneConfirmTitle: 'Confirm deleting the extra snapshots',
403
+ pruneConfirmBody: (target, count, limit) =>
404
+ `Remove the oldest ${count} snapshot(s) of ${target}, keeping the newest ${limit}. Once deleted, those snapshots can no longer restore anything.`,
405
+ pruneConfirmNotes: [
406
+ 'Only the part past the limit is removed; the recent ones are untouched.',
407
+ 'Only the snapshot files go; installed packages and Skill directories are not modified.',
408
+ 'The plugin never deletes on its own. This happens only when you confirm it.',
409
+ ],
378
410
  restoreConfirm: (v) => `Restore the version to ${v}. Only the version is restored.`,
379
411
  restoring: 'Restoring…',
380
412
  restoreRefused: 'Cannot restore safely',
@@ -652,7 +684,7 @@ window.__ModuleLoader__.load({
652
684
  gap: 4,
653
685
  padding: '1px 7px',
654
686
  borderRadius: 999,
655
- border: `1px solid ${COLORS.line}`,
687
+ border: `1px solid ${props.tone === 'warn' ? COLORS.warn : COLORS.line}`,
656
688
  background: COLORS.soft,
657
689
  fontSize: 11,
658
690
  lineHeight: 1.6,
@@ -912,7 +944,7 @@ window.__ModuleLoader__.load({
912
944
  }
913
945
 
914
946
  function SnapshotList(props) {
915
- const { t, language, snapshots, installed, onRestore, busy } = props
947
+ const { t, language, snapshots, installed, onRestore, busy, retention } = props
916
948
  if (snapshots.length === 0) {
917
949
  return h('div', { style: { fontSize: 12, opacity: 0.7, marginTop: 4 } }, t.noSnapshots)
918
950
  }
@@ -922,7 +954,7 @@ window.__ModuleLoader__.load({
922
954
  snapshots
923
955
  .slice()
924
956
  .reverse()
925
- .map((snapshot) =>
957
+ .map((snapshot, index) =>
926
958
  h(
927
959
  'li',
928
960
  {
@@ -940,6 +972,9 @@ window.__ModuleLoader__.load({
940
972
  h('span', { style: { opacity: 0.65 } }, formatTime(snapshot.takenAt, language)),
941
973
  snapshot.reason === 'unreadable' ? h(Badge, null, snapshot.reason) : null,
942
974
  snapshot.installedVersion === installed ? h(Badge, null, t.colVersion) : null,
975
+ index >= (retention?.limit ?? Infinity)
976
+ ? h(Badge, { tone: 'warn' }, t.snapshotBeyond)
977
+ : null,
943
978
  h(
944
979
  'span',
945
980
  { style: { marginLeft: 'auto' } },
@@ -958,6 +993,39 @@ window.__ModuleLoader__.load({
958
993
  )
959
994
  }
960
995
 
996
+ /**
997
+ * How many snapshots exist, how many are past the limit that is kept, and
998
+ * the one action that removes the extras.
999
+ *
1000
+ * The plugin never prunes on its own: deleting the way back is the user's
1001
+ * decision, so the count is stated before the button does anything.
1002
+ */
1003
+ function RetentionLine(props) {
1004
+ const { t, retention, busy, onPrune } = props
1005
+ if (retention === undefined || retention === null) return null
1006
+ const beyond = retention.beyondLimit ?? 0
1007
+ return h(
1008
+ 'div',
1009
+ {
1010
+ style: { display: 'flex', gap: 8, alignItems: 'center', marginTop: 6, fontSize: 12, flexWrap: 'wrap' },
1011
+ },
1012
+ h(
1013
+ 'span',
1014
+ { style: { opacity: 0.75 } },
1015
+ beyond === 0
1016
+ ? t.retentionOk(retention.stored, retention.limit)
1017
+ : t.retentionOver(retention.stored, retention.limit, beyond),
1018
+ ),
1019
+ beyond === 0
1020
+ ? null
1021
+ : h(
1022
+ Button,
1023
+ { onClick: onPrune, disabled: busy, ariaLabel: t.pruneAction },
1024
+ busy ? t.pruneBusy : t.pruneAction,
1025
+ ),
1026
+ )
1027
+ }
1028
+
961
1029
  function ConfirmBar(props) {
962
1030
  const { t, title, body, notes, onCancel, onConfirm, busy, confirmLabel } = props
963
1031
  return h(
@@ -1002,7 +1070,8 @@ window.__ModuleLoader__.load({
1002
1070
  const [snapshotBusy, setSnapshotBusy] = useState(false)
1003
1071
  const [pendingRestore, setPendingRestore] = useState(null)
1004
1072
  const [restoreBusy, setRestoreBusy] = useState(false)
1005
-
1073
+ const [pruneBusy, setPruneBusy] = useState(false)
1074
+ const [pendingPrune, setPendingPrune] = useState(false)
1006
1075
  const loadVersions = useCallback(async () => {
1007
1076
  setVersionsBusy(true)
1008
1077
  setVersionsError(null)
@@ -1032,6 +1101,33 @@ window.__ModuleLoader__.load({
1032
1101
  }
1033
1102
  }, [row.targetId, onRefresh, t])
1034
1103
 
1104
+ // Removal is the one action that takes away a way back, so it asks first
1105
+ // and says how many files it will touch. The host re-checks the limit
1106
+ // itself: this number is what the panel believes, not what it commands.
1107
+ const pruneSnapshots = useCallback(async () => {
1108
+ setPruneBusy(true)
1109
+ setResult(null)
1110
+ try {
1111
+ const body = await request('/snapshots/prune', {
1112
+ method: 'POST',
1113
+ body: { targetId: row.targetId, confirm: true },
1114
+ })
1115
+ setResult({
1116
+ ok: body.ok === true,
1117
+ message:
1118
+ body.removed.length === 0
1119
+ ? t.pruneNothing
1120
+ : t.pruneDone(body.removed.length, body.stored),
1121
+ })
1122
+ setPendingPrune(false)
1123
+ await onRefresh()
1124
+ } catch (error) {
1125
+ setResult({ ok: false, message: describeError(error, t) })
1126
+ } finally {
1127
+ setPruneBusy(false)
1128
+ }
1129
+ }, [row.targetId, onRefresh, t])
1130
+
1035
1131
  const runUpdate = useCallback(async () => {
1036
1132
  if (pendingUpdate === null) return
1037
1133
  setUpdateBusy(true)
@@ -1214,8 +1310,27 @@ window.__ModuleLoader__.load({
1214
1310
  snapshots: row.snapshots ?? [],
1215
1311
  installed: row.installedVersion,
1216
1312
  busy: restoreBusy ? 'x' : null,
1313
+ retention: row.retention ?? null,
1217
1314
  onRestore: (snapshot) => setPendingRestore(snapshot),
1218
1315
  }),
1316
+ h(RetentionLine, {
1317
+ t,
1318
+ retention: row.retention ?? null,
1319
+ busy: pruneBusy,
1320
+ onPrune: () => setPendingPrune(true),
1321
+ }),
1322
+ pendingPrune === true
1323
+ ? h(ConfirmBar, {
1324
+ t,
1325
+ title: t.pruneConfirmTitle,
1326
+ body: t.pruneConfirmBody(row.targetId, row.retention?.beyondLimit ?? 0, row.retention?.limit ?? 0),
1327
+ notes: t.pruneConfirmNotes,
1328
+ busy: pruneBusy,
1329
+ onCancel: () => setPendingPrune(false),
1330
+ onConfirm: pruneSnapshots,
1331
+ confirmLabel: t.pruneAction,
1332
+ })
1333
+ : null,
1219
1334
  ),
1220
1335
 
1221
1336
  versionsError === null ? null : h(Notice, { tone: 'fail', title: t.networkFailed }, describeError(versionsError, t)),
@@ -117,7 +117,12 @@ function runGitBytes(args) {
117
117
  * @returns {string}
118
118
  */
119
119
  function registryPath(dshHome, profileId) {
120
- return join(dshHome, 'version-manager', 'git-skills', `${profileId.replace(/[^A-Za-z0-9._-]/g, '_')}.json`)
120
+ // Deliberately not `encodeSegment`: this one is a *file* name with `.json`
121
+ // appended, so `..` cannot traverse, and the stricter alphabet it has always
122
+ // used is what the registries already on disk are named after. Widening it
123
+ // would make an existing registry look empty rather than moved.
124
+ const safe = String(profileId).replace(/[^A-Za-z0-9._-]/g, '_')
125
+ return join(dshHome, 'version-manager', 'git-skills', `${safe}.json`)
121
126
  }
122
127
 
123
128
  /**
@@ -22,6 +22,8 @@ import { mkdir, readdir, readFile, rename, writeFile } from 'node:fs/promises'
22
22
  import { join } from 'node:path'
23
23
  import { randomUUID } from 'node:crypto'
24
24
 
25
+ import { encodeSegment } from './segment.js'
26
+
25
27
  /** The states a change can be in. Order matters: it is the order they occur. */
26
28
  export const STATES = Object.freeze([
27
29
  'planned',
@@ -48,14 +50,6 @@ export function operationRoot(dshHome, profileId) {
48
50
  return join(dshHome, 'version-manager', 'operations', encodeSegment(profileId))
49
51
  }
50
52
 
51
- /**
52
- * @param {string} value
53
- * @returns {string}
54
- */
55
- function encodeSegment(value) {
56
- return value.replace(/\//g, '%2F').replace(/[^A-Za-z0-9%._@-]/g, '_')
57
- }
58
-
59
53
  /**
60
54
  * Start a record.
61
55
  *
@@ -39,6 +39,7 @@ import { listSkillSnapshots, readSkills, snapshotSkill } from './skills.js'
39
39
  import { previewSkillRestore, restoreSkillSnapshot, skillRestoreRefusal } from './skill-restore.js'
40
40
  import { TERMINAL, beginOperation, listOperations, transition, unresolved } from './operations.js'
41
41
  import {
42
+ SNAPSHOT_KEEP,
42
43
  deleteSnapshot,
43
44
  fingerprintTree,
44
45
  listSnapshots,
@@ -202,7 +203,19 @@ export async function buildOverview(ctx) {
202
203
  })
203
204
  row.compatibility.detail = typeof row.loadError === 'string' ? row.loadError : null
204
205
 
205
- row.snapshots = (await listSnapshots(profile.home, profile.id, row.targetId)).map(summarise)
206
+ const stored = await listSnapshots(profile.home, profile.id, row.targetId)
207
+ row.snapshots = stored.map(summarise)
208
+ // Retention is reported, not enforced. Nothing here deletes a snapshot: an
209
+ // older one is still restorable, so the panel has to say how many are past
210
+ // the comfortable limit rather than let the list grow in silence.
211
+ const beyond = snapshotsBeyondRetention(stored)
212
+ row.retention = {
213
+ limit: SNAPSHOT_KEEP,
214
+ stored: stored.length,
215
+ beyondLimit: beyond.length,
216
+ oldestBeyond: beyond.length === 0 ? null : summarise(beyond[0]),
217
+ pruning: 'manual',
218
+ }
206
219
  }
207
220
 
208
221
  const operations = await listOperations(profile.home, profile.id, 30)
@@ -1120,6 +1133,71 @@ async function readSnapshotDocument(dshHome, profileId, targetId, file) {
1120
1133
 
1121
1134
  export { snapshotsBeyondRetention, deleteSnapshot }
1122
1135
 
1136
+ /**
1137
+ * Delete the snapshots past the retention limit for one target.
1138
+ *
1139
+ * The plugin never runs this on its own: removing the way back is a decision
1140
+ * the user makes, one target at a time, and the number of files that will go is
1141
+ * stated in the confirmation before the call is sent. Everything up to and
1142
+ * including the newest `SNAPSHOT_KEEP` snapshots stays.
1143
+ *
1144
+ * @param {any} ctx
1145
+ * @param {{ targetId?: string }} body
1146
+ * @returns {Promise<{ status: number, body: object }>}
1147
+ */
1148
+ export async function pruneSnapshots(ctx, body) {
1149
+ const profile = readProfileContext(ctx)
1150
+ if (profile.home === null || profile.id === 'unknown') {
1151
+ return { status: 409, body: { error: 'profile-identity-unknown' } }
1152
+ }
1153
+ if (typeof body.targetId !== 'string' || body.targetId === '') {
1154
+ return { status: 400, body: { error: 'missing-target' } }
1155
+ }
1156
+
1157
+ const stored = await listSnapshots(profile.home, profile.id, body.targetId)
1158
+ const beyond = snapshotsBeyondRetention(stored)
1159
+ if (beyond.length === 0) {
1160
+ return {
1161
+ status: 200,
1162
+ body: {
1163
+ ok: true,
1164
+ targetId: body.targetId,
1165
+ removed: [],
1166
+ limit: SNAPSHOT_KEEP,
1167
+ stored: stored.length,
1168
+ note: `Nothing to remove: ${stored.length} snapshot(s) is within the ${SNAPSHOT_KEEP} kept per target.`,
1169
+ },
1170
+ }
1171
+ }
1172
+
1173
+ const removed = []
1174
+ const kept = []
1175
+ for (const snapshot of beyond) {
1176
+ // `deleteSnapshot` re-validates the file name; a listing is not a promise
1177
+ // that the name is safe to join onto a path.
1178
+ if (await deleteSnapshot(profile.home, profile.id, body.targetId, snapshot.file)) {
1179
+ removed.push(snapshot.file)
1180
+ } else {
1181
+ kept.push(snapshot.file)
1182
+ }
1183
+ }
1184
+
1185
+ const remaining = await listSnapshots(profile.home, profile.id, body.targetId)
1186
+ return {
1187
+ status: 200,
1188
+ body: {
1189
+ ok: kept.length === 0,
1190
+ targetId: body.targetId,
1191
+ removed,
1192
+ failed: kept,
1193
+ limit: SNAPSHOT_KEEP,
1194
+ stored: remaining.length,
1195
+ note:
1196
+ 'Only snapshots past the retention limit were removed. Any snapshot still listed can still be restored.',
1197
+ },
1198
+ }
1199
+ }
1200
+
1123
1201
  /**
1124
1202
  * Register every route on the host webserver.
1125
1203
  *
@@ -1329,6 +1407,7 @@ export function registerRoutes(ctx, scope) {
1329
1407
  writeRoute('/skills/snapshot', async (_request, _response, body) => takeSkillSnapshot(ctx, body))
1330
1408
  writeRoute('/skills/restore', async (_request, _response, body) => restoreSkillRoute(ctx, body))
1331
1409
  writeRoute('/snapshot', async (_request, _response, body) => takeSnapshot(ctx, body))
1410
+ writeRoute('/snapshots/prune', async (_request, _response, body) => pruneSnapshots(ctx, body))
1332
1411
  writeRoute('/update', async (_request, _response, body) => runUpdate(ctx, body))
1333
1412
  writeRoute('/restore', async (_request, _response, body) => restoreSnapshot(ctx, body))
1334
1413
 
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Turning a name from the host into one path segment, safely.
3
+ *
4
+ * Profile ids and package names become directory names under
5
+ * `<DSH_HOME>/version-manager/`. Most of them are already usable as-is, so the
6
+ * encoding stays conservative: only characters that would break a path are
7
+ * replaced, and a name that was fine yesterday lands in the same directory
8
+ * today. Changing the layout for ordinary names would strand every snapshot
9
+ * already on disk.
10
+ *
11
+ * The case worth spelling out is `.` and `..`. Replacing `/` is not enough,
12
+ * because `path.join(root, '..')` walks *up*, out of the plugin's own
13
+ * directory. A segment that is nothing but dots is therefore encoded outright.
14
+ * This cannot happen for a profile the CLI created, and it costs three lines to
15
+ * make sure it cannot happen for one it did not.
16
+ *
17
+ * @module dsh-version-manager/lib/host/segment
18
+ */
19
+
20
+ /**
21
+ * @param {unknown} value
22
+ * @returns {string}
23
+ */
24
+ export function encodeSegment(value) {
25
+ const text = typeof value === 'string' ? value : String(value ?? '')
26
+ const encoded = text.replace(/\//g, '%2F').replace(/[^A-Za-z0-9%._@-]/g, '_')
27
+ if (encoded === '') return '_'
28
+ // `.` and `..` (and `...`, which Windows will not keep either) are the only
29
+ // encodings that still mean something to a filesystem.
30
+ if (/^\.+$/.test(encoded)) return encoded.replace(/\./g, '%2E')
31
+ return encoded
32
+ }
33
+
34
+ /**
35
+ * Accept a name as a path segment, or say no.
36
+ *
37
+ * Skill names are directory names reported by the host's own catalog, and they
38
+ * are legitimately non-ASCII — a snapshot directory called `office` and one
39
+ * called `离线诊断` are both fine. Encoding those into ASCII would move every
40
+ * existing snapshot to a new directory, so this path validates instead of
41
+ * rewriting: a name that cannot be a single path segment is refused rather
42
+ * than approximated into one.
43
+ *
44
+ * @param {unknown} value
45
+ * @returns {string | null} the name, unchanged, or null when it is not usable
46
+ */
47
+ export function safeSegment(value) {
48
+ if (typeof value !== 'string' || value === '') return null
49
+ if (value === '.' || value === '..') return null
50
+ if (value.includes('/') || value.includes('\\')) return null
51
+ if (value.includes('\0')) return null
52
+ return value
53
+ }
@@ -31,6 +31,7 @@ import { cp, mkdir, readFile, readdir, rename, rm } from 'node:fs/promises'
31
31
  import { dirname, join, sep } from 'node:path'
32
32
 
33
33
  import { fingerprintTree } from './snapshot-store.js'
34
+ import { encodeSegment, safeSegment } from './segment.js'
34
35
  import { directoryState, listSkillSnapshots, readGitState, snapshotSkill } from './skills.js'
35
36
 
36
37
  /**
@@ -40,7 +41,11 @@ import { directoryState, listSkillSnapshots, readGitState, snapshotSkill } from
40
41
  * @returns {string}
41
42
  */
42
43
  function skillRoot(dshHome, profileId, name) {
43
- return join(dshHome, 'version-manager', 'skills', profileId, name)
44
+ // A skill name reaches this from a request body as well as from the catalog,
45
+ // and `..` here would walk out of the snapshot store and read somebody else's
46
+ // files. The caller validates first; this is the second lock on the same door.
47
+ const segment = safeSegment(name) ?? encodeSegment(name)
48
+ return join(dshHome, 'version-manager', 'skills', profileId, segment)
44
49
  }
45
50
 
46
51
  /**
@@ -17,6 +17,7 @@ import { cp, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises'
17
17
  import { join, relative } from 'node:path'
18
18
 
19
19
  import { fingerprintTree } from './snapshot-store.js'
20
+ import { safeSegment } from './segment.js'
20
21
 
21
22
  const GIT_TIMEOUT_MS = 5000
22
23
  const MAX_SKILL_FILES = 5000
@@ -222,8 +223,10 @@ function emptyGit() {
222
223
  */
223
224
  export async function snapshotSkill(input) {
224
225
  const { dshHome, profileId, name, directory, git, reason } = input
226
+ const segment = safeSegment(name)
227
+ if (segment === null) throw new Error(`A skill snapshot needs a plain name, not ${JSON.stringify(name)}`)
225
228
  const stamp = new Date().toISOString().replace(/[:.]/g, '-')
226
- const root = join(dshHome, 'version-manager', 'skills', profileId, name)
229
+ const root = join(dshHome, 'version-manager', 'skills', profileId, segment)
227
230
  const directoryCopy = join(root, `${stamp}-files`)
228
231
  await mkdir(root, { recursive: true })
229
232
 
@@ -270,7 +273,9 @@ export async function snapshotSkill(input) {
270
273
  * @param {string} name
271
274
  */
272
275
  export async function listSkillSnapshots(dshHome, profileId, name) {
273
- const root = join(dshHome, 'version-manager', 'skills', profileId, name)
276
+ const segment = safeSegment(name)
277
+ if (segment === null) return []
278
+ const root = join(dshHome, 'version-manager', 'skills', profileId, segment)
274
279
  let entries
275
280
  try {
276
281
  entries = await readdir(root)
@@ -24,6 +24,8 @@ import { createHash, randomUUID } from 'node:crypto'
24
24
  import { mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
25
25
  import { join } from 'node:path'
26
26
 
27
+ import { encodeSegment } from './segment.js'
28
+
27
29
  /** Bumped whenever the shape below changes in a way old readers cannot read. */
28
30
  export const SNAPSHOT_SCHEMA = 1
29
31
 
@@ -34,12 +36,15 @@ export const SNAPSHOT_KEEP = 20
34
36
  * A filename-safe form of a package name.
35
37
  *
36
38
  * `@scope/name` would otherwise create a directory, and a name is not a path.
39
+ * The encoding itself lives in `segment.js` so that the four places that turn a
40
+ * host-supplied name into a directory cannot drift apart; `.` and `..` are the
41
+ * cases it exists for.
37
42
  *
38
43
  * @param {string} targetId
39
44
  * @returns {string}
40
45
  */
41
46
  export function encodeTarget(targetId) {
42
- return targetId.replace(/\//g, '%2F').replace(/[^A-Za-z0-9%._@-]/g, '_')
47
+ return encodeSegment(targetId)
43
48
  }
44
49
 
45
50
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-version-manager",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
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",