dsh-log-contract 0.3.28 → 0.3.33

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/lib/explain.js ADDED
@@ -0,0 +1,129 @@
1
+ /**
2
+ * dsh-log-contract · lib/explain.js
3
+ *
4
+ * `explain <ruleId>` 的数据层:把一条契约规则"解读"成结构化对象。
5
+ *
6
+ * **单一权威**:标题 / 判据(触发条件)/ 严重度 / 层级 / 出处 **原样引自
7
+ * `lib/contracts.js` 的 `CONTRACT_RULES`**——本模块 ⛔ 不复制、不改写判据文本,
8
+ * 也不维护第二份规则清单(改规则只改注册表一处)。
9
+ *
10
+ * 本模块只补充两类**指针**(不是判据):
11
+ * - 正/反例指针:扫描 `test/` 里以该规则 id 做断言的用例(文件 + 标题);
12
+ * 发布包不含 `test/` 时如实为空(不冒充有对照)。
13
+ * - 相关命令:用法指针(check / prewrite / contracts,按层级补专项开关)。
14
+ */
15
+ import fs from 'node:fs';
16
+ import path from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+ import { CONTRACT_RULES, ruleById } from './contracts.js';
19
+
20
+ /** 契约目录文档(判据全文的可读版;与注册表由生成器同步)。 */
21
+ export const EXPLAIN_DOC = 'docs/CONTRACTS.md';
22
+
23
+ /** `--json` 输出的**稳定键集**(未知 id 时同键、值为 null/空)。 */
24
+ export const EXPLAIN_KEYS = Object.freeze([
25
+ 'id', 'found', 'title', 'severity', 'layer', 'source', 'criteria',
26
+ 'examples', 'relatedCommands', 'doc',
27
+ ]);
28
+
29
+ const NEGATIVE_HINTS = ['负对照', '反例', '违规', '判红', '拒绝', '拒', '撕裂', '缺口', '损坏', '截断', '坏', 'poison', 'corrupt', 'bad', 'gap', 'torn', 'missing', 'fail', '未知 id', 'unknown'];
30
+ const POSITIVE_HINTS = ['正对照', '正例', '合规', '判绿', '通过', '健康', 'good', 'green', 'complete', '绿'];
31
+
32
+ function classify(text) {
33
+ const t = String(text);
34
+ const neg = NEGATIVE_HINTS.some((k) => t.includes(k));
35
+ const pos = POSITIVE_HINTS.some((k) => t.includes(k));
36
+ if (neg && !pos) return 'negative';
37
+ if (pos && !neg) return 'positive';
38
+ return 'unclassified';
39
+ }
40
+
41
+ /**
42
+ * 扫描 `test/` 找该规则 id 的对照用例指针(文件 + 最近的用例标题)。
43
+ * 发布包/无 test 目录 ⇒ 空列表 + note(⛔ 不冒充"有对照")。
44
+ */
45
+ export function examplePointers(ruleId, { testDir } = {}) {
46
+ const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
47
+ const dir = testDir ?? path.join(root, 'test');
48
+ const out = { negative: [], positive: [], unclassified: [], note: null };
49
+ if (!fs.existsSync(dir)) {
50
+ out.note = '本安装不含 test/ 目录(发布包只含运行时代码与文档)——判据以规则注册表为准';
51
+ return out;
52
+ }
53
+ const quoted = [`'${ruleId}'`, `"${ruleId}"`, `\`${ruleId}\``];
54
+ for (const name of fs.readdirSync(dir).filter((f) => f.endsWith('.js')).sort()) {
55
+ const file = path.join(dir, name);
56
+ let text;
57
+ try {
58
+ text = fs.readFileSync(file, 'utf8');
59
+ } catch {
60
+ continue;
61
+ }
62
+ const lines = text.split('\n');
63
+ for (let i = 0; i < lines.length; i++) {
64
+ if (!quoted.some((q) => lines[i].includes(q))) continue;
65
+ // 最近的 it/test/describe 标题(往上找,至多 60 行)——指针指向"哪条用例"。
66
+ let title = '';
67
+ for (let j = i; j >= 0 && j >= i - 60; j--) {
68
+ const m = /(?:^|[^\w.])(?:it|test|describe)(?:\.\w+)*\(\s*[`'"]([^`'"]{4,120})/.exec(lines[j]);
69
+ if (m) { title = m[1]; break; }
70
+ }
71
+ const bucket = classify(`${title} ${lines[i]}`);
72
+ const pointer = `test/${name}${title ? ` › ${title}` : ''}`;
73
+ if (!out[bucket].includes(pointer)) out[bucket].push(pointer);
74
+ }
75
+ }
76
+ return out;
77
+ }
78
+
79
+ /** 相关命令(用法指针,按层级补专项开关)。 */
80
+ export function relatedCommandsOf(rule) {
81
+ const cmds = [
82
+ 'dsh-log-contract check <session-log> # 离线体检:逐条判定本规则',
83
+ 'dsh-log-contract prewrite <edit-file> --log <session-log> # 写前校验(落盘前拦截)',
84
+ `dsh-log-contract contracts # 全部规则目录(${CONTRACT_RULES.length} 条,含出处)`,
85
+ ];
86
+ if (rule?.layer === 'archive') {
87
+ cmds.push('dsh-log-contract check <session-log> --archive-root DIR # A1 维度需归档根才可判');
88
+ }
89
+ if (rule?.layer === 'migration') {
90
+ cmds.push('dsh-log-contract check <session-log> --json # migration 维度(G 段独立于 ok/verdict)');
91
+ }
92
+ return cmds;
93
+ }
94
+
95
+ /**
96
+ * 解读一条规则。**数据只来自 `CONTRACT_RULES`**(单一权威)。
97
+ *
98
+ * @param {string} ruleId 规则 id(如 `E5`;大小写不敏感)。
99
+ * @param {{testDir?: string}} [opts]
100
+ * @returns {object} 与 `EXPLAIN_KEYS` 同键的稳定结构;未知 id ⇒ `found:false`
101
+ * 且其余字段为 null/空数组(键集不变,便于机器判读)。
102
+ */
103
+ export function explainRule(ruleId, opts = {}) {
104
+ const raw = String(ruleId ?? '').trim();
105
+ const rule = ruleById(raw) ?? CONTRACT_RULES.find((r) => r.id.toLowerCase() === raw.toLowerCase());
106
+ const base = {
107
+ id: rule?.id ?? raw,
108
+ found: Boolean(rule),
109
+ title: rule?.title ?? null,
110
+ severity: rule?.severity ?? null,
111
+ layer: rule?.layer ?? null,
112
+ source: rule?.source ?? null,
113
+ criteria: rule?.description ?? null,
114
+ examples: { negative: [], positive: [], unclassified: [] },
115
+ relatedCommands: [],
116
+ doc: EXPLAIN_DOC,
117
+ };
118
+ if (!rule) {
119
+ return {
120
+ ...base,
121
+ error: 'unknown-rule',
122
+ knownCount: CONTRACT_RULES.length,
123
+ hint: `未知规则 id "${raw}"——用 \`dsh-log-contract contracts\` 查看全部 ${CONTRACT_RULES.length} 条(或见 ${EXPLAIN_DOC})`,
124
+ };
125
+ }
126
+ base.examples = examplePointers(rule.id, opts);
127
+ base.relatedCommands = relatedCommandsOf(rule);
128
+ return base;
129
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * dsh-log-contract · lib/host-probes.js —— **行为探针**(漂移检测的正解)
3
- * ([n]-09-14)
3
+ * (2026-09-14)
4
4
  *
5
5
  * 为什么需要它:本包"承重墙建错了地方"——**委托宿主运行时函数**的判据基本正确,
6
6
  * **作者手写镜像/自建模型**的判据成片出错,而 `hostPackageVersion()`/`hostCapability()`
@@ -119,8 +119,8 @@ export const PROBES = [
119
119
  rules: ['E8'],
120
120
  expect: 'adoptSessionEvent 不拒(宿主 load 路径容忍)',
121
121
  // 这条探针**修正了一条规则的过度声称**(探针的价值实证):
122
- // · 宿主 `assertSessionEventEnvelope`(dsh-session@0.1.5-rc.1 lib/index.js:[n]-[n])确实拒多余键,
123
- // 但它的**唯一调用点**是 Session 构造器的 **seed 路径**(:[n]-[n])——不是 JSONL load 路径;
122
+ // · 宿主 `assertSessionEventEnvelope`(dsh-session@0.1.5-rc.1 lib/index.js:849-861)确实拒多余键,
123
+ // 但它的**唯一调用点**是 Session 构造器的 **seed 路径**(:1063-1068)——不是 JSONL load 路径;
124
124
  // · load 路径(`adoptSessionEvent`)实测**容忍**多余键。
125
125
  // ⇒ E8 从 error 降为 **warning**、口径限定为"seed/restore 会拒"(原判"写入即拒"是过度声称)。
126
126
  run: () => rejects(() => adoptSessionEvent({
@@ -165,7 +165,7 @@ export function runHostProbes(probes = PROBES) {
165
165
  ok = probe.run() === true;
166
166
  } catch (err) {
167
167
  ok = false;
168
- error = String(err?.message ?? err).slice(0, [n]);
168
+ error = String(err?.message ?? err).slice(0, 200);
169
169
  }
170
170
  results.push({ id: probe.id, title: probe.title, rules: probe.rules, expect: probe.expect, ok, ...(error ? { error } : {}) });
171
171
  if (!ok) for (const r of probe.rules) unverified.add(r);
package/lib/index.js CHANGED
@@ -9,6 +9,7 @@ export { validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope }
9
9
  export { createPreWriter, preWriterFromLog } from './prewrite.js';
10
10
  export { repairSession, strictScanText, removeMarkersText, neutralizeMarkersText, clipCrossStepSourcesText, dropFailedTurnsText, trimLastMessagesText, trimLastMessagesByBudget, estimateTokensText, compactLastMessagesText, rebuildZstdText, tailRenumberText, neutralizeOrphanText, extractTurnText, keepRangesText } from './repair.js';
11
11
  export { CONTRACT_RULES, LAYER, SEVERITY, ruleById } from './contracts.js';
12
+ export { explainRule, examplePointers, relatedCommandsOf, EXPLAIN_KEYS, EXPLAIN_DOC } from './explain.js';
12
13
  export { HOST_MAX_FILE_VERSION, hostPackageVersion, hostCapability, isAssessableFileVersion } from './vocab.js';
13
14
  export { TESTED_BASELINE, compareVersions, detectSupport, supportOfLog } from './version-support.js';
14
15
  export { tokenMeterViolations, tokenMeterSourceViolations, stepKeyViolations, nullTurnStepViolations, turnEndReasonViolations, ignorableTypeViolations, physicalOrderViolations, inboxReplayViolations, sourceEventSeqElementViolations, rawSourceEventSeqViolations, isSeqRangePair, seedLengthViolations, carrierPairingViolations, carrierWriteViolations, isCarrierAuditSegment, carrierRangesMatch, surfaceReplaceRange, declarativeIgnorableViolations, isIgnorableRegistered, resolveIgnorableWhitelist, DEFAULT_IGNORABLE_WHITELIST } from './checks.js';
@@ -1,26 +1,26 @@
1
1
  /**
2
2
  * dsh-log-contract · lib/legacy-fold.js —— **v0/v1/v2 旧格式的 surface 终验器**
3
3
  *
4
- * 为什么需要这个文件(一手证据,[n]-09-14):
4
+ * 为什么需要这个文件(一手证据,2026-09-14):
5
5
  *
6
6
  * 官方 `@deepseek-ai/dsh-session` 的 `foldSurface` 在 0.1.5-rc.1 里换成了 **v3 语义**,
7
7
  * 它**不是** rc.7(v0 语义)的超集,而是一个**不同格式**的校验器:
8
8
  * - replace 操作数字段改名:rc.7 `{op,start,end}` → 0.1.5 `{op,startSeq,endSeq}`
9
- * (0.1.5 `lib/index.js:[n]`:`isReplaceOp` 要求 startSeq/endSeq ⇒ 旧 marker 直接
9
+ * (0.1.5 `lib/index.js:279`:`isReplaceOp` 要求 startSeq/endSeq ⇒ 旧 marker 直接
10
10
  * “carries an invalid replace surfaceOp”);
11
- * - provenance 收紧:0.1.5 `lib/index.js:[n]` 起对 `assistant/message` **一律**禁止
11
+ * - provenance 收紧:0.1.5 `lib/index.js:285` 起对 `assistant/message` **一律**禁止
12
12
  * `sourceEventSeqs`(“embeds its source stream and cannot carry sourceEventSeqs”);
13
13
  * rc.7 允许(空数组仅限 assistant/message)。
14
14
  *
15
15
  * App 2.0.9 的真实文件版本分布证明旧格式仍在线上:App 内置
16
16
  * `dsh-session-format-v0-to-v1` / `v1-to-v2` / `v2-to-v3` 三个迁移包,
17
- * `SESSION_FORMAT_VERSION = 3`;且 `v2-to-v3/lib/index.js:[n]-[n]` 明示 **v2 仍是
17
+ * `SESSION_FORMAT_VERSION = 3`;且 `v2-to-v3/lib/index.js:361-371` 明示 **v2 仍是
18
18
  * `{start,end}`**、由迁移改名为 `startSeq/endSeq`。
19
19
  *
20
20
  * ⇒ 结论:**用运行时的 v3 `foldSurface` 去终验 v0/v1/v2 文件必然误报**;旧格式必须用
21
21
  * 本文件这份等价实现(rc.7 `foldSurface` 的逐条移植,语义等价、同样 fail-loud)。
22
22
  *
23
- * 移植源:`@deepseek-ai/dsh-session@0.1.0-rc.7` `lib/index.js:[n]-[n]`
23
+ * 移植源:`@deepseek-ai/dsh-session@0.1.0-rc.7` `lib/index.js:229-455`
24
24
  * (`isSurfaceEligibleType` / `isEventSeq` / `isReplaceOp` / `surfaceOpOf` /
25
25
  * `assertProvenance` / `replacementRange` / `isDeepEqualJson` / `assertToolResultRewrite` /
26
26
  * `planSurfaceEvent` / `applySurfacePlan` / `foldSurface`)。
package/lib/log-reader.js CHANGED
@@ -5,19 +5,42 @@
5
5
  * `decodeStorageRecord` 展开(chunk 行展开 / 损坏行报错)。
6
6
  *
7
7
  * 契约来源:
8
- * - 帧扫描/撕裂尾帧判定:按 zstd 规范逐帧扫(magic 0xFD2FB[n]、descriptor、block 头)。
8
+ * - 帧扫描/撕裂尾帧判定:按 zstd 规范逐帧扫(magic 0xFD2FB528、descriptor、block 头)。
9
9
  * - 行解码:本地兼容层 `./compat.js` 的 `decodeStorageRecord`(原官方导出于 0.1.5 移除)
10
- * (lib/index.js:[n],validateRow :[n] / expandRow :[n])。
10
+ * (lib/index.js:1029,validateRow :922 / expandRow :973)。
11
11
  * - 损坏语义:chunk 行损坏 = 整段 run 丢失且加载失败(dsh-session
12
- * lib/index.js:[n]-[n] 注释明示 fail-loud,无跳过逃生舱)。
12
+ * lib/index.js:1022-1024 注释明示 fail-loud,无跳过逃生舱)。
13
13
  */
14
14
  import fs from 'node:fs';
15
15
  import { zstdDecompressSync } from 'node:zlib';
16
16
  import { decodeStorageRecord, normalizeEventSeqRanges } from './compat.js';
17
17
 
18
- const ZSTD_MAGIC = 0xfd2fb[n];
18
+ const ZSTD_MAGIC = 0xfd2fb528;
19
19
 
20
- /** 扫描 zstd 帧边界;返回 [start, end] 列表与是否出现撕裂尾帧。 */
20
+ /**
21
+ * 单帧元数据(0.3.32 · Z7/Z8)。
22
+ *
23
+ * - `{start, end, size, checksum}`:`start`/`end` 是帧在文件里的字节区间(含帧头与
24
+ * checksum 尾),`size = end - start`,`checksum` = 帧头 descriptor 的
25
+ * `Content_Checksum` 位(bit 2)是否置位。
26
+ * - **向后兼容**:旧调用方按 `[start, end]` 解构(`const [s, e] = frames[i]`)仍然可用
27
+ * —— 对象自带 `Symbol.iterator`,只产出 start/end 两个数。新代码请读属性。
28
+ */
29
+ function frameMetadata(start, end, checksum) {
30
+ const meta = { start, end, size: end - start, checksum };
31
+ meta[Symbol.iterator] = function* frameRangeIterator() {
32
+ yield start;
33
+ yield end;
34
+ };
35
+ return meta;
36
+ }
37
+
38
+ /**
39
+ * 扫描 zstd 帧边界。
40
+ *
41
+ * @returns {{frames: Array<{start:number,end:number,size:number,checksum:boolean}>, torn:boolean, reason?:string}}
42
+ * 每帧元数据(0.3.32 起由 `[start,end]` 二元组升级为对象,仍支持二元组解构)+ 是否出现撕裂尾帧。
43
+ */
21
44
  export function scanZstdFrames(buf) {
22
45
  const frames = [];
23
46
  let offset = 0;
@@ -57,7 +80,7 @@ export function scanZstdFrames(buf) {
57
80
  torn = true;
58
81
  break;
59
82
  }
60
- // R4([n]-10-26 事故复盘):块头是 **3 字节** little-endian。旧实现这里用
83
+ // R4(2026-10-26 事故复盘):块头是 **3 字节** little-endian。旧实现这里用
61
84
  // `readUInt32LE`(读 4 字节)——恰剩 3 字节时抛 `ERR_OUT_OF_RANGE`,一个截断
62
85
  // 文件就炸掉整个读取/枚举入口。改 `readUIntLE(offset, 3)`:语义完全等价
63
86
  // (块大小只有低 21 位参与 `>>> 3 & 0x1fffff`,第 4 字节从未被用到),
@@ -74,7 +97,7 @@ export function scanZstdFrames(buf) {
74
97
  break;
75
98
  }
76
99
  if (checksum) offset += 4;
77
- frames.push([start, offset]);
100
+ frames.push(frameMetadata(start, offset, checksum));
78
101
  }
79
102
  return { frames, torn, reason: torn ? 'incomplete-tail' : undefined };
80
103
  }
@@ -82,23 +105,23 @@ export function scanZstdFrames(buf) {
82
105
  /** 把 zstd 多帧拼成完整明文;任一帧解码失败即抛错(N5 单帧全损语义)。 */
83
106
  export function decompressZstd(buf, { allowTorn = true } = {}) {
84
107
  const { frames, torn } = scanZstdFrames(buf);
85
- // ── [n]-09-14 实测:这里的 Z2 是误报 ───────────────────────────────────
108
+ // ── 2026-09-14 实测:这里的 Z2 是误报 ───────────────────────────────────
86
109
  // 撕裂尾帧**不是**损坏:宿主 `dsh-session-persistence-jsonl@0.1.5-rc.1`
87
- // · `readZstdPrefix`(lib/index.js:[n]-[n])——"Decode complete frames and retain
88
- // complete JSONL records from a torn final frame",恢复并返回 `tornTruncateTo`(:[n]);
89
- // · 下次写入 `:[n]-[n]` 调 `truncateTornTail` 自动截断。
110
+ // · `readZstdPrefix`(lib/index.js:2791-2849)——"Decode complete frames and retain
111
+ // complete JSONL records from a torn final frame",恢复并返回 `tornTruncateTo`(:2847);
112
+ // · 下次写入 `:226-228` 调 `truncateTornTail` 自动截断。
90
113
  // 旧实现(本函数)对 torn 直接抛错 ⇒ `loadSessionLog` 返回 header=null/events=[]
91
114
  // ⇒ `validate.js` 级联出 Z1(warning)+Z2(error)+H1(error)、verdict=broken —— 把宿主
92
115
  // **本来能修**的"边写边读"健康态报成"会话坏了"。现在对齐宿主:解出全部**完整帧**,
93
116
  // 尾帧未写完的部分丢弃,由调用方用 `frameInfo.torn` 报 Z1(warning)。
94
117
  // `frames.length === 0`(连一个完整帧都没有,例如头帧就断了)**仍然报错** —— 宿主
95
- // `readZstdPrefix:[n]` 对这种情况同样抛 "empty or header-less Zstandard session log"。
118
+ // `readZstdPrefix:2793` 对这种情况同样抛 "empty or header-less Zstandard session log"。
96
119
  if (frames.length === 0) throw new Error('空文件 / 无完整 zstd 帧(incomplete or header-less session log)');
97
120
  if (torn && !allowTorn) throw new Error('zstd 尾帧撕裂(incomplete tail frame)——strict 模式(allowTorn:false)');
98
121
  // 逐帧解码后一次性 Buffer.concat:避免每帧一次 concat 的 O(n²) 拷贝
99
122
  const parts = new Array(frames.length);
100
123
  for (let i = 0; i < frames.length; i++) {
101
- const [s, e] = frames[i];
124
+ const { start: s, end: e } = frames[i];
102
125
  try {
103
126
  parts[i] = zstdDecompressSync(buf.subarray(s, e));
104
127
  } catch (err) {
@@ -137,7 +160,7 @@ export function tailSeq(path) {
137
160
  return null;
138
161
  }
139
162
  if (frames.length === 0) return null;
140
- const [s, e] = frames[frames.length - 1];
163
+ const { start: s, end: e } = frames[frames.length - 1];
141
164
  try {
142
165
  plain = zstdDecompressSync(buf.subarray(s, e));
143
166
  } catch {
@@ -166,7 +189,8 @@ export function tailSeq(path) {
166
189
  * header: object|null, headerLine: number|null,
167
190
  * rows: Array<{lineNo:number, value:unknown, decoded:Array|null, error:Error|null}>,
168
191
  * events: Array<{seq:number, event:object, lineNo:number}>,
169
- * frameInfo: {frames:number, torn:boolean, compressedBytes:number, plaintextBytes:number},
192
+ * frameInfo: {frames:number, torn:boolean, compressedBytes:number, plaintextBytes:number,
193
+ * frameMeta:Array<{start:number,end:number,size:number,checksum:boolean}>},
170
194
  * }}
171
195
  */
172
196
  export function loadSessionLog(path) {
@@ -190,22 +214,32 @@ export function loadSessionLog(path) {
190
214
  try {
191
215
  ({ frames, torn } = scanZstdFrames(buf));
192
216
  } catch { /* 降级:torn=true ⇒ tailStatus 由 deriveTailStatus 判 */ }
193
- // 帧形状事实(Z4/Z5,[n]-09-16 真机事故):官方写盘形状 = **header 独占第一帧** +
217
+ // 帧形状事实(Z4/Z5,2026-09-16 真机事故):官方写盘形状 = **header 独占第一帧** +
194
218
  // 事件逐帧追加;读取端有硬断言 `assertZstdHeaderFrame`(首帧必须**恰好一行**)。
195
219
  // 这里把该事实带出来给 validate 判:整文件被重压成单帧时,首帧装的是全部行 ⇒ 宿主必抛,
196
220
  // 而抛点在 `listArtifacts` **遍历全库**、无 per-session 容错 ⇒ 整个客户端起不来。
197
221
  let firstFrameOneLine = true, firstFrameLines = 1;
198
222
  try {
199
- const [s0, e0] = frames[0];
223
+ const { start: s0, end: e0 } = frames[0];
200
224
  const first = zstdDecompressSync(buf.subarray(s0, e0)).toString('utf8');
201
225
  const nl = first.indexOf('\n');
202
226
  firstFrameOneLine = nl === first.length - 1 && first.length > 1;
203
227
  firstFrameLines = first.split('\n').filter((x) => x !== '').length;
204
228
  } catch { /* 首帧解码失败另有 Z2 报 */ }
205
- frameInfo = { frames: frames.length, torn, compressedBytes: buf.length, plaintextBytes: plain.length, firstFrameOneLine, firstFrameLines };
229
+ frameInfo = {
230
+ frames: frames.length,
231
+ torn,
232
+ compressedBytes: buf.length,
233
+ plaintextBytes: plain.length,
234
+ firstFrameOneLine,
235
+ firstFrameLines,
236
+ // 逐帧元数据(0.3.32 · Z7 尺寸 / Z8 checksum):判据在 lib/checks.js
237
+ // `frameMetadataViolations()`;不进 report summary(只把结论变成 violations)。
238
+ frameMeta: frames,
239
+ };
206
240
  } else {
207
241
  plain = buf;
208
- frameInfo = { frames: 0, torn: false, compressedBytes: 0, plaintextBytes: plain.length };
242
+ frameInfo = { frames: 0, torn: false, compressedBytes: 0, plaintextBytes: plain.length, frameMeta: [] };
209
243
  }
210
244
  if (loadError) {
211
245
  return {
@@ -217,7 +251,7 @@ export function loadSessionLog(path) {
217
251
  };
218
252
  }
219
253
 
220
- // 按行解码(Buffer 切分),避免整文件字符串化(>[size] 抛字符串上限)
254
+ // 按行解码(Buffer 切分),避免整文件字符串化(>536MB 抛字符串上限)
221
255
  const lines = (() => { const out = []; let s = 0, i; while ((i = plain.indexOf(0x0a, s)) !== -1) { out.push(plain.subarray(s, i).toString('utf8')); s = i + 1 } out.push(plain.subarray(s).toString('utf8')); return out })();
222
256
 
223
257
  // 第一行 = header
@@ -307,7 +341,7 @@ export function deriveTailStatus({ frameInfo, rows = [], header = null } = {}) {
307
341
  *
308
342
  * 帧布局:帧 1 = header 行(单行 JSON,~几百字节),帧 2+ = 事件流。
309
343
  * 短码推导(工作区 createdAt 序号)需要扫全部会话但只需要 header——
310
- * 读文件前缀 64KiB 足够覆盖完整帧 1,避免全量读大文件([internal]压缩后可达
344
+ * 读文件前缀 64KiB 足够覆盖完整帧 1,避免全量读大文件(大会话压缩后可达
311
345
  * 数百 MiB)。失败返回 null(调用方降级)。
312
346
  *
313
347
  * @param {string} path 会话日志文件路径(.jsonl.zstd 或明文 .jsonl)。
@@ -322,7 +356,7 @@ export function readSessionHeader(path) {
322
356
  let head;
323
357
  try {
324
358
  const fd = fs.openSync(path, 'r');
325
- const buf = Buffer.alloc(64 * [n]);
359
+ const buf = Buffer.alloc(64 * 1024);
326
360
  const n = fs.readSync(fd, buf, 0, buf.length, 0);
327
361
  fs.closeSync(fd);
328
362
  head = buf.subarray(0, n);
@@ -340,7 +374,7 @@ export function readSessionHeader(path) {
340
374
  }
341
375
  const { frames } = scanZstdFrames(head);
342
376
  if (frames.length === 0) return null;
343
- const [s, e] = frames[0];
377
+ const { start: s, end: e } = frames[0];
344
378
  let plain;
345
379
  try {
346
380
  plain = zstdDecompressSync(head.subarray(s, e));
package/lib/prewrite.js CHANGED
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * ★ 写前校验(pre-write validation)——本工具的第一公民。
5
5
  *
6
- * 复盘事故([n]-08-25)第 1 次尝试失败就是"违约写入没被拦":surface-replace
6
+ * 复盘事故(2026-08-25)第 1 次尝试失败就是"违约写入没被拦":surface-replace
7
7
  * 的 `sourceEventSeqs` 被清空后写入,会话加载直接抛
8
8
  * `SessionPersistenceCorruptionError`。如果写入前先校验,会话根本不会被改坏。
9
9
  *
@@ -28,7 +28,7 @@ import { normalizeEventSeqRanges } from './compat.js';
28
28
  const LEGACY_MARKER_ID_PREFIXES = ['retrace', 'message-editor'];
29
29
 
30
30
  /**
31
- * **可识别的历史 retrace 载体**([n]-09-14 实测:白名单收窄)。
31
+ * **可识别的历史 retrace 载体**(2026-09-14 实测:白名单收窄)。
32
32
  *
33
33
  * 旧实现只判"任意 `data.editor` 存在" ⇒ **任何**写 `assistant/message` replace + `data.editor`
34
34
  * 的第三方插件都能领 T1 豁免(实测判定:"设计粗糙的豁口")。收窄为四条同时成立:
@@ -67,7 +67,7 @@ function normalizeCandidate(candidate, nextSeq) {
67
67
  * `createPreWriter` 调用内固定**并显式传给每条按版本择路的判定。**不再读写模块级全局**
68
68
  * `fileVersion`——旧实现下同一进程"先 validate(v3) 再 prewrite(v0)"会把同一份合法 v0 输入
69
69
  * 的结论翻成 S4+S8(实测复现)。下游 `dsh-retrace` 正是只传 `events` 直接调用
70
- * (`lib/prewrite-guard.js:[n]`),所以缺省时必须能自行推断,不能把 v3 输入按 0 处理
70
+ * (`lib/prewrite-guard.js:166`),所以缺省时必须能自行推断,不能把 v3 输入按 0 处理
71
71
  * (否则首次调用即 10 条 E3/S2/S8 误报)。
72
72
  *
73
73
  * @param {{ events: Array<object>, baseSeq?: number, formatVersion?: number, header?: object|null, ignorableWhitelist?: string[] }} input
@@ -128,7 +128,7 @@ export function createPreWriter(input = {}) {
128
128
  if (folded.error) {
129
129
  violations.push(violation('S8', { lineNo: null }, `foldSurface 重放失败(按文件版本选:v3 官方 / v0–v2 本地等价):${folded.error.message} —— 会话加载会被拒(SessionPersistenceCorruptionError)`));
130
130
  }
131
- // W1/W2 —— wire 流配对([n]-09-09 V3 验证补:离线 check 有、写前原漏——悬空 tool
131
+ // W1/W2 —— wire 流配对(2026-09-09 V3 验证补:离线 check 有、写前原漏——悬空 tool
132
132
  // 编辑必须写前拦,否则违约写入先落盘、体检才报 = 晚一步)
133
133
  violations.push(...wireViolations(candidateEvents.map((event) => ({ event })), formatVersion));
134
134
  // T1 —— token-meter 配对(事故根因 3 固化)。写前校验只判定**拟写事件自身**
@@ -139,7 +139,7 @@ export function createPreWriter(input = {}) {
139
139
  // (check),不在这里重复拦截(否则历史 marker 会让后续编辑全部被拒)。
140
140
  const lastCandidate = candidateEvents[candidateEvents.length - 1];
141
141
  const legacyKind = legacyMarkerKindOf(lastCandidate);
142
- // 版本门([n]-09-14):降级**只对 ≤v2 文件**。
142
+ // 版本门(2026-09-14):降级**只对 ≤v2 文件**。
143
143
  // 依据:新载体(`user/message` + `data.id`,retrace 0.4.26)根本不带 `data.editor`,在 v3 上
144
144
  // 降级**救不回任何写入**(v3 禁 assistant/message 带 provenance ⇒ S8 兜住) —— 留在 v3 上
145
145
  // 只会掩盖 T1 的真实原因。v0/v1/v2 才是有价值的作用域(回放/重写历史形态 marker)。
@@ -162,7 +162,7 @@ export function createPreWriter(input = {}) {
162
162
  violations.push(t1);
163
163
  }
164
164
  }
165
- // T3/T4 —— 渲染层([n]-09-02 渲染层白屏事故)。**error 级拒绝**:
165
+ // T3/T4 —— 渲染层(2026-09-02 渲染层白屏事故)。**error 级拒绝**:
166
166
  // - T4:拟写事件(step/start|step/end|assistant/message)turn 缺失 → 客户端
167
167
  // 渲染死循环白屏(D8),写入前直接拦下(防再犯:任何写 turn:null 的 marker);
168
168
  // - T3:拟写事件引入 step 节点 key 冲突(同 turn 同 step 的 step/start 重复)→