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
@@ -12,63 +12,70 @@ import path from 'node:path';
12
12
  import { createHash } from 'node:crypto';
13
13
  import { spawn } from 'node:child_process';
14
14
  import { packLocalPlugins, parsePackOutput, resolveLocalPluginPath } from './local-plugin-pack.js';
15
- import { quoteCmdArg } from './plugin-cli.js';
15
+ import { killTree, quoteCmdArg } from './plugin-cli.js';
16
16
  import { engineMsg } from './messages-core.js';
17
17
  /** `npm pack` 单次调用的超时上限(慢网络/大插件留足余量,但不得无限挂起) */
18
18
  const PACK_TIMEOUT_MS = 5 * 60 * 1000;
19
19
  /** cmd.exe 垫片路径(Windows 上 npm 是 .cmd;与 core/plugin-cli.ts 的 spawnShim 同源做法) */
20
20
  const COMSPEC = process.env.ComSpec ?? 'cmd.exe';
21
21
  /**
22
- * 默认 exec:把 `npm pack` 作为子进程执行并收集 stdout/stderr。
22
+ * 造一个真实 `npm pack` 执行器;默认导出实例给生产用,测试可注入 spawn / killTree。
23
23
  *
24
- * **刻意不用 `execFile(..., { shell: true })`**:该组合会触发 Node 的 DEP0190
25
- * (`shell:true` + args 数组只做拼接不做转义,存在注入面)。仓库既有解法是
26
- * 在 Windows 上显式走 `cmd.exe /d /s /c "<转义后的命令行>"`(见 core/plugin-cli.ts
27
- * 的 spawnShim + quoteCmdArg),本模块复用同一做法。
28
- *
29
- * 失败**不 reject**(把退出码交回调用方判定),只有 spawn 本身失败才 reject——
30
- * 这样「npm 报错」与「npm 不存在」能被分开处理(前者是插件问题,后者是环境问题)。
24
+ * 超时为什么要整棵树:调用方只 `child.kill()` 时,Windows 死掉的只是 cmd.exe 包装进程,
25
+ * npm/pnpm 孙进程成孤儿继续写 tarball,而 `finally` 已经 rm 掉 packDir(审计 P2-3:
26
+ * 孤儿随后在已删除目录里写、或写出一份没人收的产物)。killTree 与 plugin-cli 的
27
+ * `dsh plugin` 子进程用同一实现(Windows taskkill /T /F;POSIX 负 pid 杀进程组 ——
28
+ * 因此 POSIX 上必须 `detached: true` 让子进程自成进程组,否则 -pid 会打到自己的组)。
31
29
  */
