dsh-config-manager 0.8.2 → 0.9.0

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.
Files changed (345) hide show
  1. package/lib/adapters/mcp.js +42 -13
  2. package/lib/adapters/messages.d.ts +1 -0
  3. package/lib/adapters/messages.js +2 -0
  4. package/lib/adapters/patch-key-guard.d.ts +23 -0
  5. package/lib/adapters/patch-key-guard.js +13 -0
  6. package/lib/adapters/plugin-data.d.ts +19 -5
  7. package/lib/adapters/plugin-data.js +76 -22
  8. package/lib/adapters/plugins.d.ts +14 -1
  9. package/lib/adapters/plugins.js +147 -4
  10. package/lib/cli/actions.d.ts +7 -105
  11. package/lib/cli/actions.js +16 -172
  12. package/lib/cli/control-state.d.ts +54 -0
  13. package/lib/cli/control-state.js +107 -0
  14. package/lib/cli/index.js +14 -0
  15. package/lib/cli/write-gates.d.ts +61 -0
  16. package/lib/cli/write-gates.js +110 -0
  17. package/lib/client.d.ts +104 -49
  18. package/lib/client.js +12536 -12006
  19. package/lib/core/backup.d.ts +0 -4
  20. package/lib/core/backup.js +21 -4
  21. package/lib/core/boot-rescue.d.ts +1 -1
  22. package/lib/core/boot-rescue.js +12 -1
  23. package/lib/core/boot-safety.js +37 -2
  24. package/lib/core/conflict-decisions.js +2 -1
  25. package/lib/core/exporter.js +22 -1
  26. package/lib/core/journal.d.ts +54 -4
  27. package/lib/core/journal.js +158 -35
  28. package/lib/core/local-plugin-host.d.ts +29 -0
  29. package/lib/core/local-plugin-host.js +55 -48
  30. package/lib/core/messages.d.ts +7 -0
  31. package/lib/core/messages.js +14 -0
  32. package/lib/core/migration-history.js +16 -9
  33. package/lib/core/model-tools.d.ts +2 -2
  34. package/lib/core/model-tools.js +14 -2
  35. package/lib/core/patch-secret-guard.d.ts +49 -0
  36. package/lib/core/patch-secret-guard.js +164 -0
  37. package/lib/core/reconcile.d.ts +8 -0
  38. package/lib/core/reconcile.js +18 -3
  39. package/lib/core/reinstall.d.ts +2 -0
  40. package/lib/core/reinstall.js +6 -2
  41. package/lib/core/restore.js +31 -6
  42. package/lib/core/section-sanitize.d.ts +32 -0
  43. package/lib/core/section-sanitize.js +13 -0
  44. package/lib/core/snapshot-diff.d.ts +30 -0
  45. package/lib/core/snapshot-diff.js +56 -20
  46. package/lib/core/startup-barrier.js +8 -2
  47. package/lib/core/types.d.ts +22 -0
  48. package/lib/core/update-check.js +51 -2
  49. package/lib/foreign/kernel.js +9 -2
  50. package/lib/foreign/read-claude-plugins.js +29 -11
  51. package/lib/foreign/read-dsh.js +31 -2
  52. package/lib/foreign/session-ir.js +50 -9
  53. package/lib/foreign/session-read.d.ts +8 -0
  54. package/lib/foreign/session-read.js +26 -0
  55. package/lib/index.d.ts +1 -1
  56. package/lib/index.js +1 -1
  57. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  58. package/lib/profiles/dsh-profile-io.js +27 -0
  59. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  60. package/lib/profiles/dsh-profile-manager.js +45 -4
  61. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  62. package/lib/profiles/dsh-profile-runtime.js +16 -3
  63. package/lib/profiles/process-control.d.ts +18 -1
  64. package/lib/profiles/process-control.js +25 -1
  65. package/lib/routes/profiles.js +2 -1
  66. package/lib/routes/sync.js +13 -1
  67. package/lib/schema/types.d.ts +11 -0
  68. package/lib/security/redaction.js +22 -6
  69. package/lib/sync/autosync-repeat.d.ts +27 -0
  70. package/lib/sync/autosync-repeat.js +23 -0
  71. package/lib/sync/autosync-scheduler.d.ts +34 -1
  72. package/lib/sync/autosync-scheduler.js +151 -43
  73. package/lib/sync/baseline-heal.js +7 -0
  74. package/lib/sync/baseline-record.d.ts +67 -0
  75. package/lib/sync/baseline-record.js +74 -0
  76. package/lib/sync/blob-store.js +13 -0
  77. package/lib/sync/content-diff.d.ts +39 -0
  78. package/lib/sync/content-diff.js +46 -0
  79. package/lib/sync/git/git-transport.d.ts +32 -1
  80. package/lib/sync/git/git-transport.js +146 -26
  81. package/lib/sync/github-auth.d.ts +17 -1
  82. package/lib/sync/github-auth.js +37 -1
  83. package/lib/sync/merge-apply-plan.d.ts +38 -0
  84. package/lib/sync/merge-apply-plan.js +76 -0
  85. package/lib/sync/messages.d.ts +1 -0
  86. package/lib/sync/messages.js +2 -0
  87. package/lib/sync/pending-merge.d.ts +34 -0
  88. package/lib/sync/pending-merge.js +53 -0
  89. package/lib/sync/s3/s3-transport.d.ts +14 -2
  90. package/lib/sync/s3/s3-transport.js +72 -48
  91. package/lib/sync/sync-engine.d.ts +23 -40
  92. package/lib/sync/sync-engine.js +115 -132
  93. package/lib/sync/sync-history.d.ts +7 -0
  94. package/lib/sync/sync-state.d.ts +28 -0
  95. package/lib/sync/sync-state.js +20 -0
  96. package/lib/sync/transport.d.ts +12 -3
  97. package/lib/sync/transport.js +13 -4
  98. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  99. package/lib/sync/webdav/webdav-transport.js +81 -40
  100. package/lib/ui/commands.js +5 -11
  101. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  102. package/lib/ui/dsh-profiles-view.js +9 -5
  103. package/lib/ui/i18n.d.ts +2 -1
  104. package/lib/ui/i18n.js +4 -2
  105. package/lib/ui/menu-placement.js +1 -1
  106. package/lib/ui/migration-consult-view.d.ts +11 -0
  107. package/lib/ui/migration-consult-view.js +15 -0
  108. package/lib/ui/overview-view.d.ts +7 -0
  109. package/lib/ui/overview-view.js +3 -0
  110. package/lib/ui/report.d.ts +9 -0
  111. package/lib/ui/report.js +17 -4
  112. package/lib/ui/selection-model.d.ts +8 -0
  113. package/lib/ui/selection-model.js +16 -0
  114. package/lib/utils/patch-yaml.d.ts +39 -1
  115. package/lib/utils/patch-yaml.js +82 -2
  116. package/lib/utils/paths.d.ts +13 -0
  117. package/lib/utils/paths.js +35 -0
  118. package/lib/utils/workdir-lock.js +18 -3
  119. package/package.json +2 -1
  120. package/src/adapters/mcp.test.ts +29 -0
  121. package/src/adapters/mcp.ts +43 -12
  122. package/src/adapters/messages.ts +2 -0
  123. package/src/adapters/patch-key-guard.ts +29 -0
  124. package/src/adapters/plugin-data.test.ts +126 -0
  125. package/src/adapters/plugin-data.ts +97 -26
  126. package/src/adapters/plugins.test.ts +288 -0
  127. package/src/adapters/plugins.ts +141 -4
  128. package/src/cli/actions.test.ts +74 -1
  129. package/src/cli/actions.ts +27 -246
  130. package/src/cli/control-state.ts +143 -0
  131. package/src/cli/index.ts +18 -0
  132. package/src/cli/web/web.test.ts +27 -0
  133. package/src/cli/write-gates.ts +149 -0
  134. package/src/client/about/AboutPanel.tsx +7 -6
  135. package/src/client/about/release-notes-view.test.ts +17 -0
  136. package/src/client/about/release-notes-view.ts +49 -24
  137. package/src/client/chat/ChatEntryView.tsx +2 -2
  138. package/src/client/chat/rollback-entry-view.ts +6 -1
  139. package/src/client/common/CommandPalette.tsx +6 -3
  140. package/src/client/common/ConfirmDialog.tsx +29 -12
  141. package/src/client/common/ContentPicker.tsx +13 -12
  142. package/src/client/common/Modal.tsx +12 -5
  143. package/src/client/common/MoreMenu.tsx +4 -1
  144. package/src/client/common/RunsCenter.tsx +103 -32
  145. package/src/client/common/Select.tsx +2 -2
  146. package/src/client/common/floating-bounds.ts +1 -1
  147. package/src/client/common/floating-units.test.ts +1 -2
  148. package/src/client/common/plan-text-redaction.test.ts +188 -3
  149. package/src/client/common/runs-center-guard.test.ts +60 -0
  150. package/src/client/common/runs-center-view.test.ts +128 -0
  151. package/src/client/common/runs-center-view.ts +96 -0
  152. package/src/client/common/section-title-action.test.ts +66 -0
  153. package/src/client/common/ui.tsx +93 -30
  154. package/src/client/config-manager.module.css +1507 -272
  155. package/src/client/consult/ConsultCard.tsx +7 -6
  156. package/src/client/environment/EnvironmentPanel.tsx +20 -21
  157. package/src/client/environment/maintenance/DiskUsageCard.tsx +65 -91
  158. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  159. package/src/client/export/ExportView.tsx +7 -16
  160. package/src/client/history/HistoryPanel.tsx +88 -28
  161. package/src/client/history/history-locales.ts +3 -3
  162. package/src/client/home/BackupScheduleCard.tsx +35 -30
  163. package/src/client/home/HomePanel.tsx +45 -10
  164. package/src/client/import/ConflictList.tsx +13 -13
  165. package/src/client/import/ForeignImportView.tsx +7 -6
  166. package/src/client/import/ImportWizardView.tsx +2 -3
  167. package/src/client/import/PathMappingForm.tsx +4 -4
  168. package/src/client/import/PathPickerDialog.tsx +2 -1
  169. package/src/client/import/import-wizard-steps.tsx +51 -39
  170. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  171. package/src/client/import/use-import-wizard-controller.ts +116 -22
  172. package/src/client/library/ArtifactRow.tsx +2 -2
  173. package/src/client/library/BackupInspectView.tsx +19 -15
  174. package/src/client/library/LibraryActions.tsx +56 -16
  175. package/src/client/library/LibraryPanel.tsx +7 -7
  176. package/src/client/library/RestorePlanView.tsx +13 -8
  177. package/src/client/locales/about.ts +0 -2
  178. package/src/client/locales/backup.ts +10 -12
  179. package/src/client/locales/common.ts +2 -0
  180. package/src/client/locales/export.ts +5 -12
  181. package/src/client/locales/foreign.ts +2 -2
  182. package/src/client/locales/import.ts +3 -2
  183. package/src/client/locales/overview.ts +4 -0
  184. package/src/client/locales/profiles.ts +32 -4
  185. package/src/client/locales/restore.ts +0 -2
  186. package/src/client/locales/sessions.ts +0 -2
  187. package/src/client/locales/shell.ts +2 -2
  188. package/src/client/market/MarketPanel.tsx +38 -20
  189. package/src/client/market/MyConfigsList.tsx +34 -32
  190. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  191. package/src/client/market/MyConfigsView.tsx +5 -5
  192. package/src/client/market/MyConfigsWizard.tsx +7 -12
  193. package/src/client/market/market-locales.ts +0 -6
  194. package/src/client/market/my-configs-split.test.ts +2 -1
  195. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  196. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  197. package/src/client/recovery/RecoveryPanel.tsx +31 -16
  198. package/src/client/recovery/RollbackCard.tsx +58 -16
  199. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  200. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  201. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  202. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  203. package/src/client/recovery/recovery-locales.ts +12 -8
  204. package/src/client/run-store.test.ts +30 -0
  205. package/src/client/run-store.ts +21 -1
  206. package/src/client/sync/AddChannelCard.tsx +65 -0
  207. package/src/client/sync/AutosyncCard.tsx +182 -108
  208. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  209. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  210. package/src/client/sync/MergePreviewView.tsx +3 -5
  211. package/src/client/sync/PushReportSections.tsx +35 -0
  212. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  213. package/src/client/sync/SyncConfirmView.tsx +3 -3
  214. package/src/client/sync/SyncLogList.tsx +16 -5
  215. package/src/client/sync/SyncPanel.tsx +153 -159
  216. package/src/client/sync/SyncProbeRow.tsx +5 -7
  217. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  218. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  219. package/src/client/sync/SyncSettingsDialog.tsx +304 -0
  220. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  221. package/src/client/sync/WorkDirCard.tsx +2 -4
  222. package/src/client/sync/config-clear-guard.test.ts +94 -0
  223. package/src/client/sync/config-clear-guard.ts +98 -0
  224. package/src/client/sync/config-dirty.test.ts +91 -0
  225. package/src/client/sync/config-dirty.ts +88 -0
  226. package/src/client/sync/history-model.test.ts +2 -0
  227. package/src/client/sync/history-model.ts +3 -0
  228. package/src/client/sync/merge-request.ts +20 -0
  229. package/src/client/sync/sync-api.ts +12 -0
  230. package/src/client/sync/sync-locales.ts +87 -47
  231. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  232. package/src/client/sync/sync-view.test.ts +20 -0
  233. package/src/client/sync/sync-view.ts +42 -4
  234. package/src/core/backup.test.ts +61 -1
  235. package/src/core/backup.ts +21 -4
  236. package/src/core/boot-rescue.test.ts +35 -0
  237. package/src/core/boot-rescue.ts +13 -2
  238. package/src/core/boot-safety.test.ts +25 -0
  239. package/src/core/boot-safety.ts +37 -2
  240. package/src/core/conflict-decisions.ts +2 -1
  241. package/src/core/exporter.ts +21 -1
  242. package/src/core/journal.test.ts +183 -0
  243. package/src/core/journal.ts +163 -25
  244. package/src/core/local-plugin-host.test.ts +68 -2
  245. package/src/core/local-plugin-host.ts +31 -4
  246. package/src/core/messages.ts +14 -0
  247. package/src/core/migration-history.test.ts +27 -0
  248. package/src/core/migration-history.ts +12 -4
  249. package/src/core/model-tools.test.ts +67 -0
  250. package/src/core/model-tools.ts +16 -4
  251. package/src/core/patch-secret-guard.test.ts +110 -0
  252. package/src/core/patch-secret-guard.ts +176 -0
  253. package/src/core/reconcile.ts +32 -4
  254. package/src/core/reinstall.ts +8 -2
  255. package/src/core/restore.ts +32 -7
  256. package/src/core/section-sanitize.ts +37 -0
  257. package/src/core/snapshot-diff.test.ts +73 -1
  258. package/src/core/snapshot-diff.ts +66 -21
  259. package/src/core/startup-barrier.test.ts +64 -0
  260. package/src/core/startup-barrier.ts +8 -2
  261. package/src/core/types.ts +27 -1
  262. package/src/core/update-check.test.ts +40 -0
  263. package/src/core/update-check.ts +53 -2
  264. package/src/foreign/claude-code.test.ts +5 -0
  265. package/src/foreign/claude-plugins.test.ts +57 -0
  266. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  267. package/src/foreign/dsh.test.ts +23 -0
  268. package/src/foreign/kernel.ts +9 -2
  269. package/src/foreign/read-claude-plugins.ts +32 -11
  270. package/src/foreign/read-dsh.ts +33 -2
  271. package/src/foreign/session-ir.test.ts +67 -0
  272. package/src/foreign/session-ir.ts +54 -14
  273. package/src/foreign/session-read.ts +23 -0
  274. package/src/index.ts +1 -1
  275. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  276. package/src/profiles/dsh-profile-io.ts +29 -0
  277. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  278. package/src/profiles/dsh-profile-manager.ts +53 -5
  279. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  280. package/src/profiles/dsh-profile-runtime.ts +17 -3
  281. package/src/profiles/process-control.test.ts +97 -0
  282. package/src/profiles/process-control.ts +28 -1
  283. package/src/routes/profiles.ts +2 -1
  284. package/src/routes/sync.ts +13 -1
  285. package/src/schema/types.ts +16 -1
  286. package/src/security/redaction.test.ts +31 -0
  287. package/src/security/redaction.ts +23 -6
  288. package/src/sync/autosync-repeat.test.ts +58 -0
  289. package/src/sync/autosync-repeat.ts +55 -0
  290. package/src/sync/autosync-scheduler.test.ts +417 -0
  291. package/src/sync/autosync-scheduler.ts +154 -41
  292. package/src/sync/baseline-heal.ts +6 -0
  293. package/src/sync/baseline-record.ts +135 -0
  294. package/src/sync/blob-store.test.ts +16 -0
  295. package/src/sync/blob-store.ts +13 -0
  296. package/src/sync/content-diff.test.ts +95 -0
  297. package/src/sync/content-diff.ts +79 -0
  298. package/src/sync/git/git-transport.test.ts +151 -4
  299. package/src/sync/git/git-transport.ts +143 -27
  300. package/src/sync/github-auth.test.ts +26 -1
  301. package/src/sync/github-auth.ts +37 -1
  302. package/src/sync/merge-apply-plan.ts +117 -0
  303. package/src/sync/messages.ts +2 -0
  304. package/src/sync/pending-merge.ts +77 -0
  305. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  306. package/src/sync/s3/s3-transport.ts +76 -42
  307. package/src/sync/sync-config.test.ts +39 -12
  308. package/src/sync/sync-device-identity.test.ts +3 -0
  309. package/src/sync/sync-engine.test.ts +465 -12
  310. package/src/sync/sync-engine.ts +130 -135
  311. package/src/sync/sync-history.ts +7 -0
  312. package/src/sync/sync-state.ts +48 -0
  313. package/src/sync/transport.test.ts +13 -1
  314. package/src/sync/transport.ts +12 -4
  315. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  316. package/src/sync/webdav/webdav-transport.ts +86 -34
  317. package/src/ui/commands.test.ts +11 -0
  318. package/src/ui/commands.ts +5 -14
  319. package/src/ui/dsh-profiles-view.test.ts +16 -0
  320. package/src/ui/dsh-profiles-view.ts +11 -5
  321. package/src/ui/i18n.ts +4 -2
  322. package/src/ui/menu-placement.ts +1 -1
  323. package/src/ui/migration-consult-view.test.ts +20 -1
  324. package/src/ui/migration-consult-view.ts +17 -0
  325. package/src/ui/overview-view.ts +10 -0
  326. package/src/ui/report.test.ts +25 -1
  327. package/src/ui/report.ts +15 -4
  328. package/src/ui/selection-model.test.ts +15 -1
  329. package/src/ui/selection-model.ts +18 -0
  330. package/src/utils/js-yaml4.d.ts +35 -0
  331. package/src/utils/patch-yaml.test.ts +207 -1
  332. package/src/utils/patch-yaml.ts +98 -2
  333. package/src/utils/paths.test.ts +14 -1
  334. package/src/utils/paths.ts +35 -0
  335. package/src/utils/workdir-lock.test.ts +69 -0
  336. package/src/utils/workdir-lock.ts +17 -3
  337. package/lib/ui/path-mapping.d.ts +0 -38
  338. package/lib/ui/path-mapping.js +0 -75
  339. package/src/client/common/InfoHint.tsx +0 -289
  340. package/src/client/common/info-hint-guard.test.ts +0 -1119
  341. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  342. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  343. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  344. package/src/ui/path-mapping.test.ts +0 -67
  345. package/src/ui/path-mapping.ts +0 -103
