Compare commits

...
4 Commits
Author SHA1 Message Date
que01 1001c43af6 chore: 提供可复现的 CI runner 安装脚本
CI / Production build (push) Has been cancelled
CI / API integration (push) Has been cancelled
CI / Static checks (push) Has been cancelled
2026-10-21 14:41:47 +08:00
que01 121148f6cf fix: 修正 deploy:status 远程脚本执行并检查 runner 2026-10-21 14:41:39 +08:00
que01 a08a2f0f98 ci: 让 main 的必需检查始终上报 2026-10-21 14:41:31 +08:00
que01 669d4a7de6 chore: 收敛模板证据哈希并接入提交钩子 2026-10-21 14:41:23 +08:00
12 changed files with 395 additions and 36 deletions

No files matched your search

@@ -1,7 +1,7 @@
{
"schemaVersion": 1,
"scope": "模板完成证据登记,保留命令、日志与产物哈希",
"generatedAt": "2026-10-21T06:14:04.698Z",
"generatedAt": "2026-10-21T06:41:20.085Z",
"templates": {
"acheng-campus-food": {
"real-manifest-interaction": {
@@ -256,5 +256,5 @@
}
}
},
"sourceTreeHash": "e25ff96a374cec651bc82f2b142f662039831c34104005579fec55d921c9f7f7"
"sourceTreeHash": "1b979d8c64ea424e32b7b20a96a2d97c692cc37099f8a9e41d3b45178655a410"
}
+6
View File
@@ -3,7 +3,13 @@ name: CI
on:
push:
branches: [main]
# 纯文档提交不消耗 2 核 runner;需要状态时用 workflow_dispatch 手动触发。
paths-ignore:
- "**.md"
# PR 不设置 paths-ignore:branch protection 的 required checks 必须始终上报,
# 否则纯文档 PR 会永远等不到状态检查而无法合并。
pull_request:
workflow_dispatch:
concurrency:
group: ci-${{ github.ref }}
+6
View File
@@ -0,0 +1,6 @@
#!/bin/sh
# 提交前让模板完成证据的源码哈希跟随当前工作树,避免额外的 chore 提交。
set -e
[ -f scripts/template-evidence-refresh.mjs ] || exit 0
command -v node >/dev/null 2>&1 || exit 0
node scripts/template-evidence-refresh.mjs --stage
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
# 在 CI 主机上安装并注册 Gitea Actions runner(Ubuntu/arm64 或 amd64)。
#
# 用法(在 runner 主机上、仓库之外执行):
# GITEA_URL=https://git.example.com RUNNER_TOKEN=xxx ./deploy/runner/install-runner.sh
# DRY_RUN=1 ... ./deploy/runner/install-runner.sh # 只打印将执行的命令
#
# 需要的环境变量:
# GITEA_URL Gitea 站点地址
# RUNNER_TOKEN 仓库 Settings → Actions → Runners 里生成的注册 token
# 可选:
# RUNNER_NAME runner 名称,默认取 hostname
# RUNNER_LABELS 默认 ubuntu-latest,oracle-arm
# RUNNER_VERSION 默认 5.2.0
# RUNNER_ROOT 默认 $HOME/gitea-runner
# CACHE_PORT 默认 8193
# RUNNER_CACHE_HOST 默认 172.17.0.1(Docker 默认 bridge 网关)
set -euo pipefail
GITEA_URL=${GITEA_URL:?需要设置 GITEA_URL}
RUNNER_TOKEN=${RUNNER_TOKEN:?需要设置 RUNNER_TOKEN}
RUNNER_NAME=${RUNNER_NAME:-$(hostname -s)}
RUNNER_LABELS=${RUNNER_LABELS:-ubuntu-latest,oracle-arm}
RUNNER_VERSION=${RUNNER_VERSION:-5.2.0}
RUNNER_ROOT=${RUNNER_ROOT:-$HOME/gitea-runner}
CACHE_PORT=${CACHE_PORT:-8193}
RUNNER_CACHE_HOST=${RUNNER_CACHE_HOST:-172.17.0.1}
CACHE_DIR=${CACHE_DIR:-$RUNNER_ROOT/cache-data}
DRY_RUN=${DRY_RUN:-0}
command -v docker >/dev/null 2>&1 || { echo "缺少 docker,请先安装并启动 Docker" >&2; exit 1; }
command -v systemctl >/dev/null 2>&1 || { echo "缺少 systemd,当前脚本只支持 systemd 主机" >&2; exit 1; }
case "$(uname -m)" in
aarch64 | arm64) ARCH=arm64 ;;
x86_64 | amd64) ARCH=amd64 ;;
*) echo "不支持的架构: $(uname -m)" >&2; exit 1 ;;
esac
run() {
if [ "$DRY_RUN" = "1" ]; then
echo "+ ${*//$RUNNER_TOKEN/***}"
else
"$@"
fi
}
archive="gitea-runner-${RUNNER_VERSION}-linux-${ARCH}.xz"
base="https://dl.gitea.com/gitea-runner/${RUNNER_VERSION}"
run mkdir -p "$RUNNER_ROOT" "$CACHE_DIR"
if [ ! -x "$RUNNER_ROOT/gitea-runner-${RUNNER_VERSION}-linux-${ARCH}" ]; then
run curl -fsSL -o "$RUNNER_ROOT/$archive" "$base/$archive"
run curl -fsSL -o "$RUNNER_ROOT/$archive.sha256" "$base/$archive.sha256"
run env -C "$RUNNER_ROOT" sha256sum -c "$archive.sha256"
run xz -d -f "$RUNNER_ROOT/$archive"
fi
run ln -sf "gitea-runner-${RUNNER_VERSION}-linux-${ARCH}" "$RUNNER_ROOT/gitea-runner"
if [ ! -f "$RUNNER_ROOT/.runner" ]; then
run env -C "$RUNNER_ROOT" ./gitea-runner register \
--no-interactive \
--instance "$GITEA_URL" \
--token "$RUNNER_TOKEN" \
--name "$RUNNER_NAME" \
--labels "$RUNNER_LABELS"
run chmod 600 "$RUNNER_ROOT/.runner"
fi
run tee "$RUNNER_ROOT/config.yaml" >/dev/null <<CONFIG
log:
level: debug
runner:
file: .runner
capacity: 1
timeout: 2h
fetch_timeout: 10s
fetch_interval: 2s
labels:
$(printf '%s\n' "$RUNNER_LABELS" | tr ',' '\n' | sed 's|^\(.*\)$| - "\1:docker://node:24-bookworm"|')
cache:
enabled: true
dir: ${CACHE_DIR}
host: ${RUNNER_CACHE_HOST}
port: ${CACHE_PORT}
container:
options: "--cpus=1.5 --memory=4g"
valid_volumes: []
docker_host: "-"
CONFIG
run mkdir -p "$HOME/.config/systemd/user"
run tee "$HOME/.config/systemd/user/gitea-runner.service" >/dev/null <<UNIT
[Unit]
Description=Gitea Actions Runner (${RUNNER_NAME})
After=network-online.target
Wants=network-online.target
[Service]
WorkingDirectory=${RUNNER_ROOT}
ExecStart=${RUNNER_ROOT}/gitea-runner daemon -c ${RUNNER_ROOT}/config.yaml
Restart=always
RestartSec=5
[Install]
WantedBy=default.target
UNIT
# 用户级 systemd 服务默认在最后一个会话退出后停止;开启 linger 才能在重启后自动拉起 runner。
if command -v loginctl >/dev/null 2>&1; then
run sudo loginctl enable-linger "$USER"
fi
run systemctl --user daemon-reload
run systemctl --user enable --now gitea-runner.service
# 任务容器经 Docker bridge 访问 runner 内置 cache server,ufw 默认 INPUT DROP 会拦截。
# Gitea Actions 会给每个 job 建独立 bridge(实测 192.168.x),因此三个私网段都要放行。
if command -v ufw >/dev/null 2>&1; then
for cidr in 172.16.0.0/12 192.168.0.0/16 10.0.0.0/8; do
run sudo ufw allow from "$cidr" to any port "$CACHE_PORT" proto tcp comment "gitea actions cache"
done
fi
echo
echo "runner 已安装:$RUNNER_ROOT"
echo "检查状态:systemctl --user status gitea-runner.service"
echo "检查 linger:loginctl show-user \"$USER\" -p Linger"
echo "检查日志:journalctl --user -u gitea-runner -n 100 --no-pager"
+31 -1
View File
@@ -4,6 +4,8 @@
## Runner
安装与运维步骤见 `docs/runner-setup.md`(`deploy/runner/install-runner.sh` 可复现整套配置)。
- 程序:`gitea-runner` v5.2.0(linux/arm64),位于 `/home/ubuntu/gitea-runner`
- 服务:systemd user unit `gitea-runner.service`
- 标签:`ubuntu-latest`、`oracle-arm`
@@ -67,7 +69,7 @@ Runner 日志级别保持 `debug`:`info` 级别不会记录各 step 的 `Succe
该轮次全部告警均来自缓存后端不可达(`ETIMEDOUT`),已按上一节修复。
修复后的对照数据(run `22`,commit `261a33a`):
修复后的对照数据(run `22`,commit `261a33a`;run `23` 的 static 为 5.7 分钟):
| job | 修复前耗时 | 修复后耗时 |
| ---------------- | ---------- | --------------------------------------------------------- |
@@ -76,3 +78,31 @@ Runner 日志级别保持 `debug`:`info` 级别不会记录各 step 的 `Succe
| API integration | 9.7 min | 3.8 min |
缓存内容为 pnpm store,首次落盘约 268 MB,位于 `/home/ubuntu/gitea-runner/cache-data`。
## 触发范围
- `push` 到 `main` 时忽略纯文档改动(`**.md`),避免 2 核主机为文档提交跑完整 CI。
- `pull_request` 不设置 `paths-ignore`。branch protection 要求的 status check 必须每次都上报,否则纯文档 PR 会一直停在「等待检查」而无法合并。
- 需要给纯文档提交补一次状态时,用 `workflow_dispatch` 手动触发。
模板完成证据的源码哈希已同步收敛,文档、CI 配置和部署脚本改动不再使证据失效;模板、renderer、Admin 模板编辑器、品牌内容 API 等会影响交付的源码改动仍会更新哈希。`pre-commit` 会按 Git index 重算并暂存证据,不再需要单独的 `chore: 更新模板完成证据源码哈希` 提交。注意:`pre-commit` 只在该仓库执行过 `pnpm install`(触发 `prepare` 设置 `core.hooksPath`)后生效。
## 分支保护
`main` 由 Gitea branch protection 保护,规则为:
- 禁止直接 push 和 force push,所有改动走分支 + Pull Request。
- 必须通过 `CI / *` 状态检查(覆盖 `Static checks`、`Production build`、`API integration` 及其后续新增 job)。
- `required_approvals = 0`:当前是单人维护,不强制他人审批,但 CI 必须全绿。
仓库管理员如需紧急放行,应临时调整保护规则并在事后恢复,不要长期用管理员权限绕过检查。规则可通过 `PATCH /api/v1/repos/que01/persionalBrand/branch_protections/main` 复现:
```json
{
"enable_push": false,
"enable_force_push": false,
"enable_status_check": true,
"status_check_contexts": ["CI / *"],
"required_approvals": 0
}
```
+60
View File
@@ -0,0 +1,60 @@
# CI Runner 安装与运维
CI 跑在自托管 Gitea Actions runner 上(当前主机 `oracle_arm`,与生产 API 共用 2 核)。本文件记录可复现的安装步骤,避免换机器时重新摸索。
## 一次性准备
1. 在 Gitea 仓库 Settings → Actions → Runners 里创建注册 token(只对单个仓库或整个实例生效)。
2. 目标主机需要:Docker、`curl`、`xz`、`ufw`、systemd、可用 sudo、Node 不需要(任务容器自带)。
## 安装
把仓库里的脚本拷到目标主机后执行:
```bash
GITEA_URL=https://git.example.com \
RUNNER_TOKEN=<注册 token> \
RUNNER_NAME=oracle-arm \
RUNNER_LABELS=ubuntu-latest,oracle-arm \
./install-runner.sh
```
加 `DRY_RUN=1` 可先看它准备执行哪些命令(token 会被替换成 `***`)。
脚本做的事:
1. 按架构下载 `gitea-runner-<version>-linux-<arch>`,校验 `.sha256` 后解压到 `~/gitea-runner`。
2. 用 `--no-interactive` 注册,写出 `.runner`(已存在则跳过,可重复执行)。
3. 生成 `config.yaml`:单并发、`docker://node:24-bookworm` 标签、内置 cache server 监听 `172.17.0.1:8193`、任务容器限制 `--cpus=1.5 --memory=4g`。
4. 装 systemd user unit `gitea-runner.service`,执行 `loginctl enable-linger` 后 `enable --now`。
5. 放行任务容器到 cache 端口的 ufw 规则。
## 为什么 ufw 要放行三个网段
任务容器访问宿主机的 cache server 走 Docker bridge,`ufw` 默认 `INPUT DROP` 会直接丢包。Gitea Actions 每个 job 会新建独立 bridge(实测 `192.168.x`),默认 `docker0` 又是 `172.17.x`,所以需要 `172.16.0.0/12`、`192.168.0.0/16`、`10.0.0.0/8` 三条规则。只放行其中一条的后果是缓存恢复/保存各空等数分钟并最终超时。
## 日常检查
```bash
systemctl --user status gitea-runner.service
journalctl --user -u gitea-runner -n 100 --no-pager
du -sh ~/gitea-runner/cache-data
```
仓库侧 `pnpm deploy:status` 也会打印 `ci-runner=` 一行。
## 排障
| 现象 | 先查什么 |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| push 后 CI 一直 queued 不启动 | runner 服务是否 active;Gitea 仓库 Runners 页面是否显示 online |
| 日志出现 `Failed to GetCacheEntryDownloadURL ... ETIMEDOUT` | ufw 是否放行三个私网段;`docker exec <job-container> node -e 'fetch("http://172.17.0.1:8193/")'` 应返回 404 |
| 一轮 CI 突然变慢 | 缓存是否命中;宿主机负载与磁盘余量 |
| 生产 API 变慢 | CI 与生产共用主机,检查是否在跑 build/api job;必要时暂停 runner |
| 重启后 runner 没起来 | `loginctl show-user "$USER" -p Linger` 应为 `Linger=yes`;否则执行 `sudo loginctl enable-linger "$USER"` |
## 约束
- `capacity: 1`:不要提高并发,2 核主机上并发只会让生产和 CI 一起变慢。
- 日志级别保持 `debug`:`info` 级别不记录各 step 的结果行,排障时等于没有日志。
- 浏览器回归不进 CI(见 `docs/ci.md`),因为 Playwright 会长期占用 CPU。
+7 -1
View File
@@ -30,7 +30,7 @@ staticStatus 只代表支持范围内的静态检查。completionStatus 保持 u
已逐条完成源码审阅的 review 可登记在 `.codex-tasks/template-audit-execution/raw/manual-review.json`。登记必须使用和诊断报告一致的 `file/page/target/binding/line/message`,并保留结论与证据;doctor 只把精确匹配的 review 标记为 `source-reviewed`,不改变 `completionStatus`。未匹配的新 review 和全部 blocker 仍会让命令失败。
完成证据登记在 `.codex-tasks/template-audit-execution/raw/completion-evidence.json`。每套模板必须提供 `real-manifest-interaction`、`save-reload-publish-isolation`、`visual-reference`、`empty-error-branches` 四类 `passed` 证据;每类证据必须包含实际命令、`exitCode=0`、日志或截图产物及其 SHA-256。registry 还必须记录 source tree hash;doctor 会计算当前仓库源码树(排除 `.codex-tasks/` 证据目录)的 hash,并在不匹配时拒绝完成态。doctor 会校验证据覆盖全部模板、产物存在且哈希一致。全部通过时 `completionStatus=complete`;证据文件缺失时保持 `unverified`;登记不完整或哈希不匹配时对应模板为 `incomplete` 并让命令失败。
完成证据登记在 `.codex-tasks/template-audit-execution/raw/completion-evidence.json`。每套模板必须提供 `real-manifest-interaction`、`save-reload-publish-isolation`、`visual-reference`、`empty-error-branches` 四类 `passed` 证据;每类证据必须包含实际命令、`exitCode=0`、日志或截图产物及其 SHA-256。registry 还必须记录 source tree hash;doctor 会计算当前仓库源码树的 hash,并在不匹配时拒绝完成态。哈希范围只包含会影响模板交付的源码:排除 `.codex-tasks/`、`.gitea/`、`deploy/` 以及除 `docs/template-completion-rules.md` 之外的全部 markdown。改文档、改 CI 或改部署脚本不再让已完成证据失效,改模板、renderer、诊断器或本文件仍然会。doctor 会校验证据覆盖全部模板、产物存在且哈希一致。全部通过时 `completionStatus=complete`;证据文件缺失时保持 `unverified`;登记不完整或哈希不匹配时对应模板为 `incomplete` 并让命令失败。
AST 解析可追踪 workspace.brand、presentation、object 和局部别名。动态路径、跨组件和间接映射等未知情况标为 review,不能猜测为通过。诊断器包含正反故障注入测试。
@@ -94,3 +94,9 @@ Taro 小程序构建默认会把 CSS 中的 HTML 标签选择器重写为 `.h5-<
4. 原生控件必查:显示类型、宽度、高度令牌、文字垂直居中、点击命中、安全区和底部遮挡。
5. 真机必查:request/media 合法域名、登录、拨号、复制、滚动、字体缩放和 iPhone 底部安全区。
6. 修复方式先查共享 reset、令牌和 Taro 运行时,再改模板局部样式;同类问题必须补产物契约测试或视觉清单项,不允许只改单个模板的单个按钮。
## 证据哈希维护
`git config core.hooksPath .githooks` 由 `pnpm install` 的 `prepare` 自动设置,`.githooks/pre-commit` 会在提交前调用 `node scripts/template-evidence-refresh.mjs --stage`,把最新的 `sourceTreeHash` 合并进同一个提交。不要再用「先提交业务改动、再提交 `chore: 更新模板完成证据源码哈希`」的两段式流程:那会让真正的改动永远拿不到绿色 CI。
需要手动重算时执行 `pnpm evidence:refresh`;加 `--stage` 会同时 `git add -f` 已跟踪的证据文件。
+2
View File
@@ -14,6 +14,8 @@
"format": "prettier --write .",
"format:check": "prettier --check .",
"check": "pnpm format:check && pnpm lint && pnpm typecheck && pnpm template:check",
"prepare": "git config core.hooksPath .githooks || true",
"evidence:refresh": "node scripts/template-evidence-refresh.mjs",
"db:migrate": "pnpm --filter @personal-brand/api db:migrate",
"db:seed": "pnpm --filter @personal-brand/api db:seed",
"test:api-client": "pnpm --filter @personal-brand/api exec tsx --test ../../packages/api-client/test/**/*.test.ts",
+24 -20
View File
@@ -15,26 +15,30 @@ function run(command, args) {
process.stdout.write(result.stdout);
}
run("ssh", [
target,
"bash",
"-lc",
[
"set -euo pipefail",
'source "$HOME/.nvm/nvm.sh"',
"export DEPLOY_ROOT=/home/ubuntu/persional-brand",
'printf "current=%s\\n" "$(readlink /home/ubuntu/persional-brand/current)"',
'printf "api="; test "$(pm2 pid personal-brand-api)" != "0"; echo online',
'printf "pm2-autostart="; systemctl --user is-enabled personal-brand-pm2.service',
'printf "admin="; systemctl --user is-active personal-brand-admin-static.service',
'printf "database="; docker inspect -f "{{.State.Status}}" personal-brand-postgres-1',
'printf "backups="; find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -name "*.dump" | wc -l',
'printf "latest-backup="; newest=$(find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); test -n "$newest"; stat -c "%y %s bytes" "$newest"; docker exec -i personal-brand-postgres-1 pg_restore -l < "$newest" >/dev/null; echo readable',
'printf "backup-temp-files="; find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -type f -name "*.tmp" | wc -l',
'printf "disk="; df -h / | awk "NR==2 {print \\$5 \" used, \" \\$4 \" free\"}"',
'printf "release-count="; find /home/ubuntu/persional-brand/releases -mindepth 1 -maxdepth 1 -type d | wc -l',
].join("; "),
]);
// ssh 会把多个参数用空格拼成一个字符串交给远端 shell,整段脚本必须先整体加引号,
// 否则 `bash -lc set -euo pipefail; ...` 只会执行 `set`,其余命令落到远端登录 shell。
function shellQuote(value) {
return "'" + value.replace(/'/g, "'\\''") + "'";
}
const remoteScript = [
"set -euo pipefail",
'source "$HOME/.nvm/nvm.sh"',
"export DEPLOY_ROOT=/home/ubuntu/persional-brand",
'printf "current=%s\\n" "$(readlink /home/ubuntu/persional-brand/current)"',
'printf "api="; test "$(pm2 pid personal-brand-api)" != "0"; echo online',
'printf "pm2-autostart="; systemctl --user is-enabled personal-brand-pm2.service',
'printf "admin="; systemctl --user is-active personal-brand-admin-static.service',
'printf "database="; docker inspect -f "{{.State.Status}}" personal-brand-postgres-1',
'printf "ci-runner="; systemctl --user is-active gitea-runner.service',
'printf "backups="; find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -name "*.dump" | wc -l',
'printf "latest-backup="; newest=$(find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -type f -name "*.dump" -printf "%T@ %p\\n" | sort -nr | head -1 | cut -d" " -f2-); test -n "$newest"; stat -c "%y %s bytes" "$newest"; docker exec -i personal-brand-postgres-1 pg_restore -l < "$newest" >/dev/null; echo readable',
'printf "backup-temp-files="; find /home/ubuntu/persional-brand/shared/backups -maxdepth 1 -type f -name "*.tmp" | wc -l',
'printf "disk="; df -h / | awk \'NR==2 {print $5 " used, " $4 " free"}\'',
'printf "release-count="; find /home/ubuntu/persional-brand/releases -mindepth 1 -maxdepth 1 -type d | wc -l',
].join("; ");
run("ssh", [target, "bash -lc " + shellQuote(remoteScript)]);
for (const route of [
"/admin/",
+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");