dsh-log-contract 0.3.20 → 0.3.22

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
@@ -302,6 +302,21 @@ pnpm check && pnpm test # syntax check + contract-doc drift gate + all unit t
302
302
  > Local maintainer tooling is not part of the public repository, so `pnpm check` and `pnpm test`
303
303
  > work from a clean clone.
304
304
 
305
+ ## Local git hooks (opt-in)
306
+
307
+ The repository ships `.githooks/pre-push` (runs `pnpm check` before pushing), but it is
308
+ **not active automatically on clone** — point Git at it explicitly:
309
+
310
+ ```bash
311
+ git config core.hooksPath .githooks # enable
312
+ git config --get core.hooksPath # verify: should print .githooks
313
+ ```
314
+
315
+ Skip only for emergencies: `git push --no-verify`. Uninstall: `git config --unset core.hooksPath`.
316
+
317
+ > Hooks are local convenience, not a trust boundary: CI (`.github/workflows/ci.yml`) runs
318
+ > `pnpm check` / `pnpm check:strict` / `pnpm test`, so clones without hooks stay gated.
319
+
305
320
  Verdict by **log shape** — what the tool must say about each defect class, not about
306
321
  any particular file:
307
322
 
@@ -344,6 +359,50 @@ MIT © OfferKuai Team
344
359
 
345
360
  ---
346
361
 
362
+ ## 🧱 Architecture — contract layer + platform adapter
363
+
364
+ Validation is split into a **platform-agnostic contract layer** (`contract/`) and a **platform adapter**
365
+ (`adapters/dsh/`): invariants, verdict model and the rule registry are shared; event shapes, format
366
+ versions (v0–v4), zstd framing and surface semantics live in the adapter. Adding another host platform is intended to
367
+ mean writing one adapter; the split is extracted and enforced today, while the adapter-facing API
368
+ (orchestration entry, id-neutral violations) is still being finalized.
369
+
370
+ The boundary is machine-enforced: `contract/` may contain no platform vocabulary and no adapter/implementation
371
+ imports (`pnpm check:strict`, also in CI and the optional pre-push hook). The public API, rule set (51 rules)
372
+ and verdicts are unchanged.
373
+
374
+ **Current status: partial.** The split is extracted and machine-enforced, but a second adapter is **not yet
375
+ drop-in**: the contract layer still emits platform rule ids for some invariants, and there is no
376
+ platform-neutral orchestration entry yet — a second adapter today would also need a thin runner.
377
+ See "Known gaps" in the changelog for the tracked follow-up list. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
378
+
379
+ ## 🆕 0.3.18 – 0.3.21 · DSH 0.2.x (session format v4) support
380
+
381
+ **Session format v4** (`@deepseek-ai/dsh-session` 0.2.x) is now validated by format-version dispatch
382
+ rather than by relaxing the format gate:
383
+
384
+ - `tool/result` is validated with the v4 shape (`role: 'tool'`, no `tool-result` wrapper block)
385
+ - `system/message` accepts v4's `source.kind: 'system-prompt'`
386
+ - validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
387
+ - the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
388
+
389
+ **New rules (51 total):**
390
+
391
+ | Rule | Checks |
392
+ |---|---|
393
+ | `G4` | unknown historical events may be declaratively skipped (`ignorable: true`; allow-list injectable) |
394
+ | `S10` | `sourceEventSeqs` elements: non-negative integers after decoding (official interval pairs allowed in storage) |
395
+ | `I2` | `seedLength` means *number of inherited events* (not bytes); `parentSession` + missing/0 is legal |
396
+ | `P5` | two-segment carrier pairing: 2nd segment's first seq == 1st segment seq (read side accepts the legacy order) |
397
+ | `A1` | "in-place restorable" is judged from structured fields only (`archiveRef` / `archive` / `externalized.*`) — never from free text |
398
+
399
+ **Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~536 MB),
400
+ and repair rebuilds `.jsonl.zstd` with streaming frames (header frame + chunked body frames, per-frame checksum + round-trip).
401
+
402
+ **Windows:** the `header.cwd` absolute-path check in `H2` is platform-aware (`win32` and `posix` both accepted).
403
+
404
+ **Compatibility:** Node ≥ 22; `@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`; session formats v0–v4.
405
+
347
406
  ## ⚠️ Upgrading to 0.3.17 — behaviour changes you must know (0.3.12 → 0.3.17)
