dsh-log-contract 0.3.43 → 0.3.44

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
@@ -15,88 +15,186 @@ offline health check + pre-write validation. The business layer's **doctor**.
15
15
 
16
16
  </div>
17
17
 
18
+ ## What it is
19
+
18
20
  Formerly `log-contract-validator`; now **`dsh-log-contract`**.
19
21
 
20
- A fuse for DSH session logs (`*.jsonl` / `*.jsonl.zstd`): format drift that humans
21
- cannot see but parsers crash on is caught and reported here. It does **not** judge
22
- whether log *content* is right — only whether log *structure* breaks the
23
- expectations of downstream consumers (the Harness read path, the client engine,
24
- plugin marker semantics).
25
-
26
- - **`check <session-log>`** — offline health check: official decoder full decode +
27
- per-rule contract validation + foldSurface final verification, with a violation
28
- report and a machine-readable **tail-completeness** field (`tailStatus`).
29
- - **`prewrite <edit-file> --log <session-log>`** — ★ pre-write validation: any
30
- write (append / frame-level surgery) passes the three-layer contract before it
31
- lands; violations are blocked (including self-invented `seq` values).
32
- - **`contracts`** — list the built-in contract rule catalog (each with its
33
- official source reference).
34
- - **`check --resume`** — three-tier verdict (`loadable` / `resumable` /
35
- `compactable`, plus `not-assessable` when the host cannot judge the file).
36
- - **`fix` / `extract` / `audit-report`** — repair primitives and read-only
37
- session archaeology.
38
-
39
- **Capabilities at a glance**: session formats **v0–v4** · **63 contract rules (57 log-contract + 6 error-expression)** ·
40
- exit-code contract `0/1/3/4` · three-tier verdicts · pre-write validation ·
41
- per-rule negative-control tests + rules self-test · tolerant reading (a single
42
- damaged file degrades to structured results and is counted, never thrown).
43
-
44
- ---
22
+ A session log (`*.jsonl` / `*.jsonl.zstd`) has two readers: humans, who tolerate format
23
+ drift, and programs, which fail on it. This tool checks the **structure** of the log —
24
+ frame layout, event envelope, `seq` continuity, surface/replace rules, wire message order,
25
+ plugin markers — and answers one question with an exit code:
26
+
27
+ > **Will a downstream reader (the Harness read path, the client engine, plugin semantics)
28
+ > choke on this file — and if so, exactly where?**
29
+
30
+ It does **not** judge conversation content. It can also validate a write **before** it
31
+ lands: the same rule set runs as pre-write validation.
32
+
33
+ ### In 30 seconds
34
+
35
+ - **What:** a checker for DSH session-log structure; input is one `.jsonl` / `.jsonl.zstd` file.
36
+ - **Why install it:** it catches drift that humans cannot see but parsers crash on, and it
37
+ stops a bad write before it reaches disk.
38
+ - **Minimum usage:** three commands — see [Quick start](#quick-start-3-commands).
39
+ - **What makes it mechanically checkable:** every rule has a stable id, a severity, a source
40
+ reference and positive/negative control cases; results are a stable JSON report plus a
41
+ documented exit code.
42
+ - **Where to read more:** [rule catalog](docs/CONTRACTS.md) ·
43
+ [report families](#rule-families-what-turns-red) ·
44
+ [version map](VERSIONS.md) · [changelog](CHANGELOG.md).
45
45
 
46
46
  ## Where it sits in the business layer
47
- > **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.
48
- >
49
- > **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`.
47
+
48
+ > **`dsh-log-contract` is the core check-and-repair component of
49
+ > [dsh-retrace](https://github.com/yamingmou/dsh-retrace)** — the business layer's "doctor"
50
+ > module. It ensures that every recall / edit / rollback lands on a legal log:
51
+ > pre-write validation rejects error-level violations **before** anything is written.
50
52
 
51
53
  | Layer | What it is | Components |
52
54
  |---|---|---|
53
55
  | **Agent business layer (production-grade)** | Framework-agnostic core: session hygiene / retraceability / auditability / recoverability | Four modules: governance / retrospect / archaeology / **doctor** |
54
- | **dsh-retrace** | The business layer's DeepSeek Harness implementation | recall/edit/version/rollback/watchdog |
56
+ | **dsh-retrace** | The business layer's DeepSeek Harness implementation | recall / edit / version / rollback / watchdog |
55
57
  | **dsh-log-contract** | dsh-retrace's core component = the business layer's **doctor** (check & repair) | check / prewrite / fix / extract / audit-report |
56
58
 
57
- **Meaning**: dsh-log-contract is published standalone (for direct use or
58
- re-implementation), but it is first the "check & repair" capability of dsh-retrace —
59
- together they form the **Agent business layer (production-grade guarantees)** on
60
- DSH (see the [dsh-retrace repository](https://github.com/yamingmou/dsh-retrace)).
59
+ **Meaning:** the package is published standalone (for direct use or re-implementation), but
60
+ it is first the "check & repair" capability of dsh-retrace — together they form the
61
+ **Agent business layer (production-grade guarantees)** on DSH.
61
62
 
62
- ---
63
+ **About `/compact` (stated honestly):** what this tool guarantees is that **new writes**
64
+ stop creating token-meter pairing debt — since two-segment atomic pairs (marker + paired
65
+ segment) landed, new markers pass T1 by construction. **Legacy** (single-segment) markers
66
+ remain **known design debt**: pre-write validation downgrades their T1 violation to a
67
+ warning (`legacyMarkerKindOf` in `lib/prewrite.js`, historical markers only), so such
68
+ sessions need **one check + cleanup before compaction** (`check` to locate →
69
+ `fix --remove-markers`). Otherwise the T1 self-check blocks `/compact`.
63
70
 
64
71
  ## Why it exists
65
- **"one log, two consumers, two verdicts"**: one log is consumed by both
66
- humans and automated programs. Humans tolerate format drift; programs depend on
67
- strict contracts. Once the format drifts, humans see nothing wrong while programs
68
- crash or misreport.
69
72
 
70
- **Real log-corruption shapes found in production sessions shaped most of the rules here** —
71
- see the [Case log](#case-log--why-production-grade-is-not-a-slogan) below. The case-derived instances are pinned by regression tests: a corrupt log shape
72
- this tool must flag, and the repaired shape it must pass. The remaining rules come from
73
- line-by-line verification against the official Host source (each rule carries its
74
- `source`).
73
+ **One log, two consumers, two verdicts.** Humans tolerate format drift; programs depend on
74
+ strict contracts. Once the format drifts, humans see nothing wrong while programs crash or
75
+ misreport.
76
+
77
+ **Most rules here were shaped by real corrupted sessions** — see the
78
+ [case log](#case-log--why-production-grade-is-not-a-slogan). Each case is pinned by a
79
+ regression test: a corrupt shape this tool must flag, and the repaired shape it must pass.
80
+ The remaining rules come from line-by-line verification against the official Host source
81
+ (every rule carries a `source` reference).
82
+
83
+ ## Quick start (3 commands)
84
+
85
+ Requires **Node ≥ 22** (built-in zstd) and the peer package `@deepseek-ai/dsh-session`
86
+ (decode/fold semantics are reused from the host).
87
+
88
+ ```bash
89
+ # 1. install (or use `pnpm dlx dsh-log-contract` without installing)
90
+ pnpm add -D dsh-log-contract
91
+
92
+ # 2. check a session log — machine-readable output
93
+ pnpm dlx dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json
94
+
95
+ # 3. see every log-contract rule (id, severity, source)
96
+ pnpm dlx dsh-log-contract contracts
97
+ ```
98
+
99
+ > **Using dsh-retrace?** No separate install is needed — it declares `dsh-log-contract` as a
100
+ > dependency, so the guard comes with the plugin. **Downloaded the repo as a ZIP?**
101
+ > `cd dsh-log-contract && npm install`, then run `node bin/dsh-log-contract.mjs check <log>`
102
+ > (no build step, no global install).
103
+
104
+ ## What a check reports
105
+
106
+ ```text
107
+ 📋 dsh-log-contract check —— <file>
108
+ 事件 204754 | surface 节点 16 | replace 代数 5 | 帧 8620
109
+ 违规 1(error 1 / warning 0)
110
+
111
+ [error] S5 @ seq <seq> / line <line> (assistant/message)
112
+ surface replace: sourceEventSeqs 必须覆盖每个被替换节点;缺失 121774, 121779(共 2 个)
113
+
114
+ ❌ 未通过:见上方违规明细(error 级 = 会话不可读/不可写)
115
+ ```
116
+
117
+ ### Exit codes
118
+
119
+ `check` uses `0 / 1 / 3 / 4` — **there is no `2`**. `error-contract` is a separate command
120
+ with its own codes.
121
+
122
+ | code | command | meaning |
123
+ |---|---|---|
124
+ | `0` | `check` | pass — no error-level violations, migration pre-check not blocked |
125
+ | `1` | `check` | error-level violations exist (a downstream reader would fail) |
126
+ | `3` | `check` | not assessable on this host (file format newer than host support) — **not** "broken" |
127
+ | `4` | `check` | migration pre-check blocked (the official upgrade chain would refuse the file) |
128
+ | `0 / 1 / 2` | `error-contract` | no findings (third-party findings are report-only) / error-level findings (T1, or T2 with `--strict`) / cannot judge (bad input) |
129
+
130
+ ### Three-tier verdict (`check --resume`)
131
+
132
+ | tier | what it certifies | `--json` |
133
+ |---|---|---|
134
+ | `loadable` | the session can be read (structure rules) | `resume.loadable` |
135
+ | `resumable` | + inbox replay is valid | `resume.resumable` |
136
+ | `compactable` | + token-meter pairing is valid | `resume.compactable` |
137
+ | `broken` | fails the `loadable` tier | `resume.verdict` |
138
+ | `not-assessable` | this host cannot judge the file (exit 3) | `assessable: false` |
139
+
140
+ ### What is *not* judged (never read as a pass)
141
+
142
+ `ok: null` / `skipped` means **unverifiable**, not success. The same rule applies to every
143
+ optional section:
144
+
145
+ | situation | field / value | how to read it |
146
+ |---|---|---|
147
+ | identity registry absent (npm install has no `docs/identity-registry.json`) | `identity.ok: null` | unverifiable — run identity checks in a source checkout / release pipeline |
148
+ | a run-contract assertion has no input | assertion `ok: null`, listed in `skipped` | unverifiable — provide the runtime record |
149
+ | archive reader not ready / unavailable | `archive.verdict: "unverifiable"` (`notReady`, `unavailable`) | **not** "content missing"; retry when the reader is up |
150
+ | host too old for the file format | `assessable: false`, exit 3 | not a health verdict |
151
+ | last frame cut mid-write | `summary.tailStatus: interrupted / truncated / unknown` | `ok: true` only certifies the events actually read |
75
152
 
76
- ---
153
+ **Tail boundary:** `ok: true` never promises the file is complete. A torn tail
154
+ (`interrupted`) is recoverable by the host reader; `truncated` means data is actually
155
+ missing; `unknown` means the tail could not be read.
77
156
 
78
157
  ## Three-layer contract (the model)
79
- > **63 rules in two families**: **57 log-contract rules** across the layers below
80
- > (each with its official source reference) + **6 error-expression rules** (E1–E6, see
81
- > §1.1). `contracts` lists the 57 log-contract rules; the error-expression catalogue is
82
- > returned by `check --json` under `errorContract`, and `error-contract` scans source text for it.
158
+
159
+ > **72 rules in four report families**: **57 log-contract rules** across the layers below
160
+ > (each with an official source reference), plus **6 error-expression** (E1–E6),
161
+ > **2 version-identity** (ID1/ID2) and **7 run-contract** rules. `contracts` lists the 57
162
+ > log-contract rules; the other families live in their own documents.
83
163
 
84
164
  | Layer | Rules | What it guards |
85
165
  |---|---|---|
86
- | **Persistence** | H/R/E/S (incl. **S5**) + **S9** | seq contiguous, known types, legal `surfaceOp`, `sourceEventSeqs` fully covers shadowed nodes, file-physical seq monotonic, `foldSurface` not throwing |
166
+ | **Persistence** | H/R/E/S (incl. **S5**) + **S9** | `seq` contiguous; known types; legal `surfaceOp`; `sourceEventSeqs` fully covers shadowed nodes; file-physical `seq` monotonic; `foldSurface` does not throw |
87
167
  | **Client engine** | **M1** + **T1 / T2 / I1** | turn-null markers only as replace; token-meter pairing; cross-step source refs; inbox seed-relative replay |
88
- | **Wire message flow** | **W1 / W2** | tool messages follow an assistant with tool_calls; no user text between tool_calls and results |
89
- | **Plugin semantics** | P1/P2 | marker id prefixes recognizable; a marker's seq not in its own shadowed set |
90
- | **Framing** | Z1–Z6 | zstd frame shape (header own first frame; no single-frame re-compression), empty-shell sessions, **tail completeness (`tailStatus`)** |
91
- | **Reader / aggregation** | **R4 / R5** | a single damaged file must degrade to a structured, countable result (never throw, never abort enumeration); aggregation APIs isolate failures per item |
168
+ | **Wire message flow** | **W1 / W2** | tool messages follow an assistant with tool_calls; no user text between tool_calls and their results |
169
+ | **Plugin semantics** | **P1 / P2** | marker id prefixes are recognizable; a marker's seq is not in its own shadowed set |
170
+ | **Framing** | **Z1–Z8** | zstd frame shape (header owns the first frame; no single-frame recompression), empty sessions, tail completeness, frame size/checksum |
171
+ | **Reader / aggregation** | **R4 / R5** | a single damaged file degrades to a structured, countable result (never throws, never aborts enumeration); aggregation isolates failures per item |
92
172
 
93
173
  > Philosophy: first an incremental replay with official-equivalent semantics for
94
- > **per-event attribution** (pinpoint seq/line), then the official `foldSurface` as
95
- > the **final verdict** (not throwing = pass) — both green to pass.
174
+ > **per-event attribution** (pinpoint `seq` / line), then the official `foldSurface` as the
175
+ > **final verdict** (not throwing = pass) — both must be green.
176
+
177
+ ## Rule families (what turns red)
178
+
179
+ Every rule has a stable id, a severity, a source reference and **positive/negative control
180
+ cases** (a violating sample must fail, a compliant one must pass). The four families are
181
+ dispatched by `family` and must not be merged by bare id.
96
182
 
97
- ---
183
+ | family | rules | guards | full list |
184
+ |---|---|---|---|
185
+ | **log contract** | **57** | persisted session logs: frames (Z), header (H), storage rows (R), envelope/`seq` (E), surface (S), client engine (T/M/I), wire order (W), markers (P), concurrency (C), migration (G), archive (A) | [docs/CONTRACTS.md](docs/CONTRACTS.md) |
186
+ | **error-expression** | **6** (E1–E6) | error handling as a contract: one code with many causes, constant messages, terminal-word misuse, swallowed `cause`, unconditional success, claimed-but-unenforced invariants | [docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md) |
187
+ | **version-identity** | **2** (ID1–ID2) | *is the artifact you run the one the version promises?* ID1 one version ↔ one digest; ID2 the digest is computed from the artifact and bound to `package.json.version` | [docs/interface-versioning.md](docs/interface-versioning.md) |
188
+ | **run-contract** | **7** | *will it silently change while running?* R-1 failure latched; R-2a failed write never marked complete; R-2b withdrawal needs a consumer-readable reason; R-2b-2 initializing ≠ "none"; R-3 missing input ⇒ incompatible; R-5 closed sets exhaustive / open sets tolerant; R-6 side effects idempotent per stable key | [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md) |
189
+
190
+ Total: **72** assertions (57 + 6 + 2 + 7). The run-contract ids are **not** a contiguous
191
+ 1…7 sequence — the code ids are `R-1 / R-2a / R-2b / R-2b-2 / R-3 / R-5 / R-6` (that is all
192
+ seven). S9 (log family) additionally reports a diagnosis category
193
+ (`old-cursor-replay` / `concurrent-writer` / `format-mix`) with a confidence and the decision
194
+ basis; the S9 verdict itself is unchanged.
98
195
 
99
196
  ## Identity contract (ID1 / ID2) — "is what runs what you think it is?"
197
+
100
198
  A **separate report family** (`version-identity`): not counted in the 57 log-contract rules,
101
199
  and **not part of `ok` / exit codes** — it answers whether the artifact you run is the one
102
200
  the declared version promises.
@@ -112,260 +210,110 @@ the declared version promises.
112
210
  `docs/**/*.md` only. After a version bump or a runtime-code change, re-register:
113
211
  `pnpm identity:register` (source checkout only; the npm package does not ship `scripts/`).
114
212
 
115
- ---
213
+ ## Runtime contract (7 rules) — "will it silently change while running?"
116
214
 
117
- ## Runtime contract (R-3 / R-1 / R-2a) — "will it silently change while running?"
118
215
  A **separate report family** (`run-contract`, exposed as `check --json` → `runContract`), again
119
- outside `ok` / exit codes. It ships three assertion helpers for real run records:
216
+ outside `ok` / exit codes. It ships assertion helpers for real run records:
120
217
 
121
218
  | Rule | Assertion | What it guards |
122
219
  |---|---|---|
123
- | `R-3` | `assertFailClosed({ required, provided, result })` | any missing required input (field / file / context) ⇒ the verdict must be **incompatible**, with a visible reason naming the missing input — a missing input never matches (`fail-open` is red) |
124
220
  | `R-1` | `assertFailureLatched(history)` | a failure is **latched**: after `failed: true`, no later snapshot (recover / reload / cache clear) may write `failed: false` |
125
221
  | `R-2a` | `assertWriteOutcome({ write, artifact })` | a failed or unknown write must never leave the artifact marked `complete` — withdraw it or mark it `partial` / `unavailable` / `withdrawn` |
126
- | `R-2b` | `assertWithdrawalHasReason({ withdrawals, reasonField?, reasonSupported? })` | a withdrawal response must carry a **consumer-readable reason** field; a reason that only lives in logs/telemetry is red; implementations without such a field report `ok:null` (unverifiable) |
127
- | `R-2b②` | `assertInitializedNotTreatedAsEmpty({ resources })` | a resource that is **initializing / unavailable** must not be judged as "none": judging from an empty value before `initialized === true` is red; no init signal ⇒ `ok:null` |
128
- | `R-5` | `assertClosedSetExhaustive({ closedSet, covered })` / `assertOpenSetTolerant({ openSet, observations })` | our **closed** enumerations must be exhaustive (no missing/extra values); **open** sets (upstream event types, error codes, providers) must not be exhausted — unknown values need trace + default-allow + upgradeability |
129
- | `R-6` | `assertIdempotentSideEffects({ operations, keyField? })` | side effects are grouped by a **stable key**: at most one execution per key, later attempts must be cached or explicitly "duplicate"; records without keys report `ok:null` (precondition: the key is supplied by the runtime) |
130
-
131
- `checkRunContract({...})` runs them together (unverifiable results stay `null`) and lists the assertions you did not supply under
132
- `skipped`; when **none** ran, `ok` is `null` (unverifiable — never "pass"). Usage, positive/negative examples and the open items for R-2b
133
- (reason field) and R-6 (idempotency key) are in [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md).
222
+ | `R-2b` | `assertWithdrawalHasReason({ withdrawals, reasonField?, reasonSupported? })` | a withdrawal response must carry a **consumer-readable reason**; a reason only in logs/telemetry is red; no such field ⇒ `ok: null` |
223
+ | `R-2b-2` | `assertInitializedNotTreatedAsEmpty({ resources })` | a resource still initializing (or unavailable) must not be judged as "none"; no initialization signal ⇒ `ok: null` |
224
+ | `R-3` | `assertFailClosed({ required, provided, result })` | any missing required input (field / file / context) ⇒ the verdict must be **incompatible**, with a visible reason naming the missing input |
225
+ | `R-5` | `assertClosedSetExhaustive({ closedSet, covered })` / `assertOpenSetTolerant({ openSet, observations })` | own closed sets must be exhaustive (missing / extra values are red); external open sets must not be exhausted — unknown values must be traced, allowed by default and upgradeable |
226
+ | `R-6` | `assertIdempotentSideEffects({ operations, keyField? })` | side effects execute at most once per stable idempotency key; later attempts must be cached / explicitly duplicated; no stable key ⇒ `ok: null` |
134
227
 
135
- ---
228
+ `checkRunContract({...})` runs them together and lists assertions you did not supply under
229
+ `skipped`; when **none** ran, `ok` is `null` (unverifiable — never "pass"). Usage,
230
+ positive/negative examples and open items are in [docs/RUN-CONTRACT.md](docs/RUN-CONTRACT.md).
136
231
 
137
232
  ## Version support (host / session format)
138
- **Tested baseline (the versions this rule set was verified against)**:
233
+
234
+ **Tested baseline (the versions this rule set was verified against):**
139
235
 
140
236
  | Item | Baseline | Note |
141
237
  |---|---|---|
142
- | Host package | `@deepseek-ai/dsh-session@0.2.0-rc.2` | the version this rule set is developed and CI-tested against (CI runs `pnpm check` + `pnpm test`; the four `prepublishOnly` steps are green locally on it) |
238
+ | Host package | `@deepseek-ai/dsh-session@0.2.0-rc.2` | the version this rule set is developed and CI-tested against |
143
239
  | Session format | **v4** (`SESSION_FORMAT_VERSION = 4`) | v4 uses the runtime vocabulary + official `foldSurface` final check |
144
- | Declared range | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1` | installable — a declared range is **not** a per-version verification |
240
+ | Declared range | `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1` | installable — a declared range is **not** a per-version verification |
145
241
  | Known formats | 0 / 1 / 2 / 3 / 4 | 0–2 are supported by this package's **vendored** vocabulary + local equivalent fold (`legacyFoldSurface`), independent of the host |
146
242
 
147
- **What happens on unverified versions (detected and reported at runtime — never silently judged by stale rules)**:
243
+ **What happens on unverified versions (detected at runtime — never silently judged by stale rules):**
148
244
 
149
245
  | Case | Behaviour |
150
246
  |---|---|
151
- | Host **newer than the baseline** | explicit **warning** (`host … is newer than the tested baseline …`); the verdict is still produced but flagged as possibly not applicable |
152
- | Host older than the baseline (still in peer range) | notice + the host-capability gate decides whether the file's format is assessable (`SESSION_FORMAT_VERSION` too low ⇒ `not-assessable`, exit 3) |
247
+ | Host **newer than the baseline** | explicit **warning**; the verdict is still produced but flagged as possibly not applicable |
248
+ | Host older than the baseline (still in peer range) | notice + the host-capability check decides whether the file's format is assessable (`SESSION_FORMAT_VERSION` too low ⇒ `not-assessable`, exit 3) |
153
249
  | **Unknown** session format (not in 0/1/2/3/4) | reported as **unverified format** and handled **read-only**: `check` runs structure rules only; `prewrite` / `fix` **refuse** (exit 3) |
154
- | Format **unrecognisable** (no `header.version` and no distinguishing event shapes) | same: "unverified format" + read-only |
250
+ | Format **unrecognisable** (no `header.version`, no distinguishing shapes) | same: "unverified format" + read-only |
155
251
  | File version above the host's supported maximum | `not-assessable` (**not** broken), exit 3; skipped/executed rules are listed |
156
252
 
157
- Implementation: `lib/version-support.js` (`TESTED_BASELINE` / `detectSupport()`, exported in the public API).
158
- Both the human-readable `check` output and the `--json` `support` field carry the baseline summary and the warnings, e.g.:
159
-
160
- ```
161
- version support: host @deepseek-ai/dsh-session@0.2.0-rc.2 (baseline 0.2.0-rc.2) | file format v4 (header, baseline)
162
- ```
163
-
164
- ## 🆕 0.3.28 · Reader tolerance, tail completeness, seq provenance
165
- Four rules distilled from recent production failures (each pinned by a
166
- negative-control test — a violating sample must turn red, a compliant one green):
253
+ Implementation: `lib/version-support.js` (`TESTED_BASELINE` / `detectSupport()`), exported in
254
+ the public API; the `--json` `support` field carries the same baseline and warnings.
167
255
 
168
- | Rule | Checks | Severity |
169
- |---|---|---|
170
- | `R4` | read/parse tolerance: a single damaged file (torn zstd frame, corrupt line, bad chunk row, empty file) must degrade to a **structured, countable** result (`null` / per-row `error` markers / `frameInfo` facts) — never throw and never abort an enumeration/summary run | error |
171
- | `R5` | aggregation/summary APIs isolate failures **per item** (per-item `try/catch` + a `skipped` counter); one bad item must not sink the batch | error |
172
- | `E11` | `seq` is assigned by the log layer's continuous cursor only: a pre-write candidate must omit `seq` (auto-assigned) or carry exactly `nextSeq`; producer-side `seq` invention / delete-without-renumber shows up as gaps ⇒ `E2`/`S9` | error |
173
- | `Z6` | tail completeness must be declared: `tailStatus: complete \| interrupted \| truncated \| unknown` (see the known boundary below) | warning |
174
-
175
- Also in 0.3.28: **rules self-test** — the registry, the tests and the generated
176
- docs are cross-checked (`test/rules-self-test.test.js`): every rule must be
177
- referenced by a control or a binding assertion in the tests (or carry an
178
- explicit, justified delegation entry; the red/green strength of each control is
179
- owned by that rule's own negative-control cases); every emitted violation id
180
- must be registered. `summary.unreadableRows` and
181
- `summary.tailStatus` are new machine-readable fields.
182
-
183
- **Known boundary (stated honestly)**: `check` / `check --json` guarantee that
184
- **the events actually read** are self-consistent — they do **not** guarantee the
185
- file tail is intact. A file whose last frame was cut mid-write can still come
186
- back `ok=true`; read `summary.tailStatus` (`--json`) to know the tail state.
187
- `tailStatus` values: `complete` (tail intact) · `interrupted` (torn zstd tail —
188
- in-flight/interrupted write; the host reader keeps complete records and drops
189
- the unfinished tail, so it is recoverable) · `truncated` (the tail record itself
190
- is cut — data is missing) · `unknown` (undecidable: unreadable/empty file).
191
- `Z6` reports the non-`complete` states as a warning and deliberately does not
192
- flip `ok`.
193
-
194
- ## 🆕 0.3.18 – 0.3.24 · DSH 0.2.x (session format v4) support
195
- **Session format v4** (`@deepseek-ai/dsh-session` 0.2.x) is now validated by format-version dispatch
196
- rather than by relaxing the format gate:
197
-
198
- - `tool/result` is validated with the v4 shape (`role: 'tool'`, no `tool-result` wrapper block)
199
- - `system/message` accepts v4's `source.kind: 'system-prompt'`
200
- - validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
201
- - the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
202
-
203
- **Rules (55 as of 0.3.28, 57 as of 0.3.32; 63 total as of 0.3.36 — 57 log-contract + 6 error-expression):** the five rules below were added in the
204
- 0.3.18 – 0.3.24 window (see above for the 0.3.28 additions):
205
-
206
- | Rule | Checks |
207
- |---|---|
208
- | `G4` | unknown historical events may be declaratively skipped (`ignorable: true`; allow-list injectable) |
209
- | `S10` | `sourceEventSeqs` elements: non-negative integers after decoding (official interval pairs allowed in storage) |
210
- | `I2` | `seedLength` means *number of inherited events* (not bytes); `parentSession` + missing/0 is legal |
211
- | `P5` | two-segment carrier pairing: 2nd segment's first seq == 1st segment seq (read side accepts the legacy order) |
212
- | `A1` | "in-place restorable" is judged from structured fields only (`archiveRef` / `archive` / `externalized.*`) — never from free text |
213
-
214
- **Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~536 MB),
215
- and repair rebuilds `.jsonl.zstd` with streaming frames (header frame + chunked body frames, per-frame checksum + round-trip).
216
-
217
- **Windows:** the `header.cwd` absolute-path check in `H2` is platform-aware (`win32` and `posix` both accepted).
218
-
219
- **Compatibility:** Node ≥ 22; `@deepseek-ai/dsh-session` `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1`; session formats v0–v4.
220
-
221
- ## Case log — why "production-grade" is not a slogan
222
- Each entry below is a **real log-corruption shape** from production sessions — the cases that
223
- shaped this tool. Dates and shapes are real; session ids and file names are
224
- omitted.
225
-
226
- | # | Date | What happened | The rule / fix it produced |
227
- | --- | --- | --- | --- |
228
- | 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 |
229
- | 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` |
230
- | 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` |
231
- | 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 |
232
- | 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) |
233
- | 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` |
234
- | 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) | |
235
- | 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 | |
236
- | 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 | |
237
- | 10 | 2026-09-17 | On **Windows**, `header.cwd` was judged with POSIX-only rules → **every** session flagged by **H2** ⇒ platform-aware absolute-path check | |
238
- | 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 | |
239
- | 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 | |
240
- | 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 | |
241
- | 14 | 2026-10-20 | An **unknown but explicitly ignorable** event type blocked an entire migration ⇒ **G4** declarative skip + allow-list | |
242
- | 15 | 2026-10-26 | A **truncated zstd frame** made the session-header reader throw `ERR_OUT_OF_RANGE`, and because there was no per-item isolation the whole enumeration/summary run failed (hundreds of failures over 33 days) — **one damaged file sank the whole batch** | **R4** (read/parse tolerance: degrade to a structured, countable result), **R5** (per-item isolation + failure counting in aggregation APIs) |
243
- | 16 | 2026-10-26 | A file whose **last frame was cut mid-write** still reported `ok=true` — the check certifies only the events it actually read | **Z6** (`tailStatus: complete/interrupted/truncated/unknown`) + the documented tail-completeness boundary |
244
- | 17 | 2026-10-26 | Producers **inventing `seq` on the write side**, and **deleting rows without renumbering** | **E11** (`seq` assigned by the log layer only; pre-write rejects self-invented `seq`), gap traces pinned to `E2`/`S9` |
245
-
246
- > **Takeaway**: these rules are not synthetic theory — each one is pinned by a
247
- > regression test that reproduces the corrupt shape it guards against. That is what
248
- > "production-grade" means here.
249
-
250
- ---
251
-
252
- ## Installation
253
- ```bash
254
- pnpm add -D dsh-log-contract # or npm install
255
- pnpm dlx dsh-log-contract --help
256
- ```
257
-
258
- > **Using dsh-retrace?** No separate install needed — `dsh-retrace` declares
259
- > `dsh-log-contract` as a dependency, so the contract guard (check / pre-write /
260
- > repair primitives) comes with the plugin automatically. This package is published
261
- > standalone for direct use or re-implementation.
262
- >
263
- > **Downloaded the repo as a ZIP?** `cd dsh-log-contract && npm install`, then
264
- > `node bin/dsh-log-contract.mjs check <session-log>` — no build step and no global install needed.
265
-
266
- Dependencies: Node ≥ 22 (`node:zlib` has built-in zstd), `@deepseek-ai/dsh-session`
267
- (peer; validation/decode reuse the official implementation, so it stays in sync
268
- with the Harness read path).
256
+ ## CLI
269
257
 
270
- ---
258
+ After install, `dsh-log-contract` is on the PATH through your package manager (the examples
259
+ below use `pnpm exec`; `pnpm dlx dsh-log-contract …` works without installing).
271
260
 
272
- ## CLI
273
261
  ### 1. Offline health check
274
262
 
275
263
  ```bash
276
- dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd
277
- dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json # machine-readable
264
+ pnpm exec dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd
265
+ pnpm exec dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json # machine-readable
266
+ pnpm exec dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --resume # three-tier verdict
278
267
  ```
279
268
 
280
- Sample output (the CLI reports in Chinese — it is the tool's UI language):
281
-
282
- ```
283
- 📋 dsh-log-contract check —— backup-session-xxxx.jsonl.zstd
284
- 事件 204754 | surface 节点 16 | replace 代数 5 | 帧 8620(3439.5KiB → 8191.3KiB)
285
- 违规 1(error 1 / warning 0)
269
+ `check` also runs **W1/W2 wire-level checks**: expand the model request stream in surface
270
+ order and catch "dangling tool messages" (a tool result with no preceding assistant
271
+ tool_calls) and "user text between tool_calls and their results" — tolerated by some
272
+ endpoints, `INVALID_REQUEST` on strict ones.
286
273
 
287
- [error] S5 @ seq <seq> / line <line> (assistant/message)
288
- surface replace: sourceEventSeqs 必须覆盖每个被替换节点;缺失 121774, 121779(共 2 个)
289
-
290
- ❌ 未通过:见上方违规明细(error 级 = 会话不可读/不可写)
291
- ```
292
-
293
- **Exit-code contract** (there is no exit code `2`):
294
-
295
- | Code | Meaning |
296
- |---|---|
297
- | `0` | pass — no error-level violations (and the migration pre-check is not blocked) |
298
- | `1` | error-level violations exist (session unreadable/unwritable under this rule set) |
299
- | `3` | not assessable on this host (file format newer than the host supports) — **not** "broken" |
300
- | `4` | the migration pre-check is blocked (the official upgrade chain will refuse the file) |
301
-
302
- **Three-tier verdict** (`check --resume`, also in `--json` as `resume`):
303
- `loadable` (structure green) ⊂ `resumable` (+ `I1` inbox replay green) ⊂
304
- `compactable` (+ `T1`/`T2` token-meter pairing green); a file failing the first
305
- tier is reported as `broken`, and `not-assessable` is a separate fourth state
306
- when the host cannot judge the file.
307
-
308
- **Tail-completeness boundary**: `ok=true` only certifies that *the events actually
309
- read* are self-consistent — see the `tailStatus` note in the 0.3.28 section above.
310
-
311
- **Report structure versioning (`schemaVersion`)**: every `check --json` report
312
- carries a top-level `schemaVersion` (currently `"2"`) that versions the **report
313
- structure** itself — field set / types / meanings — not the tool version and not
314
- the log format version. Within one version, reports are additive only (existing
315
- top-level keys are never removed, renamed or redefined); a report **without** the
316
- field is to be read as `"1"`. `"2"` adds S9 diagnosis fields (`category`/`confidence`/`hint`/`basis`) without changing the S9 verdict. Full compatibility promise and bump rules:
317
- [docs/interface-versioning.md](./docs/interface-versioning.md).
318
-
319
- `check` adds **W1/W2 wire-level checks** since 0.2.0: expand the model request
320
- stream in surface order and catch "dangling tool messages" (a tool result with no
321
- preceding assistant tool_calls) and "user text between tool_calls and their
322
- results" — tolerated by some endpoints, `INVALID_REQUEST` on strict ones
323
- (MiMo, verified 2026-08-27).
324
-
325
- ### 1.1 Error-expression contract scan (`error-contract`)
274
+ ### 1.1 Error-expression scan (`error-contract`)
326
275
 
327
276
  Static scan of *how errors are raised* (source text; no AST). This is the **6-rule
328
- error-expression family** (E1–E6; 63 = 57 log-contract + 6 here):
329
- E1 one code with many causes · E2 constant message · E3 terminal word on a non-terminal
330
- cause · E4 `cause` not surfaced · E5 unconditional success (candidate) · E6 claims with no
331
- enforcement point (candidate).
277
+ error-expression family** (E1–E6): one code with many causes · constant message · terminal
278
+ word on a non-terminal cause · `cause` not surfaced · unconditional success (candidate) ·
279
+ claims with no enforcement point (candidate).
332
280
 
333
281
  ```bash
334
- dsh-log-contract error-contract lib/ bin/ --json # T1 (our code): hits ⇒ exit 1
335
- dsh-log-contract error-contract <pkg>/lib/index.js --target T2 # T2 (third-party): report only, exit 0
336
- dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom # E6① declared-key reads
337
- dsh-log-contract error-contract lib/ --config cordis.patch.yml # E6① from YAML config keys
282
+ pnpm exec dsh-log-contract error-contract lib/ bin/ --json # T1 (our code): hits ⇒ exit 1
283
+ pnpm exec dsh-log-contract error-contract <pkg>/lib/index.js --target T2 # T2 (third-party): report only, exit 0
284
+ pnpm exec dsh-log-contract error-contract lib/ --keys thresholdRatio,headroom
285
+ pnpm exec dsh-log-contract error-contract lib/ --config cordis.patch.yml
338
286
  ```
339
287
 
340
288
  ⚠️ **Output is a suspicion list, not a verdict**: the rules are heuristics and necessarily
341
289
  carry false positives — every finding ships raw `evidence` for human review; whitelist
342
- entries must carry an `expires` date (missing/invalid/expired ⇒ exit 2, fail-closed).
343
- Full criteria, false-positive risks and whitelist format: [docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md).
290
+ entries must carry an `expires` date (missing/invalid/expired ⇒ exit 2, fail-closed). Full
291
+ criteria: [docs/ERROR-CONTRACT.md](docs/ERROR-CONTRACT.md).
344
292
 
345
293
  ### 2. Repair (`fix`)
346
294
 
347
295
  ```bash
348
296
  # Dry run (report only): strict seq scan + full contract check + removable-marker count
349
- dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers
297
+ pnpm exec dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers
350
298
 
351
- # Apply: backup first, then write (.zstd rebuilt in official frame format: frame1=header,
352
- # frame2=rest, checksum, single trailing newline)
353
- dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
299
+ # Apply: backup first, then write (.zstd rebuilt in official frame format:
300
+ # frame 1 = header, following frames = batches, checksum, single trailing newline)
301
+ pnpm exec dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
354
302
  ```
355
303
 
356
304
  - `--remove-markers`: remove retrace/message-editor markers and renumber everything
357
- (seq/seq0/sourceEventSeqs/surfaceOp in sync) — for large marker-shadowed history
358
- or markers that left dangling tools.
359
- - `--neutralize`: in-place neutralization of turn-null markers (case #6) —
360
- type → `retrace/marker` + `ignorable:true`, drops surfaceOp/sourceEventSeqs,
361
- seq/line count unchanged (safe while the session is resident).
362
- - `--clip-crossstep`: trim cross-step sourceEventSeqs (case #6) — keep only
363
- same-turn/step chunk references.
364
- - Surgery safety protocol: back up first, re-verify after (strictScan + check +
365
- foldSurface); markers may only shadow earlier nodes; a marker must never become
366
- append (M1 crashes the client engine).
367
- - ⚠️ If the session is resident in a running app, **restart the app** after fixing
368
- the file (hard-kill to avoid dirty state flushing back).
305
+ (`seq` / `seq0` / `sourceEventSeqs` / `surfaceOp` in sync) — for large marker-shadowed
306
+ history or markers that left dangling tools.
307
+ - `--neutralize`: in-place neutralization of turn-null markers — type → `retrace/marker` +
308
+ `ignorable: true`, drops `surfaceOp` / `sourceEventSeqs`, `seq` / line count unchanged
309
+ (safe while the session is resident).
310
+ - `--clip-crossstep`: trim cross-step `sourceEventSeqs` — keep only same-turn/step chunk
311
+ references.
312
+ - Surgery safety: back up first, re-verify after (strict scan + check + `foldSurface`);
313
+ markers may only shadow earlier nodes; a marker must never become append (M1 crashes the
314
+ client engine).
315
+ - ⚠️ If the session is resident in a running app, **restart the app** after fixing the file
316
+ (hard-kill to avoid dirty state flushing back).
369
317
 
370
318
  ### 3. Pre-write validation (`prewrite`)
371
319
 
@@ -373,53 +321,81 @@ dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
373
321
 
374
322
  ```jsonc
375
323
  // Append one event to the log tail (seq omitted = auto-assigned as nextSeq)
376
- { "append": { "type": "assistant/message", "surfaceOp": { "op": "replace", "start": 121774, "end": 156421 }, "sourceEventSeqs": [121774, 121779, "…"], "data": { "turn": null, "step": null, "message": { "…": "…" }, "editor": { "targetSeq": 156430, "text": "…" } } } }
324
+ { "append": { "type": "assistant/message", "surfaceOp": { "op": "replace", "start": 121774, "end": 156421 }, "sourceEventSeqs": [121774, 121779], "data": { "turn": null, "step": null, "message": {}, "editor": { "targetSeq": 156430, "text": "…" } } } }
377
325
 
378
- // Frame-level surgery: the complete event list after the edit (both baseline and
379
- // result must be green before it may land)
380
- { "edit": [ "…full event list…" ] }
326
+ // Frame-level surgery: the complete event list after the edit
327
+ { "edit": [ "…the full event list…" ] }
381
328
  ```
382
329
 
383
330
  ```bash
384
- dsh-log-contract prewrite marker-write.json --log ~/.dsh/sessions/<id>.jsonl.zstd
331
+ pnpm exec dsh-log-contract prewrite marker-write.json --log ~/.dsh/sessions/<id>.jsonl.zstd
385
332
  ```
386
333
 
387
- - A baseline with error-level violations is rejected outright (safety protocol
388
- step 2: **the pre-surgery baseline must be green**).
389
- - `seq` must be **omitted** (auto-assigned as `nextSeq`) or exactly `nextSeq` —
390
- a self-invented `seq` is rejected (`E11`); on the file side, delete-without-
391
- renumber and invented `seq` show up as gaps and are caught by `E2`/`S9`.
392
- - Only a pass may land — **validate first, commit later** (same idea as the
393
- official `SurfaceManager.validateNext`).
334
+ - A baseline with error-level violations is rejected outright (the pre-surgery baseline must
335
+ be green).
336
+ - `seq` must be **omitted** (auto-assigned as `nextSeq`) or exactly `nextSeq` — a
337
+ self-invented `seq` is rejected (`E11`); on the file side, delete-without-renumber and
338
+ invented `seq` show up as gaps and are caught by `E2` / `S9`.
339
+ - Only a pass may land — **validate first, commit later** (the same idea as the official
340
+ `SurfaceManager.validateNext`).
394
341
 
395
342
  ### 4. Contract catalog
396
343
 
397
344
  ```bash
398
- dsh-log-contract contracts
345
+ pnpm exec dsh-log-contract contracts # 57 log-contract rules with sources
346
+ pnpm exec dsh-log-contract explain S9 --json # one rule: title, criteria, control pointers
399
347
  ```
400
348
 
401
- Full catalog in [docs/CONTRACTS.md](docs/CONTRACTS.md).
349
+ Full catalog: [docs/CONTRACTS.md](docs/CONTRACTS.md).
402
350
 
403
351
  ### 5. Session archaeology (`extract` / `audit-report`)
404
352
 
405
- Every tool call's full input/output is persisted in the session log — a data and
406
- audit asset. Read-only archaeology:
353
+ Every tool call's full input/output is persisted in the session log — a data and audit
354
+ asset. Read-only archaeology:
407
355
 
408
- ```sh
356
+ ```bash
409
357
  # Export tool outputs matching a command regex (original text preserved)
410
- dsh-log-contract extract <session-log> --pattern "build-report" --min-size 50 --out ./found
358
+ pnpm exec dsh-log-contract extract <session-log> --pattern "build-report" --min-size 50 --out ./found
411
359
 
412
- # Archaeology audit report: call count / pairing rate / orphans / command distribution
413
- dsh-log-contract audit-report <session-log>
360
+ # Audit report: call count / pairing rate / orphans / command distribution
361
+ pnpm exec dsh-log-contract audit-report <session-log>
414
362
  ```
415
363
 
416
- Contract rules P3 (tool/call↔tool/result pairing integrity) and P4 (output
417
- structure parseable) keep the dig working: orphan calls and abnormal `text` fields
418
- are flagged in `check`.
364
+ Contract rules **P3** (tool/call ↔ tool/result pairing integrity) and **P4** (output
365
+ structure parseable) keep the dig working: orphan calls and abnormal `text` fields are
366
+ flagged in `check`.
367
+
368
+ ## Case log — why "production-grade" is not a slogan
419
369
 
420
- ---
370
+ Each entry is a **real log-corruption shape** from production sessions — the cases that
371
+ shaped this tool. Dates and shapes are real; session ids and file names are omitted.
372
+
373
+ | # | Date | What happened | The rule / fix it produced |
374
+ |---|---|---|---|
375
+ | 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 |
376
+ | 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` |
377
+ | 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` |
378
+ | 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 |
379
+ | 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 request stream. | **W1 / W2** (wire message flow) |
380
+ | 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. The 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` |
381
+ | 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** (first frame = exactly one header line; body framed) |
382
+ | 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 |
383
+ | 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 |
384
+ | 10 | 2026-09-17 | On **Windows**, `header.cwd` was judged with POSIX-only rules → **every** session flagged by **H2**. | platform-aware absolute-path check |
385
+ | 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 |
386
+ | 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 |
387
+ | 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 |
388
+ | 14 | 2026-10-20 | An **unknown but explicitly ignorable** event type blocked an entire migration. | **G4** declarative skip + allow-list |
389
+ | 15 | 2026-10-26 | A **truncated zstd frame** made the session-header reader throw `ERR_OUT_OF_RANGE`; with no per-item isolation the whole enumeration/summary run failed (hundreds of failures over 33 days) — one damaged file sank the whole batch. | **R4** (read/parse tolerance: structured, countable result), **R5** (per-item isolation + failure counting) |
390
+ | 16 | 2026-10-26 | A file whose **last frame was cut mid-write** still reported `ok=true` — the check certifies only the events it actually read. | **Z6** (`tailStatus: complete/interrupted/truncated/unknown`) + the documented tail boundary |
391
+ | 17 | 2026-10-26 | Producers **inventing `seq` on the write side**, and **deleting rows without renumbering**. | **E11** (`seq` assigned by the log layer only; pre-write rejects self-invented `seq`), gap traces pinned to `E2` / `S9` |
392
+
393
+ > **Takeaway:** these rules are not synthetic theory — each one is pinned by a regression
394
+ > test that reproduces the corrupt shape it guards against. That is what "production-grade"
395
+ > means here.
421
396
 
422
397
  ## Node API (embed pre-write validation in your script)
398
+
423
399
  ```js
424
400
  import { loadSessionLog, validateSessionLog, createPreWriter } from 'dsh-log-contract';
425
401
 
@@ -433,8 +409,8 @@ const prewriter = createPreWriter({ events: log.events.map((e) => e.event) });
433
409
  const verdict = prewriter.validateAppend({
434
410
  type: 'assistant/message',
435
411
  surfaceOp: { op: 'replace', start: 121774, end: 156421 },
436
- sourceEventSeqs: [121774, 121779 /* …must fully cover shadowed nodes… */],
437
- data: { turn: null, step: null, message: { /* … */ } },
412
+ sourceEventSeqs: [121774, 121779], // must fully cover shadowed nodes
413
+ data: { turn: null, step: null, message: {} },
438
414
  });
439
415
  if (!verdict.ok) {
440
416
  for (const v of verdict.violations) console.error(v.id, v.message);
@@ -443,136 +419,75 @@ if (!verdict.ok) {
443
419
  // ③ Only a pass writes
444
420
  ```
445
421
 
446
- ---
422
+ ## Versioning and compatibility
447
423
 
448
- ## Tests
449
- ```bash
450
- pnpm check && pnpm test # syntax check + contract-doc drift gate + all unit tests
451
- ```
424
+ Three independent axes:
452
425
 
453
- - **Synthetic fixtures** (in-repo): legal session / seq gap / empty sourceEventSeqs
454
- / turn-null append / unknown type / bad chunk row / torn tail frame / unknown
455
- marker prefix / self-shadowing etc.
456
- - **Negative controls are mandatory**: every rule must have a violating sample
457
- that turns red and a compliant sample that stays green (the incident-derived
458
- fixtures above double as those controls).
459
- - **Rules self-test** (`test/rules-self-test.test.js`): registry completeness,
460
- `violation(id)` binding, test coverage per rule (or an explicit justified
461
- delegation), and "every emitted id is registered" — so a rule cannot exist
462
- without a control, and a control cannot reference a rule that was never
463
- registered.
426
+ | axis | where it lives | current |
427
+ |---|---|---|
428
+ | package version | npm / `package.json` | see the badge above |
429
+ | session format version | `header.version` in the log | v0–v4 |
430
+ | report structure version | `schemaVersion` in `check --json` | **`"6"`** |
464
431
 
465
- > The dev gate `scripts/check-tag-surface.mjs --json` also reports `clean` (the compliant tag list, mutually exclusive with `violations`), so "green" on the tag surface is an explicit list — not merely an empty `violations` array.
432
+ `schemaVersion` history (each step is additive; old consumers ignore unknown keys):
466
433
 
467
- > **Scope of the published package**: it contains the runtime code and documentation only.
468
- > Local maintainer tooling is not part of the public repository, so `pnpm check` and `pnpm test`
469
- > work from a clean clone.
434
+ | version | added | compatible reading |
435
+ |---|---|---|
436
+ | `"1"` | base `check` report | pre-field reports are read as `"1"` |
437
+ | `"2"` | S9 diagnosis fields (`category` / `confidence` / `hint` / `basis` / `diagnosis`) | v1 consumers can ignore the added fields |
438
+ | `"3"` | `identity` section (version-identity) | v2 consumers ignore the section |
439
+ | `"4"` | `runContract` section (3 rules) | v3 consumers ignore the section |
440
+ | `"5"` | run-contract +R-2b / R-6 (5 rules) | v4 consumers ignore new rule entries |
441
+ | `"6"` | run-contract +R-2b-2 / R-5 (7 rules); archive `unverifiable` on not-ready readers | v5 consumers ignore new rule entries |
442
+
443
+ - Package version, session format version and report schema version are **not**
444
+ interchangeable; a docs-only change does not change the rule set or `schemaVersion`.
445
+ - Version map: [VERSIONS.md](VERSIONS.md). Per-release notes: [CHANGELOG.md](CHANGELOG.md).
446
+ - Host support: tested against `@deepseek-ai/dsh-session` **0.2.0-rc.2**; declared peer range
447
+ `^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.1.7-rc.2 || ^0.2.0-rc.1`. A file newer than the host
448
+ supports is reported as *not assessable* (exit 3, read-only), never judged by stale rules.
449
+
450
+ ## FAQ
451
+
452
+ **Does `ok: true` mean the session is "usable"?** It means *nothing this rule set looks at
453
+ is broken*. It does not promise content quality; when the file needs a format migration the
454
+ assessment scope is `partial` — the migration dimension is only partly covered (`--json` →
455
+ `assessmentScope` / `migration.coverage.uncovered`).
456
+
457
+ **The tail is cut off — why still green?** The check certifies only what it read. Read
458
+ `summary.tailStatus`: `interrupted` (torn tail, recoverable) is not the same as `truncated`
459
+ (records actually missing).
460
+
461
+ **What is the identity digest for?** It catches "same version number, different content" —
462
+ the class of bug where consumers silently run an old build. The registry is
463
+ `docs/identity-registry.json`; re-register with `pnpm identity:register` after a version bump
464
+ or runtime-code change (source checkout only). In an npm install the registry is absent, so
465
+ `identity.ok` is `null` — unverifiable, never "pass".
466
+
467
+ **What does S9's diagnosis mean?** Besides the violation itself, S9 reports a cause category:
468
+ `old-cursor-replay` (stale in-memory cursor resumed after a tail rewrite), `concurrent-writer`
469
+ (two writers interleaved) or `format-mix` (legacy and modern event shapes mixed), with a
470
+ confidence and a decision basis (`category` / `confidence` / `hint` / `basis`); the verdict
471
+ does not change.
472
+
473
+ **How are the rules verified?** Every rule ships positive/negative controls; the suite also
474
+ runs a rules self-test (registry completeness, id binding, per-rule coverage, and "every
475
+ emitted id is registered"). See [Tests](#tests).
470
476
 
471
- ## Local git hooks (opt-in)
472
- The repository ships `.githooks/pre-push` (runs `pnpm check` before pushing), but it is
473
- **not active automatically on clone** — point Git at it explicitly:
477
+ ## Tests
474
478
 
475
479
  ```bash
476
- git config core.hooksPath .githooks # enable
477
- git config --get core.hooksPath # verify: should print .githooks
480
+ pnpm check && pnpm test # doc drift check + full suite (positive/negative controls + rules self-test)
478
481
  ```
479
482
 
480
- Skip only for emergencies: `git push --no-verify`. Uninstall: `git config --unset core.hooksPath`.
481
-
482
- > Hooks are local convenience, not a trust boundary: CI (`.github/workflows/ci.yml`) runs
483
- > `pnpm check` / `pnpm check:strict` / `pnpm test`, so clones without hooks stay gated.
484
-
485
- Verdict by **log shape** — what the tool must say about each defect class, not about
486
- any particular file:
487
-
488
- | Log shape | Verdict | Rules that fire |
489
- |---|---|---|
490
- | seq gap, or non-monotonic file-physical order | FAIL | S8 / C1 / T1 / E2 (plus S9 when seq goes backwards) |
491
- | a rewrite that introduces a gap | FAIL | S8 / C1 / T1 / E2 / I1 |
492
- | invalid inbox splice + turn-null marker | FAIL | T1 / I1 |
493
- | pre-fix shape: legacy turn-null markers still present | FAIL | T1 |
494
- | a multi-thousand-span replace marker with full coverage | PASS | error 0 — data-legal, official `foldSurface` replays cleanly |
495
-
496
- Rule evolution moves rows: 0.3.5 added I1, which flipped the "invalid inbox splice"
497
- shape from PASS to FAIL. And "a repaired session passes" holds only for the repaired
498
- artifact — the pre-repair form of the same session is normally still a FAIL. See the
499
- boundary note in [docs/CONTRACTS.md](docs/CONTRACTS.md).
500
-
501
- ---
502
-
503
- ## ⚠️ Upgrading — behaviour notes (0.3.12 → 0.3.28)
504
-
505
- ### 0.3.24 → 0.3.28 in one paragraph
506
-
507
- Four rules were added (`R4`/`R5` read tolerance and aggregation isolation,
508
- `E11` seq provenance on the write side, `Z6` tail completeness) and three
509
- machine-readable fields appeared in `--json` (`summary.tailStatus`,
510
- `summary.tailStatusReason`, `summary.unreadableRows`). Behaviour changes are narrow: `check` now emits a
511
- `Z6` **warning** when the tail is not `complete` (verdicts and exit codes are
512
- unchanged — a torn tail is recoverable under the host reader semantics), and
513
- `prewrite` rejects a candidate that carries a self-invented `seq` (`E11`, error).
514
- Rule count: 51 → 55.
515
-
516
- ### 0.3.18 → 0.3.24 in one paragraph
517
-
518
- Session format **v4** (host `dsh-session` 0.2.x) is supported by version dispatch (`tool/result` role,
519
- `system/message` source); five rules were added (`G4` unknown-but-ignorable events, `S10` reference element
520
- types, `I2` `seedLength` semantics, `P5` carrier pairing, `A1` structured-only in-place restorability);
521
- large sessions (> 500 MB) are read line-wise and repaired with streaming frames; the Windows absolute-path
522
- check for `H2` is platform-aware. still **partial** — see the changelog's known-gap list). Verdicts, exit codes and `--json` fields are unchanged.
523
-
524
- > **0.3.17 changes no behaviour.** It only adjusts the wording of comments, test titles, a few
525
- > diagnostic strings and the README. Every verdict, exit code and `--json`
526
- > field is unchanged from 0.3.15, so everything below applies unchanged when going from 0.3.12 to 0.3.17.
527
- >
528
- > 0.3.15 was a documentation-only release as well.
529
-
530
- **1. New exit codes `3` / `4` — a defect fix that is also a breaking change.**
531
- - `3` = **not assessable on this host**: the file's `header.version` is higher than the host supports
532
- (e.g. checking a v3 log under `@deepseek-ai/dsh-session@0.1.0-rc.7`). Instead of reporting `broken`,
533
- the tool now says the host lacks the capability, and `fix --apply` **refuses** the file (nothing written, no backup).
534
- - `4` = **migration pre-check blocked**: the tool judges that the official upgrade chain will refuse the file.
535
- - ⚠️ **Pipelines that treated `exit 0` as "fine" will now fail.** The old behaviour returned `0` even for files
536
- the tool itself reported as refused by the official chain — a false negative where the exit code contradicted
537
- the verdict. `--fail-on-migration` is an **explicit alias of the (now default) behaviour**; the **real opt-out
538
- is `--no-fail-on-migration`**, which restores the 0.3.11 behaviour (structural green ⇒ `exit 0`). When both
539
- flags are given, the opt-out wins. You can also ignore the exit code and read `assessmentScope` /
540
- `migration.ready` from `--json` with your own threshold.
541
-
542
- **2. `--json` gains `assessmentScope` (three values).**
543
-
544
- | value | meaning |
545
- |---|---|
546
- | `full` | file is already the host's target format (no migration) — coverage is complete |
547
- | `partial` | file needs migration ⇒ the migration pre-check covers **2 rules only; 6 classes are uncovered** (≠ pass; see `coverage.uncovered`) |
548
- | `none` | **not assessable on this host** — no "usable / upgradable" claim is certified |
549
-
550
- Under `partial` the CLI no longer prints an unconditional green: both the migration line and the last line say
551
- the migration dimension is only partially covered.
552
-
553
- **3. What "the health check passed" does *not* mean.**
554
- The rule set is **not** the official upgrade chain's acceptance condition. `assessmentScope=partial` means
555
- "the part this tool looked at is clean" — it does **not** mean the official upgrade will accept the file.
556
- Read `coverage.uncovered` for the known gaps.
557
-
558
- ## Roadmap
559
- - [x] **Phase 1 (0.1.0)**: CLI offline check + pre-write validation + contract catalog
560
- - [x] **Phase 1.5 (0.2.0)**: `fix` subcommand (strict seq scan + W1/W2 wire checks +
561
- marker removal with renumbering + official frame rebuild); CI integration
562
- (`dsh-log-contract check` as a scheduled guard over the Harness session dir)
563
- - [x] **0.3.x (2026-08-30 case hardening)**: T1 token-meter pairing → 0.3.1 W1/W2
564
- fold-position fix → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize` (in-place
565
- turn-null neutralization) → 0.3.4 `fix --clip-crossstep` (cross-step clipping) →
566
- 0.3.5 **T2/S9/I1 rules** (cross-step source refs / physical order / inbox replay)
567
- - [x] **0.3.6 → 0.3.15**: per-version rule routing for v0–v3 (T3/T4/T5, L3–L5, E8/E9/E10),
568
- exit codes `3`/`4` for the host-capability and migration gates, and a version-support
569
- report that says what was *not* verified (see [CHANGELOG.md](CHANGELOG.md))
570
- - [ ] Phase 2: runtime guard (subscribe to the session append stream, validate live,
571
- mark violations as `dsh/contract-violation`, policy configurable alert/block) —
572
- DSH plugin form
573
- - [ ] Phase 3: link with dsh-turn-guard / dsh-retrace timeline
483
+ - **Synthetic fixtures** (in-repo): legal session / seq gap / empty `sourceEventSeqs` /
484
+ turn-null append / unknown type / bad chunk row / torn tail frame / unknown marker prefix /
485
+ self-shadowing.
486
+ - **Negative controls are mandatory**: every rule must have a violating sample that turns red
487
+ and a compliant sample that stays green.
488
+ - **Rules self-test**: registry completeness, `violation(id)` binding, per-rule coverage (or
489
+ an explicit justified delegation), and "every emitted id is registered".
574
490
 
575
491
  ## License
576
- MIT © OfferKuai Team
577
492
 
578
- ---
493
+ MIT © OfferKuai Team