From 3db7378e5bb40407a53feafe3fd6593571985e2c Mon Sep 17 00:00:00 2001
From: Precious Okwu <32944039+libracoder@users.noreply.github.com>
Date: Wed, 2 Dec 2026 02:41:04 +0100
Subject: [PATCH] CI & release: enforce executable regression checks, PR gates,
Windows unit tests, and Mac release gate (#1128)
* CI & release: enforce executable regression checks, PR gates, Windows unit tests, and Mac release gate
* Compose: keep empty environment variables distinct instead of gluing onto preceding entry
---
.github/workflows/tests.yml | 105 ++++-
RELEASES.md | 6 +-
crates/kiri/src/daemon/localtime.rs | 50 +++
crates/kiri/src/daemon/storage.rs | 27 +-
crates/kiri/src/ui/assemble.rs | 22 +-
crates/kiri/src/ui/compose.rs | 10 +-
scripts/ci/check-pr-gates.py | 595 ++++++++++++++++++++++++++++
scripts/ci/test_check_pr_gates.py | 300 ++++++++++++++
scripts/ci/test_release_gate_mac.py | 236 +++++++++++
scripts/ci/test_tests_scope.py | 14 +
scripts/ci/tests-scope.py | 20 +-
scripts/release-gate-mac.py | 426 ++++++++++++++++++++
tests/disk-grow.py | 5 +
tests/lib/check-regressions.py | 316 +++++++++++++--
tests/regressions.tsv | 177 +++++----
15 files changed, 2160 insertions(+), 149 deletions(-)
create mode 100755 scripts/ci/check-pr-gates.py
create mode 100644 scripts/ci/test_check_pr_gates.py
create mode 100644 scripts/ci/test_release_gate_mac.py
create mode 100755 scripts/release-gate-mac.py
mode change 100644 => 100755 tests/lib/check-regressions.py
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 15ceb341..101f6c81 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -20,22 +20,23 @@
#
# - unit: the workspace's unit tests on Linux (kiri-init's as root, as in
# the guest, since several need it).
-# - windows-build: the Windows app and CLI still compile, so shared code
-# can't use something only Unix has.
+# - windows-build: the build and unit tests on Windows, so shared and Windows
+# code is both compiled and run.
# - mac-build: the build and the unit tests on a Mac, and what the runner
# offers for Kiri's VM (in its job summary).
-# - scripts: a change to the suites' or scripts' shell or Python files is
-# checked in under a minute: bash -n, shellcheck, py_compile, the
-# regressions table and the CI scripts' own tests.
+# - scripts: a change to the suites, scripts or regression targets is checked
+# in under a minute: bash -n, shellcheck, py_compile, the regressions table,
+# the pull request gates and the CI scripts' own tests.
# - page-scan: what a pull request adds to the window's page is read for
# new addresses, network calls and hidden code (scripts/ci/page-scan.py);
# anything flagged fails until a maintainer adds the label `page-read`.
#
-# One long job waits to be asked for:
+# End-to-end Linux suite:
# - e2e-linux: the Linux engine built and started as a Linux host runs it,
# then tests/e2e.sh in strict mode (what the runner lacks fails, it is
# not skipped) and tests/stress.sh, both through the docker CLI. It runs
-# only on a pull request that carries the label `run-tests`. Only people
+# automatically on pull requests in this repository that change the suites,
+# and on any pull request that carries the label `run-tests`. Only people
# with rights on the repository can add a label. The label also starts the
# quick jobs whatever the files are.
#
@@ -85,10 +86,31 @@ jobs:
with:
fetch-depth: 2
persist-credentials: false
+ - name: Check regressions table and pull request gates
+ env:
+ PR_TITLE: ${{ github.event.pull_request.title }}
+ PR_BODY: ${{ github.event.pull_request.body }}
+ NO_REGRESSION: ${{ contains(github.event.pull_request.labels.*.name, 'no-regression-needed') }}
+ run: |
+ if git show HEAD^1:tests/lib/check-regressions.py > "$RUNNER_TEMP/check-regressions.py" 2>/dev/null \
+ && grep -q '::' "$RUNNER_TEMP/check-regressions.py"; then
+ :
+ else
+ cp tests/lib/check-regressions.py "$RUNNER_TEMP/check-regressions.py"
+ fi
+ git show HEAD^1:scripts/ci/check-pr-gates.py > "$RUNNER_TEMP/check-pr-gates.py" 2>/dev/null \
+ || cp scripts/ci/check-pr-gates.py "$RUNNER_TEMP/check-pr-gates.py"
+ python3 -I "$RUNNER_TEMP/check-regressions.py" --repo "$PWD"
+ set -- --repo "$PWD" --base HEAD^1 --head HEAD
+ if [ "$NO_REGRESSION" = true ]; then
+ set -- "$@" --skip-issue-check
+ fi
+ python3 -I "$RUNNER_TEMP/check-pr-gates.py" "$@"
- name: Which jobs this pull request needs
id: scope
env:
FORCED: ${{ contains(github.event.pull_request.labels.*.name, 'run-tests') }}
+ SAME_REPO: ${{ github.event.pull_request.head.repo.full_name == github.repository }}
run: |
# The scripts are main's copies when main has them, so a pull
# request can't decide for itself that it needs no tests. They read
@@ -97,13 +119,19 @@ jobs:
git show HEAD^1:scripts/ci/tests-scope.py > "$RUNNER_TEMP/scope.py" 2>/dev/null || cp scripts/ci/tests-scope.py "$RUNNER_TEMP/scope.py"
git show HEAD^1:scripts/ci/page-scan.py > "$RUNNER_TEMP/page-scan.py" 2>/dev/null || cp scripts/ci/page-scan.py "$RUNNER_TEMP/page-scan.py"
python3 -I "$RUNNER_TEMP/scope.py" HEAD^1 HEAD | tee "$RUNNER_TEMP/scope.txt"
- if grep -qx 'suites_changed=true' "$RUNNER_TEMP/scope.txt" && [ "$FORCED" != true ]; then
- echo "this pull request changes the suites; add the label run-tests to run them" | tee -a "$GITHUB_STEP_SUMMARY"
- fi
- echo "suite=false" >> "$RUNNER_TEMP/scope.txt"
if [ "$FORCED" = true ]; then
echo "the run-tests label is on: every job runs" | tee -a "$GITHUB_STEP_SUMMARY"
printf 'linux=true\nwindows=true\nmac=true\nscripts=true\nsuite=true\n' > "$RUNNER_TEMP/scope.txt"
+ elif grep -qx 'suites_changed=true' "$RUNNER_TEMP/scope.txt"; then
+ if [ "$SAME_REPO" = true ]; then
+ echo "this pull request changes the suites: e2e-linux runs automatically" | tee -a "$GITHUB_STEP_SUMMARY"
+ echo "suite=true" >> "$RUNNER_TEMP/scope.txt"
+ else
+ echo "this pull request from a fork changes the suites; add the label run-tests to run them" | tee -a "$GITHUB_STEP_SUMMARY"
+ echo "suite=false" >> "$RUNNER_TEMP/scope.txt"
+ fi
+ else
+ echo "suite=false" >> "$RUNNER_TEMP/scope.txt"
fi
# The page scan goes by the files whatever the labels are.
python3 -I "$RUNNER_TEMP/page-scan.py" --changed HEAD^1 HEAD | tee -a "$RUNNER_TEMP/scope.txt"
@@ -141,13 +169,51 @@ jobs:
needs: scope
if: needs.scope.outputs.windows == 'true'
runs-on: windows-latest
- timeout-minutes: 20
+ timeout-minutes: 30
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- - name: Check the Windows app and CLI compile
- run: cargo check --locked --target x86_64-pc-windows-msvc -p kiri-win -p kiri
+ - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: |
+ ~/.cargo/registry
+ ~/.cargo/git
+ target
+ key: unit-${{ runner.os }}-${{ hashFiles('Cargo.lock') }}
+ restore-keys: unit-${{ runner.os }}-
+ # kiri-win includes crates/kiri/src/ui/compose.rs, whose unit tests run
+ # the docker CLI and Compose offline. Install the exact versions Kiri for
+ # Windows bundles, verified against crates/kiri/src/cli_pins.rs.
+ - name: The docker CLI and Compose Kiri ships
+ shell: pwsh
+ run: |
+ $ErrorActionPreference = 'Stop'
+ function Get-Pin([string]$Name) {
+ $m = Select-String -Path 'crates/kiri/src/cli_pins.rs' -Pattern "^pub const ${Name}: \(&str, &str\) = \(`"([^`"]+)`", `"([0-9a-f]{64})`"\);$"
+ if (-not $m) { throw "could not read $Name from cli_pins.rs" }
+ return @($m.Matches[0].Groups[1].Value, $m.Matches[0].Groups[2].Value)
+ }
+ $dv, $dsum = Get-Pin 'WIN_DOCKER_CLI'
+ $cv, $csum = Get-Pin 'WIN_COMPOSE'
+ $zip = Join-Path $env:RUNNER_TEMP 'docker.zip'
+ $compose = Join-Path $env:RUNNER_TEMP 'docker-compose.exe'
+ curl.exe -fsSL --proto '=https' -o $zip "https://download.docker.com/win/static/stable/x86_64/docker-$dv.zip"
+ if ((Get-FileHash -Algorithm SHA256 $zip).Hash.ToLowerInvariant() -ne $dsum) { throw 'docker.zip SHA-256 mismatch' }
+ curl.exe -fsSL --proto '=https' -o $compose "https://github.com/docker/compose/releases/download/$cv/docker-compose-windows-x86_64.exe"
+ if ((Get-FileHash -Algorithm SHA256 $compose).Hash.ToLowerInvariant() -ne $csum) { throw 'docker-compose.exe SHA-256 mismatch' }
+ $unzipDir = Join-Path $env:RUNNER_TEMP 'docker-unpack'
+ $binDir = Join-Path $env:RUNNER_TEMP 'bin'
+ $pluginDir = Join-Path $env:USERPROFILE '.docker\cli-plugins'
+ New-Item -ItemType Directory -Force -Path $unzipDir, $binDir, $pluginDir | Out-Null
+ tar.exe -xf $zip -C $unzipDir docker/docker.exe
+ Copy-Item -Force (Join-Path $unzipDir 'docker\docker.exe') (Join-Path $binDir 'docker.exe')
+ Copy-Item -Force $compose (Join-Path $pluginDir 'docker-compose.exe')
+ Add-Content -Path $env:GITHUB_PATH -Value $binDir
+ & (Join-Path $binDir 'docker.exe') --version
+ & (Join-Path $binDir 'docker.exe') compose version
+ - name: Build and unit tests on Windows
+ run: cargo test --locked --target x86_64-pc-windows-msvc -p kiri-win -p kiri
mac-build:
needs: scope
@@ -246,6 +312,17 @@ jobs:
exit $fail
- name: The regressions table names checks that exist
run: python3 tests/lib/check-regressions.py
+ - name: Pull request gates
+ env:
+ PR_TITLE: ${{ github.event.pull_request.title }}
+ PR_BODY: ${{ github.event.pull_request.body }}
+ NO_REGRESSION: ${{ contains(github.event.pull_request.labels.*.name, 'no-regression-needed') }}
+ run: |
+ set -- --base HEAD^1 --head HEAD
+ if [ "$NO_REGRESSION" = true ]; then
+ set -- "$@" --skip-issue-check
+ fi
+ python3 scripts/ci/check-pr-gates.py "$@"
- name: The CI scripts' own tests
run: python3 -m unittest discover -s scripts/ci -p 'test_*.py'
diff --git a/RELEASES.md b/RELEASES.md
index 2bac184b..68948069 100644
--- a/RELEASES.md
+++ b/RELEASES.md
@@ -25,7 +25,11 @@ maker's own build machines.
run:
- Mac: `cargo xtask guest`, `cargo xtask release` and `cargo xtask dmg`
(the VM's guest, the signed app, the disk image; all in `xtask/`), then
- Apple's notarization (`xcrun notarytool`)
+ `python3 scripts/release-gate-mac.py target/Kiri.app` on Apple silicon
+ hardware (checks the bundled guest assets, initramfs repair and resize
+ tools, ext4 template superblock, and code signature, boots the packaged
+ app in an isolated `/tmp` sandbox to run `tests/disk-grow.py`, and writes
+ a JSON pass receipt), followed by Apple's notarisation (`xcrun notarytool`)
- Windows: `cargo xtask msi` (the installer, from `installer/windows`)
- Linux: `scripts/ci/linux-build.sh` (all `.deb` and `.rpm` packages),
then `packaging/linux/test-host.sh`, which installs them on Ubuntu and
diff --git a/crates/kiri/src/daemon/localtime.rs b/crates/kiri/src/daemon/localtime.rs
index a8dbe8df..cc938be6 100644
--- a/crates/kiri/src/daemon/localtime.rs
+++ b/crates/kiri/src/daemon/localtime.rs
@@ -571,4 +571,54 @@ mod tests {
let _ = fs::remove_dir_all(&root);
}
+
+ #[test]
+ fn kiri_linux_script_populates_zoneinfo_and_valid_utc_tzif2() {
+ let script_path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../scripts/kiri-linux.sh");
+ let script = fs::read_to_string(&script_path).expect("read scripts/kiri-linux.sh");
+ let func_start = script.find("write_utc_tzif() {").expect("write_utc_tzif in kiri-linux.sh");
+ let func_end = script[func_start..].find("\n}\n").expect("end of write_utc_tzif") + func_start + 3;
+ let tz_start = script.find("if [ -d /usr/share/zoneinfo ]; then").expect("zoneinfo block in kiri-linux.sh");
+ let tz_end = script[tz_start..].find("\ntar -C ").expect("tar line in kiri-linux.sh") + tz_start;
+ let snippet = format!(
+ "set -eu\n{}\n{}\n",
+ &script[func_start..func_end],
+ script[tz_start..tz_end]
+ .replace("if [ -d /usr/share/zoneinfo ]; then", "if [ -d \"$host_zinfo\" ]; then")
+ .replace("cp -a /usr/share/zoneinfo/.", "cp -a \"$host_zinfo\"/."),
+ );
+
+ // 1. Minimal build environment without host /usr/share/zoneinfo: synthesises RFC 8536 UTC TZif2.
+ let root = test_root("kiri-linux-minimal");
+ let status = std::process::Command::new("/bin/sh")
+ .args(["-c", &snippet])
+ .env("root", &root)
+ .env("host_zinfo", root.join("no-host-zoneinfo"))
+ .status()
+ .expect("run kiri-linux.sh timezone snippet");
+ assert!(status.success());
+ assert_valid_utc_tzif2(&fs::read(root.join("usr/share/zoneinfo/Etc/UTC")).unwrap());
+ assert_valid_utc_tzif2(&fs::read(root.join("usr/share/zoneinfo/UTC")).unwrap());
+ assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Etc/UTC"));
+ assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Etc/UTC\n");
+ let _ = fs::remove_dir_all(&root);
+
+ // 2. Host with /usr/share/zoneinfo: copies zoneinfo tree and links /etc/localtime.
+ let root = test_root("kiri-linux-host-tz");
+ let host_zinfo = root.join("fake-host-zoneinfo");
+ fs::create_dir_all(host_zinfo.join("Europe")).unwrap();
+ fs::write(host_zinfo.join("Europe/London"), &UTC_TZIF2).unwrap();
+ let status = std::process::Command::new("/bin/sh")
+ .args(["-c", &snippet])
+ .env("root", &root)
+ .env("host_zinfo", &host_zinfo)
+ .status()
+ .expect("run kiri-linux.sh timezone snippet with host zoneinfo");
+ assert!(status.success());
+ assert_eq!(fs::read(root.join("usr/share/zoneinfo/Europe/London")).unwrap(), UTC_TZIF2);
+ assert_valid_utc_tzif2(&fs::read(root.join("usr/share/zoneinfo/Etc/UTC")).unwrap());
+ assert_eq!(fs::read_link(root.join("etc/localtime")).unwrap(), Path::new("/usr/share/zoneinfo/Etc/UTC"));
+ assert_eq!(fs::read_to_string(root.join("etc/timezone")).unwrap(), "Etc/UTC\n");
+ let _ = fs::remove_dir_all(&root);
+ }
}
diff --git a/crates/kiri/src/daemon/storage.rs b/crates/kiri/src/daemon/storage.rs
index c4e7c862..f1f0e7a0 100644
--- a/crates/kiri/src/daemon/storage.rs
+++ b/crates/kiri/src/daemon/storage.rs
@@ -497,6 +497,12 @@ fn effective_vm_in_use(
(Some(raw.saturating_add(overhead)), clamped_update)
}
+#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
+fn statvfs_bytes_from_counts(blocks: u64, bfree: u64, frsize: u64, bsize: u64) -> (u64, u64) {
+ let unit = if frsize > 0 { frsize } else { bsize };
+ (blocks.saturating_sub(bfree).saturating_mul(unit), blocks.saturating_mul(unit))
+}
+
#[cfg(target_os = "linux")]
fn statvfs_usage(path: &Path) -> Option<(u64, u64)> {
use std::os::unix::ffi::OsStrExt;
@@ -506,10 +512,7 @@ fn statvfs_usage(path: &Path) -> Option<(u64, u64)> {
if unsafe { libc::statvfs(c.as_ptr(), &mut s) } != 0 {
return None;
}
- let frsize = if s.f_frsize > 0 { s.f_frsize as u64 } else { s.f_bsize as u64 };
- let blocks = s.f_blocks as u64;
- let bfree = s.f_bfree as u64;
- Some((blocks.saturating_sub(bfree).saturating_mul(frsize), blocks.saturating_mul(frsize)))
+ Some(statvfs_bytes_from_counts(s.f_blocks as u64, s.f_bfree as u64, s.f_frsize as u64, s.f_bsize as u64))
}
#[derive(Default)]
@@ -1401,4 +1404,20 @@ mod tests {
assert!(max_ext4_overhead(256 << 30, 64 << 30) <= (4 << 30) + (512 << 20));
let _ = std::fs::remove_dir_all(&d);
}
+
+ #[test]
+ fn statvfs_usage_counts_bfree_not_bavail_root_reserve() {
+ // 1 TiB sparse WSL ext4.vhdx with 5% root-reserved blocks (~51.2 GiB):
+ // bfree excludes only truly allocated blocks, whereas bavail also subtracts
+ // root's reserve (#190).
+ let blocks = 268_435_456u64; // 1 TiB in 4 KiB blocks
+ let used_blocks = 1_048_576u64; // 4 GiB actually used
+ let bfree = blocks - used_blocks;
+ let _bavail = bfree - (blocks / 20); // ~51.2 GiB lower than bfree
+ let (in_use, capacity) = statvfs_bytes_from_counts(blocks, bfree, 4096, 4096);
+ assert_eq!(in_use, 4 << 30);
+ assert_eq!(capacity, 1 << 40);
+ // Falls back to f_bsize when f_frsize is 0.
+ assert_eq!(statvfs_bytes_from_counts(1000, 750, 0, 4096), (250 * 4096, 1000 * 4096));
+ }
}
diff --git a/crates/kiri/src/ui/assemble.rs b/crates/kiri/src/ui/assemble.rs
index f5103f75..df18fb1c 100644
--- a/crates/kiri/src/ui/assemble.rs
+++ b/crates/kiri/src/ui/assemble.rs
@@ -549,11 +549,25 @@ mod tests {
// Escapes outside strings, custom property values: tight_css's edge cases.
"",
];
+ let py = if cfg!(windows) { "python" } else { "python3" };
+ if !std::process::Command::new(py)
+ .arg("--version")
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .status()
+ .is_ok_and(|s| s.success())
+ {
+ eprintln!("no {py}: skipped");
+ return;
+ }
for page in cases {
- let Ok(mut child) = std::process::Command::new("python3").arg(script).arg("--strip").stdin(std::process::Stdio::piped()).stdout(std::process::Stdio::piped()).spawn() else {
- eprintln!("no python3: skipped");
- return;
- };
+ let mut child = std::process::Command::new(py)
+ .arg(script)
+ .arg("--strip")
+ .stdin(std::process::Stdio::piped())
+ .stdout(std::process::Stdio::piped())
+ .spawn()
+ .expect("spawn python for ui-test.py --strip");
let mut stdin = child.stdin.take().unwrap();
let input = page.to_owned();
let writer = std::thread::spawn(move || stdin.write_all(input.as_bytes()));
diff --git a/crates/kiri/src/ui/compose.rs b/crates/kiri/src/ui/compose.rs
index 3ed77554..f266a8c5 100644
--- a/crates/kiri/src/ui/compose.rs
+++ b/crates/kiri/src/ui/compose.rs
@@ -1002,8 +1002,9 @@ pub fn environment(out: &str) -> Vec<(String, String)> {
secret_name(k) && first.starts_with("-----BEGIN ") && first.ends_with("-----") && !v.lines().skip(1).any(|l| l.starts_with("-----END "))
});
let after = |k: &str| vars.last().is_none_or(|(p, _)| p.as_str() < k);
+ let padding = |v: &str| !v.is_empty() && v.chars().all(|c| c == '=');
match l.split_once('=') {
- Some((k, v)) if name(k) && !v.chars().all(|c| c == '=') && after(k) && !open => vars.push((k.to_owned(), v.to_owned())),
+ Some((k, v)) if name(k) && !padding(v) && after(k) && !open => vars.push((k.to_owned(), v.to_owned())),
_ => {
if let Some((_, v)) = vars.last_mut() {
v.push('\n');
@@ -7158,6 +7159,9 @@ mod tests {
// A plain value that says `-----BEGIN ` takes nothing after it.
let v = environment("NOTE=-----BEGIN here\nWEB_PASSWORD=web1\n");
assert_eq!(v, [("NOTE".to_owned(), "-----BEGIN here".to_owned()), ("WEB_PASSWORD".to_owned(), "web1".to_owned())]);
+ // An empty variable (`HOME=` on Windows) stays its own entry rather than gluing onto the variable before it.
+ let v = environment("GOOGLE_CREDENTIALS=./creds.json\nHOME=\nNUM_TOKEN=8080\n");
+ assert_eq!(v, [("GOOGLE_CREDENTIALS".to_owned(), "./creds.json".to_owned()), ("HOME".to_owned(), String::new()), ("NUM_TOKEN".to_owned(), "8080".to_owned())]);
}
#[test]
@@ -8615,6 +8619,7 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
+ #[cfg(unix)]
#[test]
fn a_real_check_that_takes_too_long_says_so() {
// `config --quiet` (the real values' check) hangs; every other run is Compose's own.
@@ -8873,6 +8878,7 @@ mod tests {
}
/// A docker CLI that counts its runs in `KIRI_T_COUNT`'s file.
+ #[cfg(unix)]
fn counted() -> io::Result {
let docker = client::docker_cli().expect("a docker CLI");
let log = std::env::temp_dir().join(format!("kiri-compose-count-{}", std::process::id()));
@@ -8898,6 +8904,7 @@ mod tests {
}
/// Every docker CLI run `counted` made.
+ #[cfg(unix)]
fn count_all() -> usize {
let log = std::env::temp_dir().join(format!("kiri-compose-count-{}", std::process::id()));
std::fs::read_to_string(log).unwrap_or_default().lines().count()
@@ -9040,6 +9047,7 @@ mod tests {
let _ = std::fs::remove_dir_all(&d);
}
+ #[cfg(unix)]
#[test]
fn twenty_by_name_projects_cost_no_compose_run_on_an_unchanged_poll() {
let _one = LOOSE_TEST.lock().unwrap_or_else(|e| e.into_inner());
diff --git a/scripts/ci/check-pr-gates.py b/scripts/ci/check-pr-gates.py
new file mode 100755
index 00000000..4700dfe4
--- /dev/null
+++ b/scripts/ci/check-pr-gates.py
@@ -0,0 +1,595 @@
+#!/usr/bin/env python3
+"""Mechanical pull request gates for Kiri's test and regression invariants.
+
+1. No silent `KIRI_TEST_*` early-return skips in Rust unit tests:
+ Scans `crates/` and `xtask/` for non-`#[ignore]` `#[test]` functions (and
+ `#[cfg(test)]` helpers) that read a `KIRI_TEST_*` environment variable not
+ spawned by `.env(...)` in the same file and return early instead of running
+ or failing. Child-process re-entry helpers that spawn `current_exe()` with
+ `.env(...)` in the same file are permitted.
+
+2. Closing issue keywords require a regression entry:
+ When `--base` and `--head` (or `PR_TITLE` / `PR_BODY`) are given, every
+ same-repo `#N` matched by GitHub's closing keywords (`fix`, `fixes`, `fixed`,
+ `close`, `closes`, `closed`, `resolve`, `resolves`, `resolved`) in commit
+ messages in `base..head`, `PR_TITLE`, or `PR_BODY` must appear in the second
+ column of `tests/regressions.tsv`, unless `--skip-issue-check` is set (from
+ the `no-regression-needed` pull request label).
+
+Standard library only.
+
+ python3 scripts/ci/check-pr-gates.py [--base HEAD^1 --head HEAD] [--skip-issue-check]
+"""
+import argparse
+import os
+import pathlib
+import re
+import subprocess
+import sys
+
+REPO = pathlib.Path(__file__).resolve().parent.parent.parent
+
+IDENT = re.compile(r"[^\W\d]\w*")
+RAW_STR = re.compile(r'(?:b|c)?r(#*)"')
+NUMBER = re.compile(r"\d[\w]*(?:\.\d[\w]*)?")
+CLOSING_ISSUE = re.compile(
+ r"(?", re.DOTALL)
+
+# KIRI_TEST_REGISTRY selects the container image mirror rather than gating execution.
+NON_SKIP_ENVS = frozenset({"KIRI_TEST_REGISTRY"})
+
+
+class Tok:
+ __slots__ = ("kind", "text", "line")
+
+ def __init__(self, kind, text, line):
+ self.kind, self.text, self.line = kind, text, line
+
+
+def tokenize_rust(src):
+ toks = []
+ i, n, line = 0, len(src), 1
+ while i < n:
+ c = src[i]
+ if c == "\n":
+ line += 1
+ i += 1
+ elif c.isspace():
+ i += 1
+ elif src.startswith("//", i):
+ j = src.find("\n", i)
+ i = n if j < 0 else j
+ elif src.startswith("/*", i):
+ depth, j, start = 0, i, line
+ while j < n:
+ if src.startswith("/*", j):
+ depth += 1
+ j += 2
+ elif src.startswith("*/", j):
+ depth -= 1
+ j += 2
+ if depth == 0:
+ break
+ else:
+ if src[j] == "\n":
+ line += 1
+ j += 1
+ if depth != 0:
+ raise ValueError(f"unclosed block comment from line {start}")
+ i = j
+ elif (m := RAW_STR.match(src, i)) is not None:
+ close = '"' + m.group(1)
+ j = src.find(close, m.end())
+ if j < 0:
+ raise ValueError(f"unclosed raw string from line {line}")
+ text = src[i : j + len(close)]
+ toks.append(Tok("str", text, line))
+ line += text.count("\n")
+ i = j + len(close)
+ elif c == '"' or (c in "bc" and src.startswith('"', i + 1)):
+ j = i + (1 if c == '"' else 2)
+ while j < n and src[j] != '"':
+ j += 2 if src[j] == "\\" else 1
+ if j >= n:
+ raise ValueError(f"unclosed string from line {line}")
+ text = src[i : j + 1]
+ toks.append(Tok("str", text, line))
+ line += text.count("\n")
+ i = j + 1
+ elif c == "'" or (c == "b" and src.startswith("'", i + 1)):
+ q = i if c == "'" else i + 1
+ if src.startswith("\\", q + 1):
+ j = src.find("'", q + 3)
+ if j < 0 or "\n" in src[q:j]:
+ raise ValueError(f"unclosed char literal on line {line}")
+ toks.append(Tok("char", src[i : j + 1], line))
+ i = j + 1
+ elif q + 2 < n and src[q + 2] == "'" and src[q + 1] != "\n":
+ toks.append(Tok("char", src[i : q + 3], line))
+ i = q + 3
+ elif c == "'" and (m := IDENT.match(src, q + 1)) is not None:
+ toks.append(Tok("life", src[i : m.end()], line))
+ i = m.end()
+ else:
+ toks.append(Tok("punct", c, line))
+ i += 1
+ elif c == "r" and src.startswith("#", i + 1) and (m := IDENT.match(src, i + 2)) is not None:
+ toks.append(Tok("ident", src[i + 2 : m.end()], line))
+ i = m.end()
+ elif (m := IDENT.match(src, i)) is not None:
+ toks.append(Tok("ident", m.group(), line))
+ i = m.end()
+ elif c.isdigit():
+ m = NUMBER.match(src, i)
+ toks.append(Tok("num", m.group(), line))
+ i = m.end()
+ else:
+ toks.append(Tok("punct", c, line))
+ i += 1
+ return toks
+
+
+def match_brackets(toks):
+ opens, closes = "([{", ")]}"
+ pairs, stack = {}, []
+ for idx, t in enumerate(toks):
+ if t.kind != "punct":
+ continue
+ if t.text in opens:
+ stack.append(idx)
+ elif t.text in closes:
+ if not stack or opens.index(toks[stack[-1]].text) != closes.index(t.text):
+ raise ValueError(f"unbalanced {t.text!r} on line {t.line}")
+ o = stack.pop()
+ pairs[o], pairs[idx] = idx, o
+ if stack:
+ raise ValueError(f"unclosed {toks[stack[-1]].text!r} from line {toks[stack[-1]].line}")
+ return pairs
+
+
+def str_value(tok):
+ t = tok.text
+ m = RAW_STR.match(t)
+ if m:
+ return t[m.end() : len(t) - 1 - len(m.group(1))]
+ if t[0] in "bc":
+ t = t[1:]
+ return t[1:-1].replace("\\\\", "\\").replace('\\"', '"')
+
+
+def _attr_is_test(tokens):
+ if not tokens:
+ return False
+ if len(tokens) == 1 and tokens[0].kind == "ident" and tokens[0].text == "test":
+ return True
+ if tokens[-1].kind == "ident" and tokens[-1].text == "test":
+ if all(t.kind == "ident" or t.text == ":" for t in tokens[:-1]):
+ return True
+ if tokens[0].kind == "ident" and tokens[0].text == "cfg_attr":
+ return any(t.kind == "ident" and t.text == "test" for t in tokens[1:])
+ return False
+
+
+def _attr_is_ignore(tokens):
+ if not tokens:
+ return False
+ if tokens[0].kind == "ident" and tokens[0].text == "ignore":
+ return True
+ if tokens[0].kind == "ident" and tokens[0].text == "cfg_attr":
+ return any(t.kind == "ident" and t.text == "ignore" for t in tokens[1:])
+ return False
+
+
+def _attr_mentions_cfg_test(tokens):
+ if len(tokens) >= 4 and tokens[0].kind == "ident" and tokens[0].text == "cfg":
+ return any(t.kind == "ident" and t.text == "test" for t in tokens[1:])
+ return False
+
+
+def _collect_consts(toks, lo, hi):
+ """Finds `const NAME: ... = "KIRI_TEST_...";` bindings inside `toks[lo:hi]`."""
+ consts = {}
+ i = lo
+ while i + 5 < hi:
+ if toks[i].kind == "ident" and toks[i].text == "const" and toks[i + 1].kind == "ident":
+ name = toks[i + 1].text
+ j = i + 2
+ while j < hi and toks[j].text != ";" and toks[j].text != "=":
+ j += 1
+ if j + 1 < hi and toks[j].text == "=" and toks[j + 1].kind == "str":
+ val = str_value(toks[j + 1])
+ if val.startswith("KIRI_TEST_"):
+ consts[name] = val
+ i += 1
+ return consts
+
+
+def _resolve_env_arg(toks, arg_lo, arg_hi, consts):
+ if arg_lo >= arg_hi:
+ return None
+ # Direct string literal: "KIRI_TEST_..." or &str reference
+ for k in range(arg_lo, min(arg_lo + 3, arg_hi)):
+ if toks[k].kind == "str":
+ val = str_value(toks[k])
+ return val if val.startswith("KIRI_TEST_") and val not in NON_SKIP_ENVS else None
+ if toks[k].kind == "ident" and toks[k].text in consts:
+ val = consts[toks[k].text]
+ return val if val not in NON_SKIP_ENVS else None
+ return None
+
+
+def _collect_spawned_envs(toks, pairs, lo, hi, consts):
+ """Finds `KIRI_TEST_*` names passed to `.env(NAME, ...)` in `toks[lo:hi]`."""
+ spawned = set()
+ i = lo
+ while i + 3 < hi:
+ if (
+ toks[i].text == "."
+ and toks[i + 1].kind == "ident"
+ and toks[i + 1].text == "env"
+ and toks[i + 2].text == "("
+ and (i + 2) in pairs
+ ):
+ close = pairs[i + 2]
+ comma = next((k for k in range(i + 3, close) if toks[k].text == ","), close)
+ val = _resolve_env_arg(toks, i + 3, comma, consts)
+ if val:
+ spawned.add(val)
+ i += 1
+ return spawned
+
+
+def _collect_env_reads(toks, pairs, lo, hi, consts):
+ """Finds `(env_name, line)` read via `var`, `var_os`, or `option_env!` in `toks[lo:hi]`."""
+ reads = []
+ i = lo
+ while i + 2 < hi:
+ # var(...) / var_os(...)
+ if (
+ toks[i].kind == "ident"
+ and toks[i].text in ("var", "var_os")
+ and toks[i + 1].text == "("
+ and (i + 1) in pairs
+ ):
+ # Exclude method calls like `foo.var(...)` (unless `::var(...)` or bare `var(...)`).
+ if i == lo or toks[i - 1].text != ".":
+ close = pairs[i + 1]
+ val = _resolve_env_arg(toks, i + 2, close, consts)
+ if val:
+ reads.append((val, toks[i].line))
+ # option_env!("KIRI_TEST_...")
+ elif (
+ i + 3 < hi
+ and toks[i].kind == "ident"
+ and toks[i].text == "option_env"
+ and toks[i + 1].text == "!"
+ and toks[i + 2].text in "([{"
+ and (i + 2) in pairs
+ ):
+ close = pairs[i + 2]
+ val = _resolve_env_arg(toks, i + 3, close, consts)
+ if val:
+ reads.append((val, toks[i].line))
+ i += 1
+ return reads
+
+
+def scan_rust_file(text, rel_path):
+ """Scans one Rust source file for silent `KIRI_TEST_*` skips in unit tests."""
+ try:
+ toks = tokenize_rust(text)
+ pairs = match_brackets(toks)
+ except ValueError as exc:
+ return [f"{rel_path}: cannot tokenise Rust source: {exc}"]
+
+ file_consts = _collect_consts(toks, 0, len(toks))
+ functions = [] # (fn_name, fn_line, is_test, is_ignored, in_cfg_test, body_lo, body_hi, consts)
+
+ def walk(lo, hi, in_cfg_test, scope_consts):
+ local_consts = dict(scope_consts)
+ local_consts.update(_collect_consts(toks, lo, hi))
+ i = lo
+ # Inner `#![cfg(test)]` attribute at module/file top.
+ while (
+ i + 2 < hi
+ and toks[i].text == "#"
+ and toks[i + 1].text == "!"
+ and toks[i + 2].text == "["
+ and (i + 2) in pairs
+ ):
+ close = pairs[i + 2]
+ if _attr_mentions_cfg_test(toks[i + 3 : close]):
+ in_cfg_test = True
+ i = close + 1
+
+ while i < hi:
+ attrs = []
+ while (
+ i + 1 < hi
+ and toks[i].text == "#"
+ and toks[i + 1].text == "["
+ and (i + 1) in pairs
+ ):
+ close = pairs[i + 1]
+ attrs.append(toks[i + 2 : close])
+ i = close + 1
+ if i >= hi:
+ break
+ j = i
+ if j < hi and toks[j].kind == "ident" and toks[j].text == "pub":
+ j += 1
+ if j < hi and toks[j].text == "(" and j in pairs:
+ j = pairs[j] + 1
+ while j < hi and toks[j].kind == "ident" and toks[j].text in ("async", "unsafe", "const", "extern"):
+ j += 1
+ if j < hi and toks[j].kind == "str":
+ j += 1
+
+ item_cfg_test = in_cfg_test or any(_attr_mentions_cfg_test(a) for a in attrs)
+
+ if j + 1 < hi and toks[j].kind == "ident" and toks[j].text == "mod" and toks[j + 1].kind == "ident":
+ if j + 2 < hi and toks[j + 2].text == "{" and (j + 2) in pairs:
+ close = pairs[j + 2]
+ walk(j + 3, close, item_cfg_test, local_consts)
+ i = close + 1
+ continue
+
+ if j + 1 < hi and toks[j].kind == "ident" and toks[j].text == "fn" and toks[j + 1].kind == "ident":
+ fn_name = toks[j + 1].text
+ fn_line = toks[j].line
+ # Find the function body `{ ... }` or `;` (for trait declarations).
+ k = j + 2
+ body_open = None
+ while k < hi:
+ if toks[k].text == ";" and body_open is None:
+ i = k + 1
+ break
+ if toks[k].text in "([" and k in pairs:
+ k = pairs[k] + 1
+ continue
+ if toks[k].text == "{" and k in pairs:
+ # Might be inside a `where` bound only if rare; first top-level `{` is the fn body.
+ body_open = k
+ break
+ k += 1
+ if body_open is not None:
+ body_close = pairs[body_open]
+ fn_consts = dict(local_consts)
+ fn_consts.update(_collect_consts(toks, body_open + 1, body_close))
+ is_test = any(_attr_is_test(a) for a in attrs)
+ is_ignored = any(_attr_is_ignore(a) for a in attrs)
+ functions.append(
+ (
+ fn_name,
+ fn_line,
+ is_test,
+ is_ignored,
+ item_cfg_test,
+ body_open + 1,
+ body_close,
+ fn_consts,
+ )
+ )
+ # Also walk nested items inside the function body.
+ walk(body_open + 1, body_close, item_cfg_test, fn_consts)
+ i = body_close + 1
+ continue
+
+ if toks[i].text in "([{" and i in pairs:
+ i = pairs[i] + 1
+ else:
+ i += 1
+
+ walk(0, len(toks), False, file_consts)
+
+ # Collect KIRI_TEST_* variables spawned via `.env(...)` in non-ignored functions.
+ spawned = set()
+ for _name, _line, _is_test, is_ignored, _in_cfg_test, b_lo, b_hi, fn_consts in functions:
+ if not is_ignored:
+ spawned |= _collect_spawned_envs(toks, pairs, b_lo, b_hi, fn_consts)
+
+ # Map cfg(test) helper functions that read unspawned KIRI_TEST_* variables.
+ helper_unspawned = {}
+ for fn_name, _fn_line, is_test, is_ignored, in_cfg_test, b_lo, b_hi, fn_consts in functions:
+ if is_ignored or is_test or not in_cfg_test:
+ continue
+ reads = [(v, ln) for v, ln in _collect_env_reads(toks, pairs, b_lo, b_hi, fn_consts) if v not in spawned]
+ if reads:
+ helper_unspawned[fn_name] = reads
+
+ errors = []
+ seen = set()
+ for fn_name, fn_line, is_test, is_ignored, in_cfg_test, b_lo, b_hi, fn_consts in functions:
+ if is_ignored:
+ continue
+ body_toks = toks[b_lo:b_hi]
+ has_return = any(t.kind == "ident" and t.text == "return" for t in body_toks)
+ has_soft_probe = any(
+ t.kind == "ident" and t.text in ("ok", "is_err", "is_none", "unwrap_or", "unwrap_or_default", "unwrap_or_else")
+ for t in body_toks
+ )
+ if is_test:
+ for env_name, read_line in _collect_env_reads(toks, pairs, b_lo, b_hi, fn_consts):
+ if env_name not in spawned and (has_return or has_soft_probe):
+ key = (rel_path, read_line, env_name)
+ if key not in seen:
+ seen.add(key)
+ errors.append(
+ f"{rel_path}:{read_line}: #[test] fn {fn_name} (line {fn_line}) reads {env_name} "
+ "and can return without running; remove the KIRI_TEST_* gate so the test always "
+ "executes, or mark manual-only tests #[ignore]"
+ )
+ if has_return and helper_unspawned:
+ called = {
+ body_toks[idx].text
+ for idx in range(len(body_toks) - 1)
+ if body_toks[idx].kind == "ident"
+ and body_toks[idx + 1].text == "("
+ and body_toks[idx].text in helper_unspawned
+ }
+ for helper in sorted(called):
+ for env_name, read_line in helper_unspawned[helper]:
+ key = (rel_path, read_line, env_name)
+ if key not in seen:
+ seen.add(key)
+ errors.append(
+ f"{rel_path}:{read_line}: test helper fn {helper} (called by #[test] fn "
+ f"{fn_name} at line {fn_line}) reads {env_name} for an early-return skip; "
+ "remove the KIRI_TEST_* gate or mark manual-only tests #[ignore]"
+ )
+ elif in_cfg_test and has_return:
+ for env_name, read_line in _collect_env_reads(toks, pairs, b_lo, b_hi, fn_consts):
+ if env_name not in spawned:
+ key = (rel_path, read_line, env_name)
+ if key not in seen:
+ seen.add(key)
+ errors.append(
+ f"{rel_path}:{read_line}: test helper fn {fn_name} (line {fn_line}) reads "
+ f"{env_name} and returns early; silent KIRI_TEST_* skips are banned"
+ )
+
+ return errors
+
+
+def check_silent_test_skips(repo=REPO):
+ repo = pathlib.Path(repo)
+ errors = []
+ for sub in ("crates", "xtask"):
+ base = repo / sub
+ if not base.is_dir():
+ continue
+ for rs_path in sorted(base.rglob("*.rs")):
+ rel = rs_path.relative_to(repo).as_posix()
+ errors.extend(scan_rust_file(rs_path.read_text(encoding="utf-8"), rel))
+ return errors
+
+
+def extract_closing_issues(text):
+ """Returns ordered unique list of `#N` strings matched by GitHub closing keywords."""
+ if not text:
+ return []
+ cleaned = HTML_COMMENT.sub(" ", text)
+ seen = set()
+ out = []
+ for m in CLOSING_ISSUE.finditer(cleaned):
+ issue = f"#{int(m.group(1))}"
+ if issue not in seen:
+ seen.add(issue)
+ out.append(issue)
+ return out
+
+
+def regressions_issues(table_path):
+ issues = set()
+ for line in pathlib.Path(table_path).read_text(encoding="utf-8").splitlines():
+ if not line.strip() or line.startswith("#"):
+ continue
+ cols = line.split("\t")
+ if len(cols) == 3 and re.fullmatch(r"#[0-9]+", cols[1]) and cols[2].strip():
+ issues.add(cols[1])
+ return issues
+
+
+def check_closing_issues(repo=REPO, commit_messages=(), pr_title="", pr_body="", table_path=None):
+ repo = pathlib.Path(repo)
+ table = pathlib.Path(table_path) if table_path is not None else repo / "tests/regressions.tsv"
+ covered = regressions_issues(table)
+ sources = []
+ for msg in commit_messages:
+ for issue in extract_closing_issues(msg):
+ sources.append((issue, "commit message"))
+ for issue in extract_closing_issues(pr_title):
+ sources.append((issue, "PR title"))
+ for issue in extract_closing_issues(pr_body):
+ sources.append((issue, "PR description"))
+
+ by_issue = {}
+ order = []
+ for issue, where in sources:
+ if issue not in by_issue:
+ by_issue[issue] = []
+ order.append(issue)
+ if where not in by_issue[issue]:
+ by_issue[issue].append(where)
+
+ errors = []
+ for issue in order:
+ if issue not in covered:
+ places = ", ".join(by_issue[issue])
+ errors.append(
+ f"tests/regressions.tsv: missing regression check for {issue} (referenced in {places}). "
+ f"Add an executable check for {issue} to tests/regressions.tsv, or add the pull request "
+ "label no-regression-needed if no regression test applies."
+ )
+ return errors
+
+
+def git_commit_messages(repo, base, head):
+ out = subprocess.run(
+ ["git", "log", "--format=%B%x00", f"{base}..{head}"],
+ cwd=repo,
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout
+ return [chunk for chunk in out.split("\x00") if chunk.strip()]
+
+
+def write_summary(errors):
+ summary_path = os.environ.get("GITHUB_STEP_SUMMARY")
+ if not summary_path or not errors:
+ return
+ lines = ["### Pull request gate failures", ""]
+ lines.extend(f"- {err}" for err in errors)
+ lines.append("")
+ with open(summary_path, "a", encoding="utf-8") as f:
+ f.write("\n".join(lines))
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=pathlib.Path, default=REPO)
+ parser.add_argument("--base", default=None, help="Base git revision (for example HEAD^1)")
+ parser.add_argument("--head", default=None, help="Head git revision (for example HEAD)")
+ parser.add_argument("--pr-title", default=None, help="Pull request title (defaults to $PR_TITLE)")
+ parser.add_argument("--pr-body", default=None, help="Pull request body (defaults to $PR_BODY)")
+ parser.add_argument(
+ "--skip-issue-check",
+ action="store_true",
+ help="Skip the Fixes/Closes/Resolves #N -> tests/regressions.tsv check (label no-regression-needed)",
+ )
+ args = parser.parse_args(argv)
+
+ if (args.base is None) != (args.head is None):
+ parser.error("--base and --head must be given together")
+
+ errors = check_silent_test_skips(args.repo)
+
+ pr_title = args.pr_title if args.pr_title is not None else os.environ.get("PR_TITLE", "")
+ pr_body = args.pr_body if args.pr_body is not None else os.environ.get("PR_BODY", "")
+ if not args.skip_issue_check and (args.base is not None or pr_title or pr_body):
+ commits = git_commit_messages(args.repo, args.base, args.head) if args.base is not None else ()
+ errors.extend(
+ check_closing_issues(
+ args.repo,
+ commit_messages=commits,
+ pr_title=pr_title,
+ pr_body=pr_body,
+ )
+ )
+
+ for err in errors:
+ print(err)
+ write_summary(errors)
+ if errors:
+ print(f"check-pr-gates: {len(errors)} problem(s) found")
+ return 1
+ print("check-pr-gates: all checks passed")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/test_check_pr_gates.py b/scripts/ci/test_check_pr_gates.py
new file mode 100644
index 00000000..26155c1b
--- /dev/null
+++ b/scripts/ci/test_check_pr_gates.py
@@ -0,0 +1,300 @@
+#!/usr/bin/env python3
+"""Unit tests for scripts/ci/check-pr-gates.py and tests/lib/check-regressions.py.
+
+ python3 -m unittest discover -s scripts/ci -p 'test_check_pr_gates.py'
+"""
+import importlib.util
+import os
+import pathlib
+import subprocess
+import tempfile
+import unittest
+
+HERE = pathlib.Path(__file__).resolve().parent
+REPO = HERE.parent.parent
+
+_gates_spec = importlib.util.spec_from_file_location("check_pr_gates", HERE / "check-pr-gates.py")
+gates = importlib.util.module_from_spec(_gates_spec)
+_gates_spec.loader.exec_module(gates)
+
+_reg_spec = importlib.util.spec_from_file_location("check_regressions", REPO / "tests/lib/check-regressions.py")
+reg = importlib.util.module_from_spec(_reg_spec)
+_reg_spec.loader.exec_module(reg)
+
+
+class SilentSkipGateTests(unittest.TestCase):
+ def test_flags_let_else_early_return_in_unit_test(self):
+ src = """
+ #[cfg(test)]
+ mod tests {
+ #[test]
+ fn grows_when_configured() {
+ let Ok(dev) = std::env::var("KIRI_TEST_EXT4_DEV") else {
+ return;
+ };
+ assert!(!dev.is_empty());
+ }
+ }
+ """
+ errs = gates.scan_rust_file(src, "crates/kiri-init/src/linux/disk.rs")
+ self.assertEqual(len(errs), 1)
+ self.assertIn("KIRI_TEST_EXT4_DEV", errs[0])
+ self.assertIn("grows_when_configured", errs[0])
+
+ def test_flags_const_alias_and_helper_wrapped_skip(self):
+ src = """
+ #[cfg(test)]
+ mod tests {
+ const OPT_IN: &str = "KIRI_TEST_NEED_LOOP";
+ fn loop_dev() -> Option {
+ std::env::var(OPT_IN).ok()
+ }
+ #[test]
+ fn mounts_loop() {
+ let Some(d) = loop_dev() else { return };
+ assert!(!d.is_empty());
+ }
+ }
+ """
+ errs = gates.scan_rust_file(src, "crates/kiri/src/loop_test.rs")
+ self.assertEqual(len(errs), 1)
+ self.assertIn("KIRI_TEST_NEED_LOOP", errs[0])
+
+ def test_allows_child_process_reentry_in_same_file(self):
+ src = """
+ #[cfg(test)]
+ mod tests {
+ const CHILD: &str = "KIRI_TEST_UMASK_CHILD";
+ #[test]
+ fn runs_isolated_child() {
+ if std::env::var_os(CHILD).is_some() {
+ return;
+ }
+ let status = std::process::Command::new(std::env::current_exe().unwrap())
+ .env(CHILD, "1")
+ .status()
+ .unwrap();
+ assert!(status.success());
+ }
+ }
+ """
+ self.assertEqual(gates.scan_rust_file(src, "crates/kiri/src/umask.rs"), [])
+
+ def test_allows_split_parent_and_child_tests_in_same_file(self):
+ src = """
+ #[cfg(test)]
+ mod kill_points {
+ const CHILD: &str = "KIRI_TEST_STORE_CHILD";
+ fn in_child() {
+ let _ = std::process::Command::new("exe").env(CHILD, "/tmp/x").status();
+ }
+ #[test]
+ fn child_entry() {
+ let Some(_root) = std::env::var_os(CHILD) else { return };
+ }
+ #[test]
+ fn parent_driver() {
+ if std::env::var_os(CHILD).is_some() { return; }
+ in_child();
+ }
+ }
+ """
+ self.assertEqual(gates.scan_rust_file(src, "crates/kiri-image/src/store.rs"), [])
+
+ def test_ignored_test_allowed_and_cannot_excuse_unignored_skip(self):
+ src = """
+ #[cfg(test)]
+ mod tests {
+ #[test]
+ #[ignore = "manual stress test"]
+ fn manual_only() {
+ let Some(_) = std::env::var_os("KIRI_TEST_MANUAL") else { return };
+ let _ = std::process::Command::new("exe").env("KIRI_TEST_SNEAKY", "1");
+ }
+ #[test]
+ fn unignored_sneaky_skip() {
+ let Some(_) = std::env::var_os("KIRI_TEST_SNEAKY") else { return };
+ }
+ }
+ """
+ errs = gates.scan_rust_file(src, "crates/kiri/src/sneaky.rs")
+ self.assertEqual(len(errs), 1)
+ self.assertIn("KIRI_TEST_SNEAKY", errs[0])
+
+ def test_comments_and_plain_strings_do_not_trigger(self):
+ src = """
+ #[cfg(test)]
+ mod tests {
+ // std::env::var("KIRI_TEST_COMMENT") else { return; }
+ /* std::env::var("KIRI_TEST_BLOCK") */
+ #[test]
+ fn plain_assertion() {
+ let msg = "KIRI_TEST_LITERAL_ONLY";
+ if msg.is_empty() {
+ return;
+ }
+ assert_eq!(msg.len(), 22);
+ }
+ }
+ """
+ self.assertEqual(gates.scan_rust_file(src, "crates/kiri/src/clean.rs"), [])
+
+
+class ClosingIssuesGateTests(unittest.TestCase):
+ def test_extracts_github_closing_keywords_only(self):
+ text = (
+ "Fixes #101, closes: #202 and RESOLVED #303.\n"
+ "Also (fix #404). External: Fixes docker/cli#999, prefix #888, unfixed #777.\n"
+ ""
+ )
+ self.assertEqual(gates.extract_closing_issues(text), ["#101", "#202", "#303", "#404"])
+
+ def test_enforces_regressions_tsv_coverage_and_skip_flag(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = pathlib.Path(tmp)
+ (root / "tests").mkdir()
+ (root / "crates/demo/src").mkdir(parents=True)
+ (root / "tests/regressions.tsv").write_text(
+ "# header\ncrates/demo/src/lib.rs::guards_101\t#101\twhat broke\n",
+ encoding="utf-8",
+ )
+ (root / "crates/demo/src/lib.rs").write_text(
+ "#[test]\nfn guards_101() { assert_eq!(1, 1); }\n",
+ encoding="utf-8",
+ )
+ subprocess.run(["git", "init", "-q"], cwd=root, check=True)
+ subprocess.run(["git", "config", "user.email", "ci@example.com"], cwd=root, check=True)
+ subprocess.run(["git", "config", "user.name", "CI"], cwd=root, check=True)
+ subprocess.run(["git", "add", "."], cwd=root, check=True)
+ subprocess.run(["git", "commit", "-q", "-m", "Initial commit"], cwd=root, check=True)
+
+ (root / "crates/demo/src/lib.rs").write_text(
+ "#[test]\nfn guards_101() { assert_eq!(2, 2); }\n",
+ encoding="utf-8",
+ )
+ subprocess.run(["git", "add", "."], cwd=root, check=True)
+ subprocess.run(["git", "commit", "-q", "-m", "Engine: fix #101 and closes #202"], cwd=root, check=True)
+
+ # Missing #202 in commit message and #303 in PR body -> fails.
+ rc = gates.main(
+ [
+ "--repo",
+ str(root),
+ "--base",
+ "HEAD^1",
+ "--head",
+ "HEAD",
+ "--pr-title",
+ "Engine: repair",
+ "--pr-body",
+ "Resolves #303",
+ ]
+ )
+ self.assertEqual(rc, 1)
+
+ # With --skip-issue-check (no-regression-needed label) -> passes.
+ rc_skip = gates.main(
+ [
+ "--repo",
+ str(root),
+ "--base",
+ "HEAD^1",
+ "--head",
+ "HEAD",
+ "--pr-body",
+ "Resolves #303",
+ "--skip-issue-check",
+ ]
+ )
+ self.assertEqual(rc_skip, 0)
+
+ # Once #202 and #303 are recorded in tests/regressions.tsv -> passes without skip flag.
+ (root / "tests/regressions.tsv").write_text(
+ "# header\n"
+ "crates/demo/src/lib.rs::guards_101\t#101\tfirst\n"
+ "crates/demo/src/lib.rs::guards_202\t#202\tsecond\n"
+ "crates/demo/src/lib.rs::guards_303\t#303\tthird\n",
+ encoding="utf-8",
+ )
+ rc_ok = gates.main(
+ [
+ "--repo",
+ str(root),
+ "--base",
+ "HEAD^1",
+ "--head",
+ "HEAD",
+ "--pr-body",
+ "Resolves #303",
+ ]
+ )
+ self.assertEqual(rc_ok, 0)
+
+
+class CheckRegressionsTableTests(unittest.TestCase):
+ def test_real_repository_regressions_table_is_clean(self):
+ rows, errors = reg.check_table(REPO)
+ self.assertGreater(rows, 400)
+ self.assertEqual(errors, [])
+
+ def test_rejects_unexecuted_and_bare_paths_and_accepts_valid_targets(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = pathlib.Path(tmp)
+ for d in ("tests/ui", "scripts", "crates/kiri/src", "guest/kernel/patches"):
+ (root / d).mkdir(parents=True)
+ (root / "scripts/ui-test.py").write_text("# runner\n", encoding="utf-8")
+ (root / "tests/e2e.sh").write_text('#!/bin/bash\nt valid-shell-check "ok"\n', encoding="utf-8")
+ (root / "tests/disk-grow.py").write_text("print('standalone')\n", encoding="utf-8")
+ (root / "tests/ui/fixture.js").write_text("// helper\n", encoding="utf-8")
+ (root / "tests/ui/good.js").write_text('report(["PASS ok"]);\n', encoding="utf-8")
+ (root / "tests/ui/noreport.js").write_text("console.log('nothing');\n", encoding="utf-8")
+ (root / "guest/kernel/patches/0001-fix.patch").write_text("diff --git a/x b/x\n", encoding="utf-8")
+ (root / "crates/kiri/src/lib.rs").write_text(
+ """
+ // #[test]
+ // fn commented_out() {}
+ #[test]
+ fn real_unit_test() {}
+ #[test]
+ #[ignore = "manual"]
+ fn ignored_unit_test() {}
+ """,
+ encoding="utf-8",
+ )
+ table = root / "tests/regressions.tsv"
+ table.write_text(
+ "\n".join(
+ [
+ "valid-shell-check\t#1\tshell check",
+ "tests/ui/good.js\t#2\tui check",
+ "crates/kiri/src/lib.rs::real_unit_test\t#3\trust check",
+ "guest/kernel/patches/0001-fix.patch\t#4\tkernel patch",
+ "crates/kiri/src/lib.rs\t#5\tbare rust file",
+ "tests/disk-grow.py\t#6\tstandalone python script",
+ "crates/kiri/src/lib.rs::missing_fn\t#7\tmissing fn",
+ "crates/kiri/src/lib.rs::ignored_unit_test\t#8\tignored fn",
+ "crates/kiri/src/lib.rs::commented_out\t#9\tcommented fn",
+ "tests/ui/fixture.js\t#10\tfixture not a test",
+ "tests/ui/noreport.js\t#11\tui without report",
+ "valid-shell-check\t#12\tduplicate check",
+ ]
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ rows, errors = reg.check_table(root, table)
+ self.assertEqual(rows, 12)
+ joined = "\n".join(errors)
+ self.assertEqual(len(errors), 8, joined)
+ self.assertIn("bare Rust file crates/kiri/src/lib.rs is not allowed", joined)
+ self.assertIn("tests/disk-grow.py is not an executed CI check", joined)
+ self.assertIn("no #[test] fn missing_fn", joined)
+ self.assertIn("ignored_unit_test in crates/kiri/src/lib.rs is marked #[ignore]", joined)
+ self.assertIn("no #[test] fn commented_out", joined)
+ self.assertIn("tests/ui/fixture.js is not discovered by scripts/ui-test.py", joined)
+ self.assertIn("tests/ui/noreport.js never calls report()", joined)
+ self.assertIn("valid-shell-check is listed twice", joined)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/ci/test_release_gate_mac.py b/scripts/ci/test_release_gate_mac.py
new file mode 100644
index 00000000..141a2200
--- /dev/null
+++ b/scripts/ci/test_release_gate_mac.py
@@ -0,0 +1,236 @@
+#!/usr/bin/env python3
+"""Unit tests for scripts/release-gate-mac.py."""
+
+import importlib.util
+import json
+from pathlib import Path
+import stat
+import struct
+import subprocess
+import tempfile
+import unittest
+
+REPO = Path(__file__).resolve().parents[2]
+
+
+def _load_module():
+ path = REPO / "scripts/release-gate-mac.py"
+ spec = importlib.util.spec_from_file_location("release_gate_mac", path)
+ mod = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(mod)
+ return mod
+
+
+GATE = _load_module()
+
+
+def _make_cpio(entries: list[tuple[str, int, bytes]], *, include_trailer: bool = True) -> bytes:
+ buf = bytearray()
+ ino = 0
+
+ def add(name: str, mode: int, payload: bytes) -> None:
+ nonlocal ino
+ ino += 1
+ name_bytes = name.encode("utf-8") + b"\x00"
+ fields = [
+ ino,
+ mode,
+ 0,
+ 0,
+ 1,
+ 0,
+ len(payload),
+ 0,
+ 0,
+ 0,
+ 0,
+ len(name_bytes),
+ 0,
+ ]
+ buf.extend(b"070701")
+ for val in fields:
+ buf.extend(f"{val:08x}".encode("ascii"))
+ buf.extend(name_bytes)
+ while len(buf) % 4:
+ buf.append(0)
+ buf.extend(payload)
+ while len(buf) % 4:
+ buf.append(0)
+
+ for name, mode, payload in entries:
+ add(name, mode, payload)
+ if include_trailer:
+ ino = -1
+ add("TRAILER!!!", 0, b"")
+ return bytes(buf)
+
+
+def _write_ext4_image(path: Path, *, size: int, magic: int = 0xEF53, compat: int = 0x003C) -> None:
+ with path.open("wb") as fh:
+ fh.truncate(size)
+ sb = bytearray(1024)
+ struct.pack_into("", encoding="utf-8")
+
+ digest_a = GATE.bundle_sha256(app)
+ digest_b = GATE.bundle_sha256(app)
+ self.assertEqual(digest_a, digest_b)
+
+ exe.chmod(0o644)
+ self.assertNotEqual(digest_a, GATE.bundle_sha256(app))
+ exe.chmod(0o755)
+ self.assertEqual(digest_a, GATE.bundle_sha256(app))
+
+ exe.write_bytes(b"binary-v2")
+ digest_c = GATE.bundle_sha256(app)
+ self.assertNotEqual(digest_a, digest_c)
+
+ receipt_file = root / "receipt.json"
+ written = GATE.write_receipt(
+ receipt_file,
+ app,
+ ["guest_assets_present", "packaged_vm_disk_grow"],
+ head="a" * 40,
+ app_digest=digest_c,
+ timestamp="2026-12-02T00:00:00Z",
+ )
+ loaded = json.loads(receipt_file.read_text(encoding="utf-8"))
+ self.assertEqual(loaded, written)
+ self.assertEqual(loaded["git_head"], "a" * 40)
+ self.assertEqual(loaded["app_sha256"], digest_c)
+ self.assertEqual(loaded["timestamp"], "2026-12-02T00:00:00Z")
+ self.assertEqual(loaded["checks_passed"], ["guest_assets_present", "packaged_vm_disk_grow"])
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/scripts/ci/test_tests_scope.py b/scripts/ci/test_tests_scope.py
index 49a0f502..04932b98 100644
--- a/scripts/ci/test_tests_scope.py
+++ b/scripts/ci/test_tests_scope.py
@@ -404,6 +404,20 @@ class NotRust(unittest.TestCase):
out, res = run({"README.md": "x\n"})
self.assertFalse(res["scripts"] or res["suites_changed"])
+ def test_regression_targets_and_gate_scripts_start_scripts_job(self):
+ out, res = run(edit("crates/kiri/src/shared.rs", "let a = 1;", "let a = 10;"))
+ self.assertTrue(res["scripts"])
+ out, res = run({"tests/ui/new-check.js": 'report(["PASS ok"]);\n'})
+ self.assertTrue(res["scripts"])
+ self.assertFalse(res["suites_changed"])
+ out, res = run({"guest/kernel/patches/0012-fix.patch": "diff\n"})
+ self.assertTrue(res["scripts"])
+ self.assertEqual({s for s in ts.SYSTEMS if res[s]}, set())
+ for gate_script in ("scripts/ci/check-pr-gates.py", "scripts/release-gate-mac.py"):
+ out, res = run({gate_script: "#!/usr/bin/env python3\n"})
+ self.assertTrue(res["scripts"], gate_script)
+ self.assertEqual({s for s in ts.SYSTEMS if res[s]}, set(), gate_script)
+
if __name__ == "__main__":
unittest.main()
diff --git a/scripts/ci/tests-scope.py b/scripts/ci/tests-scope.py
index d1204a17..471b297d 100644
--- a/scripts/ci/tests-scope.py
+++ b/scripts/ci/tests-scope.py
@@ -6,10 +6,10 @@
prints, on stdout:
linux=true|false unit: the workspace's unit tests on Linux
- windows=true|false windows-build: the Windows app and CLI compile
+ windows=true|false windows-build: the build and unit tests on Windows
mac=true|false mac-build: the build and unit tests on a Mac
- scripts=true|false scripts: the suites' and scripts' own checks
- suites_changed=true|false the suites changed (the label run-tests runs them)
+ scripts=true|false scripts: the suites', scripts' and regression gates' checks
+ suites_changed=true|false the suites changed (runs e2e-linux on same-repo PRs, or with run-tests)
and, on stderr and in $GITHUB_STEP_SUMMARY when it is set, every changed file
with the jobs it starts and why.
@@ -71,7 +71,7 @@ TARGET = {
# The crates each job builds, as the workflow's commands build them:
# unit cargo test --workspace --exclude kiri-init; cargo test -p kiri-init
# mac-build cargo test --workspace --exclude kiri-init
-# windows-build cargo check --target x86_64-pc-windows-msvc -p kiri-win -p kiri
+# windows-build cargo test --target x86_64-pc-windows-msvc -p kiri-win -p kiri
# with the path dependencies each needs on that system. Change this with them.
JOBS = {
"linux": {"workspace": True, "exclude": ()},
@@ -88,8 +88,10 @@ PATHS = [
(("guest/kernel/*",), NONE, "Kiri's kernel: a runner runs its own kernel and can't start Kiri's VM"),
(("tests/*", "bench/*"), NONE, "the suites: the label run-tests runs them"),
((".github/workflows/codeql.yml", ".github/workflows/perf.yml", ".github/workflows/ui-tests.yml", "scripts/perf*", "scripts/ui-*",
- "scripts/i18n-check.py", "scripts/dmg-*", "scripts/ci/tests-scope.py", "scripts/ci/test_tests_scope.py", "scripts/ci/tests-scope-replay.py",
- "scripts/ci/page-scan.py", "scripts/ci/test_page_scan.py"), NONE, "another workflow's or job's own file"),
+ "scripts/i18n-check.py", "scripts/dmg-*", "scripts/release-gate-mac.py",
+ "scripts/ci/tests-scope.py", "scripts/ci/test_tests_scope.py", "scripts/ci/tests-scope-replay.py",
+ "scripts/ci/page-scan.py", "scripts/ci/test_page_scan.py",
+ "scripts/ci/check-pr-gates.py", "scripts/ci/test_check_pr_gates.py", "scripts/ci/test_release_gate_mac.py"), NONE, "another workflow's or job's own file"),
(("crates/kiri/kiri.entitlements", "xtask/dev-icon.swift"), frozenset({"mac"}), "the Mac app's packaging"),
(("contrib/windows/*", "installer/windows/*"), frozenset({"windows"}), "the Windows app's packaging"),
(("contrib/linux/*", "contrib/wsl/*", "packaging/linux/*", "scripts/kiri-linux.sh", "scripts/windows-engine.sh", "scripts/ci/linux-*"),
@@ -98,9 +100,13 @@ PATHS = [
def scripts_job(path):
- """The `scripts` job: the suites' and scripts' shell and Python files."""
+ """The `scripts` job: the suites, scripts, and files regressions.tsv names."""
if path.startswith(("tests/", "scripts/")) and path.endswith((".sh", ".py")):
return True
+ if path.endswith(".rs") and path.startswith(("crates/", "xtask/")):
+ return True
+ if path.startswith(("tests/ui/", "guest/kernel/patches/")):
+ return True
return path == "tests/regressions.tsv" or path.startswith("tests/lib/")
diff --git a/scripts/release-gate-mac.py b/scripts/release-gate-mac.py
new file mode 100755
index 00000000..f301dc88
--- /dev/null
+++ b/scripts/release-gate-mac.py
@@ -0,0 +1,426 @@
+#!/usr/bin/env python3
+"""Hardware release gate for a packaged macOS Kiri.app bundle.
+
+Runs on an Apple Silicon Mac before a release is notarised or published:
+
+ python3 scripts/release-gate-mac.py target/Kiri.app [--receipt target/release-gate-receipt.json]
+
+Checks:
+1. Contents/MacOS/kiri and Contents/Resources/guest/{Image,initramfs.cpio,data.img.tgz}
+ exist, initramfs.cpio contains init, sbin/e2fsck, and sbin/resize2fs, and
+ data.img.tgz unpacks to a 64 GiB sparse ext4 image without sparse_super2.
+2. `codesign --verify --deep --strict` passes on Kiri.app and Contents/MacOS/kiri
+ carries `com.apple.security.virtualization`.
+3. `tests/disk-grow.py` passes against the packaged binary and unpacked guest
+ assets inside an isolated `/tmp` sandbox without touching `~/.kiri`.
+4. Writes an atomic JSON pass receipt (`git_head`, `app_sha256`, `timestamp`,
+ `checks_passed`).
+"""
+
+import argparse
+from datetime import datetime, timezone
+import hashlib
+import json
+import os
+from pathlib import Path
+import platform
+import plistlib
+import posixpath
+import shutil
+import stat
+import struct
+import subprocess
+import sys
+import tempfile
+
+EXT4_SUPERBLOCK_OFFSET = 1024
+EXT4_SUPERBLOCK_SIZE = 1024
+EXT4_SUPER_MAGIC = 0xEF53
+EXT2_FEATURE_COMPAT_SPARSE_SUPER2 = 0x0200
+EXPECTED_TEMPLATE_BYTES = 64 << 30
+
+REQUIRED_GUEST_FILES = ("Image", "initramfs.cpio", "data.img.tgz")
+REQUIRED_INITRAMFS_TOOLS = ("init", "sbin/e2fsck", "sbin/resize2fs")
+
+
+class GateError(RuntimeError):
+ """Raised when any release gate check fails."""
+
+
+def _normalise_cpio_name(raw_name: str) -> str:
+ name = raw_name.replace("\\", "/")
+ while name.startswith("./"):
+ name = name[2:]
+ name = name.lstrip("/")
+ return posixpath.normpath(name) if name else ""
+
+
+def parse_cpio_newc(data: bytes) -> dict[str, tuple[int, int, bytes]]:
+ """Parse an uncompressed newc (070701/070702) initramfs archive.
+
+ Returns a mapping of normalised archive path to (mode, filesize, payload).
+ """
+ entries: dict[str, tuple[int, int, bytes]] = {}
+ offset = 0
+ total = len(data)
+ saw_trailer = False
+
+ while offset < total:
+ # Concatenated cpio archives may be padded with NUL bytes between segments.
+ while offset < total and data[offset] == 0:
+ offset += 1
+ if offset >= total:
+ break
+ if offset + 110 > total:
+ raise GateError(f"truncated cpio header at byte {offset}")
+ magic = data[offset : offset + 6]
+ if magic not in (b"070701", b"070702"):
+ raise GateError(f"unsupported initramfs header magic {magic!r} at byte {offset} (expected uncompressed newc)")
+ try:
+ mode = int(data[offset + 14 : offset + 22].decode("ascii"), 16)
+ filesize = int(data[offset + 54 : offset + 62].decode("ascii"), 16)
+ namesize = int(data[offset + 94 : offset + 102].decode("ascii"), 16)
+ except (UnicodeDecodeError, ValueError) as exc:
+ raise GateError(f"malformed cpio hex header at byte {offset}: {exc}") from exc
+
+ if namesize < 1:
+ raise GateError(f"invalid cpio namesize {namesize} at byte {offset}")
+ name_start = offset + 110
+ name_end = name_start + namesize
+ if name_end > total:
+ raise GateError(f"truncated cpio entry name at byte {offset}")
+ name_bytes = data[name_start:name_end]
+ if not name_bytes.endswith(b"\x00"):
+ raise GateError(f"cpio entry name at byte {offset} is missing NUL terminator")
+ raw_name = name_bytes[:-1].decode("utf-8", errors="replace")
+
+ data_start = (name_end + 3) & ~3
+ data_end = data_start + filesize
+ if data_end > total:
+ raise GateError(f"truncated cpio payload for {raw_name!r} at byte {offset}")
+ payload = data[data_start:data_end]
+ offset = (data_end + 3) & ~3
+
+ if raw_name == "TRAILER!!!":
+ saw_trailer = True
+ continue
+
+ norm = _normalise_cpio_name(raw_name)
+ if norm and norm != ".":
+ entries[norm] = (mode, filesize, payload)
+
+ if not saw_trailer:
+ raise GateError("initramfs.cpio is missing TRAILER!!! sentinel")
+ return entries
+
+
+def _resolve_cpio_entry(
+ entries: dict[str, tuple[int, int, bytes]],
+ path: str,
+ depth: int = 0,
+) -> tuple[int, int]:
+ if depth > 16:
+ raise GateError(f"initramfs symlink loop while resolving {path!r}")
+ if path not in entries:
+ raise GateError(f"initramfs.cpio is missing required entry {path!r}")
+ mode, filesize, payload = entries[path]
+ kind = stat.S_IFMT(mode)
+ if kind == stat.S_IFLNK:
+ target_raw = payload.decode("utf-8", errors="replace").rstrip("\x00")
+ if not target_raw:
+ raise GateError(f"initramfs symlink {path!r} has an empty target")
+ if target_raw.startswith("/"):
+ resolved = _normalise_cpio_name(target_raw)
+ else:
+ parent = posixpath.dirname(path)
+ resolved = _normalise_cpio_name(posixpath.join(parent, target_raw))
+ return _resolve_cpio_entry(entries, resolved, depth + 1)
+ if kind != stat.S_IFREG:
+ raise GateError(f"initramfs entry {path!r} is not a regular file (mode 0o{mode:o})")
+ if filesize <= 0:
+ raise GateError(f"initramfs entry {path!r} is empty (0 bytes)")
+ return mode, filesize
+
+
+def verify_initramfs(
+ cpio_path: Path,
+ required: tuple[str, ...] = REQUIRED_INITRAMFS_TOOLS,
+) -> None:
+ if not cpio_path.is_file():
+ raise GateError(f"missing initramfs archive: {cpio_path}")
+ entries = parse_cpio_newc(cpio_path.read_bytes())
+ for item in required:
+ _resolve_cpio_entry(entries, item)
+
+
+def verify_ext4_superblock(
+ img_path: Path,
+ expected_size: int | None = EXPECTED_TEMPLATE_BYTES,
+) -> None:
+ if not img_path.is_file():
+ raise GateError(f"missing unpacked disk image: {img_path}")
+ info = img_path.stat()
+ if expected_size is not None and info.st_size != expected_size:
+ raise GateError(
+ f"{img_path}: expected {expected_size} bytes ({expected_size >> 30} GiB), got {info.st_size}"
+ )
+ if info.st_size < EXT4_SUPERBLOCK_OFFSET + EXT4_SUPERBLOCK_SIZE:
+ raise GateError(f"{img_path}: file too small ({info.st_size} bytes) to hold an ext4 superblock")
+
+ with img_path.open("rb") as fh:
+ fh.seek(EXT4_SUPERBLOCK_OFFSET)
+ sb = fh.read(EXT4_SUPERBLOCK_SIZE)
+ if len(sb) != EXT4_SUPERBLOCK_SIZE:
+ raise GateError(f"{img_path}: short read of ext4 superblock")
+
+ magic = struct.unpack_from(" None:
+ exe = app_path / "Contents/MacOS/kiri"
+ if not exe.is_file() or not os.access(exe, os.X_OK):
+ raise GateError(f"missing or non-executable host binary: {exe}")
+
+ guest_dir = app_path / "Contents/Resources/guest"
+ for name in REQUIRED_GUEST_FILES:
+ asset = guest_dir / name
+ if not asset.is_file():
+ raise GateError(f"missing packaged guest asset: {asset}")
+ if asset.stat().st_size <= 0:
+ raise GateError(f"packaged guest asset is empty: {asset}")
+
+ verify_initramfs(guest_dir / "initramfs.cpio")
+
+ guest_stage_dir.mkdir(parents=True, exist_ok=True)
+ proc = subprocess.run(
+ ["tar", "-xzf", str(guest_dir / "data.img.tgz"), "-C", str(guest_stage_dir)],
+ capture_output=True,
+ text=True,
+ )
+ if proc.returncode != 0:
+ detail = (proc.stderr or proc.stdout).strip()
+ raise GateError(f"failed to unpack {guest_dir / 'data.img.tgz'}: {detail}")
+
+ data_img = guest_stage_dir / "data.img"
+ verify_ext4_superblock(data_img)
+ img_stat = data_img.stat()
+ if hasattr(img_stat, "st_blocks") and img_stat.st_blocks * 512 >= img_stat.st_size // 4:
+ raise GateError(f"{data_img}: unpacked template is not sparse ({img_stat.st_blocks * 512} bytes allocated)")
+
+ for name in ("Image", "initramfs.cpio"):
+ shutil.copyfile(guest_dir / name, guest_stage_dir / name)
+
+
+def verify_codesign(app_path: Path) -> None:
+ verify = subprocess.run(
+ ["codesign", "--verify", "--deep", "--strict", str(app_path)],
+ capture_output=True,
+ text=True,
+ )
+ if verify.returncode != 0:
+ detail = (verify.stderr or verify.stdout).strip()
+ raise GateError(f"codesign verification failed for {app_path}: {detail}")
+
+ exe = app_path / "Contents/MacOS/kiri"
+ ent = subprocess.run(
+ ["codesign", "-d", "--entitlements", ":-", str(exe)],
+ capture_output=True,
+ )
+ if ent.returncode != 0:
+ detail = ent.stderr.decode("utf-8", errors="replace").strip()
+ raise GateError(f"could not read entitlements from {exe}: {detail}")
+ try:
+ plist = plistlib.loads(ent.stdout) if ent.stdout.strip() else {}
+ except Exception as exc:
+ raise GateError(f"malformed entitlements plist on {exe}: {exc}") from exc
+ if plist.get("com.apple.security.virtualization") is not True:
+ raise GateError(f"{exe} is missing com.apple.security.virtualization entitlement")
+
+
+def bundle_sha256(app_path: Path) -> str:
+ """Compute a deterministic SHA-256 digest across all files in an .app bundle."""
+ if not app_path.is_dir():
+ raise GateError(f"app bundle directory does not exist: {app_path}")
+ outer = hashlib.sha256()
+ entries: list[tuple[str, Path]] = []
+ for root, dirs, files in os.walk(app_path, followlinks=False):
+ dirs.sort()
+ files.sort()
+ root_path = Path(root)
+ for name in dirs:
+ candidate = root_path / name
+ if candidate.is_symlink():
+ rel = candidate.relative_to(app_path).as_posix()
+ entries.append((rel, candidate))
+ for name in files:
+ candidate = root_path / name
+ rel = candidate.relative_to(app_path).as_posix()
+ entries.append((rel, candidate))
+
+ entries.sort(key=lambda item: item[0])
+ for rel, full in entries:
+ st = full.lstat()
+ kind = stat.S_IFMT(st.st_mode)
+ if kind == stat.S_IFLNK:
+ target = os.readlink(full)
+ outer.update(f"L\0{rel}\0{target}\n".encode("utf-8"))
+ elif kind == stat.S_IFREG:
+ file_hash = hashlib.sha256()
+ with full.open("rb") as fh:
+ while chunk := fh.read(1 << 20):
+ file_hash.update(chunk)
+ exec_bit = 1 if (st.st_mode & stat.S_IXUSR) else 0
+ outer.update(f"F\0{rel}\0{exec_bit}\0{file_hash.hexdigest()}\n".encode("utf-8"))
+ else:
+ raise GateError(f"unexpected special file in bundle: {full}")
+ return outer.hexdigest()
+
+
+def git_head(repo_root: Path) -> str:
+ proc = subprocess.run(
+ ["git", "-C", str(repo_root), "rev-parse", "HEAD"],
+ capture_output=True,
+ text=True,
+ )
+ if proc.returncode != 0:
+ detail = (proc.stderr or proc.stdout).strip()
+ raise GateError(f"could not read git HEAD in {repo_root}: {detail}")
+ head = proc.stdout.strip()
+ if len(head) != 40 or any(ch not in "0123456789abcdef" for ch in head):
+ raise GateError(f"unexpected git HEAD output: {head!r}")
+ return head
+
+
+def run_disk_grow_gate(
+ repo_root: Path,
+ app_path: Path,
+ guest_stage_dir: Path,
+ sandbox_dir: Path,
+) -> None:
+ home_dir = sandbox_dir / "home"
+ docker_cfg = sandbox_dir / "docker-config"
+ home_dir.mkdir(parents=True, exist_ok=True)
+ docker_cfg.mkdir(parents=True, exist_ok=True)
+
+ env = os.environ.copy()
+ env["HOME"] = str(home_dir)
+ env["DOCKER_CONFIG"] = str(docker_cfg)
+ bundled_bin = app_path / "Contents/Resources/bin"
+ if bundled_bin.is_dir():
+ env["PATH"] = f"{bundled_bin}{os.pathsep}{env.get('PATH', '')}"
+
+ script = repo_root / "tests/disk-grow.py"
+ exe = app_path / "Contents/MacOS/kiri"
+ proc = subprocess.run(
+ [sys.executable, str(script), str(exe), "--guest-dir", str(guest_stage_dir)],
+ cwd=str(repo_root),
+ env=env,
+ )
+ if proc.returncode != 0:
+ raise GateError(f"tests/disk-grow.py failed with exit code {proc.returncode}")
+
+
+def write_receipt(
+ receipt_path: Path,
+ app_path: Path,
+ checks_passed: list[str],
+ *,
+ head: str,
+ app_digest: str,
+ timestamp: str | None = None,
+) -> dict[str, object]:
+ if timestamp is None:
+ timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+ payload: dict[str, object] = {
+ "git_head": head,
+ "app_path": str(app_path),
+ "app_sha256": app_digest,
+ "timestamp": timestamp,
+ "checks_passed": list(checks_passed),
+ }
+ receipt_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_path = receipt_path.with_name(f".{receipt_path.name}.{os.getpid()}.tmp")
+ tmp_path.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ os.replace(tmp_path, receipt_path)
+ return payload
+
+
+def run_gate(repo_root: Path, app_path: Path, receipt_path: Path) -> dict[str, object]:
+ if platform.system() != "Darwin" or platform.machine() != "arm64":
+ raise GateError(
+ f"release-gate-mac.py must run on Apple Silicon macOS (got {platform.system()} {platform.machine()})"
+ )
+ app_resolved = app_path.resolve()
+ if not app_resolved.is_dir() or app_resolved.suffix != ".app":
+ raise GateError(f"expected a .app bundle directory, got: {app_path}")
+ if app_resolved == Path("/Applications/Kiri.app"):
+ raise GateError("refusing to run release gate against installed /Applications/Kiri.app; pass a built bundle")
+
+ head = git_head(repo_root)
+ checks_passed: list[str] = []
+
+ with tempfile.TemporaryDirectory(prefix="kiri-release-gate-", dir="/tmp") as tmp:
+ sandbox = Path(tmp).resolve()
+ guest_stage = sandbox / "guest"
+
+ print(f"==> [1/4] Checking guest assets and ext4 template in {app_resolved}", flush=True)
+ unpack_and_verify_guest(app_resolved, guest_stage)
+ checks_passed.extend([
+ "guest_assets_present",
+ "initramfs_tools_present",
+ "ext4_superblock_valid_no_sparse_super2",
+ ])
+
+ print(f"==> [2/4] Verifying code signature and entitlements on {app_resolved}", flush=True)
+ verify_codesign(app_resolved)
+ checks_passed.append("codesign_deep_strict_and_virtualization_entitlement")
+
+ print("==> [3/4] Running packaged VM disk-growth test in isolated /tmp sandbox", flush=True)
+ run_disk_grow_gate(repo_root, app_resolved, guest_stage, sandbox)
+ checks_passed.append("packaged_vm_disk_grow")
+
+ print("==> [4/4] Writing release gate receipt", flush=True)
+ digest = bundle_sha256(app_resolved)
+ receipt = write_receipt(
+ receipt_path.resolve(),
+ app_resolved,
+ checks_passed,
+ head=head,
+ app_digest=digest,
+ )
+ print(f"PASS release gate receipt written to {receipt_path.resolve()}", flush=True)
+ return receipt
+
+
+def main(argv: list[str] | None = None) -> int:
+ repo_root = Path(__file__).resolve().parent.parent
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("app", type=Path, help="Path to the built Kiri.app bundle (for example target/Kiri.app)")
+ parser.add_argument(
+ "--receipt",
+ type=Path,
+ default=None,
+ help="Output path for the JSON pass receipt (default: /release-gate-receipt.json)",
+ )
+ args = parser.parse_args(argv)
+ receipt_path = args.receipt if args.receipt is not None else args.app.resolve().parent / "release-gate-receipt.json"
+ try:
+ run_gate(repo_root, args.app, receipt_path)
+ except GateError as exc:
+ print(f"FAIL release gate: {exc}", file=sys.stderr)
+ return 1
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/disk-grow.py b/tests/disk-grow.py
index 82735364..f5db1262 100644
--- a/tests/disk-grow.py
+++ b/tests/disk-grow.py
@@ -88,6 +88,11 @@ def main():
"CFBundleIdentifier": "dev.kiri.app." + feature,
"CFBundleExecutable": "kiri",
}))
+ subprocess.run(
+ ["codesign", "--force", "--sign", "-", "--entitlements",
+ str(repo / "crates/kiri/kiri.entitlements"), str(contents.parent)],
+ check=True, capture_output=True, text=True,
+ )
socket = work / "docker.sock"
env.update(KIRI_SOCKET=str(socket), KIRI_DATA_DIR=str(work / "data"),
KIRI_GUEST_DIR=str(args.guest_dir.resolve()), KIRI_NO_FINDER="1",
diff --git a/tests/lib/check-regressions.py b/tests/lib/check-regressions.py
old mode 100644
new mode 100755
index 4420c4b5..a2075978
--- a/tests/lib/check-regressions.py
+++ b/tests/lib/check-regressions.py
@@ -1,62 +1,318 @@
#!/usr/bin/env python3
-"""tests/regressions.tsv must name only checks that still exist. Each line
-is a check name, a tab, the issue or pull request (#N), a tab, and one line
-on what broke. A check exists when a test script runs it by that name
-(t NAME or code NAME; a case of tests/stress.sh, selected NAME); a name
-with a / is a file under the repo.
-Reads the files only (no engine, no network); prints what is wrong and
-exits 1 if anything is.
+"""tests/regressions.tsv must name only checks that CI or the suites actually
+execute. Each non-comment line has three tab-separated columns: check name,
+issue or pull request (#N), and one line describing what broke.
+
+Allowed check names:
+ - NAME (no `/` or `::`): a named check in `tests/*.sh` (`t`, `code`, `check`,
+ or `selected`).
+ - `tests/ui/.js`: a page test discovered and run by `scripts/ui-test.py`
+ (not `fixture.js`, and calling `report(`).
+ - `/.../.rs::`: a Rust `#[test]` function in that
+ file, not marked `#[ignore]`.
+ - `guest/kernel/patches/.patch`: a guest kernel patch checked by the
+ kernel build.
+
+Reads the repository files only (no engine, no network); prints any problem and
+exits 1 if anything is wrong.
python3 tests/lib/check-regressions.py
"""
+import argparse
+import os
import pathlib
import re
import sys
TESTS = pathlib.Path(__file__).resolve().parent.parent
+REPO = TESTS.parent
TABLE = TESTS / "regressions.tsv"
+IDENT = re.compile(r"[^\W\d]\w*")
+RAW_STR = re.compile(r'(?:b|c)?r(#*)"')
+NUMBER = re.compile(r"\d[\w]*(?:\.\d[\w]*)?")
+SHELL_RUN = re.compile(r'(?:^|[\s;(&|])(?:t|code|check|selected)\s+"?([a-z0-9][a-z0-9_-]*)"?\s')
+UI_PATH = re.compile(r"tests/ui/([A-Za-z0-9._-]+\.js)")
+PATCH_PATH = re.compile(r"guest/kernel/patches/[A-Za-z0-9._-]+\.patch")
+RUST_FN = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
-def defined():
+
+def defined_shell_checks(tests_dir):
names = set()
- run = re.compile(r"(?:^|[\s;(&|])(?:t|code|check|selected)\s+\"?([a-z0-9][a-z0-9_-]*)\"?\s")
- for p in sorted(TESTS.glob("*.sh")):
- for line in p.read_text().splitlines():
+ for p in sorted(tests_dir.glob("*.sh")):
+ for line in p.read_text(encoding="utf-8").splitlines():
if line.lstrip().startswith("#"):
continue
- names.update(m.group(1) for m in run.finditer(line + " "))
+ names.update(m.group(1) for m in SHELL_RUN.finditer(line + " "))
return names
-def main():
- have = defined()
- bad = 0
+def discovered_ui_tests(repo):
+ ui_dir = repo / "tests/ui"
+ if not ui_dir.is_dir():
+ return set()
+ runner = repo / "scripts/ui-test.py"
+ if not runner.is_file():
+ return set()
+ return {
+ f"tests/ui/{entry.name}"
+ for entry in sorted(ui_dir.iterdir())
+ if entry.is_file() and entry.name.endswith(".js") and entry.name != "fixture.js"
+ }
+
+
+def tokenize_rust(src):
+ toks = []
+ i, n = 0, len(src)
+ while i < n:
+ c = src[i]
+ if c.isspace():
+ i += 1
+ elif src.startswith("//", i):
+ j = src.find("\n", i)
+ i = n if j < 0 else j
+ elif src.startswith("/*", i):
+ depth, j = 0, i
+ while j < n:
+ if src.startswith("/*", j):
+ depth += 1
+ j += 2
+ elif src.startswith("*/", j):
+ depth -= 1
+ j += 2
+ if depth == 0:
+ break
+ else:
+ j += 1
+ if depth != 0:
+ raise ValueError("unclosed block comment")
+ i = j
+ elif (m := RAW_STR.match(src, i)) is not None:
+ close = '"' + m.group(1)
+ j = src.find(close, m.end())
+ if j < 0:
+ raise ValueError("unclosed raw string")
+ toks.append(("str", src[i : j + len(close)]))
+ i = j + len(close)
+ elif c == '"' or (c in "bc" and src.startswith('"', i + 1)):
+ j = i + (1 if c == '"' else 2)
+ while j < n and src[j] != '"':
+ j += 2 if src[j] == "\\" else 1
+ if j >= n:
+ raise ValueError("unclosed string")
+ toks.append(("str", src[i : j + 1]))
+ i = j + 1
+ elif c == "'" or (c == "b" and src.startswith("'", i + 1)):
+ q = i if c == "'" else i + 1
+ if src.startswith("\\", q + 1):
+ j = src.find("'", q + 3)
+ if j < 0 or "\n" in src[q:j]:
+ raise ValueError("unclosed char literal")
+ toks.append(("char", src[i : j + 1]))
+ i = j + 1
+ elif q + 2 < n and src[q + 2] == "'" and src[q + 1] != "\n":
+ toks.append(("char", src[i : q + 3]))
+ i = q + 3
+ elif c == "'" and (m := IDENT.match(src, q + 1)) is not None:
+ toks.append(("life", src[i : m.end()]))
+ i = m.end()
+ else:
+ toks.append(("punct", c))
+ i += 1
+ elif c == "r" and src.startswith("#", i + 1) and (m := IDENT.match(src, i + 2)) is not None:
+ toks.append(("ident", src[i + 2 : m.end()]))
+ i = m.end()
+ elif (m := IDENT.match(src, i)) is not None:
+ toks.append(("ident", m.group()))
+ i = m.end()
+ elif c.isdigit():
+ m = NUMBER.match(src, i)
+ toks.append(("num", m.group()))
+ i = m.end()
+ else:
+ toks.append(("punct", c))
+ i += 1
+ return toks
+
+
+def match_brackets(toks):
+ opens, closes = "([{", ")]}"
+ pairs, stack = {}, []
+ for idx, (kind, text) in enumerate(toks):
+ if kind != "punct":
+ continue
+ if text in opens:
+ stack.append(idx)
+ elif text in closes:
+ if not stack or opens.index(toks[stack[-1]][1]) != closes.index(text):
+ raise ValueError(f"unbalanced {text!r}")
+ o = stack.pop()
+ pairs[o], pairs[idx] = idx, o
+ if stack:
+ raise ValueError(f"unclosed {toks[stack[-1]][1]!r}")
+ return pairs
+
+
+def _attr_is_test(tokens):
+ names = [t for k, t in tokens if k == "ident"]
+ if not names:
+ return False
+ if tokens[0] == ("ident", "test") and len(tokens) == 1:
+ return True
+ if tokens[-1] == ("ident", "test") and all(
+ t in ((("punct", "::")),) or k == "ident" for k, t in tokens[:-1]
+ ):
+ return True
+ if tokens[0] == ("ident", "cfg_attr") and ("ident", "test") in tokens[1:]:
+ return True
+ return False
+
+
+def _attr_is_ignore(tokens):
+ if not tokens:
+ return False
+ if tokens[0] == ("ident", "ignore"):
+ return True
+ if tokens[0] == ("ident", "cfg_attr") and ("ident", "ignore") in tokens[1:]:
+ return True
+ return False
+
+
+def rust_tests_in_file(path):
+ """Returns dict of fn_name -> is_ignored for every #[test] fn in `path`."""
+ toks = tokenize_rust(path.read_text(encoding="utf-8"))
+ pairs = match_brackets(toks)
+ found = {}
+ i, n = 0, len(toks)
+ while i < n:
+ attrs = []
+ while (
+ i + 1 < n
+ and toks[i] == ("punct", "#")
+ and toks[i + 1] == ("punct", "[")
+ and (i + 1) in pairs
+ ):
+ close = pairs[i + 1]
+ attrs.append(toks[i + 2 : close])
+ i = close + 1
+ if attrs and i < n:
+ j = i
+ if j < n and toks[j] == ("ident", "pub"):
+ j += 1
+ if j < n and toks[j] == ("punct", "(") and j in pairs:
+ j = pairs[j] + 1
+ while j < n and toks[j][0] == "ident" and toks[j][1] in ("async", "unsafe", "const", "extern"):
+ j += 1
+ if j < n and toks[j][0] == "str":
+ j += 1
+ if j + 1 < n and toks[j] == ("ident", "fn") and toks[j + 1][0] == "ident":
+ fn_name = toks[j + 1][1]
+ if any(_attr_is_test(a) for a in attrs):
+ ignored = any(_attr_is_ignore(a) for a in attrs)
+ found[fn_name] = found.get(fn_name, False) or ignored
+ i = j + 2
+ continue
+ i += 1
+ return found
+
+
+def check_table(repo=REPO, table_path=None):
+ repo = pathlib.Path(repo)
+ table_path = pathlib.Path(table_path) if table_path is not None else repo / "tests/regressions.tsv"
+ shell_checks = defined_shell_checks(repo / "tests")
+ ui_tests = discovered_ui_tests(repo)
+ rust_cache = {}
+ errors = []
seen = set()
rows = 0
- for n, line in enumerate(TABLE.read_text().splitlines(), 1):
+ rel_table = os.path.relpath(table_path, repo) if table_path.is_relative_to(repo) else str(table_path)
+
+ for n, line in enumerate(table_path.read_text(encoding="utf-8").splitlines(), 1):
if not line.strip() or line.startswith("#"):
continue
rows += 1
cols = line.split("\t")
- where = f"tests/regressions.tsv:{n}"
+ where = f"{rel_table}:{n}"
if len(cols) != 3 or not re.fullmatch(r"#[0-9]+", cols[1]) or not cols[2].strip():
- print(f"{where}: want NAME#Nwhat broke, got {line!r}")
- bad += 1
+ errors.append(f"{where}: want NAME#Nwhat broke, got {line!r}")
continue
name = cols[0]
if name in seen:
- print(f"{where}: {name} is listed twice")
- bad += 1
+ errors.append(f"{where}: {name} is listed twice")
seen.add(name)
- if "/" in name:
- if not (TESTS.parent / name).is_file():
- print(f"{where}: no file {name}")
- bad += 1
- elif name not in have:
- print(f"{where}: no check named {name} in tests/*.sh")
- bad += 1
- print(f"{rows} regression checks listed, {bad} problem(s)")
- return 1 if bad else 0
+
+ if "::" in name:
+ parts = name.split("::")
+ if len(parts) != 2:
+ errors.append(f"{where}: want ::, got {name!r}")
+ continue
+ rs_rel, fn_name = parts
+ norm = pathlib.PurePosixPath(rs_rel)
+ if (
+ ".." in norm.parts
+ or not rs_rel.endswith(".rs")
+ or not rs_rel.startswith(("crates/", "xtask/"))
+ or not RUST_FN.fullmatch(fn_name)
+ ):
+ errors.append(
+ f"{where}: Rust check must be /.../.rs::, got {name!r}"
+ )
+ continue
+ rs_path = repo / rs_rel
+ if not rs_path.is_file():
+ errors.append(f"{where}: no Rust file {rs_rel}")
+ continue
+ if rs_rel not in rust_cache:
+ try:
+ rust_cache[rs_rel] = rust_tests_in_file(rs_path)
+ except ValueError as exc:
+ errors.append(f"{where}: cannot scan {rs_rel}: {exc}")
+ rust_cache[rs_rel] = None
+ continue
+ tests = rust_cache[rs_rel]
+ if tests is None:
+ continue
+ if fn_name not in tests:
+ errors.append(f"{where}: no #[test] fn {fn_name} in {rs_rel}")
+ elif tests[fn_name]:
+ errors.append(f"{where}: #[test] fn {fn_name} in {rs_rel} is marked #[ignore]")
+ elif "/" in name:
+ if UI_PATH.fullmatch(name):
+ ui_file = repo / name
+ if not ui_file.is_file():
+ errors.append(f"{where}: no UI test file {name}")
+ elif name not in ui_tests:
+ errors.append(f"{where}: {name} is not discovered by scripts/ui-test.py")
+ elif "report(" not in ui_file.read_text(encoding="utf-8"):
+ errors.append(f"{where}: UI test {name} never calls report()")
+ elif PATCH_PATH.fullmatch(name):
+ if not (repo / name).is_file():
+ errors.append(f"{where}: no kernel patch {name}")
+ elif name.endswith(".rs"):
+ errors.append(
+ f"{where}: bare Rust file {name} is not allowed; name a concrete #[test] as {name}::"
+ )
+ else:
+ errors.append(
+ f"{where}: {name} is not an executed CI check (use a tests/*.sh check name, "
+ "tests/ui/.js, ::, or guest/kernel/patches/.patch)"
+ )
+ else:
+ if name not in shell_checks:
+ errors.append(f"{where}: no check named {name} in tests/*.sh")
+
+ return rows, errors
+
+
+def main(argv=None):
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument("--repo", type=pathlib.Path, default=REPO)
+ args = parser.parse_args(argv)
+ rows, errors = check_table(args.repo)
+ for err in errors:
+ print(err)
+ print(f"{rows} regression checks listed, {len(errors)} problem(s)")
+ return 1 if errors else 0
if __name__ == "__main__":
diff --git a/tests/regressions.tsv b/tests/regressions.tsv
index dd7af8cf..4af4ee81 100644
--- a/tests/regressions.tsv
+++ b/tests/regressions.tsv
@@ -1,11 +1,12 @@
# Checks that guard a real bug: check name, tab, issue or pull request, tab,
-# what broke. A failing check listed here prints a "guards:" line naming it.
-# A name with a / is a test file (tests/ui/...). Every bug fix adds its check
-# here; python3 tests/lib/check-regressions.py fails when a name is gone.
+# what broke. A failing suite check listed here prints a "guards:" line naming it.
+# Allowed check names: a check in tests/*.sh, tests/ui/.js,
+# /.../.rs::, or guest/kernel/patches/.patch.
+# Every bug fix adds its check here; python3 tests/lib/check-regressions.py verifies every row.
connection-close-start #588 a start sent with Connection: close was never closed, so Docker.DotNet hung until its timeout (#520)
http10-start-closes #588 an HTTP/1.0 request stayed open after its answer (#479)
keep-alive-start-stays #588 the connection-close fix must not close a kept-alive connection
-crates/kiri/src/daemon/ops.rs #925 docker events --until without --since printed none of the kept events; Docker replays them up to --until
+crates/kiri/src/daemon/ops.rs::events_until_without_since_replays_matching_history #925 docker events --until without --since printed none of the kept events; Docker replays them up to --until
connection-close-said #588 the answer to Connection: close did not say Connection: close
http10-ping-closes #588 an HTTP/1.0 ping stayed open after its answer (#479)
pid-mode-inspect #588 --pid was accepted and ignored; inspect lost HostConfig.PidMode (#347)
@@ -32,7 +33,7 @@ top-eo #588 docker top -eo did not give the columns asked for (#348)
top-eo-rss #588 docker top -eo rss gave no memory column (#348)
top-ps-args-refused #588 unsupported ps_args were silently ignored instead of refused (#348)
ps-limit-latest #839 docker ps -l and -n ignored the requested limit and skipped stopped containers
-crates/kiri/src/daemon/time.rs #924 docker ps Status said "Up 1 minutes", "1 hours" and "1 days" instead of Docker's "About a minute", "About an hour", "24 hours", weeks, months and years
+crates/kiri/src/daemon/time.rs::status_durations_read_like_docker #924 docker ps Status said "Up 1 minutes", "1 hours" and "1 days" instead of Docker's "About a minute", "About an hour", "24 hours", weeks, months and years
ij-setup #588 sets up the damaged image list check below (#440)
ij-info-warns #588 a repaired images.json gave no docker info warning (#440)
ij-info-names-lost #588 the repair warning did not name the images it lost (#440)
@@ -280,7 +281,7 @@ hostnet-published-loopback #732 a port published on 127.0.0.1 was unreachable fr
hostnet-published-every-address #732 the same for a port published on every address
hostnet-dns-kiri #732 a --network host container asked the Mac's resolver for the VM network directly, with no fallback when it refused
socket-container-uid-group #127 a standalone root-run Linux daemon put its 0600 socket under /root/.kiri/run/docker.sock instead of a 0660 /run/kiri/docker.sock, locking out containerized SDK clients whose numeric uid has no host account
-tests/disk-grow.py #384 the macOS VM data disk stayed fixed at 64 GiB instead of growing via KIRI_DISK_GB / vm.json and online ext4 resize
+crates/kiri/src/guest/disk.rs::growth_preserves_data_and_holes_and_never_shrinks #384 the macOS VM data disk stayed fixed at 64 GiB instead of growing via KIRI_DISK_GB / vm.json and online ext4 resize
tests/ui/resources-disk.js #384 Settings -> Resources had no Disk image size control for macOS VM disk growth without shrinking
tests/ui/storage-location.js #355 Settings → Storage had no way to move images, containers, volumes and the VM disk to another folder or external drive, or recover when an external drive is unplugged
network-ipv6-subnet-ignored-when-disabled #433 POST /networks/create with EnableIPv6 false (or omitted) and an IPv6 subnet in IPAM.Config was refused instead of ignoring the IPv6 subnet as Docker does (mailcow-dockerized)
@@ -302,25 +303,25 @@ import-upper-runs-with-files #410 an imported container started without the file
leave-first-running-disconnect #789 disconnecting a running container from its only network was refused (or left its veth, routes, and published ports active instead of isolating it)
leave-first-running-reconnect #789 reconnecting a running container after leaving its first network failed to restore veth connectivity, DNS aliases, or published ports
leave-first-running-promote #789 disconnecting a running container's first network when attached to a second network failed to isolate the left network, promote the default route, or rebind published ports
-crates/kiri/src/hostrelay.rs #550 on Windows (WSL 2), host.docker.internal resolved to the WSL bridge gateway (172.17.0.1) instead of 192.168.65.254 relayed to Windows 127.0.0.1 and [::1]
-crates/kiri-win/src/ports.rs #640 WSL 2's localhostForwarding only forwards loopback TCP, so published UDP container ports and non-loopback Windows host-IP or 0.0.0.0 LAN TCP bindings were unreachable on Windows (#218)
-crates/kiri/src/daemon/ports.rs #218 publishing a container port on a Windows host interface IP (-p IP:port:port) failed inside WSL 2 with EADDRNOTAVAIL (os error 99) instead of binding WSL's eth0 address for kiri-win to forward, and macOS lacked KIRI_HOST_LOOPBACK=off to block untrusted containers from reaching host loopback services (#995)
-crates/kiri/src/wsl.rs #761 running kiri.exe diag report [--out PATH] on Windows wrote the report file inside the WSL Linux rootfs instead of the Windows filesystem
+crates/kiri/src/hostrelay.rs::dial_side_with_host_allows_dynamic_ipv4_and_ipv6_ports_and_rejects_port_zero #550 on Windows (WSL 2), host.docker.internal resolved to the WSL bridge gateway (172.17.0.1) instead of 192.168.65.254 relayed to Windows 127.0.0.1 and [::1]
+crates/kiri-win/src/ports.rs::plans_udp_and_non_loopback_tcp_forwards #640 WSL 2's localhostForwarding only forwards loopback TCP, so published UDP container ports and non-loopback Windows host-IP or 0.0.0.0 LAN TCP bindings were unreachable on Windows (#218)
+crates/kiri/src/daemon/ports.rs::ipconfig_parser_extracts_windows_interface_ips_and_excludes_gateways_and_masks #218 publishing a container port on a Windows host interface IP (-p IP:port:port) failed inside WSL 2 with EADDRNOTAVAIL (os error 99) instead of binding WSL's eth0 address for kiri-win to forward, and macOS lacked KIRI_HOST_LOOPBACK=off to block untrusted containers from reaching host loopback services (#995)
+crates/kiri/src/wsl.rs::parses_windows_diag_report_out_and_send_flags #761 running kiri.exe diag report [--out PATH] on Windows wrote the report file inside the WSL Linux rootfs instead of the Windows filesystem
dns-default-bridge-stub #330 on a Linux host whose /etc/resolv.conf names only 127.0.0.53 (systemd-resolved), default-bridge containers got 1.1.1.1 instead of querying the host stub through the bridge gateway over UDP and TCP
build-pinned-digest #288 a digest-pinned FROM image (@sha256:...) already pulled into Kiri's store was re-serialized instead of served with its upstream manifest and index bytes, failing BuildKit's digest check (#330)
build-host-network-dns #209 build steps under docker build and docker build --network=host (or a host-network builder) could not resolve names through a loopback stub resolver on the host (#330)
-crates/kiri/src/main.rs #743 kiri --help listed commands not compiled for the current OS (such as macOS-only setup, import, bench and boot on Linux, or Linux-only bridge on macOS)
-crates/kiri/src/update.rs #840 kiri update --help and kiri update -h entered the updater and tried the release feed (or failed the dev-build check) instead of printing OS-appropriate usage offline, and on Windows kiri update --check fell through to docker update --check (#984)
+crates/kiri/src/main.rs::usage_lists_only_commands_for_this_os #743 kiri --help listed commands not compiled for the current OS (such as macOS-only setup, import, bench and boot on Linux, or Linux-only bridge on macOS)
+crates/kiri/src/update.rs::help_skips_release_lookup #840 kiri update --help and kiri update -h entered the updater and tried the release feed (or failed the dev-build check) instead of printing OS-appropriate usage offline, and on Windows kiri update --check fell through to docker update --check (#984)
vol-rm-force-in-use #773 docker volume rm --force (and DELETE /volumes/{name}?force=1) removed a volume still used by a container instead of returning 409 Conflict and keeping its data
vol-rm-force-missing #773 DELETE /volumes/{name}?force=1 (and docker volume rm -f) returned 404 Not Found for a missing volume instead of 204 No Content as Docker does
-crates/kiri-image/src/reference.rs #746 Reference::parse and archive::load accepted quotes, backslashes, queries and fragments in image names, storing unparseable or hostile RepoTags from docker load, and Reference::parse kept `index.docker.io` as a registry of its own instead of Docker Hub, so `docker run index.docker.io/library/alpine` pulled the image and then found no such image (#1018)
+crates/kiri-image/src/reference.rs::rejects_garbage #746 Reference::parse and archive::load accepted quotes, backslashes, queries and fragments in image names, storing unparseable or hostile RepoTags from docker load, and Reference::parse kept `index.docker.io` as a registry of its own instead of Docker Hub, so `docker run index.docker.io/library/alpine` pulled the image and then found no such image (#1018)
image-index-docker-io #1018 docker run, inspect, tag and rmi with index.docker.io/... treated Docker Hub's old domain as a separate registry and missed stored Docker Hub images
-crates/kiri/src/daemon/mirror.rs #746 registry and mirror names were written into buildkitd.toml without TOML string escaping, so a quote or backslash broke buildkitd startup on every build
-crates/kiri/src/daemon/http.rs #745 chunked request bodies left trailer headers on keep-alive connections, Expect: 100-continue never sent 100 Continue before reading bodies, conflicting Transfer-Encoding + Content-Length headers were not rejected with 400 Bad Request (#134), and idle or stalled connections had no request-header read timeout (#207)
+crates/kiri/src/daemon/mirror.rs::names_are_quoted_for_toml #746 registry and mirror names were written into buildkitd.toml without TOML string escaping, so a quote or backslash broke buildkitd startup on every build
+crates/kiri/src/daemon/http.rs::chunked_trailers_preserve_keep_alive_boundaries #745 chunked request bodies left trailer headers on keep-alive connections, Expect: 100-continue never sent 100 Continue before reading bodies, conflicting Transfer-Encoding + Content-Length headers were not rejected with 400 Bad Request (#134), and idle or stalled connections had no request-header read timeout (#207)
tests/ui/watch-bind-mounts.js #487 Settings -> Resources had no toggle on Windows to turn C:\ bind-mount file events (watchBindMounts) on or off
-crates/kiri/src/client.rs #836 Linux client socket discovery missed WSL 2 integration sockets under /mnt/wsl/kiri/sockets//docker.sock (and /var/run/docker.sock symlinks to them) and reported socket EACCES as "Kiri isn't running"
-crates/kiri/src/daemon/mod.rs #836 non-root kiri daemon on Linux bound ~/.kiri/run/docker.sock instead of failing fast, sudo kiri daemon did not fall back to the kiri group, grant SUDO_UID POSIX ACL access, or link /run/docker.sock when free, and the daemon accept loops had no isolated host/WSL and container caps on concurrent open client connections (#207)
-crates/kiri/src/docker.rs #836 kiri docker subcommands reported socket permission errors and Linux/WSL not-running errors with the macOS `kiri daemon` message instead of OS-accurate guidance
+crates/kiri/src/client.rs::socket_for_discovers_wsl_integration_sockets_and_symlinks #836 Linux client socket discovery missed WSL 2 integration sockets under /mnt/wsl/kiri/sockets//docker.sock (and /var/run/docker.sock symlinks to them) and reported socket EACCES as "Kiri isn't running"
+crates/kiri/src/daemon/mod.rs::linux_root_check_sudo_uid_and_docker_sock_symlink #836 non-root kiri daemon on Linux bound ~/.kiri/run/docker.sock instead of failing fast, sudo kiri daemon did not fall back to the kiri group, grant SUDO_UID POSIX ACL access, or link /run/docker.sock when free, and the daemon accept loops had no isolated host/WSL and container caps on concurrent open client connections (#207)
+crates/kiri/src/client.rs::check_alive_distinguishes_alive_not_running_and_permission_denied #836 kiri docker subcommands reported socket permission errors and Linux/WSL not-running errors with the macOS `kiri daemon` message instead of OS-accurate guidance
hostnet-ports-discarded #764 on a Linux host, a container with network_mode: host and published ports bound host port forwarders in the shared host netns, causing the container's own listener to fail with EADDRINUSE and populating NetworkSettings.Ports instead of {}
load-oci-ref #465 docker load rejected OCI image-layout archives (index.json + blobs/sha256/...) with "no manifest.json"
load-oci-untagged #465 untagged digest-only OCI image-layout archives had no tag annotation and needed to load by config digest ID
@@ -330,102 +331,102 @@ load-oci-platform #465 POST /images/load?platform=... did not select the request
load-oci-platform-json #465 Docker API v1.48 sends platform as a JSON-encoded ocispec.Platform object on POST /images/load
load-oci-no-platform #465 loading a multi-platform OCI archive for an absent platform needed an explicit error rather than loading another arch or attestation manifest
load-oci-buildx #465 docker buildx build --output type=oci archives use io.containerd.image.name for the full image name while org.opencontainers.image.ref.name holds only the tag
-crates/kiri/src/share.rs #207 Share mutex locks panicked on poisoning under panic=abort, traffic/state writes used shared .tmp names without create_new/0600 or Ended serialization, and sharing a non-localhost target gave no warning
-crates/kiri-init/src/linux/mod.rs #207 with panic=abort, a panic in PID 1 or the host agent aborted silently without writing its message and location directly to stderr from a stack buffer
+crates/kiri/src/share.rs::traffic_and_state_files_are_user_only_0600 #207 Share mutex locks panicked on poisoning under panic=abort, traffic/state writes used shared .tmp names without create_new/0600 or Ended serialization, and sharing a non-localhost target gave no warning
+crates/kiri-init/src/linux/mod.rs::formats_panic_location_and_payload_into_stack_buffer #207 with panic=abort, a panic in PID 1 or the host agent aborted silently without writing its message and location directly to stderr from a stack buffer
restart-policy-refused #841 docker update stored unknown restart policies or enabled restarts on AutoRemove containers, and container create/update accepted negative or non-on-failure MaximumRetryCount values
-crates/kiri/src/ui/compose.rs #770 on Windows, Compose projects started inside a WSL distro had Linux label paths (/home/...) rejected as non-absolute and \\wsl.localhost\\... rejected as remote UNC paths, and canonical paths with multi-byte UTF-8 right after C:\ or \\?\ panicked at byte index 4 (#1087)
-crates/kiri-win/src/watch.rs #1087 collapsing Windows bind-mount watch folders panicked when a shorter parent path length fell inside a multi-byte UTF-8 character of another path
-crates/kiri-init/src/linux/firewall.rs #1100 on WSL 2 and minimal Linux hosts without an iptables binary, Docker's or ufw's nf_tables filter DROP chains blocked container-to-container and egress traffic instead of syncing DOCKER-USER, FORWARD, and INPUT DNS rules directly over netlink (#761)
-crates/kiri-init/src/linux/netlink.rs #1100 nf_tables netlink rule builders and handle-based deletion for filter DOCKER-USER, FORWARD, and INPUT chains with KIRI_RULE_COMMENT userdata (#761)
+crates/kiri/src/ui/compose.rs::wsl_compose_labels_map_to_windows_paths_across_legacy_integrated_and_mounted_drives #770 on Windows, Compose projects started inside a WSL distro had Linux label paths (/home/...) rejected as non-absolute and \\wsl.localhost\\... rejected as remote UNC paths, and canonical paths with multi-byte UTF-8 right after C:\ or \\?\ panicked at byte index 4 (#1087)
+crates/kiri-win/src/watch.rs::collapses_nested_watch_specs #1087 collapsing Windows bind-mount watch folders panicked when a shorter parent path length fell inside a multi-byte UTF-8 character of another path
+crates/kiri-init/src/linux/firewall.rs::wsl_nft_docker_user_and_input_drop_forwarding_without_iptables_binary #1100 on WSL 2 and minimal Linux hosts without an iptables binary, Docker's or ufw's nf_tables filter DROP chains blocked container-to-container and egress traffic instead of syncing DOCKER-USER, FORWARD, and INPUT DNS rules directly over netlink (#761)
+crates/kiri-init/src/linux/netlink.rs::filter_sync_batch_encodes_udata_comment_deletes_handles_and_prepends_in_order #1100 nf_tables netlink rule builders and handle-based deletion for filter DOCKER-USER, FORWARD, and INPUT chains with KIRI_RULE_COMMENT userdata (#761)
dockerfw-no-iptables-rules #1100 with iptables uninstalled and ip filter FORWARD/INPUT policy drop, Kiri installs its 3 DOCKER-USER and 2 INPUT DNS rules directly via nf_tables netlink (#761)
dockerfw-no-iptables-traffic #1100 same-network container-to-container and egress HTTP both pass ip filter DOCKER-USER with bridge-nf-call-iptables=1 and no iptables binary installed (#761)
-crates/kiri/src/daemon/api.rs #770 containers created inside WSL did not expose their owning WSL distro on GET /containers/json for Windows Compose path mapping, image config Labels could inject dev.kiri.* and com.docker.compose.* control-plane labels, and Caller::Wsl could invoke host admin endpoints (#1013), and the `reference` filter of `docker images` took one `*` at most, no `?` or class, and let `*` cross a `/`, so `--filter reference='*/*'` listed nothing (#1019)
+crates/kiri/src/daemon/api.rs::wsl_distro_is_recorded_from_caller_and_inferred_from_legacy_mounts #770 containers created inside WSL did not expose their owning WSL distro on GET /containers/json for Windows Compose path mapping, image config Labels could inject dev.kiri.* and com.docker.compose.* control-plane labels, and Caller::Wsl could invoke host admin endpoints (#1013), and the `reference` filter of `docker images` took one `*` at most, no `?` or class, and let `*` cross a `/`, so `--filter reference='*/*'` listed nothing (#1019)
image-ls-reference-glob #1019 docker images --filter reference= took one * at most, supported neither ? nor character classes, and let * cross /
bind-nonroot-parallel #796 concurrent non-root file and directory creation on a macOS bind mount raced with root stat/ls and /proc/kiri-fsnotify on the shared virtiofs inode's cached i_uid/i_gid, failing with EACCES/EPERM
bind-nonroot-ro #796 non-root writes to a read-only 0444 bind-mount file must still fail with EACCES, including inside an unprivileged unshare -Ur user namespace
-crates/kiri/src/daemon/rofs.rs #768 when Kiri's WSL 2 ext4.vhdx or Linux storage filesystem was remounted read-only (emergency_ro), daemon startup, /info and diagnostics lacked actionable fsck / storage recovery steps
-crates/kiri-init/src/linux/sys.rs #768 on a read-only or emergency_ro storage filesystem, overlayfs silently mounted writable container rootfs read-only instead of refusing with actionable recovery steps
-crates/kiri-win/src/wslsync.rs #768 kiri-start and kiri-win reported a generic WSL install failure instead of ext4.vhdx emergency_ro e2fsck recovery steps when Kiri's WSL 2 disk was remounted read-only, KIRI_CONTEXT_HASH did not match sha256("kiri"), and wsl_enable_script overwrote Windows's npipe kiri context when ~/.docker/contexts in WSL was symlinked into /mnt/ (#269)
+crates/kiri/src/daemon/rofs.rs::detects_wsl_from_interop_or_kernel_release_and_formats_recovery_steps #768 when Kiri's WSL 2 ext4.vhdx or Linux storage filesystem was remounted read-only (emergency_ro), daemon startup, /info and diagnostics lacked actionable fsck / storage recovery steps
+crates/kiri-init/src/linux/sys.rs::parses_readonly_mounts_and_formats_wsl_and_linux_diagnostics #768 on a read-only or emergency_ro storage filesystem, overlayfs silently mounted writable container rootfs read-only instead of refusing with actionable recovery steps
+crates/kiri-win/src/wslsync.rs::parses_wsl_proc_mounts_and_formats_vhdx_recovery_message #768 kiri-start and kiri-win reported a generic WSL install failure instead of ext4.vhdx emergency_ro e2fsck recovery steps when Kiri's WSL 2 disk was remounted read-only, KIRI_CONTEXT_HASH did not match sha256("kiri"), and wsl_enable_script overwrote Windows's npipe kiri context when ~/.docker/contexts in WSL was symlinked into /mnt/ (#269)
tls-company-root-pull #303 a registry signed by a root the system trusts failed UnknownIssuer: only the bundled roots were trusted
tls-company-root-login #303 docker login to a registry signed by a root the system trusts failed UnknownIssuer
tls-unknown-root-refused #303 a root the system does not trust must still be refused
-crates/kiri-image/src/roots.rs #303 root store merge, system distrust filtering (macOS Never Trust, Windows Disallowed and disabled Server Auth EKU), cross-cert preservation, caps, and KIRI_TLS_ROOTS=webpki escape hatch
-crates/kiri/src/daemon/hostroots.rs #303 Windows host roots persistence in WSL must enforce Caller::Host, 0600 atomic writes, non-symlink/non-FIFO reads, and bounded sizes
-crates/kiri/src/setup.rs #556 opening Kiri.app re-appended the ~/.kiri/bin PATH block on every launch, modified shell profiles or replaced /usr/local/bin/kiri even when Homebrew's cask binary stanza already linked kiri directly (#733), macOS elevation staged files in $TMPDIR and escaped quotes before backslashes in AppleScript (#1013), and kiri setup appended Kiri's cli-plugins folder to cliPluginsExtraDirs in ~/.docker/config.json, overriding other engines' compose and buildx plugins for every Docker context (#1042)
-crates/kiri/src/k8s.rs #816 kiri k8s set had no --version or --k3s-arg/--clear-k3s-args options to pin a k3s image tag or pass custom k3s server flags, kiri k8s start did not sync ~/.kiri/k8s-manifests into k3s, and kiri k8s delete and node recreates omitted v=1 when removing kiri-k8s, leaving three anonymous volumes behind (#1103)
-crates/kiri-win/src/k8s.rs #816 Windows k8s.json config and container creation did not preserve or apply custom k3s version tags and extra k3s server arguments, and cluster delete and node recreates omitted v=1 when removing kiri-k8s, leaving three anonymous volumes behind (#1103)
+crates/kiri-image/src/roots.rs::windows_disabled_eku_drops_disabled_bundled_root_but_keeps_enabled_and_cross_roots #303 root store merge, system distrust filtering (macOS Never Trust, Windows Disallowed and disabled Server Auth EKU), cross-cert preservation, caps, and KIRI_TLS_ROOTS=webpki escape hatch
+crates/kiri/src/daemon/hostroots.rs::the_kept_roots_are_private_whatever_the_umask #303 Windows host roots persistence in WSL must enforce Caller::Host, 0600 atomic writes, non-symlink/non-FIFO reads, and bounded sizes
+crates/kiri/src/setup.rs::first_launch_edits_shell_profiles_only_once #556 opening Kiri.app re-appended the ~/.kiri/bin PATH block on every launch, modified shell profiles or replaced /usr/local/bin/kiri even when Homebrew's cask binary stanza already linked kiri directly (#733), macOS elevation staged files in $TMPDIR and escaped quotes before backslashes in AppleScript (#1013), and kiri setup appended Kiri's cli-plugins folder to cliPluginsExtraDirs in ~/.docker/config.json, overriding other engines' compose and buildx plugins for every Docker context (#1042)
+crates/kiri/src/k8s.rs::set_parses_persists_resets_and_builds_k3s_server_command #816 kiri k8s set had no --version or --k3s-arg/--clear-k3s-args options to pin a k3s image tag or pass custom k3s server flags, kiri k8s start did not sync ~/.kiri/k8s-manifests into k3s, and kiri k8s delete and node recreates omitted v=1 when removing kiri-k8s, leaving three anonymous volumes behind (#1103)
+crates/kiri-win/src/k8s.rs::custom_k3s_version_and_args_are_validated_and_applied #816 Windows k8s.json config and container creation did not preserve or apply custom k3s version tags and extra k3s server arguments, and cluster delete and node recreates omitted v=1 when removing kiri-k8s, leaving three anonymous volumes behind (#1103)
k8s-set-keeps-malformed-config #926 kiri k8s set replaced a k8s.json it could not parse with defaults, losing every other setting, and reported success
mac-gpg-ssh-agent-mount #763 macOS launchd-started daemons used Apple's empty default Listeners SSH socket instead of GnuPG's S.gpg-agent.ssh when enable-ssh-support was set, and direct host SSH agent socket bind mounts failed across virtiofs
-crates/kiri/src/daemon/grpc.rs #734 docker build run from a Docker CLI inside a socket-mounted container auto-created a buildx docker-container builder without default-load=true and never stored the built image in Kiri's image store
-crates/kiri-image/src/store.rs #864 an image put under a name another image had dropped the old record without freeing its unreferenced blobs, and Store::pin updated PINNED without BLOB_LOCK
+crates/kiri/src/daemon/grpc.rs::rewrites_moby_solve_request_and_preserves_other_fields #734 docker build run from a Docker CLI inside a socket-mounted container auto-created a buildx docker-container builder without default-load=true and never stored the built image in Kiri's image store
+crates/kiri-image/src/store.rs::an_image_put_under_a_taken_name_frees_the_blobs_only_the_old_one_used #864 an image put under a name another image had dropped the old record without freeing its unreferenced blobs, and Store::pin updated PINNED without BLOB_LOCK
bind-chown-chmod #382 chown on a macOS virtiofs bind mount returned 0 while leaving files owned by the caller so chmod by the new owner failed with EPERM, and warm bind-mount reads lacked close-to-open page/dir caching and BDI read-ahead (#415)
-crates/kiri/src/vm_cli.rs #473 macOS low ports (<1024) on 127.0.0.1/::1 failed without root instead of falling back to dual-stack with strict loopback peer filtering, and macOS VM had no shared_nat=false option (`kiri vm set --shared-nat off`) to omit VZNATNetworkDeviceAttachment and route egress/DNS over vsock under Cloudflare WARP (#383) or non-DF firewall drops (#350)
+crates/kiri/src/vm_cli.rs::save_shared_nat_creates_and_preserves_existing_vm_json_keys #473 macOS low ports (<1024) on 127.0.0.1/::1 failed without root instead of falling back to dual-stack with strict loopback peer filtering, and macOS VM had no shared_nat=false option (`kiri vm set --shared-nat off`) to omit VZNATNetworkDeviceAttachment and route egress/DNS over vsock under Cloudflare WARP (#383) or non-DF firewall drops (#350)
finder-mount-nobrowse #929 Finder showed an automatic < sidebar entry for the local NFS socket mount
guest-kernel-ext2-vfat #934 guest kernel lacked CONFIG_EXT4_USE_FOR_EXT2 and CONFIG_VFAT_FS so loop-mounted ext2 and FAT/EFI disk images failed to mount
guest-kernel-nfs-dmcrypt #494 guest kernel lacked CONFIG_NFS_FS / NFSv3 / NFSv4 client and CONFIG_DM_CRYPT / device-mapper so type=nfs volumes and LUKS dm-crypt devices failed in the macOS VM
guest-kernel-write-mounted #1056 guest kernel lacked CONFIG_BLK_DEV_WRITE_MOUNTED, so mount -o loop failed with EBUSY and a mounted block device could not be opened for writing
guest-kernel-loopaes-md5 #1074 guest kernel lacked CONFIG_CRYPTO_MD5, so dm-crypt loop-AES v2/v3 LMK mappings failed in the macOS VM
-crates/kiri-image/src/compress.rs #1070 Client::push re-gzipped every plain-tar layer upfront before checking HEAD on the registry instead of caching deterministic gzip metadata per verified layer blob
+crates/kiri-image/src/registry.rs::incremental_push_probes_head_from_gzip_stamp_without_recompressing_and_lazily_compresses_on_404 #1070 Client::push re-gzipped every plain-tar layer upfront before checking HEAD on the registry instead of caching deterministic gzip metadata per verified layer blob
machine-loop-partitions #977 partitions of a loop device attached with losetup -P inside a privileged kiri machine never appeared or updated in /dev
-crates/kiri-init/src/linux/devsync.rs #977 kiri-init did not sync loopN and loopNpM block device nodes from /sys/class/block into a running privileged machine's /dev tmpfs on kernel uevents, and later loop uevents replaced unchanged block nodes whose owner or mode udev or chown/chmod had modified (#1102)
+crates/kiri-init/src/linux/devsync.rs::sync_adds_updates_removes_and_enforces_tmpfs_st_dev_and_symlink_guards #977 kiri-init did not sync loopN and loopNpM block device nodes from /sys/class/block into a running privileged machine's /dev tmpfs on kernel uevents, and later loop uevents replaced unchanged block nodes whose owner or mode udev or chown/chmod had modified (#1102)
load-legacy-rootfs-and-layer-reuse #1064 docker load rejected legacy uppercase RootFS image configs without rootfs.type and zero-byte layer placeholders referencing locally stored diff_ids
-crates/kiri-image/src/archive.rs #1064 archive::load failed on legacy RootFS configs and zero-byte layer placeholders, and archive fixture directories used colons invalid on Windows (#1035)
-crates/kiri/src/machine.rs #935 kiri machine create always pulled --image instead of probing local images first, and --systemd machines mounted /tmp and /run with noexec
-crates/kiri/src/daemon/localtime.rs #938 Kiri WSL lacked /etc/localtime so `-v /etc/localtime:/etc/localtime:ro` created an empty directory there, breaking timezone bind mounts until self-healed and guarded against directory creation
-crates/kiri-init/src/linux/localtime.rs #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone
-scripts/kiri-linux.sh #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs
-crates/kiri-init/src/linux/dns.rs #932 IPv4-only container networks forwarded external AAAA queries returning unreachable IPv6 addresses, and enterprise macOS packet-tunnel / RTF_IFSCOPE VPNs bypassed host egress relay causing TLS handshake timeouts
+crates/kiri-image/src/archive.rs::loads_legacy_uppercase_rootfs_without_type_and_preserves_config_digest #1064 archive::load failed on legacy RootFS configs and zero-byte layer placeholders, and archive fixture directories used colons invalid on Windows (#1035)
+crates/kiri/src/machine.rs::local_image_skips_pull_and_creates_container_immediately #935 kiri machine create always pulled --image instead of probing local images first, and --systemd machines mounted /tmp and /run with noexec
+crates/kiri/src/daemon/localtime.rs::repairs_empty_localtime_directory_into_valid_tzif2_file #938 Kiri WSL lacked /etc/localtime so `-v /etc/localtime:/etc/localtime:ro` created an empty directory there, breaking timezone bind mounts until self-healed and guarded against directory creation
+crates/kiri-init/src/linux/localtime.rs::repairs_empty_dir_and_refuses_non_empty_dir #938 kiri-init on WSL did not self-heal a missing or empty-directory /etc/localtime on startup and parse_mounts could create a directory at /etc/localtime or /etc/timezone
+crates/kiri/src/daemon/localtime.rs::kiri_linux_script_populates_zoneinfo_and_valid_utc_tzif2 #938 Kiri Linux WSL rootfs omitted /usr/share/zoneinfo, /etc/localtime and /etc/timezone, preventing WSL 2 Windows-to-Linux timezone sync and leaving /etc/localtime missing on fresh installs
+crates/kiri-init/src/linux/dns.rs::ipv4_only_server_answers_external_aaaa_with_nodata_while_ipv6_forwards #932 IPv4-only container networks forwarded external AAAA queries returning unreachable IPv6 addresses, and enterprise macOS packet-tunnel / RTF_IFSCOPE VPNs bypassed host egress relay causing TLS handshake timeouts
tests/ui/volumes-size.js #936 Volumes view did not show each volume's disk size, and loading sizes synchronously or via GET /system/df could stall list refreshes or wake a sleeping VM
-crates/kiri/src/builds.rs #923 a running build's steps were read with `buildx history logs`, which follows the build until it ends: the Builds pane stayed on "Loading the steps..." and each 2 s ask left a docker and buildx process running
+crates/kiri/src/builds.rs::a_follower_gives_what_it_printed_and_is_stopped_with_its_children #923 a running build's steps were read with `buildx history logs`, which follows the build until it ends: the Builds pane stayed on "Loading the steps..." and each 2 s ask left a docker and buildx process running
tests/ui/builds-running.js #923 the Builds view asked for a running build's steps on every tick, not once the last ask was answered
-crates/kiri/src/setup_win.rs #984 on Windows, `kiri setup`, `kiri import` and `kiri build-with` were missing from `kiri.exe`, uninstalling Docker Desktop wiped `%USERPROFILE%\.docker\config.json` (`cliPluginsExtraDirs`, `kiri` context, dangling `desktop-linux`), `npipe_host` formatted `\\.\pipe\kiri` as `npipe://./pipe/kiri` instead of `npipe:////./pipe/kiri`, and `kiri` subcommands executed side effects or exited 1 on `--help` / `-h` (#982)
-crates/kiri-win/src/engine.rs #984 Windows `allowed_url` lacked `runkiri.com` and `canestack.com`, so Settings -> About links did not open, and `kiri-win` startup did not self-heal a wiped `~/.docker/config.json`
+crates/kiri/src/setup_win.rs::repairs_wiped_docker_config_and_dangling_desktop_linux_context #984 on Windows, `kiri setup`, `kiri import` and `kiri build-with` were missing from `kiri.exe`, uninstalling Docker Desktop wiped `%USERPROFILE%\.docker\config.json` (`cliPluginsExtraDirs`, `kiri` context, dangling `desktop-linux`), `npipe_host` formatted `\\.\pipe\kiri` as `npipe://./pipe/kiri` instead of `npipe:////./pipe/kiri`, and `kiri` subcommands executed side effects or exited 1 on `--help` / `-h` (#982)
+crates/kiri-win/src/engine.rs::only_runkiri_and_kiri_releases_open #984 Windows `allowed_url` lacked `runkiri.com` and `canestack.com`, so Settings -> About links did not open, and `kiri-win` startup did not self-heal a wiped `~/.docker/config.json`
vm-swap-as-set #326 the VM had no swap, so a container that outgrew the VM's memory was killed instead of slowing down
vm-swap-container-over-memory #326 a container over its --memory with --memory-swap room left was killed: the VM had no swap for its pages
-crates/kiri-init/src/linux/net.rs #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit
+crates/kiri-init/src/linux/net.rs::abstract_netns_lock_rejects_second_holder_across_full_retry_loop #443 a second Kiri engine starting in a shared Linux/WSL 2 network namespace overwrote nft table ip kiri, claimed existing kiri0 bridges, and tore down the first engine's network on exit
machine-prune-keeps #975 docker container prune and docker system prune deleted a stopped kiri machine and everything in its writable layer
-crates/kiri/src/daemon/vmlink.rs #948 VmLink::call waited without a timeout and Writer::write blocked indefinitely holding the writer mutex when the guest wedged, deadlocking hundreds of kiri-api threads
-crates/kiri-init/src/linux/container.rs #948 finish_stdio called recv_fd with no timeout on single-threaded kiri-init and exec did not reap a killed child when TTY setup failed
-crates/kiri/src/daemon/engine.rs #989 kiri-k8s caused mac_bind_sources to watch all of /Users and /Volumes via FSEvents, spawned kubectl every 3s for LoadBalancer polling, lacked timer coalescing for k3s's 100ms watch_progress tickers, Engine::route iterated HashMap in random order with equal priority (#1013), disconnecting a container from the none network was refused (#1084), and unstarted exec instances survived container stop to run on a subsequent start while inspect omitted ExecIDs and exec_capture leaked failed starts (#1104)
+crates/kiri/src/daemon/vmlink.rs::wedged_peer_that_never_replies_times_out_and_closes_transport #948 VmLink::call waited without a timeout and Writer::write blocked indefinitely holding the writer mutex when the guest wedged, deadlocking hundreds of kiri-api threads
+crates/kiri-init/src/linux/container.rs::finish_stdio_times_out_when_tty_child_never_sends_pty_and_reaps_child #948 finish_stdio called recv_fd with no timeout on single-threaded kiri-init and exec did not reap a killed child when TTY setup failed
+crates/kiri/src/daemon/engine.rs::k8s_node_skips_host_bind_watchers_and_gets_timer_slack #989 kiri-k8s caused mac_bind_sources to watch all of /Users and /Volumes via FSEvents, spawned kubectl every 3s for LoadBalancer polling, lacked timer coalescing for k3s's 100ms watch_progress tickers, Engine::route iterated HashMap in random order with equal priority (#1013), disconnecting a container from the none network was refused (#1084), and unstarted exec instances survived container stop to run on a subsequent start while inspect omitted ExecIDs and exec_capture leaked failed starts (#1104)
exec-dropped-on-stop #1104 an exec created before docker stop stayed registered and ran after docker start, and container inspect omitted ExecIDs
loop-partscan-keeps-perms #1102 a later unrelated loop uevent replaced existing /dev/loopNpM nodes and reset udev or chown/chmod owner and mode
disconnect-none-join #1084 docker network disconnect none was refused with 400 Bad Request, preventing --network none containers from detaching none and joining another network
-crates/kiri-init/src/linux/hostopts.rs #989 kiri-init hostopts lacked timerslack_ns support to coalesce k3s background pollers across execve, and lacked ipc/uts host option parsing for IpcMode and UTSMode (#1066)
-crates/kiri/src/daemon/hostopts.rs #1066 HostConfig.IpcMode and HostConfig.UTSMode were dropped at container create and omitted from inspect, reporting IpcMode="" instead of Docker's default "private"
+crates/kiri-init/src/linux/hostopts.rs::parses_and_refuses #989 kiri-init hostopts lacked timerslack_ns support to coalesce k3s background pollers across execve, and lacked ipc/uts host option parsing for IpcMode and UTSMode (#1066)
+crates/kiri/src/daemon/hostopts.rs::ipc_and_uts_modes #1066 HostConfig.IpcMode and HostConfig.UTSMode were dropped at container create and omitted from inspect, reporting IpcMode="" instead of Docker's default "private"
ipc-mode-inspect #1066 docker inspect returned an empty HostConfig.IpcMode by default and dropped explicit --ipc and --uts modes
ipc-mode-shareable #1066 --ipc shareable, --ipc container: and --ipc none were not applied to container IPC namespaces and /dev/shm mounts
-crates/kiri/src/engine_cli.rs #983 kiri CLI had no `kiri engine start | stop | restart | status [--json]` commands to stop, restart, or inspect the engine without waking a sleeping VM
-crates/kiri-win/src/refuse.rs #983 Windows pipe gate did not handle `POST /kiri/stop` idempotently while stopped or synchronize `kiri-win` on external CLI stops
-crates/kiri/src/domains_cli.rs #744 `kiri domains set` and `kiri domains reset` failed with a daemon-not-running error instead of updating `domains.json` offline when the daemon was stopped
-crates/kiri-image/src/registry.rs #611 `Client::manifest` did not retry transient registry responses such as HTTP 429 during concurrent image pulls
-crates/kiri/src/daemon/storage.rs #190 `statvfs_usage` subtracted `f_bavail` instead of `f_bfree`, counting ~55 GB of ext4 root-reserved free blocks on WSL's sparse `ext4.vhdx` as used disk space
-crates/kiri/src/dockerctx.rs #269 Windows `repair_windows_config` did not self-heal `%USERPROFILE%\.docker\contexts\meta\\meta.json` when overwritten with a WSL `unix://` socket endpoint
-crates/kiri-proto/src/lib.rs #381 `start_on_vm` spawned the container process before attaching `spec.extra_networks`, causing fast `docker compose run` commands on secondary external networks to run before `eth1` and its IPv4 default route were attached
-crates/kiri/src/daemon/binds.rs #420 WSL distro bind translation rewrote `/run/host-services/ssh-auth.sock` and `/sys` paths into `/mnt/wsl/kiri/roots//...`, local `o=bind` volumes did not resolve `device` relative to the calling WSL distro or Windows drive, and `on_drive` passed `/mnt/wslg/distro` through to Kiri's own WSL rootfs (#1013)
+crates/kiri/src/engine_cli.rs::collect_status_sends_background_header_and_respects_offline_stopped_marker #983 kiri CLI had no `kiri engine start | stop | restart | status [--json]` commands to stop, restart, or inspect the engine without waking a sleeping VM
+crates/kiri-win/src/refuse.rs::stopped_gate_allows_wake_and_refuses_other_requests_with_503 #983 Windows pipe gate did not handle `POST /kiri/stop` idempotently while stopped or synchronize `kiri-win` on external CLI stops
+crates/kiri/src/daemon/domains.rs::offline_set_and_reset_update_saved_ports_and_validate #744 `kiri domains set` and `kiri domains reset` failed with a daemon-not-running error instead of updating `domains.json` offline when the daemon was stopped
+crates/kiri-image/src/registry.rs::manifest_retries_transient_429_before_succeeding #611 `Client::manifest` did not retry transient registry responses such as HTTP 429 during concurrent image pulls
+crates/kiri/src/daemon/storage.rs::statvfs_usage_counts_bfree_not_bavail_root_reserve #190 `statvfs_usage` subtracted `f_bavail` instead of `f_bfree`, counting ~55 GB of ext4 root-reserved free blocks on WSL's sparse `ext4.vhdx` as used disk space
+crates/kiri/src/dockerctx.rs::windows_config_repair_heals_wiped_config_plugins_and_dangling_desktop_context #269 Windows `repair_windows_config` did not self-heal `%USERPROFILE%\.docker\contexts\meta\\meta.json` when overwritten with a WSL `unix://` socket endpoint
+crates/kiri-proto/src/lib.rs::round_trip #381 `start_on_vm` spawned the container process before attaching `spec.extra_networks`, causing fast `docker compose run` commands on secondary external networks to run before `eth1` and its IPv4 default route were attached
+crates/kiri/src/daemon/binds.rs::wsl_distro_path_translation_and_confinement #420 WSL distro bind translation rewrote `/run/host-services/ssh-auth.sock` and `/sys` paths into `/mnt/wsl/kiri/roots//...`, local `o=bind` volumes did not resolve `device` relative to the calling WSL distro or Windows drive, and `on_drive` passed `/mnt/wslg/distro` through to Kiri's own WSL rootfs (#1013)
image-load-diffid-mismatch-refused #1013 docker load accepted archives whose uncompressed layer SHA-256 did not match rootfs.diff_ids
-crates/kiri-image/src/diffid.rs #1013 image pull and load did not verify uncompressed layer SHA-256 digests against rootfs.diff_ids or bound multi-layer decompression
-crates/kiri-zstd/src/lib.rs #1013 zstd and gzip layer decompression lacked multi-frame zstd block/checksum verification and trailing-byte gzip rejection
-crates/kiri/src/daemon/builder.rs #1013 managed privileged BuildKit container trusted mutable local moby/buildkit:buildx-stable-1 tags without verifying pinned config digest and layer diff_ids
-crates/kiri/src/fdclean.rs #1089 kiri-forge worker and daemon helper subprocesses inherited published-port listening sockets and vsock descriptors without FD_CLOEXEC, preventing recreated containers from rebinding their host ports
+crates/kiri-image/src/diffid.rs::bounded_parallelism_and_per_layer_and_per_image_zip_bomb_caps #1013 image pull and load did not verify uncompressed layer SHA-256 digests against rootfs.diff_ids or bound multi-layer decompression
+crates/kiri-zstd/src/lib.rs::checked_gzip_multi_member_and_trailing_byte_rejection #1013 zstd and gzip layer decompression lacked multi-frame zstd block/checksum verification and trailing-byte gzip rejection
+crates/kiri/src/daemon/builder.rs::builder_image_pin_rejects_spoofed_and_accepts_retagged_genuine #1013 managed privileged BuildKit container trusted mutable local moby/buildkit:buildx-stable-1 tags without verifying pinned config digest and layer diff_ids
+crates/kiri/src/fdclean.rs::child_does_not_inherit_low_or_high_listening_sockets #1089 kiri-forge worker and daemon helper subprocesses inherited published-port listening sockets and vsock descriptors without FD_CLOEXEC, preventing recreated containers from rebinding their host ports
publish-recreate-after-forge-build #1089 recreating a container on the same published host port after spawning kiri-forge worker failed with 409 port is already allocated
entrypoint-image-empty #1091 an image built with ENTRYPOINT [""] kept [""] and failed to start: executable file not found in $PATH
-crates/kiri-init/src/linux/layers.rs #1068 layer unpack split PAX SCHILY.xattr.* records on 0x0a instead of reading each record by its decimal length prefix, failing with malformed pax extension when an xattr or POSIX ACL value contained 0x0a
+crates/kiri-init/src/linux/layers.rs::pax_xattrs_with_newline_and_posix_acl_unpack_into_layer #1068 layer unpack split PAX SCHILY.xattr.* records on 0x0a instead of reading each record by its decimal length prefix, failing with malformed pax extension when an xattr or POSIX ACL value contained 0x0a
pax-xattr-newline #1068 unpacking an image layer with 0x0a inside a PAX SCHILY.xattr.* value failed container creation with malformed pax extension
-crates/kiri/src/daemon/dns.rs #1067 macOS DNS relay read only /etc/resolver/* and /etc/resolv.conf, returning NXDOMAIN for VPN split-DNS Supplemental domains in scutil --dns when a security NetworkExtension activated prefer_relay
-crates/kiri-init/src/linux/rmtree.rs #1013 deep directory removal in kiri-init used recursive remove_dir_all, exhausting stack or file descriptors and failing on deep read-only trees
-crates/kiri-init/src/linux/tarnum.rs #993 layer unpack failed on zero-mtime PAX XGlobalHeader entries and leading-NUL octal tar header fields
+crates/kiri/src/daemon/dns.rs::scutil_dns_supplemental_resolvers_route_vpn_split_dns_and_respect_precedence #1067 macOS DNS relay read only /etc/resolver/* and /etc/resolv.conf, returning NXDOMAIN for VPN split-DNS Supplemental domains in scutil --dns when a security NetworkExtension activated prefer_relay
+crates/kiri-init/src/linux/rmtree.rs::removes_deep_tree_past_2000_levels_and_readonly_0500_0000_past_path_max #1013 deep directory removal in kiri-init used recursive remove_dir_all, exhausting stack or file descriptors and failing on deep read-only trees
+crates/kiri-init/src/linux/tarnum.rs::leading_nuls_before_octal_digits_parse_as_in_go #993 layer unpack failed on zero-mtime PAX XGlobalHeader entries and leading-NUL octal tar header fields
bind-share-ancestors-and-proc-refused #1013 macOS bind mounts did not block VM root/ancestors of /mnt/mac, /proc//root/mnt/mac traversals, or symlinks escaping MAC_SHARES, nor revalidate stored mounts on start and cp
volume-driver-allowlist #1013 local volume options accepted arbitrary filesystem types and /dev/* block devices such as type=ext4,device=/dev/vda
-crates/kiri-init/src/linux/volmount.rs #1013 host and VM local volume mount validation lacked strict filesystem type, device, and mount-option allowlists, and synchronous network-volume mounts blocked the agent loop (#1085)
-crates/kiri-init/src/linux/relay.rs #1085 macOS NFS and CIFS volume mounts whose server matched a host egress or host-bound redirect deadlocked inside mount(2) for 40 s because the VM relay shared the single-threaded agent loop, and broader split-tunnel VPN prefixes captured narrower non-tunnel LAN routes
+crates/kiri-init/src/linux/volmount.rs::strict_volume_type_and_device_allowlist #1013 host and VM local volume mount validation lacked strict filesystem type, device, and mount-option allowlists, and synchronous network-volume mounts blocked the agent loop (#1085)
+crates/kiri-init/src/linux/relay.rs::forked_vm_relays_pump_output_redirected_rpc_while_parent_blocks #1085 macOS NFS and CIFS volume mounts whose server matched a host egress or host-bound redirect deadlocked inside mount(2) for 40 s because the VM relay shared the single-threaded agent loop, and broader split-tunnel VPN prefixes captured narrower non-tunnel LAN routes
nfs-volume-host-relay #1085 mounting a macOS NFSv4 volume routed through the VM host relay blocked the agent loop instead of relaying the kernel's RPCs
dns-and-domainname-control-chars-refused #1013 Domainname, Dns, DnsSearch, DnsOptions, --link aliases, and build extrahosts accepted control characters or non-IP nameserver strings
-crates/kiri/src/daemon/proxy.rs #1013 GET /kiri/proxy exposed cleartext proxy credentials to non-Host callers
-crates/kiri/src/daemon/hostetc.rs #1034 generated /etc files were written in place instead of atomically via create_new + rename, exposing truncated reads during concurrent container starts and following symlinks at the target or temporary path
-crates/kiri/src/forge_mgr.rs #1086 Forge release checks and archive downloads (along with tools, Grype scanner, and update HTTP clients) ignored Kiri's configured proxy and WSL loopback proxy relay
-crates/kiri/src/kiribuild.rs #1065 kiri build BuildKit fallback failed when docker buildx version did not find buildx directly even though docker-buildx existed in cliPluginsExtraDirs, system plugin directories, or Kiri's own bundled cli-plugins folder
+crates/kiri/src/daemon/proxy.rs::a_proxy_is_shown_without_its_password #1013 GET /kiri/proxy exposed cleartext proxy credentials to non-Host callers
+crates/kiri/src/daemon/hostetc.rs::concurrent_readers_never_observe_empty_or_partial_files #1034 generated /etc files were written in place instead of atomically via create_new + rename, exposing truncated reads during concurrent container starts and following symlinks at the target or temporary path
+crates/kiri/src/forge_mgr.rs::honours_relayed_daemon_proxy_custom_settings_no_proxy_and_cli_env #1086 Forge release checks and archive downloads (along with tools, Grype scanner, and update HTTP clients) ignored Kiri's configured proxy and WSL loopback proxy relay
+crates/kiri/tests/build_passthrough.rs::fallback_discovers_buildx_in_extra_dirs_and_bundled_plugins_or_reports_clearly #1065 kiri build BuildKit fallback failed when docker buildx version did not find buildx directly even though docker-buildx existed in cliPluginsExtraDirs, system plugin directories, or Kiri's own bundled cli-plugins folder
host-internal-server-close #1077 host.docker.internal, outbound egress, and SSH agent vsock relays hung waiting for guest EOF when the host side closed first on macOS Virtualization.framework, stalling EOF-delimited or keep-alive clients and leaking descriptors and threads until EMFILE
-crates/kiri-vmm/src/apple.rs #1077 VsockStream::drop did not call VZVirtioSocketConnection::close on the VM queue, leaving accepted guest vsock streams open inside Virtualization.framework when closed from the host
+crates/kiri/src/daemon/ports.rs::host_bound_and_guest_target_relay_handle_half_close_without_leaking_fds_or_threads #1077 VsockStream::drop did not call VZVirtioSocketConnection::close on the VM queue, leaving accepted guest vsock streams open inside Virtualization.framework when closed from the host
internal-dns-refused #1013 embedded DNS forwarded external queries from --internal networks and gateway DNS listeners did not isolate bridges via SO_BINDTODEVICE
internal-netadmin-blocked #1013 --internal bridges were not isolated across nftables prerouting, forward, input, and postrouting chains
isolated-host-unreached #1001 com.docker.network.bridge.gateway_mode_ipv4=isolated and inhibit_ipv4=true did not leave the host off an internal network's bridge
@@ -433,27 +434,27 @@ publish-bridge-default-host-ip #985 com.docker.network.bridge.host_binding_ipv4
icc-off-no-peer #213 com.docker.network.bridge.enable_icc=false was accepted but not enforced via bridge port isolation
icc-off-connect-no-peer #213 a container joined via network connect to an enable_icc=false network still reached peer containers on that bridge
network-name-default-refused #992 Networks::create allowed creating an unreachable user network named default and parse_ipam_both accepted network or broadcast addresses as gateways
-crates/kiri/src/daemon/apparmor.rs #1013 Linux hosts with AppArmor enabled ran containers unconfined without loading and enforcing kiri-default
-crates/kiri/src/kubeconfig.rs #1013 kubeconfig::from_k3s passed untrusted k3s YAML lines through to ~/.kube/config without an inline credential allowlist and k8s.rs did not pin rancher/k3s by digest
-crates/kiri/src/weburl.rs #1013 WebView link opening, localUrl domain labels, CSP, navigation policy, and i18n markup parity needed shared strict validation
+crates/kiri/src/daemon/apparmor.rs::what_start_finds #1013 Linux hosts with AppArmor enabled ran containers unconfined without loading and enforcing kiri-default
+crates/kiri/src/kubeconfig.rs::rejects_exec_auth_provider_and_host_file_read_payloads #1013 kubeconfig::from_k3s passed untrusted k3s YAML lines through to ~/.kube/config without an inline credential allowlist and k8s.rs did not pin rancher/k3s by digest
+crates/kiri/src/weburl.rs::bypasses_are_refused #1013 WebView link opening, localUrl domain labels, CSP, navigation policy, and i18n markup parity needed shared strict validation
tests/ui/csp.js #1013 assembled UI HTML lacked a SHA-256 script Content-Security-Policy blocking injected scripts
tests/ui/domain-label.js #1013 localUrl accepted non-plain hostnames or rendered non-HTTP domain URLs
tests/ui/tr-markup.js #1013 localized strings were not sanitized for safe inline tags and attribute parity at runtime
tests/ui/typed-values.js #1013 hub and sharing JSON renderers interpolated numeric fields without finite-number coercion
-crates/kiri/src/usb/helper.rs #1013 macOS USB helper staged signed binaries through $TMPDIR instead of a root-owned staging file verified before codesign
-crates/kiri-win/src/update.rs #1013 Windows MSI updater staged in %TEMP% and lacked WinVerifyTrust Authenticode / Ed25519 signature verification before silent msiexec
-crates/kiri/src/diag/redact.rs #994 kiri diag did not redact JSON secret values truncated before their closing quote at end of text
+crates/kiri/src/usb/helper.rs::install_script_verifies_shasum_before_codesign_and_avoids_tmpdir #1013 macOS USB helper staged signed binaries through $TMPDIR instead of a root-owned staging file verified before codesign
+crates/kiri-win/src/update.rs::verifies_detached_ed25519_signatures_in_hex_and_base64 #1013 Windows MSI updater staged in %TEMP% and lacked WinVerifyTrust Authenticode / Ed25519 signature verification before silent msiexec
+crates/kiri/src/diag/redact.rs::a_json_value_cut_off_by_the_end_of_the_text_is_taken_out #994 kiri diag did not redact JSON secret values truncated before their closing quote at end of text
guest/kernel/patches/0011-virtio-net-repair-unfinished-checksums.patch #1029 macOS Virtualization.framework delivered replies from another bridged/shared VM on the same Mac with unfinished pseudo-header-only TX checksums and no DATA_VALID flag, causing the guest kernel to drop them on host and container paths
-crates/kiri/src/ui/mod.rs #1031 containers with a Compose project label and a missing service label showed undefined. in the UI (and an empty service label or the menu lost the local address) instead of falling back to the container name, and HTTPS links were emitted for names TLS refuses
+crates/kiri/src/ui/mod.rs::menu_local_url_matches_tls_and_router_rules #1031 containers with a Compose project label and a missing service label showed undefined. in the UI (and an empty service label or the menu lost the local address) instead of falling back to the container name, and HTTPS links were emitted for names TLS refuses
tests/ui/compose-no-compose-file.js #1031 projects carrying only com.docker.compose.project without config_files or working_dir showed the missing-compose-file warning instead of a plain notice
tests/ui/compose-label-only-services.js #1031 containers carrying com.docker.compose.project without com.docker.compose.service produced a phantom empty-name service in project_row and a Not created row in cmpUnmade
tests/ui/compose-no-compose-file-actions.js #1031 projects made without a compose file sent Start/Stop/Restart/Remove and Logs through docker compose -p (skipping containers without service labels), offered Show in compose file on member rows, and blanked svc in label_by_service
-crates/kiri/src/singleflight.rs #1016 build-history queries could overlap, drop refreshes while in flight, hang without a timeout, or query builder aliases of the same node twice
-crates/kiri/src/daemon/health.rs #1052 Health::next_wait slept the full start_interval (5s by default) even when less of start_period remained, delaying the first probe and regular interval past start_period
+crates/kiri/src/singleflight.rs::two_requests_during_one_query_give_exactly_one_more_query #1016 build-history queries could overlap, drop refreshes while in flight, hang without a timeout, or query builder aliases of the same node twice
+crates/kiri/src/daemon/health.rs::start_interval_is_capped_by_remaining_start_period #1052 Health::next_wait slept the full start_interval (5s by default) even when less of start_period remained, delaying the first probe and regular interval past start_period
health-start-interval-capped #1052 a healthcheck with --health-interval 2s --health-start-period 2s waited 5s (default start_interval) instead of probing within the 2s start_period
tests/ui/volume-network-used.js #1062 Volumes and Networks views lacked a Used by column showing attached containers per state and container names in tooltips
tests/ui/window-script-types.js #1033 setRail passed a boolean to setAttribute("aria-pressed"), dgTime called global isNaN on a Date, and [data-smore] chained void closeMenu()/showMenu() with ||
tests/ui/logs-sort-order.js #1081 Container and Compose log views could only display lines oldest-first without a toggle to view newest lines at the top
-crates/kiri/src/fontconfig.rs #1078 stale or corrupt user ~/.cache/fontconfig files on Linux trapped WebKitWebProcess in a 100% CPU loop before first paint with a blank window and no diagnostic warning
-crates/kiri-init/src/linux/disk.rs #1118 an ext4 data disk with EXT4_ERROR_FS or sparse_super2 stayed stuck at 64 GiB when KIRI_DISK_GB or vm.json raised data.img, and VM shutdown skipped swapoff and umount on /var/lib/kiri
-crates/kiri/src/guest/disk.rs #1118 kiri engine restart raced Virtualization.framework's retiring XPC helper for O_EXLOCK on vm/data.img instead of waiting for an exclusive flock before growing and reattaching the disk
+crates/kiri/src/fontconfig.rs::bypass_stamp_persists_while_unchanged_and_retires_when_rebuilt_or_removed #1078 stale or corrupt user ~/.cache/fontconfig files on Linux trapped WebKitWebProcess in a 100% CPU loop before first paint with a blank window and no diagnostic warning
+crates/kiri-init/src/linux/disk.rs::repairs_dirty_ext4_grows_sparse_super2_and_grows_online_when_root #1118 an ext4 data disk with EXT4_ERROR_FS or sparse_super2 stayed stuck at 64 GiB when KIRI_DISK_GB or vm.json raised data.img, and VM shutdown skipped swapoff and umount on /var/lib/kiri
+crates/kiri/src/guest/disk.rs::wait_unlocked_and_grow_waits_for_flock_holder_releases_lock_and_times_out #1118 kiri engine restart raced Virtualization.framework's retiring XPC helper for O_EXLOCK on vm/data.img instead of waiting for an exclusive flock before growing and reattaching the disk