dsh-config-sync-plugin 0.3.66 → 0.3.68

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,322 @@
1
+ // 会话日志(session.v*.jsonl.zstd)底层读写库
2
+ //
3
+ // 背景:这份文件是 append-only 的**多帧 zstd**。首帧是 header(一行 JSON),之后是事件行,
4
+ // 每行带连续 seq。实测 11MB 的日志里 6884 帧装了 10776 个事件 —— 写入侧会把多个事件压进同一帧,
5
+ // 所以「一帧一个事件」的假设不成立,读正文必须逐行解析。
6
+ //
7
+ // 切帧办法:
8
+ // A) 二分逐帧试解 —— 1 万帧 × 24 次试解,10MB 要 11 秒,太慢,不能进同步热路径。
9
+ // B) 扫描帧魔数 28 B5 2F FD 当候选,逐候选验证「切出来能解且解完是完整行」。
10
+ // 随机数据命中魔数概率约 1/2^32,12MB 期望 0.003 次,误判由验证兜掉。
11
+ // 每帧只解一次 = O(n) 原生解压。本库用 B:12MB 全解析约 640ms。
12
+ //
13
+ // 判定原则(append-only 的硬性质):
14
+ // 同源两份日志去掉首帧(首帧 cwd 会被归一成占位符,字节不同)后,短的那份必然是长的那份的
15
+ // **字节前缀**。于是只需一次 memcmp:
16
+ // identical / 一方是另一方前缀 → 同源,保留更长的那份,零风险
17
+ // 互不为前缀 → 可能分叉(也可能只是帧边界重压过),再用 seq 集合判断:
18
+ // 一方 seq 是另一方子集 → 仍是同源,取超集
19
+ // 两边各有对方没有的 seq → 真分叉,按 seq 求并集
20
+ //
21
+ // 导出的主要函数见各段注释。
22
+
23
+ import fs from 'node:fs';
24
+ import zlib from 'node:zlib';
25
+
26
+ const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd];
27
+
28
+ export function isFrameMagic(buf, i) {
29
+ return (
30
+ i + 4 <= buf.length &&
31
+ buf[i] === ZSTD_MAGIC[0] &&
32
+ buf[i + 1] === ZSTD_MAGIC[1] &&
33
+ buf[i + 2] === ZSTD_MAGIC[2] &&
34
+ buf[i + 3] === ZSTD_MAGIC[3]
35
+ );
36
+ }
37
+
38
+ /**
39
+ * 找第一帧(header)的结束偏移。
40
+ * 注意:不能靠「zstdDecompressSync(buf) 成功」来判断「整份只有一帧」—— Node 的
41
+ * zstdDecompressSync 遇到多帧缓冲会忽略后续帧并返回第一帧内容,据此返回 buf.length
42
+ * 会把 rest 判成空。所以这里只做「下一个魔数位置能切出完整行」的精确判定,判不出来就 -1。
43
+ */
44
+ export function firstFrameEnd(buf) {
45
+ if (!isFrameMagic(buf, 0)) return -1;
46
+ for (let i = 1; i + 4 <= buf.length; i++) {
47
+ if (!isFrameMagic(buf, i)) continue;
48
+ for (const plus of [0, 4, 8]) {
49
+ const e = i + plus;
50
+ if (e > buf.length) continue;
51
+ try {
52
+ const out = zlib.zstdDecompressSync(buf.subarray(0, e));
53
+ if (out.length > 0 && out[out.length - 1] === 0x0a) return e;
54
+ } catch {
55
+ /* 假帧头或 checksum 未计入,试下一个偏移 */
56
+ }
57
+ }
58
+ }
59
+ return -1;
60
+ }
61
+
62
+ /** 扫描候选帧头并验证,返回真实帧边界 */
63
+ export function splitFrames(buf) {
64
+ if (buf.length === 0) return [];
65
+ if (!isFrameMagic(buf, 0)) throw new Error('not a zstd frame stream (bad magic at byte 0)');
66
+
67
+ const cands = [0];
68
+ for (let i = 1; i + 4 <= buf.length; i++) {
69
+ if (buf[i] === 0x28 && buf[i + 1] === 0xb5 && buf[i + 2] === 0x2f && buf[i + 3] === 0xfd) cands.push(i);
70
+ }
71
+ cands.push(buf.length);
72
+
73
+ const frames = [];
74
+ let start = 0;
75
+ for (let k = 1; k < cands.length; k++) {
76
+ const end = cands[k];
77
+ if (end <= start) continue;
78
+ const slice = buf.subarray(start, end);
79
+ let ok = false;
80
+ let decoded = null;
81
+ try {
82
+ decoded = zlib.zstdDecompressSync(slice);
83
+ ok = decoded.length > 0 && decoded[decoded.length - 1] === 0x0a;
84
+ } catch {
85
+ ok = false;
86
+ }
87
+ const isLast = k === cands.length - 1;
88
+ if (ok) {
89
+ frames.push({ start, end, data: slice, decoded });
90
+ start = end;
91
+ continue;
92
+ }
93
+ if (isLast) {
94
+ // 末帧:可能带 4 字节 checksum 未计入,也可能就是尾巴不完整
95
+ let fixed = null;
96
+ for (const plus of [4, 8]) {
97
+ const e = end + plus;
98
+ if (e > buf.length) continue;
99
+ try {
100
+ const out = zlib.zstdDecompressSync(buf.subarray(start, e));
101
+ if (out.length > 0) {
102
+ fixed = { start, end: e, data: buf.subarray(start, e), decoded: out };
103
+ break;
104
+ }
105
+ } catch {
106
+ /* 继续 */
107
+ }
108
+ }
109
+ if (fixed) {
110
+ frames.push(fixed);
111
+ start = fixed.end;
112
+ } else if (decoded !== null) {
113
+ frames.push({ start, end, data: slice, decoded });
114
+ start = end;
115
+ } else {
116
+ frames.push({ start, end, data: slice, decoded: null });
117
+ start = end;
118
+ }
119
+ }
120
+ // 非末帧且解码失败:假帧头,继续累积到下一个候选
121
+ }
122
+ if (start < buf.length) {
123
+ let decoded = null;
124
+ try {
125
+ decoded = zlib.zstdDecompressSync(buf.subarray(start));
126
+ } catch {
127
+ decoded = null;
128
+ }
129
+ frames.push({ start, end: buf.length, data: buf.subarray(start), decoded });
130
+ }
131
+ return frames;
132
+ }
133
+
134
+ function frameText(frame) {
135
+ if (frame.decoded) return frame.decoded.toString('utf8');
136
+ return zlib.zstdDecompressSync(frame.data).toString('utf8');
137
+ }
138
+
139
+ /**
140
+ * 解析整份日志。
141
+ * 返回 { header, rows:[{ seq, text, frameIndex }], frames }
142
+ * rows[].text 是该事件的原始 JSON 行文本(merge 时逐行复用,保证内容不变)
143
+ */
144
+ export function parseLog(buf) {
145
+ const frames = splitFrames(buf);
146
+ if (frames.length === 0) return { header: null, rows: [], frames };
147
+
148
+ let header = null;
149
+ let rowStart = 0;
150
+ try {
151
+ const first = frameText(frames[0]);
152
+ const line = first.split('\n').find((l) => l.trim() !== '');
153
+ if (line) {
154
+ header = JSON.parse(line);
155
+ rowStart = 1;
156
+ }
157
+ } catch {
158
+ header = null;
159
+ rowStart = 0;
160
+ }
161
+
162
+ const rows = [];
163
+ for (let i = rowStart; i < frames.length; i++) {
164
+ let text = null;
165
+ try {
166
+ text = frameText(frames[i]);
167
+ } catch {
168
+ text = null;
169
+ }
170
+ if (text === null) {
171
+ rows.push({ seq: null, text: null, frameIndex: i });
172
+ continue;
173
+ }
174
+ for (const line of text.split('\n')) {
175
+ if (!line.trim()) continue;
176
+ let seq = null;
177
+ try {
178
+ const obj = JSON.parse(line);
179
+ if (typeof obj.seq === 'number') seq = obj.seq;
180
+ } catch {
181
+ seq = null;
182
+ }
183
+ rows.push({ seq, text: line, frameIndex: i });
184
+ }
185
+ }
186
+ return { header, rows, frames, headerText: header ? JSON.stringify(header) : null };
187
+ }
188
+
189
+ export function loadLog(path) {
190
+ const buf = fs.readFileSync(path);
191
+ const log = parseLog(buf);
192
+ log.path = path;
193
+ log.bytes = buf.length;
194
+ log.buf = buf;
195
+ return log;
196
+ }
197
+
198
+ /** 去掉首帧后的字节(跨机同源字节前缀判定用)。切不出首帧时返回 null。 */
199
+ export function restAfterHeader(buf) {
200
+ const e = firstFrameEnd(buf);
201
+ if (e <= 0) return null;
202
+ if (e >= buf.length) return Buffer.alloc(0);
203
+ return buf.subarray(e);
204
+ }
205
+
206
+ export function findGaps(rows) {
207
+ const gaps = [];
208
+ const seqs = [];
209
+ for (const r of rows) if (typeof r.seq === 'number') seqs.push(r.seq);
210
+ for (let i = 1; i < seqs.length; i++) {
211
+ if (seqs[i] !== seqs[i - 1] + 1) gaps.push({ at: i, expected: seqs[i - 1] + 1, got: seqs[i] });
212
+ }
213
+ return { gaps, seqs, first: seqs.length ? seqs[0] : null, tail: seqs.length ? seqs[seqs.length - 1] : null };
214
+ }
215
+
216
+ export function seqTailOf(log) {
217
+ for (let i = log.rows.length - 1; i >= 0; i--) {
218
+ if (typeof log.rows[i].seq === 'number') return log.rows[i].seq;
219
+ }
220
+ return null;
221
+ }
222
+
223
+ /** 分块 memcmp。返回 { relation, divergeAt, aLen, bLen } */
224
+ export function compareRaw(a, b) {
225
+ const n = Math.min(a.length, b.length);
226
+ const CHUNK = 1 << 16;
227
+ let i = 0;
228
+ while (i < n) {
229
+ const step = Math.min(CHUNK, n - i);
230
+ if (a.compare(b, i, i + step, i, i + step) !== 0) {
231
+ // 二分找第一个不同字节
232
+ let lo = i;
233
+ let hi = i + step - 1;
234
+ while (lo < hi) {
235
+ const mid = (lo + hi) >> 1;
236
+ if (a.compare(b, i, mid + 1, i, mid + 1) === 0) lo = mid + 1;
237
+ else hi = mid;
238
+ }
239
+ return { relation: 'fork', divergeAt: lo, aLen: a.length, bLen: b.length };
240
+ }
241
+ i += step;
242
+ }
243
+ if (a.length === b.length) return { relation: 'identical', aLen: a.length, bLen: b.length };
244
+ if (a.length < b.length) return { relation: 'a_is_prefix_of_b', aLen: a.length, bLen: b.length };
245
+ return { relation: 'b_is_prefix_of_a', aLen: a.length, bLen: b.length };
246
+ }
247
+
248
+ /** seq 集合关系:'equal'|'a_superset'|'b_superset'|'both_exclusive' */
249
+ export function compareSeqs(rowsA, rowsB) {
250
+ const sa = new Set(rowsA.map((r) => r.seq).filter((s) => typeof s === 'number'));
251
+ const sb = new Set(rowsB.map((r) => r.seq).filter((s) => typeof s === 'number'));
252
+ const onlyA = [];
253
+ const onlyB = [];
254
+ for (const x of sa) if (!sb.has(x)) onlyA.push(x);
255
+ for (const x of sb) if (!sa.has(x)) onlyB.push(x);
256
+ let relation;
257
+ if (onlyA.length === 0 && onlyB.length === 0) relation = 'equal';
258
+ else if (onlyB.length === 0) relation = 'a_superset';
259
+ else if (onlyA.length === 0) relation = 'b_superset';
260
+ else relation = 'both_exclusive';
261
+ return { relation, onlyA, onlyB, countA: sa.size, countB: sb.size };
262
+ }
263
+
264
+ /**
265
+ * 按 seq 求并集,重建一份可读日志。
266
+ *
267
+ * 关键:**逐事件重建**,不复用整帧。因为一帧可能装多个事件,若把「含 48,49,50 的帧」和
268
+ * 「含 50 的帧」都拼进去,输出里 seq 50 就出现两次,DSH 读到就是 expected 51 got 50。
269
+ * 所以这里把每个事件的原始行文本单独压成一帧,保证 seq 严格单调 +1。
270
+ */
271
+ export function mergeLogs(logA, logB, preferredHeader) {
272
+ const bySeq = new Map();
273
+ const conflicts = [];
274
+ let anon = 0;
275
+
276
+ const add = (log, tag) => {
277
+ for (const r of log.rows) {
278
+ if (r.text === null) continue;
279
+ if (typeof r.seq !== 'number') {
280
+ // 没有 seq 的行无法排序对账,只在没有同 seq 冲突时按出现顺序追加
281
+ bySeq.set(`anon${anon++}`, { key: null, text: r.text, tag });
282
+ continue;
283
+ }
284
+ const cur = bySeq.get(r.seq);
285
+ if (!cur) {
286
+ bySeq.set(r.seq, { key: r.seq, text: r.text, tag });
287
+ } else if (cur.text !== r.text) {
288
+ conflicts.push(r.seq);
289
+ }
290
+ }
291
+ };
292
+ add(logA, 'a');
293
+ add(logB, 'b');
294
+
295
+ const keys = [...bySeq.keys()];
296
+ const numeric = keys.filter((k) => typeof k === 'number').sort((x, y) => x - y);
297
+ const anonKeys = keys.filter((k) => typeof k !== 'number');
298
+
299
+ const holes = [];
300
+ for (let i = 1; i < numeric.length; i++) {
301
+ if (numeric[i] !== numeric[i - 1] + 1) {
302
+ holes.push({ after: numeric[i - 1], next: numeric[i], missing: numeric[i] - numeric[i - 1] - 1 });
303
+ }
304
+ }
305
+
306
+ const headerText = preferredHeader || (logA.header ? JSON.stringify(logA.header) : logB.header ? JSON.stringify(logB.header) : null);
307
+ const parts = [];
308
+ if (headerText) parts.push(zlib.zstdCompressSync(Buffer.from(headerText + '\n', 'utf8')));
309
+ for (const k of numeric) parts.push(zlib.zstdCompressSync(Buffer.from(bySeq.get(k).text + '\n', 'utf8')));
310
+ for (const k of anonKeys) parts.push(zlib.zstdCompressSync(Buffer.from(bySeq.get(k).text + '\n', 'utf8')));
311
+
312
+ return {
313
+ buffer: Buffer.concat(parts),
314
+ rows: numeric.length + anonKeys.length,
315
+ seqFirst: numeric.length ? numeric[0] : null,
316
+ seqTail: numeric.length ? numeric[numeric.length - 1] : null,
317
+ holes,
318
+ conflicts,
319
+ fromA: [...bySeq.values()].filter((v) => v.tag === 'a').length,
320
+ fromB: [...bySeq.values()].filter((v) => v.tag === 'b').length,
321
+ };
322
+ }
@@ -0,0 +1,156 @@
1
+ // 会话日志(session.v*.jsonl.zstd)完整性检查器
2
+ //
3
+ // 用途:跨机同步前后判定一份会话日志是否「自洽」(seq 连续)、以及两份日志
4
+ // 之间是「包含关系」(可以安全覆盖)还是「分叉」(覆盖就会丢事件、产生 seq gap)。
5
+ //
6
+ // 为什么必须做:会话日志是 append-only 的多帧 zstd,每个事件一帧、行内带 seq。
7
+ // 两台机器同时在同一个会话里跑,各自追加自己的帧;同步只按文件覆盖,
8
+ // 后推的一方赢、另一方那段事件被整段丢掉 —— 表现就是 DSH 启动时报
9
+ // corrupt session log: released v2 row N has seq gap (expected N, got M)
10
+ //
11
+ // 用法:
12
+ // node check-session-log.mjs <log 文件> [<对比的 log 文件>]
13
+ // 输出 JSON:
14
+ // { ok, rows, header, gaps:[{at,expected,got}], seqTail, seqFirst, verdict }
15
+ // 带第二个参数时额外输出 { compare: { relation: 'prefix'|'superset'|'fork'|'identical'|'disjoint', ... } }
16
+ //
17
+ // 退出码:0=自洽;1=有 gap / 分叉;2=用法或解压失败
18
+
19
+ import fs from 'node:fs';
20
+ import zlib from 'node:zlib';
21
+
22
+ const ZSTD_MAGIC = [0x28, 0xb5, 0x2f, 0xfd];
23
+ const isFrameMagic = (b, i) => b.length >= i + 4 && b[i] === 0x28 && b[i + 1] === 0xb5 && b[i + 2] === 0x2f && b[i + 3] === 0xfd;
24
+
25
+ /** 把多帧 zstd 缓冲逐帧解开,拼成完整明文。节点只解第一帧,所以必须自己切帧。 */
26
+ function decompressAllFrames(buf) {
27
+ const out = [];
28
+ let off = 0;
29
+ while (off < buf.length) {
30
+ if (!isFrameMagic(buf, off)) {
31
+ // 帧头之后有杂字节:记下来交给上层判定(可能是历史写坏残留)
32
+ throw new Error(`invalid frame magic at byte ${off}`);
33
+ }
34
+ // 二分找这一帧的最小可解前缀
35
+ let lo = off + 1;
36
+ let hi = buf.length;
37
+ let expected = null;
38
+ let frameEnd = -1;
39
+ while (lo <= hi) {
40
+ const mid = (lo + hi) >> 1;
41
+ let got = null;
42
+ try { got = zlib.zstdDecompressSync(buf.subarray(off, mid)); } catch { got = null; }
43
+ if (got === null) { lo = mid + 1; continue; }
44
+ if (expected === null) { expected = got; frameEnd = mid; hi = mid - 1; continue; }
45
+ if (got.length >= expected.length) { frameEnd = mid; hi = mid - 1; } else { lo = mid + 1; }
46
+ }
47
+ if (frameEnd < 0) throw new Error(`failed to decode frame at byte ${off}`);
48
+ // 带 content checksum 的帧,二分结果会短 4 字节:用「下一处帧头」校正
49
+ const withCs = frameEnd + 4;
50
+ if (frameEnd < buf.length && isFrameMagic(buf, frameEnd)) {
51
+ // 正好落在帧头,不用修
52
+ } else if (withCs <= buf.length && (withCs === buf.length || isFrameMagic(buf, withCs))) {
53
+ frameEnd = withCs;
54
+ }
55
+ out.push(zlib.zstdDecompressSync(buf.subarray(off, frameEnd)));
56
+ off = frameEnd;
57
+ }
58
+ return Buffer.concat(out);
59
+ }
60
+
61
+ function analyze(file) {
62
+ const buf = fs.readFileSync(file);
63
+ const text = decompressAllFrames(buf).toString('utf8');
64
+ const lines = text.split('\n').filter((l) => l.trim() !== '');
65
+ if (lines.length === 0) return { ok: false, rows: 0, error: 'empty log' };
66
+
67
+ let header = null;
68
+ try { header = JSON.parse(lines[0]); } catch { header = null; }
69
+
70
+ const seqs = [];
71
+ for (let i = 1; i < lines.length; i++) {
72
+ let row;
73
+ try { row = JSON.parse(lines[i]); } catch { continue; }
74
+ if (typeof row.seq === 'number') seqs.push(row.seq);
75
+ }
76
+ const gaps = [];
77
+ for (let i = 1; i < seqs.length; i++) {
78
+ if (seqs[i] !== seqs[i - 1] + 1) {
79
+ gaps.push({ at: i, expected: seqs[i - 1] + 1, got: seqs[i] });
80
+ }
81
+ }
82
+ return {
83
+ ok: gaps.length === 0,
84
+ bytes: buf.length,
85
+ lines: lines.length,
86
+ rows: seqs.length,
87
+ header: header === null ? null : {
88
+ version: header.version,
89
+ sessionId: header.sessionId,
90
+ cwd: header.cwd,
91
+ createdAt: header.createdAt,
92
+ keys: Object.keys(header)
93
+ },
94
+ seqFirst: seqs.length ? seqs[0] : null,
95
+ seqTail: seqs.length ? seqs[seqs.length - 1] : null,
96
+ gaps
97
+ };
98
+ }
99
+
100
+ function relation(a, b) {
101
+ // a、b 的 seq 集合关系
102
+ const sa = new Set(a.seqSet);
103
+ const sb = new Set(b.seqSet);
104
+ const onlyA = [...sa].filter((x) => !sb.has(x));
105
+ const onlyB = [...sb].filter((x) => !sa.has(x));
106
+ let rel;
107
+ if (onlyA.length === 0 && onlyB.length === 0) rel = 'identical';
108
+ else if (onlyB.length === 0) rel = 'superset'; // a 完全包含 b(a 更全)
109
+ else if (onlyA.length === 0) rel = 'prefix'; // a 是 b 的前缀(b 更全)
110
+ else rel = 'fork'; // 两边互有对方没有的事件 —— 真分叉
111
+ return {
112
+ relation: rel,
113
+ onlyA: onlyA.length,
114
+ onlyB: onlyB.length,
115
+ sampleOnlyA: onlyA.slice(0, 5),
116
+ sampleOnlyB: onlyB.slice(0, 5)
117
+ };
118
+ }
119
+
120
+ function seqSetOf(file) {
121
+ const buf = fs.readFileSync(file);
122
+ const text = decompressAllFrames(buf).toString('utf8');
123
+ const lines = text.split('\n').filter((l) => l.trim() !== '');
124
+ const seqs = [];
125
+ for (let i = 1; i < lines.length; i++) {
126
+ try { const r = JSON.parse(lines[i]); if (typeof r.seq === 'number') seqs.push(r.seq); } catch { }
127
+ }
128
+ return seqs;
129
+ }
130
+
131
+ const args = process.argv.slice(2).filter(Boolean);
132
+ if (args.length === 0) {
133
+ console.error('用法:node check-session-log.mjs <log> [<对比 log>]');
134
+ process.exit(2);
135
+ }
136
+
137
+ let rc = 0;
138
+ const out = {};
139
+ try {
140
+ const a = analyze(args[0]);
141
+ a.seqSet = seqSetOf(args[0]);
142
+ out.self = { file: args[0], ok: a.ok, bytes: a.bytes, rows: a.rows, seqFirst: a.seqFirst, seqTail: a.seqTail, gaps: a.gaps, header: a.header };
143
+ if (!a.ok) rc = 1;
144
+ if (args[1]) {
145
+ const b = analyze(args[1]);
146
+ b.seqSet = seqSetOf(args[1]);
147
+ out.other = { file: args[1], ok: b.ok, bytes: b.bytes, rows: b.rows, seqFirst: b.seqFirst, seqTail: b.seqTail, gaps: b.gaps };
148
+ out.compare = relation(a, b);
149
+ if (out.compare.relation === 'fork') rc = 1;
150
+ }
151
+ } catch (e) {
152
+ out.error = e.message;
153
+ rc = 2;
154
+ }
155
+ console.log(JSON.stringify(out, null, 2));
156
+ process.exit(rc);
@@ -1,4 +1,4 @@
1
- <#
1
+ <#
2
2
  打包 dsh-config-sync-plugin 插件 tgz(发布用,自包含:只读本仓库)
