Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

feat(ci): add lane classifier, sharded test runner, ratchet, gate and integration engine

rubenluetke10-beep0cd8d7e23c11
diff --git a/scripts/agent_land.py b/scripts/agent_land.py
new file mode 100644
index 0000000000..6621781c12
--- /dev/null
+++ b/scripts/agent_land.py
@@ -0,0 +1,187 @@
+#!/usr/bin/env python3
+"""Land a coding agent's finished branch: rebase, self-check, push.
+
+One command for every agent (Claude Code, Codex, Gemini CLI, ...) working in
+its own worktree or clone::
+
+ python scripts/agent_land.py # on a feature branch -> PR, auto-merge
+ python scripts/agent_land.py --direct # fast-forward main itself
+
+What it does, in order — and it stops at the first real problem:
+
+1. **Rebase** the branch onto the latest ``<remote>/main``. Generated files
+ (frontend dist, agent mirrors, reference docs, lockfiles) and append-only
+ files (CHANGELOG) are resolved automatically; anything else is listed for
+ the agent to resolve (or handed to ``--resolver-cmd``).
+2. **Static gates** — ``scripts/ci/run_gates.py``, the same set CI runs.
+3. **Relevant tests** — ``scripts/ci/select_tests.py`` picks the test files
+ the diff can affect and ``scripts/ci/run_tests_parallel.py`` runs them in
+ isolated processes. The full suite runs in CI.
+4. **Push** — a feature branch gets a pull request labelled ``auto-merge``;
+ the merge train keeps it current and lands it once the CI gate is green.
+
+It never stashes, never force-pushes, and refuses a dirty worktree: the main
+checkout is shared with other sessions, so this belongs in your own worktree.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import subprocess
+import sys
+import tempfile
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from scripts.ci import agent_integrate # noqa: E402
+from scripts.ci.select_tests import SMOKE # noqa: E402
+
+PY = sys.executable
+
+
+def run(cmd: list[str], *, check: bool = False) -> subprocess.CompletedProcess[str]:
+ return subprocess.run( # noqa: S603
+ cmd,
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=check,
+ )
+
+
+def step(title: str) -> None:
+ print(f"\n== {title}", flush=True)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--remote", default="origin")
+ parser.add_argument("--direct", action="store_true", help="Push straight to main.")
+ parser.add_argument("--pr", action="store_true", help="Push the branch and open a PR.")
+ parser.add_argument("--skip-tests", action="store_true")
+ parser.add_argument("--skip-gates", action="store_true")
+ parser.add_argument("--no-push", action="store_true", help="Check only.")
+ parser.add_argument(
+ "--resolver-cmd",
+ default=os.environ.get("CONFLICT_RESOLVER_CMD", ""),
+ help="Command that edits conflicted files in place (prompt on stdin).",
+ )
+ args = parser.parse_args(argv)
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+
+ branch = run(["git", "rev-parse", "--abbrev-ref", "HEAD"], check=True).stdout.strip()
+ direct = args.direct or (branch == "main" and not args.pr)
+ dirty = run(["git", "status", "--porcelain", "--untracked-files=no"]).stdout.strip()
+ if dirty:
+ print("Refusing to land: the worktree has uncommitted changes to tracked files.")
+ print("Commit your own paths first (git commit -- <paths>); never stash here.")
+ return 2
+ upstream = f"{args.remote}/main"
+
+ step(f"1/4 rebase {branch} onto {upstream}")
+ if run(["git", "fetch", "--quiet", args.remote, "main"]).returncode != 0:
+ print(f"Could not fetch {upstream}.")
+ return 2
+ report = agent_integrate.update(upstream, "rebase", args.resolver_cmd, REPO_ROOT)
+ print(report)
+ if report["status"] == "conflict":
+ print("\nThese files conflict and need a human-quality resolution:")
+ for path in report.get("unresolved", []): # type: ignore[union-attr]
+ print(f" - {path}")
+ print(
+ f"\nRun `git rebase {upstream}`, resolve them (keep both sides' intent), "
+ "`git add` them, `git rebase --continue`, then run this script again."
+ )
+ return 3
+
+ if not args.skip_gates:
+ step("2/4 static gates")
+ gates = subprocess.run( # noqa: S603
+ [PY, "scripts/ci/run_gates.py", "--base", upstream, "--pr"], cwd=REPO_ROOT, check=False
+ )
+ if gates.returncode != 0:
+ print("A static gate failed - fix it before landing.")
+ return 4
+
+ if not args.skip_tests:
+ step("3/4 relevant tests")
+ changed = run(["git", "diff", "--name-only", f"{upstream}...HEAD"]).stdout
+ with tempfile.TemporaryDirectory(prefix="agent-land-") as tmp:
+ changed_file = Path(tmp) / "changed.txt"
+ selected = Path(tmp) / "selected.txt"
+ changed_file.write_text(changed, encoding="utf-8")
+ sel = run(
+ [
+ PY,
+ "scripts/ci/select_tests.py",
+ "--changed-from",
+ str(changed_file),
+ "--out",
+ str(selected),
+ ]
+ )
+ print(sel.stdout.strip())
+ files = [x for x in selected.read_text(encoding="utf-8").splitlines() if x]
+ if "mode=all" in sel.stdout:
+ print("The change reaches the whole suite; running the contract guards here.")
+ files = list(SMOKE)
+ selected.write_text("\n".join(files) + "\n", encoding="utf-8")
+ if files:
+ tests = subprocess.run( # noqa: S603
+ [
+ PY,
+ "scripts/ci/run_tests_parallel.py",
+ "--files-from",
+ str(selected),
+ "--report",
+ str(Path(tmp) / "report.json"),
+ "--junit-out",
+ str(Path(tmp) / "report.xml"),
+ ],
+ cwd=REPO_ROOT,
+ check=False,
+ )
+ if tests.returncode != 0:
+ print(
+ "Relevant tests failed. If a failure is pre-existing on main, it is in "
+ "scripts/ci/test-baseline-*.json and CI will not block on it."
+ )
+ return 5
+ else:
+ print("No test can see this change.")
+
+ if args.no_push:
+ print("\nChecks passed; --no-push given, nothing pushed.")
+ return 0
+ step("4/4 push")
+ if direct:
+ push = run(["git", "push", args.remote, "HEAD:main"])
+ print(push.stdout + push.stderr)
+ if push.returncode != 0:
+ print("main moved while checking - run this script again (it rebases first).")
+ return 6
+ return 0
+ push = run(["git", "push", "--set-upstream", args.remote, f"HEAD:refs/heads/{branch}"])
+ print(push.stdout + push.stderr)
+ if push.returncode != 0:
+ print("Push rejected. Never force it: pull, re-run this script.")
+ return 6
+ existing = run(["gh", "pr", "view", branch, "--json", "number", "-q", ".number"])
+ if existing.returncode == 0 and existing.stdout.strip():
+ print(f"PR #{existing.stdout.strip()} updated; the merge train lands it when green.")
+ return 0
+ created = run(["gh", "pr", "create", "--fill", "--base", "main", "--label", "auto-merge"])
+ print(created.stdout + created.stderr)
+ return 0 if created.returncode == 0 else 7
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/agent_integrate.py b/scripts/ci/agent_integrate.py
new file mode 100644
index 0000000000..630603b0e9
--- /dev/null
+++ b/scripts/ci/agent_integrate.py
@@ -0,0 +1,548 @@
+#!/usr/bin/env python3
+"""Bring a branch up to date with main and resolve merge conflicts on its own.
+
+This is the engine behind both halves of agent integration:
+
+* the **merge train** (``.github/workflows/merge-train.yml`` -> ``train``)
+ that keeps every open agent pull request current with main and lands the
+ green ones one at a time, and
+* ``scripts/agent_land.py``, which a coding agent runs locally before it
+ pushes.
+
+Conflicts are resolved by file class, cheapest first:
+
+1. **Generated files** (frontend ``dist/``, the AGENTS.md / .agents / .codex
+ mirrors, the CLI reference docs, lockfiles, timing caches): take main's
+ copy, then REGENERATE from the merged sources. A hand-merge of generated
+ output is always wrong; a regeneration is always right.
+2. **Append-only files** (CHANGELOG.md, allowlists, .gitignore): a union
+ merge keeps both sides' lines.
+3. **Everything else**: handed to an optional resolver command
+ (``--resolver-cmd``, e.g. ``claude -p`` or ``codex exec -``) that edits
+ the files in place. Its output must leave no conflict markers and must
+ still parse (Python compiles, JSON loads) — otherwise the update aborts.
+4. Anything still unresolved aborts cleanly and is reported, so a human or
+ the authoring agent resolves it. Nothing half-merged is ever committed.
+
+``git rerere`` is on throughout, so a resolution recorded once is replayed.
+
+Usage::
+
+ agent_integrate.py update --onto origin/main [--mode merge|rebase]
+ agent_integrate.py train --repo OWNER/NAME [--dry-run]
+"""
+
+from __future__ import annotations
+
+import argparse
+import fnmatch
+import json
+import os
+import py_compile
+import shlex
+import shutil
+import subprocess
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+FRONTEND = "jarvis/ui/web/frontend"
+
+# (glob, regenerator key). Main's copy is taken, then the key regenerates it.
+GENERATED: tuple[tuple[str, str], ...] = (
+ ("jarvis/ui/web/dist/*", "frontend-build"),
+ ("AGENTS.md", "mirrors"),
+ (".agents/*", "mirrors"),
+ (".codex/agents/*", "mirrors"),
+ ("docs/jarvis-cli-reference.md", "reference-docs"),
+ ("docs/commands-reference.md", "reference-docs"),
+ (f"{FRONTEND}/package-lock.json", "npm-lock"),
+ ("uv.lock", "uv-lock"),
+ ("requirements.txt", "requirements"),
+ ("test_durations.json", ""),
+ ("scripts/ci/test-baseline-*.json", ""),
+)
+UNION: tuple[str, ...] = (
+ "CHANGELOG.md",
+ "scripts/ci/german-allowlist.txt",
+ ".gitignore",
+ "docs/BUGS.md",
+)
+AGENT_BRANCH_PREFIXES = ("codex/", "claude/", "agent/", "agents/", "gemini/", "cursor/", "bot/")
+OPT_OUT_LABELS = {"no-auto-merge", "do-not-merge", "wip", "needs-human"}
+OPT_IN_LABEL = "auto-merge"
+GATE_CHECK = "CI gate"
+
+
+def git(*args: str, check: bool = True, cwd: Path = REPO_ROOT) -> subprocess.CompletedProcess[str]:
+ return subprocess.run( # noqa: S603
+ ["git", "-c", "rerere.enabled=true", "-c", "rerere.autoupdate=true", *args], # noqa: S607
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=check,
+ )
+
+
+def _sh(cmd: list[str], *, cwd: Path = REPO_ROOT, stdin: str | None = None) -> int:
+ print(f"[integrate] $ {' '.join(cmd)}", flush=True)
+ proc = subprocess.run( # noqa: S603
+ cmd,
+ cwd=cwd,
+ input=stdin,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ )
+ return proc.returncode
+
+
+def classify(path: str) -> tuple[str, str]:
+ """Return (strategy, regenerator) for a conflicted path."""
+ for pattern, regen in GENERATED:
+ if fnmatch.fnmatch(path, pattern):
+ return "generated", regen
+ if path in UNION:
+ return "union", ""
+ return "semantic", ""
+
+
+def conflicted_files(cwd: Path = REPO_ROOT) -> list[str]:
+ out = git("diff", "--name-only", "--diff-filter=U", cwd=cwd).stdout
+ return [line.strip() for line in out.splitlines() if line.strip()]
+
+
+def has_markers(path: Path) -> bool:
+ try:
+ text = path.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return False
+ return text.startswith("<<<<<<< ") or any(m in text for m in ("\n<<<<<<< ", "\n>>>>>>> "))
+
+
+def still_valid(path: Path) -> str | None:
+ """Return an error when a resolved file no longer parses."""
+ if not path.exists():
+ return None
+ if has_markers(path):
+ return "conflict markers remain"
+ if path.suffix == ".py":
+ try:
+ py_compile.compile(str(path), doraise=True)
+ except py_compile.PyCompileError as exc:
+ return f"does not compile: {exc.msg.strip()[:200]}"
+ if path.suffix == ".json":
+ try:
+ json.loads(path.read_text(encoding="utf-8"))
+ except ValueError as exc:
+ return f"invalid JSON: {exc}"
+ return None
+
+
+def _stage_blob(stage: int, path: str, cwd: Path) -> str | None:
+ result = git("show", f":{stage}:{path}", check=False, cwd=cwd)
+ return result.stdout if result.returncode == 0 else None
+
+
+def union_merge(path: str, cwd: Path) -> bool:
+ base = _stage_blob(1, path, cwd) or ""
+ ours = _stage_blob(2, path, cwd)
+ theirs = _stage_blob(3, path, cwd)
+ if ours is None or theirs is None:
+ return False
+ tmp = cwd / ".git-union-tmp"
+ tmp.mkdir(exist_ok=True)
+ try:
+ files = []
+ for name, text in (("ours", ours), ("base", base), ("theirs", theirs)):
+ target = tmp / name
+ target.write_text(text, encoding="utf-8", newline="")
+ files.append(str(target))
+ proc = subprocess.run( # noqa: S603
+ ["git", "merge-file", "--union", "-p", *files], # noqa: S607
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ check=False,
+ cwd=cwd,
+ )
+ (cwd / path).write_text(proc.stdout, encoding="utf-8", newline="")
+ finally:
+ shutil.rmtree(tmp, ignore_errors=True)
+ git("add", "--", path, cwd=cwd)
+ return True
+
+
+def take_side(path: str, side: str, cwd: Path) -> None:
+ """Check out one side of a conflict; a side that deleted the file deletes it."""
+ result = git("checkout", f"--{side}", "--", path, check=False, cwd=cwd)
+ if result.returncode != 0:
+ git("rm", "-q", "--cached", "--ignore-unmatch", "--", path, check=False, cwd=cwd)
+ (cwd / path).unlink(missing_ok=True)
+ return
+ git("add", "--", path, cwd=cwd)
+
+
+def regenerate(keys: set[str], cwd: Path) -> list[str]:
+ """Run the regenerators; return the ones that failed."""
+ failures: list[str] = []
+ py = sys.executable
+ commands: dict[str, list[list[str]]] = {
+ "mirrors": [
+ [py, "scripts/ci/sync_agents_md.py"],
+ [py, "scripts/ci/sync_agents_dir.py"],
+ [py, "scripts/ci/sync_codex_agents.py"],
+ ],
+ "reference-docs": [
+ [py, "scripts/ci/gen_cli_reference.py"],
+ [py, "scripts/ci/gen_commands_reference.py"],
+ ],
+ "uv-lock": [["uv", "lock"]],
+ "requirements": [
+ [
+ "uv",
+ "pip",
+ "compile",
+ "--universal",
+ "--generate-hashes",
+ "--python-version",
+ "3.11",
+ "--output-file=requirements.txt",
+ "requirements.in",
+ ]
+ ],
+ }
+ npm = shutil.which("npm") or "npm"
+ commands["npm-lock"] = [[npm, "install", "--package-lock-only", "--ignore-scripts"]]
+ commands["frontend-build"] = [[npm, "ci"], [npm, "run", "build"]]
+ order = ["npm-lock", "uv-lock", "requirements", "mirrors", "reference-docs", "frontend-build"]
+ for key in order:
+ if key not in keys:
+ continue
+ workdir = cwd / FRONTEND if key in {"npm-lock", "frontend-build"} else cwd
+ tool = commands[key][0][0]
+ if shutil.which(tool) is None and not Path(tool).exists():
+ print(f"[integrate] regenerator {key}: {tool} not installed", flush=True)
+ failures.append(key)
+ continue
+ for cmd in commands[key]:
+ if _sh(cmd, cwd=workdir) != 0:
+ failures.append(key)
+ break
+ return failures
+
+
+@dataclass
+class Resolution:
+ resolved: list[str] = field(default_factory=list)
+ unresolved: list[str] = field(default_factory=list)
+ regenerate: set[str] = field(default_factory=set)
+ ai_resolved: list[str] = field(default_factory=list)
+
+
+def resolve_conflicts(main_side: str, resolver_cmd: str, cwd: Path) -> Resolution:
+ """Resolve the current index conflicts. ``main_side`` is ours|theirs."""
+ res = Resolution()
+ semantic: list[str] = []
+ for path in conflicted_files(cwd):
+ strategy, regen = classify(path)
+ if strategy == "generated":
+ take_side(path, main_side, cwd)
+ if regen:
+ res.regenerate.add(regen)
+ res.resolved.append(path)
+ elif strategy == "union" and union_merge(path, cwd):
+ res.resolved.append(path)
+ else:
+ semantic.append(path)
+ # rerere may already have replayed a recorded resolution: both sides still
+ # exist and the markers are gone. A modify/delete conflict also has no
+ # markers, but one side is missing — that one stays unresolved.
+ for path in list(semantic):
+ both_sides = _stage_blob(2, path, cwd) is not None and _stage_blob(3, path, cwd) is not None
+ if both_sides and (cwd / path).exists() and still_valid(cwd / path) is None:
+ git("add", "--", path, cwd=cwd)
+ semantic.remove(path)
+ res.resolved.append(path)
+ if semantic and resolver_cmd:
+ prompt = build_prompt(semantic, main_side)
+ _sh([*shlex.split(resolver_cmd)], cwd=cwd, stdin=prompt)
+ for path in list(semantic):
+ error = still_valid(cwd / path)
+ if error is None:
+ git("add", "--", path, cwd=cwd)
+ semantic.remove(path)
+ res.resolved.append(path)
+ res.ai_resolved.append(path)
+ else:
+ print(f"[integrate] resolver left {path} broken: {error}", flush=True)
+ res.unresolved = semantic
+ return res
+
+
+def build_prompt(paths: list[str], main_side: str) -> str:
+ branch_side = "theirs" if main_side == "ours" else "ours"
+ listing = "\n".join(f"- {p}" for p in paths)
+ return (
+ "You are resolving git merge conflicts in the Personal Jarvis repository. "
+ "The files below contain conflict markers. For each file, edit it in place so "
+ "that it keeps the intent of BOTH sides: the main branch "
+ f"(git side '{main_side}') is the latest shared state; the feature branch "
+ f"(git side '{branch_side}') carries new work that must survive on top of it. "
+ "Remove every conflict marker. Do not touch any other file, do not run git, "
+ "do not commit. If a conflict cannot be resolved safely, leave its markers in "
+ "place — an unresolved file is reported to a human, a wrong guess is not.\n\n"
+ f"Files:\n{listing}\n"
+ )
+
+
+def _in_progress(cwd: Path) -> str | None:
+ git_dir = Path(git("rev-parse", "--git-dir", cwd=cwd).stdout.strip())
+ if not git_dir.is_absolute():
+ git_dir = cwd / git_dir
+ if (git_dir / "MERGE_HEAD").exists():
+ return "merge"
+ if (git_dir / "rebase-merge").exists() or (git_dir / "rebase-apply").exists():
+ return "rebase"
+ return None
+
+
+def update(onto: str, mode: str, resolver_cmd: str, cwd: Path = REPO_ROOT) -> dict[str, object]:
+ """Update HEAD with ``onto``. Returns a JSON-able report; ``status`` is
+ ``up-to-date`` | ``updated`` | ``conflict``."""
+ if git("merge-base", "--is-ancestor", onto, "HEAD", check=False, cwd=cwd).returncode == 0:
+ return {"status": "up-to-date"}
+ report: dict[str, object] = {"status": "updated", "resolved": [], "ai_resolved": []}
+ regen: set[str] = set()
+ resolved: list[str] = []
+ ai: list[str] = []
+ if mode == "merge":
+ result = git("merge", "--no-edit", "--no-ff", onto, check=False, cwd=cwd)
+ if result.returncode != 0:
+ res = resolve_conflicts("theirs", resolver_cmd, cwd)
+ resolved += res.resolved
+ ai += res.ai_resolved
+ regen |= res.regenerate
+ if res.unresolved or conflicted_files(cwd):
+ git("merge", "--abort", check=False, cwd=cwd)
+ return {"status": "conflict", "unresolved": res.unresolved or conflicted_files(cwd)}
+ git("commit", "--no-edit", check=False, cwd=cwd)
+ else:
+ git("rebase", onto, check=False, cwd=cwd)
+ guard = 0
+ while _in_progress(cwd) == "rebase":
+ guard += 1
+ res = resolve_conflicts("ours", resolver_cmd, cwd)
+ resolved += res.resolved
+ ai += res.ai_resolved
+ regen |= res.regenerate
+ if res.unresolved or conflicted_files(cwd) or guard > 200:
+ git("rebase", "--abort", check=False, cwd=cwd)
+ return {"status": "conflict", "unresolved": res.unresolved or conflicted_files(cwd)}
+ env_result = subprocess.run( # noqa: S603
+ ["git", "-c", "core.editor=true", "rebase", "--continue"], # noqa: S607
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if env_result.returncode != 0 and not conflicted_files(cwd):
+ # An emptied commit: its change already landed on main.
+ git("rebase", "--skip", check=False, cwd=cwd)
+ if regen:
+ failed = regenerate(regen, cwd)
+ paths = [p for p, _ in GENERATED] + ["jarvis/ui/web/dist"]
+ git("add", "-A", "--", *[p.rstrip("*") for p in paths], check=False, cwd=cwd)
+ staged = git("diff", "--cached", "--name-only", cwd=cwd).stdout.strip()
+ if staged:
+ git("commit", "-m", "chore: regenerate generated files after update", cwd=cwd)
+ report["regenerated"] = sorted(regen - set(failed))
+ if failed:
+ report["regen_failed"] = failed
+ report["resolved"] = sorted(set(resolved))
+ report["ai_resolved"] = sorted(set(ai))
+ return report
+
+
+# --------------------------------------------------------------------------- merge train
+
+
+def gh_json(*args: str) -> object:
+ out = subprocess.run( # noqa: S603
+ ["gh", *args], # noqa: S607
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ check=True,
+ ).stdout
+ return json.loads(out or "null")
+
+
+def gh(*args: str) -> int:
+ print(f"[train] $ gh {' '.join(args)}", flush=True)
+ return subprocess.run(["gh", *args], check=False).returncode # noqa: S603, S607
+
+
+def eligible(pr: dict) -> bool:
+ labels = {label["name"] for label in pr.get("labels", [])}
+ if pr.get("isDraft") or pr.get("baseRefName") != "main" or labels & OPT_OUT_LABELS:
+ return False
+ if pr.get("isCrossRepository"):
+ return False # a fork's code never runs with this workflow's write token
+ return OPT_IN_LABEL in labels or pr.get("headRefName", "").startswith(AGENT_BRANCH_PREFIXES)
+
+
+def gate_state(repo: str, sha: str) -> str:
+ """success | failure | pending | missing for the CI gate on ``sha``."""
+ data = gh_json(
+ "api",
+ f"repos/{repo}/commits/{sha}/check-runs?check_name={GATE_CHECK.replace(' ', '%20')}",
+ )
+ runs = (data or {}).get("check_runs", []) if isinstance(data, dict) else []
+ if not runs:
+ return "missing"
+ latest = max(runs, key=lambda r: r.get("started_at") or "")
+ if latest.get("status") != "completed":
+ return "pending"
+ return "success" if latest.get("conclusion") == "success" else "failure"
+
+
+def dispatch_ci(ref: str) -> None:
+ gh("workflow", "run", "ci.yml", "--ref", ref, "-f", "full=false")
+
+
+def train(repo: str, max_updates: int, resolver_cmd: str, dry_run: bool, token_is_bot: bool) -> int:
+ prs = gh_json(
+ "pr",
+ "list",
+ "--repo",
+ repo,
+ "--state",
+ "open",
+ "--base",
+ "main",
+ "--limit",
+ "100",
+ "--json",
+ "number,title,headRefName,headRefOid,isDraft,labels,baseRefName,isCrossRepository",
+ )
+ queue = sorted(
+ (p for p in prs or [] if eligible(p)), # type: ignore[union-attr]
+ key=lambda p: (not any(lb["name"] == "priority" for lb in p["labels"]), p["number"]),
+ )
+ print(f"[train] {len(queue)} eligible pull request(s)", flush=True)
+ updates = 0
+ merged = False
+ summary: list[str] = []
+ for pr in queue:
+ number, branch, sha = pr["number"], pr["headRefName"], pr["headRefOid"]
+ git("fetch", "--quiet", "origin", "main", branch)
+ behind = git("merge-base", "--is-ancestor", "origin/main", sha, check=False).returncode
+ if behind != 0:
+ if updates >= max_updates:
+ summary.append(f"#{number}: behind main, waits for a free update slot")
+ continue
+ updates += 1
+ summary.append(f"#{number}: " + update_pr(pr, resolver_cmd, dry_run, token_is_bot))
+ continue
+ state = gate_state(repo, sha)
+ if state == "success" and not merged:
+ if dry_run:
+ summary.append(f"#{number}: would merge")
+ continue
+ if gh("pr", "merge", str(number), "--repo", repo, "--squash") == 0:
+ merged = True
+ summary.append(f"#{number}: merged")
+ if token_is_bot:
+ dispatch_ci("main") # a GITHUB_TOKEN merge fires no push event
+ else:
+ summary.append(f"#{number}: merge refused (protection or conflict)")
+ elif state == "missing":
+ summary.append(f"#{number}: no CI on {sha[:8]}, dispatching")
+ if not dry_run:
+ dispatch_ci(branch)
+ else:
+ summary.append(f"#{number}: CI gate {state}")
+ lines = ["## Merge train", "", *[f"- {line}" for line in summary]]
+ print("\n".join(lines))
+ target = os.environ.get("GITHUB_STEP_SUMMARY")
+ if target:
+ with open(target, "a", encoding="utf-8") as handle:
+ handle.write("\n".join(lines) + "\n")
+ return 0
+
+
+def update_pr(pr: dict, resolver_cmd: str, dry_run: bool, token_is_bot: bool) -> str:
+ number, branch = pr["number"], pr["headRefName"]
+ git("checkout", "--quiet", "-B", f"train/{number}", f"origin/{branch}")
+ report = update("origin/main", "merge", resolver_cmd, REPO_ROOT)
+ status = report["status"]
+ repo = os.environ.get("GITHUB_REPOSITORY", "")
+ if status == "conflict":
+ files = "\n".join(f"- `{f}`" for f in report.get("unresolved", [])) # type: ignore[union-attr]
+ body = (
+ "The merge train could not bring this branch up to date with `main`: "
+ f"these files conflict and could not be resolved automatically.\n\n{files}\n\n"
+ "Resolve locally with `python scripts/agent_land.py --pr` (it rebases, "
+ "resolves generated files and lists what is left). The train retries on "
+ "the next push to this branch."
+ )
+ if not dry_run:
+ gh("pr", "comment", str(number), "--repo", repo, "--body", body)
+ gh("pr", "edit", str(number), "--repo", repo, "--add-label", "needs-rebase")
+ return "conflict - " + ", ".join(report.get("unresolved", [])) # type: ignore[arg-type]
+ if dry_run:
+ return f"would push update ({status})"
+ push = git("push", "origin", f"HEAD:refs/heads/{branch}", check=False)
+ if push.returncode != 0:
+ return "update rejected (the branch moved); retry next tick"
+ gh("pr", "edit", str(number), "--repo", repo, "--remove-label", "needs-rebase")
+ ai = report.get("ai_resolved") or []
+ if ai:
+ listing = ", ".join(f"`{f}`" for f in ai) # type: ignore[union-attr]
+ gh(
+ "pr",
+ "comment",
+ str(number),
+ "--repo",
+ repo,
+ "--body",
+ f"Merge train: conflicts in {listing} were resolved by the configured AI "
+ "resolver. CI re-runs on the result before anything lands; please skim them.",
+ )
+ if token_is_bot:
+ dispatch_ci(branch) # a GITHUB_TOKEN push fires no pull_request event
+ return f"updated with main ({len(report.get('resolved', []))} conflicts auto-resolved)" # type: ignore[arg-type]
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ sub = parser.add_subparsers(dest="cmd", required=True)
+ up = sub.add_parser("update")
+ up.add_argument("--onto", default="origin/main")
+ up.add_argument("--mode", choices=("merge", "rebase"), default="rebase")
+ up.add_argument("--resolver-cmd", default=os.environ.get("CONFLICT_RESOLVER_CMD", ""))
+ tr = sub.add_parser("train")
+ tr.add_argument("--repo", required=True)
+ tr.add_argument("--max-updates", type=int, default=3)
+ tr.add_argument("--resolver-cmd", default=os.environ.get("CONFLICT_RESOLVER_CMD", ""))
+ tr.add_argument("--dry-run", action="store_true")
+ tr.add_argument("--token-is-bot", action="store_true")
+ args = parser.parse_args(argv)
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+ if args.cmd == "update":
+ report = update(args.onto, args.mode, args.resolver_cmd)
+ print(json.dumps(report, indent=2))
+ return 0 if report["status"] != "conflict" else 2
+ return train(args.repo, args.max_updates, args.resolver_cmd, args.dry_run, args.token_is_bot)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/classify_changes.py b/scripts/ci/classify_changes.py
new file mode 100644
index 0000000000..742e0a1202
--- /dev/null
+++ b/scripts/ci/classify_changes.py
@@ -0,0 +1,232 @@
+#!/usr/bin/env python3
+"""Classify a change set into CI lanes (the orchestrator's ``detect`` job).
+
+Reads newline-separated changed paths (repo-relative, forward slashes) from
+stdin or ``--files-from``, decides which CI lanes the change can affect, and
+writes ``lane=true|false`` lines to ``$GITHUB_OUTPUT`` (and stdout).
+
+Contract — FAIL OPEN, never closed. A lane may run without need; it must
+never be skipped when the change could break it:
+
+* ``--full`` (push to main, nightly, release, manual dispatch) or an EMPTY
+ change set turns every lane on. An empty set means the diff could not be
+ computed, never "nothing changed".
+* A change under ``.github/`` or ``scripts/ci/`` turns every lane on: it
+ rewires the pipeline itself.
+* ``python`` is a DENYLIST: it is off only when every path is provably
+ outside what the test suite reads. Tests read docs/, the frontend source,
+ install/ and assets/, so those keep it on.
+
+Outputs beyond the lanes:
+
+* ``full`` — every lane forced on (the caller also widens matrices).
+* ``changed_count`` — number of changed paths (0 = unknown).
+
+Usage::
+
+ git diff --name-only BASE HEAD | python scripts/ci/classify_changes.py
+ python scripts/ci/classify_changes.py --full
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import sys
+from collections.abc import Iterable
+from pathlib import Path
+
+# Trees the Python suite never reads (verified by grepping tests/ for each).
+# Everything NOT listed keeps the python lane on — unknown means relevant.
+_PY_IRRELEVANT_PREFIXES = (
+ "wiki-video/",
+ "homebrew-tap/",
+ "scoop-bucket/",
+ "board-backend/",
+ "qa/",
+ "skillbook/",
+ "keyproxy/",
+ ".github/ISSUE_TEMPLATE/",
+)
+_PY_IRRELEVANT_FILES = {
+ ".github/PULL_REQUEST_TEMPLATE.md",
+ ".github/dependabot.yml",
+ "CODE_OF_CONDUCT.md",
+ "SECURITY.md",
+}
+
+_PIPELINE_PREFIXES = (".github/workflows/", ".github/actions/", "scripts/ci/")
+
+_FRONTEND_PREFIXES = ("jarvis/ui/web/frontend/",)
+_FRONTEND_FILES = {"scripts/ci/check_frontend_bundle_budget.py"}
+
+_DEPS_FILES = {
+ "pyproject.toml",
+ "requirements.in",
+ "requirements.txt",
+ "uv.lock",
+}
+
+_REALTIME_PREFIXES = (
+ "jarvis/realtime/",
+ "jarvis/plugins/realtime/",
+ "jarvis/audio/",
+ "jarvis/speech/",
+ "jarvis/live/",
+ "jarvis/core/",
+ "tests/contract/test_realtime",
+ "tests/contract/test_gpt_live",
+)
+_REALTIME_FILES = {"scripts/realtime_reliability_gate.py"} | _DEPS_FILES
+
+_CLI_PREFIXES = ("jarvis/cli_ctl/", "jarvis/commands/", "tests/unit/cli_ctl/")
+
+_DRAGDROP_FILES = {
+ "jarvis/overlay/drop_target.py",
+ "jarvis/overlay/drop_bridge.py",
+ "scripts/crossplatform/verify_drop_target.py",
+}
+
+_BROWSER_PREFIXES = (
+ "jarvis/society/browser/",
+ "tests/contract/test_browser",
+ "tests/unit/society/test_browser",
+)
+_BROWSER_FILES = {
+ "jarvis/ui/web/society_browser_routes.py",
+ "jarvis/ui/web/mcp_server_routes.py",
+ "jarvis/agent_chat/runner_cli.py",
+ "jarvis/brain/tool_gateway.py",
+ "jarvis/society/approvals.py",
+}
+
+# Native macOS surface: permissions, bundle, autostart, Computer-Use. The old
+# standalone workflow also matched all of tests/** and jarvis/ui/**, which put
+# three 45-minute macOS jobs behind nearly every PR; the lane keeps the
+# platform code and the exact test files that job runs.
+_MACOS_PREFIXES = (
+ "install/",
+ "jarvis/admin/",
+ "jarvis/audio/",
+ "jarvis/autostart/",
+ "jarvis/cu/",
+ "jarvis/platform/",
+ "jarvis/setup/",
+ "jarvis/trigger/",
+ "jarvis/vision/",
+ "jarvis/ui/desktop",
+ "tests/unit/platform/",
+ "tests/unit/autostart/",
+ "tests/unit/cu/",
+ "tests/unit/setup/",
+ "tests/unit/vision/",
+)
+_MACOS_FILES = {
+ "pyproject.toml",
+ "uv.lock",
+ ".githooks/pre-push",
+ "scripts/measure_boot.py",
+ "scripts/measure_desktop_boot.py",
+}
+
+# Installer smoke: the raw install path a downloader runs.
+_INSTALLER_PREFIXES = ("install/",)
+_INSTALLER_FILES = {
+ "pyproject.toml",
+ "requirements.txt",
+ "jarvis/__main__.py",
+ "jarvis/setup/prefetch.py",
+ "jarvis/setup/model_report.py",
+ "jarvis/speech/wake_model_fetch.py",
+ "tests/unit/install/test_install_sh_stage1.py",
+ ".github/workflows/sign-installer.yml",
+}
+
+LANES = (
+ "python",
+ "frontend",
+ "deps",
+ "realtime",
+ "cli",
+ "dragdrop",
+ "browser",
+ "macos_desktop",
+ "installer",
+)
+
+
+def _normalize(paths: Iterable[str]) -> list[str]:
+ out: list[str] = []
+ for raw in paths:
+ path = raw.strip().replace("\\", "/")
+ if path.startswith("./"):
+ path = path[2:]
+ if path:
+ out.append(path)
+ return out
+
+
+def _any(paths: list[str], prefixes: tuple[str, ...] = (), files: set[str] | None = None) -> bool:
+ files = files or set()
+ return any(p.startswith(prefixes) or p in files for p in paths)
+
+
+def _python_relevant(path: str) -> bool:
+ return not (path.startswith(_PY_IRRELEVANT_PREFIXES) or path in _PY_IRRELEVANT_FILES)
+
+
+def classify(paths: Iterable[str], *, full: bool = False) -> dict[str, bool]:
+ """Return ``{lane: bool}`` plus ``full`` for a change set."""
+ changed = _normalize(paths)
+ force = full or not changed or _any(changed, _PIPELINE_PREFIXES)
+ if force:
+ result = {lane: True for lane in LANES}
+ result["full"] = True
+ return result
+ return {
+ "python": any(_python_relevant(p) for p in changed),
+ "frontend": _any(changed, _FRONTEND_PREFIXES, _FRONTEND_FILES),
+ "deps": _any(changed, (), _DEPS_FILES),
+ "realtime": _any(changed, _REALTIME_PREFIXES, _REALTIME_FILES),
+ "cli": _any(changed, _CLI_PREFIXES)
+ or any(p.startswith("jarvis/ui/web/") and p.endswith("_routes.py") for p in changed),
+ "dragdrop": _any(changed, (), _DRAGDROP_FILES),
+ "browser": _any(changed, _BROWSER_PREFIXES, _BROWSER_FILES),
+ "macos_desktop": _any(changed, _MACOS_PREFIXES, _MACOS_FILES),
+ "installer": _any(changed, _INSTALLER_PREFIXES, _INSTALLER_FILES),
+ "full": False,
+ }
+
+
+def _emit(result: dict[str, bool], changed_count: int) -> list[str]:
+ lines = [f"{key}={'true' if value else 'false'}" for key, value in result.items()]
+ lines.append(f"changed_count={changed_count}")
+ return lines
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--full", action="store_true", help="Force every lane on.")
+ parser.add_argument("--files-from", type=Path, help="Read paths from this file, not stdin.")
+ args = parser.parse_args(argv)
+
+ if args.full:
+ paths: list[str] = []
+ elif args.files_from:
+ paths = args.files_from.read_text(encoding="utf-8").splitlines()
+ else:
+ paths = [] if sys.stdin is None or sys.stdin.isatty() else sys.stdin.read().splitlines()
+ changed = _normalize(paths)
+ result = classify(changed, full=args.full)
+ lines = _emit(result, len(changed))
+
+ output = os.environ.get("GITHUB_OUTPUT")
+ if output:
+ with open(output, "a", encoding="utf-8") as handle:
+ handle.write("\n".join(lines) + "\n")
+ print("\n".join(lines))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/cut_release.py b/scripts/ci/cut_release.py
new file mode 100644
index 0000000000..d029a22331
--- /dev/null
+++ b/scripts/ci/cut_release.py
@@ -0,0 +1,154 @@
+#!/usr/bin/env python3
+"""Prepare a release commit: bump the version and write the CHANGELOG section.
+
+Used by ``.github/workflows/release-cut.yml`` (a manual, maintainer-only
+dispatch — a release never happens by itself) and runnable locally::
+
+ python scripts/ci/cut_release.py --bump patch # 2.3.2 -> 2.3.3
+ python scripts/ci/cut_release.py --version 2.4.0
+
+The version lives in exactly two places, ``pyproject.toml`` and
+``jarvis/__init__.py``. The CHANGELOG section takes the ``[Unreleased]``
+notes when there are any; otherwise it is built from the Conventional Commit
+subjects since the previous tag (feat -> Added, fix -> Fixed, perf/refactor ->
+Changed). The notes are also written to ``--notes-out`` for the GitHub
+Release body. Prints the new version on the last line.
+"""
+
+from __future__ import annotations
+
+import argparse
+import datetime as dt
+import re
+import subprocess
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from scripts.ci.release_admit import versions # noqa: E402
+
+_SECTIONS = {"feat": "Added", "fix": "Fixed", "perf": "Changed", "refactor": "Changed"}
+_SUBJECT = re.compile(r"^(?P<type>[a-z]+)(?:\([^)]*\))?(?P<bang>!)?: (?P<text>.+)$")
+
+
+def bump(version: str, part: str) -> str:
+ major, minor, patch = (int(x) for x in version.split("."))
+ if part == "major":
+ return f"{major + 1}.0.0"
+ if part == "minor":
+ return f"{major}.{minor + 1}.0"
+ return f"{major}.{minor}.{patch + 1}"
+
+
+def notes_from_commits(subjects: list[str]) -> str:
+ grouped: dict[str, list[str]] = {"Added": [], "Changed": [], "Fixed": []}
+ breaking: list[str] = []
+ for subject in subjects:
+ match = _SUBJECT.match(subject.strip())
+ if not match:
+ continue
+ section = _SECTIONS.get(match.group("type"))
+ text = match.group("text").strip()
+ text = text[0].upper() + text[1:]
+ if match.group("bang"):
+ breaking.append(text)
+ if section and text not in grouped[section]:
+ grouped[section].append(text)
+ parts: list[str] = []
+ if breaking:
+ parts.append("### Breaking\n\n" + "\n".join(f"- {t}" for t in breaking))
+ for section, items in grouped.items():
+ if items:
+ parts.append(f"### {section}\n\n" + "\n".join(f"- {t}" for t in items))
+ return "\n\n".join(parts) or "### Changed\n\n- Maintenance release."
+
+
+def split_unreleased(changelog: str) -> tuple[str, str, str]:
+ """Return (head incl. '## [Unreleased]' line, unreleased body, rest)."""
+ match = re.search(r"^## \[Unreleased\][^\n]*\n", changelog, re.MULTILINE)
+ if not match:
+ raise SystemExit("CHANGELOG.md has no '## [Unreleased]' heading")
+ after = changelog[match.end() :]
+ nxt = re.search(r"^## \[", after, re.MULTILINE)
+ body = after[: nxt.start()] if nxt else after
+ rest = after[nxt.start() :] if nxt else ""
+ return changelog[: match.end()], body, rest
+
+
+def section_notes(changelog: str, version: str) -> str:
+ """The body of ``## [version]`` without its trailing ``---`` rule."""
+ match = re.search(
+ rf"^## \[{re.escape(version)}\][^\n]*\n(.*?)(?=^## \[|\Z)", changelog, re.S | re.M
+ )
+ return (match.group(1) if match else "").strip().rstrip("-").strip()
+
+
+def apply(version: str, notes: str, today: str, root: Path = REPO_ROOT) -> None:
+ pyproject = root / "pyproject.toml"
+ text = pyproject.read_text(encoding="utf-8")
+ text = re.sub(r'(?m)^version = "[^"]+"', f'version = "{version}"', text, count=1)
+ pyproject.write_bytes(text.encode("utf-8"))
+ init = root / "jarvis" / "__init__.py"
+ text = init.read_text(encoding="utf-8")
+ text = re.sub(r'__version__ = "[^"]+"', f'__version__ = "{version}"', text, count=1)
+ init.write_bytes(text.encode("utf-8"))
+ changelog = root / "CHANGELOG.md"
+ head, _body, rest = split_unreleased(changelog.read_text(encoding="utf-8"))
+ section = f"## [{version}] — {today}\n\n{notes.strip()}\n\n---\n\n"
+ changelog.write_bytes((head + "\n---\n\n" + section + rest).encode("utf-8"))
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ group = parser.add_mutually_exclusive_group(required=True)
+ group.add_argument("--bump", choices=("patch", "minor", "major"))
+ group.add_argument("--version")
+ group.add_argument("--print-notes", metavar="X.Y.Z", help="Print a released section.")
+ parser.add_argument("--notes-out", type=Path, default=Path("release-notes.md"))
+ args = parser.parse_args(argv)
+ if args.print_notes:
+ print(
+ section_notes(
+ (REPO_ROOT / "CHANGELOG.md").read_text(encoding="utf-8"), args.print_notes
+ )
+ )
+ return 0
+
+ current, package = versions()
+ if current != package:
+ raise SystemExit(f"version drift: pyproject {current} vs jarvis {package}")
+ new = args.version or bump(current, args.bump)
+ if not re.fullmatch(r"\d+\.\d+\.\d+", new):
+ raise SystemExit(f"not a SemVer version: {new}")
+ changelog = (REPO_ROOT / "CHANGELOG.md").read_text(encoding="utf-8")
+ _head, body, _rest = split_unreleased(changelog)
+ unreleased = body.strip().strip("-").strip()
+ if not unreleased:
+ last = subprocess.run( # noqa: S603
+ ["git", "describe", "--tags", "--abbrev=0", "--match", "v*"], # noqa: S607
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ check=False,
+ ).stdout.strip()
+ span = f"{last}..HEAD" if last else "HEAD"
+ subjects = subprocess.run( # noqa: S603
+ ["git", "log", "--no-merges", "--format=%s", span], # noqa: S607
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ check=True,
+ ).stdout.splitlines()
+ unreleased = notes_from_commits(subjects)
+ apply(new, unreleased, dt.date.today().isoformat())
+ args.notes_out.write_text(unreleased.strip() + "\n", encoding="utf-8")
+ print(new)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/ratchet_tests.py b/scripts/ci/ratchet_tests.py
new file mode 100644
index 0000000000..0499119976
--- /dev/null
+++ b/scripts/ci/ratchet_tests.py
@@ -0,0 +1,197 @@
+#!/usr/bin/env python3
+"""Known-failure ratchet for the sharded test suite.
+
+The old CI step ended in ``|| echo`` — ANY failure rode through green as long
+as the passed count stayed above a floor. The suite does carry a backlog of
+failures (mostly platform-specific), so going strict in one step would turn
+every PR red for reasons it did not cause. The ratchet splits the two:
+
+* a failure listed in ``scripts/ci/test-baseline-<os>.json`` is KNOWN — it is
+ reported, never blocking;
+* any other failure is NEW — it blocks the change that introduced it;
+* a known failure that now passes is reported so the baseline can shrink
+ (``update`` rewrites it from a full run; it may only get smaller in review).
+
+Commands::
+
+ ratchet_tests.py check --baseline B.json report*.json # per shard, blocking
+ ratchet_tests.py summary --baseline B.json --floor report*.json
+ ratchet_tests.py update --out B.json report*.json # regenerate
+ ratchet_tests.py durations --out D.json dur*.json # merge timing caches
+
+A missing baseline file means "not bootstrapped yet": ``check`` reports and
+passes, so a first run on a new OS leg can produce its own baseline.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+_CRASH = re.compile(r"::<(?:timeout|pytest exit)[^>]*>$")
+
+
+def normalize(test_id: str) -> str:
+ """Timeouts and crashes differ only in their number between runs."""
+ return _CRASH.sub("::<crash>", test_id)
+
+
+def load_reports(paths: list[Path]) -> list[dict]:
+ reports = []
+ for path in paths:
+ if path.is_dir():
+ reports.extend(load_reports(sorted(path.rglob("test-report*.json"))))
+ continue
+ reports.append(json.loads(path.read_text(encoding="utf-8")))
+ return reports
+
+
+def load_baseline(path: Path) -> set[str] | None:
+ if not path.is_file():
+ return None
+ data = json.loads(path.read_text(encoding="utf-8"))
+ return {normalize(x) for x in data.get("known_failures", [])}
+
+
+def failed_ids(reports: list[dict]) -> set[str]:
+ return {normalize(fid) for report in reports for fid in report.get("failed_ids", [])}
+
+
+def _summary(lines: list[str]) -> None:
+ target = os.environ.get("GITHUB_STEP_SUMMARY")
+ if target:
+ with open(target, "a", encoding="utf-8") as handle:
+ handle.write("\n".join(lines) + "\n")
+
+
+def cmd_check(args: argparse.Namespace) -> int:
+ reports = load_reports(args.reports)
+ baseline = load_baseline(args.baseline)
+ failures = failed_ids(reports)
+ if baseline is None:
+ print(f"[ratchet] no baseline at {args.baseline} - report-only bootstrap mode")
+ for fid in sorted(failures):
+ print(f" failing: {fid}")
+ return 0
+ new = sorted(failures - baseline)
+ known = sorted(failures & baseline)
+ flaky = sorted({f for r in reports for f in r.get("flaky_files", [])})
+ print(f"[ratchet] {len(failures)} failing ids: {len(new)} new, {len(known)} known (baselined)")
+ for fid in flaky:
+ print(f" flaky (passed on retry): {fid}")
+ lines = [f"### Test ratchet ({args.baseline.name})", ""]
+ if new:
+ lines.append(f"**{len(new)} NEW failure(s)** — not baselined, so this change owns them:")
+ lines.extend(f"- `{fid}`" for fid in new)
+ for fid in new:
+ print(f"::error title=New test failure::{fid}")
+ else:
+ lines.append(f"No new failures ({len(known)} known, {len(flaky)} flaky files).")
+ _summary(lines)
+ return 1 if new else 0
+
+
+def cmd_summary(args: argparse.Namespace) -> int:
+ reports = load_reports(args.reports)
+ if not reports:
+ print("[ratchet] no shard reports found - the test lane produced nothing")
+ return 1
+ counts = {"tests": 0, "passed": 0, "failed": 0, "skipped": 0}
+ for report in reports:
+ for key in counts:
+ counts[key] += report.get("counts", {}).get(key, 0)
+ status = 0
+ lines = [
+ f"### Test suite ({len(reports)} shards)",
+ "",
+ f"{counts['passed']} passed · {counts['failed']} failed · {counts['skipped']} skipped",
+ ]
+ if args.floor:
+ from scripts.ci.assert_min_passed import FLOOR
+
+ if counts["passed"] < FLOOR:
+ lines.append(f"**FAIL: passed={counts['passed']} is below the floor {FLOOR}**")
+ print(f"::error::passed={counts['passed']} < FLOOR={FLOOR} (mass-skip regression?)")
+ status = 1
+ else:
+ lines.append(f"Min-passed floor: {counts['passed']} >= {FLOOR}")
+ baseline = load_baseline(args.baseline) if args.baseline else None
+ if baseline is not None:
+ fixed = sorted(baseline - failed_ids(reports))
+ if fixed:
+ lines.append("")
+ lines.append(f"{len(fixed)} baselined failure(s) now pass — shrink the baseline:")
+ lines.extend(f"- `{fid}`" for fid in fixed[:50])
+ slowest = max(reports, key=lambda r: float(r.get("elapsed_seconds", 0)))
+ lines.append(f"Slowest shard: {slowest.get('shard')} ({slowest.get('elapsed_seconds')} s)")
+ print("\n".join(lines))
+ _summary(lines)
+ return status
+
+
+def cmd_update(args: argparse.Namespace) -> int:
+ reports = load_reports(args.reports)
+ failures = sorted(failed_ids(reports))
+ payload = {
+ "comment": (
+ "Known test failures. Generated by scripts/ci/ratchet_tests.py update from a "
+ "full CI run; entries may only be removed by hand, never added to hide a "
+ "regression."
+ ),
+ "known_failures": failures,
+ }
+ args.out.write_text(json.dumps(payload, indent=2) + "\n", encoding="utf-8")
+ print(f"[ratchet] wrote {len(failures)} known failures to {args.out}")
+ return 0
+
+
+def cmd_durations(args: argparse.Namespace) -> int:
+ merged: dict[str, float] = {}
+ if args.base and args.base.is_file():
+ merged.update(json.loads(args.base.read_text(encoding="utf-8")))
+ for path in args.inputs:
+ files = sorted(path.rglob("durations*.json")) if path.is_dir() else [path]
+ for file in files:
+ merged.update(json.loads(file.read_text(encoding="utf-8")))
+ payload = json.dumps(dict(sorted(merged.items())), indent=1) + "\n"
+ args.out.write_text(payload, encoding="utf-8")
+ print(f"[ratchet] duration cache: {len(merged)} files -> {args.out}")
+ return 0
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ sub = parser.add_subparsers(dest="cmd", required=True)
+ check = sub.add_parser("check")
+ check.add_argument("--baseline", type=Path, required=True)
+ check.add_argument("reports", nargs="+", type=Path)
+ summary = sub.add_parser("summary")
+ summary.add_argument("--baseline", type=Path)
+ summary.add_argument("--floor", action="store_true")
+ summary.add_argument("reports", nargs="+", type=Path)
+ update = sub.add_parser("update")
+ update.add_argument("--out", type=Path, required=True)
+ update.add_argument("reports", nargs="+", type=Path)
+ durations = sub.add_parser("durations")
+ durations.add_argument("--base", type=Path)
+ durations.add_argument("--out", type=Path, required=True)
+ durations.add_argument("inputs", nargs="+", type=Path)
+ args = parser.parse_args(argv)
+ handler = {
+ "check": cmd_check,
+ "summary": cmd_summary,
+ "update": cmd_update,
+ "durations": cmd_durations,
+ }[args.cmd]
+ return handler(args)
+
+
+if __name__ == "__main__":
+ if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+ sys.exit(main())
diff --git a/scripts/ci/release_admit.py b/scripts/ci/release_admit.py
new file mode 100644
index 0000000000..b5a0ef8d1c
--- /dev/null
+++ b/scripts/ci/release_admit.py
@@ -0,0 +1,136 @@
+#!/usr/bin/env python3
+"""Admit a release tag: nothing ships that main's CI has not proven.
+
+Every tag-triggered workflow (PyPI, desktop installers, signed installer)
+runs this first through ``.github/workflows/release-gate.yml``. It checks:
+
+1. the tag is ``vX.Y.Z`` and matches ``pyproject.toml`` and
+ ``jarvis.__version__``;
+2. ``CHANGELOG.md`` has a ``## [X.Y.Z]`` section;
+3. the tagged commit is reachable from ``origin/main`` (no release from an
+ unmerged branch);
+4. the ``CI gate`` check on that exact commit concluded ``success`` — waiting
+ while it is still running, because the release-cut workflow dispatches CI
+ for its own version-bump commit right before it tags.
+
+ release_admit.py --tag v2.4.0 --sha <commit> --repo OWNER/NAME [--wait-minutes 150]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import re
+import subprocess
+import sys
+import time
+import tomllib
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+GATE_CHECK = "CI gate"
+
+
+def versions(root: Path = REPO_ROOT) -> tuple[str, str]:
+ project = tomllib.loads((root / "pyproject.toml").read_text(encoding="utf-8"))
+ init = (root / "jarvis" / "__init__.py").read_text(encoding="utf-8")
+ match = re.search(r'__version__ = "([^"]+)"', init)
+ return project["project"]["version"], match.group(1) if match else ""
+
+
+def changelog_has(version: str, root: Path = REPO_ROOT) -> bool:
+ text = (root / "CHANGELOG.md").read_text(encoding="utf-8")
+ return re.search(rf"^## \[{re.escape(version)}\]", text, re.MULTILINE) is not None
+
+
+def check_identity(tag: str, root: Path = REPO_ROOT) -> list[str]:
+ errors: list[str] = []
+ match = re.fullmatch(r"v(\d+\.\d+\.\d+)", tag)
+ if not match:
+ return [f"tag {tag!r} is not vX.Y.Z"]
+ version = match.group(1)
+ project, package = versions(root)
+ if not (version == project == package):
+ errors.append(f"tag {version} != pyproject {project} / jarvis.__version__ {package}")
+ if not changelog_has(version, root):
+ errors.append(f"CHANGELOG.md has no '## [{version}]' section")
+ return errors
+
+
+def gate_state(repo: str, sha: str) -> str:
+ proc = subprocess.run( # noqa: S603
+ [ # noqa: S607
+ "gh",
+ "api",
+ f"repos/{repo}/commits/{sha}/check-runs?check_name=CI%20gate&per_page=50",
+ ],
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ check=False,
+ )
+ if proc.returncode != 0:
+ print(f"[admit] check-run lookup failed: {proc.stderr.strip()[:300]}")
+ return "missing"
+ runs = json.loads(proc.stdout or "{}").get("check_runs", [])
+ if not runs:
+ return "missing"
+ if any(r.get("status") == "completed" and r.get("conclusion") == "success" for r in runs):
+ return "success"
+ if any(r.get("status") != "completed" for r in runs):
+ return "pending"
+ return "failure"
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--tag", required=True)
+ parser.add_argument("--sha", required=True)
+ parser.add_argument("--repo", required=True)
+ parser.add_argument("--wait-minutes", type=int, default=150)
+ parser.add_argument("--skip-ci", action="store_true", help="Identity checks only.")
+ args = parser.parse_args(argv)
+
+ errors = check_identity(args.tag)
+ subprocess.run(["git", "fetch", "--quiet", "origin", "main"], check=False) # noqa: S607
+ ancestor = subprocess.run( # noqa: S603
+ ["git", "merge-base", "--is-ancestor", args.sha, "origin/main"], # noqa: S607
+ check=False,
+ )
+ if ancestor.returncode != 0:
+ errors.append(f"{args.sha[:12]} is not on origin/main")
+ for error in errors:
+ print(f"::error title=Release not admitted::{error}")
+ if errors:
+ return 1
+ if args.skip_ci:
+ print("[admit] identity OK; CI check skipped on request")
+ return 0
+
+ deadline = time.monotonic() + args.wait_minutes * 60
+ missing_since = time.monotonic()
+ while True:
+ state = gate_state(args.repo, args.sha)
+ print(f"[admit] CI gate on {args.sha[:12]}: {state}", flush=True)
+ if state == "success":
+ print(f"[admit] {args.tag} admitted")
+ return 0
+ if state == "failure":
+ print(f"::error::CI gate failed on {args.sha[:12]}; fix main and cut a new tag.")
+ return 1
+ if state == "missing" and time.monotonic() - missing_since > 15 * 60:
+ print(
+ f"::error::No CI run exists for {args.sha[:12]}. Run "
+ f"`gh workflow run ci.yml --ref main`, then re-run this workflow."
+ )
+ return 1
+ if state == "pending":
+ missing_since = time.monotonic()
+ if time.monotonic() > deadline:
+ print("::error::Timed out waiting for the CI gate.")
+ return 1
+ time.sleep(60)
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/required_results.py b/scripts/ci/required_results.py
new file mode 100644
index 0000000000..3880f2ccf6
--- /dev/null
+++ b/scripts/ci/required_results.py
@@ -0,0 +1,79 @@
+#!/usr/bin/env python3
+"""The single aggregate CI gate ("CI gate" — the only required check).
+
+Input: ``toJSON(needs)`` of the gate job on stdin. Branch protection and the
+merge train require ONLY this check, so adding, renaming or path-gating a job
+never needs a settings change.
+
+* Any ``failure`` / ``cancelled`` result fails the gate.
+* ``skipped`` passes in normal mode — a lane the change cannot affect.
+* ``--strict`` (nightly, release) fails a skipped job too, except the jobs in
+ :data:`STRICT_SKIP_OK` that can never run on those events.
+
+ echo "$NEEDS" | python scripts/ci/required_results.py [--strict]
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+from typing import Any
+
+# Jobs that only exist on some events: pull-request-only checks and manual
+# soak runs. A strict run may skip these and nothing else.
+STRICT_SKIP_OK = frozenset({"pr-policy", "soak"})
+
+
+def evaluate(needs: dict[str, dict[str, Any]] | None, *, strict: bool = False) -> dict[str, Any]:
+ failed: list[str] = []
+ skipped: list[str] = []
+ entries = needs or {}
+ if not entries:
+ failed.append("<no-needs>")
+ for name, info in entries.items():
+ result = (info or {}).get("result")
+ if result == "success":
+ continue
+ if result == "skipped" and (not strict or name in STRICT_SKIP_OK):
+ skipped.append(name)
+ continue
+ failed.append(name)
+ return {"ok": not failed, "failed": sorted(failed), "skipped": sorted(skipped)}
+
+
+def render(needs: dict[str, dict[str, Any]] | None, verdict: dict[str, Any]) -> list[str]:
+ lines = ["| job | result |", "|---|---|"]
+ for name in sorted(needs or {}):
+ result = (needs[name] or {}).get("result", "unknown") # type: ignore[index]
+ icon = {"success": "pass", "skipped": "skip"}.get(result, "FAIL")
+ lines.append(f"| {name} | {icon} ({result}) |")
+ if verdict["failed"]:
+ lines.append("")
+ lines.append(f"**Failed:** {', '.join(verdict['failed'])}")
+ return lines
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--strict", action="store_true", help="A skipped job fails too.")
+ args = parser.parse_args(argv)
+
+ needs = json.load(sys.stdin)
+ verdict = evaluate(needs, strict=args.strict)
+ report = render(needs, verdict)
+ print("\n".join(report))
+ summary = os.environ.get("GITHUB_STEP_SUMMARY")
+ if summary:
+ with open(summary, "a", encoding="utf-8") as handle:
+ handle.write("## CI gate\n\n" + "\n".join(report) + "\n")
+ if not verdict["ok"]:
+ print(f"::error::CI gate failed: {', '.join(verdict['failed'])}")
+ return 1
+ print("CI gate: all required jobs passed" + (" (strict)" if args.strict else ""))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/run_gates.py b/scripts/ci/run_gates.py
new file mode 100644
index 0000000000..c4720056d5
--- /dev/null
+++ b/scripts/ci/run_gates.py
@@ -0,0 +1,157 @@
+#!/usr/bin/env python3
+"""Run every static repository gate in one process and report them together.
+
+The gates used to be ~25 separate CI steps spread over five jobs, each paying
+for its own runner, checkout and Python set-up — and the first red step hid
+every later one. Here they run back to back (each takes seconds), all of them
+report, and the exit code is non-zero if any failed. Agents run the SAME
+command locally before landing work::
+
+ python scripts/ci/run_gates.py # everything that applies
+ python scripts/ci/run_gates.py --base origin/main --pr
+ python scripts/ci/run_gates.py --only mirrors,privacy
+
+``--pr`` adds the gates that judge a diff against its merge base (no new
+German, unrelated history). ``--base`` feeds the diff-scoped privacy scan.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import shutil
+import subprocess
+import sys
+import time
+from dataclasses import dataclass
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+PY = sys.executable
+
+
+@dataclass(frozen=True)
+class Gate:
+ name: str
+ commands: tuple[tuple[str, ...], ...]
+ pr_only: bool = False
+ needs_base: bool = False
+ needs_docker: bool = False
+
+
+def _gates(base: str) -> list[Gate]:
+ ci = "scripts/ci/"
+ return [
+ Gate("private-keys", ((PY, ci + "check_no_private_keys.py"),)),
+ Gate("dist-consistency", ((PY, ci + "check_dist_consistency.py"),)),
+ Gate("brand-logos", ((PY, ci + "check_brand_logos.py"),)),
+ Gate(
+ "mirrors",
+ (
+ (PY, ci + "sync_agents_md.py", "--check"),
+ (PY, ci + "sync_agents_dir.py", "--check"),
+ (PY, ci + "sync_codex_agents.py", "--check"),
+ ),
+ ),
+ Gate("cli-coverage", ((PY, ci + "check_cli_coverage.py"),)),
+ Gate("danger-metadata", ((PY, ci + "check_danger_metadata.py"),)),
+ Gate("cli-install-methods", ((PY, ci + "check_cli_install_methods.py"),)),
+ Gate("dead-config-switches", ((PY, ci + "check_config_switches_wired.py"),)),
+ Gate("silent-exceptions", ((PY, ci + "check_silent_exception_handlers.py"),)),
+ Gate("async-routes", ((PY, ci + "check_async_routes.py"),)),
+ Gate("webgl-contexts", ((PY, ci + "check_webgl_contexts_released.py"),)),
+ Gate("plugin-auth-contract", ((PY, ci + "check_plugin_auth_contract.py"),)),
+ Gate(
+ "reference-docs",
+ (
+ (PY, ci + "gen_cli_reference.py", "--check"),
+ (PY, ci + "gen_commands_reference.py", "--check"),
+ ),
+ ),
+ Gate("docs-privacy", ((PY, ci + "docs_privacy_scan.py"),)),
+ Gate("public-docs", ((PY, ci + "check_public_docs.py"),)),
+ Gate("shell-bash32", ((PY, ci + "check_shell_bash32.py", "--require"),), needs_docker=True),
+ Gate("privacy", ((PY, ci + "privacy_scan_ci.py", "--base", base),), needs_base=True),
+ Gate("no-new-german", ((PY, ci + "check_no_new_german.py", base),), pr_only=True),
+ Gate(
+ "history",
+ (("git", "merge-base", base, "HEAD"),),
+ pr_only=True,
+ needs_base=True,
+ ),
+ ]
+
+
+def _run(cmd: tuple[str, ...]) -> tuple[int, str]:
+ env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
+ proc = subprocess.run( # noqa: S603
+ list(cmd),
+ cwd=REPO_ROOT,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ env=env,
+ check=False,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0) if os.name == "nt" else 0,
+ )
+ return proc.returncode, (proc.stdout + proc.stderr).strip()
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--base", default="", help="Diff base (sha or ref).")
+ parser.add_argument("--pr", action="store_true", help="Also run pull-request gates.")
+ parser.add_argument("--only", default="", help="Comma-separated gate names.")
+ parser.add_argument("--skip", default="", help="Comma-separated gate names.")
+ args = parser.parse_args(argv)
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+
+ only = {x for x in args.only.split(",") if x}
+ skip = {x for x in args.skip.split(",") if x}
+ has_docker = shutil.which("docker") is not None
+ results: list[tuple[str, str, float]] = []
+ failed = False
+ for gate in _gates(args.base):
+ if (only and gate.name not in only) or gate.name in skip:
+ continue
+ reason = ""
+ if gate.pr_only and not args.pr:
+ reason = "pull-request gate"
+ elif gate.needs_base and not args.base:
+ reason = "no --base given"
+ elif gate.name == "no-new-german" and not args.base:
+ reason = "no --base given"
+ elif gate.needs_docker and not has_docker:
+ reason = "docker unavailable"
+ if reason:
+ results.append((gate.name, f"skip ({reason})", 0.0))
+ continue
+ started = time.monotonic()
+ status = "pass"
+ for cmd in gate.commands:
+ code, output = _run(cmd)
+ if code != 0:
+ status = f"FAIL (exit {code})"
+ failed = True
+ print(f"::group::{gate.name} FAILED: {' '.join(cmd)}")
+ print(output[-6000:])
+ print("::endgroup::")
+ print(f"::error title=Gate {gate.name} failed::{' '.join(cmd[1:])}")
+ break
+ results.append((gate.name, status, time.monotonic() - started))
+
+ lines = ["| gate | result | seconds |", "|---|---|---|"]
+ lines += [f"| {name} | {status} | {secs:.1f} |" for name, status, secs in results]
+ print("\n".join(lines))
+ summary = os.environ.get("GITHUB_STEP_SUMMARY")
+ if summary:
+ with open(summary, "a", encoding="utf-8") as handle:
+ handle.write("## Static gates\n\n" + "\n".join(lines) + "\n")
+ return 1 if failed else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/run_tests_parallel.py b/scripts/ci/run_tests_parallel.py
new file mode 100644
index 0000000000..89a1a7c031
--- /dev/null
+++ b/scripts/ci/run_tests_parallel.py
@@ -0,0 +1,432 @@
+#!/usr/bin/env python3
+"""Sharded, process-isolated pytest runner (the CI test engine).
+
+Why this exists: one monolithic ``pytest tests/`` process took 75-95 minutes
+on a 4-core runner and routinely hit the job timeout. A single wedged test ate
+the whole budget, and module state leaked across the ~2 000 test files.
+
+How it works (the idea is borrowed from Hermes Agent's per-file runner):
+
+1. **Discover** every ``test_*.py`` / ``*_test.py`` under the roots.
+2. **Shard** (``--shard 2/6``): longest-processing-time bin packing over the
+ per-file duration cache, so shards finish together. Every shard computes
+ the same packing, so no coordination is needed.
+3. **Batch**: consecutive files of one directory run in one pytest process
+ (the ~1.5 s interpreter + conftest start-up is paid once per batch).
+4. **Isolate on failure**: a failed or timed-out batch is re-run file by file
+ in fresh processes, and a failed file gets one more fresh attempt. A pass
+ on that attempt is reported as FLAKY, not as a failure.
+5. **Bound**: every process has a wall-clock budget and is killed with its
+ whole process tree, so a hang costs one file, never the job.
+
+Outputs: ``--report`` (JSON: failed test ids, flaky files, counts) and
+``--junit-out`` (merged JUnit XML), plus ``--durations-out`` (timings of files
+that passed on the first attempt — a hang can never ratchet its own budget).
+
+The runner exits 1 when any test failed for real; whether that blocks the
+build is ``test_ratchet.py``'s decision (known failures are baselined).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import shlex
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+import xml.etree.ElementTree as ET # noqa: S405 - parses our own pytest output
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+DEFAULT_MARKERS = (
+ "not skip_ci and not slow and not openclaw_live and not voice_latency and not eval"
+)
+_SKIP_DIRS = {"__pycache__", "node_modules", "fakes", "fixtures", ".pytest_cache"}
+DEFAULT_DURATION = 4.0 # seconds, for a file the cache has never seen
+MIN_FILE_TIMEOUT = 300.0
+MAX_FILE_TIMEOUT = 900.0
+BATCH_TARGET_SECONDS = 45.0
+BATCH_MAX_FILES = 12
+_OK_EXIT_CODES = {0, 5} # 5 = every test deselected / none collected
+
+
+# --------------------------------------------------------------------------- discovery
+
+
+def discover(roots: list[str], repo: Path = REPO_ROOT) -> list[str]:
+ files: set[str] = set()
+ for root in roots:
+ base = (repo / root).resolve()
+ if base.is_file():
+ files.add(base.relative_to(repo).as_posix())
+ continue
+ if not base.is_dir():
+ continue
+ for path in base.rglob("*.py"):
+ rel = path.relative_to(repo)
+ if any(part in _SKIP_DIRS for part in rel.parts):
+ continue
+ if path.name.startswith("test_") or path.name.endswith("_test.py"):
+ files.add(rel.as_posix())
+ return sorted(files)
+
+
+def load_durations(path: Path | None) -> dict[str, float]:
+ if not path or not path.is_file():
+ return {}
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError) as exc:
+ print(f"[runner] duration cache unreadable ({exc}); using defaults", flush=True)
+ return {}
+ return {str(k): float(v) for k, v in data.items() if isinstance(v, int | float)}
+
+
+def estimate(file: str, durations: dict[str, float]) -> float:
+ return max(0.5, durations.get(file, DEFAULT_DURATION))
+
+
+def shard(files: list[str], index: int, total: int, durations: dict[str, float]) -> list[str]:
+ """Deterministic LPT bin packing; returns shard ``index`` (1-based) of ``total``."""
+ if total <= 1:
+ return list(files)
+ bins: list[tuple[float, int, list[str]]] = [(0.0, i, []) for i in range(total)]
+ for file in sorted(files, key=lambda f: (-estimate(f, durations), f)):
+ load, idx, members = min(bins, key=lambda b: (b[0], b[1]))
+ members.append(file)
+ bins[idx] = (load + estimate(file, durations), idx, members)
+ return sorted(bins[index - 1][2])
+
+
+def make_batches(files: list[str], durations: dict[str, float]) -> list[list[str]]:
+ batches: list[list[str]] = []
+ current: list[str] = []
+ current_dir = None
+ load = 0.0
+ for file in sorted(files):
+ directory = file.rsplit("/", 1)[0]
+ cost = estimate(file, durations)
+ # A file that alone exceeds the target always runs by itself.
+ if current and (
+ directory != current_dir
+ or load + cost > BATCH_TARGET_SECONDS
+ or len(current) >= BATCH_MAX_FILES
+ or cost > BATCH_TARGET_SECONDS
+ ):
+ batches.append(current)
+ current, load = [], 0.0
+ current.append(file)
+ current_dir = directory
+ load += cost
+ if current:
+ batches.append(current)
+ return batches
+
+
+def file_timeout(file: str, durations: dict[str, float]) -> float:
+ return min(MAX_FILE_TIMEOUT, max(MIN_FILE_TIMEOUT, 3 * durations.get(file, 0.0)))
+
+
+# --------------------------------------------------------------------------- execution
+
+
+@dataclass
+class RunResult:
+ files: list[str]
+ exit_code: int
+ duration: float
+ timed_out: bool
+ failed_ids: list[str] = field(default_factory=list)
+ file_seconds: dict[str, float] = field(default_factory=dict)
+ counts: dict[str, int] = field(default_factory=dict)
+ junit: Path | None = None
+ log_tail: str = ""
+
+ @property
+ def ok(self) -> bool:
+ return not self.timed_out and self.exit_code in _OK_EXIT_CODES and not self.failed_ids
+
+
+def _kill_tree(proc: subprocess.Popen[bytes]) -> None:
+ try:
+ if os.name == "nt":
+ subprocess.run( # noqa: S603
+ ["taskkill", "/F", "/T", "/PID", str(proc.pid)], # noqa: S607
+ capture_output=True,
+ check=False,
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
+ )
+ else:
+ os.killpg(proc.pid, signal.SIGKILL)
+ except (OSError, subprocess.SubprocessError) as exc:
+ print(f"[runner] could not kill process tree {proc.pid}: {exc}", flush=True)
+ try:
+ proc.kill()
+ except OSError:
+ pass # already gone - the tree kill above reaped it
+
+
+def _module_to_file(classname: str, files: list[str]) -> str | None:
+ dotted = classname.replace(".", "/")
+ best = None
+ for file in files:
+ stem = file[:-3]
+ if dotted == stem or dotted.startswith(stem + "/"):
+ if best is None or len(stem) > len(best[:-3]):
+ best = file
+ return best
+
+
+def parse_junit(path: Path, files: list[str]) -> tuple[list[str], dict[str, float], dict[str, int]]:
+ """Return (failed ids, seconds per file, counts) from one pytest JUnit file."""
+ failed: list[str] = []
+ seconds: dict[str, float] = {}
+ counts = {"tests": 0, "passed": 0, "failed": 0, "skipped": 0}
+ if not path.is_file():
+ return failed, seconds, counts
+ try:
+ root = ET.parse(path).getroot() # noqa: S314 - our own pytest output
+ except ET.ParseError as exc:
+ print(f"[runner] unreadable JUnit {path.name}: {exc}", flush=True)
+ return failed, seconds, counts
+ for case in root.iter("testcase"):
+ classname = case.get("classname", "")
+ name = case.get("name", "")
+ counts["tests"] += 1
+ owner = _module_to_file(classname, files) or (files[0] if len(files) == 1 else "")
+ seconds[owner] = seconds.get(owner, 0.0) + float(case.get("time", 0) or 0)
+ if case.find("failure") is not None or case.find("error") is not None:
+ counts["failed"] += 1
+ failed.append(f"{classname}::{name}")
+ elif case.find("skipped") is not None:
+ counts["skipped"] += 1
+ else:
+ counts["passed"] += 1
+ return failed, seconds, counts
+
+
+class Runner:
+ def __init__(self, args: argparse.Namespace, durations: dict[str, float], workdir: Path):
+ self.args = args
+ self.durations = durations
+ self.workdir = workdir
+ self._seq = 0
+ self._lock = threading.Lock()
+
+ def _next_id(self) -> int:
+ with self._lock:
+ self._seq += 1
+ return self._seq
+
+ def run(self, files: list[str], timeout: float) -> RunResult:
+ run_id = self._next_id()
+ junit = self.workdir / f"run-{run_id:05d}.xml"
+ log = self.workdir / f"run-{run_id:05d}.log"
+ cmd = [
+ sys.executable,
+ "-m",
+ "pytest",
+ *files,
+ "-q",
+ "-p",
+ "no:cacheprovider",
+ "-o",
+ "faulthandler_timeout=240",
+ f"--basetemp={self.workdir / f'tmp-{run_id:05d}'}",
+ f"--junitxml={junit}",
+ "-m",
+ self.args.markers,
+ *shlex.split(self.args.pytest_args or ""),
+ ]
+ env = dict(os.environ)
+ env.setdefault("PYTHONUTF8", "1")
+ env["JARVIS_TEST_RUNNER_ISOLATED"] = "1"
+ popen_kwargs: dict[str, object] = {}
+ if os.name == "nt":
+ popen_kwargs["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0)
+ else:
+ popen_kwargs["start_new_session"] = True
+ started = time.monotonic()
+ timed_out = False
+ with log.open("wb") as sink:
+ proc = subprocess.Popen( # noqa: S603
+ cmd,
+ cwd=REPO_ROOT,
+ stdout=sink,
+ stderr=subprocess.STDOUT,
+ stdin=subprocess.DEVNULL,
+ env=env,
+ **popen_kwargs, # type: ignore[arg-type]
+ )
+ try:
+ exit_code = proc.wait(timeout=timeout)
+ except subprocess.TimeoutExpired:
+ timed_out = True
+ _kill_tree(proc)
+ exit_code = proc.wait()
+ duration = time.monotonic() - started
+ failed, seconds, counts = parse_junit(junit, files)
+ tail = ""
+ if timed_out or exit_code not in _OK_EXIT_CODES or failed:
+ text = log.read_text(encoding="utf-8", errors="replace")
+ tail = "\n".join(text.splitlines()[-60:])
+ if timed_out:
+ failed = failed or [f"{f}::<timeout {int(timeout)}s>" for f in files]
+ elif not failed:
+ failed = [f"{f}::<pytest exit {exit_code}>" for f in files]
+ return RunResult(
+ files, exit_code, duration, timed_out, failed, seconds, counts, junit, tail
+ )
+
+ def run_unit(self, batch: list[str]) -> dict[str, object]:
+ """Run one batch with isolation-on-failure and a flaky retry."""
+ budget = min(1800.0, sum(file_timeout(f, self.durations) for f in batch))
+ first = self.run(batch, budget)
+ outcome: dict[str, object] = {"runs": [first], "flaky": [], "first_pass": []}
+ if first.ok:
+ outcome["first_pass"] = list(batch)
+ return outcome
+ runs: list[RunResult] = []
+ flaky: list[str] = []
+ for file in batch:
+ budget_one = file_timeout(file, self.durations)
+ single = first if len(batch) == 1 else self.run([file], budget_one)
+ if not single.ok and not single.timed_out:
+ retry = self.run([file], budget_one)
+ if retry.ok:
+ flaky.append(file)
+ single = retry
+ runs.append(single)
+ outcome["runs"] = runs
+ outcome["flaky"] = flaky
+ return outcome
+
+
+# --------------------------------------------------------------------------- reporting
+
+
+def merge_junit(paths: list[Path], out: Path) -> None:
+ merged = ET.Element("testsuites")
+ for path in paths:
+ if not path.is_file():
+ continue
+ try:
+ root = ET.parse(path).getroot() # noqa: S314 - our own pytest output
+ except ET.ParseError as exc:
+ print(f"[runner] skipping unreadable JUnit {path.name}: {exc}", flush=True)
+ continue
+ suites = [root] if root.tag == "testsuite" else list(root.iter("testsuite"))
+ merged.extend(suites)
+ out.parent.mkdir(parents=True, exist_ok=True)
+ ET.ElementTree(merged).write(out, encoding="utf-8", xml_declaration=True)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("roots", nargs="*", default=["tests"], help="Discovery roots.")
+ parser.add_argument("--files-from", type=Path, help="Explicit file list (one per line).")
+ parser.add_argument("--shard", default="1/1", help="i/n — run shard i of n.")
+ parser.add_argument("--workers", type=int, default=os.cpu_count() or 2)
+ parser.add_argument("--markers", default=DEFAULT_MARKERS)
+ parser.add_argument("--pytest-args", default="", help="Extra args for every pytest run.")
+ parser.add_argument("--durations", type=Path, default=REPO_ROOT / "test_durations.json")
+ parser.add_argument("--durations-out", type=Path)
+ parser.add_argument("--report", type=Path, default=Path("test-report.json"))
+ parser.add_argument("--junit-out", type=Path, default=Path("report.xml"))
+ parser.add_argument("--list", action="store_true", help="Print the shard's files and exit.")
+ args = parser.parse_args(argv)
+ # Windows consoles default to cp1252; a test log with box-drawing
+ # characters must never crash the runner that is reporting it (AP-1).
+ for stream in (sys.stdout, sys.stderr):
+ if hasattr(stream, "reconfigure"):
+ stream.reconfigure(encoding="utf-8", errors="replace")
+
+ index, total = (int(x) for x in args.shard.split("/", 1))
+ durations = load_durations(args.durations)
+ if args.files_from:
+ wanted = [line.strip() for line in args.files_from.read_text(encoding="utf-8").splitlines()]
+ files = sorted({f for f in wanted if f and (REPO_ROOT / f).is_file()})
+ else:
+ files = discover(args.roots)
+ mine = shard(files, index, total, durations)
+ if args.list:
+ print("\n".join(mine))
+ return 0
+
+ print(
+ f"[runner] shard {index}/{total}: {len(mine)} of {len(files)} files, "
+ f"{args.workers} workers, markers={args.markers!r}",
+ flush=True,
+ )
+ batches = make_batches(mine, durations)
+ started = time.monotonic()
+ workdir = Path(tempfile.mkdtemp(prefix="jarvis-tests-"))
+ runner = Runner(args, durations, workdir)
+ all_runs: list[RunResult] = []
+ flaky: list[str] = []
+ first_pass: list[str] = []
+ done = 0
+ with ThreadPoolExecutor(max_workers=max(1, args.workers)) as pool:
+ futures = [pool.submit(runner.run_unit, batch) for batch in batches]
+ for future in futures:
+ outcome = future.result()
+ runs = outcome["runs"] # type: ignore[assignment]
+ all_runs.extend(runs) # type: ignore[arg-type]
+ flaky.extend(outcome["flaky"]) # type: ignore[arg-type]
+ first_pass.extend(outcome["first_pass"]) # type: ignore[arg-type]
+ done += 1
+ for run in runs: # type: ignore[attr-defined]
+ if not run.ok:
+ label = "TIMEOUT" if run.timed_out else f"FAIL exit={run.exit_code}"
+ names = " ".join(run.files)
+ print(f"\n[runner] {label}: {names}\n{run.log_tail}\n", flush=True)
+ if done % 20 == 0 or done == len(futures):
+ print(f"[runner] {done}/{len(futures)} batches done", flush=True)
+
+ failed_ids = sorted({fid for run in all_runs for fid in run.failed_ids})
+ counts = {"tests": 0, "passed": 0, "failed": 0, "skipped": 0}
+ for run in all_runs:
+ for key in counts:
+ counts[key] += run.counts.get(key, 0)
+ elapsed = time.monotonic() - started
+ report = {
+ "shard": f"{index}/{total}",
+ "platform": sys.platform,
+ "files": len(mine),
+ "counts": counts,
+ "failed_ids": failed_ids,
+ "flaky_files": sorted(set(flaky)),
+ "timeouts": sorted({f for run in all_runs if run.timed_out for f in run.files}),
+ "elapsed_seconds": round(elapsed, 1),
+ }
+ args.report.parent.mkdir(parents=True, exist_ok=True)
+ args.report.write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
+ merge_junit([run.junit for run in all_runs if run.junit], args.junit_out)
+
+ if args.durations_out:
+ fresh: dict[str, float] = {}
+ for run in all_runs:
+ for file, secs in run.file_seconds.items():
+ if file in first_pass:
+ fresh[file] = round(secs + 1.0, 2) # + interpreter start-up share
+ payload = json.dumps(fresh, indent=1, sort_keys=True) + "\n"
+ args.durations_out.write_text(payload, encoding="utf-8")
+
+ print(
+ f"[runner] done in {elapsed:.0f}s: {counts['passed']} passed, {counts['failed']} failed, "
+ f"{counts['skipped']} skipped, {len(set(flaky))} flaky files, "
+ f"{len(report['timeouts'])} timed-out files",
+ flush=True,
+ )
+ return 1 if failed_ids else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/scripts/ci/select_tests.py b/scripts/ci/select_tests.py
new file mode 100644
index 0000000000..bd7b0d7f4c
--- /dev/null
+++ b/scripts/ci/select_tests.py
@@ -0,0 +1,133 @@
+#!/usr/bin/env python3
+"""Pick the test files a change can plausibly affect (impact selection).
+
+Used where running everything is expensive and a full run follows anyway:
+the Windows leg of a pull request (the full Windows suite runs on every push
+to main and nightly) and ``scripts/agent_land.py``'s fast local check.
+
+Selection is textual and deliberately generous — FAIL OPEN:
+
+* a changed test file selects itself;
+* a changed ``jarvis/a/b.py`` selects every test that names ``jarvis.a.b``
+ (import or monkeypatch target) and every ``test_b*.py``;
+* any other changed file (frontend source, docs, assets) selects the tests
+ that mention its path or its file stem;
+* conftest, packaging, lockfiles or the pipeline itself select EVERYTHING,
+ and so does a selection larger than :data:`ALL_RATIO` of the suite.
+
+Writes the file list to ``--out`` and ``mode=all|selected|none`` plus
+``count=N`` to ``$GITHUB_OUTPUT``.
+"""
+
+from __future__ import annotations
+
+import argparse
+import os
+import re
+import sys
+from pathlib import Path
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+if str(REPO_ROOT) not in sys.path:
+ sys.path.insert(0, str(REPO_ROOT))
+
+from scripts.ci.run_tests_parallel import discover # noqa: E402
+
+ALL_RATIO = 0.35
+_EVERYTHING_PREFIXES = (".github/workflows/", "scripts/ci/", "tests/fakes/", "tests/fixtures/")
+_EVERYTHING_FILES = {
+ "conftest.py",
+ "tests/conftest.py",
+ "tests/unit/conftest.py",
+ "pyproject.toml",
+ "requirements.txt",
+ "uv.lock",
+ "jarvis/__init__.py",
+}
+# The contract guards CLAUDE.md names: cheap, and they pin the invariants a
+# change anywhere in jarvis/ can break without importing them by name.
+SMOKE = (
+ "tests/unit/brain/test_routing.py",
+ "tests/unit/brain/test_output_filter.py",
+ "tests/unit/sessions/test_hangup_reason_parity.py",
+ "tests/unit/core/test_turn_language.py",
+)
+_MIN_STEM = 5
+
+
+def _needles(path: str) -> list[str]:
+ stem = Path(path).stem
+ if path.startswith("jarvis/") and path.endswith(".py"):
+ dotted = path[:-3].replace("/", ".")
+ if dotted.endswith(".__init__"):
+ dotted = dotted[: -len(".__init__")]
+ parent, _, leaf = dotted.rpartition(".")
+ needles = [dotted, f"from {parent} import {leaf}" if parent else dotted]
+ return needles
+ needles = [path]
+ if len(stem) >= _MIN_STEM and stem not in {"index", "__init__", "README", "types"}:
+ needles.append(stem)
+ return needles
+
+
+def select(changed: list[str], tests: list[str], texts: dict[str, str]) -> tuple[str, list[str]]:
+ changed = [c.strip().replace("\\", "/") for c in changed if c.strip()]
+ if not changed:
+ return "all", list(tests)
+ if any(c.startswith(_EVERYTHING_PREFIXES) or c in _EVERYTHING_FILES for c in changed):
+ return "all", list(tests)
+ if any(Path(c).name == "conftest.py" for c in changed):
+ return "all", list(tests)
+ chosen: set[str] = set()
+ touches_product = False
+ test_set = set(tests)
+ for path in changed:
+ if path in test_set:
+ chosen.add(path)
+ continue
+ if path.startswith("jarvis/"):
+ touches_product = True
+ stem = Path(path).stem
+ if path.endswith(".py") and stem != "__init__":
+ pattern = re.compile(rf"(^|/)test_{re.escape(stem)}(_[^/]*)?\.py$")
+ chosen.update(t for t in tests if pattern.search(t))
+ needles = _needles(path)
+ for test, text in texts.items():
+ if any(needle in text for needle in needles):
+ chosen.add(test)
+ if touches_product:
+ chosen.update(t for t in SMOKE if t in test_set)
+ if len(chosen) > ALL_RATIO * max(1, len(tests)):
+ return "all", list(tests)
+ if not chosen:
+ return "none", []
+ return "selected", sorted(chosen)
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--changed-from", type=Path, help="File with changed paths (else stdin).")
+ parser.add_argument("--out", type=Path, default=Path("selected-tests.txt"))
+ args = parser.parse_args(argv)
+
+ if args.changed_from:
+ changed = args.changed_from.read_text(encoding="utf-8").splitlines()
+ else:
+ changed = sys.stdin.read().splitlines()
+ tests = discover(["tests"])
+ texts = {
+ t: (REPO_ROOT / t).read_text(encoding="utf-8", errors="replace").replace("\\", "/")
+ for t in tests
+ }
+ mode, chosen = select(changed, tests, texts)
+ args.out.write_text("\n".join(chosen) + ("\n" if chosen else ""), encoding="utf-8")
+ print(f"mode={mode} count={len(chosen)} of {len(tests)}")
+ output = os.environ.get("GITHUB_OUTPUT")
+ if output:
+ with open(output, "a", encoding="utf-8") as handle:
+ handle.write(f"mode={mode}\ncount={len(chosen)}\n")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/tests/unit/ci/test_pipeline_scripts.py b/tests/unit/ci/test_pipeline_scripts.py
new file mode 100644
index 0000000000..45427e3645
--- /dev/null
+++ b/tests/unit/ci/test_pipeline_scripts.py
@@ -0,0 +1,324 @@
+"""Behaviour of the CI orchestrator's scripts (lanes, gate, sharding, ratchet,
+impact selection, conflict resolution, release cut)."""
+
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from scripts.ci import (
+ agent_integrate,
+ classify_changes,
+ cut_release,
+ ratchet_tests,
+ required_results,
+ run_tests_parallel,
+ select_tests,
+)
+
+# --------------------------------------------------------------------------- lanes
+
+
+def test_empty_change_set_fails_open_to_every_lane():
+ result = classify_changes.classify([])
+ assert result["full"] is True
+ assert all(result[lane] for lane in classify_changes.LANES)
+
+
+def test_pipeline_change_runs_everything():
+ result = classify_changes.classify(["scripts/ci/run_gates.py"])
+ assert result["full"] and result["frontend"] and result["macos_desktop"]
+
+
+def test_frontend_source_change_keeps_python_on_because_tests_read_it():
+ result = classify_changes.classify(["jarvis/ui/web/frontend/src/views/tasks/taskSpec.ts"])
+ assert result["frontend"] is True
+ assert result["python"] is True
+ assert result["realtime"] is False
+ assert result["full"] is False
+
+
+def test_unrelated_subproject_skips_python():
+ result = classify_changes.classify(["wiki-video/src/scene.tsx", "homebrew-tap/Formula/x.rb"])
+ assert result["python"] is False
+ assert not any(result[lane] for lane in classify_changes.LANES)
+
+
+def test_route_change_turns_on_cli_lane_and_windows_path_is_normalized():
+ result = classify_changes.classify(["jarvis\\ui\\web\\update_routes.py"])
+ assert result["cli"] is True
+ assert result["python"] is True
+
+
+def test_lockfile_change_reaches_deps_realtime_and_installer():
+ result = classify_changes.classify(["requirements.txt"])
+ assert result["deps"] and result["realtime"] and result["installer"]
+
+
+# --------------------------------------------------------------------------- gate
+
+
+def test_gate_passes_skips_but_fails_failures_and_cancellations():
+ needs = {"a": {"result": "success"}, "b": {"result": "skipped"}}
+ assert required_results.evaluate(needs)["ok"] is True
+ needs["c"] = {"result": "cancelled"}
+ verdict = required_results.evaluate(needs)
+ assert verdict["ok"] is False and verdict["failed"] == ["c"]
+
+
+def test_strict_gate_rejects_a_skip_outside_the_allow_list():
+ needs = {"frontend": {"result": "skipped"}, "soak": {"result": "skipped"}}
+ verdict = required_results.evaluate(needs, strict=True)
+ assert verdict["failed"] == ["frontend"]
+
+
+def test_gate_with_no_jobs_fails():
+ assert required_results.evaluate({})["ok"] is False
+
+
+# --------------------------------------------------------------------------- sharding
+
+
+def test_shards_partition_the_suite_exactly_once():
+ files = [f"tests/unit/m{i}/test_{i}.py" for i in range(40)]
+ durations = {f: float(i % 7 + 1) for i, f in enumerate(files)}
+ parts = [run_tests_parallel.shard(files, i, 4, durations) for i in range(1, 5)]
+ flat = [f for part in parts for f in part]
+ assert sorted(flat) == sorted(files)
+ loads = [sum(run_tests_parallel.estimate(f, durations) for f in part) for part in parts]
+ assert max(loads) - min(loads) <= 7 # LPT keeps shards within one file
+
+
+def test_batches_stay_in_one_directory_and_isolate_slow_files():
+ durations = {"tests/a/test_slow.py": 200.0}
+ files = ["tests/a/test_1.py", "tests/a/test_slow.py", "tests/a/test_2.py", "tests/b/test_3.py"]
+ batches = run_tests_parallel.make_batches(files, durations)
+ assert ["tests/a/test_slow.py"] in batches
+ assert all(len({f.rsplit("/", 1)[0] for f in batch}) == 1 for batch in batches)
+ assert sorted(f for batch in batches for f in batch) == sorted(files)
+
+
+def test_file_timeout_scales_with_history_but_is_bounded():
+ assert run_tests_parallel.file_timeout("x", {}) == run_tests_parallel.MIN_FILE_TIMEOUT
+ assert (
+ run_tests_parallel.file_timeout("x", {"x": 10_000}) == run_tests_parallel.MAX_FILE_TIMEOUT
+ )
+
+
+def test_runner_reports_failures_and_passes(tmp_path):
+ repo = run_tests_parallel.REPO_ROOT
+ rel = Path(f"tests/unit/ci/_runner_probe_{tmp_path.name}")
+ probe = repo / rel
+ probe.mkdir()
+ try:
+ (probe / "test_probe_ok.py").write_text("def test_ok():\n assert True\n")
+ (probe / "test_probe_bad.py").write_text("def test_bad():\n assert False\n")
+ code = run_tests_parallel.main(
+ [
+ str(rel),
+ "--workers",
+ "2",
+ "--markers",
+ "",
+ "--durations",
+ str(tmp_path / "none.json"),
+ "--report",
+ str(tmp_path / "r.json"),
+ "--junit-out",
+ str(tmp_path / "r.xml"),
+ ]
+ )
+ finally:
+ shutil.rmtree(probe, ignore_errors=True)
+ report = json.loads((tmp_path / "r.json").read_text(encoding="utf-8"))
+ assert code == 1
+ assert report["counts"]["passed"] == 1
+ assert any(fid.endswith("::test_bad") for fid in report["failed_ids"])
+
+
+# --------------------------------------------------------------------------- ratchet
+
+
+def _report(path: Path, failed: list[str], passed: int = 10) -> Path:
+ path.write_text(
+ json.dumps({"failed_ids": failed, "counts": {"passed": passed}, "elapsed_seconds": 1}),
+ encoding="utf-8",
+ )
+ return path
+
+
+def test_ratchet_blocks_only_new_failures(tmp_path):
+ baseline = tmp_path / "b.json"
+ baseline.write_text(json.dumps({"known_failures": ["t.a::x"]}), encoding="utf-8")
+ known = _report(tmp_path / "r1.json", ["t.a::x"])
+ new = _report(tmp_path / "r2.json", ["t.a::x", "t.b::y"])
+ assert ratchet_tests.main(["check", "--baseline", str(baseline), str(known)]) == 0
+ assert ratchet_tests.main(["check", "--baseline", str(baseline), str(new)]) == 1
+
+
+def test_ratchet_matches_timeouts_regardless_of_budget(tmp_path):
+ baseline = tmp_path / "b.json"
+ baseline.write_text(
+ json.dumps({"known_failures": ["tests/x.py::<timeout 300s>"]}), encoding="utf-8"
+ )
+ report = _report(tmp_path / "r.json", ["tests/x.py::<timeout 900s>"])
+ assert ratchet_tests.main(["check", "--baseline", str(baseline), str(report)]) == 0
+
+
+def test_missing_baseline_is_report_only(tmp_path):
+ report = _report(tmp_path / "r.json", ["t::new"])
+ assert ratchet_tests.main(["check", "--baseline", str(tmp_path / "no.json"), str(report)]) == 0
+
+
+def test_update_writes_a_baseline_the_check_accepts(tmp_path):
+ report = _report(tmp_path / "test-report-1.json", ["t::a", "t::b"])
+ out = tmp_path / "base.json"
+ assert ratchet_tests.main(["update", "--out", str(out), str(report)]) == 0
+ assert ratchet_tests.main(["check", "--baseline", str(out), str(report)]) == 0
+
+
+# --------------------------------------------------------------------------- selection
+
+
+def test_selection_maps_a_module_to_the_tests_that_import_it():
+ others = [f"tests/unit/b/test_other{i}.py" for i in range(9)]
+ tests = ["tests/unit/a/test_widget.py", *others]
+ texts = dict.fromkeys(others, "import json")
+ texts["tests/unit/a/test_widget.py"] = "from jarvis.core.widget import Widget"
+ mode, chosen = select_tests.select(["jarvis/core/widget.py"], tests, texts)
+ assert mode == "selected"
+ assert chosen == ["tests/unit/a/test_widget.py"]
+
+
+def test_selection_falls_back_to_everything_for_shared_fixtures():
+ tests = ["tests/unit/a/test_x.py"]
+ mode, chosen = select_tests.select(["tests/conftest.py"], tests, {tests[0]: ""})
+ assert mode == "all" and chosen == tests
+
+
+# --------------------------------------------------------------------------- integration
+
+
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", "-C", str(repo), *args], capture_output=True, text=True, check=True
+ ).stdout
+
+
+def repo(tmp_path):
+ root = tmp_path / "repo"
+ root.mkdir()
+ _git(root, "init", "-q", "-b", "main")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "t")
+ _git(root, "config", "core.autocrlf", "false")
+ (root / "CHANGELOG.md").write_text("# Changelog\n\n- base\n", encoding="utf-8")
+ (root / "test_durations.json").write_text('{"a": 1}\n', encoding="utf-8")
+ (root / "app.py").write_text("VALUE = 1\n", encoding="utf-8")
+ _git(root, "add", ".")
+ _git(root, "commit", "-q", "-m", "base")
+ return root
+
+
+def _diverge(repo: Path, main_edit: dict[str, str], branch_edit: dict[str, str]) -> None:
+ _git(repo, "checkout", "-q", "-b", "feature")
+ for name, text in branch_edit.items():
+ (repo / name).write_text(text, encoding="utf-8")
+ _git(repo, "commit", "-q", "-am", "feature work")
+ _git(repo, "checkout", "-q", "main")
+ for name, text in main_edit.items():
+ (repo / name).write_text(text, encoding="utf-8")
+ _git(repo, "commit", "-q", "-am", "main work")
+ _git(repo, "checkout", "-q", "feature")
+
+
[email protected]("mode", ["merge", "rebase"])
+def test_generated_and_append_only_conflicts_resolve_themselves(repo, mode):
+ _diverge(
+ repo,
+ {
+ "CHANGELOG.md": "# Changelog\n\n- main entry\n- base\n",
+ "test_durations.json": '{"a": 2}\n',
+ },
+ {
+ "CHANGELOG.md": "# Changelog\n\n- branch entry\n- base\n",
+ "test_durations.json": '{"a": 3}\n',
+ },
+ )
+ report = agent_integrate.update("main", mode, "", repo)
+ assert report["status"] == "updated", report
+ changelog = (repo / "CHANGELOG.md").read_text(encoding="utf-8")
+ assert "main entry" in changelog and "branch entry" in changelog
+ assert json.loads((repo / "test_durations.json").read_text(encoding="utf-8")) == {"a": 2}
+ assert _git(repo, "status", "--porcelain").strip() == ""
+
+
[email protected]("mode", ["merge", "rebase"])
+def test_semantic_conflict_aborts_cleanly_without_a_resolver(repo, mode):
+ _diverge(repo, {"app.py": "VALUE = 2\n"}, {"app.py": "VALUE = 3\n"})
+ head = _git(repo, "rev-parse", "HEAD")
+ report = agent_integrate.update("main", mode, "", repo)
+ assert report["status"] == "conflict"
+ assert report["unresolved"] == ["app.py"]
+ assert _git(repo, "rev-parse", "HEAD") == head
+ assert (repo / "app.py").read_text(encoding="utf-8") == "VALUE = 3\n"
+
+
+def test_up_to_date_branch_is_left_alone(repo):
+ assert agent_integrate.update("main", "merge", "", repo) == {"status": "up-to-date"}
+
+
+def test_train_eligibility():
+ base = {"baseRefName": "main", "isDraft": False, "labels": [], "isCrossRepository": False}
+ assert agent_integrate.eligible({**base, "headRefName": "codex/fix"})
+ assert not agent_integrate.eligible({**base, "headRefName": "feature/x"})
+ assert agent_integrate.eligible(
+ {**base, "headRefName": "feature/x", "labels": [{"name": "auto-merge"}]}
+ )
+ assert not agent_integrate.eligible(
+ {**base, "headRefName": "codex/x", "labels": [{"name": "needs-human"}]}
+ )
+ assert not agent_integrate.eligible(
+ {**base, "headRefName": "codex/x", "isCrossRepository": True}
+ )
+ assert not agent_integrate.eligible({**base, "headRefName": "dependabot/pip/x"})
+
+
+# --------------------------------------------------------------------------- release
+
+
+def test_bump_and_commit_notes():
+ assert cut_release.bump("2.3.2", "patch") == "2.3.3"
+ assert cut_release.bump("2.3.2", "minor") == "2.4.0"
+ assert cut_release.bump("2.3.2", "major") == "3.0.0"
+ notes = cut_release.notes_from_commits(
+ ["feat(ide): drag folders", "fix: stale backend", "chore: tidy", "feat!: new config"]
+ )
+ assert "### Added\n\n- Drag folders" in notes
+ assert "### Fixed\n\n- Stale backend" in notes
+ assert "### Breaking" in notes and "Tidy" not in notes
+
+
+def test_apply_moves_notes_under_a_dated_section(tmp_path):
+ (tmp_path / "jarvis").mkdir()
+ (tmp_path / "pyproject.toml").write_text('[project]\nversion = "1.0.0"\n', encoding="utf-8")
+ (tmp_path / "jarvis" / "__init__.py").write_text('__version__ = "1.0.0"\n', encoding="utf-8")
+ (tmp_path / "CHANGELOG.md").write_text(
+ "# Changelog\n\n## [Unreleased]\n\n---\n\n## [1.0.0] — 2026-01-01\n\n- old\n",
+ encoding="utf-8",
+ )
+ cut_release.apply("1.1.0", "### Added\n\n- thing", "2026-09-28", tmp_path)
+ text = (tmp_path / "CHANGELOG.md").read_text(encoding="utf-8")
+ assert text.index("## [Unreleased]") < text.index("## [1.1.0] — 2026-09-28")
+ assert text.index("## [1.1.0]") < text.index("## [1.0.0]")
+ assert cut_release.section_notes(text, "1.1.0") == "### Added\n\n- thing"
+ from scripts.ci import release_admit
+
+ assert release_admit.versions(tmp_path) == ("1.1.0", "1.1.0")
+ assert release_admit.check_identity("v1.1.0", tmp_path) == []
+ assert release_admit.check_identity("v1.2.0", tmp_path)