create-clis 1.0.0 → 1.2.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 (88) hide show
  1. package/README.md +22 -14
  2. package/README.zh-CN.md +22 -14
  3. package/assets/manifest.json +7 -2
  4. package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +15 -29
  5. package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +6 -12
  6. package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +3 -3
  7. package/assets/template/.github/workflows/ci.yml +69 -7
  8. package/assets/template/.github/workflows/release.yml +23 -23
  9. package/assets/template/.gitignorerc.json +1 -8
  10. package/assets/template/.oxlintrc.json +1 -6
  11. package/assets/template/.prettierignore +0 -1
  12. package/assets/template/.releaserc.json +6 -1
  13. package/assets/template/.vscode/launch.json +1 -1
  14. package/assets/template/.vscode/settings.json +1 -0
  15. package/assets/template/.vscode/tasks.json +45 -0
  16. package/assets/template/AGENTS.md +4 -4
  17. package/assets/template/CONTRIBUTING.md +6 -4
  18. package/assets/template/CONTRIBUTING.zh-CN.md +6 -4
  19. package/assets/template/_gitignore +7 -405
  20. package/assets/template/bunfig.toml +2 -11
  21. package/assets/template/docs/README.md +6 -6
  22. package/assets/template/docs/adrs/README.md +4 -2
  23. package/assets/template/docs/development.md +15 -9
  24. package/assets/template/lefthook.yml +20 -30
  25. package/assets/template/package.json +5 -6
  26. package/assets/template/packages/{{NAME}}/README.md +4 -4
  27. package/assets/template/packages/{{NAME}}/README.zh-CN.md +2 -2
  28. package/assets/template/packages/{{NAME}}/package.json +3 -1
  29. package/assets/template/packages/{{NAME}}/scripts/build.ts +50 -14
  30. package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +140 -15
  31. package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +27 -14
  32. package/assets/template/packages/{{NAME}}/tsconfig.build.json +1 -1
  33. package/assets/template/packages/{{NAME}}-cli/README.md +9 -6
  34. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +6 -3
  35. package/assets/template/packages/{{NAME}}-cli/bin/bunfig.toml +3 -0
  36. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +43 -21
  37. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +8 -17
  38. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +6 -3
  39. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +189 -107
  40. package/assets/template/packages/{{NAME}}-cli/package.json +3 -2
  41. package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +24 -73
  42. package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +8 -3
  43. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +16 -10
  44. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +8 -52
  45. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +3 -3
  46. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +8 -68
  47. package/assets/template/packages/{{NAME}}-cli/src/cli.ts +51 -11
  48. package/assets/template/scripts/ci.ts +285 -64
  49. package/assets/template/scripts/install-git-hooks.mjs +10 -0
  50. package/assets/template/scripts/install-git-hooks.test.ts +1 -1
  51. package/assets/template/scripts/lib/npm-trust-parse.ts +169 -0
  52. package/assets/template/scripts/lib/release-cli.ts +299 -0
  53. package/assets/template/scripts/lib/release-verify.ts +148 -15
  54. package/assets/template/scripts/lib/workspace.test.ts +63 -1
  55. package/assets/template/scripts/lib/workspace.ts +132 -42
  56. package/assets/template/scripts/lint-dependency-direction.test.ts +131 -0
  57. package/assets/template/scripts/lint-dependency-direction.ts +130 -0
  58. package/assets/template/scripts/lint-doc-examples.test.ts +45 -9
  59. package/assets/template/scripts/lint-doc-examples.ts +227 -50
  60. package/assets/template/scripts/lint-doc-references.test.ts +36 -0
  61. package/assets/template/scripts/lint-doc-references.ts +142 -57
  62. package/assets/template/scripts/lint-doc-shared.ts +26 -23
  63. package/assets/template/scripts/lint-stray-backups.test.ts +3 -1
  64. package/assets/template/scripts/lint-stray-backups.ts +7 -3
  65. package/assets/template/scripts/npm-trust-guard.test.ts +56 -8
  66. package/assets/template/scripts/npm-trust-guard.ts +116 -200
  67. package/assets/template/scripts/safe-install.ts +28 -23
  68. package/assets/template/scripts/transcription/api-harness.ts +28 -206
  69. package/assets/template/scripts/transcription/compare.test.ts +84 -0
  70. package/assets/template/scripts/transcription/compare.ts +4 -4
  71. package/assets/template/scripts/transcription/corpus.ts +9 -3
  72. package/assets/template/scripts/transcription/fixture.ts +2 -4
  73. package/assets/template/scripts/transcription/make-mutants.ts +116 -37
  74. package/assets/template/scripts/transcription/run-conformance.ts +57 -34
  75. package/assets/template/scripts/transcription/validate-coverage.test.ts +11 -14
  76. package/assets/template/scripts/transcription/validate-coverage.ts +8 -10
  77. package/assets/template/scripts/transcription/validate.ts +18 -3
  78. package/assets/template/tsconfig.json +2 -20
  79. package/assets/template/turbo.jsonc +7 -52
  80. package/bin/bunfig.toml +3 -0
  81. package/bin/create-clis.mjs +165 -104
  82. package/dist/create-clis.js +48 -87681
  83. package/dist/manifest.json +3 -3
  84. package/package.json +9 -5
  85. package/assets/template/packages/{{NAME}}/docs/README.md +0 -21
  86. package/assets/template/packages/{{NAME}}-cli/docs/README.md +0 -21
  87. package/bin/create-clis +0 -35
  88. package/bin/create-clis.cmd +0 -32
@@ -3,7 +3,7 @@
3
3
  * 并注入单点缺陷, 生成到 mutants/gen-<id>/; 副本自带 node_modules 链接 (指向 api 副本), 可独立运行。
4
4
  *
5
5
  * 用途 (变异自证): 语料必须能抓住每一个 mutant; 抓不住 = 语料盲区 (或该 mutant 定义过弱),
6
- * 不是「实现没问题」。注入面见下方 MUTANTS 清单 (重跑纪律见 docs/sweep/protocol/README.md「维护规则」),
6
+ * 不是「实现没问题」。注入面见下方 MUTANTS 清单 (重跑纪律见对应 API 包的 docs/protocol/README.md「维护规则」),
7
7
  * 每个 mutant 只做一行级补丁。
8
8
  *
9
9
  * 幂等: 每次重建自己的 gen-* 目录, 并清掉清单之外的陈旧 gen-*; 锚点失配 (源码在漂移) 时显式
@@ -20,6 +20,7 @@
20
20
  * 运行某 mutant (api 面): --api-target "bun scripts/transcription/mutants/gen-<id>/scripts/transcription/api-harness.ts"
21
21
  * (两者均与 run-conformance.ts 配合)。
22
22
  */
23
+ import { existsSync } from 'node:fs';
23
24
  import {
24
25
  mkdir,
25
26
  readFile,
@@ -29,16 +30,30 @@ import {
29
30
  symlink,
30
31
  writeFile,
31
32
  } from 'node:fs/promises';
32
- import { dirname, join, resolve } from 'node:path';
33
+ import { dirname, join, relative, resolve } from 'node:path';
33
34
  import { fileURLToPath } from 'node:url';
34
35
 
35
- import { resolveCliAndApi } from '../lib/workspace.ts';
36
+ import { resolveProductPairs } from '../lib/workspace.ts';
36
37
 
37
38
  const HERE = dirname(fileURLToPath(import.meta.url));
38
39
  /** 仓库根 (scripts/transcription/ 上溯两级): 两包源码与配置的定位基准 */
39
40
  const REPO_ROOT = resolve(HERE, '..', '..');
40
- /** 两包坐标: 由根 package.json 的 workspaces 派生 (包目录 / 包名变更时本文件零修改) */
41
- const { api: API_PKG, cli: CLI_PKG } = resolveCliAndApi(REPO_ROOT);
41
+
42
+ /** 在多产品仓中按 docs/protocol 锚点唯一定位承接转写套件的双包产品 (单产品仓直接取唯一对) */
43
+ function resolveProtocolProductPair(root: string) {
44
+ const pairs = resolveProductPairs(root);
45
+ if (pairs.length === 1) return pairs[0]!;
46
+ const matched = pairs.filter(({ api }) =>
47
+ existsSync(join(root, api.dir, 'docs', 'protocol')),
48
+ );
49
+ if (matched.length === 1) return matched[0]!;
50
+ throw new Error(
51
+ `无法唯一确定承接转写协议的双包产品 (现有 ${pairs.length} 组, 带 docs/protocol 的 ${matched.length} 组)`,
52
+ );
53
+ }
54
+
55
+ /** 两包坐标: 由根 package.json 的 workspaces 与 docs/protocol 锚点派生 */
56
+ const { api: API_PKG, cli: CLI_PKG } = resolveProtocolProductPair(REPO_ROOT);
42
57
  /** 被测源: 两包的 src (mutant 是整仓实现的注入副本) 与各自 package.json (副本自足可跑) */
43
58
  const API_SRC_DIR = join(REPO_ROOT, API_PKG.dir, 'src');
44
59
  const CLI_SRC_DIR = join(REPO_ROOT, CLI_PKG.dir, 'src');
@@ -67,11 +82,16 @@ interface PatchSpec {
67
82
  effect: string;
68
83
  }
69
84
 
85
+ /** 预期抓住该 mutant 的测试面 (三态: cli / api / both) */
86
+ export type MutantSurface = 'cli' | 'api' | 'both';
87
+
70
88
  interface MutantSpec {
71
89
  id: string;
72
90
  title: string;
73
- /** 预期抓住它的语料类型; 变异自证时逐条核对 */
74
- expectCaughtBy: string;
91
+ /** 预期被哪一面语料抓住 (三态: cli / api / both); 变异自证时按面核对 */
92
+ expectCaughtBy: MutantSurface;
93
+ /** 预期抓住它的典型用例说明 (人读, 随 mutant.json 存档) */
94
+ expectNote: string;
75
95
  patches: PatchSpec[];
76
96
  }
77
97
 
@@ -79,7 +99,9 @@ const MUTANTS: MutantSpec[] = [
79
99
  {
80
100
  id: 'prune-negated',
81
101
  title: '剪枝谓词取反',
82
- expectCaughtBy: '任一命中 node_modules 的用例 (stdoutExact / fs 断言)',
102
+ expectCaughtBy: 'both',
103
+ expectNote:
104
+ '任一命中 node_modules 的 CLI / API 用例 (stdoutExact / hits / fs 断言)',
83
105
  patches: [
84
106
  {
85
107
  file: 'scan-parallel.ts',
@@ -93,8 +115,9 @@ const MUTANTS: MutantSpec[] = [
93
115
  {
94
116
  id: 'exit-swallowed',
95
117
  title: '退出码吞掉',
96
- expectCaughtBy:
97
- '期望 exitCode 为 1 的用例 (参数错误 / 配置损坏 / 删除失败 / 无配置 --yes)',
118
+ expectCaughtBy: 'cli',
119
+ expectNote:
120
+ '期望 exitCode 为 1 的 CLI 用例 (参数错误 / 配置损坏 / 删除失败 / 无配置 --yes)',
98
121
  patches: [
99
122
  {
100
123
  file: 'cli.ts',
@@ -107,7 +130,9 @@ const MUTANTS: MutantSpec[] = [
107
130
  {
108
131
  id: 'sort-missing',
109
132
  title: '排序缺失',
110
- expectCaughtBy: '≥2 个命中的用例 (stdoutExact 逐字节比较), 或复现性三连跑',
133
+ expectCaughtBy: 'both',
134
+ expectNote:
135
+ '≥2 个命中的 CLI / API 用例 (stdoutExact / hits 升序断言), 或复现性三连跑',
111
136
  patches: [
112
137
  {
113
138
  file: 'scan-parallel.ts',
@@ -121,8 +146,9 @@ const MUTANTS: MutantSpec[] = [
121
146
  {
122
147
  id: 'exclude-silent',
123
148
  title: '排除静默失效',
124
- expectCaughtBy:
125
- '使用 exclude (配置 exclude 或 --exclude) 的用例: 被排除子树重新出现在清单里',
149
+ expectCaughtBy: 'both',
150
+ expectNote:
151
+ '使用 exclude 的 CLI / API 用例 (被排除子树重新出现在清单或 hits 里)',
126
152
  patches: [
127
153
  {
128
154
  file: 'scan-parallel.ts',
@@ -136,8 +162,9 @@ const MUTANTS: MutantSpec[] = [
136
162
  {
137
163
  id: 'message-removed',
138
164
  title: '提示语删改',
139
- expectCaughtBy:
140
- '空结果用例 (stdoutExact / stdoutContains 对「未发现」文案的断言)',
165
+ expectCaughtBy: 'cli',
166
+ expectNote:
167
+ '空结果 CLI 用例 (stdoutExact / stdoutContains 对「未发现」文案的断言)',
141
168
  patches: [
142
169
  {
143
170
  file: 'render.ts',
@@ -150,8 +177,9 @@ const MUTANTS: MutantSpec[] = [
150
177
  {
151
178
  id: 'size-unit-wrong',
152
179
  title: '体积计数单位错',
153
- expectCaughtBy:
154
- '带体积数字断言的用例; 注意: 仅 du 可用平台 (unix) 生效, Windows 走 js 候选时抓不住',
180
+ expectCaughtBy: 'cli',
181
+ expectNote:
182
+ '带体积数字断言的 CLI 用例; 注意: 仅 du 可用平台 (unix) 生效, Windows 走 js 候选时抓不住',
155
183
  patches: [
156
184
  {
157
185
  file: 'size-du.ts',
@@ -161,6 +189,50 @@ const MUTANTS: MutantSpec[] = [
161
189
  },
162
190
  ],
163
191
  },
192
+ {
193
+ id: 'size-gone-dropped',
194
+ title: '体积 gone 桶丢弃 (破坏 BC-43 三桶完备性)',
195
+ expectCaughtBy: 'api',
196
+ expectNote:
197
+ '断言 SizeResult.gone 的 API 用例 (api-size-gone-bucket / api-size-three-buckets-and-warning)',
198
+ patches: [
199
+ {
200
+ file: 'size-du.ts',
201
+ find: ' gone.push(target);',
202
+ replace: ' /* mutant: drop gone target */',
203
+ effect:
204
+ 'du 候选丢弃已消失目标的 gone 记录, 破坏 SizeResult 三桶完备性恒等式',
205
+ },
206
+ {
207
+ file: 'size-js.ts',
208
+ find: ' gone.push(target);',
209
+ replace: ' /* mutant: drop gone target */',
210
+ effect:
211
+ 'js 候选丢弃已消失目标的 gone 记录, 破坏 SizeResult 三桶完备性恒等式',
212
+ },
213
+ ],
214
+ },
215
+ {
216
+ id: 'terminal-event-dropped',
217
+ title: '编排终结事件丢失 (破坏 BC-44)',
218
+ expectCaughtBy: 'api',
219
+ expectNote:
220
+ '断言 plan-done / done 终结事件的 API 用例 (api-sweep-plan-terminal-event / api-plan-onprogress-override / api-sweep-run-terminal-event)',
221
+ patches: [
222
+ {
223
+ file: 'sweep.ts',
224
+ find: " planOptions?.onProgress?.({\n kind: 'plan-done',\n plan,\n elapsedMs: Date.now() - startedAt,\n });",
225
+ replace: ' /* mutant: drop plan-done terminal event */',
226
+ effect: 'sweeper.plan() 不再发射 plan-done 终结事件',
227
+ },
228
+ {
229
+ file: 'sweep.ts',
230
+ find: " emit?.({ kind: 'done', status, elapsedMs: Date.now() - startedAt });",
231
+ replace: ' /* mutant: drop done terminal event */',
232
+ effect: 'sweeper.run() 不再发射 done 终结事件',
233
+ },
234
+ ],
235
+ },
164
236
  ];
165
237
 
166
238
  // ---------------------------------------------------------------------------
@@ -190,18 +262,24 @@ function countOccurrences(text: string, needle: string): number {
190
262
  const lineOf = (text: string, needle: string): number =>
191
263
  text.slice(0, text.indexOf(needle)).split('\n').length;
192
264
 
193
- /** 取 src 下应复制的文件清单: 全部 .ts, 排除测试文件; 排序保证复制次序确定 */
194
- async function listSourceFiles(srcDir: string): Promise<string[]> {
195
- const entries = await readdir(srcDir, { withFileTypes: true });
196
- return entries
197
- .filter(
198
- (entry) =>
199
- entry.isFile() &&
200
- entry.name.endsWith('.ts') &&
201
- !entry.name.endsWith('.test.ts'),
202
- )
203
- .map((entry) => entry.name)
204
- .sort();
265
+ /** 递归取 src 下应复制的相对路径清单: 全部 .ts, 排除测试文件; 排序保证复制次序确定 */
266
+ async function listSourceFiles(srcDir: string, prefix = ''): Promise<string[]> {
267
+ const dir = prefix === '' ? srcDir : join(srcDir, prefix);
268
+ const entries = await readdir(dir, { withFileTypes: true });
269
+ const files: string[] = [];
270
+ for (const entry of entries) {
271
+ const rel = prefix === '' ? entry.name : join(prefix, entry.name);
272
+ if (entry.isDirectory()) {
273
+ files.push(...(await listSourceFiles(srcDir, rel)));
274
+ } else if (
275
+ entry.isFile() &&
276
+ entry.name.endsWith('.ts') &&
277
+ !entry.name.endsWith('.test.ts')
278
+ ) {
279
+ files.push(rel);
280
+ }
281
+ }
282
+ return files.sort();
205
283
  }
206
284
 
207
285
  interface AppliedPatch {
@@ -269,11 +347,10 @@ async function makeMutant(mutant: MutantSpec): Promise<AppliedPatch[]> {
269
347
  [API_SRC_DIR, join(outDir, API_PKG.dir)],
270
348
  [CLI_SRC_DIR, join(outDir, CLI_PKG.dir)],
271
349
  ] as const) {
272
- for (const name of await listSourceFiles(srcDir)) {
273
- await writeFile(
274
- join(pkgDir, 'src', name),
275
- await readFile(join(srcDir, name)),
276
- );
350
+ for (const rel of await listSourceFiles(srcDir)) {
351
+ const dest = join(pkgDir, 'src', rel);
352
+ await mkdir(dirname(dest), { recursive: true });
353
+ await writeFile(dest, await readFile(join(srcDir, rel)));
277
354
  }
278
355
  }
279
356
  // 套件的 API 参考 harness 副本: 按仓库同相对结构放入, 使 api 面语料可直接以
@@ -313,13 +390,14 @@ async function makeMutant(mutant: MutantSpec): Promise<AppliedPatch[]> {
313
390
  );
314
391
 
315
392
  // cli 副本对 API 包名的解析必须落在 api 副本上 (而非宿主仓库的真包);
316
- // 链接置于副本根 node_modules, 按就近解析优先于仓库根的真实 workspace 链接。
393
+ // 链接目标按 relative(dirname(apiLink), apiTarget) 动态算深度, 同时兼容 scoped (@scope/pkg → ../..) 与无 scope (pkg → ..)
317
394
  const apiLink = join(outDir, 'node_modules', API_PKG_NAME);
395
+ const apiTarget = join(outDir, API_PKG.dir);
318
396
  await mkdir(dirname(apiLink), { recursive: true });
319
397
  await symlink(
320
398
  process.platform === 'win32'
321
- ? join(outDir, API_PKG.dir)
322
- : join('..', '..', API_PKG.dir),
399
+ ? apiTarget
400
+ : relative(dirname(apiLink), apiTarget),
323
401
  apiLink,
324
402
  process.platform === 'win32' ? 'junction' : 'dir',
325
403
  );
@@ -344,6 +422,7 @@ async function makeMutant(mutant: MutantSpec): Promise<AppliedPatch[]> {
344
422
  id: mutant.id,
345
423
  title: mutant.title,
346
424
  expectCaughtBy: mutant.expectCaughtBy,
425
+ expectNote: mutant.expectNote,
347
426
  sourceDir: `${API_PKG.dir}/src + ${CLI_PKG.dir}/src`,
348
427
  runHint: `bun ${join(MUTANTS_DIR, `${GEN_PREFIX}${mutant.id}`, CLI_PKG.dir, 'src', 'cli.ts')}`,
349
428
  patches: applied,
@@ -10,9 +10,9 @@
10
10
  * - fixture.ts fixture 建树 / setup 预置 / 最小 env / 执行 / 清理 (cli 与 api 两类 case);
11
11
  * - compare.ts 逐项比对 (cli: 退出码 / stdout 与 stderr 的子串含与禁含 / fs 终态; api: 返回值 / 抛错 / 事件);
12
12
  * - report.ts 报告数据结构与人读 / JSON 渲染;
13
- * - api-harness.ts 参考 API harness (独立入口; 协议见 docs/sweep/protocol/conformance/api-harness-protocol.md)。
13
+ * - api-harness.ts 参考 API harness (独立入口; 协议见 packages/{{NAME}}/docs/protocol/conformance/api-harness-protocol.md)。
14
14
  *
15
- * 语料权威: docs/sweep/protocol/conformance/corpus.schema.json (字段语义以 schema 为准; 手写校验是
15
+ * 语料权威: packages/{{NAME}}/docs/protocol/conformance/corpus.schema.json (字段语义以 schema 为准; 手写校验是
16
16
  * schema 的物化子集, 只为尽早给出可读报错, 不复刻 schema 的全部约束)。
17
17
  *
18
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 子串>]
@@ -21,13 +21,13 @@
21
21
  * 退出码: 0 全部通过; 1 存在失败用例; 2 用法 / 语料 / 环境错误 (runner 自身问题, 非被测缺陷)。
22
22
  */
23
23
  import { existsSync } from 'node:fs';
24
- import { mkdir, mkdtemp, realpath } from 'node:fs/promises';
25
- import { homedir } from 'node:os';
24
+ import { realpath } from 'node:fs/promises';
26
25
  import { dirname, isAbsolute, join, resolve } from 'node:path';
27
26
  import { fileURLToPath } from 'node:url';
28
27
 
28
+ import { makeTmpRoot } from '../lib/tmp-root.ts';
29
29
  import { compareApiCase, compareCase } from './compare.ts';
30
- import { type CorpusCase, loadCorpus } from './corpus.ts';
30
+ import { CORPUS_REL, type CorpusCase, loadCorpus } from './corpus.ts';
31
31
  import {
32
32
  type ExecOutcome,
33
33
  type RunContext,
@@ -46,26 +46,20 @@ import {
46
46
 
47
47
  const HERE = dirname(fileURLToPath(import.meta.url));
48
48
  /**
49
- * 默认语料目录: 语料的权威落点在协议区 (docs/sweep/protocol/conformance/corpus), 脚本不随身携带语料。
50
- * 脚本现居 scripts/transcription/, 自 HERE 上溯 2 级到仓库根再取 docs。
49
+ * 默认语料目录: 从 corpus.ts 的唯一协议根常量 (PROTOCOL_ROOT) 派生, 避免路径硬编码散落。
51
50
  */
52
- const DEFAULT_CORPUS_DIR = join(
53
- HERE,
54
- '..',
55
- '..',
56
- 'docs',
57
- 'sweep',
58
- 'protocol',
59
- 'conformance',
60
- 'corpus',
61
- );
51
+ const DEFAULT_CORPUS_DIR = join(HERE, '..', '..', CORPUS_REL);
62
52
  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')}`;
53
+ /** 默认 API harness 命令数组: 直接以 argv 形态构造, 不对含绝对路径的命令做空白 split */
54
+ const DEFAULT_API_TARGET_ARGV: readonly string[] = [
55
+ 'bun',
56
+ join(HERE, 'api-harness.ts'),
57
+ ];
65
58
 
66
59
  interface CliOptions {
67
60
  target: string;
68
- apiTarget: string;
61
+ /** 显式传入的 --api-target 字符串; 缺省时直接使用 DEFAULT_API_TARGET_ARGV 数组 */
62
+ apiTarget?: string;
69
63
  corpusDir: string;
70
64
  filter?: string;
71
65
  timeoutMs: number;
@@ -84,9 +78,9 @@ type ParseOutcome =
84
78
  const HELP_TEXT = [
85
79
  '用法: bun scripts/transcription/run-conformance.ts --target "<被测命令>" [选项]',
86
80
  '',
87
- ' --target <cmd> 被测进程命令 (如 "bun packages/{{NAME}}-cli/src/cli.ts", 或 PATH 中的 "{{BIN_NAME}}" / 绝对路径形态); 按空白拆分, 不支持含空格的路径',
81
+ ' --target <cmd> 被测进程命令 (如 "bun packages/{{NAME}}-cli/src/cli.ts", 或 PATH 中的 "{{BIN_NAME}}" / 绝对路径形态); 按空白拆分, 支持用单 / 双引号包裹含空格的路径',
88
82
  ' --api-target <cmd> API 用例的被测 harness 命令 (缺省: 随套件参考 harness, 即 "bun <仓库根>/scripts/transcription/api-harness.ts"); 拆分与绝对化规则同 --target',
89
- ' --corpus <dir> 语料目录 (默认: docs/sweep/protocol/conformance/corpus)',
83
+ ` --corpus <dir> 语料目录 (默认: ${CORPUS_REL})`,
90
84
  ' --filter <text> 只跑 id 含该子串的用例',
91
85
  ' --timeout <ms> 单条用例执行超时 (默认 15000), 到期即判失败 (超时守卫)',
92
86
  ' --json 输出结构化 JSON 报告 (stdout 仅 JSON, 诊断走 stderr)',
@@ -108,12 +102,12 @@ const HELP_TEXT = [
108
102
  * --target 收值 'bun packages/{{NAME}}-cli/src/cli.ts'; --filter 收值 'scan-'; 其余取默认
109
103
  *
110
104
  * 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 } }
105
+ * return { ok: true, options: { target: 'bun packages/{{NAME}}-cli/src/cli.ts', corpusDir: 'packages/{{NAME}}/docs/protocol/conformance/corpus', filter: 'scan-', timeoutMs: 15000, json: false, keep: false, help: false } }
112
106
  * ```
113
107
  */
114
108
  function parseArgs(argv: string[]): ParseOutcome {
115
109
  let target: string | undefined;
116
- let apiTarget = DEFAULT_API_TARGET;
110
+ let apiTarget: string | undefined;
117
111
  let corpusDir = DEFAULT_CORPUS_DIR;
118
112
  let filter: string | undefined;
119
113
  let timeoutMs = DEFAULT_TIMEOUT_MS;
@@ -200,6 +194,38 @@ function parseArgs(argv: string[]): ParseOutcome {
200
194
  };
201
195
  }
202
196
 
197
+ /**
198
+ * 将命令行字符串切分为 argv 数组: 支持单 / 双引号包裹含空格的路径,
199
+ * 避免直接 `.split(/\s+/)` 撕裂含空格的绝对路径。
200
+ */
201
+ function splitCommand(raw: string): string[] {
202
+ const parts: string[] = [];
203
+ let current = '';
204
+ let quote: string | null = null;
205
+ for (let index = 0; index < raw.length; index += 1) {
206
+ const ch = raw[index]!;
207
+ if (quote !== null) {
208
+ if (ch === quote) quote = null;
209
+ else current += ch;
210
+ continue;
211
+ }
212
+ if (ch === '"' || ch === "'") {
213
+ quote = ch;
214
+ continue;
215
+ }
216
+ if (/\s/.test(ch)) {
217
+ if (current !== '') {
218
+ parts.push(current);
219
+ current = '';
220
+ }
221
+ continue;
222
+ }
223
+ current += ch;
224
+ }
225
+ if (current !== '') parts.push(current);
226
+ return parts;
227
+ }
228
+
203
229
  /**
204
230
  * 把 target 命令里按启动目录写的相对路径绝对化。
205
231
  * 必要原因: 被测进程的 cwd 会被设为 fixture 目录 (用例可声明), 而 `--target "bun packages/{{NAME}}-cli/src/cli.ts"`
@@ -208,7 +234,7 @@ function parseArgs(argv: string[]): ParseOutcome {
208
234
  * 的路径串, 其余原样透传。
209
235
  */
210
236
  function absolutizeTargetArgv(
211
- targetArgv: string[],
237
+ targetArgv: readonly string[],
212
238
  launchDir: string,
213
239
  ): string[] {
214
240
  return targetArgv.map((part, index) => {
@@ -231,7 +257,7 @@ async function runCase(
231
257
  ctx: RunContext,
232
258
  ): Promise<CaseReport> {
233
259
  const startedAt = Date.now();
234
- const rawRoot = await mkdtemp(join(ctx.workBase, 'sweep-conformance-'));
260
+ const rawRoot = makeTmpRoot('conformance-');
235
261
  // realpath 归一: macOS 上 /var 与 /private/var 是同一位置的两种拼写, 统一用 realpath 形态
236
262
  // 作 $FIXTURE 的替换值, 使期望文本与 process.cwd() / realpath 化输出一致。
237
263
  const root = await realpath(rawRoot);
@@ -285,13 +311,13 @@ async function main(): Promise<number> {
285
311
  }
286
312
 
287
313
  const targetArgv = absolutizeTargetArgv(
288
- options.target.trim().split(/\s+/),
289
- process.cwd(),
290
- );
291
- const apiTargetArgv = absolutizeTargetArgv(
292
- options.apiTarget.trim().split(/\s+/),
314
+ splitCommand(options.target),
293
315
  process.cwd(),
294
316
  );
317
+ const apiTargetArgv =
318
+ options.apiTarget === undefined
319
+ ? [...DEFAULT_API_TARGET_ARGV]
320
+ : absolutizeTargetArgv(splitCommand(options.apiTarget), process.cwd());
295
321
  let cases: CorpusCase[];
296
322
  try {
297
323
  cases = await loadCorpus(resolve(options.corpusDir));
@@ -311,14 +337,11 @@ async function main(): Promise<number> {
311
337
  return 2;
312
338
  }
313
339
 
314
- const workBase = join(homedir(), 'tmp');
315
- await mkdir(workBase, { recursive: true });
316
340
  const ctx: RunContext = {
317
341
  targetArgv,
318
342
  apiTargetArgv,
319
343
  timeoutMs: options.timeoutMs,
320
344
  keep: options.keep,
321
- workBase,
322
345
  };
323
346
 
324
347
  const reports: CaseReport[] = [];
@@ -8,6 +8,7 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { dirname, join } from 'node:path';
9
9
 
10
10
  import { makeTmpRoot } from '../lib/tmp-root.ts';
11
+ import { CONTRACT_REL, CORPUS_REL, COVERAGE_REL } from './corpus.ts';
11
12
  import {
12
13
  collectCorpusRefs,
13
14
  extractContractNumbers,
@@ -83,12 +84,10 @@ describe('reconcile', () => {
83
84
  describe('validateCoverage 集成', () => {
84
85
  test('健康态全绿; 造一处悬空与一处漏登记即分别抓出', () => {
85
86
  const healthy = makeRoot({
86
- 'docs/sweep/protocol/behavior-contract.md':
87
- '| BC-01 | 甲 |\n| BC-02 | 乙 |\n',
88
- 'docs/sweep/protocol/conformance/coverage.md':
87
+ [CONTRACT_REL]: '| BC-01 | 甲 |\n| BC-02 | 乙 |\n',
88
+ [COVERAGE_REL]:
89
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',
90
+ [`${CORPUS_REL}/a.json`]: '{"id":"a","specRefs":["BC-01"]}\n',
92
91
  });
93
92
  expect(validateCoverage(healthy)).toEqual({
94
93
  dangling: [],
@@ -97,11 +96,9 @@ describe('validateCoverage 集成', () => {
97
96
  });
98
97
 
99
98
  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',
99
+ [CONTRACT_REL]: '| BC-01 | 甲 |\n| BC-02 | 乙 |\n',
100
+ [COVERAGE_REL]: '## 一、覆盖表\n',
101
+ [`${CORPUS_REL}/a.json`]: '{"id":"a","specRefs":["BC-01","BC-77"]}\n',
105
102
  });
106
103
  const result = validateCoverage(broken);
107
104
  expect(result.dangling).toEqual(['BC-77']);
@@ -110,10 +107,10 @@ describe('validateCoverage 集成', () => {
110
107
 
111
108
  test('corpus 目录单文件缺 specRefs 即抛 (语料损坏属硬错)', () => {
112
109
  const root = makeRoot({
113
- 'docs/sweep/protocol/conformance/corpus/bad.json': '{"id":"bad"}\n',
110
+ [`${CORPUS_REL}/bad.json`]: '{"id":"bad"}\n',
114
111
  });
115
- expect(() =>
116
- collectCorpusRefs(join(root, 'docs/sweep/protocol/conformance/corpus')),
117
- ).toThrow(/缺 specRefs/);
112
+ expect(() => collectCorpusRefs(join(root, CORPUS_REL))).toThrow(
113
+ /缺 specRefs/,
114
+ );
118
115
  });
119
116
  });
@@ -18,13 +18,11 @@ import { readFileSync, readdirSync } from 'node:fs';
18
18
  import { join } from 'node:path';
19
19
 
20
20
  import { REPO_ROOT } from '../lint-doc-shared.ts';
21
+ import { CONTRACT_REL, CORPUS_REL, COVERAGE_REL } from './corpus.ts';
22
+ import { CLAUSE_ID_SOURCE, SPEC_REF_PATTERN } from './validate.ts';
21
23
 
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;
24
+ /** 条款号形态 (行首表格单元格): 与 validate.ts 共享唯一正则源 */
25
+ const CLAUSE_IN_CELL = new RegExp(CLAUSE_ID_SOURCE, 'g');
28
26
 
29
27
  /** 从行为契约主表提取全部条款号 (行首单元格以条款号开头的表格行) */
30
28
  export function extractContractNumbers(text: string): Set<string> {
@@ -32,7 +30,7 @@ export function extractContractNumbers(text: string): Set<string> {
32
30
  for (const line of text.split('\n')) {
33
31
  const cell = line.match(/^\|\s*([^|]*?)\s*\|/)?.[1];
34
32
  if (!cell) continue;
35
- for (const m of cell.matchAll(/^(?:BC|OF|EC)-\d+$/g)) numbers.add(m[0]);
33
+ if (SPEC_REF_PATTERN.test(cell)) numbers.add(cell);
36
34
  }
37
35
  return numbers;
38
36
  }
@@ -99,12 +97,12 @@ export function validateCoverage(
99
97
  root: string = REPO_ROOT,
100
98
  ): CoverageReconciliation {
101
99
  const contract = extractContractNumbers(
102
- readFileSync(join(root, CONTRACT_MD), 'utf8'),
100
+ readFileSync(join(root, CONTRACT_REL), 'utf8'),
103
101
  );
104
102
  const exempt = extractExemptNumbers(
105
- readFileSync(join(root, COVERAGE_MD), 'utf8'),
103
+ readFileSync(join(root, COVERAGE_REL), 'utf8'),
106
104
  );
107
- const referenced = collectCorpusRefs(join(root, CORPUS_DIR));
105
+ const referenced = collectCorpusRefs(join(root, CORPUS_REL));
108
106
  return reconcile(contract, referenced, exempt);
109
107
  }
110
108
 
@@ -2,7 +2,7 @@
2
2
  * 转写契约套件 · 语料手写校验层 (schema 的物化子集)。
3
3
  *
4
4
  * 职责: 对 loadCorpus 读入的单条 case 做结构校验 (cli 与 api 两类按 kind 分流), 返回可读
5
- * 问题清单; 字段语义以 docs/sweep/protocol/conformance/corpus.schema.json 为准, 本层只为尽早给出
5
+ * 问题清单; 字段语义以对应产品包的 docs/protocol/conformance/corpus.schema.json 为准, 本层只为尽早给出
6
6
  * 报错, 不复刻 schema 的全部约束。
7
7
  */
8
8
  import { isAbsolute } from 'node:path';
@@ -17,7 +17,9 @@ const asRecord = (value: unknown): Record<string, unknown> | null =>
17
17
  : null;
18
18
 
19
19
  const ID_PATTERN = /^[a-z0-9]+(-[a-z0-9]+)*$/;
20
- const SPEC_REF_PATTERN = /^[A-Z]{2,4}-[0-9]+$/;
20
+ /** 契约条款编号统一形态 (单源: validate.ts 与 validate-coverage.ts 共用) */
21
+ export const CLAUSE_ID_SOURCE = '(?:BC|OF|EC)-\\d+';
22
+ export const SPEC_REF_PATTERN = new RegExp(`^${CLAUSE_ID_SOURCE}$`);
21
23
 
22
24
  /** 相对路径判定: 非空、非绝对 (含 win 盘符)、不含反斜杠与 '..' 段 */
23
25
  function isSafeRelPath(value: unknown): value is string {
@@ -279,6 +281,20 @@ function validateApiExpect(expect: unknown, problems: string[]): void {
279
281
  }
280
282
  }
281
283
  const result = record.result;
284
+ const error = record.error;
285
+ if (result !== undefined && error !== undefined) {
286
+ problems.push('expect.result 与 expect.error 互斥, 不能同时声明');
287
+ }
288
+ if (
289
+ result === undefined &&
290
+ error === undefined &&
291
+ record.events === undefined &&
292
+ record.fs === undefined
293
+ ) {
294
+ problems.push(
295
+ 'api case 的 expect 须至少含 result / error / events / fs 之一',
296
+ );
297
+ }
282
298
  if (result !== undefined) {
283
299
  const shape = asRecord(result);
284
300
  const hasExact = shape !== null && 'exact' in shape;
@@ -287,7 +303,6 @@ function validateApiExpect(expect: unknown, problems: string[]): void {
287
303
  problems.push('expect.result 须恰含 exact 或 subset 之一');
288
304
  }
289
305
  }
290
- const error = record.error;
291
306
  if (error !== undefined) {
292
307
  const shape = asRecord(error);
293
308
  if (shape === null || typeof shape.code !== 'string' || shape.code === '') {
@@ -1,20 +1,11 @@
1
1
  {
2
2
  "compilerOptions": {
3
- // bun / node 均可直跑 TS, 目标取保守基线
4
3
  "target": "ES2022",
5
4
  "lib": ["ES2022"],
6
5
  "module": "preserve",
7
6
  "moduleResolution": "bundler",
8
- // 开发态解析: monorepo 内对 API 包的引用直指单源 src (零构建), 发布态由 API 包
9
- // package.json 的 exports 指向 dist; tsconfig paths 优先级高于 node_modules 解析
10
- // (bun 运行时 / tsc / bun build 三处已实测, 2026-09-29), 消费方项目无本配置不受影响
11
7
  "paths": {
12
- "{{SCOPE}}/{{NAME}}": [
13
- "./packages/{{NAME}}/src/index.ts"
14
- ],
15
- "{{SCOPE}}/{{NAME}}/testing": [
16
- "./packages/{{NAME}}/src/fixtures.ts"
17
- ]
8
+ "{{SCOPE}}/{{NAME}}": ["./packages/{{NAME}}/src/index.ts"]
18
9
  },
19
10
 
20
11
  "strict": true,
@@ -33,14 +24,5 @@
33
24
 
34
25
  "types": ["bun"]
35
26
  },
36
- // 变异生成器的产物 (scripts/transcription/mutants/gen-*/packages/*/src/*.ts) 由 make-mutants.ts
37
- // 生成, 是派生件而非源码; 不排除则从根跑 tsc 会把它们收进编译范围并变红 (实测命中)
38
- // 生成器包 (packages/create-clis) 的两个模板空间同理不进本仓检查面: assets/ 是按清单产出的
39
- // 构建产物 (目录结构是新项目根, 含占位符路径与跨包引用), template-skeletons/ 是镜像新项目布局的
40
- // 骨架; 二者只在新项目语境里成立 (同款排除见 .gitignore / .prettierignore / .oxlintrc.json)
41
- "exclude": [
42
- "scripts/transcription/mutants",
43
- "packages/create-clis/assets",
44
- "packages/create-clis/scripts/template-skeletons"
45
- ]
27
+ "exclude": ["dist", "node_modules"]
46
28
  }