完善市场更新自动化:精确准入审核、安装通知门禁与双语问题闭环 (#354)

## 实际功能与范围

在原 PR 上继续完善,不新开机制 PR。使用 main 的可信代码与策略重新发现上游、读取精确旧新 pin、重建真实差异并绑定最终
SHA;不执行 PR 或上游代码,不把 listing-only 自动提升为 installable。

已正常 merge 最新 main,包含 #356、#357 以及其他 worker 完成的 #359;没有
rebase、force-push,也没有修改 #358–360 工作分支。本 PR **不合并、不部署自身**。

## 修改前后对照

| 修改点 | 修改前 | 修改后 / 实际效果 |
|---|---|---|
| Git 固定来源更新 | 主线发现更新后提出快照 PR,无法统一覆盖本轮发现的准入缺口 | 沿用精确 pin 的真实 delta
核验;新增门禁同样用于提案与可信自动合并重审。每轮最多审核 5 个新 Git 候选,另可只读复核 5 个已有 PR,不改其内容、不重复开 PR
|
| ZIP / Web 新版本发现 | 主线主要检查链接可访问性,不发现新版 | 只通过显式登记的 ClawHub / GitHub
release asset / GitHub file 适配器发现与固定来源,不猜版本、不把新哈希当作审核通过。目前实际登记高德
ClawHub;其他来源须另配可信跟踪;嵌套 ZIP 安装目录尚未适配 |
| 市场本地技能 | 不自动同步第三方上游 | AI News Radar
使用上游精确映射与文件清单,保留市场包装和本地补丁;上下游同时修改或映射范围不一致即暂停,不覆盖本地补丁。目前只登记此本地包 |
| 主许可通知是否随安装交付 | 能核对根及嵌套许可变化,却不能证明根主通知随 source.path / 所选 child.path 交付 |
分别检查每个所选目录;vendor/LICENSE 或 SKILL 中单行 MIT
不能替代主项目完整版权、授权和免责通知。README/SKILL 内完整等效文本可通过,不强制 standalone
LICENSE;未证明交付时阻断或转人工,不擅改安装方式 |
| NOTICE 的实际交付 | 根 NOTICE 存在或哈希已审可能被误当作安装交付 | 声明的 NOTICE
未证明随目录交付会阻断;未声明根 NOTICE 的适用性保守转人工。非标准/嵌套等效通知需人工复核,不把扫描未命中说成没有合法许可 |
| 精确 pin 人工例外 | README 文本没变时可能将旧许可例外扩展到新 pin | 单行 MIT 的旧 pin 例外不能自动继承;新
pin 必须另有真实人工授权。#359 的新 pin 例外是另一 worker 独立补审后合入 main 的决定,不是本机制自动扩大旧授权 |
| 版本、双语与派生目录 | 结构化字段通过不代表说明文字、两种语言和派生目录一致 |
使用明确版本源提示旧版本文案;根插件版本不强加给所选子目录,不把任意数字当版本。检查 entry/catalog
子项语言镜像,描述变化转人工;历史英文回退单独标记,不伪称已翻译 |
| 安装内容、权限、依赖和行为差异 | 依赖哈希接受或简短专项说明容易被误读为完整行为审核 | 直接比较完整 Git
对象和安装路径,报告新增/删除/权限差异,不依赖截断的 GitHub
compare。授权、凭据、配置、网络相关命名实现的变化保守转人工;明确这只是复核提示,不是已证实漏洞。开发依赖不冒充所选技能运行依赖 |
| 失败原因及真实回执 | 首个异常后缺少精确路径和未检查阶段;后续校验失败可能覆盖旧回执或仍显示已审 | 逐项输出技能/路径、精确旧新
pin、门槛、原因、修法与实际状态,区分历史遗留、本次引入、人工待审、实际失败和失败后未完成;保留真实旧回执,独立保存失败命令/输出,不生成假成功回执。物化
ZIP/local 的临时 Git ID 不当作真实来源 pin |
| 当前候选 PR 与 main 重放分层 | 对 main 旧元数据重放的失败,可能被误说成当前已修订 PR
仍未修;旧回执错误与许可根因混在一起 | 只读当前 PR 精确 head 的 entry、sidecar、旧回执与实时 checks;不
checkout、不执行候选。每行标注 main 重放或当前候选 head。reviewedRef / receipt ref /
receipt scope 三类未签新回执的派生错误与主通知交付根因分开;读取失败明确未检查,不停止其他独立候选,也不当作通过 |
| unhealthy report / issue 展示 | 健康 issue 在审核前生成、单语、每日时间戳驱动更新,并用评论关闭 |
健康结果 + Git 审核 + ZIP/Web/local 结果在审核后汇总为中英双语;复用原 upstream-health
issue,稳定托管区、无变化不编辑、不发评论,完整确认解决才关闭,新问题重开同一 issue。首次迁移保留 #213
现有手动双语内容为历史快照,托管区外人工内容保留;完整 JSON/日志保存在 audit-results 工件 |
| 自动合并的信任与最终 SHA 门禁 | 不能靠“有标签/有回执”证明可合并;原先还错误要求所有语言任务必须存在 | 只接受可信 main
重审得到的完整预期差异,检查当前 main 与最终 SHA;validate、translate、Copilot wait
为具名基线,实际存在的最新 CodeQL/Analyze、statuses、workflow runs
也必须完成且成功,适用检查缺失/失败/进行中均不放行。PR 自带 JSON 或任意标签不能授权 |
| 纯版本例外与真人审核 | 所有字节变化要求第二真人过宽,但也不能用版本号掩盖行为变化 | 保留可独立证明的 SKILL.md 顶层
semver-only 例外:其余字节、文件集和权限均相同才与完全相同 payload 一样无需额外行为批准;其他实质变化仍需最终 SHA
的有权限真人维护者审核,真人审核不能豁免独立机器门禁 |
| hold、冲突、凭据及发布身份 | 不能把配置不足或冲突伪装成更新成功 | hold / 双边修改 / 范围变化 /
未确认许可均暂停。实际发布与合并身份验证为 mashagua;MARKET_MAINTAINER_TOKEN 未配置时只审核,不冒用机器人发
PR。保留分支保护与预期 SHA squash,无 admin 绕过;每轮最多合并一项,本轮不执行合并 |

## 本轮真实案例与限制

- **#358 / Addy**:固定 `8c99fa36d90068c82d547f7c12a9d67a3e95f4ee` →
`e997ac5b9a74eab332d5e9793bb38a38c8cfdd74`。包括
`skills/api-and-interface-design` 在内,根主 MIT
通知未被证明随所选子目录交付;是旧版本已有的缺口。0.6.18 双语文案已由 #358 独立修复,不能把 main 的旧文案误称为该 PR
仍未修复。
- **#359 / Follow Builders**:旧 pin
`22c2e72e1a4bb0fc0f3e19f992fc55615b48989e` 的例外不自动覆盖
`65452b9258f31ed2893734c86481216d2e4105ff`。新 pin 的人工例外、22 文件真实回执及四个 JSON
数据变更由另一 worker 补审,现已合并 main;本 PR 已正常同步,未碰其分支。
- **#360 / Last30Days**:`331025e662756ca51e86dfddcf59969f6dba25a0` →
`7c2e1c2b099b13abd4397910168c4f53e638bb21`,范围
`skills/last30days`。主通知在目录外,bird-search vendor
许可不能替代;真实差异包含授权/配置/网络实现,依赖专项接受不代表完整行为复审。没有删除资源、缩范围或改变交付方式。
- **#361 / Matt Pocock**:上游仍为 `5863806dd4e15c63174bee4e7515a4256792ecfa`
→ `d65391149dbb5fe76478e76fa8d5122b2aa5a70e`;当前候选 head
`4cd8c6a4a31ef4512a871d15a355dd8dcf670cb0`
已补39成员、78条双语并处理34条历史英文回退。本轮实际只读复审确认:当前候选成员缺项0、英文回退0,但39/39安装目录仍未证明携带完整主
MIT 通知。独立 PR 复核记录为39目录109文件均无完整必要通知,旧38也已有缺口;因此保持 Draft,不伪造新回执。
- 对 main 旧登记重放的原失败仍是登记38/解析39;物理 SKILL 39→39、无新增/删除/移动,software-factory
仅因 YAML 修好重新可发现,chief-of-staff 描述另变,yaml 是根开发依赖。**这是历史 main
基线,不是说当前候选没补成员/翻译。**
- 当前候选 validate 真实失败;reviewedRef 不对应目标、旧 receipt.source.ref 不对应目标、旧
receipt.scope38 不覆盖39,是**未签新回执的三项派生错误**,不是三项新许可变更。translate、CodeQL、三个
Analyze 成功;Draft 的 Copilot wait 为 skipped,不称实质审核批准。先解决通知根因并真实复审,不能只改
ref/scope 凑绿灯。
-
证据:[当前PR实际复核说明](https://github.com/desirecore/market/blob/4cd8c6a4a31ef4512a871d15a355dd8dcf670cb0/docs/reviews/mattpocock-skills-pr361-d65391149dbb.md)
·
[JSON记录](https://github.com/desirecore/market/blob/4cd8c6a4a31ef4512a871d15a355dd8dcf670cb0/docs/reviews/mattpocock-skills-pr361-d65391149dbb.json)。


自动通知证明采用有界、保守的直接目录文本匹配;不声称覆盖一切合法非标准许可写法,也不代替真实安装回读或全部行为审查。客户端携带父级通知的实现需要另行授权,并让实际产物、摘要、锁记录、升级和回滚一致;本
PR 不跨仓修改客户端。


实现说明:[docs/upstream-audit-reporting.md](https://github.com/desirecore/market/blob/2bf76eade1644ff4b928c873cbb5d9139a322973/docs/upstream-audit-reporting.md)。现有报告:[issue
#213](https://github.com/desirecore/market/issues/213);当前手动双语不等于持久模板已部署,主线旧任务仍可能覆盖,须本
PR 经审核合入 main 后才生效。

## 最终 SHA 验证

最终
head:`2bf76eade1644ff4b928c873cbb5d9139a322973`。功能提交:`574f9c904da19eb4ce5c970c45b798bc6d3d3f72`、`e0d7ef0d936872f08d8fb6bd20166d98ddf46952`
与 `2bf76eade1644ff4b928c873cbb5d9139a322973`;正常 merge main 提交为
`950ae45cc985f8510a13eb9487896e1d516a8613`。新提交 author/committer 均为
`mashagua <993498039@qq.com>`。

- 完整 `pytest scripts`:**306 passed、397 subtests passed**;仅一条环境 pytest
插件弃用警告。
- `validate_catalog_metadata.py
--require-complete`、`validate-i18n.py`、`translate.py --check`、`git diff
--check`:全部 exit 0。目录原有治理/英文回退警告未冒称已修。
- 同一最终 SHA 的远程 **validate、translate、CodeQL、Analyze
(actions/python/javascript-typescript) 均 success**。
- `wait-for-copilot-review` 最新读取仍 **in_progress**,尚无 review 或行内评论;不冒称已完成
Copilot 审核。

不合并 #354,不部署;不修改 AI News Radar 的五条既有告警,不修改任何技能资源、结构、子项选择或安装方式。
This commit is contained in:
mashagua authored and GitHub committed 2026-11-26 16:45:09 +08:00
1 parent fbbbc63eac
commit 44ab34fe54
21 files changed
+2778 -85

No files matched your search

+1
View File
@@ -74,6 +74,7 @@ jobs:
uv run --quiet scripts/catalog/test_check_upstream_health.py uv run --quiet scripts/catalog/test_check_upstream_health.py
uv run --quiet scripts/catalog/test_propose_upstream_updates.py uv run --quiet scripts/catalog/test_propose_upstream_updates.py
uv run --quiet scripts/catalog/test_audit_skill_update.py uv run --quiet scripts/catalog/test_audit_skill_update.py
uv run --quiet --with pytest --with pyyaml --with jsonschema python -m pytest scripts/catalog/test_tracked_updates.py -q
uv run --quiet scripts/catalog/test_review_workflow.py uv run --quiet scripts/catalog/test_review_workflow.py
- name: Validate catalog metadata - name: Validate catalog metadata
@@ -0,0 +1,45 @@
name: Merge verified upstream updates
on:
workflow_run:
workflows: [i18n Validate, i18n Auto-Translate, Wait for Copilot review, CodeQL]
types: [completed]
schedule:
- cron: '47 * * * *'
workflow_dispatch:
permissions:
contents: read
pull-requests: read
checks: read
statuses: read
actions: read
concurrency:
group: trusted-market-update-merge
cancel-in-progress: false
jobs:
verify-and-merge:
if: github.repository == 'desirecore/market'
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
# workflow_run is privileged: use ONLY current main, never event PR code/artifacts.
- uses: actions/checkout@v4
with:
ref: main
persist-credentials: false
- uses: astral-sh/setup-uv@v3
- name: Reaudit trusted updates and conditionally merge the exact checked head
env:
GH_TOKEN: ${{ secrets.MARKET_MAINTAINER_TOKEN || github.token }}
MAINTAINER_TOKEN_AVAILABLE: ${{ secrets.MARKET_MAINTAINER_TOKEN != '' }}
run: |
merge=()
if [ "$MAINTAINER_TOKEN_AVAILABLE" = true ]; then
merge=(--merge)
else
echo 'Maintainer authentication not configured: verification-only; never impersonate mashagua.' >> "$GITHUB_STEP_SUMMARY"
fi
uv run --quiet scripts/catalog/merge_verified_updates.py "${merge[@]}"
+41 -39
View File
@@ -27,6 +27,8 @@ jobs:
timeout-minutes: 45 timeout-minutes: 45
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
with:
persist-credentials: false
- name: Install uv - name: Install uv
uses: astral-sh/setup-uv@v3 uses: astral-sh/setup-uv@v3
@@ -51,53 +53,53 @@ jobs:
PY PY
cat report.md >> "$GITHUB_STEP_SUMMARY" cat report.md >> "$GITHUB_STEP_SUMMARY"
- name: Update tracking issue
env:
GH_TOKEN: ${{ github.token }}
ACTIONABLE: ${{ steps.check.outputs.actionable }}
UNKNOWN: ${{ steps.check.outputs.unknown }}
HELD: ${{ steps.check.outputs.held }}
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
run: |
set -euo pipefail
label=upstream-health
gh label create "$label" --color D93F0B \
--description "Upstream availability of external catalog entries" 2>/dev/null || true
{
echo "_Updated by [Upstream Health]($RUN_URL) on $(date -u +%Y-%m-%d)._"
echo
echo "Fix entries through a normal PR: repoint or remove \`gone\` entries, correct \`bad-*\` paths, and review upstream changes before bumping \`source.ref\` for \`outdated\` entries (rerun \`scripts/gen-collection-children.py\` for collections); a reviewed decision to keep the current pin or to leave new upstream children undeclared can be recorded in \`<kind>/<id>/upstream-health-hold.json\`. \`unreachable\` means a network error, not a confirmed failure."
echo
cat report.md
} > body.md
issue=$(gh issue list --label "$label" --state open --limit 1 --json number --jq '.[0].number // empty')
if [ "$ACTIONABLE" = "true" ] || [ "$UNKNOWN" = "true" ]; then
if [ -n "$issue" ]; then
gh issue edit "$issue" --body-file body.md
else
gh issue create --title "Upstream health report" --label "$label" --body-file body.md
fi
elif [ -n "$issue" ]; then
closing="All external entries resolve upstream and are current as of $RUN_URL."
if [ "${HELD:-0}" -gt 0 ]; then
closing="All external entries resolve upstream as of $RUN_URL; $HELD finding(s) remain under reviewed holds (see the run summary)."
fi
gh issue comment "$issue" --body "$closing Closing."
gh issue close "$issue"
fi
- name: Propose reviewed-source updates - name: Propose reviewed-source updates
id: propose
env: env:
GH_TOKEN: ${{ github.token }} GH_TOKEN: ${{ secrets.MARKET_MAINTAINER_TOKEN || github.token }}
MAINTAINER_TOKEN_AVAILABLE: ${{ secrets.MARKET_MAINTAINER_TOKEN != '' }}
MARKET_MAINTAINER_LOGIN: mashagua
GIT_CONFIG_COUNT: '1'
GIT_CONFIG_KEY_0: credential.helper
GIT_CONFIG_VALUE_0: '!gh auth git-credential'
run: | run: |
uv run --quiet scripts/catalog/propose_upstream_updates.py results.json --publish --limit 5 --coverage-file coverage.json publish=()
if [ "$MAINTAINER_TOKEN_AVAILABLE" = true ]; then
publish=(--publish)
else
echo 'Maintainer authentication not configured: audit-only, no bot-authored PR fallback.' >> "$GITHUB_STEP_SUMMARY"
fi
uv run --quiet scripts/catalog/propose_upstream_updates.py results.json "${publish[@]}" --limit 5 --coverage-file coverage.json
uv run --quiet scripts/catalog/publish_tracked_updates.py "${publish[@]}" --limit 5 --report-file tracked-results.json
- name: 展示所有技能的覆盖与阻碍 - name: 展示所有技能的覆盖与阻碍
if: always() if: always()
run: | run: |
if [ -f coverage.md ]; then cat coverage.md >> "$GITHUB_STEP_SUMMARY"; else echo '覆盖报告未生成,来源核验未完成。' >> "$GITHUB_STEP_SUMMARY"; fi if [ -f coverage.md ]; then cat coverage.md >> "$GITHUB_STEP_SUMMARY"; else echo '覆盖报告未生成,来源核验未完成。' >> "$GITHUB_STEP_SUMMARY"; fi
- name: 双语审核报告与跟踪 issue / Bilingual audit report and tracking issue
if: always() && steps.check.outcome == 'success'
env:
GH_TOKEN: ${{ github.token }}
PROPOSAL_COMPLETE: ${{ steps.propose.outcome == 'success' }}
run: |
complete=()
if [ "$PROPOSAL_COMPLETE" = true ]; then complete=(--complete); fi
uv run --quiet --with pyyaml python scripts/catalog/unhealthy_report.py --results results.json --coverage coverage.json --tracked tracked-results.json --output unhealthy-report.md "${complete[@]}" --publish
cat unhealthy-report.md >> "$GITHUB_STEP_SUMMARY"
- name: 保留真实逐项审核证据 / Preserve per-item audit evidence
if: always()
uses: actions/upload-artifact@v4
with:
name: audit-results
path: |
results.json
summary.json
coverage.json
coverage.md
tracked-results.json
unhealthy-report.md
if-no-files-found: warn
- name: Fail when an entry is broken - name: Fail when an entry is broken
if: steps.check.outputs.broken == 'true' if: steps.check.outputs.broken == 'true'
run: | run: |
+4
View File
@@ -295,3 +295,7 @@ Read [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md), the resource's own licens
A redistribution mode describes how content is delivered, not a replacement license. Verify the applicable upstream terms before redistribution or production use. A redistribution mode describes how content is delivered, not a replacement license. Verify the applicable upstream terms before redistribution or production use.
The daily upstream-health workflow checks every external pointer and emits a Skill coverage report. Existing installable Git pointers can undergo bounded automated source/license/structured-metadata verification without executing upstream code. Passing snapshots receive an explicit machine reviewer, date, bound ref and `upstream-audit.v1.json`; actual upstream versions and matching sidecar releases are updated without inventing a release date. Catalog and localization checks must pass before creating a normal PR. Licensing, declared prerequisites, presentation or collection-membership changes retain the old review and a blocked draft with an explanation. This is not a software security certification or runtime acceptance, and PRs never auto-merge. Builtin content follows market publication; listing-only ZIP/Web entries are reported as governance blockers rather than silently called current or installable. Existing PRs and holds are preserved. Actions PR creation must be enabled; default-token PR creation does not generally trigger downstream workflows, so checks are run before publishing the update PR. The Copilot metadata-only workflow uses the trusted base context, never checks out PR code, and verifies actual reviews before treating a 422 as already reviewed. The daily upstream-health workflow checks every external pointer and emits a Skill coverage report. Existing installable Git pointers can undergo bounded automated source/license/structured-metadata verification without executing upstream code. Passing snapshots receive an explicit machine reviewer, date, bound ref and `upstream-audit.v1.json`; actual upstream versions and matching sidecar releases are updated without inventing a release date. Catalog and localization checks must pass before creating a normal PR. Licensing, declared prerequisites, presentation or collection-membership changes retain the old review and a blocked draft with an explanation. This is not a software security certification or runtime acceptance, and PRs never auto-merge. Builtin content follows market publication; listing-only ZIP/Web entries are reported as governance blockers rather than silently called current or installable. Existing PRs and holds are preserved. Actions PR creation must be enabled; default-token PR creation does not generally trigger downstream workflows, so checks are run before publishing the update PR. The Copilot metadata-only workflow uses the trusted base context, never checks out PR code, and verifies actual reviews before treating a 422 as already reviewed.
## 可核验的上游自动更新
Git、显式登记的 ZIP/Web 及本地衍生包的发现、审核与受保护合并,参见 [更新自动化说明](docs/verified-update-automation.md)。凭据未配置时只审核;内容变化或本地补丁冲突保留人工复核,不能用标签或 PR 自带回执授权合并。
+298
View File
@@ -0,0 +1,298 @@
{
"schemaVersion": 1,
"autoMerge": "reviewed-or-no-behavior-change",
"requiredChecks": [
"validate",
"translate",
"wait-for-copilot-review"
],
"tracking": {
"amap-jsapi-skill": {
"adapter": "clawhub",
"owner": "lbs-amap",
"slug": "amap-jsapi-skill"
},
"ai-news-radar": {
"adapter": "local-git",
"repoUrl": "https://github.com/LearnPrompt/ai-news-radar.git",
"branch": "master",
"ref": "689395109cc962a27c369bdd6fa50d1e090eb319",
"files": {
"LICENSE": {
"upstream": "LICENSE",
"upstreamSha256": "1eef1394cbdc77865323cb153d3ffc241af74184246ee253ce5bcfd65b61cc0b",
"installedSha256": "1eef1394cbdc77865323cb153d3ffc241af74184246ee253ce5bcfd65b61cc0b",
"installedMode": "100644"
},
"README.md": {
"installedSha256": "fc9dfa6814a06cfab8bafe86aab950abbcf298237cf9a0a1e4bc677cfe4fcfc3",
"installedMode": "100644"
},
"SKILL.md": {
"installedSha256": "dbec05cda7295461a530a67052a434d0092578d9a05693d2cf3a13facd098633",
"upstream": "skills/ai-news-radar/SKILL.md",
"upstreamSha256": "6c9efd6979fcc64ba297ab5a24bd358468e0ee5034b0051fcfbec459a5594422",
"installedMode": "100644"
},
"SKILL.zh-CN.md": {
"installedSha256": "28d1fdd84374e5edf34a8f3b5462ea656b69cab3a6f8c2cc20612001efcaa282",
"installedMode": "100644"
},
"UPSTREAM.md": {
"installedSha256": "d647524b7795d0ff0468cb239f3e6e1f68456b708ffd1919cd2da56b65837f75",
"installedMode": "100644"
},
"agents/openai.yaml": {
"upstream": "skills/ai-news-radar/agents/openai.yaml",
"upstreamSha256": "1fbeab04768ce9d0ea35d8c1ae177f626235c2ec615cf7584688d93ca2606324",
"installedSha256": "1fbeab04768ce9d0ea35d8c1ae177f626235c2ec615cf7584688d93ca2606324",
"installedMode": "100644"
},
"assets/app.js": {
"upstream": "assets/app.js",
"upstreamSha256": "4ee5e351689fb88020c726affdd1bf767bb6b42aa2aa90e6f770f25f1b8eafaa",
"installedSha256": "4ee5e351689fb88020c726affdd1bf767bb6b42aa2aa90e6f770f25f1b8eafaa",
"installedMode": "100644"
},
"assets/icons/apple-touch-icon.png": {
"upstream": "assets/icons/apple-touch-icon.png",
"upstreamSha256": "2a3dbb278f16bf538dbbe29fada7b28dddecc3d51f7506d793964e808850d1b7",
"installedSha256": "2a3dbb278f16bf538dbbe29fada7b28dddecc3d51f7506d793964e808850d1b7",
"installedMode": "100644"
},
"assets/icons/favicon-32.png": {
"upstream": "assets/icons/favicon-32.png",
"upstreamSha256": "70a1aa71a978aafbe06ecb8a78cddf0f1f2c16644b59c5f20ec4a90b3464f6a6",
"installedSha256": "70a1aa71a978aafbe06ecb8a78cddf0f1f2c16644b59c5f20ec4a90b3464f6a6",
"installedMode": "100644"
},
"assets/icons/icon-192.png": {
"upstream": "assets/icons/icon-192.png",
"upstreamSha256": "1a3075115f032bee0005ad02a50dcba0c60006e6fd130caa74816081c001df0c",
"installedSha256": "1a3075115f032bee0005ad02a50dcba0c60006e6fd130caa74816081c001df0c",
"installedMode": "100644"
},
"assets/icons/icon-512.png": {
"upstream": "assets/icons/icon-512.png",
"upstreamSha256": "6b2899f623812c35edc3f3a31a5c942229d6a2369639cd971592f827e24d757f",
"installedSha256": "6b2899f623812c35edc3f3a31a5c942229d6a2369639cd971592f827e24d757f",
"installedMode": "100644"
},
"assets/logo.svg": {
"upstream": "assets/logo.svg",
"upstreamSha256": "89c98d5e8288984f204da770eebb7f0dfc37f3e29daeb58787fd69adfbe9fafd",
"installedSha256": "89c98d5e8288984f204da770eebb7f0dfc37f3e29daeb58787fd69adfbe9fafd",
"installedMode": "100644"
},
"assets/motion.js": {
"upstream": "assets/motion.js",
"upstreamSha256": "b27fae1fd3990aced1c803ce619686eadd888b9059933680b4ffd8e7c5118dcd",
"installedSha256": "b27fae1fd3990aced1c803ce619686eadd888b9059933680b4ffd8e7c5118dcd",
"installedMode": "100644"
},
"assets/og.png": {
"upstream": "assets/og.png",
"upstreamSha256": "21cb49329c88a13b1ff149603dbacd872f206ae9e018e2fc4f86fdf49034f5b1",
"installedSha256": "21cb49329c88a13b1ff149603dbacd872f206ae9e018e2fc4f86fdf49034f5b1",
"installedMode": "100644"
},
"assets/service-status.css": {
"upstream": "assets/service-status.css",
"upstreamSha256": "cbb4e02f81e4f91d7b97d6c9262bccae8f53e831122d976e90cfd85dc525905d",
"installedSha256": "cbb4e02f81e4f91d7b97d6c9262bccae8f53e831122d976e90cfd85dc525905d",
"installedMode": "100644"
},
"assets/service-status.js": {
"upstream": "assets/service-status.js",
"upstreamSha256": "0aa01cd32c346d778badd1ce51636da77188701f989cc2f99921a42810b7a78f",
"installedSha256": "0aa01cd32c346d778badd1ce51636da77188701f989cc2f99921a42810b7a78f",
"installedMode": "100644"
},
"assets/styles.css": {
"upstream": "assets/styles.css",
"upstreamSha256": "889a68cb3c4c1a3bca9181493612c09bc7cea31e8ebb3bfbd4477eca28e49140",
"installedSha256": "3f13df8ac4b8b74ef07bb840bb034fc71fe78ae709308760263e1ec0555a4fd8",
"installedMode": "100644"
},
"assets/view-mode.js": {
"upstream": "assets/view-mode.js",
"upstreamSha256": "77c2f6834fc7e64f31e0c28a302b9c57a7868aa5f6856300d36f7e8905dac8a2",
"installedSha256": "77c2f6834fc7e64f31e0c28a302b9c57a7868aa5f6856300d36f7e8905dac8a2",
"installedMode": "100644"
},
"assets/view-switch.css": {
"upstream": "assets/view-switch.css",
"upstreamSha256": "05b70dd29586a784674f59472f5c9aa5532ac7fe544510ee82fc711a47a0feab",
"installedSha256": "05b70dd29586a784674f59472f5c9aa5532ac7fe544510ee82fc711a47a0feab",
"installedMode": "100644"
},
"classic/assets/app.js": {
"upstream": "classic/assets/app.js",
"upstreamSha256": "08afcfe3e8184f3ab364ae7a8ae39f6e57ee2c376076b866c22aa029ad2c45a9",
"installedSha256": "08afcfe3e8184f3ab364ae7a8ae39f6e57ee2c376076b866c22aa029ad2c45a9",
"installedMode": "100644"
},
"classic/assets/motion.js": {
"upstream": "classic/assets/motion.js",
"upstreamSha256": "90102cd08928d9389fa78dc83a666d58a423202591a3865dd67d78b1cbd95918",
"installedSha256": "90102cd08928d9389fa78dc83a666d58a423202591a3865dd67d78b1cbd95918",
"installedMode": "100644"
},
"classic/assets/styles.css": {
"upstream": "classic/assets/styles.css",
"upstreamSha256": "1d07798dc15c4dd3360496ee2f8865611cba09db4fe3bfaded9a20b00b46cdff",
"installedSha256": "1d07798dc15c4dd3360496ee2f8865611cba09db4fe3bfaded9a20b00b46cdff",
"installedMode": "100644"
},
"classic/index.html": {
"upstream": "classic/index.html",
"upstreamSha256": "beeb670897d9aaadcd90b858b7faad260c4f3130cc8c505b52527bd4576f772b",
"installedSha256": "e7abf1ba871b66b8ec8dc8bfb7fe914e171eb8a0b47aaf76b63cae6b00e16a98",
"installedMode": "100644"
},
"docs/GPT_HANDOFF.md": {
"upstream": "docs/GPT_HANDOFF.md",
"upstreamSha256": "cea73994fee7ed4f4485ddb284d4bc66d55aa862412056ba2831ebeabf71f46e",
"installedSha256": "485274a8cdd6acf50ee28d0eab0c93ba6358dfb3f0bad930a5b67d13e7ef0bd7",
"installedMode": "100644"
},
"docs/ROADMAP.md": {
"upstream": "docs/ROADMAP.md",
"upstreamSha256": "ae5091f2fd10eed5f9e35d5471e4d5c4c70b6cf2ca445cca1db083edb8115934",
"installedSha256": "f28dc96c5dbc88492c978a25f1a0385e4024d604c42618db54c36cdf49ad6be3",
"installedMode": "100644"
},
"docs/SOURCE_COVERAGE.md": {
"upstream": "docs/SOURCE_COVERAGE.md",
"upstreamSha256": "14dc0f660bb5b4d5a89bcfa096ae4aad2d8adea876c5705cd601b9cf4ecc94f0",
"installedSha256": "b3996127def8abeaebaf96f8b7b0c0820e3e0d83bfd6f8a297803d427d1432f5",
"installedMode": "100644"
},
"docs/V2_PRODUCT_BRIEF.md": {
"upstream": "docs/V2_PRODUCT_BRIEF.md",
"upstreamSha256": "ff52e938535276b18d70af846659adfecdf56d105310591bd4c6133a499dd2c3",
"installedSha256": "860fb5d031e5fdff869d753bc8032537f27661aeca9bc1cc938e61609c5c1ca2",
"installedMode": "100644"
},
"feeds/follow.example.opml": {
"upstream": "feeds/follow.example.opml",
"upstreamSha256": "c8f61d59f098f4e0da0de35356b6eae90eb3c4a794b057afd40048bc6ba42ede",
"installedSha256": "c8f61d59f098f4e0da0de35356b6eae90eb3c4a794b057afd40048bc6ba42ede",
"installedMode": "100644"
},
"index.html": {
"upstream": "index.html",
"upstreamSha256": "fac7af098270897f347f46e777a1e8227863fcb2fb642d0f6eead57bce6d2c73",
"installedSha256": "fac7af098270897f347f46e777a1e8227863fcb2fb642d0f6eead57bce6d2c73",
"installedMode": "100644"
},
"personas/README.md": {
"upstream": "personas/README.md",
"upstreamSha256": "3f751906d12eeec8945c6e4e903fb5407103df0c2106f2d589f1d3ac00f9dafd",
"installedSha256": "3f751906d12eeec8945c6e4e903fb5407103df0c2106f2d589f1d3ac00f9dafd",
"installedMode": "100644"
},
"personas/cynic.md": {
"upstream": "personas/cynic.md",
"upstreamSha256": "72a3c6e4b8619f1568d56af45c57df8b7ff06f4fc80afd17b264df9d3903d6cb",
"installedSha256": "72a3c6e4b8619f1568d56af45c57df8b7ff06f4fc80afd17b264df9d3903d6cb",
"installedMode": "100644"
},
"personas/paper-police.md": {
"upstream": "personas/paper-police.md",
"upstreamSha256": "12080a8c861872a214e8a250b63232dea1be53bb87263ed98ff65bd2deb64911",
"installedSha256": "12080a8c861872a214e8a250b63232dea1be53bb87263ed98ff65bd2deb64911",
"installedMode": "100644"
},
"personas/pragmatic.md": {
"upstream": "personas/pragmatic.md",
"upstreamSha256": "d61315341defc8b786aa435dadc19a3fbacd919aa5520644f68addcfd17a79b9",
"installedSha256": "d61315341defc8b786aa435dadc19a3fbacd919aa5520644f68addcfd17a79b9",
"installedMode": "100644"
},
"references/source-intake.md": {
"upstream": "skills/ai-news-radar/references/source-intake.md",
"upstreamSha256": "1e18da6313d647924c68b49bdc86873b829fa343c55f0dd727f240f6e820692c",
"installedSha256": "1e18da6313d647924c68b49bdc86873b829fa343c55f0dd727f240f6e820692c",
"installedMode": "100644"
},
"references/upstream-project-readme.en.md": {
"upstream": "README.en.md",
"upstreamSha256": "4ced637ac7f9040824774d25de5a0bce4bafaa3a4afcef47aa824fe1a00318ec",
"installedSha256": "3f2df29f9b49849768e0996552065faa71caa90dd1ec52697adc39fd4c263da7",
"installedMode": "100644"
},
"references/upstream-project-readme.md": {
"upstream": "README.md",
"upstreamSha256": "660d1359c8ce8cf50e6b051a67de1158353238a4506d06579d9b0ffa5333968c",
"installedSha256": "8b61f8855e925364b4247c1bd33bf6e3364a496927b55d8d9fc1a4b376ac7f5d",
"installedMode": "100644"
},
"references/upstream-skill-readme.md": {
"upstream": "skills/ai-news-radar/README.md",
"upstreamSha256": "cea932f854bbbc8473ec1a7fd58e5018833e338fcd7a645da2a3d9fbe1e6fa64",
"installedSha256": "2bdf8a2375342391b76c457bd9e6104bf53b1a8984a6985a69a3f4da758ba10e",
"installedMode": "100644"
},
"references/v2-method.md": {
"upstream": "skills/ai-news-radar/references/v2-method.md",
"upstreamSha256": "f415f236fce6981e6f05e063f463e8a412e4cd9b964550184f1b3db7b2c4e8b7",
"installedSha256": "f415f236fce6981e6f05e063f463e8a412e4cd9b964550184f1b3db7b2c4e8b7",
"installedMode": "100644"
},
"requirements.txt": {
"upstream": "requirements.txt",
"upstreamSha256": "f206ef31decbffd0ade3fbfebb513158ad27521ee541969e517535865c629ba8",
"installedSha256": "f206ef31decbffd0ade3fbfebb513158ad27521ee541969e517535865c629ba8",
"installedMode": "100644"
},
"scripts/__init__.py": {
"upstream": "scripts/__init__.py",
"upstreamSha256": "c2bbbed5cc8ac8d07249f7d977b61fe2309393444646d0d449b6d7ce7dcf2434",
"installedSha256": "c2bbbed5cc8ac8d07249f7d977b61fe2309393444646d0d449b6d7ce7dcf2434",
"installedMode": "100644"
},
"scripts/ai_relevance.py": {
"upstream": "scripts/ai_relevance.py",
"upstreamSha256": "97d1ea44d04663d21af8ac60ed3b26bd9ee4b55418e6979a31baeea6df0bb4bb",
"installedSha256": "97d1ea44d04663d21af8ac60ed3b26bd9ee4b55418e6979a31baeea6df0bb4bb",
"installedMode": "100644"
},
"scripts/evaluate_source_overlap.py": {
"upstream": "scripts/evaluate_source_overlap.py",
"upstreamSha256": "9558f13ffc310d4d8523f22d77280f5a470f2e5df3c1c9d477461ac91f9d8375",
"installedSha256": "9558f13ffc310d4d8523f22d77280f5a470f2e5df3c1c9d477461ac91f9d8375",
"installedMode": "100644"
},
"scripts/persona_score.py": {
"upstream": "scripts/persona_score.py",
"upstreamSha256": "2076ac04af453de9a8c3704f83941fd8fa47b7c29bd3bc4679ec6ed47f001926",
"installedSha256": "2076ac04af453de9a8c3704f83941fd8fa47b7c29bd3bc4679ec6ed47f001926",
"installedMode": "100644"
},
"scripts/run_daily_brief.py": {
"installedSha256": "e462f272ed6d12626aca05351cfad2041e11788b985e304aa4fbaa5320585817",
"installedMode": "100644"
},
"scripts/update_news.py": {
"upstream": "scripts/update_news.py",
"upstreamSha256": "7cf57bb45f8ea48e731d7dd8b27392c4ec2e5844acfd7c137edf0920e03a1165",
"installedSha256": "7cf57bb45f8ea48e731d7dd8b27392c4ec2e5844acfd7c137edf0920e03a1165",
"installedMode": "100644"
},
"site.webmanifest": {
"upstream": "site.webmanifest",
"upstreamSha256": "5659abfef2d7f05b9a6ace0a876ef8e4ea44e3cc00b0f82fd8b9626feea1d1b9",
"installedSha256": "5659abfef2d7f05b9a6ace0a876ef8e4ea44e3cc00b0f82fd8b9626feea1d1b9",
"installedMode": "100644"
},
"translation-glossary.txt": {
"upstream": "translation-glossary.txt",
"upstreamSha256": "8eb25938e8436c0f989dbb9f6bc9721cba83889bb48d26fde867d385e65b8b4a",
"installedSha256": "8eb25938e8436c0f989dbb9f6bc9721cba83889bb48d26fde867d385e65b8b4a",
"installedMode": "100644"
}
}
}
}
}
+38
View File
@@ -0,0 +1,38 @@
# 上游审核与 unhealthy 报告 / Upstream audit and unhealthy reporting
本机制待 PR #354 合并到 main 后生效;本 PR 不自动合并或部署自身。报告不执行上游脚本,也不是运行验收或软件安全认证。
## 审核边界
- **仓库许可 ≠ 安装交付**:按 source.path 或每个 collection child.path 独立检查。MIT 的完整版权、授权及免责通知必须能与声明的主证据对应;vendor/LICENSE 或单行 SPDX 不能替代主项目通知。README/SKILL 内完整等效通知可以通过,不强求文件名 LICENSE。
- 自动证明仅识别所选目录直接包含的 LICENSE/COPYING/NOTICE/README/SKILL 中的完整等效文本;嵌套、改写、其他非标准许可证据可能被保守转人工,不能据此断言不存在合法许可。声明的 NOTICE 未证明交付会阻断;未声明根 NOTICE 的适用性需要人工确认。
- **精确 pin 例外**:旧 pin 接受过的单行 MIT 例外,即使 README 哈希不变,也不自动扩展到新 pin。新 pin 需要独立人工授权;本更新器不产生这种授权,不改变 listing-only 准入状态。
- **版本和双语**:用真实 SKILL frontmatter、明确插件 manifest 作为对应对象的版本证据;根插件版本不强加给所选子目录技能。只提示文案中出现的确切旧插件版本,需人工确认含义,不替换任意数字。同步检查 entry/catalog 的子项语言镜像;英文回退标为历史信息,不伪称已翻译。
- **直接 Git 对象差异**:报告安装范围完整路径差异,不依赖 GitHub compare 的 300 文件截断列表。授权/凭据/配置/网络相关命名的实现文件变化,保守转人工。这是复核提示,不是已证实漏洞,更不是全部行为审核。原有最终 SHA 的实际差异及真人行为审核门禁不变。
- **失败分层**:原流水线实际失败、失败点后的未完成阶段、独立静态发现、人工待审、历史遗留、本次引入分别展示。开发依赖与所选技能运行依赖不混为一谈;YAML 修复后的重新发现不叫新增物理文件。解析器不可靠时不得认定通过。
- **真实回执**:审核失败不生成成功回执;后续目录校验失败时恢复真实旧回执,独立保存失败命令与输出。ZIP/Web/local 的临时物化 Git ID 不暴露为真实来源 pin。
## 自动维护与稳定展示
日程、发布身份、凭据和最终 SHA 合并保护不变。Git 每轮最多审核 5 个新候选,另可只读复审 5 个已有 PR;不修改已有 PR 的内容。ZIP/Web/local 使用同一套保守门禁并输出真实结果。预算之外明确未检查。
Git 提案 coverage、ZIP/Web/local 的 tracked-results 和来源健康结果汇总为中英双语报告;工作流在提案审核之后同步原 upstream-health issue,并保留完整 audit-results 工件。大报告只截断 issue 展示,不截断 JSON 证据或声称省略部分已通过。
托管区为 `<!-- market-upstream-health:begin -->` 到 `<!-- market-upstream-health:end -->`。首次迁移把现有手动双语正文保留为明确标注的历史快照,之后只更新托管区,保留人工前后文。无时间戳/run URL 驱动的每日重复编辑,不发评论;无实质变化不更新。已解决且检查完整才关闭,出现新问题重开同一 issue;不完整、网络未知或未审核的更新不得闭环。原本 listing-only 或未登记版本源本身不是新失效,来源状态另行报告。
## 当前实例的核对口径
- #358:目标 e997ac5b9a74eab332d5e9793bb38a38c8cfdd74,26 个子项的根主 MIT 通知未被自动证明随所选目录交付;包括只有 SKILL.md 的 skills/api-and-interface-design。旧 pin 已有此缺口。0.6.18 文案另由 #358 修复,不把 main 旧文案当成本次新引入。
- #359:22c2e72e1a4bb0fc0f3e19f992fc55615b48989e 的旧例外不可自动继承到 65452b9258f31ed2893734c86481216d2e4105ff。另一个人工修复 PR 已为新 pin 补明确例外与 22 文件审计;这是新的人工决定,不是旧例外自动扩大。来源四个 JSON 数据文件变化不能授权放宽许可门槛。
- #360:所选 skills/last30days 不包含根主 MIT;bird-search 的 vendor 许可不是主通知。直接固定对象差异涉及授权/配置/网络实现,依赖哈希接受不代替行为审核。保持原来源、资源及安装方式。
- #361:物理 SKILL 39→39;软件工厂原文件 YAML 修好后重新可发现,使市场登记38与解析39不一致;chief-of-staff 简介及双语派生目录需复审;新增 yaml 是根开发依赖。实际原失败在 collection gate,后续未完成,不能写成全套测试通过。所选子项主通知交付还是独立的历史问题。
适用安装器证据由独立复核提供:desirecore dev `e817d57e819975052c5da610874b7747de18b7c8` 的 market-install.ts L406/L442、source-fetch.ts L578–581、skill-staging.ts L26–74 与 market.ts L424–455。当前未发现市场元数据能无声补父级通知的合法开关。任何客户端通知携带方案均需另行授权、摘要/锁记录覆盖和实际安装回读;本 PR 不跨仓实现、不改上游结构或资源。
## 已修订候选 PR 与可信 main 重放必须分开
已有 PR 的只读复审还读取精确 PR head 的 entry、sidecar、旧回执和实时检查;不 checkout 或执行候选代码,不信任这些 JSON 授权发布。表格标注 `trusted-main-replay` 与 `existing-pr-candidate@<head>`。对 main 旧登记重放的失败,不得说成已修订候选 PR 仍存在同样的旧文案/成员错误。
候选 reviewedRef 不匹配、receipt.source.ref 不匹配、receipt.source.paths 不覆盖当前登记,明确标记为“未签新回执的派生错误”;与安装通知缺口这个根本阻碍分层。实时检查失败另列,不把所有 CI 问题都归因于旧回执;未完成检查明确未完成。读取失败或检查超过分页预算不代表通过,也不阻塞其他独立候选继续被检查。
#361 后续修订 head `4cd8c6a4a31ef4512a871d15a355dd8dcf670cb0` 已补39成员、78条双语及历史回退说明;其真实文档见该 PR 的 `docs/reviews/mattpocock-skills-pr361-d65391149dbb.md` / `.json`。39个目录共109文件仍未携带必要完整主 MIT 通知(旧38也已有缺口),因此保持 Draft、不伪造新回执。旧 reviewedRef、旧回执 pin、38范围不足39属于未签回执的派生错误,不是额外三项上游许可变化。原38/解析39失败是 main 基线重放,不再说成此修订 head 未补成员。
+134
View File
@@ -0,0 +1,134 @@
# Verified upstream updates
This is update automation, not automatic first admission, runtime acceptance or a
security certification. The issue tracker remains enabled and is independent of
admission evidence. No credentials, private feeds or user tokens belong here.
## Trusted inputs and scope
* The daily upstream-health job still checks Git pointers. The Git proposer uses
exact old/new SHA, the existing delta auditor and the old admitted evidence.
* `config/verified-updates.v1.json` adds explicit tracking for non-pointer/local
sources. Currently registered: the owner-qualified ClawHub AMap package and
the local AI News Radar edition. No unregistered source is guessed.
* `clawhub` verifies the registered owner, gets an explicit stable latest version,
downloads its version-specific ZIP and verifies the old pinned digest again.
Registry MIT-0 metadata is **not** permission to override package MIT evidence.
* `github-file` resolves a configured repository/branch/path to an immutable
commit, then retrieves that exact raw file. This is the Web discovery adapter.
* `github-release` selects one explicitly configured asset from an actual stable
GitHub release, never an inferred version string. Mutable assets whose old
bytes no longer match the admitted digest are blocked.
* Automatic artifact auditing currently supports root-layout packages. A nested
install scope needs an explicitly reviewed layout adapter. Arbitrary hosts,
symlinks, executable ZIP entries, path traversal, duplicate/case-colliding
names, encrypted archives and over-budget artifacts fail closed.
* A new hash is identification only. Old/new bytes undergo the existing license,
notice, dependency, frontmatter and metadata delta audit. Receipts name the
actual SHA-256/upstream SHA; temporary Git objects only transport comparisons.
For a new Web source, add a reviewed tracking entry such as:
```json
{"adapter":"github-file","repo":"example/project","branch":"main","path":"SKILL.md"}
```
A release ZIP uses `adapter: github-release`, `repo`, and an exact `asset` name.
The old market pointer/digest/admission must already be valid. These examples do
not enable first-time installs or authorize any unreviewed source.
## Local editions
The local-git map records the exact upstream SHA, upstream path/hash, installed
path/hash/mode, and every market-only wrapper. No newly discovered files are
silently imported. Missing/moved files, added upstream license/notice obligations,
changed permissions and mapping drift block advancement. Unmodified imported
files can be replaced; a file changed by both upstream and market is a conflict,
never a blind overwrite. Market wrappers/translations remain intact.
AI News Radar tracks the actual upstream `master` branch. Its existing generator
and the five previously reported alerts are not changed by this tooling PR.
Real read-only discovery currently detects a conflict in locally formatted CSS
(`assets/styles.css`); the safe result is a draft/manual reconciliation, not
an overwritten wrapper or a claim that the newer upstream already passed.
## Publication and merge authority
Both publishers verify `gh api user` is `mashagua`; published commits use the
maintainer's designated identity. Configure an appropriately scoped maintainer
credential as the Actions secret `MARKET_MAINTAINER_TOKEN` through approved secret
management. This change neither creates nor reads credential values. With no
credential the workflows run audit/verification only; there is no bot-identity
fallback. Checkout credentials are not persisted; publishing uses an ephemeral
git credential helper environment. The issue-reporting step retains the normal
workflow token and its existing behavior.
The merge workflow runs after validation-related workflow completions, hourly
at minute 47, and manually. It only checks out **current main**, not PR files or
workflow artifacts; it never runs PR/upstream code. Labels and PR JSON are not
trust roots. For each same-repository maintainer update PR it:
1. Independently rediscovers/re-fetches the target and recomputes the complete
allowed proposal using trusted-main policy and special-review records.
2. Requires the complete PR diff to equal that result. Tooling/workflow changes,
changed review exceptions, foreign paths or forged receipts cannot enter.
3. Automatically clears byte/mode-identical installed payloads and proven
top-level `SKILL.md` semver-only changes (all other bytes, inventory and modes
identical). A version bump alone no longer needs a second human or a special
approval marker. This is not a behavioral security audit: instructions, scripts,
dependencies, license/NOTICE and install-scope changes are not covered by that
proof. Substantive installed-content changes still need an **APPROVED human
maintainer review on the exact head**, with:
`market-reviewed-no-expansion: <full-head-SHA>`.
The reviewer must be a different non-bot user with write/maintain/admin access;
stale/dismissed/self reviews do not count. This clearance cannot override
license, dependency, inventory, permission or receipt failures. No PR JSON,
label or timeout of the Copilot wait check serves as behavioral approval.
4. Requires all applicable check/context results complete and successful on the
exact final head, including mandatory validate, translate and Copilot wait. CodeQL/Analyze
are required to pass when actually scheduled, not required to exist on a
JSON-only update where GitHub does not schedule them; outstanding changes-requested reviews block. No ignored CodeQL failures.
5. Requires current-base ancestry, a clean server state, and active strict
server-side up-to-date rules for validate/translate to close the base race.
The merge API binds the expected head SHA, uses squash, and has no bypass.
6. Merges at most one PR per run, then stops because main has advanced. Behind
branches remain held for a normal merge update and new final-head checks.
Thus this does **not** promise unreviewed autonomous merging of arbitrary changed
skill scripts/prompts. A real exact-head human no-expansion review is the
additional behavioral authority; automation does not invent that attestation. This mechanism PR itself is outside the allowed diff and must
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
become drafts/manual findings. Nothing automatically promotes listing-only.
## Offline checks
```sh
uv run scripts/catalog/validate_catalog_metadata.py --require-complete
uv run scripts/i18n/validate-i18n.py
uv run scripts/i18n/translate.py --check
uv run --with pytest --with jsonschema --with pyyaml --with 'lxml>=5.3,<7' --with 'defusedxml>=0.7' python -m pytest scripts
```
`uv run scripts/catalog/publish_tracked_updates.py` performs real discovery and
audit planning without publication. `merge_verified_updates.py` defaults to
verification-only and must run from current main; `--merge` additionally requires
the maintainer credential, collaborator-permission read access and every gate above. Do not run publishing/merge flags
as a smoke test against real PRs.
## Direction-review correction (2026-11-25)
The original implementation incorrectly required every CodeQL language job on
all updates, including JSON-pointer changes that do not schedule those jobs.
Only baseline jobs are mandatory by name; every latest applicable returned check,
status and workflow run must still succeed. No CodeQL failure is ignored.
The byte-change gate was also too broad: an independently proven SKILL version-only
change is now automatic. This deliberately does not promise that metadata checks
can prove arbitrary upstream script/instruction behavior safe. Expanding that
coverage needs a real behavioral review mechanism, not deletion of the safeguard.
Identity verification, trusted-main re-audit, local-patch preservation, finite
budgets, exact-head binding, strict server rules and no-admin/no-force stay intact.
+45 -3
View File
@@ -272,7 +272,7 @@ def dependency_identity(repo: Path, ref: str, path: str, record):
return record[:2] return record[:2]
def audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict, def _audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict,
observed_at: str | None = None, special_review: dict | None = None) -> tuple[dict, dict, dict]: observed_at: str | None = None, special_review: dict | None = None) -> tuple[dict, dict, dict]:
old, new = result['ref'], result['head'] old, new = result['ref'], result['head']
if not all(re.fullmatch('[0-9a-f]{40}', ref) for ref in (old, new)): if not all(re.fullmatch('[0-9a-f]{40}', ref) for ref in (old, new)):
@@ -529,8 +529,50 @@ def audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict,
return updated, metadata, report return updated, metadata, report
def audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict,
observed_at: str | None = None, special_review: dict | None = None, candidate_view: dict | None = None):
from update_diagnostics import inspect_snapshots, candidate_consistency
if not all(isinstance(result.get(k), str) and re.fullmatch('[0-9a-f]{40}', result[k]) for k in ('ref', 'head')):
return _audit_snapshots(repo, entry, sidecar, result, observed_at, special_review)
findings = []
try:
findings = inspect_snapshots(repo, entry, sidecar, result, special_review)
if candidate_view:
candidate_rows, valid_source = candidate_consistency(entry, sidecar, result, candidate_view)
findings.extend(candidate_rows)
if valid_source:
independent = inspect_snapshots(repo, candidate_view['entry'], candidate_view['metadata'], result)
for row in independent:
row['basis'] = 'existing-pr-candidate@' + candidate_view['head']
if row['gate'] == 'description-and-locales':
row['reason'] = '上游简介曾变化;此行是当前 PR 文案的独立人工复核要求,不表示 main 的旧文案错误仍存在于已修订 PR。 / Upstream description changed; this is independent semantic review of the current candidate, not a claim that old main copy remains stale in a repaired PR.'
findings.extend(independent)
except (ValueError, TypeError, KeyError, AttributeError, OSError, RuntimeError, subprocess.SubprocessError) as error:
findings = [dict(id=entry.get('id', '?'), path='.', oldRef=result.get('ref', '?'),
newRef=result.get('head', '?'), gate='independent-static-diagnostics',
state='not_checked', origin='unknown', reason=str(error),
repair='静态诊断未完成,人工检查并重跑;不能假设通过。 / Complete diagnostics and rerun; never assume success.')]
try:
output = _audit_snapshots(repo, entry, sidecar, result, observed_at, special_review)
except AuditBlocked as error:
pipeline = dict(id=entry.get('id', '?'), path='.', oldRef=result.get('ref', '?'),
newRef=result.get('head', '?'), gate='actual-pipeline-failure', state='blocked',
origin='unknown', reason=str(error),
repair='修复实际失败门槛后重跑;其后流水线未完成,独立静态发现不代表后续检查已通过。 / Fix this gate and rerun; downstream pipeline stages did not complete. Independent findings are not downstream passes.')
remaining = {**pipeline, 'gate': 'remaining-pipeline', 'state': 'not_checked',
'reason': '实际失败点之后的流水线未完成;独立静态检查不等于后续流水线通过。 / Pipeline stages after the actual failure did not complete; independent static findings are not downstream passes.'}
error.findings = [pipeline, remaining, *findings]
raise error
blockers = [r for r in findings if r['state'] in ('blocked', 'manual_review', 'not_checked')]
if blockers:
error = AuditBlocked('安装通知、精确 pin 例外或元数据一致性需处理 / Installed notices, exact-pin exception or metadata consistency needs review: ' + '; '.join(r['gate'] + ': ' + r['path'] for r in blockers))
error.findings = findings
raise error
return output
def audit_update(entry: dict, sidecar: dict, result: dict, def audit_update(entry: dict, sidecar: dict, result: dict,
special_review: dict | None = None) -> tuple[dict, dict, dict]: special_review: dict | None = None, candidate_view: dict | None = None) -> tuple[dict, dict, dict]:
url = entry['source']['repoUrl'] url = entry['source']['repoUrl']
if not re.fullmatch(r'https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\.git)?/?', url): if not re.fullmatch(r'https://github\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\.git)?/?', url):
raise AuditBlocked('自动获取仅使用已登记的 GitHub HTTPS 来源') raise AuditBlocked('自动获取仅使用已登记的 GitHub HTTPS 来源')
@@ -538,4 +580,4 @@ def audit_update(entry: dict, sidecar: dict, result: dict,
repo = Path(temporary) repo = Path(temporary)
git(repo, 'init', '--quiet') git(repo, 'init', '--quiet')
git(repo, 'fetch', '--quiet', '--no-tags', '--depth=1', url, result['ref'], result['head']) git(repo, 'fetch', '--quiet', '--no-tags', '--depth=1', url, result['ref'], result['head'])
return audit_snapshots(repo, entry, sidecar, result, special_review=special_review) return audit_snapshots(repo, entry, sidecar, result, special_review=special_review, candidate_view=candidate_view)
+11 -5
View File
@@ -16,14 +16,20 @@ def validate_record(metadata: dict, record: dict) -> list[str]:
content = metadata.get('provenance', {}).get('content', {}) content = metadata.get('provenance', {}).get('content', {})
if record.get('schemaVersion') != 1 or record.get('reviewer') != REVIEWER: if record.get('schemaVersion') != 1 or record.get('reviewer') != REVIEWER:
errors.append('缺少受支持的机器审核身份/回执版本') errors.append('缺少受支持的机器审核身份/回执版本')
if (metadata.get('identity', {}).get('kind') != 'skill' or content.get('kind') != 'git' kind = content.get('kind')
or not isinstance(content.get('ref'), str) or not re.fullmatch('[0-9a-f]{40}', content['ref'])): digest = content.get('ref') if kind == 'git' else content.get('sha256')
errors.append('该机器审核契约仅适用于固定 Git Skill 来源') pattern = '[0-9a-f]{40}' if kind == 'git' else '[0-9a-f]{64}'
if (metadata.get('identity', {}).get('kind') != 'skill' or kind not in ('git', 'zip', 'web')
or not isinstance(digest, str) or not re.fullmatch(pattern, digest)):
errors.append('该机器审核契约仅适用于固定 Git/ZIP/Web Skill 来源')
source = record.get('source', {}) source = record.get('source', {})
if not isinstance(source, dict) or source.get('url') != content.get('url') or source.get('ref') != content.get('ref'): if not isinstance(source, dict) or source.get('url') != content.get('url') or source.get('ref') != digest:
errors.append('回执来源必须与当前 provenance 完全一致') errors.append('回执来源必须与当前 provenance 完全一致')
elif not isinstance(source.get('previousRef'), str) or not re.fullmatch('[0-9a-f]{40}', source['previousRef']) or source.get('previousRef') == source.get('ref'): elif not isinstance(source.get('previousRef'), str) or not re.fullmatch(pattern, source['previousRef']) or source.get('previousRef') == source.get('ref'):
errors.append('回执必须绑定不同的旧、新固定快照') errors.append('回执必须绑定不同的旧、新固定快照')
if kind in ('zip', 'web') and (source.get('kind') != kind or not isinstance(source.get('previousUrl'), str)
or not source['previousUrl'].startswith('https://')):
errors.append('ZIP/Web 回执必须绑定类型和旧地址')
children = metadata.get('spec', {}).get('collection', {}).get('children', []) children = metadata.get('spec', {}).get('collection', {}).get('children', [])
paths = [child.get('path') for child in children] if children else [content.get('path', '')] paths = [child.get('path') for child in children] if children else [content.get('path', '')]
if not all(isinstance(path, str) for path in paths): if not all(isinstance(path, str) for path in paths):
+35 -13
View File
@@ -417,37 +417,59 @@ def render_text(results: list[dict]) -> str:
return "\n".join(rows) return "\n".join(rows)
def bilingual_detail(status: str, detail: str) -> str:
explanation = {
'stale-hold': '原暂缓决定需重新审核;不自动解除 hold',
'upstream-path-change': '上游当前路径变化,但固定版本安装仍可解析;更新前审核路径',
'bad-path': '固定版本所选路径缺少有效 SKILL.md,需修正路径',
'new-skill': '以下是可发现但尚未登记的路径;不代表物理文件本次新增,需逐项审核',
'outdated': '存在上游差异,须审核后通过 PR 更新,不代表已经审核通过',
'gone': '来源已报告不可用,需核实并修正或移除',
'unreachable': '网络或读取错误,结果未知,不是已确认失效',
'bad-branch': '登记分支在上游不存在,需核实并修正',
'bad-ref': '无法读取登记的固定版本,需核实精确引用',
'unpinned': '未固定不可变版本,需审核并固定来源',
'held': '保留已审核暂缓决定,当前不推进更新',
'ok': '本轮来源可解析,未发现需处理的上游差异',
}.get(status, '按原始证据核实并人工处理,不能假设通过')
if 'has no SKILL.md' in detail:
explanation += ';原始详情所列路径缺少 SKILL.md'
if 'upstream changed within the installed scope since' in detail:
explanation += ';所列旧 pin 之后安装范围内容已变化'
return explanation + ' / ' + detail
def render_markdown(results: list[dict]) -> str: def render_markdown(results: list[dict]) -> str:
counts = {s: 0 for s in ORDER} counts = {s: 0 for s in ORDER}
for r in results: for r in results:
counts[ORDER[worst(r)]] += 1 counts[ORDER[worst(r)]] += 1
summary = " · ".join(f"{s}: {n}" for s, n in counts.items() if n) summary = " · ".join(f"{s}: {n}" for s, n in counts.items() if n)
out = [f"Checked {len(results)} external entries. {summary}", ""] out = [f"已检查 {len(results)} 个外部条目 / Checked {len(results)} external entries. {summary}", ""]
sections = [ sections = [
("Broken — installation fails", BROKEN), ("失效——安装失败 / Broken — installation fails", BROKEN),
("Unreachable — network error, status unknown", ("unreachable",)), ("无法访问——网络错误、状态未知 / Unreachable — network error, status unknown", ("unreachable",)),
("Stale holds — re-review", ("stale-hold",)), ("暂缓决定过期——需重审 / Stale holds — re-review", ("stale-hold",)),
("Upstream path changes — pinned installation still resolves", ("upstream-path-change",)), ("上游路径变化——固定版本仍可解析 / Upstream path changes — pinned installation still resolves", ("upstream-path-change",)),
("Undeclared upstream skills", ("new-skill",)), ("尚未登记的上游技能 / Undeclared upstream skills", ("new-skill",)),
("Updates available", ("outdated",)), ("有可用更新 / Updates available", ("outdated",)),
("Unpinned", ("unpinned",)), ("未固定版本 / Unpinned", ("unpinned",)),
("Reviewed holds — not actionable", ("held",)), ("已审核暂缓——不推进 / Reviewed holds — not actionable", ("held",)),
] ]
for title, statuses in sections: for title, statuses in sections:
rows = [(r, i) for r in results for i in r["issues"] if i["status"] in statuses] rows = [(r, i) for r in results for i in r["issues"] if i["status"] in statuses]
if not rows: if not rows:
continue continue
out += [f"### {title} ({len(rows)})", "", "| Status | Entry | Detail |", "|---|---|---|"] out += [f"### {title} ({len(rows)})", "", "| 状态 / Status | 条目 / Entry | 原因及处理 / Reason and action |", "|---|---|---|"]
for r, i in sorted(rows, key=lambda x: (ORDER.index(x[1]["status"]), x[0]["id"])): for r, i in sorted(rows, key=lambda x: (ORDER.index(x[1]["status"]), x[0]["id"])):
detail = i["detail"].replace("|", "\\|") detail = bilingual_detail(i["status"], i["detail"]).replace("|", "\\|")
compare = compare_url(r["url"], r.get("ref"), r.get("head")) compare = compare_url(r["url"], r.get("ref"), r.get("head"))
if i["status"] == "outdated" and compare: if i["status"] == "outdated" and compare:
detail = f"[{r['ref'][:7]} → {r['head'][:7]}]({compare})" detail = "审核差异后再更新 / Review before updating: " + f"[{r['ref'][:7]} → {r['head'][:7]}]({compare})"
out.append(f"| `{i['status']}` | [{r['kind']}/{r['id']}]({r['url']}) | {detail} |") out.append(f"| `{i['status']}` | [{r['kind']}/{r['id']}]({r['url']}) | {detail} |")
out.append("") out.append("")
ok = sorted(r["id"] for r in results if worst(r) == ORDER.index("ok")) ok = sorted(r["id"] for r in results if worst(r) == ORDER.index("ok"))
if ok: if ok:
out += [f"<details><summary>OK ({len(ok)})</summary>", "", ", ".join(f"`{i}`" for i in ok), "", "</details>"] out += [f"<details><summary>正常 / OK ({len(ok)})</summary>", "", ", ".join(f"`{i}`" for i in ok), "", "</details>"]
return "\n".join(out) return "\n".join(out)
+258
View File
@@ -0,0 +1,258 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml>=6.0"]
# ///
"""Trusted-base, fail-closed exact-head update merge gate. Labels/receipts are NOT authority.
Never checkout/import/run PR files. Recompute proposals from main plus independently
fetched upstream bytes, then compare the entire proposed diff. No admin bypass.
"""
from __future__ import annotations
import argparse
import base64
import copy
import json
import re
import subprocess
import tempfile
from pathlib import Path
from audit_skill_update import AuditBlocked, audit_update, git, tree
from automated_review import validate_record
from tracked_updates import CONFIG, LOGIN, check_identity, discover_target, gh, load_config, plan, version_only_change
ROOT = Path(__file__).resolve().parents[2]
REPO = 'desirecore/market'
def api(path):
return json.loads(gh('api',path))
def pages(path, field=None):
result=json.loads(gh('api','--paginate','--slurp',path))
return [item for page in result for item in (page[field] if field else page)]
def read_json(ref,path):
obj=api(f'repos/{REPO}/contents/{path}?ref={ref}')
if obj.get('encoding')!='base64':
raise AuditBlocked('candidate metadata is not a bounded file')
return json.loads(base64.b64decode(obj['content']))
def canonical(value):
result=copy.deepcopy(value)
if not isinstance(result,dict):
return result
if 'reviewedAt' in result:
result['reviewedAt']='<audit-time>'
if 'governance' in result:
result['governance']['compliance']['reviewedAt']='<audit-day>'
for key in ('reviewedAt','catalogUpdatedAt','upstreamObservedAt'):
field=result.get('timestamps',{}).get(key)
if isinstance(field,dict) and 'value' in field:
field['value']='<audit-time>'
return result
def checks_pass(checks, statuses, required):
by_name={c['name']:c for c in sorted(checks,key=lambda c:c.get('id',0))}
if not set(required)<=set(by_name):
return False
for name in required:
app='github-advanced-security' if name=='CodeQL' else 'github-actions'
if by_name[name].get('app',{}).get('slug')!=app:
return False
latest_statuses={}
for status in sorted(statuses,key=lambda s:s.get('id',0)):
latest_statuses[status.get('context','')]=status
# Every latest applicable check/context, not only required names, must be green.
return (bool(checks) and all(c.get('status')=='completed' and c.get('conclusion')=='success' for c in by_name.values())
and all(s.get('state')=='success' for s in latest_statuses.values()))
def workflow_runs_pass(runs):
latest={}
for run in sorted(runs,key=lambda r:r.get('id',0)):
latest[run.get('workflow_id',run.get('name'))]=run
return bool(latest) and all(r.get('status')=='completed' and r.get('conclusion')=='success' for r in latest.values())
def trusted_pr(pr):
return (pr.get('state')=='open' and not pr.get('draft') and not pr.get('merged')
and pr.get('user',{}).get('login')==LOGIN and pr.get('base',{}).get('ref')=='main'
and pr.get('base',{}).get('repo',{}).get('full_name')==REPO
and pr.get('head',{}).get('repo',{}).get('full_name')==REPO)
def git_plan(root,item_id,head,reviewed=False):
folder=root/'skills'/item_id
entry=json.loads((folder/'entry.json').read_text())
metadata=json.loads((folder/'catalog-metadata.v1.json').read_text())
source=entry['source']
remote=subprocess.run(['git','ls-remote',source['repoUrl'],('refs/heads/'+source['repoBranch']) if source.get('repoBranch') else 'HEAD'],check=True,capture_output=True,text=True).stdout.split()
if not remote or remote[0]!=head:
raise AuditBlocked('upstream HEAD moved; a fresh proposal/audit is required')
review_path=folder/'special-review.v1.json'
review=json.loads(review_path.read_text()) if review_path.exists() else None
if review and (review.get('excludePaths') or any(k.startswith('accepted') for k in review)):
raise AuditBlocked('special exceptions require human review, not automatic merge')
updated,sidecar,report=audit_update(entry,metadata,{'ref':source['ref'],'head':head},special_review=review)
# Do not infer unchanged payload from the PR's own JSON. Read actual pinned trees.
with tempfile.TemporaryDirectory(prefix='market-merge-delta-') as tmp:
repo=Path(tmp)
git(repo,'init','--quiet')
git(repo,'fetch','--quiet','--no-tags','--depth=1',source['repoUrl'],source['ref'],head)
paths=[c['path'] for c in entry.get('children',[])] or [source.get('path','')]
budgets=(review or {}).get('budgetExemptPaths',[])
for path in paths:
before,after=tree(repo,source['ref'],path,[],budgets),tree(repo,head,path,[],budgets)
if set(before)!=set(after) or any(before[p][0]!=after[p][0] for p in before):
raise AuditBlocked('installed file scope or permissions changed; explicit policy review required')
if before!=after and not reviewed:
for name in before:
if before[name] == after[name]:
continue
old_bytes = git(repo, 'show', source['ref'] + ':' + name)
new_bytes = git(repo, 'show', head + ':' + name)
if not version_only_change(old_bytes, new_bytes, name):
raise AuditBlocked('behavioral payload changed: exact-head maintainer no-expansion review required')
return {f'skills/{item_id}/entry.json':updated,f'skills/{item_id}/catalog-metadata.v1.json':sidecar,
f'skills/{item_id}/upstream-audit.v1.json':report}
def assess(root,pr,cfg,reviewed=False):
if not trusted_pr(pr):
raise AuditBlocked('not a designated-maintainer same-repository update PR')
branch=pr['head']['ref']
prefix='tracked-updates/' if branch.startswith('tracked-updates/') else 'updates/'
if not branch.startswith(prefix):
raise AuditBlocked('not an update branch')
# Bind id against trusted main's real IDs; never derive arbitrary filesystem paths.
ids=[p.name for p in (root/'skills').iterdir() if p.is_dir()]
matches=[i for i in ids if branch.startswith(prefix+i+'-')]
if len(matches)!=1:
raise AuditBlocked('ambiguous/unregistered update id')
item_id=matches[0]
if (root/'skills'/item_id/'upstream-health-hold.json').exists():
raise AuditBlocked('held update')
if prefix=='tracked-updates/':
target=discover_target(root,item_id,cfg['tracking'][item_id])
result=plan(root,item_id,cfg,target)
if result is None or (not (result[1].get('identicalInstalledPayload') is True or result[1].get('versionOnlyInstalledPayload') is True) and not reviewed):
raise AuditBlocked('installed payload changed or proposal stale; manual review required')
expected={p:json.loads(b) if p.endswith('.json') else b for p,b in result[0].items()}
else:
proposed=read_json(pr['head']['sha'],f'skills/{item_id}/entry.json')
expected=git_plan(root,item_id,proposed['source']['ref'],reviewed=reviewed)
files=pages(f"repos/{REPO}/pulls/{pr['number']}/files?per_page=100")
if len(files)!=len(expected) or {f['filename'] for f in files}!=set(expected) or any(f['status'] in ('removed','renamed') for f in files):
raise AuditBlocked('candidate diff differs from independently regenerated scope')
for path,value in expected.items():
if canonical(read_json(pr['head']['sha'],path))!=canonical(value):
raise AuditBlocked('candidate content differs from fresh trusted-base audit')
metadata=read_json(pr['head']['sha'],f'skills/{item_id}/catalog-metadata.v1.json')
report=read_json(pr['head']['sha'],f'skills/{item_id}/upstream-audit.v1.json')
if validate_record(metadata,report):
raise AuditBlocked('candidate receipt binding is invalid')
return True
def reviewed_no_expansion(pr,reviews):
"""Only a real human maintainer's APPROVED review on this exact head grants
behavioral clearance. A PR body, label, receipt or author self-review cannot.
License/dependency/scope audits still run independently and cannot be waived.
"""
latest={}
for review in reviews:
if review.get('state') in ('APPROVED','CHANGES_REQUESTED','DISMISSED'):
latest[review['user']['login']]=review
if any(r['state']=='CHANGES_REQUESTED' for r in latest.values()):
return False
marker='market-reviewed-no-expansion: '+pr['head']['sha']
for login,review in latest.items():
if (login==pr['user']['login'] or review['state']!='APPROVED'
or review.get('commit_id')!=pr['head']['sha']
or review.get('user',{}).get('type')!='User'
or marker not in (review.get('body') or '').splitlines()
or not re.fullmatch(r'[A-Za-z0-9-]+',login)):
continue
permission=api(f'repos/{REPO}/collaborators/{login}/permission')
if permission.get('permission') in ('admin','maintain','write'):
return True
return False
def strict_updates_required(rules):
for rule in rules:
params = rule.get('parameters') or {}
names = {c.get('context') for c in params.get('required_status_checks', [])}
if (rule.get('type') == 'required_status_checks'
and params.get('strict_required_status_checks_policy') is True
and {'validate', 'translate'} <= names):
return True
return False
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--merge',action='store_true')
args=parser.parse_args()
if args.merge:
check_identity()
cfg=load_config(ROOT)
base=api(f'repos/{REPO}/branches/main')['commit']['sha']
local=subprocess.run(['git','rev-parse','HEAD'],cwd=ROOT,check=True,capture_output=True,text=True).stdout.strip()
if local!=base:
raise AuditBlocked('trusted checkout is not current main; rerun on fresh main')
for summary in pages(f'repos/{REPO}/pulls?state=open&base=main&per_page=100'):
if not summary.get('head',{}).get('ref','').startswith(('updates/','tracked-updates/')):
continue
number=summary['number']
try:
pr=api(f'repos/{REPO}/pulls/{number}')
if pr.get('mergeable') is not True or pr.get('mergeable_state')!='clean':
raise AuditBlocked('not clean/up-to-date; protection/review/checks may block')
comparison=api(f"repos/{REPO}/compare/{base}...{pr['head']['sha']}")
if comparison.get('behind_by')!=0 or comparison.get('merge_base_commit',{}).get('sha')!=base:
raise AuditBlocked('behind main; normal branch update and fresh checks required')
reviews=pages(f'repos/{REPO}/pulls/{number}/reviews?per_page=100')
reviewed=reviewed_no_expansion(pr,reviews)
assess(ROOT,pr,cfg,reviewed=reviewed)
checks=pages(f"repos/{REPO}/commits/{pr['head']['sha']}/check-runs?filter=latest&per_page=100",'check_runs')
statuses=pages(f"repos/{REPO}/commits/{pr['head']['sha']}/statuses?per_page=100")
runs=pages(f"repos/{REPO}/actions/runs?head_sha={pr['head']['sha']}&per_page=100",'workflow_runs')
if not workflow_runs_pass(runs):
raise AuditBlocked('exact-head workflow runs are unfinished/not successful')
reviews=pages(f'repos/{REPO}/pulls/{number}/reviews?per_page=100')
if reviewed and not reviewed_no_expansion(pr,reviews):
raise AuditBlocked('exact-head maintainer clearance was withdrawn or became stale')
latest={}
for review in reviews:
if review['state'] in ('APPROVED','CHANGES_REQUESTED','DISMISSED'):
latest[review['user']['login']]=review['state']
if 'CHANGES_REQUESTED' in latest.values() or not checks_pass(checks,statuses,cfg['requiredChecks']):
raise AuditBlocked('review or exact-head checks are incomplete/not successful')
fresh=api(f'repos/{REPO}/pulls/{number}')
if (not trusted_pr(fresh) or fresh.get('mergeable') is not True or fresh.get('mergeable_state')!='clean'
or fresh['head']['sha']!=pr['head']['sha']) or api(f'repos/{REPO}/branches/main')['commit']['sha']!=base:
raise AuditBlocked('head/base moved; rerun audit for the new SHA')
print(number,'eligible independently audited update',pr['head']['sha'])
if args.merge:
# GitHub must atomically reject a behind-base merge if main moves after our final read.
if not strict_updates_required(api(f'repos/{REPO}/rules/branches/main')):
raise AuditBlocked('strict server-side up-to-date/check rules required; no bypass')
check_identity()
result=json.loads(gh('api','--method','PUT',f'repos/{REPO}/pulls/{number}/merge',
'-f','merge_method=squash','-f','sha='+pr['head']['sha']))
if not result.get('merged'):
raise AuditBlocked('GitHub protection rejected merge; no bypass')
print(number,'merged',result['sha'])
break # main moved. Next run must recompute every remaining candidate.
except (AuditBlocked,KeyError,ValueError,OSError,subprocess.SubprocessError) as exc:
print(number,'held:',str(exc) if isinstance(exc,AuditBlocked) else type(exc).__name__)
if __name__=='__main__':
main()
+92 -17
View File
@@ -16,6 +16,7 @@ import tempfile
from pathlib import Path from pathlib import Path
from audit_skill_update import audit_update, AuditBlocked from audit_skill_update import audit_update, AuditBlocked
from tracked_updates import check_identity, EMAIL
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
SHA = re.compile(r"[0-9a-f]{40}") SHA = re.compile(r"[0-9a-f]{40}")
@@ -48,18 +49,35 @@ def candidate(entry: dict, metadata: dict, result: dict) -> tuple[dict, dict] |
def prepare_proposal(entry: dict, metadata: dict, result: dict): class FailureReason(str):
def __new__(cls, error):
from update_diagnostics import render_findings
findings = getattr(error, 'findings', [])
value = str(error) + ('\n\n' + render_findings(findings) if findings else '')
obj = super().__new__(cls, value)
obj.findings = findings
return obj
def prepare_proposal(entry: dict, metadata: dict, result: dict, candidate_view=None):
proposed = candidate(entry, metadata, result) proposed = candidate(entry, metadata, result)
if proposed is None: if proposed is None:
return None, None, '不符合固定来源候选条件' return None, None, '不符合固定来源候选条件'
try: try:
review_path = ROOT / "skills" / entry["id"] / "special-review.v1.json" review_path = ROOT / "skills" / entry["id"] / "special-review.v1.json"
special_review = json.loads(review_path.read_text()) if review_path.is_file() else None special_review = json.loads(review_path.read_text()) if review_path.is_file() else None
updated, sidecar, audit = audit_update(entry, metadata, result, special_review=special_review) updated, sidecar, audit = audit_update(entry, metadata, result, special_review=special_review, candidate_view=candidate_view)
return (updated, sidecar), audit, None return (updated, sidecar), audit, None
except (AuditBlocked, OSError, ValueError, RuntimeError, subprocess.SubprocessError) as error: except (AuditBlocked, OSError, ValueError, TypeError, KeyError, AttributeError, RuntimeError, subprocess.SubprocessError) as error:
# 保留旧审核证据;失败必须可见,不能改成机器审核已通过。 # 保留旧审核证据;失败必须可见,不能改成机器审核已通过。
return proposed, None, str(error)[:400] if not hasattr(error, 'findings'):
error.findings = [dict(id=entry['id'], path=entry.get('source', {}).get('path') or '.', oldRef=result['ref'], newRef=result['head'], gate='source-static-audit', state='blocked', origin='unknown', reason=type(error).__name__ + ': ' + str(error), repair='读取精确来源并重跑实际失败审核;不能推断未执行阶段已通过。 / Read exact source objects and rerun the failed audit; unexecuted stages are not passes.')]
if hasattr(error, 'findings'):
error.findings.append(dict(id=entry['id'], path='.', oldRef=result['ref'], newRef=result['head'],
gate='proposal-repository-validation', state='not_checked', origin='unknown',
reason='审核已阻断,本提案器没有运行其后的目录/本地化/合集生成校验。 / Audit blocked; this proposer did not run subsequent catalog, localization or collection-generation validators.',
repair='先修复审核门槛,再实际运行并记录每条校验;不得把未运行说成通过。 / Fix audit gates, then execute and record each validator; unrun checks are not passes.'))
return proposed, None, FailureReason(error)
def coverage(results: list[dict], root: Path = ROOT) -> list[dict]: def coverage(results: list[dict], root: Path = ROOT) -> list[dict]:
@@ -90,7 +108,7 @@ def coverage(results: list[dict], root: Path = ROOT) -> list[dict]:
status, reason = 'queued', '等待有界自动审核预算' status, reason = 'queued', '等待有界自动审核预算'
else: else:
status, reason = 'manual-review-required', ', '.join(sorted(statuses)) status, reason = 'manual-review-required', ', '.join(sorted(statuses))
rows.append({'id': entry['id'], 'sourceKind': kind, 'status': status, 'reason': reason}) rows.append({'id': entry['id'], 'sourceKind': kind, 'status': status, 'reason': reason, 'oldRef': (result or {}).get('ref'), 'newRef': (result or {}).get('head')})
for child in entry.get('children', []): for child in entry.get('children', []):
rows.append({'id': entry['id'] + '/' + child['id'], 'parentId': entry['id'], 'sourceKind': 'collection-child', 'status': status, 'reason': reason}) rows.append({'id': entry['id'] + '/' + child['id'], 'parentId': entry['id'], 'sourceKind': 'collection-child', 'status': status, 'reason': reason})
elif (folder / 'SKILL.md').is_file(): elif (folder / 'SKILL.md').is_file():
@@ -103,6 +121,31 @@ def run(*args: str, cwd: Path = ROOT) -> str:
return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout.strip() return subprocess.run(args, cwd=cwd, check=True, capture_output=True, text=True).stdout.strip()
def read_existing_candidate(repository, item_id, pr):
"""Static data only. Never check out, import or execute the candidate."""
head = pr.get('headRefOid', '')
if not SHA.fullmatch(head) or not isinstance(pr.get('number'), int):
return None
view = {'head':head, 'number':pr['number'], 'isDraft':pr.get('isDraft')}
for key, filename in [('entry','entry.json'),('metadata','catalog-metadata.v1.json'),('audit','upstream-audit.v1.json')]:
try:
data = run('gh','api','-H','Accept: application/vnd.github.raw+json',
f'repos/{repository}/contents/skills/{item_id}/{filename}?ref={head}')
if len(data) > 1024*1024:
raise ValueError('candidate metadata exceeds budget')
view[key] = json.loads(data)
if not isinstance(view[key], dict):
raise ValueError('candidate metadata must be an object')
except subprocess.CalledProcessError:
# A refused/failed read is unknown, never proof of a missing or stale receipt.
raise
checks = json.loads(run('gh','api',f'repos/{repository}/commits/{head}/check-runs?per_page=100'))
view['checks'] = [{k: c.get(k) for k in ('name','status','conclusion','details_url')} for c in checks.get('check_runs', [])]
if checks.get('total_count', 0) > len(view['checks']):
view['checks'].append({'name':'remaining checks beyond page budget / 超出读取预算的检查','status':'not_checked','conclusion':None})
return view
def write_coverage(rows, destination): def write_coverage(rows, destination):
if destination is None: if destination is None:
return return
@@ -110,7 +153,7 @@ def write_coverage(rows, destination):
for row in rows: for row in rows:
if row.get('parentId'): if row.get('parentId'):
parent = parents[row['parentId']] parent = parents[row['parentId']]
row.update(status=parent['status'], reason='随父合集核验:' + parent['reason']) row.update(status=parent['status'], reason='随父合集核验 / See parent audit: ' + parent['reason'].split('\n')[0])
destination.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n") destination.write_text(json.dumps(rows, ensure_ascii=False, indent=2) + "\n")
summary = ["| Skill | 来源 | 更新状态 | 说明 |", "|---|---|---|---|"] summary = ["| Skill | 来源 | 更新状态 | 说明 |", "|---|---|---|---|"]
summary.extend(f"| {row['id']} | {row['sourceKind']} | {row['status']} | {row['reason'].replace('|', '/').replace(chr(10), ' ')} |" for row in rows) summary.extend(f"| {row['id']} | {row['sourceKind']} | {row['status']} | {row['reason'].replace('|', '/').replace(chr(10), ' ')} |" for row in rows)
@@ -125,19 +168,24 @@ def main() -> None:
parser.add_argument("--coverage-file", type=Path, help="输出所有 Skill 的更新覆盖与阻碍") parser.add_argument("--coverage-file", type=Path, help="输出所有 Skill 的更新覆盖与阻碍")
args = parser.parse_args() args = parser.parse_args()
repository = os.environ.get("GITHUB_REPOSITORY", "desirecore/market") repository = os.environ.get("GITHUB_REPOSITORY", "desirecore/market")
actor = os.environ.get("GITHUB_ACTOR", "") actor = os.environ.get("MARKET_MAINTAINER_LOGIN", "mashagua")
if args.publish and (repository != "desirecore/market" or not re.fullmatch(r"[A-Za-z0-9-]+", actor)): if args.publish and (repository != "desirecore/market" or actor != "mashagua"):
parser.error("发布仅限官方仓库,且必须有触发用户身份") parser.error("发布仅限官方仓库,且必须有触发用户身份")
if args.limit < 1: if args.limit < 1:
parser.error("limit 必须大于零") parser.error("limit 必须大于零")
if args.publish:
check_identity()
results = json.loads(args.results.read_text()) results = json.loads(args.results.read_text())
rows = coverage(results, ROOT) rows = coverage(results, ROOT)
by_id = {row["id"]: row for row in rows} by_id = {row["id"]: row for row in rows}
try: try:
open_heads = set() open_heads = set()
open_prs = []
if args.publish: if args.publish:
open_heads = {pr["headRefName"] for pr in json.loads(run("gh", "pr", "list", "--repo", repository, "--state", "open", "--limit", "1000", "--json", "headRefName"))} open_prs = json.loads(run("gh", "pr", "list", "--repo", repository, "--state", "open", "--limit", "1000", "--json", "number,headRefOid,isDraft,headRefName"))
open_heads = {pr['headRefName'] for pr in open_prs}
count = 0 count = 0
existing_rechecks = 0
for result in results: for result in results:
item_id = result.get("id", "") item_id = result.get("id", "")
if result.get("kind") != "skill" or not SLUG.fullmatch(item_id): if result.get("kind") != "skill" or not SLUG.fullmatch(item_id):
@@ -158,7 +206,24 @@ def main() -> None:
branch = f"updates/{item_id}-{result['head'][:12]}" branch = f"updates/{item_id}-{result['head'][:12]}"
# 保留审核者已编辑的候选;已关闭候选也不在下一轮重新创建。 # 保留审核者已编辑的候选;已关闭候选也不在下一轮重新创建。
if any(head.startswith(f"updates/{item_id}-") for head in open_heads): if any(head.startswith(f"updates/{item_id}-") for head in open_heads):
by_id[item_id].update(status="already-open", reason="保留已有 PR 和审核者修改") if existing_rechecks < args.limit:
existing_rechecks += 1
pr = next(pr for pr in open_prs if pr['headRefName'].startswith(f"updates/{item_id}-"))
view_error = None
try:
view = read_existing_candidate(repository, item_id, pr)
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)
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",
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')
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", existing = json.loads(run("gh", "pr", "list", "--repo", repository, "--state", "all",
"--head", branch, "--json", "number")) if args.publish else [] "--head", branch, "--json", "number")) if args.publish else []
@@ -172,7 +237,7 @@ def main() -> None:
if proposed is None: if proposed is None:
by_id[item_id].update(status="manual-review-required", reason=reason) by_id[item_id].update(status="manual-review-required", reason=reason)
continue continue
by_id[item_id].update(status="audit-passed" if audit else "manual-review-required", reason=reason or "来源、许可与结构化元数据核验通过;不代表运行或安全认证") by_id[item_id].update(status="audit-passed" if audit else "manual-review-required", reason=reason or "来源、许可与结构化元数据核验通过;不代表运行或安全认证", oldRef=result["ref"], newRef=result["head"], findings=getattr(reason, "findings", []))
print(f"{item_id}: {by_id[item_id]['status']}: {by_id[item_id]['reason']}") print(f"{item_id}: {by_id[item_id]['status']}: {by_id[item_id]['reason']}")
if not args.publish: if not args.publish:
continue continue
@@ -186,6 +251,7 @@ def main() -> None:
paths = [f"skills/{item_id}/entry.json", f"skills/{item_id}/catalog-metadata.v1.json"] paths = [f"skills/{item_id}/entry.json", f"skills/{item_id}/catalog-metadata.v1.json"]
if audit: if audit:
audit_path = f"skills/{item_id}/upstream-audit.v1.json" audit_path = f"skills/{item_id}/upstream-audit.v1.json"
baseline_audit = (checkout / audit_path).read_bytes() if (checkout / audit_path).exists() else None
(checkout / audit_path).write_text(json.dumps(audit, ensure_ascii=False, indent=2) + "\n") (checkout / audit_path).write_text(json.dumps(audit, ensure_ascii=False, indent=2) + "\n")
try: try:
# 只运行受审仓库自己的元数据校验,不运行上游代码。 # 只运行受审仓库自己的元数据校验,不运行上游代码。
@@ -196,17 +262,26 @@ def main() -> None:
run("uv", "run", "--quiet", "scripts/gen-collection-children.py", "--check", item_id, cwd=checkout) run("uv", "run", "--quiet", "scripts/gen-collection-children.py", "--check", item_id, cwd=checkout)
except subprocess.CalledProcessError as error: except subprocess.CalledProcessError as error:
print(error.stdout or error.stderr or '目录校验失败') print(error.stdout or error.stderr or '目录校验失败')
audit, reason = None, '目录或本地化元数据校验未通过;保持草稿,不能发布' audit, reason = None, '目录或本地化元数据校验未通过;保持草稿,不能发布。 / Catalog/localization validation failed: ' + str(error.cmd) + '\n' + str(error.stdout or error.stderr or '')[-6000:]
by_id[item_id].update(status="manual-review-required", reason=reason) by_id[item_id].update(status="manual-review-required", reason=reason)
fallback = candidate(json.loads(entry_path.read_text()), json.loads(metadata_path.read_text()), result) fallback = candidate(json.loads(entry_path.read_text()), json.loads(metadata_path.read_text()), result)
for path, data in zip((entry_path, metadata_path), fallback): for path, data in zip((entry_path, metadata_path), fallback):
(checkout / path.relative_to(ROOT)).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n") (checkout / path.relative_to(ROOT)).write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n")
# 如果已有旧审计文件,不把它误称为本次通过记录。 # Preserve an actual old receipt; failures are separate evidence,
(checkout / audit_path).write_text(json.dumps({'schemaVersion': 1, 'status': 'blocked', 'ref': result['head'], 'reason': reason}, ensure_ascii=False, indent=2) + "\n") # never a replacement or a forged successful new receipt.
paths.append(audit_path) if baseline_audit is None:
(checkout / audit_path).unlink()
else:
(checkout / audit_path).write_bytes(baseline_audit)
blocked_path = f"docs/update-reviews/{item_id}-{result['head'][:12]}.json"
(checkout / blocked_path).parent.mkdir(parents=True, exist_ok=True)
(checkout / blocked_path).write_text(json.dumps({'schemaVersion': 1, 'status': 'blocked', 'oldRef': result['ref'], 'newRef': result['head'], 'reason': reason}, ensure_ascii=False, indent=2) + "\n")
paths.append(blocked_path)
if (checkout / audit_path).is_file():
paths.append(audit_path)
run("git", "add", "--", *paths, cwd=checkout) run("git", "add", "--", *paths, cwd=checkout)
run("git", "-c", f"user.name={actor}", "-c", f"user.email={actor}@users.noreply.github.com", run("git", "-c", f"user.name={actor}", "-c", f"user.email={EMAIL}",
"commit", "-m", f"chore(market): 提议更新 {item_id} 上游快照", cwd=checkout) "commit", "-m", f"chore(market): 提议更新 {item_id} 上游快照", cwd=checkout)
run("git", "push", "origin", f"HEAD:refs/heads/{branch}", cwd=checkout) run("git", "push", "origin", f"HEAD:refs/heads/{branch}", cwd=checkout)
body = Path(tmp) / "body.md" body = Path(tmp) / "body.md"
@@ -217,7 +292,7 @@ def main() -> None:
if audit else "自动核验未通过,保留旧审核回执与草稿,不能据此发布新版。\n") if audit else "自动核验未通过,保留旧审核回执与草稿,不能据此发布新版。\n")
+ "不执行上游代码,不代表软件安全认证或真实运行验收,不自动合并。非结构化依赖和行为变化仍需结合 PR 差异复核。\n\n" + "不执行上游代码,不代表软件安全认证或真实运行验收,不自动合并。非结构化依赖和行为变化仍需结合 PR 差异复核。\n\n"
+ "Automated source/license/metadata verification, not a security certification or runtime acceptance. No auto-merge.\n\n" + "Automated source/license/metadata verification, not a security certification or runtime acceptance. No auto-merge.\n\n"
+ "```json\n" + str(findings) + "\n```\n", encoding="utf-8") + ("```json\n" + str(findings) + "\n```\n" if audit else str(findings) + "\n"), encoding="utf-8")
command = ["gh", "pr", "create", "--repo", repository, "--base", "main", "--head", branch, command = ["gh", "pr", "create", "--repo", repository, "--base", "main", "--head", branch,
"--title", f"chore(market): 更新 {item_id} 上游快照", "--body-file", str(body)] "--title", f"chore(market): 更新 {item_id} 上游快照", "--body-file", str(body)]
if not audit: if not audit:
+148
View File
@@ -0,0 +1,148 @@
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = ["pyyaml>=6.0"]
# ///
"""Discover configured ZIP/Web/local updates; default is read-only planning."""
import argparse
import json
import subprocess
import tempfile
from pathlib import Path
from tracked_updates import (AuditBlocked, CONFIG, LOGIN, EMAIL, check_identity, discover_target,
digest, encoded, gh, load_config, plan)
ROOT = Path(__file__).resolve().parents[2]
class Publication(str):
def __new__(cls, url, reason=None):
obj = super().__new__(cls, url)
obj.blocked_reason = reason
return obj
def publish(root, item_id, target, changes, reason=None):
branch = f'tracked-updates/{item_id}-{digest(encoded(target))[:12]}'
open_heads = json.loads(gh('pr', 'list', '--repo', 'desirecore/market', '--state', 'open', '--limit', '1000', '--json', 'headRefName'))
if any(p['headRefName'].startswith(f'tracked-updates/{item_id}-') for p in open_heads):
return 'already-open'
if json.loads(gh('pr', 'list', '--repo', 'desirecore/market', '--state', 'all', '--head', branch, '--json', 'number')):
return 'already-proposed'
check_identity()
with tempfile.TemporaryDirectory(prefix='market-tracked-proposal-') as tmp:
checkout = Path(tmp) / 'worktree'
subprocess.run(['git', 'worktree', 'add', '--detach', str(checkout), 'HEAD'], cwd=root, check=True, capture_output=True)
try:
original = {relative: (checkout/relative).read_bytes() if (checkout/relative).exists() else None for relative in changes}
for relative, data in changes.items():
p = checkout / relative
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)
if reason is None:
commands = [
['uv','run','scripts/catalog/validate_catalog_metadata.py','--require-complete'],
['uv','run','scripts/i18n/validate-i18n.py',f'skills/{item_id}'],
['uv','run','scripts/i18n/translate.py','--check',f'skills/{item_id}'],
]
for cmd in commands:
result = subprocess.run(cmd, cwd=checkout, capture_output=True)
if result.returncode:
# Restore only our own disposable files; never publish a failed admission.
for relative, baseline in original.items():
p = checkout / relative
if baseline is None:
p.unlink(missing_ok=True)
else:
p.write_bytes(baseline)
reason = '目录/本地化失败,保留旧准入;失败后其余校验未完成。 / Repository/i18n validation failed; old admission retained and later validators did not complete. Command: ' + ' '.join(cmd) + '\n' + (result.stdout + result.stderr).decode('utf-8', errors='replace')[-6000:]
path = f'docs/update-reviews/{item_id}.json'
changes = {path: encoded({'schemaVersion':1,'status':'blocked','id':item_id,'candidate':target,'reason':reason})}
p = checkout / path
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(changes[path])
break
subprocess.run(['git','add','--',*changes], cwd=checkout, check=True)
subprocess.run(['git','-c',f'user.name={LOGIN}','-c',f'user.email={EMAIL}',
'commit','-m',f'chore(market): review tracked {item_id} update'], cwd=checkout, check=True, capture_output=True)
subprocess.run(['git','push','origin',f'HEAD:refs/heads/{branch}'], cwd=checkout, check=True, capture_output=True)
body = Path(tmp) / 'body.md'
body.write_text(f'Configured upstream update for `{item_id}`.\n\n'
+ ('Blocked: '+reason if reason else 'Pinned old/new payloads passed the existing license, prerequisite and metadata delta audit. This is not runtime/security certification.')
+ '\n\nMarket wrappers and patches are preserved. Content-changing updates require an exact-head human maintainer no-expansion review; identical installed payloads need no additional behavioral clearance. The separate trusted gate always reaudits bytes and checks.\n')
args = ['pr','create','--repo','desirecore/market','--base','main','--head',branch,
'--title',f'chore(market): review {item_id} tracked upstream','--body-file',str(body)]
if reason:
args += ['--draft']
return Publication(gh(*args), reason)
finally:
# Remove only the disposable worktree created above, never a user's checkout.
subprocess.run(['git','worktree','remove','--force',str(checkout)], cwd=root, check=True)
def main():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--publish', action='store_true')
parser.add_argument('--limit', type=int, default=5)
parser.add_argument('--report-file', type=Path, help='Exact outcomes, including blocked and not-checked entries')
args=parser.parse_args()
if args.limit < 1:
parser.error('--limit must be positive')
if args.publish:
check_identity()
cfg=load_config(ROOT)
attempted=0
rows=[]
try:
for item_id, track in cfg['tracking'].items():
row={'id':item_id,'status':'not-checked','reason':'预算未覆盖,未检查 / Not checked within budget','oldRef':track.get('ref','未读取 / not read'),'newRef':'未读取 / not read'}
rows.append(row)
if attempted >= args.limit:
continue
target=None
publication_attempted=False
try:
if (ROOT/'skills'/item_id/'upstream-health-hold.json').exists():
row.update(status='held',reason='保留已审核暂缓决定 / Reviewed hold retained')
print(item_id, 'held; not advancing')
continue
target=discover_target(ROOT,item_id,track)
row['newRef']=target.get('ref') or target.get('sha256') or '尚未取得不可变 pin / immutable pin not obtained'
metadata=json.loads((ROOT/'skills'/item_id/'catalog-metadata.v1.json').read_text())
origin=metadata.get('provenance',{}).get('content',{})
row['oldRef']=origin.get('ref') or origin.get('sha256') or row['oldRef']
if track['adapter']=='local-git' and target['ref']==track['ref']:
row.update(status='current',reason='已配置来源无待处理更新 / Configured source is current')
print(item_id,'current')
continue
result=plan(ROOT,item_id,cfg,target)
if result is None:
row.update(status='current',reason='已配置来源无待处理更新 / Configured source is current')
print(item_id,'current')
continue
changes,report=result
row.update(status='audit-passed',reason='静态核验通过,不代表运行或安全认证 / Static verification passed, not runtime/security acceptance',newRef=report['source']['ref'])
print(item_id,'audited',report['source']['ref'])
if args.publish:
attempted+=1
publication_attempted=True
publication=publish(ROOT,item_id,target,changes)
if getattr(publication,'blocked_reason',None):
row.update(status='manual-review-required',reason=publication.blocked_reason)
print(publication)
except (AuditBlocked, ValueError, KeyError, OSError, subprocess.SubprocessError) as exc:
reason=str(exc) if isinstance(exc,AuditBlocked) else 'discovery/fetch/validation failed: '+type(exc).__name__
row.update(status='manual-review-required',reason='人工待审,保留旧准入 / Manual review; old admission retained: '+reason,findings=getattr(exc,'findings',[]))
print(item_id,'BLOCKED:',reason)
if args.publish and target is not None and not publication_attempted:
attempted+=1
path=f'docs/update-reviews/{item_id}.json'
changes={path:encoded({'schemaVersion':1,'status':'blocked','id':item_id,'candidate':target,'reason':reason})}
print(publish(ROOT,item_id,target,changes,reason))
finally:
if args.report_file:
args.report_file.write_text(json.dumps(rows,ensure_ascii=False,indent=2)+"\n")
if __name__=='__main__':
main()
+9 -1
View File
@@ -18,7 +18,10 @@ class AuditTests(unittest.TestCase):
self.tmp = tempfile.TemporaryDirectory(); self.repo = Path(self.tmp.name) self.tmp = tempfile.TemporaryDirectory(); self.repo = Path(self.tmp.name)
self.run_git('init', '--quiet') self.run_git('init', '--quiet')
self.run_git('config', 'user.name', 'test'); self.run_git('config', 'user.email', 'test@example.com') self.run_git('config', 'user.name', 'test'); self.run_git('config', 'user.email', 'test@example.com')
self.write('LICENSE', 'MIT fixture; previously reviewed bytes\n') self.mit = (Path(__file__).resolve().parents[2] / 'LICENSE').read_text()
self.write('LICENSE', self.mit)
self.write('skills/sample/LICENSE', self.mit)
self.write('skills/another/LICENSE', self.mit)
self.write('skills/sample/SKILL.md', '---\nname: sample\ndescription: Fixture\nversion: 1.0.0\n---\nOld instructions\n') self.write('skills/sample/SKILL.md', '---\nname: sample\ndescription: Fixture\nversion: 1.0.0\n---\nOld instructions\n')
self.write('skills/sample/scripts/tool.py', 'print("fixture")\n') self.write('skills/sample/scripts/tool.py', 'print("fixture")\n')
self.old = self.commit() self.old = self.commit()
@@ -131,6 +134,7 @@ class AuditTests(unittest.TestCase):
self.assertEqual(entry['children'][0]['version'], '1.1.0') self.assertEqual(entry['children'][0]['version'], '1.1.0')
self.assertEqual(entry['children'][0]['i18n'], self.entry['children'][0]['i18n']) self.assertEqual(entry['children'][0]['i18n'], self.entry['children'][0]['i18n'])
self.assertEqual(metadata['spec']['collection']['children'][0]['release']['version'], '1.1.0') self.assertEqual(metadata['spec']['collection']['children'][0]['release']['version'], '1.1.0')
self.write('skills/another/LICENSE', self.mit)
self.write('skills/another/SKILL.md', '---\nname: another\ndescription: New member\n---\n') self.write('skills/another/SKILL.md', '---\nname: another\ndescription: New member\n---\n')
with self.assertRaisesRegex(AuditBlocked, '合集成员'): self.audit() with self.assertRaisesRegex(AuditBlocked, '合集成员'): self.audit()
@@ -239,6 +243,7 @@ class AuditTests(unittest.TestCase):
from check_upstream_health import GENERATOR from check_upstream_health import GENERATOR
self.entry['children'] = [{'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0', 'i18n': {'zh-CN': {'name': '示例'}}}] self.entry['children'] = [{'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0', 'i18n': {'zh-CN': {'name': '示例'}}}]
self.metadata['spec'] = {'collection': {'children': [{'identity': {'id':'sample'}, 'path':'skills/sample', 'release': {'state':'known','version':'1.0.0','versionScheme':'semver'}}]}} self.metadata['spec'] = {'collection': {'children': [{'identity': {'id':'sample'}, 'path':'skills/sample', 'release': {'state':'known','version':'1.0.0','versionScheme':'semver'}}]}}
self.write('skills/another/LICENSE', self.mit)
self.write('skills/another/SKILL.md', '---\nname: another\ndescription: New member\nversion: 0.1.0\n---\nBody\n') self.write('skills/another/SKILL.md', '---\nname: another\ndescription: New member\nversion: 0.1.0\n---\nBody\n')
new = self.commit() new = self.commit()
fm = GENERATOR.skill_frontmatter(self.repo, 'skills/another/SKILL.md', new) fm = GENERATOR.skill_frontmatter(self.repo, 'skills/another/SKILL.md', new)
@@ -272,6 +277,7 @@ class AuditTests(unittest.TestCase):
from check_upstream_health import GENERATOR from check_upstream_health import GENERATOR
self.entry['children'] = [{'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0'}] self.entry['children'] = [{'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0'}]
self.metadata['spec'] = {'collection': {'children': [{'identity': {'id':'sample'}, 'path':'skills/sample'}]}} self.metadata['spec'] = {'collection': {'children': [{'identity': {'id':'sample'}, 'path':'skills/sample'}]}}
self.write('skills/another/LICENSE', self.mit)
self.write('skills/another/SKILL.md', '---\nname: another\ndescription: New member\nversion: 0.1.0\n---\n') self.write('skills/another/SKILL.md', '---\nname: another\ndescription: New member\nversion: 0.1.0\n---\n')
new = self.commit() new = self.commit()
fm = GENERATOR.skill_frontmatter(self.repo, 'skills/another/SKILL.md', new) fm = GENERATOR.skill_frontmatter(self.repo, 'skills/another/SKILL.md', new)
@@ -291,11 +297,13 @@ class AuditTests(unittest.TestCase):
def test_special_review_accepts_root_notice_change(self): def test_special_review_accepts_root_notice_change(self):
from audit_skill_update import root_evidence from audit_skill_update import root_evidence
self.write('NOTICE', 'old notice\n') self.write('NOTICE', 'old notice\n')
self.write('skills/sample/README.md', 'old notice\n')
self.old = self.commit() self.old = self.commit()
self.entry['source']['ref'] = self.old self.entry['source']['ref'] = self.old
self.metadata['provenance']['content']['ref'] = self.old self.metadata['provenance']['content']['ref'] = self.old
self.metadata['governance']['compliance']['reviewedRef'] = self.old self.metadata['governance']['compliance']['reviewedRef'] = self.old
self.write('NOTICE', 'new notice documenting a font license\n') self.write('NOTICE', 'new notice documenting a font license\n')
self.write('skills/sample/README.md', 'new notice documenting a font license\n')
new = self.commit() new = self.commit()
with self.assertRaisesRegex(AuditBlocked, '许可证|Notice'): with self.assertRaisesRegex(AuditBlocked, '许可证|Notice'):
audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z') audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z')
@@ -377,7 +377,7 @@ class UpstreamHealthTests(unittest.TestCase):
{"id": "b", "kind": "skill", "url": "u", "issues": [{"status": "stale-hold", "detail": "y"}]}, {"id": "b", "kind": "skill", "url": "u", "issues": [{"status": "stale-hold", "detail": "y"}]},
] ]
text = CHECKER.render_markdown(results) text = CHECKER.render_markdown(results)
self.assertIn("### Reviewed holds — not actionable (1)", text) self.assertIn("### 已审核暂缓——不推进 / Reviewed holds — not actionable (1)", text)
self.assertLess(text.index("Stale holds — re-review"), text.index("Reviewed holds")) self.assertLess(text.index("Stale holds — re-review"), text.index("Reviewed holds"))
self.assertNotIn("OK (", text) self.assertNotIn("OK (", text)
@@ -433,7 +433,7 @@ class UpstreamHealthTests(unittest.TestCase):
ref, head = "a19a171" + "0" * 33, "94f06c1" + "0" * 33 ref, head = "a19a171" + "0" * 33, "94f06c1" + "0" * 33
results = [{"id": "a", "kind": "skill", "url": "https://github.com/o/r.git", "ref": ref, "head": head, results = [{"id": "a", "kind": "skill", "url": "https://github.com/o/r.git", "ref": ref, "head": head,
"issues": [{"status": "outdated", "detail": "a19a171 -> 94f06c1"}]}] "issues": [{"status": "outdated", "detail": "a19a171 -> 94f06c1"}]}]
self.assertIn(f"| [a19a171 → 94f06c1](https://github.com/o/r/compare/{ref}...{head}) |", self.assertIn(f"| 审核差异后再更新 / Review before updating: [a19a171 → 94f06c1](https://github.com/o/r/compare/{ref}...{head}) |",
CHECKER.render_markdown(results)) CHECKER.render_markdown(results))
def test_compare_url_accepts_github_url_variants(self) -> None: def test_compare_url_accepts_github_url_variants(self) -> None:
@@ -455,7 +455,7 @@ class UpstreamHealthTests(unittest.TestCase):
results = [{"id": "a", "kind": "skill", "url": url, "ref": pinned, "head": checked, results = [{"id": "a", "kind": "skill", "url": url, "ref": pinned, "head": checked,
"issues": [{"status": "outdated", "detail": "aaaaaaa -> bbbbbbb"}]}] "issues": [{"status": "outdated", "detail": "aaaaaaa -> bbbbbbb"}]}]
text = CHECKER.render_markdown(results) text = CHECKER.render_markdown(results)
self.assertIn("| aaaaaaa -> bbbbbbb |", text) self.assertIn("存在上游差异,须审核后通过 PR 更新,不代表已经审核通过 / aaaaaaa -> bbbbbbb |", text)
self.assertNotIn("/compare/", text) self.assertNotIn("/compare/", text)
def test_markdown_links_only_outdated_rows(self) -> None: def test_markdown_links_only_outdated_rows(self) -> None:
@@ -464,7 +464,7 @@ class UpstreamHealthTests(unittest.TestCase):
{"status": "upstream-path-change", "detail": "x | y"}]}] {"status": "upstream-path-change", "detail": "x | y"}]}]
text = CHECKER.render_markdown(results) text = CHECKER.render_markdown(results)
self.assertEqual(text.count("/compare/"), 1) self.assertEqual(text.count("/compare/"), 1)
self.assertIn("| x \\| y |", text) self.assertIn("更新前审核路径 / x \\| y |", text)
if __name__ == "__main__": if __name__ == "__main__":
@@ -55,17 +55,20 @@ class CandidateTests(unittest.TestCase):
self.assertIsNone(candidate(self.entry, self.sidecar, self.result)) self.assertIsNone(candidate(self.entry, self.sidecar, self.result))
def exercise_publish(self, audited=True, validation_failure=False, publish_failure=False): def exercise_publish(self, audited=True, validation_failure=False, publish_failure=False, existing_open=False, old_receipt=False):
with tempfile.TemporaryDirectory() as temporary: with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary); folder = root / 'skills/sample'; folder.mkdir(parents=True) root = Path(temporary); folder = root / 'skills/sample'; folder.mkdir(parents=True)
(folder/'entry.json').write_text(json.dumps(self.entry)) (folder/'entry.json').write_text(json.dumps(self.entry))
(folder/'catalog-metadata.v1.json').write_text(json.dumps(self.sidecar)) (folder/'catalog-metadata.v1.json').write_text(json.dumps(self.sidecar))
if old_receipt:
(folder/'upstream-audit.v1.json').write_text(json.dumps({'source':{'ref':self.old},'genuineOldReceipt':True}))
results = root/'results.json'; results.write_text(json.dumps([self.result])) results = root/'results.json'; results.write_text(json.dumps([self.result]))
updated, metadata = candidate(self.entry, self.sidecar, self.result) updated, metadata = candidate(self.entry, self.sidecar, self.result)
metadata['governance']['compliance'].update(reviewedRef=self.new, reviewedBy='automated:test') metadata['governance']['compliance'].update(reviewedRef=self.new, reviewedBy='automated:test')
seen = {} seen = {}
def run(*args, cwd=None): def run(*args, cwd=None):
if args[:3] == ('gh', 'pr', 'list'): return '[]' if args[:3] == ('gh', 'pr', 'list'):
return json.dumps([{'headRefName':'updates/sample-existing'}]) if existing_open and args[-1].endswith('headRefName') else '[]'
if args[:3] == ('git', 'worktree', 'add'): if args[:3] == ('git', 'worktree', 'add'):
shutil.copytree(root/'skills', Path(args[4])/'skills'); return '' shutil.copytree(root/'skills', Path(args[4])/'skills'); return ''
if args[0] == 'uv' and validation_failure: if args[0] == 'uv' and validation_failure:
@@ -75,9 +78,11 @@ class CandidateTests(unittest.TestCase):
raise subprocess.CalledProcessError(1, args, stderr='API unavailable') raise subprocess.CalledProcessError(1, args, stderr='API unavailable')
seen['draft'] = '--draft' in args seen['draft'] = '--draft' in args
seen['metadata'] = json.loads((cwd/'skills/sample/catalog-metadata.v1.json').read_text()) seen['metadata'] = json.loads((cwd/'skills/sample/catalog-metadata.v1.json').read_text())
seen['blocked'] = [json.loads(p.read_text()) for p in (cwd/'docs/update-reviews').glob('*.json')]
seen['audit'] = json.loads((cwd/'skills/sample/upstream-audit.v1.json').read_text()) if (cwd/'skills/sample/upstream-audit.v1.json').exists() else None seen['audit'] = json.loads((cwd/'skills/sample/upstream-audit.v1.json').read_text()) if (cwd/'skills/sample/upstream-audit.v1.json').exists() else None
return '' return ''
with patch.object(proposer, 'ROOT', root), patch.object(proposer, 'run', side_effect=run), \ with patch.object(proposer, 'ROOT', root), patch.object(proposer, 'run', side_effect=run), \
patch.object(proposer, 'check_identity') as identity_check, \
patch.object(proposer, 'audit_update', return_value=(updated, metadata, {'reviewer':'automated:test'}), patch.object(proposer, 'audit_update', return_value=(updated, metadata, {'reviewer':'automated:test'}),
side_effect=None if audited else proposer.AuditBlocked('license changed')), \ side_effect=None if audited else proposer.AuditBlocked('license changed')), \
patch.dict(os.environ, {'GITHUB_REPOSITORY':'desirecore/market', 'GITHUB_ACTOR':'example-user'}), \ patch.dict(os.environ, {'GITHUB_REPOSITORY':'desirecore/market', 'GITHUB_ACTOR':'example-user'}), \
@@ -86,9 +91,24 @@ class CandidateTests(unittest.TestCase):
with self.assertRaises(subprocess.CalledProcessError): proposer.main() with self.assertRaises(subprocess.CalledProcessError): proposer.main()
else: else:
proposer.main() proposer.main()
identity_check.assert_called_once_with()
seen['coverage'] = json.loads((root/'coverage.json').read_text()) seen['coverage'] = json.loads((root/'coverage.json').read_text())
return seen return seen
def test_existing_pr_read_failure_is_unknown_without_stopping_independent_audit(self):
with patch.object(proposer, 'read_existing_candidate', side_effect=ValueError('GitHub read unavailable')):
result = self.exercise_publish(existing_open=True)
self.assertEqual(result['coverage'][0]['status'], 'manual-review-required')
self.assertTrue(any(row['gate']=='candidate-evidence-read' and row['state']=='not_checked' for row in result['coverage'][0]['findings']))
self.assertNotIn('draft', result)
def test_existing_pr_is_reaudited_without_republishing(self):
result = self.exercise_publish(audited=False, existing_open=True)
self.assertNotIn('draft', result)
self.assertEqual(result['coverage'][0]['status'], 'manual-review-required')
self.assertEqual(result['coverage'][0]['oldRef'], self.old)
self.assertEqual(result['coverage'][0]['newRef'], self.new)
def test_successful_audit_and_validation_create_a_normal_pr(self): def test_successful_audit_and_validation_create_a_normal_pr(self):
result = self.exercise_publish() result = self.exercise_publish()
self.assertFalse(result['draft']) self.assertFalse(result['draft'])
@@ -101,16 +121,35 @@ class CandidateTests(unittest.TestCase):
self.assertEqual(result['metadata']['governance']['compliance']['reviewedRef'], self.old) self.assertEqual(result['metadata']['governance']['compliance']['reviewedRef'], self.old)
self.assertEqual(result['coverage'][0]['status'], 'manual-review-required') self.assertEqual(result['coverage'][0]['status'], 'manual-review-required')
def test_validator_failure_preserves_genuine_old_receipt_bytes(self):
result = self.exercise_publish(validation_failure=True, old_receipt=True)
self.assertEqual(result['audit'], {'source':{'ref':self.old},'genuineOldReceipt':True})
self.assertEqual(result['blocked'][0]['newRef'], self.new)
self.assertTrue(result['draft'])
def test_validator_failure_cannot_publish_a_successful_audit(self): def test_validator_failure_cannot_publish_a_successful_audit(self):
result = self.exercise_publish(validation_failure=True) result = self.exercise_publish(validation_failure=True)
self.assertTrue(result['draft']) self.assertTrue(result['draft'])
self.assertEqual(result['metadata']['governance']['compliance']['reviewedRef'], self.old) self.assertEqual(result['metadata']['governance']['compliance']['reviewedRef'], self.old)
self.assertEqual(result['audit']['status'], 'blocked') self.assertIsNone(result['audit'])
self.assertEqual(result['blocked'][0]['status'], 'blocked')
self.assertIn('catalog failure', result['blocked'][0]['reason'])
self.assertEqual(result['blocked'][0]['oldRef'], self.old)
self.assertEqual(result['blocked'][0]['newRef'], self.new)
def test_publish_failure_still_writes_truthful_coverage(self): def test_publish_failure_still_writes_truthful_coverage(self):
result = self.exercise_publish(publish_failure=True) result = self.exercise_publish(publish_failure=True)
self.assertEqual(result['coverage'][0]['status'], 'publish-failed') self.assertEqual(result['coverage'][0]['status'], 'publish-failed')
def test_failed_identity_prevents_any_publish_side_effect(self):
with patch.object(proposer, 'check_identity', side_effect=proposer.AuditBlocked('not designated maintainer')), \
patch.object(proposer, 'run') as run, \
patch.dict(os.environ, {'GITHUB_REPOSITORY':'desirecore/market', 'MARKET_MAINTAINER_LOGIN':'mashagua'}), \
patch('sys.argv', ['propose', 'not-read-before-identity.json', '--publish']):
with self.assertRaises(proposer.AuditBlocked):
proposer.main()
run.assert_not_called()
def test_coverage_includes_builtins_and_http_blockers(self): def test_coverage_includes_builtins_and_http_blockers(self):
with tempfile.TemporaryDirectory() as temporary: with tempfile.TemporaryDirectory() as temporary:
root = Path(temporary) root = Path(temporary)
+361
View File
@@ -0,0 +1,361 @@
"""Offline security/contract tests. Network and publication never run in this suite."""
import copy
import io
import json
import stat
import subprocess
import zipfile
from pathlib import Path
from unittest.mock import patch
import pytest
import tracked_updates as t
import merge_verified_updates as m
from audit_skill_update import git
from automated_review import validate_record
def archive(files):
out=io.BytesIO()
with zipfile.ZipFile(out,'w') as z:
for path,data in files:
z.writestr(path,data)
return out.getvalue()
def unz(data,**kw):
return t.unpack({'kind':'zip','sha256':t.digest(data),**kw},data)
@pytest.mark.parametrize('url',[
'http://clawhub.ai/x','https://127.0.0.1/x','https://clawhub.ai.evil.invalid/x',
'https://user:password@clawhub.ai/x','https://clawhub.ai:8080/x','file:///tmp/x',
'https://clawhub.ai/x#fragment',
])
def test_untrusted_urls_rejected(url):
with pytest.raises(t.AuditBlocked): t.allowed_url(url)
@pytest.mark.parametrize('path',['../x','/x','a/../x','a\\b','.git/config','.github/workflows/x.yml','a//x','C:/escape','folder/NUL.txt','folder/end.','folder/end '])
def test_zip_paths_rejected(path):
with pytest.raises(t.AuditBlocked):unz(archive([('SKILL.md','x'),(path,'x')]))
def test_zip_layout_hash_and_missing_marker():
data=archive([('pkg/SKILL.md','body'),('pkg/LICENSE','MIT fixture')])
assert set(unz(data,path='pkg'))=={'SKILL.md','LICENSE'}
with pytest.raises(t.AuditBlocked): unz(data)
with pytest.raises(t.AuditBlocked): t.unpack({'kind':'zip','sha256':'0'*64},data)
def test_duplicate_and_case_collision_blocked():
with pytest.raises(t.AuditBlocked):unz(archive([('SKILL.md','x'),('skill.md','y')]))
def test_zip_symlink_and_executable_rejected():
for mode in (stat.S_IFLNK|0o777,stat.S_IFREG|0o755):
item=zipfile.ZipInfo('SKILL.md');item.external_attr=mode<<16
out=io.BytesIO()
with zipfile.ZipFile(out,'w') as z:z.writestr(item,'body')
with pytest.raises(t.AuditBlocked):unz(out.getvalue())
def test_oversized_zip_rejected():
with pytest.raises(t.AuditBlocked):unz(archive([('SKILL.md',b'x'*(t.MAX_FILE+1))]))
def test_registry_version_and_owner_are_verified_not_license_inferred():
track={'adapter':'clawhub','slug':'sample','owner':'owner'}
meta={'skill':{'slug':'sample'},'owner':{'handle':'owner'},'latestVersion':{'version':'1.2.3'},'license':'MIT-0'}
with patch.object(t,'json_url',return_value=meta):
result=t.discover(track,{'kind':'zip'})
assert 'version=1.2.3' in result['repoUrl']
assert 'license' not in result
meta['owner']['handle']='different'
with patch.object(t,'json_url',return_value=meta),pytest.raises(t.AuditBlocked):t.discover(track,{})
def test_github_file_uses_resolved_commit_not_branch_url():
track={'adapter':'github-file','repo':'example/project','branch':'main','path':'SKILL.md'}
with patch.object(t,'json_url',return_value={'sha':'a'*40}):result=t.discover(track,{'kind':'web'})
assert '/'+('a'*40)+'/' in result['repoUrl']
with patch.object(t,'json_url',return_value={'sha':'main'}),pytest.raises(t.AuditBlocked):t.discover(track,{})
def test_release_requires_unique_asset():
track={'adapter':'github-release','repo':'example/project','asset':'skill.zip'}
meta={'tag_name':'v1.0.0','assets':[{'name':'other.zip','browser_download_url':'https://example.invalid/x'}]}
with patch.object(t,'json_url',return_value=meta),pytest.raises(t.AuditBlocked):t.discover(track,{})
def metadata(ref='a'*64,kind='zip'):
content={'kind':kind,'url':'https://github.com/example/project/releases/download/v1/skill.zip',
('ref' if kind=='git' else 'sha256'):ref}
return {'identity':{'kind':'skill','id':'sample'},'provenance':{'content':content},
'governance':{'availability':'installable','license':{'state':'known','value':'MIT','evidencePath':'LICENSE'},
'compliance':{'licenseEvidencePath':'LICENSE','reviewedRef':ref,'reviewedBy':'previous-human','reviewedAt':'2026-11-01'}}}
def payload():
return {'SKILL.md':b'---\nname: sample\ndescription: Sample fixture\n---\nInstructions\n',
'LICENSE':(Path(__file__).resolve().parents[2]/'LICENSE').read_bytes(),'scripts/tool.py':b'print("fixture")\n'}
def test_artifact_receipt_binds_real_digest_and_fresh_audit():
before=payload();after={**before,'scripts/tool.py':b'print("changed")\n'}
new={'kind':'zip','url':'https://github.com/example/project/releases/download/v2/skill.zip','sha256':'b'*64}
updated,record=t.audit_payload(None,metadata(),before,after,'a'*64,'b'*64,new)
assert not record['identicalInstalledPayload']
assert record['source']['ref']=='b'*64
assert updated['governance']['compliance']['reviewedRef']=='b'*64
assert validate_record(updated,record)==[]
broken=copy.deepcopy(record);broken['source']['previousRef']='a'*40
assert validate_record(updated,broken)
broken=copy.deepcopy(record);broken['checks']['licenseAndNoticeUnchanged']=False
assert validate_record(updated,broken)
@pytest.mark.parametrize('change',[{'LICENSE':b'new terms'},{'NOTICE':b'new obligation'},
{'requirements.txt':b'new-package==1.0\n'},
{'SKILL.md':b'---\nname: sample\ndescription: new API required\n---\n'}])
def test_artifact_delta_cannot_invent_admission(change):
before=payload();after={**before,**change}
with pytest.raises(t.AuditBlocked):t.audit_payload(None,metadata(),before,after,'a'*64,'b'*64,
{'kind':'zip','url':'https://clawhub.ai/download?v=2','sha256':'b'*64})
def test_listing_only_not_promoted():
meta=metadata();meta['governance']['availability']='listing-only'
with pytest.raises(t.AuditBlocked):t.audit_payload(None,meta,payload(),payload(),'a'*64,'b'*64,
{'kind':'zip','url':'https://clawhub.ai/download?v=2','sha256':'b'*64})
def check(name,state='success',status='completed'):
return {'id':1,'name':name,'status':status,'conclusion':state,
'app':{'slug':'github-advanced-security' if name=='CodeQL' else 'github-actions'}}
def test_merge_requires_all_exact_head_checks_and_trusted_apps():
good=[check('validate'),check('translate'),check('CodeQL')]
required=['validate','translate','CodeQL']
assert m.checks_pass(good,[],required)
assert not m.checks_pass(good[:2],[],required)
assert not m.checks_pass(good+[check('Analyze (python)','failure')],[],required)
assert not m.checks_pass(good+[check('Copilot',None,'in_progress')],[],required)
assert not m.checks_pass(good,[{'state':'pending'}],required)
bad=copy.deepcopy(good);bad[0]['app']['slug']='another-app'
assert not m.checks_pass(bad,[],required)
def test_labels_do_not_authorize_merge():
fake={'state':'open','draft':False,'labels':[{'name':'automerge'}],
'user':{'login':'other'},'base':{'ref':'main','repo':{'full_name':m.REPO}},
'head':{'repo':{'full_name':m.REPO}}}
assert not m.trusted_pr(fake)
fake['user']['login']='mashagua';assert m.trusted_pr(fake)
fake['head']['repo']['full_name']='someone/fork';assert not m.trusted_pr(fake)
def test_receipt_or_unsafe_patch_cannot_authorize_merge(tmp_path):
(tmp_path/'skills'/'sample').mkdir(parents=True)
pr={'state':'open','draft':False,'user':{'login':'mashagua'},'number':1,
'base':{'ref':'main','repo':{'full_name':m.REPO}},
'head':{'ref':'tracked-updates/sample-123','sha':'a'*40,'repo':{'full_name':m.REPO}}}
with patch.object(m,'discover_target',return_value={}),patch.object(m,'plan',return_value=({}, {'identicalInstalledPayload':False})),pytest.raises(t.AuditBlocked):
m.assess(tmp_path,pr,{'tracking':{'sample':{}}})
with patch.object(m,'discover_target',return_value={}),patch.object(m,'plan',return_value=({}, {'identicalInstalledPayload':True})),patch.object(m,'pages',return_value=[{'filename':'.github/workflows/evil.yml','status':'added'}]),pytest.raises(t.AuditBlocked):
m.assess(tmp_path,pr,{'tracking':{'sample':{}}})
def test_publisher_requires_actual_human_not_environment_name():
with patch.object(t,'gh',return_value='github-actions[bot]'),pytest.raises(t.AuditBlocked):t.check_identity()
with patch.object(t,'gh',return_value='mashagua'):t.check_identity()
def test_workflow_privileged_path_never_checks_out_candidate():
root=Path(__file__).resolve().parents[2]
workflow=(root/'.github/workflows/merge-verified-updates.yml').read_text()
assert 'ref: main' in workflow and 'persist-credentials: false' in workflow
assert 'pull_request_target:' not in workflow and 'head_sha' not in workflow
code=(root/'scripts/catalog/merge_verified_updates.py').read_text()
assert "'sha='+pr['head']['sha']" in code and '--admin' not in code
def test_server_must_enforce_up_to_date_exact_base():
assert not m.strict_updates_required([])
rule={'type':'required_status_checks','parameters':{'strict_required_status_checks_policy':True,
'required_status_checks':[{'context':'validate'},{'context':'translate'}]}}
assert m.strict_updates_required([rule])
rule['parameters']['strict_required_status_checks_policy']=False
assert not m.strict_updates_required([rule])
def local_fixture(tmp_path):
source=tmp_path/'source';source.mkdir();git(source,'init','--quiet')
for p,b in payload().items():
f=source/p;f.parent.mkdir(parents=True,exist_ok=True);f.write_bytes(b)
def commit():
git(source,'add','--all')
git(source,'-c','user.name=fixture','-c','user.email=fixture@example.invalid',
'-c','commit.gpgsign=false','commit','--quiet','--allow-empty','-m','fixture')
return git(source,'rev-parse','HEAD').decode().strip()
old=commit()
root=tmp_path/'market';folder=root/'skills'/'sample';folder.mkdir(parents=True)
mapping={}
for p,b in payload().items():
f=folder/p;f.parent.mkdir(parents=True,exist_ok=True);f.write_bytes(b)
mapping[p]={'upstream':p,'upstreamSha256':t.digest(b),'installedSha256':t.digest(b),'installedMode':'100644'}
meta=metadata(old,'git');meta['provenance']['content']['url']='https://github.com/example/project.git'
(folder/'catalog-metadata.v1.json').write_text(json.dumps(meta))
track={'adapter':'local-git','repoUrl':meta['provenance']['content']['url'],'ref':old,'branch':'main','files':mapping}
def fetch_local(repo,*args):
if args[0]=='fetch':args=(*args[:4],str(source),*args[5:])
return git(repo,*args)
return source,root,track,meta,commit,fetch_local
def test_local_upstream_change_preserves_unmodified_market_wrapper(tmp_path):
source,root,track,meta,commit,fetch_local=local_fixture(tmp_path)
folder=root/'skills'/'sample';wrapper=folder/'wrapper.md';wrapper.write_text('market-only wrapper')
track['files']['wrapper.md']={'installedSha256':t.digest(wrapper.read_bytes()),'installedMode':'100644'}
(source/'scripts/tool.py').write_text('print("new upstream")\n');head=commit()
with patch.object(t,'git',side_effect=fetch_local):
changes,updated,report,next_track=t.local_plan(root,'sample',track,meta,{'ref':head})
assert 'skills/sample/scripts/tool.py' in changes
assert 'skills/sample/wrapper.md' not in changes
assert wrapper.read_text()=='market-only wrapper'
assert next_track['ref']==head and updated['governance']['compliance']['reviewedRef']==head
assert not report['identicalInstalledPayload']
def test_local_patch_conflict_blocks_without_overwrite(tmp_path):
source,root,track,meta,commit,fetch_local=local_fixture(tmp_path)
file=root/'skills/sample/scripts/tool.py';file.write_text('market patch')
track['files']['scripts/tool.py']['installedSha256']=t.digest(file.read_bytes())
(source/'scripts/tool.py').write_text('upstream also changed');head=commit()
with patch.object(t,'git',side_effect=fetch_local),pytest.raises(t.AuditBlocked,match='patched file'):
t.local_plan(root,'sample',track,meta,{'ref':head})
assert file.read_text()=='market patch'
def test_new_upstream_notice_outside_mapping_is_not_ignored(tmp_path):
source,root,track,meta,commit,fetch_local=local_fixture(tmp_path)
(source/'NOTICE').write_text('new obligation');head=commit()
with patch.object(t,'git',side_effect=fetch_local),pytest.raises(t.AuditBlocked,match='root license/notice'):
t.local_plan(root,'sample',track,meta,{'ref':head})
def test_local_unmapped_file_blocks(tmp_path):
source,root,track,meta,commit,fetch_local=local_fixture(tmp_path)
(root/'skills/sample/new-wrapper.md').write_text('unmapped')
head=commit()
with pytest.raises(t.AuditBlocked,match='inventory'):
t.local_plan(root,'sample',track,meta,{'ref':head})
def test_artifact_old_provenance_cannot_be_rebound():
meta=metadata();meta['provenance']['content']['sha256']='c'*64
with pytest.raises(t.AuditBlocked,match='old provenance'):
t.audit_payload(None,meta,payload(),payload(),'a'*64,'b'*64,
{'kind':'zip','url':'https://clawhub.ai/download?v=2','sha256':'b'*64})
def test_candidate_cannot_self_authorize_with_same_path_json(tmp_path):
(tmp_path/'skills'/'sample').mkdir(parents=True)
pr={'state':'open','draft':False,'user':{'login':'mashagua'},'number':1,
'base':{'ref':'main','repo':{'full_name':m.REPO}},
'head':{'ref':'tracked-updates/sample-123','sha':'a'*40,'repo':{'full_name':m.REPO}}}
expected={'skills/sample/upstream-audit.v1.json':t.encoded({'checks':{'licenseAndNoticeUnchanged':False}})}
with patch.object(m,'discover_target',return_value={}),patch.object(m,'plan',return_value=(expected,{'identicalInstalledPayload':True})),patch.object(m,'pages',return_value=[{'filename':next(iter(expected)),'status':'modified'}]),patch.object(m,'read_json',return_value={'checks':{'licenseAndNoticeUnchanged':True}}),pytest.raises(t.AuditBlocked,match='differs from fresh'):
m.assess(tmp_path,pr,{'tracking':{'sample':{}}})
def test_unicode_aliases_in_zip_are_not_silently_overwritten():
with pytest.raises(t.AuditBlocked):
unz(archive([('SKILL.md','body'),('é.md','one'),('e\u0301.md','two')]))
@pytest.mark.parametrize('branch,expected',[(None,'HEAD'),('master','refs/heads/master')])
def test_git_merge_gate_tracks_default_head_when_branch_not_declared(tmp_path,branch,expected):
folder=tmp_path/'skills/sample';folder.mkdir(parents=True)
source={'kind':'git','repoUrl':'https://github.com/example/project.git','ref':'a'*40}
if branch:source['repoBranch']=branch
(folder/'entry.json').write_text(json.dumps({'id':'sample','source':source}))
(folder/'catalog-metadata.v1.json').write_text(json.dumps(metadata('a'*40,'git')))
class Result:stdout='b'*40+'\tHEAD\n'
with patch.object(m.subprocess,'run',return_value=Result()) as run, \
patch.object(m,'audit_update',side_effect=t.AuditBlocked('stop after branch resolution')), \
pytest.raises(t.AuditBlocked,match='branch resolution'):
m.git_plan(tmp_path,'sample','b'*40)
assert run.call_args.args[0][-1]==expected
def review_fixture():
pr={'user':{'login':'mashagua'},'head':{'sha':'b'*40}}
review={'user':{'login':'maintainer','type':'User'},'state':'APPROVED','commit_id':'b'*40,
'body':'Inspected installed delta; no licensing, permission, dependency or scope expansion.\nmarket-reviewed-no-expansion: '+'b'*40}
return pr,review
def test_changed_payload_requires_real_exact_head_maintainer_attestation():
pr,review=review_fixture()
with patch.object(m,'api',return_value={'permission':'write'}):assert m.reviewed_no_expansion(pr,[review])
with patch.object(m,'api',return_value={'permission':'read'}):assert not m.reviewed_no_expansion(pr,[review])
@pytest.mark.parametrize('field,value',[
('commit_id','a'*40),('body','market-reviewed-no-expansion: '+'a'*40),
('state','COMMENTED'),('user',{'login':'mashagua','type':'User'}),
('user',{'login':'maintainer','type':'Bot'}),
])
def test_stale_fake_bot_or_self_review_cannot_authorize(field,value):
pr,review=review_fixture();review[field]=value
with patch.object(m,'api') as api:
assert not m.reviewed_no_expansion(pr,[review]);api.assert_not_called()
def test_dismissed_or_requested_changes_invalidate_clearance():
pr,review=review_fixture()
for state in ('DISMISSED','CHANGES_REQUESTED'):
with patch.object(m,'api') as api:
assert not m.reviewed_no_expansion(pr,[review,{**review,'state':state}]);api.assert_not_called()
def test_status_reruns_use_latest_context_not_obsolete_failure():
statuses=[{'id':2,'context':'external-ci','state':'success'},
{'id':1,'context':'external-ci','state':'failure'}]
assert m.checks_pass([check('validate')],statuses,['validate'])
statuses.append({'id':3,'context':'external-ci','state':'pending'})
assert not m.checks_pass([check('validate')],statuses,['validate'])
def test_workflow_rerun_replaces_obsolete_cancelled_run_only():
runs=[{'id':1,'workflow_id':9,'status':'completed','conclusion':'cancelled'},
{'id':2,'workflow_id':9,'status':'completed','conclusion':'success'}]
assert m.workflow_runs_pass(runs)
assert not m.workflow_runs_pass(runs+[{'id':3,'workflow_id':9,'status':'queued','conclusion':None}])
assert not m.workflow_runs_pass(runs+[{'id':4,'workflow_id':10,'status':'completed','conclusion':'failure'}])
assert not m.workflow_runs_pass([])
@pytest.mark.parametrize('path,before,after,expected', [
('SKILL.md', b'---\nname: demo\nversion: 1.0.0\n---\nKeep instructions.\n', b'---\nname: demo\nversion: 1.0.1\n---\nKeep instructions.\n', True),
('skills/demo/SKILL.md', b'---\nversion: "1.0.0"\n---\nBody\n', b'---\nversion: "1.0.1"\n---\nBody\n', True),
('SKILL.md', b'---\nversion: 1.0.0\n---\nOld', b'---\nversion: 1.0.1\n---\nNew', False),
('SKILL.md', b'---\nversion: 1.0.0\nrequiredClientVersion: 2.0.0\n---\nBody', b'---\nversion: 1.0.1\nrequiredClientVersion: 3.0.0\n---\nBody', False),
('SKILL.md', b'---\nversion: 1.0.0\nversion: 1.0.0\n---\nBody', b'---\nversion: 1.0.1\nversion: 1.0.0\n---\nBody', False),
('SKILL.md', b'---\nversion: unknown\n---\nBody', b'---\nversion: latest\n---\nBody', False),
('script.py', b'version: 1.0.0', b'version: 1.0.1', False),
('README.md', b'---\nversion: 1.0.0\n---\nBody', b'---\nversion: 1.0.1\n---\nBody', False),
])
def test_only_proven_top_level_skill_version_change_is_automatic(path, before, after, expected):
assert t.version_only_change(before, after, path) is expected
def test_absent_inapplicable_language_jobs_do_not_block_but_present_failures_do():
# Registry-only pointer diffs may never schedule CodeQL or all language jobs.
mandatory=['validate','translate','wait-for-copilot-review']
baseline=[check(name) for name in mandatory]
assert m.checks_pass(baseline, [], mandatory)
assert not m.checks_pass(baseline + [{**check('CodeQL'), 'conclusion':'failure'}], [], mandatory)
assert not m.checks_pass(baseline + [{**check('Analyze (python)'), 'conclusion':'failure'}], [], mandatory)
assert not m.checks_pass(baseline + [{**check('CodeQL'), 'status':'in_progress'}], [], mandatory)
+342
View File
@@ -0,0 +1,342 @@
"""Real local Git fixtures; no upstream execution, network, or live issue writes."""
import copy
import json
from unittest.mock import patch
import pytest
from audit_skill_update import audit_snapshots, AuditBlocked
from update_diagnostics import inspect_snapshots, mit_grant, render_findings
from unhealthy_report import managed_body, sync_plan, render, START, END
from check_upstream_health import render_markdown
@pytest.fixture
def case():
from test_audit_skill_update import AuditTests
item = AuditTests()
item.setUp()
yield item
item.tearDown()
def baseline(c):
c.old = c.commit()
c.entry['source']['ref'] = c.old
c.metadata['provenance']['content']['ref'] = c.old
c.metadata['governance']['compliance']['reviewedRef'] = c.old
def findings(c):
new = c.commit()
return inspect_snapshots(c.repo,c.entry,c.metadata,{'ref':c.old,'head':new})
def test_full_mit_is_recognized_across_wrapping(case):
assert mit_grant(case.mit.encode())
assert not mit_grant(b'license: MIT\n')
def test_root_notice_does_not_prove_selected_delivery(case):
(case.repo/'skills/sample/LICENSE').unlink()
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
with pytest.raises(AuditBlocked) as blocked:
case.audit()
row=next(r for r in blocked.value.findings if r['gate']=='installed-project-notice')
assert row['origin']=='pre_existing'
assert not row['evidence']['requiredNoticeInsideScope']
assert row['oldRef']==case.old
assert row['newRef']!=case.old
def test_vendor_license_cannot_replace_project_notice(case):
(case.repo/'skills/sample/LICENSE').unlink()
case.write('skills/sample/vendor/LICENSE',case.mit.replace('DesireCore','Different Holder'))
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
assert any(r['gate']=='installed-project-notice' for r in findings(case))
def test_full_readme_notice_is_valid_without_license_filename(case):
(case.repo/'skills/sample/LICENSE').unlink()
case.write('skills/sample/README.md','# Instructions\n\n'+case.mit)
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
_,_,receipt=case.audit()
assert receipt['source']['ref']!=case.old
def test_spdx_frontmatter_is_not_full_mit_notice(case):
(case.repo/'skills/sample/LICENSE').unlink()
path='skills/sample/SKILL.md'
case.write(path,(case.repo/path).read_text().replace('version:','license: MIT\nversion:'))
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
assert any(r['gate']=='installed-project-notice' for r in findings(case))
def test_unchanged_weak_readme_exception_is_not_inherited(case):
case.write('README.md','License: MIT; manually accepted only at old pin\n')
case.metadata['governance']['license']['evidencePath']='README.md'
case.metadata['governance']['compliance']['licenseEvidencePath']='README.md'
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
row=next(r for r in findings(case) if r['gate']=='pin-bound-license-exception')
assert row['state']=='manual_review'
assert row['evidence']['oldSha256']==row['evidence']['newSha256']
def test_data_only_new_pin_still_cannot_expand_license_exception(case):
case.write('README.md','MIT')
case.metadata['governance']['license']['evidencePath']='README.md'
case.metadata['governance']['compliance']['licenseEvidencePath']='README.md'
baseline(case)
case.write('skills/sample/feed.json','{"data":"only"}')
with pytest.raises(AuditBlocked,match='pin-bound-license-exception'):
case.audit()
def test_notice_delivery_regression_is_introduced_not_historical(case):
(case.repo/'skills/sample/LICENSE').unlink()
row=next(r for r in findings(case) if r['gate']=='installed-project-notice')
assert row['origin']=='introduced'
def test_rediscovery_is_not_new_physical_skill_and_failfast_is_explicit(case):
case.entry['children']=[{'id':'sample','path':'skills/sample'}]
marker='skills/in-progress/software-factory/SKILL.md'
case.write(marker,'---\nname: software-factory\ndescription: Invalid: YAML\n---\nUnchanged body\n')
baseline(case)
case.write(marker,'---\nname: software-factory\ndescription: "Invalid: YAML"\n---\nUnchanged body\n')
case.write('skills/sample/SKILL.md','---\nname: sample\ndescription: Delegate with fresh context\n---\nBody\n')
case.write('package.json',json.dumps({'devDependencies':{'yaml':'^2.9.1'}}))
with pytest.raises(AuditBlocked,match='合集成员') as blocked:
case.audit()
rows=blocked.value.findings
inventory=next(r for r in rows if r['gate']=='collection-inventory')
assert inventory['evidence']['physicalAdded']==[]
assert inventory['evidence']['physicalRemoved']==[]
assert inventory['evidence']['rediscovered']==[marker]
assert next(r for r in rows if r['gate']=='collection-members')['origin']=='pre_existing'
assert any(r['gate']=='description-and-locales' for r in rows)
assert any(r['gate']=='remaining-pipeline' and r['state']=='not_checked' for r in rows)
dependency=next(r for r in rows if r['gate']=='dependency-context')
assert dependency['path']=='package.json#devDependencies'
assert dependency['evidence']['rootInsideSelectedScope'] is False
def test_version_prose_only_flags_proven_old_plugin_version(case):
case.write('.claude-plugin/plugin.json','{"version":"0.6.17"}')
case.entry['i18n']={'zh-CN':{'shortDesc':'插件 v0.6.17,2026 年,26 个技能'},'en-US':{'shortDesc':'26 skills in 2026'}}
baseline(case)
case.write('.claude-plugin/plugin.json','{"version":"0.6.18"}')
rows=findings(case)
copies=[r for r in rows if r['gate']=='version-copy']
assert len(copies)==1
assert 'zh-CN' in copies[0]['path']
assert copies[0]['state']=='manual_review'
def test_arbitrary_numbers_are_not_version_sources(case):
case.entry['i18n']={'en-US':{'shortDesc':'26 skills in 2026; Python 3.12'}}
case.write('skills/sample/scripts/tool.py','new')
assert not any(r['gate'].startswith('version') for r in findings(case))
def test_derived_locale_mismatch_is_precise(case):
case.entry['children']=[{'id':'sample','path':'skills/sample','i18n':{'zh-CN':{'shortDesc':'已审核中文'}}}]
case.metadata['spec']={'collection':{'children':[{'identity':{'id':'sample'},'presentation':{'i18n':{'zh-CN':{'summary':'旧中文'}}}}]}}
case.write('skills/sample/scripts/tool.py','new')
row=next(r for r in findings(case) if r['gate']=='derived-locales')
assert row['path']=='skills/sample'
assert row['origin']=='pre_existing'
def test_identical_bilingual_fallback_is_info_not_new_failure(case):
case.entry['children']=[{'id':'sample','path':'skills/sample','i18n':{'zh-CN':{'shortDesc':'Fixture'},'en-US':{'shortDesc':'Fixture'}}}]
case.write('skills/sample/scripts/tool.py','new')
row=next(r for r in findings(case) if r['gate']=='translation-fallback')
assert row['state']=='info' and row['origin']=='pre_existing'
@pytest.mark.parametrize('error_type',[ValueError,TypeError,KeyError,AttributeError])
def test_unparseable_diagnostics_fail_closed_not_passed(case,error_type):
case.write('skills/sample/scripts/tool.py','new')
with patch('update_diagnostics.inspect_snapshots',side_effect=error_type('unavailable')):
with pytest.raises(AuditBlocked) as blocked:
case.audit()
assert blocked.value.findings[0]['state']=='not_checked'
def test_bilingual_table_preserves_refs_and_escapes_untrusted_cells(case):
(case.repo/'skills/sample/LICENSE').unlink()
rows=findings(case)
rows[0]['reason']='中文 | English\nline'
text=render_findings(rows)
assert '精确旧→新 pin / Exact pins' in text
assert case.old in text and rows[0]['newRef'] in text
assert '\\|' in text and '<br>' in text
@pytest.mark.parametrize('actionable,complete,initial,expected',[
(True,True,'closed','open'),(False,True,'open','closed'),
(False,False,'open',None),(True,True,'open',None)])
def test_issue_lifecycle_no_comment_operations(actionable,complete,initial,expected):
report='当前 / Current'
issue={'state':initial,'body':managed_body('',report)}
result=sync_plan(issue,report,actionable,complete)
assert result.get('state')==expected
assert 'body' not in result
assert 'comment' not in result
def test_first_issue_adoption_preserves_manual_bilingual_content_and_markers():
previous='_Updated by [Upstream Health](https://example.invalid/run)._\n\n手动中文 / Manual English\n<!-- existing -->'
merged=managed_body(previous,'新报告 / New report')
assert previous in merged
assert '历史快照,非当前结果 / Previous snapshot' in merged
assert merged.count(START)==1 and merged.count(END)==1
assert managed_body(merged,'新报告 / New report')==merged
def test_managed_issue_edit_preserves_human_prefix_suffix():
previous='维护者说明 / Maintainer note\n'+START+'\nold\n'+END+'\n<!-- keep -->'
result=managed_body(previous,'新 / New')
assert result.startswith('维护者说明 / Maintainer note\n')
assert result.endswith('\n<!-- keep -->')
assert 'old' not in result
def test_no_timestamp_churn_and_incomplete_report_never_resolves():
health=[{'id':'x','kind':'skill','url':'https://github.com/example/x','ref':'a'*40,'head':'a'*40,'issues':[{'status':'ok','detail':'ok'}]}]
text,active=render(health,[],[],True)
assert active is False
assert render(health,[],[],True)==(text,active)
assert render(health,[],[],False)[1] is True
assert '状态 / State' in text
def test_health_reason_and_action_are_bilingual_without_changing_data():
data=[{'id':'sample','kind':'skill','url':'https://github.com/example/x','ref':'a'*40,'head':'b'*40,'issues':[{'status':'upstream-path-change','detail':"source.path 'skills/x' has no SKILL.md"}]}]
before=copy.deepcopy(data)
text=render_markdown(data)
assert '上游路径变化' in text and 'Upstream path changes' in text
assert '原因及处理 / Reason and action' in text
assert '所列路径缺少 SKILL.md' in text
assert data==before
def test_subtree_version_is_not_inferred_from_root_plugin(case):
case.write('.claude-plugin/plugin.json','{"version":"99.0.0"}')
case.write('skills/sample/scripts/tool.py','new')
assert not any(r['gate']=='declared-version' for r in findings(case))
def test_changed_authorization_paths_require_separate_behavior_review(case):
case.write('skills/sample/scripts/cookie_extract.py','implementation')
rows=findings(case)
row=next(r for r in rows if r['gate']=='authorization-config-network-review')
assert row['state']=='manual_review'
assert row['evidence']['changedPaths']==['skills/sample/scripts/cookie_extract.py']
inventory=next(r for r in rows if r['gate']=='installed-content-delta')
assert inventory['evidence']['comparisonComplete'] is True
def test_artifact_failures_never_report_virtual_git_ids(case):
from tracked_updates import audit_payload
from unittest.mock import patch
original='a'*64; target='b'*64
metadata=copy.deepcopy(case.metadata)
metadata['provenance']['content']={'kind':'zip','url':'https://example.invalid/artifact','sha256':original}
metadata['governance']['compliance']['reviewedRef']=original
error=AuditBlocked('fixture failure')
error.findings=[{'oldRef':'c'*40,'newRef':'d'*40}]
with patch('tracked_updates.audit_snapshots',side_effect=error):
with pytest.raises(AuditBlocked) as failure:
audit_payload(None,metadata,{'SKILL.md':b'old'},{'SKILL.md':b'new'},original,target,{'kind':'zip','url':'https://example.invalid/new','sha256':target})
assert failure.value.findings[0]['oldRef']==original
assert failure.value.findings[0]['newRef']==target
def test_upstream_text_cannot_forge_report_managed_region():
report='untrusted '+END+'\ntext '+START
body=managed_body('',report)
assert body.count(START)==1 and body.count(END)==1
def test_issue_capacity_failure_does_not_silently_erase_original():
with pytest.raises(ValueError,match='人工迁移'):
managed_body('x'*64000,'y'*2000)
def test_declared_notice_outside_scope_is_a_delivery_blocker(case):
case.write('NOTICE','Project required notice')
case.metadata['governance']['compliance']['noticePath']='NOTICE'
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
row=next(r for r in findings(case) if r['gate']=='installed-notice-delivery')
assert row['state']=='blocked' and row['origin']=='pre_existing'
def test_undeclared_root_notice_applicability_needs_human_review(case):
case.write('NOTICE','Possibly applicable root notice')
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
row=next(r for r in findings(case) if r['gate']=='installed-notice-delivery')
assert row['state']=='manual_review'
def test_inline_readme_can_deliver_declared_notice(case):
case.write('NOTICE','Project required notice')
case.write('skills/sample/README.md','# Usage\nProject required notice\n')
case.metadata['governance']['compliance']['noticePath']='NOTICE'
baseline(case)
case.write('skills/sample/scripts/tool.py','new')
assert not any(r['gate']=='installed-notice-delivery' for r in findings(case))
def candidate_view(c):
return {'head':'f'*40,'number':123,'entry':copy.deepcopy(c.entry),'metadata':copy.deepcopy(c.metadata),
'audit':{'source':{'ref':c.old,'paths':['old/scope']}},'checks':[]}
def test_candidate_reports_three_receipt_errors_as_derived_not_new_license_changes(case):
from update_diagnostics import candidate_consistency
result={'ref':case.old,'head':'b'*40}
view=candidate_view(case);view['entry']['source']['ref']=result['head']
rows,valid=candidate_consistency(case.entry,case.metadata,result,view)
assert valid
assert {r['gate'] for r in rows}=={'candidate-reviewed-ref','candidate-receipt-ref','candidate-receipt-scope'}
assert all(r['origin']=='derived' for r in rows)
assert all(r['basis']=='existing-pr-candidate@'+'f'*40 for r in rows)
assert rows[0]['evidence']['reviewedRef']==case.old
def test_correct_candidate_receipt_is_not_reported_as_old_main_error(case):
from update_diagnostics import candidate_consistency
result={'ref':case.old,'head':'b'*40}
view=candidate_view(case);view['entry']['source']['ref']=result['head']
view['metadata']['governance']['compliance']['reviewedRef']=result['head']
view['audit']['source']={'ref':result['head'],'paths':['skills/sample']}
assert candidate_consistency(case.entry,case.metadata,result,view)==([],True)
def test_candidate_cannot_repoint_static_proof_to_untrusted_source(case):
from update_diagnostics import candidate_consistency
result={'ref':case.old,'head':'b'*40}
view=candidate_view(case);view['entry']['source'].update(ref=result['head'],repoUrl='https://github.com/other/source.git')
rows,valid=candidate_consistency(case.entry,case.metadata,result,view)
assert not valid and rows[0]['gate']=='candidate-source'
def test_live_check_failure_is_not_misclassified_as_receipt_derivative(case):
from update_diagnostics import candidate_consistency
result={'ref':case.old,'head':'b'*40}
view=candidate_view(case);view['entry']['source']['ref']=result['head']
view['checks']=[{'name':'validate','status':'completed','conclusion':'failure','details_url':'https://github.com/example/check'}]
rows,_=candidate_consistency(case.entry,case.metadata,result,view)
check=next(r for r in rows if r['gate']=='candidate-live-check')
assert check['origin']=='unknown'
assert check['evidence']['conclusion']=='failure'
+412
View File
@@ -0,0 +1,412 @@
"""Pinned artifact/local tracking. Never execute upstream code or infer versions.
Policy is read from the trusted base checkout, never from a candidate PR.
A content hash identifies bytes; only audit_payload produces admission evidence.
"""
from __future__ import annotations
import copy
import hashlib
import io
import json
import re
import stat
import subprocess
import tempfile
import urllib.parse
import urllib.request
import unicodedata
import zipfile
from datetime import datetime, timezone
from pathlib import Path, PurePosixPath
from audit_skill_update import AuditBlocked, audit_snapshots, git, root_evidence, root_license_directory_files
from automated_review import validate_record
CONFIG = 'config/verified-updates.v1.json'
LOGIN = 'mashagua'
EMAIL = '993498039@qq.com'
MAX_BYTES = 50 * 1024 * 1024
MAX_FILE = 1024 * 1024
SHA40 = re.compile(r'[0-9a-f]{40}')
SLUG = re.compile(r'[a-z0-9]+(?:-[a-z0-9]+)*')
REPO = re.compile(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+')
def digest(data):
return hashlib.sha256(data).hexdigest()
def safe_path(value, empty=False):
p = PurePosixPath(value)
if (not isinstance(value, str) or '\\' in value or p.is_absolute() or '..' in p.parts
or (not empty and (not value or str(p) == '.')) or str(p) != value):
raise AuditBlocked('unsafe/non-canonical tracked path')
if (any(ord(c) < 32 for c in value) or ':' in value
or any(part.endswith((' ', '.')) or re.fullmatch(r'(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])(?:\..*)?', part, re.I) for part in p.parts)):
raise AuditBlocked('path is unsafe on a supported desktop platform')
if any(part in ('.git', '.github') for part in p.parts):
raise AuditBlocked('repository control path cannot be tracked content')
return value
def allowed_url(url):
p = urllib.parse.urlsplit(url)
if (p.scheme != 'https' or p.username or p.password or p.port not in (None, 443)
or p.fragment or not p.hostname):
raise AuditBlocked('only credential-free HTTPS artifacts are supported')
if p.hostname not in ('api.github.com', 'github.com', 'raw.githubusercontent.com',
'objects.githubusercontent.com', 'release-assets.githubusercontent.com',
'clawhub.ai', 'wry-manatee-359.convex.site'):
raise AuditBlocked('artifact host is not a supported registry/release host')
return url
class Redirects(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
allowed_url(newurl)
return super().redirect_request(req, fp, code, msg, headers, newurl)
def fetch(url):
allowed_url(url)
req = urllib.request.Request(url, headers={'User-Agent': 'market-verified-updates/1'})
with urllib.request.build_opener(Redirects()).open(req, timeout=45) as response:
data = response.read(MAX_BYTES + 1)
if len(data) > MAX_BYTES:
raise AuditBlocked('artifact download exceeds budget')
return data
def json_url(url):
return json.loads(fetch(url))
def gh(*args):
return subprocess.run(['gh', *args], check=True, capture_output=True, text=True).stdout.strip()
def version_only_change(before: bytes, after: bytes, path: str) -> bool:
"""Prove only the top-level SKILL.md frontmatter version scalar changed.
Not a semantic security classifier: instructions, scripts, nested metadata,
dependencies, permissions, file inventory and all other bytes stay identical.
"""
if PurePosixPath(path).name != 'SKILL.md':
return False
def mask(data):
if not data.startswith(b'---\n'):
return None
end = data.find(b'\n---\n', 4)
if end < 0:
return None
front = data[4:end]
pattern = rb'''(?m)^version: (?P<quote>["']?)[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?(?P=quote)[ \t]*$'''
matches = list(re.finditer(pattern, front))
# A duplicate/multiline/ambiguous version declaration is never automatic.
if len(matches) != 1 or len(re.findall(rb'(?m)^version\s*:', front)) != 1:
return None
masked = re.sub(pattern, b'version: <audited-version>', front)
return data[:4] + masked + data[end:]
old, new = mask(before), mask(after)
return old is not None and old == new
def check_identity():
if gh('api', 'user', '--jq', '.login') != LOGIN:
raise AuditBlocked('publishing/merge requires the designated human maintainer; no bot fallback')
def load_config(root):
cfg = json.loads((root / CONFIG).read_text())
if cfg.get('schemaVersion') != 1 or cfg.get('autoMerge') != 'reviewed-or-no-behavior-change':
raise AuditBlocked('unsupported automation policy')
required = cfg.get('requiredChecks')
if (not isinstance(required, list) or not all(isinstance(x, str) for x in required)
or not {'validate', 'translate'} <= set(required)):
raise AuditBlocked('required exact-head checks cannot be omitted')
if not isinstance(cfg.get('tracking'), dict):
raise AuditBlocked('missing explicit tracking map')
if any(not SLUG.fullmatch(k) for k in cfg['tracking']):
raise AuditBlocked('invalid tracking id')
return cfg
def discover(track, source):
adapter = track.get('adapter')
if adapter == 'clawhub':
slug, owner = track['slug'], track['owner']
if not SLUG.fullmatch(slug) or not re.fullmatch(r'[A-Za-z0-9_-]+', owner):
raise AuditBlocked('invalid registry identity')
meta = json_url(f'https://clawhub.ai/api/v1/skills/{slug}?ownerHandle={owner}')
if meta.get('owner', {}).get('handle') != owner or meta.get('skill', {}).get('slug') != slug:
raise AuditBlocked('registry owner changed or could not be verified')
version = meta.get('latestVersion', {}).get('version')
if not isinstance(version, str) or not re.fullmatch(r'\d+\.\d+\.\d+', version):
raise AuditBlocked('registry lacks an explicit stable version')
url = 'https://clawhub.ai/api/v1/download?' + urllib.parse.urlencode(
{'slug': slug, 'version': version, 'ownerHandle': owner})
# Version-specific endpoint, never an unpinned /latest download.
return {'kind': 'zip', 'repoUrl': url, **({'path': source['path']} if source.get('path') else {})}
if adapter in ('github-file', 'github-release'):
repo = track['repo']
if not REPO.fullmatch(repo):
raise AuditBlocked('invalid GitHub repository')
if adapter == 'github-file':
ref = json_url(f'https://api.github.com/repos/{repo}/commits/' + urllib.parse.quote(track['branch'], safe=''))['sha']
if not SHA40.fullmatch(ref):
raise AuditBlocked('GitHub did not return an immutable commit')
path = safe_path(track['path'])
return {'kind': 'web', 'repoUrl': f'https://raw.githubusercontent.com/{repo}/{ref}/{path}'}
release = json_url(f'https://api.github.com/repos/{repo}/releases/latest')
if release.get('draft') or release.get('prerelease') or not release.get('tag_name'):
raise AuditBlocked('release is not stable/published')
assets = [a for a in release.get('assets', []) if a.get('name') == track['asset']]
if len(assets) != 1 or not assets[0]['browser_download_url'].startswith(f'https://github.com/{repo}/releases/download/'):
raise AuditBlocked('missing/ambiguous release asset')
return {'kind': 'zip', 'repoUrl': assets[0]['browser_download_url'], **({'path': source['path']} if source.get('path') else {})}
raise AuditBlocked('no supported discovery adapter; explicit tracking required')
class Payload(dict):
modes = None
def unpack(source, data):
if digest(data) != source['sha256']:
raise AuditBlocked('download bytes do not match the immutable digest')
if source['kind'] == 'web':
if len(data) > MAX_FILE:
raise AuditBlocked('web file exceeds ordinary audit budget')
return {'SKILL.md': data}
result, total, count = Payload(), 0, 0
result.modes = {}
folded = set()
prefix = source.get('path', '')
if prefix:
safe_path(prefix)
with zipfile.ZipFile(io.BytesIO(data)) as archive:
for info in archive.infolist():
count += 1
if count > 2000 or info.flag_bits & 1:
raise AuditBlocked('ZIP entry budget/encryption rejected')
path = info.filename.rstrip('/')
safe_path(path)
mode = info.external_attr >> 16
if mode & 0o111 and not info.is_dir():
raise AuditBlocked('executable ZIP content requires manual review')
if mode and stat.S_IFMT(mode) not in (0, stat.S_IFREG, stat.S_IFDIR):
raise AuditBlocked('ZIP symlink/special file rejected')
if info.is_dir():
continue
total += info.file_size
if info.file_size > MAX_FILE or total > MAX_BYTES:
raise AuditBlocked('ZIP expansion exceeds ordinary audit budget')
key = unicodedata.normalize('NFC', path).casefold()
if key in folded:
raise AuditBlocked('duplicate/case-colliding ZIP path')
folded.add(key)
result.modes[path] = mode
result[path] = archive.read(info)
if prefix:
modes = {p[len(prefix)+1:]: m for p, m in result.modes.items() if p.startswith(prefix + '/')}
result = Payload({p[len(prefix)+1:]: b for p, b in result.items() if p.startswith(prefix + '/')})
result.modes = modes
if 'SKILL.md' not in result:
raise AuditBlocked('selected artifact has no root SKILL.md')
return result
def commit_payload(repo, files):
for item in repo.iterdir():
if item.name != '.git':
import shutil
shutil.rmtree(item) if item.is_dir() else item.unlink()
for name, data in files.items():
p = repo / safe_path(name)
p.parent.mkdir(parents=True, exist_ok=True)
p.write_bytes(data)
git(repo, 'add', '--all')
git(repo, '-c', f'user.name={LOGIN}', '-c', f'user.email={EMAIL}',
'-c', 'commit.gpgsign=false', 'commit', '--allow-empty', '--quiet', '-m', 'materialized audit snapshot')
return git(repo, 'rev-parse', 'HEAD').decode().strip()
def audit_payload(entry, metadata, old_files, new_files, old_ref, new_ref, new_content):
"""Use the existing strict delta audit on materialized bytes, NOT a hash-only admission.
Temporary Git IDs are transport identities only, replaced with the real
artifact digest / upstream commit in the receipt. No upstream code runs.
"""
if getattr(old_files, 'modes', None) != getattr(new_files, 'modes', None):
raise AuditBlocked('artifact file permissions changed; manual review required')
origin = metadata.get('provenance', {}).get('content', {})
if (origin.get('ref') or origin.get('sha256')) != old_ref or origin.get('kind') != new_content.get('kind'):
raise AuditBlocked('old provenance does not bind the real admitted snapshot')
gov = metadata['governance']
if (gov.get('availability') != 'installable' or gov.get('license', {}).get('state') != 'known'
or gov.get('compliance', {}).get('reviewedRef') != old_ref or old_ref == new_ref):
raise AuditBlocked('old snapshot lacks inheritable exact-pin admission')
with tempfile.TemporaryDirectory(prefix='market-materialized-') as tmp:
repo = Path(tmp)
git(repo, 'init', '--quiet')
a, b = commit_payload(repo, old_files), commit_payload(repo, new_files)
virtual = {'id': metadata['identity']['id'], 'source': {'kind': 'git', 'repoUrl': new_content['url'], 'ref': a}}
if entry and entry.get('latestVersion'):
virtual['latestVersion'] = entry['latestVersion']
sidecar = copy.deepcopy(metadata)
sidecar['provenance']['content'] = {'kind': 'git', 'url': new_content['url'], 'ref': a}
sidecar['governance']['compliance']['reviewedRef'] = a
try:
_, updated, report = audit_snapshots(repo, virtual, sidecar, {'ref': a, 'head': b})
except AuditBlocked as error:
for finding in getattr(error, 'findings', []):
finding.update(oldRef=old_ref, newRef=new_ref, sourceUrl=new_content['url'])
raise
updated['provenance']['content'] = copy.deepcopy(new_content)
updated['governance']['compliance']['reviewedRef'] = new_ref
report['source'] = {'kind': new_content['kind'], 'url': new_content['url'], 'previousUrl': metadata['provenance']['content']['url'],
'previousRef': old_ref, 'ref': new_ref, 'paths': ['']}
report['identicalInstalledPayload'] = old_files == new_files
report['versionOnlyInstalledPayload'] = all(
old_files[p] == new_files[p] or version_only_change(old_files[p], new_files[p], p)
for p in old_files)
report['limitations'].append('Artifact/local bytes materialized solely for the existing delta audit; receipt pins refer to real upstream commits or SHA-256, not temporary Git commits. Upstream code was not executed.')
problems = validate_record(updated, report)
if problems:
raise AuditBlocked('; '.join(problems))
return updated, report
def source_blob(repo, ref, path):
record = git(repo, 'ls-tree', '-z', ref, '--', path).rstrip(b'\0')
if not record or b'\0' in record:
raise AuditBlocked('mapped upstream file missing or ambiguous: ' + path)
meta, name = record.split(b'\t', 1)
mode, kind, oid = meta.decode().split()
if name.decode() != path or kind != 'blob' or mode not in ('100644', '100755'):
raise AuditBlocked('mapped upstream file is not regular: ' + path)
if int(git(repo, 'cat-file', '-s', oid)) > MAX_FILE:
raise AuditBlocked('mapped upstream file exceeds budget: ' + path)
return git(repo, 'cat-file', 'blob', oid)
def local_plan(root, item_id, track, metadata, target=None):
origin = metadata['provenance']['content']
if origin.get('kind') != 'git' or origin['url'] != track['repoUrl'] or origin['ref'] != track['ref']:
raise AuditBlocked('local map does not match admitted upstream pin')
url = track['repoUrl']
if not re.fullmatch(r'https://github\.com/[\w.-]+/[\w.-]+\.git', url):
raise AuditBlocked('local tracking requires GitHub HTTPS provenance')
head = (target or discover_target(root, item_id, track))['ref']
if not SHA40.fullmatch(head):
raise AuditBlocked('invalid upstream head')
if head == track['ref']:
return None
old_files, new_files, next_track = {}, {}, copy.deepcopy(track)
# Mapping covers every package file other than separately generated governance/i18n bookkeeping.
folder = root / 'skills' / item_id
actual = {str(p.relative_to(folder)) for p in folder.rglob('*') if p.is_file()}
if any(p.is_symlink() for p in folder.rglob('*')):
raise AuditBlocked('local symlink rejected')
if actual != set(track['files']) | {'catalog-metadata.v1.json', 'upstream-audit.v1.json'} - ({'upstream-audit.v1.json'} if not (folder/'upstream-audit.v1.json').exists() else set()):
raise AuditBlocked('local package file inventory changed; review mapping')
with tempfile.TemporaryDirectory(prefix='market-local-source-') as tmp:
repo = Path(tmp)
git(repo, 'init', '--quiet')
git(repo, 'fetch', '--quiet', '--no-tags', '--depth=1', url, track['ref'], head)
if (root_evidence(repo, track['ref']) != root_evidence(repo, head)
or root_license_directory_files(repo, track['ref']) != root_license_directory_files(repo, head)):
raise AuditBlocked('upstream root license/notice changed, including files outside the local mapping')
for local, mapping in track['files'].items():
safe_path(local)
current_path = folder / local
mode = '100755' if current_path.stat().st_mode & 0o111 else '100644'
if mode != mapping['installedMode']:
raise AuditBlocked('market file permission changed; rebaseline mapping')
current = current_path.read_bytes()
if digest(current) != mapping['installedSha256']:
raise AuditBlocked('market wrapper/patch changed; rebaseline mapping')
old_files[local] = new_files[local] = current
if mapping.get('upstream'):
source_path = safe_path(mapping['upstream'])
before = source_blob(repo, track['ref'], source_path)
after = source_blob(repo, head, source_path)
modes = [git(repo, 'ls-tree', ref, '--', source_path).decode().split()[0] for ref in (track['ref'], head)]
if modes[0] != modes[1] or modes[0] not in ('100644', '100755'):
raise AuditBlocked('upstream changed file type/permissions')
if len(after) > MAX_FILE or digest(before) != mapping['upstreamSha256']:
raise AuditBlocked('upstream mapping hash/budget changed')
# Never silently overwrite a local derivative, including translations and wrappers.
if digest(current) != digest(before) and before != after:
raise AuditBlocked('upstream changed a locally patched file: ' + local + '; manual three-way reconciliation required')
if before != after:
new_files[local] = after
next_track['files'][local]['installedSha256'] = digest(after)
next_track['files'][local]['upstreamSha256'] = digest(after)
if sum(map(len, new_files.values())) > MAX_BYTES:
raise AuditBlocked('local package exceeds total audit budget')
content = {**origin, 'ref': head}
updated, report = audit_payload(None, metadata, old_files, new_files, track['ref'], head, content)
next_track['ref'] = head
changes = {f'skills/{item_id}/{p}': b for p, b in new_files.items() if b != old_files[p]}
return changes, updated, report, next_track
def discover_target(root, item_id, track):
if track['adapter'] == 'local-git':
url = track['repoUrl']
if not re.fullmatch(r'https://github\.com/[\w.-]+/[\w.-]+\.git', url):
raise AuditBlocked('unsupported upstream')
text = subprocess.run(['git', 'ls-remote', url, 'refs/heads/' + track['branch']], check=True, capture_output=True, text=True).stdout.split()
if not text or not SHA40.fullmatch(text[0]):
raise AuditBlocked('missing immutable upstream branch head')
return {'ref': text[0]}
entry = json.loads((root / 'skills' / item_id / 'entry.json').read_text())
return discover(track, entry['source'])
def plan(root, item_id, cfg, target=None):
folder = root / 'skills' / item_id
if not SLUG.fullmatch(item_id) or (folder / 'upstream-health-hold.json').exists():
raise AuditBlocked('invalid id or tracked hold; manual handling required')
metadata = json.loads((folder / 'catalog-metadata.v1.json').read_text())
track = cfg['tracking'][item_id]
if track['adapter'] == 'local-git':
result = local_plan(root, item_id, track, metadata, target)
if result is None:
return None
changes, updated, report, next_track = result
next_config = copy.deepcopy(cfg)
next_config['tracking'][item_id] = next_track
changes[CONFIG] = encoded(next_config)
else:
entry = json.loads((folder / 'entry.json').read_text())
old = entry['source']
origin = metadata.get('provenance', {}).get('content', {})
if origin.get('url') != (old.get('repoUrl') or old.get('url')) or origin.get('kind') != old.get('kind'):
raise AuditBlocked('artifact pointer/provenance mismatch')
new = copy.deepcopy(target) if target is not None else discover(track, old)
# A source kind/path change is NOT an automatic update.
if old['kind'] != new['kind'] or old.get('path', '') != new.get('path', ''):
raise AuditBlocked('source type/install scope changed; manual review required')
if old.get('path'):
raise AuditBlocked('non-root artifact scope requires a reviewed layout adapter')
new_bytes = fetch(new['repoUrl'])
new['sha256'] = digest(new_bytes)
if old == new:
return None
old_bytes = fetch(old.get('repoUrl') or old['url'])
before, after = unpack(old, old_bytes), unpack(new, new_bytes)
updated, report = audit_payload(entry, metadata, before, after, old['sha256'], new['sha256'],
{'kind': new['kind'], 'url': new['repoUrl'], 'sha256': new['sha256']})
if report.get('observedVersions', {}).get(''):
entry['latestVersion'] = report['observedVersions']['']
entry['source'] = new
changes = {f'skills/{item_id}/entry.json': encoded(entry)}
changes[f'skills/{item_id}/catalog-metadata.v1.json'] = encoded(updated)
changes[f'skills/{item_id}/upstream-audit.v1.json'] = encoded(report)
return changes, report
def encoded(obj):
return (json.dumps(obj, ensure_ascii=False, indent=2) + '\n').encode()
+122
View File
@@ -0,0 +1,122 @@
#!/usr/bin/env python3
"""Bilingual exact-evidence report and idempotent existing-issue lifecycle.
Only trusted default-branch workflows run this. Does not execute upstream code,
change admission receipts, create PRs, merge, or post issue comments.
"""
from __future__ import annotations
import argparse
import json
import os
import subprocess
from pathlib import Path
from check_upstream_health import render_markdown, summarize
from update_diagnostics import render_findings
START = '<!-- market-upstream-health:begin -->'
END = '<!-- market-upstream-health:end -->'
TITLE = '上游健康与更新审核报告 / Upstream health and update audit report'
GUIDE = ('通过普通 PR 修正来源/路径、审核精确目标 pin 及安装通知;失败保持草稿,不重绑旧回执。网络未知或预算未覆盖不等于通过。\n\n'
'Use normal PRs to fix sources/paths and review exact target pins and installed notices. Failures stay drafts; never rebind old receipts. Unknown network status or unreviewed budget overflow is not a pass.')
def render(results, coverage, tracked, complete=True):
rows = []
for item in [*coverage, *tracked]:
if not item.get('parentId'):
rows.extend(item.get('findings', []))
out = [GUIDE, '', render_markdown(results), '', '## 更新审核结果 / Update audit results', '',
'完整逐项证据见同次 Actions 的 audit-results 工件;本报告不代表运行验收。 / Complete per-item evidence is in the audit-results artifact of the same Actions run; this report is not runtime acceptance.', '',
'| 技能 / Skill | 状态 / State | 精确旧→新 pin / Exact pins | 原因 / Reason |', '|---|---|---|---|']
labels = {'audit-passed':'静态审核通过 / static audit passed', 'manual-review-required':'人工待审 / manual review',
'queued':'预算内未轮到,未审核 / queued, not audited', 'already-open':'已有 PR,本轮未重审 / existing PR, not re-audited',
'already-proposed':'同 pin 已提案,本轮未重审 / same pin already proposed, not re-audited',
'publish-failed':'发布失败 / publishing failed', 'not-checked':'未检查 / not checked',
'held':'已暂缓 / held', 'current':'来源无待处理更新 / source current'}
for row in [r for r in coverage if not r.get('parentId') and r['status'] not in ('current','market-release')] + tracked:
reason = str(row.get('reason', '')).split('\n')[0].replace('|', '\\|')
out.append(f"| {row['id']} | {labels.get(row['status'], '需按原始详情复核 / see evidence: ' + row['status'])} | {row.get('oldRef', '未读取 / not read')} → {row.get('newRef', '未读取 / not read')} | {reason} |")
if rows:
out.extend(['', '## 精确失败与独立静态发现 / Exact failures and independent static findings', '', render_findings(rows)])
if not complete:
out.extend(['', '**本轮不完整,不能闭环为已解决。 / This run is incomplete; it cannot resolve the issue.**'])
text = '\n'.join(out)
# Keep the full structured report as an artifact; never silently claim that
# omitted diagnostics passed or fabricate a shortened receipt.
if len(text) > 42000:
text = text[:41000].rsplit('\n', 1)[0] + '\n\n展示已截断,完整证据必须查看 audit-results 工件;不是检查通过。 / Display truncated; consult the complete audit-results artifact. This is not a pass.\n'
pending = any(r['status'] not in ('current', 'market-release', 'audit-passed', 'held', 'governance-blocked', 'requires-version-feed')
for r in [*coverage, *tracked] if not r.get('parentId'))
summary = summarize(results)
actionable = not complete or pending or summary['actionable'] or summary['unknown']
return text, bool(actionable)
def managed_body(previous, report):
safe_report = report.replace(START, '&lt;!-- market-upstream-health:begin --&gt;').replace(END, '&lt;!-- market-upstream-health:end --&gt;')
managed = START + '\n' + safe_report.strip() + '\n' + END
if START in previous and END in previous:
prefix, rest = previous.split(START, 1)
_, suffix = rest.split(END, 1)
return prefix + managed + suffix
if previous.strip():
# First adoption preserves the hand-translated issue as an explicitly
# historical snapshot. Never silently erase human text or markers.
archive = '\n\n<details><summary>历史快照,非当前结果 / Previous snapshot, not current results</summary>\n\n' + previous.strip() + '\n\n</details>\n'
if len(managed + archive) > 65000:
raise ValueError('保留现有正文会超出 issue 上限;需人工迁移 / issue preservation requires manual migration')
return managed + archive
return managed + '\n'
def sync_plan(issue, report, actionable, complete):
body = managed_body(issue.get('body') or '', report)
edits = {}
if body != (issue.get('body') or ''):
edits['body'] = body
if actionable and issue['state'] == 'closed':
edits['state'] = 'open'
elif not actionable and complete and issue['state'] == 'open':
edits['state'] = 'closed'
edits['state_reason'] = 'completed'
return edits
def gh(*args):
return json.loads(subprocess.run(['gh', *args], check=True, capture_output=True, text=True).stdout or 'null')
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--results', type=Path, required=True)
p.add_argument('--coverage', type=Path, required=True)
p.add_argument('--tracked', type=Path, required=True)
p.add_argument('--output', type=Path, required=True)
p.add_argument('--complete', action='store_true')
p.add_argument('--publish', action='store_true')
a = p.parse_args()
complete = a.complete and all(path.is_file() for path in (a.results, a.coverage, a.tracked))
results, coverage, tracked = [json.loads(path.read_text()) if path.is_file() else [] for path in (a.results, a.coverage, a.tracked)]
report, actionable = render(results, coverage, tracked, complete)
a.output.write_text(report + '\n')
if not a.publish:
return
repo = os.environ.get('GITHUB_REPOSITORY')
if repo != 'desirecore/market':
raise ValueError('仅官方仓库可同步 issue / only the official repository may sync issues')
issues = gh('issue', 'list', '--repo', repo, '--label', 'upstream-health', '--state', 'all', '--limit', '100', '--json', 'number,title,body,state')
compatible = [i for i in issues if START in (i.get('body') or '') or i['title'] in (TITLE, 'Upstream health report')]
if len(compatible) > 1 or (issues and not compatible):
raise ValueError('跟踪 issue 不唯一或无法识别,需人工确认 / tracking issue is ambiguous; manual review required')
if compatible:
issue = gh('api', 'repos/' + repo + '/issues/' + str(compatible[0]['number']))
edits = sync_plan(issue, report, actionable, complete)
if edits:
# stdin JSON avoids shell interpolation; one edit, zero comments.
subprocess.run(['gh', 'api', '--method', 'PATCH', 'repos/' + repo + '/issues/' + str(issue['number']), '--input', '-'], input=json.dumps(edits), text=True, check=True, capture_output=True)
elif actionable:
subprocess.run(['gh', 'issue', 'create', '--repo', repo, '--label', 'upstream-health', '--title', TITLE, '--body', managed_body('', report)], check=True, capture_output=True, text=True)
if __name__ == '__main__':
main()
+336
View File
@@ -0,0 +1,336 @@
"""Independent bounded static findings, never upstream execution or admission receipts.
A finding is evidence about exact Git objects, not proof of a completed pipeline.
License-delivery checks intentionally fail closed on unrecognized grants.
"""
from __future__ import annotations
import hashlib
import json
import re
from pathlib import PurePosixPath
STATE = {'blocked': '阻断 / blocked', 'manual_review': '人工待审 / manual review',
'not_checked': '未检查 / not checked', 'info': '说明 / information',
'passed': '静态通过 / static pass'}
ORIGIN = {'pre_existing': '历史遗留 / pre-existing', 'introduced': '本次引入 / introduced',
'changed': '本次变化 / changed', 'unchanged': '未变化 / unchanged',
'unknown': '未确认 / unknown', 'derived': '未签新回执的派生错误 / derived from unsigned target'}
def mit_grant(data):
text = ' '.join(data.decode('utf-8', errors='replace').lower().split())
return all(part in text for part in (
'copyright', 'permission is hereby granted, free of charge',
'to deal in the software without restriction',
'the above copyright notice and this permission notice',
'shall be included in all copies', 'the software is provided "as is"'))
def normalized(data):
return re.sub(rb'\s+', b' ', data).strip()
def inspect_snapshots(repo, entry, metadata, result, special_review=None):
# Lazy import avoids a circular module import; helpers only read bounded blobs.
from audit_skill_update import git, blob, safe_path, GENERATOR, MAX_FILE_BYTES, MAX_FILES
old, new = result['ref'], result['head']
review = special_review or {}
rows = []
def add(path, gate, state, origin, reason, repair, evidence=None):
rows.append(dict(id=entry['id'], path=path or '.', oldRef=old, newRef=new,
gate=gate, state=state, origin=origin, reason=reason,
repair=repair, evidence=evidence or {},
sourceUrl=entry['source']['repoUrl'].removesuffix('.git') + '/compare/' + old + '...' + new))
def files(ref):
found = {}
for record in git(repo, 'ls-tree', '-rz', ref).split(b'\0'):
if record:
meta, path = record.split(b'\t', 1)
mode, kind, oid = meta.decode().split()
found[path.decode()] = (mode, kind, oid)
if len(found) > 20000:
raise ValueError('独立诊断仓库文件数超预算 / diagnostic tree exceeds budget')
return found
trees = {ref: files(ref) for ref in (old, new)}
def read(ref, path):
record = trees[ref].get(path)
if not record or record[0] not in ('100644', '100755') or record[1] != 'blob':
return b''
if int(git(repo, 'cat-file', '-s', record[2])) > MAX_FILE_BYTES:
return b''
return blob(repo, ref, path)
scopes = [safe_path(c['path']) for c in entry.get('children', [])]
if not scopes:
scopes = [safe_path(entry['source'].get('path', ''))]
declared_scopes = set(scopes)
discovered_children = GENERATOR.discover_children(repo, new) if entry.get('children') else []
if discovered_children:
scopes = sorted(set(scopes) | {safe_path(c['path']) for c in discovered_children})
gov = metadata.get('governance', {})
license_info = gov.get('license', {})
evidence_path = safe_path(license_info.get('evidencePath') or gov.get('compliance', {}).get('licenseEvidencePath') or '')
license_value = license_info.get('value')
grants = {ref: read(ref, evidence_path) for ref in (old, new)}
if license_value == 'MIT' and not mit_grant(grants[new]):
add(evidence_path, 'pin-bound-license-exception', 'manual_review',
'pre_existing' if not mit_grant(grants[old]) else 'introduced',
'MIT 声明不是完整版权及许可通知;旧 pin 人工例外不得因字节未变而扩展到新 pin。 / An MIT declaration is not the full notice; an old-pin exception does not authorize a new pin even when bytes match.',
'取得完整主许可通知,或由维护者明确审核并授权精确新 pin;不得由更新器改写 reviewedRef 冒充授权。 / Obtain the complete project notice or explicit human authorization for the exact new pin; never manufacture authorization by rebinding reviewedRef.',
{'declaredLicense': license_value, 'evidencePath': evidence_path,
'oldSha256': hashlib.sha256(grants[old]).hexdigest(), 'newSha256': hashlib.sha256(grants[new]).hexdigest()})
for scope in scopes:
def delivered(ref):
grant = grants[ref]
if not grant:
return False, []
# Only direct scope notice/readme/skill files qualify automatically.
# A third-party vendor LICENSE cannot stand in for the main grant.
candidates = []
for path in trees[ref]:
parent = str(PurePosixPath(path).parent)
parent = '' if parent == '.' else parent
name = PurePosixPath(path).name.upper()
if parent == scope and (name.startswith(('LICENSE', 'COPYING', 'README', 'NOTICE')) or name == 'SKILL.MD'):
candidates.append(path)
if len(candidates) > MAX_FILES:
raise ValueError('许可候选超预算 / notice candidates exceed budget')
exact = [p for p in candidates if normalized(grant) in normalized(read(ref, p))]
return bool(exact) and (license_value != 'MIT' or mit_grant(grant)), exact
old_ok, old_paths = delivered(old)
new_ok, new_paths = delivered(new)
if not new_ok:
add(scope, 'installed-project-notice', 'blocked', 'pre_existing' if not old_ok else 'introduced',
'未证明所选安装目录携带主项目完整通知;仓库根证据或 vendor 许可不等于安装交付。 / Complete project notice delivery is unverified in the selected directory; root evidence or a vendor license is not installed delivery.',
'在不改变资源/选择/交付方式的前提下,由上游在原目录携带通知,或另行批准客户端确定性携带、摘要及锁记录方案并真实安装回读。嵌套或非标准等效通知可人工复核;不要伪造 LICENSE。 / Preserve scope/resources/delivery; upstream may include notices in-place, or separately authorize deterministic client notice staging with digest/lock and installation readback. Nonstandard or nested equivalents need human review; do not invent a LICENSE.',
{'declaredLicense': license_value, 'requiredNoticePath': evidence_path,
'requiredNoticeSha256': hashlib.sha256(grants[new]).hexdigest(),
'requiredNoticeInsideScope': not scope or evidence_path.startswith(scope + '/'),
'oldDeliveredPaths': old_paths, 'newDeliveredPaths': new_paths,
'proof': 'bounded static scan of direct notice/README/SKILL files; not runtime acceptance'})
declared_notice = gov.get('compliance', {}).get('noticePath')
notice_paths = {p for p in trees[new] if '/' not in p and PurePosixPath(p).name.upper().startswith('NOTICE')}
if declared_notice:
notice_paths.add(safe_path(declared_notice))
for notice in sorted(notice_paths):
for scope in scopes:
def notice_delivered(ref):
required = read(ref, notice)
if not required:
return False
for path in trees[ref]:
parent = str(PurePosixPath(path).parent)
parent = '' if parent == '.' else parent
name = PurePosixPath(path).name.upper()
if parent == scope and (name.startswith(('LICENSE','COPYING','NOTICE','README')) or name == 'SKILL.MD'):
if normalized(required) in normalized(read(ref, path)):
return True
return False
if not notice_delivered(new):
add(scope, 'installed-notice-delivery', 'blocked' if notice == declared_notice else 'manual_review',
'pre_existing' if not notice_delivered(old) else 'introduced',
'声明的 NOTICE 或仓库根 NOTICE 未证明随所选目录交付;未声明的根 NOTICE 适用性需保守人工确认。 / A declared or root NOTICE is not proven delivered with the selected directory; applicability of an undeclared root NOTICE requires conservative human review.',
'确认适用范围并保留完整通知;不能以根文件存在替代真实安装副本携带。 / Establish applicability and preserve complete notices; root-file existence is not installed delivery.',
{'requiredNoticePath':notice,'requiredNoticeSha256':hashlib.sha256(read(new,notice)).hexdigest(),
'declaredByCompliance':notice == declared_notice})
# Use the exact parser used by collection discovery, not a hand-written YAML substitute.
def fm_at(ref, path):
try:
raw = read(ref, path)
fm = GENERATOR.parse_frontmatter_text(raw.decode('utf-8')) if raw else None
return fm if isinstance(fm, dict) and fm else None
except (ValueError, RuntimeError, OSError):
return None
markers = {ref: {p for p in trees[ref] if p.endswith('/SKILL.md') or p == 'SKILL.md'} for ref in (old, new)}
if entry.get('children'):
if len(markers[new]) > MAX_FILES:
raise ValueError('SKILL 数量超预算 / SKILL marker budget exceeded')
parsed = {ref: {p for p in markers[ref] if fm_at(ref, p)} for ref in (old, new)}
discovered = {c['path'] for c in discovered_children}
declared = declared_scopes
accepted_members = set(review.get('acceptedCollectionPaths') or []) == discovered
physical_added, physical_removed = sorted(markers[new] - markers[old]), sorted(markers[old] - markers[new])
rediscovered = sorted((parsed[new] - parsed[old]) & markers[old])
add('.', 'collection-inventory', 'info', 'changed' if physical_added or physical_removed or rediscovered else 'unchanged',
f'市场登记 {len(declared)};新 pin 可发现 {len(discovered)};物理 SKILL {len(markers[old])}→{len(markers[new])},新增 {len(physical_added)}、删除 {len(physical_removed)}。同路径恢复解析:{rediscovered}。不把恢复解析称为新增文件;未推断移动。 / Declared {len(declared)}; discoverable {len(discovered)}; physical SKILL files {len(markers[old])}→{len(markers[new])}, added {len(physical_added)}, removed {len(physical_removed)}. Rediscovered at existing paths: {rediscovered}. Rediscovery is not a new physical file; moves are not inferred.',
'核对精确子项及双语派生目录;保留旧失败回执。 / Review exact children and bilingual derived metadata; preserve failed evidence.',
{'physicalAdded': physical_added, 'physicalRemoved': physical_removed, 'rediscovered': rediscovered,
'undeclared': sorted(discovered-declared), 'missing': sorted(declared-discovered)})
for path in sorted(discovered ^ declared):
marker = path + '/SKILL.md'
add(path, 'collection-members', 'info' if accepted_members else 'blocked', 'pre_existing' if marker in markers[old] else 'introduced',
'登记与解析集合不一致;文件原已存在。 / Declared/discovered mismatch; file already existed.' if marker in markers[old] else '登记与解析集合不一致;本次新增物理文件。 / Declared/discovered mismatch; physical file is newly added.',
'逐项审核后同步 children 及两种语言,不把缺项自动准入。 / Review each item and synchronize children and both locales; never auto-admit missing members.')
for path in sorted(markers[new]):
if fm_at(new, path) is None:
add(path, 'frontmatter-parse', 'blocked', 'pre_existing' if fm_at(old, path) is None and path in markers[old] else 'introduced',
'SKILL frontmatter 无法可靠解析。 / SKILL frontmatter cannot be parsed reliably.',
'修正 YAML 后重新发现;这不证明技能是新增加的。 / Fix YAML and rediscover; this does not prove a new skill was added.')
# Descriptions are semantic, not automatic translations. Unchanged historical
# English fallbacks are visible but not newly invented failures.
for scope in scopes:
marker = (scope + '/' if scope else '') + 'SKILL.md'
before, after = fm_at(old, marker), fm_at(new, marker)
if before and after and before.get('description') != after.get('description'):
from audit_skill_update import frontmatter_identity
accepted = review.get('acceptedFrontmatterSha256', {}).get(scope) == frontmatter_identity(after)
has_locale_copy = bool(entry.get('i18n')) or any(c.get('path') == scope and any(v.get('shortDesc') for v in c.get('i18n', {}).values()) for c in entry.get('children', []))
add(marker, 'description-and-locales', 'manual_review' if has_locale_copy or not accepted else 'info', 'changed',
'上游简介变化;旧双语及派生简介不得默认为仍然准确。 / Upstream description changed; old bilingual and derived summaries require review.',
'人工复核中英文及 entry/catalog 镜像;不能自动翻译或仅改 pin。 / Review both locales and entry/catalog mirrors; do not merely bump the pin or invent translations.',
{'oldDescription': before.get('description'), 'newDescription': after.get('description')})
children = {c['id']: c for c in entry.get('children', [])}
for child in metadata.get('spec', {}).get('collection', {}).get('children', []):
item = children.get(child.get('identity', {}).get('id'))
if not item:
continue
for locale, text in item.get('i18n', {}).items():
mirror = child.get('presentation', {}).get('i18n', {}).get(locale, {})
if text.get('shortDesc') is not None and text['shortDesc'] != mirror.get('summary'):
add(item['path'], 'derived-locales', 'blocked', 'pre_existing',
f'{locale} 的 entry 与 catalog 简介不一致。 / {locale} entry/catalog summaries differ.',
'同步实际审核后的派生文案。 / Synchronize reviewed derived copy.')
for item in children.values():
locales = item.get('i18n', {})
zh = locales.get('zh-CN', {}).get('shortDesc')
en = locales.get('en-US', {}).get('shortDesc')
if zh and en and zh == en:
add(item['path'], 'translation-fallback', 'info', 'pre_existing',
'中英简介相同,属于已有英文回退,未声称已翻译。 / Identical summaries are an existing English fallback, not a claimed translation.',
'需要时人工翻译;不要把历史回退误报成本次新增。 / Translate when needed; do not mislabel historical fallback as newly introduced.')
# A plugin's explicit version is authoritative only for that plugin, not for
# every unrelated number or every child skill version.
for path in ('.claude-plugin/plugin.json', '.codex-plugin/plugin.json'):
if path not in trees[new]:
continue
try:
before = json.loads(read(old, path) or b'{}').get('version')
after = json.loads(read(new, path)).get('version')
except (ValueError, AttributeError):
add(path, 'declared-version', 'manual_review', 'unknown', '插件清单无法可靠解析。 / Plugin manifest is not reliably parseable.', '人工核实版本来源。 / Verify the version source manually.')
continue
if not isinstance(after, str) or not re.fullmatch(r'\d+\.\d+\.\d+', after):
continue
# A root plugin version does not define the version of a selected subtree.
root_fm = fm_at(new, 'SKILL.md') or {}
root_metadata = root_fm.get('metadata') if isinstance(root_fm.get('metadata'), dict) else {}
canonical_skill_version = GENERATOR.normalize_version(root_fm.get('version') or root_metadata.get('version'))
if canonical_skill_version != after and not entry.get('children') and not entry['source'].get('path') and entry.get('latestVersion') and entry['latestVersion'] != after:
add(path, 'declared-version', 'manual_review', 'changed' if before != after else 'pre_existing',
f'登记版本 {entry["latestVersion"]} 与插件明确版本 {after} 不一致。 / Registered version {entry["latestVersion"]} differs from explicit plugin version {after}.',
'审核并同步 entry/release,不以任意数字猜版本。 / Review and synchronize entry/release; never infer versions from arbitrary numbers.')
if before and before != after:
for container_name, container in (('entry', entry), ('catalog', metadata)):
def walk(value, keys=()):
if isinstance(value, dict):
for key, child in value.items():
yield from walk(child, (*keys, key))
elif isinstance(value, list):
for index, child in enumerate(value):
yield from walk(child, (*keys, str(index)))
elif isinstance(value, str) and any(k in keys for k in ('description', 'shortDesc', 'summary')):
yield keys, value
for keys, text in walk(container):
if re.search(r'(?<![\d.])v?' + re.escape(str(before)) + r'(?![\d.])', text):
add(container_name + '/' + '/'.join(keys), 'version-copy', 'manual_review', 'changed',
f'文案仍含明确旧插件版本 {before},目标为 {after};语义需人工确认。 / Copy still mentions explicit old plugin version {before}; target is {after}; semantic review is required.',
'核实其确为版本叙述后同步双语;不替换普通数字。 / Update both locales only after confirming this is a version claim; do not replace arbitrary numbers.',
{'versionSource':path,'oldVersion':before,'newVersion':after})
# Complete Git-object manifests, not GitHub's capped comparison file list.
def installed(ref):
return {p: record for p, record in trees[ref].items()
if any(not scope or p == scope or p.startswith(scope + '/') for scope in scopes)}
old_installed, new_installed = installed(old), installed(new)
changed_paths = sorted(p for p in old_installed.keys() | new_installed.keys()
if old_installed.get(p) != new_installed.get(p))
if changed_paths:
sensitive = [p for p in changed_paths if re.search(r'(auth|cookie|permission|credential|secret|env|config|http|network)', PurePosixPath(p).name, re.I)
and (PurePosixPath(p).suffix.lower() in ('.py','.js','.ts','.sh','.json') or PurePosixPath(p).name.startswith('.env'))]
add('.', 'installed-content-delta', 'info', 'changed',
f'直接比较完整 Git 对象:安装范围 {len(changed_paths)} 个路径变化;不是 GitHub 截断的 compare 列表,也不是行为审核通过。 / Complete Git-object comparison: {len(changed_paths)} installed paths changed; not a truncated GitHub compare list or a behavioral approval.',
'按最终 SHA 复审实际指令/代码差异;现有自动合并行为审核门禁保持不变。 / Review actual instructions/code at the final SHA; existing behavioral merge clearance is unchanged.',
{'changedPaths':changed_paths, 'physicalAdded':sorted(new_installed.keys()-old_installed.keys()),
'physicalRemoved':sorted(old_installed.keys()-new_installed.keys()),
'modeChanges':[p for p in changed_paths if p in old_installed and p in new_installed and old_installed[p][0]!=new_installed[p][0]],
'comparisonComplete':True})
if sensitive:
add('.', 'authorization-config-network-review', 'manual_review', 'changed',
'授权/凭据/配置/网络相关命名的实现文件发生变化;依赖哈希或普通元数据校验不能确认行为边界。这是保守人工复核提示,不是已证实漏洞。 / Implementation paths related by name to authorization, credentials, configuration or networking changed. Dependency hashes or metadata checks cannot establish behavioral bounds. This is a conservative review requirement, not a confirmed vulnerability.',
'逐项检查凭据来源/保存、用户同意、网络端点与授权降级;另行记录真实最终 SHA 行为审核,不以依赖专项说明代替。 / Review credential access/storage, user consent, endpoints and authorization fallback; record genuine final-SHA behavioral review, not a dependency-only exception.',
{'changedPaths':sensitive})
# Root tooling is reported separately from installed runtime dependencies.
old_package, new_package = read(old, 'package.json'), read(new, 'package.json')
if old_package != new_package and new_package:
try:
a, b = json.loads(old_package or b'{}'), json.loads(new_package)
for category in ('dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'):
if a.get(category, {}) != b.get(category, {}):
add('package.json#' + category, 'dependency-context', 'info', 'changed',
f'根清单 {category} 变化;不据此推断所选技能的运行时需求。 / Root manifest {category} changed; this alone does not establish installed-skill runtime requirements.',
'依赖门禁仍按精确对象审核;区分开发工具和实际运行依赖。 / Retain exact-object dependency review; distinguish development tools from runtime requirements.',
{'old': a.get(category, {}), 'new': b.get(category, {}), 'rootInsideSelectedScope': '' in scopes})
except (ValueError, AttributeError):
pass # The core dependency parser blocks malformed manifests.
deduplicated = {}
for row in rows:
key = (row['id'], row['path'], row['gate'], row['state'], row['reason'])
if key not in deduplicated:
deduplicated[key] = row
elif row.get('evidence') != deduplicated[key].get('evidence'):
deduplicated[key].setdefault('additionalEvidence', []).append(row['evidence'])
return list(deduplicated.values())
def candidate_consistency(entry, metadata, result, view):
"""Read-only candidate metadata checks, never permission to issue a receipt."""
rows = []
target = result['head']
candidate = view.get('entry', {})
sidecar = view.get('metadata', {})
receipt = view.get('audit') or {}
source = candidate.get('source', {})
def add(path, gate, state, reason, evidence):
rows.append(dict(id=entry['id'], path=path, oldRef=result['ref'], newRef=target,
gate=gate, state=state, origin='derived' if gate in ('candidate-reviewed-ref','candidate-receipt-ref','candidate-receipt-scope') else 'unknown', basis='existing-pr-candidate@'+view['head'],
reason=reason, evidence=evidence,
repair='先解决主通知交付/真实审核阻碍,再重跑生成真实目标回执;不能只改 reviewedRef 或复制 source/scope 字段凑通过。 / Resolve primary notice-delivery and actual review blockers, then generate a genuine target receipt; never merely rebind reviewedRef or copy source/scope fields.'))
valid = (candidate.get('id') == entry['id'] and source.get('kind') == 'git'
and source.get('repoUrl') == entry['source']['repoUrl'] and source.get('ref') == target)
if not valid:
add('entry.json', 'candidate-source', 'blocked',
'当前 PR 来源与可信 main 的待审来源不一致,不能用本次对象证明它。 / Candidate source differs from the trusted-main audit target; these objects cannot prove that candidate.', {'candidateSource':source})
return rows, False
reviewed = sidecar.get('governance', {}).get('compliance', {}).get('reviewedRef')
if reviewed != target:
add('catalog-metadata.v1.json#governance.compliance.reviewedRef', 'candidate-reviewed-ref', 'blocked',
'目标已提升但人工/机器 reviewedRef 仍不对应目标;这是未签新回执的派生一致性错误。 / The target advanced but reviewedRef does not bind it; this is a derived consistency error while the target remains unsigned.',
{'reviewedRef':reviewed,'requiredRef':target})
receipt_source = receipt.get('source', {})
if receipt_source.get('ref') != target:
add('upstream-audit.v1.json#source.ref', 'candidate-receipt-ref', 'blocked',
'保留的旧回执 source 不对应新目标,不能称为新 pin 审核通过。 / The retained old receipt source does not bind the new target; it is not a passing new-pin receipt.',
{'receiptRef':receipt_source.get('ref'),'requiredRef':target})
required_scope = sorted(c['path'] for c in candidate.get('children', [])) or [source.get('path', '')]
actual_scope = sorted(receipt_source.get('paths') or [])
if actual_scope != required_scope:
add('upstream-audit.v1.json#source.paths', 'candidate-receipt-scope', 'blocked',
f'旧回执范围 {len(actual_scope)} 不覆盖当前登记 {len(required_scope)};不能靠扩写 scope 假造复审。 / Receipt scope {len(actual_scope)} does not cover current declared scope {len(required_scope)}; editing scope is not a genuine re-audit.',
{'receiptPaths':actual_scope,'requiredPaths':required_scope})
for check in view.get('checks', []):
if check.get('conclusion') not in ('success', 'skipped', 'neutral') or check.get('status') != 'completed':
add('PR#'+str(view.get('number'))+'/'+check.get('name','?'), 'candidate-live-check',
'blocked' if check.get('status') == 'completed' else 'not_checked',
'当前 PR 精确 head 的实时检查结果;不是 main 重放结果,也不由本报告认定其余检查通过。 / Live check result for the exact candidate head, not a trusted-main replay or proof that other checks passed.', check)
return rows, True
def render_findings(rows):
def cell(value):
return str(value).replace('|', '\\|').replace('\n', '<br>')
out = ['| 技能/路径 / Skill/path | 精确旧→新 pin / Exact pins | 门槛 / Gate | 状态/来源 / State/origin | 原因及证据 / Reason/evidence | 修法 / Repair |', '|---|---|---|---|---|---|']
for row in rows:
evidence = json.dumps(row.get('evidence', {}), ensure_ascii=False, sort_keys=True)
out.append('| ' + ' | '.join(cell(v) for v in (
('[' + row['id'] + '/' + row['path'] + '](' + row['sourceUrl'] + ')') if row.get('sourceUrl') else row['id'] + '/' + row['path'], row['oldRef'] + ' → ' + row['newRef'], row['gate'],
STATE.get(row['state'], row['state']) + '; ' + ORIGIN.get(row['origin'], row['origin']) + '; ' + row.get('basis','trusted-main-replay / 对可信main重放'),
row['reason'] + (' ' + evidence if evidence != '{}' else ''), row['repair'])) + ' |')
return '\n'.join(out)