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(missions): support sourceless runtime workspaces

Ruben Lütke1cdf827e540c
diff --git a/docs/adr/0027-portable-mission-isolation-root.md b/docs/adr/0027-portable-mission-isolation-root.md
index 5cec3da1b0..f0967b873b 100644
--- a/docs/adr/0027-portable-mission-isolation-root.md
+++ b/docs/adr/0027-portable-mission-isolation-root.md
@@ -48,7 +48,26 @@ existing bootstrap remains responsible for creation and error reporting.
The official runtime image installs `git`. A distribution image without host
checkout history can therefore run lean artifact tasks in an isolated
standalone repository. Tasks that require the Personal Jarvis source checkout
-still require a real repository and must fail honestly when it is absent.
+still require a real repository. Workspace classification is preserved across
+the deterministic, no-brain, provider-error, and invalid-plan decomposition
+paths; an unavailable decomposition model therefore cannot accidentally turn a
+standalone task into a source task. Older model plans that omit `needs_repo`
+are backfilled from deterministic source-affinity checks, while an explicit
+model claim can never downgrade a clearly source-dependent prompt.
+
+Before creating task scaffolding, the full-worktree path verifies that the
+application root has a real `.git` marker and that `git rev-parse` resolves it
+as the repository root. A copied, frozen, or container application tree raises
+the distinct `source_checkout_unavailable` capability failure. It never falls
+through to the read-only application tree and is not described as a broken ZIP
+installation. The lean path deliberately skips this source probe and runs
+entirely under the writable isolation root.
+
+Boot cleanup uses the same distinction. When the application root has no
+source checkout, it skips the nonexistent host worktree registry without a
+warning and still age-sweeps leaked standalone run directories from the data
+volume. A source-less runtime therefore does not accumulate abandoned lean
+repositories merely because `git worktree list` is unavailable at `/app`.
The container sets `HOME=/app/data/home` and creates that directory before
dropping privileges. Per-user skills, CLI metadata, documents, and related
@@ -63,6 +82,10 @@ trying to create an undeclared `/home/jarvis` tree.
runtime state.
- Headless skill and CLI registries retain a writable per-user home and no
longer disappear behind caught `PermissionError` exceptions.
+- Repository-independent missions remain runnable when decomposition falls
+ back because a planning provider is unavailable or returns invalid output.
+- Source-dependent missions fail before worker startup with an explicit
+ capability reason; no task directory or unisolated source edit is attempted.
- Desktop checkout layouts and legacy output discovery remain unchanged when
neither environment override is present.
- The container image grows by the system `git` package and its runtime
@@ -87,5 +110,5 @@ trying to create an undeclared `/home/jarvis` tree.
- Keep a non-root container smoke test that verifies the resolved output root,
creates a lean workspace, and reaches the health endpoint.
- Keep checkout-mode tests for the repo-parent and legacy output paths.
-- Surface an explicit capability error for source-dependent tasks when the
- installed runtime has no host repository history.
+- Keep decomposition tests that prove provider failures preserve standalone
+ workspace classification and cannot downgrade a source task.
diff --git a/jarvis/missions/isolation/__init__.py b/jarvis/missions/isolation/__init__.py
index ef085142d9..8a4c5a5150 100644
--- a/jarvis/missions/isolation/__init__.py
+++ b/jarvis/missions/isolation/__init__.py
@@ -16,10 +16,11 @@ from __future__ import annotations
from .env import build_worker_env
from .job_object import WindowsJobObject
-from .worktree import WorktreeManager
+from .worktree import SourceCheckoutUnavailableError, WorktreeManager
__all__ = [
"WindowsJobObject",
+ "SourceCheckoutUnavailableError",
"WorktreeManager",
"build_worker_env",
]
diff --git a/jarvis/missions/isolation/worktree.py b/jarvis/missions/isolation/worktree.py
index 88ea9eee3f..c236c16d83 100644
--- a/jarvis/missions/isolation/worktree.py
+++ b/jarvis/missions/isolation/worktree.py
@@ -62,6 +62,25 @@ _SLUG_RE = re.compile(r"[^a-z0-9]+")
BASE_SHA_SIDECAR: str = ".mission_base_sha"
+class SourceCheckoutUnavailableError(RuntimeError):
+ """The installed application tree is not a usable source checkout.
+
+ Lean missions do not need the Personal Jarvis checkout and never raise
+ this error. A source-dependent mission does: silently treating copied
+ package files as a repository would either make ``git worktree add`` fail
+ later or tempt a worker to edit the read-only application tree directly.
+ """
+
+ def __init__(self, repo_root: Path) -> None:
+ self.repo_root = repo_root
+ super().__init__(
+ "This Jarvis-Agent task requires the Personal Jarvis source "
+ "checkout, but this installation only contains application "
+ "files without Git history. Repository-independent tasks remain "
+ "available in isolated workspaces."
+ )
+
+
def read_worktree_base_sha(workspace: Path) -> str | None:
"""Return the recorded base commit SHA for a worktree, or ``None``.
@@ -206,6 +225,8 @@ class WorktreeManager:
Raises:
ValueError: when the path exceeds 200 chars (path-length cap).
+ SourceCheckoutUnavailableError: when ``needs_repo=True`` but the
+ installed application tree is not a real source checkout.
subprocess.CalledProcessError: when `git worktree add` (full mode)
or `git init`/the initial commit (lean mode) fails.
@@ -232,17 +253,26 @@ class WorktreeManager:
self._outputs_root / run_dir_name / "tasks" / task_dir_name / "workspace"
)
+ # Source capability is independent of the selected output path. Check
+ # it first so copied/frozen installs report the actionable missing-
+ # checkout reason even when a custom isolation root is also too long.
+ if needs_repo:
+ self._require_source_checkout()
+
if len(str(workspace)) > _MAX_WORKTREE_PATH_LEN:
raise ValueError(
f"Worktree path is too long ({len(str(workspace))} > "
f"{_MAX_WORKTREE_PATH_LEN}): {workspace}"
)
- workspace.parent.mkdir(parents=True, exist_ok=True)
-
if not needs_repo:
+ workspace.parent.mkdir(parents=True, exist_ok=True)
return self._create_lean(workspace, branch_hint=task_part)
+ # The capability probe above established that this is a real source
+ # checkout. Only now may full-worktree scaffolding be created.
+ workspace.parent.mkdir(parents=True, exist_ok=True)
+
branch_name = f"agent/{task_part}-{short_uuid}"
cmd = [
@@ -310,6 +340,35 @@ class WorktreeManager:
self._write_base_sha(workspace)
return workspace
+ def _require_source_checkout(self) -> None:
+ """Raise early unless ``repo_root`` is a real Git working tree.
+
+ ``.git`` may be either a directory (main checkout) or a file (linked
+ worktree), so existence is the portable structural pre-check. The
+ ``rev-parse`` probe then rejects a stale or synthetic marker before a
+ task directory is created. A missing Git executable retains the
+ existing ``FileNotFoundError`` path so the caller can report the more
+ specific ``git_missing`` capability reason.
+ """
+ if shutil.which("git") is None:
+ raise FileNotFoundError(2, "Git executable was not found", "git")
+
+ if not (self._repo_root / ".git").exists():
+ raise SourceCheckoutUnavailableError(self._repo_root)
+
+ try:
+ result = self._run_git(["git", "rev-parse", "--show-toplevel"])
+ except subprocess.CalledProcessError as exc:
+ raise SourceCheckoutUnavailableError(self._repo_root) from exc
+
+ raw_top = (result.stdout or "").strip()
+ try:
+ top = Path(raw_top).resolve(strict=False)
+ except OSError as exc:
+ raise SourceCheckoutUnavailableError(self._repo_root) from exc
+ if not raw_top or top != self._repo_root:
+ raise SourceCheckoutUnavailableError(self._repo_root)
+
def _write_base_sha(self, workspace: Path) -> None:
"""Persist the worktree's base commit SHA next to (not inside) the tree.
@@ -503,14 +562,26 @@ class WorktreeManager:
)
report["skipped_no_git"] = 1
return report
- try:
- self.prune_orphans()
- report["pruned"] = 1
- # OSError (incl. FileNotFoundError if git vanishes mid-run) as well as a
- # non-zero git exit must never escape this best-effort housekeeping path.
- except (subprocess.CalledProcessError, OSError) as exc:
- logger.warning("prune_and_sweep_leaked: prune failed: %s", exc)
- report["errors"] += 1
+ has_source_checkout = (self._repo_root / ".git").exists()
+ if has_source_checkout:
+ try:
+ self.prune_orphans()
+ report["pruned"] = 1
+ # OSError (including FileNotFoundError if git vanishes mid-run) and
+ # a non-zero exit must not escape best-effort housekeeping.
+ except (subprocess.CalledProcessError, OSError) as exc:
+ logger.warning("prune_and_sweep_leaked: prune failed: %s", exc)
+ report["errors"] += 1
+ else:
+ # Copied/frozen/container installations can only create standalone
+ # lean repos. There is no host worktree registry to prune or query;
+ # continue to the age-based run-directory sweep with an empty
+ # active set instead of logging a false Git error on every boot.
+ logger.info(
+ "WorktreeManager.prune_and_sweep_leaked: source checkout "
+ "unavailable — host worktree registry skipped"
+ )
+ report["skipped_no_source_checkout"] = 1
if not self._outputs_root.is_dir():
return report
@@ -518,25 +589,24 @@ class WorktreeManager:
# Build the set of paths git currently considers a worktree.
# `git worktree list --porcelain` emits "worktree <path>" lines.
active_paths: set[Path] = set()
- try:
- out = self._run_git(["git", "worktree", "list", "--porcelain"])
- for line in out.stdout.splitlines():
- if line.startswith("worktree "):
- p = Path(line[len("worktree "):].strip()).resolve()
- active_paths.add(p)
- # Layout: outputs_root / <run-dir> / tasks / <task-id> /
- # workspace. So workspace.parent.parent.parent IS the
- # run-dir, and one level up is outputs_root. Record the
- # run-dir so we never wipe a run-dir that still has a
- # live worktree underneath it.
- if p.parent.parent.parent.parent == self._outputs_root:
- active_paths.add(p.parent.parent.parent)
- except (subprocess.CalledProcessError, OSError) as exc:
- logger.warning(
- "prune_and_sweep_leaked: worktree list failed: %s", exc,
- )
- report["errors"] += 1
- return report
+ if has_source_checkout:
+ try:
+ out = self._run_git(["git", "worktree", "list", "--porcelain"])
+ for line in out.stdout.splitlines():
+ if line.startswith("worktree "):
+ p = Path(line[len("worktree "):].strip()).resolve()
+ active_paths.add(p)
+ # Layout: outputs_root / <run-dir> / tasks / <task-id> /
+ # workspace. workspace.parent.parent.parent is the
+ # run-dir, and one level up is outputs_root.
+ if p.parent.parent.parent.parent == self._outputs_root:
+ active_paths.add(p.parent.parent.parent)
+ except (subprocess.CalledProcessError, OSError) as exc:
+ logger.warning(
+ "prune_and_sweep_leaked: worktree list failed: %s", exc,
+ )
+ report["errors"] += 1
+ return report
cutoff = time.time() - max_age_hours * 3600.0
for child in self._outputs_root.iterdir():
diff --git a/jarvis/missions/kontrollierer/decomposer.py b/jarvis/missions/kontrollierer/decomposer.py
index 43260a3974..0ebf794830 100644
--- a/jarvis/missions/kontrollierer/decomposer.py
+++ b/jarvis/missions/kontrollierer/decomposer.py
@@ -19,7 +19,8 @@ from __future__ import annotations
import json
import logging
import re
-from typing import Any, Awaitable, Callable, Final, Literal
+from collections.abc import Awaitable, Callable
+from typing import Any, Final, Literal
from pydantic import BaseModel, ConfigDict, Field, ValidationError
@@ -41,7 +42,7 @@ EXTERNAL_SYSTEM_MARKERS: Final[tuple[str, ...]] = (
)
-# Repo-affinity markers — when ANY of these appear in a single-step prompt we
+# Repo-affinity markers — when ANY of these appear in a step prompt we
# keep the full git worktree (needs_repo=True) even though the step would
# otherwise qualify for a lean workspace. This is the conservative guard for
# the lean path: the moment a task smells like it touches THIS repo's code
@@ -50,19 +51,21 @@ EXTERNAL_SYSTEM_MARKERS: Final[tuple[str, ...]] = (
#
# Deliberately a SUPERSET-aware companion to EXTERNAL_SYSTEM_MARKERS (which is
# about *whether* to split into multiple steps); this regex is about *whether*
-# the single step needs the codebase on disk. It never weakens multi-step
-# classification — it is only consulted on the deterministic single-step paths.
+# a step needs the codebase on disk. It never weakens multi-step
+# classification and is the hard guard when an LLM labels source work as lean.
_REPO_AFFINITY_RE: Final = re.compile(
r"""
\b(?:
- repo | repository | repos
- | git | github | gitlab | branch | branches
- | commit | commits | merge | rebase | pull[ -]?request | \bPR\b
+ git | commit | commits | merge | rebase
| pyproject | requirements\.txt | codebase | code[ -]?base
+ | source[ -]?checkout | source[ -]?tree | working[ -]?tree | worktree
| refactor | refactors | refactoring
| bugfix | bug[ -]?fix | hotfix
- | regression | unit[ -]?test | pytest
)\b
+ | \b(?:this|our|current|local|personal[ -]?jarvis)\s+
+ (?:repo(?:sitory)?|code[ -]?base|source|project)\b
+ | \b(?:modify|change|edit|fix|refactor|implement|add|remove|update|test)\b
+ [^.]{0,80}\b(?:repo(?:sitory)?|code[ -]?base|source(?:[ -]?code)?|project[ -]?files?)\b
| \bfix(?:es|ed|ing)?\b[^.]*\bbug\b # "fix the bug", "fixing a nasty bug"
| \bjarvis/ # an in-repo path reference
| \b[\w./-]+\.(?:py|ts|tsx|js|jsx|toml|cfg|ini|yaml|yml|sql|sh|ps1)\b
@@ -70,12 +73,77 @@ _REPO_AFFINITY_RE: Final = re.compile(
re.IGNORECASE | re.VERBOSE,
)
+# Positive evidence that a task can run without the Personal Jarvis checkout.
+# Connected services are remote capabilities; standalone artifacts are lean
+# only when an artifact action and artifact noun occur near each other. This
+# positive-evidence rule is intentional: an ambiguous prompt such as "improve
+# performance" stays source-dependent and fails early in a copied install
+# instead of launching a worker into an empty repository.
+_STANDALONE_SERVICE_RE: Final = re.compile(
+ r"\b(?:"
+ r"github|gitlab|slack|discord|notion|jira|linear|mcp|"
+ r"browser|https?|url|website|web[ -]?page|scrape|crawl|"
+ r"email|calendar|google[ -]?drive|google[ -]?docs|google[ -]?sheets"
+ r")\b",
+ re.IGNORECASE,
+)
+_STANDALONE_ACTION_RE: Final = re.compile(
+ r"\b(?:"
+ r"create|write|draft|generate|prepare|render|make|produce|"
+ r"research|summari[sz]e|compare|list|find|search|"
+ r"erstelle|erstellen|schreibe|" # i18n-allow: German input vocabulary
+ r"schreiben|entwirf|generiere|" # i18n-allow: German input vocabulary
+ r"bereite|rendere|recherchiere|" # i18n-allow: German input vocabulary
+ r"fasse|vergleiche|liste|finde|suche|" # i18n-allow: German input vocabulary
+ r"crea|crear|escribe|escribir|redacta|genera|prepara|"
+ r"renderiza|investiga|resume|compara|lista|busca"
+ r")\b",
+ re.IGNORECASE,
+)
+_STANDALONE_ARTIFACT_RE: Final = re.compile(
+ r"\b(?:"
+ r"standalone|report|summary|document|file|artifact|"
+ r"html|markdown|csv|json|spreadsheet|presentation|slides?|"
+ r"image|video|audio|poster|email|table|checklist|news|weather|"
+ r"datei|bericht|zusammenfassung|" # i18n-allow: German input vocabulary
+ r"dokument|tabelle|nachrichten|wetter|" # i18n-allow: German input vocabulary
+ r"archivo|informe|resumen|documento|tabla|noticias|clima"
+ r")\b",
+ re.IGNORECASE,
+)
+
def _has_repo_affinity(prompt: str) -> bool:
"""True when the prompt points at THIS repo's code (keep full worktree)."""
return _REPO_AFFINITY_RE.search(prompt) is not None
+def _has_standalone_affinity(prompt: str) -> bool:
+ """True when the prompt has positive evidence it needs no source tree."""
+ if _STANDALONE_SERVICE_RE.search(prompt) is not None:
+ return True
+ actions = tuple(_STANDALONE_ACTION_RE.finditer(prompt))
+ artifacts = tuple(_STANDALONE_ARTIFACT_RE.finditer(prompt))
+ return any(
+ abs(action.start() - artifact.start()) <= 120
+ for action in actions
+ for artifact in artifacts
+ )
+
+
+def _workspace_requirement(prompt: str) -> bool | None:
+ """Return True for source, False for lean, or None when ambiguous.
+
+ Source evidence wins over standalone evidence. This makes remote-service
+ tasks portable while keeping ambiguous work fail-closed.
+ """
+ if _has_repo_affinity(prompt):
+ return True
+ if _has_standalone_affinity(prompt):
+ return False
+ return None
+
+
# Type for a brain caller (compatible with BrainManager.generate).
BrainCallerFn = Callable[[str], Awaitable[str]]
@@ -101,14 +169,14 @@ class Step(BaseModel):
# as its workspace. Default True keeps every existing path byte-compatible:
# old persisted plan payloads (which never carried the field) deserialize
# fine, and any step the decomposer does NOT explicitly classify as a lean
- # external-artefact task gets the full, isolated worktree it always had.
+ # external-artifact task gets the full, isolated worktree it always had.
#
# When False the orchestrator hands the worker a LEAN workspace — a fresh
# empty `git init` repo with one initial commit — instead of a checkout of
- # the whole codebase. This is reserved for single-step tasks that produce a
- # standalone deliverable ("create an HTML file with today's news") and have
- # no affinity to this repo's code, where cloning + exploring the repo
- # otherwise burned 10+ minutes and >1.3M input tokens before a trivial
+ # the whole codebase. This is reserved for steps that use connected services
+ # or produce standalone deliverables ("create an HTML file with today's
+ # news") and have no affinity to this repo's code. Cloning and exploring the
+ # repo otherwise burned 10+ minutes and >1.3M input tokens before a trivial
# write (live mission 019eb17d, 2026-06-10).
needs_repo: bool = True
@@ -146,12 +214,12 @@ class MissionDecomposer:
1-Step-Plan, no crash.
"""
if not mission_prompt or not mission_prompt.strip():
- raise ValueError("MissionDecomposer: leerer prompt")
+ raise ValueError("MissionDecomposer: empty prompt")
- # A single step qualifies for a LEAN workspace only when it has no
- # affinity to this repo's code. The default everywhere else is the full
- # worktree (needs_repo=True) — conservative by design.
- lean_eligible = not _has_repo_affinity(mission_prompt)
+ # A single step qualifies for a LEAN workspace only with positive
+ # standalone evidence and no source affinity. Ambiguous prompts keep
+ # the full worktree (needs_repo=True) — conservative by design.
+ lean_eligible = _workspace_requirement(mission_prompt) is False
# Heuristic 1: short prompts are never multi-step
if len(mission_prompt) < SHORT_PROMPT_CHAR_LIMIT:
@@ -168,25 +236,40 @@ class MissionDecomposer:
needs_repo=not lean_eligible,
)
- # LLM-Pfad — Brain not bound -> Fallback Single-Step.
+ # LLM path — Brain not bound -> fallback single-step.
if self._brain is None:
logger.info(
"MissionDecomposer: brain=None, falling back to single-step plan"
)
- return self._single_step_plan(mission_prompt, reason="no_brain_available")
+ return self._single_step_plan(
+ mission_prompt,
+ reason="no_brain_available",
+ needs_repo=not lean_eligible,
+ )
# LLM decomposition
decomposition_prompt = self._build_decomposition_prompt(mission_prompt)
try:
raw = await self._brain(decomposition_prompt)
except Exception: # noqa: BLE001
- logger.warning("MissionDecomposer: brain call raised — fallback single-step", exc_info=True)
- return self._single_step_plan(mission_prompt, reason="brain_error")
+ logger.warning(
+ "MissionDecomposer: brain call raised — fallback single-step",
+ exc_info=True,
+ )
+ return self._single_step_plan(
+ mission_prompt,
+ reason="brain_error",
+ needs_repo=not lean_eligible,
+ )
plan = self._parse_plan(raw, mission_prompt)
if plan is None:
logger.info("MissionDecomposer: parse failed, falling back to single-step")
- return self._single_step_plan(mission_prompt, reason="parse_failed")
+ return self._single_step_plan(
+ mission_prompt,
+ reason="parse_failed",
+ needs_repo=not lean_eligible,
+ )
return plan
@@ -197,11 +280,11 @@ class MissionDecomposer:
) -> MissionPlan:
"""Fallback: entire mission as a single step.
- ``needs_repo`` defaults to True so every non-heuristic fallback
- (no_brain_available, brain_error, parse_failed) stays conservative and
- keeps the full worktree. Only the deterministic ``short_prompt`` and
- ``single_external_target`` heuristics pass ``needs_repo=False`` (and
- only when the prompt has no repo affinity).
+ ``needs_repo`` defaults to True for callers that have not classified a
+ prompt. All built-in paths pass the deterministic repo-affinity result,
+ including no-brain/error/parse fallbacks. This matters in copied or
+ frozen installations: a repository-independent fallback remains
+ runnable in a lean workspace even though no source checkout exists.
"""
slug = _slugify(mission_prompt)[:40] or "task"
return MissionPlan(
@@ -241,7 +324,8 @@ class MissionDecomposer:
'"prompt": "<full instructions for one worker>", '
'"worker_cli": "claude" | "codex", '
'"model": "sonnet" | "opus" | "haiku", '
- '"allowed_tools": "Read,Edit,Write,Bash,Grep,Glob" }\n'
+ '"allowed_tools": "Read,Edit,Write,Bash,Grep,Glob", '
+ '"needs_repo": true | false }\n'
" ],\n"
' "n_workers": <int 1..5>,\n'
' "expected_output": "<one-sentence description of the deliverable>"\n'
@@ -249,6 +333,10 @@ class MissionDecomposer:
"Rules:\n"
"- DO NOT split if tasks share files (race conditions).\n"
"- DO NOT include task_id (auto-generated).\n"
+ "- Set needs_repo=true only when the step must read or modify the "
+ "Personal Jarvis source checkout.\n"
+ "- Set needs_repo=false for research, connected-service actions, "
+ "and standalone artifacts that do not use Personal Jarvis source.\n"
"- Default worker_cli is 'claude'; only use 'codex' for OpenAI-specific work.\n"
"- Default model is 'sonnet'; use 'opus' only for reasoning-heavy steps."
)
@@ -269,6 +357,39 @@ class MissionDecomposer:
if "n_workers" not in data and "steps" in data:
data["n_workers"] = len(data["steps"])
+ # Older model outputs predate ``needs_repo`` and therefore omit it.
+ # Backfill those outputs from deterministic source-affinity rather than
+ # allowing Step's persistence-safe default (True) to disable every
+ # standalone mission in a copied/container distribution. Conversely,
+ # an explicit model-provided False may never override clear source
+ # affinity in either the original mission or the individual step.
+ mission_requirement = _workspace_requirement(mission_prompt)
+ raw_steps = data.get("steps")
+ if isinstance(raw_steps, list):
+ for raw_step in raw_steps:
+ if not isinstance(raw_step, dict):
+ continue
+ step_prompt = raw_step.get("prompt")
+ step_requirement = (
+ _workspace_requirement(step_prompt)
+ if isinstance(step_prompt, str)
+ else None
+ )
+ inferred = (
+ step_requirement
+ if step_requirement is not None
+ else mission_requirement
+ )
+ if inferred is not None:
+ # Deterministic evidence owns the boundary: a model cannot
+ # downgrade source work or unnecessarily disable a clearly
+ # remote/standalone task in a source-less installation.
+ raw_step["needs_repo"] = inferred
+ elif "needs_repo" not in raw_step:
+ # Neither the step nor mission is classifiable. Preserve
+ # the fail-closed persistence default.
+ raw_step["needs_repo"] = True
+
try:
return MissionPlan.model_validate(data)
except ValidationError as exc:
diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.py
index deb273e654..1230aad07c 100644
--- a/jarvis/missions/kontrollierer/orchestrator.py
+++ b/jarvis/missions/kontrollierer/orchestrator.py
@@ -28,9 +28,10 @@ import re
import shutil
import subprocess
import time
+from collections.abc import Callable
from contextlib import suppress
from pathlib import Path
-from typing import Any, Awaitable, Callable, Final, Literal
+from typing import Any, Final, Literal
from ...core.process_utils import NO_WINDOW_CREATIONFLAGS
from ..budget import BudgetExceeded, BudgetTracker
@@ -57,7 +58,11 @@ from ..events import (
WorkerSpawned,
now_ms,
)
-from ..isolation.worktree import WorktreeManager, read_worktree_base_sha
+from ..isolation.worktree import (
+ SourceCheckoutUnavailableError,
+ WorktreeManager,
+ read_worktree_base_sha,
+)
from ..manager import MissionManager
from ..safety import (
extract_worker_authored_text,
@@ -259,9 +264,11 @@ def _classify_worktree_setup_failure(exc: BaseException) -> str:
- ``git_missing``: no git executable on PATH at all
(``FileNotFoundError``/``OSError`` from the subprocess spawn itself).
- - ``git_not_a_repository``: git IS present but ``repo_root`` has no
- ``.git`` (the "Download ZIP" install facet) — ``git worktree add``
- exits 128 with a "not a git repository" stderr.
+ - ``source_checkout_unavailable``: the installed application tree has no
+ usable Git history. This is expected for copied/frozen/container
+ distributions and blocks only source-dependent tasks.
+ - ``git_not_a_repository``: backwards-compatible classification for an
+ older ``git worktree add`` failure carrying "not a git repository".
- ``worktree_setup_failed``: the pre-existing generic fallback for
everything else (200-char path-length cap ``ValueError``, an
index-lock ``CalledProcessError``, etc.) — unchanged behaviour.
@@ -270,6 +277,8 @@ def _classify_worktree_setup_failure(exc: BaseException) -> str:
above falls through to the generic fallback so this is always safe to
call from an except clause.
"""
+ if isinstance(exc, SourceCheckoutUnavailableError):
+ return "source_checkout_unavailable"
if isinstance(exc, FileNotFoundError):
return "git_missing"
if isinstance(exc, subprocess.CalledProcessError):
@@ -812,9 +821,9 @@ class Kontrollierer:
# `_run_task_with_critic_loop` when `WorktreeManager.create()` raises,
# consumed once (popped) by the `SETUP_FAILED` aggregation branch in
# `run_mission` so the terminal reason names the real cause
- # ("git_missing" / "git_not_a_repository") instead of the generic
- # "worktree_setup_failed" fallback. Last write wins, same convention
- # as `_mission_failure_context`.
+ # ("git_missing" / "source_checkout_unavailable") instead of the
+ # generic "worktree_setup_failed" fallback. Last write wins, same
+ # convention as `_mission_failure_context`.
self._setup_failure_reason: dict[str, str] = {}
# Per-mission worker answers for read-only/informational tasks (empty
# diff + tool evidence). Surfaced as MissionApproved.summary_de so the
@@ -1067,9 +1076,9 @@ class Kontrollierer:
# Worktree-create failure (path cap / git index lock / missing git
# binary / no .git repo) — surface an actionable cause instead of
# the generic "worker aborted" (#8). AP-23 wave-2 finding 1: the
- # classified reason (git_missing / git_not_a_repository) set by
- # `_run_task_with_critic_loop`'s except clause takes priority over
- # the pre-existing generic fallback.
+ # classified reason (git_missing / source_checkout_unavailable)
+ # set by `_run_task_with_critic_loop`'s except clause takes
+ # priority over the pre-existing generic fallback.
setup_reason = self._setup_failure_reason.pop(
mission_id, "worktree_setup_failed"
)
@@ -1131,7 +1140,12 @@ class Kontrollierer:
task_id=step.task_id,
needs_repo=step.needs_repo,
)
- except (subprocess.CalledProcessError, ValueError, OSError) as exc:
+ except (
+ SourceCheckoutUnavailableError,
+ subprocess.CalledProcessError,
+ ValueError,
+ OSError,
+ ) as exc:
# OSError added (AP-23 wave-2 finding 1): a missing git binary
# raises FileNotFoundError (an OSError subclass), which used
# to escape uncaught here and crash every mission — even a
diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.py
index a28ae421ec..c7bde96f80 100644
--- a/jarvis/missions/voice/readback.py
+++ b/jarvis/missions/voice/readback.py
@@ -198,6 +198,11 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {
"Jarvis-Agents brauchen einen Git-Checkout, bitte über den " # i18n-allow
"Git-Installer installieren, nicht als ZIP." # i18n-allow
),
+ "source_checkout_unavailable": (
+ "Diese Jarvis-Agent-Aufgabe braucht den " # i18n-allow: German TTS
+ "Quellcode-Checkout, der in dieser " # i18n-allow: German TTS
+ "Installation nicht verfügbar ist." # i18n-allow: German TTS
+ ),
# error_class keys (looked up BEFORE the reason key; see
# failure_phrase_key). Same table so announcer + direct-TTS listener
# cannot drift (2026-05-27 finding #7).
@@ -227,21 +232,30 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {
"Jarvis-Agents require a git checkout (install via the "
"git-based installer, not a ZIP download)."
),
+ "source_checkout_unavailable": (
+ "This Jarvis-Agent task requires the source checkout, which is "
+ "not available in this installation."
+ ),
"provider_auth": "The AI provider sign-in is invalid or expired.",
"provider_quota": "The AI provider's quota is exhausted.",
"provider_unreachable": "The AI provider is currently unreachable.",
"worker_timeout": "The worker hit its time limit.",
},
# Spanish is an equal supported product-surface language (CLAUDE.md §1).
- # Only the two git-setup reason keys added with this fix carry ``es`` for
- # now — the rest of the table is de/en pending a broader translation pass;
- # a missing key here falls back via ``.get(language, {})``.
+ # Only the portable workspace-setup reason keys carry ``es`` for now — the
+ # rest of the table is de/en pending a broader translation pass; a missing
+ # key here falls back via ``.get(language, {})``.
"es": {
"git_missing": "Jarvis-Agents necesitan que git esté instalado y en el PATH.", # i18n-allow: Spanish TTS product-surface phrase
"git_not_a_repository": (
"Jarvis-Agents necesitan una copia de git (instala con el " # i18n-allow: Spanish TTS product-surface phrase
"instalador de git, no con una descarga ZIP)." # i18n-allow: Spanish TTS product-surface phrase
),
+ "source_checkout_unavailable": (
+ "Esta tarea de Jarvis-Agent necesita el " # i18n-allow: Spanish TTS
+ "repositorio del código fuente, que no está " # i18n-allow: Spanish TTS
+ "disponible en esta instalación." # i18n-allow: Spanish TTS
+ ),
},
}
diff --git a/tests/missions/kontrollierer/test_decomposer.py b/tests/missions/kontrollierer/test_decomposer.py
index 84ab4348f2..aa89e1d965 100644
--- a/tests/missions/kontrollierer/test_decomposer.py
+++ b/tests/missions/kontrollierer/test_decomposer.py
@@ -15,7 +15,6 @@ from jarvis.missions.kontrollierer.decomposer import (
Step,
)
-
# --- Pydantic-Schema ---
@@ -94,7 +93,7 @@ async def test_long_prompt_with_one_marker_single_step() -> None:
@pytest.mark.asyncio
async def test_empty_prompt_raises() -> None:
d = MissionDecomposer(brain=None)
- with pytest.raises(ValueError, match="leer"):
+ with pytest.raises(ValueError, match="empty"):
await d.decompose("")
@@ -159,7 +158,7 @@ async def test_llm_path_returns_multi_step_plan() -> None:
@pytest.mark.asyncio
async def test_llm_path_handles_json_in_prose() -> None:
- """The LLM sometimes returns JSON with leading/trailing prose — the decomposer must extract it."""
+ """The decomposer extracts JSON wrapped in model-generated prose."""
async def brain(p: str) -> str:
return f"Sure, here's the plan:\n```json\n{_valid_plan_json()}\n```\nDone."
@@ -184,7 +183,7 @@ async def test_llm_path_invalid_json_falls_back_single() -> None:
@pytest.mark.asyncio
async def test_llm_path_brain_crash_falls_back_single() -> None:
async def brain(p: str) -> str:
- raise RuntimeError("BrainManager kaputt")
+ raise RuntimeError("BrainManager failed")
prompt = "x" * 300 + " " + " ".join(EXTERNAL_SYSTEM_MARKERS[:5])
d = MissionDecomposer(brain=brain)
@@ -289,9 +288,10 @@ async def test_external_artefact_task_is_lean() -> None:
@pytest.mark.asyncio
async def test_german_html_news_task_is_lean() -> None:
- """German external-artefact prompt → lean workspace (no repo markers)."""
+ """German external-artifact prompt → lean workspace (no repo markers)."""
d = MissionDecomposer(brain=None)
- plan = await d.decompose("Erstelle eine HTML-Datei von den aktuellen Tagesnews") # i18n-allow: simulated German user utterance verifying bilingual input handling
+ prompt = "Erstelle eine HTML-Datei von den aktuellen Tagesnews" # i18n-allow: DE input
+ plan = await d.decompose(prompt)
assert len(plan.steps) == 1
assert plan.steps[0].needs_repo is False
@@ -392,3 +392,181 @@ async def test_no_brain_fallback_keeps_full_worktree() -> None:
plan = await d.decompose(prompt)
assert len(plan.steps) == 1
assert plan.steps[0].needs_repo is True
+
+
+async def test_remote_github_issue_summary_is_lean() -> None:
+ """A connected GitHub read is not evidence that local source is needed."""
+ d = MissionDecomposer(brain=None)
+ plan = await d.decompose(
+ "Summarize the open issues in the GitHub repository for me"
+ )
+ assert len(plan.steps) == 1
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_remote_pull_request_review_is_lean() -> None:
+ """Reviewing remote metadata through a connected service needs no clone."""
+ plan = await MissionDecomposer(brain=None).decompose(
+ "Review the open GitHub pull request and summarize its status"
+ )
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_remote_github_test_failure_review_is_lean() -> None:
+ """Generic code nouns do not turn a connected-service read into local work."""
+ plan = await MissionDecomposer(brain=None).decompose(
+ "Review the failing tests in the GitHub repository and summarize them"
+ )
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_ambiguous_task_fails_closed_to_source_workspace() -> None:
+ """Absence of a source keyword is not enough to select an empty repo."""
+ plan = await MissionDecomposer(brain=None).decompose(
+ "Improve performance without changing existing behavior"
+ )
+ assert plan.steps[0].needs_repo is True
+
+
+async def test_spanish_standalone_report_is_lean() -> None:
+ """Workspace classification is locale-neutral across supported input."""
+ plan = await MissionDecomposer(brain=None).decompose(
+ "Crea un informe independiente con una tabla comparativa"
+ )
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_explicit_local_repository_analysis_keeps_full_worktree() -> None:
+ """An explicit reference to the local project remains fail-closed."""
+ d = MissionDecomposer(brain=None)
+ plan = await d.decompose("Analyze this repository's architecture")
+ assert plan.steps[0].needs_repo is True
+
+
+async def test_no_brain_fallback_keeps_standalone_task_lean() -> None:
+ """A source-less install can still run a long connected-service task when
+ the decomposition brain is unavailable. Fallback must preserve the
+ deterministic workspace classification instead of defaulting to a source
+ checkout that the distribution does not contain."""
+ d = MissionDecomposer(brain=None)
+ prompt = (
+ "Research the current product announcements in the browser, prepare "
+ "a detailed standalone report with links and a comparison table, and "
+ "post a concise summary to Slack for the project team. " * 3
+ )
+ assert len(prompt) > SHORT_PROMPT_CHAR_LIMIT
+ plan = await d.decompose(prompt)
+ assert len(plan.steps) == 1
+ assert plan.steps[0].needs_repo is False
+
+
[email protected]("failure_mode", ["brain_error", "parse_error"])
+async def test_llm_failure_keeps_standalone_task_lean(failure_mode: str) -> None:
+ """Brain and parse failures must not turn independent work into a source
+ task merely because the fallback plan has one step."""
+
+ async def brain(_prompt: str) -> str:
+ if failure_mode == "brain_error":
+ raise RuntimeError("provider unavailable")
+ return "not valid JSON"
+
+ prompt = (
+ "Use the browser to research current accessibility guidance, then "
+ "prepare a standalone report and send its short summary to Slack. " * 3
+ )
+ plan = await MissionDecomposer(brain=brain).decompose(prompt)
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_llm_plan_backfills_missing_workspace_requirement() -> None:
+ """Legacy model output without ``needs_repo`` is classified per mission
+ rather than inheriting Step's persistence-safe source default."""
+
+ async def brain(_prompt: str) -> str:
+ return json.dumps(
+ {
+ "steps": [
+ {
+ "slug": "research-release",
+ "prompt": "Research the release and write report.md",
+ }
+ ],
+ "n_workers": 1,
+ }
+ )
+
+ prompt = (
+ "Research the latest release in the browser and send a summary to "
+ "Slack after creating a standalone report. " * 4
+ )
+ plan = await MissionDecomposer(brain=brain).decompose(prompt)
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_llm_cannot_disable_clear_standalone_task() -> None:
+ """A model's over-conservative flag cannot brick a connected-service task
+ on a copied/headless installation."""
+
+ async def brain(_prompt: str) -> str:
+ return json.dumps(
+ {
+ "steps": [
+ {
+ "slug": "summarize-issues",
+ "prompt": "Summarize the open GitHub issues",
+ "needs_repo": True,
+ }
+ ],
+ "n_workers": 1,
+ }
+ )
+
+ prompt = (
+ "Summarize open GitHub issues, compare them with the Jira backlog, "
+ "and post a concise status update to Slack. " * 3
+ )
+ plan = await MissionDecomposer(brain=brain).decompose(prompt)
+ assert plan.steps[0].needs_repo is False
+
+
+async def test_llm_cannot_mark_source_task_as_lean() -> None:
+ """Deterministic source affinity overrides an unsafe model classification."""
+
+ calls: list[str] = []
+
+ async def brain(model_prompt: str) -> str:
+ calls.append(model_prompt)
+ return json.dumps(
+ {
+ "steps": [
+ {
+ "slug": "fix-router",
+ "prompt": "Fix the bug in jarvis/brain/manager.py",
+ "needs_repo": False,
+ }
+ ],
+ "n_workers": 1,
+ }
+ )
+
+ prompt = (
+ "Fix the bug in jarvis/brain/manager.py, commit it on a branch, open "
+ "a GitHub pull request, and link the Jira issue with a Slack update. "
+ "Preserve every existing behavior, add focused regression coverage, "
+ "and explain the verification evidence in the pull request body."
+ )
+ assert len(prompt) > SHORT_PROMPT_CHAR_LIMIT
+ plan = await MissionDecomposer(brain=brain).decompose(prompt)
+ assert len(calls) == 1
+ assert plan.steps[0].needs_repo is True
diff --git a/tests/missions/kontrollierer/test_worktree_setup_failure.py b/tests/missions/kontrollierer/test_worktree_setup_failure.py
index dc0bce8443..db9101ecea 100644
--- a/tests/missions/kontrollierer/test_worktree_setup_failure.py
+++ b/tests/missions/kontrollierer/test_worktree_setup_failure.py
@@ -16,6 +16,7 @@ from pathlib import Path
import pytest
+from jarvis.missions.isolation.worktree import SourceCheckoutUnavailableError
from jarvis.missions.kontrollierer.decomposer import Step
from jarvis.missions.kontrollierer.orchestrator import Kontrollierer, TaskOutcome
@@ -31,7 +32,7 @@ class _PathCapWorktrees:
def create(
self, *, mission_slug: str, task_id: str, needs_repo: bool = True
): # noqa: ANN201
- raise ValueError("Worktree-Pfad zu lang (250 > 200): ...")
+ raise ValueError("Worktree path is too long (250 > 200): ...")
class _GitLockWorktrees:
@@ -71,6 +72,15 @@ class _NotAGitRepositoryWorktrees:
)
+class _SourceCheckoutUnavailableWorktrees:
+ """Simulates a copied/container installation with no source history."""
+
+ def create(
+ self, *, mission_slug: str, task_id: str, needs_repo: bool = True
+ ): # noqa: ANN201
+ raise SourceCheckoutUnavailableError(Path("/app"))
+
+
@pytest.mark.asyncio
async def test_worktree_path_cap_failure_returns_setup_failed(
tmp_path: Path,
@@ -173,3 +183,31 @@ async def test_worktree_not_a_git_repository_yields_zip_install_reason(
assert outcome == TaskOutcome.SETUP_FAILED
assert k._setup_failure_reason["m-no-repo"] == "git_not_a_repository"
+
+
+async def test_source_checkout_capability_failure_is_distinct(
+ tmp_path: Path,
+) -> None:
+ """Copied application files are a supported runtime shape, not a broken
+ ZIP install. Source-dependent missions must surface their own capability
+ reason before a worker is started."""
+ k = object.__new__(Kontrollierer)
+ k._budget = _NoopBudget()
+ k._setup_failure_reason = {}
+ k._worktrees = _SourceCheckoutUnavailableWorktrees()
+
+ outcome = await k._run_task_with_critic_loop(
+ mission_id="m-source-unavailable",
+ mission_prompt="Fix the router source",
+ step=Step(slug="fix-router", prompt="Fix jarvis/brain/manager.py"),
+ mission_dir=tmp_path,
+ reflections=object(),
+ sem=asyncio.Semaphore(1),
+ )
+
+ assert outcome == TaskOutcome.SETUP_FAILED
+ assert (
+ k._setup_failure_reason["m-source-unavailable"]
+ == "source_checkout_unavailable"
+ )
diff --git a/tests/missions/test_voice_readback.py b/tests/missions/test_voice_readback.py
index dd4ae78813..468de54a1e 100644
--- a/tests/missions/test_voice_readback.py
+++ b/tests/missions/test_voice_readback.py
@@ -1,15 +1,12 @@
"""Tests for MissionReadback — DE templates + name-neutral tone + 280-cap."""
from __future__ import annotations
-import pytest
-
from jarvis.missions.voice.readback import (
MAX_VOICE_CHARS,
- MissionReadback,
READBACK_TEMPLATES,
+ MissionReadback,
)
-
# --- Tone-Anchor: name-neutral mission-status templates ---
# The mission-status templates carry NO hardcoded owner name so a fresh
# clone never speaks the maintainer's name. The persona rule still holds:
@@ -124,10 +121,28 @@ def test_render_failed_maps_git_not_a_repository_to_zip_install_phrase() -> None
assert "zip" in out_en.lower(), f"expected the ZIP-install hint, got {out_en!r}"
+def test_render_failed_maps_missing_source_checkout_to_capability_phrase() -> None:
+ """A copied/container install is healthy for standalone missions, so its
+ source-task failure must describe the missing capability rather than tell
+ the user that the installation itself is broken."""
+ rb = MissionReadback()
+ reason = "source_checkout_unavailable"
+
+ out_de = rb.render_failed(reason=reason, language="de")
+ assert reason not in out_de
+ assert "Quellcode" in out_de, f"expected source capability cause, got {out_de!r}"
+
+ out_en = rb.render_failed(reason=reason, language="en")
+ assert reason not in out_en
+ assert "source checkout" in out_en.lower(), (
+ f"expected source capability cause, got {out_en!r}"
+ )
+
+
def test_git_setup_reasons_carry_spanish() -> None:
"""CLAUDE.md §1: Spanish is an equal supported product-surface language,
- so the two new git-setup reason keys must carry an ``es`` phrase — the
- exact lines this fix added must not perpetuate the de/en-only gap."""
+ so every portable workspace-setup reason added here must carry an ``es``
+ phrase rather than perpetuating the de/en-only gap."""
from jarvis.missions.voice.readback import FAILURE_REASON_PHRASES
es = FAILURE_REASON_PHRASES.get("es", {})
@@ -135,10 +150,14 @@ def test_git_setup_reasons_carry_spanish() -> None:
assert "git_not_a_repository" in es, (
"git_not_a_repository missing from the es phrase map"
)
+ assert "source_checkout_unavailable" in es, (
+ "source_checkout_unavailable missing from the es phrase map"
+ )
# Natural Spanish, not a snake_case token or a de/en copy.
assert "git" in es["git_missing"].lower()
assert "git_missing" not in es["git_missing"]
assert "zip" in es["git_not_a_repository"].lower()
+ assert "código" in es["source_checkout_unavailable"].lower()
def test_render_failed_maps_attempts_timed_out_to_honest_timeout_phrase() -> None:
diff --git a/tests/missions/test_worktree.py b/tests/missions/test_worktree.py
index 562409a944..4fecb98f82 100644
--- a/tests/missions/test_worktree.py
+++ b/tests/missions/test_worktree.py
@@ -15,7 +15,10 @@ from pathlib import Path
import pytest
-from jarvis.missions.isolation.worktree import WorktreeManager
+from jarvis.missions.isolation.worktree import (
+ SourceCheckoutUnavailableError,
+ WorktreeManager,
+)
# Skip marker for everything if git is missing (CI cases).
_GIT_AVAILABLE = shutil.which("git") is not None
@@ -62,7 +65,7 @@ def tmp_git_repo(tmp_path: Path) -> Path:
@pytest.fixture
def manager(tmp_git_repo: Path, tmp_path: Path) -> WorktreeManager:
- """WorktreeManager der seine Outputs in tmp_path/outputs ablegt."""
+ """A WorktreeManager that stores its outputs under tmp_path/outputs."""
return WorktreeManager(
repo_root=tmp_git_repo,
outputs_root=tmp_path / "outputs",
@@ -289,8 +292,72 @@ def test_full_create_still_default_when_needs_repo_omitted(
assert (workspace / ".git").is_file() # worktree link FILE, not a dir
+def test_lean_create_works_from_sourceless_application_tree(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Copied/container installs have application files but no ``.git``.
+
+ A repository-independent task must initialize its standalone repository
+ under the writable data volume without invoking Git against the read-only
+ application root.
+ """
+ app_root = tmp_path / "read-only-app"
+ app_root.mkdir()
+ (app_root / "pyproject.toml").write_text("[project]\n", encoding="utf-8")
+ # Keep the writable root above pytest's long per-test directory so the
+ # production 200-character Windows workspace cap is not what this test is
+ # exercising.
+ data_root = tmp_path.parent / "d-lean"
+ monkeypatch.delenv("JARVIS_ISOLATION_ROOT", raising=False)
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(data_root))
+ manager = WorktreeManager(repo_root=app_root)
+
+ def reject_host_git(_cmd: list[str]) -> subprocess.CompletedProcess[str]:
+ raise AssertionError("lean creation must not invoke Git in app_root")
+
+ monkeypatch.setattr(manager, "_run_git", reject_host_git)
+
+ workspace = manager.create(
+ mission_slug="standalone-report",
+ task_id="01-write-report",
+ needs_repo=False,
+ )
+
+ assert workspace.is_relative_to(
+ data_root.resolve() / "jarvis-agent-outputs"
+ )
+ assert (workspace / ".git").is_dir()
+ assert not (workspace / "pyproject.toml").exists()
+ assert _git_out(["rev-parse", "HEAD"], workspace).returncode == 0
+
+
+def test_source_task_fails_before_scaffolding_without_checkout(
+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """Source work must never fall through to a copied application tree."""
+ app_root = tmp_path / "read-only-app"
+ app_root.mkdir()
+ (app_root / "jarvis").mkdir()
+ data_root = tmp_path.parent / "d-source"
+ monkeypatch.delenv("JARVIS_ISOLATION_ROOT", raising=False)
+ monkeypatch.setenv("JARVIS_DATA_DIR", str(data_root))
+ manager = WorktreeManager(repo_root=app_root)
+
+ with pytest.raises(
+ SourceCheckoutUnavailableError,
+ match="requires the Personal Jarvis source checkout",
+ ):
+ manager.create(
+ mission_slug="source-change",
+ task_id="01-fix-router",
+ needs_repo=True,
+ )
+
+ assert not (data_root / "jarvis-agent-outputs").exists()
+
+
def test_create_path_layout_matches_spec(manager: WorktreeManager, tmp_path: Path) -> None:
- """Pfad-Pattern: outputs/<run-dir>/tasks/<NN>__<task-slug>/workspace/."""
+ """Path pattern: outputs/<run-dir>/tasks/<NN>__<task-slug>/workspace/."""
workspace = manager.create(mission_slug="hello", task_id="01-router")
# workspace.parent == .../tasks/<NN>__<slug>
# workspace.parent.parent == .../tasks
@@ -298,7 +365,7 @@ def test_create_path_layout_matches_spec(manager: WorktreeManager, tmp_path: Pat
assert workspace.parent.parent.name == "tasks"
run_dir = workspace.parent.parent.parent
assert run_dir.parent == (tmp_path / "outputs").resolve()
- # run-dir-Name enthaelt die Mission-Slug
+ # The run-directory name includes the mission slug.
assert "hello" in run_dir.name
diff --git a/tests/missions/test_worktree_no_git.py b/tests/missions/test_worktree_no_git.py
index 80e1d0e6dc..6acfbbac50 100644
--- a/tests/missions/test_worktree_no_git.py
+++ b/tests/missions/test_worktree_no_git.py
@@ -10,6 +10,9 @@ git, never raise, and never log a traceback.
"""
from __future__ import annotations
+import os
+import time
+
from jarvis.missions.isolation import worktree as wt
from jarvis.missions.isolation.worktree import WorktreeManager
@@ -34,3 +37,30 @@ def test_sweep_skips_cleanly_when_git_is_absent(tmp_path, monkeypatch) -> None:
assert called["git"] is False, "sweep must not invoke git when git is absent from PATH"
assert report["errors"] == 0
assert report.get("skipped_no_git") == 1
+
+
+def test_sourceless_sweep_skips_host_git_and_cleans_old_lean_run(
+ tmp_path, monkeypatch
+) -> None:
+ """A copied install has Git for lean repos but no host worktree registry."""
+ outputs = tmp_path / "data" / "jarvis-agent-outputs"
+ old_run = outputs / "20260101T000000__report__deadbeef"
+ workspace = old_run / "tasks" / "01-report" / "workspace"
+ (workspace / ".git").mkdir(parents=True)
+ old_time = time.time() - 8 * 3600
+ os.utime(old_run, (old_time, old_time))
+
+ mgr = WorktreeManager(repo_root=tmp_path / "copied-app", outputs_root=outputs)
+ monkeypatch.setattr(wt.shutil, "which", lambda name: "git")
+
+ def reject_host_git(cmd: list[str]): # noqa: ANN202
+ raise AssertionError(f"host Git must not run without a checkout: {cmd}")
+
+ monkeypatch.setattr(mgr, "_run_git", reject_host_git)
+
+ report = mgr.prune_and_sweep_leaked(max_age_hours=6.0)
+
+ assert report["errors"] == 0
+ assert report["skipped_no_source_checkout"] == 1
+ assert report["swept_run_dirs"] == 1
+ assert not old_run.exists()