dsh-session-sync 0.2.32 → 0.3.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/ARCHITECTURE.md +10 -3
- package/CHANGELOG.md +22 -0
- package/README.en.md +455 -0
- package/README.es.md +455 -0
- package/README.hi.md +455 -0
- package/README.md +271 -214
- package/README.pt.md +455 -0
- package/cordis.patch.yml +11 -0
- package/index.mjs +69 -4
- package/lib/constants.mjs +10 -1
- package/lib/cwdmap.mjs +248 -0
- package/lib/encrypted.mjs +10 -1
- package/lib/engine.mjs +77 -5
- package/lib/git.mjs +25 -1
- package/lib/mirror.mjs +294 -35
- package/lib/projection.mjs +191 -0
- package/lib/render.mjs +17 -2
- package/lib/sessionlog.mjs +142 -0
- package/package.json +2 -1
- package/types.d.ts +34 -0
- package/README-es.md +0 -392
- package/README-hi.md +0 -392
- package/README-pt.md +0 -392
- package/README-zh.md +0 -394
package/lib/git.mjs
CHANGED
|
@@ -35,6 +35,7 @@ export const ALLOWED_VERBS = new Set([
|
|
|
35
35
|
'ls-files',
|
|
36
36
|
'ls-tree',
|
|
37
37
|
'update-ref',
|
|
38
|
+
'update-index',
|
|
38
39
|
'status',
|
|
39
40
|
])
|
|
40
41
|
|
|
@@ -57,6 +58,10 @@ export function assertSafe(args) {
|
|
|
57
58
|
if (verb === 'merge' && !(args.includes('--no-commit') || args.includes('--abort'))) {
|
|
58
59
|
throw gitFailed('assert', 'git merge is only allowed with --no-commit or --abort')
|
|
59
60
|
}
|
|
61
|
+
if (verb === 'update-index' && !(args.length === 3 && args[1] === '-q' && args[2] === '--refresh')) {
|
|
62
|
+
// 只允许刷新 stat 缓存;绝不接受 --add/--remove/--force-remove 等改索引内容的旗标。
|
|
63
|
+
throw gitFailed('assert', 'git update-index is only allowed as `-q --refresh`')
|
|
64
|
+
}
|
|
60
65
|
if (verb === 'commit' && args.includes('--amend')) {
|
|
61
66
|
throw gitFailed('assert', 'git commit --amend is forbidden (history is append-only)')
|
|
62
67
|
}
|
|
@@ -269,6 +274,18 @@ export class GitBackend {
|
|
|
269
274
|
throw gitFailed('fetch', redactText(stderr).trim().split('\n').slice(-3).join(' | ') || `exit ${result.code}`)
|
|
270
275
|
}
|
|
271
276
|
|
|
277
|
+
/**
|
|
278
|
+
* 刷新索引里的 stat 信息(不改变内容)。宿主的原子写暂存文件会让工作树长期
|
|
279
|
+
* 处于 stat-dirty 状态:`git diff-files` 有输出但内容没变,`git merge` 因此
|
|
280
|
+
* 走 autostash,而 `git stash create` 在没有真实改动时输出为空,git 直接以
|
|
281
|
+
* `fatal: stash failed` 中止(#29)。合并前刷新一次即可把这类“假脏”清掉。
|
|
282
|
+
* 退出码非零(仍有真实改动)被忽略——调用方已先做过本地提交。
|
|
283
|
+
* @returns {Promise<void>}
|
|
284
|
+
*/
|
|
285
|
+
async refreshIndex() {
|
|
286
|
+
await this.#maybe(['update-index', '-q', '--refresh'])
|
|
287
|
+
}
|
|
288
|
+
|
|
272
289
|
/**
|
|
273
290
|
* 开始合并:git merge --no-commit --allow-unrelated-histories <remoteHead>。
|
|
274
291
|
* 干净自动合并退出 0(变更已暂存,待 commit --no-edit 落合并提交);
|
|
@@ -287,7 +304,14 @@ export class GitBackend {
|
|
|
287
304
|
return { conflicted: false, inProgress: true }
|
|
288
305
|
}
|
|
289
306
|
const inProgress = await this.mergeInProgress()
|
|
290
|
-
|
|
307
|
+
if (!inProgress) {
|
|
308
|
+
// 退出非零且没有 MERGE_HEAD:合并根本没有开始(例如 autostash 失败、
|
|
309
|
+
// 未跟踪文件将被覆盖)。旧代码把它当成 “already up to date”,pull 于是
|
|
310
|
+
// 静默成功、lastError 不更新,仓库却永远合不上(#29)。
|
|
311
|
+
const tail = redactText(String(result.stderr ?? '')).trim().split('\n').slice(-3).join(' | ') || `exit ${result.code}`
|
|
312
|
+
throw gitFailed('merge', tail)
|
|
313
|
+
}
|
|
314
|
+
return { conflicted: true, inProgress: true }
|
|
291
315
|
}
|
|
292
316
|
|
|
293
317
|
/** 是否存在进行中的合并(MERGE_HEAD)。 */
|
package/lib/mirror.mjs
CHANGED
|
@@ -2,40 +2,126 @@
|
|
|
2
2
|
//
|
|
3
3
|
// 会话文件一律按不透明字节复制(JSONL/zstd 等物理编码属于宿主,插件不解析)。
|
|
4
4
|
// 安全边界:
|
|
5
|
-
// -
|
|
5
|
+
// - 默认绝不跟随符号链接(源或目标为链接一律跳过并报告,杜绝写出根外);
|
|
6
|
+
// `followSessionSymlinks: true` 时只跟随 realpath 仍落在 sessionRoot 内的链接
|
|
7
|
+
// (proot link2symlink 那类"可读但 dirent 报 symlink"的宿主,见 #30);
|
|
6
8
|
// - 删除仅限工作树内、源已不存在、且非 fork 文件、非宿主私有产物的常规文件;
|
|
7
9
|
// - fork 文件(FORK_NAME_RE)永不复制、永不删除——冲突双方字节的持久载体;
|
|
8
10
|
// - 宿主私有会话产物(HOST_ARTIFACT_NAME_RE:session.lock / 迁移暂存)同样
|
|
9
11
|
// 永不复制、永不删除——运行时状态不属于可同步内容。
|
|
12
|
+
//
|
|
13
|
+
// 跨平台 cwd 投影(#28):恢复时把 header.cwd 投成本机路径、文件落到宿主布局的
|
|
14
|
+
// 投影位置;镜像里的字节仍是原设备的 header(见 lib/projection.mjs)。镜像枚举
|
|
15
|
+
// 因此跳过投影位置,并按投影表把本地尾部接回镜像里的原首帧——推送出去的字节
|
|
16
|
+
// 与对端追加的字节逐字节一致。
|
|
10
17
|
|
|
11
18
|
import { promises as fs } from 'node:fs'
|
|
12
19
|
import path from 'node:path'
|
|
13
20
|
import { createHash } from 'node:crypto'
|
|
14
|
-
import { FORK_NAME_RE, HOST_ARTIFACT_NAME_RE } from './constants.mjs'
|
|
21
|
+
import { FORK_NAME_RE, HOST_ARTIFACT_NAME_RE, UNMAPPED_DIR } from './constants.mjs'
|
|
22
|
+
import {
|
|
23
|
+
canonicalizeProjectedFile,
|
|
24
|
+
planRestoreFile,
|
|
25
|
+
readProjectionState,
|
|
26
|
+
writeProjectionState,
|
|
27
|
+
} from './projection.mjs'
|
|
28
|
+
|
|
29
|
+
/** 跟随符号链接时允许的最大目录深度(防环耗尽栈)。 */
|
|
30
|
+
const MAX_WALK_DEPTH = 64
|
|
15
31
|
|
|
16
|
-
/**
|
|
17
|
-
|
|
32
|
+
/** 符号链接的 realpath 是否仍在 root 内(真实路径 containment)。 */
|
|
33
|
+
function insideRoot(rootReal, targetReal) {
|
|
34
|
+
const rel = path.relative(rootReal, targetReal)
|
|
35
|
+
return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 递归枚举 root 下全部常规文件(POSIX 相对路径;符号链接默认跳过并回报)。
|
|
40
|
+
* 跟随边界:只有当链接的 realpath 仍落在 `realpath(root)` 内时才读取/递归;
|
|
41
|
+
* 越界链接仍进 `skipped`。目录链接用 realpath 去环。
|
|
42
|
+
* @param {string} root - 会话存储根。
|
|
43
|
+
* @param {{followSymlinks?: boolean}} [options] - 是否跟随根内符号链接。
|
|
44
|
+
* @returns {Promise<{files: {absolute: string, rel: string}[], skipped: string[], followed: string[]}>} 枚举结果。
|
|
45
|
+
*/
|
|
46
|
+
async function listFiles(root, options = {}) {
|
|
47
|
+
const followSymlinks = options.followSymlinks === true
|
|
18
48
|
const files = []
|
|
19
49
|
const skipped = []
|
|
20
|
-
const
|
|
50
|
+
const followed = []
|
|
51
|
+
const seenFiles = new Set()
|
|
52
|
+
const rootReal = followSymlinks ? await fs.realpath(root) : undefined
|
|
53
|
+
const visitedDirectories = new Set()
|
|
54
|
+
const walk = async (dir, depth) => {
|
|
21
55
|
const entries = await fs.readdir(dir, { withFileTypes: true })
|
|
22
56
|
for (const entry of entries) {
|
|
23
57
|
const absolute = path.join(dir, entry.name)
|
|
58
|
+
const rel = path.relative(root, absolute).split(path.sep).join('/')
|
|
24
59
|
if (entry.isSymbolicLink()) {
|
|
60
|
+
if (!followSymlinks) {
|
|
61
|
+
skipped.push(absolute)
|
|
62
|
+
continue
|
|
63
|
+
}
|
|
64
|
+
if (depth > MAX_WALK_DEPTH) {
|
|
65
|
+
skipped.push(absolute)
|
|
66
|
+
continue
|
|
67
|
+
}
|
|
68
|
+
let targetReal
|
|
69
|
+
try {
|
|
70
|
+
targetReal = await fs.realpath(absolute)
|
|
71
|
+
} catch {
|
|
72
|
+
skipped.push(absolute)
|
|
73
|
+
continue
|
|
74
|
+
}
|
|
75
|
+
if (!insideRoot(/** @type {string} */ (rootReal), targetReal)) {
|
|
76
|
+
skipped.push(absolute)
|
|
77
|
+
continue
|
|
78
|
+
}
|
|
79
|
+
let stats
|
|
80
|
+
try {
|
|
81
|
+
stats = await fs.stat(absolute)
|
|
82
|
+
} catch {
|
|
83
|
+
skipped.push(absolute)
|
|
84
|
+
continue
|
|
85
|
+
}
|
|
86
|
+
if (stats.isDirectory()) {
|
|
87
|
+
if (visitedDirectories.has(targetReal)) continue
|
|
88
|
+
visitedDirectories.add(targetReal)
|
|
89
|
+
followed.push(rel)
|
|
90
|
+
await walk(absolute, depth + 1)
|
|
91
|
+
continue
|
|
92
|
+
}
|
|
93
|
+
if (stats.isFile()) {
|
|
94
|
+
if (seenFiles.has(rel)) continue
|
|
95
|
+
seenFiles.add(rel)
|
|
96
|
+
files.push({ absolute, rel })
|
|
97
|
+
followed.push(rel)
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
25
100
|
skipped.push(absolute)
|
|
26
101
|
continue
|
|
27
102
|
}
|
|
28
103
|
if (entry.isDirectory()) {
|
|
29
|
-
|
|
104
|
+
if (followSymlinks) {
|
|
105
|
+
try {
|
|
106
|
+
const real = await fs.realpath(absolute)
|
|
107
|
+
if (visitedDirectories.has(real)) continue
|
|
108
|
+
visitedDirectories.add(real)
|
|
109
|
+
} catch {
|
|
110
|
+
continue
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
await walk(absolute, depth + 1)
|
|
30
114
|
continue
|
|
31
115
|
}
|
|
32
116
|
if (entry.isFile()) {
|
|
33
|
-
|
|
117
|
+
if (seenFiles.has(rel)) continue
|
|
118
|
+
seenFiles.add(rel)
|
|
119
|
+
files.push({ absolute, rel })
|
|
34
120
|
}
|
|
35
121
|
}
|
|
36
122
|
}
|
|
37
|
-
await walk(root)
|
|
38
|
-
return { files, skipped }
|
|
123
|
+
await walk(root, 0)
|
|
124
|
+
return { files, skipped, followed }
|
|
39
125
|
}
|
|
40
126
|
|
|
41
127
|
/** 拒绝任何解析后落在 root 之外的写入(含父目录 symlink 逃逸)。 */
|
|
@@ -67,10 +153,28 @@ async function writeIfDifferent(target, content, root) {
|
|
|
67
153
|
// 目标不存在 → 照写。
|
|
68
154
|
}
|
|
69
155
|
await fs.mkdir(path.dirname(target), { recursive: true })
|
|
70
|
-
|
|
156
|
+
try {
|
|
157
|
+
await fs.writeFile(target, content)
|
|
158
|
+
} catch (error) {
|
|
159
|
+
// 只读投影副本(占位目录)由本插件写成 0o444;再次恢复前先解开写位。
|
|
160
|
+
if (error?.code !== 'EACCES' && error?.code !== 'EPERM') throw error
|
|
161
|
+
await fs.chmod(target, 0o644).catch(() => {})
|
|
162
|
+
await fs.writeFile(target, content)
|
|
163
|
+
}
|
|
71
164
|
return true
|
|
72
165
|
}
|
|
73
166
|
|
|
167
|
+
/** 删除文件;只读投影副本(占位目录 0o444)在 Windows 上先解开只读位再删。 */
|
|
168
|
+
async function unlinkFile(target) {
|
|
169
|
+
try {
|
|
170
|
+
await fs.unlink(target)
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if (error?.code !== 'EACCES' && error?.code !== 'EPERM') throw error
|
|
173
|
+
await fs.chmod(target, 0o644).catch(() => {})
|
|
174
|
+
await fs.unlink(target)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
74
178
|
/** 源快照状态文件:本地、不进提交、不随仓库同步。 */
|
|
75
179
|
export const SOURCE_SNAPSHOT_FILE = path.join('.git', 'dsh-session-sync-mirror.json')
|
|
76
180
|
|
|
@@ -89,7 +193,8 @@ async function readSourceSnapshot(repoDir) {
|
|
|
89
193
|
/** @param {string} repoDir @param {Set<string>} sourcePaths */
|
|
90
194
|
async function writeSourceSnapshot(repoDir, sourcePaths) {
|
|
91
195
|
const target = path.join(repoDir, SOURCE_SNAPSHOT_FILE)
|
|
92
|
-
const payload = Buffer.from(`${JSON.stringify({ version: 1, sourcePaths: [...sourcePaths].sort() })}
|
|
196
|
+
const payload = Buffer.from(`${JSON.stringify({ version: 1, sourcePaths: [...sourcePaths].sort() })}
|
|
197
|
+
`)
|
|
93
198
|
try {
|
|
94
199
|
const st = await fs.stat(path.dirname(target))
|
|
95
200
|
if (!st.isDirectory()) return
|
|
@@ -103,12 +208,16 @@ async function writeSourceSnapshot(repoDir, sourcePaths) {
|
|
|
103
208
|
* 把 sessionRoot 镜像进 <repoDir>/<mirrorDir>/…。
|
|
104
209
|
* 宿主私有会话产物(租约/迁移暂存,HOST_ARTIFACT_NAME_RE)既不复制、也不删除:
|
|
105
210
|
* 它们是运行时状态,同步它们只会把某设备的瞬时状态变成另一侧的删除/噪音。
|
|
106
|
-
*
|
|
107
|
-
*
|
|
211
|
+
* 跨平台 cwd 投影:投影位置(`projectedRel`)不作为镜像源;对应条目按投影表
|
|
212
|
+
* 把本地追加尾部接回镜像首帧后写入**原路径**,镜像字节因此保持原设备视角。
|
|
213
|
+
* @param {object} deps - {sessionRoot, repoDir, mirrorDir, forkNameRe?, followSessionSymlinks?, projectionState?}。
|
|
214
|
+
* @returns {Promise<{mirrored: number, unchanged: number, skippedLinks: string[], followedLinks: string[], deleted: string[], remotePreserved: string[], snapshotUnknown: boolean, forkedPreserved: string[], hostArtifactsSkipped: number, hostArtifactsPreserved: string[], cwdMapped: number, cwdUnmapped: number, cwdProjectionSkipped: number, projectionError?: string}>}
|
|
108
215
|
*/
|
|
109
216
|
export async function mirrorSessionRoot(deps) {
|
|
110
217
|
const forkRe = deps.forkNameRe ?? FORK_NAME_RE
|
|
111
|
-
const
|
|
218
|
+
const projectionState = deps.projectionState ?? await readProjectionState(deps.repoDir)
|
|
219
|
+
const projectedRels = new Set(projectionState.entries.map(entry => entry.projectedRel))
|
|
220
|
+
const source = await listFiles(deps.sessionRoot, { followSymlinks: deps.followSessionSymlinks === true })
|
|
112
221
|
const mirrorRoot = path.join(deps.repoDir, deps.mirrorDir)
|
|
113
222
|
const targets = new Set()
|
|
114
223
|
const previous = await readSourceSnapshot(deps.repoDir)
|
|
@@ -116,7 +225,11 @@ export async function mirrorSessionRoot(deps) {
|
|
|
116
225
|
let mirrored = 0
|
|
117
226
|
let unchanged = 0
|
|
118
227
|
let hostArtifactsSkipped = 0
|
|
228
|
+
let cwdProjectionSkipped = 0
|
|
229
|
+
let cwdMapped = 0
|
|
230
|
+
let cwdUnmapped = 0
|
|
119
231
|
for (const file of source.files) {
|
|
232
|
+
if (projectedRels.has(file.rel)) continue
|
|
120
233
|
if (HOST_ARTIFACT_NAME_RE.test(path.posix.basename(file.rel))) {
|
|
121
234
|
hostArtifactsSkipped += 1
|
|
122
235
|
continue
|
|
@@ -128,6 +241,42 @@ export async function mirrorSessionRoot(deps) {
|
|
|
128
241
|
else unchanged += 1
|
|
129
242
|
}
|
|
130
243
|
|
|
244
|
+
// 投影条目:本地投影副本存在 → 镜像原路径必须继续受保护(删除保护),
|
|
245
|
+
// 且只在可推送(非占位只读)时把本地尾部接回原首帧后覆写。
|
|
246
|
+
for (const entry of projectionState.entries) {
|
|
247
|
+
let local
|
|
248
|
+
const localPath = path.join(deps.sessionRoot, ...entry.projectedRel.split('/'))
|
|
249
|
+
try {
|
|
250
|
+
const localStat = await fs.lstat(localPath)
|
|
251
|
+
// 投影副本必须是常规文件:绝不经符号链接读取(根内跟随只对镜像源开放)。
|
|
252
|
+
if (localStat.isSymbolicLink() || !localStat.isFile()) continue
|
|
253
|
+
local = await fs.readFile(localPath)
|
|
254
|
+
} catch {
|
|
255
|
+
continue
|
|
256
|
+
}
|
|
257
|
+
targets.add(entry.canonicalRel)
|
|
258
|
+
let mirrorExisting
|
|
259
|
+
try {
|
|
260
|
+
mirrorExisting = await fs.readFile(path.join(mirrorRoot, ...entry.canonicalRel.split('/')))
|
|
261
|
+
} catch {
|
|
262
|
+
mirrorExisting = undefined
|
|
263
|
+
}
|
|
264
|
+
// 占位(只读视图)永不作为推送源;可映射条目要求本地首帧仍是投影形状。
|
|
265
|
+
if (entry.readOnly === true) {
|
|
266
|
+
cwdUnmapped += 1
|
|
267
|
+
continue
|
|
268
|
+
}
|
|
269
|
+
const canonical = canonicalizeProjectedFile({ entry, localContent: local, mirrorContent: mirrorExisting })
|
|
270
|
+
if (canonical === undefined) {
|
|
271
|
+
cwdProjectionSkipped += 1
|
|
272
|
+
continue
|
|
273
|
+
}
|
|
274
|
+
cwdMapped += 1
|
|
275
|
+
const wrote = await writeIfDifferent(path.join(mirrorRoot, ...entry.canonicalRel.split('/')), canonical, deps.repoDir)
|
|
276
|
+
if (wrote) mirrored += 1
|
|
277
|
+
else unchanged += 1
|
|
278
|
+
}
|
|
279
|
+
|
|
131
280
|
// 删除:目标树中源已不存在、且非 fork 命名、非宿主私有产物的文件。
|
|
132
281
|
const deleted = []
|
|
133
282
|
const remotePreserved = []
|
|
@@ -174,7 +323,22 @@ export async function mirrorSessionRoot(deps) {
|
|
|
174
323
|
}
|
|
175
324
|
await writeSourceSnapshot(deps.repoDir, targets)
|
|
176
325
|
|
|
177
|
-
return {
|
|
326
|
+
return {
|
|
327
|
+
mirrored,
|
|
328
|
+
unchanged,
|
|
329
|
+
skippedLinks: source.skipped,
|
|
330
|
+
followedLinks: source.followed,
|
|
331
|
+
deleted,
|
|
332
|
+
remotePreserved,
|
|
333
|
+
snapshotUnknown: previous === undefined,
|
|
334
|
+
forkedPreserved,
|
|
335
|
+
hostArtifactsSkipped,
|
|
336
|
+
hostArtifactsPreserved,
|
|
337
|
+
cwdMapped,
|
|
338
|
+
cwdUnmapped,
|
|
339
|
+
cwdProjectionSkipped,
|
|
340
|
+
projectionError: projectionState.error,
|
|
341
|
+
}
|
|
178
342
|
}
|
|
179
343
|
|
|
180
344
|
/** 恢复状态文件:本地、不进提交、不随仓库同步。 */
|
|
@@ -226,27 +390,29 @@ async function mirrorRelSet(root) {
|
|
|
226
390
|
}
|
|
227
391
|
|
|
228
392
|
/**
|
|
229
|
-
*
|
|
230
|
-
*
|
|
231
|
-
*
|
|
232
|
-
* @param {{repoDir: string, mirrorRoot: string, sessionRoot: string}} deps
|
|
393
|
+
* 删除本插件曾经从某次 pull 恢复、且远端随后删除的本机副本;只有当前字节仍等于
|
|
394
|
+
* 记录的哈希时才删(用户改过的副本保留并照常推送)。投影位置通过投影表映射回
|
|
395
|
+
* 镜像相对路径。
|
|
396
|
+
* @param {{repoDir: string, mirrorRoot: string, sessionRoot: string, projectionState?: object}} deps
|
|
233
397
|
* @returns {Promise<{pruned: string[], keptEdited: string[]}>}
|
|
234
398
|
*/
|
|
235
399
|
export async function pruneRestoredSessions(deps) {
|
|
236
400
|
const state = await readRestoreState(deps.repoDir)
|
|
237
401
|
if (state.size === 0) return { pruned: [], keptEdited: [] }
|
|
402
|
+
const projectionState = deps.projectionState ?? await readProjectionState(deps.repoDir)
|
|
238
403
|
const mirror = await mirrorRelSet(deps.mirrorRoot)
|
|
239
404
|
const pruned = []
|
|
240
405
|
const keptEdited = []
|
|
241
406
|
for (const [rel, expected] of [...state]) {
|
|
242
|
-
|
|
407
|
+
const canonicalRel = projectionState.byProjected.get(rel)?.canonicalRel ?? rel
|
|
408
|
+
if (mirror.has(canonicalRel)) continue
|
|
243
409
|
const target = path.join(deps.sessionRoot, ...rel.split('/'))
|
|
244
410
|
try {
|
|
245
411
|
const st = await fs.lstat(target)
|
|
246
412
|
if (st.isSymbolicLink()) { state.delete(rel); continue }
|
|
247
413
|
const content = await fs.readFile(target)
|
|
248
414
|
if (hashContent(content) === expected) {
|
|
249
|
-
await
|
|
415
|
+
await unlinkFile(target)
|
|
250
416
|
pruned.push(rel)
|
|
251
417
|
} else {
|
|
252
418
|
keptEdited.push(rel)
|
|
@@ -263,47 +429,138 @@ export async function pruneRestoredSessions(deps) {
|
|
|
263
429
|
/**
|
|
264
430
|
* Copy the merged mirror back into the live session store. Pull used to merge only
|
|
265
431
|
* into the mirror; the next push then saw those files as "missing locally" and
|
|
266
|
-
* unlinked them. This writes new/changed regular files back, never deletes,
|
|
267
|
-
* follows symlinks, and never writes fork files or host-private artifacts.
|
|
268
|
-
*
|
|
269
|
-
*
|
|
432
|
+
* unlinked them. This writes new/changed regular files back, never deletes,
|
|
433
|
+
* never follows symlinks, and never writes fork files or host-private artifacts.
|
|
434
|
+
*
|
|
435
|
+
* 跨平台 cwd 投影(#28):需要投影的会话写到宿主布局的投影位置
|
|
436
|
+
* (`<projectKey(投影 cwd)>/<sessionId>/<file>`)并改写首帧 cwd;镜像里的原
|
|
437
|
+
* 路径不落盘(同一会话 id 不能同时出现在两个项目目录)。投影表落在本地
|
|
438
|
+
* `.git/` 下,推送时用于把原首帧接回。
|
|
439
|
+
* @param {object} deps - {repoDir, mirrorRoot, sessionRoot, forkNameRe?, cwdMap?, platform?}。
|
|
440
|
+
* @returns {Promise<{restored: number, unchanged: number, skipped: number, tracked: number, cwdMapped: number, cwdUnmapped: number, cwdProjectionSkipped: number, projectionError?: string}>}
|
|
270
441
|
*/
|
|
271
442
|
export async function restoreSessionRoot(deps) {
|
|
272
443
|
const forkRe = deps.forkNameRe ?? FORK_NAME_RE
|
|
444
|
+
const mirrorRoot = deps.mirrorRoot
|
|
273
445
|
let entries
|
|
274
446
|
try {
|
|
275
|
-
entries = await fs.readdir(
|
|
447
|
+
entries = await fs.readdir(mirrorRoot, { recursive: true, withFileTypes: true })
|
|
276
448
|
} catch {
|
|
277
|
-
return { restored: 0, unchanged: 0, skipped: 0, tracked: 0 }
|
|
449
|
+
return { restored: 0, unchanged: 0, skipped: 0, tracked: 0, cwdMapped: 0, cwdUnmapped: 0, cwdProjectionSkipped: 0 }
|
|
278
450
|
}
|
|
451
|
+
const previous = await readProjectionState(deps.repoDir)
|
|
452
|
+
const nextEntries = []
|
|
453
|
+
const nextRelSet = new Set()
|
|
279
454
|
let restored = 0
|
|
280
455
|
let unchanged = 0
|
|
281
456
|
let skipped = 0
|
|
457
|
+
let cwdMapped = 0
|
|
458
|
+
let cwdUnmapped = 0
|
|
459
|
+
let cwdProjectionSkipped = 0
|
|
282
460
|
const state = deps.repoDir === undefined ? new Map() : await readRestoreState(deps.repoDir)
|
|
283
461
|
for (const entry of entries) {
|
|
284
462
|
if (!entry.isFile()) { skipped += 1; continue }
|
|
285
|
-
const parent = entry.parentPath ?? entry.path ??
|
|
463
|
+
const parent = entry.parentPath ?? entry.path ?? mirrorRoot
|
|
286
464
|
const absolute = path.join(parent, entry.name)
|
|
287
|
-
const rel = path.relative(
|
|
465
|
+
const rel = path.relative(mirrorRoot, absolute).split(path.sep).join('/')
|
|
288
466
|
const basename = path.posix.basename(rel)
|
|
289
467
|
if (forkRe.test(basename) || HOST_ARTIFACT_NAME_RE.test(basename)) { skipped += 1; continue }
|
|
290
|
-
const
|
|
468
|
+
const content = await fs.readFile(absolute)
|
|
469
|
+
const plan = planRestoreFile({
|
|
470
|
+
content,
|
|
471
|
+
mirrorRel: rel,
|
|
472
|
+
cwdMap: deps.cwdMap ?? [],
|
|
473
|
+
sessionRoot: deps.sessionRoot,
|
|
474
|
+
platform: deps.platform,
|
|
475
|
+
})
|
|
476
|
+
if (plan.kind === 'skipped') {
|
|
477
|
+
cwdProjectionSkipped += 1
|
|
478
|
+
// 无法投影(如 id 与目录不符):保持镜像原样落盘,绝不写坏布局。
|
|
479
|
+
}
|
|
480
|
+
if (plan.kind === 'mapped') cwdMapped += 1
|
|
481
|
+
if (plan.kind === 'placeholder') cwdUnmapped += 1
|
|
482
|
+
if (plan.entry !== undefined) {
|
|
483
|
+
nextEntries.push(plan.entry)
|
|
484
|
+
// 映射目标 / 占位目录必须真实存在,宿主才能 realpath 并把它归入 workspace
|
|
485
|
+
// (失败不影响可读性:会话仍会以 ungrouped 出现在列表里)。
|
|
486
|
+
await fs.mkdir(plan.entry.projectedCwd, { recursive: true }).catch(() => {})
|
|
487
|
+
}
|
|
488
|
+
nextRelSet.add(plan.rel)
|
|
489
|
+
const target = path.join(deps.sessionRoot, ...plan.rel.split('/'))
|
|
291
490
|
let existed = false
|
|
292
491
|
try {
|
|
293
492
|
const st = await fs.lstat(target)
|
|
294
493
|
if (st.isSymbolicLink()) { skipped += 1; continue }
|
|
295
494
|
existed = true
|
|
296
495
|
} catch { /* target absent */ }
|
|
297
|
-
const
|
|
298
|
-
const wrote = await writeIfDifferent(target, content, deps.sessionRoot)
|
|
496
|
+
const wrote = await writeIfDifferent(target, plan.content, deps.sessionRoot)
|
|
299
497
|
if (wrote) restored += 1
|
|
300
498
|
else unchanged += 1
|
|
499
|
+
// 占位投影是只读视图:尽力在文件系统层面也标注只读(root 可写时由推送端
|
|
500
|
+
// 兜底——占位条目永不作为推送源)。
|
|
501
|
+
if (plan.kind === 'placeholder') await fs.chmod(target, 0o444).catch(() => {})
|
|
301
502
|
// Track only copies this plugin created (target absent before) or already
|
|
302
503
|
// tracked. A pre-existing user file is never claimed by the sync plugin.
|
|
303
|
-
if (!existed || state.has(rel)) state.set(rel, hashContent(content))
|
|
504
|
+
if (!existed || state.has(plan.rel)) state.set(plan.rel, hashContent(plan.content))
|
|
505
|
+
// 投影位置与原路径不同:清掉旧版或旧映射遗留在原路径上的本机副本,否则
|
|
506
|
+
// 宿主会把同一 session id 看成两个项目里的重复会话。
|
|
507
|
+
if (plan.rel !== rel) {
|
|
508
|
+
const legacyTarget = path.join(deps.sessionRoot, ...rel.split('/'))
|
|
509
|
+
let legacyStat
|
|
510
|
+
try {
|
|
511
|
+
legacyStat = await fs.lstat(legacyTarget)
|
|
512
|
+
} catch {
|
|
513
|
+
legacyStat = undefined
|
|
514
|
+
}
|
|
515
|
+
if (legacyStat?.isFile() === true) {
|
|
516
|
+
const legacyContent = await fs.readFile(legacyTarget)
|
|
517
|
+
const tracked = state.get(rel)
|
|
518
|
+
if (legacyContent.equals(content) || (tracked !== undefined && hashContent(legacyContent) === tracked)) {
|
|
519
|
+
await unlinkFile(legacyTarget)
|
|
520
|
+
state.delete(rel)
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
// 失效投影清理:配置变更(映射删除/改写)后,旧投影位置上的副本若仍是本插件
|
|
526
|
+
// 写的字节,就删掉;否则保留并让状态记录它(用户改动优先)。
|
|
527
|
+
for (const oldEntry of previous.entries) {
|
|
528
|
+
if (nextRelSet.has(oldEntry.projectedRel)) continue
|
|
529
|
+
const oldTarget = path.join(deps.sessionRoot, ...oldEntry.projectedRel.split('/'))
|
|
530
|
+
let oldStat
|
|
531
|
+
try {
|
|
532
|
+
oldStat = await fs.lstat(oldTarget)
|
|
533
|
+
} catch {
|
|
534
|
+
oldStat = undefined
|
|
535
|
+
}
|
|
536
|
+
if (oldStat?.isFile() !== true) continue
|
|
537
|
+
const expected = state.get(oldEntry.projectedRel)
|
|
538
|
+
try {
|
|
539
|
+
const oldContent = await fs.readFile(oldTarget)
|
|
540
|
+
// 只删"本插件上次恢复、且此后没人改动"的副本:无哈希记录或字节已变都保留
|
|
541
|
+
// (用户改动优先,宁可留下一个可见副本也不误删数据)。
|
|
542
|
+
if (expected !== undefined && hashContent(oldContent) === expected) {
|
|
543
|
+
await unlinkFile(oldTarget)
|
|
544
|
+
state.delete(oldEntry.projectedRel)
|
|
545
|
+
}
|
|
546
|
+
} catch {
|
|
547
|
+
// 读不到就不删(安全优先)。
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
if (deps.repoDir !== undefined) {
|
|
551
|
+
await writeRestoreState(deps.repoDir, state)
|
|
552
|
+
await writeProjectionState(deps.repoDir, nextEntries)
|
|
553
|
+
}
|
|
554
|
+
return {
|
|
555
|
+
restored,
|
|
556
|
+
unchanged,
|
|
557
|
+
skipped,
|
|
558
|
+
tracked: state.size,
|
|
559
|
+
cwdMapped,
|
|
560
|
+
cwdUnmapped,
|
|
561
|
+
cwdProjectionSkipped,
|
|
562
|
+
projectionError: previous.error,
|
|
304
563
|
}
|
|
305
|
-
if (deps.repoDir !== undefined) await writeRestoreState(deps.repoDir, state)
|
|
306
|
-
return { restored, unchanged, skipped, tracked: state.size }
|
|
307
564
|
}
|
|
308
565
|
|
|
309
566
|
/**
|
|
@@ -318,3 +575,5 @@ export async function ensureDeviceFile(repoDir, deviceFile, deviceId) {
|
|
|
318
575
|
const content = Buffer.from(`${deviceId}\n`)
|
|
319
576
|
return writeIfDifferent(target, content)
|
|
320
577
|
}
|
|
578
|
+
|
|
579
|
+
export { UNMAPPED_DIR }
|