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.

chore(i18n): mark simulated German user-request test literals with i18n-allow

Ruben Lütkec6c11b8f1b1c
diff --git a/jarvis/ui/web/skills_routes.py b/jarvis/ui/web/skills_routes.py
index 0370cb7177..b3103051b0 100644
--- a/jarvis/ui/web/skills_routes.py
+++ b/jarvis/ui/web/skills_routes.py
@@ -1,16 +1,16 @@
-"""REST-API fuer das Skill-System (Desktop-UI).
+"""REST API for the skill system (desktop UI).
Endpoints:
-- ``GET /api/skills`` → Liste (ohne Body, schlank fuer Sidebar).
-- ``GET /api/skills/{name}`` → Voller Skill inkl. Markdown-Body.
-- ``PUT /api/skills/{name}`` → Body (und optional Frontmatter) updaten.
- Bei Builtin-Skills: ``admin_password`` im Request-Body noetig.
-- ``POST /api/skills/{name}/enable`` → State -> ACTIVE.
-- ``POST /api/skills/{name}/disable`` → State -> DISABLED.
-- ``POST /api/skills/reload`` → Registry.reload() forcen.
-
-Der Router erwartet eine ``SkillRegistry`` auf ``app.state.skill_registry`` — die
-wird vom ``WebServer`` beim Startup gesetzt (nach ``ensure_user_skills_dir()``).
+- ``GET /api/skills`` → list (no body, lean for the sidebar).
+- ``GET /api/skills/{name}`` → full skill incl. Markdown body.
+- ``PUT /api/skills/{name}`` → update body (and optionally frontmatter).
+ For built-in skills: ``admin_password`` is required in the request body.
+- ``POST /api/skills/{name}/enable`` → state -> ACTIVE.
+- ``POST /api/skills/{name}/disable`` → state -> DISABLED.
+- ``POST /api/skills/reload`` → force ``Registry.reload()``.
+
+The router expects a ``SkillRegistry`` on ``app.state.skill_registry`` — it is
+set by the ``WebServer`` at startup (after ``ensure_user_skills_dir()``).
"""
from __future__ import annotations
@@ -59,14 +59,14 @@ def _require_optional_module(module: str, feature: str) -> None:
def _require_registry(request: Request) -> Any:
reg = getattr(request.app.state, "skill_registry", None)
if reg is None:
- raise HTTPException(status_code=503, detail="SkillRegistry nicht verfuegbar")
+ raise HTTPException(status_code=503, detail="SkillRegistry not available")
return reg
def _security_cfg(request: Request) -> Any:
- """Holt die SecurityConfig aus dem app-state. ``None`` wenn Cfg fehlt
- (z.B. in Tests mit Mock-App) — Admin-Checks fallen dann zurueck auf
- "kein Hash gesetzt = Builtin-Edits gesperrt"."""
+ """Fetches the SecurityConfig from app state. ``None`` when the config is
+ missing (e.g. in tests with a mock app) — admin checks then fall back to
+ "no hash set = built-in edits locked"."""
cfg = getattr(request.app.state, "config", None)
if cfg is None:
return None
@@ -82,9 +82,9 @@ def _is_builtin(name: str) -> bool:
def _skill_to_summary(s: Skill) -> dict[str, Any]:
- """Schlanke Repraesentation fuer ``GET /api/skills`` — ohne Body."""
+ """Lean representation for ``GET /api/skills`` — without the body."""
fm = s.frontmatter
- # resources als plain dict mit Listen (statt Tuples) fuer JSON-Serialisation
+ # resources as a plain dict with lists (instead of tuples) for JSON serialization
resources = {k: list(v) for k, v in s.resources.items()}
resource_count = sum(len(v) for v in resources.values())
return {
@@ -103,7 +103,7 @@ def _skill_to_summary(s: Skill) -> dict[str, Any]:
def _skill_to_detail(s: Skill) -> dict[str, Any]:
- """Volles Detail inkl. Body + Frontmatter-Dump."""
+ """Full detail incl. body + frontmatter dump."""
out = _skill_to_summary(s)
out["body"] = s.body
out["body_hash"] = s.body_hash
@@ -112,7 +112,7 @@ def _skill_to_detail(s: Skill) -> dict[str, Any]:
rel = s.path.relative_to(user_skills_dir())
out["path"] = str(rel).replace("\\", "/")
except ValueError:
- # Skill liegt nicht unter user_skills_dir() (z.B. Test-Fixture)
+ # Skill does not live under user_skills_dir() (e.g. a test fixture)
out["path"] = str(s.path)
return out
@@ -135,46 +135,46 @@ def _sort_by_order(skills: list[Skill], order: list[str]) -> list[Skill]:
def _resolve_resource_path(skill: Skill, kind: str, filename: str) -> Path:
- """Loest einen Resource-Pfad und stellt sicher, dass er nicht aus dem
- Skill-Root ausbricht (Path-Traversal-Schutz).
+ """Resolves a resource path and makes sure it does not escape the
+ skill root (path-traversal protection).
- Wirft HTTPException bei unbekanntem Kind, fehlendem Ordner, oder Path-Escape.
+ Raises HTTPException on an unknown kind, a missing folder, or a path escape.
"""
if kind not in RESOURCE_KINDS:
raise HTTPException(
status_code=400,
- detail=f"Unbekannter Resource-Kind '{kind}' (erwartet: {list(RESOURCE_KINDS)})",
+ detail=f"Unknown resource kind '{kind}' (expected: {list(RESOURCE_KINDS)})",
)
kind_root = (skill.root / kind).resolve()
if not kind_root.is_dir():
raise HTTPException(
- status_code=404, detail=f"Ordner '{kind}/' existiert nicht"
+ status_code=404, detail=f"Folder '{kind}/' does not exist"
)
target = (kind_root / filename).resolve()
try:
target.relative_to(kind_root)
except ValueError:
- # Symlink oder `..`-Konstrukt, das ausserhalb des Kind-Roots zeigt
+ # Symlink or `..` construct that points outside the kind root
raise HTTPException(
- status_code=400, detail="Pfad-Traversal ausserhalb des Resource-Ordners"
+ status_code=400, detail="Path traversal outside the resource folder"
)
if not target.is_file():
raise HTTPException(
- status_code=404, detail=f"Datei '{kind}/{filename}' nicht gefunden"
+ status_code=404, detail=f"File '{kind}/{filename}' not found"
)
return target
# ----------------------------------------------------------------------
-# Admin-Pass-Check
+# Admin password check
# ----------------------------------------------------------------------
def _check_admin_pass(provided: str | None, security_cfg: Any) -> bool:
- """Prueft ein Admin-Password gegen ``security.admin_password_hash``.
+ """Checks an admin password against ``security.admin_password_hash``.
- - Kein Hash gesetzt (leerer String) -> immer False (Builtin-Edits gesperrt).
- - Kein Password provided -> False.
- - Sonst: SHA-256 vergleichen, constant-time via ``hmac.compare_digest``.
+ - No hash set (empty string) -> always False (built-in edits locked).
+ - No password provided -> False.
+ - Otherwise: compare SHA-256, constant-time via ``hmac.compare_digest``.
"""
if security_cfg is None:
return False
@@ -190,23 +190,23 @@ def _check_admin_pass(provided: str | None, security_cfg: Any) -> bool:
# ----------------------------------------------------------------------
class SkillUpdateBody(BaseModel):
- """Body fuer ``PUT /api/skills/{name}``.
+ """Body for ``PUT /api/skills/{name}``.
- ``content`` ist die vollstaendige SKILL.md (Frontmatter + Markdown). Der
- Server re-parsed das File in-place, damit die Registry die State-Change
- via Hot-Reload aufnimmt.
+ ``content`` is the complete SKILL.md (frontmatter + Markdown). The
+ server re-parses the file in place so the registry picks up the state
+ change via hot-reload.
"""
content: str
admin_password: str | None = Field(default=None)
class SkillCreateBody(BaseModel):
- """Body fuer ``POST /api/skills`` (neuer User-Skill aus der Desktop-App).
+ """Body for ``POST /api/skills`` (a new user skill from the desktop app).
- Die Felder mappen 1:1 auf die Form im ``SkillCreateDialog`` — Optional-
- Felder werden vom Authoring-Service auf Defaults gemappt (``risk_policy``
- defaultet auf ``{default_tier: "ask"}``, ``body`` auf ein minimales
- Markdown-Geruest).
+ The fields map 1:1 onto the form in ``SkillCreateDialog`` — optional
+ fields are mapped to defaults by the authoring service (``risk_policy``
+ defaults to ``{default_tier: "ask"}``, ``body`` to a minimal Markdown
+ scaffold).
"""
name: str = Field(min_length=3, max_length=64)
description: str = ""
@@ -222,10 +222,10 @@ class SkillCreateBody(BaseModel):
class SkillCreatorDraftBody(BaseModel):
- """Body fuer ``POST /api/skills/creator/draft``.
+ """Body for ``POST /api/skills/creator/draft``.
- ``intent`` ist die eigentliche Nutzerbeschreibung. Die restlichen Felder
- sind optionale UI-Hints, damit der Creator nicht alles erraten muss.
+ ``intent`` is the actual user description. The remaining fields are
+ optional UI hints so the creator doesn't have to guess everything.
"""
intent: str = Field(min_length=3, max_length=4000)
name_hint: str = Field(default="", max_length=100)
@@ -235,7 +235,7 @@ class SkillCreatorDraftBody(BaseModel):
class SkillCreatorRefineBody(SkillCreatorDraftBody):
- """Revision eines bestehenden AI-Drafts mit User-Feedback."""
+ """Revision of an existing AI draft with user feedback."""
draft: dict[str, Any] = Field(default_factory=dict)
feedback: str = Field(default="", max_length=4000)
@@ -273,7 +273,7 @@ class SkillBulkDeleteBody(BaseModel):
class SkillQueryBody(BaseModel):
- """Body fuer ``POST /api/skills/query`` — lokale Skill-Suche mit BM25 + LLM."""
+ """Body for ``POST /api/skills/query`` — local skill search with BM25 + LLM."""
q: str = Field(default="", max_length=500)
category: str | None = None
state: str | None = None # "active" | "validated" | "draft" | "disabled"
@@ -301,10 +301,10 @@ async def list_skills(request: Request) -> dict[str, Any]:
@router.post("")
async def create_skill(body: SkillCreateBody, request: Request) -> dict[str, Any]:
- """Legt einen neuen User-Skill an und gibt die vollstaendige Detail-Repr zurueck.
+ """Creates a new user skill and returns the full detail representation.
- Kollisionen (Name == Builtin oder Name == existierender Skill) werden mit
- 409 abgelehnt. Slug-Verstoss oder ungueltige Frontmatter → 400.
+ Collisions (name == built-in or name == an existing skill) are rejected
+ with 409. A slug violation or invalid frontmatter → 400.
"""
from jarvis.skills.authoring import (
SkillAuthoringError,
@@ -342,7 +342,7 @@ async def create_skill_draft(
body: SkillCreatorDraftBody,
request: Request,
) -> dict[str, Any]:
- """Erzeugt einen AI-Draft, ohne Dateien zu schreiben."""
+ """Generates an AI draft without writing any files."""
_require_optional_module("jarvis.skills.creator_service", "Skill Creator")
from jarvis.skills.creator_service import SkillCreatorInput, SkillCreatorService
@@ -373,7 +373,7 @@ async def refine_skill_draft(
body: SkillCreatorRefineBody,
request: Request,
) -> dict[str, Any]:
- """Ueberarbeitet einen AI-Draft anhand von Feedback/Rueckfragen."""
+ """Revises an AI draft based on feedback / follow-up questions."""
_require_optional_module("jarvis.skills.creator_service", "Skill Creator")
from jarvis.skills.creator_service import SkillCreatorInput, SkillCreatorService
@@ -406,7 +406,7 @@ async def validate_skill_draft(
body: SkillCreatorValidateBody,
request: Request,
) -> dict[str, Any]:
- """Validiert einen Draft oder SKILL.md-Text, ohne zu persistieren."""
+ """Validates a draft or SKILL.md text without persisting it."""
_require_optional_module("jarvis.skills.creator_service", "Skill Creator")
from jarvis.skills.creator_service import render_skill_md, validate_skill_md
@@ -424,7 +424,7 @@ async def commit_skill_draft(
body: SkillCreatorCommitBody,
request: Request,
) -> dict[str, Any]:
- """Persistiert den bestaetigten AI-Draft als User-Skill."""
+ """Persists the confirmed AI draft as a user skill."""
_require_optional_module("jarvis.skills.creator_service", "Skill Creator")
from jarvis.skills.authoring import SkillAuthoringError
from jarvis.skills.creator_service import SkillCreatorService
@@ -451,7 +451,7 @@ def _extract_import_url(value: str) -> str:
if not match:
raise HTTPException(
status_code=400,
- detail="Kein http(s)-Link gefunden. Fuege einen SKILL.md-Link oder einen CLI-Befehl mit Link ein.",
+ detail="No http(s) link found. Paste a SKILL.md link or a CLI command containing a link.",
)
url = match.group(0).rstrip(").,;")
github_blob = re.match(
@@ -466,10 +466,10 @@ def _extract_import_url(value: str) -> str:
@router.post("/import")
async def import_skill(body: SkillImportBody, request: Request) -> dict[str, Any]:
- """Importiert einen Skill aus einem Link oder einem eingefuegten CLI-Befehl.
+ """Imports a skill from a link or a pasted CLI command.
- Der Endpoint akzeptiert absichtlich keinen beliebigen Shell-Command. Aus dem
- Text wird nur der erste http(s)-Link extrahiert und als SKILL.md geladen.
+ The endpoint deliberately does not accept an arbitrary shell command. Only
+ the first http(s) link is extracted from the text and loaded as SKILL.md.
"""
import tempfile
@@ -488,14 +488,14 @@ async def import_skill(body: SkillImportBody, request: Request) -> dict[str, Any
except httpx.HTTPError as exc:
raise HTTPException(
status_code=400,
- detail=f"Download fehlgeschlagen: {exc}",
+ detail=f"Download failed: {exc}",
) from exc
content = resp.text
if "---" not in content[:200]:
raise HTTPException(
status_code=400,
- detail="Der Link sieht nicht wie eine SKILL.md mit YAML-Frontmatter aus.",
+ detail="This link does not look like a SKILL.md with YAML frontmatter.",
)
with tempfile.TemporaryDirectory(prefix="jarvis-skill-import-") as tmp:
@@ -507,14 +507,14 @@ async def import_skill(body: SkillImportBody, request: Request) -> dict[str, Any
if parsed.frontmatter is None:
raise HTTPException(
status_code=400,
- detail=f"SKILL.md konnte nicht gelesen werden: {parsed.error}",
+ detail=f"SKILL.md could not be read: {parsed.error}",
)
name = parsed.name
if name in BUILTIN_SKILL_NAMES:
raise HTTPException(
status_code=409,
- detail=f"'{name}' ist ein Builtin-Skill-Name und kann nicht importiert werden.",
+ detail=f"'{name}' is a built-in skill name and cannot be imported.",
)
try:
reg.get(name)
@@ -523,7 +523,7 @@ async def import_skill(body: SkillImportBody, request: Request) -> dict[str, Any
else:
raise HTTPException(
status_code=409,
- detail=f"Skill '{name}' existiert bereits.",
+ detail=f"Skill '{name}' already exists.",
)
target_dir = user_skills_dir() / name
@@ -536,7 +536,7 @@ async def import_skill(body: SkillImportBody, request: Request) -> dict[str, Any
except OSError as exc:
raise HTTPException(
status_code=500,
- detail=f"Konnte Skill nicht schreiben: {exc}",
+ detail=f"Could not write skill: {exc}",
) from exc
installed = parse_skill(target_file)
@@ -661,7 +661,7 @@ async def update_skill(
body: SkillUpdateBody,
request: Request,
) -> dict[str, Any]:
- """Schreibt die SKILL.md neu. Bei Builtin-Skills wird der Admin-Pass geprueft."""
+ """Rewrites the SKILL.md. For built-in skills the admin password is checked."""
reg = _require_registry(request)
try:
skill = reg.get(name)
@@ -672,11 +672,11 @@ async def update_skill(
if not _check_admin_pass(body.admin_password, _security_cfg(request)):
raise HTTPException(
status_code=403,
- detail="Builtin-Skill darf nur mit gueltigem Admin-Password bearbeitet werden.",
+ detail="A built-in skill can only be edited with a valid admin password.",
)
- # Atomar schreiben: temp-file + rename, damit der Watcher keinen halb
- # geschriebenen Zwischenstand liest.
+ # Write atomically: temp file + rename, so the watcher never reads a
+ # half-written intermediate state.
target: Path = skill.path
tmp = target.with_suffix(target.suffix + ".tmp")
try:
@@ -684,11 +684,11 @@ async def update_skill(
tmp.replace(target)
except OSError as exc:
raise HTTPException(
- status_code=500, detail=f"Konnte Skill nicht schreiben: {exc}"
+ status_code=500, detail=f"Could not write skill: {exc}"
) from exc
- # Sofort re-parsen + in Registry ersetzen, damit der Response den neuen State
- # zeigt (der watchdog-Hotreload macht danach dasselbe, aber async).
+ # Re-parse immediately + replace in the registry, so the response shows the
+ # new state (the watchdog hot-reload does the same afterward, but async).
updated = parse_skill(target)
reg._skills[name] = updated # type: ignore[attr-defined]
return _skill_to_detail(updated)
@@ -713,11 +713,11 @@ async def reload_registry(request: Request) -> dict[str, Any]:
@router.get("/{name}/link-health")
async def get_skill_link_health(name: str, request: Request) -> dict[str, Any]:
- """Prueft die URLs (homepage/source/docs) eines Skills.
+ """Checks a skill's URLs (homepage/source/docs).
- Stale-While-Revalidate: ist ein Cache-Eintrag vorhanden (auch wenn stale),
- wird er sofort zurueckgegeben — zugleich laeuft ein Refresh im Hintergrund.
- Das sorgt dafuer, dass die UI nie auf HEAD-Requests wartet.
+ Stale-while-revalidate: if a cache entry exists (even if stale), it is
+ returned immediately — a refresh runs in the background at the same time.
+ This ensures the UI never waits on HEAD requests.
"""
_require_optional_module("jarvis.skills.link_health", "Skill link-health check")
from jarvis.skills.link_health import LinkHealthChecker
@@ -738,7 +738,7 @@ async def get_skill_link_health(name: str, request: Request) -> dict[str, Any]:
"docs_url": fm.docs_url,
}
- # Checker pro App-State cachen, damit die SQLite-Connection wiederverwendet wird
+ # Cache the checker per app state, so the SQLite connection is reused
checker = getattr(request.app.state, "_link_health_checker", None)
if checker is None:
checker = LinkHealthChecker()
@@ -752,7 +752,7 @@ async def get_skill_link_health(name: str, request: Request) -> dict[str, Any]:
continue
cached = checker.read_cached(url)
if cached is None:
- # Cache-Miss — synchroner Check (einmalig, schnell)
+ # Cache miss — synchronous check (one-off, fast)
status = await checker.check_url(url)
out[field_name] = status.to_dict()
else:
@@ -760,8 +760,8 @@ async def get_skill_link_health(name: str, request: Request) -> dict[str, Any]:
if not cached.fresh:
stale_urls.append(url)
- # Stale-Eintraege im Hintergrund refreshen — der aktuelle Response enthaelt
- # den alten Wert mit fresh=False, der naechste Call sieht den neuen.
+ # Refresh stale entries in the background — the current response contains
+ # the old value with fresh=False; the next call will see the new one.
if stale_urls:
asyncio.create_task(checker.check_all(stale_urls, force=True))
@@ -772,11 +772,11 @@ async def get_skill_link_health(name: str, request: Request) -> dict[str, Any]:
async def get_skill_resource(
name: str, kind: str, filename: str, request: Request
) -> PlainTextResponse:
- """Liefert den Content eines Bundle-Resource-Files (Text-only, UTF-8).
+ """Returns the content of a bundled resource file (text-only, UTF-8).
- Binaer-Files (Icons, Audio) werden aktuell nicht unterstuetzt — die UI
- kann sie aus der Liste zeigen, aber nicht rendern. Anzeige fuer Bilder
- waere ein spaeterer Ausbau via separatem Media-Endpoint.
+ Binary files (icons, audio) are currently not supported — the UI can show
+ them in the list but not render them. Displaying images would be a later
+ extension via a separate media endpoint.
"""
reg = _require_registry(request)
try:
@@ -790,7 +790,7 @@ async def get_skill_resource(
except UnicodeDecodeError:
raise HTTPException(
status_code=415,
- detail=f"Datei '{kind}/{filename}' ist nicht UTF-8-Text (binaer?)",
+ detail=f"File '{kind}/{filename}' is not UTF-8 text (binary?)",
)
return PlainTextResponse(content=text, media_type="text/plain; charset=utf-8")
@@ -804,12 +804,12 @@ def _flip_state(
except KeyError:
raise HTTPException(status_code=404, detail=f"Skill '{name}' not found")
- # DRAFT bleibt DRAFT — man kann einen kaputten Skill nicht aktivieren.
+ # DRAFT stays DRAFT — a broken skill can't be activated.
if skill.state == SkillLifecycleState.DRAFT:
raise HTTPException(
status_code=409,
- detail=f"Skill '{name}' ist im DRAFT-State (Fehler: {skill.error}) — "
- "erst reparieren.",
+ detail=f"Skill '{name}' is in DRAFT state (error: {skill.error}) — "
+ "fix it first.",
)
updated = replace(skill, state=new_state)
@@ -824,15 +824,15 @@ def _flip_state(
# ----------------------------------------------------------------------
-# Skill-Finder (Catalog-Search + Install)
+# Skill finder (catalog search + install)
# ----------------------------------------------------------------------
class SkillSearchBody(BaseModel):
- """Body fuer ``POST /api/skills/catalog/search``.
+ """Body for ``POST /api/skills/catalog/search``.
- Die Felder mappen 1:1 auf das Dropdown-Menue im SkillFinder-Dialog.
- Alle bis auf ``query`` sind optional — ohne Filter matcht gegen den
- kompletten Katalog.
+ The fields map 1:1 onto the dropdown menu in the SkillFinder dialog.
+ All fields except ``query`` are optional — without a filter it matches
+ against the full catalog.
"""
query: str = Field(default="", max_length=500)
trust: str = Field(default="any") # "any" | "official" | "verified" | "community" | "experimental"
@@ -844,12 +844,12 @@ class SkillSearchBody(BaseModel):
class SkillInstallBody(BaseModel):
- """Body fuer ``POST /api/skills/catalog/install``.
+ """Body for ``POST /api/skills/catalog/install``.
- Der Client schickt den vollstaendigen Kandidaten zurueck (und nicht nur
- den Namen), damit der Server nicht nochmal den Katalog durchsuchen muss
- und der User-Intent stabil bleibt, selbst wenn der Katalog zwischen Such-
- und Install-Call aktualisiert wird.
+ The client sends back the full candidate (not just the name), so the
+ server doesn't have to search the catalog again and the user's intent
+ stays stable even if the catalog is updated between the search and the
+ install call.
"""
name: str
raw_url: str | None = None
@@ -861,12 +861,12 @@ class SkillInstallBody(BaseModel):
async def query_local_skills(
body: SkillQueryBody, request: Request
) -> dict[str, Any]:
- """Lokale Skill-Suche: BM25 + optionales LLM-Re-Ranking.
+ """Local skill search: BM25 + optional LLM re-ranking.
- Mit leerer Query laeuft der Endpoint als reiner Filter-Router fuer Sidebar-
- Filter (Kategorie/State/Risk/Builtin-Toggle/Tags). Mit Query wird zunaechst
- FTS5-BM25 gegen den in-memory Skill-Index gefahren, dann (bei ausreichend
- vielen Tokens + verfuegbarem Brain) ein LLM-Rerank der Top-15.
+ With an empty query the endpoint acts as a pure filter router for sidebar
+ filters (category/state/risk/built-in toggle/tags). With a query, FTS5-BM25
+ runs first against the in-memory skill index, then (given enough tokens and
+ an available brain) an LLM rerank of the top 15.
"""
from jarvis.skills.local_search import (
LocalSearchFilters,
@@ -876,15 +876,15 @@ async def query_local_skills(
reg = _require_registry(request)
brain = getattr(request.app.state, "brain", None)
- # Cache pro App-State: LocalSkillSearch haelt den FTS5-Index in-memory.
- # Wir haengen die Instanz an app.state, damit sie zwischen Requests wieder-
- # verwendet wird (sonst muessten wir den Index pro Request neu bauen).
+ # Cache per app state: LocalSkillSearch keeps the FTS5 index in memory.
+ # We attach the instance to app.state so it's reused across requests
+ # (otherwise we'd have to rebuild the index on every request).
searcher = getattr(request.app.state, "_local_skill_search", None)
if searcher is None or searcher._registry is not reg:
searcher = LocalSkillSearch(registry=reg, brain=brain)
request.app.state._local_skill_search = searcher
else:
- # Brain kann sich zwischen Requests aendern (z.B. nach Provider-Switch)
+ # The brain can change between requests (e.g. after a provider switch)
searcher._brain = brain
filters = LocalSearchFilters(
@@ -899,11 +899,11 @@ async def query_local_skills(
try:
hits, brain_used = await searcher.query(filters)
except Exception as exc: # noqa: BLE001
- raise HTTPException(status_code=500, detail=f"Query fehlgeschlagen: {exc}") from exc
+ raise HTTPException(status_code=500, detail=f"Query failed: {exc}") from exc
- # Fuer jeden Hit das volle Summary zurueckgeben, damit die UI dieselben
- # Objekte wie in der normalen Liste rendern kann (keine separate
- # Sub-Komponente fuer Search-Ergebnisse).
+ # Return the full summary for every hit, so the UI can render the same
+ # objects as in the normal list (no separate sub-component for search
+ # results).
results: list[dict[str, Any]] = []
for hit in hits:
try:
@@ -927,16 +927,16 @@ async def query_local_skills(
async def search_catalog(
body: SkillSearchBody, request: Request
) -> dict[str, Any]:
- """Semantisch-gerankte Suche im Skill-Katalog.
+ """Semantically ranked search over the skill catalog.
- Wenn ``app.state.brain`` gesetzt ist, nutzt der Finder das Brain fuer
- Ranking. Ohne Brain fallback auf heuristisches Token-Matching — die Suche
- funktioniert also auch im Headless-Mode ohne Credentials.
+ If ``app.state.brain`` is set, the finder uses the brain for ranking.
+ Without a brain it falls back to heuristic token matching — so search
+ still works in headless mode without credentials.
"""
brain = getattr(request.app.state, "brain", None)
finder = SkillFinder(brain=brain)
- # Typ-Konversion: Pydantic erlaubt nicht Literal-Union direkt als Query-Param
+ # Type conversion: Pydantic doesn't allow a Literal union directly as a query param
trust_val: Any = body.trust if body.trust in ("any", "official", "verified", "community", "experimental") else "any"
filters = SearchFilters(
@@ -952,7 +952,7 @@ async def search_catalog(
try:
candidates = await finder.search(filters)
except Exception as exc: # noqa: BLE001
- raise HTTPException(status_code=500, detail=f"Suche fehlgeschlagen: {exc}") from exc
+ raise HTTPException(status_code=500, detail=f"Search failed: {exc}") from exc
return {
"query": body.query,
@@ -966,17 +966,17 @@ async def search_catalog(
async def install_from_catalog(
body: SkillInstallBody, request: Request
) -> dict[str, Any]:
- """Installiert einen Skill aus dem Katalog.
+ """Installs a skill from the catalog.
- Schritte:
- 1. Datei per ``httpx`` aus ``raw_url`` holen (oder abbrechen wenn None).
- 2. In ``<user_skills>/<name>/SKILL.md`` ablegen.
- 3. Registry re-parsen + hot-swap einfuegen, damit die UI sofort den
- neuen Skill sieht.
+ Steps:
+ 1. Fetch the file via ``httpx`` from ``raw_url`` (or abort if None).
+ 2. Save it to ``<user_skills>/<name>/SKILL.md``.
+ 3. Re-parse the registry + hot-swap it in, so the UI sees the new
+ skill immediately.
"""
reg = _require_registry(request)
- # Kollisions-Check: existierender Skill mit gleichem Namen?
+ # Collision check: does a skill with the same name already exist?
try:
existing = reg.get(body.name)
except KeyError:
@@ -984,10 +984,10 @@ async def install_from_catalog(
if existing is not None:
raise HTTPException(
status_code=409,
- detail=f"Skill '{body.name}' existiert bereits. Loesche ihn, bevor du neu installierst.",
+ detail=f"Skill '{body.name}' already exists. Delete it before reinstalling.",
)
- # Minimaler SkillCandidate fuer install() — wir brauchen raw_url + name
+ # Minimal SkillCandidate for install() — we only need raw_url + name
from jarvis.skills.finder import SkillCandidate
candidate = SkillCandidate(
@@ -1012,14 +1012,14 @@ async def install_from_catalog(
raise HTTPException(status_code=400, detail=str(exc)) from exc
except Exception as exc: # noqa: BLE001
raise HTTPException(
- status_code=500, detail=f"Installation fehlgeschlagen: {exc}"
+ status_code=500, detail=f"Installation failed: {exc}"
) from exc
- # Registry refresh — neuer Skill soll sofort in der Sidebar erscheinen
+ # Registry refresh — the new skill should appear in the sidebar immediately
try:
await reg.reload()
except Exception as exc: # noqa: BLE001
- # Reload-Fail ist nicht fatal — der watchdog faengt's asynchron eh ein
+ # A reload failure is not fatal — the watchdog will catch it async anyway
return {
"ok": True,
"name": body.name,
@@ -1038,9 +1038,9 @@ async def install_from_catalog(
@router.get("/catalog/meta")
async def catalog_meta(request: Request) -> dict[str, Any]:
- """Meta-Info fuer das Frontend: welche Kategorien, Sprachen, Trust-Levels
- existieren im aktuellen Katalog. Fuellt die Dropdowns im SkillFinder-Dialog
- dynamisch, damit sie nicht mit der JSON auseinanderlaufen.
+ """Meta info for the frontend: which categories, languages, and trust levels
+ exist in the current catalog. Fills the dropdowns in the SkillFinder dialog
+ dynamically, so they don't drift out of sync with the JSON.
"""
from jarvis.skills.catalog import load_catalog
diff --git a/jarvis/ui/web/sub_agents_routes.py b/jarvis/ui/web/sub_agents_routes.py
index fe81270591..214ecc04b8 100644
--- a/jarvis/ui/web/sub_agents_routes.py
+++ b/jarvis/ui/web/sub_agents_routes.py
@@ -1,11 +1,11 @@
-"""REST-API fuer das Sub-Agent-Dashboard (Desktop-UI).
+"""REST API for the sub-agent dashboard (desktop UI).
Endpoints:
-- ``GET /api/sub-agents/tree`` → Snapshot aller aktiven Agents.
-- ``GET /api/sub-agents/{trace_id}`` → Einzelne Node (fuer DetailPanel).
+- ``GET /api/sub-agents/tree`` → snapshot of all active agents.
+- ``GET /api/sub-agents/{trace_id}`` → a single node (for the detail panel).
-Der Router erwartet eine ``SubAgentRegistry`` auf
-``app.state.sub_agent_registry`` (vom ``WebServer._build_app`` gesetzt).
+The router expects a ``SubAgentRegistry`` on
+``app.state.sub_agent_registry`` (set by ``WebServer._build_app``).
"""
from __future__ import annotations
@@ -21,7 +21,7 @@ router = APIRouter(prefix="/api/sub-agents", tags=["sub-agents"])
@router.get("/tree")
async def get_tree(request: Request) -> dict:
- """Aktueller Agent-Tree (alle laufenden + TTL-gepufferte Nodes)."""
+ """Current agent tree (all running + TTL-buffered nodes)."""
registry = getattr(request.app.state, "sub_agent_registry", None)
if registry is None:
return {"roots": [], "all": {}, "count": 0, "server_ts_ns": 0}
@@ -30,7 +30,7 @@ async def get_tree(request: Request) -> dict:
@router.get("/{trace_id}")
async def get_agent(trace_id: str, request: Request) -> dict:
- """Eine Agent-Node im Detail (fuer das DetailPanel)."""
+ """A single agent node in detail (for the detail panel)."""
registry = getattr(request.app.state, "sub_agent_registry", None)
if registry is None:
raise HTTPException(status_code=503, detail="sub-agent registry not ready")
diff --git a/jarvis/ui/web/tasks_routes.py b/jarvis/ui/web/tasks_routes.py
index dda9dd2421..29f38265b6 100644
--- a/jarvis/ui/web/tasks_routes.py
+++ b/jarvis/ui/web/tasks_routes.py
@@ -1,16 +1,16 @@
-"""REST-API fuer die Task-Queue (Phase 5 Capability 4).
+"""REST API for the task queue (Phase 5 Capability 4).
Endpoints:
-- ``POST /api/tasks`` → TaskSpec anlegen + schedulen.
-- ``GET /api/tasks`` → Task-Liste, optional ``?state=...``.
-- ``GET /api/tasks/{id}`` → Full-Task mit Steps-Timeline.
-- ``POST /api/tasks/{id}/cancel`` → Soft-Cancel (aus Heap entfernen).
-- ``DELETE /api/tasks/{id}`` → Harter Delete (nur Terminal-States).
-
-Der Router erwartet einen ``TaskStore`` + ``TaskScheduler`` auf
-``app.state.task_store`` bzw. ``app.state.task_scheduler`` — die werden
-vom DesktopApp beim Startup gesetzt. Wenn nichts gesetzt ist, antworten
-die Endpoints mit ``503`` (Service Unavailable).
+- ``POST /api/tasks`` → create + schedule a TaskSpec.
+- ``GET /api/tasks`` → task list, optionally ``?state=...``.
+- ``GET /api/tasks/{id}`` → full task with steps timeline.
+- ``POST /api/tasks/{id}/cancel`` → soft cancel (remove from the heap).
+- ``DELETE /api/tasks/{id}`` → hard delete (terminal states only).
+
+The router expects a ``TaskStore`` + ``TaskScheduler`` on
+``app.state.task_store`` resp. ``app.state.task_scheduler`` — these are
+set by the DesktopApp at startup. If neither is set, the endpoints answer
+with ``503`` (Service Unavailable).
"""
from __future__ import annotations
@@ -27,7 +27,7 @@ router = APIRouter(prefix="/api/tasks", tags=["tasks"])
def _require_store(request: Request) -> Any:
store = getattr(request.app.state, "task_store", None)
if store is None:
- raise HTTPException(status_code=503, detail="TaskStore nicht verfuegbar")
+ raise HTTPException(status_code=503, detail="TaskStore not available")
return store
@@ -36,7 +36,7 @@ def _optional_scheduler(request: Request) -> Any | None:
def _row_to_summary(row: dict[str, Any]) -> dict[str, Any]:
- """Wandelt einen DB-Row in ein UI-Summary-Dict. Nur flache Keys, keine Steps."""
+ """Converts a DB row into a UI summary dict. Flat keys only, no steps."""
return {
"id": row["id"],
"title": row.get("title") or "",
@@ -57,9 +57,9 @@ def _row_to_summary(row: dict[str, Any]) -> dict[str, Any]:
@router.post("", status_code=201)
async def create_task(spec: TaskSpec, request: Request) -> dict[str, Any]:
- """Legt einen Task an. Wenn ein ``TaskScheduler`` verfuegbar ist, laeuft
- der komplette ``schedule()``-Pfad (inkl. Heap-Push + Wakeup); sonst
- reiner Store-Insert.
+ """Creates a task. If a ``TaskScheduler`` is available, the complete
+ ``schedule()`` path runs (incl. heap push + wakeup); otherwise it's
+ a plain store insert.
"""
store = _require_store(request)
scheduler = _optional_scheduler(request)
@@ -76,7 +76,7 @@ async def list_tasks(
state: str | None = None,
limit: int = 100,
) -> dict[str, Any]:
- """Liste aller Tasks, optional nach State gefiltert."""
+ """List of all tasks, optionally filtered by state."""
store = _require_store(request)
filter_val: str | list[str] | None
if state is None or state == "":
@@ -94,13 +94,13 @@ async def list_tasks(
@router.get("/{task_id}")
async def get_task(task_id: str, request: Request) -> dict[str, Any]:
- """Full-Task inkl. Steps-Timeline."""
+ """Full task incl. steps timeline."""
store = _require_store(request)
task = await store.get(task_id)
if task is None:
- raise HTTPException(status_code=404, detail="Task nicht gefunden")
+ raise HTTPException(status_code=404, detail="Task not found")
- # spec_json → dict fuer UI-Convenience
+ # spec_json → dict for UI convenience
spec_obj = None
spec_raw = task.get("spec_json")
if spec_raw:
@@ -117,20 +117,20 @@ async def get_task(task_id: str, request: Request) -> dict[str, Any]:
@router.post("/{task_id}/cancel")
async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:
- """Soft-Cancel: entfernt den Task aus dem Heap/Event-Index und setzt
- State auf ``cancelled``. Bricht **nicht** harte CU-Loops ab — dafuer
- gibt es den globalen Kill-Switch.
+ """Soft cancel: removes the task from the heap/event index and sets
+ its state to ``cancelled``. Does **not** abort a hard CU loop — that's
+ what the global kill switch is for.
"""
store = _require_store(request)
scheduler = _optional_scheduler(request)
- # 404 fuer Unbekannte
+ # 404 for unknown tasks
task = await store.get(task_id)
if task is None:
- raise HTTPException(status_code=404, detail="Task nicht gefunden")
+ raise HTTPException(status_code=404, detail="Task not found")
if task["state"] in ("completed", "failed", "cancelled", "interrupted"):
raise HTTPException(
status_code=409,
- detail=f"Task ist bereits final (state={task['state']})",
+ detail=f"Task is already final (state={task['state']})",
)
if scheduler is not None:
@@ -145,15 +145,15 @@ async def cancel_task(task_id: str, request: Request) -> dict[str, Any]:
@router.delete("/{task_id}")
async def delete_task(task_id: str, request: Request) -> dict[str, Any]:
- """Harter Delete — nur erlaubt wenn der Task in einem Terminal-State ist."""
+ """Hard delete — only allowed when the task is in a terminal state."""
store = _require_store(request)
task = await store.get(task_id)
if task is None:
- raise HTTPException(status_code=404, detail="Task nicht gefunden")
+ raise HTTPException(status_code=404, detail="Task not found")
if task["state"] not in ("completed", "failed", "cancelled", "interrupted"):
raise HTTPException(
status_code=409,
- detail=f"Task noch aktiv (state={task['state']}) — erst cancellen",
+ detail=f"Task is still active (state={task['state']}) — cancel it first",
)
deleted = await store.delete(task_id)
return {"ok": deleted, "id": task_id}
diff --git a/jarvis/ui/web/telephony_routes.py b/jarvis/ui/web/telephony_routes.py
index 162187054e..044338724c 100644
--- a/jarvis/ui/web/telephony_routes.py
+++ b/jarvis/ui/web/telephony_routes.py
@@ -370,7 +370,7 @@ async def post_selftest(request: Request) -> JSONResponse:
error = f"brain: {exc}"
if not response_text:
- response_text = "Ja, das Telefon funktioniert. Ich höre dich klar und deutlich."
+ response_text = "Ja, das Telefon funktioniert. Ich höre dich klar und deutlich." # i18n-allow: canned voice-output fallback, synthesized via TTS below
# Scrub + TTS -> count synthesized bytes after transcode to Twilio mu-law.
try:
diff --git a/jarvis/ui/web/tools_routes.py b/jarvis/ui/web/tools_routes.py
index f020702b93..f58a7a2dd8 100644
--- a/jarvis/ui/web/tools_routes.py
+++ b/jarvis/ui/web/tools_routes.py
@@ -1,7 +1,7 @@
-"""REST-API für Tool-Registry-Inspektion.
+"""REST API for tool-registry inspection.
-Zeigt alle Tools, die dem Brain zur Laufzeit verfügbar sind — MCP-Adapter,
-native Plugin-Tools, Skills. Reine Read-Only-API für UI und Debug.
+Shows all tools available to the brain at runtime — MCP adapters, native
+plugin tools, skills. A pure read-only API for the UI and debugging.
"""
from __future__ import annotations
@@ -24,7 +24,7 @@ def _tool_to_dict(name: str, tool: Any) -> dict[str, Any]:
"risk_tier": getattr(tool, "risk_tier", "monitor"),
"schema": getattr(tool, "schema", {}) or {},
"source": source,
- # MCP-Adapter haben einen MCPClient — wir zeigen den Server-Name für UI
+ # MCP adapters have an MCPClient — we show the server name for the UI
"mcp_server": (
getattr(getattr(tool, "_client", None), "spec", None).name
if hasattr(tool, "_client")
diff --git a/jarvis/ui/web/workflows_routes.py b/jarvis/ui/web/workflows_routes.py
index 9ae62eaf57..960cb0dbeb 100644
--- a/jarvis/ui/web/workflows_routes.py
+++ b/jarvis/ui/web/workflows_routes.py
@@ -1,20 +1,20 @@
-"""REST-API fuer Workflows (Phase 6).
+"""REST API for workflows (Phase 6).
Endpoints:
-- ``GET /api/workflows`` → Dashboard-Liste (Workflows + Summary).
-- ``POST /api/workflows`` → WorkflowDef anlegen.
-- ``GET /api/workflows/{id}`` → Detail inkl. letzter Runs.
-- ``PATCH /api/workflows/{id}`` → Enable/Disable (partial update).
-- ``DELETE /api/workflows/{id}`` → Entfernen.
-- ``POST /api/workflows/{id}/run`` → Manuell triggern, body = input dict.
-- ``GET /api/workflows/runs/{run_id}``→ Run-Detail mit Step-Timeline.
-
-Erwartet auf ``app.state``:
+- ``GET /api/workflows`` → dashboard list (workflows + summary).
+- ``POST /api/workflows`` → create a WorkflowDef.
+- ``GET /api/workflows/{id}`` → detail incl. most recent runs.
+- ``PATCH /api/workflows/{id}`` → enable/disable (partial update).
+- ``DELETE /api/workflows/{id}`` → remove.
+- ``POST /api/workflows/{id}/run`` → trigger manually, body = input dict.
+- ``GET /api/workflows/runs/{run_id}``→ run detail with step timeline.
+
+Expected on ``app.state``:
- ``workflow_store`` (WorkflowStore)
- ``workflow_runner`` (WorkflowRunner)
-Fallback: wenn nichts gesetzt ist, geben die Endpoints 503 zurueck — die
-UI zeigt dann einen Empty-State statt zu crashen.
+Fallback: if neither is set, the endpoints return 503 — the UI then shows
+an empty state instead of crashing.
"""
from __future__ import annotations
@@ -30,29 +30,29 @@ router = APIRouter(prefix="/api/workflows", tags=["workflows"])
# ----------------------------------------------------------------------
-# State-Accessor
+# State accessor
# ----------------------------------------------------------------------
def _require_store(request: Request) -> Any:
store = getattr(request.app.state, "workflow_store", None)
if store is None:
- raise HTTPException(status_code=503, detail="WorkflowStore nicht verfuegbar")
+ raise HTTPException(status_code=503, detail="WorkflowStore not available")
return store
def _require_runner(request: Request) -> Any:
runner = getattr(request.app.state, "workflow_runner", None)
if runner is None:
- raise HTTPException(status_code=503, detail="WorkflowRunner nicht verfuegbar")
+ raise HTTPException(status_code=503, detail="WorkflowRunner not available")
return runner
# ----------------------------------------------------------------------
-# Row → UI-Dict
+# Row → UI dict
# ----------------------------------------------------------------------
def _row_to_summary(row: dict[str, Any]) -> dict[str, Any]:
- """Flaches Dashboard-Summary — ohne volle Def (sparsam fuer Listen)."""
+ """Flat dashboard summary — without the full def (lean for lists)."""
def_json = row.get("def_json") or "{}"
try:
defs = json.loads(def_json)
@@ -84,8 +84,8 @@ def _row_to_summary(row: dict[str, Any]) -> dict[str, Any]:
@router.get("/integrations")
async def integrations_status(request: Request) -> dict[str, Any]:
- """Status der externen Integrationen — UI rendert Setup-Banner wenn
- etwas fehlt (z.B. Telegram-Bot-Token nicht gesetzt)."""
+ """Status of external integrations — the UI renders a setup banner when
+ something is missing (e.g. the Telegram bot token is not set)."""
from jarvis.core.config import get_secret
# Telegram
@@ -98,7 +98,7 @@ async def integrations_status(request: Request) -> dict[str, Any]:
except Exception: # noqa: BLE001
chat_id = ""
- # gws-CLI: versuchen, den Pfad aufzuloesen
+ # gws CLI: try to resolve the path
import shutil
gws_path = shutil.which("gws")
@@ -108,19 +108,19 @@ async def integrations_status(request: Request) -> dict[str, Any]:
"has_token": bool(token),
"has_chat_id": bool(chat_id),
"setup_hint": (
- "Erstelle einen Bot via @BotFather, setze den Token als "
- "ENV TELEGRAM_BOT_TOKEN (setx TELEGRAM_BOT_TOKEN <token>) "
- "und trage die Chat-ID unter [integrations.telegram] in "
- "jarvis.toml ein."
+ "Create a bot via @BotFather, set the token as "
+ "ENV TELEGRAM_BOT_TOKEN (setx TELEGRAM_BOT_TOKEN <token>), "
+ "and enter the chat ID under [integrations.telegram] in "
+ "jarvis.toml."
),
},
"gws_cli": {
"configured": bool(gws_path),
"path": gws_path,
"setup_hint": (
- "Google-Workspace-CLI — wird fuer gmail/calendar/drive-Workflows "
- "genutzt. Installation + Auth laut gws-Doku; nach Setup "
- "'gws auth status' testen."
+ "Google Workspace CLI — used for gmail/calendar/drive workflows. "
+ "See the gws docs for installation + auth; after setup, "
+ "test with 'gws auth status'."
),
},
}
@@ -128,7 +128,7 @@ async def integrations_status(request: Request) -> dict[str, Any]:
@router.get("")
async def list_workflows(request: Request) -> dict[str, Any]:
- """Dashboard-Liste: alle Workflows + aggregierte Kennzahlen."""
+ """Dashboard list: all workflows + aggregated metrics."""
store = _require_store(request)
rows = await store.list_workflows()
summaries = [_row_to_summary(r) for r in rows]
@@ -161,7 +161,7 @@ async def create_workflow(
wf: WorkflowDef,
request: Request,
) -> dict[str, Any]:
- """Legt einen neuen Workflow an (oder ueberschreibt per ID)."""
+ """Creates a new workflow (or overwrites by ID)."""
store = _require_store(request)
wid = await store.upsert_workflow(wf)
return {"id": wid}
@@ -172,7 +172,7 @@ async def get_workflow(workflow_id: str, request: Request) -> dict[str, Any]:
store = _require_store(request)
row = await store.get_workflow(workflow_id)
if row is None:
- raise HTTPException(status_code=404, detail="Workflow nicht gefunden")
+ raise HTTPException(status_code=404, detail="Workflow not found")
summary = _row_to_summary(row)
try:
defs = json.loads(row.get("def_json") or "{}")
@@ -189,14 +189,14 @@ async def patch_workflow(
request: Request,
payload: dict[str, Any] = Body(...),
) -> dict[str, Any]:
- """Partial Update. Momentan nur ``enabled`` — mehr Felder kommen bei Bedarf."""
+ """Partial update. Currently only ``enabled`` — more fields as needed."""
store = _require_store(request)
row = await store.get_workflow(workflow_id)
if row is None:
- raise HTTPException(status_code=404, detail="Workflow nicht gefunden")
+ raise HTTPException(status_code=404, detail="Workflow not found")
if "enabled" in payload:
await store.set_enabled(workflow_id, bool(payload["enabled"]))
- # Cron-Workflows: next_run neu berechnen beim Toggle
+ # Cron workflows: recompute next_run on toggle
if not payload["enabled"]:
await store.set_next_run(workflow_id, None)
updated = await store.get_workflow(workflow_id)
@@ -208,7 +208,7 @@ async def delete_workflow(workflow_id: str, request: Request) -> dict[str, Any]:
store = _require_store(request)
deleted = await store.delete_workflow(workflow_id)
if not deleted:
- raise HTTPException(status_code=404, detail="Workflow nicht gefunden")
+ raise HTTPException(status_code=404, detail="Workflow not found")
return {"ok": True, "id": workflow_id}
@@ -218,8 +218,8 @@ async def run_workflow(
request: Request,
input_data: dict[str, Any] = Body(default_factory=dict),
) -> dict[str, Any]:
- """Triggert einen Workflow-Run manuell. Returnt sofort die Run-ID —
- der eigentliche Lauf ist Fire-and-Forget, UI polled/WS-streamed."""
+ """Manually triggers a workflow run. Returns the run ID immediately —
+ the actual run is fire-and-forget; the UI polls / streams over WS."""
_require_store(request)
runner = _require_runner(request)
try:
@@ -238,7 +238,7 @@ async def get_run(run_id: str, request: Request) -> dict[str, Any]:
store = _require_store(request)
run = await store.get_run(run_id)
if run is None:
- raise HTTPException(status_code=404, detail="Run nicht gefunden")
+ raise HTTPException(status_code=404, detail="Run not found")
return run
diff --git a/jarvis/vision/__init__.py b/jarvis/vision/__init__.py
index 15c8cc1f2d..9a9a499658 100644
--- a/jarvis/vision/__init__.py
+++ b/jarvis/vision/__init__.py
@@ -1,14 +1,14 @@
-"""Vision-Engine (Phase 5 Capability 1).
+"""Vision engine (Phase 5 Capability 1).
Exports:
- - ScreenshotSource — Primary-Monitor-Screenshot via mss.
- - UIATreeSource — gepruneder UIA-Tree via pywinauto.
- - VisionEngine — orchestrierter Entry-Point mit Heuristik + Cache.
- - VisionCache — Hash-basierter Observation-Cache.
- - Pruning-Helpers (pruning.py) — reine Funktionen, testbar ohne Windows.
+ - ScreenshotSource — primary-monitor screenshot via mss.
+ - UIATreeSource — pruned UIA tree via pywinauto.
+ - VisionEngine — orchestrated entry point with heuristics + cache.
+ - VisionCache — hash-based observation cache.
+ - Pruning helpers (pruning.py) — pure functions, testable without Windows.
-Siehe ADR-0002 fuer die Pruning-Strategie und
-`jarvis.core.protocols.VisionSource` fuer den Contract.
+See ADR-0002 for the pruning strategy and
+`jarvis.core.protocols.VisionSource` for the contract.
"""
from __future__ import annotations
diff --git a/jarvis/vision/cache.py b/jarvis/vision/cache.py
index 322be2794d..0772456d09 100644
--- a/jarvis/vision/cache.py
+++ b/jarvis/vision/cache.py
@@ -1,16 +1,16 @@
-"""VisionCache — Screenshot-Hash-basierter Dedup fuer Observations.
+"""VisionCache — screenshot-hash-based dedup for observations.
-Hintergrund: Der CU-Loop ruft `VisionEngine.observe()` mehrmals pro Step.
-Wenn der Bildschirm sich zwischen zwei Calls nicht veraendert hat, ist
-das UIA-Pruning (Haupt-Kostenfaktor) Verschwendung. Wir cachen daher
-Observations unter ihrem Screenshot-Hash.
+Background: the CU loop calls `VisionEngine.observe()` several times per
+step. If the screen hasn't changed between two calls, the UIA pruning (the
+main cost factor) is wasted work. So we cache observations under their
+screenshot hash.
-Strategie: FIFO, Kapazitaet 10 Eintraege. Wenn ein Screenshot-Hash
-gecached ist und die UIA-Tree-Struktur (node_count, window_title) passt,
-gib die alte Observation zurueck. Andernfalls Cache-Miss.
+Strategy: FIFO, capacity 10 entries. If a screenshot hash is cached and the
+UIA tree structure (node_count, window_title) matches, return the old
+observation. Otherwise it's a cache miss.
-Der Cache lebt im Prozess — keine Persistenz. Das ist ok, weil der erste
-Observe eines neuen Prozesses ohnehin einen frischen Screenshot braucht.
+The cache lives in-process — no persistence. That's fine, because the first
+observe of a new process needs a fresh screenshot anyway.
"""
from __future__ import annotations
@@ -20,9 +20,9 @@ from jarvis.core.protocols import Observation
class VisionCache:
- """FIFO-Cache fuer Observations, gekeyt auf Screenshot-Hash.
+ """FIFO cache for observations, keyed on the screenshot hash.
- Nutzung:
+ Usage:
cache = VisionCache(capacity=10)
cached = cache.get(hash_of_current_screenshot)
@@ -35,34 +35,34 @@ class VisionCache:
def __init__(self, *, capacity: int = 10) -> None:
if capacity < 1:
- raise ValueError("capacity muss >= 1 sein")
+ raise ValueError("capacity must be >= 1")
self._capacity = capacity
- # OrderedDict gibt uns FIFO ueber `popitem(last=False)`.
+ # OrderedDict gives us FIFO via `popitem(last=False)`.
self._store: OrderedDict[str, Observation] = OrderedDict()
def get(self, screenshot_hash: str) -> Observation | None:
- """Gibt eine gecachte Observation zurueck oder None."""
+ """Returns a cached observation, or None."""
if not screenshot_hash:
return None
return self._store.get(screenshot_hash)
def put(self, obs: Observation) -> None:
- """Legt eine Observation unter ihrem Screenshot-Hash ab.
+ """Stores an observation under its screenshot hash.
- Wenn der Hash leer ist, wird der Put ignoriert — ein Cache ohne
- Key macht keinen Sinn. Das kann bei `source='ui_tree_only'`
- vorkommen, wo es keinen Screenshot gibt.
+ If the hash is empty, the put is ignored — a cache without a key
+ makes no sense. This can happen with `source='ui_tree_only'`,
+ where there is no screenshot.
"""
if not obs.screenshot_hash:
return
- # Bei Hash-Collision ueberschreiben wir und die Ordering bleibt FIFO.
+ # On a hash collision we overwrite, and the ordering stays FIFO.
if obs.screenshot_hash in self._store:
- # Move-to-end wuerde LRU sein, wir wollen FIFO: entfernen + neu einfuegen,
- # damit ein ueberschriebener Eintrag seine urspruengliche Position verliert.
- # Fuer Cache-Hit-Tests ist FIFO die klarere Semantik.
+ # Move-to-end would be LRU; we want FIFO: remove + re-insert,
+ # so an overwritten entry loses its original position.
+ # FIFO is the clearer semantics for cache-hit tests.
del self._store[obs.screenshot_hash]
self._store[obs.screenshot_hash] = obs
- # Evict bei Ueberlauf — aelteste Entry raus.
+ # Evict on overflow — drop the oldest entry.
while len(self._store) > self._capacity:
self._store.popitem(last=False)
diff --git a/jarvis/vision/context_provider.py b/jarvis/vision/context_provider.py
index 60edaeff46..fc20a2648b 100644
--- a/jarvis/vision/context_provider.py
+++ b/jarvis/vision/context_provider.py
@@ -1,27 +1,27 @@
-"""VisionContextProvider - Background-Cache frischer Screen-Observations.
+"""VisionContextProvider - background cache of fresh screen observations.
-Hybrid-Refresh-Strategie: Ein async Background-Task refresht alle
-`refresh_interval_s` ueber `VisionEngine.observe(mode=capture_mode)` und
-haelt die letzte Observation im Cache. `current()` liefert sie sofort -
-oder forced einen Fresh-Capture wenn der Cache aelter als
-`max_staleness_s` ist (Liveness-Garantie).
+Hybrid refresh strategy: an async background task refreshes every
+`refresh_interval_s` via `VisionEngine.observe(mode=capture_mode)` and
+keeps the latest observation in the cache. `current()` returns it
+immediately - or forces a fresh capture if the cache is older than
+`max_staleness_s` (the liveness guarantee).
Lifecycle:
provider = VisionContextProvider(engine, bus=bus)
- await provider.start() # Task laeuft
+ await provider.start() # task is running
obs = await provider.current()
- provider.pause() # Privacy-Toggle
+ provider.pause() # privacy toggle
provider.resume()
- await provider.stop() # Task canceled, < 500ms
+ await provider.stop() # task canceled, < 500ms
-Pausiert `current()` wirft `VisionPaused`. Exceptions im Loop werden
-geloggt, Loop laeuft weiter (stirbt nur via stop()).
+While paused, `current()` raises `VisionPaused`. Exceptions in the loop are
+logged; the loop keeps running (it only dies via stop()).
-Design-Notiz (Reality-Check: Provider.start() sync-startbar): `start()`
-ist zwar `async def`, macht aber nur `asyncio.create_task(...)` - das
-laeuft in jedem Event-Loop-Kontext und blockiert nicht. Wer den Provider
-aus sync-Code startet, kann `asyncio.run(provider.start())` nutzen oder
-den Task spaeter in seinem eigenen Loop erzeugen.
+Design note (reality check: Provider.start() is sync-startable): `start()`
+is declared `async def`, but only does `asyncio.create_task(...)` - that
+runs in any event-loop context and does not block. Anyone starting the
+provider from sync code can use `asyncio.run(provider.start())` or create
+the task later in their own loop.
"""
from __future__ import annotations
@@ -42,16 +42,16 @@ CaptureMode = Literal["auto", "screenshot", "ui_tree", "composite"]
class VisionPaused(RuntimeError):
- """Raised by VisionContextProvider.current() wenn pausiert."""
+ """Raised by VisionContextProvider.current() while paused."""
class VisionContextProvider:
- """Background-Cache-Layer vor einer VisionEngine.
+ """Background cache layer in front of a VisionEngine.
- Haelt die juengste Observation im Speicher und refresht sie periodisch
- im Hintergrund. Konsumenten bekommen so Screen-Kontext ohne die
- Latenz eines frischen Captures - es sei denn der Cache ist aelter
- als `max_staleness_s`, dann wird synchron nachgezogen.
+ Keeps the most recent observation in memory and refreshes it
+ periodically in the background. Consumers thus get screen context
+ without the latency of a fresh capture - unless the cache is older
+ than `max_staleness_s`, in which case it catches up synchronously.
"""
def __init__(
@@ -76,9 +76,9 @@ class VisionContextProvider:
# ---------- Lifecycle ----------
async def start(self) -> None:
- """Startet den Background-Refresh-Loop auf dem aktuellen Event-Loop.
+ """Starts the background refresh loop on the current event loop.
- Idempotent: Mehrfacher Aufruf ohne vorheriges stop() ist ein No-op.
+ Idempotent: calling it again without a prior stop() is a no-op.
"""
if self._task is not None and not self._task.done():
return
@@ -89,9 +89,9 @@ class VisionContextProvider:
)
async def stop(self) -> None:
- """Cancelt den Loop und wartet max 500ms auf sauberes Beenden.
+ """Cancels the loop and waits at most 500ms for a clean shutdown.
- Nach stop() ist der Provider wieder startbar via start().
+ After stop(), the provider is startable again via start().
"""
self._stopping = True
t = self._task
@@ -110,17 +110,17 @@ class VisionContextProvider:
# ---------- Public Access ----------
async def current(self, *, force_refresh: bool = False) -> Observation:
- """Liefert aktuellste Observation.
+ """Returns the most recent observation.
- Forced einen frischen Capture wenn (a) explizit via `force_refresh`,
- (b) noch keine Observation vorliegt oder (c) die vorhandene aelter
- als `max_staleness_s` ist.
+ Forces a fresh capture if (a) explicitly via `force_refresh`,
+ (b) no observation exists yet, or (c) the existing one is older
+ than `max_staleness_s`.
Raises:
- VisionPaused: wenn der Provider gerade pausiert ist.
+ VisionPaused: if the provider is currently paused.
"""
if self._paused:
- raise VisionPaused("Vision pausiert")
+ raise VisionPaused("Vision paused")
need_fresh = (
force_refresh
or self._latest is None
@@ -140,11 +140,11 @@ class VisionContextProvider:
return self._latest
def pause(self) -> None:
- """Privacy-Toggle: Loop refresht nicht, current() wirft VisionPaused."""
+ """Privacy toggle: the loop stops refreshing, current() raises VisionPaused."""
self._paused = True
def resume(self) -> None:
- """Hebt pause() auf. Loop refresht beim naechsten Tick wieder."""
+ """Undoes pause(). The loop resumes refreshing on the next tick."""
self._paused = False
@property
@@ -157,28 +157,28 @@ class VisionContextProvider:
@property
def latest(self) -> Observation | None:
- """Letzte gecachte Observation ohne Refresh-Check (kann stale sein)."""
+ """Last cached observation without a refresh check (may be stale)."""
return self._latest
# ---------- Internals ----------
@staticmethod
def _age_s(obs: Observation) -> float:
- """Alter der Observation in Sekunden, geclampt auf >= 0."""
+ """Age of the observation in seconds, clamped to >= 0."""
return max(0.0, time.time_ns() / 1e9 - obs.timestamp_ns / 1e9)
async def _refresh_loop(self) -> None:
- """Background-Task: periodisch observe() aufrufen und cachen.
+ """Background task: periodically call observe() and cache the result.
- Exceptions werden geloggt aber nicht propagiert - der Loop stirbt
- ausschliesslich ueber stop() (-> CancelledError).
+ Exceptions are logged but not propagated - the loop only dies via
+ stop() (-> CancelledError).
- Error-Logging: die ERSTE Exception (oder erste nach 5 aufeinander
- folgenden Fehlern) wird als `error` mit Stacktrace geloggt, damit sie
- im Flight-Recorder + UI sichtbar ist. Weitere gleichartige Fehler
- werden nur als `warning` ohne Trace reported, damit die Logs nicht
- fluten (typischer Fall: mss scheitert wegen RDP-Lock-Screen und
- wiederholt sich alle 2s bis zum Unlock).
+ Error logging: the FIRST exception (or the first after 5 consecutive
+ failures) is logged as `error` with a stack trace, so it's visible in
+ the flight recorder + UI. Further errors of the same kind are only
+ reported as `warning` without a trace, so the logs don't flood
+ (typical case: mss fails due to an RDP lock screen and repeats every
+ 2s until unlock).
None return from engine.observe(): ScreenshotSource already handled the
BitBlt error (logged once), returning None means "skip this frame".
@@ -198,7 +198,7 @@ class VisionContextProvider:
self._latest = obs
if consecutive_errors > 0:
log.info(
- "VisionContextProvider recovered nach %d Fehlern.",
+ "VisionContextProvider recovered after %d errors.",
consecutive_errors,
)
consecutive_errors = 0
@@ -206,7 +206,7 @@ class VisionContextProvider:
raise
except Exception as exc: # noqa: BLE001
consecutive_errors += 1
- # Erster Fehler sowie jeder 5. Folgefehler: laut mit Trace.
+ # The first error and every 5th subsequent one: log loudly with a trace.
if consecutive_errors == 1 or consecutive_errors % 5 == 0:
log.error(
"VisionContextProvider Loop-Exception (#%d): %s "
diff --git a/jarvis/vision/engine.py b/jarvis/vision/engine.py
index 91cb771d9b..6fe30f1db5 100644
--- a/jarvis/vision/engine.py
+++ b/jarvis/vision/engine.py
@@ -1,22 +1,21 @@
-"""VisionEngine — orchestriert Screenshot- und UIA-Tree-Sources.
+"""VisionEngine — orchestrates screenshot and UIA-tree sources.
-Die Engine ist der einzige Zugriffspunkt fuer CU-Loop und Tools. Sie waehlt
-pro Observe-Call heuristisch, welche Source billiger/robuster ist:
+The engine is the single access point for the CU loop and tools. For each
+observe call it heuristically picks whichever source is cheaper/more robust:
-- `mode='screenshot'`: nur Bild.
-- `mode='ui_tree'`: nur Baum (gepruneded).
-- `mode='composite'`: beides, gemergt zu einer Observation mit `source='full'`.
-- `mode='auto'` (Default): heuristische Wahl. Bekannte Text-heavy Apps
- (Chrome, VSCode, Slack — erkannt an Process-Name oder Window-Title)
- bekommen `screenshot`, weil Pruning dort zu teuer oder instabil ist.
- Alles andere bekommt `composite`.
+- `mode='screenshot'`: image only.
+- `mode='ui_tree'`: tree only (pruned).
+- `mode='composite'`: both, merged into one observation with `source='full'`.
+- `mode='auto'` (default): heuristic choice. Known text-heavy apps
+ (Chrome, VSCode, Slack — detected via process name or window title)
+ get `screenshot`, because pruning there is too expensive or unstable.
+ Everything else gets `composite`.
-Die Engine cached ueber `VisionCache` auf dem Screenshot-Hash: wenn der
-Bildschirm sich nicht veraendert hat, gibt sie die letzte Observation
-zurueck.
+The engine caches via `VisionCache` on the screenshot hash: if the screen
+hasn't changed, it returns the last observation.
-Emittiert `ObservationCaptured` an den optionalen EventBus — der Flight-
-Recorder und die UI subscriben darauf.
+Emits `ObservationCaptured` to the optional EventBus — the flight recorder
+and the UI subscribe to it.
"""
from __future__ import annotations
@@ -40,8 +39,8 @@ logger = logging.getLogger(__name__)
ObserveMode = Literal["auto", "screenshot", "ui_tree", "composite"]
-# Process-Namen + Window-Title-Fragmente, fuer die Pruning zu teuer ist.
-# Wir matchen case-insensitive gegen Title ODER Process-Name.
+# Process names + window-title fragments for which pruning is too expensive.
+# We match case-insensitively against the title OR the process name.
_TEXT_HEAVY_HINTS: tuple[str, ...] = (
"chrome",
"chromium",
@@ -56,7 +55,7 @@ _TEXT_HEAVY_HINTS: tuple[str, ...] = (
class VisionEngine:
- """Orchestrator vor den Sources. Siehe Modul-Docstring."""
+ """Orchestrator in front of the sources. See the module docstring."""
name: str = "vision-engine"
kind: Literal["screenshot", "ui_tree", "composite"] = "composite"
@@ -94,14 +93,14 @@ class VisionEngine:
cancel_token: CancelToken | None = None,
window_title_filter: str | None = None,
) -> Observation | None:
- """Einzelner Observation-Snapshot.
+ """A single observation snapshot.
- `mode='auto'` entscheidet heuristisch: wenn der aktuelle
- Foreground-Process in `_TEXT_HEAVY_HINTS` liegt, nimm `screenshot`,
- sonst `composite`.
+ `mode='auto'` decides heuristically: if the current foreground
+ process is in `_TEXT_HEAVY_HINTS`, use `screenshot`, otherwise
+ `composite`.
- CancelToken wird an die Sub-Sources weitergereicht. Jeder
- Sub-Operation-Start prueft zusaetzlich selbst.
+ The CancelToken is passed down to the sub-sources. Each
+ sub-operation additionally checks it at the start.
Returns None when the screenshot source signals a transient BitBlt /
GDI failure (ScreenshotSource.observe() returned None). The caller
@@ -133,8 +132,8 @@ class VisionEngine:
if effective_mode == "screenshot" and not obs.window_title and hint:
obs = replace(obs, window_title=hint)
- # Cache-Check ueber Hash. Wenn wir die exakt gleiche Observation
- # schon hatten, recyclen wir.
+ # Cache check via hash. If we already had the exact same observation,
+ # recycle it.
cached = self._cache.get(obs.screenshot_hash)
if cached is not None and self._cache_is_fresh(cached, obs):
await self._emit(cached)
@@ -148,15 +147,15 @@ class VisionEngine:
await self._uia_source.close()
self._cache.clear()
- # ---- Heuristik ---------------------------------------------------------
+ # ---- Heuristics ---------------------------------------------------------
def _resolve_mode(
self,
mode: ObserveMode,
hint: str,
) -> Literal["screenshot", "ui_tree", "composite"]:
- """Wandelt `auto` in einen konkreten Modus um. ``hint`` ist der vom
- Caller bereits ermittelte Foreground-Hinweis (Titel/Filter)."""
+ """Turns `auto` into a concrete mode. ``hint`` is the foreground
+ hint (title/filter) the caller has already determined."""
if mode != "auto":
return mode
if hint and any(h in hint.lower() for h in _TEXT_HEAVY_HINTS):
@@ -165,14 +164,13 @@ class VisionEngine:
@staticmethod
def _guess_active_app_hint(window_title_filter: str | None) -> str:
- """Best-effort Active-Window-Hinweis.
-
- - Wenn ein `window_title_filter` mitgegeben ist, nutzen wir ihn als
- Hint — der Caller weiss typischerweise, auf welches Fenster er
- sich gerade bezieht.
- - Sonst via GetForegroundWindow + GetWindowText (nur Windows).
- - Auf non-Windows liefern wir einen leeren String, wodurch die
- Heuristik `composite` waehlt — pragmatisch fuer Tests.
+ """Best-effort active-window hint.
+
+ - If a `window_title_filter` is passed, we use it as the hint — the
+ caller typically knows which window it is currently referring to.
+ - Otherwise via GetForegroundWindow + GetWindowText (Windows only).
+ - On non-Windows we return an empty string, which makes the
+ heuristic choose `composite` — pragmatic for tests.
"""
if window_title_filter:
return window_title_filter
@@ -194,10 +192,10 @@ class VisionEngine:
@staticmethod
def _cache_is_fresh(cached: Observation, current: Observation) -> bool:
- """Prueft, ob der gecachte Eintrag noch fuer den aktuellen Call
- passt. Wir verlangen denselben window_title — wenn der User in ein
- anderes Fenster gewechselt hat, ist der alte Tree stale, selbst
- wenn der Screenshot-Hash (zufaellig) der gleiche waere.
+ """Checks whether the cached entry still fits the current call.
+ We require the same window_title — if the user has switched to a
+ different window, the old tree is stale even if the screenshot
+ hash happened to be the same.
"""
return cached.window_title == current.window_title
@@ -233,7 +231,7 @@ class VisionEngine:
cancel_token: CancelToken | None,
window_title_filter: str | None,
) -> Observation | None:
- """Beides aufnehmen und mergen.
+ """Captures both and merges them.
Returns None when the screenshot source signals a transient BitBlt
failure — the composite result is unusable without a screenshot.
@@ -253,9 +251,9 @@ class VisionEngine:
window_title_filter=window_title_filter,
)
- # Wenn das UIA-Pruning overflow-te, bleibt's bei screenshot_only —
- # die Tree-Source hat `source='screenshot_only'` markiert. Wir
- # uebernehmen den Screenshot-Part und leere Nodes.
+ # If the UIA pruning overflowed, it stays at screenshot_only — the
+ # tree source has marked `source='screenshot_only'`. We take the
+ # screenshot part and empty nodes.
if tree.source == "screenshot_only":
merged_nodes: tuple[UIANode, ...] = ()
merged_source: Literal["full", "screenshot_only", "ui_tree_only"] = (
@@ -277,7 +275,7 @@ class VisionEngine:
pruning_stats=tree.pruning_stats,
)
- # ---- Event-Emission ----------------------------------------------------
+ # ---- Event emission ----------------------------------------------------
async def _emit(self, obs: Observation) -> None:
if self._bus is None:
@@ -295,5 +293,5 @@ class VisionEngine:
)
)
except Exception: # noqa: BLE001
- logger.warning("ObservationCaptured konnte nicht publiziert werden",
+ logger.warning("ObservationCaptured could not be published",
exc_info=True)
diff --git a/jarvis/vision/pruning.py b/jarvis/vision/pruning.py
index 766381c942..a1d09025ef 100644
--- a/jarvis/vision/pruning.py
+++ b/jarvis/vision/pruning.py
@@ -1,34 +1,34 @@
-"""Pruning-Helpers fuer den UIAutomation-Tree (ADR-0002).
+"""Pruning helpers for the UIAutomation tree (ADR-0002).
-Drei Filter-Stufen, die der `UIATreeSource` in Reihenfolge anwendet:
+Three filter stages that `UIATreeSource` applies in order:
-1. `filter_by_depth` — Depth-Limit (Default 6).
-2. `filter_by_role` — Interesting-Role-Whitelist + Name-non-empty.
-3. `filter_on_screen` — BoundingRect mindestens 50 % innerhalb Primary-Monitor.
+1. `filter_by_depth` — depth limit (default 6).
+2. `filter_by_role` — interesting-role whitelist + non-empty name.
+3. `filter_on_screen` — bounding rect at least 50% inside the primary monitor.
-Ziel: <= 150 Nodes. Bei Ueberschreitung iteriert `UIATreeSource` mit kleineren
-Depths (6 -> 5 -> 4). Die Helpers selbst sind stateless und arbeiten auf einer
-einfachen RawNode-Dataclass, damit sie ohne pywinauto testbar bleiben.
+Goal: <= 150 nodes. On overflow, `UIATreeSource` iterates with smaller
+depths (6 -> 5 -> 4). The helpers themselves are stateless and operate on a
+simple RawNode dataclass, so they stay testable without pywinauto.
-Designziel: reine Python-Funktionen, kein Windows-API-Call — Contract-Test
-laeuft auf beliebigem OS.
+Design goal: pure Python functions, no Windows API calls — the contract
+test runs on any OS.
"""
from __future__ import annotations
from dataclasses import dataclass, field
# ---------------------------------------------------------------------------
-# RawNode — intermediate Darstellung waehrend der Traversal.
+# RawNode — intermediate representation during the traversal.
# ---------------------------------------------------------------------------
@dataclass
class RawNode:
- """Zwischenmodell vor dem Pruning. Wird vor Konvertierung zu
- `jarvis.core.protocols.UIANode` verwendet.
+ """Intermediate model before pruning. Used before conversion to
+ `jarvis.core.protocols.UIANode`.
- Felder entsprechen den Properties, die `UIAElementInfo` liefert — wir
- bilden bewusst nicht das gesamte Objekt ab, sondern nur, was fuer die
- Pruning-Filter und die spaetere Serialisierung relevant ist.
+ Fields correspond to the properties `UIAElementInfo` provides — we
+ deliberately do not mirror the whole object, only what's relevant for
+ the pruning filters and the later serialization.
"""
role: str = ""
name: str = ""
@@ -45,12 +45,12 @@ class RawNode:
# focus is verifiable post-hoc). Best-effort per OS; default False.
is_password: bool = False
focused: bool = False
- # Kinder-Indizes werden waehrend der Traversal im Tree-Builder verwaltet.
+ # Child indices are managed by the tree builder during the traversal.
children: list[int] = field(default_factory=list)
# ---------------------------------------------------------------------------
-# Default-Konstanten (ADR-0002)
+# Default constants (ADR-0002)
# ---------------------------------------------------------------------------
DEFAULT_MAX_DEPTH: int = 6
@@ -71,14 +71,15 @@ DEFAULT_INTERESTING_ROLES: tuple[str, ...] = (
# ---------------------------------------------------------------------------
-# Filter
+# Filters
# ---------------------------------------------------------------------------
def filter_by_depth(nodes: list[RawNode], *, max_depth: int) -> list[RawNode]:
- """Behaelt nur Nodes mit `depth <= max_depth`.
+ """Keeps only nodes with `depth <= max_depth`.
- Root hat depth=0. Ein max_depth von 6 erlaubt also 7 Ebenen inklusive
- Root — das entspricht der ADR-0002-Definition ("ab Root-Window").
+ Root has depth=0. A max_depth of 6 thus allows 7 levels including
+ root — that matches the ADR-0002 definition ("starting from the root
+ window").
"""
return [n for n in nodes if n.depth <= max_depth]
@@ -88,12 +89,12 @@ def filter_by_role(
*,
interesting_roles: tuple[str, ...] = DEFAULT_INTERESTING_ROLES,
) -> list[RawNode]:
- """Behaelt nur Nodes, deren Role in der Whitelist steht und die einen
- nicht-leeren Namen haben.
+ """Keeps only nodes whose role is on the whitelist and that have a
+ non-empty name.
- Ausnahme: Nodes mit nicht-leerer AutomationId werden ebenfalls behalten,
- auch wenn der Name leer ist — die AutomationId ist oft der stabilere
- Anker fuer Clicks.
+ Exception: nodes with a non-empty AutomationId are also kept even if
+ the name is empty — the AutomationId is often the more stable anchor
+ for clicks.
"""
kept: list[RawNode] = []
for node in nodes:
@@ -109,15 +110,15 @@ def rect_overlap_fraction(
bounds: tuple[int, int, int, int],
monitor_bounds: tuple[int, int, int, int],
) -> float:
- """Anteil von `bounds` innerhalb `monitor_bounds` (0.0–1.0).
+ """Fraction of `bounds` inside `monitor_bounds` (0.0–1.0).
- Bounds-Format (x, y, w, h). Wenn das Node-Rect 0 Flaeche hat, return 0.0.
+ Bounds format (x, y, w, h). If the node rect has 0 area, returns 0.0.
"""
bx, by, bw, bh = bounds
if bw <= 0 or bh <= 0:
return 0.0
mx, my, mw, mh = monitor_bounds
- # Schnittflaeche berechnen
+ # Compute the intersection area
ix1 = max(bx, mx)
iy1 = max(by, my)
ix2 = min(bx + bw, mx + mw)
@@ -135,11 +136,11 @@ def filter_on_screen(
monitor_bounds: tuple[int, int, int, int],
min_overlap: float = 0.5,
) -> list[RawNode]:
- """Behaelt nur Nodes, deren BoundingRect mindestens `min_overlap` (Default
- 0.5) innerhalb des Primary-Monitors liegt UND die nicht als `IsOffscreen`
- markiert sind.
+ """Keeps only nodes whose bounding rect lies at least `min_overlap`
+ (default 0.5) inside the primary monitor AND that are not marked as
+ `IsOffscreen`.
- `monitor_bounds` im selben Format wie `bounds`: (x, y, w, h).
+ `monitor_bounds` uses the same format as `bounds`: (x, y, w, h).
"""
kept: list[RawNode] = []
for node in nodes:
@@ -155,24 +156,24 @@ def _remap_parent_indices(
kept: list[RawNode],
original: list[RawNode],
) -> None:
- """H1-Fix: Nach Pruning muss ``parent_index`` auf den Index des
- naechsten erhaltenen Vorfahren **im gepruenten Subset** zeigen —
- nicht mehr auf den Index in der Original-Liste.
+ """H1 fix: after pruning, ``parent_index`` must point to the index of the
+ nearest surviving ancestor **in the pruned subset** — no longer to the
+ index in the original list.
- Mutiert ``kept`` in-place. Wenn kein Vorfahre ueberlebt hat, wird
- ``parent_index = -1`` gesetzt (Root bzw. disconnected).
+ Mutates ``kept`` in place. If no ancestor survived, ``parent_index = -1``
+ is set (root or disconnected).
"""
kept_to_new_idx: dict[int, int] = {id(n): i for i, n in enumerate(kept)}
for n in kept:
original_parent = n.parent_index
- n.parent_index = -1 # Default falls kein Vorfahre
+ n.parent_index = -1 # Default if no ancestor survives
while 0 <= original_parent < len(original):
parent_node = original[original_parent]
new_idx = kept_to_new_idx.get(id(parent_node))
if new_idx is not None:
n.parent_index = new_idx
break
- # Vorfahre wurde wegge-prunt → eine Ebene hoch suchen.
+ # Ancestor was pruned away → search one level up.
original_parent = parent_node.parent_index
@@ -184,28 +185,28 @@ def prune_tree(
monitor_bounds: tuple[int, int, int, int] = (0, 0, 1920, 1080),
min_overlap: float = 0.5,
) -> list[RawNode]:
- """Wendet die drei Filter in kanonischer Reihenfolge an (depth -> role
- -> on-screen). Returned eine neue Liste, Eingabe bleibt unveraendert.
+ """Applies the three filters in canonical order (depth -> role ->
+ on-screen). Returns a new list; the input is left unchanged.
- Root bleibt immer erhalten (Index 0) — auch wenn er selbst nicht in die
- Interesting-Roles-Liste faellt. Andernfalls verlieren wir die parent-
- Hierarchie vollstaendig.
+ Root is always kept (index 0) — even if it doesn't itself fall into the
+ interesting-roles list. Otherwise we'd lose the parent hierarchy
+ entirely.
- H1-Fix: parent_index der verbleibenden Nodes wird auf den Subset-Index
- remapped (via ``_remap_parent_indices``).
+ H1 fix: the remaining nodes' parent_index is remapped to the subset
+ index (via ``_remap_parent_indices``).
"""
if not nodes:
return []
- # Filter 1: Depth
+ # Filter 1: depth
after_depth = filter_by_depth(nodes, max_depth=max_depth)
- # Filter 2: Rolle — Root (depth=0) ist davon ausgenommen.
+ # Filter 2: role — root (depth=0) is exempt from this.
root = after_depth[0] if after_depth else None
after_role = [
n for n in after_depth
if n is root
or (n.role in interesting_roles and (n.name or n.automation_id))
]
- # Filter 3: On-Screen — Root bleibt immer erhalten.
+ # Filter 3: on-screen — root is always kept.
after_screen = [
n for n in after_role
if n is root or (
@@ -213,11 +214,10 @@ def prune_tree(
and rect_overlap_fraction(n.bounds, monitor_bounds) >= min_overlap
)
]
- # Kept-Liste sind Referenzen auf dieselben Objekte wie in ``nodes`` —
- # damit wir den Original-Vorfahrencheck via ``is``/``id()`` machen koennen.
- # Wir machen eine Shallow-Copy, damit der Caller die Original-Liste
- # behaelt (parent_index-Mutation wirkt sich auf beide aus; das ist
- # Pragma-Kompromiss — Caller sollte nicht nach prune_tree die Original
- # erneut nutzen).
+ # The kept list holds references to the same objects as in ``nodes`` —
+ # so we can do the original-ancestor check via ``is``/``id()``.
+ # We make a shallow copy so the caller keeps the original list
+ # (parent_index mutation affects both; that's a pragmatic compromise —
+ # the caller shouldn't reuse the original list after prune_tree).
_remap_parent_indices(after_screen, nodes)
return after_screen
diff --git a/jarvis/vision/screenshot.py b/jarvis/vision/screenshot.py
index 11b4ffaffc..3b7da66cf2 100644
--- a/jarvis/vision/screenshot.py
+++ b/jarvis/vision/screenshot.py
@@ -1,22 +1,22 @@
-"""ScreenshotSource — Primary-Monitor-Screenshot via mss.
+"""ScreenshotSource — primary-monitor screenshot via mss.
-Liefert eine `Observation` mit `source="screenshot_only"` (keine UIA-Nodes,
-die Source ist reiner Bildzug). Falls gewuenscht wird der PNG-Blob unter
-`data/flight_recorder/blobs/<sha256>.png` abgelegt, damit der Flight-Recorder
-die Roh-Observation replayen kann.
+Returns an `Observation` with `source="screenshot_only"` (no UIA nodes,
+the source is pure image capture). If desired, the PNG blob is stored under
+`data/flight_recorder/blobs/<sha256>.png` so the flight recorder can replay
+the raw observation.
-Wichtige Windows-Spezifika (ADR-0002 plus Erfahrung aus Phase 1c):
+Important Windows specifics (ADR-0002 plus experience from Phase 1c):
-- `SetProcessDpiAwareness(2)` muss einmal beim Init aufgerufen werden.
- Ohne das liefert Windows auf 125 %/150 %-Scaling-Setups verzerrte
- Koordinaten (virtuelle statt physische Pixel), was spaeter beim
- `pyautogui.click(x, y)` zu systematischem Miss fuehrt.
-- mss liefert BGRA; Pillow schreibt PNG aus einem RGB/RGBA-Array. Wir
- konvertieren explizit, damit der Hash stabil ist (BGRA-Rohbytes sind
- nicht portabel).
+- `SetProcessDpiAwareness(2)` must be called once at init. Without it,
+ Windows returns distorted coordinates (virtual instead of physical
+ pixels) on 125%/150% scaling setups, which later causes systematic
+ misses in `pyautogui.click(x, y)`.
+- mss delivers BGRA; Pillow writes PNG from an RGB/RGBA array. We
+ convert explicitly so the hash is stable (raw BGRA bytes are not
+ portable).
-Der Screenshot ist synchron-blockierend; wir wrappen ihn in
-`asyncio.to_thread` damit der Event-Loop responsive bleibt.
+The screenshot is a synchronous, blocking call; we wrap it in
+`asyncio.to_thread` so the event loop stays responsive.
"""
from __future__ import annotations
@@ -34,8 +34,8 @@ from jarvis.core.protocols import CancelToken, Observation
logger = logging.getLogger(__name__)
-# Default-Blob-Verzeichnis — liegt unter Repo-Root/data. Kann ueber den
-# Konstruktor ueberschrieben werden (z.B. fuer Tests).
+# Default blob directory — lives under repo-root/data. Can be overridden via
+# the constructor (e.g. for tests).
_DEFAULT_BLOB_DIR = Path("data") / "flight_recorder" / "blobs"
# H1 (DEEP-DIVE-AUDIT-2026-06-19): on macOS, screen capture is gated behind a
@@ -77,9 +77,9 @@ def warn_if_screen_recording_denied() -> bool:
# ---------------------------------------------------------------------------
-# DPI-Awareness — extrahiert nach jarvis/core/win32_dpi.py (Phase A1).
-# Re-Export hier damit alter Code (Tests, Vision-Engine) ohne Aenderung
-# weiterlaeuft.
+# DPI awareness — extracted to jarvis/core/win32_dpi.py (Phase A1).
+# Re-exported here so old code (tests, vision engine) keeps working
+# without changes.
# ---------------------------------------------------------------------------
from jarvis.core.win32_dpi import ensure_dpi_awareness as _ensure_dpi_awareness # noqa: E402
@@ -113,21 +113,21 @@ def select_capture_monitor(
strategy: MonitorStrategy = "foreground",
primary_override: str = "primary",
) -> dict:
- """Waehlt den Monitor, von dem ein Screenshot gegrabbt werden soll.
+ """Selects the monitor a screenshot should be grabbed from.
- ``mss.monitors`` ist 1-indexiert fuer physische Bildschirme; ``[0]`` ist
- die virtuelle Bounding-Box ueber alle. Auf Multi-Monitor-Setups ist
- hardcoded ``[1]`` falsch, sobald der User auf einem anderen Display
- arbeitet — Jarvis wuerde sonst einen "leeren" Monitor sehen, waehrend
- der User auf einem anderen aktiv ist. Die Default-Strategie ``foreground``
- folgt deshalb dem aktiven Fenster.
+ ``mss.monitors`` is 1-indexed for physical screens; ``[0]`` is
+ the virtual bounding box over all of them. On multi-monitor setups,
+ the hardcoded ``[1]`` is wrong as soon as the user works on a different
+ display — Jarvis would otherwise see an "empty" monitor while the user
+ is active on another one. The default strategy ``foreground`` therefore
+ follows the active window.
- Strategien:
+ Strategies:
- - ``"foreground"`` — Foreground-Window-Center -> Monitor-Lookup.
- Fallback bei minimiertem/unauffindbarem Fenster: Primary.
- - ``"primary"`` — explizit der Primaer-Monitor (mss-typisch ``[1]``).
- - ``"all"`` — virtuelle Bounding-Box ueber alle Monitore (``[0]``).
+ - ``"foreground"`` — foreground-window center -> monitor lookup.
+ Fallback for a minimized/unfindable window: primary.
+ - ``"primary"`` — explicitly the primary monitor (mss-typical ``[1]``).
+ - ``"all"`` — virtual bounding box over all monitors (``[0]``).
"""
if len(monitors) <= 1:
return monitors[0]
@@ -162,14 +162,14 @@ def select_capture_monitor(
hwnd = ctypes.windll.user32.GetForegroundWindow()
if not hwnd:
logger.debug(
- "select_capture_monitor: kein Foreground-Window — fallback auf primary",
+ "select_capture_monitor: no foreground window — falling back to primary",
)
return primary
rect = wintypes.RECT()
if not ctypes.windll.user32.GetWindowRect(hwnd, ctypes.byref(rect)):
logger.debug(
- "select_capture_monitor: GetWindowRect fehlgeschlagen — fallback auf primary",
+ "select_capture_monitor: GetWindowRect failed — falling back to primary",
)
return primary
@@ -183,7 +183,7 @@ def select_capture_monitor(
if left <= cx < right and top <= cy < bottom:
if m is not primary:
logger.info(
- "select_capture_monitor: Foreground auf %s (left=%d top=%d %dx%d) — capture dort statt Primary",
+ "select_capture_monitor: foreground on %s (left=%d top=%d %dx%d) — capturing there instead of primary",
m.get("name"),
left,
top,
@@ -192,22 +192,22 @@ def select_capture_monitor(
)
else:
logger.debug(
- "select_capture_monitor: Foreground auf Primary %s",
+ "select_capture_monitor: foreground on primary %s",
m.get("name"),
)
return m
- # Foreground-Center liegt ausserhalb aller physischen Monitore
- # (z.B. Fenster minimiert -> rect = -32000/-32000).
+ # Foreground center lies outside all physical monitors
+ # (e.g. window minimized -> rect = -32000/-32000).
logger.debug(
- "select_capture_monitor: Foreground-Center (%d,%d) auf keinem Monitor — fallback auf primary",
+ "select_capture_monitor: foreground center (%d,%d) is on no monitor — falling back to primary",
cx,
cy,
)
return primary
except Exception: # noqa: BLE001
logger.warning(
- "select_capture_monitor: Foreground-Detection fehlgeschlagen, nutze Primary",
+ "select_capture_monitor: foreground detection failed, using primary",
exc_info=True,
)
return primary
@@ -286,22 +286,22 @@ def capture_region(
class ScreenshotSource:
- """Nimmt Screenshots vom richtigen Monitor via mss auf.
-
- Erfuellt `jarvis.core.protocols.VisionSource` strukturell — kein
- `isinstance`-Import noetig.
-
- Monitor-Strategie (Default: ``"foreground"``):
-
- - ``"foreground"`` — folgt dem aktiven Fenster (GetForegroundWindow +
- GetWindowRect → Monitor-Lookup ueber den Window-Mittelpunkt). Damit
- sieht Jarvis das, was der User gerade vor sich hat, auch auf
- Multi-Monitor-Setups. Fallback bei minimiertem/unauffindbarem
- Fenster: Primary-Monitor.
- - ``"primary"`` — alter Hardcode (mss.monitors[1]). Nur fuer
- Regression-Tests / explizite Einzel-Monitor-Setups.
- - ``"all"`` — virtuelle Bounding-Box ueber alle Monitore
- (mss.monitors[0]). Token-teuer, aber maximaler Kontext.
+ """Takes screenshots from the correct monitor via mss.
+
+ Structurally satisfies `jarvis.core.protocols.VisionSource` — no
+ `isinstance` import needed.
+
+ Monitor strategy (default: ``"foreground"``):
+
+ - ``"foreground"`` — follows the active window (GetForegroundWindow +
+ GetWindowRect → monitor lookup via the window's center point). This
+ way Jarvis sees what the user currently has in front of them, even on
+ multi-monitor setups. Fallback for a minimized/unfindable window:
+ the primary monitor.
+ - ``"primary"`` — the old hardcode (mss.monitors[1]). Only for
+ regression tests / explicit single-monitor setups.
+ - ``"all"`` — virtual bounding box over all monitors
+ (mss.monitors[0]). Token-expensive, but maximum context.
"""
name: str = "screenshot"
@@ -343,13 +343,13 @@ class ScreenshotSource:
self,
*,
cancel_token: CancelToken | None = None,
- window_title_filter: str | None = None, # noqa: ARG002 — fuer Protocol-Signatur
+ window_title_filter: str | None = None, # noqa: ARG002 — for the protocol signature
) -> Observation | None:
- """Nimmt einen Primary-Monitor-Screenshot auf.
+ """Takes a primary-monitor screenshot.
- `window_title_filter` wird hier ignoriert — ein reiner Screenshot
- kann nicht pro-Fenster gefiltert werden. Der Parameter bleibt aber
- in der Signatur wegen dem Protocol.
+ `window_title_filter` is ignored here — a plain screenshot can't be
+ filtered per window. The parameter still stays in the signature
+ because of the protocol.
Returns None when the GDI/BitBlt grab fails transiently (display
asleep, locked workstation, resolution change). The caller (engine /
@@ -358,11 +358,11 @@ class ScreenshotSource:
refresh loop alive during monitor power-save / lock-screen events.
"""
if self._closed:
- raise RuntimeError("ScreenshotSource ist geschlossen")
+ raise RuntimeError("ScreenshotSource is closed")
if cancel_token is not None and cancel_token.is_cancelled():
raise RuntimeError(f"cancelled: {cancel_token.reason}")
- # Screenshot synchron — Thread-Pool wegen blockierender GDI-Calls.
+ # Screenshot is synchronous — thread pool because of blocking GDI calls.
image_bytes = await asyncio.to_thread(self._capture_image)
# _capture_image returns None on a transient BitBlt / GDI error.
@@ -380,13 +380,13 @@ class ScreenshotSource:
try:
blob_path = await asyncio.to_thread(self._write_blob, sha, image_bytes)
except OSError as exc:
- # Write-Fehler (Permission denied, Disk full, Antivirus-Block)
- # duerfen die Observation nicht canceln — aber wir muessen es
- # laut loggen, sonst kriegt der Router spaeter screenshot_path
- # =None und der Vision-Inject-Pfad wirft ValueError silent.
+ # A write failure (permission denied, disk full, antivirus block)
+ # must not cancel the observation — but we do need to log it
+ # loudly, otherwise the router later gets screenshot_path=None
+ # and the vision-inject path silently raises a ValueError.
logger.error(
- "ScreenshotSource: Blob-Write nach %s fehlgeschlagen: %s "
- "— Observation wird ohne Disk-Pfad zurueckgegeben.",
+ "ScreenshotSource: blob write to %s failed: %s "
+ "— observation is returned without a disk path.",
self._blob_dir,
exc,
exc_info=True,
@@ -413,12 +413,12 @@ class ScreenshotSource:
# ---- Internals ---------------------------------------------------------
def _capture_image(self) -> bytes | None:
- """Blocking: nimmt Primary-Monitor auf und gibt Bild-Bytes zurueck.
+ """Blocking: takes a primary-monitor capture and returns image bytes.
- Format ist `self._image_format` — JPEG q85 default (8x kleiner als PNG
- bei identischen Token-Kosten, da Claude/GPT/Gemini in Pixel-Area
- rechnen, nicht in Bytes). PNG nur fuer Tests/Screenshots wo Pixel-
- perfekte Reproduktion gebraucht wird.
+ Format is `self._image_format` — JPEG q85 default (8x smaller than PNG
+ at identical token cost, since Claude/GPT/Gemini bill by pixel area,
+ not bytes). PNG only for tests/screenshots where pixel-perfect
+ reproduction is needed.
Returns None on transient GDI/BitBlt failure (display asleep, workstation
locked, resolution change, disconnected monitor). The caller must treat
@@ -426,18 +426,18 @@ class ScreenshotSource:
next successful grab. Only one WARNING is logged per error episode
(state-change logging: silent while the error persists, INFO on recovery).
"""
- # Late-Import, damit das Modul auch ohne mss importierbar bleibt
- # (Contract-Tests laufen so, selbst wenn die Dep fehlt).
+ # Late import, so the module stays importable even without mss
+ # (contract tests run this way even when the dep is missing).
try:
import mss # type: ignore[import-not-found] # noqa: PLC0415
except ImportError as exc:
raise RuntimeError(
- "mss ist nicht installiert — Dependency aus pyproject.toml fehlt"
+ "mss is not installed — dependency from pyproject.toml is missing"
) from exc
try:
from PIL import Image # noqa: PLC0415
except ImportError as exc:
- raise RuntimeError("pillow ist nicht installiert") from exc
+ raise RuntimeError("pillow is not installed") from exc
# Lazy import of the exception class — same pattern as the mss import
# above; keeps this module importable without mss installed.
@@ -501,16 +501,16 @@ class ScreenshotSource:
return buf.getvalue()
def _select_capture_monitor(self, monitors: list[dict]) -> dict:
- """Delegiert an die Modul-Funktion, damit andere Pfade
- (z.B. das ``screenshot``-Router-Tool) dieselbe Logik teilen koennen.
+ """Delegates to the module function, so other paths
+ (e.g. the ``screenshot`` router tool) can share the same logic.
"""
return select_capture_monitor(monitors, strategy=self._monitor_strategy)
def _write_blob(self, sha: str, image_bytes: bytes) -> str:
- """Speichert den Bild-Blob unter `<blob_dir>/<sha><ext>`."""
+ """Stores the image blob under `<blob_dir>/<sha><ext>`."""
self._blob_dir.mkdir(parents=True, exist_ok=True)
target = self._blob_dir / f"{sha}{self.file_extension}"
if not target.exists():
- # Atomares Write ist hier uebertrieben; sha im Namen ist Idempotenz.
+ # An atomic write is overkill here; the sha in the name gives idempotency.
target.write_bytes(image_bytes)
return str(target)
diff --git a/tests/missions/critic/test_capability_honesty.py b/tests/missions/critic/test_capability_honesty.py
index a16e48c210..5b3f35d789 100644
--- a/tests/missions/critic/test_capability_honesty.py
+++ b/tests/missions/critic/test_capability_honesty.py
@@ -183,7 +183,7 @@ def test_gate_passes_codex_worker_with_real_actions() -> None:
]
)
check = enforce_capability_honesty(
- user_request="Erstelle eine HTML-Datei und analysiere meine E-Mails",
+ user_request="Erstelle eine HTML-Datei und analysiere meine E-Mails", # i18n-allow (simulated German user request)
verdict=_approval_verdict(),
worker_output=stream,
)
@@ -255,9 +255,9 @@ def test_request_is_messaging_action() -> None:
assert _request_is_messaging_action("reply to the message from Tom") is True
# artefact tasks that only MENTION the topic must NOT be misclassified
assert _request_is_messaging_action(
- "Erstelle einen HTML-Report über meine E-Mails"
+ "Erstelle einen HTML-Report über meine E-Mails" # i18n-allow (simulated German user request)
) is False
- assert _request_is_messaging_action("Mach eine HTML-Datei zum Aktienmarkt") is False
+ assert _request_is_messaging_action("Mach eine HTML-Datei zum Aktienmarkt") is False # i18n-allow (simulated German user request)
def _force_requires_evidence(monkeypatch: pytest.MonkeyPatch) -> None:
@@ -278,7 +278,7 @@ def test_gate_credits_worktree_diff_for_prose_worker(
still said 'made no tool call' and burned all three critic loops)."""
_force_requires_evidence(monkeypatch)
check = enforce_capability_honesty(
- user_request="Mach eine visuell ansprechende HTML-Datei zum Aktienmarkt",
+ user_request="Mach eine visuell ansprechende HTML-Datei zum Aktienmarkt", # i18n-allow (simulated German user request)
verdict=_approval_verdict(),
worker_output=_AGY_PROSE, # NO tool_use frames at all
worker_diff=_REAL_GIT_DIFF,
@@ -295,7 +295,7 @@ def test_gate_still_blocks_prose_worker_with_empty_diff(
tool frame still fails, even for a CLI worker."""
_force_requires_evidence(monkeypatch)
check = enforce_capability_honesty(
- user_request="Mach eine visuell ansprechende HTML-Datei zum Aktienmarkt",
+ user_request="Mach eine visuell ansprechende HTML-Datei zum Aktienmarkt", # i18n-allow (simulated German user request)
verdict=_approval_verdict(),
worker_output=_AGY_PROSE,
worker_diff="", # nothing written
@@ -312,7 +312,7 @@ def test_gate_messaging_action_ignores_file_diff(
credit must not re-open the 'I have sent the email' hallucination)."""
_force_requires_evidence(monkeypatch)
check = enforce_capability_honesty(
- user_request="Sende eine E-Mail an Max mit der Zusammenfassung",
+ user_request="Sende eine E-Mail an Max mit der Zusammenfassung", # i18n-allow (simulated German user request)
verdict=_approval_verdict(),
worker_output=_AGY_PROSE,
worker_diff=_REAL_GIT_DIFF, # wrote a file, but that's not a sent email