@@ -22,7 +22,7 @@
22
22
  * detail = too-large / max-logs-reached / session-byte-budget),绝不静默截断。
23
23
  */
24
24
  import { envValue, joinFor, normalizePlatform } from './platform-paths.ts';
25
- import { listDirNames, listFileNames, readBytesSafe, statOrNull } from './session-read.ts';
25
+ import { listDirNames, listFileNames, readBytesPrefixSafe, readBytesSafe, statOrNull } from './session-read.ts';
26
26
  import { readLogHeaderFromBytes } from '../utils/session-log.ts';
27
27
  import type { SessionLogHeader } from '../utils/session-log.ts';
28
28
  import type { RootProbeOptions, SessionReadOutcome } from './session-source.ts';
@@ -38,6 +38,13 @@ export type DshGeneration = 'v3' | 'v4';
38
38
  const DEFAULT_MAX_LOGS = 2000;
39
39
  const DEFAULT_MAX_FILE_BYTES = 32 * 1024 * 1024;
40
40
  const DEFAULT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
41
+
42
+ /**
43
+ * 代次嗅探窗口(审计 P7-7):header 是第一行 JSON,64 KiB 覆盖任何真实 cwd/标题组合
44
+ * (首行实测 < 1 KiB)。窗口内解析不出 header 时退回整读,因此这个值只影响「能不能提前
45
+ * 跳过非目标代次」,不会改变任何判定结果。
46
+ */
47
+ const HEADER_SNIFF_BYTES = 64 * 1024;
41
48
  const HEADER_WINDOW_BYTES = 64 * 1024;
