From 84b13233b265b49fe8344bd6e5adc493f0642864 Mon Sep 17 00:00:00 2001 From: TNT-Likely Date: Wed, 2 Dec 2026 18:54:00 +0800 Subject: [PATCH] ci(pr-policy): require verified isolated QA reports on external PRs --- .../references/delivery.md | 2 +- .github/PULL_REQUEST_TEMPLATE.md | 9 + .github/pr-policy.json | 14 +- .github/scripts/pr-policy.cjs | 460 +++++++++++++++++- .github/scripts/pr-policy.test.cjs | 271 ++++++++++- docs/pr-policy.md | 18 + docs/pr-policy.zh-CN.md | 18 + 7 files changed, 770 insertions(+), 22 deletions(-) diff --git a/.agents/skills/panwatch-local-delivery/references/delivery.md b/.agents/skills/panwatch-local-delivery/references/delivery.md index bdaff93bb..e86d7f7f7 100644 --- a/.agents/skills/panwatch-local-delivery/references/delivery.md +++ b/.agents/skills/panwatch-local-delivery/references/delivery.md @@ -9,7 +9,7 @@ - index.html:离线可打开,先展示需求、操作、截图、业务数据对照、逐项状态和限制。 - OPEN.md:解压打开说明、版本、自动验收时间和当前人工验收环境状态。 - evidence/:脱敏截图和 JSON;引用使用包内相对路径。 -- manifest.json:文件大小/hash、业务 SHA/内容 hash、构建 hash、run ID、技能版本/hash。 +- manifest.json:文件大小/hash、业务 SHA/内容 hash、构建 hash、run ID、技能版本/hash。为满足 `PR policy` 机械校验,至少包含顶层字段 `base_sha`(当前 PR head SHA)、`run_id`、`skill_version`(例如 `"1.3.0"`)以及 `summary`(含 `failed` 计数)。 - SHA256SUMS:文件校验表。先完成其他内容,再生成 manifest 的文件清单(不包含 manifest 自身和 SHA256SUMS);最后校验表包含 manifest,排除校验表自身。ZIP 自身 hash 留在包外。 技术信息置于折叠附录。HTML 图片/样式/脚本均来自包内,不依赖 CDN、运行服务、file:// 或本机绝对路径。检查桌面和窄屏、长路径/JSON 换行及证据引用。 diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 2e21ea150..e1da3e309 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -28,6 +28,15 @@ Commands and results: +### Test report + + ## Acceptance evidence Steps: diff --git a/.github/pr-policy.json b/.github/pr-policy.json index 3a759608c..0a8c826c3 100644 --- a/.github/pr-policy.json +++ b/.github/pr-policy.json @@ -9,6 +9,18 @@ "needsSplit": "pr:needs-split", "needsEvidence": "pr:needs-evidence", "hold": "pr:hold", - "scopeApproved": "pr:scope-approved" + "scopeApproved": "pr:scope-approved", + "qaExempt": "pr:qa-exempt" + }, + "qaReport": { + "required": true, + "exemptAuthors": [ + "TNT-Likely" + ], + "minSkillVersion": "1.3.0", + "maxZipBytes": 20971520, + "maxUncompressedBytes": 52428800, + "maxEntries": 500, + "fetchTimeoutMs": 15000 } } diff --git a/.github/scripts/pr-policy.cjs b/.github/scripts/pr-policy.cjs index 5cab2f036..ee38ea3c9 100644 --- a/.github/scripts/pr-policy.cjs +++ b/.github/scripts/pr-policy.cjs @@ -1,10 +1,37 @@ 'use strict'; +const crypto = require('node:crypto'); +const zlib = require('node:zlib'); const config = require('../pr-policy.json'); + const MARKER = ''; const DAY = 86400000; const SECTIONS = ['Background', 'Changes', 'Scope', 'Validation', 'Acceptance evidence', 'Boundaries and risks', 'Follow-up']; +const ALLOWED_DOWNLOAD_HOSTS = [ + /^github\.com$/i, + /^objects\.githubusercontent\.com$/i, + /^release-assets\.githubusercontent\.com$/i, + /\.githubusercontent\.com$/i, + /\.blob\.core\.windows\.net$/i, + /\.amazonaws\.com$/i, +]; + +const FORBIDDEN_ARCHIVE_PATTERNS = [ + /(^|\/)credentials\.json$/i, + /(^|\/)\.env(\.|$)/i, + /\.(?:db|db-wal|db-shm|sqlite|sqlite3|pem|key)$/i, + /(^|\/)[^/]*storage[-_]?state[^/]*\.json$/i, +]; + +const SECRET_TEXT_PATTERNS = [ + {name: 'AUTH_PASSWORD', pattern: /\bAUTH_PASSWORD\s*=\s*\S+/}, + {name: 'jwt_secret', pattern: /"jwt_secret"\s*:\s*"[^"]{8,}"/i}, + {name: 'bot_token', pattern: /"bot_token"\s*:\s*"\d{6,}:[A-Za-z0-9_-]{20,}"/i}, + {name: 'GitHub token', pattern: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b|\bgithub_pat_[A-Za-z0-9_]{20,}\b/}, + {name: 'OpenAI-style API key', pattern: /\bsk-(?:proj-)?[A-Za-z0-9_-]{24,}\b/}, +]; + function substantive(text) { const clean = text.replace(//g, '').replace(/\[[ xX]\]/g, '').trim(); return clean.length > 0 && !/^(?:[-*\s]*|TODO|TBD|N\/?A|None|<[^>]+>|\.{3})[.!\s]*$/i.test(clean); @@ -28,7 +55,329 @@ function productionFile(path) { || /(^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock|uv\.lock|poetry\.lock)$/.test(path)); } -function evaluate(pr, files, scopeApproved = false) { +function isExemptAuthor(pr, qaConfig = config.qaReport) { + const login = String(pr?.user?.login || '').trim().toLowerCase(); + if (!login) return false; + const exempt = (qaConfig?.exemptAuthors || []).map(name => String(name).trim().toLowerCase()).filter(Boolean); + return exempt.includes(login); +} + +function isQaReportRequired(pr, productionFiles, qaExemptApproved = false, qaConfig = config.qaReport) { + if (!qaConfig?.required) return false; + if (productionFiles <= 0) return false; + if (qaExemptApproved) return false; + if (isExemptAuthor(pr, qaConfig)) return false; + return true; +} + +function isAllowedAttachmentUrl(rawUrl, repo = null) { + let parsed; + try { parsed = new URL(rawUrl); } catch { return false; } + if (parsed.protocol !== 'https:' || parsed.hostname.toLowerCase() !== 'github.com') return false; + if (!/\.zip$/i.test(parsed.pathname)) return false; + if (/^\/user-attachments\/files\/\d+\/[^/]+\.zip$/i.test(parsed.pathname)) return true; + if (repo?.owner && repo?.repo) { + const prefix = `/${repo.owner}/${repo.repo}/files/`.toLowerCase(); + if (parsed.pathname.toLowerCase().startsWith(prefix) && /\/files\/\d+\/[^/]+\.zip$/i.test(parsed.pathname)) return true; + } else if (/^\/[^/]+\/[^/]+\/files\/\d+\/[^/]+\.zip$/i.test(parsed.pathname)) { + return true; + } + return false; +} + +function extractQaReport(body, repo = null) { + const parts = sections(body); + const scope = [parts.validation || '', parts['acceptance evidence'] || ''].join('\n'); + const urls = [...scope.matchAll(/https:\/\/[^\s)<>"']+\.zip(?=[)\s>"']|$)/gi)].map(match => match[0]); + const allowedUrl = urls.find(url => isAllowedAttachmentUrl(url, repo)) || null; + const shaMatch = scope.match(/(?:^|\n)\s*(?:[-*]\s+)?(?:ZIP|QA\s+report)\s+SHA256:\s*`?([a-f0-9]{64})`?/i); + return { + url: allowedUrl, + invalidUrl: !allowedUrl && urls.length > 0 ? urls[0] : null, + sha256: shaMatch ? shaMatch[1].toLowerCase() : null, + }; +} + +function parseSemver(version) { + const match = String(version || '').trim().match(/^(\d+)\.(\d+)\.(\d+)/); + return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null; +} + +function semverGte(actual, minimum) { + const a = parseSemver(actual); + const b = parseSemver(minimum); + if (!a || !b) return false; + for (let i = 0; i < 3; i++) { + if (a[i] !== b[i]) return a[i] > b[i]; + } + return true; +} + +function parseZipEntries(buffer, {maxEntries = 500, maxUncompressedBytes = 52428800} = {}) { + if (!Buffer.isBuffer(buffer) || buffer.length < 22) throw new Error('Archive is not a valid ZIP file.'); + const minOffset = Math.max(0, buffer.length - 65557); + let eocd = -1; + for (let i = buffer.length - 22; i >= minOffset; i--) { + if (buffer.readUInt32LE(i) === 0x06054b50) { + eocd = i; + break; + } + } + if (eocd < 0) throw new Error('Archive is missing ZIP end-of-central-directory record.'); + const entryCount = buffer.readUInt16LE(eocd + 10); + const cdSize = buffer.readUInt32LE(eocd + 12); + const cdOffset = buffer.readUInt32LE(eocd + 16); + if (entryCount === 0) throw new Error('ZIP archive is empty.'); + if (entryCount > maxEntries) throw new Error(`ZIP archive has too many entries (${entryCount} > ${maxEntries}).`); + if (cdOffset + cdSize > buffer.length) throw new Error('ZIP central directory exceeds archive size.'); + + const entries = new Map(); + let totalUncompressed = 0; + let pos = cdOffset; + for (let idx = 0; idx < entryCount; idx++) { + if (pos + 46 > buffer.length || buffer.readUInt32LE(pos) !== 0x02014b50) { + throw new Error('Corrupt ZIP central directory header.'); + } + const method = buffer.readUInt16LE(pos + 10); + const compressedSize = buffer.readUInt32LE(pos + 20); + const uncompressedSize = buffer.readUInt32LE(pos + 24); + const nameLen = buffer.readUInt16LE(pos + 28); + const extraLen = buffer.readUInt16LE(pos + 30); + const commentLen = buffer.readUInt16LE(pos + 32); + const localHeaderOffset = buffer.readUInt32LE(pos + 42); + const rawName = buffer.subarray(pos + 46, pos + 46 + nameLen).toString('utf8'); + pos += 46 + nameLen + extraLen + commentLen; + + if (rawName.includes('\\') || rawName.startsWith('/') || rawName.split('/').includes('..')) { + throw new Error(`ZIP contains an unsafe entry path: ${rawName}`); + } + if (rawName.endsWith('/')) continue; + + if (localHeaderOffset + 30 > buffer.length || buffer.readUInt32LE(localHeaderOffset) !== 0x04034b50) { + throw new Error(`Corrupt ZIP local file header for ${rawName}.`); + } + const lfNameLen = buffer.readUInt16LE(localHeaderOffset + 26); + const lfExtraLen = buffer.readUInt16LE(localHeaderOffset + 28); + const dataStart = localHeaderOffset + 30 + lfNameLen + lfExtraLen; + if (dataStart + compressedSize > buffer.length) { + throw new Error(`ZIP entry data out of bounds for ${rawName}.`); + } + const remainingBudget = maxUncompressedBytes - totalUncompressed; + if (uncompressedSize > remainingBudget) { + throw new Error(`ZIP uncompressed size exceeds limit (${maxUncompressedBytes} bytes).`); + } + const compressed = buffer.subarray(dataStart, dataStart + compressedSize); + let content; + if (method === 0) { + content = Buffer.from(compressed); + } else if (method === 8) { + content = zlib.inflateRawSync(compressed, {maxOutputLength: remainingBudget}); + } else { + throw new Error(`Unsupported ZIP compression method (${method}) for ${rawName}.`); + } + totalUncompressed += content.length; + if (totalUncompressed > maxUncompressedBytes) { + throw new Error(`ZIP uncompressed size exceeds limit (${maxUncompressedBytes} bytes).`); + } + if (entries.has(rawName)) throw new Error(`ZIP contains duplicate entry: ${rawName}`); + entries.set(rawName, content); + } + return entries; +} + +function stripCommonRoot(entries) { + const names = [...entries.keys()]; + const firstSegments = new Set(names.map(name => name.includes('/') ? name.split('/')[0] : '')); + if (firstSegments.size === 1) { + const [prefix] = firstSegments; + if (prefix && names.every(name => name.startsWith(`${prefix}/`))) { + return new Map(names.map(name => [name.slice(prefix.length + 1), entries.get(name)])); + } + } + return entries; +} + +function sha256Hex(buffer) { + return crypto.createHash('sha256').update(buffer).digest('hex'); +} + +function verifyQaReportZip(buffer, {expectedSha256, headSha, minSkillVersion = config.qaReport?.minSkillVersion || '1.3.0', maxEntries = config.qaReport?.maxEntries || 500, maxUncompressedBytes = config.qaReport?.maxUncompressedBytes || 52428800} = {}) { + const problems = []; + if (!Buffer.isBuffer(buffer) || buffer.length === 0) { + return ['QA report ZIP is empty or unreadable.']; + } + const actualSha = sha256Hex(buffer); + if (expectedSha256 && actualSha !== expectedSha256.toLowerCase()) { + return [`QA report ZIP SHA256 mismatch: expected ${expectedSha256.toLowerCase()}, got ${actualSha}.`]; + } + + let rawEntries; + try { + rawEntries = parseZipEntries(buffer, {maxEntries, maxUncompressedBytes}); + } catch (error) { + return [`QA report ZIP could not be verified: ${error.message}`]; + } + + for (const name of rawEntries.keys()) { + if (FORBIDDEN_ARCHIVE_PATTERNS.some(pattern => pattern.test(name))) { + problems.push(`QA report ZIP contains a disallowed private file: ${name}. Remove credentials, databases and env files before uploading.`); + } + } + + const entries = stripCommonRoot(rawEntries); + const indexHtml = entries.get('index.html'); + const manifestBuf = entries.get('manifest.json'); + const sumsBuf = entries.get('SHA256SUMS'); + + if (!indexHtml || !indexHtml.toString('utf8').trim()) { + problems.push('QA report ZIP must include a non-empty index.html.'); + } + if (!manifestBuf) { + problems.push('QA report ZIP must include manifest.json.'); + } + if (!sumsBuf) { + problems.push('QA report ZIP must include SHA256SUMS.'); + } + + if (manifestBuf) { + let manifest; + try { + manifest = JSON.parse(manifestBuf.toString('utf8')); + } catch { + problems.push('QA report manifest.json is not valid JSON.'); + } + if (manifest && typeof manifest === 'object') { + const recordedSha = String(manifest.base_sha || manifest.commit_sha || manifest.tested_commit || '').trim().toLowerCase(); + if (!/^[a-f0-9]{7,40}$/.test(recordedSha) || !String(headSha || '').toLowerCase().startsWith(recordedSha)) { + problems.push(`QA report manifest.json base_sha (${recordedSha || 'missing'}) does not match the current PR head; rerun isolated QA after pushing.`); + } + if (!String(manifest.run_id || '').trim()) { + problems.push('QA report manifest.json must record a non-empty run_id from isolated QA.'); + } + if (!semverGte(manifest.skill_version, minSkillVersion)) { + problems.push(`QA report manifest.json skill_version (${manifest.skill_version || 'missing'}) must be at least ${minSkillVersion} (use .agents/skills/panwatch-local-delivery).`); + } + const failedCount = Number(manifest.failed_count ?? manifest.summary?.failed ?? 0); + if (Number.isFinite(failedCount) && failedCount > 0 || String(manifest.status || '').toUpperCase() === 'FAIL') { + problems.push('QA report manifest.json records failing acceptance checks; resolve failures and upload a passing report.'); + } + } + } + + if (sumsBuf) { + const lines = sumsBuf.toString('utf8').split(/\r?\n/).map(line => line.trim()).filter(Boolean); + if (!lines.length) { + problems.push('QA report SHA256SUMS is empty.'); + } else { + const listed = new Set(); + for (const line of lines) { + const match = line.match(/^([a-f0-9]{64})\s+\*?(.+)$/i); + if (!match) { + problems.push(`QA report SHA256SUMS has an invalid line: ${line.slice(0, 60)}.`); + break; + } + const expected = match[1].toLowerCase(); + const relPath = match[2].replace(/^\.\//, ''); + listed.add(relPath); + const content = entries.get(relPath); + if (!content) { + problems.push(`QA report SHA256SUMS references a missing file: ${relPath}.`); + break; + } + if (sha256Hex(content) !== expected) { + problems.push(`QA report SHA256SUMS checksum mismatch for ${relPath}.`); + break; + } + } + if (!listed.has('manifest.json') || !listed.has('index.html')) { + problems.push('QA report SHA256SUMS must cover both index.html and manifest.json.'); + } + } + } + + for (const [name, content] of entries.entries()) { + if (!/\.(?:html?|json|md|txt|csv|log|js|css|svg)$/i.test(name) && name !== 'SHA256SUMS') continue; + const text = content.toString('utf8'); + for (const rule of SECRET_TEXT_PATTERNS) { + if (rule.pattern.test(text)) { + problems.push(`QA report file ${name} appears to contain unsanitized sensitive data (${rule.name}); redact secrets and re-upload.`); + break; + } + } + } + + return problems; +} + +class AttachmentDownloadError extends Error { + constructor(message, {transient = false} = {}) { + super(message); + this.transient = transient; + } +} + +async function downloadAttachmentZip(url, {maxZipBytes = config.qaReport?.maxZipBytes || 20971520, timeoutMs = config.qaReport?.fetchTimeoutMs || 15000, repo = null} = {}) { + if (!isAllowedAttachmentUrl(url, repo)) { + throw new AttachmentDownloadError('QA report link must be a GitHub PR file attachment ZIP URL (https://github.com/user-attachments/files/.../*.zip).'); + } + let current = url; + for (let redirects = 0; redirects < 6; redirects++) { + const parsed = new URL(current); + if (parsed.protocol !== 'https:' || !ALLOWED_DOWNLOAD_HOSTS.some(pattern => pattern.test(parsed.hostname))) { + throw new AttachmentDownloadError(`QA report redirect target host is not allowed: ${parsed.hostname}.`); + } + const controller = new AbortController(); + const timer = setTimeout(() => controller.abort(), timeoutMs); + let response; + try { + response = await fetch(current, {redirect: 'manual', signal: controller.signal, headers: {'User-Agent': 'panwatch-pr-policy'}}); + } catch (error) { + clearTimeout(timer); + throw new AttachmentDownloadError(`Failed to fetch QA report ZIP: ${error.message}`, {transient: true}); + } + if (response.status >= 300 && response.status < 400) { + clearTimeout(timer); + const location = response.headers.get('location'); + if (!location) throw new AttachmentDownloadError('QA report attachment returned a redirect without a Location header.'); + current = new URL(location, current).toString(); + continue; + } + if (response.status >= 500) { + clearTimeout(timer); + throw new AttachmentDownloadError(`GitHub attachment host returned HTTP ${response.status}.`, {transient: true}); + } + if (!response.ok) { + clearTimeout(timer); + throw new AttachmentDownloadError(`QA report ZIP is not accessible (HTTP ${response.status}); upload the ZIP to this PR so it is publicly downloadable.`); + } + const contentLength = Number(response.headers.get('content-length') || 0); + if (contentLength > maxZipBytes) { + clearTimeout(timer); + throw new AttachmentDownloadError(`QA report ZIP exceeds the maximum size (${maxZipBytes} bytes).`); + } + const chunks = []; + let total = 0; + try { + for await (const chunk of response.body) { + const buf = Buffer.from(chunk); + total += buf.length; + if (total > maxZipBytes) { + throw new AttachmentDownloadError(`QA report ZIP exceeds the maximum size (${maxZipBytes} bytes).`); + } + chunks.push(buf); + } + } catch (error) { + clearTimeout(timer); + if (error instanceof AttachmentDownloadError) throw error; + throw new AttachmentDownloadError(`Interrupted while downloading QA report ZIP: ${error.message}`, {transient: true}); + } + clearTimeout(timer); + return Buffer.concat(chunks); + } + throw new AttachmentDownloadError('QA report attachment exceeded maximum redirect hops.'); +} + +function evaluate(pr, files, scopeApproved = false, options = {}) { if (pr.changed_files !== files.length) throw new Error(`Incomplete file list for #${pr.number}: ${files.length}/${pr.changed_files}`); const production = files.filter(file => productionFile(file.filename) || (file.previous_filename && productionFile(file.previous_filename))); const changes = production.reduce((sum, file) => sum + file.additions + file.deletions, 0); @@ -53,16 +402,51 @@ function evaluate(pr, files, scopeApproved = false) { if (!scopeApproved && (production.length > config.maxProductionFiles || changes > config.maxProductionChanges)) { problems.push(`Scope exceeds the budget: ${production.length} production files / ${changes} added+deleted lines; split into independently usable PRs or request a maintainer scope exception.`); } + + const qaConfig = options.qaConfig || config.qaReport; + const qaExemptApproved = Boolean(options.qaExemptApproved); + const qaReportRequired = isQaReportRequired(pr, production.length, qaExemptApproved, qaConfig); + const qaReport = qaReportRequired ? extractQaReport(pr.body, options.repo || null) : null; + if (qaReportRequired) { + if (!qaReport.url) { + problems.push( + qaReport.invalidUrl + ? `QA report link must be a GitHub PR attachment ZIP (https://github.com/user-attachments/files/.../*.zip); rejected external link (${qaReport.invalidUrl}).` + : 'External production PRs must run isolated QA (.agents/skills/panwatch-local-delivery) and attach the sanitized report ZIP link (https://github.com/user-attachments/files/.../*.zip) in Validation or Acceptance evidence.' + ); + } + if (!qaReport.sha256) { + problems.push('External production PRs must include "ZIP SHA256: <64-hex>" matching the attached isolated QA report ZIP.'); + } + if (Array.isArray(options.qaZipProblems) && options.qaZipProblems.length) { + problems.push(...options.qaZipProblems); + } + } + const labels = new Set(pr.labels.map(label => label.name)); if (labels.has(config.labels.needsSplit)) problems.push('A maintainer requested a scope split (pr:needs-split); ask for re-review after narrowing the PR.'); if (labels.has(config.labels.needsEvidence)) problems.push('A maintainer requested acceptance evidence (pr:needs-evidence); ask for re-review after supplying it.'); - return {problems, productionFiles: production.length, productionChanges: changes, hold: labels.has(config.labels.hold)}; + return { + problems, + productionFiles: production.length, + productionChanges: changes, + hold: labels.has(config.labels.hold), + qaReportRequired, + qaReport, + }; } -function nextState(result, previous = {}, now = new Date(), scopeSha = null) { +function nextState(result, previous = {}, now = new Date(), scopeSha = null, qaExemptSha = null) { const since = result.problems.length && !result.hold ? (previous.since || now.toISOString()) : null; const age = since ? (now - new Date(since)) / DAY : 0; - return {since, scopeSha, remindedAt: since && since === previous.since ? previous.remindedAt || null : null, reminder: age >= config.reminderDays, close: age >= config.closeDays && !result.hold}; + return { + since, + scopeSha, + qaExemptSha, + remindedAt: since && since === previous.since ? previous.remindedAt || null : null, + reminder: age >= config.reminderDays, + close: age >= config.closeDays && !result.hold, + }; } function readState(comment) { @@ -79,16 +463,16 @@ function notice(result, state, policyUrl) { const message = result.hold ? 'A maintainer has put this PR on hold. Automatic closure is paused; merge readiness is still checked.' : result.problems.length ? 'This PR needs changes before review.' : 'The mechanical PR requirements are satisfied. Product acceptance, evidence quality and code review remain maintainer decisions.'; const deadline = state.since ? new Date(Date.parse(state.since) + config.closeDays * DAY).toISOString() : null; - return [MARKER, ``, '### PanWatch contribution check', message, + return [MARKER, ``, '### PanWatch contribution check', message, `Scope: ${result.productionFiles} production files, ${result.productionChanges} added + deleted production lines. Tests, Markdown docs and known lockfiles are excluded.`, ...result.problems.map(problem => `- ${problem}`), ...(deadline ? [`${state.reminder ? '**Reminder:** ' : ''}Please resolve the items by **${deadline}** (${config.closeDays} days from the first notice). Comments and pushes do not extend this deadline. A maintainer may apply \`pr:hold\` when more time is justified; removing it grants a fresh window.`, 'If unresolved, this PR will be closed on a daily sweep. The branch is preserved; reopen or submit smaller PRs when ready. Existing PRs receive the same full notice period.'] : []), - `[Contribution policy](${policyUrl})`, '本检查只核对材料与改动规模,不代表产品或实现已经验收。首次提示后有14天整改窗口;第7天提醒,逾期仍未达标自动关闭。维护者可用 pr:hold 暂停;关闭后仍可重开或提交拆分版本。' + `[Contribution policy](${policyUrl})`, '本检查只核对材料、隔离测试报告完整性与改动规模,不代表产品或实现已经验收。首次提示后有14天整改窗口;第7天提醒,逾期仍未达标自动关闭。维护者可用 pr:hold 暂停、pr:qa-exempt 豁免隔离报告;关闭后仍可重开或提交拆分版本。' ].join('\n\n'); } -async function run({github, context, core}) { +async function run({github, context, core, fetchZip = downloadAttachmentZip}) { const mode = process.env.PR_POLICY_MODE || 'audit'; if (!['audit', 'enforce'].includes(mode)) throw new Error(`Unknown PR_POLICY_MODE: ${mode}`); const repo = context.repo; @@ -115,13 +499,37 @@ async function run({github, context, core}) { const labels = new Set(pr.labels.map(label => label.name)); const justApproved = context.payload.action === 'labeled' && context.payload.label?.name === config.labels.scopeApproved && context.payload.pull_request?.head.sha === pr.head.sha; const scopeSha = labels.has(config.labels.scopeApproved) && (justApproved || previous.scopeSha === pr.head.sha) ? pr.head.sha : null; - const result = evaluate(pr, files, Boolean(scopeSha)); + const justQaExempt = Boolean(config.labels.qaExempt) && context.payload.action === 'labeled' && context.payload.label?.name === config.labels.qaExempt && context.payload.pull_request?.head.sha === pr.head.sha; + const qaExemptSha = Boolean(config.labels.qaExempt) && labels.has(config.labels.qaExempt) && (justQaExempt || previous.qaExemptSha === pr.head.sha) ? pr.head.sha : null; + + let result = evaluate(pr, files, Boolean(scopeSha), {qaExemptApproved: Boolean(qaExemptSha), repo}); + if (result.qaReportRequired && result.qaReport?.url && result.qaReport?.sha256) { + let qaZipProblems = []; + try { + const zipBuffer = await fetchZip(result.qaReport.url, {repo}); + qaZipProblems = verifyQaReportZip(zipBuffer, { + expectedSha256: result.qaReport.sha256, + headSha: pr.head.sha, + }); + } catch (error) { + if (error instanceof AttachmentDownloadError && !error.transient) { + qaZipProblems = [error.message]; + } else { + throw error; + } + } + if (qaZipProblems.length) { + result = evaluate(pr, files, Boolean(scopeSha), {qaExemptApproved: Boolean(qaExemptSha), repo, qaZipProblems}); + } + } + const renewed = context.payload.action === 'reopened' || (context.payload.action === 'unlabeled' && context.payload.label?.name === config.labels.hold); - const state = nextState(result, renewed ? {...previous, since: null} : previous, new Date(), scopeSha); + const state = nextState(result, renewed ? {...previous, since: null} : previous, new Date(), scopeSha, qaExemptSha); summary.push(`#${pr.number}: ${result.problems.length} item(s), ${result.productionFiles} files / ${result.productionChanges} lines${state.close ? ', due for closure' : ''}`); if (!mutate) continue; - // A scope exception covers one reviewed head; a new push must be reviewed again. + // Head-bound maintainer exceptions cover one reviewed head; a new push must be reviewed again. if (labels.has(config.labels.scopeApproved) && !scopeSha) await github.rest.issues.removeLabel({...repo, issue_number: pr.number, name: config.labels.scopeApproved}); + if (config.labels.qaExempt && labels.has(config.labels.qaExempt) && !qaExemptSha) await github.rest.issues.removeLabel({...repo, issue_number: pr.number, name: config.labels.qaExempt}); if (result.problems.length && !labels.has(config.labels.needsWork)) await github.rest.issues.addLabels({...repo, issue_number: pr.number, labels: [config.labels.needsWork]}); if (!result.problems.length && labels.has(config.labels.needsWork)) await github.rest.issues.removeLabel({...repo, issue_number: pr.number, name: config.labels.needsWork}); const policyUrl = `${context.serverUrl}/${repo.owner}/${repo.repo}/blob/${pr.base.repo.default_branch}/docs/pr-policy.md`; @@ -132,7 +540,7 @@ async function run({github, context, core}) { const body = notice(result, state, policyUrl); let target = comment?.html_url || pr.html_url; if (comment && comment.body !== body) await github.rest.issues.updateComment({...repo, comment_id: comment.id, body}); - else if (!comment && (result.problems.length || scopeSha || result.hold)) { + else if (!comment && (result.problems.length || scopeSha || qaExemptSha || result.hold)) { const {data: created} = await github.rest.issues.createComment({...repo, issue_number: pr.number, body}); target = created.html_url; } @@ -143,10 +551,13 @@ async function run({github, context, core}) { // Re-fetch metadata and files before closing: never close on a stale snapshot. const {data: latest} = await github.rest.pulls.get({...repo, pull_number: pr.number}); const fingerprint = item => JSON.stringify([item.head.sha, item.base.sha, item.changed_files, item.title, item.body, item.labels.map(label => label.name).sort()]); - // The needs-work label was added above; ignore only that bot-owned label. - const withoutOwnedLabel = item => ({...item, labels: item.labels.filter(label => label.name !== config.labels.needsWork && label.name !== config.labels.scopeApproved)}); + // Bot-managed and head-bound labels changed above; ignore only those labels. + const ownedLabels = new Set([config.labels.needsWork, config.labels.scopeApproved, config.labels.qaExempt].filter(Boolean)); + const withoutOwnedLabel = item => ({...item, labels: item.labels.filter(label => !ownedLabels.has(label.name))}); if (latest.state !== 'open' || fingerprint(withoutOwnedLabel(latest)) !== fingerprint(withoutOwnedLabel(pr))) continue; - if (latest.labels.some(label => label.name === config.labels.hold) || (!scopeSha && latest.labels.some(label => label.name === config.labels.scopeApproved))) continue; + if (latest.labels.some(label => label.name === config.labels.hold) + || (!scopeSha && latest.labels.some(label => label.name === config.labels.scopeApproved)) + || (config.labels.qaExempt && !qaExemptSha && latest.labels.some(label => label.name === config.labels.qaExempt))) continue; await github.rest.issues.createComment({...repo, issue_number: pr.number, body: 'Closing after the 14-day contribution notice: the items above remain unresolved. This preserves your branch and work. Please reopen after addressing them, or submit independently usable smaller PRs.\n\n整改提示已满14天,以上事项仍未解决,因此关闭此PR。分支与改动保留;补齐验收材料后可以重开,也欢迎按独立可用的范围拆分提交。'}); await github.rest.pulls.update({...repo, pull_number: pr.number, state: 'closed'}); } @@ -155,4 +566,23 @@ async function run({github, context, core}) { await core.summary.addHeading(`PR policy: ${mode}`).addCodeBlock(summary.join('\n'), 'text').write(); } -module.exports = {config, MARKER, sections, field, productionFile, evaluate, nextState, readState, notice, run}; +module.exports = { + config, + MARKER, + sections, + field, + productionFile, + isExemptAuthor, + isQaReportRequired, + isAllowedAttachmentUrl, + extractQaReport, + parseZipEntries, + verifyQaReportZip, + AttachmentDownloadError, + downloadAttachmentZip, + evaluate, + nextState, + readState, + notice, + run, +}; diff --git a/.github/scripts/pr-policy.test.cjs b/.github/scripts/pr-policy.test.cjs index 888e1260d..ae5a244ef 100644 --- a/.github/scripts/pr-policy.test.cjs +++ b/.github/scripts/pr-policy.test.cjs @@ -1,8 +1,27 @@ 'use strict'; const test = require('node:test'); const assert = require('node:assert/strict'); -const {config, MARKER, evaluate, productionFile, nextState, readState, notice, run} = require('./pr-policy.cjs'); +const crypto = require('node:crypto'); +const zlib = require('node:zlib'); +const { + config, + MARKER, + evaluate, + productionFile, + isExemptAuthor, + isQaReportRequired, + isAllowedAttachmentUrl, + extractQaReport, + verifyQaReportZip, + AttachmentDownloadError, + nextState, + readState, + notice, + run, +} = require('./pr-policy.cjs'); + const SHA = 'a'.repeat(40); +const ATTACHMENT_URL = 'https://github.com/user-attachments/files/12345678/panwatch-qa-report.zip'; const BODY = `## Background A report action loses its selected symbol. ## Changes @@ -22,11 +41,113 @@ Evidence: Sanitized request output: symbol=SPY, market=US. Only this action changes; no migration or real notification. ## Follow-up None`; -const makePr = changes => ({number: 1, title: 'fix(reports): preserve the selected symbol', body: BODY, head: {sha: SHA}, - base: {repo: {default_branch: 'main'}}, labels: [], changed_files: 1, state: 'open', created_at: '2020-01-01T00:00:00Z', html_url: 'https://github.com/example/repo/pull/1', ...changes}); + +// Default test PR uses an exempt maintainer login so existing non-QA policy tests stay focused; +// external-contributor QA enforcement is tested explicitly with user: {login: 'external-dev'}. +const makePr = changes => ({ + number: 1, + title: 'fix(reports): preserve the selected symbol', + body: BODY, + user: {login: 'TNT-Likely'}, + head: {sha: SHA}, + base: {repo: {default_branch: 'main'}}, + labels: [], + changed_files: 1, + state: 'open', + created_at: '2020-01-01T00:00:00Z', + html_url: 'https://github.com/example/repo/pull/1', + ...changes, +}); const FILES = [{filename: 'src/report.py', additions: 10, deletions: 2}]; const NOW = new Date('2026-10-13T00:00:00Z'); +function crc32(buf) { + let crc = 0xffffffff; + for (let i = 0; i < buf.length; i++) { + crc ^= buf[i]; + for (let j = 0; j < 8; j++) crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); + } + return (crc ^ 0xffffffff) >>> 0; +} + +function buildZip(fileMap, {deflate = true} = {}) { + const locals = []; + const centrals = []; + let offset = 0; + for (const [name, raw] of Object.entries(fileMap)) { + const content = Buffer.isBuffer(raw) ? raw : Buffer.from(String(raw), 'utf8'); + const nameBuf = Buffer.from(name, 'utf8'); + const method = deflate ? 8 : 0; + const compressed = deflate ? zlib.deflateRawSync(content) : content; + const crc = crc32(content); + + const local = Buffer.alloc(30 + nameBuf.length); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); + local.writeUInt16LE(method, 8); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(compressed.length, 18); + local.writeUInt32LE(content.length, 22); + local.writeUInt16LE(nameBuf.length, 26); + nameBuf.copy(local, 30); + locals.push(local, compressed); + + const central = Buffer.alloc(46 + nameBuf.length); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(20, 4); + central.writeUInt16LE(20, 6); + central.writeUInt16LE(method, 10); + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(compressed.length, 20); + central.writeUInt32LE(content.length, 24); + central.writeUInt16LE(nameBuf.length, 28); + central.writeUInt32LE(offset, 42); + nameBuf.copy(central, 46); + centrals.push(central); + + offset += local.length + compressed.length; + } + const cdBuf = Buffer.concat(centrals); + const eocd = Buffer.alloc(22); + eocd.writeUInt32LE(0x06054b50, 0); + eocd.writeUInt16LE(centrals.length, 8); + eocd.writeUInt16LE(centrals.length, 10); + eocd.writeUInt32LE(cdBuf.length, 12); + eocd.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, cdBuf, eocd]); +} + +function sha256(buf) { + return crypto.createHash('sha256').update(buf).digest('hex'); +} + +function makeValidQaZip({headSha = SHA, skillVersion = '1.3.0', prefix = 'report/', extraFiles = {}, manifestOverrides = {}, deflate = true} = {}) { + const indexHtml = Buffer.from('

