create-clis 0.1.0

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.
Files changed (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -0
  3. package/README.zh-CN.md +113 -0
  4. package/assets/manifest.json +99 -0
  5. package/assets/template/.editorconfig +12 -0
  6. package/assets/template/.gitattributes +18 -0
  7. package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +86 -0
  8. package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +45 -0
  9. package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +26 -0
  10. package/assets/template/.github/workflows/ci.yml +42 -0
  11. package/assets/template/.github/workflows/release.yml +65 -0
  12. package/assets/template/.gitignorerc.json +21 -0
  13. package/assets/template/.nvmrc +1 -0
  14. package/assets/template/.oxlintrc.json +52 -0
  15. package/assets/template/.prettierignore +11 -0
  16. package/assets/template/.prettierrc +11 -0
  17. package/assets/template/.releaserc.json +17 -0
  18. package/assets/template/.vscode/extensions.json +8 -0
  19. package/assets/template/.vscode/launch.json +13 -0
  20. package/assets/template/.vscode/settings.json +14 -0
  21. package/assets/template/AGENTS.md +25 -0
  22. package/assets/template/CODE_OF_CONDUCT.md +91 -0
  23. package/assets/template/CONTRIBUTING.md +85 -0
  24. package/assets/template/CONTRIBUTING.zh-CN.md +85 -0
  25. package/assets/template/LICENSE +21 -0
  26. package/assets/template/README.md +22 -0
  27. package/assets/template/README.zh-CN.md +22 -0
  28. package/assets/template/SECURITY.md +21 -0
  29. package/assets/template/_gitignore +409 -0
  30. package/assets/template/_npmrc +6 -0
  31. package/assets/template/bunfig.toml +16 -0
  32. package/assets/template/docs/README.md +30 -0
  33. package/assets/template/docs/adrs/README.md +7 -0
  34. package/assets/template/docs/designs/README.md +11 -0
  35. package/assets/template/docs/designs/tech-debt.md +22 -0
  36. package/assets/template/docs/development.md +59 -0
  37. package/assets/template/lefthook.yml +55 -0
  38. package/assets/template/package.json +38 -0
  39. package/assets/template/packages/{{NAME}}/CHANGELOG.md +3 -0
  40. package/assets/template/packages/{{NAME}}/LICENSE +21 -0
  41. package/assets/template/packages/{{NAME}}/README.md +33 -0
  42. package/assets/template/packages/{{NAME}}/README.zh-CN.md +33 -0
  43. package/assets/template/packages/{{NAME}}/docs/README.md +21 -0
  44. package/assets/template/packages/{{NAME}}/package.json +40 -0
  45. package/assets/template/packages/{{NAME}}/scripts/build.ts +82 -0
  46. package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +214 -0
  47. package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +152 -0
  48. package/assets/template/packages/{{NAME}}/src/index.ts +15 -0
  49. package/assets/template/packages/{{NAME}}/tsconfig.build.json +12 -0
  50. package/assets/template/packages/{{NAME}}/tsconfig.json +5 -0
  51. package/assets/template/packages/{{NAME}}-cli/CHANGELOG.md +3 -0
  52. package/assets/template/packages/{{NAME}}-cli/LICENSE +21 -0
  53. package/assets/template/packages/{{NAME}}-cli/README.md +35 -0
  54. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +35 -0
  55. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +30 -0
  56. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +30 -0
  57. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +23 -0
  58. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +212 -0
  59. package/assets/template/packages/{{NAME}}-cli/docs/README.md +21 -0
  60. package/assets/template/packages/{{NAME}}-cli/package.json +48 -0
  61. package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +141 -0
  62. package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +70 -0
  63. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +444 -0
  64. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +72 -0
  65. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +126 -0
  66. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +81 -0
  67. package/assets/template/packages/{{NAME}}-cli/src/cli.ts +36 -0
  68. package/assets/template/packages/{{NAME}}-cli/tsconfig.json +4 -0
  69. package/assets/template/scripts/ci.ts +163 -0
  70. package/assets/template/scripts/install-git-hooks.mjs +122 -0
  71. package/assets/template/scripts/install-git-hooks.test.ts +418 -0
  72. package/assets/template/scripts/lib/git-env.ts +21 -0
  73. package/assets/template/scripts/lib/release-verify.ts +431 -0
  74. package/assets/template/scripts/lib/tmp-root.ts +17 -0
  75. package/assets/template/scripts/lib/workspace.test.ts +92 -0
  76. package/assets/template/scripts/lib/workspace.ts +100 -0
  77. package/assets/template/scripts/lint-doc-examples.test.ts +129 -0
  78. package/assets/template/scripts/lint-doc-examples.ts +249 -0
  79. package/assets/template/scripts/lint-doc-references.test.ts +158 -0
  80. package/assets/template/scripts/lint-doc-references.ts +308 -0
  81. package/assets/template/scripts/lint-doc-shared.ts +59 -0
  82. package/assets/template/scripts/lint-stray-backups.test.ts +53 -0
  83. package/assets/template/scripts/lint-stray-backups.ts +39 -0
  84. package/assets/template/scripts/npm-trust-guard.test.ts +253 -0
  85. package/assets/template/scripts/npm-trust-guard.ts +533 -0
  86. package/assets/template/scripts/safe-install.ts +39 -0
  87. package/assets/template/scripts/transcription/api-harness.ts +219 -0
  88. package/assets/template/scripts/transcription/compare.ts +421 -0
  89. package/assets/template/scripts/transcription/corpus.ts +208 -0
  90. package/assets/template/scripts/transcription/fixture.ts +290 -0
  91. package/assets/template/scripts/transcription/make-mutants.ts +425 -0
  92. package/assets/template/scripts/transcription/report.ts +86 -0
  93. package/assets/template/scripts/transcription/run-conformance.ts +344 -0
  94. package/assets/template/scripts/transcription/validate-coverage.test.ts +119 -0
  95. package/assets/template/scripts/transcription/validate-coverage.ts +144 -0
  96. package/assets/template/scripts/transcription/validate.ts +366 -0
  97. package/assets/template/tsconfig.json +46 -0
  98. package/assets/template/turbo.jsonc +60 -0
  99. package/bin/create-clis +35 -0
  100. package/bin/create-clis.cmd +32 -0
  101. package/bin/create-clis.mjs +219 -0
  102. package/dist/create-clis.js +87682 -0
  103. package/dist/manifest.json +7 -0
  104. package/package.json +57 -0
@@ -0,0 +1,344 @@
1
+ /**
2
+ * 转写契约套件 · 确定性验收器 (conformance runner) 入口。
3
+ *
4
+ * 职责: 解析 CLI → 加载语料 → 逐条建 fixture 树、以最小白名单 env 执行被测命令、逐项比对、
5
+ * 清理现场 → 汇总报告, 任一条失败即非零退出。纯程序、零 AI、零第三方依赖 (bun / node 直跑)。
6
+ *
7
+ * 模块划分 (同目录, 本文件只留 CLI 解析 / 编排 / 帮助):
8
+ * - corpus.ts 语料类型、$FIXTURE 变量替换契约、目录加载;
9
+ * - validate.ts 语料手写校验 (schema 的物化子集, 见文件头);
10
+ * - fixture.ts fixture 建树 / setup 预置 / 最小 env / 执行 / 清理 (cli 与 api 两类 case);
11
+ * - compare.ts 逐项比对 (cli: 退出码 / stdout 与 stderr 的子串含与禁含 / fs 终态; api: 返回值 / 抛错 / 事件);
12
+ * - report.ts 报告数据结构与人读 / JSON 渲染;
13
+ * - api-harness.ts 参考 API harness (独立入口; 协议见 docs/sweep/protocol/conformance/api-harness-protocol.md)。
14
+ *
15
+ * 语料权威: docs/sweep/protocol/conformance/corpus.schema.json (字段语义以 schema 为准; 手写校验是
16
+ * schema 的物化子集, 只为尽早给出可读报错, 不复刻 schema 的全部约束)。
17
+ *
18
+ * 用法: bun scripts/transcription/run-conformance.ts --target "bun packages/{{NAME}}-cli/src/cli.ts" [--api-target "bun scripts/transcription/api-harness.ts"] [--corpus <dir>] [--filter <id 子串>]
19
+ * [--timeout <ms>] [--json] [--keep] [--help]
20
+ *
21
+ * 退出码: 0 全部通过; 1 存在失败用例; 2 用法 / 语料 / 环境错误 (runner 自身问题, 非被测缺陷)。
22
+ */
23
+ import { existsSync } from 'node:fs';
24
+ import { mkdir, mkdtemp, realpath } from 'node:fs/promises';
25
+ import { homedir } from 'node:os';
26
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
27
+ import { fileURLToPath } from 'node:url';
28
+
29
+ import { compareApiCase, compareCase } from './compare.ts';
30
+ import { type CorpusCase, loadCorpus } from './corpus.ts';
31
+ import {
32
+ type ExecOutcome,
33
+ type RunContext,
34
+ applySetup,
35
+ buildFixture,
36
+ cleanupFixture,
37
+ executeApiCase,
38
+ executeCase,
39
+ } from './fixture.ts';
40
+ import {
41
+ type CaseReport,
42
+ type FailureItem,
43
+ printHumanReport,
44
+ printJsonReport,
45
+ } from './report.ts';
46
+
47
+ const HERE = dirname(fileURLToPath(import.meta.url));
48
+ /**
49
+ * 默认语料目录: 语料的权威落点在协议区 (docs/sweep/protocol/conformance/corpus), 脚本不随身携带语料。
50
+ * 脚本现居 scripts/transcription/, 自 HERE 上溯 2 级到仓库根再取 docs。
51
+ */
52
+ const DEFAULT_CORPUS_DIR = join(
53
+ HERE,
54
+ '..',
55
+ '..',
56
+ 'docs',
57
+ 'sweep',
58
+ 'protocol',
59
+ 'conformance',
60
+ 'corpus',
61
+ );
62
+ const DEFAULT_TIMEOUT_MS = 15000;
63
+ /** 默认 API harness: 随套件提供的参考 harness (import API 包单源; 见 api-harness.ts 文件头) */
64
+ const DEFAULT_API_TARGET = `bun ${join(HERE, 'api-harness.ts')}`;
65
+
66
+ interface CliOptions {
67
+ target: string;
68
+ apiTarget: string;
69
+ corpusDir: string;
70
+ filter?: string;
71
+ timeoutMs: number;
72
+ json: boolean;
73
+ keep: boolean;
74
+ help: boolean;
75
+ }
76
+
77
+ type ParseOutcome =
78
+ { ok: true; options: CliOptions } | { ok: false; message: string };
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // 命令行解析
82
+ // ---------------------------------------------------------------------------
83
+
84
+ const HELP_TEXT = [
85
+ '用法: bun scripts/transcription/run-conformance.ts --target "<被测命令>" [选项]',
86
+ '',
87
+ ' --target <cmd> 被测进程命令 (如 "bun packages/{{NAME}}-cli/src/cli.ts", 或 PATH 中的 "{{BIN_NAME}}" / 绝对路径形态); 按空白拆分, 不支持含空格的路径',
88
+ ' --api-target <cmd> API 用例的被测 harness 命令 (缺省: 随套件参考 harness, 即 "bun <仓库根>/scripts/transcription/api-harness.ts"); 拆分与绝对化规则同 --target',
89
+ ' --corpus <dir> 语料目录 (默认: docs/sweep/protocol/conformance/corpus)',
90
+ ' --filter <text> 只跑 id 含该子串的用例',
91
+ ' --timeout <ms> 单条用例执行超时 (默认 15000), 到期即判失败 (超时守卫)',
92
+ ' --json 输出结构化 JSON 报告 (stdout 仅 JSON, 诊断走 stderr)',
93
+ ' --keep 保留 fixture 目录并打印路径 (调试用; 默认跑完即清理)',
94
+ ' --help 显示本帮助',
95
+ '',
96
+ '退出码: 0 全部通过; 1 存在失败用例; 2 用法 / 语料 / 环境错误',
97
+ ].join('\n');
98
+
99
+ /**
100
+ * 解析参数: 仅支持 `--flag value` 与布尔旗标; 未知参数、缺值一律判错 (调用方落退出码 2)。
101
+ *
102
+ * ### 数据追踪示例
103
+ * ```text
104
+ * Input(真实 Payload)
105
+ * argv = ['--target', 'bun packages/{{NAME}}-cli/src/cli.ts', '--filter', 'scan-']
106
+ *
107
+ * 步骤 1:逐项识别
108
+ * --target 收值 'bun packages/{{NAME}}-cli/src/cli.ts'; --filter 收值 'scan-'; 其余取默认
109
+ *
110
+ * Output(数据契约)
111
+ * return { ok: true, options: { target: 'bun packages/{{NAME}}-cli/src/cli.ts', corpusDir: 'docs/sweep/protocol/conformance/corpus', filter: 'scan-', timeoutMs: 15000, json: false, keep: false, help: false } }
112
+ * ```
113
+ */
114
+ function parseArgs(argv: string[]): ParseOutcome {
115
+ let target: string | undefined;
116
+ let apiTarget = DEFAULT_API_TARGET;
117
+ let corpusDir = DEFAULT_CORPUS_DIR;
118
+ let filter: string | undefined;
119
+ let timeoutMs = DEFAULT_TIMEOUT_MS;
120
+ let json = false;
121
+ let keep = false;
122
+ let help = false;
123
+
124
+ for (let index = 0; index < argv.length; index += 1) {
125
+ const arg = argv[index];
126
+ if (arg === '--help' || arg === '-h') {
127
+ help = true;
128
+ continue;
129
+ }
130
+ if (arg === '--json') {
131
+ json = true;
132
+ continue;
133
+ }
134
+ if (arg === '--keep') {
135
+ keep = true;
136
+ continue;
137
+ }
138
+ if (
139
+ arg === '--target' ||
140
+ arg === '--api-target' ||
141
+ arg === '--corpus' ||
142
+ arg === '--filter' ||
143
+ arg === '--timeout'
144
+ ) {
145
+ const value = argv[index + 1];
146
+ if (value === undefined || value.startsWith('-')) {
147
+ return { ok: false, message: `参数 ${arg} 缺少取值` };
148
+ }
149
+ if (arg === '--target') target = value;
150
+ if (arg === '--api-target') apiTarget = value;
151
+ if (arg === '--corpus') corpusDir = value;
152
+ if (arg === '--filter') filter = value;
153
+ if (arg === '--timeout') {
154
+ const parsed = Number(value);
155
+ if (!Number.isInteger(parsed) || parsed <= 0) {
156
+ return {
157
+ ok: false,
158
+ message: `--timeout 须为正整数毫秒, 收到: ${value}`,
159
+ };
160
+ }
161
+ timeoutMs = parsed;
162
+ }
163
+ index += 1;
164
+ continue;
165
+ }
166
+ return { ok: false, message: `未知参数: ${arg}` };
167
+ }
168
+
169
+ if (help) {
170
+ return {
171
+ ok: true,
172
+ options: {
173
+ target: target ?? '',
174
+ apiTarget,
175
+ corpusDir,
176
+ filter,
177
+ timeoutMs,
178
+ json,
179
+ keep,
180
+ help: true,
181
+ },
182
+ };
183
+ }
184
+ if (target === undefined || target.trim() === '') {
185
+ return { ok: false, message: '缺少 --target (被测命令)' };
186
+ }
187
+
188
+ return {
189
+ ok: true,
190
+ options: {
191
+ target,
192
+ apiTarget,
193
+ corpusDir,
194
+ filter,
195
+ timeoutMs,
196
+ json,
197
+ keep,
198
+ help: false,
199
+ },
200
+ };
201
+ }
202
+
203
+ /**
204
+ * 把 target 命令里按启动目录写的相对路径绝对化。
205
+ * 必要原因: 被测进程的 cwd 会被设为 fixture 目录 (用例可声明), 而 `--target "bun packages/{{NAME}}-cli/src/cli.ts"`
206
+ * 里 `src/cli.ts` 是相对 runner 启动目录书写的; 不绝对化就会在 fixture cwd 下解析而找不到文件。
207
+ * 规则保守: 只动 index >= 1 (argv[0] 是命令名, 留给 PATH 解析)、非旗标、且相对启动目录真实存在
208
+ * 的路径串, 其余原样透传。
209
+ */
210
+ function absolutizeTargetArgv(
211
+ targetArgv: string[],
212
+ launchDir: string,
213
+ ): string[] {
214
+ return targetArgv.map((part, index) => {
215
+ if (index === 0 || isAbsolute(part) || part.startsWith('-')) return part;
216
+ const candidate = resolve(launchDir, part);
217
+ return existsSync(candidate) ? candidate : part;
218
+ });
219
+ }
220
+
221
+ // ---------------------------------------------------------------------------
222
+ // 单条用例编排
223
+ // ---------------------------------------------------------------------------
224
+
225
+ /**
226
+ * 跑一条用例: 建树 → setup → 执行 → 比对 → 清理 (keep 时保留现场)。
227
+ * 外部副作用:fixture 目录的创建与删除 (keep 时仅创建)。
228
+ */
229
+ async function runCase(
230
+ caseSpec: CorpusCase,
231
+ ctx: RunContext,
232
+ ): Promise<CaseReport> {
233
+ const startedAt = Date.now();
234
+ const rawRoot = await mkdtemp(join(ctx.workBase, 'sweep-conformance-'));
235
+ // realpath 归一: macOS 上 /var 与 /private/var 是同一位置的两种拼写, 统一用 realpath 形态
236
+ // 作 $FIXTURE 的替换值, 使期望文本与 process.cwd() / realpath 化输出一致。
237
+ const root = await realpath(rawRoot);
238
+ let failures: FailureItem[] = [];
239
+ let exec: ExecOutcome | undefined;
240
+
241
+ try {
242
+ await buildFixture(root, caseSpec.fixture);
243
+ await applySetup(root, caseSpec.setup ?? []);
244
+ if (caseSpec.kind === 'api') {
245
+ exec = executeApiCase(caseSpec, root, ctx);
246
+ failures = await compareApiCase(caseSpec.expect, exec, root);
247
+ } else {
248
+ exec = executeCase(caseSpec, root, ctx);
249
+ failures = await compareCase(caseSpec.expect, exec, root);
250
+ }
251
+ } finally {
252
+ if (ctx.keep) {
253
+ process.stderr.write(`[keep] fixture 保留于: ${root}\n`);
254
+ } else {
255
+ await cleanupFixture(rawRoot, caseSpec.fixture);
256
+ }
257
+ }
258
+
259
+ return {
260
+ id: caseSpec.id,
261
+ specRefs: caseSpec.specRefs,
262
+ status: failures.length === 0 ? 'pass' : 'fail',
263
+ durationMs: Date.now() - startedAt,
264
+ failures,
265
+ ...(failures.length > 0 && exec !== undefined
266
+ ? { diagnostics: { stdout: exec.stdout, stderr: exec.stderr } }
267
+ : {}),
268
+ };
269
+ }
270
+
271
+ // ---------------------------------------------------------------------------
272
+ // 主流程
273
+ // ---------------------------------------------------------------------------
274
+
275
+ async function main(): Promise<number> {
276
+ const parsed = parseArgs(process.argv.slice(2));
277
+ if (!parsed.ok) {
278
+ process.stderr.write(`参数错误: ${parsed.message}\n\n${HELP_TEXT}\n`);
279
+ return 2;
280
+ }
281
+ const options = parsed.options;
282
+ if (options.help) {
283
+ process.stdout.write(`${HELP_TEXT}\n`);
284
+ return 0;
285
+ }
286
+
287
+ const targetArgv = absolutizeTargetArgv(
288
+ options.target.trim().split(/\s+/),
289
+ process.cwd(),
290
+ );
291
+ const apiTargetArgv = absolutizeTargetArgv(
292
+ options.apiTarget.trim().split(/\s+/),
293
+ process.cwd(),
294
+ );
295
+ let cases: CorpusCase[];
296
+ try {
297
+ cases = await loadCorpus(resolve(options.corpusDir));
298
+ } catch (error) {
299
+ process.stderr.write(`${(error as Error).message}\n`);
300
+ return 2;
301
+ }
302
+
303
+ const selected =
304
+ options.filter === undefined
305
+ ? cases
306
+ : cases.filter((item) => item.id.includes(options.filter!));
307
+ if (selected.length === 0) {
308
+ process.stderr.write(
309
+ `--filter "${options.filter}" 未匹配到任何用例 (合计 ${cases.length} 条)\n`,
310
+ );
311
+ return 2;
312
+ }
313
+
314
+ const workBase = join(homedir(), 'tmp');
315
+ await mkdir(workBase, { recursive: true });
316
+ const ctx: RunContext = {
317
+ targetArgv,
318
+ apiTargetArgv,
319
+ timeoutMs: options.timeoutMs,
320
+ keep: options.keep,
321
+ workBase,
322
+ };
323
+
324
+ const reports: CaseReport[] = [];
325
+ for (const caseSpec of selected) {
326
+ reports.push(await runCase(caseSpec, ctx));
327
+ }
328
+
329
+ if (options.json) printJsonReport(options.corpusDir, options.target, reports);
330
+ else printHumanReport(options.corpusDir, options.target, reports);
331
+
332
+ return reports.some((report) => report.status === 'fail') ? 1 : 0;
333
+ }
334
+
335
+ try {
336
+ process.exitCode = await main();
337
+ } catch (error) {
338
+ // 未预期异常兜底归入「环境错误」退出码 (头注释的 2), 冒泡成默认的退 1 + 栈会把
339
+ // runner 自身故障伪装成「存在失败用例」, 误导对被测实现的判定。
340
+ process.stderr.write(
341
+ `验收器未预期错误: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
342
+ );
343
+ process.exitCode = 2;
344
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * 台账校验闸门单测: 纯解析函数逐类断言; 集成路径在临时 mini 根上验证「悬空 / 漏登记」
3
+ * 两类断裂抓得住、健康态全绿。
4
+ */
5
+ import { afterAll, describe, expect, test } from 'bun:test';
6
+
7
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+
10
+ import { makeTmpRoot } from '../lib/tmp-root.ts';
11
+ import {
12
+ collectCorpusRefs,
13
+ extractContractNumbers,
14
+ extractExemptNumbers,
15
+ reconcile,
16
+ validateCoverage,
17
+ } from './validate-coverage.ts';
18
+
19
+ const roots: string[] = [];
20
+ function makeRoot(files: Record<string, string>): string {
21
+ const root = makeTmpRoot('coverage-');
22
+ roots.push(root);
23
+ for (const [rel, content] of Object.entries(files)) {
24
+ const abs = join(root, rel);
25
+ mkdirSync(dirname(abs), { recursive: true });
26
+ writeFileSync(abs, content);
27
+ }
28
+ return root;
29
+ }
30
+ afterAll(() => {
31
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
32
+ });
33
+
34
+ describe('extractContractNumbers', () => {
35
+ test('只收行首单元格恰为条款号的主表行', () => {
36
+ const text = [
37
+ '| 编号 | 条款 |',
38
+ '| --- | --- |',
39
+ '| BC-01 | 甲 |',
40
+ '| EC-08 | 乙 |',
41
+ '正文提及 BC-99 不算主表行',
42
+ '| BC-01 / BC-02 | 一格式多号不算主表单号行 |',
43
+ ].join('\n');
44
+ expect([...extractContractNumbers(text)].sort()).toEqual([
45
+ 'BC-01',
46
+ 'EC-08',
47
+ ]);
48
+ });
49
+ });
50
+
51
+ describe('extractExemptNumbers', () => {
52
+ test('只取「二、」段内行首单元格的条款号 (含一格式多号)', () => {
53
+ const text = [
54
+ '## 一、覆盖表',
55
+ '| BC-01 | 1 | 语料甲 |',
56
+ '## 二、未覆盖条款',
57
+ '| BC-13 | 不可黑盒 (竞态) | 说明 |',
58
+ '| BC-21 / BC-22 | 不可黑盒 | 说明 |',
59
+ '## 三、变异自证',
60
+ '| BC-33 | 三节里不算 |',
61
+ ].join('\n');
62
+ expect([...extractExemptNumbers(text)].sort()).toEqual([
63
+ 'BC-13',
64
+ 'BC-21',
65
+ 'BC-22',
66
+ ]);
67
+ });
68
+ });
69
+
70
+ describe('reconcile', () => {
71
+ test('三边对账给出悬空 / 漏登记 / 部分豁免三类', () => {
72
+ const result = reconcile(
73
+ new Set(['BC-01', 'BC-02', 'BC-03']),
74
+ new Set(['BC-01', 'BC-99']),
75
+ new Set(['BC-03', 'BC-01']),
76
+ );
77
+ expect(result.dangling).toEqual(['BC-99']);
78
+ expect(result.unregistered).toEqual(['BC-02']);
79
+ expect(result.partial).toEqual(['BC-01']);
80
+ });
81
+ });
82
+
83
+ describe('validateCoverage 集成', () => {
84
+ test('健康态全绿; 造一处悬空与一处漏登记即分别抓出', () => {
85
+ const healthy = makeRoot({
86
+ 'docs/sweep/protocol/behavior-contract.md':
87
+ '| BC-01 | 甲 |\n| BC-02 | 乙 |\n',
88
+ 'docs/sweep/protocol/conformance/coverage.md':
89
+ '## 一、覆盖表\n| BC-01 | 1 | 甲语料 |\n## 二、未覆盖条款\n| BC-02 | 模块级 | 理由 |\n',
90
+ 'docs/sweep/protocol/conformance/corpus/a.json':
91
+ '{"id":"a","specRefs":["BC-01"]}\n',
92
+ });
93
+ expect(validateCoverage(healthy)).toEqual({
94
+ dangling: [],
95
+ unregistered: [],
96
+ partial: [],
97
+ });
98
+
99
+ const broken = makeRoot({
100
+ 'docs/sweep/protocol/behavior-contract.md':
101
+ '| BC-01 | 甲 |\n| BC-02 | 乙 |\n',
102
+ 'docs/sweep/protocol/conformance/coverage.md': '## 一、覆盖表\n',
103
+ 'docs/sweep/protocol/conformance/corpus/a.json':
104
+ '{"id":"a","specRefs":["BC-01","BC-77"]}\n',
105
+ });
106
+ const result = validateCoverage(broken);
107
+ expect(result.dangling).toEqual(['BC-77']);
108
+ expect(result.unregistered).toEqual(['BC-02']);
109
+ });
110
+
111
+ test('corpus 目录单文件缺 specRefs 即抛 (语料损坏属硬错)', () => {
112
+ const root = makeRoot({
113
+ 'docs/sweep/protocol/conformance/corpus/bad.json': '{"id":"bad"}\n',
114
+ });
115
+ expect(() =>
116
+ collectCorpusRefs(join(root, 'docs/sweep/protocol/conformance/corpus')),
117
+ ).toThrow(/缺 specRefs/);
118
+ });
119
+ });
@@ -0,0 +1,144 @@
1
+ /**
2
+ * 语料台账校验闸门: 行为契约条款 × 语料 specRefs × coverage 豁免登记的三角对账。
3
+ *
4
+ * 动机: 2026-09-30 复审立案「台账校验靠手跑 jq / comm」; 三边一致性是确定性事实, 不该靠
5
+ * 人记得跑, 故固化为闸门 (套件维护规则「条款变更须同步语料与覆盖表」的物理化)。
6
+ *
7
+ * 校验 (硬红灯两类):
8
+ * - 悬空引用: 任一语料 specRefs 里的条款号在行为契约主表中不存在;
9
+ * - 漏登记: 存在「无任何语料引用」且「未出现在 coverage.md 未覆盖条款区」的条款。
10
+ * 口径: 未覆盖条款区 = coverage.md 中 `## 二、` 标题起至下一个 `## ` 前; 区内行首单元格里
11
+ * 的条款号即为已登记豁免 (含 `BC-21 / BC-22` 一格式多号)。豁免区中「已被语料引用」的条款
12
+ * (部分豁免形态, 如「静态形态已覆盖 / 竞态形态模块级」) 只作 INFO 打印, 不判错。
13
+ *
14
+ * 用法: bun scripts/transcription/validate-coverage.ts
15
+ * 退出码: 0 全绿; 1 存在悬空引用或漏登记。
16
+ */
17
+ import { readFileSync, readdirSync } from 'node:fs';
18
+ import { join } from 'node:path';
19
+
20
+ import { REPO_ROOT } from '../lint-doc-shared.ts';
21
+
22
+ const CONTRACT_MD = 'docs/sweep/protocol/behavior-contract.md';
23
+ const COVERAGE_MD = 'docs/sweep/protocol/conformance/coverage.md';
24
+ const CORPUS_DIR = 'docs/sweep/protocol/conformance/corpus';
25
+
26
+ /** 条款号形态 (行首表格单元格): BC-01 / OF-15 / EC-08 */
27
+ const CLAUSE_IN_CELL = /(?:BC|OF|EC)-\d+/g;
28
+
29
+ /** 从行为契约主表提取全部条款号 (行首单元格以条款号开头的表格行) */
30
+ export function extractContractNumbers(text: string): Set<string> {
31
+ const numbers = new Set<string>();
32
+ for (const line of text.split('\n')) {
33
+ const cell = line.match(/^\|\s*([^|]*?)\s*\|/)?.[1];
34
+ if (!cell) continue;
35
+ for (const m of cell.matchAll(/^(?:BC|OF|EC)-\d+$/g)) numbers.add(m[0]);
36
+ }
37
+ return numbers;
38
+ }
39
+
40
+ /** 从 coverage.md 的「二、未覆盖条款」段提取豁免登记的条款号集合 */
41
+ export function extractExemptNumbers(text: string): Set<string> {
42
+ const numbers = new Set<string>();
43
+ let inSection = false;
44
+ for (const line of text.split('\n')) {
45
+ if (line.startsWith('## ')) {
46
+ inSection = line.startsWith('## 二、');
47
+ continue;
48
+ }
49
+ if (!inSection) continue;
50
+ const cell = line.match(/^\|\s*([^|]*?)\s*\|/)?.[1];
51
+ if (!cell) continue;
52
+ for (const m of cell.matchAll(CLAUSE_IN_CELL)) numbers.add(m[0]);
53
+ }
54
+ return numbers;
55
+ }
56
+
57
+ /** 读全部语料, 汇总 specRefs 引用集合; 单个文件解析失败即抛 (语料损坏属硬错) */
58
+ export function collectCorpusRefs(corpusDir: string): Set<string> {
59
+ const refs = new Set<string>();
60
+ for (const name of readdirSync(corpusDir).sort()) {
61
+ if (!name.endsWith('.json')) continue;
62
+ const parsed = JSON.parse(readFileSync(join(corpusDir, name), 'utf8')) as {
63
+ specRefs?: unknown;
64
+ };
65
+ if (!Array.isArray(parsed.specRefs)) {
66
+ throw new Error(`${name}: 缺 specRefs 数组`);
67
+ }
68
+ for (const ref of parsed.specRefs) refs.add(String(ref));
69
+ }
70
+ return refs;
71
+ }
72
+
73
+ /** 三角对账的产物 */
74
+ export interface CoverageReconciliation {
75
+ /** 悬空引用: 语料引用了契约里不存在的条款号 */
76
+ dangling: string[];
77
+ /** 漏登记: 无引用且未在豁免区登记的条款号 */
78
+ unregistered: string[];
79
+ /** INFO: 在豁免区但已有语料引用的条款号 (部分豁免形态合法) */
80
+ partial: string[];
81
+ }
82
+
83
+ /** 三边对账 (纯函数, 供测试) */
84
+ export function reconcile(
85
+ contract: Set<string>,
86
+ referenced: Set<string>,
87
+ exempt: Set<string>,
88
+ ): CoverageReconciliation {
89
+ const dangling = [...referenced].filter((n) => !contract.has(n)).sort();
90
+ const unregistered = [...contract]
91
+ .filter((n) => !referenced.has(n) && !exempt.has(n))
92
+ .sort();
93
+ const partial = [...exempt].filter((n) => referenced.has(n)).sort();
94
+ return { dangling, unregistered, partial };
95
+ }
96
+
97
+ /** 在给定仓库根上跑全量对账 (供测试注入临时根) */
98
+ export function validateCoverage(
99
+ root: string = REPO_ROOT,
100
+ ): CoverageReconciliation {
101
+ const contract = extractContractNumbers(
102
+ readFileSync(join(root, CONTRACT_MD), 'utf8'),
103
+ );
104
+ const exempt = extractExemptNumbers(
105
+ readFileSync(join(root, COVERAGE_MD), 'utf8'),
106
+ );
107
+ const referenced = collectCorpusRefs(join(root, CORPUS_DIR));
108
+ return reconcile(contract, referenced, exempt);
109
+ }
110
+
111
+ /** 主流程: 打印对账结果并以退出码收口 (0 全绿 / 1 断裂) */
112
+ function main(): void {
113
+ let result: CoverageReconciliation;
114
+ try {
115
+ result = validateCoverage();
116
+ } catch (error) {
117
+ process.stderr.write(
118
+ `台账读取失败: ${error instanceof Error ? error.message : String(error)}\n`,
119
+ );
120
+ process.exitCode = 1;
121
+ return;
122
+ }
123
+ const { dangling, unregistered, partial } = result;
124
+ if (dangling.length > 0) {
125
+ process.stderr.write(
126
+ `悬空引用 (语料引用了契约里不存在的条款): ${dangling.join(' / ')}\n`,
127
+ );
128
+ }
129
+ if (unregistered.length > 0) {
130
+ process.stderr.write(
131
+ `漏登记 (无引用且未在未覆盖条款区登记): ${unregistered.join(' / ')}\n`,
132
+ );
133
+ }
134
+ if (dangling.length === 0 && unregistered.length === 0) {
135
+ process.stdout.write(
136
+ `语料台账校验全绿 ✓ (悬空引用 0 / 漏登记 0${partial.length > 0 ? `; 部分豁免 ${partial.join(' / ')}` : ''})\n`,
137
+ );
138
+ return;
139
+ }
140
+ process.exitCode = 1;
141
+ }
142
+
143
+ // 仅作为入口执行时跑主流程 (被 import 时不执行, 供测试)
144
+ if (import.meta.main) main();