chore: 收敛模板证据哈希并接入提交钩子

This commit is contained in:
que01 committed 2026-10-21 14:41:23 +08:00
1 parent ec0cf78d69
commit 669d4a7de6
7 files changed
+146 -15

No files matched your search

+35 -12
View File
@@ -431,32 +431,55 @@ function walkRepositoryFiles(root, directory = root) {
return files;
}
export function sourceTreeHash(root) {
const EVIDENCE_SCOPE_IGNORED_PREFIXES = [".codex-tasks/", ".gitea/", "deploy/", "scripts/deploy/"];
const EVIDENCE_SCOPE_IGNORED_EXTENSIONS = [".md", ".mdx"];
const EVIDENCE_SCOPE_ALWAYS_INCLUDED = ["docs/template-completion-rules.md"];
// 证据哈希只覆盖会影响模板交付的源码:文档、CI 配置和部署脚本的改动不使证据失效。
export function isEvidenceSourcePath(relativePath) {
const normalized = relativePath.split(path.sep).join("/");
if (EVIDENCE_SCOPE_ALWAYS_INCLUDED.includes(normalized)) return true;
if (EVIDENCE_SCOPE_IGNORED_PREFIXES.some((prefix) => normalized.startsWith(prefix))) return false;
return !EVIDENCE_SCOPE_IGNORED_EXTENSIONS.some((extension) => normalized.endsWith(extension));
}
export function sourceTreeHash(root, options = {}) {
const rootPath = path.resolve(root);
const { staged = false } = options;
let files;
let readContent;
if (fs.existsSync(path.join(rootPath, ".git"))) {
const output = execFileSync(
"git",
["ls-files", "-z", "--cached", "--others", "--exclude-standard"],
{ cwd: rootPath, maxBuffer: 64 * 1024 * 1024 },
);
// 只统计已跟踪文件:未纳入版本控制的文件不属于任何一次可复现的交付。
// staged 模式从 Git index 读取内容,供 pre-commit 使用,避免部分暂存时把
// 工作区里的未提交改动算进提交对应的证据哈希。
const output = execFileSync("git", ["ls-files", "-z", "--cached"], {
cwd: rootPath,
maxBuffer: 64 * 1024 * 1024,
});
files = output
.toString("utf8")
.split("\0")
.filter((file) => file && !file.startsWith(".codex-tasks/"))
.map((file) => path.join(rootPath, file))
.filter((file) => fs.existsSync(file) && fs.statSync(file).isFile());
.filter((file) => file && isEvidenceSourcePath(file))
.map((file) => path.join(rootPath, file));
readContent = staged
? (file) =>
execFileSync("git", ["show", ":" + path.relative(rootPath, file)], {
cwd: rootPath,
maxBuffer: 64 * 1024 * 1024,
})
: (file) => fs.readFileSync(file);
} else {
files = walkRepositoryFiles(rootPath).filter(
(file) => !path.relative(rootPath, file).startsWith(".codex-tasks/"),
files = walkRepositoryFiles(rootPath).filter((file) =>
isEvidenceSourcePath(path.relative(rootPath, file)),
);
readContent = (file) => fs.readFileSync(file);
}
files.sort();
const hash = crypto.createHash("sha256");
for (const file of files) {
hash.update(path.relative(rootPath, file));
hash.update("\0");
hash.update(fs.readFileSync(file));
hash.update(readContent(file));
hash.update("\0");
}
return hash.digest("hex");
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env node
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { sourceTreeHash } from "./lib/template-doctor.mjs";
const REGISTRY = path.join(
".codex-tasks",
"template-audit-execution",
"raw",
"completion-evidence.json",
);
const shouldStage = process.argv.includes("--stage");
if (!fs.existsSync(REGISTRY)) {
console.log(`template evidence: ${REGISTRY} 不存在,跳过`);
process.exit(0);
}
const registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
const nextHash = sourceTreeHash(process.cwd(), { staged: shouldStage });
if (registry.sourceTreeHash === nextHash) {
console.log("template evidence: 源码哈希已是最新");
process.exit(0);
}
registry.sourceTreeHash = nextHash;
registry.generatedAt = new Date().toISOString();
fs.writeFileSync(REGISTRY, JSON.stringify(registry, null, 2) + "\n");
console.log(`template evidence: sourceTreeHash 更新为 ${nextHash}`);
if (shouldStage) execFileSync("git", ["add", "-f", REGISTRY], { stdio: "inherit" });
+62
View File
@@ -9,6 +9,7 @@ import {
applyCompletionEvidence,
applyManualReview,
diagnoseTemplate,
isEvidenceSourcePath,
sourceTreeHash,
} from "../lib/template-doctor.mjs";
@@ -78,6 +79,67 @@ test("CLI 自动发现全部模板,问题退出 1,未知模板退出 2", ()
assert.equal(missing.status, 2);
});
test("证据哈希范围排除文档、CI 与部署脚本,保留模板交付相关源码", () => {
assert.equal(isEvidenceSourcePath("docs/ci.md"), false);
assert.equal(isEvidenceSourcePath("PROJECT_STATUS.md"), false);
assert.equal(isEvidenceSourcePath(".gitea/workflows/ci.yml"), false);
assert.equal(isEvidenceSourcePath("deploy/install-release.mjs"), false);
assert.equal(isEvidenceSourcePath("scripts/deploy/status.mjs"), false);
assert.equal(isEvidenceSourcePath(".codex-tasks/template-audit-execution/raw/a.json"), false);
assert.equal(isEvidenceSourcePath("docs/template-completion-rules.md"), true);
assert.equal(isEvidenceSourcePath("apps/api/src/main.ts"), true);
assert.equal(isEvidenceSourcePath("packages/template-linjing-editorial/template.json"), true);
});
test("文档改动不改变证据哈希,源码改动仍然改变", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-scope-"));
try {
fs.mkdirSync(path.join(root, "docs"), { recursive: true });
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 1;\n");
const baseline = sourceTreeHash(root);
fs.writeFileSync(path.join(root, "PROJECT_STATUS.md"), "状态更新\n");
fs.writeFileSync(path.join(root, "docs", "ci.md"), "文档更新\n");
assert.equal(sourceTreeHash(root), baseline);
fs.writeFileSync(path.join(root, "docs", "template-completion-rules.md"), "规则更新\n");
assert.notEqual(sourceTreeHash(root), baseline);
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 2;\n");
assert.notEqual(sourceTreeHash(root), baseline);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("pre-commit 证据哈希按暂存区计算,不受部分暂存和未跟踪文件影响", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-staged-"));
const git = (...args) => {
const result = spawnSync("git", args, { cwd: root, encoding: "utf8" });
assert.equal(result.status, 0, result.stderr);
return result.stdout;
};
try {
git("init", "-q");
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 1;\n");
git("add", "app.ts");
const stagedBaseline = sourceTreeHash(root, { staged: true });
fs.writeFileSync(path.join(root, "app.ts"), "export const value = 2;\n");
fs.writeFileSync(path.join(root, "untracked.ts"), "export const draft = true;\n");
const stagedWithUnstagedEdits = sourceTreeHash(root, { staged: true });
assert.equal(stagedWithUnstagedEdits, stagedBaseline);
assert.notEqual(sourceTreeHash(root), stagedBaseline);
git("-c", "user.name=test", "-c", "user.email=test@example.com", "commit", "-qm", "one");
git("checkout", "--", "app.ts");
assert.equal(sourceTreeHash(root), stagedBaseline);
assert.equal(sourceTreeHash(root, { staged: true }), stagedBaseline);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
test("完成证据登记必须覆盖全部要求并校验产物哈希", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "template-doctor-evidence-"));
const artifactPath = path.join(root, "integration.log");