PanWatch QA Report

', 'utf8'); + const manifest = Buffer.from(JSON.stringify({ + run_id: 'run-1234', + base_sha: headSha, + skill_version: skillVersion, + summary: {passed: 4, failed: 0, skipped: 0}, + ...manifestOverrides, + }, null, 2), 'utf8'); + const entries = { + [`${prefix}index.html`]: indexHtml, + [`${prefix}manifest.json`]: manifest, + ...extraFiles, + }; + const sums = [ + `${sha256(indexHtml)} index.html`, + `${sha256(manifest)} manifest.json`, + ].join('\n') + '\n'; + entries[`${prefix}SHA256SUMS`] = Buffer.from(sums, 'utf8'); + const zip = buildZip(entries, {deflate}); + return {zip, zipSha256: sha256(zip)}; +} + +function bodyWithQaReport(zipSha256, url = ATTACHMENT_URL) { + return `${BODY.replace('## Acceptance evidence', `### Test report\n\n[Download the test report (ZIP)](${url})\n\nZIP SHA256: \`${zipSha256}\`\n\n## Acceptance evidence`)}`; +} + for (const name of ['tests/test_prices.py', 'frontend/tests/view.test.tsx', 'src/__tests__/test.py', 'README.zh-CN.md', 'docs/demo.md', 'frontend/pnpm-lock.yaml', '.github/scripts/pr-policy.test.cjs']) { test(`exclude ${name} from production budget`, () => assert.equal(productionFile(name), false)); } @@ -64,6 +185,92 @@ test('incomplete file API data fails safely', () => assert.throws(() => evaluate test('scope exception does not waive maintainer evidence requests', () => { assert.match(evaluate(makePr({labels: [{name: config.labels.needsEvidence}]}), FILES, true).problems.join(' '), /maintainer requested acceptance/); }); + +// --- Isolated QA report enforcement tests --- + +test('repository owner (TNT-Likely) PRs are automatically exempted from mandatory QA ZIP', () => { + assert.equal(isExemptAuthor({user: {login: 'TNT-Likely'}}), true); + assert.equal(isExemptAuthor({user: {login: 'tnt-likely'}}), true); + assert.equal(isExemptAuthor({user: {login: 'external-dev'}}), false); + assert.equal(isExemptAuthor({}), false); + assert.equal(isQaReportRequired(makePr({user: {login: 'TNT-Likely'}}), 1, false), false); + assert.deepEqual(evaluate(makePr({user: {login: 'TNT-Likely'}}), FILES).problems, []); +}); + +test('external docs/test-only PRs (0 production files) are automatically exempted from QA ZIP', () => { + const testOnly = [{filename: 'tests/test_evaluations_api.py', additions: 8, deletions: 2}]; + const pr = makePr({user: {login: 'external-dev'}}); + const result = evaluate(pr, testOnly); + assert.equal(result.qaReportRequired, false); + assert.deepEqual(result.problems, []); +}); + +test('external production PR without QA report ZIP link and SHA256 fails', () => { + const pr = makePr({user: {login: 'external-dev'}}); + const result = evaluate(pr, FILES); + assert.equal(result.qaReportRequired, true); + assert.match(result.problems.join('\n'), /panwatch-local-delivery/); + assert.match(result.problems.join('\n'), /ZIP SHA256/); +}); + +test('external production PR with non-GitHub ZIP URL is rejected (SSRF guard)', () => { + const {zipSha256} = makeValidQaZip(); + assert.equal(isAllowedAttachmentUrl(ATTACHMENT_URL), true); + assert.equal(isAllowedAttachmentUrl('https://evil.example.com/report.zip'), false); + assert.equal(isAllowedAttachmentUrl('http://github.com/user-attachments/files/1/r.zip'), false); + const pr = makePr({user: {login: 'external-dev'}, body: bodyWithQaReport(zipSha256, 'https://evil.example.com/report.zip')}); + const result = evaluate(pr, FILES); + assert.match(result.problems.join('\n'), /rejected external link/); +}); + +test('extractQaReport parses both panwatch-local-delivery and explicit QA report field styles', () => { + const sha = 'f'.repeat(64); + const a = extractQaReport(bodyWithQaReport(sha)); + assert.equal(a.url, ATTACHMENT_URL); + assert.equal(a.sha256, sha); + const b = extractQaReport(`${BODY}\nQA report: ${ATTACHMENT_URL}\nQA report SHA256: ${sha}\n`); + assert.equal(b.url, null); // Outside Validation / Acceptance evidence sections + const c = extractQaReport(BODY.replace('Evidence:', `QA report: ${ATTACHMENT_URL}\nQA report SHA256: ${sha}\nEvidence:`)); + assert.equal(c.url, ATTACHMENT_URL); + assert.equal(c.sha256, sha); +}); + +test('verifyQaReportZip passes for valid deflated and stored QA report archives', () => { + for (const deflate of [true, false]) { + const {zip, zipSha256} = makeValidQaZip({deflate}); + assert.deepEqual(verifyQaReportZip(zip, {expectedSha256: zipSha256, headSha: SHA}), []); + } +}); + +test('verifyQaReportZip catches SHA256 mismatch, stale head, old skill version, failing summary, tampered checksums and secrets', () => { + const {zip} = makeValidQaZip(); + assert.match(verifyQaReportZip(zip, {expectedSha256: '0'.repeat(64), headSha: SHA}).join('\n'), /SHA256 mismatch/); + + const stale = makeValidQaZip({headSha: 'b'.repeat(40)}); + assert.match(verifyQaReportZip(stale.zip, {expectedSha256: stale.zipSha256, headSha: SHA}).join('\n'), /base_sha/); + + const oldSkill = makeValidQaZip({skillVersion: '1.0.0'}); + assert.match(verifyQaReportZip(oldSkill.zip, {expectedSha256: oldSkill.zipSha256, headSha: SHA}).join('\n'), /skill_version/); + + const failedRun = makeValidQaZip({manifestOverrides: {summary: {passed: 2, failed: 1}}}); + assert.match(verifyQaReportZip(failedRun.zip, {expectedSha256: failedRun.zipSha256, headSha: SHA}).join('\n'), /failing acceptance checks/); + + const leakedFile = makeValidQaZip({extraFiles: {'report/private/credentials.json': '{"password":"secret"}'}}); + assert.match(verifyQaReportZip(leakedFile.zip, {expectedSha256: leakedFile.zipSha256, headSha: SHA}).join('\n'), /disallowed private file/); + + const leakedToken = makeValidQaZip({extraFiles: {'report/notes.txt': 'AUTH_PASSWORD=supersecret'}}); + assert.match(verifyQaReportZip(leakedToken.zip, {expectedSha256: leakedToken.zipSha256, headSha: SHA}).join('\n'), /unsanitized sensitive data/); + + const tampered = buildZip({ + 'index.html': '