348
407
 
349
408
  > **0.3.17 changes no behaviour.** It only adjusts the wording of comments, test titles, a few
package/README.zh.md CHANGED
@@ -265,6 +265,20 @@ pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测
265
265
  > **发布包范围**:只含运行时代码与文档。维护者本地工具不在公开仓内,
266
266
  > 因此 `pnpm check` / `pnpm test` 在干净的克隆里即可通过。
267
267
 
268
+ ## 本地 Git 钩子(可选,需手动安装)
269
+
270
+ 仓库提供 `.githooks/pre-push`(推送前跑 `pnpm check`),但它**不会因为 clone 自动生效**——必须显式指向:
271
+
272
+ ```bash
273
+ git config core.hooksPath .githooks # 启用
274
+ git config --get core.hooksPath # 验证:应输出 .githooks
275
+ ```
276
+
277
+ 跳过仅限紧急情况:`git push --no-verify`。卸载:`git config --unset core.hooksPath`。
278
+
279
+ > 钩子是本地便利,不是信任边界:CI(`.github/workflows/ci.yml`)会跑 `pnpm check` /
280
+ > `pnpm check:strict` / `pnpm test`,未安装钩子的克隆同样受门禁约束。
281
+
268
282
  按**日志形态**给出的判定——本工具对每类缺陷该说什么,而不是对某个具体文件:
269
283
 
270
284
  | 日志形态 | 判定 | 触发的规则 |
@@ -295,6 +309,40 @@ MIT © OfferKuai Team
295
309
 
296
310
  ---
297
311
 
312
+ ## 🧱 架构 —— 契约层 + 平台适配器
313
+
314
+ 校验被拆成**平台无关的契约层**(`contract/`)与**平台适配器**(`adapters/dsh/`):不变量、判定模型与规则注册表共享;
315
+ 事件形状、格式版本(v0–v4)、zstd 帧与 surface 语义放在适配器里。**接入另一个宿主平台的意图是只写一个适配器、契约层不动**——分层已抽取并由机器强制;但适配器对接面(编排入口、与平台无关的违规 id)仍在收尾,在此之前接第二个平台还需一层薄 runner。
316
+
317
+ 边界由机器强制:`contract/` 不得出现平台词汇、不得依赖适配器或实现层(`pnpm check:strict`,CI 与可选 pre-push 钩子同跑)。
318
+ 公开 API、51 条规则与判定结果均不变。详见 [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)。
319
+
320
+ ## 🆕 0.3.18 – 0.3.21 · 支持 DSH 0.2.x(会话格式 v4)
321
+
322
+ **会话格式 v4**(`@deepseek-ai/dsh-session` 0.2.x)改为**按格式版本分派规则**,而不是放宽格式闸门:
323
+
324
+ - `tool/result` 按 v4 形状校验(`role: 'tool'`、无 `tool-result` 包裹块)
325
+ - `system/message` 接受 v4 的 `source.kind: 'system-prompt'`
326
+ - **v3 及更早的判据零改动**(408 份真实 v3 会话前后判定完全一致)
327
+ - 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
328
+
329
+ **新增规则(共 51 条):**
330
+
331
+ | 规则 | 判据 |
332
+ |---|---|
333
+ | `G4` | 未知历史事件可**声明式跳过**(`ignorable: true`;白名单可注入) |
334
+ | `S10` | `sourceEventSeqs` 元素:**解码后**必须为非负整数(存储层允许官方区间对) |
335
+ | `I2` | `seedLength` = **继承事件条数**(非字节);`parentSession` 存在且缺失/0 属合法 |
336
+ | `P5` | 两段 carrier 配对:第 2 段首元素 = 第 1 段 seq(读侧兼容早期写法) |
337
+ | `A1` | 「在位可还原」**只认结构化字段**(`archiveRef`/`archive`/`externalized.*`),不从自由文本推断 |
338
+
339
+ **大会话**:读取改为**按行解码**(不再整文件字符串化 ⇒ 约 536MB 以上不再抛 `ERR_STRING_TOO_LONG`);
340
+ 修复采用**流式帧重建** `.jsonl.zstd`(header 帧 + 正文分块多帧,逐帧 checksum + roundtrip 校验)。
341
+
342
+ **Windows**:`H2` 的 `header.cwd` 绝对路径判断改为**平台感知**(`win32` 与 `posix` 都认)。
343
+
344
+ **兼容性**:Node ≥ 22;`@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`;会话格式 v0–v4。
345
+
298
346
  ## ⚠️ 升级到 0.3.17 —— 必须知道的行为变更(0.3.12 → 0.3.17)
