dsh-config-manager 0.4.3 → 0.6.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 (286) hide show
  1. package/README.md +10 -0
  2. package/README.zh-CN.md +10 -0
  3. package/lib/adapters/mcp.d.ts +9 -0
  4. package/lib/adapters/mcp.js +37 -0
  5. package/lib/adapters/plugins.js +10 -2
  6. package/lib/adapters/pnpm-workspace.js +1 -1
  7. package/lib/adapters/self.d.ts +2 -0
  8. package/lib/adapters/self.js +18 -2
  9. package/lib/adapters/workspaces.js +1 -1
  10. package/lib/cli/restore-resume.js +1 -1
  11. package/lib/cli/web/page.js +2 -2
  12. package/lib/client.d.ts +17 -41
  13. package/lib/client.js +946 -761
  14. package/lib/core/backup.d.ts +11 -0
  15. package/lib/core/backup.js +27 -0
  16. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  17. package/lib/core/env-lock-lifecycle.js +38 -0
  18. package/lib/core/external-failure.d.ts +9 -0
  19. package/lib/core/external-failure.js +50 -0
  20. package/lib/core/local-plugin-host.d.ts +9 -7
  21. package/lib/core/local-plugin-host.js +109 -15
  22. package/lib/core/local-plugin-pack.d.ts +20 -0
  23. package/lib/core/local-plugin-pack.js +18 -3
  24. package/lib/core/mcp-connector-store.d.ts +13 -0
  25. package/lib/core/mcp-connector-store.js +16 -1
  26. package/lib/core/messages-core.d.ts +45 -0
  27. package/lib/core/messages-core.js +92 -0
  28. package/lib/core/messages.d.ts +5 -0
  29. package/lib/core/messages.js +14 -0
  30. package/lib/core/migration-history.d.ts +40 -0
  31. package/lib/core/migration-history.js +55 -0
  32. package/lib/core/model-tool-plans.d.ts +66 -0
  33. package/lib/core/model-tool-plans.js +128 -0
  34. package/lib/core/model-tools.d.ts +96 -8
  35. package/lib/core/model-tools.js +568 -31
  36. package/lib/core/phase3-host.js +10 -2
  37. package/lib/core/plugin-cli.d.ts +5 -0
  38. package/lib/core/plugin-cli.js +11 -3
  39. package/lib/core/plugin-data-registry.d.ts +1 -1
  40. package/lib/core/plugin-data-registry.js +1 -1
  41. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  42. package/lib/core/restore-plan-fingerprint.js +18 -0
  43. package/lib/core/restore-resume.d.ts +1 -1
  44. package/lib/core/restore-resume.js +1 -1
  45. package/lib/core/restore.d.ts +5 -0
  46. package/lib/core/restore.js +4 -1
  47. package/lib/core/types.d.ts +12 -0
  48. package/lib/foreign/claude-sessions.d.ts +1 -1
  49. package/lib/foreign/claude-sessions.js +1 -1
  50. package/lib/foreign/registry.js +1 -1
  51. package/lib/foreign/types.d.ts +1 -1
  52. package/lib/index.d.ts +19 -15
  53. package/lib/index.js +72 -80
  54. package/lib/market/git-file-writer.js +1 -1
  55. package/lib/market/github-repos.js +1 -1
  56. package/lib/market/market-config.js +1 -1
  57. package/lib/market/messages-market.js +1 -1
  58. package/lib/market/my-repo.js +1 -1
  59. package/lib/market/prepare.js +1 -1
  60. package/lib/market/reader.js +2 -2
  61. package/lib/market/repo-url.d.ts +1 -1
  62. package/lib/market/security.js +2 -2
  63. package/lib/market/star-cache.d.ts +1 -1
  64. package/lib/market/types.d.ts +1 -1
  65. package/lib/market/types.js +1 -1
  66. package/lib/market/url.js +1 -1
  67. package/lib/profiles/dsh-profile-manager.d.ts +1 -1
  68. package/lib/profiles/dsh-profile-manager.js +26 -7
  69. package/lib/profiles/dsh-profile-shared.d.ts +3 -1
  70. package/lib/routes/backup.js +17 -9
  71. package/lib/routes/index.d.ts +1 -1
  72. package/lib/routes/kit.d.ts +2 -2
  73. package/lib/routes/market.d.ts +1 -1
  74. package/lib/routes/market.js +3 -60
  75. package/lib/routes/model-tools-deps.d.ts +41 -0
  76. package/lib/routes/model-tools-deps.js +18 -0
  77. package/lib/routes/recovery.js +5 -3
  78. package/lib/routes/route-support.d.ts +18 -26
  79. package/lib/routes/route-support.js +19 -32
  80. package/lib/routes/snapshots.d.ts +1 -1
  81. package/lib/routes/snapshots.js +4 -40
  82. package/lib/routes/sync.js +40 -28
  83. package/lib/schema/index.d.ts +2 -2
  84. package/lib/schema/index.js +2 -2
  85. package/lib/schema/section-registry.d.ts +5 -3
  86. package/lib/schema/section-registry.js +7 -3
  87. package/lib/security/secret-scanner.js +1 -1
  88. package/lib/sync/apply-bundle.d.ts +50 -0
  89. package/lib/sync/apply-bundle.js +60 -0
  90. package/lib/sync/autosync-scheduler.d.ts +9 -0
  91. package/lib/sync/autosync-scheduler.js +118 -89
  92. package/lib/sync/backup-scheduler.js +5 -4
  93. package/lib/sync/blob-store.d.ts +2 -2
  94. package/lib/sync/git/git-transport.d.ts +12 -0
  95. package/lib/sync/git/git-transport.js +50 -2
  96. package/lib/sync/merge.d.ts +2 -0
  97. package/lib/sync/merge.js +28 -0
  98. package/lib/sync/messages.d.ts +4 -0
  99. package/lib/sync/messages.js +9 -2
  100. package/lib/sync/s3/s3-transport.d.ts +1 -1
  101. package/lib/sync/s3/s3-transport.js +1 -1
  102. package/lib/sync/sync-engine.d.ts +4 -4
  103. package/lib/sync/sync-engine.js +25 -26
  104. package/lib/sync/sync-scope-boot.d.ts +34 -0
  105. package/lib/sync/sync-scope-boot.js +71 -0
  106. package/lib/sync/sync-scope.d.ts +103 -0
  107. package/lib/sync/sync-scope.js +229 -0
  108. package/lib/sync/sync-selection.d.ts +17 -4
  109. package/lib/sync/sync-selection.js +40 -14
  110. package/lib/sync/transport.d.ts +4 -1
  111. package/lib/sync/transport.js +6 -0
  112. package/lib/sync/webdav/webdav-transport.js +1 -1
  113. package/lib/sync/workspace-merge.d.ts +36 -0
  114. package/lib/sync/workspace-merge.js +152 -0
  115. package/lib/ui/backup-schedule.d.ts +13 -2
  116. package/lib/ui/backup-schedule.js +3 -0
  117. package/lib/ui/snapshots-view.d.ts +16 -0
  118. package/lib/ui/snapshots-view.js +21 -0
  119. package/lib/ui/sync-repository-picker.d.ts +21 -0
  120. package/lib/ui/sync-repository-picker.js +18 -0
  121. package/lib/utils/env-lock.d.ts +96 -0
  122. package/lib/utils/env-lock.js +332 -111
  123. package/lib/utils/messages-utils.d.ts +6 -0
  124. package/lib/utils/messages-utils.js +17 -1
  125. package/lib/utils/patch-yaml.js +1 -1
  126. package/lib/utils/remove-tree.d.ts +7 -0
  127. package/lib/utils/remove-tree.js +265 -0
  128. package/lib/utils/zip.js +1 -1
  129. package/package.json +3 -2
  130. package/src/adapters/mcp.test.ts +28 -0
  131. package/src/adapters/mcp.ts +33 -0
  132. package/src/adapters/plugins.test.ts +49 -0
  133. package/src/adapters/plugins.ts +9 -1
  134. package/src/adapters/pnpm-workspace.ts +1 -1
  135. package/src/adapters/self.test.ts +39 -1
  136. package/src/adapters/self.ts +20 -2
  137. package/src/adapters/workspaces.ts +1 -1
  138. package/src/cli/restore-resume.ts +1 -1
  139. package/src/cli/web/page.ts +2 -2
  140. package/src/client/about/AboutPanel.tsx +1 -1
  141. package/src/client/about/about-view.test.ts +1 -1
  142. package/src/client/about/about-view.ts +1 -1
  143. package/src/client/api.ts +1 -6
  144. package/src/client/chat/chat-entry-view.test.ts +1 -1
  145. package/src/client/chat/chat-slots.ts +1 -1
  146. package/src/client/chat/rollback-diff-tab.ts +1 -1
  147. package/src/client/client-types.ts +1 -1
  148. package/src/client/common/routes.ts +1 -5
  149. package/src/client/config-manager.module.css +21 -1
  150. package/src/client/css-scale-guard.test.ts +1 -1
  151. package/src/client/environment/EnvironmentPanel.tsx +2 -2
  152. package/src/client/home/HomePanel.tsx +3 -0
  153. package/src/client/library/ArtifactRow.tsx +14 -2
  154. package/src/client/library/LibraryPanel.tsx +44 -0
  155. package/src/client/locales/overview.ts +10 -2
  156. package/src/client/locales/profiles.ts +2 -0
  157. package/src/client/locales/sessions.ts +3 -0
  158. package/src/client/market/MyConfigsView.tsx +1 -1
  159. package/src/client/market/market-api.ts +2 -14
  160. package/src/client/market/market-locales.ts +1 -1
  161. package/src/client/market/market-view.ts +3 -3
  162. package/src/client/market/my-configs-api.ts +1 -1
  163. package/src/client/market/my-configs-view.ts +1 -1
  164. package/src/client/recovery/recovery-locales.test.ts +1 -1
  165. package/src/client/run-store.ts +1 -1
  166. package/src/client/sync/ChannelConfigDialog.tsx +32 -1
  167. package/src/client/sync/SyncPanel.tsx +11 -30
  168. package/src/client/sync/SyncRepositoryPicker.tsx +34 -13
  169. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  170. package/src/client/sync/SyncSettingsView.test.ts +32 -0
  171. package/src/client/sync/config-save-state.test.ts +99 -0
  172. package/src/client/sync/config-save-state.ts +69 -0
  173. package/src/client/sync/history-model.test.ts +28 -7
  174. package/src/client/sync/history-model.ts +6 -3
  175. package/src/client/sync/sync-locales.ts +14 -4
  176. package/src/client/sync/sync-view.ts +1 -1
  177. package/src/core/analyzer-cache.test.ts +1 -1
  178. package/src/core/backup.test.ts +45 -1
  179. package/src/core/backup.ts +25 -0
  180. package/src/core/disk-usage.test.ts +2 -0
  181. package/src/core/engine-locale.test.ts +4 -0
  182. package/src/core/env-lock-lifecycle.ts +33 -3
  183. package/src/core/external-failure.test.ts +60 -0
  184. package/src/core/external-failure.ts +54 -0
  185. package/src/core/integrity-extra-entries.test.ts +1 -1
  186. package/src/core/local-plugin-host.test.ts +134 -0
  187. package/src/core/local-plugin-host.ts +122 -17
  188. package/src/core/local-plugin-pack.ts +39 -3
  189. package/src/core/mcp-connector-store.ts +26 -1
  190. package/src/core/messages-core.ts +94 -0
  191. package/src/core/messages.ts +14 -0
  192. package/src/core/migration-history.test.ts +65 -0
  193. package/src/core/migration-history.ts +70 -0
  194. package/src/core/model-tool-plans.test.ts +111 -0
  195. package/src/core/model-tool-plans.ts +170 -0
  196. package/src/core/model-tools.test.ts +212 -12
  197. package/src/core/model-tools.ts +710 -38
  198. package/src/core/phase3-host.ts +10 -2
  199. package/src/core/phase3-production-integration.test.ts +43 -0
  200. package/src/core/plugin-cli.fs.test.ts +30 -3
  201. package/src/core/plugin-cli.ts +11 -3
  202. package/src/core/plugin-data-registry.ts +1 -1
  203. package/src/core/restore-plan-fingerprint.ts +19 -0
  204. package/src/core/restore-resume.ts +1 -1
  205. package/src/core/restore.ts +9 -1
  206. package/src/core/types.ts +12 -0
  207. package/src/foreign/claude-sessions.ts +3 -3
  208. package/src/foreign/registry.ts +1 -1
  209. package/src/foreign/types.ts +1 -1
  210. package/src/index.ts +102 -111
  211. package/src/market/git-file-writer.ts +1 -1
  212. package/src/market/github-repos.test.ts +1 -1
  213. package/src/market/github-repos.ts +1 -1
  214. package/src/market/market-config.ts +1 -1
  215. package/src/market/messages-market.ts +1 -1
  216. package/src/market/my-repo.test.ts +1 -1
  217. package/src/market/my-repo.ts +1 -1
  218. package/src/market/prepare.test.ts +1 -1
  219. package/src/market/prepare.ts +1 -1
  220. package/src/market/reader.ts +2 -2
  221. package/src/market/repo-url.ts +1 -1
  222. package/src/market/security.ts +2 -2
  223. package/src/market/star-cache.ts +1 -1
  224. package/src/market/types.ts +1 -1
  225. package/src/market/url.test.ts +1 -1
  226. package/src/market/url.ts +1 -1
  227. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  228. package/src/profiles/dsh-profile-manager.test.ts +20 -0
  229. package/src/profiles/dsh-profile-manager.ts +25 -7
  230. package/src/profiles/dsh-profile-shared.ts +2 -0
  231. package/src/routes/backup.ts +16 -9
  232. package/src/routes/index.ts +1 -1
  233. package/src/routes/kit.ts +2 -2
  234. package/src/routes/market.ts +2 -59
  235. package/src/routes/model-tools-deps.ts +56 -0
  236. package/src/routes/recovery.ts +5 -3
  237. package/src/routes/route-support.ts +49 -36
  238. package/src/routes/snapshots.ts +4 -40
  239. package/src/routes/sync.ts +39 -27
  240. package/src/schema/index.ts +2 -2
  241. package/src/schema/manifest-schema.test.ts +2 -2
  242. package/src/schema/registry.test.ts +1 -1
  243. package/src/schema/section-registry.ts +9 -4
  244. package/src/security/redaction.test.ts +1 -1
  245. package/src/security/secret-scanner.test.ts +2 -2
  246. package/src/security/secret-scanner.ts +1 -1
  247. package/src/sync/apply-bundle.ts +104 -0
  248. package/src/sync/autosync-scheduler.test.ts +180 -6
  249. package/src/sync/autosync-scheduler.ts +132 -92
  250. package/src/sync/backup-scheduler.test.ts +11 -4
  251. package/src/sync/backup-scheduler.ts +5 -4
  252. package/src/sync/blob-store.ts +2 -2
  253. package/src/sync/git/git-transport.test.ts +62 -0
  254. package/src/sync/git/git-transport.ts +54 -3
  255. package/src/sync/merge.ts +29 -0
  256. package/src/sync/messages.ts +9 -2
  257. package/src/sync/s3/s3-transport.ts +1 -1
  258. package/src/sync/sync-engine.test.ts +238 -2
  259. package/src/sync/sync-engine.ts +25 -26
  260. package/src/sync/sync-preview-push.test.ts +2 -1
  261. package/src/sync/sync-scope-boot.ts +87 -0
  262. package/src/sync/sync-scope.test.ts +154 -0
  263. package/src/sync/sync-scope.ts +256 -0
  264. package/src/sync/sync-selection.test.ts +76 -2
  265. package/src/sync/sync-selection.ts +40 -13
  266. package/src/sync/transport.test.ts +21 -1
  267. package/src/sync/transport.ts +12 -0
  268. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  269. package/src/sync/webdav/webdav-transport.ts +1 -1
  270. package/src/sync/workspace-merge.test.ts +110 -0
  271. package/src/sync/workspace-merge.ts +180 -0
  272. package/src/ui/backup-schedule.test.ts +5 -0
  273. package/src/ui/backup-schedule.ts +21 -2
  274. package/src/ui/session-issue-labels.ts +1 -1
  275. package/src/ui/snapshots-view.test.ts +32 -0
  276. package/src/ui/snapshots-view.ts +34 -0
  277. package/src/ui/sync-repository-picker.test.ts +34 -1
  278. package/src/ui/sync-repository-picker.ts +24 -0
  279. package/src/utils/env-lock.test.ts +242 -9
  280. package/src/utils/env-lock.ts +247 -13
  281. package/src/utils/messages-utils.ts +17 -1
  282. package/src/utils/patch-yaml.ts +1 -1
  283. package/src/utils/remove-tree.test.ts +120 -0
  284. package/src/utils/remove-tree.ts +239 -0
  285. package/src/utils/zip.ts +1 -1
  286. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -8,7 +8,9 @@