42
49
 
43
50
  export interface DshResolvedHome { readonly home: string; readonly overridden: boolean }
@@ -158,6 +165,23 @@ export async function readDshLogs(opts: DshReadOptions): Promise<SessionReadOutc
158
165
  scanned += 1;
159
166
  if (st.size > maxFileBytes) { truncated = truncated ?? 'too-large'; continue; }
160
167
  if (bytesRead + st.size > maxTotalBytes) { truncated = 'byte-budget'; break outer; }
168
+ /**
169
+ * 代次嗅探(审计 P7-7):日志的 header 就在第一行,而 dsh 与 dsh4 两代并存的机器上
170
+ * 一半文件属于「非目标代次」——旧实现为了看那 1 KB header 把 31 MiB 的日志整份读进来
171
+ * 再丢掉。现在先只读头部窗口,判定为别的代次就直接 countedContinue,一次整读都不做。
172
+ *
173
+ * 退化路径保持旧行为:头部窗口解析不出 header(首行比窗口还长 / 读不出)时仍整读一次,
174
+ * 让 log-header-unreadable / log-read-error 这些既有码的触发条件逐字不变。
175
+ */
176
+ const head = await readBytesPrefixSafe(abs, HEADER_SNIFF_BYTES);
177
+ if (head !== null) {
178
+ const sniffed = dshHeaderOfLogBytes(head);
179
+ const sniffedGeneration = sniffed === undefined ? undefined : dshGenerationOfVersion(sniffed.version);
180
+ if (sniffedGeneration !== undefined && sniffedGeneration !== opts.generation) {
181
+ otherGeneration += 1;
182
+ continue;
183
+ }
184
+ }
161
185
  const data = await readBytesSafe(abs, maxFileBytes);
