dsh-config-manager 0.6.0 → 0.7.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 (49) hide show
  1. package/lib/client.d.ts +5 -0
  2. package/lib/client.js +605 -566
  3. package/lib/core/local-plugin-host.d.ts +9 -0
  4. package/lib/core/local-plugin-host.js +174 -1
  5. package/lib/core/messages.d.ts +3 -0
  6. package/lib/core/messages.js +8 -0
  7. package/lib/core/run-registry.d.ts +10 -0
  8. package/lib/core/run-registry.js +17 -0
  9. package/lib/index.d.ts +3 -2
  10. package/lib/index.js +8 -6
  11. package/lib/routes/import.js +6 -1
  12. package/lib/routes/route-support.d.ts +2 -1
  13. package/lib/routes/route-support.js +8 -3
  14. package/lib/routes/sync.js +5 -2
  15. package/lib/sync/autosync-config.d.ts +9 -1
  16. package/lib/sync/autosync-config.js +10 -2
  17. package/lib/sync/autosync-scheduler.js +18 -6
  18. package/lib/sync/git/git-transport.d.ts +31 -1
  19. package/lib/sync/git/git-transport.js +119 -23
  20. package/lib/sync/sync-config.d.ts +34 -3
  21. package/lib/sync/sync-config.js +38 -5
  22. package/lib/ui/sync-settings-view.d.ts +4 -0
  23. package/lib/ui/sync-settings-view.js +3 -0
  24. package/package.json +1 -1
  25. package/src/client/run-store.test.ts +1 -1
  26. package/src/client/run-store.ts +5 -0
  27. package/src/client/sync/ChannelConfigDialog.tsx +15 -1
  28. package/src/client/sync/SyncPanel.tsx +6 -0
  29. package/src/client/sync/sync-api.ts +2 -0
  30. package/src/client/sync/sync-locales.ts +6 -0
  31. package/src/core/local-plugin-host.test.ts +31 -2
  32. package/src/core/local-plugin-host.ts +175 -2
  33. package/src/core/messages.ts +8 -0
  34. package/src/core/run-registry-runs.test.ts +26 -1
  35. package/src/core/run-registry.ts +18 -0
  36. package/src/index.sync.test.ts +27 -0
  37. package/src/index.ts +10 -8
  38. package/src/routes/import.ts +6 -1
  39. package/src/routes/route-support.ts +7 -3
  40. package/src/routes/sync.ts +5 -2
  41. package/src/sync/autosync-config.ts +10 -2
  42. package/src/sync/autosync-scheduler.test.ts +61 -1
  43. package/src/sync/autosync-scheduler.ts +17 -5
  44. package/src/sync/git/git-transport.test.ts +117 -0
  45. package/src/sync/git/git-transport.ts +131 -23
  46. package/src/sync/sync-config.test.ts +59 -1
  47. package/src/sync/sync-config.ts +51 -5
  48. package/src/ui/sync-settings-view.test.ts +1 -0
  49. package/src/ui/sync-settings-view.ts +7 -0
@@ -31,6 +31,15 @@ export interface LocalPluginPackHookOptions {
31
31
  sourceFingerprint?: (absPath: string) => Promise<string | null>;
32
32
  /** tarball 体积上限(缺省 MAX_LOCAL_TARBALL_BYTES;测试用小值验证超限负缓存) */
33
33
  maxTarballBytes?: number;
34
+ /**
35
+ * 内容缓存上限(字节;缺省 PACKED_CACHE_MAX_BYTES,**0 = 关闭**)。
36
+ * 命中判据 = 源目录的**内容指纹**(递归 rel/size/mtime)未变:命中即复用上次的 tarball 字节,跳过 npm pack。
37
+ */
38
+ packedCacheMaxBytes?: number;
39
+ /** 内容缓存条目上限(缺省 PACKED_CACHE_MAX_ENTRIES)。 */
40
+ packedCacheMaxEntries?: number;
41
+ /** 内容指纹(测试注入;缺省 deepSourceFingerprint)。 */
42
+ contentFingerprint?: (absPath: string) => Promise<string | null>;
34
43
  }
35
44
  export declare function createLocalPluginPackHook(opts: LocalPluginPackHookOptions): LocalPluginPackHook;
36
45
  /** 供其他模块复用(避免重复实现 npm 输出解析) */
@@ -9,6 +9,7 @@
9
9
  */
10
10
  import fsp from 'node:fs/promises';
11
11
  import path from 'node:path';
12
+ import { createHash } from 'node:crypto';
12
13
  import { spawn } from 'node:child_process';
13
14
  import { packLocalPlugins, parsePackOutput, resolveLocalPluginPath } from './local-plugin-pack.js';
14
15
  import { quoteCmdArg } from './plugin-cli.js';
@@ -102,6 +103,74 @@ async function defaultSourceFingerprint(absPath) {
102
103
  return null;
103
104
  }
104
105
  }
