diff --git a/.github/agent/risk-rules.json b/.github/agent/risk-rules.json new file mode 100644 index 000000000..c3f0dbfb5 --- /dev/null +++ b/.github/agent/risk-rules.json @@ -0,0 +1,80 @@ +{ + "version": 2, + "note": "Report only: these rules give a pull request a tier (issue #3393). Nothing reads them yet to block, label or merge; T3 needs a human, and the final merge policy is decided in stage 5 of #3393. Editing this file is itself T3 (`.github/**`). Paths are matched in the fixed order T3 -> T2 -> T1 -> T0, first match wins, so a broader lower tier never shadows a narrower higher one: keep the lists non-overlapping when they cover the same directory.", + "tiers": { + "T3": { + "meaning": "high risk: the automation itself, the vendored upstream, dependency and deploy manifests, secrets and auth code. Green CI is not enough; a human approves.", + "paths": [ + ".github/**", + "scripts/**", + "deploy/**", + "runtime/ds-bot-upstream/**", + "runtime/third_party/**", + "**/package.json", + "**/package-lock.json", + "**/Dockerfile", + "**/Dockerfile.*", + "**/docker-compose*.yml", + "**/*.compose.yml", + "**/*.env.example", + "LICENSE", + "NOTICE", + "SECURITY.md", + "flybot_workspace/{oidc,security,skill_secrets,invites,members,model_http_policy,fake_oidc}.py", + "services/bot-social/src/{oauth,crypto,custody,owner-mcp,auth-limit,load-env,local-room-invites}.ts" + ], + "codeExt": "\\.(js|mjs|cjs|ts|jsx|tsx|py|sh|yml|yaml|json|html|css)$", + "diffPatterns": [ + "\\bchild_process\\b", + "\\beval\\(", + "new Function\\(", + "\\bexec(Sync)?\\(['\"]", + "\\bos\\.system\\(|\\bsubprocess\\.(run|call|Popen|check_output)", + "process\\.env\\.[A-Za-z_]*(TOKEN|KEY|SECRET)", + "os\\.environ(\\.get)?[\\[(][^\\n]{0,60}(TOKEN|KEY|SECRET)", + "\\.dsh(?![-\\w])|DSH_HOME", + "\\.(only|skip)\\(", + "@unittest\\.skip|pytest\\.mark\\.(skip|xfail)", + "(eslint|oxlint)-disable|#\\s*noqa\\b" + ], + "diffPatternsNotInTests": [ + "https?://(?!(localhost|127\\.0\\.0\\.1|example\\.(com|org)|github\\.com/(ThinkFlowLab|Birfy)|raw\\.githubusercontent\\.com/(ThinkFlowLab|Birfy)|registry\\.npmjs\\.org))", + "untrusted-(message|file)|\\bfence|sanitiz|displayName|display name" + ], + "testPaths": ["tests/**", "**/test/**", "**/tests/**", "**/*.test.{js,mjs,cjs,ts,jsx,tsx}", "**/test_*.py", "**/*_test.py"], + "topics": [] + }, + "T2": { + "meaning": "medium risk: service, runtime and manager code, and any path no rule names (never silently T0/T1).", + "paths": [ + "services/**", + "manager/**", + "runtime/flybot/**", + "runtime/flybot-image/**", + "runtime/flybot-web-slots/**", + "runtime/flybot-social-host/**", + "flybot_workspace/*.py", + "flybot_workspace/manager/**", + "flybot_workspace/dsbot_routes.json" + ] + }, + "T1": { + "meaning": "low risk: client code, tests and the checked-in static pages.", + "paths": [ + "runtime/flybot-workspace-web/**", + "flybot_workspace/static/**", + "tests/**", + "**/*.test.{js,mjs,cjs,ts,jsx,tsx,py}" + ] + }, + "T0": { + "meaning": "lowest risk: documentation.", + "paths": ["docs/**", "**/*.md"] + } + }, + "unknownPathTier": "T2", + "generatedPaths": ["runtime/ds-bot-upstream/ds-bot/client.js"], + "generatedPathsNote": "The built browser half of the vendored ds-bot (3.2 MB, `Generated from src/client ... Do not edit by hand`); it is inside the vendor tree and so T3 by path anyway, this only keeps the size count honest. In the old layout the same file was `core/client.js`.", + "limitsNote": "Recomputed for the 0.3.0 tree. Sample of six changes in the new layout (five merged, one open): #3390 5L/1F, #3389 54L/5F, #3386 280L/11F, #3391 386L/13F, #3382 633L/7F, #3388 1128L/14F. The old caps (T0 300/15, T1 400/20, T2 250/12) were sized for the pre-0.3.0 layout, where the largest such change was under 400 lines; here the largest real UI change is #3388 at 1128L/14F, which the old T1 cap would have called T3. So: T2 keeps #3382 (633L/7F) and #3391 (386L/13F) at T2 with margin; T1 keeps #3388 at T1; T0 doubles the docs budget for a full doc rewrite. Going over a cap still means T3 (a human looks), which is the safe direction; T3 has no cap of its own.", + "limits": {"T0": {"lines": 600, "files": 20}, "T1": {"lines": 1200, "files": 20}, "T2": {"lines": 800, "files": 15}} +} diff --git a/.github/scripts/risk-gate-api.test.mjs b/.github/scripts/risk-gate-api.test.mjs new file mode 100644 index 000000000..26285565a --- /dev/null +++ b/.github/scripts/risk-gate-api.test.mjs @@ -0,0 +1,94 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { prFiles, mergedPrs, request, DEFAULT_REPO } from './risk-gate.mjs' + +// --- GitHub REST layer, without a network and without a token ------------------------------ +const reply = (body, { status = 200, link = null, remaining = '55' } = {}) => ({ + ok: status >= 200 && status < 300, + status, + statusText: status === 200 ? 'OK' : 'Error', + headers: { + get: (k) => { + const key = k.toLowerCase() + if (key === 'link') return link + if (key === 'x-ratelimit-remaining') return remaining + return null + }, + }, + json: async () => body, + text: async () => JSON.stringify(body), +}) +const withFetch = async (stub, fn) => { + const real = globalThis.fetch + const calls = [] + globalThis.fetch = async (url, init) => { + calls.push({ url: String(url), init }) + return stub(String(url), calls.length) + } + try { await fn(calls) } finally { globalThis.fetch = real } +} + +test('prFiles: reads the API anonymously, with no authorization header', async () => { + const saved = { GITHUB_TOKEN: process.env.GITHUB_TOKEN, GH_TOKEN: process.env.GH_TOKEN, GITHUB_API_URL: process.env.GITHUB_API_URL } + delete process.env.GITHUB_TOKEN + delete process.env.GH_TOKEN + delete process.env.GITHUB_API_URL + try { + await withFetch(() => reply([{ filename: 'docs/a.md' }]), async (calls) => { + assert.deepEqual(await prFiles(DEFAULT_REPO, 3382), [{ filename: 'docs/a.md' }]) + assert.equal(calls.length, 1) + assert.equal(calls[0].url, `https://api.github.com/repos/${DEFAULT_REPO}/pulls/3382/files?per_page=100`) + assert.equal(calls[0].init.headers.authorization, undefined, 'no token, no authorization header') + }) + } finally { + for (const [k, v] of Object.entries(saved)) if (v === undefined) delete process.env[k]; else process.env[k] = v + } +}) + +test('prFiles: sends a token when one is set, and follows the Link header to the next page', async () => { + const saved = process.env.GITHUB_TOKEN + process.env.GITHUB_TOKEN = 'test-token' + try { + const next = 'https://api.github.com/repos/o/r/pulls/3112/files?per_page=100&page=2' + await withFetch((url) => (url.includes('page=2') + ? reply([{ filename: 'docs/b.md' }]) + : reply([{ filename: 'docs/a.md' }], { link: `<${next}>; rel="next", <${next}>; rel="last"` })), + async (calls) => { + assert.deepEqual(await prFiles('o/r', 3112), [{ filename: 'docs/a.md' }, { filename: 'docs/b.md' }]) + assert.equal(calls.length, 2) + assert.equal(calls[0].init.headers.authorization, 'Bearer test-token') + assert.equal(calls[1].url, next) + }) + } finally { + if (saved === undefined) delete process.env.GITHUB_TOKEN; else process.env.GITHUB_TOKEN = saved + } +}) + +test('request: a spent anonymous quota is named in the error, not just a status code', async () => { + await withFetch(() => reply({ message: 'API rate limit exceeded' }, { status: 403, remaining: '0' }), async () => { + await assert.rejects(() => request('/repos/o/r/pulls/1/files'), (e) => { + assert.match(e.message, /403/) + assert.match(e.message, /quota spent/) + assert.match(e.message, /GH_TOKEN/) + return true + }) + }) +}) + +test('mergedPrs: keeps merged PRs only (closed-but-unmerged is not a replay sample)', async () => { + await withFetch(() => reply([ + { number: 7, title: 'merged one', merged_at: '2026-11-26T00:00:00Z' }, + { number: 8, title: 'closed unmerged', merged_at: null }, + ]), async () => { + assert.deepEqual(await mergedPrs(DEFAULT_REPO, 5), [{ number: 7, title: 'merged one' }]) + }) +}) + +// The script runs with no token and no `gh`: the acceptance command is +// `node .github/scripts/risk-gate.mjs --pr 3382`, so it must not shell out or require one. +test('the script needs no gh binary and no token to run', () => { + const src = readFileSync(new URL('./risk-gate.mjs', import.meta.url), 'utf8') + assert.doesNotMatch(src, /child_process/, 'no gh/exec dependency') + assert.doesNotMatch(src, /secrets\.|GITHUB_TOKEN\)?\s*\?\?/, 'no token requirement') +}) diff --git a/.github/scripts/risk-gate-judge.test.mjs b/.github/scripts/risk-gate-judge.test.mjs new file mode 100644 index 000000000..22184448a --- /dev/null +++ b/.github/scripts/risk-gate-judge.test.mjs @@ -0,0 +1,100 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { render, summaryLine } from './risk-gate.mjs' +import { gate, file, meaning, rules } from './risk-gate.fixtures.mjs' + +test('judge: removed lines and prose are not content hits', () => { + const removed = { ...file('runtime/flybot/plugins/social/src/a.js'), patch: '@@ -1 +1 @@\n-eval(x)\n+ok' } + assert.equal(gate.judge([removed]).tier, 'T2') + assert.equal(gate.judge([file('docs/a.md', ['+see https://evil.example.net and eval(x)'])]).tier, 'T0') +}) + +test('judge: allowed URL hosts are not hits; tests may quote URLs and fences', () => { + assert.equal(gate.judge([file('runtime/flybot/plugins/social/src/a.js', ["+fetch('http://localhost:3000/x')"])]).tier, 'T2') + assert.equal(gate.judge([file('runtime/flybot/plugins/social/src/a.js', ['+// https://github.com/ThinkFlowLab/FlyBot/issues/1'])]).tier, 'T2') + assert.equal(gate.judge([file('runtime/flybot/plugins/social/test/a.test.js', ["+const u = 'https://evil.example.net'", '+const fence = 1'])]).tier, 'T2') + // ...but test-only red flags still count in tests + assert.equal(gate.judge([file('runtime/flybot/plugins/social/test/a.test.js', ["+it.skip('x', () => {})"])]).tier, 'T3') +}) + +test('judge: a diff that cannot be read is T3; generated files are exempt', () => { + const noPatch = { filename: 'runtime/flybot/plugins/social/src/big.js', status: 'modified', additions: 900, deletions: 0, changes: 900 } + assert.equal(gate.judge([noPatch]).tier, 'T3') + const generated = { filename: 'runtime/ds-bot-upstream/ds-bot/client.js', status: 'modified', additions: 90000, deletions: 5, changes: 90005 } + const r = gate.judge([generated, file('runtime/flybot/plugins/social/src/a.js')]) + // The bundle sits in the vendor tree, so the path rule alone makes this T3; the exemption is + // about counting (90000 lines of generated output must not trip a size cap) and about not + // scanning a 3.2 MB build product for red flags. + assert.equal(r.tier, 'T3') + assert.equal(r.lines, 1) + assert.equal(r.generated, 1) + assert.doesNotMatch(r.why.join('\n'), /size /) +}) + +test('judge: size caps use the tier reached so far', () => { + const many = (n) => Array.from({ length: n }, (_, i) => file(`docs/f${i}.md`, ['+x'])) + assert.equal(gate.judge(many(20)).tier, 'T0') + assert.equal(gate.judge(many(21)).tier, 'T3') + assert.equal(gate.judge([file('docs/a.md', Array.from({ length: 600 }, () => '+x'))]).tier, 'T0') + assert.equal(gate.judge([file('docs/a.md', Array.from({ length: 601 }, () => '+x'))]).tier, 'T3') + // T3 by path has no size limit of its own + const t3 = gate.judge([file('scripts/big.mjs', Array.from({ length: 5000 }, () => '+x'))]) + assert.equal(t3.tier, 'T3') + assert.doesNotMatch(t3.why.join('\n'), /size /) +}) + +test('judge: a file list that may be truncated is T3', () => { + assert.equal(gate.judge([file('docs/a.md')], { truncated: true }).tier, 'T3') + assert.equal(gate.judge(Array.from({ length: 3000 }, (_, i) => file(`docs/f${i}.md`))).tier, 'T3') +}) + +test('judge: no files is T0', () => { + assert.equal(gate.judge([]).tier, 'T0') +}) + +test('render: names the tier, the reasons, and says it is report only', () => { + const text = render(gate.judge([file('NOTICE')]), meaning) + assert.match(text, /Risk tier: T3/) + assert.match(text, /path NOTICE/) + assert.match(text, /does not block, label or merge/) + assert.match(text, /risk-rules\.json/) +}) + +test('render: a T2 verdict is quotable too, not only a T3 hit', () => { + const text = render(gate.judge([file('services/bot-social/src/social.ts')]), meaning) + assert.match(text, /Risk tier: T2/) + assert.match(text, /services\/bot-social\/src\/social\.ts \(T2\)/) +}) + +test('summaryLine: one machine-readable line with the tier and the paths that set it', () => { + const r = gate.judge([file('NOTICE'), file('services/bot-social/src/oauth.ts')]) + assert.equal(summaryLine(r), 'risk-tier: T3; basis: NOTICE=T3, services/bot-social/src/oauth.ts=T3') +}) + +test('summaryLine: highest tier first, and a long basis is capped', () => { + const files = Array.from({ length: 12 }, (_, i) => file(`services/bot-social/src/p${i}.ts`)) + const line = summaryLine(gate.judge([...files, file('docs/x.md')])) + assert.match(line, /^risk-tier: T2; basis: /) + assert.match(line, /\+3 more$/) +}) + +test('summaryLine: no changed files says so instead of listing nothing', () => { + assert.equal(summaryLine(gate.judge([])), 'risk-tier: T0; basis: none (no changed files)') +}) + +test('render: the machine-readable line is the last line of the report', () => { + const r = gate.judge([file('NOTICE'), file('flybot_workspace/server.py')]) + assert.equal(render(r, meaning).trimEnd().split('\n').at(-1), summaryLine(r)) +}) + +test('rules file is consistent', () => { + for (const t of ['T0', 'T1', 'T2', 'T3']) assert.ok(rules.tiers[t].meaning && rules.tiers[t].paths.length, t) + assert.ok(['T2', 'T3'].includes(rules.unknownPathTier), 'unknown paths must not default below T2') + for (const p of [...rules.tiers.T3.diffPatterns, ...rules.tiers.T3.diffPatternsNotInTests]) new RegExp(p) + for (const [t, lim] of Object.entries(rules.limits)) { + assert.ok(rules.tiers[t], `limits name an existing tier: ${t}`) + assert.ok(lim.lines > 0 && lim.files > 0, t) + } + assert.equal(rules.limits.T3, undefined, 'T3 is the top tier: no cap of its own') + assert.ok(rules.limitsNote && rules.limitsNote.length > 100, 'a recomputed cap carries its reason') +}) diff --git a/.github/scripts/risk-gate.fixtures.mjs b/.github/scripts/risk-gate.fixtures.mjs new file mode 100644 index 000000000..ad6e35434 --- /dev/null +++ b/.github/scripts/risk-gate.fixtures.mjs @@ -0,0 +1,12 @@ +// Shared set-up for the risk-gate tests: the rules as they ship, the gate built from them, and a +// changed file shaped like the pull request files API returns it. Not a test file. +import { createGate, loadRules } from './risk-gate.mjs' + +export const rules = loadRules(new URL('../agent/risk-rules.json', import.meta.url)) +export const gate = createGate(rules) +export const meaning = Object.fromEntries(Object.entries(rules.tiers).map(([t, d]) => [t, d.meaning])) +// A changed file as GET /pulls/{n}/files returns it. +export const file = (filename, patchLines = ['+x'], extra = {}) => ({ + filename, status: 'modified', additions: patchLines.length, deletions: 0, changes: patchLines.length, + patch: '@@ -1 +1 @@\n' + patchLines.join('\n'), ...extra, +}) diff --git a/.github/scripts/risk-gate.mjs b/.github/scripts/risk-gate.mjs new file mode 100644 index 000000000..26f8f72cc --- /dev/null +++ b/.github/scripts/risk-gate.mjs @@ -0,0 +1,116 @@ +// Risk tier of a pull request (report only; rules: .github/agent/risk-rules.json, issue #3393). +// +// node .github/scripts/risk-gate.mjs --pr 12 # anonymous read: no token needed +// GH_TOKEN=... node .github/scripts/risk-gate.mjs --pr 12 # same, with a token (spares the shared quota) +// node .github/scripts/risk-gate.mjs --replay 30 # tiers of the last N merged PRs +// PR=12 GITHUB_REPOSITORY=owner/repo node .github/scripts/risk-gate.mjs # what a workflow passes +// +// The PR is read only through the GitHub REST API (the list of changed files and their patches); no +// PR code is checked out or run. The rules engine (paths, tiers, report) is risk-tier.mjs; this file +// reads the PR and prints. It exits 0 with a tier and 1 only when it could not compute one. +import { appendFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { ORDER, createGate, loadRules, render } from './risk-tier.mjs' + +// Re-exported so the engine and the command can be imported from one place. +export * from './risk-tier.mjs' + +export const DEFAULT_REPO = 'ThinkFlowLab/FlyBot' // so `--pr N` works with no other set-up +const MAX_PAGES = 100 // a runaway Link header must not spin forever + +// `fetch` is global since node 18, so no dependency and no `gh` binary is needed. A token is used +// when the environment has one (fewer failures on a shared anonymous quota), never required. +const apiBase = () => (process.env.GITHUB_API_URL || 'https://api.github.com').replace(/\/+$/, '') +const authToken = () => process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '' + +// `[link]` header -> the next absolute URL, or undefined. +function nextLink(link) { + for (const part of String(link || '').split(',')) { + const m = part.match(/<([^>]+)>\s*;\s*rel="?next"?/) + if (m) return m[1] + } + return undefined +} + +export async function request(path) { + const url = /^https?:/.test(path) ? path : apiBase() + path + const headers = { accept: 'application/vnd.github+json', 'user-agent': 'flybot-risk-gate' } + const token = authToken() + if (token) headers.authorization = `Bearer ${token}` + const res = await fetch(url, { headers }) + if (!res.ok) { + const left = res.headers.get('x-ratelimit-remaining') + const hint = left === '0' + ? ` (anonymous API quota spent; resets at ${new Date(Number(res.headers.get('x-ratelimit-reset')) * 1000).toISOString()} - set GH_TOKEN to use your own)` + : '' + const body = (await res.text()).slice(0, 200).replace(/\s+/g, ' ') + throw new Error(`GET ${url} -> ${res.status} ${res.statusText}${hint}${body ? `: ${body}` : ''}`) + } + return { body: await res.json(), next: nextLink(res.headers.get('link')) } +} + +export async function list(path) { + const out = [] + let next = path + for (let page = 0; next && page < MAX_PAGES; page++) { + const r = await request(next) + out.push(...r.body) + next = r.next + } + return out +} + +export const prFiles = (repo, n) => list(`/repos/${repo}/pulls/${n}/files?per_page=100`) + +// The last N merged PRs: closed PRs by recency, filtered on merged_at (a closed-but-unmerged PR is +// not a replay sample). `gh pr list --state merged` is gone with the gh dependency. +export async function mergedPrs(repo, n) { + const out = [] + let next = `/repos/${repo}/pulls?state=closed&per_page=100&sort=updated&direction=desc` + for (let page = 0; next && page < MAX_PAGES && out.length < n; page++) { + const r = await request(next) + for (const pr of r.body) if (pr.merged_at) out.push({ number: pr.number, title: pr.title || '' }) + next = r.next + } + return out.slice(0, n) +} + +function arg(name) { + const i = process.argv.indexOf(name) + return i > 0 ? process.argv[i + 1] : undefined +} + +async function main() { + const rulesPath = arg('--rules') || process.env.RISK_RULES || fileURLToPath(new URL('../agent/risk-rules.json', import.meta.url)) + const rules = loadRules(rulesPath) + const gate = createGate(rules) + const meaning = Object.fromEntries(Object.entries(rules.tiers).map(([t, d]) => [t, d.meaning])) + const repo = arg('--repo') || process.env.GH_REPO || process.env.GITHUB_REPOSITORY || DEFAULT_REPO + + if (arg('--replay')) { + const n = Number(arg('--replay')) + const prs = await mergedPrs(repo, n) + const dist = Object.fromEntries(ORDER.map((t) => [t, 0])) + for (const pr of prs.sort((a, b) => a.number - b.number)) { + const r = gate.judge(await prFiles(repo, pr.number)) + dist[r.tier]++ + console.log(`#${pr.number}\t${r.tier}\t${r.lines}L/${r.files}F\t${pr.title.slice(0, 60)}\n\t${r.why.slice(0, 4).join(' | ')}`) + } + console.log(`\nDistribution over ${prs.length} merged PRs: ` + ORDER.map((t) => `${t} ${dist[t]}`).join(', ')) + return + } + + const pr = arg('--pr') || process.env.PR + if (!pr) throw new Error('set PR or pass --pr N (or --replay N)') + const r = gate.judge(await prFiles(repo, pr)) + const text = render(r, meaning) + // The console line keeps the reason even when no T3 rule fired, so a T1/T2 verdict is quotable. + const why = r.why.length ? r.why : r.basis.filter((b) => b.tier === r.tier).slice(0, 5).map((b) => `${b.path}=${b.tier}`) + console.log(`risk-gate (report only): PR #${pr} tier ${r.tier}${why.length ? '; ' + why.join('; ') : ''}`) + if (process.env.GITHUB_STEP_SUMMARY) appendFileSync(process.env.GITHUB_STEP_SUMMARY, text + '\n') + else console.log('\n' + text) +} + +if (process.argv[1] === fileURLToPath(import.meta.url)) { + main().catch((e) => { console.error(`risk-gate: ${e.message}`); process.exit(1) }) +} diff --git a/.github/scripts/risk-gate.test.mjs b/.github/scripts/risk-gate.test.mjs new file mode 100644 index 000000000..d91787a65 --- /dev/null +++ b/.github/scripts/risk-gate.test.mjs @@ -0,0 +1,94 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { createGate, globToRe } from './risk-gate.mjs' +import { gate, file, rules } from './risk-gate.fixtures.mjs' + +test('globToRe: ** crosses directories, * does not, **/ may match zero directories', () => { + assert.ok(globToRe('docs/**').test('docs/a/b.md')) + assert.ok(!globToRe('docs/*').test('docs/a/b.md')) + assert.ok(globToRe('**/package.json').test('package.json')) + assert.ok(globToRe('**/package.json').test('core/package.json')) + assert.ok(!globToRe('**/package.json').test('core/not-package.json')) + assert.ok(!globToRe('services/*/test/**').test('services/a/b/test/x.js')) + assert.ok(globToRe('flybot_workspace/{oidc,security}.py').test('flybot_workspace/security.py')) + assert.ok(!globToRe('flybot_workspace/{oidc,security}.py').test('flybot_workspace/securityX.py')) + assert.ok(!globToRe('NOTICE').test('NOTICEx'), 'no wildcard means a literal path') + assert.ok(globToRe('.github/**').test('.github/workflows/tests.yml')) +}) + +test('tierOf: highest matching tier wins; an unnamed path is T2, never T0/T1', () => { + assert.equal(gate.tierOf('docs/ARCHITECTURE.md'), 'T0') + assert.equal(gate.tierOf('README.md'), 'T0') + assert.equal(gate.tierOf('tests/test_shell_page.py'), 'T1') + assert.equal(gate.tierOf('flybot_workspace/static/agents/app.mjs'), 'T1') + assert.equal(gate.tierOf('runtime/flybot-workspace-web/index.js'), 'T1') + assert.equal(gate.tierOf('flybot_workspace/server.py'), 'T2') + assert.equal(gate.tierOf('runtime/flybot/plugins/social/client.js'), 'T2') + assert.equal(gate.tierOf('services/bot-social/src/social.ts'), 'T2') + // services/** is T2 as a whole: a test under it stays T2, not T1 (T2 is checked first) + assert.equal(gate.tierOf('services/bot-social/test/a.test.ts'), 'T2') + assert.equal(gate.tierOf('.github/workflows/tests.yml'), 'T3') + assert.equal(gate.tierOf('scripts/ds-bot-upstream.mjs'), 'T3') + assert.equal(gate.tierOf('deploy/isolated/bot-social.compose.yml'), 'T3') + assert.equal(gate.tierOf('runtime/ds-bot-upstream/ds-bot/src/host/schedules.js'), 'T3') + assert.equal(gate.tierOf('services/bot-social/src/oauth.ts'), 'T3') + assert.equal(gate.tierOf('flybot_workspace/security.py'), 'T3') + assert.equal(gate.tierOf('services/bot-social/package.json'), 'T3') + assert.equal(gate.tierOf('brand-new-dir/file.txt'), 'T2') +}) + +test('judge: tier is the maximum over files', () => { + assert.equal(gate.judge([file('docs/a.md'), file('README.md')]).tier, 'T0') + assert.equal(gate.judge([file('docs/a.md'), file('tests/test_a.py')]).tier, 'T1') + assert.equal(gate.judge([file('tests/test_a.py'), file('flybot_workspace/server.py')]).tier, 'T2') + assert.equal(gate.judge([file('docs/a.md'), file('NOTICE')]).tier, 'T3') +}) + +test('judge: moving a file out of a T3 path is still T3 (old path counts)', () => { + const r = gate.judge([file('runtime/flybot/host/moved.ts', ['+x'], { status: 'renamed', previous_filename: 'services/bot-social/src/oauth.ts' })]) + assert.equal(r.tier, 'T3') + assert.match(r.why.join(), /oauth\.ts/) +}) + +test('judge: content hits in added lines of code raise to T3', () => { + const risky = { + child_process: "+import { exec } from 'node:child_process'", + eval: '+eval(input)', + secret: '+const t = process.env.GITHUB_TOKEN', + only: "+test.only('x', () => {})", + lint: '+// oxlint-disable-next-line', + url: "+fetch('https://evil.example.net/x')", + fence: '+const fenced = sanitizeName(x)', + } + for (const [name, line] of Object.entries(risky)) { + assert.equal(gate.judge([file('runtime/flybot/plugins/social/src/a.js', [line])]).tier, 'T3', name) + } + // The tree is mostly Python now, so the same red flags are read in .py code too. + const python = { + subprocess: '+proc = subprocess.run(cmd, check=True)', + environ: "+token = os.environ['GITHUB_TOKEN']", + noqa: '+x = 1 # noqa: E501', + pytest_skip: '+@pytest.mark.skip(reason="later")', + url: "+BASE = 'https://evil.example.net/x'", + } + for (const [name, line] of Object.entries(python)) { + assert.equal(gate.judge([file('flybot_workspace/agent_helper.py', [line])]).tier, 'T3', name) + } +}) + +test('#679: a topic counts on the registration line, not on a line that names the tool', () => { + // The rule survives the port even though no tool in this tree registers a topic yet (`topics` is + // empty): a plain substring match made any mention of a tool a T3 PR, so the narrow form is kept + // under test on a rules copy that has one. + const withTopic = createGate({ ...rules, tiers: { ...rules.tiers, T3: { ...rules.tiers.T3, topics: ['create_child_bot'] } } }) + const named = withTopic.judge([ + file('runtime/flybot/plugins/social/src/prompt.js', ["+ 'Use create_child_bot to add a child Bot under yourself.',"]), + file('runtime/flybot/plugins/social/src/social.js', ['+ adoptUnattached(root)']), + ]) + assert.equal(named.tier, 'T2', 'naming the tool in prose must not raise the tier') + assert.doesNotMatch(named.why.join('\n'), /topic create_child_bot/) + // The positive control, so the rule is narrowed rather than switched off. + const registered = withTopic.judge([file('runtime/flybot/plugins/social/src/tools.js', ["+ name: 'create_child_bot',"])]) + assert.equal(registered.tier, 'T3') + assert.match(registered.why.join('\n'), /runtime\/flybot\/plugins\/social\/src\/tools\.js: topic create_child_bot/) +}) diff --git a/.github/scripts/risk-tier.mjs b/.github/scripts/risk-tier.mjs new file mode 100644 index 000000000..8766c30d5 --- /dev/null +++ b/.github/scripts/risk-tier.mjs @@ -0,0 +1,131 @@ +// Risk tier rules engine (report only; rules: .github/agent/risk-rules.json, issue #3393). +// +// Pure functions over the rules file and the list of files a pull request changed: no network, no +// `gh`, no process exit. The command that reads a pull request is risk-gate.mjs next to this file, +// which re-exports everything here, so `import { createGate } from './risk-gate.mjs'` works. +// +// The tier is the highest of: the path of every changed file (and the old path of a rename), +// content hits in added lines of code files, and a size cap for the tier reached. +import { readFileSync } from 'node:fs' + +export const ORDER = ['T0', 'T1', 'T2', 'T3'] +const MAX_FILES = 3000 // the pull request files API stops here + +// Glob: `**/` any directories (or none), `**` anything, `*` within a segment, `?` one character, +// `{a,b}` alternatives (literals). Everything else is literal. +export function globToRe(g) { + const lit = (s) => s.replace(/[.+^$()|[\]\\{}*?]/g, '\\$&') + let re = '' + let i = 0 + while (i < g.length) { + const c = g[i] + if (c === '*' && g[i + 1] === '*') { + if (g[i + 2] === '/') { re += '(?:.*/)?'; i += 3 } else { re += '.*'; i += 2 } + } else if (c === '*') { re += '[^/]*'; i++ } + else if (c === '?') { re += '[^/]'; i++ } + else if (c === '{' && g.indexOf('}', i) > i) { + const j = g.indexOf('}', i) + re += '(?:' + g.slice(i + 1, j).split(',').map(lit).join('|') + ')' + i = j + 1 + } else { re += lit(c); i++ } + } + return new RegExp('^' + re + '$') +} + +export function createGate(rules) { + const t3 = rules.tiers.T3 + const paths = Object.fromEntries(Object.entries(rules.tiers).map(([t, d]) => [t, (d.paths || []).map(globToRe)])) + const generated = (rules.generatedPaths || []).map(globToRe) + const codeExt = new RegExp(t3.codeExt) + const compile = (list) => (list || []).map((p) => [p, new RegExp(p)]) + const patterns = compile(t3.diffPatterns) // every code file + // A topic is a tool name (#679): it counts when an added line registers the tool + // (`name: 'create_child_bot'`, the shape in plugins/tree/src/tools.js), not when a prompt + // merely names it. A plain substring match made any mention of the tool a T3 PR. + const topicName = (name) => new RegExp(`name\\s*:\\s*['"]${name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`) + const topicRules = (t3.topics || []).map((name) => [name, topicName(name)]) + const prosePatterns = compile(t3.diffPatternsNotInTests) // code files except tests: a test may quote a URL or a fence + const tests = (t3.testPaths || []).map(globToRe) + const unknown = rules.unknownPathTier || 'T2' + const isGenerated = (name) => generated.some((r) => r.test(name)) + + function tierOf(file) { + for (const t of ['T3', 'T2', 'T1', 'T0']) if (paths[t].some((r) => r.test(file))) return t + return unknown + } + + // files: the array of GET /pulls/{n}/files. truncated: the list may be incomplete. + function judge(files, { truncated = false } = {}) { + let tier = 'T0' + const why = [] + const bump = (t, reason) => { + if (ORDER.indexOf(t) > ORDER.indexOf(tier)) tier = t + if (reason) why.push(reason) + } + // Every path the rules were asked about, with the tier it got: the machine-readable line at + // the end of the report is built from this, not from a second walk over the rules. + const basis = [] + if (truncated || files.length >= MAX_FILES) bump('T3', `file list may be incomplete (${files.length} files)`) + for (const f of files) { + for (const name of [f.filename, f.previous_filename].filter(Boolean)) { + const t = tierOf(name) + basis.push([name, t]) + bump(t, t === 'T3' ? `path ${name}` : null) + } + if (isGenerated(f.filename)) continue // generated files are verified by `patches check`, not read here + if (f.changes > 0 && f.patch === undefined) { bump('T3', `diff not inspectable: ${f.filename}`); continue } + if (!codeExt.test(f.filename)) continue // patterns look at code, not prose + const added = (f.patch || '').split('\n').filter((l) => l.startsWith('+') && !l.startsWith('+++')).join('\n') + const active = tests.some((r) => r.test(f.filename)) ? patterns : [...patterns, ...prosePatterns] + for (const [src, re] of active) if (re.test(added)) bump('T3', `${f.filename}: /${src.slice(0, 60)}/`) + for (const [w, re] of topicRules) if (re.test(added)) bump('T3', `${f.filename}: topic ${w}`) + } + const real = files.filter((f) => !isGenerated(f.filename)) + const lines = real.reduce((n, f) => n + (f.additions || 0) + (f.deletions || 0), 0) + const lim = (rules.limits || {})[tier] + if (lim && (lines > lim.lines || real.length > lim.files)) { + bump('T3', `size ${lines} lines / ${real.length} files > ${lim.lines} / ${lim.files} allowed for ${tier}`) + } + const seen = new Map() + for (const [path, t] of basis) if (!seen.has(path)) seen.set(path, t) + const ordered = [...seen].map(([path, t]) => ({ path, tier: t })) + .sort((a, b) => ORDER.indexOf(b.tier) - ORDER.indexOf(a.tier) || a.path.localeCompare(b.path)) + return { tier, why: [...new Set(why)], lines, files: real.length, generated: files.length - real.length, basis: ordered } + } + + return { tierOf, judge } +} + +// The one machine-readable line the job summary ends with (#609): the tier and the paths that +// set it, from the same judge() result the human-readable report is built from, so a reviewer can +// quote a tier instead of guessing one. +export const SUMMARY_LIMIT = 10 +export function summaryLine({ tier, basis = [] }) { + const shown = basis.slice(0, SUMMARY_LIMIT).map((b) => `${b.path}=${b.tier}`) + const rest = basis.length > SUMMARY_LIMIT ? `, +${basis.length - SUMMARY_LIMIT} more` : '' + return basis.length === 0 ? `risk-tier: ${tier}; basis: none (no changed files)` : `risk-tier: ${tier}; basis: ${shown.join(', ')}${rest}` +} + +export function render(result, meaning) { + const { tier, why, lines, files, generated, basis = [] } = result + const out = [ + `### Risk tier: ${tier}`, + '', + `${meaning[tier] || ''}`, + '', + `Size (generated files excluded): ${lines} changed lines in ${files} files${generated ? `; ${generated} generated file(s) not counted` : ''}.`, + ] + // A reason for every tier, not only for T3: when no T3 rule fired, the paths that set the tier + // reached are the reason (`services/bot-social/src/x.ts=T2`), so a T1/T2 verdict is quotable too. + const reasons = why.length ? why : basis.filter((b) => b.tier === tier).map((b) => `path ${b.path} (${b.tier})`) + if (reasons.length) { + out.push('', 'Why:', ...reasons.slice(0, 20).map((w) => `- ${w}`)) + if (reasons.length > 20) out.push(`- ... and ${reasons.length - 20} more`) + } + out.push('', '_Report only: this does not block, label or merge anything. Rules: `.github/agent/risk-rules.json` (issue #3393)._', '', summaryLine(result)) + return out.join('\n') +} + +export function loadRules(path) { + return JSON.parse(readFileSync(path, 'utf8')) +} diff --git a/.github/workflows/risk-tier.yml b/.github/workflows/risk-tier.yml new file mode 100644 index 000000000..363b70588 --- /dev/null +++ b/.github/workflows/risk-tier.yml @@ -0,0 +1,40 @@ +name: Risk tier +# Report only: classifies the pull request diff and prints the tier with the +# rules that fired. It never labels, comments, or blocks a merge, so a T3 +# verdict is a green check whose summary says "a human has to approve this", +# not a failing build. The gate that requires anything is a later stage. + +on: + pull_request: + types: [opened, synchronize, reopened] + +permissions: + contents: read + pull-requests: read + +concurrency: + group: risk-tier-${{ github.event.pull_request.number }} + cancel-in-progress: true + +jobs: + risk-tier: + name: risk-tier + runs-on: ubuntu-24.04 + timeout-minutes: 10 + steps: + - uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6 + with: + persist-credentials: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: '22' + # risk-gate.mjs exits 0 whenever it could compute a tier (T3 included) and + # 1 only when it could not compute one, which is the case worth reporting. + # The runner sets GITHUB_STEP_SUMMARY, so the script writes the readable + # reason table there and the console line carries the one-line verdict. + - name: Classify the pull request diff + env: + PR: ${{ github.event.pull_request.number }} + GITHUB_REPOSITORY: ${{ github.repository }} + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: node .github/scripts/risk-gate.mjs