Coverage for aq_devtools.py: 100%
1305 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Developer and maintainer commands of `aq`: the commit gate, the environment, CI, dependencies, coverage, Codespaces,
2the vault, Problems, lint, the CLI's own docs and completion, and the project's at-a-glance status.
4Every command is a `cmd_*(args) -> int`, registered by `register(subparsers)` from `aq_cli.build_parser()`. Every
5subprocess goes through `RUN` (tests replace it), so nothing here calls git, gh, npm or docker under test. Commands
6that need a source checkout (scripts/, .git, .githooks) say so and exit 1 on a wheel install.
8Exit codes: 0 ok, 1 failure, 2 usage, 3 a gate failed or something is still running, 130 interrupted.
9"""
11from __future__ import annotations
13import argparse
14import datetime as _datetime
15import difflib
16import fnmatch
17import json
18import os
19import platform
20import re
21import shutil
22import subprocess
23import sys
24import time
25from collections.abc import Callable, Iterable, Mapping, Sequence
26from importlib.metadata import PackageNotFoundError
27from importlib.metadata import version as _package_version
28from pathlib import Path
29from typing import Any
31ROOT_DIR = Path(__file__).resolve().parent
32RUN: Callable[..., subprocess.CompletedProcess] = subprocess.run
33COVERAGE_MARKER = "aq-skip-coverage"
34COVERAGE_STATES = ("persistent", "once")
35PACKAGE_NAME = "aether-quant"
36EXIT_OK, EXIT_FAIL, EXIT_USAGE, EXIT_GATE, EXIT_INTERRUPTED = 0, 1, 2, 3, 130
39# ---------------------------------------------------------------------------
40# shared helpers
41# ---------------------------------------------------------------------------
44def run_capture(command: Sequence[str], *, cwd: Path | None = None, env: Mapping[str, str] | None = None, timeout: float | None = 120) -> tuple[int, str]:
45 """(exit code, stdout+stderr) of `command`; a missing program or a timeout is exit 127 / 124 with the reason as text."""
46 try:
47 result = RUN(list(command), cwd=str(cwd or ROOT_DIR), env=dict(env) if env is not None else None, capture_output=True, text=True, check=False, timeout=timeout)
48 except FileNotFoundError:
49 return 127, f"{command[0]}: not found"
50 except subprocess.TimeoutExpired:
51 return 124, f"{command[0]}: timed out"
52 return result.returncode, (result.stdout or "") + (result.stderr or "")
55def run_live(command: Sequence[str], *, cwd: Path | None = None, env: Mapping[str, str] | None = None) -> int:
56 """Run `command` with the terminal attached; a missing program is exit 127 with one line on stderr."""
57 try:
58 return RUN(list(command), cwd=str(cwd or ROOT_DIR), env=dict(env) if env is not None else None, check=False).returncode
59 except FileNotFoundError:
60 print(f"aq: {command[0]} not found on PATH", file=sys.stderr)
61 return 127
64def emit(data: Any, as_json: bool, render: Callable[[Any], str] | None = None) -> None:
65 """Print `data` as JSON (finite-safe) or through `render`."""
66 if as_json:
67 from json_safety import sanitize_json_finite
69 print(json.dumps(sanitize_json_finite(data), indent=2, sort_keys=True, default=str))
70 else:
71 print(render(data) if render else str(data))
74def confirm(prompt: str, *, assume_yes: bool, isatty: Callable[[], bool] | None = None, ask: Callable[[str], str] = input) -> bool:
75 """True when `--yes` was given or the user typed y on a terminal; never prompts without a terminal."""
76 if assume_yes:
77 return True
78 if not (isatty or sys.stdin.isatty)():
79 print(f"aq: {prompt} - pass --yes to confirm", file=sys.stderr)
80 return False
81 return ask(f"{prompt} [y/N] ").strip().lower() in {"y", "yes"}
84def add_json_flag(parser: argparse.ArgumentParser) -> None:
85 parser.add_argument("--json", action="store_true", help="Print JSON instead of text")
88def add_dry_run_flag(parser: argparse.ArgumentParser) -> None:
89 parser.add_argument("--dry-run", action="store_true", help="Print what would happen, change nothing")
92def add_yes_flag(parser: argparse.ArgumentParser) -> None:
93 parser.add_argument("--yes", action="store_true", help="Confirm without a prompt (needed without a terminal)")
96def source_checkout(root: Path = ROOT_DIR) -> bool:
97 """A git checkout of this project (scripts/ and .githooks/ exist), not a wheel install."""
98 return (root / "scripts").is_dir() and (root / ".githooks").is_dir() and (root / "pyproject.toml").is_file()
101def needs_checkout(root: Path = ROOT_DIR) -> int | None:
102 if source_checkout(root):
103 return None
104 print("aq: this command needs a source checkout of Aether Quant (git clone https://github.com/leon1706-lol/Aether-quant)", file=sys.stderr)
105 return EXIT_FAIL
108def color(text: str, code: str) -> str:
109 """ANSI colour unless NO_COLOR is set or stdout is not a terminal."""
110 if os.environ.get("NO_COLOR") or not sys.stdout.isatty():
111 return text
112 return f"\x1b[{code}m{text}\x1b[0m"
115def _epilog(*examples: str) -> str:
116 return "Examples:\n" + "\n".join(f" {example}" for example in examples)
119def _parser(subparsers, name: str, help_text: str, *examples: str) -> argparse.ArgumentParser:
120 return subparsers.add_parser(name, help=help_text.replace("%", "%%"), description=help_text, epilog=_epilog(*examples), formatter_class=argparse.RawDescriptionHelpFormatter)
123def installed_version() -> str:
124 try:
125 return _package_version(PACKAGE_NAME)
126 except PackageNotFoundError:
127 return "unknown"
130# ---------------------------------------------------------------------------
131# hooks: the pre-commit gate and its coverage switch
132# ---------------------------------------------------------------------------
135def git_path(name: str, root: Path = ROOT_DIR) -> Path:
136 """`git rev-parse --git-path NAME`, resolved against `root`."""
137 code, out = run_capture(["git", "rev-parse", "--git-path", name], cwd=root)
138 if code != 0 or not out.strip():
139 return root / ".git" / name
140 path = Path(out.strip().splitlines()[-1])
141 return path if path.is_absolute() else root / path
144def coverage_state(marker: Path) -> str:
145 """'on', 'off' (persistent) or 'once' (the next commit only)."""
146 if not marker.exists():
147 return "on"
148 content = marker.read_text(encoding="utf-8").strip()
149 return "once" if content == "once" else "off"
152def set_coverage(marker: Path, state: str) -> str:
153 """Write or remove the marker the pre-commit hook reads; returns the new state."""
154 if state == "on":
155 marker.unlink(missing_ok=True)
156 return "on"
157 marker.parent.mkdir(parents=True, exist_ok=True)
158 marker.write_text("once" if state == "once" else "persistent", encoding="utf-8", newline="\n")
159 return coverage_state(marker)
162HOOK_GATES = ("secrets-check", "library gate", "formal inventory", "scorecard pins", "ruff (staged .py)", "coverage of changed modules")
165def hooks_status(root: Path = ROOT_DIR) -> dict:
166 sys.path.insert(0, str(root / "scripts"))
167 try:
168 import install_hooks
169 finally:
170 sys.path.pop(0)
171 coverage_json = root / "coverage-report" / "coverage.json"
172 return {
173 "installed": install_hooks.installed(root),
174 "gates": list(HOOK_GATES),
175 "coverage": coverage_state(git_path(COVERAGE_MARKER, root)),
176 "coverage_json_age_hours": round((time.time() - coverage_json.stat().st_mtime) / 3600, 1) if coverage_json.exists() else None,
177 }
180def _render_hooks_status(status: dict) -> str:
181 age = status["coverage_json_age_hours"]
182 return "\n".join([
183 f"pre-commit wrapper: {'installed' if status['installed'] else 'NOT installed (aq hooks install)'}",
184 f"gates: {', '.join(status['gates'])}",
185 f"coverage gate: {status['coverage']}" + ("" if status["coverage"] == "on" else " (turn on: aq hooks coverage on)"),
186 f"coverage-report/coverage.json: {'missing' if age is None else f'{age} h old'}",
187 ])
190def cmd_hooks(args: argparse.Namespace) -> int:
191 if (missing := needs_checkout()) is not None:
192 return missing
193 if args.hooks_command == "install":
194 if args.dry_run:
195 print("would install .git/hooks/pre-commit (a wrapper that runs .githooks/pre-commit)")
196 return EXIT_OK
197 sys.path.insert(0, str(ROOT_DIR / "scripts"))
198 try:
199 import install_hooks
200 finally:
201 sys.path.pop(0)
202 print(install_hooks.install(ROOT_DIR))
203 return EXIT_OK if install_hooks.installed(ROOT_DIR) else EXIT_FAIL
204 if args.hooks_command == "status":
205 emit(hooks_status(), args.json, _render_hooks_status)
206 return EXIT_OK
207 marker = git_path(COVERAGE_MARKER)
208 action = args.coverage_action
209 if action == "status":
210 emit({"coverage": coverage_state(marker)}, args.json, lambda data: f"coverage gate: {data['coverage']}")
211 return EXIT_OK
212 target = "on" if action == "on" else ("once" if args.once else "off")
213 if args.dry_run:
214 print(f"coverage gate: {coverage_state(marker)} -> {target} (dry run)")
215 return EXIT_OK
216 state = set_coverage(marker, target)
217 print(f"coverage gate: {state}")
218 if state != "on":
219 print("warning: CI's python-tests still enforces 100% coverage; run `aq test --coverage` before pushing", file=sys.stderr)
220 return EXIT_OK
223def cmd_commit(args: argparse.Namespace) -> int:
224 """`git commit` with the coverage gate skipped for this one commit when asked; the other gates still run."""
225 command = ["git", "commit", "-m", args.message, *(["-a"] if args.all else []), *(args.git_args or [])]
226 env = {**os.environ}
227 if args.skip_coverage:
228 env["AQ_SKIP_COVERAGE_HOOK"] = "1"
229 print("coverage gate skipped for this commit; run `aq test --coverage` before pushing", file=sys.stderr)
230 if args.dry_run:
231 print(("AQ_SKIP_COVERAGE_HOOK=1 " if args.skip_coverage else "") + " ".join(command))
232 return EXIT_OK
233 return run_live(command, env=env)
236def cmd_check(args: argparse.Namespace) -> int:
237 """Run exactly the pre-commit hook, committing nothing."""
238 if (missing := needs_checkout()) is not None:
239 return missing
240 env = {**os.environ, **({"AQ_SKIP_COVERAGE_HOOK": "1"} if args.no_coverage else {})}
241 sh = shutil.which("sh") or shutil.which("bash")
242 if sh is None:
243 print("aq check: no sh found (Git for Windows ships one)", file=sys.stderr)
244 return EXIT_FAIL
245 return run_live([sh, str(ROOT_DIR / ".githooks" / "pre-commit")], env=env)
248# ---------------------------------------------------------------------------
249# doctor
250# ---------------------------------------------------------------------------
253def _check(name: str, status: str, detail: str, fix: str = "") -> dict:
254 return {"name": name, "status": status, "detail": detail, "fix": fix}
257def _total_ram_gb() -> float | None:
258 try:
259 import psutil
261 return psutil.virtual_memory().total / 1e9
262 except ImportError:
263 pass
264 if sys.platform == "win32":
265 import ctypes
267 class _Status(ctypes.Structure):
268 _fields_ = [("length", ctypes.c_ulong), ("load", ctypes.c_ulong), ("total", ctypes.c_ulonglong), ("avail", ctypes.c_ulonglong),
269 ("total_page", ctypes.c_ulonglong), ("avail_page", ctypes.c_ulonglong), ("total_virtual", ctypes.c_ulonglong),
270 ("avail_virtual", ctypes.c_ulonglong), ("avail_extended", ctypes.c_ulonglong)]
272 status = _Status()
273 status.length = ctypes.sizeof(_Status)
274 ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(status))
275 return status.total / 1e9
276 try:
277 return os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") / 1e9
278 except (ValueError, OSError, AttributeError):
279 return None
282def _tcp_open(host: str, port: int, timeout: float = 1.0) -> bool:
283 import socket
285 try:
286 with socket.create_connection((host, port), timeout=timeout):
287 return True
288 except OSError:
289 return False
292DOCTOR_PROBES: dict[str, Callable[..., Any]] = {
293 "which": shutil.which,
294 "ram_gb": _total_ram_gb,
295 "disk_free_gb": lambda root: shutil.disk_usage(root).free / 1e9,
296 "tcp_open": _tcp_open,
297 "run": run_capture,
298}
301def _editable_check(root: Path) -> dict:
302 import importlib.util
304 text = (root / "pyproject.toml").read_text(encoding="utf-8") if (root / "pyproject.toml").exists() else ""
305 match = re.search(r"^py-modules = \[(.*?)\]", text, re.MULTILINE)
306 modules = re.findall(r'"([^"]+)"', match.group(1)) if match else []
307 missing = [name for name in modules if importlib.util.find_spec(name) is None]
308 if missing:
309 return _check("editable install", "fail", f"not importable: {', '.join(missing)}", "pip install -e .")
310 spec = importlib.util.find_spec("aq_cli")
311 origin = Path(spec.origin).resolve().parent if spec and spec.origin else None
312 if origin is not None and origin != root.resolve():
313 return _check("editable install", "warn", f"aq_cli loads from {origin}, not this checkout", "pip install -e .")
314 return _check("editable install", "ok", f"{len(modules)} top-level modules import from this checkout")
317def doctor_checks(root: Path = ROOT_DIR, probes: Mapping[str, Callable[..., Any]] = DOCTOR_PROBES) -> list[dict]:
318 """Every environment check, each {name, status: ok|warn|fail|skip, detail, fix}."""
319 which = probes["which"]
320 checks: list[dict] = []
321 version = sys.version_info
322 if version < (3, 10):
323 checks.append(_check("python", "fail", platform.python_version(), "install Python 3.10 or newer"))
324 elif version < (3, 11):
325 checks.append(_check("python", "warn", f"{platform.python_version()}: pipeline files and some tools need 3.11", "use Python 3.11+"))
326 else:
327 checks.append(_check("python", "ok", platform.python_version()))
328 checkout = source_checkout(root)
329 checks.append(_editable_check(root) if checkout else _check("editable install", "skip", "a wheel install"))
330 checks.append(_check("aq on PATH", "ok" if which("aq") else "warn", which("aq") or "not found", "pip install -e . (or add the Scripts folder to PATH)"))
331 if checkout:
332 state = hooks_status(root)
333 checks.append(_check("pre-commit hook", "ok" if state["installed"] else "warn", "installed" if state["installed"] else "not installed", "aq hooks install"))
334 checks.append(_check("coverage gate", "ok" if state["coverage"] == "on" else "warn", state["coverage"], "aq hooks coverage on"))
335 for tool, fix, level in (("git", "install git", "fail"), ("gh", "install the GitHub CLI and run gh auth login", "warn"), ("uv", "pip install uv", "warn"),
336 ("docker", "install Docker Desktop (Lean backtests, the dashboard image)", "warn"), ("node", "install Node.js (webui)", "warn")):
337 found = which(tool)
338 checks.append(_check(tool, "ok" if found else level, found or "not found", fix))
339 if which("gh"):
340 code, _ = probes["run"](["gh", "auth", "status"])
341 checks.append(_check("gh auth", "ok" if code == 0 else "warn", "logged in" if code == 0 else "not logged in", "gh auth login"))
342 if which("docker"):
343 code, _ = probes["run"](["docker", "info", "--format", "{{.ServerVersion}}"], timeout=20)
344 checks.append(_check("docker daemon", "ok" if code == 0 else "warn", "running" if code == 0 else "not running", "start Docker Desktop"))
345 if checkout and (root / "formal").is_dir():
346 checks.append(_check("elan (Lean 4)", "ok" if which("lake") else "skip", which("lake") or "not installed: only `aq prove` needs it"))
347 for name, port in (("redis", 6379), ("postgres", 5432)):
348 up = probes["tcp_open"]("127.0.0.1", port)
349 checks.append(_check(name, "ok" if up else "warn", f"localhost:{port} {'open' if up else 'closed'}", "aq docker up (optional: everything degrades without it)"))
350 ram = probes["ram_gb"]()
351 if ram is None:
352 checks.append(_check("RAM", "skip", "unknown"))
353 elif ram < 8:
354 checks.append(_check("RAM", "warn", f"{ram:.1f} GB", "train with --memory-profile low; never aq test --parallel"))
355 else:
356 checks.append(_check("RAM", "ok", f"{ram:.1f} GB"))
357 free = probes["disk_free_gb"](root)
358 checks.append(_check("disk", "ok" if free >= 10 else "warn", f"{free:.0f} GB free", "free space: aq clean ml / coverage / caches"))
359 pins = root / "ml" / "artifact_pins.json"
360 if pins.exists():
361 from retraining.artifact_pins import artifact_problems
363 problems = artifact_problems(root / "ml", pins)
364 checks.append(_check("model pins", "ok" if not problems else "fail", "ml/ matches its sha256 pins" if not problems else "; ".join(problems[:3]), "restore ml/ from the vault or rerun the install"))
365 else:
366 checks.append(_check("model pins", "skip", "no ml/ (the project's models are private)"))
367 config = root / "config.json"
368 if config.exists():
369 try:
370 json.loads(config.read_text(encoding="utf-8"))
371 checks.append(_check("config.json", "ok", "parses"))
372 except ValueError as error:
373 checks.append(_check("config.json", "fail", str(error), "fix the JSON"))
374 return checks
377_STATUS_MARK = {"ok": "ok ", "warn": "WARN", "fail": "FAIL", "skip": "skip"}
378_STATUS_COLOR = {"ok": "32", "warn": "33", "fail": "31", "skip": "90"}
381def render_checks(checks: Sequence[dict]) -> str:
382 lines = []
383 for check in checks:
384 mark = color(_STATUS_MARK[check["status"]], _STATUS_COLOR[check["status"]])
385 fix = f" -> {check['fix']}" if check["status"] in {"warn", "fail"} and check["fix"] else ""
386 lines.append(f"[{mark}] {check['name']}: {check['detail']}{fix}")
387 counts = {status: sum(1 for check in checks if check["status"] == status) for status in _STATUS_MARK}
388 lines.append(f"{counts['ok']} ok, {counts['warn']} warnings, {counts['fail']} failures, {counts['skip']} skipped")
389 return "\n".join(lines)
392def cmd_doctor(args: argparse.Namespace) -> int:
393 checks = doctor_checks()
394 emit(checks, args.json, render_checks)
395 return EXIT_FAIL if any(check["status"] == "fail" for check in checks) else EXIT_OK
398# ---------------------------------------------------------------------------
399# version, completion, help
400# ---------------------------------------------------------------------------
403def version_info(root: Path = ROOT_DIR) -> dict:
404 info = {"aether_quant": installed_version(), "python": platform.python_version(), "platform": platform.platform(), "source_checkout": source_checkout(root)}
405 if info["source_checkout"]:
406 code, sha = run_capture(["git", "rev-parse", "--short", "HEAD"], cwd=root)
407 _, dirty = run_capture(["git", "status", "--porcelain", "--untracked-files=no"], cwd=root)
408 info["git"] = sha.strip() if code == 0 else None
409 info["dirty"] = bool(dirty.strip()) if code == 0 else None
410 return info
413def _render_version(info: dict) -> str:
414 text = f"aq {info['aether_quant']} (python {info['python']}, {info['platform']})"
415 if info.get("git"):
416 text += f"\nsource checkout at {info['git']}{' with uncommitted changes' if info.get('dirty') else ''}"
417 elif not info["source_checkout"]:
418 text += "\nwheel install"
419 return text
422def cmd_version(args: argparse.Namespace) -> int:
423 emit(version_info(), args.json, _render_version)
424 return EXIT_OK
427def _subparsers_of(parser: argparse.ArgumentParser) -> dict[str, argparse.ArgumentParser]:
428 for action in parser._actions:
429 if isinstance(action, argparse._SubParsersAction):
430 return dict(action.choices)
431 return {}
434def walk_commands(parser: argparse.ArgumentParser, prefix: tuple[str, ...] = ()) -> list[tuple[tuple[str, ...], argparse.ArgumentParser]]:
435 """Every (command path, parser) pair under `parser`, depth first; the root is the empty path."""
436 found = [(prefix, parser)]
437 for name, child in _subparsers_of(parser).items():
438 found += walk_commands(child, (*prefix, name))
439 return found
442def _options(parser: argparse.ArgumentParser) -> list[str]:
443 return sorted({option for action in parser._actions for option in action.option_strings if option.startswith("--")})
446def completion_script(parser: argparse.ArgumentParser, shell: str) -> str:
447 """A static completion script for `shell` built from the parser tree: subcommand names, then each command's flags."""
448 table = {" ".join(path): (sorted(_subparsers_of(sub)), _options(sub)) for path, sub in walk_commands(parser)}
449 if shell == "powershell":
450 entries = "\n".join(f" '{key}' = @({', '.join(repr(word) for word in [*subs, *opts])})" for key, (subs, opts) in sorted(table.items()))
451 return f"""# aq completion for PowerShell: aq completion powershell >> $PROFILE
452$aqWords = @{{
453{entries}
454}}
455Register-ArgumentCompleter -Native -CommandName aq -ScriptBlock {{
456 param($wordToComplete, $commandAst, $cursorPosition)
457 $parts = @($commandAst.CommandElements | Select-Object -Skip 1 | ForEach-Object {{ $_.ToString() }} | Where-Object {{ $_ -notlike '-*' -and $_ -ne $wordToComplete }})
458 $key = ($parts -join ' ')
459 while ($key -ne '' -and -not $aqWords.ContainsKey($key)) {{ $key = ($key -replace ' ?[^ ]+$', '') }}
460 $aqWords[$key] | Where-Object {{ $_ -like "$wordToComplete*" }} | ForEach-Object {{ [System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_) }}
461}}
462"""
463 cases = "\n".join(f' "{key}") words="{" ".join([*subs, *opts])}" ;;' for key, (subs, opts) in sorted(table.items()))
464 body = f"""_aq_complete() {{
465 local cur key words i
466 cur="${{COMP_WORDS[COMP_CWORD]}}"
467 key=""
468 for ((i=1; i<COMP_CWORD; i++)); do
469 case "${{COMP_WORDS[i]}}" in -*) ;; *) key="${{key:+$key }}${{COMP_WORDS[i]}}" ;; esac
470 done
471 while :; do
472 case "$key" in
473{cases}
474 *) key="${{key% *}}"; [ "$key" = "${{key% *}}" ] && [ -z "${{key##* *}}" ] && key=""; continue ;;
475 esac
476 break
477 done
478 COMPREPLY=($(compgen -W "$words" -- "$cur"))
479}}
480complete -F _aq_complete aq
481"""
482 if shell == "zsh":
483 return "# aq completion for zsh: aq completion zsh >> ~/.zshrc\nautoload -U +X bashcompinit && bashcompinit\n" + body
484 return "# aq completion for bash: aq completion bash >> ~/.bashrc\n" + body
487def cmd_completion(args: argparse.Namespace) -> int:
488 from aq_cli import build_parser
490 print(completion_script(build_parser(), args.shell))
491 return EXIT_OK
494def cmd_help(args: argparse.Namespace) -> int:
495 from aq_cli import build_parser
497 parser = build_parser()
498 target = parser
499 for word in args.topic or []:
500 children = _subparsers_of(target)
501 if word not in children:
502 close = difflib.get_close_matches(word, list(children), n=3)
503 print(f"aq help: no command {word!r}" + (f"; did you mean: {', '.join(close)}?" if close else ""), file=sys.stderr)
504 return EXIT_USAGE
505 target = children[word]
506 target.print_help()
507 return EXIT_OK
510# ---------------------------------------------------------------------------
511# status
512# ---------------------------------------------------------------------------
515def _todo_objective(root: Path) -> str | None:
516 todo = root / "todo.md"
517 if not todo.exists():
518 return None
519 match = re.search(r"^# Current objective:\s*(.+)$", todo.read_text(encoding="utf-8"), re.MULTILINE)
520 return match.group(1).strip() if match else None
523def status_report(root: Path = ROOT_DIR, *, online: bool = True) -> dict:
524 """Branch, sync, dirty files, last commit, hook and coverage state, CI of HEAD, Dependabot PRs, Codespaces, the objective."""
525 report: dict[str, Any] = {"objective": _todo_objective(root)}
526 code, branch = run_capture(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
527 if code != 0:
528 report["git"] = None
529 return report
530 _, porcelain = run_capture(["git", "status", "--porcelain"], cwd=root)
531 _, last = run_capture(["git", "log", "-1", "--format=%h %s (%cr)"], cwd=root)
532 sync_code, sync = run_capture(["git", "rev-list", "--left-right", "--count", "@{upstream}...HEAD"], cwd=root)
533 behind, ahead = (sync.split() + ["?", "?"])[:2] if sync_code == 0 else ("?", "?")
534 report["git"] = {"branch": branch.strip(), "dirty": len([line for line in porcelain.splitlines() if line.strip()]), "last_commit": last.strip(), "ahead": ahead, "behind": behind}
535 if source_checkout(root):
536 hooks = hooks_status(root)
537 report["hooks"] = {"installed": hooks["installed"], "coverage": hooks["coverage"], "coverage_json_age_hours": hooks["coverage_json_age_hours"]}
538 if online and shutil.which("gh"):
539 _, sha = run_capture(["git", "rev-parse", "HEAD"], cwd=root)
540 runs = ci_runs(sha.strip())
541 report["ci"] = summarize_runs(runs) if runs is not None else "unknown"
542 report["dependabot_prs"] = len(dependabot_prs() or [])
543 spaces = codespaces()
544 report["codespaces_running"] = [space["name"] for space in spaces or [] if space.get("state") == "Available"]
545 return report
548def _render_status(report: dict) -> str:
549 lines = []
550 if report.get("objective"):
551 lines.append(f"objective: {report['objective']}")
552 git = report.get("git")
553 if git is None:
554 lines.append("git: not a git checkout")
555 return "\n".join(lines)
556 lines.append(f"branch {git['branch']} (ahead {git['ahead']}, behind {git['behind']}), {git['dirty']} changed file(s); last: {git['last_commit']}")
557 if "hooks" in report:
558 hooks = report["hooks"]
559 age = hooks["coverage_json_age_hours"]
560 lines.append(f"hook {'installed' if hooks['installed'] else 'NOT installed'}, coverage gate {hooks['coverage']}, coverage.json {'missing' if age is None else f'{age} h old'}")
561 if "ci" in report:
562 ci = report["ci"]
563 lines.append("CI of HEAD: unknown" if ci == "unknown" else f"CI of HEAD: {ci['verdict']} ({', '.join(ci['failed']) or 'no failures'}{', running: ' + ', '.join(ci['running']) if ci['running'] else ''})")
564 lines.append(f"open Dependabot PRs: {report['dependabot_prs']}")
565 running = report["codespaces_running"]
566 lines.append(color(f"Codespaces RUNNING (billing): {', '.join(running)}", "31") if running else "Codespaces: none running")
567 return "\n".join(lines)
570def cmd_status(args: argparse.Namespace) -> int:
571 if args.git:
572 return run_live(["git", "status"])
573 emit(status_report(online=not args.offline), args.json, _render_status)
574 return EXIT_OK
577# ---------------------------------------------------------------------------
578# CI (gh)
579# ---------------------------------------------------------------------------
582def _gh_json(command: Sequence[str]) -> Any:
583 code, out = run_capture(["gh", *command], timeout=60)
584 if code != 0:
585 return None
586 try:
587 return json.loads(out)
588 except ValueError:
589 return None
592def ci_runs(sha: str) -> list[dict] | None:
593 """Every workflow run of commit `sha`, each with its jobs."""
594 runs = _gh_json(["run", "list", "--commit", sha, "--limit", "50", "--json", "databaseId,workflowName,status,conclusion,event"])
595 if runs is None:
596 return None
597 for run in runs:
598 run["jobs"] = (_gh_json(["run", "view", str(run["databaseId"]), "--json", "jobs"]) or {}).get("jobs", [])
599 return runs
602def summarize_runs(runs: Sequence[dict]) -> dict:
603 """{verdict: green|red|running|none, failed: [workflow / job], running: [workflow]}."""
604 failed, running = [], []
605 for run in runs:
606 if run.get("status") != "completed":
607 running.append(run.get("workflowName", "?"))
608 bad_jobs = [job.get("name", "?") for job in run.get("jobs", []) if job.get("conclusion") in {"failure", "timed_out", "cancelled"}]
609 if run.get("conclusion") in {"failure", "timed_out", "startup_failure"} or bad_jobs:
610 failed += [f"{run.get('workflowName', '?')} / {job}" for job in bad_jobs] or [run.get("workflowName", "?")]
611 verdict = "none" if not runs else "red" if failed else "running" if running else "green"
612 return {"verdict": verdict, "failed": failed, "running": running, "runs": len(runs)}
615LOG_PATTERN = re.compile(r"FAILED|Error|error:|AssertionError|Missing|fail_under|fail-under|requires !2|Traceback|ERESOLVE|##\[error\]")
616_LOG_STAMP = re.compile(r"^\S+Z\s")
619def filter_log(text: str, *, before: int = 3, cap: int = 80) -> list[str]:
620 """The lines of a job log that explain a failure, each with up to `before` lines of context, at most `cap` lines."""
621 lines = [_LOG_STAMP.sub("", line) for line in text.splitlines()]
622 keep: list[int] = []
623 for index, line in enumerate(lines):
624 if LOG_PATTERN.search(line):
625 keep.extend(range(max(0, index - before), index + 1))
626 out, seen = [], set()
627 for index in keep:
628 if index not in seen:
629 seen.add(index)
630 out.append(lines[index])
631 return out[-cap:]
634def _repo_slug() -> str | None:
635 data = _gh_json(["repo", "view", "--json", "nameWithOwner"])
636 return data.get("nameWithOwner") if isinstance(data, dict) else None
639def cmd_ci(args: argparse.Namespace) -> int:
640 if args.ci_command == "local":
641 return cmd_ci_local(args)
642 if not shutil.which("gh"):
643 print("aq ci: needs the GitHub CLI (gh) logged in: https://cli.github.com", file=sys.stderr)
644 return EXIT_FAIL
645 if args.ci_command == "logs":
646 slug = _repo_slug()
647 view = _gh_json(["run", "view", args.run_id, "--json", "jobs"])
648 if slug is None or view is None:
649 print(f"aq ci logs: run {args.run_id} not found", file=sys.stderr)
650 return EXIT_FAIL
651 jobs = [job for job in view.get("jobs", []) if (args.job and args.job in job.get("name", "")) or (not args.job and job.get("conclusion") == "failure")]
652 lines = {}
653 for job in jobs:
654 _, log = run_capture(["gh", "api", f"repos/{slug}/actions/jobs/{job['databaseId']}/logs"], timeout=120)
655 lines[job.get("name")] = filter_log(log, cap=args.lines)
656 none = "no failed job" + (f" matching {args.job!r}" if args.job else "")
657 emit(lines, getattr(args, "json", False),
658 lambda data: "\n".join(f"=== {name}\n" + ("\n".join(rows) or "(no failure lines found)") for name, rows in data.items()) or none)
659 return EXIT_OK
660 ref = args.sha
661 if args.branch:
662 code, out = run_capture(["git", "rev-parse", f"origin/{args.branch}"])
663 ref = out.strip() if code == 0 else args.branch
664 code, sha = run_capture(["git", "rev-parse", ref])
665 sha = sha.strip() if code == 0 else ref
666 while True:
667 runs = ci_runs(sha)
668 if runs is None:
669 print("aq ci status: gh could not list runs (gh auth status?)", file=sys.stderr)
670 return EXIT_FAIL
671 summary = summarize_runs(runs)
672 if not args.watch or summary["verdict"] != "running":
673 break
674 print(f"{sha[:8]}: {len(summary['running'])} workflow(s) running ({', '.join(summary['running'])}); next check in {args.interval}s", flush=True)
675 time.sleep(args.interval)
676 summary["sha"] = sha
678 def render(data: dict) -> str:
679 head = {"green": color("green", "32"), "red": color("red", "31"), "running": color("running", "33"), "none": "no runs"}[data["verdict"]]
680 lines = [f"{data['sha'][:8]}: {head} ({data['runs']} workflow run(s))"]
681 lines += [f" failed: {item}" for item in data["failed"]]
682 lines += [f" running: {item}" for item in data["running"]]
683 if data["failed"]:
684 lines.append(" details: aq ci logs <run-id> (gh run list --commit " + data["sha"][:8] + ")")
685 return "\n".join(lines)
687 emit(summary, args.json, render)
688 return {"green": EXIT_OK, "none": EXIT_OK, "red": EXIT_FAIL, "running": EXIT_GATE}[summary["verdict"]]
691def ci_job_steps(workflow: Mapping[str, Any], job: str, matrix: Mapping[str, str] | None = None) -> list[dict]:
692 """The steps of `job`: {name, run|uses, env}. `${{ matrix.KEY }}` is filled from `matrix` (default: each key's first value)."""
693 spec = workflow.get("jobs", {}).get(job)
694 if spec is None:
695 raise KeyError(job)
696 values = {key: (value[0] if isinstance(value, list) and value else value) for key, value in (spec.get("strategy", {}).get("matrix") or {}).items() if key not in {"include", "exclude"}}
697 values.update(matrix or {})
698 job_env = {key: str(value) for key, value in (spec.get("env") or {}).items()}
700 def fill(text: str) -> str:
701 return re.sub(r"\$\{\{\s*matrix\.([\w-]+)\s*\}\}", lambda match: str(values.get(match.group(1), match.group(0))), text)
703 steps = []
704 for index, step in enumerate(spec.get("steps", [])):
705 entry = {"name": step.get("name") or step.get("uses") or f"step {index + 1}", "env": {**job_env, **{key: fill(str(value)) for key, value in (step.get("env") or {}).items()}}}
706 if "run" in step:
707 entry["run"] = fill(step["run"])
708 else:
709 entry["uses"] = step.get("uses", "")
710 steps.append(entry)
711 return steps
714def ci_job_needs(workflow: Mapping[str, Any]) -> dict[str, list[str]]:
715 """{job: what it needs that a PC may lack: docker, services, matrix}."""
716 out = {}
717 for name, spec in workflow.get("jobs", {}).items():
718 needs = []
719 text = json.dumps(spec)
720 if "docker" in text.lower():
721 needs.append("docker")
722 if spec.get("services"):
723 needs.append("services")
724 if spec.get("strategy", {}).get("matrix"):
725 needs.append("matrix")
726 out[name] = needs
727 return out
730def cmd_ci_local(args: argparse.Namespace) -> int:
731 if (missing := needs_checkout()) is not None:
732 return missing
733 import yaml
735 workflow = yaml.safe_load((ROOT_DIR / ".github" / "workflows" / args.workflow).read_text(encoding="utf-8"))
736 if args.list or not args.job:
737 for name, needs in ci_job_needs(workflow).items():
738 print(f"{name}" + (f" (needs: {', '.join(needs)})" if needs else ""))
739 return EXIT_OK
740 matrix = dict(item.split("=", 1) for item in args.matrix or [])
741 try:
742 steps = ci_job_steps(workflow, args.job, matrix)
743 except KeyError:
744 close = difflib.get_close_matches(args.job, list(workflow.get("jobs", {})), n=3)
745 print(f"aq ci local: no job {args.job!r} in {args.workflow}" + (f"; did you mean: {', '.join(close)}?" if close else ""), file=sys.stderr)
746 return EXIT_USAGE
747 bash = shutil.which("bash")
748 for step in steps:
749 if "uses" in step:
750 print(f"-- skipped: {step['name']} ({step['uses']})")
751 continue
752 print(f"-- {step['name']}", flush=True)
753 if args.dry_run:
754 print(step["run"])
755 continue
756 if bash is None:
757 print("aq ci local: bash not found (Git for Windows ships one)", file=sys.stderr)
758 return EXIT_FAIL
759 code = run_live([bash, "-e", "-c", step["run"]], env={**os.environ, **step["env"]})
760 if code != 0:
761 print(f"aq ci local: step {step['name']!r} failed (exit {code})", file=sys.stderr)
762 return code
763 return EXIT_OK
766# ---------------------------------------------------------------------------
767# dependencies
768# ---------------------------------------------------------------------------
770_TITLE_RE = re.compile(r"^(?:Bump|Update) (?P<pkg>\S+)(?: requirement)? from (?P<old>\S+) to (?P<new>\S+)(?: in (?P<dir>\S+))?$")
773def parse_dependabot_title(title: str) -> dict | None:
774 """{package, old, new, directory, ecosystem, major} from a Dependabot PR title, or None for a grouped/other title."""
775 match = _TITLE_RE.match(title.strip())
776 if not match:
777 return None
778 directory = match.group("dir") or "/"
779 ecosystem = "pip" if directory.startswith("/requirements") else "npm" if directory.startswith("/webui") else "github-actions"
781 def major(value: str) -> str:
782 return re.sub(r"^[^\d]*", "", value).split(".")[0]
784 return {"package": match.group("pkg"), "old": match.group("old"), "new": match.group("new"), "directory": directory, "ecosystem": ecosystem,
785 "major": major(match.group("old")) != major(match.group("new"))}
788def split_diff(diff: str) -> list[tuple[str, str]]:
789 """[(path, file diff text)] of a unified git diff."""
790 parts = re.split(r"(?m)^(?=diff --git )", diff)
791 out = []
792 for part in parts:
793 match = re.match(r"diff --git a/(\S+) b/(\S+)", part)
794 if match:
795 out.append((match.group(2), part))
796 return out
799def without_lock_files(diff: str) -> str:
800 """The diff without its `requirements/lock/*.txt` files, which only scripts/lock_requirements.py may write."""
801 return "".join(text for path, text in split_diff(diff) if not fnmatch.fnmatch(path, "requirements/lock/*.txt"))
804def lock_via(lock_text: str, package: str) -> list[str]:
805 """What pulls `package` into a uv lock file: the `# via` lines under its pin."""
806 lines = lock_text.splitlines()
807 name = package.lower().replace("_", "-")
808 for index, line in enumerate(lines):
809 if re.match(rf"^{re.escape(name)}==", line.strip().lower().replace("_", "-")):
810 via = []
811 for follow in lines[index + 1:]:
812 stripped = follow.strip()
813 if not stripped or (not follow.startswith(" ") and not stripped.startswith("#")):
814 break
815 if stripped.startswith("# via"):
816 first = stripped[len("# via"):].strip()
817 if first:
818 via.append(first)
819 elif stripped.startswith("#"):
820 via.append(stripped.lstrip("#").strip())
821 return via
822 return []
825def dependabot_prs() -> list[dict] | None:
826 prs = _gh_json(["pr", "list", "--author", "app/dependabot", "--state", "open", "--json", "number,title,headRefName,statusCheckRollup"])
827 if prs is None:
828 return None
829 for pr in prs:
830 pr["parsed"] = parse_dependabot_title(pr.get("title", ""))
831 checks = pr.get("statusCheckRollup") or []
832 pr["checks"] = "failing" if any(check.get("conclusion") == "FAILURE" for check in checks) else "pending" if any(check.get("status") not in {None, "COMPLETED"} for check in checks) else "passing"
833 return prs
836def _render_prs(prs: Sequence[dict]) -> str:
837 if not prs:
838 return "no open Dependabot PRs"
839 rows = []
840 for pr in prs:
841 parsed = pr["parsed"]
842 what = f"{parsed['ecosystem']:<15} {parsed['package']} {parsed['old']} -> {parsed['new']}{' (major)' if parsed['major'] else ''}" if parsed else pr["title"]
843 rows.append(f"#{pr['number']:<5} {pr['checks']:<8} {what}")
844 return "\n".join(rows)
847def cmd_deps(args: argparse.Namespace) -> int:
848 if (missing := needs_checkout()) is not None:
849 return missing
850 command = args.deps_command
851 if command == "lock":
852 return run_live([sys.executable, "scripts/lock_requirements.py", *[part for profile in args.profile or [] for part in ("--profile", profile)],
853 *[part for package in args.upgrade_package or [] for part in ("--upgrade-package", package)]])
854 if command == "pins":
855 return run_live([sys.executable, "scripts/scorecard_pins.py"])
856 if command == "audit":
857 if not shutil.which("pip-audit"):
858 print("aq deps audit: pip-audit not found: pip install --require-hashes -r requirements/lock/tools.txt", file=sys.stderr)
859 return EXIT_FAIL
860 worst = 0
861 for profile in ("runtime", "ci"):
862 worst = max(worst, run_live(["pip-audit", "--requirement", f"requirements/lock/{profile}.txt", "--require-hashes", "--disable-pip", "--desc"]))
863 return worst
864 if command == "why":
865 rows = {}
866 for lock in sorted((ROOT_DIR / "requirements" / "lock").glob("*.txt")):
867 if args.profile and lock.stem not in args.profile:
868 continue
869 via = lock_via(lock.read_text(encoding="utf-8"), args.package)
870 if via:
871 rows[lock.stem] = via
872 emit(rows, args.json, lambda data: "\n".join(f"{profile}: {', '.join(via)}" for profile, via in data.items()) or f"{args.package} is in no lock file")
873 return EXIT_OK if rows else EXIT_FAIL
874 if not shutil.which("gh"):
875 print("aq deps: needs the GitHub CLI (gh) logged in", file=sys.stderr)
876 return EXIT_FAIL
877 if command == "prs":
878 prs = dependabot_prs()
879 if prs is None:
880 print("aq deps prs: gh could not list pull requests", file=sys.stderr)
881 return EXIT_FAIL
882 emit(prs, args.json, _render_prs)
883 return EXIT_OK
884 worst = 0
885 for number in args.numbers:
886 worst = max(worst, apply_dependabot_pr(number, dry_run=args.dry_run))
887 if worst == 0 and not args.dry_run:
888 print("next: aq test --impacted, aq check, then aq commit -m '...'")
889 return worst
892def apply_dependabot_pr(number: str, *, dry_run: bool = False) -> int:
893 """Apply one Dependabot PR to the working tree the way the checks accept it."""
894 view = _gh_json(["pr", "view", str(number), "--json", "title"])
895 parsed = parse_dependabot_title(view.get("title", "")) if isinstance(view, dict) else None
896 if parsed is None:
897 print(f"aq deps apply: #{number} is not a single-package Dependabot PR", file=sys.stderr)
898 return EXIT_FAIL
899 if parsed["ecosystem"] == "npm":
900 command = ["npm", "install", f"{parsed['package']}@^{parsed['new']}"]
901 print(f"#{number}: (cd webui) {' '.join(command)}")
902 if dry_run:
903 return EXIT_OK
904 code = run_live(command, cwd=ROOT_DIR / "webui")
905 _, tree = run_capture(["npm", "ls", "--all"], cwd=ROOT_DIR / "webui", timeout=300)
906 if "invalid" in tree or "ERESOLVE" in tree:
907 print("warning: npm reports invalid peers: bump the paired packages too (e.g. vitest with @vitest/coverage-v8, react with react-dom)", file=sys.stderr)
908 return code
909 code, diff = run_capture(["gh", "pr", "diff", str(number)], timeout=120)
910 if code != 0:
911 print(f"aq deps apply: could not read #{number}'s diff", file=sys.stderr)
912 return EXIT_FAIL
913 patch = without_lock_files(diff) if parsed["ecosystem"] == "pip" else diff
914 print(f"#{number}: applying {len(split_diff(patch))} file(s) of {parsed['package']} {parsed['old']} -> {parsed['new']}")
915 if dry_run:
916 return EXIT_OK
917 if patch.strip():
918 result = RUN(["git", "apply", "-"], cwd=str(ROOT_DIR), input=patch, text=True, capture_output=True, check=False)
919 if result.returncode != 0:
920 print(f"aq deps apply: git apply failed: {result.stderr.strip()}", file=sys.stderr)
921 return EXIT_FAIL
922 if parsed["ecosystem"] == "pip":
923 return run_live([sys.executable, "scripts/lock_requirements.py", "--upgrade-package", parsed["package"]])
924 if parsed["package"].startswith("github/codeql-action/"):
925 print("warning: bump every github/codeql-action/* use to the same SHA (init, analyze, upload-sarif)", file=sys.stderr)
926 return EXIT_OK
929# ---------------------------------------------------------------------------
930# coverage
931# ---------------------------------------------------------------------------
934def coverage_summary(data: Mapping[str, Any], *, json_mtime: float | None = None, root: Path | None = None) -> dict:
935 """Total percent, files below 100% and whether a tracked .py changed after the report."""
936 root = root or ROOT_DIR
937 files = data.get("files") or {}
938 below = {name.replace("\\", "/"): report.get("summary", {}).get("percent_covered") for name, report in files.items() if report.get("missing_lines")}
939 stale = []
940 if json_mtime is not None:
941 stale = sorted(name.replace("\\", "/") for name in files if (root / name).exists() and (root / name).stat().st_mtime > json_mtime)
942 return {"percent": (data.get("totals") or {}).get("percent_covered"), "files": len(files), "below_100": below, "changed_since": stale}
945def cmd_coverage(args: argparse.Namespace) -> int:
946 report_path = ROOT_DIR / "coverage-report" / "coverage.json"
947 if args.coverage_command == "misses":
948 if (missing := needs_checkout()) is not None:
949 return missing
950 command = [sys.executable, "scripts/coverage_misses.py", *[part for pattern in args.include or [] for part in ("--include", pattern)]]
951 command += ["--by-function"] if args.by_function else []
952 command += ["--context", str(args.context)] if args.context is not None else []
953 return run_live(command)
954 if args.coverage_command == "clean":
955 return clean_paths(coverage_paths(ROOT_DIR), apply=args.apply, assume_yes=args.yes, as_json=args.json, root=ROOT_DIR)
956 if not report_path.exists():
957 print("no coverage-report/coverage.json yet: aq test --coverage", file=sys.stderr)
958 return EXIT_FAIL
959 summary = coverage_summary(json.loads(report_path.read_text(encoding="utf-8")), json_mtime=report_path.stat().st_mtime)
960 summary["age_hours"] = round((time.time() - report_path.stat().st_mtime) / 3600, 1)
962 def render(data: dict) -> str:
963 lines = [f"total {data['percent']:.2f}% over {data['files']} files, {data['age_hours']} h old"]
964 lines += [f" {name}: {percent:.1f}%" for name, percent in sorted(data["below_100"].items())]
965 if data["changed_since"]:
966 lines.append(f" {len(data['changed_since'])} file(s) changed since: rerun (aq test --coverage --changed)")
967 return "\n".join(lines)
969 emit(summary, args.json, render)
970 return EXIT_OK if not summary["below_100"] else EXIT_GATE
973# ---------------------------------------------------------------------------
974# cleaning (coverage, caches, build)
975# ---------------------------------------------------------------------------
977_NEVER_CLEAN = ("backtests", "ml", "data", ".git")
980def coverage_paths(root: Path) -> list[Path]:
981 return [path for path in [root / "coverage-report", *root.glob(".coverage*")] if path.exists()]
984def cache_paths(root: Path) -> list[Path]:
985 found = []
986 for name in (".pytest_cache", ".ruff_cache", ".hypothesis", ".mypy_cache"):
987 if (root / name).exists():
988 found.append(root / name)
989 for folder in ("aether_quant", "aq_devtools", "lab", "evaluation", "features", "portfolio", "risk", "execution", "retraining", "tests", "scripts", "inference",
990 "data_pipeline", "audit", "monitoring", "notifications", "performance", "regime", "topology", "liquidity", "moe", "experts", "experience", "analyzer"):
991 found += [path for path in (root / folder).rglob("__pycache__") if path.is_dir()] if (root / folder).is_dir() else []
992 if (root / "__pycache__").is_dir():
993 found.append(root / "__pycache__")
994 return found
997def build_paths(root: Path) -> list[Path]:
998 return [path for path in (root / "build", root / "dist") if path.exists()]
1001def _size(path: Path) -> int:
1002 if path.is_file():
1003 return path.stat().st_size
1004 return sum(item.stat().st_size for item in path.rglob("*") if item.is_file())
1007def clean_paths(paths: Sequence[Path], *, apply: bool, assume_yes: bool, as_json: bool, root: Path | None = None) -> int:
1008 root = root or ROOT_DIR
1009 safe = [path for path in paths if path.resolve().relative_to(root.resolve()).parts[:1] not in [(name,) for name in _NEVER_CLEAN]]
1010 rows = [{"path": str(path.relative_to(root)), "bytes": _size(path)} for path in safe]
1011 emit({"apply": apply, "items": rows, "bytes": sum(row["bytes"] for row in rows)}, as_json,
1012 lambda data: "\n".join([*(f"{row['path']} ({row['bytes'] / 1e6:.1f} MB)" for row in data["items"]),
1013 f"{'deleting' if apply else 'would delete (dry run; --apply deletes)'} {len(data['items'])} item(s), {data['bytes'] / 1e6:.1f} MB"]))
1014 if not apply or not safe:
1015 return EXIT_OK
1016 if not confirm(f"delete {len(safe)} item(s)?", assume_yes=assume_yes):
1017 return EXIT_USAGE
1018 for path in safe:
1019 if path.is_dir():
1020 shutil.rmtree(path, ignore_errors=True)
1021 else:
1022 path.unlink(missing_ok=True)
1023 return EXIT_OK
1026# ---------------------------------------------------------------------------
1027# Codespaces
1028# ---------------------------------------------------------------------------
1031def codespaces() -> list[dict] | None:
1032 return _gh_json(["codespace", "list", "--json", "name,displayName,state,lastUsedAt,repository"])
1035def cmd_codespace(args: argparse.Namespace) -> int:
1036 if not shutil.which("gh"):
1037 print("aq codespace: needs the GitHub CLI (gh) logged in", file=sys.stderr)
1038 return EXIT_FAIL
1039 spaces = codespaces()
1040 if spaces is None:
1041 print("aq codespace: gh could not list Codespaces (gh auth refresh -s codespace?)", file=sys.stderr)
1042 return EXIT_FAIL
1043 if args.codespace_command == "list":
1044 def render(data: list) -> str:
1045 if not data:
1046 return "no Codespaces"
1047 return "\n".join((color(f"{space['name']} {space['state']} (BILLING)", "31") if space.get("state") == "Available" else f"{space['name']} {space['state']}")
1048 + f" last used {space.get('lastUsedAt', '?')}" for space in data)
1050 emit(spaces, args.json, render)
1051 return EXIT_OK
1052 names = [space["name"] for space in spaces]
1053 if args.codespace_command == "stop":
1054 targets = [space["name"] for space in spaces if space.get("state") == "Available"] if args.all else [args.name] if args.name else []
1055 if not targets:
1056 print("nothing to stop" if args.all else "aq codespace stop: give NAME or --all", file=sys.stderr if not args.all else sys.stdout)
1057 return EXIT_OK if args.all else EXIT_USAGE
1058 worst = 0
1059 for name in targets:
1060 print(f"stopping {name}{' (dry run)' if args.dry_run else ''}")
1061 if not args.dry_run:
1062 worst = max(worst, run_live(["gh", "codespace", "stop", "-c", name]))
1063 return worst
1064 if args.name not in names:
1065 print(f"aq codespace delete: no Codespace {args.name!r}", file=sys.stderr)
1066 return EXIT_USAGE
1067 if args.dry_run:
1068 print(f"would delete {args.name}")
1069 return EXIT_OK
1070 if not confirm(f"delete Codespace {args.name} (its storage is gone for good)?", assume_yes=args.yes):
1071 return EXIT_USAGE
1072 return run_live(["gh", "codespace", "delete", "-c", args.name, "--force"])
1075# ---------------------------------------------------------------------------
1076# vault
1077# ---------------------------------------------------------------------------
1080def cmd_vault(args: argparse.Namespace) -> int:
1081 if (missing := needs_checkout()) is not None:
1082 return missing
1083 if args.vault_command == "record":
1084 command = [sys.executable, "scripts/vault_record.py", "--label", args.label, *[part for metric in args.metric or [] for part in ("--metric", metric)], *args.paths]
1085 if args.dry_run:
1086 print(" ".join(command))
1087 return EXIT_OK
1088 return run_live(command)
1089 vault = ROOT_DIR / "Aether-quant-Obsidian-Vault"
1090 if not vault.is_dir():
1091 print("aq vault graph: no Aether-quant-Obsidian-Vault/ in this checkout", file=sys.stderr)
1092 return EXIT_FAIL
1093 commands = [
1094 [sys.executable, "scripts/generate_code_graph.py", "--repo-root", "..", "--vault", "."],
1095 [sys.executable, "scripts/regenerate_vault.py", "--repo-root", "..", "--vault", ".", "--append-handoff", "--agent", args.agent, "--action", "completed",
1096 "--summary", args.summary, "--files", *args.files],
1097 ]
1098 for command in commands:
1099 print(" ".join(command))
1100 if not args.dry_run and (code := run_live(command, cwd=vault)) != 0:
1101 return code
1102 return EXIT_OK
1105# ---------------------------------------------------------------------------
1106# Problems.md
1107# ---------------------------------------------------------------------------
1109_PROBLEM_RE = re.compile(r"^### (\d+)([a-z]?)\. (.+?)\s*$", re.MULTILINE)
1112def parse_problems(text: str) -> list[dict]:
1113 """[{number, title, status, body}] from Problems.md's `### N. Title` entries."""
1114 matches = list(_PROBLEM_RE.finditer(text))
1115 out = []
1116 for index, match in enumerate(matches):
1117 end = matches[index + 1].start() if index + 1 < len(matches) else len(text)
1118 body = text[match.end():end].strip()
1119 first = body.splitlines()[0] if body else ""
1120 status = "fixed" if "🟢" in first else "partial" if "🟡" in first else "closed" if "🔴" in first else "unknown"
1121 out.append({"number": f"{match.group(1)}{match.group(2)}", "title": match.group(3), "status": status, "body": body})
1122 return out
1125def next_problem_number(problems: Sequence[dict]) -> int:
1126 return max((int(re.match(r"\d+", problem["number"]).group(0)) for problem in problems), default=0) + 1
1129PROBLEM_TEMPLATE = """### {number}. <Title> ({version})
1130🟢 `fixed` · N/10
1132**Problem:** <1-3 sentences>
1134**Fix:** <1-3 sentences>
1136**Verification:** <1-3 sentences>
1137"""
1140def cmd_problems(args: argparse.Namespace) -> int:
1141 path = ROOT_DIR / "development" / "Problems.md"
1142 if not path.exists():
1143 print("aq problems: no development/Problems.md (a source checkout has it)", file=sys.stderr)
1144 return EXIT_FAIL
1145 problems = parse_problems(path.read_text(encoding="utf-8"))
1146 if args.problems_command == "next":
1147 number = next_problem_number(problems)
1148 emit({"next": number}, args.json, lambda data: PROBLEM_TEMPLATE.format(number=data["next"], version="V?.?.?"))
1149 return EXIT_OK
1150 if args.problems_command == "show":
1151 found = next((problem for problem in problems if problem["number"] == str(args.number)), None)
1152 if found is None:
1153 print(f"aq problems show: no #{args.number}", file=sys.stderr)
1154 return EXIT_FAIL
1155 emit(found, args.json, lambda data: f"### {data['number']}. {data['title']}\n{data['body']}")
1156 return EXIT_OK
1157 open_items = [problem for problem in problems if problem["status"] == "partial"]
1158 emit([{key: problem[key] for key in ("number", "title", "status")} for problem in open_items], args.json,
1159 lambda data: "\n".join(f"#{item['number']} {item['title']}" for item in data) or "no partial (🟡) problems")
1160 return EXIT_OK
1163# ---------------------------------------------------------------------------
1164# lint
1165# ---------------------------------------------------------------------------
1168def cmd_lint(args: argparse.Namespace) -> int:
1169 ruff = shutil.which("ruff")
1170 command = [ruff] if ruff else [sys.executable, "-m", "ruff"]
1171 code = run_live([*command, "check", ".", *(["--fix"] if args.fix else [])])
1172 if args.types and code == 0:
1173 if (missing := needs_checkout()) is not None:
1174 return missing
1175 code = run_live([sys.executable, "scripts/type_completeness.py"])
1176 return code
1179# ---------------------------------------------------------------------------
1180# config / lean diff
1181# ---------------------------------------------------------------------------
1184def leaf_items(node: Any, prefix: str = "") -> dict[str, Any]:
1185 """{dotted.path: leaf value} of a JSON tree (lists are leaves)."""
1186 if isinstance(node, dict) and node:
1187 out: dict[str, Any] = {}
1188 for key, value in node.items():
1189 out.update(leaf_items(value, f"{prefix}.{key}" if prefix else str(key)))
1190 return out
1191 return {prefix: node}
1194def leaf_diff(old: Any, new: Any) -> dict[str, list]:
1195 """{added: [[path, value]], removed: [[path, value]], changed: [[path, old, new]]} between two JSON trees."""
1196 before, after = leaf_items(old), leaf_items(new)
1197 return {
1198 "added": [[path, after[path]] for path in sorted(after.keys() - before.keys())],
1199 "removed": [[path, before[path]] for path in sorted(before.keys() - after.keys())],
1200 "changed": [[path, before[path], after[path]] for path in sorted(before.keys() & after.keys()) if before[path] != after[path]],
1201 }
1204def render_leaf_diff(diff: Mapping[str, list]) -> str:
1205 lines = [f"+ {path} = {json.dumps(value)}" for path, value in diff["added"]]
1206 lines += [f"- {path} = {json.dumps(value)}" for path, value in diff["removed"]]
1207 lines += [f"~ {path}: {json.dumps(old)} -> {json.dumps(new)}" for path, old, new in diff["changed"]]
1208 return "\n".join(lines) or "no differences"
1211def json_file_diff(path: Path, ref: str, root: Path = ROOT_DIR) -> dict[str, list] | None:
1212 """`path` against its version at git `ref`; None when git has no such version."""
1213 code, old_text = run_capture(["git", "show", f"{ref}:{path.relative_to(root).as_posix()}"], cwd=root)
1214 if code != 0:
1215 return None
1216 return leaf_diff(json.loads(old_text), json.loads(path.read_text(encoding="utf-8")))
1219def cmd_json_diff(path: Path, args: argparse.Namespace) -> int:
1220 diff = json_file_diff(path, args.ref)
1221 if diff is None:
1222 print(f"aq: git has no {path.name} at {args.ref}", file=sys.stderr)
1223 return EXIT_FAIL
1224 emit(diff, args.json, render_leaf_diff)
1225 return EXIT_OK
1228# ---------------------------------------------------------------------------
1229# the CLI's own reference, and the docs' links
1230# ---------------------------------------------------------------------------
1233def render_cli_markdown(parser: argparse.ArgumentParser) -> str:
1234 """Every command and subcommand with its usage line, description and flags, as Markdown for docs/reference/cli.md."""
1235 out = []
1236 for path, sub in walk_commands(parser):
1237 if not path:
1238 continue
1239 depth = min(len(path) + 2, 5)
1240 out.append(f"{'#' * depth} `aq {' '.join(path)}`\n")
1241 summary = _md_text(sub.description or "")
1242 if summary:
1243 out.append(summary + "\n")
1244 usage = " ".join(sub.format_usage().split())
1245 out.append(f"```text\n{usage.removeprefix('usage: ')}\n```\n")
1246 rows = []
1247 for action in sub._actions:
1248 if isinstance(action, (argparse._HelpAction, argparse._SubParsersAction)) or action.help == argparse.SUPPRESS:
1249 continue
1250 name = ", ".join(f"`{option}`" for option in action.option_strings) or f"`{action.dest}`"
1251 text = _md_text((action.help or "").replace("%%", "%").replace("|", "\\|"))
1252 rows.append(f"| {name} | {text} |")
1253 if rows:
1254 out.append("| Flag | Meaning |\n|---|---|\n" + "\n".join(rows) + "\n")
1255 return "\n".join(out).rstrip() + "\n"
1258def _md_text(text: str) -> str:
1259 """One line of help as Markdown text: `<run>` stays visible instead of becoming an HTML tag."""
1260 return " ".join(text.replace("<", "<").replace(">", ">").split())
1263_LINK_RE = re.compile(r"(?<!!)\[[^\]]*\]\(([^)\s]+)(?:\s+\"[^\"]*\")?\)")
1266def markdown_anchors(text: str) -> set[str]:
1267 """GitHub-style anchors of every heading in `text`."""
1268 anchors = set()
1269 for heading in re.findall(r"^#{1,6}\s+(.+?)\s*#*$", text, re.MULTILINE):
1270 anchors.add(re.sub(r"[^\w\- ]", "", heading.strip().lower()).replace(" ", "-"))
1271 return anchors
1274def broken_links(paths: Iterable[Path], root: Path | None = None) -> list[str]:
1275 """`file: target` for every relative link whose file or anchor does not exist (external links are skipped)."""
1276 root = root or ROOT_DIR
1277 problems = []
1278 cache: dict[Path, set[str]] = {}
1279 for path in paths:
1280 text = path.read_text(encoding="utf-8")
1281 in_fence = False
1282 for line in text.splitlines():
1283 if line.lstrip().startswith("```"):
1284 in_fence = not in_fence
1285 continue
1286 if in_fence:
1287 continue
1288 for target in _LINK_RE.findall(re.sub(r"`[^`]*`", "", line)):
1289 if re.match(r"^[a-z][a-z0-9+.-]*:", target) or target.startswith("{{"):
1290 continue
1291 file_part, _, anchor = target.partition("#")
1292 resolved = (path.parent / file_part).resolve() if file_part else path.resolve()
1293 if file_part and not resolved.exists():
1294 problems.append(f"{path.relative_to(root).as_posix()}: {target}")
1295 continue
1296 if anchor and resolved.suffix == ".md":
1297 if resolved not in cache:
1298 cache[resolved] = markdown_anchors(resolved.read_text(encoding="utf-8"))
1299 if anchor.lower() not in cache[resolved]:
1300 problems.append(f"{path.relative_to(root).as_posix()}: {target} (no such heading)")
1301 return problems
1304def link_docs(root: Path | None = None) -> list[Path]:
1305 root = root or ROOT_DIR
1306 paths = [root / "README.md", *sorted((root / "docs").rglob("*.md")), *sorted((root / "development").glob("*.md"))]
1307 paths += sorted(path for path in root.glob("*/README.md") if path.parent.name not in {"node_modules", "Aether-quant-Obsidian-Vault", "build", "site"})
1308 return [path for path in paths if path.exists()]
1311def external_links(paths: Iterable[Path]) -> list[str]:
1312 found = set()
1313 for path in paths:
1314 found |= {target for target in _LINK_RE.findall(path.read_text(encoding="utf-8")) if target.startswith(("http://", "https://"))}
1315 return sorted(found)
1318def check_external(url: str, timeout: float = 5.0) -> bool:
1319 import urllib.request
1321 request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "aq-docs-links/1.0"})
1322 try:
1323 with urllib.request.urlopen(request, timeout=timeout) as response:
1324 return response.status < 400
1325 except Exception: # any network failure counts as a broken link, reported, never raised
1326 return False
1329def cmd_docs_extra(args: argparse.Namespace) -> int:
1330 command = args.docs_command
1331 if command in {"build", "serve"}:
1332 if not shutil.which("mkdocs"):
1333 print('aq docs: mkdocs not found: pip install --require-hashes -r requirements/lock/docs.txt', file=sys.stderr)
1334 return EXIT_FAIL
1335 if command == "build":
1336 if (code := run_live([sys.executable, "scripts/build_docs.py"])) != 0:
1337 return code
1338 return run_live(["mkdocs", "build", *(["--strict"] if args.strict else [])])
1339 return run_live(["mkdocs", "serve", "--dev-addr", f"127.0.0.1:{args.port}"])
1340 if command == "cli":
1341 from docs_facts import apply_blocks, cli_reference_block
1343 page = ROOT_DIR / "docs" / "reference" / "cli.md"
1344 text = page.read_text(encoding="utf-8") if page.exists() else ""
1345 updated, moved = apply_blocks(text, {"CLI_REFERENCE": cli_reference_block()})
1346 if args.check:
1347 print("docs/reference/cli.md is current" if not moved else "docs/reference/cli.md is stale: aq docs cli")
1348 return EXIT_FAIL if moved else EXIT_OK
1349 if moved:
1350 page.write_text(updated, encoding="utf-8", newline="\n")
1351 print("docs/reference/cli.md " + ("updated" if moved else "already current"))
1352 return EXIT_OK
1353 paths = link_docs()
1354 problems = broken_links(paths)
1355 if args.external:
1356 problems += [f"external: {url}" for url in external_links(paths) if not check_external(url)]
1357 emit(problems, args.json, lambda data: "\n".join(data) or f"{len(paths)} docs: every relative link resolves")
1358 return EXIT_FAIL if problems else EXIT_OK
1361# ---------------------------------------------------------------------------
1362# bug report
1363# ---------------------------------------------------------------------------
1366def bug_report(root: Path = ROOT_DIR) -> str:
1367 """A Markdown report for a GitHub issue: versions and the doctor's results, with the home folder replaced by ~."""
1368 home = str(Path.home())
1369 packages = {}
1370 for name in ("numpy", "pandas", "torch", "lean", "fastapi"):
1371 try:
1372 packages[name] = _package_version(name)
1373 except PackageNotFoundError:
1374 packages[name] = "not installed"
1375 lines = ["<!-- aq bug-report: versions and environment checks only; no config values, environment variables or user names -->",
1376 "## Environment", "", f"- aq: {installed_version()}", f"- Python: {platform.python_version()}", f"- OS: {platform.platform()}"]
1377 lines += [f"- {name}: {value}" for name, value in packages.items()]
1378 lines += ["", "## aq doctor", "", "```text", render_checks(doctor_checks(root)), "```", "", "## What happened", "", "<steps, expected, actual>"]
1379 text = "\n".join(lines)
1380 text = text.replace(home, "~").replace(home.replace("\\", "/"), "~")
1381 user = os.environ.get("USERNAME") or os.environ.get("USER")
1382 return text.replace(user, "<user>") if user and len(user) > 2 else text
1385def cmd_bug_report(args: argparse.Namespace) -> int:
1386 text = re.sub(r"\x1b\[[0-9;]*m", "", bug_report())
1387 if args.out:
1388 Path(args.out).write_text(text + "\n", encoding="utf-8")
1389 print(f"wrote {args.out}")
1390 else:
1391 print(text)
1392 return EXIT_OK
1395# ---------------------------------------------------------------------------
1396# examples and notebooks
1397# ---------------------------------------------------------------------------
1400def _docstring_line(path: Path) -> str:
1401 match = re.search(r'^\s*(?:"""|\'\'\')(.+?)$', path.read_text(encoding="utf-8"), re.MULTILINE)
1402 return match.group(1).strip().rstrip('."') if match else ""
1405def cmd_examples(args: argparse.Namespace) -> int:
1406 folder = ROOT_DIR / "examples"
1407 scripts = sorted(folder.glob("*.py")) if folder.is_dir() else []
1408 if args.examples_command == "list":
1409 emit([{"name": path.stem, "about": _docstring_line(path)} for path in scripts], args.json,
1410 lambda data: "\n".join(f"{item['name']}: {item['about']}" for item in data) or "no examples/ folder (a source checkout has it)")
1411 return EXIT_OK
1412 match = next((path for path in scripts if path.stem == args.name), None)
1413 if match is None:
1414 close = difflib.get_close_matches(args.name, [path.stem for path in scripts], n=3)
1415 print(f"aq examples run: no example {args.name!r}" + (f"; did you mean: {', '.join(close)}?" if close else ""), file=sys.stderr)
1416 return EXIT_USAGE
1417 return run_live([sys.executable, str(match)])
1420def notebook_title(path: Path) -> str:
1421 data = json.loads(path.read_text(encoding="utf-8"))
1422 for cell in data.get("cells", []):
1423 if cell.get("cell_type") == "markdown":
1424 text = "".join(cell.get("source", []))
1425 match = re.search(r"^#\s+(.+)$", text, re.MULTILINE)
1426 if match:
1427 return match.group(1).strip()
1428 return path.stem
1431def cmd_notebooks(args: argparse.Namespace) -> int:
1432 folder = ROOT_DIR / "docs" / "tutorials"
1433 books = sorted(folder.glob("*.ipynb")) if folder.is_dir() else []
1434 if args.notebooks_command == "list":
1435 emit([{"name": path.stem, "title": notebook_title(path)} for path in books], args.json,
1436 lambda data: "\n".join(f"{item['name']}: {item['title']}" for item in data) or "no docs/tutorials/ (a source checkout has it)")
1437 return EXIT_OK
1438 match = next((path for path in books if path.stem == args.name or path.stem.split("_", 1)[-1] == args.name), None)
1439 if match is None:
1440 print(f"aq notebooks run: no notebook {args.name!r} (aq notebooks list)", file=sys.stderr)
1441 return EXIT_USAGE
1442 try:
1443 import nbclient
1444 import nbformat
1445 except ImportError:
1446 print('aq notebooks run: needs the notebook tools: pip install "aether-quant[notebooks]"', file=sys.stderr)
1447 return EXIT_FAIL
1448 book = nbformat.read(str(match), as_version=4)
1449 nbclient.NotebookClient(book, timeout=600, kernel_name="python3", resources={"metadata": {"path": str(match.parent)}}).execute()
1450 out = Path(args.out) if args.out else None
1451 if out:
1452 nbformat.write(book, str(out))
1453 print(f"ran {match.name}, wrote {out}")
1454 else:
1455 print(f"ran {match.name}: every cell executed")
1456 return EXIT_OK
1459# ---------------------------------------------------------------------------
1460# phase check
1461# ---------------------------------------------------------------------------
1463MANUAL_PHASE_ITEMS = (
1464 "GitHub About: gh repo edit --description ... --homepage ... (when the book or the site moves)",
1465 "Older releases without assets: gh workflow run release.yml -f backfill_tag=vX.Y.Z",
1466 "Scorecard account checks: branch protection, code review, CII badge (owner decisions)",
1467 "Research Record / Backtest Statistics / long-window row / readiness block: only when a round, a Lean pin or a paper period happened",
1468)
1471def _script_ok(script: str, *args: str, root: Path = ROOT_DIR) -> tuple[bool, str]:
1472 code, out = run_capture([sys.executable, f"scripts/{script}", *args], cwd=root, timeout=600)
1473 return code == 0, (out.strip().splitlines() or [""])[-1][:160]
1476def phase_checks(version: str, root: Path = ROOT_DIR) -> list[dict]:
1477 """The automatic items of AGENTS.md's 'After every phase' and wrap-up lists."""
1478 checks = []
1479 changelog = (root / "development" / "Changelog.md").read_text(encoding="utf-8") if (root / "development" / "Changelog.md").exists() else ""
1480 checks.append(_check("Changelog phase", "ok" if f"## Phase {version}" in changelog else "fail", f"## Phase {version}", "add the phase to development/Changelog.md"))
1481 highlights = (root / "docs" / "about" / "changelog.md").read_text(encoding="utf-8") if (root / "docs" / "about" / "changelog.md").exists() else ""
1482 checks.append(_check("docs changelog highlights", "ok" if version in highlights else "fail", "docs/about/changelog.md", "write 3-6 highlight bullets"))
1483 todo = (root / "todo.md").read_text(encoding="utf-8") if (root / "todo.md").exists() else ""
1484 checks.append(_check("todo.md", "ok" if version in todo else "fail", "names the phase" if version in todo else "does not name the phase", "rewrite the current objective"))
1485 probe = ("import docs_facts, sys; r = docs_facts.sync_docs(docs_facts.tracked_docs(), docs_facts.compute_facts(), check=True, "
1486 "blocks=docs_facts.compute_blocks()); print(len(r['changed'])); sys.exit(1 if r['changed'] else 0)")
1487 code, out = run_capture([sys.executable, "-c", probe], cwd=root, timeout=600)
1488 checks.append(_check("doc facts", "ok" if code == 0 else "fail", "current" if code == 0 else f"{out.strip()} stale", "aq docs sync"))
1489 for script, label, args in (("scorecard_pins.py", "scorecard pins", ()), ("library_gate.py", "library gate", ()), ("formal_inventory.py", "formal inventory", ()),
1490 ("readme_freshness.py", "README freshness", ())):
1491 if (root / "scripts" / script).exists():
1492 ok, detail = _script_ok(script, *args, root=root)
1493 checks.append(_check(label, "ok" if ok else "fail", detail, f"python scripts/{script}"))
1494 report = root / "coverage-report" / "coverage.json"
1495 if report.exists():
1496 summary = coverage_summary(json.loads(report.read_text(encoding="utf-8")), json_mtime=report.stat().st_mtime, root=root)
1497 ok = summary["percent"] == 100 and not summary["changed_since"] and not summary["below_100"]
1498 checks.append(_check("coverage 100%", "ok" if ok else "fail", f"{summary['percent']}%, {len(summary['changed_since'])} file(s) changed since", "aq test --coverage"))
1499 else:
1500 checks.append(_check("coverage 100%", "fail", "no coverage-report/coverage.json", "aq test --coverage"))
1501 _, porcelain = run_capture(["git", "status", "--porcelain"], cwd=root)
1502 checks.append(_check("clean tree", "ok" if not porcelain.strip() else "fail", f"{len(porcelain.splitlines())} changed file(s)", "commit (aq commit)"))
1503 if shutil.which("gh"):
1504 _, sha = run_capture(["git", "rev-parse", "HEAD"], cwd=root)
1505 runs = ci_runs(sha.strip())
1506 verdict = summarize_runs(runs)["verdict"] if runs is not None else "unknown"
1507 checks.append(_check("CI of HEAD", "ok" if verdict == "green" else "fail", verdict, "aq ci status --watch"))
1508 running = [space["name"] for space in codespaces() or [] if space.get("state") == "Available"]
1509 checks.append(_check("Codespaces stopped", "ok" if not running else "fail", ", ".join(running) or "none running", "aq codespace stop --all"))
1510 handoff = root / "Aether-quant-Obsidian-Vault" / "HANDOFF.md"
1511 today = _datetime.date.today().isoformat()
1512 if handoff.exists():
1513 checks.append(_check("vault handoff", "ok" if today in handoff.read_text(encoding="utf-8") else "fail", "an entry today" if today in handoff.read_text(encoding="utf-8") else "no entry today", "aq vault graph --summary ..."))
1514 checks += [_check(item.split(":")[0], "manual", item) for item in MANUAL_PHASE_ITEMS]
1515 return checks
1518def cmd_phase(args: argparse.Namespace) -> int:
1519 if (missing := needs_checkout()) is not None:
1520 return missing
1521 checks = phase_checks(args.version)
1523 def render(data: list) -> str:
1524 marks = {"ok": "✓", "fail": "✗", "manual": "·", "skip": "-"}
1525 return "\n".join(f"{marks.get(item['status'], '?')} {item['name']}: {item['detail']}" + (f" -> {item['fix']}" if item["status"] == "fail" and item["fix"] else "") for item in data)
1527 emit(checks, args.json, render)
1528 return EXIT_GATE if any(check["status"] == "fail" for check in checks) else EXIT_OK
1531# ---------------------------------------------------------------------------
1532# scaffolding (aq scaffold module, aq test new)
1533# ---------------------------------------------------------------------------
1536def infer_group(module_path: str, groups: Iterable[str]) -> str:
1537 """The `_SUBSYSTEM_TEST_FILES` group a module's test belongs in: its top-level folder when that is a group, else meta."""
1538 parts = Path(module_path).parts
1539 known = set(groups)
1540 mapping = {"data_pipeline": "data-pipeline", "aq_devtools.py": "cli", "aq_lab_cli.py": "lab", "lab": "lab", "execution": "risk", "inference": "ml",
1541 "moe": "ml", "experts": "ml", "audit": "audit", "monitoring": "live", "notifications": "notifications"}
1542 head = parts[0] if parts else ""
1543 if head in known:
1544 return head
1545 if mapping.get(head) in known:
1546 return mapping[head]
1547 return "meta" if "meta" in known else sorted(known)[0]
1550def register_test_file(aq_cli_text: str, group: str, test_name: str) -> str:
1551 """`aq_cli.py`'s text with `test_name` added at the top of `group`'s list in `_SUBSYSTEM_TEST_FILES`."""
1552 if f'"{test_name}"' in aq_cli_text:
1553 return aq_cli_text
1554 start = aq_cli_text.index("_SUBSYSTEM_TEST_FILES: dict[str, list[str]] = {")
1555 key = f' "{group}": [\n'
1556 index = aq_cli_text.index(key, start)
1557 insert = index + len(key)
1558 return aq_cli_text[:insert] + f' "{test_name}",\n' + aq_cli_text[insert:]
1561def test_file_text(module: str, dotted: str) -> str:
1562 return f'''"""{module}: its own test file (AGENTS.md: one test file per source module)."""
1564from __future__ import annotations
1566import {dotted} # noqa: F401
1569def test_write_the_first_test():
1570 assert False, "write the first test for {dotted}"
1571'''
1574def module_text(dotted: str) -> str:
1575 return f'''"""{dotted}: <one sentence on what this module does and why it exists>."""
1577from __future__ import annotations
1578'''
1581def add_py_module(pyproject_text: str, name: str) -> str:
1582 """pyproject's text with `name` added to `py-modules` (sorted), unchanged if it is there."""
1583 match = re.search(r"^py-modules = \[(.*?)\]$", pyproject_text, re.MULTILINE)
1584 if match is None:
1585 raise ValueError("pyproject.toml has no py-modules line")
1586 names = re.findall(r'"([^"]+)"', match.group(1))
1587 if name in names:
1588 return pyproject_text
1589 joined = ", ".join(f'"{item}"' for item in sorted([*names, name]))
1590 return pyproject_text[:match.start()] + f"py-modules = [{joined}]" + pyproject_text[match.end():]
1593def scaffold_test(module_path: str, *, group: str | None, root: Path = ROOT_DIR, dry_run: bool = False) -> tuple[int, list[str]]:
1594 """Create tests/test_<stem>.py for `module_path` and register it; returns (exit code, the actions taken)."""
1595 from aq_cli import _SUBSYSTEM_TEST_FILES
1597 posix = module_path.replace("\\", "/")
1598 stem = Path(posix).stem
1599 dotted = posix.removesuffix(".py").replace("/", ".")
1600 test_path = root / "tests" / f"test_{stem}.py"
1601 if test_path.exists():
1602 return EXIT_FAIL, [f"{test_path.relative_to(root).as_posix()} already exists"]
1603 chosen = group or infer_group(posix, _SUBSYSTEM_TEST_FILES)
1604 if chosen not in _SUBSYSTEM_TEST_FILES:
1605 return EXIT_USAGE, [f"no test group {chosen!r}; groups: {', '.join(_SUBSYSTEM_TEST_FILES)}"]
1606 actions = [f"create {test_path.relative_to(root).as_posix()}", f"register it under {chosen!r} in aq_cli.py"]
1607 if not dry_run:
1608 test_path.write_text(test_file_text(posix, dotted), encoding="utf-8", newline="\n")
1609 cli = root / "aq_cli.py"
1610 cli.write_text(register_test_file(cli.read_text(encoding="utf-8"), chosen, test_path.name), encoding="utf-8", newline="\n")
1611 return EXIT_OK, actions
1614def scaffold_module(module_path: str, *, group: str | None, root: Path = ROOT_DIR, dry_run: bool = False) -> tuple[int, list[str]]:
1615 posix = module_path.replace("\\", "/")
1616 if not posix.endswith(".py"):
1617 return EXIT_USAGE, ["give a path ending in .py, e.g. risk/my_rule.py"]
1618 target = root / posix
1619 if target.exists():
1620 return EXIT_FAIL, [f"{posix} already exists"]
1621 if not dry_run and not target.parent.is_dir():
1622 return EXIT_USAGE, [f"{target.parent.relative_to(root).as_posix()}/ does not exist"]
1623 actions = [f"create {posix}"]
1624 if not dry_run:
1625 target.write_text(module_text(posix.removesuffix(".py").replace("/", ".")), encoding="utf-8", newline="\n")
1626 if "/" not in posix:
1627 actions.append(f"add {Path(posix).stem!r} to pyproject.toml py-modules, then: pip install -e .")
1628 if not dry_run:
1629 pyproject = root / "pyproject.toml"
1630 pyproject.write_text(add_py_module(pyproject.read_text(encoding="utf-8"), Path(posix).stem), encoding="utf-8", newline="\n")
1631 code, more = scaffold_test(posix, group=group, root=root, dry_run=dry_run)
1632 actions += more
1633 actions += ["rule 14: export its public names from aether_quant/<subsystem>.py (or list them in tests/data/aether_quant_unexported.json with a reason)",
1634 f"add a line for it to {Path(posix).parent.as_posix() or '.'}/README.md"]
1635 return code, actions
1638def cmd_scaffold(args: argparse.Namespace) -> int:
1639 if (missing := needs_checkout()) is not None:
1640 return missing
1641 code, actions = scaffold_module(args.path, group=args.group, dry_run=args.dry_run)
1642 print("\n".join(("would " if args.dry_run else "") + action if action.startswith(("create", "register", "add ")) else action for action in actions))
1643 return code
1646# ---------------------------------------------------------------------------
1647# registration
1648# ---------------------------------------------------------------------------
1651def register(subparsers) -> None:
1652 """Add the developer commands to `aq`'s subparsers."""
1653 hooks = _parser(subparsers, "hooks", "The pre-commit gate: install it, show it, turn its coverage step off or on",
1654 "aq hooks install", "aq hooks status", "aq hooks coverage off --once")
1655 hooks_sub = hooks.add_subparsers(dest="hooks_command", required=True, parser_class=type(hooks))
1656 install = _parser(hooks_sub, "install", "Install the wrapper in .git/hooks/pre-commit", "aq hooks install")
1657 add_dry_run_flag(install)
1658 status = _parser(hooks_sub, "status", "Whether the hook is installed, its gates, and the coverage switch", "aq hooks status --json")
1659 add_json_flag(status)
1660 coverage = _parser(hooks_sub, "coverage", "Turn the hook's coverage step off (--once: the next commit only), back on, or show it",
1661 "aq hooks coverage off --once", "aq hooks coverage on")
1662 coverage.add_argument("coverage_action", choices=["off", "on", "status"])
1663 coverage.add_argument("--once", action="store_true", help="With off: skip only the next commit's coverage step")
1664 add_dry_run_flag(coverage)
1665 add_json_flag(coverage)
1666 hooks.set_defaults(func=cmd_hooks)
1668 commit = _parser(subparsers, "commit", "git commit through the pre-commit gate, optionally skipping its coverage step for this one commit",
1669 'aq commit -m "fix the gate" --skip-coverage', 'aq commit -a -m "docs" -- --signoff')
1670 commit.add_argument("-m", "--message", required=True, help="The commit message")
1671 commit.add_argument("-a", "--all", action="store_true", help="Stage every tracked change first (git commit -a)")
1672 commit.add_argument("--skip-coverage", action="store_true", help="Skip the coverage step for this commit only (sets AQ_SKIP_COVERAGE_HOOK=1); the other gates still run")
1673 add_dry_run_flag(commit)
1674 commit.add_argument("git_args", nargs="*", help="More git commit arguments, after --")
1675 commit.set_defaults(func=cmd_commit)
1677 check = _parser(subparsers, "check", "Run the pre-commit gate now, committing nothing", "aq check", "aq check --no-coverage")
1678 check.add_argument("--no-coverage", action="store_true", help="Skip the coverage step")
1679 check.set_defaults(func=cmd_check)
1681 doctor = _parser(subparsers, "doctor", "Check the environment: Python, the install, tools, services, RAM, disk, model pins", "aq doctor", "aq doctor --json")
1682 add_json_flag(doctor)
1683 doctor.set_defaults(func=cmd_doctor)
1685 version = _parser(subparsers, "version", "The installed version, Python, platform and (in a checkout) the git commit", "aq version", "aq --version")
1686 add_json_flag(version)
1687 version.set_defaults(func=cmd_version)
1689 completion = _parser(subparsers, "completion", "Print a shell completion script", "aq completion powershell >> $PROFILE", "aq completion bash >> ~/.bashrc")
1690 completion.add_argument("shell", choices=["bash", "zsh", "powershell"])
1691 completion.set_defaults(func=cmd_completion)
1693 help_parser = _parser(subparsers, "help", "Help for a command (the same as aq COMMAND --help)", "aq help evaluate", "aq help hooks coverage")
1694 help_parser.add_argument("topic", nargs="*", help="The command path")
1695 help_parser.set_defaults(func=cmd_help)
1697 status_parser = _parser(subparsers, "status", "The project at a glance: branch, changes, hook and coverage, CI of HEAD, Dependabot, Codespaces",
1698 "aq status", "aq status --offline", "aq status --git")
1699 add_json_flag(status_parser)
1700 status_parser.add_argument("--offline", action="store_true", help="Skip the GitHub queries (CI, PRs, Codespaces)")
1701 status_parser.add_argument("--git", action="store_true", help="Print plain git status instead")
1702 status_parser.set_defaults(func=cmd_status)
1704 ci = _parser(subparsers, "ci", "GitHub Actions: the runs of a commit, the failing lines of a run, or a ci.yml job run here",
1705 "aq ci status --watch", "aq ci logs 44777003047", "aq ci local fast-guards")
1706 ci_sub = ci.add_subparsers(dest="ci_command", required=True, parser_class=type(ci))
1707 ci_status = _parser(ci_sub, "status", "Every workflow run of a commit: green, red (exit 1) or running (exit 3)", "aq ci status", "aq ci status --branch main --watch")
1708 ci_status.add_argument("--sha", default="HEAD", help="The commit (default HEAD)")
1709 ci_status.add_argument("--branch", default=None, help="The tip of this remote branch instead")
1710 ci_status.add_argument("--watch", action="store_true", help="Poll until nothing is running")
1711 ci_status.add_argument("--interval", type=int, default=30, help="Seconds between polls with --watch (default 30)")
1712 add_json_flag(ci_status)
1713 ci_logs = _parser(ci_sub, "logs", "The lines that explain each failed job of a run", "aq ci logs 44777003047", "aq ci logs 44777003047 --job python-compat")
1714 ci_logs.add_argument("run_id")
1715 ci_logs.add_argument("--job", default=None, help="Only jobs whose name contains this (default: every failed job)")
1716 ci_logs.add_argument("--lines", type=int, default=80, help="At most this many lines per job (default 80)")
1717 add_json_flag(ci_logs)
1718 ci_local = _parser(ci_sub, "local", "Run a workflow job's run: steps here, in order (uses: steps are skipped)", "aq ci local --list", "aq ci local fast-guards --dry-run")
1719 ci_local.add_argument("job", nargs="?", default=None, help="The job (omit or --list to list them)")
1720 ci_local.add_argument("--workflow", default="ci.yml", help="The workflow file under .github/workflows (default ci.yml)")
1721 ci_local.add_argument("--list", action="store_true", help="List the jobs and what each needs")
1722 ci_local.add_argument("--matrix", action="append", metavar="KEY=VALUE", help="A matrix value (default: each key's first)")
1723 add_dry_run_flag(ci_local)
1724 ci.set_defaults(func=cmd_ci)
1726 deps = _parser(subparsers, "deps", "Dependencies: Dependabot PRs, applying one correctly, the hash locks, pins, audit, why a package is locked",
1727 "aq deps prs", "aq deps apply 57", "aq deps why numpy")
1728 deps_sub = deps.add_subparsers(dest="deps_command", required=True, parser_class=type(deps))
1729 prs = _parser(deps_sub, "prs", "Open Dependabot PRs: ecosystem, package, versions, checks", "aq deps prs --json")
1730 add_json_flag(prs)
1731 apply_parser = _parser(deps_sub, "apply", "Apply Dependabot PRs to the working tree (pip: re-lock with uv; npm: npm install); never commits",
1732 "aq deps apply 53 55", "aq deps apply 57 --dry-run")
1733 apply_parser.add_argument("numbers", nargs="+", help="PR numbers")
1734 add_dry_run_flag(apply_parser)
1735 lock = _parser(deps_sub, "lock", "Rebuild requirements/lock/*.txt from their .in files (uv)", "aq deps lock", "aq deps lock --profile ci --upgrade-package numpy")
1736 lock.add_argument("--profile", action="append", help="One profile (repeatable; default all)")
1737 lock.add_argument("--upgrade-package", action="append", metavar="NAME", help="Let this pin move to its newest allowed version (repeatable)")
1738 _parser(deps_sub, "pins", "Every install pinned by hash (the Scorecard check); prints 0 when clean", "aq deps pins")
1739 _parser(deps_sub, "audit", "pip-audit over the runtime and ci locks (as CI's dependency-audit job)", "aq deps audit")
1740 why = _parser(deps_sub, "why", "Which packages pull PACKAGE into each lock", "aq deps why urllib3", "aq deps why numpy --profile light")
1741 why.add_argument("package")
1742 why.add_argument("--profile", action="append", help="Only this lock profile (repeatable)")
1743 add_json_flag(why)
1744 deps.set_defaults(func=cmd_deps)
1746 cov = _parser(subparsers, "coverage", "The last coverage run: totals, files below 100%, misses by function, cleaning",
1747 "aq coverage report", "aq coverage misses --include \"risk/*\" --by-function")
1748 cov_sub = cov.add_subparsers(dest="coverage_command", required=True, parser_class=type(cov))
1749 report = _parser(cov_sub, "report", "Total, files below 100%, age, and files changed since (exit 3 below 100%)", "aq coverage report --json")
1750 add_json_flag(report)
1751 misses = _parser(cov_sub, "misses", "Uncovered lines, by file or function (scripts/coverage_misses.py)", "aq coverage misses --include lab/* --context 2")
1752 misses.add_argument("--include", action="append", help="Glob of files (repeatable)")
1753 misses.add_argument("--by-function", action="store_true", help="Group misses by function")
1754 misses.add_argument("--context", type=int, default=None, metavar="N", help="Print each miss with N lines around it")
1755 clean = _parser(cov_sub, "clean", "Delete coverage-report/ and .coverage* (dry run unless --apply)", "aq coverage clean --apply --yes")
1756 clean.add_argument("--apply", action="store_true", help="Delete (default: list only)")
1757 add_yes_flag(clean)
1758 add_json_flag(clean)
1759 cov.set_defaults(func=cmd_coverage)
1761 space = _parser(subparsers, "codespace", "GitHub Codespaces: list (running ones bill), stop, delete", "aq codespace list", "aq codespace stop --all")
1762 space_sub = space.add_subparsers(dest="codespace_command", required=True, parser_class=type(space))
1763 space_list = _parser(space_sub, "list", "Every Codespace and its state", "aq codespace list --json")
1764 add_json_flag(space_list)
1765 stop = _parser(space_sub, "stop", "Stop one Codespace, or every running one", "aq codespace stop --all", "aq codespace stop NAME")
1766 stop.add_argument("name", nargs="?", default=None)
1767 stop.add_argument("--all", action="store_true", help="Every running Codespace")
1768 add_dry_run_flag(stop)
1769 delete = _parser(space_sub, "delete", "Delete a Codespace and its storage (asks first)", "aq codespace delete NAME --yes")
1770 delete.add_argument("name")
1771 add_dry_run_flag(delete)
1772 add_yes_flag(delete)
1773 space.set_defaults(func=cmd_codespace)
1775 vault = _parser(subparsers, "vault", "Aether-Vault records and the Obsidian code graph", "aq vault record --label rules ml/evaluation/rules.json",
1776 'aq vault graph --summary "V6.7.1 done" --files aq_cli.py')
1777 vault_sub = vault.add_subparsers(dest="vault_command", required=True, parser_class=type(vault))
1778 record = _parser(vault_sub, "record", "Record files in the vault with a label and metrics (scripts/vault_record.py)", "aq vault record --label freeze --metric trials=12 a.json")
1779 record.add_argument("--label", required=True, help="The record's tag")
1780 record.add_argument("--metric", action="append", help="key=value (repeatable)")
1781 record.add_argument("paths", nargs="+")
1782 add_dry_run_flag(record)
1783 graph = _parser(vault_sub, "graph", "Regenerate the Obsidian code graph and append a handoff entry", 'aq vault graph --summary "..." --files a.py b.py')
1784 graph.add_argument("--summary", required=True, help="The handoff summary")
1785 graph.add_argument("--files", nargs="+", required=True, help="Files the phase changed")
1786 graph.add_argument("--agent", default="ox-alpha", help="The handoff's agent name (default ox-alpha)")
1787 add_dry_run_flag(graph)
1788 vault.set_defaults(func=cmd_vault)
1790 problems = _parser(subparsers, "problems", "development/Problems.md: the next number and template, one entry, the partial ones", "aq problems next", "aq problems show 413")
1791 problems_sub = problems.add_subparsers(dest="problems_command", required=True, parser_class=type(problems))
1792 next_parser = _parser(problems_sub, "next", "The next free number and an entry template", "aq problems next")
1793 add_json_flag(next_parser)
1794 show = _parser(problems_sub, "show", "One entry", "aq problems show 413")
1795 show.add_argument("number")
1796 add_json_flag(show)
1797 open_parser = _parser(problems_sub, "open", "Entries still partial (🟡)", "aq problems open --json")
1798 add_json_flag(open_parser)
1799 problems.set_defaults(func=cmd_problems)
1801 lint = _parser(subparsers, "lint", "ruff over the project, optionally fixing, optionally the library's type completeness", "aq lint", "aq lint --fix --types")
1802 lint.add_argument("--fix", action="store_true", help="Apply ruff's safe fixes")
1803 lint.add_argument("--types", action="store_true", help="Also check the library's type completeness (scripts/type_completeness.py)")
1804 lint.set_defaults(func=cmd_lint)
1806 scaffold = _parser(subparsers, "scaffold", "Create a module with its registered test file and the reminders for the export and the readme",
1807 "aq scaffold risk/my_rule.py", "aq scaffold my_tool.py --group meta --dry-run")
1808 scaffold.add_argument("path", help="The new module's path, e.g. risk/my_rule.py")
1809 scaffold.add_argument("--group", default=None, help="The test group (default: from the folder)")
1810 add_dry_run_flag(scaffold)
1811 scaffold.set_defaults(func=cmd_scaffold)
1813 phase = _parser(subparsers, "phase", "The end-of-phase checklist from AGENTS.md, checked where it can be", "aq phase check --version V6.7.1")
1814 phase_sub = phase.add_subparsers(dest="phase_command", required=True, parser_class=type(phase))
1815 phase_check = _parser(phase_sub, "check", "Changelog, docs, gates, coverage, tree, CI, Codespaces, vault (exit 3 on a failure)", "aq phase check --version V6.7.1 --json")
1816 phase_check.add_argument("--version", required=True, help="The phase as its Changelog heading names it")
1817 add_json_flag(phase_check)
1818 phase.set_defaults(func=cmd_phase)
1820 bug = _parser(subparsers, "bug-report", "A Markdown report for a GitHub issue: versions and the doctor's checks (no config, no env, no user names)",
1821 "aq bug-report", "aq bug-report --out issue.md")
1822 bug.add_argument("--out", default=None, help="Write it here instead of printing")
1823 bug.set_defaults(func=cmd_bug_report)
1825 examples = _parser(subparsers, "examples", "The runnable examples in examples/", "aq examples list", "aq examples run aether_quant_quickstart")
1826 examples_sub = examples.add_subparsers(dest="examples_command", required=True, parser_class=type(examples))
1827 examples_list = _parser(examples_sub, "list", "Every example and what it shows", "aq examples list --json")
1828 add_json_flag(examples_list)
1829 examples_run = _parser(examples_sub, "run", "Run one example", "aq examples run aether_quant_quickstart")
1830 examples_run.add_argument("name")
1831 examples.set_defaults(func=cmd_examples)
1833 notebooks = _parser(subparsers, "notebooks", "The tutorial notebooks: list them, run one", "aq notebooks list", "aq notebooks run 00_hello_world --out done.ipynb")
1834 notebooks_sub = notebooks.add_subparsers(dest="notebooks_command", required=True, parser_class=type(notebooks))
1835 notebooks_list = _parser(notebooks_sub, "list", "Every tutorial and its title", "aq notebooks list --json")
1836 add_json_flag(notebooks_list)
1837 notebooks_run = _parser(notebooks_sub, "run", "Execute one tutorial", "aq notebooks run hello_world")
1838 notebooks_run.add_argument("name", help="The file name without .ipynb, or without its number prefix")
1839 notebooks_run.add_argument("--out", default=None, help="Write the executed notebook here")
1840 notebooks.set_defaults(func=cmd_notebooks)