dsh-log-contract 0.3.26 → 0.3.29
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 +104 -22
- package/README.zh.md +84 -23
- package/bin/dsh-log-contract.mjs +5 -5
- package/docs/CONTRACTS.md +31 -3
- package/lib/archaeology.js +38 -22
- package/lib/checks.js +1 -1
- package/lib/contracts.js +37 -5
- package/lib/log-reader.js +71 -6
- package/lib/prewrite.js +17 -1
- package/lib/repair.js +1 -1
- package/lib/validate.js +31 -3
- package/package.json +6 -2
package/README.md
CHANGED
|
@@ -25,12 +25,21 @@ plugin marker semantics).
|
|
|
25
25
|
|
|
26
26
|
- **`check <session-log>`** — offline health check: official decoder full decode +
|
|
27
27
|
per-rule contract validation + foldSurface final verification, with a violation
|
|
28
|
-
report.
|
|
28
|
+
report and a machine-readable **tail-completeness** field (`tailStatus`).
|
|
29
29
|
- **`prewrite <edit-file> --log <session-log>`** — ★ pre-write validation: any
|
|
30
30
|
write (append / frame-level surgery) passes the three-layer contract before it
|
|
31
|
-
lands; violations are blocked.
|
|
31
|
+
lands; violations are blocked (including self-invented `seq` values).
|
|
32
32
|
- **`contracts`** — list the built-in contract rule catalog (each with its
|
|
33
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** · 55 contract rules ·
|
|
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).
|
|
34
43
|
|
|
35
44
|
---
|
|
36
45
|
|
|
@@ -67,7 +76,7 @@ line-by-line verification against the official Host source (each rule carries it
|
|
|
67
76
|
---
|
|
68
77
|
|
|
69
78
|
## Three-layer contract (the model)
|
|
70
|
-
>
|
|
79
|
+
> 55 rules across the layers below (`contracts` lists them all, each with its
|
|
71
80
|
> official source reference).
|
|
72
81
|
|
|
73
82
|
| Layer | Rules | What it guards |
|
|
@@ -76,6 +85,8 @@ line-by-line verification against the official Host source (each rule carries it
|
|
|
76
85
|
| **Client engine** | **M1** + **T1 / T2 / I1** | turn-null markers only as replace; token-meter pairing; cross-step source refs; inbox seed-relative replay |
|
|
77
86
|
| **Wire message flow** | **W1 / W2** | tool messages follow an assistant with tool_calls; no user text between tool_calls and results |
|
|
78
87
|
| **Plugin semantics** | P1/P2 | marker id prefixes recognizable; a marker's seq not in its own shadowed set |
|
|
88
|
+
| **Framing** | Z1–Z6 | zstd frame shape (header own first frame; no single-frame re-compression), empty-shell sessions, **tail completeness (`tailStatus`)** |
|
|
89
|
+
| **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 |
|
|
79
90
|
|
|
80
91
|
> Philosophy: first an incremental replay with official-equivalent semantics for
|
|
81
92
|
> **per-event attribution** (pinpoint seq/line), then the official `foldSurface` as
|
|
@@ -88,18 +99,18 @@ line-by-line verification against the official Host source (each rule carries it
|
|
|
88
99
|
|
|
89
100
|
| Item | Baseline | Note |
|
|
90
101
|
|---|---|---|
|
|
91
|
-
| Host package | `@deepseek-ai/dsh-session@0.
|
|
92
|
-
| Session format | **
|
|
93
|
-
| Declared range | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1` | installable — a declared range is **not** a per-version verification |
|
|
94
|
-
| Known formats | 0 / 1 / 2 / 3 | 0–2 are supported by this package's **vendored** vocabulary + local equivalent fold (`legacyFoldSurface`), independent of the host |
|
|
102
|
+
| 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) |
|
|
103
|
+
| Session format | **v4** (`SESSION_FORMAT_VERSION = 4`) | v4 uses the runtime vocabulary + official `foldSurface` final check |
|
|
104
|
+
| Declared range | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1` | installable — a declared range is **not** a per-version verification |
|
|
105
|
+
| 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 |
|
|
95
106
|
|
|
96
107
|
**What happens on unverified versions (detected and reported at runtime — never silently judged by stale rules)**:
|
|
97
108
|
|
|
98
109
|
| Case | Behaviour |
|
|
99
110
|
|---|---|
|
|
100
111
|
| 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 |
|
|
101
|
-
| Host older than the baseline (still in peer range) | notice + the host-capability gate decides whether
|
|
102
|
-
| **Unknown** session format (not in 0/1/2/3) | reported as **unverified format** and handled **read-only**: `check` runs structure rules only; `prewrite` / `fix` **refuse** (exit 3) |
|
|
112
|
+
| 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) |
|
|
113
|
+
| **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) |
|
|
103
114
|
| Format **unrecognisable** (no `header.version` and no distinguishing event shapes) | same: "unverified format" + read-only |
|
|
104
115
|
| File version above the host's supported maximum | `not-assessable` (**not** broken), exit 3; skipped/executed rules are listed |
|
|
105
116
|
|
|
@@ -107,9 +118,39 @@ Implementation: `lib/version-support.js` (`TESTED_BASELINE` / `detectSupport()`,
|
|
|
107
118
|
Both the human-readable `check` output and the `--json` `support` field carry the baseline summary and the warnings, e.g.:
|
|
108
119
|
|
|
109
120
|
```
|
|
110
|
-
version support: host @deepseek-ai/dsh-session@0.
|
|
121
|
+
version support: host @deepseek-ai/dsh-session@0.2.0-rc.2 (baseline 0.2.0-rc.2) | file format v4 (header, baseline)
|
|
111
122
|
```
|
|
112
123
|
|
|
124
|
+
## 🆕 0.3.28 · Reader tolerance, tail completeness, seq provenance
|
|
125
|
+
Four rules distilled from recent production failures (each pinned by a
|
|
126
|
+
negative-control test — a violating sample must turn red, a compliant one green):
|
|
127
|
+
|
|
128
|
+
| Rule | Checks | Severity |
|
|
129
|
+
|---|---|---|
|
|
130
|
+
| `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 |
|
|
131
|
+
| `R5` | aggregation/summary APIs isolate failures **per item** (per-item `try/catch` + a `skipped` counter); one bad item must not sink the batch | error |
|
|
132
|
+
| `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 |
|
|
133
|
+
| `Z6` | tail completeness must be declared: `tailStatus: complete \| interrupted \| truncated \| unknown` (see the known boundary below) | warning |
|
|
134
|
+
|
|
135
|
+
Also in 0.3.28: **rules self-test** — the registry, the tests and the generated
|
|
136
|
+
docs are cross-checked (`test/rules-self-test.test.js`): every rule must be
|
|
137
|
+
referenced by a control or a binding assertion in the tests (or carry an
|
|
138
|
+
explicit, justified delegation entry; the red/green strength of each control is
|
|
139
|
+
owned by that rule's own negative-control cases); every emitted violation id
|
|
140
|
+
must be registered. `summary.unreadableRows` and
|
|
141
|
+
`summary.tailStatus` are new machine-readable fields.
|
|
142
|
+
|
|
143
|
+
**Known boundary (stated honestly)**: `check` / `check --json` guarantee that
|
|
144
|
+
**the events actually read** are self-consistent — they do **not** guarantee the
|
|
145
|
+
file tail is intact. A file whose last frame was cut mid-write can still come
|
|
146
|
+
back `ok=true`; read `summary.tailStatus` (`--json`) to know the tail state.
|
|
147
|
+
`tailStatus` values: `complete` (tail intact) · `interrupted` (torn zstd tail —
|
|
148
|
+
in-flight/interrupted write; the host reader keeps complete records and drops
|
|
149
|
+
the unfinished tail, so it is recoverable) · `truncated` (the tail record itself
|
|
150
|
+
is cut — data is missing) · `unknown` (undecidable: unreadable/empty file).
|
|
151
|
+
`Z6` reports the non-`complete` states as a warning and deliberately does not
|
|
152
|
+
flip `ok`.
|
|
153
|
+
|
|
113
154
|
## 🆕 0.3.18 – 0.3.24 · DSH 0.2.x (session format v4) support
|
|
114
155
|
**Session format v4** (`@deepseek-ai/dsh-session` 0.2.x) is now validated by format-version dispatch
|
|
115
156
|
rather than by relaxing the format gate:
|
|
@@ -119,7 +160,8 @@ rather than by relaxing the format gate:
|
|
|
119
160
|
- validation for v3 and earlier is **unchanged** (identical verdicts on 408 real v3 sessions before/after)
|
|
120
161
|
- the format gate still rejects **unknown** future versions (`readOnly`); v5+ remains unassessable by design
|
|
121
162
|
|
|
122
|
-
**
|
|
163
|
+
**Rules (55 total as of 0.3.28):** the five rules below were added in the
|
|
164
|
+
0.3.18 – 0.3.24 window (see above for the 0.3.28 additions):
|
|
123
165
|
|
|
124
166
|
| Rule | Checks |
|
|
125
167
|
|---|---|
|
|
@@ -129,7 +171,7 @@ rather than by relaxing the format gate:
|
|
|
129
171
|
| `P5` | two-segment carrier pairing: 2nd segment's first seq == 1st segment seq (read side accepts the legacy order) |
|
|
130
172
|
| `A1` | "in-place restorable" is judged from structured fields only (`archiveRef` / `archive` / `externalized.*`) — never from free text |
|
|
131
173
|
|
|
132
|
-
**Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~
|
|
174
|
+
**Large sessions:** reading is line-wise (no whole-file stringification ⇒ no `ERR_STRING_TOO_LONG` above ~[size]),
|
|
133
175
|
and repair rebuilds `.jsonl.zstd` with streaming frames (header frame + chunked body frames, per-frame checksum + round-trip).
|
|
134
176
|
|
|
135
177
|
**Windows:** the `header.cwd` absolute-path check in `H2` is platform-aware (`win32` and `posix` both accepted).
|
|
@@ -153,10 +195,13 @@ omitted.
|
|
|
153
195
|
| 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 | |
|
|
154
196
|
| 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 | |
|
|
155
197
|
| 10 | 2026-09-17 | On **Windows**, `header.cwd` was judged with POSIX-only rules → **every** session flagged by **H2** ⇒ platform-aware absolute-path check | |
|
|
156
|
-
| 11 | 2026-10-20 | A **>
|
|
198
|
+
| 11 | 2026-10-20 | A **> [size] session** crashed the reader (`ERR_STRING_TOO_LONG`) and repair built the whole text in memory ⇒ line-wise decode + streaming frame rebuild | |
|
|
157
199
|
| 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 | |
|
|
158
200
|
| 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 | |
|
|
159
201
|
| 14 | 2026-10-20 | An **unknown but explicitly ignorable** event type blocked an entire migration ⇒ **G4** declarative skip + allow-list | |
|
|
202
|
+
| 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) |
|
|
203
|
+
| 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 |
|
|
204
|
+
| 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` |
|
|
160
205
|
|
|
161
206
|
> **Takeaway**: these rules are not synthetic theory — each one is pinned by a
|
|
162
207
|
> regression test that reproduces the corrupt shape it guards against. That is what
|
|
@@ -188,8 +233,8 @@ with the Harness read path).
|
|
|
188
233
|
### 1. Offline health check
|
|
189
234
|
|
|
190
235
|
```bash
|
|
191
|
-
dsh-log-contract check
|
|
192
|
-
dsh-log-contract check
|
|
236
|
+
dsh-log-contract check [path]<id>.jsonl.zstd
|
|
237
|
+
dsh-log-contract check [path]<id>.jsonl.zstd --json # machine-readable
|
|
193
238
|
```
|
|
194
239
|
|
|
195
240
|
Sample output (the CLI reports in Chinese — it is the tool's UI language):
|
|
@@ -205,8 +250,23 @@ Sample output (the CLI reports in Chinese — it is the tool's UI language):
|
|
|
205
250
|
❌ 未通过:见上方违规明细(error 级 = 会话不可读/不可写)
|
|
206
251
|
```
|
|
207
252
|
|
|
208
|
-
Exit
|
|
209
|
-
|
|
253
|
+
**Exit-code contract** (there is no exit code `2`):
|
|
254
|
+
|
|
255
|
+
| Code | Meaning |
|
|
256
|
+
|---|---|
|
|
257
|
+
| `0` | pass — no error-level violations (and the migration pre-check is not blocked) |
|
|
258
|
+
| `1` | error-level violations exist (session unreadable/unwritable under this rule set) |
|
|
259
|
+
| `3` | not assessable on this host (file format newer than the host supports) — **not** "broken" |
|
|
260
|
+
| `4` | the migration pre-check is blocked (the official upgrade chain will refuse the file) |
|
|
261
|
+
|
|
262
|
+
**Three-tier verdict** (`check --resume`, also in `--json` as `resume`):
|
|
263
|
+
`loadable` (structure green) ⊂ `resumable` (+ `I1` inbox replay green) ⊂
|
|
264
|
+
`compactable` (+ `T1`/`T2` token-meter pairing green); a file failing the first
|
|
265
|
+
tier is reported as `broken`, and `not-assessable` is a separate fourth state
|
|
266
|
+
when the host cannot judge the file.
|
|
267
|
+
|
|
268
|
+
**Tail-completeness boundary**: `ok=true` only certifies that *the events actually
|
|
269
|
+
read* are self-consistent — see the `tailStatus` note in the 0.3.28 section above.
|
|
210
270
|
|
|
211
271
|
`check` adds **W1/W2 wire-level checks** since 0.2.0: expand the model request
|
|
212
272
|
stream in surface order and catch "dangling tool messages" (a tool result with no
|
|
@@ -218,11 +278,11 @@ results" — tolerated by some endpoints, `INVALID_REQUEST` on strict ones
|
|
|
218
278
|
|
|
219
279
|
```bash
|
|
220
280
|
# Dry run (report only): strict seq scan + full contract check + removable-marker count
|
|
221
|
-
dsh-log-contract fix
|
|
281
|
+
dsh-log-contract fix [path]<id>.jsonl.zstd --remove-markers
|
|
222
282
|
|
|
223
283
|
# Apply: backup first, then write (.zstd rebuilt in official frame format: frame1=header,
|
|
224
284
|
# frame2=rest, checksum, single trailing newline)
|
|
225
|
-
dsh-log-contract fix
|
|
285
|
+
dsh-log-contract fix [path]<id>.jsonl.zstd --remove-markers --apply
|
|
226
286
|
```
|
|
227
287
|
|
|
228
288
|
- `--remove-markers`: remove retrace/message-editor markers and renumber everything
|
|
@@ -253,11 +313,14 @@ dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
|
|
|
253
313
|
```
|
|
254
314
|
|
|
255
315
|
```bash
|
|
256
|
-
dsh-log-contract prewrite marker-write.json --log
|
|
316
|
+
dsh-log-contract prewrite marker-write.json --log [path]<id>.jsonl.zstd
|
|
257
317
|
```
|
|
258
318
|
|
|
259
319
|
- A baseline with error-level violations is rejected outright (safety protocol
|
|
260
320
|
step 2: **the pre-surgery baseline must be green**).
|
|
321
|
+
- `seq` must be **omitted** (auto-assigned as `nextSeq`) or exactly `nextSeq` —
|
|
322
|
+
a self-invented `seq` is rejected (`E11`); on the file side, delete-without-
|
|
323
|
+
renumber and invented `seq` show up as gaps and are caught by `E2`/`S9`.
|
|
261
324
|
- Only a pass may land — **validate first, commit later** (same idea as the
|
|
262
325
|
official `SurfaceManager.validateNext`).
|
|
263
326
|
|
|
@@ -322,6 +385,14 @@ pnpm check && pnpm test # syntax check + contract-doc drift gate + all unit t
|
|
|
322
385
|
- **Synthetic fixtures** (in-repo): legal session / seq gap / empty sourceEventSeqs
|
|
323
386
|
/ turn-null append / unknown type / bad chunk row / torn tail frame / unknown
|
|
324
387
|
marker prefix / self-shadowing etc.
|
|
388
|
+
- **Negative controls are mandatory**: every rule must have a violating sample
|
|
389
|
+
that turns red and a compliant sample that stays green (the incident-derived
|
|
390
|
+
fixtures above double as those controls).
|
|
391
|
+
- **Rules self-test** (`test/rules-self-test.test.js`): registry completeness,
|
|
392
|
+
`violation(id)` binding, test coverage per rule (or an explicit justified
|
|
393
|
+
delegation), and "every emitted id is registered" — so a rule cannot exist
|
|
394
|
+
without a control, and a control cannot reference a rule that was never
|
|
395
|
+
registered.
|
|
325
396
|
|
|
326
397
|
> **Scope of the published package**: it contains the runtime code and documentation only.
|
|
327
398
|
> Local maintainer tooling is not part of the public repository, so `pnpm check` and `pnpm test`
|
|
@@ -359,14 +430,25 @@ boundary note in [docs/CONTRACTS.md](docs/CONTRACTS.md).
|
|
|
359
430
|
|
|
360
431
|
---
|
|
361
432
|
|
|
362
|
-
## ⚠️ Upgrading — behaviour notes (0.3.12 → 0.3.
|
|
433
|
+
## ⚠️ Upgrading — behaviour notes (0.3.12 → 0.3.28)
|
|
434
|
+
|
|
435
|
+
### 0.3.24 → 0.3.28 in one paragraph
|
|
436
|
+
|
|
437
|
+
Four rules were added (`R4`/`R5` read tolerance and aggregation isolation,
|
|
438
|
+
`E11` seq provenance on the write side, `Z6` tail completeness) and three
|
|
439
|
+
machine-readable fields appeared in `--json` (`summary.tailStatus`,
|
|
440
|
+
`summary.tailStatusReason`, `summary.unreadableRows`). Behaviour changes are narrow: `check` now emits a
|
|
441
|
+
`Z6` **warning** when the tail is not `complete` (verdicts and exit codes are
|
|
442
|
+
unchanged — a torn tail is recoverable under the host reader semantics), and
|
|
443
|
+
`prewrite` rejects a candidate that carries a self-invented `seq` (`E11`, error).
|
|
444
|
+
Rule count: 51 → 55.
|
|
363
445
|
|
|
364
446
|
### 0.3.18 → 0.3.24 in one paragraph
|
|
365
447
|
|
|
366
448
|
Session format **v4** (host `dsh-session` 0.2.x) is supported by version dispatch (`tool/result` role,
|
|
367
449
|
`system/message` source); five rules were added (`G4` unknown-but-ignorable events, `S10` reference element
|
|
368
450
|
types, `I2` `seedLength` semantics, `P5` carrier pairing, `A1` structured-only in-place restorability);
|
|
369
|
-
large sessions (>
|
|
451
|
+
large sessions (> [size]) are read line-wise and repaired with streaming frames; the Windows absolute-path
|
|
370
452
|
check for `H2` is platform-aware. still **partial** — see the changelog's known-gap list). Verdicts, exit codes and `--json` fields are unchanged.
|
|
371
453
|
|
|
372
454
|
> **0.3.17 changes no behaviour.** It only adjusts the wording of comments, test titles, a few
|
package/README.zh.md
CHANGED
|
@@ -22,9 +22,14 @@
|
|
|
22
22
|
|
|
23
23
|
给 DSH 会话日志(`*.jsonl` / `*.jsonl.zstd`)装一条保险丝:人眼看不出、程序解析会崩的日志格式漂移,在它这里被拦下并告警。它不判断日志**内容**对不对,只守护日志**结构**是否破坏了下游消费者(Harness 读路径、客户端引擎、插件 marker 语义)的预期。
|
|
24
24
|
|
|
25
|
-
- **`check <session-log>`** —— 离线体检:官方解码器全量解码 + 契约逐条校验 + foldSurface
|
|
26
|
-
- **`prewrite <edit-file> --log <session-log>`** —— ★ 写前校验:任何写入(追加 /
|
|
25
|
+
- **`check <session-log>`** —— 离线体检:官方解码器全量解码 + 契约逐条校验 + foldSurface 终验,产出违规报告,并给出机器可判的**尾部完整性**字段(`tailStatus`)。
|
|
26
|
+
- **`prewrite <edit-file> --log <session-log>`** —— ★ 写前校验:任何写入(追加 / 帧级手术)在落盘之前先过三层契约,违约即拦(含写侧自造 `seq`)。
|
|
27
27
|
- **`contracts`** —— 列出内置契约规则目录(每条附官方源码出处)。
|
|
28
|
+
- **`check --resume`** —— 三档结论(`loadable` / `resumable` / `compactable`,宿主判不了时另有 `not-assessable`)。
|
|
29
|
+
- **`fix` / `extract` / `audit-report`** —— 修复原语 + 只读会话考古。
|
|
30
|
+
|
|
31
|
+
**能力一览**:会话格式 **v0–v4** · 契约规则 **55 条** · 退出码契约 `0/1/3/4` · 三档结论 ·
|
|
32
|
+
写前校验 · 每条规则都有负对照用例 + 规则自检 · 读取容错(单文件损坏降级为结构化结果并计数,不抛出)。
|
|
28
33
|
|
|
29
34
|
---
|
|
30
35
|
|
|
@@ -53,7 +58,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
53
58
|
---
|
|
54
59
|
|
|
55
60
|
## 三层契约(判定模型)
|
|
56
|
-
>
|
|
61
|
+
> 55 条规则,覆盖以下各层(`contracts` 列出全部,每条附官方源码出处)。
|
|
57
62
|
|
|
58
63
|
| 层 | 规则 | 守护什么 |
|
|
59
64
|
|---|---|---|
|
|
@@ -61,6 +66,8 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
61
66
|
| **客户端引擎层** | **M1** + **T1 / T2 / I1** | turn-null marker 只能 replace;token-meter 配对;跨 step 源引用;inbox seed 相对重放 |
|
|
62
67
|
| **wire 消息流** | **W1 / W2** | tool 消息跟在带 tool_calls 的 assistant 之后;user 文本不插在 tool_calls 与结果之间 |
|
|
63
68
|
| **插件语义层** | P1/P2 | marker 前缀可识别;marker 自身 seq 不进自身 shadowed 集 |
|
|
69
|
+
| **帧结构层** | Z1–Z6 | zstd 帧形状(header 独占首帧;不得整体重压单帧)、空壳会话、**尾部完整性(`tailStatus`)** |
|
|
70
|
+
| **读取 / 聚合层** | **R4 / R5** | 单文件损坏必须降级为**结构化、可计数**结果(不抛出、不中断枚举/汇总);聚合 API 逐项隔离失败 |
|
|
64
71
|
|
|
65
72
|
> 校验哲学:先用与官方同语义的增量重放做**逐事件归因**(定位到 seq/行号),再跑官方 `foldSurface` 做**终验**(不抛才算过)——两套都绿才过。
|
|
66
73
|
|
|
@@ -71,18 +78,18 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
71
78
|
|
|
72
79
|
| 项 | 基线 | 说明 |
|
|
73
80
|
|---|---|---|
|
|
74
|
-
| 宿主包 | `@deepseek-ai/dsh-session@0.
|
|
75
|
-
| 会话格式 | **
|
|
76
|
-
| 声明范围 | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1` | 允许安装;**范围内不等于逐个验证过** |
|
|
77
|
-
| 已知格式 | 0 / 1 / 2 / 3 | 0–2 由本包**自带** vendored 词表 + 本地等价折叠(`legacyFoldSurface`)支持,与宿主版本无关 |
|
|
81
|
+
| 宿主包 | `@deepseek-ai/dsh-session@0.2.0-rc.2` | 本规则集开发与 CI 验证所用的版本(CI 跑 `pnpm check` + `pnpm test`;`prepublishOnly` 四步在本机该版本上全绿) |
|
|
82
|
+
| 会话格式 | **v4**(`SESSION_FORMAT_VERSION = 4`) | v4 走运行时词表 + 官方 `foldSurface` 终验 |
|
|
83
|
+
| 声明范围 | `peerDependencies: ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1` | 允许安装;**范围内不等于逐个验证过** |
|
|
84
|
+
| 已知格式 | 0 / 1 / 2 / 3 / 4 | 0–2 由本包**自带** vendored 词表 + 本地等价折叠(`legacyFoldSurface`)支持,与宿主版本无关 |
|
|
78
85
|
|
|
79
86
|
**未验证的版本会发生什么(运行时检测并报告,不闷着按旧规则判)**:
|
|
80
87
|
|
|
81
88
|
| 情形 | 行为 |
|
|
82
89
|
|---|---|
|
|
83
90
|
| 宿主**比基线新** | 明确**告警**(`⚠️ 宿主 … 比测试基线 … 新 —— 本规则集未在该宿主上验证…`);结论仍给出,但标注可能不适用 |
|
|
84
|
-
| 宿主比基线旧(仍在 peer 内) | 提示 +
|
|
85
|
-
| 被检文件格式**未知**(不在 0/1/2/3) | 报「**未验证格式**」并**按只读处理**:`check` 只跑结构层,`prewrite` / `fix` **直接拒绝**(退出码 3) |
|
|
91
|
+
| 宿主比基线旧(仍在 peer 内) | 提示 + 由宿主能力闸决定能否评估该文件格式(`SESSION_FORMAT_VERSION` 不足 ⇒ `not-assessable`,退出码 3) |
|
|
92
|
+
| 被检文件格式**未知**(不在 0/1/2/3/4) | 报「**未验证格式**」并**按只读处理**:`check` 只跑结构层,`prewrite` / `fix` **直接拒绝**(退出码 3) |
|
|
86
93
|
| 格式**无法识别**(无 `header.version` 且事件形状无判别特征) | 同上:报「未验证格式」+ 只读 |
|
|
87
94
|
| 文件版本 > 宿主支持上限 | `not-assessable`(**不是** broken),退出码 3;显式列出跳过/执行的规则 |
|
|
88
95
|
|
|
@@ -90,10 +97,33 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
90
97
|
`check` 的人类可读输出与 `--json` 的 `support` 字段都带基线摘要与逐条告警,例如:
|
|
91
98
|
|
|
92
99
|
```
|
|
93
|
-
版本支持:宿主 @deepseek-ai/dsh-session@0.
|
|
94
|
-
测试基线:@deepseek-ai/dsh-session@0.
|
|
100
|
+
版本支持:宿主 @deepseek-ai/dsh-session@0.2.0-rc.2(基线 0.2.0-rc.2,baseline) | 文件格式 v4(header,baseline)
|
|
101
|
+
测试基线:@deepseek-ai/dsh-session@0.2.0-rc.2 | 会话格式 v4(已知 0/1/2/3/4;peer ^0.1.0-rc.7 || ^0.1.5-rc.1 || ^0.2.0-rc.1)
|
|
95
102
|
```
|
|
96
103
|
|
|
104
|
+
## 🆕 0.3.28 · 读取容错 / 尾部完整性 / seq 来源
|
|
105
|
+
从近期真实故障中提炼的四条规则(每条都有负对照用例:违规样本必须判红、合规样本必须绿):
|
|
106
|
+
|
|
107
|
+
| 规则 | 判据 | 严重度 |
|
|
108
|
+
|---|---|---|
|
|
109
|
+
| `R4` | 读取/解析容错:单文件损坏(截断 zstd 帧、损坏行、坏 chunk 行、空文件)必须降级为**结构化、可计数**结果(null / 逐行 `error` 标记 / `frameInfo` 事实)——**不得抛出**、不得中断枚举/汇总 | error |
|
|
110
|
+
| `R5` | 汇总/枚举类 API **逐项隔离**失败(per-item try/catch + `skipped` 计数);一项坏不得毁掉整批 | error |
|
|
111
|
+
| `E11` | seq 只能由日志层连续光标分配:写侧拟写事件要么省略 `seq`(自动赋值)、要么恰好等于 `nextSeq`;生产者自造 seq / 删行不重编号的痕迹由 `E2`/`S9` 判红 | error |
|
|
112
|
+
| `Z6` | 尾部完整性必须显式声明:`tailStatus: complete \| interrupted \| truncated \| unknown`(见下方已知边界) | warning |
|
|
113
|
+
|
|
114
|
+
0.3.28 另含:**规则自检(rules self-test)**——注册表、测试、生成文档三者互检
|
|
115
|
+
(`test/rules-self-test.test.js`):每条规则必须在测试里有对照或绑定断言引用
|
|
116
|
+
(或显式登记"判定委托"并给出理由;对照的红/绿强度由各规则自己的负对照用例负责);
|
|
117
|
+
每个报出的违规码都必须已注册。`--json` 新增机器可判字段
|
|
118
|
+
`summary.tailStatus` 与 `summary.unreadableRows`。
|
|
119
|
+
|
|
120
|
+
**已知边界(如实表述)**:`check` / `check --json` 只保证"**已读到的事件**自洽",
|
|
121
|
+
**不保证尾部完整**——最后一帧在写入中被切掉的文件仍可能 `ok=true`;尾部状态请读
|
|
122
|
+
`summary.tailStatus`(`--json`)。取值:`complete`(尾部完整)· `interrupted`
|
|
123
|
+
(zstd 尾帧撕裂 = 写入中断/进行中;宿主读取器保留完整记录、丢弃未写完尾帧,可恢复)·
|
|
124
|
+
`truncated`(尾部记录本身被切,数据缺失)· `unknown`(不可判:不可读/空文件)。
|
|
125
|
+
非 `complete` 时 `Z6` 以 warning 报出,且**刻意不翻转** `ok`。
|
|
126
|
+
|
|
97
127
|
## 🆕 0.3.18 – 0.3.24 · 支持 DSH 0.2.x(会话格式 v4)
|
|
98
128
|
**会话格式 v4**(`@deepseek-ai/dsh-session` 0.2.x)改为**按格式版本分派规则**,而不是放宽格式闸门:
|
|
99
129
|
|
|
@@ -102,7 +132,8 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
102
132
|
- **v3 及更早的判据零改动**(408 份真实 v3 会话前后判定完全一致)
|
|
103
133
|
- 格式闸门仍**拒绝未知的未来版本**(`readOnly`);v5+ 按设计保持"不可评估"
|
|
104
134
|
|
|
105
|
-
|
|
135
|
+
**规则(0.3.28 起共 55 条)**:下表五条是 0.3.18 – 0.3.24 窗口新增
|
|
136
|
+
(0.3.28 新增的四条见上一节):
|
|
106
137
|
|
|
107
138
|
| 规则 | 判据 |
|
|
108
139
|
|---|---|
|
|
@@ -112,7 +143,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
112
143
|
| `P5` | 两段 carrier 配对:第 2 段首元素 = 第 1 段 seq(读侧兼容早期写法) |
|
|
113
144
|
| `A1` | 「在位可还原」**只认结构化字段**(`archiveRef`/`archive`/`externalized.*`),不从自由文本推断 |
|
|
114
145
|
|
|
115
|
-
|
|
146
|
+
**internal**:读取改为**按行解码**(不再整文件字符串化 ⇒ 约 [size] 以上不再抛 `ERR_STRING_TOO_LONG`);
|
|
116
147
|
修复采用**流式帧重建** `.jsonl.zstd`(header 帧 + 正文分块多帧,逐帧 checksum + roundtrip 校验)。
|
|
117
148
|
|
|
118
149
|
**Windows**:`H2` 的 `header.cwd` 绝对路径判断改为**平台感知**(`win32` 与 `posix` 都认)。
|
|
@@ -134,10 +165,13 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
|
|
|
134
165
|
| 8 | 2026-08-31 | **尾帧在写入中被撕裂**的日志完全无法加载、且没有诊断 ⇒ **Z1** + 明确报「尾帧撕裂 / 写入中」 | |
|
|
135
166
|
| 9 | 2026-09-09 | **会话格式 v4** 下 `tool/result` 改用 `role:'tool'`、`system/message` 带 `system-prompt` 来源 → v3 语义的检查在**健康 v4 日志**上产出**数千条误报** ⇒ 版本分派 + **E6/E9** v4 语义 | |
|
|
136
167
|
| 10 | 2026-09-17 | **Windows** 上 `header.cwd` 用 POSIX 规则判定 → **所有**会话被 **H2** 误报 ⇒ 平台感知的绝对路径判定 | |
|
|
137
|
-
| 11 | 2026-10-20 | **超过
|
|
168
|
+
| 11 | 2026-10-20 | **超过 [size] 的会话**让读取器崩溃(`ERR_STRING_TOO_LONG`),修复时又把全文拼进内存 ⇒ 按行解码 + 流式帧重建 | |
|
|
138
169
|
| 12 | 2026-10-20 | 两段式载体引用有的把「审计段」写在前面、早期约定从区间起点开始 → 读取侧报出**数百个假孤儿载体** ⇒ **P5** 写侧成对 + 读侧容错 | |
|
|
139
170
|
| 13 | 2026-10-20 | `seedLength` 被部分消费方当作**字节数**(其语义是「继承事件条数」),且 `parentSession` 配缺失/0 被当成损坏 ⇒ **I2** 语义钉死 | |
|
|
140
171
|
| 14 | 2026-10-20 | 一种**未知但显式可忽略**的事件类型让整条迁移卡死 ⇒ **G4** 声明式跳过 + 白名单 | |
|
|
172
|
+
| 15 | 2026-10-26 | 一个**截断 zstd 帧**让会话读头抛 `ERR_OUT_OF_RANGE`,而聚合循环没有逐项隔离 ⇒ 整个枚举/汇总能力失败(33 天内数百次)——**单文件损坏 ⇒ 整表失败** | **R4**(读取容错:降级为结构化、可计数结果)、**R5**(聚合 API 逐项隔离 + 失败计数) |
|
|
173
|
+
| 16 | 2026-10-26 | **最后一帧写入中被切**的文件仍报 `ok=true`——体检只认证已读到的事件 | **Z6**(`tailStatus: complete/interrupted/truncated/unknown`)+ 明示口径边界 |
|
|
174
|
+
| 17 | 2026-10-26 | 生产者**写侧自造 seq**、以及**删行不重编号** | **E11**(seq 由日志层分配;写前拒绝自造 seq)、缺口痕迹钉到 `E2`/`S9` |
|
|
141
175
|
|
|
142
176
|
|
|
143
177
|
> **结论**:这些规则不是合成理论——每一条都有回归测试复现它守护的那种损坏形态。这就是这里「生产级」的含义。
|
|
@@ -165,8 +199,8 @@ pnpm dlx dsh-log-contract --help
|
|
|
165
199
|
### 1. 离线体检
|
|
166
200
|
|
|
167
201
|
```bash
|
|
168
|
-
dsh-log-contract check
|
|
169
|
-
dsh-log-contract check
|
|
202
|
+
dsh-log-contract check [path]<id>.jsonl.zstd
|
|
203
|
+
dsh-log-contract check [path]<id>.jsonl.zstd --json # 机器可读
|
|
170
204
|
```
|
|
171
205
|
|
|
172
206
|
输出示例:
|
|
@@ -182,7 +216,20 @@ dsh-log-contract check ~/.dsh/sessions/<id>.jsonl.zstd --json # 机器可读
|
|
|
182
216
|
❌ 未通过:见上方违规明细(error 级 = 会话不可读/不可写)
|
|
183
217
|
```
|
|
184
218
|
|
|
185
|
-
|
|
219
|
+
**退出码契约**(没有退出码 `2`):
|
|
220
|
+
|
|
221
|
+
| 退出码 | 含义 |
|
|
222
|
+
|---|---|
|
|
223
|
+
| `0` | 通过——无 error 级违规(且迁移预检未 blocked) |
|
|
224
|
+
| `1` | 存在 error 级违规(本规则集下会话不可读/不可写) |
|
|
225
|
+
| `3` | 不可在本宿主评估(文件格式新于宿主支持上限)——**不是** "broken" |
|
|
226
|
+
| `4` | 迁移预检 blocked(官方升级链会拒绝该文件) |
|
|
227
|
+
|
|
228
|
+
**三档结论**(`check --resume`,`--json` 里为 `resume` 字段):
|
|
229
|
+
`loadable`(结构绿)⊂ `resumable`(+ `I1` inbox 重放绿)⊂ `compactable`
|
|
230
|
+
(+ `T1`/`T2` token-meter 配对绿);第一档就不过的报 `broken`,宿主判不了时是独立的第四态 `not-assessable`。
|
|
231
|
+
|
|
232
|
+
**尾部完整性边界**:`ok=true` 只认证"已读到的事件自洽"——详见 0.3.28 一节的 `tailStatus` 说明。
|
|
186
233
|
|
|
187
234
|
`check` 自 0.2.0 起新增 **W1/W2 wire 级检查**:按 surface 顺序展开模型请求消息流,
|
|
188
235
|
捕获"悬空 tool 消息"(tool 结果没有前置 assistant tool_calls)与"user 文本插在
|
|
@@ -193,10 +240,10 @@ tool_calls 与其结果之间"——这类问题 DeepSeek 曾容忍,但 MiMo
|
|
|
193
240
|
|
|
194
241
|
```bash
|
|
195
242
|
# 干跑(只报告):严格 seq 连续扫描 + 全契约体检(含 W1/W2)+ 可移除 marker 数
|
|
196
|
-
dsh-log-contract fix
|
|
243
|
+
dsh-log-contract fix [path]<id>.jsonl.zstd --remove-markers
|
|
197
244
|
|
|
198
245
|
# 应用:备份后落盘(.zstd 走官方帧格式重建:帧1=header、帧2=其余、checksum、单个结尾换行)
|
|
199
|
-
dsh-log-contract fix
|
|
246
|
+
dsh-log-contract fix [path]<id>.jsonl.zstd --remove-markers --apply
|
|
200
247
|
```
|
|
201
248
|
|
|
202
249
|
- `--remove-markers`:移除 retrace/message-editor marker 并全量重编号
|
|
@@ -222,10 +269,12 @@ dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
|
|
|
222
269
|
```
|
|
223
270
|
|
|
224
271
|
```bash
|
|
225
|
-
dsh-log-contract prewrite marker-write.json --log
|
|
272
|
+
dsh-log-contract prewrite marker-write.json --log [path]<id>.jsonl.zstd
|
|
226
273
|
```
|
|
227
274
|
|
|
228
275
|
- 基线本身有 error 级违规时直接拒绝校验(安全修复协议第 2 步:**改前基线必须绿**)。
|
|
276
|
+
- `seq` 必须**省略**(自动赋 `nextSeq`)或恰好等于 `nextSeq`——自造 `seq` 直接拒绝(`E11`);
|
|
277
|
+
文件侧的"删行不重编号 / 自造 seq"痕迹由 `E2`/`S9` 判红。
|
|
229
278
|
- 判定通过才允许落盘——**validate first, commit later**(与官方 `SurfaceManager.validateNext` 同思路)。
|
|
230
279
|
|
|
231
280
|
### 4. 契约目录
|
|
@@ -286,6 +335,10 @@ pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测
|
|
|
286
335
|
```
|
|
287
336
|
|
|
288
337
|
- **合成夹具**(入库):合法会话 / seq 缺口 / 空 sourceEventSeqs / turn=null append / 未知 type / 坏 chunk 行 / 撕裂尾帧 / 未知 marker 前缀 / 自指 shadowed 等。
|
|
338
|
+
- **负对照是硬要求**:每条规则都必须有"违规样本判红 + 合规样本绿"的对照用例(上面的案例回归夹具同时充当这些对照)。
|
|
339
|
+
- **规则自检**(`test/rules-self-test.test.js`):注册表完整性、`violation(id)` 绑定、
|
|
340
|
+
每条规则的测试对照覆盖(或显式登记的判定委托)、以及"每个报出的违规码都已注册"——
|
|
341
|
+
规则不可能没有对照而存在,对照也不可能引用未注册的规则。
|
|
289
342
|
|
|
290
343
|
> **发布包范围**:只含运行时代码与文档。维护者本地工具不在公开仓内,
|
|
291
344
|
> 因此 `pnpm check` / `pnpm test` 在干净的克隆里即可通过。
|
|
@@ -318,13 +371,21 @@ git config --get core.hooksPath # 验证:应输出 .githooks
|
|
|
318
371
|
|
|
319
372
|
---
|
|
320
373
|
|
|
321
|
-
## ⚠️ 升级说明(0.3.12 → 0.3.
|
|
374
|
+
## ⚠️ 升级说明(0.3.12 → 0.3.28)
|
|
375
|
+
|
|
376
|
+
### 0.3.24 → 0.3.28 一段话说清
|
|
377
|
+
|
|
378
|
+
新增四条规则(`R4`/`R5` 读取容错与聚合隔离、`E11` 写侧 seq 来源、`Z6` 尾部完整性),
|
|
379
|
+
`--json` 新增三个机器可判字段(`summary.tailStatus`、`summary.tailStatusReason`、`summary.unreadableRows`)。
|
|
380
|
+
行为变更很窄:尾部非 `complete` 时 `check` 会多报一条 `Z6` **warning**(判定结论与退出码
|
|
381
|
+
不变——撕裂尾帧在宿主读取器语义下可恢复);`prewrite` 拒绝携带自造 `seq` 的拟写事件
|
|
382
|
+
(`E11`,error)。规则数 51 → 55。
|
|
322
383
|
|
|
323
384
|
### 0.3.18 → 0.3.24 一段话说清
|
|
324
385
|
|
|
325
386
|
**会话格式 v4**(宿主 `dsh-session` 0.2.x)改为按版本分派判定(`tool/result` 的 role、`system/message` 的来源);
|
|
326
387
|
新增五条规则(`G4` 未知但可忽略事件、`S10` 引用元素类型、`I2` `seedLength` 语义、`P5` 载体配对、`A1` 只认结构化字段的在位可还原);
|
|
327
|
-
|
|
388
|
+
internal(>[size])按行读取 + 流式帧重建;Windows 的 `header.cwd` 判定改为平台感知。
|
|
328
389
|
> **0.3.17 不含行为变更。** 它只调整了注释、测试标题、少量诊断文案与 README 的措辞。
|
|
329
390
|
> 所有判定结果、退出码与 `--json` 字段与 0.3.15 完全一致,
|
|
330
391
|
> 因此从 0.3.12 升到 0.3.17 时,下面各条与原来完全一致。
|
|
@@ -345,7 +406,7 @@ git config --get core.hooksPath # 验证:应输出 .githooks
|
|
|
345
406
|
|
|
346
407
|
| 值 | 含义 |
|
|
347
408
|
|---|---|
|
|
348
|
-
| `full` |
|
|
409
|
+
| `full` | 被检文件已是当前宿主的目标格式(**无需迁移**),覆盖完整 |
|
|
349
410
|
| `partial` | 需要迁移 ⇒ 迁移预检**只覆盖 2 条规则,另有 6 类未覆盖**(≠ 通过;见 `coverage.uncovered`) |
|
|
350
411
|
| `none` | **不可在本宿主评估**(宿主能力不足),不认证任何"可用/可升级"结论 |
|
|
351
412
|
|
package/bin/dsh-log-contract.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, as
|
|
|
19
19
|
/**
|
|
20
20
|
* 同步写 fd——`process.stdout.write` 在**管道**下是异步的,紧跟着的
|
|
21
21
|
* `process.exit()` 不会等待 flush:>~64KiB 的输出会丢尾,`--json` 因此变成非法 JSON
|
|
22
|
-
* (实测在 3000 事件夹具与真实
|
|
22
|
+
* (实测在 3000 事件夹具与真实 [size] v3 会话上复现,stdout 56648B 处 "Unterminated string")。
|
|
23
23
|
* 这里直接同步写 fd 1/2(非阻塞管道 EAGAIN 时自旋重试),做到"先写完再 exit"。
|
|
24
24
|
*/
|
|
25
25
|
function writeAllSync(fd, text) {
|
|
@@ -146,7 +146,7 @@ function printViolations(violations, maxDetails = 8) {
|
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
|
|
149
|
-
/** 漂移抬头(2026-09-14):漂移清单 +
|
|
149
|
+
/** 漂移抬头(2026-09-14):漂移清单 + 未internal清单 + "勿据此跑 fix --apply"。 */
|
|
150
150
|
function driftLines(drift, probes) {
|
|
151
151
|
if (!drift) return '';
|
|
152
152
|
const host = probes ? `${probes.hostPackage}(SESSION_FORMAT_VERSION=${probes.sessionFormatVersion},词表 ${probes.knownTypes} 类)` : '未知';
|
|
@@ -158,10 +158,10 @@ function driftLines(drift, probes) {
|
|
|
158
158
|
if (drift.unverifiedRules.length > 0) {
|
|
159
159
|
out += ` ⛔ **UNVERIFIED**(探针与规则假设不一致,结论不可采信):${drift.unverifiedRules.join('、')}\n`;
|
|
160
160
|
}
|
|
161
|
-
out += `
|
|
161
|
+
out += ` 出处未internal(已知债,仅告警):${drift.driftedSources.join('、')}\n`;
|
|
162
162
|
out += ` 判定前提存疑(仅告警):${drift.premiseStale.join('、')}${drift.undecidable.length ? `;无法判定:${drift.undecidable.join('、')}` : ''}\n`;
|
|
163
163
|
if (drift.fixApplyBlocked) {
|
|
164
|
-
out += ' ⛔ **禁止据此跑 `fix --apply`**(存在未验证规则:写入类动作不可逆)——先按 report
|
|
164
|
+
out += ' ⛔ **禁止据此跑 `fix --apply`**(存在未验证规则:写入类动作不可逆)——先按 report internal这些规则或显式确认。\n';
|
|
165
165
|
}
|
|
166
166
|
return out;
|
|
167
167
|
}
|
|
@@ -451,7 +451,7 @@ function cmdContracts() {
|
|
|
451
451
|
for (const r of CONTRACT_RULES) {
|
|
452
452
|
const flags = [
|
|
453
453
|
r.candidate ? '候选规则' : null,
|
|
454
|
-
r.sourceVerified === false ? '
|
|
454
|
+
r.sourceVerified === false ? '出处未internal' : null,
|
|
455
455
|
r.premiseStale ? '判定前提存疑' : null,
|
|
456
456
|
].filter(Boolean).join(' / ');
|
|
457
457
|
out(` ${r.id} [${r.severity}/${r.layer}] ${r.title}${flags ? ` ⟪${flags}⟫` : ''}\n ${r.description}\n 出处: ${r.source}\n\n`);
|
package/docs/CONTRACTS.md
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
>
|
|
23
23
|
> 严重度:**error** = 违反即会话不可加载/写入被拒(fail-loud);**warning** = 合法但可疑。
|
|
24
24
|
|
|
25
|
-
## 规则索引(共
|
|
25
|
+
## 规则索引(共 55 条)
|
|
26
26
|
|
|
27
27
|
| id | 严重度 | 层级 | 规则 |
|
|
28
28
|
|---|---|---|---|
|
|
@@ -31,6 +31,8 @@
|
|
|
31
31
|
| R1 | error | persistence | 每行必须是合法 JSON |
|
|
32
32
|
| R2 | error | persistence | chunk 行必须满足精确信封形状 |
|
|
33
33
|
| R3 | error | persistence | chunk 行展开后成员 seq/time 安全 |
|
|
34
|
+
| R4 | error | persistence | 读取/解析容错:单文件损坏不得抛出、不得中断枚举与汇总 |
|
|
35
|
+
| R5 | error | persistence | 汇总/枚举类 API 逐项隔离(per-item try/catch + 失败计数) |
|
|
34
36
|
| E1 | error | persistence | 每个事件携带非负安全整数 seq |
|
|
35
37
|
| E2 | error | persistence | seq 严格连续(单写入者假设) |
|
|
36
38
|
| S9 | error | persistence | 文件物理序 seq 单调(多写入者交织现场特征) |
|
|
@@ -58,6 +60,7 @@
|
|
|
58
60
|
| E8 | warning | persistence | 事件信封键白名单(多余键:seed/restore 路径会拒) |
|
|
59
61
|
| E9 | error | persistence | system/message 的 source 契约(v3 plugin / v4 system-prompt) |
|
|
60
62
|
| E10 | error | persistence | request/header 的 data.header 字段约束 |
|
|
63
|
+
| E11 | error | persistence | seq 由日志层分配:写侧不得自造(省略 seq,或必须等于 nextSeq) |
|
|
61
64
|
| Z3 | warning | framing | 空会话文件(有 header 无事件)显式报出 |
|
|
62
65
|
| P3 | warning | plugin | tool/call ↔ tool/result 配对完整性(考古 B1) |
|
|
63
66
|
| P4 | warning | plugin | tool/result 输出结构可解析(考古 B2) |
|
|
@@ -70,6 +73,7 @@
|
|
|
70
73
|
| Z2 | error | framing | zstd 帧解码失败 = 单帧全损 |
|
|
71
74
|
| Z4 | error | framing | 首帧必须恰好一行 header |
|
|
72
75
|
| Z5 | error | framing | 多行日志不得压成单帧 |
|
|
76
|
+
| Z6 | warning | framing | 尾部完整性必须显式声明(tailStatus: complete|truncated|interrupted|unknown) |
|
|
73
77
|
| W1 | error | engine | wire 流:tool 消息必须跟在带 tool-call 的 assistant 消息之后 |
|
|
74
78
|
| W2 | error | engine | wire 流:user 文本不得插在 tool_calls 与其 tool 结果之间 |
|
|
75
79
|
| G1 | warning | migration | 迁移预检:v0 源文件的 subagent/descriptor.data.version 必须为 3 |
|
|
@@ -110,6 +114,18 @@
|
|
|
110
114
|
- **出处**: @deepseek-ai/dsh-session lib/index.js:964-969
|
|
111
115
|
- **契约**: 展开后成员 seq 与 time 必须保持安全整数(seq0+len-1 与逐 gap 累加的 time 不溢出)。
|
|
112
116
|
|
|
117
|
+
### R4 — 读取/解析容错:单文件损坏不得抛出、不得中断枚举与汇总
|
|
118
|
+
|
|
119
|
+
- **层级**: persistence | **严重度**: error
|
|
120
|
+
- **出处**: 2026-10 实测:一个截断 zstd 帧让会话读头抛 ERR_OUT_OF_RANGE,逐会话读头的聚合/枚举能力整体失败(33 天内数百次);根因之一是帧扫描的块头 3 字节越界读(readUInt32LE 读了 4 字节)
|
|
121
|
+
- **契约**: **读取/解析入口的行为契约**(判在 rules self-test,不是逐文件判据):任何单文件**内容级**异常(截断帧、损坏行、坏 chunk 行、空文件、非法 JSON)都必须降级为**结构化结果**——返回 null / 逐行 error 标记 / 帧事实(frameInfo.error / torn / tailStatus / unreadableRows),可被调用方统计;**不得抛出异常**中断"枚举 N 个会话"这类汇总能力。IO 级异常(文件不存在/无权限)不在本条范围(照常抛给调用方处理)。违规样本(截断/损坏文件)必须"判红"(R1/R2/Z1/Z2 或结构化 null + 计数)而不是抛栈;合规样本(健康文件)必须全绿。覆盖入口:读头 readSessionHeader、全量读取 loadSessionLog、尾部查询 tailSeq、帧扫描 scanZstdFrames。
|
|
122
|
+
|
|
123
|
+
### R5 — 汇总/枚举类 API 逐项隔离(per-item try/catch + 失败计数)
|
|
124
|
+
|
|
125
|
+
- **层级**: persistence | **严重度**: error
|
|
126
|
+
- **出处**: 2026-10 实测:单文件炸整表的第二个根因——聚合循环"一项坏 ⇒ 整批抛",既无逐项 try/catch 也无失败计数(坏项不可见、整体不可用)
|
|
127
|
+
- **契约**: 聚合/汇总类 API(逐事件扫描、工具调用审计、逐项配对导出等)必须**逐项**隔离失败:单项异常只丢该项并**计数**(如 skipped/unreadable),整体结果照常返回。违规样本(构造一个读取即抛的畸形事件)必须让 API 返回"结果 + skipped≥1"且不抛;合规样本必须 skipped=0。⛔ "整体抛出"或"静默吞掉且不可统计"都算违规。
|
|
128
|
+
|
|
113
129
|
### E1 — 每个事件携带非负安全整数 seq
|
|
114
130
|
|
|
115
131
|
- **层级**: persistence | **严重度**: error
|
|
@@ -144,7 +160,7 @@
|
|
|
144
160
|
|
|
145
161
|
- **层级**: persistence | **严重度**: error
|
|
146
162
|
- **出处**: @deepseek-ai/dsh-session-format-v0-to-v1@0.2.0-rc.2 package/lib/index.js:1707(`seedLength` → `inheritedEventCount`,缺省 0)、:1720(`isSeeded = seedLength !== undefined`)、:1517-1520("Session inheritedEventCount exceeds its event count" / "unseeded Session inheritedEventCount must be 0");v4 运行时头禁该字段:dsh-session@0.2.0-rc.2 lib/index.js:1040("session header has invalid field \"seedLength\"")
|
|
147
|
-
- **契约**: `header.seedLength` 的语义被钉死为**继承事件条数**(官方 `inheritedEventCount`),不是字节数、不是行数。判据:① 若存在必须是非负安全整数;② `seedLength > 展开后事件数` ⇒ error(官方解码/迁移直接抛 "inheritedEventCount exceeds its event count");③ 文件版本 ≥4 时该字段必须不存在(v4 运行时 header 校验拒)。**`parentSession` 有值 ∧ `seedLength` 缺失或 0 ⇒ 合法**:`parentSession` 只记血缘,是否 seeded 由 `seedLength` 字段是否存在决定(`isSeeded = seedLength !== undefined`;只有 unseeded 才要求 inheritedEventCount === 0)——实测本机 712/760 份真实 v3/v4 头带 `parentSession` 且无 `seedLength`(`isSeeded:false`)仍正常加载,不能判违规。真实读数(本机 29 份 v0 化石):19 份带 `seedLength`(15 万/53 万/68 万/28 万/67 万量级),**全部 ≤ 展开后事件数**(约 69 万/59 万/72 万/39 万/317 万条),而同一文件的明文体积是 20.3–
|
|
163
|
+
- **契约**: `header.seedLength` 的语义被钉死为**继承事件条数**(官方 `inheritedEventCount`),不是字节数、不是行数。判据:① 若存在必须是非负安全整数;② `seedLength > 展开后事件数` ⇒ error(官方解码/迁移直接抛 "inheritedEventCount exceeds its event count");③ 文件版本 ≥4 时该字段必须不存在(v4 运行时 header 校验拒)。**`parentSession` 有值 ∧ `seedLength` 缺失或 0 ⇒ 合法**:`parentSession` 只记血缘,是否 seeded 由 `seedLength` 字段是否存在决定(`isSeeded = seedLength !== undefined`;只有 unseeded 才要求 inheritedEventCount === 0)——实测本机 712/760 份真实 v3/v4 头带 `parentSession` 且无 `seedLength`(`isSeeded:false`)仍正常加载,不能判违规。真实读数(本机 29 份 v0 化石):19 份带 `seedLength`(15 万/53 万/68 万/28 万/67 万量级),**全部 ≤ 展开后事件数**(约 69 万/59 万/72 万/39 万/317 万条),而同一文件的明文体积是 20.3–[size] ⇒ `seedLength` 既不可能是字节数(差 1–2 个数量级),也不可能是行数(行数仅 1.3–7 万)⇒ 真实数据与"继承事件条数"一致,本机命中 0 例 `> 展开事件数`(判红分支是防"当字节数用"的护栏)。
|
|
148
164
|
|
|
149
165
|
### E3 — type 必须在已知词汇表内(或带 ignorable 标记)
|
|
150
166
|
|
|
@@ -272,11 +288,17 @@
|
|
|
272
288
|
- **出处**: @deepseek-ai/dsh-session@0.1.5-rc.1 lib/index.js:231-248(validateSessionEventData:omit header.system / omit empty tools / omit empty adapterDefaults)
|
|
273
289
|
- **契约**: request/header 必须省略 header.system(系统提示改走 system/message)、空 tools、空 adapterDefaults。实测(反例):带 header.system 的写入宿主拒、旧契约 0 违规 ⇒ 漏检。
|
|
274
290
|
|
|
291
|
+
### E11 — seq 由日志层分配:写侧不得自造(省略 seq,或必须等于 nextSeq)
|
|
292
|
+
|
|
293
|
+
- **层级**: persistence | **严重度**: error
|
|
294
|
+
- **出处**: 官方 append 信封按日志层连续光标分配 seq(dsh-session lib/index.js:1453-1459 append 信封、:398 planSurfaceEvent "not contiguous");实测两类破坏:① 生产者自行生成 seq 写入 ⇒ E2/S8 类红;② 删除两行不重编号 ⇒ 缺口
|
|
295
|
+
- **契约**: seq 的唯一合法来源是**日志层的连续光标**(写入时分配)。写侧(prewrite)拟写事件**不携带 seq**(由校验器赋 nextSeq),携带时必须等于 nextSeq,否则 E11 拒绝——⛔ 生产者不得自造/自增 seq。文件侧的"写侧自造"痕迹由 E2(缺口/倒退)与 S9(文件物理序回退)判红:删行不重编号 = 缺口 ⇒ E2;自造/回放旧光标 = 与光标不连续或物理序回退 ⇒ E2/S9。离线单看一行无法知道 seq 是谁写的,故文件侧判据是"连续性/物理序"这条可判下界。
|
|
296
|
+
|
|
275
297
|
### Z3 — 空会话文件(有 header 无事件)显式报出
|
|
276
298
|
|
|
277
299
|
- **层级**: framing | **严重度**: warning
|
|
278
300
|
- **出处**: 实测 2026-09-09 T3(36 条规则全来自有内容事故,空态无覆盖)
|
|
279
|
-
- **契约**: 有 header 但零事件 = 异常空会话(新建即空或写入未落盘)。空态不在任何有内容规则的覆盖下,显式 warning
|
|
301
|
+
- **契约**: 有 header 但零事件 = 异常空会话(新建即空或写入未落盘)。空态不在任何有内容规则的覆盖下,显式 warning 供人判断。**与文件版本无关**:v0–v4 一律判(v4 空壳同样报 Z3);0 字节/无 header 的空文件另由 H1 判(首行不可解析)+ tailStatus=unknown。
|
|
280
302
|
|
|
281
303
|
### P3 — tool/call ↔ tool/result 配对完整性(考古 B1)
|
|
282
304
|
|
|
@@ -344,6 +366,12 @@
|
|
|
344
366
|
- **出处**: 官方形状:header 第一帧 + 事件批次逐帧追加
|
|
345
367
|
- **契约**: 把整份日志重压成 1 帧会同时触发 Z4;任何"重写会话"的路径都必须**保形**(逐帧解、逐帧回写,或走宿主写入器),不得整体重压缩。
|
|
346
368
|
|
|
369
|
+
### Z6 — 尾部完整性必须显式声明(tailStatus: complete|truncated|interrupted|unknown)
|
|
370
|
+
|
|
371
|
+
- **层级**: framing | **严重度**: warning
|
|
372
|
+
- **出处**: 2026-10 实测口径边界:体检只保证"已读到的事件自洽",最后一帧被切掉仍可能 ok=true;判定实现见 lib/log-reader.js deriveTailStatus(与宿主 readZstdPrefix"保留完整记录、丢弃未写完尾帧"语义对齐)
|
|
373
|
+
- **契约**: 每次体检必须给出机器可判的 `tailStatus`(`complete` 尾部完整|`interrupted` zstd 尾帧撕裂=写入中断/进行中,宿主可恢复|`truncated` 末行记录被切断|`unknown` 帧解码失败/空文件/不可读)。**口径边界**:`ok=true` 只保证"已读到的事件自洽",**不保证尾部完整**——判读尾部请用 `check --json` 的 `summary.tailStatus`(库级 `validateSessionLog()` 返回值另有顶层 `tailStatus`)。非 complete 时显式报 warning(⛔ 不翻转 ok:撕裂尾帧在宿主读取器语义下是可恢复的边写边读态,见 Z1;真损坏由 Z2/R1 判 error)。离线无法区分"写入中被读到"与"写完前进程中断"(字节形态相同)⇒ 都归 `interrupted`。
|
|
374
|
+
|
|
347
375
|
### W1 — wire 流:tool 消息必须跟在带 tool-call 的 assistant 消息之后
|
|
348
376
|
|
|
349
377
|
- **层级**: engine | **严重度**: error
|
package/lib/archaeology.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* dsh-log-contract · lib/archaeology.js
|
|
3
3
|
*
|
|
4
4
|
* 会话日志考古 —— 两插件共享:
|
|
5
|
-
* retrace
|
|
5
|
+
* retrace 的考古界面/导出(四类)与 log-contract 的 extract/audit-report
|
|
6
6
|
* (B3/B4)都消费这里的纯函数。**只读不写**(纪律 §8.1)。
|
|
7
7
|
*
|
|
8
8
|
* 核心事实(§2):
|
|
@@ -72,27 +72,35 @@ export function toolCommandOf(event) {
|
|
|
72
72
|
* calls: Map<callId, { command: string, callSeq: number }>,
|
|
73
73
|
* outputs: Map<callId, { text: string, size: number, resultSeq: number }>,
|
|
74
74
|
* orphans: string[], // 无 result 的 callId(P3 同源)
|
|
75
|
+
* skipped: number, // R5:逐项隔离——单项异常只丢该项并计数,不中断汇总
|
|
75
76
|
* }}
|
|
76
77
|
*/
|
|
77
78
|
export function indexToolCalls(events) {
|
|
78
79
|
const calls = new Map();
|
|
79
80
|
const outputs = new Map();
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
81
|
+
let skipped = 0;
|
|
82
|
+
for (const event of events ?? []) {
|
|
83
|
+
// R5(0.3.28 · 汇总逐项隔离):单项读取异常(畸形事件、读取即抛的字段、
|
|
84
|
+
// 超深嵌套)只丢**该项**并计数——⛔ 不得让"一项坏 ⇒ 整批抛"毁掉整个汇总能力。
|
|
85
|
+
try {
|
|
86
|
+
if (event.type === 'tool/call') {
|
|
87
|
+
const callId = event.data?.callId;
|
|
88
|
+
if (typeof callId === 'string' && callId !== '') {
|
|
89
|
+
calls.set(callId, { command: toolCommandOf(event), callSeq: event.seq });
|
|
90
|
+
}
|
|
91
|
+
} else if (event.type === 'tool/result') {
|
|
92
|
+
const callId = event.data?.message?.source?.callId;
|
|
93
|
+
if (typeof callId === 'string' && callId !== '') {
|
|
94
|
+
const text = extractText(event.data?.message?.content);
|
|
95
|
+
outputs.set(callId, { text, size: text.length, resultSeq: event.seq });
|
|
96
|
+
}
|
|
91
97
|
}
|
|
98
|
+
} catch {
|
|
99
|
+
skipped += 1;
|
|
92
100
|
}
|
|
93
101
|
}
|
|
94
102
|
const orphans = [...calls.keys()].filter((callId) => !outputs.has(callId));
|
|
95
|
-
return { calls, outputs, orphans };
|
|
103
|
+
return { calls, outputs, orphans, skipped };
|
|
96
104
|
}
|
|
97
105
|
|
|
98
106
|
/**
|
|
@@ -101,20 +109,26 @@ export function indexToolCalls(events) {
|
|
|
101
109
|
* @param events - 会话事件数组。
|
|
102
110
|
* @param pattern - 命令正则(字符串或 RegExp;字符串按子串匹配,空则全量)。
|
|
103
111
|
* @param opts.minSize - 输出最小字节数过滤(默认 0;CLI 默认用 50 过滤噪声)。
|
|
104
|
-
* @returns {{ pairs: Array<{ callId, command, text, size }>, matched: number, total: number }}
|
|
112
|
+
* @returns {{ pairs: Array<{ callId, command, text, size }>, matched: number, total: number, skipped: number }}
|
|
105
113
|
*/
|
|
106
114
|
export function extractToolOutputs(events, pattern = '', { minSize = 0 } = {}) {
|
|
107
|
-
const { calls, outputs } = indexToolCalls(events);
|
|
115
|
+
const { calls, outputs, skipped: skippedIndexed } = indexToolCalls(events);
|
|
116
|
+
let skipped = skippedIndexed;
|
|
108
117
|
const re = pattern instanceof RegExp ? pattern : (pattern ? new RegExp(pattern) : null);
|
|
109
118
|
const pairs = [];
|
|
110
119
|
for (const [callId, call] of calls) {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
120
|
+
// R5:逐项隔离——单个配对的读取/匹配异常只丢该项并计数。
|
|
121
|
+
try {
|
|
122
|
+
const matched = re === null || re.test(call.command);
|
|
123
|
+
if (!matched) continue;
|
|
124
|
+
const output = outputs.get(callId);
|
|
125
|
+
if (!output || output.size < minSize) continue;
|
|
126
|
+
pairs.push({ callId, command: call.command, text: output.text, size: output.size });
|
|
127
|
+
} catch {
|
|
128
|
+
skipped += 1;
|
|
129
|
+
}
|
|
116
130
|
}
|
|
117
|
-
return { pairs, matched: pairs.length, total: calls.size };
|
|
131
|
+
return { pairs, matched: pairs.length, total: calls.size, skipped };
|
|
118
132
|
}
|
|
119
133
|
|
|
120
134
|
/**
|
|
@@ -125,10 +139,11 @@ export function extractToolOutputs(events, pattern = '', { minSize = 0 } = {}) {
|
|
|
125
139
|
* calls, results, paired, orphans, pairingRate,
|
|
126
140
|
* commands: { top: Array<{ command, count }>, distinct },
|
|
127
141
|
* outputBytes, largest: { callId, command, size } | null,
|
|
142
|
+
* skipped: number, // R5:逐项隔离的失败计数(可统计)
|
|
128
143
|
* }}
|
|
129
144
|
*/
|
|
130
145
|
export function auditToolCalls(events) {
|
|
131
|
-
const { calls, outputs, orphans } = indexToolCalls(events);
|
|
146
|
+
const { calls, outputs, orphans, skipped } = indexToolCalls(events);
|
|
132
147
|
const commandCounts = new Map();
|
|
133
148
|
for (const call of calls.values()) {
|
|
134
149
|
const key = call.command || '(no-command)';
|
|
@@ -155,5 +170,6 @@ export function auditToolCalls(events) {
|
|
|
155
170
|
commands: { top: top.slice(0, 15), distinct: top.length },
|
|
156
171
|
outputBytes,
|
|
157
172
|
largest,
|
|
173
|
+
skipped,
|
|
158
174
|
};
|
|
159
175
|
}
|
package/lib/checks.js
CHANGED
|
@@ -569,7 +569,7 @@ export function turnEndReasonViolations(events) {
|
|
|
569
569
|
/**
|
|
570
570
|
* E7 —— ignorable 未知 type 合法性(2026-09-09 T2 增量)。
|
|
571
571
|
*
|
|
572
|
-
* 盲区:E3 对"未知 type + ignorable:true"
|
|
572
|
+
* 盲区:E3 对"未知 type + ignorable:true"直接internal(容忍更新版本 harness 写入),
|
|
573
573
|
* 但 ignorable 标记无合法性校验 = 后门——被读路径接纳却无人消费的未知事件 =
|
|
574
574
|
* 静默垃圾(违 R3 精神)。补:未知 type + ignorable + **不在已知消费者白名单** →
|
|
575
575
|
* warning"有被忽略的未知事件"。
|
package/lib/contracts.js
CHANGED
|
@@ -39,14 +39,14 @@ export const SEVERITY = { ERROR: 'error', WARNING: 'warning', INFO: 'info' };
|
|
|
39
39
|
* - G 迁移预检(migration gate,**独立维度**:官方迁移会不会拒;不进 ok/verdict)
|
|
40
40
|
*/
|
|
41
41
|
/**
|
|
42
|
-
* (2026-09-14
|
|
42
|
+
* (2026-09-14 实测)——**机读的漂移/未internal标注**。
|
|
43
43
|
*
|
|
44
44
|
* 核对结论:规则的 `source` 大量停在 `@deepseek-ai/dsh-session@0.1.0-rc.7` 的行号上,
|
|
45
45
|
* 且其中 4 条(T2/P1/P2/C1)的**判定前提**在真宿主 0.1.5 上已不成立——此前**没有任何机制
|
|
46
46
|
* 能发现**(`source` 只是人读字符串)。这里把它们变成机读字段,并由 `check` 抬头点名。
|
|
47
47
|
*/
|
|
48
48
|
export const SOURCE_DRIFT = Object.freeze({
|
|
49
|
-
/** 出处停在 rc.7 行号、未在 0.1.5
|
|
49
|
+
/** 出处停在 rc.7 行号、未在 0.1.5 上internal(清单见下)。 */
|
|
50
50
|
drifted: Object.freeze(['T2', 'P1', 'P2', 'C1', 'I1', 'G3', 'R2', 'R3', 'E5', 'E6']),
|
|
51
51
|
/**
|
|
52
52
|
* **判定前提在 0.1.5 上不成立/无法判定**:
|
|
@@ -58,7 +58,7 @@ export const SOURCE_DRIFT = Object.freeze({
|
|
|
58
58
|
/** 明确"无法判定"、需要真机实验的条目(列出来是为了不假装覆盖)。 */
|
|
59
59
|
undecidable: Object.freeze(['T3', 'T4']),
|
|
60
60
|
note: '出处/前提漂移是**静默失真**:行为探针(lib/host-probes.js)负责机器可判的那部分,'
|
|
61
|
-
+ '
|
|
61
|
+
+ '其余在此显式列出,结论抬头必须带漂移清单与未internal清单。',
|
|
62
62
|
});
|
|
63
63
|
|
|
64
64
|
export const CONTRACT_RULES = [
|
|
@@ -107,6 +107,22 @@ export const CONTRACT_RULES = [
|
|
|
107
107
|
source: '@deepseek-ai/dsh-session lib/index.js:964-969',
|
|
108
108
|
description: '展开后成员 seq 与 time 必须保持安全整数(seq0+len-1 与逐 gap 累加的 time 不溢出)。',
|
|
109
109
|
},
|
|
110
|
+
{
|
|
111
|
+
id: 'R4',
|
|
112
|
+
title: '读取/解析容错:单文件损坏不得抛出、不得中断枚举与汇总',
|
|
113
|
+
layer: LAYER.PERSISTENCE,
|
|
114
|
+
severity: SEVERITY.ERROR,
|
|
115
|
+
source: '2026-10 实测:一个截断 zstd 帧让会话读头抛 ERR_OUT_OF_RANGE,逐会话读头的聚合/枚举能力整体失败(33 天内数百次);根因之一是帧扫描的块头 3 字节越界读(readUInt32LE 读了 4 字节)',
|
|
116
|
+
description: '**读取/解析入口的行为契约**(判在 rules self-test,不是逐文件判据):任何单文件**内容级**异常(截断帧、损坏行、坏 chunk 行、空文件、非法 JSON)都必须降级为**结构化结果**——返回 null / 逐行 error 标记 / 帧事实(frameInfo.error / torn / tailStatus / unreadableRows),可被调用方统计;**不得抛出异常**中断"枚举 N 个会话"这类汇总能力。IO 级异常(文件不存在/无权限)不在本条范围(照常抛给调用方处理)。违规样本(截断/损坏文件)必须"判红"(R1/R2/Z1/Z2 或结构化 null + 计数)而不是抛栈;合规样本(健康文件)必须全绿。覆盖入口:读头 readSessionHeader、全量读取 loadSessionLog、尾部查询 tailSeq、帧扫描 scanZstdFrames。',
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
id: 'R5',
|
|
120
|
+
title: '汇总/枚举类 API 逐项隔离(per-item try/catch + 失败计数)',
|
|
121
|
+
layer: LAYER.PERSISTENCE,
|
|
122
|
+
severity: SEVERITY.ERROR,
|
|
123
|
+
source: '2026-10 实测:单文件炸整表的第二个根因——聚合循环"一项坏 ⇒ 整批抛",既无逐项 try/catch 也无失败计数(坏项不可见、整体不可用)',
|
|
124
|
+
description: '聚合/汇总类 API(逐事件扫描、工具调用审计、逐项配对导出等)必须**逐项**隔离失败:单项异常只丢该项并**计数**(如 skipped/unreadable),整体结果照常返回。违规样本(构造一个读取即抛的畸形事件)必须让 API 返回"结果 + skipped≥1"且不抛;合规样本必须 skipped=0。⛔ "整体抛出"或"静默吞掉且不可统计"都算违规。',
|
|
125
|
+
},
|
|
110
126
|
|
|
111
127
|
// ── E · 事件信封 ────────────────────────────────────────────────────────
|
|
112
128
|
{
|
|
@@ -156,7 +172,7 @@ export const CONTRACT_RULES = [
|
|
|
156
172
|
layer: LAYER.PERSISTENCE,
|
|
157
173
|
severity: SEVERITY.ERROR,
|
|
158
174
|
source: '@deepseek-ai/dsh-session-format-v0-to-v1@0.2.0-rc.2 package/lib/index.js:1707(`seedLength` → `inheritedEventCount`,缺省 0)、:1720(`isSeeded = seedLength !== undefined`)、:1517-1520("Session inheritedEventCount exceeds its event count" / "unseeded Session inheritedEventCount must be 0");v4 运行时头禁该字段:dsh-session@0.2.0-rc.2 lib/index.js:1040("session header has invalid field \\"seedLength\\"")',
|
|
159
|
-
description: '`header.seedLength` 的语义被钉死为**继承事件条数**(官方 `inheritedEventCount`),不是字节数、不是行数。判据:① 若存在必须是非负安全整数;② `seedLength > 展开后事件数` ⇒ error(官方解码/迁移直接抛 "inheritedEventCount exceeds its event count");③ 文件版本 ≥4 时该字段必须不存在(v4 运行时 header 校验拒)。**`parentSession` 有值 ∧ `seedLength` 缺失或 0 ⇒ 合法**:`parentSession` 只记血缘,是否 seeded 由 `seedLength` 字段是否存在决定(`isSeeded = seedLength !== undefined`;只有 unseeded 才要求 inheritedEventCount === 0)——实测本机 712/760 份真实 v3/v4 头带 `parentSession` 且无 `seedLength`(`isSeeded:false`)仍正常加载,不能判违规。真实读数(本机 29 份 v0 化石):19 份带 `seedLength`(15 万/53 万/68 万/28 万/67 万量级),**全部 ≤ 展开后事件数**(约 69 万/59 万/72 万/39 万/317 万条),而同一文件的明文体积是 20.3–
|
|
175
|
+
description: '`header.seedLength` 的语义被钉死为**继承事件条数**(官方 `inheritedEventCount`),不是字节数、不是行数。判据:① 若存在必须是非负安全整数;② `seedLength > 展开后事件数` ⇒ error(官方解码/迁移直接抛 "inheritedEventCount exceeds its event count");③ 文件版本 ≥4 时该字段必须不存在(v4 运行时 header 校验拒)。**`parentSession` 有值 ∧ `seedLength` 缺失或 0 ⇒ 合法**:`parentSession` 只记血缘,是否 seeded 由 `seedLength` 字段是否存在决定(`isSeeded = seedLength !== undefined`;只有 unseeded 才要求 inheritedEventCount === 0)——实测本机 712/760 份真实 v3/v4 头带 `parentSession` 且无 `seedLength`(`isSeeded:false`)仍正常加载,不能判违规。真实读数(本机 29 份 v0 化石):19 份带 `seedLength`(15 万/53 万/68 万/28 万/67 万量级),**全部 ≤ 展开后事件数**(约 69 万/59 万/72 万/39 万/317 万条),而同一文件的明文体积是 20.3–[size] ⇒ `seedLength` 既不可能是字节数(差 1–2 个数量级),也不可能是行数(行数仅 1.3–7 万)⇒ 真实数据与"继承事件条数"一致,本机命中 0 例 `> 展开事件数`(判红分支是防"当字节数用"的护栏)。',
|
|
160
176
|
},
|
|
161
177
|
{
|
|
162
178
|
id: 'E3',
|
|
@@ -340,13 +356,21 @@ export const CONTRACT_RULES = [
|
|
|
340
356
|
description: 'request/header 必须省略 header.system(系统提示改走 system/message)、空 tools、空 adapterDefaults。实测(反例):带 header.system 的写入宿主拒、旧契约 0 违规 ⇒ 漏检。',
|
|
341
357
|
candidate: true,
|
|
342
358
|
},
|
|
359
|
+
{
|
|
360
|
+
id: 'E11',
|
|
361
|
+
title: 'seq 由日志层分配:写侧不得自造(省略 seq,或必须等于 nextSeq)',
|
|
362
|
+
layer: LAYER.PERSISTENCE,
|
|
363
|
+
severity: SEVERITY.ERROR,
|
|
364
|
+
source: '官方 append 信封按日志层连续光标分配 seq(dsh-session lib/index.js:1453-1459 append 信封、:398 planSurfaceEvent "not contiguous");实测两类破坏:① 生产者自行生成 seq 写入 ⇒ E2/S8 类红;② 删除两行不重编号 ⇒ 缺口',
|
|
365
|
+
description: 'seq 的唯一合法来源是**日志层的连续光标**(写入时分配)。写侧(prewrite)拟写事件**不携带 seq**(由校验器赋 nextSeq),携带时必须等于 nextSeq,否则 E11 拒绝——⛔ 生产者不得自造/自增 seq。文件侧的"写侧自造"痕迹由 E2(缺口/倒退)与 S9(文件物理序回退)判红:删行不重编号 = 缺口 ⇒ E2;自造/回放旧光标 = 与光标不连续或物理序回退 ⇒ E2/S9。离线单看一行无法知道 seq 是谁写的,故文件侧判据是"连续性/物理序"这条可判下界。',
|
|
366
|
+
},
|
|
343
367
|
{
|
|
344
368
|
id: 'Z3',
|
|
345
369
|
title: '空会话文件(有 header 无事件)显式报出',
|
|
346
370
|
layer: LAYER.FRAMING,
|
|
347
371
|
severity: SEVERITY.WARNING,
|
|
348
372
|
source: '实测 2026-09-09 T3(36 条规则全来自有内容事故,空态无覆盖)',
|
|
349
|
-
description: '有 header 但零事件 = 异常空会话(新建即空或写入未落盘)。空态不在任何有内容规则的覆盖下,显式 warning
|
|
373
|
+
description: '有 header 但零事件 = 异常空会话(新建即空或写入未落盘)。空态不在任何有内容规则的覆盖下,显式 warning 供人判断。**与文件版本无关**:v0–v4 一律判(v4 空壳同样报 Z3);0 字节/无 header 的空文件另由 H1 判(首行不可解析)+ tailStatus=unknown。',
|
|
350
374
|
},
|
|
351
375
|
{
|
|
352
376
|
id: 'P3',
|
|
@@ -449,6 +473,14 @@ export const CONTRACT_RULES = [
|
|
|
449
473
|
source: '官方形状:header 第一帧 + 事件批次逐帧追加',
|
|
450
474
|
description: '把整份日志重压成 1 帧会同时触发 Z4;任何"重写会话"的路径都必须**保形**(逐帧解、逐帧回写,或走宿主写入器),不得整体重压缩。',
|
|
451
475
|
},
|
|
476
|
+
{
|
|
477
|
+
id: 'Z6',
|
|
478
|
+
title: '尾部完整性必须显式声明(tailStatus: complete|truncated|interrupted|unknown)',
|
|
479
|
+
layer: LAYER.FRAMING,
|
|
480
|
+
severity: SEVERITY.WARNING,
|
|
481
|
+
source: '2026-10 实测口径边界:体检只保证"已读到的事件自洽",最后一帧被切掉仍可能 ok=true;判定实现见 lib/log-reader.js deriveTailStatus(与宿主 readZstdPrefix"保留完整记录、丢弃未写完尾帧"语义对齐)',
|
|
482
|
+
description: '每次体检必须给出机器可判的 `tailStatus`(`complete` 尾部完整|`interrupted` zstd 尾帧撕裂=写入中断/进行中,宿主可恢复|`truncated` 末行记录被切断|`unknown` 帧解码失败/空文件/不可读)。**口径边界**:`ok=true` 只保证"已读到的事件自洽",**不保证尾部完整**——判读尾部请用 `check --json` 的 `summary.tailStatus`(库级 `validateSessionLog()` 返回值另有顶层 `tailStatus`)。非 complete 时显式报 warning(⛔ 不翻转 ok:撕裂尾帧在宿主读取器语义下是可恢复的边写边读态,见 Z1;真损坏由 Z2/R1 判 error)。离线无法区分"写入中被读到"与"写完前进程中断"(字节形态相同)⇒ 都归 `interrupted`。',
|
|
483
|
+
},
|
|
452
484
|
|
|
453
485
|
// ── W · wire 消息流(模型请求序列)───────────────────────────────────────
|
|
454
486
|
{
|
package/lib/log-reader.js
CHANGED
|
@@ -57,7 +57,12 @@ export function scanZstdFrames(buf) {
|
|
|
57
57
|
torn = true;
|
|
58
58
|
break;
|
|
59
59
|
}
|
|
60
|
-
|
|
60
|
+
// R4(2026-10-26 事故复盘):块头是 **3 字节** little-endian。旧实现这里用
|
|
61
|
+
// `readUInt32LE`(读 4 字节)——恰剩 3 字节时抛 `ERR_OUT_OF_RANGE`,一个截断
|
|
62
|
+
// 文件就炸掉整个读取/枚举入口。改 `readUIntLE(offset, 3)`:语义完全等价
|
|
63
|
+
// (块大小只有低 21 位参与 `>>> 3 & 0x1fffff`,第 4 字节从未被用到),
|
|
64
|
+
// 且永不越界;残缺块头一律按"撕裂尾帧"降级(`torn = true`)。
|
|
65
|
+
const bh = buf.readUIntLE(offset, 3);
|
|
61
66
|
offset += 3;
|
|
62
67
|
lastBlock = (bh & 1) !== 0;
|
|
63
68
|
offset += (bh >>> 3) & 0x1fffff;
|
|
@@ -124,7 +129,13 @@ export function tailSeq(path) {
|
|
|
124
129
|
const isZstd = buf.length >= 4 && buf.readUInt32LE(0) === ZSTD_MAGIC;
|
|
125
130
|
let plain;
|
|
126
131
|
if (isZstd) {
|
|
127
|
-
|
|
132
|
+
// R4:损坏文件不得让"读尾部 seq"这类单点查询抛错(聚合方拿 null 降级并计数)。
|
|
133
|
+
let frames = [];
|
|
134
|
+
try {
|
|
135
|
+
({ frames } = scanZstdFrames(buf));
|
|
136
|
+
} catch {
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
128
139
|
if (frames.length === 0) return null;
|
|
129
140
|
const [s, e] = frames[frames.length - 1];
|
|
130
141
|
try {
|
|
@@ -172,7 +183,13 @@ export function loadSessionLog(path) {
|
|
|
172
183
|
loadError = err;
|
|
173
184
|
plain = Buffer.alloc(0);
|
|
174
185
|
}
|
|
175
|
-
|
|
186
|
+
// R4:帧扫描是"读取入口",损坏文件不得让它抛(3 字节块头越界 bug 已修;这里仍
|
|
187
|
+
// 防御性兜住——扫描失败按"撕裂/不可判"降级,不中断读取与汇总)。
|
|
188
|
+
let frames = [];
|
|
189
|
+
let torn = true;
|
|
190
|
+
try {
|
|
191
|
+
({ frames, torn } = scanZstdFrames(buf));
|
|
192
|
+
} catch { /* 降级:torn=true ⇒ tailStatus 由 deriveTailStatus 判 */ }
|
|
176
193
|
// 帧形状事实(Z4/Z5,2026-09-16 真机事故):官方写盘形状 = **header 独占第一帧** +
|
|
177
194
|
// 事件逐帧追加;读取端有硬断言 `assertZstdHeaderFrame`(首帧必须**恰好一行**)。
|
|
178
195
|
// 这里把该事实带出来给 validate 判:整文件被重压成单帧时,首帧装的是全部行 ⇒ 宿主必抛,
|
|
@@ -196,11 +213,11 @@ export function loadSessionLog(path) {
|
|
|
196
213
|
headerLine: 0,
|
|
197
214
|
rows: [],
|
|
198
215
|
events: [],
|
|
199
|
-
frameInfo: { ...frameInfo, error: loadError.message },
|
|
216
|
+
frameInfo: { ...frameInfo, error: loadError.message, tailStatus: 'unknown', tailStatusReason: 'frame-decode-failed' },
|
|
200
217
|
};
|
|
201
218
|
}
|
|
202
219
|
|
|
203
|
-
// 按行解码(Buffer 切分),避免整文件字符串化(>
|
|
220
|
+
// 按行解码(Buffer 切分),避免整文件字符串化(>[size] 抛字符串上限)
|
|
204
221
|
const lines = (() => { const out = []; let s = 0, i; while ((i = plain.indexOf(0x0a, s)) !== -1) { out.push(plain.subarray(s, i).toString('utf8')); s = i + 1 } out.push(plain.subarray(s).toString('utf8')); return out })();
|
|
205
222
|
|
|
206
223
|
// 第一行 = header
|
|
@@ -246,21 +263,62 @@ export function loadSessionLog(path) {
|
|
|
246
263
|
// 按 seq 排序(文件顺序即日志顺序,此处防御性排序以便下游契约检查)
|
|
247
264
|
events.sort((a, b) => a.seq - b.seq);
|
|
248
265
|
|
|
266
|
+
// R4/Z6:尾部完整性是**文件事实**,在读取层唯一入口判定一次,随 frameInfo 带出。
|
|
267
|
+
const { tailStatus, tailStatusReason } = deriveTailStatus({ frameInfo, rows, header });
|
|
268
|
+
frameInfo.tailStatus = tailStatus;
|
|
269
|
+
frameInfo.tailStatusReason = tailStatusReason;
|
|
270
|
+
|
|
249
271
|
return { header, headerLine, rows, events, frameInfo };
|
|
250
272
|
}
|
|
251
273
|
|
|
274
|
+
/**
|
|
275
|
+
* Z6 · 尾部完整性判定(`tailStatus`)。
|
|
276
|
+
*
|
|
277
|
+
* 背景(口径边界):`check --json` 只保证"**已读到的事件**自洽",**不保证尾部完整**——
|
|
278
|
+
* 最后一帧/最后一行被切掉时仍可能 `ok=true`。这里把尾部状态变成机器可判字段:
|
|
279
|
+
*
|
|
280
|
+
* | 值 | 判定 | 含义 |
|
|
281
|
+
* |---|---|---|
|
|
282
|
+
* | `complete` | 全部帧完整、末行是完整 JSON 记录 | 尾部完整 |
|
|
283
|
+
* | `interrupted` | zstd 尾帧撕裂(incomplete-tail) | 写入中断/进行中(in-flight);宿主读取器丢弃未写完尾帧、保留完整记录(可恢复),其后可能还有未落盘数据 |
|
|
284
|
+
* | `truncated` | 末行不是完整 JSON(记录被切) | 尾部数据已被切断,需修复/回滚 |
|
|
285
|
+
* | `unknown` | 帧解码失败 / 空文件 / 无法读取 | 判不了,不冒充 complete |
|
|
286
|
+
*
|
|
287
|
+
* 离线无法区分"写入中被读到"与"写完前进程崩溃"——两者都归 `interrupted`
|
|
288
|
+
* (字节形态相同,宿主同语义处理)。`truncated` 留给**记录级**被切(末行半截)。
|
|
289
|
+
*
|
|
290
|
+
* @param {{frameInfo?: object, rows?: Array, header?: object|null}} input
|
|
291
|
+
* @returns {{tailStatus: 'complete'|'truncated'|'interrupted'|'unknown', tailStatusReason: string}}
|
|
292
|
+
*/
|
|
293
|
+
export function deriveTailStatus({ frameInfo, rows = [], header = null } = {}) {
|
|
294
|
+
if (typeof frameInfo?.tailStatus === 'string') {
|
|
295
|
+
return { tailStatus: frameInfo.tailStatus, tailStatusReason: frameInfo.tailStatusReason ?? 'declared' };
|
|
296
|
+
}
|
|
297
|
+
if (frameInfo?.error) return { tailStatus: 'unknown', tailStatusReason: 'frame-decode-failed' };
|
|
298
|
+
if (frameInfo?.torn) return { tailStatus: 'interrupted', tailStatusReason: 'torn-tail-frame' };
|
|
299
|
+
const last = rows.length > 0 ? rows[rows.length - 1] : null;
|
|
300
|
+
if (last?.error && last.value === null) return { tailStatus: 'truncated', tailStatusReason: 'tail-record-not-json' };
|
|
301
|
+
if (header === null && rows.length === 0) return { tailStatus: 'unknown', tailStatusReason: 'empty-or-unreadable' };
|
|
302
|
+
return { tailStatus: 'complete', tailStatusReason: 'all-frames-and-tail-record-complete' };
|
|
303
|
+
}
|
|
304
|
+
|
|
252
305
|
/**
|
|
253
306
|
* 轻量读取会话文件 header(只解第一帧,不读全文件帧)。
|
|
254
307
|
*
|
|
255
308
|
* 帧布局:帧 1 = header 行(单行 JSON,~几百字节),帧 2+ = 事件流。
|
|
256
309
|
* 短码推导(工作区 createdAt 序号)需要扫全部会话但只需要 header——
|
|
257
|
-
* 读文件前缀 64KiB 足够覆盖完整帧 1
|
|
310
|
+
* 读文件前缀 64KiB 足够覆盖完整帧 1,避免全量读大文件(internal压缩后可达
|
|
258
311
|
* 数百 MiB)。失败返回 null(调用方降级)。
|
|
259
312
|
*
|
|
260
313
|
* @param {string} path 会话日志文件路径(.jsonl.zstd 或明文 .jsonl)。
|
|
261
314
|
* @returns {object|null} header 对象;无法解析返回 null。
|
|
262
315
|
*/
|
|
263
316
|
export function readSessionHeader(path) {
|
|
317
|
+
/* readSessionHeader-safe(R4):单文件帧截断/损坏 ⇒ 返回 null,
|
|
318
|
+
不让一个坏文件炸掉整张读头汇总表(实测:单文件损坏曾让逐会话读头的
|
|
319
|
+
聚合能力在 33 天内数百次整体失败)。 */
|
|
320
|
+
try {
|
|
321
|
+
return (function () {
|
|
264
322
|
let head;
|
|
265
323
|
try {
|
|
266
324
|
const fd = fs.openSync(path, 'r');
|
|
@@ -296,4 +354,11 @@ export function readSessionHeader(path) {
|
|
|
296
354
|
} catch {
|
|
297
355
|
return null;
|
|
298
356
|
}
|
|
357
|
+
})()
|
|
358
|
+
} catch (error) {
|
|
359
|
+
if (process.env.DSH_LOG_CONTRACT_DEBUG_HEADER === '1') {
|
|
360
|
+
console.error(`readSessionHeader: ${path}: ${String(error && error.message || error)}`)
|
|
361
|
+
}
|
|
362
|
+
return null
|
|
363
|
+
}
|
|
299
364
|
}
|
package/lib/prewrite.js
CHANGED
|
@@ -231,9 +231,25 @@ export function createPreWriter(input = {}) {
|
|
|
231
231
|
nextSeq,
|
|
232
232
|
};
|
|
233
233
|
}
|
|
234
|
+
// E11(0.3.28 · seq 来源):seq 只能由**日志层连续光标**分配。拟写事件携带
|
|
235
|
+
// seq 时必须等于 nextSeq;⛔ 写侧/生产者不得自造、自增 seq(自造 seq 的落盘
|
|
236
|
+
// 痕迹 = 缺口/倒退/物理序回退,文件侧由 E2/S9 判红)。
|
|
237
|
+
const seqProvenanceViolations = [];
|
|
238
|
+
if (candidate.seq !== undefined && candidate.seq !== nextSeq) {
|
|
239
|
+
seqProvenanceViolations.push(violation(
|
|
240
|
+
'E11',
|
|
241
|
+
{ seq: typeof candidate.seq === 'number' ? candidate.seq : null, eventType: candidate.type },
|
|
242
|
+
`写侧不得自造 seq:拟写事件携带 seq=${String(candidate.seq)},日志层分配的下一个 seq 是 ${nextSeq}——请省略 seq(由校验器赋 ${nextSeq})或显式传 ${nextSeq}`,
|
|
243
|
+
));
|
|
244
|
+
}
|
|
234
245
|
const normalized = normalizeEventSeqRanges(normalizeCandidate(candidate, nextSeq));
|
|
235
246
|
const after = [...events, normalized];
|
|
236
|
-
const result = runChecks(after, nextSeq);
|
|
247
|
+
const result = runChecks(after, nextSeq);
|
|
248
|
+
result.violations = [...seqProvenanceViolations, ...result.violations];
|
|
249
|
+
result.bySeverity = { error: 0, warning: 0, info: 0 };
|
|
250
|
+
for (const v of result.violations) result.bySeverity[v.severity] = (result.bySeverity[v.severity] ?? 0) + 1;
|
|
251
|
+
result.ok = result.bySeverity.error === 0;
|
|
252
|
+
result.stateAfter = {
|
|
237
253
|
events: after,
|
|
238
254
|
nextSeq: result.nextSeq,
|
|
239
255
|
surfaceNodes: result.surface?.nodes ?? [],
|
package/lib/repair.js
CHANGED
|
@@ -1137,7 +1137,7 @@ export function rebuildZstdText(text) {
|
|
|
1137
1137
|
|
|
1138
1138
|
/**
|
|
1139
1139
|
* 按官方 writer 帧格式重建 .jsonl.zstd(帧1=header,帧2..n=正文**分块多帧**,均带 checksum)。
|
|
1140
|
-
* 流式/分块版 —— 不构造整份大字符串(>
|
|
1140
|
+
* 流式/分块版 —— 不构造整份大字符串(>[size] 会 ERR_STRING_TOO_LONG);逐帧 roundtrip 校验。
|
|
1141
1141
|
* @param {string[]} lines - 按 \n 切开的行数组;末元素必须为 ''(单个换行结尾)。
|
|
1142
1142
|
* @param {{chunkBytes?:number}} [opts]
|
|
1143
1143
|
* @returns {Buffer}
|
package/lib/validate.js
CHANGED
|
@@ -12,6 +12,7 @@
|
|
|
12
12
|
import { posix as posixPath, win32 as win32Path } from 'node:path';
|
|
13
13
|
import { ruleById } from './contracts.js';
|
|
14
14
|
import { normalizeEventSeqRanges } from './compat.js';
|
|
15
|
+
import { deriveTailStatus } from './log-reader.js';
|
|
15
16
|
import { HOST_MAX_FILE_VERSION, MIGRATION_TARGET_VERSION, hostCapability, isAssessableFileVersion } from './vocab.js';
|
|
16
17
|
import { detectSupport } from './version-support.js';
|
|
17
18
|
import { runHostProbes } from './host-probes.js';
|
|
@@ -51,8 +52,8 @@ import { archiveVerdict } from './archive.js';
|
|
|
51
52
|
* 旧实现只认 POSIX 的 `/` 前缀 ⇒ Windows 会话的 `C:\…` / `\\server\share\…` 全部误报 H2
|
|
52
53
|
* (体检是离线、跨机只读的:被检日志可能来自任意平台,不能按本机 `process.platform` 判)。
|
|
53
54
|
* 两种形态都接受:
|
|
54
|
-
* - POSIX:`/
|
|
55
|
-
* - Windows 盘符绝对:`C:\Users\x`、`C:/
|
|
55
|
+
* - POSIX:`/home/x`、`/home/x`
|
|
56
|
+
* - Windows 盘符绝对:`C:\Users\x`、`C:/home/x`
|
|
56
57
|
* - Windows UNC:`\\server\share\x`、`//server/share/x`
|
|
57
58
|
*
|
|
58
59
|
* 反例(仍报 H2):`C:relative`(盘符相对)、`Users/x`、`./x`、空串。
|
|
@@ -108,6 +109,19 @@ export function validateSessionLog(log, opts = {}) {
|
|
|
108
109
|
if (frameInfo?.error) {
|
|
109
110
|
violations.push(violation('Z2', { lineNo: null }, frameInfo.error));
|
|
110
111
|
}
|
|
112
|
+
// ── Z6 · 尾部完整性显式声明(0.3.28 · 口径边界)────────────────────────
|
|
113
|
+
// `ok=true` 只保证"已读到的事件自洽",**不保证尾部完整**(最后一帧被切掉仍可能 ok)。
|
|
114
|
+
// tailStatus 是机器可判字段:complete | interrupted | truncated | unknown。
|
|
115
|
+
const tail = deriveTailStatus({ frameInfo, rows, header });
|
|
116
|
+
if (tail.tailStatus !== 'complete') {
|
|
117
|
+
const why = {
|
|
118
|
+
interrupted: 'zstd 尾帧未写完(写入中断/进行中;宿主读取器丢弃未写完尾帧、保留完整记录,可恢复)',
|
|
119
|
+
truncated: '末行记录被切断(不是完整 JSON)——尾部数据缺失,需修复/回滚',
|
|
120
|
+
unknown: '尾部状态不可判(帧解码失败 / 空文件 / 不可读)',
|
|
121
|
+
}[tail.tailStatus] ?? tail.tailStatusReason;
|
|
122
|
+
violations.push(violation('Z6', { lineNo: null },
|
|
123
|
+
`尾部完整性 = ${tail.tailStatus}(${tail.tailStatusReason}):${why} —— 本次结论只覆盖"已读到的事件";机器判读用 summary.tailStatus`));
|
|
124
|
+
}
|
|
111
125
|
// Z4 · 首帧必须恰好一行 header(2026-09-16 真机事故:整份日志被重压成单帧 ⇒ 客户端起不来)
|
|
112
126
|
if (frameInfo?.firstFrameOneLine === false) {
|
|
113
127
|
violations.push(violation('Z4', { lineNo: null },
|
|
@@ -274,6 +288,10 @@ export function validateSessionLog(log, opts = {}) {
|
|
|
274
288
|
fileVersion: formatVersion,
|
|
275
289
|
hostMaxFileVersion: HOST_MAX_FILE_VERSION,
|
|
276
290
|
assessable: true,
|
|
291
|
+
// Z6(0.3.28):尾部完整性机器可判字段 + 损坏行计数(R4"可统计")。
|
|
292
|
+
tailStatus: tail.tailStatus,
|
|
293
|
+
tailStatusReason: tail.tailStatusReason,
|
|
294
|
+
unreadableRows: rows.filter((r) => r.error).length,
|
|
277
295
|
// 0.3.19:结构化读数(不进 ok,只供报告/机器判读)
|
|
278
296
|
seedLength: Object.hasOwn(header ?? {}, 'seedLength') ? header.seedLength : null,
|
|
279
297
|
ignorableDrops: { registered: ignorableDrops.registered.length, unregistered: ignorableDrops.unregistered.length },
|
|
@@ -283,6 +301,8 @@ export function validateSessionLog(log, opts = {}) {
|
|
|
283
301
|
const result = {
|
|
284
302
|
ok: bySeverity.error === 0,
|
|
285
303
|
assessable: true,
|
|
304
|
+
// Z6:尾部完整性与 `ok` **并列**(ok 只保证"已读到的事件自洽")。
|
|
305
|
+
tailStatus: tail.tailStatus,
|
|
286
306
|
violations,
|
|
287
307
|
summary,
|
|
288
308
|
surface: folded.surface ?? { nodes: replay.nodes, replacements: [] },
|
|
@@ -326,6 +346,10 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
|
|
|
326
346
|
// ── Z · 帧结构(版本无关)──
|
|
327
347
|
if (frameInfo?.torn) violations.push(violation('Z1', { lineNo: null }, `zstd 尾帧撕裂:可能是写入中的 in-flight 帧或文件被截断(帧数 ${frameInfo.frames})`));
|
|
328
348
|
if (frameInfo?.error) violations.push(violation('Z2', { lineNo: null }, frameInfo.error));
|
|
349
|
+
const tail = deriveTailStatus({ frameInfo, rows, header });
|
|
350
|
+
if (tail.tailStatus !== 'complete') {
|
|
351
|
+
violations.push(violation('Z6', { lineNo: null }, `尾部完整性 = ${tail.tailStatus}(${tail.tailStatusReason})——本次结论只覆盖"已读到的事件";机器判读用 summary.tailStatus`));
|
|
352
|
+
}
|
|
329
353
|
|
|
330
354
|
// ── H · header(版本无关)──
|
|
331
355
|
if (header === null) {
|
|
@@ -388,6 +412,7 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
|
|
|
388
412
|
ok: false, // 不认证(**不是**"broken"——语义见 notAssessable.reason)
|
|
389
413
|
assessable: false,
|
|
390
414
|
structuralOk: bySeverity.error === 0,
|
|
415
|
+
tailStatus: tail.tailStatus,
|
|
391
416
|
notAssessable,
|
|
392
417
|
violations,
|
|
393
418
|
summary: {
|
|
@@ -403,6 +428,9 @@ function unassessableResult({ header, headerLine, rows, events, frameInfo, baseS
|
|
|
403
428
|
fileVersion: formatVersion,
|
|
404
429
|
hostMaxFileVersion: HOST_MAX_FILE_VERSION,
|
|
405
430
|
assessable: false,
|
|
431
|
+
tailStatus: tail.tailStatus,
|
|
432
|
+
tailStatusReason: tail.tailStatusReason,
|
|
433
|
+
unreadableRows: rows.filter((r) => r.error).length,
|
|
406
434
|
seedLength: Object.hasOwn(header ?? {}, 'seedLength') ? header.seedLength : null,
|
|
407
435
|
ignorableDrops: { registered: 0, unregistered: 0 },
|
|
408
436
|
archiveVerdict: archive.verdict,
|
|
@@ -435,7 +463,7 @@ function hostProbes() {
|
|
|
435
463
|
/**
|
|
436
464
|
* 合并出的**漂移报告**(`check` 抬头与 `--json` 共用)。
|
|
437
465
|
* · `unverifiedRules` —— 行为探针在本宿主上**不成立**的规则(宿主语义与规则假设不符);
|
|
438
|
-
* · `driftedSources` —— 出处停在 rc.7、未在 0.1.5
|
|
466
|
+
* · `driftedSources` —— 出处停在 rc.7、未在 0.1.5 上internal(机读清单);
|
|
439
467
|
* · `premiseStale` —— 判定前提已不成立/无法判定;
|
|
440
468
|
* · `fixApplyBlocked` —— 只要任一非空,就**不得据此跑 `fix --apply`**。
|
|
441
469
|
*/
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-log-contract",
|
|
3
3
|
"description": "日志契约守护 — DSH session log contract guard: offline health check (CLI) + pre-write validation for DeepSeek Harness session logs",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.29",
|
|
5
5
|
"packageManager": "pnpm@11.7.0",
|
|
6
6
|
"type": "module",
|
|
7
7
|
"main": "lib/index.js",
|
|
@@ -31,7 +31,11 @@
|
|
|
31
31
|
"scripts": {
|
|
32
32
|
"check": "node scripts/check-syntax.mjs && node scripts/gen-contracts-doc.mjs --check",
|
|
33
33
|
"test": "vitest run",
|
|
34
|
-
"prepublishOnly": "node scripts/check-pkg-meta.mjs && node scripts/prepublish-gate.mjs && pnpm check && pnpm test"
|
|
34
|
+
"prepublishOnly": "node scripts/pre-publish.mjs --release && node scripts/check-pkg-meta.mjs && node internal/scripts/prepublish-gate.mjs && pnpm check && pnpm test",
|
|
35
|
+
"surface:check": "node scripts/check-external-surface.mjs",
|
|
36
|
+
"review:check": "node scripts/check-review-record.mjs",
|
|
37
|
+
"release:check": "node scripts/check-release-discipline.mjs && node scripts/check-external-surface.mjs && node scripts/check-review-record.mjs",
|
|
38
|
+
"release": "node scripts/release.mjs"
|
|
35
39
|
},
|
|
36
40
|
"keywords": [
|
|
37
41
|
"dsh",
|