162
186
  if (data === null) {
163
187
  findings.push({ code: 'source-unreadable', origin: name, detail: 'log-read-error' });
@@ -178,7 +202,14 @@ export async function readDshLogs(opts: DshReadOptions): Promise<SessionReadOutc
178
202
  findings.push({ code: 'source-unreadable', origin: name, detail: 'log-header-incomplete' });
179
203
  continue;
180
204
  }
181
- if (seen.has(header.id)) continue;
205
+ if (seen.has(header.id)) {
206
+ /**
207
+ * 同一 id 出现在两个会话目录(复制/迁移残留):只保留第一个,但**必须留码** ——
208
+ * 静默丢会让「导入少了一条会话」在计划里无从解释(本文件顶部第 21-22 行的硬约束)。
209
+ */
210
+ findings.push({ code: 'session-id-conflict', origin: header.id, detail: 'duplicate-session-id' });
211
+ continue;
212
+ }
182
213
  seen.add(header.id);
183
214
  bytesRead += data.length;
184
215
  files.push({ id: header.id, cwd: header.cwd, version: header.version, name, data });
@@ -252,3 +252,70 @@ test('未闭合工具调用:不伪造 result、callId 非空、后续事件与
252
252
  assert.equal(rows.filter((r) => r.type === 'user/message').length, 2, '中断之后的消息不得被吞掉');
253
253
  assert.equal(rows[rows.length - 1]?.type, 'user/message');
254
254
  });
255
+
256
+ /* ---------------- 工具结果的三种「静默丢失」路径(2026-11-14 审计 P7-1/2/4/5) ---------------- */
257
+
258
+ function synthOf(messages: readonly IrMessage[]): { rows: DshSessionRow[]; stats: SynthesisStats } {
259
+ const s = stats();
260
+ const rows = synthesizeDshRows(
261
+ { id: 's9', cwd: 'D:/proj', createdAt: NOW, records: messages.length, messages },
262
+ { title: '', titleSource: { kind: 'fallback' }, emptyBlocks: [], provider: 'claude-code', reasoningEffort: 'medium', maxTokens: 8192 },
263
+ s,
264
+ NOW,
265
+ );
266
+ return { rows, stats: s };
267
+ }
268
+
269
+ /** P7-1:同一条 user 记录既含 tool_result 又含 text —— 文本必须另发一条 user/message,不能消失且不能无计数。 */
270
+ test('user 记录同时含 tool_result 与 text:文本作为独立 user/message 发出', () => {
271
+ const { rows, stats: s } = synthOf([
272
+ irMessage(irFallbackMessageId(0), 'user', [irTextBlock('开始')], { time: NOW }),
273
+ irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('t1', 'terminal', { command: 'ls' })], { time: NOW + 1 }),
274
+ irMessage(irFallbackMessageId(2), 'user', [irToolResultBlock('t1', 'ok', false), irTextBlock('MARKER-TEXT')], { time: NOW + 2 }),
275
+ ]);
276
+ const humanTexts = rows
277
+ .filter((r) => r.type === 'user/message')
278
+ .map((r) => (r.data as { source: { kind: string }; content: { text?: string }[] }));
279
+ const fromUser = humanTexts.filter((m) => m.source.kind === 'user').flatMap((m) => m.content.map((c) => c.text ?? ''));
280
+ assert.ok(fromUser.join('|').includes('MARKER-TEXT'), '用户文本被静默吞掉了:' + JSON.stringify(rows.map((r) => r.type)));
281
+ assert.equal(s.userMessages, 2, '结果块之后的文本也要计入 userMessages');
282
+ assert.equal(s.toolResults, 1, '同一条记录里的 tool/result 仍必须发出');
283
+ assert.equal(rows.filter((r) => r.type === 'tool/result').length, 1);
284
+ });
285
+
286
+ /** P7-4:非空 id 但不在未决表里 = 悬空引用,必须计数丢弃(不得发指向不存在调用的结果)。 */
287
+ test('tool_result 带未知 id:按 orphan-tool-result 计数,不产出悬空 callId', () => {
288
+ const { rows, stats: s } = synthOf([
289
+ irMessage(irFallbackMessageId(0), 'user', [irTextBlock('开始')], { time: NOW }),
290
+ irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('t1', 'terminal', { command: 'ls' })], { time: NOW + 1 }),
291
+ irMessage(irFallbackMessageId(2), 'user', [irToolResultBlock('t1', 'ok', false), irToolResultBlock('t-unknown', 'x', false)], { time: NOW + 2 }),
292
+ ]);
293
+ const results = rows.filter((r) => r.type === 'tool/result');
294
+ assert.deepEqual(results.map((r) => (r.data as { message: { source: { callId: string } } }).message.source.callId), ['t1']);
295
+ assert.equal(s.ignored['orphan-tool-result'], 1, '悬空 id 必须可见地计数');
296
+ });
297
+
298
+ /** P7-2:缺 id 的结果不得回填到**上一个回合**已闭合的调用上(openCallIds 必须按回合清空)。 */
299
+ test('回合闭合后缺 id 的 tool_result 不回填上一回合的调用', () => {
300
+ const { rows } = synthOf([
301
+ irMessage(irFallbackMessageId(0), 'user', [irTextBlock('turn1')], { time: NOW }),
302
+ irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('turn1-call', 'terminal', { command: 'a' })], { time: NOW + 1 }),
303
+ irMessage(irFallbackMessageId(2), 'user', [irTextBlock('turn2')], { time: NOW + 2 }),
304
+ irMessage(irFallbackMessageId(3), 'assistant', [irToolCallBlock('turn2-call', 'terminal', { command: 'b' })], { time: NOW + 3 }),
305
+ irMessage(irFallbackMessageId(4), 'user', [irToolResultBlock('', 'late', false)], { time: NOW + 4 }),
306
+ ]);
307
+ const result = rows.find((r) => r.type === 'tool/result');
308
+ const callId = (result?.data as { message: { source: { callId: string } } } | undefined)?.message.source.callId;
309
+ assert.equal(callId, 'turn2-call', '缺 id 的结果只能配对当前回合仍未结算的调用,不能跨回合回填');
310
+ });
311
+
312
+ /** P7-5:assistant 记录里携带的 tool_result 无处归位 —— 必须计数(绝不静默丢弃)。 */
313
+ test('assistant 记录携带 tool_result:按 assistant-tool-result 计数', () => {
314
+ const { rows, stats: s } = synthOf([
315
+ irMessage(irFallbackMessageId(0), 'user', [irTextBlock('开始')], { time: NOW }),
316
+ irMessage(irFallbackMessageId(1), 'assistant', [irToolCallBlock('t1', 'terminal', { command: 'ls' }), irToolResultBlock('t1', 'ok', false)], { time: NOW + 1 }),
317
+ ]);
318
+ assert.equal(s.ignored['assistant-tool-result'], 1, '助手记录里的结果块不得无声消失');
319
+ assert.equal(s.toolResults, 0);
320
+ assert.equal(rows.filter((r) => r.type === 'tool/result').length, 0);
321
+ });
@@ -330,6 +330,12 @@ export function synthesizeDshRows(
330
330
  };
331
331
  const closeTurn = (): void => {
332
332
  closeStep();
333
+ /**
334
+ * 回合闭合后再到的结果**不许**回填到本回合的调用上:`openCallIds` 是跨 step 共享的 FIFO,
335
+ * 若不在回合边界清空,下一回合缺 id 的 tool_result 会消费到上一回合已结束的 callId
336
+ * (结果落在 turn N+1、却引用 turn N 的调用,DSH 侧配对不上)。
337
+ */
338
+ openCallIds.length = 0;
333
339
  if (turnOpen) {
334
340
  push('turn/end', now, { turn, reason: { kind: 'completed' } });
335
341
  turnOpen = false;
@@ -344,6 +350,21 @@ export function synthesizeDshRows(
344
350
  });
345
351
  turnOpen = true;
346
352
  };
