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
@@ -133,9 +133,11 @@ export function copyDirCommand(src, dest, platform = process.platform) {
133
133
  const s = isWindows(platform) ? psQuote(src) : shellQuote(src);
134
134
  const d = isWindows(platform) ? psQuote(dest) : shellQuote(dest);
135
135
  if (isWindows(platform)) {
136
- return `Remove-Item -Recurse -Force ${d} -ErrorAction SilentlyContinue; Copy-Item -Recurse ${s} ${d} -ErrorAction SilentlyContinue`;
136
+ // 删旧目标可失败(本来不存在);复制失败必须让命令退出码非零 —— 备份是删除前唯一兜底。
137
+ return `Remove-Item -Recurse -Force ${d} -ErrorAction SilentlyContinue; Copy-Item -Recurse ${s} ${d} -ErrorAction Stop`;
137
138
  }
138
- return `rm -rf ${d}; cp -r ${s} ${d} 2>/dev/null; true`;
139
+ // 同上:不吞 stderr、不用 `; true` 抹平退出码(审计 P11-7)。
140
+ return `rm -rf ${d} && cp -r ${s} ${d}`;
139
141
  }
140
142
  /**
141
143
  * 生成重装计划。exec 用于实时解析 npm root 等路径;plan 生成完成后,
@@ -198,6 +200,8 @@ export async function buildReinstallPlan(selection, version, exec, env = process
198
200
  label: engineMsg('core.reinstall.stepBackupHome'),
199
201
  command: copyDirCommand(dshHome, `${dshHome}.reinstall-backup`, platform),
200
202
  dangerous: true,
203
+ // 备份失败 → 后面的 settings/profiles/sessions/credentials 清空没有抢救副本,必须中止。
204
+ critical: true,
201
205
  });
202
206
  }
203
207
  if (selection.has('settings')) {
@@ -42,6 +42,18 @@ async function loadSnapshot(snapshotDir, msg) {
42
42
  }
43
43
  return parsed;
44
44
  }
45
+ /**
46
+ * `snapshot.entries` 兜底(审计 P3-3):旧 / 截断 / 手改的 snapshot.json 可能整段缺 entries
47
+ * (或写成非数组),直接 `for…of` 会抛裸 TypeError(`snapshot.entries is not iterable`)。
48
+ *
49
+ * 为什么按空集合而不是拒绝:快照可信度已在计划期按 verdict 过门(CORRUPT/INVALID 拒绝、
50
+ * LEGACY 放行),字段缺失属旧快照常态;同文件 `hostFileBackups ?? []` / `pluginRemovals ?? []`
51
+ * / `expectedSessionRefs(entries ?? [])` 都是这个口径 —— 旧快照诚实跳过,绝不把「字段缺失」
52
+ * 升级成类型错误。
53
+ */
54
+ function snapshotEntries(snapshot) {
55
+ return Array.isArray(snapshot.entries) ? snapshot.entries : [];
56
+ }
45
57
  async function fileExists(p) {
46
58
  try {
47
59
  await fs.access(p);
@@ -166,7 +178,12 @@ function createTargetSafetyChecker(homeDir) {
166
178
  return 'target-symlink';
167
179
  }
168
180
  catch (err) {
169
- if (err.code !== 'ENOENT')
181
+ // ENOTDIR 与 ENOENT 同义:路径上某一段是普通文件(POSIX 的 lstat 抛 ENOTDIR,
182
+ // Windows 抛 ERROR_PATH_NOT_FOUND ⇒ ENOENT)。目标本身既不存在,也就不可能是链接
183
+ // ⇒ 交给下面的父级投影判定;真越界仍会被 isPathInside 拒。
184
+ // 判据 → docs/evidence/recovery-console.md;CI 三平台复现见 tests/core/restore.test.ts R-ghost-unreadable。
185
+ const code = err.code;
186
+ if (code !== 'ENOENT' && code !== 'ENOTDIR')
170
187
  return 'target-unreadable';
171
188
  }
172
189
  const parentReal = projectedParentReal(path.dirname(absTarget));
@@ -542,7 +559,7 @@ export async function planRestore(opts) {
542
559
  let patchLineCount = 0;
543
560
  let workspaceCount = 0;
544
561
  let credentialAbsentCount = 0;
545
- for (const entry of snapshot.entries) {
562
+ for (const entry of snapshotEntries(snapshot)) {
546
563
  switch (entry.kind) {
547
564
  case 'file': {
548
565
  const rel = toRelPath(homeDir, resolveFileAbs(homeDir, entry.adapter, entry.ref));
@@ -917,16 +934,24 @@ export async function restore(opts) {
917
934
  }
918
935
  /* ------------------------------------------------------------ 幽灵会话(F5) */
919
936
  /**
920
- * 磁盘 sessions 目录实际相对路径清单(相对 <homeDir>/sessions;目录缺失视为空)。
937
+ * 磁盘 sessions 目录实际相对路径清单(相对 <homeDir>/sessions;**只有 ENOENT** 视为空)。
921
938
  * 用 node fs 递归列举(离线引擎不依赖 HostContext),分隔符由 sessionKeyOf 归一。
939
+ *
940
+ * 「读不到」≠「没有」(AGENTS.md 文件类分区条;同 listSnapshots 的 EACCES/ENOTDIR 处理):
941
+ * EACCES / EPERM / ENOTDIR(sessions 被普通文件占住)若也降级成空集合,幽灵判定会把快照里
942
+ * **每一个**期望会话都报成「备份有记录、磁盘无文件,需人工清理」(审计 P3-4)。
943
+ * 故只在 ENOENT(确实没有会话分区)时返回空;其余错误原样上抛,由调用方记入 failed
944
+ * —— 报告成「未知」,绝不断言磁盘上没有这些会话。
922
945
  */
923
946
  async function listSessionEntries(homeDir) {
924
947
  const base = path.join(homeDir, 'sessions');
925
948
  try {
926
949
  return await fs.readdir(base, { recursive: true });
927
950
  }
928
- catch {
929
- return []; // 目录不存在(无会话分区)→ 空
951
+ catch (err) {
952
+ if (err.code === 'ENOENT')
953
+ return [];
954
+ throw err;
930
955
  }
931
956
  }
932
957
  /**
@@ -938,7 +963,7 @@ async function listSessionEntries(homeDir) {
938
963
  */
939
964
  async function sweepRestoredSessions(snapshotDir, homeDir, msg) {
940
965
  const snapshot = await loadSnapshot(snapshotDir, msg);
941
- const expected = expectedSessionRefs(snapshot.entries ?? []);
966
+ const expected = expectedSessionRefs(snapshotEntries(snapshot));
942
967
  if (expected.length === 0)
943
968
  return [];
944
969
  return sweepGhostSessions(expected, await listSessionEntries(homeDir));
@@ -0,0 +1,32 @@
1
+ /**
2
+ * 分区载荷脱敏的**唯一入口**(issue #136 C)。
3
+ *
4
+ * 为什么必须只有一处:同一分区数据有五个出口 —— 导出、push 载荷、push 预览、
5
+ * `hasLocalChanges` 的基线比对、合并落地的本地侧与「落地后重新导出记基线」。
6
+ * 这些字节必须**逐字相同**(参见 AGENTS.md「本地有改动与导出载荷必须同一份字节」):
7
+ * 任何一处只做 `scanAndRedact` 而不做归属标注,就会让「被剥空路径」在那一侧消失,
8
+ * 与另一侧算出的 hash 分叉,表现为每轮同步都真推一次 / 合并判冲突。
9
+ *
10
+ * 归属标注钩子见 `ConfigAdapter.annotateRedactions`(只有 plugins 分区实现:把 hit 的
11
+ * `patch[i].raw.x` 归属回第 i 行的 `redactedPaths`)。
12
+ */
13
+ import type { ConfigAdapter, SensitiveHit } from './types.ts';
14
+ /** 扫描器最小契约(`SecretScanner` 结构性满足;此处只依赖用到的那一个方法)。 */
15
+ export interface SectionScanner {
16
+ scanAndRedact(data: unknown): {
17
+ sanitized: unknown;
18
+ hits: SensitiveHit[];
19
+ };
20
+ }
21
+ /** 可参与脱敏归属标注的适配器(只要求用到的那部分形状)。 */
22
+ type AnnotatingAdapter = Pick<ConfigAdapter, 'annotateRedactions'>;
23
+ /**
24
+ * 扫描 + 剥离 + (如实现)归属标注。
25
+ *
26
+ * @param adapter 分区适配器;未实现 `annotateRedactions` 时行为与直接 `scanAndRedact` 逐字相同。
27
+ */
28
+ export declare function sanitizeSectionData(adapter: AnnotatingAdapter | undefined, scanner: SectionScanner, data: unknown): {
29
+ sanitized: unknown;
30
+ hits: SensitiveHit[];
31
+ };
32
+ export {};
@@ -0,0 +1,13 @@
1
+ /**
2
+ * 扫描 + 剥离 + (如实现)归属标注。
3
+ *
4
+ * @param adapter 分区适配器;未实现 `annotateRedactions` 时行为与直接 `scanAndRedact` 逐字相同。
5
+ */
6
+ export function sanitizeSectionData(adapter, scanner, data) {
7
+ const scanned = scanner.scanAndRedact(data);
8
+ const annotate = adapter?.annotateRedactions;
9
+ if (annotate === undefined)
10
+ return { sanitized: scanned.sanitized, hits: scanned.hits };
11
+ return { sanitized: annotate.call(adapter, scanned.sanitized, scanned.hits), hits: scanned.hits };
12
+ }
13
+ //# sourceMappingURL=section-sanitize.js.map
@@ -55,6 +55,35 @@ export interface RestoreChangeSummary {
55
55
  /** 统计口径上限(UI 提示用) */
56
56
  limits: typeof SNAPSHOT_DIFF_LIMITS;
57
57
  }
58
+ /** 单侧读取结果(缺文件 = exists:false 且 text 为空串)。 */
59
+ interface SideRead {
60
+ exists: boolean;
61
+ bytes: number;
62
+ /** 文本内容;null = 未读取(二进制 / 超限 / 不可读) */
63
+ text: string | null;
64
+ binary: boolean;
65
+ oversized: boolean;
66
+ unreadable: boolean;
67
+ }
68
+ /** readSide 依赖的最小 fs 能力(默认 = 真 fs)。 */
69
+ export interface SideReadIo {
70
+ stat(abs: string): Promise<{
71
+ isFile(): boolean;
72
+ size: number;
73
+ }>;
74
+ readFile(abs: string): Promise<Buffer>;
75
+ }
76
+ /**
77
+ * 读单侧内容。
78
+ *
79
+ * 三种结果必须分开:真的没有(ABSENT)/ 存在但读不出(unreadable)/ 正常读到。
80
+ * 原先整段包一个 try + 末尾 `catch { return ABSENT }`,把「stat 成功、readFile 抛 EACCES」
81
+ * 判成了不存在 —— 预览因此把只读文件显示成「新增」(审计 P2-6)。
82
+ *
83
+ * `io` 参数只为单测注入:Windows 上造不出 EACCES 夹具,而这条分支必须被真正覆盖;
84
+ * 生产调用方一律不传(走 REAL_SIDE_IO)。
85
+ */
86
+ export declare function readSide(abs: string, maxBytes: number, io?: SideReadIo): Promise<SideRead>;
58
87
  /**
59
88
  * 列表阶段:逐动作产出变更状态 + 行数统计(零写入;不抛错)。
60
89
  * plan 为空或 action 不可分析时返回对应 entry(status='skip'),绝不抛错给路由。
@@ -104,3 +133,4 @@ export declare function snapshotFileDiff(opts: {
104
133
  blobPath?: string;
105
134
  msg?: MsgFunc;
106
135
  }): Promise<SnapshotFileDiff>;
136
+ export {};
@@ -37,6 +37,17 @@ export const SNAPSHOT_DIFF_LIMITS = {
37
37
  context: 3,
38
38
  };
39
39
  const ABSENT = { exists: false, bytes: 0, text: '', binary: false, oversized: false, unreadable: false };
40
+ /** 该 errno 是否等于「路径真的不存在」(其余 = 存在但拿不到,绝不能当作不存在)。 */
41
+ function isEnoent(err) {
42
+ return typeof err === 'object' && err !== null && err.code === 'ENOENT';
43
+ }
44
+ /**
45
+ * 「存在但读不出」的唯一形态(目录 / 无权限 / 被占用 / stat 抛非 ENOENT)。
46
+ * 与 ABSENT(真的不存在)严格区分:判成不存在会让预览把改不了的文件显示成「新增」(审计 P2-6)。
47
+ */
48
+ function unreadableAt(bytes) {
49
+ return { exists: true, bytes, text: null, binary: false, oversized: false, unreadable: true };
50
+ }
40
51
  /** 只探测存在性(预算触顶时用:不读内容,只 stat)。 */
41
52
  async function probeExists(opts) {
42
53
  let abs;
@@ -48,30 +59,53 @@ async function probeExists(opts) {
48
59
  }
49
60
  try {
50
61
  const stat = await fs.stat(abs);
51
- return stat.isFile() ? 'exists' : 'absent';
62
+ return stat.isFile() ? 'exists' : 'unreadable';
52
63
  }
53
- catch {
54
- return 'absent';
64
+ catch (err) {
65
+ // ENOENT 才是「没有」;EACCES 一类说明路径在,只是拿不到状态
66
+ return isEnoent(err) ? 'absent' : 'unreadable';
55
67
  }
56
68
  }
57
- async function readSide(abs, maxBytes) {
69
+ const REAL_SIDE_IO = {
70
+ stat: (abs) => fs.stat(abs),
71
+ readFile: (abs) => fs.readFile(abs),
72
+ };
73
+ /**
74
+ * 读单侧内容。
75
+ *
76
+ * 三种结果必须分开:真的没有(ABSENT)/ 存在但读不出(unreadable)/ 正常读到。
77
+ * 原先整段包一个 try + 末尾 `catch { return ABSENT }`,把「stat 成功、readFile 抛 EACCES」
78
+ * 判成了不存在 —— 预览因此把只读文件显示成「新增」(审计 P2-6)。
79
+ *
80
+ * `io` 参数只为单测注入:Windows 上造不出 EACCES 夹具,而这条分支必须被真正覆盖;
81
+ * 生产调用方一律不传(走 REAL_SIDE_IO)。
82
+ */
83
+ export async function readSide(abs, maxBytes, io = REAL_SIDE_IO) {
84
+ let stat;
58
85
  try {
59
- const stat = await fs.stat(abs);
60
- if (!stat.isFile()) {
61
- return { exists: true, bytes: stat.size, text: null, binary: false, oversized: false, unreadable: true };
62
- }
63
- if (stat.size > maxBytes) {
64
- return { exists: true, bytes: stat.size, text: null, binary: false, oversized: true, unreadable: false };
65
- }
66
- const buf = await fs.readFile(abs);
67
- if (buf.subarray(0, 8192).includes(0)) {
68
- return { exists: true, bytes: buf.byteLength, text: null, binary: true, oversized: false, unreadable: false };
69
- }
70
- return { exists: true, bytes: buf.byteLength, text: buf.toString('utf8'), binary: false, oversized: false, unreadable: false };
86
+ stat = await io.stat(abs);
71
87
  }
72
- catch {
73
- return ABSENT;
88
+ catch (err) {
89
+ return isEnoent(err) ? ABSENT : unreadableAt(0);
90
+ }
91
+ if (!stat.isFile())
92
+ return unreadableAt(stat.size);
93
+ if (stat.size > maxBytes) {
94
+ return { exists: true, bytes: stat.size, text: null, binary: false, oversized: true, unreadable: false };
95
+ }
96
+ let buf;
97
+ try {
98
+ buf = await io.readFile(abs);
99
+ }
100
+ catch (err) {
101
+ // stat 已证明它是普通文件:这里读失败 = 存在但读不出(EACCES/EBUSY/…);
102
+ // stat 与 read 之间被删掉的 ENOENT 仍按「不存在」处理,那才是当时的真实状态
103
+ return isEnoent(err) ? ABSENT : unreadableAt(stat.size);
104
+ }
105
+ if (buf.subarray(0, 8192).includes(0)) {
106
+ return { exists: true, bytes: buf.byteLength, text: null, binary: true, oversized: false, unreadable: false };
74
107
  }
108
+ return { exists: true, bytes: buf.byteLength, text: buf.toString('utf8'), binary: false, oversized: false, unreadable: false };
75
109
  }
76
110
  /** 变更状态判定(恢复类:before 存在 = 修改,不存在 = 新增)。 */
77
111
  function statusOf(kind, beforeExists) {
@@ -184,10 +218,12 @@ export async function summarizeRestoreChanges(opts) {
184
218
  entry.statSkipped = 'unreadable';
185
219
  }
186
220
  else {
187
- entry.beforeExists = probe === 'exists';
221
+ // 「存在但读不出」与 readSide 同口径:算存在(否则会显示成「新增」),只把行数统计标成 unreadable
222
+ const unreadable = probe === 'unreadable';
223
+ entry.beforeExists = probe === 'exists' || unreadable;
188
224
  entry.afterExists = restoreKind;
189
225
  entry.status = statusOf(action.kind, entry.beforeExists);
190
- entry.statSkipped = 'budget';
226
+ entry.statSkipped = unreadable ? 'unreadable' : 'budget';
191
227
  }
192
228
  skipped += 1;
193
229
  entries.push(entry);
@@ -24,8 +24,14 @@ export function classifyStartup(opts) {
24
24
  const insp = await inspectStartup(opts.store, opts.hooks, opts.env, opts.options ?? {}, opts.lockState);
25
25
  let state;
26
26
  if (opts.lockState === 'LOCKED') {
27
- // fresh heartbeat:活锁;若仍有 unresolved journal → 视为 live op(LOCKED_LIVE,不作 recovery/接管)
28
- state = insp.unresolved.length > 0 ? { kind: 'LOCKED_LIVE', operationId: insp.unresolved[0] } : { kind: 'NORMAL' };
27
+ // fresh heartbeat:活锁。判据 = 「另一实例持锁 + 确实有 live 且未到 terminal 的 journal」——
28
+ // 那才是正在跑的操作,分类为 LOCKED_LIVE(不作 recovery/接管,也不启动调度器)。
29
+ // 审计 P3-8:旧实现在这里看 unresolved,但 live 分支恒 unresolved:false(且 LOCKED 下所有
30
+ // journal 都被强制按 live 处理),于是「持锁 + 真正在跑」永远落到 NORMAL;只有 parse 失败
31
+ // 的 corrupt journal(走 quarantine 分支)才碰巧命中 LOCKED_LIVE。现在改用 liveIncomplete。
32
+ state = insp.liveIncomplete.length > 0
33
+ ? { kind: 'LOCKED_LIVE', operationId: insp.liveIncomplete[0] }
34
+ : { kind: 'NORMAL' };
29
35
  }
30
36
  else if (insp.recoveryRequired) {
31
37
  state = { kind: 'RECOVERY_REQUIRED', operationId: insp.unresolved[0] };
@@ -678,6 +678,17 @@ export type SessionFormatDisposition = 'abort' | 'skip' | 'guide';
678
678
  export interface ConflictDecision {
679
679
  itemId: string;
680
680
  resolution: ItemResolution;
681
+ /**
682
+ * 这条裁决是**谁**下的(issue #136 A):
683
+ * - `'item'`:用户对该计划项逐项决策(`decisions.resolutions[id]`,含导入页的逐行确认)——
684
+ * 适配器可把它当作「我确实要这一行按导入值写」的确认。
685
+ * - `'section'`:由**分区级**裁决换算而来(合并落地 `planMergeApply` 的 second pass 把
686
+ * 「该分区已裁决」逐项注入成 `useImported`)。分区级裁决决定「分区是否应用」,
687
+ * 不构成对某一行值的确认,写回守卫不得据此清空本机明文。
688
+ * - 缺省:未标注来源。写回守卫按**未确认**处理(默认拒绝清空)—— 忘了标注只会少清空,
689
+ * 不会误清空;确认必须显式写明来源。
690
+ */
691
+ decidedBy?: 'item' | 'section';
681
692
  }
682
693
  export interface PathMapping {
683
694
  oldPrefix: string;
@@ -1254,6 +1265,17 @@ export interface ConfigAdapter<TSection = unknown> {
1254
1265
  /** 读取当前 DSH 该类别配置 → 导出数据(无秘密值)。
1255
1266
  * 实现方应尊重 `options.includeItems?.[this.id]`(条目级选择,见 adapters/units.ts)。 */
1256
1267
  export(ctx: HostContext, options: ExportOptions): Promise<ExportSection<TSection>>;
1268
+ /**
1269
+ * 可选:脱敏**归属标注**(issue #136 C)—— 把 SecretScanner 的命中路径归属回具体载荷单元。
1270
+ *
1271
+ * 调用点只有一个:`sanitizeSectionData()`(`src/core/section-sanitize.ts`),纯函数语义
1272
+ * (不改入参、不读盘);只做「标注」,绝不把值写回去(脱敏仍是扫描器的职责)。
1273
+ *
1274
+ * plugins 分区用它把 `patch[i].raw.x` 的命中写进第 i 行的 `redactedPaths`:目标机据此区分
1275
+ * 「被剥空」与「用户写空」,写回层才能精确保护本机明文(`src/core/patch-secret-guard.ts`)。
1276
+ * 未实现 = 载荷不含归属信息,写回侧走保守分支。
1277
+ */
1278
+ annotateRedactions?(sanitized: unknown, hits: SensitiveHit[]): unknown;
1257
1279
  /**
1258
1280
  * 可选:**只读预览**(`/export-preview` 用)。
1259
1281
  *
@@ -63,6 +63,55 @@ export function wantsForcedUpdateCheck(url) {
63
63
  }
64
64
  return false;
65
65
  }
66
+ /**
67
+ * **按字节**有界地读响应体;超过 `maxBytes` 返回 null(调用方给 'registry response too large')。
68
+ *
69
+ * 为什么不是 `text.length`:它数的是 UTF-16 代码单元,一个 CJK 字符占 3 个 UTF-8 字节 ⇒
70
+ * 120KB 的中文响应 `text.length` 只有 40K,上限形同虚设(审计 P11-6)。
71
+ * 顺序:Content-Length 预检(有就先拒,一个字节都不读)→ 流式累计,越界立刻 abort
72
+ * (不把大响应读进内存)→ 没有 body 流的运行时退回 arrayBuffer 量 byteLength。
73
+ */
74
+ async function readBoundedBody(res, maxBytes, controller) {
75
+ // 防御:真实 Response 一定有 headers/body,但注入的替身(脚本、极简 mock)可能只给 text()。
76
+ // 缺什么就退化成「全量读 + 字节口径判定」——判据不变,只是失去流式提前止损。
77
+ const declared = typeof res.headers?.get === 'function' ? res.headers.get('content-length') : null;
78
+ if (declared !== null) {
79
+ const n = Number(declared);
80
+ if (Number.isFinite(n) && n > maxBytes) {
81
+ controller.abort();
82
+ return null;
83
+ }
84
+ }
85
+ const body = res.body;
86
+ if (body === null || body === undefined) {
87
+ const bytes = typeof res.arrayBuffer === 'function'
88
+ ? new Uint8Array(await res.arrayBuffer())
89
+ : new TextEncoder().encode(await res.text());
90
+ return bytes.byteLength > maxBytes ? null : new TextDecoder('utf-8').decode(bytes);
91
+ }
92
+ const reader = body.getReader();
93
+ const chunks = [];
94
+ let total = 0;
95
+ for (;;) {
96
+ const { done, value } = await reader.read();
97
+ if (done)
98
+ break;
99
+ total += value.byteLength;
100
+ if (total > maxBytes) {
101
+ controller.abort();
102
+ await reader.cancel().catch(() => undefined);
103
+ return null;
104
+ }
105
+ chunks.push(value);
106
+ }
107
+ const merged = new Uint8Array(total);
108
+ let at = 0;
109
+ for (const chunk of chunks) {
110
+ merged.set(chunk, at);
111
+ at += chunk.byteLength;
112
+ }
113
+ return new TextDecoder('utf-8').decode(merged);
114
+ }
66
115
  /**
67
116
  * 探测 npm latest(无缓存、无状态)。任何异常都被收成 `{ ok:false, error }`:
68
117
  * 网络错误 / 超时 / 非 2xx / 体积超限 / JSON 畸形 / 版本号形态不认识。
@@ -81,8 +130,8 @@ export async function probeLatestVersion(deps = {}) {
81
130
  });
82
131
  if (!res.ok)
83
132
  return { ok: false, error: `registry returned HTTP ${res.status}` };
84
- const text = await res.text();
85
- if (text.length > UPDATE_CHECK_MAX_BYTES)
133
+ const text = await readBoundedBody(res, UPDATE_CHECK_MAX_BYTES, controller);
134
+ if (text === null)
86
135
  return { ok: false, error: 'registry response too large' };
87
136
  let payload;
88
137
  try {
@@ -128,8 +128,15 @@ export function stripUserInfo(url) {
128
128
  const at = rest.indexOf('@');
129
129
  if (at < 0)
130
130
  return { url, stripped: false };
131
- const slash = rest.indexOf('/');
132
- if (slash >= 0 && at > slash)
131
+ /**
132
+ * userinfo 只可能出现在 authority 段里:@ 若落在第一个 '/'、'?' 或 '#' 之后,
133
+ * 它就是 path/query/fragment 里的普通字符(无路径 URL 的 `?k=a@b` 曾把整条 URL 截成 `https://b`)。
134
+ * 纯字符判定,不用正则。
135
+ */
136
+ const boundary = [rest.indexOf('/'), rest.indexOf('?'), rest.indexOf('#')]
137
+ .filter((i) => i >= 0)
138
+ .sort((a, b) => a - b)[0];
139
+ if (boundary !== undefined && at > boundary)
133
140
  return { url, stripped: false };
134
141
  return { url: url.slice(0, scheme + 3) + rest.slice(at + 1), stripped: true };
135
142
  }
@@ -41,6 +41,18 @@ const DEFAULT_MAX_PLUGIN_FILES = 200;
41
41
  const WALK_MAX_DEPTH = 8;
42
42
  /** 跳过原因:符号链接(与 read-claude-code 同码同义) */
43
43
  const DETAIL_SYMLINK = 'symlink-skipped';
44
+ /**
45
+ * 走盘并**明确回报是否真的截断**(审计 P7-9)。
46
+ *
47
+ * 共享的 `walkFiles()` 只返回数组,「拿满上限」与「恰好等于上限」在返回值上无法区分 ——
48
+ * 调用方拿长度反推会把「正好 N 个文件」误报成触顶。这里多要一条:拿到 N+1 条才算真截断,
49
+ * 再把多要的那条切掉(共享内核在 `src/foreign/session-read.ts`,本文件不动它)。
50
+ */
51
+ async function walkFilesChecked(root, options) {
52
+ const probe = await walkFiles(root, { ...options, maxFiles: options.maxFiles + 1 });
53
+ const truncated = probe.length > options.maxFiles;
54
+ return { files: truncated ? probe.slice(0, options.maxFiles) : probe, truncated };
55
+ }
44
56
  /** 有上限的整数解析:只用安全正整数(脏值一律回落缺省) */
45
57
  function positiveLimit(value, fallback) {
46
58
  return typeof value === 'number' && Number.isSafeInteger(value) && value > 0 ? value : fallback;
@@ -295,36 +307,40 @@ async function readPluginAt(pluginDir, specName, marketplace, market, options) {
295
307
  findings.push({ code: 'source-unreadable', origin: 'plugin:' + specName + '/.mcp.json', detail: mcp.problem });
296
308
  }
297
309
  /* commands/**:递归计数(只数,不读内容) */
298
- const commandFiles = await walkFiles(path.join(pluginDir, 'commands'), {
310
+ const commands = await walkFilesChecked(path.join(pluginDir, 'commands'), {
299
311
  maxDepth: WALK_MAX_DEPTH,
300
312
  maxFiles: options.maxPluginFiles,
301
313
  });
302
- if (commandFiles.length > 0) {
303
- plugin.commandCount = commandFiles.length;
314
+ if (commands.files.length > 0) {
315
+ plugin.commandCount = commands.files.length;
304
316
  plugin.components.push('commands');
305
317
  }
306
- if (commandFiles.length >= options.maxPluginFiles)
318
+ if (commands.truncated)
307
319
  filesTruncated = true;
320
+ // 上限是「单插件文件数」:只计数的组件也占额度(否则 N 个目录各带 199 个文件仍然全过)
321
+ let countedFiles = filesUsed + commands.files.length;
308
322
  /* agents/*.md:只取文件名(不读内容) */
309
- const agentFiles = await walkFiles(path.join(pluginDir, 'agents'), {
323
+ const agentsWalked = await walkFilesChecked(path.join(pluginDir, 'agents'), {
310
324
  maxDepth: 0,
311
325
  maxFiles: options.maxPluginFiles,
312
326
  match: (name) => name.endsWith('.md'),
313
327
  });
314
- if (agentFiles.length > 0) {
315
- plugin.agents = agentFiles.map((file) => file.name).sort();
328
+ if (agentsWalked.files.length > 0) {
329
+ plugin.agents = agentsWalked.files.map((file) => file.name).sort();
316
330
  plugin.components.push('agents');
317
331
  }
318
- if (agentFiles.length >= options.maxPluginFiles)
332
+ if (agentsWalked.truncated)
319
333
  filesTruncated = true;
334
+ countedFiles += agentsWalked.files.length;
320
335
  /* hooks/ 与 hooks.json:**只数文件数**(hooks 是执行面,内容一律不读) */
321
- const hookFiles = await walkFiles(path.join(pluginDir, 'hooks'), {
336
+ const hooksWalked = await walkFilesChecked(path.join(pluginDir, 'hooks'), {
322
337
  maxDepth: WALK_MAX_DEPTH,
323
338
  maxFiles: options.maxPluginFiles,
324
339
  });
325
- let hookCount = hookFiles.length;
326
- if (hookCount >= options.maxPluginFiles)
340
+ let hookCount = hooksWalked.files.length;
341
+ if (hooksWalked.truncated)
327
342
  filesTruncated = true;
343
+ countedFiles += hooksWalked.files.length;
328
344
  const hooksJson = await statOrNull(path.join(pluginDir, 'hooks.json'));
329
345
  if (hooksJson !== null && hooksJson.isFile())
330
346
  hookCount += 1;
@@ -332,6 +348,8 @@ async function readPluginAt(pluginDir, specName, marketplace, market, options) {
332
348
  plugin.hookFiles = hookCount;
333
349
  plugin.components.push('hooks');
334
350
  }
351
+ if (countedFiles > options.maxPluginFiles)
352
+ filesTruncated = true;
335
353
  if (filesTruncated) {
336
354
  findings.push({
337
355
  code: 'source-unreadable',
@@ -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.js';
25
- import { listDirNames, listFileNames, readBytesSafe, statOrNull } from './session-read.js';
25
+ import { listDirNames, listFileNames, readBytesPrefixSafe, readBytesSafe, statOrNull } from './session-read.js';
26
26
  import { readLogHeaderFromBytes } from '../utils/session-log.js';
27
27
  export const DSH_HOME_ENV = 'DSH_HOME';
28
28
  export const DSH_DEFAULT_DIR = '.dsh';
@@ -30,6 +30,12 @@ export const DSH_SESSIONS_SUBDIR = 'sessions';
30
30
  const DEFAULT_MAX_LOGS = 2000;
31
31
  const DEFAULT_MAX_FILE_BYTES = 32 * 1024 * 1024;
32
32
  const DEFAULT_MAX_TOTAL_BYTES = 256 * 1024 * 1024;
33
+ /**
34
+ * 代次嗅探窗口(审计 P7-7):header 是第一行 JSON,64 KiB 覆盖任何真实 cwd/标题组合
35
+ * (首行实测 < 1 KiB)。窗口内解析不出 header 时退回整读,因此这个值只影响「能不能提前
36
+ * 跳过非目标代次」,不会改变任何判定结果。
37
+ */
38
+ const HEADER_SNIFF_BYTES = 64 * 1024;
33
39
  const HEADER_WINDOW_BYTES = 64 * 1024;
34
40
  /** DSH_HOME(非空即替换;只报键名)→ 默认 ~/.dsh */
35
41
  export function resolveDshHome(opts) {
@@ -144,6 +150,23 @@ export async function readDshLogs(opts) {
144
150
  truncated = 'byte-budget';
145
151
  break outer;
146
152
  }
153
+ /**
154
+ * 代次嗅探(审计 P7-7):日志的 header 就在第一行,而 dsh 与 dsh4 两代并存的机器上
155
+ * 一半文件属于「非目标代次」——旧实现为了看那 1 KB header 把 31 MiB 的日志整份读进来
156
+ * 再丢掉。现在先只读头部窗口,判定为别的代次就直接 countedContinue,一次整读都不做。
157
+ *
158
+ * 退化路径保持旧行为:头部窗口解析不出 header(首行比窗口还长 / 读不出)时仍整读一次,
159
+ * 让 log-header-unreadable / log-read-error 这些既有码的触发条件逐字不变。
160
+ */
161
+ const head = await readBytesPrefixSafe(abs, HEADER_SNIFF_BYTES);
162
+ if (head !== null) {
163
+ const sniffed = dshHeaderOfLogBytes(head);
164
+ const sniffedGeneration = sniffed === undefined ? undefined : dshGenerationOfVersion(sniffed.version);
165
+ if (sniffedGeneration !== undefined && sniffedGeneration !== opts.generation) {
166
+ otherGeneration += 1;
167
+ continue;
168
+ }
169
+ }
147
170
  const data = await readBytesSafe(abs, maxFileBytes);
148
171
  if (data === null) {
149
172
  findings.push({ code: 'source-unreadable', origin: name, detail: 'log-read-error' });
@@ -167,8 +190,14 @@ export async function readDshLogs(opts) {
167
190
  findings.push({ code: 'source-unreadable', origin: name, detail: 'log-header-incomplete' });
168
191
  continue;
169
192
  }
170
- if (seen.has(header.id))
193
+ if (seen.has(header.id)) {
194
+ /**
195
+ * 同一 id 出现在两个会话目录(复制/迁移残留):只保留第一个,但**必须留码** ——
196
+ * 静默丢会让「导入少了一条会话」在计划里无从解释(本文件顶部第 21-22 行的硬约束)。
197
+ */
198
+ findings.push({ code: 'session-id-conflict', origin: header.id, detail: 'duplicate-session-id' });
171
199
  continue;
200
+ }
172
201
  seen.add(header.id);
173
202
  bytesRead += data.length;
174
203
  files.push({ id: header.id, cwd: header.cwd, version: header.version, name, data });