3
3
 
4
4
  用法
@@ -94,7 +94,7 @@ function check(label, cond, detail = '') {
94
94
  }
95
95
 
96
96
  console.log('== dsh-config-sync-plugin 宿主半身自检 ==')
97
- check('apply() 注册了路由', routes.size === 10 && routes.has('/config-sync/update') && routes.has('/config-sync/scope') && routes.has('/config-sync/extra-config') && routes.has('/config-sync/conflict') && routes.has('/config-sync/roots') && routes.has('/config-sync/feedback'), `实际 ${routes.size} 条:${[...routes.keys()].join(', ')}`)
97
+ check('apply() 注册了路由', routes.size === 11 && routes.has('/config-sync/update') && routes.has('/config-sync/scope') && routes.has('/config-sync/extra-config') && routes.has('/config-sync/conflict') && routes.has('/config-sync/roots') && routes.has('/config-sync/feedback') && routes.has('/config-sync/cache-guard'), `实际 ${routes.size} 条:${[...routes.keys()].join(', ')}`)
98
98
 
99
99
  const status = await call('/config-sync/status', { headers: { host: 'localhost:3080' } })
100
100
  const body = JSON.parse(status.body || '{}')
@@ -613,8 +613,10 @@ if (prevScope === null) { try { unlinkSync(scopeFile) } catch { } } else writeFi
613
613
 
