dsh-config-manager 0.4.2 → 0.5.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 (263) hide show
  1. package/README.md +24 -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 +19 -41
  13. package/lib/client.js +863 -722
  14. package/lib/core/access-mode.d.ts +25 -0
  15. package/lib/core/access-mode.js +28 -0
  16. package/lib/core/backup.d.ts +11 -0
  17. package/lib/core/backup.js +27 -0
  18. package/lib/core/env-lock-lifecycle.d.ts +17 -3
  19. package/lib/core/env-lock-lifecycle.js +38 -0
  20. package/lib/core/external-failure.d.ts +9 -0
  21. package/lib/core/external-failure.js +50 -0
  22. package/lib/core/local-plugin-host.d.ts +9 -7
  23. package/lib/core/local-plugin-host.js +109 -15
  24. package/lib/core/local-plugin-pack.d.ts +20 -0
  25. package/lib/core/local-plugin-pack.js +18 -3
  26. package/lib/core/mcp-connector-store.d.ts +13 -0
  27. package/lib/core/mcp-connector-store.js +16 -1
  28. package/lib/core/messages-core.d.ts +45 -0
  29. package/lib/core/messages-core.js +92 -0
  30. package/lib/core/messages.d.ts +1 -0
  31. package/lib/core/messages.js +6 -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-data-registry.d.ts +1 -1
  38. package/lib/core/plugin-data-registry.js +1 -1
  39. package/lib/core/restore-plan-fingerprint.d.ts +2 -0
  40. package/lib/core/restore-plan-fingerprint.js +18 -0
  41. package/lib/core/restore-resume.d.ts +1 -1
  42. package/lib/core/restore-resume.js +1 -1
  43. package/lib/core/restore.d.ts +5 -0
  44. package/lib/core/restore.js +4 -1
  45. package/lib/core/types.d.ts +12 -0
  46. package/lib/foreign/claude-sessions.d.ts +1 -1
  47. package/lib/foreign/claude-sessions.js +1 -1
  48. package/lib/foreign/registry.js +1 -1
  49. package/lib/foreign/types.d.ts +1 -1
  50. package/lib/index.d.ts +15 -15
  51. package/lib/index.js +65 -72
  52. package/lib/market/git-file-writer.js +1 -1
  53. package/lib/market/github-repos.js +1 -1
  54. package/lib/market/market-config.js +1 -1
  55. package/lib/market/messages-market.js +1 -1
  56. package/lib/market/my-repo.js +1 -1
  57. package/lib/market/prepare.js +1 -1
  58. package/lib/market/reader.js +2 -2
  59. package/lib/market/repo-url.d.ts +1 -1
  60. package/lib/market/security.js +2 -2
  61. package/lib/market/star-cache.d.ts +1 -1
  62. package/lib/market/types.d.ts +1 -1
  63. package/lib/market/types.js +1 -1
  64. package/lib/market/url.js +1 -1
  65. package/lib/routes/backup.js +17 -9
  66. package/lib/routes/index.d.ts +1 -1
  67. package/lib/routes/kit.d.ts +42 -3
  68. package/lib/routes/kit.js +43 -3
  69. package/lib/routes/market.d.ts +1 -1
  70. package/lib/routes/market.js +3 -60
  71. package/lib/routes/model-tools-deps.d.ts +41 -0
  72. package/lib/routes/model-tools-deps.js +18 -0
  73. package/lib/routes/recovery.js +5 -3
  74. package/lib/routes/request-trust.d.ts +28 -0
  75. package/lib/routes/request-trust.js +65 -0
  76. package/lib/routes/route-support.d.ts +18 -26
  77. package/lib/routes/route-support.js +19 -32
  78. package/lib/routes/snapshots.d.ts +1 -1
  79. package/lib/routes/snapshots.js +4 -40
  80. package/lib/routes/sync.js +40 -28
  81. package/lib/schema/index.d.ts +2 -2
  82. package/lib/schema/index.js +2 -2
  83. package/lib/schema/section-registry.d.ts +5 -3
  84. package/lib/schema/section-registry.js +7 -3
  85. package/lib/security/secret-scanner.js +1 -1
  86. package/lib/sync/apply-bundle.d.ts +50 -0
  87. package/lib/sync/apply-bundle.js +60 -0
  88. package/lib/sync/autosync-scheduler.d.ts +9 -0
  89. package/lib/sync/autosync-scheduler.js +118 -89
  90. package/lib/sync/backup-scheduler.js +5 -4
  91. package/lib/sync/blob-store.d.ts +2 -2
  92. package/lib/sync/git/git-transport.d.ts +12 -0
  93. package/lib/sync/git/git-transport.js +50 -2
  94. package/lib/sync/merge.d.ts +2 -0
  95. package/lib/sync/merge.js +28 -0
  96. package/lib/sync/messages.d.ts +4 -0
  97. package/lib/sync/messages.js +9 -2
  98. package/lib/sync/s3/s3-transport.d.ts +1 -1
  99. package/lib/sync/s3/s3-transport.js +1 -1
  100. package/lib/sync/sync-engine.d.ts +4 -4
  101. package/lib/sync/sync-engine.js +25 -26
  102. package/lib/sync/sync-scope-boot.d.ts +34 -0
  103. package/lib/sync/sync-scope-boot.js +71 -0
  104. package/lib/sync/sync-scope.d.ts +103 -0
  105. package/lib/sync/sync-scope.js +229 -0
  106. package/lib/sync/sync-selection.d.ts +17 -4
  107. package/lib/sync/sync-selection.js +40 -14
  108. package/lib/sync/transport.d.ts +4 -1
  109. package/lib/sync/transport.js +6 -0
  110. package/lib/sync/webdav/webdav-transport.js +1 -1
  111. package/lib/sync/workspace-merge.d.ts +36 -0
  112. package/lib/sync/workspace-merge.js +152 -0
  113. package/lib/ui/backup-schedule.d.ts +13 -2
  114. package/lib/ui/backup-schedule.js +3 -0
  115. package/lib/ui/snapshots-view.d.ts +16 -0
  116. package/lib/ui/snapshots-view.js +21 -0
  117. package/lib/utils/env-lock.d.ts +96 -0
  118. package/lib/utils/env-lock.js +332 -111
  119. package/lib/utils/messages-utils.d.ts +6 -0
  120. package/lib/utils/messages-utils.js +17 -1
  121. package/lib/utils/patch-yaml.js +1 -1
  122. package/lib/utils/zip.js +1 -1
  123. package/package.json +3 -2
  124. package/src/adapters/mcp.test.ts +28 -0
  125. package/src/adapters/mcp.ts +33 -0
  126. package/src/adapters/plugins.test.ts +49 -0
  127. package/src/adapters/plugins.ts +9 -1
  128. package/src/adapters/pnpm-workspace.ts +1 -1
  129. package/src/adapters/self.test.ts +39 -1
  130. package/src/adapters/self.ts +20 -2
  131. package/src/adapters/workspaces.ts +1 -1
  132. package/src/cli/restore-resume.ts +1 -1
  133. package/src/cli/web/page.ts +2 -2
  134. package/src/client/about/AboutPanel.tsx +8 -1
  135. package/src/client/about/about-view.test.ts +1 -1
  136. package/src/client/about/about-view.ts +1 -1
  137. package/src/client/api.ts +1 -6
  138. package/src/client/chat/chat-entry-view.test.ts +1 -1
  139. package/src/client/chat/chat-slots.ts +1 -1
  140. package/src/client/chat/rollback-diff-tab.ts +1 -1
  141. package/src/client/client-types.ts +1 -1
  142. package/src/client/common/access-mode.ts +21 -0
  143. package/src/client/common/routes.ts +1 -5
  144. package/src/client/css-scale-guard.test.ts +1 -1
  145. package/src/client/home/HomePanel.tsx +34 -6
  146. package/src/client/library/ArtifactRow.tsx +14 -2
  147. package/src/client/library/LibraryPanel.tsx +44 -0
  148. package/src/client/locales/about.ts +6 -0
  149. package/src/client/locales/overview.ts +18 -2
  150. package/src/client/locales/sessions.ts +3 -0
  151. package/src/client/market/MyConfigsView.tsx +1 -1
  152. package/src/client/market/market-api.ts +2 -14
  153. package/src/client/market/market-locales.ts +1 -1
  154. package/src/client/market/market-view.ts +3 -3
  155. package/src/client/market/my-configs-api.ts +1 -1
  156. package/src/client/market/my-configs-view.ts +1 -1
  157. package/src/client/recovery/recovery-locales.test.ts +1 -1
  158. package/src/client/run-store.ts +1 -1
  159. package/src/client/sync/SyncSectionPickerDialog.tsx +0 -5
  160. package/src/client/sync/history-model.test.ts +28 -7
  161. package/src/client/sync/history-model.ts +6 -3
  162. package/src/client/sync/sync-locales.ts +10 -4
  163. package/src/client/sync/sync-view.ts +1 -1
  164. package/src/core/access-mode.ts +37 -0
  165. package/src/core/analyzer-cache.test.ts +1 -1
  166. package/src/core/backup.test.ts +45 -1
  167. package/src/core/backup.ts +25 -0
  168. package/src/core/disk-usage.test.ts +2 -0
  169. package/src/core/env-lock-lifecycle.ts +33 -3
  170. package/src/core/external-failure.test.ts +60 -0
  171. package/src/core/external-failure.ts +54 -0
  172. package/src/core/integrity-extra-entries.test.ts +1 -1
  173. package/src/core/local-plugin-host.test.ts +134 -0
  174. package/src/core/local-plugin-host.ts +122 -17
  175. package/src/core/local-plugin-pack.ts +39 -3
  176. package/src/core/mcp-connector-store.ts +26 -1
  177. package/src/core/messages-core.ts +94 -0
  178. package/src/core/messages.ts +6 -0
  179. package/src/core/model-tool-plans.test.ts +111 -0
  180. package/src/core/model-tool-plans.ts +170 -0
  181. package/src/core/model-tools.test.ts +212 -12
  182. package/src/core/model-tools.ts +710 -38
  183. package/src/core/phase3-host.ts +10 -2
  184. package/src/core/phase3-production-integration.test.ts +43 -0
  185. package/src/core/plugin-data-registry.ts +1 -1
  186. package/src/core/restore-plan-fingerprint.ts +19 -0
  187. package/src/core/restore-resume.ts +1 -1
  188. package/src/core/restore.ts +9 -1
  189. package/src/core/types.ts +12 -0
  190. package/src/foreign/claude-sessions.ts +3 -3
  191. package/src/foreign/registry.ts +1 -1
  192. package/src/foreign/types.ts +1 -1
  193. package/src/index.ts +96 -103
  194. package/src/market/git-file-writer.ts +1 -1
  195. package/src/market/github-repos.test.ts +1 -1
  196. package/src/market/github-repos.ts +1 -1
  197. package/src/market/market-config.ts +1 -1
  198. package/src/market/messages-market.ts +1 -1
  199. package/src/market/my-repo.test.ts +1 -1
  200. package/src/market/my-repo.ts +1 -1
  201. package/src/market/prepare.test.ts +1 -1
  202. package/src/market/prepare.ts +1 -1
  203. package/src/market/reader.ts +2 -2
  204. package/src/market/repo-url.ts +1 -1
  205. package/src/market/security.ts +2 -2
  206. package/src/market/star-cache.ts +1 -1
  207. package/src/market/types.ts +1 -1
  208. package/src/market/url.test.ts +1 -1
  209. package/src/market/url.ts +1 -1
  210. package/src/profiles/dsh-profile-copy-rollback.test.ts +1 -1
  211. package/src/routes/backup.ts +16 -9
  212. package/src/routes/index.ts +1 -1
  213. package/src/routes/kit.ts +71 -5
  214. package/src/routes/market.ts +2 -59
  215. package/src/routes/model-tools-deps.ts +56 -0
  216. package/src/routes/recovery.ts +5 -3
  217. package/src/routes/request-trust.ts +97 -0
  218. package/src/routes/route-support.ts +49 -36
  219. package/src/routes/snapshots.ts +4 -40
  220. package/src/routes/sync.ts +39 -27
  221. package/src/schema/index.ts +2 -2
  222. package/src/schema/manifest-schema.test.ts +2 -2
  223. package/src/schema/registry.test.ts +1 -1
  224. package/src/schema/section-registry.ts +9 -4
  225. package/src/security/redaction.test.ts +1 -1
  226. package/src/security/secret-scanner.test.ts +2 -2
  227. package/src/security/secret-scanner.ts +1 -1
  228. package/src/sync/apply-bundle.ts +104 -0
  229. package/src/sync/autosync-scheduler.test.ts +180 -6
  230. package/src/sync/autosync-scheduler.ts +132 -92
  231. package/src/sync/backup-scheduler.test.ts +11 -4
  232. package/src/sync/backup-scheduler.ts +5 -4
  233. package/src/sync/blob-store.ts +2 -2
  234. package/src/sync/git/git-transport.test.ts +62 -0
  235. package/src/sync/git/git-transport.ts +54 -3
  236. package/src/sync/merge.ts +29 -0
  237. package/src/sync/messages.ts +9 -2
  238. package/src/sync/s3/s3-transport.ts +1 -1
  239. package/src/sync/sync-engine.test.ts +238 -2
  240. package/src/sync/sync-engine.ts +25 -26
  241. package/src/sync/sync-preview-push.test.ts +2 -1
  242. package/src/sync/sync-scope-boot.ts +87 -0
  243. package/src/sync/sync-scope.test.ts +154 -0
  244. package/src/sync/sync-scope.ts +256 -0
  245. package/src/sync/sync-selection.test.ts +76 -2
  246. package/src/sync/sync-selection.ts +40 -13
  247. package/src/sync/transport.test.ts +21 -1
  248. package/src/sync/transport.ts +12 -0
  249. package/src/sync/webdav/webdav-delete-index-unreadable.test.ts +2 -2
  250. package/src/sync/webdav/webdav-transport.ts +1 -1
  251. package/src/sync/workspace-merge.test.ts +110 -0
  252. package/src/sync/workspace-merge.ts +180 -0
  253. package/src/ui/backup-schedule.test.ts +5 -0
  254. package/src/ui/backup-schedule.ts +21 -2
  255. package/src/ui/session-issue-labels.ts +1 -1
  256. package/src/ui/snapshots-view.test.ts +32 -0
  257. package/src/ui/snapshots-view.ts +34 -0
  258. package/src/utils/env-lock.test.ts +242 -9
  259. package/src/utils/env-lock.ts +247 -13
  260. package/src/utils/messages-utils.ts +17 -1
  261. package/src/utils/patch-yaml.ts +1 -1
  262. package/src/utils/zip.ts +1 -1
  263. package/src/client/CLIENT_DEPENDENCIES.md +0 -94