299
347
 
300
348
  > **0.3.17 不含行为变更。** 它只调整了注释、测试标题、少量诊断文案与 README 的措辞。
@@ -0,0 +1,135 @@
1
+ /**
2
+ * dsh-log-contract · adapters/dsh/archive.js
3
+ *
4
+ * DSH 专属:外置内容(归档)指针的读取与归档文件读取。
5
+ *
6
+ * 「在位可还原」的**判定核心**是平台无关的(目标存在 + 行存在 + 指纹匹配),
7
+ * 在 contract/invariants.js 的 verifyExternalizedPointers;本文件只提供 DSH 侧的
8
+ * 结构化指针字段、归档文件名解析与压缩归档的行读取。
9
+ */
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { verifyExternalizedPointers } from '../../contract/invariants.js';
13
+ import { decompressZstd } from '../../lib/log-reader.js';
14
+ import { ARCHIVE_POINTER_FIELDS, EXTERNALIZED_POINTER_FIELDS } from './vocab.js';
15
+
16
+ const ZSTD_MAGIC = 0xfd2fb528;
17
+
18
+ // 结构化指针字段名(定义在词表适配器;此处转发以保持归档适配器的导出面完整)。
19
+ export { ARCHIVE_POINTER_FIELDS, EXTERNALIZED_POINTER_FIELDS };
20
+
21
+ function isPlainRecord(value) {
22
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
23
+ }
24
+
25
+
26
+ function pushPointer(out, event, lineNo, field, ref, line, sha) {
27
+ if (typeof ref !== 'string' || ref === '') return;
28
+ out.push({
29
+ seq: Number.isSafeInteger(event.seq) ? event.seq : null,
30
+ lineNo: typeof lineNo === 'number' ? lineNo : null,
31
+ type: typeof event.type === 'string' ? event.type : null,
32
+ field,
33
+ ref,
34
+ archiveLine: Number.isSafeInteger(line) ? line : null,
35
+ sha256: typeof sha === 'string' && sha !== '' ? sha : null,
36
+ });
37
+ }
38
+
39
+ /**
40
+ * 从事件流提取**结构化**归档指针(纯函数,不读盘)。
41
+ *
42
+ * 入参既接受 `{event, lineNo}` 包装(`loadSessionLog().events` 的形状),也接受裸事件对象
43
+ * (手搓用例/第三方直接传事件数组)。
44
+ *
45
+ * @param {Array<{event:object,lineNo?:number}|object>} events
46
+ * @returns {Array<{seq:number|null,lineNo:number|null,type:string|null,field:string,ref:string,archiveLine:number|null,sha256:string|null}>}
47
+ */
48
+
49
+ export function collectArchivePointers(events) {
50
+ const out = [];
51
+ for (const item of events ?? []) {
52
+ const event = item && typeof item === 'object' && Object.hasOwn(item, 'event') ? item.event : item;
53
+ const lineNo = item && typeof item === 'object' ? item.lineNo : undefined;
54
+ if (!event || typeof event !== 'object') continue;
55
+ const data = event.data;
56
+ if (!isPlainRecord(data)) continue;
57
+ for (const field of ARCHIVE_POINTER_FIELDS) {
58
+ if (data[field] === undefined) continue;
59
+ pushPointer(out, event, lineNo, `data.${field}`, data[field], data.archiveLine, data.sha256 ?? data.archiveSha256);
60
+ }
61
+ const ext = data.externalized;
62
+ if (isPlainRecord(ext)) {
63
+ for (const field of EXTERNALIZED_POINTER_FIELDS) {
64
+ if (ext[field] === undefined) continue;
65
+ pushPointer(out, event, lineNo, `data.externalized.${field}`, ext[field], ext.archiveLine, ext.sha256 ?? ext.archiveSha256);
66
+ }
67
+ }
68
+ }
69
+ return out;
70
+ }
71
+
72
+ /** 归档引用 basename(用于在归档根里解析;不改变"在位"判据,只用于 relocated 判定)。 */
73
+
74
+ export function archiveBasename(ref) {
75
+ return typeof ref === 'string' ? path.basename(ref) : '';
76
+ }
77
+
78
+
79
+ /**
80
+ * 读归档文件的**行索引**(只保留请求的行;巨型归档不能整体 `toString`:
81
+ * >512MiB 明文会触发 V8 字符串上限——那是器具限制,不是内容缺失,必须避免把它误报成 A1)。
82
+ *
83
+ * @param {string} file 归档路径(.jsonl.zst 走多帧解压;.jsonl 直接 utf8)
84
+ * @param {Set<number>} [wantedLines] 需要的 1-based 行号
85
+ * @returns {{count:number, lineAt:(n:number)=>string}}
86
+ */
87
+ export function readArchiveIndex(file, wantedLines = new Set()) {
88
+ const buf = fs.readFileSync(file);
89
+ const isZstd = buf.length >= 4 && buf.readUInt32LE(0) === ZSTD_MAGIC;
90
+ const plain = isZstd ? decompressZstd(buf) : buf;
91
+ const lines = new Map();
92
+ let count = 0;
93
+ let start = 0;
94
+ for (let i = 0; i < plain.length; i++) {
95
+ if (plain[i] !== 0x0a) continue;
96
+ count++;
97
+ if (wantedLines.has(count)) lines.set(count, plain.subarray(start, i).toString('utf8'));
98
+ start = i + 1;
99
+ }
100
+ if (start < plain.length) {
101
+ count++;
102
+ if (wantedLines.has(count)) lines.set(count, plain.subarray(start).toString('utf8'));
103
+ }
104
+ return { count, lineAt: (n) => lines.get(n) ?? '' };
105
+ }
106
+
107
+
108
+ /** 读归档文件为明文行数组(.jsonl.zst 走多帧解压;.jsonl 直接 utf8)。 */
109
+ export function readArchiveLines(file) {
110
+ const buf = fs.readFileSync(file);
111
+ const isZstd = buf.length >= 4 && buf.readUInt32LE(0) === ZSTD_MAGIC;
112
+ const text = isZstd ? decompressZstd(buf).toString('utf8') : buf.toString('utf8');
113
+ const lines = text.split('\n');
114
+ if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
115
+ return lines;
116
+ }
117
+
118
+ /**
119
+ * 校验结构化指针能否在位还原(适配器默认注入压缩归档读取器)。
120
+ * @param {Array} pointers collectArchivePointers() 的结果
121
+ * @param {{archiveRoots?:string[], readLines?:Function}} [opts]
122
+ */
123
+ export function verifyArchivePointers(pointers, { archiveRoots = [], readLines } = {}) {
124
+ return verifyExternalizedPointers(pointers, { archiveRoots, readLines: readLines ?? readArchiveIndex });
125
+ }
126
+
127
+ /**
128
+ * A1 一站式:事件流 → 结构化指针 → 在位可还原结论。
129
+ * @param {Array<{event:object,lineNo?:number}>} events
130
+ * @param {{archiveRoots?:string[], readLines?:Function}} [opts]
131
+ */
132
+ export function archiveVerdict(events, { archiveRoots = [], readLines } = {}) {
133
+ const pointers = collectArchivePointers(events);
134
+ return verifyArchivePointers(pointers, { archiveRoots, readLines });
135
+ }