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.

docs(core): explain intentional exception fallbacks

rubenluetke10-beep55c05951ea00
diff --git a/jarvis/agent_chat/cli_catalog.py b/jarvis/agent_chat/cli_catalog.py
index fcf783a25c..ac36520d3b 100644
--- a/jarvis/agent_chat/cli_catalog.py
+++ b/jarvis/agent_chat/cli_catalog.py
@@ -59,7 +59,7 @@ def catalog_key(argv: list[str], env: Mapping[str, str], cwd: Path) -> str:
try:
stat = path.stat()
stamps.append((str(path), stat.st_mtime_ns, stat.st_size))
- except OSError:
+ except OSError: # Missing optional CLI metadata gets an empty cache stamp.
stamps.append((str(path), None, None))
payload = json.dumps([argv, sorted(env.items()), str(cwd), stamps], sort_keys=True)
return hashlib.sha256(payload.encode()).hexdigest()
diff --git a/jarvis/agent_chat/control.py b/jarvis/agent_chat/control.py
index 4eba58585f..1b11fe5219 100644
--- a/jarvis/agent_chat/control.py
+++ b/jarvis/agent_chat/control.py
@@ -708,7 +708,7 @@ class ChatControls:
event = await queue.get()
if relevant(event):
return json.dumps(event["payload"], ensure_ascii=False)
- except TimeoutError:
+ except TimeoutError: # The caller receives a pending update notice.
return "No background update yet. Check the existing task; do not submit it again."
finally:
self.service.unsubscribe(sid, queue)
diff --git a/jarvis/agent_chat/control_eval.py b/jarvis/agent_chat/control_eval.py
index f0a95bfcb6..935966f9ad 100644
--- a/jarvis/agent_chat/control_eval.py
+++ b/jarvis/agent_chat/control_eval.py
@@ -165,7 +165,7 @@ async def evaluate_goal(
continue
try:
data = json.loads(str(event["payload"].get("output") or "null"))
- except ValueError:
+ except ValueError: # Ignore malformed tool output; other events still determine status.
continue
if isinstance(data, dict):
status = str(data.get("status") or data.get("state") or "").lower()
diff --git a/jarvis/agent_chat/media.py b/jarvis/agent_chat/media.py
index 4e74801254..453355a30d 100644
--- a/jarvis/agent_chat/media.py
+++ b/jarvis/agent_chat/media.py
@@ -96,7 +96,7 @@ def media_type(reference: str, hint: str = "") -> str | None:
or normalized.startswith("/api/")
else normalized
)
- except ValueError:
+ except ValueError: # An invalid media URL has no supported type.
return None
path = re.sub(r"/(download|raw|view)$", "", path)
return MEDIA_TYPES.get(Path(path).suffix.lower())
@@ -428,7 +428,7 @@ def normalize_media_event(
if isinstance(value, str):
try:
parsed = json.loads(value) if value.lstrip().startswith(("{", "[")) else None
- except ValueError:
+ except ValueError: # Malformed JSON falls through to text normalization.
parsed = None
processed = normalizer.structured(parsed, scan_text=True) if parsed is not None else None
rewritten = (
diff --git a/jarvis/agent_chat/native_control.py b/jarvis/agent_chat/native_control.py
index 3a86eb5032..365a7de067 100644
--- a/jarvis/agent_chat/native_control.py
+++ b/jarvis/agent_chat/native_control.py
@@ -136,7 +136,7 @@ class NativeClaudeGoal:
)
try:
response = json.loads(probe.stdout)
- except ValueError:
+ except ValueError: # An invalid probe response means the engine is unavailable.
return False
if not isinstance(response, dict):
return False
@@ -384,7 +384,7 @@ class GoalRpc:
pass # Tree containment already reaped the process.
try:
await asyncio.wait_for(self.proc.wait(), timeout=3)
- except TimeoutError:
+ except TimeoutError: # Teardown escalates from a bounded wait to killing the child.
self.proc.kill()
await self.proc.wait()
diff --git a/jarvis/agent_chat/service.py b/jarvis/agent_chat/service.py
index d314f310bd..c728529ef4 100644
--- a/jarvis/agent_chat/service.py
+++ b/jarvis/agent_chat/service.py
@@ -116,7 +116,7 @@ def stop_cli_at_cwd(cwd: str) -> int:
root = Path(cwd).expanduser()
try:
root = root.resolve()
- except OSError:
+ except OSError: # An unresolvable workspace cannot match a running process.
return 0
if not root.is_dir():
return 0
@@ -905,7 +905,7 @@ class AgentChatService:
assert run is not None and run.task is not None
try:
await asyncio.wait_for(asyncio.shield(run.task), timeout=15.0)
- except TimeoutError:
+ except TimeoutError: # Stop escalates to task cancellation after the bounded wait.
run.task.cancel()
await asyncio.gather(run.task, return_exceptions=True)
except asyncio.CancelledError:
diff --git a/jarvis/cli_ctl/commands/auth.py b/jarvis/cli_ctl/commands/auth.py
index 715e141674..e70cd322ed 100644
--- a/jarvis/cli_ctl/commands/auth.py
+++ b/jarvis/cli_ctl/commands/auth.py
@@ -20,7 +20,7 @@ def _probe(url: str, key: str) -> bool:
with make_client(url=url, key=key) as client:
client.request("GET", _PROBE)
return True
- except ApiError:
+ except ApiError: # The probe reports an unreachable server through its Boolean result.
return False
@@ -69,7 +69,7 @@ def status(
try:
client.request("GET", _PROBE)
reachable = True
- except ApiError:
+ except ApiError: # The command emits reachable=false and exits with a failure code.
reachable = False
render.emit({"base_url": target, "reachable": reachable}, as_json=as_json())
if not reachable:
diff --git a/jarvis/dictation/local_preview.py b/jarvis/dictation/local_preview.py
index 8d6c314a58..7d2b29ce6f 100644
--- a/jarvis/dictation/local_preview.py
+++ b/jarvis/dictation/local_preview.py
@@ -678,7 +678,7 @@ class LocalPreviewTranscriber:
self._loading = True
try:
loop = asyncio.get_running_loop()
- except RuntimeError:
+ except RuntimeError: # Without a running loop, model loading uses a daemon thread.
threading.Thread(
target=self._load_model, name="dictation-preview-load", daemon=True
).start()
@@ -736,7 +736,7 @@ class LocalPreviewTranscriber:
if callable(close):
try:
loop = asyncio.get_running_loop()
- except RuntimeError:
+ except RuntimeError: # Without a running loop, close the preview synchronously.
close()
else:
diff --git a/jarvis/live/session.py b/jarvis/live/session.py
index 7c7a82480a..1099369755 100644
--- a/jarvis/live/session.py
+++ b/jarvis/live/session.py
@@ -800,7 +800,7 @@ class LiveVoiceSession:
result = await self._tools.execute(
f"{self._wire_epoch}:{item['call_id']}", item["name"], arguments, revision
)
- except (ValueError, TypeError):
+ except (ValueError, TypeError): # The tool receives an invalid-arguments result.
result = {"success": False, "error": "Invalid function arguments."}
if self._closing:
return
diff --git a/jarvis/platform/open_path.py b/jarvis/platform/open_path.py
index 72ab19fcaa..934a5f52f7 100644
--- a/jarvis/platform/open_path.py
+++ b/jarvis/platform/open_path.py
@@ -199,7 +199,7 @@ def _windows_default_browser_exe() -> str | None:
"""
try:
import winreg
- except ImportError:
+ except ImportError: # Registry integration is optional outside Windows.
return None
try:
with winreg.OpenKey(
@@ -212,7 +212,7 @@ def _windows_default_browser_exe() -> str | None:
winreg.HKEY_CLASSES_ROOT, rf"{progid}\shell\open\command"
) as key:
command, _ = winreg.QueryValueEx(key, "") # "" = the (Default) value
- except OSError:
+ except OSError: # An absent registry association leaves no executable to open.
return None
exe = _parse_exe_from_shell_command(command)
if exe and exe.lower().endswith(".exe") and Path(exe).exists():
@@ -572,7 +572,7 @@ def _inside(root: Path, candidate: Path) -> bool:
try:
resolved_root = root.resolve()
resolved = candidate.resolve()
- except OSError:
+ except OSError: # Unresolvable candidates fail the containment check closed.
return False
return resolved == resolved_root or resolved_root in resolved.parents
@@ -617,7 +617,7 @@ def _existing_absolute(native: str) -> Path | None:
return None
try:
target = path.resolve()
- except OSError:
+ except OSError: # An unresolvable target is not an openable local path.
return None
if target.exists() and (target.is_file() or target.is_dir()):
return target
diff --git a/jarvis/plugins/tool/delegate_to_agent.py b/jarvis/plugins/tool/delegate_to_agent.py
index 42073537ac..a7e2c9a186 100644
--- a/jarvis/plugins/tool/delegate_to_agent.py
+++ b/jarvis/plugins/tool/delegate_to_agent.py
@@ -205,7 +205,7 @@ class DelegateToAgentTool:
try:
policy = select_reply_policy(args.get("reply_policy"), MsgType.ASSIGN)
- except (TypeError, ValueError) as exc:
+ except (TypeError, ValueError) as exc: # Invalid policy returns a failed tool result.
return ToolResult(success=False, output=None, error=str(exc))
context = str(args.get("context") or "").strip()
criteria = str(args.get("completion_criteria") or "").strip()
diff --git a/jarvis/setup/macos_app_bundle.py b/jarvis/setup/macos_app_bundle.py
index 08e3684421..fb14b1978d 100644
--- a/jarvis/setup/macos_app_bundle.py
+++ b/jarvis/setup/macos_app_bundle.py
@@ -227,7 +227,7 @@ def _is_macho_executable(path: Path) -> bool:
mode = path.stat().st_mode
with path.open("rb") as stream:
magic = stream.read(4)
- except OSError:
+ except OSError: # An unreadable binary cannot pass the bundle probe.
return False
# Windows cannot represent POSIX execute bits. The only Windows caller is
# the explicit cross-platform fixture seam; production validation runs on
@@ -260,6 +260,7 @@ def _codesign_issue(bundle: Path) -> str | None:
creationflags=NO_WINDOW_CREATIONFLAGS,
)
except (OSError, subprocess.TimeoutExpired) as exc:
+ # The caller receives the verification failure as a diagnostic.
return f"codesign verification did not run: {exc}"
if result.returncode == 0:
return None
@@ -284,7 +285,7 @@ def _bundle_cdhash(bundle: Path) -> str | None:
check=False,
creationflags=NO_WINDOW_CREATIONFLAGS,
)
- except (OSError, subprocess.TimeoutExpired):
+ except (OSError, subprocess.TimeoutExpired): # A failed code-hash probe has no usable hash.
return None
# codesign prints the display block on stderr.
match = re.search(r"^CDHash=([0-9a-f]+)", result.stderr or "", re.MULTILINE)
@@ -457,6 +458,7 @@ def _launchable_issue(candidate: Path) -> str | None:
with info_path.open("rb") as stream:
info = plistlib.load(stream)
except (OSError, plistlib.InvalidFileException) as exc:
+ # The caller receives the plist failure text.
return f"Info.plist is unreadable: {exc}"
executable_name = info.get("CFBundleExecutable")
if not isinstance(executable_name, str) or Path(executable_name).name != executable_name:
@@ -734,14 +736,14 @@ def _prefer_unversioned_runtime(dylib: Path, base_prefix: Path | None) -> Path:
return dylib
try:
relative = dylib.relative_to(base_prefix)
- except ValueError:
+ except ValueError: # A library outside the base prefix keeps its original path.
return dylib
candidate = base_prefix.with_name(match.group("head") + (match.group("tail") or ""))
sibling = candidate / relative
try:
if sibling.is_file():
return sibling
- except OSError:
+ except OSError: # A missing sibling library keeps the original path.
return dylib
return dylib
@@ -950,6 +952,7 @@ def _runtime_identity_valid(
and payload.get("machine") == platform.machine()
)
except (OSError, ValueError, json.JSONDecodeError, subprocess.TimeoutExpired) as exc:
+ # Diagnostics record the unavailable identity before this probe fails.
if diagnostics is not None:
diagnostics.append(f"identity probe failed: {type(exc).__name__}: {exc}")
return False
@@ -1003,6 +1006,7 @@ def _running_managed_bundle(
diagnostics.extend(f"current process: {reason}" for reason in reasons)
return None if reasons else current_bundle
except (ImportError, OSError, TypeError, ValueError) as exc:
+ # Diagnostics record the failed process probe when requested.
if diagnostics is not None:
diagnostics.append(f"current process: probe failed: {type(exc).__name__}: {exc}")
return None
@@ -1054,6 +1058,7 @@ def _bundle_version(bundle: Path) -> str | None:
with (bundle / "Contents" / "Info.plist").open("rb") as stream:
version = plistlib.load(stream).get("CFBundleShortVersionString")
except (OSError, ValueError, plistlib.InvalidFileException):
+ # An unreadable plist has no usable version.
return None
return version if isinstance(version, str) else None
diff --git a/jarvis/society/agent_tools.py b/jarvis/society/agent_tools.py
index ba3aa56d58..5e5ba94acc 100644
--- a/jarvis/society/agent_tools.py
+++ b/jarvis/society/agent_tools.py
@@ -171,7 +171,7 @@ class MessageAgentTool:
refs = args.get("refs")
try:
policy = select_reply_policy(args.get("reply_policy"), msg_type)
- except (TypeError, ValueError) as exc:
+ except (TypeError, ValueError) as exc: # Invalid reply policy returns a policy failure.
return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))
reply_status = args.get("reply_status", "done")
if reply_status not in ("done", "blocked"):
@@ -351,14 +351,14 @@ class WikiNoteTool:
rel, _ = await rt.memory.note(
caller, title, text, origin=origin, trace=trace, root=self._vault_root
)
- except MemoryRefused as exc:
+ except MemoryRefused as exc: # The caller receives the vault refusal as a policy failure.
return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))
try:
from .memory import build_memory_diff as _build_diff
vault = rt.memory.root(self._vault_root)
after_page = (vault / rel).read_text(encoding="utf-8")
- except OSError:
+ except OSError: # If the saved page is unreadable, report the submitted text instead.
after_page = text
return ToolResult(
success=True,
@@ -528,7 +528,7 @@ class ProposeChangeTool:
reason=str(args.get("reason") or ""),
session_id=self._session_id or caller.session_id,
)
- except ProposalRefused as exc:
+ except ProposalRefused as exc: # Return the proposal's explicit refusal reason.
return _failure(exc.reason, exc.detail)
if apply_now:
task_store, scheduler = rt.task_services()
@@ -637,7 +637,7 @@ class ShellTool:
return _failure(FailureReason.BLOCKED_BY_POLICY, "command is required")
try:
cwd = resolve_contained(self._workspace, args.get("cwd"))
- except ContainmentError as exc:
+ except ContainmentError as exc: # Return the workspace containment failure to the caller.
return _failure(FailureReason.BLOCKED_BY_POLICY, str(exc))
level = self._level(command)
tier = "ask" if level == DESTRUCTIVE else "monitor"
@@ -664,7 +664,7 @@ class ShellTool:
cwd.mkdir(parents=True, exist_ok=True)
try:
timeout = float(args.get("timeout_s") or DEFAULT_TIMEOUT_S)
- except (TypeError, ValueError):
+ except (TypeError, ValueError): # Invalid optional timeouts use the bounded default.
timeout = DEFAULT_TIMEOUT_S
result = await self._backend.run(command, cwd=cwd, timeout_s=timeout)
body = {
diff --git a/jarvis/society/coding_supervision.py b/jarvis/society/coding_supervision.py
index f1fde7a502..d99eb74d9c 100644
--- a/jarvis/society/coding_supervision.py
+++ b/jarvis/society/coding_supervision.py
@@ -179,7 +179,9 @@ class CodingSupervision:
)
except BaseException:
# A cancelled/crashed delivery remains inspectable and is never replayed.
- await self._pause_notice(key, "Assignment delivery interrupted. Inspect before resuming.")
+ await self._pause_notice(
+ key, "Assignment delivery interrupted. Inspect before resuming."
+ )
self._ensure_loop()
raise
row.update(
@@ -353,7 +355,7 @@ class CodingSupervision:
try:
if budget is not None:
budget.assert_under_limit(row["trace_id"])
- except Exception as exc:
+ except Exception as exc: # The pause notice reports the budget failure to the agent.
await self._pause_notice(key, f"Budget limit: {exc}")
return
if agent.daily_budget_usd > 0:
diff --git a/jarvis/society/conversation_tool.py b/jarvis/society/conversation_tool.py
index b227218db4..7e388466fe 100644
--- a/jarvis/society/conversation_tool.py
+++ b/jarvis/society/conversation_tool.py
@@ -142,5 +142,5 @@ class RoutineInvokeTool:
task_id, args.get("payload") or {}, str(uuid4()), mode="chat"
)
return ToolResult(status in {"queued", "duplicate", "filtered"}, {"status": status})
- except ValueError as exc:
+ except ValueError as exc: # Invalid input becomes an explicit failed tool result.
return ToolResult(False, {}, str(exc))
diff --git a/jarvis/society/mars/navigation_service.py b/jarvis/society/mars/navigation_service.py
index 7f412055f3..909dd5a015 100644
--- a/jarvis/society/mars/navigation_service.py
+++ b/jarvis/society/mars/navigation_service.py
@@ -244,7 +244,7 @@ class MarsNavigationService(RoverServiceMixin):
async def reauthorize(record):
try:
await self._authorize(record.agent_id, record.station_id, record.mode)
- except StationError as exc:
+ except StationError as exc: # Persist a denied or unavailable navigation receipt.
return record.command_id, (
"denied" if exc.status_code in {401, 403, 404} else "unavailable"
)
diff --git a/jarvis/society/mars/rover_service.py b/jarvis/society/mars/rover_service.py
index 0023a9e6cc..36cf86bb47 100644
--- a/jarvis/society/mars/rover_service.py
+++ b/jarvis/society/mars/rover_service.py
@@ -482,7 +482,7 @@ class RoverServiceMixin:
async def check(ride):
try:
await self._authorize(ride.agent_id, ride.vehicle_id, TravelMode.ROVER, rover=True)
- except StationError as exc:
+ except StationError as exc: # Return denied or unavailable for the rover receipt.
return ride.ride_id, "denied" if exc.status_code in {
401,
403,
diff --git a/jarvis/society/mars/service.py b/jarvis/society/mars/service.py
index 77afa66af1..b1fc7d9dda 100644
--- a/jarvis/society/mars/service.py
+++ b/jarvis/society/mars/service.py
@@ -143,7 +143,7 @@ class MarsStationService:
# A queued command's grants/agent state may have changed while waiting.
try:
await self._authorize(claimed.agent_id)
- except StationError as exc:
+ except StationError as exc: # Authorization failure is recorded against the command.
await self.store.apply(
claimed.command_id,
claimed.fence,
@@ -172,7 +172,7 @@ class MarsStationService:
receipt = ExecutionReceipt.model_validate(raw, strict=False)
if operation != "cancel" and receipt.cancel_attempt is not None:
raise ValueError("cancellation attempt evidence belongs only to cancel receipts")
- except DispatchRejected as exc:
+ except DispatchRejected as exc: # The receipt records the dispatch refusal.
if operation == "dispatch":
receipt = ExecutionReceipt(state=CommandState.FAILED)
reason = exc.reason
diff --git a/jarvis/society/proposals.py b/jarvis/society/proposals.py
index 23ed039ec7..5b44bcb015 100644
--- a/jarvis/society/proposals.py
+++ b/jarvis/society/proposals.py
@@ -459,7 +459,7 @@ async def apply(
try:
detail = await manage_routine(agent, payload, task_store, scheduler)
- except (ValueError, KeyError, RuntimeError) as exc:
+ except (ValueError, KeyError, RuntimeError) as exc: # Return the failure detail.
return {"applied": False, "detail": str(exc), "kind": kind}
return {"applied": True, "detail": detail, "kind": kind}
if await count_routines(task_store, agent.agent_id) >= MAX_ROUTINES_PER_AGENT:
@@ -473,7 +473,7 @@ async def apply(
announce_on_success=payload.get("announce_on_success"),
workflow_id=payload.get("workflow_id"),
)
- except (ValueError, KeyError) as exc:
+ except (ValueError, KeyError) as exc: # Return the invalid routine detail to the proposer.
return {"applied": False, "detail": f"invalid routine: {exc}", "kind": kind}
task_id = await create_routine(task_store, scheduler, spec)
return {"applied": True, "detail": f"routine scheduled ({task_id})", "kind": kind}
diff --git a/jarvis/society/routine_runner.py b/jarvis/society/routine_runner.py
index a6375504b7..c019ab2b29 100644
--- a/jarvis/society/routine_runner.py
+++ b/jarvis/society/routine_runner.py
@@ -168,7 +168,7 @@ async def run_owned_routine(
raise asyncio.CancelledError
try:
event = await asyncio.wait_for(queue.get(), timeout=0.25)
- except TimeoutError:
+ except TimeoutError: # An empty poll window simply waits for the next event.
continue
payload = event.get("payload") or {}
if payload.get("turn_id") not in (None, turn_id):
diff --git a/jarvis/society/runtime.py b/jarvis/society/runtime.py
index f6f9f7c43f..ce00d2bc71 100644
--- a/jarvis/society/runtime.py
+++ b/jarvis/society/runtime.py
@@ -220,7 +220,7 @@ class SocietyRuntime:
self._context_start_task = task
try:
return await asyncio.wait_for(asyncio.shield(task), timeout=timeout_s)
- except TimeoutError:
+ except TimeoutError: # A bounded wait reports that the task is still running.
return False
async def _start_for_context(self) -> bool:
@@ -823,7 +823,7 @@ class SocietyRuntime:
status = "blocked"
error = str(payload.get("error") or payload.get("status") or "")
break
- except asyncio.CancelledError:
+ except asyncio.CancelledError: # Session cancellation is normal shutdown.
return
finally:
svc.unsubscribe(session_id, queue)
diff --git a/jarvis/society/scheduler.py b/jarvis/society/scheduler.py
index e3141066ee..e47b30ff47 100644
--- a/jarvis/society/scheduler.py
+++ b/jarvis/society/scheduler.py
@@ -345,7 +345,7 @@ class SocietyScheduler:
assert isinstance(target, AgentRecord)
try:
await self._deliver(target, env)
- except DeliveryBusy:
+ except DeliveryBusy: # A busy destination keeps the delivery pending for retry.
return False
except Exception as exc: # noqa: BLE001 — persist the failure and report it
await self._store.mark_delivery(env.event_id, "failed", str(exc))
diff --git a/jarvis/speech/watchdog.py b/jarvis/speech/watchdog.py
index b3d5d2f0ce..0238707028 100644
--- a/jarvis/speech/watchdog.py
+++ b/jarvis/speech/watchdog.py
@@ -66,14 +66,14 @@ def _write_pid_file(path: Path) -> None:
try:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(str(os.getpid()), encoding="utf-8")
- except OSError:
+ except OSError: # The PID marker is advisory; startup still proceeds without it.
pass
def _read_pid_file(path: Path) -> int | None:
try:
return int(path.read_text(encoding="utf-8").strip())
- except (OSError, ValueError):
+ except (OSError, ValueError): # An unreadable marker has no trusted owner PID.
return None
@@ -89,7 +89,7 @@ def _pid_is_live_watchdog(pid: int) -> bool:
return False
try:
import psutil # noqa: PLC0415 - optional at type-check time, required at runtime
- except ImportError:
+ except ImportError: # Without the optional process probe, do not claim a PID is dead.
return True
try:
proc = psutil.Process(pid)
@@ -132,7 +132,7 @@ def _clear_pid_file(path: Path) -> None:
if _read_pid_file(path) != os.getpid():
return
path.unlink()
- except OSError:
+ except OSError: # Best-effort marker cleanup must not mask shutdown.
pass
@@ -141,7 +141,7 @@ async def _main() -> None:
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
sys.stderr.reconfigure(encoding="utf-8", errors="replace") # type: ignore[union-attr]
- except (AttributeError, OSError):
+ except (AttributeError, OSError): # stderr may not support reconfiguration.
pass
project_root = Path(__file__).resolve().parents[2]
diff --git a/jarvis/tasks/external_auth.py b/jarvis/tasks/external_auth.py
index 5a517d817c..7c626f74d9 100644
--- a/jarvis/tasks/external_auth.py
+++ b/jarvis/tasks/external_auth.py
@@ -44,7 +44,7 @@ def verify_google_token(token: str, audience: str, service_account: str) -> bool
try:
claims = verify_oauth2_token(token, _google_request, audience=audience)
return claims.get("email") == service_account and claims.get("email_verified") is True
- except (ValueError, TypeError):
+ except (ValueError, TypeError): # Malformed claims fail authentication closed.
return False
@@ -89,7 +89,7 @@ def verify_provider(
signatures = [value for name, _, value in parts if name == "v1"]
else:
return False
- except (ValueError, TypeError, AttributeError):
+ except (ValueError, TypeError, AttributeError): # Invalid signatures fail closed.
return False
expected = hmac.new(key.encode("utf-8"), signed, hashlib.sha256).hexdigest()
return any(
diff --git a/jarvis/tasks/scheduler.py b/jarvis/tasks/scheduler.py
index 2272f8e33c..9fac6d9a6f 100644
--- a/jarvis/tasks/scheduler.py
+++ b/jarvis/tasks/scheduler.py
@@ -276,7 +276,7 @@ class TaskScheduler:
status = await self.receive_hook(
task_id, payload, str(event.trace_id), source="source", lineage=path
)
- except ValueError:
+ except ValueError: # The source is marked blocked with payload_invalid below.
status = "payload_invalid"
if status not in {"queued", "duplicate", "filtered"}:
await self._store.sources.status(task_id, "blocked", status)
@@ -384,7 +384,7 @@ class TaskScheduler:
and current["state"] == "scheduled"
):
await self._store.update_state(tid, "completed")
- except RoutineDeferred:
+ except RoutineDeferred: # Keep the hook pending and retry after a short delay.
await self._store.hooks.mark(tid, delivery, "pending")
self._hook_retry_at[tid] = time.monotonic() + 2
except asyncio.CancelledError:
@@ -805,7 +805,7 @@ class TaskScheduler:
if trig.type == "at_time":
try:
return parse_iso_timestamp_to_ns(trig.iso_timestamp)
- except ValueError:
+ except ValueError: # Invalid ISO times have no schedulable due date.
return None
if trig.type == "cron":
return next_every_due_ns(spec, time.time_ns())
@@ -815,7 +815,7 @@ class TaskScheduler:
if trig.start_at:
try:
return parse_iso_timestamp_to_ns(trig.start_at)
- except ValueError:
+ except ValueError: # Invalid start times have no schedulable due date.
return None
return time.time_ns() + int(trig.interval_seconds * 1e9)
return None
@@ -858,7 +858,7 @@ class TaskScheduler:
await self._wakeup.wait()
else:
await asyncio.wait_for(self._wakeup.wait(), timeout=timeout)
- except TimeoutError:
+ except TimeoutError: # The periodic wake interval elapsed without a signal.
pass
self._wakeup.clear()
@@ -990,7 +990,7 @@ def next_every_due_ns(spec: TaskSpec, now_ns: int) -> int:
if start_at:
try:
anchor = parse_iso_timestamp_to_ns(start_at)
- except ValueError:
+ except ValueError: # An invalid anchor falls back to the current interval.
anchor = None
if anchor is not None:
if anchor > now_ns:
@@ -1067,7 +1067,7 @@ def _match_filter(event: Event, filter_expr: str | None) -> bool:
try:
tree = ast.parse(filter_expr, mode="eval")
- except SyntaxError:
+ except SyntaxError: # Malformed filters are rejected before evaluation.
return False
for node in ast.walk(tree):
diff --git a/jarvis/tasks/source_catalog.py b/jarvis/tasks/source_catalog.py
index a8b0f655ea..b467644c6a 100644
--- a/jarvis/tasks/source_catalog.py
+++ b/jarvis/tasks/source_catalog.py
@@ -37,7 +37,7 @@ def available(kind: str) -> bool:
return True
try:
return find_spec(module) is not None
- except (ModuleNotFoundError, ValueError):
+ except (ModuleNotFoundError, ValueError): # An unavailable optional driver is not installed.
return False
diff --git a/jarvis/tasks/source_drivers.py b/jarvis/tasks/source_drivers.py
index 17e30695ee..c9b70401ee 100644
--- a/jarvis/tasks/source_drivers.py
+++ b/jarvis/tasks/source_drivers.py
@@ -40,12 +40,12 @@ def decode(value: bytes | str) -> Any:
raise ValueError("Source payload exceeds 32 KiB")
try:
text = value.decode("utf-8") if isinstance(value, bytes) else value
- except UnicodeDecodeError:
+ except UnicodeDecodeError: # Preserve non-UTF-8 payloads as base64 instead of dropping them.
assert isinstance(value, bytes)
return {"encoding": "base64", "value": base64.b64encode(value).decode("ascii")}
try:
return json.loads(text)
- except ValueError:
+ except ValueError: # Non-JSON payloads remain plain text.
return text
@@ -410,7 +410,7 @@ async def listen_mqtt(
raise ConnectionError("MQTT disconnected")
try:
message = await asyncio.wait_for(messages.get(), timeout=1)
- except TimeoutError:
+ except TimeoutError: # An empty MQTT poll keeps listening for the next message.
continue
if message is None:
raise ConnectionError("MQTT disconnected")
diff --git a/jarvis/ui/web/routine_hooks_routes.py b/jarvis/ui/web/routine_hooks_routes.py
index f5aacbc08e..4af06c4eb3 100644
--- a/jarvis/ui/web/routine_hooks_routes.py
+++ b/jarvis/ui/web/routine_hooks_routes.py
@@ -157,7 +157,7 @@ async def install_source_support(task_id: UUID, request: Request) -> dict[str, A
current = await scheduler._store.get_spec(str(task_id))
if current and current.trigger.type == "source":
scheduler.sources.start(current)
- except Exception as exc:
+ except Exception as exc: # Publish the failed install status for the UI to display.
request.app.state.source_install_status = {
"status": "error",
"detail": type(exc).__name__,
diff --git a/jarvis/ui/web/society_routes.py b/jarvis/ui/web/society_routes.py
index 6335862315..4f06e0c689 100644
--- a/jarvis/ui/web/society_routes.py
+++ b/jarvis/ui/web/society_routes.py
@@ -1263,7 +1263,7 @@ async def memory_file(request: Request, path: str = "") -> dict[str, Any]:
content = content[-200_000:]
try:
updated_ms = int(target.stat().st_mtime * 1000)
- except OSError:
+ except OSError: # Missing source metadata uses an unknown update timestamp.
updated_ms = 0
parts = Path(rel).parts
agent_id = parts[1] if len(parts) >= 3 else ""