feat: 增加按目录权重检查 README 的全仓校验器

从 Git 跟踪成员推导目录,根目录始终检查,其余目录权重严格大于 5 时要求 README。
直接子目录和文件各计 1,README 不计数,同名脚本与唯一测试成对计 1。
新增独立命令、针对性测试、算法说明和实际缺口报告,不新增配置文件或批量生成文档。

验证:938 项测试通过,类型与版本检查通过,校验脚本及测试独立类型检查通过。
仓库审计:80 个目录中 28 个需要 README,11 个通过,17 个缺失。
This commit is contained in:
gitea committed 2026-10-30 16:20:01 +08:00
1 parent 01fcebdb1c
commit 3cb087b59d
5 files changed
+337 -1

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
# 2026-10-30 README 权重校验器
## 已确认规则与实际实现
在 `01fcebd` 基线上增加仓库级只读校验器。没有配置文件、目录白名单或额外黑名单,也没有自动创建或重命名 README。
- 根目录始终检查 `README.md`。
- 从 Git 索引的已跟踪成员推导所有父目录,包括中间目录;只统计工作区仍存在的成员。未跟踪内容不计数,已跟踪且后来匹配 `.gitignore` 的内容仍计数。
- 每个直接子目录计 1,每个直接文件计 1,README 文件不计数。后代文件不累计到父目录;父目录未达阈值也会继续检查其子目录。
- 同目录的唯一同名脚本和唯一 `.test.*` 测试文件合计 1,例如 `foo.ts` 与 `foo.test.ts`、`install.sh` 与 `install.test.ts`;独立测试、资源文件及歧义配对仍各计 1。
- 权重严格大于 5 时,要求 `README.{目录名}.md`;权重恰好为 5 不要求。只在根目录或达标目录检查精确大小写、普通文件和非空正文。
- 不跟随符号链接,README 链接不能替代普通文件;Git 子模块作为父目录的一个子目录计数,不进入其他仓库。
## 文件与行为
| 文件 | 实际修改 |
|---|---|
| [check-readme.ts](../../scripts/checks/check-readme.ts) | 权重计算、唯一配对、全仓 Git 目录审计、人类/JSON 输出与退出码 |
| [check-readme.test.ts](../../scripts/checks/check-readme.test.ts) | 使用临时 Git 仓库验证阈值边界、配对、递归、忽略行为、命名、非空、链接、只读性及 CLI |
| [package.json](../../package.json) | 新增独立入口 `bun run check:readme` |
| [README.scripts.md](../../scripts/README.scripts.md) | 说明完整算法、配对格式、调用参数与使用边界 |
`bun run check:readme --json` 返回每个目录的权重、文件配对和预期 README;`--threshold=5` 可覆盖权重阈值,`--root=...` 可指定另一个 Git 工作区。默认定位脚本所属仓库,调用者工作目录不影响结果。退出码为 0(合规)、1(文档不合规)、2(参数/Git/读取异常)。
当前作为独立审计命令,没有接入 CI 门禁,也没有更改原有 `bun run check` 的类型检查语义。目录原有文档不足时返回 1 是真实审计结果,不自动忽略以使结果通过。
## 实际验证与仓库缺口
隔离配置和持久化路径执行全量测试:**938 通过、0 失败,122 文件、4489 次断言**;新增 8 项针对性测试。`bun run check`、`bun run check:version`、校验器及其测试的独立严格 TypeScript 检查、`git diff --check` 均通过。日志位于 `.drafts/readme-check-20261030/`。没有执行企业数据操作、安装或发布。
实际在本仓库审计 **80 个目录**,其中 **28 个要求 README,11 个通过,17 个缺失**。JSON 原始审计记录保存于 Git 忽略目录 `.drafts/readme-check-20261030/audit.json`。
| 目录 | 权重 | 需要补充 |
|---|---:|---|
| `.agents/rules/` | 6 | `README.rules.md` |
| `docs/reviews/` | 8 | `README.reviews.md` |
| `skills/hose-use/references/` | 13 | `README.references.md` |
| `specs/hose-open-api/paths/` | 6 | `README.paths.md` |
| `src/` | 11 | `README.src.md` |
| `src/cli/commands/` | 43 | `README.commands.md` |
| `src/cli/commands/assist-platform/` | 11 | `README.assist-platform.md` |
| `src/cli/commands/bill/` | 13 | `README.bill.md` |
| `src/cli/commands/corps/` | 10 | `README.corps.md` |
| `src/cli/commands/workflow/` | 24 | `README.workflow.md` |
| `src/core/auth/` | 8 | `README.auth.md` |
| `src/core/cache/` | 6 | `README.cache.md` |
| `src/core/http/` | 12 | `README.http.md` |
| `src/domains/platform/workflow/analysis/` | 6 | `README.analysis.md` |
| `src/domains/platform/workflow/nodes/` | 8 | `README.nodes.md` |
| `src/domains/platform/workflow/script/` | 7 | `README.script.md` |
| `src/domains/platform/workflow/watch/` | 8 | `README.watch.md` |
## 与方案的关系及限制
阈值遵循用户最后确认的统一权重规则,替代早期讨论中的“文件数/目录数分别达标”方案;未保留早期的 `readme.config.json`、命名例外表或目录排除清单。
本轮只交付校验器和缺口清单,没有批量补写目录文档。新文件需要先进入 Git 索引,才会影响审计范围和权重;一个已纳入检查的目录中,正在编写的 README 可直接从工作区读取。非空检查不等于内容质量审查,文档是否解释清楚职责和调用方式仍需人工复核。
+1
View File
@@ -20,6 +20,7 @@
"aipro": "bun run src/aipro-cli.ts",
"probe": "bun run src/cli.ts probe",
"check": "tsc --noEmit",
"check:readme": "bun run scripts/checks/check-readme.ts",
"typecheck": "tsc --noEmit",
"test": "bun test",
"bump": "bun run scripts/release/bump-version.ts",
+12 -1
View File
@@ -10,7 +10,7 @@
| [release/](./release/) | 版本更新、一致性检查、发布 Tag 校验及发布流程测试 |
| [generate/](./generate/) | 包装层 OpenAPI 打包、原生下游规范生成、工作流 Schema 导出 |
| [dev/](./dev/) | 本地开发安装覆盖、环境检查与清理规划,及对应测试 |
| [checks/](./checks/) | 文档等仓库级检查;目前为 SDK README 示例编译测试 |
| [checks/](./checks/) | README 覆盖与命名校验、SDK README 示例编译测试 |
| [install.sh](./install.sh) | 公开安装入口,路径保持稳定;安装测试保留在同级 |
对应脚本的测试与脚本放在同一个目录,统一由 `bun test` 发现。生成文件写入 `specs/`,构建输出写入 Git 忽略的 `dist/`。
@@ -24,6 +24,7 @@
| `bun run package:plugin` | [package-plugin.mjs](./build/package-plugin.mjs) | 从当前源码重建插件并生成 `dist/bin/hose-use-plugin-v*.tar.gz`;支持 `--out-dir=...` |
| `bun run scripts/build/verify-binary.ts <产物>` | [verify-binary.ts](./build/verify-binary.ts) | 在临时目录验证 CLI/MCP;插件产物加 `--plugin` |
| `bun run check:version` | [check-version-sync.ts](./release/check-version-sync.ts) | 只读检查版本一致性 |
| `bun run check:readme` | [check-readme.ts](./checks/check-readme.ts) | 只读检查 Git 跟踪目录的 README;支持 `--json`、`--threshold=5` 和 `--root=...` |
| `bun run bump <版本>` | [bump-version.ts](./release/bump-version.ts) | 要求干净的指定发布分支;修改版本源文件并重建规范与插件;`sync:release` 为同一入口 |
| `bun run scripts/release/verify-release.ts <Tag>` | [verify-release.ts](./release/verify-release.ts) | 只读验证发布 Tag、当前提交、主分支祖先关系与版本 |
| `bun run openapi:bundle` | [bundle-openapi.ts](./generate/bundle-openapi.ts) | `specs/hose-open-api/` YAML → `specs/openapi.json` |
@@ -49,3 +50,13 @@
`workflow-schema.json` 的 `schemas` 分别保存 WorkflowDetail、WorkflowTask 和 Workflow 的独立 JSON Schema,描述 Zod 解析完成后的输出,不是服务端原始输入;每份 Schema 的递归引用相对于该份 Schema 解析。带默认值的输出字段保持必填,数字转换后仍为 number。
`alarm` 可从 JSON 字符串归一化为告警对象,也可为 null 或缺省。导出视图显式使用同一个 `WorkflowAlarmSchema` 描述对象输出;不会尝试把字符串解析函数转换为 JSON Schema,也不会改动域层的输入兼容和解析行为。新增其他无法表示的转换时仍会报错,避免默默丢失约束。
## README 校验规则
- 从 Git 索引中的已跟踪文件推导目录;只统计工作区仍存在的成员。不纳入未跟踪文件或空目录,也不自行扫描依赖和本地草稿。新文件需先 `git add` 才会影响目录权重;已跟踪的文件后来匹配 `.gitignore`,仍然计入。
- 根目录始终要求 `README.md`;其他目录的权重**严格大于 5**时,要求 `README.{当前目录名}.md`。默认阈值为 5,可通过 `--threshold` 覆盖;没有配置文件、目录白名单或额外黑名单。
- 每个直接子目录计 1,每个直接文件计 1,README 文件不计权重。后代内容不累计到父目录,未达阈值的父目录不会阻止对子目录的检查。
- 同目录、同名的脚本与唯一的 `名称.test.*` 测试合计 1;例如 `foo.ts` + `foo.test.ts`、`build.mjs` + `build.test.ts`、`install.sh` + `install.test.ts`。支持 TS/JS(含 JSX、TSX、MJS、CJS)、Shell、Python、PowerShell 源文件;测试采用 `.test.ts/js/tsx/jsx/mjs/cjs`。只有唯一源文件和唯一测试能配对,独立测试、资源文件或歧义配对各自计数;不跨目录合并。
- 只在要求 README 的目录检查命名、精确大小写、普通文件与非空内容;已有 README 不会被自动创建、改名或修改。符号链接按文件计但不跟随,README 符号链接不合规;子模块只作为父目录的一个子目录计数,不进入另一个仓库。
- 默认定位脚本所属仓库,从其他工作目录调用结果相同;`--root` 可指定其他 Git 工作区(指向其子目录时会定位到该仓库根目录)。JSON 结果包含每个目录的权重、文件配对明细及预期 README,便于复查。
- 退出码:`0` 全部合规,`1` 存在缺失、错名、空文档或无效文档,`2` 为参数、Git 或读取错误。当前作为独立审计入口,不接入 CI 门禁,也不修改通用类型检查命令。
+133
View File
@@ -0,0 +1,133 @@
import { afterEach, expect, test } from "bun:test";
import { execFileSync, spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { checkReadmes, fileUnits } from "./check-readme.js";
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
function fixture(readme = true) {
const root = mkdtempSync(join(tmpdir(), "hose readme 检查 "));
roots.push(root);
const git = (...args: string[]) => execFileSync("git", ["-C", root, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
git("init", "--quiet");
const write = (path: string, content = "fixture", tracked = true) => {
const target = join(root, path);
mkdirSync(dirname(target), { recursive: true });
writeFileSync(target, content);
if (tracked) git("add", "--", path);
};
if (readme) write("README.md", "# Fixture");
const files = (dir: string, count: number) => { for (let i = 0; i < count; i++) write(`${dir}/file-${i}.ts`); };
const cli = (...args: string[]) => spawnSync(process.execPath, [resolve(import.meta.dir, "check-readme.ts"), `--root=${root}`, ...args], { encoding: "utf8" });
return { root, git, write, files, cli, result: (path: string) => checkReadmes(root).results.find(item => item.directory === path)! };
}
test("脚本与唯一同名 .test.* 合并,独立测试和资源文件不误配", () => {
expect(fileUnits(["foo.ts", "foo.test.ts", "install.sh", "install.test.ts", "build.mjs", "build.test.ts"])).toEqual([
["build.mjs", "build.test.ts"], ["foo.ts", "foo.test.ts"], ["install.sh", "install.test.ts"],
]);
expect(fileUnits(["foo.json", "foo.test.ts", "bar.test.ts", "foo.spec.ts"])).toHaveLength(4);
expect(fileUnits(["foo.ts", "foo.js", "foo.test.ts"])).toHaveLength(3);
expect(fileUnits(["README.md", "README.foo.md", "readme.markdown", "README", "foo.ts"])).toEqual([["foo.ts"]]);
});
test("根目录不受阈值影响,5 不要求,6 要求;测试对只算 1", () => {
const f = fixture(false);
expect(checkReadmes(f.root).results[0]?.status).toBe("missing");
f.write("README.md", "# Root");
f.files("src", 4);
f.write("src/example.ts");
f.write("src/example.test.ts");
expect(f.result("src")).toMatchObject({ weight: 5, required: false, status: "not-required" });
f.write("src/sixth.ts");
expect(f.result("src")).toMatchObject({ weight: 6, required: true, status: "missing", expectedReadme: "README.src.md" });
f.write("src/README.src.md", "# Source");
expect(f.result("src")).toMatchObject({ weight: 6, status: "ok" });
});
test("直接子目录各计 1,不累计后代文件,低权重父目录不阻止向下检查", () => {
const f = fixture();
f.files("parent/child", 8);
f.write("parent/other/example.ts");
expect(f.result("parent")).toMatchObject({ weight: 2, directoryWeight: 2, required: false });
expect(f.result("parent/child")).toMatchObject({ weight: 8, status: "missing" });
f.files("mixed", 4);
f.write("mixed/child/a.ts");
f.write("mixed/other/b.ts");
expect(f.result("mixed")).toMatchObject({ weight: 6, directoryWeight: 2, status: "missing" });
});
test("配对只在同一目录内进行", () => {
const f = fixture();
f.write("a/foo.ts");
f.write("b/foo.test.ts");
expect(f.result("a").fileUnits).toEqual([["foo.ts"]]);
expect(f.result("b").fileUnits).toEqual([["foo.test.ts"]]);
});
test("只检查 Git 跟踪成员;未跟踪、嵌套忽略内容不计数,已跟踪的忽略项仍计数", () => {
const f = fixture();
f.write(".gitignore", "ignored/\n");
f.write("src/.gitignore", "local/\n");
f.write("ignored/a.ts", "ignored", false);
f.write("src/local/a.ts", "ignored", false);
f.write("untracked/a.ts", "untracked", false);
f.files("src", 4);
expect(f.result("src").weight).toBe(5);
expect(checkReadmes(f.root).results.map(item => item.directory)).toEqual([".", "src"]);
f.write("ignored/tracked.ts", "tracked", false);
f.git("add", "-f", "--", "ignored/tracked.ts");
expect(f.result("ignored").weight).toBe(1);
});
test("校验真实大小写、错名、空文档和符号链接;检查不写文件", () => {
const f = fixture();
f.files("src", 6);
f.write("src/README.md", "# Wrong name");
expect(f.result("src").status).toBe("misnamed");
rmSync(join(f.root, "src/README.md"));
f.write("src/readme.src.md", "# Wrong case");
expect(f.result("src").status).toBe("misnamed");
rmSync(join(f.root, "src/readme.src.md"));
f.write("src/README.src.md", " \n\t ");
expect(f.result("src").status).toBe("empty");
rmSync(join(f.root, "src/README.src.md"));
symlinkSync(join(f.root, "README.md"), join(f.root, "src/README.src.md"));
expect(f.result("src").status).toBe("invalid-file");
const before = f.git("status", "--porcelain");
checkReadmes(f.root);
expect(f.git("status", "--porcelain")).toBe(before);
});
test("符号链接目录不展开,工作区中已删除的文件不计权重", () => {
const f = fixture();
f.files("src", 6);
rmSync(join(f.root, "src/file-0.ts"));
expect(f.result("src").weight).toBe(5);
mkdirSync(join(f.root, "outside"));
writeFileSync(join(f.root, "outside/secret.txt"), "fixture");
symlinkSync(join(f.root, "outside"), join(f.root, "link"));
f.git("add", "--", "link");
expect(checkReadmes(f.root).results.map(item => item.directory)).not.toContain("link");
});
test("CLI 支持 JSON、阈值与稳定退出码,非 Git 路径或无效参数返回 2", () => {
const f = fixture();
expect(f.cli().status).toBe(0);
f.files("src", 6);
const failed = f.cli("--json");
expect(failed.status).toBe(1);
expect(JSON.parse(failed.stdout)).toMatchObject({ threshold: 5, failed: 1 });
expect(f.cli("--threshold", "6").status).toBe(0);
expect(f.cli("--threshold=5").status).toBe(1);
for (const arg of ["--threshold=-1", "--threshold=1.5", "--threshold=9007199254740992", "--unknown", "--threshold"]) {
expect(f.cli("--json", arg).status).toBe(2);
}
const dir = mkdtempSync(join(tmpdir(), "hose-non-git-")); roots.push(dir);
const invalid = f.cli("--json", `--root=${dir}`);
expect(invalid.status).toBe(2);
expect(JSON.parse(invalid.stdout).error).toBeString();
expect(f.cli("--help").status).toBe(0);
});
+134
View File
@@ -0,0 +1,134 @@
import { execFileSync } from "node:child_process";
import { lstatSync, readFileSync, readdirSync } from "node:fs";
import { posix, resolve } from "node:path";
const isReadme = (name: string) => /^readme(?:\..*)?$/i.test(name);
const scriptPattern = /\.(?:[cm]?js|jsx|tsx?|sh|bash|py|ps1)$/;
const testPattern = /^(.*)\.test\.(?:[cm]?js|jsx|tsx?)$/;
/** 只合并同目录内唯一的同名脚本/测试对,资源文件和独立测试各计 1。 */
export function fileUnits(names: string[]): string[][] {
const files = [...new Set(names)].filter(name => !isReadme(name)).sort();
const sources = new Map<string, string[]>();
const tests = new Map<string, string[]>();
for (const name of files) {
const test = name.match(testPattern);
const key = test?.[1] ?? (scriptPattern.test(name) ? name.replace(scriptPattern, "") : undefined);
if (key === undefined) continue;
const target = test ? tests : sources;
target.set(key, [...(target.get(key) ?? []), name]);
}
const paired = new Map<string, string>();
for (const [stem, source] of sources) {
const test = tests.get(stem);
if (source.length === 1 && test?.length === 1) paired.set(source[0]!, test[0]!);
}
const consumed = new Set(paired.values());
return files.filter(name => !consumed.has(name)).map(name => paired.has(name) ? [name, paired.get(name)!] : [name]);
}
export interface DirectoryResult {
directory: string;
expectedReadme: string;
fileUnits: string[][];
directoryWeight: number;
weight: number;
required: boolean;
status: "ok" | "not-required" | "missing" | "misnamed" | "empty" | "invalid-file";
foundReadmes: string[];
}
export function checkReadmes(directory: string, threshold = 5) {
if (!Number.isSafeInteger(threshold) || threshold < 0) throw new Error("threshold 必须为非负安全整数");
const git = (args: string[]) => execFileSync("git", ["-C", resolve(directory), ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
const root = git(["rev-parse", "--show-toplevel"]).trim();
const tracked = execFileSync("git", ["-C", root, "ls-files", "--cached", "-z"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
const tree = new Map<string, { files: Set<string>; directories: Set<string> }>();
const ensure = (path: string) => {
if (!tree.has(path)) tree.set(path, { files: new Set(), directories: new Set() });
return tree.get(path)!;
};
ensure(".");
for (const path of new Set(tracked.split("\0").filter(Boolean))) {
let stat;
try {
stat = lstatSync(resolve(root, path));
} catch (error) {
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
throw error;
}
let parent = posix.dirname(path);
// 子模块只计为直接子目录;不进入另一个 Git 仓库。符号链接按文件计,不跟随。
if (stat.isDirectory()) ensure(parent).directories.add(posix.basename(path));
else ensure(parent).files.add(posix.basename(path));
while (parent !== ".") {
const ancestor = posix.dirname(parent);
ensure(ancestor).directories.add(posix.basename(parent));
parent = ancestor;
}
}
const results: DirectoryResult[] = [...tree.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([path, members]) => {
const units = fileUnits([...members.files]);
const weight = units.length + members.directories.size;
const required = path === "." || weight > threshold;
const expectedReadme = path === "." ? "README.md" : `README.${posix.basename(path)}.md`;
const result: DirectoryResult = { directory: path, expectedReadme, fileUnits: units, directoryWeight: members.directories.size, weight, required, status: "not-required", foundReadmes: [] };
if (!required) return result;
const absolute = resolve(root, path);
// 必须比较目录条目的真实大小写,不能依赖 macOS 的大小写不敏感路径查询。
result.foundReadmes = readdirSync(absolute).filter(isReadme).sort();
if (!result.foundReadmes.includes(expectedReadme)) {
result.status = result.foundReadmes.length ? "misnamed" : "missing";
} else if (!lstatSync(resolve(absolute, expectedReadme)).isFile()) {
result.status = "invalid-file";
} else {
result.status = readFileSync(resolve(absolute, expectedReadme), "utf8").trim() ? "ok" : "empty";
}
return result;
});
const required = results.filter(result => result.required);
return { root, threshold, directories: results.length, required: required.length, failed: required.filter(result => result.status !== "ok").length, results };
}
export function main(args: string[]): number {
const json = args.includes("--json");
try {
let root = resolve(import.meta.dir, "../..");
let threshold = 5;
for (let i = 0; i < args.length; i++) {
const arg = args[i]!;
if (arg === "--json") continue;
if (arg === "--help" || arg === "-h") {
console.log("用法:bun run check:readme [--threshold=5] [--root=<Git 仓库路径>] [--json]\n根目录始终检查;其余目录的直接文件单位 + 直接子目录数 > threshold 时要求 README.{目录名}.md。\n只统计 Git 已跟踪且工作区仍存在的成员;同名脚本与唯一的 .test.* 测试文件合计 1。只读检查。");
return 0;
}
const match = arg.match(/^--(threshold|root)(?:=(.*))?$/);
if (!match) throw new Error(`未知参数:${arg}`);
const value = match[2] ?? args[++i];
if (!value || value.startsWith("--")) throw new Error(`参数缺少值:${arg}`);
if (match[1] === "root") root = resolve(value);
else {
if (!/^\d+$/.test(value)) throw new Error("threshold 必须为非负安全整数");
threshold = Number(value);
}
}
const report = checkReadmes(root, threshold);
if (json) console.log(JSON.stringify(report, null, 2));
else {
const labels = { missing: "缺失", misnamed: "错名", empty: "空文档", "invalid-file": "不是普通文件", ok: "通过", "not-required": "未达阈值" };
for (const result of report.results.filter(item => item.required && item.status !== "ok")) {
console.log(`${labels[result.status]} ${result.directory}/ 权重 ${result.weight},预期 ${result.expectedReadme}${result.foundReadmes.length ? `,发现 ${result.foundReadmes.join("、")}` : ""}`);
}
console.log(`检查 ${report.directories} 个目录;要求 README ${report.required} 个,通过 ${report.required - report.failed} 个,失败 ${report.failed} 个;其余 ${report.directories - report.required} 个未达阈值。`);
}
return report.failed ? 1 : 0;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
if (json) console.log(JSON.stringify({ error: message }));
else console.error(`README 校验失败:${message}`);
return 2;
}
}
if (import.meta.main) process.exitCode = main(process.argv.slice(2));