@@ -31,7 +31,7 @@ import path from 'node:path';
31
31
 
32
32
  import {
33
33
  FileSnapshotStore, PRE_RESTORE_KEEP_ATTEMPTS, PRE_RESTORE_KEEP_DAYS,
34
- createSnapshot, normalizeDshVersion, resolveFileTarget, verifySnapshot,
34
+ createSnapshot, normalizeDshVersion, normalizeOriginProfile, resolveFileTarget, verifySnapshot,
35
35
  } from './backup.ts';
36
36
  import type { PrunePlan } from './backup.ts';
37
37
  import { existsSync } from 'node:fs';
@@ -599,3 +599,47 @@ test('BK-05/④:反悔副本全部过期后不留空壳目录(快照已不
599
599
  assert.equal(existsSync(path.join(dir, first.id)), false, '快照没了 + 反悔副本也过期 ⇒ 不留空壳');
600
600
  });
601
601
 
602
+ /* ---------------- BK-06:来源档案(originProfile)标注 ----------------
603
+ * 插件数据目录 $DSH_HOME/dsh-config-manager 被**所有** DSH profile 共用,快照库因此混着别的档案拍的条目;
604
+ * 不标注来源用户就分不出哪条来自哪个档案。三条硬边界:必须可选、只在能证明时写、绝不写占位值。 */
605
+
606
+ test('BK-06/①:createSnapshot 记下拍快照的档案名(ctx.profile 有值 ⇒ 写入 originProfile)', async () => {
607
+ const store = new MemSnapshotStore();
608
+
609
+ const ctx = makeContext('win32', 'C:/home/.dsh', 'web');
610
+ await seedHostFiles(ctx);
611
+ const snap = await createSnapshot({ ctx, plan: emptyPlan(), sourceZip: 'unit.zip', store, adapters: [] });
612
+ assert.equal(snap.originProfile, 'web', '档案名要随快照落盘:不标注就分不出来源');
613
+ assert.equal(store.snapshots.get(snap.id)?.originProfile, 'web', 'store 落库的对象也要带该字段(不只是返回值)');
614
+
615
+ // 首尾空白按 trim 归一(宿主偶尔带空格;档案身份本身不含首尾空白)
616
+ const padded = makeContext('win32', 'C:/home/.dsh', ' Test1 ');
617
+ await seedHostFiles(padded);
618
+ const snap2 = await createSnapshot({ ctx: padded, plan: emptyPlan(), sourceZip: 'unit.zip', store, adapters: [] });
619
+ assert.equal(snap2.originProfile, 'Test1');
620
+ });
621
+
622
+ test('BK-06/②:来源档案取不到或不可信 ⇒ 不写 originProfile(绝不写 unknown 占位)', async () => {
623
+ const store = new MemSnapshotStore();
624
+ const profiles: Array<string | undefined> = [undefined, '', ' ', 'unknown', 'web/extra', '..', 'node_modules'];
625
+
626
+ for (const profile of profiles) {
627
+ const ctx = makeContext('win32', 'C:/home/.dsh', profile);
628
+ await seedHostFiles(ctx);
629
+ const snap = await createSnapshot({ ctx, plan: emptyPlan(), sourceZip: 'unit.zip', store, adapters: [] });
630
+ assert.equal(
631
+ 'originProfile' in snap, false,
632
+ `profile=${JSON.stringify(profile)} 时该字段必须**整个缺席**(写 'unknown' 会把「不知道」伪装成「确知」)`,
633
+ );
634
+ }
635
+ });
636
+
637
+ test('BK-06/③:normalizeOriginProfile 只放行真实档案名', () => {
638
+ assert.equal(normalizeOriginProfile('web'), 'web');
639
+ assert.equal(normalizeOriginProfile(' Test1 '), 'Test1');
640
+ assert.equal(normalizeOriginProfile('desktop'), 'desktop');
641
+ for (const bad of [undefined, null, 42, {}, [], '', ' ', 'unknown', 'a/b', 'a\\b', '.', '..', 'node_modules']) {
642
+ assert.equal(normalizeOriginProfile(bad), undefined, `${JSON.stringify(bad)} 不是可证明的档案名`);
643
+ }
644
+ });
645
+
@@ -274,6 +274,25 @@ export function normalizeDshVersion(value: unknown): string | undefined {
274
274
  return trimmed;
275
275
  }
