dsh-xlock 0.0.0-stage → 0.2.9

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.
@@ -0,0 +1,170 @@
1
+ /**
2
+ * dsh-xlock — 归档状态跨机同步器(core/archivesync.mjs)
3
+ *
4
+ * 把宿主 `~/.dsh/storages/workspace.json`(不在同步面)里 `global.archivedSessionIds`
5
+ * 这份**本机归档集**,和会话目录(在同步面,经 Syncthing 跨机同步)里每个会话的
6
+ * 归档标记文件(core/archive.mjs,`.dsh-xlock-archive.json`)做成双向对账:
7
+ *
8
+ * 写侧:宿主归档集变化(domain/changed 事件)→ 差异落成标记文件,随会话目录
9
+ * 走文件级同步推给对端机器。
10
+ * 读侧:对端写的标记文件 → 收敛到本机宿主归档集(workspaceRegistry.archiveSession /
11
+ * unarchiveSession),让对端的归档决定在本机也生效。
12
+ *
13
+ * 这套机制原先住在 dsh-tweaks(`createArchiveSync`,index.js:1326-1450),现在按
14
+ * 用户要求整体搬来 xlock(tweaks 不参与 xlock 会话相关的任何功能)。原实现的三条
15
+ * 纪律(只处理真变化、目录索引一次建全、盘上已是目标值不重写防回声)原样保留,
16
+ * 只是标记文件名和存放位置换成了 xlock 自己的命名空间(core/archive.mjs,双读单写
17
+ * 兼容存量 `.dsh-tweaks-archive.json`)。
18
+ *
19
+ * 非目标:不做归档与锁(core/marker.mjs)的因果绑定——归档与否不影响粘锁状态,
20
+ * 两者是同一目录里的两套独立标记,只是共享"贴身跟着会话目录走同步面"这条路。
21
+ */
22
+
23
+ import { scanArchiveMarkers, writeArchiveMarker } from './archive.mjs'
24
+ import { sessionsRoot } from './sessionfs.mjs'
25
+
26
+ function nonNegativeInt(value, fallback) {
27
+ return Number.isInteger(value) && value >= 0 ? value : fallback
28
+ }
29
+
30
+ /**
31
+ * 启动(或按需)对账一次归档集 ↔ 归档标记。
32
+ *
33
+ * ctx 需要暴露 `workspaceRegistry`(`archiveSession`/`unarchiveSession` 两个函数 +
34
+ * `archivedSessionIds` 数组);三者任一缺失即整体退化成空函数(no-op),不报错——
35
+ * 单元测试里可以只给 `{ logger: {}, on: () => () => {} }` 这种最小上下文验证不崩。
36
+ *
37
+ * 返回 disposer(清理定时器 + 注销 domain/changed 订阅);额外暴露 `dispose.scan`
38
+ * (单次读侧对账)和 `dispose.writeDiff`(单次写侧对账),仅供独立测试 harness 直接
39
+ * 调用——Cordis 只把返回值当 disposer 用,这两个属性是测试钩子,不是公开 API。
40
+ *
41
+ * @param {{ workspaceRegistry?: object, on?: Function, logger?: object }} ctx
42
+ * @param {number} [intervalMs=15000] 读侧对账轮询间隔;0 = 关闭定时器(只跑一次/手动触发)。
43
+ * @returns {(() => void) & { scan?: Function, writeDiff?: Function }}
44
+ */
45
+ export function createArchiveSync(ctx, intervalMs = 15000) {
46
+ const delay = nonNegativeInt(intervalMs, 15000)
47
+ const registry = ctx?.workspaceRegistry
48
+ if (
49
+ delay === 0 || !registry || typeof registry.archiveSession !== 'function' ||
50
+ typeof registry.unarchiveSession !== 'function' || !Array.isArray(registry.archivedSessionIds)
51
+ ) return () => {}
52
+
53
+ let stopped = false
54
+ let activeScan
55
+ let knownArchived = new Set(registry.archivedSessionIds.map(String))
56
+
57
+ function warn(key, error) {
58
+ try { ctx.logger?.warn?.(`dsh-xlock archive sync: ${key}: ${String(error?.message ?? error)}`) } catch {}
59
+ }
60
+
61
+ /**
62
+ * 写侧:把归档集的差异落成标记。`next` 是本机此刻的归档集(权威)。
63
+ *
64
+ * 三条纪律:
65
+ * ① 只处理「相对上一轮真的变了」的 id —— 否则任何一次无关的 workspace 写
66
+ * (改标题、加成员)都会重写全部会话目录,把同步面搅成噪音;
67
+ * ② 目录索引一次建全 —— 批量归档几十条时不能每条都重扫一遍目录树;
68
+ * ③ 盘上那份已经写着目标值时**不重写** —— 读侧把对端的标记应用到本机归档集
69
+ * 之后会经由 `domain/changed` 回到这里,重写会把「是谁归档的」抹成本机。
70
+ * 值一致就没有什么要传播的,跳过即可(这也顺带掐断了回声)。
71
+ */
72
+ function writeDiff(next) {
73
+ const added = [...next].filter((id) => !knownArchived.has(id))
74
+ const removed = [...knownArchived].filter((id) => !next.has(id))
75
+ if (added.length === 0 && removed.length === 0) return
76
+ const index = new Map(
77
+ scanArchiveMarkers({ sessionsDir: sessionsRoot() }).map((row) => [row.sessionId, row]),
78
+ )
79
+ for (const id of [...added, ...removed]) {
80
+ const archived = added.includes(id)
81
+ const row = index.get(id)
82
+ if (row === undefined) continue
83
+ const remember = () => {
84
+ knownArchived = archived
85
+ ? new Set([...knownArchived, id])
86
+ : new Set([...knownArchived].filter((x) => x !== id))
87
+ }
88
+ // 盘上已经是目标值:那是读侧刚应用的对端标记,重写会把作者抹成本机。
89
+ if (row.source === 'marker' && row.archived === archived) {
90
+ remember()
91
+ continue
92
+ }
93
+ const result = writeArchiveMarker(row.dir, archived)
94
+ if (result.ok) remember()
95
+ else warn(`write ${id}`, result.error)
96
+ }
97
+ }
98
+
99
+ /**
100
+ * 读侧:对端写的标记 → 本机归档集。
101
+ *
102
+ * 只动「与宿主归档集不一致」的会话。异常一律只记日志:一条会话收敛失败不该
103
+ * 拖住其余会话,更不该让插件崩掉。
104
+ */
105
+ async function applyMarkers() {
106
+ const markers = scanArchiveMarkers({ sessionsDir: sessionsRoot() })
107
+ const current = new Set(registry.archivedSessionIds.map(String))
108
+ for (const row of markers) {
109
+ if (stopped) return
110
+ if (row.source !== 'marker' || typeof row.archived !== 'boolean') continue
111
+ const wanted = row.archived
112
+ if (current.has(row.sessionId) === wanted) continue
113
+ try {
114
+ if (wanted) await registry.archiveSession(row.sessionId, { stopActivity: true })
115
+ else await registry.unarchiveSession(row.sessionId)
116
+ if (wanted) current.add(row.sessionId)
117
+ else current.delete(row.sessionId)
118
+ } catch (error) {
119
+ warn(`apply ${row.sessionId}`, error)
120
+ }
121
+ }
122
+ }
123
+
124
+ async function scanOnce() {
125
+ try {
126
+ await applyMarkers()
127
+ } catch (error) {
128
+ warn('marks', error)
129
+ }
130
+ }
131
+
132
+ function scan() {
133
+ if (stopped) return Promise.resolve()
134
+ if (activeScan) return activeScan
135
+ activeScan = scanOnce()
136
+ .catch((error) => warn('list', error))
137
+ .finally(() => { activeScan = undefined })
138
+ return activeScan
139
+ }
140
+
141
+ // 写侧:只在归档集真的变化时落标记(`domain/changed` 的 global put)。
142
+ const offChanged = typeof ctx.on === 'function'
143
+ ? ctx.on('domain/changed', (change) => {
144
+ if (!change || change.domain !== 'workspace') return
145
+ if (change.table !== '' || change.operation !== 'put') return
146
+ const next = new Set(
147
+ Array.isArray(change.value?.archivedSessionIds) ? change.value.archivedSessionIds.map(String) : [],
148
+ )
149
+ try {
150
+ writeDiff(next)
151
+ } catch (error) {
152
+ warn('write', error)
153
+ }
154
+ })
155
+ : null
156
+
157
+ const timer = setInterval(() => { void scan() }, delay)
158
+ void scan()
159
+
160
+ function dispose() {
161
+ if (stopped) return
162
+ stopped = true
163
+ clearInterval(timer)
164
+ if (typeof offChanged === 'function') { try { offChanged() } catch {} }
165
+ }
166
+ // Exposed only to the standalone test harness; Cordis uses the disposer itself.
167
+ dispose.scan = scan
168
+ dispose.writeDiff = writeDiff
169
+ return dispose
170
+ }
package/core/audit.mjs ADDED
@@ -0,0 +1,226 @@
1
+ /**
2
+ * dsh-xlock — 会话审计(CLI 与写打开顺手审计共用)。
3
+ *
4
+ * audit 对一个会话目录:
5
+ * - 走查全部 canonical 日志(健康 + 记录画像);
6
+ * - 走查全部冲突副本并对照同版本主文件分类;
7
+ * - 报告标记状态与标记冲突副本(异机持锁痕迹);
8
+ * - 默认不动任何文件(AC6),唯二例外:--gc 顺带清隔离区;
9
+ * divergent 副本在【写打开门禁】里隔离时才落盘。
10
+ */
11
+
12
+ import { readFileSync, statSync } from 'node:fs'
13
+ import { basename, dirname, join } from 'node:path'
14
+ import { walkLog } from './frames.mjs'
15
+ import { auditCopyFile, detectOpenTurn } from './classify.mjs'
16
+ import { inventorySessionDir, machineName } from './sessionfs.mjs'
17
+ import { markerStatus } from './marker.mjs'
18
+ import { inferOrigin, originSourceLabel } from './origin.mjs'
19
+ import { isoUtc } from './util.mjs'
20
+
21
+ /**
22
+ * 审计一个会话目录。
23
+ * @param {string} dir 会话目录绝对路径
24
+ * @param {{identity:{uuid:string,host:string}, machines:object, sessionName?:string}} env
25
+ * @returns {object} 报告(含 needsAttention 汇总)
26
+ */
27
+ export function auditSessionDir(dir, { identity, machines, sessionName }) {
28
+ const inv = inventorySessionDir(dir)
29
+ const canonical = inv.canonical
30
+ .slice()
31
+ .sort((a, b) => b.version - a.version)
32
+ .map((entry) => {
33
+ let walk
34
+ let error
35
+ try {
36
+ walk = walkLogRead(entry.path)
37
+ } catch (e) {
38
+ error = String(e?.message || e)
39
+ }
40
+ const summary = walk ? summarizeWalk(walk) : undefined
41
+ return {
42
+ name: entry.name,
43
+ version: entry.version,
44
+ bytes: fileSize(entry.path),
45
+ error,
46
+ ...summary,
47
+ }
48
+ })
49
+
50
+ const primaryByVersion = new Map(canonical.filter((c) => c.error === undefined).map((c) => [c.version, c]))
51
+
52
+ const copies = inv.logConflicts
53
+ .slice()
54
+ .sort((a, b) => (a.version - b.version) || String(a.name).localeCompare(b.name))
55
+ .map((entry) => {
56
+ const primaryEntry = primaryByVersion.get(entry.version)
57
+ const primaryPath = primaryEntry ? canonicalPathOf(dir, primaryEntry.name) : joinGuess(dir, entry)
58
+ const verdict = auditCopyFile(entry.path, primaryPath)
59
+ const mn = machineName(entry.shortId, machines)
60
+ return {
61
+ name: entry.name,
62
+ version: entry.version,
63
+ shortId: entry.shortId,
64
+ machine: mn,
65
+ syncedAtUtc: entry.date && entry.time ? `${entry.date.slice(0, 4)}-${entry.date.slice(4, 6)}-${entry.date.slice(6, 8)}T${entry.time.slice(0, 2)}:${entry.time.slice(2, 4)}:${entry.time.slice(4, 6)}Z` : undefined,
66
+ bytes: fileSize(entry.path),
67
+ kind: verdict.kind,
68
+ firstDivergenceSeq: verdict.firstDivergenceSeq,
69
+ copyEventCount: verdict.copyEventCount,
70
+ primaryEventCount: verdict.primaryEventCount,
71
+ copyOnlyCount: verdict.copyOnly ? verdict.copyOnly.length : undefined,
72
+ differingCount: verdict.differing ? verdict.differing.length : undefined,
73
+ error: verdict.error,
74
+ copy: verdict.copy,
75
+ }
76
+ })
77
+
78
+ const marker = markerStatus(dir, identity)
79
+ // 创建归属:三层证据(创建记录 → 目录桶推断 → 未知)。
80
+ // 注意它和 marker 是两件事:marker 是"现在谁持有",归属是"当初谁建的"。
81
+ const origin = inferOrigin(dir, {
82
+ identity,
83
+ registry: machines,
84
+ bucket: basename(dirname(dir)),
85
+ })
86
+ const needsAttention = []
87
+ if (copies.some((c) => c.kind === 'divergent')) needsAttention.push('divergent-copy')
88
+ if (copies.some((c) => c.kind === 'unreadable')) needsAttention.push('unreadable-copy')
89
+ if (copies.some((c) => c.kind === 'orphan')) needsAttention.push('orphan-copy')
90
+ if (inv.markerConflicts.length > 0) needsAttention.push('marker-conflict-copy')
91
+ if (marker.foreign || marker.corrupt) needsAttention.push('marker-held')
92
+ for (const c of canonical) {
93
+ if (c.error !== undefined) needsAttention.push(`primary-unreadable:${c.name}`)
94
+ else if (c.health?.tornJsonlLastLine) needsAttention.push(`torn-jsonl:${c.name}`)
95
+ else if (c.health?.seqGaps?.length) needsAttention.push(`seq-gap:${c.name}`)
96
+ }
97
+
98
+ return {
99
+ sessionId: sessionName || basename(dir),
100
+ dir,
101
+ at: isoUtc(),
102
+ canonical,
103
+ copies,
104
+ markerConflicts: inv.markerConflicts,
105
+ marker: {
106
+ state: marker.state,
107
+ corrupt: marker.corrupt,
108
+ foreign: marker.foreign,
109
+ holder: marker.holder,
110
+ conflicts: marker.conflicts,
111
+ },
112
+ origin,
113
+ needsAttention: [...new Set(needsAttention)],
114
+ }
115
+ }
116
+
117
+ function canonicalPathOf(dir, name) {
118
+ return join(dir, name)
119
+ }
120
+
121
+ /** 同版本 canonical 缺失时,退而求其次找任意更高版本主文件比较(供 orphan 判断)。 */
122
+ function joinGuess(dir, entry) {
123
+ return canonicalPathOf(dir, `session.v${entry.version}.jsonl.zstd`)
124
+ }
125
+
126
+ function walkLogRead(path) {
127
+ return walkLog(readFileSync(path))
128
+ }
129
+
130
+ function fileSize(path) {
131
+ try {
132
+ return statSync(path).size
133
+ } catch {
134
+ return 0
135
+ }
136
+ }
137
+
138
+ function summarizeWalk(walk) {
139
+ const events = walk.records.filter((r) => typeof r.seq === 'number')
140
+ // 真机事件用 time(header 用 createdAt);两者都收,取真实跨度。
141
+ const stamps = walk.records
142
+ .map((r) => (typeof r.time === 'number' ? r.time : typeof r.createdAt === 'number' ? r.createdAt : undefined))
143
+ .filter((n) => typeof n === 'number')
144
+ const lastTurnEnd = [...walk.records].reverse().find((r) => r.type === 'turn/end')
145
+ return {
146
+ header: walk.header,
147
+ eventCount: events.length,
148
+ seqFirst: events.length ? events[0].seq : undefined,
149
+ seqLast: events.length ? events[events.length - 1].seq : undefined,
150
+ createdAtFirst: stamps.length ? Math.min(...stamps) : undefined,
151
+ createdAtLast: stamps.length ? Math.max(...stamps) : undefined,
152
+ lastTurn: lastTurnEnd ? { turn: lastTurnEnd.turn, reason: lastTurnEnd.raw?.reason } : undefined,
153
+ openTurn: detectOpenTurn(walk.records),
154
+ health: walk.health,
155
+ }
156
+ }
157
+
158
+ /**
159
+ * 把审计报告渲染成人读文本。
160
+ * @param {object} report auditSessionDir 的返回值
161
+ * @returns {string}
162
+ */
163
+ export function renderReport(report) {
164
+ const L = []
165
+ L.push(`会话 ${report.sessionId}`)
166
+ L.push(` 目录: ${report.dir}`)
167
+ for (const c of report.canonical) {
168
+ if (c.error !== undefined) {
169
+ L.push(` 主文件 ${c.name}: 不可读 (${c.error})`)
170
+ continue
171
+ }
172
+ const range =
173
+ c.createdAtFirst && c.createdAtLast
174
+ ? `${new Date(c.createdAtFirst).toISOString()} → ${new Date(c.createdAtLast).toISOString()}`
175
+ : '(no timestamps)'
176
+ const flags = []
177
+ if (c.health.tornTailFrame) flags.push('torn-tail-frame(写打开自愈)')
178
+ if (c.health.tornJsonlLastLine) flags.push('torn-JSONL-末行(需修复)')
179
+ if (c.health.seqGaps.length) flags.push(`seq-gap×${c.health.seqGaps.length}`)
180
+ if (c.openTurn !== undefined) flags.push(`turn***REMOVED***${c.openTurn}未闭合`)
181
+ L.push(
182
+ ` 主文件 ${c.name}: ${c.eventCount} events, frames=${c.health.frameCount}, ${range}` +
183
+ (flags.length ? ` ⚠ ${flags.join(', ')}` : ' ✓'),
184
+ )
185
+ }
186
+ if (report.copies.length === 0) {
187
+ L.push(' 冲突副本: 无')
188
+ }
189
+ for (const c of report.copies) {
190
+ const known = c.machine.known ? c.machine.name : `${c.machine.name}(未补录 → machines.json)`
191
+ L.push(
192
+ ` 副本 ${c.name}: [${c.kind}] 来自 ${known}` +
193
+ (c.syncedAtUtc ? ` 冲突于 ${c.syncedAtUtc}` : '') +
194
+ (c.firstDivergenceSeq !== undefined ? ` 首个分叉 seq=${c.firstDivergenceSeq}` : '') +
195
+ ` (copy=${c.copyEventCount ?? '?'} vs primary=${c.primaryEventCount ?? '?'})`,
196
+ )
197
+ }
198
+ if (report.markerConflicts.length > 0) {
199
+ L.push(` ⚠ 标记冲突副本×${report.markerConflicts.length}: ${report.markerConflicts.join(', ')}`)
200
+ }
201
+ const o = report.origin
202
+ if (o) {
203
+ const label = o.known ? o.host : `${o.host}(未登记 → machines.json)`
204
+ L.push(
205
+ ` 创建归属: ${label}${o.local ? '(本机)' : '(异机)'} · 依据 ${originSourceLabel(o.source)}` +
206
+ (o.conflicts > 0 ? ` · ⚠ 创建记录冲突副本×${o.conflicts}` : ''),
207
+ )
208
+ }
209
+ const m = report.marker
210
+ if (m.state === 'held') {
211
+ L.push(` 锁标记: held by ${m.holder?.host || '?'}${m.foreign ? '(异机)' : '(本机)'}`)
212
+ } else if (m.state === 'released') {
213
+ L.push(' 锁标记: released(可接管)')
214
+ } else if (m.corrupt) {
215
+ L.push(' 锁标记: 损坏(fail-safe 视为持有)→ xlock 工具 reset(或 dsh-xlock.ps1 reset)')
216
+ } else {
217
+ L.push(' 锁标记: 无')
218
+ }
219
+ if (report.needsAttention.length > 0) {
220
+ L.push(` 需要处理: ${report.needsAttention.join(', ')}`)
221
+ L.push(' 裁决入口: xlock 工具 resolve(或 dsh-xlock.ps1 resolve)<session> --keep primary|copy')
222
+ } else {
223
+ L.push(' 状态: 健康')
224
+ }
225
+ return L.join('\n')
226
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * dsh-xlock — 冲突副本分类(对照主文件)。
3
+ *
4
+ * 三分类(人裁决,绝不机械合并):
5
+ * - identical:与主文件记录完全一致(冗余,可隔离删除);
6
+ * - prefix :副本是主文件的严格前缀(旧状态,可隔离删除);
7
+ * - divergent:同 seq 内容不同,或副本含主文件没有的 seq(真分叉 → 导出+人裁决);
8
+ * - unreadable:副本无法完整解码(fail-safe:按 divergent 通道拦截,不自动删);
9
+ * - orphan :同版本主文件不存在(归属不明 → 报告,不自动动)。
10
+ *
11
+ * 比较按「记录序列」不按帧:两机的提交批(frame 边界)天然不同。
12
+ */
13
+
14
+ import { readFileSync } from 'node:fs'
15
+ import { walkLog } from './frames.mjs'
16
+
17
+ /**
18
+ * 比较副本记录与主文件记录。
19
+ * @param {{records:Array, health:object}} primary walkLog(主文件)
20
+ * @param {{records:Array, health:object}} copy walkLog(副本)
21
+ * @returns {{
22
+ * kind: 'identical'|'prefix'|'divergent'|'unreadable',
23
+ * firstDivergenceSeq?: number,
24
+ * copyOnly: Array<object>, // 副本独有记录(seq 超出主文件范围)
25
+ * differing: Array<{seq:number, primary:object, copy:object}>, // 同 seq 内容不同
26
+ * copyEventCount: number,
27
+ * primaryEventCount: number,
28
+ * }}
29
+ */
30
+ export function classifyCopy(primary, copy) {
31
+ const p = primary.records.filter((r) => typeof r.seq === 'number')
32
+ const c = copy.records.filter((r) => typeof r.seq === 'number')
33
+ const result = {
34
+ kind: 'identical',
35
+ copyOnly: [],
36
+ differing: [],
37
+ copyEventCount: c.length,
38
+ primaryEventCount: p.length,
39
+ }
40
+ if (copy.health.corruptMiddle || copy.health.frameCount === 0 || (copy.health.tornTailFrame && c.length === 0)) {
41
+ // 零帧 = 完全解不开(垃圾字节或全损坏)→ fail-safe unreadable。
42
+ result.kind = 'unreadable'
43
+ return result
44
+ }
45
+ const pBySeq = new Map(p.map((r) => [r.seq, r]))
46
+ const maxPrimarySeq = p.length > 0 ? p[p.length - 1].seq : undefined
47
+ for (let i = 0; i < c.length; i++) {
48
+ const rec = c[i]
49
+ const twin = pBySeq.get(rec.seq)
50
+ if (twin === undefined) {
51
+ result.kind = 'divergent'
52
+ if (result.firstDivergenceSeq === undefined) result.firstDivergenceSeq = rec.seq
53
+ if (maxPrimarySeq === undefined || rec.seq > maxPrimarySeq) result.copyOnly.push(rec)
54
+ else result.differing.push({ seq: rec.seq, primary: undefined, copy: rec })
55
+ continue
56
+ }
57
+ if (JSON.stringify(twin.raw) !== JSON.stringify(rec.raw)) {
58
+ result.kind = 'divergent'
59
+ if (result.firstDivergenceSeq === undefined) result.firstDivergenceSeq = rec.seq
60
+ result.differing.push({ seq: rec.seq, primary: twin, copy: rec })
61
+ }
62
+ }
63
+ if (result.kind === 'identical' && c.length < p.length) result.kind = 'prefix'
64
+ return result
65
+ }
66
+
67
+ /**
68
+ * 走查并分类一个副本文件。
69
+ * @param {string} copyPath 副本绝对路径
70
+ * @param {string} primaryPath 同版本主文件路径(可不存在)
71
+ * @param {{readFileSync?: Function}} [deps] 测试注入
72
+ */
73
+ export function auditCopyFile(copyPath, primaryPath, deps = {}) {
74
+ const read = deps.readFileSync ?? readFileSync
75
+ let copyWalk
76
+ try {
77
+ copyWalk = walkLog(read(copyPath))
78
+ } catch (error) {
79
+ return { path: copyPath, kind: 'unreadable', error: String(error?.message || error) }
80
+ }
81
+ let primaryWalk
82
+ let primaryMissing = false
83
+ try {
84
+ primaryWalk = walkLog(read(primaryPath))
85
+ } catch {
86
+ primaryMissing = true
87
+ }
88
+ if (primaryMissing) {
89
+ return { path: copyPath, kind: 'orphan', copy: summarize(copyWalk) }
90
+ }
91
+ const verdict = classifyCopy(primaryWalk, copyWalk)
92
+ return { path: copyPath, ...verdict, copy: summarize(copyWalk), primary: summarize(primaryWalk) }
93
+ }
94
+
95
+ function summarize(walk) {
96
+ const events = walk.records.filter((r) => typeof r.seq === 'number')
97
+ // 真机事件用 time(header 用 createdAt);两者都收,取真实跨度。
98
+ const stamps = walk.records
99
+ .map((r) => (typeof r.time === 'number' ? r.time : typeof r.createdAt === 'number' ? r.createdAt : undefined))
100
+ .filter((n) => typeof n === 'number')
101
+ const lastTurn = [...walk.records].reverse().find((r) => r.type === 'turn/end')
102
+ return {
103
+ eventCount: events.length,
104
+ seqFirst: events.length ? events[0].seq : undefined,
105
+ seqLast: events.length ? events[events.length - 1].seq : undefined,
106
+ createdAtFirst: stamps.length ? Math.min(...stamps) : walk.header?.createdAt,
107
+ createdAtLast: stamps.length ? Math.max(...stamps) : undefined,
108
+ lastTurn: lastTurn ? { turn: lastTurn.turn, reason: lastTurn.raw?.reason } : undefined,
109
+ openTurn: detectOpenTurn(walk.records),
110
+ health: walk.health,
111
+ header: walk.header,
112
+ }
113
+ }
114
+
115
+ /** 末尾未闭合 turn(turn/start 后无对应 turn/end)。 */
116
+ export function detectOpenTurn(records) {
117
+ let open
118
+ for (const r of records) {
119
+ if (r.type === 'turn/start') open = r.turn
120
+ else if (r.type === 'turn/end' && r.turn === open) open = undefined
121
+ }
122
+ return open
123
+ }
@@ -0,0 +1,139 @@
1
+ /**
2
+ * dsh-xlock — 配置加载。
3
+ *
4
+ * 真身:包内 config.json(随 dsh-plugins 同步面跨机共享);
5
+ * cordis.patch.yml 的 insert config 可作本机覆盖(apply 第二参)。
6
+ * CLI 只读 config.json(+ --flag 覆盖)。
7
+ */
8
+
9
+ import { homedir } from 'node:os'
10
+ import { join } from 'node:path'
11
+ import { PKG_ROOT, atomicWriteText, existsSync, readJsonSafe } from './util.mjs'
12
+
13
+ export const DEFAULTS = Object.freeze({
14
+ /** 非"分叉导出"类隔离条目的保留天数(-1 = 永久)。 */
15
+ retentionDays: 30,
16
+ /** 分叉导出证据的保留天数(更长,作为人裁决的凭据)。 */
17
+ exportRetentionDays: 180,
18
+ /** 隔离区总字节上限(超出最旧优先删)。 */
19
+ maxQuarantineBytes: 536870912, // 512 MiB
20
+ /** 写打开通过门禁后的静默复检等待(毫秒)。0 = 关闭。 */
21
+ acquireQuiesceMs: 0,
22
+ /** 分叉副本遇写打开:'block'(拦截,默认)| 'warn'(放行+报告)。 */
23
+ divergentGate: 'block',
24
+ /** 宿主启动时顺带跑一次隔离区 gc。 */
25
+ startupGc: true,
26
+ /** 是否开启「归档状态跨机同步」(写侧落标记 + 读侧收敛归档集)。默认开。 */
27
+ archiveSyncRoute: true,
28
+ /** 判定「对端此刻还在写」的日志活跃窗口(毫秒)。超过它且 turn 未闭合 → 视为残锁。 */
29
+ sessionActiveMs: 180000,
30
+ })
31
+
32
+ /**
33
+ * 合并配置(默认值 ← config.json ← 覆盖)。
34
+ * @param {object} [overrides]
35
+ * @returns {object}
36
+ */
37
+ export function loadConfig(overrides = {}) {
38
+ const file = readJsonSafe(join(PKG_ROOT, 'config.json'), {})
39
+ const merged = { ...DEFAULTS, ...(file || {}), ...(overrides || {}) }
40
+ for (const key of ['retentionDays', 'exportRetentionDays', 'acquireQuiesceMs']) {
41
+ const n = Number(merged[key])
42
+ merged[key] = Number.isFinite(n) ? Math.max(-1, Math.floor(n)) : DEFAULTS[key]
43
+ }
44
+ const bytes = Number(merged.maxQuarantineBytes)
45
+ merged.maxQuarantineBytes = Number.isFinite(bytes) ? Math.max(0, Math.floor(bytes)) : DEFAULTS.maxQuarantineBytes
46
+ merged.divergentGate = merged.divergentGate === 'warn' ? 'warn' : 'block'
47
+ merged.startupGc = merged.startupGc !== false
48
+ merged.archiveSyncRoute = merged.archiveSyncRoute !== false
49
+ const activeMs = Number(merged.sessionActiveMs)
50
+ merged.sessionActiveMs = Number.isFinite(activeMs) && activeMs >= 0 ? Math.floor(activeMs) : DEFAULTS.sessionActiveMs
51
+ return merged
52
+ }
53
+
54
+ /**
55
+ * machines.json 的权威路径。
56
+ *
57
+ * 宿主半跑的是 profile 里的**安装副本**(node_modules\dsh-xlock),而 node_modules
58
+ * 不在同步面上:往那里写 machines.json 只有本机看得到,跨机学习就失效了。
59
+ * 所以优先用同步面上的源码包(~/.dsh/dsh-plugins/dsh-xlock)——
60
+ * 两台机器的这个位置都指向同一份 Syncthing 共享目录。找不到才退回包内。
61
+ *
62
+ * @returns {string}
63
+ */
64
+ export function registryPath() {
65
+ // 显式覆盖优先(测试与排查用),避免任何情况下误写真实 registry。
66
+ const override = process.env.DSH_XLOCK_REGISTRY
67
+ if (typeof override === 'string' && override !== '') return override
68
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
69
+ const synced = join(home, 'dsh-plugins', 'dsh-xlock', 'machines.json')
70
+ if (existsSync(synced)) return synced
71
+ return join(PKG_ROOT, 'machines.json')
72
+ }
73
+
74
+ /**
75
+ * 读 machines.json。
76
+ *
77
+ * 两个区并存(老文件只有 devices,照样能用):
78
+ * - `machines`: machineId → { host, syncthing, cwds[] }。cwds 是各机 apply 时
79
+ * 自动登记的本地工作区路径,用于「桶名 → 机器」的历史归属推断;
80
+ * - `devices`: Syncthing 设备短 ID → 机器名(冲突副本文件名里的最后一段)。
81
+ *
82
+ * @returns {{machines:Record<string,{host?:string,syncthing?:string,cwds:string[]}>, devices:Record<string,string>}}
83
+ */
84
+ export function loadMachines() {
85
+ const data = readJsonSafe(registryPath(), {})
86
+ if (!data || typeof data !== 'object') return { machines: {}, devices: {} }
87
+ const machines = {}
88
+ for (const [machineId, entry] of Object.entries(data.machines || {})) {
89
+ if (!entry || typeof entry !== 'object') continue
90
+ machines[machineId] = {
91
+ host: typeof entry.host === 'string' ? entry.host : undefined,
92
+ syncthing: typeof entry.syncthing === 'string' ? entry.syncthing : undefined,
93
+ cwds: Array.isArray(entry.cwds) ? entry.cwds.filter((c) => typeof c === 'string' && c !== '') : [],
94
+ }
95
+ }
96
+ return { machines, devices: data.devices || {} }
97
+ }
98
+
99
+ /**
100
+ * 把本机的 host / cwds 登记进 registry(apply 时自动学习)。
101
+ * 只增不改:已有条目只补空缺,不覆盖别的机器写下的内容;文件内容不变则不写盘
102
+ * (否则每次启动都会触发一次跨机同步)。
103
+ *
104
+ * @param {{uuid:string,host:string}} identity
105
+ * @param {string[]} cwds 本机近期工作区路径
106
+ * @param {(line:string)=>void} [log]
107
+ * @param {string} [registryFile] 覆盖 registry 路径(测试用;默认同步面上的 machines.json)
108
+ * @returns {boolean} 是否真的写了盘
109
+ */
110
+ export function learnRegistry(identity, cwds, log = () => {}, registryFile = registryPath()) {
111
+ const path = registryFile
112
+ const data = readJsonSafe(path, {})
113
+ const base = data && typeof data === 'object' ? data : {}
114
+ const machines = base.machines && typeof base.machines === 'object' ? { ...base.machines } : {}
115
+ const current = machines[identity.uuid] && typeof machines[identity.uuid] === 'object' ? machines[identity.uuid] : {}
116
+ const known = Array.isArray(current.cwds) ? current.cwds.slice() : []
117
+ const merged = known.slice()
118
+ for (const cwd of cwds) {
119
+ if (typeof cwd === 'string' && cwd !== '' && !merged.includes(cwd)) merged.push(cwd)
120
+ }
121
+ const next = {
122
+ host: identity.host,
123
+ ...(typeof current.syncthing === 'string' ? { syncthing: current.syncthing } : {}),
124
+ cwds: merged,
125
+ }
126
+ const before = JSON.stringify(current)
127
+ const after = JSON.stringify(next)
128
+ if (before === after) return false
129
+ machines[identity.uuid] = next
130
+ const out = { ...base, machines }
131
+ try {
132
+ atomicWriteText(path, `${JSON.stringify(out, null, 2)}\n`)
133
+ log(`registry learned: machine=${identity.host} cwds=${merged.join(',') || '(none)'}`)
134
+ return true
135
+ } catch (error) {
136
+ log(`registry learn failed (ignored): ${error?.message || error}`)
137
+ return false
138
+ }
139
+ }