From 58e25e1f977989ba07e03308c8cb779e6dbe4302 Mon Sep 17 00:00:00 2001 From: mashagua <993498039@qq.com> Date: Fri, 27 Nov 2026 10:06:36 +0800 Subject: [PATCH] =?UTF-8?q?feat(market):=20=E4=B8=93=E9=A1=B9=E5=A4=8D?= =?UTF-8?q?=E6=A0=B8=E6=94=AF=E6=8C=81=E5=AE=A2=E6=88=B7=E7=AB=AF=E9=99=84?= =?UTF-8?q?=E5=8A=A0=E6=A0=B9=E9=80=9A=E7=9F=A5=E4=B8=8E=E7=AE=80=E4=BB=8B?= =?UTF-8?q?=E5=8F=8C=E8=AF=AD=E5=A4=8D=E6=A0=B8=20(#374)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## 变更 / Changes 为 Class C 专项复核增加两个字段,以便在**不把根 LICENSE 存在视为安装交付、不发明许可例外、也不把旧简介或未更新的 shortDesc 延伸到新 pin**的前提下,记录: 1. `acceptedClientAttachedNotices`:接受已核验 DesireCore 客户端在安装合集子项时把根 `LICENSE` / `NOTICE` / `COPYING` 附进副本的真实安装回读。 2. `acceptedDescriptionAndLocales`:记录上游 `SKILL.md` 简介已变、市场条目中英 `shortDesc` 与 catalog 镜像已按新简介人工复核的证据。该字段只覆盖本身已有 shortDesc 的安装范围;合集根目录的市场简介不视为每个子项的派生文案。 这是完成 [desirecore/market#361](https://github.com/desirecore/market/pull/361) 所必需的审核能力,本身不改任何技能 pin。 对应客户端实现为 [desirecore/desirecore#6426](https://github.com/desirecore/desirecore/pull/6426) squash 合入 `dev` 的 `28128a15b3abd76e1529b983ca8a921bdfe9ff30`(tree `e8c1321e6a098eb905f4646b2027bc7b2259ca6b`)。当前 `dev` 已前移,但该修复仍在历史中且附加代码未被改动。后续 tip 不能自动视为同一实现。 ## 安全边界 / Security boundaries 默认拒绝仍然成立。只有同时满足以下条件才会被接受: - 记录必须包含真实的 `reviewedBy`、`reviewedAt` 和非空 `notes`。 - `acceptedClientAttachedNotices.sourceRef` 必须等于本次审核的新 pin 完整 40 位 SHA;`clientCommit` 必须是已核验的附加实现提交(当前仅 `28128a15…`);`noticeSha256` 必须与当前快照根通知字节一致;`scopes` 必须恰好等于全部安装范围并附子项安装回读。错 pin、错客户端 SHA / tree、错根通知哈希、缺子项回读、不完整 MIT,以及仅有「将会附加」说明一律拒绝。 - `acceptedDescriptionAndLocales.fromRef` / `toRef` 必须等于本次审核的旧 / 新 pin;`files` 必须恰好覆盖上游简介已变且该范围本身已有双语副本的路径;每语种必须绑定已更新的 `shortDesc` 及其 SHA-256,英文简介必须覆盖新简介的特有词项,中文简介必须是与英文、旧简介不同的中文文案,catalog `summary` 必须与 entry 一致。错 pin、错路径、未更新或未匹配新简介的 shortDesc 一律不能通过,也不得自动延伸到新 pin。 本变更不执行上游代码,不代表安全认证或运行验收。#361 的正式快照 PR 会用正常 merge 把本分支合进对应快照分支,以便 required checks 能跑到新挂钩。本 PR 本身不含 #361 快照,也不自行合并。 ## 验证 / Verification - `PYTHONPATH=scripts/catalog uv run --with pytest --with jsonschema --with pyyaml python -m pytest scripts/catalog/test_audit_skill_update.py scripts/catalog/test_update_diagnostics.py scripts/catalog/test_validate_catalog_metadata.py`:**150 passed**(含 190 subtests)。正例为绑定当前 pin 与完整证据的接受;反例覆盖错 pin、错客户端 SHA / tree、错根通知哈希、缺子项回读、错路径、未更新或未匹配新简介的 shortDesc、缺理由、不完整 MIT,以及仅有「将会附加」或「已复核」说明的情况。另有回归:合集根 i18n 不会单独要求没有 shortDesc 的子项通过简介字段。既有「根 LICENSE 不等于安装交付」用例保持失败。 Automated source/license/metadata verification tooling only. No auto-merge of skill snapshot PRs in this change. --- schemas/special-review.v1.schema.json | 88 ++++++ scripts/catalog/audit_skill_update.py | 323 +++++++++++++++++++++ scripts/catalog/test_audit_skill_update.py | 308 +++++++++++++++++++- scripts/catalog/test_update_diagnostics.py | 164 +++++++++++ scripts/catalog/update_diagnostics.py | 44 ++- 5 files changed, 922 insertions(+), 5 deletions(-) diff --git a/schemas/special-review.v1.schema.json b/schemas/special-review.v1.schema.json index 603ad26..15b7761 100644 --- a/schemas/special-review.v1.schema.json +++ b/schemas/special-review.v1.schema.json @@ -71,6 +71,86 @@ "type": "object", "description": "Map of a repo-root LICENSE*/NOTICE*/COPYING* directory name (for example licenses) to the SHA-256 of the canonical JSON manifest of regular files under that directory at the *new* snapshot (sorted path to file SHA-256). Required when those directory file sets change, including renames. This does not accept changes to, replacements of, or deletions of root LICENSE/NOTICE/COPYING files (deletions remain forbidden; file changes still use acceptedRootEvidenceSha256). Symlinks, submodules, and other non-regular files at those root names or inside the directory remain blocked.", "additionalProperties": { "type": "string", "pattern": "^[a-f0-9]{64}$" } + }, + "acceptedClientAttachedNotices": { + "type": "object", + "description": "Bound install-readback evidence that a verified DesireCore client commit attached collection/repo-root LICENSE/NOTICE/COPYING files into each selected install copy. This is not a license exception and does not treat a root file seen at audit time, or a future client change, as delivery. sourceRef must equal the audit's new pin; clientCommit must be an already-verified attach implementation (not a descendant tip by default); noticeSha256 must equal the regular root notice file at that pin; scopes must be exactly the install paths with per-copy attached name/sourceName/sha256 matching that root notice. The acceptance does not automatically extend to a later pin.", + "additionalProperties": false, + "required": ["sourceRef", "clientCommit", "noticeRootPath", "noticeSha256", "scopes"], + "properties": { + "sourceRef": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "clientCommit": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "clientTree": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "observedAt": { "type": "string", "pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$" }, + "noticeRootPath": { "type": "string", "minLength": 1 }, + "noticeSha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "scopes": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["path", "attached"], + "properties": { + "path": { "type": "string", "minLength": 1 }, + "contentDigest": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "attached": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["name", "sourceName", "sha256"], + "properties": { + "name": { "type": "string", "minLength": 1 }, + "sourceName": { "type": "string", "minLength": 1 }, + "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" } + } + } + } + } + } + } + } + }, + "acceptedDescriptionAndLocales": { + "type": "object", + "description": "Human review that market listing shortDesc/summary copy was updated to match a changed upstream SKILL.md description. Bound to the exact old and new pins and to each affected install path. Files must be exactly the description-changed scopes that already have locale copy. Each locale binds the reviewed shortDesc and its SHA-256, plus the previous listing text; the English/latin shortDesc must cover distinctive new-description terms, and zh-CN must be distinct CJK rather than a leftover English or old listing string. Catalog summary mirrors must match. This is not a generic exemption and does not automatically extend to a later pin.", + "additionalProperties": false, + "required": ["fromRef", "toRef", "files"], + "properties": { + "fromRef": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "toRef": { "type": "string", "pattern": "^[0-9a-f]{40}$" }, + "files": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["path", "oldDescription", "newDescription", "newFrontmatterSha256", "locales"], + "properties": { + "path": { "type": "string" }, + "oldDescription": { "type": "string", "minLength": 1 }, + "newDescription": { "type": "string", "minLength": 1 }, + "newFrontmatterSha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "locales": { + "type": "object", + "minProperties": 1, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": ["shortDesc", "sha256", "previousShortDesc"], + "properties": { + "shortDesc": { "type": "string", "minLength": 1 }, + "sha256": { "type": "string", "pattern": "^[a-f0-9]{64}$" }, + "previousShortDesc": { "type": "string" } + } + } + } + } + } + } + } } }, "allOf": [ @@ -81,6 +161,14 @@ { "if": { "required": ["acceptedRootLicenseDirectoryManifestSha256"] }, "then": { "required": ["reviewedBy", "reviewedAt", "notes"] } + }, + { + "if": { "required": ["acceptedClientAttachedNotices"] }, + "then": { "required": ["reviewedBy", "reviewedAt", "notes"] } + }, + { + "if": { "required": ["acceptedDescriptionAndLocales"] }, + "then": { "required": ["reviewedBy", "reviewedAt", "notes"] } } ] } diff --git a/scripts/catalog/audit_skill_update.py b/scripts/catalog/audit_skill_update.py index 5ef331c..78018cc 100644 --- a/scripts/catalog/audit_skill_update.py +++ b/scripts/catalog/audit_skill_update.py @@ -187,6 +187,315 @@ def _sha256_hex(value: object) -> bool: return isinstance(value, str) and bool(re.fullmatch(r'[a-f0-9]{64}', value)) +# Verified DesireCore client commits whose collection-child installer attaches +# root LICENSE/NOTICE/COPYING files after verifying the selected child tree. +# This is not a license exception. A later descendant tip is not accepted +# automatically; add a newly verified implementation commit explicitly. +CLIENT_ATTACHED_NOTICE_IMPLEMENTATIONS = { + '28128a15b3abd76e1529b983ca8a921bdfe9ff30': 'e8c1321e6a098eb905f4646b2027bc7b2259ca6b', +} + +ROOT_NOTICE_NAME_PREFIXES = ('LICENSE', 'LICENCE', 'NOTICE', 'COPYING') + + +def is_root_notice_filename(name: str) -> bool: + if not isinstance(name, str) or not name or name in ('.', '..'): + return False + if name != PurePosixPath(name).name or any(symbol in name for symbol in ('/', '\\', '\0')): + return False + upper = name.upper() + return any(upper == prefix or upper.startswith(prefix + '.') or upper.startswith(prefix + '-') + for prefix in ROOT_NOTICE_NAME_PREFIXES) + + +def root_regular_file_sha256(repo: Path, ref: str, path: str) -> str: + path = safe_path(path) + if path != PurePosixPath(path).name: + raise AuditBlocked('客户端附加通知专项复核的根通知路径无效') + for record in git(repo, 'ls-tree', '-z', ref, '--', path).split(b'\0'): + if not record: + continue + meta, name = record.split(b'\t', 1) + if name.decode() != path: + continue + mode, kind, _ = meta.decode().split()[:3] + if kind != 'blob' or mode not in ('100644', '100755'): + raise AuditBlocked('根许可或 Notice 不是普通文件') + return hashlib.sha256(blob(repo, ref, path)).hexdigest() + raise AuditBlocked('客户端附加通知专项复核的根通知在当前快照中不存在') + + +def accept_client_attached_notices(review: dict, repo: Path, new: str, install_scopes: list[str], + grant: bytes, license_value: str | None) -> set[str]: + """Return install scopes proven by bound client attach + install readback. + + Absent field: empty set. Present but invalid: AuditBlocked. The acceptance is + bound to the exact new pin and a verified client commit; it does not extend + to a later pin and does not treat a future client change as delivery. + """ + accepted = review.get('acceptedClientAttachedNotices') + if not accepted: + return set() + if not isinstance(accepted, dict): + raise AuditBlocked('客户端附加通知专项复核记录无效') + if not all(isinstance(review.get(key), str) and review[key].strip() + for key in ('reviewedBy', 'reviewedAt', 'notes')): + raise AuditBlocked('客户端附加通知专项复核必须包含审核人、日期和理由') + source_ref = accepted.get('sourceRef') + client_commit = accepted.get('clientCommit') + client_tree = accepted.get('clientTree') + observed_at = accepted.get('observedAt') + notice_path = accepted.get('noticeRootPath') + notice_sha = accepted.get('noticeSha256') + if not isinstance(source_ref, str) or not re.fullmatch(r'[0-9a-f]{40}', source_ref): + raise AuditBlocked('客户端附加通知专项复核未绑定完整上游 pin') + if source_ref != new: + raise AuditBlocked('客户端附加通知专项复核未绑定当前固定快照') + if not isinstance(client_commit, str) or not re.fullmatch(r'[0-9a-f]{40}', client_commit): + raise AuditBlocked('客户端附加通知专项复核的客户端提交无效') + if client_commit not in CLIENT_ATTACHED_NOTICE_IMPLEMENTATIONS: + raise AuditBlocked('客户端附加通知专项复核的客户端提交不在已核验实现清单中') + expected_tree = CLIENT_ATTACHED_NOTICE_IMPLEMENTATIONS[client_commit] + if client_tree is not None and (not isinstance(client_tree, str) + or not re.fullmatch(r'[0-9a-f]{40}', client_tree) + or client_tree != expected_tree): + raise AuditBlocked('客户端附加通知专项复核的客户端 tree 与已核验实现不一致') + if observed_at is not None and not (isinstance(observed_at, str) + and re.fullmatch(r'\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z', observed_at)): + raise AuditBlocked('客户端附加通知专项复核的回读时间格式不正确') + if not isinstance(notice_path, str) or not is_root_notice_filename(notice_path): + raise AuditBlocked('客户端附加通知专项复核的根通知路径无效') + if not _sha256_hex(notice_sha): + raise AuditBlocked('客户端附加通知专项复核的根通知哈希无效') + actual = root_regular_file_sha256(repo, new, notice_path) + if actual != notice_sha: + raise AuditBlocked('客户端附加通知专项复核的根通知哈希与当前快照不一致') + if not grant or hashlib.sha256(grant).hexdigest() != notice_sha: + raise AuditBlocked('客户端附加通知专项复核的根通知哈希与当前快照不一致') + from update_diagnostics import mit_grant + if license_value == 'MIT' and not mit_grant(grant): + raise AuditBlocked('客户端附加通知专项复核不能用于不完整的 MIT 声明') + + scopes = accepted.get('scopes') + if not isinstance(scopes, list) or not scopes: + raise AuditBlocked('客户端附加通知专项复核缺少子项安装回读') + required = {safe_path(scope) for scope in install_scopes} + seen: set[str] = set() + for item in scopes: + if not isinstance(item, dict): + raise AuditBlocked('客户端附加通知专项复核子项回读无效') + raw_path = item.get('path') + if not isinstance(raw_path, str) or any(symbol in raw_path for symbol in '*?[]'): + raise AuditBlocked('客户端附加通知专项复核路径不安全') + path = safe_path(raw_path) + if path != raw_path: + raise AuditBlocked('客户端附加通知专项复核路径不安全') + if path in seen: + raise AuditBlocked('客户端附加通知专项复核路径重复') + seen.add(path) + attached = item.get('attached') + if not isinstance(attached, list) or not attached: + raise AuditBlocked('客户端附加通知专项复核缺少子项安装回读') + delivered = False + names: set[str] = set() + for record in attached: + if not isinstance(record, dict): + raise AuditBlocked('客户端附加通知专项复核子项回读无效') + name, source_name, digest = record.get('name'), record.get('sourceName'), record.get('sha256') + if not is_root_notice_filename(name) or not is_root_notice_filename(source_name): + raise AuditBlocked('客户端附加通知专项复核的附带文件名无效') + if not _sha256_hex(digest): + raise AuditBlocked('客户端附加通知专项复核子项哈希无效') + if name in names: + raise AuditBlocked('客户端附加通知专项复核附带文件名重复') + names.add(name) + if source_name == notice_path and digest == notice_sha: + delivered = True + if not delivered: + raise AuditBlocked('客户端附加通知专项复核未证明该子项安装副本携带完整根通知') + if seen != required: + raise AuditBlocked('客户端附加通知专项复核与安装范围不一致或缺少子项安装回读') + return seen + + + + +LATIN_TOKEN = re.compile(r"[A-Za-z][A-Za-z0-9'-]{4,}") +CJK_RE = re.compile(r"[\u3400-\u9fff\uf900-\ufaff]") + + +def _text_sha256(value: str) -> str: + return hashlib.sha256(value.encode('utf-8')).hexdigest() + + +def _latin_stems(text: str) -> set[str]: + tokens: set[str] = set() + for match in LATIN_TOKEN.finditer(text or ''): + for part in re.split(r"[-']", match.group(0).casefold()): + if len(part) >= 5: + tokens.add(part) + stems = set(tokens) + for token in tokens: + for suffix in ('ing', 'ed', 'es', 's'): + if len(token) > len(suffix) + 3 and token.endswith(suffix): + stems.add(token[:-len(suffix)]) + if suffix == 'ing': + stems.add(token[:-3] + 'e') + return stems + + +def short_desc_covers_new_description(short_desc: str, old_description: str, new_description: str, + previous_short_desc: str = '') -> bool: + """English/latin shortDesc must pick up distinctive new-description terms not already in the old listing.""" + new_only = _latin_stems(new_description) - _latin_stems(old_description) + incremental = new_only - _latin_stems(previous_short_desc or '') + target = incremental or new_only + if not target: + return True + return bool(_latin_stems(short_desc) & target) + + +def _scope_locale_sources(entry: dict, sidecar: dict, scope: str) -> tuple[dict, dict | None]: + for child in entry.get('children') or []: + if safe_path(child.get('path') or '') == scope: + catalog = None + for item in sidecar.get('spec', {}).get('collection', {}).get('children', []): + item_path = item.get('path') + same_path = isinstance(item_path, str) and safe_path(item_path) == scope + same_id = item.get('identity', {}).get('id') == child.get('id') + if same_path or same_id: + catalog = item + break + return child, catalog + return {'id': entry.get('id'), 'path': scope, 'i18n': entry.get('i18n') or {}}, sidecar + + +def _has_locale_copy(entry: dict, scope: str) -> bool: + """True only when this install scope already has listing shortDesc to review. + + Collection-root i18n is not a derived summary of every child; a new member + without its own shortDesc is not treated as already having locale copy. + """ + for child in entry.get('children') or []: + if child.get('path') == scope: + return any(isinstance(value, dict) and value.get('shortDesc') + for value in (child.get('i18n') or {}).values()) + if entry.get('children'): + return False + return any(isinstance(value, dict) and value.get('shortDesc') + for value in (entry.get('i18n') or {}).values()) + + +def description_changed_locale_scopes(repo: Path, entry: dict, old: str, new: str, install_scopes: list[str]) -> dict[str, tuple[dict, dict]]: + changed: dict[str, tuple[dict, dict]] = {} + for scope in install_scopes: + marker = f'{scope}/SKILL.md' if scope else 'SKILL.md' + before = GENERATOR.skill_frontmatter(repo, marker, old) + after = GENERATOR.skill_frontmatter(repo, marker, new) + if not isinstance(before, dict) or not isinstance(after, dict): + continue + if before.get('description') != after.get('description') and _has_locale_copy(entry, scope): + changed[scope] = (before, after) + return changed + + +def accept_description_and_locales(review: dict, entry: dict, sidecar: dict, repo: Path, + old: str, new: str, install_scopes: list[str]) -> set[str]: + """Return scopes whose listing shortDesc was reviewed against the new upstream description. + + Absent field: empty set. Present but invalid: AuditBlocked. The acceptance is + bound to the exact old/new pins and reviewed listing text; it does not extend + to a later pin and does not accept stale or unmatched shortDesc. + """ + accepted = review.get('acceptedDescriptionAndLocales') + if not accepted: + return set() + if not isinstance(accepted, dict): + raise AuditBlocked('简介与双语专项复核记录无效') + if not all(isinstance(review.get(key), str) and review[key].strip() + for key in ('reviewedBy', 'reviewedAt', 'notes')): + raise AuditBlocked('简介与双语专项复核必须包含审核人、日期和理由') + from_ref, to_ref = accepted.get('fromRef'), accepted.get('toRef') + if not isinstance(from_ref, str) or not re.fullmatch(r'[0-9a-f]{40}', from_ref): + raise AuditBlocked('简介与双语专项复核未绑定完整旧 pin') + if not isinstance(to_ref, str) or not re.fullmatch(r'[0-9a-f]{40}', to_ref): + raise AuditBlocked('简介与双语专项复核未绑定完整新 pin') + if from_ref != old or to_ref != new: + raise AuditBlocked('简介与双语专项复核未绑定当前固定快照') + required = description_changed_locale_scopes(repo, entry, old, new, install_scopes) + files = accepted.get('files') + if not isinstance(files, list) or not files: + raise AuditBlocked('简介与双语专项复核缺少受影响路径') + seen: set[str] = set() + for item in files: + if not isinstance(item, dict): + raise AuditBlocked('简介与双语专项复核路径记录无效') + raw_path = item.get('path') + if not isinstance(raw_path, str) or any(symbol in raw_path for symbol in '*?[]'): + raise AuditBlocked('简介与双语专项复核路径不安全') + path = safe_path(raw_path) + if path != raw_path: + raise AuditBlocked('简介与双语专项复核路径不安全') + if path in seen: + raise AuditBlocked('简介与双语专项复核路径重复') + seen.add(path) + if path not in required: + raise AuditBlocked('简介与双语专项复核路径与上游简介变化范围不一致') + before, after = required[path] + if item.get('oldDescription') != before.get('description'): + raise AuditBlocked('简介与双语专项复核的旧简介与当前快照不一致') + if item.get('newDescription') != after.get('description'): + raise AuditBlocked('简介与双语专项复核的新简介与当前快照不一致') + if item.get('newFrontmatterSha256') != frontmatter_identity(after): + raise AuditBlocked('简介与双语专项复核的 frontmatter 哈希与当前快照不一致') + locales = item.get('locales') + if not isinstance(locales, dict) or not locales: + raise AuditBlocked('简介与双语专项复核缺少语种文案') + source, catalog = _scope_locale_sources(entry, sidecar, path) + existing = { + locale: (copy.get('shortDesc') if isinstance(copy, dict) else None) + for locale, copy in (source.get('i18n') or {}).items() + } + existing = {locale: text for locale, text in existing.items() if isinstance(text, str) and text} + if set(locales) != set(existing): + raise AuditBlocked('简介与双语专项复核语种与条目现有简介不一致') + english_text = None + if isinstance(locales.get('en-US'), dict): + english_text = locales['en-US'].get('shortDesc') + for locale, record in locales.items(): + if not isinstance(locale, str) or not locale.strip() or not isinstance(record, dict): + raise AuditBlocked('简介与双语专项复核语种记录无效') + short_desc = record.get('shortDesc') + previous = record.get('previousShortDesc') + digest = record.get('sha256') + if not isinstance(short_desc, str) or not short_desc.strip(): + raise AuditBlocked('简介与双语专项复核的简介文案为空') + if not isinstance(previous, str): + raise AuditBlocked('简介与双语专项复核缺少原先简介') + if not _sha256_hex(digest) or digest != _text_sha256(short_desc): + raise AuditBlocked('简介与双语专项复核的简介哈希与文案不一致') + if existing.get(locale) != short_desc: + raise AuditBlocked('简介与双语专项复核的简介与条目现有文案不一致') + if catalog is not None: + summary = ((catalog.get('presentation') or {}).get('i18n') or {}).get(locale, {}) + if not isinstance(summary, dict) or summary.get('summary') != short_desc: + raise AuditBlocked('简介与双语专项复核的 catalog 镜像与条目简介不一致') + if previous.strip() and short_desc == previous: + raise AuditBlocked('简介与双语专项复核的简介未相对原先文案更新') + if short_desc == before.get('description'): + raise AuditBlocked('简介与双语专项复核的简介仍是旧的上游简介') + if CJK_RE.search(short_desc) or locale.lower().startswith('zh'): + if not CJK_RE.search(short_desc): + raise AuditBlocked('简介与双语专项复核的中文简介不是中文') + if short_desc in {before.get('description'), after.get('description'), english_text}: + raise AuditBlocked('简介与双语专项复核的中文简介未实际更新以匹配上游简介') + elif not short_desc_covers_new_description(short_desc, before.get('description') or '', after.get('description') or '', previous): + raise AuditBlocked('简介与双语专项复核的简介未实际更新以匹配上游简介') + if seen != set(required): + raise AuditBlocked('简介与双语专项复核与上游简介变化范围不一致或缺少路径') + return seen + + def accept_scoped_notice_changes(review: dict, repo: Path, old: str, new: str, old_map: dict[str, str], new_map: dict[str, str]) -> None: """Accept only exact, additive, in-place NOTICE edits bound to this snapshot pair. @@ -328,6 +637,16 @@ def _audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict, raise AuditBlocked('新快照为空或超过总预算') old_root = root_evidence(repo, old) new_root = root_evidence(repo, new) + if review.get('acceptedClientAttachedNotices'): + evidence_path = safe_path((sidecar.get('governance', {}).get('license') or {}).get('evidencePath') + or sidecar.get('governance', {}).get('compliance', {}).get('licenseEvidencePath') + or '') + grant = blob(repo, new, evidence_path) if evidence_path else b'' + accept_client_attached_notices( + review, repo, new, paths, grant, + (sidecar.get('governance', {}).get('license') or {}).get('value')) + if review.get('acceptedDescriptionAndLocales'): + accept_description_and_locales(review, entry, sidecar, repo, old, new, paths) if old_root != new_root: accepted_root = review.get('acceptedRootEvidenceSha256') or {} if set(old_root) - set(new_root): @@ -521,6 +840,10 @@ def _audit_snapshots(repo: Path, entry: dict, sidecar: dict, result: dict, report['limitations'].append('安装范围内的 Notice 如有变化,已按专项复核记录中绑定的快照、路径和哈希核对,且新文件必须完整保留旧 Notice 字节;不代表与旧快照逐字节相同,也不接受嵌套许可证变更。') if review.get('acceptedRootLicenseDirectoryManifestSha256'): report['limitations'].append('根 licenses/ 等许可目录内的第三方许可文本如有变化,已按专项复核记录中的目录清单哈希核对,不代表与旧快照逐文件相同;不接受根 LICENSE/NOTICE/COPYING 文件被删除或改成非普通文件。') + if review.get('acceptedClientAttachedNotices'): + report['limitations'].append('所选安装目录在源树中仍可能没有完整通知;已按专项复核中绑定的上游 pin、已核验客户端提交和逐项安装回读哈希证明安装副本携带了完整根通知。该接受不是许可例外,不得自动延伸到新 pin,也不能把尚未回读的客户端附加写成已交付。') + if review.get('acceptedDescriptionAndLocales'): + report['limitations'].append('上游简介如有变化,已按专项复核中绑定的旧/新 pin、路径、frontmatter 哈希和已更新的双语简介核对;不代表自动翻译,也不得把旧简介或未匹配新简介的文案延伸到新 pin。') if exclude_paths: report['limitations'].append('excludePaths 只从本仓库的自动审核树遍历中省略路径;DesireCore 安装器在支持该字段前仍会从上游 pin 安装这些文件。') errors = validate_record(metadata, report) diff --git a/scripts/catalog/test_audit_skill_update.py b/scripts/catalog/test_audit_skill_update.py index d1fffd0..e1ab739 100644 --- a/scripts/catalog/test_audit_skill_update.py +++ b/scripts/catalog/test_audit_skill_update.py @@ -5,12 +5,14 @@ # /// """真实本地 Git 快照的自动核验;不联网、不运行上游代码。""" import copy +import hashlib import json import subprocess import tempfile import unittest from pathlib import Path -from audit_skill_update import audit_snapshots, audit_update, AuditBlocked, REVIEWER +from audit_skill_update import (audit_snapshots, audit_update, AuditBlocked, REVIEWER, + GENERATOR, frontmatter_identity, _text_sha256) class AuditTests(unittest.TestCase): @@ -563,6 +565,36 @@ class AuditTests(unittest.TestCase): self.metadata['provenance']['content']['ref'] = sha self.metadata['governance']['compliance']['reviewedRef'] = sha + def _client_attach_review(self, new, scopes, notice_sha, **overrides): + review = { + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'Install-copy readback of verified client root-notice attach for this pin.', + 'acceptedClientAttachedNotices': { + 'sourceRef': new, + 'clientCommit': '28128a15b3abd76e1529b983ca8a921bdfe9ff30', + 'clientTree': 'e8c1321e6a098eb905f4646b2027bc7b2259ca6b', + 'observedAt': '2026-11-26T16:04:23Z', + 'noticeRootPath': 'LICENSE', + 'noticeSha256': notice_sha, + 'scopes': [ + {'path': path, 'attached': [ + {'name': 'LICENSE', 'sourceName': 'LICENSE', 'sha256': notice_sha}, + ]} + for path in scopes + ], + }, + } + accepted = overrides.pop('acceptedClientAttachedNotices', None) + review.update(overrides) + if accepted is not None: + merged = dict(review['acceptedClientAttachedNotices']) + merged.update(accepted) + review['acceptedClientAttachedNotices'] = merged + return review + + def test_root_licenses_directory_is_not_a_broken_license_file(self): """A normal licenses/ directory plus an unchanged MIT LICENSE must pass (old and new pins).""" self.write('licenses/thirdparty-MIT.txt', 'Permission is hereby granted, MIT third-party text.\n') @@ -667,9 +699,283 @@ class AuditTests(unittest.TestCase): self.assertIn('licenses/thirdparty-MIT.txt', report['licenseEvidenceSha256']) self.assertTrue(any('安装范围内的 Notice' in item for item in report['limitations'])) + + def test_client_attached_notices_accepts_bound_install_readback(self): + from jsonschema import Draft7Validator + schema = json.loads((Path(__file__).resolve().parents[2] / 'schemas' / 'special-review.v1.schema.json').read_text()) + (self.repo / 'skills/sample/LICENSE').unlink() + self._rebind_old(self.commit()) + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + notice_sha = hashlib.sha256((self.repo / 'LICENSE').read_bytes()).hexdigest() + new = self.commit() + review = self._client_attach_review(new, ['skills/sample'], notice_sha) + Draft7Validator(schema).validate(review) + entry, metadata, report = audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z', + special_review=review) + self.assertEqual(metadata['governance']['compliance']['reviewedRef'], new) + self.assertEqual(report['source']['ref'], new) + self.assertEqual(report['source']['previousRef'], self.old) + self.assertTrue(any('安装副本携带了完整根通知' in item for item in report['limitations'])) + + def test_client_attached_notices_rejects_mismatched_bindings(self): + (self.repo / 'skills/sample/LICENSE').unlink() + self._rebind_old(self.commit()) + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + notice_sha = hashlib.sha256((self.repo / 'LICENSE').read_bytes()).hexdigest() + new = self.commit() + valid = self._client_attach_review(new, ['skills/sample'], notice_sha) + cases = [ + ('未绑定当前固定快照', {'acceptedClientAttachedNotices': {'sourceRef': self.old}}), + ('未绑定当前固定快照', {'acceptedClientAttachedNotices': {'sourceRef': 'a' * 40}}), + ('不在已核验实现清单中', {'acceptedClientAttachedNotices': {'clientCommit': 'a' * 40}}), + ('客户端提交无效', {'acceptedClientAttachedNotices': {'clientCommit': '28128a15'}}), + ('客户端 tree 与已核验实现不一致', {'acceptedClientAttachedNotices': {'clientTree': 'a' * 40}}), + ('根通知哈希与当前快照不一致', {'acceptedClientAttachedNotices': {'noticeSha256': 'b' * 64}}), + ('缺少子项安装回读', {'acceptedClientAttachedNotices': {'scopes': []}}), + ('必须包含审核人、日期和理由', {'notes': ''}), + ('必须包含审核人、日期和理由', {'reviewedBy': ''}), + ] + for message, overrides in cases: + with self.subTest(overrides=overrides): + review = self._client_attach_review(new, ['skills/sample'], notice_sha, **overrides) + with self.assertRaisesRegex(AuditBlocked, message): + audit_snapshots(self.repo, self.entry, self.metadata, + {'ref': self.old, 'head': new}, '2026-10-31T01:02:03Z', + special_review=review) + + def test_client_attached_notices_rejects_missing_child_readback(self): + self.write('skills/another/SKILL.md', '---\nname: another\ndescription: Fixture\nversion: 1.0.0\n---\n') + (self.repo / 'skills/sample/LICENSE').unlink() + (self.repo / 'skills/another/LICENSE').unlink() + self.entry['children'] = [ + {'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0'}, + {'id': 'another', 'path': 'skills/another', 'version': '1.0.0'}, + ] + self.metadata['spec'] = {'collection': {'children': [ + {'identity': {'id': 'sample'}, 'path': 'skills/sample', + 'release': {'state': 'known', 'version': '1.0.0', 'versionScheme': 'semver'}}, + {'identity': {'id': 'another'}, 'path': 'skills/another', + 'release': {'state': 'known', 'version': '1.0.0', 'versionScheme': 'semver'}}, + ]}} + self._rebind_old(self.commit()) + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + notice_sha = hashlib.sha256((self.repo / 'LICENSE').read_bytes()).hexdigest() + new = self.commit() + complete = self._client_attach_review(new, ['skills/sample', 'skills/another'], notice_sha) + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=complete) + partial = self._client_attach_review(new, ['skills/sample'], notice_sha) + with self.assertRaisesRegex(AuditBlocked, '缺少子项安装回读|与安装范围不一致'): + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=partial) + + def test_client_attached_notices_cannot_excuse_incomplete_mit(self): + self.write('LICENSE', 'License: MIT\n') + (self.repo / 'skills/sample/LICENSE').unlink() + self._rebind_old(self.commit()) + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + notice_sha = hashlib.sha256((self.repo / 'LICENSE').read_bytes()).hexdigest() + new = self.commit() + review = self._client_attach_review(new, ['skills/sample'], notice_sha) + with self.assertRaisesRegex(AuditBlocked, '不完整的 MIT 声明|完整版权|pin-bound-license-exception'): + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) + + def test_notes_without_client_attached_evidence_do_not_pass(self): + (self.repo / 'skills/sample/LICENSE').unlink() + self._rebind_old(self.commit()) + self.write('skills/sample/scripts/tool.py', 'print("new fixture")\n') + with self.assertRaisesRegex(AuditBlocked, 'Installed notices|安装通知'): + audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': self.commit()}, + '2026-10-31T01:02:03Z', + special_review={ + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'The client will attach the root LICENSE later.', + }) + def test_disallows_non_github_fetch_targets(self): self.entry['source']['repoUrl'] = 'file:///private/source' with self.assertRaisesRegex(AuditBlocked, 'HTTPS'): audit_update(self.entry, self.metadata, {}) + def _collection_description_fixture(self, new_description, short_descs, catalog=True): + self.entry = { + 'id': 'collection', + 'latestVersion': '1.0.0', + 'source': {'kind': 'git', 'repoUrl': 'https://github.com/example/sample.git', 'ref': self.old}, + 'children': [{ + 'id': 'sample', + 'path': 'skills/sample', + 'version': '1.0.0', + 'i18n': { + 'zh-CN': {'shortDesc': '旧的中文简介:在单个长会话中统筹子 Agent。'}, + 'en-US': {'shortDesc': 'Acts as a chief of staff in one long session, co-ordinating subagents toward a long-running goal.'}, + }, + }], + } + self.metadata['identity'] = {'kind': 'skill', 'id': 'collection'} + self.metadata['provenance']['content'] = {'kind': 'git', 'url': self.entry['source']['repoUrl'], 'ref': self.old} + self.metadata['spec'] = {'collection': {'children': [{ + 'identity': {'kind': 'skill', 'id': 'sample', 'parentId': 'collection'}, + 'path': 'skills/sample', + 'presentation': {'defaultLocale': 'en-US', 'i18n': { + 'en-US': {'name': 'sample', 'summary': self.entry['children'][0]['i18n']['en-US']['shortDesc']}, + 'zh-CN': {'name': 'sample', 'summary': self.entry['children'][0]['i18n']['zh-CN']['shortDesc']}, + }, 'tags': []}, + 'release': {'state': 'unknown'}, + }]}} if catalog else {'collection': {'children': [{'identity': {'id': 'sample'}, 'path': 'skills/sample'}]}} + old_text = (self.repo / 'skills/sample/SKILL.md').read_text() + self.write('skills/sample/SKILL.md', old_text.replace('description: Fixture', f'description: {new_description}')) + self.entry['children'][0]['i18n']['en-US']['shortDesc'] = short_descs['en-US'] + self.entry['children'][0]['i18n']['zh-CN']['shortDesc'] = short_descs['zh-CN'] + if catalog: + i18n = self.metadata['spec']['collection']['children'][0]['presentation']['i18n'] + i18n['en-US']['summary'] = short_descs['en-US'] + i18n['zh-CN']['summary'] = short_descs['zh-CN'] + new = self.commit() + return new, GENERATOR.skill_frontmatter(self.repo, 'skills/sample/SKILL.md', new) + + def _description_review(self, new, fm, short_descs, **overrides): + from audit_skill_update import frontmatter_identity, _text_sha256 + accepted = { + 'fromRef': self.old, + 'toRef': new, + 'files': [{ + 'path': 'skills/sample', + 'oldDescription': 'Fixture', + 'newDescription': fm['description'], + 'newFrontmatterSha256': frontmatter_identity(fm), + 'locales': { + locale: { + 'shortDesc': text, + 'sha256': _text_sha256(text), + 'previousShortDesc': { + 'en-US': 'Acts as a chief of staff in one long session, co-ordinating subagents toward a long-running goal.', + 'zh-CN': '旧的中文简介:在单个长会话中统筹子 Agent。', + }[locale], + } + for locale, text in short_descs.items() + }, + }], + } + accepted.update(overrides) + return { + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'Reviewed bilingual listing copy against the new upstream description for this pin.', + 'acceptedFrontmatterSha256': {'skills/sample': frontmatter_identity(fm)}, + 'acceptedDescriptionAndLocales': accepted, + } + + def test_description_and_locales_accepts_updated_short_desc(self): + new_description = 'Delegate the work to fresh subagents and remember what it taught you in a dated wiki, so the next session picks up the thread.' + short_descs = { + 'en-US': 'Delegates work to fresh-context background subagents and records dated knowledge in an agreed wiki for later sessions.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + new, fm = self._collection_description_fixture(new_description, short_descs) + entry, metadata, report = audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=self._description_review(new, fm, short_descs)) + self.assertEqual(entry['source']['ref'], new) + self.assertEqual(metadata['governance']['compliance']['reviewedRef'], new) + self.assertTrue(any('双语简介' in item or '简介' in item for item in report['limitations'])) + + def test_description_and_locales_rejects_mismatched_bindings(self): + new_description = 'Delegate the work to fresh subagents and remember what it taught you in a dated wiki, so the next session picks up the thread.' + short_descs = { + 'en-US': 'Delegates work to fresh-context background subagents and records dated knowledge in an agreed wiki for later sessions.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + new, fm = self._collection_description_fixture(new_description, short_descs) + review = self._description_review(new, fm, short_descs) + variants = [ + ('未绑定当前固定快照', {'toRef': self.old}), + ('未绑定当前固定快照', {'fromRef': new}), + ('路径与上游简介变化范围不一致', {'files': [{**review['acceptedDescriptionAndLocales']['files'][0], 'path': 'skills/missing'}]}), + ] + for message, override in variants: + with self.subTest(message): + broken = self._description_review(new, fm, short_descs, **override) + with self.assertRaisesRegex(AuditBlocked, message): + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=broken) + + def test_description_and_locales_rejects_stale_or_unmatched_short_desc(self): + new_description = 'Delegate the work to fresh subagents and remember what it taught you in a dated wiki, so the next session picks up the thread.' + stale = { + 'en-US': 'Acts as a chief of staff in one long session, co-ordinating subagents toward a long-running goal.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + new, fm = self._collection_description_fixture(new_description, stale) + with self.assertRaisesRegex(AuditBlocked, '未相对原先文案更新|未实际更新以匹配上游简介'): + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=self._description_review(new, fm, stale)) + self.run_git('reset', '--hard', self.old) + self.run_git('clean', '-fd') + unmatched = { + 'en-US': 'A completely unrelated listing about typography and typographic color palettes.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + new, fm = self._collection_description_fixture(new_description, unmatched) + with self.assertRaisesRegex(AuditBlocked, '未实际更新以匹配上游简介'): + audit_snapshots(self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=self._description_review(new, fm, unmatched)) + + def test_notes_without_description_locale_evidence_do_not_pass(self): + new_description = 'Delegate the work to fresh subagents and remember what it taught you in a dated wiki, so the next session picks up the thread.' + short_descs = { + 'en-US': 'Delegates work to fresh-context background subagents and records dated knowledge in an agreed wiki for later sessions.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + new, fm = self._collection_description_fixture(new_description, short_descs) + from audit_skill_update import frontmatter_identity + with self.assertRaisesRegex(AuditBlocked, 'description-and-locales|简介|manual_review|安装通知|元数据'): + audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', + special_review={ + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'The bilingual shortDesc was reviewed.', + 'acceptedFrontmatterSha256': {'skills/sample': frontmatter_identity(fm)}, + }) + + + def test_collection_root_i18n_does_not_require_child_locale_review(self): + # A collection listing shortDesc is not derived copy for a member that has none. + self.entry = { + 'id': 'collection', + 'latestVersion': '1.0.0', + 'source': {'kind': 'git', 'repoUrl': 'https://github.com/example/sample.git', 'ref': self.old}, + 'i18n': {'en-US': {'name': 'Collection', 'shortDesc': 'Root listing only.'}, + 'zh-CN': {'name': '合集', 'shortDesc': '仅有合集简介。'}}, + 'children': [{'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0'}], + } + self.metadata['identity'] = {'kind': 'skill', 'id': 'collection'} + self.metadata['provenance']['content'] = {'kind': 'git', 'url': self.entry['source']['repoUrl'], 'ref': self.old} + self.metadata['spec'] = {'collection': {'children': [{'identity': {'id': 'sample'}, 'path': 'skills/sample'}]}} + new_description = 'Delegate the work to fresh subagents and remember what it taught you in a dated wiki, so the next session picks up the thread.' + self.write('skills/sample/SKILL.md', (self.repo/'skills/sample/SKILL.md').read_text().replace('description: Fixture', f'description: {new_description}')) + new = self.commit() + fm = GENERATOR.skill_frontmatter(self.repo, 'skills/sample/SKILL.md', new) + review = { + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'Frontmatter-only review; this child has no listing shortDesc.', + 'acceptedFrontmatterSha256': {'skills/sample': frontmatter_identity(fm)}, + } + entry, metadata, report = audit_snapshots( + self.repo, self.entry, self.metadata, {'ref': self.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) + self.assertEqual(entry['source']['ref'], new) + self.assertEqual(metadata['governance']['compliance']['reviewedRef'], new) + if __name__ == '__main__': unittest.main() diff --git a/scripts/catalog/test_update_diagnostics.py b/scripts/catalog/test_update_diagnostics.py index 9a1239f..a0e955c 100644 --- a/scripts/catalog/test_update_diagnostics.py +++ b/scripts/catalog/test_update_diagnostics.py @@ -340,3 +340,167 @@ def test_live_check_failure_is_not_misclassified_as_receipt_derivative(case): check=next(r for r in rows if r['gate']=='candidate-live-check') assert check['origin']=='unknown' assert check['evidence']['conclusion']=='failure' + + +def _client_attach_review(case, new, scopes, notice_sha): + return { + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'Install-copy readback of verified client root-notice attach for this pin.', + 'acceptedClientAttachedNotices': { + 'sourceRef': new, + 'clientCommit': '28128a15b3abd76e1529b983ca8a921bdfe9ff30', + 'clientTree': 'e8c1321e6a098eb905f4646b2027bc7b2259ca6b', + 'observedAt': '2026-11-26T16:04:23Z', + 'noticeRootPath': 'LICENSE', + 'noticeSha256': notice_sha, + 'scopes': [ + {'path': path, 'attached': [ + {'name': 'LICENSE', 'sourceName': 'LICENSE', 'sha256': notice_sha}, + ]} + for path in scopes + ], + }, + } + + +def test_client_attached_notice_readback_is_info_not_blocked(case): + import hashlib + (case.repo/'skills/sample/LICENSE').unlink() + baseline(case) + case.write('skills/sample/scripts/tool.py','new') + new = case.commit() + notice_sha = hashlib.sha256((case.repo/'LICENSE').read_bytes()).hexdigest() + review = _client_attach_review(case, new, ['skills/sample'], notice_sha) + rows = inspect_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, review) + row = next(r for r in rows if r['gate']=='installed-project-notice') + assert row['state']=='info' + assert row['evidence']['clientCommit']=='28128a15b3abd76e1529b983ca8a921bdfe9ff30' + assert not any(r['gate']=='installed-project-notice' and r['state']=='blocked' for r in rows) + _,_,receipt = audit_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) + assert receipt['source']['ref']==new + + +def test_wrong_pin_client_attach_review_does_not_deliver(case): + import hashlib + (case.repo/'skills/sample/LICENSE').unlink() + baseline(case) + case.write('skills/sample/scripts/tool.py','new') + new = case.commit() + notice_sha = hashlib.sha256((case.repo/'LICENSE').read_bytes()).hexdigest() + review = _client_attach_review(case, case.old, ['skills/sample'], notice_sha) + rows = inspect_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, review) + assert any(r['gate']=='client-attached-notice' and r['state']=='blocked' for r in rows) + assert any(r['gate']=='installed-project-notice' and r['state']=='blocked' for r in rows) + with pytest.raises(AuditBlocked): + audit_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) + + +def _updated_short_descs(): + return { + 'en-US': 'Delegates work to fresh-context background subagents and records dated knowledge in an agreed wiki for later sessions.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + + +def _description_locale_case(case, short_descs): + from audit_skill_update import GENERATOR, frontmatter_identity, _text_sha256 + old_en = 'Acts as a chief of staff in one long session, co-ordinating subagents toward a long-running goal.' + old_zh = '旧的中文简介:在单个长会话中统筹子 Agent。' + case.entry = { + 'id': 'collection', + 'latestVersion': '1.0.0', + 'source': {'kind': 'git', 'repoUrl': 'https://github.com/example/sample.git', 'ref': case.old}, + 'children': [{'id': 'sample', 'path': 'skills/sample', 'version': '1.0.0', 'i18n': { + 'zh-CN': {'shortDesc': old_zh}, + 'en-US': {'shortDesc': old_en}, + }}], + } + case.metadata['identity'] = {'kind': 'skill', 'id': 'collection'} + case.metadata['provenance']['content'] = {'kind': 'git', 'url': case.entry['source']['repoUrl'], 'ref': case.old} + case.metadata['spec'] = {'collection': {'children': [{ + 'identity': {'kind': 'skill', 'id': 'sample', 'parentId': 'collection'}, + 'path': 'skills/sample', + 'presentation': {'defaultLocale': 'en-US', 'i18n': { + 'en-US': {'name': 'sample', 'summary': old_en}, + 'zh-CN': {'name': 'sample', 'summary': old_zh}, + }, 'tags': []}, + 'release': {'state': 'unknown'}, + }]}} + case.entry['source']['ref'] = case.old + case.metadata['provenance']['content']['ref'] = case.old + case.metadata['governance']['compliance']['reviewedRef'] = case.old + new_description = 'Delegate the work to fresh subagents and remember what it taught you in a dated wiki, so the next session picks up the thread.' + case.write('skills/sample/SKILL.md', (case.repo/'skills/sample/SKILL.md').read_text().replace('description: Fixture', f'description: {new_description}')) + case.entry['children'][0]['i18n']['en-US']['shortDesc'] = short_descs['en-US'] + case.entry['children'][0]['i18n']['zh-CN']['shortDesc'] = short_descs['zh-CN'] + i18n = case.metadata['spec']['collection']['children'][0]['presentation']['i18n'] + i18n['en-US']['summary'] = short_descs['en-US'] + i18n['zh-CN']['summary'] = short_descs['zh-CN'] + new = case.commit() + fm = GENERATOR.skill_frontmatter(case.repo, 'skills/sample/SKILL.md', new) + review = { + 'schemaVersion': 1, + 'reviewedBy': 'mashagua', + 'reviewedAt': '2026-11-27', + 'notes': 'Reviewed bilingual listing copy against the new upstream description for this pin.', + 'acceptedFrontmatterSha256': {'skills/sample': frontmatter_identity(fm)}, + 'acceptedDescriptionAndLocales': { + 'fromRef': case.old, + 'toRef': new, + 'files': [{ + 'path': 'skills/sample', + 'oldDescription': 'Fixture', + 'newDescription': fm['description'], + 'newFrontmatterSha256': frontmatter_identity(fm), + 'locales': { + locale: { + 'shortDesc': text, + 'sha256': _text_sha256(text), + 'previousShortDesc': {'en-US': old_en, 'zh-CN': old_zh}[locale], + } + for locale, text in short_descs.items() + }, + }], + }, + } + return new, fm, review + + +def test_description_locale_review_is_info_not_manual(case): + new, fm, review = _description_locale_case(case, _updated_short_descs()) + rows = inspect_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, review) + row = next(r for r in rows if r['gate']=='description-and-locales') + assert row['state']=='info' + assert not any(r['gate']=='description-and-locales-review' and r['state']=='blocked' for r in rows) + _,_,receipt = audit_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) + assert receipt['source']['ref']==new + + +def test_wrong_pin_description_locale_review_does_not_pass(case): + new, fm, review = _description_locale_case(case, _updated_short_descs()) + review['acceptedDescriptionAndLocales']['toRef'] = case.old + rows = inspect_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, review) + assert any(r['gate']=='description-and-locales-review' and r['state']=='blocked' for r in rows) + assert any(r['gate']=='description-and-locales' and r['state']=='manual_review' for r in rows) + with pytest.raises(AuditBlocked): + audit_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) + + +def test_stale_short_desc_description_locale_review_does_not_pass(case): + stale = { + 'en-US': 'Acts as a chief of staff in one long session, co-ordinating subagents toward a long-running goal.', + 'zh-CN': '将工作委派给新上下文后台子 Agent,并把有日期的知识写入约定 wiki,供后续会话续接。', + } + new, fm, review = _description_locale_case(case, stale) + rows = inspect_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, review) + assert any(r['gate']=='description-and-locales-review' and r['state']=='blocked' for r in rows) + assert any(r['gate']=='description-and-locales' and r['state']=='manual_review' for r in rows) + with pytest.raises(AuditBlocked): + audit_snapshots(case.repo, case.entry, case.metadata, {'ref': case.old, 'head': new}, + '2026-10-31T01:02:03Z', special_review=review) diff --git a/scripts/catalog/update_diagnostics.py b/scripts/catalog/update_diagnostics.py index 4501f27..04eaf96 100644 --- a/scripts/catalog/update_diagnostics.py +++ b/scripts/catalog/update_diagnostics.py @@ -32,7 +32,10 @@ def normalized(data): 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 + from audit_skill_update import ( + git, blob, safe_path, GENERATOR, MAX_FILE_BYTES, MAX_FILES, + accept_client_attached_notices, accept_description_and_locales, _has_locale_copy, AuditBlocked, + ) old, new = result['ref'], result['head'] review = special_review or {} rows = [] @@ -78,6 +81,26 @@ def inspect_snapshots(repo, entry, metadata, result, special_review=None): '取得完整主许可通知,或由维护者明确审核并授权精确新 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()}) + attached_scopes = set() + if review.get('acceptedClientAttachedNotices'): + try: + attached_scopes = accept_client_attached_notices( + review, repo, new, scopes, grants[new], license_value) + except AuditBlocked as error: + add('.', 'client-attached-notice', 'blocked', 'introduced', + '专项复核的客户端附加通知证据无效或未绑定当前 pin。 / Client-attached notice special review is invalid or not bound to this pin.', + '按已核验客户端实现、当前上游 pin、根通知哈希和全部安装范围的真实安装回读补全证据;不要把「将会附加」写成已交付,也不要把旧回执延伸到新 pin。 / Complete evidence bound to a verified client implementation, the current pin, the root notice hash, and install-copy readback for every install scope; do not record future attachment as delivery or extend an old receipt to a new pin.', + {'detail': str(error)}) + locale_accepted_scopes = set() + if review.get('acceptedDescriptionAndLocales'): + try: + locale_accepted_scopes = accept_description_and_locales( + review, entry, metadata, repo, old, new, scopes) + except AuditBlocked as error: + add('.', 'description-and-locales-review', 'blocked', 'introduced', + '专项复核的简介与双语证据无效或未绑定当前 pin。 / Description-and-locales special review is invalid or not bound to this pin.', + '按当前旧/新 pin、变化路径、新 frontmatter 哈希和已更新并匹配上游新简介的条目/catalog 简介补全证据;不要把未更新文案或旧回执延伸到新 pin。 / Complete evidence bound to the current pins, changed paths, the new frontmatter hash, and updated entry/catalog summaries that match the new upstream description; do not extend stale copy or an old receipt to a new pin.', + {'detail': str(error)}) for scope in scopes: def delivered(ref): grant = grants[ref] @@ -98,7 +121,19 @@ def inspect_snapshots(repo, entry, metadata, result, special_review=None): 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: + if not new_ok and scope in attached_scopes: + accepted = review.get('acceptedClientAttachedNotices') or {} + add(scope, 'installed-project-notice', 'info', 'pre_existing' if not old_ok else 'changed', + '源子目录仍无完整通知;已按绑定当前 pin 与已核验客户端实现的安装回读,证明安装副本携带了完整根通知。 / The source child directory still lacks a complete notice; install-copy readback bound to this pin and a verified client implementation proves the staged copy carries the complete root notice.', + '该接受仅绑定本专项复核中的上游 pin 与客户端提交;不得自动延伸到新 pin,也不是许可例外。 / This acceptance is bound to the source pin and client commit in the special review; it does not automatically extend to a later pin and is not a license exception.', + {'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, + 'clientCommit': accepted.get('clientCommit'), + 'noticeRootPath': accepted.get('noticeRootPath'), + 'proof': 'client attach install-copy readback bound to pin, client commit, and root notice hash'}) + elif 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.', @@ -173,8 +208,9 @@ def inspect_snapshots(repo, entry, metadata, result, special_review=None): 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', + has_locale_copy = _has_locale_copy(entry, scope) + locale_ok = scope in locale_accepted_scopes + add(marker, 'description-and-locales', 'info' if locale_ok else ('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')})