8
8
  * 关键不变量(NON-NEGOTIABLE,违反即破坏正确性):
9
9
  * - 所有权获取 **必须** `open(lockPath, 'wx')` 独占创建语义;**禁止** exists→write、rm→recreate、
10
10
  * 用 Phase 1 `atomicWriteFile(environment.lock)` 获取所有权。
11
- * - `environment.lock` 是 **immutable ownership record**:创建后直到 release 不被 rename/replace。
11
+ * - `environment.lock` 是 **immutable ownership record**:创建后直到 release 不被 rename/replace
12
+ * (唯一例外:release 的 unlink 失败 / acquire 发现自己的残留时,按 instanceId 校验后
13
+ * rename 到 `environment.recovering.*` ——「quarantine 自己」,见 quarantineOwnership)。
12
14
  * - heartbeat 走 **独立 sidecar** `environment.heartbeat.<instanceId>`,可安全用 Phase 1 `atomicWriteFile` 更新。
13
15
  * - **operation-scoped** `MutationLockToken`:禁止 process-level reentrant(instanceId/handle/reenterCount 判嵌套)。
14
16
  * - stale 检测只分类(LOCKED / STALE_LOCK_DETECTED / UNKNOWN_STATE);**acquire 侧绝不自动 unlink/takeover**。
