create-clis 0.1.0 → 1.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 (87) 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 +6 -6
  34. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +2 -2
  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/scripts/ci.ts +285 -64
  48. package/assets/template/scripts/install-git-hooks.mjs +10 -0
  49. package/assets/template/scripts/install-git-hooks.test.ts +1 -1
  50. package/assets/template/scripts/lib/npm-trust-parse.ts +169 -0
  51. package/assets/template/scripts/lib/release-cli.ts +299 -0
  52. package/assets/template/scripts/lib/release-verify.ts +148 -15
  53. package/assets/template/scripts/lib/workspace.test.ts +63 -1
  54. package/assets/template/scripts/lib/workspace.ts +132 -42
  55. package/assets/template/scripts/lint-dependency-direction.test.ts +131 -0
  56. package/assets/template/scripts/lint-dependency-direction.ts +130 -0
  57. package/assets/template/scripts/lint-doc-examples.test.ts +45 -9
  58. package/assets/template/scripts/lint-doc-examples.ts +227 -50
  59. package/assets/template/scripts/lint-doc-references.test.ts +36 -0
  60. package/assets/template/scripts/lint-doc-references.ts +142 -57
  61. package/assets/template/scripts/lint-doc-shared.ts +26 -23
  62. package/assets/template/scripts/lint-stray-backups.test.ts +3 -1
  63. package/assets/template/scripts/lint-stray-backups.ts +7 -3
  64. package/assets/template/scripts/npm-trust-guard.test.ts +56 -8
  65. package/assets/template/scripts/npm-trust-guard.ts +116 -200
  66. package/assets/template/scripts/safe-install.ts +28 -23
  67. package/assets/template/scripts/transcription/api-harness.ts +28 -206
  68. package/assets/template/scripts/transcription/compare.test.ts +84 -0
  69. package/assets/template/scripts/transcription/compare.ts +4 -4
  70. package/assets/template/scripts/transcription/corpus.ts +9 -3
  71. package/assets/template/scripts/transcription/fixture.ts +2 -4
  72. package/assets/template/scripts/transcription/make-mutants.ts +116 -37
  73. package/assets/template/scripts/transcription/run-conformance.ts +57 -34
  74. package/assets/template/scripts/transcription/validate-coverage.test.ts +11 -14
  75. package/assets/template/scripts/transcription/validate-coverage.ts +8 -10
  76. package/assets/template/scripts/transcription/validate.ts +18 -3
  77. package/assets/template/tsconfig.json +2 -20
  78. package/assets/template/turbo.jsonc +7 -52
  79. package/bin/bunfig.toml +3 -0
  80. package/bin/create-clis.mjs +165 -104
  81. package/dist/create-clis.js +48 -87681
  82. package/dist/manifest.json +3 -3
  83. package/package.json +9 -5
  84. package/assets/template/packages/{{NAME}}/docs/README.md +0 -21
  85. package/assets/template/packages/{{NAME}}-cli/docs/README.md +0 -21
  86. package/bin/create-clis +0 -35
  87. package/bin/create-clis.cmd +0 -32