614
614
  // 进度窗口的收尾:推送/拉取完成后窗口留着等用户自己关(不自动消失),
615
615
  // 且客户端是在这之前由 explorer 拉起来的 —— 所以点 × 关掉窗口不会把客户端带走。
616
- check('推送/拉取完成后进度窗口不自动关闭(等按键或点 ×)',
617
- postExitSrc.includes("if ($Mode -eq 'pull' -or $Mode -eq 'push'") && postExitSrc.includes('RawUI.ReadKey'),
616
+ // 0.3.64 起改成「展示 6 分钟后自动关窗」:远程桌面/无焦点时 ReadKey 会一直卡住,
617
+ // 用户要的是别让窗口永远挡在前面。所以断言改成盯 Start-Sleep 而不是 ReadKey。
618
+ check('推送/拉取完成后进度窗口保留一段时间再自动关闭(不再卡在 ReadKey)',
619
+ postExitSrc.includes("if ($Mode -eq 'pull' -or $Mode -eq 'push'") && /Start-Sleep -Seconds 360/.test(postExitSrc) && !postExitSrc.includes('RawUI.ReadKey'),
618
620
  postExit || 'post-exit.ps1')
619
621
  check('插件更新完成后窗口同样留着(不与同步窗口两套行为)',
620
622
  /-eq 'pull'.*?-eq 'push'.*?-eq 'update'/.test(postExitSrc) && postExitSrc.includes('插件更新已完成'),
@@ -1457,5 +1459,69 @@ console.log('== 0.3.54:三处纯性能改动(行为不变) ==')
1457
1459
  'Get-OversizedHistory 的返回值')
1458
1460
  }
