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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(app): harden mission outcomes and desktop workflows
Ruben Lütkeb66f4fcb3365
diff --git a/desktop-ttu-latest.json b/desktop-ttu-latest.jsonindex 0b7cde1387..cfe9bba008 100644--- a/desktop-ttu-latest.json+++ b/desktop-ttu-latest.json@@ -1,33 +1,37 @@{"path": "desktop (_run_backend, GUI-free driver)","runs": 1,- "python": "C:\\Program Files\\Python311\\python.exe",- "vault_pages": 84,- "median_wall_ms": 633.8,- "median_boot_ready_ms": 104.2,- "median_bind_wall_ms": 591.4,- "median_voice_ready_wall_ms": 5142.4,+ "python": "/Users/joanaluetke/PersonalJarvis/.venv/bin/python3",+ "vault_pages": 83,+ "median_wall_ms": 742.7,+ "median_boot_ready_ms": 103.1,+ "median_bind_wall_ms": 705.2,+ "median_voice_ready_wall_ms": 14676.7,"voice_ready_wall_ms_runs": [- 5142.4+ 14676.7],- "median_voice_usable_wall_ms": 5577.5,+ "median_voice_usable_wall_ms": 15265.9,"voice_usable_wall_ms_runs": [- 5577.5+ 15265.9],- "median_app_interactive_wall_ms": 5653.1,+ "median_app_interactive_wall_ms": 15246.6,"app_interactive_wall_ms_runs": [- 5653.1+ 15246.6],"wall_ms_runs": [- 633.8+ 742.7],"boot_ready_ms_runs": [- 104.2+ 103.1],"phase_medians_ms": {- "db_app_interactive": 1802.3,- "db_pre_webserver": 773.3,- "db_webserver_ctor": 2590.4+ "db_app_interactive": 9310.3,+ "db_pre_webserver": 1286.4,+ "db_webserver_ctor": 4047.7,+ "flight_recorder": 0.4,+ "mission_stack": 36.9,+ "screenshot_retention": 0.9,+ "uvicorn_serve": 0.0},"anchor": "spawn -> /api/health responds 200 (= DesktopApp._wait_for_backend success = window creation point)","secondary_anchor": "median_bind_wall_ms = spawn -> BOOT_READY print (bootstrap bind; may precede a responsive health endpoint)",diff --git a/docs/BUGS.md b/docs/BUGS.mdindex 478a32895a..37675267b5 100644--- a/docs/BUGS.md+++ b/docs/BUGS.md@@ -6580,3 +6580,96 @@ through visible pixels, retain against a stable intended interaction footprint,and reconcile with the real cursor. Non-activating overlays must explicitlyprove both states in every visual mode: pointer outside means normal rendering;pointer on the bar means controls visible and usable.++---++## BUG-096: viable Jarvis-Agent deliverables are reported as generic errors (HIGH, FIXED 2026-07-19)++**Symptom (local macOS mission forensic, platform-neutral path).** The Outputs+view showed every recent Jarvis-Agent mission as an error or cancellation even+though four runs had produced complete HTML documents between 48 and 59 KB. A+fifth worker produced a 10 KB Markdown report that remained in its disposable+worktree but never appeared in Outputs. The active database contained four+`FAILED` missions, one `CANCELLED` mission, and no `MissionApproved` event, so+the frontend was faithfully displaying an upstream lifecycle decision rather+than merely recoloring a successful row.++**Root cause.** Several independent defects compounded:++1. Direct Codex critic output uses a flat strict schema. Its reconstruction+ instantiated `CriticVerdict` directly and bypassed the tolerant validation+ used by full verdicts. A valid decision whose English or localized voice+ summary exceeded 280 characters was discarded solely for+ `string_too_long`. Live logs show approval-shaped fallback output followed+ by an adversarial retry and eventual failure.+2. The critic was told to act as a code reviewer and find at least three bugs,+ regardless of the original goal. Static reports therefore accumulated new+ polish, browser-validation, citation, or accessibility demands on each+ round. Non-blocking suggestions became blocking revisions merely to satisfy+ the quota.+3. Codex and API workers appended every correction attempt to one+ `stream.jsonl`. The current critic round could re-grade stale errors and old+ final answers after the worker had corrected them.+4. A correction prevented by the task time guard fell through to+ `critic_loop_exhausted`, so one local mission claimed three failed attempts+ despite having only two critic verdicts.+5. Shutdown cancellation changed the header to `CANCELLED` without publishing+ the canonical `MissionCancelled` terminal event. Draft artifacts were+ archived only in the task-level `finally`, so a process restart between+ `WorkerDraftReady` and critic completion could leave the canonical output+ directory empty.+6. The Outputs response returned `error: null` and no terminal reason. It could+ not distinguish a content-free failure from unsigned but reviewable output.++**Fix.** Flat Codex decisions now carry grounded per-axis status/evidence and an+explicit blocking flag. The direct prompt describes that exact flat contract,+and reconstruction goes through the same narrowly tolerant validator as every+other provider. Only presentation summaries may be truncated; every+substantive schema error and every empty evidence axis still fails closed. The+critic judges the original mission goal, revises only for a cited blocking+defect, and may approve with low/medium non-blocking suggestions. The defect+quota is removed. Each worker spawn truncates its own stream before any+subprocess setup so a failed spawn cannot expose stale evidence.++Draft files are snapshotted into the persistent mission directory before the+draft event is published. The canonical `files/` snapshot is synchronized to+the latest iteration, so a deleted or renamed first draft cannot replace the+final deliverable; earlier content remains in the per-iteration patches. A+complete sibling snapshot is staged before a portable two-phase directory+promotion, so a copy failure leaves the previous durable output untouched.+Shutdown emits exactly one canonical cancellation event, and cancellation is+rendered separately from failure on the Jarvis-Agent board. A correction+stopped by the time guard records+`review_time_budget_exhausted`, while the mission header records the actual+zero-based critic iteration without rewriting lifecycle state. Execution+failures outrank review outcomes when a multi-task mission aggregates its final+reason. The typed Outputs response exposes terminal event, terminal reason,+artifact count, `has_partial_output`, and `needs_review`. Only exhausted,+unavailable, or time-limited review with retained deliverables becomes+**Needs review**. An explicit critic rejection, setup, worker, safety, or+execution-timeout failure remains visibly failed even when a partial file was+retained.++**Safety boundary.** File existence never equals approval. The forensic set+also contained a historical 286-byte placeholder and reports with real factual+or safety findings. Only a signed `MissionApproved` event is successful. A real+blocking issue remains failed; a retained deliverable without approval remains+reviewable partial output. Historical events are not rewritten.++**Guards.** Regression coverage pins overlong flat approvals, malformed-field+rejection, contradictory blocker/axis rejection, grounded blocking revisions,+all-pass non-blocking normalization, fresh per-spawn worker logs, pre-critic+draft durability, canonical shutdown+cancellation, atomic snapshot copy-failure recovery, rename/delete archive+synchronization, truthful time-budget and multi-task failure precedence,+race-safe mission-header iteration, typed+Python/TypeScript status parity, terminal-reason propagation, narrowed+Needs-review classification, and distinct cancellation rendering. The+lifecycle contains no OS-specific status branch, so the same correction applies+to Windows, macOS, Linux desktop, and headless Linux.++**Class rule.** Treat worker execution, artifact durability, critic approval,+and user-facing outcome as four separate facts. Never infer approval from a+file, never discard a valid decision because a presentation field is verbose,+never review stale attempt logs, and never collapse retained unsigned work into+an unexplained error.diff --git a/docs/adr/0009-self-healing-worker-critic.md b/docs/adr/0009-self-healing-worker-critic.mdindex 42be7049f0..f80538e8db 100644--- a/docs/adr/0009-self-healing-worker-critic.md+++ b/docs/adr/0009-self-healing-worker-critic.md@@ -4,14 +4,14 @@ slug: adr-0009-self-healing-worker-criticdiataxis: adrstatus: activeowner: sam-last_reviewed: 2026-04-29+last_reviewed: 2026-07-19phase: 6audience: developer---# ADR-0009 — Self-Healing Worker-Critic-Loop with Action/Observation Invariant-**Status:** Accepted (2026-04-26)+**Status:** Amended 2026-07-19**Phase:** 6 — Self-Healing Multi-Agent Orchestrator## Context@@ -128,3 +128,85 @@ Heuristic: a mission is Phase-6-eligible if the router classifier returns `code`- **Cross-model-critic trigger:** should the switch to Codex/GPT as the critic happen automatically when Worker = Claude and iteration == 3, or only via config? Gather observations during Phase 6, amend if needed.- **Worktree-cleanup policy on MissionFailed:** immediate `git worktree remove --force` or keep for N days for forensics? Proposal: keep + automatic prune after 7 days.- **Voice readback at iteration 2:** should the user hear "I'm trying again" after the critic verdict `revise`, or loop silently until approval? Default silent, opt-in via `[voice].announce_critic_loop = true`.++## Amendment 2026-07-19 — goal-based review and truthful partial outcomes++### Context++Local mission forensics found a repeated false-negative pattern in otherwise+substantial HTML and Markdown deliverables. The direct Codex critic returned a+structured decision, but its flat-schema reconstruction bypassed the tolerant+validator used by every full verdict. A `summary` or `summary_de` longer than+the 280-character voice-readback cap therefore invalidated the entire decision.+Some fallback critics subsequently returned approval-shaped JSON, but the lost+primary decision and an adversarial retry could still end the mission as+`critic_loop_exhausted`.++The prompt amplified that parser defect. It required an adversarial *code*+critic to find at least three bugs even when the original goal was a report or+standalone HTML document. Optional polish, unavailable browser automation, and+new requirements invented during review were consequently treated like+blocking failures. Correction iterations also reused an accumulating worker+log, so stale errors from an earlier attempt could be judged again after the+worker had fixed them. Finally, the Outputs read model collapsed every terminal+failure with an archived deliverable into a generic error without exposing the+terminal reason or the existence of reviewable partial work.++Artifact existence alone is not approval. The same forensic set contained an+old placeholder artifact and deliverables with real factual or safety defects.+The signed `MissionApproved` event remains the only success authority.++### Decision++- The critic judges the original mission goal and uses a blocking-defect+ threshold. `revise` means that cited evidence shows the requested outcome is+ missing, unusable, unsafe, materially incorrect, or violates an explicit+ requirement. Low- and medium-severity polish may be reported with an+ approval; it must not be promoted into a blocking defect to satisfy a quota.+ The critic remains skeptical, evidence-grounded, read-only, and subject to+ the action/observation invariant.+- Every provider path applies the same presentation-field tolerance. Overlong+ voice summaries are truncated to their declared cap only after all other+ schema fields validate. Missing axes, invalid enums, empty approval evidence,+ empty revision evidence, and malformed decisions still fail closed. A direct+ provider's prompt and enforced output schema must describe the same shape.+- Each worker correction attempt owns a fresh runtime log. Evidence from prior+ attempts remains available through bounded reflections and per-iteration+ artifacts, not by concatenating stale process streams into the current+ observation.+- A terminal read model distinguishes signed success, cancellation, genuine+ failure without a usable artifact, and a non-approved mission that still has+ reviewable output. Only exhausted, unavailable, or time-limited review can+ enter the last category; an explicit rejection, execution failure, or safety+ failure with a leftover file remains failed. A reviewable partial is never a+ green success, and its terminal reason remains visible.+- Draft deliverables are copied into a complete sibling tree before the latest+ `files/` snapshot is promoted. A copy or promotion error preserves and rolls+ back to the prior durable tree; no platform-specific rename primitive is+ required.+- `MAX_CRITIC_LOOPS = 3` remains fixed. This amendment changes decision quality+ and presentation, not the retry budget.++### Consequences++- A valid critic decision can no longer be discarded solely because its spoken+ summary is verbose.+- Reports and static documents are evaluated against their requested purpose,+ while evidence-backed factual, safety, security, and missing-deliverable+ defects continue to block approval.+- A correction is judged on the current attempt instead of stale worker errors.+- Users can recover a useful but unsigned artifact without being told that it+ is either fully successful or wholly absent.+- Existing historical events are not rewritten. Their audit trail remains+ intact; the read model may describe retained artifacts more precisely.++### Alternatives considered++- Treat any created file as success: rejected because a file can be empty,+ placeholder-only, unsafe, factually wrong, or unrelated to the request.+- Add more critic retries: rejected because it preserves the biased decision+ rule, increases cost, and violates the fixed-loop decision.+- Remove adversarial review: rejected because grounded review still catches+ real defects and protects the signed success contract.+- Rewrite historical mission events after reclassification: rejected because+ it would destroy the append-only forensic record.diff --git a/jarvis/agents/registry.py b/jarvis/agents/registry.pyindex 72134bff71..77818ab2b4 100644--- a/jarvis/agents/registry.py+++ b/jarvis/agents/registry.py@@ -8,7 +8,7 @@ Design decisions (see Plan §3):- **Client-side tree building** is possible (all events reach the frontendvia WebSocket anyway), but the registry provides a snapshot endpoint forthe initial render (before WS events start flowing).-- **TTL 60s** for completed/failed nodes. An asyncio task sleeps, then+- **TTL 60s** for completed/failed/cancelled nodes. An asyncio task sleeps, thenremoves the node from the map and from ``parent.children_trace_ids``.- **Heuristic parent linking for HarnessDispatched**: the event has no``parent_trace_id`` field. We take the most recently started still-running@@ -52,7 +52,7 @@ from jarvis.missions.events import (log = logging.getLogger(__name__)NodeKind = Literal["router", "jarvis_agent", "harness", "tool_call"]-NodeStatus = Literal["running", "completed", "failed"]+NodeStatus = Literal["running", "completed", "failed", "cancelled"]def _tid(uuid_or_str: UUID | str | None) -> str | None:@@ -325,7 +325,7 @@ class JarvisAgentRegistry:task.add_done_callback(self._cleanup_tasks.discard)def _mark_running_children_terminal(- self, parent_tid: str, ts_ns: int, *, success: bool+ self, parent_tid: str, ts_ns: int, *, status: NodeStatus) -> None:"""When a mission terminates, sweep its still-`running` children.@@ -341,10 +341,12 @@ class JarvisAgentRegistry:child = self._nodes.get(child_tid)if child is None or child.status != "running":continue- child.status = "completed" if success else "failed"+ child.status = statuschild.completed_ns = ts_ns- if not success and not child.error:+ if status == "failed" and not child.error:child.error = "mission ended before worker exit"+ elif status == "cancelled" and not child.error:+ child.error = "cancelled with mission"async def _remove_after_ttl(self, tid: str) -> None:try:@@ -437,7 +439,11 @@ class JarvisAgentRegistry:node = self._nodes.get(worker_tid)if node is None:return- node.status = "failed"+ node.status = (+ "cancelled"+ if payload.reason in ("user", "parent_cancelled")+ else "failed"+ )node.completed_ns = ts_nsnode.error = payload.error_detail or f"killed: {payload.reason}"node.error_class = payload.error_class@@ -463,7 +469,7 @@ class JarvisAgentRegistry:node.tokens_out = payload.tokens_usedif payload.summary_de:node.prompts.append(f"[summary] {payload.summary_de}")- self._mark_running_children_terminal(tid, ts_ns, success=True)+ self._mark_running_children_terminal(tid, ts_ns, status="completed")self._schedule_removal(tid)return@@ -471,16 +477,18 @@ class JarvisAgentRegistry:node = self._nodes.get(tid)if node is None:return- node.status = "failed"node.completed_ns = ts_nsif isinstance(payload, MissionFailed):+ node.status = "failed"node.error = payload.error_detail or payload.reasonnode.error_class = payload.error_classelif isinstance(payload, MissionCancelled):+ node.status = "cancelled"node.error = f"cancelled: {payload.reason}"else:+ node.status = "failed"node.error = "timed out"- self._mark_running_children_terminal(tid, ts_ns, success=False)+ self._mark_running_children_terminal(tid, ts_ns, status=node.status)self._schedule_removal(tid)returndiff --git a/jarvis/missions/critic/prompts.py b/jarvis/missions/critic/prompts.pyindex 5086c0bee3..3f601f5273 100644--- a/jarvis/missions/critic/prompts.py+++ b/jarvis/missions/critic/prompts.py@@ -1,29 +1,70 @@"""Critic prompt templates for the Phase-6 Worker-Critic loop.-Source: Research-Doc §F (Critic prompt engineering) lines 247-301. Verbatim-adversarial framing, anchor token (`<<<{mission_prompt}>>>` triple-bracketed),-JSON output schema reminder in the prompt.--Design-reviewer criteria (see `.claude/agents/jarvis-critic-design-reviewer.md`):-- Criterion 2 (Adversarial Framing): "skeptical of this implementation",- "find at least three concrete bugs", "explain why each plausible failure- mode does NOT apply" — all three phrases verbatim in the template.-- Criterion 3 (Anchor Token): `mission_prompt` is NOT paraphrased,- NOT summarised; re-injected verbatim inside <<<>>> brackets every iteration.+The critic stays skeptical and evidence-grounded, but judges the requested+deliverable instead of assuming every mission is source code. The original+mission is re-injected verbatim inside ``<<<>>>`` on every iteration."""from __future__ import annotationsfrom typing import Final-# Verbatim from Research-Doc §F lines 247-301. NO rewording — the phrasing-# is calibrated for sycophancy mitigation (Kim & Kim 2025: casual rebuttal-# increases sycophancy; formal phrasing reduces it).+FULL_CRITIC_OUTPUT_CONTRACT: Final[str] = """\+OUTPUT SCHEMA (Pydantic CriticVerdict):+{+ "verdict": "approve" | "revise" | "reject",+ "axes": {+ "correctness": { "status": "pass"|"fail", "evidence": ["file:line", ...] },+ "completeness": { "status": "pass"|"fail", "evidence": [...] },+ "side_effects": { "status": "pass"|"fail", "evidence": [...] },+ "security": { "status": "pass"|"fail", "evidence": [...] }+ },+ "issues": [+ { "severity": "low"|"med"|"high"|"critical",+ "category": "correctness"|"completeness"|"side_effects"|"security",+ "description": "...",+ "evidence_ref": "src/foo.py:42 OR log_line:128 OR test:test_x",+ "fix": "concrete instruction to the worker" }+ ],+ "correction_instruction": "single-paragraph instruction the worker reads on retry",+ "summary": "<= 2 sentences for voice readback (English)",+ "summary_de": "<= 2 sentences for voice readback (German)",+ "confidence": 0.0..1.0,+ "suggested_next_action": "retry"|"accept"|"escalate_to_user"|"abort"+}"""++CODEX_FLAT_OUTPUT_CONTRACT: Final[str] = """\+OUTPUT SCHEMA (flat Codex critic; every field is required):+{+ "verdict": "approve" | "revise" | "reject",+ "confidence": 0.0..1.0,+ "summary": "<= 2 sentences for voice readback (English)",+ "summary_de": "<= 2 sentences for voice readback (German)",+ "correction_instruction": "empty on approval; concrete blocker fix otherwise",+ "blocking_issue": true | false,+ "correctness_status": "pass" | "fail",+ "correctness_evidence": "one concise, non-empty evidence reference",+ "completeness_status": "pass" | "fail",+ "completeness_evidence": "one concise, non-empty evidence reference",+ "side_effects_status": "pass" | "fail",+ "side_effects_evidence": "one concise, non-empty evidence reference",+ "security_status": "pass" | "fail",+ "security_evidence": "one concise, non-empty evidence reference"+}+Set blocking_issue=true exactly when a cited blocking defect remains. The+runtime derives the nested axes and next action from these flat fields. Do not+emit nested axes, issues, or suggested_next_action in this format."""++# Amended by ADR-0009 (2026-07-19): adversarial review remains mandatory, but+# a defect quota is forbidden. The old "find at least three" instruction made+# a report or static HTML page fail until the critic invented three more polish+# requests. Only evidence-backed blockers may force another worker iteration.CRITIC_SYSTEM_PROMPT: Final[str] = """\-You are an adversarial code critic for the Personal Jarvis worker-critic loop.-You are a senior engineer who is skeptical of this implementation. Your job-is to find at least three concrete bugs, edge cases, or security issues. If-you cannot find any, explain why each plausible failure mode does NOT apply,-citing specific code lines.+You are an adversarial mission-output critic for the Personal Jarvis+worker-critic loop. You are a senior reviewer who is skeptical of this+deliverable. Search rigorously for concrete correctness, completeness,+side-effect, and security defects. Never invent findings or expand the user's+scope to satisfy a defect quota. If no blocking defect remains, approve the+deliverable and briefly explain why the plausible failure modes do not apply.ORIGINAL MISSION GOAL (user's original request, anchor your judgment here):<<<{mission_prompt}>>>@@ -40,47 +81,31 @@ PRIOR REFLECTIONS (last 3 critique cycles, if any):CURRENT ITERATION: {iteration} (max 3 — failure here ends the mission)TASK: Evaluate the worker output across four axes. For each axis, output PASS-or FAIL with cited evidence (file:line, log_line:N, or test:name). If you-cannot find any issue on an axis, briefly justify why each plausible failure-mode does NOT apply — your justifications also count as evidence and MUST be-non-empty. Cite at most THREE concise ``file:line — brief note`` items per-axis (twelve words max each); never paste file contents or long excerpts.-Keep the whole verdict SHORT — an over-long response can be cut off by the-output limit and then cannot be parsed, which wrongly fails the mission.-Output ONLY the JSON object matching the schema — no prose, no-markdown, no code fences.+or FAIL with cited evidence (file:line, log_line:N, or test:name). FAIL means+you found a BLOCKING defect: the requested outcome is missing, unusable,+unsafe, materially incorrect, or violates an explicit requirement. Optional+polish, speculative hardening, unavailable optional browser automation, and+requirements not present in the original mission are NON-BLOCKING. Keep the+relevant axis PASS and mention such suggestions briefly if useful. If you cannot+find a blocking issue on an axis, briefly justify why plausible failure modes+do not apply; the justification is evidence and MUST be non-empty. Cite at+most THREE concise ``file:line — brief note`` items per axis (twelve words max+each); never paste file contents or long excerpts. Keep the whole verdict+SHORT. Output ONLY the JSON object matching the schema — no prose, no markdown,+no code fences.AXES:- correctness: does the diff achieve the original goal?-- completeness: are edge cases, error paths, and tests covered?+- completeness: are the original goal and its explicit edge cases covered?- side_effects: were unrelated tests or files broken? Any unexpected mutations?- security: any unsafe operations (eval, shell injection, secrets, network)?-OUTPUT SCHEMA (Pydantic CriticVerdict):-{{- "verdict": "approve" | "revise" | "reject",- "axes": {{- "correctness": {{ "status": "pass"|"fail", "evidence": ["file:line", ...] }},- "completeness": {{ "status": "pass"|"fail", "evidence": [...] }},- "side_effects": {{ "status": "pass"|"fail", "evidence": [...] }},- "security": {{ "status": "pass"|"fail", "evidence": [...] }}- }},- "issues": [- {{ "severity": "low"|"med"|"high"|"critical",- "category": "correctness"|"completeness"|"side_effects"|"security",- "description": "...",- "evidence_ref": "src/foo.py:42 OR log_line:128 OR test:test_x",- "fix": "concrete instruction to the worker" }}- ],- "correction_instruction": "single-paragraph instruction the worker reads on retry",- "summary": "<= 2 sentences for voice readback (English)",- "summary_de": "<= 2 sentences for voice readback (German)",- "confidence": 0.0..1.0,- "suggested_next_action": "retry"|"accept"|"escalate_to_user"|"abort"-}}+{output_contract}Rules:-- verdict=approve only if every axis is pass AND every axis has non-empty evidence.+- verdict=approve when the original goal is satisfied, every axis is pass, and+ every axis has non-empty evidence. Low/med non-blocking suggestions may remain.+- verdict=revise only when at least one axis has a cited blocking defect.- verdict=reject only if you have evidence the task is impossible or outside scope.- Empty-evidence FAILs are treated as abstentions and rejected by the orchestrator.- Empty-evidence PASSes are also rejected — justify your judgement.@@ -200,10 +225,10 @@ believed the log and approved with confidence=0.9):ADVERSARIAL_REFRAME_PREFIX: Final[str] = """\PREVIOUS RESPONSE WAS REJECTED BECAUSE: it returned an approval withoutspecific evidence references, or its output could not be parsed as one valid-JSON object — often because it was too long and got cut off. This is the-hallmark of a sycophantic critic (or a runaway one). Re-evaluate from scratch with-maximum skepticism. Your default position is now FAIL — only approve if every-axis has concrete evidence. Cite at most THREE concise ``file:line`` items per+JSON object — often because it was too long and got cut off. Re-evaluate from+scratch with maximum skepticism, but do not invent a blocker or broaden the+original goal. Approve only when every axis has concrete evidence; revise only+for a cited blocking defect. Cite at most THREE concise ``file:line`` items peraxis; do NOT paste file contents or write prose. Output ONLY the JSON object,nothing before or after it — keeping it short is what lets it be parsed.@@ -218,6 +243,7 @@ def render_critic_prompt(prior_reflections: str,iteration: int,adversarial_reframe: bool = False,+ codex_flat: bool = False,) -> str:"""Render the Critic prompt with anchor token and adversarial framing.@@ -230,6 +256,7 @@ def render_critic_prompt(iteration: Current iteration (0..MAX_CRITIC_LOOPS-1).adversarial_reframe: When True, prepend ADVERSARIAL_REFRAME_PREFIX(retry path after empty-evidence approval / JSONError).+ codex_flat: Render the strict flat schema accepted by ``codex exec``."""base = CRITIC_SYSTEM_PROMPT.format(mission_prompt=mission_prompt,@@ -237,6 +264,9 @@ def render_critic_prompt(log_summary=log_summary,prior_reflections=prior_reflections,iteration=iteration,+ output_contract=(+ CODEX_FLAT_OUTPUT_CONTRACT if codex_flat else FULL_CRITIC_OUTPUT_CONTRACT+ ),)if adversarial_reframe:return ADVERSARIAL_REFRAME_PREFIX + base@@ -245,6 +275,8 @@ def render_critic_prompt(__all__ = ["ADVERSARIAL_REFRAME_PREFIX",+ "CODEX_FLAT_OUTPUT_CONTRACT","CRITIC_SYSTEM_PROMPT",+ "FULL_CRITIC_OUTPUT_CONTRACT","render_critic_prompt",]diff --git a/jarvis/missions/critic/runner.py b/jarvis/missions/critic/runner.pyindex d8f54a2ae7..72cddd0f71 100644--- a/jarvis/missions/critic/runner.py+++ b/jarvis/missions/critic/runner.py@@ -662,10 +662,23 @@ _CODEX_CRITIC_OUTPUT_SCHEMA: Final[dict] = {"summary": {"type": "string"},"summary_de": {"type": "string"},"correction_instruction": {"type": "string"},+ "blocking_issue": {"type": "boolean"},+ "correctness_status": {"type": "string", "enum": ["pass", "fail"]},+ "correctness_evidence": {"type": "string"},+ "completeness_status": {"type": "string", "enum": ["pass", "fail"]},+ "completeness_evidence": {"type": "string"},+ "side_effects_status": {"type": "string", "enum": ["pass", "fail"]},+ "side_effects_evidence": {"type": "string"},+ "security_status": {"type": "string", "enum": ["pass", "fail"]},+ "security_evidence": {"type": "string"},},"required": ["verdict", "confidence", "summary", "summary_de",- "correction_instruction",+ "correction_instruction", "blocking_issue",+ "correctness_status", "correctness_evidence",+ "completeness_status", "completeness_evidence",+ "side_effects_status", "side_effects_evidence",+ "security_status", "security_evidence",],}@@ -673,35 +686,100 @@ _CODEX_CRITIC_OUTPUT_SCHEMA: Final[dict] = {def _verdict_from_codex_flat(flat: dict) -> CriticVerdict:"""Reconstruct a full CriticVerdict from codex's flat structured output.- codex only returns the 5 decision fields (forced by --output-schema).- The four required axes are synthesised: all ``pass`` when the verdict is- approve, all ``fail`` otherwise -- consistent with the aggregate-axis- downgrade logic the Jarvis-Agent path already relies on. The- suggested_next_action is derived from the verdict so the mission state- machine has a concrete next step.+ New structured outputs carry one status and one concise evidence reference+ per axis plus an explicit blocking flag. Older five-field payloads remain+ readable for compatibility, using the historical synthetic-axis fallback.++ The semantic fields are authoritative when a model contradicts its own+ verdict label: all-pass evidence with no blocker is an approval, while a+ claimed approval with a blocker or failed axis is a revision. This keeps the+ original-goal threshold deterministic without treating file existence as+ success. The reconstructed full verdict goes through the shared tolerant+ validator, so a voice-summary length cap cannot discard a valid decision."""verdict = str(flat.get("verdict", "revise"))- axis_status = "pass" if verdict == "approve" else "fail"- evidence = (- ["codex structured-output verdict"]- if verdict == "approve" else []- )- axes = {- ax: CriticAxis(status=axis_status, evidence=list(evidence))- for ax in REQUIRED_AXES+ axis_field_names = {+ field_name+ for axis in REQUIRED_AXES+ for field_name in (f"{axis}_status", f"{axis}_evidence")}+ has_any_axis_field = bool(axis_field_names.intersection(flat))+ has_axis_fields = all(+ f"{axis}_status" in flat and f"{axis}_evidence" in flat+ for axis in REQUIRED_AXES+ )+ if (has_any_axis_field or "blocking_issue" in flat) and (+ not has_axis_fields or "blocking_issue" not in flat+ ):+ raise ValueError("Incomplete Codex flat verdict axis fields")+ if has_axis_fields:+ axes = {+ axis: CriticAxis(+ status=str(flat[f"{axis}_status"]), # type: ignore[arg-type]+ evidence=(+ [str(flat[f"{axis}_evidence"]).strip()]+ if str(flat[f"{axis}_evidence"]).strip()+ else []+ ),+ )+ for axis in REQUIRED_AXES+ }+ empty_evidence_axes = [+ axis for axis, axis_verdict in axes.items() if not axis_verdict.evidence+ ]+ if empty_evidence_axes:+ raise ValueError(+ "Codex flat verdict has empty evidence for axis/axes: "+ + ", ".join(sorted(empty_evidence_axes))+ )+ blocking_issue = bool(flat.get("blocking_issue", verdict != "approve"))+ all_axes_pass = all(axis.status == "pass" for axis in axes.values())+ has_failed_axis = not all_axes_pass+ if blocking_issue != has_failed_axis:+ raise ValueError(+ "Codex flat verdict contradicts its blocking flag and axis statuses"+ )+ if all_axes_pass:+ if verdict != "approve":+ logger.info(+ "CriticRunner: normalized flat verdict=%s to approve "+ "because every grounded axis passed and no blocker was reported",+ verdict,+ )+ verdict = "approve"+ elif verdict == "approve":+ verdict = "revise"+ else:+ axis_status = "pass" if verdict == "approve" else "fail"+ evidence = (+ ["codex structured-output verdict"]+ if verdict == "approve" else []+ )+ axes = {+ axis: CriticAxis(status=axis_status, evidence=list(evidence))+ for axis in REQUIRED_AXES+ }+next_action = {"approve": "accept", "revise": "retry", "reject": "escalate_to_user",}.get(verdict, "retry")- return CriticVerdict(- verdict=verdict, # type: ignore[arg-type]- axes=axes,- issues=[],- correction_instruction=str(flat.get("correction_instruction", "")),- summary=str(flat.get("summary", "")),- summary_de=str(flat.get("summary_de", "")),- confidence=float(flat.get("confidence", 0.5)),- suggested_next_action=next_action, # type: ignore[arg-type]+ payload = {+ "verdict": verdict,+ "axes": {axis: value.model_dump() for axis, value in axes.items()},+ "issues": [],+ "correction_instruction": str(flat.get("correction_instruction", "")),+ "summary": str(flat.get("summary", "")),+ "summary_de": str(flat.get("summary_de", "")),+ "confidence": flat.get("confidence", 0.5),+ "suggested_next_action": next_action,+ }+ return _validate_verdict_tolerant(json.dumps(payload))+++def _verdict_has_grounded_axes(verdict: CriticVerdict) -> bool:+ """Return whether every required axis carries at least one evidence item."""+ return REQUIRED_AXES.issubset(verdict.axes) and all(+ verdict.axes[axis].evidence for axis in REQUIRED_AXES)@@ -1040,7 +1118,7 @@ class CriticRunner:adversarial_reframe=False,)- # Aggregation check FIRST (deterministic, no LLM retry):+ # Aggregation check FIRST (deterministic):# If the Critic returns verdict=approve but any axis is fail,# we immediately downgrade to revise. The LLM gave us the information;# only the verdict label is inconsistent — no second LLM round needed.@@ -1052,7 +1130,7 @@ class CriticRunner:logger.warning("CriticRunner: verdict=approve with fail-axis -> deterministic downgrade to revise")- return verdict.model_copy(+ verdict = verdict.model_copy(update={"verdict": "revise","summary": (@@ -1063,15 +1141,17 @@ class CriticRunner:})- # JSONError OR empty-evidence approval -> one LLM retry with reframe.- # (Empty evidence + all axes pass = classic sycophancy; LLM gets one more try.)+ # JSON error or any ungrounded axis -> one LLM retry with reframe.+ # Unsupported revisions are as harmful as unsupported approvals: they+ # spend another worker round and can falsely exhaust the mission.retry_needed = (verdict is None- or (verdict.verdict == "approve" and not is_approval_valid(verdict))+ or not _verdict_has_grounded_axes(verdict))if retry_needed:logger.info(- "CriticRunner: empty-evidence approval or JSONError -> retry with adversarial reframe (iter=%d)",+ "CriticRunner: ungrounded verdict or JSON error -> retry with "+ "adversarial reframe (iter=%d)",iteration,)verdict = await self._invoke_once(@@ -1094,7 +1174,7 @@ class CriticRunner:and verdict.verdict == "approve"and aggregate_axes_status(verdict) != "pass"):- return verdict.model_copy(+ verdict = verdict.model_copy(update={"verdict": "revise","summary": (@@ -1109,12 +1189,16 @@ class CriticRunner:"Critic returned no schema-valid JSON output twice.")- # Empty-evidence approval even after retry -> raise (no silent pass).- if verdict.verdict == "approve" and not is_approval_valid(verdict):+ # Any ungrounded verdict after retry is an abstention, not a decision.+ if not _verdict_has_grounded_axes(verdict):raise CriticVerdictInconsistent(- "Critic approved with empty evidence even after adversarial reframe."+ "Critic returned missing or empty axis evidence after "+ "adversarial reframe.")+ if verdict.verdict == "approve" and not is_approval_valid(verdict):+ raise CriticVerdictInconsistent("Critic approval remained inconsistent.")+# --- Capability-Honesty Gate (Layer 3c, Capability Coupling spec) ---# Must run AFTER the sycophancy / schema checks above so we only# apply the gate to structurally valid verdicts. Gated behind@@ -1397,6 +1481,15 @@ class CriticRunner:iteration=iteration,adversarial_reframe=adversarial_reframe,)+ codex_prompt = render_critic_prompt(+ mission_prompt=mission_prompt,+ worker_diff=worker_diff,+ log_summary=log_summary,+ prior_reflections=prior_reflections,+ iteration=iteration,+ adversarial_reframe=adversarial_reframe,+ codex_flat=True,+ )# Append the JSON-only output contract once at the call site so both# the Jarvis-Agent worker and the direct paths see the same prompt. (The old@@ -1409,6 +1502,13 @@ class CriticRunner:"JSON schema. No prose, markdown, or code fences before or after "f"it.\n{schema_json}\n")+ codex_prompt_for_subprocess = (+ f"{codex_prompt}\n\n"+ "---\n"+ "Output contract: return exactly one flat JSON object matching "+ "this JSON schema. No prose, markdown, or code fences before or "+ f"after it.\n{json.dumps(_CODEX_CRITIC_OUTPUT_SCHEMA)}\n"+ )primary_provider, primary_model = _resolve_critic_provider_model()# Auth-viability gate (2026-07-07, mission 019f3d18 / BUG-042 defect 5):@@ -1469,7 +1569,7 @@ class CriticRunner:primary_model or model)codex_verdict = await self._invoke_via_codex_direct(- prompt=prompt_for_subprocess,+ prompt=codex_prompt_for_subprocess,worktree=worktree,env=env,model=effective_critic_model,@@ -1799,7 +1899,7 @@ class CriticRunner:req = BrainRequest(messages=(BrainMessage(role="user", content=prompt),),system=(- "You are a strict, adversarial code-review critic. Return "+ "You are a strict, adversarial mission-output critic. Return ""EXACTLY one JSON object matching the schema in the prompt — ""no prose and no markdown fences before or after it."),@@ -2010,10 +2110,9 @@ class CriticRunner:return None# Last agent_message wins. With --output-schema codex returns the- # FLAT decision object ({verdict, confidence, summary, summary_de,- # correction_instruction}); reconstruct the full CriticVerdict from- # it. Fall back to validating the raw text as a full CriticVerdict- # for backwards-compatibility (older runs / non-schema paths).+ # FLAT decision object (decision fields plus grounded per-axis fields);+ # reconstruct the full CriticVerdict from it. Fall back to validating+ # raw full-verdict text for older runs and non-schema paths.candidate = agent_texts[-1]cleaned = _strip_json_fences(candidate.strip())try:@@ -2160,19 +2259,21 @@ def _parse_verdict_from_text(Returns ``None`` when no valid verdict object is present."""cleaned = _strip_json_fences(stdout_text.strip())+ last_error: Exception | None = Nonetry:return _validate_verdict_tolerant(cleaned)- except (json.JSONDecodeError, ValueError, ValidationError):- pass+ except (json.JSONDecodeError, ValueError, ValidationError) as exc:+ last_error = excfor candidate in reversed(_iter_balanced_json_objects(stdout_text)):try:return _validate_verdict_tolerant(_strip_json_fences(candidate))- except (json.JSONDecodeError, ValueError, ValidationError):+ except (json.JSONDecodeError, ValueError, ValidationError) as exc:+ last_error = exccontinuelogger.warning("CriticRunner: JSON-parse failed (no valid verdict object) iter=%d adv=%s "- "output[:300]=%r",- iteration, adversarial_reframe, stdout_text[:300],+ "validation=%r output[:300]=%r",+ iteration, adversarial_reframe, str(last_error)[:600], stdout_text[:300],)return Nonediff --git a/jarvis/missions/event_store.py b/jarvis/missions/event_store.pyindex f1f718047a..ac9ba7566c 100644--- a/jarvis/missions/event_store.py+++ b/jarvis/missions/event_store.py@@ -43,7 +43,7 @@ class MissionEventStore:self._db_path.parent.mkdir(parents=True, exist_ok=True)conn = await aiosqlite.connect(self._db_path,- isolation_level=None, # autocommit — WAL ist Lock-Manager+ isolation_level=None, # autocommit — WAL is the lock manager)await conn.execute("PRAGMA journal_mode=WAL")await conn.execute("PRAGMA synchronous=NORMAL")@@ -92,10 +92,10 @@ class MissionEventStore:@propertydef conn(self) -> aiosqlite.Connection:if self._conn is None:- raise RuntimeError("MissionEventStore: open() vor Verwendung aufrufen")+ raise RuntimeError("MissionEventStore: call open() before use")return self._conn- # --- Append & Publish (atomar im WAL-Sinne) ---+ # --- Append & Publish (atomic in the WAL sense) ---async def append_and_publish(self, envelope: EventEnvelope) -> int:"""Persist event, then publish to bus. Returns the assigned seq.@@ -239,6 +239,29 @@ class MissionEventStore:return Nonereturn (str(row[0]), str(row[1]), str(row[2]), int(row[3]), float(row[4]))+ async def advance_mission_iteration(+ self,+ mission_id: str,+ *,+ iteration: int,+ ts_ms: int,+ ) -> None:+ """Advance the header iteration without changing its lifecycle state.++ Critic events and cancellation can race. Reusing ``upsert_mission`` for+ progress would write a previously read state back into the header and+ could therefore revert a concurrent terminal transition. This narrow+ update keeps iteration monotonic while leaving state authoritative.+ """+ await self.conn.execute(+ """+ UPDATE missions+ SET updated_ms = ?, iteration = MAX(iteration, ?)+ WHERE id = ?+ """,+ (ts_ms, iteration, mission_id),+ )+async def list_missions(self,*,diff --git a/jarvis/missions/isolation/env.py b/jarvis/missions/isolation/env.pyindex bd775b5945..226efee950 100644--- a/jarvis/missions/isolation/env.py+++ b/jarvis/missions/isolation/env.py@@ -19,6 +19,7 @@ from __future__ import annotationsimport jsonimport logging+import ntpathimport osimport shutilimport time@@ -55,24 +56,24 @@ def _repair_windows_worker_path("""root = environ.get("SystemRoot") or environ.get("windir") or r"C:\Windows"essentials: list[str] = [- os.path.join(root, "System32"),+ ntpath.join(root, "System32"),root,- os.path.join(root, "System32", "Wbem"),- os.path.join(root, "System32", "WindowsPowerShell", "v1.0"),+ ntpath.join(root, "System32", "Wbem"),+ ntpath.join(root, "System32", "WindowsPowerShell", "v1.0"),]if node_exe:- essentials.append(str(Path(node_exe).parent))+ essentials.append(ntpath.dirname(node_exe))appdata = environ.get("APPDATA")if appdata:# npm-global shims (codex.cmd / claude.cmd / gemini.cmd) live here.- essentials.append(os.path.join(appdata, "npm"))+ essentials.append(ntpath.join(appdata, "npm"))- existing = [p for p in path.split(os.pathsep) if p]+ existing = [p for p in path.split(";") if p]seen = {p.rstrip("\\/").lower() for p in existing}additions = [d for d in essentials if d.rstrip("\\/").lower() not in seen]if not additions:return path- return os.pathsep.join(existing + additions)+ return ";".join(existing + additions)# System variables that are ALWAYS forwarded from os.environ (when set).# - PATH: without it the worker cannot find binaries (git, claude, codex, python).diff --git a/jarvis/missions/kontrollierer/orchestrator.py b/jarvis/missions/kontrollierer/orchestrator.pyindex 8edd826b5b..54876a6206 100644--- a/jarvis/missions/kontrollierer/orchestrator.py+++ b/jarvis/missions/kontrollierer/orchestrator.py@@ -27,6 +27,7 @@ import loggingimport reimport shutilimport subprocess+import tempfileimport timefrom collections.abc import Callablefrom contextlib import suppress@@ -49,6 +50,7 @@ from ..events import (CriticVerdictReady,EventEnvelope,MissionApproved,+ MissionCancelled,MissionFailed,MissionPlanReady,WorkerCorrectionRequired,@@ -706,6 +708,7 @@ class TaskOutcome:EXHAUSTED = "exhausted"REJECTED = "rejected"BUDGET_EXCEEDED = "budget_exceeded"+ TIME_BUDGET_EXHAUSTED = "time_budget_exhausted"ERROR = "error"# Live forensic 2026-05-16 (mission_019e3288): iter0 produced a real# 1237-byte diff, but the Critic spawn returned non-zero rc twice in@@ -906,6 +909,7 @@ class Kontrollierer:task = self._running_missions.get(mission_id)if task is None or task.done():continue+ transitioned = Falsetry:await self._manager.transition_state(mission_id,@@ -913,6 +917,7 @@ class Kontrollierer:reason=reason,source_actor="kontrollierer",)+ transitioned = Trueexcept IllegalStateTransition:# Already terminal — still cancel the zombie task below.pass@@ -920,6 +925,24 @@ class Kontrollierer:logger.exception("cancel_all_running: state flip failed for %s", mission_id)+ if transitioned:+ try:+ await self._manager.store.append_and_publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=MissionCancelled(+ cascade=True,+ reason=reason,+ ),+ )+ )+ except Exception: # noqa: BLE001 — shutdown still kills the worker+ logger.exception(+ "cancel_all_running: terminal event failed for %s",+ mission_id,+ )task.cancel()tasks.append(task)finalized.append(mission_id)@@ -1051,27 +1074,13 @@ class Kontrollierer:# or critic-reject is more recoverable when the user can see the# work the worker actually produced.partial = self._collect_partial_artifacts(mission_id, plan)- # CRITIC_UNAVAILABLE has priority over EXHAUSTED: when the- # Critic spawn crashed before iter0's verdict could be rendered,- # subsequent iterations only saw the deterministic empty-diff- # fast-path and contributed nothing. Surfacing the real root- # cause to the voice layer is the whole point of this branch.+ # Execution/setup failures outrank review outcomes in a multi-task+ # mission. Otherwise one review time guard can mask a real worker crash+ # in another step and show the user the wrong terminal cause.if TaskOutcome.BUDGET_EXCEEDED in task_outcomes:await self._fail_mission(mission_id, "budget_exceeded", partial_artifacts=partial)- elif TaskOutcome.CRITIC_UNAVAILABLE in task_outcomes:- await self._fail_mission(- mission_id, "critic_unavailable", partial_artifacts=partial- )- elif TaskOutcome.REJECTED in task_outcomes:- await self._fail_mission(- mission_id, "critic_rejected", partial_artifacts=partial- )- elif TaskOutcome.EXHAUSTED in task_outcomes:- await self._fail_mission(- mission_id, "critic_loop_exhausted", partial_artifacts=partial- )elif TaskOutcome.SETUP_FAILED in task_outcomes:# Worktree-create failure (path cap / git index lock / missing git# binary / no .git repo) — surface an actionable cause instead of@@ -1092,14 +1101,37 @@ class Kontrollierer:# reason="timeout"; surface the same truth at the mission level so# the voice layer never speaks the "worker aborted" phrase for a run# that simply ran out of time.- # Ranked BELOW BUDGET/CRITIC_UNAVAILABLE/REJECTED/EXHAUSTED on- # purpose: in a multi-step mission, a reviewer-failed or budget-- # capped step is a more specific, more actionable diagnosis than a- # wall-clock cap on a different step. TIMED_OUT only wins over the- # generic task_error fallback.+ # A worker timeout outranks review outcomes in another step because+ # it is an execution failure and must remain visible. Budget remains+ # the only higher-priority aggregate terminal cause.await self._fail_mission(mission_id, "attempts_timed_out", partial_artifacts=partial)+ elif TaskOutcome.ERROR in task_outcomes:+ await self._fail_mission(+ mission_id, "task_error", partial_artifacts=partial+ )+ # CRITIC_UNAVAILABLE has priority over the other review outcomes: when+ # the critic crashed before iter0's verdict, later empty-diff rounds do+ # not turn that infrastructure failure into ordinary exhaustion.+ elif TaskOutcome.CRITIC_UNAVAILABLE in task_outcomes:+ await self._fail_mission(+ mission_id, "critic_unavailable", partial_artifacts=partial+ )+ elif TaskOutcome.REJECTED in task_outcomes:+ await self._fail_mission(+ mission_id, "critic_rejected", partial_artifacts=partial+ )+ elif TaskOutcome.TIME_BUDGET_EXHAUSTED in task_outcomes:+ await self._fail_mission(+ mission_id,+ "review_time_budget_exhausted",+ partial_artifacts=partial,+ )+ elif TaskOutcome.EXHAUSTED in task_outcomes:+ await self._fail_mission(+ mission_id, "critic_loop_exhausted", partial_artifacts=partial+ )else:await self._fail_mission(mission_id, "task_error", partial_artifacts=partial@@ -1266,9 +1298,10 @@ class Kontrollierer:# Time-budget guard (2026-06-10 mandate): a correction# iteration only starts when it can FINISH inside the task# budget (its worker slice + one critic call). Otherwise the- # loop ends here with the existing exhausted semantics — a- # late, rushed correction would overshoot the 20-minute- # target without improving the deliverable.+ # loop ends with an explicit time-budget outcome — a late,+ # rushed correction would overshoot the 20-minute target+ # without improving the deliverable. Do not claim that all+ # three critic attempts ran when this guard prevented one.elapsed_s = time.monotonic() - task_t0needed_s = _CORRECTION_WORKER_TIMEOUT_S + _CRITIC_TIME_RESERVE_Sif elapsed_s + needed_s > _TASK_TIME_BUDGET_S:@@ -1279,7 +1312,7 @@ class Kontrollierer:step.task_id, iteration, elapsed_s, needed_s,_TASK_TIME_BUDGET_S,)- break+ return TaskOutcome.TIME_BUDGET_EXHAUSTEDawait self._safe_transition(mission_id, MissionState.LOOPING, f"iter-{iteration}-revise")@@ -1565,7 +1598,30 @@ class Kontrollierer:# double-counting. Hard-abort on overrun is detected by the# pre-spawn assert_under_limit() check at the top of each# iteration of this loop.- draft_env = await self._publish_worker_draft(+ # Persist the current draft BEFORE announcing it. The final archive+ # in the worktree-cleanup block is still authoritative, but it never+ # runs after a hard process crash. A WorkerDraftReady event must not+ # point at a deliverable that exists only in a disposable worktree.+ try:+ snapshot = await asyncio.to_thread(+ self._archive_task_artifacts,+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=step.task_id,+ drain_iteration_diffs=False,+ )+ if snapshot is None:+ logger.warning(+ "draft artifact snapshot returned no archive for %s",+ worktree,+ )+ except Exception: # noqa: BLE001 — snapshot is best-effort+ logger.warning(+ "draft artifact snapshot failed for %s",+ worktree,+ exc_info=True,+ )+ await self._publish_worker_draft(mission_id=mission_id,worker_id=spawn_result.worker_id,diff=diff_text,@@ -2399,6 +2455,7 @@ class Kontrollierer:worktree: Path,mission_dir: Path,task_id: str,+ drain_iteration_diffs: bool = True,) -> Path | None:"""Persist the worker's outputs out of the worktree so they survivethe per-task cleanup.@@ -2417,32 +2474,34 @@ class Kontrollierer:Falls back to a fresh `git diff HEAD` of the worktree when noper-iter captures exist (rare: only when this helper is calledout-of-band from a test fixture).- - ``files/<rel>`` — verbatim copies of any *new* untracked files.- The diff records only their paths, not their content, so a- "create hello.txt"-style task would leave nothing recoverable- here without an explicit copy step.-- All git operations are best-effort with a 10s cap. Returns the- artifacts directory on success, ``None`` on irrecoverable failure- (the upstream finally still runs the worktree cleanup either way).+ - ``files/<rel>`` — a synchronized snapshot of the latest deliverable+ files. Earlier iteration content remains recoverable from the+ ``diff.iter<N>.patch`` history, but a deleted or renamed draft must+ never survive here as if it were the final output.++ ``drain_iteration_diffs=False`` creates a crash-safe draft snapshot+ while retaining the in-memory per-iteration history for later critic+ rounds. The final cleanup call uses the default ``True`` and releases+ that history. All git operations are best-effort with a 10s cap.+ Returns the artifacts directory on success, ``None`` on irrecoverable+ failure (the upstream finally still runs the worktree cleanup either+ way)."""try:artifacts = mission_dir / "tasks" / task_id[:13] / "artifacts"artifacts.mkdir(parents=True, exist_ok=True)- # Drain the per-iteration captures collected during the- # critic loop. The dict-pop guarantees a single mission can't- # accidentally double-archive the same task and that the- # per-mission map doesn't grow unbounded across the- # orchestrator's lifetime. `getattr` keeps test fixtures- # happy that instantiate via `object.__new__` and bypass- # the constructor — the helper still produces a valid- # archive in that case, just without per-iter snapshots.+ # Read or drain per-iteration captures. Draft-time snapshots retain+ # the list so later rounds and the final cleanup can still choose+ # the best diff; final archival pops it to prevent process-lifetime+ # growth. `getattr` keeps bare unit-test fixtures functional.iter_map = getattr(self, "_task_iter_diffs", None)if iter_map is None:per_iter: list[tuple[int, str]] = []- else:+ elif drain_iteration_diffs:per_iter = iter_map.pop(task_id, [])+ else:+ per_iter = list(iter_map.get(task_id, []))for it_idx, diff_text in per_iter:(artifacts / f"diff.iter{it_idx}.patch").write_text(diff_text or "", encoding="utf-8"@@ -2597,10 +2656,11 @@ class Kontrollierer:timeout=10.0,creationflags=NO_WINDOW_CREATIONFLAGS,)+ current_diff = _strip_managed_persona_hunks(r_diff.stdout or "")final_diff = (best_diffif best_diff is not None- else (r_diff.stdout or "")+ else current_diff)# best_diff is already stripped (it comes from _capture_diff); the# r_diff fallback is not — strip managed contract files either way@@ -2609,11 +2669,14 @@ class Kontrollierer:(artifacts / "diff.patch").write_text(final_diff, encoding="utf-8")- # Recover new-file paths the ``git ls-files --others`` call+ # Recover current new-file paths the ``git ls-files --others`` call# missed because earlier ``_capture_diff`` invocations had# already run ``git add -A`` (live 2026-05-27 regression# mission_019e6858-ab9a: SUCCESS but artifacts/files/ empty).- for _np in _extract_new_file_paths_from_diff(final_diff):+ # Use the fresh worktree diff, not the largest historical diff:+ # the latter may name a first draft that a later worker deleted or+ # renamed. Per-iteration patches preserve that history separately.+ for _np in _extract_new_file_paths_from_diff(current_diff):if _np not in untracked:untracked.append(_np)# Drop managed worker-contract files (AGENTS.md etc.) and@@ -2635,22 +2698,58 @@ class Kontrollierer:)if _generators:untracked = [r for r in untracked if r not in _generators]- if untracked:- files_root = artifacts / "files"+ files_root = artifacts / "files"+ # ``files`` is the canonical latest snapshot. Rebuild it on every+ # draft/final archive so deleted and renamed first drafts cannot be+ # mistaken for the current deliverable. Historical bytes remain in+ # the per-iteration patches written above. Build the entire new+ # tree beside the canonical one before promotion: a copy failure+ # must leave the last durable snapshot untouched.+ staged_root = Path(+ tempfile.mkdtemp(prefix=".files-next-", dir=str(artifacts))+ )+ previous_root = staged_root.with_name(+ staged_root.name.replace(".files-next-", ".files-previous-", 1)+ )+ try:for rel in untracked:src = worktree / relif not src.is_file():# Skip directories, broken symlinks etc. — only# regular files round-trip cleanly via copy2.continue- dst = files_root / rel+ dst = staged_root / reldst.parent.mkdir(parents=True, exist_ok=True)- try:- shutil.copy2(src, dst)- except OSError as exc:- logger.warning(- "artifact copy failed for %s: %s", src, exc- )+ shutil.copy2(src, dst)++ # Path.replace is a same-volume rename because both trees are+ # siblings. Keep the prior directory under a unique backup+ # name until the new tree is canonical; if promotion fails,+ # roll it back. This portable two-phase swap works on Windows,+ # macOS, and Linux without relying on platform-specific rename+ # exchange flags.+ moved_previous = False+ if files_root.exists():+ files_root.replace(previous_root)+ moved_previous = True+ try:+ staged_root.replace(files_root)+ except OSError:+ if (+ moved_previous+ and previous_root.exists()+ and not files_root.exists()+ ):+ previous_root.replace(files_root)+ raise+ if moved_previous:+ shutil.rmtree(previous_root, ignore_errors=True)+ finally:+ # No-op after successful promotion. On a copy/promotion error,+ # remove only the unpublished staging tree; never the prior+ # canonical snapshot (or its rollback copy).+ if staged_root.exists():+ shutil.rmtree(staged_root, ignore_errors=True)return artifactsexcept (subprocess.TimeoutExpired, OSError) as exc:logger.warning(@@ -2966,7 +3065,7 @@ class Kontrollierer:payload=WorkerDraftReady(worker_id=worker_id,artifact_uri=f"diff://{worker_id}",- diff=diff[:8000], # Cap zum Schutz vor Riesen-Diffs im Event-Store+ diff=diff[:8000], # Cap protects the event store from huge diffs.tokens_used=tokens_used,cost_usd=cost_usd,session_id=session_id,@@ -3001,6 +3100,19 @@ class Kontrollierer:),)await self._manager.store.append_and_publish(env)+ try:+ await self._manager.store.advance_mission_iteration(+ mission_id,+ iteration=iteration,+ ts_ms=now_ms(),+ )+ except Exception: # noqa: BLE001 — event remains authoritative+ logger.warning(+ "critic verdict header update failed for %s iter-%d",+ mission_id,+ iteration,+ exc_info=True,+ )async def _publish_correction(self,diff --git a/jarvis/missions/voice/readback.py b/jarvis/missions/voice/readback.pyindex d13ee0ffa9..de60f64c85 100644--- a/jarvis/missions/voice/readback.py+++ b/jarvis/missions/voice/readback.py@@ -186,6 +186,9 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {"critic_rejected": "Die Prüfung war nicht zufrieden.", # i18n-allow"task_error": "Der Worker ist abgebrochen.", # i18n-allow"attempts_timed_out": "Das Zeitlimit wurde überschritten.", # i18n-allow (DE TTS phrase)+ "review_time_budget_exhausted": ( # i18n-allow: German TTS phrase+ "Das Prüfzeitlimit ist erreicht; das Zwischenergebnis ist verfügbar." # i18n-allow+ ),"budget_exceeded": "Das Kostenlimit ist erreicht.", # i18n-allow"decompose_failed": "Die Aufgabe konnte ich nicht zerlegen.", # i18n-allow"crash_recovery": "Eine alte Mission wurde aufgeräumt.", # i18n-allow@@ -218,6 +221,9 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {"critic_rejected": "The review wasn't satisfied.","task_error": "The worker aborted.","attempts_timed_out": "The time limit was reached.",+ "review_time_budget_exhausted": (+ "The review time budget was reached; partial output is available."+ ),"budget_exceeded": "The cost limit was reached.","decompose_failed": "I could not break the task down.","crash_recovery": "An old mission was cleaned up.",@@ -246,6 +252,10 @@ FAILURE_REASON_PHRASES: Final[dict[str, dict[str, str]]] = {# rest of the table is de/en pending a broader translation pass; a missing# key here falls back via ``.get(language, {})``."es": {+ "review_time_budget_exhausted": ( # i18n-allow: Spanish TTS phrase+ "Se agotó el tiempo de revisión; el resultado parcial está " # i18n-allow+ "disponible." # i18n-allow+ ),"git_missing": "{agents} necesitan que git esté instalado y en el PATH.", # i18n-allow: Spanish TTS product-surface phrase"git_not_a_repository": ("{agents} necesitan una copia de git (instala con el " # i18n-allow: Spanish TTS product-surface phrasediff --git a/jarvis/missions/workers/api_agent_worker.py b/jarvis/missions/workers/api_agent_worker.pyindex cb616c35d9..cf22c6f897 100644--- a/jarvis/missions/workers/api_agent_worker.py+++ b/jarvis/missions/workers/api_agent_worker.py@@ -294,6 +294,11 @@ class ApiAgentWorker:resolved_model = _resolve_worker_model(self.provider, model)log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240 — trivial sync mkdir (mirrors sibling workers)stream_path = log_dir / "stream.jsonl"+ # The orchestrator reuses one log directory across critic iterations.+ # Keep stream evidence scoped to this spawn instead of appending a new+ # run to stale frames from an earlier worker attempt.+ with suppress(OSError):+ stream_path.write_text("", encoding="utf-8")written: list[str] = []broker_specs = broker_binding.tool_specs if broker_binding is not None else ()local_names = {str(spec["name"]) for spec in WORKER_TOOL_SPECS}diff --git a/jarvis/missions/workers/codex_direct_worker.py b/jarvis/missions/workers/codex_direct_worker.pyindex c6a71b3498..54fdf47324 100644--- a/jarvis/missions/workers/codex_direct_worker.py+++ b/jarvis/missions/workers/codex_direct_worker.py@@ -556,6 +556,11 @@ class CodexDirectWorker:log_dir.mkdir(parents=True, exist_ok=True) # noqa: ASYNC240stdout_log = log_dir / "stream.jsonl"stderr_log = log_dir / "stderr.log"+ # The orchestrator reuses one log directory across critic iterations.+ # Clear it before any subprocess setup so even a spawn failure cannot+ # leave stale evidence masquerading as the current worker attempt.+ with suppress(OSError):+ stdout_log.write_bytes(b"")session_id = resume_session_id or str(uuid.uuid4())self.last_session_id = session_iddiff --git a/jarvis/platform/clipboard.py b/jarvis/platform/clipboard.pynew file mode 100644index 0000000000..ac6d08bb13--- /dev/null+++ b/jarvis/platform/clipboard.py@@ -0,0 +1,166 @@+"""Cross-platform system clipboard writer for the local desktop shell.++The Web UI normally uses the browser Clipboard API. Embedded WebViews can deny+that API even after a visible button click (notably WKWebView after an awaited+request), so the desktop backend needs a native, capability-gated fallback.++Only text is supported here. Clipboard contents are passed through stdin or a+native memory buffer, never process arguments or logs. Missing display/tooling+returns ``False`` instead of raising, preserving headless operation.+"""+from __future__ import annotations++import ctypes+import logging+import shutil+import subprocess+import time+from collections.abc import Sequence++from jarvis.core.process_utils import NO_WINDOW_CREATIONFLAGS+from jarvis.platform import detect_platform+from jarvis.platform.capabilities import detect_capabilities++log = logging.getLogger(__name__)++_COMMAND_TIMEOUT_S = 5.0+_WINDOWS_CLIPBOARD_RETRIES = 10+_WINDOWS_CLIPBOARD_RETRY_S = 0.01+++def write_text(text: str) -> bool:+ """Replace the local desktop clipboard with *text*.++ Returns ``True`` only when the platform clipboard accepted the complete+ string. A headless host or unavailable OS integration returns ``False``.+ """+ if not detect_capabilities().display_present:+ log.info("clipboard: no display present; native copy is unavailable")+ return False++ platform = detect_platform()+ if platform == "win32":+ return _write_windows(text)+ if platform == "darwin":+ return _run_command(["/usr/bin/pbcopy"], text)+ return _write_linux(text)+++def _run_command(command: Sequence[str], text: str) -> bool:+ """Feed clipboard text to a fixed OS command through UTF-8 stdin."""+ try:+ completed = subprocess.run( # noqa: S603 - fixed, non-shell OS command+ list(command),+ input=text,+ capture_output=True,+ text=True,+ encoding="utf-8",+ errors="replace",+ timeout=_COMMAND_TIMEOUT_S,+ check=False,+ close_fds=True,+ creationflags=NO_WINDOW_CREATIONFLAGS,+ )+ except (OSError, subprocess.SubprocessError) as exc:+ log.warning("clipboard: native copy command unavailable (%s)", exc)+ return False+ if completed.returncode != 0:+ detail = (completed.stderr or "").strip()+ log.warning(+ "clipboard: native copy command failed with exit %d%s",+ completed.returncode,+ f" ({detail[:300]})" if detail else "",+ )+ return False+ return True+++def _write_linux(text: str) -> bool:+ """Use the available Wayland/X11 clipboard command, if any."""+ candidates = (+ ("wl-copy", ["wl-copy", "--type", "text/plain;charset=utf-8"]),+ ("xclip", ["xclip", "-selection", "clipboard", "-in"]),+ ("xsel", ["xsel", "--clipboard", "--input"]),+ )+ for executable, command in candidates:+ resolved = shutil.which(executable)+ if resolved:+ command[0] = resolved+ return _run_command(command, text)+ log.info("clipboard: no wl-copy, xclip, or xsel command is available")+ return False+++def _write_windows(text: str) -> bool:+ """Write Unicode text with the Win32 clipboard API.++ ``SetClipboardData`` takes ownership of the movable allocation after a+ successful call; every failure path frees it locally. Brief retries handle+ another application momentarily holding the clipboard open.+ """+ try:+ from ctypes import wintypes++ user32 = ctypes.WinDLL("user32", use_last_error=True)+ kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)++ user32.OpenClipboard.argtypes = [wintypes.HWND]+ user32.OpenClipboard.restype = wintypes.BOOL+ user32.EmptyClipboard.argtypes = []+ user32.EmptyClipboard.restype = wintypes.BOOL+ user32.SetClipboardData.argtypes = [wintypes.UINT, wintypes.HANDLE]+ user32.SetClipboardData.restype = wintypes.HANDLE+ user32.CloseClipboard.argtypes = []+ user32.CloseClipboard.restype = wintypes.BOOL+ kernel32.GlobalAlloc.argtypes = [wintypes.UINT, ctypes.c_size_t]+ kernel32.GlobalAlloc.restype = wintypes.HGLOBAL+ kernel32.GlobalLock.argtypes = [wintypes.HGLOBAL]+ kernel32.GlobalLock.restype = ctypes.c_void_p+ kernel32.GlobalUnlock.argtypes = [wintypes.HGLOBAL]+ kernel32.GlobalUnlock.restype = wintypes.BOOL+ kernel32.GlobalFree.argtypes = [wintypes.HGLOBAL]+ kernel32.GlobalFree.restype = wintypes.HGLOBAL+ except (AttributeError, OSError) as exc:+ log.warning("clipboard: Win32 API unavailable (%s)", exc)+ return False++ opened = False+ for _attempt in range(_WINDOWS_CLIPBOARD_RETRIES):+ if user32.OpenClipboard(None):+ opened = True+ break+ time.sleep(_WINDOWS_CLIPBOARD_RETRY_S)+ if not opened:+ log.warning("clipboard: Win32 clipboard remained busy")+ return False++ handle = None+ try:+ if not user32.EmptyClipboard():+ return False+ buffer = ctypes.create_unicode_buffer(text)+ size = ctypes.sizeof(buffer)+ handle = kernel32.GlobalAlloc(0x0002, size) # GMEM_MOVEABLE+ if not handle:+ return False+ target = kernel32.GlobalLock(handle)+ if not target:+ return False+ try:+ ctypes.memmove(target, ctypes.addressof(buffer), size)+ finally:+ kernel32.GlobalUnlock(handle)+ if not user32.SetClipboardData(13, handle): # CF_UNICODETEXT+ return False+ handle = None # ownership transferred to the operating system+ return True+ except (AttributeError, OSError, ValueError) as exc:+ log.warning("clipboard: Win32 clipboard write failed (%s)", exc)+ return False+ finally:+ if handle:+ kernel32.GlobalFree(handle)+ user32.CloseClipboard()+++__all__ = ["write_text"]diff --git a/jarvis/ui/web/clipboard_routes.py b/jarvis/ui/web/clipboard_routes.pynew file mode 100644index 0000000000..46581b1b47--- /dev/null+++ b/jarvis/ui/web/clipboard_routes.py@@ -0,0 +1,43 @@+"""Desktop-only REST fallback for writing text to the system clipboard."""+from __future__ import annotations++from fastapi import APIRouter, HTTPException, Request+from pydantic import BaseModel, Field++from jarvis.platform.clipboard import write_text++router = APIRouter(prefix="/api/clipboard", tags=["clipboard"])++_MAX_TEXT_CHARS = 5 * 1024 * 1024+++class ClipboardTextRequest(BaseModel):+ """Text to place on the local desktop clipboard."""++ text: str = Field(max_length=_MAX_TEXT_CHARS)+++class ClipboardTextResponse(BaseModel):+ """Native clipboard write result."""++ copied: bool+++ "/text",+ response_model=ClipboardTextResponse,+ summary="Copy text to the local desktop clipboard",+ openapi_extra={"x-jarvis-dangerous": True},+)+def copy_text_to_system_clipboard(+ request: Request,+ body: ClipboardTextRequest,+) -> ClipboardTextResponse:+ """Write text only when this backend owns a local desktop shell."""+ if not bool(getattr(request.app.state, "native_file_actions", False)):+ raise HTTPException(status_code=404, detail="native-clipboard-disabled")+ if not write_text(body.text):+ raise HTTPException(status_code=503, detail="native-clipboard-unavailable")+ return ClipboardTextResponse(copied=True)++__all__ = ["router"]diff --git a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsxindex b7b419f80a..db372a1820 100644--- a/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx+++ b/jarvis/ui/web/frontend/src/components/docs/CodeBlock.tsx@@ -1,6 +1,7 @@import { useEffect, useRef, useState } from "react";import { Check, Copy } from "lucide-react";+import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -105,7 +106,8 @@ export function CodeBlock({ language, code }: CodeBlockProps) {}, [language, code]);const handleCopy = () => {- void navigator.clipboard.writeText(code).then(() => {+ void robustCopy(code).then((copied) => {+ if (!copied) return;setCopied(true);window.setTimeout(() => {if (mountedRef.current) setCopied(false);diff --git a/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx b/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsxindex 6c4a4f4e9f..c831707fbe 100644--- a/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/JarvisAgentPanel.tsx@@ -14,6 +14,7 @@ import { useShallow } from "zustand/react/shallow";import { ScrollArea } from "@/components/ui/scroll-area";import { useT } from "@/i18n";+import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import type { JarvisAgentReattachStatus, JarvisAgentWorkerSnapshot } from "@/types/missions";@@ -46,12 +47,7 @@ function formatTokens(value: number): string {}async function copyToClipboard(value: string): Promise<void> {- try {- await navigator.clipboard.writeText(value);- } catch {- // Best-effort. If the browser API isn't available (e.g. an insecure- // context), the user will just see nothing happen — we log it silently.- }+ await robustCopy(value);}export function JarvisAgentPanel() {diff --git a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts b/jarvis/ui/web/frontend/src/hooks/useOutputs.tsindex 54e8e641eb..299b24850d 100644--- a/jarvis/ui/web/frontend/src/hooks/useOutputs.ts+++ b/jarvis/ui/web/frontend/src/hooks/useOutputs.ts@@ -39,10 +39,20 @@ export interface PlanResponse {steps: PlanStep[];}+/** Must stay in parity with `OUTPUT_STATUSES` in `outputs_routes.py`. */+export const OUTPUT_STATUSES = [+ "running",+ "success",+ "error",+ "cancelled",+ "unknown",+] as const;+export type OutputStatus = (typeof OUTPUT_STATUSES)[number];+export interface OutputSummary {slug: string;utterance?: string;- status?: string;+ status?: OutputStatus;/** Full missions.id when the dir resolved to a DB row — enables cancel. */mission_id?: string | null;summary?: string;@@ -51,6 +61,14 @@ export interface OutputSummary {started_at?: number;github_url?: string | null;error?: string | null;+ /** Canonical terminal-event reason, when one was recorded. */+ terminal_reason?: string | null;+ terminal_event?: string | null;+ artifact_count?: number;+ /** A non-approved/cancelled mission retained genuine deliverable files. */+ has_partial_output?: boolean;+ /** Review ended without approval, but a genuine deliverable was retained. */+ needs_review?: boolean;/** When this terminal mission has already been continued/restarted and that* re-run is still running, the full id + slug of that live child. The card* then shows a "running" indicator pointing at the child instead of adiff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex c30deec454..73b91b9cc0 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -1470,6 +1470,11 @@"rerun_starting": "Wird gestartet…","rerun_confirm": "Erneut ausführen","continuation_running": "Fortgesetzt · läuft",+ "needs_review": "Prüfung nötig",+ "needs_review_hint": "Ein Ergebnis wurde gespeichert, aber nicht vom Critic freigegeben. Prüfe die Dateien oder starte die Mission neu.",+ "partial_output_hint": "Einige Dateien der fehlgeschlagenen Mission wurden aufbewahrt. Das ist keine Freigabe.",+ "cancellation_reason": "Abbruchgrund",+ "failure_reason": "Fehlergrund","list_load_error": "Outputs nicht geladen","empty_sessions": "Noch keine {name}-Agent-Sessions. Starte einen {name}-Agent-Task.","select_session": "Wähle eine Session.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 336771c96e..07234f110e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -1471,6 +1471,11 @@"rerun_starting": "Starting…","rerun_confirm": "Confirm re-run","continuation_running": "Continued · running",+ "needs_review": "Needs review",+ "needs_review_hint": "A deliverable was saved, but no critic approval was recorded. Review the files or restart the mission.",+ "partial_output_hint": "Some files were retained from the failed mission. Their presence is not an approval.",+ "cancellation_reason": "Cancellation reason",+ "failure_reason": "Failure reason","list_load_error": "Could not load outputs","empty_sessions": "No {name}-Agent sessions yet. Start a {name}-Agent task.","select_session": "Select a session.",diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex 24c4a966f9..24a9034df1 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -1470,6 +1470,11 @@"rerun_starting": "Iniciando…","rerun_confirm": "Confirmar reejecución","continuation_running": "Continuado · en curso",+ "needs_review": "Requiere revisión",+ "needs_review_hint": "Se guardó un resultado, pero el crítico no lo aprobó. Revisa los archivos o reinicia la misión.",+ "partial_output_hint": "Se conservaron algunos archivos de la misión fallida. Su presencia no implica aprobación.",+ "cancellation_reason": "Motivo de la cancelación",+ "failure_reason": "Motivo del fallo","list_load_error": "No se pudieron cargar las salidas","empty_sessions": "Aún no hay sesiones de {name}-Agents. Inicia una tarea de {name}-Agent.","select_session": "Selecciona una sesión.",diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.test.ts b/jarvis/ui/web/frontend/src/lib/clipboard.test.tsindex 1427a82486..bcf1678698 100644--- a/jarvis/ui/web/frontend/src/lib/clipboard.test.ts+++ b/jarvis/ui/web/frontend/src/lib/clipboard.test.ts@@ -1,6 +1,32 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { saveOrDownload } from "./clipboard";+import { robustCopy, saveOrDownload } from "./clipboard";++const originalClipboard = Object.getOwnPropertyDescriptor(navigator, "clipboard");+const originalExecCommand = Object.getOwnPropertyDescriptor(document, "execCommand");++function restoreProperty(+ owner: object,+ name: string,+ descriptor: PropertyDescriptor | undefined,+) {+ if (descriptor) Object.defineProperty(owner, name, descriptor);+ else delete (owner as Record<string, unknown>)[name];+}++function stubClipboard(writeText: (text: string) => Promise<void>) {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { writeText },+ });+}++function stubExecCommand(copy: () => boolean) {+ Object.defineProperty(document, "execCommand", {+ configurable: true,+ value: copy,+ });+}/** jsdom does not define URL.createObjectURL at all, so assign the methods* directly (spyOn would fail) + stub the anchor click so the browser-download@@ -22,6 +48,64 @@ describe("saveOrDownload", () => {afterEach(() => {vi.restoreAllMocks();vi.unstubAllGlobals();+ restoreProperty(navigator, "clipboard", originalClipboard);+ restoreProperty(document, "execCommand", originalExecCommand);+ });++ describe("robustCopy", () => {+ it("uses the browser clipboard when it succeeds", async () => {+ const writeText = vi.fn(async () => undefined);+ const fetchMock = vi.fn();+ stubClipboard(writeText);+ stubExecCommand(() => false);+ vi.stubGlobal("fetch", fetchMock);++ await expect(robustCopy("short text")).resolves.toBe(true);++ expect(writeText).toHaveBeenCalledWith("short text");+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("falls back to the desktop backend when WKWebView blocks DOM copy", async () => {+ stubClipboard(vi.fn(async () => Promise.reject(new Error("blocked"))));+ stubExecCommand(() => false);+ const fetchMock = vi.fn(async () => ({+ ok: true,+ json: async () => ({ copied: true }),+ }));+ vi.stubGlobal("fetch", fetchMock);++ await expect(robustCopy("first line\nsecond line")).resolves.toBe(true);++ expect(fetchMock).toHaveBeenCalledWith(+ "/api/clipboard/text",+ expect.objectContaining({+ method: "POST",+ body: JSON.stringify({ text: "first line\nsecond line" }),+ }),+ );+ });++ it("uses the backend when WebView2 cannot confirm a multiline overwrite", async () => {+ stubClipboard(vi.fn(async () => undefined));+ stubExecCommand(() => false);+ const fetchMock = vi.fn(async () => ({+ ok: true,+ json: async () => ({ copied: true }),+ }));+ vi.stubGlobal("fetch", fetchMock);++ await expect(robustCopy("one\ntwo")).resolves.toBe(true);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it("reports failure when browser and native clipboard paths fail", async () => {+ stubClipboard(vi.fn(async () => Promise.reject(new Error("blocked"))));+ stubExecCommand(() => false);+ vi.stubGlobal("fetch", vi.fn(async () => ({ ok: false })));++ await expect(robustCopy("copy me")).resolves.toBe(false);+ });});it("posts base64 to the backend on desktop and returns the saved path", async () => {diff --git a/jarvis/ui/web/frontend/src/lib/clipboard.ts b/jarvis/ui/web/frontend/src/lib/clipboard.tsindex 7cca6add59..5a91d45b53 100644--- a/jarvis/ui/web/frontend/src/lib/clipboard.ts+++ b/jarvis/ui/web/frontend/src/lib/clipboard.ts@@ -1,25 +1,21 @@/*** Robust clipboard + download helper.*- * Background: on Windows, pywebview uses the WebView2 engine- * (Edge Chromium). Its ``navigator.clipboard.writeText`` has a known- * quirk for **multi-line strings** (e.g. JSON with ``indent=2``) —- * sometimes only the first line (= ``{``) ends up in the system- * clipboard. Markdown/plain text hits this less often, because their- * header fills the first line with more characters.+ * Background: embedded WebViews do not expose one dependable browser clipboard+ * path. WebView2 can truncate multi-line text, while WKWebView can reject both+ * ``navigator.clipboard.writeText`` and ``execCommand('copy')`` after the click+ * handler awaited an export request and lost its transient user activation.*- * Solution: robustCopy() first tries the modern clipboard API. On- * failure OR on suspiciously short output (multi-line truncation), it- * falls back to the classic ``document.execCommand('copy')`` path —- * which works via a hidden ``textarea`` + selection and reliably- * writes the full content in WebView2.+ * Solution: robustCopy() tries the modern API, then a selected hidden textarea,+ * then a desktop-only REST fallback that writes through the operating system.+ * The REST route is disabled on a browser/headless server, so those surfaces+ * remain scoped to the user's browser clipboard.*//*** Robustly copies a string to the system clipboard.*- * Returns true if successful (or if the fallback path was used),- * false if both paths failed.+ * Returns true if any path succeeded, false if all paths failed.*/export async function robustCopy(text: string): Promise<boolean> {// Path A — modern clipboard API. Fast and reliable for short texts.@@ -37,7 +33,8 @@ export async function robustCopy(text: string): Promise<boolean> {// too — it overwrites the corrupted entry with the full text// if needed.if (text.includes("\n")) {- return execCommandCopy(text);+ if (execCommandCopy(text)) return true;+ return nativeBackendCopy(text);}return true;}@@ -45,7 +42,29 @@ export async function robustCopy(text: string): Promise<boolean> {// Path A failed — fall through to the fallback.}// Path B — classic fallback via a hidden textarea.- return execCommandCopy(text);+ if (execCommandCopy(text)) return true;+ // Path C — local desktop backend. It is intentionally unavailable on a+ // browser/headless server, where writing would target the wrong machine.+ return nativeBackendCopy(text);+}++async function nativeBackendCopy(text: string): Promise<boolean> {+ if (typeof fetch !== "function") return false;+ try {+ const response = await fetch("/api/clipboard/text", {+ method: "POST",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ text }),+ });+ if (!response.ok) return false;+ const result = (await response.json().catch(() => null)) as {+ copied?: unknown;+ } | null;+ return result?.copied === true;+ } catch {+ return false;+ }}function execCommandCopy(text: string): boolean {diff --git a/jarvis/ui/web/frontend/src/store/jarvisAgents.ts b/jarvis/ui/web/frontend/src/store/jarvisAgents.tsindex 722ca9e63a..d5683ab16d 100644--- a/jarvis/ui/web/frontend/src/store/jarvisAgents.ts+++ b/jarvis/ui/web/frontend/src/store/jarvisAgents.ts@@ -10,7 +10,7 @@ import { create } from "zustand";import { agentBrandNow } from "@/lib/agentBrand";export type NodeKind = "router" | "jarvis_agent" | "harness" | "tool_call";-export type NodeStatus = "running" | "completed" | "failed";+export type NodeStatus = "running" | "completed" | "failed" | "cancelled";export interface ToolCallEntry {trace_id?: string | null;diff --git a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsxindex f6bd0c73e7..f3f5e06f62 100644--- a/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx+++ b/jarvis/ui/web/frontend/src/views/ApiKeysView.tsx@@ -38,6 +38,7 @@ import {import { useEventStore } from "@/store/events";import { useVoiceMode } from "@/hooks/useVoiceMode";import { agentBrand, agentsBrand } from "@/lib/agentBrand";+import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -1738,10 +1739,8 @@ function CodexAuthWidget({async function handleCopy() {setPending("copy");try {- await navigator.clipboard.writeText(installCommand);- pushToast("success", "Install command copied");- } catch {- pushToast("warning", installCommand);+ const copied = await robustCopy(installCommand);+ pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);} finally {setPending(null);}@@ -1871,10 +1870,8 @@ function AntigravityAuthWidget({async function handleCopy() {setPending("copy");try {- await navigator.clipboard.writeText(installCommand);- pushToast("success", "Install command copied");- } catch {- pushToast("warning", installCommand);+ const copied = await robustCopy(installCommand);+ pushToast(copied ? "success" : "warning", copied ? "Install command copied" : installCommand);} finally {setPending(null);}diff --git a/jarvis/ui/web/frontend/src/views/McpsView.tsx b/jarvis/ui/web/frontend/src/views/McpsView.tsxindex 45ec4ab77b..a4228039cf 100644--- a/jarvis/ui/web/frontend/src/views/McpsView.tsx+++ b/jarvis/ui/web/frontend/src/views/McpsView.tsx@@ -12,6 +12,7 @@ import { ScrollArea } from "@/components/ui/scroll-area";import { Switch } from "@/components/ui/switch";import { Button } from "@/components/ui/button";import { useEventStore } from "@/store/events";+import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -362,12 +363,13 @@ function ConfigModal({ onClose }: { onClose: () => void }) {},});- const copyPath = () => {+ const copyPath = async () => {const path = info.data?.path;if (!path) return;- navigator.clipboard?.writeText(path).then(- () => pushToast("info", t("mcps_view.path_copied")),- () => pushToast("error", t("mcps_view.copy_failed")),+ const copied = await robustCopy(path);+ pushToast(+ copied ? "info" : "error",+ t(copied ? "mcps_view.path_copied" : "mcps_view.copy_failed"),);};diff --git a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsxindex 7f94bf69ff..90459de263 100644--- a/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx+++ b/jarvis/ui/web/frontend/src/views/OutputsView.rerun.test.tsx@@ -135,6 +135,53 @@ describe("OutputsView rerun button gating", () => {expect(screen.queryByRole("button", { name: "Continue" })).toBeNull();});+ it("shows retained output as needs-review instead of a generic error", async () => {+ installFetchMock([+ session({+ slug: "review-slug",+ status: "error",+ mission_id: "m-review",+ has_partial_output: true,+ needs_review: true,+ artifact_count: 1,+ terminal_reason: "critic_loop_exhausted",+ error: "critic_loop_exhausted",+ }),+ ]);++ renderView();++ await waitFor(() =>+ expect(screen.getByTestId("output-needs-review")).toBeDefined(),+ );+ expect(screen.getAllByText("Needs review").length).toBeGreaterThan(0);+ expect(screen.getAllByText("critic_loop_exhausted").length).toBeGreaterThan(0);+ expect(screen.queryByTestId("output-terminal-reason")).toBeNull();+ });++ it("keeps a worker failure red when it merely retained a partial file", async () => {+ installFetchMock([+ session({+ slug: "failed-partial",+ status: "error",+ mission_id: "m-failed",+ has_partial_output: true,+ needs_review: false,+ artifact_count: 1,+ terminal_reason: "task_error",+ error: "task_error",+ }),+ ]);++ renderView();++ await waitFor(() =>+ expect(screen.getByTestId("output-terminal-reason")).toBeDefined(),+ );+ expect(screen.queryByTestId("output-needs-review")).toBeNull();+ expect(screen.getAllByText("error").length).toBeGreaterThan(0);+ });+it("replaces Continue with a live continuation chip and jumps to the child", async () => {// Forensic 2026-06-28: a cancelled mission that was already "continued"// kept showing a Continue button next to its own running child — the twodiff --git a/jarvis/ui/web/frontend/src/views/OutputsView.tsx b/jarvis/ui/web/frontend/src/views/OutputsView.tsxindex dd1ac1b011..bfa720b71f 100644--- a/jarvis/ui/web/frontend/src/views/OutputsView.tsx+++ b/jarvis/ui/web/frontend/src/views/OutputsView.tsx@@ -30,6 +30,7 @@ import {revealArtifact,openArtifactWith,type OutputSummary,+ type OutputStatus,type ArtifactSummary,} from "@/hooks/useOutputs";import { OpenWithDialog } from "@/components/OpenWithDialog";@@ -38,7 +39,7 @@ import { useT } from "@/i18n";import { applyMissionDragImage } from "@/lib/missionDragImage";import { useMissionDrag } from "@/store/missionDrag";-const STATUS_BADGE: Record<string, string> = {+const STATUS_BADGE: Record<OutputStatus, string> = {success: "border-emerald-400/40 bg-emerald-400/10 text-emerald-400",error: "border-destructive/40 bg-destructive/10 text-destructive",running: "border-primary/40 bg-primary/10 text-primary",@@ -47,6 +48,9 @@ const STATUS_BADGE: Record<string, string> = {unknown: "border-border bg-secondary/40 text-muted-foreground",};+const NEEDS_REVIEW_BADGE =+ "border-amber-400/40 bg-amber-400/10 text-amber-300";+/** Tiny ping dot inside the RUNNING badge — inherits the badge colour. */function PulseDot() {return (@@ -236,7 +240,9 @@ function SessionRow({const t = useT();const cancel = useCancelMission();const statusKey = meta.status ?? "unknown";- const badgeClass = STATUS_BADGE[statusKey] ?? STATUS_BADGE.unknown;+ const needsReview = statusKey === "error" && !!meta.needs_review;+ const badgeClass = needsReview ? NEEDS_REVIEW_BADGE : STATUS_BADGE[statusKey];+ const statusLabel = needsReview ? t("outputs_view.needs_review") : statusKey;const ts = meta.completed_at ?? meta.started_at;const tsLabel = ts ? new Date(ts * 1000).toLocaleString() : "--";const canAbort = statusKey === "running" && !!meta.mission_id;@@ -316,7 +322,7 @@ function SessionRow({)}>{statusKey === "running" && <PulseDot />}- {statusKey}+ {statusLabel}</span></span>{meta.github_url && (@@ -373,7 +379,10 @@ function SessionDetail({const cancel = useCancelMission();const plan = usePlanForOutput(meta.slug);const statusKey = meta.status ?? "unknown";- const badgeClass = STATUS_BADGE[statusKey] ?? STATUS_BADGE.unknown;+ const needsReview = statusKey === "error" && !!meta.needs_review;+ const isCancelled = statusKey === "cancelled";+ const badgeClass = needsReview ? NEEDS_REVIEW_BADGE : STATUS_BADGE[statusKey];+ const statusLabel = needsReview ? t("outputs_view.needs_review") : statusKey;const canAbort = statusKey === "running" && !!meta.mission_id;const liveChildSlug =statusKey === "cancelled" || statusKey === "error"@@ -399,7 +408,7 @@ function SessionDetail({)}>{statusKey === "running" && <PulseDot />}- {statusKey}+ {statusLabel}</span>{typeof meta.duration_s === "number" && (<span className="text-xs text-muted-foreground">@@ -467,6 +476,41 @@ function SessionDetail({</div></header>+ {(meta.terminal_reason || needsReview) && (+ <section+ data-testid={needsReview ? "output-needs-review" : "output-terminal-reason"}+ className={cn(+ "rounded-xl border p-4",+ needsReview || isCancelled+ ? "border-amber-400/30 bg-amber-400/5"+ : "border-destructive/30 bg-destructive/5",+ )}+ >+ <div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">+ {needsReview+ ? t("outputs_view.needs_review")+ : isCancelled+ ? t("outputs_view.cancellation_reason")+ : t("outputs_view.failure_reason")}+ </div>+ {needsReview && (+ <p className="text-sm leading-relaxed text-foreground/90">+ {t("outputs_view.needs_review_hint")}+ </p>+ )}+ {!needsReview && !isCancelled && meta.has_partial_output && (+ <p className="text-sm leading-relaxed text-foreground/90">+ {t("outputs_view.partial_output_hint")}+ </p>+ )}+ {meta.terminal_reason && (+ <div className="mt-2 font-mono text-[11px] text-muted-foreground">+ {meta.terminal_reason}+ </div>+ )}+ </section>+ )}+{meta.summary && (<section className="rounded-xl border border-border bg-card/40 p-4"><div className="mb-2 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">@@ -478,7 +522,7 @@ function SessionDetail({</section>)}- {meta.error && (+ {meta.error && !meta.terminal_reason && (<section className="rounded-xl border border-destructive/30 bg-destructive/5 p-4"><div className="mb-1 text-[10px] font-semibold uppercase tracking-wide text-destructive">{t("common.error")}diff --git a/jarvis/ui/web/frontend/src/views/PluginsView.tsx b/jarvis/ui/web/frontend/src/views/PluginsView.tsxindex a93a55eb4d..ef3863817c 100644--- a/jarvis/ui/web/frontend/src/views/PluginsView.tsx+++ b/jarvis/ui/web/frontend/src/views/PluginsView.tsx@@ -1543,12 +1543,9 @@ function DeviceCodeDialog({}, [poll.data?.state, onSuccess]);const copyCode = async () => {- try {- await navigator.clipboard.writeText(userCode);+ if (await robustCopy(userCode)) {setCopied(true);window.setTimeout(() => setCopied(false), 1200);- } catch {- // Ignore — user can still type the code manually.}};diff --git a/jarvis/ui/web/frontend/src/views/TelephonyView.tsx b/jarvis/ui/web/frontend/src/views/TelephonyView.tsxindex 4a87c103e0..c8304ed14e 100644--- a/jarvis/ui/web/frontend/src/views/TelephonyView.tsx+++ b/jarvis/ui/web/frontend/src/views/TelephonyView.tsx@@ -19,6 +19,7 @@ import { Button } from "@/components/ui/button";import { Switch } from "@/components/ui/switch";import { SettingsField, settingsInputCls } from "@/views/settings/SettingsBlock";import { useEventStore } from "@/store/events";+import { robustCopy } from "@/lib/clipboard";import { cn } from "@/lib/utils";import { useT } from "@/i18n";@@ -437,11 +438,10 @@ function CopyValue({async function copy() {if (!value) return;- try {- await navigator.clipboard.writeText(value);+ if (await robustCopy(value)) {setCopied(true);window.setTimeout(() => setCopied(false), 1500);- } catch {+ } else {pushToast("warning", value);}}@@ -967,11 +967,10 @@ function ScriptRow({ script }: { script: TelephonyScript }) {const pushToast = useEventStore((s) => s.pushToast);async function copy() {- try {- await navigator.clipboard.writeText(script.command);+ if (await robustCopy(script.command)) {setCopied(true);window.setTimeout(() => setCopied(false), 1500);- } catch {+ } else {pushToast("warning", script.command);}}diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsxnew file mode 100644index 0000000000..edee147543--- /dev/null+++ b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.test.tsx@@ -0,0 +1,51 @@+import type { ComponentProps } from "react";+import { cleanup, render, screen, within } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { DepartureBoard } from "./DepartureBoard";++afterEach(cleanup);++type JarvisAgentNode = NonNullable<+ ComponentProps<typeof DepartureBoard>["agents"]+>[number];++function cancelledNode(): JarvisAgentNode {+ return {+ trace_id: "mission-cancelled",+ kind: "jarvis_agent",+ name: "Assistant-Agent",+ status: "cancelled",+ parent_trace_id: null,+ started_ns: 1,+ completed_ns: 2,+ duration_ms: 1,+ cost_usd: 0,+ tokens_in: 0,+ tokens_out: 0,+ utterance: "Cancelled mission",+ context_hints: [],+ prompts: [],+ tool_calls: [],+ children_trace_ids: [],+ error: "cancelled: user_cancelled",+ error_class: null,+ review_iterations: 0,+ depth: 0,+ ui_appeared_at: 1,+ };+}++describe("DepartureBoard cancellation status", () => {+ it("renders cancellation distinctly and does not count it as failed", () => {+ render(<DepartureBoard agents={[cancelledNode()]} />);++ const row = screen.getByRole("button", { name: /cancelled mission/i });+ expect(within(row).getByText("CANCELLED")).toBeTruthy();+ expect(within(row).queryByText("FAILED")).toBeNull();++ const failedMetric = screen.getByText("Failed").parentElement;+ expect(failedMetric).not.toBeNull();+ expect(within(failedMetric as HTMLElement).getByText("0")).toBeTruthy();+ });+});diff --git a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsxindex 064b90013d..59b377871a 100644--- a/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx+++ b/jarvis/ui/web/frontend/src/views/sub-agents/DepartureBoard.tsx@@ -24,12 +24,14 @@ const STATUS_COLOR: Record<SubAgentNode["status"], string> = {running: "text-primary",completed: "text-emerald-400",failed: "text-destructive",+ cancelled: "text-amber-400",};const STATUS_LABEL: Record<SubAgentNode["status"], string> = {running: "ACTIVE",completed: "DONE",failed: "FAILED",+ cancelled: "CANCELLED",};const TOOL_STATUS_LABEL: Record<ToolCallEntry["status"], string> = {diff --git a/jarvis/ui/web/outputs_routes.py b/jarvis/ui/web/outputs_routes.pyindex 6a35b71b13..173595cd12 100644--- a/jarvis/ui/web/outputs_routes.py+++ b/jarvis/ui/web/outputs_routes.py@@ -22,7 +22,7 @@ import reimport timefrom datetime import UTCfrom pathlib import Path-from typing import Any+from typing import Any, Final, Literal, get_argsfrom fastapi import APIRouter, HTTPException, Requestfrom pydantic import BaseModel@@ -50,6 +50,56 @@ _SLUG_RE = re.compile(r"^(?P<ts>\d{8}T\d{6})__(?P<utterance>.+?)__(?P<short>[0-9# embedded utterance or timestamp._MISSION_DIR_RE = re.compile(r"^mission_(?P<short>[0-9a-f-]{6,40})$")+OUTPUT_STATUSES: Final[tuple[str, ...]] = (+ "running",+ "success",+ "error",+ "cancelled",+ "unknown",+)+OutputStatus = Literal["running", "success", "error", "cancelled", "unknown"]+if set(get_args(OutputStatus)) != set(OUTPUT_STATUSES):+ raise RuntimeError("OutputStatus drifted from OUTPUT_STATUSES")++# A retained file makes these review outcomes recoverable, but does not sign+# them as successful. Execution, setup, safety, and timeout failures remain+# visibly failed even when they happened to leave a partial file behind.+_REVIEWABLE_FAILURE_REASONS: Final[frozenset[str]] = frozenset(+ {+ "critic_loop_exhausted",+ "critic_unavailable",+ "review_time_budget_exhausted",+ }+)+++class OutputSummary(BaseModel):+ """Typed read model for one archived mission output."""++ slug: str+ utterance: str | None = None+ status: OutputStatus = "unknown"+ mission_id: str | None = None+ summary: str | None = None+ started_at: float | None = None+ completed_at: float | None = None+ duration_s: float | None = None+ github_url: str | None = None+ error: str | None = None+ terminal_reason: str | None = None+ terminal_event: str | None = None+ artifact_count: int = 0+ has_partial_output: bool = False+ needs_review: bool = False+ active_child_id: str | None = None+ active_child_slug: str | None = None+++class OutputsResponse(BaseModel):+ """Response model for the Outputs list."""++ sessions: list[OutputSummary]+def _outputs_root(request: Request) -> Path:"""Resolve the mission outputs directory.@@ -196,7 +246,7 @@ async def _mission_status_lookup(continuetry:cur = await mgr.store.conn.execute(- "SELECT id, state, cost_usd, updated_ms, created_ms, prompt "+ "SELECT id, state, cost_usd, updated_ms, created_ms, prompt, language ""FROM missions WHERE id LIKE ? ORDER BY updated_ms DESC LIMIT 1",(f"{prefix}%",),)@@ -213,8 +263,16 @@ async def _mission_status_lookup("updated_ms": int(row[3] or 0),"created_ms": int(row[4] or 0),"prompt": row[5],+ "language": row[6],"full_id": row[0],}+ record.update(+ await _terminal_outcome_details(+ mgr.store.conn,+ mission_id=str(row[0]),+ output_language=str(row[6] or "en"),+ )+ )# Index by both the short prefix the caller passed AND the full# uuid — downstream code can look up either form.out[prefix] = record@@ -222,6 +280,86 @@ async def _mission_status_lookup(return out+async def _terminal_outcome_details(+ conn: Any,+ *,+ mission_id: str,+ output_language: str = "en",+) -> dict[str, Any]:+ """Return the latest canonical terminal event, with transition fallback.++ Older shutdown cancellation paths persisted only ``MissionStateChanged``.+ The fallback keeps their reason visible without rewriting history; new runs+ also emit the canonical terminal event.+ """+ try:+ cur = await conn.execute(+ """+ SELECT event_type, payload_json+ FROM mission_events+ WHERE mission_id = ?+ AND event_type IN (+ 'MissionApproved', 'MissionFailed', 'MissionCancelled',+ 'MissionTimedOut', 'MissionStateChanged'+ )+ ORDER BY seq DESC+ LIMIT 50+ """,+ (mission_id,),+ )+ rows = await cur.fetchall()+ await cur.close()+ except Exception as exc: # noqa: BLE001+ logger.debug("outputs: terminal event lookup failed for %s: %s", mission_id, exc)+ return {}++ transition_fallback: dict[str, Any] = {}+ for event_type, payload_json in rows:+ try:+ payload = json.loads(payload_json or "{}")+ except (ValueError, TypeError):+ continue+ event_type = str(event_type)+ if event_type == "MissionApproved":+ language = output_language.lower().split("-", 1)[0]+ preferred_summary = {+ "de": payload.get("summary_de"),+ "en": payload.get("summary_en"),+ }.get(language)+ return {+ "terminal_event": event_type,+ "terminal_reason": None,+ "terminal_summary": (+ preferred_summary+ or payload.get("summary_en")+ or payload.get("summary_de")+ ),+ }+ if event_type in ("MissionFailed", "MissionCancelled"):+ return {+ "terminal_event": event_type,+ "terminal_reason": payload.get("reason"),+ "terminal_summary": None,+ }+ if event_type == "MissionTimedOut":+ return {+ "terminal_event": event_type,+ "terminal_reason": "mission_timed_out",+ "terminal_summary": None,+ }+ if (+ not transition_fallback+ and event_type == "MissionStateChanged"+ and str(payload.get("to_state")) in _TERMINAL_STATE_VALUES+ ):+ transition_fallback = {+ "terminal_event": event_type,+ "terminal_reason": payload.get("reason"),+ "terminal_summary": None,+ }+ return transition_fallback++_STATE_TO_STATUS: dict[str, str] = {"PENDING": "running","PLANNING": "running",@@ -301,8 +439,8 @@ async def _live_continuation_map(request: Request) -> dict[str, str]:return out-async def list_outputs(request: Request) -> dict[str, Any]:[email protected]("", response_model=OutputsResponse)+async def list_outputs(request: Request) -> OutputsResponse:"""List output directories newest-first.Each entry mirrors `OutputSummary` in `useOutputs.ts`:@@ -315,7 +453,7 @@ async def list_outputs(request: Request) -> dict[str, Any]:"""root = _outputs_root(request)if not root.is_dir():- return {"sessions": []}+ return OutputsResponse(sessions=[])try:entries = sorted(@@ -385,6 +523,11 @@ async def list_outputs(request: Request) -> dict[str, Any]:"duration_s": None,"github_url": None,"error": None,+ "terminal_reason": None,+ "terminal_event": None,+ "artifact_count": 0,+ "has_partial_output": False,+ "needs_review": False,# When this (terminal) mission has already been continued/restarted# and that re-run is still live, the full id + slug of the running# child — so the UI shows "running", not a redundant "Continue".@@ -401,6 +544,11 @@ async def list_outputs(request: Request) -> dict[str, Any]:summary["active_child_id"] = child_idsummary["active_child_slug"] = f"mission_{child_id[:13]}"summary["utterance"] = summary["utterance"] or mission_row.get("prompt")+ summary["summary"] = mission_row.get("terminal_summary")+ summary["terminal_reason"] = mission_row.get("terminal_reason")+ summary["terminal_event"] = mission_row.get("terminal_event")+ if status == "error":+ summary["error"] = mission_row.get("terminal_reason")# Running missions tick wall-clock from created_ms: right after# dispatch created_ms == updated_ms, so updated-minus-created# rendered a frozen "RUNNING 0.0s" until the next mission event@@ -418,9 +566,39 @@ async def list_outputs(request: Request) -> dict[str, Any]:0.0,(end_ms - mission_row["created_ms"]) / 1000.0,)+ artifact_count = _count_deliverables(entry)+ summary["artifact_count"] = artifact_count+ summary["has_partial_output"] = (+ artifact_count > 0 and summary["status"] in ("error", "cancelled")+ )+ terminal_reason = str(summary.get("terminal_reason") or "")+ reason_key = terminal_reason.split(":", 1)[0]+ summary["needs_review"] = (+ artifact_count > 0+ and summary["status"] == "error"+ and reason_key in _REVIEWABLE_FAILURE_REASONS+ )sessions.append(summary)- return {"sessions": sessions}+ return OutputsResponse.model_validate({"sessions": sessions})+++def _count_deliverables(session_dir: Path) -> int:+ """Count genuine archived files without reading their contents."""+ count = 0+ try:+ for child in session_dir.glob("tasks/*/artifacts/files/**/*"):+ if not child.is_file():+ continue+ try:+ rel_parts = child.relative_to(session_dir).parts+ except ValueError:+ continue+ if _is_deliverable_relpath(rel_parts):+ count += 1+ except OSError as exc:+ logger.debug("outputs: deliverable count failed for %s: %s", session_dir, exc)+ return count@router.get("/capabilities")diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.pyindex f1cf70c5f7..f421b6c109 100644--- a/jarvis/ui/web/server.py+++ b/jarvis/ui/web/server.py@@ -286,6 +286,7 @@ class WebServer:from .chats_routes import router as chats_routerfrom .claude_routes import router as claude_routerfrom .cli_routes import router as cli_router+ from .clipboard_routes import router as clipboard_routerfrom .commands_routes import router as commands_routerfrom .computer_use_routes import router as computer_use_routerfrom .contacts_routes import router as contacts_router@@ -394,6 +395,7 @@ class WebServer:app.include_router(sub_agents_router)app.include_router(outputs_router)app.include_router(downloads_router)+ app.include_router(clipboard_router)# Socials section — project social-media links (pure file store, no Brain dep).app.include_router(socials_router)# In-app feedback / bug-report form → Discord webhook.diff --git a/tests/integration/test_clipboard_routes.py b/tests/integration/test_clipboard_routes.pynew file mode 100644index 0000000000..0402843ed3--- /dev/null+++ b/tests/integration/test_clipboard_routes.py@@ -0,0 +1,72 @@+"""Integration tests for the desktop-only clipboard REST fallback."""+from __future__ import annotations++import pytest+from fastapi import FastAPI+from fastapi.testclient import TestClient++import jarvis.ui.web.clipboard_routes as clipboard_routes+from jarvis.ui.web.clipboard_routes import router as clipboard_router+++def _client(*, native: bool) -> TestClient:+ app = FastAPI()+ app.state.native_file_actions = native+ app.include_router(clipboard_router)+ return TestClient(app)+++def test_desktop_copy_writes_complete_text(monkeypatch: pytest.MonkeyPatch) -> None:+ copied: list[str] = []+ monkeypatch.setattr(+ clipboard_routes,+ "write_text",+ lambda text: (copied.append(text), True)[1],+ )++ response = _client(native=True).post(+ "/api/clipboard/text",+ json={"text": "first line\nsecond line"},+ )++ assert response.status_code == 200, response.text+ assert response.json() == {"copied": True}+ assert copied == ["first line\nsecond line"]+++def test_headless_copy_is_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ called = False++ def _unexpected(_text: str) -> bool:+ nonlocal called+ called = True+ return True++ monkeypatch.setattr(clipboard_routes, "write_text", _unexpected)+ response = _client(native=False).post(+ "/api/clipboard/text",+ json={"text": "browser-owned text"},+ )++ assert response.status_code == 404+ assert response.json()["detail"] == "native-clipboard-disabled"+ assert called is False+++def test_unavailable_native_clipboard_returns_503(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(clipboard_routes, "write_text", lambda _text: False)+ response = _client(native=True).post(+ "/api/clipboard/text",+ json={"text": "copy me"},+ )++ assert response.status_code == 503+ assert response.json()["detail"] == "native-clipboard-unavailable"+++def test_copy_route_declares_danger_metadata() -> None:+ schema = _client(native=True).app.openapi()+ operation = schema["paths"]["/api/clipboard/text"]["post"]+ assert operation["x-jarvis-dangerous"] is Truediff --git a/tests/missions/critic/test_prompts.py b/tests/missions/critic/test_prompts.pyindex 83d70af259..ad9cff6d95 100644--- a/tests/missions/critic/test_prompts.py+++ b/tests/missions/critic/test_prompts.py@@ -1,40 +1,76 @@"""Tests for the Critic prompt templates.-Explicitly checks the five design-reviewer criteria from+Checks the applicable design-reviewer criteria from`.claude/agents/jarvis-critic-design-reviewer.md`:- Criterion 1 — evidence-cite requirement (prompt demands file:line / log_line:N / test:name).-- Criterion 2 — adversarial framing verbatim from the research doc §F.+- Criterion 2 — skeptical framing without a defect quota.- Criterion 3 — anchor token (mission_prompt verbatim, triple-bracketed)."""from __future__ import annotationsfrom jarvis.missions.critic.prompts import (ADVERSARIAL_REFRAME_PREFIX,+ CODEX_FLAT_OUTPUT_CONTRACT,CRITIC_SYSTEM_PROMPT,+ FULL_CRITIC_OUTPUT_CONTRACT,render_critic_prompt,)-# --- Criterion 2 — Adversarial Framing ---def test_template_contains_skeptical_phrasing() -> None:- assert "skeptical of this implementation" in CRITIC_SYSTEM_PROMPT+ assert "skeptical of this" in CRITIC_SYSTEM_PROMPT-def test_template_demands_minimum_three_issues() -> None:- assert "find at least three concrete bugs" in CRITIC_SYSTEM_PROMPT+def test_template_forbids_a_defect_quota() -> None:+ assert "find at least three concrete bugs" not in CRITIC_SYSTEM_PROMPT+ assert "Never invent findings" in CRITIC_SYSTEM_PROMPT-def test_template_demands_falsification_justification() -> None:- assert (- "explain why each plausible failure mode does NOT apply"- in CRITIC_SYSTEM_PROMPT+def test_template_only_revises_for_blocking_defects() -> None:+ assert "verdict=revise only" in CRITIC_SYSTEM_PROMPT+ assert "cited blocking defect" in CRITIC_SYSTEM_PROMPT+ assert "NON-BLOCKING" in CRITIC_SYSTEM_PROMPT+ assert "requirements not present in the original mission" in CRITIC_SYSTEM_PROMPT+++def test_codex_prompt_uses_only_the_flat_output_contract() -> None:+ prompt = render_critic_prompt(+ mission_prompt="Build a report",+ worker_diff="diff",+ log_summary="log",+ prior_reflections="none",+ iteration=0,+ codex_flat=True,)+ assert CODEX_FLAT_OUTPUT_CONTRACT in prompt+ assert FULL_CRITIC_OUTPUT_CONTRACT not in prompt+ assert '"correctness_evidence"' in prompt+ assert '"axes"' not in prompt+ assert '"issues"' not in prompt+++def test_default_prompt_retains_the_full_verdict_contract() -> None:+ prompt = render_critic_prompt(+ mission_prompt="Build a report",+ worker_diff="diff",+ log_summary="log",+ prior_reflections="none",+ iteration=0,+ )++ assert FULL_CRITIC_OUTPUT_CONTRACT in prompt+ assert CODEX_FLAT_OUTPUT_CONTRACT not in prompt+++def test_template_demands_falsification_justification() -> None:+ assert "plausible failure modes do not apply" in CRITIC_SYSTEM_PROMPT+def test_template_uses_adversarial_role() -> None:- assert "adversarial code critic" in CRITIC_SYSTEM_PROMPT+ assert "adversarial mission-output critic" in CRITIC_SYSTEM_PROMPT# --- Criterion 1 — Evidence-Cite Requirement ---@@ -90,7 +126,7 @@ def test_render_does_not_paraphrase_mission_prompt() -> None:# --- Schema-Reminder + Output-Rules ----def test_template_includes_output_schema_keys() -> None:+def test_full_output_contract_includes_schema_keys() -> None:for key in ("verdict","axes",@@ -100,7 +136,7 @@ def test_template_includes_output_schema_keys() -> None:"confidence","suggested_next_action",):- assert f'"{key}"' in CRITIC_SYSTEM_PROMPT+ assert f'"{key}"' in FULL_CRITIC_OUTPUT_CONTRACTdef test_template_demands_no_prose_no_markdown() -> None:@@ -219,8 +255,9 @@ def test_render_adversarial_reframe_prepends_prefix() -> None:def test_adversarial_prefix_emphasizes_skepticism() -> None:- assert "sycophantic critic" in ADVERSARIAL_REFRAME_PREFIX- assert "default position is now FAIL" in ADVERSARIAL_REFRAME_PREFIX+ assert "maximum skepticism" in ADVERSARIAL_REFRAME_PREFIX+ assert "do not invent a blocker" in ADVERSARIAL_REFRAME_PREFIX+ assert "default position is now FAIL" not in ADVERSARIAL_REFRAME_PREFIXdef test_render_anchor_present_in_both_modes() -> None:diff --git a/tests/missions/critic/test_runner_claude_direct.py b/tests/missions/critic/test_runner_claude_direct.pyindex a4872dc44b..94a640d3df 100644--- a/tests/missions/critic/test_runner_claude_direct.py+++ b/tests/missions/critic/test_runner_claude_direct.py@@ -120,6 +120,10 @@ def _patch_direct("jarvis.missions.critic.runner._resolve_critic_provider_model",lambda: ("claude-api", "claude-sonnet-4-6"),)+ monkeypatch.setattr(+ "jarvis.missions.critic.runner._claude_cli_critic_viable",+ lambda: True,+ )# Neutralize the in-process API critic so no live network call is made# even on a machine that has a real API key configured.monkeypatch.setattr(diff --git a/tests/missions/critic/test_runner_codex_flat.py b/tests/missions/critic/test_runner_codex_flat.pynew file mode 100644index 0000000000..fe2bffabb4--- /dev/null+++ b/tests/missions/critic/test_runner_codex_flat.py@@ -0,0 +1,160 @@+"""Regression coverage for the direct Codex critic's flat output contract."""++from __future__ import annotations++import pytest++from jarvis.missions.critic.runner import (+ _CODEX_CRITIC_OUTPUT_SCHEMA,+ _verdict_from_codex_flat,+)+from jarvis.missions.critic.verdict import REQUIRED_AXES, is_approval_valid+++def _flat_verdict(+ *,+ verdict: str = "approve",+ blocking_issue: bool = False,+ summary: str = "The requested deliverable is complete.",+ summary_de: str = "The requested deliverable is complete.",+) -> dict[str, object]:+ payload: dict[str, object] = {+ "verdict": verdict,+ "confidence": 0.91,+ "summary": summary,+ "summary_de": summary_de,+ "correction_instruction": "" if verdict == "approve" else "Fix the blocker.",+ "blocking_issue": blocking_issue,+ }+ for axis in REQUIRED_AXES:+ payload[f"{axis}_status"] = "pass"+ payload[f"{axis}_evidence"] = f"artifact.html:1 — {axis} verified"+ return payload+++def test_schema_requires_grounded_axis_fields_and_blocking_decision() -> None:+ properties = set(_CODEX_CRITIC_OUTPUT_SCHEMA["properties"])+ required = set(_CODEX_CRITIC_OUTPUT_SCHEMA["required"])+ assert properties == required+ assert "blocking_issue" in required+ for axis in REQUIRED_AXES:+ assert f"{axis}_status" in required+ assert f"{axis}_evidence" in required+++def test_overlong_flat_approval_is_truncated_not_discarded() -> None:+ verdict = _verdict_from_codex_flat(+ _flat_verdict(summary="A" * 400, summary_de="B" * 400)+ )++ assert verdict.verdict == "approve"+ assert is_approval_valid(verdict)+ assert len(verdict.summary) == 280+ assert len(verdict.summary_de) == 280+ assert verdict.summary.endswith("…")+ assert verdict.summary_de.endswith("…")+++def test_legacy_five_field_approval_also_uses_tolerant_validation() -> None:+ verdict = _verdict_from_codex_flat(+ {+ "verdict": "approve",+ "confidence": 0.9,+ "summary": "A" * 400,+ "summary_de": "B" * 400,+ "correction_instruction": "",+ }+ )++ assert verdict.verdict == "approve"+ assert is_approval_valid(verdict)+ assert len(verdict.summary) == 280+ assert len(verdict.summary_de) == 280+++def test_blocking_revision_preserves_truthful_axis_evidence() -> None:+ payload = _flat_verdict(verdict="revise", blocking_issue=True)+ payload["correctness_status"] = "fail"+ payload["correctness_evidence"] = "artifact.html:42 — unsafe medical claim"++ verdict = _verdict_from_codex_flat(payload)++ assert verdict.verdict == "revise"+ assert verdict.axes["correctness"].status == "fail"+ assert verdict.axes["correctness"].evidence == [+ "artifact.html:42 — unsafe medical claim"+ ]+ assert verdict.axes["security"].status == "pass"+ assert verdict.axes["security"].evidence+++def test_nonblocking_all_pass_revision_is_normalized_to_approval() -> None:+ payload = _flat_verdict(verdict="revise", blocking_issue=False)+ payload["correction_instruction"] = "Optional: polish the print stylesheet."++ verdict = _verdict_from_codex_flat(payload)++ assert verdict.verdict == "approve"+ assert verdict.suggested_next_action == "accept"+ assert is_approval_valid(verdict)+++def test_nonblocking_all_pass_rejection_is_normalized_to_approval() -> None:+ payload = _flat_verdict(verdict="reject", blocking_issue=False)+ payload["correction_instruction"] = ""++ verdict = _verdict_from_codex_flat(payload)++ assert verdict.verdict == "approve"+ assert verdict.suggested_next_action == "accept"+ assert is_approval_valid(verdict)+++def test_blocker_without_a_failed_axis_is_rejected_as_contradictory() -> None:+ payload = _flat_verdict(verdict="revise", blocking_issue=True)++ with pytest.raises(ValueError, match="contradicts its blocking flag"):+ _verdict_from_codex_flat(payload)+++def test_claimed_approval_with_a_blocker_fails_closed() -> None:+ payload = _flat_verdict(verdict="approve", blocking_issue=True)+ payload["completeness_status"] = "fail"+ payload["completeness_evidence"] = "artifact.html:8 — requested section absent"++ verdict = _verdict_from_codex_flat(payload)++ assert verdict.verdict == "revise"+ assert verdict.suggested_next_action == "retry"+++def test_partial_new_axis_shape_is_rejected_instead_of_using_legacy_fallback() -> None:+ payload = {+ "verdict": "approve",+ "confidence": 0.9,+ "summary": "ok",+ "summary_de": "ok",+ "correction_instruction": "",+ "blocking_issue": False,+ "correctness_status": "pass",+ }++ with pytest.raises(ValueError, match="Incomplete Codex flat verdict"):+ _verdict_from_codex_flat(payload)+++def test_empty_revision_evidence_is_rejected() -> None:+ payload = _flat_verdict(verdict="revise", blocking_issue=True)+ payload["correctness_status"] = "fail"+ payload["correctness_evidence"] = " "++ with pytest.raises(ValueError, match="empty evidence.*correctness"):+ _verdict_from_codex_flat(payload)+++def test_non_summary_schema_error_is_not_tolerated() -> None:+ payload = _flat_verdict()+ payload["confidence"] = 1.5++ with pytest.raises(ValueError):+ _verdict_from_codex_flat(payload)diff --git a/tests/missions/kontrollierer/test_cancel_running.py b/tests/missions/kontrollierer/test_cancel_running.pyindex a5ff8a36d6..a7e033955a 100644--- a/tests/missions/kontrollierer/test_cancel_running.py+++ b/tests/missions/kontrollierer/test_cancel_running.py@@ -18,6 +18,7 @@ from typing import Anyimport pytestfrom jarvis.missions.budget import BudgetTracker+from jarvis.missions.events import now_msfrom jarvis.missions.kontrollierer.orchestrator import Kontrolliererfrom jarvis.missions.manager import MissionManagerfrom jarvis.missions.state_machine import MissionState@@ -188,6 +189,19 @@ async def test_cancel_all_running_finalizes_inflight_missions(view = await manager.mission(mid)assert view is not Noneassert view.state == MissionState.CANCELLED+ cancelled_events = [+ event.payload+ for event in await manager.store.events_for_mission(mid)+ if event.payload.event_type == "MissionCancelled"+ ]+ assert len(cancelled_events) == 1+ assert cancelled_events[0].reason == "app_shutdown"+ assert cancelled_events[0].cascade is True++ # A late critic progress update may race with shutdown. It may advance the+ # diagnostic iteration, but it must never resurrect a terminal mission.+ await manager.store.advance_mission_iteration(mid, iteration=2, ts_ms=now_ms())+ assert await manager.store.get_mission_state(mid) == MissionState.CANCELLED.value# Idempotent: nothing left in flight.assert await k.cancel_all_running(reason="app_shutdown") == []diff --git a/tests/missions/kontrollierer/test_capture_diff.py b/tests/missions/kontrollierer/test_capture_diff.pyindex 5446e2d7bb..1207f655c0 100644--- a/tests/missions/kontrollierer/test_capture_diff.py+++ b/tests/missions/kontrollierer/test_capture_diff.py@@ -27,7 +27,6 @@ from jarvis.missions.isolation.worktree import WorktreeManagerfrom jarvis.missions.kontrollierer.orchestrator import Kontrolliererfrom jarvis.missions.worker_runtime.workspace import materialize_worker_contract-PROJECT_ROOT = Path(__file__).resolve().parents[3]@@ -274,6 +273,188 @@ def test_archive_task_artifacts_handles_empty_worktree(assert (artifacts / "diff.patch").read_text(encoding="utf-8") == ""+def test_draft_snapshot_survives_before_final_archive_and_retains_history(+ worktree: Path, kontrollierer: Kontrollierer, tmp_path: Path+) -> None:+ """A published draft must already have a durable file outside its worktree."""+ task_id = "draft-snapshot-task"+ mission_dir = tmp_path / "mission_root"+ mission_dir.mkdir()+ output = worktree / "report.html"+ output.write_text("<!doctype html><p>first draft</p>", encoding="utf-8")+ first_diff = kontrollierer._capture_diff(worktree)+ kontrollierer._task_iter_diffs = {task_id: [(0, first_diff)]}++ draft_artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ drain_iteration_diffs=False,+ )++ assert draft_artifacts is not None+ durable = draft_artifacts / "files" / "report.html"+ assert durable.read_text(encoding="utf-8") == "<!doctype html><p>first draft</p>"+ assert task_id in kontrollierer._task_iter_diffs++ output.write_text("<!doctype html><p>corrected draft</p>", encoding="utf-8")+ second_diff = kontrollierer._capture_diff(worktree)+ kontrollierer._task_iter_diffs[task_id].append((1, second_diff))+ final_artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ )++ assert final_artifacts is not None+ assert (final_artifacts / "diff.iter0.patch").is_file()+ assert (final_artifacts / "diff.iter1.patch").is_file()+ assert durable.read_text(encoding="utf-8") == "<!doctype html><p>corrected draft</p>"+ assert task_id not in kontrollierer._task_iter_diffs+++def test_final_archive_replaces_a_deleted_and_renamed_first_draft(+ worktree: Path, kontrollierer: Kontrollierer, tmp_path: Path+) -> None:+ """Canonical files must reflect the latest iteration, not the largest diff."""+ task_id = "rename-draft"+ mission_dir = tmp_path / "mission_root"+ mission_dir.mkdir()+ first = worktree / "draft-one.html"+ first.write_text("<!doctype html><p>first</p>", encoding="utf-8")+ first_diff = kontrollierer._capture_diff(worktree)+ kontrollierer._task_iter_diffs = {task_id: [(0, first_diff)]}++ draft_artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ drain_iteration_diffs=False,+ )+ assert draft_artifacts is not None+ assert (draft_artifacts / "files" / first.name).is_file()++ first.unlink()+ final = worktree / "final.html"+ final.write_text("<!doctype html><p>final</p>", encoding="utf-8")+ second_diff = kontrollierer._capture_diff(worktree)+ kontrollierer._task_iter_diffs[task_id].append((1, second_diff))++ final_artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ )++ assert final_artifacts is not None+ assert not (final_artifacts / "files" / first.name).exists()+ assert (final_artifacts / "files" / final.name).read_text(encoding="utf-8") == (+ "<!doctype html><p>final</p>"+ )+ assert (final_artifacts / "diff.iter0.patch").is_file()+ assert (final_artifacts / "diff.iter1.patch").is_file()+++def test_snapshot_copy_failure_preserves_previous_durable_draft(+ worktree: Path,+ kontrollierer: Kontrollierer,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A failed refresh must not erase the last recoverable worker output."""+ task_id = "copy-failure"+ mission_dir = tmp_path / "mission_root"+ mission_dir.mkdir()+ output = worktree / "report.html"+ output.write_text("<!doctype html><p>durable draft</p>", encoding="utf-8")++ draft_artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ drain_iteration_diffs=False,+ )+ assert draft_artifacts is not None+ durable = draft_artifacts / "files" / output.name+ assert durable.read_text(encoding="utf-8") == (+ "<!doctype html><p>durable draft</p>"+ )++ output.write_text("<!doctype html><p>new draft</p>", encoding="utf-8")+ real_copy2 = shutil.copy2++ def fail_new_snapshot_copy(+ src: Path, dst: Path, *args: object, **kwargs: object+ ) -> object:+ if Path(src) == output and ".files-next-" in str(dst):+ raise OSError("simulated snapshot copy failure")+ return real_copy2(src, dst, *args, **kwargs)++ monkeypatch.setattr(shutil, "copy2", fail_new_snapshot_copy)++ failed_archive = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ )++ assert failed_archive is None+ assert durable.read_text(encoding="utf-8") == (+ "<!doctype html><p>durable draft</p>"+ )+ assert not list(draft_artifacts.glob(".files-next-*"))+++def test_snapshot_promotion_failure_rolls_back_previous_durable_draft(+ worktree: Path,+ kontrollierer: Kontrollierer,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A failed directory promotion restores the prior canonical snapshot."""+ task_id = "promotion-failure"+ mission_dir = tmp_path / "mission_root"+ mission_dir.mkdir()+ output = worktree / "report.html"+ output.write_text("<!doctype html><p>durable draft</p>", encoding="utf-8")++ draft_artifacts = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ drain_iteration_diffs=False,+ )+ assert draft_artifacts is not None+ durable = draft_artifacts / "files" / output.name++ output.write_text("<!doctype html><p>new draft</p>", encoding="utf-8")+ real_replace = Path.replace+ failed_once = False++ def fail_staged_promotion(source: Path, target: Path) -> Path:+ nonlocal failed_once+ if source.name.startswith(".files-next-") and not failed_once:+ failed_once = True+ raise OSError("simulated snapshot promotion failure")+ return real_replace(source, target)++ monkeypatch.setattr(Path, "replace", fail_staged_promotion)++ failed_archive = kontrollierer._archive_task_artifacts(+ worktree=worktree,+ mission_dir=mission_dir,+ task_id=task_id,+ )++ assert failed_archive is None+ assert failed_once is True+ assert durable.read_text(encoding="utf-8") == (+ "<!doctype html><p>durable draft</p>"+ )+ assert not list(draft_artifacts.glob(".files-next-*"))+ assert not list(draft_artifacts.glob(".files-previous-*"))++# --- 2026-05-27 hardening audit: archive must round-trip non-ASCII and# gitignored deliverables, and must NOT leak materialized contract files.@@ -458,7 +639,7 @@ def test_archive_captures_committed_deliverable((not a `.md` summary) in artifacts/files/. Reproduces mission 019f26d0-bb07."""ws = lean_manager.create(- mission_slug="choc", task_id="01-committed-archive", needs_repo=False+ mission_slug="choc", task_id="01-a", needs_repo=False)mission_dir = tmp_path / "mission_root"mission_dir.mkdir()diff --git a/tests/missions/kontrollierer/test_loop.py b/tests/missions/kontrollierer/test_loop.pyindex 5c719a13a0..69f6ff079d 100644--- a/tests/missions/kontrollierer/test_loop.py+++ b/tests/missions/kontrollierer/test_loop.py@@ -377,7 +377,7 @@ async def test_critic_unavailable_short_circuits_when_iter0_has_real_diff(async def test_three_iter_exhaustion_fails_mission(manager: MissionManager, tmp_path: Path) -> None:- """Alle 3 Iterationen revise -> MissionFailed("critic_loop_exhausted") nach exakt 3 Spawns."""+ """Three revisions fail once, after exactly three worker spawns."""critic = FakeCriticRunner(*[_make_revise_verdict() for _ in range(3)])shared_worker = FakeWorker()k = _make_kontrollierer(@@ -392,6 +392,9 @@ async def test_three_iter_exhaustion_fails_mission(assert end_state == MissionState.FAILEDassert len(critic.calls) == 3assert len(shared_worker.spawn_calls) == 3+ header = await manager.store.get_mission_view(mid)+ assert header is not None+ assert header[3] == 2, "mission header must reflect the final zero-based iteration"@pytest.mark.asyncio@@ -1369,6 +1372,47 @@ async def test_empty_task_outcomes_is_not_approved()+async def test_worker_error_outranks_review_time_budget_in_multi_task_mission(+ manager: MissionManager,+ tmp_path: Path,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A real worker failure must not be mislabeled as a review time guard."""+ plan = MissionPlan(+ steps=[+ Step(slug="review-step", prompt="review output"),+ Step(slug="worker-step", prompt="run worker"),+ ],+ n_workers=2,+ expected_output="two results",+ )+ k = _make_kontrollierer(+ manager=manager,+ tmp_path=tmp_path,+ critic=FakeCriticRunner(),+ decomposer_plan=plan,+ )++ async def _outcome_for_step(**kwargs: Any) -> str:+ step = kwargs["step"]+ if step.slug == "review-step":+ return TaskOutcome.TIME_BUDGET_EXHAUSTED+ return TaskOutcome.ERROR++ monkeypatch.setattr(k, "_run_task_with_critic_loop", _outcome_for_step)+ mission_id = await manager.dispatch(prompt="run two tasks")++ assert await k.run_mission(mission_id) == MissionState.FAILED+ failures = [+ event.payload+ for event in await manager.store.events_for_mission(mission_id)+ if event.payload.event_type == "MissionFailed"+ ]+ assert len(failures) == 1+ assert failures[0].reason == "task_error"++@pytest.mark.asyncioasync def test_default_max_concurrent_missions_is_one(manager: MissionManager, tmp_path: Pathdiff --git a/tests/missions/kontrollierer/test_time_budget.py b/tests/missions/kontrollierer/test_time_budget.pyindex 6bec303d1d..f7abc2d166 100644--- a/tests/missions/kontrollierer/test_time_budget.py+++ b/tests/missions/kontrollierer/test_time_budget.py@@ -12,8 +12,8 @@ Shape pinned here:- correction iterations get the short budget (6 min) — they refine anexisting workspace, they do not rebuild;- no new correction iteration starts when the remaining task time cannot- fit a correction + one critic call (the loop ends with the existing- exhausted semantics instead of overshooting the 20-minute target);+ fit a correction + one critic call (the mission records that explicit reason+ instead of pretending all three critic attempts ran);- MAX_CRITIC_LOOPS stays untouched (ADR-0009) — the time guard is anadditional bound, not a loop-count change."""@@ -77,8 +77,7 @@ async def test_iter0_gets_main_budget_corrections_get_short_budget(async def test_no_new_iteration_when_time_budget_exhausted(manager: MissionManager, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:- """When no correction fits the remaining budget, the loop ends instead- of overshooting — existing exhausted semantics, only one worker spawn."""+ """When no correction fits, report time budget rather than three failures."""monkeypatch.setattr(orch_mod, "_TASK_TIME_BUDGET_S", 0.0)worker = FakeWorker()critic = FakeCriticRunner(_make_revise_verdict())@@ -95,6 +94,13 @@ async def test_no_new_iteration_when_time_budget_exhausted(assert len(worker.spawn_calls) == 1, ("no second iteration may start once the time budget is spent")+ failures = [+ event.payload+ for event in await manager.store.events_for_mission(mid)+ if event.payload.event_type == "MissionFailed"+ ]+ assert len(failures) == 1+ assert failures[0].reason == "review_time_budget_exhausted"def test_worker_error_transient_matcher_knows_subscription_limits() -> None:diff --git a/tests/missions/test_api_agent_worker_capability_gate.py b/tests/missions/test_api_agent_worker_capability_gate.pyindex 7359d1082f..b6fd8e8137 100644--- a/tests/missions/test_api_agent_worker_capability_gate.py+++ b/tests/missions/test_api_agent_worker_capability_gate.py@@ -112,7 +112,9 @@ async def test_tool_incapable_model_fails_early(assert errors, "expected an early error result"msg = (errors[-1].result or "").lower()assert "cannot call tools" in msg- assert "jarvis-agents" in msg+ assert "missions deliver work" in msg+ assert "settings -> agents" in msg+ assert "jarvis-agent" not in msg# the gate fires before the turn loop — no assistant/user turn was emittedkinds = [type(e).__name__ for e in events]assert "ClaudeAssistantMessage" not in kinds@@ -157,7 +159,9 @@ async def test_first_round_trip_no_endpoints_error_is_translated(assert errors, "expected the raw provider error to be translated"msg = (errors[-1].result or "").lower()assert "cannot call tools" in msg- assert "jarvis-agents" in msg+ assert "missions deliver work" in msg+ assert "settings -> agents" in msg+ assert "jarvis-agent" not in msgasync def test_unrelated_tool_error_is_not_mislabeled(diff --git a/tests/missions/test_voice_readback.py b/tests/missions/test_voice_readback.pyindex 468de54a1e..d645f96c39 100644--- a/tests/missions/test_voice_readback.py+++ b/tests/missions/test_voice_readback.py@@ -258,6 +258,10 @@ def test_failure_reason_phrases_shared_with_announcer() -> None:# 2026-06-07 fix back to a raw snake_case token on the voice path.assert "attempts_timed_out" in FAILURE_REASON_PHRASES["de"]assert "attempts_timed_out" in FAILURE_REASON_PHRASES["en"]+ assert all(+ "review_time_budget_exhausted" in FAILURE_REASON_PHRASES[language]+ for language in ("de", "en", "es")+ )assert set(FAILURE_REASON_PHRASES["de"]) == set(FAILURE_REASON_PHRASES["en"])diff --git a/tests/missions/workers/test_api_agent_worker.py b/tests/missions/workers/test_api_agent_worker.pyindex 9f19f427b0..1032444614 100644--- a/tests/missions/workers/test_api_agent_worker.py+++ b/tests/missions/workers/test_api_agent_worker.py@@ -432,3 +432,32 @@ async def test_stream_jsonl_is_valid_ndjson(worker_id="m::0", log_dir=log_dir)for line in (log_dir / "stream.jsonl").read_text(encoding="utf-8").splitlines():json.loads(line) # every line is valid JSON+++async def test_stream_jsonl_is_isolated_per_spawn(+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path+) -> None:+ """A new worker attempt must replace evidence from the prior iteration."""+ _patch_brain(+ monkeypatch,+ FakeBrain([[BrainDelta(content="current spawn"), BrainDelta(finish_reason="end_turn")]]),+ )+ log_dir = tmp_path / "_logs"+ log_dir.mkdir()+ stream_path = log_dir / "stream.jsonl"+ stream_path.write_text('{"stale":"prior spawn"}\n', encoding="utf-8")++ await _drain(+ ApiAgentWorker("openai"),+ prompt="x",+ worktree=tmp_path,+ env={},+ job=None,+ worker_id="m::1",+ log_dir=log_dir,+ )++ stream_text = stream_path.read_text(encoding="utf-8")+ assert "prior spawn" not in stream_text+ assert "current spawn" in stream_textdiff --git a/tests/missions/workers/test_codex_stream_live.py b/tests/missions/workers/test_codex_stream_live.pyindex b9b457fb02..ba97cb12c7 100644--- a/tests/missions/workers/test_codex_stream_live.py+++ b/tests/missions/workers/test_codex_stream_live.py@@ -176,6 +176,58 @@ async def test_stream_jsonl_written_live(await agen.aclose()+async def test_stream_jsonl_is_isolated_per_spawn(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A new worker attempt must replace evidence from the prior iteration."""+ stdout = _LiveStream()++ async def _fake_exec(*_a: Any, **_k: Any) -> _LiveProc:+ return _LiveProc(stdout)++ monkeypatch.setattr(cdw.asyncio, "create_subprocess_exec", _fake_exec)+ stream_path = tmp_path / "logs" / "stream.jsonl"+ stream_path.parent.mkdir(parents=True)+ stream_path.write_text('{"stale":"prior spawn"}\n', encoding="utf-8")++ agen = _spawn(CodexDirectWorker(), tmp_path)+ try:+ await agen.__anext__() # init+ stdout.queue.put_nowait(_agent_line("current spawn"))+ await asyncio.wait_for(agen.__anext__(), timeout=2.0)++ stream_text = stream_path.read_text(encoding="utf-8")+ assert "prior spawn" not in stream_text+ assert "current spawn" in stream_text++ stdout.queue.put_nowait(b"")+ async for _ in agen:+ pass+ finally:+ await agen.aclose()+++async def test_spawn_failure_does_not_leave_prior_stream_evidence(+ tmp_path: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ """A missing Codex binary must not expose the preceding attempt's log."""++ async def _missing_exec(*_a: Any, **_k: Any) -> Any:+ raise FileNotFoundError("codex")++ monkeypatch.setattr(cdw, "create_worker_subprocess", _missing_exec)+ stream_path = tmp_path / "logs" / "stream.jsonl"+ stream_path.parent.mkdir(parents=True)+ stream_path.write_text('{"stale":"prior spawn"}\n', encoding="utf-8")++ events = [event async for event in _spawn(CodexDirectWorker(), tmp_path)]++ assert getattr(events[-1], "is_error", False) is True+ assert stream_path.read_text(encoding="utf-8") == ""++@pytest.mark.asyncioasync def test_partial_stream_survives_startup_timeout(tmp_path: Path, monkeypatch: pytest.MonkeyPatchdiff --git a/tests/unit/agents/test_node_status_parity.py b/tests/unit/agents/test_node_status_parity.pynew file mode 100644index 0000000000..037f457fc0--- /dev/null+++ b/tests/unit/agents/test_node_status_parity.py@@ -0,0 +1,69 @@+"""Cross-layer parity guard for the Jarvis-Agent Board status vocabulary.++Agent nodes are in-memory dataclasses serialized directly by the REST snapshot,+so the persistence and Pydantic layers collapse here. This guard keeps the+Python producer, TypeScript consumer, and visible board labels synchronized.+"""+from __future__ import annotations++import re+from pathlib import Path+from typing import get_args++from jarvis.agents.registry import NodeStatus++_REPO = Path(__file__).resolve().parents[3]+_STORE = (+ _REPO+ / "jarvis"+ / "ui"+ / "web"+ / "frontend"+ / "src"+ / "store"+ / "jarvisAgents.ts"+)+_BOARD = (+ _REPO+ / "jarvis"+ / "ui"+ / "web"+ / "frontend"+ / "src"+ / "views"+ / "sub-agents"+ / "DepartureBoard.tsx"+)+++def _ts_node_statuses() -> set[str]:+ text = _STORE.read_text(encoding="utf-8")+ match = re.search(r"export type NodeStatus\s*=([^;]+);", text)+ assert match is not None, "TypeScript NodeStatus union is missing"+ return set(re.findall(r'"([^"]+)"', match.group(1)))+++def _board_status_labels() -> set[str]:+ text = _BOARD.read_text(encoding="utf-8")+ match = re.search(+ r"const STATUS_LABEL: Record<[^>]+> = \{(.*?)\n\};",+ text,+ flags=re.DOTALL,+ )+ assert match is not None, "DepartureBoard STATUS_LABEL map is missing"+ return set(re.findall(r"^\s{2}([a-z_]+):", match.group(1), flags=re.MULTILINE))+++def test_node_status_python_typescript_and_ui_parity() -> None:+ python_statuses = set(get_args(NodeStatus))+ assert python_statuses == _ts_node_statuses()+ assert python_statuses == _board_status_labels()+++def test_node_status_expected_vocabulary() -> None:+ assert set(get_args(NodeStatus)) == {+ "running",+ "completed",+ "failed",+ "cancelled",+ }diff --git a/tests/unit/agents/test_registry.py b/tests/unit/agents/test_registry.pyindex 6527553709..8a7155b178 100644--- a/tests/unit/agents/test_registry.py+++ b/tests/unit/agents/test_registry.py@@ -24,8 +24,8 @@ from jarvis.core.events import (BrainTurnStarted,HarnessCompleted,HarnessDispatched,- JarvisAgentTaskCompleted,JarvisAgentReviewTriggered,+ JarvisAgentTaskCompleted,JarvisAgentTaskStarted,ToolCallCompleted,ToolCallStarted,@@ -453,6 +453,67 @@ async def test_mission_bus_bridge_failed_marks_failed(assert "critic exhausted" in (node.error or "")+async def test_mission_bus_bridge_cancelled_marks_tree_cancelled(+ registry: JarvisAgentRegistry,+) -> None:+ """Mission cancellation stays distinct from worker or critic failure."""+ from jarvis.missions.event_bus import MissionBus+ from jarvis.missions.events import (+ EventEnvelope,+ MissionCancelled,+ MissionDispatched,+ WorkerSpawned,+ now_ms,+ )++ mbus = MissionBus()+ registry.attach_mission_bus(mbus)++ mission_id = "019e1800-0000-7000-8000-000000000020"+ worker_id = "019e1800-0000-7000-8000-000000000021"+ await mbus.publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="hauptjarvis",+ ts_ms=now_ms(),+ payload=MissionDispatched(prompt="cancel me", language="en"),+ )+ )+ await mbus.publish(+ EventEnvelope(+ mission_id=mission_id,+ worker_id=worker_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=WorkerSpawned(+ worker_id=worker_id,+ step={"task": "build"},+ pid=4242,+ cli="claude",+ model="sonnet",+ worktree="/workspace/agent-1",+ ),+ )+ )+ await mbus.publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=MissionCancelled(cascade=True, reason="user_cancelled"),+ )+ )++ snapshot = registry.snapshot()+ mission = snapshot[mission_id.replace("-", "")]+ worker = snapshot[worker_id.replace("-", "")]+ assert mission.status == "cancelled"+ assert mission.error == "cancelled: user_cancelled"+ assert worker.status == "cancelled"+ assert worker.error == "cancelled with mission"++@pytest.mark.asyncioasync def test_mission_bus_bridge_is_idempotent(registry: JarvisAgentRegistry,@@ -689,3 +750,62 @@ async def test_worker_killed_without_detail_falls_back_to_reason(assert node.status == "failed"assert node.error == "killed: timeout"assert node.error_class is None++[email protected]("reason", ["user", "parent_cancelled"])+async def test_worker_cancel_reason_stays_distinct_from_failure(+ registry: JarvisAgentRegistry,+ reason: str,+) -> None:+ from jarvis.missions.event_bus import MissionBus+ from jarvis.missions.events import (+ EventEnvelope,+ MissionDispatched,+ WorkerKilled,+ WorkerSpawned,+ now_ms,+ )++ mbus = MissionBus()+ registry.attach_mission_bus(mbus)++ mission_id = "019e1800-0000-7000-8000-000000000030"+ worker_id = "019e1800-0000-7000-8000-000000000031"+ await mbus.publish(+ EventEnvelope(+ mission_id=mission_id,+ source_actor="hauptjarvis",+ ts_ms=now_ms(),+ payload=MissionDispatched(prompt="build it", language="en"),+ )+ )+ await mbus.publish(+ EventEnvelope(+ mission_id=mission_id,+ worker_id=worker_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=WorkerSpawned(+ worker_id=worker_id,+ step={"task": "build"},+ pid=4242,+ cli="claude",+ model="sonnet",+ worktree="/workspace/agent-1",+ ),+ )+ )+ await mbus.publish(+ EventEnvelope(+ mission_id=mission_id,+ worker_id=worker_id,+ source_actor="kontrollierer",+ ts_ms=now_ms(),+ payload=WorkerKilled(worker_id=worker_id, reason=reason),+ )+ )++ node = registry.snapshot()[worker_id.replace("-", "")]+ assert node.status == "cancelled"+ assert node.error == f"killed: {reason}"diff --git a/tests/unit/platform/test_clipboard.py b/tests/unit/platform/test_clipboard.pynew file mode 100644index 0000000000..04cc6021c1--- /dev/null+++ b/tests/unit/platform/test_clipboard.py@@ -0,0 +1,103 @@+"""Unit tests for the cross-platform native clipboard writer."""+from __future__ import annotations++import subprocess+from types import SimpleNamespace++import pytest++import jarvis.platform.clipboard as clipboard+++def _capabilities(display_present: bool) -> SimpleNamespace:+ return SimpleNamespace(display_present=display_present)+++def test_headless_host_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(False)+ )+ called = False++ def _unexpected(_text: str) -> bool:+ nonlocal called+ called = True+ return True++ monkeypatch.setattr(clipboard, "_write_windows", _unexpected)+ assert clipboard.write_text("hello") is False+ assert called is False+++def test_macos_uses_pbcopy_with_stdin(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(True)+ )+ monkeypatch.setattr(clipboard, "detect_platform", lambda: "darwin")+ calls: list[tuple[list[str], str]] = []+ monkeypatch.setattr(+ clipboard,+ "_run_command",+ lambda command, text: (calls.append((list(command), text)), True)[1],+ )++ assert clipboard.write_text("line one\nline two") is True+ assert calls == [(["/usr/bin/pbcopy"], "line one\nline two")]+++def test_windows_dispatches_to_native_unicode_writer(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ clipboard, "detect_capabilities", lambda: _capabilities(True)+ )+ monkeypatch.setattr(clipboard, "detect_platform", lambda: "win32")+ calls: list[str] = []+ monkeypatch.setattr(+ clipboard,+ "_write_windows",+ lambda text: (calls.append(text), True)[1],+ )++ assert clipboard.write_text("Unicode: café") is True+ assert calls == ["Unicode: café"]+++def test_linux_prefers_wayland_clipboard_tool(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ monkeypatch.setattr(+ clipboard.shutil,+ "which",+ lambda name: "/usr/bin/wl-copy" if name == "wl-copy" else None,+ )+ calls: list[tuple[list[str], str]] = []+ monkeypatch.setattr(+ clipboard,+ "_run_command",+ lambda command, text: (calls.append((list(command), text)), True)[1],+ )++ assert clipboard._write_linux("hello") is True+ assert calls == [+ (["/usr/bin/wl-copy", "--type", "text/plain;charset=utf-8"], "hello")+ ]+++def test_command_writer_passes_text_only_through_stdin(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ captured: dict[str, object] = {}++ def _run(command: list[str], **kwargs: object) -> subprocess.CompletedProcess[str]:+ captured["command"] = command+ captured.update(kwargs)+ return subprocess.CompletedProcess(command, 0, stdout="", stderr="")++ monkeypatch.setattr(clipboard.subprocess, "run", _run)+ clipboard_text = "sensitive multiline text"++ assert clipboard._run_command(["pbcopy"], clipboard_text) is True+ assert captured["command"] == ["pbcopy"]+ assert captured["input"] == clipboard_text+ assert clipboard_text not in captured["command"]diff --git a/tests/unit/ui/web/test_output_status_parity.py b/tests/unit/ui/web/test_output_status_parity.pynew file mode 100644index 0000000000..82e4488d9d--- /dev/null+++ b/tests/unit/ui/web/test_output_status_parity.py@@ -0,0 +1,26 @@+"""Parity guard for the Outputs status vocabulary across Python and TypeScript."""++from __future__ import annotations++import re+from pathlib import Path+from typing import get_args++from jarvis.ui.web.outputs_routes import OUTPUT_STATUSES, OutputStatus+++def test_output_status_python_and_typescript_vocabularies_match() -> None:+ repo_root = Path(__file__).resolve().parents[4]+ hook_source = (+ repo_root / "jarvis/ui/web/frontend/src/hooks/useOutputs.ts"+ ).read_text(encoding="utf-8")+ match = re.search(+ r"export const OUTPUT_STATUSES = \[(?P<body>.*?)\] as const;",+ hook_source,+ flags=re.DOTALL,+ )+ assert match is not None, "TypeScript OUTPUT_STATUSES constant is missing"+ ts_statuses = tuple(re.findall(r'"([a-z_]+)"', match.group("body")))++ assert set(get_args(OutputStatus)) == set(OUTPUT_STATUSES)+ assert ts_statuses == OUTPUT_STATUSESdiff --git a/tests/unit/ui/web/test_outputs_routes.py b/tests/unit/ui/web/test_outputs_routes.pyindex d852d46120..1126d02500 100644--- a/tests/unit/ui/web/test_outputs_routes.py+++ b/tests/unit/ui/web/test_outputs_routes.py@@ -18,6 +18,7 @@ design).from __future__ import annotations+import jsonimport timefrom collections.abc import AsyncIteratorfrom pathlib import Path@@ -162,8 +163,6 @@ async def _insert_dispatch_event(the parent→child edge lives only in the dispatch event payload (the``missions`` header has no parent column)."""- import json-payload = json.dumps({"event_type": "MissionDispatched",@@ -179,6 +178,20 @@ async def _insert_dispatch_event()+async def _insert_terminal_event(+ conn: aiosqlite.Connection,+ *,+ mission_id: str,+ event_type: str,+ payload: dict[str, object],+) -> None:+ await conn.execute(+ "INSERT INTO mission_events (mission_id, event_type, payload_json) "+ "VALUES (?, ?, ?)",+ (mission_id, event_type, json.dumps(payload)),+ )++# --- _parse_slug + _mission_id_prefix_for_dir unit tests ---------------------@@ -282,6 +295,161 @@ async def test_list_outputs_mission_dir_failed_state(r = client.get("/api/outputs")sessions = r.json()["sessions"]assert sessions[0]["status"] == "error"+ assert sessions[0]["has_partial_output"] is False+ assert sessions[0]["needs_review"] is False+ assert sessions[0]["artifact_count"] == 0+++async def test_failed_mission_with_deliverable_is_exposed_as_reviewable_partial(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ """A retained file is not approval, but it is not a content-free error."""+ mission_id = "019e3600-c100-7000-8000-000000000103"+ mission_dir = _make_mission_dir(tmp_path, mission_id)+ _seed(+ mission_dir / "tasks/task-1/artifacts/files/report.html",+ "<!doctype html><html><body>Report</body></html>",+ )+ await _insert_mission(db_conn, mission_id=mission_id, state="FAILED")+ await _insert_terminal_event(+ db_conn,+ mission_id=mission_id,+ event_type="MissionFailed",+ payload={"reason": "critic_loop_exhausted"},+ )++ with TestClient(app) as client:+ response = client.get("/api/outputs")++ assert response.status_code == 200+ session = response.json()["sessions"][0]+ assert session["status"] == "error"+ assert session["terminal_event"] == "MissionFailed"+ assert session["terminal_reason"] == "critic_loop_exhausted"+ assert session["error"] == "critic_loop_exhausted"+ assert session["artifact_count"] == 1+ assert session["has_partial_output"] is True+ assert session["needs_review"] is True+++async def test_execution_failure_with_retained_file_stays_failed(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ """A leftover file does not soften a worker crash into a review outcome."""+ mission_id = "019e3600-c150-7000-8000-000000000153"+ mission_dir = _make_mission_dir(tmp_path, mission_id)+ _seed(mission_dir / "tasks/task-1/artifacts/files/partial.html", "partial")+ await _insert_mission(db_conn, mission_id=mission_id, state="FAILED")+ await _insert_terminal_event(+ db_conn,+ mission_id=mission_id,+ event_type="MissionFailed",+ payload={"reason": "task_error"},+ )++ with TestClient(app) as client:+ response = client.get("/api/outputs")++ session = response.json()["sessions"][0]+ assert session["status"] == "error"+ assert session["has_partial_output"] is True+ assert session["needs_review"] is False+++async def test_explicit_critic_rejection_with_retained_file_stays_failed(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ """An explicit rejection is a real terminal decision, not review exhaustion."""+ mission_id = "019e3600-c175-7000-8000-000000000173"+ mission_dir = _make_mission_dir(tmp_path, mission_id)+ _seed(mission_dir / "tasks/task-1/artifacts/files/rejected.html", "partial")+ await _insert_mission(db_conn, mission_id=mission_id, state="FAILED")+ await _insert_terminal_event(+ db_conn,+ mission_id=mission_id,+ event_type="MissionFailed",+ payload={"reason": "critic_rejected"},+ )++ with TestClient(app) as client:+ response = client.get("/api/outputs")++ session = response.json()["sessions"][0]+ assert session["status"] == "error"+ assert session["terminal_reason"] == "critic_rejected"+ assert session["has_partial_output"] is True+ assert session["needs_review"] is False+++async def test_approved_mission_exposes_signed_summary_without_partial_flag(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ mission_id = "019e3600-c200-7000-8000-000000000203"+ mission_dir = _make_mission_dir(tmp_path, mission_id)+ _seed(mission_dir / "tasks/task-1/artifacts/files/report.md", "# Complete")+ await _insert_mission(db_conn, mission_id=mission_id, state="APPROVED")+ await _insert_terminal_event(+ db_conn,+ mission_id=mission_id,+ event_type="MissionApproved",+ payload={+ "summary_en": "The report was approved.",+ "summary_de": "Der Bericht wurde freigegeben.", # i18n-allow: fixture+ },+ )++ with TestClient(app) as client:+ response = client.get("/api/outputs")++ session = response.json()["sessions"][0]+ assert session["status"] == "success"+ assert session["summary"] == "Der Bericht wurde freigegeben." # i18n-allow: fixture+ assert session["artifact_count"] == 1+ assert session["has_partial_output"] is False+ assert session["needs_review"] is False+ assert session["error"] is None+++async def test_terminal_state_transition_reason_is_a_legacy_fallback(+ app: FastAPI, tmp_path: Path, db_conn: aiosqlite.Connection+) -> None:+ mission_id = "019e3600-c300-7000-8000-000000000303"+ _make_mission_dir(tmp_path, mission_id)+ await _insert_mission(db_conn, mission_id=mission_id, state="CANCELLED")+ await _insert_terminal_event(+ db_conn,+ mission_id=mission_id,+ event_type="MissionStateChanged",+ payload={"to_state": "CANCELLED", "reason": "app_shutdown"},+ )++ with TestClient(app) as client:+ response = client.get("/api/outputs")++ session = response.json()["sessions"][0]+ assert session["status"] == "cancelled"+ assert session["terminal_event"] == "MissionStateChanged"+ assert session["terminal_reason"] == "app_shutdown"+ assert session["error"] is None+++def test_outputs_openapi_exposes_typed_status_and_partial_fields(app: FastAPI) -> None:+ schema = app.openapi()["components"]["schemas"]["OutputSummary"]+ status_schema = schema["properties"]["status"]+ assert status_schema["enum"] == [+ "running",+ "success",+ "error",+ "cancelled",+ "unknown",+ ]+ assert schema["properties"]["has_partial_output"]["type"] == "boolean"+ assert schema["properties"]["needs_review"]["type"] == "boolean"@pytest.mark.asyncio