Skip to content

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

feat(cli): --check and --doctor can report as JSON Lines

rubenluetke10-beepdb90c338372f
diff --git a/jarvis/__main__.py b/jarvis/__main__.py
index 071884c33c..67c4623ae3 100644
--- a/jarvis/__main__.py
+++ b/jarvis/__main__.py
@@ -57,6 +57,14 @@ def _build_parser() -> argparse.ArgumentParser:
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
parser.add_argument("--wizard", action="store_true", help="Restart the setup wizard.")
parser.add_argument("--check", action="store_true", help="Only show the hardware analysis.")
+ parser.add_argument(
+ "--json", action="store_true", dest="json_output",
+ help="With --check or --doctor: emit JSON Lines (one object per component: "
+ "component, status, message, hint) instead of the human report, so an "
+ "installer can gate on the result without parsing prose. Exit codes are "
+ "unchanged. Must follow the command flag — a LEADING `--json` is the "
+ "control CLI's own global option (`jarvis --json missions list`).",
+ )
parser.add_argument("--plugins", action="store_true", help="List the plugin registry.")
parser.add_argument(
"--worker-tool-broker-stdio",
@@ -153,8 +161,8 @@ def _parse_args(argv: list[str]) -> argparse.Namespace:
return _build_parser().parse_args(argv)
-def _cmd_check() -> int:
- return detection.main()
+def _cmd_check(as_json: bool = False) -> int:
+ return detection.main(as_json=as_json)
def _cmd_plugins() -> int:
@@ -236,7 +244,7 @@ def _cmd_phase5_doctor() -> int:
return 0
-def _cmd_doctor() -> int:
+def _cmd_doctor(as_json: bool = False) -> int:
"""Completeness self-check — what is registered & ready vs. advertised but
missing. Generalises the phantom-jarvis-agent forensic (2026-06-28): a fresh
download can *look* complete while one dead reference makes a working feature
@@ -249,6 +257,14 @@ def _cmd_doctor() -> int:
config = cfg.load_config()
findings = run_doctor(config)
+ if as_json:
+ from jarvis.diagnostics.json_report import dumps, record
+
+ print(dumps([
+ record(f.category, f.status, f.message, f.hint) for f in findings
+ ]))
+ return 1 if has_failures(findings) else 0
+
lines: list[str] = [f"Jarvis {__version__} — Doctor (completeness self-check)",
"=" * 64]
last_cat: str | None = None
@@ -541,7 +557,7 @@ def main(argv: list[str] | None = None) -> int:
return broker_stdio_main()
if args.check:
- return _cmd_check()
+ return _cmd_check(as_json=args.json_output)
if args.plugins:
return _cmd_plugins()
if args.phase5_doctor:
@@ -549,7 +565,7 @@ def main(argv: list[str] | None = None) -> int:
if args.orb_doctor:
return _cmd_orb_doctor()
if args.doctor:
- return _cmd_doctor()
+ return _cmd_doctor(as_json=args.json_output)
if args.install_admin_helper:
return _cmd_install_admin_helper()
if args.uninstall:
diff --git a/jarvis/cli_ctl/reserved.py b/jarvis/cli_ctl/reserved.py
index 3a0d1a90d0..343f50884f 100644
--- a/jarvis/cli_ctl/reserved.py
+++ b/jarvis/cli_ctl/reserved.py
@@ -52,14 +52,40 @@ RESERVED_CONTROL_NAMES: frozenset[str] = frozenset(
)
# Control-global options accepted before a subcommand (root callback options).
-# When one of these is the first argv token we also route to the control CLI.
+# When one of these leads the invocation we look PAST it for a reserved command
+# name before routing — see is_control_invocation.
CONTROL_GLOBAL_OPTIONS: frozenset[str] = frozenset({"--json", "--url", "--key"})
+# Control-global options that consume the following token as their value, so
+# scanning for the command name must skip that token too.
+_VALUE_OPTIONS: frozenset[str] = frozenset({"--url", "--key"})
+
def is_control_invocation(argv: list[str]) -> bool:
"""True if ``argv`` should be handled by the control CLI rather than the
- launcher argument parser."""
+ launcher argument parser.
+
+ A leading bare word decides on its own. A leading control-global option is
+ only a hint: ``--json`` is now ALSO a launcher flag (``jarvis --check
+ --json`` emits the preflight as JSON Lines), so routing on the option alone
+ would send ``jarvis --json --check`` to the control CLI, which has no such
+ command. Instead, look past the leading options for the first bare word and
+ route only if that word is a reserved control command.
+ """
if not argv:
return False
first = argv[0]
- return first in RESERVED_CONTROL_NAMES or first in CONTROL_GLOBAL_OPTIONS
+ if first in RESERVED_CONTROL_NAMES:
+ return True
+ if first not in CONTROL_GLOBAL_OPTIONS:
+ return False
+
+ i = 0
+ while i < len(argv) and argv[i] in CONTROL_GLOBAL_OPTIONS:
+ i += 2 if argv[i] in _VALUE_OPTIONS else 1
+ if i >= len(argv):
+ # Nothing but control-global options: `jarvis --json` belongs to the
+ # control CLI, which answers with its own usage rather than launching
+ # the app.
+ return True
+ return argv[i] in RESERVED_CONTROL_NAMES
diff --git a/jarvis/diagnostics/json_report.py b/jarvis/diagnostics/json_report.py
new file mode 100644
index 0000000000..bb2e66455e
--- /dev/null
+++ b/jarvis/diagnostics/json_report.py
@@ -0,0 +1,82 @@
+"""Machine-readable shape for the preflight commands (``--check``, ``--doctor``).
+
+Installers and setup scripts need to gate on a preflight result. Parsing the
+human report is the wrong way to do that: the box-drawing layout is free to
+change with every wording fix, and a script that greps it silently starts
+lying the moment it does.
+
+This module is the single home for the machine contract those scripts bind to.
+Both preflight commands emit **JSON Lines** — one self-contained JSON object
+per line, no enclosing array — so a caller can stream them, and a truncated
+run still yields valid records for everything that already ran.
+
+Each record is::
+
+ {"component": "ram", "status": "ok", "message": "31.9 GB total", "hint": null}
+
+``status`` is a CLOSED set, which is the whole point: a script branches on it.
+The four values mirror :class:`jarvis.diagnostics.doctor.DoctorFinding` so the
+two commands never drift into two vocabularies:
+
+ ``ok`` — present and usable.
+ ``warn`` — usable but degraded, or configured-but-inert. Not fatal.
+ ``fail`` — something advertised cannot work. This is what an installer
+ should stop on.
+ ``info`` — a neutral fact (detected CPU, chosen model). Never a verdict, and
+ never a reason to fail a script.
+
+Exit codes are deliberately NOT changed by asking for JSON: ``--check`` keeps
+returning 0 and ``--doctor`` keeps returning 1 on any ``fail``, so callers that
+already gate on the exit status keep working unmodified.
+"""
+from __future__ import annotations
+
+import json
+from typing import Final, Literal
+
+Status = Literal["ok", "warn", "fail", "info"]
+
+#: The closed status vocabulary, exported so tests and callers can assert
+#: against one list instead of restating it.
+STATUSES: Final[tuple[str, ...]] = ("ok", "warn", "fail", "info")
+
+#: Field order in every emitted record. Fixed so a diff of two runs is
+#: readable and a golden-file test is stable.
+FIELDS: Final[tuple[str, ...]] = ("component", "status", "message", "hint")
+
+
+def record(
+ component: str,
+ status: Status,
+ message: str,
+ hint: str | None = None,
+) -> dict[str, object]:
+ """Build one preflight record, rejecting an out-of-vocabulary status.
+
+ The guard is not defensive noise: an unknown status would reach a caller's
+ ``if status == ...`` branch and be silently treated as "not a failure",
+ which is exactly the class of bug the closed set exists to prevent.
+ """
+ if status not in STATUSES:
+ raise ValueError(
+ f"status {status!r} is not one of {STATUSES} — the preflight "
+ f"vocabulary is closed so scripts can branch on it"
+ )
+ return {
+ "component": component,
+ "status": status,
+ "message": message,
+ "hint": hint,
+ }
+
+
+def dumps(records: list[dict[str, object]]) -> str:
+ """Render records as JSON Lines.
+
+ ``ensure_ascii=False`` keeps a detected device name readable rather than
+ escaping it; the stream is UTF-8 like every other Jarvis stdout.
+ """
+ return "\n".join(
+ json.dumps({field: rec.get(field) for field in FIELDS}, ensure_ascii=False)
+ for rec in records
+ )
diff --git a/jarvis/hardware/detection.py b/jarvis/hardware/detection.py
index e9defd3474..5ed7e27341 100644
--- a/jarvis/hardware/detection.py
+++ b/jarvis/hardware/detection.py
@@ -393,6 +393,105 @@ def _format_report(report: HardwareReport, rec: WhisperRecommendation) -> str:
return "\n".join(lines)
+def check_records(
+ report: HardwareReport, rec: WhisperRecommendation
+) -> list[dict[str, object]]:
+ """The same preflight as :func:`_format_report`, as machine-readable records.
+
+ One record per component, in the closed vocabulary defined by
+ :mod:`jarvis.diagnostics.json_report`. The verdicts here are not invented
+ for the JSON path — they are the ones the human report already makes:
+
+ * ``ffmpeg`` missing is the one thing the text report calls out as
+ needing action, so it is the one ``warn`` that is always meaningful.
+ * ``ram`` uses the SAME 8 GB threshold as :func:`recommend_whisper`. Below
+ it, local speech-to-text is not recommended and the box needs a cloud
+ provider key to have a voice at all — worth a ``warn``, never a
+ ``fail``, because Jarvis runs fine that way.
+
+ Everything else is ``info``: a CPU name or an absent GPU is a fact about
+ the host, not a defect, and a script must never fail an install over it.
+ """
+ from jarvis.diagnostics.json_report import record
+
+ os_version = report.os_version.split()[0] if report.os_version else ""
+ records: list[dict[str, object]] = [
+ record("os", "info", f"{report.os_name} {os_version}".strip()),
+ record(
+ "python",
+ "info",
+ f"{report.python_version} ({report.python_executable})",
+ ),
+ record(
+ "cpu",
+ "info",
+ f"{report.cpu_name} — {report.cpu_cores_physical} physical / "
+ f"{report.cpu_cores_logical} logical cores",
+ ),
+ ]
+
+ ram_ok = report.ram_total_mb >= 8192
+ records.append(
+ record(
+ "ram",
+ "ok" if ram_ok else "warn",
+ f"{report.ram_total_mb} MB total, {report.ram_available_mb} MB available",
+ None
+ if ram_ok
+ else "Under 8 GB — local speech-to-text is not recommended here. "
+ "Configure a cloud provider key so voice input still works.",
+ )
+ )
+
+ if report.gpus:
+ for i, gpu in enumerate(report.gpus):
+ detail = f"{gpu.name} ({gpu.vram_mb} MB VRAM)"
+ if gpu.compute_capability:
+ detail += f", compute capability {gpu.compute_capability}"
+ records.append(record(f"gpu{i}", "ok", detail))
+ else:
+ records.append(
+ record("gpu", "info", "no NVIDIA GPU detected — everything runs on CPU")
+ )
+
+ records.append(
+ record(
+ "cuda-runtime",
+ "ok" if report.cuda_runtime else "info",
+ report.cuda_runtime or "not installed",
+ )
+ )
+ records.append(
+ record(
+ "torch-cuda",
+ "ok" if report.torch_cuda_available else "info",
+ "available" if report.torch_cuda_available else "not available",
+ )
+ )
+ records.append(
+ record(
+ "ffmpeg",
+ "ok" if report.ffmpeg_version else "warn",
+ report.ffmpeg_version or "not found",
+ None if report.ffmpeg_version else "Install ffmpeg and put it on PATH.",
+ )
+ )
+
+ for pkg, version in sorted(report.existing_installs.items()):
+ records.append(record(f"installed:{pkg}", "info", version))
+
+ records.append(
+ record(
+ "speech-to-text",
+ "info",
+ f"{rec.provider} / {rec.model} on {rec.device} ({rec.compute_type}), "
+ f"~{rec.expected_latency_ms} ms for 5 s of audio",
+ rec.rationale,
+ )
+ )
+ return records
+
+
def cuda_inference_verified() -> bool | None:
"""Cached GPU-inference verdict for this host (non-blocking), or ``None``.
@@ -461,9 +560,20 @@ def system_ram_gb() -> float | None:
return round(total_mb / 1024.0, 1) if total_mb > 0 else None
-def main() -> int:
+def main(as_json: bool = False) -> int:
+ """Render the hardware preflight.
+
+ ``as_json`` swaps the box-drawing report for JSON Lines so an installer can
+ gate on it. The exit code is 0 either way — this command reports, it does
+ not judge — so existing callers keep working unchanged.
+ """
report = analyze()
rec = recommend_whisper(report, gpu_inference_verified=cuda_inference_verified())
+ if as_json:
+ from jarvis.diagnostics.json_report import dumps
+
+ print(dumps(check_records(report, rec)))
+ return 0
print(_format_report(report, rec))
return 0
diff --git a/tests/unit/cli_ctl/test_dispatch.py b/tests/unit/cli_ctl/test_dispatch.py
index e9d63cc523..f494858a13 100644
--- a/tests/unit/cli_ctl/test_dispatch.py
+++ b/tests/unit/cli_ctl/test_dispatch.py
@@ -20,14 +20,42 @@ def _launcher_tokens():
return options, positionals
+# `--json` is deliberately shared: leading, it is the control CLI's global
+# option (`jarvis --json missions list`); trailing a launcher flag, it switches
+# the preflight to JSON Lines (`jarvis --check --json`). Dispatch separates the
+# two by looking for a reserved COMMAND past the leading options, which is what
+# test_json_is_shared_and_dispatch_separates_the_two_uses pins down. Every other
+# control-global option must still be exclusive to the control CLI.
+_SHARED_OPTIONS = frozenset({"--json"})
+
+
def test_no_reserved_name_collides_with_launcher():
options, positionals = _launcher_tokens()
# A launcher subcommand (e.g. `serve`) must never be hijacked by dispatch.
assert RESERVED_CONTROL_NAMES.isdisjoint(positionals)
- # Control-global options must not collide with launcher flags.
- assert CONTROL_GLOBAL_OPTIONS.isdisjoint(options)
+ # Control-global options must not collide with launcher flags, except for
+ # the one that is shared on purpose.
+ assert (CONTROL_GLOBAL_OPTIONS - _SHARED_OPTIONS).isdisjoint(options)
# Reserved names are bare words, never flag-like.
assert all(not n.startswith("-") for n in RESERVED_CONTROL_NAMES)
+ # The shared option really is on both sides — if it ever leaves the
+ # launcher, the carve-out above must go with it.
+ assert _SHARED_OPTIONS <= options
+ assert _SHARED_OPTIONS <= CONTROL_GLOBAL_OPTIONS
+
+
+def test_json_is_shared_and_dispatch_separates_the_two_uses():
+ # Control CLI: a reserved command follows the global options.
+ assert is_control_invocation(["--json", "missions", "list"])
+ assert is_control_invocation(["--json", "--url", "http://h:1", "brain", "list"])
+ # Bare `jarvis --json` is the control CLI answering with its own usage,
+ # never the app launching.
+ assert is_control_invocation(["--json"])
+ # Launcher: `--json` decorates a launcher flag, in either order of reading.
+ assert not is_control_invocation(["--check", "--json"])
+ assert not is_control_invocation(["--json", "--check"])
+ assert not is_control_invocation(["--json", "--doctor"])
+ assert not is_control_invocation(["--json", "serve"])
def test_launcher_invocations_not_routed():
@@ -65,7 +93,7 @@ def test_main_does_not_route_launcher(monkeypatch):
raise AssertionError("launcher invocation must not route to control")
monkeypatch.setattr(jm, "_run_control", boom)
- monkeypatch.setattr(jm, "_cmd_check", lambda: 0)
+ monkeypatch.setattr(jm, "_cmd_check", lambda as_json=False: 0)
rc = jm.main(["--check"])
assert rc == 0
diff --git a/tests/unit/diagnostics/test_preflight_json.py b/tests/unit/diagnostics/test_preflight_json.py
new file mode 100644
index 0000000000..d088ba8139
--- /dev/null
+++ b/tests/unit/diagnostics/test_preflight_json.py
@@ -0,0 +1,146 @@
+"""`jarvis --check --json` / `jarvis --doctor --json` emit a stable machine contract.
+
+The point of the JSON path is that an installer can branch on it. That only
+holds if the status vocabulary stays closed and the exit codes keep the meaning
+they had before the flag existed — both are asserted here.
+"""
+from __future__ import annotations
+
+import json
+
+import pytest
+
+import jarvis.__main__ as jm
+from jarvis.diagnostics.json_report import FIELDS, STATUSES, dumps, record
+from jarvis.hardware.detection import (
+ GPUInfo,
+ HardwareReport,
+ WhisperRecommendation,
+ check_records,
+)
+
+
+def _report(**overrides) -> HardwareReport:
+ base = dict(
+ os_name="Linux",
+ os_version="6.8.0 #1 SMP",
+ cpu_name="Generic CPU",
+ cpu_cores_physical=4,
+ cpu_cores_logical=8,
+ ram_total_mb=16384,
+ ram_available_mb=8192,
+ python_version="3.11.9",
+ python_executable="/usr/bin/python3",
+ ffmpeg_version="6.1",
+ )
+ base.update(overrides)
+ return HardwareReport(**base)
+
+
+def _rec() -> WhisperRecommendation:
+ return WhisperRecommendation(
+ provider="faster-whisper",
+ model="base",
+ device="cpu",
+ compute_type="int8",
+ expected_latency_ms=1200,
+ rationale="No CUDA-capable GPU detected.",
+ )
+
+
+# ---------------------------------------------------------------- schema
+
+
+def test_record_rejects_a_status_outside_the_closed_set():
+ with pytest.raises(ValueError, match="vocabulary is closed"):
+ record("brain", "degraded", "…") # type: ignore[arg-type]
+
+
+def test_every_record_carries_exactly_the_declared_fields():
+ for rec in check_records(_report(), _rec()):
+ assert set(rec) == set(FIELDS)
+ assert rec["status"] in STATUSES
+
+
+def test_dumps_emits_one_json_object_per_line():
+ text = dumps(check_records(_report(), _rec()))
+ lines = text.splitlines()
+ assert lines
+ for line in lines:
+ parsed = json.loads(line)
+ assert list(parsed) == list(FIELDS) # field order is part of the contract
+
+
+# ---------------------------------------------------------------- verdicts
+
+
+def test_missing_ffmpeg_is_a_warning_with_an_actionable_hint():
+ recs = {r["component"]: r for r in check_records(_report(ffmpeg_version=None), _rec())}
+ assert recs["ffmpeg"]["status"] == "warn"
+ assert recs["ffmpeg"]["hint"]
+
+
+def test_ram_verdict_uses_the_same_8gb_threshold_as_the_recommendation():
+ # Exactly at the threshold recommend_whisper still chooses local STT.
+ at = {r["component"]: r for r in check_records(_report(ram_total_mb=8192), _rec())}
+ assert at["ram"]["status"] == "ok"
+ below = {r["component"]: r for r in check_records(_report(ram_total_mb=8191), _rec())}
+ assert below["ram"]["status"] == "warn"
+ assert below["ram"]["hint"]
+
+
+def test_an_absent_gpu_is_information_never_a_failure():
+ recs = {r["component"]: r for r in check_records(_report(), _rec())}
+ assert recs["gpu"]["status"] == "info"
+
+
+def test_a_detected_gpu_is_reported_per_device():
+ report = _report(
+ gpus=[
+ GPUInfo(name="NVIDIA A", vram_mb=8000),
+ GPUInfo(name="NVIDIA B", vram_mb=4000, compute_capability="8.6"),
+ ]
+ )
+ recs = {r["component"]: r for r in check_records(report, _rec())}
+ assert recs["gpu0"]["status"] == "ok"
+ assert "8.6" in str(recs["gpu1"]["message"])
+
+
+# ---------------------------------------------------------------- CLI wiring
+
+
+def test_check_json_keeps_exit_code_zero(monkeypatch, capsys):
+ monkeypatch.setattr(jm, "_run_control", lambda argv: pytest.fail("must not route"))
+ assert jm.main(["--check", "--json"]) == 0
+ out = capsys.readouterr().out.strip()
+ assert out
+ for line in out.splitlines():
+ assert json.loads(line)["status"] in STATUSES
+
+
+def test_doctor_json_still_fails_on_a_hard_failure(monkeypatch, capsys):
+ from jarvis.diagnostics.doctor import DoctorFinding
+
+ monkeypatch.setattr(
+ "jarvis.diagnostics.doctor.run_doctor",
+ lambda config: [DoctorFinding("router-tools", "fail", "phantom tool", "fix it")],
+ )
+ assert jm.main(["--doctor", "--json"]) == 1
+ parsed = json.loads(capsys.readouterr().out.strip())
+ assert parsed == {
+ "component": "router-tools",
+ "status": "fail",
+ "message": "phantom tool",
+ "hint": "fix it",
+ }
+
+
+def test_doctor_json_returns_zero_without_failures(monkeypatch, capsys):
+ from jarvis.diagnostics.doctor import DoctorFinding
+
+ monkeypatch.setattr(
+ "jarvis.diagnostics.doctor.run_doctor",
+ lambda config: [DoctorFinding("brain-provider", "warn", "no key", None)],
+ )
+ assert jm.main(["--doctor", "--json"]) == 0
+ assert json.loads(capsys.readouterr().out.strip())["hint"] is None