dsh-log-contract 0.3.28 → 0.3.33

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.
@@ -14,12 +14,12 @@
14
14
  */
15
15
  import fs from 'node:fs';
16
16
  import { delimiter as pathDelimiter } from 'node:path';
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
+ import { loadSessionLog, validateSessionLog, resumeVerdict, migrationVerdict, assessmentScope, createPreWriter, repairSession, readSessionHeader, CONTRACT_RULES, ruleById, explainRule, extractToolOutputs, auditToolCalls, hostCapability, HOST_MAX_FILE_VERSION, detectSupport } from '../lib/index.js';
18
18
 
19
19
  /**
20
20
  * 同步写 fd——`process.stdout.write` 在**管道**下是异步的,紧跟着的
21
21
  * `process.exit()` 不会等待 flush:>~64KiB 的输出会丢尾,`--json` 因此变成非法 JSON
22
- * (实测在 [n] 事件夹具与真实 [size] v3 会话上复现,stdout [n]B 处 "Unterminated string")。
22
+ * (实测在 3000 事件夹具与真实 14.5MB v3 会话上复现,stdout 56648B 处 "Unterminated string")。
23
23
  * 这里直接同步写 fd 1/2(非阻塞管道 EAGAIN 时自旋重试),做到"先写完再 exit"。
24
24
  */
25
25
  function writeAllSync(fd, text) {
@@ -73,14 +73,14 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
73
73
  --no-fail-on-migration 退出该档)。
74
74
 
75
75
  dsh-log-contract fix <session-log> [--remove-markers] [--neutralize] [--neutralize-legacy-markers] [--clip-crossstep] [--drop-failed-turns] [--trim-last N] [--compact-last N] [--tail-renumber D] [--neutralize-orphan] [--extract-turn N] [--keep-ranges a-b,c-d] [--apply] [--backup-dir DIR] [--json]
76
- 诊断 + 修复([n]-08 事故固化方案)。先做严格 seq 连续扫描 + 契约体检
76
+ 诊断 + 修复(2026-08 事故固化方案)。先做严格 seq 连续扫描 + 契约体检
77
77
  (含 W1/W2 wire 级悬空 tool 检查),再按需修复:
78
78
  --remove-markers 移除 retrace/message-editor marker 并全量重编号
79
79
  (用于大范围遮蔽历史 / marker 漏盖 tool/result)
80
80
  --clip-crossstep 裁剪 assistant/message 的跨 step sourceEventSeqs(token-meter 不再抛 belongs to another step)
81
81
  --neutralize 原地中和 turn-null marker(type→retrace/marker +
82
82
  ignorable:true,删 surfaceOp/sourceEventSeqs,seq/行数不变)
83
- —— token-meter 不再刷屏,会话驻留也安全([n]-08-30 事故)
83
+ —— token-meter 不再刷屏,会话驻留也安全(2026-08-30 事故)
84
84
  --neutralize-legacy-markers
85
85
  **一次性根治历史载体债**:只中和
86
86
  assistant/message + data.editor 形态的历史 retrace marker
@@ -122,6 +122,12 @@ const USAGE = `dsh-log-contract —— 日志契约守护(DSH session log cont
122
122
  dsh-log-contract contracts
123
123
  列出内置契约规则目录(含官方源码出处)。
124
124
 
125
+ dsh-log-contract explain <ruleId> [--json]
126
+ 规则解读:标题 / 判据(原文引自规则注册表,⛔ 不另立文本)/ 正反例指针
127
+ (指向 test/ 里的对照用例与夹具)/ 相关命令。
128
+ 未知 id ⇒ 明确提示 + 非零退出;--json 输出稳定键集(id/found/title/severity/
129
+ layer/source/criteria/examples/relatedCommands/doc)。
130
+
125
131
  dsh-log-contract --version / --help
126
132
  `;
127
133
 
@@ -146,7 +152,7 @@ function printViolations(violations, maxDetails = 8) {
146
152
  }
147
153
  }
148
154
 