@@ -1,31 +1,25 @@
1
1
  /**
2
- * 文档示例闸门: ts 代码块的真实类型校验 + shell 块的 CLI 面核对。
3
- *
4
- * 动机: 2026-09-30 漂移复审实测抓到文档示例与真实签名不符 (api-surface 的
5
- * `isSuccessOutcome` 片段入参类型错误, 照抄编译报 TS2345), 属「只有人工审计才能发现」
6
- * 的类别; 示例可编译性是确定性事实, 故落为闸门 (镜像实现对: fiu-kits 的 lint-doc-examples)。
2
+ * 文档示例闸门: ts 代码块的真实类型校验 + shell 块的多 CLI 面核对。
7
3
  *
8
4
  * 两档:
9
- * - 类型档: 采集「自足」ts 块 (判据: 块内出现行首 import 语句), 拼成临时 tsc 工程对 API 包
10
- * 真实类型校验 (临时工程 extends 仓库根 tsconfig, paths 直连源码单源; typeRoots 指回仓
11
- * 内 @types, 临时目录解析不到 bun 类型实测 TS2688)。报错分类: 全为「名字未找到」类
12
- * (TS2304 等) 的块判为片段 (依赖上文块, 不做跨块拼接), 打印 INFO 跳过; 含其他错误
13
- * (TS2345 签名不符 / TS2339 成员不存在等) 的块判为真断裂, 红灯。
14
- * - CLI 档: 采集 shell 块内以 `{{BIN_NAME}}` 开头的命令, 提取旗标与子命令, 对照 `--help`
15
- * 输出逐一核对存在性 (抓「新增旗标漏登记进文档 / 文档写了不存在的旗标」)。
5
+ * - 类型档: 采集「自足」ts 块 (行首 import), 拼成临时 tsc 工程对 API 包真实类型校验。
6
+ * - 校验 tsc 执行本身未故障 (退出码非零且无块错误或 spawn 报错直接红灯, 防工具坏了假绿);
7
+ * - 若 TS2307 (Cannot find module) 指向本仓 scope/包名, 判为真断裂 (防改包名后示例假绿);
8
+ * - 仅非本仓虚构模块或未定义外部变量的块判为片段跳过。
9
+ * - CLI 档: 自动发现仓内所有带 `bin` 且具备 `src/cli.ts` 的 CLI 工具,
10
+ * 采集 shell 块内以对应命令名开头的行, 对照各自 `--help` 核对旗标与子命令。
16
11
  *
17
12
  * 用法: bun scripts/lint-doc-examples.ts
18
13
  * 退出码: 0 全绿; 1 存在断裂。
19
14
  */
20
15
  import { spawnSync } from 'node:child_process';
21
- import { readFileSync, rmSync, writeFileSync } from 'node:fs';
16
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
22
17
  import { join } from 'node:path';
23
18
 
24
19
  import { makeTmpRoot } from './lib/tmp-root.ts';
20
+ import { listWorkspacePackages } from './lib/workspace.ts';
25
21
  import { REPO_ROOT, walkFiles } from './lint-doc-shared.ts';
26
22
 
27
- const CLI_ENTRY = 'packages/{{NAME}}-cli/src/cli.ts';
28
-
29
23
  /** 一个被采集到的 ts 代码块 */