353
+ /** 发一条**人类** user/message(唯一形状出口:两条路径共用,避免字段漂移) */
354
+ const emitUserMessage = (text: string, at: number, id: string): void => {
355
+ push(
356
+ 'user/message',
357
+ at,
358
+ {
359
+ content: [irTextBlock(text)],
360
+ source: { kind: 'user' },
361
+ role: 'user',
362
+ id,
363
+ },
364
+ 'append',
365
+ );
366
+ stats.userMessages++;
367
+ };
347
368
 
348
369
  for (const message of session.messages) {
349
370
  // time 缺省(源没给可解析时间)→ 用调用方的时间兜底;安全整数校验在 IR 层已完成
@@ -354,6 +375,15 @@ export function synthesizeDshRows(
354
375
  if (message.role === 'assistant') {
355
376
  const text = irTextOfBlocks(blocks);
356
377
  const calls = blocks.filter((b): b is IrToolCallBlock => b.type === 'tool_call');
378
+ /**
379
+ * 助手记录里携带的 tool_result:本分支只消费 text/tool_call,这类结果**无处归位**
380
+ * (opencode 等来源把 call 与 result 写进同一条记录,由 `splitToolResults` 先拆开;
381
+ * 没拆到这里的不能静默消失)。计数后丢弃 —— 绝不产出悬空引用,也绝不无声丢内容。
382
+ */
383
+ const assistantResults = blocks.filter((b): b is IrToolResultBlock => b.type === 'tool_result');
384
+ if (assistantResults.length > 0) {
385
+ irBump(stats.ignored, 'assistant-tool-result', assistantResults.length);
386
+ }
357
387
  const source = message.passthrough?.['source'];
358
388
  const m = irStr((source as Record<string, unknown> | undefined)?.['model']);
359
389
  if (m !== undefined) model = m;
@@ -361,7 +391,8 @@ export function synthesizeDshRows(
361
391
  const providerName = hints.provider === '' ? 'foreign' : hints.provider;
362
392
  const modelName = model === '' ? 'unknown' : model;
363
393
  if (text.trim() === '' && calls.length === 0) {
364
- irBump(stats.ignored, 'assistant-empty');
394
+ // 只有 tool_result 的助手记录已按 assistant-tool-result 计数,不再重复记 assistant-empty
395
+ if (assistantResults.length === 0) irBump(stats.ignored, 'assistant-empty');
365
396
  continue;
366
397
  }
367
398
  if (!turnOpen) openTurn(at);
@@ -468,7 +499,17 @@ export function synthesizeDshRows(
468
499
  callId = next === undefined ? '' : next;
469
500
  } else {
470
501
  const idx = openCallIds.indexOf(callId);
471
- if (idx >= 0) openCallIds.splice(idx, 1);
502
+ if (idx >= 0) {
503
+ openCallIds.splice(idx, 1);
504
+ } else {
505
+ /**
506
+ * 非空 id 但不在未决表里 = 悬空引用(调用已在上一回合闭合,或源侧 id 与真正发出的
507
+ * callId 不同)。与「缺 id 且无未决调用」同口径:计数后丢弃,绝不发指向不存在
508
+ * tool/call 的结果(DSH 侧会按损坏流拒读整条会话)。
509
+ */
510
+ irBump(stats.ignored, 'orphan-tool-result');
511
+ continue;
512
+ }
472
513
  }
473
514
  if (callId === '') {
474
515
  irBump(stats.ignored, 'orphan-tool-result');
@@ -498,6 +539,16 @@ export function synthesizeDshRows(
498
539
  'append',
499
540
  );
500
541
  }
542
+ /**
543
+ * 同一条 user 记录里既有 tool_result 又有 text(Anthropic 形状里很常见:结果块后跟人类补充):
544
+ * 结果先收进当前 step,文本必须**再发一条真正的 user/message** —— 否则这段用户输入
545
+ * 既到不了目标机、也不进 ignored,属于静默丢失。
546
+ */
547
+ const trailing = irTextOfBlocks(blocks);
548
+ if (trailing.trim() !== '') {
549
+ closeTurn();
550
+ emitUserMessage(trailing, at, message.id);
551
+ }
501
552
  messageIndex++;
502
553
  continue;
503
554
  }
@@ -509,18 +560,7 @@ export function synthesizeDshRows(
509
560
  continue;
510
561
  }
511
562
  closeTurn();
512
- push(
513
- 'user/message',
514
- at,
515
- {
516
- content: [irTextBlock(text)],
517
- source: { kind: 'user' },
518
- role: 'user',
519
- id: message.id,
520
- },
521
- 'append',
522
- );
523
- stats.userMessages++;
563
+ emitUserMessage(text, at, message.id);
524
564
  messageIndex++;
525
565
  }
526
566
  closeTurn();
@@ -65,6 +65,29 @@ export async function readBytesSafe(p: string, maxBytes: number = DEFAULT_MAX_FI
65
65
  }
66
66
  }
67
67
 
68
+ /**
69
+ * 只读文件**头部窗口**(审计 P7-7):给「先看 header 再决定要不要整读」的场景用。
70
+ *
71
+ * 与 readBytesSafe 的区别只有一点:不超过 maxBytes 时只取前 maxBytes 字节,而不是整份读。
72
+ * 语义仍守四条硬边界(读不到返回 null、绝不抛、超上限不读)。调用方必须自己处理
73
+ * 「头部窗口不足以判定」的退化路径 —— 不要把它当成整份内容。
74
+ */
75
+ export async function readBytesPrefixSafe(p: string, maxBytes: number): Promise<Uint8Array | null> {
76
+ const st = await statOrNull(p);
77
+ if (st === null || !st.isFile() || maxBytes <= 0) return null;
78
+ let handle: fs.FileHandle | null = null;
79
+ try {
80
+ handle = await fs.open(p, 'r');
81
+ const buf = new Uint8Array(Math.min(maxBytes, st.size));
82
+ const { bytesRead } = await handle.read(buf, 0, buf.byteLength, 0);
83
+ return bytesRead === buf.byteLength ? buf : buf.subarray(0, bytesRead);
84
+ } catch {
85
+ return null;
86
+ } finally {
87
+ if (handle !== null) await handle.close().catch(() => undefined);
88
+ }
89
+ }
90
+
68
91
  export async function readTextSafe(p: string, maxBytes: number = DEFAULT_MAX_FILE_BYTES): Promise<string | null> {
69
92
  const st = await statOrNull(p);
70
93
  if (st === null || !st.isFile() || st.size > maxBytes) return null;
package/src/index.ts CHANGED
@@ -184,7 +184,7 @@ export const name = 'config-manager'
184
184
  export const inject = ['settings', 'credentials']
185
185
 
186
186
  /** Plugin version, kept in sync with package.json ("version"). */
187
- export const PLUGIN_VERSION = '0.8.2'
187
+ export const PLUGIN_VERSION = '0.9.0'
188
188
 
189
189
  /** Plugin own package name — excluded from its own exported plugins list. */
190
190
  const PLUGIN_NAME = 'dsh-config-manager'
@@ -14,12 +14,14 @@
14
14
  */
15
15
  import test from 'node:test'
16
16
  import assert from 'node:assert/strict'
17
- import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
17
+ import { existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs'
18
18
  import { join } from 'node:path'
19
19
  import { tmpdir } from 'node:os'
20
20
 
21
- import { DshProfileManager, rollbackCopiedProfileDir } from './dsh-profile-manager.ts'
21
+ import { DshProfileError, DshProfileManager, rollbackCopiedProfileDir } from './dsh-profile-manager.ts'
22
+ import type { DshProfileManagerOptions } from './dsh-profile-manager.ts'
22
23
  import type { DshProfileCopyMarker } from './dsh-profile-shared.ts'
24
+ import type { AtomicIoSync } from '../utils/atomic-write.ts'
23
25
 
24
26
  /** 磁盘契约字面量:改名即等于把旧版本留下的残留重新变成「查不到」(与 dsh-profile-incomplete-copy.test.ts 同口径)。 */
25
27
  const MARKER = '.dcm-copy-in-progress.json'
@@ -33,14 +35,40 @@ const MARKER_OBJ: DshProfileCopyMarker = {
33
35
  pid: 4242,
34
36
  }
35
37
 
36
- function makeManager(): { mgr: DshProfileManager; home: string; cleanup: () => void } {
38
+ function makeManager(extra: Partial<DshProfileManagerOptions> = {}): { mgr: DshProfileManager; home: string; cleanup: () => void } {
37
39
  const root = mkdtempSync(join(tmpdir(), 'dsh-copy-rollback-'))
38
40
  const home = join(root, 'home')
39
41
  mkdirSync(join(home, 'profiles'), { recursive: true })
40
- const mgr = new DshProfileManager({ homeDir: home, currentProfile: () => 'web' })
42
+ const mgr = new DshProfileManager({ homeDir: home, currentProfile: () => 'web', ...extra })
41
43
  return { mgr, home, cleanup: () => { rmSync(root, { recursive: true, force: true }) } }
42
44
  }
43
45
 
46
+ /**
47
+ * 只让「标记那一次写入」失败:除 open(atomicWriteFileSync 唯一会真的动盘前的最后一步)之外
48
+ * 全部转发真实 fs。用它复现「目录已建好、标记却写不出来」这条窄缝。
49
+ */
50
+ function failingMarkerIo(): AtomicIoSync {
51
+ return {
52
+ mkdir: (dir, opts) => { mkdirSync(dir, { recursive: opts.recursive }) },
53
+ lstat: (target) => {
54
+ try {
55
+ const stat = lstatSync(target)
56
+ return { isSymbolicLink: () => stat.isSymbolicLink(), mode: stat.mode }
57
+ } catch {
58
+ return null
59
+ }
60
+ },
61
+ realpath: (target) => realpathSync(target),
62
+ open: () => { throw new Error('EIO: simulated copy-marker write failure') },
63
+ writeFd: () => {},
64
+ fsyncFd: () => {},
65
+ closeFd: () => {},
66
+ rename: (from, to) => { renameSync(from, to) },
67
+ unlink: (target) => { rmSync(target, { force: true }) },
68
+ fsyncDir: () => {},
69
+ }
70
+ }
71
+
44
72
  /** 造一个「复制中途失败」的目标目录:部分内容 + 标记,**没有 package.json**。 */
45
73
  function writeHalfCopy(home: string, name = 'work-copy'): string {
46
74
  const dir = join(home, 'profiles', name)
@@ -154,3 +182,29 @@ test('#5-D:copy() 失败路径确实走回滚(整体接线)—— 目标
154
182
  cleanup()
155
183
  }
156
184
  })
185
+
186
+ test('#5-E:标记写不出来 ⇒ 连目标目录一起回滚,绝不留「list() 看不到、remove() 报 notFound」的空壳', async () => {
187
+ const { mgr, home, cleanup } = makeManager({ markerIo: failingMarkerIo() })
188
+ try {
189
+ const src = join(home, 'profiles', 'work')
190
+ mkdirSync(src, { recursive: true })
191
+ writeFileSync(join(src, 'package.json'), JSON.stringify({ name: 'dsh-profile-work', dependencies: {} }), 'utf8')
192
+
193
+ const dest = join(home, 'profiles', 'work-copy')
194
+ await assert.rejects(
195
+ mgr.copy('work', 'work-copy'),
196
+ (err: unknown) => err instanceof DshProfileError && err.code === 'copyFailed',
197
+ '标记写失败也是复制失败:必须走统一错误码,不得把底层 fs 错误原样抛给调用方',
198
+ )
199
+
200
+ // 三个视角同时成立,才算没有孤儿:
201
+ // ① 盘上没有那个目录(旧实现会留下一个空目录)
202
+ assert.equal(existsSync(dest), false, '标记写失败必须连目录一起清掉')
203
+ // ② 档案列表里没有它
204
+ assert.deepEqual(mgr.list().map((meta) => meta.name), ['work'], '列表里只有源档案')
205
+ // ③ 残留列举里也没有它(残留应该是「有标记的半截副本」,而不是空壳)
206
+ assert.deepEqual(mgr.listIncompleteCopies(), [])
207
+ } finally {
208
+ cleanup()
209
+ }
210
+ })
@@ -11,6 +11,7 @@
11
11
  * `sanitizeFilePart`(同一正则)。
12
12
  */
13
13
  import { readFileSync } from 'node:fs'
14
+ import { createHash } from 'node:crypto'
14
15
 
15
16
  /**
16
17
  * 读文本文件;不可读返回 **null** —— 语义差异由调用方显式表达(**不得把 null 统一成 ''**):
@@ -29,3 +30,31 @@ export function readTextSafe(path: string): string | null {
29
30
  export function sanitizeFilePart(name: string): string {
30
31
  return name.replace(/[^A-Za-z0-9._-]/g, '_')
31
32
  }
33
+
34
+ /**
35
+ * 运行心跳文件名(**唯一实现**)—— 可读前缀 + 名字哈希。
36
+ *
37
+ * 为什么必须带哈希(审计 P11-2 P1,2026-11-13 实测):心跳文件此前叫
38
+ * `<sanitizeFilePart(name)>.json`,而清洗是**多对一**的 —— `web` 与 `web!` 都落到
39
+ * `web.json`,于是两个实例共享同一个心跳文件:后写的覆盖先写的,`listActive()` 只看得到
40
+ * 一个,`stopExternal` 可能停错人,`withdraw()` 也会删掉别人的心跳(对方从此「不可见」,
41
+ * 界面上又能被重复启动 —— 正是这套机制要防的事)。
42
+ *
43
+ * 判据:清洗只用于可读性(截断到 48 字符、去掉结尾的点/空格,Windows 会吃掉结尾点),
44
+ * **唯一性由 sha256(原名) 的前 12 hex 保证**;\0 之类不可达字符也天然被哈希区隔。
45
+ */
46
+ export function runtimeFileName(name: string): string {
47
+ const readable = sanitizeFilePart(name).replace(/[. ]+$/, '').slice(0, 48)
48
+ const digest = createHash('sha256').update(name, 'utf8').digest('hex').slice(0, 12)
49
+ return readable === '' ? `${digest}.json` : `${readable}-${digest}.json`
50
+ }
51
+
52
+ /**
53
+ * 旧版心跳文件名(升级清理专用):`<sanitizeFilePart(name)>.json`。
54
+ *
55
+ * 只用于「自报/自撤时顺手删掉自己那份旧文件」—— 否则升级后同一个 profile 会留下两份心跳,
56
+ * `listActive` 对同名记录会看到两条。绝不用于读别人的记录。
57
+ */
58
+ export function legacyRuntimeFileName(name: string): string {
59
+ return `${sanitizeFilePart(name)}.json`
60
+ }
@@ -349,6 +349,36 @@ test('remove:物理删除目录;当前 profile 需显式确认', () => {
349
349
  }
350
350
  })
351
351
 
352
+ test('removeAsync(审计 P11-9):同一套护栏 + 删除期间事件循环不被独占', async () => {
353
+ const { mgr, home, cleanup } = makeManager()
354
+ try {
355
+ mgr.create('work', 'base')
356
+ const dir = join(home, 'profiles', 'work')
357
+ mkdirSync(join(dir, 'node_modules', 'pkg'), { recursive: true })
358
+ for (let i = 0; i < 400; i += 1) writeFileSync(join(dir, 'node_modules', 'pkg', `f-${i}.js`), 'x')
359
+
360
+ // 删除期间每 5 ms 一次的心跳(真机对应宿主里的定时探测):同步实现期间一次都不会触发
361
+ let ticks = 0
362
+ const timer = setInterval(() => { ticks += 1 }, 5)
363
+ try {
364
+ await mgr.removeAsync('work')
365
+ } finally {
366
+ clearInterval(timer)
367
+ }
368
+ assert.equal(existsSync(dir), false, '目录必须真的删净')
369
+ assert.ok(ticks > 0, `异步删除期间事件循环必须能跑定时器,实际 ticks=${ticks}`)
370
+
371
+ // 护栏与同步版一致
372
+ mgr.create('live', 'web')
373
+ const current = new DshProfileManager({ homeDir: home, currentProfile: () => 'live' })
374
+ await assert.rejects(() => current.removeAsync('live'), (e: unknown) => e instanceof DshProfileError && e.code === 'currentProfile')
375
+ await assert.rejects(() => mgr.removeAsync('desktop'), (e: unknown) => e instanceof DshProfileError && e.code === 'managedProfile')
376
+ await assert.rejects(() => mgr.removeAsync('gone'), (e: unknown) => e instanceof DshProfileError && e.code === 'notFound')
377
+ } finally {
378
+ cleanup()
379
+ }
380
+ })
381
+
352
382
  test('remove:含悬空 junction 的档案也能删净(fs.rm 静默失效的回归)', () => {
353
383
  const { mgr, home, cleanup } = makeManager()
354
384
  try {
@@ -27,7 +27,7 @@ import { existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, type
27
27
  // 复制走 async fs(整档案上万个文件,cpSync 会把宿主事件循环卡住二十多秒)
28
28
  import { copyFile, cp, mkdir, readdir, readlink, stat, symlink, unlink } from 'node:fs/promises'
29
29
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
30
- import { atomicWriteFileSync } from '../utils/atomic-write.ts'
30
+ import { atomicWriteFileSync, type AtomicIoSync } from '../utils/atomic-write.ts'
31
31
  import { removeTree, removeTreeSync } from '../utils/remove-tree.ts'
32
32
  import { isRecord } from '../utils/guards.ts'
33
33
  import { resolveProfileDir, validateProfileName } from '../core/plugin-cli.ts'
@@ -81,6 +81,13 @@ export interface DshProfileManagerOptions {
81
81
  /** 插件 dataDir(保留给调用方复用;本引擎不再落任何状态) */
82
82
  /** 当前运行中的 profile 名(惰性读取,宿主注入) */
83
83
  currentProfile?: () => string
84
+ /**
85
+ * 「复制进行中标记」那一次写盘用的可注入同步 io(缺省 undefined = 真实 fs)。
86
+ *
87
+ * 只给单测用:Windows 上造不出「目录建好、标记写不出来」的真实故障(写完立刻腾空间就失败了),
88
+ * 而这条窄缝恰恰会留下既不在 list() 里、remove() 又报 notFound 的空目录。
89
+ */
90
+ markerIo?: AtomicIoSync
84
91
  }
85
92
 
86
93
  /**
@@ -182,10 +189,13 @@ export async function rollbackCopiedProfileDir(
182
189
  export class DshProfileManager {
183
190
  private readonly homeDir: string
184
191
  private readonly currentProfile: () => string
192
+ /** 见 DshProfileManagerOptions.markerIo:只作用于「复制进行中标记」的写入 */
193
+ private readonly markerIo: AtomicIoSync | undefined
185
194
 
186
195
  constructor(options: DshProfileManagerOptions) {
187
196
  this.homeDir = options.homeDir
188
197
  this.currentProfile = options.currentProfile ?? ((): string => 'web')
198
+ this.markerIo = options.markerIo
189
199
  }
190
200
 
191
201
  /** profiles 根目录(`$DSH_HOME/profiles`) */
@@ -297,9 +307,6 @@ export class DshProfileManager {
297
307
  if (existsSync(destDir)) throw new DshProfileError('exists')
298
308
  const includeNodeModules = opts.includeNodeModules !== false
299
309
  const startedAt = Date.now()
300
- await mkdir(destDir, { recursive: true })
301
- // cross-F3:**先落标记再拷文件**。进程被强杀时标记留在目标目录里,使这个半截副本可被
302
- // 档案列表 / 恢复面板辨识并物理删除;不留标记的话它既不在列表里、删除又报 notFound。
303
310
  const marker: DshProfileCopyMarker = {
304
311
  sourceName: name,
305
312
  newName,
@@ -307,8 +314,13 @@ export class DshProfileManager {
307
314
  includeNodeModules,
308
315
  pid: process.pid,
309
316
  }
310
- atomicWriteFileSync(this.copyMarkerPath(destDir), `${JSON.stringify(marker, null, 2)}\n`, { mode: 0o644 })
317
+ // 建目录与落标记同属一个回滚范围:标记写不出来时这个目录还没有任何可辨认身份,
318
+ // 留在盘上就是「list() 看不到、remove() 报 notFound」的空壳 —— 必须在 catch 里一并清掉。
311
319
  try {
320
+ await mkdir(destDir, { recursive: true })
321
+ // cross-F3:**先落标记再拷文件**。进程被强杀时标记留在目标目录里,使这个半截副本可被
322
+ // 档案列表 / 恢复面板辨识并物理删除;不留标记的话它既不在列表里、删除又报 notFound。
323
+ this.writeCopyMarker(destDir, marker)
312
324
  const entries = await readdir(srcDir, { withFileTypes: true })
313
325
  for (const entry of entries) {
314
326
  // node_modules 与 DSH 投影出来的 .dsh-module-fallback 同进同出(后者的链接都指向前者)
@@ -449,6 +461,30 @@ export class DshProfileManager {
449
461
  }
450
462
  }
451
463
 
464
+ /**
465
+ * remove() 的异步版本:语义、护栏、错误码完全一致,只是不阻塞事件循环(审计 P11-9)。
466
+ *
467
+ * 为什么需要两份:档案目录是整仓里最大的一棵树(含 node_modules,真机 2 万文件)。实测
468
+ * removeTreeSync 删 2 万文件耗 15.5 s,期间宿主 20 ms 定时器 0/776 次触发 —— 心跳、实例
469
+ * 存活探测、同步定时器全停摆,面板表现成「后端卡死」。HTTP 删除走这里;只有确实同步
470
+ * 上下文(脚本、收尾清理)才用 remove(),且必须是自己知道很小的树。
471
+ */
472
+ async removeAsync(name: string, opts: { allowCurrent?: boolean } = {}): Promise<void> {
473
+ if (isManagedProfileName(name)) throw new DshProfileError('managedProfile')
474
+ const dir = this.requireManagedDir(name)
475
+ if (name === this.currentProfile() && opts.allowCurrent !== true) {
476
+ throw new DshProfileError('currentProfile')
477
+ }
478
+ try {
479
+ await removeTree(dir)
480
+ } catch (error) {
481
+ throw new DshProfileError('deleteFailed', error instanceof Error ? error.message : String(error))
482
+ }
483
+ if (existsSync(dir)) {
484
+ throw new DshProfileError('deleteFailed', `profile directory still exists after removal: ${dir}`)
485
+ }
486
+ }
487
+
452
488
  /**
453
489
  * cross-F3:目标目录 = **正常 profile(有 package.json)** 或 **中断的复制残留(有进行中标记)**;
454
490
  * 两者都没有 → notFound。残余标记的目录必须能被定位与删除,否则就是孤儿。
@@ -465,6 +501,18 @@ export class DshProfileManager {
465
501
  throw new DshProfileError('notFound')
466
502
  }
467
503
 
504
+ /**
505
+ * 落「复制进行中标记」(cross-F3 的唯一凭据)。
506
+ *
507
+ * 单独抽出来只为把注入点收窄到这一处写入:调用方(copy)据此保证「标记写失败 ⇒ 目录一起回滚」。
508
+ */
509
+ private writeCopyMarker(dir: string, marker: DshProfileCopyMarker): void {
510
+ atomicWriteFileSync(this.copyMarkerPath(dir), `${JSON.stringify(marker, null, 2)}\n`, {
511
+ mode: 0o644,
512
+ ...(this.markerIo === undefined ? {} : { syncIo: this.markerIo }),
513
+ })
514
+ }
515
+
468
516
  /** 复制进行中标记的路径。 */
469
517
  private copyMarkerPath(dir: string): string {
470
518
  return join(dir, PROFILE_COPY_MARKER_FILENAME)
@@ -16,6 +16,7 @@ import {
16
16
  parseRuntimeRecord, runtimeRecordLive,
17
17
  } from './dsh-profile-runtime.ts'
18
18
  import { DshProfileError } from './dsh-profile-manager.ts'
19
+ import { runtimeFileName } from './dsh-profile-io.ts'
19
20
 
20
21
  interface HarnessOptions {
21
22
  name?: string
@@ -75,13 +76,13 @@ test('announce / listActive / withdraw:自报 → 可见 → 自撤', () => {
75
76
  assert.equal(written.name, 'web')
76
77
  assert.equal(written.pid, 111)
77
78
  assert.equal(written.port, 3080)
78
- assert.equal(existsSync(join(h.dir, 'web.json')), true)
79
+ assert.equal(existsSync(join(h.dir, runtimeFileName('web'))), true)
79
80
  const active = h.registry.listActive()
80
81
  assert.deepEqual(active.map((r) => r.name), ['web'])
81
82
  assert.equal(active[0]?.port, 3080)
82
83
  h.registry.withdraw()
83
84
  assert.deepEqual(h.registry.listActive(), [])
84
- assert.equal(existsSync(join(h.dir, 'web.json')), false)
85
+ assert.equal(existsSync(join(h.dir, runtimeFileName('web'))), false)
85
86
  } finally { h.cleanup() }
86
87
  })
87
88
 
@@ -118,10 +119,31 @@ test('listActive:死心跳 / 过期心跳 / 坏文件都会被清掉(进程
118
119
  writeFileSync(join(h.dir, 'stale.json'), JSON.stringify(stale))
119
120
  const active = h.registry.listActive()
120
121
  assert.deepEqual(active.map((r) => r.name), ['web'], '只留活着的自己')
121
- assert.deepEqual(readdirSync(h.dir).sort(), ['web.json'], '死/坏心跳文件已清理')
122
+ assert.deepEqual(readdirSync(h.dir).sort(), [runtimeFileName('web')], '死/坏心跳文件已清理')
122
123
  } finally { h.cleanup() }
123
124
  })
124
125
 
126
+ test('心跳文件名必须唯一:清洗后同形的两个 profile 不得共用/互删心跳(审计 P11-2 回归)', () => {
127
+ // 旧实现 <sanitizeFilePart(name)>.json:'web' 与 'web!' 都落成 web.json ⇒ 后写的覆盖先写的,
128
+ // listActive 只看得到一个,withdraw 还会删掉别人的心跳(对方从此「不可见」,又能被重复启动)。
129
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-runtime-'))
130
+ try {
131
+ const mk = (name: string, pid: number) => new DshProfileRuntimeRegistry({
132
+ dataDir: dir, name, pid,
133
+ deps: { isAlivePid: (p) => p === pid, killPid: () => {}, now: () => 1_000_000, sleep: () => Promise.resolve() },
134
+ })
135
+ const a = mk('web', 111)
136
+ const b = mk('web!', 222)
137
+ a.announce()
138
+ b.announce()
139
+ assert.notEqual(a.fileFor('web'), b.fileFor('web!'), '清洗同形的两个名字必须落到不同文件')
140
+ assert.equal(readdirSync(join(dir, 'running')).length, 2, '两个实例各留一份心跳')
141
+ b.withdraw()
142
+ assert.equal(existsSync(a.fileFor('web')), true, 'B 自撤不得删掉 A 的心跳')
143
+ assert.deepEqual(a.listActive().map((r) => r.name), ['web'], 'A 仍可见')
144
+ } finally { rmSync(dir, { recursive: true, force: true }) }
145
+ })
146
+
125
147
  test('stopExternal:停**别的**实例(按它的心跳 pid),成功后删除它的心跳', async () => {
126
148
  const a = makeHarness({ name: 'web', pid: 111, alive: 'die-on-kill' })
127
149
  const b = makeHarness({ name: 'cmtest', pid: 222, alive: 'die-on-kill' })
@@ -142,7 +164,7 @@ test('stopExternal:停**别的**实例(按它的心跳 pid),成功后删
142
164
  assert.equal(stopped.name, 'cmtest')
143
165
  assert.deepEqual(a.killed, ['222:graceful'])
144
166
  assert.deepEqual(a.registry.listActive().map((r) => r.name), ['web'], 'B 的心跳已被删')
145
- assert.equal(existsSync(join(a.dir, 'cmtest.json')), false)
167
+ assert.equal(existsSync(join(a.dir, runtimeFileName('cmtest'))), false)
146
168
  } finally { a.cleanup(); b.cleanup() }
147
169
  })
148
170
 
@@ -165,7 +187,7 @@ test('stopExternal:没有心跳 → notRunning;停自己 → currentProfile
165
187
  () => h.registry.stopExternal('cmtest'),
166
188
  (e: unknown) => e instanceof DshProfileError && e.code === 'stopFailed' && e.message.includes('222'),
167
189
  )
168
- assert.equal(existsSync(join(h.dir, 'cmtest.json')), true, '杀不掉就不删心跳(否则会以为它已经没了)')
190
+ assert.equal(existsSync(join(h.dir, runtimeFileName('cmtest'))), true, '杀不掉就不删心跳(否则会以为它已经没了)')
169
191
  forced.cleanup()
170
192
  } finally { h.cleanup() }
171
193
  })
@@ -184,10 +206,10 @@ test('startHeartbeat:按 refreshMs 定期 announce,stop() 之后不再刷',
184
206
  const stop = h.registry.startHeartbeat()
185
207
  assert.equal(intervalMs, RUNTIME_REFRESH_MS)
186
208
  assert.notEqual(box.fn, null)
187
- const before = JSON.parse(readFileSync(join(h.dir, 'web.json'), 'utf8')) as { updatedAt: number }
209
+ const before = JSON.parse(readFileSync(join(h.dir, runtimeFileName('web')), 'utf8')) as { updatedAt: number }
188
210
  h.tick(5_000)
189
211
  box.fn?.()
190
- const after = JSON.parse(readFileSync(join(h.dir, 'web.json'), 'utf8')) as { updatedAt: number }
212
+ const after = JSON.parse(readFileSync(join(h.dir, runtimeFileName('web')), 'utf8')) as { updatedAt: number }
191
213
  assert.equal(after.updatedAt, before.updatedAt + 5_000, '心跳被刷新(判活靠它)')
192
214
  stop()
193
215
  stop()