feat(catalog): 增加过期草稿轮换、非可安装条目跳过与静态位图预算分档规则 (#430)

## 概述 / Summary

在**不放松任何安全/供应链审核红线**的前提下,为每日 `Upstream Health` 工作流落地 3 条减少无效 Draft
堆积的安全规则:

1. **规则 A — 过期自动草稿自动轮换 & 放宽重审预算(`propose_upstream_updates.py`)**:
- 已有 PR 重审预算从 `args.limit`(5)提升至 `max(args.limit * 4, 25)`,避免 15+ 个打开的
Draft PR 互相饿死。
- 当已有自动生成的 Draft PR(经 `_is_automated_draft_only`
确认无人工提交或额外文件)落后于上游新提交,且**新提交按最新 `main` 规则已通过全部审核**时,自动关闭旧草稿(留注释说明)并直接为新
SHA 创建正式 Ready PR(解决 `#396`、`#398` 这类卡在旧 SHA 草稿上的问题)。
2. **规则 B — 非 `installable` 条目不白建必然失败的 Draft
PR(`propose_upstream_updates.py`)**:
- `catalog-metadata.v1.json` 中 `governance.availability` 明确非
`installable`(例如 `listing-only`)的条目,直接在覆盖报告记为
`governance-blocked`,不再创建注定失败的 Draft PR 噪音(覆盖
`#402`/`#403`/`#410`/`#411`/`#423` 同类场景)。
3. **规则 C — 静态位图单文件预算分档(`audit_skill_update.py`)**:
- 非可执行静态位图(`mode=100644` 的 `.png`/`.jpg`/`.jpeg`/`.webp`)单文件预算放宽至 `5
MiB`(`MAX_STATIC_IMAGE_BYTES`),减少演示截图误伤;
   - 脚本、代码、`.svg`(可能含脚本)、文档与二进制仍严格维持 `1 MiB` 上限,且超预算报错明确输出具体文件路径与字节数。

## 变更 / Changes
- `scripts/catalog/propose_upstream_updates.py`:新增
`_non_installable_availability`、`rotate_stale_automated_draft_pr`、扩大
`recheck_budget`
- `scripts/catalog/audit_skill_update.py`:新增 `MAX_STATIC_IMAGE_BYTES` /
`STATIC_IMAGE_EXTENSIONS` 分档预算与精确路径报错
- `docs/verified-update-automation.md`:同步更新规则说明
- `scripts/catalog/test_propose_upstream_updates.py` &
`scripts/catalog/test_audit_skill_update.py`:新增 3 项单测覆盖规则 A/B/C

## 验证 / Validation
- `uv run --offline --quiet
scripts/catalog/test_propose_upstream_updates.py`
- `uv run --offline --quiet scripts/catalog/test_audit_skill_update.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`
This commit is contained in:
mashagua authored and GitHub committed 2026-12-03 21:27:26 +08:00
1 parent f6d1eccf70
commit 599de06444
5 files changed
+157 -23

No files matched your search

+6 -2
View File
@@ -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('来源超过自动审核内容预算')
+73 -20
View File
@@ -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:
@@ -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'<svg>' + b' ' * (2 * 1024 * 1024) + b'</svg>')
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()
@@ -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()