Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions .github/agent/risk-rules.json
Original file line number Diff line number Diff line change
@@ -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}}
}
94 changes: 94 additions & 0 deletions .github/scripts/risk-gate-api.test.mjs
Original file line number Diff line number Diff line change
@@ -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')
})
100 changes: 100 additions & 0 deletions .github/scripts/risk-gate-judge.test.mjs
Original file line number Diff line number Diff line change
@@ -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')
})
12 changes: 12 additions & 0 deletions .github/scripts/risk-gate.fixtures.mjs
Original file line number Diff line number Diff line change
@@ -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,
})
Loading
Loading