1459
1461
 
1462
+ console.log('== 0.3.68:会话投影缓存守卫(agent-busy 自动清缓存) ==')
1463
+ {
1464
+ const guardSrc = readFileSync(join(pluginRootSelf, 'runtime', 'tools', 'session-cache-guard.mjs'), 'utf8')
1465
+ const indexSrc = readFileSync(join(pluginRootSelf, 'index.js'), 'utf8')
1466
+ const clientSrc = readFileSync(join(pluginRootSelf, 'client.js'), 'utf8')
1467
+
1468
+ check('守卫库导出 runGuard / clearSessionCaches / appendGuardLog / scanSessionCaches',
1469
+ /export function runGuard/.test(guardSrc) && /export function clearSessionCaches/.test(guardSrc)
1470
+ && /export function appendGuardLog/.test(guardSrc) && /export function scanSessionCaches/.test(guardSrc))
1471
+ check('判定同时要求:缓存标空 + 日志里有对话 + 日志比缓存新',
1472
+ guardSrc.includes('if (rec.blank !== true) continue')
1473
+ && guardSrc.includes('const progressed = head.hasTurn || head.hasUser')
1474
+ && guardSrc.includes('head.tailSeq <= rec.maxSeq'), '守卫的三重判据')
1475
+ check('清理只挪走不改内容:写备份目录、全程不 unlink',
1476
+ guardSrc.includes("'session-cache-guard-backup'") && guardSrc.includes('renameSync')
1477
+ && !guardSrc.includes('unlinkSync'), '只 rename 到备份目录')
1478
+ check('宿主导入守卫库并注册 /config-sync/cache-guard',
1479
+ indexSrc.includes("from './runtime/tools/session-cache-guard.mjs'")
1480
+ && indexSrc.includes("const ROUTE_CACHE_GUARD = '/config-sync/cache-guard'")
1481
+ && indexSrc.includes('handleCacheGuard'), 'index.js 的接线')
1482
+ check('设置里有 cacheGuard 开关(默认开:raw.cacheGuard !== false)',
1483
+ indexSrc.includes('cacheGuard: raw.cacheGuard !== false')
1484
+ && indexSrc.includes('cacheGuard: s.cacheGuard !== false'), 'readSettings / writeSettings')
1485
+ check('启动后挂定时扫描,且受开关控制',
1486
+ indexSrc.includes('function scheduleCacheGuard(config)')
1487
+ && indexSrc.includes('scheduleCacheGuard(config)')
1488
+ && indexSrc.includes("readSettings(dshHomeOf(config)).cacheGuard === false"), 'scheduleCacheGuard')
1489
+ check('status 里带 cacheGuard 状态快照',
1490
+ indexSrc.includes('cacheGuard: cacheGuardSnapshot(config)'), 'inspect() 的返回体')
1491
+ check('四种 action:scan / sweep / clear / busy',
1492
+ indexSrc.includes("action === 'scan'") && indexSrc.includes("action === 'sweep'")
1493
+ && indexSrc.includes("action === 'clear'") && indexSrc.includes("action === 'busy'"), 'handleCacheGuard 的分支')
1494
+ check('客户端包了 sessions.create,撞 agent-busy 才介入',
1495
+ clientSrc.includes('function guardSessionCreate(sessions)')
1496
+ && clientSrc.includes('sessions.create = async function patchedCreate')
1497
+ && clientSrc.includes("const BUSY_RE = /session\\/agent-busy"), 'client.js 的守卫')
1498
+ check('重试前去掉旧 sessionId(否则会再撞同一堵墙)',
1499
+ clientSrc.includes('delete retry.sessionId'), 'patchedCreate 的重试参数')
1500
+ check('客户端把 sessionId 上报给宿主',
1501
+ clientSrc.includes("action: 'busy', sessionId: sessionId || ''"), 'reportAgentBusy')
1502
+
1503
+ const gGet = await call('/config-sync/cache-guard', { headers: { host: 'localhost:3080' } })
1504
+ const gBody = JSON.parse(gGet.body || '{}')
1505
+ check('GET /config-sync/cache-guard 返回 200 且只读',
1506
+ gGet.statusCode === 200 && gBody.ok === true && typeof gBody.scanned === 'number'
1507
+ && Array.isArray(gBody.stale) && typeof gBody.staleCount === 'number', gGet.body.slice(0, 200))
1508
+ check('GET 不动手:applied=false 且 removed 为空',
1509
+ gBody.applied === false && Array.isArray(gBody.removed) && gBody.removed.length === 0, gGet.body.slice(0, 200))
1510
+ const gCross = await call('/config-sync/cache-guard', {
1511
+ method: 'POST',
1512
+ headers: { host: 'localhost:3080', 'sec-fetch-site': 'cross-site' },
1513
+ body: JSON.stringify({ action: 'sweep' }),
1514
+ })
1515
+ check('跨站 POST 被 403 挡住', gCross.statusCode === 403, String(gCross.statusCode))
1516
+ const gClear = await call('/config-sync/cache-guard', {
1517
+ method: 'POST',
1518
+ headers: { host: 'localhost:3080' },
1519
+ body: JSON.stringify({ action: 'clear', ids: [] }),
1520
+ })
1521
+ const gClearBody = JSON.parse(gClear.body || '{}')
1522
+ check('clear 不给 ids 时 400 且 ok=false',
1523
+ gClear.statusCode === 400 && gClearBody.ok === false, gClear.body.slice(0, 160))
1524
+ }
1525
+
1460
1526
  console.log('')
1461
1527
  process.exit(failures === 0 ? 0 : 1)