dsh-config-manager 0.8.2 → 0.10.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 (418) hide show
  1. package/lib/adapters/mcp.js +51 -15
  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 +204 -6
  10. package/lib/adapters/prompts.js +15 -4
  11. package/lib/adapters/test-helpers.d.ts +15 -1
  12. package/lib/adapters/test-helpers.js +11 -0
  13. package/lib/cli/actions.d.ts +7 -105
  14. package/lib/cli/actions.js +16 -172
  15. package/lib/cli/control-state.d.ts +54 -0
  16. package/lib/cli/control-state.js +107 -0
  17. package/lib/cli/help.d.ts +1 -1
  18. package/lib/cli/help.js +21 -14
  19. package/lib/cli/index.js +132 -104
  20. package/lib/cli/sessions-repair.js +58 -22
  21. package/lib/cli/web/client-script.d.ts +1 -1
  22. package/lib/cli/web/client-script.js +71 -5
  23. package/lib/cli/web/page.d.ts +9 -19
  24. package/lib/cli/web/page.js +277 -173
  25. package/lib/cli/web/routes.js +85 -25
  26. package/lib/cli/write-gates.d.ts +61 -0
  27. package/lib/cli/write-gates.js +110 -0
  28. package/lib/client.d.ts +196 -75
  29. package/lib/client.js +8139 -7487
  30. package/lib/core/backup.d.ts +0 -4
  31. package/lib/core/backup.js +21 -4
  32. package/lib/core/boot-rescue.d.ts +1 -1
  33. package/lib/core/boot-rescue.js +12 -1
  34. package/lib/core/boot-safety.js +37 -2
  35. package/lib/core/conflict-decisions.js +2 -1
  36. package/lib/core/exporter.js +22 -1
  37. package/lib/core/journal.d.ts +54 -4
  38. package/lib/core/journal.js +158 -35
  39. package/lib/core/local-plugin-host.d.ts +29 -0
  40. package/lib/core/local-plugin-host.js +55 -48
  41. package/lib/core/messages.d.ts +17 -0
  42. package/lib/core/messages.js +34 -0
  43. package/lib/core/migration-history.js +16 -9
  44. package/lib/core/model-tools.d.ts +2 -2
  45. package/lib/core/model-tools.js +20 -2
  46. package/lib/core/patch-chain.d.ts +65 -0
  47. package/lib/core/patch-chain.js +100 -0
  48. package/lib/core/patch-document.d.ts +32 -4
  49. package/lib/core/patch-document.js +48 -17
  50. package/lib/core/patch-secret-guard.d.ts +49 -0
  51. package/lib/core/patch-secret-guard.js +164 -0
  52. package/lib/core/reconcile.d.ts +8 -0
  53. package/lib/core/reconcile.js +18 -3
  54. package/lib/core/reinstall.d.ts +2 -0
  55. package/lib/core/reinstall.js +6 -2
  56. package/lib/core/restore.js +31 -6
  57. package/lib/core/section-sanitize.d.ts +32 -0
  58. package/lib/core/section-sanitize.js +13 -0
  59. package/lib/core/snapshot-diff.d.ts +30 -0
  60. package/lib/core/snapshot-diff.js +56 -20
  61. package/lib/core/startup-barrier.js +8 -2
  62. package/lib/core/types.d.ts +38 -1
  63. package/lib/core/update-check.js +51 -2
  64. package/lib/foreign/kernel.js +9 -2
  65. package/lib/foreign/read-claude-plugins.js +29 -11
  66. package/lib/foreign/read-dsh.js +31 -2
  67. package/lib/foreign/session-ir.js +50 -9
  68. package/lib/foreign/session-read.d.ts +8 -0
  69. package/lib/foreign/session-read.js +26 -0
  70. package/lib/index.d.ts +9 -4
  71. package/lib/index.js +42 -47
  72. package/lib/profiles/dsh-profile-io.d.ts +20 -0
  73. package/lib/profiles/dsh-profile-io.js +27 -0
  74. package/lib/profiles/dsh-profile-manager.d.ts +27 -0
  75. package/lib/profiles/dsh-profile-manager.js +45 -4
  76. package/lib/profiles/dsh-profile-runtime.d.ts +5 -1
  77. package/lib/profiles/dsh-profile-runtime.js +16 -3
  78. package/lib/profiles/process-control.d.ts +18 -1
  79. package/lib/profiles/process-control.js +25 -1
  80. package/lib/routes/profiles.js +2 -1
  81. package/lib/routes/sync.js +19 -1
  82. package/lib/schema/types.d.ts +11 -0
  83. package/lib/security/redaction.js +22 -6
  84. package/lib/sync/autosync-repeat.d.ts +27 -0
  85. package/lib/sync/autosync-repeat.js +23 -0
  86. package/lib/sync/autosync-scheduler.d.ts +47 -2
  87. package/lib/sync/autosync-scheduler.js +217 -53
  88. package/lib/sync/baseline-heal.js +7 -0
  89. package/lib/sync/baseline-record.d.ts +67 -0
  90. package/lib/sync/baseline-record.js +74 -0
  91. package/lib/sync/blob-store.js +13 -0
  92. package/lib/sync/content-diff.d.ts +39 -0
  93. package/lib/sync/content-diff.js +46 -0
  94. package/lib/sync/git/git-transport.d.ts +32 -1
  95. package/lib/sync/git/git-transport.js +146 -26
  96. package/lib/sync/github-auth.d.ts +17 -1
  97. package/lib/sync/github-auth.js +37 -1
  98. package/lib/sync/local-changes.d.ts +15 -0
  99. package/lib/sync/local-changes.js +39 -0
  100. package/lib/sync/merge-apply-plan.d.ts +38 -0
  101. package/lib/sync/merge-apply-plan.js +76 -0
  102. package/lib/sync/merge-keyed.d.ts +68 -0
  103. package/lib/sync/merge-keyed.js +124 -0
  104. package/lib/sync/messages.d.ts +1 -0
  105. package/lib/sync/messages.js +2 -0
  106. package/lib/sync/patch-line-identity.d.ts +19 -0
  107. package/lib/sync/patch-line-identity.js +99 -0
  108. package/lib/sync/pending-merge.d.ts +41 -0
  109. package/lib/sync/pending-merge.js +61 -0
  110. package/lib/sync/plugin-removals.d.ts +15 -15
  111. package/lib/sync/plugin-removals.js +134 -83
  112. package/lib/sync/push-skip.d.ts +55 -0
  113. package/lib/sync/push-skip.js +70 -0
  114. package/lib/sync/s3/s3-transport.d.ts +14 -2
  115. package/lib/sync/s3/s3-transport.js +72 -48
  116. package/lib/sync/sync-engine.d.ts +44 -51
  117. package/lib/sync/sync-engine.js +160 -194
  118. package/lib/sync/sync-history.d.ts +7 -0
  119. package/lib/sync/sync-state.d.ts +28 -0
  120. package/lib/sync/sync-state.js +20 -0
  121. package/lib/sync/transport.d.ts +12 -3
  122. package/lib/sync/transport.js +13 -4
  123. package/lib/sync/webdav/webdav-transport.d.ts +19 -2
  124. package/lib/sync/webdav/webdav-transport.js +81 -40
  125. package/lib/sync/workspace-merge.d.ts +8 -2
  126. package/lib/ui/artifact-view.d.ts +1 -1
  127. package/lib/ui/commands.js +5 -11
  128. package/lib/ui/dsh-profiles-view.d.ts +8 -3
  129. package/lib/ui/dsh-profiles-view.js +9 -5
  130. package/lib/ui/foreign-view.d.ts +14 -0
  131. package/lib/ui/foreign-view.js +34 -0
  132. package/lib/ui/i18n.d.ts +7 -1
  133. package/lib/ui/i18n.js +15 -2
  134. package/lib/ui/menu-placement.js +1 -1
  135. package/lib/ui/migration-consult-view.d.ts +11 -0
  136. package/lib/ui/migration-consult-view.js +15 -0
  137. package/lib/ui/overview-view.d.ts +7 -0
  138. package/lib/ui/overview-view.js +3 -0
  139. package/lib/ui/report.d.ts +9 -0
  140. package/lib/ui/report.js +17 -4
  141. package/lib/ui/selection-model.d.ts +10 -2
  142. package/lib/ui/selection-model.js +23 -3
  143. package/lib/utils/async-once.d.ts +11 -0
  144. package/lib/utils/async-once.js +15 -0
  145. package/lib/utils/patch-chain-read.d.ts +51 -0
  146. package/lib/utils/patch-chain-read.js +240 -0
  147. package/lib/utils/patch-yaml.d.ts +39 -1
  148. package/lib/utils/patch-yaml.js +82 -2
  149. package/lib/utils/paths.d.ts +13 -0
  150. package/lib/utils/paths.js +35 -0
  151. package/lib/utils/workdir-lock.js +18 -3
  152. package/package.json +3 -2
  153. package/src/adapters/mcp.test.ts +29 -0
  154. package/src/adapters/mcp.ts +52 -14
  155. package/src/adapters/messages.ts +2 -0
  156. package/src/adapters/patch-key-guard.ts +29 -0
  157. package/src/adapters/plugin-data.test.ts +126 -0
  158. package/src/adapters/plugin-data.ts +97 -26
  159. package/src/adapters/plugins.test.ts +403 -0
  160. package/src/adapters/plugins.ts +198 -8
  161. package/src/adapters/prompts.ts +15 -4
  162. package/src/adapters/test-helpers.ts +15 -1
  163. package/src/cli/actions.test.ts +74 -1
  164. package/src/cli/actions.ts +27 -246
  165. package/src/cli/control-state.ts +143 -0
  166. package/src/cli/help.ts +21 -14
  167. package/src/cli/index.ts +123 -107
  168. package/src/cli/sessions-repair.ts +55 -22
  169. package/src/cli/web/client-script.ts +71 -5
  170. package/src/cli/web/page.ts +327 -208
  171. package/src/cli/web/routes.ts +85 -25
  172. package/src/cli/web/web.test.ts +65 -0
  173. package/src/cli/write-gates.ts +149 -0
  174. package/src/client/ConfigManagerSection.tsx +8 -4
  175. package/src/client/about/AboutPanel.tsx +9 -12
  176. package/src/client/about/release-notes-view.test.ts +17 -0
  177. package/src/client/about/release-notes-view.ts +49 -24
  178. package/src/client/api.ts +2 -1
  179. package/src/client/chat/ChatEntryView.tsx +2 -2
  180. package/src/client/chat/rollback-entry-view.ts +6 -1
  181. package/src/client/common/CommandPalette.tsx +6 -3
  182. package/src/client/common/ConfirmDialog.tsx +29 -12
  183. package/src/client/common/ContentPicker.tsx +24 -24
  184. package/src/client/common/Modal.tsx +12 -5
  185. package/src/client/common/MoreMenu.tsx +4 -1
  186. package/src/client/common/RunsCenter.tsx +103 -32
  187. package/src/client/common/Select.tsx +2 -2
  188. package/src/client/common/floating-bounds.ts +1 -1
  189. package/src/client/common/floating-units.test.ts +1 -2
  190. package/src/client/common/plan-text-redaction.test.ts +190 -5
  191. package/src/client/common/runs-center-guard.test.ts +60 -0
  192. package/src/client/common/runs-center-view.test.ts +128 -0
  193. package/src/client/common/runs-center-view.ts +96 -0
  194. package/src/client/common/section-title-action.test.ts +66 -0
  195. package/src/client/common/ui.tsx +93 -30
  196. package/src/client/config-manager.module.css +1515 -270
  197. package/src/client/consult/ConsultCard.tsx +7 -6
  198. package/src/client/environment/EnvironmentPanel.tsx +22 -25
  199. package/src/client/environment/maintenance/DiskUsageCard.tsx +69 -96
  200. package/src/client/environment/profiles-incomplete-ui.test.ts +8 -8
  201. package/src/client/export/ExportView.tsx +7 -16
  202. package/src/client/history/HistoryPanel.tsx +88 -28
  203. package/src/client/history/history-locales.ts +3 -3
  204. package/src/client/home/BackupScheduleCard.tsx +77 -69
  205. package/src/client/home/HomePanel.tsx +47 -12
  206. package/src/client/import/ConflictList.tsx +13 -13
  207. package/src/client/import/ForeignImportView.tsx +67 -9
  208. package/src/client/import/ImportWizardView.tsx +4 -4
  209. package/src/client/import/PathMappingForm.tsx +36 -9
  210. package/src/client/import/PathPickerDialog.tsx +2 -1
  211. package/src/client/import/import-wizard-split.test.ts +1 -1
  212. package/src/client/import/import-wizard-steps.tsx +51 -39
  213. package/src/client/import/use-import-wizard-controller.test.ts +129 -0
  214. package/src/client/import/use-import-wizard-controller.ts +116 -22
  215. package/src/client/library/ArtifactRow.tsx +2 -2
  216. package/src/client/library/BackupInspectView.tsx +21 -15
  217. package/src/client/library/LibraryActions.tsx +116 -28
  218. package/src/client/library/LibraryPanel.tsx +14 -15
  219. package/src/client/library/RestorePlanView.tsx +13 -8
  220. package/src/client/locales/about.ts +0 -2
  221. package/src/client/locales/backup.ts +15 -12
  222. package/src/client/locales/common.ts +2 -0
  223. package/src/client/locales/export.ts +5 -12
  224. package/src/client/locales/foreign.ts +4 -2
  225. package/src/client/locales/import.ts +5 -2
  226. package/src/client/locales/overview.ts +4 -0
  227. package/src/client/locales/profiles.ts +32 -4
  228. package/src/client/locales/restore.ts +2 -2
  229. package/src/client/locales/sessions.ts +0 -2
  230. package/src/client/locales/shell.ts +2 -2
  231. package/src/client/market/MarketImportReview.tsx +4 -4
  232. package/src/client/market/MarketPanel.tsx +58 -56
  233. package/src/client/market/MyConfigsList.tsx +34 -32
  234. package/src/client/market/MyConfigsLoginCard.tsx +12 -15
  235. package/src/client/market/MyConfigsView.tsx +8 -15
  236. package/src/client/market/MyConfigsWizard.tsx +7 -12
  237. package/src/client/market/market-locales.ts +0 -6
  238. package/src/client/market/my-configs-split.test.ts +2 -1
  239. package/src/client/nav-menu-clip-guard.test.ts +52 -0
  240. package/src/client/recovery/IncompleteCopiesSection.tsx +1 -3
  241. package/src/client/recovery/RecoveryPanel.tsx +35 -22
  242. package/src/client/recovery/RollbackCard.tsx +132 -75
  243. package/src/client/recovery/RollbackFileChanges.tsx +40 -27
  244. package/src/client/recovery/SessionHealthCard.tsx +2 -2
  245. package/src/client/recovery/SessionHealthDialog.tsx +5 -7
  246. package/src/client/recovery/SessionLayoutSection.tsx +3 -5
  247. package/src/client/recovery/recovery-locales.ts +12 -8
  248. package/src/client/recovery/rollback-enabled.ts +29 -0
  249. package/src/client/recovery/use-recovery-write.ts +5 -0
  250. package/src/client/run-store.test.ts +30 -0
  251. package/src/client/run-store.ts +21 -1
  252. package/src/client/sync/AddChannelCard.tsx +65 -0
  253. package/src/client/sync/AutosyncCard.tsx +184 -108
  254. package/src/client/sync/ChannelClearConfirmDialog.tsx +5 -1
  255. package/src/client/sync/ChannelConfigDialog.tsx +27 -48
  256. package/src/client/sync/MergePreviewView.tsx +5 -7
  257. package/src/client/sync/PushPreviewCard.tsx +2 -1
  258. package/src/client/sync/PushReportSections.tsx +35 -0
  259. package/src/client/sync/SyncChannelEntryCard.tsx +33 -24
  260. package/src/client/sync/SyncConfirmView.tsx +130 -133
  261. package/src/client/sync/SyncLogList.tsx +29 -14
  262. package/src/client/sync/SyncPanel.tsx +188 -185
  263. package/src/client/sync/SyncProbeRow.tsx +5 -7
  264. package/src/client/sync/SyncRepositoryPicker.tsx +17 -4
  265. package/src/client/sync/SyncSecuritySection.tsx +157 -0
  266. package/src/client/sync/SyncSettingsDialog.tsx +293 -0
  267. package/src/client/sync/SyncSettingsView.test.ts +26 -8
  268. package/src/client/sync/WorkDirCard.tsx +2 -4
  269. package/src/client/sync/config-clear-guard.test.ts +94 -0
  270. package/src/client/sync/config-clear-guard.ts +98 -0
  271. package/src/client/sync/config-dirty.test.ts +91 -0
  272. package/src/client/sync/config-dirty.ts +88 -0
  273. package/src/client/sync/history-model.test.ts +2 -0
  274. package/src/client/sync/history-model.ts +5 -0
  275. package/src/client/sync/merge-request.ts +20 -0
  276. package/src/client/sync/sync-api.ts +13 -1
  277. package/src/client/sync/sync-locales.ts +95 -47
  278. package/src/client/sync/sync-panel-clear.test.ts +44 -0
  279. package/src/client/sync/sync-push-preview.test.ts +9 -0
  280. package/src/client/sync/sync-view.test.ts +20 -0
  281. package/src/client/sync/sync-view.ts +76 -4
  282. package/src/core/backup.test.ts +61 -1
  283. package/src/core/backup.ts +21 -4
  284. package/src/core/boot-rescue.test.ts +35 -0
  285. package/src/core/boot-rescue.ts +13 -2
  286. package/src/core/boot-safety.test.ts +25 -0
  287. package/src/core/boot-safety.ts +37 -2
  288. package/src/core/conflict-decisions.ts +2 -1
  289. package/src/core/exporter.ts +21 -1
  290. package/src/core/journal.test.ts +183 -0
  291. package/src/core/journal.ts +163 -25
  292. package/src/core/local-plugin-host.test.ts +68 -2
  293. package/src/core/local-plugin-host.ts +31 -4
  294. package/src/core/messages.ts +34 -0
  295. package/src/core/migration-history.test.ts +27 -0
  296. package/src/core/migration-history.ts +12 -4
  297. package/src/core/model-tools.test.ts +67 -0
  298. package/src/core/model-tools.ts +22 -4
  299. package/src/core/patch-chain.test.ts +83 -0
  300. package/src/core/patch-chain.ts +150 -0
  301. package/src/core/patch-document.test.ts +48 -1
  302. package/src/core/patch-document.ts +66 -15
  303. package/src/core/patch-layers.test.ts +1 -1
  304. package/src/core/patch-secret-guard.test.ts +110 -0
  305. package/src/core/patch-secret-guard.ts +176 -0
  306. package/src/core/reconcile.ts +32 -4
  307. package/src/core/reinstall.ts +8 -2
  308. package/src/core/restore.ts +32 -7
  309. package/src/core/section-sanitize.ts +37 -0
  310. package/src/core/smoke.test.ts +2 -1
  311. package/src/core/snapshot-diff.test.ts +73 -1
  312. package/src/core/snapshot-diff.ts +66 -21
  313. package/src/core/startup-barrier.test.ts +64 -0
  314. package/src/core/startup-barrier.ts +8 -2
  315. package/src/core/types.ts +43 -2
  316. package/src/core/update-check.test.ts +40 -0
  317. package/src/core/update-check.ts +53 -2
  318. package/src/foreign/claude-code.test.ts +5 -0
  319. package/src/foreign/claude-plugins.test.ts +57 -0
  320. package/src/foreign/claude-sessions-bytes.test.ts +7 -1
  321. package/src/foreign/dsh.test.ts +23 -0
  322. package/src/foreign/kernel.ts +9 -2
  323. package/src/foreign/read-claude-plugins.ts +32 -11
  324. package/src/foreign/read-dsh.ts +33 -2
  325. package/src/foreign/session-ir.test.ts +67 -0
  326. package/src/foreign/session-ir.ts +54 -14
  327. package/src/foreign/session-read.ts +23 -0
  328. package/src/index.facade.test.ts +186 -6
  329. package/src/index.ts +53 -47
  330. package/src/profiles/dsh-profile-copy-rollback.test.ts +58 -4
  331. package/src/profiles/dsh-profile-io.ts +29 -0
  332. package/src/profiles/dsh-profile-manager.test.ts +30 -0
  333. package/src/profiles/dsh-profile-manager.ts +53 -5
  334. package/src/profiles/dsh-profile-runtime.test.ts +29 -7
  335. package/src/profiles/dsh-profile-runtime.ts +17 -3
  336. package/src/profiles/process-control.test.ts +97 -0
  337. package/src/profiles/process-control.ts +28 -1
  338. package/src/routes/profiles.ts +2 -1
  339. package/src/routes/sync.ts +19 -1
  340. package/src/schema/types.ts +16 -1
  341. package/src/security/redaction.test.ts +31 -0
  342. package/src/security/redaction.ts +23 -6
  343. package/src/security/security.test.ts +1 -1
  344. package/src/sync/autosync-repeat.test.ts +58 -0
  345. package/src/sync/autosync-repeat.ts +55 -0
  346. package/src/sync/autosync-scheduler.test.ts +515 -0
  347. package/src/sync/autosync-scheduler.ts +225 -51
  348. package/src/sync/baseline-heal.ts +6 -0
  349. package/src/sync/baseline-record.ts +135 -0
  350. package/src/sync/blob-store.test.ts +16 -0
  351. package/src/sync/blob-store.ts +13 -0
  352. package/src/sync/content-diff.test.ts +95 -0
  353. package/src/sync/content-diff.ts +79 -0
  354. package/src/sync/git/git-transport.test.ts +151 -4
  355. package/src/sync/git/git-transport.ts +143 -27
  356. package/src/sync/github-auth.test.ts +26 -1
  357. package/src/sync/github-auth.ts +37 -1
  358. package/src/sync/local-changes.ts +40 -0
  359. package/src/sync/merge-apply-plan.ts +117 -0
  360. package/src/sync/merge-keyed.test.ts +167 -0
  361. package/src/sync/merge-keyed.ts +160 -0
  362. package/src/sync/messages.ts +3 -0
  363. package/src/sync/patch-line-identity.test.ts +73 -0
  364. package/src/sync/patch-line-identity.ts +105 -0
  365. package/src/sync/pending-merge.test.ts +41 -0
  366. package/src/sync/pending-merge.ts +85 -0
  367. package/src/sync/plugin-removals.test.ts +199 -39
  368. package/src/sync/plugin-removals.ts +150 -64
  369. package/src/sync/push-skip.test.ts +326 -0
  370. package/src/sync/push-skip.ts +102 -0
  371. package/src/sync/s3/s3-delete-and-blob-index.test.ts +249 -0
  372. package/src/sync/s3/s3-transport.ts +76 -42
  373. package/src/sync/sync-config.test.ts +39 -12
  374. package/src/sync/sync-device-identity.test.ts +3 -0
  375. package/src/sync/sync-engine.test.ts +465 -12
  376. package/src/sync/sync-engine.ts +189 -193
  377. package/src/sync/sync-history.ts +7 -0
  378. package/src/sync/sync-state.ts +48 -0
  379. package/src/sync/transport.test.ts +13 -1
  380. package/src/sync/transport.ts +12 -4
  381. package/src/sync/webdav/webdav-delete-and-blob-index.test.ts +249 -0
  382. package/src/sync/webdav/webdav-transport.ts +86 -34
  383. package/src/sync/workspace-merge.ts +9 -2
  384. package/src/ui/artifact-view.ts +1 -1
  385. package/src/ui/commands.test.ts +11 -0
  386. package/src/ui/commands.ts +5 -14
  387. package/src/ui/dsh-profiles-view.test.ts +16 -0
  388. package/src/ui/dsh-profiles-view.ts +11 -5
  389. package/src/ui/foreign-view.test.ts +49 -0
  390. package/src/ui/foreign-view.ts +47 -0
  391. package/src/ui/i18n.ts +15 -2
  392. package/src/ui/menu-placement.ts +1 -1
  393. package/src/ui/migration-consult-view.test.ts +20 -1
  394. package/src/ui/migration-consult-view.ts +17 -0
  395. package/src/ui/overview-view.ts +10 -0
  396. package/src/ui/report.test.ts +25 -1
  397. package/src/ui/report.ts +15 -4
  398. package/src/ui/selection-model.test.ts +29 -1
  399. package/src/ui/selection-model.ts +25 -4
  400. package/src/utils/async-once.ts +14 -0
  401. package/src/utils/js-yaml4.d.ts +35 -0
  402. package/src/utils/patch-chain-read.test.ts +171 -0
  403. package/src/utils/patch-chain-read.ts +259 -0
  404. package/src/utils/patch-yaml.test.ts +215 -3
  405. package/src/utils/patch-yaml.ts +98 -2
  406. package/src/utils/paths.test.ts +14 -1
  407. package/src/utils/paths.ts +35 -0
  408. package/src/utils/workdir-lock.test.ts +69 -0
  409. package/src/utils/workdir-lock.ts +17 -3
  410. package/lib/ui/path-mapping.d.ts +0 -38
  411. package/lib/ui/path-mapping.js +0 -75
  412. package/src/client/common/InfoHint.tsx +0 -289
  413. package/src/client/common/info-hint-guard.test.ts +0 -1119
  414. package/src/client/sync/DecryptPasswordCard.tsx +0 -48
  415. package/src/client/sync/SecurityOptionsCard.tsx +0 -97
  416. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -213
  417. package/src/ui/path-mapping.test.ts +0 -67
  418. package/src/ui/path-mapping.ts +0 -103