@@ -61,6 +63,9 @@ export const DEFAULT_LONG_EXPIRED_AFTER_MS = 30 * 60_000
61
63
  /** acquire 中「EEXIST 但 ownership 读不到」的竞态重试上限(issue #79):文件在两次读取之间
62
64
  * 被释放时重试 open('wx') 即可拿到锁,不在锁间隙里空等 acquireTimeoutMs。 */
63
65
  const MAX_FREE_RETRIES = 5
66
+ /** 长持有告警阈值(缺省 2 分钟):正常 mutation(导出/合并/推送)远短于此,超过即视为可疑,
67
+ * 但**只告警不解锁** —— 活持有者可能真的在跑长任务,强拆会造出双持有(比卡死更难查)。 */
68
+ export const DEFAULT_HOLD_WARN_AFTER_MS = 120_000
64
69
 
65
70
  // ---------- 类型 ----------
66
71
 
@@ -159,6 +164,10 @@ export interface AcquireResult {
159
164
  token: MutationLockToken | null
160
165
  /** 诊断信息(非敏感):占用方 op/hostname、或错误描述 */
161
166
  detail?: string
167
+ /** STALE_LOCK_DETECTED 的细分(只用于给用户的分类文案):
168
+ * owner-gone = 结构可证(进程已死 / PID 复用 / 无 identity 能力但心跳长过期);
169
+ * heartbeat-stopped = 进程仍活、identity 相同,但心跳长期停止(典型:release 失败留痕)。 */
170
+ staleKind?: 'owner-gone' | 'heartbeat-stopped'
162
171
  }
163
172
 
164
173
  /** operation-scoped lock token:accepted 后只属于当前 mutation 调用链 */
@@ -254,7 +263,9 @@ export async function withMutationLock(
254
263
  const reason: LockBlockReason = res.state === 'LOCKED'
255
264
  ? 'locked'
256
265
  : res.state === 'STALE_LOCK_DETECTED'
257
- ? 'stale'
266
+ // 残留锁再分两类(issue:真机 release 失败留痕):结构可证(进程已死/PID 复用)与
267
+ // 「进程还活着但心跳长期停止」。后者不能谎称「持有进程已不存在」,必须给出不同的处置指引。
268
+ ? (res.staleKind === 'heartbeat-stopped' ? 'stale-degraded' : 'stale')
258
269
  : 'unavailable'
259
270
  return { context: null, release: async () => {}, reason, detail: res.detail }
260
271
  }
@@ -359,8 +370,18 @@ export interface EnvLockManagerOptions {
359
370
  lockVersion?: string
360
371
  /** heartbeat 续期写失败回调(留痕;不中断 mutation) */
361
372
  onHeartbeatWriteFailure?: (err: unknown) => void
373
+ /** release 无法把 ownership 从盘上摘掉时留痕(unlink 反复失败 → 已 quarantine 解除阻塞;或彻底失败)。
374
+ * 以前这条路径完全静默:调用方 `release().catch(() => {})` 把错误吞掉,锁留在盘上无人知道。 */
375
+ onReleaseFailure?: (b: { err: unknown; quarantined: boolean }) => void
362
376
  /** heartbeat 定时器(测试可注入手动 tick 的假定时器;缺省用全局定时器) */
363
377
  timers?: LockTimerApi
378
+ /** 单次持有超过该时长只**告警**(缺省 120 s;0 = 关闭看门狗)。
379
+ * 真机 issue:autosync 成功后 ownership 与 heartbeat 都没释放、seq 一直涨,recover-stale-lock
380
+ * 判定「持有者还活着」拒绝回收,用户只能删 locks 目录或重启桌面端 —— 期间**没有任何线索**
381
+ * 说明是哪个 op 卡住了。看门狗只补这一层可观测性,绝不强拆活持有者(那会造出双持有)。 */
382
+ holdWarnAfterMs?: number
383
+ /** 长持有告警回调(留痕/上报;异常被吞,绝不影响锁状态) */
384
+ onHoldExceeded?: (info: { op: string; heldMs: number; tokenId: string }) => void
364
385
  }
365
386
 
366
387
  /** 默认 io 实现 */
