dsh-session-sync 0.2.33 → 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 +13 -0
- package/README.en.md +26 -1
- package/README.es.md +26 -1
- package/README.hi.md +26 -1
- package/README.md +26 -1
- package/README.pt.md +26 -1
- package/cordis.patch.yml +11 -0
- package/index.mjs +56 -3
- package/lib/constants.mjs +6 -0
- package/lib/cwdmap.mjs +248 -0
- package/lib/encrypted.mjs +10 -1
- package/lib/engine.mjs +68 -3
- 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/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 }
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// lib/projection.mjs — 恢复期 cwd 投影表(本地状态;镜像字节保持原样)。
|
|
2
|
+
//
|
|
3
|
+
// 恢复时,跨平台会话被写到宿主布局中的**投影位置**
|
|
4
|
+
// (`<projectKey(投影 cwd)>/<sessionId>/<file>`)并把首帧 cwd 换成本机路径。
|
|
5
|
+
// 同步仓库(镜像)里仍是原设备的 header——投影表只落在本地 `.git/` 下、不进
|
|
6
|
+
// 提交,记录 canonicalRel ↔ projectedRel、原始 cwd 与首帧字节,供推送时把本地
|
|
7
|
+
// 追加尾部接回原首帧(对端看到的仍是逐字节 append)。
|
|
8
|
+
//
|
|
9
|
+
// 不可解析的日志/状态一律"保持原样":本模块绝不猜测字节,也绝不让一份看不懂的
|
|
10
|
+
// 会话变成一次写坏布局的操作。
|
|
11
|
+
|
|
12
|
+
import { promises as fs } from 'node:fs'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { decodeSegment } from './paths.mjs'
|
|
15
|
+
import { projectCwd, projectedRelOf } from './cwdmap.mjs'
|
|
16
|
+
import {
|
|
17
|
+
SESSION_LOG_NAME_RE,
|
|
18
|
+
encodeSessionHeader,
|
|
19
|
+
isCompressedName,
|
|
20
|
+
readSessionHeader,
|
|
21
|
+
} from './sessionlog.mjs'
|
|
22
|
+
|
|
23
|
+
/** 投影表状态文件(本地、不进提交)。 */
|
|
24
|
+
export const PROJECTION_STATE_FILE = path.join('.git', 'dsh-session-sync-projection.json')
|
|
25
|
+
|
|
26
|
+
const STATE_VERSION = 1
|
|
27
|
+
/** header 首帧的缓存上限:超过就不缓存(推送时退回重新压缩)。 */
|
|
28
|
+
const MAX_HEADER_FRAME_BYTES = 64 * 1024
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 空投影表。
|
|
32
|
+
* @returns {{entries: object[], byCanonical: Map<string, object>, byProjected: Map<string, object>, error?: string}} 投影表。
|
|
33
|
+
*/
|
|
34
|
+
function emptyProjection() {
|
|
35
|
+
return { entries: [], byCanonical: new Map(), byProjected: new Map() }
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* 由条目数组建投影表(按 canonical/projected 双向索引)。
|
|
40
|
+
* @param {object[]} entries - 投影条目。
|
|
41
|
+
* @returns {{entries: object[], byCanonical: Map<string, object>, byProjected: Map<string, object>}} 投影表。
|
|
42
|
+
*/
|
|
43
|
+
function indexProjection(entries) {
|
|
44
|
+
const byCanonical = new Map()
|
|
45
|
+
const byProjected = new Map()
|
|
46
|
+
for (const entry of entries) {
|
|
47
|
+
byCanonical.set(entry.canonicalRel, entry)
|
|
48
|
+
byProjected.set(entry.projectedRel, entry)
|
|
49
|
+
}
|
|
50
|
+
return { entries, byCanonical, byProjected }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* 读取投影表。缺失 = 空表(尚未投影过);损坏 = 空表 + error(fail closed:
|
|
55
|
+
* 不投影、不把本地视图当推送源)。
|
|
56
|
+
* @param {string|undefined} repoDir - 同步仓库根。
|
|
57
|
+
* @returns {Promise<{entries: object[], byCanonical: Map<string, object>, byProjected: Map<string, object>, error?: string}>} 投影表。
|
|
58
|
+
*/
|
|
59
|
+
export async function readProjectionState(repoDir) {
|
|
60
|
+
if (typeof repoDir !== 'string' || repoDir.length === 0) return emptyProjection()
|
|
61
|
+
let raw
|
|
62
|
+
try {
|
|
63
|
+
raw = await fs.readFile(path.join(repoDir, PROJECTION_STATE_FILE), 'utf8')
|
|
64
|
+
} catch {
|
|
65
|
+
return emptyProjection()
|
|
66
|
+
}
|
|
67
|
+
let parsed
|
|
68
|
+
try {
|
|
69
|
+
parsed = JSON.parse(raw)
|
|
70
|
+
} catch {
|
|
71
|
+
return { ...emptyProjection(), error: 'projection state is not valid JSON (run a pull to rebuild it)' }
|
|
72
|
+
}
|
|
73
|
+
if (parsed === null || typeof parsed !== 'object' || parsed.version !== STATE_VERSION || !Array.isArray(parsed.entries)) {
|
|
74
|
+
return { ...emptyProjection(), error: 'projection state has an unsupported shape (run a pull to rebuild it)' }
|
|
75
|
+
}
|
|
76
|
+
const entries = []
|
|
77
|
+
for (const entry of parsed.entries) {
|
|
78
|
+
if (entry === null || typeof entry !== 'object') continue
|
|
79
|
+
if (typeof entry.canonicalRel !== 'string' || typeof entry.projectedRel !== 'string') continue
|
|
80
|
+
if (typeof entry.originalCwd !== 'string' || typeof entry.projectedCwd !== 'string') continue
|
|
81
|
+
if (typeof entry.id !== 'string' || typeof entry.readOnly !== 'boolean') continue
|
|
82
|
+
entries.push({
|
|
83
|
+
canonicalRel: entry.canonicalRel,
|
|
84
|
+
projectedRel: entry.projectedRel,
|
|
85
|
+
id: entry.id,
|
|
86
|
+
originalCwd: entry.originalCwd,
|
|
87
|
+
projectedCwd: entry.projectedCwd,
|
|
88
|
+
readOnly: entry.readOnly,
|
|
89
|
+
compressed: entry.compressed === true,
|
|
90
|
+
headerFrame: typeof entry.headerFrame === 'string' ? entry.headerFrame : undefined,
|
|
91
|
+
})
|
|
92
|
+
}
|
|
93
|
+
return indexProjection(entries)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* 写投影表(原子替换;`.git` 不存在时静默跳过——等价于不持久化)。
|
|
98
|
+
* @param {string|undefined} repoDir - 同步仓库根。
|
|
99
|
+
* @param {object[]} entries - 新投影条目。
|
|
100
|
+
* @returns {Promise<void>}
|
|
101
|
+
*/
|
|
102
|
+
export async function writeProjectionState(repoDir, entries) {
|
|
103
|
+
if (typeof repoDir !== 'string' || repoDir.length === 0) return
|
|
104
|
+
const target = path.join(repoDir, PROJECTION_STATE_FILE)
|
|
105
|
+
try {
|
|
106
|
+
const st = await fs.stat(path.dirname(target))
|
|
107
|
+
if (!st.isDirectory()) return
|
|
108
|
+
} catch {
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
const payload = Buffer.from(`${JSON.stringify({ version: STATE_VERSION, entries: [...entries].sort((a, b) => a.canonicalRel.localeCompare(b.canonicalRel)) })}
|
|
112
|
+
`)
|
|
113
|
+
const temporary = `${target}.${process.pid}.tmp`
|
|
114
|
+
await fs.writeFile(temporary, payload)
|
|
115
|
+
await fs.rename(temporary, target)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* 规划一个镜像文件在恢复时的落盘形态。
|
|
120
|
+
* @param {{content: Buffer, mirrorRel: string, cwdMap: ReadonlyArray<object>, sessionRoot: string, platform?: NodeJS.Platform}} deps - 文件与配置。
|
|
121
|
+
* @returns {{rel: string, content: Buffer, kind: 'as-is'|'mapped'|'placeholder'|'skipped', entry?: object}} 落盘计划。
|
|
122
|
+
*/
|
|
123
|
+
export function planRestoreFile(deps) {
|
|
124
|
+
const name = path.posix.basename(deps.mirrorRel)
|
|
125
|
+
const asIs = { rel: deps.mirrorRel, content: deps.content, kind: /** @type {const} */ ('as-is') }
|
|
126
|
+
if (!SESSION_LOG_NAME_RE.test(name)) return asIs
|
|
127
|
+
const compressed = isCompressedName(name)
|
|
128
|
+
const parsed = readSessionHeader(deps.content, compressed)
|
|
129
|
+
if (parsed === undefined || typeof parsed.header.cwd !== 'string') return asIs
|
|
130
|
+
const parts = deps.mirrorRel.split('/')
|
|
131
|
+
// 宿主布局 = <projectKey>/<sessionId>/<file>;旧扁平布局不投影(否则路径语义
|
|
132
|
+
// 不对,宁可不改)。
|
|
133
|
+
if (parts.length < 3) return asIs
|
|
134
|
+
if (decodeSegment(parts[1]) !== parsed.header.id) {
|
|
135
|
+
return { ...asIs, kind: 'skipped' }
|
|
136
|
+
}
|
|
137
|
+
const projection = projectCwd(parsed.header.cwd, {
|
|
138
|
+
map: deps.cwdMap,
|
|
139
|
+
sessionRoot: deps.sessionRoot,
|
|
140
|
+
platform: deps.platform,
|
|
141
|
+
})
|
|
142
|
+
if (!projection.mapped && !projection.unmapped) return asIs
|
|
143
|
+
const rel = projectedRelOf(deps.mirrorRel, /** @type {string} */ (projection.cwd))
|
|
144
|
+
if (rel === undefined || rel === deps.mirrorRel) return asIs
|
|
145
|
+
const header = { ...parsed.header, cwd: projection.cwd }
|
|
146
|
+
const entry = {
|
|
147
|
+
canonicalRel: deps.mirrorRel,
|
|
148
|
+
projectedRel: rel,
|
|
149
|
+
id: parsed.header.id,
|
|
150
|
+
originalCwd: parsed.header.cwd,
|
|
151
|
+
projectedCwd: projection.cwd,
|
|
152
|
+
readOnly: projection.readOnly,
|
|
153
|
+
compressed,
|
|
154
|
+
headerFrame: parsed.frame.length <= MAX_HEADER_FRAME_BYTES ? parsed.frame.toString('base64') : undefined,
|
|
155
|
+
}
|
|
156
|
+
return {
|
|
157
|
+
rel,
|
|
158
|
+
content: Buffer.concat([encodeSessionHeader(header, compressed), parsed.rest]),
|
|
159
|
+
kind: projection.readOnly ? 'placeholder' : 'mapped',
|
|
160
|
+
entry,
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* 把本机投影副本还原成镜像字节:镜像里的原首帧 + 本地追加尾部。
|
|
166
|
+
* 占位(只读视图)与 header 被改动的副本一律返回 undefined(永不推送)。
|
|
167
|
+
* @param {{entry: object, localContent: Buffer, mirrorContent?: Buffer}} deps - 投影条目与两侧字节。
|
|
168
|
+
* @returns {Buffer|undefined} 可推送的镜像字节。
|
|
169
|
+
*/
|
|
170
|
+
export function canonicalizeProjectedFile(deps) {
|
|
171
|
+
const entry = deps.entry
|
|
172
|
+
if (entry.readOnly === true) return undefined
|
|
173
|
+
if (!Buffer.isBuffer(deps.localContent)) return undefined
|
|
174
|
+
const local = readSessionHeader(deps.localContent, entry.compressed === true)
|
|
175
|
+
if (local === undefined) return undefined
|
|
176
|
+
if (local.header.id !== entry.id) return undefined
|
|
177
|
+
if (local.header.cwd !== entry.projectedCwd) return undefined
|
|
178
|
+
let headerFrame
|
|
179
|
+
if (Buffer.isBuffer(deps.mirrorContent)) {
|
|
180
|
+
const mirror = readSessionHeader(deps.mirrorContent, entry.compressed === true)
|
|
181
|
+
// 镜像 header 可能被对端迁移更新过:优先沿用它的首帧,保证不丢更新。
|
|
182
|
+
if (mirror !== undefined && mirror.header.id === entry.id) headerFrame = mirror.frame
|
|
183
|
+
}
|
|
184
|
+
if (headerFrame === undefined && typeof entry.headerFrame === 'string') {
|
|
185
|
+
headerFrame = Buffer.from(entry.headerFrame, 'base64')
|
|
186
|
+
}
|
|
187
|
+
if (headerFrame === undefined) {
|
|
188
|
+
headerFrame = encodeSessionHeader({ ...local.header, cwd: entry.originalCwd }, entry.compressed === true)
|
|
189
|
+
}
|
|
190
|
+
return Buffer.concat([headerFrame, local.rest])
|
|
191
|
+
}
|