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.

fix(outputs): preserve legacy mission history

Ruben Lütke656de5185365
diff --git a/jarvis/missions/isolation/worktree.py b/jarvis/missions/isolation/worktree.py
index 9f6a99e727..a6b8a999da 100644
--- a/jarvis/missions/isolation/worktree.py
+++ b/jarvis/missions/isolation/worktree.py
@@ -149,7 +149,9 @@ def resolve_outputs_root(repo_root: Path) -> Path:
Prefers ``<repo_root>.parent/jarvis-agent-outputs/`` (post-rename, 2026-06-29).
Falls back to ``<repo_root>.parent/sub-agents-outputs/`` when that old directory
exists AND the new one does NOT — this keeps existing missions readable without
- any migration step. Does NOT create the directory; callers are responsible.
+ any migration step. Read surfaces that need retained history from both locations
+ use :func:`resolve_readable_outputs_roots`. Does NOT create the directory;
+ callers are responsible.
"""
explicit_root = os.environ.get("JARVIS_ISOLATION_ROOT", "").strip()
if explicit_root:
@@ -167,6 +169,31 @@ def resolve_outputs_root(repo_root: Path) -> Path:
return new_dir
+def resolve_readable_outputs_roots(repo_root: Path) -> tuple[Path, ...]:
+ """Return output roots that may contain user-visible mission history.
+
+ New missions still use :func:`resolve_outputs_root` as their single write
+ location. During the directory-name transition, however, both the canonical
+ ``jarvis-agent-outputs`` directory and the legacy ``sub-agents-outputs``
+ directory can exist at the same time. Read surfaces must include both or
+ creating the canonical directory makes every retained legacy mission vanish
+ from the UI.
+
+ Explicit isolation and application-data roots remain strictly isolated and
+ never scan a sibling directory.
+ """
+ primary = resolve_outputs_root(repo_root)
+ if os.environ.get("JARVIS_ISOLATION_ROOT", "").strip():
+ return (primary,)
+ if os.environ.get("JARVIS_DATA_DIR", "").strip():
+ return (primary,)
+
+ legacy = repo_root.resolve().parent / "sub-agents-outputs"
+ if legacy.is_dir() and legacy != primary:
+ return (primary, legacy)
+ return (primary,)
+
+
class WorktreeManager:
"""Manages `git worktree add/remove` for Phase-6 worker tasks.
diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.py
index 173595cd12..54ecc14e9e 100644
--- a/jarvis/ui/web/outputs_routes.py
+++ b/jarvis/ui/web/outputs_routes.py
@@ -1,7 +1,8 @@
"""REST-API for the Outputs view (`/api/outputs`).
-Lists the per-mission work directories under `<repo_parent>/sub-agents-outputs/`,
-optionally enriched with mission status from the Phase-6 `missions.db`. Read-only.
+Lists the per-mission work directories across the canonical and retained legacy
+output roots, optionally enriched with mission status from the Phase-6
+`missions.db`. Read-only.
Why a thin filesystem endpoint and not a frontend rewrite to `/api/missions`:
the Outputs view was built around the on-disk work directory layout (slug,
@@ -119,6 +120,36 @@ def _outputs_root(request: Request) -> Path:
return resolve_outputs_root(repo_root)
+def _outputs_roots(request: Request) -> tuple[Path, ...]:
+ """Return output roots in read precedence order.
+
+ The mission stack writes to one canonical root but exposes all compatible
+ read roots on app state so retained pre-rename sessions remain visible.
+ Route-only test apps and partial boots keep the historical single-root
+ behavior.
+ """
+ cached = getattr(request.app.state, "outputs_roots", None)
+ if cached:
+ return tuple(Path(root) for root in cached)
+ return (_outputs_root(request),)
+
+
+def _resolve_output_dir(request: Request, slug: str) -> Path:
+ """Resolve a session directory across all readable roots, safely."""
+ invalid_slug = False
+ for candidate_root in _outputs_roots(request):
+ root = candidate_root.resolve()
+ target = (root / slug).resolve()
+ if not target.is_relative_to(root):
+ invalid_slug = True
+ continue
+ if target.is_dir():
+ return target
+ if invalid_slug:
+ raise HTTPException(status_code=400, detail="invalid slug")
+ raise HTTPException(status_code=404, detail=f"unknown slug: {slug}")
+
+
def _parse_slug(name: str) -> dict[str, Any]:
"""Pull started_at + utterance + short_id out of the directory name.
@@ -451,19 +482,28 @@ async def list_outputs(request: Request) -> OutputsResponse:
(None otherwise) — the frontend needs it to POST
`/api/missions/{id}/cancel` for the hold-to-abort affordance.
"""
- root = _outputs_root(request)
- if not root.is_dir():
- return OutputsResponse(sessions=[])
-
- try:
- entries = sorted(
- (p for p in root.iterdir() if p.is_dir()),
- key=lambda p: p.name,
- reverse=True,
- )
- except OSError as exc:
- logger.warning("outputs: listdir failed for %s: %s", root, exc)
+ entries_by_name: dict[str, Path] = {}
+ read_errors: list[OSError] = []
+ readable_root_found = False
+ for root in _outputs_roots(request):
+ if not root.is_dir():
+ continue
+ try:
+ root_entries = [path for path in root.iterdir() if path.is_dir()]
+ except OSError as exc:
+ logger.warning("outputs: listdir failed for %s: %s", root, exc)
+ read_errors.append(exc)
+ continue
+ readable_root_found = True
+ for entry in root_entries:
+ # Roots are ordered canonical-first. A duplicate slug therefore
+ # resolves to the current canonical copy on every detail endpoint.
+ entries_by_name.setdefault(entry.name, entry)
+
+ if not readable_root_found and read_errors:
+ exc = read_errors[0]
raise HTTPException(status_code=500, detail=f"Outputs root not readable: {exc}") from exc
+ entries = sorted(entries_by_name.values(), key=lambda path: path.name, reverse=True)
sessions: list[dict[str, Any]] = []
# Map dir-name → mission-id prefix derived from the dir-name itself.
@@ -623,10 +663,7 @@ async def get_output_plan(slug: str, request: Request) -> dict[str, Any]:
treats that as "no plan available" and the user sees the session metadata
plus the "open in Explorer" button.
"""
- root = _outputs_root(request)
- target = root / slug
- if not target.is_dir():
- raise HTTPException(status_code=404, detail=f"unknown slug: {slug}")
+ _resolve_output_dir(request, slug)
return {"plan": None, "steps": []}
@@ -689,12 +726,7 @@ def _resolve_artifact_target(request: Request, slug: str, path: str) -> Path:
never confirming a scaffolding file exists) on any violation. Used by the
download/view/reveal/open-native routes.
"""
- root = _outputs_root(request).resolve()
- base = (root / slug).resolve()
- try:
- base.relative_to(root)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail="invalid slug") from exc
+ base = _resolve_output_dir(request, slug)
target = (base / path).resolve()
try:
rel_parts = target.relative_to(base).parts
@@ -771,14 +803,7 @@ async def list_output_artifacts(slug: str, request: Request) -> dict[str, Any]:
]
}
"""
- root = _outputs_root(request).resolve()
- target = (root / slug).resolve()
- try:
- target.relative_to(root)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail="invalid slug") from exc
- if not target.is_dir():
- raise HTTPException(status_code=404, detail=f"unknown slug: {slug}")
+ target = _resolve_output_dir(request, slug)
files: list[dict[str, Any]] = []
try:
@@ -836,12 +861,7 @@ async def get_output_artifact_raw(slug: str, path: str, request: Request) -> dic
listing endpoint; calling this on a non-text file returns a base64
placeholder rather than raw bytes (UI can't render anyway).
"""
- root = _outputs_root(request).resolve()
- base = (root / slug).resolve()
- try:
- base.relative_to(root)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail="invalid slug") from exc
+ base = _resolve_output_dir(request, slug)
target = (base / path).resolve()
try:
rel_parts = target.relative_to(base).parts
@@ -1189,14 +1209,7 @@ async def open_output(slug: str, request: Request) -> dict[str, Any]:
Best-effort, non-blocking — frontend ignores errors. Restricts the path
inside `outputs_root` so a crafted slug can't open arbitrary folders.
"""
- root = _outputs_root(request).resolve()
- target = (root / slug).resolve()
- try:
- target.relative_to(root)
- except ValueError as exc:
- raise HTTPException(status_code=400, detail="invalid slug") from exc
- if not target.is_dir():
- raise HTTPException(status_code=404, detail=f"unknown slug: {slug}")
+ target = _resolve_output_dir(request, slug)
from jarvis.platform import open_path
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 3e603d7d0f..9d1634b60f 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -2428,11 +2428,15 @@ class WebServer:
# cleanup_days by mtime, not DB-gated): without this seam an isolated
# headless boot (e.g. scripts/measure_boot.py) would sweep real mission
# outputs older than 14 days.
+ from jarvis.missions.isolation.worktree import (
+ resolve_outputs_root,
+ resolve_readable_outputs_roots,
+ )
+
_iso_override = os.environ.get("JARVIS_ISOLATION_ROOT")
if _iso_override:
isolation_root = Path(_iso_override)
else:
- from jarvis.missions.isolation.worktree import resolve_outputs_root
isolation_root = resolve_outputs_root(repo_root)
# Fail-closed primary-instance gate: POSITIVE proof is required.
@@ -2482,6 +2486,7 @@ class WebServer:
# otherwise have to re-derive the same WEB_DIR.parent.parent.parent
# walk and would silently drift if the launcher layout changes.
self.app.state.outputs_root = isolation_root
+ self.app.state.outputs_roots = resolve_readable_outputs_roots(repo_root)
self._missions_voice_listener = result["voice_listener"]
self._missions_cleanup_task = result["cleanup_task"]
diff --git a/tests/missions/test_outputs_root.py b/tests/missions/test_outputs_root.py
index 2d44f80a97..868225fdc7 100644
--- a/tests/missions/test_outputs_root.py
+++ b/tests/missions/test_outputs_root.py
@@ -2,7 +2,10 @@
from __future__ import annotations
-from jarvis.missions.isolation.worktree import resolve_outputs_root
+from jarvis.missions.isolation.worktree import (
+ resolve_outputs_root,
+ resolve_readable_outputs_roots,
+)
def test_headless_data_dir_keeps_outputs_in_writable_volume(
@@ -33,3 +36,26 @@ def test_checkout_defaults_to_repo_parent_when_no_override(
monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)
assert resolve_outputs_root(repo) == tmp_path / "jarvis-agent-outputs"
+
+
+def test_read_roots_include_retained_legacy_history_when_both_exist(
+ tmp_path, monkeypatch
+) -> None:
+ repo = tmp_path / "repo"
+ canonical = tmp_path / "jarvis-agent-outputs"
+ legacy = tmp_path / "sub-agents-outputs"
+ canonical.mkdir()
+ legacy.mkdir()
+ monkeypatch.delenv("JARVIS_ISOLATION_ROOT", raising=False)
+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)
+
+ assert resolve_readable_outputs_roots(repo) == (canonical, legacy)
+
+
+def test_explicit_read_root_never_scans_a_legacy_sibling(tmp_path, monkeypatch) -> None:
+ explicit = tmp_path / "jarvis-agent-outputs"
+ (tmp_path / "sub-agents-outputs").mkdir()
+ monkeypatch.setenv("JARVIS_ISOLATION_ROOT", str(explicit))
+ monkeypatch.delenv("JARVIS_DATA_DIR", raising=False)
+
+ assert resolve_readable_outputs_roots(tmp_path / "repo") == (explicit.resolve(),)
diff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.py
index 1126d02500..b84cd1b2a6 100644
--- a/tests/unit/ui/web/test_outputs_routes.py
+++ b/tests/unit/ui/web/test_outputs_routes.py
@@ -245,6 +245,64 @@ async def test_list_outputs_empty_root(app: FastAPI) -> None:
assert r.json() == {"sessions": []}
+async def test_list_outputs_includes_legacy_sessions_when_canonical_root_exists(
+ app: FastAPI, tmp_path: Path
+) -> None:
+ """A newly-created canonical root must not hide retained mission history."""
+ canonical = tmp_path / "jarvis-agent-outputs"
+ legacy = tmp_path / "sub-agents-outputs"
+ canonical.mkdir()
+ legacy.mkdir()
+ mission_id = "019e3600-a84e-7000-8000-000000000099"
+ legacy_session = _make_mission_dir(legacy, mission_id)
+ _seed(
+ legacy_session / "tasks" / "task-1" / "artifacts" / "files" / "report.md",
+ "legacy output",
+ )
+ app.state.outputs_root = canonical
+ app.state.outputs_roots = (canonical, legacy)
+
+ with TestClient(app) as client:
+ listing = client.get("/api/outputs")
+ artifacts = client.get(f"/api/outputs/{legacy_session.name}/artifacts")
+
+ assert listing.status_code == 200
+ assert [session["slug"] for session in listing.json()["sessions"]] == [
+ legacy_session.name
+ ]
+ assert artifacts.status_code == 200
+ assert [item["path"] for item in artifacts.json()["files"]] == [
+ "tasks/task-1/artifacts/files/report.md"
+ ]
+
+
+async def test_canonical_root_wins_when_both_roots_contain_the_same_slug(
+ app: FastAPI, tmp_path: Path
+) -> None:
+ canonical = tmp_path / "jarvis-agent-outputs"
+ legacy = tmp_path / "sub-agents-outputs"
+ canonical.mkdir()
+ legacy.mkdir()
+ mission_id = "019e3600-a84e-7000-8000-000000000098"
+ canonical_session = _make_mission_dir(canonical, mission_id)
+ legacy_session = _make_mission_dir(legacy, mission_id)
+ rel = Path("tasks/task-1/artifacts/files/report.md")
+ _seed(canonical_session / rel, "canonical output")
+ _seed(legacy_session / rel, "legacy output")
+ app.state.outputs_root = canonical
+ app.state.outputs_roots = (canonical, legacy)
+
+ with TestClient(app) as client:
+ listing = client.get("/api/outputs")
+ raw = client.get(f"/api/outputs/{canonical_session.name}/files/{rel.as_posix()}/raw")
+
+ assert len(listing.json()["sessions"]) == 1
+ assert raw.status_code == 200
+ assert raw.json()["text"] == "canonical output"
+
+
@pytest.mark.asyncio
async def test_list_outputs_mission_dir_resolves_status_from_db(
app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection