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,219 @@
1
+ /**
2
+ * 转写契约套件 · API 面参考 harness。
3
+ *
4
+ * 职责: 把一条 api 语料的调用指令 (stdin JSON) 物化为对 API 包真实导出的调用, 把末步返回值 /
5
+ * 抛错 / 收集的进度事件写成 stdout JSON。它与 CLI 面「被测命令是参数」同构: 任何语言的实现
6
+ * 按协议 (docs/sweep/protocol/conformance/api-harness-protocol.md) 提供自己的 harness 可执行,
7
+ * 套件零改动即可验收。
8
+ *
9
+ * 指令形状 (stdin):
10
+ * { "steps": [
11
+ * { "as": "s", "call": { "export": "createScanner", "args": [ { ... } ] } }, // 创建步
12
+ * { "call": { "on": "s", "method": "scan", "args": [] }, "collectEvents": true } // 方法步
13
+ * ] }
14
+ * 步骤按序执行; 末步返回值即输出的 value; 任一步抛错即终止并以 error 形态输出。
15
+ *
16
+ * 输出形状 (stdout):
17
+ * { "ok": true, "value": <末步返回值>, "events": [ ... ]? }
18
+ * { "ok": false, "error": { "name", "code"?, "message", "details"? } }
19
+ * (方法步声明过 collectEvents 即附 events 字段, 可为空数组; 创建步声明该字段按指令错误处理。)
20
+ *
21
+ * 变量与探针: 字符串内的 $FIXTURE 由验收器 (runner) 在派发前替换; 参数中形如
22
+ * { "$probe": "<名>" } 的对象整体替换为下方探针注册表的值。collectEvents 为 true 时,
23
+ * 收集器以 onProgress 并入该次调用的末个参数 (末参为对象则合并其中并覆盖既有 onProgress,
24
+ * 否则追加 { onProgress })。
25
+ *
26
+ * 路径策略: 本文件以相对路径直连 API 包单源 (.../packages/{{NAME}}/src/index.ts);
27
+ * mutant 副本按同相对结构复制本文件即自动指向副本源码 (见 make-mutants.ts)。bun 与 node
28
+ * (≥ 22.18 类型剥离) 均可直跑。
29
+ */
30
+ import { readFileSync } from 'node:fs';
31
+
32
+ import * as api from '../../packages/{{NAME}}/src/index.ts';
33
+
34
+ /** harness 自身问题 (指令非法 / 探针未知 / 导出与方法不存在), 与被测 API 的抛错同形态输出 */
35
+ class HarnessError extends Error {
36
+ override readonly name = 'HarnessError';
37
+ }
38
+
39
+ /**
40
+ * 探针注册表 (初版最小集; 协议规定的命名集合, 语言实现者须提供同名等价物)。
41
+ * - pathops.posix / pathops.win32: 真实 PathStyle (纯 path 语义, 可直接充当被测的注入面);
42
+ * - deviceProbe.uniform: 恒报同一设备号的 DeviceProbe stub (同设备基准面; 跨设备类场景的
43
+ * 细分 stub 按条款需求增补, 增补不破坏既有语料)。
44
+ * 增补探针时须同步 docs/sweep/protocol/conformance/api-harness-protocol.md 的注册表清单。
45
+ */
46
+ const PROBES: Record<string, unknown> = {
47
+ 'pathops.posix': api.POSIX_STYLE,
48
+ 'pathops.win32': api.WIN32_STYLE,
49
+ 'deviceProbe.uniform': async () => 1,
50
+ };
51
+
52
+ /** 单步指令 (字段全可选, 合法性由执行期校验并给出可读报错) */
53
+ interface CallStep {
54
+ as?: string;
55
+ call?: {
56
+ export?: string;
57
+ on?: string;
58
+ method?: string;
59
+ args?: unknown[];
60
+ };
61
+ collectEvents?: boolean;
62
+ }
63
+
64
+ const isPlainObject = (value: unknown): value is Record<string, unknown> =>
65
+ typeof value === 'object' && value !== null && !Array.isArray(value);
66
+
67
+ /**
68
+ * 递归解析参数值: 含 $probe 键的对象整体替换为探针实现 (对象其余键不参与); 数组与普通对象递归
69
+ * 下钻; 其余值原样。探针名不在注册表即抛 HarnessError (指令缺陷, 不静默透传)。
70
+ */
71
+ function resolveProbes(value: unknown): unknown {
72
+ if (Array.isArray(value)) return value.map(resolveProbes);
73
+ if (isPlainObject(value)) {
74
+ if ('$probe' in value) {
75
+ const name = value.$probe;
76
+ if (typeof name !== 'string' || !(name in PROBES)) {
77
+ throw new HarnessError(`未知探针: ${String(name)}`);
78
+ }
79
+ return PROBES[name];
80
+ }
81
+ return Object.fromEntries(
82
+ Object.entries(value).map(([key, item]) => [key, resolveProbes(item)]),
83
+ );
84
+ }
85
+ return value;
86
+ }
87
+
88
+ /**
89
+ * 执行一条指令: 按 steps 顺序建句柄 / 调方法, 收集事件, 返回末步返回值。
90
+ *
91
+ * ### 数据追踪示例
92
+ * ```text
93
+ * Input(真实 Payload)
94
+ * instruction.steps = [
95
+ * { as: 's', call: { export: 'createScanner', args: [{ roots: ['<fixture>/zone'], exclude: [] }] } },
96
+ * { call: { on: 's', method: 'scan' }, collectEvents: true },
97
+ * ]
98
+ *
99
+ * 步骤 1:创建步执行
100
+ * handles = { s: <Scanner 实例> }; value = Scanner 实例
101
+ *
102
+ * 步骤 2:collectEvents 并入末参
103
+ * finalArgs = [{ onProgress: <收集器> }]; returned = ScanResult; events 累计进度事件
104
+ *
105
+ * Output(数据契约)
106
+ * return { value: ScanResult, events: MeasureProgressEvent 以外的 ScanProgressEvent[] }
107
+ * ```
108
+ */
109
+ async function runInstruction(instruction: unknown): Promise<{
110
+ value: unknown;
111
+ events: unknown[];
112
+ collected: boolean;
113
+ }> {
114
+ if (
115
+ !isPlainObject(instruction) ||
116
+ !Array.isArray(instruction.steps) ||
117
+ instruction.steps.length === 0
118
+ ) {
119
+ throw new HarnessError('指令缺少非空 steps 数组');
120
+ }
121
+
122
+ const handles = new Map<string, Record<string, unknown>>();
123
+ const events: unknown[] = [];
124
+ let collected = false;
125
+ let value: unknown;
126
+
127
+ for (const [index, item] of instruction.steps.entries()) {
128
+ const step = item as CallStep;
129
+ if (!isPlainObject(step) || !isPlainObject(step.call)) {
130
+ throw new HarnessError(`steps[${index}] 须为 { call: { ... } } 形态`);
131
+ }
132
+ const call = step.call;
133
+ if (call.args !== undefined && !Array.isArray(call.args)) {
134
+ throw new HarnessError(`steps[${index}]: args 须为数组`);
135
+ }
136
+ const args = (call.args ?? []).map(resolveProbes);
137
+ let returned: unknown;
138
+
139
+ if (typeof call.export === 'string') {
140
+ if (step.collectEvents === true) {
141
+ throw new HarnessError(
142
+ `steps[${index}]: 创建步不支持 collectEvents (仅方法步)`,
143
+ );
144
+ }
145
+ const fn = (api as Record<string, unknown>)[call.export];
146
+ if (typeof fn !== 'function') {
147
+ throw new HarnessError(
148
+ `steps[${index}]: 导出不存在或不是函数: ${call.export}`,
149
+ );
150
+ }
151
+ returned = await (fn as (...rest: unknown[]) => unknown)(...args);
152
+ } else if (typeof call.on === 'string' && typeof call.method === 'string') {
153
+ const handle = handles.get(call.on);
154
+ if (handle === undefined) {
155
+ throw new HarnessError(`steps[${index}]: 句柄未定义: ${call.on}`);
156
+ }
157
+ const method = handle[call.method];
158
+ if (typeof method !== 'function') {
159
+ throw new HarnessError(
160
+ `steps[${index}]: 句柄 ${call.on} 上无方法: ${call.method}`,
161
+ );
162
+ }
163
+ let finalArgs = args;
164
+ if (step.collectEvents === true) {
165
+ collected = true;
166
+ const onProgress = (event: unknown): void => {
167
+ events.push(event);
168
+ };
169
+ const lastIndex = args.length - 1;
170
+ const last = args[lastIndex];
171
+ finalArgs = isPlainObject(last)
172
+ ? [...args.slice(0, lastIndex), { ...last, onProgress }]
173
+ : [...args, { onProgress }];
174
+ }
175
+ returned = await (method as (...rest: unknown[]) => unknown).apply(
176
+ handle,
177
+ finalArgs,
178
+ );
179
+ } else {
180
+ throw new HarnessError(
181
+ `steps[${index}]: 须为创建步 (call.export) 或方法步 (call.on + call.method)`,
182
+ );
183
+ }
184
+
185
+ if (typeof step.as === 'string') {
186
+ if (!isPlainObject(returned)) {
187
+ throw new HarnessError(
188
+ `steps[${index}]: as 句柄要求返回对象, 实得 ${typeof returned}`,
189
+ );
190
+ }
191
+ handles.set(step.as, returned);
192
+ }
193
+ value = returned;
194
+ }
195
+
196
+ return { value, events, collected };
197
+ }
198
+
199
+ try {
200
+ const raw = readFileSync(0, 'utf8');
201
+ const outcome = await runInstruction(JSON.parse(raw));
202
+ const output: Record<string, unknown> = { ok: true, value: outcome.value };
203
+ if (outcome.collected) output.events = outcome.events;
204
+ process.stdout.write(`${JSON.stringify(output)}\n`);
205
+ } catch (error) {
206
+ // 抛出物未必是 Error (字符串 / undefined 等): 包装后 name / message 恒有, 协议声明的
207
+ // 必有字段不失守 (JSON.stringify 会丢弃 undefined 值, 否则 error 成空对象)。
208
+ const failure: Error & { code?: unknown; details?: unknown } =
209
+ error instanceof Error
210
+ ? (error as Error & { code?: unknown; details?: unknown })
211
+ : new Error(String(error));
212
+ const errorOut: Record<string, unknown> = {
213
+ name: failure.name !== '' ? failure.name : 'Error',
214
+ message: failure.message,
215
+ };
216
+ if (typeof failure.code === 'string') errorOut.code = failure.code;
217
+ if (failure.details !== undefined) errorOut.details = failure.details;
218
+ process.stdout.write(`${JSON.stringify({ ok: false, error: errorOut })}\n`);
219
+ }
@@ -0,0 +1,421 @@
1
+ /**
2
+ * 转写契约套件 · 比对层。
3
+ *
4
+ * 职责: 拿一条语料的 expect 面逐项量被测进程的实际结果 (cli case: 退出码 / stdout 逐字节 /
5
+ * stdout 与 stderr 的子串含与禁含 / 文件系统终态; api case: 返回值深比较与子集包含 / 错误名与码 /
6
+ * 事件集与末事件), 产出失败清单。本层只判不修: 不触碰现场, 不改被测行为。
7
+ */
8
+ import { lstat, readdir } from 'node:fs/promises';
9
+ import { join } from 'node:path';
10
+
11
+ import {
12
+ type ApiExpectSpec,
13
+ type ExpectSpec,
14
+ type FsExpectation,
15
+ applyVars,
16
+ replaceVarsDeep,
17
+ } from './corpus.ts';
18
+ import type { ExecOutcome } from './fixture.ts';
19
+ import { type FailureItem, clip } from './report.ts';
20
+
21
+ /** 找两段文本的首个差异行, 返回人话摘要 (行号从 1 起) */
22
+ export function firstLineDiff(expected: string, actual: string): string {
23
+ const expectedLines = expected.split('\n');
24
+ const actualLines = actual.split('\n');
25
+ const max = Math.max(expectedLines.length, actualLines.length);
26
+ for (let index = 0; index < max; index += 1) {
27
+ const exp = expectedLines[index];
28
+ const act = actualLines[index];
29
+ if (exp === act) continue;
30
+ if (exp === undefined)
31
+ return `第 ${index + 1} 行起实际输出更长: 实际 "${clip(act ?? '')}"`;
32
+ if (act === undefined)
33
+ return `第 ${index + 1} 行起期望输出更长: 期望 "${clip(exp)}"`;
34
+ return `首个差异在第 ${index + 1} 行: 期望 "${clip(exp)}", 实际 "${clip(act)}"`;
35
+ }
36
+ return '全文逐行相等但不逐字节相等 (差异在行尾字节)';
37
+ }
38
+
39
+ /**
40
+ * 文件系统终态断言: gone (不存在) / exists (存在, lstat 语义) / empty (存在且空目录)。
41
+ * 返回 null 即通过, 否则返回失败说明。
42
+ */
43
+ export async function checkFs(
44
+ root: string,
45
+ item: FsExpectation,
46
+ ): Promise<string | null> {
47
+ const full = join(root, item.path);
48
+ let info: Awaited<ReturnType<typeof lstat>> | null;
49
+ try {
50
+ info = await lstat(full);
51
+ } catch {
52
+ info = null;
53
+ }
54
+
55
+ if (item.state === 'gone') {
56
+ return info === null ? null : `期望不存在, 实际存在 (${item.path})`;
57
+ }
58
+ if (info === null) return `期望存在, 实际不存在 (${item.path})`;
59
+ if (item.state === 'exists') return null;
60
+
61
+ if (!info.isDirectory()) return `期望为空目录, 实际不是目录 (${item.path})`;
62
+ const entries = await readdir(full);
63
+ return entries.length === 0
64
+ ? null
65
+ : `期望为空目录, 实际有 ${entries.length} 项 (${item.path})`;
66
+ }
67
+
68
+ /**
69
+ * 逐项比对一条用例的全部断言。超时与执行级失败为短路项 (后续断言无意义, 只报该条)。
70
+ *
71
+ * ### 数据追踪示例
72
+ * ```text
73
+ * Input(真实 Payload)
74
+ * expect = { exitCode: 0, stdoutExact: '▍ <CLI 显示名> 预览 · 1 个根: $FIXTURE/zone\n…', fs: [{ path: 'zone/a/node_modules', state: 'exists' }] }
75
+ * exec = { status: 0, stdout: '…与期望一致…', stderr: '', timedOut: false }
76
+ *
77
+ * 步骤 1:短路项检查
78
+ * timedOut / spawnError 均为假, 继续逐项比对
79
+ *
80
+ * 步骤 2:逐项 (退出码 → stdoutExact → 子串含与禁含 → fs)
81
+ * 全部通过 → failures = []
82
+ *
83
+ * Output(数据契约)
84
+ * return [] (通过) 或 FailureItem[] (逐项失败原因与期望 / 实际)
85
+ * ```
86
+ */
87
+ export async function compareCase(
88
+ expect: ExpectSpec,
89
+ exec: ExecOutcome,
90
+ root: string,
91
+ ): Promise<FailureItem[]> {
92
+ const failures: FailureItem[] = [];
93
+
94
+ if (exec.timedOut) {
95
+ failures.push({
96
+ kind: 'timeout',
97
+ message: '执行超时 (超时守卫击中, 进程已被杀), 判失败',
98
+ });
99
+ return failures;
100
+ }
101
+ if (exec.spawnError !== undefined) {
102
+ failures.push({
103
+ kind: 'spawn',
104
+ message: `被测命令无法执行: ${exec.spawnError}`,
105
+ });
106
+ return failures;
107
+ }
108
+
109
+ if (exec.status !== expect.exitCode) {
110
+ failures.push({
111
+ kind: 'exitCode',
112
+ message: `退出码不符: 期望 ${expect.exitCode}, 实际 ${exec.status}`,
113
+ expected: String(expect.exitCode),
114
+ actual: String(exec.status),
115
+ });
116
+ }
117
+
118
+ if (expect.stdoutExact !== undefined) {
119
+ const wanted = applyVars(expect.stdoutExact, root);
120
+ if (exec.stdout !== wanted) {
121
+ failures.push({
122
+ kind: 'stdoutExact',
123
+ message: `stdout 与期望不逐字节相等 (${firstLineDiff(wanted, exec.stdout)})`,
124
+ expected: wanted,
125
+ actual: exec.stdout,
126
+ });
127
+ }
128
+ }
129
+
130
+ for (const needle of expect.stdoutContains ?? []) {
131
+ const wanted = applyVars(needle, root);
132
+ if (!exec.stdout.includes(wanted)) {
133
+ failures.push({
134
+ kind: 'stdoutContains',
135
+ message: `stdout 缺少子串: "${clip(wanted)}"`,
136
+ });
137
+ }
138
+ }
139
+
140
+ for (const needle of expect.stdoutMustNotContain ?? []) {
141
+ const forbidden = applyVars(needle, root);
142
+ if (exec.stdout.includes(forbidden)) {
143
+ failures.push({
144
+ kind: 'stdoutMustNotContain',
145
+ message: `stdout 出现了禁含子串: "${clip(forbidden)}"`,
146
+ });
147
+ }
148
+ }
149
+
150
+ for (const needle of expect.stderrContains ?? []) {
151
+ const wanted = applyVars(needle, root);
152
+ if (!exec.stderr.includes(wanted)) {
153
+ failures.push({
154
+ kind: 'stderrContains',
155
+ message: `stderr 缺少子串: "${clip(wanted)}"`,
156
+ });
157
+ }
158
+ }
159
+
160
+ for (const needle of expect.stderrMustNotContain ?? []) {
161
+ const forbidden = applyVars(needle, root);
162
+ if (exec.stderr.includes(forbidden)) {
163
+ failures.push({
164
+ kind: 'stderrMustNotContain',
165
+ message: `stderr 出现了禁含子串: "${clip(forbidden)}"`,
166
+ });
167
+ }
168
+ }
169
+
170
+ for (const item of expect.fs ?? []) {
171
+ const problem = await checkFs(root, item);
172
+ if (problem !== null) failures.push({ kind: 'fs', message: problem });
173
+ }
174
+
175
+ return failures;
176
+ }
177
+
178
+ /** 对象判定 (JSON 语义: 非 null、非数组的对象) */
179
+ const isPlainRecord = (value: unknown): value is Record<string, unknown> =>
180
+ typeof value === 'object' && value !== null && !Array.isArray(value);
181
+
182
+ /** 深比较 (键序无关; 作用域为 JSON 域值: 对象 / 数组 / 原始值) */
183
+ function deepEqual(left: unknown, right: unknown): boolean {
184
+ if (left === right) return true;
185
+ if (Array.isArray(left) || Array.isArray(right)) {
186
+ return (
187
+ Array.isArray(left) &&
188
+ Array.isArray(right) &&
189
+ left.length === right.length &&
190
+ left.every((item, index) => deepEqual(item, right[index]))
191
+ );
192
+ }
193
+ if (isPlainRecord(left) || isPlainRecord(right)) {
194
+ if (!isPlainRecord(left) || !isPlainRecord(right)) return false;
195
+ const leftKeys = Object.keys(left).sort();
196
+ const rightKeys = Object.keys(right).sort();
197
+ return (
198
+ leftKeys.length === rightKeys.length &&
199
+ leftKeys.every(
200
+ (key, index) =>
201
+ key === rightKeys[index] && deepEqual(left[key], right[key]),
202
+ )
203
+ );
204
+ }
205
+ return false;
206
+ }
207
+
208
+ /**
209
+ * 递归子集检查: 期望对象逐键存在且子集匹配, 期望数组等长逐项匹配, 原始值深比较。
210
+ * 返回首个差异说明 (通过为 null); pathHint 形如 `$.hits[0].target`。
211
+ */
212
+ function subsetDiff(
213
+ expected: unknown,
214
+ actual: unknown,
215
+ pathHint: string,
216
+ ): string | null {
217
+ if (isPlainRecord(expected)) {
218
+ if (!isPlainRecord(actual)) {
219
+ return `${pathHint}: 期望对象, 实际 ${JSON.stringify(actual)}`;
220
+ }
221
+ for (const [key, value] of Object.entries(expected)) {
222
+ if (!(key in actual)) return `${pathHint}: 缺键 ${key}`;
223
+ const problem = subsetDiff(value, actual[key], `${pathHint}.${key}`);
224
+ if (problem !== null) return problem;
225
+ }
226
+ return null;
227
+ }
228
+ if (Array.isArray(expected)) {
229
+ if (!Array.isArray(actual)) return `${pathHint}: 期望数组, 实际非数组`;
230
+ if (expected.length !== actual.length) {
231
+ return `${pathHint}: 数组长度 期望 ${expected.length} 实际 ${actual.length}`;
232
+ }
233
+ for (const [index, item] of expected.entries()) {
234
+ const problem = subsetDiff(item, actual[index], `${pathHint}[${index}]`);
235
+ if (problem !== null) return problem;
236
+ }
237
+ return null;
238
+ }
239
+ if (!deepEqual(expected, actual)) {
240
+ return `${pathHint}: 期望 ${JSON.stringify(expected)}, 实际 ${JSON.stringify(actual)}`;
241
+ }
242
+ return null;
243
+ }
244
+
245
+ /** 事件流断言: 集合成员 (mustInclude) 与末位 (lastIs); 事件序不承诺, 故不按序比对 */
246
+ function checkEvents(
247
+ expect: NonNullable<ApiExpectSpec['events']>,
248
+ raw: unknown,
249
+ ): FailureItem[] {
250
+ const failures: FailureItem[] = [];
251
+ if (!Array.isArray(raw)) {
252
+ failures.push({
253
+ kind: 'events',
254
+ message:
255
+ '期望事件断言, 但 harness 输出未附 events 数组 (步骤是否漏了 collectEvents?)',
256
+ });
257
+ return failures;
258
+ }
259
+ const kinds = raw.map((item) =>
260
+ isPlainRecord(item) ? item.kind : undefined,
261
+ );
262
+ if (expect.lastIs !== undefined) {
263
+ const last = kinds[kinds.length - 1];
264
+ if (last !== expect.lastIs) {
265
+ failures.push({
266
+ kind: 'events',
267
+ message: `末事件不符: 期望 ${expect.lastIs}, 实际 ${String(last)}`,
268
+ expected: expect.lastIs,
269
+ actual: typeof last === 'string' ? last : String(last),
270
+ });
271
+ }
272
+ }
273
+ for (const wanted of expect.mustInclude ?? []) {
274
+ if (!kinds.includes(wanted)) {
275
+ failures.push({ kind: 'events', message: `事件流缺少 kind: ${wanted}` });
276
+ }
277
+ }
278
+ return failures;
279
+ }
280
+
281
+ /**
282
+ * 逐项比对一条 api 用例的全部断言: 解析 harness 输出 JSON → result (exact / subset) /
283
+ * error (code / name) / events (lastIs / mustInclude) / fs。超时与执行级失败为短路项
284
+ * (与 cli 面同口径)。
285
+ *
286
+ * ### 数据追踪示例
287
+ * ```text
288
+ * Input(真实 Payload)
289
+ * expect = { result: { subset: { hits: [{ target: '$FIXTURE/zone/a/node_modules' }] } } }
290
+ * exec = { status: 0, stdout: '{"ok":true,"value":{"hits":[{"target":"<realpath>/zone/a/node_modules", …}], …}}', stderr: '', timedOut: false }
291
+ *
292
+ * 步骤 1:形态校验
293
+ * outcome = { ok: true, value: { … } }, 合法 (ok 为布尔且层次正确)
294
+ *
295
+ * 步骤 2:result.subset 递归比对 ($FIXTURE 已替换为 realpath)
296
+ * $.hits[0].target 命中 → 其余相等 → failures = []
297
+ *
298
+ * Output(数据契约)
299
+ * return [] 或 FailureItem[] (kind: harness | result | error | events | fs)
300
+ * ```
301
+ */
302
+ export async function compareApiCase(
303
+ expect: ApiExpectSpec,
304
+ exec: ExecOutcome,
305
+ root: string,
306
+ ): Promise<FailureItem[]> {
307
+ const failures: FailureItem[] = [];
308
+
309
+ if (exec.timedOut) {
310
+ failures.push({
311
+ kind: 'timeout',
312
+ message: '执行超时 (超时守卫击中, 进程已被杀), 判失败',
313
+ });
314
+ return failures;
315
+ }
316
+ if (exec.spawnError !== undefined) {
317
+ failures.push({
318
+ kind: 'spawn',
319
+ message: `API harness 无法执行: ${exec.spawnError}`,
320
+ });
321
+ return failures;
322
+ }
323
+ if (exec.status !== 0) {
324
+ const stderrNote =
325
+ exec.stderr.trim() === '' ? '' : `; stderr: ${clip(exec.stderr.trim())}`;
326
+ failures.push({
327
+ kind: 'harness',
328
+ message: `harness 非零退出 (${String(exec.status)})${stderrNote}`,
329
+ });
330
+ return failures;
331
+ }
332
+ let outcome: unknown;
333
+ try {
334
+ outcome = JSON.parse(exec.stdout);
335
+ } catch {
336
+ failures.push({
337
+ kind: 'harness',
338
+ message: `harness stdout 不是合法 JSON: ${clip(exec.stdout.trim())}`,
339
+ });
340
+ return failures;
341
+ }
342
+ if (!isPlainRecord(outcome) || typeof outcome.ok !== 'boolean') {
343
+ failures.push({
344
+ kind: 'harness',
345
+ message: `harness 输出缺少 ok 布尔字段: ${clip(exec.stdout.trim())}`,
346
+ });
347
+ return failures;
348
+ }
349
+
350
+ if (outcome.ok === true) {
351
+ if (expect.error !== undefined) {
352
+ failures.push({
353
+ kind: 'error',
354
+ message: `期望抛错 (code=${expect.error.code}), 实际成功返回`,
355
+ });
356
+ }
357
+ if (expect.result !== undefined) {
358
+ if ('exact' in expect.result) {
359
+ const wanted = replaceVarsDeep(expect.result.exact, root);
360
+ if (!deepEqual(wanted, outcome.value)) {
361
+ failures.push({
362
+ kind: 'result',
363
+ message: 'result 与期望深比较不等',
364
+ expected: JSON.stringify(wanted, null, 2) ?? 'undefined',
365
+ actual: JSON.stringify(outcome.value, null, 2) ?? 'undefined',
366
+ });
367
+ }
368
+ } else {
369
+ const wanted = replaceVarsDeep(expect.result.subset, root);
370
+ const problem = subsetDiff(wanted, outcome.value, '$');
371
+ if (problem !== null) {
372
+ failures.push({
373
+ kind: 'result',
374
+ message: `result 子集不符: ${problem}`,
375
+ });
376
+ }
377
+ }
378
+ }
379
+ if (expect.events !== undefined) {
380
+ failures.push(...checkEvents(expect.events, outcome.events));
381
+ }
382
+ } else {
383
+ const error = isPlainRecord(outcome.error) ? outcome.error : null;
384
+ if (expect.result !== undefined) {
385
+ const code = typeof error?.code === 'string' ? error.code : '?';
386
+ const message = typeof error?.message === 'string' ? error.message : '';
387
+ failures.push({
388
+ kind: 'error',
389
+ message: `期望成功返回, 实际抛错: ${code} ${message}`.trim(),
390
+ });
391
+ }
392
+ if (expect.error !== undefined) {
393
+ const actualCode = error?.code;
394
+ if (actualCode !== expect.error.code) {
395
+ failures.push({
396
+ kind: 'error',
397
+ message: `错误码不符: 期望 ${expect.error.code}, 实际 ${String(actualCode)}`,
398
+ expected: expect.error.code,
399
+ actual:
400
+ typeof actualCode === 'string' ? actualCode : String(actualCode),
401
+ });
402
+ }
403
+ if (
404
+ expect.error.name !== undefined &&
405
+ error?.name !== expect.error.name
406
+ ) {
407
+ failures.push({
408
+ kind: 'error',
409
+ message: `错误类名不符: 期望 ${expect.error.name}, 实际 ${String(error?.name)}`,
410
+ });
411
+ }
412
+ }
413
+ }
414
+
415
+ for (const item of expect.fs ?? []) {
416
+ const problem = await checkFs(root, item);
417
+ if (problem !== null) failures.push({ kind: 'fs', message: problem });
418
+ }
419
+
420
+ return failures;
421
+ }