149
- /** 漂移抬头([n]-09-14):漂移清单 + 未复核清单 + "勿据此跑 fix --apply"。 */
155
+ /** 漂移抬头(2026-09-14):漂移清单 + 未复核清单 + "勿据此跑 fix --apply"。 */
150
156
  function driftLines(drift, probes) {
151
157
  if (!drift) return '';
152
158
  const host = probes ? `${probes.hostPackage}(SESSION_FORMAT_VERSION=${probes.sessionFormatVersion},词表 ${probes.knownTypes} 类)` : '未知';
@@ -166,7 +172,7 @@ function driftLines(drift, probes) {
166
172
  return out;
167
173
  }
168
174
 
169
- /** 版本支持面([n]-09-14 用户要求第 1 条):一行摘要 + 逐条告警。
175
+ /** 版本支持面(2026-09-14 用户要求第 1 条):一行摘要 + 逐条告警。
170
176
  * `readOnly` = 未验证格式 ⇒ 只读(check 照跑结构层;prewrite/fix 直接拒绝)。 */
171
177
  function supportLines(support) {
172
178
  if (!support) return '';
@@ -194,7 +200,7 @@ function notAssessableBanner(result) {
194
200
  /** 迁移预检(独立维度)文本。
195
201
  * @param {object} mig `migrationVerdict()` 结果
196
202
  * @param {boolean} partial 待迁移文件(`migration.applies===true`)⇒ 迁移维度只部分覆盖,
197
- * 不得给无条件绿([n]-09-14 规格 (i)+(iii))。
203
+ * 不得给无条件绿(2026-09-14 规格 (i)+(iii))。
198
204
  */
199
205
  function migrationLine(mig, partial = false) {
200
206
  if (!mig) return '';
@@ -207,7 +213,7 @@ function migrationLine(mig, partial = false) {
207
213
  : ` 迁移预检(独立维度,≠"可用/可升级"):✅ 通过(仅限本工具覆盖范围)\n`)
208
214
  : ` 迁移预检(独立维度,≠"可用/可升级"):❌ blocked(${n} 项:官方升级路径会拒)\n`;
209
215
  for (const v of (mig.blocked ?? []).slice(0, 5)) {
210
- s += ` [${v.id}] seq ${v.seq ?? '-'}${v.eventType ? ` (${v.eventType})` : ''} — ${String(v.message).slice(0, [n])}\n`;
216
+ s += ` [${v.id}] seq ${v.seq ?? '-'}${v.eventType ? ` (${v.eventType})` : ''} — ${String(v.message).slice(0, 130)}\n`;
211
217
  }
212
218
  if (n > 5) s += ` …另有 ${n - 5} 项\n`;
213
219
  const drops = mig.acceptedDrops ?? { registered: [], unregistered: [] };
@@ -237,7 +243,7 @@ function archiveLines(archive) {
237
243
  if (archive.verdict === 'unverifiable') {
238
244
  return ' 在位可还原(A1,独立维度):— 未提供归档根目录(不可判定;加 `--archive-root DIR` 或 env DSH_LOG_CONTRACT_ARCHIVE_ROOTS 才评估)\n';
239
245
  }
240
- const rate = (archive.restorableRate * [n]).toFixed(2);
246
+ const rate = (archive.restorableRate * 100).toFixed(2);
241
247
  let s = ` 在位可还原(A1,独立维度,只认结构指针):${archive.verdict === 'restorable' ? '✅' : '❌'} ${rate}%`
242
248
  + `(指针 ${archive.pointers},去重后 ${archive.effectivePointers ?? archive.pointers}:可还原 ${archive.restorable}`
243
249
  + ` / relocated ${archive.relocated} / 缺失 ${archive.missing} / 行缺失 ${archive.lineMissing} / sha 不符 ${archive.shaMismatch} / 无法解析 ${archive.unresolved})\n`;
@@ -304,7 +310,7 @@ function cmdCheck(args) {
304
310
  const exitCode = notAssessable ? 3 : (!ok ? 1 : (migGate ? 4 : 0));
305
311
 
306
312
  if (json) {
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 };
313
+ const payload = { schemaVersion: result.schemaVersion ?? '1', 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 };
308
314
  if (notAssessable) payload.notAssessable = result.notAssessable;
309
315
  if (resume) payload.resume = resumeVerdict(result);
310
316
  out(JSON.stringify(payload, null, 2) + '\n');
@@ -324,7 +330,7 @@ function cmdCheck(args) {
324
330
  const passMark = partial ? '✔' : '✅';
325
331
  const icons = { loadable: `${passMark} 可加载`, resumable: `${passMark} 可继续`, compactable: `${passMark} 可压缩`, broken: '❌ 不可用' };
326
332
  out(`\n📋 dsh-log-contract check --resume —— ${file}\n`);
327
- out(` 事件 ${summary.events} | surface 节点 ${summary.surfaceNodes} | replace 代数 ${summary.replaceGeneration} | 帧 ${summary.frames}(${(summary.compressedBytes / [n]).toFixed(1)}KiB → ${(summary.plaintextBytes / [n]).toFixed(1)}KiB)\n`);
333
+ out(` 事件 ${summary.events} | surface 节点 ${summary.surfaceNodes} | replace 代数 ${summary.replaceGeneration} | 帧 ${summary.frames}(${(summary.compressedBytes / 1024).toFixed(1)}KiB → ${(summary.plaintextBytes / 1024).toFixed(1)}KiB)\n`);
328
334
  out(` 违规 ${summary.total}(error ${summary.bySeverity.error} / warning ${summary.bySeverity.warning})\n\n`);
329
335
  out(` 分层结论(**本工具规则集内**,不代表"可用",也不代表官方升级会接受):\n`);
330
336
  const tiers = [
@@ -351,7 +357,7 @@ function cmdCheck(args) {
351
357
  }
352
358
 
353
359
  out(`\n📋 dsh-log-contract check —— ${file}\n`);
354
- out(` 事件 ${summary.events} | surface 节点 ${summary.surfaceNodes} | replace 代数 ${summary.replaceGeneration} | 帧 ${summary.frames}(${(summary.compressedBytes / [n]).toFixed(1)}KiB → ${(summary.plaintextBytes / [n]).toFixed(1)}KiB)\n`);
360
+ out(` 事件 ${summary.events} | surface 节点 ${summary.surfaceNodes} | replace 代数 ${summary.replaceGeneration} | 帧 ${summary.frames}(${(summary.compressedBytes / 1024).toFixed(1)}KiB → ${(summary.plaintextBytes / 1024).toFixed(1)}KiB)\n`);
355
361
  out(` 违规 ${summary.total}(error ${summary.bySeverity.error} / warning ${summary.bySeverity.warning})\n`);
356
362
  out(supportLines(result.support));
357
363
  out(driftLines(result.drift, result.probes));
@@ -393,7 +399,7 @@ function cmdPrewrite(args) {
393
399
  ? process.env.DSH_LOG_CONTRACT_IGNORABLE_WHITELIST.split(',').map((x) => x.trim()).filter(Boolean)
394
400
  : undefined;
395
401
  const baseline = validateSessionLog(log, { ignorableWhitelist: prewriteWhitelist });
396
- // 版本支持面([n]-09-14 用户要求第 1 条):**未验证格式 ⇒ 只读**,不得给出写入结论。
402
+ // 版本支持面(2026-09-14 用户要求第 1 条):**未验证格式 ⇒ 只读**,不得给出写入结论。
397
403
  if (baseline.support?.readOnly) {
398
404
  fail(`未验证的会话格式(来源 ${baseline.support.file.source},版本 v${baseline.support.file.version})——按只读处理,写前校验无法给出可信结论。`
399
405
  + ` ${baseline.support.warnings?.[0] ?? ''}`, 3);
@@ -458,6 +464,51 @@ function cmdContracts() {
458
464
  }
459
465
  }
460
466
 
467
+ /**
468
+ * `explain <ruleId>` —— 规则解读(标题 / 判据 / 正反例指针 / 相关命令)。
469
+ * 数据源 = `lib/contracts.js` 规则注册表(单一权威,判据原文引用);
470
+ * 未知 id ⇒ 明确提示 + 非零退出(--json 时输出同键稳定结构 + found:false)。
471
+ */
472
+ function cmdExplain(args) {
473
+ const json = args.includes('--json');
474
+ const id = args.find((a) => !a.startsWith('-'));
475
+ if (!id) fail(USAGE);
476
+ const info = explainRule(id);
477
+ if (!info.found) {
478
+ if (json) {
479
+ out(JSON.stringify(info, null, 2) + '\n');
480
+ } else {
481
+ errOut(`❌ ${info.hint}\n`);
482
+ }
483
+ process.exit(1);
484
+ }
485
+ if (json) {
486
+ out(JSON.stringify(info, null, 2) + '\n');
487
+ process.exit(0);
488
+ }
489
+ out(`\n📘 dsh-log-contract explain —— ${info.id}\n\n`);
490
+ out(` id ${info.id} | 严重度 ${info.severity} | 层级 ${info.layer}\n`);
491
+ out(` 标题 ${info.title}\n`);
492
+ out(` 出处 ${info.source}\n\n`);
493
+ out(' 判据 / 触发条件(原文引自规则注册表 lib/contracts.js;⛔ 不另立第二权威):\n');
494
+ out(` ${info.criteria}\n\n`);
495
+ out(' 正/反例指针(测试 / 夹具):\n');
496
+ const rows = [
497
+ ...info.examples.negative.map((p) => ['反例', p]),
498
+ ...info.examples.positive.map((p) => ['正例', p]),
499
+ ...info.examples.unclassified.map((p) => ['对照', p]),
500
+ ];
501
+ if (rows.length === 0) {
502
+ out(` ${info.examples.note ?? '(未找到该 id 的对照引用——以规则注册表判据为准)'}\n`);
503
+ } else {
504
+ for (const [kind, p] of rows.slice(0, 12)) out(` [${kind}] ${p}\n`);
505
+ }
506
+ out('\n 相关命令:\n');
507
+ for (const c of info.relatedCommands) out(` - ${c}\n`);
508
+ out(`\n 完整目录:${info.doc}(由规则注册表生成)\n\n`);
509
+ process.exit(0);
510
+ }
511
+
461
512
  function cmdFix(args) {
462
513
  const json = args.includes('--json');
463
514
  const removeMarkers = args.includes('--remove-markers');
@@ -472,7 +523,7 @@ function cmdFix(args) {
472
523
  const trimBudget = budgetIdx >= 0 && args[budgetIdx + 1] ? Number(args[budgetIdx + 1]) : undefined;
473
524
  const compactIdx = args.indexOf('--compact-last');
474
525
  const compactLast = compactIdx >= 0 && args[compactIdx + 1] ? Number(args[compactIdx + 1]) : undefined;
475
- // L4 新原语([n]-08-30 收编外部验证工具)
526
+ // L4 新原语(2026-08-30 收编外部验证工具)
476
527
  const tailIdx = args.indexOf('--tail-renumber');
477
528
  const tailRenumberDelta = tailIdx >= 0 && args[tailIdx + 1] ? Number(args[tailIdx + 1]) : undefined;
478
529
  const neutralizeOrphan = args.includes('--neutralize-orphan');
@@ -575,7 +626,7 @@ function cmdAuditReport(args) {
575
626
  process.exit(0);
576
627
  }
577
628
  out(`\n📊 dsh-log-contract audit-report —— ${file}\n`);
578
- out(` 工具调用 ${report.calls} | 结果 ${report.results} | 孤儿 ${report.orphans} | 配对率 ${(report.pairingRate * [n]).toFixed(1)}%\n`);
629
+ out(` 工具调用 ${report.calls} | 结果 ${report.results} | 孤儿 ${report.orphans} | 配对率 ${(report.pairingRate * 100).toFixed(1)}%\n`);
579
630
  out(` 输出总字节 ${report.outputBytes}`);
580
631
  if (report.largest) out(` | 最大 ${report.largest.size}B(${(report.largest.command || '?').slice(0, 40)})`);
581
632
  out(`\n 命令分布(前 ${report.commands.top.length} 个去重):\n`);
@@ -603,4 +654,5 @@ else if (cmd === 'audit-report') cmdAuditReport(args.slice(1));
603
654
  else if (cmd === 'prewrite') cmdPrewrite(args.slice(1));
604
655
  else if (cmd === 'fix') cmdFix(args.slice(1));
605
656
  else if (cmd === 'contracts') cmdContracts();
657
+ else if (cmd === 'explain') cmdExplain(args.slice(1));
606
658
  else fail(`未知子命令 "${cmd}"\n\n${USAGE}`);