Modified

', + 'manifest.json': JSON.stringify({run_id: 'r1', base_sha: SHA, skill_version: '1.3.0'}), + 'SHA256SUMS': `${'1'.repeat(64)} index.html\n${'2'.repeat(64)} manifest.json\n`, + }); + assert.match(verifyQaReportZip(tampered, {expectedSha256: sha256(tampered), headSha: SHA}).join('\n'), /checksum mismatch/); +}); + +// --- Policy workflow state & sweep tests --- + test('old PR gets a fresh full notice window', () => { const state = nextState({problems: ['missing'], hold: false}, {}, NOW); assert.equal(state.since, NOW.toISOString()); @@ -89,7 +296,7 @@ test('only the policy bot can provide persisted state', () => { assert.deepEqual(readState({user: {login: 'github-actions[bot]'}, body: `${MARKER}\n`}), {}); }); -function harness({pr = makePr(), previous = null, latest = null, files = FILES} = {}) { +function harness({pr = makePr(), previous = null, latest = null, files = FILES, fetchZip = null} = {}) { let current = structuredClone(pr); let reads = 0; let comments = previous ? [{id: 11, html_url: 'https://github.com/example/repo/pull/1#issuecomment-11', user: {login: 'github-actions[bot]'}, body: notice({problems: ['missing'], productionFiles: 1, productionChanges: 12, hold: false}, previous, 'https://example.com/policy')}] : []; @@ -106,7 +313,13 @@ function harness({pr = makePr(), previous = null, latest = null, files = FILES} repos: {createCommitStatus: write('status')} }, paginate: async (fn, args) => fn(args)}; const summary = {addHeading() {return this;}, addCodeBlock() {return this;}, async write() {}}; - return {github, context: {repo: {owner: 'example', repo: 'repo'}, serverUrl: 'https://github.com', payload: {}}, core: {info() {}, summary}, writes}; + return { + github, + context: {repo: {owner: 'example', repo: 'repo'}, serverUrl: 'https://github.com', payload: {}}, + core: {info() {}, summary}, + fetchZip: fetchZip || (async () => { throw new Error('unexpected fetchZip'); }), + writes, + }; } async function execute(h, mode = 'enforce') { const old = process.env.PR_POLICY_MODE; @@ -114,6 +327,7 @@ async function execute(h, mode = 'enforce') { try { await run(h); } finally {if (old === undefined) delete process.env.PR_POLICY_MODE; else process.env.PR_POLICY_MODE = old;} } const EXPIRED = {since: '2020-01-01T00:00:00Z', scopeSha: null}; + test('audit performs no mutations even for expired invalid PRs', async () => { const h = harness({pr: makePr({body: ''}), previous: EXPIRED}); await execute(h, 'audit'); @@ -172,6 +386,53 @@ test('a compliant PR awaiting maintainer review is kept open', async () => { assert.equal(h.writes.find(write => write.method === 'status').args.state, 'success'); }); +test('external production PR passes end-to-end when a valid QA ZIP is attached', async () => { + const {zip, zipSha256} = makeValidQaZip(); + const pr = makePr({user: {login: 'external-dev'}, body: bodyWithQaReport(zipSha256)}); + const h = harness({pr, fetchZip: async () => zip}); + await execute(h); + assert.equal(h.writes.find(write => write.method === 'status').args.state, 'success'); +}); + +test('external production PR fails when downloaded QA ZIP has a stale head SHA', async () => { + const {zip, zipSha256} = makeValidQaZip({headSha: 'c'.repeat(40)}); + const pr = makePr({user: {login: 'external-dev'}, body: bodyWithQaReport(zipSha256)}); + const h = harness({pr, fetchZip: async () => zip}); + await execute(h); + assert.equal(h.writes.find(write => write.method === 'status').args.state, 'failure'); + const comment = h.writes.find(write => write.method === 'createComment').args.body; + assert.match(comment, /base_sha/); +}); + +test('external production PR fails cleanly when ZIP attachment returns 404', async () => { + const {zipSha256} = makeValidQaZip(); + const pr = makePr({user: {login: 'external-dev'}, body: bodyWithQaReport(zipSha256)}); + const h = harness({pr, fetchZip: async () => { throw new AttachmentDownloadError('QA report ZIP is not accessible (HTTP 404)'); }}); + await execute(h); + assert.equal(h.writes.find(write => write.method === 'status').args.state, 'failure'); +}); + +test('transient attachment host outage throws without starting a closure clock', async () => { + const {zipSha256} = makeValidQaZip(); + const pr = makePr({user: {login: 'external-dev'}, body: bodyWithQaReport(zipSha256)}); + const h = harness({pr, fetchZip: async () => { throw new AttachmentDownloadError('HTTP 503', {transient: true}); }}); + await assert.rejects(() => execute(h), /HTTP 503/); + assert.equal(h.writes.some(write => write.method === 'close' || write.method === 'status'), false); +}); + +test('pr:qa-exempt label exempts an external PR for that head and is revoked on a new push', async () => { + const pr = makePr({user: {login: 'external-dev'}, labels: [{name: config.labels.qaExempt}]}); + const h1 = harness({pr}); + h1.context.payload = {action: 'labeled', label: {name: config.labels.qaExempt}, pull_request: pr}; + await execute(h1); + assert.equal(h1.writes.find(write => write.method === 'status').args.state, 'success'); + + const h2 = harness({pr, previous: {...EXPIRED, qaExemptSha: 'b'.repeat(40)}}); + await execute(h2); + assert.equal(h2.writes.some(write => write.method === 'removeLabel' && write.args.name === config.labels.qaExempt), true); + assert.equal(h2.writes.find(write => write.method === 'status').args.state, 'failure'); +}); + test('day-seven reminder is posted once and recorded in the persistent notice', async () => { const since = new Date(Date.now() - 8 * 86400000).toISOString(); for (const alreadyReminded of [false, true]) { diff --git a/docs/pr-policy.md b/docs/pr-policy.md index 42e972f3e..7ea73479a 100644 --- a/docs/pr-policy.md +++ b/docs/pr-policy.md @@ -39,6 +39,23 @@ Evidence should match the change: Full-project tests and a browser report are not mandatory for every PR. Required checks depend on the affected behavior. Private positions, secrets and credentials must be removed from evidence. +## Isolated QA report attachment + +External pull requests that modify production files (`productionFiles > 0`) must run isolated local acceptance using the repository skill `.agents/skills/panwatch-local-delivery` and attach the sanitized offline ZIP report directly to the PR (`https://github.com/user-attachments/files/.../*.zip`), along with `ZIP SHA256: <64-hex>` in `Validation` or `Acceptance evidence`. + +The `PR policy` bot performs a read-only verification of the uploaded ZIP (without executing any code inside the archive): + +- The attachment link must be a GitHub PR file attachment `.zip` URL (max 20 MB), and its SHA256 must match `ZIP SHA256`. +- The archive must contain `index.html`, `manifest.json`, and `SHA256SUMS` with valid checksums covering `index.html` and `manifest.json`. +- `manifest.json` must record `base_sha` matching the current PR head, a non-empty `run_id`, `skill_version >= 1.3.0`, and no recorded failing acceptance checks (`summary.failed == 0`). +- Private files (`credentials.json`, `.env*`, `*.db`, `*.sqlite*`, `*.pem`, `*.key`, browser storage state) and obvious unredacted secrets are rejected. + +Automatic exemptions: + +- Pull requests authored by configured repository maintainers (`qaReport.exemptAuthors` in `.github/pr-policy.json`, currently `TNT-Likely`) are exempted from the mandatory ZIP check. +- Pull requests with 0 production files (tests, Markdown documentation, or lockfiles only) are exempted. +- Maintainers can apply `pr:qa-exempt` to waive the ZIP requirement for one reviewed head on small external changes; pushing a new commit automatically revokes the label. + ## Automated notices and closure The workflow initially runs in **audit** mode: it reads PR metadata/files and logs results without writing labels, comments, statuses or closing PRs. Maintainers activate enforcement separately. @@ -62,6 +79,7 @@ Maintainer labels: | `pr:needs-split` | Human scope decision; blocks readiness until a maintainer clears it | | `pr:needs-evidence` | Human evidence-quality decision; blocks readiness until cleared | | `pr:scope-approved` | Size exception for one reviewed head; not an evidence waiver | +| `pr:qa-exempt` | Waives the isolated QA report ZIP requirement for one reviewed head on external PRs | | `pr:hold` | Pauses automatic closure, clears the deadline and keeps readiness pending; removing it starts a fresh window if still noncompliant | Authors should ask for re-review after addressing human requests. Maintainers can use a hold while that re-review is pending; an unchanged blocking label remains an unmet requirement. diff --git a/docs/pr-policy.zh-CN.md b/docs/pr-policy.zh-CN.md index 8eff86e15..c647f53fb 100644 --- a/docs/pr-policy.zh-CN.md +++ b/docs/pr-policy.zh-CN.md @@ -39,6 +39,23 @@ Acceptance evidence 包含 `Steps:`、`Expected:`、`Observed:`、`Evidence:`。 每个 PR 不必都跑完整项目测试或提交浏览器报告,检查范围与变更匹配即可。材料必须移除个人持仓、密钥与凭据。 +## 隔离验收测试报告附件 + +凡是修改生产代码(生产文件数 `> 0`)的**外部贡献者 PR**,必须使用仓库技能 `.agents/skills/panwatch-local-delivery` 执行隔离验收,将脱敏后的离线报告 ZIP 上传为当前 PR 附件(`https://github.com/user-attachments/files/.../*.zip`),并在 `Validation` 或 `Acceptance evidence` 中附上下载链接与 `ZIP SHA256: <64位哈希>`。 + +`PR policy` 机器人会对附件 ZIP 执行**纯只读校验**(不执行包内任何代码): + +- 链接必须为 GitHub PR 附件 `.zip`(上限 20 MB),且实际字节 SHA256 必须与正文 `ZIP SHA256` 一致; +- 包内必须包含非空 `index.html`、`manifest.json` 和 `SHA256SUMS`,且 `SHA256SUMS` 覆盖 `index.html` 与 `manifest.json` 并全部校验通过; +- `manifest.json` 必须包含匹配当前 PR head 的 `base_sha`、非空 `run_id`、`skill_version >= 1.3.0`,且不存在失败项(`summary.failed == 0`); +- 自动拒绝夹带私密文件(`credentials.json`、`.env*`、`*.db`、`*.sqlite*`、`*.pem`、`*.key`、浏览器 storage state)或明显未脱敏密钥的压缩包。 + +自动豁免规则: + +- 仓库维护者本人的 PR(在 `.github/pr-policy.json` 的 `qaReport.exemptAuthors` 中配置,默认 `TNT-Likely`)自动豁免,无需强制上传 ZIP; +- 生产文件数为 0 的 PR(纯测试、纯 Markdown 文档或 lockfile)自动豁免; +- 维护者可为小范围外部 PR 添加 `pr:qa-exempt` 标签豁免当前 head 的报告要求;新推送后标签自动失效。 + ## 自动提示与关闭 工作流初始为 **audit 只读模式**:只读取元数据和文件、输出检查结果,不写标签、评论或状态,不关闭 PR。由维护者单独启用 enforce。 @@ -62,6 +79,7 @@ Acceptance evidence 包含 `Steps:`、`Expected:`、`Observed:`、`Evidence:`。 | `pr:needs-split` | 人工认定需要收窄;维护者移除前阻止验收通过 | | `pr:needs-evidence` | 人工认定证据不足;移除前阻止通过 | | `pr:scope-approved` | 当前已审阅 head 的规模例外,不豁免证据 | +| `pr:qa-exempt` | 为外部 PR 当前已审阅 head 豁免隔离验收报告 ZIP 要求 | | `pr:hold` | 暂停自动关闭、清除截止时间,合入状态保持 pending;移除后若仍未达标,重新给宽限期 | 作者补齐人工要求后应申请复审;复审等待期间维护者可以用 hold 暂停。未移除的人工阻塞标签仍视为尚未达标。