@@ -589,6 +610,14 @@ export class EnvironmentLockManager {
589
610
  private readonly acquireTimeoutMs: number
590
611
  private readonly lockVersion: string
591
612
  private readonly onHeartbeatWriteFailure: (err: unknown) => void
613
+ private readonly onReleaseFailure: (b: { err: unknown; quarantined: boolean }) => void
614
+ /** 长持有看门狗阈值/回调(见 EnvLockManagerOptions.holdWarnAfterMs) */
615
+ private readonly holdWarnAfterMs: number
616
+ private readonly onHoldExceeded: (info: { op: string; heldMs: number; tokenId: string }) => void
617
+ /** 看门狗定时器句柄(与 heartbeatTimer 分开:一个是续期,一个是「该不该还没释放」) */
618
+ private holdWatchdogTimer: unknown = null
619
+ private holdStartedAt = 0
620
+ private holdOp = ''
592
621
  /** 诊断用(acquire 时写 ownership.op/target) */
593
622
  private readonly defaultOp: string
594
623
  private readonly defaultTarget: string
@@ -601,6 +630,10 @@ export class EnvironmentLockManager {
601
630
  /** heartbeat 定时器句柄(注入面返回值,类型未知 → 用 null 判「未启动」) */
602
631
  private heartbeatTimer: unknown = null
603
632
  private heartbeatSeq = 0
633
+ /** 在飞 acquire 计数:reclaimOwnLeftover 只在「本 manager 此刻没有别的 acquire 在飞」时动手。
634
+ * 否则 A 刚 open('wx') 成功、还没写上 activeToken 的那一瞬,并发 B 会把 A 的**新锁**当成自己的
635
+ * 残留挪走 —— §11.1-c23 实测会出现两个 ACQUIRED(双持有),那是比卡死更难查的错。 */
636
+ private acquireInFlight = 0
604
637
  private readonly activeInstanceId: string
605
638
  /** 串行化的 heartbeat 写链(**最后一次写**的 promise);release 前用于 drain,见 drainHeartbeat */
606
639
  private pendingHeartbeat: Promise<void> = Promise.resolve()
@@ -632,6 +665,9 @@ export class EnvironmentLockManager {
632
665
  this.acquireTimeoutMs = opts.acquireTimeoutMs ?? DEFAULT_ACQUIRE_TIMEOUT_MS
633
666
  this.lockVersion = opts.lockVersion ?? '0.1.0'
634
667
  this.onHeartbeatWriteFailure = opts.onHeartbeatWriteFailure ?? (() => {})
668
+ this.onReleaseFailure = opts.onReleaseFailure ?? (() => {})
669
+ this.holdWarnAfterMs = opts.holdWarnAfterMs ?? DEFAULT_HOLD_WARN_AFTER_MS
670
+ this.onHoldExceeded = opts.onHoldExceeded ?? (() => {})
635
671
  this.timers = opts.timers ?? defaultTimers
636
672
  this.defaultOp = opts.op ?? 'mutation'
637
673
  this.defaultTarget = opts.target ?? 'unknown'
@@ -667,6 +703,8 @@ export class EnvironmentLockManager {
667
703
  : null
668
704
  /** 「EEXIST/EPERM 说文件在,inspect 却读不到」= 文件在两次读取之间被释放的竞态(issue #79) */
669
705
  let freeRetries = 0
706
+ this.acquireInFlight += 1
707
+ try {
670
708
  for (;;) {
671
709
  // —— 先确保 locks 目录存在(mkdir 递归;EPERM 在下面归类为 PERMISSION_ERROR)——
672
710
  try {
@@ -693,6 +731,9 @@ export class EnvironmentLockManager {
693
731
  // issue #79:EEXIST 与「ownership 读不到」同时出现 = 上一次占用的释放竞态。
694
732
  // 此前直接判 LOCKED,一次无害的竞态就变成「另一个任务正在运行」并可能被记成
695
733
  // mutation-locked(真机:连续 16 次跳过,用户侧看不出原因)。重试 open('wx') 即可。
734
+ // 盘上这份 ownership 是本 manager 自己的残留(上一次 release 失败留在盘上)→ 结构可证地
735
+ // 自愈后重试;否则它会以「owner alive degraded」永久占住锁,所有 destructive 操作恒 423。
736
+ if (await this.reclaimOwnLeftover(inspect)) continue
696
737
  if (inspect.state === 'FREE' && freeRetries < MAX_FREE_RETRIES) {
697
738
  freeRetries += 1
698
739
  continue
@@ -706,7 +747,7 @@ export class EnvironmentLockManager {
706
747
  return { state: 'LOCKED', token: null, detail: inspect.detail }
707
748
  }
708
749
  // STALE/UNKNOWN/IO 直接返回(不自动删除;destructive 不执行)
709
- return { state: inspect.state, token: null, detail: inspect.detail }
750
+ return { state: inspect.state, token: null, detail: inspect.detail, staleKind: inspect.staleKind }
710
751
  }
711
752
  // EPERM/EACCES 等(Windows open('wx') 对存在文件常抛 EPERM 而非 EEXIST):
712
753
  // 按 §8.1 分类 —— 先检查 environment.lock 是否确实存在且可读取;
@@ -716,6 +757,8 @@ export class EnvironmentLockManager {
716
757
  const exists = await this.statLockExists()
717
758
  if (exists === true) {
718
759
  const inspect = await this.inspectLockState()
760
+ // 同 EEXIST 分支:自己的残留 → 自愈后重试
761
+ if (await this.reclaimOwnLeftover(inspect)) continue
719
762
  // 同 EEXIST 分支:文件刚被释放的竞态 → 重试独占创建(不是「被占用」)
720
763
  if (inspect.state === 'FREE' && freeRetries < MAX_FREE_RETRIES) {
721
764
  freeRetries += 1
@@ -725,7 +768,7 @@ export class EnvironmentLockManager {
725
768
  await sleep(this.heartbeatIntervalMs / 2)
726
769
  continue
727
770
  }
728
- return { state: inspect.state, token: null, detail: inspect.detail }
771
+ return { state: inspect.state, token: null, detail: inspect.detail, staleKind: inspect.staleKind }
729
772
  }
730
773
  // 无既有锁 → 权限/ACL/文件系统错误(可能目录不可写 / ACL 拒绝),非锁占用
731
774
  return exists === false
@@ -774,8 +817,13 @@ export class EnvironmentLockManager {
774
817
  this.activeToken = token
775
818
  this.heartbeatSeq = 0
776
819
  this.startHeartbeat()
820
+ // 与 heartbeat 同期启动看门狗:它回答的是另一个问题 ——「这次持有是不是早该释放了」
821
+ this.startHoldWatchdog(op, token.tokenId)
777
822
  return { state: 'ACQUIRED', token, detail: `op=${op}` }
778
823
  }
824
+ } finally {
825
+ this.acquireInFlight -= 1
826
+ }
779
827
  }
780
828
 
781
829
  /* ------------------------------------------------------------ validate / release */
@@ -809,6 +857,8 @@ export class EnvironmentLockManager {
809
857
  throw new EnvironmentLockOwnedByAnotherError(utilsMsg('utils.envLock.releaseForeignToken'))
810
858
  }
811
859
  const instanceId = this.activeInstanceId
860
+ // 每一条 release 出口都经过这里(含下面全部抛错分支)→ 看门狗在此统一停掉,不留悬空定时器
861
+ this.stopHoldWatchdog()
812
862
  this.stopHeartbeat()
813
863
  // —— release 前校验磁盘 ownership record 仍属于自己(防异常恢复/人工修改)——
814
864
  const st = await this.readOwnershipState()
@@ -839,15 +889,42 @@ export class EnvironmentLockManager {
839
889
  )
840
890
  }
841
891
  // —— matching:unlink ——(acquire 成功后句柄已 close,此处只有 unlink)
842
- try {
843
- await this.io.unlink(this.ownershipPath)
844
- } catch (e) {
845
- // unlink 失败:**保留 activeToken**(仍持有该磁盘 inode),调用方可重试 release;
846
- // 绝不在此清空 token(否则锁卡死在磁盘而令牌失效)。
892
+ // 有界瞬时重试(Windows 上杀软/索引器/搜索服务会短暂持有句柄 → EBUSY/EPERM 自行消失)。
893
+ let unlinkErr: unknown = null
894
+ this.transientRetries = 0
895
+ for (;;) {
896
+ try {
897
+ await this.io.unlink(this.ownershipPath)
898
+ unlinkErr = null
899
+ break
900
+ } catch (e) {
901
+ // ENOENT:正式路径已经没了 → 释放目的已达成(不是失败)
902
+ if (isENOENT(e)) { unlinkErr = null; break }
903
+ unlinkErr = e
904
+ if (await this.tryTransientRetry('unlink')) continue
905
+ break
906
+ }
907
+ }
908
+ if (unlinkErr !== null) {
909
+ // 仍删不掉(真机卡死态的起点):以前这里直接抛错,而调用方普遍 `release().catch(() => {})`
910
+ // → ownership 留在盘上、心跳已停、进程仍活 ⇒ inspectLockState 判「owner alive degraded」
911
+ // ⇒ 永不 STALE ⇒ 所有 destructive 操作恒 423,用户只能手工删锁文件。
912
+ // 现在先把 ownership 挪出正式路径(quarantine)解除阻塞,再如实留痕。
913
+ const quarantined = await this.quarantineOwnership(instanceId)
914
+ if (quarantined) {
915
+ this.activeToken = null
916
+ await this.drainHeartbeat()
917
+ await this.cleanupHeartbeat(instanceId).catch(() => {})
918
+ this.onReleaseFailure({ err: unlinkErr, quarantined: true })
919
+ return
920
+ }
921
+ // quarantine 也失败(rename 与 unlink 双双被拒):**保留 activeToken**(仍持有该磁盘 inode),
922
+ // 调用方可重试 release;绝不在此清空 token(否则锁卡死在磁盘而令牌失效)。
847
923
  // 同 ownership-lost 分支:抛错前 drain 在途写(定时器已停 → drain 有界),
848
924
  // 否则调用方随后的目录清理会与已启动的 tmp→rename 竞争。
849
925
  await this.drainHeartbeat()
850
- throw new EnvironmentLockIOError(utilsMsg('utils.envLock.releaseUnlinkFailed', { path: this.ownershipPath, reason: e instanceof Error ? e.message : String(e) }), e)
926
+ this.onReleaseFailure({ err: unlinkErr, quarantined: false })
927
+ throw new EnvironmentLockIOError(utilsMsg('utils.envLock.releaseUnlinkFailed', { path: this.ownershipPath, reason: unlinkErr instanceof Error ? unlinkErr.message : String(unlinkErr) }), unlinkErr)
851
928
  }
852
929
  // unlink 成功 → 释放完成:**先清 token 再 drain**,最后清自己的 heartbeat sidecar。
853
930
  // 顺序关键:activeToken=null 必须早于 drain —— 否则 interval 可能在 drain 返回之后、cleanup 之前
@@ -858,6 +935,60 @@ export class EnvironmentLockManager {
858
935
  await this.cleanupHeartbeat(instanceId).catch(() => {})
859
936
  }
860
937
 
938
+ /**
939
+ * 把正式路径上的 ownership 记录挪到 `environment.recovering.*`(quarantine)。
940
+ * 只用于**确证属于本 manager** 的路径:release 的 unlink 失败、acquire 发现盘上是自己的 instanceId。
941
+ *
942
+ * 为什么用 rename 而不是继续 unlink:unlink 删不掉说明「这个目录项删不动」(Windows 共享冲突 /
943
+ * 杀软句柄),重复同一操作不会变好;rename 只移动目录项、不删 inode,能立刻把正式路径腾空,
944
+ * 让后续 acquire 继续。挪走后二次读校验 captured 的 instanceId 仍是自己的才删副本;
945
+ * 不符(异常:被他人写入)就保留副本可查 —— 阻塞已解除,这是本方法与「直接抛错」的关键区别。
946
+ */
947
+ private async quarantineOwnership(instanceId: string): Promise<boolean> {
948
+ const capturedPath = path.join(this.locksDir, `${RECOVERING_PREFIX}${randomHex(8)}`)
949
+ try {
950
+ await this.io.rename(this.ownershipPath, capturedPath)
951
+ } catch (e) {
952
+ // ENOENT:正式路径已经空了 → 目的达成(没有可 quarantine 的对象)
953
+ return isENOENT(e)
954
+ }
955
+ let own = false
956
+ try {
957
+ const captured = readLockJsonSafe(await this.io.readFileText(capturedPath)) as LockOwnershipRecord | null
958
+ own = captured !== null && typeof captured === 'object' && captured.owner?.instanceId === instanceId
959
+ } catch { own = false }
960
+ // 只删确证是自己的副本;否则保留(不删他人数据)
961
+ if (own) await this.io.unlink(capturedPath).catch(() => {})
962
+ return true
963
+ }
964
+
965
+ /**
966
+ * 回收「本 manager 自己上一次释放留下的残留」。
967
+ *
968
+ * 真机卡死态:release 的 unlink 失败被调用方 `release().catch(() => {})` 静默吞掉 →
969
+ * ownership 留在盘上、心跳已停,而本进程仍活 ⇒ inspectLockState 判 LOCKED(owner alive degraded)
970
+ * ⇒ 永不 STALE、显式回收也拒 ⇒ 所有 destructive 操作永久 423。
971
+ *
972
+ * 判据必须结构可证(否则就成了跨实例误删):盘上 instanceId === 本 manager 的 activeInstanceId
973
+ * (随机 16 字节、只有本 manager 会产生 ⇒ 宿主内不可能是别人的锁),并且本 manager 此刻
974
+ * 没有在途临界区(activeToken === null),或 release 已进入但没走完(heartbeatTimer === null,
975
+ * 即 stopHeartbeat() 已执行)。两者都不成立时一律返回 false。
976
+ */
977
+ private async reclaimOwnLeftover(insp: { ownerInstanceId?: string }): Promise<boolean> {
978
+ if (insp.ownerInstanceId !== this.activeInstanceId) return false
979
+ // 有别的 acquire 在飞 = 盘上这份可能是它刚拿到的**新锁**(open 与 token 赋值之间有 await 窗口)
980
+ if (this.acquireInFlight > 1) return false
981
+ if (this.activeToken !== null && this.heartbeatTimer !== null) return false
982
+ this.stopHeartbeat()
983
+ const ok = await this.quarantineOwnership(this.activeInstanceId)
984
+ if (!ok) return false
985
+ this.activeToken = null
986
+ this.heartbeatSeq = 0
987
+ await this.drainHeartbeat()
988
+ await this.cleanupHeartbeat(this.activeInstanceId).catch(() => {})
989
+ return true
990
+ }
991
+
861
992
  /* ------------------------------------------------------------ heartbeat */
862
993
 
863
994
  private startHeartbeat(): void {
@@ -880,6 +1011,55 @@ export class EnvironmentLockManager {
880
1011
  }
881
1012
  }
882
1013
 
1014
+ /**
1015
+ * 长持有看门狗:持有时间超过阈值时**告警一次**,然后自行停掉。
1016
+ *
1017
+ * 只做观察,不做解锁。真机 issue(Windows 桌面端):「autosync 成功后 ownership 与 heartbeat
1018
+ * 都没释放、heartbeat seq 一直在涨,recover-stale-lock 判定持有者还活着拒绝回收,只能手动删
1019
+ * locks 目录或重启桌面端」。那种状态下心跳是「活着」的,任何结构性 stale 判据都不会命中 ——
1020
+ * 所以最需要的是**一条能定位到 op 的日志**,而不是又一个自动回收器(强拆活持有者会造出双持有)。
1021
+ *
1022
+ * 定时器沿用注入面(LockTimerApi 只有 setInterval):命中一次即 clearInterval,等价于一次性。
1023
+ */
1024
+ private startHoldWatchdog(op: string, tokenId: string): void {
1025
+ this.stopHoldWatchdog()
1026
+ if (!(this.holdWarnAfterMs > 0)) return
1027
+ this.holdStartedAt = this.now()
1028
+ this.holdOp = op
1029
+ const timer = this.timers.setInterval(() => {
1030
+ // token 已换人/已释放 → 这次持有已结束,看门狗无事可做
1031
+ if (this.activeToken === null || this.activeToken.tokenId !== tokenId) {
1032
+ this.stopHoldWatchdog()
1033
+ return
1034
+ }
1035
+ const heldMs = Math.max(this.now() - this.holdStartedAt, 0)
1036
+ this.stopHoldWatchdog()
1037
+ try {
1038
+ this.onHoldExceeded({ op, heldMs, tokenId })
1039
+ } catch {
1040
+ /* 观察者异常绝不影响锁状态(看门狗是观察面,不是控制面) */
1041
+ }
1042
+ }, Math.max(this.holdWarnAfterMs, 50))
1043
+ this.holdWatchdogTimer = timer
1044
+ const handle = timer as { unref?: () => void } | null | undefined
1045
+ if (handle !== null && handle !== undefined && typeof handle.unref === 'function') handle.unref()
1046
+ }
1047
+
1048
+ private stopHoldWatchdog(): void {
1049
+ if (this.holdWatchdogTimer !== null) {
1050
+ this.timers.clearInterval(this.holdWatchdogTimer)
1051
+ this.holdWatchdogTimer = null
1052
+ }
1053
+ // 注意:**不清** holdOp/holdStartedAt —— 告警命中后定时器即停,但这次持有的「是谁、持了多久」
1054
+ // 仍要继续可读(holdInfo),直到 release 时 activeToken 归零自然失效。
1055
+ }
1056
+
1057
+ /** 当前持有的操作与已持有时长(诊断用;未持有 → null)。持有超过阈值时它给出「是哪个 op」。 */
1058
+ get holdInfo(): { op: string; heldMs: number } | null {
1059
+ if (this.activeToken === null) return null
1060
+ return { op: this.holdOp, heldMs: Math.max(this.now() - this.holdStartedAt, 0) }
1061
+ }
1062
+
883
1063
  /**
884
1064
  * 等待**当前在途**的 heartbeat 写完成(不改变持有状态、不停定时器)。
885
1065
  * 首写在 startHeartbeat() 中**同步**入链,故 acquire() 之后调用本方法必然等到首写落盘。
@@ -900,6 +1080,7 @@ export class EnvironmentLockManager {
900
1080
  * 锁的持有状态与磁盘内容由调用方的 release 决定。
901
1081
  */
902
1082
  async stopHeartbeatAndDrain(): Promise<void> {
1083
+ this.stopHoldWatchdog()
903
1084
  this.stopHeartbeat()
904
1085
  await this.drainHeartbeat()
905
1086
  }
@@ -1000,7 +1181,14 @@ export class EnvironmentLockManager {
1000
1181
  * heartbeat expired + PID alive + identity 相同 → LOCKED (owner alive / heartbeat degraded)
1001
1182
  * probe 无法可靠确定 → UNKNOWN_STATE
1002
1183
  */
1003
- async inspectLockState(): Promise<{ state: LockState; detail?: string; corruptOwnership?: boolean; ownerInstanceId?: string }> {
1184
+ async inspectLockState(): Promise<{
1185
+ state: LockState
1186
+ detail?: string
1187
+ corruptOwnership?: boolean
1188
+ ownerInstanceId?: string
1189
+ /** STALE_LOCK_DETECTED 的细分(供用户文案分类;见 AcquireResult.staleKind) */
1190
+ staleKind?: 'owner-gone' | 'heartbeat-stopped'
1191
+ }> {
1004
1192
  const st = await this.readOwnershipState()
1005
1193
  if (st.kind === 'missing') {
1006
1194
  // 无所有权文件:可能在创建中、也已被清除 —— **报告**层如实说「没有锁」(issue #79)。
@@ -1068,6 +1256,19 @@ export class EnvironmentLockManager {
1068
1256
  return { state: 'STALE_LOCK_DETECTED', ownerInstanceId: rec.owner.instanceId, detail: utilsMsg('utils.envLock.pidReuse', { pid: rec.owner.pid }) }
1069
1257
  }
1070
1258
  // alive 且 identity 相同 → owner alive(heartbeat degraded 保护)
1259
+ // issue #36 对称性(本例 = 真机卡死态):identity 相同只证明「这个 pid 还活着」,不证明它仍在持有锁。
1260
+ // 心跳**长过期**(远超窗口,见 longExpiredAfterMs)说明写方早已停摆(典型:release 的 unlink 失败 +
1261
+ // 调用方静默吞错)——此时判 STALE,让「回收残留锁」可用;acquire 侧依旧不自动摘锁
1262
+ // (isProvablyStale 不变),所以放宽分类不会变成跨实例误删许可。
1263
+ const longExpiredSame = this.longExpiredReason(heartbeat, now)
1264
+ if (longExpiredSame !== null) {
1265
+ return {
1266
+ state: 'STALE_LOCK_DETECTED',
1267
+ ownerInstanceId: rec.owner.instanceId,
1268
+ staleKind: 'heartbeat-stopped',
1269
+ detail: utilsMsg('utils.envLock.ownerAliveHeartbeatStopped', { pid: rec.owner.pid, longExpired: longExpiredSame }),
1270
+ }
1271
+ }
1071
1272
  return { state: 'LOCKED', ownerInstanceId: rec.owner.instanceId, detail: utilsMsg('utils.envLock.ownerAliveDegraded') }
1072
1273
  }
1073
1274
 
@@ -1214,8 +1415,11 @@ export class EnvironmentLockManager {
1214
1415
  }
1215
1416
  // recorded identity 与探测不同 → PID reuse → 原 owner 已死 → stale 成立
1216
1417
  if (rec.owner.osProcessStartIdentity !== ident.osProcessStartIdentity) return true
1217
- // 同一进程仍存活 → 非 stale
1218
- return false
1418
+ // 同一进程仍存活:常规判定非 stale,但必须与 inspectLockState 用**同一**判据(同 issue #36 的理由,
1419
+ // 见上方无 identity 能力分支):心跳长过期 ⇒ 写方已停摆,显式回收要放行;否则用户点「回收残留锁」
1420
+ // 只会拿到「二次验证失败」,等于没修。
1421
+ const hbSamePid = await this.readHeartbeat(rec.owner.instanceId).catch(() => null)
1422
+ return this.longExpiredReason(hbSamePid, this.now()) !== null
1219
1423
  }
1220
1424
 
1221
1425
  /** 心跳「长过期」判据(issue #36):达到阈值 → 返回可读原因,否则 null。
@@ -1348,6 +1552,12 @@ export type LockBlockReason =
1348
1552
  * 必须显式回收(GUI「事故恢复」/ CLI `recover-stale-lock`)。见 issue #27。
1349
1553
  */
1350
1554
  | 'stale'
1555
+ /**
1556
+ * 残留锁的**降级形态**:记录里的进程仍活着、OS 身份也一致,但心跳已长期停止(远超窗口)。
1557
+ * 只有一种真实成因:持有者的 release 没能把 ownership 从盘上摘掉(Windows 句柄冲突),
1558
+ * 而调用方又把 release 的错误吞了。文案不能谎称「持有进程已不存在」,也不用「稍后重试」骗人。
1559
+ */
1560
+ | 'stale-degraded'
1351
1561
  /** 锁不可用/IO/权限/UNKNOWN(→ 「操作暂时无法执行,请稍后重试」) */
1352
1562
  | 'unavailable'
1353
1563
 
@@ -1363,6 +1573,8 @@ export const LOCK_BLOCK_MESSAGE: Record<LockBlockReason, string> = {
1363
1573
  // issue #31:文案承诺的「事故恢复」入口必须真的能回收残留锁——GUI 已接线
1364
1574
  // (GET /recovery/status 的 lock 字段 + POST /recovery/lock/recover),两处入口都真实可达。
1365
1575
  get stale() { return utilsMsg('utils.envLock.block.stale') },
1576
+ // 降级形态:不谎称进程已退出,也不说「稍后重试」——处置路径与 stale 相同(显式回收)。
1577
+ get 'stale-degraded'() { return utilsMsg('utils.envLock.block.staleDegraded') },
1366
1578
  }
1367
1579
 
1368
1580
  /** 分类的**简短**文案(单行、可用于表格单元格/迁移历史摘要/日志前缀)。
@@ -1375,6 +1587,28 @@ export const LOCK_BLOCK_BRIEF: Record<LockBlockReason, string> = {
1375
1587
  get unavailable() { return utilsMsg('utils.envLock.brief.unavailable') },
1376
1588
  // stale 必须点出「残留」——否则用户会像 issue #31 那样等 9 天(57 次静默跳过)。
1377
1589
  get stale() { return utilsMsg('utils.envLock.brief.stale') },
1590
+ get 'stale-degraded'() { return utilsMsg('utils.envLock.brief.staleDegraded') },
1591
+ }
1592
+
1593
+ /**
1594
+ * 锁分类 → 落进结果对象/历史记录的**机器token**(客户端据此本地化;不许再把所有被挡拍平成一个词)。
1595
+ *
1596
+ * issue:真机现场 SAFE MODE 被拒时 locks 目录是空的,界面却说「环境锁被占用」——
1597
+ * 因为宿主所有被挡路径都写死 'mutation-locked',客户端只能照最坏情况解释,排查方向被带偏。
1598
+ * 现在按分类发 token:**只有真被另一项活任务占着(LOCKED)才叫 locked**。
1599
+ * - 'mutation-safe-mode':被 SAFE MODE 阻断(锁目录通常为空,处置入口是事故恢复)
1600
+ * - 'mutation-lock-stale':残留锁(含心跳降级形态)——重试/重启都不会自愈,必须显式回收
1601
+ * - 'mutation-lock-unavailable':锁不可用(目录 IO/权限/未知,或 acquire 直接抛错)
1602
+ * 旧 token 'mutation-locked' 仍表示「被活跃任务持有」,客户端必须继续认它。
1603
+ */
1604
+ export function lockSkipToken(reason: LockBlockReason | undefined): string {
1605
+ switch (reason) {
1606
+ case 'blocked': return 'mutation-safe-mode'
1607
+ case 'locked': return 'mutation-locked'
1608
+ case 'stale':
1609
+ case 'stale-degraded': return 'mutation-lock-stale'
1610
+ default: return 'mutation-lock-unavailable'
1611
+ }
1378
1612
  }
1379
1613
 
1380
1614
  /** destructive 必须成功获取 Environment Lock;否则抛此错(被另一进程/操作持有,或锁不可用)。
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * src/utils/** 的领域消息目录(zh 源语言 / en 镜像)——「英文界面零中文」迁移(t5)。
3
3
  *
4
- * 口径(与 src/core/messages.ts 一致,见 docs/design/2026-10-08-i18n-en-hardcoding.md):
4
+ * 口径(与 src/core/messages.ts 一致,见 docs/archive/2026-10-08-i18n-en-hardcoding.md):
5
5
  * - zh 值 = 迁移前的既有中文文案**逐字不变**(既有测试断言依赖它,只允许新增 en);
6
6
  * - en 值类型为 Record<keyof typeof zh, string> —— 缺键/多键即编译错误;
7
7
  * - 动态明细一律走 {param} 插值传参,不得丢信息;
@@ -73,6 +73,7 @@ export const zh = {
73
73
  'utils.envLock.heartbeatExpiredNoIdentity': 'heartbeat 过期且 pid={pid} 存活,但无法可靠取得 OS process identity,保守拒绝删除',
74
74
  'utils.envLock.pidReuse': 'pid reuse:pid={pid} identity 与 recorded 不同',
75
75
  'utils.envLock.ownerAliveDegraded': 'owner 进程存活(heartbeat 可能 degraded),非 stale',
76
+ 'utils.envLock.ownerAliveHeartbeatStopped': 'owner pid={pid} 进程存活且进程身份一致,但 heartbeat {longExpired} → 判定为残留锁(写方已停摆),可显式回收',
76
77
  'utils.envLock.notStaleRefuseRecovery': '非 stale,拒绝 recovery',
77
78
  'utils.envLock.ownershipGone': 'ownership 已消失(被他人接管/清除),停止 recovery',
78
79
  'utils.envLock.captureRenameFailed': '捕获 rename 失败(可能被他人接管),停止',
@@ -91,6 +92,9 @@ export const zh = {
91
92
  'utils.envLock.durationMinutes': '{value} 分钟',
92
93
  'utils.envLock.durationSeconds': '{value} 秒',
93
94
  'utils.envLock.ioPermissionNotLock': '{what}: 权限/ACL 错误 ({code}),非锁占用',
95
+ 'utils.envLock.heartbeatWriteFailed': '环境锁心跳写入失败: {reason}',
96
+ 'utils.envLock.releaseFailedQuarantined': '环境锁释放失败,已把 ownership 挪到 recovering 解除阻塞: {reason}',
97
+ 'utils.envLock.releaseFailedStuck': '环境锁释放失败,且无法挪走 ownership(后续操作会被判为锁被占用): {reason}',
94
98
 
95
99
  // ---------- utils/env-lock.ts:锁被挡时给用户的分类文案(长 / 短两套,同源同分类) ----------
96
100
  'utils.envLock.block.locked': '另一个任务正在运行,请稍后重试。',
@@ -99,10 +103,14 @@ export const zh = {
99
103
  'utils.envLock.block.stale': '检测到上次异常退出残留的配置锁(其持有进程已不存在),操作已被阻止。'
100
104
  + '该锁不会自动清除,重试或重启 DSH 均无效:请在「事故恢复」中点击「回收残留锁」,'
101
105
  + '或运行 dsh-config-manager recover-stale-lock 回收后再重试。',
106
+ 'utils.envLock.block.staleDegraded': '检测到残留的配置锁:其记录中的进程仍在运行,但心跳已长期停止,说明上次释放没有完成。'
107
+ + '操作已被阻止,重试或重启 DSH 都不会自愈:请在「事故恢复」中点击「回收残留锁」,'
108
+ + '或运行 dsh-config-manager recover-stale-lock 回收后再重试。',
102
109
  'utils.envLock.brief.locked': '环境锁被另一项任务占用',
103
110
  'utils.envLock.brief.blocked': '配置修改已被保护,需先处理恢复事项',
104
111
  'utils.envLock.brief.unavailable': '环境锁暂时不可用',
105
112
  'utils.envLock.brief.stale': '残留配置锁(持有进程已不存在),需先回收',
113
+ 'utils.envLock.brief.staleDegraded': '残留配置锁(心跳已长期停止),需先回收',
106
114
 
107
115
  // ---------- utils/proxy.ts:代理隧道(保留原文的双语形态,zh 逐字不变) ----------
108
116
  'utils.proxy.connectTimeout': '代理连接超时 / proxy connect timed out ({ms}ms)',
@@ -179,6 +187,7 @@ export const en: Record<keyof typeof zh, string> = {
179
187
  'utils.envLock.heartbeatExpiredNoIdentity': 'heartbeat expired and pid={pid} is alive, but the OS process identity cannot be obtained reliably — conservatively refusing to delete',
180
188
  'utils.envLock.pidReuse': 'pid reuse: pid={pid} identity differs from the recorded one',
181
189
  'utils.envLock.ownerAliveDegraded': 'owner process is alive (heartbeat may be degraded), not stale',
190
+ 'utils.envLock.ownerAliveHeartbeatStopped': 'owner pid={pid} is alive and its process identity matches, but heartbeat {longExpired} → judged a stale lock (the writer stopped), explicit reclaim allowed',
182
191
  'utils.envLock.notStaleRefuseRecovery': 'not stale — refusing recovery',
183
192
  'utils.envLock.ownershipGone': 'ownership has disappeared (taken over/cleared by someone else) — stopping recovery',
184
193
  'utils.envLock.captureRenameFailed': 'capture rename failed (possibly taken over by someone else) — stopping',
@@ -197,6 +206,9 @@ export const en: Record<keyof typeof zh, string> = {
197
206
  'utils.envLock.durationMinutes': '{value} minutes',
198
207
  'utils.envLock.durationSeconds': '{value} seconds',
199
208
  'utils.envLock.ioPermissionNotLock': '{what}: permission/ACL error ({code}), not lock contention',
209
+ 'utils.envLock.heartbeatWriteFailed': 'Environment lock heartbeat write failed: {reason}',
210
+ 'utils.envLock.releaseFailedQuarantined': 'Environment lock release failed; the ownership file was moved to recovering so writes are no longer blocked: {reason}',
211
+ 'utils.envLock.releaseFailedStuck': 'Environment lock release failed and the ownership file could not be moved aside (later operations will look lock-blocked): {reason}',
200
212
 
201
213
  'utils.envLock.block.locked': 'Another task is running, please retry later.',
202
214
  'utils.envLock.block.blocked': 'Configuration changes are protected — resolve the recovery items before continuing.',
@@ -204,10 +216,14 @@ export const en: Record<keyof typeof zh, string> = {
204
216
  'utils.envLock.block.stale': 'A configuration lock left behind by a previous abnormal exit was detected (its owning process no longer exists), so the operation was blocked.'
205
217
  + 'This lock will not clear itself — retrying or restarting DSH will not help: click "Reclaim stale lock" under "Incident recovery",'
206
218
  + 'or run dsh-config-manager recover-stale-lock and then retry.',
219
+ 'utils.envLock.block.staleDegraded': 'A leftover configuration lock was detected: its recorded process is still running, but its heartbeat stopped long ago, so the last release never finished.'
220
+ + 'The operation was blocked, and retrying or restarting DSH will not clear it: click "Reclaim stale lock" under "Incident recovery",'
221
+ + 'or run dsh-config-manager recover-stale-lock and then retry.',
207
222
  'utils.envLock.brief.locked': 'Environment lock held by another task',
208
223
  'utils.envLock.brief.blocked': 'Configuration changes are protected; resolve recovery items first',
209
224
  'utils.envLock.brief.unavailable': 'Environment lock temporarily unavailable',
210
225
  'utils.envLock.brief.stale': 'Stale configuration lock (owning process is gone); reclaim it first',
226
+ 'utils.envLock.brief.staleDegraded': 'Stale configuration lock (heartbeat stopped long ago); reclaim it first',
211
227
 
212
228
  // ---------- utils/proxy.ts ----------
213
229
  'utils.proxy.connectTimeout': 'Proxy connection timed out ({ms}ms)',
@@ -11,7 +11,7 @@
11
11
  * 调用方若把它 catch 成「这一层没有 patch 行」,用户手写的整层配置就会在导出/同步/预览里凭空消失;
12
12
  * 导入写回时更会把整份文件重写成「只剩本次导入的行」—— 这正是 issue #75 报告的数据丢失。
13
13
  *
14
- * 两个形状与 DSH 逐字对齐(**改这里等于改对外契约**,见 `docs/spec/bundle-format-v1.md`):
14
+ * 两个形状与 DSH 逐字对齐(**改这里等于改对外契约**,见 `docs/contracts/bundle-format-v1.md`):
15
15
  * - 载入:`!!js <源码>` → `{ __jsExpr: <源码> }`
16
16
  * - 写回:`{ __jsExpr: <源码> }` → `!!js <源码>`
17
17
  * 判据与 cordis 的 `isJsExpr`(`value instanceof Object && '__jsExpr' in value`)一致,于是 bundle 里
@@ -0,0 +1,120 @@
1
+ /**
2
+ * remove-tree 测试:复现并覆盖 `fs.rmSync(recursive, force)` 的静默失效。
3
+ * - 基线(win32):目录里一个悬空 junction ⇒ rmSync 不抛错也不删(回归判据)
4
+ * - removeTreeSync / removeTree:普通嵌套、悬空链接、有效 junction(只删链接)、只读文件、深树
5
+ * - 目标本身是链接 ⇒ 只删链接,指向的真实目录保留
6
+ */
7
+ import test from 'node:test';
8
+ import assert from 'node:assert/strict';
9
+ import fssync from 'node:fs';
10
+ import os from 'node:os';
11
+ import path from 'node:path';
12
+ import { removeTree, removeTreeSync } from './remove-tree.ts';
13
+
14
+ const linkType = process.platform === 'win32' ? 'junction' : 'dir';
15
+
16
+ function sandbox(t: test.TestContext): string {
17
+ const dir = fssync.mkdtempSync(path.join(os.tmpdir(), 'remove-tree-'));
18
+ t.after(() => { try { removeTreeSync(dir); } catch { /* 已删净 */ } });
19
+ return dir;
20
+ }
21
+
22
+ function write(file: string, text = 'x'): void {
23
+ fssync.mkdirSync(path.dirname(file), { recursive: true });
24
+ fssync.writeFileSync(file, text);
25
+ }
26
+
27
+ test('removeTreeSync:普通嵌套目录整棵删掉', (t) => {
28
+ const root = sandbox(t);
29
+ const target = path.join(root, 'profile');
30
+ write(path.join(target, 'a', 'b', 'deep.txt'));
31
+ write(path.join(target, 'top.txt'));
32
+ write(path.join(target, '.dsh', 'config.yml'));
33
+ removeTreeSync(target);
34
+ assert.equal(fssync.existsSync(target), false);
35
+ });
36
+
37
+ test('removeTreeSync:悬空 junction 不再卡住删除(rm 静默失效的根因)', (t) => {
38
+ const root = sandbox(t);
39
+ const target = path.join(root, 'profile');
40
+ write(path.join(target, 'package.json'));
41
+ write(path.join(target, 'node_modules', 'real-dep', 'index.js'));
42
+ // DSH 的真实形态:node_modules/<pkg> -> 已消失的 .dsh-module-fallback/node_modules/<pkg>
43
+ const danglingPkgs = ['immer', 'react', 'react-dom', 'scheduler'];
44
+ for (const pkg of danglingPkgs) {
45
+ fssync.symlinkSync(
46
+ path.join(target, '.dsh-module-fallback', 'node_modules', pkg),
47
+ path.join(target, 'node_modules', pkg),
48
+ linkType,
49
+ );
50
+ }
51
+ removeTreeSync(target);
52
+ assert.equal(fssync.existsSync(target), false);
53
+ });
54
+
55
+ test('基线:fs.rmSync 遇到悬空 junction 会静默留下条目(按环境观察,不作强断言)', (t) => {
56
+ const root = sandbox(t);
57
+ const target = path.join(root, 'profile');
58
+ write(path.join(target, 'keep.txt'));
59
+ write(path.join(target, 'node_modules', 'real', 'index.js'));
60
+ fssync.symlinkSync(path.join(target, '.dsh-module-fallback', 'node_modules', 'immer'), path.join(target, 'node_modules', 'immer'), linkType);
61
+ fssync.rmSync(target, { recursive: true, force: true });
62
+ // 实测(D: 卷):不抛错、留下 node_modules;同一形状在 C: temp 上却被删干净 ——
63
+ // 所以这里只记录观察值,真正的判据是「移除器一定收干净」,而不是 rmSync 一定失败。
64
+ t.diagnostic(`fs.rmSync left target behind: ${fssync.existsSync(target)}`);
65
+ removeTreeSync(target);
66
+ assert.equal(fssync.existsSync(target), false);
67
+ });
68
+
69
+ test('removeTreeSync:有效 junction 只删链接,绝不跟进目标目录', (t) => {
70
+ const root = sandbox(t);
71
+ const outside = path.join(root, 'pnpm-store', 'pkg');
72
+ write(path.join(outside, 'index.js'), 'outside');
73
+ const target = path.join(root, 'profile');
74
+ fssync.mkdirSync(path.join(target, 'node_modules'), { recursive: true });
75
+ fssync.symlinkSync(outside, path.join(target, 'node_modules', 'pkg'), linkType);
76
+ removeTreeSync(target);
77
+ assert.equal(fssync.existsSync(target), false);
78
+ assert.equal(fssync.readFileSync(path.join(outside, 'index.js'), 'utf8'), 'outside');
79
+ });
80
+
81
+ test('removeTreeSync:只读文件 / 只读目录照样删掉', (t) => {
82
+ const root = sandbox(t);
83
+ const target = path.join(root, 'profile');
84
+ const readonly = path.join(target, 'ro', 'file.txt');
85
+ write(readonly);
86
+ fssync.chmodSync(readonly, 0o444);
87
+ removeTreeSync(target);
88
+ assert.equal(fssync.existsSync(target), false);
89
+ });
90
+
91
+ test('removeTreeSync:目标本身是链接时只删链接', (t) => {
92
+ const root = sandbox(t);
93
+ const real = path.join(root, 'real');
94
+ write(path.join(real, 'index.js'), 'real');
95
+ const link = path.join(root, 'link');
96
+ fssync.symlinkSync(real, link, linkType);
97
+ removeTreeSync(link);
98
+ assert.equal(fssync.existsSync(link), false);
99
+ assert.equal(fssync.readFileSync(path.join(real, 'index.js'), 'utf8'), 'real');
100
+ });
101
+
102
+ test('removeTreeSync:深树 + 不存在路径(不抛错)', (t) => {
103
+ const root = sandbox(t);
104
+ let deep = path.join(root, 'profile');
105
+ for (let i = 0; i < 12; i++) deep = path.join(deep, `d${i}`);
106
+ write(path.join(deep, 'leaf.txt'));
107
+ removeTreeSync(path.join(root, 'profile'));
108
+ assert.equal(fssync.existsSync(path.join(root, 'profile')), false);
109
+ removeTreeSync(path.join(root, 'never-existed'));
110
+ });
111
+
112
+ test('removeTree(异步版)与同步版语义一致', async (t) => {
113
+ const root = sandbox(t);
114
+ const target = path.join(root, 'profile');
115
+ write(path.join(target, 'node_modules', 'real', 'index.js'));
116
+ fssync.symlinkSync(path.join(target, 'gone'), path.join(target, 'node_modules', 'ghost'), linkType);
117
+ await removeTree(target);
118
+ assert.equal(fssync.existsSync(target), false);
119
+ await removeTree(path.join(root, 'never-existed'));
120
+ });