dsh-log-contract 0.3.18 → 0.3.20

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
@@ -60,8 +60,8 @@ humans and automated programs. Humans tolerate format drift; programs depend on
60
60
  strict contracts. Once the format drifts, humans see nothing wrong while programs
61
61
  crash or misreport.
62
62
 
63
- **Real incidents shaped most of the rules here** — see the [Incident log](#-incident-log)
64
- below. The incident-derived cases are pinned by regression tests: a corrupt log shape
63
+ **Real log-corruption shapes found in production sessions shaped most of the rules here** —
64
+ see the [Case log](#-case-log) below. The case-derived instances are pinned by regression tests: a corrupt log shape
65
65
  this tool must flag, and the repaired shape it must pass. The remaining rules come from
66
66
  line-by-line verification against the official Host source (each rule carries its
67
67
  `source`).
@@ -86,10 +86,10 @@ line-by-line verification against the official Host source (each rule carries it
86
86
 
87
87
  ---
88
88
 
89
- ## ⚡ Incident log — why "production-grade" is not a slogan
89
+ ## ⚡ Case log — why "production-grade" is not a slogan
90
90
 
91
- Each entry below is a **real incident** from production sessions — the cases that
92
- made us build this tool. Dates and shapes are real; session ids and file names are
91
+ Each entry below is a **real log-corruption shape** from production sessions — the cases that
92
+ shaped this tool. Dates and shapes are real; session ids and file names are
93
93
  omitted.
94
94
 
95
95
  | # | Date | What happened | The rule / fix it produced |
@@ -201,10 +201,10 @@ dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
201
201
  - `--remove-markers`: remove retrace/message-editor markers and renumber everything
202
202
  (seq/seq0/sourceEventSeqs/surfaceOp in sync) — for large marker-shadowed history
203
203
  or markers that left dangling tools.
204
- - `--neutralize`: in-place neutralization of turn-null markers (incident #6) —
204
+ - `--neutralize`: in-place neutralization of turn-null markers (case #6) —
205
205
  type → `retrace/marker` + `ignorable:true`, drops surfaceOp/sourceEventSeqs,
206
206
  seq/line count unchanged (safe while the session is resident).
207
- - `--clip-crossstep`: trim cross-step sourceEventSeqs (incident #6) — keep only
207
+ - `--clip-crossstep`: trim cross-step sourceEventSeqs (case #6) — keep only
208
208
  same-turn/step chunk references.
209
209
  - Surgery safety protocol: back up first, re-verify after (strictScan + check +
210
210
  foldSurface); markers may only shadow earlier nodes; a marker must never become
@@ -326,7 +326,7 @@ boundary note in [docs/CONTRACTS.md](docs/CONTRACTS.md).
326
326
  - [x] **Phase 1.5 (0.2.0)**: `fix` subcommand (strict seq scan + W1/W2 wire checks +
327
327
  marker removal with renumbering + official frame rebuild); CI integration
328
328
  (`dsh-log-contract check` as a scheduled guard over the Harness session dir)
329
- - [x] **0.3.x (2026-08-30 incident hardening)**: T1 token-meter pairing → 0.3.1 W1/W2
329
+ - [x] **0.3.x (2026-08-30 case hardening)**: T1 token-meter pairing → 0.3.1 W1/W2
330
330
  fold-position fix → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize` (in-place
331
331
  turn-null neutralization) → 0.3.4 `fix --clip-crossstep` (cross-step clipping) →
332
332
  0.3.5 **T2/S9/I1 rules** (cross-step source refs / physical order / inbox replay)
@@ -346,8 +346,8 @@ MIT © OfferKuai Team
346
346
 
347
347
  ## ⚠️ Upgrading to 0.3.17 — behaviour changes you must know (0.3.12 → 0.3.17)
348
348
 
349
- > **0.3.17 changes no behaviour.** It rewrites comments, test titles, a few diagnostic strings and the
350
- > README so that they describe the product and its contract only. Every verdict, exit code and `--json`
349
+ > **0.3.17 changes no behaviour.** It only adjusts the wording of comments, test titles, a few
350
+ > diagnostic strings and the README. Every verdict, exit code and `--json`
351
351
  > field is unchanged from 0.3.15, so everything below applies unchanged when going from 0.3.12 to 0.3.17.
352
352
  >
353
353
  > 0.3.15 was a documentation-only release as well.
package/README.zh.md CHANGED
@@ -50,7 +50,7 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
50
50
 
51
51
  **「one log, two consumers, two verdicts」**:一条日志同时被人类与自动化程序消费,人眼容忍格式微调,程序解析依赖严格契约;格式一旦漂移,人看不出问题,程序直接崩溃或误报。
52
52
 
53
- **这里大多数规则都来自真实事故**——见下方 [⚡ 事故记录](#-事故记录)。事故派生的用例都有回归测试钉住:损坏的日志形态本工具必须报出,修复后的形态必须通过。其余规则来自对官方宿主源码的逐行核对(每条规则都带 `source`)。
53
+ **这里大多数规则都来自会话日志中实际出现过的损坏形态**——见下方 [⚡ 案例记录](#-案例记录)。由这些案例派生的用例都有回归测试钉住:损坏的日志形态本工具必须报出,修复后的形态必须通过。其余规则来自对官方宿主源码的逐行核对(每条规则都带 `source`)。
54
54
 
55
55
  ---
56
56
 
@@ -69,9 +69,9 @@ dsh-retrace 的「日志体检与修复」能力——与 dsh-retrace 一起构
69
69
 
70
70
  ---
71
71
 
72
- ## ⚡ 事故记录 ——「生产级保证」不是口号
72
+ ## ⚡ 案例记录 ——「生产级保证」不是口号
73
73
 
74
- 下面每一条都是一起来自生产会话的**真实事故**——正是这些案例促成了本工具。日期与形态真实,会话 id 与文件名省略。
74
+ 下面每一条都来自**生产会话中实际出现的日志损坏形态**——正是这些案例促成了本工具。日期与形态真实,会话 id 与文件名省略。
75
75
 
76
76
  | # | 日期 | 发生了什么 | 产出的规则/修复 |
77
77
  |---|---|---|---|
@@ -175,9 +175,9 @@ dsh-log-contract fix ~/.dsh/sessions/<id>.jsonl.zstd --remove-markers --apply
175
175
  - `--remove-markers`:移除 retrace/message-editor marker 并全量重编号
176
176
  (seq/seq0/sourceEventSeqs/surfaceOp 同步)——用于大范围 marker 遮蔽历史、
177
177
  marker 漏盖 tool/result 导致的悬空 tool。
178
- - `--neutralize`:原地中和 turn-null marker(事故 #6)——type → `retrace/marker` +
178
+ - `--neutralize`:原地中和 turn-null marker(案例 #6)——type → `retrace/marker` +
179
179
  `ignorable:true`,删 surfaceOp/sourceEventSeqs,seq/行数不变(会话驻留也安全)。
180
- - `--clip-crossstep`:裁剪跨 step sourceEventSeqs(事故 #6)——只保留同 turn/step 的 chunk 引用。
180
+ - `--clip-crossstep`:裁剪跨 step sourceEventSeqs(案例 #6)——只保留同 turn/step 的 chunk 引用。
181
181
  - 手术安全协议:改前备份、改后全量复检(strictScan + check + foldSurface)、
182
182
  marker 只能遮蔽其之前的节点、marker 绝不能改成 append(M1 客户端崩溃)。
183
183
  - ⚠️ 若会话已被运行中的应用驻留内存,修复文件后需**重启应用**(强杀避免脏状态刷回)。
@@ -257,7 +257,7 @@ if (!verdict.ok) {
257
257
  ## 测试
258
258
 
259
259
  ```bash
260
- pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测(含事故回归用例)
260
+ pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测(含案例回归用例)
261
261
  ```
262
262
 
263
263
  - **合成夹具**(入库):合法会话 / seq 缺口 / 空 sourceEventSeqs / turn=null append / 未知 type / 坏 chunk 行 / 撕裂尾帧 / 未知 marker 前缀 / 自指 shadowed 等。
@@ -284,7 +284,7 @@ pnpm check && pnpm test # 语法检查 + 契约文档漂移闸 + 全部单测
284
284
 
285
285
  - [x] **Phase 1(0.1.0)**:CLI 离线体检 + 写前校验 + 契约目录
286
286
  - [x] **Phase 1.5(0.2.0)**:`fix` 子命令(严格 seq 扫描 + W1/W2 wire 检查 + 移除 marker 重编号 + 官方帧格式重建);CI 集成(`dsh-log-contract check` 作为 Harness 会话目录的定时守护)
287
- - [x] **0.3.x(2026-08-30 事故固化)**:T1 token-meter 配对 → 0.3.1 W1/W2 折叠位置修复 → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize`(turn-null marker 原地中和)→ 0.3.4 `fix --clip-crossstep`(跨 step 引用裁剪)→ 0.3.5 **T2/S9/I1 规则**(跨 step 源引用 / 物理序单调 / inbox 重放)
287
+ - [x] **0.3.x(2026-08-30 案例固化)**:T1 token-meter 配对 → 0.3.1 W1/W2 折叠位置修复 → 0.3.2 `tailSeq` → 0.3.3 `fix --neutralize`(turn-null marker 原地中和)→ 0.3.4 `fix --clip-crossstep`(跨 step 引用裁剪)→ 0.3.5 **T2/S9/I1 规则**(跨 step 源引用 / 物理序单调 / inbox 重放)
288
288
  - [x] **0.3.6 → 0.3.15**:按被检文件版本择路的 v0–v3 规则(T3/T4/T5、L3–L5、E8/E9/E10)、宿主能力与迁移预检的退出码 `3`/`4`,以及如实报告"哪些版本**未**验证"的版本支持说明(详见 [CHANGELOG.md](CHANGELOG.md))
289
289
  - [ ] Phase 2:运行时守护(订阅 session append 事件流实时校验,断裂即标记 `dsh/contract-violation` 事件,策略可配 告警/拦截)——DSH 插件形态
290
290
  - [ ] Phase 3:与 dsh-turn-guard / dsh-retrace 时间线联动
@@ -297,8 +297,8 @@ MIT © OfferKuai Team
297
297
 
298
298
  ## ⚠️ 升级到 0.3.17 —— 必须知道的行为变更(0.3.12 → 0.3.17)
299
299
 
300
- > **0.3.17 不含行为变更。** 它只重写了注释、测试标题、少量诊断文案与 README,让它们
301
- > 只描述产品与契约本身。所有判定结果、退出码与 `--json` 字段与 0.3.15 完全一致,
300
+ > **0.3.17 不含行为变更。** 它只调整了注释、测试标题、少量诊断文案与 README 的措辞。
301
+ > 所有判定结果、退出码与 `--json` 字段与 0.3.15 完全一致,
302
302
  > 因此从 0.3.12 升到 0.3.17 时,下面各条与原来完全一致。
303
303
  >
304
304
  > 0.3.15 同样只是文档层面的发布。
@@ -13,6 +13,7 @@
13
13
  * contracts 列出内置契约规则目录
14
14
  */
15
15
  import fs from 'node:fs';
16
+ import { delimiter as pathDelimiter } from 'node:path';
16
17
  import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport } from '../lib/index.js';
17
18
 
18
19
  /**
@@ -39,8 +40,8 @@ const errOut = (text) => writeAllSync(2, text);
39
40
  const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log contract guard)
40
41
 
41
42
  用法:
42
- dsh-log-contract check <session-log> [--json] [--max-details N] [--resume] [--fail-on-migration] [--no-fail-on-migration]
43
- 离线体检 + **迁移预检**(两个**独立维度**,互不蕴含)。session-log 支持 .jsonl 与 .jsonl.zstd。
43
+ dsh-log-contract check <session-log> [--json] [--max-details N] [--resume] [--fail-on-migration] [--no-fail-on-migration] [--archive-root DIR] [--ignorable-whitelist a,b]
44
+ 离线体检 + **迁移预检** + **在位可还原(A1,独立维度)**。session-log 支持 .jsonl 与 .jsonl.zstd。
44
45
  ⚠️ 口径边界:本工具只判定它实现的规则集。「ok」/「可加载」/「可继续」/「可压缩」
45
46
  **不代表**会话"可用",**不代表**可安全编辑,也**不代表**官方升级路径会接受
46
47
  (迁移是独立维度,覆盖边界见 contracts 输出与 lib/contracts.js 的 G 段)。
@@ -59,6 +60,13 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
59
60
  'partial' = **需要迁移**(version<3):迁移维度只覆盖 2 条规则,另有 6 类未覆盖 ⇒
60
61
  **不构成"官方升级会接受"**;'none' = 本宿主能力不足以评估(文件版本 > 宿主上限)。
61
62
  机器应判 assessmentScope == "full" 才可把绿读作完整评估(partial/none 都不该)。
63
+ --archive-root DIR A1「在位可还原」的归档根目录(可重复;也可用 env
64
+ DSH_LOG_CONTRACT_ARCHIVE_ROOTS,按路径分隔符分隔)。**不提供 = 该维度
65
+ 不可判定(unverifiable),不冒充通过**。只认结构化指针
66
+ (archiveRef/archive/externalized.*),⛔ 不从自由文本 grep 路径。
67
+ --ignorable-whitelist a,b
68
+ G4 可忽略消费者白名单(精确 type 或以 / 结尾的前缀;也可用 env
69
+ DSH_LOG_CONTRACT_IGNORABLE_WHITELIST)。已登记 ⇒ acceptedDrop 不阻断迁移。
62
70
  退出码:0 本工具认为可加载且无迁移阻断;1 有 error 级违规;3 不可在本宿主评估
63
71
  (被检文件版本 > 宿主支持上限,如 rc.7 宿主的 v3 文件——**不是** broken);
64
72
  4 迁移预检 blocked(assessmentScope=partial 且 migration.ready=false;可用
@@ -202,6 +210,16 @@ function migrationLine(mig, partial = false) {
202
210
  s += ` [${v.id}] seq ${v.seq ?? '-'}${v.eventType ? ` (${v.eventType})` : ''} — ${String(v.message).slice(0, 130)}\n`;
203
211
  }
204
212
  if (n > 5) s += ` …另有 ${n - 5} 项\n`;
213
+ const drops = mig.acceptedDrops ?? { registered: [], unregistered: [] };
214
+ if (drops.registered.length > 0) {
215
+ s += ` 声明式可忽略(G4 · 已登记 acceptedDrop,不阻断迁移):${drops.registered.length} 项`;
216
+ const types = [...new Set(drops.registered.map((d) => d.eventType).filter(Boolean))];
217
+ if (types.length > 0) s += `(${types.slice(0, 5).join('、')}${types.length > 5 ? ' 等' : ''})`;
218
+ s += '\n';
219
+ }
220
+ if (drops.unregistered.length > 0) {
221
+ s += ` ⛔ 声明可忽略但**未登记**(G4 warning,仍阻断迁移):${drops.unregistered.length} 项——登记到 opts.ignorableWhitelist / DSH_LOG_CONTRACT_IGNORABLE_WHITELIST 后才移出阻断\n`;
222
+ }
205
223
  s += ` 覆盖边界:已覆盖 ${mig.coverage.implemented.length} 条;未覆盖 ${mig.coverage.uncovered.length} 类官方迁移规则(未覆盖 ≠ 通过;判据 ${mig.coverage.note})\n`;
206
224
  // 规格 (iii):把未覆盖类名直接列出来,人不必开 --json 才知道边界。
207
225
  if (partial) {
@@ -210,6 +228,23 @@ function migrationLine(mig, partial = false) {
210
228
  return s;
211
229
  }
212
230
 
231
+ /**
232
+ * A1「在位可还原」独立维度(0.3.19 · 最小集 ⑤)。
233
+ * 未提供归档根 ⇒ `unverifiable`(不冒充通过);提供后才给读数与违规。
234
+ */
235
+ function archiveLines(archive) {
236
+ if (!archive) return '';
237
+ if (archive.verdict === 'unverifiable') {
238
+ return ' 在位可还原(A1,独立维度):— 未提供归档根目录(不可判定;加 `--archive-root DIR` 或 env DSH_LOG_CONTRACT_ARCHIVE_ROOTS 才评估)\n';
239
+ }
240
+ const rate = (archive.restorableRate * 100).toFixed(2);
241
+ let s = ` 在位可还原(A1,独立维度,只认结构指针):${archive.verdict === 'restorable' ? '✅' : '❌'} ${rate}%`
242
+ + `(指针 ${archive.pointers},去重后 ${archive.effectivePointers ?? archive.pointers}:可还原 ${archive.restorable}`
243
+ + ` / relocated ${archive.relocated} / 缺失 ${archive.missing} / 行缺失 ${archive.lineMissing} / sha 不符 ${archive.shaMismatch} / 无法解析 ${archive.unresolved})\n`;
244
+ if (archive.relocated > 0) s += ' ⚠️ relocated:绝对路径已失效但同名归档在归档根可解析(内容可找回,但不在位;re-home 未回写)\n';
245
+ return s;
246
+ }
247
+
213
248
  function cmdCheck(args) {
214
249
  const json = args.includes('--json');
215
250
  const resume = args.includes('--resume');
@@ -220,7 +255,32 @@ function cmdCheck(args) {
220
255
  const noFailOnMigration = args.includes('--no-fail-on-migration');
221
256
  const maxDetailsIdx = args.indexOf('--max-details');
222
257
  const maxDetails = maxDetailsIdx >= 0 && args[maxDetailsIdx + 1] ? Number(args[maxDetailsIdx + 1]) : 8;
223
- const file = args.find((a) => !a.startsWith('-'));
258
+ // 0.3.19:G4 白名单 / A1 归档根(可重复 `--archive-root DIR`,或 env 用 path.delimiter 分隔)。
259
+ const flagValues = (flag) => {
260
+ const vals = [];
261
+ for (let i = 0; i < args.length; i++) if (args[i] === flag && args[i + 1] !== undefined && !args[i + 1].startsWith('-')) vals.push(args[i + 1]);
262
+ return vals;
263
+ };
264
+ const archiveRoots = [
265
+ ...flagValues('--archive-root'),
266
+ ...(process.env.DSH_LOG_CONTRACT_ARCHIVE_ROOTS ? process.env.DSH_LOG_CONTRACT_ARCHIVE_ROOTS.split(pathDelimiter).filter(Boolean) : []),
267
+ ];
268
+ const whitelistRaw = [
269
+ ...flagValues('--ignorable-whitelist'),
270
+ ...(process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST ? [process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST] : []),
271
+ ];
272
+ const ignorableWhitelist = whitelistRaw.length > 0
273
+ ? whitelistRaw.flatMap((v) => String(v).split(',')).map((s) => s.trim()).filter(Boolean)
274
+ : undefined;
275
+ // 取位置参数时排除所有带值开关的值(否则 `--archive-root /x` 的 /x 会被当成被检文件)。
276
+ const valuedFlags = new Set(['--max-details', '--archive-root', '--ignorable-whitelist']);
277
+ const positional = [];
278
+ for (let i = 0; i < args.length; i++) {
279
+ const a = args[i];
280
+ if (a.startsWith('-')) { if (valuedFlags.has(a)) i++; continue; }
281
+ positional.push(a);
282
+ }
283
+ const file = positional[0];
224
284
  if (!file) fail(USAGE);
225
285
 
226
286
  let log;
@@ -229,7 +289,7 @@ function cmdCheck(args) {
229
289
  } catch (err) {
230
290
  fail(`读取失败:${err.message}`);
231
291
  }
232
- const result = validateSessionLog(log);
292
+ const result = validateSessionLog(log, { archiveRoots, ignorableWhitelist });
233
293
  const { summary, violations, ok } = result;
234
294
  const notAssessable = result.assessable === false;
235
295
  const migration = result.migration ?? migrationVerdict(result);
@@ -244,7 +304,7 @@ function cmdCheck(args) {
244
304
  const exitCode = notAssessable ? 3 : (!ok ? 1 : (migGate ? 4 : 0));
245
305
 
246
306
  if (json) {
247
- const payload = { file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations };
307
+ const payload = { file, ok, assessable: !notAssessable, assessmentScope: scope, host: hostCapability(), support: result.support ?? null, probes: result.probes ?? null, drift: result.drift ?? null, migration, summary, violations, archive: result.archive ?? null, ignorableDrops: result.ignorableDrops ?? null };
248
308
  if (notAssessable) payload.notAssessable = result.notAssessable;
249
309
  if (resume) payload.resume = resumeVerdict(result);
250
310
  out(JSON.stringify(payload, null, 2) + '\n');
@@ -280,6 +340,7 @@ function cmdCheck(args) {
280
340
  out(supportLines(result.support));
281
341
  out(driftLines(result.drift, result.probes));
282
342
  out(migrationLine(migration, partial));
343
+ out(archiveLines(result.archive));
283
344
  out(`\n 结论: ${icons[tier]}${migBlocked
284
345
  ? '(本工具规则集内)—— 但**迁移预检 blocked**:不得据此宣称"可升级"'
285
346
  : partial
@@ -295,6 +356,7 @@ function cmdCheck(args) {
295
356
  out(supportLines(result.support));
296
357
  out(driftLines(result.drift, result.probes));
297
358
  out(migrationLine(migration, partial));
359
+ out(archiveLines(result.archive));
298
360
  out('\n');
299
361
  printViolations(violations, maxDetails);
300
362
  out(`\n${ok
@@ -327,7 +389,10 @@ function cmdPrewrite(args) {
327
389
  } catch (err) {
328
390
  fail(`会话日志读取失败:${err.message}`);
329
391
  }
330
- const baseline = validateSessionLog(log);
392
+ const prewriteWhitelist = process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST
393
+ ? process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST.split(',').map((x) => x.trim()).filter(Boolean)
394
+ : undefined;
395
+ const baseline = validateSessionLog(log, { ignorableWhitelist: prewriteWhitelist });
331
396
  // 版本支持面(2026-09-14 用户要求第 1 条):**未验证格式 ⇒ 只读**,不得给出写入结论。
332
397
  if (baseline.support?.readOnly) {
333
398
  fail(`未验证的会话格式(来源 ${baseline.support.file.source},版本 v${baseline.support.file.version})——按只读处理,写前校验无法给出可信结论。`
@@ -343,7 +408,7 @@ function cmdPrewrite(args) {
343
408
  }
344
409
 
345
410
  // C2:把被检文件的 header 显式交给 prewriter(版本不再靠模块级全局;缺省也能自行推断)
346
- const prewriter = createPreWriter({ events: log.events.map((e) => e.event), header: log.header });
411
+ const prewriter = createPreWriter({ events: log.events.map((e) => e.event), header: log.header, ignorableWhitelist: prewriteWhitelist });
347
412
  let result;
348
413
  if (Object.hasOwn(plan, 'append')) {
349
414
  result = prewriter.validateAppend(plan.append);
package/docs/CONTRACTS.md CHANGED
@@ -22,7 +22,7 @@
22
22
  >
23
23
  > 严重度:**error** = 违反即会话不可加载/写入被拒(fail-loud);**warning** = 合法但可疑。
24
24
 
25
- ## 规则索引(共 46 条)
25
+ ## 规则索引(共 51 条)
26
26
 
27
27
  | id | 严重度 | 层级 | 规则 |
28
28
  |---|---|---|---|
@@ -34,7 +34,9 @@
34
34
  | E1 | error | persistence | 每个事件携带非负安全整数 seq |
35
35
  | E2 | error | persistence | seq 严格连续(单写入者假设) |
36
36
  | S9 | error | persistence | 文件物理序 seq 单调(多写入者交织现场特征) |
37
+ | S10 | error | persistence | sourceEventSeqs 元素必须是(解码后的)非负整数;存储形态只允许官方区间对 |
37
38
  | I1 | error | engine | inbox seed 相对重放(fork 边界孤儿 spliced) |
39
+ | I2 | error | persistence | seedLength = 继承事件条数(不是字节数);parentSession ∧ seedLength∈{缺失,0} 合法 |
38
40
  | E3 | error | persistence | type 必须在已知词汇表内(或带 ignorable 标记) |
39
41
  | E4 | error | persistence | data 与 surface 元数据必须 JSON 无损 |
40
42
  | E5 | error | persistence | 禁用遗留词汇 |
@@ -62,6 +64,7 @@
62
64
  | M1 | error | engine | turn/step 为 null 的 assistant/message 只能 replace,不能 append |
63
65
  | P1 | warning | plugin | marker id 前缀必须被识别 |
64
66
  | P2 | error | plugin | marker 自身 seq 不得出现在自身 shadowed 集 |
67
+ | P5 | error | plugin | carrier 两段配对:第 2 段 sourceEventSeqs 首元素 = 第 1 段(审计段)seq |
65
68
  | C1 | warning | concurrency | seq 缺口/倒退提示多写入者 |
66
69
  | Z1 | warning | framing | zstd 尾帧撕裂 |
67
70
  | Z2 | error | framing | zstd 帧解码失败 = 单帧全损 |
@@ -72,6 +75,8 @@
72
75
  | G1 | warning | migration | 迁移预检:v0 源文件的 subagent/descriptor.data.version 必须为 3 |
73
76
  | G2 | warning | migration | 迁移预检:v0 源文件不得含词表外的历史事件类型(含 ignorable) |
74
77
  | G3 | warning | migration | 迁移预检:v0 源 session/title 系列的 messageSeqs 必须引用更早的人类 user/message |
78
+ | G4 | warning | migration | 未知历史事件声明式可忽略(ignorable:true + 白名单)——迁移不得硬拒 |
79
+ | A1 | error | archive | 在位可还原只认结构化归档指针(archiveRef / archive / externalized.*) |
75
80
 
76
81
  ## 详细规则
77
82
 
@@ -123,12 +128,24 @@
123
128
  - **出处**: 2026-08-28 实锤(某真实会话):文件物理序出现回退(大→小→更大);单进程 appendCore 断言 seq==cursor+i 且按 id 串行化不可能写出
124
129
  - **契约**: 按文件物理行序要求展开后事件 seq 严格单调递增。E2 在排序后检查(loadSessionLog 会 sort),物理序倒退被掩盖;S9 在排序前按行序检查,非单调 = 多写入者/旧光标回放交织的直接现场证据,加载会被拒。
125
130
 
131
+ ### S10 — sourceEventSeqs 元素必须是(解码后的)非负整数;存储形态只允许官方区间对
132
+
133
+ - **层级**: persistence | **严重度**: error
134
+ - **出处**: @deepseek-ai/dsh-session@0.2.0-rc.2 lib/index.js:963-999(encodeSeqRanges:连续 ≥3 才压缩成 `[start,end]`,即 v3+ JSONL 的存储形态)、:1000-1026(decodeSeqRanges/assertSeq:元素必须是非负安全整数,区间对只允许 `[start,end]` 且 start ≤ end、解码后严格递增)
135
+ - **契约**: 所有事件的 `sourceEventSeqs`(**含非 surface 类型与 ignorable 未知插件事件**)原始存储形态只允许两种元素:非负安全整数、或官方区间对 `[start,end]`;经官方 `decodeSeqRanges` 解码后必须全部是非负安全整数。解码后仍为数组/非整数 = 契约违规(投影层/restore/重写路径会把它静默当成 seq,实测 v4test 即如此)⇒ 判红并给出该事件的 seq/行号。注意:`[a,b]` 本身是 v3+ 的**合法存储形态**(本机 760 份真实会话里 265 处,全部可解码),不得误报;判红点是「解码后仍非整数」与「非官方区间对形态」。
136
+
126
137
  ### I1 — inbox seed 相对重放(fork 边界孤儿 spliced)
127
138
 
128
139
  - **层级**: engine | **严重度**: error
129
140
  - **出处**: @deepseek-ai/dsh-agent lib/types/inbox.js:155-178 (apply/validate);2026-08-28 实锤(某两个真实会话):fork 边界 removedCount=1 孤儿
130
141
  - **契约**: 从 header.seedLength 起重放 agent/inbox/spliced,next-turn/next-step 双队列;start+removedCount 不得超过队列长、不得产生重复 pending id。fork 时"移除父待处理提示词"的 splice 假设父会话 inbox,子会话 seed 相对空 inbox 上非法 → resume 被拒(invalid persisted inbox splice)。
131
142
 
143
+ ### I2 — seedLength = 继承事件条数(不是字节数);parentSession ∧ seedLength∈{缺失,0} 合法
144
+
145
+ - **层级**: persistence | **严重度**: error
146
+ - **出处**: @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–105.4 MB ⇒ `seedLength` 既不可能是字节数(差 1–2 个数量级),也不可能是行数(行数仅 1.3–7 万)⇒ 真实数据与"继承事件条数"一致,本机命中 0 例 `> 展开事件数`(判红分支是防"当字节数用"的护栏)。
148
+
132
149
  ### E3 — type 必须在已知词汇表内(或带 ignorable 标记)
133
150
 
134
151
  - **层级**: persistence | **严重度**: error
@@ -291,6 +308,12 @@
291
308
  - **出处**: retrace 插件 lib/client.js:393("event and never a surface node")
292
309
  - **契约**: marker 的 sourceEventSeqs(= shadowedSeqs,驱动 CSS 隐藏)不得包含 marker 自身 seq——marker 节点由隐藏逻辑跳过,出现在 shadowed 集属于自指语义错误。
293
310
 
311
+ ### P5 — carrier 两段配对:第 2 段 sourceEventSeqs 首元素 = 第 1 段(审计段)seq
312
+
313
+ - **层级**: plugin | **严重度**: error
314
+ - **出处**: 仓库既有两段载体形状(test/semantics-v4.test.js:108-121:`compaction/prune` 审计段 + `user/message` replace 载体);2026-10-20 本机实测 760 份真实 v3/v4:884 个载体按现役写法(审计段 seq 在 `sourceEventSeqs[0]`,全部 user/message);另有 1,519 个载体按**早期写法**(首元素 = 区间起点、不引用审计段 seq;user/message 1,022 + tool/result 497)⇒ 读侧必须两种都认;对照官方 compaction 的 `compaction/summary` 引用是另一形状(`[compaction/start, compaction/summary, …]`,15 例),不属本条
315
+ - **契约**: 两段载体(第 1 段 = `compaction/prune` 审计段,带 `data.shadowedRange`/`shadowedSeqs`;第 2 段 = 紧随其后的 surface replace 载体)的配对规则:第 2 段 `sourceEventSeqs[0]` 必须等于第 1 段的 seq(现役写法),其余元素覆盖被遮蔽节点。**读侧容错(两种写法都认)**:① 现役 `[审计段 seq, ...被遮蔽节点]`;② 早期 `[区间起点, ...被遮蔽节点]`(不引用审计段 seq——实测真实语料 1,519 个载体即此写法,若判红会全成"孤儿")。只有"审计段 seq 在中间位且首元素既非审计段也非区间起点"、或"紧邻审计段却既不引用它、首元素也不是区间起点"才报 error。**写侧**(prewrite)按现役写法严格校验:拟写载体若紧邻审计段,`sourceEventSeqs[0]` 必须是该审计段 seq,否则拒绝(早期写法在写侧被要求升级)。
316
+
294
317
  ### C1 — seq 缺口/倒退提示多写入者
295
318
 
296
319
  - **层级**: concurrency | **严重度**: warning
@@ -351,3 +374,15 @@
351
374
  - **出处**: @deepseek-ai/dsh-session-format-v0-to-v1@0.1.5-rc.2 lib/index.js:2543-2556(assertTitleSources):`session/title` 的 messageSeqs 为空 ⟺ source.kind === "user";每个被引 seq 必须解析到 `user/message` 且其 `data.source.kind === "user"`,否则 "messageSeqs must cite earlier human user/message events" / "must be empty exactly for a user title"
352
375
  - **契约**: 文件版本 0 且事件为 session/title 或 session/title-llm-request:messageSeqs 必须是数组;session/title 的"空数组 ⟺ 用户标题"必须成立;每个被引 seq 必须是更早的 user/message 且 source.kind === "user"。违反 → 官方升级到当前格式时拒绝。**应用面说明**:官方 `assertTitleSources` 与 turn/start 状态机同在 `assertReleasedArtifactRelationships`,由 v1→v2 在**变换后的 v1/v2 artifact** 上调用(`dsh-session-format-v1-to-v2/lib/index.js:104`);对 messageSeqs 这类按 seq 索引 + 类型/source 判定的引用,变换保序保类型 ⇒ 在原始 v0 上判是必要条件的近似,实测 281 真实 v0 上 0 误报。
353
376
 
377
+ ### G4 — 未知历史事件声明式可忽略(ignorable:true + 白名单)——迁移不得硬拒
378
+
379
+ - **层级**: migration | **严重度**: warning
380
+ - **出处**: @deepseek-ai/dsh-session-format-v0-to-v1@0.2.0-rc.2 package/lib/index.js:1513-1535(assertReleasedArtifactCoordinates:`ignorableCurrent` 分支只在 allowLegacySteering=false 时生效;:1531 原文 "migration refuses unknown historical events even when ignorable")、同处 `vocabularyNeutral` 参数("whether unknown event types remain opaque",未知类型按不透明事件保留的策略)
381
+ - **契约**: 未知历史事件(不在本包 vendored v0 词表内)若带信封级 `ignorable:true`,契约层按**声明式可忽略**处置:允许按声明丢弃并登记为 `acceptedDrop`,**不得**让整条迁移硬拒(这正是"每新增一类插件事件就卡死整条迁移"的根因)。消费者白名单可注入:`opts.ignorableWhitelist` / `createPreWriter({ignorableWhitelist})` / 环境变量 `DSH_LOG_CONTRACT_IGNORABLE_WHITELIST`(逗号分隔;元素为精确 type 或以 `/` 结尾的前缀),默认 = 已知插件消费者 `retrace/`、`message-editor/`。**未登记**的未知 ignorable 事件仍报 G4 warning(⛔ 不静默),且保持迁移阻断。G2 仍**原样保留**为"官方 v0→v1 会拒"的事实预检,不放宽;本规则只把"已声明可忽略且已登记"的事件从迁移阻断移入 `acceptedDrops`。实测:本机 2 份真实 v0 化石含 `retrace/goal-marker`(ignorable),默认白名单命中 ⇒ acceptedDrops,迁移不再被它阻断。
382
+
383
+ ### A1 — 在位可还原只认结构化归档指针(archiveRef / archive / externalized.*)
384
+
385
+ - **层级**: archive | **严重度**: error
386
+ - **出处**: 归档指针口径的外部实测(2026-10-20):只认 `archiveRef`/`archive`/`externalized.*`,⛔ 不得从自由文本 grep 路径;两版文本口径实测全错(原版 78.26%、只认绝对路径 2.04%);本机 763 份真实会话实测:结构化指针 273,571 个 → 按(目标,行)去重后 271,538 条记录,**可还原 271,538(100%)**、真实落空 0、行缺失 0、sha 不符 0;同批数据自由文本 `archive 第 N 行` 出现在 144,391 个事件里(口径差近 20 倍)
387
+ - **契约**: 外置内容的"在位可还原"判定**只**从结构化字段取指针:`data.archiveRef` / `data.archive` / `data.externalized.archiveRef` / `data.externalized.archive`(校验元数据取同级 `archiveLine`/`sha256`);⛔ **永不**从 `content`/`pointer`/散文模板等自由文本 grep 路径(实测两版全错:模板/示例会被算成引用,真实路径示例又被误计)。判据:目标文件存在 + `archiveLine` 行存在 + `sha256` 匹配 = 在位可还原;目标缺失/行缺失/sha 不符 = error;绝对路径失效但同名归档在归档根可解析 = `relocated` warning(re-home 未回写)。**按记录去重**:同一事件同时带 `archiveRef`(basename) 与 `archive`(绝对路径) 时按(目标,行)算一条记录——本机 2,033 个双字段指针即此类(其中 `/tmp` 绝对路径已失效者由 `archiveRef` 解析回 history 根,故真实落空 0,而不是把工具限制或旧路径算成内容缺失)。**独立维度**:需要归档根目录才能评估(`opts.archiveRoots` / `check --archive-root DIR`),未提供时结论为 `unverifiable`(不冒充通过,也不产生违规)。启用本维度后,真实缺失/行缺失/sha 不符是 **error**(红判据:在位可还原须 100%),会进 `ok` 与三档结论;`relocated` 只是 warning。
388
+