diff --git a/apps/presentation/dashboard/src/data/status.ts b/apps/presentation/dashboard/src/data/status.ts index 60d10a7ace..50ea5d5728 100644 --- a/apps/presentation/dashboard/src/data/status.ts +++ b/apps/presentation/dashboard/src/data/status.ts @@ -617,7 +617,7 @@ export const runGoalSchema = z.object({ delivery_window: z.object({ schema_version: z.string().optional(), state: z.enum(["fresh", "stale", "missing", "unknown"]).catch("unknown"), - reason: z.enum(["no_expectation", "no_observation", "unparseable_observation"]).optional().nullable(), + reason: z.enum(["no_expectation", "no_observation", "unparseable_observation", "unverified_activity"]).optional().nullable(), last_observed_at: z.string().optional().nullable(), age_seconds: z.number().optional().nullable(), age_hours: z.number().optional().nullable(), diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-activity-view.tsx b/apps/presentation/dashboard/src/features/personal-workspace/goal-activity-view.tsx index 72f118514e..13e556fb57 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-activity-view.tsx +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-activity-view.tsx @@ -71,6 +71,7 @@ const observationReasons: Readonly> = { record_unrecognized: "activity.reason.recordUnrecognized", no_turn_marker: "activity.reason.noTurnMarker", unparseable_observation: "activity.reason.unparseableObservation", + unverified_activity: "activity.reason.unverifiedActivity", }; /** A sibling of the Goal navigation button so help never selects a Goal. */ diff --git a/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts b/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts index 3f922c18db..cba0b674e6 100644 --- a/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts +++ b/apps/presentation/dashboard/src/features/personal-workspace/goal-activity.ts @@ -165,7 +165,8 @@ export function goalObservationGaps(goal: Pick = { "activity.reason.recordUnrecognized": "暂时无法识别宿主记录格式。", "activity.reason.noTurnMarker": "有限的宿主历史中没有回合开始或结束标记,执行状态仍未知。", "activity.reason.unparseableObservation": "暂时无法读取记录中的活动时间。", + "activity.reason.unverifiedActivity": "线程最近有活动,但没有与定时提示匹配的送达记录,交付状态未验证。", "activity.claimedAt": "领取于{time}", "activity.viaHost": "{host} 宿主", "activity.quiet": "已 {minutes} 分钟无新动静", diff --git a/docs/integrations/attached-agent-session-broker.md b/docs/integrations/attached-agent-session-broker.md index ea9a4b0b2a..fd027a3fe8 100644 --- a/docs/integrations/attached-agent-session-broker.md +++ b/docs/integrations/attached-agent-session-broker.md @@ -108,3 +108,101 @@ to another host, deliver a message or qualify live execution. Homes are searched in the order `CODEX_HOME`, `~/.codex`, then sibling `~/.codex-*` directories; set `LOOPX_CODEX_HOMES` (an `os.pathsep`-separated list) to search exactly those homes instead. + +## Missed Delivery Windows + +The status route adds `delivery_window` to each observed lane of +`host_thread_activity`. For a `codex-app` lane the expected cadence comes from +the `rrule` of the installed heartbeat automation whose prompt names that Goal +and agent and whose `target_thread_id` is the lane's canonical binding; another +lane's automation is never read as this one's, and two automations claiming one +lane leave the window `unknown`. Other surfaces report `unknown` there. + +Activity alone does not prove a scheduled prompt arrived: an empty Turn, a +resumed Turn and a hand-written message leave the same trace. `loopx doctor` +therefore also asks for *delivery evidence* and only reads a lane `fresh` when +the thread's newest Turn is one the host attributes to an automation — its +`task_started.turn_attribution.turn_trigger` is `automation_heartbeat` (the +routing contract's name) or `automation_heartbeat_scheduled` (the value the +current Codex App rollout writes for the same delivery), with the +`heartbeat_xml` / `user_input` / `user` transport the contract already requires +— and carries a user message matching the installed prompt. Matching text is +only a pointer: a `composer` Turn that repeats the prompt verbatim, with or +without the host's envelope, proves nothing, and a trigger this adapter has not +seen stays unverified rather than being read as a tick. When the envelope names an +``, it must be the automation installed for this lane, so a +sibling automation's body cannot stand in. The matching message's time is +published as `delivery_evidence_at`. The scan reads a bounded 8 MiB tail of the +thread's own rollout and stops at the newest `task_started`; a Turn that arrives +without its opening record, without attribution, or one larger than that budget +is unattributed rather than guessed. + +| `state` | Meaning | +| --- | --- | +| `fresh` | The lane received its installed prompt inside `expected_interval_minutes × tolerance` (tolerance defaults to 2). | +| `stale` | The lane's last recorded tick is older than that window. This names the symptom only; it does not name a cause. | +| `missing` | No observation of this lane was available at all. | +| `unknown` | The window could not be computed; `reason` is `no_expectation`, `no_observation`, `unparseable_observation` or `unverified_activity`. | + +`unverified_activity` is the middle case: the lane moved inside its window but +nothing ties that activity to the installed prompt. Its last activity time is +still reported, so an operator can tell "quiet" from "busy, but not scheduled". +The Dashboard status route keeps its existing activity-only semantics; only the +`doctor` readback asks for delivery evidence. + +`loopx doctor` reads the same projection once per run and reports it as the +optional `host_prompt_delivery_windows` check and the `host_prompt_delivery` +payload: a `status` of `fresh`, `stale`, `unverified` or `not_applicable`, a +per-state `counts` map, and one row per lane carrying `last_observed_at`, +`age_hours`, `window_minutes` and the cadence `source`. A `stale` lane carries +`diagnosis.code = host_prompt_delivery_missed` with the last tick the host did +record; `missing`/`unknown` lanes carry +`diagnosis.code = host_prompt_delivery_unverified` and their reason. Only a +missed window turns the check red — an absent receipt is not proof that the host +stopped delivering, so it is reported rather than counted as a fault. A run that +could not measure every lane also leaves the optional check red, with the gap +named in its detail, because a green check would claim coverage the run did not +have. The check stays optional either way, so it never fails `loopx doctor` on +its own. + +Stopped Goals are skipped: their automation is no longer a live promise. +Observation is bounded to 64 lanes per run (`truncated` says whether the bound +was hit). The shared observer also keeps at most 32 bindings per Goal; a Goal +past that cap is counted in `incomplete_goals` and also sets `truncated`, since a +silent lane can hide among the bindings that were not read. + +Lane identity is resolved over the Goal's complete binding list, before that +bound trims what the run reads. An agent bound to two threads on one surface has +no canonical thread, so its window stays `unknown/no_expectation` whether the +second binding sits at position 2 or past the cap; truncation removes +observations, never identities. + +A run that did not measure every lane never reports `fresh`: the lanes it did +read may all be inside their window while an unread lane is silent. Such a run +reports `unverified` with `reason = scan_truncated` when the lane bound was hit, +or `not_applicable` with the same reason when nothing was left to read. A +binding on an observable surface that names no thread (`unmeasured_bindings`) or +a Goal whose activation record cannot be read +(`unreadable_activation_goals`) reports `unverified` with +`reason = unmeasured_lane`. + +Doctor reads each lane's store read-only and never starts a Turn, writes the host +store or spends quota. The diagnostic registry is the one the run resolved: an +explicit `--registry` replaces the default global path for every diagnostic this +run projects, so a moved registry is measured where it lives instead of reading +as an empty workspace. A registry this build cannot decode is reported as +`not_applicable` with `reason = registry_requires_upgrade`, and a missing or +unreadable one as `registry_unavailable`, so a broken workspace never turns this +optional check into a doctor failure. `loopx doctor --installation-only` does +not read host state at all and therefore omits this projection. + +A Goal, agent or host surface identifier is free-form registry text, so a lane +can be named after a directory or a token-shaped string. Such a label is +replaced before publication by `>` plus, when the last +path segment is itself safe, `:`; the row carries +`label_redacted = true`. The digest is stable across runs and differs per +identifier, so two path-shaped Goals stay distinguishable and an operator can +still match the lane to the silent Goal. If any unanticipated field still +violates the public-output boundary, the projection keeps its `status`, counts +and check verdict and sets `labels_withheld = true` instead of failing the +whole doctor run. diff --git a/loopx/codex_app_thread_activity.py b/loopx/codex_app_thread_activity.py index fba46e8b4e..35eb30e9fa 100644 --- a/loopx/codex_app_thread_activity.py +++ b/loopx/codex_app_thread_activity.py @@ -10,6 +10,7 @@ from __future__ import annotations import hashlib +import json import os import re import sqlite3 @@ -406,6 +407,17 @@ def _automation_rrule_interval_minutes(rrule: Any) -> int | None: def _installed_automation_intervals( homes: list[Path] | None = None, ) -> dict[tuple[str, str, str], int]: + values: dict[tuple[str, str, str], int] = {} + for key, entry in _installed_automations(homes).items(): + interval = entry.get("interval_minutes") + if isinstance(interval, int): + values[key] = interval + return values + + +def _installed_automations( + homes: list[Path] | None = None, +) -> dict[tuple[str, str, str], dict[str, object]]: """Map each installed heartbeat automation to the lane it serves. A lane is identified the way the canonical resolver identifies it @@ -416,9 +428,13 @@ def _installed_automation_intervals( instead of being measured against another lane's cadence. """ - from .upgrade import infer_agent_id_from_prompt, infer_goal_id_from_prompt + from .upgrade import ( + infer_agent_id_from_prompt, + infer_goal_id_from_prompt, + prompt_digest, + ) - intervals: dict[tuple[str, str, str], int] = {} + intervals: dict[tuple[str, str, str], dict[str, object]] = {} ambiguous: set[tuple[str, str, str]] = set() identities: set[tuple[int, int]] = set() for home in codex_homes() if homes is None else homes: @@ -455,6 +471,9 @@ def _installed_automation_intervals( interval = _automation_rrule_interval_minutes(item.get("rrule")) if not goal_id or not agent_id or not target_thread_id or interval is None: continue + # The digest, not the body, is what reaches an evidence comparison: + # the installed prompt is the only text a scheduled delivery must + # reproduce byte-for-byte, and a digest never leaves this process. key = (goal_id, agent_id, target_thread_id) if key in intervals: # Two automations claim one lane: neither is that lane's cadence. @@ -462,10 +481,312 @@ def _installed_automation_intervals( ambiguous.add(key) continue if key not in ambiguous: - intervals[key] = interval + intervals[key] = { + "interval_minutes": interval, + # The id names which automation's envelope may claim this + # lane; a sibling automation's tick is not this one's. The + # installer falls back to the directory name the same way. + "automation_id": str(item.get("id") or path.parent.name).strip(), + # A scheduled tick wraps the installed prompt in the host's + # heartbeat envelope, so the envelope is stripped before the + # digest is taken and compared against each message the same + # way. + "prompt_sha256": prompt_digest(prompt.strip()), + } return intervals +# The backward scan mirrors the activity observer's budget: a heartbeat turn can +# append hundreds of tool records, so a record count would stop long before the +# `task_started` that opens it. A turn larger than this budget is reported as +# unattributed rather than guessed. +_EVIDENCE_TAIL_BYTES = 8 * 1024 * 1024 +_INSTRUCTIONS_OPEN = "" +_INSTRUCTIONS_CLOSE = "" +_AUTOMATION_ID_OPEN = "" +_AUTOMATION_ID_CLOSE = "" +# The host's own labels for a turn it started from an installed automation. The +# canonical heartbeat transport contract +# (``loopx_codex_provider_routing.contract.qualify_heartbeat_transport``) names +# ``automation_heartbeat``; a current Codex App rollout records the same turn as +# ``automation_heartbeat_scheduled``. Both describe a scheduled delivery, while +# a ``composer`` turn, a ``guardian_review`` and a resumed turn do not. The set +# stays closed on purpose: a value this adapter has not seen is reported +# unverified rather than assumed to be the automation, because a wrong ``fresh`` +# hides exactly the fault this readback exists to name. +_HEARTBEAT_TURN_TRIGGERS = frozenset( + {"automation_heartbeat", "automation_heartbeat_scheduled"} +) +_HEARTBEAT_TRANSPORT_FIELDS = { + "payload_kind": "heartbeat_xml", + "delivery_kind": "user_input", + "message_role": "user", +} + + +def _message_text(payload: Mapping[str, Any]) -> str | None: + """Return one user message's text, or ``None`` for any other record shape.""" + + if payload.get("type") != "message" or payload.get("role") != "user": + return None + content = payload.get("content") + if not isinstance(content, list): + return None + parts = [ + item.get("text") + for item in content + if isinstance(item, Mapping) and item.get("type") == "input_text" + ] + if not parts or not all(isinstance(part, str) for part in parts): + return None + return "".join(parts) + + +def _heartbeat_automation_id(text: str) -> tuple[bool, str]: + """Return whether a message names an automation, and which one. + + A malformed or empty element still counts as naming one: it is not the + lane's automation, so it cannot be read as "the envelope omitted the id". + """ + + start = text.find(_AUTOMATION_ID_OPEN) + if start < 0: + return False, "" + start += len(_AUTOMATION_ID_OPEN) + end = text.find(_AUTOMATION_ID_CLOSE, start) + if end < 0: + return True, "" + return True, text[start:end].strip() + + +def _delivered_prompt_digests(payload: Mapping[str, Any]) -> list[tuple[str, bool, str]]: + """Return the (digest, automation id) pairs one message can carry. + + Codex App injects a scheduled prompt either verbatim or inside its + ```` envelope, where the installed body sits in + ```` and ```` names the installation. Both + spellings compare equal by digest; the envelope also has to name this lane's + automation, and a message with neither spelling is a hand-written one and + matches nothing here. + """ + + text = _message_text(payload) + if text is None: + return [] + found: list[tuple[str, bool, str]] = [] + stripped = text.strip() + if stripped: + # A verbatim prompt names no automation; whether it may count is the + # turn's to say. + found.append((_prompt_digest_of(stripped), False, "")) + start = text.find(_INSTRUCTIONS_OPEN) + if start >= 0: + start += len(_INSTRUCTIONS_OPEN) + end = text.find(_INSTRUCTIONS_CLOSE, start) + if end > start: + inner = text[start:end].strip() + if inner: + named, automation = _heartbeat_automation_id(text) + found.append((_prompt_digest_of(inner), named, automation)) + return found + + +def _heartbeat_turn(payload: Mapping[str, Any]) -> bool: + """Return whether the host attributes this turn to a scheduled heartbeat. + + A turn's own ``turn_attribution.turn_trigger`` is the host's testimony that + an automation started it. Text that happens to equal the installed prompt + is only a pointer: a hand-typed message in a ``composer`` turn, or a + guardian review, must never be read as a scheduled delivery. The two + triggers a release has been observed to publish for a scheduled turn are + both accepted, so the adapter does not read a real tick as a manual one. + Transport fields the rollout carries are checked against the same contract + when present; the rollout is not required to repeat fields it does not + record. + """ + + attribution = payload.get("turn_attribution") + if not isinstance(attribution, Mapping): + return False + trigger = attribution.get("turn_trigger") + if not isinstance(trigger, str) or trigger not in _HEARTBEAT_TURN_TRIGGERS: + return False + turn_id = attribution.get("turn_id") + if isinstance(turn_id, str) and turn_id: + started = payload.get("turn_id") + if isinstance(started, str) and started and started != turn_id: + # One record claiming two turns cannot attribute either of them. + return False + for field, expected in _HEARTBEAT_TRANSPORT_FIELDS.items(): + observed = attribution.get(field) + if observed is None: + observed = payload.get(field) + if observed is not None and observed != expected: + return False + return True + + +def _rollout_prompt_evidence( + path: Path, digest: str, automation_id: str = "" +) -> str | None: + """Return when this thread's newest turn received the installed prompt. + + Walks a bounded tail of the thread's own rollout backward. The newest + ``task_started`` opens the turn under examination, and that turn must carry + one of the host's automation triggers before anything inside it counts; a + user message whose prompt (or heartbeat-envelope body) hashes to + the installed prompt is then its scheduled delivery. A hand-written message + -- even one that repeats the installed text verbatim -- a resumed turn or an + empty turn produces no match, so none of them can make a silent lane look + healthy. + """ + + try: + with open_rollout(path) as handle: + size = os.fstat(handle.fileno()).st_size + truncated = size > _EVIDENCE_TAIL_BYTES + handle.seek(max(0, size - _EVIDENCE_TAIL_BYTES)) + tail = handle.read() + except OSError: + return None + lines = tail.split(b"\n") + if truncated: + # The first fragment starts mid-record; drop it. + lines = lines[1:] + delivered_at: str | None = None + trailing = True + for raw in reversed(lines): + if not raw.strip(): + continue + try: + row = json.loads(raw) + except ValueError: + # The host appends while this runs, so the last line can be a + # record still being written. It carries no delivery yet; one + # unreadable record anywhere else is a broken store, not evidence. + if trailing: + trailing = False + continue + return None + trailing = False + if not isinstance(row, Mapping): + return None + payload = row.get("payload") + timestamp = row.get("timestamp") + if not isinstance(payload, Mapping) or not isinstance(timestamp, str): + return None + if row.get("type") == "event_msg" and payload.get("type") == "task_started": + # The newest turn decides twice: the host must attribute it to a + # scheduled heartbeat, and a message inside it must match. Text + # alone is a pointer, so a manual turn repeating the prompt stays + # unverified. + return delivered_at if _heartbeat_turn(payload) else None + if row.get("type") == "response_item": + for carried_digest, named_automation, envelope_automation in ( + _delivered_prompt_digests(payload) + ): + if carried_digest != digest: + continue + if named_automation and envelope_automation != automation_id: + # Another installation's envelope body is not this lane's. + continue + # A prompt repeated inside one turn is still that turn's delivery. + delivered_at = delivered_at or timestamp + break + # The whole bounded tail belongs to one turn that never showed its start. + return None + + +def _prompt_digest_of(text: str) -> str: + from .upgrade import prompt_digest + + return prompt_digest(text) + + +def _thread_rollouts( + thread_ids: Iterable[str], homes: list[Path] | None +) -> dict[str, Path]: + """Map each thread this local store records to its rollout file.""" + + remaining = sorted(set(thread_ids)) + paths: dict[str, Path] = {} + for home in codex_homes() if homes is None else homes: + if not remaining: + break + try: + db = _state_db(home) + if db is None: + continue + rows = _thread_rows(db, remaining) + except _UnrecognizedStore: + continue + except (OSError, sqlite3.Error): + continue + root = Path(os.path.realpath(home)) + for thread_id, (rollout_path, archived) in rows.items(): + if archived not in (0, False) or not isinstance(rollout_path, str): + continue + if not rollout_path: + continue + path = Path(os.path.realpath(rollout_path)) + # The same boundary the activity observer keeps: a store row is not + # a license to read a file outside the home that records it. + if not path.is_relative_to(root): + continue + paths[thread_id] = path + remaining = [item for item in remaining if item != thread_id] + return paths + + +def codex_delivery_evidence( + scopes: Iterable[HostDeliveryScope], + *, + homes: list[Path] | None = None, +) -> dict[HostDeliveryScope, str | None]: + """Resolve when each lane last received its installed heartbeat prompt. + + Only an installed ``heartbeat`` automation names a prompt a scheduled tick + must reproduce, and only the thread it targets can hold that delivery. A + lane without one is omitted, so its window stays unverified rather than + being measured against another lane's prompt. This reads the thread's own + rollout read-only and never starts a turn or writes the host store. + """ + + wanted = [ + scope + for scope in scopes + if scope.host_surface == CODEX_APP_BINDING_SURFACE and scope.thread_id + ] + if not wanted: + return {} + automations = _installed_automations(homes) + placements: dict[HostDeliveryScope, Mapping[str, object]] = {} + for scope in wanted: + entry = automations.get((scope.goal_id, scope.agent_id, scope.thread_id or "")) + if entry is not None: + placements[scope] = entry + if not placements: + return {} + rollouts = _thread_rollouts( + (scope.thread_id or "" for scope in placements), homes + ) + cache: dict[tuple[Path, str, str], str | None] = {} + evidence: dict[HostDeliveryScope, str | None] = {} + for scope, entry in placements.items(): + path = rollouts.get(scope.thread_id or "") + if path is None: + continue + digest = str(entry.get("prompt_sha256") or "") + if not digest: + continue + automation_id = str(entry.get("automation_id") or "") + key = (path, digest, automation_id) + if key not in cache: + cache[key] = _rollout_prompt_evidence(path, digest, automation_id) + evidence[scope] = cache[key] + return evidence + + def codex_delivery_expectations( scopes: Iterable[HostDeliveryScope], *, diff --git a/loopx/control_plane/agents/host_delivery_diagnosis.py b/loopx/control_plane/agents/host_delivery_diagnosis.py new file mode 100644 index 0000000000..35bf4e9f82 --- /dev/null +++ b/loopx/control_plane/agents/host_delivery_diagnosis.py @@ -0,0 +1,577 @@ +"""Doctor readback of whether bound host lanes still deliver scheduled prompts. + +A Codex App automation that stops delivering its prompt leaves the Goal in the +same shape as a Goal that is simply waiting: an open Todo, a normal +``should-run`` decision, and no Turn entering the LoopX protocol. Nothing in the +Goal's own records distinguishes the two, so the operator learns days later. + +The readback here reuses the observation and window owners that already serve +the status projection. It reads each bound lane once, reports one typed window +per lane, and names a missed-delivery window only when the lane has a cadence to +keep and was observed past it. A lane with no cadence, no record or an +unreadable record is reported as ``missing``/``unknown`` -- never as healthy and +never as a fault. + +This module performs no host action: it does not start a Turn, write the host +store, or spend quota. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from datetime import datetime, timezone +import hashlib +from pathlib import Path +import re +from typing import Any + +from ...public_safe_text import SECRET_LIKE_SURFACE_PATTERN, find_public_safe_local_path +from ..goals.activation import GoalActivationState, goal_activation_state +from ..runtime.public_safety import validate_public_safe_value +from .host_thread_activity import ( + DEFAULT_DELIVERY_WINDOW_TOLERANCE, + HOST_DELIVERY_WINDOW_SCHEMA_VERSION, + MAX_OBSERVED_THREADS_PER_GOAL, + HostDeliveryEvidenceProvider, + HostDeliveryWindowState, + HostThreadObservationCompleteness, + HostDeliveryExpectationProvider, + HostThreadObserver, + HostThreadState, + attach_host_delivery_windows, + attach_host_thread_activity, +) + +HOST_DELIVERY_DIAGNOSIS_SCHEMA_VERSION = "loopx_host_delivery_diagnosis_v0" +# Two typed outcomes, deliberately distinct. A lane observed past its cadence +# shows a missed delivery; a lane with no comparable tick shows only that the +# receipt is unverified. An absent record is not proof the host stopped. +HOST_PROMPT_DELIVERY_MISSED = "host_prompt_delivery_missed" +HOST_PROMPT_DELIVERY_UNVERIFIED = "host_prompt_delivery_unverified" + +# Doctor reads one bounded slice: a few dozen lanes describe every plausible +# workspace, and an unbounded scan would turn a diagnostic into a walk over the +# whole Codex history. +MAX_DIAGNOSED_LANES = 64 + +_LOCAL_OBSERVED_STATES = ( + HostDeliveryWindowState.FRESH, + HostDeliveryWindowState.STALE, + HostDeliveryWindowState.MISSING, + HostDeliveryWindowState.UNKNOWN, +) + + +def _observed_bindings( + goal: Mapping[str, Any], observer_surfaces: Iterable[str] +) -> tuple[list[dict[str, Any]], int]: + """Return the Goal's bindings this doctor can observe, and unmeasured ones. + + Only a binding with a host surface this process can read is kept: a Goal + bound to a host without an observer must not be reported as a missed + delivery by an observer that never had a way to see it. A binding on an + observable surface that names no thread cannot be measured, so it is counted + rather than dropped: an operator who mistyped a binding otherwise reads a + healthy workspace with one lane missing. + """ + + coordination = goal.get("coordination") + raw_bindings = ( + coordination.get("thread_agent_bindings") + if isinstance(coordination, Mapping) + else None + ) + surfaces = set(observer_surfaces) + bindings: list[dict[str, Any]] = [] + unmeasured = 0 + for raw in raw_bindings if isinstance(raw_bindings, list) else []: + if not isinstance(raw, Mapping): + continue + host_surface = str(raw.get("host_surface") or "").strip() + thread_id = str(raw.get("thread_id") or "").strip() + agent_id = str(raw.get("agent_id") or "").strip() + if host_surface not in surfaces: + continue + if thread_id and agent_id: + bindings.append(dict(raw)) + else: + # The shared observer drops a binding without both an agent and a + # thread, so it would vanish from the report entirely. + unmeasured += 1 + return bindings, unmeasured + + +def _ambiguous_lanes(bindings: Iterable[Mapping[str, Any]]) -> set[tuple[str, str]]: + """Return the ``(agent, surface)`` lanes bound to more than one thread. + + This reads the Goal's complete binding list, before the lane bound trims + what this run observes. Truncation removes observations, not identities: a + lane that names two threads is ambiguous whether the second binding sits at + position 2 or 65, and slicing first would let the survivor look like a + single canonical thread. + """ + + counts: dict[tuple[str, str], int] = {} + for raw in bindings: + key = ( + str(raw.get("agent_id") or "").strip(), + str(raw.get("host_surface") or "").strip(), + ) + counts[key] = counts.get(key, 0) + 1 + return {key for key, count in counts.items() if count > 1} + + +_SAFE_LABEL_TAIL = re.compile(r"[A-Za-z0-9._-]{1,40}") +# A registry identifier is free text; keeping a very long one would push a +# pasted `doctor` transcript past any reader's patience without adding detail a +# digest does not already carry. +MAX_LABEL_LENGTH = 120 + + +def _unsafe_label(text: str) -> bool: + if len(text) > MAX_LABEL_LENGTH: + return True + try: + text.encode("utf-8") + except UnicodeEncodeError: + # A lone surrogate cannot be written to a UTF-8 stdout at all. + return True + return bool( + find_public_safe_local_path(text) or SECRET_LIKE_SURFACE_PATTERN.search(text) + ) + + +def _public_label(value: object) -> tuple[str, bool]: + """Return a label that may be published, and whether it was redacted. + + A Goal, agent or surface identifier is free-form text in the registry: an + operator can name a Goal after a directory or paste a token-shaped value. + Doctor output also serves ``--format json`` and pasted transcripts, and the + public-output boundary rejects both shapes, so an unsafe identifier would + otherwise abort the whole run instead of naming the lane. Keep a digest of + the exact identifier (stable across runs and distinct per identifier) and, + when the last path segment is itself safe, append it so the operator can + still recognize the lane. + """ + + text = str(value or "").strip() + if not text: + return "", False + if not _unsafe_label(text): + return text, False + digest = hashlib.sha256(text.encode("utf-8", "surrogatepass")).hexdigest()[:10] + tail = text.replace("\\", "/").rsplit("/", 1)[-1].strip() + safe_tail = tail if _SAFE_LABEL_TAIL.fullmatch(tail) and not _unsafe_label(tail) else "" + marker = f"" + return (f"{marker}:{safe_tail}" if safe_tail else marker), True + + +def _lane_segment(text: str) -> str: + """Spell one label component so ``/`` keeps separating exactly three parts. + + Two different registries can spell ``goal=a`` + ``agent=b/c`` and + ``goal=a/b`` + ``agent=c``; joined verbatim both read ``a/b/c`` and one + silent lane would hide behind the other. Percent-encoding the separator (and + the escape itself) keeps the label reversible and unique. + """ + + return text.replace("%", "%25").replace("/", "%2F") + + +def _lane_identity(goal_id: str, agent_id: object, host_surface: object) -> str: + return "/".join( + _lane_segment(str(part or "")) for part in (goal_id, agent_id, host_surface) + ) + + +def _lane_payload(goal_id: str, row: Mapping[str, Any]) -> dict[str, Any]: + window = row.get("delivery_window") + window = window if isinstance(window, Mapping) else {} + goal_label, goal_redacted = _public_label(goal_id) + agent_label, agent_redacted = _public_label(row.get("agent_id")) + surface_label, surface_redacted = _public_label(row.get("host_surface")) + lane: dict[str, Any] = { + "lane": _lane_identity(goal_label, agent_label, surface_label), + "goal_id": goal_label, + "agent_id": agent_label, + "host_surface": surface_label, + "thread_state": row.get("state"), + "window_state": window.get("state") or HostDeliveryWindowState.UNKNOWN.value, + } + if goal_redacted or agent_redacted or surface_redacted: + # The digest carries identity; this flag tells a reader the shown name + # is not the registry spelling, so it does not grep for it in the store. + lane["label_redacted"] = True + for key in ( + "last_observed_at", + "age_hours", + "expected_interval_minutes", + "window_minutes", + "source", + "reason", + "delivery_evidence_at", + ): + if window.get(key) is not None: + lane[key] = window[key] + if lane["window_state"] in { + HostDeliveryWindowState.MISSING.value, + HostDeliveryWindowState.UNKNOWN.value, + }: + # Why the lane could not be measured, so a reader does not go looking + # for an absent automation that was never installed for this surface. + reason = window.get("reason") + if lane["thread_state"] == HostThreadState.ARCHIVED.value: + # The host's own record says this thread is archived, so its + # rollout holds no comparable tick. That is not the "unparseable + # observation" the window layer infers from an empty timestamp, and + # naming it keeps the operator off the wrong trail. + reason = "thread_archived" + lane["diagnosis"] = { + "code": HOST_PROMPT_DELIVERY_UNVERIFIED, + "state": lane["window_state"], + "reason": reason, + } + if lane["window_state"] == HostDeliveryWindowState.STALE.value: + lane["diagnosis"] = { + "code": HOST_PROMPT_DELIVERY_MISSED, + "state": HostDeliveryWindowState.STALE.value, + # The last tick the host did record: without it the operator cannot + # tell how long the lane has been silent. + "last_observed_at": window.get("last_observed_at"), + "age_hours": window.get("age_hours"), + "window_minutes": window.get("window_minutes"), + "expected_interval_minutes": window.get("expected_interval_minutes"), + "source": window.get("source"), + } + return lane + + +def collect_host_delivery_diagnosis( + goals: Iterable[Mapping[str, Any]], + *, + observers: Mapping[str, HostThreadObserver], + expectations: HostDeliveryExpectationProvider, + now: datetime | None = None, + tolerance: int = DEFAULT_DELIVERY_WINDOW_TOLERANCE, + max_lanes: int = MAX_DIAGNOSED_LANES, + evidence: HostDeliveryEvidenceProvider | None = None, +) -> dict[str, Any]: + """Report one typed delivery window per bound host lane of ``goals``. + + ``goals`` is the registry view the caller already read; this function never + writes it. Stopped goals are skipped: their automations are not a live + promise, so a quiet lane there is not a missed delivery. + + ``evidence`` names the most recent tick each lane's scheduled prompt + produced. When it is given, recent activity alone no longer reads ``fresh``: + an empty turn or a hand-written message leaves the lane unverified while its + activity time is still reported. + """ + + if max_lanes < 1: + raise ValueError("max_lanes must be at least one") + surfaces = tuple(observers) + projection_goals: list[dict[str, Any]] = [] + stopped = 0 + lanes_seen = 0 + truncated = False + unreadable_activation = 0 + unmeasured_bindings = 0 + ambiguous_by_goal: dict[str, set[tuple[str, str]]] = {} + for goal in goals: + if not isinstance(goal, Mapping) or not str(goal.get("id") or "").strip(): + continue + try: + state = goal_activation_state(dict(goal)) + except ValueError: + # An unreadable activation record is not this check's finding; the + # registry and activation readers already report it. Count the Goal + # so the verdict below does not present its lanes as measured. + unreadable_activation += 1 + continue + if state is GoalActivationState.STOPPED: + stopped += 1 + continue + local, unmeasured = _observed_bindings(goal, surfaces) + unmeasured_bindings += unmeasured + if not local: + continue + goal_id = str(goal["id"]) + # Resolve identity over every binding this Goal records, then trim what + # the run reads. + ambiguous_by_goal.setdefault(goal_id, set()).update(_ambiguous_lanes(local)) + remaining = max_lanes - lanes_seen + if remaining <= 0: + truncated = True + break + if len(local) > remaining: + local = local[:remaining] + truncated = True + lanes_seen += len(local) + projection_goals.append( + {"id": goal_id, "coordination": {"thread_agent_bindings": local}} + ) + + payload: dict[str, Any] = {"run_history": {"goals": projection_goals}} + observed_at = now + if projection_goals: + attach_host_thread_activity(payload, observers=observers, now=observed_at) + attach_host_delivery_windows( + payload, + expectations=expectations, + tolerance=tolerance, + now=observed_at, + evidence=evidence, + ambiguous_lanes=ambiguous_by_goal, + ) + + lanes: list[dict[str, Any]] = [] + seen: set[tuple[str, str, str]] = set() + incomplete_goals = 0 + for goal in payload["run_history"]["goals"]: + activity = goal.get("host_thread_activity") + threads = activity.get("threads") if isinstance(activity, Mapping) else None + if isinstance(activity, Mapping) and ( + activity.get("completeness") + == HostThreadObservationCompleteness.INCOMPLETE.value + ): + # The shared observer keeps a per-Goal binding bound. A Goal past it + # is reported here as truncated rather than as fully observed: a + # silent lane can hide among the bindings it did not read. + incomplete_goals += 1 + for row in threads if isinstance(threads, list) else []: + if not isinstance(row, Mapping): + continue + # Dedupe on the exact identity parts, not on the joined label: two + # different registries can spell ids whose concatenation collides + # (``a`` + ``b/c`` and ``a/b`` + ``c``). + identity = ( + str(goal.get("id") or ""), + str(row.get("agent_id") or ""), + str(row.get("host_surface") or ""), + ) + # Two bindings for one agent on one surface are one lane whose + # canonical thread is ambiguous; both resolve to the same window, so + # a second row would only duplicate the label an operator greps. + if identity in seen: + continue + seen.add(identity) + lanes.append(_lane_payload(identity[0], row)) + + counts = {state.value: 0 for state in _LOCAL_OBSERVED_STATES} + for lane in lanes: + if lane["window_state"] in counts: + counts[lane["window_state"]] += 1 + stale = [lane for lane in lanes if lane["window_state"] == HostDeliveryWindowState.STALE.value] + unverified = [ + lane + for lane in lanes + if lane["window_state"] in { + HostDeliveryWindowState.MISSING.value, + HostDeliveryWindowState.UNKNOWN.value, + } + ] + bounded = truncated or bool(incomplete_goals) + # Every lane this run did not read is a lane that could be silent. + unmeasured = bounded or bool(unmeasured_bindings) or bool(unreadable_activation) + incomplete_reason = "scan_truncated" if bounded else "unmeasured_lane" + if not lanes: + # A scan that read nothing proves nothing: a lane may sit past the bound + # or past the per-Goal binding cap this run did not read. + status, reason = "not_applicable", ( + incomplete_reason if unmeasured else "no_bound_host_lane" + ) + elif stale: + status, reason = "stale", HOST_PROMPT_DELIVERY_MISSED + elif unverified: + status, reason = "unverified", "no_comparable_tick" + elif unmeasured: + # Everything read is inside its window, but the unread lanes could be + # silent. Reporting `fresh` here would claim coverage this run did not + # have. + status, reason = "unverified", incomplete_reason + else: + status, reason = "fresh", None + diagnosis = { + "schema_version": HOST_DELIVERY_DIAGNOSIS_SCHEMA_VERSION, + "window_schema_version": HOST_DELIVERY_WINDOW_SCHEMA_VERSION, + "observed_at": (observed_at or datetime.now(timezone.utc)).isoformat(), + "status": status, + "reason": reason, + "lane_count": len(lanes), + "counts": counts, + "truncated": bounded, + "incomplete_goals": incomplete_goals, + "unmeasured_bindings": unmeasured_bindings, + "unreadable_activation_goals": unreadable_activation, + "per_goal_binding_cap": MAX_OBSERVED_THREADS_PER_GOAL, + "stale_lanes": [lane["lane"] for lane in stale], + "unverified_lanes": [lane["lane"] for lane in unverified], + "skipped_stopped_goals": stopped, + "tolerance": tolerance, + "lanes": lanes, + } + return _publishable(diagnosis) + + +def _publishable(diagnosis: dict[str, Any]) -> dict[str, Any]: + """Return ``diagnosis`` only if the public-output boundary accepts it. + + Lane labels are sanitized before they are built, so this is a last-resort + guard against a field this module did not anticipate. An optional check + must never take the whole ``doctor`` run down: on a remaining violation the + verdict and per-state counts survive and only the identifying names are + withheld, so an operator still sees that a lane is silent. + """ + + try: + validate_public_safe_value(diagnosis) + return diagnosis + except ValueError: + withheld = dict(diagnosis) + withheld["lanes"] = [] + withheld["stale_lanes"] = [] + withheld["unverified_lanes"] = [] + withheld["labels_withheld"] = True + validate_public_safe_value(withheld) + return withheld + + +def collect_registry_host_delivery_diagnosis( + *, + registry_path: Path | str, + max_lanes: int = MAX_DIAGNOSED_LANES, +) -> dict[str, Any]: + """Read the registry and report the delivery window of each bound lane. + + The registry is an input the caller already trusts; a missing or unreadable + registry is reported as ``not_applicable``/``registry_unavailable`` so a + broken workspace cannot turn this optional check into a doctor failure. + """ + + from ...registry import registry_goals + from ..projects.registry_codec import ProjectRegistryProtocolError, load_registry + + try: + registry = load_registry(Path(registry_path)) + except ProjectRegistryProtocolError: + # The file is readable; this build just cannot decode it. Telling the + # operator the registry is unavailable would send them looking for a + # missing file instead of the upgrade the reader asked for. + return _empty_diagnosis("registry_requires_upgrade") + except (OSError, ValueError): + return _empty_diagnosis("registry_unavailable") + goals = registry_goals(registry) + if not goals: + return _empty_diagnosis("registry_empty") + + from ...codex_app_thread_activity import ( + CODEX_APP_BINDING_SURFACE, + codex_delivery_evidence, + codex_delivery_expectations, + codex_thread_observers, + ) + + # Only an installed app automation carries a cadence. A Goal bound to a CLI + # TUI or IDE thread keeps its own loop, so reporting such a lane here would + # permanently read "unverified" and teach operators to ignore the check. + observers = codex_thread_observers() + observers = ( + {CODEX_APP_BINDING_SURFACE: observers[CODEX_APP_BINDING_SURFACE]} + if CODEX_APP_BINDING_SURFACE in observers + else {} + ) + return collect_host_delivery_diagnosis( + goals, + observers=observers, + expectations=codex_delivery_expectations, + evidence=codex_delivery_evidence, + max_lanes=max_lanes, + ) + + +def _empty_diagnosis(reason: str) -> dict[str, Any]: + return { + "schema_version": HOST_DELIVERY_DIAGNOSIS_SCHEMA_VERSION, + "window_schema_version": HOST_DELIVERY_WINDOW_SCHEMA_VERSION, + "observed_at": datetime.now(timezone.utc).isoformat(), + "status": "not_applicable", + "reason": reason, + "lane_count": 0, + "counts": {state.value: 0 for state in _LOCAL_OBSERVED_STATES}, + "stale_lanes": [], + "unverified_lanes": [], + "truncated": False, + "incomplete_goals": 0, + "unmeasured_bindings": 0, + "unreadable_activation_goals": 0, + "per_goal_binding_cap": MAX_OBSERVED_THREADS_PER_GOAL, + "skipped_stopped_goals": 0, + "lanes": [], + } + + +def collect_host_delivery_diagnosis_route( + *, + registry_path: Path, + route_status: str, + max_lanes: int = MAX_DIAGNOSED_LANES, +) -> dict[str, Any]: + """Doctor entry point: skip a route the local-state reader already refused.""" + + if route_status in {"conflict", "invalid"}: + return _empty_diagnosis("local_state_route_unresolved") + return collect_registry_host_delivery_diagnosis( + registry_path=registry_path, max_lanes=max_lanes + ) + + +HOST_DELIVERY_CHECK_ID = "host_prompt_delivery_windows" + + +def host_delivery_diagnosis_check(diagnosis: Mapping[str, Any]) -> dict[str, Any]: + """Project one diagnosis onto the doctor check vocabulary. + + Two outcomes fail the check: a missed window, and a run that could not + measure every lane. A lane with no comparable tick is reported as unverified + in the detail only: absence of a receipt is not proof the host stopped + delivering, and claiming a fault would teach operators to ignore this check + on the first install. + """ + + counts = diagnosis.get("counts") or {} + status = str(diagnosis.get("status") or "not_applicable") + # A run that skipped lanes cannot claim the workspace is observed. That is a + # gap in this readback rather than a host fault, so it is named in the + # detail and turns the optional check red without failing `doctor`. + coverage_complete = not any( + diagnosis.get(key) + for key in ("truncated", "unmeasured_bindings", "unreadable_activation_goals") + ) + detail = ( + f"status={status};reason={diagnosis.get('reason')};" + f"stale={counts.get('stale', 0)};fresh={counts.get('fresh', 0)};" + f"unverified={counts.get('missing', 0) + counts.get('unknown', 0)};" + f"lanes={diagnosis.get('lane_count', 0)};" + f"truncated={str(bool(diagnosis.get('truncated'))).lower()};" + f"incomplete_goals={diagnosis.get('incomplete_goals', 0)};" + f"unmeasured_bindings={diagnosis.get('unmeasured_bindings', 0)};" + f"unreadable_activation_goals=" + f"{diagnosis.get('unreadable_activation_goals', 0)}" + ) + stale = diagnosis.get("stale_lanes") or [] + if stale: + last_ticks = { + lane.get("lane"): lane.get("last_observed_at") + for lane in diagnosis.get("lanes") or [] + if lane.get("window_state") == HostDeliveryWindowState.STALE.value + } + detail += ";missed=" + ",".join( + f"{lane}@{last_ticks.get(lane) or 'unknown'}" for lane in stale[:5] + ) + return { + "id": HOST_DELIVERY_CHECK_ID, + "required": False, + "ok": status != "stale" and coverage_complete, + "detail": detail, + } diff --git a/loopx/control_plane/agents/host_thread_activity.py b/loopx/control_plane/agents/host_thread_activity.py index 852f94eaec..18aab46c82 100644 --- a/loopx/control_plane/agents/host_thread_activity.py +++ b/loopx/control_plane/agents/host_thread_activity.py @@ -10,7 +10,7 @@ from __future__ import annotations from collections.abc import Callable, Iterable, Mapping -from dataclasses import dataclass +from dataclasses import dataclass, replace from datetime import datetime, timezone from enum import Enum from typing import Any @@ -158,6 +158,10 @@ class HostDeliveryWindowUnknownReason(str, Enum): NO_EXPECTATION = "no_expectation" NO_OBSERVATION = "no_observation" UNPARSEABLE_OBSERVATION = "unparseable_observation" + # The lane moved recently, but nothing ties that activity to a scheduled + # prompt. A hand-written message or an empty turn leaves the same trace as + # a delivered tick; calling that `fresh` would hide a silent automation. + UNVERIFIED_ACTIVITY = "unverified_activity" _REASONED_DELIVERY_WINDOW_STATES = frozenset( @@ -212,6 +216,9 @@ class HostDeliveryWindow: window_minutes: int | None = None tolerance: int | None = None source: str | None = None + # The most recent tick that a scheduled prompt, not just any activity, + # produced. Present only when the caller asked for delivery evidence. + delivery_evidence_at: str | None = None def __post_init__(self) -> None: reasoned = self.state in _REASONED_DELIVERY_WINDOW_STATES @@ -242,6 +249,7 @@ def to_payload(self) -> dict[str, Any]: "window_minutes": self.window_minutes, "tolerance": self.tolerance, "source": self.source, + "delivery_evidence_at": self.delivery_evidence_at, } return {key: value for key, value in payload.items() if value is not None} @@ -265,11 +273,19 @@ def build_host_delivery_window( *, now: datetime | None = None, tolerance: int = DEFAULT_DELIVERY_WINDOW_TOLERANCE, + delivered_at: str | None = None, + require_evidence: bool = False, ) -> HostDeliveryWindow: """Compare one observed lane against the cadence it is expected to keep. Absence of evidence is never reported as healthy: an unobserved lane is ``missing`` and an incomputable window is ``unknown``. Neither is ``fresh``. + + ``require_evidence`` narrows ``fresh`` to activity a scheduled prompt + produced: ``delivered_at`` is the most recent tick the caller could attribute + to this lane's automation. A lane with recent activity and no such tick is + ``unknown``/``unverified_activity`` while keeping its activity time, so an + operator still sees the last thing the host recorded. """ if tolerance < 1: @@ -291,12 +307,27 @@ def build_host_delivery_window( window_minutes = expectation.expected_interval_minutes * tolerance reference = now or datetime.now(timezone.utc) age_seconds = max(0, int((reference - observed).total_seconds())) + inside_window = age_seconds <= window_minutes * 60 + evidence = _parse_observation_time(delivered_at) if require_evidence else None + evidenced = ( + evidence is not None + and max(0, int((reference - evidence).total_seconds())) <= window_minutes * 60 + ) + state = HostDeliveryWindowState.STALE + reason: HostDeliveryWindowUnknownReason | None = None + if inside_window: + if require_evidence and not evidenced: + # The thread moved, but nothing ties that movement to the installed + # prompt; the activity time is kept for the operator. + state, reason = ( + HostDeliveryWindowState.UNKNOWN, + HostDeliveryWindowUnknownReason.UNVERIFIED_ACTIVITY, + ) + else: + state = HostDeliveryWindowState.FRESH return HostDeliveryWindow( - state=( - HostDeliveryWindowState.FRESH - if age_seconds <= window_minutes * 60 - else HostDeliveryWindowState.STALE - ), + state=state, + reason=reason, last_observed_at=activity.last_event_at, age_seconds=age_seconds, age_hours=round(age_seconds / 3600, 2), @@ -304,6 +335,7 @@ def build_host_delivery_window( window_minutes=window_minutes, tolerance=tolerance, source=expectation.source, + delivery_evidence_at=evidence.isoformat() if evidence is not None else None, ) @@ -313,6 +345,12 @@ def build_host_delivery_window( [Iterable[HostDeliveryScope]], Mapping[HostDeliveryScope, HostDeliveryExpectation] ] +# Maps bound lanes to the most recent tick a scheduled prompt produced; lanes it +# cannot attribute are omitted or mapped to ``None`` rather than guessed. +HostDeliveryEvidenceProvider = Callable[ + [Iterable[HostDeliveryScope]], Mapping[HostDeliveryScope, str | None] +] + def _bound_thread_ids(goal: Mapping[str, Any]) -> dict[tuple[str, str], str | None]: """Map each ``(agent, surface)`` lane of a Goal to its canonical thread. @@ -349,6 +387,8 @@ def attach_host_delivery_windows( expectations: HostDeliveryExpectationProvider, tolerance: int = DEFAULT_DELIVERY_WINDOW_TOLERANCE, now: datetime | None = None, + evidence: HostDeliveryEvidenceProvider | None = None, + ambiguous_lanes: Mapping[str, set[tuple[str, str]]] | None = None, ) -> None: """Add ``delivery_window`` to each observed lane of ``host_thread_activity``. @@ -357,6 +397,12 @@ def attach_host_delivery_windows( canonical binding the Goal records, so a cadence installed for another thread of the same Goal is not read as this lane's. A lane the expectation provider cannot resolve is reported as ``unknown``, never as healthy. + + ``evidence``, when given, names the most recent tick a scheduled prompt + produced for each lane; ``fresh`` then requires one inside the window. + ``ambiguous_lanes`` carries the lanes the caller resolved over the Goal's + complete binding list: a lane naming two threads has no canonical identity, + so trimming the observed bindings must not let the survivor look unique. """ run_history = status_payload.get("run_history") @@ -385,14 +431,33 @@ def attach_host_delivery_windows( if scope is not None: scopes.append(scope) resolved = expectations(scopes) if scopes else {} + delivered = evidence(scopes) if evidence is not None and scopes else {} for goal_id, rows, bound in rows_by_goal: + ambiguous = (ambiguous_lanes or {}).get(goal_id) or set() for row in rows: scope = _scope_from_row(goal_id, row, bound) + if (row.get("agent_id"), row.get("host_surface")) in ambiguous: + # Keep the observed tick and cadence the lane still carries, and + # only refuse to call the lane measured. + measured = build_host_delivery_window( + _activity_from_row(row), + resolved.get(scope) if scope is not None else None, + now=now, + tolerance=tolerance, + ) + row["delivery_window"] = replace( + measured, + state=HostDeliveryWindowState.UNKNOWN, + reason=HostDeliveryWindowUnknownReason.NO_EXPECTATION, + ).to_payload() + continue row["delivery_window"] = build_host_delivery_window( _activity_from_row(row), resolved.get(scope) if scope is not None else None, now=now, tolerance=tolerance, + delivered_at=delivered.get(scope) if scope is not None else None, + require_evidence=evidence is not None, ).to_payload() diff --git a/loopx/doctor.py b/loopx/doctor.py index 5756ef0d1b..e8c9545c2b 100644 --- a/loopx/doctor.py +++ b/loopx/doctor.py @@ -1045,6 +1045,11 @@ def collect_doctor( ), } default_global_registry = global_registry_path(selected_runtime_root) + # The caller may have selected its registry explicitly; every diagnostic + # below reads that same file, so a moved registry is not reported empty. + diagnostic_registry_path = ( + registry_path if registry_path is not None else default_global_registry + ) global_registry_writability = ( probe_registry_write_path(default_global_registry, create_parent=True) if local_state_route["status"] not in {"conflict", "invalid"} @@ -1052,13 +1057,14 @@ def collect_doctor( ) runtime_projection_routes = ( collect_runtime_projection_route_diagnostics( - registry_path=default_global_registry, + registry_path=diagnostic_registry_path, runtime_root=selected_runtime_root, ) - if default_global_registry.exists() and local_state_route["status"] not in {"conflict", "invalid"} + if diagnostic_registry_path.exists() + and local_state_route["status"] not in {"conflict", "invalid"} else { "schema_version": "runtime_projection_route_diagnostics_v0", - "registry": str(default_global_registry.resolve()), + "registry": str(diagnostic_registry_path.resolve()), "runtime_root": str(selected_runtime_root.resolve()), "goal_filter": None, "activation_state_filter": None, @@ -1073,6 +1079,15 @@ def collect_doctor( capture_host_diagnostics_detail, collect_capture_host_diagnostics, ) + from .control_plane.agents.host_delivery_diagnosis import ( + collect_host_delivery_diagnosis_route, + host_delivery_diagnosis_check, + ) + + host_delivery_diagnosis = collect_host_delivery_diagnosis_route( + registry_path=diagnostic_registry_path, + route_status=str(local_state_route["status"]), + ) decision_context_capture = collect_capture_host_diagnostics(selected_runtime_root) typescript_control_plane = collect_effect_runtime_readiness(deep=deep) @@ -1221,6 +1236,7 @@ def collect_doctor( sort_keys=True, ), }, + host_delivery_diagnosis_check(host_delivery_diagnosis), { "id": "decision_context_capture_hosts_healthy", "required": False, @@ -1289,6 +1305,7 @@ def collect_doctor( "global_registry_writability": global_registry_writability, "runtime_projection_routes": runtime_projection_routes, "decision_context_capture": decision_context_capture, + "host_prompt_delivery": host_delivery_diagnosis, "typescript_control_plane": typescript_control_plane, "install_freshness": install_freshness, "upgrade_hint": install_freshness, @@ -1454,6 +1471,28 @@ def render_doctor_markdown(payload: dict[str, Any]) -> str: if isinstance(typescript_control_plane.get("runtime_lifecycle"), dict) else {} ) + # Installation-only scope never reads host state, so the section is absent + # there rather than rendered as an empty value a reader would misread. + host_prompt_delivery = ( + payload.get("host_prompt_delivery") + if isinstance(payload.get("host_prompt_delivery"), dict) + else None + ) + host_prompt_delivery_lines: list[str] = [] + if host_prompt_delivery: + stale_ticks = [ + str(lane.get("last_observed_at")) + for lane in host_prompt_delivery.get("lanes") or [] + if isinstance(lane, dict) and lane.get("window_state") == "stale" + ] + host_prompt_delivery_lines = [ + f"- host_prompt_delivery: `{host_prompt_delivery.get('status')}`" + f" (reason=`{host_prompt_delivery.get('reason')}`," + f" lanes=`{host_prompt_delivery.get('lane_count')}`," + f" stale=`{(host_prompt_delivery.get('counts') or {}).get('stale')}`)" + f" last_ticks=`{','.join(stale_ticks) or 'none'}`" + f" labels_withheld=`{bool(host_prompt_delivery.get('labels_withheld'))}`" + ] lines = [ "# LoopX Doctor", "", @@ -1479,6 +1518,7 @@ def render_doctor_markdown(payload: dict[str, Any]) -> str: f" (registry=`{(payload.get('runtime_projection_routes') or {}).get('registry')}`," f" goals=`{(payload.get('runtime_projection_routes') or {}).get('goal_count')}`," f" counts=`{json.dumps((payload.get('runtime_projection_routes') or {}).get('counts') or {}, sort_keys=True)}`)", + *host_prompt_delivery_lines, f"- decision_context_capture_hosts_healthy: `{(payload.get('decision_context_capture') or {}).get('healthy')}`" f" (hosts=`{(payload.get('decision_context_capture') or {}).get('host_count')}`," f" unhealthy=`{(payload.get('decision_context_capture') or {}).get('unhealthy_count')}`)", diff --git a/tests/test_doctor_delivery_window.py b/tests/test_doctor_delivery_window.py new file mode 100644 index 0000000000..01edc46bcc --- /dev/null +++ b/tests/test_doctor_delivery_window.py @@ -0,0 +1,1463 @@ +"""Doctor reports a missed Codex App delivery window as a typed diagnosis. + +The Goal's own records cannot tell "waiting" from "the host stopped delivering +the scheduled prompt". This readback measures each bound lane against the +cadence its installed automation asks for, so the operator sees the silent lane +on the next ``loopx doctor`` instead of days later. +""" + +from __future__ import annotations + +import json +import sqlite3 +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest + +import loopx.codex_app_thread_activity as codex_activity +from loopx import doctor +from loopx.control_plane.agents.host_delivery_diagnosis import ( + HOST_DELIVERY_CHECK_ID, + HOST_PROMPT_DELIVERY_MISSED, + HOST_PROMPT_DELIVERY_UNVERIFIED, + collect_host_delivery_diagnosis, +) +from loopx.control_plane.agents.host_thread_activity import ( + HostDeliveryExpectation, + HostDeliveryScope, + HostThreadActivity, + HostThreadState, +) +from loopx.codex_app_thread_activity import observe_codex_threads + + +def _ts(moment: datetime) -> str: + return moment.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z" + + +def _automation_prompt(goal_id: str, agent_id: str) -> str: + return f"Advance `{goal_id}` from active state. Agent: `{agent_id}`." + + +def _user_message(timestamp: str, text: str) -> dict[str, object]: + """A user-authored message record, the shape a delivered prompt leaves.""" + + return { + "timestamp": timestamp, + "type": "response_item", + "payload": { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": text}], + "internal_chat_message_metadata_passthrough": { + "content_item_kinds": ["user.text"], + "content_item_metadata": [{"provenance": {"type": "user"}}], + }, + }, + } + + +def _event(timestamp: str, kind: str, **payload: object) -> dict[str, object]: + return { + "timestamp": timestamp, + "type": "event_msg", + "payload": {"type": kind, **payload}, + } + + +def _task_started( + timestamp: str, *, trigger: str = "automation_heartbeat", **attribution: object +) -> dict[str, object]: + """A turn the host opens, with the attribution a real rollout carries.""" + + return _event( + timestamp, + "task_started", + turn_attribution={"turn_trigger": trigger, **attribution}, + ) + + +def _observed_task_started(timestamp: str, trigger: str) -> dict[str, object]: + """A ``task_started`` with the surrounding fields a current rollout records. + + Trimmed of content, but keeping the sibling fields the host writes next to + ``turn_attribution`` so a check that silently depends on their absence shows + up here. + """ + + turn = "01a21330-2287-7830-bf82-d28412f35c23" + return _event( + timestamp, + "task_started", + turn_attribution={ + "turn_id": turn, + "turn_trigger": trigger, + "parent_turn_id": None, + "initiating_agent_path": None, + "root_turn_id": turn, + }, + turn_id=turn, + root_turn_id=turn, + started_at=1795618420, + model_context_window=258400, + collaboration_mode_kind="default", + ) + + +class _CodexHome: + def __init__(self, root: Path) -> None: + self.root = root + (root / "sessions").mkdir(parents=True) + self.db = root / "state_5.sqlite" + with sqlite3.connect(self.db) as connection: + connection.execute( + "CREATE TABLE threads (id TEXT PRIMARY KEY, rollout_path TEXT, archived INTEGER)" + ) + + def thread(self, thread_id: str, records: list[dict[str, object]]) -> Path: + if not records or records[0].get("type") != "session_meta": + records = [ + { + "timestamp": records[0]["timestamp"] if records else "2026-09-25T09:59:00.000Z", + "type": "session_meta", + "payload": {"id": thread_id}, + }, + *records, + ] + path = self.root / "sessions" / f"rollout-{thread_id}.jsonl" + path.write_text( + "".join(json.dumps(record) + "\n" for record in records), encoding="utf-8" + ) + with sqlite3.connect(self.db) as connection: + connection.execute( + "INSERT INTO threads VALUES (?, ?, ?)", (thread_id, str(path), 0) + ) + return path + + def automation( + self, + automation_id: str, + *, + goal_id: str, + agent_id: str, + target_thread_id: str, + rrule: str = "RRULE:FREQ=MINUTELY;INTERVAL=20", + status: str = "ACTIVE", + ) -> None: + path = self.root / "automations" / automation_id / "automation.toml" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text( + f'version = 1\nid = "{automation_id}"\nkind = "heartbeat"\n' + f'status = "{status}"\nrrule = "{rrule}"\n' + f'target_thread_id = "{target_thread_id}"\n' + f'prompt = "{_automation_prompt(goal_id, agent_id)}"\n', + encoding="utf-8", + ) + + +@pytest.fixture(autouse=True) +def _fresh_rollout_cache() -> None: + codex_activity._rollout_cache.clear() + + +def _goal(goal_id: str = "release-work", *, thread_id: str = "thread-lane") -> dict: + return { + "id": goal_id, + "coordination": { + "thread_agent_bindings": [ + {"agent_id": "operations", "host_surface": "codex-app", "thread_id": thread_id} + ] + }, + } + + +def _observers_and_expectations(interval_minutes: int = 20): + def expect(scopes): + return { + scope: HostDeliveryExpectation( + expected_interval_minutes=interval_minutes, source="codex_app_automation_rrule" + ) + for scope in scopes + if isinstance(scope, HostDeliveryScope) + } + + return ( + {"codex-app": lambda ids: observe_codex_threads(ids, homes=[])}, + expect, + ) + + +def test_a_lane_past_its_window_is_reported_with_the_last_observed_tick(tmp_path: Path) -> None: + home = _CodexHome(tmp_path / ".codex") + observed = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + home.thread("thread-lane", [_event(_ts(observed), "task_complete")]) + now = observed + timedelta(hours=3) + observers = {"codex-app": lambda ids: observe_codex_threads(ids, homes=[home.root])} + + diagnosis = collect_host_delivery_diagnosis( + [_goal()], + observers=observers, + expectations=lambda scopes: { + scope: HostDeliveryExpectation(20, "codex_app_automation_rrule") for scope in scopes + }, + now=now, + ) + + assert diagnosis["status"] == "stale" + assert diagnosis["reason"] == HOST_PROMPT_DELIVERY_MISSED + assert diagnosis["counts"]["stale"] == 1 + [lane] = diagnosis["lanes"] + assert lane["lane"] == "release-work/operations/codex-app" + assert lane["window_state"] == "stale" + assert lane["diagnosis"]["code"] == HOST_PROMPT_DELIVERY_MISSED + assert lane["diagnosis"]["last_observed_at"] == "2026-09-25T10:00:00.000Z" + assert lane["diagnosis"]["age_hours"] == 3.0 + assert lane["diagnosis"]["window_minutes"] == 40 + + +def test_a_lane_inside_its_window_is_quiet(tmp_path: Path) -> None: + home = _CodexHome(tmp_path / ".codex") + observed = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + home.thread("thread-lane", [_event(_ts(observed), "task_complete")]) + observers = {"codex-app": lambda ids: observe_codex_threads(ids, homes=[home.root])} + + diagnosis = collect_host_delivery_diagnosis( + [_goal()], + observers=observers, + expectations=lambda scopes: { + scope: HostDeliveryExpectation(20, "codex_app_automation_rrule") for scope in scopes + }, + now=observed + timedelta(minutes=25), + ) + + assert diagnosis["status"] == "fresh" + assert diagnosis["reason"] is None + assert diagnosis["stale_lanes"] == [] + assert "diagnosis" not in diagnosis["lanes"][0] + + +def _proof(tmp_path: Path, records: list[dict[str, object]], *, now: datetime): + home = _CodexHome(tmp_path / ".codex") + home.thread("thread-lane", records) + home.automation( + "nightly", goal_id="release-work", agent_id="operations", target_thread_id="thread-lane" + ) + return home, collect_host_delivery_diagnosis( + [_goal()], + observers={"codex-app": lambda ids: observe_codex_threads(ids, homes=[home.root])}, + expectations=lambda scopes: { + scope: HostDeliveryExpectation(20, "codex_app_automation_rrule") for scope in scopes + }, + evidence=lambda scopes: codex_activity.codex_delivery_evidence(scopes, homes=[home.root]), + now=now, + ) + + +def test_a_recent_empty_turn_is_unverified_and_keeps_its_activity_time( + tmp_path: Path, +) -> None: + # The empty turn #3927 describes: the host started and finished a turn with + # no message at all. Nothing in it can be attributed to the scheduled prompt. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _event(_ts(recent), "task_started"), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + assert lane["last_observed_at"] == _ts(recent + timedelta(seconds=30)) + assert lane["diagnosis"]["code"] == HOST_PROMPT_DELIVERY_UNVERIFIED + assert diagnosis["status"] == "unverified" + assert diagnosis["stale_lanes"] == [] + + +def test_a_recent_manual_message_is_not_a_scheduled_delivery(tmp_path: Path) -> None: + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent), trigger="composer"), + _user_message(_ts(recent), "can you also rename the release notes?"), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + assert lane["last_observed_at"] == _ts(recent + timedelta(seconds=30)) + + +def test_a_delivered_scheduled_prompt_is_fresh(tmp_path: Path) -> None: + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent)), + _user_message(_ts(recent), _automation_prompt("release-work", "operations")), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + assert diagnosis["status"] == "fresh" + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "fresh" + assert datetime.fromisoformat(lane["delivery_evidence_at"]) == recent + + +def test_a_manual_retelling_of_the_prompt_is_not_a_scheduled_delivery( + tmp_path: Path, +) -> None: + # The prompt text is public in the manifest; a person can paste it, and a + # workspace whose automation is broken can look busy because of it. Only the + # host's own turn attribution proves the scheduler delivered anything. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent), trigger="composer"), + _user_message(_ts(recent), _automation_prompt("release-work", "operations")), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + assert lane["last_observed_at"] == _ts(recent + timedelta(seconds=30)) + assert "delivery_evidence_at" not in lane + assert diagnosis["status"] == "unverified" + assert diagnosis["stale_lanes"] == [] + + +def test_a_manual_retelling_of_the_envelope_is_not_a_scheduled_delivery( + tmp_path: Path, +) -> None: + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent), trigger="composer"), + _user_message( + _ts(recent), + _heartbeat_envelope(_automation_prompt("release-work", "operations")), + ), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + assert "delivery_evidence_at" not in lane + + +def test_a_heartbeat_turn_carrying_another_automations_envelope_is_unverified( + tmp_path: Path, +) -> None: + # Two automations can hold the same body in different envelopes; the id is + # what says whose tick this is. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + envelope = _heartbeat_envelope( + _automation_prompt("release-work", "operations") + ).replace( + "nightly", + "sidecar", + ) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent)), + _user_message(_ts(recent), envelope), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + assert "delivery_evidence_at" not in lane + + +def test_a_heartbeat_trigger_with_a_non_user_transport_is_unverified( + tmp_path: Path, +) -> None: + # The trigger alone is not the contract: the same routing contract requires a + # ``heartbeat_xml`` user message, so a turn that says it delivered the prompt + # as tool output is not this lane's scheduled delivery. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent), delivery_kind="tool_output"), + _user_message(_ts(recent), _automation_prompt("release-work", "operations")), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + + +def test_a_turn_without_attribution_cannot_prove_a_delivery(tmp_path: Path) -> None: + # Older rollouts and the resumed record shape report no attribution at all; + # text inside them stays a pointer until the host names the trigger. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _event(_ts(recent), "task_started"), + _user_message(_ts(recent), _automation_prompt("release-work", "operations")), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + + +def test_an_envelope_without_an_automation_id_falls_back_to_the_body( + tmp_path: Path, +) -> None: + # Older envelopes name no installation; the attributed turn plus the body + # still prove this lane's tick received its installed prompt. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + envelope = _heartbeat_envelope( + _automation_prompt("release-work", "operations") + ).replace(" nightly\n", "") + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent)), + _user_message(_ts(recent), envelope), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + assert diagnosis["status"] == "fresh" + assert diagnosis["lanes"][0]["window_state"] == "fresh" + + +def test_an_envelope_with_an_unreadable_automation_id_is_unverified( + tmp_path: Path, +) -> None: + # An empty element names an automation the lane cannot be; it must not be + # read as "no id" and fall back to the body. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + envelope = _heartbeat_envelope( + _automation_prompt("release-work", "operations") + ).replace("nightly", " ") + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent)), + _user_message(_ts(recent), envelope), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + + +def test_the_trigger_a_current_rollout_records_for_a_scheduled_turn_is_accepted( + tmp_path: Path, +) -> None: + # The routing contract names ``automation_heartbeat``; the current Codex App + # rollout writes ``automation_heartbeat_scheduled`` for the same delivery. + # Reading only the contract's spelling would report every real tick as + # unverified. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _observed_task_started(_ts(recent), "automation_heartbeat_scheduled"), + _user_message( + _ts(recent), + _heartbeat_envelope(_automation_prompt("release-work", "operations")), + ), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + assert diagnosis["status"] == "fresh" + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "fresh" + assert datetime.fromisoformat(lane["delivery_evidence_at"]) == recent + + +def test_a_trigger_this_adapter_has_not_seen_is_unverified(tmp_path: Path) -> None: + # A new host value could be a scheduled tick or could not. Reporting + # unverified keeps the fault visible; guessing ``fresh`` would hide it. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _observed_task_started(_ts(recent), "automation_heartbeat_manual"), + _user_message( + _ts(recent), + _heartbeat_envelope(_automation_prompt("release-work", "operations")), + ), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + assert "delivery_evidence_at" not in lane + + +def test_the_recorded_trigger_still_rejects_a_manual_message( + tmp_path: Path, +) -> None: + # Resuming acceptance of the recorded trigger must not reopen the manual + # path: a composer turn with the same text stays unverified. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _observed_task_started(_ts(recent), "composer"), + _user_message( + _ts(recent), + _heartbeat_envelope(_automation_prompt("release-work", "operations")), + ), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + + +def test_a_long_quiet_lane_stays_stale_without_delivery_evidence(tmp_path: Path) -> None: + # A missed window is still a missed window: requiring evidence must not turn + # a silent lane into an unverified one. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + _home, diagnosis = _proof( + tmp_path, [_event(_ts(old), "task_complete")], now=old + timedelta(hours=3) + ) + + assert diagnosis["status"] == "stale" + assert diagnosis["lanes"][0]["diagnosis"]["code"] == HOST_PROMPT_DELIVERY_MISSED + + +def _heartbeat_envelope(prompt: str) -> str: + """The shape Codex App wraps a scheduled automation prompt in.""" + + return ( + "\n" + " nightly\n" + " 2026-09-25T13:00:00Z\n" + " \n" + f"{prompt}\n" + " \n" + "" + ) + + +def test_a_heartbeat_envelope_delivery_is_attributed_to_the_installed_prompt( + tmp_path: Path, +) -> None: + # The host injects the installed body inside its envelope; comparing the + # message text verbatim to the manifest prompt would leave every real + # scheduled turn unverified and the check permanently amber. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_complete"), + _task_started(_ts(recent)), + _user_message( + _ts(recent), + _heartbeat_envelope(_automation_prompt("release-work", "operations")), + ), + _event(_ts(recent + timedelta(seconds=30)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + assert diagnosis["status"] == "fresh" + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "fresh" + assert datetime.fromisoformat(lane["delivery_evidence_at"]) == recent + + +def test_a_delivered_prompt_survives_a_long_turn_ahead_of_it(tmp_path: Path) -> None: + # One heartbeat turn appends far more than a few dozen records: tool calls, + # reasoning and token counts. A record-count bound would exhaust itself on + # the newest turn and report a delivered lane as unverified forever. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + noisy = [ + _task_started(_ts(recent)), + _user_message(_ts(recent), _automation_prompt("release-work", "operations")), + ] + [ + { + "timestamp": _ts(recent + timedelta(seconds=index)), + "type": "event_msg", + "payload": {"type": "token_count", "index": index}, + } + for index in range(400) + ] + _home, diagnosis = _proof( + tmp_path, + [_event(_ts(old), "task_complete"), *noisy], + now=recent + timedelta(minutes=1), + ) + + assert diagnosis["status"] == "fresh" + assert diagnosis["lanes"][0]["window_state"] == "fresh" + + +def test_a_prompt_matched_before_that_turn_does_not_prove_this_turn(tmp_path: Path) -> None: + # The newest turn is what is in question. An earlier delivered prompt is + # outside the window, so it cannot make the lane fresh now. + old = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + recent = old + timedelta(hours=3) + _home, diagnosis = _proof( + tmp_path, + [ + _event(_ts(old), "task_started"), + _user_message(_ts(old), _automation_prompt("release-work", "operations")), + _event(_ts(old), "task_complete"), + _event(_ts(recent), "task_started"), + _event(_ts(recent + timedelta(seconds=5)), "task_complete"), + ], + now=recent + timedelta(minutes=1), + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "unverified_activity" + + +def test_a_lane_without_a_cadence_is_unverified_not_healthy(tmp_path: Path) -> None: + home = _CodexHome(tmp_path / ".codex") + observed = datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc) + home.thread("thread-lane", [_event(_ts(observed), "task_complete")]) + observers = {"codex-app": lambda ids: observe_codex_threads(ids, homes=[home.root])} + + diagnosis = collect_host_delivery_diagnosis( + [_goal()], observers=observers, expectations=lambda scopes: {}, now=observed + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "unknown" + assert lane["reason"] == "no_expectation" + assert lane["diagnosis"] == { + "code": HOST_PROMPT_DELIVERY_UNVERIFIED, + "state": "unknown", + "reason": "no_expectation", + } + assert diagnosis["status"] == "unverified" + assert diagnosis["reason"] == "no_comparable_tick" + # Unverified is not a fault: nothing proves the host stopped delivering. + assert diagnosis["stale_lanes"] == [] + + +def test_a_lane_with_no_record_is_missing_rather_than_fresh() -> None: + diagnosis = collect_host_delivery_diagnosis( + [_goal()], + observers={ + "codex-app": lambda ids: { + thread: __import__( + "loopx.control_plane.agents.host_thread_activity", + fromlist=["HostThreadActivity"], + ).HostThreadActivity.unknown( + __import__( + "loopx.control_plane.agents.host_thread_activity", + fromlist=["HostThreadUnknownReason"], + ).HostThreadUnknownReason.THREAD_NOT_FOUND + ) + for thread in ids + } + }, + expectations=lambda scopes: { + scope: HostDeliveryExpectation(20, "codex_app_automation_rrule") for scope in scopes + }, + ) + + [lane] = diagnosis["lanes"] + assert lane["window_state"] == "missing" + assert diagnosis["status"] == "unverified" + + +def test_a_stopped_goal_is_not_measured_and_unbound_goals_are_skipped() -> None: + stopped = {**_goal("retired"), "activation": {"state": "stopped"}} + unbound = {"id": "no-thread"} + diagnosis = collect_host_delivery_diagnosis( + [stopped, unbound], + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + ) + + assert diagnosis["lanes"] == [] + assert diagnosis["skipped_stopped_goals"] == 1 + assert diagnosis["status"] == "not_applicable" + assert diagnosis["reason"] == "no_bound_host_lane" + + +def test_a_binding_without_a_thread_is_counted_not_silently_dropped() -> None: + # The surface is observable, so this Goal is this check's business; a + # binding holding no thread id cannot be measured. Dropping it would leave + # the operator reading a healthy workspace with one lane simply missing. + goal = { + "id": "release-work", + "coordination": { + "thread_agent_bindings": [ + {"agent_id": "operations", "host_surface": "codex-app", "thread_id": ""}, + {"host_surface": "codex-app", "thread_id": "thread-lane"}, + ] + }, + } + diagnosis = collect_host_delivery_diagnosis( + [goal], + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + ) + + assert diagnosis["lanes"] == [] + assert diagnosis["unmeasured_bindings"] == 2 + assert diagnosis["status"] == "not_applicable" + assert diagnosis["reason"] == "unmeasured_lane" + + +def test_an_unreadable_activation_record_does_not_read_fresh() -> None: + unreadable = { + "id": "old-goal", + "coordination": _goal()["coordination"], + "activation": {"schema_version": "loopx_goal_activation_v0"}, + } + + def observe(thread_ids): + return { + thread_id: HostThreadActivity( + HostThreadState.IDLE, last_event_at=_ts(datetime.now(timezone.utc)) + ) + for thread_id in thread_ids + } + + diagnosis = collect_host_delivery_diagnosis( + [unreadable, _goal()], + observers={"codex-app": observe}, + expectations=_observers_and_expectations()[1], + ) + + assert diagnosis["counts"]["fresh"] == 1 + assert diagnosis["unreadable_activation_goals"] == 1 + assert diagnosis["status"] == "unverified" + assert diagnosis["reason"] == "unmeasured_lane" + + +def test_a_goal_bound_only_to_an_unreadable_surface_is_not_reported() -> None: + goal = { + "id": "another-host", + "coordination": { + "thread_agent_bindings": [ + {"agent_id": "operations", "host_surface": "agy", "thread_id": "thread-1"} + ] + }, + } + diagnosis = collect_host_delivery_diagnosis( + [goal], + observers={"codex-app": lambda ids: pytest.fail("no Codex lane is bound")}, + expectations=lambda scopes: {}, + ) + + assert diagnosis["lanes"] == [] + assert diagnosis["reason"] == "no_bound_host_lane" + + +def test_two_bindings_of_one_lane_report_one_window() -> None: + goal = { + "id": "release-work", + "coordination": { + "thread_agent_bindings": [ + {"agent_id": "operations", "host_surface": "codex-app", "thread_id": "thread-a"}, + {"agent_id": "operations", "host_surface": "codex-app", "thread_id": "thread-b"}, + ] + }, + } + diagnosis = collect_host_delivery_diagnosis( + [goal], + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + ) + + # An agent with two candidate threads has no single identity, so its window + # stays unknown; it must still appear once, under the label an operator + # would search for. + assert diagnosis["lane_count"] == 1 + assert diagnosis["lanes"][0]["lane"] == "release-work/operations/codex-app" + assert diagnosis["lanes"][0]["window_state"] == "unknown" + + +def _wide_goal(duplicate_at: int) -> dict: + bindings = [ + { + "agent_id": f"agent-{index}", + "host_surface": "codex-app", + "thread_id": f"thread-{index}", + } + for index in range(64) + ] + # The same agent and surface twice: no single canonical thread. + bindings.insert(duplicate_at, dict(bindings[0], thread_id="thread-other")) + return {"id": "wide-goal", "coordination": {"thread_agent_bindings": bindings}} + + +@pytest.mark.parametrize("duplicate_at", [1, 64]) +def test_a_duplicate_binding_stays_ambiguous_wherever_it_sits(duplicate_at: int) -> None: + # The same 65 bindings, only moving the duplicate from position 2 to 65. The + # lane has no single identity in either case, so neither may be measured as + # a confirmed miss by the survivor that happened to fit the lane bound. + observed = _ts(datetime(2026, 9, 25, 10, 0, tzinfo=timezone.utc)) + + def observe(thread_ids): + return { + thread_id: HostThreadActivity(HostThreadState.IDLE, last_event_at=observed) + for thread_id in thread_ids + } + + diagnosis = collect_host_delivery_diagnosis( + [_wide_goal(duplicate_at)], + observers={"codex-app": observe}, + expectations=_observers_and_expectations()[1], + now=datetime(2026, 9, 27, 10, 0, tzinfo=timezone.utc), + ) + + assert diagnosis["truncated"] is True + lane = next( + row for row in diagnosis["lanes"] if row["agent_id"] == "agent-0" + ) + assert lane["window_state"] == "unknown" + assert lane["reason"] == "no_expectation" + assert diagnosis["counts"]["stale"] == diagnosis["lane_count"] - 1 + + +def test_the_lane_scan_is_bounded_and_says_so() -> None: + goals = [ + { + "id": f"goal-{index}", + "coordination": { + "thread_agent_bindings": [ + { + "agent_id": "operations", + "host_surface": "codex-app", + "thread_id": f"thread-{index}", + } + ] + }, + } + for index in range(5) + ] + diagnosis = collect_host_delivery_diagnosis( + goals, + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + max_lanes=3, + ) + + assert diagnosis["lane_count"] == 3 + assert diagnosis["truncated"] is True + assert len(diagnosis["lanes"]) == 3 + + +def test_a_goal_past_the_shared_binding_cap_reads_truncated() -> None: + # The shared observer keeps only MAX_OBSERVED_THREADS_PER_GOAL bindings per + # Goal. A silent lane can sit in the part it did not read, so a bounded scan + # must not present the result as complete. + cap = 32 + goal = { + "id": "wide-goal", + "coordination": { + "thread_agent_bindings": [ + { + "agent_id": f"agent-{index}", + "host_surface": "codex-app", + "thread_id": f"thread-{index}", + } + for index in range(cap + 1) + ] + }, + } + diagnosis = collect_host_delivery_diagnosis( + [goal], + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + ) + + assert diagnosis["lane_count"] == cap + assert diagnosis["incomplete_goals"] == 1 + assert diagnosis["per_goal_binding_cap"] == cap + assert diagnosis["truncated"] is True + + +def test_a_bounded_scan_does_not_claim_a_fresh_verdict() -> None: + # The lanes that were read are inside their window, but the bound left + # others unread; calling that `fresh` would claim coverage the run did not + # have, which is the fault this readback exists to prevent. + goals = [ + { + "id": f"goal-{index}", + "coordination": { + "thread_agent_bindings": [ + { + "agent_id": "operations", + "host_surface": "codex-app", + "thread_id": f"thread-{index}", + } + ] + }, + } + for index in range(3) + ] + + def observe(thread_ids): + return { + thread_id: HostThreadActivity( + HostThreadState.IDLE, last_event_at=_ts(datetime.now(timezone.utc)) + ) + for thread_id in thread_ids + } + + diagnosis = collect_host_delivery_diagnosis( + goals, + observers={"codex-app": observe}, + expectations=_observers_and_expectations()[1], + max_lanes=2, + ) + + assert diagnosis["counts"]["fresh"] == 2 + assert diagnosis["truncated"] is True + assert diagnosis["status"] == "unverified" + assert diagnosis["reason"] == "scan_truncated" + + +def test_a_binding_named_like_a_local_path_is_redacted_not_fatal() -> None: + # A Goal id is free-form registry text: an operator can name it after the + # directory it covers. Doctor output also serves `--format json`, whose + # public-output boundary refuses absolute paths. An optional diagnostic must + # still answer, and must still name the silent lane. + goal = _goal("/Users/operator/private-goal") + diagnosis = collect_host_delivery_diagnosis( + [goal], + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + max_lanes=4, + ) + + assert diagnosis["status"] == "unverified" + [lane] = diagnosis["lanes"] + assert lane["goal_id"].startswith(" None: + goal = { + "id": "release-work", + "coordination": { + "thread_agent_bindings": [ + { + "agent_id": "api_key=sk-live-abcdefghijklmnop", + "host_surface": "codex-app", + "thread_id": "thread-lane", + } + ] + }, + } + diagnosis = collect_host_delivery_diagnosis( + [goal], + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + ) + + [lane] = diagnosis["lanes"] + assert lane["agent_id"].startswith(" None: + # `a` + `b/c` and `a/b` + `c` are different lanes that once shared a joined + # label, so one of them silently disappeared from the report. + goals = [ + { + "id": "a", + "coordination": { + "thread_agent_bindings": [ + {"agent_id": "b/c", "host_surface": "codex-app", "thread_id": "thread-1"} + ] + }, + }, + { + "id": "a/b", + "coordination": { + "thread_agent_bindings": [ + {"agent_id": "c", "host_surface": "codex-app", "thread_id": "thread-2"} + ] + }, + }, + ] + diagnosis = collect_host_delivery_diagnosis( + goals, + observers={"codex-app": lambda ids: {}}, + expectations=lambda scopes: {}, + ) + + assert diagnosis["lane_count"] == 2 + assert {lane["goal_id"] for lane in diagnosis["lanes"]} == {"a", "a/b"} + # Each lane also stays addressable by its own single label. + assert {lane["lane"] for lane in diagnosis["lanes"]} == { + "a/b%2Fc/codex-app", + "a%2Fb/c/codex-app", + } + + +def test_an_archived_target_thread_names_the_real_cause() -> None: + # An archived thread holds no rollout to read, so the window layer infers an + # unparseable observation from the empty timestamp. The host record says + # something more useful, and naming it keeps the operator off the wrong trail. + diagnosis = collect_host_delivery_diagnosis( + [_goal()], + observers={ + "codex-app": lambda ids: { + thread_id: HostThreadActivity(HostThreadState.ARCHIVED) + for thread_id in ids + } + }, + expectations=lambda scopes: { + scope: HostDeliveryExpectation(20, "codex_app_automation_rrule") for scope in scopes + }, + ) + + [lane] = diagnosis["lanes"] + assert lane["thread_state"] == "archived" + assert lane["diagnosis"]["reason"] == "thread_archived" + assert diagnosis["status"] == "unverified" + + +def _isolated_doctor(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> tuple[Path, Path]: + home = tmp_path / "home" + runtime = tmp_path / "runtime" + monkeypatch.setattr(Path, "home", classmethod(lambda cls: home)) + monkeypatch.setenv("CODEX_HOME", str(home / ".codex")) + monkeypatch.delenv("LOOPX_CODEX_HOMES", raising=False) + monkeypatch.delenv("LOOPX_RELEASE_ROOT", raising=False) + command = tmp_path / "bin" / "loopx" + command.parent.mkdir() + command.write_text("synthetic command; never executed", encoding="utf-8") + monkeypatch.setattr( + doctor, + "default_runtime_route", + lambda: { + "selected_runtime_root": str(runtime), + "status": "fresh", + "recommended_action": None, + "target_runtime_root": str(runtime), + "legacy_runtime_root": None, + "target_registry_exists": False, + "legacy_registry_exists": False, + }, + ) + monkeypatch.setattr( + doctor, "resolve_command_path", lambda name: command if name == "loopx" else None + ) + monkeypatch.setattr(doctor, "current_script_invocation_path", lambda: None) + monkeypatch.setattr(doctor, "python_distribution_install", lambda _: {"available": False}) + monkeypatch.setattr( + doctor.doctor_git, "trusted_release_ref_for_root", lambda *a, **k: None + ) + monkeypatch.setattr( + doctor, "latest_promotion_readiness_event", lambda _: {"available": False} + ) + monkeypatch.setattr(doctor, "probe_registry_write_path", lambda *a, **k: {"ok": True}) + monkeypatch.setattr( + "loopx.control_plane.effect_runtime.collect_effect_runtime_readiness", + lambda *, deep: {"ready": True, "status": "ready"}, + ) + monkeypatch.setattr( + "loopx.capabilities.decision_context.freshness.collect_capture_host_diagnostics", + lambda _: {"healthy": True, "hosts": []}, + ) + monkeypatch.setattr( + "loopx.desktop_installation.desktop_installation_status", + lambda _: {"apps": [], "status": "not_installed"}, + ) + runtime.mkdir(parents=True) + return home / ".codex", runtime + + +def _write_registry(runtime: Path, goal: dict, *, revision: str = "rev-1") -> Path: + path = runtime / "registry.global.json" + path.write_text(json.dumps({"goals": [dict(goal, revision=revision)]}), encoding="utf-8") + return path + + +def test_doctor_reports_the_missed_window_from_the_real_automation_manifest( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + home = _CodexHome(codex_home) + old_tick = _ts(datetime.now(timezone.utc) - timedelta(days=3)) + home.thread("thread-lane", [_event(old_tick, "task_complete")]) + home.automation( + "nightly", goal_id="release-work", agent_id="operations", target_thread_id="thread-lane" + ) + _write_registry(runtime, _goal()) + + payload = doctor.collect_doctor() + + diagnosis = payload["host_prompt_delivery"] + assert diagnosis["status"] == "stale" + assert diagnosis["lanes"][0]["diagnosis"]["code"] == HOST_PROMPT_DELIVERY_MISSED + assert diagnosis["lanes"][0]["last_observed_at"] == old_tick + check = next(item for item in payload["checks"] if item["id"] == HOST_DELIVERY_CHECK_ID) + assert check["required"] is False + assert check["ok"] is False + assert "missed=release-work/operations/codex-app@" in check["detail"] + assert f"last_ticks=`{old_tick}`" in doctor.render_doctor_markdown(payload) + + +def test_doctor_keeps_a_quiet_workspace_healthy( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + home = _CodexHome(codex_home) + # A quiet workspace is a lane whose scheduled prompt was delivered inside + # its window: the turn carries the installed automation's own text. + tick = datetime.now(timezone.utc) + home.thread( + "thread-lane", + [ + _task_started(_ts(tick)), + _user_message(_ts(tick), _automation_prompt("release-work", "operations")), + _event(_ts(tick), "task_complete"), + ], + ) + home.automation( + "nightly", goal_id="release-work", agent_id="operations", target_thread_id="thread-lane" + ) + _write_registry(runtime, _goal()) + + payload = doctor.collect_doctor() + + assert payload["host_prompt_delivery"]["status"] == "fresh" + check = next(item for item in payload["checks"] if item["id"] == HOST_DELIVERY_CHECK_ID) + assert check["ok"] is True + assert payload["ok"] is True + + +def test_a_lane_bound_to_a_non_app_surface_is_not_reported_as_unverified( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # Only an installed app automation carries a cadence. A Goal bound to a CLI + # or IDE thread would otherwise read `unverified` on every run, which is how + # an optional check stops being read at all. + codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + home = _CodexHome(codex_home) + home.thread("thread-lane", [_event(_ts(datetime.now(timezone.utc)), "task_complete")]) + goal = { + "id": "release-work", + "coordination": { + "thread_agent_bindings": [ + { + "agent_id": "operations", + "host_surface": "codex-cli-tui", + "thread_id": "thread-lane", + } + ] + }, + } + _write_registry(runtime, goal) + + payload = doctor.collect_doctor() + + assert payload["host_prompt_delivery"]["status"] == "not_applicable" + assert payload["host_prompt_delivery"]["reason"] == "no_bound_host_lane" + check = next(item for item in payload["checks"] if item["id"] == HOST_DELIVERY_CHECK_ID) + assert check["ok"] is True + + +def test_an_explicit_registry_is_what_the_delivery_check_reads( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # The CLI hands `collect_doctor` the registry it resolved. A registry kept + # outside the default runtime root must still be the one measured, or a moved + # workspace reads `registry_empty` instead of its silent lane. + codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + home = _CodexHome(codex_home) + old_tick = _ts(datetime.now(timezone.utc) - timedelta(days=3)) + home.thread("thread-lane", [_event(old_tick, "task_complete")]) + home.automation( + "nightly", goal_id="release-work", agent_id="operations", target_thread_id="thread-lane" + ) + explicit = tmp_path / "moved" / "registry.global.json" + explicit.parent.mkdir() + explicit.write_text( + json.dumps({"goals": [dict(_goal(), revision="rev-1")]}), encoding="utf-8" + ) + + payload = doctor.collect_doctor(registry_path=explicit) + + diagnosis = payload["host_prompt_delivery"] + assert diagnosis["status"] == "stale" + assert diagnosis["reason"] == HOST_PROMPT_DELIVERY_MISSED + [lane] = diagnosis["lanes"] + assert lane["lane"] == "release-work/operations/codex-app" + assert lane["last_observed_at"] == old_tick + # The default location has no registry at all; nothing else supplied it. + assert not (runtime / "registry.global.json").exists() + check = next(item for item in payload["checks"] if item["id"] == HOST_DELIVERY_CHECK_ID) + assert check["ok"] is False + + +def test_a_missing_default_registry_does_not_hide_the_explicit_one( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + home = _CodexHome(codex_home) + recent = _ts(datetime.now(timezone.utc)) + home.thread("thread-lane", [_event(recent, "task_complete")]) + home.automation( + "nightly", goal_id="release-work", agent_id="operations", target_thread_id="thread-lane" + ) + explicit = tmp_path / "moved" / "registry.global.json" + explicit.parent.mkdir() + explicit.write_text( + json.dumps({"goals": [dict(_goal(), revision="rev-1")]}), encoding="utf-8" + ) + + default_only = doctor.collect_doctor() + explicit_scope = doctor.collect_doctor(registry_path=explicit) + + # No registry at the default location decodes to an empty goal list, which + # is exactly the reading the explicit path must not inherit. + assert default_only["host_prompt_delivery"]["reason"] == "registry_empty" + assert default_only["host_prompt_delivery"]["lane_count"] == 0 + # A recent tick with no delivery evidence is unverified, not a fault; this + # only asserts the explicit registry was read at all. + assert explicit_scope["host_prompt_delivery"]["reason"] == "no_comparable_tick" + assert explicit_scope["host_prompt_delivery"]["lane_count"] == 1 + assert not (runtime / "registry.global.json").exists() + + +def test_doctor_reports_no_bound_lane_without_a_fault( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + _write_registry(runtime, {"id": "documentation-only"}) + + payload = doctor.collect_doctor() + + assert payload["host_prompt_delivery"]["status"] == "not_applicable" + assert payload["host_prompt_delivery"]["reason"] == "no_bound_host_lane" + check = next(item for item in payload["checks"] if item["id"] == HOST_DELIVERY_CHECK_ID) + assert check["ok"] is True + + +def test_the_publish_guard_withholds_labels_instead_of_failing_the_run( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + # The last-resort guard: if a label this module did not anticipate still + # violates the boundary, the verdict survives and only the names are + # withheld. An optional check must never abort `loopx doctor`. + codex_home, runtime = _isolated_doctor(monkeypatch, tmp_path) + home = _CodexHome(codex_home) + old_tick = _ts(datetime.now(timezone.utc) - timedelta(days=3)) + home.thread("thread-lane", [_event(old_tick, "task_complete")]) + home.automation( + "nightly", goal_id="release-work", agent_id="operations", target_thread_id="thread-lane" + ) + _write_registry(runtime, _goal()) + monkeypatch.setattr( + "loopx.control_plane.agents.host_delivery_diagnosis._public_label", + lambda value: (str(value or ""), False), + ) + monkeypatch.setattr( + "loopx.control_plane.agents.host_delivery_diagnosis._lane_payload", + lambda goal_id, row: { + "lane": "/Users/operator/private-goal", + "goal_id": goal_id, + "agent_id": row.get("agent_id"), + "host_surface": row.get("host_surface"), + "window_state": (row.get("delivery_window") or {}).get("state"), + "last_observed_at": (row.get("delivery_window") or {}).get("last_observed_at"), + }, + ) + + payload = doctor.collect_doctor() + + diagnosis = payload["host_prompt_delivery"] + assert diagnosis["status"] == "stale" + assert diagnosis["labels_withheld"] is True + assert diagnosis["lanes"] == [] + assert "private-goal" not in json.dumps(payload) + check = next(item for item in payload["checks"] if item["id"] == HOST_DELIVERY_CHECK_ID) + assert check["ok"] is False + + +def test_a_corrupt_registry_reports_unavailable_instead_of_raising( + tmp_path: Path, +) -> None: + from loopx.control_plane.agents.host_delivery_diagnosis import ( + collect_registry_host_delivery_diagnosis, + ) + + path = tmp_path / "registry.global.json" + path.write_text("{not json", encoding="utf-8") + + diagnosis = collect_registry_host_delivery_diagnosis(registry_path=path) + + assert diagnosis["status"] == "not_applicable" + assert diagnosis["reason"] == "registry_unavailable" + + +def test_a_registry_this_build_cannot_decode_names_its_own_reason( + tmp_path: Path, +) -> None: + # A readable file this build cannot decode is a different operator action + # from a missing one, and the readback has to say which. + from loopx.control_plane.agents.host_delivery_diagnosis import ( + collect_registry_host_delivery_diagnosis, + ) + + path = tmp_path / "registry.json" + path.write_text( + json.dumps( + { + "schema_version": "loopx_project_registry_envelope_v2", + "minimum_writer_protocol": "goal_instance_v2", + "payload_sha256": "0" * 64, + "profile_id": "source_session_v1", + "goals": [], + } + ), + encoding="utf-8", + ) + + diagnosis = collect_registry_host_delivery_diagnosis(registry_path=path) + + assert diagnosis["status"] == "not_applicable" + assert diagnosis["reason"] == "registry_requires_upgrade" + + +def test_a_truncated_readback_does_not_report_the_check_green() -> None: + from loopx.control_plane.agents.host_delivery_diagnosis import ( + host_delivery_diagnosis_check, + ) + + diagnosis = { + "status": "unverified", + "reason": "scan_truncated", + "counts": {"fresh": 2, "stale": 0, "missing": 0, "unknown": 0}, + "lane_count": 2, + "truncated": True, + "unmeasured_bindings": 0, + "unreadable_activation_goals": 0, + "stale_lanes": [], + "lanes": [], + } + check = host_delivery_diagnosis_check(diagnosis) + + assert check["ok"] is False + assert "truncated=true" in check["detail"] + + +def test_a_quiet_workspace_read_back_in_full_is_green() -> None: + from loopx.control_plane.agents.host_delivery_diagnosis import ( + host_delivery_diagnosis_check, + ) + + diagnosis = { + "status": "fresh", + "reason": None, + "counts": {"fresh": 1, "stale": 0, "missing": 0, "unknown": 0}, + "lane_count": 1, + "truncated": False, + "unmeasured_bindings": 0, + "unreadable_activation_goals": 0, + "stale_lanes": [], + "lanes": [], + } + + assert host_delivery_diagnosis_check(diagnosis)["ok"] is True + + +def test_installation_scope_still_does_not_open_host_state( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + _isolated_doctor(monkeypatch, tmp_path) + + def forbidden(*args, **kwargs): + raise AssertionError("installation-only scope must not read host delivery") + + monkeypatch.setattr( + "loopx.control_plane.agents.host_delivery_diagnosis.collect_host_delivery_diagnosis_route", + forbidden, + ) + payload = doctor.collect_doctor(installation_only=True) + assert payload["scope"] == "installation_only" + assert "host_prompt_delivery" not in payload