dsh-xlock 0.0.0-stage → 0.2.8
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/README.md +123 -3
- package/cli/xlock.mjs +359 -0
- package/client.js +307 -0
- package/config.json +10 -0
- package/cordis.patch.yml +10 -0
- package/core/archive.mjs +195 -0
- package/core/archivesync.mjs +170 -0
- package/core/audit.mjs +226 -0
- package/core/classify.mjs +123 -0
- package/core/config.mjs +139 -0
- package/core/frames.mjs +216 -0
- package/core/identity.mjs +44 -0
- package/core/intercept.mjs +364 -0
- package/core/live.mjs +173 -0
- package/core/marker.mjs +234 -0
- package/core/origin.mjs +267 -0
- package/core/quarantine.mjs +240 -0
- package/core/repair.mjs +105 -0
- package/core/sessionfs.mjs +128 -0
- package/core/uistate.mjs +141 -0
- package/core/util.mjs +168 -0
- package/core/xlocktool.mjs +112 -0
- package/dsh-xlock.ps1 +50 -0
- package/index.js +255 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +48 -3
package/core/frames.mjs
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — zstd 帧走查与会话日志解析。
|
|
3
|
+
*
|
|
4
|
+
* 会话日志 = 多个 zstd frame 背靠背拼接(每 frame ≈ 一次提交批的 JSONL)。
|
|
5
|
+
* Node 24 内置 zlib.zstdDecompressSync 只解第一个 frame——恰好用它做
|
|
6
|
+
* 「从候选起点解码到候选终点」的边界试探:
|
|
7
|
+
* - 终点=真帧尾 → 成功;
|
|
8
|
+
* - 终点在帧内(magic 误报)→ 解码失败(unexpected end);
|
|
9
|
+
* - 起点后的第一个 magic 即真帧尾(健康文件帧背靠背无缝)。
|
|
10
|
+
*
|
|
11
|
+
* 记录形态(dsh-session,以真机日志为准):
|
|
12
|
+
* 首行 header {type:'session', version, id, createdAt, isSeeded, delegationDepth, …}
|
|
13
|
+
* 其后 events {seq(连续), type:'turn/start'|…, time(epoch ms), data:{turn, step, …}}
|
|
14
|
+
* —— 时间字段是 time(不是 createdAt);turn/step 在 data 里,不在顶层。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { zstdDecompressSync } from 'node:zlib'
|
|
18
|
+
|
|
19
|
+
const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd])
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* 把 buffer 切成 zstd frame 边界并解码。
|
|
23
|
+
* @param {Buffer} buf 文件全量字节
|
|
24
|
+
* @returns {{
|
|
25
|
+
* frames: Array<{start:number,end:number,text?:string}>,
|
|
26
|
+
* tornTailStart?: number // 末尾不可解码残帧的起点(torn final frame)
|
|
27
|
+
* }}
|
|
28
|
+
*/
|
|
29
|
+
export function splitFrames(buf) {
|
|
30
|
+
const candidates = []
|
|
31
|
+
for (let i = buf.indexOf(ZSTD_MAGIC); i !== -1; i = buf.indexOf(ZSTD_MAGIC, i + 1)) {
|
|
32
|
+
candidates.push(i)
|
|
33
|
+
}
|
|
34
|
+
const frames = []
|
|
35
|
+
let tornTailStart
|
|
36
|
+
let idx = 0
|
|
37
|
+
while (idx < candidates.length) {
|
|
38
|
+
const start = candidates[idx]
|
|
39
|
+
if (start >= buf.length) break
|
|
40
|
+
let end
|
|
41
|
+
// 依次尝试后续候选终点(含 buf.length),第一个解码成功的即帧尾。
|
|
42
|
+
for (let j = idx + 1; ; j++) {
|
|
43
|
+
const stop = j < candidates.length ? candidates[j] : buf.length
|
|
44
|
+
if (stop <= start) {
|
|
45
|
+
if (j >= candidates.length) {
|
|
46
|
+
end = undefined
|
|
47
|
+
break
|
|
48
|
+
}
|
|
49
|
+
continue
|
|
50
|
+
}
|
|
51
|
+
try {
|
|
52
|
+
const text = zstdDecompressSync(buf.subarray(start, stop)).toString('utf8')
|
|
53
|
+
end = { stop, text }
|
|
54
|
+
break
|
|
55
|
+
} catch {
|
|
56
|
+
if (j >= candidates.length) {
|
|
57
|
+
end = undefined
|
|
58
|
+
break
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
if (end) {
|
|
63
|
+
frames.push({ start, end: end.stop, text: end.text })
|
|
64
|
+
// 跳过被吞进本帧的所有候选(含 magic 误报)。
|
|
65
|
+
let next = idx + 1
|
|
66
|
+
while (next < candidates.length && candidates[next] < end.stop) next++
|
|
67
|
+
idx = next
|
|
68
|
+
} else {
|
|
69
|
+
tornTailStart = start
|
|
70
|
+
break
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return { frames, tornTailStart }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* 解析一条记录行的关键信息。
|
|
78
|
+
* @param {string} line JSONL 行
|
|
79
|
+
* @returns {{seq?:number,type?:string,turn?:number,step?:number,createdAt?:number,time?:number}}
|
|
80
|
+
*/
|
|
81
|
+
export function recordMeta(line) {
|
|
82
|
+
let obj
|
|
83
|
+
try {
|
|
84
|
+
obj = JSON.parse(line)
|
|
85
|
+
} catch {
|
|
86
|
+
return { torn: true }
|
|
87
|
+
}
|
|
88
|
+
if (!obj || typeof obj !== 'object') return { torn: true }
|
|
89
|
+
// 真机日志:turn/step 在 data 里;时间字段是 time(header 用 createdAt)。
|
|
90
|
+
const data = obj.data !== null && typeof obj.data === 'object' ? obj.data : undefined
|
|
91
|
+
const turn = typeof obj.turn === 'number' ? obj.turn : typeof data?.turn === 'number' ? data.turn : undefined
|
|
92
|
+
const step = typeof obj.step === 'number' ? obj.step : typeof data?.step === 'number' ? data.step : undefined
|
|
93
|
+
return {
|
|
94
|
+
seq: typeof obj.seq === 'number' ? obj.seq : undefined,
|
|
95
|
+
type: typeof obj.type === 'string' ? obj.type : undefined,
|
|
96
|
+
turn,
|
|
97
|
+
step,
|
|
98
|
+
createdAt: typeof obj.createdAt === 'number' ? obj.createdAt : undefined,
|
|
99
|
+
time: typeof obj.time === 'number' ? obj.time : undefined,
|
|
100
|
+
raw: obj,
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 走查整个日志 buffer → 记录 + 健康状况。
|
|
106
|
+
* @param {Buffer} buf
|
|
107
|
+
* @returns {{
|
|
108
|
+
* header?: object,
|
|
109
|
+
* records: Array<{seq?:number,type?:string,turn?:number,step?:number,createdAt?:number,time?:number,lineNo:number,raw:object}>,
|
|
110
|
+
* health: {
|
|
111
|
+
* tornTailFrame: boolean, // 末帧不可解(DSH 写打开会自愈截断)
|
|
112
|
+
* tornJsonlLastLine: boolean, // 完整帧内末行 JSON 截断(DSH 拒载 → 需修复)
|
|
113
|
+
* tornFrameIndex?: number, // 出现 JSON 截断的帧序号(0 基)
|
|
114
|
+
* corruptMiddle: boolean, // 中间帧不可解(无法按帧修复)
|
|
115
|
+
* seqGaps: Array<[number, number]>, // [前 seq, 后 seq] 非连续处
|
|
116
|
+
* frameCount: number,
|
|
117
|
+
* }
|
|
118
|
+
* }}
|
|
119
|
+
*/
|
|
120
|
+
export function walkLog(buf) {
|
|
121
|
+
const { frames, tornTailStart } = splitFrames(buf)
|
|
122
|
+
const records = []
|
|
123
|
+
let header
|
|
124
|
+
let tornJsonlLastLine = false
|
|
125
|
+
let tornFrameIndex
|
|
126
|
+
const seqGaps = []
|
|
127
|
+
let lastSeq
|
|
128
|
+
|
|
129
|
+
frames.forEach((frame, frameIndex) => {
|
|
130
|
+
const lines = frame.text.split('\n')
|
|
131
|
+
// 帧内最后一行:正常以 \n 结尾 → split 产生末尾空串;非空 = JSON 截断候选。
|
|
132
|
+
const lastLine = lines[lines.length - 1]
|
|
133
|
+
const bodyLines = lastLine === '' ? lines.slice(0, -1) : lines
|
|
134
|
+
const trailingGarbage = lastLine !== '' && lastLine.trim() !== ''
|
|
135
|
+
for (const line of bodyLines) {
|
|
136
|
+
if (line.trim() === '') continue
|
|
137
|
+
const meta = recordMeta(line)
|
|
138
|
+
if (meta.torn) {
|
|
139
|
+
// 完整帧内出现不可解析行(非末行)——按截断记录处理,仅末行可修。
|
|
140
|
+
if (!tornJsonlLastLine) {
|
|
141
|
+
tornJsonlLastLine = true
|
|
142
|
+
tornFrameIndex = frameIndex
|
|
143
|
+
}
|
|
144
|
+
continue
|
|
145
|
+
}
|
|
146
|
+
if (!header && meta.type === 'session' && meta.raw && meta.seq === undefined) {
|
|
147
|
+
header = meta.raw
|
|
148
|
+
records.push({ ...meta, lineNo: records.length + 1 })
|
|
149
|
+
continue
|
|
150
|
+
}
|
|
151
|
+
if (typeof meta.seq === 'number') {
|
|
152
|
+
if (lastSeq !== undefined && meta.seq !== lastSeq + 1) seqGaps.push([lastSeq, meta.seq])
|
|
153
|
+
lastSeq = meta.seq
|
|
154
|
+
}
|
|
155
|
+
records.push({ ...meta, lineNo: records.length + 1 })
|
|
156
|
+
}
|
|
157
|
+
// 末行有残字(无换行收尾且解不出 JSON)→ 标记可修复截断。
|
|
158
|
+
if (trailingGarbage && recordMeta(lastLine).torn) {
|
|
159
|
+
tornJsonlLastLine = true
|
|
160
|
+
tornFrameIndex = frameIndex
|
|
161
|
+
}
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
// 中间帧损坏(非末尾处解不开):splitFrames 在第一个解不开的候选起点即停,
|
|
165
|
+
// v1 一律保守记为 torn tail(DSH 读打开也只会丢弃其后内容);
|
|
166
|
+
// 是否中间损坏由 audit 报告 frameCount 与 seqGaps 供人判断。
|
|
167
|
+
return {
|
|
168
|
+
header,
|
|
169
|
+
records,
|
|
170
|
+
health: {
|
|
171
|
+
tornTailFrame: tornTailStart !== undefined,
|
|
172
|
+
tornJsonlLastLine,
|
|
173
|
+
tornFrameIndex,
|
|
174
|
+
corruptMiddle: false,
|
|
175
|
+
seqGaps,
|
|
176
|
+
frameCount: frames.length,
|
|
177
|
+
},
|
|
178
|
+
frames,
|
|
179
|
+
tornTailStart,
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 会话日志文件名解析(canonical):
|
|
185
|
+
* v0: session.jsonl.zstd;vN≥1: session.vN.jsonl.zstd
|
|
186
|
+
* 冲突副本: <canonical-without-zstd>.sync-conflict-<date>-<time>-<shortId>.zstd
|
|
187
|
+
* @param {string} name
|
|
188
|
+
* @returns {{kind:'canonical',version:number}|{kind:'conflict',version:number,shortId:string,date:string,time:string}|{kind:'other'}}
|
|
189
|
+
*/
|
|
190
|
+
export function parseLogFilename(name) {
|
|
191
|
+
if (!name.endsWith('.zstd')) return { kind: 'other' }
|
|
192
|
+
const stem = name.slice(0, -'.zstd'.length)
|
|
193
|
+
let version = 0
|
|
194
|
+
if (/^session\.v(0|[1-9]\d*)\.jsonl$/.test(stem)) {
|
|
195
|
+
version = Number(/^session\.v(0|[1-9]\d*)\.jsonl$/.exec(stem)[1])
|
|
196
|
+
} else if (/^session\.jsonl$/.test(stem)) {
|
|
197
|
+
version = 0
|
|
198
|
+
} else {
|
|
199
|
+
const conflict = /\.sync-conflict-(\d{8})-(\d{6})-([A-Za-z0-9]+)$/.exec(stem)
|
|
200
|
+
if (!conflict) return { kind: 'other' }
|
|
201
|
+
const inner = stem.slice(0, conflict.index)
|
|
202
|
+
if (/^session\.v(0|[1-9]\d*)\.jsonl$/.test(inner)) {
|
|
203
|
+
version = Number(/^session\.v(0|[1-9]\d*)\.jsonl$/.exec(inner)[1])
|
|
204
|
+
} else if (inner !== 'session.jsonl') {
|
|
205
|
+
return { kind: 'other' }
|
|
206
|
+
}
|
|
207
|
+
return {
|
|
208
|
+
kind: 'conflict',
|
|
209
|
+
version,
|
|
210
|
+
shortId: conflict[3],
|
|
211
|
+
date: conflict[1],
|
|
212
|
+
time: conflict[2],
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
return { kind: 'canonical', version }
|
|
216
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — 机器身份:machineId 的生成与加载。
|
|
3
|
+
*
|
|
4
|
+
* 存放于 %LOCALAPPDATA%\dsh-xlock\machineId.json:
|
|
5
|
+
* - LOCALAPPDATA 不在 Syncthing 同步面,天然机器绑定,免注册表依赖;
|
|
6
|
+
* - 防克隆守卫:host 不匹配(整盘克隆到新机器)→ 判陈旧并重新生成 uuid。
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { randomUUID } from 'node:crypto'
|
|
10
|
+
import { hostname } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
import { ensureDir, readJsonSafe, atomicWriteText } from './util.mjs'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* %LOCALAPPDATA%\dsh-xlock 根目录(隔离区与身份文件的家)。
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export function xlockDataRoot() {
|
|
19
|
+
return join(process.env.LOCALAPPDATA || join(process.env.USERPROFILE || '.', 'AppData', 'Local'), 'dsh-xlock')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* 加载(或首次生成)本机身份。
|
|
24
|
+
* @returns {{uuid:string, host:string, createdAt:string}}
|
|
25
|
+
*/
|
|
26
|
+
export function loadIdentity() {
|
|
27
|
+
const dir = xlockDataRoot()
|
|
28
|
+
const path = join(dir, 'machineId.json')
|
|
29
|
+
const host = hostname()
|
|
30
|
+
const existing = readJsonSafe(path, undefined)
|
|
31
|
+
if (
|
|
32
|
+
existing &&
|
|
33
|
+
typeof existing.uuid === 'string' &&
|
|
34
|
+
existing.uuid.length >= 8 &&
|
|
35
|
+
existing.host === host
|
|
36
|
+
) {
|
|
37
|
+
return existing
|
|
38
|
+
}
|
|
39
|
+
// 不存在 / 损坏 / 克隆(host 不匹配)→ 重新生成。
|
|
40
|
+
const identity = { v: 1, uuid: randomUUID(), host, createdAt: new Date().toISOString() }
|
|
41
|
+
ensureDir(dir)
|
|
42
|
+
atomicWriteText(path, `${JSON.stringify(identity, null, 2)}\n`)
|
|
43
|
+
return identity
|
|
44
|
+
}
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-xlock — sessionPersistence 实例级拦截(锁层心脏)。
|
|
3
|
+
*
|
|
4
|
+
* 唯一宿主级拦截点 = JS 实例级方法赋值(cordis ctx.provide 不可重提供;
|
|
5
|
+
* createTraceable 的 set 陷阱把赋值透传到原始实例,get 时自有属性优先)。
|
|
6
|
+
* 拦截 open(id,'write') 与 create(header):
|
|
7
|
+
*
|
|
8
|
+
* open('write'):
|
|
9
|
+
* 1) 标记门禁:异机 held / corrupt / 标记冲突副本 → XlockHeldError
|
|
10
|
+
* (name='SessionAlreadyOwnedError' → 控制器映射 writer-held 直达 UI)
|
|
11
|
+
* 2) 冲突副本门禁:前缀/identical → 自动隔离;divergent → block|warn
|
|
12
|
+
* 3) 尾部修复门禁:完整帧内 JSONL 末行截断 → 先修复再放行
|
|
13
|
+
* 4) 原始 open → 包装 handle(close → released)
|
|
14
|
+
*
|
|
15
|
+
* create(header): 原始 create → 包装 handle。初始写入走 jsonl 后端 tracker
|
|
16
|
+
* 的 live routing(原始 handle),包装 append 的懒 ensure 可能永不触发 →
|
|
17
|
+
* create 后起有界后台轮询(25ms×80≈2s)等物化 → 标记门禁(异机/corrupt →
|
|
18
|
+
* close 句柄阻止写入)→ acquireMarker。之后包装 append 的 ensure 幂等兜底。
|
|
19
|
+
*
|
|
20
|
+
* 防御边界:门禁内部【非 Xlock*】的意外异常一律放行并记日志(插件的 bug
|
|
21
|
+
* 不许弄哑用户的会话);Xlock* 是有意 fail-safe。
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import { dirname } from 'node:path'
|
|
25
|
+
import {
|
|
26
|
+
XlockHeldError,
|
|
27
|
+
acquireMarker,
|
|
28
|
+
markerStatus,
|
|
29
|
+
releaseMarker,
|
|
30
|
+
} from './marker.mjs'
|
|
31
|
+
import { loadMachines } from './config.mjs'
|
|
32
|
+
import { inventorySessionDir, machineName } from './sessionfs.mjs'
|
|
33
|
+
import { writeOriginOnce } from './origin.mjs'
|
|
34
|
+
import { auditCopyFile } from './classify.mjs'
|
|
35
|
+
import { quarantineFile, quarantineCopyOf, ledgerAppend } from './quarantine.mjs'
|
|
36
|
+
import { tailRepairIfNeeded } from './repair.mjs'
|
|
37
|
+
import { isoUtc } from './util.mjs'
|
|
38
|
+
|
|
39
|
+
const WRAP_TAG = Symbol('dsh-xlock.wrapped')
|
|
40
|
+
|
|
41
|
+
/** 门禁专用错误:分叉副本拦截(controller 走 gateway/internal,消息直达 UI)。 */
|
|
42
|
+
export class XlockDivergentError extends Error {
|
|
43
|
+
constructor(sessionId, message) {
|
|
44
|
+
super(message)
|
|
45
|
+
this.name = 'XlockDivergentError'
|
|
46
|
+
this.sessionId = sessionId
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function sleep(ms) {
|
|
51
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* 包装 sessionPersistence 服务实例。
|
|
56
|
+
* @param {object} inst SessionPersistence 实例(可能是 cordis 代理)
|
|
57
|
+
* @param {{uuid:string,host:string}} identity
|
|
58
|
+
* @param {object} cfg loadConfig() 结果
|
|
59
|
+
* @param {(line:string, extra?:object) => void} log 日志函数
|
|
60
|
+
* @returns {() => void} 还原函数(effect 清理用)
|
|
61
|
+
*/
|
|
62
|
+
export function wrapPersistence(inst, identity, cfg, log) {
|
|
63
|
+
// 幂等守卫:WRAP_TAG(defineProperty 可能被代理拒绝)+ 函数名双保险,
|
|
64
|
+
// 防止对已包装实例二次包装导致 origOpen=wrappedOpen 递归。
|
|
65
|
+
const alreadyWrapped = Boolean(inst) && (
|
|
66
|
+
inst[WRAP_TAG]
|
|
67
|
+
|| inst.open?.name === 'wrappedOpen'
|
|
68
|
+
|| inst.create?.name === 'wrappedCreate'
|
|
69
|
+
)
|
|
70
|
+
if (!inst || typeof inst.open !== 'function' || alreadyWrapped) {
|
|
71
|
+
return () => {}
|
|
72
|
+
}
|
|
73
|
+
const origOpen = inst.open.bind(inst)
|
|
74
|
+
const origCreate = inst.create.bind(inst)
|
|
75
|
+
const origStat = inst.stat.bind(inst)
|
|
76
|
+
|
|
77
|
+
// 同目录串行化(进程内并发 open 的标记操作互斥)。
|
|
78
|
+
const queues = new Map()
|
|
79
|
+
function serialized(key, fn) {
|
|
80
|
+
const prev = queues.get(key) ?? Promise.resolve()
|
|
81
|
+
const next = prev.then(fn, fn)
|
|
82
|
+
queues.set(key, next.catch(() => {}))
|
|
83
|
+
return next
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function throwHeld(sessionId, message) {
|
|
87
|
+
throw new XlockHeldError(sessionId, message)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* 冲突副本门禁。返回处理动作列表(供日志)。
|
|
92
|
+
*/
|
|
93
|
+
function conflictCopyGate(sessionDir, sessionId) {
|
|
94
|
+
const inv = inventorySessionDir(sessionDir)
|
|
95
|
+
if (inv.logConflicts.length === 0 && inv.markerConflicts.length === 0) return []
|
|
96
|
+
const machines = loadMachines()
|
|
97
|
+
const actions = []
|
|
98
|
+
// 标记冲突副本:异机持锁痕迹 → 拦(AC10)。
|
|
99
|
+
if (inv.markerConflicts.length > 0) {
|
|
100
|
+
throwHeld(
|
|
101
|
+
sessionId,
|
|
102
|
+
`session "${sessionId}" lock marker has sync-conflict copies — two machines contested it. ` +
|
|
103
|
+
`Use the xlock tool: reset then audit this session`,
|
|
104
|
+
)
|
|
105
|
+
}
|
|
106
|
+
// 日志冲突副本:同版本 canonical 为参照。
|
|
107
|
+
const canonicalByVer = new Map(inv.canonical.map((c) => [c.version, c]))
|
|
108
|
+
for (const copy of inv.logConflicts) {
|
|
109
|
+
const primary = canonicalByVer.get(copy.version)
|
|
110
|
+
let verdict
|
|
111
|
+
try {
|
|
112
|
+
verdict = auditCopyFile(copy.path, primary ? primary.path : copy.path.replace(copy.name, `session.v${copy.version}.jsonl.zstd`))
|
|
113
|
+
} catch (error) {
|
|
114
|
+
verdict = { kind: 'unreadable', error: String(error?.message || error) }
|
|
115
|
+
}
|
|
116
|
+
const mn = machineName(copy.shortId, machines)
|
|
117
|
+
const from = `from ${mn.known ? mn.name : `device ${copy.shortId}(未补录)`}`
|
|
118
|
+
if (verdict.kind === 'identical' || verdict.kind === 'prefix') {
|
|
119
|
+
const dir = quarantineFile(copy.path, {
|
|
120
|
+
sessionId,
|
|
121
|
+
kind: 'conflict-copy',
|
|
122
|
+
classifiedAs: verdict.kind,
|
|
123
|
+
machines: { copy: mn.name, shortId: copy.shortId },
|
|
124
|
+
action: 'auto-quarantine',
|
|
125
|
+
note: `write-open gate: ${verdict.kind} copy (${from})`,
|
|
126
|
+
})
|
|
127
|
+
actions.push(`auto-quarantined ${verdict.kind} copy ${copy.name} → ${dir}`)
|
|
128
|
+
continue
|
|
129
|
+
}
|
|
130
|
+
if (verdict.kind === 'divergent') {
|
|
131
|
+
if (cfg.divergentGate === 'warn') {
|
|
132
|
+
log(`divergent copy on write-open (warn mode): ${copy.name} ${from} firstDivergenceSeq=${verdict.firstDivergenceSeq}`)
|
|
133
|
+
actions.push(`warn: divergent copy ${copy.name} left in place`)
|
|
134
|
+
continue
|
|
135
|
+
}
|
|
136
|
+
ledgerAppend({ action: 'gate-block', kind: 'divergent', sessionId, file: copy.name, firstDivergenceSeq: verdict.firstDivergenceSeq })
|
|
137
|
+
throw new XlockDivergentError(
|
|
138
|
+
sessionId,
|
|
139
|
+
`session "${sessionId}" has an unresolved DIVERGENT sync-conflict copy (${copy.name}, ${from}, ` +
|
|
140
|
+
`first divergence seq=${verdict.firstDivergenceSeq}). ` +
|
|
141
|
+
`Use the xlock tool audit to compare both sides, then the xlock tool resolve ` +
|
|
142
|
+
`${sessionId} --keep primary|copy`,
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
if (verdict.kind === 'orphan') {
|
|
146
|
+
// 同版本主文件缺失(副本比现存文件还新?)→ 保守拦截,交人判断。
|
|
147
|
+
throw new XlockDivergentError(
|
|
148
|
+
sessionId,
|
|
149
|
+
`session "${sessionId}" has a sync-conflict copy (${copy.name}, ${from}) whose version has no ` +
|
|
150
|
+
`canonical file — resolve manually: use the xlock tool audit ${sessionId}`,
|
|
151
|
+
)
|
|
152
|
+
}
|
|
153
|
+
// unreadable:fail-safe 拦截。
|
|
154
|
+
throwHeld(
|
|
155
|
+
sessionId,
|
|
156
|
+
`session "${sessionId}" has an unreadable sync-conflict copy (${copy.name}) — ` +
|
|
157
|
+
`fail-safe block; use the xlock tool audit ${sessionId}`,
|
|
158
|
+
)
|
|
159
|
+
}
|
|
160
|
+
return actions
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
async function wrappedOpen(id, access, options) {
|
|
164
|
+
if (access !== 'write') return origOpen(id, access, options)
|
|
165
|
+
log(`write-open gate: id=${id}`)
|
|
166
|
+
let snap
|
|
167
|
+
try {
|
|
168
|
+
snap = await origStat(id)
|
|
169
|
+
} catch (error) {
|
|
170
|
+
log(`write-open stat failed (treat as unmaterialized): id=${id} err=${error?.message || error}`)
|
|
171
|
+
snap = undefined
|
|
172
|
+
}
|
|
173
|
+
const location = snap && snap.location
|
|
174
|
+
if (!location || !location.path) {
|
|
175
|
+
// 未物化(尚无文件)→ 无锁面,直接走原始 open(NotFound 原样抛)。
|
|
176
|
+
log(`write-open passthrough (unmaterialized): id=${id}`)
|
|
177
|
+
return origOpen(id, 'write', options)
|
|
178
|
+
}
|
|
179
|
+
const sessionDir = dirname(location.path)
|
|
180
|
+
await serialized(sessionDir, async () => {
|
|
181
|
+
// 0) 标记门禁(最先:异机持有时不动目录里任何文件,AC1 文件 hash 不变)。
|
|
182
|
+
const marker = markerStatus(sessionDir, identity)
|
|
183
|
+
if (marker.corrupt) {
|
|
184
|
+
throwHeld(id, `session "${id}" lock marker is corrupt (fail-safe) — use the xlock tool (action "reset") to clear it`)
|
|
185
|
+
}
|
|
186
|
+
if (marker.foreign) {
|
|
187
|
+
const holder = marker.holder?.host || marker.conflicts?.join(', ') || 'another machine'
|
|
188
|
+
throwHeld(
|
|
189
|
+
id,
|
|
190
|
+
`session "${id}" is locked on host "${holder}" (sticky lock marker; the owning machine crashed ` +
|
|
191
|
+
`or still runs). To take over: confirm the owning machine has stopped writing, then run the ` +
|
|
192
|
+
`xlock tool (action "reset", session "${id}") — or delete the marker file directly`,
|
|
193
|
+
)
|
|
194
|
+
}
|
|
195
|
+
try {
|
|
196
|
+
// 1) 冲突副本门禁(可能自动隔离/抛 XlockDivergentError)。
|
|
197
|
+
const actions = conflictCopyGate(sessionDir, id)
|
|
198
|
+
for (const line of actions) log(line)
|
|
199
|
+
// 2) 尾部修复门禁(可能重写文件)。
|
|
200
|
+
const repair = tailRepairIfNeeded(location.path, {
|
|
201
|
+
sessionId: id,
|
|
202
|
+
quarantineCopy: (src, meta) =>
|
|
203
|
+
// 复制语义留证:修复要原位重写原路径,不能先搬走原文件。
|
|
204
|
+
quarantineCopyOf(src, { sessionId: id, kind: meta.kind, action: 'pre-repair-backup', note: 'torn JSONL last line in complete frame', extra: { droppedBytes: meta.droppedBytes } }),
|
|
205
|
+
log,
|
|
206
|
+
})
|
|
207
|
+
if (repair.repaired) {
|
|
208
|
+
log(`tail repair applied for session "${id}": droppedBytes=${repair.droppedBytes}${repair.quarantineDir ? ` pre-repair copy at ${repair.quarantineDir}` : ''}`)
|
|
209
|
+
}
|
|
210
|
+
// 3) 取得本机持锁(missing→wx / released→翻转 / held+本机→保持)。
|
|
211
|
+
acquireMarker(sessionDir, identity, id)
|
|
212
|
+
log(`marker held: id=${id} host=${identity.host}`)
|
|
213
|
+
// 4) 可选静默复检:等同步窗口过去后确认标记仍归我们。
|
|
214
|
+
if (cfg.acquireQuiesceMs > 0) {
|
|
215
|
+
await sleep(cfg.acquireQuiesceMs)
|
|
216
|
+
const re = markerStatus(sessionDir, identity)
|
|
217
|
+
if (re.foreign || re.corrupt) {
|
|
218
|
+
throwHeld(
|
|
219
|
+
id,
|
|
220
|
+
`session "${id}" lock marker changed during acquire quiesce (${re.corrupt ? 'corrupt' : re.holder?.host || 'foreign'}) — blocking`,
|
|
221
|
+
)
|
|
222
|
+
}
|
|
223
|
+
acquireMarker(sessionDir, identity, id)
|
|
224
|
+
}
|
|
225
|
+
} catch (error) {
|
|
226
|
+
// 有意拦截 → 原样抛;插件自身 bug → 放行(不许弄哑用户会话)。
|
|
227
|
+
if (error instanceof XlockHeldError || error instanceof XlockDivergentError) throw error
|
|
228
|
+
log(`dsh-xlock gate unexpected error (fail-open): ${error?.stack || error}`)
|
|
229
|
+
return
|
|
230
|
+
}
|
|
231
|
+
})
|
|
232
|
+
const handle = await origOpen(id, 'write', options)
|
|
233
|
+
return wrapWriteHandle(handle, { dir: sessionDir, id, ensured: true, origStat })
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
async function wrappedCreate(header, options) {
|
|
237
|
+
log(`create gate: pid=${process.pid} id=${header.id}`)
|
|
238
|
+
const handle = await origCreate(header, options)
|
|
239
|
+
const state = { dir: undefined, id: header.id, ensured: false, origStat, cwd: header?.cwd, fromCreate: true }
|
|
240
|
+
wrapWriteHandle(handle, state)
|
|
241
|
+
scheduleCreateEnsure(handle, state)
|
|
242
|
+
return handle
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* create 后的有界后台 ensure:等目录物化 → 补挂粘性标记。
|
|
247
|
+
* 子代理/GUI 新会话的初始写入走 live routing(原始 handle),包装 append
|
|
248
|
+
* 可能永不触发,标记必须在这里补挂。异机/corrupt → close 句柄阻止写入。
|
|
249
|
+
*/
|
|
250
|
+
function scheduleCreateEnsure(handle, state) {
|
|
251
|
+
void (async () => {
|
|
252
|
+
for (let attempt = 0; attempt < 80; attempt++) {
|
|
253
|
+
await sleep(25)
|
|
254
|
+
try {
|
|
255
|
+
const snap = await state.origStat(state.id)
|
|
256
|
+
const dir = snap?.location?.path ? dirname(snap.location.path) : undefined
|
|
257
|
+
if (!dir) continue
|
|
258
|
+
let blocked = false
|
|
259
|
+
await serialized(dir, async () => {
|
|
260
|
+
if (state.ensured) return
|
|
261
|
+
const marker = markerStatus(dir, identity)
|
|
262
|
+
if (marker.corrupt || marker.foreign) {
|
|
263
|
+
blocked = true
|
|
264
|
+
log(`create blocked (${marker.corrupt ? 'corrupt' : `foreign ${marker.holder?.host || 'machine'}`}): id=${state.id} — closing handle`)
|
|
265
|
+
return
|
|
266
|
+
}
|
|
267
|
+
acquireMarker(dir, identity, state.id)
|
|
268
|
+
state.dir = dir
|
|
269
|
+
state.ensured = true
|
|
270
|
+
log(`marker ensured on create: id=${state.id} host=${identity.host}`)
|
|
271
|
+
// 创建归属记录:wx 独占、只写一次。写失败不影响会话(纯元数据)。
|
|
272
|
+
if (writeOriginOnce(dir, identity, state.id, state.cwd)) {
|
|
273
|
+
log(`origin recorded: id=${state.id} host=${identity.host} cwd=${state.cwd || '(none)'}`)
|
|
274
|
+
}
|
|
275
|
+
})
|
|
276
|
+
if (blocked) {
|
|
277
|
+
try { await handle.close() } catch { /* wrapped close 吞错 */ }
|
|
278
|
+
return
|
|
279
|
+
}
|
|
280
|
+
if (state.ensured) return
|
|
281
|
+
} catch (error) {
|
|
282
|
+
// 门禁内部意外错误 → 放弃 ensure(fail-open),后续包装 append 仍可补挂。
|
|
283
|
+
log(`create ensure unexpected error (give up): id=${state.id} err=${error?.stack || error}`)
|
|
284
|
+
return
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
log(`create ensure gave up (never materialized within 2s): id=${state.id}`)
|
|
288
|
+
})()
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function wrapWriteHandle(handle, state) {
|
|
292
|
+
const origAppend = handle.append.bind(handle)
|
|
293
|
+
const origClose = handle.close.bind(handle)
|
|
294
|
+
handle.append = async (events, options) => {
|
|
295
|
+
if (!state.ensured && Array.isArray(events) && events.length > 0) {
|
|
296
|
+
state.ensured = true
|
|
297
|
+
try {
|
|
298
|
+
let dir = state.dir
|
|
299
|
+
if (!dir) {
|
|
300
|
+
const snap = await state.origStat(state.id)
|
|
301
|
+
dir = snap?.location?.path ? dirname(snap.location.path) : undefined
|
|
302
|
+
log(`ensure stat: pid=${process.pid} id=${state.id} dir=${dir || 'none'}`)
|
|
303
|
+
if (!dir) {
|
|
304
|
+
// 仍未物化(append 失败?)→ 下一次 append 再补。
|
|
305
|
+
state.ensured = false
|
|
306
|
+
return origAppend(events, options)
|
|
307
|
+
}
|
|
308
|
+
state.dir = dir
|
|
309
|
+
}
|
|
310
|
+
const marker = markerStatus(dir, identity)
|
|
311
|
+
if (marker.corrupt || marker.foreign) {
|
|
312
|
+
throwHeld(
|
|
313
|
+
state.id,
|
|
314
|
+
`session "${state.id}" is locked on host "${marker.holder?.host || 'another machine'}" ` +
|
|
315
|
+
`(marker appeared before first append). To take over: run the xlock tool ` +
|
|
316
|
+
`(action "reset", session "${state.id}") or delete the marker file`,
|
|
317
|
+
)
|
|
318
|
+
}
|
|
319
|
+
acquireMarker(dir, identity, state.id)
|
|
320
|
+
log(`marker ensured on first append: id=${state.id} host=${identity.host}`)
|
|
321
|
+
if (state.fromCreate) {
|
|
322
|
+
// 兜底路径:create 的 ensure 没在 2s 内物化时,首次 append 补写归属。
|
|
323
|
+
if (writeOriginOnce(dir, identity, state.id, state.cwd)) {
|
|
324
|
+
log(`origin recorded on first append: id=${state.id} host=${identity.host} cwd=${state.cwd || '(none)'}`)
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
} catch (error) {
|
|
328
|
+
try {
|
|
329
|
+
await origClose()
|
|
330
|
+
} catch {
|
|
331
|
+
/* close 失败不掩盖原始错误 */
|
|
332
|
+
}
|
|
333
|
+
throw error
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
return origAppend(events, options)
|
|
337
|
+
}
|
|
338
|
+
handle.close = async () => {
|
|
339
|
+
try {
|
|
340
|
+
return await origClose()
|
|
341
|
+
} finally {
|
|
342
|
+
if (state.dir) releaseMarker(state.dir, identity) // 吞错:close 语义优先
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return handle
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
inst.open = wrappedOpen
|
|
349
|
+
inst.create = wrappedCreate
|
|
350
|
+
try {
|
|
351
|
+
Object.defineProperty(inst, WRAP_TAG, { value: { at: isoUtc() }, enumerable: false, configurable: true })
|
|
352
|
+
} catch {
|
|
353
|
+
/* 代理拒绝定义符号 → 无法标记,靠还原函数兜底 */
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
return function restore() {
|
|
357
|
+
try {
|
|
358
|
+
inst.open = origOpen
|
|
359
|
+
inst.create = origCreate
|
|
360
|
+
} catch {
|
|
361
|
+
/* 实例已被替换 */
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|