276
276
 
277
+ /**
278
+ * 归一「快照来源档案」(originProfile)。
279
+ *
280
+ * 与 `normalizeDshVersion` 同一口径(非空、非 'unknown' 占位),但判据多一层:档案名要拿去和
281
+ * 当前档案比对、要在界面上按档案分组,所以还得是**合法档案名形态**。形态判据与
282
+ * `core/plugin-cli.ts` 的 `validateProfileName` 同源(拒绝路径分隔符与 '.'/'..'/'node_modules'),
283
+ * 差别只在失败处理:那边是拼 `profiles/<name>` 路径,非法必须抛错;这里只是标注**只过滤不抛错** ——
284
+ * 一个可疑档案名不该让快照落盘失败。
285
+ * 归一不到 → undefined(快照不写该字段,界面按「未标注」处理,绝不写 'unknown' 占位)。
286
+ */
287
+ export function normalizeOriginProfile(value: unknown): string | undefined {
288
+ if (typeof value !== 'string') return undefined;
289
+ const trimmed = value.trim();
290
+ if (trimmed === '' || trimmed === 'unknown') return undefined;
291
+ if (trimmed.includes('/') || trimmed.includes('\\')) return undefined;
292
+ if (trimmed === '.' || trimmed === '..' || trimmed === 'node_modules') return undefined;
293
+ return trimmed;
294
+ }
295
+
277
296
  export interface CreateSnapshotOptions {
278
297
  ctx: HostContext;
279
298
  plan: ImportPlan;
@@ -513,6 +532,10 @@ export async function createSnapshot(opts: CreateSnapshotOptions): Promise<Snaps
513
532
  ctx.log.warn(`快照登记插件清单失败: ${err instanceof Error ? err.message : String(err)}`);
514
533
  }
