From 2d96fc9c41ccedbd3c1a3e0358913eb489b799ab Mon Sep 17 00:00:00 2001 From: mashagua <993498039@qq.com> Date: Wed, 2 Dec 2026 10:25:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(catalog):=20=E5=B7=B2=E6=9C=89=E8=87=AA?= =?UTF-8?q?=E5=8A=A8=E8=8D=89=E7=A8=BF=20PR=20=E6=8C=89=E6=9C=80=E6=96=B0?= =?UTF-8?q?=20main=20=E9=87=8D=E5=AE=A1=E9=80=9A=E8=BF=87=E5=90=8E?= =?UTF-8?q?=E8=87=AA=E5=8A=A8=E8=BD=AC=20Ready=20(#419)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 概述 / Summary 增强每日 `Upstream Health` 工作流中的 `propose_upstream_updates.py`:当已有自动生成的 **Draft PR** 按最新 `main` 规则与 `special-review.v1.json` 重新审核通过时,自动同步 `main`、运行全部仓库校验、刷新机器审计回执并解除 Draft(`gh pr ready`)。 ### 安全边界(绝不误伤人工 PR) 1. **仅处理自动草稿**:必须同时满足 `isDraft == true`、目标分支与当前 `updates/-` 完全一致,且 PR 上所有提交与改动文件均来自自动提案器(或普通 `Merge branch 'main'`)。若检测到任何人工提交或额外文件,立即跳过保留原样。 2. **绝不 rebase / force-push**:使用普通 `git merge --no-edit ` 同步主干;遇到合并冲突直接保持 Draft。 3. **强制重跑全部仓库校验**:推送与 `gh pr ready` 前强制执行 `validate_catalog_metadata.py --require-complete`、`validate-i18n.py`、`translate.py --check`(及合集的 `gen-collection-children.py --check`),任意校验失败立即中止并保留 Draft;清理过期的 `docs/update-reviews/-*.json` 阻断记录。 ## 变更 / Changes - `scripts/catalog/propose_upstream_updates.py`:新增 `_is_automated_draft_only` 与 `promote_verified_draft_pr`,并在已有 PR 重审通过分支挂钩 - `scripts/catalog/test_propose_upstream_updates.py`:新增 3 项单测覆盖自动转 Ready、人工修改保护与校验失败拦截 - `docs/verified-update-automation.md`:同步更新自动草稿重审转 Ready 的行为说明 ## 验证 / Validation - `uv run --offline --quiet scripts/catalog/test_propose_upstream_updates.py` - `uv run --offline --quiet scripts/catalog/validate_catalog_metadata.py --require-complete` - `uv run --offline --quiet scripts/i18n/validate-i18n.py` - `uv run --offline --quiet scripts/i18n/translate.py --check` - `git diff --check` --- docs/verified-update-automation.md | 7 +- scripts/catalog/propose_upstream_updates.py | 139 +++++++++++++++++- .../catalog/test_propose_upstream_updates.py | 76 ++++++++++ 3 files changed, 219 insertions(+), 3 deletions(-) diff --git a/docs/verified-update-automation.md b/docs/verified-update-automation.md index c746de3..33bbad4 100644 --- a/docs/verified-update-automation.md +++ b/docs/verified-update-automation.md @@ -102,7 +102,12 @@ be reviewed/merged separately by a maintainer. Daily discovery remains 09:23 Asia/Singapore (GitHub can delay execution). Git and configured-source publishers each have a five-candidate cap. An existing open PR for a skill is preserved, not overwritten; the same closed candidate is -not recreated. Discovery/audit/validation failures retain old admission and +not recreated. When an existing **bot-authored Draft PR** for the exact same +target SHA passes fresh re-audit under updated `main` policy/special-review +records (with zero manual human commits/files on the draft branch), the proposer +merges `main` normally (no rebase/force-push), re-runs all catalog/i18n +validators, updates the receipt/body, and marks the PR Ready (`gh pr ready`). +Discovery/audit/validation failures retain old admission and become drafts/manual findings. Nothing automatically promotes listing-only. ## Offline checks diff --git a/scripts/catalog/propose_upstream_updates.py b/scripts/catalog/propose_upstream_updates.py index a7d0cde..d75a137 100644 --- a/scripts/catalog/propose_upstream_updates.py +++ b/scripts/catalog/propose_upstream_updates.py @@ -160,6 +160,127 @@ def write_coverage(rows, destination): destination.with_suffix('.md').write_text("\n".join(summary) + "\n") +def _is_automated_draft_only(item_id: str, pr_details: dict) -> bool: + """Return True only if every commit and file on the Draft PR is from the automated proposer.""" + allowed_headlines = { + f"chore(market): 提议更新 {item_id} 上游快照", + f"chore(market): 重审通过并更新 {item_id} 上游快照", + } + commits = pr_details.get("commits") or [] + if not commits: + return False + for commit in commits: + headline = (commit.get("messageHeadline") or "").strip() + if headline in allowed_headlines: + continue + if headline.startswith(("Merge branch 'main'", "Merge remote-tracking branch")): + continue + return False + allowed_files = { + f"skills/{item_id}/entry.json", + f"skills/{item_id}/catalog-metadata.v1.json", + f"skills/{item_id}/upstream-audit.v1.json", + } + review_prefix = f"docs/update-reviews/{item_id}-" + files = pr_details.get("files") or [] + for item in files: + path = item.get("path") or "" + if path in allowed_files: + continue + if path.startswith(review_prefix) and path.endswith(".json"): + continue + return False + return True + + +def promote_verified_draft_pr( + repository: str, + actor: str, + item_id: str, + pr: dict, + branch: str, + entry_path: Path, + metadata_path: Path, + proposed: tuple[dict, dict], + audit: dict, + result: dict, +) -> tuple[bool, str]: + """Safely sync a bot-authored Draft PR with main and mark Ready when re-audit passes. + + Never touches non-draft PRs, PRs for a different target SHA, or PRs with manual + human commits/files. Uses a normal merge of main (no rebase, no force-push) and + re-runs all repository validators before pushing and calling `gh pr ready`. + """ + pr_number = pr.get("number") + if not pr.get("isDraft") or not pr_number or pr.get("headRefName") != branch: + return False, "" + pr_details = json.loads( + run("gh", "pr", "view", str(pr_number), "--repo", repository, "--json", "commits,files") + ) + if not _is_automated_draft_only(item_id, pr_details): + return False, "已有草稿包含人工修改,保留原样由维护者处理 / Existing draft has manual edits; left untouched" + + main_sha = run("git", "rev-parse", "HEAD") + with tempfile.TemporaryDirectory() as tmp: + checkout = Path(tmp) / "repo" + run("git", "fetch", "origin", branch) + run("git", "worktree", "add", "--detach", str(checkout), "FETCH_HEAD") + try: + try: + run("git", "-c", f"user.name={actor}", "-c", f"user.email={EMAIL}", + "merge", "--no-edit", main_sha, cwd=checkout) + except subprocess.CalledProcessError: + return False, "同步 main 时存在冲突,保持草稿由人工处理 / Merge with main conflicted; kept as draft" + + paths = [] + for path, data in zip((entry_path, metadata_path), proposed): + rel = path.relative_to(ROOT) + (checkout / rel).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n") + paths.append(str(rel)) + audit_path = f"skills/{item_id}/upstream-audit.v1.json" + (checkout / audit_path).write_text(json.dumps(audit, ensure_ascii=False, indent=2) + "\n") + paths.append(audit_path) + + # Remove any stale blocked review JSON for this item if present on the draft branch + review_dir = checkout / "docs/update-reviews" + if review_dir.is_dir(): + for stale in sorted(review_dir.glob(f"{item_id}-*.json")): + rel_stale = str(stale.relative_to(checkout)) + stale.unlink() + paths.append(rel_stale) + + try: + run("uv", "run", "--quiet", "scripts/catalog/validate_catalog_metadata.py", "--require-complete", cwd=checkout) + run("uv", "run", "--quiet", "scripts/i18n/validate-i18n.py", f"skills/{item_id}", cwd=checkout) + run("uv", "run", "--quiet", "scripts/i18n/translate.py", "--check", f"skills/{item_id}", cwd=checkout) + if proposed[0].get("children"): + run("uv", "run", "--quiet", "scripts/gen-collection-children.py", "--check", item_id, cwd=checkout) + except subprocess.CalledProcessError as error: + detail = str(error.stdout or error.stderr or "目录校验失败")[-2000:] + return False, f"重审后目录或本地化校验未通过,保持草稿 / Re-audit catalog/i18n validation failed; kept as draft: {detail}" + + run("git", "add", "-A", "--", *paths, cwd=checkout) + if run("git", "status", "--porcelain", cwd=checkout): + run("git", "-c", f"user.name={actor}", "-c", f"user.email={EMAIL}", + "commit", "-m", f"chore(market): 重审通过并更新 {item_id} 上游快照", cwd=checkout) + run("git", "push", "origin", f"HEAD:refs/heads/{branch}", cwd=checkout) + + body = Path(tmp) / "body.md" + body.write_text( + f"`{item_id}` 上游快照:`{result['ref']}` → `{result['head']}`\n\n" + "已有草稿 PR 已按最新 `main` 策略与专项复核记录重审通过,已同步 `main` 并转为 Ready;审核身份和记录明确标为机器。已运行目录与本条目元数据校验。\n" + "不执行上游代码,不代表软件安全认证或真实运行验收,不自动合并。非结构化依赖和行为变化仍需结合 PR 差异复核。\n\n" + "Automated source/license/metadata re-verification passed under latest main; synced with main and promoted from draft. Not a security certification or runtime acceptance. No auto-merge.\n\n" + + "```json\n" + json.dumps(audit, ensure_ascii=False, indent=2) + "\n```\n", + encoding="utf-8", + ) + run("gh", "pr", "edit", str(pr_number), "--repo", repository, "--body-file", str(body), cwd=checkout) + run("gh", "pr", "ready", str(pr_number), "--repo", repository, cwd=checkout) + return True, "已有草稿 PR 按最新 main 规则重审通过,已同步主干并转为 Ready / Existing draft PR passed re-audit under latest main; synced with main and marked ready" + finally: + run("git", "worktree", "remove", "--force", str(checkout)) + + def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("results", type=Path) @@ -215,9 +336,23 @@ def main() -> None: except (OSError, ValueError, subprocess.SubprocessError) as error: view = None view_error = str(error) - _, fresh_audit, fresh_reason = prepare_proposal(json.loads(entry_path.read_text()), json.loads(metadata_path.read_text()), result, candidate_view=view) + fresh_proposed, fresh_audit, fresh_reason = prepare_proposal(json.loads(entry_path.read_text()), json.loads(metadata_path.read_text()), result, candidate_view=view) + promoted, promote_note = False, "" + if args.publish and fresh_audit and fresh_proposed and not view_error: + try: + promoted, promote_note = promote_verified_draft_pr( + repository, actor, item_id, pr, branch, + entry_path, metadata_path, fresh_proposed, fresh_audit, result, + ) + except (OSError, ValueError, subprocess.SubprocessError) as error: + promote_note = f"自动转 Ready 失败,保留原草稿 / Auto-promote failed, kept as draft: {error}" + default_ok_reason = ( + promote_note if promoted else ( + promote_note or "已有 PR 对应main来源本轮重新静态核验通过;候选证据另列,不修改PR / Trusted-main source re-audited; candidate evidence is separate; PR untouched" + ) + ) by_id[item_id].update(status="audit-passed" if fresh_audit else "manual-review-required", - reason=("对可信main旧登记重放;当前PR证据另列 / Trusted-main baseline replay; current candidate evidence is separate: " + fresh_reason) if fresh_reason else "已有 PR 对应main来源本轮重新静态核验通过;候选证据另列,不修改PR / Trusted-main source re-audited; candidate evidence is separate; PR untouched", + reason=("对可信main旧登记重放;当前PR证据另列 / Trusted-main baseline replay; current candidate evidence is separate: " + fresh_reason) if fresh_reason else default_ok_reason, findings=getattr(fresh_reason, "findings", [])) if view_error: by_id[item_id]['findings'].append(dict(id=item_id,path='PR#'+str(pr.get('number')),oldRef=result['ref'],newRef=result['head'],gate='candidate-evidence-read',state='not_checked',origin='unknown',reason='当前 PR 元数据或检查未读取完成 / Candidate metadata/check read incomplete: '+view_error,repair='恢复标准 GitHub 读取后重试;main 重放不代表当前 PR 检查通过。 / Retry standard GitHub reads; main replay is not a candidate validation pass.')) diff --git a/scripts/catalog/test_propose_upstream_updates.py b/scripts/catalog/test_propose_upstream_updates.py index a28daf7..2df9809 100644 --- a/scripts/catalog/test_propose_upstream_updates.py +++ b/scripts/catalog/test_propose_upstream_updates.py @@ -166,6 +166,82 @@ class CandidateTests(unittest.TestCase): self.assertEqual(rows['archive']['status'], 'governance-blocked') self.assertEqual(rows['sample']['status'], 'queued') + def _exercise_promote(self, *, manual_commit=False, validation_failure=False): + branch = f"updates/sample-{self.new[:12]}" + with tempfile.TemporaryDirectory() as temporary: + root = Path(temporary); folder = root / 'skills/sample'; folder.mkdir(parents=True) + (folder/'entry.json').write_text(json.dumps(self.entry)) + (folder/'catalog-metadata.v1.json').write_text(json.dumps(self.sidecar)) + stale_dir = root / 'docs/update-reviews'; stale_dir.mkdir(parents=True) + (stale_dir / f'sample-{self.new[:12]}.json').write_text(json.dumps({'status': 'blocked'})) + results = root / 'results.json'; results.write_text(json.dumps([self.result])) + updated, metadata = candidate(self.entry, self.sidecar, self.result) + metadata['governance']['compliance'].update(reviewedRef=self.new, reviewedBy='automated:test') + events = [] + + def run(*args, cwd=None): + if args[:3] == ('gh', 'pr', 'list'): + return json.dumps([{'number': 396, 'headRefOid': '1' * 40, 'isDraft': True, 'headRefName': branch}]) + if args[:3] == ('gh', 'pr', 'view'): + commits = [{'messageHeadline': 'chore(market): 提议更新 sample 上游快照'}] + if manual_commit: + commits.append({'messageHeadline': 'fix: manual human tweak'}) + return json.dumps({ + 'commits': commits, + 'files': [ + {'path': 'skills/sample/entry.json'}, + {'path': f'docs/update-reviews/sample-{self.new[:12]}.json'}, + ], + }) + if args[:2] == ('git', 'rev-parse'): + return '9' * 40 + if args[:3] == ('git', 'worktree', 'add'): + dst = Path(args[4]) + shutil.copytree(root/'skills', dst/'skills') + shutil.copytree(root/'docs', dst/'docs') + return '' + if args[:2] == ('git', 'status'): + return ' M skills/sample/entry.json' + if args[0] == 'uv' and validation_failure: + raise subprocess.CalledProcessError(1, args, output='catalog failure') + if 'merge' in args and '--no-edit' in args: + events.append(('git', 'merge', '--no-edit')) + elif args[:3] in (('git', 'push', 'origin'), ('gh', 'pr', 'edit'), ('gh', 'pr', 'ready')): + events.append(args[:3]) + if args[:3] == ('gh', 'pr', 'ready'): + events.append(('stale_removed', not (cwd / f'docs/update-reviews/sample-{self.new[:12]}.json').exists())) + return '' + + with patch.object(proposer, 'ROOT', root), patch.object(proposer, 'run', side_effect=run), \ + patch.object(proposer, 'check_identity'), \ + patch.object(proposer, 'read_existing_candidate', return_value=None), \ + patch.object(proposer, 'audit_update', return_value=(updated, metadata, {'reviewer': 'automated:test'})), \ + patch.dict(os.environ, {'GITHUB_REPOSITORY': 'desirecore/market', 'MARKET_MAINTAINER_LOGIN': 'mashagua'}), \ + patch('sys.argv', ['propose', str(results), '--publish', '--coverage-file', str(root/'coverage.json')]): + proposer.main() + return events, json.loads((root/'coverage.json').read_text()) + + def test_existing_automated_draft_pr_is_promoted_to_ready_when_reaudit_passes(self): + events, cov = self._exercise_promote() + self.assertIn(('git', 'merge', '--no-edit'), events) + self.assertIn(('git', 'push', 'origin'), events) + self.assertIn(('gh', 'pr', 'edit'), events) + self.assertIn(('gh', 'pr', 'ready'), events) + self.assertIn(('stale_removed', True), events) + self.assertEqual(cov[0]['status'], 'audit-passed') + self.assertIn('转为 Ready', cov[0]['reason']) + + def test_existing_draft_pr_with_manual_human_edits_is_never_touched(self): + events, cov = self._exercise_promote(manual_commit=True) + self.assertEqual(events, []) + self.assertIn('人工修改', cov[0]['reason']) + + def test_existing_draft_pr_stays_draft_when_promotion_validation_fails(self): + events, cov = self._exercise_promote(validation_failure=True) + self.assertNotIn(('git', 'push', 'origin'), events) + self.assertNotIn(('gh', 'pr', 'ready'), events) + self.assertIn('校验未通过', cov[0]['reason']) + if __name__ == "__main__": unittest.main()