Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
feat(harness): add agent-free scheduled command tasks (#1149)
Qi Qicde33c9d5eab
diff --git a/core/agent_tool_policy.py b/core/agent_tool_policy.pyindex 23b0d3767..d8b8d7f80 100644--- a/core/agent_tool_policy.py+++ b/core/agent_tool_policy.py@@ -110,6 +110,7 @@ def _check_schedule_wakeup(tool_input: Dict[str, Any]) -> ToolPolicyDecision:"Use the durable Harness instead:\n"" vibe task add --at <ISO-8601> --message ... (one-shot)\n"' vibe task add --cron "<expr>" --message ... (recurring)\n'+ ' vibe task add --cron "<expr>" --shell "<cmd>" (command, no Agent turn)\n'"If you are waiting on an external signal rather than a clock, use ""`vibe watch add` instead.\n"f"{_HARNESS_HINT}"@@ -124,6 +125,7 @@ def _check_cron_create(tool_input: Dict[str, Any]) -> ToolPolicyDecision:"the agent process exits.\n""Use the durable Harness instead:\n"' vibe task add --cron "<expr>" --message ...\n'+ ' vibe task add --cron "<expr>" --shell "<cmd>" (command, no Agent turn)\n'f"{_HARNESS_HINT}")diff --git a/core/command_runner.py b/core/command_runner.pynew file mode 100644index 000000000..d67232a35--- /dev/null+++ b/core/command_runner.py@@ -0,0 +1,411 @@+"""Shared supervised-command runner.++One place owns the mechanics of running a user command through the stable+``core.watch_worker`` supervisor: spawn, spec handshake, timeout, cancellation,+and tree teardown. Callers own policy -- registries, localization, persistence+and result interpretation -- so this module stays a leaf with no knowledge of+watches, scheduled tasks, storage or the service layer.+"""++from __future__ import annotations++import asyncio+import logging+import os+import shlex+import signal+import sys+from collections import deque+from dataclasses import dataclass+from pathlib import Path+from typing import Callable, Optional++from core import watch_worker+from core.process_isolation import (+ DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,+ KILL_SIGNAL,+ PersistedProcessIdentity,+ capture_spawned_process_identity,+ isolated_subprocess_kwargs,+ new_process_identity_marker,+ process_identity_subprocess_env,+ signal_process_tree,+ terminate_and_communicate,+)++logger = logging.getLogger(__name__)++TIMEOUT_EXIT_CODE = 124+_READ_CHUNK_BYTES = 64 * 1024++#: What a capped stream puts where its dropped middle was. Plain ASCII on purpose: this+#: module is a leaf with no localization, and the marker is part of the captured bytes+#: rather than user-facing chrome. Its own length is charged to the cap, so the returned+#: output never exceeds ``max_output_bytes``.+STREAM_TRUNCATION_MARKER = b"[avibe: output truncated]\n"++#: One line is all any surface gives a command, so the cap is shared rather than+#: repeated: an uncapped ``bash -lc`` pipeline would bury the error text that follows+#: it in a failure notice, and wrap the row in ``vibe task list``.+COMMAND_PREVIEW_MAX_CHARS = 120+++def command_line_preview(+ shell_command: Optional[str],+ argv: Optional[list[str]],+ *,+ max_chars: int = COMMAND_PREVIEW_MAX_CHARS,+) -> str:+ """The one-line form of a command, or ``""`` when there is none.++ Lives beside the runner because every surface that names a command has to name the+ SAME string: ``vibe task list``, ``vibe watch list``, a failure notice, and an Agent+ escalation prompt were three separate copies of this, and a user comparing the+ notice against the list had no guarantee they were reading one command.++ ``shell_command`` wins when present -- it is the string the user typed -- and an+ argv is re-quoted with ``shlex.join`` so the preview is something they could paste.+ """++ preview = (shell_command or (shlex.join(argv) if argv else "")).strip()+ if len(preview) <= max_chars:+ return preview+ return preview[: max_chars - 1].rstrip() + "…"+++@dataclass(frozen=True)+class SupervisedCommandResult:+ """The outcome of one supervised command run.++ ``stdout``/``stderr`` are decoded with ``errors="replace"`` and returned+ verbatim: not stripped, not localized. Callers decide what to do with them.+ """++ exit_code: int+ stdout: str+ stderr: str+ timed_out: bool+ stdout_truncated: bool = False+ stderr_truncated: bool = False+++class SupervisedCommandStartupError(RuntimeError):+ """The worker exited or broke the pipe while receiving its spec.++ ``detail`` is the raw decoded+stripped stderr (may be empty).+ """++ def __init__(self, detail: str) -> None:+ super().__init__(detail or "supervised command worker exited during startup")+ self.detail = detail+++async def _read_capped_stream(stream: object, max_bytes: int) -> tuple[bytes, bool]:+ """Drain ``stream`` to EOF, retaining a bounded HEAD *and* TAIL of it.++ Draining must continue past the cap: a reader that stops consuming would+ block the child once the pipe buffer fills, and the run would look like a+ timeout instead of a large output.++ Both ends are kept because both ends are read. The head holds the first error a+ build or migration printed; the tail holds the sentence that explains the exit+ status, and the tail is what every failure surface actually shows -- the notice+ and the CLI list report the LAST non-empty line of stderr. A head-only cap made+ that read a confident lie: it named the last line of the first ``max_bytes`` and+ silently dropped the real ending, on exactly the runs whose ending matters.++ The budget is split evenly between the ends, with ``STREAM_TRUNCATION_MARKER``+ charged to it, so the retained bytes never exceed ``max_bytes``. Both ends are+ moved to a line boundary -- the head back to its last newline, the tail forward+ past its first -- so no half line survives to be mistaken for a line the command+ printed, which is the same mistake a head-only cap made one level up. A+ ``max_bytes`` too small to hold the marker degrades to a head-only cap rather+ than returning nothing but chrome.+ """++ if stream is None:+ return b"", False+ # One extra byte for the newline a head with no line boundary of its own needs+ # before the marker.+ budget = max_bytes - len(STREAM_TRUNCATION_MARKER) - 1+ head_max = max(budget // 2, 0)+ tail_max = budget - head_max if budget > 0 else 0+ if tail_max <= 0:+ head_max = max_bytes+ head: list[bytes] = []+ head_bytes = 0+ # Rolling window over the end of the stream: every chunk that did not fit the head+ # enters here and the oldest bytes are dropped, so the last ``tail_max`` bytes seen+ # are always the ones being held.+ tail: deque[bytes] = deque()+ tail_bytes = 0+ total_bytes = 0+ while True:+ chunk = await stream.read(_READ_CHUNK_BYTES) # type: ignore[attr-defined]+ if not chunk:+ break+ total_bytes += len(chunk)+ if head_bytes < head_max:+ take = min(head_max - head_bytes, len(chunk))+ head.append(chunk[:take])+ head_bytes += take+ chunk = chunk[take:]+ if not chunk:+ continue+ if tail_max <= 0:+ continue+ tail.append(chunk)+ tail_bytes += len(chunk)+ while tail_bytes > tail_max:+ oldest = tail.popleft()+ drop = min(len(oldest), tail_bytes - tail_max)+ if drop < len(oldest):+ tail.appendleft(oldest[drop:])+ tail_bytes -= drop+ if tail_max <= 0:+ # No room for a marked tail: a head-only cap, and no marker either, because the+ # cap is a hard cap and the marker would be most of what fits.+ return b"".join(head), total_bytes > head_bytes+ if total_bytes <= head_bytes + tail_bytes:+ return b"".join(head) + b"".join(tail), False+ retained_head = b"".join(head)+ boundary = retained_head.rfind(b"\n")+ if boundary != -1:+ retained_head = retained_head[: boundary + 1]+ elif retained_head:+ retained_head += b"\n"+ retained_tail = b"".join(tail)+ boundary = retained_tail.find(b"\n")+ if boundary != -1:+ retained_tail = retained_tail[boundary + 1 :]+ return retained_head + STREAM_TRUNCATION_MARKER + retained_tail, True+++async def _cancel_readers(tasks: list[asyncio.Task]) -> None:+ for task in tasks:+ task.cancel()+ if tasks:+ await asyncio.gather(*tasks, return_exceptions=True)+ tasks.clear()+++async def _timed_out_keeping_retained_output(+ process: asyncio.subprocess.Process,+ collector: "asyncio.Future[tuple[bytes, bytes, bool, bool]]",+ label: str,+) -> SupervisedCommandResult:+ """End a timed-out capped run, keeping what its readers already retained.++ ``terminate_and_communicate`` must NOT be used here: its ``communicate()``+ would be a SECOND consumer on the streams ``_read_capped_stream`` is already+ awaiting. Signalling the tree closes the pipes instead, so the readers reach+ EOF on their own and the collector returns everything it kept -- which is the+ point. Cancelling the readers, as this path used to, threw those buffers away+ and left a hung command reporting no output at all, the one failure mode with+ no exit status to explain itself.++ The collector is shielded so the grace period cannot cancel it: after+ ``KILL_SIGNAL`` we still want the bytes it is holding.+ """++ if process.returncode is None:+ signal_process_tree(process, signal.SIGTERM, logger, label)+ try:+ stdout, stderr, stdout_truncated, stderr_truncated = await asyncio.wait_for(+ asyncio.shield(collector),+ timeout=DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,+ )+ except asyncio.TimeoutError:+ signal_process_tree(process, KILL_SIGNAL, logger, label)+ stdout, stderr, stdout_truncated, stderr_truncated = await collector+ return SupervisedCommandResult(+ exit_code=TIMEOUT_EXIT_CODE,+ stdout=stdout.decode("utf-8", errors="replace"),+ stderr=stderr.decode("utf-8", errors="replace"),+ timed_out=True,+ stdout_truncated=stdout_truncated,+ stderr_truncated=stderr_truncated,+ )+++async def _reap_or_kill(process: asyncio.subprocess.Process, label: str) -> tuple[bytes, bytes]:+ """Reap the tree, and kill it anyway if the orderly teardown itself fails.++ ``terminate_and_communicate`` is the ORDERLY form: signal, then drain the pipes so+ the caller can still report what the command managed to say. It can also fail --+ an ``OSError`` draining a pipe, a ``RuntimeError`` from a loop already closing, a+ re-delivered ``CancelledError`` while a service stop unwinds -- and every caller+ below is itself an ``except`` clause, so an exception raised out of one is NOT+ caught by the catch-all clause beside it. It leaves this frame carrying a live+ supervisor whose only durable name the scheduled-task caller then clears in its own+ ``finally`` (``_execute_command_task``), on the documented assumption that the+ runner has already reaped the tree: a backup or deployment still running, that+ nothing can ever find again.++ So the tree dies here whatever the drain does. ``signal_process_tree`` is+ SYNCHRONOUS and takes the process group first, which is what makes it usable as the+ fallback: it needs no await, so there is nothing left for a cancellation to+ interrupt, in the very frames where a cancellation is what brought us here. The+ retained output is lost in that case; the orphan is not.++ An ordinary failure is swallowed, because each caller already has the outcome it+ means to report -- the cancellation it re-raises, or the timeout it returns -- and a+ teardown that could not finish must not replace it. A ``BaseException`` propagates+ once the kill is done, because a cancellation or a ``KeyboardInterrupt`` is not this+ frame's to discard.+ """++ try:+ return await terminate_and_communicate(process, logger, label)+ except BaseException as exc:+ if process.returncode is None:+ signal_process_tree(process, KILL_SIGNAL, logger, label)+ if not isinstance(exc, Exception):+ raise+ logger.debug("failed to drain %s while tearing it down", label, exc_info=True)+ return b"", b""+++async def run_supervised_command(+ *,+ command: Optional[list[str]] = None,+ shell_command: Optional[str] = None,+ cwd: str,+ timeout_seconds: float,+ label: str,+ on_spawn: Optional[Callable[[int, Optional[PersistedProcessIdentity]], None]] = None,+ max_output_bytes: Optional[int] = None,+) -> SupervisedCommandResult:+ """Run one command under the stable supervisor and return its outcome.++ ``timeout_seconds <= 0`` means no timeout. ``max_output_bytes`` of ``None``+ keeps exact ``communicate()`` semantics; a value caps the retained bytes per+ stream while still draining the child to EOF.+ """++ worker_marker = new_process_identity_marker()+ spawn_env = process_identity_subprocess_env(worker_marker)+ process = await asyncio.create_subprocess_exec(+ os.path.abspath(sys.executable),+ os.fspath(Path(watch_worker.__file__).resolve()),+ cwd=cwd,+ env=spawn_env,+ stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE,+ stderr=asyncio.subprocess.PIPE,+ **isolated_subprocess_kwargs(),+ )+ identity = capture_spawned_process_identity(process.pid, worker_marker)++ reader_tasks: list[asyncio.Task] = []+ try:+ if on_spawn is not None:+ # INSIDE the protected block, because the callback is allowed to REFUSE:+ # the scheduled-task lane will not run a command whose worker it could not+ # durably name, and a callback that raises must reap the tree like every+ # other failure here rather than leaking the very orphan it is protecting+ # against. Still before the spec is written, so the supervisor is blocked+ # on stdin and nothing the user asked for has started yet.+ on_spawn(process.pid, identity)+ if process.stdin is None:+ await terminate_and_communicate(process, logger, label)+ raise RuntimeError("watch worker supervisor stdin is unavailable")+ try:+ process.stdin.write(+ watch_worker.encode_watch_worker_spec(+ command=list(command or []),+ shell_command=shell_command,+ )+ )+ await process.stdin.drain()+ except (BrokenPipeError, ConnectionResetError):+ _startup_stdout, startup_stderr = await process.communicate()+ raise SupervisedCommandStartupError(+ startup_stderr.decode("utf-8", errors="replace").strip()+ ) from None+ finally:+ process.stdin.close()+ if max_output_bytes is None:+ if timeout_seconds > 0:+ stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_seconds)+ else:+ stdout, stderr = await process.communicate()+ stdout_truncated = False+ stderr_truncated = False+ else:++ async def _collect() -> tuple[bytes, bytes, bool, bool]:+ stdout_task = asyncio.ensure_future(_read_capped_stream(process.stdout, max_output_bytes))+ stderr_task = asyncio.ensure_future(_read_capped_stream(process.stderr, max_output_bytes))+ reader_tasks.extend((stdout_task, stderr_task))+ (out_bytes, out_truncated), (err_bytes, err_truncated) = await asyncio.gather(+ stdout_task,+ stderr_task,+ )+ await process.wait()+ return out_bytes, err_bytes, out_truncated, err_truncated++ if timeout_seconds > 0:+ # ``asyncio.wait`` rather than ``wait_for``: a timeout must NOT cancel+ # the collector, because its readers are holding the retained output+ # this run still owes the user. ``_timed_out_keeping_retained_output``+ # ends it by closing the pipes instead.+ collector = asyncio.ensure_future(_collect())+ done, _still_running = await asyncio.wait(+ {collector}, timeout=timeout_seconds+ )+ if not done:+ return await _timed_out_keeping_retained_output(+ process, collector, label+ )+ stdout, stderr, stdout_truncated, stderr_truncated = await collector+ else:+ stdout, stderr, stdout_truncated, stderr_truncated = await _collect()+ except asyncio.CancelledError:+ await _cancel_readers(reader_tasks)+ await _reap_or_kill(process, label)+ raise+ except asyncio.TimeoutError:+ await _cancel_readers(reader_tasks)+ stdout, stderr = await _reap_or_kill(process, label)+ return SupervisedCommandResult(+ exit_code=TIMEOUT_EXIT_CODE,+ stdout="",+ stderr=stderr.decode("utf-8", errors="replace"),+ timed_out=True,+ )+ except BaseException:+ # EVERY OTHER WAY OUT OF THIS BLOCK, because the two above are not the only+ # ones: an ``OSError`` draining a capped pipe, one reader dying while its twin+ # still runs, a ``KeyboardInterrupt`` between the spawn and the collector. The+ # supervisor and the command under it are still running, and ``on_spawn`` has+ # already handed the caller the only durable record of them -- which the+ # scheduled-task caller clears in its own ``finally`` the moment this raises,+ # on the documented assumption that "by the time control is here the runner has+ # reaped the tree". Leaving without reaping breaks that assumption and orphans+ # a live process tree that nothing can ever name again, so the tree does not+ # outlive this frame even on a failure nobody predicted.+ await _cancel_readers(reader_tasks)+ if process.returncode is None:+ # Skipped when the supervisor is already collected -- the stdin-handshake+ # paths above ``communicate()`` first, and a second consumer on those+ # streams is exactly what ``_timed_out_keeping_retained_output`` warns of.+ try:+ await _reap_or_kill(process, label)+ except BaseException:+ # The original failure is the one worth propagating; a teardown that+ # cannot complete must not replace it. The tree is already dead by+ # here -- ``_reap_or_kill`` kills before it re-raises.+ logger.debug(+ "failed to reap %s after an unexpected runner error", label, exc_info=True+ )+ raise++ return SupervisedCommandResult(+ exit_code=process.returncode if process.returncode is not None else 0,+ stdout=stdout.decode("utf-8", errors="replace"),+ stderr=stderr.decode("utf-8", errors="replace"),+ timed_out=False,+ stdout_truncated=stdout_truncated,+ stderr_truncated=stderr_truncated,+ )diff --git a/core/process_isolation.py b/core/process_isolation.pyindex fa067678f..16fc2bd6e 100644--- a/core/process_isolation.py+++ b/core/process_isolation.py@@ -13,7 +13,7 @@ import signalimport subprocessimport timefrom dataclasses import dataclass-from typing import Any+from typing import Any, Literalimport psutil@@ -21,6 +21,21 @@ KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)PROCESS_IDENTITY_ENV = "AVIBE_PROCESS_IDENTITY"DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS = 3.0+#: What a liveness probe could actually establish about a pid: a process is there,+#: nothing is there, or this pass could not tell. Only the middle answer means a+#: durable handle on that process has stopped being worth keeping.+ProcessLivenessStatus = Literal["alive", "gone", "unknown"]++#: What a recovery reap established about a managed tree: this pass stopped it, it+#: was already gone, or neither could be shown. Only the last one keeps the record.+ProcessReapOutcome = Literal["reaped", "gone", "unconfirmed"]++#: What a LOOK established about a managed tree, with nothing signalled: something of+#: it is still there, it is provably gone, or this pass could not tell. A caller+#: deciding whether it may start a second copy of that work must treat the last two+#: differently -- only "gone" is permission.+ProcessTreePresence = Literal["present", "gone", "unknown"]+@dataclass(frozen=True)class ProcessIdentity:@@ -70,6 +85,61 @@ def capture_spawned_process_identity()+def serialize_process_identity(identity: PersistedProcessIdentity) -> dict[str, Any]:+ """The JSON form of a captured identity, for any store that persists one."""++ return {+ "pid": identity.pid,+ "create_time": identity.create_time,+ "worker_fingerprint": identity.worker_fingerprint,+ }+++def _valid_worker_fingerprint(value: Any) -> bool:+ if not isinstance(value, str) or not value.startswith("sha256:") or len(value) != 71:+ return False+ return all(char in "0123456789abcdef" for char in value[7:])+++def process_identity_from_payload(+ payload: Any,+ pid: int,+) -> PersistedProcessIdentity | None:+ """Rebuild a persisted identity, or ``None`` if the payload cannot be trusted.++ Deliberately strict, because the ONLY consumer of the result is a kill: a+ payload that has been truncated, hand-edited, or written by an older format+ must produce ``None`` (leave the process alone) rather than a plausible-looking+ identity that authorises signalling some unrelated pid.+ """++ if not isinstance(payload, dict):+ return None+ identity_pid = payload.get("pid")+ create_time = payload.get("create_time")+ worker_fingerprint = payload.get("worker_fingerprint")+ try:+ normalized_create_time = float(create_time)+ except (TypeError, ValueError, OverflowError):+ return None+ if (+ not isinstance(identity_pid, int)+ or isinstance(identity_pid, bool)+ or identity_pid != pid+ or not isinstance(create_time, (int, float))+ or isinstance(create_time, bool)+ or not math.isfinite(normalized_create_time)+ or normalized_create_time <= 0+ or not _valid_worker_fingerprint(worker_fingerprint)+ ):+ return None+ return PersistedProcessIdentity(+ pid=identity_pid,+ create_time=normalized_create_time,+ worker_fingerprint=worker_fingerprint,+ )++def process_identity_matches(expected: PersistedProcessIdentity,live: ProcessIdentity,@@ -113,6 +183,35 @@ def inspect_process_identity(pid: int) -> ProcessIdentity | None:return identity+def probe_process_liveness(pid: int) -> ProcessLivenessStatus:+ """Say whether a pid is occupied, free, or unanswerable right now.++ ``inspect_process_identity`` collapses the third answer into ``None``, and for+ its own callers that is correct: they are deciding whether they may still+ *steer* a process, and a pid they cannot read is one they must not signal+ either way. A caller deciding whether to DISCARD the only durable handle on+ that process needs the answers apart. "Gone" retires the record because there+ is nothing left to kill; "unanswerable" -- an exhausted fd table, a+ ``/proc`` read losing a race, a platform refusing ``create_time`` -- says+ only that this pass could not look, and throwing the record away then makes a+ still-running backup unkillable by every pass after it too.++ Mirrors ``process_group_identity_status``: the same three-way verdict, at the+ granularity of a single pid rather than a group.+ """++ if not isinstance(pid, int) or isinstance(pid, bool) or pid <= 0:+ # Not a pid at all, so there is no process to preserve a handle for.+ return "gone"+ try:+ _open_process_identity(pid)+ except (psutil.NoSuchProcess, ProcessLookupError):+ return "gone"+ except (psutil.Error, OSError, ValueError):+ return "unknown"+ return "alive"++def isolated_subprocess_kwargs() -> dict[str, Any]:"""Return subprocess kwargs that put a child outside this process group."""if os.name == "nt":@@ -564,6 +663,139 @@ def terminate_process_tree_by_pid(return False+def orphaned_process_tree_presence(+ logger: logging.Logger,+ label: str,+ *,+ expected_identity: PersistedProcessIdentity,+) -> ProcessTreePresence:+ """Answer whether a recorded tree is still out there, WITHOUT signalling it.++ The read-only twin of ``reap_orphaned_process_tree``, asking the same question+ along the same two paths -- the leader by identity, then the group it leads -- for+ a caller with the opposite intent. The reap wants to stop a survivor; this wants+ to know whether starting a *second* copy of that work would collide with one, and+ a probe that killed the first copy to answer would be no answer at all.++ The three verdicts are not two. ``present`` and ``unknown`` both forbid a second+ copy, but for different reasons and with different remedies -- one is a running+ process, the other is a pass that could not look -- and only ``gone`` is proof+ that the recorded tree has stopped, which is what lets a caller both proceed and+ retire the record.+ """++ if not isinstance(expected_identity, PersistedProcessIdentity):+ # Nothing trustworthy was recorded, so there is no tree this can vouch for.+ return "gone"+ pid = expected_identity.pid+ liveness = probe_process_liveness(pid)+ if liveness == "unknown":+ return "unknown"+ if liveness == "alive":+ live_identity = inspect_process_identity(pid)+ if live_identity is None:+ # Occupied, but unreadable: cannot show it is ours, cannot show it is not.+ return "unknown"+ if process_identity_matches(expected_identity, live_identity):+ return "present"+ # A stranger holds the recycled number. Our leader has exited -- which, as the+ # reap's own comment says, only starts the question: the group may live on.++ if not process_group_exists(pid, logger, label):+ return "gone"+ status = process_group_identity_status(pid, expected_identity, logger, label)+ if status == "match":+ return "present"+ if status == "mismatch":+ # Members, every one of them another tree's: this pgid was recycled too.+ return "gone"+ return "unknown"+++def reap_orphaned_process_tree(+ logger: logging.Logger,+ label: str,+ *,+ expected_identity: PersistedProcessIdentity,+) -> ProcessReapOutcome:+ """Kill whatever is left of a managed tree whose owner died, by identity.++ Recovery asks one question -- "may I stop tracking this process now?" -- and it+ has three answers, not two. ``gone`` and ``reaped`` retire the durable record+ that names the tree; ``unconfirmed`` must keep it, because the record is+ typically the only place the identity is written and discarding it makes the+ survivor unfindable by every later pass, not just this one.++ THE LEADER IS NOT THE TREE. A supervisor spawned with ``start_new_session``+ leads the group ``pgid == pid``, and on POSIX that group outlives it: if the+ supervisor is killed (an OOM kill, a crash in its own code) while the backup or+ migration under it keeps running, the pid is free while the work continues in a+ group nothing else names. So an empty pid only starts the question -- the group+ is checked next, and only a group with no members, or one whose members carry+ another tree's marker, means our tree is really gone.++ Identity throughout, never a bare pid or pgid: ``terminate_process_tree_by_pid``+ re-reads the leader's start time and ``AVIBE_PROCESS_IDENTITY`` marker, and+ ``terminate_process_group_by_pgid`` requires a surviving member to carry that+ marker, so a recycled number cannot make this signal a stranger's process.+ """++ if not isinstance(expected_identity, PersistedProcessIdentity):+ return "gone"+ pid = expected_identity.pid+ liveness = probe_process_liveness(pid)+ if liveness == "unknown":+ # The probe could not read the process table; that says nothing about the+ # process, so it cannot be the reason a handle on it is dropped.+ return "unconfirmed"+ if liveness == "alive":+ try:+ if terminate_process_tree_by_pid(+ pid,+ logger,+ label,+ expected_identity=expected_identity,+ ):+ return "reaped"+ except Exception:+ logger.exception("Unexpected error terminating %s pid=%s", label, pid)+ if probe_process_liveness(pid) != "gone":+ return "unconfirmed"+ # The leader went away without confirming; its children may not have.++ if not process_group_exists(pid, logger, label):+ return "gone"+ status = process_group_identity_status(pid, expected_identity, logger, label)+ if status == "mismatch":+ # Members, but every one of them carries some other tree's marker: this pgid+ # was recycled and ours has exited.+ return "gone"+ if status != "match":+ logger.warning(+ "Could not verify what still occupies %s process group pgid=%s; leaving it "+ "tracked for a later pass",+ label,+ pid,+ )+ return "unconfirmed"+ logger.warning(+ "Reaping %s process group pgid=%s after its leader exited",+ label,+ pid,+ )+ try:+ if terminate_process_group_by_pgid(+ pid,+ logger,+ label,+ expected_identity=expected_identity,+ ):+ return "reaped"+ except Exception:+ logger.exception("Unexpected error terminating %s process group pgid=%s", label, pid)+ return "unconfirmed"++async def terminate_process_tree(process: Any,logger: logging.Logger,diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.pyindex 4be29e76f..825b2dbed 100644--- a/core/scheduled_tasks.py+++ b/core/scheduled_tasks.py@@ -11,7 +11,7 @@ import timefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom pathlib import Path-from types import MappingProxyType+from types import MappingProxyType, SimpleNamespacefrom typing import Any, Dict, Mapping, NamedTuple, Optional, Sequencefrom uuid import uuid4from zoneinfo import ZoneInfo@@ -61,13 +61,30 @@ from storage.agent_session_rows import (from storage.db import create_sqlite_engine, get_cached_sqlite_enginefrom core import failure_noticesfrom core.backend_failure import emit_replayed_backend_failure+from core.command_runner import (+ SupervisedCommandStartupError,+ command_line_preview,+ run_supervised_command,+)from core.delivery_evidence import (ACK_EVIDENCE_DELIVERY_ONLY,ACK_EVIDENCE_RECEIPT,STAGE_PERSIST,DeliveryEvidence,)+from core.process_isolation import (+ PersistedProcessIdentity,+ orphaned_process_tree_presence,+ process_identity_from_payload,+ reap_orphaned_process_tree,+ serialize_process_identity,+)+from core.watch_worker import decode_watch_worker_error, localize_worker_errorfrom storage.background import (+ COMMAND_SNAPSHOT_METADATA_KEY,+ COMMAND_TIMED_OUT_METADATA_KEY,+ COMMAND_WORKER_METADATA_KEY,+ COMMAND_WORKER_REAP_ATTEMPTS_KEY,DefinitionWriteConflict,DefinitionWriteExpectation,NOTICE_FAILED,@@ -134,6 +151,39 @@ def _adopt_delivery_evidence(target: DeliveryEvidence, source: DeliveryEvidence)target.error_stage = source.error_stage+#: How much of a failing command's stderr may ride the one-line error text. The full+#: stream is on the run row; this is only the hint the CLI list and the notice show.+_COMMAND_ERROR_DETAIL_MAX_CHARS = 200+++def _last_nonempty_line(text: Optional[str]) -> str:+ """The LAST non-empty stderr line, trimmed -- the usual place the cause is.++ A failing command's stderr commonly ends with the sentence that explains the+ failure (a traceback's exception line, a shell's "command not found"), while the+ first lines are warnings and progress noise.+ """++ for line in reversed((text or "").splitlines()):+ stripped = line.strip()+ if stripped:+ return stripped[:_COMMAND_ERROR_DETAIL_MAX_CHARS]+ return ""+++def _format_seconds(seconds: float) -> str:+ """A duration as the user wrote it: ``3600``, ``0.5``, ``1.9``.++ ``--timeout`` is a float, so ``int()`` was not rounding, it was DELETING the value+ for every sub-second limit: ``--timeout 0.5`` reported "timed out after 0+ second(s)", a sentence that describes an impossible event and hides the actual+ setting the user has to change.+ """++ value = float(seconds)+ return str(int(value)) if value.is_integer() else f"{value:g}"++def _json_loads(value: str | None, default: Any) -> Any:if not value:return default@@ -453,6 +503,17 @@ class TaskExecutionResult:failure_code: Optional[str] = Nonecomplete_on_return: bool = Truereconcile_delivery_on_return: bool = False+ #: Command-task outcome facts, all ``None`` for a message task. They ride the+ #: result rather than being written by the executor so the run row's terminal+ #: write stays a single guarded statement in ``complete()``.+ exit_code: Optional[int] = None+ stdout: Optional[str] = None+ stderr: Optional[str] = None+ #: The Agent turn a failed ``--on-failure agent`` command fire queued, already+ #: durable when this is set. It rides the run row's metadata so the settle that+ #: transitions the run also records that its failure has a REPORT, which is what+ #: suppresses the owed failure notice for the same failure.+ escalation_run_id: Optional[str] = None@dataclass(frozen=True)@@ -522,15 +583,84 @@ BINDING_FOLLOWS_SESSION_METADATA_KEY = "binding_follows_session"#: Each entry: ``{"session_id": str, "reason": str, "at": iso8601}``.ORPHANED_RESERVATIONS_METADATA_KEY = "orphaned_reservations"+#: Wall-clock ceiling applied to a command task that stored no ``timeout_seconds``.+#: Six hours: long enough that an ordinary batch job is never cut short, short+#: enough that a wedged child cannot hold a run row ``running`` forever. A stored+#: ``0`` is NOT this default -- it flows through the runner as "no timeout".+COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS = 21600.0++#: Retained bytes per output stream for one command run. The runner keeps draining+#: the child past the cap, so a chatty command is truncated in the run row rather+#: than deadlocked on a full pipe.+COMMAND_TASK_OUTPUT_CAP_BYTES = 64 * 1024++def command_snapshot(task: Any) -> Optional[dict[str, Any]]:+ """The ``{"shell", "argv"}`` record of what a command definition would run.++ A run row carried an exit code and output but never the command, so every reader+ -- the failure notice, ``vibe runs show``, the Workbench run detail -- had to go+ back to the definition for the copy. The definition is mutable and deletable, and+ the notice drain is asynchronous, so by the time a reader asked, the answer could+ be a command that never ran (the user rewrote it after the fire) or no answer at+ all (the user deleted the task). A run is an immutable record of one execution;+ what it executed belongs ON it.++ The SQLite backend stamps the same key from the authoritative definition row+ inside its enqueue transaction; this is the file backend's copy of that write.+ ``None`` for a definition that has no command, so a caller can merge the result+ unconditionally without stamping an empty key onto every Agent run's metadata.+ """++ if not getattr(task, "has_command", False):+ return None+ shell_command = getattr(task, "shell_command", None)+ argv = getattr(task, "command", None)+ return {+ "shell": shell_command or None,+ "argv": [str(part) for part in (argv or [])],+ }+++def command_snapshot_of_run(run: Any) -> Optional[SimpleNamespace]:+ """The snapshot a run carries, shaped like the definition readers already accept.++ Returns an object exposing ``has_command`` / ``shell_command`` / ``command`` so+ the preview helpers take it and a ``ScheduledTask`` through the same code path.+ ``None`` when the run predates the snapshot or is not a command run at all -- the+ callers fall back to the live definition there, which is the best (and, for those+ rows, the only) answer available.+ """++ if not isinstance(run, dict):+ return None+ metadata = run.get("metadata")+ if not isinstance(metadata, dict):+ return None+ snapshot = metadata.get(COMMAND_SNAPSHOT_METADATA_KEY)+ if not isinstance(snapshot, dict):+ return None+ shell_command = snapshot.get("shell")+ raw_argv = snapshot.get("argv")+ argv = [str(part) for part in raw_argv] if isinstance(raw_argv, (list, tuple)) else []+ shell_command = str(shell_command) if isinstance(shell_command, str) else None+ if not shell_command and not argv:+ return None+ return SimpleNamespace(+ has_command=True,+ shell_command=shell_command,+ command=argv,+ )+#: What a fire reports when its terminal stamp was REFUSED by the guarded-#: full-row write (HFR-261/HFR-264). Plain text, like every other value that-#: reaches ``last_error`` and the run ledger's ``error`` from this module (the-#: rebind/pause details right below, ``str(exc)``, the reclaim's pause reason), so-#: one outcome channel does not carry two different string conventions.-_TASK_RESULT_NOT_RECORDED_ERROR = (- "the result of this run could not be recorded: the task was reclaimed, "- "repointed or removed while it was running, so its stored state is unchanged"-)+#: full-row write (HFR-261/HFR-264). Translated, not plain text: this is a sentence+#: THIS MODULE composes for a user, and it lands in the run ledger's ``error`` --+#: the same column ``harness.command.timedOut`` / ``exited`` and the settlement+#: reasons in ``core/run_settlement.py`` already fill through ``vibe/i18n``, rendered+#: verbatim in the Harness detail pane, the CLI and the failure notice. The values+#: that stay untranslated on this channel are the ones nobody here wrote -- ``str(exc)``+#: from an arbitrary exception, a worker's own stderr -- so "one convention per+#: channel" is the wrong reading: the line is between OUR copy and QUOTED text.+_TASK_RESULT_NOT_RECORDED_I18N_KEY = "harness.task.resultNotRecorded"#: "No value was supplied", as distinct from "the supplied value is ``None``".#: A reclaim snapshot records a session's ``model`` / ``reasoning_effort`` as@@ -831,6 +961,38 @@ def _created_by_caller(task: Any, run_metadata: Any) -> Optional[dict[str, Any]]return caller if isinstance(caller, dict) else None+def _coerce_command_argv(value: Any) -> Optional[list[str]]:+ """An argv list of strings, or ``None`` for absent/empty/malformed input.++ ``[]`` collapses to ``None`` on purpose: an empty argv is not a command, and the+ storage layer must keep the column NULL so ``has_command`` stays False.+ """++ if not isinstance(value, list) or not value:+ return None+ if not all(isinstance(item, str) for item in value):+ return None+ return [str(item) for item in value]+++def _coerce_optional_float(value: Any) -> Optional[float]:+ if value is None:+ return None+ try:+ return float(value)+ except (TypeError, ValueError):+ return None+++def _coerce_optional_int(value: Any) -> Optional[int]:+ if value is None:+ return None+ try:+ return int(value)+ except (TypeError, ValueError):+ return None++@dataclassclass ScheduledTask:id: str@@ -853,6 +1015,29 @@ class ScheduledTask:last_run_at: Optional[str] = Nonelast_error: Optional[str] = Nonemetadata: dict[str, Any] = field(default_factory=dict)+ # Command tasks run a subprocess instead of messaging an Agent. All four stay+ # ``None`` for a message task, which is what keeps its stored columns NULL.+ shell_command: Optional[str] = None+ command: Optional[list[str]] = None+ timeout_seconds: Optional[float] = None+ last_exit_code: Optional[int] = None++ @property+ def has_command(self) -> bool:+ """Whether this definition runs a command rather than prompting an Agent."""++ return bool(self.shell_command or self.command)++ @property+ def on_failure(self) -> str:+ """What a failed command run should do; ``"none"`` when unset.++ Kept in ``metadata`` rather than a column: it is a command-task-only policy,+ and the CLI owns validating which values are accepted.+ """++ value = str((self.metadata or {}).get("on_failure") or "none").strip().lower()+ return value or "none"def to_dict(self) -> Dict[str, Any]:return asdict(self)@@ -880,6 +1065,10 @@ class ScheduledTask:last_run_at=payload.get("last_run_at"),last_error=payload.get("last_error"),metadata=payload.get("metadata") if isinstance(payload.get("metadata"), dict) else {},+ shell_command=(str(payload["shell_command"]) if payload.get("shell_command") else None),+ command=_coerce_command_argv(payload.get("command")),+ timeout_seconds=_coerce_optional_float(payload.get("timeout_seconds")),+ last_exit_code=_coerce_optional_int(payload.get("last_exit_code")),)@@ -1156,16 +1345,34 @@ class ScheduledTaskStore:metadata=task.metadata,)+ @property+ def sqlite_backend(self) -> Optional[SQLiteBackgroundTaskStore]:+ """The SQLite backend behind this store, or ``None`` for the file backend.++ The guard ``_write_task`` applies lives in SQLite; the file backend has no+ compare-and-set at all. Exposed so a caller can ask whether a guarded stamp and+ an outbox row can be committed together (HFR-269).+ """++ return self._sqlite+def _write_task(self,task: ScheduledTask,expect: DefinitionWriteExpectation,*,+ queued_run: Optional[dict[str, Any]] = None,+ expected_uncanceled_run_id: Optional[str] = None,expected_enabled_agent_id: Optional[str] = None,expected_reference_agent_id: Optional[str] = None,) -> bool:"""Persist a whole task row; ``False`` means the guard refused the write.+ ``queued_run`` is an ``agent_runs`` outbox payload this write AUTHORISES; it is+ committed in the SAME transaction as the row (HFR-269), so a refusal or a+ failure leaves neither behind. Only the SQLite backend can do that, and passing+ one to the file backend is a caller bug -- see ``sqlite_backend``.+On refusal the in-memory mirror is reloaded, so the store never keeps servingthe mutated task that the database rejected -- and on a RAISED write too(HFR-272, the watch store's twin). A rolled-back transaction and a refused one@@ -1177,14 +1384,33 @@ class ScheduledTaskStore:try:if self._sqlite is None:+ # The watch store's answer, replicated verbatim: REFUSE rather than+ # save-then-enqueue. A file-backed store cannot make the two writes one+ # decision at all, and a best-effort second write is exactly the+ # two-commits bug HFR-269 removed.+ if queued_run is not None:+ raise ValueError(+ "a file-backed scheduled task store cannot commit a queued run "+ "with the task row"+ )self._save()return True- landed = self._sqlite.upsert_scheduled_task(- task.to_dict(),- expect=expect,- expected_enabled_agent_id=expected_enabled_agent_id,- expected_reference_agent_id=expected_reference_agent_id,- )+ if queued_run is None:+ landed = self._sqlite.upsert_scheduled_task(+ task.to_dict(),+ expect=expect,+ expected_enabled_agent_id=expected_enabled_agent_id,+ expected_reference_agent_id=expected_reference_agent_id,+ )+ else:+ # No agent-guard kwargs: the only caller that passes a queued run is+ # ``mark_task_result``, which never passes them either.+ landed = self._sqlite.upsert_scheduled_task_with_queued_run(+ task.to_dict(),+ expect=expect,+ run_payload=queued_run,+ expected_uncanceled_run_id=expected_uncanceled_run_id,+ )except Exception:self._reload_after_lost_write(task.id)raise@@ -1270,6 +1496,9 @@ class ScheduledTaskStore:cron: Optional[str] = None,run_at: Optional[str] = None,timezone_name: str,+ shell_command: Optional[str] = None,+ command: Optional[list[str]] = None,+ timeout_seconds: Optional[float] = None,metadata: Optional[dict[str, Any]] = None,expected_enabled_agent_id: Optional[str] = None,expected_reference_agent_id: Optional[str] = None,@@ -1290,6 +1519,9 @@ class ScheduledTaskStore:run_at=run_at,timezone=timezone_name,metadata=dict(metadata or {}),+ shell_command=shell_command,+ command=command,+ timeout_seconds=timeout_seconds,)return self.upsert_task(task,@@ -1349,6 +1581,10 @@ class ScheduledTaskStore:session_policy: Optional[str] = None,cwd: Optional[str] = None,update_cwd: bool = False,+ shell_command: Optional[str] = None,+ command: Optional[list[str]] = None,+ timeout_seconds: Optional[float] = None,+ update_command_fields: bool = False,metadata: Optional[dict[str, Any]] = None,expected_enabled_agent_id: Optional[str] = None,expected_reference_agent_id: Optional[str] = None,@@ -1374,6 +1610,12 @@ class ScheduledTaskStore:task.cron = crontask.run_at = run_attask.timezone = timezone_name+ if update_command_fields:+ # Gated like ``cwd``: an edit that says nothing about the command must not+ # clear it, and ``last_exit_code`` is runtime state no edit ever rewrites.+ task.shell_command = shell_command+ task.command = command+ task.timeout_seconds = timeout_secondsif metadata is not None:task.metadata = dict(metadata)task.updated_at = _utc_now_iso()@@ -1485,7 +1727,30 @@ class ScheduledTaskStore:error: Optional[str],disable_one_shot: bool = True,expected_binding: Optional[tuple[Optional[str], str, str]] = None,+ exit_code: Optional[int] = None,+ records_command_outcome: bool = False,+ timed_out: bool = False,+ queued_run: Optional[dict[str, Any]] = None,+ expected_uncanceled_run_id: Optional[str] = None,) -> bool:+ """Stamp a fire's outcome; ``False`` means the store refused the write.++ ``queued_run`` is the outbox row this stamp AUTHORISES -- today the+ ``--on-failure agent`` escalation turn. Passing it makes the stamp and the turn+ ONE transaction (HFR-269): both land or neither does, so no teardown can commit+ between them and a failed one-shot ``at`` task cannot be disabled while losing+ the report that explains why.++ ``records_command_outcome`` marks the ONE stamp that is a command fire's own+ result, and it is what makes ``exit_code`` authoritative in both directions --+ see the write below.++ ``expected_uncanceled_run_id`` re-asserts, inside that same transaction, that+ the fire being stamped has not been stopped -- see+ ``upsert_scheduled_task_with_queued_run``. Only meaningful alongside+ ``queued_run``, because it exists to stop a stopped run queuing an Agent turn.+ """+self.maybe_reload()task = self._tasks.get(task_id)if task is None:@@ -1499,6 +1764,29 @@ class ScheduledTaskStore:expect = self._read_state(task)task.last_run_at = _utc_now_iso()task.last_error = error+ if records_command_outcome:+ # A COMMAND FIRE'S OWN STAMP OWNS THIS COLUMN, ``None`` included. A fire+ # that never reached a process -- a working directory that vanished, a+ # supervisor that died during startup -- has no status of its own, and+ # leaving the previous fire's code on the row made every surface report+ # "exited 7" beside a failure that ran no command. The notice already+ # refuses to print an exit code it does not have; the row must refuse to+ # keep one it no longer has.+ task.last_exit_code = int(exit_code) if exit_code is not None else None+ # AND WHETHER THE SCHEDULER IS WHY IT STOPPED, which the code cannot say on+ # its own: the runner reports its own timeout as 124, and a command that+ # wraps itself in ``timeout`` reports a real one as 124 too. Written on+ # every command stamp, both values, so a fire that did NOT time out+ # positively clears the previous fire's claim that one did.+ task.metadata = {+ **(task.metadata if isinstance(task.metadata, dict) else {}),+ COMMAND_TIMED_OUT_METADATA_KEY: bool(timed_out),+ }+ elif exit_code is not None:+ # A stamp from any other lane reports the code only when it has one: a+ # message task has none and must never blank what a command fire of the+ # same definition recorded.+ task.last_exit_code = int(exit_code)if disable_one_shot and task.schedule_type == "at":task.enabled = Falsetask.updated_at = _utc_now_iso()@@ -1506,7 +1794,12 @@ class ScheduledTaskStore:# guarded: this payload carries the mirror's ``session_id`` and ``enabled``, so# a run result landing after a ``/new`` reclaim would re-enable the definition# and re-point it at the session the reclaim just tore down.- return self._write_task(task, expect)+ return self._write_task(+ task,+ expect,+ queued_run=queued_run,+ expected_uncanceled_run_id=expected_uncanceled_run_id,+ )class TaskExecutionStore:@@ -1571,6 +1864,17 @@ class TaskExecutionStore:interrupt_reason: str = SETTLED_BY_RESTARTED,cancellation_error: Optional[str] = None,) -> None:+ """Settle the fires a dead service left ``running``.++ A fire that still carries a ``command_worker`` record is left ``running``:+ that record is the last name anyone has for a process this start could not+ prove dead, and it is readable only while the row is ``running``. Settling it+ would leave a backup or deployment running with nothing able to find it, so+ the row waits for the next start to retry -- bounded by+ ``_retain_unreaped_command_worker``, which stops re-stamping after+ ``_MAX_COMMAND_WORKER_REAP_ATTEMPTS``.+ """+interruption_error = interruption_error or i18n_t(SETTLEMENT_I18N_KEYS[interrupt_reason],"en",@@ -1600,38 +1904,114 @@ class TaskExecutionStore:payload = json.loads(path.read_text(encoding="utf-8"))except Exception:payload = {}+ stored_metadata = payload.get("metadata") if isinstance(payload, dict) else None+ if isinstance(stored_metadata, dict) and stored_metadata.get(+ COMMAND_WORKER_METADATA_KEY+ ):+ # Same rule as the SQLite pass: a surviving worker record means a+ # process this start could not prove dead, and this file is the only+ # place its identity is written. Requeuing is no safer than settling --+ # it would run the command again alongside the one still running.+ continueif not isinstance(payload, dict) or not payload.get("pid"):path.replace(pending_path)continue- now = _utc_now_iso()- metadata = payload.get("metadata")- canceled = bool(payload.get("cancel_requested"))- effective_error = cancellation_error if canceled else interruption_error- effective_reason = SETTLED_BY_STOPPED if canceled else interrupt_reason- payload.update(- {- "status": "canceled" if canceled else "failed",- "ok": False,- "error": effective_error,- "completed_at": now,- "updated_at": now,- "metadata": {- **(metadata if isinstance(metadata, dict) else {}),- "interrupt_reason": effective_reason,- },- }+ self._settle_processing_file(+ path,+ payload,+ interruption_error=interruption_error,+ cancellation_error=cancellation_error,+ interrupt_reason=interrupt_reason,)- with tempfile.NamedTemporaryFile(- mode="w",- dir=self.completed_dir,- suffix=".tmp",- delete=False,- encoding="utf-8",- ) as handle:- json.dump(payload, handle, indent=2)- tmp_path = Path(handle.name)- tmp_path.replace(completed_path)- path.unlink(missing_ok=True)++ def _settle_processing_file(+ self,+ path: Path,+ payload: dict[str, Any],+ *,+ interruption_error: str,+ cancellation_error: str,+ interrupt_reason: str,+ ) -> str:+ """Write one processing file out to ``completed`` as a result-less terminal.++ The file store's only settlement primitive, shared by the startup pass above and+ the per-run settle below so that both write the same row. A cancel the user+ already requested wins the status and the reason: they asked before the service+ could answer, and the answer never came.+ """++ now = _utc_now_iso()+ metadata = payload.get("metadata")+ canceled = bool(payload.get("cancel_requested"))+ status = "canceled" if canceled else "failed"+ payload.update(+ {+ "status": status,+ "ok": False,+ "error": cancellation_error if canceled else interruption_error,+ "completed_at": now,+ "updated_at": now,+ "metadata": {+ **(metadata if isinstance(metadata, dict) else {}),+ "interrupt_reason": SETTLED_BY_STOPPED if canceled else interrupt_reason,+ },+ }+ )+ with tempfile.NamedTemporaryFile(+ mode="w",+ dir=self.completed_dir,+ suffix=".tmp",+ delete=False,+ encoding="utf-8",+ ) as handle:+ json.dump(payload, handle, indent=2)+ tmp_path = Path(handle.name)+ tmp_path.replace(self.completed_dir / path.name)+ path.unlink(missing_ok=True)+ return status++ def settle_recovered_run(+ self,+ run_id: str,+ *,+ interruption_error: str,+ cancellation_error: str,+ interrupt_reason: str = SETTLED_BY_RESTARTED,+ ) -> Optional[str]:+ """Terminalize the ONE run whose retained worker has just been proven dead.++ ``recover_processing`` settles a whole start's worth of rows and deliberately+ steps over any row that still names a worker; this settles the single row whose+ worker was proven dead later, mid-life, once closing it can no longer orphan+ anything. Both backends answer, because the leak is the same on both: a run left+ ``running`` for a command that is long over, until some later start notices.++ Returns the status written, or ``None`` when nothing was: the SQLite write is+ status-scoped, and on the file store the processing file may already be gone.+ """++ if self._sqlite is not None:+ return self.settle_without_result(+ run_id,+ terminal_status=SETTLEMENT_TERMINAL_STATUS.get(interrupt_reason, "failed"),+ error=interruption_error,+ metadata={"interrupt_reason": interrupt_reason},+ )+ processing_path = self._request_path(run_id, state="processing")+ try:+ payload = json.loads(processing_path.read_text(encoding="utf-8"))+ except Exception:+ return None+ if not isinstance(payload, dict):+ return None+ return self._settle_processing_file(+ processing_path,+ payload,+ interruption_error=interruption_error,+ cancellation_error=cancellation_error,+ interrupt_reason=interrupt_reason,+ )def mark_execution_started(self, request_id: str) -> bool:"""Persist the boundary between a bare claim and executing its coroutine."""@@ -1665,6 +2045,116 @@ class TaskExecutionStore:tmp_path.replace(processing_path)return True+ def record_command_worker(+ self,+ request_id: str,+ identity: Optional[dict[str, Any]],+ ) -> bool:+ """Remember (or forget) the isolated supervisor this in-flight fire spawned.++ See ``SQLiteBackgroundTaskStore.record_command_worker``.+ """++ return self._merge_inflight_metadata(+ request_id, COMMAND_WORKER_METADATA_KEY, identity+ )++ def record_command_snapshot(+ self,+ request_id: str,+ snapshot: Optional[dict[str, Any]],+ ) -> bool:+ """Re-stamp what this in-flight fire is about to run.++ See ``SQLiteBackgroundTaskStore.record_command_snapshot``.+ """++ return self._merge_inflight_metadata(+ request_id, COMMAND_SNAPSHOT_METADATA_KEY, snapshot+ )++ def _merge_inflight_metadata(+ self,+ request_id: str,+ key: str,+ value: Optional[dict[str, Any]],+ ) -> bool:+ """Set (or drop) one metadata key on an in-flight fire.++ The file backend keeps the same keys in the processing payload's ``metadata``+ so a store swapped in by a test observes the same contract as SQLite.+ """++ if self._sqlite is not None:+ return self._sqlite.merge_running_run_metadata(request_id, key, value)+ processing_path = self._request_path(request_id, state="processing")+ try:+ payload = json.loads(processing_path.read_text(encoding="utf-8"))+ except Exception:+ return False+ if not isinstance(payload, dict):+ return False+ metadata = payload.get("metadata")+ metadata = dict(metadata) if isinstance(metadata, dict) else {}+ if value is None:+ if key not in metadata:+ return False+ metadata.pop(key, None)+ else:+ metadata[key] = dict(value)+ payload["metadata"] = metadata+ payload["updated_at"] = _utc_now_iso()+ with tempfile.NamedTemporaryFile(+ mode="w",+ dir=self.processing_dir,+ suffix=".tmp",+ delete=False,+ encoding="utf-8",+ ) as handle:+ json.dump(payload, handle, indent=2)+ tmp_path = Path(handle.name)+ tmp_path.replace(processing_path)+ return True++ def list_running_command_workers(self) -> list[dict[str, Any]]:+ """Every in-flight fire that still names a command worker.++ ``definition_id`` is part of the contract, not decoration: a caller asking+ whether ITS definition still has a worker running filters on it, so a backend+ that omits the field does not report "no worker" -- it reports it about every+ definition at once, and single flight silently stops holding here. The file+ payload spells the same association ``task_id`` (SQLite renamed that column),+ so the field is normalized at this boundary rather than at each reader.+ """++ if self._sqlite is not None:+ return self._sqlite.list_running_command_workers()+ self._ensure_dirs()+ workers: list[dict[str, Any]] = []+ for path in sorted(self.processing_dir.glob("*.json")):+ try:+ payload = json.loads(path.read_text(encoding="utf-8"))+ except Exception:+ continue+ if not isinstance(payload, dict):+ continue+ metadata = payload.get("metadata")+ identity = (+ metadata.get(COMMAND_WORKER_METADATA_KEY)+ if isinstance(metadata, dict)+ else None+ )+ if isinstance(identity, dict):+ definition_id = payload.get("task_id")+ workers.append(+ {+ "run_id": path.stem,+ "definition_id": str(definition_id) if definition_id else None,+ "identity": identity,+ }+ )+ return workers+@staticmethoddef queued_run_payload(request: TaskExecutionRequest) -> dict[str, Any]:"""The ``agent_runs`` payload ``enqueue`` would write for *request*.@@ -1728,6 +2218,13 @@ class TaskExecutionStore:source_kind=source_kind,))+ metadata = dict(task.metadata or {})+ snapshot = command_snapshot(task)+ if snapshot is not None:+ # Taken HERE, where the run row is created, because this is the last moment+ # at which the definition and the work about to run are the same thing. The+ # definition is editable and deletable from this instant on; the run is not.+ metadata[COMMAND_SNAPSHOT_METADATA_KEY] = snapshotreturn self.enqueue_definition_run(definition_id=task.id,run_type="scheduled",@@ -1739,7 +2236,7 @@ class TaskExecutionStore:prompt=task.prompt,agent_name=task.agent_name,session_policy=task.session_policy,- metadata=task.metadata,+ metadata=metadata,)def enqueue_definition_run(@@ -1943,7 +2440,20 @@ class TaskExecutionStore:return [TaskExecutionRequest.from_dict(item)for item in self._sqlite.list_runs(status="pending")- if item.get("request_type") in {"task_run", "hook_send", "agent_run", "scheduled", "watch", "webhook"}+ # ``task_escalation`` belongs here for the same reason ``hook_send``+ # does: it is a queued Agent turn the drain loop must claim. Left out,+ # the escalation row would be durable and never executed -- a failure+ # report the atomic stamp promised and nothing ever delivered.+ if item.get("request_type")+ in {+ "task_run",+ "hook_send",+ "agent_run",+ "scheduled",+ "watch",+ "webhook",+ "task_escalation",+ }]self._ensure_dirs()requests: list[TaskExecutionRequest] = []@@ -2025,6 +2535,24 @@ class TaskExecutionStore:not in TERMINAL_RUN_STATUSES]+ def find_escalation_run(self, *, parent_run_id: str) -> Optional[dict[str, Any]]:+ """Return the escalation Run one command fire queued, whatever its status.++ The status is the CALLER's decision to make -- retracting one is only valid+ while it is still non-terminal -- so this reports the row rather than filtering+ it out and answering "there is none".+ """++ if self._sqlite is not None:+ return self._sqlite.find_escalation_run(parent_run_id=parent_run_id)+ for run in self._list_file_runs():+ if (+ run.get("request_type") == "task_escalation"+ and run.get("parent_run_id") == parent_run_id+ ):+ return run+ return None+def find_callback_run(self,*,@@ -2486,6 +3014,10 @@ class TaskExecutionStore:session_id: Optional[str] = None,interrupt_reason: Optional[str] = None,failure_code: Optional[str] = None,+ exit_code: Optional[int] = None,+ stdout: Optional[str] = None,+ stderr: Optional[str] = None,+ escalation_run_id: Optional[str] = None,) -> Optional[str]:"""Settle one claimed request.@@ -2505,6 +3037,16 @@ class TaskExecutionStore:passthrough at a completion site is how an unrelated key comes to overwrite``interrupt_reason``, ``failure_code`` or the notice blob itself.+ ``exit_code`` / ``stdout`` / ``stderr`` are a command fire's outcome facts and+ stay ``None`` for every other request type.++ ``escalation_run_id`` names the already-durable Agent turn that carries this+ failure's report (``--on-failure agent``). It rides the metadata channel for+ exactly the reason ``interrupt_reason`` does: ``_merge_owed_failure_notice``+ applies ``extra_metadata`` BEFORE ``_owed_failure_notice_for_transition`` reads+ it, so the marker is in place when the notice decision is made and the same+ failure is not reported twice -- once as a turn, once as an alert.+Returns the exact terminal status this call wrote, or ``None`` when anotherterminal owner already won."""@@ -2514,6 +3056,8 @@ class TaskExecutionStore:extra_metadata["interrupt_reason"] = interrupt_reasonif failure_code:extra_metadata["failure_code"] = failure_code+ if escalation_run_id:+ extra_metadata["escalation_run_id"] = escalation_run_idif self._sqlite is not None:# Guarded, NOT ``update_run_status``: that writer's UPDATE has no status# predicate, so an ordinary completion rewrote a status another actor had@@ -2530,6 +3074,9 @@ class TaskExecutionStore:session_key=session_key if session_key is not None else request.session_key,session_id=session_id if session_id is not None else request.session_id,metadata=extra_metadata,+ exit_code=exit_code,+ stdout=stdout,+ stderr=stderr,)processing_path = self._request_path(request.id, state="processing")completed_path = self._request_path(request.id, state="completed")@@ -2537,6 +3084,7 @@ class TaskExecutionStore:return Noneterminal_status = "succeeded" if ok else "failed"payload = request.to_dict()+ self._carry_inflight_writes(processing_path, payload)payload.update({"ok": ok,@@ -2548,16 +3096,27 @@ class TaskExecutionStore:"callback_session_id": request.callback_session_id,})- if interrupt_reason or failure_code:+ # Command outcome facts only when this fire produced them, so a message task's+ # completed JSON keeps exactly the keys it has always had.+ if exit_code is not None:+ payload["exit_code"] = exit_code+ if stdout is not None:+ payload["stdout"] = stdout+ if stderr is not None:+ payload["stderr"] = stderr+ if interrupt_reason or failure_code or escalation_run_id:# The file backend has no owed-notice machinery at all, so this records the# class where its only reader — an operator looking at the completed JSON —# can see it, rather than dropping the one fact the caller went to the- # trouble of classifying.+ # trouble of classifying. ``escalation_run_id`` rides the same channel: it+ # suppresses nothing here (there is nothing to suppress), but the pointer+ # from a failure to the turn that reports it is the same kind of fact.existing = payload.get("metadata")payload["metadata"] = {**(existing if isinstance(existing, dict) else {}),**({"interrupt_reason": interrupt_reason} if interrupt_reason else {}),**({"failure_code": failure_code} if failure_code else {}),+ **({"escalation_run_id": escalation_run_id} if escalation_run_id else {}),}with tempfile.NamedTemporaryFile(mode="w",@@ -2572,6 +3131,54 @@ class TaskExecutionStore:processing_path.unlink(missing_ok=True)return terminal_status+ @staticmethod+ def _carry_inflight_writes(processing_path: Path, payload: dict[str, Any]) -> None:+ """Layer what was written to this run WHILE it ran onto its terminal payload.++ ``complete`` composes that payload from the caller's ``TaskExecutionRequest``,+ which is the copy taken at ENQUEUE: every in-flight write went to the processing+ file and to nothing the caller holds. ``record_command_snapshot`` is one --+ SCT-028's re-stamp of the command the executor really spawned, after its+ post-claim reload of the definition -- so starting from the request alone+ discarded it, and the completed run reported the definition as it stood BEFORE+ an edit committed in that window. SQLite has no such gap: the metadata lives on+ the row ``settle_run_terminal`` updates in place and is carried forward for free,+ which is exactly why this backend has to do it deliberately. Same reason the+ recovery writer (``_settle_processing_file``) composes from the file, and the two+ terminal writers must not disagree about what a settled row remembers.++ The file wins on ``metadata`` key by key rather than wholesale, so a key only+ the request carries is not dropped by a store whose in-flight merges never saw+ it, and the caller's own outcome facts still land afterwards. ``pid`` and+ ``started_at`` come along for the same reason the metadata does: they exist only+ because ``mark_execution_started`` wrote them here.+ """++ try:+ stored = json.loads(processing_path.read_text(encoding="utf-8"))+ except Exception:+ # The payload composed from the request is still a truthful terminal record+ # of the fire; it just forgets what ran. Failing the completion instead would+ # leave the row ``running`` over bookkeeping.+ logger.debug(+ "failed to read in-flight state for %s while completing it",+ processing_path.name,+ exc_info=True,+ )+ return+ if not isinstance(stored, dict):+ return+ stored_metadata = stored.get("metadata")+ if isinstance(stored_metadata, dict):+ existing = payload.get("metadata")+ payload["metadata"] = {+ **(existing if isinstance(existing, dict) else {}),+ **stored_metadata,+ }+ for key in ("pid", "started_at"):+ if stored.get(key) is not None:+ payload[key] = stored[key]+def settle_turn_participants(self,request: TaskExecutionRequest,@@ -2605,6 +3212,10 @@ class ScheduledTaskService:# simply leaves the rest queued and re-checks on the next tick. This caps# fan-out without re-introducing head-of-line blocking._MAX_CONCURRENT_EXECUTIONS = 8+ #: Starts allowed to try killing one surviving command worker. Retrying is what+ #: gives an unkillable orphan a second chance at all; the cap is what stops its+ #: run from being held ``running`` for the life of the install.+ _MAX_COMMAND_WORKER_REAP_ATTEMPTS = 3def __init__(self,@@ -2655,22 +3266,440 @@ class ScheduledTaskService:self._requires_service_lease = runtime.service_instance_lock_attached_to_process()self._drain_dirty = Trueself._recover_activity_lifecycle()+ # BEFORE ``recover_processing``, which nulls ``pid`` and settles these rows:+ # the run is the only place the orphan's identity is recorded, so once it is+ # terminal the child can never be found again. This pass decides each record by+ # WRITING it -- cleared once the process is proven dead, re-stamped while it may+ # still be running -- and ``recover_processing`` then leaves exactly the rows+ # whose record survived, so the NEXT start can try again.+ self._reap_orphaned_command_workers()self.request_store.recover_processing(interruption_error=self._t(SETTLEMENT_I18N_KEYS[SETTLED_BY_RESTARTED]),cancellation_error=self._t(SETTLEMENT_I18N_KEYS[SETTLED_BY_STOPPED]),)- def _t(self, key: str, **kwargs: Any) -> str:- """Translate a user-visible string in the configured language.+ def _t(self, key: str, **kwargs: Any) -> str:+ """Translate a user-visible string in the configured language.++ Mirrors ``UpdateChecker._t``: read the language straight off the+ controller's config so a headless service (tests, CLI-only runs) with no+ controller still falls back to English instead of raising.+ """++ config = getattr(self.controller, "config", None)+ lang = str(getattr(config, "language", "en") or "en")+ return i18n_t(key, lang, **kwargs)++ def _localize_worker_error(self, stderr: Optional[str]) -> str:+ """The shared worker-error decoder, reading this lane's copy.++ Both lanes spawn the SAME supervisor, so both can receive its+ machine-readable error line -- see ``core.watch_worker.localize_worker_error``.+ The ``harness.command`` namespace is what keeps the sentence honest: a user+ managing a cron job has no watch worker, and should not be told about one.+ Ordinary command stderr passes through untouched.+ """++ return localize_worker_error(+ stderr or "", self._t, namespace="harness.command"+ )++ def _require_command_worker_record(+ self,+ execution_id: str,+ identity: Optional[PersistedProcessIdentity],+ ) -> None:+ """Refuse to run a command whose worker could not be durably named.++ THE ONE MOMENT THIS CAN BE REFUSED FOR FREE. The supervisor is blocked reading+ its spec off stdin, so the backup, deployment or migration has not started: an+ exception here costs the user a reported failure, while continuing costs the+ ability to ever find the process again if this service dies mid-command -- the+ unrecoverable side of the same trade SCT-029/031/032 keep landing on. The runner+ reaps the tree on the way out (the callback runs inside its protected block).++ An UNCAPTURED identity is not that case and does not refuse. Its dominant cause+ is a supervisor that has already exited -- ``psutil.NoSuchProcess`` -- where there+ is no process to name and the handshake is about to report the worker's own,+ better error; and an identity that could not be captured cannot be made+ trustworthy by persisting it, because every kill path refuses a record it cannot+ fully vouch for (``process_identity_from_payload``).++ A refused stamp (``False``) means the row is no longer ``running``: the fire was+ stopped or already settled, so nothing would ever read the record anyway. Failing+ is right there too, and costs the user nothing -- a stop normalizes this fire to+ ``canceled``, which owes no notice (SCT-027).+ """++ if identity is None:+ logger.warning(+ "command fire %s has no durable worker identity; a crash during this "+ "command would leave it unfindable",+ execution_id,+ )+ return+ try:+ stamped = self.request_store.record_command_worker(+ execution_id, serialize_process_identity(identity)+ )+ except Exception as exc:+ raise RuntimeError(self._t("harness.command.workerNotRecorded")) from exc+ if not stamped:+ raise RuntimeError(self._t("harness.command.workerNotRecorded"))++ def _clear_command_worker(self, execution_id: str) -> None:+ """Drop a fire's worker record, never failing the fire.++ Best-effort on purpose, and the opposite trade from the stamp: this runs when+ the process is gone or proven dead, so the record it removes protects nothing,+ and a store hiccup must not turn a command that ran fine into a reported+ failure. A record left behind by such a hiccup is harmless -- the next start+ finds a pid it cannot vouch for and drops it.+ """++ try:+ self.request_store.record_command_worker(execution_id, None)+ except Exception:+ logger.debug(+ "failed to clear command worker for %s", execution_id, exc_info=True+ )++ def _record_executed_command(self, execution_id: str, task: ScheduledTask) -> None:+ """Correct the run's command snapshot to the definition actually being run.++ The enqueue stamped the definition as it stood THEN; this stamps it as it+ stands at the moment of execution, which is the copy the fire will really+ spawn (``_execute_claimed_request`` re-reads the definition after claiming).+ An edit committed in that window otherwise left the notice, the escalation+ prompt and the Workbench run detail naming a command that never ran.++ Best-effort like the worker stamp: a store hiccup must degrade the record,+ not fail a command that is about to run correctly.+ """++ try:+ self.request_store.record_command_snapshot(+ execution_id, command_snapshot(task)+ )+ except Exception:+ logger.debug(+ "failed to record executed command for %s", execution_id, exc_info=True+ )++ def _reap_orphaned_command_workers(self) -> None:+ """Kill command workers this host left running when the service died.++ Identity, not pid: between the crash and this pass the OS is free to reuse+ the number, so a bare ``kill(pid)`` here would be a coin flip on the user's+ other processes. Every kill path inside ``reap_orphaned_process_tree``+ re-reads the live start time and ``AVIBE_PROCESS_IDENTITY`` marker and+ refuses on any mismatch, and ``process_identity_from_payload`` refuses a+ record it cannot fully trust -- in both directions the safe answer is to+ leave the process alone and just drop the record.++ The tree, not the leaf: the worker is a supervisor, and the backup or+ migration doing the side effects is its child -- which is also why an empty+ pid is not the end of the question. ``reap_orphaned_process_tree`` owns that+ walk (the leader, then the group it left behind) so both worker lanes answer+ it the same way.++ THE PASS COMMUNICATES BY WRITING, and that is why it returns nothing. Only a+ proven death retires the record; every maybe keeps it, and ``recover_processing``+ -- which runs next -- leaves any fire still carrying one ``running``. Clearing+ on a maybe throws away the ONLY durable handle on a backup or deployment that is+ still writing, and it is unrecoverable: that row is where the identity lives, so+ no later start can find the process even in principle.++ So EVERY FAILURE HERE MUST LEAVE THE RECORD ALONE, including a failure to look.+ Returning a "nothing to protect" answer on a read error was the same category+ mistake one layer up: it licensed the settle pass to strip every live worker's+ name. A row unexamined for any reason keeps its record, hence its ``running``+ status, and ``_MAX_COMMAND_WORKER_REAP_ATTEMPTS`` stops the retries from+ becoming a run that is ``running`` forever.+ """++ try:+ workers = self.request_store.list_running_command_workers()+ except Exception:+ # Warning, not debug: nothing was killed and nothing was cleared, so any+ # orphan from the last life survives this start untouched -- worth a line in+ # the log, and safe, because the unread records keep their rows ``running``.+ logger.warning(+ "failed to list command workers for recovery; leaving their records "+ "in place for the next start",+ exc_info=True,+ )+ return+ for worker in workers:+ run_id = str(worker.get("run_id") or "")+ payload = worker.get("identity")+ pid = payload.get("pid") if isinstance(payload, dict) else None+ expected = (+ process_identity_from_payload(payload, pid)+ if isinstance(pid, int) and not isinstance(pid, bool)+ else None+ )+ # An untrusted payload counts as gone: every kill path refuses a record it+ # cannot fully trust, on this pass and on every future one, so keeping it+ # would pin the run ``running`` without ever buying a kill.+ try:+ outcome = (+ reap_orphaned_process_tree(+ logger,+ f"scheduled command worker {run_id}",+ expected_identity=expected,+ )+ if expected is not None+ else "gone"+ )+ except Exception:+ # One row's inspection blowing up must not abort the loop: the rows+ # after it would go unexamined AND the settle pass would never run, so+ # every other interrupted run of every other type would stay ``running``.+ logger.warning(+ "failed to inspect command worker from run %s; treating it as "+ "possibly alive",+ run_id,+ exc_info=True,+ )+ outcome = "unconfirmed"+ if outcome == "unconfirmed" and run_id and self._retain_unreaped_command_worker(run_id, payload):+ continue+ if run_id:+ self._clear_command_worker(run_id)++ def _retain_unreaped_command_worker(+ self,+ run_id: str,+ payload: Any,+ ) -> bool:+ """Keep an unkillable worker's identity for the next start, up to a limit.++ ``True`` means the record was kept and the run must stay ``running`` for+ ``list_running_command_workers`` to find it again. ``False`` is the give-up+ answer, and it has exactly two grounds: the attempts are spent, or the row is+ no longer ``running`` and so cannot hold a record at all. Then the run settles+ and reports like any other interrupted fire rather than being held open by a+ process that never exits.++ A WRITE THAT FAILS IS NOT A GROUND. The caller's next line clears the record,+ which is the one outcome this whole path exists to prevent: a locked database or+ a lost connection during the re-stamp says nothing about the process, and+ answering ``False`` there would hand a still-running backup's only durable name+ to the very code that deletes it. The already-stored record survives the failed+ write untouched -- it simply keeps the attempt count it had, so this pass is not+ charged against the cap and the next start looks again.+ """++ identity = dict(payload) if isinstance(payload, dict) else {}+ attempts = identity.get(COMMAND_WORKER_REAP_ATTEMPTS_KEY)+ attempts = attempts + 1 if isinstance(attempts, int) and not isinstance(attempts, bool) else 1+ if attempts >= self._MAX_COMMAND_WORKER_REAP_ATTEMPTS:+ logger.error(+ "giving up on command worker pid=%s from run %s after %s attempts; "+ "it may still be running",+ identity.get("pid"),+ run_id,+ attempts,+ )+ return False+ identity[COMMAND_WORKER_REAP_ATTEMPTS_KEY] = attempts+ logger.warning(+ "command worker pid=%s from run %s survived teardown; retrying on the "+ "next start (attempt %s)",+ identity.get("pid"),+ run_id,+ attempts,+ )+ try:+ # The already-serialized payload, re-stamped with its attempt count:+ # ``_require_command_worker_record`` takes a live identity and this record's+ # process is precisely the one we could not inspect our way back to.+ return bool(self.request_store.record_command_worker(run_id, identity))+ except Exception:+ logger.warning(+ "failed to re-stamp the attempt count on the command worker record for "+ "run %s; keeping the record as stored",+ run_id,+ exc_info=True,+ )+ return True++ def _command_fire_definition_id(self, request: TaskExecutionRequest) -> Optional[str]:+ """The definition id when this request is a command fire, else ``None``."""- Mirrors ``UpdateChecker._t``: read the language straight off the- controller's config so a headless service (tests, CLI-only runs) with no- controller still falls back to English instead of raising.+ if request.request_type not in {"task_run", "scheduled"}:+ return None+ task_id = request.task_id+ if not task_id:+ return None+ task = self.store.get_task(task_id)+ if task is None or not task.has_command:+ return None+ return task_id++ def _command_definition_has_live_worker(self, task_id: str) -> bool:+ """Whether a previous fire of this definition may still be running.++ SINGLE FLIGHT PER DEFINITION IS THE RULE (see ``_execution_lock_key``), and+ ``self._inflight_sessions`` only enforces it for as long as this process lives.+ A crash is exactly when it stops being enforced and exactly when a survivor is+ most likely: the supervisor's tree outlives the service, its record is retained+ by ``_reap_orphaned_command_workers`` precisely because it could not be shown+ dead, and the next tick of the same cron would then start a SECOND copy of that+ backup or migration -- two writers over one dataset, which is worse than a late+ fire in every case.++ A LOOK, NEVER A SIGNAL: the retained record's whole purpose is to let a later+ start kill that tree, so a fire must not resolve the collision by killing the+ earlier copy. ``orphaned_process_tree_presence`` answers on identity and returns+ the three answers apart, and ``present``/``unknown`` both defer the new fire --+ proceeding on "could not tell" is the same wager as proceeding on "yes".++ Proof of death releases the definition here rather than waiting for the next+ start: the record is retired, the interrupted fire is SETTLED (nothing else will+ ever come back for it -- see ``_settle_recovered_command_fire``) and the new fire+ runs, so a supervisor that ended while the service was down does not hold its own+ schedule shut.++ Untrusted records do not block. Every kill path refuses them, so no pass will+ ever act on one; treating it as a live worker would wedge the definition for+ good, which is the mirror of the reap's own reading of the same payload."""- config = getattr(self.controller, "config", None)- lang = str(getattr(config, "language", "en") or "en")- return i18n_t(key, lang, **kwargs)+ try:+ workers = self.request_store.list_running_command_workers()+ except Exception:+ # Unreadable, so unknown -- and unknown defers. Deferring costs a late fire+ # that the next tick retries; guessing "clear" costs a second writer.+ logger.warning(+ "failed to check for a live command worker on task %s; deferring the "+ "fire",+ task_id,+ exc_info=True,+ )+ return True+ for worker in workers:+ if str(worker.get("definition_id") or "") != task_id:+ continue+ run_id = str(worker.get("run_id") or "")+ if run_id and run_id in self._inflight_executions:+ # This process's own fire, already covered by the in-memory lock the+ # callers check first; not an orphan and not this method's business.+ continue+ payload = worker.get("identity")+ pid = payload.get("pid") if isinstance(payload, dict) else None+ expected = (+ process_identity_from_payload(payload, pid)+ if isinstance(pid, int) and not isinstance(pid, bool)+ else None+ )+ if expected is None:+ continue+ try:+ presence = orphaned_process_tree_presence(+ logger,+ f"scheduled command worker {run_id}",+ expected_identity=expected,+ )+ except Exception:+ logger.warning(+ "failed to inspect command worker from run %s; deferring the fire "+ "for task %s",+ run_id,+ task_id,+ exc_info=True,+ )+ return True+ if presence == "gone":+ if run_id:+ self._settle_recovered_command_fire(run_id)+ continue+ logger.warning(+ "task %s still has a command worker pid=%s from run %s (%s); deferring "+ "this fire",+ task_id,+ expected.pid,+ run_id,+ presence,+ )+ return True+ return False++ def _settle_recovered_command_fire(self, run_id: str) -> None:+ """Close the fire whose retained worker has just been shown dead.++ NO OTHER PASS COMES BACK FOR THIS ROW. ``recover_processing`` runs once, at+ startup, and deliberately steps over a run that still names a worker; the only+ other pass over stale rows -- ``sweep_stale_runs`` -- classifies orphans as+ ``run_type == "agent_run"`` and never looks at a command fire. So the row here,+ kept ``running`` by ``_reap_orphaned_command_workers`` because the process could+ not be proven dead and proven dead only now, has nobody left to close it.+ Releasing the definition without closing it would just trade a stuck schedule for+ a run that reads ``running`` until the next restart, describing a backup that+ ended long ago.++ THE RECORD GOES FIRST, because it is readable only while the row is ``running``:+ clearing after the settle would leave a dead process's name stamped on a terminal+ row where nothing would ever read or retire it. Neither order can cost a live+ process its only handle -- reaching this method IS the proof that there is no+ live process.++ Reported as ``restarted`` because that is what happened: the service died+ mid-fire and the supervisor did not outlive it. It is the same sentence the+ startup pass writes for every other run that restart cut off, so one+ interruption is not told two ways depending on which pass could prove it. The+ settle owes the notice, hence the drain nudge -- the user hears that the fire was+ interrupted, rather than only seeing the next one succeed.++ Settled through ``settle_recovered_run`` rather than the guarded writer directly,+ because the leak is not SQLite's alone: the legacy file store has no guarded+ per-run write, and skipping it here would release the definition while its+ processing file still read ``running``. The store owns that difference, so this+ method has one path instead of a supported-store branch that silently does+ nothing.++ Best-effort by construction: the caller is a fire's own admission check, and a+ store hiccup while closing the PREVIOUS run must not stop this one. Nothing is+ lost by deferring -- the record is already gone, so the next start's+ ``recover_processing`` settles the row it left behind.+ """++ self._clear_command_worker(run_id)+ settled_by = SETTLED_BY_RESTARTED+ try:+ settled = self.request_store.settle_recovered_run(+ run_id,+ interruption_error=self._t(SETTLEMENT_I18N_KEYS[settled_by]),+ cancellation_error=self._t(SETTLEMENT_I18N_KEYS[SETTLED_BY_STOPPED]),+ interrupt_reason=settled_by,+ )+ if settled is None:+ logger.info(+ "Interrupted command fire %s was already settled elsewhere",+ run_id,+ )+ return+ logger.warning(+ "Command fire %s settled %s after its worker was shown gone (%s)",+ run_id,+ settled,+ settled_by,+ )+ self._project_terminal_definition_result(+ self.request_store.get_run(run_id),+ execution_id=run_id,+ expected_status=settled,+ )+ except Exception:+ logger.warning(+ "failed to settle interrupted command fire %s after its worker was "+ "shown gone; leaving it for the next start",+ run_id,+ exc_info=True,+ )+ return+ self._drain_dirty = Truedef _execution_interruption(self, execution_id: str) -> str:return self._inflight_cancellation_causes.get(@@ -2957,6 +3986,77 @@ class ScheduledTaskService:return SETTLED_BY_STOPPEDreturn SETTLED_BY_RESTARTED+ def _is_command_execution(self, request: TaskExecutionRequest) -> bool:+ """Is this in-flight request a command fire rather than an Agent turn?++ Answered from the REQUEST, which is fixed for the life of the fire, before+ falling back to the live definition. Asking the store first got this wrong in+ the one case where the answer decides whether a child process lives: removing+ a task drops the definition and leaves its Run in flight, so a user cancelling+ a misbehaving command was told it was not a command and the child ran on to+ its ``--timeout``. The fallback still covers runs enqueued before the snapshot+ existed, whose definition is the only record there is.+ """++ if request.request_type not in {"task_run", "scheduled"} or not request.task_id:+ return False+ if command_snapshot_of_run({"metadata": request.metadata}) is not None:+ return True+ task = self.store.get_task(request.task_id)+ return bool(task is not None and task.has_command)++ def _propagate_requested_cancellations(self) -> None:+ """Pull the trigger on in-flight COMMAND fires the user has cancelled.++ ``cancel_run`` sets a flag; for a command fire nothing was reading it while the+ work was in flight. The flag was honoured only at settlement, and for a command+ that hangs that is up to ``--timeout`` away -- six hours by default -- so the+ child kept running, kept holding whatever it held, and the row the user had just+ cancelled reported a run that was over. Every other lane already closes this+ loop: a queued claim is terminalized at the door by ``claim_pending_run``, and a+ turn is interrupted by the turn lane.++ The kill itself needs nothing new. ``run_supervised_command`` turns a cancelled+ await into a process-tree teardown, and ``_execute_claimed_request`` settles the+ row from its ``CancelledError`` handler -- before the result stamp, so a+ cancelled fire also queues no escalation and stamps no failure on the definition.+ What was missing was somebody to observe the flag, which is this: the same+ ``_inflight_cancellation_causes`` + ``task.cancel()`` pair service shutdown uses,+ with the user named as the cause so the run reads ``stopped`` rather than+ ``interrupted``.++ COMMAND FIRES ONLY, deliberately. For an Agent turn cancelling this coroutine+ would abandon work that is still streaming into a conversation, and stopping a+ turn coherently -- interrupting the backend, closing the transcript -- belongs to+ the lane that owns it. A command's coroutine cancel IS the complete stop.+ """++ if not self._inflight_executions:+ return+ for request_id, execution in list(self._inflight_executions.items()):+ if execution.done() or request_id in self._inflight_cancellation_causes:+ continue+ request = self._inflight_requests.get(request_id)+ if request is None or not self._is_command_execution(request):+ continue+ try:+ run = self.request_store.get_run(request_id)+ except Exception:+ logger.exception(+ "Failed to read Run %s while checking for a requested cancellation",+ request_id,+ )+ continue+ if not run or not bool(run.get("cancel_requested")):+ continue+ if str(run.get("status") or "") in TERMINAL_RUN_STATUSES:+ continue+ logger.info(+ "Stopping in-flight command Run %s: cancellation requested", request_id+ )+ self._inflight_cancellation_causes[request_id] = SETTLED_BY_STOPPED+ execution.cancel()+def _begin_stop(self, *, cancel_reconcile: bool = True) -> None:self._running = Falsecurrent_task = self._current_asyncio_task()@@ -3055,6 +4155,11 @@ class ScheduledTaskService:# so sweep for owed auto-resume callbacks every tick — a cheap indexed lookup that# no-ops when nothing is pending.await self._drain_vault_callbacks()+ # A cancellation requested against work THIS process is running emits no+ # store change either — the flag is written by the CLI or the UI — so+ # only a periodic pass can act on it. No-ops unless a command fire is+ # actually in flight.+ self._propagate_requested_cancellations()# Same reason, one layer down: a run whose owner vanished emits no# store change either, so only a periodic pass can find it. Self# rate-limited, so riding this tick is cheap.@@ -3349,6 +4454,15 @@ class ScheduledTaskService:if lock_key is not None and lock_key in self._inflight_sessions:self.request_store.requeue(request.id)return+ command_definition_id = self._command_fire_definition_id(request)+ if command_definition_id is not None and self._command_definition_has_live_worker(+ command_definition_id+ ):+ # Requeued, not dropped: the row stays the definition's one pending fire and+ # runs as soon as the earlier worker is shown gone.+ self.request_store.requeue(request.id)+ self._drain_dirty = True+ returnself._spawn_execution(request, lock_key)execution = self._inflight_executions.get(request.id)if execution is not None:@@ -3388,6 +4502,15 @@ class ScheduledTaskService:# making progress and must not look sweepable.self.request_store.record_skip_reason(pending.id, reason=SKIP_REASON_SESSION_BUSY)continue+ command_definition_id = self._command_fire_definition_id(pending)+ if command_definition_id is not None and self._command_definition_has_live_worker(+ command_definition_id+ ):+ # Same reason as the lock above and recorded the same way: the definition+ # is busy -- here with a worker this process did not start -- so the row+ # keeps waiting and must not look sweepable while it does.+ self.request_store.record_skip_reason(pending.id, reason=SKIP_REASON_SESSION_BUSY)+ continuerequest = self.request_store.claim(pending.id)if request is None:continue@@ -4522,7 +5645,40 @@ class ScheduledTaskService:)else:headline = self._t("harness.notice.failed", name=name)- lines = [headline, self._t("harness.notice.error", error=error)]+ # COMMAND COPY, ORDINARY-FAILED LANE ONLY. A command definition's notice named+ # the definition and the error but never the command, so "Error: command exited+ # with status 7: boom" left the reader to go and look up WHAT exited. The lane+ # gate is deliberate: an interrupted command run is a fact about the SERVICE+ # (restart, eviction) and not about the command, so that lane keeps the generic+ # copy the headline already explains.+ #+ # The command copy is read off the RUN's own snapshot, falling back to the live+ # definition only for rows written before the snapshot existed. This notice is+ # drained asynchronously, so the definition can have been rewritten -- or+ # deleted -- between the fire and this call; either way ``get_task`` answers+ # about the wrong execution, or not at all.+ executed = command_snapshot_of_run(run)+ command_source = executed if executed is not None else task+ is_command_failure = (+ not failure_notices.is_interruption(notice)+ and command_source is not None+ and command_source.has_command+ )+ lines = [headline]+ if is_command_failure:+ command_preview = self._notice_command_preview(command_source)+ if command_preview:+ lines.append(self._t("harness.notice.commandLine", command=command_preview))+ lines.append(self._t("harness.notice.error", error=error))+ if is_command_failure and run.get("exit_code") is not None:+ # ONLY when the row actually carries one. A fire that never spawned — a+ # missing working directory, a supervisor that died during startup — has no+ # exit code at all, and "Exit code: None" (or a fabricated 0/1) would be+ # copy about nothing on the very notice that has to be trusted. No stderr+ # tail line either: the executor already appends the last non-empty stderr+ # line to the run's ``error``, so the line above carries it and a third+ # line would print the same text twice.+ lines.append(self._t("harness.notice.commandExit", exitCode=run.get("exit_code")))if not failure_notices.is_interruption(notice):# D5 asks for "the error and its CLASS", and on this lane the class was# dropped: the interrupted headline was the only place any reason was@@ -4627,6 +5783,19 @@ class ScheduledTaskService:lines.append(self._t("harness.notice.rerun", id=definition_id))return "\n".join(lines)+ @staticmethod+ def _notice_command_preview(task: Any) -> str:+ """The one-line command a notice names, or ``""`` for a non-command definition.++ Reads whichever shape the caller has -- a ``ScheduledTask`` or the run's own+ snapshot -- and hands both to the shared ``command_line_preview``, so the+ command in a failure notice is the same string ``vibe task list`` showed.+ """++ return command_line_preview(+ getattr(task, "shell_command", None), getattr(task, "command", None)+ )+def _task_lifecycle_state(self, definition_id: Optional[str], task: Any) -> str:"""The lifecycle state the badge shows for this task — asked of the badge.@@ -4929,6 +6098,16 @@ class ScheduledTaskService:Returns ``None`` for ``create_per_run`` (fresh session each time) andunkeyable requests.++ A COMMAND FIRE IS NOT A TURN, so it never takes a conversation's key. The lock+ exists to stop two Agent turns running in one conversation at once; a command+ talks to no Agent and holds no native session, yet it is bound to one (an+ ``--on-failure agent`` definition must be), and ``--timeout`` defaults to six+ hours -- so inheriting that key let one long backup command leave every queued+ turn in the conversation skipped as ``session_busy`` for as long as it ran. Its+ escalation IS a turn, and that is a separate run which takes the lock in the+ ordinary way. Keyed on the definition rather than dropped to ``None`` so a fire+ is still serialized against itself."""session_policy = request.session_policysession_id = request.session_id@@ -4937,6 +6116,8 @@ class ScheduledTaskService:if request.request_type in {"task_run", "scheduled"} and task_id:task = self.store.get_task(task_id)if task is not None:+ if task.has_command:+ return f"task:{task_id}"session_policy = task.session_policy or session_policysession_id = task.session_id or session_idsession_key = task.session_key or session_key@@ -4982,6 +6163,14 @@ class ScheduledTaskService:return Nonedef _transport_ready_for_request(self, request: TaskExecutionRequest) -> bool:+ if request.request_type in {"task_run", "scheduled"} and request.task_id:+ task = self.store.get_task(request.task_id)+ if task is not None and task.has_command:+ # A command run needs no IM transport: it produces an exit code and+ # output, not a reply. Gating it on a platform's readiness would hold a+ # backup or health check queued while an unrelated IM adapter is down.+ # The failure-notice path owns delivery, and it can be owed later.+ return Truetry:platform = self._request_target_platform(request)except Exception:@@ -5115,6 +6304,15 @@ class ScheduledTaskService:task_id = request.task_idsession_key = request.session_keysession_id = request.session_id+ #: Command-fire outcome facts. They stay ``None`` for every other request type,+ #: which is what keeps those rows' columns untouched.+ exit_code: Optional[int] = None+ stdout: Optional[str] = None+ stderr: Optional[str] = None+ #: The already-durable escalation turn a failed ``--on-failure agent`` command+ #: fire queued, or ``None``. Recorded on THIS run's metadata by ``complete()``,+ #: which is what stops the same failure being reported twice.+ escalation_run_id: Optional[str] = Nonetry:if request.request_type in {"task_run", "scheduled"}:self.store.maybe_reload()@@ -5141,7 +6339,16 @@ class ScheduledTaskService:failure_code = result.failure_codeshould_complete = result.complete_on_returnreconcile_delivery_on_return = result.reconcile_delivery_on_return- elif request.request_type in {"hook_send", "watch", "webhook"}:+ exit_code = result.exit_code+ stdout = result.stdout+ stderr = result.stderr+ escalation_run_id = result.escalation_run_id+ elif request.request_type in {+ "hook_send",+ "watch",+ "webhook",+ "task_escalation",+ }:if not request.prompt:raise ValueError("hook request requires prompt")if request.session_policy == "create_per_run":@@ -5163,7 +6370,17 @@ class ScheduledTaskService:prompt=request.prompt,execution_id=request.id,task_id=task_id,- trigger_kind=request.request_type if request.request_type != "hook_send" else "hook",+ # ``delivery_intent_for_trigger`` has a CLOSED vocabulary, and an+ # escalation IS a hook send -- an out-of-band turn a definition+ # queued -- so it takes the hook intent rather than a new one no+ # mapping knows. Provenance is not lost: the run row still carries+ # ``run_type="task_escalation"`` and the failed fire's+ # ``parent_run_id``.+ trigger_kind=(+ "hook"+ if request.request_type in {"hook_send", "task_escalation"}+ else request.request_type+ ),agent_name=request.agent_name,_capture_dispatch_result=True,**({"agent_id": request.agent_id} if request.agent_id else {}),@@ -5288,8 +6505,34 @@ class ScheduledTaskService:session_id=session_id,interrupt_reason=interrupt_reason,failure_code=failure_code,+ exit_code=exit_code,+ stdout=stdout,+ stderr=stderr,+ escalation_run_id=escalation_run_id,)- if project_terminal_definition_on_cancel and written_status is not None:+ # A STOP THAT NEVER BECAME A ``CancelledError``. ``cancel_run`` can+ # commit its flag after the work returned, so ``complete`` normalizes+ # this run to ``canceled`` while the coroutine ran to the end without+ # ever being interrupted -- and a command stamp refused by that same+ # flag then left the definition still reporting the fire BEFORE this+ # one. Read from the status ACTUALLY written rather than from+ # ``project_terminal_definition_on_cancel``, which says only that the+ # cancellation arrived the usual way: a service shutdown cancels the+ # same coroutine and settles ``interrupted``, which is a stop of the+ # SERVICE and not of this fire.+ fire_was_stopped = written_status == "canceled" and request.request_type in {+ "task_run",+ "scheduled",+ }+ if fire_was_stopped:+ # BEFORE the projection, because the escalation is claimable the+ # whole time this coroutine is still finishing up.+ self._retract_escalation_of_stopped_fire(request.id)+ if written_status is not None and (+ # The projection is the lane that settles a canceled fire.+ project_terminal_definition_on_cancel+ or fire_was_stopped+ ):self._project_terminal_definition_result(self.request_store.get_run(request.id),execution_id=request.id,@@ -5341,6 +6584,386 @@ class ScheduledTaskService:session_id,)+ def _runtime_default_workdir(self) -> Optional[str]:+ """The configured directory Agent work runs in, when nothing closer answered.++ Last stop before the ``~/.avibe`` fallback, and the reason that fallback is now+ nearly unreachable: a definition can legitimately carry no ``cwd`` and no+ readable Session -- a per-run binding created before+ ``_command_definition_spawn_cwd`` recorded one, or a definition written straight+ through the API -- and the product state directory is the worst possible place to+ run a user's command. ``runtime.default_cwd`` is where this install's Agent turns+ already run, so it is the same answer the escalation Session would get.++ Validated here rather than trusted: an unset or deleted ``default_cwd`` must fall+ through to the fallback below, not fail the fire with ``workdirMissing``.+ """++ config = getattr(self.controller, "config", None)+ candidate = getattr(getattr(config, "runtime", None), "default_cwd", None)+ if not isinstance(candidate, str) or not candidate.strip():+ return None+ resolved = os.path.abspath(os.path.expanduser(candidate.strip()))+ return resolved if os.path.isdir(resolved) else None++ def _bound_session_workdir(self, task: ScheduledTask) -> Optional[str]:+ """Where a command with no stored ``cwd`` should run: its binding's directory.++ ``--cwd`` is REFUSED for a definition bound to an existing Session+ (``cwd_with_existing_session``), on the rule that the Session owns its working+ directory -- so an escalating command task legitimately stores ``cwd=None``. A+ message task loses nothing to that: the Agent turn starts in the Session's+ workdir. A command has no turn to inherit it from, so ``None`` fell through to+ the ``~/.avibe`` fallback and ``--shell './scripts/sync.sh'`` -- the form the+ docs use -- ran from the product state directory, with the one flag that could+ have said otherwise rejected by the Session rule.++ Read live rather than copied into the definition at creation time, so the+ command follows a Session whose workdir was later changed, and so a per-run+ binding that does not exist yet simply reads as "no answer" (``None``) instead+ of a stale one. Best effort by design: a missing row, a NULL workdir or a read+ failure all fall back rather than failing the fire, and the fallback is still+ validated by the ``isdir`` check below.+ """++ session_id = str(task.session_id or "").strip()+ if not session_id:+ return None+ try:+ from storage.sessions_service import SQLiteSessionsService++ service = SQLiteSessionsService(paths.get_sqlite_state_path())+ try:+ row = service.get_agent_session_by_id(session_id)+ finally:+ # One store per FIRE, so it must not outlive the read: each one+ # carries an engine and an invalidation probe, and a cron command+ # running every minute would otherwise accumulate a connection a+ # minute for the life of the service.+ service.close()+ except Exception as exc: # pragma: no cover - defensive+ logger.warning(+ "Could not read the workdir of Session %s bound to task %s: %s",+ session_id,+ task.id,+ exc,+ )+ return None+ if not row:+ return None+ return str(row.get("workdir") or "").strip() or None++ async def _execute_command_task(+ self, task: ScheduledTask, *, execution_id: str, disable_one_shot: bool+ ) -> TaskExecutionResult:+ """Run one command definition's fire and record its outcome.++ The command runner owns the process mechanics -- spawn, spec handshake,+ timeout, cancellation and tree teardown -- so this method owns only scheduled+ task policy: where to run, how long to allow, and how the outcome is written+ to the definition and the run row.++ Every ORDERLY stop reaches the child through the runner: a timeout kills the+ tree from inside, while a service stop and a ``vibe runs cancel`` both cancel+ the awaiting coroutine, which the runner turns into a tree teardown (see+ ``_propagate_requested_cancellations`` for how the cancel flag becomes that+ cancellation). A SIGKILLed or crashed service reaches it through none of them:+ no ``CancelledError`` is ever delivered, and the isolated supervisor keeps its+ command running -- so a later fire of the same cron would start a second+ backup or migration beside the orphan. ``on_spawn`` therefore persists the+ worker identity on the run for ``_reap_orphaned_command_workers`` to find on+ the next start, and the ``finally`` clears it the moment the child is reaped.++ That identity lives in the run's ``metadata``, NOT in its ``pid`` column: that+ column holds the SERVICE pid, written by ``mark_execution_started`` for the+ recovery gate, and must not be repurposed.+ """++ error: Optional[str] = None+ exit_code: Optional[int] = None+ stdout_value: Optional[str] = None+ stderr_value: Optional[str] = None+ #: Whether the SCHEDULER stopped this fire, as opposed to the command choosing+ #: its own exit status. Recorded separately because the two are indistinguishable+ #: from the code alone: the runner reports a timeout as 124, and ``timeout 5 ...``+ #: inside a shell command reports a real one as 124 too.+ timed_out = False++ # BEFORE anything can fail, and before the spawn: the enqueue predicted this+ # command from the definition as it stood then, and the executor re-read the+ # definition after claiming. This is the copy that will actually run.+ self._record_executed_command(execution_id, task)++ spawn_cwd = (+ task.cwd+ or self._bound_session_workdir(task)+ or self._runtime_default_workdir()+ )+ if not spawn_cwd:+ stable_cwd = paths.get_vibe_remote_dir()+ stable_cwd.mkdir(parents=True, exist_ok=True)+ spawn_cwd = str(stable_cwd)++ if not os.path.isdir(spawn_cwd):+ # Do NOT spawn: ``create_subprocess_exec`` would raise a bare+ # ``NotADirectoryError``/``FileNotFoundError`` whose text does not name the+ # directory the user configured.+ error = self._t("harness.command.workdirMissing", cwd=spawn_cwd)+ else:+ effective_timeout = (+ task.timeout_seconds+ if task.timeout_seconds is not None+ else COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS+ )+ try:+ result = await run_supervised_command(+ command=task.command,+ shell_command=task.shell_command,+ cwd=spawn_cwd,+ timeout_seconds=effective_timeout,+ label=f"scheduled task {task.id}",+ on_spawn=lambda pid, identity: self._require_command_worker_record(+ execution_id, identity+ ),+ max_output_bytes=COMMAND_TASK_OUTPUT_CAP_BYTES,+ )+ except SupervisedCommandStartupError as exc:+ # Its own clause, BEFORE the broad one: the class subclasses+ # ``RuntimeError``, so a single ``except Exception`` would swallow it and+ # report the worker's startup failure as an ordinary command error.+ error = self._localize_worker_error(exc.detail) or self._t(+ "harness.command.supervisorExitedDuringStartup"+ )+ except Exception as exc:+ error = str(exc)+ logger.error(+ "Scheduled task %s command failed: %s", task.id, exc, exc_info=True+ )+ else:+ exit_code = result.exit_code+ # THE WORKER'S OWN FAILURES ARRIVE HERE, not only through+ # ``SupervisedCommandStartupError``: that is raised solely when the+ # stdin handshake breaks, so a worker that accepted the spec and THEN+ # could not spawn (an argv whose executable does not exist is the+ # ordinary case) simply exits 1 with its machine-readable error line on+ # stderr. Left undecoded, that raw JSON became the definition's+ # ``last_error``, the failure notice, and the Agent escalation prompt.+ worker_error = decode_watch_worker_error(result.stderr or "")+ stderr_value = self._localize_worker_error(result.stderr)+ stdout_value = result.stdout+ if result.timed_out:+ # Both streams are kept: whatever the command printed before it+ # hung is the only evidence of WHY it hung, and a timeout has no+ # exit status that explains itself. The runner preserves the+ # capped readers' buffers across the kill for exactly this.+ timed_out = True+ error = self._t(+ "harness.command.timedOut",+ seconds=_format_seconds(effective_timeout),+ )+ elif worker_error is not None:+ # THE SUPERVISOR'S EXIT STATUS IS NOT THE COMMAND'S. ``main()``+ # returns 1 for both of its own failures, so a spawn the worker+ # could not perform arrived here as ``exit_code == 1`` and was+ # published as a fact about the user's command: "Exit code: 1" in+ # the failure notice and the escalation prompt, ``last_exit_code = 1``+ # on the definition, an ``exit_code`` in the run row that+ # ``vibe runs show`` prints -- for a command that never started, and+ # alongside "Command exited with status 1" contradicting the+ # supervisor sentence in the same message. There IS no command exit+ # status in this outcome, and ``None`` is how this lane spells that+ # (the handshake failure above reports it the same way). The error+ # line the worker wrote is the discriminator, decoded rather than+ # sniffed: only the supervisor emits it, before any of the command's+ # own output can reach the stream, and a command that forged it is+ # already reporting itself as a supervisor failure through+ # ``_localize_worker_error`` -- losing an exit code it lied about is+ # the smaller half of that.+ #+ # The WATCH lane keeps its exit code here by design: a cycle's status+ # drives ``retry_exit_codes`` and ``_CycleResult`` has no "no status"+ # to spell, so leave that behaviour to the lane that owns it.+ exit_code = None+ error = stderr_value or self._t(+ "harness.command.unknownSupervisorFailure"+ )+ elif exit_code:+ detail = _last_nonempty_line(stderr_value)+ error = (+ self._t(+ "harness.command.exitedWithDetail",+ code=exit_code,+ detail=detail,+ )+ if detail+ else self._t("harness.command.exited", code=exit_code)+ )+ finally:+ # Reached on success, on failure, and on the ``CancelledError`` a+ # stop raises: by the time control is here the runner has reaped+ # the tree, so the stored identity now names a dead pid that the+ # OS is free to hand to something else.+ self._clear_command_worker(execution_id)++ # THE ESCALATION IS COMPOSED BEFORE THE STAMP AND QUEUED BY IT. A definition+ # carrying ``on_failure == "agent"`` owes the user ONE Agent turn per failed+ # fire, carrying the report -- and that turn is what the stamp AUTHORISES, so+ # the two must be one transaction (HFR-269, ``core/watches.py``: "TWO COMMITS+ # ARE NOT ONE DECISION"). Split in two, a teardown landing between them queues+ # an escalation under a definition that no longer authorises it, and an+ # exception between them disables a failed one-shot while LOSING the report.+ #+ # Never ``enqueue_definition_run``: that writer re-reads the definition and+ # RAISES on a disabled one, and a failed ``at`` task is disabled by the very+ # stamp that authorises this turn.+ escalation_request = None+ if error and task.on_failure == "agent":+ escalation_request = self.request_store.build_hook_send(+ session_key=task.session_key or "",+ session_id=task.session_id,+ prompt=self._escalation_prompt(+ task,+ run_id=execution_id,+ error=error,+ exit_code=exit_code,+ stdout=stdout_value,+ stderr=stderr_value,+ ),+ post_to=task.post_to,+ deliver_key=task.deliver_key,+ agent_name=task.agent_name,+ session_policy=task.session_policy,+ run_type="task_escalation",+ definition_id=task.id,+ source_kind="scheduler",+ parent_run_id=execution_id,+ metadata=dict(task.metadata or {}),+ )+ stamped = self.store.mark_task_result(+ task.id,+ error=error,+ disable_one_shot=disable_one_shot,+ exit_code=exit_code,+ # This IS the command fire's own result, so its ``exit_code`` -- including+ # ``None`` for a fire that never spawned -- is the whole truth about the+ # definition's last status.+ records_command_outcome=True,+ timed_out=timed_out,+ # THE BINDING THIS FIRE STARTED AGAINST, and only when a turn is being+ # authorised. ``mark_task_result`` reloads the mirror and derives its+ # compare-and-set expectation from the RELOADED row, so a ``/new`` reclaim+ # committed while the command ran becomes the expectation -- it matches, and+ # the stamp lands. Harmless while the stamp wrote only bookkeeping; not+ # harmless now that it queues an Agent turn, because the escalation above was+ # composed from the PRE-EXECUTION task and would be durably queued against+ # the session the reclaim just tore down, with the notice suppressed in its+ # favour. Refusing instead rolls both halves back and leaves the failure to+ # the owed-notice ladder.+ expected_binding=(+ (task.session_id, task.session_key, task.schedule_type)+ if escalation_request is not None+ else None+ ),+ # AND THAT THIS FIRE HAS NOT BEEN STOPPED, re-read server-side for the same+ # reason and in the same transaction. A ``vibe runs cancel`` committed while+ # the command was exiting settles the run ``canceled`` a moment later, and+ # without this the turn it authorises would already be durably queued: the+ # user stops a job and the job answers by starting an Agent.+ expected_uncanceled_run_id=(+ execution_id if escalation_request is not None else None+ ),+ queued_run=(+ self.request_store.queued_run_payload(escalation_request)+ if escalation_request is not None+ else None+ ),+ )+ # ONLY when the stamp landed. A refusal rolled the escalation row back with it,+ # so claiming an escalation id here would suppress the failure notice in favour+ # of a turn that does not exist -- and the failure would be silent.+ escalation_run_id = (+ escalation_request.id if escalation_request is not None and stamped else None+ )+ if not stamped:+ # Same refusal as the message path (HFR-261/HFR-264): the definition was+ # reclaimed, repointed or removed while this fire was running, so nothing+ # was stored. A would-be success must not be reported as one.+ logger.warning(+ "Scheduled task %s produced a result the store refused to stamp; "+ "reporting the run as failed",+ task.id,+ )+ if not error:+ error = self._t(_TASK_RESULT_NOT_RECORDED_I18N_KEY)+ # An ``at`` command task just disabled itself; the APScheduler job must drop.+ self.reconcile_jobs()+ return TaskExecutionResult(+ error=error,+ session_key=task.session_key or "",+ session_id=task.session_id,+ failure_code=None,+ complete_on_return=True,+ exit_code=exit_code,+ stdout=stdout_value,+ stderr=stderr_value,+ escalation_run_id=escalation_run_id,+ )++ def _escalation_prompt(+ self,+ task: ScheduledTask,+ *,+ run_id: str,+ error: str,+ exit_code: Optional[int],+ stdout: Optional[str],+ stderr: Optional[str],+ ) -> str:+ """The Agent-facing failure report a ``--shell ... --on-failure agent`` fire sends.++ NOT i18n'd, deliberately, and the watch completion-hook prompts are the+ precedent: this text is read by an AGENT, not shown to a user. It is the input+ to a turn, so the reply it produces is what the user actually reads -- and that+ reply is written in whatever language the conversation is in. Localizing the+ input would only make the instructions the model follows vary by locale.++ The user's own stored message comes FIRST when there is one: it is the standing+ instruction ("open a ticket if the backup fails"), and the machine-generated+ report is the evidence it operates on.+ """++ lines: list[str] = []+ stored_message = (task.prompt or "").strip()+ if stored_message:+ lines.append(stored_message)+ lines.append("")+ label = (task.name or "").strip()+ lines.append(+ f"A scheduled command task failed: {label} ({task.id})"+ if label+ else f"A scheduled command task failed: {task.id}"+ )+ command_preview = self._notice_command_preview(task)+ if command_preview:+ lines.append(f"Command: {command_preview}")+ # ``error`` already names the outcome in the only form that covers every branch:+ # the exit status, the timeout, a missing working directory, or the supervisor's+ # own startup detail. The exit code line is added only when the fire actually+ # produced one -- a run that never spawned has none, and "Exit code: None" would+ # be a fabricated fact on the one message that has to be trusted.+ lines.append(f"Outcome: {error}")+ if exit_code is not None:+ lines.append(f"Exit code: {exit_code}")+ stdout_tail = _last_nonempty_line(stdout)+ if stdout_tail:+ lines.append(f"Last stdout line: {stdout_tail}")+ stderr_tail = _last_nonempty_line(stderr)+ if stderr_tail:+ lines.append(f"Last stderr line: {stderr_tail}")+ lines.append(f"Run id: {run_id}")+ lines.append(f"Inspect with: vibe runs show {run_id}")+ return "\n".join(lines)+async def _execute_task(self,task: ScheduledTask,@@ -5362,6 +6985,15 @@ class ScheduledTaskService:# books whatever this run does, and outside the ``try`` because it reports# itself and must never be mistaken for the run's own failure.self._retry_orphaned_reservations(task)+ if task.has_command:+ # A command definition runs a subprocess instead of prompting an Agent, so+ # none of the session/binding machinery below applies to it. An+ # ``on_failure == "agent"`` definition queues its escalation turn from in+ # there, in the same transaction as its result stamp -- it does not dispatch+ # one from here.+ return await self._execute_command_task(+ task, execution_id=execution_id, disable_one_shot=disable_one_shot+ )try:if task.session_policy == "create_per_run":session_id = self._reserve_runtime_session(@@ -5462,7 +7094,7 @@ class ScheduledTaskService:task.id,)if not error:- error = _TASK_RESULT_NOT_RECORDED_ERROR+ error = self._t(_TASK_RESULT_NOT_RECORDED_I18N_KEY)reconcile_delivery_on_return = not complete_on_returncomplete_on_return = Trueif binding_change is not None:@@ -5813,6 +7445,87 @@ class ScheduledTaskService:if settled_any:self._drain_dirty = True+ def _retract_escalation_of_stopped_fire(self, execution_id: str) -> None:+ """Take back the Agent turn a fire queued, once the user stops that fire.++ A failed ``--on-failure agent`` fire commits its stamp and its escalation in ONE+ transaction, guarded on the fire not being cancelled (HFR-269). That guard can+ only see the cancels that exist WHEN IT COMMITS: ``cancel_run`` on a running fire+ writes a flag, and the flag can land after the stamp has already returned --+ ``settle_run_terminal`` then re-reads it and normalizes this fire to ``canceled``+ while the durable escalation sits queued and claimable. The user stops a job and+ the job answers by starting an Agent, which is the same defect the compare-and-set+ was written for, one lane further along.++ WHY RETRACTION AND NOT ONE BIGGER TRANSACTION. The enqueue has to commit with the+ STAMP -- that is what authorises the turn, and splitting them is what HFR-269+ closed -- while this settlement happens later, in another lane, after+ ``reconcile_jobs``. There is no single transaction that holds both without+ reopening the window it fixed. So the escalation is committed optimistically and+ withdrawn by whoever settles the fire against it.++ NEITHER REPORT IS OWED HERE, and that is deliberate. ``canceled`` is written only+ when the user asked for this fire to stop (``_cancel_aware_terminal_status``), and+ a stopped fire owes no failure notice -- the same rule SCT-027 relies on when a+ teardown cancels the fire itself. Re-arming the notice instead would alert the+ user about a job they had just stopped, which is this defect's mirror image. The+ failure is not lost either way: the stamp landed, so the definition still reports+ it.++ Found by LINKAGE rather than from the local ``escalation_run_id``: a+ ``CancelledError`` delivered anywhere after the stamp skips the assignment+ entirely, and the escalation is durable by then regardless.++ THIS IS THE SECOND OF TWO GUARDS, and it is the weaker one. Retraction can only+ take back a row that is still queued: ``cancel_run`` on an escalation the+ dispatch loop has already claimed writes a flag, and the turn lane does not+ watch that flag (see ``_propagate_requested_cancellations`` for why a turn's+ stop belongs to the lane that owns it). So the claim itself refuses an+ escalation whose fire is already cancelled+ (``_escalates_a_stopped_fire``), which is what actually makes the ordering+ between these two lanes irrelevant: whichever runs first, no Agent turn starts+ for a stopped fire. What remains is only an escalation claimed BEFORE the user's+ stop landed -- a turn that was legitimately in flight when the request arrived,+ which is the same thing that happens to any other out-of-band turn and is+ stopped from the turn lane, not from here.+ """++ try:+ escalation = self.request_store.find_escalation_run(parent_run_id=execution_id)+ except Exception:+ logger.exception(+ "Failed to look for the escalation queued by stopped Run %s", execution_id+ )+ return+ if escalation is None:+ return+ escalation_id = str(escalation.get("id") or "").strip()+ status = str(+ _normalize_requested_run_status(escalation.get("status"))+ or escalation.get("status")+ or ""+ ).strip()+ if not escalation_id or status in TERMINAL_RUN_STATUSES:+ # Already settled -- including by the claim door, which refuses an+ # escalation whose fire is cancelled and terminalizes it as ``canceled``+ # exactly as this would have.+ return+ try:+ retracted = self.request_store.cancel_run(escalation_id)+ except Exception:+ logger.exception(+ "Failed to retract escalation Run %s for stopped Run %s",+ escalation_id,+ execution_id,+ )+ return+ if retracted:+ logger.info(+ "Retracted escalation Run %s: its command fire %s was stopped",+ escalation_id,+ execution_id,+ )+def _project_terminal_definition_result(self,run: Optional[dict[str, Any]],@@ -5874,11 +7587,24 @@ class ScheduledTaskService:str(run.get("source_kind") or "") == "scheduler"and task.schedule_type == "at")+ # A COMMAND fire that ends here ended without reaching its own result stamp --+ # cancelled, or interrupted by shutdown -- so this projection IS that fire's+ # authoritative outcome, and it has no exit status to report. Saying so+ # (``records_command_outcome``) is what clears the previous fire's code;+ # without it the row read "exited 7" beside a run the user had just stopped.+ # Only for command runs: the generic lane must never blank the column on+ # behalf of a message task, which never had a code of its own.+ records_command_outcome = (+ command_snapshot_of_run(run) is not None or task.has_command+ )+ raw_exit_code = run.get("exit_code")try:recorded = self.store.mark_task_result(task.id,error=error,disable_one_shot=retire_one_shot,+ exit_code=int(raw_exit_code) if raw_exit_code is not None else None,+ records_command_outcome=records_command_outcome,expected_binding=(task.session_id,task.session_key,diff --git a/core/system_prompt_injection.py b/core/system_prompt_injection.pyindex 571db7105..05d99a67e 100644--- a/core/system_prompt_injection.py+++ b/core/system_prompt_injection.py@@ -257,7 +257,7 @@ Before choosing a command, ask: what outcome is the user trying to secure, what| Agent | Reusable role: backend, model, prompt, description, enabled state | Work needs a stable specialist identity || Session | Continuing context for one Agent work lineage | Work should continue or fork context || Scope | IM surface and routing context: channel, thread, DM, user scope | Delivery, workdir, user/platform context matter |-| Task | Saved message triggered by time | Time is the trigger |+| Task | Time trigger: saved Agent message, or a command with no Agent turn | Time is the trigger || Watch | Managed waiter triggered by an external signal | Any condition needs monitoring until it becomes true || Run | Concrete execution record | You need status, output, result, error, or history |@@ -277,6 +277,7 @@ Useful Harness queries include schema discovery, current session lookup, existin| Need | Use || --- | --- || Time trigger | `vibe task add` |+| Scheduled command, no Agent turn | `vibe task add --cron "<expr>" --shell "<cmd>"` || External signal trigger | `vibe watch add` || Independent Agent delegation | `vibe agent run --agent <agent-name>` || Continue a pointed Session | `vibe agent run --session-id ...` |@@ -287,7 +288,7 @@ Useful Harness queries include schema discovery, current session lookup, existin| State/history inspection | `vibe data query`, `vibe runs list --current-session`, `vibe runs show` || Recurring specialist workflow | `vibe agent create/update` plus tasks, watches, or runs |-`vibe task add` creates a time-triggered saved Agent message. Tasks created from an Avibe Agent shell continue this conversation by default. Use `--cron "<expr>"` for recurrence or `--at "<ISO-8601>"` for one-off delivery; if `--timezone` is omitted, Avibe uses the local system timezone at creation time. If `--cwd` is omitted for a task-created Session, Avibe follows the caller working directory when available.+`vibe task add` creates a time-triggered saved Agent message. Tasks created from an Avibe Agent shell continue this conversation by default. Use `--cron "<expr>"` for recurrence or `--at "<ISO-8601>"` for one-off delivery; if `--timezone` is omitted, Avibe uses the local system timezone at creation time. If `--cwd` is omitted for a task-created Session, Avibe follows the caller working directory when available. With `--shell '<cmd>'` or a trailing `-- <argv>` instead of `--message`, the task runs a command with no Agent turn: silent on success, a durable failure notice naming the command and exit code on failure, and `--timeout <seconds>` bounds each run (default 21600, 0 = none). Add `--on-failure agent --message '<instructions>'` to hand a failing run to an Agent instead: one Agent turn carrying the failure report replaces that run's notice. A pure command task takes no session, scope, or agent flags.`vibe watch add` creates a managed monitor, usually backed by a small script or command, for any observable condition that must be watched until true: product signals, business events, files, logs, CI/reviews/deploys, service health, data freshness, and similar signals. Watches created from an Avibe Agent shell follow up in this conversation by default. If `--cwd` is omitted, Avibe runs the waiter from the caller working directory when available.diff --git a/core/watch_worker.py b/core/watch_worker.pyindex b8c1d4a4c..ad033dbe0 100644--- a/core/watch_worker.py+++ b/core/watch_worker.py@@ -63,6 +63,52 @@ def decode_watch_worker_error(stderr: str) -> tuple[str, str | None] | None:return payload["code"], detail if isinstance(detail, str) else None+#: The leaf i18n key per handshake failure the worker can report. The PROTOCOL is one+#: thing whichever lane spawned the supervisor, but the SENTENCE is not: the same+#: failure has to read as "watch worker" to somebody managing a watch and as "command"+#: to somebody managing a scheduled command task, so the namespace is the caller's and+#: only the leaf is fixed here.+_PROTOCOL_ERROR_I18N_LEAVES = {+ "specTooLarge": "protocolErrors.specTooLarge",+ "invalidEncoding": "protocolErrors.invalidEncoding",+ "invalidJson": "protocolErrors.invalidJson",+ "unsupportedVersion": "protocolErrors.unsupportedVersion",+ "invalidCommand": "protocolErrors.invalidCommand",+}+++def localize_worker_error(+ stderr: str, translate: Any, *, namespace: str = "harness.watch"+) -> str:+ """Turn a worker's machine-readable error line into a sentence, or pass it through.++ LIVES HERE, beside the encoder, because both spawning lanes need it and only this+ module knows the wire format. ``core/watches.py`` had the only copy, so a scheduled+ command task whose executable did not exist stored the raw+ ``AVIBE_WATCH_WORKER_ERROR:{...}`` JSON as its ``last_error`` -- and then repeated+ it verbatim in the failure notice and in the Agent escalation prompt.++ ``translate`` is injected rather than imported: this module is also the child+ process's entry point, and it must stay importable without pulling the service's+ i18n stack in behind it. ``namespace`` selects which lane's copy to read, so the+ scheduled lane does not tell a user managing a cron job about a "watch worker".++ Anything that is not a worker error line is returned UNCHANGED -- ordinary command+ stderr is the common case, and it is nobody's to rewrite.+ """++ error = decode_watch_worker_error(stderr)+ if error is None:+ return stderr+ code, detail = error+ leaf = _PROTOCOL_ERROR_I18N_LEAVES.get(code)+ if leaf:+ detail = translate(f"{namespace}.{leaf}")+ elif not detail:+ detail = translate(f"{namespace}.unknownSupervisorFailure")+ return translate(f"{namespace}.supervisorFailed", detail=detail)++def _read_watch_worker_spec() -> tuple[list[str], str | None]:payload = sys.stdin.buffer.read(_MAX_SPEC_BYTES + 1)if len(payload) > _MAX_SPEC_BYTES:diff --git a/core/watches.py b/core/watches.pyindex ce5b96320..cffcefc09 100644--- a/core/watches.py+++ b/core/watches.py@@ -5,9 +5,7 @@ from __future__ import annotationsimport asyncioimport jsonimport logging-import mathimport os-import sysimport tempfilefrom dataclasses import asdict, dataclass, fieldfrom datetime import datetime, timezone@@ -17,18 +15,16 @@ from uuid import uuid4from config import pathsfrom core import watch_worker+from core.command_runner import SupervisedCommandStartupError, run_supervised_commandfrom core.process_isolation import (DEFAULT_PROCESS_TERMINATE_TIMEOUT_SECONDS,PersistedProcessIdentity,- capture_spawned_process_identity,inspect_process_identity,- isolated_subprocess_kwargs,- new_process_identity_marker,process_group_exists,process_group_identity_status,+ process_identity_from_payload,process_identity_matches,- process_identity_subprocess_env,- terminate_and_communicate,+ serialize_process_identity,terminate_process_group_by_pgid,terminate_process_tree_by_pid,)@@ -69,50 +65,11 @@ def _payload_float(payload: dict[str, Any], key: str, default: float) -> float:return float(payload[key])-def _serialize_process_identity(identity: PersistedProcessIdentity) -> dict[str, Any]:- return {- "pid": identity.pid,- "create_time": identity.create_time,- "worker_fingerprint": identity.worker_fingerprint,- }---def _valid_worker_fingerprint(value: Any) -> bool:- if not isinstance(value, str) or not value.startswith("sha256:") or len(value) != 71:- return False- return all(char in "0123456789abcdef" for char in value[7:])--def _process_identity_from_runtime_entry(entry: dict[str, Any],pid: int,) -> PersistedProcessIdentity | None:- payload = entry.get("process_identity")- if not isinstance(payload, dict):- return None- identity_pid = payload.get("pid")- create_time = payload.get("create_time")- worker_fingerprint = payload.get("worker_fingerprint")- try:- normalized_create_time = float(create_time)- except (TypeError, ValueError, OverflowError):- return None- if (- not isinstance(identity_pid, int)- or isinstance(identity_pid, bool)- or identity_pid != pid- or not isinstance(create_time, (int, float))- or isinstance(create_time, bool)- or not math.isfinite(normalized_create_time)- or normalized_create_time <= 0- or not _valid_worker_fingerprint(worker_fingerprint)- ):- return None- return PersistedProcessIdentity(- pid=identity_pid,- create_time=normalized_create_time,- worker_fingerprint=worker_fingerprint,- )+ return process_identity_from_payload(entry.get("process_identity"), pid)def _entry_updated_timestamp(entry: dict[str, Any]) -> float | None:@@ -846,22 +803,7 @@ class ManagedWatchService:return i18n_t(key, language, **kwargs)def _localize_watch_worker_error(self, stderr: str) -> str:- error = watch_worker.decode_watch_worker_error(stderr)- if error is None:- return stderr- code, detail = error- protocol_error_keys = {- "specTooLarge": "harness.watch.protocolErrors.specTooLarge",- "invalidEncoding": "harness.watch.protocolErrors.invalidEncoding",- "invalidJson": "harness.watch.protocolErrors.invalidJson",- "unsupportedVersion": "harness.watch.protocolErrors.unsupportedVersion",- "invalidCommand": "harness.watch.protocolErrors.invalidCommand",- }- if code in protocol_error_keys:- detail = self._t(protocol_error_keys[code])- elif not detail:- detail = self._t("harness.watch.unknownSupervisorFailure")- return self._t("harness.watch.supervisorFailed", detail=detail)+ return watch_worker.localize_worker_error(stderr, self._t)def active_process_pids(self) -> set[int]:"""Return active waiter process roots owned by managed watches."""@@ -1241,7 +1183,7 @@ class ManagedWatchService:}identity = self._active_process_identities.get(watch_id)if identity is not None:- entry["process_identity"] = _serialize_process_identity(identity)+ entry["process_identity"] = serialize_process_identity(identity)payload["watches"][watch_id] = entrytry:self.runtime_store.write(payload)@@ -1483,77 +1425,63 @@ class ManagedWatchService:returnasync def _run_cycle(self, watch: ManagedWatch, *, timeout_seconds: float) -> _CycleResult:+ """Run one waiter cycle through the shared supervised-command runner.++ The runner owns the process mechanics; this method owns watch policy:+ the active-pid/identity registries, runtime-state writes, and the+ localization of worker errors.+ """+spawn_cwd = _watch_spawn_cwd(watch)- worker_marker = new_process_identity_marker()- spawn_env = process_identity_subprocess_env(worker_marker)- process = await asyncio.create_subprocess_exec(- os.path.abspath(sys.executable),- os.fspath(Path(watch_worker.__file__).resolve()),- cwd=spawn_cwd,- env=spawn_env,- stdin=asyncio.subprocess.PIPE,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- **isolated_subprocess_kwargs(),- )- self._active_pids[watch.id] = process.pid- identity = capture_spawned_process_identity(process.pid, worker_marker)- if identity is not None:- self._active_process_identities[watch.id] = identity- else:- logger.warning(- "Unable to capture process identity for watch worker pid=%s watch_id=%s; "- "a future recovery will leave it untouched",- process.pid,- watch.id,- )- self._runtime_state_dirty = True- self._write_runtime_state()- try:- if process.stdin is None:- await terminate_and_communicate(process, logger, f"watch {watch.id}")- raise RuntimeError("watch worker supervisor stdin is unavailable")- try:- process.stdin.write(- watch_worker.encode_watch_worker_spec(- command=watch.command,- shell_command=watch.shell_command,- )- )- await process.stdin.drain()- except (BrokenPipeError, ConnectionResetError):- stdout, stderr = await process.communicate()- detail = stderr.decode("utf-8", errors="replace").strip()- detail = self._localize_watch_worker_error(detail)- raise RuntimeError(- detail or self._t("harness.watch.supervisorExitedDuringStartup")- ) from None- finally:- process.stdin.close()- if timeout_seconds > 0:- stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_seconds)++ def _register_spawn(pid: int, identity: Optional[PersistedProcessIdentity]) -> None:+ self._active_pids[watch.id] = pid+ if identity is not None:+ self._active_process_identities[watch.id] = identityelse:- stdout, stderr = await process.communicate()- timed_out = False- except asyncio.CancelledError:- await terminate_and_communicate(process, logger, f"watch {watch.id}")- raise- except asyncio.TimeoutError:- stdout, stderr = await terminate_and_communicate(process, logger, f"watch {watch.id}")- return _CycleResult(exit_code=124, stdout="", stderr=stderr.decode("utf-8", errors="replace"), timed_out=True)+ logger.warning(+ "Unable to capture process identity for watch worker pid=%s watch_id=%s; "+ "a future recovery will leave it untouched",+ pid,+ watch.id,+ )+ self._runtime_state_dirty = True+ self._write_runtime_state()++ try:+ result = await run_supervised_command(+ command=watch.command,+ shell_command=watch.shell_command,+ cwd=spawn_cwd,+ timeout_seconds=timeout_seconds,+ label=f"watch {watch.id}",+ on_spawn=_register_spawn,+ max_output_bytes=None,+ )+ except SupervisedCommandStartupError as exc:+ detail = self._localize_watch_worker_error(exc.detail)+ raise RuntimeError(+ detail or self._t("harness.watch.supervisorExitedDuringStartup")+ ) from Nonefinally:self._active_pids.pop(watch.id, None)self._active_process_identities.pop(watch.id, None)self._runtime_state_dirty = Trueself._write_runtime_state()+ if result.timed_out:+ return _CycleResult(+ exit_code=result.exit_code,+ stdout="",+ stderr=result.stderr,+ timed_out=True,+ )+return _CycleResult(- exit_code=process.returncode or 0,- stdout=stdout.decode("utf-8", errors="replace").strip(),- stderr=self._localize_watch_worker_error(- stderr.decode("utf-8", errors="replace").strip()- ),- timed_out=timed_out,+ exit_code=result.exit_code,+ stdout=result.stdout.strip(),+ stderr=self._localize_watch_worker_error(result.stderr.strip()),+ timed_out=False,)def _hook_request(diff --git a/docs/CLI.md b/docs/CLI.mdindex 31d9243fc..ae6413a64 100644--- a/docs/CLI.md+++ b/docs/CLI.md@@ -227,6 +227,7 @@ Create, inspect, update, run, pause, resume, or remove scheduled tasks.```bashvibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'vibe task add --cron '0 * * * *' --message 'Share the hourly summary.' # inside an Avibe Agent shell+vibe task add --name nightly-sync --cron '0 3 * * *' --shell './scripts/sync.sh' # command task, no Agent turnvibe task listvibe task update <task-id> --cron '*/30 * * * *'vibe task run <task-id>@@ -239,12 +240,24 @@ Use `vibe task add --help` and `vibe task update --help` for the full command su- `--create-session`, `--create-session-per-run`, `--same-scope`, and `--scope-id` for Session placement- `--cron` and `--at` scheduling- `--name`, `--timezone`, and message file support+- `--shell` / trailing `-- <argv>` for a scheduled command with no Agent turn,+ with `--on-failure {none,agent}` and a per-run `--timeout` (default 21600+ seconds, 0 = none)When `vibe task add` runs inside an Avibe-injected Agent shell, `--session-id`may be omitted. Avibe defaults the task target to the caller Session from`AVIBE_SESSION_ID` and reports that default in the command output. Explicit`--session-id`, session creation flags, and delivery flags still win.+A pure command task (`--on-failure none`, the default) skips that caller-session+default and takes no session, scope, or agent flags. Successful runs are silent;+a failed run records a durable failure notice naming the command and its exit+code. With `--on-failure agent --message '<instructions>'` the failure instead+starts one Agent turn carrying the failure report, and that turn replaces the+notice for the run. `vibe task update` can change a command task's `--shell`,+argv, or `--timeout`, but switching a task between message and command form, or+changing `--on-failure`, is rejected — remove the task and recreate it.+`--session-key` remains accepted for older scripts, but new tasks should usethe Agent Session ID shown in the active Avibe prompt.diff --git a/docs/CLI_ZH.md b/docs/CLI_ZH.mdindex 260a9a9b7..799f0a0e1 100644--- a/docs/CLI_ZH.md+++ b/docs/CLI_ZH.md@@ -208,6 +208,7 @@ vibe runs show # 在 Avibe Agent shell 内查看调用```bashvibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'vibe task add --cron '0 * * * *' --message 'Share the hourly summary.' # 在 Avibe Agent shell 内+vibe task add --name nightly-sync --cron '0 3 * * *' --shell './scripts/sync.sh' # 命令任务,不触发 Agent turnvibe task listvibe task update <task-id> --cron '*/30 * * * *'vibe task run <task-id>@@ -220,12 +221,23 @@ vibe task remove <task-id>- 用 `--create-session`、`--create-session-per-run`、`--same-scope` 和 `--scope-id` 控制 Session placement- 用 `--cron` / `--at` 控制定时方式- 以及 `--name`、`--timezone`、`--message-file` 等参数+- 用 `--shell` 或写在 `--` 之后的 argv 创建不触发 Agent turn 的定时命令任务,+ 可搭配 `--on-failure {none,agent}` 和按次执行的 `--timeout`+ (默认 21600 秒,`0` 表示不限制)当 `vibe task add` 运行在 Avibe 已注入 caller context 的 Agent shell 内时,可以省略 `--session-id`。Avibe 会把任务目标默认到 `AVIBE_SESSION_ID`对应的调用方 Session,并在命令输出里报告这次默认。显式 `--session-id`、session creation 参数和 delivery 参数仍然优先。+纯命令任务(`--on-failure none`,即默认值)不会套用上面这条调用方 Session 默认,+也不接受 session、scope 或 agent 相关参数。执行成功时完全静默;执行失败会记录一条+持久化的失败通知,并在通知中写明命令与退出码。若使用+`--on-failure agent --message '<处理说明>'`,失败会改为触发一次携带失败报告的 Agent+turn,并由该 turn 取代这次执行的失败通知。`vibe task update` 可以修改命令任务的+`--shell`、argv 或 `--timeout`,但在 message 形态与 command 形态之间切换、或修改+`--on-failure`,都会被拒绝——请删除任务后重新创建。+`--session-key` 仍兼容旧脚本,但新任务应使用当前 Avibe prompt里展示的 Agent Session ID。diff --git a/docs/COMMANDS.md b/docs/COMMANDS.mdindex 9a4ed141d..53eaf5add 100644--- a/docs/COMMANDS.md+++ b/docs/COMMANDS.md@@ -719,7 +719,12 @@ vibe upgrade### `vibe task add````bash+# Agent task, and a command task that escalates to an Agent on failurevibe task add (--session-id <session_id> | --create-session | --create-session-per-run) (--cron <expr> | --at <timestamp>) (--message <text> | --message-file <file>) [options]+vibe task add (--session-id <session_id> | --create-session | --create-session-per-run) (--cron <expr> | --at <timestamp>) (--shell <cmd> | -- <argv>...) --on-failure agent [options]++# Pure command task: no Agent, and therefore no session target+vibe task add (--cron <expr> | --at <timestamp>) (--shell <cmd> | -- <argv>...) [options]```Important options:@@ -735,8 +740,15 @@ Important options:- `--at`- `--message`- `--message-file`+- `--shell`+- `--on-failure {none,agent}`+- `--timeout <seconds>`- `--timezone`+A command task (`--shell` or a trailing `-- <argv>`) runs with no Agent turn and+takes no session, scope, or agent flags unless `--on-failure agent` is set.+`--timeout` bounds each command run (default 21600 seconds, `0` = no timeout).+### `vibe task update````bash@@ -758,8 +770,13 @@ Important options:- `--at`- `--message`- `--message-file`+- `--shell`+- `--timeout <seconds>`- `--timezone`+Switching a task between message and command form, or changing `--on-failure`,+is rejected with `task_mode_immutable` — remove the task and recreate it.+### `vibe task list````bashdiff --git a/docs/COMMANDS_ZH.md b/docs/COMMANDS_ZH.mdindex 16e3637c9..8f70d9f45 100644--- a/docs/COMMANDS_ZH.md+++ b/docs/COMMANDS_ZH.md@@ -697,7 +697,12 @@ vibe upgrade### `vibe task add````bash+# Agent 任务,以及失败后升级给 Agent 的命令任务vibe task add (--session-id <session_id> | --create-session | --create-session-per-run) (--cron <表达式> | --at <时间戳>) (--message <文本> | --message-file <文件>) [options]+vibe task add (--session-id <session_id> | --create-session | --create-session-per-run) (--cron <表达式> | --at <时间戳>) (--shell <命令> | -- <argv>...) --on-failure agent [options]++# 纯命令任务:不涉及 Agent,因此也不接受 session 目标+vibe task add (--cron <表达式> | --at <时间戳>) (--shell <命令> | -- <argv>...) [options]```重要参数:@@ -714,8 +719,15 @@ vibe task add (--session-id <session_id> | --create-session | --create-session-p- `--at`- `--message`- `--message-file`+- `--shell`+- `--on-failure {none,agent}`+- `--timeout <秒>`- `--timezone`+命令任务(`--shell` 或写在 `--` 之后的 argv)执行时不会触发任何 Agent turn,+除非设置了 `--on-failure agent`,否则不接受 session、scope 或 agent 相关参数。+`--timeout` 限制每次命令执行的时长(默认 21600 秒,`0` 表示不限制)。+### `vibe task update````bash@@ -737,8 +749,13 @@ vibe task update <task_id> [options]- `--at`- `--message`- `--message-file`+- `--shell`+- `--timeout <秒>`- `--timezone`+在 message 形态与 command 形态之间切换,或修改 `--on-failure`,都会被+`task_mode_immutable` 拒绝——请删除任务后重新创建。+### `vibe task list````bashdiff --git a/docs/plans/scheduled-command-task.md b/docs/plans/scheduled-command-task.mdnew file mode 100644index 000000000..740f40985--- /dev/null+++ b/docs/plans/scheduled-command-task.md@@ -0,0 +1,544 @@+# Scheduled Command Tasks (Agent-Free Task Mode)++## Background++The Harness has two trigger types, and both end by handing work to an AI Agent:++- `vibe task` — a time trigger that sends a stored message to an Agent Session+ (`core/scheduled_tasks.py:5344` resolves the session and dispatches the+ message as a normal user turn).+- `vibe watch` — a condition trigger that runs a real subprocess and then sends+ its stdout to an Agent as a follow-up message.++There is no way to schedule a plain command with no AI turn. Users who want a+cron job today either fall back to system cron/systemd — losing Avibe's run+history, scoped cwd, and failure visibility — or abuse a forever watch whose+waiter always exits with the retry exit code (default 75): in forever mode a+retry-code exit authorises no agent hook (`core/watches.py:1467`), so the watch+silently becomes an interval-based agent-free runner. That is a trick, not a+feature: it is interval-based rather than cron-based, and any stray exit code+wakes an Agent.++This is not a foreign concept bolted onto the Harness. The Harness value+proposition is durability, ownership, trigger, delivery target, and observable+progress — none of which require an LLM — and the storage model already agrees:++- `run_definitions` is one unified definition table+ (`storage/models.py:203`). It already carries the time half (`cron`,+ `run_at`, `timezone`), the command half (`shell_command`, `command_json`,+ `timeout_seconds`), and the agent half (`agent_name`, `session_policy`,+ `session_id`) — all nullable. Tasks use the time half, watches use the+ command half; nothing yet uses time + command together.+- `agent_runs` already stores `pid`, `exit_code`, `stdout`, `stderr`+ (`storage/models.py`, and the watch supervisor already writes such rows). It+ is a process-execution record, not only an LLM-turn record.++What Avibe adds over system cron is scoped execution: the caller's working+directory, run history in the same place as agent work, durable failure+notices, and — the genuinely differentiated part — optional escalation to an+AI Agent when the command fails. Plain cron cannot hand a failing job to an+agent for diagnosis.++## Product Model++```text+Task = a time trigger that creates Runs.+Watch = a condition trigger that creates Runs.+A Run's action is either an Agent message (existing) or a command (new).+```++A **command task** is a scheduled task whose action is a subprocess instead of+an Agent message, with a per-definition failure policy:++- `on-failure: none` (default) — pure cron. No Agent turn, ever. Success is+ silent; failure produces a durable failure notice through the existing+ non-agent notice ladder.+- `on-failure: agent` — cron with AI triage. A non-zero exit or timeout+ enqueues one Agent turn carrying the run report.++```bash+vibe task add --name nightly-sync --cron '0 3 * * *' \+ --shell './scripts/sync.sh'++vibe task add --name nightly-sync --cron '0 3 * * *' \+ --shell './scripts/sync.sh' \+ --on-failure agent --message 'The nightly sync failed. Diagnose it.'+```++This updates the sentence in `docs/plans/agent-run-harness.md` ("Task = a time+trigger that creates Agent Runs"): the trigger model is unchanged; the run's+actor is now either an Agent or a command.++## Goals++- Schedule a command with `vibe task add --shell '<cmd>'` or+ `vibe task add ... -- <cmd> [args...]`, on `--cron` or `--at`, with the same+ timezone handling, pause/resume/update/remove lifecycle, and manual+ `vibe task run <id>` as message tasks.+- Zero AI involvement for `--on-failure none` tasks, including on failure.+- Reuse — not duplicate — the watch subprocess runner, the run-record+ machinery, the per-definition serialization, and the owed-failure-notice+ delivery ladder.+- Optional `--on-failure agent` escalation that enqueues one Agent turn per+ failed fire, atomically with the run's terminal stamp.+- Full observability: `vibe task list/show`, `vibe runs list/show`, and the+ Web UI Tasks tab show command tasks and their exit codes.++## Non-Goals (first cut)++- Success notifications or routing stdout anywhere on success. Cron culture is+ silence on success; output lives in run history. A user who wants a summary+ in chat should use a message task or `--on-failure agent`.+- Catch-up of fires missed while the service was down. The scheduler uses an+ in-memory jobstore rebuilt from definitions on start+ (`core/scheduled_tasks.py:2618`, `:3265`), so downtime misses are lost today+ for message tasks too; command tasks inherit that unchanged.+- First-class Vault fields on the definition (see Vault section).+- Overlap policy other than "skip while a run is in flight".+- Resource limits (nice/cgroups), retry-on-failure, and webhook triggers.+- A Web UI create/edit form for command tasks. V1 is CLI-create; the UI+ displays, pauses, resumes, and removes them through the existing+ `definition_type="scheduled"` endpoints (`vibe/ui_server.py:8754`).+- Any change to `vibe watch` behavior. The exit-75 idiom keeps working; docs+ simply stop needing to teach it.++## CLI Design++### `vibe task add`++New arguments, mirroring the watch waiter convention exactly+(`vibe watch add` already accepts `--shell '<command>'` or a trailing+`-- command args...`):++- `--shell '<command>'` — shell string form.+- trailing `-- <command> [args...]` — argv form, stored in `command_json`.+- `--on-failure {none,agent}` — default `none`. Only valid with a command.+- `--timeout <seconds>` — per-run timeout, default 21600 (the watch default),+ `0` for none. Only valid with a command.++`--message`/`--message-file` moves from parser-level required+(`vibe/cli.py:13939`) to validated in `cmd_task_add` (`vibe/cli.py:2960`):++| Combination | Result |+| --- | --- |+| `--message` only | Message task (today's behavior, unchanged) |+| `--shell`/`--` only | Command task, `on-failure none` |+| command + `--on-failure agent` | Command task with escalation; auto-built report |+| command + `--on-failure agent` + `--message` | Escalation prompt = message + auto report |+| neither message nor command | Reject: one action source is required |+| `--message` + command without `--on-failure agent` | Reject: a message needs a consumer |+| `--on-failure agent` / `--timeout` without command | Reject |+| `--shell` + trailing `--` command | Reject: one command source |++Session/scope/agent flags (`--session-id`, `--create-session`,+`--create-session-per-run`, `--same-scope`, `--scope-id`, `--agent`) configure+the **escalation turn** and are therefore valid only with+`--on-failure agent`, with today's exact semantics and defaults (inside an+Agent shell, escalation continues the caller conversation by default, per+`_apply_caller_session_default`). With `--on-failure none` they are rejected:+there is no session, so accepting them would record dead configuration.++There is a hidden fourth input to that matrix: the **ambient caller default**.+`cmd_task_add` applies `_apply_caller_session_default` before anything else+(`vibe/cli.py:2964`), so inside an Agent shell a session target exists with no+session flag passed at all. Rejecting "session flags" must therefore+distinguish an explicit flag from the injected default — otherwise a pure cron+task could not be created from chat at all. Rule: **skip the caller default when+a command is present and `on_failure=none`**, and let it apply normally for+`on_failure=agent`. `_validate_definition_session_policy` and+`_resolve_session_target_args` also need a genuine "no session at all" leg. This+is where most of step 4's real work lives.++`--cwd` keeps its current meaning and default (caller directory) and becomes+the command's working directory for command tasks.++One consequence needs naming, because it has no `--cwd` to fix it: a definition+bound to an *existing* Session must not pass `--cwd` at all+(`cwd_with_existing_session` — the Session owns its directory), so an escalating+command task legitimately stores `cwd=None`. A message task loses nothing there,+since the Agent turn starts in the Session's workdir; a command has no turn to+inherit from. So the command reads that workdir itself at fire time+(`_bound_session_workdir`) rather than falling through to `~/.avibe`. Read live,+not copied at creation, so it follows a Session whose workdir later changes and+reads as "no answer" for a per-run binding that does not exist yet.++`vibe task update` accepts the same new fields. Switching a definition between+message and command mode via update is rejected (`task_mode_immutable`) —+delete and recreate — because the write-guard model+(`DefinitionWriteConflict`, `storage/background.py:294`) is built around+full-row payloads whose session bindings do not change shape mid-life.++This rejection is **permanent, not a v1 placeholder**. Step 6 does not make the+switch reachable in any clean way. `none → agent` would need a message, a+session policy, and a binding to arrive in one command, and `cmd_task_update`+has no caller-default machinery (`_apply_caller_session_default` is an add-path+helper), so even from an Agent shell the user would have to pass explicit+`--session-id` / `--create-session --same-scope`. `agent → none` is worse:+update semantics keep the stored session when no flags are passed, so stripping+a binding would need a `--clear-session`-style flag that does not exist. Both+directions cost new flag surface plus a doubled validation matrix, against an+alternative that is two short commands.++`vibe task run <id>`, `pause`, `resume`, `remove` work unchanged: they operate+on the definition and the enqueue path, not on the action type.++`vibe task list`/`show` gain a kind marker (`message` | `command`), the+command text, timeout, on-failure policy, and last exit code+(`last_exit_code` already exists on `run_definitions`).++## Design Decisions++### D1: Same `definition_type="scheduled"`, no new definition kind++A command task is stored as a `run_definitions` row with+`definition_type="scheduled"`, non-null `shell_command` or `command_json`, and+null `prompt`. The presence of a command *is* the mode; no new discriminator+column.++The losing alternative — a third `definition_type="command"` — was rejected+because every routing call site special-cases exactly two values today:+`_DEFINITION_KINDS` (`storage/background.py:251`), the UI enable endpoints+(`vibe/ui_server.py:8754`, `:8812`), workbench queue classification+(`storage/workbench_sessions_service.py:993`), the agent graph+(`core/services/agent_graph.py:190`), and session reclaim. A third value buys+nothing (the schedule half is byte-for-byte the same columns) and costs a+migration plus a third case at each site. With `"scheduled"` unchanged, all of+those sites — and the tasks tab, pause/resume, deletion — keep working without+modification.++The on-failure policy is stored in `metadata_json.on_failure`+(`"none"`/`"agent"`), not a new column. `metadata_json` already carries+behavior-affecting facts (caller scope placement via+`_definition_metadata_with_scope`, `vibe/cli.py:3064`), and this avoids+touching the dual migration stacks (`storage/migrations.py` NEW_COLUMNS plus+alembic) for one enum. If the UI later needs to filter on it, promoting it to+a column is a routine additive migration. `timeout_seconds` uses the existing+column watches already own.++New `ScheduledTask` dataclass fields (`core/scheduled_tasks.py:835`):+`shell_command`, `command`, `timeout_seconds`, `on_failure` — round-tripped+through `to_dict`/`from_dict` and the store upsert payload, exactly as+`ManagedWatch` (`core/watches.py:134`) does for the same columns.++Run rows: the command execution is the scheduled fire itself, so it keeps+`run_type="scheduled"` with `exit_code`/`stdout`/`stderr`/`pid` filled and+`session_id` null. Run-count queries per definition keep working. This follows+the watch precedent in reverse: watches use a distinct `run_type` only for the+long-lived supervisor heartbeat (`watch_runtime`,+`storage/background.py:269`), which exists to keep a non-execution row out of+execution counts. A command run *is* the execution, so it keeps the execution+run_type. The escalation turn is a second row — see D4.++### D2: Extract the watch subprocess runner and share it++The watch service already owns a hardened runner (`_run_cycle`,+`core/watches.py:1485`): it spawns `core/watch_worker.py` as a supervisor+subprocess with `isolated_subprocess_kwargs()`, passes the command spec over+stdin (`watch_worker.encode_watch_worker_spec`), captures a process-identity+marker so a kill after service restart can never hit a recycled PID, enforces+the per-cycle timeout with `terminate_and_communicate`, and converts worker+protocol errors into localized messages.++Decision: extract the service-side spawn/timeout/identity logic of+`_run_cycle` into a shared `core/command_runner.py` helper+(`run_supervised_command(command|shell_command, cwd, timeout_seconds,+on_spawn(pid, identity))`), used by both `ManagedWatchService` and the new+command-task branch. `core/watch_worker.py` stays as-is and becomes the shared+worker binary; its name can be generalized later without a protocol change.++The losing alternative — a direct `asyncio.create_subprocess_shell` in the+task service — was rejected because it would re-grow, one incident at a time,+exactly the hardening watches already paid for: timeout kills, orphan recovery+by identity, and the worker error protocol. This is the CLAUDE.md "fix at the+highest appropriate layer" rule applied to execution: the behavior is common,+so the shared core owns it. The timing models do differ (a watch cycle can be+hours-long and re-arming; a command run is one bounded execution), but the+difference lives entirely in the *caller loop*, not in the spawn/wait/kill+mechanics being extracted.++### D3: Execution path and gates++The command branch lives in `_execute_task`+(`core/scheduled_tasks.py:5344`): when the definition carries a command, run+it via the shared runner instead of resolving a session and calling+`_execute_request` (`:6890`). Everything upstream is reused unchanged:++- **Trigger and reconcile**: unchanged, and the command fields must **not** be+ added to the `reconcile_jobs` change signature (`:3271-3280`). That signature+ exists only to rebuild the APScheduler *job*, whose identity is the trigger;+ `_run_task` re-reads the definition at fire time, so command edits take effect+ with no job churn. Adding the fields would cause pointless remove/re-add+ cycling. `coalesce=True, max_instances=1` stays correct: an event-loop stall+ collapses a backlog into one catch-up run, which is the right semantic for a+ sync-style job.+- **Durability**: `_run_task` (`:3323`) persists the `agent_runs` row via+ `enqueue_task_run` (`:1715`) before executing, and its pending-request dedup+ already prevents double-queueing one definition.+- **Serialization**: `_execution_lock_key` (`:4917`) already returns+ `task:{task_id}` when a definition has no session, so command runs of one+ definition serialize with no new code. Policy: a fire that arrives while the+ previous run is still executing is skipped (dedup), not queued. Real cron+ overlaps; we deliberately do not, because overlapping the same job is almost+ always a bug amplifier and "skip" is what the existing machinery does.+- **Transport gating must be short-circuited** (corrected — the naive reading is+ wrong). `_transport_ready_for_request` (`:4984`) falls through to+ `metadata["session_scope_id"]` (`_request_target_platform`, `:4975`), which+ `_definition_metadata_with_scope` (`vibe/cli.py:2282`) writes for *any*+ shell-created definition. So a pure command task created from a Slack chat+ would refuse to execute a local script while Slack transport is down. Step 3+ short-circuits the check for scheduled requests whose definition carries a+ command — the definition re-read is already that function's first act.+ Execution needs no transport; the failure-notice path owns "deliver when+ possible". The escalation request keeps normal gating, because it *is* a+ message.+- **Completion**: the run row terminalizes with `exit_code`, `stdout`,+ `stderr` (each capped at 64 KiB — a new, stated cap; SQLite rows must not+ inherit an unbounded pipe), and timing. Timeout maps to exit code 124,+ matching the watch convention (`storage/background.py:263`). The run row's+ `pid` column keeps its existing meaning — the *service* pid stamped by+ `mark_execution_started` (`core/scheduled_tasks.py:1711`), which is what+ `recover_processing` gates on. The child pid is not persisted in v1; the+ runner holds the process object and owns every kill path.+- **Cancellation and teardown**: `vibe runs cancel` on a processing row only+ sets `cancel_requested` (`core/scheduled_tasks.py:2427-2454`) — nothing polls+ that flag mid-run. It is consumed by `settle_run_terminal`, which settles the+ row `canceled` rather than `failed` when the run completes, and by+ `_shutdown_interruption_for` (`:3022`) at service stop. A live kill therefore+ happens only when the service stops: `_begin_stop` (`:3035`) cancels inflight+ coroutines, and the runner's `CancelledError` path performs the+ identity-verified kill exactly as `_run_cycle` does (`core/watches.py:1538`).+ This is the same behavior agent runs already have, so v1 is at parity — but+ it is weaker than "cancel kills the child", and the CLI help should not imply+ otherwise. A service restart mid-run is settled by the existing+ processing-recovery sweep (`TaskExecutionStore.recover_processing`, `:1567`).++### D4: Delivery without an Agent — reuse the failure-notice ladder++For `--on-failure none`:++- **Success**: no message anywhere. The run row is the record; `vibe runs+ show` and the UI show stdout.+- **Failure** (non-zero exit or timeout): the run terminalizes with an error,+ which stamps an owed failure notice — and from there the *existing*,+ battle-tested non-agent delivery path does everything:+ `_deliver_one_failure_notice` (`core/scheduled_tasks.py:3516`) claims the+ notice with a lease, and `_emit_failure_notice` (`:3775`) walks the delivery+ ladder (`emit_replayed_backend_failure` per rung) ending at the reserved+ workspace-notifications session. This is already a direct message with no+ LLM turn, already deadline-bounded, already retried with backoff, and —+ critically — already streak-suppressed (`failure_streak_decision`), so an+ every-5-minutes job that starts failing does not send a notice per fire.++The only new delivery code is copy: `_failure_notice_body`+(`:4462`) gains a command-task variant that names the command, exit code, and+a stderr tail, and points at `vibe task show <id>` / `vibe runs show <run-id>`+— through `vibe/i18n/`, per the i18n rule.++Bounding the scope creep the brief warned about: there is **no** new outbound+"post stdout to a scope" surface in v1. The losing alternative — posting raw+output to the owning scope on every run or every failure — was rejected+because it recreates per-platform formatting, truncation, and noise problems+that the Agent normally absorbs, and the notice ladder already answers "where+does the user find out" without any of that. Consequence: a command task with+`on-failure none` requires **no session and no scope at all**; if created from+an Agent shell, the caller scope recorded in definition metadata gives the+notice ladder better rungs to try first, but nothing requires it+(`_definition_metadata_with_scope`, `vibe/cli.py:3064`).++For `--on-failure agent`:++On failure, build the escalation prompt (optional stored `--message` ++auto-built report: command, exit code, duration, stdout/stderr tails — same+composition idea as the watch `_build_prompt(message, stdout)`) and enqueue a+prompt-carrying request through the exact path watch hooks use:+`build_hook_send` (`core/scheduled_tasks.py:1839`) into the+`request_type in {"hook_send", "watch", "webhook"}` execution branch+(`:5144`), with `run_type="task_escalation"` and `parent_run_id` set to the+command run's id (both columns exist, and `_run_values` already maps them,+`storage/background.py:5745-5747`). Session policy, per-run session+reservation, agent resolution, and delivery all come along for free.++Two additions this requires: the executor branch set (`:5144`) must gain+`"task_escalation"` plus its `trigger_kind` mapping; and escalation must **not**+route through `enqueue_definition_run`, whose server-side re-read raises on a+disabled definition (`storage/background.py:2583`) — a one-shot `at` task is+already disabled by `mark_task_result(disable_one_shot=True)` before escalation+would enqueue.++Atomicity is non-negotiable: the command run's terminal stamp and the+escalation enqueue commit in **one** transaction, per the lesson documented at+`core/watches.py:1589` ("TWO COMMITS ARE NOT ONE DECISION") — a teardown+landing between two commits would otherwise queue an escalation under a+definition that no longer authorises it.++The precedent to copy is `SQLiteBackgroundTaskStore.upsert_watch_with_queued_run`+(`storage/background.py:2483`): a guarded definition CAS plus+`enqueue_run_in_connection` inside one `run_update_event_transaction`, rolled+back on refusal. Four concrete pieces are needed:++1. a twin method `upsert_scheduled_task_with_queued_run(payload, *, expect,+ run_payload)`;+2. a `queued_run: Optional[dict]` parameter on `ScheduledTaskStore.mark_task_result`+ (`core/scheduled_tasks.py:1481`) threaded through `_write_task`, mirroring+ `ManagedWatchStore.mark_cycle_result` (`core/watches.py:683`);+3. a `sqlite_backend` property on `ScheduledTaskStore` — missing today, whereas+ `ManagedWatchStore` has one (`core/watches.py:374`) — so the atomic path can+ be gated with a sequential fallback;+4. `_execute_task` builds the request via `build_hook_send` and passes+ `queued_run_payload(request)` into the stamp.++Exactly one of {escalation turn, failure notice} fires per failed run. The+mechanism is concrete: the notice is stamped by the run's terminal transition in+`complete()` (`:2478`, deliberately named-kwargs-only), so `TaskExecutionResult`+carries an `escalation_run_id` up through `_execute_claimed_request` and into+`complete()` as a new named kwarg that the notice decision reads as a+suppression input. If the escalation enqueue itself fails, the failure notice+proceeds so the failure is never silent.++One crash window is accepted deliberately. The atomic stamp+enqueue and the+run-row settle are two separate commits, so a teardown landing between them+loses the `escalation_run_id` marker and fires **both** the (already durable)+escalation and a notice. That bias is the correct one: duplicated visibility on+a rare teardown beats a silently dropped failure report, and closing it would+require cross-row suppression, which this design does not build.++The *opposite* bias is not accepted, and two teardown paths had to be taught so+(both found in the Codex review of the implementation):++- **Session teardown vs. a queued escalation.** Archiving or `/new`-ing the bound+ Session ends the escalation — cancelled by `archive_session` /+ `_delete_agent_session_rows`' archival half, or simply orphaned when its empty+ half deletes the row the turn was bound to. Either way the promised report can+ no longer happen, so `rearm_notices_for_escalations_canceled_with_session`+ (`storage/background.py`) stamps the suppressed notice back onto the parent run+ **in the same transaction** as the teardown. `escalation_run_id` is left on the+ row as the audit trail of what was attempted. The notice ladder is the right+ fallback precisely because it needs no Session: a notice is delivered to the+ scope. Two details decide whether that re-arm actually holds. It keys on+ `TEARDOWN_CONDEMNED_RUN_STATUSES` — every status teardown *cancel-requests*,+ not the narrower pair it terminalizes in the same statement — because an+ escalation the executor already claimed is condemned by the same transaction+ and merely dies later, having possibly reported nothing. And both teardown+ halves now cancel the runs bound to the Session before the row goes: with no+ foreign key on `agent_runs.session_id`, a delete otherwise leaves the turn+ claimable against a Session that is gone, and its death would report the same+ failure a second time from the very lane meant to replace it.+- **A binding that moved mid-fire.** `mark_task_result` derives its+ compare-and-set expectation from the mirror it *reloads*, so a `/new` reclaim+ committed while the command ran becomes its own expectation and the stamp+ lands. Harmless while the stamp wrote only bookkeeping; not harmless once it+ queues an Agent turn composed from the pre-execution task. The escalating call+ therefore passes `expected_binding` — the binding the fire started against — so+ the whole fire is refused and the failure stays with the notice ladder.++Escalation frequency: every failed fire escalates in v1, matching cron's+mail-on-every-failure semantics. Transition-only escalation+(`--escalate-on transition`) is deferred; `last_exit_code` on+`run_definitions` makes it cheap when wanted.++### D5: Vault — compose, don't integrate++V1 adds no Vault fields. A command task that needs secrets writes them into+its own command line: `--shell 'vibe vault run --env API_KEY -- ./sync.sh'`.++- **Standard secrets** without `always_ask` deliver headlessly — this works+ unattended today.+- **Standard `always_ask` secrets** return `approval_required`+ (`vibe/cli.py:7111`) and **protected secrets** require browser + passkey+ approval. Both are incompatible with unattended scheduled fires *by+ design* — protected values are end-to-end encrypted behind a user unlock,+ and no unattended path exists or should be built. Such a run fails with the+ vault error as its stderr, and the task's on-failure policy applies (a+ notice, or an Agent who can tell the user an approval is needed).++The losing alternative — a first-class `--vault-env` column resolved by the+service at spawn — is deferred, not rejected: it is additive, and doing it+later avoids blocking v1 on the design question of secret references inside+definitions.++### D6: UI — a kind within the Tasks tab, not a new tab++`TAB_ORDER` stays `tasks | watches | runs`+(`ui/src/components/workbench/harnessTabs.ts:8`). Command tasks appear in the+existing Tasks tab with a kind chip (Message / Command), the command text, and+last exit code; the run list and run detail show exit code and captured+output. Command runs have `session_id` null, so the run row simply has no+session to open — the run detail is the destination. All new strings go+through `ui/src/i18n/en.json` and `zh.json`; `cd ui && npm run build` before+push.++### D7: Prompt guidance, docs, and tests++CLI examples in injected system prompts are live callers. Surfaces to update+in the same PR that ships the CLI flags:++- `core/system_prompt_injection.py:279` (the "Time trigger →+ `vibe task add`" table and the `:290` paragraph): one added sentence — a+ scheduled command with no Agent turn is `vibe task add --cron ... --shell+ ...`.+- `core/agent_tool_policy.py:111`–`:126` (native-scheduler denial guidance):+ the CronCreate denial can now answer the agent-free case directly.+- `skills/use-avibe/SKILL.md`, `skills/use-vibe-remote/SKILL.md`,+ `docs/CLI.md`, `docs/CLI_ZH.md`, `docs/COMMANDS.md`, `docs/COMMANDS_ZH.md`.++Test layers:++- **Unit**: shared runner extraction (behavior-preserving for watches — run+ `tests/test_watches.py` unchanged, plus runner tests for timeout/kill/caps);+ `ScheduledTask` round-trip and store upsert with command fields+ (`tests/test_scheduled_tasks.py` patterns); executor command branch+ (success, non-zero, timeout, cancel); notice-body copy; escalation+ prompt composition.+- **Contract**: extend `tests/test_cli_task_command.py` with the full+ validation matrix above (every Reject row is a test); parser-parse every+ documented example, and extend the guidance assertions in+ `tests/test_harness_skill_guidance.py` / `tests/test_agent_tool_policy.py`+ so prompt text and parser cannot drift apart.+- **Scenario**: new `tests/scenarios/harness_command_task/` catalog + a+ closed-loop harness case in the style of+ `tests/scenarios/harness_failure_recovery/`: (a) fire → fail →+ exactly one failure notice; (b) fire → fail with `on-failure agent` →+ exactly one escalation run linked via `parent_run_id` and zero notices;+ (c) fire → success → silence. Scenario IDs named in the PR description.++All tests hermetic: isolate `CODEX_HOME`/`CLAUDE_CONFIG_DIR`/state paths as+the suite already requires.++## Compatibility and Rollout++- The watch exit-75 idiom keeps working; nothing in the watch path changes.+- A command-task row read by an older service is not a clean no-op: with no+ session binding, `_execute_request` fails at `parse_session_key("")`+ (`core/scheduled_tasks.py:256-260`) and every fire records a failed run with+ `last_error` set (failure notices apply, streak-suppressed); with a session+ binding and an empty prompt, the dispatched blank turn returns early without+ an Agent response. Neither case dispatches a spurious Agent turn or corrupts+ state, and the failure is visible rather than silent. Mixed CLI/service+ versions remain unsupported — they ship together.+- No schema migration: all columns exist; new facts ride `metadata_json`.++## Todo++Ordered; each step ships independently.++1. Extract `core/command_runner.py` from `ManagedWatchService._run_cycle`+ with no watch behavior change; port watch service to it; runner unit tests+ and untouched `tests/test_watches.py` green.+2. Storage: command fields on `ScheduledTask` + store round-trip ++ `add_task`/`update_task` acceptance; `enqueue_task_run` carries them; unit+ tests.+3. Executor: command branch in `_execute_task` using the shared runner —+ run-row completion with capped output, timeout as exit 124, pid/identity+ registration, cancel and teardown settlement; unit tests.+4. CLI: `--shell` / trailing `--` / `--on-failure` / `--timeout` on+ `vibe task add` and `task update`, the full validation matrix,+ `task list/show` rendering; contract tests for every matrix row and every+ documented example.+5. Failure notices for command runs: command-aware notice body via+ `vibe/i18n/`; scenario case (a) and (c).+6. Escalation: `--on-failure agent` via `build_hook_send` with+ `run_type="task_escalation"`, `parent_run_id`, single-transaction stamp ++ enqueue, notice suppression invariant; scenario case (b).+7. UI: kind chip, command/exit-code rendering on tasks tab and run detail,+ i18n en/zh, `npm run build`.+8. Prompt guidance + skills + docs updates with their contract assertions.diff --git a/skills/use-avibe/SKILL.md b/skills/use-avibe/SKILL.mdindex cc4763ceb..b5b7c76f9 100644--- a/skills/use-avibe/SKILL.md+++ b/skills/use-avibe/SKILL.md@@ -782,6 +782,8 @@ Preferred CLI shape:- recurring task for this conversation: `vibe task add --cron '<expr>' --message '...'`- one-off task for this conversation: `vibe task add --at '<ISO-8601>' --message '...'`- task that creates a visible sibling Session: `vibe task add --create-session --same-scope --cron '<expr>' --message '...'`+- scheduled command with no Agent turn: `vibe task add --cron '<expr>' --shell '<command>'`+- command task with AI failure triage: `vibe task add --cron '<expr>' --shell '<command>' --on-failure agent --message '<what to do>'`- immediate rerun: `vibe task run <id>`- managed background watch for this conversation: `vibe watch add --message '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)- watch that creates a visible sibling Session: `vibe watch add --create-session --same-scope --message '...' -- <cmd>`@@ -803,7 +805,7 @@ Targeting and callbacks:- When a task, watch, or new Agent run creates a Session and `--cwd` is omitted, Avibe uses the command's current working directory. Forks keep the source Session cwd by default.- Async Agent runs return the final result to this conversation by default. Pass `--no-callback` only when you will inspect the run later with `vibe runs`. Pass `--callback-session-id <id>` only when the final result should return to a different Session.- `--message` and `--message-file` are the user-message flags for task, watch, and agent-run commands.-- `vibe task add` stores the message template and creates Agent Runs when the time trigger fires.+- `vibe task add` stores a message template — or, with `--shell` / a trailing `-- <argv>`, a command — and creates Runs when the time trigger fires. A command task runs with no Agent turn: silent on success, a failure notice on failure, `--on-failure agent` to escalate failures to an Agent.- `vibe watch add` uses `--message` as the instruction template for the Agent Run created after the waiter reaches a reportable state.- `--fork-self` forks this Session's native backend context. `--fork-session <id>` forks another explicit Session. Forks keep the source Session backend, scope, and cwd by default.- Fork overrides are intentionally narrow: `--agent`, `--model`, and `--reasoning-effort` can override the forked Session only if the backend stays the same. Do not combine fork flags with existing-session or session-creation flags.@@ -811,7 +813,7 @@ Targeting and callbacks:Operational guidance:- use `vibe task list` before editing or deleting an existing task; use `vibe watch list` before touching a managed watch-- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`+- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches and command tasks both accept `--shell` and `--timeout` (per-cycle for watches, per-run for tasks), while `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay` stay watch-only- use `vibe task update <id>` to keep the same task ID while changing name, schedule, message, agent, or target- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options- Agent-facing collection commands return 20 compact rows per page, cap `--limit` at 100, and have no unpaginated `--all` mode; follow `pagination.next_command` when more rows exist@@ -966,6 +968,7 @@ Screenshots:Scheduled tasks:- `vibe task add`, `vibe task update`, `vibe task list [--include-finished] [--page N] [--limit N]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`+- Switching a task between message and command form, or changing `--on-failure`, is rejected — remove and recreate.Agent runs:@@ -976,7 +979,7 @@ Watches:- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--include-finished] [--page N] [--limit N]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`-For any subcommand, prefer `<command> --help` before composing a new invocation. Harness commands default to this Agent Session inside an Avibe-injected Agent shell. Use `--session-id` only to target a different existing Session, `--same-scope` or `--scope-id` when creating a Session in a visible scope, and `--no-callback` only when an async Agent run will be inspected later through `vibe runs`. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--sync`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy flags between task, watch, and agent-run commands without checking help.+For any subcommand, prefer `<command> --help` before composing a new invocation. Harness commands default to this Agent Session inside an Avibe-injected Agent shell. Use `--session-id` only to target a different existing Session, `--same-scope` or `--scope-id` when creating a Session in a visible scope, and `--no-callback` only when an async Agent run will be inspected later through `vibe runs`. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--sync`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). `vibe task add` also accepts `--shell` or a command after `--`, plus `--on-failure {none,agent}` and a per-run `--timeout`; a pure command task takes no session, scope, or agent flags. Do not copy flags between task, watch, and agent-run commands without checking help.## Troubleshootingdiff --git a/skills/use-vibe-remote/SKILL.md b/skills/use-vibe-remote/SKILL.mdindex 0a4f8b525..efc504ec0 100644--- a/skills/use-vibe-remote/SKILL.md+++ b/skills/use-vibe-remote/SKILL.md@@ -782,6 +782,8 @@ Preferred CLI shape:- recurring task for this conversation: `vibe task add --cron '<expr>' --message '...'`- one-off task for this conversation: `vibe task add --at '<ISO-8601>' --message '...'`- task that creates a visible sibling Session: `vibe task add --create-session --same-scope --cron '<expr>' --message '...'`+- scheduled command with no Agent turn: `vibe task add --cron '<expr>' --shell '<command>'`+- command task with AI failure triage: `vibe task add --cron '<expr>' --shell '<command>' --on-failure agent --message '<what to do>'`- immediate rerun: `vibe task run <id>`- managed background watch for this conversation: `vibe watch add --message '...' -- <cmd>` (or `--shell '<cmd>'` to pass a single shell string)- watch that creates a visible sibling Session: `vibe watch add --create-session --same-scope --message '...' -- <cmd>`@@ -803,7 +805,7 @@ Targeting and callbacks:- When a task, watch, or new Agent run creates a Session and `--cwd` is omitted, Avibe uses the command's current working directory. Forks keep the source Session cwd by default.- Async Agent runs return the final result to this conversation by default. Pass `--no-callback` only when you will inspect the run later with `vibe runs`. Pass `--callback-session-id <id>` only when the final result should return to a different Session.- `--message` and `--message-file` are the user-message flags for task, watch, and agent-run commands.-- `vibe task add` stores the message template and creates Agent Runs when the time trigger fires.+- `vibe task add` stores a message template — or, with `--shell` / a trailing `-- <argv>`, a command — and creates Runs when the time trigger fires. A command task runs with no Agent turn: silent on success, a failure notice on failure, `--on-failure agent` to escalate failures to an Agent.- `vibe watch add` uses `--message` as the instruction template for the Agent Run created after the waiter reaches a reportable state.- `--fork-self` forks this Session's native backend context. `--fork-session <id>` forks another explicit Session. Forks keep the source Session backend, scope, and cwd by default.- Fork overrides are intentionally narrow: `--agent`, `--model`, and `--reasoning-effort` can override the forked Session only if the backend stays the same. Do not combine fork flags with existing-session or session-creation flags.@@ -811,7 +813,7 @@ Targeting and callbacks:Operational guidance:- use `vibe task list` before editing or deleting an existing task; use `vibe watch list` before touching a managed watch-- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches accept additional flags like `--shell`, `--timeout` (per-cycle), `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay`+- if this is the first time using `vibe task add`, `vibe agent run`, `vibe runs`, or `vibe watch add`, read the matching `--help` output first — watches and command tasks both accept `--shell` and `--timeout` (per-cycle for watches, per-run for tasks), while `--lifetime-timeout` (overall), `--forever`, `--retry-exit-code`, and `--retry-delay` stay watch-only- use `vibe task update <id>` to keep the same task ID while changing name, schedule, message, agent, or target- use `vibe watch update <id> ...` when you must rename, retarget, or change the waiter/options- Agent-facing collection commands return 20 compact rows per page, cap `--limit` at 100, and have no unpaginated `--all` mode; follow `pagination.next_command` when more rows exist@@ -965,6 +967,7 @@ Screenshots:Scheduled tasks:- `vibe task add`, `vibe task update`, `vibe task list [--include-finished] [--page N] [--limit N]`, `vibe task show <id>`, `vibe task run <id>`, `vibe task pause <id>`, `vibe task resume <id>`, `vibe task remove <id>`+- Switching a task between message and command form, or changing `--on-failure`, is rejected — remove and recreate.Agent runs:@@ -975,7 +978,7 @@ Watches:- `vibe watch add`, `vibe watch update <id>`, `vibe watch list [--include-finished] [--page N] [--limit N]`, `vibe watch show <id>`, `vibe watch pause <id>`, `vibe watch resume <id>`, `vibe watch remove <id>`-For any subcommand, prefer `<command> --help` before composing a new invocation. Harness commands default to this Agent Session inside an Avibe-injected Agent shell. Use `--session-id` only to target a different existing Session, `--same-scope` or `--scope-id` when creating a Session in a visible scope, and `--no-callback` only when an async Agent run will be inspected later through `vibe runs`. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--sync`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). Do not copy flags between task, watch, and agent-run commands without checking help.+For any subcommand, prefer `<command> --help` before composing a new invocation. Harness commands default to this Agent Session inside an Avibe-injected Agent shell. Use `--session-id` only to target a different existing Session, `--same-scope` or `--scope-id` when creating a Session in a visible scope, and `--no-callback` only when an async Agent run will be inspected later through `vibe runs`. Use `--message` / `--message-file` for user messages. `vibe task add` and `vibe watch add` take `--name`; only `vibe task add` takes `--cron` / `--at` / `--timezone`; `vibe agent run` takes `--sync`; and `vibe watch add` takes its own waiter options (`--shell` or a positional command after `--`, `--cwd`, `--timeout`, `--forever`, `--lifetime-timeout`, `--retry-exit-code`, `--retry-delay`). `vibe task add` also accepts `--shell` or a command after `--`, plus `--on-failure {none,agent}` and a per-run `--timeout`; a pure command task takes no session, scope, or agent flags. Do not copy flags between task, watch, and agent-run commands without checking help.## Troubleshootingdiff --git a/storage/background.py b/storage/background.pyindex 7f43457c1..bc7e72444 100644--- a/storage/background.py+++ b/storage/background.py@@ -151,6 +151,53 @@ def _resolve_agent_identity_by_name(conn: Any, agent_name: Any) -> Optional[dictreturn {"id": str(row["id"]), "name": str(row["name"])}+def _pin_run_to_definition_agent(+ conn: Any,+ run_values: dict[str, Any],+ *,+ agent_name: Any,+) -> None:+ """Point a not-yet-inserted run row at the Agent its DEFINITION names now.++ Both stamp-plus-enqueue writers compose their run row LONG before the transaction+ opens: the escalation turn a command failure authorises, and the completion hook a+ terminal watch authorises, are built from the definition as the executor claimed+ it -- minutes or hours of command runtime earlier. A rename in that window rewrites+ ``run_definitions.agent_name`` and every ACTIVE run's reference (see+ ``core.vibe_agents._rewrite_references``), but this row does not exist yet, so it+ escapes the rewrite and is inserted naming an Agent the catalog no longer has.+ ``refresh_run_agent_reference`` then resolves nothing at claim time and the turn+ carrying the report cannot run -- while the notice its stamp suppressed is already+ gone. That is the one unrecoverable outcome the two-report invariant exists to+ prevent: neither report, not both.++ The narrower race -- a rename landing AFTER the payload was reloaded -- needs+ nothing here, because it bumps the definition's agent binding revision and+ ``definition_state_unchanged`` refuses the whole stamp, rolling both writes back.+ What survives that guard is a rename the reload already absorbed, leaving the+ definition current and only this pre-composed run row stale. So the name is read+ from the definition values being written in THIS transaction, and resolved to the+ catalog's durable ``agent_id`` so the NEXT rename cannot reopen the window. A row+ that already carries an ``agent_id`` is left alone: it is pinned by identity, which+ a rename does not move.+ """++ if str(run_values.get("agent_id") or "").strip():+ return+ name = str(agent_name or "").strip()+ if not name:+ return+ agent = _resolve_agent_identity_by_name(conn, name)+ if agent is None:+ # Archived or deleted, not renamed. Keep the definition's own spelling and+ # leave the claim to report it: inventing an id here would bind the turn to+ # an Agent the user removed.+ run_values["agent_name"] = name+ return+ run_values["agent_id"] = agent["id"]+ run_values["agent_name"] = agent["name"]++def resolve_run_at(run_at: str, timezone_name: Optional[str]) -> datetime:"""The instant a one-shot ``run_at`` names, in the task's own timezone.@@ -223,6 +270,16 @@ RUN_STATUS_ALIASES: dict[str, str] = {"canceled": "canceled",}_LIKE_ESCAPE = "\\"+# Every run status Session teardown condemns, which is deliberately WIDER than the+# set it terminalizes in the same statement. Teardown flags all four+# ``cancel_requested`` and then flips only ``pending``/``queued`` to ``canceled`` on+# the spot; a run the executor has already claimed is canceled a moment later, by the+# executor, out of that transaction. For anything that has to compensate for a+# teardown cancel, the decision is made here, so this is the set to key on.+# ``storage.sessions_service._delete_agent_session_rows`` uses this directly;+# ``_ACTIVE_RUN_STATUSES`` in ``storage.workbench_sessions_service`` still mirrors it+# to keep that module's import graph unchanged, so widen the two together.+TEARDOWN_CONDEMNED_RUN_STATUSES = ("pending", "queued", "processing", "running")# What a task/watch is *doing*, which is not what ``enabled`` records.## ``enabled`` is a switch: it says whether the scheduler may fire the row, and@@ -267,6 +324,17 @@ _TIMEOUT_EXIT_CODE = 124# read as "running" and leave "waiting" unreachable. Waiter liveness is a# separate field (``process_alive``), not a state._WATCH_RUNTIME_RUN_TYPE = "watch_runtime"+# The Agent turn a ``--on-failure agent`` command fire queues to REPORT its failure.+# It carries the failing definition's own ``definition_id`` -- that link is how the+# Harness shows the turn beside the task -- and it settles ``succeeded`` whenever the+# Agent answers, because answering is all it was asked to do.+_TASK_ESCALATION_RUN_TYPE = "task_escalation"+# Rows that carry a definition's id but are NOT a verdict on that definition. Both+# members present as the newest row for the definition and both settle ``succeeded``+# on their own schedule, so counted as verdicts they make a broken definition read+# healthy: the watch heartbeat on every service restart, the escalation turn on the+# very failure it exists to report.+_NON_VERDICT_RUN_TYPES = (_WATCH_RUNTIME_RUN_TYPE, _TASK_ESCALATION_RUN_TYPE)# SQLite caps how many parameters one statement may bind (999 on builds before# 3.32). Paged lookups stay far under it, but the unpaged harness lists resolve# every row in the store at once, so batch resolvers chunk their id lists: a few@@ -616,6 +684,20 @@ def _row_lifecycle_state(row: Any) -> Optional[str]:return None+def _definition_timed_out(metadata: Any) -> Optional[bool]:+ """Whether the scheduler stopped this definition's last fire, or ``None`` if unknown.++ Anything other than a real boolean reads as unknown: an absent key is a row from+ before the fact was recorded, and a corrupted one must not be trusted to overrule+ the exit code either way.+ """++ if not isinstance(metadata, dict):+ return None+ value = metadata.get(COMMAND_TIMED_OUT_METADATA_KEY)+ return value if isinstance(value, bool) else None++def definition_lifecycle_detail(*,lifecycle_state: Optional[str],@@ -623,6 +705,7 @@ def definition_lifecycle_detail(last_run_at: Any = None,last_exit_code: Any = None,last_error: Any = None,+ timed_out: Optional[bool] = None,) -> Optional[str]:"""How a finished task/watch ended: ``normal``, ``timeout``, or ``error``.@@ -630,13 +713,25 @@ def definition_lifecycle_detail(have no ending to report yet. Python rather than SQL because it has exactlyone consumer — the row — and never a ``GROUP BY``: the filter groups bystate, and the row alone says which of the three endings it was.++ ``timed_out`` is THE ANSWER when the row has one, and the three states are+ distinct on purpose. 124 is the code the runner synthesizes for a limit it+ enforced itself, but it is also an exit status a command is free to return —+ ``timeout 5 ...`` inside a ``--shell`` script returns exactly that — so reading+ the code alone told a user their backup had been cut short by Avibe when it had+ in fact cut itself short. ``False`` therefore SUPPRESSES the old inference rather+ than merely not triggering it; ``None`` means the row never recorded the fact+ (a watch, or a task stamped before this key existed) and keeps the inference,+ which is still the best guess available for those rows."""if lifecycle_state != "finished":return Noneif definition_type == "scheduled" and last_run_at is None:return None- if last_exit_code == _TIMEOUT_EXIT_CODE:+ if timed_out:+ return "timeout"+ if timed_out is None and last_exit_code == _TIMEOUT_EXIT_CODE:return "timeout"if last_exit_code not in (None, 0):return "error"@@ -876,6 +971,47 @@ NOTICE_FAILED = "failed"#: Terminal notice states: never delivered again, and no longer blocking a streak.NOTICE_TERMINAL_STATES = frozenset({NOTICE_SENT, NOTICE_SKIPPED, NOTICE_FAILED})+#: Where a command run records WHAT IT RAN, inside the run's own ``metadata``.+#: Entry: ``{"shell": str | None, "argv": list[str]}``. Read by+#: ``core.scheduled_tasks.command_snapshot_of_run`` and by the Workbench run detail.+COMMAND_SNAPSHOT_METADATA_KEY = "command"++#: Where a command run records the ISOLATED SUPERVISOR it spawned, so a service that+#: dies without unwinding can still find and kill the orphan on the next start.+#: Entry: the ``core.process_isolation.serialize_process_identity`` payload. Distinct+#: from the ``pid`` column, which holds the SERVICE pid and gates startup recovery.+COMMAND_WORKER_METADATA_KEY = "command_worker"++#: How many starts have tried and failed to kill that supervisor, inside the same+#: payload. Entry: a positive ``int``, absent until a teardown comes back unconfirmed.+#: It is what keeps "retry the orphan next start" from holding a run ``running``+#: forever when the process genuinely never exits.+COMMAND_WORKER_REAP_ATTEMPTS_KEY = "reap_attempts"++#: Whether the SCHEDULER stopped the DEFINITION's last command fire, on the definition's+#: own ``metadata``. Entry: ``True``/``False``, written by every command stamp and+#: absent on every row that predates it -- see ``definition_lifecycle_detail``, which+#: needs those three states apart.+COMMAND_TIMED_OUT_METADATA_KEY = "last_command_timed_out"+++def command_snapshot_from_definition_row(row: Any) -> Optional[dict[str, Any]]:+ """The ``{"shell", "argv"}`` record of what a scheduled definition row would run.++ ``None`` for anything that is not a command *task*: a message task has both+ columns NULL, and a watch fills them with its WAITER command, which is not the+ work a watch run performs.+ """++ if str(row["definition_type"] or "") != "scheduled":+ return None+ shell_command = row["shell_command"] or None+ argv = _json_loads(row["command_json"], None)+ argv = [str(part) for part in argv] if isinstance(argv, (list, tuple)) else []+ if not shell_command and not argv:+ return None+ return {"shell": str(shell_command) if shell_command else None, "argv": argv}+class _UnstampableInstant(str):"""A ``next_attempt_at`` that is not JSON text, carried through an expectation.@@ -1257,6 +1393,21 @@ def _not_an_out_of_band_interruption() -> Any:reason = literal_column(INTERRUPT_REASON_SQL)return or_(reason.is_(None), reason.notin_(sorted(RUN_INTERRUPTION_REASONS)))++def _is_a_definition_verdict() -> Any:+ """SQL for "this row's outcome is an outcome OF the definition it names".++ Shared by name across the health window, the streak scope and the last-success+ read, because those three answer one question -- how is this definition doing --+ and a row class excluded from one but not the others gives the same definition two+ different answers on two surfaces. See ``_NON_VERDICT_RUN_TYPES`` for the members.+ """++ return or_(+ agent_runs.c.run_type.is_(None),+ agent_runs.c.run_type.notin_(_NON_VERDICT_RUN_TYPES),+ )+#: Derived health, per definition. No new state: both counters come from one#: indexed query over ``agent_runs``, so nothing has to be kept in sync or#: backfilled.@@ -1294,6 +1445,29 @@ def _owed_failure_notice_for_transition(An existing notice is never overwritten. Re-stamping would reset ``attempts``and resurrect a dead letter, so a row that already carries a notice keeps theone it has whatever later writer touches it.++ ``escalation_run_id`` SUPPRESSES the notice, the same shape of decision+ ``_callback_parent_owns_failure_notice`` makes: a command definition configured+ with ``--on-failure agent`` already had one Agent turn queued -- carrying the+ failure report -- in the SAME transaction that stamped its definition, so a notice+ as well is the identical failure told twice, once as a report and once as an alert.++ ACCEPTED CRASH WINDOW, stated rather than hidden. The escalation is durable before+ this settle runs, and the marker only reaches the run row here, so a teardown+ between the atomic stamp+enqueue and this settle loses the marker: the escalation+ still fires AND a notice is stamped. That is the deliberate direction -- both,+ never neither. A cross-row lookup ("does some queued run name me as its parent?")+ would close the duplicate at the cost of the never-silent bias, and the duplicate+ is the cheaper failure.++ THE OPPOSITE ORDERING NEEDS NO GUARD HERE, and the reason is worth stating because+ it looks like it should. A teardown that cancels the escalation in that same window+ cancels the PARENT with it -- ``archive_session`` flags every non-terminal run of+ the session, and the hard-delete path removes their rows -- so this settle sees+ ``canceled`` (or no row at all) and owes nothing to suppress. Checking the+ escalation's status from here would only describe ``vibe runs cancel`` aimed at the+ escalation itself, which is the user declining that report the same way+ ``canceled`` above declines a notice."""if normalize_run_status(status) != "failed":@@ -1301,6 +1475,9 @@ def _owed_failure_notice_for_transition(existing = metadata.get(OWED_FAILURE_NOTICE_KEY)if isinstance(existing, dict) and str(existing.get("state") or "").strip():return None+ if str(metadata.get("escalation_run_id") or "").strip():+ # The escalation turn IS the user-visible report for this failure.+ return Nonereason = str(metadata.get("interrupt_reason") or "").strip() or Nonereturn {"state": NOTICE_PENDING,@@ -1357,6 +1534,104 @@ def _owed_failure_notice_for_transition(}+def rearm_notices_for_escalations_canceled_with_session(+ conn: Any, session_id: str, *, now: str+) -> list[str]:+ """Give a failed command fire its notice back when teardown kills its escalation.++ An ``--on-failure agent`` fire suppresses its own failure notice because the+ escalation turn IS the report (``_owed_failure_notice_for_transition``). Session+ teardown then cancels every not-yet-terminal run bound to the session -- the+ escalation among them -- and a ``canceled`` run owes nothing. Without this, the+ failure ends up with NO turn and NO notice: the exactly-one-of invariant broken in+ the silent direction, which is the one direction the design refuses. The accepted+ crash window biases towards BOTH reports; this must not bias towards neither.++ The notice ladder is the right fallback precisely because it does not need the+ session: a notice is delivered to the scope, not into a conversation.++ Escalations teardown has merely condemned count too, not only the ones it+ terminalizes on the spot (``TEARDOWN_CONDEMNED_RUN_STATUSES``). A turn already+ under way is the worse case, since it can have reported nothing yet while looking+ like it will. Re-arming one that did manage to report costs a duplicate, which is+ the bias the design already accepts; the alternative costs silence, which it does+ not.++ MUST be called inside the SAME transaction as the cancel it compensates for. Two+ commits are not one decision: a teardown that committed the cancel and then failed+ here would leave exactly the silence this closes.++ ``escalation_run_id`` is deliberately LEFT on the parent. It is the audit trail of+ what was attempted, and the row is then honest about both facts -- it escalated,+ the escalation died, a notice is owed. Returns the parents it re-armed.+ """++ normalized = str(session_id or "").strip()+ if not normalized:+ return []+ doomed = (+ conn.execute(+ select(agent_runs.c.parent_run_id)+ .where(agent_runs.c.session_id == normalized)+ .where(agent_runs.c.run_type == "task_escalation")+ # Not just the queued ones. An escalation the executor had already claimed+ # is condemned by this same teardown, only terminalized later and+ # elsewhere -- and it is the worse case, because a turn killed mid-flight+ # can have reported nothing while still looking like it was under way.+ .where(agent_runs.c.status.in_(TEARDOWN_CONDEMNED_RUN_STATUSES))+ )+ .scalars()+ .all()+ )+ rearmed: list[str] = []+ for raw_parent_id in doomed:+ parent_id = str(raw_parent_id or "").strip()+ if not parent_id:+ continue+ parent = (+ conn.execute(+ select(agent_runs.c.status, agent_runs.c.metadata_json)+ .where(agent_runs.c.id == parent_id)+ .limit(1)+ )+ .mappings()+ .first()+ )+ if parent is None:+ continue+ metadata = _json_loads(parent["metadata_json"], {})+ if not isinstance(metadata, dict):+ continue+ # The marker is withheld from the BUILDER, not from the row: it exists only to+ # suppress this notice in favour of a turn that is being canceled in this very+ # transaction, so for the purpose of deciding what is owed it no longer applies.+ # Everything else is passed through untouched so the interruption/failure lane+ # still picks the identity the live path would have used.+ notice = _owed_failure_notice_for_transition(+ parent_id,+ status=parent["status"],+ metadata={+ key: value+ for key, value in metadata.items()+ if key != "escalation_run_id"+ },+ now=now,+ )+ if notice is None:+ # Not a failure, or it already owes one. Either way nothing is missing.+ continue+ metadata[OWED_FAILURE_NOTICE_KEY] = notice+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == parent_id)+ .values(metadata_json=_json_dumps(metadata), updated_at=now)+ )+ rearmed.append(parent_id)+ if rearmed:+ _defer_run_ids_updated_from_connection(conn, rearmed)+ return rearmed++def _callback_parent_owns_failure_notice(conn: Any,*,@@ -2516,10 +2791,81 @@ class SQLiteBackgroundTaskStore:values = self._watch_values(payload)run_values = self._run_values(run_payload)with run_update_event_transaction(self.engine) as conn:+ reserve_write_lock(conn)if not upsert_definition_in_connection(conn, values, expect=expect, definition_type="watch"):return False+ _pin_run_to_definition_agent(+ conn, run_values, agent_name=values.get("agent_name")+ )+ enqueue_run_in_connection(conn, run_values)+ return True++ def upsert_scheduled_task_with_queued_run(+ self,+ payload: dict[str, Any],+ *,+ expect: DefinitionWriteExpectation | None,+ run_payload: dict[str, Any],+ expected_uncanceled_run_id: Optional[str] = None,+ ) -> bool:+ """A guarded task stamp and the outbox row it authorises, ONE transaction.++ The twin of ``upsert_watch_with_queued_run``, and HFR-269 is the same bug on+ the scheduled side: two commits are not one decision.++ self.store.mark_task_result(...) # transaction 1, COMMITS+ self.request_store.enqueue_hook_send(...) # transaction 2, COMMITS++ A ``/new`` reclaim or an archive from another connection can commit in the gap.+ The stamp is accepted -- it won its compare-and-set fairly, before the teardown+ -- and the escalation turn is queued afterwards anyway, against a definition the+ database has since paused or soft-deleted. The inverse is the other half: an+ exception between the two commits leaves a failed one-shot ``at`` task durably+ DISABLED with the failure report that explains it LOST, so the user is never+ told why the task they scheduled never came back.++ Here they are one: the outbox row is written on the same connection, after the+ guard, and a refusal or an exception rolls BOTH back. ``False`` means nothing+ was written; the definition is untouched and no queued run exists.++ Deliberately NOT ``enqueue_definition_run``: that writer re-reads the+ definition server-side and RAISES on a disabled one, and the stamp in this very+ transaction is what disables a failed one-shot.++ ``expected_uncanceled_run_id`` is the PARENT fire, re-read here rather than in+ the caller for the same reason ``cancel_not_requested`` is a SQL predicate: a+ ``vibe runs cancel`` committed while the command was exiting sets the flag from+ another connection, and the caller's snapshot is older than this write. Without+ the re-read the flag could land after the command returned and before this+ stamp, and the run then settled as ``canceled`` while this transaction had+ already marked the definition failed and durably queued an Agent turn -- a+ stopped run that goes on to start follow-up work. Refusing leaves the outcome+ to the terminal projection lane, which is where a canceled fire belongs.+ """++ values = self._scheduled_task_values(payload)+ run_values = self._run_values(run_payload)+ with run_update_event_transaction(self.engine) as conn:+ reserve_write_lock(conn)+ if expected_uncanceled_run_id and agent_run_cancellation_won_in_connection(+ conn, expected_uncanceled_run_id+ ):+ return False+ if not upsert_definition_in_connection(+ # Only the refusal LOG's label; the row's ``definition_type`` column+ # comes from ``_scheduled_task_values``. Spelled the way the rest of+ # the scheduled family spells it.+ conn,+ values,+ expect=expect,+ definition_type="scheduled task",+ ):+ return False+ _pin_run_to_definition_agent(+ conn, run_values, agent_name=values.get("agent_name")+ )enqueue_run_in_connection(conn, run_values)return True@@ -2560,6 +2906,7 @@ class SQLiteBackgroundTaskStore:reserve_write_lock(conn)definition = conn.execute(select(+ run_definitions.c.definition_type,run_definitions.c.agent_name,run_definitions.c.session_policy,run_definitions.c.session_id,@@ -2570,6 +2917,8 @@ class SQLiteBackgroundTaskStore:run_definitions.c.message,run_definitions.c.message_payload_json,run_definitions.c.metadata_json,+ run_definitions.c.command_json,+ run_definitions.c.shell_command,run_definitions.c.enabled,run_definitions.c.deleted_at,)@@ -2588,6 +2937,18 @@ class SQLiteBackgroundTaskStore:metadata = _json_loads(definition["metadata_json"], {})if not isinstance(metadata, dict):metadata = {}+ # A run is an immutable record of one execution, so WHAT it executed+ # belongs on it -- the definition it came from is editable and+ # deletable, and the failure-notice drain reads long after the fire.+ # Taken here rather than trusted from the caller because this method+ # replaces the caller's metadata wholesale with the authoritative row,+ # and a snapshot a caller can forget to pass is a snapshot production+ # will be missing.+ snapshot = command_snapshot_from_definition_row(definition)+ if snapshot is not None:+ metadata[COMMAND_SNAPSHOT_METADATA_KEY] = snapshot+ else:+ metadata.pop(COMMAND_SNAPSHOT_METADATA_KEY, None)values.update(agent_name=identity["name"] if identity else current_name,agent_id=identity["id"] if identity else None,@@ -2988,6 +3349,15 @@ class SQLiteBackgroundTaskStore:run_definitions.c.schedule_type,run_definitions.c.cron,run_definitions.c.run_at,+ # A command task's instruction lives here, not in+ # ``message``/``prompt`` -- which it may leave empty, since+ # nothing is being said to an Agent. Without these two the only+ # text that distinguishes such a row is the one text search+ # would not read. ``cwd`` stays out on purpose (the ``watch``+ # branch keeps it): task rows overwhelmingly share one working+ # directory, so matching on it returns almost everything.+ run_definitions.c.command_json,+ run_definitions.c.shell_command,])elif definition_type == "watch":@@ -3126,14 +3496,65 @@ class SQLiteBackgroundTaskStore:_publish_queue_updated(queue_session_id)return row_to_publish is not None+ def _escalates_a_stopped_fire(self, conn: Any, row: Any) -> bool:+ """Is this claim about to start an Agent turn for a fire the user stopped?++ A failed ``--on-failure agent`` fire commits its stamp and its escalation in ONE+ transaction guarded on the fire not being cancelled, and whoever settles that+ fire ``canceled`` takes the escalation back+ (``_retract_escalation_of_stopped_fire``). Between those two moments the+ escalation is a queued row like any other, so the dispatch loop can claim it --+ and a claim is the one transition retraction cannot undo, because+ ``cancel_run`` on a running Agent Run only writes a flag that nothing in the+ turn lane is watching. The stopped job would then answer by starting an Agent.++ So the claim asks the question itself, from the parent row, inside the+ transaction that would otherwise start the work: the escalation exists only to+ report ITS fire, and a fire the user stopped has nothing to report. Read from+ ``run_type`` plus ``parent_run_id`` -- the durable linkage the stamp wrote --+ rather than from anything the retraction has to reach first, so the ordering+ between the two lanes stops mattering.++ ``cancel_requested`` counts as well as a written ``canceled``: the flag is what+ the fire's own settlement normalizes from, and it is set the instant the user+ asks, which is earlier than any status this could wait for. A shutdown-+ interrupted fire carries no flag, so its escalation is still claimed -- there+ the report IS owed.+ """++ if str(row["run_type"] or "").strip() != "task_escalation":+ return False+ parent_run_id = str(row["parent_run_id"] or "").strip()+ if not parent_run_id:+ return False+ parent = conn.execute(+ select(agent_runs.c.status, agent_runs.c.cancel_requested)+ .where(agent_runs.c.id == parent_run_id)+ .limit(1)+ ).mappings().first()+ if parent is None:+ return False+ return bool(parent["cancel_requested"]) or normalize_run_status(parent["status"]) == "canceled"+def claim_pending_run(self, run_id: str, *, started_at: str) -> Optional[dict[str, Any]]:row_to_publish = Nonepayload = Nonewith self.engine.begin() as conn:+ # BEFORE the reads this claim decides on, because one of them is now+ # another row: an escalation's parent fire, which a concurrent+ # ``cancel_run`` writes. Holding the writer from the start means the+ # decision cannot rest on a snapshot that goes stale before the UPDATE+ # lands -- in WAL mode that is not a lost update but an unretryable+ # ``SQLITE_BUSY_SNAPSHOT`` on the claim itself.+ reserve_write_lock(conn)row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()if not row:return None- if bool(row["cancel_requested"]) or normalize_run_status(row["status"]) == "canceled":+ if (+ bool(row["cancel_requested"])+ or normalize_run_status(row["status"]) == "canceled"+ or self._escalates_a_stopped_fire(conn, row)+ ):conn.execute(update(agent_runs).where(agent_runs.c.id == run_id)@@ -3194,6 +3615,130 @@ class SQLiteBackgroundTaskStore:_publish_run_rows_updated([row_to_publish])return row_to_publish is not None+ def merge_running_run_metadata(+ self,+ run_id: str,+ key: str,+ value: Optional[dict[str, Any]],+ ) -> bool:+ """Set (or drop) ONE key on a ``running`` run's metadata document.++ Restricted to ``running`` rows because every caller is an in-flight execution+ describing itself: a terminal run's worker is by definition already gone, and+ re-stamping one would hand startup recovery a pid that has since been+ recycled.++ Read-modify-write of ``metadata_json`` inside one transaction: the column is+ a whole-blob JSON document, so a bare UPDATE of the key would drop whatever+ the enqueue and the notice machinery put there.+ """++ now = _utc_now_iso()+ with self.engine.begin() as conn:+ row = conn.execute(+ select(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(agent_runs.c.status.in_(_status_query_values("running")))+ .limit(1)+ ).mappings().first()+ if not row:+ return False+ metadata = _json_loads(row["metadata_json"], {})+ if not isinstance(metadata, dict):+ metadata = {}+ if value is None:+ if key not in metadata:+ return False+ metadata.pop(key, None)+ else:+ metadata[key] = dict(value)+ result = conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == run_id)+ .where(agent_runs.c.status.in_(_status_query_values("running")))+ .values(metadata_json=_json_dumps(metadata), updated_at=now)+ )+ return bool(result.rowcount)++ def record_command_worker(+ self,+ run_id: str,+ identity: Optional[dict[str, Any]],+ ) -> bool:+ """Remember (or forget) the isolated supervisor a command run has spawned.++ Written the instant the child exists and cleared the instant it is reaped, so+ the window in which a SIGKILLed service leaves an untracked orphan is the+ spawn itself.+ """++ return self.merge_running_run_metadata(+ run_id, COMMAND_WORKER_METADATA_KEY, identity+ )++ def record_command_snapshot(+ self,+ run_id: str,+ snapshot: Optional[dict[str, Any]],+ ) -> bool:+ """Re-stamp what this run is ABOUT TO RUN, over what its enqueue predicted.++ The enqueue writes the snapshot from the definition row as it stood then, but+ the executor re-reads the definition after claiming the run -- so an edit+ committed in the enqueue-to-claim window left the run naming command A while+ command B ran, and the notice, the escalation prompt and the Workbench run+ detail all repeated that wrong answer with the authority of a snapshot.++ Called from the execution path with the exact definition instance being+ executed, which is the only object that can settle the question.+ """++ return self.merge_running_run_metadata(+ run_id, COMMAND_SNAPSHOT_METADATA_KEY, snapshot+ )++ def list_running_command_workers(self) -> list[dict[str, Any]]:+ """Every ``running`` run that still names a command worker.++ Called at startup BEFORE ``recover_processing_runs`` settles these rows, which+ is the only moment the association between a run and its orphaned child is+ still on disk. A failure here is not a licence to settle them: the caller+ leaves the records untouched, and ``recover_processing_runs`` reads the record+ off each row rather than trusting this list.++ Also called per fire, to ask whether the definition about to run still has a+ worker recorded from an earlier one -- hence ``definition_id`` in each entry.+ Without it a caller can see that *some* worker survives but not whose, and "some+ command is running" is not a reason to skip a different one.+ """++ with self.engine.connect() as conn:+ rows = list(+ conn.execute(+ select(+ agent_runs.c.id,+ agent_runs.c.definition_id,+ agent_runs.c.metadata_json,+ ).where(agent_runs.c.status.in_(_status_query_values("running")))+ ).mappings()+ )+ workers: list[dict[str, Any]] = []+ for row in rows:+ metadata = _json_loads(row["metadata_json"], {})+ if not isinstance(metadata, dict):+ continue+ identity = metadata.get(COMMAND_WORKER_METADATA_KEY)+ if isinstance(identity, dict):+ definition_id = row["definition_id"]+ workers.append(+ {+ "run_id": str(row["id"]),+ "definition_id": str(definition_id) if definition_id else None,+ "identity": identity,+ }+ )+ return workers+def update_run_status(self,run_id: str,@@ -3772,6 +4317,9 @@ class SQLiteBackgroundTaskStore:task_id: Optional[str] = None,session_key: Optional[str] = None,session_id: Optional[str] = None,+ exit_code: Optional[int] = None,+ stdout: Optional[str] = None,+ stderr: Optional[str] = None,) -> Optional[str]:"""Terminalize a non-terminal run in one guarded write.@@ -3795,6 +4343,12 @@ class SQLiteBackgroundTaskStore:the completion through this guarded writer would lose them on exactly therows another actor settled first.+ ``exit_code`` / ``stdout`` / ``stderr`` are the opposite kind of value: a+ command run's OUTCOME. They ride the guarded transition alongside ``error``,+ so a run another actor already settled -- a ``vibe runs cancel`` that won the+ race, say -- does not have its terminal story overwritten by the losing fire's+ output.+Returns the terminal status actually written, or ``None`` when nothing waswritten (already terminal, deferred, or missing)."""@@ -3846,6 +4400,12 @@ class SQLiteBackgroundTaskStore:values["error"] = str(error)if result_text is not None:values["result_text"] = str(result_text)+ if exit_code is not None:+ values["exit_code"] = int(exit_code)+ if stdout is not None:+ values["stdout"] = str(stdout)+ if stderr is not None:+ values["stderr"] = str(stderr)_merge_owed_failure_notice(values,conn=conn,@@ -4032,6 +4592,25 @@ class SQLiteBackgroundTaskStore:_publish_run_rows_updated([row_to_publish])return transitioned+ def find_escalation_run(self, *, parent_run_id: str) -> Optional[dict[str, Any]]:+ """Return the escalation Run one failed command fire queued.++ ``run_type`` plus ``parent_run_id`` is the durable linkage: the escalation is+ inserted by the stamp transaction carrying both, so it is findable from the fire+ even by a caller that never saw the enqueue -- a settlement reached through a+ ``CancelledError``, or a later pass entirely.+ """++ with self.engine.connect() as conn:+ row = conn.execute(+ select(agent_runs)+ .where(agent_runs.c.run_type == "task_escalation")+ .where(agent_runs.c.parent_run_id == parent_run_id)+ .order_by(agent_runs.c.created_at, agent_runs.c.id)+ .limit(1)+ ).mappings().first()+ return self._run_from_row(row) if row else None+def find_callback_run(self,*,@@ -4059,6 +4638,23 @@ class SQLiteBackgroundTaskStore:interrupt_reason: str,cancellation_error: str,) -> None:+ """Settle every run a dead service left ``running``, except live workers.++ A run that STILL CARRIES a ``command_worker`` record is left alone: that+ record is readable only while the row is ``running``, so settling it here+ would strip a surviving orphan's only durable name, and no later start could+ find that process even in principle.++ THE ROW ITSELF IS THE PREDICATE, not a set passed in by the caller. The+ recovery pass runs after ``_reap_orphaned_command_workers``, which decides+ each worker's fate by WRITING it -- cleared once the process is proven dead+ or the retries are spent, re-stamped while it may still be running -- so the+ surviving record is already the answer, read here inside the very transaction+ that would otherwise settle the row. Asking a separate query instead made a+ momentary read failure ("I could not enumerate") mean "there is nothing to+ protect", which is the one mistake whose damage cannot be undone.+ """+with run_update_event_transaction(self.engine) as conn:now = _utc_now_iso()rows = list(@@ -4078,6 +4674,11 @@ class SQLiteBackgroundTaskStore:):continuerun_id = str(row["id"])+ row_metadata = _json_loads(row["metadata_json"], {})+ if isinstance(row_metadata, dict) and row_metadata.get(+ COMMAND_WORKER_METADATA_KEY+ ):+ continueif row["pid"] is None:requeued_ids.append(run_id)continue@@ -4900,7 +5501,9 @@ class SQLiteBackgroundTaskStore:``succeeded`` on every write, and a ``succeeded`` row bearing the watch's``definition_id`` sitting between two failures CLOSES the streak, so everywatch failure would read as a first failure and notify. Fixing only the- deferral predicate would trade a permanent silence for daily spam.+ deferral predicate would trade a permanent silence for daily spam. An+ escalation turn is the same shape one definition type along: it settles+ ``succeeded`` between two failed fires of the command that queued it.Interruptions are dropped HERE, in SQL, rather than while classifying: theyare transparent to a streak — neither joining one nor closing one — so a row@@ -4912,12 +5515,7 @@ class SQLiteBackgroundTaskStore:return (select(*columns).where(agent_runs.c.definition_id == definition_id)- .where(- or_(- agent_runs.c.run_type.is_(None),- agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,- )- )+ .where(_is_a_definition_verdict()).where(_not_an_out_of_band_interruption()))@@ -5282,10 +5880,12 @@ class SQLiteBackgroundTaskStore:# because the ``LIMIT`` is applied to whatever the predicates let through —# anything the classifier would ignore must never reach it:#- # 1. the watch supervisor heartbeat (``run_type = watch_runtime``), which shares- # the watch's ``definition_id``, is refreshed to the waiter's ``started_at``- # on every restart, and flips its predecessor to ``succeeded`` — so it both- # presents as the newest "run" and closes a failure streak;+ # 1. rows that carry a definition's id without being a verdict on it+ # (``_NON_VERDICT_RUN_TYPES``): the watch supervisor heartbeat, refreshed to the+ # waiter's ``started_at`` on every restart and flipping its predecessor to+ # ``succeeded``; and the ``--on-failure agent`` escalation turn, which settles+ # ``succeeded`` when the Agent answers — on the very failure it was queued to+ # report. Both present as the newest "run" AND close a failure streak;# 2. nonterminal executions: a failing recurring definition's next fire is the# newest row for the definition and is not an outcome, so reading "the latest# run failed" off it reports an actively failing definition as healthy for the@@ -5326,21 +5926,20 @@ class SQLiteBackgroundTaskStore:batch with one value, so without the secondary key "the last success" is whicheverrow SQLite happens to return first).- ``watch_runtime`` is excluded for the same reason the health window excludes it:- the supervisor heartbeat is not the definition succeeding, and it flips to- ``succeeded`` on every restart — so without this term a permanently broken watch- would report a fresh "last succeeded" instant on every service restart.+ NON-VERDICT ROW CLASSES ARE EXCLUDED for the same reason the health window+ excludes them (``_NON_VERDICT_RUN_TYPES``), and this read is where the damage is+ most direct, because the instant it returns is printed in the notice as the last+ time the thing WORKED: the supervisor heartbeat is not the watch succeeding and+ flips to ``succeeded`` on every restart, so a permanently broken watch would+ report a fresh instant per restart; and a ``--on-failure agent`` escalation is+ not the command succeeding — it succeeds by REPORTING that the command failed —+ so the notice would date the outage from the report of the outage."""statement = (select(_SETTLED_AT).where(agent_runs.c.definition_id == str(definition_id))- .where(- or_(- agent_runs.c.run_type.is_(None),- agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,- )- )+ .where(_is_a_definition_verdict()).where(agent_runs.c.status.in_(_status_query_values("succeeded"))).order_by(_SETTLED_AT.desc(), agent_runs.c.id.desc()).limit(1)@@ -5417,12 +6016,7 @@ class SQLiteBackgroundTaskStore:# Correlated to the id currently being iterated, which is what makes the# LIMIT below per-definition rather than per-batch..where(agent_runs.c.definition_id == id_list.c.value)- .where(- or_(- agent_runs.c.run_type.is_(None),- agent_runs.c.run_type != _WATCH_RUNTIME_RUN_TYPE,- )- )+ .where(_is_a_definition_verdict()).where(agent_runs.c.status.in_(verdicts)).where(settled_at >= cutoff)# The same expression the streak read excludes interruptions with, shared@@ -5664,12 +6258,14 @@ class SQLiteBackgroundTaskStore:"cron": payload.get("cron"),"run_at": payload.get("run_at"),"timezone": payload.get("timezone") or "UTC",- "command_json": None,- "shell_command": None,+ # Command tasks reuse the watch columns, but None-preserving: a message+ # task must keep every one of them NULL (no watch-style defaults here).+ "command_json": _json_dumps(payload["command"]) if payload.get("command") else None,+ "shell_command": payload.get("shell_command"),"prefix": None,"cwd": payload.get("cwd"),"mode": None,- "timeout_seconds": None,+ "timeout_seconds": float(payload["timeout_seconds"]) if payload.get("timeout_seconds") is not None else None,"lifetime_timeout_seconds": None,"retry_exit_codes_json": None,"retry_delay_seconds": None,@@ -5686,7 +6282,10 @@ class SQLiteBackgroundTaskStore:"last_run_at": payload.get("last_run_at"),"last_run_id": payload.get("last_run_id"),"last_error": payload.get("last_error"),- "last_exit_code": None,+ # Runtime state, but written through the same FULL-ROW upsert every+ # definition edit uses: hardcoding None here would silently clear a+ # recorded exit code on the next unrelated write.+ "last_exit_code": payload.get("last_exit_code"),"metadata_json": _json_dumps(payload.get("metadata") or {}),}@@ -5798,6 +6397,10 @@ class SQLiteBackgroundTaskStore:"cron": row["cron"],"run_at": row["run_at"],"timezone": row["timezone"] or "UTC",+ "shell_command": row["shell_command"],+ "command": _json_loads(row["command_json"], None),+ "timeout_seconds": float(row["timeout_seconds"]) if row["timeout_seconds"] is not None else None,+ "last_exit_code": row["last_exit_code"],"enabled": bool(row["enabled"]),"created_at": row["created_at"],"updated_at": row["updated_at"],@@ -6018,6 +6621,7 @@ class SQLiteBackgroundTaskStore:last_run_at=row.get("last_run_at"),last_exit_code=row.get("last_exit_code"),last_error=row.get("last_error"),+ timed_out=_definition_timed_out(row.get("metadata")),)row["next_run_at"] = compute_next_run_at(enabled=bool(row.get("enabled")),diff --git a/storage/sessions_service.py b/storage/sessions_service.pyindex f9409c2bc..f21ab20f3 100644--- a/storage/sessions_service.py+++ b/storage/sessions_service.py@@ -2233,6 +2233,46 @@ def _delete_agent_session_rows(session_id,)continue+ now = _utc_now_iso()+ # BEFORE the history branch, because both halves end this Session's ability to+ # run anything: the archival half cancels its queued runs outright, and the+ # delete half removes the row they are bound to. A queued command-task+ # escalation suppressed its parent's failure notice on the promise that the turn+ # would carry the report, so either way that report is now impossible and the+ # failure has to fall back to the notice ladder -- which does not need the+ # Session, since a notice is delivered to the scope. Same reason as the archive+ # path in ``workbench_sessions_service``, and in this same transaction.+ #+ # The delete half used to be the quieter of the two: it cancelled nothing, so+ # the escalation was left queued against a row that no longer exists and no+ # cancel-shaped guard could ever see it. The cancel below closes that.+ from storage.background import (+ TEARDOWN_CONDEMNED_RUN_STATUSES,+ rearm_notices_for_escalations_canceled_with_session,+ )++ rearm_notices_for_escalations_canceled_with_session(conn, session_id, now=now)+ # Also before the branch, and for the same reason. ``agent_runs.session_id``+ # carries no foreign key, so deleting the Session row leaves its runs ``queued``+ # and claimable against a Session that is gone -- and for an escalation that is+ # not merely untidy: the re-arm just above handed the failure to the notice+ # ladder on the grounds that the turn can never run, so a turn that IS claimed+ # and then dies on the missing Session reports the same failure twice, the+ # second time from the lane meant to replace the first. Terminalizing here is+ # what makes that premise true. In-flight runs are cancel-requested only; the+ # executor owns the transition for work it has already claimed.+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.session_id == session_id)+ .where(agent_runs.c.status.in_(TEARDOWN_CONDEMNED_RUN_STATUSES))+ .values(cancel_requested=1, cancel_requested_at=now, updated_at=now)+ )+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.session_id == session_id)+ .where(agent_runs.c.status.in_(("pending", "queued")))+ .values(status="canceled", completed_at=now, updated_at=now)+ )has_retained_history = bool(conn.execute(select(messages.c.id)@@ -2261,19 +2301,6 @@ def _delete_agent_session_rows(else f"superseded:{session_id}"))- now = _utc_now_iso()- conn.execute(- update(agent_runs)- .where(agent_runs.c.session_id == session_id)- .where(agent_runs.c.status.in_(("pending", "queued", "processing", "running")))- .values(cancel_requested=1, cancel_requested_at=now, updated_at=now)- )- conn.execute(- update(agent_runs)- .where(agent_runs.c.session_id == session_id)- .where(agent_runs.c.status.in_(("pending", "queued")))- .values(status="canceled", completed_at=now, updated_at=now)- )retire_session_delivery_owners(conn, session_id)delivery_store.set_draft(conn, session_id, None)retained = conn.execute(diff --git a/storage/workbench_sessions_service.py b/storage/workbench_sessions_service.pyindex 234de5ddb..0acadb3a7 100644--- a/storage/workbench_sessions_service.py+++ b/storage/workbench_sessions_service.py@@ -52,6 +52,9 @@ from storage.models import ()# Raw ``agent_runs.status`` values that are not yet terminal — archive cancels these.+# Mirrors ``background.TEARDOWN_CONDEMNED_RUN_STATUSES``, which the compensating logic+# for these cancels keys on (an escalation cancelled here owes its parent a failure+# notice back); widen the two together, and do not narrow this one alone._ACTIVE_RUN_STATUSES = ("pending", "queued", "processing", "running")_PENDING_RUN_STATUSES = ("pending", "queued")@@ -1162,6 +1165,16 @@ def archive_session(conn: Connection, session_id: str) -> dict[str, Any]:# cancel-requested (the executor honors it for in-flight ones) and# terminalize the ones that haven't started.if reclaimed["runs"]:+ # BEFORE the cancel, and in this same transaction: a queued command-task+ # escalation is the only user-visible report of a failure whose own notice it+ # suppressed, so cancelling it silently would leave that failure reported by+ # nothing. This hands it back to the notice ladder, which does not need the+ # session being torn down.+ from storage.background import (+ rearm_notices_for_escalations_canceled_with_session,+ )++ rearm_notices_for_escalations_canceled_with_session(conn, session_id, now=now)conn.execute(update(agent_runs).where(agent_runs.c.session_id == session_id)diff --git a/tests/scenarios/INDEX.yaml b/tests/scenarios/INDEX.yamlindex 3dbccad25..5cd0834dc 100644--- a/tests/scenarios/INDEX.yaml+++ b/tests/scenarios/INDEX.yaml@@ -39,6 +39,18 @@ capabilities:- tests/test_agent_run_target.py- tests/test_watches.py- tests/test_cli_watch_command.py+ - id: harness_command_task+ name: Scheduled command tasks and their failure visibility+ status: active+ catalog: tests/scenarios/harness_command_task/catalog.yaml+ observations: tests/scenarios/harness_command_task/observations.yaml+ scenario_tests:+ - tests/test_harness_failure_visibility.py+ - tests/test_scheduled_command_task_integration.py+ unit_or_contract_tests:+ - tests/test_command_runner.py+ - tests/test_cli_task_command.py+ - tests/test_scheduled_tasks.py- id: auth_setupname: IM-driven backend auth recoverystatus: activediff --git a/tests/scenarios/harness_command_task/catalog.yaml b/tests/scenarios/harness_command_task/catalog.yamlnew file mode 100644index 000000000..2aec703ff--- /dev/null+++ b/tests/scenarios/harness_command_task/catalog.yaml@@ -0,0 +1,512 @@+version: 1+capability:+ id: harness_command_task+ name: Scheduled command tasks and their failure visibility+ canonical_tests:+ - tests/test_harness_failure_visibility.py+ - tests/test_scheduled_command_task_integration.py+ - tests/test_scheduled_tasks.py+ - tests/test_command_runner.py+ - tests/test_cli_task_command.py+ shared_harness: []+status_legend:+ covered: deterministic scenario or contract coverage exists+ manual: validated in the local Incus black-box environment+ planned: scenario id reserved, coverage not written yet+scenarios:+ - id: SCT-001+ name: a failed command fire produces exactly one command-aware failure notice+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_harness_failure_visibility.py::test_a_failed_command_fire_delivers_exactly_one_command_aware_notice+ - id: SCT-002+ name: a successful command fire notifies nowhere+ status: covered+ kind: success+ layer: scenario+ backend: shared+ test: tests/test_harness_failure_visibility.py::test_a_successful_command_fire_notifies_nowhere+ - id: SCT-003+ name: an escalated command failure produces one Agent turn and zero notices+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_failed_on_failure_agent_command_fire_queues_exactly_one_escalation+ # The drain half of the same scenario -- a failed run carrying the escalation+ # marker is never delivered a notice:+ # tests/test_harness_failure_visibility.py::test_an_escalated_command_failure_is_never_delivered_a_notice+ - id: SCT-004+ name: a reclaim committed mid-command refuses the stamp and escalates nowhere+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_reclaim_during_the_command_refuses_the_stamp_and_escalates_nowhere+ - id: SCT-005+ name: session teardown hands a killed escalation's failure back to the notice ladder+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_archiving_the_session_gives_a_killed_escalation_its_notice_back+ # The other teardown path -- ``/new`` hard-deleting an empty Session, which+ # orphans the escalation instead of cancelling it:+ # tests/test_scheduled_tasks.py::test_hard_deleting_the_session_gives_a_killed_escalation_its_notice_back+ - id: SCT-006+ name: a timed-out command reports the output it produced before it hung+ status: covered+ kind: timeout+ layer: unit+ backend: shared+ test: tests/test_command_runner.py::test_timeout_keeps_the_output_the_capped_readers_already_retained+ - id: SCT-007+ name: escalation guidance can be reworded without recreating the task+ status: covered+ kind: config+ layer: contract+ backend: shared+ test: tests/test_cli_task_command.py::test_task_update_rewords_escalation_guidance_on_an_agent_command_task+ - id: SCT-008+ name: a command with no stored cwd runs in the workdir of the Session it is bound to+ status: covered+ kind: config+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_an_escalating_command_runs_in_its_bound_sessions_workdir+ - id: SCT-009+ name: an escalation killed mid-turn by teardown still hands back its failure notice+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_archiving_the_session_gives_an_already_running_escalation_its_notice_back+ - id: SCT-010+ name: deleting a Session leaves no claimable escalation bound to it+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_hard_deleting_the_session_also_cancels_the_runs_bound_to_it+ - id: SCT-011+ name: a command task is findable by the command it runs+ status: covered+ kind: config+ layer: unit+ backend: shared+ test: tests/test_harness_definition_lifecycle.py::test_searching_tasks_looks_at_what_a_command_task_actually_runs+ - id: SCT-012+ name: a long command fire never holds its conversation's turn lock+ status: covered+ kind: concurrency+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_running_command_fire_does_not_hold_its_conversations_turn_lock+ - id: SCT-013+ name: cancelling a running command run actually stops the process+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_canceling_a_running_command_run_actually_stops_the_command+ - id: SCT-014+ name: an escalation turn is not a health verdict on the command that queued it+ status: covered+ kind: failure+ layer: unit+ backend: shared+ test: tests/test_harness_definition_lifecycle.py::test_an_escalation_turn_is_not_a_verdict_on_the_command_that_queued_it+ - id: SCT-015+ name: a capped output stream retains the tail, where the cause usually is+ status: covered+ kind: failure+ layer: unit+ backend: shared+ test: tests/test_command_runner.py::test_output_cap_keeps_the_tail_where_the_cause_usually_is+ - id: SCT-016+ name: an argv command renders with its word boundaries intact in the UI+ status: covered+ kind: config+ layer: unit+ backend: shared+ test: ui/src/components/workbench/harnessLifecycle.test.ts::taskCommandPreview quotes argv the way the shell would read it back+ - id: SCT-017+ name: a fire that produced no exit code clears the one the last fire left+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_command_task_integration.py::test_a_fire_with_no_exit_code_clears_the_one_the_last_fire_left+ - id: SCT-018+ name: the task pane states the timeout in force even when the row stores none+ status: covered+ kind: config+ layer: unit+ backend: shared+ test: ui/src/components/workbench/HarnessPage.test.tsx::TaskDetail command task states the timeout that actually applies when the row stores none+ - id: SCT-019+ name: a notice and a run detail name the command the run actually executed+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_harness_failure_visibility.py::test_a_notice_names_the_command_the_run_actually_executed+ # The write side (a real fire stamps the snapshot onto its run row) and the+ # Workbench read side:+ # tests/test_scheduled_command_task_integration.py::test_cli_created_command_task_records_a_nonzero_exit+ # ui/src/components/workbench/HarnessPage.test.tsx::RunDetail command run+ - id: SCT-020+ name: cancelling a run whose task was removed still stops the command+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_canceling_a_run_whose_task_was_removed_still_stops_the_command+ - id: SCT-021+ name: an interrupted command fire clears the exit code the last fire left+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_an_interrupted_command_fire_clears_the_previous_exit_code+ - id: SCT-022+ name: generated command failure text follows the configured language+ status: covered+ kind: config+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_command_failure_text_is_written_in_the_configured_language+ - id: SCT-023+ name: a restart after a crash reaps the command worker the dead service left running+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_crashed_service_reaps_the_command_worker_it_left_running+ - id: SCT-024+ name: a scheduler timeout is told apart from a command that exited 124 on its own+ status: covered+ kind: timeout+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_command_task_timeout_fails_the_run_with_the_timeout_exit_code+ # Same scenario, read side: the recorded flag outranks the bare exit code both+ # ways, and a sub-second limit is stated as the user wrote it rather than+ # rounded to "0 second(s)":+ # tests/test_harness_definition_lifecycle.py::test_lifecycle_detail_names_how_a_finished_row_ended+ - id: SCT-025+ name: a worker's machine-readable error line reaches the user as a sentence+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_command_whose_executable_is_missing_reads_as_a_sentence+ - id: SCT-026+ name: a cancel during the command refuses the escalation and settles cancelled+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_cancel_during_the_command_refuses_the_escalation_and_settles_canceled+ - id: SCT-027+ name: a teardown between the stamp and the settle cancels the fire itself+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_teardown_between_the_stamp_and_the_settle_cancels_the_fire_itself+ # The negative half of SCT-026: archiving the session cancels EVERY non-terminal+ # run of it, the parent fire included, so the settle sees a cancelled fire that+ # owes no notice. That is why the settle needs no second check on the escalation+ # run it just enqueued.+ - id: SCT-028+ name: the run snapshot names the command the fire actually claimed, not an older copy+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_the_run_snapshot_names_the_command_the_fire_actually_ran+ - id: SCT-029+ name: a command worker that survives the reap is kept for the next start to retry+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_worker_that_survives_the_reap_is_kept_for_the_next_start+ # Both halves in one test: the run stays ``running`` while a live worker is still+ # named, because ``list_running_command_workers`` reads only those rows -- and it+ # stops being held open once ``_MAX_COMMAND_WORKER_REAP_ATTEMPTS`` is spent, so a+ # process that genuinely never exits cannot pin a run ``running`` for the life of+ # the install.+ - id: SCT-030+ name: an Agent renamed while the command ran still receives the escalation+ status: covered+ kind: failure+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_an_agent_renamed_during_the_command_still_gets_the_escalation+ # The negative half -- an Agent that was REMOVED rather than renamed keeps the+ # definition's own spelling, because inventing an identity would bind the report to+ # a different Agent than the definition asks for:+ # tests/test_scheduled_tasks.py::test_an_archived_agent_keeps_the_escalations_own_spelling+ - id: SCT-031+ name: a liveness probe that cannot read the process keeps the worker's identity+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_probe_that_cannot_read_the_process_keeps_its_identity+ # The primitive underneath, which is where the two answers are actually told+ # apart -- an empty pid is "gone", an unreadable one is "unknown":+ # tests/test_process_isolation.py::test_probe_tells_an_empty_pid_apart_from_one_it_cannot_read+ - id: SCT-032+ name: a restart reaps the process group a dead command supervisor left behind+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_restart_reaps_the_group_a_dead_supervisor_left_behind+ # Real group, real leader exit: the supervisor leads ``pgid == pid`` and that group+ # outlives it on POSIX, so a free pid is not a reaped tree. The shared primitive+ # that owns the walk, and its refusal to signal a group it cannot vouch for:+ # tests/test_process_isolation.py::test_reaping_an_orphan_follows_the_group_its_leader_left_behind+ # tests/test_process_isolation.py::test_reaping_an_orphan_keeps_a_group_it_cannot_identify+ - id: SCT-033+ name: a stop that lands after the stamp retracts the escalation it authorised+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_stop_that_lands_after_the_stamp_retracts_the_escalation+ # SCT-026 one lane later: there the cancel is visible when the guarded stamp commits+ # and the escalation rolls back with it; here the flag lands after that transaction+ # returned, so the durable turn has to be withdrawn by whoever settles the fire+ # ``canceled``. Neither report is owed -- a stopped fire owes no notice (SCT-027).+ - id: SCT-034+ name: claiming the escalation of a stopped fire is refused at the door+ status: covered+ kind: teardown+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_claiming_the_escalation_of_a_stopped_fire_is_refused_at_the_door+ # The half SCT-033's retraction cannot reach. Retraction takes back a QUEUED row;+ # once the dispatch loop has claimed the escalation, ``cancel_run`` writes a flag the+ # turn lane does not watch, so the stopped job would launch an Agent anyway. The+ # claim asks the parent fire itself, inside the transaction that would start the+ # work, which is what makes the ordering between the two lanes irrelevant.+ - id: SCT-035+ name: an unexpected error after the spawn still reaps the command+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_command_runner.py::test_an_unexpected_error_after_the_spawn_still_reaps_the_command+ # Cancellation (SCT-014) and timeout (SCT-006) were the only exits that reaped the+ # tree. Anything else -- an OSError draining a capped pipe, one reader dying while+ # its twin still reads -- escaped with the supervisor alive, and the caller clears+ # ``command_worker`` in its own ``finally`` the moment the runner raises, so the+ # orphan was left with nothing on disk naming it.+ - id: SCT-036+ name: an enumeration that fails leaves the worker records it could not read+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_an_enumeration_that_fails_leaves_the_records_it_could_not_read+ # SCT-031 one layer up: there the unreadable thing is a process, here it is the whole+ # list. A failed ``list_running_command_workers`` used to answer with an empty skip+ # set, which licensed the very next line to settle EVERY running command fire and+ # unname every live worker on the host at once. The settle pass now reads the record+ # off the row it is about to settle instead of trusting a set handed to it, and the+ # negative half of the same test keeps a fire with no record settling normally.+ - id: SCT-037+ name: a command whose worker cannot be recorded is never started+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_command_whose_worker_cannot_be_recorded_is_never_started+ # The record's birth, which every other guard in this family presupposes. If the+ # stamp does not land the fire runs unnamed, and the handshake is the one moment+ # refusing is nearly free: the supervisor is still blocked on its spec, so nothing+ # the user asked for has started. The negative half is the same judgement inverted --+ # an identity that could not be CAPTURED does not refuse, because the usual cause is+ # a supervisor that already exited and an uncapturable identity cannot be made+ # trustworthy by persisting it.+ - id: SCT-038+ name: a refused terminal stamp reports itself in the user's language+ status: covered+ kind: observability+ layer: contract+ backend: shared+ test: tests/test_i18n_backend_keys.py::test_the_command_fires_refusal_sentences_resolve_in_every_language+ # The refusal sentence is copy THIS MODULE composes, and it lands in the run+ # ledger's ``error`` -- the column the Harness detail pane, ``vibe runs show`` and+ # the failure notice render verbatim, and the one the settlement reasons already+ # fill through ``vibe/i18n``. What stays untranslated there is quoted text nobody+ # here wrote (``str(exc)``, a worker's own stderr), so the line is between our copy+ # and quoted material, not one convention per channel.+ - id: SCT-039+ name: a supervisor failure records no command exit code+ status: covered+ kind: observability+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_supervisor_failure_records_no_command_exit_code+ # SCT-025 decoded the worker's error LINE and left its exit STATUS misattributed.+ # ``main()`` returns 1 for both of the supervisor's own failures, so a spawn it could+ # not perform was published as the command's exit code -- in the notice, the+ # escalation prompt, ``last_exit_code`` and the run row -- for a command that never+ # started. The negative half is the discriminator's proof: a command that ran and+ # exited 3 still reports 3, or the fix would blind every failing cron job.+ - id: SCT-040+ name: a definition does not fire while its own worker may be alive+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_definition_does_not_fire_while_its_own_worker_may_be_alive+ # Single flight per definition was stated (``_execution_lock_key`` keys a fire on its+ # own task id) and enforced only in memory, so it lapsed across exactly the restart+ # that leaves a supervisor running: the record is RETAINED because the tree could not+ # be shown dead, and the next cron tick then started a second copy over the same+ # dataset. The fire now consults the durable record by identity, for its own+ # definition only, and defers on "present" and on "unknown" alike. It looks and never+ # signals -- reaping to make room would destroy the work it was scheduled to protect+ # -- and proof of death both releases the schedule and retires the record, so a dead+ # worker cannot hold its own definition shut until the next restart.+ - id: SCT-041+ name: a failed retention write keeps the stored worker record+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_failed_retention_write_keeps_the_stored_worker_record+ # The last write in the path SCT-036 built, breaking SCT-036's own invariant: a+ # locked database while re-stamping the attempt count answered "did not retain", and+ # the caller's next line clears the record. A store hiccup, which says nothing about+ # the process, thereby did the one thing the path exists to prevent. The stored record+ # survives a failed write untouched, so "kept" is the honest answer, and the attempt+ # cap is charged only for attempts actually made. The test fails the re-stamp alone,+ # leaving the clear working, or a kept record could not be told from an undeletable one.+ - id: SCT-042+ name: both run stores name the definition a command worker belongs to+ status: covered+ kind: crash_recovery+ layer: contract+ backend: shared+ test: tests/test_scheduled_tasks.py::test_both_run_stores_name_the_definition_a_command_worker_belongs_to+ # SCT-040's guard filters recorded workers by definition, so the attribution IS the+ # contract. The file backend omitted it -- SQLite's column was renamed+ # ``definition_id`` while the file payload still spells the association ``task_id``+ # -- and a missing field does not read as "no worker": it reads as "no worker for+ # every definition at once", so single flight silently stopped holding on that+ # backend while looking healthy on the other. Normalized at the store boundary and+ # asserted on both backends in one test, because a reader cannot tell which one it+ # was handed.+ - id: SCT-043+ name: the task pane claims no Agent routing a pure command task does not have+ status: covered+ kind: observability+ layer: unit+ backend: shared+ test: ui/src/components/workbench/HarnessPage.test.tsx::TaskDetail command task drops the Agent routing a pure command task deliberately has none of+ # Three label helpers resolve a stored null to a CONCRETE answer -- "Inherits default+ # agent", "Reuse the same session", "Default · session location" -- which is true of a+ # message task, whose null Agent really is the inherited one. A command created with+ # the CLI's default ``--on-failure none`` is bound to nothing, so the same rendering+ # described routing it deliberately has none of, one field above an "On failure:+ # Notice only (no Agent)" that says the opposite. Gated on the BINDINGS, not on the+ # kind: an escalation turn is routed by exactly these fields, and a command created+ # from IM delivers its failure notice to a real conversation.+ - id: SCT-044+ name: a recovered fire is settled once its worker is finally shown gone+ status: covered+ kind: crash_recovery+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_recovered_fire_is_settled_when_its_worker_is_finally_shown_gone+ # SCT-040 let a proven death release the definition immediately instead of waiting for+ # a restart, and left the interrupted run behind: no other pass comes back for it.+ # ``recover_processing`` runs once at startup and steps over any row still naming a+ # worker -- this row's whole reason for surviving -- and the stale-run sweep only+ # classifies orphans of ``run_type == "agent_run"``. The run therefore read+ # ``running`` until the next restart for a command that was over, the definition+ # looked healthy, and the user was never told the fire had been cut off. Settled as+ # ``restarted``, the same cause the startup pass writes, so one interruption is not+ # told two ways depending on which pass proved the death.+ - id: SCT-045+ name: a teardown that cannot drain still kills the command+ status: covered+ kind: crash_recovery+ layer: unit+ backend: shared+ test: tests/test_command_runner.py::test_a_teardown_that_cannot_drain_still_kills_the_command+ # SCT-035 made every unexpected way out of the runner reap the tree, through a+ # catch-all clause -- which cancellation and timeout never reach, because they are+ # handled by their own ``except`` clauses beside it. Their teardown drains the pipes,+ # a drain can fail (``OSError`` on a pipe, a loop already closing), and an exception+ # raised inside an ``except`` clause is not caught by its sibling: the frame left with+ # the supervisor alive while the scheduled-task caller cleared the worker record in+ # its own ``finally``, on the documented assumption the runner had reaped it. The tree+ # now dies through a synchronous group kill -- nothing left to interrupt, in the very+ # frames a cancellation reached -- and neither handler lets that failure replace the+ # outcome it owes: a re-raised cancellation, or a 124 result.+ - id: SCT-046+ name: a recovered fire is settled on the file store too+ status: covered+ kind: crash_recovery+ layer: contract+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_recovered_fire_is_settled_on_the_file_store_too+ # SCT-044 settles through the guarded per-run writer, which only SQLite has. On the+ # legacy file store that check answered "unsupported" and the settle returned having+ # done nothing but clear the worker record: the definition was released, the next fire+ # ran, and the interrupted run's file sat in ``processing`` reading ``running`` until+ # some later restart -- the leak SCT-044 removed, still open one backend over. The+ # store now owns the difference (``settle_recovered_run``), so the caller has one path+ # instead of a supported-store branch that silently does nothing.+ - id: SCT-047+ name: a per-run command records the directory it was described in+ status: covered+ kind: routing+ layer: unit+ backend: shared+ test: tests/test_cli_task_command.py::test_task_add_per_run_command_records_the_directory_it_was_described_in+ # ``--create-session-per-run`` stores no ``cwd`` on purpose: that Session is created at+ # escalation and its workdir resolved then. A command cannot wait for it -- it fires on+ # the next tick out of the definition's ``cwd`` -- so the documented+ # ``--shell './scripts/sync.sh'`` ran from ``~/.avibe``, where the script does not+ # exist and a relative write lands in persisted state. The invocation directory is+ # recorded for the command's half only: ``session_workdir`` stays unset, or a+ # scope-bound definition would stop following its Scope's workdir.+ - id: SCT-048+ name: a command with nothing to inherit runs where Agent work runs+ status: covered+ kind: routing+ layer: scenario+ backend: shared+ test: tests/test_scheduled_tasks.py::test_a_command_with_nothing_to_inherit_runs_where_agent_work_runs+ # The runtime half of SCT-047, for the definitions its creation-time fix cannot reach:+ # one created before it, or written straight through the API. Those still arrive with+ # no ``cwd`` and no readable Session, and the product state directory is the worst+ # possible place to run a user's command. ``runtime.default_cwd`` is where this+ # install's Agent turns already run, so it is both a real directory and the answer the+ # escalation Session would get; it is validated rather than trusted, so an unset or+ # deleted setting falls through to the old fallback instead of failing the fire.+ - id: SCT-049+ name: both run stores settle a fire with the command it ran+ status: covered+ kind: crash_recovery+ layer: contract+ backend: shared+ test: tests/test_scheduled_tasks.py::test_both_run_stores_settle_a_fire_with_the_command_it_ran+ # SCT-028's re-stamp is read off the TERMINAL row -- by the failure notice, the+ # escalation prompt and the Workbench run detail -- and the file backend composed that+ # row from the ``TaskExecutionRequest`` the caller still held, the enqueue-time copy.+ # So the last write of the fire overwrote the only one that knew what ran. SQLite+ # updates the row the metadata already lives on, which is why the gap was invisible+ # from there; the recovery writer already composed from the file, so the same backend's+ # two terminal writers disagreed about what a settled row remembers.diff --git a/tests/scenarios/harness_command_task/observations.yaml b/tests/scenarios/harness_command_task/observations.yamlnew file mode 100644index 000000000..c3daf6b20--- /dev/null+++ b/tests/scenarios/harness_command_task/observations.yaml@@ -0,0 +1,503 @@+version: 1+capability: harness_command_task+observations:+ - id: OBS-HARNESS-COMMAND-TASK-001+ source: code_review_diagnosis+ related_scenarios:+ - SCT-019+ summary: A command Run recorded its exit code and output but never the command it ran, so every reader had to go back to a mutable definition.+ previous_assumption: The definition is a good enough source for "what did this run execute", because a task's command rarely changes.+ observed_behavior: Failure notices drain asynchronously, so an edited definition made the notice name a command that never ran, and a removed one made it name nothing at all.+ required_updates:+ - stamp an immutable {shell, argv} snapshot into the Run's own metadata at enqueue+ - build that snapshot inside the transactional SQLite enqueue from the authoritative run_definitions row, not from a caller argument the writer then discards+ - read the snapshot first in the notice body and the Workbench Run detail, falling back to the definition only for pre-snapshot rows+ - id: OBS-HARNESS-COMMAND-TASK-002+ source: code_review_diagnosis+ related_scenarios:+ - SCT-013+ - SCT-020+ summary: Whether an in-flight Run was a command was decided by asking the live definition store.+ previous_assumption: A Run's definition is still present for as long as the Run is in flight.+ observed_behavior: remove_task drops the definition immediately and leaves the Run alive, which is exactly how a user reacts to a misbehaving command; the cancellation was then classified as an Agent turn and ignored, and the child ran on to its --timeout (six hours by default).+ required_updates:+ - classify an in-flight execution from data fixed for the life of the fire (the Run's command snapshot)+ - keep the live-definition lookup only as the fallback for Runs enqueued before the snapshot existed+ - id: OBS-HARNESS-COMMAND-TASK-003+ source: code_review_diagnosis+ related_scenarios:+ - SCT-017+ - SCT-021+ summary: last_exit_code survived fires that produced no exit status of their own.+ previous_assumption: Writing the column only when a value exists is the safe default, because a message task has no code and must not blank a command's.+ observed_behavior: A fire that never spawned, and later a fire cancelled or interrupted mid-flight, both left the previous fire's code on the row, so the task pane read "exited 7" beside a run that never produced a 7.+ required_updates:+ - give the command fire's own stamp authority over the column, None included+ - extend that authority to the terminal projection lane, which settles cancelled and shutdown-interrupted command fires+ - leave the column alone for every non-command lane+ - id: OBS-HARNESS-COMMAND-TASK-004+ source: code_review_diagnosis+ related_scenarios:+ - SCT-022+ summary: The outcome text a command fire generates is user-visible copy, not an internal log line.+ previous_assumption: last_error is diagnostic detail, so an f-string is fine.+ observed_behavior: The generated English sentence is stored and then rendered verbatim inside otherwise-translated failure notices, vibe task list, and the Workbench.+ required_updates:+ - route every generated command outcome through vibe/i18n/+ - keep the untranslatable parts (a worker's own stderr, the configured path) inside the localized template+ - id: OBS-HARNESS-COMMAND-TASK-005+ source: code_review_diagnosis+ related_scenarios:+ - SCT-023+ summary: A command child was reachable only through the coroutine awaiting it, which a crash never runs.+ previous_assumption: Every stop of a command fire arrives as a CancelledError on the awaiting coroutine, which the runner turns into a tree teardown.+ observed_behavior: SIGKILL and a process crash deliver no CancelledError at all, so the isolated supervisor and the backup or migration under it kept running unowned; nothing on disk named that child, so the restart could not find it even in principle, and the next cron fire started a second one beside it.+ required_updates:+ - persist the worker identity on the Run via on_spawn and clear it when the child is reaped+ - reap surviving workers at startup, before recover_processing settles the very rows the identity is stored on+ - authorise the kill by process identity (start time plus inherited marker), never by pid alone, because the number is recycled across a crash+ - share the identity serialize/parse helpers with the watch lane instead of copying them+ - id: OBS-HARNESS-COMMAND-TASK-006+ source: code_review_diagnosis+ related_scenarios:+ - SCT-024+ summary: Exit code 124 was read as proof that the scheduler timed the command out.+ previous_assumption: 124 is the runner's timeout code, so a row carrying it timed out.+ observed_behavior: A --shell script that wraps its own work in timeout exits 124 by itself, and the UI then told the user to raise a limit that was never reached; separately, a float --timeout was rendered through int(), so a 0.5s limit read as "timed out after 0 second(s)" and hid the setting that had to change.+ required_updates:+ - record on the definition that the SCHEDULER is what stopped the command, and let that flag outrank the exit code in both directions+ - keep 124-implies-timeout only as the fallback for rows written before the flag existed+ - state the limit as the user configured it, without truncating a sub-second value to zero+ - id: OBS-HARNESS-COMMAND-TASK-007+ source: code_review_diagnosis+ related_scenarios:+ - SCT-025+ summary: The supervisor's protocol error lines were surfaced to the user verbatim.+ previous_assumption: A spawn failure is an internal fault, so the worker's stderr is a diagnostic that only developers read.+ observed_behavior: The line reached the failure notice and vibe task list unchanged, so a mistyped executable read as a machine token rather than a sentence, and it stayed English inside otherwise-translated copy.+ required_updates:+ - decode the worker's error line into a localized sentence through vibe/i18n/+ - keep that decoding beside the protocol that emits it (core/watch_worker.py) so both lanes share one mapping+ - id: OBS-HARNESS-COMMAND-TASK-008+ source: code_review_diagnosis+ related_scenarios:+ - SCT-026+ - SCT-027+ summary: The escalation Agent turn and the stamp that suppresses the failure notice were two separate commits.+ previous_assumption: A fire that reaches the settle still owns its outcome, so stamping and enqueueing in sequence is equivalent to doing both.+ observed_behavior: A cancel or reclaim landing between them produced either an Agent turn for a job the user had just stopped, or a stamped suppression with no report at all; the second is the unrecoverable half, because nothing later re-derives that a notice was owed.+ required_updates:+ - commit the stamp and the escalation enqueue in one transaction, guarded by compare-and-set preconditions on the binding and the uncancelled run id+ - bias the surviving crash window toward BOTH reports rather than neither+ - re-arm the owed notice when a session teardown cancels an escalation that had already suppressed one+ - id: OBS-HARNESS-COMMAND-TASK-009+ source: code_review_diagnosis+ related_scenarios:+ - SCT-029+ summary: The startup reap cleared a worker's durable identity even when the kill came back unconfirmed.+ previous_assumption: A teardown either kills the process or the process is already gone, so the record is spent either way.+ observed_behavior: >-+ An unconfirmed kill is neither -- a task wedged in uninterruptible I/O outlives+ SIGKILL, and a group whose leader moved cannot be signalled at all. The run is the+ only place the identity is written and recover_processing settles it moments later,+ so the surviving backup or migration became permanently unfindable; not just+ unkilled, but unkillable by any future pass.+ required_updates:+ - distinguish "not confirmed" from "already gone" by re-inspecting the identity before discarding it+ - keep the record and leave the run running so the next start can retry, since only running rows are scanned+ - bound the retries, because an unconditional retry holds a run running for the life of the install+ - id: OBS-HARNESS-COMMAND-TASK-010+ source: code_review_diagnosis+ related_scenarios:+ - SCT-030+ summary: >-+ The run row a stamp authorises was composed from the definition as the executor+ claimed it, and inserted unchanged however long later.+ previous_assumption: >-+ An Agent rename rewrites every reference that matters, so a queued turn always+ names an Agent that exists.+ observed_behavior: >-+ The rewrite covers definitions and ACTIVE runs; a row still being composed is+ neither, and a command task's composition window is the whole runtime of the+ command. The escalation was inserted naming an Agent the catalog no longer had, so+ it could never be claimed -- while the notice its own stamp suppressed was already+ gone. Neither report, which is the one outcome the invariant exists to rule out.+ required_updates:+ - read the Agent from the definition values written in the SAME transaction, not from the caller's older snapshot+ - resolve that name to the catalog's durable agent id so the next rename cannot reopen the window+ - hold the write lock, because this transaction now reads the Agent catalog a concurrent rename rewrites+ - leave a removed Agent's spelling alone rather than inventing an identity, and apply the same fix to the watch lane's completion hook+ - id: OBS-HARNESS-COMMAND-TASK-011+ source: code_review_diagnosis+ related_scenarios:+ - SCT-031+ summary: >-+ The liveness check in front of the reap read "I could not look" as "nothing is+ there".+ previous_assumption: >-+ inspect_process_identity returning None means the pid is empty, so the record+ naming that process is spent.+ observed_behavior: >-+ It returns None for an unreadable process too -- an exhausted fd table, a /proc+ read losing a race, a platform refusing create_time. Startup is exactly when+ those are likeliest, and the answer skipped the kill AND cleared the record, so+ the fix for OBS-009 never engaged: the surviving backup became unfindable by+ every later start, and the next fire could run beside it.+ required_updates:+ - split the probe into three answers at the primitive, beside the group-level status that already has them+ - let only an empty pid retire the record, before the kill and after an unconfirmed one+ - never signal a pid whose identity could not be read, since that is the coin flip the identity check exists to refuse+ - keep the bounded retry as the cap, so a probe that never recovers cannot hold a run running for the life of the install+ - id: OBS-HARNESS-COMMAND-TASK-012+ source: code_review_diagnosis+ related_scenarios:+ - SCT-032+ summary: >-+ The reap asked whether the supervisor pid was occupied and treated a free one as+ a reaped tree.+ previous_assumption: >-+ The supervisor is the tree's only handle, so an empty pid means everything under+ it is gone too.+ observed_behavior: >-+ A worker spawned with start_new_session LEADS the group pgid == pid, and on POSIX+ that group outlives its leader: kill the supervisor alone -- the OOM killer+ picking the parent, a fault in its own code -- and the command keeps running in a+ group nothing else names. Clearing command_worker there let recover_processing+ settle the row, so the survivor ran to completion unowned and the next fire+ started a second one beside it. The watch lane already walked the surviving group;+ the command lane stopped at the pid.+ required_updates:+ - after the leader is gone, walk the group it led before calling the tree dead+ - own that walk (leader, then group) in core/process_isolation.py so both worker lanes answer it the same way, rather than copying the watch lane's inline logic+ - keep the record when the group exists but its members cannot be identified, since refusing to signal is not proof of absence+ - retire the record only for a mismatched group, which is a recycled pgid rather than the tracked tree+ - id: OBS-HARNESS-COMMAND-TASK-013+ source: code_review_diagnosis+ related_scenarios:+ - SCT-033+ summary: >-+ The compare-and-set that refuses an escalation for a stopped fire could only see+ the stops that existed when it committed.+ previous_assumption: >-+ Re-reading the cancellation server-side inside the stamp transaction settles the+ question for the whole fire.+ observed_behavior: >-+ cancel_run on a running fire writes only a flag, and the flag can land after+ mark_task_result has returned. settle_run_terminal then re-reads it and normalizes+ the fire to canceled while the escalation that transaction committed sits queued+ and claimable, so the user stops a job and the job answers by starting an Agent --+ OBS-008's defect one lane further along.+ required_updates:+ - retract the queued escalation from whoever settles the fire canceled, found by run_type plus parent_run_id rather than from a local id a CancelledError can skip+ - key it on the status ACTUALLY written, since a service shutdown cancels the same coroutine and settles interrupted, where the report is still owed+ - owe neither report, because canceled means the user asked this fire to stop and a stopped fire owes no notice; the landed stamp still records the failure on the definition+ - keep the enqueue in the stamp's transaction rather than merging it into the settlement, which would reopen the window OBS-008 closed+ - id: OBS-HARNESS-COMMAND-TASK-014+ source: code_review_diagnosis+ related_scenarios:+ - SCT-034+ summary: >-+ Withdrawing the escalation of a stopped fire assumed the row was still queued when+ the settlement reached it.+ previous_assumption: >-+ cancel_run is enough to take an escalation back, because it is the same call the+ user's own vibe runs cancel makes.+ observed_behavior: >-+ On a run the dispatch loop has already claimed, cancel_run writes only+ cancel_requested, and nothing watches that flag for a turn:+ _propagate_requested_cancellations observes command fires only, and the CLI's live+ stop is gated on run_type == "agent_run". The escalation becomes claimable the+ moment the stamp commits, which is several awaits before the settlement that+ retracts it, so a stopped command could still answer by launching an Agent and+ running it to completion.+ required_updates:+ - ask the question at the CLAIM, from the parent fire's row, inside the transaction that would otherwise start the work+ - key it on the fire's cancel_requested as well as a written canceled, since the flag is set the instant the user asks+ - hold the writer before those reads, because the claim now decides on a row another connection writes+ - leave a shutdown-interrupted fire's escalation claimable, because there the report is still owed+ - keep the retraction as the other half rather than replacing it, so a row that is never claimed is settled rather than left queued+ - id: OBS-HARNESS-COMMAND-TASK-015+ source: code_review_diagnosis+ related_scenarios:+ - SCT-036+ summary: >-+ The startup reap reported "I could not enumerate the workers" as "there are no+ workers to protect".+ previous_assumption: >-+ Returning an empty skip set when the enumeration fails is a safe degradation,+ because the pass simply killed nothing that start.+ observed_behavior: >-+ The empty set is not read as "nothing was killed", it is read as "settle+ everything": recover_processing runs on the very next line, and because+ command_worker is readable only while a row is running, one momentary read failure+ terminalizes every live backup and deployment's row and unnames all of them+ permanently -- OBS-011's category error one layer up, with the whole host in scope.+ required_updates:+ - make the settle pass read the record off the row it is about to settle, inside the same transaction, rather than trusting a set computed by a separate query+ - let the reap communicate by writing: cleared once a process is proven dead or the retries are spent, left in place on every maybe, including the maybe where it never looked+ - do not fail startup and do not skip the settle pass, since both strand every other interrupted run type as running+ - charge nothing against the attempt cap for a start that never attempted a kill+ - tolerate a single row's inspection raising, so the rows after it are still examined and the settle pass still runs+ - id: OBS-HARNESS-COMMAND-TASK-016+ source: code_review_diagnosis+ related_scenarios:+ - SCT-035+ summary: >-+ The runner reaped its process tree on the two failures it named and on no others.+ previous_assumption: >-+ Cancellation and timeout are the ways a supervised command ends badly, so handling+ those two covers teardown.+ observed_behavior: >-+ Any other exception after the spawn -- an OSError draining a capped stream, a+ reader failing while its twin still runs, a fault between the handshake and the+ collector -- propagated with the supervisor and the command under it still running.+ The scheduled-task caller then catches it as a failed fire and clears+ command_worker in its own finally, on the documented assumption that the runner+ already reaped the tree, so the survivor became an orphan nothing can name.+ required_updates:+ - add a catch-all that cancels the readers and reaps the tree before re-raising, so no exit from the post-spawn block leaves the tree alive+ - skip the reap when the supervisor is already collected, because a second consumer on those streams is its own defect+ - never let a failing teardown replace the original exception, which is the failure worth reporting+ - id: OBS-HARNESS-COMMAND-TASK-017+ source: code_review_diagnosis+ related_scenarios:+ - SCT-037+ summary: >-+ The worker stamp was best-effort at the one moment it could be enforced for free.+ previous_assumption: >-+ Recording the worker is bookkeeping for a crash that may never happen, so a store+ hiccup must never turn a command that ran fine into a reported failure.+ observed_behavior: >-+ That reasoning holds for CLEARING the record and fails for writing it. A stamp that+ does not land leaves the fire running a backup or deployment with nothing on disk+ naming it, which is the unfindable-orphan state the rest of this family exists to+ prevent, reached before any record existed. And the cost of refusing is almost+ nothing at that point: the supervisor is blocked reading its spec off stdin, so the+ user's command has not started.+ required_updates:+ - fail the fire when a captured identity cannot be persisted, including when the stamp returns False because the row is no longer running+ - do NOT refuse when the identity could not be captured, since the dominant cause is a supervisor that already exited and no persisted record can be trusted for a process that could not be inspected+ - call on_spawn inside the runner's protected block, so a refusing callback reaps the tree instead of leaking the orphan it is protecting against+ - keep the clear path best-effort, because the record it removes protects nothing and a leftover record is dropped by the next start anyway+ - id: OBS-HARNESS-COMMAND-TASK-018+ source: code_review_diagnosis+ related_scenarios:+ - SCT-038+ summary: >-+ "One string convention per outcome channel" was the wrong line to draw.+ previous_assumption: >-+ The run's ``error`` column carries plain operator text in this module -- ``str(exc)``,+ a worker's stderr, a pause reason -- so a generated refusal sentence should match+ that convention rather than split the channel between translated and untranslated+ values.+ observed_behavior: >-+ The channel was already mixed, and correctly so: the command lane fills the very+ same ``error`` from ``harness.command.timedOut`` / ``exited``, and the settlement+ reasons in ``core/run_settlement.py`` are translated for exactly this reason. The+ real line is between copy WE compose and text we merely quote; a hard-coded English+ refusal handed a Chinese install a mixed-language failure in the Harness detail pane+ and the failure notice.+ required_updates:+ - translate the refused-terminal-stamp sentence through vibe/i18n on both call sites+ - keep quoted material (str(exc), worker stderr) untranslated, since nobody here authored it+ - guard both refusal keys with a resolution test that also fails if zh.json is filled with the English string+ - id: OBS-HARNESS-COMMAND-TASK-019+ source: code_review_diagnosis+ related_scenarios:+ - SCT-039+ - SCT-025+ summary: >-+ Decoding the supervisor's error line fixed the sentence and left the number lying.+ previous_assumption: >-+ A worker that accepted the spec and then failed to spawn is reported once the raw+ protocol JSON on its stderr is turned into a sentence; the exit status travelling+ beside it is just the runner's report of what the process returned.+ observed_behavior: >-+ That status is the SUPERVISOR's -- ``main()`` returns 1 for both of its own failures+ -- and this lane publishes it as a fact about the user's command: "Exit code: 1" in+ the failure notice and the Agent escalation prompt, ``last_exit_code`` on the+ definition, an ``exit_code`` in the run row ``vibe runs show`` prints. The message+ then said "Command exited with status 1" and "Command supervisor failed" in one+ breath, for a command that never started.+ required_updates:+ - decode the worker error line rather than sniffing it, and leave the command exit code unset for that outcome+ - report it with the supervisor sentence alone, the way the handshake failure already does+ - keep a real command's status intact, since blanking every failing fire's exit code would be the worse defect+ - leave the watch lane's exit code alone, where a cycle status drives retry_exit_codes and there is no "no status" to spell+ - id: OBS-HARNESS-COMMAND-TASK-020+ source: code_review_diagnosis+ related_scenarios:+ - SCT-040+ - SCT-036+ summary: >-+ A rule enforced only in memory is suspended by the crash it exists to survive.+ previous_assumption: >-+ Keying a command fire on its definition is enough to serialize a fire against+ itself, so one definition can never have two copies of its command running.+ observed_behavior: >-+ That key lives in ``self._inflight_sessions``, which a restart empties. The retained+ worker record is the durable statement that a copy may still be running, and nothing+ on the dispatch path read it: after the crash that leaves a backup's tree alive, the+ next tick of the same cron claimed a fire and spawned a second writer over the same+ dataset -- while the first copy's record sat one table away naming it.+ required_updates:+ - read the durable record on the dispatch path, scoped to the firing definition+ - defer on "cannot tell" as well as on "still there", since proceeding is the same wager either way+ - look without signalling, because the record exists so a later pass can kill that tree+ - release the definition and retire the record the moment the earlier worker is proven gone+ - requeue rather than drop the deferred fire, and record the skip so the row never looks sweepable+ - id: OBS-HARNESS-COMMAND-TASK-021+ source: code_review_diagnosis+ related_scenarios:+ - SCT-041+ - SCT-036+ summary: >-+ "I could not write" is not "there is nothing to protect" either.+ previous_assumption: >-+ The retain path's return value reports whether the record was retained, so a failed+ re-stamp of the attempt count is honestly reported as a retention that did not+ happen.+ observed_behavior: >-+ The caller's next line clears the record on that answer, so a locked database during+ a bookkeeping write discarded the only durable name of a process that had just been+ shown NOT dead -- the same category error as SCT-031 and SCT-036, now in the write+ rather than the read. The already-stored record was never touched by the failed+ write, so the give-up answer was not even accurate.+ required_updates:+ - keep the record when the write fails, and log it at warning rather than debug+ - reserve the give-up answer for a spent attempt cap or a row that is no longer running+ - charge the attempt cap only for attempts that were actually stored+ - id: OBS-HARNESS-COMMAND-TASK-022+ source: code_review_diagnosis+ related_scenarios:+ - SCT-042+ - SCT-040+ summary: >-+ A guard that filters on a field is only as strong as the weakest backend that fills it.+ previous_assumption: >-+ Adding the definition id to the SQLite query gave the new single-flight check what it+ needs, since that is the backend a real install runs on.+ observed_behavior: >-+ The file backend answers the same method and omitted the field, so every one of its+ records matched no definition -- and the absence reads as permission, not as caution:+ the fire concluded no worker of its own was running and started a second copy. The+ association was there all along under the older name the SQLite column was renamed+ away from.+ required_updates:+ - normalize the field at the store boundary so both backends answer the same contract+ - say in the docstring why the field is required, not merely that it is returned+ - assert the contract on both backends in one test, since a reader cannot tell them apart+ - id: OBS-HARNESS-COMMAND-TASK-023+ source: code_review_diagnosis+ related_scenarios:+ - SCT-044+ - SCT-040+ summary: >-+ Moving a transition earlier orphans whatever used to follow it.+ previous_assumption: >-+ Clearing the worker record on proof of death was enough, because that is exactly what+ the startup reap does and the settle pass runs right after it.+ observed_behavior: >-+ Right after it, at startup, and nowhere else. Proving the death mid-life released the+ definition with no pass left to close the run: ``recover_processing`` runs once and+ skips any row still naming a worker, and the stale-run sweep only classifies orphans+ of ``run_type == "agent_run"``. The fire stayed ``running`` until the next restart+ while the command it described was long over, and its interruption was never reported.+ required_updates:+ - settle the recovered run in the same step that releases its definition+ - reuse the startup pass's cause so one interruption is not reported two ways+ - keep the settle best-effort: closing the previous fire must not block the next one+ - id: OBS-HARNESS-COMMAND-TASK-024+ source: code_review_diagnosis+ related_scenarios:+ - SCT-043+ summary: >-+ A helper that resolves a null to a default answers a question that was never asked.+ previous_assumption: >-+ Rendering every task through the same routing fields is neutral: a command task simply+ shows the defaults it would inherit.+ observed_behavior: >-+ Those defaults are claims. A command with ``--on-failure none`` has no Agent, no+ session and no delivery at all, and the pane asserted all three -- contradicting the+ on-failure field directly below it. The fix cannot key on the kind either, since a+ command that escalates or that was created inside a conversation routes through+ exactly those fields.+ required_updates:+ - show the routing fields only when something in them is actually bound+ - state in the test which bindings must keep them visible, not only which hide them+ - treat a "sensible default" label on an absent binding as a fabricated fact+ - id: OBS-HARNESS-COMMAND-TASK-025+ source: code_review_diagnosis+ related_scenarios:+ - SCT-045+ summary: >-+ A catch-all clause does not catch its own siblings, so the specialized handlers were+ left with no backstop at all.+ previous_assumption: >-+ Adding a final ``except BaseException`` that reaps the tree covers every way out of the+ block, including the cancellation and timeout clauses above it.+ observed_behavior: >-+ An exception raised inside an ``except`` clause propagates past its siblings. The+ teardown those two clauses run drains pipes and can itself fail, so the two paths that+ were supposed to be the safe ones were the only ones with no backstop -- and the+ caller clears the worker record the moment they raise.+ required_updates:+ - make teardown failure-tolerant rather than adding another handler that can also fail+ - fall back to a synchronous group kill, since a cancellation leaves nothing awaitable+ - never let a failed teardown replace the outcome its handler owes the caller+ - id: OBS-HARNESS-COMMAND-TASK-026+ source: code_review_diagnosis+ related_scenarios:+ - SCT-046+ summary: >-+ A capability probe used as a guard turns "this store cannot do it" into "this store+ does not need it".+ previous_assumption: >-+ Asking ``supports_guarded_settlement()`` and returning early is the safe way to use a+ writer only one backend has.+ observed_behavior: >-+ The early return skipped the settle entirely on the file store, while the surrounding+ work -- clearing the worker record, releasing the definition, starting the next fire --+ went ahead. The backend that could not settle was the backend that leaked a ``running``+ run for a command that was over.+ required_updates:+ - put the per-run settle behind one store method that both backends answer+ - share the file store's terminal write between the startup pass and the per-run settle+ - reserve capability probes for callers that have a real alternative, not for skipping work+ - id: OBS-HARNESS-COMMAND-TASK-027+ source: code_review_diagnosis+ related_scenarios:+ - SCT-047+ - SCT-048+ summary: >-+ One ``cwd`` field answered two different questions, and declining to answer the Session's+ half silently unanswered the command's.+ previous_assumption: >-+ A definition's ``cwd`` describes the Session it will create, so a policy whose Session+ does not exist yet correctly stores nothing.+ observed_behavior: >-+ A command fires on the next tick and has no Agent turn to inherit a directory from, so+ the stored ``None`` fell through to the ``~/.avibe`` fallback: relative commands failed+ and relative writes landed in persisted product state. The invocation directory was+ available at creation time and thrown away.+ required_updates:+ - record the command's directory at creation without pinning the Session escalation creates+ - resolve the runtime default workdir at fire time for definitions creation cannot reach+ - keep the product state directory as a last resort nothing normally reaches+ - id: OBS-HARNESS-COMMAND-TASK-028+ scenario: SCT-049+ summary: >-+ An in-flight correction is only as durable as the write that publishes it, and one+ backend published from a copy taken before the correction existed.+ previous_assumption: >-+ Re-stamping the executed command on the running row makes every later reader of that+ run see it, on either store.+ observed_behavior: >-+ The file backend's completion rebuilt the terminal payload from the caller's+ enqueue-time request, so the re-stamp -- and every other in-flight write -- was+ dropped at the moment the run became readable as a result. SQLite settles the row the+ metadata already sits on and carried it forward for free, hiding the asymmetry.+ required_updates:+ - compose the file backend's terminal payload from the durable in-flight state+ - keep the caller's outcome facts authoritative over what the row already held+ - assert on both stores in one test, since a reader cannot tell which one answereddiff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yamlindex 46e7e14b4..10f3a8313 100644--- a/tests/scenarios/harness_failure_recovery/catalog.yaml+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml@@ -3395,6 +3395,26 @@ scenarios:# the re-route answers SessionBackendLockedError. Same _commit_competing_bind_after# harness and the same real _archive_write payload as HFR-252.test: tests/test_sqlite_sessions_store.py::test_update_session_cannot_rename_a_session_archived_inside_its_window+ - id: HFR-281+ name: >-+ a completion hook queued inside a stamp names an Agent the catalog still has+ status: covered+ kind: recovery+ layer: scenario+ backend: shared+ # The watch half of SCT-030 (tests/scenarios/harness_command_task). HFR-269 made the+ # stamp and the hook it authorises ONE transaction; what it did not change is WHEN the+ # hook row is composed. ``_hook_request`` builds it from ``watch.agent_name`` as the+ # cycle ends, and an Agent rename committed before the mirror absorbs the stamp+ # rewrites the definition and every ACTIVE run -- but a row still being composed is+ # neither, so the hook was inserted naming an Agent nobody can resolve and the only+ # report a ``once`` watch ever produces could never be claimed.+ # FIX (shared with the scheduled lane, since both writers had it): resolve the Agent+ # from the definition values written in the SAME transaction and pin the row to the+ # catalog's durable agent id, under the write lock the rename itself takes.+ # A rename the mirror has NOT absorbed needs nothing: it bumps the agent binding+ # revision and the compare-and-set refuses both halves.+ test: tests/test_watches.py::test_a_hook_queued_after_a_rename_names_an_agent_that_still_exists- id: HFR-430name: an Agent Run can apply the Workbench send-now transition to a busy Sessionstatus: covereddiff --git a/tests/test_agent_tool_policy.py b/tests/test_agent_tool_policy.pyindex 933c66630..f81f10598 100644--- a/tests/test_agent_tool_policy.py+++ b/tests/test_agent_tool_policy.py@@ -8,6 +8,8 @@ config, no SQLite state, no Claude SDK, no subprocess.from __future__ import annotationsimport asyncio+import re+import shleximport sysfrom pathlib import Path@@ -95,6 +97,50 @@ def test_agent_denial_points_out_that_concurrency_survives():assert "run_in_background: false" in reason+# The scheduler denials whose text embeds runnable `vibe task add` examples.+_SCHEDULER_DENIALS = (+ ("CronCreate", {"cron": "0 9 * * *", "prompt": "x"}),+ ("ScheduleWakeup", {"delaySeconds": 600, "prompt": "x", "reason": "y"}),+)+++def test_scheduler_denials_offer_the_command_task_form():+ # A scheduled shell command has no message to write, so a denial that shows+ # only `--message` forms leaves the agent no Harness equivalent for it and+ # pushes it back toward the session-only tool this policy just refused.+ for tool_name, tool_input in _SCHEDULER_DENIALS:+ reason = policy.check_tool_call(tool_name, tool_input, env={}).reason+ assert 'vibe task add --cron "<expr>" --shell "<cmd>"' in reason++# Trailing " (recurring)" style annotations are prose, not argv.+_EXAMPLE_ANNOTATION = re.compile(r"\s*\([^()]*\)\s*$")+++def _embedded_task_examples() -> list[str]:+ examples: list[str] = []+ for tool_name, tool_input in _SCHEDULER_DENIALS:+ reason = policy.check_tool_call(tool_name, tool_input, env={}).reason+ for raw in reason.splitlines():+ line = raw.strip()+ if line.startswith("vibe task add"):+ examples.append(_EXAMPLE_ANNOTATION.sub("", line))+ return examples+++def test_embedded_task_examples_parse_against_the_real_cli():+ # These denials are live callers: an agent copies the example verbatim. A+ # renamed or removed flag must fail here, not in the user's shell.+ from vibe import cli # imported lazily; the policy itself pulls in no CLI++ examples = _embedded_task_examples()+ # CronCreate embeds 2 (--message, --shell); ScheduleWakeup embeds 3+ # (one-shot --message, recurring --message, --shell).+ assert len(examples) == 5+ for example in examples:+ argv = shlex.split(example)[1:] # drop the leading `vibe`+ cli.build_parser().parse_args(argv) # SystemExit(2) if an example rots++def test_missing_tool_input_is_treated_as_the_tool_default():assert policy.check_tool_call("Agent", None, env={}).denieddiff --git a/tests/test_cli_task_command.py b/tests/test_cli_task_command.pyindex c7a4d0700..36982bb18 100644--- a/tests/test_cli_task_command.py+++ b/tests/test_cli_task_command.py@@ -3,6 +3,7 @@ from __future__ import annotationsimport ioimport jsonimport os+import shleximport sqlite3import sysfrom contextlib import redirect_stderr@@ -730,7 +731,11 @@ def test_task_show_missing_id_returns_guidance(tmp_path: Path) -> None:assert payload["help_command"] == "vibe task list"-def test_task_add_records_caller_context_metadata(tmp_path: Path, capsys) -> None:+def test_task_add_records_caller_context_metadata(tmp_path: Path, capsys, monkeypatch) -> None:+ # ``patch.dict(..., clear=False)`` below pins only the five ids this test names, so+ # the ORIGIN half of the contract (platform/channel/session_key/...) leaked in from+ # the Avibe Agent shell that runs the suite and appeared in the asserted metadata.+ _bare_terminal_caller(monkeypatch)store_path = tmp_path / "scheduled_tasks.json"store = cli.ScheduledTaskStore(store_path)args = _parse_task_add(@@ -4030,3 +4035,686 @@ def test_agent_run_refuses_the_reserved_session_with_no_side_effects("an ordinary Session must still be able to take a direct Agent Run: "f"{[r.session_id for r in request_store.list_pending()]}")+++# ---------------------------------------------------------------------------+# Scheduled command tasks (``vibe task add/update --shell`` and friends)+# ---------------------------------------------------------------------------++#: Every variable ``caller_context_from_env`` reads (core/caller_context.py). The whole+#: set is pinned per test rather than just ``AVIBE_SESSION_ID``, because these tests+#: assert on what lands in ``metadata.created_by``: a stray ``AVIBE_CALLER_PLATFORM``+#: inherited from the Agent shell that runs the suite would otherwise change the payload+#: without changing the test.+_CALLER_CONTEXT_ENV_VARS = (+ "AVIBE_SESSION_ID",+ "AVIBE_RUN_ID",+ "AVIBE_CALLER_SOURCE",+ "AVIBE_CALLER_BACKEND",+ "AVIBE_NATIVE_SESSION_ID",+ "AVIBE_CALLER_PLATFORM",+ "AVIBE_CALLER_USER_ID",+ "AVIBE_CALLER_CHANNEL_ID",+ "AVIBE_CALLER_SESSION_KEY",+ "AVIBE_CALLER_MESSAGE_ID",+ "AVIBE_CALLER_WORKSPACE_ID",+)+++def _bare_terminal_caller(monkeypatch) -> None:+ """A human typing the command in a plain shell: no Avibe caller context at all."""++ for name in _CALLER_CONTEXT_ENV_VARS:+ monkeypatch.delenv(name, raising=False)+++def _agent_shell_caller(monkeypatch, *, session_id: str = "sesCaller") -> None:+ """The command running inside an Avibe-hosted Agent turn."""++ _bare_terminal_caller(monkeypatch)+ monkeypatch.setenv("AVIBE_SESSION_ID", session_id)+ monkeypatch.setenv("AVIBE_RUN_ID", "run_caller")+ monkeypatch.setenv("AVIBE_CALLER_SOURCE", "agent_turn")+ monkeypatch.setenv("AVIBE_CALLER_BACKEND", "codex")+++def _parse_task_update(task_id: str, argv: list[str]):+ parser = cli.build_parser()+ return parser.parse_args(["task", "update", task_id, *argv])+++def _command_task_store(tmp_path: Path):+ return cli.ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+++def _caller_session_state(tmp_path: Path, *, session_id: str = "sesCaller"):+ """A migrated CLI state DB holding one active Session owned by an enabled Agent."""++ db_path = tmp_path / "state" / "vibe.sqlite"+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="codex", backend="codex")+ from storage.importer import ensure_sqlite_state+ from storage.models import agent_sessions+ from storage.settings_service import upsert_scope++ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")+ with cli.create_sqlite_engine(db_path).begin() as conn:+ now = "2026-06-28T00:00:00+00:00"+ scope_id = upsert_scope(conn, "avibe", "project", "proj-command-task", now=now)+ conn.execute(+ agent_sessions.insert().values(+ id=session_id,+ scope_id=scope_id,+ agent_backend="codex",+ agent_name="codex",+ agent_variant="default",+ session_anchor=f"anchor_{session_id}",+ native_session_id="native-caller",+ status="active",+ metadata_json="{}",+ created_at=now,+ updated_at=now,+ last_active_at=now,+ )+ )+ return db_path, agent_store+++# --- parse forms -----------------------------------------------------------+++def test_task_add_parses_shell_command_form() -> None:+ args = _parse_task_add(["--cron", "0 3 * * *", "--shell", "./scripts/sync.sh --verbose"])++ command, shell_command, has_command = cli._resolve_task_command(+ args, help_command="vibe task add --help"+ )++ assert (command, shell_command, has_command) == ([], "./scripts/sync.sh --verbose", True)+++def test_task_add_keeps_flag_values_in_trailing_command_argv() -> None:+ """``--`` must hand the whole tail to the command, option-looking tokens included."""++ args = _parse_task_add(+ ["--cron", "0 3 * * *", "--", "./scripts/sync.sh", "--target", "prod", "-v"]+ )++ command, shell_command, has_command = cli._resolve_task_command(+ args, help_command="vibe task add --help"+ )++ assert command == ["./scripts/sync.sh", "--target", "prod", "-v"]+ assert shell_command is None+ assert has_command is True+++def test_task_add_rejects_both_command_inputs() -> None:+ args = _parse_task_add(["--cron", "0 3 * * *", "--shell", "./a.sh", "--", "./b.sh"])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "conflicting_task_command_inputs"+++def test_task_add_rejects_empty_shell_command() -> None:+ args = _parse_task_add(["--cron", "0 3 * * *", "--shell", " "])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "empty_task_command"+++def test_task_add_rejects_bare_command_separator() -> None:+ args = _parse_task_add(["--cron", "0 3 * * *", "--"])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "empty_task_command"+++# --- action matrix ---------------------------------------------------------+++def test_task_add_rejects_on_failure_without_command(monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ args = _parse_task_add(+ ["--session-id", "sesTarget", "--cron", "0 * * * *", "--message", "hi", "--on-failure", "agent"]+ )++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "on_failure_requires_command"+++def test_task_add_rejects_timeout_without_command(monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ args = _parse_task_add(+ ["--session-id", "sesTarget", "--cron", "0 * * * *", "--message", "hi", "--timeout", "30"]+ )++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "timeout_requires_command"++[email protected]("timeout", ["-1", "inf", "nan"])+def test_task_add_rejects_an_unusable_timeout(monkeypatch, timeout: str) -> None:+ """``inf`` is the trap: ``float`` accepts it and ``>= 0`` waves it through.++ The documented spelling for "no timeout" is ``0``. A stored ``Infinity`` is not a+ JSON number, so it breaks the readers -- the Workbench falls back to displaying+ the six-hour default while the executor waits forever.+ """++ _bare_terminal_caller(monkeypatch)+ args = _parse_task_add(["--cron", "0 * * * *", "--shell", "./a.sh", "--timeout", timeout])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "invalid_timeout"+++def test_task_add_rejects_message_on_non_escalating_command_task(monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ args = _parse_task_add(["--cron", "0 * * * *", "--shell", "./a.sh", "--message", "look at this"])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "message_without_consumer"+ assert payload["details"]["flags"] == ["--message"]+++def test_task_add_requires_a_message_or_a_command(monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ args = _parse_task_add(["--session-id", "sesTarget", "--cron", "0 * * * *"])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "missing_task_action"+++ "flag_argv,flag_name",+ [+ (["--session-id", "sesTarget"], "--session-id"),+ (["--session-key", "slack::channel::C123"], "--session-key"),+ (["--create-session"], "--create-session"),+ (["--create-session-per-run"], "--create-session-per-run"),+ (["--scope-id", "avibe::project::proj-x"], "--scope-id"),+ (["--agent", "codex"], "--agent"),+ (["--post-to", "channel"], "--post-to"),+ (["--deliver-key", "slack::channel::C123"], "--deliver-key"),+ ],+)+def test_task_add_rejects_session_flags_for_pure_command_task(+ monkeypatch, flag_argv: list[str], flag_name: str+) -> None:+ _bare_terminal_caller(monkeypatch)+ args = _parse_task_add(["--cron", "0 3 * * *", "--shell", "./scripts/sync.sh", *flag_argv])++ result, payload = _capture_stderr_json(cli.cmd_task_add, args)++ assert result == 1+ assert payload["code"] == "session_flags_with_command_task"+ assert payload["details"]["flags"] == [flag_name]+ assert "--on-failure agent" in payload["hint"]+++# --- caller-context defaulting --------------------------------------------+++def test_task_add_pure_command_task_ignores_caller_session_default(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ """Created from chat, a pure command task must NOT inherit the calling Session.++ Otherwise ``--shell`` would be uncreatable from an Agent turn: the caller default+ would bind a Session, and a bound Session is exactly what a pure command task+ refuses to carry.+ """++ _agent_shell_caller(monkeypatch)+ db_path, agent_store = _caller_session_state(tmp_path)+ store = _command_task_store(tmp_path)+ args = _parse_task_add(["--cron", "0 3 * * *", "--shell", "./scripts/sync.sh"])++ with (+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_store", return_value=store),+ ):+ result = cli.cmd_task_add(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ definition = payload["definition"]+ assert definition["session_id"] is None+ assert definition["session_policy"] is None+ assert definition["session_key"] == ""+ assert definition["agent_name"] is None+ assert "session_default_notice" not in payload+ # The caller is still RECORDED, just not bound: creation origin survives.+ assert definition["metadata"]["created_by"]["caller"]["session_id"] == "sesCaller"+++def test_task_add_escalating_command_task_binds_caller_session(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ _agent_shell_caller(monkeypatch)+ db_path, agent_store = _caller_session_state(tmp_path)+ store = _command_task_store(tmp_path)+ args = _parse_task_add(+ [+ "--cron",+ "0 3 * * *",+ "--shell",+ "./scripts/sync.sh",+ "--on-failure",+ "agent",+ "--message",+ "The nightly sync failed. Diagnose it.",+ ]+ )++ with (+ patch("vibe.cli.paths.get_state_dir", return_value=db_path.parent),+ patch("vibe.cli.paths.get_sqlite_state_path", return_value=db_path),+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_store", return_value=store),+ ):+ result = cli.cmd_task_add(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ definition = payload["definition"]+ assert definition["session_id"] == "sesCaller"+ assert definition["session_policy"] == "existing"+ assert definition["shell_command"] == "./scripts/sync.sh"+ assert definition["prompt"] == "The nightly sync failed. Diagnose it."+ assert definition["metadata"]["on_failure"] == "agent"+ assert definition["kind"] == "command"+ assert payload["session_default_notice"]["code"] == "session_defaulted_to_caller"+++def test_task_add_per_run_command_records_the_directory_it_was_described_in(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ """SCT-047 -- a command whose Session does not exist yet still runs somewhere.++ ``--create-session-per-run`` stores no ``cwd``, on purpose: that Session is created+ at escalation, and its workdir is resolved then from the Scope or the runtime+ default. The COMMAND cannot wait for it. It fires on the next tick out of the+ definition's ``cwd``, and with nothing there it fell through to the ``~/.avibe``+ fallback -- so the documented ``--shell './scripts/sync.sh'`` ran from the product+ state directory, where the script does not exist and a relative write lands in+ persisted state.++ The Session's half of the answer must stay unanswered: recording the invocation+ directory as the definition's ``cwd`` must not also pin the Session that escalation+ creates, or a scope-bound definition would stop following its Scope's workdir.+ """++ _bare_terminal_caller(monkeypatch)+ db_path = tmp_path / "state" / "vibe.sqlite"+ agent_store = cli.VibeAgentStore(db_path)+ agent_store.create(name="worker", backend="codex")+ store = _command_task_store(tmp_path)+ invoke_dir = tmp_path / "repo"+ invoke_dir.mkdir()+ args = _parse_task_add(+ [+ "--agent",+ "worker",+ "--create-session-per-run",+ "--cron",+ "0 3 * * *",+ "--shell",+ "./scripts/sync.sh",+ "--on-failure",+ "agent",+ ]+ )++ with (+ patch("os.getcwd", return_value=str(invoke_dir)),+ patch("vibe.cli._agent_store", return_value=agent_store),+ patch("vibe.cli._task_store", return_value=store),+ ):+ result = cli.cmd_task_add(args)++ assert result == 0+ definition = json.loads(capsys.readouterr().out)["definition"]+ assert definition["session_policy"] == "create_per_run"+ assert definition["cwd"] == str(invoke_dir), (+ "the command was recorded with no directory of its own, so it fires from the "+ f"product state directory instead of where it was described: {definition['cwd']!r}"+ )+ assert "session_workdir" not in definition["metadata"], (+ "recording the command's directory also pinned the Session escalation creates"+ )+++# --- persisted shape ------------------------------------------------------+++def test_task_add_pure_shell_command_persists_command_fields(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ args = _parse_task_add(+ [+ "--name",+ "nightly-sync",+ "--cron",+ "0 3 * * *",+ "--shell",+ "./scripts/sync.sh",+ "--timeout",+ "0",+ "--cwd",+ str(tmp_path),+ ]+ )++ with patch("vibe.cli._task_store", return_value=store):+ result = cli.cmd_task_add(args)++ assert result == 0+ payload = json.loads(capsys.readouterr().out)+ definition = payload["definition"]+ assert definition["shell_command"] == "./scripts/sync.sh"+ assert definition["command"] is None+ assert definition["timeout_seconds"] == 0+ assert definition["prompt"] == ""+ assert definition["cwd"] == str(tmp_path)+ assert definition["metadata"]["on_failure"] == "none"+ assert "session_workdir" not in definition["metadata"]++ stored = store.get_task(definition["id"])+ assert stored.has_command is True+ assert stored.on_failure == "none"+ assert stored.shell_command == "./scripts/sync.sh"+ assert stored.timeout_seconds == 0+++def test_task_add_command_argv_persists_the_argv_list(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ args = _parse_task_add(+ ["--cron", "0 3 * * *", "--cwd", str(tmp_path), "--", "python3", "sync.py", "--target", "prod"]+ )++ with patch("vibe.cli._task_store", return_value=store):+ result = cli.cmd_task_add(args)++ assert result == 0+ definition = json.loads(capsys.readouterr().out)["definition"]+ assert definition["command"] == ["python3", "sync.py", "--target", "prod"]+ assert definition["shell_command"] is None+ assert definition["timeout_seconds"] is None+ assert definition["command_preview"] == "python3 sync.py --target prod"+ assert definition["display_name"] == "python3 sync.py --target prod"+++def test_task_add_message_task_stores_no_command_fields(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ """Regression guard: the message lane must be untouched by the command flags."""++ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ args = _parse_task_add(+ ["--session-key", "slack::channel::C123", "--cron", "0 * * * *", "--message", "morning briefing"]+ )++ with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),+ patch("vibe.cli._task_store", return_value=store),+ ):+ result = cli.cmd_task_add(args)++ assert result == 0+ definition = json.loads(capsys.readouterr().out)["definition"]+ assert definition["prompt"] == "morning briefing"+ assert definition["shell_command"] is None+ assert definition["command"] is None+ assert definition["timeout_seconds"] is None+ assert definition["kind"] == "message"+ assert definition["on_failure"] == "none"+ assert "on_failure" not in definition["metadata"]+++# --- update ---------------------------------------------------------------+++def _stored_command_task(store, **overrides):+ payload = {+ "name": "nightly-sync",+ "session_key": "",+ "prompt": "",+ "schedule_type": "cron",+ "cron": "0 3 * * *",+ "timezone_name": "UTC",+ "shell_command": "./scripts/old.sh",+ "timeout_seconds": 60,+ "metadata": {"on_failure": "none"},+ }+ payload.update(overrides)+ return store.add_task(**payload)+++def test_task_update_replaces_pure_command_task_shell(tmp_path: Path, capsys, monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = _stored_command_task(store, cwd=str(tmp_path))+ args = _parse_task_update(task.id, ["--shell", "./scripts/new.sh"])++ with patch("vibe.cli._task_store", return_value=store):+ result = cli.cmd_task_update(args)++ assert result == 0+ definition = json.loads(capsys.readouterr().out)["definition"]+ assert definition["shell_command"] == "./scripts/new.sh"+ # ``update_command_fields`` is all-or-nothing, so an unnamed column must survive.+ assert definition["timeout_seconds"] == 60+ assert definition["cwd"] == str(tmp_path)+ assert definition["session_policy"] is None+ assert definition["session_id"] is None+++def test_task_update_timeout_only_preserves_stored_command(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = _stored_command_task(+ store,+ shell_command=None,+ command=["python3", "sync.py"],+ cwd=str(tmp_path),+ )+ args = _parse_task_update(task.id, ["--timeout", "900"])++ with patch("vibe.cli._task_store", return_value=store):+ result = cli.cmd_task_update(args)++ assert result == 0+ definition = json.loads(capsys.readouterr().out)["definition"]+ assert definition["command"] == ["python3", "sync.py"]+ assert definition["shell_command"] is None+ assert definition["timeout_seconds"] == 900+++def test_task_update_rejects_message_flags_on_command_task(tmp_path: Path, monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = _stored_command_task(store, cwd=str(tmp_path))+ args = _parse_task_update(task.id, ["--message", "please look"])++ with patch("vibe.cli._task_store", return_value=store):+ result, payload = _capture_stderr_json(cli.cmd_task_update, args)++ assert result == 1+ assert payload["code"] == "task_mode_immutable"+ assert payload["details"]["kind"] == "command"+++def test_task_update_rewords_escalation_guidance_on_an_agent_command_task(+ tmp_path: Path, capsys, monkeypatch+) -> None:+ """SCT-007 -- an ``--on-failure agent`` task owns its message, so it stays editable.++ ``cmd_task_add`` REQUIRES ``--on-failure agent`` for a message to be legal beside+ a command (``message_without_consumer``), so rejecting the message here forbade+ exactly the shape the add path blesses -- leaving the escalation guidance+ rewordable only by deleting and recreating the task. The command columns must+ survive the edit untouched: this is a message change, not a mode switch.+ """++ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = _stored_command_task(+ store,+ cwd=str(tmp_path),+ prompt="The nightly sync failed. Diagnose it.",+ session_key="slack::channel::C123",+ metadata={"on_failure": "agent"},+ )+ args = _parse_task_update(task.id, ["--message", "Check the upstream API first."])++ with (+ patch("vibe.cli._ensure_config", return_value=_configured_v2({"slack"})),+ patch("vibe.cli._task_store", return_value=store),+ ):+ result = cli.cmd_task_update(args)++ assert result == 0+ definition = json.loads(capsys.readouterr().out)["definition"]+ assert definition["prompt"] == "Check the upstream API first."+ assert definition["shell_command"] == "./scripts/old.sh"+ assert definition["timeout_seconds"] == 60+ assert definition["on_failure"] == "agent"+++def test_task_update_rejects_command_flags_on_message_task(tmp_path: Path, monkeypatch) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="morning briefing",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )+ args = _parse_task_update(task.id, ["--shell", "./scripts/new.sh"])++ with patch("vibe.cli._task_store", return_value=store):+ result, payload = _capture_stderr_json(cli.cmd_task_update, args)++ assert result == 1+ assert payload["code"] == "task_mode_immutable"+ assert payload["details"]["kind"] == "message"+ assert payload["details"]["flags"] == ["--shell"]+++def test_task_update_rejects_failure_handling_change(tmp_path: Path, monkeypatch) -> None:+ """Escalation decides whether the definition owns a Session, so it is not editable."""++ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = _stored_command_task(store, cwd=str(tmp_path))+ args = _parse_task_update(task.id, ["--on-failure", "agent"])++ with patch("vibe.cli._task_store", return_value=store):+ result, payload = _capture_stderr_json(cli.cmd_task_update, args)++ assert result == 1+ assert payload["code"] == "task_mode_immutable"+ assert payload["details"]["on_failure"] == "none"+ assert payload["details"]["requested_on_failure"] == "agent"+++def test_task_update_rejects_session_flags_on_pure_command_task(+ tmp_path: Path, monkeypatch+) -> None:+ _bare_terminal_caller(monkeypatch)+ store = _command_task_store(tmp_path)+ task = _stored_command_task(store, cwd=str(tmp_path))+ args = _parse_task_update(task.id, ["--session-id", "sesTarget"])++ with patch("vibe.cli._task_store", return_value=store):+ result, payload = _capture_stderr_json(cli.cmd_task_update, args)++ assert result == 1+ assert payload["code"] == "session_flags_with_command_task"+++# --- rendering ------------------------------------------------------------+++def test_task_payload_renders_command_kind_and_preview(tmp_path: Path) -> None:+ store = _command_task_store(tmp_path)+ task = _stored_command_task(store, name=None, shell_command="./scripts/sync.sh --verbose")+ task.last_exit_code = 2++ payload = cli._task_payload(task)+ brief = cli._task_payload(task, brief=True)++ assert payload["kind"] == "command"+ assert payload["on_failure"] == "none"+ assert payload["command_preview"] == "./scripts/sync.sh --verbose"+ assert payload["display_name"] == "./scripts/sync.sh --verbose"+ assert brief["kind"] == "command"+ assert brief["last_exit_code"] == 2+++def test_task_payload_renders_message_kind_for_message_tasks(tmp_path: Path) -> None:+ store = _command_task_store(tmp_path)+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="morning briefing",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )++ payload = cli._task_payload(task)++ assert payload["kind"] == "message"+ assert payload["command_preview"] == ""+ assert payload["display_name"] == "morning briefing"+ assert cli._task_payload(task, brief=True)["last_exit_code"] is None+++# --- documented examples --------------------------------------------------+++def test_documented_task_command_examples_stay_parseable() -> None:+ """Injected help text is a live caller: every example must survive the parser."""++ parser = cli.build_parser()+ text = cli._task_add_examples_text() + "\n" + cli._task_update_examples_text()+ examples = [+ line.strip()+ for line in text.splitlines()+ if line.strip().startswith(("vibe task add ", "vibe task update "))+ ]+ command_examples = [line for line in examples if "--shell" in line or "--timeout" in line]+ assert len(examples) >= 4+ assert len(command_examples) >= 3++ for example in examples:+ parser.parse_args(shlex.split(example)[1:])diff --git a/tests/test_command_runner.py b/tests/test_command_runner.pynew file mode 100644index 000000000..dc8ba224c--- /dev/null+++ b/tests/test_command_runner.py@@ -0,0 +1,497 @@+"""Tests for the shared supervised-command runner."""++from __future__ import annotations++import asyncio+import os+import sys+from pathlib import Path++import pytest++from core import command_runner, watch_worker+from core.command_runner import (+ STREAM_TRUNCATION_MARKER,+ SupervisedCommandResult,+ SupervisedCommandStartupError,+ run_supervised_command,+)+++class _FakeStdin:+ def __init__(self) -> None:+ self.payload = bytearray()+ self.closed = False++ def write(self, payload: bytes) -> None:+ self.payload.extend(payload)++ async def drain(self) -> None:+ return None++ def close(self) -> None:+ self.closed = True+++class _BrokenStdin(_FakeStdin):+ async def drain(self) -> None:+ raise BrokenPipeError+++class _FakeProcess:+ def __init__(+ self,+ *,+ stdin: _FakeStdin | None = None,+ stderr: bytes = b"",+ ) -> None:+ self.pid = 1234+ self.returncode = 0+ self.stdin = stdin or _FakeStdin()+ self.stderr = stderr++ async def communicate(self) -> tuple[bytes, bytes]:+ return b"ok\n", self.stderr+++def _pid_alive(pid: int) -> bool:+ try:+ os.kill(pid, 0)+ except ProcessLookupError:+ return False+ except PermissionError:+ return True+ return True+++def _pid_exited(pid: int) -> bool:+ """Dead as far as these tests care: exited, whether or not it has been waited on.++ The kill fallback in ``_reap_or_kill`` deliberately does NOT await+ ``communicate()`` -- a failed drain is exactly what put it there -- so the exited+ supervisor can sit as a zombie for the moment it takes asyncio's child watcher to+ reap it, and ``os.kill(pid, 0)`` succeeds for a zombie. Where ``/proc`` is+ unavailable this degrades to the liveness check alone.+ """++ if not _pid_alive(pid):+ return True+ try:+ with open(f"/proc/{pid}/stat", "rb") as handle:+ fields = handle.read().rsplit(b")", 1)[-1].split()+ except OSError:+ return False+ return bool(fields) and fields[0] == b"Z"+++async def _wait_until_exited(pid: int, *, attempts: int = 100) -> bool:+ for _ in range(attempts):+ if _pid_exited(pid):+ return True+ await asyncio.sleep(0.05)+ return False+++async def test_argv_command_success_reports_streams_and_exit_code(tmp_path: Path) -> None:+ result = await run_supervised_command(+ command=[+ sys.executable,+ "-c",+ "import sys; print('out'); print('err', file=sys.stderr); sys.exit(0)",+ ],+ cwd=str(tmp_path),+ timeout_seconds=10,+ label="test argv",+ )++ assert isinstance(result, SupervisedCommandResult)+ assert result.exit_code == 0+ assert "out" in result.stdout+ assert "err" in result.stderr+ assert result.timed_out is False+ assert result.stdout_truncated is False+ assert result.stderr_truncated is False+++async def test_shell_command_success_preserves_non_zero_exit_code(tmp_path: Path) -> None:+ result = await run_supervised_command(+ shell_command="echo hi; exit 7",+ cwd=str(tmp_path),+ timeout_seconds=10,+ label="test shell",+ )++ assert result.exit_code == 7+ assert "hi" in result.stdout+ assert result.timed_out is False+++async def test_timeout_terminates_child_and_maps_exit_code_124(tmp_path: Path) -> None:+ result = await run_supervised_command(+ command=[sys.executable, "-c", "import time; time.sleep(30)"],+ cwd=str(tmp_path),+ timeout_seconds=1,+ label="test timeout",+ )++ assert result.timed_out is True+ assert result.exit_code == 124+ assert result.stdout == ""+++async def test_timeout_keeps_the_output_the_capped_readers_already_retained(+ tmp_path: Path,+) -> None:+ """SCT-006 -- a timed-out command keeps what it printed before it hung.++ The capped readers hold the retained bytes in their own buffers, so cancelling+ them on timeout threw away exactly the diagnostic the user needs to understand+ why the command hung -- and a timeout is the failure mode where that output+ matters most, because there is no exit status to explain it.++ Only the capped path is asserted here. Watches pass ``max_output_bytes=None``+ and keep ``communicate()`` semantics, guarded by+ ``test_timeout_terminates_child_and_maps_exit_code_124`` above.+ """++ result = await run_supervised_command(+ shell_command="echo diagnostic; sleep 30",+ cwd=str(tmp_path),+ timeout_seconds=1,+ label="test timeout output",+ max_output_bytes=64 * 1024,+ )++ assert result.timed_out is True+ assert result.exit_code == 124+ assert "diagnostic" in result.stdout+++async def test_zero_timeout_means_no_timeout(tmp_path: Path) -> None:+ result = await run_supervised_command(+ command=[sys.executable, "-c", "import time; time.sleep(0.2); print('done')"],+ cwd=str(tmp_path),+ timeout_seconds=0,+ label="test no timeout",+ )++ assert result.timed_out is False+ assert result.exit_code == 0+ assert "done" in result.stdout+++async def test_on_spawn_is_called_once_before_the_result_returns(tmp_path: Path) -> None:+ spawns: list[tuple[int, object]] = []++ def on_spawn(pid: int, identity: object) -> None:+ spawns.append((pid, identity))++ result = await run_supervised_command(+ command=[sys.executable, "-c", "print('ok')"],+ cwd=str(tmp_path),+ timeout_seconds=10,+ label="test on_spawn",+ on_spawn=on_spawn,+ )++ assert result.exit_code == 0+ assert len(spawns) == 1+ pid, identity = spawns[0]+ assert pid > 0+ assert identity is None or identity.pid == pid+++async def test_cancellation_propagates_and_kills_the_child(tmp_path: Path) -> None:+ spawned: list[int] = []++ task = asyncio.ensure_future(+ run_supervised_command(+ command=[sys.executable, "-c", "import time; time.sleep(30)"],+ cwd=str(tmp_path),+ timeout_seconds=0,+ label="test cancel",+ on_spawn=lambda pid, _identity: spawned.append(pid),+ )+ )+ for _ in range(200):+ if spawned:+ break+ await asyncio.sleep(0.02)+ assert spawned, "the supervisor never spawned"++ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ pid = spawned[0]+ for _ in range(100):+ if not _pid_alive(pid):+ break+ await asyncio.sleep(0.05)+ assert not _pid_alive(pid)+++async def test_an_unexpected_error_after_the_spawn_still_reaps_the_command(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-035 -- cancellation and timeout are not the only ways out of a run.++ Those two ways out reap the tree; every other exception left it running. An+ ``OSError`` draining a capped pipe, one reader dying while its twin still reads,+ an unexpected fault anywhere between the spawn and the collector -- the exception+ propagated with the supervisor and the backup or migration under it untouched.++ That is the unrecoverable case, not merely an untidy one: ``on_spawn`` has already+ handed the caller the worker's identity, and the scheduled-task caller clears it in+ its own ``finally`` the moment this raises, on the documented assumption that the+ runner has reaped the tree by then. So the orphan is left with nothing on disk+ naming it, and the next fire runs a second copy beside it.+ """++ spawned: list[int] = []++ async def _explode(*_args, **_kwargs):+ raise OSError("the pipe went away")++ monkeypatch.setattr(command_runner, "_read_capped_stream", _explode)++ with pytest.raises(OSError, match="the pipe went away"):+ await run_supervised_command(+ command=[sys.executable, "-c", "import time; time.sleep(30)"],+ cwd=str(tmp_path),+ timeout_seconds=0,+ label="test unexpected failure",+ on_spawn=lambda pid, _identity: spawned.append(pid),+ # The capped path, because that is where the readers -- and the realistic+ # unexpected failure -- live.+ max_output_bytes=65536,+ )++ assert spawned, "the supervisor never spawned, so nothing could be orphaned"+ pid = spawned[0]+ for _ in range(100):+ if not _pid_alive(pid):+ break+ await asyncio.sleep(0.05)+ assert not _pid_alive(pid), (+ "an unexpected runner error left the supervisor and its command running while "+ "the caller was clearing the only record of them"+ )+++async def test_a_teardown_that_cannot_drain_still_kills_the_command(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-045 -- the two specialized handlers survive their OWN teardown failing.++ Cancellation and timeout each reap the tree by draining it, and a drain can fail:+ an ``OSError`` on a pipe, a ``RuntimeError`` from a loop already closing. Both+ handlers are ``except`` clauses, so an exception raised out of one is not caught by+ the catch-all clause beside it -- the fix in SCT-035 does not cover them. The frame+ then left with the supervisor still running, while the scheduled-task caller cleared+ the worker record in its own ``finally``: the same orphan-with-no-name as SCT-035,+ reached through the paths that were supposed to be the safe ones.++ Both handlers are driven here because they fail differently: cancellation owes the+ caller a ``CancelledError``, a timeout owes it a 124 result, and neither may be+ replaced by the teardown's own error.+ """++ async def _explode(*_args, **_kwargs):+ raise OSError("the pipe went away")++ monkeypatch.setattr(command_runner, "terminate_and_communicate", _explode)++ timed_out_spawns: list[int] = []+ result = await run_supervised_command(+ command=[sys.executable, "-c", "import time; time.sleep(30)"],+ cwd=str(tmp_path),+ timeout_seconds=1,+ label="test timeout teardown failure",+ on_spawn=lambda pid, _identity: timed_out_spawns.append(pid),+ )++ assert result.timed_out is True+ assert result.exit_code == 124+ assert timed_out_spawns, "the supervisor never spawned"+ assert await _wait_until_exited(timed_out_spawns[0]), (+ "a timeout whose drain failed left the supervisor and its command running"+ )++ canceled_spawns: list[int] = []+ task = asyncio.ensure_future(+ run_supervised_command(+ command=[sys.executable, "-c", "import time; time.sleep(30)"],+ cwd=str(tmp_path),+ timeout_seconds=0,+ label="test cancel teardown failure",+ on_spawn=lambda pid, _identity: canceled_spawns.append(pid),+ )+ )+ for _ in range(200):+ if canceled_spawns:+ break+ await asyncio.sleep(0.02)+ assert canceled_spawns, "the supervisor never spawned"++ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await task++ assert await _wait_until_exited(canceled_spawns[0]), (+ "a cancellation whose drain failed left the supervisor and its command running"+ )+++async def test_startup_pipe_break_raises_startup_error_with_raw_detail(tmp_path: Path, monkeypatch) -> None:+ process = _FakeProcess(+ stdin=_BrokenStdin(),+ stderr=watch_worker.encode_watch_worker_error("invalidCommand").encode() + b"\n",+ )++ async def fake_create_subprocess_exec(*_args, **_kwargs):+ return process++ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)++ with pytest.raises(SupervisedCommandStartupError) as excinfo:+ await run_supervised_command(+ command=[sys.executable, "-c", "print('ok')"],+ cwd=str(tmp_path),+ timeout_seconds=5,+ label="test startup",+ )++ assert excinfo.value.detail == watch_worker.encode_watch_worker_error("invalidCommand")+ assert process.stdin.closed is True+++async def test_spawn_uses_the_stable_supervisor_entrypoint(tmp_path: Path, monkeypatch) -> None:+ captured: dict[str, object] = {}++ async def fake_create_subprocess_exec(*args, **kwargs):+ captured["args"] = args+ captured["kwargs"] = kwargs+ return _FakeProcess()++ monkeypatch.setattr(asyncio, "create_subprocess_exec", fake_create_subprocess_exec)++ result = await run_supervised_command(+ command=["python3", "-c", "print('ok')"],+ cwd=str(tmp_path),+ timeout_seconds=5,+ label="test argv shape",+ )++ assert result.exit_code == 0+ assert captured["args"] == (+ os.path.abspath(sys.executable),+ str(Path(watch_worker.__file__).resolve()),+ )+ kwargs = captured["kwargs"]+ assert kwargs["cwd"] == str(tmp_path)+ assert kwargs["stdin"] == asyncio.subprocess.PIPE+ assert kwargs["stdout"] == asyncio.subprocess.PIPE+ assert kwargs["stderr"] == asyncio.subprocess.PIPE+++_LARGE_OUTPUT_COMMAND = (+ "import sys; sys.stdout.write('x' * 300000); sys.stdout.flush(); sys.exit(0)"+)+++async def test_output_cap_truncates_but_keeps_draining(tmp_path: Path) -> None:+ result = await run_supervised_command(+ command=[sys.executable, "-c", _LARGE_OUTPUT_COMMAND],+ cwd=str(tmp_path),+ timeout_seconds=20,+ label="test cap",+ max_output_bytes=65536,+ )++ assert result.timed_out is False+ assert result.exit_code == 0+ assert len(result.stdout.encode("utf-8")) <= 65536+ assert result.stdout_truncated is True+ assert result.stderr_truncated is False+++async def test_output_cap_keeps_the_tail_where_the_cause_usually_is(tmp_path: Path) -> None:+ """SCT-015 -- a capped stream must retain its END, not only its beginning.++ Every consumer of a failed command's output reads the tail: the notice and the CLI+ list show ``_last_nonempty_line`` of stderr, because a failure's explanation is the+ last thing written (a traceback's exception line, a shell's "command not found").+ A head-only cap makes that read a lie -- it reports the last line of the first 64 KiB+ of a chatty command and drops the sentence that says why the run failed, with no+ sign that the real ending was ever there.++ Head is kept too: the first error in a build log is at the top. The gap between them+ is marked, and the tail starts on a line boundary, so no consumer can mistake a+ spliced fragment for a line the command actually printed.+ """++ result = await run_supervised_command(+ command=[+ sys.executable,+ "-c",+ (+ "import sys\n"+ "sys.stderr.write('noise line\\n' * 40000)\n"+ "sys.stderr.write('FINAL: the cause of the failure\\n')\n"+ ),+ ],+ cwd=str(tmp_path),+ timeout_seconds=20,+ label="test cap tail",+ max_output_bytes=65536,+ )++ assert result.exit_code == 0+ assert result.stderr_truncated is True+ assert len(result.stderr.encode("utf-8")) <= 65536, (+ "the cap stays a hard cap on the returned bytes, marker included"+ )+ lines = [line for line in result.stderr.splitlines() if line.strip()]+ assert lines[-1] == "FINAL: the cause of the failure", (+ f"the real last line is what the notice reads: {lines[-3:]}"+ )+ assert lines[0] == "noise line", f"the head is retained as whole lines too: {lines[:2]}"+ assert STREAM_TRUNCATION_MARKER.decode().strip() in result.stderr, (+ "the dropped middle has to be visible, not a silent splice"+ )+ assert set(lines) <= {+ "noise line",+ "FINAL: the cause of the failure",+ STREAM_TRUNCATION_MARKER.decode().strip(),+ }, "no spliced fragment may appear as a line the command never printed"+++async def test_output_cap_leaves_small_output_untruncated(tmp_path: Path) -> None:+ result = await run_supervised_command(+ command=[sys.executable, "-c", "print('small')"],+ cwd=str(tmp_path),+ timeout_seconds=20,+ label="test cap small",+ max_output_bytes=65536,+ )++ assert result.exit_code == 0+ assert "small" in result.stdout+ assert result.stdout_truncated is False+ assert result.stderr_truncated is False+++async def test_no_cap_returns_large_output_in_full(tmp_path: Path) -> None:+ result = await run_supervised_command(+ command=[sys.executable, "-c", _LARGE_OUTPUT_COMMAND],+ cwd=str(tmp_path),+ timeout_seconds=20,+ label="test uncapped",+ max_output_bytes=None,+ )++ assert result.exit_code == 0+ assert len(result.stdout.encode("utf-8")) == 300000+ assert result.stdout_truncated is False+ assert result.stderr_truncated is Falsediff --git a/tests/test_harness_definition_lifecycle.py b/tests/test_harness_definition_lifecycle.pyindex 44755e412..057758bc3 100644--- a/tests/test_harness_definition_lifecycle.py+++ b/tests/test_harness_definition_lifecycle.py@@ -249,21 +249,39 @@ def test_an_unknown_status_is_rejected_rather_than_silently_ignored(store) -> No@pytest.mark.parametrize(- ("exit_code", "error", "expected"),+ ("exit_code", "error", "timed_out", "expected"),[- (0, None, "normal"),- (None, None, "normal"),- (124, "waiter timed out", "timeout"),- (1, "boom", "error"),+ (0, None, None, "normal"),+ (None, None, None, "normal"),+ # A watch cycle, and every row written before the scheduler recorded the fact:+ # 124 is all there is to go on, so it still reads as a timeout.+ (124, "waiter timed out", None, "timeout"),+ (1, "boom", None, "error"),# Scheduled tasks never write an exit code, so the code alone would call# every failed one a normal ending.- (None, "boom", "error"),- (0, " ", "normal"),+ (None, "boom", None, "error"),+ (0, " ", None, "normal"),+ # SCT-024. The scheduler is the only witness to its own timeout: a command+ # that wraps itself in ``timeout`` reports a REAL one as 124 too, and calling+ # that "stopped for running too long" tells the user to raise a limit that+ # was never reached.+ (124, "command exited with status 124", False, "error"),+ (124, "command timed out after 5 second(s)", True, "timeout"),+ # And the flag outranks the code in the other direction as well: a command+ # killed by the scheduler that still managed its own exit status.+ (137, "command timed out after 5 second(s)", True, "timeout"),],)-def test_lifecycle_detail_names_how_a_finished_row_ended(exit_code, error, expected) -> None:+def test_lifecycle_detail_names_how_a_finished_row_ended(+ exit_code, error, timed_out, expected+) -> None:assert (- definition_lifecycle_detail(lifecycle_state="finished", last_exit_code=exit_code, last_error=error)+ definition_lifecycle_detail(+ lifecycle_state="finished",+ last_exit_code=exit_code,+ last_error=error,+ timed_out=timed_out,+ )== expected)@@ -838,6 +856,92 @@ def test_naive_one_shot_uses_its_task_timezone_in_rows_counts_and_next_fire(storassert (counts["waiting"], counts["finished"]) == (1, 1)+def test_searching_tasks_looks_at_what_a_command_task_actually_runs(store) -> None:+ """SCT-011 -- a command task is findable by its command, like a watch already is.++ Search offers a different field list per definition type, and the ``scheduled``+ branch was written when every task was a prompt: it reads ``message``/``prompt``+ but not ``shell_command``/``command_json``. A command task stores its instruction+ in the latter and can leave ``message`` empty (nothing is being said to an Agent),+ so the only text distinguishing it was the one text search would not read. The+ ``watch`` branch has always read both columns; tasks now share them.++ ``cwd`` is deliberately still excluded here: task rows overwhelmingly share one+ working directory, so matching on it would return almost everything.+ """++ _task(store, "deploy-task", name="nightly", shell_command="./scripts/sync.sh --dry-run")+ _task(store, "argv-task", name="probe", command=["curl", "-sf", "https://health.local"])+ _task(store, "prompt-task", name="digest", prompt="summarise the day")++ def _found(query: str) -> set[str]:+ page = store.list_scheduled_tasks_page(page_request=PageRequest(limit=50), query=query)+ return {row["id"] for row in page.items}++ assert _found("sync.sh") == {"deploy-task"}, "a shell command task is unfindable"+ assert _found("health.local") == {"argv-task"}, "an argv command task is unfindable"+ assert _found("summarise") == {"prompt-task"}, "and message search still works"+ # The chips count the same rows the list returns, because both go through+ # ``_definitions_query``; a field added to one but not the other splits them.+ assert store.count_scheduled_tasks(query="sync.sh")["total"] == 1+++def test_an_escalation_turn_is_not_a_verdict_on_the_command_that_queued_it(store) -> None:+ """SCT-014 -- the Agent turn REPORTING a failure must not report it as a success.++ A ``--on-failure agent`` escalation is an ``agent_runs`` row carrying the failing+ definition's own ``definition_id`` -- which is what links the turn to the task -- and+ it settles ``succeeded`` whenever the Agent answers, because answering is all it was+ asked to do. Read as one of the definition's verdicts it is the newest row in the+ window, so the health badge went green on the strength of the very turn that exists+ to say the command broke, "last succeeded" pointed at that turn, and a success+ between two failures closed the failure streak.++ Exactly the ``watch_runtime`` shape (a row sharing a definition's id that is not+ that definition's outcome), so it takes the same exclusion.+ """++ settled = datetime.now(timezone.utc)+ fresh = (settled - timedelta(minutes=5)).isoformat()+ later = settled.isoformat()++ _task(store, "backup", name="nightly backup", shell_command="./scripts/backup.sh")+ for index in range(2):+ _run(+ store,+ f"fire-{index}",+ "backup",+ request_type="scheduled",+ run_type="scheduled",+ status="failed",+ error="command exited with status 2",+ created_at=fresh,+ completed_at=fresh,+ )+ # The turn the second failure queued, and it answered.+ _run(+ store,+ "escalation-1",+ "backup",+ request_type="task_escalation",+ run_type="task_escalation",+ status="succeeded",+ parent_run_id="fire-1",+ created_at=later,+ completed_at=later,+ )++ health = store.definition_health("backup")+ assert health["health"] == "failing", (+ "the escalation turn reporting the failure was counted as the task succeeding: "+ f"{health}"+ )+ assert health["consecutive_failures"] == 2+ assert store.last_success_settled_at("backup") is None, (+ "the definition has never succeeded, but the escalation turn claimed it did"+ )++def test_mark_cycle_result_stamps_a_finish_only_when_it_retires_the_watch(tmp_path: Path) -> None:"""Only the cycle that changes enabled -> disabled owns retirement state."""from core.watches import ManagedWatchStorediff --git a/tests/test_harness_failure_visibility.py b/tests/test_harness_failure_visibility.pyindex 450747917..f80be2bc7 100644--- a/tests/test_harness_failure_visibility.py+++ b/tests/test_harness_failure_visibility.py@@ -3108,6 +3108,11 @@ def _drain_service(tmp_path: Path, controller, sqlite, requests):# service built without ``__init__`` still needs the handle the dispatcher keys its# single-flight check on.service._notice_drain_task = None+ # The tick also observes cancellations requested against work THIS process runs, and+ # that pass reads the in-flight registry first. Empty here: this service never claims+ # a request, so the pass is a no-op — but the attribute has to exist, because an+ # AttributeError inside the tick aborts every LATER pass in it.+ service._inflight_executions = {}service.controller = controllerservice._owns_service_instance = lambda: Trueservice.validate_platform = lambda platform: None@@ -10126,8 +10131,9 @@ def test_the_last_success_read_is_one_bounded_indexed_seek(tmp_path: Path) -> No)assert "DEFINITION_ID = ?" in normalized, f"the definition is an equality term: {statement}"assert "STATUS IN" in normalized, f"the verdict filter is a SQL term: {statement}"- assert "RUN_TYPE !=" in normalized, (- f"the watch-supervisor exclusion is a SQL term too: {statement}"+ assert "RUN_TYPE NOT IN" in normalized, (+ "the non-verdict exclusion (watch supervisor, escalation turn) is a SQL term too: "+ f"{statement}")# And the answer is the real one: the newest succeeded row in the history above.@@ -12244,3 +12250,541 @@ def test_the_workspace_card_carries_the_creation_origin(assert _SLACK_ORIGIN_PERMALINK in card, (f"and give the user a way back to it: {card}")+++# --- command-task notice copy (tests/scenarios/harness_command_task) -------+#+# A command definition runs a subprocess and never prompts an Agent, so its failure+# notice was the only place the user could learn a scheduled command broke — and it+# named the definition and the error while never naming the COMMAND. These tests pin+# the failed-lane copy (command line before the error, exit code after it, and only+# when the row carries one) and the two closed-loop scenarios SCT-001/SCT-002.+++def _command_task(sqlite, definition_id: str, **overrides) -> None:+ """One command definition: no prompt, a command, and a rung-(1) delivery key."""++ payload = {+ "name": definition_id,+ "prompt": "",+ "deliver_key": "slack::channel::C1",+ "shell_command": "echo boom >&2; exit 7",+ }+ payload.update(overrides)+ _task(sqlite, definition_id, **payload)+++def _command_run(definition_id: str, run_id: str = "run-cmd", **overrides) -> dict:+ """The run row shape a settled command fire leaves behind."""++ run = {+ "id": run_id,+ "task_id": definition_id,+ "error": "command exited with status 7: boom",+ "exit_code": 7,+ "stdout": "",+ "stderr": "boom\n",+ }+ run.update(overrides)+ return run+++def _notice_prefix(key: str, language: str = "en") -> str:+ from vibe.i18n import t as i18n_t++ return i18n_t(key, language).split("{")[0].strip()++[email protected]("language", ["en", "zh"])+def test_a_failed_command_notice_names_the_command_then_the_error_then_the_exit_code(+ tmp_path: Path,+ language: str,+) -> None:+ """The failed lane's command copy, in the order a reader needs it.++ WHAT it ran, WHY it failed, and the exit status it failed with. Order is asserted+ rather than mere membership: the command has to arrive before the error it explains,+ and the exit code after it, or the three lines read as unrelated facts.++ Both languages, through the REAL translator, for the same reason the failure-class+ test does it: a ``_t`` that echoes keys proves which key was chosen and says nothing+ about whether the sentence a user reads is translated.+ """++ from types import SimpleNamespace++ sqlite, requests = _store(tmp_path)+ _command_task(sqlite, "task-cmd")++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), language+ )+ body = service._failure_notice_body(+ _command_run("task-cmd"), {"failure_id": "run-cmd", "interrupt_reason": None}+ )++ command_line = _notice_prefix("harness.notice.commandLine", language)+ error_line = _notice_prefix("harness.notice.error", language)+ exit_line = _notice_prefix("harness.notice.commandExit", language)++ assert "echo boom >&2; exit 7" in body, f"the notice must name the command: {body}"+ assert command_line in body and exit_line in body, (+ f"both command lines must be rendered through localized copy: {body}"+ )+ assert "7" in body.split(exit_line)[1].splitlines()[0], (+ f"the exit line must carry the exit code: {body}"+ )+ assert body.index(command_line) < body.index(error_line) < body.index(exit_line), (+ f"command, then error, then exit code: {body}"+ )+ assert "harness.notice." not in body, f"never a dotted key path: {body}"+++def test_an_argv_command_notice_renders_the_shell_joined_argv(tmp_path: Path) -> None:+ """The ``-- argv`` form has no shell string, so the preview joins the list.++ ``str(list)`` would print Python repr quoting at a user; ``shlex.join`` prints+ something the user can paste back into a shell, which is the same choice+ ``vibe task list`` already made.+ """++ from types import SimpleNamespace++ sqlite, requests = _store(tmp_path)+ _command_task(+ sqlite,+ "task-argv",+ shell_command=None,+ command=["/bin/sh", "-c", "echo hello world"],+ )++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ body = service._failure_notice_body(+ _command_run("task-argv"), {"failure_id": "run-cmd", "interrupt_reason": None}+ )++ assert "/bin/sh -c 'echo hello world'" in body, (+ f"the argv preview must be shell-joined, not a Python list: {body}"+ )+ assert "['/bin/sh'" not in body, f"and never a repr: {body}"+++def test_a_notice_names_the_command_the_run_actually_executed(tmp_path: Path) -> None:+ """SCT-019 -- the command copy comes from the RUN, not from the live definition.++ The notice drain is asynchronous and the definition is editable: between the fire+ settling and the notice going out, the user can rewrite the command or delete the+ task. Composing the line from ``get_task`` therefore reported the REPLACEMENT+ command as the thing that failed -- and after a delete, dropped the line entirely --+ while the run row itself kept only output and an exit code and could not say what+ had run. Either way the user debugs the wrong command, or none.++ So the fire snapshots its own command onto the run, and every later reader uses the+ snapshot. The live definition stays the fallback for rows written before the+ snapshot existed.+ """++ from types import SimpleNamespace++ sqlite, requests = _store(tmp_path)+ # The definition as it is NOW: already rewritten since the fire.+ _command_task(sqlite, "task-edited", shell_command="./scripts/backup-v2.sh --fast")++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ body = service._failure_notice_body(+ _command_run(+ "task-edited",+ metadata={"command": {"shell": "./scripts/backup.sh", "argv": []}},+ ),+ {"failure_id": "run-cmd", "interrupt_reason": None},+ )++ assert "./scripts/backup.sh" in body, (+ f"the notice must name the command the run actually executed: {body}"+ )+ assert "backup-v2" not in body, (+ f"and never the replacement the user has since configured: {body}"+ )++ # And the harder half of the same defect: once the definition is DELETED,+ # ``get_task`` has no answer at all, so the command line vanished from exactly the+ # notice that needs it most -- a task the user can no longer inspect.+ deleted = service._failure_notice_body(+ _command_run(+ "task-gone",+ metadata={"command": {"shell": None, "argv": ["/bin/sh", "-c", "echo hi there"]}},+ ),+ {"failure_id": "run-cmd", "interrupt_reason": None},+ )++ assert "/bin/sh -c 'echo hi there'" in deleted, (+ f"a removed definition's run still names its command, shell-joined: {deleted}"+ )+++def test_a_command_that_never_spawned_carries_no_exit_code_line(tmp_path: Path) -> None:+ """No exit code exists, so no exit line — the row is the only source of truth.++ A missing working directory is refused BEFORE the spawn, so the run settles with+ ``exit_code`` NULL. "Exit code: None", or a fabricated 0, would be a lie on the one+ surface that has to be trusted. The command line still renders: the user still needs+ to know which definition's command could not be run.+ """++ from types import SimpleNamespace++ sqlite, requests = _store(tmp_path)+ _command_task(sqlite, "task-nospawn")++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ body = service._failure_notice_body(+ _command_run(+ "task-nospawn",+ error="working directory does not exist: /nope/gone",+ exit_code=None,+ ),+ {"failure_id": "run-cmd", "interrupt_reason": None},+ )++ assert _notice_prefix("harness.notice.commandLine") in body, (+ f"a no-spawn failure still names its command: {body}"+ )+ assert "/nope/gone" in body, f"and still carries the error: {body}"+ assert _notice_prefix("harness.notice.commandExit") not in body, (+ f"a run with no exit code must get no exit line: {body}"+ )+ assert "None" not in body, f"and must never render the missing value: {body}"+++def test_a_long_command_is_truncated_in_the_notice(tmp_path: Path) -> None:+ """A notice is a chat message: an uncapped pipeline would bury the error line.++ Same 120-char cap and trailing ellipsis as the CLI preview, so the notice and+ ``vibe task list`` show the same string for the same definition.+ """++ from types import SimpleNamespace++ sqlite, requests = _store(tmp_path)+ long_command = "echo " + ("x" * 200)+ _command_task(sqlite, "task-long", shell_command=long_command)++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ body = service._failure_notice_body(+ _command_run("task-long"), {"failure_id": "run-cmd", "interrupt_reason": None}+ )++ rendered = [line for line in body.splitlines() if line.startswith(_notice_prefix("harness.notice.commandLine"))]+ assert len(rendered) == 1, f"exactly one command line: {body}"+ assert long_command not in body, f"the full command must not be rendered: {body}"+ assert "…" in rendered[0], f"a truncated preview must say so: {rendered[0]}"+ preview = rendered[0].split(":", 1)[1].strip()+ assert len(preview) == 120, f"the cap is 120 characters: {len(preview)}"+++def test_a_message_task_notice_carries_no_command_copy(tmp_path: Path) -> None:+ """The regression guard: an Agent-prompting task's notice is unchanged.++ A message task has no command, so neither line may appear — not with an empty+ value, and not at all.+ """++ from types import SimpleNamespace++ sqlite, requests = _store(tmp_path)+ _task(sqlite, "task-message", name="daily report", deliver_key="slack::channel::C1")++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ body = service._failure_notice_body(+ {"id": "run-msg", "task_id": "task-message", "error": "backend exploded"},+ {"failure_id": "run-msg", "interrupt_reason": None},+ )++ assert _notice_prefix("harness.notice.commandLine") not in body, (+ f"a message task's notice must carry no command line: {body}"+ )+ assert _notice_prefix("harness.notice.commandExit") not in body, (+ f"nor an exit line: {body}"+ )+ assert _notice_prefix("harness.notice.error") in body, f"the error line stays: {body}"+++def test_an_interrupted_command_run_keeps_the_generic_interruption_copy(+ tmp_path: Path,+) -> None:+ """An interrupted command run is a fact about the SERVICE, not about the command.++ The interrupted headline already says nothing is wrong with the definition itself;+ printing the command and an exit code beside it would invite the user to go and+ debug a command that was never given the chance to finish. So the command copy is+ gated on the FAILED lane by the same predicate the rest of the body uses.+ """++ from types import SimpleNamespace++ import core.failure_notices as failure_notices++ sqlite, requests = _store(tmp_path)+ _command_task(sqlite, "task-cmd-interrupted")++ notice = {"failure_id": "run-cmd", "interrupt_reason": "restarted"}+ assert failure_notices.is_interruption(notice), (+ "the premise: this reason belongs to the interrupted lane"+ )++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ body = service._failure_notice_body(+ _command_run(+ "task-cmd-interrupted",+ error="the service restarted",+ exit_code=None,+ ),+ notice,+ )++ assert _notice_prefix("harness.notice.commandLine") not in body, (+ f"the interrupted lane keeps generic copy: {body}"+ )+ assert _notice_prefix("harness.notice.commandExit") not in body, (+ f"including no exit line: {body}"+ )+++def _command_fire_service(tmp_path: Path, sqlite, requests):+ """A REAL ``ScheduledTaskService`` over tmp-path stores that can fire a command.++ Built through ``__init__`` rather than ``__new__``, because these two scenarios are+ about the executor and the drain being CONNECTED: a fake settle would prove the copy+ and nothing about whether a real command fire reaches it. Only the scheduler and the+ two ownership guards are stubbed — the parts that would otherwise need a live+ APScheduler and a service lease.+ """++ from types import SimpleNamespace++ from core.scheduled_tasks import ScheduledTaskService, ScheduledTaskStore++ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ store._sqlite = sqlite+ store.load()++ controller = SimpleNamespace(platform_settings_managers={}, session_turn_gate=None)+ service = ScheduledTaskService(+ controller=controller, store=store, request_store=requests+ )+ service.scheduler = SimpleNamespace(+ get_job=lambda *_a, **_kw: None,+ add_job=lambda *_a, **_kw: None,+ remove_job=lambda *_a, **_kw: None,+ get_jobs=lambda *_a, **_kw: [],+ running=True,+ )+ service._owns_service_instance = lambda: True+ service.validate_platform = lambda platform: None+ return service+++def _fire_command_task(service, definition_id: str) -> dict:+ """Run one real fire of *definition_id* through the claimed-request path."""++ task = service.store.get_task(definition_id)+ assert task is not None and task.has_command, "the premise: a command definition"+ queued = service.request_store.enqueue_task_run(+ definition_id, source_kind="scheduler", task=task+ )+ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))+ run = service.request_store.get_run(queued.id)+ assert run is not None+ return run+++def _capture_notice_emissions(monkeypatch) -> list[dict]:+ """Stub rung (1) delivery and record every notice body it is handed."""++ import core.scheduled_tasks as scheduled_tasks++ emitted: list[dict] = []++ async def _fake_emit(controller, context, backend, diagnostic, **kwargs):+ emitted.append(+ {+ "platform": context.platform,+ "channel_id": context.channel_id,+ "body": kwargs.get("display_text"),+ "failure_id": kwargs.get("failure_id"),+ }+ )+ evidence = kwargs.get("delivery")+ if evidence is not None:+ evidence.delivered_id = "1717.42"+ evidence.persisted_row = {"id": "msg-1"}+ return False++ monkeypatch.setattr(scheduled_tasks, "emit_replayed_backend_failure", _fake_emit)+ return emitted+++def test_a_failed_command_fire_delivers_exactly_one_command_aware_notice(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-001 — closed loop: a real failing command fire, one command-aware notice.++ Everything real except the outbound send: the subprocess actually runs and exits+ nonzero, ``_execute_claimed_request`` settles the row through the executor's own+ path (stamping ``exit_code``/``stderr`` and the owed notice), and+ ``_drain_failure_notices`` walks the ladder to the definition's delivery key. ONE+ notice, because the streak machinery is keyed on the definition and a second pass+ must see the acknowledgement.+ """++ sqlite, requests = _store(tmp_path)+ _command_task(+ sqlite,+ "task-sct-001",+ name="nightly sync",+ shell_command="echo boom >&2; exit 7",+ cwd=str(tmp_path),+ timeout_seconds=30,+ )++ emitted = _capture_notice_emissions(monkeypatch)+ service = _real_translator(_command_fire_service(tmp_path, sqlite, requests), "en")++ run = _fire_command_task(service, "task-sct-001")+ assert run["status"] == "failed", f"the premise: the fire failed: {run['status']!r}"+ assert run["exit_code"] == 7, f"the row must carry the exit code: {run['exit_code']!r}"++ asyncio.run(service._drain_failure_notices())++ assert len(emitted) == 1, f"exactly one notice for one failed fire: {emitted}"+ assert (emitted[0]["platform"], emitted[0]["channel_id"]) == ("slack", "C1")++ body = emitted[0]["body"]+ assert "echo boom >&2; exit 7" in body, f"the delivered notice must name the command: {body}"+ assert _notice_prefix("harness.notice.commandLine") in body, body+ assert "7" in body.split(_notice_prefix("harness.notice.commandExit"))[1].splitlines()[0], (+ f"and the exit code the fire actually produced: {body}"+ )++ emitted.clear()+ asyncio.run(service._drain_failure_notices())+ assert emitted == [], "an acknowledged notice must never be delivered twice"+++def test_a_successful_command_fire_notifies_nowhere(tmp_path: Path, monkeypatch) -> None:+ """SCT-002 — silent success is the contract, not an omission.++ ``--on-failure none`` is cron parity: a command task that succeeds is visible in+ ``vibe task show`` (``last_exit_code``) and ``vibe runs show`` (stdout) and NOWHERE+ else. So the guard is two-sided — nothing is owed, and the drain sends nothing —+ because a success notification would turn every minute-ly command task into a+ notification firehose.+ """++ sqlite, requests = _store(tmp_path)+ _command_task(+ sqlite,+ "task-sct-002",+ name="nightly sync",+ shell_command="echo fine",+ cwd=str(tmp_path),+ )++ emitted = _capture_notice_emissions(monkeypatch)+ service = _real_translator(_command_fire_service(tmp_path, sqlite, requests), "en")++ run = _fire_command_task(service, "task-sct-002")+ assert run["status"] == "succeeded", f"the premise: the fire succeeded: {run['error']!r}"+ assert run["exit_code"] == 0++ assert sqlite.owed_failure_notice(run["id"]) is None, (+ "a succeeded command run must owe no notice"+ )+ assert sqlite.list_owed_failure_notices() == [], (+ "and must not appear in the drain's work list"+ )++ asyncio.run(service._drain_failure_notices())+ assert emitted == [], f"a successful command fire must notify nobody: {emitted}"+++def test_an_escalated_command_failure_is_never_delivered_a_notice(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-003, drain half — the escalation IS the report, so the notice is suppressed.++ A ``--on-failure agent`` fire queues one Agent turn carrying the failure report, in+ the same transaction that stamps its definition. A notice as well would be the same+ failure told twice — once as a turn the Agent acts on, once as an alert the user has+ to. Asserted at the DRAIN, not just at the stamp: nothing must be owed, the row must+ not appear in the drain's work list, and a real drain pass must send nothing.++ The regression half is the second run: the identical failure WITHOUT the marker+ still owes and still delivers, so the suppression cannot silence anything else.+ """++ sqlite, requests = _store(tmp_path)+ _command_task(sqlite, "task-sct-003", name="nightly sync")++ escalated = requests.enqueue_task_run("task-sct-003", source_kind="scheduler")+ claimed = requests.claim(escalated.id)+ assert claimed is not None+ requests.complete(+ claimed,+ ok=False,+ error="command exited with status 7: boom",+ task_id="task-sct-003",+ exit_code=7,+ stderr="boom\n",+ escalation_run_id="esc-sct-003",+ )++ row = sqlite.get_run(escalated.id)+ assert row is not None and row["status"] == "failed"+ assert row["metadata"].get("escalation_run_id") == "esc-sct-003"+ assert sqlite.owed_failure_notice(escalated.id) is None, (+ "an escalated failure owes a notice as well; the report would arrive twice"+ )+ assert [item["id"] for item in sqlite.list_owed_failure_notices()] == [], (+ "and it reached the drain's work list anyway"+ )++ emitted = _capture_notice_emissions(monkeypatch)+ from types import SimpleNamespace++ service = _real_translator(+ _drain_service(tmp_path, SimpleNamespace(), sqlite, requests), "en"+ )+ asyncio.run(service._drain_failure_notices())+ assert emitted == [], f"an escalated failure was delivered a notice: {emitted}"++ plain = requests.enqueue_task_run("task-sct-003", source_kind="scheduler")+ plain_claimed = requests.claim(plain.id)+ assert plain_claimed is not None+ requests.complete(+ plain_claimed,+ ok=False,+ error="command exited with status 7: boom",+ task_id="task-sct-003",+ exit_code=7,+ stderr="boom\n",+ )+ notice = sqlite.owed_failure_notice(plain.id)+ assert notice is not None and notice.get("state"), (+ "the suppression leaked to un-escalated failures; every failed command fire "+ "would go silent"+ )diff --git a/tests/test_harness_skill_guidance.py b/tests/test_harness_skill_guidance.pyindex 781fbcc0f..cd45f8098 100644--- a/tests/test_harness_skill_guidance.py+++ b/tests/test_harness_skill_guidance.py@@ -1,15 +1,38 @@from __future__ import annotations+import re+import shlexfrom pathlib import Path+from vibe import cli+ROOT = Path(__file__).resolve().parents[1]+# A `vibe task/watch` example embedded in prompt copy, stopping at the markdown+# punctuation that ends it (backtick, table pipe, newline).+_EMBEDDED_EXAMPLE = re.compile(r"vibe (?:task|watch) (?:add|update)[^`|\n\\]*")+def _read(path: str) -> str:return (ROOT / path).read_text()+def _embedded_cli_examples(body: str) -> list[str]:+ """Every embedded `vibe task/watch` example that carries at least one flag.++ A bare `vibe task add` in prose names the command rather than demonstrating a+ call, so it is not a live caller and is excluded.+ """++ found = set()+ for match in _EMBEDDED_EXAMPLE.finditer(body):+ example = re.sub(r"\s+\(.*\)$", "", match.group(0)).strip()+ if "--" in example:+ found.add(example)+ return sorted(found)++def test_avibe_skills_teach_current_harness_defaults() -> None:for path in ("skills/use-avibe/SKILL.md", "skills/use-vibe-remote/SKILL.md"):body = _read(path)@@ -20,6 +43,12 @@ def test_avibe_skills_teach_current_harness_defaults() -> None:assert "vibe agent run --agent '<agent-name>' --message '...'" in bodyassert "from an Avibe Agent shell" in bodyassert "vibe task add --cron '<expr>' --message '...'" in body+ # A scheduled command task is not a saved message: no Agent turn fires.+ assert "vibe task add --cron '<expr>' --shell '<command>'" in body+ assert (+ "vibe task add --cron '<expr>' --shell '<command>' "+ "--on-failure agent --message '<what to do>'"+ ) in bodyassert "vibe watch add --message '...' -- <cmd>" in bodyassert "vibe agent run --agent '<agent-name>' --same-scope --message '...'" in bodyassert "Avibe uses the command's current working directory" in body@@ -27,6 +56,37 @@ def test_avibe_skills_teach_current_harness_defaults() -> None:assert "follows the caller or source Session cwd" not in body+def test_injected_harness_prompt_examples_parse_against_the_real_cli() -> None:+ """CLI examples in the injected prompt are live callers, so they must parse.++ The agent reads this prompt and runs what it finds. An example that argparse+ rejects — a renamed flag, a dropped one, a form that never existed — teaches+ the agent a call that fails at runtime. `tests/test_agent_tool_policy.py`+ guards the same rule for the native-scheduler denial strings; this guards the+ Harness prompt itself, which is where scheduled-command guidance lives.+ """++ examples = _embedded_cli_examples(_read("core/system_prompt_injection.py"))+ assert examples, "no embedded vibe task/watch examples found — did the regex drift?"++ parser = cli.build_parser()+ for example in examples:+ argv = shlex.split(example)[1:]+ try:+ parser.parse_args(argv)+ except SystemExit as exc: # argparse rejected a live caller+ raise AssertionError(+ f"injected prompt teaches an unparseable command: {example!r}"+ ) from exc++ # The scheduled-command form specifically: it is the whole point of the+ # command-task guidance, and the easiest example to leave stale.+ assert any(+ "--shell" in example and example.startswith("vibe task add")+ for example in examples+ ), "the injected prompt no longer shows a scheduled command task example"++def test_avibe_skills_do_not_reintroduce_legacy_harness_guidance() -> None:disallowed = ("--deliver-key",diff --git a/tests/test_i18n_backend_keys.py b/tests/test_i18n_backend_keys.pyindex 59c6ceebc..d87189315 100644--- a/tests/test_i18n_backend_keys.py+++ b/tests/test_i18n_backend_keys.py@@ -274,3 +274,27 @@ def test_the_origin_lines_keep_their_placeholders_in_both_languages() -> None:assert key in bundle, f"{key} missing from {lang}"missing = [name for name in placeholders if name not in bundle[key]]assert not missing, f"{lang} {key} dropped {missing}: {bundle[key]!r}"+++def test_the_command_fires_refusal_sentences_resolve_in_every_language() -> None:+ """OBS-HARNESS-COMMAND-TASK-018 — the run's ``error`` column is product copy.++ Both keys are sentences ``core/scheduled_tasks.py`` composes itself, and both land+ in the run ledger's ``error``, which the Harness detail pane, ``vibe runs show`` and+ the failure notice render verbatim — the same column the settlement reasons above+ already fill through ``vibe/i18n``. ``str(exc)`` and a worker's own stderr stay+ untranslated on that channel because nobody here wrote them; our own copy does not+ get that exemption, and an unresolved key would print the dotted path to a user.+ """++ from core.scheduled_tasks import _TASK_RESULT_NOT_RECORDED_I18N_KEY++ for key in (_TASK_RESULT_NOT_RECORDED_I18N_KEY, "harness.command.workerNotRecorded"):+ for lang in get_supported_languages():+ resolved = t(key, lang)+ assert resolved != key, f"{key} is not translated in {lang}"+ assert resolved.strip()+ assert t(key, "zh") != t(key, "en"), (+ f"{key} was added to zh.json as the English string; a Chinese install would "+ "read a mixed-language failure"+ )diff --git a/tests/test_process_isolation.py b/tests/test_process_isolation.pyindex b8ceb3937..9f1854efe 100644--- a/tests/test_process_isolation.py+++ b/tests/test_process_isolation.py@@ -4,10 +4,13 @@ import asyncioimport loggingimport osimport signal+import subprocessimport sys+from contextlib import suppressfrom pathlib import Pathfrom types import SimpleNamespace+import psutilimport pytestfrom core import watch_worker@@ -21,9 +24,12 @@ from core.process_isolation import (inspect_process_identity,isolated_subprocess_kwargs,new_process_identity_marker,+ process_group_exists,process_group_identity_status,process_identity_matches,process_identity_subprocess_env,+ probe_process_liveness,+ reap_orphaned_process_tree,signal_process_tree,terminate_process_group_by_pgid,terminate_process_tree_by_pid,@@ -78,6 +84,175 @@ def test_process_identity_reads_inherited_worker_marker(monkeypatch: pytest.Monkassert identity == _live_identity()+def test_probe_tells_an_empty_pid_apart_from_one_it_cannot_read(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The three answers must stay three, because callers act oppositely on two of them.++ ``inspect_process_identity`` folds "gone" and "could not look" into ``None``,+ which is right for deciding whether to signal and wrong for deciding whether to+ DISCARD the record that names the process: only an empty pid means there is+ nothing left to keep a handle for.+ """++ assert probe_process_liveness(os.getpid()) == "alive"+ assert probe_process_liveness(0) == "gone"+ assert probe_process_liveness(-1) == "gone"++ def _raise(exc: BaseException):+ def _factory(_pid: int):+ raise exc++ return _factory++ monkeypatch.setattr(+ "core.process_isolation.psutil.Process", _raise(psutil.NoSuchProcess(12345))+ )+ assert probe_process_liveness(12345) == "gone"++ monkeypatch.setattr(+ "core.process_isolation.psutil.Process", _raise(ProcessLookupError())+ )+ assert probe_process_liveness(12345) == "gone"++ # A process that is there but unreadable: an exhausted fd table on the way into+ # ``/proc``, or a platform refusing ``create_time``.+ monkeypatch.setattr(+ "core.process_isolation.psutil.Process", _raise(OSError(24, "Too many open files"))+ )+ assert probe_process_liveness(12345) == "unknown"++ monkeypatch.setattr(+ "core.process_isolation.psutil.Process", _raise(psutil.AccessDenied(12345))+ )+ assert probe_process_liveness(12345) == "unknown"+++_LEADER_THAT_LEAVES_A_CHILD = (+ "import os, subprocess, sys, time\n"+ "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(3600)'])\n"+ "sys.stdout.write(f'{child.pid}\\n')\n"+ "sys.stdout.flush()\n"+ "time.sleep(0.5)\n"+ "os._exit(0)\n"+)+++def test_reaping_an_orphan_follows_the_group_its_leader_left_behind() -> None:+ """An empty pid is not an empty tree, so it cannot be where the reap stops.++ A supervisor started with ``start_new_session`` leads the group ``pgid == pid``,+ and on POSIX that group outlives it: kill the supervisor -- an OOM kill, a fault+ in its own code -- and the backup or migration under it keeps running in a group+ nothing else names. A recovery pass that reads the free pid as proof the tree was+ reaped then drops the only record of it, and the survivor runs to completion+ unowned while the next fire starts a second one beside it.+ """++ if os.name == "nt":+ pytest.skip("process groups outliving their leader is POSIX-specific")++ marker = new_process_identity_marker()+ leader = subprocess.Popen( # noqa: S603 - fixed argv, test-owned+ [os.path.abspath(sys.executable), "-c", _LEADER_THAT_LEAVES_A_CHILD],+ stdout=subprocess.PIPE,+ text=True,+ env=process_identity_subprocess_env(marker),+ **isolated_subprocess_kwargs(),+ )+ child_pid: int | None = None+ try:+ identity = capture_spawned_process_identity(leader.pid, marker)+ assert identity is not None+ assert leader.stdout is not None+ child_pid = int(leader.stdout.readline().strip())+ assert leader.wait(timeout=15) == 0, "the leader did not exit on its own"++ # The state under test: leader reaped, its group still occupied by the work.+ assert probe_process_liveness(leader.pid) == "gone"+ assert os.getpgid(child_pid) == leader.pid+ assert process_group_exists(leader.pid, logging.getLogger(__name__), "test group")++ outcome = reap_orphaned_process_tree(+ logging.getLogger(__name__),+ "test orphan",+ expected_identity=identity,+ )++ assert outcome == "reaped", (+ "the surviving child was left running and its identity was about to be "+ f"discarded as spent: {outcome}"+ )+ assert not psutil.pid_exists(child_pid) or _is_reaped(child_pid), (+ "the child outlived a reap that reported success"+ )+ finally:+ if child_pid is not None:+ with suppress(ProcessLookupError, PermissionError):+ os.kill(child_pid, KILL_SIGNAL)+ with suppress(Exception):+ leader.kill()+ with suppress(Exception):+ leader.wait(timeout=5)+ if leader.stdout is not None:+ leader.stdout.close()+++def _is_reaped(pid: int) -> bool:+ """Whether a pid that still exists is only a zombie awaiting its parent."""+ try:+ return psutil.Process(pid).status() == psutil.STATUS_ZOMBIE+ except psutil.Error:+ return True+++def test_reaping_an_orphan_keeps_a_group_it_cannot_identify() -> None:+ """A group it cannot vouch for is neither killed nor forgotten.++ Signalling a pgid whose members carry no recognizable marker is the coin flip on+ an unrelated process group that the identity check exists to refuse -- but+ "refused to signal" is not "nothing there", so the record has to survive for a+ later pass rather than being retired as spent.+ """++ if os.name == "nt":+ pytest.skip("process groups outliving their leader is POSIX-specific")++ logger = logging.getLogger(__name__)+ identity = _persisted_identity(pid=4242)+ signalled: list[int] = []++ def _never_reached(pgid, *_args, **_kwargs) -> bool:+ signalled.append(pgid)+ return True++ with pytest.MonkeyPatch.context() as patched:+ patched.setattr("core.process_isolation.probe_process_liveness", lambda _pid: "gone")+ patched.setattr("core.process_isolation.process_group_exists", lambda *_a, **_k: True)+ patched.setattr(+ "core.process_isolation.process_group_identity_status",+ lambda *_a, **_k: "unknown",+ )+ patched.setattr(+ "core.process_isolation.terminate_process_group_by_pgid", _never_reached+ )++ assert reap_orphaned_process_tree(+ logger, "test orphan", expected_identity=identity+ ) == "unconfirmed"+ assert signalled == [], "an unidentifiable group was signalled anyway"++ # A group whose members all carry SOME OTHER tree's marker is ours no longer.+ patched.setattr(+ "core.process_isolation.process_group_identity_status",+ lambda *_a, **_k: "mismatch",+ )+ assert reap_orphaned_process_tree(+ logger, "test orphan", expected_identity=identity+ ) == "gone"+ assert signalled == [], "a recycled pgid was signalled"++def test_process_identity_survives_exec_transition() -> None:if os.name == "nt":pytest.skip("exec transition is POSIX-specific")diff --git a/tests/test_scheduled_command_task_integration.py b/tests/test_scheduled_command_task_integration.pynew file mode 100644index 000000000..c657d97c3--- /dev/null+++ b/tests/test_scheduled_command_task_integration.py@@ -0,0 +1,307 @@+"""Cross-layer coverage for scheduled command tasks: CLI create -> executor run.++`tests/test_cli_task_command.py` proves the CLI writes the right definition and+`tests/test_scheduled_tasks.py` proves the executor runs one, but both build their+fixtures with hand-written `add_task` payloads. A disagreement between the two+layers — a field type, or `on_failure` living somewhere the executor does not read —+passes both suites and only fails once a real cron task fires. These tests drive the+real `cmd_task_add` and the real claimed-request path so that seam stays covered.++Hermetic: state, definition store, and the fallback spawn cwd all land in `tmp_path`.+"""++import asyncio+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import config.paths as paths+from core.caller_context import (+ AVIBE_CALLER_BACKEND_ENV,+ AVIBE_CALLER_CHANNEL_ID_ENV,+ AVIBE_CALLER_MESSAGE_ID_ENV,+ AVIBE_CALLER_PLATFORM_ENV,+ AVIBE_CALLER_SESSION_KEY_ENV,+ AVIBE_CALLER_SOURCE_ENV,+ AVIBE_CALLER_USER_ID_ENV,+ AVIBE_CALLER_WORKSPACE_ID_ENV,+ AVIBE_NATIVE_SESSION_ID_ENV,+ AVIBE_RUN_ID_ENV,+ AVIBE_SESSION_ID_ENV,+)+from core.scheduled_tasks import (+ ScheduledTaskService,+ ScheduledTaskStore,+ TaskExecutionStore,+)+from vibe import cli++_CALLER_ENV_VARS = (+ AVIBE_SESSION_ID_ENV,+ AVIBE_RUN_ID_ENV,+ AVIBE_CALLER_SOURCE_ENV,+ AVIBE_CALLER_BACKEND_ENV,+ AVIBE_NATIVE_SESSION_ID_ENV,+ AVIBE_CALLER_PLATFORM_ENV,+ AVIBE_CALLER_USER_ID_ENV,+ AVIBE_CALLER_CHANNEL_ID_ENV,+ AVIBE_CALLER_SESSION_KEY_ENV,+ AVIBE_CALLER_MESSAGE_ID_ENV,+ AVIBE_CALLER_WORKSPACE_ID_ENV,+)+++def _isolate(tmp_path: Path, monkeypatch) -> None:+ """Point every write-capable path at ``tmp_path`` and clear caller context.++ The caller vars matter: this suite may itself run inside an Avibe Agent shell,+ where an ambient ``AVIBE_SESSION_ID`` would otherwise reach+ ``_apply_caller_session_default``. A pure command task must be creatable there,+ so leaving them set would test the wrong thing.+ """++ db_path = tmp_path / "state" / "vibe.sqlite"+ monkeypatch.setattr(paths, "get_state_dir", lambda: db_path.parent)+ monkeypatch.setattr(paths, "get_sqlite_state_path", lambda: db_path)+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / "avibe_home")++ from storage.importer import ensure_sqlite_state++ ensure_sqlite_state(db_path=db_path, primary_platform="slack")+ for var in _CALLER_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+++def _store(tmp_path: Path) -> ScheduledTaskStore:+ """The SQLite definition store, i.e. the one production actually uses.++ ``tmp_path`` is unused now that ``_isolate`` has pointed the state dir at it; the+ parameter stays so every call site keeps naming the sandbox it depends on. A+ file-backed store here would leave the definition absent from ``run_definitions``,+ and the request store's transactional enqueue re-reads that row -- so the two+ layers would only agree in the test.+ """++ return ScheduledTaskStore()+++def _service(tmp_path: Path, calls: list) -> ScheduledTaskService:+ """A service on the SQLite request store, mirroring the executor suite's fixture."""++ async def _handle_scheduled_message(context, message, parsed_session_key=None):+ calls.append(message)+ return None++ settings_manager = SimpleNamespace(+ get_store=lambda: SimpleNamespace(get_user=lambda *_a, **_kw: None)+ )+ controller = SimpleNamespace(+ platform_settings_managers={"slack": settings_manager},+ message_handler=SimpleNamespace(+ handle_scheduled_message=_handle_scheduled_message+ ),+ )+ service = ScheduledTaskService(+ controller=controller,+ store=_store(tmp_path),+ request_store=TaskExecutionStore(),+ )+ service.scheduler = SimpleNamespace(+ get_job=lambda *_a, **_kw: None,+ add_job=lambda *_a, **_kw: None,+ remove_job=lambda *_a, **_kw: None,+ get_jobs=lambda *_a, **_kw: [],+ running=True,+ )+ return service+++def _add_via_cli(tmp_path: Path, argv: list[str]) -> None:+ args = cli.build_parser().parse_args(["task", "add", *argv])+ with patch("vibe.cli._task_store", return_value=_store(tmp_path)):+ assert cli.cmd_task_add(args) == 0, "the CLI refused to create the command task"+++def _fire(service: ScheduledTaskService, task) -> dict:+ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))+ run = service.request_store.get_run(queued.id)+ assert run is not None+ return run+++def test_cli_created_command_task_runs_with_no_agent_turn(+ tmp_path: Path, monkeypatch, capsys+) -> None:+ """The headline promise: a cron task that executes and never involves an Agent."""++ _isolate(tmp_path, monkeypatch)+ marker = tmp_path / "ran.txt"+ _add_via_cli(+ tmp_path,+ [+ "--name",+ "nightly-sync",+ "--cron",+ "0 3 * * *",+ "--shell",+ f"echo fired > {marker}; exit 0",+ "--cwd",+ str(tmp_path),+ ],+ )+ capsys.readouterr()++ task = _store(tmp_path).list_tasks()[0]+ assert task.has_command, "the CLI-written definition is not seen as a command task"+ assert task.on_failure == "none", f"on_failure did not survive: {task.on_failure!r}"+ assert not task.session_id and not task.session_key, (+ "a pure command task was given an Agent session; it must have none"+ )++ calls: list = []+ run = _fire(_service(tmp_path, calls), task)++ assert run["status"] == "succeeded", f"the run failed: {run['error']!r}"+ assert run["exit_code"] == 0, f"the run row lost the exit code: {run['exit_code']!r}"+ assert marker.read_text().strip() == "fired", "the command never actually ran"+ assert calls == [], f"a pure command task dispatched an Agent turn: {calls!r}"+ assert _store(tmp_path).get_task(task.id).last_exit_code == 0+++def test_cli_created_command_task_records_a_nonzero_exit(+ tmp_path: Path, monkeypatch, capsys+) -> None:+ """A failing command must surface on the run row AND the definition."""++ _isolate(tmp_path, monkeypatch)+ _add_via_cli(+ tmp_path,+ [+ "--cron",+ "0 3 * * *",+ "--shell",+ "echo boom >&2; exit 7",+ "--cwd",+ str(tmp_path),+ "--timeout",+ "30",+ ],+ )+ capsys.readouterr()++ task = _store(tmp_path).list_tasks()[0]+ assert task.timeout_seconds == 30, (+ f"--timeout did not reach the definition: {task.timeout_seconds!r}"+ )++ calls: list = []+ run = _fire(_service(tmp_path, calls), task)++ assert run["status"] == "failed", f"a nonzero exit did not fail the run: {run['status']!r}"+ assert run["exit_code"] == 7, f"the run row lost the exit code: {run['exit_code']!r}"+ assert "boom" in (run["stderr"] or ""), f"stderr was not persisted: {run['stderr']!r}"+ assert calls == [], "a failing pure command task must still not dispatch an Agent turn"+ assert _store(tmp_path).get_task(task.id).last_exit_code == 7+ # SCT-019: the run records WHAT it ran. The definition is editable and deletable,+ # so a reader that goes back to it can be told about a command that never ran.+ assert run["metadata"]["command"] == {"shell": "echo boom >&2; exit 7", "argv": []}, (+ f"the run row carries no command snapshot: {run['metadata']!r}"+ )+++def test_a_fire_with_no_exit_code_clears_the_one_the_last_fire_left(+ tmp_path: Path, monkeypatch, capsys+) -> None:+ """SCT-017 -- ``last_exit_code`` must describe THIS fire or nothing.++ Some fires never reach a process: a working directory that no longer exists, a+ supervisor that dies during startup. They have no exit code at all, and the notice+ is careful never to invent one. The definition row was not: the stamp only wrote+ ``last_exit_code`` when it had a value, so the code from the LAST fire stayed on+ the row and the Harness pane and ``vibe task list`` showed "exited 7" beside a+ failure that never ran a command -- a fabricated fact, and a misleading one,+ because 7 was a real status the same definition really produced once.++ A message task is the reason the write is not unconditional: it has no exit code+ to report and must not blank a command fire's. So the command fire's own stamp is+ the one authorised to clear it.+ """++ _isolate(tmp_path, monkeypatch)+ workdir = tmp_path / "workdir"+ workdir.mkdir()+ _add_via_cli(+ tmp_path,+ [+ "--cron",+ "0 3 * * *",+ "--shell",+ "exit 7",+ "--cwd",+ str(workdir),+ "--timeout",+ "30",+ ],+ )+ capsys.readouterr()++ task = _store(tmp_path).list_tasks()[0]+ first = _fire(_service(tmp_path, []), task)+ assert first["exit_code"] == 7+ assert _store(tmp_path).get_task(task.id).last_exit_code == 7++ # The directory disappears between fires: the next fire cannot spawn, so it has no+ # status of its own to report.+ workdir.rmdir()+ second = _fire(_service(tmp_path, []), task)++ assert second["status"] == "failed"+ assert "Working directory does not exist" in (second["error"] or "")+ assert second["exit_code"] is None, (+ f"a fire that never spawned must not carry an exit code: {second['exit_code']!r}"+ )+ stored = _store(tmp_path).get_task(task.id)+ assert stored.last_exit_code is None, (+ "the definition kept the previous fire's exit code beside a failure that "+ f"never ran a command: {stored.last_exit_code!r}"+ )+ assert stored.last_error and "Working directory does not exist" in stored.last_error+++def test_cli_created_argv_command_task_runs(+ tmp_path: Path, monkeypatch, capsys+) -> None:+ """The ``-- argv`` form must survive the CLI pre-parse and execute as a list."""++ _isolate(tmp_path, monkeypatch)+ marker = tmp_path / "argv.txt"+ _add_via_cli(+ tmp_path,+ [+ "--cron",+ "0 3 * * *",+ "--cwd",+ str(tmp_path),+ "--",+ "/bin/sh",+ "-c",+ f"echo argv > {marker}",+ ],+ )+ capsys.readouterr()++ task = _store(tmp_path).list_tasks()[0]+ assert task.command == ["/bin/sh", "-c", f"echo argv > {marker}"], (+ f"the argv list did not round-trip: {task.command!r}"+ )+ assert not task.shell_command, "an argv task must not also store a shell command"++ run = _fire(_service(tmp_path, []), task)++ assert run["status"] == "succeeded", f"the argv run failed: {run['error']!r}"+ assert marker.read_text().strip() == "argv"diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.pyindex 664c1e953..25af3fd51 100644--- a/tests/test_scheduled_tasks.py+++ b/tests/test_scheduled_tasks.py@@ -3,8 +3,11 @@ from __future__ import annotationsimport asyncioimport astimport json+import osimport sqlite3+import subprocessimport sys+import timefrom contextlib import suppressfrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -18,12 +21,21 @@ from sqlalchemy import select, updatesys.path.insert(0, str(Path(__file__).resolve().parents[1]))import core.scheduled_tasks as scheduled_tasks+from core import command_runnerfrom config import pathsfrom config.v2_settings import make_thread_native_idfrom core.controller import Controllerfrom core.message_dispatcher import ConsolidatedMessageDispatcherfrom core.message_mirror import mirror_harness_inboundfrom core.message_output import MessageOutput, stop_output_for+import core.process_isolation as process_isolation+from core.process_isolation import (+ capture_spawned_process_identity,+ fingerprint_process_marker,+ isolated_subprocess_kwargs,+ process_identity_subprocess_env,+ serialize_process_identity,+)from core.run_settlement import (RUN_INTERRUPTION_REASONS,SETTLED_BY_BACKEND_REFRESH,@@ -45,13 +57,14 @@ from core.scheduled_tasks import (BINDING_FOLLOWS_SESSION_METADATA_KEY,BINDING_RECOVERY_METADATA_KEY,ParsedSessionKey,+ ScheduledTask,ScheduledTaskService,ScheduledTaskStore,SessionBindingChange,TaskDispatchResult,TaskExecutionRequest,TaskExecutionStore,- _TASK_RESULT_NOT_RECORDED_ERROR,+ _TASK_RESULT_NOT_RECORDED_I18N_KEY,_agent_run_message_for_request,build_session_key_for_context,normalize_agent_run_delivery_intent,@@ -59,10 +72,17 @@ from core.scheduled_tasks import (resolve_session_id_target,session_anchor_for_target,)+from core.watch_worker import WATCH_WORKER_ERROR_PREFIX+from vibe.i18n import t as i18n_tfrom modules.im import MessageContextfrom storage import message_deliveriesfrom storage.db import create_sqlite_engine-from storage.background import SQLiteBackgroundTaskStore+from storage.background import (+ COMMAND_SNAPSHOT_METADATA_KEY,+ COMMAND_TIMED_OUT_METADATA_KEY,+ SQLiteBackgroundTaskStore,+ definition_lifecycle_detail,+)from storage.models import (agent_events,agent_runs,@@ -627,6 +647,219 @@ def test_update_task_preserves_id_and_overwrites_selected_fields(tmp_path: Path)assert updated.timezone == "UTC"+def _sqlite_backed_task_store(tmp_path: Path) -> tuple[ScheduledTaskStore, SQLiteBackgroundTaskStore]:+ """A scheduled-task store on its own SQLite file under ``tmp_path``."""++ sqlite = SQLiteBackgroundTaskStore(tmp_path / "state" / "vibe.sqlite")+ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ store._sqlite = sqlite+ return store, sqlite+++def _reloaded_task_store(tmp_path: Path, sqlite: SQLiteBackgroundTaskStore) -> ScheduledTaskStore:+ reloaded = ScheduledTaskStore(tmp_path / "scheduled_tasks-reloaded.json")+ reloaded._sqlite = sqlite+ reloaded.load()+ return reloaded+++def _definition_row(sqlite: SQLiteBackgroundTaskStore, definition_id: str) -> dict[str, Any]:+ with sqlite.engine.connect() as conn:+ row = (+ conn.execute(select(run_definitions).where(run_definitions.c.id == definition_id))+ .mappings()+ .first()+ )+ assert row is not None+ return dict(row)+++def test_store_round_trip_persists_shell_command_task(tmp_path: Path) -> None:+ store, sqlite = _sqlite_backed_task_store(tmp_path)+ task = store.add_task(+ name="Nightly sync",+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 3 * * *",+ timezone_name="UTC",+ shell_command="./sync.sh; exit 0",+ timeout_seconds=300.0,+ metadata={"on_failure": "agent"},+ )++ saved = _reloaded_task_store(tmp_path, sqlite).get_task(task.id)++ assert saved is not None+ assert saved.shell_command == "./sync.sh; exit 0"+ assert saved.command is None+ assert saved.timeout_seconds == 300.0+ assert saved.last_exit_code is None+ assert saved.has_command is True+ assert saved.on_failure == "agent"+ # A command task needs no session, and the inference must not invent one.+ assert saved.session_policy is None+++def test_store_round_trip_persists_argv_command_task(tmp_path: Path) -> None:+ store, sqlite = _sqlite_backed_task_store(tmp_path)+ task = store.add_task(+ name="Echo",+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="*/5 * * * *",+ timezone_name="UTC",+ command=["/bin/echo", "hi"],+ )++ saved = _reloaded_task_store(tmp_path, sqlite).get_task(task.id)++ assert saved is not None+ assert saved.command == ["/bin/echo", "hi"]+ assert saved.shell_command is None+ assert saved.timeout_seconds is None+ assert saved.has_command is True+ assert saved.on_failure == "none"+++def test_message_task_keeps_command_columns_null(tmp_path: Path) -> None:+ store, sqlite = _sqlite_backed_task_store(tmp_path)+ task = store.add_task(+ session_key="slack::channel::C123",+ prompt="send digest",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ )++ row = _definition_row(sqlite, task.id)+ saved = _reloaded_task_store(tmp_path, sqlite).get_task(task.id)++ assert row["command_json"] is None+ assert row["shell_command"] is None+ assert row["timeout_seconds"] is None+ assert row["last_exit_code"] is None+ assert saved is not None+ assert saved.shell_command is None+ assert saved.command is None+ assert saved.timeout_seconds is None+ assert saved.last_exit_code is None+ assert saved.has_command is False+++def test_from_dict_defaults_command_fields_for_legacy_payloads() -> None:+ task = ScheduledTask.from_dict(+ {+ "id": "task-legacy",+ "session_key": "slack::channel::C123",+ "prompt": "send digest",+ "schedule_type": "cron",+ "cron": "0 * * * *",+ }+ )++ assert task.shell_command is None+ assert task.command is None+ assert task.timeout_seconds is None+ assert task.last_exit_code is None+ assert task.has_command is False+ assert task.on_failure == "none"+ assert task.to_dict()["shell_command"] is None+++def test_update_task_only_rewrites_command_fields_when_gated(tmp_path: Path) -> None:+ store, sqlite = _sqlite_backed_task_store(tmp_path)+ task = store.add_task(+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 3 * * *",+ timezone_name="UTC",+ shell_command="./sync.sh",+ timeout_seconds=120.0,+ )++ preserved = store.update_task(+ task.id,+ name="Renamed",+ session_key="",+ prompt="",+ schedule_type="cron",+ post_to=None,+ deliver_key=None,+ cron="0 4 * * *",+ run_at=None,+ timezone_name="UTC",+ )++ assert preserved.shell_command == "./sync.sh"+ assert preserved.timeout_seconds == 120.0+ assert _reloaded_task_store(tmp_path, sqlite).get_task(task.id).shell_command == "./sync.sh"++ replaced = store.update_task(+ task.id,+ name="Renamed",+ session_key="",+ prompt="",+ schedule_type="cron",+ post_to=None,+ deliver_key=None,+ cron="0 4 * * *",+ run_at=None,+ timezone_name="UTC",+ command=["/bin/echo", "hi"],+ timeout_seconds=45.0,+ update_command_fields=True,+ )++ reloaded = _reloaded_task_store(tmp_path, sqlite).get_task(task.id)+ assert replaced.shell_command is None+ assert replaced.command == ["/bin/echo", "hi"]+ assert reloaded.command == ["/bin/echo", "hi"]+ assert reloaded.shell_command is None+ assert reloaded.timeout_seconds == 45.0+++def test_last_exit_code_survives_an_unrelated_definition_write(tmp_path: Path) -> None:+ """A definition edit must not wipe the exit code a command run recorded.++ Every scheduled-task write is a FULL-ROW upsert, so a hardcoded ``None`` in the+ column mapping would clear the exit code on the next rename or ``mark_task_result``.+ """++ store, sqlite = _sqlite_backed_task_store(tmp_path)+ task = store.add_task(+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 3 * * *",+ timezone_name="UTC",+ shell_command="./sync.sh",+ )+ sqlite.upsert_scheduled_task({**task.to_dict(), "last_exit_code": 3})+ store.load()++ assert store.get_task(task.id).last_exit_code == 3++ store.update_task(+ task.id,+ name="Renamed",+ session_key="",+ prompt="",+ schedule_type="cron",+ post_to=None,+ deliver_key=None,+ cron="0 4 * * *",+ run_at=None,+ timezone_name="UTC",+ )+ assert store.mark_task_result(task.id, error=None) is True++ assert _definition_row(sqlite, task.id)["last_exit_code"] == 3+ assert _reloaded_task_store(tmp_path, sqlite).get_task(task.id).last_exit_code == 3++def test_store_reload_detects_deleted_task_file(tmp_path: Path) -> None:store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")store.add_task(@@ -11154,9 +11387,7 @@ def test_a_refused_result_stamp_cannot_complete_the_run_ok(tmp_path: Path, monke"the run ledger recorded a success for a fire whose terminal stamp the "f"database refused (status={run['status']!r}); the stored task never moved")- from core.scheduled_tasks import _TASK_RESULT_NOT_RECORDED_ERROR-- assert run["error"] == _TASK_RESULT_NOT_RECORDED_ERROR, (+ assert run["error"] == i18n_t(_TASK_RESULT_NOT_RECORDED_I18N_KEY, "en"), (f"the refusal reached the ledger without saying why: {run['error']!r}")@@ -11214,7 +11445,7 @@ def test_refused_task_stamp_fails_durable_run_and_reconciles_its_delivery(run = service.request_store.get_run(queued.id)assert run is not Noneassert run["status"] == "failed"- assert run["error"] == _TASK_RESULT_NOT_RECORDED_ERROR+ assert run["error"] == i18n_t(_TASK_RESULT_NOT_RECORDED_I18N_KEY, "en")assert reconciled == [(queued.id, session_id)]@@ -12806,3 +13037,3423 @@ def test_a_dropped_task_mirror_recovers_with_no_unrelated_commit_to_wake_it() ->"the durable row changed, so the failed write committed something and the ""recovery above was reading a different definition than the one that was dropped")+++# --- Command tasks: a definition that runs a subprocess instead of an Agent turn ---+++def _command_task_env(tmp_path: Path, monkeypatch) -> Path:+ """``_binding_env`` plus a test-owned fallback spawn cwd.++ A command definition with no ``cwd`` spawns in ``paths.get_vibe_remote_dir()``,+ which is the REAL ``~/.avibe`` in an unpatched process. Redirected here so no+ command test can spawn a child inside the user's live product state.+ """++ db_path = _binding_env(tmp_path, monkeypatch)+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / "avibe_home")+ return db_path+++def _fire_command_task(+ service: ScheduledTaskService, task: ScheduledTask+) -> dict[str, Any]:+ """Fire one definition through the REAL claimed-request path; return its run row."""++ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))+ run = service.request_store.get_run(queued.id)+ assert run is not None+ return run+++def _add_command_task(+ store: ScheduledTaskStore,+ *,+ shell_command: str,+ cwd: Optional[str],+ schedule_type: str = "cron",+ timeout_seconds: Optional[float] = None,+ metadata: Optional[dict[str, Any]] = None,+) -> ScheduledTask:+ return store.add_task(+ session_key="",+ prompt="",+ schedule_type=schedule_type,+ cron="0 * * * *" if schedule_type == "cron" else None,+ run_at="2026-07-28T09:00:00+00:00" if schedule_type == "at" else None,+ timezone_name="UTC",+ cwd=cwd,+ shell_command=shell_command,+ timeout_seconds=timeout_seconds,+ metadata=dict(metadata or {"origin": "cli"}),+ )+++def test_command_task_fire_records_a_successful_run_and_exit_code(+ tmp_path: Path, monkeypatch+) -> None:+ """A zero-exit command run is a SUCCEEDED run with its output on the row.++ The whole point of a command task: the outcome the user reads is the exit code+ and the captured output, not an Agent reply. Driven through the real+ claimed-request path so the assertions are on ``agent_runs`` -- what+ ``vibe task runs`` and the Harness detail pane actually show.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="echo hi; exit 0", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "succeeded", f"a zero-exit command run failed: {run['error']!r}"+ assert run["error"] in (None, "")+ assert run["exit_code"] == 0, f"the run row lost the exit code: {run['exit_code']!r}"+ assert "hi" in (run["stdout"] or ""), f"stdout was not persisted: {run['stdout']!r}"+ assert run["run_type"] == "scheduled", (+ f"a command fire changed the run type to {run['run_type']!r}; the CLI and Harness "+ "filter scheduled fires on it"+ )++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code == 0, (+ f"the definition did not record the exit code: {stored.last_exit_code!r}"+ )+ assert stored.last_error is None+ assert stored.last_run_at is not None+++def test_command_task_failure_records_the_exit_code_and_stderr(+ tmp_path: Path, monkeypatch+) -> None:+ """A nonzero exit fails the run and keeps the cause where a reader can find it."""++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(+ store, shell_command="echo boom >&2; exit 7", cwd=str(tmp_path)+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", "a command that exited 7 was recorded as a success"+ assert "status 7" in (run["error"] or ""), (+ f"the run error does not name the exit status: {run['error']!r}"+ )+ assert "boom" in (run["error"] or ""), (+ "the last stderr line -- the only hint the list view shows -- was dropped from "+ f"the error text: {run['error']!r}"+ )+ assert "boom" in (run["stderr"] or ""), f"stderr was not persisted: {run['stderr']!r}"+ assert run["exit_code"] == 7++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code == 7+ assert "status 7" in (stored.last_error or "")+++def test_command_failure_text_is_written_in_the_configured_language(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-022 -- the outcome a command fire generates is user-visible copy.++ ``last_error`` is rendered verbatim inside the failure notice, ``vibe task list``+ and the Workbench, all of which are otherwise translated. Generating it in English+ put an English sentence in the middle of a Chinese notice.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ service.controller.config = SimpleNamespace(language="zh")++ exited = _fire_command_task(+ service,+ _add_command_task(store, shell_command="echo boom >&2; exit 7", cwd=str(tmp_path)),+ )+ assert "命令退出" in (exited["error"] or ""), (+ f"a Chinese install got an English command outcome: {exited['error']!r}"+ )+ assert "boom" in (exited["error"] or ""), "the stderr detail was lost in translation"++ missing = tmp_path / "gone"+ no_spawn = _fire_command_task(+ service, _add_command_task(store, shell_command="true", cwd=str(missing))+ )+ assert "工作目录不存在" in (no_spawn["error"] or ""), (+ f"the no-spawn outcome stayed English: {no_spawn['error']!r}"+ )+ assert str(missing) in (no_spawn["error"] or ""), "the translation dropped the path"+++def test_command_task_timeout_fails_the_run_with_the_timeout_exit_code(+ tmp_path: Path, monkeypatch+) -> None:+ """A command that outlives its timeout is killed and reported as a timeout.++ ``124`` is the runner's timeout code, and it must reach both the run row and the+ definition: a wedged command that merely stopped being awaited would leave the+ run ``running`` forever with nothing naming the cause.++ SCT-024 rides along on the same fire, because both halves are about the sentence+ the user reads. ``--timeout`` is a FLOAT, so the limit is stated as the user wrote+ it: ``int()`` was not rounding a sub-second limit, it was deleting it, and "timed+ out after 0 second(s)" describes an impossible event while hiding the setting that+ has to change. And the definition records that the SCHEDULER is why the command+ stopped, which nothing else can say -- ``timeout 5 ...`` inside a ``--shell``+ script exits 124 all by itself.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(+ store, shell_command="sleep 30", cwd=str(tmp_path), timeout_seconds=0.5+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed"+ assert run["exit_code"] == 124, (+ f"the timeout exit code did not reach the run row: {run['exit_code']!r}"+ )+ assert "timed out" in (run["error"] or ""), (+ f"the error text does not say the command timed out: {run['error']!r}"+ )+ assert "0.5 second" in (run["error"] or ""), (+ "the fractional limit was truncated away, so the text names a limit that was "+ f"never configured: {run['error']!r}"+ )++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code == 124+ assert (stored.metadata or {}).get(COMMAND_TIMED_OUT_METADATA_KEY) is True, (+ "the definition did not record that the scheduler is what stopped this fire, "+ f"so 124 is all the row has to go on: {stored.metadata!r}"+ )++ # And a real 124 from the command itself POSITIVELY clears the claim, rather than+ # merely failing to make it: the same definition, the next fire.+ _edit_definition_command(task.id, "exit 124")+ reread = ScheduledTaskStore().get_task(task.id)+ assert reread is not None+ _fire_command_task(service, reread)++ settled = ScheduledTaskStore().get_task(task.id)+ assert settled is not None and settled.last_exit_code == 124+ assert (settled.metadata or {}).get(COMMAND_TIMED_OUT_METADATA_KEY) is False, (+ "a command that chose its own 124 still reads as a scheduler timeout: "+ f"{settled.metadata!r}"+ )+ assert (+ definition_lifecycle_detail(+ lifecycle_state="finished",+ definition_type="scheduled",+ last_run_at=settled.last_run_at,+ last_exit_code=settled.last_exit_code,+ last_error=settled.last_error,+ timed_out=(settled.metadata or {}).get(COMMAND_TIMED_OUT_METADATA_KEY),+ )+ == "error"+ ), "the UI would tell the user to raise a limit that was never reached"+++def test_command_task_with_a_missing_cwd_fails_without_spawning(+ tmp_path: Path, monkeypatch+) -> None:+ """A configured working directory that is gone must be named, not guessed at.++ Spawning anyway raises a bare ``NotADirectoryError`` from deep inside asyncio+ whose text never mentions the directory the user configured -- and there is no+ exit code to report, because nothing ran.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ missing = tmp_path / "gone"+ task = _add_command_task(store, shell_command="echo hi", cwd=str(missing))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ spawned: list[dict[str, Any]] = []++ async def _never(**kwargs):+ spawned.append(kwargs)+ raise AssertionError("a command was spawned into a directory that does not exist")++ monkeypatch.setattr(scheduled_tasks, "run_supervised_command", _never)++ run = _fire_command_task(service, task)++ assert spawned == []+ assert run["status"] == "failed"+ assert str(missing) in (run["error"] or ""), (+ f"the error does not name the missing directory: {run['error']!r}"+ )+ assert run["exit_code"] is None, (+ f"a run that never spawned reported an exit code: {run['exit_code']!r}"+ )++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code is None+ assert str(missing) in (stored.last_error or "")+++def test_command_task_reports_a_supervisor_startup_failure_verbatim(+ tmp_path: Path, monkeypatch+) -> None:+ """``SupervisedCommandStartupError`` must be caught BEFORE the broad handler.++ It subclasses ``RuntimeError``, so a single ``except Exception`` would swallow it+ and report the worker's own startup detail as an ordinary command error --+ losing ``exc.detail``, the only text that says what the worker rejected.+ """++ from core.command_runner import SupervisedCommandStartupError++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="echo hi", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ async def _startup_failure(**_kwargs):+ raise SupervisedCommandStartupError("bad spec")++ monkeypatch.setattr(scheduled_tasks, "run_supervised_command", _startup_failure)++ run = _fire_command_task(service, task)++ assert run["status"] == "failed"+ assert run["error"] == "bad spec", (+ f"the supervisor's own startup detail was rewritten: {run['error']!r}"+ )+ assert run["exit_code"] is None++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_error == "bad spec"+++def test_a_command_whose_executable_is_missing_reads_as_a_sentence(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-025 -- the worker's machine-readable error line is not user-facing text.++ ``SupervisedCommandStartupError`` is raised ONLY when the stdin handshake breaks,+ so the ordinary failure -- an ``argv`` whose executable does not exist -- takes the+ other route entirely: the worker accepts the spec, fails to spawn, and exits 1+ with ``AVIBE_WATCH_WORKER_ERROR:{...}`` on stderr. The watch lane decodes that; the+ scheduled lane did not, so the raw JSON became the definition's ``last_error``, the+ text of the failure notice, and the body of the Agent escalation prompt.++ Driven through the REAL worker, because the wire format is the thing under test:+ a hand-written stderr string would keep passing if the encoder changed.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ cwd=str(tmp_path),+ command=[str(tmp_path / "no-such-executable"), "--now"],+ metadata={"origin": "cli"},+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the spawn failed ({run['error']!r})"+ for field, value in (+ ("error", run["error"]),+ ("stderr", run["stderr"]),+ ):+ assert WATCH_WORKER_ERROR_PREFIX not in (value or ""), (+ f"the run's {field} is raw worker protocol JSON, not a sentence: {value!r}"+ )+ assert "supervisor failed" in (run["error"] or "").lower(), (+ f"the decoded text does not say what went wrong: {run['error']!r}"+ )+ assert "no-such-executable" in (run["error"] or ""), (+ f"the decoded text dropped the detail naming the cause: {run['error']!r}"+ )++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert WATCH_WORKER_ERROR_PREFIX not in (stored.last_error or ""), (+ f"the definition stored the raw protocol line: {stored.last_error!r}"+ )+++def test_a_supervisor_failure_records_no_command_exit_code(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-039 -- the supervisor's exit status is not the command's.++ SCT-025 decoded the worker's error LINE and left its exit STATUS misattributed.+ ``core/watch_worker.py``'s ``main()`` returns 1 for both of its own failures, so a+ spawn the worker could not perform arrived as ``exit_code == 1`` and was published as+ a fact about the user's command: ``Exit code: 1`` in the failure notice and the+ escalation prompt, ``last_exit_code = 1`` on the definition, an ``exit_code`` in the+ run row ``vibe runs show`` prints -- for a command that never ran, and next to+ "Command exited with status 1" contradicting the supervisor sentence beside it.++ The negative half is the point of the discriminator: a command that DID run and+ exited 1 must keep saying so, or this fix would blind every failing cron job.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ cwd=str(tmp_path),+ command=[str(tmp_path / "no-such-executable"), "--now"],+ metadata={"origin": "cli"},+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the spawn failed ({run['error']!r})"+ assert run["exit_code"] is None, (+ "the run row published the SUPERVISOR's status as the command's exit code "+ f"({run['exit_code']!r}); the command never started"+ )+ assert "supervisor failed" in (run["error"] or "").lower(), (+ f"the failure stopped naming the supervisor: {run['error']!r}"+ )+ assert "exited with status" not in (run["error"] or "").lower(), (+ "one message claims the command exited AND that the supervisor failed: "+ f"{run['error']!r}"+ )++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code is None, (+ "the definition's lifecycle claims a command exited: "+ f"last_exit_code={stored.last_exit_code!r}"+ )++ # The negative half, through the same real worker: a command that ran and failed.+ ran = _add_command_task(+ store, shell_command="exit 3", cwd=str(tmp_path), timeout_seconds=30.0+ )+ ran_run = _fire_command_task(service, ran)+ assert ran_run["status"] == "failed"+ assert ran_run["exit_code"] == 3, (+ "a real command's exit status was blanked along with the supervisor's: "+ f"{ran_run['exit_code']!r}"+ )+ assert "3" in (ran_run["error"] or ""), (+ f"the failure no longer reports the status the command exited with: {ran_run['error']!r}"+ )+++def test_command_run_is_not_gated_on_im_transport_readiness(+ tmp_path: Path, monkeypatch+) -> None:+ """A command run needs no IM transport, so a down adapter must not hold it queued.++ The regression guard is the second half: the SAME setup on a MESSAGE definition+ must still be gated, because that fire really does owe a reply to a platform.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ metadata = {"origin": "cli", "session_scope_id": "slack::channel::C123"}+ command_task = _add_command_task(+ store, shell_command="echo hi", cwd=str(tmp_path), metadata=metadata+ )+ message_task = store.add_task(+ session_key="",+ prompt="send digest",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ metadata=dict(metadata),+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ service.controller.is_im_transport_ready = lambda _platform: False++ command_request = TaskExecutionRequest(+ id="run-command",+ request_type="scheduled",+ task_id=command_task.id,+ metadata=dict(metadata),+ )+ message_request = TaskExecutionRequest(+ id="run-message",+ request_type="scheduled",+ task_id=message_task.id,+ metadata=dict(metadata),+ )++ assert service._transport_ready_for_request(command_request) is True, (+ "a command run was held queued behind an IM adapter it never needs"+ )+ assert service._transport_ready_for_request(message_request) is False, (+ "the short-circuit leaked to message tasks; a reply-owing fire must stay gated "+ "until its platform can deliver"+ )+++def test_one_shot_command_task_is_disabled_after_it_fires(+ tmp_path: Path, monkeypatch+) -> None:+ """An ``at`` command definition must not be able to fire twice."""++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(+ store, shell_command="echo hi", cwd=str(tmp_path), schedule_type="at"+ )+ assert task.enabled is True+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "succeeded"+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.enabled is False, "a one-shot command definition stayed enabled"+++def test_command_task_never_dispatches_an_agent_turn(tmp_path: Path, monkeypatch) -> None:+ """A command definition must run its subprocess INSTEAD of prompting an Agent.++ Not a stylistic check: dispatching as well would post an unasked-for reply into+ the bound conversation and bill an Agent turn for every scheduled backup.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="echo hi", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ dispatched: list[dict[str, Any]] = []++ async def _spy(**kwargs):+ dispatched.append(kwargs)+ return TaskDispatchResult(error=None)++ service._execute_request = _spy # type: ignore[method-assign]++ run = _fire_command_task(service, task)++ assert run["status"] == "succeeded"+ assert dispatched == [], (+ f"a command task also dispatched an Agent turn: {dispatched!r}"+ )+++def test_mark_task_result_stamps_an_exit_code_only_when_one_is_given(+ tmp_path: Path, monkeypatch+) -> None:+ """``exit_code=None`` means "this fire had none", never "clear the stored one".++ A message fire of a definition that also stores a command must not blank the last+ exit code a command fire recorded.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="echo hi", cwd=str(tmp_path))++ assert store.mark_task_result(task.id, error="boom", exit_code=7) is True+ assert ScheduledTaskStore().get_task(task.id).last_exit_code == 7++ assert store.mark_task_result(task.id, error=None) is True+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code == 7, (+ f"a result with no exit code cleared the stored one: {stored.last_exit_code!r}"+ )+ assert stored.last_error is None++ assert store.mark_task_result(task.id, error=None, exit_code=0) is True+ assert ScheduledTaskStore().get_task(task.id).last_exit_code == 0+++def test_canceling_a_command_fire_propagates_and_stamps_nothing(+ tmp_path: Path, monkeypatch+) -> None:+ """Cancellation must escape the command path un-swallowed.++ ``_execute_claimed_request``'s own ``except asyncio.CancelledError`` is what+ settles the run row as an interruption, so absorbing the cancellation here would+ record a service stop as an ordinary failed command AND leave a stale+ ``last_error`` on the definition for a fire whose outcome is unknown.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(+ store, shell_command="sleep 30", cwd=str(tmp_path), timeout_seconds=0.0+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ stamped: list[dict[str, Any]] = []+ monkeypatch.setattr(+ store,+ "mark_task_result",+ lambda *args, **kwargs: stamped.append(kwargs) or True,+ )++ real_runner = scheduled_tasks.run_supervised_command+ entered = asyncio.Event()++ async def _tracking_runner(**kwargs):+ entered.set()+ return await real_runner(**kwargs)++ monkeypatch.setattr(scheduled_tasks, "run_supervised_command", _tracking_runner)++ # A real claimed run, because the execution id is not decoration: the fire records+ # its worker onto that ``running`` row before it will run the user's command+ # (SCT-037), and a fabricated id would be refused at the spawn -- leaving this test+ # cancelling a fire that had already failed.+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None++ async def _exercise() -> None:+ fire = asyncio.ensure_future(+ service._execute_command_task(+ task, execution_id=request.id, disable_one_shot=False+ )+ )+ # Cancel only once the child is genuinely being awaited: a cancel that landed+ # before the spawn would prove nothing about the running path.+ await asyncio.wait_for(entered.wait(), timeout=3)+ await asyncio.sleep(0.2)+ fire.cancel()+ with pytest.raises(asyncio.CancelledError):+ await fire++ asyncio.run(_exercise())++ assert entered.is_set(), "the command never started, so nothing was cancelled"+ assert stamped == [], (+ f"a cancelled command fire stamped a terminal result anyway: {stamped!r}"+ )+++# --- ``--on-failure agent``: the escalation turn a failed command fire owes -------+#+# A command definition never prompts an Agent, so a failure it should ACT on has to+# queue that turn itself. The turn is what the result stamp AUTHORISES, so the two are+# ONE transaction (HFR-269, ``core/watches.py``: "TWO COMMITS ARE NOT ONE DECISION").+# Split in two, a teardown between the commits queues an escalation under a definition+# that no longer authorises it, and an exception between them disables a failed one-shot+# while LOSING the report that explains it.+++def _escalation_command_task(+ store: ScheduledTaskStore,+ tmp_path: Path,+ *,+ shell_command: str,+ schedule_type: str = "cron",+ session_id: Optional[str] = None,+ prompt: str = "",+ agent_name: Optional[str] = None,+) -> ScheduledTask:+ """A command definition configured with ``--on-failure agent`` and a binding.++ The CLI guarantees such a definition has a session policy and a binding, because+ the escalation is a real Agent turn that has to land in a real conversation.+ """++ return store.add_task(+ session_key="",+ session_id=session_id,+ session_policy="existing" if session_id else None,+ agent_name=agent_name,+ prompt=prompt,+ schedule_type=schedule_type,+ cron="0 * * * *" if schedule_type == "cron" else None,+ run_at="2026-07-28T09:00:00+00:00" if schedule_type == "at" else None,+ timezone_name="UTC",+ cwd=str(tmp_path),+ deliver_key="slack::channel::C123",+ shell_command=shell_command,+ metadata={"origin": "cli", "on_failure": "agent"},+ )+++def _queued_runs(store: ScheduledTaskStore) -> list[dict[str, Any]]:+ assert store._sqlite is not None+ return [run for run in store._sqlite.list_runs() if run["status"] == "queued"]+++def _escalation_runs(store: ScheduledTaskStore) -> list[dict[str, Any]]:+ return [run for run in _queued_runs(store) if run["run_type"] == "task_escalation"]+++def _escalation_run_payload(task: ScheduledTask, *, run_id: str = "esc-1") -> dict[str, Any]:+ """The ``agent_runs`` outbox payload an escalation stamp would carry."""++ return {+ "id": run_id,+ "request_type": "task_escalation",+ "task_id": task.id,+ "session_key": "",+ "session_id": task.session_id,+ "prompt": "the report",+ "message": "the report",+ "source_kind": "scheduler",+ "parent_run_id": "parent-run",+ "status": "queued",+ "created_at": "2026-07-28T09:00:00+00:00",+ "updated_at": "2026-07-28T09:00:00+00:00",+ }+++def test_the_atomic_task_stamp_and_its_queued_run_both_land(+ tmp_path: Path, monkeypatch+) -> None:+ """HFR-269 control — with nothing racing it, ONE transaction carries both halves.++ A combined write that simply refused everything would satisfy the refusal test+ below vacuously ("no run row, definition untouched" is exactly what a method that+ never commits produces), so the positive half needs its own test: the definition's+ transition is readable AND the outbox row is durable, from one call.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ assert store.sqlite_backend is not None, (+ "this test needs the SQLite backend; a shared transaction is the whole fix"+ )+ task = _escalation_command_task(store, tmp_path, shell_command="exit 7")+ expect = store._read_state(task)+ task.last_error = "command exited with status 7"+ task.last_exit_code = 7++ landed = store.sqlite_backend.upsert_scheduled_task_with_queued_run(+ task.to_dict(), expect=expect, run_payload=_escalation_run_payload(task)+ )++ assert landed is True+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None and stored.last_exit_code == 7, (+ f"the definition's transition did not commit: {stored and stored.last_exit_code!r}"+ )+ runs = _escalation_runs(store)+ assert len(runs) == 1, f"expected exactly one queued escalation, got {runs!r}"+ assert runs[0]["id"] == "esc-1" and runs[0]["task_id"] == task.id+++def test_a_refused_atomic_task_stamp_writes_neither_half(+ tmp_path: Path, monkeypatch+) -> None:+ """A refused compare-and-set must leave NO run row and an untouched definition.++ The inverse of the control above, and the reason the two are one transaction: an+ escalation queued against a definition whose stamp was refused is a durable turn+ nothing authorises.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ assert store.sqlite_backend is not None+ task = _escalation_command_task(store, tmp_path, shell_command="exit 7")+ before = _stored_definition_row(task.id)+ # A STALE expectation: the payload claims it was read from a paused definition,+ # which is what a teardown committed after the read would have left behind.+ stale = scheduled_tasks.DefinitionWriteExpectation.from_read(+ session_id=task.session_id,+ enabled=False,+ deleted_at=None,+ metadata=task.metadata,+ )+ task.last_error = "command exited with status 7"++ landed = store.sqlite_backend.upsert_scheduled_task_with_queued_run(+ task.to_dict(), expect=stale, run_payload=_escalation_run_payload(task)+ )++ assert landed is False, "a stale expectation must be refused"+ assert _escalation_runs(store) == [], (+ "the refused stamp still queued its escalation; the two are not one transaction"+ )+ assert _stored_definition_row(task.id)["last_error"] == before["last_error"], (+ "a refused compare-and-set partially landed"+ )+++def test_mark_task_result_stamps_and_enqueues_in_one_call(+ tmp_path: Path, monkeypatch+) -> None:+ """``queued_run`` rides the stamp: one call, one transaction, both effects."""++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _escalation_command_task(store, tmp_path, shell_command="exit 7")++ stamped = store.mark_task_result(+ task.id,+ error="command exited with status 7",+ exit_code=7,+ queued_run=_escalation_run_payload(task),+ )++ assert stamped is True+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None and stored.last_exit_code == 7+ assert [run["id"] for run in _escalation_runs(store)] == ["esc-1"]+++def test_a_refused_mark_task_result_queues_no_run(tmp_path: Path, monkeypatch) -> None:+ """The refusal path: an unmatched binding expectation writes neither half."""++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _escalation_command_task(store, tmp_path, shell_command="exit 7")++ stamped = store.mark_task_result(+ task.id,+ error="command exited with status 7",+ exit_code=7,+ # The binding this fire started against, as the caller remembers it — and it+ # is not what the definition says, so the stamp must refuse.+ expected_binding=("some-other-session", "", "cron"),+ queued_run=_escalation_run_payload(task),+ )++ assert stamped is False+ assert _escalation_runs(store) == []+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None and stored.last_exit_code is None, (+ "a refused stamp recorded the exit code anyway"+ )+++def test_an_agent_renamed_during_the_command_still_gets_the_escalation(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-030 -- the queued turn must name an Agent the catalog still has.++ The escalation payload is composed from the definition as the fire CLAIMED it,+ which for a command task is however long the command ran. A rename committed in+ that window rewrites the definition and every ACTIVE run, but this run does not+ exist yet, so it escaped the rewrite and was inserted naming an Agent nobody can+ resolve: the turn carrying the failure report could never be claimed, while the+ notice its own stamp suppressed was already gone -- neither report, which is the+ one outcome the two-report invariant exists to rule out.++ The narrower race (a rename the mirror has NOT yet seen) needs no fix: the payload+ then carries the pre-rename binding revision and the compare-and-set refuses both+ halves, leaving the fire to the notice ladder exactly like the reclaim in SCT-004.+ What survives that guard is the rename the mirror ABSORBED -- and it absorbs one+ whenever ``PRAGMA data_version`` reports another connection's commit, which during+ a command long enough to matter is the normal case, not the exotic one. The reload+ is forced here because that probe is timing-dependent and the defect is not.+ """++ _command_task_env(tmp_path, monkeypatch)+ from core.vibe_agents import VibeAgentStore++ agent_store = VibeAgentStore(paths.get_sqlite_state_path())+ try:+ # A user Agent, because a built-in one cannot be renamed at all.+ agent_store.create(name="ops", backend="claude")+ finally:+ agent_store.close()++ store = ScheduledTaskStore()+ task = _escalation_command_task(+ store, tmp_path, shell_command="exit 7", agent_name="ops"+ )+ assert task.agent_name == "ops"+ # What ``build_hook_send`` puts on the payload: the name, resolved by the executor+ # before the command started. There is no ``agent_id`` to carry -- ``run_definitions``+ # stores only the spelling.+ run_payload = _escalation_run_payload(task)+ run_payload["agent_name"] = task.agent_name++ agent_store = VibeAgentStore(paths.get_sqlite_state_path())+ try:+ renamed = agent_store.rename("ops", "night-shift")+ finally:+ agent_store.close()+ # The executor's mirror catching up mid-command, which is what makes the stamp's+ # expectation current and the pre-composed run row the only stale thing left.+ store.load()+ assert store.get_task(task.id).agent_name == "night-shift"++ stamped = store.mark_task_result(+ task.id,+ error="command exited with status 7",+ exit_code=7,+ records_command_outcome=True,+ queued_run=run_payload,+ )++ assert stamped is True, "the rename was absorbed by the reload, so the stamp must land"+ runs = _escalation_runs(store)+ assert len(runs) == 1, f"expected exactly one queued escalation, got {runs!r}"+ queued = runs[0]+ assert queued["agent_name"] == "night-shift", (+ "the escalation was queued against the pre-rename name, which resolves to no "+ f"Agent at claim time: {queued['agent_name']!r}"+ )+ assert queued["agent_id"] == renamed.id, (+ "the escalation was not pinned to the Agent's durable identity, so the NEXT "+ f"rename loses it again: {queued['agent_id']!r}"+ )+++def test_an_archived_agent_keeps_the_escalations_own_spelling(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-030, negative half -- a REMOVED Agent must not be papered over.++ Resolution failing is not always a rename. If the user archived or deleted the+ Agent the definition names, there is no identity to pin and inventing one would+ bind the report to a different Agent than the definition asks for. The row keeps+ the definition's own spelling and lets the claim report the truth.+ """++ _command_task_env(tmp_path, monkeypatch)+ from core.vibe_agents import VibeAgentStore++ agent_store = VibeAgentStore(paths.get_sqlite_state_path())+ try:+ agent_store.create(name="ops", backend="claude")+ finally:+ agent_store.close()++ store = ScheduledTaskStore()+ task = _escalation_command_task(+ store, tmp_path, shell_command="exit 7", agent_name="ops"+ )+ run_payload = _escalation_run_payload(task)+ run_payload["agent_name"] = task.agent_name+ _delete_agent_row(paths.get_sqlite_state_path(), "ops")++ stamped = store.mark_task_result(+ task.id,+ error="command exited with status 7",+ exit_code=7,+ records_command_outcome=True,+ queued_run=run_payload,+ )++ assert stamped is True+ runs = _escalation_runs(store)+ assert len(runs) == 1+ assert runs[0]["agent_name"] == "ops", (+ f"the definition's own spelling was dropped: {runs[0]['agent_name']!r}"+ )+ assert not (runs[0]["agent_id"] or ""), (+ f"an identity was invented for an Agent that no longer exists: {runs[0]['agent_id']!r}"+ )+++def _delete_agent_row(db_path: Path, name: str) -> None:+ """Remove an Agent from the catalog outright, as a delete leaves it."""++ from storage.models import agents as agents_table++ with create_sqlite_engine(db_path).begin() as conn:+ conn.execute(agents_table.delete().where(agents_table.c.name == name))+++def test_a_file_backed_task_store_refuses_a_queued_run(tmp_path: Path) -> None:+ """The watch store's answer, replicated: REFUSE rather than save-then-enqueue.++ A file-backed store cannot make the two writes one decision at all, so a+ best-effort second write would be exactly the two-commits bug HFR-269 removed.+ Passing one here is a caller bug and says so.+ """++ store = ScheduledTaskStore(tmp_path / "scheduled_tasks.json")+ assert store.sqlite_backend is None+ task = store.add_task(+ session_key="",+ prompt="",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ shell_command="exit 7",+ metadata={"on_failure": "agent"},+ )++ with pytest.raises(ValueError):+ store.mark_task_result(+ task.id, error="boom", queued_run=_escalation_run_payload(task)+ )+++def test_a_failed_on_failure_agent_command_fire_queues_exactly_one_escalation(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-003 — a failed ``--on-failure agent`` fire reports through ONE Agent turn.++ The whole point of the mode: instead of a notification the user has to act on, the+ failure becomes a turn the Agent can act on. So all four halves are asserted from a+ REAL fire through the claimed-request path:++ * the parent run is ``failed`` and carries the ``escalation_run_id`` marker,+ * exactly one queued ``task_escalation`` row exists, pointing back at the fire and+ at the definition,+ * its prompt carries the command and the outcome the Agent has to act on, and+ * the parent owes NO failure notice -- the escalation IS the report, and both would+ be the same failure told twice.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_escalation")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="echo boom >&2; exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the fire failed ({run['error']!r})"+ escalations = _escalation_runs(store)+ assert len(escalations) == 1, (+ f"expected exactly one queued escalation for one failed fire: {escalations!r}"+ )+ escalation = escalations[0]+ assert run["metadata"].get("escalation_run_id") == escalation["id"], (+ "the failed run does not point at the turn that reports it: "+ f"{run['metadata'].get('escalation_run_id')!r} != {escalation['id']!r}"+ )+ assert escalation["parent_run_id"] == run["id"], (+ f"the escalation lost its parent fire: {escalation['parent_run_id']!r}"+ )+ assert escalation["task_id"] == task.id, (+ f"the escalation lost its definition: {escalation['task_id']!r}"+ )+ assert escalation["session_id"] == session_id+ assert "echo boom >&2; exit 7" in (escalation["prompt"] or ""), (+ f"the escalation must name the command that failed: {escalation['prompt']!r}"+ )+ assert "status 7" in (escalation["prompt"] or ""), (+ f"and the outcome it failed with: {escalation['prompt']!r}"+ )+ assert store._sqlite.owed_failure_notice(run["id"]) is None, (+ "an escalated failure also owes a notice; the same failure would be reported "+ "twice, once as a turn and once as an alert"+ )+++def test_archiving_the_session_gives_a_killed_escalation_its_notice_back(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-005 -- teardown must not turn an escalated failure into a silent one.++ A failed ``--on-failure agent`` fire suppresses its own failure notice because+ the escalation turn IS the report. Session teardown then cancels every queued run+ bound to that session -- the escalation among them -- and a ``canceled`` run owes+ nothing. So the failure ended up with NO turn and NO notice, which is the one+ direction this design refuses: the accepted crash window biases towards BOTH,+ never towards neither.++ The failure must fall back to the notice ladder, which does not need the+ torn-down session: a notice is delivered to the scope, not into a conversation.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_archive_esc")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the fire failed ({run['error']!r})"+ escalations = _escalation_runs(store)+ assert len(escalations) == 1, f"the premise: one escalation is queued ({escalations!r})"+ assert store._sqlite.owed_failure_notice(run["id"]) is None, (+ "the premise: the escalation suppressed the notice"+ )++ from storage.workbench_sessions_service import archive_session++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ archive_session(conn, session_id)+ finally:+ engine.dispose()++ assert _escalation_runs(store) == [], (+ "the premise: archiving the session cancels the queued escalation"+ )+ notice = store._sqlite.owed_failure_notice(run["id"])+ assert notice is not None, (+ "the escalation was canceled and no notice replaced it, so this failure is "+ "reported by nothing at all"+ )+ assert notice["state"] == "pending"+++def _start_the_escalation(escalation_id: str) -> None:+ """Move an escalation to ``running``, the way the executor does when it claims it."""++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ conn.execute(+ update(agent_runs)+ .where(agent_runs.c.id == escalation_id)+ .values(status="running", started_at="2026-07-28T09:00:01+00:00")+ )+ finally:+ engine.dispose()+++def test_archiving_the_session_gives_an_already_running_escalation_its_notice_back(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-009 -- an escalation teardown kills MID-TURN owes the same fallback.++ Teardown treats the two halves of "not yet terminal" differently: it flags all four+ active statuses ``cancel_requested`` and lets the executor honour it, but only+ ``pending``/``queued`` are terminalized on the spot. So an escalation the executor+ had already claimed is not canceled by this transaction -- it is canceled a moment+ later, out here, by the executor.++ That is the same silence as the queued case and it is harder to see. The re-arm ran+ only for ``pending``/``queued``, so an escalation cancelled at ``running`` settled+ ``canceled`` (owing nothing, as a cancel does) while the parent's notice stayed+ suppressed by ``escalation_run_id`` on the promise of a turn that was killed before+ it reported anything. What the re-arm must key on is "teardown has condemned this+ escalation", which is exactly the set teardown cancel-requests -- not the narrower+ set it happens to terminalize in the same statement.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_running_esc")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the fire failed ({run['error']!r})"+ escalations = _escalation_runs(store)+ assert len(escalations) == 1, f"the premise: one escalation is queued ({escalations!r})"+ assert store._sqlite.owed_failure_notice(run["id"]) is None, (+ "the premise: the escalation suppressed the notice"+ )++ # The window: the executor claims the turn, then teardown lands.+ _start_the_escalation(escalations[0]["id"])++ from storage.workbench_sessions_service import archive_session++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ archive_session(conn, session_id)+ with engine.begin() as conn:+ condemned = (+ conn.execute(+ select(agent_runs.c.cancel_requested).where(+ agent_runs.c.id == escalations[0]["id"]+ )+ )+ .scalars()+ .first()+ )+ finally:+ engine.dispose()++ assert condemned, (+ "the premise: teardown condemns a running escalation too, it just leaves the "+ "terminalizing to the executor"+ )+ notice = store._sqlite.owed_failure_notice(run["id"])+ assert notice is not None, (+ "the turn was killed before it could report anything and no notice replaced "+ "it, so this failure is reported by nothing at all"+ )+ assert notice["state"] == "pending"+++def test_hard_deleting_the_session_gives_a_killed_escalation_its_notice_back(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-005, other half -- ``/new`` owes the same fallback, and owes it EARLIER.++ ``_delete_agent_session_rows`` splits on retained history: a Session with Messages+ or Deliveries is archived and re-anchored (and cancels its queued runs on the way),+ while an EMPTY one is deleted outright. The empty branch is the one that bites,+ because it is both reachable and quieter: a Session created for a command task has+ no Messages until a turn actually delivers, so the first thing that ever happens in+ it can be a queued escalation -- and deleting the row leaves that escalation queued+ against a Session that no longer exists. It is not cancelled, so no cancel-shaped+ guard can see it; it simply never runs, and the notice it suppressed never came.++ So the re-arm belongs BEFORE the branch, not inside the archival half: the failure+ must fall back to the notice ladder whichever way the row goes.+ """++ from storage.models import agent_sessions+ from storage.session_reclaim import RECLAIM_PAUSE+ from storage.sessions_service import _delete_agent_session_rows++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_delete_esc")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the fire failed ({run['error']!r})"+ assert len(_escalation_runs(store)) == 1, "the premise: one escalation is queued"+ assert store._sqlite.owed_failure_notice(run["id"]) is None, (+ "the premise: the escalation suppressed the notice"+ )++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ deleted = _delete_agent_session_rows(+ conn,+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id),+ reclaim_mode=RECLAIM_PAUSE,+ reclaim_reason="new_session",+ )+ finally:+ engine.dispose()++ assert deleted == 1, "the premise: the empty Session row was torn down"+ notice = store._sqlite.owed_failure_notice(run["id"])+ assert notice is not None, (+ "the Session the escalation was queued against is gone, so the turn can never "+ "run and no notice replaced it: this failure is reported by nothing at all"+ )+ assert notice["state"] == "pending"+++def test_hard_deleting_the_session_also_cancels_the_runs_bound_to_it(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-010 -- a deleted Session must not leave claimable runs behind it.++ ``agent_runs.session_id`` carries no foreign key, so deleting the Session row does+ not touch the runs bound to it: they stay ``queued``, and the executor will happily+ claim one against a Session that no longer exists. The archival half of this same+ function cancels them; the delete half only stopped mattering less because the row+ it removes hid the problem.++ For a command-task escalation the cost is precise. The re-arm above has already+ handed the failure back to the notice ladder on the grounds that the turn can never+ run -- so if the turn is nonetheless claimed and dies on the missing Session, that+ death reports the SAME failure a second time, from the lane meant to replace it.+ Terminalizing here is what makes the re-arm's premise true.+ """++ from storage.models import agent_sessions+ from storage.session_reclaim import RECLAIM_PAUSE+ from storage.sessions_service import _delete_agent_session_rows++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_delete_orphan")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed", f"the premise: the fire failed ({run['error']!r})"+ escalations = _escalation_runs(store)+ assert len(escalations) == 1, f"the premise: one escalation is queued ({escalations!r})"++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ deleted = _delete_agent_session_rows(+ conn,+ select(agent_sessions.c.id).where(agent_sessions.c.id == session_id),+ reclaim_mode=RECLAIM_PAUSE,+ reclaim_reason="new_session",+ )+ with engine.begin() as conn:+ settled = (+ conn.execute(+ select(agent_runs.c.status, agent_runs.c.cancel_requested).where(+ agent_runs.c.id == escalations[0]["id"]+ )+ )+ .mappings()+ .first()+ )+ finally:+ engine.dispose()++ assert deleted == 1, "the premise: the empty Session row was torn down"+ assert settled is not None, "the escalation row itself should survive as history"+ assert settled["status"] == "canceled", (+ "the escalation is still claimable against a Session that no longer exists: "+ f"{settled['status']!r}"+ )+ assert settled["cancel_requested"], (+ "and nothing recorded that the teardown is what ended it"+ )+++def _edit_definition_command(definition_id: str, shell_command: str) -> None:+ """Commit a command edit from another connection, the way ``vibe task update`` does."""++ from storage.models import run_definitions++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ conn.execute(+ update(run_definitions)+ .where(run_definitions.c.id == definition_id)+ .values(shell_command=shell_command)+ )+ finally:+ engine.dispose()+++def _repoint_definition_session(definition_id: str, session_id: str) -> None:+ """Commit a binding change from another connection, the way ``/new`` does."""++ from storage.models import run_definitions++ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ conn.execute(+ update(run_definitions)+ .where(run_definitions.c.id == definition_id)+ .values(session_id=session_id)+ )+ finally:+ engine.dispose()+++def test_a_reclaim_during_the_command_refuses_the_stamp_and_escalates_nowhere(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-004 -- a binding that moved mid-fire must not receive the escalation.++ ``mark_task_result`` reloads the mirror and derives its compare-and-set+ expectation FROM THE RELOADED ROW, so a ``/new`` reclaim that commits while the+ command is running becomes the expectation the stamp compares against -- it+ matches, and the stamp lands. That was survivable while the stamp only wrote+ bookkeeping. It is not survivable now that the same stamp QUEUES AN AGENT TURN:+ the escalation is composed from the pre-execution task object, so it would be+ durably queued against the session the reclaim just tore down, and the notice+ would be suppressed in favour of a turn that can never be delivered there.++ The fire must instead be refused whole: no escalation row, and the failure+ reported on the run so the owed-notice ladder still owns it.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_reclaim_before")+ reclaimed_session_id = _bare_session_row(+ workdir=tmp_path, anchor="avibe_task_reclaim_after"+ )+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ real_runner = scheduled_tasks.run_supervised_command++ async def _reclaim_then_fail(**kwargs):+ # The reclaim commits WHILE the command runs, which is the only ordering that+ # reaches the window: before the fire there is nothing to stamp, and after the+ # stamp the transaction has already closed.+ result = await real_runner(**kwargs)+ _repoint_definition_session(task.id, reclaimed_session_id)+ return result++ monkeypatch.setattr(scheduled_tasks, "run_supervised_command", _reclaim_then_fail)++ run = _fire_command_task(service, task)++ assert _escalation_runs(store) == [], (+ "an escalation was queued against a binding the definition no longer has"+ )+ assert run["status"] == "failed", (+ f"a fire whose stamp was refused must not report success: {run['status']!r}"+ )+ assert run["metadata"].get("escalation_run_id") in (None, ""), (+ "the run claims an escalation that was never queued, which suppresses the "+ f"notice too: {run['metadata'].get('escalation_run_id')!r}"+ )+++def test_a_cancel_during_the_command_refuses_the_escalation_and_settles_canceled(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-026 -- a stopped job must not answer by starting an Agent.++ The reclaim twin above guards the BINDING; this guards the STOP, and the window is+ narrower than the one SCT-013 covers. There the flag is observed by the tick, which+ cancels the awaiting coroutine and the fire never reaches its stamp. Here the+ command has already exited, so nothing is left to interrupt: ``mark_task_result``+ stamps the failure and durably queues the escalation, and only afterwards does+ ``complete`` read ``cancel_requested`` and settle the run ``canceled``.++ Two commits are not one decision. The turn the stamp authorises is durable by then,+ so the user stops a job and the job answers by starting an Agent. The stop has to be+ re-read SERVER-SIDE inside the stamp's own transaction, which is the only place it+ can still roll the escalation back with it.++ The definition must still end up describing this fire rather than the one before it+ -- that is the terminal projection's job, and a refused stamp is exactly when it is+ needed.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_cancel_stamp")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="echo boom >&2; exit 7",+ session_id=session_id,+ )+ # The premise for the projection assertion: a PREVIOUS fire left an outcome behind.+ store.mark_task_result(task.id, error=None, exit_code=3, records_command_outcome=True)++ service = _scheduled_service_with_ledger(tmp_path, store, [])+ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ real_runner = scheduled_tasks.run_supervised_command++ async def _stop_it_as_it_exits(**kwargs):+ result = await real_runner(**kwargs)+ # The only ordering that reaches the window: after the command is done, so the+ # tick has nothing left to interrupt, and before the stamp opens its transaction.+ service.request_store.cancel_run(queued.id)+ return result++ monkeypatch.setattr(scheduled_tasks, "run_supervised_command", _stop_it_as_it_exits)++ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))++ run = service.request_store.get_run(queued.id)+ assert run is not None+ assert run["status"] == "canceled", (+ f"the premise: the stop won the settlement race ({run['status']!r})"+ )+ assert _escalation_runs(store) == [], (+ "the user stopped this run and it answered by durably queueing an Agent turn"+ )+ assert run["metadata"].get("escalation_run_id") in (None, ""), (+ "the run claims an escalation that was rolled back with the stamp: "+ f"{run['metadata'].get('escalation_run_id')!r}"+ )++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ # 7, not the 3 the previous fire left: the stamp was refused, so the terminal+ # projection is what describes this fire -- and the fire did exit 7, which the run+ # row carries. The refusal rolls back the ESCALATION, not the record of the outcome.+ assert stored.last_exit_code == 7, (+ "the refused stamp left the definition reporting the exit code of the fire "+ f"BEFORE this one: {stored.last_exit_code!r}"+ )+ assert (stored.metadata or {}).get(COMMAND_TIMED_OUT_METADATA_KEY) is False, (+ "the projection left the timeout claim of an earlier fire standing beside a "+ f"code this one chose for itself: {stored.metadata!r}"+ )+++def test_a_stop_that_lands_after_the_stamp_retracts_the_escalation(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-033 -- a compare-and-set can only refuse the stops it can already see.++ SCT-026 closes the window where the cancel is visible when the stamp commits: the+ transaction re-reads it server-side and rolls the escalation back with the stamp.+ One step further along the same coroutine the guard has already run. ``cancel_run``+ on a running fire writes only a flag, so the flag can land AFTER+ ``mark_task_result`` returns -- and ``settle_run_terminal`` then re-reads it and+ normalizes this fire to ``canceled`` while the escalation it just committed sits+ queued and claimable. The user stops a job and the job answers by starting an Agent,+ which is SCT-026's defect surviving one lane later.++ Retraction rather than a wider transaction: the enqueue must commit with the STAMP+ (that is what authorises the turn), and this settlement happens afterwards in+ another lane, so no single transaction holds both without reopening HFR-269.++ NEITHER report is owed. ``canceled`` is written only for a stop the user asked for,+ and a stopped fire owes no notice -- SCT-027's rule. Alerting instead would report a+ failure for a job they had just stopped. The definition still describes the failure,+ because this stamp -- unlike SCT-026's -- landed.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_late_stop")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="echo boom >&2; exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ real_mark = service.store.mark_task_result++ def _stop_it_after_the_stamp(*args, **kwargs):+ stamped = real_mark(*args, **kwargs)+ # THE window: the guarded transaction has committed, so the escalation is+ # durable and no compare-and-set is left to consult.+ service.request_store.cancel_run(queued.id)+ return stamped++ monkeypatch.setattr(service.store, "mark_task_result", _stop_it_after_the_stamp)++ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))++ run = service.request_store.get_run(queued.id)+ assert run is not None+ assert run["status"] == "canceled", (+ f"the premise: the stop won the settlement race ({run['status']!r})"+ )+ assert run["metadata"].get("escalation_run_id"), (+ "the premise: this stamp LANDED, so the run names the turn it authorised"+ )++ escalation_id = str(run["metadata"]["escalation_run_id"])+ escalation = service.request_store.get_run(escalation_id)+ assert escalation is not None, "the escalation row vanished rather than settling"+ assert escalation["status"] == "canceled", (+ "the user stopped this command and the Agent turn it queued is still claimable: "+ f"{escalation['status']!r}"+ )+ assert _escalation_runs(store) == [], (+ "a queued escalation survived the stop of the fire that queued it"+ )++ # The failure itself is not lost: this stamp landed, unlike SCT-026's.+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None and stored.last_exit_code == 7+++def test_claiming_the_escalation_of_a_stopped_fire_is_refused_at_the_door(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-034 -- retraction is too late once the dispatch loop has claimed the turn.++ SCT-033 takes the escalation back from whoever settles the fire ``canceled``, and+ that works for exactly as long as the row is still queued. The dispatch loop runs on+ the same loop as the fire's own coroutine, and the escalation becomes claimable the+ moment the stamp commits -- well before this settlement reaches it. A claim is the+ one transition retraction cannot undo: ``cancel_run`` on a running Agent Run writes+ a flag, and the turn lane does not watch that flag, so the stopped job would launch+ an Agent and run it to completion.++ So the CLAIM answers the question, from the parent row, inside the transaction that+ would otherwise start the work -- and then it no longer matters which of the two+ lanes gets there first. Keyed on the fire's ``cancel_requested``, which is set the+ instant the user asks, rather than on any status a claim would have to wait for.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_claimed_stop")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="echo boom >&2; exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ real_mark = service.store.mark_task_result+ claim_attempt: dict[str, Any] = {}++ def _stop_it_then_claim_the_escalation(*args, **kwargs):+ stamped = real_mark(*args, **kwargs)+ if claim_attempt:+ # The terminal projection stamps the definition again on its way out; only+ # the FIRST stamp is the one that queued the escalation.+ return stamped+ # THE ordering: the escalation is durable, the user's stop lands, and the+ # dispatch loop claims the escalation before the fire's settlement gets to it.+ service.request_store.cancel_run(queued.id)+ escalation = service.request_store.find_escalation_run(parent_run_id=queued.id)+ assert escalation is not None, "the premise: the stamp queued an escalation"+ claim_attempt["id"] = str(escalation["id"])+ claim_attempt["claimed"] = service.request_store.claim(claim_attempt["id"])+ return stamped++ monkeypatch.setattr(+ service.store, "mark_task_result", _stop_it_then_claim_the_escalation+ )++ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))++ run = service.request_store.get_run(queued.id)+ assert run is not None+ assert run["status"] == "canceled", (+ f"the premise: the stop won the settlement race ({run['status']!r})"+ )+ assert claim_attempt.get("claimed") is None, (+ "the dispatch loop was handed the escalation of a fire the user had already "+ f"stopped: {claim_attempt.get('claimed')!r}"+ )++ escalation = service.request_store.get_run(str(claim_attempt["id"]))+ assert escalation is not None, "the escalation row vanished rather than settling"+ assert escalation["status"] == "canceled", (+ "the refused claim left the escalation of a stopped fire non-terminal, so a "+ f"later pass can start it: {escalation['status']!r}"+ )+ assert _escalation_runs(store) == [], (+ "a claimable escalation survived the stop of the fire that queued it"+ )++ # The failure is still recorded on the definition; only the Agent turn is withdrawn.+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None and stored.last_exit_code == 7+++def test_teardown_between_the_stamp_and_the_settle_cancels_the_fire_itself(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-027 -- why the settle needs no second check on the escalation it names.++ SCT-005 and SCT-009 both let the parent settle FIRST, so+ ``rearm_notices_for_escalations_canceled_with_session`` finds a ``failed`` row and+ can hand it a notice. The window in between looks like it breaks that: teardown+ lands after the atomic stamp+enqueue and before ``complete``, so the re-arm sees a+ parent that is still ``running`` and owes nothing yet, and ``complete`` then writes+ ``escalation_run_id`` -- apparently suppressing a notice in favour of a turn that+ was cancelled a moment earlier, leaving the failure reported by nothing.++ IT DOES NOT, and this test is the reason a status check inside the settle would be+ dead code. The teardown that cancels the escalation cannot cancel only the+ escalation: ``archive_session`` flags EVERY non-terminal run of that session, and+ this fire is one of them. So the settle normalizes the parent to ``canceled``, and+ ``canceled`` owes no notice by design -- the run is recorded as stopped, not as a+ failure whose report went missing. Nothing is suppressed because nothing was owed.+ """++ from storage.workbench_sessions_service import archive_session++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_stamp_teardown")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ real_mark = store.mark_task_result++ def _stamp_then_tear_down(*args, **kwargs):+ stamped = real_mark(*args, **kwargs)+ engine = create_sqlite_engine(paths.get_sqlite_state_path())+ try:+ with engine.begin() as conn:+ archive_session(conn, session_id)+ finally:+ engine.dispose()+ return stamped++ monkeypatch.setattr(store, "mark_task_result", _stamp_then_tear_down)++ run = _fire_command_task(service, task)++ assert run["status"] == "canceled", (+ "the teardown that cancelled the escalation left this fire settling as a "+ f"failure, so the settle really can suppress a notice for a dead turn: {run['status']!r}"+ )+ assert _escalation_runs(store) == [], (+ "the premise: teardown cancelled the escalation this fire queued"+ )+ assert store._sqlite.owed_failure_notice(run["id"]) is None, (+ "a cancelled fire stamped a failure notice, which is the noise "+ "``_owed_failure_notice_for_transition`` exists to refuse"+ )+++def test_the_escalation_prompt_prepends_the_stored_message_and_names_the_run(+ tmp_path: Path, monkeypatch+) -> None:+ """The user's standing instruction first, then the machine-generated evidence.++ ``vibe task add --shell ... --on-failure agent --message "open a ticket"`` stores+ that message as the definition's prompt: it is the instruction, and the report is+ what it operates on. The report also has to name the run, or the Agent cannot look+ up the full output the one-line tails were cut from.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="echo boom >&2; exit 7",+ prompt="Open a ticket if the nightly sync breaks.",+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ prompt = service._escalation_prompt(+ task,+ run_id="run-abc123",+ error="command exited with status 7: boom",+ exit_code=7,+ stdout="starting\nsyncing\n",+ stderr="warning: slow\nboom\n",+ )++ assert prompt.startswith("Open a ticket if the nightly sync breaks."), (+ f"the stored instruction must come first: {prompt!r}"+ )+ assert "echo boom >&2; exit 7" in prompt, f"the command must be named: {prompt!r}"+ assert "command exited with status 7: boom" in prompt+ assert "Exit code: 7" in prompt+ assert "boom" in prompt.split("Last stderr line:")[1].splitlines()[0], (+ f"the stderr tail is where the cause usually is: {prompt!r}"+ )+ assert "syncing" in prompt.split("Last stdout line:")[1].splitlines()[0], (+ f"the stdout tail was dropped: {prompt!r}"+ )+ assert "run-abc123" in prompt and "vibe runs show run-abc123" in prompt, (+ f"the report must say how to read the full output: {prompt!r}"+ )+++def test_an_escalating_command_runs_in_its_bound_sessions_workdir(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-008 -- the relative commands the docs promise have to resolve somewhere.++ ``--cwd`` is REFUSED for a definition bound to an existing Session, on the rule+ that the Session owns its working directory (`cwd_with_existing_session`), so the+ CLI stores ``cwd=None``. For a message task that is complete: the Agent turn starts+ in the Session's workdir. A command task has no Agent turn to inherit it from, so+ the stored ``None`` fell through to the ``~/.avibe`` fallback -- meaning+ ``--shell './scripts/sync.sh'``, the form the docs use, ran from the product state+ directory with no way to override it: the flag that would fix it is the one the+ Session rule rejects.++ So the binding has to supply what it refused to let the user state.++ The lookup opens a store per FIRE, and each one carries an engine and an+ invalidation probe, so the second assertion is that it does not outlive the read:+ a cron command running every minute would otherwise leak a connection a minute for+ the life of the service.+ """++ import storage.sessions_service as sessions_service++ _command_task_env(tmp_path, monkeypatch)+ project = tmp_path / "project"+ project.mkdir()+ (project / "marker").write_text("bound-session-workdir\n", encoding="utf-8")++ opened: list[str] = []+ closed: list[str] = []++ class _CountedSessionsService(sessions_service.SQLiteSessionsService):+ def __init__(self, *args: Any, **kwargs: Any) -> None:+ super().__init__(*args, **kwargs)+ opened.append(str(id(self)))++ def close(self) -> None:+ closed.append(str(id(self)))+ super().close()++ monkeypatch.setattr(+ sessions_service, "SQLiteSessionsService", _CountedSessionsService+ )++ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=project, anchor="avibe_task_cwd")+ task = store.add_task(+ session_key="",+ session_id=session_id,+ # The exact shape ``vibe task add --shell ... --on-failure agent+ # --session-id ...`` stores: an existing binding, and NO cwd.+ session_policy="existing",+ prompt="",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ cwd=None,+ deliver_key="slack::channel::C123",+ shell_command="cat marker",+ metadata={"origin": "cli", "on_failure": "agent"},+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "succeeded", (+ "the command could not read a file sitting in its own Session's workdir, so it "+ f"ran somewhere else: {run['error']!r}"+ )+ assert _escalation_runs(store) == [], "a succeeded fire must not escalate"+ assert opened, "the premise: the fire resolved its workdir through a Session store"+ assert closed == opened, (+ "the workdir lookup left its Session store open, so every fire of this cron "+ f"leaks an engine and its invalidation probe: opened {opened!r}, closed {closed!r}"+ )+++def test_a_command_with_nothing_to_inherit_runs_where_agent_work_runs(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-048 -- the product state directory is the wrong last resort.++ SCT-008 gave a Session-bound command its binding's workdir. A definition can still+ reach the fire with neither: a per-run binding whose Session does not exist yet+ (created before the CLI recorded the invocation directory for it), or one written+ straight through the API. Those fell through to ``paths.get_vibe_remote_dir()`` --+ ``~/.avibe`` -- so a relative command ran against persisted product state, where its+ files are missing and its writes land among the store's.++ ``runtime.default_cwd`` is where this install's Agent turns already run, so it is+ both a real directory and the same answer the escalation Session would get.+ """++ _command_task_env(tmp_path, monkeypatch)+ work = tmp_path / "agent-work"+ work.mkdir()+ (work / "marker").write_text("runtime-default-workdir\n", encoding="utf-8")++ store = ScheduledTaskStore()+ task = store.add_task(+ session_key="",+ # The shape ``--create-session-per-run`` stores: no cwd, and no Session to read+ # one from until escalation creates it.+ session_policy="create_per_run",+ prompt="",+ schedule_type="cron",+ cron="0 * * * *",+ timezone_name="UTC",+ cwd=None,+ shell_command="cat marker",+ metadata={"origin": "cli", "on_failure": "agent"},+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ service.controller.config = SimpleNamespace(+ language="en", runtime=SimpleNamespace(default_cwd=str(work))+ )++ run = _fire_command_task(service, task)++ assert run["status"] == "succeeded", (+ "the command could not read a file sitting in the configured runtime workdir, "+ f"so it ran in the product state directory instead: {run['error']!r}"+ )+ assert "runtime-default-workdir" in (run["stdout"] or "")+++def test_the_run_snapshot_names_the_command_the_fire_actually_ran(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-028 -- the snapshot is only worth having if it is the executed copy.++ The enqueue stamps the definition as it stood THEN, but the executor re-reads the+ definition after claiming the run -- so an edit committed in that window left the+ run naming command A while command B ran, and the notice, the escalation prompt and+ the Workbench run detail all repeated that wrong answer with a snapshot's authority.+ Worse than no snapshot: it is the record readers were told to trust precisely+ because the definition is mutable.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(+ store, shell_command="echo original", cwd=str(tmp_path)+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ predicted = service.request_store.get_run(queued.id)+ assert predicted is not None+ assert predicted["metadata"].get(COMMAND_SNAPSHOT_METADATA_KEY) == {+ "shell": "echo original",+ "argv": [],+ }, f"the premise: the enqueue predicted a command ({predicted['metadata']!r})"++ # ``SqliteInvalidationProbe`` reports "changed" only by COMPARING two readings of+ # ``PRAGMA data_version``, so its very first call always answers no. A live service+ # has ticked long before a fire claims anything; a test has to prime it, or the+ # mirror below never reloads and the executor cannot see the edit at all.+ service.store.maybe_reload()++ # The window: the user rewrites the command after it was queued and before it runs.+ _edit_definition_command(task.id, "echo edited")++ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))++ run = service.request_store.get_run(queued.id)+ assert run is not None+ assert "edited" in (run["stdout"] or ""), (+ f"the premise: the executor ran the edited command ({run['stdout']!r})"+ )+ assert run["metadata"].get(COMMAND_SNAPSHOT_METADATA_KEY) == {+ "shell": "echo edited",+ "argv": [],+ }, (+ "the run's immutable record of what it executed names a command it did not "+ f"execute: {run['metadata'].get(COMMAND_SNAPSHOT_METADATA_KEY)!r}"+ )+++def test_a_running_command_fire_does_not_hold_its_conversations_turn_lock(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-012 -- a six-hour backup command must not mute the conversation for six hours.++ The per-session lock exists to stop TWO AGENT TURNS running in one conversation at+ once. A command fire is not a turn: it talks to no Agent, writes no message, and+ holds no native session. But it is bound to a Session (``--on-failure agent`` needs+ one), so it inherited that Session's lock key -- and with ``--timeout`` defaulting+ to six hours, one long command left every queued turn in the conversation skipped as+ ``session_busy`` for as long as it ran.++ The escalation it may queue is the part that IS a turn, and it is a separate run+ that takes the lock in the ordinary way. So the fire keys on the definition instead:+ still serialized against itself, no longer against the user.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_lock")+ task = _escalation_command_task(+ store, tmp_path, shell_command="sleep 3600", session_id=session_id+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ fire = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert fire is not None+ fire_lock = service._execution_lock_key(fire)+ session_lock = service._canonical_session_lock(session_id, None)+ assert fire_lock == f"task:{task.id}", (+ "the command fire took a lock keyed on something other than its own definition"+ )+ assert fire_lock != session_lock, "the fire is holding the conversation's turn lock"++ # And the consequence, through the real drain: the escalation turn this very+ # definition would queue has to be dispatchable while the command is still running.+ service._inflight_sessions.add(fire_lock)+ escalation = service.request_store.enqueue_hook_send(+ session_key="",+ session_id=session_id,+ prompt="the report",+ run_type="task_escalation",+ definition_id=task.id,+ source_kind="scheduler",+ )+ dispatched: list[str] = []+ monkeypatch.setattr(+ service, "_spawn_execution", lambda request, lock_key: dispatched.append(request.id)+ )++ asyncio.run(service._drain_requests())++ assert dispatched == [escalation.id], (+ "the escalation was held behind the command fire: "+ f"{service.request_store.get_run(escalation.id)['metadata']}"+ )+++def test_canceling_a_running_command_run_actually_stops_the_command(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-013 -- ``vibe runs cancel`` has to mean the work stops, not just the row.++ For every other run type cancellation reaches the work: a turn is interrupted, a+ queued claim is terminalized at the door. A command fire had NOTHING watching the+ flag, so ``cancel_requested`` was only read at settlement -- which for a command+ that hangs is up to ``--timeout`` (six hours by default) away. Until then the child+ kept running, holding whatever it was holding, and the row the user was shown said+ the run was already canceled.++ The runner already owns the kill: cancelling the awaiting coroutine tears down the+ process tree. What was missing was somebody to observe the flag and pull it, so the+ scheduler tick does -- the same ``_inflight_cancellation_causes`` + ``task.cancel()``+ pair service shutdown uses, only with the user named as the cause.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_cancel")+ started = tmp_path / "command-started"+ task = _escalation_command_task(+ store,+ tmp_path,+ # Announces itself, then hangs for far longer than this test may wait.+ shell_command=f"touch {started.name}; sleep 3600",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ async def _cancel_it_mid_flight() -> None:+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None+ service._spawn_execution(request, service._execution_lock_key(request))+ execution = service._inflight_executions[request.id]+ for _ in range(200):+ if started.exists():+ break+ await asyncio.sleep(0.05)+ assert started.exists(), "the command never started, so nothing was cancelled"++ service.request_store.cancel_run(request.id)+ service._propagate_requested_cancellations()+ # Ten seconds, against a command that sleeps for an hour: the point of the+ # assertion is that the wait ends because the command was killed.+ await asyncio.wait_for(+ asyncio.gather(execution, return_exceptions=True), timeout=10+ )++ try:+ asyncio.run(_cancel_it_mid_flight())+ except asyncio.TimeoutError: # pragma: no cover - the defect this test reproduces+ pytest.fail("cancelling the run left the command running")++ run = next(+ row+ for row in store._sqlite.list_runs()+ if row["run_type"] not in {"task_escalation"}+ )+ assert run["status"] == "canceled", f"a cancelled fire settled as {run['status']!r}"+ assert _escalation_runs(store) == [], (+ "a fire the user cancelled escalated to an Agent as though the command had failed"+ )+ stored = ScheduledTaskStore().get_task(task.id)+ # The stop landed before the result stamp, which is what keeps the definition free+ # of a fabricated outcome: a command killed mid-flight has no exit status, and the+ # cancellation is recorded as the stop it was (``last_error``), not as a command that+ # reported one.+ assert stored is not None and stored.last_exit_code is None, (+ "a cancelled fire stamped an exit code the command never produced"+ )+++def test_canceling_a_run_whose_task_was_removed_still_stops_the_command(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-020 -- removing the task must not make its running command unkillable.++ ``remove_task`` drops the definition immediately and leaves the in-flight Run+ alive, which is the ONLY way a user can react to a command that is misbehaving+ right now. Deciding command-ness by asking the live store therefore answered+ "not a command" exactly when the answer mattered, the cancellation was ignored,+ and the child ran on to its ``--timeout`` -- six hours by default. The run+ carries an immutable snapshot of what it launched; that is what decides.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ started = tmp_path / "orphan-started"+ task = _add_command_task(+ store,+ shell_command=f"touch {started.name}; sleep 3600",+ cwd=str(tmp_path),+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ async def _remove_then_cancel() -> None:+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None+ service._spawn_execution(request, service._execution_lock_key(request))+ for _ in range(200):+ if started.exists():+ break+ await asyncio.sleep(0.05)+ assert started.exists(), "the command never started, so nothing was cancelled"++ assert store.remove_task(task.id), "the definition was not removed"+ assert store.get_task(task.id) is None+ service.request_store.cancel_run(request.id)+ service._propagate_requested_cancellations()+ await asyncio.wait_for(+ asyncio.gather(service._inflight_executions[request.id], return_exceptions=True),+ timeout=10,+ )++ try:+ asyncio.run(_remove_then_cancel())+ except asyncio.TimeoutError: # pragma: no cover - the defect this test reproduces+ pytest.fail("removing the task left its cancelled command running")+++def test_a_crashed_service_reaps_the_command_worker_it_left_running(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-023 -- a service that dies without unwinding must not leak its command.++ Every ORDERLY stop reaches the child through the awaiting coroutine's+ ``CancelledError``. A SIGKILL or a crash delivers none: the isolated supervisor+ and the backup, deployment or migration under it keep running, unowned, and the+ next cron fire starts a SECOND one beside it. Nothing on disk named that child,+ so the restart could not have found it even in principle.++ The crash is simulated by abandoning the in-flight coroutine and constructing a+ fresh service over the same state, which is what a restart does; the assertion+ is that the abandoned fire then ends on its own, because its worker was killed.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ started = tmp_path / "worker-started"+ task = _add_command_task(+ store,+ shell_command=f"touch {started.name}; sleep 3600",+ cwd=str(tmp_path),+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ async def _crash_then_restart() -> None:+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None+ service._spawn_execution(request, service._execution_lock_key(request))+ for _ in range(200):+ if started.exists():+ break+ await asyncio.sleep(0.05)+ assert started.exists(), "the command never started, so nothing was orphaned"++ workers = service.request_store.list_running_command_workers()+ assert workers, "the fire recorded no worker, so a restart cannot find it"+ assert workers[0]["run_id"] == request.id++ # The restart. Its ``__init__`` reaps before ``recover_processing`` settles+ # the row the identity is stored on.+ _scheduled_service_with_ledger(tmp_path, store, [])++ await asyncio.wait_for(+ asyncio.gather(+ service._inflight_executions[request.id], return_exceptions=True+ ),+ timeout=15,+ )++ try:+ asyncio.run(_crash_then_restart())+ except asyncio.TimeoutError: # pragma: no cover - the defect this test reproduces+ pytest.fail("the restart left the orphaned command worker running")+++def test_a_worker_that_survives_the_reap_is_kept_for_the_next_start(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-029 -- an unconfirmed kill must not throw away the only handle on the child.++ SCT-023 records the worker's identity so a restart can find it. But the reap+ cleared that record unconditionally, INCLUDING when the teardown came back+ unconfirmed and the process was still there -- a task wedged in uninterruptible+ I/O outlives even ``SIGKILL``. Since the run is the only place the identity is+ written, and ``recover_processing`` settles the run moments later, no later pass+ could ever find that backup or migration again: it ran to completion unowned.++ So the record survives and the row stays ``running`` for the next start to retry.+ The cap is the other half: retrying forever would hold a run ``running`` for the+ life of the install whenever the process genuinely never exits.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ started = tmp_path / "unkillable-started"+ task = _add_command_task(+ store,+ shell_command=f"touch {started.name}; sleep 3600",+ cwd=str(tmp_path),+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ attempts: list[int] = []++ def _refuse_to_confirm(pid, *args, **kwargs):+ """A teardown that reports "not confirmed" while the process keeps running."""++ attempts.append(pid)+ return False++ def _worker_record() -> Optional[dict[str, Any]]:+ workers = service.request_store.list_running_command_workers()+ return workers[0]["identity"] if workers else None++ def _run_row(run_id: str) -> dict[str, Any]:+ row = service.request_store.get_run(run_id)+ assert row is not None+ return row++ async def _restart_until_it_gives_up() -> None:+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None+ service._spawn_execution(request, service._execution_lock_key(request))+ for _ in range(200):+ if started.exists():+ break+ await asyncio.sleep(0.05)+ assert started.exists(), "the command never started, so nothing was orphaned"+ assert _worker_record(), "the fire recorded no worker"++ real_terminate = process_isolation.terminate_process_tree_by_pid+ monkeypatch.setattr(+ process_isolation, "terminate_process_tree_by_pid", _refuse_to_confirm+ )+ cap = ScheduledTaskService._MAX_COMMAND_WORKER_REAP_ATTEMPTS+ # Every start before the cap: the kill is attempted, comes back unconfirmed,+ # and the record is kept with its attempt count so the NEXT one can try.+ for attempt in range(1, cap):+ _scheduled_service_with_ledger(tmp_path, store, [])+ assert len(attempts) == attempt, (+ f"start {attempt} did not attempt the kill: {attempts!r}"+ )+ identity = _worker_record()+ assert identity is not None, (+ f"start {attempt} discarded a live worker's identity, so no later start "+ "can ever find it"+ )+ assert identity.get("reap_attempts") == attempt, (+ f"the attempt count did not advance: {identity!r}"+ )+ assert _run_row(request.id)["status"] == "running", (+ "the run was settled while its worker was still alive; "+ "``list_running_command_workers`` will not see it again"+ )++ # The cap. The process is still there and still unkillable, but the run stops+ # being held open on its behalf.+ _scheduled_service_with_ledger(tmp_path, store, [])+ assert _worker_record() is None, "the reap never gave up; this run stays running forever"+ assert _run_row(request.id)["status"] != "running", (+ "the spent run was left ``running`` with nothing tracking it"+ )++ # Cleanup: the abandoned coroutine still owns the child, and its cancellation+ # is the orderly teardown every non-crash stop uses. Restored by name, never+ # ``monkeypatch.undo()`` -- that would also put back the real ``paths``, and a+ # teardown writing to the user's live ``~/.avibe`` is exactly what+ # ``_command_task_env`` exists to prevent.+ monkeypatch.setattr(+ process_isolation, "terminate_process_tree_by_pid", real_terminate+ )+ execution = service._inflight_executions[request.id]+ execution.cancel()+ await asyncio.wait_for(+ asyncio.gather(execution, return_exceptions=True), timeout=15+ )++ try:+ asyncio.run(_restart_until_it_gives_up())+ except asyncio.TimeoutError: # pragma: no cover - cleanup only+ pytest.fail("the cancelled command was left running")+++_SUPERVISOR_KILLED_MID_COMMAND = (+ "import os, subprocess, sys, time\n"+ "child = subprocess.Popen([sys.executable, '-c', 'import time; time.sleep(3600)'])\n"+ "sys.stdout.write(f'{child.pid}\\n')\n"+ "sys.stdout.flush()\n"+ "time.sleep(0.5)\n"+ "os._exit(0)\n"+)+++def test_a_restart_reaps_the_group_a_dead_supervisor_left_behind(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-032 -- an empty supervisor pid is not an empty tree.++ The worker is spawned into its own session, so it LEADS the process group+ ``pgid == pid``, and on POSIX that group outlives it. Kill the supervisor alone --+ the OOM killer picking the parent, a fault in the supervisor's own code -- and the+ backup or migration underneath keeps running in a group nothing else names.++ Reading the free pid as proof the tree was reaped is the whole defect: the reap+ stopped there, cleared ``command_worker``, and let ``recover_processing`` settle+ the row moments later, so the survivor ran to completion unowned and the next+ cron fire started a second one beside it. The watch lane already walked the+ surviving group; this asserts the command lane does too, on a real one.+ """++ if os.name == "nt":+ pytest.skip("a process group outliving its leader is POSIX-specific")++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="sleep 3600", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None++ marker = process_isolation.new_process_identity_marker()+ leader = subprocess.Popen( # noqa: S603 - fixed argv, test-owned+ [os.path.abspath(sys.executable), "-c", _SUPERVISOR_KILLED_MID_COMMAND],+ stdout=subprocess.PIPE,+ text=True,+ env=process_isolation.process_identity_subprocess_env(marker),+ **process_isolation.isolated_subprocess_kwargs(),+ )+ child_pid: Optional[int] = None+ try:+ identity = process_isolation.capture_spawned_process_identity(leader.pid, marker)+ assert identity is not None+ assert leader.stdout is not None+ child_pid = int(leader.stdout.readline().strip())+ assert leader.wait(timeout=15) == 0, "the supervisor did not die on its own"+ assert process_isolation.probe_process_liveness(leader.pid) == "gone"+ assert os.getpgid(child_pid) == leader.pid, (+ "the command did not inherit the supervisor's process group, so this is "+ "not the state the defect needs"+ )++ assert service.request_store.record_command_worker(+ request.id, process_isolation.serialize_process_identity(identity)+ )+ assert service.request_store.list_running_command_workers(), (+ "the fixture did not leave the run in the state the startup reap scans"+ )++ # The restart. Its ``__init__`` reaps before ``recover_processing`` settles+ # the row the identity is stored on.+ _scheduled_service_with_ledger(tmp_path, store, [])++ deadline = 15.0+ while deadline > 0 and process_isolation.probe_process_liveness(child_pid) != "gone":+ time.sleep(0.1)+ deadline -= 0.1+ assert process_isolation.probe_process_liveness(child_pid) == "gone", (+ "the restart read the dead supervisor as a reaped tree and left the "+ "command running, unowned, with nothing on disk naming it"+ )+ assert not service.request_store.list_running_command_workers(), (+ "a proven death must retire the record; keeping it would pin the run "+ "``running`` and retry a kill on a pid that is free"+ )+ row = service.request_store.get_run(request.id)+ assert row is not None and row["status"] != "running"+ finally:+ if child_pid is not None:+ with suppress(ProcessLookupError, PermissionError):+ os.kill(child_pid, process_isolation.KILL_SIGNAL)+ with suppress(Exception):+ leader.kill()+ with suppress(Exception):+ leader.wait(timeout=5)+ if leader.stdout is not None:+ leader.stdout.close()+++def test_a_probe_that_cannot_read_the_process_keeps_its_identity(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-031 -- "I could not look" is not "it is gone", and only gone retires a record.++ SCT-029 keeps the handle when the KILL comes back unconfirmed. The liveness+ question in front of that kill had the same two answers folded into one:+ ``inspect_process_identity`` returns ``None`` both for an empty pid and for a+ probe that could not read the process table at all -- an exhausted fd table, a+ ``/proc`` read losing a race, a platform refusing ``create_time``. Treating the+ second as absence skipped the kill AND cleared the record, so a backup still+ writing became unfindable by every later start too, and the next fire could run+ beside it.++ Reads as a restart, because that is the only caller: the reap runs from+ ``__init__``, before ``recover_processing`` settles the row the identity lives on.+ The cap applies here as well -- a probe that never recovers must not hold a run+ ``running`` for the life of the install.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="sleep 3600", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None++ # A worker record for a process that is never spawned: the probe is what is+ # under test, so the pid only has to survive ``process_identity_from_payload``.+ assert service.request_store.record_command_worker(+ request.id,+ {+ "pid": 424242,+ "create_time": 1.0,+ "worker_fingerprint": fingerprint_process_marker("orphaned-worker"),+ },+ )+ assert service.request_store.list_running_command_workers(), (+ "the fixture did not leave the run in the state the startup reap scans"+ )++ signalled: list[int] = []++ def _record_kill(pid, *_args, **_kwargs) -> bool:+ signalled.append(pid)+ return True++ monkeypatch.setattr(+ process_isolation, "probe_process_liveness", lambda _pid: "unknown"+ )+ monkeypatch.setattr(+ process_isolation, "terminate_process_tree_by_pid", _record_kill+ )++ def _worker_record() -> Optional[dict[str, Any]]:+ workers = service.request_store.list_running_command_workers()+ return workers[0]["identity"] if workers else None++ cap = ScheduledTaskService._MAX_COMMAND_WORKER_REAP_ATTEMPTS+ for attempt in range(1, cap):+ _scheduled_service_with_ledger(tmp_path, store, [])+ identity = _worker_record()+ assert identity is not None, (+ f"start {attempt} read the process as gone because it could not read it at "+ "all, and threw away the only handle on it"+ )+ assert identity.get("reap_attempts") == attempt, (+ f"the attempt count did not advance: {identity!r}"+ )+ row = service.request_store.get_run(request.id)+ assert row is not None and row["status"] == "running", (+ "the run was settled while its worker was unaccounted for; "+ "``list_running_command_workers`` will not see it again"+ )++ assert signalled == [], (+ "the reap signalled a pid whose identity it could not read; that is the "+ "coin flip on an unrelated process the identity check exists to refuse"+ )++ # The cap. Still unreadable, but the run stops being held open on its behalf.+ _scheduled_service_with_ledger(tmp_path, store, [])+ assert _worker_record() is None, "the reap never gave up; this run stays running forever"+ row = service.request_store.get_run(request.id)+ assert row is not None and row["status"] != "running", (+ "the spent run was left ``running`` with nothing tracking it"+ )+++def test_a_command_whose_worker_cannot_be_recorded_is_never_started(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-037 -- the handshake is the one moment a nameless worker can be refused.++ Every other guard in this family protects a record that already exists. If the+ stamp itself does not land, the fire runs a backup or deployment with nothing on+ disk naming it, and a crash mid-command leaves the same unfindable orphan+ SCT-023/029/031/032 exist to prevent -- reached before the record was ever written.++ Refusing costs almost nothing HERE and only here: the supervisor is blocked reading+ its spec off stdin, so the user's command has not started, and the runner reaps the+ tree on the way out. So a captured identity that cannot be persisted fails the fire.++ The negative half is the same judgement from the other side: an identity that could+ not be CAPTURED does not refuse. Its dominant cause is a supervisor that already+ exited, where there is no process to name, and no amount of persisting makes an+ uncapturable identity trustworthy -- every kill path refuses a record it cannot+ vouch for. Turning that into a refusal would stop honest commands from running.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ ran = tmp_path / "command-ran"+ task = _add_command_task(+ store, shell_command=f"touch {ran.name}", cwd=str(tmp_path)+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ supervisors: list[int] = []+ real_capture = command_runner.capture_spawned_process_identity++ def _remember_the_supervisor(pid, marker):+ supervisors.append(pid)+ return real_capture(pid, marker)++ monkeypatch.setattr(+ command_runner, "capture_spawned_process_identity", _remember_the_supervisor+ )++ real_record = type(service.request_store).record_command_worker++ def _cannot_write(self, run_id, identity):+ if identity is not None:+ raise RuntimeError("database is locked")+ return real_record(self, run_id, identity)++ monkeypatch.setattr(+ type(service.request_store), "record_command_worker", _cannot_write+ )++ queued = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ claimed = service.request_store.claim(queued.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))++ assert not ran.exists(), (+ "the command ran with nothing on disk naming the process running it; a crash "+ "here leaves an orphan no later start can find"+ )+ run = service.request_store.get_run(queued.id)+ assert run is not None and run["status"] == "failed", (+ f"the refusal was not reported as a failed fire: {run and run['status']!r}"+ )+ assert "could not be recorded" in (run["error"] or ""), (+ f"the user is not told why the command did not run: {run and run['error']!r}"+ )+ assert supervisors, "the supervisor never spawned, so nothing was refused"+ for _ in range(100):+ if process_isolation.probe_process_liveness(supervisors[0]) == "gone":+ break+ time.sleep(0.05)+ assert process_isolation.probe_process_liveness(supervisors[0]) == "gone", (+ "the refusal left the supervisor running -- the very leak it exists to prevent"+ )++ # The negative half: nothing to name is not the same as failing to name it.+ monkeypatch.setattr(+ type(service.request_store), "record_command_worker", real_record+ )+ monkeypatch.setattr(+ command_runner, "capture_spawned_process_identity", lambda _pid, _marker: None+ )+ second = service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ )+ claimed = service.request_store.claim(second.id)+ assert claimed is not None+ asyncio.run(service._execute_claimed_request(claimed))++ assert ran.exists(), (+ "a command whose identity could not be captured was refused; the usual cause "+ "is a supervisor that already exited, and the honest ones must still run"+ )+ run = service.request_store.get_run(second.id)+ assert run is not None and run["status"] == "succeeded", (+ f"the uncaptured identity failed an otherwise fine fire: {run and run['status']!r}"+ )+++def test_an_enumeration_that_fails_leaves_the_records_it_could_not_read(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-036 -- "I could not enumerate" is not "there is nothing to protect".++ SCT-031 fixed that category error one layer down, on a single process. The same+ mistake sat one layer up, on the whole set: the startup reap answered a failed+ ``list_running_command_workers`` with an empty skip set, and the ``recover_processing``+ on the very next line then settled EVERY ``running`` command fire -- because only+ ``running`` rows carry ``command_worker``, one momentary read failure permanently+ unnamed every live backup and deployment on the host, and the next fire ran beside+ them.++ So the settle pass no longer trusts a set handed to it. It reads the record off the+ row it is about to settle, inside the same transaction, and the reap communicates by+ WRITING that record: cleared once the process is proven dead or the retries are+ spent, left in place on every maybe -- including the maybe where it never looked.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="sleep 3600", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ def _claimed_fire() -> str:+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None+ return request.id++ # Two interrupted fires, differing only in whether a worker record survived: one+ # whose process is unaccounted for, and one the last life already proved dead.+ with_worker = _claimed_fire()+ without_worker = _claimed_fire()+ assert service.request_store.record_command_worker(+ with_worker,+ {+ "pid": 424242,+ "create_time": 1.0,+ "worker_fingerprint": fingerprint_process_marker("orphaned-worker"),+ },+ )++ real_list = type(service.request_store).list_running_command_workers++ def _cannot_read(_self):+ raise RuntimeError("database is locked")++ monkeypatch.setattr(+ type(service.request_store), "list_running_command_workers", _cannot_read+ )++ # The restart, with the enumeration failing exactly as a momentary lock would.+ _scheduled_service_with_ledger(tmp_path, store, [])++ monkeypatch.setattr(+ type(service.request_store), "list_running_command_workers", real_list+ )++ workers = {+ worker["run_id"]: worker["identity"]+ for worker in service.request_store.list_running_command_workers()+ }+ assert with_worker in workers, (+ "a start that could not enumerate the workers settled the run anyway, and the "+ "identity lives on that row -- no later start can find that process again"+ )+ assert workers[with_worker].get("reap_attempts") is None, (+ "no kill was attempted, so nothing may be charged against the attempt cap"+ )+ row = service.request_store.get_run(with_worker)+ assert row is not None and row["status"] == "running", (+ "the row must stay ``running`` for the next start's enumeration to see it"+ )++ # The other half: preservation keys on the surviving record, not on the run type,+ # so a fire with no worker to protect is settled like any other interrupted run.+ row = service.request_store.get_run(without_worker)+ assert row is not None and row["status"] != "running", (+ "a fire carrying no worker record was held open by a read failure that had "+ "nothing to do with it"+ )+++def test_a_definition_does_not_fire_while_its_own_worker_may_be_alive(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-040 -- single flight per definition must survive the restart that breaks it.++ ``_execution_lock_key`` keys a command fire on its definition "so a fire is still+ serialized against itself", but ``self._inflight_sessions`` is memory: the rule+ lapses at exactly the moment a survivor is most likely. The service dies, the+ supervisor's tree keeps running, the startup reap RETAINS its record because it+ could not prove it dead -- and then the next tick of the same cron starts a second+ copy of that backup over the same dataset.++ So a command fire consults the durable record too, by identity, and only for its+ own definition: another definition's live worker is not its business. It looks and+ never signals -- the retained record exists so a later start can kill that tree, and+ a fire that reaped it to make room would destroy the work it was scheduled to+ protect. Proof of death releases the definition here rather than a restart later.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ second_copy = tmp_path / "second-copy-ran"+ other_ran = tmp_path / "other-definition-ran"+ task = _add_command_task(+ store, shell_command=f"touch {second_copy}", cwd=str(tmp_path)+ )+ other = _add_command_task(store, shell_command=f"touch {other_ran}", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ async def _drain_and_wait() -> None:+ await service._drain_requests()+ for execution in list(service._inflight_executions.values()):+ await execution++ marker = "surviving-command-worker"+ survivor = subprocess.Popen(+ [sys.executable, "-c", "import time; time.sleep(300)"],+ env=process_identity_subprocess_env(marker),+ **isolated_subprocess_kwargs(),+ )+ try:+ identity = capture_spawned_process_identity(survivor.pid, marker)+ assert identity is not None+ # A fire from the previous life: claimed, ``running``, still naming the process+ # that outlived the service -- what the startup reap leaves behind on a maybe.+ orphan = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert orphan is not None+ assert service.request_store.record_command_worker(+ orphan.id, serialize_process_identity(identity)+ )++ asyncio.run(service._run_task(task.id))+ assert not second_copy.exists(), (+ "the cron tick started a second copy of a command whose first copy is still "+ "running -- two writers over one dataset"+ )+ deferred = [+ request+ for request in service.request_store.list_pending()+ if request.task_id == task.id+ ]+ assert deferred, (+ "the deferred fire was dropped rather than requeued; it must run once the "+ "earlier worker is shown gone"+ )++ # The drain reaches the same row on its own tick and must answer it the same way,+ # recording the skip so an indefinitely deferred fire never looks sweepable.+ asyncio.run(_drain_and_wait())+ assert not second_copy.exists(), (+ "the drain ran the second copy the scheduler had just refused to run"+ )+ row = service.request_store.get_run(deferred[0].id)+ assert row is not None and (row["metadata"] or {}).get(+ "last_skip_reason"+ ) == "session_busy", (+ "a fire deferred by a live worker recorded no skip reason, so the stale-run "+ f"sweep sees an idle queued row: {row and row['metadata']!r}"+ )++ assert any(+ worker["run_id"] == orphan.id+ for worker in service.request_store.list_running_command_workers()+ ), "the fire cleared the live worker's record, the only handle on that process"+ assert survivor.poll() is None, (+ "the fire SIGNALLED the earlier worker to make room for itself"+ )++ # Scoped to the definition: another definition's fire is not held up by it.+ asyncio.run(service._run_task(other.id))+ assert other_ran.exists(), (+ "one definition's live worker blocked every other definition's fire"+ )+ finally:+ survivor.kill()+ survivor.wait()++ # Proven dead now, so the record is retired and the definition fires again.+ asyncio.run(_drain_and_wait())+ assert second_copy.exists(), (+ "the deferred fire never ran after its blocking worker exited; a dead worker's "+ "record would hold its own schedule shut until the next restart"+ )+ assert not [+ worker+ for worker in service.request_store.list_running_command_workers()+ if worker["run_id"] == orphan.id+ ], "the proven-dead worker's record was left to block later fires forever"+++def test_both_run_stores_name_the_definition_a_command_worker_belongs_to(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-042 -- a worker record nobody can attribute defers nothing.++ SCT-040's guard filters the recorded workers by definition, because "some command+ is running" is not a reason to skip a different one. The file backend omitted the+ field: the SQLite column was renamed ``definition_id`` while the file payload still+ spells the association ``task_id``, so its entries matched no definition at all --+ which does not read as "no worker", it reads as "no worker for every definition at+ once", and single flight silently stopped holding on that backend.++ Asserted on both backends together, since the field is a store contract and a+ reader cannot tell which one it was handed.+ """++ db_path = _command_task_env(tmp_path, monkeypatch)+ assert db_path is not None+ task_store = ScheduledTaskStore()+ task = _add_command_task(task_store, shell_command="sleep 3600", cwd=str(tmp_path))+ identity = {+ "pid": 424242,+ "create_time": 1.0,+ "worker_fingerprint": fingerprint_process_marker("attributed-worker"),+ }++ for label, store in (+ ("sqlite", TaskExecutionStore()),+ ("file", TaskExecutionStore(tmp_path / "task_requests")),+ ):+ claimed = store.claim(+ store.enqueue_task_run(task.id, source_kind="scheduler", task=task).id+ )+ assert claimed is not None, f"{label}: could not claim the fire"+ assert store.record_command_worker(claimed.id, identity), (+ f"{label}: the worker record did not land"+ )+ workers = [+ worker+ for worker in store.list_running_command_workers()+ if worker["run_id"] == claimed.id+ ]+ assert workers, f"{label}: the recorded worker was not listed"+ assert workers[0].get("definition_id") == task.id, (+ f"{label}: the worker is not attributed to its definition "+ f"({workers[0].get('definition_id')!r}), so a fire of that definition "+ "cannot tell this worker apart from another definition's and starts a "+ "second copy of the command"+ )+++def test_both_run_stores_settle_a_fire_with_the_command_it_ran(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-049 -- the executed snapshot has to survive the completion that publishes it.++ SCT-028 re-stamps the run with the command the executor really spawned, and every+ reader of that record -- the failure notice, the escalation prompt, the Workbench run+ detail -- reads it off the TERMINAL row. The file backend composed that row from the+ ``TaskExecutionRequest`` the caller still held, which is the enqueue-time copy, so the+ re-stamp was overwritten at the last step and the settled run named the command as it+ stood before the edit. SQLite updates the row the metadata already lives on and keeps+ it for free; the gap was invisible from there.++ Asserted on both backends together, like SCT-042: what a settled run remembers is a+ store contract, and its readers cannot tell which store answered them.+ """++ db_path = _command_task_env(tmp_path, monkeypatch)+ assert db_path is not None+ task_store = ScheduledTaskStore()+ task = _add_command_task(+ task_store, shell_command="echo original", cwd=str(tmp_path)+ )++ for label, store in (+ ("sqlite", TaskExecutionStore()),+ ("file", TaskExecutionStore(tmp_path / "task_requests")),+ ):+ queued = store.enqueue_task_run(task.id, source_kind="scheduler", task=task)+ predicted = store.get_run(queued.id)+ assert predicted is not None+ assert predicted["metadata"].get(COMMAND_SNAPSHOT_METADATA_KEY) == {+ "shell": "echo original",+ "argv": [],+ }, f"{label}: the premise -- the enqueue predicted a command"++ claimed = store.claim(queued.id)+ assert claimed is not None, f"{label}: could not claim the fire"+ # The executor's re-stamp: the definition was edited between enqueue and claim.+ assert store.record_command_snapshot(+ claimed.id, {"shell": "echo edited", "argv": []}+ ), f"{label}: the executed snapshot did not land on the in-flight row"++ assert (+ store.complete(claimed, ok=True, exit_code=0, stdout="edited\n")+ == "succeeded"+ ), f"{label}: the fire did not settle"++ settled = store.get_run(queued.id)+ assert settled is not None, f"{label}: the settled run is unreadable"+ assert settled["metadata"].get(COMMAND_SNAPSHOT_METADATA_KEY) == {+ "shell": "echo edited",+ "argv": [],+ }, (+ f"{label}: the settled run's immutable record of what it executed names a "+ "command it did not execute "+ f"({settled['metadata'].get(COMMAND_SNAPSHOT_METADATA_KEY)!r}), so the "+ "notice and the escalation prompt report the wrong command with a "+ "snapshot's authority"+ )+++def test_a_failed_retention_write_keeps_the_stored_worker_record(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-041 -- the last write in the retain path is not allowed to lose the record.++ SCT-036 established the invariant one call up: every maybe keeps the record, a+ failure to look included. The retain path itself then broke it at the end -- a+ locked database while re-stamping the attempt count answered "did not retain", and+ the caller's next line clears the record. A store hiccup, which says nothing at all+ about the process, thereby did the one thing the whole path exists to prevent.++ The stored record survives a failed write untouched, so the honest answer is that it+ was kept: it simply keeps the attempt count it had, this pass is not charged against+ the cap, and the next start looks again.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="sleep 3600", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ orphan = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert orphan is not None+ identity = {+ "pid": 424242,+ "create_time": 1.0,+ "worker_fingerprint": fingerprint_process_marker("unreapable-worker"),+ }+ assert service.request_store.record_command_worker(orphan.id, identity)++ # A worker that could not be shown dead, and a re-stamp that fails the way a+ # momentary lock does. Neither is a fact about the process.+ monkeypatch.setattr(+ scheduled_tasks,+ "reap_orphaned_process_tree",+ lambda *_a, **_kw: "unconfirmed",+ )+ real_record = type(service.request_store).record_command_worker++ def _cannot_write(self, run_id, identity):+ if identity is None:+ # Only the re-stamp fails. The clear on the caller's next line must still+ # work, or this test cannot tell a kept record from an undeletable one.+ return real_record(self, run_id, identity)+ raise RuntimeError("database is locked")++ monkeypatch.setattr(+ type(service.request_store), "record_command_worker", _cannot_write+ )++ service._reap_orphaned_command_workers()++ monkeypatch.setattr(+ type(service.request_store), "record_command_worker", real_record+ )++ workers = {+ worker["run_id"]: worker["identity"]+ for worker in service.request_store.list_running_command_workers()+ }+ assert orphan.id in workers, (+ "a failed attempt-count write discarded the identity of a worker that could not "+ "be shown dead -- that row was the only place it was written"+ )+ assert workers[orphan.id].get("reap_attempts") is None, (+ "the write failed, so nothing was stored and nothing may be charged against the "+ "attempt cap"+ )+ row = service.request_store.get_run(orphan.id)+ assert row is not None and row["status"] == "running", (+ "the row must stay ``running`` for the next start's enumeration to see it"+ )+++def test_a_recovered_fire_is_settled_when_its_worker_is_finally_shown_gone(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-044 -- releasing the definition is only half of closing the old fire.++ SCT-040 made a proven death release the definition immediately instead of waiting+ for a restart, which left the interrupted run behind: NO OTHER PASS COMES BACK FOR+ IT. ``recover_processing`` runs once at startup and steps over any row still naming+ a worker -- this row's whole reason for surviving -- and ``sweep_stale_runs`` only+ classifies orphans of ``run_type == "agent_run"``. So the run stayed ``running``+ until the next restart while the backup it described was over, the definition read+ as still executing, and the user was never told the fire had been interrupted at all.++ Settled the same way the startup pass would have settled it, ``restarted``, since+ that is what happened -- one interruption should not be told two ways depending on+ which pass got to prove the death.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="sleep 3600", cwd=str(tmp_path))+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ # A worker whose death is PROVABLE: spawned, named, then reaped, so its recorded+ # identity points at a pid the OS has fully released.+ marker = "worker-that-died-while-the-service-was-down"+ dead = subprocess.Popen(+ [sys.executable, "-c", "import sys; sys.exit(0)"],+ env=process_identity_subprocess_env(marker),+ **isolated_subprocess_kwargs(),+ )+ identity = capture_spawned_process_identity(dead.pid, marker)+ dead.wait()+ assert identity is not None++ orphan = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert orphan is not None+ assert service.request_store.record_command_worker(+ orphan.id, serialize_process_identity(identity)+ )++ assert service._command_definition_has_live_worker(task.id) is False, (+ "a worker proven dead must not defer the next fire"+ )++ row = service.request_store.get_run(orphan.id)+ assert row is not None+ assert row["status"] == "failed", (+ "the recovered fire was released but never closed, so it reads as still running "+ f"a command that ended before the service came back: {row['status']!r}"+ )+ assert row["completed_at"], "a terminal run with no completion time"+ assert row["error"], (+ "the interrupted fire settled with no explanation for the user to read"+ )+ assert (row["metadata"] or {}).get("interrupt_reason") == "restarted", (+ "the interruption was recorded under a different cause than the startup pass "+ f"uses for the same event: {row['metadata']!r}"+ )+ assert not [+ worker+ for worker in service.request_store.list_running_command_workers()+ if worker["run_id"] == orphan.id+ ], "the dead worker's record outlived the run it named"+ settled = store.get_task(task.id)+ assert settled is not None and settled.last_error, (+ "the definition still shows no failure for a fire that was interrupted, so the "+ "Harness lists it as healthy and the user never learns the command was cut off"+ )+++def test_a_recovered_fire_is_settled_on_the_file_store_too(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-046 -- the legacy store must not release a fire it never closed.++ SCT-044 settles the released fire through the guarded per-run writer, which only+ SQLite has. On the file store that check answered "unsupported" and the method+ returned having done nothing but clear the worker record: the definition was+ released, the next fire ran, and the interrupted run's file sat in ``processing``+ reading ``running`` until some later restart -- the exact leak SCT-044 removed,+ still open one backend over.++ Both backends are asked the same question here because both are read the same way:+ ``vibe runs`` and the Harness show whatever the store says, and a run that says+ ``running`` describes a backup that is still going.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ task = _add_command_task(store, shell_command="sleep 3600", cwd=str(tmp_path))+ service = _binding_service(tmp_path, store, [])+ assert service.request_store.supports_guarded_settlement() is False, (+ "this test is about the store WITHOUT the guarded writer"+ )++ marker = "file-store-worker-that-died-while-the-service-was-down"+ dead = subprocess.Popen(+ [sys.executable, "-c", "import sys; sys.exit(0)"],+ env=process_identity_subprocess_env(marker),+ **isolated_subprocess_kwargs(),+ )+ identity = capture_spawned_process_identity(dead.pid, marker)+ dead.wait()+ assert identity is not None++ orphan = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert orphan is not None+ assert service.request_store.mark_execution_started(orphan.id)+ assert service.request_store.record_command_worker(+ orphan.id, serialize_process_identity(identity)+ )++ assert service._command_definition_has_live_worker(task.id) is False++ row = service.request_store.get_run(orphan.id)+ assert row is not None+ assert row["status"] == "failed", (+ "the file-backed fire was released but never closed, so it still reads as "+ f"running a command that ended before the service came back: {row['status']!r}"+ )+ assert row["error"], "the interrupted fire settled with no explanation"+ assert (row["metadata"] or {}).get("interrupt_reason") == "restarted"+ assert not (tmp_path / "task_requests" / "processing" / f"{orphan.id}.json").exists(), (+ "the run was reported terminal while its processing file still claimed it"+ )+ assert not [+ worker+ for worker in service.request_store.list_running_command_workers()+ if worker["run_id"] == orphan.id+ ], "the dead worker's record outlived the run it named"+++def test_an_interrupted_command_fire_clears_the_previous_exit_code(+ tmp_path: Path, monkeypatch+) -> None:+ """SCT-021 -- an interrupted fire is still a fire with no status of its own.++ SCT-017 gave the command fire's own stamp authority over ``last_exit_code``,+ ``None`` included. A cancelled or shutdown-interrupted fire never reaches that+ stamp: ``run_supervised_command`` raises, and settlement projects the run through+ the generic lane, which by design leaves the column alone so a message task cannot+ blank a command's code. The result was "exited 7" on the row beside a run the user+ had just stopped -- the same fabricated fact SCT-017 removed, one lane over.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ started = tmp_path / "interrupted-started"+ task = _add_command_task(+ store,+ shell_command=f"touch {started.name}; sleep 3600",+ cwd=str(tmp_path),+ )+ # What a previous fire of this definition left behind.+ assert store.mark_task_result(+ task.id, error="exited 7", exit_code=7, records_command_outcome=True+ )+ assert ScheduledTaskStore().get_task(task.id).last_exit_code == 7+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ async def _cancel_mid_flight() -> None:+ request = service.request_store.claim(+ service.request_store.enqueue_task_run(+ task.id, source_kind="scheduler", task=task+ ).id+ )+ assert request is not None+ service._spawn_execution(request, service._execution_lock_key(request))+ for _ in range(200):+ if started.exists():+ break+ await asyncio.sleep(0.05)+ assert started.exists(), "the command never started"+ service.request_store.cancel_run(request.id)+ service._propagate_requested_cancellations()+ await asyncio.wait_for(+ asyncio.gather(service._inflight_executions[request.id], return_exceptions=True),+ timeout=10,+ )++ asyncio.run(_cancel_mid_flight())++ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None+ assert stored.last_exit_code is None, (+ "an interrupted command fire kept the previous fire's exit code: "+ f"{stored.last_exit_code!r}"+ )+ assert stored.last_error, "the interruption was not recorded on the definition"+++def test_a_failed_one_shot_command_task_is_disabled_and_escalates_together(+ tmp_path: Path, monkeypatch+) -> None:+ """The trap this design avoids: the stamp that authorises the turn also disables.++ ``enqueue_definition_run`` re-reads the definition server-side and RAISES on a+ disabled one -- and a failed ``at`` task is disabled by the very stamp that+ authorises its escalation. Routing the turn through that writer would mean a+ one-shot command task NEVER escalates, which is the case that needs it most: there+ is no next fire to notice the failure.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_oneshot")+ task = _escalation_command_task(+ store,+ tmp_path,+ shell_command="exit 7",+ schedule_type="at",+ session_id=session_id,+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "failed"+ stored = ScheduledTaskStore().get_task(task.id)+ assert stored is not None and stored.enabled is False, (+ "a failed one-shot command definition stayed enabled"+ )+ assert len(_escalation_runs(store)) == 1, (+ "the one-shot was disabled without queueing the report that explains why"+ )+++def test_a_refused_result_stamp_queues_no_escalation_and_leaves_a_notice(+ tmp_path: Path, monkeypatch+) -> None:+ """Stamp refused -> zero escalation rows AND a notice: never silent.++ THE PRODUCTION STORY (HFR-261/HFR-264 applied to this lane). A command task fires+ and fails. While the fire is running the user archives the bound Session, and+ ``reclaim_bound_definitions(mode='delete')`` soft-deletes the definition. The+ guarded stamp then correctly REFUSES -- and the escalation rolls back with it,+ because both were the same transaction. The failure must still be visible, so the+ owed-notice path takes it over.+ """++ from storage.session_reclaim import RECLAIM_DELETE++ from storage.sessions_service import SQLiteSessionsService++ _binding_env(tmp_path, monkeypatch)+ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / "avibe_home")+ store = ScheduledTaskStore()+ assert store._sqlite is not None+ sessions = SQLiteSessionsService(paths.get_sqlite_state_path())+ try:+ session_id = sessions.bind_agent_session(+ scope_key="slack::channel::C123",+ agent_name="codex",+ session_anchor="slack_C123:escalation_refusal",+ native_session_id="native-esc",+ )+ finally:+ sessions.close()+ assert session_id is not None+ task = _escalation_command_task(+ store, tmp_path, shell_command="exit 7", session_id=session_id+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ race = _commit_reclaim_after(+ store._sqlite.engine,+ session_id,+ read=_DEFINITION_EXISTS_SELECT,+ mode=RECLAIM_DELETE,+ reason="the session was archived",+ )++ run = _fire_command_task(service, task)++ assert race["fired"] == 1, (+ "the competing archive never landed inside the write window, so this test "+ "proved nothing; the rendered SQL of the guarded upsert's existence probe drifted"+ )+ assert run["status"] == "failed"+ assert _escalation_runs(store) == [], (+ "an escalation survived a refused stamp: a durable turn nothing authorises"+ )+ assert run["metadata"].get("escalation_run_id") is None, (+ "the run claims an escalation the transaction rolled back"+ )+ notice = store._sqlite.owed_failure_notice(run["id"])+ assert notice is not None and notice.get("state"), (+ "no escalation AND no notice: the failure is silent, which is the one outcome "+ "this design must never produce"+ )+++def test_claiming_an_escalation_dispatches_it_as_a_hook_send(+ tmp_path: Path, monkeypatch+) -> None:+ """The executor has to accept the new request type and route it somewhere real.++ ``delivery_intent_for_trigger`` has a CLOSED vocabulary and would RAISE on an+ unmapped trigger, so an escalation takes the hook intent -- it IS an out-of-band+ turn a definition queued. Provenance is not lost: the row still carries+ ``run_type="task_escalation"`` and its parent fire.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_escalation_exec")+ task = _escalation_command_task(+ store, tmp_path, shell_command="exit 7", session_id=session_id+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ dispatched: list[dict[str, Any]] = []++ async def _spy(**kwargs):+ dispatched.append(kwargs)+ return TaskDispatchResult(error=None)++ service._execute_request = _spy # type: ignore[method-assign]++ escalation = service.request_store.build_hook_send(+ session_key="",+ session_id=session_id,+ prompt="A scheduled command task failed: nightly sync",+ deliver_key=task.deliver_key,+ session_policy=task.session_policy,+ run_type="task_escalation",+ definition_id=task.id,+ source_kind="scheduler",+ parent_run_id="parent-run",+ )+ service.request_store.enqueue(escalation)+ assert [run["id"] for run in _escalation_runs(store)] == [escalation.id], (+ "the escalation is not visible as a queued run at all"+ )+ assert [+ pending.id+ for pending in service.request_store.list_pending()+ if pending.request_type == "task_escalation"+ ] == [escalation.id], (+ "the drain loop's pending list filters the escalation out, so a durable "+ "escalation would never be executed"+ )+ claimed = service.request_store.claim(escalation.id)+ assert claimed is not None++ asyncio.run(service._execute_claimed_request(claimed))++ assert len(dispatched) == 1, f"the escalation was not dispatched: {dispatched!r}"+ assert dispatched[0]["trigger_kind"] == "hook", (+ f"an escalation must take the hook delivery intent: {dispatched[0]['trigger_kind']!r}"+ )+ assert dispatched[0]["prompt"] == escalation.prompt, (+ "the dispatched turn is not carrying the composed report"+ )+ settled = service.request_store.get_run(escalation.id)+ assert settled is not None and settled["status"] == "succeeded"+ assert settled["run_type"] == "task_escalation", (+ f"the escalation's provenance was rewritten to {settled['run_type']!r}"+ )+++def test_a_successful_on_failure_agent_command_fire_escalates_nothing(+ tmp_path: Path, monkeypatch+) -> None:+ """``--on-failure agent`` is a FAILURE policy; success stays silent.++ Otherwise a minute-ly health check would bill an Agent turn every minute and post+ a reply nobody asked for.+ """++ _command_task_env(tmp_path, monkeypatch)+ store = ScheduledTaskStore()+ session_id = _bare_session_row(workdir=tmp_path, anchor="avibe_task_escalation_ok")+ task = _escalation_command_task(+ store, tmp_path, shell_command="echo fine", session_id=session_id+ )+ service = _scheduled_service_with_ledger(tmp_path, store, [])++ run = _fire_command_task(service, task)++ assert run["status"] == "succeeded", f"the premise: the fire succeeded ({run['error']!r})"+ assert _escalation_runs(store) == [], "a successful fire escalated anyway"+ assert run["metadata"].get("escalation_run_id") is None+ assert store._sqlite.owed_failure_notice(run["id"]) is None, (+ "a succeeded run must owe no notice either"+ )+++def test_complete_with_an_escalation_marker_stamps_no_owed_notice(+ tmp_path: Path, monkeypatch+) -> None:+ """The suppression is decided from the metadata the SAME statement writes.++ ``_merge_owed_failure_notice`` applies ``extra_metadata`` before+ ``_owed_failure_notice_for_transition`` reads it, which is what makes the marker+ visible to the notice decision. The regression half is the second run: without the+ kwarg the identical failure still owes its notice, so this cannot silence anything+ it was not asked to.+ """++ _command_task_env(tmp_path, monkeypatch)+ requests = TaskExecutionStore()+ assert requests.sqlite_backend is not None++ escalated = requests.enqueue_hook_send(session_key="slack::channel::C123", prompt="hi")+ claimed = requests.claim(escalated.id)+ assert claimed is not None+ requests.complete(claimed, ok=False, error="boom", escalation_run_id="esc-9")++ row = requests.get_run(escalated.id)+ assert row is not None and row["status"] == "failed"+ assert row["metadata"].get("escalation_run_id") == "esc-9", (+ f"the marker never reached the run row: {row['metadata']!r}"+ )+ assert requests.sqlite_backend.owed_failure_notice(escalated.id) is None, (+ "an escalated failure stamped a notice as well"+ )++ plain = requests.enqueue_hook_send(session_key="slack::channel::C123", prompt="hi")+ plain_claimed = requests.claim(plain.id)+ assert plain_claimed is not None+ requests.complete(plain_claimed, ok=False, error="boom")++ notice = requests.sqlite_backend.owed_failure_notice(plain.id)+ assert notice is not None and notice.get("state"), (+ "the suppression leaked to ordinary failures; every failed run would go silent"+ )diff --git a/tests/test_watches.py b/tests/test_watches.pyindex f32a7564f..87e3b5eb3 100644--- a/tests/test_watches.py+++ b/tests/test_watches.py@@ -2952,6 +2952,73 @@ _WATCH_FIXTURE_PAYLOAD = {}+def test_a_hook_queued_after_a_rename_names_an_agent_that_still_exists(tmp_path: Path) -> None:+ """The watch half of SCT-030 -- the completion hook must be claimable.++ ``_hook_request`` composes the hook from ``watch.agent_name`` when the cycle ends,+ and the row becomes durable inside the stamp's transaction. A rename committed+ between those two moments rewrites the definition and every ACTIVE run, but not a+ row still being composed, so the hook was inserted naming an Agent the catalog no+ longer had -- and the user is never told the watch finished, which for a ``once``+ watch is the only report it ever produces.++ The mirror reload is forced because ``PRAGMA data_version`` is timing-dependent; a+ rename the mirror has NOT absorbed is refused by the compare-and-set instead, which+ needs no fix.+ """++ from core.vibe_agents import VibeAgentStore++ store = ManagedWatchStore()+ assert store._sqlite is not None, "the shared transaction this covers lives in SQLite"+ request_store = TaskExecutionStore()+ assert request_store._sqlite is not None++ agent_store = VibeAgentStore(paths.get_sqlite_state_path())+ try:+ # A user Agent: a built-in one cannot be renamed at all.+ agent_store.create(name="ops", backend="claude")+ finally:+ agent_store.close()++ watch = store.add_watch(**{**_WATCH_FIXTURE_PAYLOAD, "agent_name": "ops"})+ hook = request_store.build_hook_send(+ session_key=watch.session_key,+ prompt="the watch finished",+ agent_name=watch.agent_name,+ run_type="watch",+ definition_id=watch.id,+ source_kind="watch",+ )++ agent_store = VibeAgentStore(paths.get_sqlite_state_path())+ try:+ renamed = agent_store.rename("ops", "night-shift")+ finally:+ agent_store.close()+ store.load()+ assert store.get_watch(watch.id).agent_name == "night-shift"++ assert store.mark_cycle_result(+ watch.id,+ exit_code=0,+ error=None,+ event_detected=True,+ disable=True,+ queued_run=hook.to_dict(),+ ) is True++ rows = [row for row in request_store._sqlite.list_runs() if row["id"] == hook.id]+ assert len(rows) == 1, f"the hook did not become durable: {rows!r}"+ assert rows[0]["agent_name"] == "night-shift", (+ "the hook was queued against the pre-rename name, which resolves to no Agent "+ f"at claim time: {rows[0]['agent_name']!r}"+ )+ assert rows[0]["agent_id"] == renamed.id, (+ f"the hook was not pinned to the Agent's durable identity: {rows[0]['agent_id']!r}"+ )++@pytest.mark.parametrize("writer", list(_MIRROR_WRITERS))def test_a_definition_write_that_raises_leaves_no_live_mirror_ahead_of_the_database(tmp_path: Path, writer: strdiff --git a/ui/src/components/workbench/AgentGraphTriggerDetail.tsx b/ui/src/components/workbench/AgentGraphTriggerDetail.tsxindex c4be5ffba..222eb8cf1 100644--- a/ui/src/components/workbench/AgentGraphTriggerDetail.tsx+++ b/ui/src/components/workbench/AgentGraphTriggerDetail.tsx@@ -20,6 +20,7 @@ import {statusMeta,triggerFiredSessionIds,} from '../../lib/agentGraph';+import { formatCommandLine } from './harnessLifecycle';// While a trigger detail panel is open, re-fetch its definition AND recent runs// on this cadence so a watch's runtime (running/pid) tracks WatchSupervisor's@@ -242,10 +243,7 @@ export const AgentGraphTriggerDetail: React.FC<AgentGraphTriggerDetailProps> = (// pre-load fallback.const scheduleText =task?.cron || task?.run_at || task?.schedule_type || trigger.schedule_label?.trim() || '—';- const commandText =- watch?.shell_command?.trim() ||- (Array.isArray(watch?.command) ? (watch?.command as unknown[]).join(' ') : '') ||- '—';+ const commandText = formatCommandLine(watch?.shell_command, watch?.command) || '—';const runtimeText = watch?.runtime?.running? watch.runtime.pid != null? t('agents.graph.triggerDetail.runningPid', { pid: watch.runtime.pid })diff --git a/ui/src/components/workbench/HarnessPage.test.tsx b/ui/src/components/workbench/HarnessPage.test.tsxindex cdde9e4d8..655c0dc97 100644--- a/ui/src/components/workbench/HarnessPage.test.tsx+++ b/ui/src/components/workbench/HarnessPage.test.tsx@@ -10,6 +10,7 @@ import type {ApiContextType,HarnessRun,HarnessSessionSummary,+ HarnessTask,HarnessWatch,VibeAgentBrief,} from '../../context/ApiContext';@@ -18,6 +19,8 @@ import {HealthBadge,RunDetail,RunTriggerChip,+ TaskDetail,+ TaskKindBadge,WatchDetail,} from './HarnessPage';import { agentDisplayName, loadHarnessAgentCatalog } from './harnessAgents';@@ -105,6 +108,45 @@ const watch = (overrides: Partial<HarnessWatch>): HarnessWatch => ({...overrides,});+// A scheduled task as ``/api/harness/tasks`` serves it: the raw store row, so+// ``metadata`` arrives already decoded and the command columns are+// None-preserving. Defaults describe a *message* task, which is what almost+// every stored row is; a command case overrides shell_command/command.+const task = (overrides: Partial<HarnessTask>): HarnessTask =>+ ({+ id: 'task-1',+ name: null,+ agent_name: null,+ session_policy: null,+ session_id: null,+ session_key: '',+ prompt: '',+ message: '',+ message_payload: null,+ schedule_type: 'cron',+ cron: '17 3 * * *',+ run_at: null,+ timezone: 'UTC',+ post_to: null,+ deliver_key: null,+ enabled: true,+ created_at: null,+ updated_at: null,+ last_run_at: null,+ last_run_id: null,+ last_error: null,+ lifecycle_state: 'waiting',+ lifecycle_detail: null,+ next_run_at: null,+ waiting_since: null,+ running_since: null,+ health: null,+ consecutive_failures: 0,+ recent_failures: 0,+ ...NO_SESSION,+ ...overrides,+ }) as HarnessTask;+// Translation-free stand-in: proves the mappers pick the right key without// depending on the copy.const key = (k: string) => k;@@ -392,6 +434,222 @@ describe('HealthBadge', () => {});});+describe('TaskKindBadge', () => {+ it('marks a command task, so the list distinguishes it from a message task', () => {+ const label = i18n.t('harness.taskKind.command');+ expect(label).not.toBe('harness.taskKind.command');++ const html = render(<TaskKindBadge row={task({ shell_command: 'make test' })} kind="task" />);++ expect(html).toContain(`>${label}<`);+ // Same chip anatomy as the schedule chip beside it.+ expect(html).toContain('font-mono text-[9px] uppercase');+ // The full command is one hover away even though the chip is two words.+ expect(html).toContain('title="make test"');+ });++ it('marks an argv command task too', () => {+ const html = render(<TaskKindBadge row={task({ command: ['python3', 'scripts/health.py'] })} kind="task" />);++ expect(html).toContain(`>${i18n.t('harness.taskKind.command')}<`);+ expect(html).toContain('title="python3 scripts/health.py"');+ });++ it('renders nothing for a message task', () => {+ // Silence is the signal: a chip on every one of the overwhelming majority+ // is noise, and it is what makes the command chip worth reading.+ expect(render(<TaskKindBadge row={task({ prompt: 'Summarize #ops', message: 'Summarize #ops' })} kind="task" />)).toBe('');+ expect(render(<TaskKindBadge row={task({ command: [] })} kind="task" />)).toBe('');+ });++ it('renders nothing for a watch, which always runs a command', () => {+ expect(render(<TaskKindBadge row={watch({ shell_command: 'wait_pr.py 1140' })} kind="watch" />)).toBe('');+ });+});++describe('TaskDetail command task', () => {+ const commandTask = task({+ shell_command: 'pg_dump mydb | gzip > /backups/db.gz',+ session_id: null,+ last_exit_code: 7,+ timeout_seconds: 900,+ metadata: { on_failure: 'agent' },+ });+ const detail = (value: HarnessTask) =>+ render(<TaskDetail task={value} onToggleEnabled={() => undefined} pending={false} />);++ it('shows the command, the failure policy, the timeout and the last exit code', () => {+ const html = detail(commandTask);++ expect(html).toContain(`>${i18n.t('harness.detail.command')}<`);+ expect(html).toContain('pg_dump mydb | gzip > /backups/db.gz');+ expect(html).toContain(`>${i18n.t('harness.detail.onFailure')}<`);+ expect(html).toContain(`>${i18n.t('harness.onFailure.agent')}<`);+ expect(html).toContain(`>${i18n.t('harness.detail.timeout')}<`);+ expect(html).toContain('900s');+ expect(html).toContain(`>${i18n.t('harness.detail.lastExitCode')}<`);+ expect(html).toContain('>7<');+ });++ it('names the command in the header, instead of the word "Scheduled task"', () => {+ // A command task has no name and no message to fall back to, so the+ // existing title chain landed on the kind label and every unnamed command+ // task in the list read as "Scheduled task".+ const html = detail(commandTask);++ expect(html).toContain('title="pg_dump mydb | gzip > /backups/db.gz"');+ expect(html).not.toContain(`>${i18n.t('harness.kind.task')}<`);+ });++ it('renders a command task with no session without a broken chat link', () => {+ // ``--on-failure none`` stores no session at all. DetailSession already+ // owns the four session states, so this must say so rather than link to+ // /chat/null.+ const html = detail(commandTask);++ expect(html).toContain(i18n.t('harness.detail.sessionNone'));+ expect(html).not.toContain('/chat/');+ });++ it('drops the Agent routing a pure command task deliberately has none of', () => {+ // SCT-043. The label helpers resolve a null to a concrete answer, so a+ // command created with the CLI's default ``--on-failure none`` — no Agent,+ // no session, no delivery — was described as routing through an "Inherited+ // default" Agent with an "Existing" session policy delivering to "Session".+ // Every one of those was invented, and the on-failure field right below+ // already states that no Agent is involved.+ const html = detail(task({ shell_command: 'make test' }));++ expect(html).not.toContain(`>${i18n.t('harness.detail.agent')}<`);+ expect(html).not.toContain(i18n.t('harness.detail.agentInherit'));+ expect(html).not.toContain(`>${i18n.t('harness.detail.sessionPolicy')}<`);+ expect(html).not.toContain(`>${i18n.t('harness.detail.delivery')}<`);+ expect(html).toContain(`>${i18n.t('harness.onFailure.none')}<`);+ });++ it('keeps the routing fields wherever there is something to route', () => {+ // Not gated on the KIND: an escalation turn is routed by exactly these+ // fields, and a command bound to a conversation delivers its failure notice+ // there, so hiding them for every command would drop real answers.+ const escalates = detail(task({ shell_command: 'make test', metadata: { on_failure: 'agent' } }));+ expect(escalates).toContain(`>${i18n.t('harness.detail.agent')}<`);+ expect(escalates).toContain(`>${i18n.t('harness.detail.delivery')}<`);++ const bound = detail(task({ shell_command: 'make test', session_key: 'slack::channel::C123', post_to: 'thread' }));+ expect(bound).toContain(`>${i18n.t('harness.detail.delivery')}<`);+ expect(bound).toContain(`>${i18n.t('harness.delivery.thread')}<`);++ const pinned = detail(task({ shell_command: 'make test', agent_name: 'claude' }));+ expect(pinned).toContain(`>${i18n.t('harness.detail.agent')}<`);++ // And a message task is untouched: its null agent really is the inherited one.+ const message = detail(task({ prompt: 'Summarize #ops', message: 'Summarize #ops' }));+ expect(message).toContain(`>${i18n.t('harness.detail.agent')}<`);+ expect(message).toContain(i18n.t('harness.detail.agentInherit'));+ expect(message).toContain(`>${i18n.t('harness.detail.sessionPolicy')}<`);+ });++ it('drops the Message field a command task has nothing to put in', () => {+ const html = detail(commandTask);++ expect(html).not.toContain(`>${i18n.t('harness.detail.message')}<`);+ });++ it('keeps the Message field for a command task that escalates with one', () => {+ const html = detail(task({ shell_command: 'make test', message: 'Tests failed, investigate' }));++ expect(html).toContain(`>${i18n.t('harness.detail.message')}<`);+ expect(html).toContain('Tests failed, investigate');+ });++ it('says "no timeout" rather than "0s", which would read as an instant kill', () => {+ const html = detail(task({ shell_command: 'make test', timeout_seconds: 0 }));++ expect(html).toContain(i18n.t('harness.detail.timeoutNone'));+ expect(html).not.toContain('0s');+ });++ it('states the quiet default when no failure policy is stored', () => {+ const html = detail(task({ shell_command: 'make test' }));++ expect(html).toContain(`>${i18n.t('harness.onFailure.none')}<`);+ });++ it('states the timeout that actually applies when the row stores none', () => {+ // SCT-018. A null ``timeout_seconds`` is not "unlimited" and not "unknown": the+ // executor applies COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS, so a six-hour limit is+ // in force. Hiding the field left the pane silent about the one number that+ // decides whether a long backup is killed mid-run, right next to a policy field+ // that DOES state its default — so the omission read as "no limit".+ const html = detail(task({ shell_command: 'make test' }));++ expect(html).toContain(`>${i18n.t('harness.detail.timeout')}<`);+ expect(html).toContain(i18n.t('harness.detail.timeoutDefault', { duration: '6h' }));+ expect(html).not.toContain(i18n.t('harness.detail.timeoutNone'));++ // A stored limit is the user's own number, and carries no default marker.+ const stored = detail(task({ shell_command: 'make test', timeout_seconds: 900 }));+ expect(stored).toContain('900s');+ expect(stored).not.toContain(i18n.t('harness.detail.timeoutDefault', { duration: '6h' }));+ });++ it('colours a zero exit code as neutral and a non-zero one as a failure', () => {+ expect(detail(task({ shell_command: 'make test', last_exit_code: 0 }))).toContain(+ '<span class="font-mono text-[11px] text-muted">0</span>',+ );+ expect(detail(task({ shell_command: 'make test', last_exit_code: 1 }))).toContain(+ '<span class="font-mono text-[11px] text-pink">1</span>',+ );+ });++ it('leaves a message task rendering exactly as it does today', () => {+ const html = detail(task({ name: 'Nightly digest', prompt: 'Summarize #ops', message: 'Summarize #ops' }));++ expect(html).toContain(`>${i18n.t('harness.detail.message')}<`);+ expect(html).toContain('Summarize #ops');+ // None of the command-only fields appear.+ for (const label of ['harness.detail.command', 'harness.detail.onFailure', 'harness.detail.timeout', 'harness.detail.lastExitCode']) {+ expect(html).not.toContain(`>${i18n.t(label)}<`);+ }+ expect(html).not.toContain(i18n.t('harness.taskKind.command'));+ });+});++describe('RunDetail command run', () => {+ it('renders a command run with no session, and keeps its exit code visible', () => {+ // A command run keeps ``run_type: "scheduled"`` and carries exit_code /+ // stdout / stderr with ``session_id: null`` — nothing on this pane may+ // assume every run has a session.+ const html = render(+ <RunDetail+ run={run({+ run_type: 'scheduled',+ status: 'failed',+ session_id: null,+ exit_code: 7,+ stdout: 'dumping mydb',+ stderr: 'pg_dump: connection refused',+ definition_name: 'Nightly backup',+ definition_kind: 'task',+ definition_id: 'def-9',+ metadata: { command: { shell: null, argv: ['pg_dump', 'my db'] } },+ })}+ />,+ );++ expect(html).toContain(i18n.t('harness.detail.sessionNone'));+ expect(html).not.toContain('href="/chat/');+ expect(html).toContain('exit_code 7');+ expect(html).toContain('pg_dump: connection refused');+ // Command runs reuse the existing scheduled run-type label; no new key.+ expect(html).toContain(i18n.t('harness.runType.scheduled'));+ // SCT-019: what ran comes off the RUN's own snapshot, shell-joined, so a+ // definition edited or deleted after the fire cannot rewrite this pane's answer.+ expect(html).toContain(`>${i18n.t('harness.detail.command')}<`);+ expect(html).toContain("pg_dump 'my db'");+ });+});+describe('WatchDetail runtime', () => {it.each([[diff --git a/ui/src/components/workbench/HarnessPage.tsx b/ui/src/components/workbench/HarnessPage.tsxindex ce514321c..ff026def3 100644--- a/ui/src/components/workbench/HarnessPage.tsx+++ b/ui/src/components/workbench/HarnessPage.tsx@@ -68,11 +68,17 @@ import {definitionRowTitle,definitionStatusCount,definitionSurvivesToggle,+ formatCommandLine,formatWallTime,humanizeCron,humanizeTime,isWallClockTimestamp,lifecycleLabel,+ runCommandSnapshotLine,+ taskCommandPreview,+ taskIsCommand,+ taskOnFailure,+ taskTimeout,waiterExpectedAlive,} from './harnessLifecycle';import type {@@ -104,6 +110,23 @@ function formatSchedule(task: HarnessTask, t: (k: string, opts?: any) => string)return task.schedule_type || t('harness.unknownSchedule');}+// The limit a command definition's next fire runs under, in one phrase. Three+// distinct states, and none of them may be rendered as another: a stored positive+// value is the user's own number, a stored 0 is no limit at all, and no stored value+// means the executor's default applies — which is a real limit, so it is named and+// marked as the default rather than left out.+function formatTimeout(+ task: HarnessTask,+ t: (k: string, opts?: Record<string, unknown>) => string,+): string {+ const { seconds, isDefault } = taskTimeout(task);+ if (seconds <= 0) return t('harness.detail.timeoutNone');+ if (isDefault) {+ return t('harness.detail.timeoutDefault', { duration: formatElapsed(seconds, t) });+ }+ return t('harness.detail.timeoutSeconds', { seconds });+}+// Status segments per tab. Definitions filter by what they are doing; runs by// execution outcome. One control renders whichever set the tab needs.const RUN_STATUS_FILTERS = ['all', 'queued', 'running', 'succeeded', 'failed', 'canceled'] as const;@@ -1028,6 +1051,30 @@ export const HealthBadge: React.FC<{ row: HarnessTask | HarnessWatch }> = ({ row);};+// What a task *does*, when that is not the default. A command task runs a+// subprocess instead of prompting an Agent, and nothing else on the row says so:+// the schedule chip, the state dot and the second line read identically for both+// kinds, so an operator scanning the list had no way to tell a shell task from a+// message task without opening it.+//+// A message task gets no chip — the same philosophy as ``HealthBadge``'s+// ``healthy``: the overwhelming majority are message tasks, a chip on every one+// of them is noise, and the silence is what makes this chip worth reading.+// Watches are excluded outright: every watch runs a command, so the chip would+// say nothing there (their ``kind`` chip already reads once/continuous).+export const TaskKindBadge: React.FC<{ row: HarnessTask | HarnessWatch; kind: HarnessDefinitionKind }> = ({+ row,+ kind,+}) => {+ const { t } = useTranslation();+ if (kind !== 'task' || !taskIsCommand(row)) return null;+ return (+ <Badge variant="secondary" className="shrink-0 font-mono text-[9px] uppercase" title={taskCommandPreview(row)}>+ {t('harness.taskKind.command')}+ </Badge>+ );+};+interface DefinitionRowProps {row: HarnessTask | HarnessWatch;kind: HarnessDefinitionKind;@@ -1050,7 +1097,16 @@ const DefinitionRow: React.FC<DefinitionRowProps> = ({onDelete,}) => {const { t } = useTranslation();- const title = definitionRowTitle(row, t(`harness.kind.${kind}`));+ // A command task has no name and no message to fall back to — its ``prompt``+ // is empty by construction — so the existing chain landed on the kind label+ // and every unnamed command task in the list rendered as the word "Task".+ // The command is what identifies it, exactly as ``_watch_display_name`` uses+ // it for a watch; it goes in the last slot of the same chain rather than+ // ahead of the user's own name.+ const title = definitionRowTitle(+ row,+ kind === 'task' && taskIsCommand(row) ? taskCommandPreview(row) : t(`harness.kind.${kind}`),+ );const chip = definitionChipLabel(row, kind, t);const line = definitionRowLine(row, kind, t, now);return (@@ -1072,6 +1128,7 @@ const DefinitionRow: React.FC<DefinitionRowProps> = ({<span className="truncate text-[14px] font-semibold text-foreground" title={title}>{title}</span>+ <TaskKindBadge row={row} kind={kind} />{chip && (<Badge variant="secondary" className="shrink-0 font-mono text-[9px] uppercase">{chip}@@ -1159,9 +1216,19 @@ interface TaskDetailProps {pending: boolean;}-const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, pending }) => {+export const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, pending }) => {const { t } = useTranslation();- const title = definitionRowTitle(task, t('harness.kind.task'));+ const isCommand = taskIsCommand(task);+ const commandPreview = isCommand ? taskCommandPreview(task) : '';+ const routesSomewhere =+ !isCommand ||+ taskOnFailure(task) === 'agent' ||+ Boolean(task.agent_name) ||+ Boolean(task.session_id) ||+ Boolean(task.session_key) ||+ Boolean(task.post_to) ||+ Boolean(task.deliver_key);+ const title = definitionRowTitle(task, isCommand ? commandPreview : t('harness.kind.task'));return (<div className="flex min-w-0 flex-col gap-4"><div className="flex min-w-0 items-center gap-2">@@ -1177,6 +1244,16 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, pdisabled={pending}/></div>+ {/* Same anatomy and position as ``WatchDetail``'s command field — the two+ run a subprocess the same way, so they read the same way. The preview+ truncates for the header; this is the copyable full text. */}+ {isCommand && (+ <DetailField label={t('harness.detail.command')}>+ <pre className="max-h-32 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">+ {formatCommandLine(task.shell_command, task.command) || '—'}+ </pre>+ </DetailField>+ )}{/* The row humanizes the schedule; this is where the literal lives, soan operator can still read and copy the exact expression. */}<DetailField label={t('harness.detail.schedule')}>@@ -1194,30 +1271,83 @@ const TaskDetail: React.FC<TaskDetailProps> = ({ task, agent, onToggleEnabled, p</span></DetailField>)}- <DetailField label={t('harness.detail.agent')}>- <DetailAgent agentName={task.agent_name} agent={agent} />- </DetailField>- <DetailField label={t('harness.detail.session')}>- <DetailSession summary={task} sessionId={task.session_id} />- </DetailField>- <div className="grid grid-cols-2 gap-4">- <DetailField label={t('harness.detail.sessionPolicy')}>- <span className="text-[12px] text-foreground">{sessionPolicyLabel(task.session_policy, t)}</span>- </DetailField>- <DetailField label={t('harness.detail.delivery')}>- <span className="text-[12px] text-foreground">{deliveryLabel(task.post_to, t)}</span>+ {/* Routing, and only where there is something to route. These three label+ helpers all resolve a null to a CONCRETE answer — "Inherited default",+ "Existing", "Session" — which is right for a message task, whose null+ agent really is the inherited default. A command created with the CLI's+ default ``--on-failure none`` is bound to nothing at all, so the same+ rendering told the user it routes through an Agent it deliberately does+ not have. Shown as soon as anything here is real: an escalation turn+ (``--on-failure agent``), a pinned Agent, or a conversation a failure+ notice is delivered to. */}+ {routesSomewhere && (+ <>+ <DetailField label={t('harness.detail.agent')}>+ <DetailAgent agentName={task.agent_name} agent={agent} />+ </DetailField>+ <DetailField label={t('harness.detail.session')}>+ <DetailSession summary={task} sessionId={task.session_id} />+ </DetailField>+ <div className="grid grid-cols-2 gap-4">+ <DetailField label={t('harness.detail.sessionPolicy')}>+ <span className="text-[12px] text-foreground">{sessionPolicyLabel(task.session_policy, t)}</span>+ </DetailField>+ <DetailField label={t('harness.detail.delivery')}>+ <span className="text-[12px] text-foreground">{deliveryLabel(task.post_to, t)}</span>+ </DetailField>+ </div>+ </>+ )}+ {/* A command task's ``prompt`` is empty by construction, so this field+ would render a bare em-dash under the heading "Message" — a promise of+ a message the task does not have. A command task that *also* carries+ one (``--on-failure agent``) still shows it. */}+ {(!isCommand || task.message || task.prompt) && (+ <DetailField label={t('harness.detail.message')}>+ <pre className="max-h-44 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">+ {task.message || task.prompt || '—'}+ </pre></DetailField>- </div>- <DetailField label={t('harness.detail.message')}>- <pre className="max-h-44 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">- {task.message || task.prompt || '—'}- </pre>- </DetailField>+ )}+ {/* What a failed run does, and how long it is allowed to take. Both are+ command-task-only policy, and both are unanswerable from anything else+ on this pane — "no Agent" is a deliberate configuration, not an+ omission, so it is stated rather than left blank. */}+ {isCommand && (+ <div className="grid grid-cols-2 gap-4">+ <DetailField label={t('harness.detail.onFailure')}>+ <span className="text-[12px] text-foreground">{t(`harness.onFailure.${taskOnFailure(task)}`)}</span>+ </DetailField>+ <DetailField label={t('harness.detail.timeout')}>+ {/* Always rendered, because a limit is always in force: a row with no+ stored timeout is run under the six-hour default, and hiding the+ field read as "no limit". A stored 0 IS "no limit" server-side, and+ printing "0s" would read as an instant kill — the opposite. The+ default is shown in duration words ("6h") because it is a policy+ constant nobody typed; a stored value is echoed in the seconds the+ user actually set. */}+ <span className="font-mono text-[11px] text-muted">{formatTimeout(task, t)}</span>+ </DetailField>+ </div>+ )}{task.last_run_at && (<DetailField label={t('harness.detail.lastRun')}><span className="font-mono text-[11px] text-muted">{formatLocalDateTime(task.last_run_at)}</span></DetailField>)}+ {/* The verdict of the last command run, on the definition rather than only+ on the run row: a nightly command task's exit code is the one fact an+ operator wants without paging through the runs tab. Not gated on+ ``last_run_at`` — a stored exit code proves a run happened. */}+ {task.last_exit_code != null && (+ <DetailField label={t('harness.detail.lastExitCode')}>+ <span+ className={clsx('font-mono text-[11px]', task.last_exit_code === 0 ? 'text-muted' : 'text-pink')}+ >+ {task.last_exit_code}+ </span>+ </DetailField>+ )}{/* Its own field, and no longer nested inside ``last_run_at``: a task cancarry a ``last_error`` with no ``last_run_at`` (a fire that failed beforeit ever ran), and that case rendered nothing at all. ``harness.detail.lastError``@@ -1303,7 +1433,7 @@ interface WatchDetailProps {export const WatchDetail: React.FC<WatchDetailProps> = ({ watch, agent, onToggleEnabled, pending }) => {const { t } = useTranslation();- const cmd = watch.shell_command || (Array.isArray(watch.command) ? watch.command.join(' ') : '') || '—';+ const cmd = formatCommandLine(watch.shell_command, watch.command) || '—';const title = definitionRowTitle(watch, t('harness.kind.watch'));const showRuntime =watch.process_alive === true || (watch.process_alive === false && waiterExpectedAlive(watch));@@ -1552,6 +1682,7 @@ export const RunDetail: React.FC<RunDetailProps> = ({ run, agent }) => {const { t } = useTranslation();const typeLabel = runTypeLabel(run.run_type || run.request_type, t);const title = runRowTitle(run, typeLabel);+ const runCommandLine = runCommandSnapshotLine(run);return (<div className="flex flex-col gap-4"><div className="flex items-start gap-2">@@ -1656,6 +1787,16 @@ export const RunDetail: React.FC<RunDetailProps> = ({ run, agent }) => {)}</DetailField>)}+ {/* What this run actually executed, read off the run's own snapshot. The+ definition it came from is editable and deletable, so it cannot answer for a+ past execution — only the run can. */}+ {runCommandLine && (+ <DetailField label={t('harness.detail.command')}>+ <pre className="max-h-32 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">+ {runCommandLine}+ </pre>+ </DetailField>+ )}{(run.message || run.prompt) && (<DetailField label={t('harness.detail.message')}><pre className="max-h-32 overflow-auto whitespace-pre-wrap rounded-md border border-border bg-surface-3 p-2 font-mono text-[11px] text-foreground">diff --git a/ui/src/components/workbench/harnessLifecycle.test.ts b/ui/src/components/workbench/harnessLifecycle.test.tsindex 62bec5246..b5e00b9f1 100644--- a/ui/src/components/workbench/harnessLifecycle.test.ts+++ b/ui/src/components/workbench/harnessLifecycle.test.ts@@ -20,6 +20,12 @@ import {isWallClockTimestamp,LIFECYCLE_DETAILS,lifecycleLabel,+ TASK_ON_FAILURE_VALUES,+ COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS,+ taskCommandPreview,+ taskIsCommand,+ taskOnFailure,+ taskTimeout,} from './harnessLifecycle';// Translation-free stand-in: proves a mapper picked the right key without@@ -362,6 +368,129 @@ describe('definitionRowTitle', () => {});});+describe('taskIsCommand', () => {+ it('recognises both shapes a command can arrive in', () => {+ expect(taskIsCommand({ shell_command: 'pg_dump mydb | gzip > /backups/db.gz' })).toBe(true);+ expect(taskIsCommand({ command: ['python3', 'scripts/health.py'] })).toBe(true);+ });++ it('is false for a message task, which carries neither', () => {+ expect(taskIsCommand({})).toBe(false);+ expect(taskIsCommand({ shell_command: null, command: null, prompt: 'Summarize #ops' })).toBe(false);+ });++ it('does not read an empty argv list as a command', () => {+ // The watches table populates ``command_json`` with ``[]`` for rows that+ // have none, and the tasks table does the same — an empty list is the+ // absence of a command, not a command that runs nothing.+ expect(taskIsCommand({ command: [] })).toBe(false);+ expect(taskIsCommand({ command: [], shell_command: '' })).toBe(false);+ });++ it('does not read a whitespace-only shell command as a command', () => {+ expect(taskIsCommand({ shell_command: ' \n' })).toBe(false);+ });+});++describe('taskCommandPreview', () => {+ it('prefers the shell command verbatim', () => {+ expect(taskCommandPreview({ shell_command: 'make test', command: ['ignored'] })).toBe('make test');+ });++ it('joins an argv list with spaces', () => {+ expect(taskCommandPreview({ command: ['python3', '-m', 'pytest', '-q'] })).toBe('python3 -m pytest -q');+ });++ it('quotes an argv part that would otherwise lose its boundary', () => {+ // SCT-016. Mirrors the backend's ``shlex.join``, which is what the CLI list and+ // the failure notice show for the same row. A plain space join renders+ // ``['bash', '-lc', 'echo hi there']`` as ``bash -lc echo hi there`` — a+ // DIFFERENT command, and the one the user would copy out of this pane to+ // reproduce a failure. Ordinary parts stay unquoted so the common case reads+ // like a command and not like an escape exercise.+ expect(taskCommandPreview({ command: ['bash', '-lc', 'echo hi there'] })).toBe(+ "bash -lc 'echo hi there'",+ );+ expect(taskCommandPreview({ command: ['grep', "it's", '/var/log/app.log'] })).toBe(+ "grep 'it'\"'\"'s' /var/log/app.log",+ );+ expect(taskCommandPreview({ command: ['./run.sh', ''] })).toBe("./run.sh ''");+ expect(taskCommandPreview({ command: ['a;rm -rf /'] })).toBe("'a;rm -rf /'");+ });++ it('trims, and returns empty for a row with no command at all', () => {+ expect(taskCommandPreview({ shell_command: ' make test \n' })).toBe('make test');+ expect(taskCommandPreview({})).toBe('');+ });++ it('ellipsizes rather than hard-slicing, so the reader sees text was dropped', () => {+ // Mirrors the CLI's ``_watch_command_preview``: cut to maxChars-1 then '…',+ // so the result is never longer than the budget.+ const long = 'x'.repeat(400);+ const preview = taskCommandPreview({ shell_command: long });+ expect(preview).toHaveLength(120);+ expect(preview.endsWith('…')).toBe(true);+ expect(preview.startsWith('x'.repeat(119))).toBe(true);+ });++ it('keeps a command that exactly fills the budget intact', () => {+ const exact = 'y'.repeat(120);+ expect(taskCommandPreview({ shell_command: exact })).toBe(exact);+ expect(taskCommandPreview({ shell_command: 'ok' }, 2)).toBe('ok');+ });++ it('honours a caller-supplied budget', () => {+ expect(taskCommandPreview({ shell_command: 'make test' }, 6)).toBe('make…');+ });+});++describe('taskTimeout', () => {+ it('separates a stored limit from the default a null row actually runs under', () => {+ expect(taskTimeout({ timeout_seconds: 900 })).toEqual({ seconds: 900, isDefault: false });+ // A stored 0 is "no limit" server-side, not "unset" — it must not be overwritten+ // by the default.+ expect(taskTimeout({ timeout_seconds: 0 })).toEqual({ seconds: 0, isDefault: false });+ // MIRROR of ``COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS``. If the backend constant+ // changes and this does not, the pane names a limit nobody enforces.+ expect(COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS).toBe(6 * 3600);+ for (const row of [{}, { timeout_seconds: null }]) {+ expect(taskTimeout(row)).toEqual({+ seconds: COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS,+ isDefault: true,+ });+ }+ });+});++describe('taskOnFailure', () => {+ it('reads the policy out of decoded metadata', () => {+ // Key is ``metadata`` on the API row, already decoded — not ``metadata_json``.+ expect(taskOnFailure({ metadata: { on_failure: 'agent' } })).toBe('agent');+ expect(taskOnFailure({ metadata: { on_failure: 'none' } })).toBe('none');+ expect(taskOnFailure({ metadata: { on_failure: ' AGENT ' } })).toBe('agent');+ });++ it('treats absence as the quiet default', () => {+ expect(taskOnFailure({})).toBe('none');+ expect(taskOnFailure({ metadata: null })).toBe('none');+ expect(taskOnFailure({ metadata: {} })).toBe('none');+ });++ it('never invents an Agent escalation from metadata it cannot read', () => {+ // Falling the other way would promise an Agent turn nobody configured.+ expect(taskOnFailure({ metadata: { on_failure: 42 } as unknown as Record<string, unknown> })).toBe('none');+ expect(taskOnFailure({ metadata: { on_failure: '' } })).toBe('none');+ expect(taskOnFailure({ metadata: { on_failure: 'escalate' } })).toBe('none');+ expect(taskOnFailure({ metadata: 'not-an-object' as unknown as Record<string, unknown> })).toBe('none');+ });++ it('has real copy behind every policy it can name, in both languages', () => {+ expectCopy('harness.onFailure', TASK_ON_FAILURE_VALUES);+ expectCopy('harness.taskKind', ['command']);+ expectCopy('harness.detail', ['command', 'onFailure', 'timeout', 'timeoutSeconds', 'timeoutNone', 'lastExitCode']);+ });+});+describe('definitionActivityAt', () => {it('walks the fallback chain instead of gating on one nullable field', () => {expect(definitionActivityAt({ waiting_since: 'a', last_event_at: 'b', updated_at: 'z' })).toBe('a');diff --git a/ui/src/components/workbench/harnessLifecycle.ts b/ui/src/components/workbench/harnessLifecycle.tsindex eb8e933f0..d906586c6 100644--- a/ui/src/components/workbench/harnessLifecycle.ts+++ b/ui/src/components/workbench/harnessLifecycle.ts@@ -330,6 +330,19 @@ export type HarnessDefinitionFacts = {health?: HarnessDefinitionHealth | string | null;consecutive_failures?: number | null;recent_failures?: number | null;+ // Command-task fields (also present on a watch, which has always run a+ // command). ``/api/harness/tasks`` serves the raw store row, so these arrive+ // exactly as ``_scheduled_task_from_row`` writes them: ``shell_command`` as a+ // string, ``command`` decoded from ``command_json``, and both None-preserving —+ // which is why every helper below tests for presence rather than truthiness of+ // a joined string.+ shell_command?: string | null;+ command?: unknown[] | null;+ timeout_seconds?: number | null;+ last_exit_code?: number | null;+ // Decoded server-side (key is ``metadata``, not ``metadata_json``). Holds the+ // command-task-only ``on_failure`` policy; see ``taskOnFailure``.+ metadata?: Record<string, unknown> | null;};// ``failing`` = the newest verdict failed; ``degraded`` = the newest succeeded but@@ -367,6 +380,109 @@ export function definitionRowTitle(return kindLabel;}+// ---------------------------------------------------------------------------+// Command tasks+// ---------------------------------------------------------------------------++// Whether this scheduled definition runs a subprocess instead of prompting an+// Agent. MIRROR of ``ScheduledTask.has_command`` in ``core/scheduled_tasks.py``:+// a non-empty ``shell_command`` or a non-empty argv list, nothing else. An empty+// argv list is not a command — the column is populated with ``[]`` by rows that+// have none.+export function taskIsCommand(row: HarnessDefinitionFacts): boolean {+ if (typeof row.shell_command === 'string' && row.shell_command.trim()) return true;+ return Array.isArray(row.command) && row.command.length > 0;+}++// Exactly Python's ``shlex._find_unsafe`` complement: a part made only of these+// characters survives a shell unquoted, so quoting it would be noise.+const SHELL_SAFE_PART = /^[\w@%+=:,./-]+$/;++// One argv part as a shell would need it written. MIRROR of ``shlex.quote``,+// including its single-quote escape (``'"'"'``), because the same row's command is+// rendered by ``shlex.join`` in ``vibe task list`` and in a failure notice, and the+// two must not disagree about what the command is.+function shellQuotePart(value: string): string {+ if (value === '') return "''";+ if (SHELL_SAFE_PART.test(value)) return value;+ return `'${value.replace(/'/g, `'"'"'`)}'`;+}++// An argv list as ONE readable line. Boundaries are preserved by quoting, never+// implied by spaces: ``['bash', '-lc', 'echo hi there']`` joined bare reads as five+// arguments, so every surface that showed it was showing a command the definition+// does not run — and the pane it is shown in is the one a user copies from when a+// fire fails.+export function formatCommandLine(shellCommand: unknown, argv: unknown): string {+ if (typeof shellCommand === 'string' && shellCommand.trim()) return shellCommand;+ if (!Array.isArray(argv)) return '';+ return argv.map((part) => shellQuotePart(String(part))).join(' ');+}++// What a command run RECORDED that it executed, from the snapshot the fire wrote onto+// its own metadata (``COMMAND_SNAPSHOT_METADATA_KEY`` in ``core/scheduled_tasks.py``).+// Empty for an Agent run, and for a command run written before the snapshot existed —+// there is nothing trustworthy to show for those, and the definition cannot stand in:+// it is editable and deletable, so it answers about the command configured NOW.+export function runCommandSnapshotLine(run: { metadata?: unknown } | null | undefined): string {+ const metadata = run?.metadata;+ if (!metadata || typeof metadata !== 'object') return '';+ const snapshot = (metadata as Record<string, unknown>).command;+ if (!snapshot || typeof snapshot !== 'object') return '';+ const { shell, argv } = snapshot as { shell?: unknown; argv?: unknown };+ return formatCommandLine(shell, argv);+}++// The command in one line, for a row title or a chip. Mirrors the CLI's+// ``_watch_command_preview``: ``shell_command`` verbatim when present, else the+// argv shell-joined, trimmed, and cut with an ellipsis rather than a hard+// slice so the reader can see that something was dropped. The full text always+// stays available (detail pane, ``title`` attribute) — this is the scannable form.+export function taskCommandPreview(row: HarnessDefinitionFacts, maxChars = 120): string {+ const preview = formatCommandLine(row.shell_command, row.command).trim();+ if (preview.length <= maxChars) return preview;+ return `${preview.slice(0, maxChars - 1).trimEnd()}…`;+}++// MIRROR of ``COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS`` in ``core/scheduled_tasks.py``:+// six hours, applied by the executor to any command definition that stores no+// timeout of its own. Keep the two in step — a client that shows a limit the+// executor does not enforce is worse than showing none.+export const COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS = 21600;++// How long a fire of this definition is actually allowed to take, and whether that+// number is the user's or the default. A null ``timeout_seconds`` is neither+// "unlimited" nor "unknown": the executor substitutes the default, so the limit is+// real and the pane owes the user the number. A stored ``0`` IS unlimited and stays+// distinguishable — the caller renders it as such rather than as "0s".+export function taskTimeout(row: HarnessDefinitionFacts): {+ seconds: number;+ isDefault: boolean;+} {+ const stored = row.timeout_seconds;+ if (typeof stored === 'number' && Number.isFinite(stored)) {+ return { seconds: stored, isDefault: false };+ }+ return { seconds: COMMAND_TASK_DEFAULT_TIMEOUT_SECONDS, isDefault: true };+}++export const TASK_ON_FAILURE_VALUES = ['none', 'agent'] as const;+export type TaskOnFailure = (typeof TASK_ON_FAILURE_VALUES)[number];++// What a failed command run does. MIRROR of ``ScheduledTask.on_failure``: the+// policy lives in ``metadata`` rather than a column, so absence, a non-object+// metadata blob, and a value this client has no word for all resolve to+// ``none`` — the quiet default. Never invent ``agent`` from a value we cannot+// read: that would promise an Agent turn nobody configured.+export function taskOnFailure(row: HarnessDefinitionFacts): TaskOnFailure {+ const metadata = row.metadata;+ if (!metadata || typeof metadata !== 'object') return 'none';+ const raw = (metadata as Record<string, unknown>).on_failure;+ if (typeof raw !== 'string') return 'none';+ const value = raw.trim().toLowerCase();+ return value === 'agent' ? 'agent' : 'none';+}+// The last moment this row is known to have done anything.//// §4.2: never gate a whole block on one nullable field. Each candidate is thediff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsxindex 6898addf6..683d0232f 100644--- a/ui/src/context/ApiContext.tsx+++ b/ui/src/context/ApiContext.tsx@@ -1300,6 +1300,20 @@ export type HarnessTask = HarnessSessionSummary & HarnessDefinitionState & {last_run_at: string | null;last_run_id: string | null;last_error: string | null;+ // Command tasks: a scheduled definition that runs a subprocess instead of+ // prompting an Agent. Non-null ``shell_command`` OR a non-empty ``command``+ // argv is what makes a row one (see ``taskIsCommand``); its ``prompt`` is+ // empty and — when ``metadata.on_failure`` is ``"none"`` — it has no session+ // at all, so nothing here may be assumed present.+ //+ // ``/api/harness/tasks`` serves the raw store row, so these are exactly the+ // keys ``_scheduled_task_from_row`` writes: ``metadata`` already decoded, not+ // ``metadata_json``.+ shell_command?: string | null;+ command?: unknown[] | null;+ timeout_seconds?: number | null;+ last_exit_code?: number | null;+ metadata?: Record<string, unknown> | null;};export type HarnessWatchRuntime = {diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 3d89b133f..541f58f0d 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -2879,7 +2879,20 @@"parentRun": "Parent run","callback": "Callback","effort": "effort {{value}}",- "waitingSince": "Waiting since"+ "waitingSince": "Waiting since",+ "onFailure": "On failure",+ "timeout": "Timeout",+ "timeoutSeconds": "{{seconds}}s",+ "timeoutNone": "No timeout",+ "timeoutDefault": "{{duration}} (default)",+ "lastExitCode": "Last exit code"+ },+ "taskKind": {+ "command": "Command"+ },+ "onFailure": {+ "none": "Notice only (no Agent)",+ "agent": "Escalate to an Agent"},"sessionPolicy": {"createPerRun": "New session each run",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 2d42e87ff..00c7e0ecd 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -2879,7 +2879,20 @@"parentRun": "父 Run","callback": "回传","effort": "推理 {{value}}",- "waitingSince": "开始等待"+ "waitingSince": "开始等待",+ "onFailure": "失败处理",+ "timeout": "超时",+ "timeoutSeconds": "{{seconds}} 秒",+ "timeoutNone": "不限时",+ "timeoutDefault": "{{duration}}(默认)",+ "lastExitCode": "最近退出码"+ },+ "taskKind": {+ "command": "命令"+ },+ "onFailure": {+ "none": "仅通知(无 Agent)",+ "agent": "升级给 Agent 处理"},"sessionPolicy": {"createPerRun": "每次运行新建会话",diff --git a/vibe/cli.py b/vibe/cli.pyindex 2c1a97e18..f03cdc23b 100644--- a/vibe/cli.py+++ b/vibe/cli.py@@ -48,6 +48,7 @@ from core.scheduled_tasks import (session_anchor_for_target,)from core.caller_context import caller_context_from_env+from core.command_runner import command_line_previewfrom core.vibe_agents import AgentArchivedEditError, AgentArchiveError, AgentNameValidationError, AgentReferenceRewriteError, VibeAgent, VibeAgentStore, iter_global_agent_files, parse_agent_file, validate_agent_backendfrom core.watches import (DEFAULT_RETRY_EXIT_CODE,@@ -125,6 +126,24 @@ WATCH_STARTUP_STABLE_RUNNING_SECONDS = 1.5WATCH_STARTUP_JITTER_BUFFER_SECONDS = 1.0+#: Commands whose trailing ``-- <command ...>`` tail is lifted out of argv BEFORE argparse+#: runs, mapped to ``(namespace attribute, first index searched for the separator)``.+#:+#: ``argparse.REMAINDER`` alone cannot carry these: it swallows everything after the first+#: non-flag token, so a legitimate option VALUE typed after the command (``-- ./sync.sh+#: --flag value``) would be eaten as part of the remainder for some orderings and dropped+#: for others. Lifting the tail here leaves the positional as a pure landing slot that+#: exists for the usage text, and keeps every flag on the command line parseable.+#:+#: The search index skips the fixed leading tokens (subcommand words plus any positional+#: id) so a definition id that happens to be ``--`` cannot be mistaken for the separator.+_POST_SEPARATOR_COMMAND_SPECS: dict[tuple[str, str], tuple[str, int]] = {+ ("watch", "update"): ("waiter_command", 3),+ ("task", "add"): ("command_argv", 2),+ ("task", "update"): ("command_argv", 3),+}++class VibeArgumentParser(argparse.ArgumentParser):def __init__(self, *args, **kwargs):self.error_help_command = kwargs.pop("error_help_command", None)@@ -133,19 +152,26 @@ class VibeArgumentParser(argparse.ArgumentParser):def parse_args(self, args=None, namespace=None):parsed_args = list(sys.argv[1:] if args is None else args)- watch_update_waiter_command = None- if self.prog == "vibe" and len(parsed_args) >= 4 and parsed_args[:2] == ["watch", "update"]:- try:- separator_index = parsed_args.index("--", 3)- except ValueError:+ lifted_attribute: str | None = None+ lifted_command: list[str] | None = None+ if self.prog == "vibe" and len(parsed_args) >= 2:+ spec = _POST_SEPARATOR_COMMAND_SPECS.get((parsed_args[0], parsed_args[1]))+ if spec is not None:+ attribute, search_from = specseparator_index = -1- if separator_index >= 0:- watch_update_waiter_command = ["--", *parsed_args[separator_index + 1 :]]- parsed_args = [*parsed_args[:separator_index]]+ if len(parsed_args) > search_from:+ try:+ separator_index = parsed_args.index("--", search_from)+ except ValueError:+ separator_index = -1+ if separator_index >= 0:+ lifted_attribute = attribute+ lifted_command = ["--", *parsed_args[separator_index + 1 :]]+ parsed_args = [*parsed_args[:separator_index]]parsed = super().parse_args(parsed_args, namespace)- if watch_update_waiter_command is not None:- setattr(parsed, "waiter_command", watch_update_waiter_command)+ if lifted_attribute is not None:+ setattr(parsed, lifted_attribute, lifted_command)return parseddef error(self, message):@@ -469,10 +495,19 @@ def _task_add_examples_text() -> str:Cron weekday digits use APScheduler semantics: 0=Mon through 6=Sun; 7 is invalid. Prefer weekday names such as mon, tue, or sun when scheduling by day of week.--timezone controls how --cron and naive --at timestamps are interpreted.+ Command tasks:+ A command task runs a subprocess on schedule with NO Agent turn, so it needs no Session, Agent, or message.+ Use --shell for a shell command string, or pass the executable and its args after '--'.+ Failure handling is silent-success by default: a successful run stays quiet, and a failed run records a failure notice.+ Add --on-failure agent with --message to spend an Agent turn triaging a failed run instead.+ --timeout bounds one run; use 0 for no timeout.+Examples:vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *' --message 'Share the hourly summary.'vibe task add --create-session --scope-id slack::channel::C123 --cron '*/5 * * * *' --message 'Tell a new joke each time.'vibe task add --create-session --scope-id slack::channel::C123 --cron '0 9 * * *' --message 'Post a visible daily summary in this scope.'+ vibe task add --name nightly-sync --cron '0 3 * * *' --shell './scripts/sync.sh'+ vibe task add --cron '0 3 * * *' --shell './scripts/sync.sh' --on-failure agent --message 'The nightly sync failed. Diagnose it.'""")@@ -489,9 +524,12 @@ def _task_update_examples_text() -> str:vibe task update 12ab34cd56ef --session-id sesk8m4q2p7xvibe task update 12ab34cd56ef --create-session --scope-id slack::channel::C123vibe task update 12ab34cd56ef --reset-delivery+ vibe task update 12ab34cd56ef --shell './scripts/sync.sh --verbose'+ vibe task update 12ab34cd56ef --timeout 900Guidance:Unspecified fields keep their existing values.+ A command task and a message task are different kinds: remove and recreate the task to move between them, or to change --on-failure.Use --reset-delivery to return to following the session target directly.Use --same-scope or --scope-id when this task should create new Sessions in a specific scope.When changing schedule fields, pass either --cron or --at.@@ -1597,8 +1635,46 @@ def _task_message_preview(message: str, *, max_chars: int = 72) -> str:return compact[: max_chars - 1].rstrip() + "…"+def _task_command_fields(task) -> tuple[Optional[str], list[str], dict]:+ """``(shell_command, command, metadata)`` from a stored row or a read projection."""++ if isinstance(task, Mapping):+ shell_command = task.get("shell_command")+ command = task.get("command") or []+ metadata = task.get("metadata")+ else:+ shell_command = task.shell_command+ command = task.command or []+ metadata = task.metadata+ return (+ str(shell_command) if shell_command else None,+ [str(item) for item in command] if isinstance(command, list) else [],+ metadata if isinstance(metadata, dict) else {},+ )+++def _task_kind(task) -> str:+ """``"command"`` when this definition runs a subprocess, else ``"message"``."""++ shell_command, command, _metadata = _task_command_fields(task)+ return "command" if (shell_command or command) else "message"+++def _task_on_failure(task) -> str:+ _shell_command, _command, metadata = _task_command_fields(task)+ value = str(metadata.get("on_failure") or "none").strip().lower()+ return value or "none"+++def _task_command_preview(task) -> str:+ shell_command, command, _metadata = _task_command_fields(task)+ return command_line_preview(shell_command, command)++def _task_display_name(task) -> str:- return task.name or _task_message_preview(task.prompt)+ # A command task stores no message, so the command itself is the only human-readable+ # label the list has; without this fallback those rows rendered with an empty name.+ return task.name or _task_message_preview(task.prompt) or _task_command_preview(task)def _task_state(task) -> str:@@ -1673,12 +1749,20 @@ def _task_payload(task, *, brief: bool = False):"last_status": _task_last_status(task),"next_run_at": _task_next_run_at(task),"schedule_summary": _task_schedule_summary(task),+ # Command-task facts. ``kind`` is what every surface branches on, and+ # ``on_failure`` is carried even for message tasks so the key never has to be+ # probed for existence.+ "kind": _task_kind(task),+ "on_failure": _task_on_failure(task),+ "command_preview": _task_command_preview(task),}if brief:return {"id": task.id,"name": task.name,"display_name": derived["display_name"],+ "kind": derived["kind"],+ "last_exit_code": task.last_exit_code,"state": derived["state"],"last_status": derived["last_status"],# ``last_error`` used to be dropped here, which left the list a user@@ -1762,18 +1846,24 @@ def _task_projection_last_status(task: Mapping[str, object]) -> str:def _task_projection_payload(task: Mapping[str, object], *, brief: bool = False) -> dict:prompt = str(task.get("prompt") or "")name = task.get("name")+ command_preview = _task_command_preview(task)derived = {- "display_name": str(name) if name else _task_message_preview(prompt),+ "display_name": str(name) if name else (_task_message_preview(prompt) or command_preview),"message_preview": _task_message_preview(prompt),"state": _task_projection_state(task),"last_status": _task_projection_last_status(task),"schedule_summary": _task_schedule_summary(task),+ "kind": _task_kind(task),+ "on_failure": _task_on_failure(task),+ "command_preview": command_preview,}if brief:payload = {"id": task.get("id"),"name": name,"display_name": derived["display_name"],+ "kind": derived["kind"],+ "last_exit_code": task.get("last_exit_code"),"state": derived["state"],"last_status": derived["last_status"],"schedule_type": task.get("schedule_type"),@@ -2669,12 +2759,51 @@ def _resolve_watch_command(args, *, help_command: str) -> tuple[list[str], Optio)-def _watch_command_preview(watch, *, max_chars: int = 120) -> str:- preview = watch.shell_command or shlex.join(watch.command)- preview = preview.strip()- if len(preview) <= max_chars:- return preview- return preview[: max_chars - 1].rstrip() + "…"+def _resolve_task_command(args, *, help_command: str) -> tuple[list[str], Optional[str], bool]:+ """Command inputs for a scheduled task, or ``([], None, False)`` for a message task.++ Same two input shapes as ``_resolve_watch_command`` — ``--shell`` XOR a trailing+ ``-- argv`` — with one deliberate difference: neither being present is NOT an+ error here, because a task may instead carry a stored message for an Agent.+ """++ raw_shell = getattr(args, "shell", None)+ shell_command = (raw_shell or "").strip()+ raw_command = list(getattr(args, "command_argv", None) or [])+ argv_present = bool(raw_command)+ if raw_command and raw_command[0] == "--":+ raw_command = raw_command[1:]++ if shell_command and raw_command:+ raise TaskCliError(+ "use either --shell or a command after '--', not both",+ code="conflicting_task_command_inputs",+ hint="Pass a shell string with --shell, or pass the executable and its args after '--'.",+ help_command=help_command,+ )+ if raw_shell is not None and not shell_command:+ raise TaskCliError(+ "--shell cannot be empty",+ code="empty_task_command",+ hint="Pass the shell command to run on schedule, for example --shell './scripts/sync.sh'.",+ help_command=help_command,+ )+ if argv_present and not raw_command:+ raise TaskCliError(+ "a command is required after '--'",+ code="empty_task_command",+ hint="Add the executable and its args after '--', or use --shell for a shell command string.",+ help_command=help_command,+ )+ if shell_command:+ return [], shell_command, True+ if raw_command:+ return raw_command, None, True+ return [], None, False+++def _watch_command_preview(watch) -> str:+ return command_line_preview(watch.shell_command, watch.command)def _watch_display_name(watch) -> str:@@ -2957,71 +3086,268 @@ def _wait_for_watch_startup()+#: Flags that only mean something for a definition that talks to an Agent Session.+#: Attribute name -> the flag as the user typed it, for the refusal message.+_TASK_SESSION_FLAG_ARGS: tuple[tuple[str, str], ...] = (+ ("session_id", "--session-id"),+ ("session_key", "--session-key"),+ ("create_session", "--create-session"),+ ("create_session_per_run", "--create-session-per-run"),+ ("same_scope", "--same-scope"),+ ("scope_id", "--scope-id"),+ ("agent", "--agent"),+ ("post_to", "--post-to"),+ ("deliver_key", "--deliver-key"),+)++_TASK_MESSAGE_FLAG_ARGS: tuple[tuple[str, str], ...] = (+ ("message", "--message"),+ ("message_file", "--message-file"),+ ("prompt", "--prompt"),+ ("prompt_file", "--prompt-file"),+)+++def _explicit_flag_names(args, candidates: tuple[tuple[str, str], ...]) -> list[str]:+ """Which of ``candidates`` the user actually passed, in declaration order."""++ present: list[str] = []+ for attribute, flag in candidates:+ value = getattr(args, attribute, None)+ if isinstance(value, bool):+ if value:+ present.append(flag)+ elif value is not None and str(value).strip():+ present.append(flag)+ return present+++def _reject_session_flags_for_command_task(args, *, help_command: str) -> None:+ """A pure command task has no Session, so Session-shaped flags are inert config."""++ offenders = _explicit_flag_names(args, _TASK_SESSION_FLAG_ARGS)+ if not offenders:+ return+ raise TaskCliError(+ "a pure command task has no Agent session; use --on-failure agent to attach one",+ code="session_flags_with_command_task",+ hint=(+ "Drop "+ + ", ".join(offenders)+ + ", or add --on-failure agent so a failed run has an Agent Session to report into."+ ),+ example="vibe task add --cron '0 3 * * *' --shell './scripts/sync.sh'",+ help_command=help_command,+ details={"flags": offenders},+ )+++def _validate_task_timeout(timeout: Optional[float], *, help_command: str) -> None:+ # ``isfinite`` and not just ``>= 0``: ``float("inf") >= 0`` is True, so ``--timeout+ # inf`` used to be stored and then waited on forever, while every reader of the+ # definition -- JSON output, the Workbench -- rejects a non-finite number and shows+ # the default instead. The documented spelling for "no timeout" is 0.+ if timeout is None or (math.isfinite(timeout) and timeout >= 0):+ return+ raise TaskCliError(+ "--timeout must be a finite number of seconds >= 0",+ code="invalid_timeout",+ hint="Use 0 for no timeout, or a positive number of seconds.",+ help_command=help_command,+ details={"timeout": timeout},+ )+++def _validate_task_action_matrix(+ args,+ *,+ has_command: bool,+ requested_on_failure: Optional[str],+ effective_on_failure: str,+ help_command: str,+) -> None:+ """Which combinations of message, command and failure policy are creatable.++ One place rather than scattered guards, because the interesting failures are all+ CROSS-flag: a policy or a timeout that nothing would consume, a message no Agent+ would ever read, and Session flags on a definition that has no Session at all.+ """++ timeout = getattr(args, "timeout", None)+ if not has_command:+ if requested_on_failure is not None:+ raise TaskCliError(+ "--on-failure only applies to command tasks",+ code="on_failure_requires_command",+ hint="Add --shell or a command after '--', or drop --on-failure.",+ example="vibe task add --cron '0 3 * * *' --shell './scripts/sync.sh' --on-failure agent --message 'Diagnose the failure.'",+ help_command=help_command,+ )+ if timeout is not None:+ raise TaskCliError(+ "--timeout only applies to command tasks",+ code="timeout_requires_command",+ hint="Add --shell or a command after '--', or drop --timeout.",+ help_command=help_command,+ )+ _validate_task_timeout(timeout, help_command=help_command)+ message_flags = _explicit_flag_names(args, _TASK_MESSAGE_FLAG_ARGS)+ if has_command and message_flags and effective_on_failure == "none":+ raise TaskCliError(+ "a stored message needs an Agent to read it",+ code="message_without_consumer",+ hint="Add --on-failure agent so the message is sent when a run fails, or drop the message.",+ example="vibe task add --cron '0 3 * * *' --shell './scripts/sync.sh' --on-failure agent --message 'The nightly sync failed. Diagnose it.'",+ help_command=help_command,+ details={"flags": message_flags},+ )+ if not has_command and not message_flags:+ raise TaskCliError(+ "one of --message, --message-file, --shell, or a command after '--' is required",+ code="missing_task_action",+ hint=(+ "Use --message for a scheduled Agent turn, or --shell for a scheduled command "+ "that runs with no Agent involved."+ ),+ example="vibe task add --cron '0 3 * * *' --shell './scripts/sync.sh'",+ help_command=help_command,+ )++def cmd_task_add(args):reserved_session_id: Optional[str] = Nonetry:caller_context = caller_context_from_env()- session_default_notice = _apply_caller_session_default(- args,- caller_context,- purpose="Task target Session",- )- schedule_type = "cron" if args.cron else "at"- session_policy = _validate_definition_session_policy(- args,- schedule_type=schedule_type,- help_command="vibe task add --help",- allow_caller_session_default=caller_context is not None,- )- scope_key = _resolve_definition_scope_key(args, caller_context=caller_context, help_command="vibe task add --help")- message = _resolve_prompt_input(+ command, shell_command, has_command = _resolve_task_command(args,help_command="vibe task add --help",- example_command="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *'",)- session_id, session_key = _resolve_session_target_args(+ requested_on_failure = getattr(args, "on_failure", None)+ effective_on_failure = requested_on_failure or "none"+ # A command task that escalates keeps the whole Session/Agent flow below,+ # because its failure notice runs a real Agent turn. A PURE command task has+ # no Session at all, so every Session-shaped input is refused instead of+ # silently stored.+ is_pure_command = has_command and effective_on_failure == "none"+ _validate_task_action_matrix(args,- required=session_policy == "existing",+ has_command=has_command,+ requested_on_failure=requested_on_failure,+ effective_on_failure=effective_on_failure,help_command="vibe task add --help",)- cwd = _resolve_definition_session_cwd(- explicit_cwd=getattr(args, "cwd", None),- existing_cwd=None,- session_policy=session_policy,- scoped_session=_has_modern_scope_target(args),- help_command="vibe task add --help",- )- agent_resolution = _resolve_agent_target(- agent_name=getattr(args, "agent", None),- session_id=session_id,- session_key=session_key or scope_key or "",- help_command="vibe task add --help",- )- agent = agent_resolution.agent- agent_name = agent.name if agent else None- expected_enabled_agent_id, expected_reference_agent_id = _agent_write_guard_ids(- agent_resolution- )- if session_policy == "create_once":- session_id = _reserve_definition_session(- agent_name=agent_name,- agent_id=agent.id if agent else None,- deliver_key=scope_key or "",- workdir=cwd,+ schedule_type = "cron" if args.cron else "at"+ if is_pure_command:+ _reject_session_flags_for_command_task(args, help_command="vibe task add --help")+ # Deliberately BEFORE any caller default is applied: inside an Avibe Agent+ # shell ``AVIBE_SESSION_ID`` would otherwise bind this task to the calling+ # conversation, and a pure cron command could not be created from chat at all.+ session_default_notice = None+ session_policy = None+ session_id = None+ session_key = ""+ agent_name = None+ expected_enabled_agent_id = None+ expected_reference_agent_id = None+ scope_key = None+ message = ""+ session_target = None+ delivery_target = None+ raw_cwd = (getattr(args, "cwd", None) or "").strip()+ cwd = (+ _resolve_existing_cwd(+ raw_cwd,+ help_command="vibe task add --help",+ code="cwd_not_found",+ label="task",+ )+ if raw_cwd+ else os.getcwd()+ )+ session_workdir = None+ else:+ session_default_notice = _apply_caller_session_default(+ args,+ caller_context,+ purpose="Task target Session",+ )+ session_policy = _validate_definition_session_policy(+ args,+ schedule_type=schedule_type,help_command="vibe task add --help",- require_enabled_agent=expected_enabled_agent_id is not None,- expected_reference_agent_id=expected_reference_agent_id,+ allow_caller_session_default=caller_context is not None,)- reserved_session_id = session_id- session_target, delivery_target = _validate_definition_delivery_target(- session_policy=session_policy,- session_id=session_id,- session_key=session_key,- post_to=getattr(args, "post_to", None),- deliver_key=getattr(args, "deliver_key", None),- scope_key=scope_key,- help_command="vibe task add --help",- )+ scope_key = _resolve_definition_scope_key(args, caller_context=caller_context, help_command="vibe task add --help")+ # Optional only for an escalating command task, where the Agent turn is a+ # failure notice and the stored message is extra triage guidance.+ message = (+ _resolve_prompt_input(+ args,+ help_command="vibe task add --help",+ example_command="vibe task add --session-id sesk8m4q2p7x --cron '0 * * * *'",+ )+ if not has_command or _explicit_flag_names(args, _TASK_MESSAGE_FLAG_ARGS)+ else ""+ )+ session_id, session_key = _resolve_session_target_args(+ args,+ required=session_policy == "existing",+ help_command="vibe task add --help",+ )+ cwd = _resolve_definition_session_cwd(+ explicit_cwd=getattr(args, "cwd", None),+ existing_cwd=None,+ session_policy=session_policy,+ scoped_session=_has_modern_scope_target(args),+ help_command="vibe task add --help",+ )+ session_workdir = cwd+ cwd = _command_definition_spawn_cwd(+ cwd, has_command=has_command, session_policy=session_policy+ )+ agent_resolution = _resolve_agent_target(+ agent_name=getattr(args, "agent", None),+ session_id=session_id,+ session_key=session_key or scope_key or "",+ help_command="vibe task add --help",+ )+ agent = agent_resolution.agent+ agent_name = agent.name if agent else None+ expected_enabled_agent_id, expected_reference_agent_id = _agent_write_guard_ids(+ agent_resolution+ )+ if session_policy == "create_once":+ session_id = _reserve_definition_session(+ agent_name=agent_name,+ agent_id=agent.id if agent else None,+ deliver_key=scope_key or "",+ workdir=cwd,+ help_command="vibe task add --help",+ require_enabled_agent=expected_enabled_agent_id is not None,+ expected_reference_agent_id=expected_reference_agent_id,+ )+ reserved_session_id = session_id+ session_target, delivery_target = _validate_definition_delivery_target(+ session_policy=session_policy,+ session_id=session_id,+ session_key=session_key,+ post_to=getattr(args, "post_to", None),+ deliver_key=getattr(args, "deliver_key", None),+ scope_key=scope_key,+ help_command="vibe task add --help",+ )+ metadata = _definition_metadata_with_scope(+ caller_context,+ scope_id=scope_key,+ # ``session_workdir`` describes a Session this definition will create, which+ # is a different question from ``cwd`` -- where its command runs. A pure+ # command task creates no Session at all, and a per-run one lets its Session+ # keep whatever workdir creation resolves (see+ # ``_command_definition_spawn_cwd``, which answers only the command's half).+ session_workdir=session_workdir,+ )+ if has_command:+ metadata["on_failure"] = effective_on_failuretimezone_name = args.timezone or _default_timezone_name()try:timezone = ZoneInfo(timezone_name)@@ -3061,7 +3387,10 @@ def cmd_task_add(args):cwd=cwd,cron=args.cron,timezone_name=timezone_name,- metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),+ shell_command=shell_command or None,+ command=command or None,+ timeout_seconds=getattr(args, "timeout", None),+ metadata=metadata,expected_enabled_agent_id=expected_enabled_agent_id,expected_reference_agent_id=expected_reference_agent_id,)@@ -3090,7 +3419,10 @@ def cmd_task_add(args):cwd=cwd,run_at=run_at,timezone_name=timezone_name,- metadata=_definition_metadata_with_scope(caller_context, scope_id=scope_key, session_workdir=cwd),+ shell_command=shell_command or None,+ command=command or None,+ timeout_seconds=getattr(args, "timeout", None),+ metadata=metadata,expected_enabled_agent_id=expected_enabled_agent_id,expected_reference_agent_id=expected_reference_agent_id,)@@ -3208,6 +3540,208 @@ def cmd_task_remove(task_id: str):return 0+def _explicit_task_command_update_flags(args) -> list[str]:+ """Command-shaped update flags the user passed, in declaration order."""++ present: list[str] = []+ if getattr(args, "shell", None) is not None:+ present.append("--shell")+ if getattr(args, "command_argv", None) is not None:+ present.append("--")+ if getattr(args, "on_failure", None) is not None:+ present.append("--on-failure")+ if getattr(args, "timeout", None) is not None:+ present.append("--timeout")+ return present+++def _resolve_definition_name_update(args, task, *, help_command: str) -> Optional[str]:+ if getattr(args, "name", None) is not None and getattr(args, "clear_name", False):+ raise TaskCliError(+ "use either --name or --clear-name, not both",+ code="conflicting_name_update",+ hint="Pass a new name with --name, or remove the stored name with --clear-name.",+ help_command=help_command,+ )+ if getattr(args, "clear_name", False):+ return None+ if getattr(args, "name", None) is not None:+ return _normalize_task_name(args.name)+ return task.name+++def _resolve_definition_schedule_update(+ args,+ task,+ *,+ help_command: str,+) -> tuple[str, Optional[str], Optional[str], str]:+ """``(schedule_type, cron, run_at, timezone_name)`` for one stored definition."""++ timezone_name = args.timezone or task.timezone+ try:+ timezone = ZoneInfo(timezone_name)+ except Exception as exc:+ raise TaskCliError(+ f"invalid timezone: {timezone_name}",+ code="invalid_timezone",+ hint="Use a valid IANA timezone such as UTC, Asia/Shanghai, or America/Los_Angeles.",+ example="Asia/Shanghai",+ help_command=help_command,+ details={"timezone": timezone_name},+ ) from exc++ if args.cron and args.at:+ raise TaskCliError(+ "use either --cron or --at when updating the schedule",+ code="conflicting_schedule_inputs",+ hint="Pass only one schedule update flag at a time.",+ help_command=help_command,+ )+ if args.cron:+ try:+ CronTrigger.from_crontab(args.cron, timezone=timezone)+ except ValueError as exc:+ raise TaskCliError(+ f"invalid cron expression: {args.cron}",+ code="invalid_cron",+ hint="Use standard 5-field crontab format: minute hour day-of-month month day-of-week.",+ example="0 * * * *",+ help_command=help_command,+ details={"cron": args.cron},+ ) from exc+ return "cron", args.cron, None, timezone_name+ if args.at:+ try:+ run_at = _normalize_run_at(args.at, timezone_name)+ except ValueError as exc:+ raise TaskCliError(+ f"invalid --at timestamp: {args.at}",+ code="invalid_run_at",+ hint="Use ISO 8601, for example 2026-03-31T09:00:00+08:00 or 2026-03-31T09:00:00.",+ example="2026-03-31T09:00:00+08:00",+ help_command=help_command,+ details={"at": args.at, "timezone": timezone_name},+ ) from exc+ return "at", None, run_at, timezone_name+ return task.schedule_type, task.cron, task.run_at, timezone_name+++def _merge_task_command_update(+ args,+ task,+ *,+ help_command: str,+) -> tuple[Optional[str], Optional[list[str]], Optional[float]]:+ """Stored command fields with the provided flags applied.++ ``update_command_fields`` is all-or-nothing across the three columns, so an edit+ that names only one of them still has to send the other two back unchanged.+ """++ shell_command = task.shell_command+ command = task.command+ if getattr(args, "shell", None) is not None or getattr(args, "command_argv", None) is not None:+ resolved_command, resolved_shell, _has_command = _resolve_task_command(args, help_command=help_command)+ shell_command = resolved_shell+ command = resolved_command or None+ requested_timeout = getattr(args, "timeout", None)+ _validate_task_timeout(requested_timeout, help_command=help_command)+ timeout_seconds = requested_timeout if requested_timeout is not None else task.timeout_seconds+ return shell_command, command, timeout_seconds+++def _cmd_task_update_pure_command(args, store, task) -> int:+ """Update a command task that has no Session, Agent, or delivery target.++ Kept off the main update path on purpose: that path resolves an Agent, defaults a+ Session policy to ``existing`` and validates a delivery target, all of which would+ invent bindings for a definition that deliberately has none — and would drop the+ stored ``cwd`` on the way, because ``existing`` Sessions own their own workdir.+ """++ help_command = "vibe task update --help"+ _reject_session_flags_for_command_task(args, help_command=help_command)+ name = _resolve_definition_name_update(args, task, help_command=help_command)+ schedule_type, cron, run_at, timezone_name = _resolve_definition_schedule_update(+ args,+ task,+ help_command=help_command,+ )+ shell_command, command, timeout_seconds = _merge_task_command_update(+ args,+ task,+ help_command=help_command,+ )+ raw_cwd = (getattr(args, "cwd", None) or "").strip()+ cwd = (+ _resolve_existing_cwd(raw_cwd, help_command=help_command, code="cwd_not_found", label="task")+ if raw_cwd+ else task.cwd+ )+ metadata = dict(task.metadata or {})+ if getattr(args, "on_failure", None) is not None:+ metadata["on_failure"] = args.on_failure++ changes = {+ "name": name,+ "schedule_type": schedule_type,+ "cwd": cwd,+ "cron": cron,+ "run_at": run_at,+ "timezone": timezone_name,+ "metadata": metadata,+ "shell_command": shell_command,+ "command": command,+ "timeout_seconds": timeout_seconds,+ }+ current = {+ "name": task.name,+ "schedule_type": task.schedule_type,+ "cwd": task.cwd,+ "cron": task.cron,+ "run_at": task.run_at,+ "timezone": task.timezone,+ "metadata": task.metadata,+ "shell_command": task.shell_command,+ "command": task.command,+ "timeout_seconds": task.timeout_seconds,+ }+ if changes == current:+ raise TaskCliError(+ "no task fields were changed",+ code="no_task_changes",+ hint="Pass at least one field to update, such as --name, --cron, --shell, or --timeout.",+ help_command=help_command,+ details={"task_id": args.task_id},+ )++ updated = store.update_task(+ args.task_id,+ name=name,+ session_key=task.session_key,+ session_id=task.session_id,+ prompt=task.prompt,+ schedule_type=schedule_type,+ agent_name=task.agent_name,+ session_policy=task.session_policy,+ post_to=task.post_to,+ deliver_key=task.deliver_key,+ cwd=cwd,+ update_cwd=True,+ cron=cron,+ run_at=run_at,+ timezone_name=timezone_name,+ shell_command=shell_command,+ command=command,+ timeout_seconds=timeout_seconds,+ update_command_fields=True,+ metadata=metadata,+ )+ _print_definition_payload(_task_mutation_payload(updated), warnings=[])+ return 0++def cmd_task_update(args):reserved_session_id: Optional[str] = Nonetry:@@ -3222,6 +3756,53 @@ def cmd_task_update(args):details={"task_id": args.task_id},)+ # A definition is either a scheduled Agent message or a scheduled command, and+ # the two shapes are not convertible in place: switching would leave the other+ # shape's columns (a session binding, or a command line) stored as dead config.+ command_flags = _explicit_task_command_update_flags(args)+ message_flags = _explicit_flag_names(args, _TASK_MESSAGE_FLAG_ARGS)+ #+ # Scoped to ``on_failure=none``, because only THERE is a message a mode switch.+ # An escalating command task already stores one -- it is the guidance the+ # failure turn carries, and ``cmd_task_add`` REQUIRES that mode for a message+ # to be legal beside a command (``message_without_consumer``). Rejecting it for+ # every command task forbade the exact shape the add path blesses, so the+ # guidance could only be reworded by deleting and recreating the task.+ if task.has_command and message_flags and task.on_failure == "none":+ raise TaskCliError(+ "this task runs a command, so its message inputs cannot be changed",+ code="task_mode_immutable",+ hint="Remove this task and create it again to move between command and message tasks.",+ help_command="vibe task update --help",+ details={"task_id": args.task_id, "kind": "command", "flags": message_flags},+ )+ if not task.has_command and command_flags:+ raise TaskCliError(+ "this task sends a stored message, so command inputs cannot be added",+ code="task_mode_immutable",+ hint="Remove this task and create it again with --shell to make it a command task.",+ help_command="vibe task update --help",+ details={"task_id": args.task_id, "kind": "message", "flags": command_flags},+ )+ requested_on_failure = getattr(args, "on_failure", None)+ if requested_on_failure is not None and requested_on_failure != task.on_failure:+ raise TaskCliError(+ f"cannot change failure handling from '{task.on_failure}' to '{requested_on_failure}'",+ code="task_mode_immutable",+ hint=(+ "Escalation decides whether this task owns an Agent Session at all. "+ "Remove this task and create it again with the failure handling you want."+ ),+ help_command="vibe task update --help",+ details={+ "task_id": args.task_id,+ "on_failure": task.on_failure,+ "requested_on_failure": requested_on_failure,+ },+ )+ if task.has_command and task.on_failure == "none":+ return _cmd_task_update_pure_command(args, store, task)+if getattr(args, "reset_delivery", False) and (getattr(args, "post_to", None) is not Noneor getattr(args, "deliver_key", None) is not None@@ -3285,19 +3866,7 @@ def cmd_task_update(args):elif scope_arg_present:metadata.pop("session_scope_id", None)- if getattr(args, "name", None) is not None and getattr(args, "clear_name", False):- raise TaskCliError(- "use either --name or --clear-name, not both",- code="conflicting_name_update",- hint="Pass a new name with --name, or remove the stored name with --clear-name.",- help_command="vibe task update --help",- )- if getattr(args, "clear_name", False):- name = None- elif getattr(args, "name", None) is not None:- name = _normalize_task_name(args.name)- else:- name = task.name+ name = _resolve_definition_name_update(args, task, help_command="vibe task update --help")# Rejected rather than silently resolved, exactly as ``--name`` /# ``--clear-name`` above. The two flags mean opposite things and the pair had@@ -3349,60 +3918,11 @@ def cmd_task_update(args):else task.prompt)- timezone_name = args.timezone or task.timezone- try:- timezone = ZoneInfo(timezone_name)- except Exception as exc:- raise TaskCliError(- f"invalid timezone: {timezone_name}",- code="invalid_timezone",- hint="Use a valid IANA timezone such as UTC, Asia/Shanghai, or America/Los_Angeles.",- example="Asia/Shanghai",- help_command="vibe task update --help",- details={"timezone": timezone_name},- ) from exc-- if args.cron and args.at:- raise TaskCliError(- "use either --cron or --at when updating the schedule",- code="conflicting_schedule_inputs",- hint="Pass only one schedule update flag at a time.",- help_command="vibe task update --help",- )- if args.cron:- try:- CronTrigger.from_crontab(args.cron, timezone=timezone)- except ValueError as exc:- raise TaskCliError(- f"invalid cron expression: {args.cron}",- code="invalid_cron",- hint="Use standard 5-field crontab format: minute hour day-of-month month day-of-week.",- example="0 * * * *",- help_command="vibe task update --help",- details={"cron": args.cron},- ) from exc- schedule_type = "cron"- cron = args.cron- run_at = None- elif args.at:- try:- run_at = _normalize_run_at(args.at, timezone_name)- except ValueError as exc:- raise TaskCliError(- f"invalid --at timestamp: {args.at}",- code="invalid_run_at",- hint="Use ISO 8601, for example 2026-03-31T09:00:00+08:00 or 2026-03-31T09:00:00.",- example="2026-03-31T09:00:00+08:00",- help_command="vibe task update --help",- details={"at": args.at, "timezone": timezone_name},- ) from exc- schedule_type = "at"- cron = None- run_at = run_at- else:- schedule_type = task.schedule_type- cron = task.cron- run_at = task.run_at+ schedule_type, cron, run_at, timezone_name = _resolve_definition_schedule_update(+ args,+ task,+ help_command="vibe task update --help",+ )session_policy = _definition_session_policy_for_update(args,@@ -3444,6 +3964,10 @@ def cmd_task_update(args):)else:cwd = task.cwd+ session_workdir = cwd+ cwd = _command_definition_spawn_cwd(+ cwd, has_command=task.has_command, session_policy=session_policy+ )scope_key = requested_scope_key or str(metadata.get("session_scope_id") or "").strip() or _legacy_scope_key_from_target(deliver_key)if session_policy == "create_once" and not scope_key:raise TaskCliError(@@ -3498,8 +4022,11 @@ def cmd_task_update(args):session_key = ""if session_policy == "existing":metadata.pop("session_workdir", None)- elif cwd:- metadata["session_workdir"] = cwd+ elif session_workdir:+ # The Session's half of the answer, not the command's: a per-run command+ # records the invocation directory in ``cwd`` above without pinning the+ # Session that escalation creates.+ metadata["session_workdir"] = session_workdirelse:metadata.pop("session_workdir", None)session_target, delivery_target = _validate_definition_update_delivery_target(@@ -3512,6 +4039,20 @@ def cmd_task_update(args):help_command="vibe task update --help",)+ # An escalating command task reaches here because it owns a Session for its+ # failure notice; only its command columns need merging, and a message task+ # sends all three back as ``None`` with the write gate closed.+ if task.has_command:+ shell_command, command, timeout_seconds = _merge_task_command_update(+ args,+ task,+ help_command="vibe task update --help",+ )+ else:+ shell_command = None+ command = None+ timeout_seconds = None+changes = {"name": name,"session_id": session_id,@@ -3527,6 +4068,9 @@ def cmd_task_update(args):"run_at": run_at,"timezone": timezone_name,"metadata": metadata,+ "shell_command": shell_command,+ "command": command,+ "timeout_seconds": timeout_seconds,}current = {"name": task.name,@@ -3543,6 +4087,9 @@ def cmd_task_update(args):"run_at": task.run_at,"timezone": task.timezone,"metadata": task.metadata,+ "shell_command": task.shell_command,+ "command": task.command,+ "timeout_seconds": task.timeout_seconds,}if changes == current:raise TaskCliError(@@ -3569,6 +4116,10 @@ def cmd_task_update(args):cron=cron,run_at=run_at,timezone_name=timezone_name,+ shell_command=shell_command,+ command=command,+ timeout_seconds=timeout_seconds,+ update_command_fields=task.has_command,metadata=metadata,expected_enabled_agent_id=expected_enabled_agent_id,expected_reference_agent_id=expected_reference_agent_id,@@ -4557,6 +5108,35 @@ def _resolve_definition_session_cwd(return os.getcwd()+def _command_definition_spawn_cwd(+ session_cwd: Optional[str],+ *,+ has_command: bool,+ session_policy: str,+) -> Optional[str]:+ """Where this definition's COMMAND runs, given where its Session would run.++ ``_resolve_definition_session_cwd`` answers a Session question, and declines to+ answer it for ``create_per_run``: that Session does not exist yet, so creation+ resolves its workdir later from the Scope or the runtime default. A command cannot+ wait for that. It runs on the next tick from the definition's ``cwd``, and with+ nothing recorded there it fell through to the ``~/.avibe`` fallback -- so+ ``--shell './scripts/sync.sh'`` ran from the product state directory, where the+ relative path is missing and a relative write lands in persisted state.++ The invocation directory is the answer, for the same reason a pure command task+ already records it: it is where the user was standing when they described the+ command. Returned only for the policy that leaves the command with no other source+ -- an ``existing`` binding is read live from its Session at fire time, and+ ``create_once`` reserves its Session immediately -- and never over an explicit+ ``--cwd``.+ """++ if not has_command or session_cwd or session_policy != "create_per_run":+ return session_cwd+ return os.getcwd()++def _has_modern_scope_target(args) -> bool:return bool((getattr(args, "scope_id", None) or "").strip()) or bool(getattr(args, "same_scope", False))@@ -13971,12 +14551,35 @@ def build_parser():schedule_group = task_add_parser.add_mutually_exclusive_group(required=True)schedule_group.add_argument("--cron", help="Recurring schedule in 5-field crontab format")schedule_group.add_argument("--at", help="One-shot timestamp in ISO 8601 format")- prompt_group = task_add_parser.add_mutually_exclusive_group(required=True)+ # Not ``required=True`` any more: a command task carries no message at all, so the+ # "message or command" choice is enforced in ``cmd_task_add`` where both inputs are+ # visible (``missing_task_action``).+ prompt_group = task_add_parser.add_mutually_exclusive_group()prompt_group.add_argument("--message", help="Stored user message to send each time the task runs")prompt_group.add_argument("--message-file", help="Read stored user message from a UTF-8 text file")prompt_group.add_argument("--prompt", help=argparse.SUPPRESS)prompt_group.add_argument("--prompt-file", help=argparse.SUPPRESS)task_add_parser.add_argument("--timezone", help="IANA timezone name used for --cron and naive --at values")+ task_add_parser.add_argument(+ "--shell",+ help="Shell command to run on schedule. Use this or pass a command after '--'.",+ )+ task_add_parser.add_argument(+ "--on-failure",+ choices=["none", "agent"],+ default=None,+ help="What a failed command run does: 'none' records the failure, 'agent' starts an Agent turn to triage it. Default: none",+ )+ task_add_parser.add_argument(+ "--timeout",+ type=float,+ help="Per-run timeout in seconds for command tasks. Use 0 for no timeout. Default: 21600.",+ )+ task_add_parser.add_argument(+ "command_argv",+ nargs=argparse.REMAINDER,+ help="-- followed by the command to run on schedule",+ )_add_json_noop(task_add_parser)task_update_parser = task_subparsers.add_parser(@@ -14026,6 +14629,24 @@ def build_parser():task_update_parser.add_argument("--prompt", help=argparse.SUPPRESS)task_update_parser.add_argument("--prompt-file", help=argparse.SUPPRESS)task_update_parser.add_argument("--timezone", help="Replace the stored IANA timezone name")+ task_update_parser.add_argument(+ "--shell",+ help="Replace the shell command a command task runs. Use this or pass a command after '--'.",+ )+ task_update_parser.add_argument(+ "--on-failure",+ choices=["none", "agent"],+ default=None,+ help=argparse.SUPPRESS,+ )+ task_update_parser.add_argument(+ "--timeout",+ type=float,+ help="Replace the per-run timeout in seconds for a command task. Use 0 for no timeout.",+ )+ # No positional landing slot here: the trailing ``-- <command ...>`` tail is lifted+ # out of argv before argparse runs, exactly as for 'vibe watch update'.+ task_update_parser.set_defaults(command_argv=None)_add_json_noop(task_update_parser)task_subparsers.add_parser(diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 824b5baca..8d19fed02 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -33,6 +33,26 @@"invalidCommand": "The watch worker command is invalid."}},+ "command": {+ "workdirMissing": "Working directory does not exist: {cwd}",+ "supervisorExitedDuringStartup": "Command supervisor exited during startup.",+ "workerNotRecorded": "The command was not started because its worker could not be recorded.",+ "supervisorFailed": "Command supervisor failed: {detail}",+ "unknownSupervisorFailure": "Unknown supervisor failure.",+ "protocolErrors": {+ "specTooLarge": "The command specification is too large.",+ "invalidEncoding": "The command specification is not valid UTF-8.",+ "invalidJson": "The command specification is not valid JSON.",+ "unsupportedVersion": "The command specification version is unsupported.",+ "invalidCommand": "The command is invalid."+ },+ "timedOut": "Command timed out after {seconds} second(s).",+ "exited": "Command exited with status {code}.",+ "exitedWithDetail": "Command exited with status {code}: {detail}"+ },+ "task": {+ "resultNotRecorded": "The result of this run could not be recorded: the task was reclaimed, repointed or removed while it was running, so its stored state is unchanged."+ },"queueCoalesced": {"summary": "[Avibe Harness] The same watch/task callback fired {count} times within a rolling {window}-second window. The queued callbacks were coalesced into this single Agent turn.","messagesLabel": "Coalesced callback messages:",@@ -61,7 +81,9 @@"notice": {"failed": "[Avibe Harness] Scheduled work \"{name}\" failed.","interrupted": "[Avibe Harness] Scheduled work \"{name}\" was interrupted ({reason}). Nothing is wrong with the definition itself.",+ "commandLine": "Command: {command}","error": "Error: {error}",+ "commandExit": "Exit code: {exitCode}","unknownError": "no error text was recorded","definition": "Definition: {id}","paused": "It is currently PAUSED and will not fire again until you resume it: vibe task resume {id}",diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 70ba52895..af20589c5 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -33,6 +33,26 @@"invalidCommand": "Watch 工作进程命令无效。"}},+ "command": {+ "workdirMissing": "\u5de5\u4f5c\u76ee\u5f55\u4e0d\u5b58\u5728\uff1a{cwd}",+ "supervisorExitedDuringStartup": "\u547d\u4ee4\u76d1\u63a7\u8fdb\u7a0b\u5728\u542f\u52a8\u671f\u95f4\u9000\u51fa\u3002",+ "workerNotRecorded": "\u672a\u542f\u52a8\u547d\u4ee4\uff1a\u65e0\u6cd5\u8bb0\u5f55\u5176\u76d1\u63a7\u8fdb\u7a0b\u3002",+ "supervisorFailed": "\u547d\u4ee4\u76d1\u63a7\u8fdb\u7a0b\u5931\u8d25\uff1a{detail}",+ "unknownSupervisorFailure": "\u672a\u77e5\u7684\u76d1\u63a7\u8fdb\u7a0b\u9519\u8bef\u3002",+ "protocolErrors": {+ "specTooLarge": "\u547d\u4ee4\u914d\u7f6e\u8fc7\u5927\u3002",+ "invalidEncoding": "\u547d\u4ee4\u914d\u7f6e\u4e0d\u662f\u6709\u6548\u7684 UTF-8\u3002",+ "invalidJson": "\u547d\u4ee4\u914d\u7f6e\u4e0d\u662f\u6709\u6548\u7684 JSON\u3002",+ "unsupportedVersion": "\u4e0d\u652f\u6301\u6b64\u547d\u4ee4\u914d\u7f6e\u7248\u672c\u3002",+ "invalidCommand": "\u547d\u4ee4\u65e0\u6548\u3002"+ },+ "timedOut": "\u547d\u4ee4\u5728 {seconds} \u79d2\u540e\u8d85\u65f6\u3002",+ "exited": "\u547d\u4ee4\u9000\u51fa\uff0c\u72b6\u6001\u7801 {code}\u3002",+ "exitedWithDetail": "\u547d\u4ee4\u9000\u51fa\uff0c\u72b6\u6001\u7801 {code}\uff1a{detail}"+ },+ "task": {+ "resultNotRecorded": "\u65e0\u6cd5\u8bb0\u5f55\u672c\u6b21\u8fd0\u884c\u7684\u7ed3\u679c\uff1a\u4efb\u52a1\u5728\u8fd0\u884c\u671f\u95f4\u88ab\u56de\u6536\u3001\u6539\u7ed1\u6216\u5220\u9664\uff0c\u5176\u5b58\u50a8\u72b6\u6001\u672a\u53d1\u751f\u53d8\u5316\u3002"+ },"queueCoalesced": {"summary": "[Avibe Harness] 同一个 watch/task callback 在滚动 {window} 秒窗口内触发了 {count} 次。已将这些排队 callback 合并为一次 Agent turn。","messagesLabel": "已合并的 callback 消息:",@@ -61,7 +81,9 @@"notice": {"failed": "[Avibe Harness] 后台任务「{name}」执行失败。","interrupted": "[Avibe Harness] 后台任务「{name}」被中断({reason}),任务本身没有问题。",+ "commandLine": "命令:{command}","error": "错误:{error}",+ "commandExit": "退出码:{exitCode}","unknownError": "未记录错误信息","definition": "任务 ID:{id}","paused": "该任务当前已暂停,恢复前不会再次触发:vibe task resume {id}",