diff --git a/docs/verified-update-automation.md b/docs/verified-update-automation.md index 33bbad4..887b1f9 100644 --- a/docs/verified-update-automation.md +++ b/docs/verified-update-automation.md @@ -107,7 +107,15 @@ 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 +When upstream has moved to a newer SHA that passes fresh re-audit and the older +open Draft PR is bot-authored only (no manual edits), the proposer closes the +stale Draft PR with a comment and opens a fresh Ready PR for the new SHA (with an +expanded re-audit budget of `max(limit * 4, 25)` so open Drafts do not starve). +Non-installable entries (`availability != "installable"`, such as `listing-only`) +are reported as `governance-blocked` in coverage rather than opening doomed Draft +PRs. For single-file size budgets, non-executable raster images (`.png`, `.jpg`, +`.jpeg`, `.webp`) are permitted up to 5 MiB while scripts, code, SVGs, docs, and +other files remain strictly capped at 1 MiB. Discovery/audit/validation failures retain old admission and become drafts/manual findings. Nothing automatically promotes listing-only. ## Offline checks diff --git a/scripts/catalog/audit_skill_update.py b/scripts/catalog/audit_skill_update.py index 1b4afd5..d752e6c 100644 --- a/scripts/catalog/audit_skill_update.py +++ b/scripts/catalog/audit_skill_update.py @@ -15,6 +15,8 @@ from pathlib import Path, PurePosixPath from check_upstream_health import GENERATOR from automated_review import REVIEWER, validate_record MAX_FILE_BYTES = 1024 * 1024 +MAX_STATIC_IMAGE_BYTES = 5 * 1024 * 1024 +STATIC_IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.webp'} MAX_CONTENT_BYTES = 50 * 1024 * 1024 MAX_FILES = 2000 DEPENDENCY_NAMES = {'package.json', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', @@ -60,8 +62,10 @@ def tree(repo: Path, ref: str, path: str = '', exclude_paths=(), budget_exempt_p if kind != 'blob' or mode not in ('100644', '100755'): raise AuditBlocked('来源包含符号链接、子模块或不支持的节点') size = int(git(repo, 'cat-file', '-s', oid)) - if size > MAX_FILE_BYTES and not path_matches(name, budget_exempt_paths): - raise AuditBlocked('单文件超过自动审核预算') + is_static_image = mode == '100644' and PurePosixPath(name).suffix.lower() in STATIC_IMAGE_EXTENSIONS + limit = MAX_STATIC_IMAGE_BYTES if is_static_image else MAX_FILE_BYTES + if size > limit and not path_matches(name, budget_exempt_paths): + raise AuditBlocked(f'单文件超过自动审核预算({name}: {size} bytes > {limit} bytes)') result[name] = (mode, oid, size) if len(result) > MAX_FILES or sum(item[2] for item in result.values()) > MAX_CONTENT_BYTES: raise AuditBlocked('来源超过自动审核内容预算') diff --git a/scripts/catalog/propose_upstream_updates.py b/scripts/catalog/propose_upstream_updates.py index a4f6f79..64d5f7c 100644 --- a/scripts/catalog/propose_upstream_updates.py +++ b/scripts/catalog/propose_upstream_updates.py @@ -298,6 +298,36 @@ def promote_verified_draft_pr( run("git", "worktree", "remove", "--force", str(checkout)) +def _non_installable_availability(metadata: dict) -> str | None: + """Return availability string when explicitly set to a non-installable state (e.g. listing-only).""" + availability = (metadata.get("governance") or {}).get("availability") + if isinstance(availability, str) and availability and availability != "installable": + return availability + return None + + +def rotate_stale_automated_draft_pr(repository: str, item_id: str, pr: dict, new_head: str) -> tuple[bool, str]: + """Close a stale bot-authored Draft PR when upstream moved to a newer commit that passes audit. + + Never touches non-draft PRs or Draft PRs containing manual human edits. + """ + pr_number = pr.get("number") + if not pr.get("isDraft") or not pr_number: + 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, "旧草稿包含人工修改,保留原样由维护者处理 / Stale draft has manual edits; left untouched" + run( + "gh", "pr", "close", str(pr_number), "--repo", repository, + "--comment", + f"上游已推进至新快照 `{new_head[:12]}` 且新快照已通过最新 `main` 自动核验,关闭旧自动草稿并由新 PR 替代。" + f" / Upstream advanced to `{new_head[:12]}` and passed automated re-audit under latest `main`; closing stale automated draft in favor of a fresh PR.", + ) + return True, f"已关闭过期自动草稿 #{pr_number},改为提交新快照 PR" + + def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("results", type=Path) @@ -324,6 +354,7 @@ def main() -> None: open_heads = {pr['headRefName'] for pr in open_prs} count = 0 existing_rechecks = 0 + recheck_budget = max(args.limit * 4, 25) for result in results: item_id = result.get("id", "") if result.get("kind") != "skill" or not SLUG.fullmatch(item_id): @@ -336,7 +367,16 @@ def main() -> None: continue if (folder / "upstream-health-hold.json").exists(): continue - proposed = candidate(json.loads(entry_path.read_text()), json.loads(metadata_path.read_text()), result) + sidecar_data = json.loads(metadata_path.read_text()) + non_installable = _non_installable_availability(sidecar_data) + if non_installable is not None: + if item_id in by_id: + by_id[item_id].update( + status="governance-blocked", + reason=f"条目当前为 {non_installable}(非 installable),不自动创建草稿 PR;需人工准入后再纳入自动更新", + ) + continue + proposed = candidate(json.loads(entry_path.read_text()), sidecar_data, result) if proposed is None: if item_id in by_id and by_id[item_id]['status'] == 'queued': by_id[item_id].update(status="manual-review-required", reason="来源或 provenance 与检查快照不一致") @@ -344,7 +384,7 @@ def main() -> None: branch = f"updates/{item_id}-{result['head'][:12]}" # 保留审核者已编辑的候选;已关闭候选也不在下一轮重新创建。 if any(head.startswith(f"updates/{item_id}-") for head in open_heads): - if existing_rechecks < args.limit: + if existing_rechecks < recheck_budget: existing_rechecks += 1 pr = next(pr for pr in open_prs if pr['headRefName'].startswith(f"updates/{item_id}-")) view_error = None @@ -353,30 +393,43 @@ def main() -> None: except (OSError, ValueError, subprocess.SubprocessError) as error: view = None view_error = str(error) - fresh_proposed, 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()), sidecar_data, result, candidate_view=view) + rotated = False 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, + if pr.get("headRefName") == branch: + 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}" + elif pr.get("isDraft"): + try: + rotated, promote_note = rotate_stale_automated_draft_pr( + repository, item_id, pr, result["head"], + ) + except (OSError, ValueError, subprocess.SubprocessError) as error: + promote_note = f"轮换过期草稿失败,保留原草稿 / Stale draft rotation failed: {error}" + if rotated: + open_heads.discard(pr["headRefName"]) + else: + 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" ) - 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 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.')) - by_id[item_id].update(status='manual-review-required') + 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 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.')) + by_id[item_id].update(status='manual-review-required') + continue else: by_id[item_id].update(status="not-checked", reason="已有 PR,本轮复核预算未覆盖;未修改 / Existing PR exceeds re-audit budget; untouched") - continue + continue existing = json.loads(run("gh", "pr", "list", "--repo", repository, "--state", "all", "--head", branch, "--json", "number")) if args.publish else [] if existing: diff --git a/scripts/catalog/test_audit_skill_update.py b/scripts/catalog/test_audit_skill_update.py index c0ad45e..99092a3 100644 --- a/scripts/catalog/test_audit_skill_update.py +++ b/scripts/catalog/test_audit_skill_update.py @@ -1141,5 +1141,25 @@ class AuditTests(unittest.TestCase): self.repo, self.entry, self.metadata, {'ref': self.old, 'head': bad_code}, '2026-10-31T01:02:03Z', special_review=review) + def test_static_raster_image_budget_allows_up_to_5mib_while_blocking_large_scripts_and_svg(self): + # 2 MiB non-executable PNG is allowed under MAX_STATIC_IMAGE_BYTES (5 MiB) + png_path = self.repo / 'skills/sample/assets/preview.png' + png_path.parent.mkdir(parents=True, exist_ok=True) + png_path.write_bytes(b'\x89PNG\r\n\x1a\n' + b'\x00' * (2 * 1024 * 1024)) + new_png = self.commit() + entry, _, _ = audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new_png}, + '2026-10-31T01:02:03Z') + self.assertEqual(entry['source']['ref'], new_png) + + # 2 MiB SVG is still blocked under strict 1 MiB MAX_FILE_BYTES (SVG can carry scripts) + svg_path = self.repo / 'skills/sample/assets/huge.svg' + svg_path.write_bytes(b'' + b' ' * (2 * 1024 * 1024) + b'') + new_svg = self.commit() + with self.assertRaisesRegex(AuditBlocked, r'单文件超过自动审核预算.*huge\.svg'): + audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new_svg}, + '2026-10-31T01:02:03Z') + if __name__ == '__main__': unittest.main() diff --git a/scripts/catalog/test_propose_upstream_updates.py b/scripts/catalog/test_propose_upstream_updates.py index a04209f..e8674f4 100644 --- a/scripts/catalog/test_propose_upstream_updates.py +++ b/scripts/catalog/test_propose_upstream_updates.py @@ -249,6 +249,55 @@ class CandidateTests(unittest.TestCase): self.assertLess(len(truncated), 65536) self.assertIn("audit-results", truncated) + def test_non_installable_listing_only_entry_skips_draft_pr_creation(self): + self.sidecar["governance"]["availability"] = "listing-only" + result = self.exercise_publish(audited=False) + self.assertNotIn('draft', result) + self.assertEqual(result['coverage'][0]['status'], 'governance-blocked') + self.assertIn('listing-only', result['coverage'][0]['reason']) + + def test_stale_automated_draft_is_closed_and_rotated_when_newer_sha_passes(self): + stale_branch = "updates/sample-000000000000" + 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)) + 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'): + if '--head' in args: + return '[]' + return json.dumps([{'number': 396, 'headRefOid': '1' * 40, 'isDraft': True, 'headRefName': stale_branch}]) + if args[:3] == ('gh', 'pr', 'view'): + return json.dumps({ + 'commits': [{'messageHeadline': 'chore(market): 提议更新 sample 上游快照'}], + 'files': [{'path': 'skills/sample/entry.json'}], + }) + if args[:3] == ('gh', 'pr', 'close'): + events.append(('closed', args[3])) + return '' + if args[:3] == ('git', 'worktree', 'add'): + shutil.copytree(root/'skills', Path(args[4])/'skills') + return '' + if args[:3] == ('gh', 'pr', 'create'): + events.append(('created', '--draft' in args)) + return '' + 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() + self.assertIn(('closed', '396'), events) + self.assertIn(('created', False), events) + if __name__ == "__main__": unittest.main()