dsh-profile-config-sync 0.6.46 → 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.
- package/README.en.md +51 -7
- package/README.md +66 -17
- package/client.js +258 -155
- package/docs/CHANGELOG.md +6 -4
- package/docs/REFERENCE.md +39 -3
- package/index.js +1080 -351
- package/package.json +6 -4
- package/release-notes.json +7 -0
- package/runtime/contract.mjs +10 -3
- package/runtime/conversations.mjs +433 -0
- package/runtime/extra-rules.mjs +238 -0
- package/runtime/install-plugin.mjs +279 -0
- package/runtime/install-plugin.ps1 +60 -1
- package/runtime/platform.mjs +198 -5
- package/runtime/porting.mjs +319 -0
- package/runtime/post-exit.mjs +347 -0
- package/runtime/post-exit.ps1 +80 -1
- package/runtime/settings-sources.mjs +46 -0
- package/runtime/sync-engine.mjs +1190 -52
- package/runtime/webdav.mjs +247 -24
- package/runtime/zip.mjs +156 -0
package/runtime/sync-engine.mjs
CHANGED
|
@@ -15,21 +15,30 @@
|
|
|
15
15
|
|
|
16
16
|
import { spawnSync } from 'node:child_process'
|
|
17
17
|
import {
|
|
18
|
-
closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync,
|
|
19
|
-
readSync, renameSync, rmSync, statSync, writeFileSync, lstatSync,
|
|
18
|
+
closeSync, copyFileSync, cpSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync,
|
|
19
|
+
readSync, realpathSync, renameSync, rmSync, statSync, writeFileSync, lstatSync,
|
|
20
20
|
} from 'node:fs'
|
|
21
21
|
import { createHash } from 'node:crypto'
|
|
22
22
|
import { homedir, hostname } from 'node:os'
|
|
23
|
-
import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path'
|
|
23
|
+
import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path'
|
|
24
24
|
import { fileURLToPath } from 'node:url'
|
|
25
25
|
|
|
26
26
|
import {
|
|
27
|
-
IS_WIN, SEP, appRootCandidates, clientExecutable, dshHome as resolveDshHome,
|
|
27
|
+
IS_WIN, SEP, appRootCandidates, appRootLayout, clientExecutable, dshHome as resolveDshHome,
|
|
28
28
|
defaultWorkspaceHome, findGit, hostNodeExe, isAppRoot, isDir, isFile, platformFamily,
|
|
29
|
+
readAppVersion as platformAppVersion, readElectronVersion as platformElectronVersion,
|
|
29
30
|
} from './platform.mjs'
|
|
30
31
|
import { buildContract, checkContract, contractPath, contractText, readContract } from './contract.mjs'
|
|
31
32
|
import { listMachines, localMachineInfo, writeMachineInfo } from './machines.mjs'
|
|
32
|
-
import {
|
|
33
|
+
import {
|
|
34
|
+
downloadRepo, isSecureUrl, normalizeWebdav, testConnection, uploadRepo, webdavActive, purgeForbiddenFromCloud, purgeStaleLocksFromCloud,
|
|
35
|
+
PRIVATE_KEY_BODY_RE, SSH_KEY_NAME_RE,
|
|
36
|
+
} from './webdav.mjs'
|
|
37
|
+
import { applyConversations, captureConversations, conversationPendingRoots, resolveGuardScript } from './conversations.mjs'
|
|
38
|
+
import { extraSkipReason, listPluginDataSlots, looksSecretFile, readExtraConfig } from './extra-rules.mjs'
|
|
39
|
+
import { SETTINGS_SOURCES, settingsSourcePath, zeroVolatileFields } from './settings-sources.mjs'
|
|
40
|
+
import { zipBuild, zipExtract } from './zip.mjs'
|
|
41
|
+
import { portPackageJson, portWorkspaceRegistry, portAgentsMd, translatePortableText, translateWinPath, readPortConfig, portContext } from './porting.mjs'
|
|
33
42
|
|
|
34
43
|
/** 占位符:仓库里存这些,落地时展开成本机路径。 */
|
|
35
44
|
export const TOKENS = {
|
|
@@ -256,8 +265,8 @@ export function expandTokenText(text, roots) {
|
|
|
256
265
|
/** 文本里还残留哪些没配值的占位符(apply 用它决定「跳过并记 pending」)。 */
|
|
257
266
|
export function missingTokens(text) {
|
|
258
267
|
const found = new Set()
|
|
259
|
-
// 名字放宽到「除花括号/空白之外任意字符」:用户的自选根 key 可能是中文({{ROOT:资料}}),
|
|
260
|
-
// 只认 ASCII 会让这种占位符既不被识别、也不被跳过,最终把字面量写进目标机配置。
|
|
268
|
+
// 名字放宽到「除花括号/空白之外任意字符」:用户的自选根 key 可能是中文({{ROOT:资料}}),
|
|
269
|
+
// 只认 ASCII 会让这种占位符既不被识别、也不被跳过,最终把字面量写进目标机配置。
|
|
261
270
|
const re = /\{\{(APP_ROOT|DSH_HOME|WORKSPACE_HOME|ROOT:[^{}\s]+)\}\}/g
|
|
262
271
|
let m
|
|
263
272
|
while ((m = re.exec(String(text))) !== null) found.add(m[0])
|
|
@@ -305,9 +314,14 @@ const GH_TOKEN_RE = /gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}/
|
|
|
305
314
|
function hasSecretLeak(name, text) {
|
|
306
315
|
const leaf = String(name || '').toLowerCase()
|
|
307
316
|
if (PRIVATE_FILE_NAMES.has(leaf) || leaf.startsWith('.env.') || /\.(pem|key|p12|pfx)$/.test(leaf)) return true
|
|
317
|
+
// 0.6.49:裸名私钥(ssh-keygen 默认产物 id_ed25519 / id_rsa / *.ppk)原来拦不住 ——
|
|
318
|
+
// 既没有 .key 后缀也不在名单里。判据与 webdav.mjs 共用同一份正则,避免两边漂移。
|
|
319
|
+
if (SSH_KEY_NAME_RE.test(leaf)) return true
|
|
308
320
|
if (String(name || '').split('/').some((seg) => BLOCKED_ENGINE_SEGMENTS.has(String(seg).toLowerCase()))) return true
|
|
309
321
|
if (typeof text === 'string' && text) {
|
|
310
322
|
if (GH_TOKEN_RE.test(text)) return true
|
|
323
|
+
// 改名/塞进别处的私钥:认 PEM / PuTTY 私钥头(与 webdav.mjs 共用)
|
|
324
|
+
if (PRIVATE_KEY_BODY_RE.test(text)) return true
|
|
311
325
|
for (const envName of ['DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']) {
|
|
312
326
|
const val = String(process.env[envName] || '').trim()
|
|
313
327
|
if (val.length >= 12 && text.includes(val)) return true
|
|
@@ -368,11 +382,16 @@ export function copyWithTokens(src, dst, roots) {
|
|
|
368
382
|
const binary = isBinaryName(name) || !isTextName(name)
|
|
369
383
|
mkdirSync(dirname(dst), { recursive: true })
|
|
370
384
|
if (binary) {
|
|
385
|
+
// 内容一致就别重写:否则每次 capture 都刷一遍 mtime,还谎报「本轮改了 N 个文件」
|
|
386
|
+
try { if (existsSync(dst) && fileHash(src) === fileHash(dst)) return { files: 0, bytes: 0 } } catch { /* 比不了就照写 */ }
|
|
371
387
|
copyFileSync(src, dst)
|
|
372
388
|
return { files: 1, bytes: st.size }
|
|
373
389
|
}
|
|
374
390
|
const text = readFileSync(src, 'utf8')
|
|
375
391
|
const out = toTokenText(text, roots).replace(/\r\n/g, '\n')
|
|
392
|
+
// 文本按「归一化后的内容」比对(占位符化 + LF),相同就不写。0.6.49 之前无条件写:
|
|
393
|
+
// 于是 profile/package.json 这类文件每次 capture 都报「有改动」,面板与提交都被噪声污染。
|
|
394
|
+
try { if (existsSync(dst) && readFileSync(dst, 'utf8') === out) return { files: 0, bytes: 0 } } catch { /* 比不了就照写 */ }
|
|
376
395
|
writeFileSync(dst, out, 'utf8')
|
|
377
396
|
return { files: 1, bytes: Buffer.byteLength(out, 'utf8') }
|
|
378
397
|
}
|
|
@@ -463,11 +482,10 @@ export function diffTrees(a, b) {
|
|
|
463
482
|
*/
|
|
464
483
|
export function readAppVersion(appRoot) {
|
|
465
484
|
if (!appRoot) return ''
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
return readAsarPackageVersion(join(appRoot, 'resources', 'app.asar'))
|
|
485
|
+
// 0.6.49:resources 的位置随平台变(macOS 在 <root>/Contents/Resources),
|
|
486
|
+
// 统一交给 platform.mjs —— 原来这里写死 <root>/resources,macOS 上恒为空,
|
|
487
|
+
// 于是契约里的 appVersion 一直空着、版本校验形同虚设。
|
|
488
|
+
return platformAppVersion(appRoot)
|
|
471
489
|
}
|
|
472
490
|
|
|
473
491
|
/** 直接从 asar 二进制里取 dsh/package.json 的 version(不依赖 asar 挂载)。 */
|
|
@@ -498,13 +516,9 @@ function readAsarPackageVersion(asarPath) {
|
|
|
498
516
|
}
|
|
499
517
|
}
|
|
500
518
|
|
|
501
|
-
/** Electron 版本(客户端根下的 version
|
|
519
|
+
/** Electron 版本(客户端根下的 version 文件;macOS 走 .app 内 Framework 的 Info.plist)。 */
|
|
502
520
|
export function readElectronVersion(appRoot) {
|
|
503
|
-
|
|
504
|
-
try {
|
|
505
|
-
const v = readFileSync(join(appRoot, 'version'), 'utf8').trim()
|
|
506
|
-
return v || ''
|
|
507
|
-
} catch { return '' }
|
|
521
|
+
return platformElectronVersion(appRoot)
|
|
508
522
|
}
|
|
509
523
|
|
|
510
524
|
function readJsonSafe(path) {
|
|
@@ -575,6 +589,333 @@ export function probeLocal({ dshHome, appRoot, workspaceHome } = {}) {
|
|
|
575
589
|
*
|
|
576
590
|
* 返回 { ok, changed:[], files, bytes, errors:[] }。
|
|
577
591
|
*/
|
|
592
|
+
/**
|
|
593
|
+
* 一个「槽」(插件数据槽 / 额外路径目录)的镜像:按规则过滤 → 拷进仓库 → 删掉本机已经不存在的。
|
|
594
|
+
*
|
|
595
|
+
* 规则用的是 runtime/extra-rules.mjs(与面板、与 PowerShell 同一份):
|
|
596
|
+
* 单文件上限、排除通配、凭据(名字 + 内容)、符号链接不跟。
|
|
597
|
+
*/
|
|
598
|
+
function mirrorSlotInto({ srcRoot, dstRoot, cfg, roots, label }) {
|
|
599
|
+
const out = { files: 0, bytes: 0, changed: [], errors: [], notes: [] }
|
|
600
|
+
const wanted = new Map()
|
|
601
|
+
for (const f of walk(srcRoot)) {
|
|
602
|
+
let st
|
|
603
|
+
try { st = statSync(f.full) } catch { continue }
|
|
604
|
+
const why = extraSkipReason(f.rel, st.size, cfg)
|
|
605
|
+
if (why === 'too-big') { out.notes.push(`${label}/${f.rel}: 超过单文件上限,未进仓库`); continue }
|
|
606
|
+
if (why) continue
|
|
607
|
+
if (looksSecretFile(f.full, f.rel)) { out.notes.push(`${label}/${f.rel}: 像是凭据文件,已跳过`); continue }
|
|
608
|
+
wanted.set(f.rel, { full: f.full, size: st.size })
|
|
609
|
+
}
|
|
610
|
+
for (const [rel, info] of wanted) {
|
|
611
|
+
const dst = join(dstRoot, ...rel.split('/'))
|
|
612
|
+
try {
|
|
613
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
614
|
+
// copyWithTokens 自己会按「归一化后的内容」比对,相同就不写并返回 files:0
|
|
615
|
+
const w = copyWithTokens(info.full, dst, roots)
|
|
616
|
+
if (w.files > 0) {
|
|
617
|
+
out.files += w.files
|
|
618
|
+
out.bytes += w.bytes
|
|
619
|
+
out.changed.push(`${label}/${rel}`)
|
|
620
|
+
}
|
|
621
|
+
} catch (e) {
|
|
622
|
+
out.errors.push(`${label}/${rel}: ${(e && e.message) || e}`)
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
// 镜像删除:本机已经没有的,仓库里也删(否则换机会把删掉的文件铺回来)
|
|
626
|
+
for (const f of walk(dstRoot)) {
|
|
627
|
+
if (wanted.has(f.rel)) continue
|
|
628
|
+
try {
|
|
629
|
+
rmSync(f.full, { force: true })
|
|
630
|
+
out.changed.push(`${label}/${f.rel}(删除)`)
|
|
631
|
+
} catch (e) {
|
|
632
|
+
out.errors.push(`删除 ${label}/${f.rel} 失败:${(e && e.message) || e}`)
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
return out
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
|
|
639
|
+
/** 插件数据组(<DshHome> 一级目录,跳过规则里的系统目录与隐藏目录)。 */
|
|
640
|
+
function capturePluginData({ repoRoot, dshHome, cfg, scope, roots }) {
|
|
641
|
+
const dstRoot = join(repoRoot, 'plugin-data')
|
|
642
|
+
const result = { files: 0, bytes: 0, changed: [], errors: [], notes: [] }
|
|
643
|
+
if (!cfg || cfg.pluginData.enabled === false) {
|
|
644
|
+
result.notes.push('插件数据:已在 config-sync-extra.json 里关闭(pluginData.enabled=false),跳过')
|
|
645
|
+
return result
|
|
646
|
+
}
|
|
647
|
+
mkdirSync(dstRoot, { recursive: true })
|
|
648
|
+
const slots = []
|
|
649
|
+
for (const slot of listPluginDataSlots(dshHome, cfg)) {
|
|
650
|
+
if (!scopeItemEnabled(scope, 'plugin-data', slot.id)) { result.notes.push(`插件数据 ${slot.id}: 未勾选`); continue }
|
|
651
|
+
const r = mirrorSlotInto({ srcRoot: slot.src, dstRoot: join(dstRoot, slot.id), cfg, roots, label: `plugin-data/${slot.id}` })
|
|
652
|
+
result.files += r.files
|
|
653
|
+
result.bytes += r.bytes
|
|
654
|
+
result.changed.push(...r.changed)
|
|
655
|
+
result.errors.push(...r.errors)
|
|
656
|
+
result.notes.push(...r.notes)
|
|
657
|
+
slots.push({ id: slot.id, src: toTokenText(slot.src, roots) })
|
|
658
|
+
}
|
|
659
|
+
// manifest 不写时间戳:写了每次抓取都会产生假改动
|
|
660
|
+
const text = JSON.stringify({ version: 1, slots }, null, 2)
|
|
661
|
+
const mp = join(dstRoot, 'manifest.json')
|
|
662
|
+
let before = ''
|
|
663
|
+
try { before = readFileSync(mp, 'utf8') } catch { /* 没有就写 */ }
|
|
664
|
+
if (before !== text) {
|
|
665
|
+
writeFileSync(mp, text, 'utf8')
|
|
666
|
+
result.changed.push('plugin-data/manifest.json')
|
|
667
|
+
}
|
|
668
|
+
return result
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/** 额外路径组(用户在面板里自己填的文件 / 目录)。 */
|
|
672
|
+
function captureExtraPaths({ repoRoot, dshHome, cfg, scope, roots }) {
|
|
673
|
+
const dstRoot = join(repoRoot, 'extra')
|
|
674
|
+
const result = { files: 0, bytes: 0, changed: [], errors: [], notes: [] }
|
|
675
|
+
if (!cfg || cfg.extra.enabled === false) {
|
|
676
|
+
result.notes.push('额外路径:已在 config-sync-extra.json 里关闭(extra.enabled=false),跳过')
|
|
677
|
+
return result
|
|
678
|
+
}
|
|
679
|
+
const paths = (cfg.extra && cfg.extra.paths) || []
|
|
680
|
+
if (!paths.length) { result.notes.push('额外路径:没有登记任何路径'); return result }
|
|
681
|
+
mkdirSync(dstRoot, { recursive: true })
|
|
682
|
+
for (const p of paths) {
|
|
683
|
+
if (!scopeItemEnabled(scope, 'extra', p.id)) { result.notes.push(`额外路径 ${p.id}: 未勾选`); continue }
|
|
684
|
+
if (!existsSync(p.src)) { result.notes.push(`额外路径本机不存在,跳过:${p.src}`); continue }
|
|
685
|
+
const isDir = isDir2(p.src)
|
|
686
|
+
const label = `extra/${p.id}`
|
|
687
|
+
if (!toTokenText(p.src, roots).includes('{{')) {
|
|
688
|
+
result.notes.push(`额外路径不在已知根下(换机可能对不上):${p.src}`)
|
|
689
|
+
}
|
|
690
|
+
if (isDir) {
|
|
691
|
+
const r = mirrorSlotInto({ srcRoot: p.src, dstRoot: join(dstRoot, p.id), cfg, roots, label })
|
|
692
|
+
result.files += r.files
|
|
693
|
+
result.bytes += r.bytes
|
|
694
|
+
result.changed.push(...r.changed)
|
|
695
|
+
result.errors.push(...r.errors)
|
|
696
|
+
result.notes.push(...r.notes)
|
|
697
|
+
} else {
|
|
698
|
+
if (looksSecretFile(p.src, basename(p.src))) { result.notes.push(`额外路径 ${p.id}: 像凭据文件,已跳过`); continue }
|
|
699
|
+
const ext = p.src.includes('.') ? p.src.slice(p.src.lastIndexOf('.')) : ''
|
|
700
|
+
const dst = join(dstRoot, `${p.id}${ext}`)
|
|
701
|
+
try {
|
|
702
|
+
const st = statSync(p.src)
|
|
703
|
+
const same = existsSync(dst) && fileHash(p.src) === fileHash(dst)
|
|
704
|
+
if (!same) {
|
|
705
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
706
|
+
copyWithTokens(p.src, dst, roots)
|
|
707
|
+
result.files += 1
|
|
708
|
+
result.bytes += st.size
|
|
709
|
+
result.changed.push(`${label}${ext}`)
|
|
710
|
+
}
|
|
711
|
+
} catch (e) {
|
|
712
|
+
result.errors.push(`${label}: ${(e && e.message) || e}`)
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
return result
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
function isDir2(p) { try { return statSync(p).isDirectory() } catch { return false } }
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* 平台分区(0.6.49):同一份仓库要能让 Windows / macOS / Linux 三个客户端各自还原,
|
|
723
|
+
* 所以**机器相关**的文件按平台分目录存,互不覆盖:
|
|
724
|
+
*
|
|
725
|
+
* profile/darwin/package.json profile/win32/package.json profile/linux/...
|
|
726
|
+
* prompt/darwin/AGENTS.md ...
|
|
727
|
+
* settings/darwin/dsh-workspaces.json ...
|
|
728
|
+
*
|
|
729
|
+
* 其它(skills / plugin-data / settings 里与路径无关的 / 会话 / 工作区登记表)仍然共用一份。
|
|
730
|
+
* 根目录那份 profile/package.json 是老版本(Windows 0.6.47 的 PowerShell 引擎)写的位置:
|
|
731
|
+
* 我们只读不写,避免两边互相覆盖 —— 老客户端继续读它自己的那份,谁也不打扰谁。
|
|
732
|
+
*/
|
|
733
|
+
const PLATFORM_LANE = process.platform
|
|
734
|
+
|
|
735
|
+
/** 机器相关的仓库相对路径 → 带平台分区的那份:profile/package.json → profile/darwin/package.json */
|
|
736
|
+
function lanePathOf(rel) {
|
|
737
|
+
const i = String(rel).indexOf('/')
|
|
738
|
+
if (i < 0) return `${PLATFORM_LANE}/${rel}`
|
|
739
|
+
return `${rel.slice(0, i)}/${PLATFORM_LANE}/${rel.slice(i + 1)}`
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
/**
|
|
743
|
+
* 读的时候先看本平台分区,再看根目录那份老位置。
|
|
744
|
+
* 返回 { rel, lane } 或 null。
|
|
745
|
+
*/
|
|
746
|
+
function pickRepoRel(repoRoot, rel) {
|
|
747
|
+
const laned = lanePathOf(rel)
|
|
748
|
+
if (existsSync(join(repoRoot, fromRepoPath(laned)))) return { rel: laned, lane: true }
|
|
749
|
+
if (existsSync(join(repoRoot, fromRepoPath(rel)))) return { rel, lane: false }
|
|
750
|
+
return null
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** 这些设置文件里写着绝对路径(工作区根),三端不能共用一份 → 按平台分区存。 */
|
|
754
|
+
const LANED_SETTINGS = new Set(['dsh-workspaces.json', 'dsh-qq-workspaces.json', 'workspace-archives.json'])
|
|
755
|
+
|
|
756
|
+
/** 本地源码插件打包时跳过的目录段(与 capture.ps1 的 $skipSegs 一致)。 */
|
|
757
|
+
const LOCAL_PLUGIN_SKIP_SEGS = new Set(['.git', 'node_modules', 'releases', '.cache'])
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* 本地源码插件(profile 里 `link:` 指向的那几个目录)→ `local-plugins/<名字>.zip`。
|
|
761
|
+
*
|
|
762
|
+
* 为什么打包而不是拷目录:换台机器的路径肯定不同,`link:` 是绝对路径;
|
|
763
|
+
* 打成 zip 之后对方解出来自己重新 link。Windows 侧用 Expand-Archive 解,所以必须是 zip。
|
|
764
|
+
*/
|
|
765
|
+
function captureLocalPlugins({ repoRoot, profileDir, dshHome, scope }) {
|
|
766
|
+
const dstRoot = join(repoRoot, 'local-plugins')
|
|
767
|
+
const result = { files: 0, bytes: 0, changed: [], errors: [], notes: [] }
|
|
768
|
+
const pkgPath = join(profileDir, 'package.json')
|
|
769
|
+
let deps = null
|
|
770
|
+
try { deps = JSON.parse(readFileSync(pkgPath, 'utf8')).dependencies } catch { deps = null }
|
|
771
|
+
if (!deps || typeof deps !== 'object') { result.notes.push('本机 profile 没有 package.json.dependencies,跳过本地插件'); return result }
|
|
772
|
+
const links = []
|
|
773
|
+
for (const [name, spec] of Object.entries(deps)) {
|
|
774
|
+
const raw = String(spec || '')
|
|
775
|
+
if (!raw.startsWith('link:')) continue
|
|
776
|
+
const target = raw.slice(5)
|
|
777
|
+
const abs = isAbsolute(target) ? target : join(profileDir, target)
|
|
778
|
+
links.push({ name, abs, dirName: basename(abs) })
|
|
779
|
+
}
|
|
780
|
+
if (!links.length) { result.notes.push('本机没有 link: 形式的本地源码插件'); return result }
|
|
781
|
+
mkdirSync(dstRoot, { recursive: true })
|
|
782
|
+
const kept = new Set()
|
|
783
|
+
for (const link of links) {
|
|
784
|
+
if (!scopeItemEnabled(scope, 'local-plugins', link.dirName)) { result.notes.push(`本地插件 ${link.dirName}: 未勾选`); continue }
|
|
785
|
+
if (!existsSync(link.abs)) { result.notes.push(`link 目标不存在,跳过:${link.abs}`); continue }
|
|
786
|
+
kept.add(`${link.dirName}.zip`)
|
|
787
|
+
const entries = []
|
|
788
|
+
for (const f of walk(link.abs)) {
|
|
789
|
+
const segs = f.rel.split('/')
|
|
790
|
+
if (segs.some((seg) => LOCAL_PLUGIN_SKIP_SEGS.has(seg.toLowerCase()))) continue
|
|
791
|
+
if (looksSecretFile(f.full, f.rel)) { result.notes.push(`本地插件 ${link.dirName} 跳过含凭据的文件:${f.rel}`); continue }
|
|
792
|
+
try { entries.push({ name: `${link.dirName}/${f.rel}`, data: readFileSync(f.full), mtime: statSync(f.full).mtime }) } catch { /* 读不了的跳过 */ }
|
|
793
|
+
}
|
|
794
|
+
if (!entries.some((e) => e.name === `${link.dirName}/package.json`)) {
|
|
795
|
+
result.errors.push(`本地插件 ${link.dirName}: 打包结果里没有 ${link.dirName}/package.json(跳过,避免换机解出坏目录)`)
|
|
796
|
+
continue
|
|
797
|
+
}
|
|
798
|
+
const zip = zipBuild(entries)
|
|
799
|
+
const dst = join(dstRoot, `${link.dirName}.zip`)
|
|
800
|
+
let same = false
|
|
801
|
+
// 比的是「要写下去的字节」:fileHash 对二进制按 sha256 算,这里也必须用 sha256(早先写了 sha1,永远不相等)
|
|
802
|
+
try { same = existsSync(dst) && fileHash(dst) === createHash('sha256').update(zip).digest('hex') } catch { same = false }
|
|
803
|
+
if (!same) {
|
|
804
|
+
writeFileSync(dst, zip)
|
|
805
|
+
result.changed.push(`local-plugins/${link.dirName}.zip`)
|
|
806
|
+
result.files += 1
|
|
807
|
+
result.bytes += zip.length
|
|
808
|
+
}
|
|
809
|
+
// 旧版发过 .tgz,留着会被另一台机器当成另一份插件
|
|
810
|
+
const staleTgz = join(dstRoot, `${link.dirName}.tgz`)
|
|
811
|
+
if (existsSync(staleTgz)) { try { rmSync(staleTgz, { force: true }); result.changed.push(`local-plugins/${link.dirName}.tgz(删除)`) } catch { /* 删不掉不影响 */ } }
|
|
812
|
+
}
|
|
813
|
+
// 镜像:当前 profile 里已经没有的 link 目标,其 zip 也删
|
|
814
|
+
let names = []
|
|
815
|
+
try { names = readdirSync(dstRoot, { withFileTypes: true }).filter((e) => e.isFile()).map((e) => e.name) } catch { names = [] }
|
|
816
|
+
for (const name of names) {
|
|
817
|
+
if (kept.has(name)) continue
|
|
818
|
+
try { rmSync(join(dstRoot, name), { force: true }); result.changed.push(`local-plugins/${name}(删除)`) } catch { /* 忽略 */ }
|
|
819
|
+
}
|
|
820
|
+
return result
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/** 工作区槽名:标题去掉 Windows 非法字符(与 capture.ps1 的 Get-SlotName 一致)。 */
|
|
824
|
+
function workspaceSlotName(title, id) {
|
|
825
|
+
let s = String(title || '').trim() || String(id || '')
|
|
826
|
+
s = s.replace(/[\\/:*?<>|]/g, '_').trim().replace(/\.+$/, '')
|
|
827
|
+
return s || String(id || '')
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
/**
|
|
831
|
+
* 工作区登记表(0.6.49 起 macOS/Linux 也同步)。
|
|
832
|
+
*
|
|
833
|
+
* **只同步登记表,不搬工作区里的文件树** —— 实测这台机器 5 个登记工作区里 `~/projects` 就 1.9 GB,
|
|
834
|
+
* 全搬进 git 仓库等于把 NAS 当网盘用,且推送一次要很久。登记表本身才是跨机要看的东西:
|
|
835
|
+
* 有哪些工作区、各自在哪、挂哪些会话、哪个是默认。
|
|
836
|
+
* 本机 DSH 自己会维护 `storages/workspace.json`,所以 apply 侧**不覆盖**它,只写一份旁路文件供参考。
|
|
837
|
+
*/
|
|
838
|
+
function captureWorkspaceRegistry({ repoRoot, dshHome, scope, roots }) {
|
|
839
|
+
const result = { files: 0, bytes: 0, changed: [], errors: [], notes: [] }
|
|
840
|
+
let reg = null
|
|
841
|
+
try { reg = JSON.parse(readFileSync(join(dshHome, 'storages', 'workspace.json'), 'utf8')) } catch { reg = null }
|
|
842
|
+
const table = reg && reg.tables && reg.tables.workspaces
|
|
843
|
+
if (!table || typeof table !== 'object') {
|
|
844
|
+
result.notes.push('本机没有工作区登记表(storages/workspace.json),跳过')
|
|
845
|
+
return result
|
|
846
|
+
}
|
|
847
|
+
const list = []
|
|
848
|
+
const usedSlots = new Map()
|
|
849
|
+
for (const [id, w] of Object.entries(table)) {
|
|
850
|
+
if (!w || typeof w !== 'object') continue
|
|
851
|
+
if (!scopeItemEnabled(scope, 'workspace', id)) { result.notes.push(`工作区 ${id}: 未勾选`); continue }
|
|
852
|
+
const title = typeof w.title === 'string' && w.title ? w.title : id
|
|
853
|
+
let slot = workspaceSlotName(title, id)
|
|
854
|
+
if (usedSlots.has(slot)) slot = workspaceSlotName(id, id)
|
|
855
|
+
let n = 1
|
|
856
|
+
while (usedSlots.has(slot)) { slot = `${workspaceSlotName(title, id)}-${n}`; n += 1 }
|
|
857
|
+
usedSlots.set(slot, true)
|
|
858
|
+
const ids = (v) => (Array.isArray(v) ? v.filter((x) => typeof x === 'string' && x) : [])
|
|
859
|
+
list.push({
|
|
860
|
+
id,
|
|
861
|
+
title,
|
|
862
|
+
slot,
|
|
863
|
+
path: typeof w.path === 'string' ? toTokenText(w.path, roots) : '',
|
|
864
|
+
sessionIds: ids(w.sessionIds),
|
|
865
|
+
archivedSessionIds: ids(w.archivedSessionIds),
|
|
866
|
+
pinnedSessionIds: ids(w.pinnedSessionIds),
|
|
867
|
+
createdAt: typeof w.createdAt === 'string' ? w.createdAt : '',
|
|
868
|
+
updatedAt: typeof w.updatedAt === 'string' ? w.updatedAt : '',
|
|
869
|
+
// 本机这条工作区占多少地方 —— 面板据此提醒「这组只同步登记表,不搬文件」
|
|
870
|
+
localFiles: countFilesQuick(w.path),
|
|
871
|
+
})
|
|
872
|
+
}
|
|
873
|
+
list.sort((a, b) => a.id.localeCompare(b.id))
|
|
874
|
+
const g = reg.global || {}
|
|
875
|
+
const manifest = {
|
|
876
|
+
unit: { name: 'dsh-workspace-sync', version: 1 },
|
|
877
|
+
mode: 'registry-only',
|
|
878
|
+
workspaces: list,
|
|
879
|
+
global: {
|
|
880
|
+
initialized: true,
|
|
881
|
+
defaultWorkspaceId: typeof g.defaultWorkspaceId === 'string' ? g.defaultWorkspaceId : '',
|
|
882
|
+
workspaceIds: list.map((x) => x.id),
|
|
883
|
+
archivedSessionIds: Array.isArray(g.archivedSessionIds) ? g.archivedSessionIds.filter((x) => typeof x === 'string' && x) : [],
|
|
884
|
+
pinnedSessionIds: Array.isArray(g.pinnedSessionIds) ? g.pinnedSessionIds.filter((x) => typeof x === 'string' && x) : [],
|
|
885
|
+
},
|
|
886
|
+
}
|
|
887
|
+
const text = JSON.stringify(manifest, null, 2) + '\n'
|
|
888
|
+
const dst = join(repoRoot, 'workspace', 'workspace-registry.json')
|
|
889
|
+
let before = ''
|
|
890
|
+
try { before = readFileSync(dst, 'utf8') } catch { /* 新文件 */ }
|
|
891
|
+
if (before !== text) {
|
|
892
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
893
|
+
writeFileSync(dst, text, 'utf8')
|
|
894
|
+
result.changed.push('workspace/workspace-registry.json')
|
|
895
|
+
result.files += 1
|
|
896
|
+
result.bytes += Buffer.byteLength(text, 'utf8')
|
|
897
|
+
}
|
|
898
|
+
result.notes.push(`工作区登记表:${list.length} 个工作区(只同步登记表,不搬工作区文件)`)
|
|
899
|
+
return result
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
/** 数一个目录里有多少文件(深度 3、上限 5000,只用来给面板显示体量,不做同步判断)。 */
|
|
903
|
+
function countFilesQuick(dir) {
|
|
904
|
+
if (!dir || !existsSync(dir)) return 0
|
|
905
|
+
let n = 0
|
|
906
|
+
const visit = (d, depth) => {
|
|
907
|
+
if (depth > 3 || n >= 5000) return
|
|
908
|
+
let entries = []
|
|
909
|
+
try { entries = readdirSync(d, { withFileTypes: true }) } catch { return }
|
|
910
|
+
for (const e of entries) {
|
|
911
|
+
if (n >= 5000) return
|
|
912
|
+
if (e.isDirectory()) { if (!SKIP_DIRS.has(e.name)) visit(join(d, e.name), depth + 1) } else if (e.isFile()) n += 1
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
visit(dir, 0)
|
|
916
|
+
return n
|
|
917
|
+
}
|
|
918
|
+
|
|
578
919
|
export function capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName = 'desktop' } = {}) {
|
|
579
920
|
const local = probeLocal({ dshHome, appRoot, workspaceHome })
|
|
580
921
|
// 用「用户确认过的根」(config-sync-roots.json):自选目录必须变成 {{ROOT:x}},
|
|
@@ -608,29 +949,89 @@ export function capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName
|
|
|
608
949
|
// 1) profile:本机 profile 目录(必需组,钉死开启)
|
|
609
950
|
const profileDir = join(local.dshHome, 'profiles', profileName)
|
|
610
951
|
if (isDir(profileDir)) {
|
|
611
|
-
|
|
612
|
-
copy(join(profileDir, '
|
|
613
|
-
copy(join(profileDir, '
|
|
614
|
-
copy(join(profileDir, '
|
|
952
|
+
// 机器相关的文件进本平台分区(profile/<platform>/...),根目录那份留给老客户端
|
|
953
|
+
copy(join(profileDir, 'package.json'), lanePathOf('profile/package.json'))
|
|
954
|
+
copy(join(profileDir, 'cordis.patch.yml'), lanePathOf('profile/cordis.patch.yml'))
|
|
955
|
+
copy(join(profileDir, 'package-lock.json'), lanePathOf('profile/package-lock.json'))
|
|
956
|
+
copy(join(profileDir, 'pnpm-lock.yaml'), lanePathOf('profile/pnpm-lock.yaml'))
|
|
957
|
+
// 0.6.49 补:`cordis.yml` 是「哪些插件开着」的名单、`pnpm-workspace.yaml` 是 hoisted 布局,
|
|
958
|
+
// 两者丢了换台机器就不是同一套插件。Windows 版一直抓这两个(capture.ps1 的 profile 文件表)。
|
|
959
|
+
copy(join(profileDir, 'cordis.yml'), lanePathOf('profile/cordis.yml'))
|
|
960
|
+
copy(join(profileDir, 'pnpm-workspace.yaml'), lanePathOf('profile/pnpm-workspace.yaml'))
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// 1.2) 插件设置与工作流(14 个插件各自的配置文件;散落在 <DshHome> 树里,不能整目录抓)
|
|
964
|
+
if (gated('settings')) skipScopedGroup(scope, repoRoot, 'settings', skippedByScope)
|
|
965
|
+
else {
|
|
966
|
+
try {
|
|
967
|
+
let wrote = 0
|
|
968
|
+
for (const entry of SETTINGS_SOURCES) {
|
|
969
|
+
if (gatedItem('settings', entry.id)) { skippedByScope.push(`settings/${entry.id}: 未勾选`); continue }
|
|
970
|
+
const src = settingsSourcePath(local.dshHome, profileDir, entry)
|
|
971
|
+
if (!existsSync(src)) continue
|
|
972
|
+
const setDir = LANED_SETTINGS.has(entry.id) ? join(repoRoot, 'settings', PLATFORM_LANE) : join(repoRoot, 'settings')
|
|
973
|
+
if (looksSecretFile(src, entry.id)) {
|
|
974
|
+
const stale = join(setDir, entry.id)
|
|
975
|
+
if (existsSync(stale)) { try { rmSync(stale, { force: true }); changed.push(`settings/${entry.id}(含凭据,已从仓库移除)`) } catch { /* 删不掉不影响其余 */ } }
|
|
976
|
+
skippedByScope.push(`settings/${entry.id}: 含令牌/凭据,已跳过(仓库里若有旧副本同时移除)`)
|
|
977
|
+
continue
|
|
978
|
+
}
|
|
979
|
+
{
|
|
980
|
+
const text = zeroVolatileFields(readFileSync(src, 'utf8'), entry.id)
|
|
981
|
+
const out = toTokenText(text, roots).replace(/\r\n/g, '\n')
|
|
982
|
+
const dst = join(setDir, entry.id)
|
|
983
|
+
let before = ''
|
|
984
|
+
try { before = readFileSync(dst, 'utf8') } catch { /* 新文件 */ }
|
|
985
|
+
if (before !== out) {
|
|
986
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
987
|
+
writeFileSync(dst, out, 'utf8')
|
|
988
|
+
// 标签写真实落点:分区的写 settings/<平台>/x.json,别再报成根目录那份(否则看日志会以为覆盖了老客户端)
|
|
989
|
+
changed.push(LANED_SETTINGS.has(entry.id) ? `settings/${PLATFORM_LANE}/${entry.id}` : `settings/${entry.id}`)
|
|
990
|
+
wrote += 1
|
|
991
|
+
}
|
|
992
|
+
files += 1
|
|
993
|
+
}
|
|
994
|
+
}
|
|
995
|
+
if (wrote === 0) skippedByScope.push('settings: 本机没有需要同步的插件设置文件(或全部无变化)')
|
|
996
|
+
} catch (e) {
|
|
997
|
+
errors.push(`settings: ${(e && e.message) || e}`)
|
|
998
|
+
}
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
// 1.5) 执行体:把 Node 引擎写进仓库根(Windows 版一直这么干,POSIX 之前漏了)
|
|
1002
|
+
try {
|
|
1003
|
+
const wrote = ensureRepoRunner(repoRoot)
|
|
1004
|
+
for (const name of wrote) changed.push(name)
|
|
1005
|
+
} catch (e) {
|
|
1006
|
+
errors.push(`runner: ${e && e.message ? e.message : e}`)
|
|
615
1007
|
}
|
|
616
1008
|
|
|
617
1009
|
// 2) 契约:记下本机实测版本 + 平台
|
|
618
1010
|
try {
|
|
619
1011
|
if (local.dshVersion) {
|
|
620
|
-
const existing = readContract(repoRoot)
|
|
1012
|
+
const existing = readContract(repoRoot, PLATFORM_LANE)
|
|
621
1013
|
const merged = buildContract({
|
|
622
1014
|
dshVersion: existing ? existing.appVersion : local.dshVersion,
|
|
623
1015
|
electronVersion: local.electronVersion,
|
|
624
1016
|
os: local.os, osFamily: local.osFamily, arch: local.arch,
|
|
625
1017
|
}, repoRoot)
|
|
626
1018
|
const text = contractText(merged)
|
|
627
|
-
const
|
|
1019
|
+
const laned = join(repoRoot, fromRepoPath(lanePathOf('profile/host-contract.json')))
|
|
628
1020
|
let before = ''
|
|
629
|
-
try { before = readFileSync(
|
|
1021
|
+
try { before = readFileSync(laned, 'utf8') } catch { /* 没有就写 */ }
|
|
630
1022
|
if (before !== text) {
|
|
631
|
-
mkdirSync(dirname(
|
|
632
|
-
writeFileSync(
|
|
633
|
-
changed.push('profile/host-contract.json')
|
|
1023
|
+
mkdirSync(dirname(laned), { recursive: true })
|
|
1024
|
+
writeFileSync(laned, text, 'utf8')
|
|
1025
|
+
changed.push(lanePathOf('profile/host-contract.json'))
|
|
1026
|
+
}
|
|
1027
|
+
// 根目录那份只补不改:老版本 PowerShell 引擎读的是它,别拿本平台的东西盖掉
|
|
1028
|
+
const rootContract = contractPath(repoRoot)
|
|
1029
|
+
if (!existsSync(rootContract)) {
|
|
1030
|
+
try {
|
|
1031
|
+
mkdirSync(dirname(rootContract), { recursive: true })
|
|
1032
|
+
writeFileSync(rootContract, text, 'utf8')
|
|
1033
|
+
changed.push('profile/host-contract.json(根目录首份)')
|
|
1034
|
+
} catch { /* 写不进去不影响同步 */ }
|
|
634
1035
|
}
|
|
635
1036
|
}
|
|
636
1037
|
} catch (e) {
|
|
@@ -641,7 +1042,9 @@ export function capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName
|
|
|
641
1042
|
if (gated('prompt')) skipScopedGroup(scope, repoRoot, 'prompt', skippedByScope)
|
|
642
1043
|
else {
|
|
643
1044
|
if (gatedItem('prompt', 'AGENTS.md')) skippedByScope.push('prompt/AGENTS.md: 未勾选')
|
|
644
|
-
|
|
1045
|
+
// 全局提示按平台分开存:里面写的是各系统的运行时路径与 shell 命令,
|
|
1046
|
+
// 共享一份的话 Mac 推一次就把 Windows 的 pwsh 路径换成了 macOS 的(反之亦然)。
|
|
1047
|
+
else copy(join(local.dshHome, 'AGENTS.md'), lanePathOf('prompt/AGENTS.md'))
|
|
645
1048
|
if (gatedItem('prompt', 'prompt-inject.md')) skippedByScope.push('prompt/prompt-inject.md: 未勾选')
|
|
646
1049
|
else copy(join(local.dshHome, 'prompt-inject.md'), 'prompt/prompt-inject.md')
|
|
647
1050
|
}
|
|
@@ -650,6 +1053,113 @@ export function capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName
|
|
|
650
1053
|
if (gated('presets')) skipScopedGroup(scope, repoRoot, 'presets', skippedByScope)
|
|
651
1054
|
else copy(join(local.dshHome, '.agent-presets'), 'presets')
|
|
652
1055
|
|
|
1056
|
+
// 3.5) 会话记录(0.6.49 起 Node 引擎也做,见 runtime/conversations.mjs):
|
|
1057
|
+
// 四块数据字节保真 + 仓库稳定目录名(--ws-<id>--)+ session-index.json;
|
|
1058
|
+
// 会话日志走 seq 护栏,避免两台机器各 append 一段后互相覆盖出 seq gap。
|
|
1059
|
+
if (gated('conversations')) skipScopedGroup(scope, repoRoot, 'conversations', skippedByScope)
|
|
1060
|
+
else {
|
|
1061
|
+
try {
|
|
1062
|
+
const conv = captureConversations({
|
|
1063
|
+
repoRoot,
|
|
1064
|
+
dshHome: local.dshHome,
|
|
1065
|
+
scope: scope.groups && typeof scope.groups === 'object' ? scope.groups.conversations : null,
|
|
1066
|
+
})
|
|
1067
|
+
files += conv.files
|
|
1068
|
+
bytes += conv.bytes
|
|
1069
|
+
changed.push(...conv.changed)
|
|
1070
|
+
errors.push(...conv.errors)
|
|
1071
|
+
for (const n of conv.notes) skippedByScope.push(`conversations: ${n}`)
|
|
1072
|
+
} catch (e) {
|
|
1073
|
+
errors.push(`conversations: ${(e && e.message) || e}`)
|
|
1074
|
+
}
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
// 3.3) 本地源码插件(profile 里 link: 指向的目录,打包成 zip 随仓库走)
|
|
1078
|
+
if (gated('local-plugins')) skipScopedGroup(scope, repoRoot, 'local-plugins', skippedByScope)
|
|
1079
|
+
else {
|
|
1080
|
+
try {
|
|
1081
|
+
const r = captureLocalPlugins({ repoRoot, profileDir, dshHome: local.dshHome, scope })
|
|
1082
|
+
files += r.files
|
|
1083
|
+
bytes += r.bytes
|
|
1084
|
+
changed.push(...r.changed)
|
|
1085
|
+
errors.push(...r.errors)
|
|
1086
|
+
for (const n of r.notes) skippedByScope.push(`local-plugins: ${n}`)
|
|
1087
|
+
} catch (e) {
|
|
1088
|
+
errors.push(`local-plugins: ${(e && e.message) || e}`)
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
// 3.4) 技能市场台账(两个小 json;装在 storages/@montersy123/dsh-skill-market/data 下)
|
|
1093
|
+
if (gated('storages-record')) skipScopedGroup(scope, repoRoot, 'storages-record', skippedByScope)
|
|
1094
|
+
else {
|
|
1095
|
+
const dataDir = join(local.dshHome, 'storages', '@montersy123', 'dsh-skill-market', 'data')
|
|
1096
|
+
const pairs = [['installed.json', 'skill-market-installed.json'], ['panel.json', 'skill-market-panel.json']]
|
|
1097
|
+
let any = false
|
|
1098
|
+
for (const [leaf, repoLeaf] of pairs) {
|
|
1099
|
+
if (gatedItem('storages-record', repoLeaf)) { skippedByScope.push(`storages-record/${repoLeaf}: 未勾选`); continue }
|
|
1100
|
+
if (!existsSync(join(dataDir, leaf))) continue
|
|
1101
|
+
copy(join(dataDir, leaf), `storages-record/${repoLeaf}`)
|
|
1102
|
+
any = true
|
|
1103
|
+
}
|
|
1104
|
+
if (!any) skippedByScope.push('storages-record: 本机没有技能市场台账(没装这个市场插件)')
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
// 3.45) 记忆数据:<AppRoot>/mnemon(记忆插件的数据目录,需要跨机一致)
|
|
1108
|
+
if (gated('mnemon')) skipScopedGroup(scope, repoRoot, 'mnemon', skippedByScope)
|
|
1109
|
+
else {
|
|
1110
|
+
const mnSrc = join(local.appRoot || '', 'mnemon')
|
|
1111
|
+
if (!local.appRoot || !existsSync(mnSrc)) {
|
|
1112
|
+
skippedByScope.push(`mnemon: 本机没有 ${mnSrc}(macOS 上记忆数据不在 .app 包内),跳过`)
|
|
1113
|
+
} else {
|
|
1114
|
+
copy(mnSrc, 'mnemon')
|
|
1115
|
+
// 镜像:本机已删的记忆文件仓库里也删(否则两台机器对不上)
|
|
1116
|
+
for (const f of walk(join(repoRoot, 'mnemon'))) {
|
|
1117
|
+
if (existsSync(join(mnSrc, ...f.rel.split('/')))) continue
|
|
1118
|
+
try { rmSync(f.full, { force: true }); changed.push(`mnemon/${f.rel}(删除)`) } catch { /* 删不掉不影响其余 */ }
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
// 3.5) 工作区登记表(只登记表,不搬文件树)
|
|
1124
|
+
if (gated('workspace')) skipScopedGroup(scope, repoRoot, 'workspace', skippedByScope)
|
|
1125
|
+
else {
|
|
1126
|
+
try {
|
|
1127
|
+
const r = captureWorkspaceRegistry({ repoRoot, dshHome: local.dshHome, scope, roots })
|
|
1128
|
+
files += r.files
|
|
1129
|
+
bytes += r.bytes
|
|
1130
|
+
changed.push(...r.changed)
|
|
1131
|
+
errors.push(...r.errors)
|
|
1132
|
+
for (const n of r.notes) skippedByScope.push(`workspace: ${n}`)
|
|
1133
|
+
} catch (e) {
|
|
1134
|
+
errors.push(`workspace: ${(e && e.message) || e}`)
|
|
1135
|
+
}
|
|
1136
|
+
}
|
|
1137
|
+
|
|
1138
|
+
// 3.6) 插件数据 / 额外路径(规则与面板、PowerShell 共用 runtime/extra-rules.mjs)
|
|
1139
|
+
try {
|
|
1140
|
+
const extraCfg = readExtraConfig(local.dshHome)
|
|
1141
|
+
if (gated('plugin-data')) skipScopedGroup(scope, repoRoot, 'plugin-data', skippedByScope)
|
|
1142
|
+
else {
|
|
1143
|
+
const r = capturePluginData({ repoRoot, dshHome: local.dshHome, cfg: extraCfg, scope, roots })
|
|
1144
|
+
files += r.files
|
|
1145
|
+
bytes += r.bytes
|
|
1146
|
+
changed.push(...r.changed)
|
|
1147
|
+
errors.push(...r.errors)
|
|
1148
|
+
for (const n of r.notes) skippedByScope.push(`plugin-data: ${n}`)
|
|
1149
|
+
}
|
|
1150
|
+
if (gated('extra')) skipScopedGroup(scope, repoRoot, 'extra', skippedByScope)
|
|
1151
|
+
else {
|
|
1152
|
+
const r = captureExtraPaths({ repoRoot, dshHome: local.dshHome, cfg: extraCfg, scope, roots })
|
|
1153
|
+
files += r.files
|
|
1154
|
+
bytes += r.bytes
|
|
1155
|
+
changed.push(...r.changed)
|
|
1156
|
+
errors.push(...r.errors)
|
|
1157
|
+
for (const n of r.notes) skippedByScope.push(`extra: ${n}`)
|
|
1158
|
+
}
|
|
1159
|
+
} catch (e) {
|
|
1160
|
+
errors.push(`plugin-data/extra: ${(e && e.message) || e}`)
|
|
1161
|
+
}
|
|
1162
|
+
|
|
653
1163
|
// 4) 本机身份(不是配置,是元数据):让别的机器知道「这份配置来自哪」
|
|
654
1164
|
try {
|
|
655
1165
|
writeMachineInfo(repoRoot, localMachineInfo({
|
|
@@ -679,6 +1189,54 @@ let applyBackupDir = ''
|
|
|
679
1189
|
* 覆盖前留底。只备份「将被覆盖且内容不同」的本机文件;内容相同的不重复拷。
|
|
680
1190
|
* src 是目录时逐文件比对。备份失败不阻断同步,但要记进 errors(否则是静默丢底)。
|
|
681
1191
|
*/
|
|
1192
|
+
/**
|
|
1193
|
+
* 共享目录的「镜像」语义:仓库里没有的,本机就删(删前留底)。
|
|
1194
|
+
*
|
|
1195
|
+
* 用户要的是「配置互相覆盖」:在 A 机删掉的技能,B 机拉一次就该消失。
|
|
1196
|
+
* 只拷贝不删的话,删掉的东西会在另一台机器上永远留着,时间一长两边就分叉了。
|
|
1197
|
+
* 只用于 skills / presets 这类以云端为准的配置目录,不动插件数据(那里有运行期文件)。
|
|
1198
|
+
*/
|
|
1199
|
+
function mirrorSharedDir({ srcDir, dstDir, dshHome, dryRun, label, backupDir, written, skipped, errors }) {
|
|
1200
|
+
if (!isDir(srcDir) || !isDir(dstDir)) return 0
|
|
1201
|
+
let srcNames = []
|
|
1202
|
+
try { srcNames = readdirSync(srcDir) } catch { return 0 }
|
|
1203
|
+
const keep = new Set(srcNames)
|
|
1204
|
+
let localNames = []
|
|
1205
|
+
try { localNames = readdirSync(dstDir) } catch { return 0 }
|
|
1206
|
+
let removed = 0
|
|
1207
|
+
for (const name of localNames) {
|
|
1208
|
+
if (keep.has(name)) continue
|
|
1209
|
+
const abs = join(dstDir, name)
|
|
1210
|
+
const rel = relative(dshHome, abs).split(sep).join('/')
|
|
1211
|
+
if (dryRun) { written.push(`${label}/${name}(会删除:仓库里没有)`); continue }
|
|
1212
|
+
try {
|
|
1213
|
+
const target = join(backupDir || join(dshHome, 'backups', 'apply-manual'), rel)
|
|
1214
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
1215
|
+
if (isDir(abs)) cpSync(abs, target, { recursive: true, force: true })
|
|
1216
|
+
else copyFileSync(abs, target)
|
|
1217
|
+
} catch (e) {
|
|
1218
|
+
errors.push(`${label}/${name}: 删除前留底失败,已跳过删除(${(e && e.message) || e})`)
|
|
1219
|
+
continue
|
|
1220
|
+
}
|
|
1221
|
+
try {
|
|
1222
|
+
rmSync(abs, { recursive: true, force: true })
|
|
1223
|
+
removed += 1
|
|
1224
|
+
written.push(`${label}/${name}(已删除:仓库里没有)`)
|
|
1225
|
+
} catch (e) {
|
|
1226
|
+
errors.push(`${label}/${name}: 删除失败 ${(e && e.message) || e}`)
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
if (removed) skipped.push(`${label}: 按云端镜像删掉本机多出来的 ${removed} 项(已留底)`)
|
|
1230
|
+
return removed
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
/**
|
|
1234
|
+
* 覆盖前留底:把**目标文件当前的样子**复制到 `<DshHome>/backups/apply-<时间戳>/`。
|
|
1235
|
+
*
|
|
1236
|
+
* src 是仓库里的那份(用来比对),dst 是本机要被覆盖的那份(用来复制)。
|
|
1237
|
+
* 早先几处调用写成了 backupBeforeWrite(dst, dst),自己跟自己比永远「内容相同」→ 备份根本没做,
|
|
1238
|
+
* 真机上覆盖 profile/package.json 时一点痕迹都没留下。别再写成两个相同参数。
|
|
1239
|
+
*/
|
|
682
1240
|
function backupBeforeWrite(src, dst, dshHome, errorsRef) {
|
|
683
1241
|
try {
|
|
684
1242
|
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '')
|
|
@@ -713,7 +1271,26 @@ export function apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName =
|
|
|
713
1271
|
// 用「用户确认过的根」(config-sync-roots.json):自选目录必须变成 {{ROOT:x}},
|
|
714
1272
|
// 否则会把本机绝对路径原样带进仓库,换机后对方文件指向一个不存在的目录。
|
|
715
1273
|
const roots = readSyncRoots(local.dshHome, local)
|
|
716
|
-
|
|
1274
|
+
// 跨平台判定要在所有组之前算:settings 组里那份「整份工作区登记表」也要据此决定怎么处理。
|
|
1275
|
+
const foreign = foreignRepoEvidence(repoRoot, local)
|
|
1276
|
+
// 移植上下文:家目录 / 根占位符 / 本机工作区清单 / 用户映射表(config-sync-port.json)
|
|
1277
|
+
let portCtx = null
|
|
1278
|
+
if (foreign.foreign) {
|
|
1279
|
+
let reg0 = null
|
|
1280
|
+
try { reg0 = JSON.parse(readFileSync(join(local.dshHome, 'storages', 'workspace.json'), 'utf8')) } catch { reg0 = null }
|
|
1281
|
+
const ws0 = []
|
|
1282
|
+
for (const [id, w] of Object.entries((reg0 && reg0.tables && reg0.tables.workspaces) || {})) {
|
|
1283
|
+
if (w && w.path) ws0.push({ id, title: w.title || basename(String(w.path)), path: w.path })
|
|
1284
|
+
}
|
|
1285
|
+
portCtx = portContext({
|
|
1286
|
+
userHome: typeof roots.userHome === 'string' && roots.userHome ? roots.userHome : homedir(),
|
|
1287
|
+
roots,
|
|
1288
|
+
localWorkspaces: ws0,
|
|
1289
|
+
portConfig: readPortConfig(local.dshHome),
|
|
1290
|
+
expand: (t) => expandTokenText(String(t || ''), roots),
|
|
1291
|
+
})
|
|
1292
|
+
}
|
|
1293
|
+
const written = [], skipped = [], errors = [], conflicts = []
|
|
717
1294
|
let files = 0, bytes = 0
|
|
718
1295
|
applyBackupDir = ''
|
|
719
1296
|
// 同步内容勾选:与 capture 同一套判定,别让「没勾的组」在 apply 侧又被铺回来
|
|
@@ -721,6 +1298,10 @@ export function apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName =
|
|
|
721
1298
|
const skippedByScope = []
|
|
722
1299
|
|
|
723
1300
|
const pull = (srcRel, dst) => {
|
|
1301
|
+
// 机器相关的文件优先读本平台分区(profile/darwin/…),没有再回落到根目录那份老位置
|
|
1302
|
+
const picked = pickRepoRel(repoRoot, srcRel)
|
|
1303
|
+
if (!picked) { skipped.push(`${srcRel}: 仓库里没有`); return }
|
|
1304
|
+
srcRel = picked.rel
|
|
724
1305
|
const src = join(repoRoot, fromRepoPath(srcRel))
|
|
725
1306
|
if (!existsSync(src)) { skipped.push(`${srcRel}: 仓库里没有`); return }
|
|
726
1307
|
try {
|
|
@@ -756,30 +1337,465 @@ export function apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName =
|
|
|
756
1337
|
return { ok: false, errors: [`profile 目录不存在:${profileDir}(本机还没跑过这个 profile?)`], written, skipped, files, bytes, local }
|
|
757
1338
|
}
|
|
758
1339
|
|
|
759
|
-
|
|
760
|
-
|
|
1340
|
+
// 跨平台移植:仓库来自另一套系统时,能翻的翻、翻不出来的丢掉并说明,
|
|
1341
|
+
// 绝不把 D:\... / pwsh7.cmd 这类东西原样铺进本机 profile。
|
|
1342
|
+
if (foreign.foreign) {
|
|
1343
|
+
const stage = join(local.dshHome, 'profile-from-cloud')
|
|
1344
|
+
const rawStage = join(stage, 'raw')
|
|
1345
|
+
skippedByScope.push(`profile: 仓库来自另一套系统(${foreign.reasons.join(';')}),按本机情况移植`)
|
|
1346
|
+
|
|
1347
|
+
// 原始文件留一份,供人工比对
|
|
1348
|
+
for (const leaf of ['package.json', 'cordis.patch.yml', 'cordis.yml', 'pnpm-workspace.yaml', 'pnpm-lock.yaml']) {
|
|
1349
|
+
const src = join(repoRoot, 'profile', leaf)
|
|
1350
|
+
if (!existsSync(src)) continue
|
|
1351
|
+
if (dryRun) continue
|
|
1352
|
+
try {
|
|
1353
|
+
mkdirSync(rawStage, { recursive: true })
|
|
1354
|
+
writeFileSync(join(rawStage, leaf), expandTokenText(readFileSync(src, 'utf8'), roots).replace(/\r\n/g, '\n'), 'utf8')
|
|
1355
|
+
} catch (e) {
|
|
1356
|
+
errors.push(`profile-from-cloud/raw/${leaf}: ${(e && e.message) || e}`)
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
|
|
1360
|
+
// 移植上下文:家目录 + 根占位符 + 本机工作区清单 + 用户映射表
|
|
1361
|
+
let localReg = null
|
|
1362
|
+
try { localReg = JSON.parse(readFileSync(join(local.dshHome, 'storages', 'workspace.json'), 'utf8')) } catch { localReg = null }
|
|
1363
|
+
const wsList = []
|
|
1364
|
+
const wsTable = (localReg && localReg.tables && localReg.tables.workspaces) || {}
|
|
1365
|
+
for (const [id, w] of Object.entries(wsTable)) if (w && w.path) wsList.push({ id, title: w.title || basename(String(w.path)), path: w.path })
|
|
1366
|
+
const pctx = portCtx || portContext({ userHome: homedir(), roots })
|
|
1367
|
+
|
|
1368
|
+
// ① package.json:合并(本机优先)+ link 路径改写 + 不可用的丢弃
|
|
1369
|
+
const livePkgPath = join(profileDir, 'package.json')
|
|
1370
|
+
let livePkg = null
|
|
1371
|
+
try { livePkg = JSON.parse(readFileSync(livePkgPath, 'utf8')) } catch { livePkg = null }
|
|
1372
|
+
let cloudPkg = null
|
|
1373
|
+
try { cloudPkg = JSON.parse(readFileSync(join(repoRoot, 'profile', 'package.json'), 'utf8')) } catch { cloudPkg = null }
|
|
1374
|
+
const ported = portPackageJson({ localPkg: livePkg, cloudPkg, ctx: pctx })
|
|
1375
|
+
for (const n of ported.notes) skippedByScope.push(`profile/package.json: ${n}`)
|
|
1376
|
+
for (const d of ported.dropped) skippedByScope.push(`profile/package.json 丢弃 ${d}`)
|
|
1377
|
+
if (ported.pkg) {
|
|
1378
|
+
const text = JSON.stringify(ported.pkg, null, 2) + '\n'
|
|
1379
|
+
if (dryRun) written.push('profile/package.json(移植后)')
|
|
1380
|
+
else {
|
|
1381
|
+
try {
|
|
1382
|
+
backupBeforeWrite(join(repoRoot, 'profile', 'package.json'), livePkgPath, local.dshHome, errors)
|
|
1383
|
+
writeFileSync(livePkgPath, text, 'utf8')
|
|
1384
|
+
written.push('profile/package.json(移植后)')
|
|
1385
|
+
conflicts.push('profiles/desktop/package.json(已按本机路径改写依赖)')
|
|
1386
|
+
mkdirSync(stage, { recursive: true })
|
|
1387
|
+
writeFileSync(join(stage, 'package.json'), text, 'utf8')
|
|
1388
|
+
} catch (e) {
|
|
1389
|
+
errors.push(`profile/package.json: ${(e && e.message) || e}`)
|
|
1390
|
+
}
|
|
1391
|
+
}
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
// ② cordis.patch.yml:翻译路径后放暂存目录。**不铺**:里面是 pwsh / wsl 的 shell 路由,
|
|
1395
|
+
// macOS 上没有这些可执行文件,硬合并会让工具调用直接失败(逐条清单在面板说明里)。
|
|
1396
|
+
const patchSrc = join(repoRoot, 'profile', 'cordis.patch.yml')
|
|
1397
|
+
if (existsSync(patchSrc)) {
|
|
1398
|
+
const translated = translatePortableText(expandTokenText(readFileSync(patchSrc, 'utf8'), roots), pctx)
|
|
1399
|
+
if (!dryRun) {
|
|
1400
|
+
try {
|
|
1401
|
+
mkdirSync(stage, { recursive: true })
|
|
1402
|
+
writeFileSync(join(stage, 'cordis.patch.yml'), translated.text.replace(/\r\n/g, '\n'), 'utf8')
|
|
1403
|
+
written.push('profile-from-cloud/cordis.patch.yml(路径已翻译)')
|
|
1404
|
+
} catch (e) {
|
|
1405
|
+
errors.push(`profile-from-cloud/cordis.patch.yml: ${(e && e.message) || e}`)
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
skippedByScope.push(`profile/cordis.patch.yml: 已翻译 ${translated.hits.length} 处路径、${translated.misses.length} 处找不到对应物;` +
|
|
1409
|
+
`内容是本机没有的 shell 路由(pwsh / wsl),不覆盖本机 patch,翻译版见 ${join(stage, 'cordis.patch.yml')}`)
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
// ③ pnpm-workspace.yaml / cordis.yml:本机已有等价文件,只在翻译版里留一份
|
|
1413
|
+
for (const leaf of ['pnpm-workspace.yaml', 'cordis.yml']) {
|
|
1414
|
+
const src = join(repoRoot, 'profile', leaf)
|
|
1415
|
+
if (!existsSync(src) || dryRun) continue
|
|
1416
|
+
try {
|
|
1417
|
+
mkdirSync(stage, { recursive: true })
|
|
1418
|
+
const t = translatePortableText(expandTokenText(readFileSync(src, 'utf8'), roots), pctx)
|
|
1419
|
+
writeFileSync(join(stage, leaf), t.text.replace(/\r\n/g, '\n'), 'utf8')
|
|
1420
|
+
written.push(`profile-from-cloud/${leaf}`)
|
|
1421
|
+
} catch (e) {
|
|
1422
|
+
errors.push(`profile-from-cloud/${leaf}: ${(e && e.message) || e}`)
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
} else {
|
|
1426
|
+
pull('profile/package.json', join(profileDir, 'package.json'))
|
|
1427
|
+
pull('profile/cordis.patch.yml', join(profileDir, 'cordis.patch.yml'))
|
|
1428
|
+
pull('profile/cordis.yml', join(profileDir, 'cordis.yml'))
|
|
1429
|
+
pull('profile/pnpm-workspace.yaml', join(profileDir, 'pnpm-workspace.yaml'))
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// 本地源码插件:解到 <DshHome>/local-plugins-restore/<名字>/,再由用户决定 link 到 profile
|
|
1433
|
+
// (不硬写进客户端包:macOS 上是签名过的 .app,写进去会破坏签名,而且 DSH 也不从那里加载插件)
|
|
1434
|
+
if (scopeGroupEnabled(scope, 'local-plugins')) {
|
|
1435
|
+
const lpRoot = join(repoRoot, 'local-plugins')
|
|
1436
|
+
if (existsSync(lpRoot)) {
|
|
1437
|
+
const restoreRoot = join(local.dshHome, 'local-plugins-restore')
|
|
1438
|
+
let zips = []
|
|
1439
|
+
try { zips = readdirSync(lpRoot, { withFileTypes: true }).filter((e) => e.isFile() && /\.zip$/i.test(e.name)).map((e) => e.name) } catch { zips = [] }
|
|
1440
|
+
for (const name of zips) {
|
|
1441
|
+
const dirName = name.replace(/\.zip$/i, '')
|
|
1442
|
+
if (!scopeItemEnabled(scope, 'local-plugins', dirName)) { skippedByScope.push(`local-plugins/${name}: 未勾选`); continue }
|
|
1443
|
+
if (dryRun) { skipped.push(`local-plugins/${name}: 会解到 ${join(restoreRoot, dirName)}`); continue }
|
|
1444
|
+
try {
|
|
1445
|
+
const r = zipExtract(readFileSync(join(lpRoot, name)), restoreRoot)
|
|
1446
|
+
if (r.files > 0) skippedByScope.push(`local-plugins/${name}: 已解到 ${join(restoreRoot, dirName)}(需要在 profile 里重新 link)`)
|
|
1447
|
+
} catch (e) {
|
|
1448
|
+
errors.push(`local-plugins/${name}: 解包失败 ${(e && e.message) || e}`)
|
|
1449
|
+
}
|
|
1450
|
+
}
|
|
1451
|
+
if (!zips.length) skippedByScope.push('local-plugins: 仓库里没有本地插件归档')
|
|
1452
|
+
}
|
|
1453
|
+
} else skippedByScope.push('local-plugins: 未勾选同步')
|
|
1454
|
+
|
|
1455
|
+
// 工作区登记表:只写一份旁路文件(不覆盖 DSH 自己的 storages/workspace.json)
|
|
1456
|
+
if (scopeGroupEnabled(scope, 'workspace')) {
|
|
1457
|
+
const regFile = join(repoRoot, 'workspace', 'workspace-registry.json')
|
|
1458
|
+
if (existsSync(regFile) && !dryRun) {
|
|
1459
|
+
try {
|
|
1460
|
+
const cloud = JSON.parse(readFileSync(regFile, 'utf8'))
|
|
1461
|
+
const cloudList = Array.isArray(cloud.workspaces) ? cloud.workspaces : []
|
|
1462
|
+
const localIds = new Set()
|
|
1463
|
+
try {
|
|
1464
|
+
const localReg = JSON.parse(readFileSync(join(local.dshHome, 'storages', 'workspace.json'), 'utf8'))
|
|
1465
|
+
for (const id of Object.keys((localReg.tables && localReg.tables.workspaces) || {})) localIds.add(id)
|
|
1466
|
+
} catch { /* 本机还没有登记表 */ }
|
|
1467
|
+
const missing = cloudList.filter((w) => w && w.id && !localIds.has(w.id))
|
|
1468
|
+
// 合并还原:本机已有的工作区一律不动,只补「本机没有的」;
|
|
1469
|
+
// 写入前留底(与其它组同一套 apply-<时间戳> 备份)。
|
|
1470
|
+
try {
|
|
1471
|
+
const regPath = join(local.dshHome, 'storages', 'workspace.json')
|
|
1472
|
+
let localReg = null
|
|
1473
|
+
try { localReg = JSON.parse(readFileSync(regPath, 'utf8')) } catch { localReg = null }
|
|
1474
|
+
const base = localReg && typeof localReg === 'object' ? localReg : { version: 1, tables: { workspaces: {} }, global: {} }
|
|
1475
|
+
base.tables = base.tables && typeof base.tables === 'object' ? base.tables : {}
|
|
1476
|
+
base.tables.workspaces = base.tables.workspaces && typeof base.tables.workspaces === 'object' ? base.tables.workspaces : {}
|
|
1477
|
+
const added = []
|
|
1478
|
+
// 跨平台时先把云端路径翻成本机的(按同名工作区 / ~/projects/<leaf> 等找对应物)
|
|
1479
|
+
let wsCtx = null
|
|
1480
|
+
if (foreign.foreign) {
|
|
1481
|
+
const cfg = readPortConfig(local.dshHome)
|
|
1482
|
+
wsCtx = portContext({
|
|
1483
|
+
userHome: typeof roots.userHome === 'string' && roots.userHome ? roots.userHome : homedir(),
|
|
1484
|
+
roots, localWorkspaces: [],
|
|
1485
|
+
portConfig: cfg,
|
|
1486
|
+
})
|
|
1487
|
+
}
|
|
1488
|
+
for (const w of missing) {
|
|
1489
|
+
let p = expandTokenText(String(w.path || ''), roots)
|
|
1490
|
+
if (wsCtx) {
|
|
1491
|
+
const t = translateWinPath(String(w.path || ''), wsCtx)
|
|
1492
|
+
if (!t) {
|
|
1493
|
+
skippedByScope.push(`workspace ${w.id}: 云端路径 ${w.path} 在本机找不到对应目录,未写入登记表`)
|
|
1494
|
+
continue
|
|
1495
|
+
}
|
|
1496
|
+
p = t.to
|
|
1497
|
+
skippedByScope.push(`workspace ${w.id}: ${w.path} → ${p}(${t.how})`)
|
|
1498
|
+
} else {
|
|
1499
|
+
const usable = IS_WIN ? /^[A-Za-z]:[\\/]/.test(p) : p.startsWith('/')
|
|
1500
|
+
if (!usable) {
|
|
1501
|
+
skippedByScope.push(`workspace ${w.id}: 云端路径 ${w.path} 在本机不可用,未写入登记表`)
|
|
1502
|
+
continue
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
base.tables.workspaces[w.id] = {
|
|
1506
|
+
title: w.title || w.id,
|
|
1507
|
+
path: p,
|
|
1508
|
+
sessionIds: Array.isArray(w.sessionIds) ? w.sessionIds : [],
|
|
1509
|
+
archivedSessionIds: Array.isArray(w.archivedSessionIds) ? w.archivedSessionIds : [],
|
|
1510
|
+
pinnedSessionIds: Array.isArray(w.pinnedSessionIds) ? w.pinnedSessionIds : [],
|
|
1511
|
+
createdAt: w.createdAt || '',
|
|
1512
|
+
updatedAt: w.updatedAt || '',
|
|
1513
|
+
}
|
|
1514
|
+
added.push(w.id)
|
|
1515
|
+
}
|
|
1516
|
+
if (added.length) {
|
|
1517
|
+
base.global = base.global && typeof base.global === 'object' ? base.global : {}
|
|
1518
|
+
if (!base.global.defaultWorkspaceId && cloud.global && cloud.global.defaultWorkspaceId && added.includes(cloud.global.defaultWorkspaceId)) {
|
|
1519
|
+
base.global.defaultWorkspaceId = cloud.global.defaultWorkspaceId
|
|
1520
|
+
}
|
|
1521
|
+
const merged = JSON.stringify(base, null, 2) + '\n'
|
|
1522
|
+
let before = ''
|
|
1523
|
+
try { before = readFileSync(regPath, 'utf8') } catch { before = '' }
|
|
1524
|
+
if (before !== merged) {
|
|
1525
|
+
backupBeforeWrite(join(repoRoot, 'workspace', 'workspace-registry.json'), regPath, local.dshHome, errors)
|
|
1526
|
+
mkdirSync(dirname(regPath), { recursive: true })
|
|
1527
|
+
writeFileSync(regPath, merged, 'utf8')
|
|
1528
|
+
conflicts.push(`storages/workspace.json(补入 ${added.length} 个工作区)`)
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
} catch (e) {
|
|
1532
|
+
errors.push(`workspace: 合并本机登记表失败:${(e && e.message) || e}`)
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
const sidecar = join(local.dshHome, 'workspace-from-cloud.json')
|
|
1536
|
+
if (cloudList.length) {
|
|
1537
|
+
writeFileSync(sidecar, JSON.stringify({
|
|
1538
|
+
note: '云端仓库里的工作区登记表(只读参考;不会覆盖本机 storages/workspace.json)',
|
|
1539
|
+
from: 'workspace/workspace-registry.json',
|
|
1540
|
+
workspaces: cloudList.map((w) => ({ ...w, path: expandTokenText(String(w.path || ''), roots) })),
|
|
1541
|
+
}, null, 2) + '\n', 'utf8')
|
|
1542
|
+
}
|
|
1543
|
+
skippedByScope.push(`workspace: 云端登记表 ${cloudList.length} 个工作区,本机缺 ${missing.length} 个(清单写到 ${sidecar})`)
|
|
1544
|
+
} catch (e) {
|
|
1545
|
+
errors.push(`workspace: 读云端登记表失败:${(e && e.message) || e}`)
|
|
1546
|
+
}
|
|
1547
|
+
} else skippedByScope.push('workspace: 仓库里没有工作区登记表')
|
|
1548
|
+
} else skippedByScope.push('workspace: 未勾选同步')
|
|
1549
|
+
|
|
1550
|
+
// 技能市场台账 / 记忆数据
|
|
1551
|
+
if (scopeGroupEnabled(scope, 'storages-record')) {
|
|
1552
|
+
const dataDir = join(local.dshHome, 'storages', '@montersy123', 'dsh-skill-market', 'data')
|
|
1553
|
+
const pairs = [['installed.json', 'skill-market-installed.json'], ['panel.json', 'skill-market-panel.json']]
|
|
1554
|
+
for (const [leaf, repoLeaf] of pairs) {
|
|
1555
|
+
if (!scopeItemEnabled(scope, 'storages-record', repoLeaf)) continue
|
|
1556
|
+
pull(`storages-record/${repoLeaf}`, join(dataDir, leaf))
|
|
1557
|
+
}
|
|
1558
|
+
} else skippedByScope.push('storages-record: 未勾选同步')
|
|
1559
|
+
if (scopeGroupEnabled(scope, 'mnemon')) {
|
|
1560
|
+
const mnDst = join(local.appRoot || '', 'mnemon')
|
|
1561
|
+
if (!local.appRoot || (!IS_WIN && !existsSync(mnDst))) {
|
|
1562
|
+
// macOS / Linux 上 <AppRoot> 是 .app 包或只读安装目录,往里写会破坏签名/权限:只提示,不动手
|
|
1563
|
+
skippedByScope.push('mnemon: 本机记忆数据目录不在客户端包内,未写入(需要时请手动放置)')
|
|
1564
|
+
} else {
|
|
1565
|
+
pull('mnemon', mnDst)
|
|
1566
|
+
}
|
|
1567
|
+
} else skippedByScope.push('mnemon: 未勾选同步')
|
|
1568
|
+
|
|
1569
|
+
// 插件设置与工作流:仓库里有的才铺;缺占位符路径的由 pull 记进 skipped,不写半成品
|
|
1570
|
+
if (scopeGroupEnabled(scope, 'settings')) {
|
|
1571
|
+
for (const entry of SETTINGS_SOURCES) {
|
|
1572
|
+
if (!scopeItemEnabled(scope, 'settings', entry.id)) { skippedByScope.push(`settings/${entry.id}: 未勾选`); continue }
|
|
1573
|
+
// 工作区登记表有两份来源:settings 里那份是整份快照,workspace 组的合并版更靠谱。
|
|
1574
|
+
// ① workspace 组开着时别用快照覆盖(与 apply.ps1 的判断一致);
|
|
1575
|
+
// ② 仓库来自另一套系统时快照里全是 D:\... 路径,铺进去面板会多出一堆打不开的工作区
|
|
1576
|
+
// (实测:真机拉了一次,21 个工作区里 19 个是 Windows 盘符,本机 5 个被顶掉)。
|
|
1577
|
+
// 跨平台这条必须先判:云端可能根本没上传 workspace/ 那份登记表,只剩 settings 里这份快照,
|
|
1578
|
+
// 走「翻译 + 合并」才能把能对上号的工作区救回来。
|
|
1579
|
+
if (entry.id === 'dsh-workspaces.json' && foreign.foreign) {
|
|
1580
|
+
// 跨平台:翻译路径后按「本机优先」合并,能对上号的工作区保留、对不上的跳过。
|
|
1581
|
+
const src = join(repoRoot, 'settings', entry.id)
|
|
1582
|
+
if (!existsSync(src)) { skippedByScope.push(`settings/${entry.id}: 仓库里没有`); continue }
|
|
1583
|
+
try {
|
|
1584
|
+
const cloudReg = JSON.parse(readFileSync(src, 'utf8'))
|
|
1585
|
+
const dstPath = settingsSourcePath(local.dshHome, profileDir, entry)
|
|
1586
|
+
let localReg = null
|
|
1587
|
+
try { localReg = JSON.parse(readFileSync(dstPath, 'utf8')) } catch { localReg = null }
|
|
1588
|
+
const ported = portWorkspaceRegistry({ localReg, cloudReg, ctx: portCtx })
|
|
1589
|
+
for (const n of ported.notes) skippedByScope.push(`settings/${entry.id}: ${n}`)
|
|
1590
|
+
for (const n of ported.skipped) skippedByScope.push(`settings/${entry.id}: ${n}`)
|
|
1591
|
+
const merged = JSON.stringify(ported.registry, null, 2) + '\n'
|
|
1592
|
+
let before = ''
|
|
1593
|
+
try { before = readFileSync(dstPath, 'utf8') } catch { before = '' }
|
|
1594
|
+
// 一条都没并进来就别写:否则会把「空的骨架文件」铺到本机(原本没有这份登记表的情况下)
|
|
1595
|
+
if (!ported.notes.length) {
|
|
1596
|
+
skippedByScope.push(`settings/${entry.id}: 没有可并到本机的工作区(云端路径在本机都对不上号)`)
|
|
1597
|
+
continue
|
|
1598
|
+
}
|
|
1599
|
+
if (before !== merged && !dryRun) {
|
|
1600
|
+
backupBeforeWrite(src, dstPath, local.dshHome, errors)
|
|
1601
|
+
mkdirSync(dirname(dstPath), { recursive: true })
|
|
1602
|
+
writeFileSync(dstPath, merged, 'utf8')
|
|
1603
|
+
written.push(`settings/${entry.id}(移植后合并)`)
|
|
1604
|
+
} else if (before !== merged) written.push(`settings/${entry.id}(移植后合并,dryRun)`)
|
|
1605
|
+
} catch (e) {
|
|
1606
|
+
errors.push(`settings/${entry.id}: 移植失败 ${(e && e.message) || e}`)
|
|
1607
|
+
}
|
|
1608
|
+
continue
|
|
1609
|
+
}
|
|
1610
|
+
if (entry.id === 'dsh-workspaces.json' && scopeGroupEnabled(scope, 'workspace')) {
|
|
1611
|
+
skippedByScope.push('settings/dsh-workspaces.json: 由 workspace 组按合并方式还原,跳过整份快照')
|
|
1612
|
+
continue
|
|
1613
|
+
}
|
|
1614
|
+
pull(`settings/${entry.id}`, settingsSourcePath(local.dshHome, profileDir, entry))
|
|
1615
|
+
}
|
|
1616
|
+
} else skippedByScope.push('settings: 未勾选同步')
|
|
761
1617
|
if (!scopeGroupEnabled(scope, 'prompt')) skippedByScope.push('prompt: 未勾选同步')
|
|
762
1618
|
else {
|
|
763
|
-
|
|
1619
|
+
const agentsRepo = join(repoRoot, 'prompt', 'AGENTS.md')
|
|
1620
|
+
// 全局提示属于「这台机器的策略」,跨平台拉取时一律摊到暂存目录:
|
|
1621
|
+
// 直接覆盖会把另一套系统的路径与命令(例如 DSH 自带的 PowerShell 运行时位置)搬到本机。
|
|
1622
|
+
const agentsForeign = Boolean(foreign.foreign) && existsSync(agentsRepo)
|
|
1623
|
+
if (scopeItemEnabled(scope, 'prompt', 'AGENTS.md')) {
|
|
1624
|
+
if (agentsForeign) {
|
|
1625
|
+
const dst = join(local.dshHome, 'prompt-from-cloud', 'AGENTS.md')
|
|
1626
|
+
const live = join(local.dshHome, 'AGENTS.md')
|
|
1627
|
+
let liveText = ''
|
|
1628
|
+
try { liveText = readFileSync(live, 'utf8') } catch { liveText = '' }
|
|
1629
|
+
const cfg = readPortConfig(local.dshHome)
|
|
1630
|
+
const actx = portContext({
|
|
1631
|
+
userHome: typeof roots.userHome === 'string' && roots.userHome ? roots.userHome : homedir(),
|
|
1632
|
+
roots, localWorkspaces: [], portConfig: cfg,
|
|
1633
|
+
})
|
|
1634
|
+
const ported = portAgentsMd(expandTokenText(readFileSync(agentsRepo, 'utf8'), roots), actx)
|
|
1635
|
+
if (!dryRun) {
|
|
1636
|
+
try {
|
|
1637
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
1638
|
+
writeFileSync(dst, ported.text, 'utf8')
|
|
1639
|
+
written.push('prompt-from-cloud/AGENTS.md(路径已翻译)')
|
|
1640
|
+
// 本机没有全局提示、或者本机那份就是上一次移植的产物 → 直接落地;
|
|
1641
|
+
// 本机有自己写的那份就只暂存,避免把 macOS 专属的环境事实覆盖掉。
|
|
1642
|
+
const ours = /本文件由 dsh-profile-config-sync 从另一套系统移植/.test(liveText)
|
|
1643
|
+
if (!liveText.trim() || ours) {
|
|
1644
|
+
backupBeforeWrite(agentsRepo, live, local.dshHome, errors)
|
|
1645
|
+
writeFileSync(live, ported.text, 'utf8')
|
|
1646
|
+
written.push('AGENTS.md(移植后)')
|
|
1647
|
+
} else {
|
|
1648
|
+
skippedByScope.push(`prompt/AGENTS.md: 本机已有自己的全局提示,移植版只暂存到 ${dst}(翻译 ${ported.hits.length} 处路径、${ported.misses.length} 处未命中)`)
|
|
1649
|
+
}
|
|
1650
|
+
} catch (e) { errors.push(`prompt-from-cloud/AGENTS.md: ${(e && e.message) || e}`) }
|
|
1651
|
+
}
|
|
1652
|
+
skippedByScope.push(`prompt/AGENTS.md: 来自另一套系统,已按本机路径翻译(${ported.hits.length} 处)`)
|
|
1653
|
+
} else pull('prompt/AGENTS.md', join(local.dshHome, 'AGENTS.md'))
|
|
1654
|
+
}
|
|
764
1655
|
else skippedByScope.push('prompt/AGENTS.md: 未勾选')
|
|
765
1656
|
if (scopeItemEnabled(scope, 'prompt', 'prompt-inject.md')) pull('prompt/prompt-inject.md', join(local.dshHome, 'prompt-inject.md'))
|
|
766
1657
|
else skippedByScope.push('prompt/prompt-inject.md: 未勾选')
|
|
767
1658
|
}
|
|
768
|
-
if (scopeGroupEnabled(scope, 'skills'))
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
1659
|
+
if (scopeGroupEnabled(scope, 'skills')) {
|
|
1660
|
+
pull('skills', join(local.dshHome, 'skills'))
|
|
1661
|
+
mirrorSharedDir({
|
|
1662
|
+
srcDir: join(repoRoot, 'skills'), dstDir: join(local.dshHome, 'skills'), dshHome: local.dshHome,
|
|
1663
|
+
dryRun, label: 'skills', backupDir: applyBackupDir, written, skipped, errors,
|
|
1664
|
+
})
|
|
1665
|
+
} else skippedByScope.push('skills: 未勾选同步')
|
|
1666
|
+
if (scopeGroupEnabled(scope, 'presets')) {
|
|
1667
|
+
pull('presets', join(local.dshHome, '.agent-presets'))
|
|
1668
|
+
mirrorSharedDir({
|
|
1669
|
+
srcDir: join(repoRoot, 'presets'), dstDir: join(local.dshHome, '.agent-presets'), dshHome: local.dshHome,
|
|
1670
|
+
dryRun, label: 'presets', backupDir: applyBackupDir, written, skipped, errors,
|
|
1671
|
+
})
|
|
1672
|
+
} else skippedByScope.push('presets: 未勾选同步')
|
|
772
1673
|
|
|
773
|
-
|
|
1674
|
+
// 会话记录:目录名按本机工作区 ID 重编码,会话日志走 seq 护栏(见 runtime/conversations.mjs)
|
|
1675
|
+
if (scopeGroupEnabled(scope, 'conversations')) {
|
|
1676
|
+
try {
|
|
1677
|
+
const conv = applyConversationsWithGuard({
|
|
1678
|
+
repoRoot, dshHome: local.dshHome, backupRoot: applyBackupDir, dryRun,
|
|
1679
|
+
scope: scope.groups && typeof scope.groups === 'object' ? scope.groups.conversations : null,
|
|
1680
|
+
})
|
|
1681
|
+
files += conv.copied
|
|
1682
|
+
for (const c of conv.conflicts) conflicts.push(c)
|
|
1683
|
+
errors.push(...conv.errors)
|
|
1684
|
+
for (const n of conv.notes) skippedByScope.push(`conversations: ${n}`)
|
|
1685
|
+
} catch (e) {
|
|
1686
|
+
errors.push(`conversations: ${(e && e.message) || e}`)
|
|
1687
|
+
}
|
|
1688
|
+
} else skippedByScope.push('conversations: 未勾选同步')
|
|
1689
|
+
|
|
1690
|
+
// 插件数据 / 额外路径:按仓库里的 manifest + 本机规则铺回(占位符展开后落到本机路径)
|
|
1691
|
+
const extraCfg = readExtraConfig(local.dshHome)
|
|
1692
|
+
if (scopeGroupEnabled(scope, 'plugin-data') && extraCfg.pluginData.enabled !== false) {
|
|
1693
|
+
const pdRoot = join(repoRoot, 'plugin-data')
|
|
1694
|
+
if (existsSync(pdRoot)) {
|
|
1695
|
+
let slots = null
|
|
1696
|
+
try { slots = JSON.parse(readFileSync(join(pdRoot, 'manifest.json'), 'utf8')).slots } catch { /* 没清单就按目录名猜 */ }
|
|
1697
|
+
if (!Array.isArray(slots)) {
|
|
1698
|
+
let names = []
|
|
1699
|
+
try { names = readdirSync(pdRoot, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => e.name) } catch { names = [] }
|
|
1700
|
+
slots = names.map((id) => ({ id }))
|
|
1701
|
+
}
|
|
1702
|
+
for (const slot of slots) {
|
|
1703
|
+
if (!slot || !slot.id) continue
|
|
1704
|
+
if (!scopeItemEnabled(scope, 'plugin-data', slot.id)) { skippedByScope.push(`plugin-data/${slot.id}: 未勾选`); continue }
|
|
1705
|
+
const target = slot.src ? expandTokenText(slot.src, roots) : join(local.dshHome, slot.id)
|
|
1706
|
+
if (slot.src && missingTokens(target).length) { skipped.push(`plugin-data/${slot.id}: 待确认路径 ${missingTokens(target).join(', ')}`); continue }
|
|
1707
|
+
if (target === local.dshHome || target.length <= local.dshHome.length) { skipped.push(`plugin-data/${slot.id}: 目标路径可疑,跳过`); continue }
|
|
1708
|
+
pull(`plugin-data/${slot.id}`, target)
|
|
1709
|
+
}
|
|
1710
|
+
}
|
|
1711
|
+
} else if (scopeGroupEnabled(scope, 'plugin-data')) skippedByScope.push('plugin-data: 已在 extra 规则里关闭')
|
|
1712
|
+
else skippedByScope.push('plugin-data: 未勾选同步')
|
|
1713
|
+
|
|
1714
|
+
if (scopeGroupEnabled(scope, 'extra') && extraCfg.extra.enabled !== false) {
|
|
1715
|
+
const exRoot = join(repoRoot, 'extra')
|
|
1716
|
+
if (existsSync(exRoot)) {
|
|
1717
|
+
for (const p of (extraCfg.extra.paths || [])) {
|
|
1718
|
+
if (!scopeItemEnabled(scope, 'extra', p.id)) { skippedByScope.push(`extra/${p.id}: 未勾选`); continue }
|
|
1719
|
+
const dirEntry = join(exRoot, p.id)
|
|
1720
|
+
if (isDir(dirEntry)) { pull(`extra/${p.id}`, p.src); continue }
|
|
1721
|
+
let fileEntry = ''
|
|
1722
|
+
try {
|
|
1723
|
+
const hit = readdirSync(exRoot).find((n) => n.startsWith(`${p.id}.`))
|
|
1724
|
+
if (hit) fileEntry = hit
|
|
1725
|
+
} catch { /* 没有就跳过 */ }
|
|
1726
|
+
if (fileEntry) pull(`extra/${fileEntry}`, p.src)
|
|
1727
|
+
else skipped.push(`extra/${p.id}: 仓库里没有`)
|
|
1728
|
+
}
|
|
1729
|
+
}
|
|
1730
|
+
} else if (scopeGroupEnabled(scope, 'extra')) skippedByScope.push('extra: 已在 extra 规则里关闭')
|
|
1731
|
+
else skippedByScope.push('extra: 未勾选同步')
|
|
1732
|
+
|
|
1733
|
+
return { ok: errors.length === 0, written, skipped, errors, conflicts, files, bytes, local, backupDir: applyBackupDir, skippedByScope }
|
|
774
1734
|
}
|
|
775
1735
|
|
|
776
1736
|
/**
|
|
777
1737
|
* 只读体检(面板 status 路由用)。
|
|
778
1738
|
* 不做任何写操作,可以安全地在客户端运行时调用。
|
|
779
1739
|
*/
|
|
1740
|
+
/**
|
|
1741
|
+
* 判断「这个仓库是另一套操作系统上传的吗」。
|
|
1742
|
+
*
|
|
1743
|
+
* 为什么要判:Windows 上推上来的 `profile/package.json` 里有
|
|
1744
|
+
* `"@local/xxx": "link:{{ROOT:userHome}}/AppData/Local/xxx"` 这类依赖,`cordis.patch.yml`
|
|
1745
|
+
* 里写死了 `D:\c\...` 路径。铺到 macOS 上,pnpm 解不出这个 link 依赖 → profile 起不来,
|
|
1746
|
+
* 客户端下次启动直接报错。跨平台同步是 0.6.49 才有的能力,这条护栏必须自己带。
|
|
1747
|
+
*
|
|
1748
|
+
* 只看证据,不看平台自报(老版本的 host-contract.json 连 os 字段都没有):
|
|
1749
|
+
* ① 契约里的 platformFamily 与本机不同;
|
|
1750
|
+
* ② `profile/package.json` 里出现盘符 / AppData(Windows 特征);
|
|
1751
|
+
* ③ `profile/cordis.patch.yml` 里出现 `X:\` 路径。
|
|
1752
|
+
*/
|
|
1753
|
+
function foreignRepoEvidence(repoRoot, local) {
|
|
1754
|
+
const reasons = []
|
|
1755
|
+
const mine = platformFamily()
|
|
1756
|
+
const contract = repoRoot ? readContract(repoRoot, PLATFORM_LANE) : null
|
|
1757
|
+
if (contract && contract.platformFamily && String(contract.platformFamily).toLowerCase() !== String(mine).toLowerCase()) {
|
|
1758
|
+
reasons.push(`仓库契约记录的平台是 ${contract.platformFamily},本机是 ${mine}`)
|
|
1759
|
+
}
|
|
1760
|
+
// 本平台分区存在 → 那份就是本平台写的,不算外来
|
|
1761
|
+
const myLane = join(repoRoot, fromRepoPath(lanePathOf('profile/package.json')))
|
|
1762
|
+
if (existsSync(myLane)) return { foreign: false, reasons: [] }
|
|
1763
|
+
const pkgPath = join(repoRoot, 'profile', 'package.json')
|
|
1764
|
+
if (existsSync(pkgPath) && !IS_WIN) {
|
|
1765
|
+
let text = ''
|
|
1766
|
+
try { text = readFileSync(pkgPath, 'utf8') } catch { text = '' }
|
|
1767
|
+
if (/AppData|[A-Za-z]:\\\\/.test(text)) reasons.push('profile/package.json 里有 Windows 路径(盘符 / AppData)')
|
|
1768
|
+
}
|
|
1769
|
+
const patchPath = join(repoRoot, 'profile', 'cordis.patch.yml')
|
|
1770
|
+
if (existsSync(patchPath) && !IS_WIN) {
|
|
1771
|
+
let text = ''
|
|
1772
|
+
try { text = readFileSync(patchPath, 'utf8') } catch { text = '' }
|
|
1773
|
+
if (/[A-Za-z]:\\\\/.test(text)) reasons.push('profile/cordis.patch.yml 里有 Windows 盘符路径')
|
|
1774
|
+
}
|
|
1775
|
+
return { foreign: reasons.length > 0, reasons }
|
|
1776
|
+
}
|
|
1777
|
+
|
|
1778
|
+
/**
|
|
1779
|
+
* 会话还原 + seq 护栏脚本定位。
|
|
1780
|
+
* 顺序:插件自带的 tools/ → 插件上一级的 tools/(仓库工作副本就是这种布局)→
|
|
1781
|
+
* 仓库里的 tools/ → 仓库根(老仓库把脚本平铺在根上)。找不到就退回整文件覆盖,
|
|
1782
|
+
* 并把这件事记进 notes —— 不静默降级。
|
|
1783
|
+
*/
|
|
1784
|
+
function applyConversationsWithGuard(opts) {
|
|
1785
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
1786
|
+
const guardScript = resolveGuardScript([
|
|
1787
|
+
// runtime/tools/ 才是发布包里那份(npm 包不含仓库根的 tools/);其余是仓库工作副本与老仓库布局
|
|
1788
|
+
join(here, 'tools', 'session-log-guard.mjs'),
|
|
1789
|
+
join(here, '..', 'tools', 'session-log-guard.mjs'),
|
|
1790
|
+
opts.repoRoot ? join(opts.repoRoot, 'tools', 'session-log-guard.mjs') : '',
|
|
1791
|
+
opts.repoRoot ? join(opts.repoRoot, 'session-log-guard.mjs') : '',
|
|
1792
|
+
])
|
|
1793
|
+
return applyConversations({ ...opts, guardScript })
|
|
1794
|
+
}
|
|
1795
|
+
|
|
780
1796
|
export function status({ repoRoot, dshHome, appRoot, workspaceHome } = {}) {
|
|
781
1797
|
const local = probeLocal({ dshHome, appRoot, workspaceHome })
|
|
782
|
-
const contract = repoRoot ? readContract(repoRoot) : null
|
|
1798
|
+
const contract = repoRoot ? readContract(repoRoot, PLATFORM_LANE) : null
|
|
783
1799
|
const machines = repoRoot ? listMachines(repoRoot) : []
|
|
784
1800
|
const git = local.git
|
|
785
1801
|
const gitState = git && repoRoot ? readGitState(repoRoot, git) : null
|
|
@@ -877,6 +1893,89 @@ function buildWarnings({ local, contract, repoRoot }) {
|
|
|
877
1893
|
return out
|
|
878
1894
|
}
|
|
879
1895
|
|
|
1896
|
+
/**
|
|
1897
|
+
* 把 Node 执行体写进仓库根(sync-engine.mjs + 它 import 的几个模块)。
|
|
1898
|
+
*
|
|
1899
|
+
* 为什么必须有:换机拉取的机器要能在**没有插件**的情况下跑 `node sync-engine.mjs`;
|
|
1900
|
+
* 更要紧的是宿主用「仓库根有没有 apply.ps1 / sync-engine.mjs」判断这是不是一个可用仓库。
|
|
1901
|
+
* 0.6.49 之前 POSIX 的 capture 只写内容、不写执行体 —— 第一次推送成功后,
|
|
1902
|
+
* 仓库立刻变成「像仓库但没执行体」,面板报「这个目录里已经有别的东西」并禁掉后续动作,
|
|
1903
|
+
* 用户只能重配一遍。Windows 版一直是连脚本一起写进仓库的,这里补齐同一语义。
|
|
1904
|
+
*/
|
|
1905
|
+
export function ensureRepoRunner(repoRoot) {
|
|
1906
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
1907
|
+
// 会话记录组的实现也是随仓库走的(另一台机器没有插件副本时靠仓库这份跑 apply)
|
|
1908
|
+
// 这几个是引擎自己 import 的模块,缺一个就 `ERR_MODULE_NOT_FOUND`:
|
|
1909
|
+
// 另一台机器没有插件副本时,全靠仓库这份跑 apply(0.6.49 新增的组都依赖它们)。
|
|
1910
|
+
const names = [
|
|
1911
|
+
'sync-engine.mjs', 'platform.mjs', 'contract.mjs', 'machines.mjs', 'webdav.mjs', 'conversations.mjs',
|
|
1912
|
+
'zip.mjs', 'extra-rules.mjs', 'settings-sources.mjs', 'porting.mjs',
|
|
1913
|
+
]
|
|
1914
|
+
// 会话日志护栏(apply 还原会话时按 CLI 调它做 seq 比对),仓库里也要有一份,
|
|
1915
|
+
// 否则新机器上只会静默降级成「不比对」。
|
|
1916
|
+
const tools = ['session-log-guard.mjs', 'session-log-lib.mjs']
|
|
1917
|
+
const pairs = names.map((n) => [join(here, n), join(repoRoot, n)])
|
|
1918
|
+
for (const t of tools) pairs.push([join(here, 'tools', t), join(repoRoot, 'tools', t)])
|
|
1919
|
+
const written = []
|
|
1920
|
+
for (const [src, dst] of pairs) {
|
|
1921
|
+
if (!isFile(src)) continue
|
|
1922
|
+
try {
|
|
1923
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
1924
|
+
let same = false
|
|
1925
|
+
try { same = existsSync(dst) && fileHash(src) === fileHash(dst) } catch { same = false }
|
|
1926
|
+
if (!same) { copyFileSync(src, dst); written.push(relative(repoRoot, dst).split(sep).join('/')) }
|
|
1927
|
+
} catch { /* 写不进去不阻断同步:仓库里已有旧版执行体也能跑 */ }
|
|
1928
|
+
}
|
|
1929
|
+
return written
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
/**
|
|
1933
|
+
* 新机器首次拉取:把空仓库 / 还没上游的仓库跟 origin 对齐。
|
|
1934
|
+
*
|
|
1935
|
+
* Windows 版的 sync.ps1 有 Initialize-RepoIfNeeded(init + fetch + checkout)兜这件事;
|
|
1936
|
+
* Node 引擎之前**没有**,于是第一次 `pull` 在全新目录上必然停在
|
|
1937
|
+
* 「快进合并失败:fatal: no such branch: 'main'」,后面 apply 拿空仓库照跑一遍,
|
|
1938
|
+
* 结果「拉取成功、什么都没落地」。macOS 上没有第二条路可退,这个洞必须补。
|
|
1939
|
+
*
|
|
1940
|
+
* 返回 { ok, bootstrapped, branch, error }
|
|
1941
|
+
*/
|
|
1942
|
+
function bootstrapRepo(repoRoot) {
|
|
1943
|
+
const remotes = gitRun(repoRoot, ['remote'], 60000)
|
|
1944
|
+
if (!remotes.out.split(/\r?\n/).includes('origin')) {
|
|
1945
|
+
return { ok: false, bootstrapped: false, error: '本机仓库没有 origin:先在面板「云端仓库」里填远端地址并保存,再拉取' }
|
|
1946
|
+
}
|
|
1947
|
+
// 远端默认分支:ls-remote --symref origin HEAD → "ref: refs/heads/main\tHEAD"
|
|
1948
|
+
let branch = ''
|
|
1949
|
+
const sym = gitRun(repoRoot, ['ls-remote', '--symref', 'origin', 'HEAD'], 60000)
|
|
1950
|
+
const m = /ref:\s+refs\/heads\/([^\s]+)\s+HEAD/.exec(sym.out || '')
|
|
1951
|
+
if (m) branch = m[1]
|
|
1952
|
+
if (!branch) {
|
|
1953
|
+
// 没有 HEAD 指向(空仓库)或老 git:退回 init.defaultBranch 或 main
|
|
1954
|
+
const guess = gitRun(repoRoot, ['symbolic-ref', '--short', 'refs/remotes/origin/HEAD'], 15000)
|
|
1955
|
+
branch = (guess.out || '').replace(/^origin\//, '') || 'main'
|
|
1956
|
+
}
|
|
1957
|
+
const fetched = gitRun(repoRoot, ['fetch', 'origin', '--prune'], 300000)
|
|
1958
|
+
if (fetched.code !== 0) {
|
|
1959
|
+
return { ok: false, bootstrapped: false, error: `git fetch 失败:${fetched.err || fetched.error}` }
|
|
1960
|
+
}
|
|
1961
|
+
const hasCommit = gitRun(repoRoot, ['rev-parse', '--verify', '--quiet', 'HEAD'], 15000).code === 0
|
|
1962
|
+
const remoteRef = `origin/${branch}`
|
|
1963
|
+
const remoteExists = gitRun(repoRoot, ['rev-parse', '--verify', '--quiet', remoteRef], 15000).code === 0
|
|
1964
|
+
if (!remoteExists) {
|
|
1965
|
+
return { ok: true, bootstrapped: false, branch, error: '' }
|
|
1966
|
+
}
|
|
1967
|
+
if (!hasCommit) {
|
|
1968
|
+
// 全新目录:直接按远端分支建本地分支并 checkout
|
|
1969
|
+
const co = gitRun(repoRoot, ['checkout', '-f', '-B', branch, '--track', remoteRef], 120000)
|
|
1970
|
+
if (co.code !== 0) {
|
|
1971
|
+
const co2 = gitRun(repoRoot, ['checkout', '-f', '-b', branch, remoteRef], 120000)
|
|
1972
|
+
if (co2.code !== 0) return { ok: false, bootstrapped: false, error: `git checkout 失败:${co2.err || co2.error || co.err}` }
|
|
1973
|
+
}
|
|
1974
|
+
return { ok: true, bootstrapped: true, branch, error: '' }
|
|
1975
|
+
}
|
|
1976
|
+
return { ok: true, bootstrapped: false, branch, error: '' }
|
|
1977
|
+
}
|
|
1978
|
+
|
|
880
1979
|
/** 仓库是否具备同步条件(有 apply.ps1 或 sync-engine 的布局标志)。 */
|
|
881
1980
|
export function isRepoRoot(dir) {
|
|
882
1981
|
if (!dir) return false
|
|
@@ -916,12 +2015,18 @@ function warnUnknownArgs(args, known, usage) {
|
|
|
916
2015
|
*/
|
|
917
2016
|
function ensureOwnRepo(repoRoot) {
|
|
918
2017
|
const norm = (s) => String(s || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
|
|
2018
|
+
// 0.6.49(macOS 实测):/var 与 /tmp 都是指向 /private/var、/private/tmp 的符号链接,
|
|
2019
|
+
// `git rev-parse --show-toplevel` 报的是**真实路径**,而用户填/系统给的是符号链接写法 ——
|
|
2020
|
+
// 只比字面量会把 /tmp/dsh-config 判成「这个目录不是仓库根」,面板的「立即推送」直接失败。
|
|
2021
|
+
// 两边都 realpath 一次再比,任何一边解析失败就退回字面量。
|
|
2022
|
+
const real = (s) => { try { return realpathSync(String(s || '')) } catch { return String(s || '') } }
|
|
2023
|
+
const sameDir = (a, b) => norm(a) === norm(b) || norm(real(a)) === norm(real(b))
|
|
919
2024
|
const top = gitRun(repoRoot, ['rev-parse', '--show-toplevel'], 60000)
|
|
920
2025
|
if (top.code !== 0) {
|
|
921
2026
|
return { ok: false, error: `这个目录还不是 git 仓库:${repoRoot}(先在面板「云端仓库」里初始化,或换成已有仓库)` }
|
|
922
2027
|
}
|
|
923
2028
|
const got = String(top.out || '').trim().split(/\r?\n/).filter(Boolean).pop() || ''
|
|
924
|
-
if (!got ||
|
|
2029
|
+
if (!got || !sameDir(got, repoRoot)) {
|
|
925
2030
|
return {
|
|
926
2031
|
ok: false,
|
|
927
2032
|
error: `这个目录不是仓库根:git 认到的是 ${got || '(空)'};请把同步仓库放在独立目录,不要塞在别的仓库里面`,
|
|
@@ -1061,6 +2166,9 @@ export async function runCli(argv) {
|
|
|
1061
2166
|
'ProfileName', 'profileName', 'Message', 'message', 'BackupDir', 'backupDir',
|
|
1062
2167
|
'SnapshotKind', 'snapshotKind', 'PluginDir', 'pluginDir', 'Force', 'force',
|
|
1063
2168
|
'AllowVersionDrift', 'allowVersionDrift',
|
|
2169
|
+
// 0.6.49:还原/铺开的「只看不动」开关。面板生成的 POSIX 脚本第一步就调 -DryRun,
|
|
2170
|
+
// 不认这个参数会打一行「未知参数」警告,还把 -DryRun 当多余参数忽略 —— 计划变真跑。
|
|
2171
|
+
'DryRun', 'dryRun',
|
|
1064
2172
|
], 'node sync-engine.mjs <status|push|pull|restore> -RepoRoot <dir> -DshHome <dir>')
|
|
1065
2173
|
const repoRoot = a.RepoRoot || a.repoRoot || process.cwd()
|
|
1066
2174
|
const dshHome = a.DshHome || a.dshHome || localDshHome()
|
|
@@ -1156,6 +2264,13 @@ export async function runCli(argv) {
|
|
|
1156
2264
|
const up = await uploadRepo(w, repoRoot)
|
|
1157
2265
|
for (const e of up.errors) console.error(` [!] ${e}`)
|
|
1158
2266
|
console.log(`WebDAV 上传:上传 ${up.uploaded.length} · 跳过 ${up.skipped.length} · 错误 ${up.errors.length}`)
|
|
2267
|
+
// 顺手清掉老版本推上去的浏览器剖面(Login Data / Cookies 不该待在云端)
|
|
2268
|
+
const purge = await purgeForbiddenFromCloud(w)
|
|
2269
|
+
const lockPurge = await purgeStaleLocksFromCloud(w)
|
|
2270
|
+
if (purge.deleted.length) console.log(`云端清理:删除 ${purge.deleted.length} 个历史文件(浏览器剖面)`)
|
|
2271
|
+
for (const e of purge.errors) console.error(` [!] ${e}`)
|
|
2272
|
+
if (lockPurge.deleted.length) console.log(`云端清理:删除 ${lockPurge.deleted.length} 个历史 session.lock(陈旧锁)`)
|
|
2273
|
+
for (const e of lockPurge.errors) console.error(` [!] ${e}`)
|
|
1159
2274
|
return up.ok ? 0 : 1
|
|
1160
2275
|
}
|
|
1161
2276
|
return 0
|
|
@@ -1185,26 +2300,36 @@ export async function runCli(argv) {
|
|
|
1185
2300
|
console.error('本机仓库没有 origin:先在面板「云端仓库」里填远端地址并保存,再拉取')
|
|
1186
2301
|
return 1
|
|
1187
2302
|
}
|
|
1188
|
-
const
|
|
1189
|
-
if (
|
|
1190
|
-
console.error(
|
|
2303
|
+
const boot = bootstrapRepo(repoRoot)
|
|
2304
|
+
if (!boot.ok) {
|
|
2305
|
+
console.error(boot.error)
|
|
1191
2306
|
console.error('离线或认证失败时不会用旧仓库覆盖本机,已停下')
|
|
1192
2307
|
return 1
|
|
1193
2308
|
}
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
console.error('[!] 仓库工作区有未提交改动,跳过自动合并(先在仓库里提交或清理,再拉取)')
|
|
2309
|
+
if (boot.bootstrapped) {
|
|
2310
|
+
console.log(`已把云端仓库拉到本机(分支 ${boot.branch})`)
|
|
1197
2311
|
} else {
|
|
1198
|
-
const
|
|
1199
|
-
if (
|
|
1200
|
-
console.error(
|
|
2312
|
+
const worktree = gitRun(repoRoot, ['status', '--porcelain'], 60000).out
|
|
2313
|
+
if (worktree) {
|
|
2314
|
+
console.error('[!] 仓库工作区有未提交改动,跳过自动合并(先在仓库里提交或清理,再拉取)')
|
|
1201
2315
|
} else {
|
|
1202
|
-
|
|
2316
|
+
// 本机有提交但还没上游(例如换机后手工 init 过):先绑上游再快进
|
|
2317
|
+
const hasUpstream = gitRun(repoRoot, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'], 60000).code === 0
|
|
2318
|
+
if (!hasUpstream && boot.branch) {
|
|
2319
|
+
const local = gitRun(repoRoot, ['rev-parse', '--abbrev-ref', 'HEAD'], 15000).out || boot.branch
|
|
2320
|
+
gitRun(repoRoot, ['branch', '--set-upstream-to', `origin/${boot.branch}`, local], 30000)
|
|
2321
|
+
}
|
|
2322
|
+
const merged = gitRun(repoRoot, ['merge', '--ff-only', '@{upstream}'], 120000)
|
|
2323
|
+
if (merged.code !== 0) {
|
|
2324
|
+
console.error(`[!] 快进合并失败:${merged.err || merged.error}(继续用当前本地仓库内容)`)
|
|
2325
|
+
} else {
|
|
2326
|
+
console.log(merged.out || '仓库已是最新')
|
|
2327
|
+
}
|
|
1203
2328
|
}
|
|
1204
2329
|
}
|
|
1205
2330
|
}
|
|
1206
2331
|
// 宿主版本契约:与 Windows 版语义一致 —— 主版本不同直接拒绝,同主版本不同号只警告。
|
|
1207
|
-
const contractDoc = readContract(repoRoot)
|
|
2332
|
+
const contractDoc = readContract(repoRoot, PLATFORM_LANE)
|
|
1208
2333
|
const localDoc = createProbeLocal({ dshHome, appRoot, workspaceHome })
|
|
1209
2334
|
const verdict = checkContract(contractDoc, localDoc)
|
|
1210
2335
|
if (verdict.level === 'block' && !(a.AllowVersionDrift || a.allowVersionDrift)) {
|
|
@@ -1214,7 +2339,10 @@ export async function runCli(argv) {
|
|
|
1214
2339
|
if (verdict.level === 'warn') {
|
|
1215
2340
|
console.error(`[!] 宿主版本不一致(${verdict.reason}):继续同步,但会剔除实验性 bundle`)
|
|
1216
2341
|
}
|
|
1217
|
-
|
|
2342
|
+
// -DryRun:只打印「会写哪些项」,一个字节都不落盘。Windows 版的还原脚本
|
|
2343
|
+
// 先跑一遍 -DryRun 再确认,POSIX 的还原脚本同样需要这一步(见 index.js buildSh)。
|
|
2344
|
+
const dryRun = a.DryRun === true || a.dryRun === true
|
|
2345
|
+
const r = apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName, dryRun })
|
|
1218
2346
|
for (const wItem of r.written) console.log(` > ${wItem}`)
|
|
1219
2347
|
for (const s of r.skipped) console.log(` - 跳过 ${s}`)
|
|
1220
2348
|
for (const e of r.errors) console.error(` [!] ${e}`)
|
|
@@ -1264,6 +2392,16 @@ export async function runCli(argv) {
|
|
|
1264
2392
|
console.error(`快照里没有可还原的 profile(没找到 profile/ 或平铺的 package.json 等文件):${snapDir}`)
|
|
1265
2393
|
return 2
|
|
1266
2394
|
}
|
|
2395
|
+
// -DryRun:只报计划(会覆盖哪些文件、留底到哪),不读不写 ——
|
|
2396
|
+
// 与 PowerShell 版 restore.ps1 -DryRun 同语义,给确认框前面那一步用。
|
|
2397
|
+
if (a.DryRun === true || a.dryRun === true) {
|
|
2398
|
+
const countIn = (dir) => walk(dir).length
|
|
2399
|
+
console.log(`[计划] 快照:${snapDir}(${kind})`)
|
|
2400
|
+
console.log(`[计划] 目标:${profileDir}`)
|
|
2401
|
+
console.log(`[计划] 将写入 ${countIn(src)} 个文件;当前 profile 有 ${countIn(profileDir)} 个文件会被先留底`)
|
|
2402
|
+
console.log(`[计划] 未做任何改动(-DryRun)`)
|
|
2403
|
+
return 0
|
|
2404
|
+
}
|
|
1267
2405
|
const restoreBackupRoot = join(dshHome, 'backups', `restore-before-${stamp}`)
|
|
1268
2406
|
mkdirSync(profileDir, { recursive: true })
|
|
1269
2407
|
// 还原同样是"覆盖本机":先把当前 profile 留底,否则还原错了没有回头路。
|