dsh-config-sync-plugin 0.4.10 → 0.4.12

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.
package/index.js CHANGED
@@ -22,12 +22,12 @@ import { createHash } from 'node:crypto'
22
22
  import { createRequire } from 'node:module'
23
23
  import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readdirSync, readFileSync, readSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
24
24
  import { homedir, hostname, tmpdir } from 'node:os'
25
- import { basename, dirname, isAbsolute, join, relative } from 'node:path'
25
+ import { basename, dirname, extname, isAbsolute, join, relative } from 'node:path'
26
26
  import { fileURLToPath } from 'node:url'
27
27
  // 0.3.76:会话投影缓存守卫(agent-busy 自动清缓存,让缓存按日志重建)
28
28
  import { runGuard, clearSessionCaches, appendGuardLog } from './runtime/tools/session-cache-guard.mjs'
29
29
  // 0.3.76:工作区显示状态(三态 + 会话独立隐藏),自包含读写 DSH 两个权威文件
30
- import { readView, setWorkspaceState, setSessionState } from './runtime/tools/workspace-view.mjs'
30
+ import { readView } from './runtime/tools/workspace-view.mjs'
31
31
  // 0.3.82:实时通道。拿不到 workspaceRegistry 时,这两个函数内部自动退回上面的文件写法。
32
32
  import { setWorkspaceStateLive, setSessionStateLive } from './runtime/tools/workspace-view.mjs'
33
33
 
@@ -75,6 +75,8 @@ function t(zh, en) {
75
75
  // ---- 插件自身的版本与更新源 ----
76
76
  // 插件目录就是 index.js 所在目录(apply 会把它部署成 <AppRoot>\dsh-config-sync-plugin-<ver>\)。
77
77
  const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url))