@@ -94,8 +94,23 @@ interface SideRead {
94
94
 
95
95
  const ABSENT: SideRead = { exists: false, bytes: 0, text: '', binary: false, oversized: false, unreadable: false };
96
96
 
97
+ /** 该 errno 是否等于「路径真的不存在」(其余 = 存在但拿不到,绝不能当作不存在)。 */
98
+ function isEnoent(err: unknown): boolean {
99
+ return typeof err === 'object' && err !== null && (err as { code?: unknown }).code === 'ENOENT';
100
+ }
101
+
102
+ /**
103
+ * 「存在但读不出」的唯一形态(目录 / 无权限 / 被占用 / stat 抛非 ENOENT)。
104
+ * 与 ABSENT(真的不存在)严格区分:判成不存在会让预览把改不了的文件显示成「新增」(审计 P2-6)。
105
+ */
106
+ function unreadableAt(bytes: number): SideRead {
107
+ return { exists: true, bytes, text: null, binary: false, oversized: false, unreadable: true };
108
+ }
109
+
97
110
  /** 只探测存在性(预算触顶时用:不读内容,只 stat)。 */
98
- async function probeExists(opts: { homeDir: string; target: string; msg: MsgFunc }): Promise<'exists' | 'absent' | 'escape'> {
111
+ async function probeExists(
112
+ opts: { homeDir: string; target: string; msg: MsgFunc },
113
+ ): Promise<'exists' | 'absent' | 'unreadable' | 'escape'> {
99
114
  let abs: string;
100
115
  try {
101
116
  abs = homeAbs(opts.homeDir, opts.target, opts.msg);
@@ -104,29 +119,57 @@ async function probeExists(opts: { homeDir: string; target: string; msg: MsgFunc
104
119
  }
105
120
  try {
106
121
  const stat = await fs.stat(abs);
107
- return stat.isFile() ? 'exists' : 'absent';
108
- } catch {
109
- return 'absent';
122
+ return stat.isFile() ? 'exists' : 'unreadable';
123
+ } catch (err) {
124
+ // ENOENT 才是「没有」;EACCES 一类说明路径在,只是拿不到状态
125
+ return isEnoent(err) ? 'absent' : 'unreadable';
110
126
  }
111
127
  }
112
128
 
113
- async function readSide(abs: string, maxBytes: number): Promise<SideRead> {
129
+ /** readSide 依赖的最小 fs 能力(默认 = 真 fs)。 */
130
+ export interface SideReadIo {
131
+ stat(abs: string): Promise<{ isFile(): boolean; size: number }>;
132
+ readFile(abs: string): Promise<Buffer>;
133
+ }
134
+
135
+ const REAL_SIDE_IO: SideReadIo = {
136
+ stat: (abs) => fs.stat(abs),
137
+ readFile: (abs) => fs.readFile(abs),
138
+ };
139
+
140
+ /**
141
+ * 读单侧内容。
142
+ *
143
+ * 三种结果必须分开:真的没有(ABSENT)/ 存在但读不出(unreadable)/ 正常读到。
144
+ * 原先整段包一个 try + 末尾 `catch { return ABSENT }`,把「stat 成功、readFile 抛 EACCES」
145
+ * 判成了不存在 —— 预览因此把只读文件显示成「新增」(审计 P2-6)。
146
+ *
147
+ * `io` 参数只为单测注入:Windows 上造不出 EACCES 夹具,而这条分支必须被真正覆盖;
148
+ * 生产调用方一律不传(走 REAL_SIDE_IO)。
149
+ */
150
+ export async function readSide(abs: string, maxBytes: number, io: SideReadIo = REAL_SIDE_IO): Promise<SideRead> {
151
+ let stat: { isFile(): boolean; size: number };
114
152
  try {
115
- const stat = await fs.stat(abs);
116
- if (!stat.isFile()) {
117
- return { exists: true, bytes: stat.size, text: null, binary: false, oversized: false, unreadable: true };
118
- }
119
- if (stat.size > maxBytes) {
120
- return { exists: true, bytes: stat.size, text: null, binary: false, oversized: true, unreadable: false };
121
- }
122
- const buf = await fs.readFile(abs);
123
- if (buf.subarray(0, 8192).includes(0)) {
124
- return { exists: true, bytes: buf.byteLength, text: null, binary: true, oversized: false, unreadable: false };
125
- }
126
- return { exists: true, bytes: buf.byteLength, text: buf.toString('utf8'), binary: false, oversized: false, unreadable: false };
127
- } catch {
128
- return ABSENT;
153
+ stat = await io.stat(abs);
154
+ } catch (err) {
155
+ return isEnoent(err) ? ABSENT : unreadableAt(0);
156
+ }
157
+ if (!stat.isFile()) return unreadableAt(stat.size);
158
+ if (stat.size > maxBytes) {
159
+ return { exists: true, bytes: stat.size, text: null, binary: false, oversized: true, unreadable: false };
160
+ }
161
+ let buf: Buffer;
162
+ try {
163
+ buf = await io.readFile(abs);
164
+ } catch (err) {
165
+ // stat 已证明它是普通文件:这里读失败 = 存在但读不出(EACCES/EBUSY/…);
166
+ // stat 与 read 之间被删掉的 ENOENT 仍按「不存在」处理,那才是当时的真实状态
167
+ return isEnoent(err) ? ABSENT : unreadableAt(stat.size);
168
+ }
169
+ if (buf.subarray(0, 8192).includes(0)) {
170
+ return { exists: true, bytes: buf.byteLength, text: null, binary: true, oversized: false, unreadable: false };
129
171
  }
172
+ return { exists: true, bytes: buf.byteLength, text: buf.toString('utf8'), binary: false, oversized: false, unreadable: false };
130
173
  }
131
174
 
132
175
  /** 变更状态判定(恢复类:before 存在 = 修改,不存在 = 新增)。 */
@@ -252,10 +295,12 @@ export async function summarizeRestoreChanges(opts: {
252
295
  entry.status = 'skip';
253
296
  entry.statSkipped = 'unreadable';
254
297
  } else {
255
- entry.beforeExists = probe === 'exists';
298
+ // 「存在但读不出」与 readSide 同口径:算存在(否则会显示成「新增」),只把行数统计标成 unreadable
299
+ const unreadable = probe === 'unreadable';
300
+ entry.beforeExists = probe === 'exists' || unreadable;
256
301
  entry.afterExists = restoreKind;
257
302
  entry.status = statusOf(action.kind, entry.beforeExists);
258
- entry.statSkipped = 'budget';
303
+ entry.statSkipped = unreadable ? 'unreadable' : 'budget';
259
304
  }
260
305
  skipped += 1;
261
306
  entries.push(entry);
@@ -8,7 +8,12 @@
8
8
  */
9
9
  import test from 'node:test';
10
10
  import assert from 'node:assert/strict';
11
+ import fssync from 'node:fs';
12
+ import os from 'node:os';
13
+ import path from 'node:path';
11
14
  import { resolveStartupSafeMode, classifyStartup, FAIL_CLOSED_STARTUP } from './startup-barrier.ts';
15
+ import { JournalStore, createJournalEntry } from './journal.ts';
16
+ import type { ReconcileEnv, ReconcileProbeHooks } from './reconcile.ts';
12
17
 
13
18
  test('issue #87:NORMAL + 无活锁者 + 陈旧 blocked 标记 → 解除(内存标志与 durable 标记一起复位)', () => {
14
19
  assert.deepEqual(
@@ -67,3 +72,62 @@ test('issue #87:classifyStartup 仍是分类唯一来源(形状自检,防
67
72
  });
68
73
  assert.equal(typeof classifier.classify, 'function');
69
74
  });
75
+
76
+ // ---------- P3-8:LOCKED_LIVE 的判据是「持锁 + live 且未 terminal 的 journal」 ----------
77
+
78
+ function tmpDir(t: test.TestContext): string {
79
+ const dir = fssync.mkdtempSync(path.join(os.tmpdir(), 'sb-'));
80
+ t.after(() => fssync.rmSync(dir, { recursive: true, force: true }));
81
+ return dir;
82
+ }
83
+
84
+ const probeHooks: ReconcileProbeHooks = {
85
+ verifyStepFingerprint: async () => 'before-match',
86
+ probeExternal: async () => 'not-installed',
87
+ snapshotExists: async () => true,
88
+ };
89
+ // 保守 env:真实进程探测恒 false(LOCKED 下由 inspectStartup 强制按 live 处理)
90
+ const probeEnv: ReconcileEnv = { environmentFingerprint: 'fp', isLiveOwner: async () => false };
91
+
92
+ function journalStore(dir: string): JournalStore {
93
+ return new JournalStore({ transactionsDir: path.join(dir, 'transactions') });
94
+ }
95
+
96
+ test('审计 P3-8:另一实例持锁 + 存在真正在跑的 journal(live 且未 terminal)→ LOCKED_LIVE(旧实现给 NORMAL)', async (t) => {
97
+ const dir = tmpDir(t);
98
+ const store = journalStore(dir);
99
+ const operationId = '00000000-0000-4000-8000-0000000000a1';
100
+ await store.create(createJournalEntry(
101
+ 'import-apply',
102
+ { operationId, ownerInstanceId: 'other-instance', lockId: 'lock-1', packageVersion: '0.1.80', environmentFingerprint: 'fp' },
103
+ '2026-01-01T00:00:00.000Z',
104
+ ));
105
+ // 进行中(非 terminal):另一个存活实例正在 apply
106
+ await store.update(operationId, (cur) => ({ ...cur, state: 'APPLYING' }));
107
+
108
+ const { state } = await classifyStartup({
109
+ store, hooks: probeHooks, env: probeEnv, lockState: 'LOCKED',
110
+ }).classify();
111
+
112
+ assert.equal(state.kind, 'LOCKED_LIVE', `持锁 + 真正在跑必须分类为 LOCKED_LIVE;实际 ${state.kind}`);
113
+ assert.equal(state.kind === 'LOCKED_LIVE' ? state.operationId : undefined, operationId, '必须指出是哪条 live op');
114
+ });
115
+
116
+ test('审计 P3-8 对照:持锁但 active 里只有已 terminal 的 journal → NORMAL(不误报 LOCKED_LIVE)', async (t) => {
117
+ const dir = tmpDir(t);
118
+ const store = journalStore(dir);
119
+ const operationId = '00000000-0000-4000-8000-0000000000a2';
120
+ await store.create(createJournalEntry(
121
+ 'import-apply',
122
+ { operationId, ownerInstanceId: 'other-instance', lockId: 'lock-1', packageVersion: '0.1.80', environmentFingerprint: 'fp' },
123
+ '2026-01-01T00:00:00.000Z',
124
+ ));
125
+ await store.update(operationId, (cur) => ({ ...cur, state: 'COMMITTED' }));
126
+
127
+ const { state } = await classifyStartup({
128
+ store, hooks: probeHooks, env: probeEnv, lockState: 'LOCKED',
129
+ }).classify();
130
+
131
+ assert.equal(state.kind, 'NORMAL', '没有未收敛的 live op ⇒ 不存在「正在跑的操作」可报');
132
+ });
133
+
@@ -44,8 +44,14 @@ export function classifyStartup(opts: {
44
44
  const insp = await inspectStartup(opts.store, opts.hooks, opts.env, opts.options ?? {}, opts.lockState);
45
45
  let state: StartupRecoveryState;
46
46
  if (opts.lockState === 'LOCKED') {
47
- // fresh heartbeat:活锁;若仍有 unresolved journal → 视为 live op(LOCKED_LIVE,不作 recovery/接管)
48
- state = insp.unresolved.length > 0 ? { kind: 'LOCKED_LIVE', operationId: insp.unresolved[0] } : { kind: 'NORMAL' };
47
+ // fresh heartbeat:活锁。判据 = 「另一实例持锁 + 确实有 live 且未到 terminal 的 journal」——
48
+ // 那才是正在跑的操作,分类为 LOCKED_LIVE(不作 recovery/接管,也不启动调度器)。
49
+ // 审计 P3-8:旧实现在这里看 unresolved,但 live 分支恒 unresolved:false(且 LOCKED 下所有
50
+ // journal 都被强制按 live 处理),于是「持锁 + 真正在跑」永远落到 NORMAL;只有 parse 失败
51
+ // 的 corrupt journal(走 quarantine 分支)才碰巧命中 LOCKED_LIVE。现在改用 liveIncomplete。
52
+ state = insp.liveIncomplete.length > 0
53
+ ? { kind: 'LOCKED_LIVE', operationId: insp.liveIncomplete[0] }
54
+ : { kind: 'NORMAL' };
49
55
  } else if (insp.recoveryRequired) {
50
56
  state = { kind: 'RECOVERY_REQUIRED', operationId: insp.unresolved[0] };
51
57
  } else if (insp.unresolved.length > 0 || insp.safeModeRequired) {
package/src/core/types.ts CHANGED
@@ -9,6 +9,7 @@ import type { EncryptionInfo, Manifest, SectionId, WorkspaceRecord } from '../sc
9
9
  import type { TombstoneKind } from '../schema/tombstones.ts';
10
10
  import type { MutationLockPort } from '../utils/env-lock.ts';
11
11
  import type { RecursiveListing } from '../utils/recursive-walk.ts';
12
+ import type { PatchChainRead, PatchWriteOutcome } from './patch-chain.ts';
12
13
  import type { Logger } from '../utils/logger.ts';
13
14
  import { zhMsg } from './messages.ts';
14
15
  import type { MsgFunc } from './messages.ts';
@@ -398,7 +399,21 @@ export interface PatchChange { lineId: string; raw: unknown; action: 'insert' |
398
399
 
399
400
  export interface PatchFileFacade {
400
401
  readPatchLines(file: string): Promise<{ lineId: string; raw: unknown }[]>;
401
- applyPatchChanges(file: string, changes: PatchChange[]): Promise<void>;
402
+ /**
403
+ * 写回一层 patch 并返回本次的降级记录(issue #144)。
404
+ *
405
+ * 返回 `PatchWriteOutcome` 而不是 `void`:请求 insert、但**生效链上已有别的层**提供该 id 时,
406
+ * 门面会把它降级成顶层覆盖行(否则就是两条 insert 抢同一个 id,插件保存配置时必然报
407
+ * `overridden by a home patch or command-line overlay`)。调用方据此给用户一条 warning。
408
+ */
409
+ applyPatchChanges(file: string, changes: PatchChange[]): Promise<PatchWriteOutcome>;
410
+ /**
411
+ * 读**整条生效 patch 链**(bundle 层 + profile 层 + home 层)的文档,issue #144。
412
+ *
413
+ * 可选能力:老宿主 / 测试替身不实现 ⇒ 调用方的链判据退化为「两层 patch 文件」的旧口径
414
+ * (fail-open,绝不因为读不到 bundle 层而拒绝写入)。
415
+ */
416
+ readPatchChain?(): Promise<PatchChainRead>;
402
417
  }
403
418
 
404
419
  /**
@@ -673,7 +688,21 @@ export type GlobalConflictStrategy = 'merge' | 'replace' | 'skipExisting';
673
688
  */
674
689
  export type SessionFormatDisposition = 'abort' | 'skip' | 'guide';
675
690
 
676
- export interface ConflictDecision { itemId: string; resolution: ItemResolution; }
691
+ export interface ConflictDecision {
692
+ itemId: string;
693
+ resolution: ItemResolution;
694
+ /**
695
+ * 这条裁决是**谁**下的(issue #136 A):
696
+ * - `'item'`:用户对该计划项逐项决策(`decisions.resolutions[id]`,含导入页的逐行确认)——
697
+ * 适配器可把它当作「我确实要这一行按导入值写」的确认。
698
+ * - `'section'`:由**分区级**裁决换算而来(合并落地 `planMergeApply` 的 second pass 把
699
+ * 「该分区已裁决」逐项注入成 `useImported`)。分区级裁决决定「分区是否应用」,
700
+ * 不构成对某一行值的确认,写回守卫不得据此清空本机明文。
701
+ * - 缺省:未标注来源。写回守卫按**未确认**处理(默认拒绝清空)—— 忘了标注只会少清空,
702
+ * 不会误清空;确认必须显式写明来源。
703
+ */
704
+ decidedBy?: 'item' | 'section';
705
+ }
677
706
 
678
707
  export interface PathMapping {
679
708
  oldPrefix: string;
@@ -1230,6 +1259,18 @@ export interface ConfigAdapter<TSection = unknown> {
1230
1259
  * 实现方应尊重 `options.includeItems?.[this.id]`(条目级选择,见 adapters/units.ts)。 */
1231
1260
  export(ctx: HostContext, options: ExportOptions): Promise<ExportSection<TSection>>;
1232
1261
 
1262
+ /**
1263
+ * 可选:脱敏**归属标注**(issue #136 C)—— 把 SecretScanner 的命中路径归属回具体载荷单元。
1264
+ *
1265
+ * 调用点只有一个:`sanitizeSectionData()`(`src/core/section-sanitize.ts`),纯函数语义
1266
+ * (不改入参、不读盘);只做「标注」,绝不把值写回去(脱敏仍是扫描器的职责)。
1267
+ *
1268
+ * plugins 分区用它把 `patch[i].raw.x` 的命中写进第 i 行的 `redactedPaths`:目标机据此区分
1269
+ * 「被剥空」与「用户写空」,写回层才能精确保护本机明文(`src/core/patch-secret-guard.ts`)。
1270
+ * 未实现 = 载荷不含归属信息,写回侧走保守分支。
1271
+ */
1272
+ annotateRedactions?(sanitized: unknown, hits: SensitiveHit[]): unknown;
1273
+
1233
1274
  /**
1234
1275
  * 可选:**只读预览**(`/export-preview` 用)。
1235
1276
  *
@@ -147,3 +147,43 @@ test('UpdateChecker:失败不写缓存(下次仍会重试),且失败结
147
147
  assert.equal(good.ok, true, '失败不进缓存 → 下一次恢复后可以直接成功');
148
148
  assert.equal(good.ok === true ? good.info.latest : null, '2.0.0');
149
149
  });
150
+
151
+ /* ---------------- 审计 P11-6:体积上限必须按字节,且不把大响应读进内存 ---------------- */
152
+
153
+ test('P11-6 回归:上限按**字节**判定 —— CJK 120KB 响应不得因 text.length 只有 40K 被放行', async () => {
154
+ // 一个 CJK 字符占 3 个 UTF-8 字节:旧实现用 text.length(UTF-16 代码单元)判上限 ⇒ 120KB 的中文
155
+ // 响应只数到 40K,上限形同虚设。这里同时钉住两个事实:字节超限、代码单元不超限。
156
+ const cjk = JSON.stringify({ version: '9.9.9', description: '中'.repeat(40_000) });
157
+ assert.ok(cjk.length <= UPDATE_CHECK_MAX_BYTES, '前提:代码单元没超限(旧口径会放行)');
158
+ assert.ok(new TextEncoder().encode(cjk).byteLength > UPDATE_CHECK_MAX_BYTES, '前提:字节数超限');
159
+ const r = await probeLatestVersion({ fetchImpl: stubFetch(cjk).impl });
160
+ assert.deepEqual(r, { ok: false, error: 'registry response too large' });
161
+ });
162
+
163
+ test('P11-6:Content-Length 声明超限时直接拒绝(一个字节都不读)', async () => {
164
+ // 不用真 Response:undici 的 Response 构造期就会 pull 一次流(实测),用它证不了「没读」。
165
+ // 这里用 getter 记账:只要实现碰了 body / arrayBuffer 就会抛错并计数。
166
+ let bodyReads = 0;
167
+ const impl = (async () => ({
168
+ ok: true,
169
+ status: 200,
170
+ headers: new Headers({ 'content-length': String(UPDATE_CHECK_MAX_BYTES + 1) }),
171
+ get body(): ReadableStream<Uint8Array> | null {
172
+ bodyReads += 1;
173
+ throw new Error('body must not be read');
174
+ },
175
+ arrayBuffer: async () => {
176
+ bodyReads += 1;
177
+ throw new Error('body must not be read');
178
+ },
179
+ })) as unknown as typeof fetch;
180
+ const r = await probeLatestVersion({ fetchImpl: impl });
181
+ assert.deepEqual(r, { ok: false, error: 'registry response too large' });
182
+ assert.equal(bodyReads, 0, '有 Content-Length 就先拒,不把大响应读进内存');
183
+ });
184
+
185
+ test('P11-6:小体量 CJK 响应照常解析(字节口径不误伤)', async () => {
186
+ const body = JSON.stringify({ version: '9.9.9', description: '中文说明'.repeat(100) });
187
+ const r = await probeLatestVersion({ fetchImpl: stubFetch(body).impl });
188
+ assert.deepEqual(r, { ok: true, version: '9.9.9' });
189
+ });
@@ -93,6 +93,57 @@ export interface UpdateCheckDeps {
93
93
  /** 探测结果(内部用):成功给版本号,失败给原因 */
94
94
  type ProbeResult = { ok: true; version: string } | { ok: false; error: string }
95
95
 
96
+ /**
97
+ * **按字节**有界地读响应体;超过 `maxBytes` 返回 null(调用方给 'registry response too large')。
98
+ *
99
+ * 为什么不是 `text.length`:它数的是 UTF-16 代码单元,一个 CJK 字符占 3 个 UTF-8 字节 ⇒
100
+ * 120KB 的中文响应 `text.length` 只有 40K,上限形同虚设(审计 P11-6)。
101
+ * 顺序:Content-Length 预检(有就先拒,一个字节都不读)→ 流式累计,越界立刻 abort
102
+ * (不把大响应读进内存)→ 没有 body 流的运行时退回 arrayBuffer 量 byteLength。
103
+ */
104
+ async function readBoundedBody(
105
+ res: Response, maxBytes: number, controller: AbortController,
106
+ ): Promise<string | null> {
107
+ // 防御:真实 Response 一定有 headers/body,但注入的替身(脚本、极简 mock)可能只给 text()。
108
+ // 缺什么就退化成「全量读 + 字节口径判定」——判据不变,只是失去流式提前止损。
109
+ const declared = typeof res.headers?.get === 'function' ? res.headers.get('content-length') : null
110
+ if (declared !== null) {
111
+ const n = Number(declared)
112
+ if (Number.isFinite(n) && n > maxBytes) {
113
+ controller.abort()
114
+ return null
115
+ }
116
+ }
117
+ const body = (res as { body?: ReadableStream<Uint8Array> | null }).body
118
+ if (body === null || body === undefined) {
119
+ const bytes = typeof res.arrayBuffer === 'function'
120
+ ? new Uint8Array(await res.arrayBuffer())
121
+ : new TextEncoder().encode(await res.text())
122
+ return bytes.byteLength > maxBytes ? null : new TextDecoder('utf-8').decode(bytes)
123
+ }
124
+ const reader = body.getReader()
125
+ const chunks: Uint8Array[] = []
126
+ let total = 0
127
+ for (;;) {
128
+ const { done, value } = await reader.read()
129
+ if (done) break
130
+ total += value.byteLength
131
+ if (total > maxBytes) {
132
+ controller.abort()
133
+ await reader.cancel().catch(() => undefined)
134
+ return null
135
+ }
136
+ chunks.push(value)
137
+ }
138
+ const merged = new Uint8Array(total)
139
+ let at = 0
140
+ for (const chunk of chunks) {
141
+ merged.set(chunk, at)
142
+ at += chunk.byteLength
143
+ }
144
+ return new TextDecoder('utf-8').decode(merged)
145
+ }
146
+
96
147
  /**
97
148
  * 探测 npm latest(无缓存、无状态)。任何异常都被收成 `{ ok:false, error }`:
98
149
  * 网络错误 / 超时 / 非 2xx / 体积超限 / JSON 畸形 / 版本号形态不认识。
@@ -109,8 +160,8 @@ export async function probeLatestVersion(deps: UpdateCheckDeps = {}): Promise<Pr
109
160
  headers: { accept: 'application/json' },
110
161
  })
111
162
  if (!res.ok) return { ok: false, error: `registry returned HTTP ${res.status}` }
112
- const text = await res.text()
113
- if (text.length > UPDATE_CHECK_MAX_BYTES) return { ok: false, error: 'registry response too large' }
163
+ const text = await readBoundedBody(res, UPDATE_CHECK_MAX_BYTES, controller)
164
+ if (text === null) return { ok: false, error: 'registry response too large' }
114
165
  let payload: unknown
115
166
  try {
116
167
  payload = JSON.parse(text) as unknown
@@ -55,6 +55,11 @@ test('t0 frontmatter 切分与 URL userinfo 剥离的边界', () => {
55
55
  assert.equal(frontmatterProblem(['---', 'name: a', 'description: ok', '---', 'body'].join(NL)), null);
56
56
  assert.deepEqual(stripUserInfo('https://u:p@h/mcp'), { url: 'https://h/mcp', stripped: true });
57
57
  assert.deepEqual(stripUserInfo('https://h/path@x'), { url: 'https://h/path@x', stripped: false });
58
+ // 无路径 URL 的 query 里出现 @ 不是 userinfo(曾把整条 URL 截成 https://b)
59
+ assert.deepEqual(stripUserInfo('https://h?k=a@b'), { url: 'https://h?k=a@b', stripped: false });
60
+ assert.deepEqual(stripUserInfo('https://h?email=a@b&x=1'), { url: 'https://h?email=a@b&x=1', stripped: false });
61
+ assert.deepEqual(stripUserInfo('https://h#a@b'), { url: 'https://h#a@b', stripped: false });
62
+ assert.deepEqual(stripUserInfo('https://u:p@h?k=1'), { url: 'https://h?k=1', stripped: true });
58
63
  assert.deepEqual(stripUserInfo('npx'), { url: 'npx', stripped: false });
59
64
  });
60
65
 
@@ -219,6 +219,63 @@ test('单插件文件数触顶报 max-plugin-files-reached,且载荷里不超
219
219
  });
220
220
  });
221
221
 
222
+
223
+ /**
224
+ * 审计 P7-9(边界回归):文件数**恰好等于**上限不是截断。
225
+ *
226
+ * 旧实现拿 walkFiles 返回数组的长度反推「是否触顶」(length >= maxPluginFiles)—— 共享内核
227
+ * 最多只返回 maxFiles 条,于是「正好 N 个」必然被误报成 max-plugin-files-reached。
228
+ * 现在由 walkFilesChecked 多要一条来取证:N+1 条才算真截断。
229
+ */
230
+ test('审计 P7-9(边界回归):文件数恰好等于上限时不报触顶,超过上限才报', async () => {
231
+ await withClaudeDir(async (claudeDir) => {
232
+ const marketDir = path.join(claudeDir, 'plugins', 'marketplaces', 'm');
233
+ await write(path.join(marketDir, '.claude-plugin', 'marketplace.json'), JSON.stringify({
234
+ name: 'm',
235
+ plugins: [{ name: 'exact', source: { source: 'github', repo: 'acme/exact' } }],
236
+ }));
237
+ /** 只带 commands/ 的极简插件:文件总数可精确控制 */
238
+ const makePlugin = async (name: string, commandFiles: number): Promise<string> => {
239
+ const dir = path.join(marketDir, 'plugins', name);
240
+ await write(path.join(dir, '.claude-plugin', 'plugin.json'), JSON.stringify({ name }));
241
+ for (let k = 0; k < commandFiles; k += 1) {
242
+ await write(path.join(dir, 'commands', 'c' + String(k) + '.md'), 'cmd ' + String(k));
243
+ }
244
+ return dir;
245
+ };
246
+
247
+ // 恰好 2 个文件 + 上限 2 → 没有被截断,不得报码(旧实现会误报)
248
+ await makePlugin('exact', 2);
249
+ const atLimit = await readClaudePlugins({
250
+ claudeDir,
251
+ settings: { enabledPlugins: { 'exact@m': true } },
252
+ limits: { maxPluginFiles: 2 },
253
+ });
254
+ const exact = pluginOf(atLimit, 'exact');
255
+ assert.ok(exact !== undefined, '插件必须产出:' + JSON.stringify(atLimit.skipped));
256
+ assert.equal(exact.commandCount, 2, '恰好等于上限时必须完整计数');
257
+ assert.equal(
258
+ exact.readFindings?.find((f) => f.detail === 'max-plugin-files-reached'),
259
+ undefined,
260
+ '恰好等于上限不是截断,实际 findings:' + JSON.stringify(exact.readFindings),
261
+ );
262
+
263
+ // 3 个文件 + 上限 2 → 真的截断了:必须报码,且计数不超过上限
264
+ await makePlugin('over', 3);
265
+ const overLimit = await readClaudePlugins({
266
+ claudeDir,
267
+ settings: { enabledPlugins: { 'over@m': true } },
268
+ limits: { maxPluginFiles: 2 },
269
+ });
270
+ const over = pluginOf(overLimit, 'over');
271
+ assert.ok(over !== undefined, '插件必须产出:' + JSON.stringify(overLimit.skipped));
272
+ const finding = over.readFindings?.find((f) => f.detail === 'max-plugin-files-reached');
273
+ assert.ok(finding !== undefined, '真触顶必须报码:' + JSON.stringify(over.readFindings));
274
+ assert.equal(finding.count, 2);
275
+ assert.ok((over.commandCount ?? 0) <= 2, '截断后计数不得带超过上限的条目');
276
+ });
277
+ });
278
+
222
279
  test('plugin.json 解析失败:回落目录名并报码(绝不猜字段)', async () => {
223
280
  await withClaudeDir(async (claudeDir) => {
224
281
  const pluginDir = path.join(claudeDir, 'plugins', 'marketplaces', 'm', 'plugins', 'broken');
@@ -204,7 +204,13 @@ const GOLDEN: Record<string, string> = {
204
204
  'frames-crossing-64k': '7518:d8be900e191b4a2c2c70819790bc0434bc8bffcbfbafbb00016b09bc04edaa8a',
205
205
  'orphan-empty-and-unknown': '339:7492bd869daacad62ee75688ad8816e23af259215a360d01de9917cdffadc727',
206
206
  'title-only-no-events': 'skip:session-empty',
207
- 'no-uuid-fallback-ids': '743:1c6ea7a8e76016376da2bff5f50e72e824eb7bce9724af4bee40d41d07d0b6df',
207
+ /**
208
+ * 2026-11-14 有意更新(**理由**):审计 P7-4 修掉了「tool_result 带未知 id 仍照发」的悬空引用。
209
+ * 本案的 tool_use 没有 id → 合成器铸了 fallback callId,而结果的 tool_use_id 是 'toolu_x',
210
+ * 两者对不上:旧实现发出一条指向不存在 tool/call 的 tool/result(743 字节),
211
+ * 现在按 orphan-tool-result 计数丢弃(666 字节,少一行 result 事件)。
212
+ */
213
+ 'no-uuid-fallback-ids': '666:88cb76a5a087644466de41f7ace7d82e8e9a1595df271855c963d0688728112f',
208
214
  'timestamps-numeric-and-unparsable': '728:64308bcdea6fc439ed190dd56cad74354e9f53f1274821d97a57bc519f3505ce',
209
215
  'unicode-and-max-id': '729:a8a5abaca4dc7ab15c499b1c38655972283def0bedd3bb73bc87558e22ef51c7',
210
216
  'skip-unsupported-version': 'skip:session-format-unsupported',
@@ -145,6 +145,29 @@ test('dsh t4 扫描:按首帧版本过滤代次(v4 只计数、不进 skip
145
145
  }
146
146
  });
147
147
 
148
+ test('dsh t4b 同一 id 出现在两个会话目录:保留第一个但必须报 session-id-conflict', async (t) => {
149
+ if (!zstdAvailable()) {
150
+ t.skip('本宿主 Node 无 zstd');
151
+ return;
152
+ }
153
+ const root = await tmpRoot('dsh-dup');
154
+ try {
155
+ for (const projectKey of ['--p-a--', '--p-b--']) {
156
+ const dir = path.join('.dsh', 'sessions', projectKey, 'dup-id');
157
+ await fs.mkdir(path.join(root, dir), { recursive: true });
158
+ await fs.writeFile(path.join(root, dir, 'session.v3.jsonl.zstd'), logBytes(headerOf('dup-id', '/p/' + projectKey, 3), [{ seq: 0 }]));
159
+ }
160
+ const read = await readDshLogs({ homeDir: root, env: {}, platform: HOST, generation: 'v3' });
161
+ assert.equal(read.files.length, 1, '同 id 只保留第一个(绝不后写覆盖先写)');
162
+ const conflict = (read.readFindings ?? []).find((s) => s.code === 'session-id-conflict');
163
+ assert.ok(conflict !== undefined, '丢弃必须留码:' + JSON.stringify(read.readFindings));
164
+ assert.equal(conflict.origin, 'dup-id');
165
+ assert.equal(read.extraCounts?.['dsh.logs.scanned'], 2);
166
+ } finally {
167
+ await fs.rm(root, { recursive: true, force: true });
168
+ }
169
+ });
170
+
148
171
  test('dsh t5 直通判定顺序:版本未知 → id 非法 → 版本不等 → cwd 缺失 → 通过', () => {
149
172
  const good: DshSessionLogFile = { id: 'sess-a', cwd: '/home/u/proj', version: 3, name: 'session.v3.jsonl.zstd', data: new Uint8Array([1]) };
150
173
  assert.equal(transcodeDshLog(good, undefined).skip?.code, 'session-format-version-unknown');
@@ -123,8 +123,15 @@ export function stripUserInfo(url: string): { url: string; stripped: boolean } {
123
123
  const rest = url.slice(scheme + 3);
124
124
  const at = rest.indexOf('@');
125
125
  if (at < 0) return { url, stripped: false };
126
- const slash = rest.indexOf('/');
127
- if (slash >= 0 && at > slash) return { url, stripped: false };
126
+ /**
127
+ * userinfo 只可能出现在 authority 段里:@ 若落在第一个 '/'、'?' 或 '#' 之后,
128
+ * 它就是 path/query/fragment 里的普通字符(无路径 URL 的 `?k=a@b` 曾把整条 URL 截成 `https://b`)。
129
+ * 纯字符判定,不用正则。
130
+ */
131
+ const boundary = [rest.indexOf('/'), rest.indexOf('?'), rest.indexOf('#')]
132
+ .filter((i) => i >= 0)
133
+ .sort((a, b) => a - b)[0];
134
+ if (boundary !== undefined && at > boundary) return { url, stripped: false };
128
135
  return { url: url.slice(0, scheme + 3) + rest.slice(at + 1), stripped: true };
129
136
  }
130
137
 
@@ -46,6 +46,22 @@ const WALK_MAX_DEPTH = 8;
46
46
  /** 跳过原因:符号链接(与 read-claude-code 同码同义) */
47
47
  const DETAIL_SYMLINK = 'symlink-skipped';
48
48
 
49
+ /**
50
+ * 走盘并**明确回报是否真的截断**(审计 P7-9)。
51
+ *
52
+ * 共享的 `walkFiles()` 只返回数组,「拿满上限」与「恰好等于上限」在返回值上无法区分 ——
53
+ * 调用方拿长度反推会把「正好 N 个文件」误报成触顶。这里多要一条:拿到 N+1 条才算真截断,
54
+ * 再把多要的那条切掉(共享内核在 `src/foreign/session-read.ts`,本文件不动它)。
55
+ */
56
+ async function walkFilesChecked(
57
+ root: string,
58
+ options: { maxDepth?: number; maxFiles: number; match?: (name: string) => boolean },
59
+ ): Promise<{ files: Awaited<ReturnType<typeof walkFiles>>; truncated: boolean }> {
60
+ const probe = await walkFiles(root, { ...options, maxFiles: options.maxFiles + 1 });
61
+ const truncated = probe.length > options.maxFiles;
62
+ return { files: truncated ? probe.slice(0, options.maxFiles) : probe, truncated };
63
+ }
64
+
49
65
  export interface ClaudePluginReadLimits {
50
66
  /** 启用的插件数上限(默认 50) */
51
67
  readonly maxPlugins?: number;
@@ -353,41 +369,46 @@ async function readPluginAt(
353
369
  }
354
370
 
355
371
  /* commands/**:递归计数(只数,不读内容) */
356
- const commandFiles = await walkFiles(path.join(pluginDir, 'commands'), {
372
+ const commands = await walkFilesChecked(path.join(pluginDir, 'commands'), {
357
373
  maxDepth: WALK_MAX_DEPTH,
358
374
  maxFiles: options.maxPluginFiles,
359
375
  });
360
- if (commandFiles.length > 0) {
361
- plugin.commandCount = commandFiles.length;
376
+ if (commands.files.length > 0) {
377
+ plugin.commandCount = commands.files.length;
362
378
  plugin.components.push('commands');
363
379
  }
364
- if (commandFiles.length >= options.maxPluginFiles) filesTruncated = true;
380
+ if (commands.truncated) filesTruncated = true;
381
+ // 上限是「单插件文件数」:只计数的组件也占额度(否则 N 个目录各带 199 个文件仍然全过)
382
+ let countedFiles = filesUsed + commands.files.length;
365
383
 
366
384
  /* agents/*.md:只取文件名(不读内容) */
367
- const agentFiles = await walkFiles(path.join(pluginDir, 'agents'), {
385
+ const agentsWalked = await walkFilesChecked(path.join(pluginDir, 'agents'), {
368
386
  maxDepth: 0,
369
387
  maxFiles: options.maxPluginFiles,
370
388
  match: (name) => name.endsWith('.md'),
371
389
  });
372
- if (agentFiles.length > 0) {
373
- plugin.agents = agentFiles.map((file) => file.name).sort();
390
+ if (agentsWalked.files.length > 0) {
391
+ plugin.agents = agentsWalked.files.map((file) => file.name).sort();
374
392
  plugin.components.push('agents');
375
393
  }
376
- if (agentFiles.length >= options.maxPluginFiles) filesTruncated = true;
394
+ if (agentsWalked.truncated) filesTruncated = true;
395
+ countedFiles += agentsWalked.files.length;
377
396
 
378
397
  /* hooks/ 与 hooks.json:**只数文件数**(hooks 是执行面,内容一律不读) */
379
- const hookFiles = await walkFiles(path.join(pluginDir, 'hooks'), {
398
+ const hooksWalked = await walkFilesChecked(path.join(pluginDir, 'hooks'), {
380
399
  maxDepth: WALK_MAX_DEPTH,
381
400
  maxFiles: options.maxPluginFiles,
382
401
  });
383
- let hookCount = hookFiles.length;
384
- if (hookCount >= options.maxPluginFiles) filesTruncated = true;
402
+ let hookCount = hooksWalked.files.length;
403
+ if (hooksWalked.truncated) filesTruncated = true;
404
+ countedFiles += hooksWalked.files.length;
385
405
  const hooksJson = await statOrNull(path.join(pluginDir, 'hooks.json'));
386
406
  if (hooksJson !== null && hooksJson.isFile()) hookCount += 1;
387
407
  if (hookCount > 0) {
388
408
  plugin.hookFiles = hookCount;
389
409
  plugin.components.push('hooks');
390
410
  }
411
+ if (countedFiles > options.maxPluginFiles) filesTruncated = true;
391
412
 
392
413
  if (filesTruncated) {
393
414
  findings.push({