106
+ /** 内容缓存上限(缺省 128 MiB):只缓存真的打过的 tarball 字节。 */
107
+ const PACKED_CACHE_MAX_BYTES = 128 * 1024 * 1024;
108
+ /** 内容缓存条目上限(防「一堆小插件」把 Map 撑大)。 */
109
+ const PACKED_CACHE_MAX_ENTRIES = 64;
110
+ /** 内容指纹的遍历上限:超过就不缓存(宁可不省,也不拿可能过期的字节去备份)。 */
111
+ const CONTENT_FP_MAX_ENTRIES = 20_000;
112
+ /**
113
+ * 内容指纹(**正缓存**用):递归列出目录内每个文件的相对路径 + 字节数 + mtime。
114
+ *
115
+ * 为什么不用上面的 defaultSourceFingerprint:它只取「目录 mtime + package.json」,
116
+ * 在 lib/ 里改一行**不会**改目录 mtime —— 拿它做正缓存,会把旧 tarball 当成当前内容上传进备份。
117
+ * 负缓存能容忍这种粗糙(最坏是少备份一次、30 分钟内重试),正缓存不能容忍(最坏是备份里是旧代码)。
118
+ *
119
+ * 成本实测(2026-11-07,真机):8810 文件 3.6 s、51502 文件 14.9 s —— 仍比一次 210 MB 插件的
120
+ * 44.7 s npm pack 便宜一个量级;超过 CONTENT_FP_MAX_ENTRIES 或遇到链接/特殊文件一律返回 null
121
+ * (调用方据此**不缓存**,直接照常打包)。
122
+ */
123
+ async function deepSourceFingerprint(absPath) {
124
+ let st;
125
+ try {
126
+ st = await fsp.stat(absPath);
127
+ }
128
+ catch {
129
+ return null;
130
+ }
131
+ if (st.isFile())
132
+ return 'file:' + st.size + ':' + Math.trunc(st.mtimeMs);
133
+ if (!st.isDirectory())
134
+ return null;
135
+ const hash = createHash('sha256');
136
+ let entries = 0;
137
+ const walk = async (dir, rel) => {
138
+ let list;
139
+ try {
140
+ list = await fsp.readdir(dir, { withFileTypes: true });
141
+ }
142
+ catch {
143
+ return false;
144
+ }
145
+ list.sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
146
+ for (const entry of list) {
147
+ // 与 npm pack 同口径:node_modules 不进产物;.git 不参与内容身份
148
+ if (entry.name === 'node_modules' || entry.name === '.git')
149
+ continue;
150
+ const abs = path.join(dir, entry.name);
151
+ const relPath = rel === '' ? entry.name : rel + '/' + entry.name;
152
+ if (entry.isDirectory()) {
153
+ if (!(await walk(abs, relPath)))
154
+ return false;
155
+ continue;
156
+ }
157
+ if (!entry.isFile())
158
+ return false; // 链接 / 设备文件:不猜它指向什么,放弃缓存
159
+ const s = await fsp.stat(abs).catch(() => null);
160
+ if (s === null)
161
+ return false;
162
+ entries += 1;
163
+ if (entries > CONTENT_FP_MAX_ENTRIES)
164
+ return false;
165
+ hash.update(relPath + '\u0000' + s.size + '\u0000' + Math.trunc(s.mtimeMs) + '\n');
166
+ }
167
+ return true;
168
+ };
169
+ if (!(await walk(absPath, '')))
170
+ return null;
171
+ hash.update('entries:' + entries);
172
+ return 'deep:' + hash.digest('hex');
173
+ }
105
174
  export function createLocalPluginPackHook(opts) {
106
175
  const exec = opts.exec ?? defaultExec;
107
176
  const oversizeTtlMs = opts.oversizeTtlMs ?? OVERSIZE_NEGATIVE_TTL_MS;
@@ -113,6 +182,42 @@ export function createLocalPluginPackHook(opts) {
113
182
  * 要省的只是那几十秒的 npm pack。键用绝对源路径(同一插件在 link:/file: 两种写法下同键)。
114
183
  */
115
184
  const oversizeCache = new Map();
185
+ /**
186
+ * 内容缓存(正缓存):解析后的源路径 → 上次打出的 tarball 字节 + 当时的内容指纹。
187
+ *
188
+ * 与超限负缓存的区别:负缓存存「结论」,这里存**产物本身**,命中即跳过 npm pack。
189
+ * 命中判据是 deepSourceFingerprint(文件级 rel/size/mtime),不是目录 mtime —— 见该函数注释。
190
+ * 上限双保险:总字节数 + 条目数,超出按「最久未用」淘汰;单条超过上限则根本不入缓存。
191
+ */
192
+ const packedMaxBytes = opts.packedCacheMaxBytes ?? PACKED_CACHE_MAX_BYTES;
193
+ const packedMaxEntries = opts.packedCacheMaxEntries ?? PACKED_CACHE_MAX_ENTRIES;
194
+ const contentFp = opts.contentFingerprint ?? deepSourceFingerprint;
195
+ const packedCache = new Map();
196
+ let packedCacheBytes = 0;
197
+ const evictPacked = () => {
198
+ while (packedCache.size > packedMaxEntries || packedCacheBytes > packedMaxBytes) {
199
+ let oldestKey = null;
200
+ let oldestAt = Number.POSITIVE_INFINITY;
201
+ for (const [key, value] of packedCache) {
202
+ if (value.usedAt < oldestAt) {
203
+ oldestAt = value.usedAt;
204
+ oldestKey = key;
205
+ }
206
+ }
207
+ if (oldestKey === null)
208
+ return;
209
+ const removed = packedCache.get(oldestKey);
210
+ if (removed !== undefined)
211
+ packedCacheBytes -= removed.bytes;
212
+ packedCache.delete(oldestKey);
213
+ }
214
+ };
215
+ /** 按入参顺序输出打包结果(缓存命中与本轮打包混在一起时,保持确定性顺序)。 */
216
+ const orderPacked = (input, packed) => {
217
+ const byName = new Map(packed.map((p) => [p.packageName, p]));
218
+ return input.map((p) => byName.get(p.name)).filter((p) => p !== undefined);
219
+ };
220
+ const rewrittenOf = (packed) => Object.fromEntries(packed.map((p) => [p.packageName, p.rewrittenSpec]));
116
221
  const hasLocalSpec = (p) => p.spec !== undefined && /^\s*(link|file):/i.test(p.spec);
117
222
  return async (plugins, ctx) => {
118
223
  // 无本地源插件时零开销返回(不建目录、不 spawn)。
@@ -165,6 +270,45 @@ export function createLocalPluginPackHook(opts) {
165
270
  if (!kept.some(hasLocalSpec)) {
166
271
  return { packed: [], rewritten: {}, warnings: cacheWarnings, oversize: cacheOversize };
167
272
  }
273
+ // —— 内容缓存命中分流:源内容没变的那几个直接复用上次的 tarball,其余才真的打包 ——
274
+ const hitPacked = [];
275
+ const toPack = [];
276
+ if (packedMaxBytes > 0) {
277
+ for (const p of kept) {
278
+ const spec = p.spec;
279
+ if (spec === undefined || !hasLocalSpec(p)) {
280
+ toPack.push(p);
281
+ continue;
282
+ }
283
+ const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
284
+ const hit = packedCache.get(abs);
285
+ if (hit === undefined) {
286
+ toPack.push(p);
287
+ continue;
288
+ }
289
+ const fp = await contentFp(abs).catch(() => null);
290
+ if (fp === null || fp !== hit.fingerprint) {
291
+ packedCacheBytes -= hit.bytes;
292
+ packedCache.delete(abs);
293
+ toPack.push(p);
294
+ continue;
295
+ }
296
+ hit.usedAt = Date.now();
297
+ hitPacked.push(hit.entry);
298
+ }
299
+ }
300
+ else {
301
+ toPack.push(...kept);
302
+ }
303
+ if (!toPack.some(hasLocalSpec)) {
304
+ // 全部命中:不建临时目录、不 spawn 一次 npm。
305
+ return {
306
+ packed: orderPacked(plugins, hitPacked),
307
+ rewritten: rewrittenOf(hitPacked),
308
+ warnings: cacheWarnings,
309
+ oversize: cacheOversize,
310
+ };
311
+ }
168
312
  const tmpRoot = path.join(opts.dataDir, 'tmp');
169
313
  let packDir;
170
314
  try {
@@ -183,8 +327,13 @@ export function createLocalPluginPackHook(opts) {
183
327
  };
184
328
  }
185
329
  try {
330
+ const specOfName = new Map();
331
+ for (const p of toPack) {
332
+ if (p.spec !== undefined && hasLocalSpec(p))
333
+ specOfName.set(p.name, p.spec);
334
+ }
186
335
  const result = await packLocalPlugins({
187
- plugins: kept.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
336
+ plugins: toPack.map((p) => ({ name: p.name, version: p.version, spec: p.spec })),
188
337
  homeDir: opts.homeDir,
189
338
  profileDir,
190
339
  packDir,
@@ -213,8 +362,32 @@ export function createLocalPluginPackHook(opts) {
213
362
  }
214
363
  }
215
364
  }
365
+ // 内容缓存记账:本轮真打出来的 tarball 按「源内容指纹」入缓存;超限/算不出指纹的跳过(不猜)。
366
+ if (packedMaxBytes > 0) {
367
+ for (const entry of result.packed) {
368
+ const spec = specOfName.get(entry.packageName);
369
+ if (spec === undefined)
370
+ continue;
371
+ const bytes = entry.data.byteLength;
372
+ if (bytes > packedMaxBytes)
373
+ continue;
374
+ const abs = resolveLocalPluginPath(spec, { homeDir: opts.homeDir, profileDir });
375
+ const fp = await contentFp(abs).catch(() => null);
376
+ if (fp === null)
377
+ continue;
378
+ const prev = packedCache.get(abs);
379
+ if (prev !== undefined)
380
+ packedCacheBytes -= prev.bytes;
381
+ packedCache.set(abs, { fingerprint: fp, entry, bytes, usedAt: Date.now() });
382
+ packedCacheBytes += bytes;
383
+ }
384
+ evictPacked();
385
+ }
386
+ const allPacked = [...hitPacked, ...result.packed];
216
387
  return {
217
388
  ...result,
389
+ packed: orderPacked(plugins, allPacked),
390
+ rewritten: { ...result.rewritten, ...rewrittenOf(hitPacked) },
218
391
  oversize: [...cacheOversize, ...result.oversize],
219
392
  warnings: [...cacheWarnings, ...result.warnings],
220
393
  };
@@ -413,6 +413,9 @@ export declare const zh: {
413
413
  readonly 'sync.git.adoptNotSyncRepo': '远端仓库顶层出现了快照布局以外的内容({entries}):它看起来不是本插件的同步仓库,已拒绝合并(不会把别的仓库内容搬进工作副本)。';
414
414
  readonly 'sync.git.adoptMergeConflict': '合并远端 {branch} 时发生冲突:已撤销这次合并(merge --abort),工作副本回到操作前的状态。请手工解决冲突后重试,或改用「重新克隆工作副本」。';
415
415
  readonly 'sync.workdirModeInvalidFull': '重建工作副本的模式非法: {mode}(只允许 relink(重指向地址)、adopt(采纳远端历史)或 reclone(重新克隆))';
416
+ readonly 'sync.git.subdirInvalid': '同步子目录前缀不合法:{subdir}(不得以 / 开头或结尾,不得含反斜杠、空段、. 段、.. 段或 .git 段)';
417
+ readonly 'sync.git.subdirRoot': '仓库根';
418
+ readonly 'sync.git.subdirChanged': '工作副本的同步布局是「{stored}」,当前配置是「{expected}」:sparse-checkout 只在首次克隆时生效,旧工作副本里没有新前缀的目录树 —— 照常同步会表现为「远端没有快照」。请在「同步 → 通道配置」里重建工作副本(重新克隆)后再同步。';
416
419
  readonly 'sync.git.cmdFailed': 'git {args} 失败 (exit {code}): {err}';
417
420
  readonly 'sync.git.identityMissing': 'git 在这台机器上没有可用的提交身份(user.name / user.email 未配置),本次操作被本机 git 拒绝(exit 128,与网络和远端无关)。插件会为同步工作副本自动补写仓库级身份;若仍失败,请在本机执行 git config --global user.name "<名字>" 与 git config --global user.email "<邮箱>" 后重试。原始错误:{err}';
418
421
  readonly 'sync.git.pushTokenRequired': '推送需要访问令牌:远端是 http(s) 仓库,但本机没有可用的令牌(拉取公开仓库可以匿名完成,推送必须认证)。请在「同步 → 通道配置」里登录 GitHub 或填入访问令牌后重试。';
@@ -411,6 +411,10 @@ export const zh = {
411
411
  'sync.git.adoptNotSyncRepo': '远端仓库顶层出现了快照布局以外的内容({entries}):它看起来不是本插件的同步仓库,已拒绝合并(不会把别的仓库内容搬进工作副本)。',
412
412
  'sync.git.adoptMergeConflict': '合并远端 {branch} 时发生冲突:已撤销这次合并(merge --abort),工作副本回到操作前的状态。请手工解决冲突后重试,或改用「重新克隆工作副本」。',
413
413
  'sync.workdirModeInvalidFull': '重建工作副本的模式非法: {mode}(只允许 relink(重指向地址)、adopt(采纳远端历史)或 reclone(重新克隆))',
414
+ // issue #131:git 通道的仓库内子目录前缀(多工具共用一个备份仓库时各占一个目录)。
415
+ 'sync.git.subdirInvalid': '同步子目录前缀不合法:{subdir}(不得以 / 开头或结尾,不得含反斜杠、空段、. 段、.. 段或 .git 段)',
416
+ 'sync.git.subdirRoot': '仓库根',
417
+ 'sync.git.subdirChanged': '工作副本的同步布局是「{stored}」,当前配置是「{expected}」:sparse-checkout 只在首次克隆时生效,旧工作副本里没有新前缀的目录树 —— 照常同步会表现为「远端没有快照」。请在「同步 → 通道配置」里重建工作副本(重新克隆)后再同步。',
414
418
  'sync.git.cmdFailed': 'git {args} 失败 (exit {code}): {err}',
415
419
  // 本机提交身份缺失(真机 issue:commit exit 128 ⇒ 交易 NEEDS_ATTENTION ⇒ 被误升 SAFE MODE)。
416
420
  // 文案必须点名「本机配置」,并把「远端/网络/令牌」这三种常见误判方向明确排除。
@@ -914,6 +918,10 @@ export const en = {
914
918
  'sync.git.adoptNotSyncRepo': 'The remote repository root contains entries outside the snapshot layout ({entries}): it does not look like this plugin\'s sync repository, so the merge was refused (another repository\'s content is never pulled into the working copy).',
915
919
  'sync.git.adoptMergeConflict': 'Merging remote {branch} produced conflicts: the merge was aborted (merge --abort) and the working copy is back to its previous state. Resolve the conflicts manually and retry, or use "clone the working copy again".',
916
920
  'sync.workdirModeInvalidFull': 'Invalid working-copy rebuild mode: {mode} (only relink (re-point the address), adopt (merge the remote history) or reclone (clone again) are allowed).',
921
+ // issue #131: in-repo subdirectory prefix for the git channel (several tools sharing one backup repository).
922
+ 'sync.git.subdirInvalid': 'Invalid sync subdirectory prefix: {subdir} (must not start or end with /, and must not contain a backslash, an empty segment, a . segment, a .. segment, or a .git segment)',
923
+ 'sync.git.subdirRoot': 'repository root',
924
+ 'sync.git.subdirChanged': 'This working copy uses the sync layout "{stored}" but the current config is "{expected}": sparse-checkout only applies on the first clone, so the old working copy has no tree for the new prefix — syncing would look like "the remote has no snapshots". Rebuild the working copy (clone again) under Sync → Channel configuration, then sync again.',
917
925
  'sync.git.cmdFailed': 'git {args} failed (exit {code}): {err}',
918
926
  // Missing local commit identity (real-world issue: commit exit 128 → NEEDS_ATTENTION → wrongly escalated to SAFE MODE).
919
927
  // Name the local config and rule out the three usual suspects (remote, network, token).
@@ -86,6 +86,16 @@ export interface RunRegistryOptions {
86
86
  * 内存 run 注册表。Node 单线程 + 同步 Map 读写,无并发竞争;
87
87
  * 所有公开读方法返回状态副本,防止外部直接篡改内部状态。
88
88
  */
89
+ /**
90
+ * 自动同步「空转」run:60s 一次的远端探测拿到 upToDate —— 本轮既没上传也没下行、没应用任何分区。
91
+ *
92
+ * 为什么要过滤(2026-11-09 真机):realtime 通道每轮都会 register('autosync'),于是运行中心每分钟
93
+ * 多一张「自动同步 · 已完成」卡片,与「迁移历史」同一种噪音(那边已由 isAutosyncIdleRound 挡住)。
94
+ * 轮询不是活动;真干活(push/pull/冲突/失败)的卡片必须留着 —— 它们才解释「刚才发生了什么」。
95
+ *
96
+ * 判定只认 run 自己的 result.idle(由调度器收尾时写入),不在 UI 猜 skipReason。
97
+ */
98
+ export declare function isIdleAutosyncRun(state: Pick<RunState, 'kind' | 'status' | 'result'>): boolean;
89
99
  export declare class RunRegistry {
90
100
  private readonly runs;
91
101
  private readonly retentionMs;
@@ -65,6 +65,23 @@ export const DEFAULT_RUN_STALLED_MS = 6 * 60 * 60 * 1000;
65
65
  * 内存 run 注册表。Node 单线程 + 同步 Map 读写,无并发竞争;
66
66
  * 所有公开读方法返回状态副本,防止外部直接篡改内部状态。
67
67
  */
68
+ /**
69
+ * 自动同步「空转」run:60s 一次的远端探测拿到 upToDate —— 本轮既没上传也没下行、没应用任何分区。
70
+ *
71
+ * 为什么要过滤(2026-11-09 真机):realtime 通道每轮都会 register('autosync'),于是运行中心每分钟
72
+ * 多一张「自动同步 · 已完成」卡片,与「迁移历史」同一种噪音(那边已由 isAutosyncIdleRound 挡住)。
73
+ * 轮询不是活动;真干活(push/pull/冲突/失败)的卡片必须留着 —— 它们才解释「刚才发生了什么」。
74
+ *
75
+ * 判定只认 run 自己的 result.idle(由调度器收尾时写入),不在 UI 猜 skipReason。
76
+ */
77
+ export function isIdleAutosyncRun(state) {
78
+ if (state.kind !== 'autosync' || state.status === 'running')
79
+ return false;
80
+ const result = state.result;
81
+ if (result === null || typeof result !== 'object')
82
+ return false;
83
+ return result.idle === true;
84
+ }
68
85
  export class RunRegistry {
69
86
  runs = new Map();
70
87
  retentionMs;
package/lib/index.d.ts CHANGED
@@ -75,7 +75,7 @@ export declare const name = "config-manager";
75
75
  /** Services required before the engine can mount (present in every profile). */
76
76
  export declare const inject: string[];
77
77
  /** Plugin version, kept in sync with package.json ("version"). */
78
- export declare const PLUGIN_VERSION = "0.6.0";
78
+ export declare const PLUGIN_VERSION = "0.7.0";
79
79
  /**
80
80
  * Star 引导弹窗指向的 GitHub 仓库(用户引导点 Star 的目标)。
81
81
  * 与 package.json 的 repository 字段保持一致;界面不可改(硬编码,参照
@@ -818,12 +818,13 @@ export type RouteEnvInferred = {
818
818
  syncWorkDir: {
819
819
  inspect: (repoUrl: string, opts?: {
820
820
  detail?: boolean;
821
+ subdir?: string;
821
822
  }) => Promise<{
822
823
  facts: GitWorkDirFacts;
823
824
  } | {
824
825
  error: string;
825
826
  }>;
826
- rebuild: (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone') => Promise<GitWorkDirFacts>;
827
+ rebuild: (repoUrl: string, mode: 'relink' | 'adopt' | 'reclone', subdir?: string) => Promise<GitWorkDirFacts>;
827
828
  };
828
829
  syncSectionCatalog: {
829
830
  id: SectionId;
package/lib/index.js CHANGED
@@ -148,7 +148,7 @@ export const name = 'config-manager';
148
148
  /** Services required before the engine can mount (present in every profile). */
149
149
  export const inject = ['settings', 'credentials'];
150
150
  /** Plugin version, kept in sync with package.json ("version"). */
151
- export const PLUGIN_VERSION = '0.6.0';
151
+ export const PLUGIN_VERSION = '0.7.0';
152
152
  /** Plugin own package name — excluded from its own exported plugins list. */
153
153
  const PLUGIN_NAME = 'dsh-config-manager';
154
154
  /**
@@ -2372,8 +2372,10 @@ function makeRoutes(deps) {
2372
2372
  * 构造 git 通道实例(同步引擎与 issue #79 的工作副本自检/重建共用同一份地址与凭据口径)。
2373
2373
  * token 只经 credentials 端口现取(值永不落盘/日志/回传)。
2374
2374
  */
2375
- const makeGitTransport = (repoUrl) => new GitTransport({
2375
+ const makeGitTransport = (repoUrl, subdir) => new GitTransport({
2376
2376
  repoUrl,
2377
+ // issue #131:子目录前缀与 repoUrl 同源(配置 → 传输层),空串 = 仓库根
2378
+ ...(subdir === undefined ? {} : { subdir }),
2377
2379
  workDir: gitWorkDir,
2378
2380
  credentials: {
2379
2381
  getToken: async () => {
@@ -2438,7 +2440,7 @@ function makeRoutes(deps) {
2438
2440
  });
2439
2441
  }
2440
2442
  else {
2441
- transport = makeGitTransport(cfg.git.repoUrl);
2443
+ transport = makeGitTransport(cfg.git.repoUrl, cfg.git.subdir);
2442
2444
  }
2443
2445
  const channel = channelOf(cfg);
2444
2446
  const sections = effectiveSections(selectionCache[channel] ?? defaultSyncSelection());
@@ -2739,7 +2741,7 @@ function makeRoutes(deps) {
2739
2741
  // issue #104 建议 3:`/sync/status` 要回传「领先远端提交数 / 远端快照数」,
2740
2742
  // 用户看不见积压就会在「以为在备份」的状态下一直失败。detail 那几条是本地只读但各起
2741
2743
  // 一次 git 进程(Windows 约 80 ms)⇒ 缺省完整(WorkDirCard 要),路由可传 false。
2742
- return { facts: await makeGitTransport(repoUrl).inspectWorkDir({ detail: opts.detail !== false }) };
2744
+ return { facts: await makeGitTransport(repoUrl, opts.subdir).inspectWorkDir({ detail: opts.detail !== false }) };
2743
2745
  }
2744
2746
  catch (err) {
2745
2747
  return { error: err instanceof Error ? err.message : String(err) };
@@ -2747,8 +2749,8 @@ function makeRoutes(deps) {
2747
2749
  },
2748
2750
  // 重建:relink 非破坏;adopt 合并远端历史(不改写本地提交,issue #104);
2749
2751
  // reclone 删目录重克隆(调用方必须先取得用户确认)
2750
- rebuild: async (repoUrl, mode) => {
2751
- const transport = makeGitTransport(repoUrl);
2752
+ rebuild: async (repoUrl, mode, subdir) => {
2753
+ const transport = makeGitTransport(repoUrl, subdir);
2752
2754
  await transport.rebuildWorkDir(mode);
2753
2755
  return await transport.inspectWorkDir();
2754
2756
  },
@@ -5,6 +5,7 @@
5
5
  * path/methods 就是唯一声明处;围栏、方法判定与顶层异常处理由 src/routes/kit.ts 在注册点统一提供。
6
6
  */
7
7
  import { endpoint, requireJsonObject, readJsonBody, writeJson, queryParam } from './kit.js';
8
+ import { isIdleAutosyncRun } from '../core/run-registry.js';
8
9
  import { DEFAULT_ROLLBACK_ON_ERROR } from '../core/import-defaults.js';
9
10
  import { decryptErrorText, isControlledPath, tryDecryptCredentials, writeRequestBodyToFile } from './route-support.js';
10
11
  import { resolveSessionFormatDisposition, sessionFormatAbortResponse } from './session-format.js';
@@ -347,7 +348,11 @@ export function importRoutes(env) {
347
348
  endpoint({ path: '/api/dsh-config-manager/runs', methods: ['GET'] }, async (req, res) => {
348
349
  const url = new URL(req.url ?? '/', 'http://localhost');
349
350
  const scope = queryParam(url, 'scope');
350
- writeJson(res, 200, scope === 'recent' ? runs.listRecent(50) : runs.listActive());
351
+ // 空转的自动同步轮次不进「运行中心」:60s 一次轮询,每轮一张「已完成」卡片与迁移历史同属噪音;
352
+ // running / 真干活的轮次照常列出(判据见 core/run-registry.ts 的 isIdleAutosyncRun)。
353
+ writeJson(res, 200, scope === 'recent'
354
+ ? runs.listRecent(50).filter((run) => !isIdleAutosyncRun(run))
355
+ : runs.listActive());
351
356
  }),
352
357
  // ------------------------------------------------------- runs/cancel
353
358
  // 运行中心「终止」:只在**计划项边界**生效的协作式取消(abort run 级信号)。
@@ -273,7 +273,8 @@ export interface SyncRefScope {
273
273
  /**
274
274
  * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
275
275
  * 请求体形状(flat,M4 契约):
276
- * - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
276
+ * - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
277
+ * token 非空写 SYNC_CREDENTIAL_REF;
277
278
  * git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
278
279
  * - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
279
280
  * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
@@ -25,7 +25,7 @@ import { decryptCredentials, SecurityError } from '../security/index.js';
25
25
  import { engineMsg } from '../core/engine-locale.js';
26
26
  import { createPreRestoreAttemptDir } from '../core/restore.js';
27
27
  import { collectRestoreWalEntries, createRestoreWal, restoreActionStepId, restoreWalHandlesFromSteps } from '../core/restore-wal.js';
28
- import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.js';
28
+ import { GIST_PROVIDER, cloudSecretRef, isS3CompatProvider, isWebDavConfig, normalizeGitSubdir, parseSyncChannel, validateCloudChannelInput, validateRepoUrl, validateWebDavUrl } from '../sync/sync-config.js';
29
29
  import { DEFAULT_AUTOSYNC_AUTO_APPLY_TIER, DEFAULT_AUTOSYNC_CONFLICT_POLICY, DEFAULT_AUTOSYNC_REALTIME, DEFAULT_AUTOSYNC_REMOTE_CHECK_MS, lastRunFailureMessage, readAllAutosyncConfigs, readAutosyncConfig } from '../sync/autosync-config.js';
30
30
  import { SYNC_CHANNELS } from '../sync/sync-config.js';
31
31
  import { normalizeSessionsInclude } from '../sync/sync-selection.js';
@@ -617,7 +617,8 @@ export function makeRestoreExecutor(snapshotDir, host, profile) {
617
617
  /**
618
618
  * 解析同步请求体,按 transport 分支返回归一化的 SyncConfig(可辨识联合,schemaVersion=2)。
619
619
  * 请求体形状(flat,M4 契约):
620
- * - git: { transport:'git', repoUrl, token? } —— token 非空写 SYNC_CREDENTIAL_REF;
620
+ * - git: { transport:'git', repoUrl, subdir?, token? } —— subdir = 仓库内子目录前缀(issue #131);
621
+ * token 非空写 SYNC_CREDENTIAL_REF;
621
622
  * git 可执行文件固定使用系统 PATH 中的 git(不再接受自定义 gitBin)。
622
623
  * - webdav: { transport:'webdav', url, username?, password? } —— password 非空写 SYNC_WEBDAV_CREDENTIAL_REF。
623
624
  * 返回值不含任何 secret(password/token 只进 credentials,永不回传/落同步文件)。
@@ -665,6 +666,10 @@ export async function parseSyncBody(body, deps) {
665
666
  const urlError = validateRepoUrl(repoUrl);
666
667
  if (urlError !== null)
667
668
  throw new SyncRouteError(urlError);
669
+ // issue #131:仓库内子目录前缀(可选;空 = 仓库根)。非法值在这里就拒,绝不先落盘再交给 git。
670
+ const subdirCheck = normalizeGitSubdir(syncStr(body['subdir']));
671
+ if (!subdirCheck.ok)
672
+ throw new SyncRouteError(engineMsg('sync.git.subdirInvalid', { subdir: syncStr(body['subdir']) }));
668
673
  const token = typeof body['token'] === 'string' && body['token'] !== '' ? body['token'] : undefined;
669
674
  if (token !== undefined) {
670
675
  try {
@@ -678,7 +683,7 @@ export async function parseSyncBody(body, deps) {
678
683
  return {
679
684
  schemaVersion: 2,
680
685
  transport: 'git',
681
- git: { repoUrl },
686
+ git: { repoUrl, ...(subdirCheck.value === '' ? {} : { subdir: subdirCheck.value }) },
682
687
  };
683
688
  }
684
689
  /** 请求体字段 → 去空白字符串(非字符串 = 空)。 */
@@ -187,14 +187,17 @@ export function syncRoutes(env) {
187
187
  // 远端快照数」(只读自检;后者是「本地一直没真正备份」的预警依据)。
188
188
  // 读不出来时**如实回传错误**(workDirError),不让状态接口静默少一块信息。
189
189
  const gitRepoUrl = full?.git?.repoUrl ?? '';
190
+ // issue #131:自检必须按配置的子目录前缀读(远端快照数来自 <subdir>/snapshots)
191
+ const gitSubdir = full?.git?.subdir ?? '';
190
192
  let workDir = null;
191
193
  if (gitRepoUrl !== '')
192
- workDir = await syncWorkDir.inspect(gitRepoUrl, { detail: opts.workDirDetail });
194
+ workDir = await syncWorkDir.inspect(gitRepoUrl, { detail: opts.workDirDetail, ...(gitSubdir === '' ? {} : { subdir: gitSubdir }) });
193
195
  return {
194
196
  ok: true,
195
197
  configured: full !== null,
196
198
  transport,
197
199
  repoUrl: full?.git?.repoUrl,
200
+ subdir: full?.git?.subdir,
198
201
  // 被丢弃的通道配置成因(默认空数组:字段恒在,客户端不必判 undefined;
199
202
  // 合法配置不产生幻影告警)。code 是机读 token,message 可直接展示。
200
203
  configIssues,
@@ -283,7 +286,7 @@ export function syncRoutes(env) {
283
286
  });
284
287
  return;
285
288
  }
286
- const rebuilt = await syncWorkDir.rebuild(repoUrl, mode);
289
+ const rebuilt = await syncWorkDir.rebuild(repoUrl, mode, full?.git?.subdir);
287
290
  writeJson(res, 200, { ok: true, mode, workDir: { facts: rebuilt } });
288
291
  }
289
292
  catch (error) {
@@ -9,7 +9,15 @@ export declare const DEFAULT_AUTOSYNC_INTERVAL: AutosyncInterval;
9
9
  export declare const DEFAULT_STARTUP_MIN_INTERVAL_MS: number;
10
10
  /** 缺省开启「本地改动即时触发」(真·自动同步;关闭后退回纯定时器) */
11
11
  export declare const DEFAULT_AUTOSYNC_REALTIME = true;
12
- /** 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 1 分钟内下行) */
12
+ /**
13
+ * 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 5 分钟内下行)。
14
+ *
15
+ * 2026-11-09 由 60s 改为 5 分钟(用户拍板):远端探测本身很便宜,但过去每轮还会顺带做一次本地
16
+ * 全量导出判定,plugins 分区要为每个本机源插件跑 npm pack(真机 12 个 ≈12 s、单个 210MB 44.7 s)
17
+ * ⇒ 60 s 一轮等于长期占用一个核。本地改动的即时性由文件监听负责(local-change 触发),
18
+ * 兜底由 interval 负责,远端「有没有新快照」不需要 1 分钟一问。旧配置里已写死的值不在此处迁移
19
+ * (用户显式选过的值优先),需要改的走 POST /sync/autosync 的 remoteCheckMs。
20
+ */
13
21
  export declare const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS: number;
14
22
  /** 远端轮询间隔下限(15 s):再短只是空转 fetch,收益为零 */
15
23
  export declare const MIN_AUTOSYNC_REMOTE_CHECK_MS: number;
@@ -27,8 +27,16 @@ export const DEFAULT_AUTOSYNC_INTERVAL = '30m';
27
27
  export const DEFAULT_STARTUP_MIN_INTERVAL_MS = 5 * 60 * 1000;
28
28
  /** 缺省开启「本地改动即时触发」(真·自动同步;关闭后退回纯定时器) */
29
29
  export const DEFAULT_AUTOSYNC_REALTIME = true;
30
- /** 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 1 分钟内下行) */
31
- export const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS = 60 * 1000;
30
+ /**
31
+ * 缺省远端轮询间隔(realtime 开启时与本地监听并行:本地改动即时上行,远端改动最迟 5 分钟内下行)。
32
+ *
33
+ * 2026-11-09 由 60s 改为 5 分钟(用户拍板):远端探测本身很便宜,但过去每轮还会顺带做一次本地
34
+ * 全量导出判定,plugins 分区要为每个本机源插件跑 npm pack(真机 12 个 ≈12 s、单个 210MB 44.7 s)
35
+ * ⇒ 60 s 一轮等于长期占用一个核。本地改动的即时性由文件监听负责(local-change 触发),
36
+ * 兜底由 interval 负责,远端「有没有新快照」不需要 1 分钟一问。旧配置里已写死的值不在此处迁移
37
+ * (用户显式选过的值优先),需要改的走 POST /sync/autosync 的 remoteCheckMs。
38
+ */
39
+ export const DEFAULT_AUTOSYNC_REMOTE_CHECK_MS = 5 * 60 * 1000;
32
40
  /** 远端轮询间隔下限(15 s):再短只是空转 fetch,收益为零 */
33
41
  export const MIN_AUTOSYNC_REMOTE_CHECK_MS = 15 * 1000;
34
42
  /** 远端轮询间隔上限(60 min):比这更慢就不该叫「实时」了 */
@@ -424,11 +424,11 @@ export class AutoSyncScheduler {
424
424
  * 仍 updatedAt == createdAt;此后每次 autosync 都 `register('autosync')` → RunConflictError
425
425
  * → 后台同步静默停摆(正是下面 finally 注释警告的后果),运行中心里那张卡片也「一直在加载」。
426
426
  */
427
- const finishRun = () => {
427
+ const finishRun = (extra = {}) => {
428
428
  if (runId === null)
429
429
  return;
430
430
  try {
431
- this.runs.finish(runId, { kind: 'autosync' });
431
+ this.runs.finish(runId, { kind: 'autosync', ...extra });
432
432
  }
433
433
  catch {
434
434
  /* 尽力而为:收尾失败不影响同步结果 */
@@ -440,11 +440,17 @@ export class AutoSyncScheduler {
440
440
  // (实测单个 210MB 插件 44.7s/次、每轮重算)。旧实现把这段整个放进 GLOBAL mutation 锁内,60s 一轮的
441
441
  // 轮询于是让锁几乎全程被占(45s/60s),用户任何 destructive 操作(删除档案…)都撞 423「另一个任务正在运行」。
442
442
  // 现在稳态(upToDate)根本不取锁;命中「有活干」才取,并在锁内重跑检测再写。
443
- const preflight = await this.detectPhase(channel, cfg, nowIso, historyId);
443
+ // 远端轮询轮跳过本地导出(reason='remote-poll'):本地改动由 realtime 监听(local-change 触发)
444
+ // 与 30 分钟兜底 interval 负责;这里每 60s 再跑一次全量导出 = 白跑 plugins 的 npm pack
445
+ // (真机单插件 44.7s/轮)。判定口径不变 —— 真要比对时比的仍是载荷字节,不做任何近似。
446
+ const preflight = await this.detectPhase(channel, cfg, nowIso, historyId, {
447
+ localCheck: opts.reason !== 'remote-poll',
448
+ });
444
449
  if (preflight.kind === 'skip') {
445
450
  this.running = false;
446
451
  this.watcher?.resume();
447
- finishRun();
452
+ // 空转轮(什么都没传)打上 idle:运行中心据此不为它留卡片(见 core/run-registry 的 isIdleAutosyncRun)。
453
+ finishRun(preflight.result.skipReason === 'upToDate' ? { idle: true } : {});
448
454
  return preflight.result;
449
455
  }
450
456
  let releaseLock = null;
@@ -799,7 +805,12 @@ export class AutoSyncScheduler {
799
805
  * 全程被占,用户任何 destructive 操作都撞 423(2026-11-07 真机事故的根因)。
800
806
  * 结论**不具权威性**:调用方取到锁之后必须重跑一次(见 runOnceInternal 的 Phase 2)。
801
807
  */
802
- async detectPhase(channel, cfg, nowIso, historyId) {
808
+ async detectPhase(channel, cfg, nowIso, historyId,
809
+ /**
810
+ * localCheck=false = 本轮只回答「远端有没有新快照」,不跑本地导出(60s 远端轮询专用)。
811
+ * 本地是否改动由 realtime 监听与兜底 interval 负责;这不是近似判定 —— 需要比对时比的仍是载荷字节。
812
+ */
813
+ opts = {}) {
803
814
  // 读该通道 sync-config:按通道判定「已配置」——git 看 git.repoUrl、webdav 看 webdav.url。
804
815
  // SEC-03:「未配置」有两种成因 —— 真的没配,或存过的地址被白名单拒掉(读侧丢弃)。
805
816
  // 必须区分:后者如果说成前者的「尚未配置」,用户会一遍遍重填同一个被拒地址。
@@ -862,7 +873,8 @@ export class AutoSyncScheduler {
862
873
  // 定时器只是兜底轮询;真正驱动是这两个「变化」信号。
863
874
  // 列表拿不到(网络失败)时 remoteMetas 为 null → 检测自己再 list 一次,行为与改造前一致
864
875
  const remoteNew = await this.detectRemoteNew(engine, remoteMetas ?? undefined);
865
- const localDirty = await this.detectLocalChange(engine);
876
+ // 关掉本地检测时 localDirty 恒 false:远端也没变 → 立刻 upToDate,一次导出都不跑。
877
+ const localDirty = opts.localCheck === false ? false : await this.detectLocalChange(engine);
866
878
  // SYN-05:首轮(从未跑过)与「远端有新快照」是覆盖风险最高的两个时刻 —— 由
867
879
  // resolveConflictPushPolicy 统一把这两处的 ask 标成 forced。
868
880
  const firstRun = cfg.lastRunAt === undefined || cfg.lastRunAt === '';