dsh-xlock 0.2.8 → 0.2.10

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/core/audit.mjs CHANGED
@@ -1,226 +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#${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
- }
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#${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
+ }