78
+ // pluginRoot()/pluginVersion() 是历史调用点保留的同义包装,统一回到这一份定义,避免三处口径漂移。
79
+ function pluginRoot() { return PLUGIN_DIR }
78
80
  const PLUGIN_VERSION = (() => {
79
81
  try {
80
82
  const pkg = JSON.parse(readFileSync(join(PLUGIN_DIR, 'package.json'), 'utf8'))
@@ -452,12 +454,8 @@ function runGit(args, env, timeout = 20000) {
452
454
  })
453
455
  }
454
456
 
455
- function lsRemoteHeads(url, settings) {
456
- return probeRemote(url, settings).then((p) => (p ? p.heads : null))
457
- }
458
-
459
457
  /** 临时 bare 仓库里数一次远端某个分支的文件数;失败返回 null。 */
460
- async function remoteFileCount(url, settings, quiet) {
458
+ async function remoteFileCount(url, settings) {
461
459
  const env = gitProbeEnv(settings)
462
460
  let dir = ''
463
461
  try {
@@ -492,7 +490,7 @@ async function probeRemote(url, settings) {
492
490
  let value = null
493
491
  if (heads === null) value = { heads: null, files: null }
494
492
  else if (heads === 0) value = { heads: 0, files: 0 }
495
- else value = { heads, files: await remoteFileCount(url, settings, 'quiet') }
493
+ else value = { heads, files: await remoteFileCount(url, settings) }
496
494
  remoteProbeCache.set(url, { at: Date.now(), value })
497
495
  return value
498
496
  }
@@ -935,6 +933,19 @@ function repoPhase(dir) {
935
933
  return others.length === 0 ? 'empty' : 'unusable'
936
934
  }
937
935
 
936
+ /**
937
+ * 仓库三态 → 推送/拉取门禁的唯一判据来源(面板 inspect 与后端自动同步共用口径)。
938
+ * phase: ok=真仓库 / empty=空目录 / missing=未建 / unusable=填错路径。
939
+ * remoteFiles: 云端分支树文件数,0=空、null=判不了。
940
+ * 注:判据与 0.4.10 原实现逐字一致,抽取只为消除三处重复,不改变任何放行行为。
941
+ */
942
+ function canPush(phase, remoteFiles) {
943
+ return phase === 'ok' || (phase === 'empty' && remoteFiles === 0)
944
+ }
945
+ function canPull(phase, remoteFiles) {
946
+ return phase === 'ok' || ((phase === 'empty' || phase === 'missing') && remoteFiles !== 0)
947
+ }
948
+
938
949
  /**
939
950
  * 体检。全部只读,不写任何文件(除了 prepare 那次由用户显式触发的 cmd 生成)。
940
951
  */
@@ -1112,9 +1123,9 @@ async function inspect(config) {
1112
1123
  ? 'ok'
1113
1124
  : (remoteFiles === 0 ? 'await-init' : 'await-pull'),
1114
1125
  // 推送:真仓库,或「空目录 + 云端确实没文件」的首次推送(判不了时不放行,宁可按老规矩只拉)
1115
- pushAllowed: phase === 'ok' || (phase === 'empty' && remoteFiles === 0),
1126
+ pushAllowed: canPush(phase, remoteFiles),
1116
1127
  // 拉取:真仓库,或空目录/没建目录且云端确实有文件(sync.ps1 的 Initialize-RepoIfNeeded 会自动 init + fetch + checkout)
1117
- pullAllowed: phase === 'ok' || ((phase === 'empty' || phase === 'missing') && remoteFiles !== 0),
1128
+ pullAllowed: canPull(phase, remoteFiles),
1118
1129
  // 路径是怎么来的:settings=本机设置(面板可改)、config=插件配置、env=环境变量、auto=自动探测、none=没配
1119
1130
  source: resolved.source,
1120
1131
  configured: Boolean(settings.repoPath || config?.repoPath),
@@ -1288,10 +1299,6 @@ function pickPs1(repo, name) {
1288
1299
  ))
1289
1300
  }
1290
1301
 
1291
- function pluginRoot() {
1292
- try { return dirname(fileURLToPath(import.meta.url)) } catch { return '' }
1293
- }
1294
-
1295
1302
  function buildCmd(config, action, repo, appRoot, dshHome, state = {}) {
1296
1303
  const isRestore = action === 'restore' || action === 'restore-backup'
1297
1304
  const restorePs1 = isRestore ? pickPs1(repo, 'restore.ps1') : ''
@@ -1749,13 +1756,14 @@ function electronApp() {
1749
1756
  }
1750
1757
 
1751
1758
  /**
1752
- * 让客户端**真的退出**。
1759
+ * 请求客户端退出(手动「立即推送/拉取/还原」排队后走这条)。
1753
1760
  *
1754
- * 旧实现是 `taskkill /PID <主进程>`(不带 /F):对 Electron 主进程无效 ——
1755
- * 主进程没有自己的顶层窗口,实测直接报 "This process can only be terminated forcefully",
1756
- * 于是「确认后自动退出 DSH」根本不生效,守护进程只能干等到 30 分钟超时。
1757
- *
1758
- * 现在优先 app.quit()(走 before-quit,配置照常落盘);拿不到 electron 才退回 taskkill。
1761
+ * 实现顺序(注释与实现保持一致,勿再写成「优先 app.quit」):
1762
+ * 1) 先按映像名发一次礼貌关闭 taskkill /IM(不带 /F),让 Electron 走正常关闭流程;
1763
+ * 2) 3.5 秒后 /F 强杀残留进程族(插件跑在子进程里,只杀 process.pid 杀不干净);
1764
+ * 3) 拿到 electron 句柄时另发一次 app.quit()(走 before-quit 落盘)。
1765
+ * 返回 true 表示「已发起退出请求」,不代表进程已确认退出(spawn 结果无法同步取得)。
1766
+ * 退出后自动同步那条链路用 forceCloseDshDetached(独立进程延迟强杀),不要混用。
1759
1767
  */
1760
1768
  function closeDsh() {
1761
1769
  const exe = join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'taskkill.exe')
@@ -1788,8 +1796,17 @@ function closeDsh() {
1788
1796
  * 用 cmd /c + ping 做秒级延时(timeout.exe 在无控制台的非交互进程里会报错),
1789
1797
  * 先给点 × 触发的正常关闭流程一点时间落盘,再 /F 兜底残留进程。
1790
1798
  */
1799
+ let _forceCloseLastAt = 0
1791
1800
  function forceCloseDshDetached(config) {
1792
1801
  const dshHome = config?.dshHome || process.env.DSH_HOME || join(homedir(), '.dsh')
1802
+ // 幂等:同一次退出事件里「窗口关闭 / 信标 / 定时预排」三处入口可能接连触发,
1803
+ // 1.5s 内只发一次独立强杀,避免重复 spawn。每次都是杀同一进程族,最终状态一致。
1804
+ const _now = Date.now()
1805
+ if (_now - _forceCloseLastAt < 1500) {
1806
+ logLaunch(dshHome, 'auto-exit:1.5s 内已发起过强杀,本次幂等跳过(同一进程族)')
1807
+ return true
1808
+ }
1809
+ _forceCloseLastAt = _now
1793
1810
  const sys = process.env.SystemRoot || 'C:\\Windows'
1794
1811
  const cmd = join(sys, 'System32', 'cmd.exe')
1795
1812
  const taskkill = join(sys, 'System32', 'taskkill.exe')
@@ -2018,8 +2035,8 @@ function sessionTitleOf(dshHome, sessionId) {
2018
2035
  }
2019
2036
 
2020
2037
  /**
2021
- * 本机 DSH 数据里「上次同步之后又写过」的文件有多少个。
2022
- * 只看 mtime,不读内容、**不跑 capture**(跑 capture 要复制整个工作区,几 GB)。
2038
+ * 本机 DSH 数据里「上次同步之后内容真正变了」的文件有多少个。
2039
+ * 先用 mtime 快筛,再对 mtime 变过的文件比内容指纹(**不跑 capture**,那要复制整个工作区,几 GB)。
2023
2040
  * 代价控制:跳过 node_modules / models / .git 等,最多 20000 个文件、最多 1.5 秒。
2024
2041
  *
2025
2042
  * 为什么要补一层内容比对:`profile\cordis.patch.yml` 这类文件 **DSH 每次启动都会重写**
@@ -2056,6 +2073,14 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2056
2073
  mirrored.set(join(profile, f), join(repoRoot, 'profile', f))
2057
2074
  }
2058
2075
  }
2076
+ // 非镜像文件的基线(会话记录 / skills / mnemon / 工作区 …)由本插件维护在本机,
2077
+ // 记录上次同步时刻的指纹;lastSyncAt 没变时用它判断 mtime 变化是否只是一次无内容重写。
2078
+ // 基线文件缺失或 lastSyncAt 对不上时先按 mtime-only 计,完整扫描结束后重建基线。
2079
+ // pendingKeys:建基线那一刻就已经 pending 的文件。它们后续即使指纹与基线相同也继续计入,
2080
+ // 防止「升级后首次 inspect 建基线 → 刷新一次就把真改动洗白」;直到 lastSyncAt 前进
2081
+ // (真正完成一次同步)重建基线才清除。
2082
+ const contentBaseline = readContentBaseline(dshHome, since)
2083
+ const baselineValid = Boolean(contentBaseline.lastSyncAt)
2059
2084
  const deadline = Date.now() + 1500
2060
2085
  let scanned = 0
2061
2086
  let pending = 0
@@ -2064,6 +2089,11 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2064
2089
  const groupCount = new Map()
2065
2090
  // 每组保留具体明细名称(会话记录名 / 本机 profile 文件名 …),供面板展开查看
2066
2091
  const groupItems = new Map()
2092
+ // 基线失效(lastSyncAt 前进/首次)时,扫描到的当前内容就是新基准;完整扫描后一次性重建
2093
+ const rebuild = !baselineValid ? {} : null
2094
+ // 重建时记录「建基线这一刻就已经 pending」的文件 key,随基线一起落盘(兼容旧基线缺省 [])
2095
+ const rebuildPendingKeys = new Set()
2096
+ const baselinePendingKeys = new Set(Array.isArray(contentBaseline.pendingKeys) ? contentBaseline.pendingKeys : [])
2067
2097
  const DETAIL_CAP = 50
2068
2098
  while (stack.length && scanned < 20000 && Date.now() < deadline) {
2069
2099
  const cur = stack.pop()
@@ -2077,14 +2107,26 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2077
2107
  continue
2078
2108
  }
2079
2109
  scanned++
2110
+ const key = contentKey(cur)
2111
+ const twin = mirrored.get(cur)
2112
+ let fp = null
2113
+ // 基线有效时只为 mtime>since 的文件算指纹(判定内容是否真变);重建时为所有扫描到的文件算。
2114
+ if (rebuild || st.mtimeMs > since) {
2115
+ try { fp = contentFingerprint(cur, ctx.appRoot) } catch { }
2116
+ }
2117
+ if (rebuild && fp) rebuild[key] = fp
2080
2118
  if (st.mtimeMs > since) {
2081
2119
  // 镜像文件的 mtime 更新可能只是宿主重写占位符:内容归一后一致就不算待推送
2082
- const twin = mirrored.get(cur)
2083
2120
  if (twin && isFile(twin)) {
2084
2121
  try {
2085
2122
  if (mirrorText(cur, ctx.appRoot) === mirrorText(twin, ctx.appRoot)) continue
2086
2123
  } catch { }
2087
2124
  }
2125
+ // 非镜像文件:mtime 更新后再跟「上次同步时刻的指纹」比,真正变了才算待推送。
2126
+ // DSH 宿主会重写会话 projcache / session-index 等文件的时间戳,字节没变时指纹相同 → 不报。
2127
+ // 但建基线时已经 pending 的文件(pendingKeys)不能靠「指纹==基线」洗白,必须持续计入。
2128
+ if (!twin && baselineValid && fp && contentBaseline.files[key] === fp && !baselinePendingKeys.has(key)) continue
2129
+ if (rebuild && !twin) rebuildPendingKeys.add(key)
2088
2130
  pending++
2089
2131
  if (st.mtimeMs > newest) newest = st.mtimeMs
2090
2132
  const gid = pendingGroupOf(cur, dshHome, profile, workspacePaths)
@@ -2106,6 +2148,13 @@ function localPending(dshHome, lastSyncAt, profileName, ctx = {}) {
2106
2148
  if (items.length < DETAIL_CAP && !items.includes(label)) items.push(label)
2107
2149
  }
2108
2150
  }
2151
+ const truncated = scanned >= 20000 || Date.now() >= deadline
2152
+ // 只有「基线缺失/过期 + 本次完整扫描」才重建:此时磁盘内容就是 lastSyncAt 那次同步的内容。
2153
+ // 基线有效时绝不更新——否则一直没同步的真实改动会被下一次面板刷新「洗白」成基线。
2154
+ if (rebuild && !truncated) {
2155
+ const fresh = { path: join(dshHome, CONTENT_BASELINE_NAME), lastSyncAt: since, complete: true, files: rebuild, pendingKeys: [...rebuildPendingKeys] }
2156
+ writeContentBaseline(fresh, since)
2157
+ }
2109
2158
  const groups = [...groupCount.entries()]
2110
2159
  .map(([id, count]) => ({
2111
2160
  id,
@@ -2138,6 +2187,126 @@ function mirrorText(file, appRoot) {
2138
2187
  return text
2139
2188
  }
2140
2189
 
2190
+ // ---- 内容级 pending:DSH 重写 mtime 但字节没变的文件不再误报 ----
2191
+ // 基线由后端自己维护在 <dshHome>\.config-sync-content-baseline.json,不依赖 capture/ps1 配合。
2192
+ // 基线记录「上次同步时刻(lastSyncAt)」各文件的指纹;只要 lastSyncAt 没变就不更新,
2193
+ // 于是 mtime 被 DSH 重写但内容没变的文件(会话 projcache / session-index 等)能被识别并跳过,
2194
+ // 真内容变化则指纹不同继续计入 pending,直到下一次同步(lastSyncAt 变化)才重建基线。
2195
+ // pendingKeys 记录建基线那刻已 pending 的文件:首次建基线时真改动会被基线收录,若不额外记住,
2196
+ // 刷新一次就会因「指纹==基线」被洗白;这些 key 持续 pending 到 lastSyncAt 前进重建为止。
2197
+ // 指纹口径:文本统一 CRLF→LF、去尾部空白、把 appRoot 变体还原成 {{APP_ROOT}},再 sha256;
2198
+ // .db/.sqlite 家族全量分块 sha256(原地页更新,size 不变但内容可变);其他二进制(.zstd/.png/…)
2199
+ // 按 size + 头/中/尾采样 sha256,绝不做 UTF8 解码。
2200
+ const CONTENT_BASELINE_NAME = '.config-sync-content-baseline.json'
2201
+ const CONTENT_SAMPLE_BYTES = 262144 // 单文件最多读 256KB:几个 MB 的会话 zstd 也只读头/中/尾三段
2202
+
2203
+ function isTextContentFile(file) {
2204
+ const ext = extname(file).toLowerCase()
2205
+ if (!ext) return true // AGENTS.md 类的无扩展名文本 / README
2206
+ return ['.md', '.txt', '.json', '.jsonl', '.yml', '.yaml', '.ps1', '.mjs', '.js', '.ts', '.toml', '.ini', '.csv'].includes(ext)
2207
+ }
2208
+
2209
+ function normalizeForContentHash(text, appRoot) {
2210
+ let s = String(text).replace(/\r\n/g, '\n').replace(/\s+$/, '')
2211
+ const root = String(appRoot || '').replace(/[\\/]+$/, '')
2212
+ if (root) {
2213
+ for (const variant of new Set([root, root.replace(/\\/g, '/'), root.replace(/\//g, '\\')])) {
2214
+ if (variant) s = s.split(variant).join('{{APP_ROOT}}')
2215
+ }
2216
+ }
2217
+ return s
2218
+ }
2219
+
2220
+ /** 原地同尺寸更新型文件(SQLite 页覆盖):头/中/尾采样会漏检中间页改动,需全量 hash。 */
2221
+ function isInPlaceUpdateFile(file) {
2222
+ return ['.db', '.sqlite', '.sqlite3', '.mdb', '.accdb', '.realm'].includes(extname(file).toLowerCase())
2223
+ }
2224
+ const CONTENT_FULL_HASH_CAP = 67108864 // 64MB:超过则退回采样,避免单个巨型 db 吃掉 1.5s 扫描预算
2225
+
2226
+ /**
2227
+ * 内容指纹:小文本(<=256KB)归一后 sha256;db/sqlite 家族全量分块 sha256;
2228
+ * 其余大文件/二进制按 size + 头/中/尾字节采样 sha256。
2229
+ * 会话日志 zstd、未压缩的大 jsonl 都走采样分支,绝不做 UTF8 解码。
2230
+ */
2231
+ function contentFingerprint(file, appRoot) {
2232
+ const st = statSync(file)
2233
+ const h = createHash('sha256')
2234
+ h.update(`size:${st.size}\n`)
2235
+ if (isTextContentFile(file) && st.size <= CONTENT_SAMPLE_BYTES) {
2236
+ h.update(normalizeForContentHash(readFileSync(file, 'utf8'), appRoot))
2237
+ } else if (isInPlaceUpdateFile(file) && st.size <= CONTENT_FULL_HASH_CAP) {
2238
+ // SQLite / db 是页级原地覆盖:size 不变但中间页可能已改,全量分块读,避免采样漏检。
2239
+ const fd = openSync(file, 'r')
2240
+ try {
2241
+ const buf = Buffer.allocUnsafe(65536)
2242
+ let off = 0
2243
+ let n
2244
+ while ((n = readSync(fd, buf, 0, buf.length, off)) > 0) {
2245
+ h.update(n === buf.length ? buf : buf.subarray(0, n))
2246
+ off += n
2247
+ }
2248
+ } finally { closeSync(fd) }
2249
+ } else {
2250
+ const fd = openSync(file, 'r')
2251
+ try {
2252
+ const n = st.size
2253
+ if (n <= CONTENT_SAMPLE_BYTES) {
2254
+ const buf = Buffer.allocUnsafe(n)
2255
+ let off = 0
2256
+ while (off < n) off += readSync(fd, buf, off, Math.min(65536, n - off), off)
2257
+ h.update(buf)
2258
+ } else {
2259
+ // 大文件:头 128KB + 中 16KB + 尾 128KB,覆盖 zstd 帧头/checksum 与末尾事件
2260
+ const CHUNK = 131072
2261
+ const buf = Buffer.allocUnsafe(CHUNK)
2262
+ let off = 0
2263
+ while (off < CHUNK) off += readSync(fd, buf, off, Math.min(65536, CHUNK - off), off)
2264
+ h.update(buf)
2265
+ const mid = Buffer.allocUnsafe(16384)
2266
+ off = 0
2267
+ const midPos = Math.floor((n - 16384) / 2)
2268
+ while (off < mid.length) off += readSync(fd, mid, off, Math.min(8192, mid.length - off), midPos + off)
2269
+ h.update(mid)
2270
+ const tail = Buffer.allocUnsafe(CHUNK)
2271
+ off = 0
2272
+ while (off < tail.length) off += readSync(fd, tail, off, Math.min(65536, tail.length - off), n - CHUNK + off)
2273
+ h.update(tail)
2274
+ }
2275
+ } finally { closeSync(fd) }
2276
+ }
2277
+ return h.digest('hex')
2278
+ }
2279
+
2280
+ /**
2281
+ * 读取本机内容基线:{ lastSyncAt, files: { "<本机绝对路径(正斜杠)>": "<sha256>" }, pendingKeys: [...] }。
2282
+ * 只有记录的 lastSyncAt 与当前一致才有效;lastSyncAt 变化(完成一次同步)后视为过期,
2283
+ * 由 localPending 在扫描结束后重写基线,不依赖任何 ps1。
2284
+ * 旧基线(无 pendingKeys 字段)兼容为 []。
2285
+ */
2286
+ function readContentBaseline(dshHome, since) {
2287
+ const p = join(dshHome, CONTENT_BASELINE_NAME)
2288
+ try {
2289
+ const parsed = JSON.parse(readFileSync(p, 'utf8'))
2290
+ // complete 必须是上一次完整扫描写出的;超时/超限的半截基线不采纳,下次重建。
2291
+ if (parsed && parsed.complete === true && parsed.lastSyncAt === since && parsed.files && typeof parsed.files === 'object' && !Array.isArray(parsed.files)) {
2292
+ return { path: p, lastSyncAt: parsed.lastSyncAt, complete: true, files: parsed.files, pendingKeys: Array.isArray(parsed.pendingKeys) ? parsed.pendingKeys : [] }
2293
+ }
2294
+ } catch { }
2295
+ return { path: p, lastSyncAt: '', complete: false, files: {}, pendingKeys: [] }
2296
+ }
2297
+
2298
+ /** 把本次完整扫描到的指纹写回基线(含扫描到的所有文件,不只 mtime 变的那批)。 */
2299
+ function writeContentBaseline(baseline, since) {
2300
+ try {
2301
+ writeFileSync(baseline.path, JSON.stringify({ lastSyncAt: since, complete: true, at: Date.now(), files: baseline.files, pendingKeys: Array.isArray(baseline.pendingKeys) ? baseline.pendingKeys : [] }, null, 2) + '\n', 'utf8')
2302
+ } catch { /* 写不了就下次全量重建,功能不降级 */ }
2303
+ }
2304
+
2305
+ /** 本机绝对路径(统一正斜杠、去尾斜杠)作为基线 key,避免 capture 侧会话目录 remap 造成键不匹配。 */
2306
+ function contentKey(file) {
2307
+ return String(file).replace(/\\/g, '/').replace(/\/+$/, '')
2308
+ }
2309
+
2141
2310
  async function repoState(repo) {
2142
2311
  if (!repo || !isDir(join(repo, '.git'))) return { ahead: 0, dirty: 0 }
2143
2312
  const status = await git(repo, ['status', '--porcelain'])
@@ -3664,13 +3833,15 @@ async function handleAuto(req, res, config) {
3664
3833
  /** 核心判断逻辑:给定配置与仓库,判断是否需要自动拉取/推送,需要则排队 watcher(可选关闭 DSH)。
3665
3834
  * 供 scheduleAutoStart(定时)、triggerAutoSyncOnClose(关闭钩子)、handleSettings(开关即时触发)复用。 */
3666
3835
  async function checkAndQueueAutoSync(dshHome, config, settings, repo, appRoot, options = {}) {
3667
- const { skipConfirm = false, isManualTrigger = false, shouldCloseDsh = true, isPeriodic = false } = options
3836
+ const { skipConfirm = false, isManualTrigger = false, shouldCloseDsh = true, isPeriodic = false, driftOverride = null } = options
3668
3837
  // 已经排队等退出了就别重复拉起 watcher;但 watcher 已死(超时退出)时允许重排
3669
3838
  if (autoState.pending && isProcessAlive(autoState.pending.watcherPid)) return { queued: false, reason: 'already_pending' }
3670
3839
  if (!repo || !isDir(join(repo, '.git'))) {
3671
3840
  return { queued: false, reason: 'no_repo' }
3672
3841
  }
3673
- const drift = await checkDrift(repo)
3842
+ // 定时复查已在同一次 run 里 checkDrift 过(结果写进 autoState.drift),经 driftOverride 复用,
3843
+ // 避免几毫秒内对同一仓库重复 git fetch。未传时行为与原来完全一致(自行 fetch)。
3844
+ const drift = driftOverride || await checkDrift(repo)
3674
3845
  if (!drift) {
3675
3846
  return { queued: false, reason: 'drift_failed' }
3676
3847
  }
@@ -3720,6 +3891,7 @@ async function checkAndQueueAutoSync(dshHome, config, settings, repo, appRoot, o
3720
3891
  const restart = settings.autoRestart !== false
3721
3892
  const started = await spawnWatcher({ mode: 'push', repo, appRoot, dshHome, restart })
3722
3893
  if (started.ok) {
3894
+ // reason=旧版兜底文案,reasonZh/reasonEn=双语文案(前端按语言优先读双语、reason 兜底),三者是不同键,勿合并
3723
3895
  autoState.pending = { mode: 'push', at: Date.now(), reason: reasonZh, reasonZh, reasonEn, restart, watcherPid: started.pid, closeRequested: false }
3724
3896
  if (shouldCloseDsh) closeDsh()
3725
3897
  return { queued: true, mode: 'push', reason: reasonZh }
@@ -3763,7 +3935,8 @@ function scheduleAutoStart(config) {
3763
3935
  // (shouldCloseDsh:false)。用户点 × 关闭 DSH 后,预排的 watcher 自动进入 run 执行。
3764
3936
  // 前端信标仍保留作双保险:它若送达、发现已排队会直接复用,不会重复。
3765
3937
  const appRoot = resolveAppRoot(config?.appRoot) || ''
3766
- await checkAndQueueAutoSync(dshHome, config, settings, repo, appRoot, { shouldCloseDsh: false, isPeriodic: true })
3938
+ // 复用本次复查刚 fetch 的 drift,避免 checkAndQueueAutoSync 内二次 fetch(同一仓库、同一时刻)
3939
+ await checkAndQueueAutoSync(dshHome, config, settings, repo, appRoot, { shouldCloseDsh: false, isPeriodic: true, driftOverride: drift })
3767
3940
  } catch (error) {
3768
3941
  autoState.checking = false
3769
3942
  autoState.lastCheckAt = Date.now()
@@ -3807,6 +3980,8 @@ async function triggerAutoSyncOnClose(config, options = {}) {
3807
3980
  const phase = repoPhase(repo)
3808
3981
 
3809
3982
  // 本机仓库还没内容:autoPull 可以直接排队(sync.ps1 首次 clone),autoPush 不行(要先确认云端为空)
3983
+ // 注:关闭走的 fast 路径不探测 remoteFiles,这里沿用原 phase === 'empty' 判据;
3984
+ // inspect() 面板门禁已收敛到 canPull()(见文件上方),口径一致但此路径不额外 fetch,行为保持不变。
3810
3985
  if (phase !== 'ok') {
3811
3986
  if (settings.autoPull && phase === 'empty') {
3812
3987
  const restart = settings.autoRestart !== false
@@ -4329,13 +4504,8 @@ async function handleRoots(req, res, config) {
4329
4504
  const GH_DEFAULT_REPO = 'QcWyGm/dsh-config-sync-plugin'
4330
4505
  const GH_FEEDBACK_LABEL = 'feedback'
4331
4506
 
4332
- /** 当前插件版本(读自己的 package.json;读不到就空串,不抛)。 */
4333
- function pluginVersion() {
4334
- try {
4335
- const pkg = JSON.parse(readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'package.json'), 'utf8'))
4336
- return String(pkg.version || '')
4337
- } catch { return '' }
4338
- }
4507
+ /** 当前插件版本(同义包装,统一回到 PLUGIN_VERSION 这一份定义)。 */
4508
+ function pluginVersion() { return PLUGIN_VERSION }
4339
4509
 
4340
4510
  function ghPathOf(dshHome) { return join(dshHome, 'config-sync-gh.json') }
4341
4511
  function outboxPathOf(dshHome) { return join(dshHome, 'config-sync-feedback-outbox.json') }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-config-sync-plugin",
3
- "version": "0.4.10",
3
+ "version": "0.4.12",
4
4
  "type": "module",
5
5
  "description": "在 DSH 设置里查看 dsh-config 仓库与本机的同步状态,并生成退出后执行的 push/pull 脚本。同步动作本身不在应用内执行。面板与文案跟随客户端语言(中文/English)。",
6
6
  "main": "./index.js",
package/runtime/apply.ps1 CHANGED
@@ -48,6 +48,7 @@ param(
48
48
  [switch]$SkipWorkspace,
49
49
  [switch]$PruneWorkspace,
50
50
  [switch]$ReplaceWorkspaceRegistry,
51
+ # 已废弃:0.4.10 起默认放行版本差异,此开关不参与判据,仅为兼容旧调用保留
51
52
  [switch]$AllowVersionDrift,
52
53
  [switch]$ForceBundles,
53
54
  [string]$WorkspaceHome = $(Join-Path $env:USERPROFILE 'Documents\deepseek-harness'),
@@ -404,6 +405,7 @@ function Sync-WorkspaceApply {
404
405
  # sessions\ 一级目录名 = Get-SessionDirName(工作区绝对路径)。编码不可逆,所以 capture
405
406
  # 在 conversations\session-index.json 里记了「目录名 ↔ 工作区 ID」;apply 按本机
406
407
  # -AppRoot / -WorkspaceHome 展开后的路径重新编码目录名,B 机才能认出这些会话。
408
+ # 与另一文件同名函数保持一致,修改需同步
407
409
  function Get-SessionDirName([string]$path) {
408
410
  $sb = New-Object System.Text.StringBuilder
409
411
  [void]$sb.Append('--')
@@ -920,7 +922,7 @@ foreach ($b in $bundlesInRepo) {
920
922
  if ($b -notlike '@deepseek-ai/dsh-experimental-*') { continue }
921
923
  $why = $null
922
924
  if ($versionDrift) {
923
- $why = "本机 app 版本不同($hostAppVersion ≠ $contractVersion)"
925
+ $why = "本机 app 版本不同($hostAppVersion ≠ $contractVersion);仅剔除实验 bundle,不影响主流程"
924
926
  } else {
925
927
  # 宿主自带 bundle 的落点因构建而异:解包版在 resources\app\dsh\node_modules,
926
928
  # 打包版整包塞在 app.asar 里(磁盘上没有目录)——所以交给 Test-HostBundle 统一判断,别只查路径。
@@ -310,6 +310,7 @@ function Sync-WorkspaceCapture {
310
310
  # 绝不做文本替换(zstd 流无法替换;projcache 按 sessionId 索引,cwd 只是历史记录,B 机可读)。
311
311
  # sessions\ 一级目录名 = Get-SessionDirName(工作区绝对路径);该编码不可逆,所以 capture 用
312
312
  # 「已知工作区路径 → 编码 → 匹配目录名」建 dir ↔ workspaceId 映射,apply 再按本机路径重编码目录名。
313
+ # 与另一文件同名函数保持一致,修改需同步
313
314
  function Get-SessionDirName([string]$path) {
314
315
  $sb = New-Object System.Text.StringBuilder
315
316
  [void]$sb.Append('--')
@@ -588,7 +589,6 @@ function Sync-ConversationCapture {
588
589
  # 关键修复(2026-11-10):旧版正则把目录名写死成 DeepSeekHarness,客户端装在 D:\DSH 时归一化整体失效,
589
590
  # 本机绝对路径会被原样写进仓库 → 另一台 apply 后 lock 与 package.json 错位 → 安装半装 → 启动崩。
590
591
  # 现在先按本机 -AppRoot 的实际路径做字面替换(任意目录名、任意盘符),再用「末级目录名」正则兜底。
591
- $AppRootPattern = Get-AppRootPattern $AppRoot
592
592
 
593
593
  function Set-AppRootToken([string]$text) {
594
594
  return (Convert-AppRootText $text $AppRoot $AppRootToken)
@@ -712,7 +712,7 @@ function Get-PluginDataFiles([string]$slotDir, $cfg, [string]$baseDir = '') {
712
712
 
713
713
  # 必需组:不许取消勾选。理由都是"不勾就报错"这一个事实:
714
714
  # profile 里的 package.json / cordis.patch.yml 是 apply 的前置条件 —— 仓库缺它们,apply.ps1 直接 Die;
715
- # 同一组的 host-contract.json 是两端版本一致性校验,丢了它版本不一致也照铺,客户端可能起不来。
715
+ # 同一组的 host-contract.json 用于实验 bundle 门控;版本差异不再阻断,只提示,不会因此拒绝铺配置。
716
716
  # 所以这里(以及面板)都把 profile 钉死为开启,手改 JSON 关掉也按开启处理。
717
717
  $SyncRequiredGroups = @('profile')
718
718
 
@@ -46,35 +46,33 @@ $ProfileDir = Join-Path $DshHome ('profiles\' + $ProfileName)
46
46
  $ProfileFiles = @('package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml')
47
47
  $HomeFiles = @('AGENTS.md', 'prompt-inject.md')
48
48
 
49
- # 客户端根:没传就按常见安装位置探测,判据是存在 resources\app\package.json
49
+ # 客户端根:优先复用主链路 Resolve-DshAppRoot(显式参数 → $env:DSH_APP_ROOT → 注册表 → 多盘候选);
50
+ # 实在找不到时保留 restore 原有的 D:\DeepSeekHarness 默认路径兜底,避免旧行为报错。
50
51
  function Resolve-AppRoot([string]$explicit) {
51
- $cands = @()
52
- if ($explicit) { $cands += $explicit }
53
- $cands += @('D:\DeepSeekHarness', 'D:\DSH', 'G:\DSH', 'G:\DeepSeekHarness', 'C:\DeepSeekHarness')
54
- foreach ($c in $cands) {
55
- if (Test-Path -LiteralPath (Join-Path $c 'resources\app\package.json')) { return $c }
56
- }
52
+ $resolved = Resolve-DshAppRoot $explicit
53
+ if ($resolved) { return $resolved }
57
54
  if ($explicit) { return $explicit }
58
55
  return 'D:\DeepSeekHarness'
59
56
  }
60
57
 
61
58
  # git 位置探测统一在 dsh-sync-common.ps1 里(Get-GitExe),restore 允许找不到(只影响 pnpm 安装步骤)
62
59
 
63
- # 按 profile\package.json 的 bundles 逐项查能否解析(profile\node_modules 优先,再宿主自带 node_modules)
60
+ # 按 profile\package.json 的 bundles 逐项查能否解析(profile\node_modules 优先,再宿主磁盘/asar)
61
+ # 宿主侧统一交给 Test-HostBundle:它同时查 resources\app\dsh\node_modules 与 resources\app.asar,
62
+ # 打包版宿主不再因为 asar 里的 bundle 被误报为缺失。
64
63
  function Get-UnresolvedBundles {
65
64
  $missing = New-Object System.Collections.ArrayList
66
65
  $pkgPath = Join-Path $ProfileDir 'package.json'
67
66
  if (-not (Test-Path -LiteralPath $pkgPath)) { return $missing }
68
67
  try { $pkg = Get-Content -LiteralPath $pkgPath -Raw -Encoding utf8 | ConvertFrom-Json } catch { return $missing }
69
68
  $bundles = @($pkg.dsh.profile.bundles)
70
- $roots = @((Join-Path $ProfileDir 'node_modules'), (Join-Path $AppRoot 'resources\app\dsh\node_modules'))
69
+ $profileModules = Join-Path $ProfileDir 'node_modules'
71
70
  foreach ($b in $bundles) {
72
71
  if ([string]::IsNullOrWhiteSpace($b)) { continue }
73
72
  $rel = [string]($b -replace '/', '\')
74
73
  $found = $false
75
- foreach ($r in $roots) {
76
- if (Test-Path -LiteralPath (Join-Path $r (Join-Path $rel 'package.json'))) { $found = $true; break }
77
- }
74
+ if (Test-Path -LiteralPath (Join-Path $profileModules (Join-Path $rel 'package.json'))) { $found = $true }
75
+ if (-not $found -and (Test-HostBundle $AppRoot $b)) { $found = $true }
78
76
  if (-not $found) { [void]$missing.Add($b) }
79
77
  }
80
78
  return $missing
@@ -501,7 +499,7 @@ if (Test-Path -LiteralPath $contractPath) {
501
499
  }
502
500
  Say " 本机 app 版本:$localVer;仓库契约:$contractVer"
503
501
  if ($localVer -and $contractVer -and $localVer -ne $contractVer) {
504
- Warn "两端版本不一致:本机 $localVer,仓库契约 $contractVer。还原只修本机文件,拉起后仍可能在 pull 时被版本契约拦下(需升级本机,或 pull 加 -AllowVersionDrift)。"
502
+ Warn "两端版本不一致:本机 $localVer,仓库契约 $contractVer。0.4.10 起 pull 会放行版本差异,仅实验 bundle 按契约剔除;如需完全一致请升级本机。"
505
503
  }
506
504
 
507
505
  $missing = @(Get-UnresolvedBundles)
package/runtime/sync.ps1 CHANGED
@@ -32,6 +32,7 @@ param(
32
32
  [switch]$WorkspaceOnly,
33
33
  [switch]$SkipWorkspace,
34
34
  [switch]$SkipInstall,
35
+ # 已废弃:0.4.10 起默认放行版本差异,此开关不参与判据,仅为兼容旧调用保留
35
36
  [switch]$AllowVersionDrift,
36
37
  # 推送前强制全量重扫历史里的超大文件(默认只在首次或推送被拒时才扫,省 20s)
37
38
  [switch]$ScanHistory,
@@ -567,7 +568,7 @@ function Get-RemoteFileCount([string]$RemoteUrl, [int]$Heads = -2) {
567
568
  初始化推送:本机空目录 + 云端空仓库,把本机配置当作仓库的初始内容推上去。
568
569
  骨架要一起带进仓库 —— 历史仓库本来就有 apply.ps1 / capture.ps1 / dsh-sync-common.ps1 这几份副本,
569
570
  少拷了它们,远端就变成「只有 settings 没有执行体」的半截仓库,另一台 pull 下来跑不起来。
570
- profile\host-contract.json 用本机客户端版本生成(apply 靠它校验两端版本,缺了只会跳过校验)。
571
+ profile\host-contract.json 用本机客户端版本生成(apply 仅用于实验 bundle 门控;版本差异不再阻断,只提示)。
571
572
  #>
572
573
  function Initialize-EmptyRepo([string]$RemoteUrl) {
573
574
  if (-not $RemoteUrl) {
@@ -1109,6 +1110,7 @@ $applyArgs = @{ RepoRoot = $RepoRoot; DshHome = $DshHome; ProfileName = $Profile
1109
1110
  if ($WorkspaceOnly) { $applyArgs['WorkspaceOnly'] = $true }
1110
1111
  if ($SkipWorkspace) { $applyArgs['SkipWorkspace'] = $true }
1111
1112
  if ($SkipInstall) { $applyArgs['SkipInstall'] = $true }
1113
+ # AllowVersionDrift 已废弃;apply.ps1 从 0.4.10 起忽略版本差异门控,这里仅为兼容旧调用继续透传
1112
1114
  if ($AllowVersionDrift) { $applyArgs['AllowVersionDrift'] = $true }
1113
1115
  if ($Force) { $applyArgs['Force'] = $true }
1114
1116
  & (Join-Path $PSScriptRoot 'apply.ps1') @applyArgs
@@ -122,9 +122,10 @@ check('设置摘要行展开时 fetch 远端再刷新(远端信息不陈旧)
122
122
  && source.includes("callAuto({ action: 'check' })")
123
123
  && source.includes('setInterval(refreshRemoteNow, 30000)')
124
124
  && source.includes('onClick: refreshRemoteNow'))
125
+ // 0.4.11 等价重构:dirty/uncommitted 读取口径统一抽成 uncommittedOf() helper
125
126
  check('远端「未提交」纳入本机待同步、刷新按钮触发 fetch(0.3.92)',
126
- source.includes('repo.uncommitted ?? repo.dirty')
127
- && source.includes('data.repo.uncommitted ?? data.repo.dirty')
127
+ source.includes('const uncommittedOf = (repo) => (repo?.uncommitted ?? repo?.dirty ?? 0)')
128
+ && source.includes('uncommittedOf(data.repo)')
128
129
  && source.includes('本机待同步 ${data.repo.pending}'))
129
130
  check('设置摘要行两个立即按钮走 pull-now / push-now 队列',
130
131
  source.includes("actNow('pull-now')")
@@ -40,9 +40,17 @@ try {
40
40
  $from = Join-Path $RepoRoot $item
41
41
  if (Test-Path -LiteralPath $from) { Copy-Item -LiteralPath $from -Destination (Join-Path $pkgDir $item) -Recurse }
42
42
  }
43
- # 排除 .git 目录(避免把仓库对象/历史打进 tgz,导致体积爆炸)
44
- Get-ChildItem -LiteralPath $pkgDir -Recurse -Directory -Force -ErrorAction SilentlyContinue |
45
- Where-Object { $_.Name -eq '.git' } |
43
+ # 排除 .git 与临时/备份目录、文件(避免把仓库对象、历史或 apply.ps1.bak-0410 之类临时备份打进 tgz)
44
+ $excludedDirNames = @('.git', '_stage-*', '_v4*', '_refactor-*', '_local-backup-*', '_pre-sync-*')
45
+ $excludedFilePatterns = @('*.bak*', '*.tmp')
46
+ Get-ChildItem -LiteralPath $pkgDir -Recurse -Force -ErrorAction SilentlyContinue |
47
+ Where-Object {
48
+ $hitDir = $false
49
+ foreach ($pattern in $excludedDirNames) { if ($_.PSIsContainer -and $_.Name -like $pattern) { $hitDir = $true; break } }
50
+ $hitFile = $false
51
+ foreach ($pattern in $excludedFilePatterns) { if (-not $_.PSIsContainer -and $_.Name -like $pattern) { $hitFile = $true; break } }
52
+ $hitDir -or $hitFile
53
+ } |
46
54
  ForEach-Object { Remove-Item -LiteralPath $_.FullName -Recurse -Force -ErrorAction SilentlyContinue }
47
55
  # package.json 必须带进包(npm 装包靠它认入口)
48
56
  Copy-Item -LiteralPath $pkgFile -Destination (Join-Path $pkgDir 'package.json') -Force