Skip to content

feat(guard): envParity check — block env drift between environments - #8

Merged
webkubor merged 1 commit into
mainfrom
feat/guard-env-parity
Nov 3, 2026
Merged

webkubor merged 1 commit into
mainfrom
feat/guard-env-parity

Conversation

@webkubor

@webkubor webkubor commented Nov 3, 2026 •

Copy link
Copy Markdown
Owner

Why

业务功能用环境变量开关 = 测试环境验证的行为与生产不一致:构建 / lint / 单测全不报错,只有真实流量进了那个分支才暴露(实例:PUBLIC_MARKET 仅 .env.test 配置,跨站兜底路径生产独有,测试永远验不到)。

What

新增 agentGuard 检查项 envParity(默认 block):

  • 触发:本次提交动了 .env*(任一 mode 变体),比对文件对(默认 .env.production vs .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 ignoreVars or keyword tuning.

Overview
Adds envParity to agentGuard (default block): when a commit stages any .env* file, it fully compares the configured pair (default .env.production vs .env.test) for missing keys and mismatched values.

Matching rules: one-sided variables fail; differing values fail unless the name matches allowDiffKeywords or the value looks like a URL/host. Single-env repos (missing/empty counterpart) and commits that do not touch env files are skipped. Config covers files, allowDiffKeywords, and ignoreVars.

Implementation lives in guard-core (parseEnvEntries, runEnvParityChecks) with types/constants in guard-types. Docs (CHANGELOG, bilingual README rows, SKILL.md, guard guide) and test/guard-env-parity.test.ts cover 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.

业务功能用环境变量开关 = 测试环境验证的行为与生产不一致,
构建/lint/单测全不报错,只有真实流量进那个分支才暴露
(实例:PUBLIC_MARKET 仅 .env.test 配置,跨站兜底路径生产独有)。

规则(默认 block,提交动了 .env* 才触发,比对文件对全量状态):
- 变量集合缺失即分叉:一侧有一侧没有 = 拦
- 同名取值不同:变量名命中 allowDiffKeywords(url/host/domain/
  endpoint/origin/port/site/base)或值形似 URL/主机名才放行,
  其余(联系邮箱、开关值、文案键)必须两环境同值
- 单环境项目(无 .env.test)自动跳过;ignoreVars 显式豁免
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T07:36:02.149395Z 0ef9fd5 PR opened
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@webkubor
webkubor enabled auto-merge (squash) November 3, 2026 07:35

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread src/guard-core.ts
Comment on lines +513 to +514
if (config.checks.envParity.enabled && staged.some((file) => ENV_FILE_PATTERN.test(file.path))) {
items.push(...runEnvParityChecks(cwd, config, staged))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/guard-core.ts
Comment on lines +388 to +391
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge 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 👍 / 👎.

Comment thread src/guard-core.ts
*/
function allowsValueDiff(name: string, value: string, keywords: string[]): boolean {
const lowerName = name.toLowerCase()
if (keywords.some((keyword) => lowerName.includes(keyword))) return true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread src/guard-core.ts
severity: check.severity,
file: primary,
line: entry.line,
message: `变量 ${entry.name} 两环境取值不同(${primary}='${truncateValue(entry.value)}' vs ${secondary}='${truncateValue(other.value)}')——非寻址类变量必须一致,用 env 开业务功能属于红线`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

Comment thread src/guard-types.ts
Comment on lines +232 to +233
/** 触发 envParity 检查的 staged 文件:.env 及其 mode 变体(.env.production / .env.test.local 等)。 */
export const ENV_FILE_PATTERN = /^\.env(?:\.[^/]+)?$/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agentic security review found 1 medium issue on the envParity value-mismatch report path.

Open in Web View Automation 

Sent by Cursor Security Agent: Security Reviewer

Comment thread src/guard-core.ts
severity: check.severity,
file: primary,
line: entry.line,
message: `变量 ${entry.name} 两环境取值不同(${primary}='${truncateValue(entry.value)}' vs ${secondary}='${truncateValue(other.value)}')——非寻址类变量必须一致,用 env 开业务功能属于红线`,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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 文件的目击面。

Fix in Cursor Fix in Web

Reviewed by Cursor Security Reviewer for commit 0ef9fd5. Configure here.

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

Fix All in Cursor

❌ 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.

Comment thread src/guard-core.ts
// 触发条件:本次提交动了 .env*(任一 mode 变体),才比对目标文件对的全量状态。
if (config.checks.envParity.enabled && staged.some((file) => ENV_FILE_PATTERN.test(file.path))) {
items.push(...runEnvParityChecks(cwd, config, staged))
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0ef9fd5. Configure here.

Comment thread src/guard-types.ts
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(?:\.[^/]+)?$/

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 0ef9fd5. Configure here.

@cursor
cursor Bot requested a review from lunove November 3, 2026 07:42
@webkubor
webkubor merged commit d148979 into main Nov 3, 2026
10 checks passed
@webkubor
webkubor deleted the feat/guard-env-parity branch November 17, 2026 01:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant