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/index.mjs CHANGED
@@ -57,6 +57,19 @@ import { collectStatus } from './lib/status.mjs'
57
57
  import { renderDiff, renderPull, renderPush, renderStatus, errorValue } from './lib/render.mjs'
58
58
  import { confirmSync, hasOpenTurn, makeEventGate, maybeAppendSessionEvent, openTurnFromProjection } from './lib/gate.mjs'
59
59
  import { sessionSyncDomainSpec } from './lib/domain.mjs'
60
+ import {
61
+ matchCwdMap,
62
+ normalizeCwdMap,
63
+ projectCwd,
64
+ projectKey,
65
+ projectedRelOf,
66
+ } from './lib/cwdmap.mjs'
67
+ import {
68
+ canonicalizeProjectedFile,
69
+ planRestoreFile,
70
+ readProjectionState,
71
+ } from './lib/projection.mjs'
72
+ import { readSessionHeader } from './lib/sessionlog.mjs'
60
73
 
61
74
  export const name = PLUGIN_NAME
62
75
 
@@ -107,6 +120,8 @@ export function probeIgnorableAppend() {
107
120
  * @property {boolean} [autoPushOnTurnEnd] 每个 turn/end 后自动推送(配置即授权)。
108
121
  * @property {number} [pullIntervalMinutes] 周期自动拉取间隔分钟(0 = 关闭)。
109
122
  * @property {'auto'|'userQuestions'|'approval'} [confirmVia] 确认通道(auto 优先 userQuestions)。
123
+ * @property {ReadonlyArray<{from: string, to: string}>} [cwdMap] 恢复期 cwd 投影表(最长前缀优先;未命中的跨平台 cwd 归一到 sessionRoot/--unmapped--)。
124
+ * @property {boolean} [followSessionSymlinks] 镜像时是否跟随 realpath 仍在 sessionRoot 内的符号链接(默认 false)。
110
125
  * @property {number} [graceMs] git 子进程终止宽限(ms)。
111
126
  * @property {number} [commandTimeoutMs] 单条 git 命令超时(ms)。
112
127
  * @property {number} [maxOutputBytes] git 输出单流收集上限(字节)。
@@ -132,6 +147,11 @@ export const Config = Schema.object({
132
147
  autoPushOnTurnEnd: Schema.boolean().default(DEFAULTS.AUTO_PUSH_ON_TURN_END),
133
148
  pullIntervalMinutes: Schema.number().default(DEFAULTS.PULL_INTERVAL_MINUTES),
134
149
  confirmVia: Schema.union(Object.values(CONFIRM_CHANNELS)).default(DEFAULTS.CONFIRM_VIA),
150
+ cwdMap: Schema.array(Schema.object({
151
+ from: Schema.string().required(),
152
+ to: Schema.string().required(),
153
+ })).default([...DEFAULTS.CWD_MAP]),
154
+ followSessionSymlinks: Schema.boolean().default(DEFAULTS.FOLLOW_SESSION_SYMLINKS),
135
155
  graceMs: Schema.number().default(DEFAULTS.GRACE_MS),
136
156
  commandTimeoutMs: Schema.number().default(DEFAULTS.COMMAND_TIMEOUT_MS),
137
157
  maxOutputBytes: Schema.number().default(DEFAULTS.MAX_OUTPUT_BYTES),
@@ -162,6 +182,8 @@ export function resolveConfig(config = {}) {
162
182
  autoPushOnTurnEnd: config.autoPushOnTurnEnd ?? DEFAULTS.AUTO_PUSH_ON_TURN_END,
163
183
  pullIntervalMinutes: config.pullIntervalMinutes ?? DEFAULTS.PULL_INTERVAL_MINUTES,
164
184
  confirmVia: config.confirmVia ?? DEFAULTS.CONFIRM_VIA,
185
+ cwdMap: normalizeCwdMap(config.cwdMap ?? DEFAULTS.CWD_MAP),
186
+ followSessionSymlinks: config.followSessionSymlinks ?? DEFAULTS.FOLLOW_SESSION_SYMLINKS,
165
187
  graceMs: config.graceMs ?? DEFAULTS.GRACE_MS,
166
188
  commandTimeoutMs: config.commandTimeoutMs ?? DEFAULTS.COMMAND_TIMEOUT_MS,
167
189
  maxOutputBytes: config.maxOutputBytes ?? DEFAULTS.MAX_OUTPUT_BYTES,
@@ -204,6 +226,9 @@ export function resolveConfig(config = {}) {
204
226
  if (!Number.isInteger(resolved.pullIntervalMinutes) || resolved.pullIntervalMinutes < LIMITS.MIN_PULL_INTERVAL_MINUTES || resolved.pullIntervalMinutes > LIMITS.MAX_PULL_INTERVAL_MINUTES) {
205
227
  throw badConfig(`pullIntervalMinutes must be an integer in [${LIMITS.MIN_PULL_INTERVAL_MINUTES}, ${LIMITS.MAX_PULL_INTERVAL_MINUTES}]`)
206
228
  }
229
+ if (typeof resolved.followSessionSymlinks !== 'boolean') {
230
+ throw badConfig('followSessionSymlinks must be a boolean')
231
+ }
207
232
  if (typeof resolved.commitName !== 'string' || resolved.commitName.trim().length === 0) {
208
233
  throw badConfig('commitName must be a non-empty string')
209
234
  }
@@ -348,9 +373,9 @@ const TOOL_TEXT = {
348
373
  }
349
374
 
350
375
  /** sync_status 工具规范结果(与工具 schema 同构)。 */
351
- /** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string, warnings?: string[]}} StatusValue */
352
- /** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, error?: string, warnings?: string[]}} PullValue */
353
- /** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, error?: string, warnings?: string[]}} PushValue */
376
+ /** @typedef {{ok: boolean, branch: string, remote: string, head?: string, remoteHead?: string, ahead: number, behind: number, dirty: string[], forks: string[], diffStat: string, mergeInProgress: boolean, lastCommits: string[], lastPullAt?: number, lastPushAt?: number, lastError?: string, error?: string, skippedSymlinks?: number, skippedSymlinkPaths?: string[], followedSymlinks?: number, cwdMapped?: number, cwdUnmapped?: number, cwdProjectionSkipped?: number, cwdPlaceholder?: string, followSessionSymlinks?: boolean, warnings?: string[]}} StatusValue */
377
+ /** @typedef {{ok: boolean, pulled?: boolean, merged?: boolean, adopted?: number, appended?: number, diverged?: number, forks?: string[], head?: string, restored?: number, cwdMapped?: number, cwdUnmapped?: number, error?: string, warnings?: string[]}} PullValue */
378
+ /** @typedef {{ok: boolean, pushed?: boolean, head?: string, mirrored?: number, deleted?: number, remote?: string, skippedSymlinks?: number, skippedSymlinkPaths?: string[], error?: string, warnings?: string[]}} PushValue */
354
379
 
355
380
  /**
356
381
  * sync_status 工具定义(read-only:不确认、不触网)。
@@ -384,6 +409,14 @@ export function makeSyncStatusTool(engine, readMeta) {
384
409
  lastPushAt: { type: 'integer' },
385
410
  lastError: { type: 'string' },
386
411
  error: { type: 'string' },
412
+ skippedSymlinks: { type: 'integer' },
413
+ skippedSymlinkPaths: { type: 'array', items: { type: 'string' } },
414
+ followedSymlinks: { type: 'integer' },
415
+ cwdMapped: { type: 'integer' },
416
+ cwdUnmapped: { type: 'integer' },
417
+ cwdProjectionSkipped: { type: 'integer' },
418
+ cwdPlaceholder: { type: 'string' },
419
+ followSessionSymlinks: { type: 'boolean' },
387
420
  warnings: { type: 'array', items: { type: 'string' } },
388
421
  },
389
422
  },
@@ -396,7 +429,17 @@ export function makeSyncStatusTool(engine, readMeta) {
396
429
  const status = await engine.status()
397
430
  try {
398
431
  const meta = await readMeta()
399
- return { ...status, lastPullAt: meta.lastPullAt, lastPushAt: meta.lastPushAt, lastError: meta.lastError }
432
+ // 只合并有值的键:把 undefined 展开进工具结果会让宿主按
433
+ // “value is not lossless JSON” 拒绝整个 sync_status 结果(#29)。
434
+ const extra = {}
435
+ if (meta.lastPullAt !== undefined) extra.lastPullAt = meta.lastPullAt
436
+ if (meta.lastPushAt !== undefined) extra.lastPushAt = meta.lastPushAt
437
+ if (meta.lastError !== undefined) extra.lastError = meta.lastError
438
+ const out = { ...status, ...extra }
439
+ // 工具结果必须是 lossless JSON:collectStatus 的 head/remoteHead/error
440
+ // 在空仓库或未配置远端时是 undefined,展开后会让宿主拒绝整个结果。
441
+ for (const key of Object.keys(out)) if (out[key] === undefined) delete out[key]
442
+ return out
400
443
  } catch {
401
444
  return status
402
445
  }
@@ -427,6 +470,9 @@ export function makeSyncPullTool(deps) {
427
470
  diverged: { type: 'integer' },
428
471
  forks: { type: 'array', items: { type: 'string' } },
429
472
  head: { type: 'string' },
473
+ restored: { type: 'integer' },
474
+ cwdMapped: { type: 'integer' },
475
+ cwdUnmapped: { type: 'integer' },
430
476
  error: { type: 'string' },
431
477
  warnings: { type: 'array', items: { type: 'string' } },
432
478
  },
@@ -486,6 +532,8 @@ export function makeSyncPushTool(deps) {
486
532
  mirrored: { type: 'integer' },
487
533
  deleted: { type: 'integer' },
488
534
  remote: { type: 'string' },
535
+ skippedSymlinks: { type: 'integer' },
536
+ skippedSymlinkPaths: { type: 'array', items: { type: 'string' } },
489
537
  error: { type: 'string' },
490
538
  warnings: { type: 'array', items: { type: 'string' } },
491
539
  },
@@ -621,6 +669,8 @@ export function apply(ctx, config = {}) {
621
669
  try {
622
670
  const current = await ensureMeta()
623
671
  const next = { ...current, ...patch }
672
+ // `undefined` 表示删除该键(清空 lastError),而不是写入一个非 JSON 值。
673
+ for (const key of Object.keys(patch)) if (patch[key] === undefined) delete next[key]
624
674
  const table = await tablePromise
625
675
  await table.put(STATE_KEY, next)
626
676
  metaCache = next
@@ -658,6 +708,8 @@ export function apply(ctx, config = {}) {
658
708
  remote: resolved.remote,
659
709
  branch: resolved.branch,
660
710
  deviceId: 'pending',
711
+ cwdMap: resolved.cwdMap,
712
+ followSessionSymlinks: resolved.followSessionSymlinks,
661
713
  reportMeta,
662
714
  reportError,
663
715
  logger,
@@ -853,6 +905,9 @@ export function apply(ctx, config = {}) {
853
905
 
854
906
  // turn/end 自动推送(配置即授权;每轮结束拉一次快照并推送)。
855
907
  if (resolved.autoPushOnTurnEnd) {
908
+ // #30:有些宿主(Android/proot 的 DSH Go)不发 session/event;把"监听器已
909
+ // 注册"记进日志,让外部可判断的是宿主事件还是插件注册。
910
+ logger.info(`auto push listener registered (session/event turn/end → push); pullIntervalMinutes=${resolved.pullIntervalMinutes}`)
856
911
  ctx.on('session/event', (session, event) => {
857
912
  if (event.type !== 'turn/end') return
858
913
  void engine.push().then(result => {
@@ -911,4 +966,14 @@ export {
911
966
  sessionSyncDomainSpec,
912
967
  registryUnavailable,
913
968
  errorValue,
969
+ // 跨平台 cwd 投影(#28)与符号链接诊断(#30)的复用/测试面。
970
+ normalizeCwdMap,
971
+ matchCwdMap,
972
+ projectCwd,
973
+ projectKey,
974
+ projectedRelOf,
975
+ planRestoreFile,
976
+ canonicalizeProjectedFile,
977
+ readProjectionState,
978
+ readSessionHeader,
914
979
  }
package/lib/constants.mjs CHANGED
@@ -17,6 +17,10 @@ export const MIRROR_DIR = 'sessions'
17
17
  // 仓库根下的设备身份文件(随机 UUID,提交进仓库供跨设备归属 fork)。
18
18
  export const DEVICE_FILE = 'device.txt'
19
19
 
20
+ // 恢复期 cwd 投影:无 cwdMap 命中的跨平台会话归一到 sessionRoot 下的这个占位
21
+ // 目录(可见但只读——只出现在本机索引里,永远不作为推送源)。
22
+ export const UNMAPPED_DIR = '--unmapped--'
23
+
20
24
  // 存储领域 state 表的单例键。
21
25
  export const STATE_KEY = 'singleton'
22
26
 
@@ -84,9 +88,12 @@ export const FORK_NAME_RE = /\.remote-fork-\d{14}-[0-9a-z]{8}(?:\.|$)/iu
84
88
  // 名称来源(session-persistence-jsonl):
85
89
  // - lease.ts:40 LEASE_FILENAME = 'session.lock'(flock 租约;仅会话打开期间存在)
86
90
  // - generation.ts:725 `session.migration.<token><suffix>.tmp`(迁移暂存,失败自清)
91
+ // - 原子写暂存:`.l2s.<payload>.<hash>.tmp<seq>.<seq>`(宿主写入会话文件时的临时
92
+ // 文件;完成即 rename 或删除,同名内容还会被反复重写)。它让工作树长期处于
93
+ // stat-dirty 状态,git merge 会因此走 autostash 并失败(#29)。
87
94
  // 注意:`session.jsonl` / `session.v<N>.jsonl[.zstd]`(session-format/filename.ts 的
88
95
  // sessionFormatLogFilename + format.ts 的 logSuffix)是**同步载荷**,不在此列。
89
- export const HOST_ARTIFACT_NAME_RE = /^(?:session\.lock|session\.migration\..+\.tmp)$/u
96
+ export const HOST_ARTIFACT_NAME_RE = /^(?:session\.lock|session\.migration\..+\.tmp|\.l2s\..+)$/u
90
97
 
91
98
  // 默认值(Config schema 的默认与 DEFAULT_* 常量同源;cordis.yml 可整体覆盖)。
92
99
  export const DEFAULTS = Object.freeze({
@@ -104,6 +111,8 @@ export const DEFAULTS = Object.freeze({
104
111
  AUTO_PUSH_ON_TURN_END: false,
105
112
  PULL_INTERVAL_MINUTES: 0,
106
113
  CONFIRM_VIA: CONFIRM_CHANNELS.AUTO,
114
+ CWD_MAP: Object.freeze([]),
115
+ FOLLOW_SESSION_SYMLINKS: false,
107
116
  GRACE_MS: 10000,
108
117
  COMMAND_TIMEOUT_MS: 120000,
109
118
  MAX_OUTPUT_BYTES: 262144,
package/lib/cwdmap.mjs ADDED
@@ -0,0 +1,248 @@
1
+ // lib/cwdmap.mjs — 恢复期 cwd 投影(纯函数,零依赖)。
2
+ //
3
+ // 跨平台会话的 header.cwd 在另一台机器上不是本机绝对路径。宿主的
4
+ // dsh-workspace 用 realpathNormalize(header.cwd) 建 workspace 索引;
5
+ // session-persistence-jsonl 更靠前——header 解析本身就要求 cwd 是本机绝对
6
+ // 路径(`isAbsolute`),非本机路径的会话连"可见"都做不到。因此恢复时必须把
7
+ // cwd 投影成本机路径。投影只落在**本地副本**上:同步仓库(镜像)里的字节保持
8
+ // 原设备的 header,推送时由 lib/projection.mjs 把原首帧接回去(逐字节 append
9
+ // 语义不变)。
10
+ //
11
+ // 匹配语义(issue #28):
12
+ // - `cwdMap: [{from, to}]`,按最长前缀优先;
13
+ // - 前缀必须结束在路径段边界上(`C:\Users\me2` 不匹配 `C:\Users\me`);
14
+ // - Windows 风格前缀按 Windows 语义大小写不敏感比较,其余按字节比较;
15
+ // - 无匹配的跨平台 cwd 归一到 `sessionRoot/--unmapped--`(可见但只读)。
16
+
17
+ import path from 'node:path'
18
+ import { posix, win32 } from 'node:path'
19
+ import { UNMAPPED_DIR } from './constants.mjs'
20
+ import { badConfig } from './errors.mjs'
21
+
22
+ const WINDOWS_DRIVE_RE = /^[A-Za-z]:/u
23
+ const SEPARATOR_RUN_RE = /[\\/]+/gu
24
+ const TRAILING_SEPARATOR_RE = /[\\/]+$/u
25
+ const SAFE_PROJECT_KEY_CHAR_RE = /^[A-Za-z0-9._-]$/u
26
+
27
+ /**
28
+ * 是否形如 Windows 路径(盘符或 UNC)。
29
+ * @param {string} value - 原始路径。
30
+ * @returns {boolean} Windows 风格为 true。
31
+ */
32
+ function looksWindows(value) {
33
+ return WINDOWS_DRIVE_RE.test(value) || value.startsWith('\\\\')
34
+ }
35
+
36
+ /**
37
+ * 是否为某个平台上的完全限定路径(宿主 fullyQualifiedWorkspacePath 的并集)。
38
+ * @param {string} value - 原始路径。
39
+ * @returns {boolean} 任一并集平台上的绝对路径为 true。
40
+ */
41
+ function absoluteOnSomePlatform(value) {
42
+ if (typeof value !== 'string' || value.length === 0) return false
43
+ if (posix.isAbsolute(value)) return true
44
+ const root = win32.parse(value).root
45
+ return win32.isAbsolute(value) && root !== '\\' && root !== '/'
46
+ }
47
+
48
+ /**
49
+ * 宿主 `fullyQualifiedWorkspacePath` 的等价判定:本机平台的完全限定路径。
50
+ * (dsh-workspace/src/paths.ts:非 win32 用 posix.isAbsolute;win32 要求
51
+ * root 不是 `\` 或 `/`。)
52
+ * @param {string} value - 待判定路径。
53
+ * @param {NodeJS.Platform} [platform] - 目标平台(测试可注入)。
54
+ * @returns {boolean} 本机完全限定为 true。
55
+ */
56
+ export function isNativeAbsolutePath(value, platform = process.platform) {
57
+ if (typeof value !== 'string' || value.length === 0) return false
58
+ if (platform !== 'win32') return posix.isAbsolute(value)
59
+ const root = win32.parse(value).root
60
+ return win32.isAbsolute(value) && root !== '\\' && root !== '/'
61
+ }
62
+
63
+ /**
64
+ * 是否为"另一平台"的绝对路径(本机不可索引,但语义上是绝对路径)。
65
+ * 相对路径/空值不算——那种 header 本来就无效,不归投影管。
66
+ * @param {string} value - header cwd。
67
+ * @param {NodeJS.Platform} [platform] - 目标平台(测试可注入)。
68
+ * @returns {boolean} 跨平台绝对路径为 true。
69
+ */
70
+ export function isForeignCwd(value, platform = process.platform) {
71
+ if (typeof value !== 'string' || value.length === 0) return false
72
+ if (isNativeAbsolutePath(value, platform)) return false
73
+ return absoluteOnSomePlatform(value)
74
+ }
75
+
76
+ /**
77
+ * 路径 → 段数组(分隔符归一;去掉绝对根产生的空首段与尾部空段)。
78
+ * `C:\Users\me` → ['C:','Users','me'];`/home/me` → ['home','me'];`/` → []。
79
+ * @param {string} value - 路径。
80
+ * @returns {string[]} 段数组。
81
+ */
82
+ function splitSegments(value) {
83
+ const parts = value.replace(SEPARATOR_RUN_RE, '/').split('/')
84
+ if (parts.length > 0 && parts[0] === '') parts.shift()
85
+ while (parts.length > 0 && parts[parts.length - 1] === '') parts.pop()
86
+ return parts
87
+ }
88
+
89
+ /**
90
+ * 校验并规范化 cwdMap:非法项加载期响亮失败(Loud misconfiguration)。
91
+ * 规范化结果按最长前缀优先排序,并携带预计算段(匹配热路径不重复切分)。
92
+ * @param {unknown} entries - Config.cwdMap 原始值。
93
+ * @returns {ReadonlyArray<{from: string, to: string, windows: boolean, segments: ReadonlyArray<string>}>} 规范化后的映射表。
94
+ */
95
+ export function normalizeCwdMap(entries) {
96
+ if (entries === undefined || entries === null) return Object.freeze([])
97
+ if (!Array.isArray(entries)) throw badConfig('cwdMap must be an array of { from, to } objects')
98
+ const seen = new Set()
99
+ const normalized = []
100
+ for (const [index, entry] of entries.entries()) {
101
+ if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
102
+ throw badConfig(`cwdMap[${index}] must be an object with from/to`)
103
+ }
104
+ const value = /** @type {{from?: unknown, to?: unknown}} */ (entry)
105
+ const extra = Object.keys(entry).filter(key => key !== 'from' && key !== 'to')
106
+ if (extra.length > 0) throw badConfig(`cwdMap[${index}] has unknown key(s): ${extra.join(', ')}`)
107
+ if (typeof value.from !== 'string' || value.from.trim().length === 0) {
108
+ throw badConfig(`cwdMap[${index}].from must be a non-empty string`)
109
+ }
110
+ if (typeof value.to !== 'string' || value.to.trim().length === 0) {
111
+ throw badConfig(`cwdMap[${index}].to must be a non-empty string`)
112
+ }
113
+ const from = value.from.replace(TRAILING_SEPARATOR_RE, '') || value.from
114
+ const to = value.to.replace(TRAILING_SEPARATOR_RE, '') || value.to
115
+ if (!absoluteOnSomePlatform(from)) {
116
+ throw badConfig(`cwdMap[${index}].from must be an absolute path: ${JSON.stringify(value.from)}`)
117
+ }
118
+ if (!isNativeAbsolutePath(to)) {
119
+ throw badConfig(`cwdMap[${index}].to must be an absolute path on this platform: ${JSON.stringify(value.to)}`)
120
+ }
121
+ const windows = looksWindows(from)
122
+ const key = windows ? from.toLowerCase() : from
123
+ if (seen.has(key)) throw badConfig(`cwdMap has a duplicate from: ${JSON.stringify(value.from)}`)
124
+ seen.add(key)
125
+ normalized.push({ from, to, windows, segments: splitSegments(from) })
126
+ }
127
+ normalized.sort((left, right) =>
128
+ right.segments.length - left.segments.length
129
+ || right.from.length - left.from.length
130
+ || left.from.localeCompare(right.from))
131
+ return Object.freeze(normalized.map(entry => Object.freeze(entry)))
132
+ }
133
+
134
+ /**
135
+ * 最长前缀匹配(段边界)。cwd 必须能完整覆盖某个 from 的段序列。
136
+ * @param {string} cwd - header.cwd。
137
+ * @param {ReadonlyArray<{from: string, to: string, windows: boolean, segments: ReadonlyArray<string>}>} maps - normalizeCwdMap 的产物。
138
+ * @returns {{entry: {from: string, to: string, windows: boolean, segments: ReadonlyArray<string>}, remainder: string[]}|undefined} 匹配项与剩余段。
139
+ */
140
+ export function matchCwdMap(cwd, maps) {
141
+ if (typeof cwd !== 'string' || cwd.length === 0) return undefined
142
+ const segments = splitSegments(cwd)
143
+ for (const entry of maps) {
144
+ if (segments.length < entry.segments.length) continue
145
+ let matches = true
146
+ for (let index = 0; index < entry.segments.length; index += 1) {
147
+ const left = entry.windows ? segments[index].toLowerCase() : segments[index]
148
+ const right = entry.windows ? entry.segments[index].toLowerCase() : entry.segments[index]
149
+ if (left !== right) {
150
+ matches = false
151
+ break
152
+ }
153
+ }
154
+ if (!matches) continue
155
+ return { entry, remainder: segments.slice(entry.segments.length) }
156
+ }
157
+ return undefined
158
+ }
159
+
160
+ /**
161
+ * 把匹配项的剩余段接到 to 上(保持 to 的分隔符风格)。
162
+ * @param {{to: string}} entry - 匹配项。
163
+ * @param {string[]} remainder - 剩余段。
164
+ * @returns {string} 映射后的本机路径。
165
+ */
166
+ function joinMapped(entry, remainder) {
167
+ const separator = entry.to.includes('\\') ? '\\' : '/'
168
+ const tail = remainder.join(separator)
169
+ return tail.length === 0 ? entry.to : `${entry.to}${separator}${tail}`
170
+ }
171
+
172
+ /**
173
+ * 宿主 `projectKey(cwd)` 的等价实现(session-persistence-jsonl/src/format.ts)。
174
+ *
175
+ * 必须逐字一致:宿主用 `<root>/<projectKey(header.cwd)>/<sessionId>/<file>` 定位
176
+ * 会话,并在 `assertStoredIdentity` 里校验路径等于这条公式——投影后的目录名差
177
+ * 一个字符,恢复出来的会话就会被判 corrupt。分隔符(含 `:`)折叠为单个 `-`,
178
+ * 其余不安全字符转 `~XXXX`,截断到 251 字符后包成 `--…--`。
179
+ * @param {string} cwd - 会话的 cwd(必须非空)。
180
+ * @returns {string} 项目目录名。
181
+ */
182
+ export function projectKey(cwd) {
183
+ if (typeof cwd !== 'string' || cwd.length === 0) {
184
+ throw new Error('cannot encode an empty project path')
185
+ }
186
+ let readable = ''
187
+ let separatorRun = false
188
+ for (let index = 0; index < cwd.length; index += 1) {
189
+ const code = cwd.charCodeAt(index)
190
+ const character = String.fromCharCode(code)
191
+ if (character === '/' || character === '\\' || character === ':') {
192
+ if (!separatorRun) readable += '-'
193
+ separatorRun = true
194
+ } else if (character !== '~' && SAFE_PROJECT_KEY_CHAR_RE.test(character)) {
195
+ readable += character
196
+ separatorRun = false
197
+ } else {
198
+ readable += `~${code.toString(16).toUpperCase().padStart(4, '0')}`
199
+ separatorRun = false
200
+ }
201
+ }
202
+ const slug = readable.replace(/^-+/u, '') || 'root'
203
+ return `--${slug.slice(0, 251)}--`
204
+ }
205
+
206
+ /**
207
+ * 计算投影后的镜像相对路径:把 `<projectKey(原 cwd)>` 段换成
208
+ * `<projectKey(投影 cwd)>`,会话目录段与文件名不变(宿主布局
209
+ * `<projectDir>/<sessionId>/<file>`)。
210
+ * @param {string} canonicalRel - 镜像相对路径(POSIX 分隔)。
211
+ * @param {string} projectedCwd - 投影后的本机 cwd。
212
+ * @returns {string|undefined} 投影相对路径;旧扁平布局(不足 3 段)为 undefined。
213
+ */
214
+ export function projectedRelOf(canonicalRel, projectedCwd) {
215
+ if (typeof canonicalRel !== 'string' || canonicalRel.length === 0) return undefined
216
+ const parts = canonicalRel.split('/')
217
+ if (parts.length < 3) return undefined
218
+ const [projectDir, sessionDir, ...rest] = parts
219
+ if (projectDir.length === 0 || sessionDir.length === 0) return undefined
220
+ return [projectKey(projectedCwd), sessionDir, ...rest].join('/')
221
+ }
222
+
223
+ /**
224
+ * 恢复期 cwd 决策:有映射 → 映射目标;无映射的跨平台 cwd → 占位目录(只读);
225
+ * 本机 cwd → 原样。
226
+ * @param {string|undefined} cwd - header.cwd。
227
+ * @param {{map?: ReadonlyArray<object>, sessionRoot: string, platform?: NodeJS.Platform}} options - 映射表、会话根与平台。
228
+ * @returns {{cwd: string|undefined, mapped: boolean, unmapped: boolean, readOnly: boolean, from: string|undefined}} 投影决策。
229
+ */
230
+ export function projectCwd(cwd, options) {
231
+ if (typeof cwd !== 'string' || cwd.length === 0) {
232
+ return { cwd: undefined, mapped: false, unmapped: false, readOnly: false, from: cwd }
233
+ }
234
+ const match = matchCwdMap(cwd, options.map ?? [])
235
+ if (match !== undefined) {
236
+ return { cwd: joinMapped(match.entry, match.remainder), mapped: true, unmapped: false, readOnly: false, from: cwd }
237
+ }
238
+ if (!isForeignCwd(cwd, options.platform)) {
239
+ return { cwd, mapped: false, unmapped: false, readOnly: false, from: cwd }
240
+ }
241
+ return {
242
+ cwd: path.join(options.sessionRoot, UNMAPPED_DIR),
243
+ mapped: false,
244
+ unmapped: true,
245
+ readOnly: true,
246
+ from: cwd,
247
+ }
248
+ }
package/lib/encrypted.mjs CHANGED
@@ -218,13 +218,17 @@ export class EncryptedBackend {
218
218
  #onForks
219
219
  /** @type {{debug: Function, info: Function, warn: Function, error: Function}} */
220
220
  #logger
221
+ /** @type {ReadonlyArray<object>} 恢复期 cwd 投影表(与明文引擎同一份)。 */
222
+ #cwdMap
223
+ /** @type {boolean} 是否跟随根内符号链接(#30)。 */
224
+ #followSessionSymlinks
221
225
  /** @type {string[]} */
222
226
  #warnings = []
223
227
  /** @type {Promise<{mode: string, warnings: string[]}>|undefined} 惰性探测结果。 */
224
228
  #ready
225
229
 
226
230
  /**
227
- * @param {object} deps - {git, sessionRoot, repoDir, remote, branch, deviceId, reportMeta, reportError, onForks, logger, run, ageBin, ageRecipient, ageIdentity, timeoutMs}。
231
+ * @param {object} deps - {git, sessionRoot, repoDir, remote, branch, deviceId, reportMeta, reportError, onForks, logger, run, ageBin, ageRecipient, ageIdentity, timeoutMs, cwdMap?, followSessionSymlinks?}。
228
232
  */
229
233
  constructor(deps) {
230
234
  this.#git = deps.git
@@ -242,6 +246,8 @@ export class EncryptedBackend {
242
246
  this.#reportError = deps.reportError
243
247
  this.#onForks = deps.onForks
244
248
  this.#logger = deps.logger
249
+ this.#cwdMap = deps.cwdMap ?? []
250
+ this.#followSessionSymlinks = deps.followSessionSymlinks === true
245
251
  this.#plain = new SyncEngine({
246
252
  git: deps.git,
247
253
  sessionRoot: deps.sessionRoot,
@@ -253,6 +259,8 @@ export class EncryptedBackend {
253
259
  reportError: deps.reportError,
254
260
  onForks: deps.onForks,
255
261
  logger: deps.logger,
262
+ cwdMap: this.#cwdMap,
263
+ followSessionSymlinks: this.#followSessionSymlinks,
256
264
  })
257
265
  }
258
266
 
@@ -317,6 +325,7 @@ export class EncryptedBackend {
317
325
  sessionRoot: this.#sessionRoot,
318
326
  repoDir: this.#repoDir,
319
327
  mirrorDir: MIRROR_DIR,
328
+ followSessionSymlinks: this.#followSessionSymlinks,
320
329
  })
321
330
  }
322
331
 
package/lib/engine.mjs CHANGED
@@ -10,7 +10,7 @@
10
10
 
11
11
  import { promises as fs } from 'node:fs'
12
12
  import path from 'node:path'
13
- import { MERGE_KINDS, MIRROR_DIR, DEVICE_FILE } from './constants.mjs'
13
+ import { MERGE_KINDS, MIRROR_DIR, DEVICE_FILE, UNMAPPED_DIR } from './constants.mjs'
14
14
  import { planMerge } from './merge.mjs'
15
15
  import { mirrorSessionRoot, restoreSessionRoot, pruneRestoredSessions, ensureDeviceFile } from './mirror.mjs'
16
16
  import { collectStatus } from './status.mjs'
@@ -27,6 +27,8 @@ import { redactText, sanitizeRemote } from './sanitize.mjs'
27
27
  * @property {string} remote - 远端地址原文(展示时 sanitize)。
28
28
  * @property {string} branch - 分支名。
29
29
  * @property {string} deviceId - 设备 id(fork 归属)。
30
+ * @property {ReadonlyArray<object>} [cwdMap] - 恢复期 cwd 投影表(最长前缀优先)。
31
+ * @property {boolean} [followSessionSymlinks] - 镜像时是否跟随根内符号链接(#30;默认 false)。
30
32
  * @property {(patch: object) => void} reportMeta - 元数据补丁回调(index.mjs 写领域)。
31
33
  * @property {(message: string) => void} reportError - 最近错误回调(写领域 lastError)。
32
34
  * @property {(forkRelPaths: string[]) => void} onForks - fork 文件产生回调(index.mjs 做会话级 fork + 事件)。
@@ -84,10 +86,42 @@ export class SyncEngine {
84
86
  sessionRoot: this.#deps.sessionRoot,
85
87
  repoDir: this.#deps.repoDir,
86
88
  mirrorDir: MIRROR_DIR,
89
+ followSessionSymlinks: this.#deps.followSessionSymlinks === true,
87
90
  })
88
91
  return { deviceWritten, mirror }
89
92
  }
90
93
 
94
+ /**
95
+ * 镜像诊断(#28/#30):跳过/跟随的符号链接、cwd 投影计数与告警。
96
+ * @param {object} mirror - mirrorSessionRoot 产物。
97
+ * @returns {{skippedSymlinks: number, skippedSymlinkPaths: string[], followedSymlinks: number, cwdMapped: number, cwdUnmapped: number, cwdProjectionSkipped: number, cwdPlaceholder: string, followSessionSymlinks: boolean, warnings: string[]}} 诊断。
98
+ */
99
+ #mirrorDiagnostics(mirror) {
100
+ const skipped = Array.isArray(mirror.skippedLinks) ? mirror.skippedLinks : []
101
+ const warnings = []
102
+ if (skipped.length > 0) {
103
+ const sample = skipped.slice(0, 5).join(', ')
104
+ warnings.push(`${skipped.length} file(s) under sessionRoot were skipped as symbolic links and are not mirrored (${sample}${skipped.length > 5 ? ', …' : ''}); set followSessionSymlinks: true to include links whose realpath stays inside sessionRoot`)
105
+ }
106
+ if ((mirror.cwdUnmapped ?? 0) > 0) {
107
+ warnings.push(`${mirror.cwdUnmapped} session(s) with a cross-platform cwd have no cwdMap entry; they are shown read-only under ${path.join(this.#deps.sessionRoot, UNMAPPED_DIR)}`)
108
+ }
109
+ if (typeof mirror.projectionError === 'string') {
110
+ warnings.push(`cwd projection state is unreadable: ${mirror.projectionError}`)
111
+ }
112
+ return {
113
+ skippedSymlinks: skipped.length,
114
+ skippedSymlinkPaths: skipped.slice(0, 20),
115
+ followedSymlinks: Array.isArray(mirror.followedLinks) ? mirror.followedLinks.length : 0,
116
+ cwdMapped: mirror.cwdMapped ?? 0,
117
+ cwdUnmapped: mirror.cwdUnmapped ?? 0,
118
+ cwdProjectionSkipped: mirror.cwdProjectionSkipped ?? 0,
119
+ cwdPlaceholder: path.join(this.#deps.sessionRoot, UNMAPPED_DIR),
120
+ followSessionSymlinks: this.#deps.followSessionSymlinks === true,
121
+ warnings,
122
+ }
123
+ }
124
+
91
125
  // 前置镜像 + 提交。调用方(push/pull)已持有 schedule 锁,这里绝不能再走
92
126
  // #schedule —— 嵌套 schedule 会在同一 git 链上自锁(fnM 等 fnP 完成、fnP 等 fnM)。
93
127
  async #mirrorAndCommit(message) {
@@ -106,14 +140,30 @@ export class SyncEngine {
106
140
  */
107
141
  status() {
108
142
  return this.#schedule(async () => {
143
+ /** @type {object|undefined} */
144
+ let mirror
109
145
  try {
110
146
  await fs.mkdir(this.#deps.repoDir, { recursive: true })
111
147
  await this.#deps.git.ensureRepo()
112
- await this.#mirrorOnly()
148
+ mirror = (await this.#mirrorOnly()).mirror
113
149
  } catch {
114
150
  // 初始化/镜像失败不阻断状态:collectStatus 会返回带 error 的快照。
115
151
  }
116
- return collectStatus(this.#deps.git, { branch: this.#deps.branch, remote: this.#deps.remote ?? '' })
152
+ const collected = await collectStatus(this.#deps.git, { branch: this.#deps.branch, remote: this.#deps.remote ?? '' })
153
+ if (mirror === undefined) return collected
154
+ const diagnostics = this.#mirrorDiagnostics(mirror)
155
+ return {
156
+ ...collected,
157
+ skippedSymlinks: diagnostics.skippedSymlinks,
158
+ skippedSymlinkPaths: diagnostics.skippedSymlinkPaths,
159
+ followedSymlinks: diagnostics.followedSymlinks,
160
+ cwdMapped: diagnostics.cwdMapped,
161
+ cwdUnmapped: diagnostics.cwdUnmapped,
162
+ cwdProjectionSkipped: diagnostics.cwdProjectionSkipped,
163
+ cwdPlaceholder: diagnostics.cwdPlaceholder,
164
+ followSessionSymlinks: diagnostics.followSessionSymlinks,
165
+ warnings: diagnostics.warnings,
166
+ }
117
167
  })
118
168
  }
119
169
 
@@ -144,8 +194,9 @@ export class SyncEngine {
144
194
  await this.#deps.git.push({ signal: opts.signal })
145
195
  }
146
196
  const head = await this.#deps.git.headSha()
147
- this.#deps.reportMeta({ lastPushAt: Date.now(), lastPushHead: head })
197
+ this.#deps.reportMeta({ lastPushAt: Date.now(), lastPushHead: head, lastError: undefined })
148
198
  this.#deps.logger.info(`sync push ok: head ${head ?? ''} (${mirror.mirrored} mirrored, ${mirror.deleted} deleted)`)
199
+ const diagnostics = this.#mirrorDiagnostics(mirror)
149
200
  return {
150
201
  ok: true,
151
202
  pushed: true,
@@ -153,6 +204,9 @@ export class SyncEngine {
153
204
  mirrored: mirror.mirrored,
154
205
  deleted: mirror.deleted.length,
155
206
  remote: sanitizeRemote(this.#deps.remote),
207
+ skippedSymlinks: diagnostics.skippedSymlinks,
208
+ skippedSymlinkPaths: diagnostics.skippedSymlinkPaths,
209
+ warnings: diagnostics.warnings,
156
210
  }
157
211
  } catch (error) {
158
212
  return this.#fail(error)
@@ -172,7 +226,11 @@ export class SyncEngine {
172
226
  await fs.mkdir(this.#deps.repoDir, { recursive: true })
173
227
  await this.#deps.git.bootstrap()
174
228
  await this.#mirrorAndCommit('dsh-session-sync: local checkpoint before pull')
175
- return await this.#pullInternal(opts)
229
+ const result = await this.#pullInternal(opts)
230
+ // 成功的拉取清掉上一次的 lastError:它曾经永久保留,让用户按几天前的
231
+ // push 错误排查当前问题(#29)。
232
+ if (result.ok) this.#deps.reportMeta({ lastError: undefined })
233
+ return result
176
234
  } catch (error) {
177
235
  return this.#fail(error)
178
236
  }
@@ -205,6 +263,9 @@ export class SyncEngine {
205
263
  this.#deps.reportMeta({ lastPullAt: Date.now() })
206
264
  return { ok: true, pulled: false, forks: [], adopted: 0, appended: 0, diverged: 0 }
207
265
  }
266
+ // 先清掉 stat-dirty:宿主原子写暂存文件会让 git 误判工作树有未提交改动,
267
+ // 从而在 merge 时走 autostash 并失败(#29)。
268
+ await this.#deps.git.refreshIndex()
208
269
  const merged = await this.#deps.git.beginMerge(remoteHead)
209
270
  if (!merged.inProgress) {
210
271
  this.#deps.reportMeta({ lastPullAt: Date.now() })
@@ -224,7 +285,15 @@ export class SyncEngine {
224
285
  repoDir: this.#deps.repoDir,
225
286
  mirrorRoot,
226
287
  sessionRoot: this.#deps.sessionRoot,
288
+ cwdMap: this.#deps.cwdMap ?? [],
227
289
  })
290
+ const pullWarnings = []
291
+ if (restored.cwdUnmapped > 0) {
292
+ pullWarnings.push(`${restored.cwdUnmapped} restored session(s) have a cross-platform cwd and no cwdMap entry; they are visible read-only under ${path.join(this.#deps.sessionRoot, UNMAPPED_DIR)}`)
293
+ }
294
+ if (restored.cwdProjectionSkipped > 0) {
295
+ pullWarnings.push(`${restored.cwdProjectionSkipped} session file(s) could not be cwd-projected (unreadable header or legacy layout) and keep the origin device's cwd`)
296
+ }
228
297
  this.#deps.reportMeta({ lastPullAt: Date.now() })
229
298
  this.#deps.logger.info(`sync pull ok: merged remote head ${remoteHead} → ${newHead ?? ''} (${result.appended} appended-both, ${result.diverged} diverged, ${result.forks.length} forks, ${restored.restored} restored, ${pruned.pruned.length} pulled-deletions)`)
230
299
  if (result.forks.length > 0) this.#deps.onForks(result.forks)
@@ -237,7 +306,10 @@ export class SyncEngine {
237
306
  diverged: result.diverged,
238
307
  forks: result.forks,
239
308
  restored: restored.restored,
309
+ cwdMapped: restored.cwdMapped,
310
+ cwdUnmapped: restored.cwdUnmapped,
240
311
  head: newHead ?? undefined,
312
+ warnings: pullWarnings,
241
313
  }
242
314
  }
243
315