32
- const defaultExec = (file, args, opts) => new Promise((resolve, reject) => {
33
- const useShim = process.platform === 'win32';
34
- const [bin, argv] = useShim
35
- ? [COMSPEC, ['/d', '/s', '/c', `"${[file, ...args].map(quoteCmdArg).join(' ')}"`]]
36
- : [file, [...args]];
37
- const child = spawn(bin, argv, {
38
- cwd: opts.cwd,
39
- windowsHide: true,
40
- windowsVerbatimArguments: useShim,
41
- shell: false, // 显式关闭:Windows 路径已由 cmd.exe 自行处理
42
- });
43
- let stdout = '';
44
- let stderr = '';
45
- let settled = false;
46
- const timeoutMs = opts.timeoutMs ?? PACK_TIMEOUT_MS;
47
- const timer = setTimeout(() => {
48
- if (settled)
49
- return;
50
- settled = true;
51
- child.kill();
52
- resolve({ stdout, stderr: engineMsg('core.localPluginHost.packTimeout', { stderr, timeoutMs }), code: 1 });
53
- }, timeoutMs);
54
- timer.unref?.();
55
- child.stdout?.on('data', (d) => { stdout += String(d); });
56
- child.stderr?.on('data', (d) => { stderr += String(d); });
57
- child.on('error', (err) => {
58
- if (settled)
59
- return;
60
- settled = true;
61
- clearTimeout(timer);
62
- reject(err); // spawn 层失败(ENOENT 等):环境问题,如实上抛
63
- });
64
- child.on('close', (code) => {
65
- if (settled)
66
- return;
67
- settled = true;
68
- clearTimeout(timer);
69
- resolve({ stdout, stderr, code });
30
+ export function createPackExec(deps = {}) {
31
+ const spawnImpl = deps.spawn ?? spawn;
32
+ const killTreeImpl = deps.killTree ?? killTree;
33
+ return (file, args, opts) => new Promise((resolve, reject) => {
34
+ const useShim = process.platform === 'win32';
35
+ const [bin, argv] = useShim
36
+ ? [COMSPEC, ['/d', '/s', '/c', `"${[file, ...args].map(quoteCmdArg).join(' ')}"`]]
37
+ : [file, [...args]];
38
+ const child = spawnImpl(bin, argv, {
39
+ cwd: opts.cwd,
40
+ windowsHide: true,
41
+ windowsVerbatimArguments: useShim,
42
+ shell: false, // 显式关闭:Windows 路径已由 cmd.exe 自行处理
43
+ // POSIX:自成进程组,超时才能用负 pid 杀掉整棵树(Windows 忽略该选项,taskkill /T 自己找树)
44
+ detached: process.platform !== 'win32',
45
+ });
46
+ let stdout = '';
47
+ let stderr = '';
48
+ let settled = false;
49
+ const timeoutMs = opts.timeoutMs ?? PACK_TIMEOUT_MS;
50
+ const timer = setTimeout(() => {
51
+ if (settled)
52
+ return;
53
+ settled = true;
54
+ // 整棵树:只 kill() 包装进程会让 npm/pnpm 孙进程成孤儿(见上)
55
+ killTreeImpl(child);
56
+ resolve({ stdout, stderr: engineMsg('core.localPluginHost.packTimeout', { stderr, timeoutMs }), code: 1 });
57
+ }, timeoutMs);
58
+ timer.unref?.();
59
+ child.stdout?.on('data', (d) => { stdout += String(d); });
60
+ child.stderr?.on('data', (d) => { stderr += String(d); });
61
+ child.on('error', (err) => {
62
+ if (settled)
63
+ return;
64
+ settled = true;
65
+ clearTimeout(timer);
66
+ reject(err); // spawn 层失败(ENOENT 等):环境问题,如实上抛
67
+ });
68
+ child.on('close', (code) => {
69
+ if (settled)
70
+ return;
71
+ settled = true;
72
+ clearTimeout(timer);
73
+ resolve({ stdout, stderr, code });
74
+ });
70
75
  });
71
- });
76
+ }
77
+ /** 生产用的默认执行器(真实 spawn + 真实整树终止) */
78
+ const defaultExec = createPackExec();
72
79
  /**
73
80
  * 构造注入给 `PluginsAdapter` 的打包钩子。
74
81
  *
@@ -21,6 +21,7 @@ export declare const zh: {
21
21
  readonly 'export.sectionFailed': '分区 {adapter} 导出失败: {reason}';
22
22
  readonly 'export.credentialsReadFailed': '读取凭据文件失败,跳过秘密导出: {reason}';
23
23
  readonly 'export.vaultRefreshed': '凭据明文未进入备份,已镜像到本机 vault({count} 个文件,恢复时可回填)';
24
+ readonly 'export.pluginDataSensitiveSkipped': '打包时剔除 {count} 个凭据文件(首个:{sample})——第三方插件数据分区永不携带凭据明文';
24
25
  readonly 'export.vaultRefreshSkipped': 'vault 镜像跳过 {rel}: {reason}';
25
26
  readonly 'export.vaultRefreshFailed': 'vault 镜像刷新失败(不影响导出): {reason}';
26
27
  readonly 'export.sessionsLimited': '会话按数量筛选:只带最新 {count} 个(共 {total} 个;单位 = 会话目录,同一会话的日志一起走)';
@@ -289,6 +290,8 @@ export declare const zh: {
289
290
  readonly 'adapter.patchLineCreate': '写入 patch 行 {lineId}';
290
291
  readonly 'adapter.patchLineSame': 'patch 行 {lineId} 已一致';
291
292
  readonly 'adapter.patchLineDiff': 'patch 行 {lineId} 与目标不同';
293
+ readonly 'adapter.patchKeyParseFail': 'patch 行 {ref} 在 {path} 处含会让 DSH 整份文件解析失败的键名:先给该键改成合法名字,再导入';
294
+ readonly 'adapter.patchKeyAmbiguous': 'patch 行 {ref} 在 {path} 处的键名 {key} 会被 DSH 读成数字 / 布尔 / null:给键名加引号(\'{key}\':)后重新导入';
292
295
  readonly 'adapter.promptSame': '提示词 {name} 已一致';
293
296
  readonly 'adapter.promptDiff': '提示词 {name} 与目标不同';
294
297
  readonly 'adapter.promptDiffWithLine': '提示词 {name} 与目标不同(目标位于行 {line})';
@@ -324,6 +327,9 @@ export declare const zh: {
324
327
  readonly 'adapter.pwPatchesUnsupported': 'patchedDependencies 为单行 flow 写法,无法安全剔除缺失条目;若目标机没有对应 patch 文件,pnpm 可能拒绝安装:{line}';
325
328
  readonly 'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml 已写入,但移除了 {count} 条 patchedDependencies 声明(目标机没有对应 patch 文件):{names}';
326
329
  readonly 'adapter.patchWritten': 'patch 行 {ref} 已写入,重启后生效';
330
+ readonly 'adapter.patchSecretsKept': '{ref} 已写入,但保留本机原有内容:{paths}(备份里这些字段被脱敏清空,未用空值覆盖本机;如需清空请对该行显式确认“使用备份配置”)';
331
+ readonly 'adapter.patchSecretsCleared': '{ref} 已按备份写入,字段 {paths} 现为空(已显式确认该行使用备份配置)';
332
+ readonly 'adapter.patchLocalReadFailed': 'patch 行 {ref} 未写入:读不出本机现值({reason});无法确认这次写入不会覆盖本机原有内容,已跳过这一行';
327
333
  readonly 'adapter.credentialValueMissing': '凭据值未提供(需补录)';
328
334
  readonly 'adapter.promptWarningNoWrite': '提示项,无需写入';
329
335
  readonly 'adapter.promptMissing': '导入数据缺少提示词 {id}';
@@ -446,6 +452,7 @@ export declare const zh: {
446
452
  readonly 'sync.pruneListFailed': '远端快照裁剪失败:无法列出远端快照,{reason}';
447
453
  readonly 'sync.pruneDeleteFailed': '远端快照裁剪失败:删除快照 {id} 失败,{reason}';
448
454
  readonly 'sync.gcSkipped': '本轮已放弃回收远端孤立文件({code}):本轮不做回收,快照本身不受影响';
455
+ readonly 'sync.latestSkippedEncrypted': '加密快照不生成远端 latest/ 视图(密文无明文镜像):latest/ 保持上一次明文快照的内容,需要明文视图请推一次非加密快照';
449
456
  readonly 'market.invalidItemId': '非法市场条目 id: {id}(仅允许字母数字开头,字符限 . _ -)';
450
457
  readonly 'market.urlWhitespace': '市场仓库地址不能包含空白字符';
451
458
  readonly 'market.urlUnparseable': '无法解析市场仓库地址: {url}';
@@ -5,6 +5,7 @@ export const zh = {
5
5
  'export.sectionFailed': '分区 {adapter} 导出失败: {reason}',
6
6
  'export.credentialsReadFailed': '读取凭据文件失败,跳过秘密导出: {reason}',
7
7
  'export.vaultRefreshed': '凭据明文未进入备份,已镜像到本机 vault({count} 个文件,恢复时可回填)',
8
+ 'export.pluginDataSensitiveSkipped': '打包时剔除 {count} 个凭据文件(首个:{sample})——第三方插件数据分区永不携带凭据明文',
8
9
  'export.vaultRefreshSkipped': 'vault 镜像跳过 {rel}: {reason}',
9
10
  'export.vaultRefreshFailed': 'vault 镜像刷新失败(不影响导出): {reason}',
10
11
  'export.sessionsLimited': '会话按数量筛选:只带最新 {count} 个(共 {total} 个;单位 = 会话目录,同一会话的日志一起走)',
@@ -280,6 +281,8 @@ export const zh = {
280
281
  'adapter.patchLineCreate': '写入 patch 行 {lineId}',
281
282
  'adapter.patchLineSame': 'patch 行 {lineId} 已一致',
282
283
  'adapter.patchLineDiff': 'patch 行 {lineId} 与目标不同',
284
+ 'adapter.patchKeyParseFail': 'patch 行 {ref} 在 {path} 处含会让 DSH 整份文件解析失败的键名:先给该键改成合法名字,再导入',
285
+ 'adapter.patchKeyAmbiguous': 'patch 行 {ref} 在 {path} 处的键名 {key} 会被 DSH 读成数字 / 布尔 / null:给键名加引号(\'{key}\':)后重新导入',
283
286
  'adapter.promptSame': '提示词 {name} 已一致',
284
287
  'adapter.promptDiff': '提示词 {name} 与目标不同',
285
288
  'adapter.promptDiffWithLine': '提示词 {name} 与目标不同(目标位于行 {line})',
@@ -316,6 +319,9 @@ export const zh = {
316
319
  'adapter.pwPatchesUnsupported': 'patchedDependencies 为单行 flow 写法,无法安全剔除缺失条目;若目标机没有对应 patch 文件,pnpm 可能拒绝安装:{line}',
317
320
  'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml 已写入,但移除了 {count} 条 patchedDependencies 声明(目标机没有对应 patch 文件):{names}',
318
321
  'adapter.patchWritten': 'patch 行 {ref} 已写入,重启后生效',
322
+ 'adapter.patchSecretsKept': '{ref} 已写入,但保留本机原有内容:{paths}(备份里这些字段被脱敏清空,未用空值覆盖本机;如需清空请对该行显式确认“使用备份配置”)',
323
+ 'adapter.patchSecretsCleared': '{ref} 已按备份写入,字段 {paths} 现为空(已显式确认该行使用备份配置)',
324
+ 'adapter.patchLocalReadFailed': 'patch 行 {ref} 未写入:读不出本机现值({reason});无法确认这次写入不会覆盖本机原有内容,已跳过这一行',
319
325
  'adapter.credentialValueMissing': '凭据值未提供(需补录)',
320
326
  'adapter.promptWarningNoWrite': '提示项,无需写入',
321
327
  'adapter.promptMissing': '导入数据缺少提示词 {id}',
@@ -450,6 +456,7 @@ export const zh = {
450
456
  'sync.pruneListFailed': '远端快照裁剪失败:无法列出远端快照,{reason}',
451
457
  'sync.pruneDeleteFailed': '远端快照裁剪失败:删除快照 {id} 失败,{reason}',
452
458
  'sync.gcSkipped': '本轮已放弃回收远端孤立文件({code}):本轮不做回收,快照本身不受影响',
459
+ 'sync.latestSkippedEncrypted': '加密快照不生成远端 latest/ 视图(密文无明文镜像):latest/ 保持上一次明文快照的内容,需要明文视图请推一次非加密快照',
453
460
  // ---------- 配置市场(m-market:只读公开仓库目录读取 + 校验) ----------
454
461
  'market.invalidItemId': '非法市场条目 id: {id}(仅允许字母数字开头,字符限 . _ -)',
455
462
  'market.urlWhitespace': '市场仓库地址不能包含空白字符',
@@ -520,6 +527,7 @@ export const en = {
520
527
  'export.sectionFailed': 'Section {adapter} export failed: {reason}',
521
528
  'export.credentialsReadFailed': 'Failed to read the credentials file; secrets export skipped: {reason}',
522
529
  'export.vaultRefreshed': 'Credential plaintext did not enter the backup; mirrored to the local vault ({count} file(s), available for restore backfill)',
530
+ 'export.pluginDataSensitiveSkipped': 'Dropped {count} credential file(s) at packaging time (first: {sample}) — third-party plugin data never carries credential plaintext',
523
531
  'export.vaultRefreshSkipped': 'Vault mirror skipped {rel}: {reason}',
524
532
  'export.vaultRefreshFailed': 'Vault mirror refresh failed (export unaffected): {reason}',
525
533
  'export.sessionsLimited': 'Sessions filtered by count: only the latest {count} are included ({total} total; the unit is a session directory, so all logs of one session travel together)',
@@ -795,6 +803,8 @@ export const en = {
795
803
  'adapter.patchLineCreate': 'Write patch row {lineId}',
796
804
  'adapter.patchLineSame': 'Patch row {lineId} is already identical',
797
805
  'adapter.patchLineDiff': 'Patch row {lineId} differs from the target',
806
+ 'adapter.patchKeyParseFail': 'Patch row {ref} has a key at {path} that makes DSH fail to parse the whole file; rename that key before importing',
807
+ 'adapter.patchKeyAmbiguous': 'Key {key} in patch row {ref} (at {path}) is read as a number / boolean / null by DSH; quote it (\'{key}\':) and import again',
798
808
  'adapter.promptSame': 'Prompt {name} is already identical',
799
809
  'adapter.promptDiff': 'Prompt {name} differs from the target',
800
810
  'adapter.promptDiffWithLine': 'Prompt {name} differs from the target (target lives at row {line})',
@@ -831,6 +841,9 @@ export const en = {
831
841
  'adapter.pwPatchesUnsupported': 'patchedDependencies uses single-line flow syntax, so missing entries cannot be removed safely; if the target lacks the patch files pnpm may refuse installs: {line}',
832
842
  'adapter.pwWrittenPatchesDropped': 'pnpm-workspace.yaml written, but {count} patchedDependencies entries were removed (the target has no matching patch file): {names}',
833
843
  'adapter.patchWritten': 'Patch row {ref} written; takes effect after restart',
844
+ 'adapter.patchSecretsKept': '{ref} written, but local values were kept for: {paths} (these fields were redacted to empty in the backup, so the empty values did not overwrite local content; confirm “use backup config” on this row explicitly if you want them cleared)',
845
+ 'adapter.patchSecretsCleared': '{ref} written from the backup; fields {paths} are now empty (you explicitly confirmed using the backup config for this row)',
846
+ 'adapter.patchLocalReadFailed': 'Patch row {ref} not written: the local value could not be read ({reason}), so the write cannot be proven safe and this row was skipped',
834
847
  'adapter.credentialValueMissing': 'Credential value not provided (re-entry required)',
835
848
  'adapter.promptWarningNoWrite': 'Informational item; nothing to write',
836
849
  'adapter.promptMissing': 'Import data is missing prompt {id}',
@@ -961,6 +974,7 @@ export const en = {
961
974
  'sync.pruneListFailed': 'Remote snapshot pruning failed: could not list remote snapshots, {reason}',
962
975
  'sync.pruneDeleteFailed': 'Remote snapshot pruning failed: deleting snapshot {id} failed, {reason}',
963
976
  'sync.gcSkipped': 'Skipped reclaiming remote orphan files this round ({code}); snapshots are unaffected',
977
+ 'sync.latestSkippedEncrypted': 'Encrypted snapshots do not produce the remote latest/ view (ciphertext has no plaintext mirror): latest/ keeps the previous plaintext snapshot content; push a non-encrypted snapshot if you need it refreshed',
964
978
  // ---------- config marketplace (m-market: read-only public repo directory read + validation) ----------
965
979
  'market.invalidItemId': 'Invalid marketplace item id: {id} (must start with an alphanumeric; only . _ - allowed)',
966
980
  'market.urlWhitespace': 'Marketplace repository URL must not contain whitespace',
@@ -137,12 +137,19 @@ export function autosyncUnifiedHistoryInput(entry, msg = engineMsg) {
137
137
  }
138
138
  const defaultIo = {
139
139
  async mkdir(d, o) { await fs.mkdir(d, o); },
140
- async readdirNames(d) { try {
141
- return await fs.readdir(d);
142
- }
143
- catch {
144
- return [];
145
- } },
140
+ // 只有「目录不存在」才算空:权限/路径类型错误必须抛给调用方(审计 P3-6)。
141
+ // 旧实现 catch 一切 → 读不出的目录被当作空目录,历史面板显示「共 0 条」、
142
+ // 自动清理也算 0 条直接跳过,用户完全看不出是读取失败。
143
+ async readdirNames(d) {
144
+ try {
145
+ return await fs.readdir(d);
146
+ }
147
+ catch (err) {
148
+ if (err.code === 'ENOENT')
149
+ return [];
150
+ throw err;
151
+ }
152
+ },
146
153
  async readFileText(p) { return (await fs.readFile(p, 'utf8')).toString(); },
147
154
  async writeAll(t, c) { await atomicWriteFile(t, c, { mode: 0o600, symlink: 'reject' }); },
148
155
  async rm(p, o) { await fs.rm(p, o); },
@@ -360,7 +367,7 @@ export class MigrationStore {
360
367
  * 调用方据此区分「共 N 条,本页只含最近 M 条」。
361
368
  */
362
369
  async read(opts = {}) {
363
- const names = await this.io.readdirNames(this.dir).catch(() => []);
370
+ const names = await this.io.readdirNames(this.dir);
364
371
  const entries = [];
365
372
  const corrupted = [];
366
373
  const sorted = names.filter(isHistoryBasename).sort();
@@ -391,7 +398,7 @@ export class MigrationStore {
391
398
  }
392
399
  /** 目录内合法历史文件总数(只 readdir,不读文件内容;供「自动清理」行展示)。 */
393
400
  async count() {
394
- const names = await this.io.readdirNames(this.dir).catch(() => []);
401
+ const names = await this.io.readdirNames(this.dir);
395
402
  return names.filter(isHistoryBasename).length;
396
403
  }
397
404
  /**
@@ -399,7 +406,7 @@ export class MigrationStore {
399
406
  * 返回本次删除的文件名。
400
407
  */
401
408
  async retention(limit = DEFAULT_MIGRATION_RETENTION) {
402
- const names = (await this.io.readdirNames(this.dir).catch(() => [])).filter(isHistoryBasename).sort();
409
+ const names = (await this.io.readdirNames(this.dir)).filter(isHistoryBasename).sort();
403
410
  const removed = [];
404
411
  // 0(或负数)= 不限制:调用方显式关闭自动清理时按「保留全部」处理,绝不当作「删光」。
405
412
  if (!Number.isFinite(limit) || limit <= 0)
@@ -20,8 +20,8 @@ export interface ModelToolsDeps {
20
20
  syncDir: string;
21
21
  /**
22
22
  * SyncEngine 工厂(git/webdav 按配置分支构造传输;与 host 路由同一来源)。
23
- * D5:agent 侧按工具决定 optInSections(仅合并类工具带用户放行的可选分区),
24
- * 推送/拉取仍走缺省(= 只 portable),与改动前的工具行为逐字节一致。
23
+ * D5:agent 侧按工具决定 optInSections —— 推送 / 拉取 / 预览 / 合并一律带用户放行的 'auto' 档,
24
+ * 再剔除 sessions(与 docs/architecture/agent-tools.md 的工具面口径同一份事实)。
25
25
  */
26
26
  makeSyncEngine: (cfg: SyncConfig, opts?: {
27
27
  optInSections?: readonly SectionId[];
@@ -85,10 +85,17 @@ async function resolveSyncTarget(deps, channel) {
85
85
  }
86
86
  return { cfg, channel: ch };
87
87
  }
88
- /** 解析同步引擎(推送 / 拉取:缺省只同步 portable 分区,与改动前行为逐字节一致)。 */
88
+ /**
89
+ * 解析同步引擎(推送 / 拉取)。
90
+ * D5:与 preview/apply 同一口径 —— 引擎构造期必须拿到用户放行的 'auto' 档可选分区,
91
+ * 否则显式传 mcp 会在 pushTargets 里被判成非 portable 并 skipNonPortable(issue #138 ④)。
92
+ */
89
93
  async function resolveEngine(deps, channel) {
90
94
  const target = await resolveSyncTarget(deps, channel);
91
- return { engine: deps.makeSyncEngine(target.cfg), channel: target.channel };
95
+ return {
96
+ engine: deps.makeSyncEngine(target.cfg, { optInSections: agentOptInSections(deps, target.channel) }),
97
+ channel: target.channel,
98
+ };
92
99
  }
93
100
  /* ------------------------------------------------------------ 结构化结论与摘要 */
94
101
  /** agent 侧永久排除的同步分区(sessions = 会话内容:路径/cwd/对话,绝不因一次工具调用被上下行)。 */
@@ -446,6 +453,11 @@ export function createModelTools(deps) {
446
453
  // 否则模型会把它当成「推送成功但内容为空」继续往下走。
447
454
  ...(report.conflict === true ? { conflict: true } : {}),
448
455
  ...(report.adoptedBase === undefined ? {} : { adoptedBase: report.adoptedBase }),
456
+ // issue #140:内容与远端最新一致 ⇒ 引擎什么都没写(不 upload、不建目录)。
457
+ // 不透传的话模型会把「ok:true + snapshotId」读成「又推了一份新快照」。
458
+ ...(report.skipped === 'unchanged'
459
+ ? { skipped: 'unchanged', adoptedSnapshotId: report.adoptedSnapshotId ?? report.snapshotId }
460
+ : {}),
449
461
  ...(report.message === undefined ? {} : { message: report.message }),
450
462
  ...(encrypt ? { passwordSource: stored === undefined ? 'argument' : 'stored' } : {}),
451
463
  };
@@ -0,0 +1,49 @@
1
+ /**
2
+ * patch 行写回守卫(issue #136 A + C)。
3
+ *
4
+ * 背景:导出侧 SecretScanner 会把命中字段名/值形状的字符串叶子替换成空串(占位符),语义是
5
+ * 「需补录」。同步/导入落盘时,若照抄这个空串,就会**静默**抹掉本机同一行里用户手写的明文
6
+ * —— 行是整行写回的,行内没有粒度。
7
+ *
8
+ * 本模块是那条「最后一个能拒绝写入」的纯逻辑:比对导入值与本机当前行,把「被脱敏剥空」的
9
+ * 叶子换回本机值;只有调用方显式声明逐行确认(`confirmed`)才允许真的写空。
10
+ *
11
+ * 两条分支(issue #136 C 的载荷字段决定):
12
+ * - `redactedPaths` 存在(新载荷):只保护**声明过的**路径,精确、可解释;
13
+ * - 缺省(旧载荷 / 未知):保守口径 —— 导入值为空串且本机同叶子非空即保留本机值。
14
+ * 绝不反过来假定「空值一定来自用户主动清空」(旧载荷没有能力区分剥空与真空)。
15
+ *
16
+ * 纯函数:不读盘、不打日志、不抛错;返回值不含任何值本身(只有路径),可直接进报告。
17
+ */
18
+ /** 路径段(对象键或数组下标)。 */
19
+ type Segment = string | number;
20
+ export interface PatchSecretGuardInput {
21
+ /** 备份/远端载荷里的整行值(可能含被剥空的叶子)。 */
22
+ importedRaw: unknown;
23
+ /** 本机当前同一行的值;`undefined` = 本机没有这一行(Create 语义,无可保护对象)。 */
24
+ localRaw: unknown;
25
+ /** 载荷声明的剥空路径(行内相对,如 `raw.mcp.args.token`);缺省 = 未知(旧载荷)。 */
26
+ redactedPaths?: readonly string[] | undefined;
27
+ /** 调用方已拿到对该行的**逐行显式确认** → 允许写空。 */
28
+ confirmed: boolean;
29
+ }
30
+ export interface PatchSecretGuardResult {
31
+ /** 实际应写入的行值(受保护叶子已换回本机值)。 */
32
+ raw: unknown;
33
+ /** 被保留的本机值路径(行内相对,展示用)。 */
34
+ kept: string[];
35
+ /** 逐行确认后真的写空的路径(同一份事实进报告)。 */
36
+ cleared: string[];
37
+ /** true = 载荷没带剥空路径,走的是保守推断分支。 */
38
+ conservative: boolean;
39
+ }
40
+ /** 解析扫描器路径语法(`a.b[0].c`)→ 路径段;语法不认识返回 null(宁可放过,不误判)。 */
41
+ declare function parsePath(path: string): Segment[] | null;
42
+ /** 路径段 → 展示用相对路径(与扫描器语法同形,如 `raw.mcp.args.token`)。 */
43
+ declare function formatPath(segs: readonly Segment[]): string;
44
+ export declare function applyPatchSecretGuard(input: PatchSecretGuardInput): PatchSecretGuardResult;
45
+ export declare const __test: {
46
+ parsePath: typeof parsePath;
47
+ formatPath: typeof formatPath;
48
+ };
49
+ export {};
@@ -0,0 +1,164 @@
1
+ /**
2
+ * patch 行写回守卫(issue #136 A + C)。
3
+ *
4
+ * 背景:导出侧 SecretScanner 会把命中字段名/值形状的字符串叶子替换成空串(占位符),语义是
5
+ * 「需补录」。同步/导入落盘时,若照抄这个空串,就会**静默**抹掉本机同一行里用户手写的明文
6
+ * —— 行是整行写回的,行内没有粒度。
7
+ *
8
+ * 本模块是那条「最后一个能拒绝写入」的纯逻辑:比对导入值与本机当前行,把「被脱敏剥空」的
9
+ * 叶子换回本机值;只有调用方显式声明逐行确认(`confirmed`)才允许真的写空。
10
+ *
11
+ * 两条分支(issue #136 C 的载荷字段决定):
12
+ * - `redactedPaths` 存在(新载荷):只保护**声明过的**路径,精确、可解释;
13
+ * - 缺省(旧载荷 / 未知):保守口径 —— 导入值为空串且本机同叶子非空即保留本机值。
14
+ * 绝不反过来假定「空值一定来自用户主动清空」(旧载荷没有能力区分剥空与真空)。
15
+ *
16
+ * 纯函数:不读盘、不打日志、不抛错;返回值不含任何值本身(只有路径),可直接进报告。
17
+ */
18
+ /** 解析扫描器路径语法(`a.b[0].c`)→ 路径段;语法不认识返回 null(宁可放过,不误判)。 */
19
+ function parsePath(path) {
20
+ const segs = [];
21
+ let rest = path;
22
+ while (rest !== '') {
23
+ const m = /^([^.[\]]+)((?:\[\d+\])*)/.exec(rest);
24
+ if (m === null)
25
+ return null;
26
+ const head = m[1];
27
+ const tail = m[2] ?? '';
28
+ if (head === undefined)
29
+ return null;
30
+ segs.push(head);
31
+ for (const hit of tail.matchAll(/\[(\d+)\]/g)) {
32
+ const idx = hit[1];
33
+ if (idx !== undefined)
34
+ segs.push(Number(idx));
35
+ }
36
+ rest = rest.slice(m[0].length);
37
+ if (rest === '')
38
+ break;
39
+ if (!rest.startsWith('.'))
40
+ return null;
41
+ rest = rest.slice(1);
42
+ }
43
+ return segs.length > 0 ? segs : null;
44
+ }
45
+ /** 路径段 → 展示用相对路径(与扫描器语法同形,如 `raw.mcp.args.token`)。 */
46
+ function formatPath(segs) {
47
+ let out = '';
48
+ for (const seg of segs) {
49
+ if (typeof seg === 'number')
50
+ out += `[${seg}]`;
51
+ else
52
+ out += out === '' ? seg : `.${seg}`;
53
+ }
54
+ return out;
55
+ }
56
+ function getAt(root, segs) {
57
+ let cur = root;
58
+ for (const seg of segs) {
59
+ if (typeof seg === 'number') {
60
+ if (!Array.isArray(cur))
61
+ return undefined;
62
+ cur = cur[seg];
63
+ }
64
+ else {
65
+ if (cur === null || typeof cur !== 'object' || Array.isArray(cur))
66
+ return undefined;
67
+ cur = cur[seg];
68
+ }
69
+ }
70
+ return cur;
71
+ }
72
+ /** 深拷贝后按路径写回(只在确有保护项时调用,避免无谓的整行拷贝)。 */
73
+ function setAt(root, segs, value) {
74
+ if (segs.length === 0)
75
+ return value;
76
+ const clone = structuredClone(root);
77
+ let cur = clone;
78
+ for (let i = 0; i < segs.length - 1; i++) {
79
+ const next = Array.isArray(cur)
80
+ ? cur[segs[i]]
81
+ : cur[segs[i]];
82
+ if (next === null || typeof next !== 'object')
83
+ return clone; // 形状不符 → 不猜,原样返回
84
+ cur = next;
85
+ }
86
+ const last = segs[segs.length - 1];
87
+ if (Array.isArray(cur))
88
+ cur[last] = value;
89
+ else
90
+ cur[last] = value;
91
+ return clone;
92
+ }
93
+ /** 本机值是否「非空」:只有非空字符串算(脱敏占位符恒为空串,故此判据与载荷同口径)。 */
94
+ function isNonEmptyLocal(value) {
95
+ return typeof value === 'string' && value !== '';
96
+ }
97
+ /** 保守分支:逐叶子找出「导入空串 + 本机非空」的路径(旧载荷没有剥空信息时的唯一线索)。 */
98
+ function collectSuspects(imported, local, segs, out) {
99
+ if (imported === null || typeof imported !== 'object') {
100
+ if (imported === '' && isNonEmptyLocal(local))
101
+ out.push([...segs]);
102
+ return;
103
+ }
104
+ if (Array.isArray(imported)) {
105
+ for (let i = 0; i < imported.length; i++) {
106
+ collectSuspects(imported[i], Array.isArray(local) ? local[i] : undefined, [...segs, i], out);
107
+ }
108
+ return;
109
+ }
110
+ const obj = imported;
111
+ const localObj = local !== null && typeof local === 'object' && !Array.isArray(local)
112
+ ? local
113
+ : undefined;
114
+ for (const [k, v] of Object.entries(obj))
115
+ collectSuspects(v, localObj?.[k], [...segs, k], out);
116
+ }
117
+ export function applyPatchSecretGuard(input) {
118
+ const { importedRaw, localRaw, redactedPaths, confirmed } = input;
119
+ // 本机没有这一行 → 没有可覆盖的东西(Create 语义),原样返回。
120
+ if (localRaw === undefined)
121
+ return { raw: importedRaw, kept: [], cleared: [], conservative: false };
122
+ const conservative = redactedPaths === undefined || redactedPaths.length === 0;
123
+ /** 候选:相对路径段(不含 `raw` 前缀;空数组 = 整行值本身)。 */
124
+ const candidates = [];
125
+ if (conservative) {
126
+ const found = [];
127
+ collectSuspects(importedRaw, localRaw, [], found);
128
+ for (const segs of found)
129
+ candidates.push({ segs, declared: false });
130
+ }
131
+ else {
132
+ for (const path of redactedPaths) {
133
+ const segs = parsePath(path);
134
+ if (segs === null)
135
+ continue;
136
+ // 载荷里的路径是相对**行对象**(`{ file, lineId, raw }`)的;行内相对只剩 `raw` 之后的部分。
137
+ const rel = segs[0] === 'raw' ? segs.slice(1) : segs;
138
+ candidates.push({ segs: rel, declared: true });
139
+ }
140
+ }
141
+ const kept = [];
142
+ const cleared = [];
143
+ let raw = importedRaw;
144
+ for (const cand of candidates) {
145
+ const localVal = getAt(localRaw, cand.segs);
146
+ if (!isNonEmptyLocal(localVal))
147
+ continue;
148
+ const importedVal = getAt(importedRaw, cand.segs);
149
+ // 声明路径上出现了非空导入值 = 载荷自相矛盾(或值形状命中后被上游改回):以导入值为准,
150
+ // 绝不因为声明了路径就把远端真实新值挡掉(issue #136 验收 3)。
151
+ if (importedVal === '' || importedVal === undefined) {
152
+ const rel = formatPath(['raw', ...cand.segs]);
153
+ if (confirmed)
154
+ cleared.push(rel);
155
+ else {
156
+ kept.push(rel);
157
+ raw = setAt(raw, cand.segs, localVal);
158
+ }
159
+ }
160
+ }
161
+ return { raw, kept, cleared, conservative };
162
+ }
163
+ export const __test = { parsePath, formatPath };
164
+ //# sourceMappingURL=patch-secret-guard.js.map
@@ -48,6 +48,12 @@ export interface ReconcileOutcome {
48
48
  safeModeRequired: boolean;
49
49
  /** unresolved(未到 terminal)的 incomplete op id(RECOVERY_REQUIRED 候选)。 */
50
50
  unresolved: string[];
51
+ /**
52
+ * 「owner 仍活着(live)但 journal 本身还没到 terminal」的 op id(审计 P3-8)。
53
+ * 与 unresolved 的区别:它们不该进 recovery(执行方还在跑),但也**不是已收敛**。
54
+ * 锁被另一实例持有时启动分类据此产出 LOCKED_LIVE,而不是把「确实在跑」误报成 NORMAL。
55
+ */
56
+ liveIncomplete: string[];
51
57
  }
52
58
  /** 可自证「不可能掩盖半成品配置改动」的残留类型(issue #87)。 */
53
59
  export type SelfProvableResidualClass = 'artifact-only' | 'no-steps';
@@ -99,6 +105,8 @@ export interface StartupInspection {
99
105
  recoveryRequired: boolean;
100
106
  decisions: ReconcileDecision[];
101
107
  unresolved: string[];
108
+ /** live owner 持有但 journal 未到 terminal 的 op id(P3-8:LOCKED_LIVE 的判据) */
109
+ liveIncomplete: string[];
102
110
  /**
103
111
  * durable SAFE MODE 标记的三态判定(t37):'blocked' / 'clear' / **'unknown'**。
104
112
  * 单独暴露的原因:`safeModeRequired` 是聚合结论(还可能因 corrupt journal / needs-attention 为 true),
@@ -74,6 +74,7 @@ function selfProvableResidual(j) {
74
74
  export async function reconcileActive(store, hooks, env, opts = {}) {
75
75
  const decisions = [];
76
76
  const unresolved = [];
77
+ const liveIncomplete = [];
77
78
  let safeModeRequired = false;
78
79
  const activeIds = await store.scanActive();
79
80
  for (const operationId of activeIds) {
@@ -83,8 +84,10 @@ export async function reconcileActive(store, hooks, env, opts = {}) {
83
84
  safeModeRequired = true;
84
85
  if (outcome.unresolved)
85
86
  unresolved.push(operationId);
87
+ if (outcome.liveIncomplete === true)
88
+ liveIncomplete.push(operationId);
86
89
  }
87
- return { decisions, safeModeRequired, unresolved };
90
+ return { decisions, safeModeRequired, unresolved, liveIncomplete };
88
91
  }
89
92
  async function reconcileOne(store, hooks, env, opts, operationId) {
90
93
  const j = await store.loadActive(operationId);
@@ -102,7 +105,14 @@ async function reconcileOne(store, hooks, env, opts, operationId) {
102
105
  }
103
106
  // live owner 检查
104
107
  if (await env.isLiveOwner(j)) {
105
- return { decision: { operationId, kind: 'live', reason: engineMsg('core.reconcile.ownerLive'), snapshotId: j.snapshotId }, safeMode: false, unresolved: false };
108
+ // P3-8:live 只说明「有人还在跑」,不等于这条 journal 已收敛。未到 terminal 的 live journal
109
+ // 必须如实上报(liveIncomplete),否则 LOCKED 下的启动分类会把「确实在跑」误判成 NORMAL。
110
+ return {
111
+ decision: { operationId, kind: 'live', reason: engineMsg('core.reconcile.ownerLive'), snapshotId: j.snapshotId },
112
+ safeMode: false,
113
+ unresolved: false,
114
+ liveIncomplete: !isTerminalState(j.state),
115
+ };
106
116
  }
107
117
  // P1-A:ownership binding 强制校验(显式 recovery 捕获的 crashed ownership 证据)。
108
118
  // journal.ownerInstanceId/lockId 必须匹配期望的 crashed ownership instanceId,否则不作 trusted 恢复。
@@ -461,7 +471,12 @@ export async function inspectStartup(store, hooks, env, opts, lockState) {
461
471
  const durableSafe = durableSafeState !== 'clear';
462
472
  const safeModeRequired = outcome.safeModeRequired || recoveryRequired || durableSafe;
463
473
  return {
464
- safeModeRequired, recoveryRequired, decisions: outcome.decisions, unresolved: outcome.unresolved, durableSafeState,
474
+ safeModeRequired,
475
+ recoveryRequired,
476
+ decisions: outcome.decisions,
477
+ unresolved: outcome.unresolved,
478
+ liveIncomplete: outcome.liveIncomplete,
479
+ durableSafeState,
465
480
  };
466
481
  }
467
482
  //# sourceMappingURL=reconcile.js.map
@@ -77,6 +77,8 @@ export interface ReinstallStep {
77
77
  command: string;
78
78
  /** 是否属于危险(触及 ~/.dsh 数据)动作 */
79
79
  dangerous: boolean;
80
+ /** 失败即中止后续所有步骤(仅备份步:它失败时后面的清空无兜底,必须停) */
81
+ critical?: boolean;
80
82
  }
81
83
  export interface ReinstallPlan {
82
84
  /** 目标 DSH 版本('latest' 表示最新版) */