30
24
  export interface TsBlock {
31
25
  file: string;
@@ -34,6 +28,20 @@ export interface TsBlock {
34
28
  content: string;
35
29
  }
36
30
 
31
+ /** 被核对的一个 CLI 目标 */
32
+ export interface CliTarget {
33
+ /** 命令名 (package.json 的 bin 字段声明的可执行名) */
34
+ binName: string;
35
+ /** CLI 源码入口相对仓库根路径 */
36
+ entryPath: string;
37
+ }
38
+
39
+ /** 从文本提取的带命令名的 shell 示例 */
40
+ export interface NamedShellCommand {
41
+ binName: string;
42
+ command: string;
43
+ }
44
+
37
45
  /** 提取全文的 ```ts 块 (闭合围栏以 ``` 收尾; startLine 指向内容首行) */
38
46
  export function extractTsBlocks(content: string, file = '<inline>'): TsBlock[] {
39
47
  const blocks: TsBlock[] = [];
@@ -61,13 +69,25 @@ export function isSelfContained(block: string): boolean {
61
69
  return /^import\b/m.test(block);
62
70
  }
63
71
 
64
- /** 提取 shell 块中以 {{BIN_NAME}} 开头的命令行 (跳过注释行) */
65
- export function extractShellCommands(content: string): string[] {
66
- const commands: string[] = [];
72
+ /** 构造命令名前缀正则 (转义正则元字符) */
73
+ const escapeRegex = (value: string): string =>
74
+ value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
75
+
76
+ /** 提取 shell/bash/sh 块中以指定命令名集合开头的命令行 (跳过注释行) */
77
+ export function extractNamedShellCommands(
78
+ content: string,
79
+ cliNames: readonly string[],
80
+ ): NamedShellCommand[] {
81
+ if (cliNames.length === 0) return [];
82
+ const patterns = cliNames.map((binName) => ({
83
+ binName,
84
+ re: new RegExp(`^${escapeRegex(binName)}(?:\\s|$)`),
85
+ }));
86
+ const commands: NamedShellCommand[] = [];
67
87
  const lines = content.split('\n');
68
88
  let inShell = false;
69
89
  for (const line of lines) {
70
- if (/^```shell\s*$/.test(line)) {
90
+ if (/^```(?:shell|bash|sh)\s*$/.test(line)) {
71
91
  inShell = true;
72
92
  continue;
73
93
  }
@@ -77,23 +97,46 @@ export function extractShellCommands(content: string): string[] {
77
97
  }
78
98
  if (!inShell) continue;
79
99
  const trimmed = line.trim();
80
- if (trimmed.startsWith('#') || !/^{{BIN_NAME}}(\s|$)/.test(trimmed)) continue;
81
- commands.push(trimmed);
100
+ if (trimmed === '' || trimmed.startsWith('#')) continue;
101
+ for (const { binName, re } of patterns) {
102
+ if (re.test(trimmed)) {
103
+ commands.push({ binName, command: trimmed });
104
+ break;
105
+ }
106
+ }
82
107
  }
83
108
  return commands;
84
109
  }
85
110
 
86
- /** 从一条命令提取待核对 token: --旗标 (去掉 =值, 去重) 与首个位置参数 (子命令) */
111
+ /** 兼容旧签名: 提取 shell 块中以 {{BIN_NAME}} 开头的命令行 */
112
+ export function extractShellCommands(
113
+ content: string,
114
+ cliName = '{{BIN_NAME}}',
115
+ ): string[] {
116
+ return extractNamedShellCommands(content, [cliName]).map(
117
+ (item) => item.command,
118
+ );
119
+ }
120
+
121
+ /** 从一条命令提取待核对 token: --旗标 (去掉 =值, 去重) 与纯标识符形态的首个子命令 */
87
122
  export function extractCommandTokens(command: string): string[] {
88
123
  const tokens: string[] = [];
89
124
  const parts = command.split(/\s+/).slice(1);
125
+ let sawFlag = false;
126
+ let sawSubcommand = false;
90
127
  for (const part of parts) {
128
+ if (part === '--') break;
129
+ if (part === '\\' || part === '&&' || part === '||' || part === '|') break;
91
130
  if (part.startsWith('-')) {
131
+ sawFlag = true;
92
132
  tokens.push(part.split('=')[0]!);
93
133
  continue;
94
134
  }
95
- // 位置参数: 只认第一个 (子命令); 其余是旗标的值 (如 --exclude my-kits 的 my-kits)
96
- if (tokens.length === 0) tokens.push(part);
135
+ // 仅在首个旗标之前、且形状为纯小写子命令标识符 (不含路径/扩展名/占位符) 时作为子命令核对
136
+ if (!sawFlag && !sawSubcommand && /^[a-z][a-z0-9-]*$/.test(part)) {
137
+ sawSubcommand = true;
138
+ tokens.push(part);
139
+ }
97
140
  }
98
141
  return [...new Set(tokens)];
99
142
  }
@@ -119,7 +162,7 @@ const FRAGMENT_ERROR_CODES: ReadonlySet<string> = new Set([
119
162
  'TS18046', // 'x' is of type 'unknown' (收窄所需的守卫未定义时连带)
120
163
  'TS2580', // Cannot find name 'require'
121
164
  'TS2503', // Cannot find namespace
122
- 'TS2307', // Cannot find module (片段引用未随块给出的模块)
165
+ 'TS2307', // Cannot find module (仅限非本仓包名的片段模块; 本仓 scope 见下单独拦)
123
166
  ]);
124
167
 
125
168
  /** 分类一个块的错误集合: 'clean' | 'fragment' | 'real' */
@@ -132,6 +175,46 @@ export function classifyBlock(
132
175
  : 'real';
133
176
  }
134
177
 
178
+ /** 收集工作区 scope 前缀与包名, 防止本仓包改名后被 TS2307 静默豁免 */
179
+ function collectWorkspaceScopes(root: string): {
180
+ names: Set<string>;
181
+ scopes: Set<string>;
182
+ } {
183
+ const names = new Set<string>();
184
+ const scopes = new Set<string>();
185
+ if (!existsSync(join(root, 'package.json'))) return { names, scopes };
186
+ try {
187
+ for (const pkg of listWorkspacePackages(root)) {
188
+ names.add(pkg.name);
189
+ if (pkg.name.startsWith('@') && pkg.name.includes('/')) {
190
+ scopes.add(`${pkg.name.slice(0, pkg.name.indexOf('/'))}/`);
191
+ }
192
+ }
193
+ } catch {
194
+ // 迷你测试根无 workspaces 时忽略
195
+ }
196
+ return { names, scopes };
197
+ }
198
+
199
+ /** 检查报错行里的 TS2307 是否指向本仓包/scope (是则真断裂, 不可豁免) */
200
+ function hitsWorkspaceModuleNotFound(
201
+ blockLines: readonly string[],
202
+ workspace: { names: Set<string>; scopes: Set<string> },
203
+ ): boolean {
204
+ for (const line of blockLines) {
205
+ const match = line.match(
206
+ /error TS2307: Cannot find module ['"]([^'"]+)['"]/,
207
+ );
208
+ if (!match) continue;
209
+ const mod = match[1]!;
210
+ if (workspace.names.has(mod)) return true;
211
+ for (const scope of workspace.scopes) {
212
+ if (mod.startsWith(scope)) return true;
213
+ }
214
+ }
215
+ return false;
216
+ }
217
+
135
218
  /** 类型档: 采集自足块 → 临时工程编译 → 返回 (真断裂条目, 片段 INFO 列表) */
136
219
  export function checkTsExamples(root: string = REPO_ROOT): {
137
220
  real: string[];
@@ -148,7 +231,7 @@ export function checkTsExamples(root: string = REPO_ROOT): {
148
231
  }
149
232
  if (blocks.length === 0) return { real: [], fragments: [] };
150
233
 
151
- // 临时工程: extends 仓库根 tsconfig (paths 直连单源), typeRoots 指回仓内 @types
234
+ const workspace = collectWorkspaceScopes(root);
152
235
  const tmp = makeTmpRoot('doc-examples-');
153
236
  try {
154
237
  for (const [index, block] of blocks.entries()) {
@@ -169,25 +252,60 @@ export function checkTsExamples(root: string = REPO_ROOT): {
169
252
  2,
170
253
  )}\n`,
171
254
  );
172
- const result = spawnSync(
173
- 'bunx',
174
- ['tsc', '-p', join(tmp, 'tsconfig.json')],
175
- { cwd: root, encoding: 'utf8' },
176
- );
177
- const perBlock = parseTscErrors(`${result.stdout ?? ''}`);
255
+ const rootTsc = join(root, 'node_modules', 'typescript', 'bin', 'tsc');
256
+ const repoTsc = join(REPO_ROOT, 'node_modules', 'typescript', 'bin', 'tsc');
257
+ const localTsc = existsSync(rootTsc) ? rootTsc : repoTsc;
258
+ const result = existsSync(localTsc)
259
+ ? spawnSync(
260
+ process.execPath,
261
+ [localTsc, '-p', join(tmp, 'tsconfig.json')],
262
+ { cwd: root, encoding: 'utf8' },
263
+ )
264
+ : spawnSync(
265
+ 'bun',
266
+ ['x', '--no-install', 'tsc', '-p', join(tmp, 'tsconfig.json')],
267
+ { cwd: root, encoding: 'utf8' },
268
+ );
269
+ const combinedOutput = `${result.stdout ?? ''}\n${result.stderr ?? ''}`;
270
+ if (result.error !== undefined) {
271
+ return {
272
+ real: [`tsc 执行失败: ${result.error.message}`],
273
+ fragments: [],
274
+ };
275
+ }
276
+ const perBlock = parseTscErrors(combinedOutput);
277
+ if (result.status !== 0 && perBlock.size === 0) {
278
+ const snippet = combinedOutput.trim().slice(0, 300);
279
+ return {
280
+ real: [
281
+ `tsc 异常退出 (exit ${String(result.status)}): ${snippet || '(无输出)'}`,
282
+ ],
283
+ fragments: [],
284
+ };
285
+ }
286
+
287
+ const allLines = combinedOutput.split('\n');
178
288
  const real: string[] = [];
179
289
  const fragments: string[] = [];
180
290
  for (const [index, block] of blocks.entries()) {
181
- const kind = classifyBlock(perBlock.get(index));
291
+ const codes = perBlock.get(index);
292
+ const blockLines = allLines.filter((line) =>
293
+ line.includes(`block-${index}.ts(`),
294
+ );
295
+ let kind = classifyBlock(codes);
296
+ if (
297
+ kind === 'fragment' &&
298
+ hitsWorkspaceModuleNotFound(blockLines, workspace)
299
+ ) {
300
+ kind = 'real';
301
+ }
182
302
  const at = `${block.file}:${block.startLine}`;
183
303
  if (kind === 'fragment') {
184
304
  fragments.push(
185
- `${at} (引用块外上下文, ${[...(perBlock.get(index) ?? [])].join('/')})`,
305
+ `${at} (引用块外上下文, ${[...(codes ?? [])].join('/')})`,
186
306
  );
187
307
  } else if (kind === 'real') {
188
- const detail = `${result.stdout ?? ''}`
189
- .split('\n')
190
- .filter((line) => line.includes(`block-${index}.ts(`))
308
+ const detail = blockLines
191
309
  .map((line) => line.replace(/^.*block-\d+\.ts/, '行内'))
192
310
  .join('; ');
193
311
  real.push(`${at} :: ${detail}`);
@@ -195,28 +313,88 @@ export function checkTsExamples(root: string = REPO_ROOT): {
195
313
  }
196
314
  return { real, fragments };
197
315
  } finally {
198
- rmSync(tmp, { recursive: true, force: true });
316
+ rmSync(tmp, {
317
+ recursive: true,
318
+ force: true,
319
+ maxRetries: 5,
320
+ retryDelay: 100,
321
+ });
322
+ }
323
+ }
324
+
325
+ /** 从 package.json 的 bin 字段提取可执行命令名列表 */
326
+ function extractBinNames(pkgName: string, binField: unknown): string[] {
327
+ if (typeof binField === 'string') {
328
+ return [
329
+ pkgName.includes('/') ? pkgName.slice(pkgName.indexOf('/') + 1) : pkgName,
330
+ ];
331
+ }
332
+ if (binField !== null && typeof binField === 'object') {
333
+ return Object.keys(binField as Record<string, unknown>);
334
+ }
335
+ return [];
336
+ }
337
+
338
+ /** 发现仓内全部可核对的 CLI 工具目标 (兼容无根 package.json 的迷你测试根) */
339
+ export function discoverCliTargets(root: string): CliTarget[] {
340
+ const targets: CliTarget[] = [];
341
+ if (existsSync(join(root, 'package.json'))) {
342
+ try {
343
+ for (const pkg of listWorkspacePackages(root)) {
344
+ const entryPath = `${pkg.dir}/src/cli.ts`;
345
+ if (!existsSync(join(root, entryPath))) continue;
346
+ for (const binName of extractBinNames(pkg.name, pkg.manifest.bin)) {
347
+ targets.push({ binName, entryPath });
348
+ }
349
+ }
350
+ } catch {
351
+ // 忽略非标准迷你根
352
+ }
199
353
  }
354
+ if (targets.length === 0) {
355
+ const fallback = 'packages/{{NAME}}-cli/src/cli.ts';
356
+ if (existsSync(join(root, fallback))) {
357
+ targets.push({ binName: '{{BIN_NAME}}', entryPath: fallback });
358
+ }
359
+ }
360
+ return targets.sort((a, b) => a.binName.localeCompare(b.binName));
200
361
  }
201
362
 
202
- /** CLI 档: 采集 README 类 shell 块的 {{BIN_NAME}} 命令, 对照 --help 核对旗标与子命令 */
363
+ /** CLI 档: 采集 shell 块内全部已发现 CLI 命令, 对照各自 --help 核对旗标与子命令 */
203
364
  export function checkCliExamples(root: string = REPO_ROOT): string[] {
365
+ const targets = discoverCliTargets(root);
366
+ if (targets.length === 0) return [];
367
+
204
368
  const missing: string[] = [];
205
- const help = spawnSync('bun', [join(root, CLI_ENTRY), '--help'], {
206
- cwd: root,
207
- encoding: 'utf8',
208
- });
209
- if (help.status !== 0) {
210
- return [`CLI --help 执行失败 (exit ${String(help.status)}), 无法核对示例`];
211
- }
212
- const helpText = help.stdout ?? '';
369
+ const helpByBin = new Map<string, string>();
370
+ for (const target of targets) {
371
+ const help = spawnSync('bun', [join(root, target.entryPath), '--help'], {
372
+ cwd: root,
373
+ encoding: 'utf8',
374
+ });
375
+ if (help.status !== 0) {
376
+ missing.push(
377
+ `CLI (${target.binName}) --help 执行失败 (exit ${String(help.status)}), 无法核对示例`,
378
+ );
379
+ continue;
380
+ }
381
+ helpByBin.set(target.binName, `${help.stdout ?? ''}\n${help.stderr ?? ''}`);
382
+ }
383
+
384
+ const cliNames = [...helpByBin.keys()];
385
+ if (cliNames.length === 0) return missing;
386
+
213
387
  for (const file of walkFiles(root, ['.md'])) {
214
388
  const content = readFileSync(join(root, file), 'utf8');
215
- for (const command of extractShellCommands(content)) {
389
+ for (const { binName, command } of extractNamedShellCommands(
390
+ content,
391
+ cliNames,
392
+ )) {
393
+ const helpText = helpByBin.get(binName)!;
216
394
  for (const token of extractCommandTokens(command)) {
217
395
  if (!helpText.includes(token)) {
218
396
  missing.push(
219
- `${file} :: 命令 "${command}" 的 ${token} 在 --help 输出中不存在`,
397
+ `${file} :: 命令 "${command}" 的 ${token} 在 ${binName} --help 输出中不存在`,
220
398
  );
221
399
  }
222
400
  }
@@ -245,5 +423,4 @@ function main(): void {
245
423
  process.exitCode = 1;
246
424
  }
247
425
 
248
- // 仅作为入口执行时跑主流程 (被 import 时不执行, 供测试)
249
426
  if (import.meta.main) main();
@@ -91,6 +91,22 @@ describe('相对链接', () => {
91
91
  0,
92
92
  );
93
93
  });
94
+
95
+ test('包根 README 禁止逃出包目录的相对链接 (防 npm 404); 包内链接与 GitHub URL 放行', () => {
96
+ const root = makeRoot({
97
+ 'docs/guide.md': '# Guide\n',
98
+ 'packages/demo/README.md': [
99
+ '[外逃](../../docs/guide.md)',
100
+ '[包内](README.zh-CN.md)',
101
+ '[绝对]({{REPO_URL}}/blob/main/docs/guide.md)',
102
+ ].join('\n'),
103
+ 'packages/demo/README.zh-CN.md': '# 中文\n',
104
+ });
105
+ const issues = findAllIssues(root).filter((f) => f.kind === 'link');
106
+ expect(issues).toHaveLength(1);
107
+ expect(issues[0]!.file).toBe('packages/demo/README.md');
108
+ expect(issues[0]!.reference).toBe('../../docs/guide.md');
109
+ });
94
110
  });
95
111
 
96
112
  describe('§章节引用', () => {
@@ -129,6 +145,17 @@ describe('§章节引用', () => {
129
145
  resolveSectionTarget(line, line.indexOf('§'), 'docs', new Map()),
130
146
  ).toBe('packages/{{NAME}}/docs/designs/api-surface.md');
131
147
  });
148
+
149
+ test('同名文档跨包引用优先命中同包而非回退根 docs/', () => {
150
+ const root = makeRoot({
151
+ 'docs/designs/architecture.md': '## 1. 根架构\n',
152
+ 'packages/pkg-a/docs/designs/architecture.md': '## 2. 包内架构\n',
153
+ 'packages/pkg-a/docs/adrs/0030-x.md': '见 architecture.md §2。\n',
154
+ });
155
+ expect(
156
+ findAllIssues(root).filter((f) => f.kind === 'section'),
157
+ ).toHaveLength(0);
158
+ });
132
159
  });
133
160
 
134
161
  describe('ADR 编号', () => {
@@ -155,4 +182,13 @@ describe('ADR 编号', () => {
155
182
  expect(issues).toHaveLength(1);
156
183
  expect(issues[0]!.reference).toBe('ADR 0022');
157
184
  });
185
+
186
+ test('跨级 ADR 编号重号碰撞直接抓出', () => {
187
+ const root = makeRoot({
188
+ 'packages/x/docs/adrs/0001-dup.md': '# ADR 0001: 重号\n',
189
+ });
190
+ const issues = findAllIssues(root).filter((f) => f.kind === 'adr');
191
+ expect(issues).toHaveLength(1);
192
+ expect(issues[0]!.message).toContain('重号碰撞');
193
+ });
158
194
  });