515
534
 
535
+ // 来源档案(originProfile):$DSH_HOME/dsh-config-manager 被所有 profile 共用,标出来源才分得清;
536
+ // 归一到「能证明的真实档案名」,取不到则不写该字段(绝不写 'unknown' 占位)。
537
+ const originProfile = normalizeOriginProfile(ctx.profile);
538
+
516
539
  const snapshot: Snapshot = {
517
540
  id: crypto.randomUUID(),
518
541
  createdAt: new Date().toISOString(),
@@ -523,6 +546,8 @@ export async function createSnapshot(opts: CreateSnapshotOptions): Promise<Snaps
523
546
  hostFileBackups,
524
547
  // F-4:拍快照时的本机 DSH 版本(归一到「能证明的真实版本」;解析不到则不写该字段)。
525
548
  dshVersion: normalizeDshVersion(ctx.dshVersion),
549
+ // 来源档案(同上:解析不到则不写该字段)。
550
+ ...(originProfile !== undefined ? { originProfile } : {}),
526
551
  // Phase 4:operation-bound binding(journal ↔ snapshot 双向一致)
527
552
  ...(opts.operationId !== undefined ? { operationId: opts.operationId } : {}),
528
553
  ...(opts.operationType !== undefined ? { operationType: opts.operationType } : {}),
@@ -382,6 +382,8 @@ test('GET /disk-usage:HTTP 报告如实包含回滚点库与遗留数据(两
382
382
  tmpDir: f.dirs.tmpDir,
383
383
  marketDir: path.join(f.root, 'market'),
384
384
  syncDir: f.dirs.syncDir,
385
+ // 体检看整棵 sync/(含 sync-profiles/<p>/):本用例的 fixture 两者同根
386
+ syncRootDir: f.dirs.syncDir,
385
387
  // 与生产同语义的「直通」包壳(本组 handler 只用它包裹写路由)
386
388
  withMutationGate: (_op: string, handler: unknown) => handler,
387
389
  };
@@ -5,16 +5,18 @@
5
5
  * ① 启动时回收「结构性可证」的 stale 残留锁(owner 确证死亡 / PID 复用),并把交给 SAFE MODE 判定的
6
6
  * 锁状态按回收结果修正;
7
7
  * ② 启动时清掉孤儿心跳 sidecar(已不是持有者、心跳也早已停更的垃圾);
8
- * ③ 进程退出时**同步**释放本实例持有的锁('exit' 里不能 await,所以必须同步 fs)。
8
+ * ③ 进程退出时**同步**释放本实例持有的锁('exit' 里不能 await,所以必须同步 fs);
9
+ * ④ 装配宿主用的 manager 实例,并把「心跳写失败 / 释放失败」接到日志(以前全静默)。
9
10
  *
10
11
  * 为什么只在分类 NORMAL 时做 ①②:RECOVERY_REQUIRED / NEEDS_ATTENTION 意味着有未决事务,此时删掉
11
12
  * ownership 等于替用户抹掉事故现场(journal↔ownership binding 也会失去对照证据)——那类必须显式恢复。
12
13
  * 为什么不碰 corrupt 残留与「心跳长过期」启发式:`reclaimProvableStaleLock` 只认结构性可证;
13
14
  * 其余留给显式回收(`--recover-stale-lock` / GUI 事故恢复),否则在拿不到 OS identity 的机器上会误删活锁。
14
15
  *
15
- * 真机成因与量化数据 → `docs/lessons/recovery-console.md`;规则 → `AGENTS.md`「备份 / 恢复 / 回滚点」。
16
+ * 真机成因与量化数据 → `docs/evidence/recovery-console.md`;规则 → `AGENTS.md`「备份 / 恢复 / 回滚点」。
16
17
  */
17
- import type { EnvironmentLockManager, LockState } from '../utils/env-lock.ts'
18
+ import { EnvironmentLockManager } from '../utils/env-lock.ts'
19
+ import type { LockState } from '../utils/env-lock.ts'
18
20
  import { mapLockStateForStartup } from './phase3-host.ts'
19
21
  import { utilsMsg } from '../utils/messages-utils.ts'
20
22
 
@@ -62,6 +64,34 @@ export async function reclaimStaleLockAtStartup(input: {
62
64
  return lockState
63
65
  }
64
66
 
67
+ /**
68
+ * 建宿主用的 mutation lock 实例,并给两类**以前全静默**的失败接上日志:
69
+ * 心跳写失败落到 noop、释放失败被调用方 `release().catch(() => {})` 吞掉 ——
70
+ * 真机表现就是「锁留在盘上、没有任何人知道为什么」,直到所有 destructive 操作恒被 423 挡住
71
+ * (2026-11-07 档案删除卡在「另一个任务正在运行」即此形状)。
72
+ * 这里只留痕,不做恢复动作:恢复一律走显式入口(事故恢复 / CLI),与 ①② 同一口径。
73
+ */
74
+ export function createHostMutationLock(input: {
75
+ dataDir: string
76
+ lockVersion: string
77
+ log: Pick<LockLifecycleLog, 'warn'>
78
+ }): EnvironmentLockManager {
79
+ const reason = (error: unknown): string => (error instanceof Error ? error.message : String(error))
80
+ return new EnvironmentLockManager({
81
+ dataDir: input.dataDir,
82
+ op: 'config-manager',
83
+ target: 'global-mutation',
84
+ lockVersion: input.lockVersion,
85
+ onHeartbeatWriteFailure: (err) => input.log.warn(utilsMsg('utils.envLock.heartbeatWriteFailed', { reason: reason(err) })),
86
+ onReleaseFailure: ({ err, quarantined }) =>
87
+ input.log.warn(
88
+ quarantined
89
+ ? utilsMsg('utils.envLock.releaseFailedQuarantined', { reason: reason(err) })
90
+ : utilsMsg('utils.envLock.releaseFailedStuck', { reason: reason(err) }),
91
+ ),
92
+ })
93
+ }
94
+
65
95
  /**
66
96
  * 生成退出释放钩子:只删**本实例 instanceId** 的 ownership 与心跳(与 `release()` 同一不变量),永不抛。
67
97
  * 调用方负责 `process.once('exit', fn)` 与 dispose 时摘钩。
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 本地可修外部失败标记(core/external-failure.ts)单测。
3
+ *
4
+ * 判据只有一条:失败是否只由**本机配置/凭据**决定、能在本机直接修好,且不会让磁盘停在半写状态。
5
+ * 只有打了标记的失败才允许 phase3 不升 durable SAFE MODE —— 其余一切保持 fail-closed,
6
+ * 所以「没有标记」必须是默认行为,且任何形状的输入都不能被误判成有标记。
7
+ */
8
+ import test from 'node:test';
9
+ import assert from 'node:assert/strict';
10
+
11
+ import {
12
+ isLocalOnlyExternalFailure,
13
+ localOnlyFailureReason,
14
+ markLocalOnlyExternalFailure,
15
+ } from './external-failure.ts';
16
+
17
+ test('默认无标记:普通错误/非对象输入一律不算 localOnly(fail-closed 的默认面)', () => {
18
+ assert.equal(isLocalOnlyExternalFailure(new Error('boom')), false);
19
+ assert.equal(localOnlyFailureReason(new Error('boom')), null);
20
+ for (const weird of [null, undefined, 0, '', 'fatal: unable to auto-detect email address', [], {}, () => {}]) {
21
+ assert.equal(isLocalOnlyExternalFailure(weird), false, '非错误输入不得被判为 localOnly: ' + String(weird));
22
+ assert.equal(localOnlyFailureReason(weird), null);
23
+ }
24
+ });
25
+
26
+ test('标记后原样返回同一对象(便于 throw mark(...)),并带上判据名', () => {
27
+ const err = new Error('fatal: empty ident name');
28
+ const marked = markLocalOnlyExternalFailure(err, 'git-identity');
29
+ assert.equal(marked, err, '必须返回同一实例(不得包裹)');
30
+ assert.equal(isLocalOnlyExternalFailure(err), true);
31
+ assert.equal(localOnlyFailureReason(err), 'git-identity');
32
+ });
33
+
34
+ test('标记不可枚举:JSON/日志序列化不会泄漏内部判据字段', () => {
35
+ const err = new Error('x');
36
+ markLocalOnlyExternalFailure(err, 'git-identity');
37
+ // 先展开再补 message(Error.message 不可枚举,不会覆盖;顺序反了 tsc 会报 TS2783)
38
+ const json = JSON.stringify({ ...err, message: err.message });
39
+ assert.equal(json.includes('git-identity'), false, '标记不得出现在可枚举/序列化字段里: ' + json);
40
+ });
41
+
42
+ test('重复标记以最后一次为准(后写覆盖先写,不抛错)', () => {
43
+ const err = new Error('x');
44
+ markLocalOnlyExternalFailure(err, 'first');
45
+ markLocalOnlyExternalFailure(err, 'second');
46
+ assert.equal(localOnlyFailureReason(err), 'second');
47
+ });
48
+
49
+ test('冻结/不可扩展的错误不会被标记(打不上就按「不可证明」保持 fail-closed)', () => {
50
+ const err = Object.freeze(new Error('frozen'));
51
+ const out = markLocalOnlyExternalFailure(err, 'git-identity');
52
+ assert.equal(out, err, '仍返回同一实例');
53
+ assert.equal(isLocalOnlyExternalFailure(err), false, '冻结对象打不上标记 → 不得误判为 localOnly');
54
+ });
55
+
56
+ test('空判据名不算标记(localOnlyFailureReason 只认非空字符串)', () => {
57
+ const err = new Error('x');
58
+ markLocalOnlyExternalFailure(err, '');
59
+ assert.equal(isLocalOnlyExternalFailure(err), false);
60
+ });
@@ -0,0 +1,54 @@
1
+ /**
2
+ * 「本地可修」外部失败的标记(零依赖模块,host 侧 phase3 与 sync 侧共用)。
3
+ *
4
+ * 背景(真机 issue):autosync 的 commit 失败只是因为**本机没配 git 身份**(exit 128),
5
+ * 但 runExternalIntent 的 catch 无条件把插件升进 durable SAFE MODE —— 一个由本机配置
6
+ * 直接修好的问题,被放大成「全部写入 423,直到手动解除阻断」。用户看到的还是
7
+ * 「环境锁被占用」,而 locks 目录其实是空的:排查方向被彻底带偏。
8
+ *
9
+ * 判据只有一条:失败是否**只由本机配置/凭据决定、且能在本机直接修好**,且它不会
10
+ * 使磁盘进入半写状态。这类失败收窄到该笔交易本身(journal → NEEDS_ATTENTION + 告警),
11
+ * 不升全局阻断。其余一切无法据此证明的失败保持 fail-closed(照旧升 SAFE MODE)。
12
+ *
13
+ * 为什么不用 Error 子类判定:错误要跨模块边界(sync/git → core/phase3)且可能被包装,
14
+ * 子类在 instanceof 上不可靠;这里用 Symbol.for 做**跨实例**标记,且 non-enumerable,
15
+ * 不会被 JSON/日志序列化污染。
16
+ */
17
+ const LOCAL_ONLY = Symbol.for('dsh-config-manager.externalFailure.localOnly')
18
+
19
+ interface LocalOnlyMark {
20
+ /** 判据名(进日志/诊断文本,不含敏感值)。 */
21
+ reason: string
22
+ }
23
+
24
+ /**
25
+ * 给一个错误打上「本地可修」标记并原样返回(便于 `throw markLocalOnlyExternalFailure(err, 'git-identity')`)。
26
+ * 同一个错误重复标记不报错(后写覆盖先写)。
27
+ */
28
+ export function markLocalOnlyExternalFailure<T extends Error>(err: T, reason: string): T {
29
+ try {
30
+ Object.defineProperty(err, LOCAL_ONLY, {
31
+ value: { reason } satisfies LocalOnlyMark,
32
+ enumerable: false,
33
+ configurable: true,
34
+ writable: true,
35
+ })
36
+ } catch {
37
+ /* 冻结对象/宿主级 Error 子类:打不上标记就按「不可证明」处理(保持 fail-closed) */
38
+ }
39
+ return err
40
+ }
41
+
42
+ /** 读取标记(无标记/非对象 → null)。 */
43
+ export function localOnlyFailureReason(err: unknown): string | null {
44
+ if (typeof err !== 'object' || err === null) return null
45
+ const mark = (err as { [k: symbol]: unknown })[LOCAL_ONLY]
46
+ if (typeof mark !== 'object' || mark === null) return null
47
+ const reason = (mark as { reason?: unknown }).reason
48
+ return typeof reason === 'string' && reason !== '' ? reason : null
49
+ }
50
+
51
+ /** 该失败是否只由本机可修的配置/凭据引起(true 才允许不升 SAFE MODE)。 */
52
+ export function isLocalOnlyExternalFailure(err: unknown): boolean {
53
+ return localOnlyFailureReason(err) !== null
54
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * SEC-05 回归:校验表只做「正向」校验 —— 表里登记的逐条比对,**表外的归档条目没人管**。
3
3
  * 文件类分区又是按归档名原样落盘的,于是「ZIP 有、checksums 没登记」的文件照样被写进目标目录,
4
- * 完整性声明形同虚设(审计 docs/research/dsh-config-manager-technical-audit.md SEC-05)。
4
+ * 完整性声明形同虚设(审计 docs/archive/2026-11-01-technical-audit.md SEC-05)。
5
5
  *
6
6
  * 修后口径:
7
7
  * - 会落盘的文件分区条目(Create/Update/Conflict)若不在 checksums 表内 ⇒ 计划项升级为 Error(逐条零写入),
@@ -0,0 +1,134 @@
1
+ /**
2
+ * local-plugin-host 单测:超限负缓存(2026-11-07 真机事故的治本项之一)。
3
+ *
4
+ * 事故:210MB 的本地插件每轮 npm pack 44.7s、结果每次都被体积上限丢弃;自动同步 60s 一轮 ⇒
5
+ * 每分钟白烧 45s,且整段时间持有 GLOBAL mutation 锁(用户删除档案恒 423)。
6
+ * 这里验证:源没变就不再重复打包、源变了会重打包、TTL 到期会重打包、关闭缓存时行为不变。
7
+ */
8
+ import { test } from 'node:test';
9
+ import assert from 'node:assert/strict';
10
+ import fsp from 'node:fs/promises';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+
14
+ import { createLocalPluginPackHook } from './local-plugin-host.ts';
15
+ import type { LocalPluginPackHook } from './local-plugin-host.ts';
16
+ import type { PackExec } from './local-plugin-pack.ts';
17
+
18
+ const TARBALL = 'local-pkg-0.1.0.tgz';
19
+
20
+ interface Fixture {
21
+ hook: LocalPluginPackHook;
22
+ calls: () => number;
23
+ sourceDir: string;
24
+ plugins: { name: string; version: string; spec?: string }[];
25
+ }
26
+
27
+ /** 造一个本地源插件目录 + 假 npm pack(把指定字节数的 tgz 写进 --pack-destination)。 */
28
+ async function fixture(t: { after: (fn: () => Promise<void>) => void }, opts: {
29
+ tarballBytes?: number;
30
+ oversizeTtlMs?: number;
31
+ maxTarballBytes?: number;
32
+ } = {}): Promise<Fixture> {
33
+ const root = await fsp.mkdtemp(path.join(os.tmpdir(), 'dshcm-packhost-'));
34
+ t.after(async () => { await fsp.rm(root, { recursive: true, force: true }); });
35
+ const homeDir = path.join(root, 'home');
36
+ const dataDir = path.join(root, 'data');
37
+ const sourceDir = path.join(root, 'local-pkg');
38
+ await fsp.mkdir(sourceDir, { recursive: true });
39
+ await fsp.writeFile(path.join(sourceDir, 'package.json'), JSON.stringify({ name: 'local-pkg', version: '0.1.0' }));
40
+
41
+ let calls = 0;
42
+ const tarballBytes = opts.tarballBytes ?? 4096;
43
+ const exec: PackExec = async (_file, args) => {
44
+ calls += 1;
45
+ const idx = args.indexOf('--pack-destination');
46
+ const packDir = args[idx + 1] as string;
47
+ await fsp.writeFile(path.join(packDir, TARBALL), Buffer.alloc(tarballBytes));
48
+ return { stdout: TARBALL + '\n', stderr: '', code: 0 };
49
+ };
50
+
51
+ const hook = createLocalPluginPackHook({
52
+ homeDir,
53
+ dataDir,
54
+ exec,
55
+ maxTarballBytes: opts.maxTarballBytes ?? 1024,
56
+ ...(opts.oversizeTtlMs === undefined ? {} : { oversizeTtlMs: opts.oversizeTtlMs }),
57
+ });
58
+ return {
59
+ hook,
60
+ calls: () => calls,
61
+ sourceDir,
62
+ plugins: [{ name: 'local-pkg', version: '0.1.0', spec: 'file:' + sourceDir }],
63
+ };
64
+ }
65
+
66
+ const ctx = { profile: 'web', profileDir: undefined } as const;
67
+
68
+ test('超限拒绝:首次打包 → warnings 有超限文案、oversize 带出源路径(供负缓存记账)', async (t) => {
69
+ const fx = await fixture(t);
70
+ const res = await fx.hook(fx.plugins, ctx);
71
+ assert.equal(fx.calls(), 1);
72
+ assert.equal(res.packed.length, 0, '超限的 tarball 不得进备份');
73
+ assert.equal(res.oversize.length, 1);
74
+ assert.equal(res.oversize[0]?.source, 'dir');
75
+ assert.equal(res.oversize[0]?.sourcePath, fx.sourceDir);
76
+ assert.equal(res.oversize[0]?.size, 4096);
77
+ assert.equal(res.warnings.length, 1);
78
+ });
79
+
80
+ test('超限负缓存:源没变 → 第二轮不再 npm pack,但告警照旧(调用方看不出区别)', async (t) => {
81
+ const fx = await fixture(t);
82
+ const first = await fx.hook(fx.plugins, ctx);
83
+ const second = await fx.hook(fx.plugins, ctx);
84
+ assert.equal(fx.calls(), 1, '第二次必须走缓存,不再白跑 npm pack');
85
+ assert.equal(second.packed.length, 0, '缓存命中同样不得产出 tarball(否则会带一个超限的大包)');
86
+ assert.deepEqual(second.warnings, first.warnings, '缓存命中的告警与实测超限逐字一致');
87
+ assert.equal(second.oversize.length, 1, '缓存命中也要原样回出超限项:调用方/界面不区分「刚发现」与「上轮已记」');
88
+ assert.deepEqual(second.oversize, first.oversize, '超限项字段与首次发现逐字一致');
89
+ });
90
+
91
+ test('超限负缓存:源变了(package.json mtime 变化)→ 重新打包', async (t) => {
92
+ const fx = await fixture(t);
93
+ await fx.hook(fx.plugins, ctx);
94
+ assert.equal(fx.calls(), 1);
95
+ const pkg = path.join(fx.sourceDir, 'package.json');
96
+ const future = new Date(Date.now() + 5000);
97
+ await fsp.utimes(pkg, future, future);
98
+ await fx.hook(fx.plugins, ctx);
99
+ assert.equal(fx.calls(), 2, '指纹变了必须重新打包(不能长期静默不备份)');
100
+ });
101
+
102
+ test('超限负缓存:TTL 到期 → 重新打包', async (t) => {
103
+ const fx = await fixture(t, { oversizeTtlMs: 5 });
104
+ await fx.hook(fx.plugins, ctx);
105
+ assert.equal(fx.calls(), 1);
106
+ await new Promise((r) => setTimeout(r, 20));
107
+ await fx.hook(fx.plugins, ctx);
108
+ assert.equal(fx.calls(), 2, 'TTL 到期必须重新实测,不能永久跳过');
109
+ });
110
+
111
+ test('oversizeTtlMs=0:关闭缓存,两轮都真打(测试与排障用)', async (t) => {
112
+ const fx = await fixture(t, { oversizeTtlMs: 0 });
113
+ await fx.hook(fx.plugins, ctx);
114
+ await fx.hook(fx.plugins, ctx);
115
+ assert.equal(fx.calls(), 2);
116
+ });
117
+
118
+ test('未超限:正常产出 packed,不进负缓存(两轮都打包)', async (t) => {
119
+ const fx = await fixture(t, { tarballBytes: 256, maxTarballBytes: 1024 });
120
+ const first = await fx.hook(fx.plugins, ctx);
121
+ assert.equal(first.packed.length, 1);
122
+ assert.equal(first.oversize.length, 0);
123
+ assert.equal(first.warnings.length, 0);
124
+ await fx.hook(fx.plugins, ctx);
125
+ assert.equal(fx.calls(), 2);
126
+ });
127
+
128
+ test('无本地源插件:零 spawn、零目录创建', async (t) => {
129
+ const fx = await fixture(t);
130
+ const res = await fx.hook([{ name: 'x', version: '1.0.0', spec: '^1.0.0' }], ctx);
131
+ assert.equal(fx.calls(), 0);
132
+ assert.deepEqual(res.warnings, []);
133
+ assert.deepEqual(res.oversize, []);
134
+ });
@@ -11,9 +11,9 @@ import fsp from 'node:fs/promises';
11
11
  import path from 'node:path';
12
12
  import { spawn } from 'node:child_process';
13
13
 
14
- import { packLocalPlugins, parsePackOutput } from './local-plugin-pack.ts';
14
+ import { packLocalPlugins, parsePackOutput, resolveLocalPluginPath } from './local-plugin-pack.ts';
15
15
  import { quoteCmdArg } from './plugin-cli.ts';
16
- import type { PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
16
+ import type { OversizeLocalPlugin, PackExec, PackExecResult, PackLocalPluginsResult } from './local-plugin-pack.ts';
17
17
  import type { HostContext } from './types.ts';
18
18
  import { engineMsg } from './messages-core.ts';
19
19
 
@@ -97,6 +97,15 @@ export interface LocalPluginPackHookOptions {
97
97
  dataDir: string;
98
98
  /** 覆盖 exec(测试注入) */
99
99
  exec?: PackExec;
100
+ /**
101
+ * 超限负缓存 TTL(缺省 OVERSIZE_NEGATIVE_TTL_MS;**0 = 关闭缓存**,测试用)。
102
+ * 命中条件 = 源指纹未变 且 距上次实测超限不足 TTL。
103
+ */
104
+ oversizeTtlMs?: number;
105
+ /** 源指纹(测试注入;缺省见 defaultSourceFingerprint) */
106
+ sourceFingerprint?: (absPath: string) => Promise<string | null>;
107
+ /** tarball 体积上限(缺省 MAX_LOCAL_TARBALL_BYTES;测试用小值验证超限负缓存) */
108
+ maxTarballBytes?: number;
100
109
  }
101
110
 
102
111
  /**
@@ -106,14 +115,98 @@ export interface LocalPluginPackHookOptions {
106
115
  * 单次导出内建一个 `<dataDir>/tmp/local-pack-<random>` 目录,导出结束(无论成败)删除,
107
116
  * 避免 tarball 残留在用户磁盘上。
108
117
  */
118
+ /** 超限负缓存 TTL:命中后这段时间内不再为同一源重复打包。
119
+ *
120
+ * 为什么需要(2026-11-07 真机事故):单个 210MB 的本地插件一次 npm pack 实测 44.7s,而结果每次都被
121
+ * 体积上限丢弃(core/local-plugin-pack.ts 的 maxTarballBytes)。自动同步 60s 一轮 ⇒ 每分钟白烧 45s CPU/磁盘,
122
+ * 且整段时间持有 GLOBAL mutation 锁(用户删除档案/导入等操作恒 423「另一个任务正在运行」)。
123
+ * 取 30 分钟而不是永久:源改动可能只落在 lib/ 上、package.json 指纹不变,重打包的代价能承受,
124
+ * 「长期静默不备份」承受不了。 */
125
+ const OVERSIZE_NEGATIVE_TTL_MS = 30 * 60 * 1000;
126
+
127
+ /** 源指纹(缺省实现):归档看自身 size/mtime;目录看「目录 mtime + package.json size/mtime」。
128
+ *
129
+ * 刻意不做整树遍历:真机实测 eac-design-world 包 8810 文件走一遍 3.6s、本仓库 51502 文件 14.9s,
130
+ * 比它要省的 45s 只是小一个量级,且每轮都要付 —— 负缓存的意义就没了。 */
131
+ async function defaultSourceFingerprint(absPath: string): Promise<string | null> {
132
+ try {
133
+ const st = await fsp.stat(absPath);
134
+ if (st.isFile()) return 'file:' + st.size + ':' + Math.trunc(st.mtimeMs);
135
+ if (!st.isDirectory()) return null;
136
+ const pkg = await fsp.stat(path.join(absPath, 'package.json')).catch(() => null);
137
+ const pkgKey = pkg === null ? '-' : pkg.size + ':' + Math.trunc(pkg.mtimeMs);
138
+ return 'dir:' + Math.trunc(st.mtimeMs) + ':' + pkgKey;
139
+ } catch {
140
+ return null;
141
+ }
142
+ }
109
143
  export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): LocalPluginPackHook {
110
144
  const exec = opts.exec ?? defaultExec;
145
+ const oversizeTtlMs = opts.oversizeTtlMs ?? OVERSIZE_NEGATIVE_TTL_MS;
146
+ const fingerprintOf = opts.sourceFingerprint ?? defaultSourceFingerprint;
147
+ /**
148
+ * 超限负缓存:解析后的源路径 → 上次实测超限的结论。
149
+ *
150
+ * 存**结论**而不是 tarball:超限的 tarball 本来就不会进备份,缓存它没有意义;
151
+ * 要省的只是那几十秒的 npm pack。键用绝对源路径(同一插件在 link:/file: 两种写法下同键)。
152
+ */
153
+ const oversizeCache = new Map<string, { fingerprint: string; at: number; oversize: OversizeLocalPlugin }>();
154
+
155
+ const hasLocalSpec = (p: { spec?: string }): boolean =>
156
+ p.spec !== undefined && /^\s*(link|file):/i.test(p.spec);
111
157
 
112
158
  return async (plugins, ctx) => {
113
- // 无本地源插件时零开销返回(不建目录、不 spawn)——由 packLocalPlugins 内部短路,
114
- // 这里先做便宜的判定避免无谓的 mkdtemp。
115
- if (!plugins.some((p) => p.spec !== undefined && /^\s*(link|file):/i.test(p.spec))) {
116
- return { packed: [], rewritten: {}, warnings: [] };
159
+ // 无本地源插件时零开销返回(不建目录、不 spawn)。
160
+ if (!plugins.some(hasLocalSpec)) {
161
+ return { packed: [], rewritten: {}, warnings: [], oversize: [] };
162
+ }
163
+
164
+ // profile 目录:**优先用 HostContext.profileDir**(DSH 的档案目录不保证是
165
+ // `<home>/profiles/<name>` 的默认布局,拼接出来的路径可能根本不存在);
166
+ // 宿主没给时回退到按 profile 名拼接,再回退到 web —— 与仓库既有约定一致。
167
+ // 提到建临时目录之前:负缓存要按解析后的源路径判定,不为判定先建目录。
168
+ const profile = ctx.profile !== undefined && ctx.profile !== '' ? ctx.profile : 'web';
169
+ const profileDir = ctx.profileDir !== undefined && ctx.profileDir !== ''
170
+ ? ctx.profileDir
171
+ : path.join(opts.homeDir, 'profiles', profile);
172
+
173
+ // —— 超限负缓存:源没变就别再白跑一遍 npm pack ——
174
+ const kept: { name: string; version: string; spec?: string }[] = [];
175
+ const cacheWarnings: string[] = [];
176
+ // 缓存命中的超限项也要原样回给调用方:与首次发现同形,界面不必区分「这轮刚发现」还是「上轮已记」
177
+ const cacheOversize: OversizeLocalPlugin[] = [];
178
+ if (oversizeTtlMs > 0 && oversizeCache.size > 0) {
179
+ const now = Date.now();
180
+ for (const p of plugins) {
181
+ const spec = p.spec;
182
+ if (spec === undefined || !hasLocalSpec(p)) {
183
+ kept.push(p);
184
+ continue;
185
+ }
186
+ const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
187
+ const hit = oversizeCache.get(abs);
188
+ if (hit === undefined || now - hit.at >= oversizeTtlMs) {
189
+ if (hit !== undefined) oversizeCache.delete(abs);
190
+ kept.push(p);
191
+ continue;
192
+ }
193
+ const fp = await fingerprintOf(abs).catch(() => null);
194
+ if (fp === null || fp !== hit.fingerprint) {
195
+ oversizeCache.delete(abs);
196
+ kept.push(p);
197
+ continue;
198
+ }
199
+ // 命中:与「打包后发现超限」用同一条文案,用户与调用方都看不出区别
200
+ cacheWarnings.push(
201
+ engineMsg('core.localPluginPack.tarballTooLarge', { name: p.name, size: hit.oversize.size, max: hit.oversize.maxBytes }),
202
+ );
203
+ cacheOversize.push(hit.oversize);
204
+ }
205
+ } else {
206
+ kept.push(...plugins);
207
+ }
208
+ if (!kept.some(hasLocalSpec)) {
209
+ return { packed: [], rewritten: {}, warnings: cacheWarnings, oversize: cacheOversize };
117
210
  }
118
211
 
119
212
  const tmpRoot = path.join(opts.dataDir, 'tmp');
@@ -125,20 +218,17 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
125
218
  return {
126
219
  packed: [],
127
220
  rewritten: {},
128
- warnings: [engineMsg('core.localPluginHost.tmpDirCreateFailed', { reason: err instanceof Error ? err.message : String(err) })],
221
+ warnings: [
222
+ ...cacheWarnings,
223
+ engineMsg('core.localPluginHost.tmpDirCreateFailed', { reason: err instanceof Error ? err.message : String(err) }),
224
+ ],
225
+ oversize: cacheOversize,
129
226
  };
130
227
  }
131
228
 
132
229
  try {
133
- // profile 目录:**优先用 HostContext.profileDir**(DSH 的档案目录不保证是
134
- // `<home>/profiles/<name>` 的默认布局,拼接出来的路径可能根本不存在);
135
- // 宿主没给时回退到按 profile 名拼接,再回退到 web —— 与仓库既有约定一致。
136
- const profile = ctx.profile !== undefined && ctx.profile !== '' ? ctx.profile : 'web';
137
- const profileDir = ctx.profileDir !== undefined && ctx.profileDir !== ''
138
- ? ctx.profileDir
139
- : path.join(opts.homeDir, 'profiles', profile);
140
- return await packLocalPlugins({
141
- plugins: plugins.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
230
+ const result = await packLocalPlugins({
231
+ plugins: kept.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
142
232
  homeDir: opts.homeDir,
143
233
  profileDir,
144
234
  packDir,
@@ -155,13 +245,28 @@ export function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): Loc
155
245
  }
156
246
  },
157
247
  timeoutMs: PACK_TIMEOUT_MS,
248
+ ...(opts.maxTarballBytes === undefined ? {} : { maxTarballBytes: opts.maxTarballBytes }),
158
249
  });
250
+
251
+ // 本轮新发现的超限项记账:下一轮同源同指纹就直接走缓存,不再 npm pack。
252
+ if (oversizeTtlMs > 0) {
253
+ for (const o of result.oversize) {
254
+ const fp = await fingerprintOf(o.sourcePath).catch(() => null);
255
+ if (fp !== null) {
256
+ oversizeCache.set(o.sourcePath, { fingerprint: fp, at: Date.now(), oversize: o });
257
+ }
258
+ }
259
+ }
260
+ return {
261
+ ...result,
262
+ oversize: [...cacheOversize, ...result.oversize],
263
+ warnings: [...cacheWarnings, ...result.warnings],
264
+ };
159
265
  } finally {
160
266
  // 无论成败都清掉临时目录:tarball 字节已读进内存并随备份走,无需留盘
161
267
  await fsp.rm(packDir, { recursive: true, force: true }).catch(() => undefined);
162
268
  }
163
269
  };
164
270
  }
165
-
166
271
  /** 供其他模块复用(避免重复实现 npm 输出解析) */
167
272
  export { parsePackOutput };