diff --git a/infra/systemd/check-continuation-snapshot.py b/infra/systemd/check-continuation-snapshot.py index 15c954a..3185c93 100644 --- a/infra/systemd/check-continuation-snapshot.py +++ b/infra/systemd/check-continuation-snapshot.py @@ -1,14 +1,16 @@ #!/usr/bin/env python3 -"""Emit one Reflex check.fact about an existing Monag continuation snapshot.""" +"""Emit one Reflex check.fact about a Monag continuation snapshot or its Planfile queue.""" import argparse from datetime import datetime, timezone import fcntl import hashlib import json import os +import re from pathlib import Path import tempfile import uuid +from urllib.parse import parse_qs, urlsplit def inspect_snapshot(path, root, now, max_age): @@ -59,25 +61,62 @@ def remember(fact, path): return fact +def inspect_queue(url): + from monag.autonomy_probes import _discovery_failure + + try: + endpoint = urlsplit(url) + query = parse_qs(endpoint.query, keep_blank_values=True) + valid = ( + endpoint.scheme in {"http", "https"} and endpoint.hostname + and endpoint.username is None and not endpoint.fragment + and query.get("mode") == ["queue"] + and query.keys() <= {"mode", "queue", "state", "view", "limit"} + and all(len(query.get(k, [])) == 1 and re.fullmatch(r"[A-Za-z0-9._-]{1,120}", query[k][0]) + for k in ("queue", "state")) + ) + except ValueError: + valid = False + if not valid: + return {"reason": "invalid_queue_binding"} + + failure = _discovery_failure(url, configured=True, timeout=1.5) + status, reason = failure if failure else (200, "queue_ready") + return {"queue": query["queue"][0], "state": query["state"][0], "http_status": status, "reason": reason} + + def main(): cli = argparse.ArgumentParser(description=__doc__) - cli.add_argument("--snapshot", type=Path, required=True) - cli.add_argument("--root", type=Path, required=True) + source = cli.add_mutually_exclusive_group(required=True) + source.add_argument("--snapshot", type=Path) + source.add_argument("--planfile-queue-url", help="Scoped Planfile discovery URL, requires the Monag package") + cli.add_argument("--root", type=Path) cli.add_argument("--target", required=True, help="Stable check target in this workspace") - cli.add_argument("--max-age-seconds", type=int, required=True) + cli.add_argument("--max-age-seconds", type=int) cli.add_argument("--last-observation", type=Path, help="Private state file for replay of unchanged evidence") args = cli.parse_args() - if args.max_age_seconds <= 0: - cli.error("--max-age-seconds must be positive") - now = datetime.now(timezone.utc) - proof = inspect_snapshot(args.snapshot, args.root.resolve(), now, args.max_age_seconds) + if args.snapshot is not None: + if args.root is None or args.max_age_seconds is None or args.max_age_seconds <= 0: + cli.error("--snapshot requires --root and positive --max-age-seconds") + now = datetime.now(timezone.utc) + proof = inspect_snapshot(args.snapshot, args.root.resolve(), now, args.max_age_seconds) + reason = proof["state"] + operation, repository, code = "ops.monag-continuation-snapshot", "semcod/monag", "unusable-snapshot" + label, prefix, success = "Scheduled Monag snapshot", "monag-snapshot", reason == "fresh" + else: + if args.root is not None or args.max_age_seconds is not None: + cli.error("--root and --max-age-seconds apply only to --snapshot") + proof = inspect_queue(args.planfile_queue_url) + now = datetime.now(timezone.utc) + reason = proof["reason"] + operation, repository, code = "ops.planfile-queue-discovery", "semcod/planfile", "queue-not-ready" + label, prefix = "Planfile queue discovery", "monag-queue" + success = proof.get("http_status") == 200 and reason == "queue_ready" invocation = os.environ.get("INVOCATION_ID") or uuid.uuid4().hex - fact = {"event_type": "check.fact", "operation": "ops.monag-continuation-snapshot", - "repository": "semcod/monag", "task_id": args.target, "failure_code": "unusable-snapshot", - "failure_category": proof["state"], "occurred_at": now.isoformat(), - "source_event_id": f"monag-snapshot-{invocation}-{now.isoformat()}", - "status": "success" if proof["state"] == "fresh" else "failure", - "summary": "Scheduled Monag snapshot: " + proof["state"], "evidence": proof} + fact = {"event_type": "check.fact", "operation": operation, "repository": repository, + "task_id": args.target, "failure_code": code, "failure_category": reason, + "occurred_at": now.isoformat(), "source_event_id": f"{prefix}-{invocation}-{now.isoformat()}", + "status": "success" if success else "failure", "summary": f"{label}: {reason}", "evidence": proof} print(json.dumps(remember(fact, args.last_observation) if args.last_observation else fact)) diff --git a/infra/systemd/test_continuation_queue_check.py b/infra/systemd/test_continuation_queue_check.py new file mode 100644 index 0000000..04072d5 --- /dev/null +++ b/infra/systemd/test_continuation_queue_check.py @@ -0,0 +1,50 @@ +import json +import runpy +import sys +from pathlib import Path +from unittest.mock import patch + +import pytest + + +SCRIPT = Path(__file__).with_name("check-continuation-snapshot.py") +URL = "http://planfile.invalid/tickets/discovery?mode=queue&queue=coding-agent&state=ready" +PAGE = {"schema": "planfile.ticket-discovery/v1", "tickets": [], + "scope": {"mode": "queue", "queue": "coding-agent", "state": "ready"}} + + +def sample(monkeypatch, capsys, tmp_path, response, url=URL): + monkeypatch.setattr(sys, "argv", [str(SCRIPT), "--planfile-queue-url", url, "--target", "central-coding-ready", + "--last-observation", str(tmp_path / "ready.json")]) + with patch("monag.autonomy_probes._http_probe", return_value=response): + runpy.run_path(str(SCRIPT), run_name="__main__") + return json.loads(capsys.readouterr().out) + + +def test_queue_change_replay_and_healing(monkeypatch, capsys, tmp_path): + error = (503, {"detail": "ticket_index_stale", "private": "sensitive payload"}) + failed = sample(monkeypatch, capsys, tmp_path, error) + assert sample(monkeypatch, capsys, tmp_path, error) == failed + wrong = sample(monkeypatch, capsys, tmp_path, (200, {**PAGE, "scope": {**PAGE["scope"], "state": "pending"}})) + healthy = sample(monkeypatch, capsys, tmp_path, (200, PAGE)) + assert sample(monkeypatch, capsys, tmp_path, (200, {**PAGE, "tickets": [{"id": "private-ticket"}]})) == healthy + recurred = sample(monkeypatch, capsys, tmp_path, error) + assert [x["status"] for x in (failed, wrong, healthy, recurred)] == ["failure", "failure", "success", "failure"] + assert len({x["source_event_id"] for x in (failed, wrong, healthy, recurred)}) == 4 + assert len({(x["operation"], x["repository"], x["task_id"], x["failure_code"]) for x in (failed, healthy)}) == 1 + assert failed["evidence"] == {"queue": "coding-agent", "state": "ready", "http_status": 503, "reason": "ticket_index_stale"} + assert wrong["evidence"]["reason"] == "discovery_response_mismatch" + assert "sensitive payload" not in str(failed) and "private-ticket" not in str(healthy) + + +@pytest.mark.parametrize("url", ["http://host/health", URL.replace("mode=queue", "mode=other"), + URL + "&state=pending", URL + "&repository=other%2Fproject", URL.replace("state=ready", "state=")]) +def test_unqualified_binding_cannot_recover_a_queue(monkeypatch, capsys, tmp_path, url): + observed = sample(monkeypatch, capsys, tmp_path, (200, PAGE), url) + assert observed["status"] == "failure" + assert observed["evidence"]["reason"] == "invalid_queue_binding" + + +def test_failure_status_cannot_be_labeled_healthy_by_the_backend(monkeypatch, capsys, tmp_path): + observation = sample(monkeypatch, capsys, tmp_path, (503, {"detail": "queue_ready"})) + assert observation["status"] == "failure" and observation["evidence"]["http_status"] == 503 diff --git a/infra/systemd/triage.env.example b/infra/systemd/triage.env.example index 693d6ff..00457c6 100644 --- a/infra/systemd/triage.env.example +++ b/infra/systemd/triage.env.example @@ -5,3 +5,7 @@ URTLOG_STATE_DIR=/srv/urtlog MONAG_OQLLM_FACT_PRINCIPAL=example-producer # Set when the deployment expects the central Planfile bridge to emit facts. # MONAG_PLANFILE_URTLOG_HEALTH_URL=http://127.0.0.1:18769/health +# Set discovery URLs from the deployment binding. Triage probes pending. +# The continuation check can observe ready independently with --planfile-queue-url. +# MONAG_PLANFILE_DISCOVERY_URL="http://127.0.0.1:18769/tickets/discovery?mode=queue&queue=coding-agent&state=pending&view=summary&limit=1" +# MONAG_PLANFILE_READY_URL="http://127.0.0.1:18769/tickets/discovery?mode=queue&queue=coding-agent&state=ready&view=summary&limit=1" diff --git a/project/TICKETS.md b/project/TICKETS.md index 676615c..890e253 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -155,4 +155,5 @@ | **ticket-166** | [`README.md`](./ticket-166/README.md) | - | - | - | - | - | | **ticket-167** | [`README.md`](./ticket-167/README.md) | - | - | - | - | - | | **ticket-168** | [`README.md`](./ticket-168/README.md) | - | - | - | - | - | +| **ticket-169** | [`README.md`](./ticket-169/README.md) | - | - | - | - | - | diff --git a/project/ticket-169/README.md b/project/ticket-169/README.md new file mode 100644 index 0000000..4f76820 --- /dev/null +++ b/project/ticket-169/README.md @@ -0,0 +1,36 @@ +# Ticket 169: PLF-29795 Publish qualified queue readiness as a continuation check fact + +- **ID**: ticket-169 +- **Owner**: unresolved:human +- **Status**: IN_PROGRESS +- **Workflow state**: EDIT +- **Created**: 2026-11-24 + +## Goal and scope + +To be completed from human-owned input. + +## Acceptance criteria + +- [ ] AC-01: Scope is approved by a human owner. + +## Tracking boundary + +This directory contains the minimal reviewed intent. Optional participant prose +and raw command logs are not required delivery output. + + +## Ticket Radar + +Initial planned-scope estimate; advisory only, not execution or merge approval. + +| Measure | Initial assessment | +| --- | --- | +| Impact score | 48/100 | +| Complexity | M | +| Estimated effort | 50 min | +| Planning budget | 30 min | +| Split recommended | yes | + +Diagnostics: RADAR-ACCEPTANCE-MISSING, RADAR-BUDGET-EXCEEDED. + diff --git a/project/ticket-169/intent.json b/project/ticket-169/intent.json new file mode 100644 index 0000000..d47bdce --- /dev/null +++ b/project/ticket-169/intent.json @@ -0,0 +1,26 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-169", + "summary": "PLF-29795 Publish qualified queue readiness as a continuation check fact", + "workstream": "infrastructure", + "classification": { + "kind": "BUG", + "priority": "P1", + "origin": "requested" + }, + "allowedPaths": [ + "project/ticket-169/**", + "TODO.md", + "project/TICKETS.md", + "infra/systemd/check-continuation-snapshot.py", + "infra/systemd/test_continuation_queue_check.py", + "infra/systemd/triage.env.example" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null +}