dsh-session-sync 0.2.33 → 0.3.2

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/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
 
@@ -105,8 +109,12 @@ export const DEFAULTS = Object.freeze({
105
109
  AGE_IDENTITY: '',
106
110
  AUTO_PULL_ON_START: false,
107
111
  AUTO_PUSH_ON_TURN_END: false,
112
+ // 自动推送前等宿主把该会话落盘的上限(ms);见 lib/durability.mjs。
113
+ DURABILITY_TIMEOUT_MS: 2000,
108
114
  PULL_INTERVAL_MINUTES: 0,
109
115
  CONFIRM_VIA: CONFIRM_CHANNELS.AUTO,
116
+ CWD_MAP: Object.freeze([]),
117
+ FOLLOW_SESSION_SYMLINKS: false,
110
118
  GRACE_MS: 10000,
111
119
  COMMAND_TIMEOUT_MS: 120000,
112
120
  MAX_OUTPUT_BYTES: 262144,
@@ -126,6 +134,9 @@ export const LIMITS = Object.freeze({
126
134
  MAX_MAX_OUTPUT_BYTES: 16 * 1024 * 1024,
127
135
  MIN_PULL_INTERVAL_MINUTES: 0,
128
136
  MAX_PULL_INTERVAL_MINUTES: 10080,
137
+ // 0 = 不等待(旧行为);上限与 timer 上限无关,只是别让自动推送被拖太久。
138
+ MIN_DURABILITY_TIMEOUT_MS: 0,
139
+ MAX_DURABILITY_TIMEOUT_MS: 60_000,
129
140
  MAX_COMMIT_MESSAGE_LENGTH: 200,
130
141
  MAX_DEVICE_ID_LENGTH: 128,
131
142
  })
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/domain.mjs CHANGED
File without changes
@@ -0,0 +1,80 @@
1
+ // lib/durability.mjs — 等宿主把该会话的缓冲事件落盘再读(零 DSH 依赖)。
2
+ //
3
+ // 为什么不能"turn/end 一到就镜像":宿主的 JSONL 持久化对 **live 事件**做有界
4
+ // 批量写窗 —— `LIVE_WRITE_BATCH_MAX_DELAY_MS = 200`
5
+ // (session-persistence-jsonl/src/storage.ts:37);`session/event` 只是把事件
6
+ // 交给 `enqueueLive` 缓冲并起一个 200ms 定时器(同文件 :269-283),真正的
7
+ // `persistBatch` 发生在定时器或 `session/flush` 触发时(同文件 :286-341、:555-562)。
8
+ // 因此 `turn/end` 刚 append 时,磁盘上的会话日志通常**还没有这一行**(首次
9
+ // 追加时甚至整个会话文件都还没物化)。在 turn/end 上立刻做字节镜像,推给
10
+ // 别的设备的就是一个**未闭合的轮次**——这正是本插件要避免的跨设备状态不一致。
11
+ //
12
+ // 宿主 0.2.2 给出的公开落盘面是 `SessionStore.flush(session)`
13
+ // (@deepseek-ai/dsh-session 的 `ctx.sessions.flush`;core/session/src/index.ts:1410-1434,
14
+ // 注释明确写着 "THE flush entry point … consumers that flush themselves before
15
+ // reading storage")。它派发 `session/flush`(core/session/src/types.ts:74),
16
+ // 持久化后端随即 `drainLive()` + `handle.flush()`(storage.ts:555-562),
17
+ // 因此 flush 决议时该会话已 append 的事件都已落盘。宿主自己的事件文档也把
18
+ // 这条责任写给了读存储的消费者:"consumers that read storage after
19
+ // `whenIdle()` flush themselves"(core/session/src/types.ts:299-300)。
20
+ //
21
+ // 本模块只包这一件事:调用落盘屏障 + 超时兜底。**任何失败/超时只回报,绝不抛**
22
+ // ——调用方照常镜像(宁可镜像落后一拍,也不让一轮会话被卡死的后端拖住)。
23
+
24
+ import { messageOf } from './errors.mjs'
25
+
26
+ /** 未配置时的落盘等待上限(ms):远大于宿主的 200ms 批量窗,又远小于一轮交互。 */
27
+ export const DURABILITY_TIMEOUT_MS = 2000
28
+
29
+ /**
30
+ * @typedef {object} DurabilityOutcome
31
+ * @property {boolean} ok - true = 屏障已决议(宿主无持久化监听器也算:没有待落盘的东西)。
32
+ * @property {boolean} [timedOut] - 超时(调用方应继续镜像,只记日志)。
33
+ * @property {boolean} [unsupported] - 该宿主没有公开的 `flush` 面(旧宿主),无法等待。
34
+ * @property {boolean} [skipped] - 配置为 0,明确不等待。
35
+ * @property {string} [error] - 屏障自身失败(脱敏后的消息);不是抛出。
36
+ */
37
+
38
+ /**
39
+ * 等待 `session` 的缓冲事件落盘,最多 `timeoutMs`。
40
+ *
41
+ * 顺序契约:本函数**先让出一个微任务**再调用 `flush`。宿主的 `session/event`
42
+ * 监听器是同步派发的(core/session/src/index.ts 的 `commit()` →
43
+ * `invokeContainedSessionObservers`),持久化后端的 `enqueueLive` 与我们的
44
+ * 处理器在同一个同步派发里;微任务只会在整个同步派发结束后运行,所以
45
+ * `drainLive()` 一定看得见触发本次调用的那条 `turn/end`。
46
+ *
47
+ * @param {unknown} session - 宿主的 live `Session`(原样交给 `flush`)。
48
+ * @param {object} [deps] - 依赖与上限。
49
+ * @param {{flush?: (session: unknown) => unknown}} [deps.sessions] - `ctx.sessions`(能力探测:无 `flush` 即旧宿主)。
50
+ * @param {number} [deps.timeoutMs] - 等待上限(ms,≤0 = 不等待)。
51
+ * @returns {Promise<DurabilityOutcome>} 结果对象;永不 reject。
52
+ */
53
+ export async function waitForSessionDurability(session, deps = {}) {
54
+ const sessions = deps?.sessions
55
+ const flush = sessions?.flush
56
+ if (typeof flush !== 'function') return { ok: false, unsupported: true }
57
+ const timeoutMs = Number.isFinite(deps?.timeoutMs) ? Number(deps.timeoutMs) : DURABILITY_TIMEOUT_MS
58
+ if (timeoutMs <= 0) return { ok: false, skipped: true }
59
+ // 见上方「顺序契约」:让同一事件的其余同步监听器先把事件交进持久化缓冲。
60
+ await Promise.resolve()
61
+ /** @type {ReturnType<typeof setTimeout> | undefined} */
62
+ let timer
63
+ // 同步抛出的 flush 也要落到 outcome 里(async 包装把 throw 变成 rejection)。
64
+ const flushed = (async () => flush.call(sessions, session))().then(
65
+ () => ({ kind: /** @type {const} */ ('flushed') }),
66
+ (error) => ({ kind: /** @type {const} */ ('failed'), error }),
67
+ )
68
+ const deadline = new Promise((resolve) => {
69
+ timer = setTimeout(() => resolve({ kind: 'timeout' }), timeoutMs)
70
+ })
71
+ try {
72
+ /** @type {{kind: 'flushed'|'failed'|'timeout', error?: unknown}} */
73
+ const outcome = await Promise.race([flushed, deadline])
74
+ if (outcome.kind === 'flushed') return { ok: true }
75
+ if (outcome.kind === 'timeout') return { ok: false, timedOut: true }
76
+ return { ok: false, error: messageOf(outcome.error) }
77
+ } finally {
78
+ clearTimeout(timer)
79
+ }
80
+ }
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
 
@@ -146,6 +196,7 @@ export class SyncEngine {
146
196
  const head = await this.#deps.git.headSha()
147
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)
@@ -231,7 +285,15 @@ export class SyncEngine {
231
285
  repoDir: this.#deps.repoDir,
232
286
  mirrorRoot,
233
287
  sessionRoot: this.#deps.sessionRoot,
288
+ cwdMap: this.#deps.cwdMap ?? [],
234
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
+ }
235
297
  this.#deps.reportMeta({ lastPullAt: Date.now() })
236
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)`)
237
299
  if (result.forks.length > 0) this.#deps.onForks(result.forks)
@@ -244,7 +306,10 @@ export class SyncEngine {
244
306
  diverged: result.diverged,
245
307
  forks: result.forks,
246
308
  restored: restored.restored,
309
+ cwdMapped: restored.cwdMapped,
310
+ cwdUnmapped: restored.cwdUnmapped,
247
311
  head: newHead ?? undefined,
312
+ warnings: pullWarnings,
248
313
  }
249
314
  }
250
315
 
package/lib/errors.mjs CHANGED
File without changes
package/lib/gate.mjs CHANGED
File without changes
package/lib/git.mjs CHANGED
File without changes
package/lib/merge.mjs CHANGED
File without changes