dsh-log-contract 0.3.21 → 0.3.23

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
@@ -35,7 +35,6 @@ plugin marker semantics).
35
35
  ---
36
36
 
37
37
  ## Where it sits in the business layer
38
-
39
38
  > **dsh-log-contract is the core capability component of [dsh-retrace](https://github.com/yamingmou/dsh-retrace)** (the business layer's "doctor" module): it **checks and repairs** session logs so every recall/edit/rollback lands on a legal log — pre-write validation (`prewrite`) rejects error-level violations **before** anything is written.
40
39
  >
41
40
  > **About `/compact` (stated honestly)**: what this tool guarantees is that **new writes** stop creating token-meter pairing debt — since two-segment atomic pairs (marker + paired segment) landed, new markers pass T1 by construction. **Legacy** (single-segment) markers are still **known design debt**: pre-write validation downgrades their T1 violation to a warning (`legacyMarkerKindOf` in `lib/prewrite.js`, which applies to **historical markers only**), so such sessions need **one check + cleanup before compaction** (`check` to locate → `fix --remove-markers`; the plugin side calls this "the doctor"). Otherwise the T1 self-check blocks `/compact`.
@@ -54,7 +53,6 @@ DSH (see the [dsh-retrace repository](https://github.com/yamingmou/dsh-retrace))
54
53
  ---
55
54
 
56
55
  ## Why it exists
57
-
58
56
  **"one log, two consumers, two verdicts"**: one log is consumed by both
59
57
  humans and automated programs. Humans tolerate format drift; programs depend on
60
58
  strict contracts. Once the format drifts, humans see nothing wrong while programs
@@ -69,7 +67,6 @@ line-by-line verification against the official Host source (each rule carries it
69
67
  ---
70
68
 
71
69
  ## Three-layer contract (the model)
72
-
73
70
  > 30+ rules across the layers below (`contracts` lists them all, each with its
74
71
  > official source reference).
75
72
 
@@ -86,29 +83,7 @@ line-by-line verification against the official Host source (each rule carries it
86
83
 
87
84
  ---
88
85
 
89
- ## ⚡ Case log — why "production-grade" is not a slogan
90
-
91
- Each entry below is a **real log-corruption shape** from production sessions — the cases that
92
- shaped this tool. Dates and shapes are real; session ids and file names are
93
- omitted.
94
-
95
- | # | Date | What happened | The rule / fix it produced |
96
- |---|---|---|---|
97
- | 1 | 2026-08-25 | A "restore hidden content" repair wrote a replace marker with **emptied `sourceEventSeqs`** → the session refused to load (`SessionPersistenceCorruptionError`); a second attempt changed the marker to **append** → the client engine crashed. Both were **violating writes that nothing caught**. | **S5** (sourceEventSeqs must cover shadowed nodes), **M1** (turn-null assistant/message can only be replace), pre-write validation |
98
- | 2 | 2026-08-27~28 | Interrupted/restarted turns replayed with a **stale in-memory cursor**, re-appending old seqs to the file tail (tail regression, duplicate batches); two writers interleaved → **file-physical order non-monotonic** (`734056 → 733539 → 735470`). Sessions failed to load with `seq gap`. | **S9** (physical-order monotonic), fix `--tail-renumber` |
99
- | 3 | 2026-08-27~28 | **Fork-boundary orphan splice**: the fork's "remove parent's pending prompt" splice assumed the parent's inbox; the child's seed-relative replay has an empty inbox → `resume failed: invalid persisted inbox splice`. | **I1** (inbox seed-relative replay), fix `--neutralize-orphan` |
100
- | 4 | 2026-08-28 | An oversized session (**1,052,557 tokens** vs the 1M window) could neither continue nor `/compact`; the trim budget estimator underpriced CJK by ~3.7×. | T1 (token-meter pairing) for compactability, `fix --trim-budget` guidance |
101
- | 5 | 2026-08-29 | **W1/W2 wire violations**: markers shadowed an assistant with tool_calls but left the tool results dangling → strict endpoints (`INVALID_REQUEST`) reject the session's request stream. | **W1 / W2** (wire message flow) |
102
- | 6 | 2026-08-30 | A single **turn-null marker** made the token-meter listener throw on **every** appended event (`consumedEvents` never advanced → full-prefix re-fold per event) → **30s / 10,008 log lines**, host event loop crushed, all sessions locked. Same session also had a **cross-step sourceEventSeqs** (steps 7/8/9 mixed in one assistant message) — offline checks were green, the live meter crashed. | **T1** (turn/step pairing), **T2** (cross-step source refs), `fix --neutralize`, `fix --clip-crossstep` |
103
-
104
- > **Takeaway**: these rules are not synthetic theory — each one is pinned by a
105
- > regression test that reproduces the corrupt shape it guards against. That is what
106
- > "production-grade" means here.
107
-
108
- ---
109
-
110
86
  ## Version support (host / session format)
111
-
112
87
  **Tested baseline (the versions this rule set was verified against)**:
113
88
 
114
89
  | Item | Baseline | Note |
@@ -135,8 +110,77 @@ Both the human-readable `check` output and the `--json` `support` field carry th
135
110
  version support: host @deepseek-ai/dsh-session@0.1.5-rc.1 (baseline 0.1.5-rc.1) | file format v3 (header, baseline)
136
111
  ```
137
112
 
138
- ## Installation
113
+ ## 🧱 Architecture — contract layer + platform adapter
114
+ Validation is split into a **platform-agnostic contract layer** (`contract/`) and a **platform adapter**
115
+ (`adapters/dsh/`): invariants, verdict model and the rule registry are shared; event shapes, format
116
+ versions (v0–v4), zstd framing and surface semantics live in the adapter. Adding another host platform is intended to
117
+ mean writing one adapter; the split is extracted and enforced today, while the adapter-facing API
118
+ (orchestration entry, id-neutral violations) is still being finalized.
139
119
 
120
+ The boundary is machine-enforced: `contract/` may contain no platform vocabulary and no adapter/implementation
121
+ imports (`pnpm check:strict`, also in CI and the optional pre-push hook). The public API, rule set (51 rules)
122
+ and verdicts are unchanged.
123
+
124
+ **Current status: partial.** The split is extracted and machine-enforced, but a second adapter is **not yet
125
+ drop-in**: the contract layer still emits platform rule ids for some invariants, and there is no
126
+ platform-neutral orchestration entry yet — a second adapter today would also need a thin runner.
127
+ See "Known gaps" in the changelog for the tracked follow-up list. See [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md).
128
+
129
+ ## 🆕 0.3.18 – 0.3.21 · DSH 0.2.x (session format v4) support
130
+ **Session format v4** (`@deepseek-ai/dsh-session` 0.2.x) is now validated by format-version dispatch
131
+ rather than by relaxing the format gate:
132
+
133
+ - `tool/result` is validated with the v4 shape (`role: 'tool'`, no `tool-result` wrapper block)
134
+ - `system/message` accepts v4's `source.kind: 'system-prompt'`
135
+ - validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
136
+ - the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
137
+
138
+ **New rules (51 total):**
139
+
140
+ | Rule | Checks |
141
+ |---|---|
142
+ | `G4` | unknown historical events may be declaratively skipped (`ignorable: true`; allow-list injectable) |
143
+ | `S10` | `sourceEventSeqs` elements: non-negative integers after decoding (official interval pairs allowed in storage) |
144
+ | `I2` | `seedLength` means *number of inherited events* (not bytes); `parentSession` + missing/0 is legal |
145
+ | `P5` | two-segment carrier pairing: 2nd segment's first seq == 1st segment seq (read side accepts the legacy order) |
146
+ | `A1` | "in-place restorable" is judged from structured fields only (`archiveRef` / `archive` / `externalized.*`) — never from free text |
147
+
148
+ **Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~536 MB),
149
+ and repair rebuilds `.jsonl.zstd` with streaming frames (header frame + chunked body frames, per-frame checksum + round-trip).
150
+
151
+ **Windows:** the `header.cwd` absolute-path check in `H2` is platform-aware (`win32` and `posix` both accepted).
152
+
153
+ **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.
154
+
155
+ ## Case log — why "production-grade" is not a slogan
156
+ Each entry below is a **real log-corruption shape** from production sessions — the cases that
157
+ shaped this tool. Dates and shapes are real; session ids and file names are
158
+ omitted.
159
+
160
+ | # | Date | What happened | The rule / fix it produced |
161
+ |---|---|---|---|
162
+ | 1 | 2026-08-25 | A "restore hidden content" repair wrote a replace marker with **emptied `sourceEventSeqs`** → the session refused to load (`SessionPersistenceCorruptionError`); a second attempt changed the marker to **append** → the client engine crashed. Both were **violating writes that nothing caught**. | **S5** (sourceEventSeqs must cover shadowed nodes), **M1** (turn-null assistant/message can only be replace), pre-write validation |
163
+ | 2 | 2026-08-27~28 | Interrupted/restarted turns replayed with a **stale in-memory cursor**, re-appending old seqs to the file tail (tail regression, duplicate batches); two writers interleaved → **file-physical order non-monotonic** (`734056 → 733539 → 735470`). Sessions failed to load with `seq gap`. | **S9** (physical-order monotonic), fix `--tail-renumber` |
164
+ | 3 | 2026-08-27~28 | **Fork-boundary orphan splice**: the fork's "remove parent's pending prompt" splice assumed the parent's inbox; the child's seed-relative replay has an empty inbox → `resume failed: invalid persisted inbox splice`. | **I1** (inbox seed-relative replay), fix `--neutralize-orphan` |
165
+ | 4 | 2026-08-28 | An oversized session (**1,052,557 tokens** vs the 1M window) could neither continue nor `/compact`; the trim budget estimator underpriced CJK by ~3.7×. | T1 (token-meter pairing) for compactability, `fix --trim-budget` guidance |
166
+ | 5 | 2026-08-29 | **W1/W2 wire violations**: markers shadowed an assistant with tool_calls but left the tool results dangling → strict endpoints (`INVALID_REQUEST`) reject the session's request stream. | **W1 / W2** (wire message flow) |
167
+ | 6 | 2026-08-30 | A single **turn-null marker** made the token-meter listener throw on **every** appended event (`consumedEvents` never advanced → full-prefix re-fold per event) → **30s / 10,008 log lines**, host event loop crushed, all sessions locked. Same session also had a **cross-step sourceEventSeqs** (steps 7/8/9 mixed in one assistant message) — offline checks were green, the live meter crashed. | **T1** (turn/step pairing), **T2** (cross-step source refs), `fix --neutralize`, `fix --clip-crossstep` |
168
+ | 7 | 2026-08-31 | A log was compressed as a **single zstd frame** (or the header did not form its own frame) → different readers disagreed on record boundaries ⇒ **Z4/Z5** frame-shape rules (first frame = exactly one header line; body framed) |
169
+ | 8 | 2026-08-31 | A log whose **last zstd frame was torn** mid-write could not be loaded at all, with no diagnosis ⇒ **Z1** + explicit "torn tail / in-flight write" reporting |
170
+ | 9 | 2026-09-09 | On **session format v4**, `tool/result` uses `role: 'tool'` and `system/message` carries a `system-prompt` source → v3-shaped checks produced **thousands of false errors on healthy v4 logs** ⇒ version dispatch + **E6/E9** v4 semantics |
171
+ | 10 | 2026-09-17 | On **Windows**, `header.cwd` was judged with POSIX-only rules → **every** session flagged by **H2** ⇒ platform-aware absolute-path check |
172
+ | 11 | 2026-10-20 | A **> 500 MB session** crashed the reader (`ERR_STRING_TOO_LONG`) and repair built the whole text in memory ⇒ line-wise decode + streaming frame rebuild |
173
+ | 12 | 2026-10-20 | Two-segment carrier references were written with the audit segment first while an earlier convention started at the range start → readers reported hundreds of **false orphan carriers** ⇒ **P5** write-side pairing + tolerant read-side |
174
+ | 13 | 2026-10-20 | `seedLength` was read as a **byte size** by some consumers (it is the number of inherited events), and `parentSession` with missing/0 was treated as corruption ⇒ **I2** semantics pinned |
175
+ | 14 | 2026-10-20 | An **unknown but explicitly ignorable** event type blocked an entire migration ⇒ **G4** declarative skip + allow-list |
176
+
177
+ > **Takeaway**: these rules are not synthetic theory — each one is pinned by a
178
+ > regression test that reproduces the corrupt shape it guards against. That is what
179
+ > "production-grade" means here.
180
+
181
+ ---
182
+
183
+ ## Installation
140
184
  ```bash
141
185
  pnpm add -D dsh-log-contract # or npm install
142
186
  pnpm dlx dsh-log-contract --help
@@ -157,7 +201,6 @@ with the Harness read path).
157
201
  ---
158
202
 
159
203
  ## CLI
160
-
161
204
  ### 1. Offline health check
162
205
 
163
206
  ```bash
@@ -262,7 +305,6 @@ are flagged in `check`.
262
305
  ---
263
306
 
264
307
  ## Node API (embed pre-write validation in your script)
265
-
266
308
  ```js
267
309
  import { loadSessionLog, validateSessionLog, createPreWriter } from 'dsh-log-contract';
268
310
 
@@ -289,7 +331,6 @@ if (!verdict.ok) {
289
331
  ---
290
332
 
291
333
  ## Tests
292
-
293
334
  ```bash
294
335
  pnpm check && pnpm test # syntax check + contract-doc drift gate + all unit tests
295
336
  ```
@@ -302,6 +343,20 @@ pnpm check && pnpm test # syntax check + contract-doc drift gate + all unit t
302
343
  > Local maintainer tooling is not part of the public repository, so `pnpm check` and `pnpm test`
303
344
  > work from a clean clone.
304
345
 
346
+ ## Local git hooks (opt-in)
347
+ The repository ships `.githooks/pre-push` (runs `pnpm check` before pushing), but it is
348
+ **not active automatically on clone** — point Git at it explicitly:
349
+
350
+ ```bash
351
+ git config core.hooksPath .githooks # enable
352
+ git config --get core.hooksPath # verify: should print .githooks
353
+ ```
354
+
355
+ Skip only for emergencies: `git push --no-verify`. Uninstall: `git config --unset core.hooksPath`.
356
+
357
+ > Hooks are local convenience, not a trust boundary: CI (`.github/workflows/ci.yml`) runs
358
+ > `pnpm check` / `pnpm check:strict` / `pnpm test`, so clones without hooks stay gated.
359
+
305
360
  Verdict by **log shape** — what the tool must say about each defect class, not about
306
361
  any particular file:
307
362
 
@@ -320,58 +375,16 @@ boundary note in [docs/CONTRACTS.md](docs/CONTRACTS.md).
320
375
 
321
376
  ---
322
377
 
323
- ## Roadmap
324
-
325
- - [x] **Phase 1 (0.1.0)**: CLI offline check + pre-write validation + contract catalog
326
- - [x] **Phase 1.5 (0.2.0)**: `fix` subcommand (strict seq scan + W1/W2 wire checks +
327
- marker removal with renumbering + official frame rebuild); CI integration
328
- (`dsh-log-contract check` as a scheduled guard over the Harness session dir)
329
- - [x] **0.3.x (2026-08-30 case hardening)**: T1 token-meter pairing → 0.3.1 W1/W2
330
- fold-position fix → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize` (in-place
331
- turn-null neutralization) → 0.3.4 `fix --clip-crossstep` (cross-step clipping) →
332
- 0.3.5 **T2/S9/I1 rules** (cross-step source refs / physical order / inbox replay)
333
- - [x] **0.3.6 → 0.3.15**: per-version rule routing for v0–v3 (T3/T4/T5, L3–L5, E8/E9/E10),
334
- exit codes `3`/`4` for the host-capability and migration gates, and a version-support
335
- report that says what was *not* verified (see [CHANGELOG.md](CHANGELOG.md))
336
- - [ ] Phase 2: runtime guard (subscribe to the session append stream, validate live,
337
- mark violations as `dsh/contract-violation`, policy configurable alert/block) —
338
- DSH plugin form
339
- - [ ] Phase 3: link with dsh-turn-guard / dsh-retrace timeline
340
-
341
- ## License
342
-
343
- MIT © OfferKuai Team
344
-
345
- ---
346
-
347
- ## 🆕 0.3.18 – 0.3.21 · DSH 0.2.x (session format v4) support
348
-
349
- **Session format v4** (`@deepseek-ai/dsh-session` 0.2.x) is now validated by format-version dispatch
350
- rather than by relaxing the format gate:
351
-
352
- - `tool/result` is validated with the v4 shape (`role: 'tool'`, no `tool-result` wrapper block)
353
- - `system/message` accepts v4's `source.kind: 'system-prompt'`
354
- - validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
355
- - the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
356
-
357
- **New rules (51 total):**
378
+ ## ⚠️ Upgrading — behaviour notes (0.3.12 → 0.3.23)
358
379
 
359
- | Rule | Checks |
360
- |---|---|
361
- | `G4` | unknown historical events may be declaratively skipped (`ignorable: true`; allow-list injectable) |
362
- | `S10` | `sourceEventSeqs` elements: non-negative integers after decoding (official interval pairs allowed in storage) |
363
- | `I2` | `seedLength` means *number of inherited events* (not bytes); `parentSession` + missing/0 is legal |
364
- | `P5` | two-segment carrier pairing: 2nd segment's first seq == 1st segment seq (read side accepts the legacy order) |
365
- | `A1` | "in-place restorable" is judged from structured fields only (`archiveRef` / `archive` / `externalized.*`) — never from free text |
380
+ ### 0.3.18 → 0.3.23 in one paragraph
366
381
 
367
- **Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~536 MB),
368
- and repair rebuilds `.jsonl.zstd` with streaming frames (header frame + chunked body frames, per-frame checksum + round-trip).
369
-
370
- **Windows:** the `header.cwd` absolute-path check in `H2` is platform-aware (`win32` and `posix` both accepted).
371
-
372
- **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.
373
-
374
- ## ⚠️ Upgrading to 0.3.17 — behaviour changes you must know (0.3.12 → 0.3.17)
382
+ Session format **v4** (host `dsh-session` 0.2.x) is supported by version dispatch (`tool/result` role,
383
+ `system/message` source); five rules were added (`G4` unknown-but-ignorable events, `S10` reference element
384
+ types, `I2` `seedLength` semantics, `P5` carrier pairing, `A1` structured-only in-place restorability);
385
+ large sessions (> 500 MB) are read line-wise and repaired with streaming frames; the Windows absolute-path
386
+ check for `H2` is platform-aware. 0.3.22 adds a `contract/` + `adapters/dsh/` layering (behaviour unchanged;
387
+ still **partial** — see the changelog's known-gap list). Verdicts, exit codes and `--json` fields are unchanged.
375
388
 
376
389
  > **0.3.17 changes no behaviour.** It only adjusts the wording of comments, test titles, a few
377
390
  > diagnostic strings and the README. Every verdict, exit code and `--json`
@@ -406,3 +419,25 @@ the migration dimension is only partially covered.
406
419
  The rule set is **not** the official upgrade chain's acceptance condition. `assessmentScope=partial` means
407
420
  "the part this tool looked at is clean" — it does **not** mean the official upgrade will accept the file.
408
421
  Read `coverage.uncovered` for the known gaps.
422
+
423
+ ## Roadmap
424
+ - [x] **Phase 1 (0.1.0)**: CLI offline check + pre-write validation + contract catalog
425
+ - [x] **Phase 1.5 (0.2.0)**: `fix` subcommand (strict seq scan + W1/W2 wire checks +
426
+ marker removal with renumbering + official frame rebuild); CI integration
427
+ (`dsh-log-contract check` as a scheduled guard over the Harness session dir)
428
+ - [x] **0.3.x (2026-08-30 case hardening)**: T1 token-meter pairing → 0.3.1 W1/W2
429
+ fold-position fix → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize` (in-place
430
+ turn-null neutralization) → 0.3.4 `fix --clip-crossstep` (cross-step clipping) →
431
+ 0.3.5 **T2/S9/I1 rules** (cross-step source refs / physical order / inbox replay)
432
+ - [x] **0.3.6 → 0.3.15**: per-version rule routing for v0–v3 (T3/T4/T5, L3–L5, E8/E9/E10),
433
+ exit codes `3`/`4` for the host-capability and migration gates, and a version-support
434
+ report that says what was *not* verified (see [CHANGELOG.md](CHANGELOG.md))
435
+ - [ ] Phase 2: runtime guard (subscribe to the session append stream, validate live,
436
+ mark violations as `dsh/contract-violation`, policy configurable alert/block) —
437
+ DSH plugin form
438
+ - [ ] Phase 3: link with dsh-turn-guard / dsh-retrace timeline
439
+
440
+ ## License
441
+ MIT © OfferKuai Team
442
+
443
+ ---
package/README.zh.md CHANGED
@@ -29,7 +29,6 @@
29
29
  ---
30
30
 
31
31
  ## 它在业务层里的位置
32
-
33
32
  > **dsh-log-contract 是 [dsh-retrace](https://github.com/yamingmou/dsh-retrace) 的核心能力组件**(业务层的「医生」模块):负责会话日志的**体检与修复**——让每一次撤回/编辑/回退都落在合法日志上,写前校验(`prewrite`)会把 error 级违约**拦在落盘之前**。
34
33
  >
35
34
  > **关于 `/compact`(如实表述)**:本工具保证的是**新写入**不再制造 token-meter 配对债——自两段原子成对(marker + 配对段)起,新 marker 天然通过 T1。**历史**(单段)marker 仍属**已知设计债**:写前校验对它的 T1 违规降级为 warning(`lib/prewrite.js` 的 `legacyMarkerKindOf` 白名单,**只适用于历史 marker**),因此这类会话**压缩(`/compact`)前需要先跑一次体检 + 清理**(`check` 定位 → `fix --remove-markers`;插件侧即「医生」),否则 T1 自检会拦住压缩。
@@ -47,7 +46,6 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
47
46
  ---
48
47
 
49
48
  ## 为什么需要它
50
-
51
49
  **「one log, two consumers, two verdicts」**:一条日志同时被人类与自动化程序消费,人眼容忍格式微调,程序解析依赖严格契约;格式一旦漂移,人看不出问题,程序直接崩溃或误报。
52
50
 
53
51
  **这里大多数规则都来自会话日志中实际出现过的损坏形态**——见下方 [⚡ 案例记录](#-案例记录)。由这些案例派生的用例都有回归测试钉住:损坏的日志形态本工具必须报出,修复后的形态必须通过。其余规则来自对官方宿主源码的逐行核对(每条规则都带 `source`)。
@@ -55,7 +53,6 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
55
53
  ---
56
54
 
57
55
  ## 三层契约(判定模型)
58
-
59
56
  > 30+ 条规则,覆盖以下三层(`contracts` 列出全部,每条附官方源码出处)。
60
57
 
61
58
  | 层 | 规则 | 守护什么 |
@@ -69,25 +66,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
69
66
 
70
67
  ---
71
68
 
72
- ## ⚡ 案例记录 ——「生产级保证」不是口号
73
-
74
- 下面每一条都来自**生产会话中实际出现的日志损坏形态**——正是这些案例促成了本工具。日期与形态真实,会话 id 与文件名省略。
75
-
76
- | # | 日期 | 发生了什么 | 产出的规则/修复 |
77
- |---|---|---|---|
78
- | 1 | 2026-08-25 | 一次「恢复被隐藏内容」的修复写了**清空 `sourceEventSeqs`** 的 replace marker → 会话加载被拒(`SessionPersistenceCorruptionError`);第二次尝试把 marker 改成 **append** → 客户端引擎崩溃。两次都是**违约写入没被拦**。 | **S5**(sourceEventSeqs 必须覆盖被替换节点)、**M1**(turn-null 的 assistant/message 只能 replace)、写前校验 |
79
- | 2 | 2026-08-27~28 | 中断/暂停的轮次恢复时按**过期内存光标**重放,把旧 seq 追加到文件尾(尾部回归、重复批次);两个写入者交织 → **文件物理序非单调**(`734056 → 733539 → 735470`)。会话 `seq gap` 加载失败。 | **S9**(物理序单调)、fix `--tail-renumber` |
80
- | 3 | 2026-08-27~28 | **fork 边界孤儿 spliced**:fork 的「移除父待处理提示词」splice 假设父会话 inbox;子会话 seed 相对重放里 inbox 为空 → `resume failed: invalid persisted inbox splice`。 | **I1**(inbox seed 相对重放)、fix `--neutralize-orphan` |
81
- | 4 | 2026-08-28 | 超限会话(**1,052,557 tokens** vs 1M 窗口)既无法继续也无法 `/compact`;裁剪预算估算对中文低估 ~3.7×。 | T1(token-meter 配对,保障可压缩)、`fix --trim-budget` 预算指引 |
82
- | 5 | 2026-08-29 | **W1/W2 wire 违规**:marker 遮蔽了带 tool_calls 的 assistant 但漏盖 tool 结果 → 悬空 tool,严格端点 `INVALID_REQUEST` 拒绝请求流。 | **W1 / W2**(wire 消息流) |
83
- | 6 | 2026-08-30 | 单个 **turn-null marker** 让 token-meter 监听器在**每条**追加事件上抛错(`consumedEvents` 不前进 → 每事件全前缀重折)→ **30 秒 / 10,008 行日志**、host 事件循环被压垮、全部会话锁定。同会话还有**跨 step sourceEventSeqs**(step 7/8/9 混进一条 assistant 消息)——离线 check 全绿、实机 meter 崩溃。 | **T1**(turn/step 配对)、**T2**(跨 step 源引用)、`fix --neutralize`、`fix --clip-crossstep` |
84
-
85
- > **结论**:这些规则不是合成理论——每一条都有回归测试复现它守护的那种损坏形态。这就是这里「生产级」的含义。
86
-
87
- ---
88
-
89
69
  ## 版本支持(宿主 / 会话格式)
90
-
91
70
  **测试基线(本规则集验证过的版本)**:
92
71
 
93
72
  | 项 | 基线 | 说明 |
@@ -115,8 +94,64 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
115
94
  测试基线:@deepseek-ai/dsh-session@0.1.5-rc.1 | 会话格式 v3(已知 0/1/2/3;peer ^0.1.0-rc.7 || ^0.1.5-rc.1)
116
95
  ```
117
96
 
118
- ## 安装
97
+ ## 🧱 架构 —— 契约层 + 平台适配器
98
+ 校验被拆成**平台无关的契约层**(`contract/`)与**平台适配器**(`adapters/dsh/`):不变量、判定模型与规则注册表共享;
99
+ 事件形状、格式版本(v0–v4)、zstd 帧与 surface 语义放在适配器里。**接入另一个宿主平台的意图是只写一个适配器、契约层不动**——分层已抽取并由机器强制;但适配器对接面(编排入口、与平台无关的违规 id)仍在收尾,在此之前接第二个平台还需一层薄 runner。
100
+
101
+ 边界由机器强制:`contract/` 不得出现平台词汇、不得依赖适配器或实现层(`pnpm check:strict`,CI 与可选 pre-push 钩子同跑)。
102
+ 公开 API、51 条规则与判定结果均不变。详见 [docs/ARCHITECTURE.md](docs/ARCHITECTURE.md)。
103
+
104
+ ## 🆕 0.3.18 – 0.3.21 · 支持 DSH 0.2.x(会话格式 v4)
105
+ **会话格式 v4**(`@deepseek-ai/dsh-session` 0.2.x)改为**按格式版本分派规则**,而不是放宽格式闸门:
106
+
107
+ - `tool/result` 按 v4 形状校验(`role: 'tool'`、无 `tool-result` 包裹块)
108
+ - `system/message` 接受 v4 的 `source.kind: 'system-prompt'`
109
+ - **v3 及更早的判据零改动**(408 份真实 v3 会话前后判定完全一致)
110
+ - 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
111
+
112
+ **新增规则(共 51 条):**
113
+
114
+ | 规则 | 判据 |
115
+ |---|---|
116
+ | `G4` | 未知历史事件可**声明式跳过**(`ignorable: true`;白名单可注入) |
117
+ | `S10` | `sourceEventSeqs` 元素:**解码后**必须为非负整数(存储层允许官方区间对) |
118
+ | `I2` | `seedLength` = **继承事件条数**(非字节);`parentSession` 存在且缺失/0 属合法 |
119
+ | `P5` | 两段 carrier 配对:第 2 段首元素 = 第 1 段 seq(读侧兼容早期写法) |
120
+ | `A1` | 「在位可还原」**只认结构化字段**(`archiveRef`/`archive`/`externalized.*`),不从自由文本推断 |
121
+
122
+ **大会话**:读取改为**按行解码**(不再整文件字符串化 ⇒ 约 536MB 以上不再抛 `ERR_STRING_TOO_LONG`);
123
+ 修复采用**流式帧重建** `.jsonl.zstd`(header 帧 + 正文分块多帧,逐帧 checksum + roundtrip 校验)。
124
+
125
+ **Windows**:`H2` 的 `header.cwd` 绝对路径判断改为**平台感知**(`win32` 与 `posix` 都认)。
126
+
127
+ **兼容性**:Node ≥ 22;`@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`;会话格式 v0–v4。
128
+
129
+ ## 案例记录 ——「生产级保证」不是口号
130
+ 下面每一条都来自**生产会话中实际出现的日志损坏形态**——正是这些案例促成了本工具。日期与形态真实,会话 id 与文件名省略。
131
+
132
+ | # | 日期 | 发生了什么 | 产出的规则/修复 |
133
+ |---|---|---|---|
134
+ | 1 | 2026-08-25 | 一次「恢复被隐藏内容」的修复写了**清空 `sourceEventSeqs`** 的 replace marker → 会话加载被拒(`SessionPersistenceCorruptionError`);第二次尝试把 marker 改成 **append** → 客户端引擎崩溃。两次都是**违约写入没被拦**。 | **S5**(sourceEventSeqs 必须覆盖被替换节点)、**M1**(turn-null 的 assistant/message 只能 replace)、写前校验 |
135
+ | 2 | 2026-08-27~28 | 中断/暂停的轮次恢复时按**过期内存光标**重放,把旧 seq 追加到文件尾(尾部回归、重复批次);两个写入者交织 → **文件物理序非单调**(`734056 → 733539 → 735470`)。会话 `seq gap` 加载失败。 | **S9**(物理序单调)、fix `--tail-renumber` |
136
+ | 3 | 2026-08-27~28 | **fork 边界孤儿 spliced**:fork 的「移除父待处理提示词」splice 假设父会话 inbox;子会话 seed 相对重放里 inbox 为空 → `resume failed: invalid persisted inbox splice`。 | **I1**(inbox seed 相对重放)、fix `--neutralize-orphan` |
137
+ | 4 | 2026-08-28 | 超限会话(**1,052,557 tokens** vs 1M 窗口)既无法继续也无法 `/compact`;裁剪预算估算对中文低估 ~3.7×。 | T1(token-meter 配对,保障可压缩)、`fix --trim-budget` 预算指引 |
138
+ | 5 | 2026-08-29 | **W1/W2 wire 违规**:marker 遮蔽了带 tool_calls 的 assistant 但漏盖 tool 结果 → 悬空 tool,严格端点 `INVALID_REQUEST` 拒绝请求流。 | **W1 / W2**(wire 消息流) |
139
+ | 6 | 2026-08-30 | 单个 **turn-null marker** 让 token-meter 监听器在**每条**追加事件上抛错(`consumedEvents` 不前进 → 每事件全前缀重折)→ **30 秒 / 10,008 行日志**、host 事件循环被压垮、全部会话锁定。同会话还有**跨 step sourceEventSeqs**(step 7/8/9 混进一条 assistant 消息)——离线 check 全绿、实机 meter 崩溃。 | **T1**(turn/step 配对)、**T2**(跨 step 源引用)、`fix --neutralize`、`fix --clip-crossstep` |
140
+
141
+ | 7 | 2026-08-31 | 日志被压成**单个 zstd 帧**(或 header 未单独成帧)→ 不同读取器对记录边界理解不一致 ⇒ **Z4/Z5** 帧形状规则(首帧必须恰好一行 header;正文分帧) |
142
+ | 8 | 2026-08-31 | **尾帧在写入中被撕裂**的日志完全无法加载、且没有诊断 ⇒ **Z1** + 明确报「尾帧撕裂 / 写入中」 |
143
+ | 9 | 2026-09-09 | **会话格式 v4** 下 `tool/result` 改用 `role:'tool'`、`system/message` 带 `system-prompt` 来源 → 按 v3 语义的检查在**健康 v4 日志**上产出**数千条误报** ⇒ 版本分派 + **E6/E9** v4 语义 |
144
+ | 10 | 2026-09-17 | **Windows** 上 `header.cwd` 用 POSIX 规则判定 → **所有**会话被 **H2** 误报 ⇒ 平台感知的绝对路径判定 |
145
+ | 11 | 2026-10-20 | **超过 500MB 的会话**让读取器崩溃(`ERR_STRING_TOO_LONG`),修复时又把全文拼进内存 ⇒ 按行解码 + 流式帧重建 |
146
+ | 12 | 2026-10-20 | 两段式载体引用有的把「审计段」写在前面、早期约定从区间起点开始 → 读取侧报出**数百个假孤儿载体** ⇒ **P5** 写侧成对 + 读侧容错 |
147
+ | 13 | 2026-10-20 | `seedLength` 被部分消费方当作**字节数**(其语义是「继承事件条数」),且 `parentSession` 配缺失/0 被当成损坏 ⇒ **I2** 语义钉死 |
148
+ | 14 | 2026-10-20 | 一种**未知但显式可忽略**的事件类型让整条迁移卡死 ⇒ **G4** 声明式跳过 + 白名单 |
149
+
150
+ > **结论**:这些规则不是合成理论——每一条都有回归测试复现它守护的那种损坏形态。这就是这里「生产级」的含义。
151
+
152
+ ---
119
153
 
154
+ ## 安装
120
155
  ```bash
121
156
  pnpm add -D dsh-log-contract # 或 npm install
122
157
  pnpm dlx dsh-log-contract --help
@@ -134,7 +169,6 @@ pnpm dlx dsh-log-contract --help
134
169
  ---
135
170
 
136
171
  ## CLI 用法
137
-
138
172
  ### 1. 离线体检
139
173
 
140
174
  ```bash
@@ -228,7 +262,6 @@ dsh-log-contract audit-report <session-log>
228
262
  ---
229
263
 
230
264
  ## Node API(写前校验嵌入你的脚本)
231
-
232
265
  ```js
233
266
  import { loadSessionLog, validateSessionLog, createPreWriter } from 'dsh-log-contract';
234
267
 
@@ -255,7 +288,6 @@ if (!verdict.ok) {
255
288
  ---
256
289
 
257
290
  ## 测试
258
-
259
291
  ```bash
260
292
  pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测(含案例回归用例)
261
293
  ```
@@ -265,6 +297,19 @@ pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测
265
297
  > **发布包范围**:只含运行时代码与文档。维护者本地工具不在公开仓内,
266
298
  > 因此 `pnpm check` / `pnpm test` 在干净的克隆里即可通过。
267
299
 
300
+ ## 本地 Git 钩子(可选,需手动安装)
301
+ 仓库提供 `.githooks/pre-push`(推送前跑 `pnpm check`),但它**不会因为 clone 自动生效**——必须显式指向:
302
+
303
+ ```bash
304
+ git config core.hooksPath .githooks # 启用
305
+ git config --get core.hooksPath # 验证:应输出 .githooks
306
+ ```
307
+
308
+ 跳过仅限紧急情况:`git push --no-verify`。卸载:`git config --unset core.hooksPath`。
309
+
310
+ > 钩子是本地便利,不是信任边界:CI(`.github/workflows/ci.yml`)会跑 `pnpm check` /
311
+ > `pnpm check:strict` / `pnpm test`,未安装钩子的克隆同样受门禁约束。
312
+
268
313
  按**日志形态**给出的判定——本工具对每类缺陷该说什么,而不是对某个具体文件:
269
314
 
270
315
  | 日志形态 | 判定 | 触发的规则 |
@@ -280,48 +325,14 @@ pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测
280
325
 
281
326
  ---
282
327
 
283
- ## Roadmap
284
-
285
- - [x] **Phase 1(0.1.0)**:CLI 离线体检 + 写前校验 + 契约目录
286
- - [x] **Phase 1.5(0.2.0)**:`fix` 子命令(严格 seq 扫描 + W1/W2 wire 检查 + 移除 marker 重编号 + 官方帧格式重建);CI 集成(`dsh-log-contract check` 作为 Harness 会话目录的定时守护)
287
- - [x] **0.3.x(2026-08-30 案例固化)**:T1 token-meter 配对 → 0.3.1 W1/W2 折叠位置修复 → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize`(turn-null marker 原地中和)→ 0.3.4 `fix --clip-crossstep`(跨 step 引用裁剪)→ 0.3.5 **T2/S9/I1 规则**(跨 step 源引用 / 物理序单调 / inbox 重放)
288
- - [x] **0.3.6 → 0.3.15**:按被检文件版本择路的 v0–v3 规则(T3/T4/T5、L3–L5、E8/E9/E10)、宿主能力与迁移预检的退出码 `3`/`4`,以及如实报告"哪些版本**未**验证"的版本支持说明(详见 [CHANGELOG.md](CHANGELOG.md))
289
- - [ ] Phase 2:运行时守护(订阅 session append 事件流实时校验,断裂即标记 `dsh/contract-violation` 事件,策略可配 告警/拦截)——DSH 插件形态
290
- - [ ] Phase 3:与 dsh-turn-guard / dsh-retrace 时间线联动
291
-
292
- ## 许可
293
-
294
- MIT © OfferKuai Team
295
-
296
- ---
297
-
298
- ## 🆕 0.3.18 – 0.3.21 · 支持 DSH 0.2.x(会话格式 v4)
299
-
300
- **会话格式 v4**(`@deepseek-ai/dsh-session` 0.2.x)改为**按格式版本分派规则**,而不是放宽格式闸门:
301
-
302
- - `tool/result` 按 v4 形状校验(`role: 'tool'`、无 `tool-result` 包裹块)
303
- - `system/message` 接受 v4 的 `source.kind: 'system-prompt'`
304
- - **v3 及更早的判据零改动**(408 份真实 v3 会话前后判定完全一致)
305
- - 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
306
-
307
- **新增规则(共 51 条):**
308
-
309
- | 规则 | 判据 |
310
- |---|---|
311
- | `G4` | 未知历史事件可**声明式跳过**(`ignorable: true`;白名单可注入) |
312
- | `S10` | `sourceEventSeqs` 元素:**解码后**必须为非负整数(存储层允许官方区间对) |
313
- | `I2` | `seedLength` = **继承事件条数**(非字节);`parentSession` 存在且缺失/0 属合法 |
314
- | `P5` | 两段 carrier 配对:第 2 段首元素 = 第 1 段 seq(读侧兼容早期写法) |
315
- | `A1` | 「在位可还原」**只认结构化字段**(`archiveRef`/`archive`/`externalized.*`),不从自由文本推断 |
328
+ ## ⚠️ 升级说明(0.3.12 → 0.3.23)
316
329
 
317
- **大会话**:读取改为**按行解码**(不再整文件字符串化 ⇒ 约 536MB 以上不再抛 `ERR_STRING_TOO_LONG`);
318
- 修复采用**流式帧重建** `.jsonl.zstd`(header 帧 + 正文分块多帧,逐帧 checksum + roundtrip 校验)。
330
+ ### 0.3.18 → 0.3.23 一段话说清
319
331
 
320
- **Windows**:`H2` 的 `header.cwd` 绝对路径判断改为**平台感知**(`win32` 与 `posix` 都认)。
321
-
322
- **兼容性**:Node ≥ 22;`@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1`;会话格式 v0–v4。
323
-
324
- ## ⚠️ 升级到 0.3.17 —— 必须知道的行为变更(0.3.12 → 0.3.17)
332
+ **会话格式 v4**(宿主 `dsh-session` 0.2.x)改为按版本分派判定(`tool/result` 的 role、`system/message` 的来源);
333
+ 新增五条规则(`G4` 未知但可忽略事件、`S10` 引用元素类型、`I2` `seedLength` 语义、`P5` 载体配对、`A1` 只认结构化字段的在位可还原);
334
+ 大会话(>500MB)按行读取 + 流式帧重建;Windows 的 `header.cwd` 判定改为平台感知。0.3.22 增加
335
+ `contract/` + `adapters/dsh/` 分层(行为不变,且**仍是部分成立** —— 见 CHANGELOG 的已知缺口清单)。判定结果、退出码与 `--json` 字段均不变。
325
336
 
326
337
  > **0.3.17 不含行为变更。** 它只调整了注释、测试标题、少量诊断文案与 README 的措辞。
327
338
  > 所有判定结果、退出码与 `--json` 字段与 0.3.15 完全一致,
@@ -352,3 +363,16 @@ MIT © OfferKuai Team
352
363
  **3.「体检通过」到哪一步为止。**
353
364
  本工具的规则集**不等于**官方升级链的接受条件。`assessmentScope=partial` 只表示"本工具看过的那部分没问题",
354
365
  **不构成**"官方升级会接受"。已知未覆盖的 6 类见 `coverage.uncovered`。
366
+
367
+ ## Roadmap
368
+ - [x] **Phase 1(0.1.0)**:CLI 离线体检 + 写前校验 + 契约目录
369
+ - [x] **Phase 1.5(0.2.0)**:`fix` 子命令(严格 seq 扫描 + W1/W2 wire 检查 + 移除 marker 重编号 + 官方帧格式重建);CI 集成(`dsh-log-contract check` 作为 Harness 会话目录的定时守护)
370
+ - [x] **0.3.x(2026-08-30 案例固化)**:T1 token-meter 配对 → 0.3.1 W1/W2 折叠位置修复 → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize`(turn-null marker 原地中和)→ 0.3.4 `fix --clip-crossstep`(跨 step 引用裁剪)→ 0.3.5 **T2/S9/I1 规则**(跨 step 源引用 / 物理序单调 / inbox 重放)
371
+ - [x] **0.3.6 → 0.3.15**:按被检文件版本择路的 v0–v3 规则(T3/T4/T5、L3–L5、E8/E9/E10)、宿主能力与迁移预检的退出码 `3`/`4`,以及如实报告"哪些版本**未**验证"的版本支持说明(详见 [CHANGELOG.md](CHANGELOG.md))
372
+ - [ ] Phase 2:运行时守护(订阅 session append 事件流实时校验,断裂即标记 `dsh/contract-violation` 事件,策略可配 告警/拦截)——DSH 插件形态
373
+ - [ ] Phase 3:与 dsh-turn-guard / dsh-retrace 时间线联动
374
+
375
+ ## 许可
376
+ MIT © OfferKuai Team
377
+
378
+ ---
@@ -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
+ }