Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
ci(verify): warn on guarded and high-risk code instead of trusting green
Richie McIlroy2f97e49a1201
diff --git a/.github/workflows/engine-verify-os.yml b/.github/workflows/engine-verify-os.ymlindex 31120d237..1bb925b9d 100644--- a/.github/workflows/engine-verify-os.yml+++ b/.github/workflows/engine-verify-os.yml@@ -188,6 +188,14 @@ jobs:scripts/verify/run.sh "${{ inputs.tier }}" --suites "${{ inputs.suites }}"fi+ # Equivalent-mutant guards (scripts/verify/guards.toml): a failing+ # sentinel is a warning for review, never a failure.+ - name: Guard sentinels+ if: always() && inputs.platform == 'linux' && matrix.shard == 1 && steps.test.outcome != 'skipped'+ continue-on-error: true+ shell: bash+ run: python3 scripts/verify/guards.py --profile "$CAP_VERIFY_CARGO_PROFILE"+- name: Summaryif: always() && steps.test.outcome != 'skipped'shell: bashdiff --git a/.github/workflows/engine-verify.yml b/.github/workflows/engine-verify.ymlindex 41212496d..9d208f8b4 100644--- a/.github/workflows/engine-verify.yml+++ b/.github/workflows/engine-verify.yml@@ -40,6 +40,10 @@ on:description: "CARGO_LOG for the build (for example cargo::core::compiler::fingerprint=info)"type: stringdefault: ""+ base:+ description: "Plan from the diff against this ref, like a pull request (scope, risk escalation)"+ type: string+ default: ""workflow_call:inputs:tier:@@ -63,7 +67,8 @@ jobs:timeout-minutes: 5outputs:run: ${{ steps.plan.outputs.run }}- tier: ${{ steps.tier.outputs.tier }}+ tier: ${{ steps.escalated.outputs.tier }}+ escalate: ${{ steps.risk.outputs.escalate }}matrix: ${{ steps.plan.outputs.matrix }}save-cache: ${{ steps.tier.outputs.save-cache }}steps:@@ -110,6 +115,7 @@ jobs:BEFORE: ${{ github.event.before }}MQ_BASE: ${{ github.event.merge_group.base_sha }}MQ_HEAD: ${{ github.event.merge_group.head_sha }}+ BASE: ${{ inputs.base }}SUITES: ${{ inputs.suites }}run: |set -euo pipefail@@ -128,16 +134,44 @@ jobs:elsegh api "repos/$GITHUB_REPOSITORY/compare/$BEFORE...$GITHUB_SHA" --jq '.files[].filename' > "$files"fi ;;- *) scope=all ;;+ *)+ if [[ -n "${BASE:-}" ]]; then+ gh api "repos/$GITHUB_REPOSITORY/compare/$BASE...$GITHUB_SHA" --jq '.files[].filename' > "$files"+ max=3000+ else+ scope=all+ fi ;;esacecho "scope=$scope" >> "$GITHUB_OUTPUT"echo "max=$max" >> "$GITHUB_OUTPUT"[[ -f "$files" ]] && { echo "$(wc -l < "$files") changed files"; head -50 "$files"; } || true+ # High-risk code (scripts/verify/guards.toml): warn, and run a pull+ # request that touches it at the FULL tier.+ - name: Risk+ id: risk+ if: steps.files.outputs.scope == 'files'+ run: python3 scripts/verify/plan.py risk --files "$RUNNER_TEMP/changed.txt" --summary "$GITHUB_STEP_SUMMARY" --output "$GITHUB_OUTPUT"++ - name: Escalate tier+ id: escalated+ env:+ TIER: ${{ steps.tier.outputs.tier }}+ ESCALATE: ${{ steps.risk.outputs.escalate }}+ EVENT: ${{ github.event_name }}+ BASE: ${{ inputs.base }}+ run: |+ tier="$TIER"+ if [[ "$ESCALATE" == true && ( "$EVENT" == pull_request || -n "$BASE" ) && "$tier" == fast ]]; then+ tier=full+ echo "High-risk code changed: running the FULL tier." | tee -a "$GITHUB_STEP_SUMMARY"+ fi+ echo "tier=$tier" >> "$GITHUB_OUTPUT"+- name: Planid: planenv:- TIER: ${{ steps.tier.outputs.tier }}+ TIER: ${{ steps.escalated.outputs.tier }}SCOPE: ${{ steps.files.outputs.scope }}MAX: ${{ steps.files.outputs.max }}SUITES: ${{ inputs.suites }}@@ -156,6 +190,26 @@ jobs:grep -E '^(reason|suites)=' "$RUNNER_TEMP/plan.txt" | sed 's/^/- /'} >> "$GITHUB_STEP_SUMMARY"+ # Labels a risky pull request needs-deep-review. Kept apart from the plan+ # job so no step that runs repository code holds a write token; fork pull+ # requests get a read-only token and only keep the summary and annotations.+ deep-review-label:+ name: Deep review label+ needs: plan+ if: github.event_name == 'pull_request' && needs.plan.outputs.escalate == 'true'+ runs-on: ubuntu-latest+ timeout-minutes: 5+ permissions:+ pull-requests: write+ steps:+ - name: Label+ env:+ GH_TOKEN: ${{ github.token }}+ PR: ${{ github.event.pull_request.number }}+ run: |+ gh api "repos/$GITHUB_REPOSITORY/issues/$PR/labels" -f "labels[]=needs-deep-review" > /dev/null \+ || echo "::notice::could not add the needs-deep-review label with this token; the summary and annotations still flag the change"+verify:name: ${{ matrix.platform }}needs: plandiff --git a/.github/workflows/verify-recording.yml b/.github/workflows/verify-recording.ymlindex af63b47a4..69828753f 100644--- a/.github/workflows/verify-recording.yml+++ b/.github/workflows/verify-recording.yml@@ -7,7 +7,8 @@ name: Verify recording (real capture)# Pull requests (and pushes to the suite branches) that touch the capture,# encode, timestamp or verify code run the FAST tier once on macos-15; the-# FULL tier runs on macos-15 and macos-26 nightly and on dispatch.+# FULL tier runs on macos-15 and macos-26 nightly and on dispatch, and for a+# pull request that touches a high-risk region of scripts/verify/guards.toml.on:workflow_dispatch:inputs:@@ -38,6 +39,15 @@ on:- "crates/project/**"- "Cargo.lock"- ".github/workflows/verify-recording.yml"+ - "crates/enc-ffmpeg/**"+ - "crates/audio/**"+ - "crates/editor/src/audio*.rs"+ - "crates/rendering/src/decoder/**"+ - "crates/video-decode/**"+ - "apps/desktop-gpui/src/upload*"+ - "apps/desktop-gpui/src/upload/**"+ - "scripts/verify/guards.toml"+push:branches:- ci/verify-ci@@ -60,19 +70,60 @@ concurrency:permissions:contents: read+ pull-requests: readjobs:+ scope:+ name: Scope+ runs-on: ubuntu-latest+ timeout-minutes: 5+ outputs:+ runners: ${{ steps.scope.outputs.runners }}+ tier: ${{ steps.scope.outputs.tier }}+ steps:+ - uses: actions/checkout@v4+ with:+ persist-credentials: false+ sparse-checkout: scripts/verify+ - name: Scope+ id: scope+ env:+ GH_TOKEN: ${{ github.token }}+ EVENT: ${{ github.event_name }}+ PR: ${{ github.event.pull_request.number }}+ INPUT_TIER: ${{ inputs.tier }}+ run: |+ set -euo pipefail+ both='["macos-15","macos-26"]'+ case "$EVENT" in+ schedule) runners="$both"; tier=full ;;+ workflow_dispatch) runners="$both"; tier="${INPUT_TIER:-full}" ;;+ pull_request)+ gh api "repos/$GITHUB_REPOSITORY/pulls/$PR/files" --paginate --jq '.[].filename' > "$RUNNER_TEMP/changed.txt"+ python3 scripts/verify/plan.py risk --files "$RUNNER_TEMP/changed.txt" --summary "$GITHUB_STEP_SUMMARY" --output "$RUNNER_TEMP/risk.txt"+ if grep -qx 'escalate=true' "$RUNNER_TEMP/risk.txt"; then+ runners="$both"; tier=full+ else+ runners='["macos-15"]'; tier=fast+ fi ;;+ *) runners='["macos-15"]'; tier=fast ;;+ esac+ echo "runners=$runners" >> "$GITHUB_OUTPUT"+ echo "tier=$tier" >> "$GITHUB_OUTPUT"+ echo "real capture: $tier tier on $runners" | tee -a "$GITHUB_STEP_SUMMARY"+real-capture:+ needs: scopestrategy:fail-fast: falsematrix:- runner: ${{ fromJSON((github.event_name == 'schedule' || github.event_name == 'workflow_dispatch') && '["macos-15", "macos-26"]' || '["macos-15"]') }}+ runner: ${{ fromJSON(needs.scope.outputs.runners) }}runs-on: ${{ matrix.runner }}timeout-minutes: 45env:CAP_VERIFY_CAPTURE: displayCAP_VERIFY_REQUIRE_CAPTURE: "1"- CAP_VERIFY_TIER: ${{ inputs.tier || (github.event_name == 'schedule' && 'full') || 'fast' }}+ CAP_VERIFY_TIER: ${{ needs.scope.outputs.tier }}CAP_VERIFY_REPEAT: ${{ inputs.repeat || (github.event_name == 'schedule' && '3') || '1' }}CAP_VERIFY_CASE: ${{ inputs.case_filter || '' }}CAP_VERIFY_KEEP: ${{ inputs.keep_artifacts && '1' || '' }}diff --git a/crates/audio/src/voice.rs b/crates/audio/src/voice.rsindex 32e786a37..f4013c418 100644--- a/crates/audio/src/voice.rs+++ b/crates/audio/src/voice.rs@@ -287,6 +287,38 @@ mod tests {}}+ /// Guard sentinel A09 (scripts/verify/guards.toml): a render that does+ /// not continue the previous one must sound exactly like a render by a+ /// new enhancer (the reset in `render`, and the editor cache that never+ /// reuses an enhancer across a seek).+ #[test]+ fn guard_a09_render_after_a_seek_equals_a_fresh_enhancer() {+ ffmpeg::init().unwrap();+ // Voiced, syllable-modulated harmonics plus noise, so the render+ // is not silence.+ let mut source = signal(96_000 * 2, 2);+ for (index, sample) in source.data.iter_mut().enumerate() {+ let t = (index / 2) as f32 / 48_000.0;+ let pitch = 140.0 + 30.0 * (t * 1.3).sin();+ let voice: f32 = (1..6)+ .map(|h| (std::f32::consts::TAU * pitch * h as f32 * t).sin() / h as f32)+ .sum();+ let syllables = (std::f32::consts::TAU * 4.0 * t).sin().max(0.0);+ *sample += 0.25 * voice * syllables;+ }+ let mut reused = VoiceEnhancer::with_settings(2, 1.0, VoiceProfile::default());+ let _ = reused.render(&source, 0, 9_600);+ let _ = reused.render(&source, 9_600, 9_600);+ let after_seek = reused.render(&source, 120_000, 9_600);+ let fresh = VoiceEnhancer::with_settings(2, 1.0, VoiceProfile::default())+ .render(&source, 120_000, 9_600);+ assert!(+ fresh.samples().iter().any(|v| v.abs() > 0.01),+ "silent render"+ );+ assert_eq!(after_seek.samples(), fresh.samples());+ }+#[test]fn leveling_preserves_chunk_boundaries_timing_and_peak_headroom() {ffmpeg::init().unwrap();diff --git a/crates/enc-ffmpeg/src/base.rs b/crates/enc-ffmpeg/src/base.rsindex 41b34700d..c2a5626df 100644--- a/crates/enc-ffmpeg/src/base.rs+++ b/crates/enc-ffmpeg/src/base.rs@@ -328,6 +328,40 @@ fn normalize_input_pts(pts: i64, last_pts: Option<i64>) -> i64 {mod tests {use super::*;+ /// Guard sentinel E02 (scripts/verify/guards.toml): a stream whose first+ /// frame carries a non-zero pts is rebased to start at 0 and keeps its+ /// frame spacing. Exports start at 0 anyway, so removing the rebase+ /// changes no export output today; this checks the rebase itself.+ #[test]+ fn guard_e02_rebases_a_stream_whose_first_pts_is_not_zero() {+ ffmpeg::init().unwrap();+ let mut encoder = ffmpeg::codec::context::Context::new().encoder();+ let mut base = EncoderBase::new(0);+ let mut seen = Vec::new();+ for pts in [3_000_i64, 3_512, 4_024, 4_536] {+ let mut frame = frame::Video::new(ffmpeg::format::Pixel::YUV420P, 2, 2);+ frame.set_pts(Some(pts));+ base.update_pts(&mut frame, Duration::MAX, &mut encoder);+ seen.push(frame.pts());+ }+ assert_eq!(seen, [Some(0), Some(512), Some(1_024), Some(1_536)]);++ // Capture timestamps (time base 1/90000) starting 2.5 s in.+ let mut video = ffmpeg::codec::context::Context::new()+ .encoder()+ .video()+ .unwrap();+ video.set_time_base((1, 90_000));+ let mut base = EncoderBase::new(0);+ let mut seen = Vec::new();+ for ms in [2_500_u64, 2_533, 2_567, 2_600] {+ let mut frame = frame::Video::new(ffmpeg::format::Pixel::YUV420P, 2, 2);+ base.update_pts(&mut frame, Duration::from_millis(ms), &mut video);+ seen.push(frame.pts());+ }+ assert_eq!(seen, [Some(0), Some(2_970), Some(6_030), Some(9_000)]);+ }+#[test]fn normalize_input_pts_passes_monotonic_input_through() {// Any strictly-forward delta passes untouched, even sub-frame onesdiff --git a/scripts/verify/guards.py b/scripts/verify/guards.pynew file mode 100644index 000000000..89cd9f57d--- /dev/null+++ b/scripts/verify/guards.py@@ -0,0 +1,62 @@+#!/usr/bin/env python3+"""Runs the guard sentinels listed in scripts/verify/guards.toml.++ guards.py [--profile PROFILE] [--summary FILE]++A sentinel that fails, or that no longer exists, is reported as a WARNING+(a ::warning annotation and a "Guard changed: needs deep review" section in+the summary file), never as a failure: the guards are equivalent mutants, so+a change to them needs review rather than a red build. Exit status is 0+unless cargo itself cannot run.+"""++import argparse+import os+import subprocess+import sys+import tomllib++ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--profile", default=os.environ.get("CAP_VERIFY_CARGO_PROFILE", "dev"))+ parser.add_argument("--summary", default=os.environ.get("GITHUB_STEP_SUMMARY"))+ args = parser.parse_args()+ with open(os.path.join(ROOT, "scripts", "verify", "guards.toml"), "rb") as f:+ guards = tomllib.load(f).get("guard", [])+ changed = []+ for g in guards:+ cmd = ["cargo", "test", "--profile", args.profile, "-p", g["package"], g["target"], "--", "--exact", g["test"]]+ if os.environ.get("CAP_VERIFY_LOCKED") == "1":+ cmd.insert(2, "--locked")+ print(f"guard {g['id']}: {' '.join(cmd)}", flush=True)+ result = subprocess.run(cmd, cwd=ROOT, capture_output=True, text=True)+ output = result.stdout + result.stderr+ if result.returncode == 0 and "running 1 test" in output:+ print(f"guard {g['id']}: sentinel holds")+ continue+ if result.returncode == 0:+ reason = f"sentinel {g['test']} did not run (renamed or removed?)"+ elif "test result: FAILED" in output:+ reason = f"sentinel {g['test']} fails"+ else:+ sys.stdout.write(output[-4000:])+ sys.exit(f"guard {g['id']}: cargo failed before running the sentinel")+ print(output[-3000:])+ print(f"::warning title=Guard changed: {g['id']} ({g['area']})::{reason}. {g['prevents']}")+ changed.append((g, reason))+ if changed and args.summary:+ lines = ["## Guard changed: needs deep review", ""]+ lines.append("A sentinel of a guard whose removal changes no checked output now fails. This is a warning, not a failure: review the change to the guard closely.")+ lines.append("")+ for g, reason in changed:+ lines.append(f"- **{g['id']}** ({g['area']}; {', '.join(g['symbols'])}): {reason}. {g['why']} Prevents: {g['prevents']} Repro: `cargo test -p {g['package']} {g['target']} -- --exact {g['test']}`")+ with open(args.summary, "a") as f:+ f.write("\n".join(lines) + "\n\n")+ print(f"guards: {len(guards) - len(changed)} of {len(guards)} sentinels hold")+++if __name__ == "__main__":+ main()diff --git a/scripts/verify/guards.toml b/scripts/verify/guards.tomlnew file mode 100644index 000000000..e2f0cae7c--- /dev/null+++ b/scripts/verify/guards.toml@@ -0,0 +1,100 @@+# Code that protects users but that the engine suites cannot see change.+#+# [[region]]: high-risk code. A pull request whose diff touches one gets a+# "needs deep review" warning (job summary, annotation, and the+# needs-deep-review label where the token may add labels), and Engine verify+# plus real capture run the FULL tier (real capture on macos-15 and+# macos-26). Paths are globs relative to the repository root; `/**` matches+# everything below a directory.+#+# [[guard]]: a protective guard whose removal changes no output of the suites+# today (an equivalent mutant), so only a sentinel notices. The sentinel is a+# small behaviour test of the unit's own API. It runs on every Linux Engine+# verify job; a failing sentinel, or a diff touching the guard's files, is a+# WARNING ("Guard changed: needs deep review"), never a CI failure. To cover+# a new equivalent mutant, add a sentinel test and an entry here.+#+# Read by scripts/verify/plan.py (`risk`) and scripts/verify/guards.py.++[[region]]+name = "encoder timestamps"+paths = [+ "crates/enc-ffmpeg/src/base.rs",+ "crates/enc-ffmpeg/src/video/**",+ "crates/enc-ffmpeg/src/mux/**",+ "crates/enc-avfoundation/src/**",+ "crates/enc-mediafoundation/src/**",+]++[[region]]+name = "audio mixing and Studio Sound"+paths = [+ "crates/audio/src/**",+ "crates/editor/src/audio.rs",+ "crates/editor/src/audio_output.rs",+ "crates/enc-ffmpeg/src/audio/**",+]++[[region]]+name = "decoder seek and frame selection"+paths = [+ "crates/rendering/src/decoder/**",+ "crates/video-decode/src/**",+]++[[region]]+name = "recording timestamps and sync"+paths = [+ "crates/recording/src/output_pipeline/**",+ "crates/recording/src/sources/**",+ "crates/recording/src/feeds/**",+ "crates/recording/src/sync_calibration.rs",+ "crates/timestamp/src/**",+]++[[region]]+name = "Instant finalize"+paths = [+ "crates/recording/src/instant_recording.rs",+ "crates/recording/src/instant_recording/**",+]++[[region]]+name = "recovery"+paths = [+ "crates/recording/src/recovery.rs",+ "crates/recording/src/recovery/**",+ "crates/recording/src/track_heal.rs",+]++[[region]]+name = "upload retry"+paths = [+ "apps/desktop-gpui/src/upload.rs",+ "apps/desktop-gpui/src/upload/**",+ "crates/recording/src/upload_resume.rs",+]++[[guard]]+id = "E02"+mutation = "E02"+area = "encoder timestamps"+files = ["crates/enc-ffmpeg/src/base.rs"]+symbols = ["EncoderBase::update_pts"]+package = "cap-enc-ffmpeg"+target = "--lib"+test = "base::tests::guard_e02_rebases_a_stream_whose_first_pts_is_not_zero"+why = "The encoder rebases a stream whose first frame has a non-zero pts so it starts at 0. Exports already start at 0, so removing the rebase changes no export the suites check."+prevents = "A recording or export whose first frame is not at 0 would start with a gap or frozen first frame and its audio would drift from the picture by that offset."++[[guard]]+id = "A09"+mutation = "A09"+area = "audio mixing and Studio Sound"+files = ["crates/audio/src/voice.rs", "crates/editor/src/audio.rs"]+symbols = ["VoiceEnhancer::render", "VoiceEnhancementCache::render"]+package = "cap-audio"+target = "--lib"+test = "voice::tests::guard_a09_render_after_a_seek_equals_a_fresh_enhancer"+why = "A Studio Sound render that does not continue the previous one restarts the enhancer (the reset in VoiceEnhancer::render), and the editor cache never reuses an enhancer across a seek. Either alone keeps the output right, so removing one changes nothing the suites see. The sentinel checks the property itself (a render after a seek equals a fresh one); removing only the reset leaves its output bit-identical too, so that edit is flagged by the path warning, not by the sentinel."+prevents = "Studio Sound after a seek or scrub would carry denoiser and leveler state from another part of the recording: a burst of wrong gain or suppressed speech right after every seek, different from the export."diff --git a/scripts/verify/plan.py b/scripts/verify/plan.pyindex d6a039524..cf1d9acee 100755--- a/scripts/verify/plan.py+++ b/scripts/verify/plan.py@@ -9,6 +9,9 @@Maps changed paths to suites through the workspace dependency graph(`cargo metadata`) and prints GitHub step outputs: run, reason,suites, matrix.+ plan.py risk --files F [--summary FILE] [--output FILE]+ changed files -> high-risk regions and guards (scripts/verify/guards.toml):+ escalate=, regions=, guards= lines plus ::warning annotations.plan.py testSelf-test of the change mapping.@@ -25,6 +28,52 @@ ROOT = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(__file__)),PLATFORMS = ["linux", "macos", "windows"]+def load_guards():+ import tomllib++ with open(os.path.join(ROOT, "scripts", "verify", "guards.toml"), "rb") as f:+ return tomllib.load(f)+++def risk(files, guards=None):+ """(regions touched, guards whose files are touched) for changed files."""+ guards = guards or load_guards()+ regions = []+ for region in guards.get("region", []):+ hits = sorted({p for p in files for pattern in region["paths"] if match(p, pattern)})+ if hits:+ regions.append((region["name"], hits))+ touched = [+ g for g in guards.get("guard", []) if any(p in g["files"] for p in files)+ ]+ return regions, touched+++def risk_report(regions, touched):+ """Job-summary markdown and annotation lines for a risky diff."""+ if not regions and not touched:+ return "", []+ md = ["## Needs deep review", ""]+ notes = []+ if regions:+ md.append("This change touches high-risk engine code. A pull request that does runs the FULL tier, with real capture on both macOS versions:")+ md.append("")+ for name, hits in regions:+ md.append(f"- **{name}**: " + ", ".join(f"`{h}`" for h in hits[:6]) + (" ..." if len(hits) > 6 else ""))+ notes.append(f"::warning title=Needs deep review ({name})::{', '.join(hits[:6])}")+ md.append("")+ if touched:+ md.append("### Guard changed: needs deep review")+ md.append("")+ md.append("These guards protect users, but removing them changes no output the suites check (equivalent mutants), so only review can catch a regression:")+ md.append("")+ for g in touched:+ md.append(f"- **{g['id']}** ({g['area']}; {', '.join(g['symbols'])}): {g['why']} Prevents: {g['prevents']}")+ notes.append(f"::warning title=Guard changed: {g['id']} ({g['area']})::{g['prevents']}")+ md.append("")+ return "\n".join(md), notes++def load_config():with open(os.path.join(ROOT, "scripts", "verify", "suites.json")) as f:return json.load(f)@@ -255,6 +304,28 @@ def cmd_changes(args):print(f"{key}={value}")+def cmd_risk(args):+ with open(args.files) as f:+ files = [line.strip() for line in f if line.strip()]+ regions, touched = risk(files)+ md, notes = risk_report(regions, touched)+ if args.summary and md:+ with open(args.summary, "a") as f:+ f.write(md + "\n")+ for note in notes:+ print(note)+ outputs = [+ f"escalate={'true' if regions or touched else 'false'}",+ f"regions={','.join(name for name, _ in regions)}",+ f"guards={','.join(g['id'] for g in touched)}",+ ]+ if args.output:+ with open(args.output, "a") as f:+ f.write("\n".join(outputs) + "\n")+ else:+ print("\n".join(outputs))++def cmd_test(_args):config = load_config()metadata = load_metadata(None)@@ -280,6 +351,22 @@ def cmd_test(_args):ok = sorted(names) == sorted(expected)failed += not okprint(f"{'ok ' if ok else 'BAD'} {files} -> {names} ({reason})")+ guards = load_guards()+ for g in guards.get("guard", []):+ if not any(match(f, pattern) for f in g["files"] for r in guards["region"] for pattern in r["paths"]):+ failed += 1+ print(f"BAD guard {g['id']}: its files lie outside every high-risk region")+ for files, expected in [+ (["crates/enc-ffmpeg/src/base.rs"], (["encoder timestamps"], ["E02"])),+ (["crates/editor/src/audio.rs", "README.md"], (["audio mixing and Studio Sound"], ["A09"])),+ (["apps/desktop-gpui/src/upload/queue.rs"], (["upload retry"], [])),+ (["crates/verify/src/oracle.rs", "apps/web/app/page.tsx"], ([], [])),+ ]:+ regions, touched = risk(files, guards)+ got = ([n for n, _ in regions], [g["id"] for g in touched])+ ok = got == expected+ failed += not ok+ print(f"{'ok ' if ok else 'BAD'} risk {files} -> {got}")rendering_only = affected(config, ["crates/rendering/src/decoder/model/mod.rs"], metadata, "fast")[0]if "decoder-model-ffmpeg" not in rendering_only:failed += 1@@ -310,6 +397,11 @@ def main():p.add_argument("--max-files", type=int, default=3000)p.add_argument("--suites")p.set_defaults(func=cmd_changes)+ p = sub.add_parser("risk")+ p.add_argument("--files", required=True)+ p.add_argument("--summary", help="append the markdown report to this file")+ p.add_argument("--output", help="append the escalate/regions/guards lines to this file (GITHUB_OUTPUT)")+ p.set_defaults(func=cmd_risk)p = sub.add_parser("test")p.set_defaults(func=cmd_test)args = parser.parse_args()