diff --git a/.codex-tasks/template-audit-execution/raw/completion-evidence.json b/.codex-tasks/template-audit-execution/raw/completion-evidence.json index 0d47510..8be1aa0 100644 --- a/.codex-tasks/template-audit-execution/raw/completion-evidence.json +++ b/.codex-tasks/template-audit-execution/raw/completion-evidence.json @@ -256,5 +256,5 @@ } } }, - "sourceTreeHash": "a5171438f3efa8ed2ff1381cc957a33be0976a600ad5d7d100b08cf83fa832a4" + "sourceTreeHash": "88af963f5c1186b8e3b9a8ba4c6132f1601d0f4ee21d334bf9b7aacfccd3e04c" } diff --git a/deploy/republish-stale-template-contracts.mjs b/deploy/republish-stale-template-contracts.mjs index f91fd9a..8ede47b 100644 --- a/deploy/republish-stale-template-contracts.mjs +++ b/deploy/republish-stale-template-contracts.mjs @@ -15,23 +15,77 @@ const CONTRACT_KEYS = new Set([ ]); const VOLATILE_KEYS = new Set(["generatedAt"]); +/** null 与缺失键都表示“没有值”,比较前统一剔除,避免旧快照缺列被误判为内容变更。 */ +function normalizeNullish(value) { + if (Array.isArray(value)) return value.map(normalizeNullish); + if (value && typeof value === "object") { + const result = {}; + for (const [key, item] of Object.entries(value)) { + if (item === null || item === undefined) continue; + result[key] = normalizeNullish(item); + } + return result; + } + return value; +} + +function isPlainObject(value) { + return Boolean(value) && typeof value === "object" && !Array.isArray(value); +} + +/** 返回递归差异路径,用于判断内容差异是否全部属于显式允许的遗留字段删除。 */ +export function diffPaths(published, current, prefix = "") { + if (isPlainObject(published) && isPlainObject(current)) { + const keys = new Set([...Object.keys(published), ...Object.keys(current)]); + return [...keys].flatMap((key) => + diffPaths(published[key], current[key], prefix ? prefix + "." + key : key), + ); + } + return isDeepStrictEqual(published, current) ? [] : [{ path: prefix }]; +} + /** * 只允许自动重发“模板契约字段变化、品牌内容未变”的发布快照。 * 一旦草稿内容与已发布快照不同,必须由管理员显式审查后发布,避免误发草稿。 + * allowedRemovedKeys 只能放行“旧值存在、新值缺失”的遗留字段删除,不能放行赋值变化。 */ -export function classifyContractRefresh(published, current) { +export function classifyContractRefresh(published, current, options = {}) { if (!published || !current) throw new Error("发布快照不能为空"); - const keys = new Set([...Object.keys(published), ...Object.keys(current)]); + const allowedRemovedKeys = new Set(options.allowedRemovedKeys ?? []); + const normalizedPublished = normalizeNullish(published); + const normalizedCurrent = normalizeNullish(current); + const keys = new Set([...Object.keys(normalizedPublished), ...Object.keys(normalizedCurrent)]); const changedKeys = [...keys] .filter((key) => !VOLATILE_KEYS.has(key)) - .filter((key) => !isDeepStrictEqual(published[key], current[key])); - if (changedKeys.length === 0) return { status: "current", changedKeys, blockingKeys: [] }; - const blockingKeys = changedKeys.filter((key) => !CONTRACT_KEYS.has(key)); - return { - status: blockingKeys.length ? "content-diverged" : "contract-stale", - changedKeys, - blockingKeys, - }; + .filter((key) => !isDeepStrictEqual(normalizedPublished[key], normalizedCurrent[key])); + const blockingKeys = []; + const allowedChanges = []; + for (const key of changedKeys) { + if (CONTRACT_KEYS.has(key)) continue; + const changes = diffPaths(normalizedPublished[key], normalizedCurrent[key], key); + const blocking = changes.filter( + (change) => + !(allowedRemovedKeys.has(change.path) && isRemovedAtPath(normalizedCurrent, change.path)), + ); + if (blocking.length) blockingKeys.push(key); + else allowedChanges.push(...changes.map((change) => change.path)); + } + const status = blockingKeys.length + ? "content-diverged" + : changedKeys.length + ? "contract-stale" + : "current"; + return { status, changedKeys, blockingKeys, allowedChanges }; +} + +function isRemovedAtPath(root, dotPath) { + let node = root; + const parts = dotPath.split("."); + for (const part of parts.slice(0, -1)) { + if (!isPlainObject(node) || !Object.hasOwn(node, part)) return false; + node = node[part]; + } + return isPlainObject(node) && !Object.hasOwn(node, parts.at(-1)); } async function loadServices() { @@ -50,8 +104,21 @@ async function loadServices() { }; } +function parseArgs(argv) { + const options = { apply: false, allowedRemovedKeys: [] }; + for (const arg of argv) { + if (arg === "--apply") options.apply = true; + else if (arg.startsWith("--allow-removed-key=")) { + const key = arg.slice("--allow-removed-key=".length); + if (!key) throw new Error("--allow-removed-key 需要字段路径"); + options.allowedRemovedKeys.push(key); + } else throw new Error(`未知参数:${arg}`); + } + return options; +} + async function main() { - const apply = process.argv.includes("--apply"); + const options = parseArgs(process.argv.slice(2)); const actorUsername = process.env.TEMPLATE_CATALOG_ACTOR ?? "admin"; const note = process.env.TEMPLATE_CONTRACT_REPUBLISH_NOTE ?? "模板契约迁移:刷新已发布页面方案兼容性"; @@ -78,14 +145,14 @@ async function main() { continue; } const current = await snapshots.buildSnapshot(brand.id); - const classification = classifyContractRefresh(release.snapshot, current); + const classification = classifyContractRefresh(release.snapshot, current, options); const result = { slug: brand.slug, releaseVersion: release.version, ...classification, }; results.push(result); - if (!apply || classification.status !== "contract-stale") continue; + if (!options.apply || classification.status !== "contract-stale") continue; const readiness = await releases.readiness(brand.id); if (!readiness.ready) { result.status = "not-ready"; @@ -98,8 +165,22 @@ async function main() { result.status = "republished"; result.newReleaseVersion = published.version; } - console.log(JSON.stringify({ apply, actor: actorUsername, results }, null, 2)); - if (apply && results.some((item) => ["content-diverged", "not-ready"].includes(item.status))) + console.log( + JSON.stringify( + { + apply: options.apply, + actor: actorUsername, + allowedRemovedKeys: options.allowedRemovedKeys, + results, + }, + null, + 2, + ), + ); + if ( + options.apply && + results.some((item) => ["content-diverged", "not-ready"].includes(item.status)) + ) process.exitCode = 1; } finally { await prisma.$disconnect(); diff --git a/deploy/republish-stale-template-contracts.test.mjs b/deploy/republish-stale-template-contracts.test.mjs index f330300..2911f4c 100644 --- a/deploy/republish-stale-template-contracts.test.mjs +++ b/deploy/republish-stale-template-contracts.test.mjs @@ -17,24 +17,27 @@ function snapshot(overrides = {}) { }; } -test("detects a contract-only stale publication", () => { - const current = snapshot({ +const staleContract = () => + snapshot({ generatedAt: "2026-10-20T01:00:00.000Z", visualTemplateDefinition: { supportedIndustryTemplates: ["doors"] }, templatePackageManifest: { supportedIndustryTemplates: ["doors"] }, installation: { templateVersion: "1.0.7" }, }); - assert.deepEqual(classifyContractRefresh(snapshot(), current), { + +test("detects a contract-only stale publication", () => { + assert.deepEqual(classifyContractRefresh(snapshot(), staleContract()), { status: "contract-stale", changedKeys: ["visualTemplateDefinition", "templatePackageManifest", "installation"], blockingKeys: [], + allowedChanges: [], }); }); test("ignores generated timestamps when the publication is current", () => { assert.deepEqual( classifyContractRefresh(snapshot(), snapshot({ generatedAt: "2026-10-21T00:00:00.000Z" })), - { status: "current", changedKeys: [], blockingKeys: [] }, + { status: "current", changedKeys: [], blockingKeys: [], allowedChanges: [] }, ); }); @@ -47,5 +50,74 @@ test("blocks automatic publication when draft content has diverged", () => { status: "content-diverged", changedKeys: ["installation", "brand"], blockingKeys: ["brand"], + allowedChanges: [], }); }); + +test("treats a missing key and an explicit null as the same value", () => { + const current = snapshot({ brand: { name: "林境门作", miniAppSettings: null } }); + assert.equal(classifyContractRefresh(snapshot(), current).status, "current"); +}); + +test("allows an explicitly permitted legacy field removal", () => { + const published = snapshot({ + brand: { name: "林境门作", config: { visualTemplateKey: "doors" } }, + }); + const current = snapshot({ brand: { name: "林境门作", config: {} } }); + assert.deepEqual( + classifyContractRefresh(published, current, { + allowedRemovedKeys: ["brand.config.visualTemplateKey"], + }), + { + status: "contract-stale", + changedKeys: ["brand"], + blockingKeys: [], + allowedChanges: ["brand.config.visualTemplateKey"], + }, + ); +}); + +test("does not allow an unlisted legacy field removal", () => { + const published = snapshot({ + brand: { name: "林境门作", config: { visualTemplateKey: "doors" } }, + }); + const current = snapshot({ brand: { name: "林境门作", config: {} } }); + assert.deepEqual(classifyContractRefresh(published, current), { + status: "content-diverged", + changedKeys: ["brand"], + blockingKeys: ["brand"], + allowedChanges: [], + }); +}); + +test("does not allow a permitted legacy field to change value", () => { + const published = snapshot({ + brand: { name: "林境门作", config: { visualTemplateKey: "doors" } }, + }); + const current = snapshot({ brand: { name: "林境门作", config: { visualTemplateKey: "other" } } }); + assert.deepEqual( + classifyContractRefresh(published, current, { + allowedRemovedKeys: ["brand.config.visualTemplateKey"], + }), + { + status: "content-diverged", + changedKeys: ["brand"], + blockingKeys: ["brand"], + allowedChanges: [], + }, + ); +}); + +test("blocks when a permitted removal is combined with other content changes", () => { + const published = snapshot({ + brand: { name: "林境门作", config: { visualTemplateKey: "doors" } }, + }); + const current = snapshot({ + brand: { name: "林境门作", config: {}, miniAppSettings: { appId: "wx-test" } }, + }); + const result = classifyContractRefresh(published, current, { + allowedRemovedKeys: ["brand.config.visualTemplateKey"], + }); + assert.equal(result.status, "content-diverged"); + assert.deepEqual(result.blockingKeys, ["brand"]); +});