Repository navigation
feat(guard): envParity check — block env drift between environments - #8
Conversation
业务功能用环境变量开关 = 测试环境验证的行为与生产不一致, 构建/lint/单测全不报错,只有真实流量进那个分支才暴露 (实例:PUBLIC_MARKET 仅 .env.test 配置,跨站兜底路径生产独有)。 规则(默认 block,提交动了 .env* 才触发,比对文件对全量状态): - 变量集合缺失即分叉:一侧有一侧没有 = 拦 - 同名取值不同:变量名命中 allowDiffKeywords(url/host/domain/ endpoint/origin/port/site/base)或值形似 URL/主机名才放行, 其余(联系邮箱、开关值、文案键)必须两环境同值 - 单环境项目(无 .env.test)自动跳过;ignoreVars 显式豁免
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 0ef9fd5718
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| if (config.checks.envParity.enabled && staged.some((file) => ENV_FILE_PATTERN.test(file.path))) { | ||
| items.push(...runEnvParityChecks(cwd, config, staged)) |
There was a problem hiding this comment.
Add envParity to the generated hook runtime
The new check is invoked only by the TypeScript runGuard, but both agentGuard and agentGit install the self-contained script produced by createGuardHookScript; its duplicated normalizeGuardConfig and runGuard contain no envParity logic. Consequently, staging divergent environment files and running the installed pre-commit hook still passes, so the advertised default blocking behavior is absent from the primary integration path.
Useful? React with 👍 / 👎.
| function envFileContent(cwd: string, relative: string, staged: StagedFile[]): string | undefined { | ||
| const snapshot = staged.find((file) => file.path === relative) | ||
| if (snapshot && !snapshot.binary) return snapshot.content | ||
| return readFileSafe(path.resolve(cwd, relative)) |
There was a problem hiding this comment.
Read the unstaged parity file from the Git index
When only one file in the configured pair is staged, the other file is read from the working tree rather than the index. For example, a staged production addition can pass if the matching test variable exists only in an unstaged edit; the resulting commit then contains the exact divergence this check is intended to block. Both sides must be compared using their index snapshots so uncommitted working-tree changes cannot affect the decision.
Useful? React with 👍 / 👎.
| */ | ||
| function allowsValueDiff(name: string, value: string, keywords: string[]): boolean { | ||
| const lowerName = name.toLowerCase() | ||
| if (keywords.some((keyword) => lowerName.includes(keyword))) return true |
There was a problem hiding this comment.
Match addressing keywords as name components
Plain substring matching exempts unrelated variables whose names happen to contain a keyword. In particular, SUPPORT_EMAIL contains port, so differing production and test support addresses are silently allowed even though contact-email differences are explicitly meant to be blocked; similar collisions occur with names such as BASELINE_FEATURE. Match delimited variable-name components rather than arbitrary substrings.
Useful? React with 👍 / 👎.
| severity: check.severity, | ||
| file: primary, | ||
| line: entry.line, | ||
| message: `变量 ${entry.name} 两环境取值不同(${primary}='${truncateValue(entry.value)}' vs ${secondary}='${truncateValue(other.value)}')——非寻址类变量必须一致,用 env 开业务功能属于红线`, |
There was a problem hiding this comment.
Redact environment values from parity reports
For any differing non-address variable, this message writes both raw values to terminal output and log/guard-report.json. If the pair contains a password, API credential, or another sensitive value, up to 60 characters of each secret are persisted verbatim; reporting the variable name and files is sufficient to diagnose the mismatch without bypassing the repository's log-redaction requirement.
AGENTS.md reference: AGENTS.md:L29-L29
Useful? React with 👍 / 👎.
| /** 触发 envParity 检查的 staged 文件:.env 及其 mode 变体(.env.production / .env.test.local 等)。 */ | ||
| export const ENV_FILE_PATTERN = /^\.env(?:\.[^/]+)?$/ |
There was a problem hiding this comment.
Trigger parity checks for nested environment files
This anchored pattern recognizes only repository-root paths such as .env.production. A valid configured pair such as packages/web/.env.production and packages/web/.env.test never activates the check when staged because both paths contain a slash, despite files accepting repository-relative paths; matching the basename or the configured pair would cover monorepo and nested-app layouts.
Useful? React with 👍 / 👎.
| severity: check.severity, | ||
| file: primary, | ||
| line: entry.line, | ||
| message: `变量 ${entry.name} 两环境取值不同(${primary}='${truncateValue(entry.value)}' vs ${secondary}='${truncateValue(other.value)}')——非寻址类变量必须一致,用 env 开业务功能属于红线`, |
There was a problem hiding this comment.
🔒 Agentic Security Review
Severity: MEDIUM
envParity 在同名变量取值不同时,会把两侧原始值(truncateValue 截断 60 字符)拼进 GuardReportItem.message。这条消息会被打印到终端,并写入 agent 会读的 log/guard-report.json。检查由任一 staged 的根目录 .env* 触发,未 staged 的对偶文件会从工作区读取(常见是 gitignore 的 .env.production),因此未进交交的凭证也会进入报告。SECRET/TOKEN/API_KEY 等命名不在 allowDiffKeywords 里,且值通常不是 URL/主机名形状,因此就是会走这条泄露路径的常见场景。同模块的 secrets 检查从不回显匹配内容;project-guide.json 也明确不写环境变量值。
Impact: 本地秘钥前缀会进入 agent/LLM 上下文与持久化报告,超出磅盘上原 .env 文件的目击面。
Reviewed by Cursor Security Reviewer for commit 0ef9fd5. Configure here.
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.
❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.
Reviewed by Cursor Bugbot for commit 0ef9fd5. Configure here.
| // 触发条件:本次提交动了 .env*(任一 mode 变体),才比对目标文件对的全量状态。 | ||
| if (config.checks.envParity.enabled && staged.some((file) => ENV_FILE_PATTERN.test(file.path))) { | ||
| items.push(...runEnvParityChecks(cwd, config, staged)) | ||
| } |
There was a problem hiding this comment.
Env parity missing from commit hook
High Severity
envParity is only added to runGuard in guard-core.ts. The self-contained pre-commit script from createGuardHookScript never runs it, so agentGuard and agentGit({ guard }) will not block env drift on real commits even though tests pass.
Reviewed by Cursor Bugbot for commit 0ef9fd5. Configure here.
| export const CSS_VAR_USE_PATTERN = /var\(\s*(--[a-zA-Z0-9_-]+)/g | ||
|
|
||
| /** 触发 envParity 检查的 staged 文件:.env 及其 mode 变体(.env.production / .env.test.local 等)。 */ | ||
| export const ENV_FILE_PATTERN = /^\.env(?:\.[^/]+)?$/ |
There was a problem hiding this comment.
Env trigger ignores nested paths
Medium Severity
ENV_FILE_PATTERN is anchored to the start of the staged path, so only root-level .env* files start the check. Nested env files and a custom files pair under a directory never trigger, even when those files are the ones being committed.
Additional Locations (1)
Reviewed by Cursor Bugbot for commit 0ef9fd5. Configure here.




Why
业务功能用环境变量开关 = 测试环境验证的行为与生产不一致:构建 / lint / 单测全不报错,只有真实流量进了那个分支才暴露(实例:
PUBLIC_MARKET仅.env.test配置,跨站兜底路径生产独有,测试永远验不到)。What
新增 agentGuard 检查项
envParity(默认 block):.env*(任一 mode 变体),比对文件对(默认.env.productionvs.env.test)的全量状态——一致性是集合性质,只看 diff 会漏掉早已分叉的变量;不动的提交不被历史分叉淹没ignoreVars显式豁免allowDiffKeywords(url / host / domain / endpoint / origin / port / site / base)或值形似 URL / 点分主机名才放行——寻址类命名千差万别(_CONSOLE、_DOCS、*_GATEWAY…),名字清单列不全,值形状才是共性;其余(联系邮箱、功能开关值、文案键)两环境必须同值.env.test)自动跳过Docs & tests
网站 guard 指南新章节、SKILL.md(顺带补上此前漏写的 cssVars)、CHANGELOG Unreleased、中英 README 各一行;11 个新测试覆盖 PUBLIC_MARKET 单侧、CONTACT_EMAIL 值分叉、域名放行、ignoreVars、单侧文件、未动 env 不触发。全仓 175 测试过,tsc 干净。
Note
Medium Risk
New default pre-commit block on env edits can surprise teams with intentional prod/test divergence; misclassified vars may need
ignoreVarsor keyword tuning.Overview
Adds
envParitytoagentGuard(default block): when a commit stages any.env*file, it fully compares the configured pair (default.env.productionvs.env.test) for missing keys and mismatched values.Matching rules: one-sided variables fail; differing values fail unless the name matches
allowDiffKeywordsor the value looks like a URL/host. Single-env repos (missing/empty counterpart) and commits that do not touch env files are skipped. Config coversfiles,allowDiffKeywords, andignoreVars.Implementation lives in
guard-core(parseEnvEntries,runEnvParityChecks) with types/constants inguard-types. Docs (CHANGELOG, bilingual README rows,SKILL.md, guard guide) andtest/guard-env-parity.test.tscover defaults, blocking, allowances, and trigger behavior.Reviewed by Cursor Bugbot for commit 0ef9fd5. Bugbot is set up for automated code reviews on this repo. Configure here.