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 CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # dsh-xlock — 跨机会话粘锁与修复插件
2
+
3
+ DeepSeek Harness(DSH)插件,在**多机 Syncthing 同步** `~/.dsh/sessions` 的场景下提供三层能力:
4
+
5
+ 1. **锁层**:会话运行期间在会话目录落粘性标记 `.dsh-xlock.json`,异机写打开(resume/prompt)被拦截并显示持有主机。
6
+ 2. **修复层**:写打开前的工程化门禁——zstd 帧走查、torn JSONL 末行自动修复(原字节留证)、Syncthing 冲突副本识别/隔离/分叉证据导出,全程不依赖大模型。
7
+ 3. **会话跨机状态层**:创建归属(`.dsh-xlock-origin.json`)、归档(`.dsh-xlock-archive.json`)与归档集双向对账,浏览器侧栏圆环 / 圆点 / 会话菜单解锁 / 会话集合刷新。
8
+
9
+ ## 为什么需要
10
+
11
+ - DSH 的写租约在 Windows 上是**本机命名信号量**(`Local\dsh-session-lock-<hash>`),对异机无效。
12
+ - resume 未闭合的会话会立即写合成 closer(step/end + turn/end)——两机先后打开即双写分叉。
13
+ - Syncthing 冲突副本(`session.v4.jsonl.sync-conflict-<日期>-<时间>-<设备短ID>.zstd`)对 DSH 是隐形文件,不会被加载也不会被清理。
14
+
15
+ ## 工作原理
16
+
17
+ 宿主半 `index.js` 启动时对 `sessionPersistence` 服务做**实例级**方法包装(`open`/`create`/`stat`),不重 provide、不改原型。写打开(`access='write'`)按序执行:
18
+
19
+ 1. **标记门禁**:`.dsh-xlock.json` 为 held 且 machineId 非本机 → 抛 `SessionAlreadyOwnedError`(映射为 `session/writer-held`,UI 显示持有主机名);标记损坏或为冲突副本 → fail-safe 拦截。
20
+ 2. **冲突副本门禁**:目录内日志冲突副本逐个分类——identical/prefix → 自动隔离;divergent → 按配置拦截(block)或告警放行(warn);unreadable → fail-safe 拦截。
21
+ 3. **修复门禁**:主日志「完整帧内 JSONL 末行截断」→ 先复制留证再原位截断重压缩修复。
22
+ 4. **取锁**:无标记/本机 held/released → 原子创建/翻转为 held。
23
+ 5. `handle.close()` → 标记翻转为 released(不删除)。崩溃 → held 残留 → 异机被粘拦(fail-safe),原机重启 resume 自愈,跨机逃生门 = `reset`。
24
+
25
+ `machineId` 存 `%LOCALAPPDATA%\dsh-xlock\machineId.json`(同步面之外,机器绑定;host 不匹配自动重生成防克隆)。
26
+
27
+ ## 创建归属
28
+
29
+ 锁标记记的是**最后持有者**,归属另走三源,逐级降级:
30
+
31
+ | 级别 | 证据 | 说明 |
32
+ | --- | --- | --- |
33
+ | L1 | `<session-dir>/.dsh-xlock-origin.json` | 宿主半在 `sessionPersistence.create()` 后写一次(`openSync(path, 'wx')` 独占,EEXIST 即放弃);只写一次、失败吞掉,纯元数据不挡会话 |
34
+ | L2 | 会话目录的**桶名** | DSH 用创建时 cwd 编桶名,`machines.json` 的 `cwds` 反查可覆盖没有记录的历史会话 |
35
+ | L3 | 都没有 | 报 `未知`,不猜 |
36
+
37
+ 会话被 `move` 到别的工作区时桶名不再代表创建地,以 L1 为准,L2 标注为推断。
38
+
39
+ `machines.json` 两个区并存:`machines`(每机 `host` / `syncthing` / `cwds`)与 `devices`(短 ID → 机器名)。`cwds` 由各机 apply 自动学习、**只增不改**,内容没变不写盘;写回同步面上的**源码包** `~/.dsh/dsh-plugins/dsh-xlock/machines.json`(`DSH_XLOCK_REGISTRY` 可覆盖)。输出:`xlock status` 给异机创建的会话加 `created-remote(<host>)`;`xlock audit` 多一行创建归属与依据。
40
+
41
+ ## 归档标记(`.dsh-xlock-archive.json`)
42
+
43
+ 平台把归档存在 `~/.dsh/storages/workspace.json`(不在同步面),而会话目录本身同步,故归档状态落成贴身标记随会话目录同步。
44
+
45
+ - **双读单写**:新名 `.dsh-xlock-archive.json` 优先读,旧名 `.dsh-tweaks-archive.json` 仍可读;写只写新名,不碰旧名存量。新名损坏按 `none` 处理,不回退旧名。
46
+ - **同步器**(`core/archivesync.mjs`,`archiveSyncRoute` 默认开):写侧监听 `workspace` 的 `domain/changed` 落标记;读侧轮询标记文件,用 `workspaceRegistry.archiveSession` / `unarchiveSession` 收敛。只处理相对上轮真变化的 id、盘上已是目标值不重写。
47
+ - 归档与锁无因果关系;归档标记的冲突副本单列 `archiveConflicts×N`,不计入粘锁争抢,也不产生 `other×N` 噪音。
48
+
49
+ ## 浏览器 UI
50
+
51
+ client 半(`client.js`)读宿主半只读路由,全部自绘,无第三方图标依赖:
52
+
53
+ - **对端活跃度圆环**(slot `sidebar.session.row.leading`,id `xlock-remote`):只对异机持锁(`held-foreign`)画——**实线脉动**(`#f0883e`,2px,1.6s 呼吸)= 对端真在写(日志在 `sessionActiveMs` 窗口内,或 `turn/start` 未闭合);**虚线灰淡**(`#8b949e`,2px,`opacity .6`)= 只剩残锁。`prefers-reduced-motion` 下关掉呼吸动画,形状仍可辨。
54
+ - **创建归属圆点**(同槽,id `xlock-origin`):8px 圆点 `#58a6ff`;有创建记录为实线、只靠桶名反推为点线;异机持锁时让路。
55
+ - **会话菜单「解除跨机锁(主机名)」**(`ctx.contextMenus.register({target:'session'})`,id `xlock.unlock`,`danger:true`):仅对 `held-foreign` 产出,点击走 `POST /dsh-xlock/session-state/reset`,只删锁标记、不改归档并立刻复查。
56
+ - **会话集合变化检测**(`GET /dsh-xlock/session-ids`,15 秒):磁盘全量 id 集合变了就让平台重拉基线。
57
+
58
+ 归档态不自绘标记(平台已给归档行淡化,悬浮卡也有归档图标)。
59
+
60
+ UI 与 CLI 的 reset 同语义、都是**显式使用者动作**:插件不自行判断对端是否已停写,必须由人确认后再点解锁。
61
+
62
+ ## CLI
63
+
64
+ ```powershell
65
+ dsh-xlock.ps1 audit <session|all> # 审计(只读,不改任何文件)
66
+ dsh-xlock.ps1 resolve <session> --keep primary # 裁决冲突:以主文件为准(副本隔离 + 分叉证据导出)
67
+ dsh-xlock.ps1 resolve <session> --keep copy # 裁决冲突:以副本为准(副本换正,先修 torn 末行)
68
+ dsh-xlock.ps1 reset <session> # 跨机逃生门:删粘锁标记与标记冲突副本
69
+ dsh-xlock.ps1 status # 全局状态总览
70
+ dsh-xlock.ps1 gc # 隔离区过期清理(也可配启动自动)
71
+ ```
72
+
73
+ DSH 原生工具 `xlock` 同名(action: `status` / `audit` / `reset` / `resolve` / `gc`,`session` 支持 id 片段模糊匹配),GUI / mobile 可达。
74
+
75
+ ## 隔离区
76
+
77
+ `%LOCALAPPDATA%\dsh-xlock\quarantine\<UTC戳>-<会话>-<kind>\`(文件 + meta.json),同步面之外。台账 `ledger.jsonl` 记录 quarantine/copy/export/delete 全动作,删除先留痕。gc:普通 30 天、分叉导出证据 180 天(`-1` 永久)、总量 512MB 超限最旧优先。
78
+
79
+ ## 配置(包内 config.json,随同步面共享)
80
+
81
+ | 键 | 默认 | 说明 |
82
+ | --- | --- | --- |
83
+ | `retentionDays` | 30 | 隔离保留天数(`-1` 永久) |
84
+ | `exportRetentionDays` | 180 | 分叉导出证据保留天数 |
85
+ | `maxQuarantineBytes` | 536870912 | 隔离区总量上限(超限最旧优先删) |
86
+ | `acquireQuiesceMs` | 0 | 取锁后静默复检毫秒数(缓解同步延迟窗口,0=关) |
87
+ | `divergentGate` | `'block'` | 分叉副本遇写打开:`'block'` 拦截 / `'warn'` 告警放行 |
88
+ | `startupGc` | true | 宿主启动时顺带 gc |
89
+ | `sessionActiveMs` | 180000 | 对端活跃窗口:日志 mtime 在此范围内判「正在写」(毫秒) |
90
+ | `archiveSyncRoute` | true | 归档状态跨机同步,见上「归档标记」 |
91
+
92
+ ## 插件页名称与描述
93
+
94
+ 走官方 locale 机制:`locale/en.json` 是锚点(缺了整个 locale 目录不读),`locale/zh.json` 给中文,两者只写 `meta.title` / `meta.description`,缺哪个语言落回英文。`package.json` 的 `files` 与 `exports` 都要带上 `locale`。
95
+
96
+ ## 安装
97
+
98
+ profile 依赖 `github:jalousiex/dsh-xlock`,pnpm 从 GitHub tarball 装成真实目录,不依赖同步盘是否就位;`~/.dsh/dsh-plugins/dsh-xlock/` 为开发工作副本。随包 `cordis.patch.yml` 的 insert 自动并入。两台机器都启用。改包内容后需重启 DSH。
99
+
100
+ **GitHub 源打包约束**:`package.json` 的 `files` 决定 tarball 内容,`config.json` / `machines.json` / `dsh-xlock.ps1` 必须列出,否则安装副本缺失、宿主静默退回内置默认值(`config.json` 的值恰与默认值相同,所以看不出异常)。
101
+
102
+ 另一台机器一键安装(同步盘把源码目录带到对机后):
103
+
104
+ ```powershell
105
+ powershell -ExecutionPolicy Bypass -File "$env:USERPROFILE\.dsh\dsh-plugins\dsh-xlock\install-into-profile.ps1" -ProfileName desktop
106
+ ```
107
+
108
+ 脚本幂等:登记 profile `package.json` → 用 DSH 自带 runtime + vendored pnpm 执行 install → 提示重启。激活验证看 `%LOCALAPPDATA%\dsh-xlock\host.log`。
109
+
110
+ ## 边界与残余风险
111
+
112
+ - 纯同步原理性边界:A 机开会话与 B 机写打开落在**分钟级同步延迟窗口**内时,两端本地取锁都可能成功 → 双写分叉;无跨机 CAS,此窗口只能缩小(`acquireQuiesceMs`)不能消除,事后由修复层 + audit + resolve 兜底。
113
+ - 只读查看(GUI 纯浏览)与 DSH 之外的直接文件工具不经过 `sessionPersistence.open('write')`,不受拦(只读不产生写终结符)。
114
+ - 设备短 ID 语义按 Syncthing 官方冲突副本命名假设,运行时以 `createdAt` 范围与文件名时间戳交叉印证,矛盾标「归属存疑」。
115
+
116
+ ## 测试
117
+
118
+ `test/run.mjs` 零依赖自包含(夹具隔离 env,不碰真实会话):
119
+
120
+ ```powershell
121
+ $env:ELECTRON_RUN_AS_NODE = '1'
122
+ & "$env:LOCALAPPDATA\Programs\DeepSeek Harness\DeepSeek Harness.exe" test\run.mjs
123
+ ```
package/cli/xlock.mjs ADDED
@@ -0,0 +1,359 @@
1
+ /**
2
+ * dsh-xlock — CLI 核心(供 dsh-xlock.ps1 以 DSH 内置 node 执行)。
3
+ *
4
+ * 用法(经 ps1 包装):
5
+ * dsh-xlock.ps1 audit [session] 走查会话目录,输出双边画像报告(不改文件)
6
+ * dsh-xlock.ps1 resolve <session> --keep primary|copy 裁决分叉(异机 held 时拒绝)
7
+ * dsh-xlock.ps1 reset <session> 删除本会话粘锁标记(跨机接管的唯一逃生门)
8
+ * dsh-xlock.ps1 status 概览:标记 held / 冲突副本 / 隔离区
9
+ * dsh-xlock.ps1 gc 立即清理过期隔离区(ledger 留痕)
10
+ *
11
+ * 设计边界:CLI 与宿主拦截共用 core/*;CLI 只做"人"的裁决入口,
12
+ * 不做自动合并——换正后由 DSH 自己的 generation 机制重建日志。
13
+ */
14
+
15
+ import process from 'node:process'
16
+ import {
17
+ readFileSync,
18
+ existsSync,
19
+ unlinkSync,
20
+ openSync,
21
+ writeSync,
22
+ ftruncateSync,
23
+ closeSync,
24
+ fsyncSync,
25
+ } from 'node:fs'
26
+ import { basename, join, resolve } from 'node:path'
27
+ import { fileURLToPath } from 'node:url'
28
+ import { zstdCompressSync } from 'node:zlib'
29
+ import { loadIdentity } from '../core/identity.mjs'
30
+ import { loadConfig, loadMachines } from '../core/config.mjs'
31
+ import { listSessionDirs, findSessionDirs, inventorySessionDir, machineName } from '../core/sessionfs.mjs'
32
+ import { auditSessionDir, renderReport } from '../core/audit.mjs'
33
+ import { inferOrigin } from '../core/origin.mjs'
34
+ import { auditCopyFile } from '../core/classify.mjs'
35
+ import { markerStatus, listMarkerConflicts, readMarker } from '../core/marker.mjs'
36
+ import { quarantineFile, writeDivergentExport, listQuarantine, gcQuarantine } from '../core/quarantine.mjs'
37
+ import { walkLog } from '../core/frames.mjs'
38
+ import { moveFile } from '../core/util.mjs'
39
+
40
+ function fail(message) {
41
+ process.stderr.write(`dsh-xlock: ${message}\n`)
42
+ process.exitCode = 1
43
+ }
44
+
45
+ function usage() {
46
+ process.stdout.write(
47
+ [
48
+ 'dsh-xlock — 跨机会话粘锁 / 同步冲突副本审计与修复',
49
+ '',
50
+ '命令:',
51
+ ' audit [session] 走查会话(缺省=全部),输出报告;不改会话文件',
52
+ ' resolve <session> --keep primary|copy 裁决分叉副本:primary=以主文件为准 / copy=以副本换正',
53
+ ' reset <session> 删除本会话粘锁标记(异机接管唯一逃生门;确认原机已停写后使用)',
54
+ ' status 概览:所有会话的标记/副本/需要处理项 + 隔离区统计',
55
+ ' gc 立即清理过期/超限隔离区',
56
+ '',
57
+ '会话名可用 session id 片段模糊匹配(唯一命中即执行)。',
58
+ ].join('\n') + '\n',
59
+ )
60
+ }
61
+
62
+ function resolveSessionDir(sessionArg) {
63
+ const roots = listSessionDirs()
64
+ const exact = roots.find((r) => r.name === sessionArg)
65
+ if (exact) return { dir: exact.dir, name: sessionArg }
66
+ const hits = findSessionDirs(sessionArg)
67
+ if (hits.length === 1) return { dir: hits[0].dir, name: hits[0].name }
68
+ if (hits.length === 0) throw new Error(`no session dir matches "${sessionArg}" (searched ${roots.length} buckets)`)
69
+ throw new Error(`ambiguous session "${sessionArg}", ${hits.length} matches:\n ${hits.map((h) => h.name).join('\n ')}`)
70
+ }
71
+
72
+ /** resolve 的安全闸:异机持锁/标记损坏时拒绝裁决。 */
73
+ function assertNotForeignHeld(dir, identity) {
74
+ const marker = markerStatus(dir, identity)
75
+ if (marker.corrupt) {
76
+ throw new Error('lock marker is corrupt — inspect with audit first; reset clears it if you accept the risk')
77
+ }
78
+ if (marker.foreign) {
79
+ throw new Error(
80
+ `session is lock-held on host "${marker.holder?.host || '?'}" — refusing. ` +
81
+ 'Stop that machine\u2019s DSH first, then re-run this command.',
82
+ )
83
+ }
84
+ }
85
+
86
+ export function cmdAudit(args) {
87
+ const identity = loadIdentity()
88
+ const machines = loadMachines()
89
+ const targets =
90
+ args.length === 0
91
+ ? listSessionDirs().map((r) => ({ dir: r.dir, name: r.name }))
92
+ : [resolveSessionDir(args[0])]
93
+ if (targets.length === 0) {
94
+ process.stdout.write('no session directories found\n')
95
+ return
96
+ }
97
+ for (const { dir, name } of targets) {
98
+ const report = auditSessionDir(dir, { identity, machines, sessionName: name })
99
+ process.stdout.write(renderReport(report) + '\n\n')
100
+ }
101
+ }
102
+
103
+ /**
104
+ * in-place 修复"完整帧内 JSONL 末行截断"(副本换正前必做——
105
+ * DSH 对这种情况拒载)。返回修复字节数(0=无需修复)。
106
+ */
107
+ function repairLastLineInPlace(path) {
108
+ const buf = readFileSync(path)
109
+ const walk = walkLog(buf)
110
+ if (!walk.health.tornJsonlLastLine || walk.health.tornFrameIndex === undefined || walk.health.tornFrameIndex === null) {
111
+ return 0
112
+ }
113
+ const frame = walk.frames[walk.health.tornFrameIndex]
114
+ if (!frame) return 0
115
+ const frameText = buf.slice(frame.start, frame.end).toString('latin1') // 帧内 JSONL 为 ASCII 安全;按字节切
116
+ const lines = frameText.split('\n')
117
+ // 末行 JSON 解析失败 → 截掉;其余保持。
118
+ while (lines.length > 0) {
119
+ const last = lines[lines.length - 1]
120
+ if (last.trim() === '') {
121
+ lines.pop()
122
+ continue
123
+ }
124
+ try {
125
+ JSON.parse(last)
126
+ break
127
+ } catch {
128
+ lines.pop()
129
+ }
130
+ }
131
+ const keptText = lines.length > 0 ? lines.join('\n') + '\n' : ''
132
+ const rebuilt = Buffer.concat([buf.slice(0, frame.start), zstdCompressSync(Buffer.from(keptText, 'latin1'))])
133
+ // 自检:重走查不得再报 tornJsonlLastLine。
134
+ const rewalk = walkLog(rebuilt)
135
+ if (rewalk.health.tornJsonlLastLine) throw new Error(`self-check failed after repairing ${basename(path)}`)
136
+ const fd = openSync(path, 'r+')
137
+ try {
138
+ writeSync(fd, rebuilt, 0, rebuilt.length, 0)
139
+ ftruncateSync(fd, rebuilt.length)
140
+ fsyncSync(fd)
141
+ } finally {
142
+ closeSync(fd)
143
+ }
144
+ return buf.length - rebuilt.length
145
+ }
146
+
147
+ export function cmdResolve(args) {
148
+ const keepIdx = args.indexOf('--keep')
149
+ let keep
150
+ if (keepIdx !== -1 && args[keepIdx + 1]) keep = args[keepIdx + 1]
151
+ const sessionArg = args.filter((a, i) => a !== '--keep' && i !== keepIdx + 1)[0]
152
+ if (!sessionArg || !keep || !['primary', 'copy'].includes(keep)) {
153
+ fail('usage: resolve <session> --keep primary|copy')
154
+ return
155
+ }
156
+ const identity = loadIdentity()
157
+ const { dir, name } = resolveSessionDir(sessionArg)
158
+ assertNotForeignHeld(dir, identity)
159
+
160
+ const inv = inventorySessionDir(dir)
161
+ if (inv.logConflicts.length === 0) {
162
+ process.stdout.write(`session "${name}": no log conflict copies — nothing to resolve\n`)
163
+ return
164
+ }
165
+ const machines = loadMachines()
166
+ let acted = 0
167
+ for (const copy of inv.logConflicts) {
168
+ const primary = inv.canonical.find((c) => c.version === copy.version)
169
+ const mn = machineName(copy.shortId, machines)
170
+ const metaBase = {
171
+ sessionId: name,
172
+ machines: { copy: mn.name, shortId: copy.shortId },
173
+ classifiedAs: undefined,
174
+ action: `resolve --keep ${keep}`,
175
+ }
176
+ if (!primary) {
177
+ fail(`copy ${copy.name} has no canonical counterpart (orphan) — decide manually, not auto-resolved`)
178
+ continue
179
+ }
180
+ const verdict = auditCopyFile(copy.path, primary.path)
181
+ metaBase.classifiedAs = verdict.kind
182
+ if (verdict.kind === 'identical' || verdict.kind === 'prefix') {
183
+ const qdir = quarantineFile(copy.path, { ...metaBase, kind: 'conflict-copy', note: `resolve: ${verdict.kind} copy discarded` })
184
+ process.stdout.write(`quarantined ${copy.name} (${verdict.kind}) → ${qdir}\n`)
185
+ acted++
186
+ continue
187
+ }
188
+ if (verdict.kind === 'unreadable') {
189
+ fail(`copy ${copy.name} is unreadable (${verdict.error || 'no frames'}) — not auto-resolved; inspect manually`)
190
+ continue
191
+ }
192
+ // divergent(含 firstDivergenceSeq):按裁决方向落盘。
193
+ if (keep === 'primary') {
194
+ const qdir = quarantineFile(copy.path, {
195
+ ...metaBase,
196
+ kind: 'conflict-copy',
197
+ note: 'resolve --keep primary: copy side discarded',
198
+ })
199
+ // 导出放隔离目录内(copyOnly + differing 双边记录)。
200
+ const exportPath = writeDivergentExport(qdir, copy.name, verdict, {
201
+ sessionId: name,
202
+ copyMachine: mn.name,
203
+ firstDivergenceSeq: verdict.firstDivergenceSeq,
204
+ })
205
+ process.stdout.write(`copy-side records exported → ${exportPath}\n`)
206
+ process.stdout.write(`quarantined copy ${copy.name} → ${qdir}\nprimary stays authoritative: ${primary.name}\n`)
207
+ acted++
208
+ } else {
209
+ // keep=copy:副本换正为主文件,原主文件隔离(原字节完整留证)。
210
+ const repairedBytes = repairLastLineInPlace(copy.path)
211
+ if (repairedBytes > 0) process.stdout.write(`promoted copy tail-repaired in place (dropped ${repairedBytes} torn bytes)\n`)
212
+ const qdir = quarantineFile(primary.path, {
213
+ ...metaBase,
214
+ kind: 'primary-demoted',
215
+ note: 'resolve --keep copy: original primary discarded (records annotated in divergent export)',
216
+ })
217
+ const exportPath = writeDivergentExport(qdir, primary.name, verdict, {
218
+ sessionId: name,
219
+ copyMachine: mn.name,
220
+ firstDivergenceSeq: verdict.firstDivergenceSeq,
221
+ })
222
+ const canonicalName = `session.v${copy.version}.jsonl.zstd`
223
+ let dest = join(dir, canonicalName)
224
+ let retries = 0
225
+ while (existsSync(dest) && retries < 4) {
226
+ retries++
227
+ dest = join(dir, `session.v${copy.version}.x${retries}.jsonl.zstd`)
228
+ }
229
+ moveFile(copy.path, dest)
230
+ process.stdout.write(`copy promoted: ${copy.name} → ${basename(dest)}\noriginal primary quarantined → ${qdir}\n`)
231
+ if (verdict.copyOnly?.length || verdict.differing?.length) {
232
+ process.stdout.write(`primary-side records exported → ${exportPath}\n`)
233
+ }
234
+ acted++
235
+ }
236
+ }
237
+ process.stdout.write(`resolve done: ${acted} copy(ies) handled. Re-run audit to confirm.\n`)
238
+ }
239
+
240
+ export function cmdReset(args) {
241
+ const sessionArg = args[0]
242
+ if (!sessionArg) {
243
+ fail('usage: reset <session>')
244
+ return
245
+ }
246
+ const identity = loadIdentity()
247
+ const { dir, name } = resolveSessionDir(sessionArg)
248
+ const marker = readMarker(dir)
249
+ const markerConflicts = listMarkerConflicts(dir)
250
+ if (marker.state === 'missing' && markerConflicts.length === 0) {
251
+ process.stdout.write(`session "${name}": no lock marker — nothing to reset\n`)
252
+ return
253
+ }
254
+ const removed = []
255
+ const markerPath = join(dir, '.dsh-xlock.json')
256
+ if (existsSync(markerPath)) {
257
+ unlinkSync(markerPath)
258
+ removed.push('.dsh-xlock.json')
259
+ }
260
+ for (const c of markerConflicts) {
261
+ unlinkSync(join(dir, c))
262
+ removed.push(c)
263
+ }
264
+ process.stdout.write(
265
+ removed.length > 0
266
+ ? `reset "${name}": removed ${removed.join(', ')} — next write-open on any machine takes the lock\n`
267
+ : `reset "${name}": nothing removed\n`,
268
+ )
269
+ }
270
+
271
+ export function cmdStatus() {
272
+ const identity = loadIdentity()
273
+ const machines = loadMachines()
274
+ const roots = listSessionDirs()
275
+ const lines = []
276
+ let attention = 0
277
+ const unknownDevices = new Set()
278
+ for (const root of roots) {
279
+ const dir = root.dir
280
+ const name = root.name
281
+ const inv = inventorySessionDir(dir)
282
+ const marker = markerStatus(dir, identity)
283
+ // 创建归属(与 marker 是两件事:marker 是「现在谁持有」,这是「当初谁建的」)。
284
+ const origin = inferOrigin(dir, { identity, registry: machines, bucket: root.bucket })
285
+ const bits = []
286
+ if (marker.state === 'held') bits.push(marker.foreign ? `HELD-foreign(${marker.holder?.host || '?'})` : 'held-self')
287
+ else if (marker.corrupt) bits.push('marker-corrupt')
288
+ else if (marker.state === 'released') bits.push('released')
289
+ if (origin.source !== 'unknown' && !origin.local) bits.push(`created-remote(${origin.host})`)
290
+ if (inv.logConflicts.length > 0) bits.push(`log-copies×${inv.logConflicts.length}`)
291
+ if (inv.markerConflicts.length > 0) bits.push(`marker-copies×${inv.markerConflicts.length}`)
292
+ // 归档标记本体是常态(存在即正常),不进摘要;只有它的 Syncthing 冲突
293
+ // 副本(两台机并发改归档状态的痕迹)才是需要看一眼的异常。
294
+ // 迁移后这桶从 foreignMarkers(外来标记)改名 archiveConflicts(自己的标记)。
295
+ const archiveCopies = inv.archiveConflicts
296
+ if (archiveCopies.length > 0) bits.push(`archive-copies×${archiveCopies.length}`)
297
+ if (inv.other.length > 0) bits.push(`other×${inv.other.length}`)
298
+ for (const c of inv.logConflicts) {
299
+ const mn = machineName(c.shortId, machines)
300
+ if (!mn.known) unknownDevices.add(c.shortId)
301
+ }
302
+ if (bits.length > 0) {
303
+ lines.push(` ${name}: ${bits.join(', ')}`)
304
+ if (marker.foreign || marker.corrupt || inv.logConflicts.length > 0 || inv.markerConflicts.length > 0 || archiveCopies.length > 0) attention++
305
+ }
306
+ }
307
+ process.stdout.write(`sessions: ${roots.length} dir(s), ${attention} need attention\n`)
308
+ if (lines.length > 0) process.stdout.write(lines.join('\n') + '\n')
309
+ const qEntries = listQuarantine()
310
+ const qBytes = qEntries.reduce((sum, e) => sum + e.bytes, 0)
311
+ const qroot = join(process.env.LOCALAPPDATA || process.env.USERPROFILE || '.', 'dsh-xlock', 'quarantine')
312
+ process.stdout.write(`quarantine: ${qEntries.length} item(s), ${qBytes} bytes — ${qroot}\n`)
313
+ if (unknownDevices.size > 0) {
314
+ process.stdout.write(`unknown device shortId(s): ${[...unknownDevices].join(', ')} → add to machines.json (AC8)\n`)
315
+ }
316
+ }
317
+
318
+ export function cmdGc() {
319
+ const cfg = loadConfig()
320
+ const gc = gcQuarantine(cfg)
321
+ process.stdout.write(`gc: deleted=${gc.deleted} dir(s), bytesFreed=${gc.freedBytes}, remaining=${gc.entries - gc.deleted}\n`)
322
+ }
323
+
324
+ export function main(argv) {
325
+ const [cmd, ...args] = argv
326
+ if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
327
+ usage()
328
+ return
329
+ }
330
+ try {
331
+ switch (cmd) {
332
+ case 'audit': return cmdAudit(args)
333
+ case 'resolve': return cmdResolve(args)
334
+ case 'reset': return cmdReset(args)
335
+ case 'status': return cmdStatus()
336
+ case 'gc': return cmdGc()
337
+ default:
338
+ fail(`unknown command "${cmd}"`)
339
+ usage()
340
+ }
341
+ } catch (error) {
342
+ fail(error?.message || String(error))
343
+ if (error?.stack && process.env.DSH_XLOCK_DEBUG) process.stderr.write(error.stack + '\n')
344
+ }
345
+ }
346
+
347
+ // 直跑入口:node cli/xlock.mjs <cmd> ...(dsh-xlock.ps1 走这条路)
348
+ // 注意:包可能经 Junction 引用(~/.dsh/dsh-plugins → 同步盘真身),
349
+ // argv[1] 与 import.meta.url 字面不同 → 必须 realpath 归一后再比,Windows 再折小写。
350
+ import { realpathSync } from 'node:fs'
351
+ if (process.argv[1]) {
352
+ try {
353
+ const invoked = realpathSync(resolve(process.argv[1])).toLowerCase()
354
+ const self = realpathSync(fileURLToPath(import.meta.url)).toLowerCase()
355
+ if (invoked === self) main(process.argv.slice(2))
356
+ } catch {
357
+ // 路径解析失败:按被导入处理,不执行 main。
358
+ }
359
+ }