← Back to Pull requests

feat: sdlc deploy via the deploy robot (a2359) #348

Merged
fatherlinux merged 7 files (1586 lines) on Dec 04, 2026 23:49 UTC
View on GitHub
fatherlinux fatherlinux commented on Dec 04, 2026 20:54 UTC
Author

Phase 5 of docs/lifecycle.md: sdlc deploy for services in the deploy robot's registry.

resolve (no credential): the digest quay.io/crunchtools/<repo>:X.Y.Z names (default: the version :latest is labelled), cosign-verified with the fleet key, its org.opencontainers.image.revision equal to the commit vX.Y.Z tags (peeled). Then the service is checked against the robot's registry (crunchtools/deployer deploy/services.toml) when it can be read: a name that is not a row, or a row for another repo, is a 1 before any ticket exists, naming this repo's real row.

ticket (rt): searches the Deploy queue for the Desk's exact subject, Deploy <service> <version>, and adopts it; otherwise refuses while another ticket for the service is new/open, otherwise files one whose body is service: / repo: / commit: and nothing else.

wait (rt): resolved is a 0 only when the robot's own comment, by the RT user hosts.toml names as [rt] robot, says "Deployed." with the commit's first 12 characters, or "Already deployed." with its first 7. Resolved without that (closed by a person) is a 1. Stalled is a 1 with the robot's last comment, worded for a wrong service name when the robot refused one. Still new after 5 minutes is a 2, as is no verdict in 30. Without [rt] robot, nothing is filed (2): nothing could prove the deploy. Only the robot's own comments are opened, newest first, and only as far as needed.

That rule encodes 2026-12-04: a ticket filed as acquacotta instead of the registry's acquacotta.crunchtools.com was refused, then closed by hand and taken for a deploy.

via = "ssh" keys are shape-checked, then the command exits 2 as not built yet (phase 6).

Not done: reading the running service's revision from the deploying machine. No read-only check of it exists off the host, so the robot's verified comment (unit active, the exact image, the probe held) is the evidence. docs/lifecycle.md says so.

Tests: tests/test_life_deploy.py, 25 cases against a fake RT (REST2) and fake skopeo/cosign/git: adopt-existing, wrong service (registry and robot refusal), robot-stalled, resolved by hand, a "Deployed." from a non-robot user, no [rt] robot, still-new timeout, unsigned digest, mismatched revision, no tag or no image, RT and skopeo error paths as 2s.

Ashigaru-Item: a2359

🤖 Generated with Claude Code

https://claude.ai/code/session_01R7Y1jeqWyD1kaUDpcBw3TN

Diff: 1586 lines (+1573 / -13) across 7 files Reviewer: fatherlinux Review duration: 175m
All Vouch review confidence checks passed
Residual risk 0.16 = Change Risk (0.89) × (1 − Review Confidence (0.82)). Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.89 · 1586 lines diff across 7 files
0.89
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.97 · 5 substantive comment(s)
0.97
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 50%
82%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size diff_size
0.400
Self Review self_review
0.140
Sensitive Paths sensitive_paths
0.089
Real PR Conversation Timeline
40 items
ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 20:56 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):

MEDIUM (Performance Check): said_by makes a separate, sequential HTTP request for each matching robot transaction's attachments. A ticket with many robot comments can therefore require up to 100 serial attachment requests for the history page, adding latency to the deploy verdict.

Suggestion: If RT supports expanding attachment content in the history response, retrieve it there; otherwise consider batching or concurrently fetching only the candidate transactions needed to find the proof.

Evidence:

for tid in reversed(ids):
    if tid is not None:
        parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
        yield "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")

<!-- gatehouse agent=performance confidence=91 votes=2/3 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 20:56 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):
+            if tid is not None:
+                parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
+                yield "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")
+
+
+def _creator(tx: Mapping) -> str:
+    """A transaction's creator's name, given as an object (fields[Creator]) or a bare name."""
+    creator = tx.get("Creator")
+    return str(creator.get("Name", "") if isinstance(creator, Mapping) else creator or "")
+
+
+def _number(value: object) -> int | None:
+    """RT gives an id as a number, or as a string of digits."""
+    digits = isinstance(value, str) and value.isdigit()
+    return int(str(value)) if digits else value if type(value) is int else None
+
+
+def _text(part: Mapping) -> str:
+    """An attachment's Content, which REST2 gives base64-encoded."""
+    raw = part.get("Content")
+    if not isinstance(raw, str):
+        return ""
+    try:
+        return base64.b64decode(raw, validate=True).decode(errors="replace")
+    except ValueError:
+        return raw
+
+
+def subject(cfg: Config, art: Artifact) -> str:
+    """The Desk's subject (ashigaru desk/cuts.py), so its filing and this one are one ticket."""
+    return f"Deploy {cfg.service} {art.version}"
+
+
+def body(cfg: Config, art: Artifact) -> str:
+    """The robot's ticket body: those three fields and nothing else."""
+    return f"service: {cfg.service}\nrepo: {art.repo}\ncommit: {art.commit}\n"
+
+
+# ------------------------------------------------------------------ the verdict
+
+
+def proof(said: Iterable[str], art: Artifact) -> str | None:
+    """The robot's own comment saying this commit is running and verified, or None.
+
+    The deployer resolves with "Deployed. <unit> is running <commit:7> (built
+    from <revision:12>, ...", or "Already deployed. <unit> was already running
+    <commit:7> ..." when the service was on it. `said` is the robot's comments,
+    newest first, by its RT user alone: anyone else's, in the robot's words or not, proves
+    nothing, and a ticket a person resolved is no deploy.
+    """
+    for text in said:
+        words = text.lstrip()
+        if words.startswith("Deployed.") and f"built from {art.commit[:12]}" in words:
+            return words
+        if words.startswith("Already deployed.") and f"running {art.commit[:7]}" in words:
+            return words
+    return None
+
+
+def robot_digest(text: str) -> str | None:
+    m = re.search(r"digest (sha256:[0-9a-f]{64})", text)
+    return m[1] if m else None
+
+
+# ------------------------------------------------------------------ the steps
+
+
+@dataclass
+class Deploy:
+    """What the steps share: where they read from. Suites replace each."""
+
+    root: Path
+    repo: str  # crunchtools/<name>
+    version: str | None
+    reg: Registry
+    http: Http = field(default_factory=_http)
+    hosts: Callable[[], _hosts.Hosts] = _hosts.load
+    timer: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
+
+    def target(self) -> tuple[Config, Artifact, dict]:
+        cfg = config(self.root)
+        art, labels = artifact(self.reg, self.repo, self.version)
+        return cfg, art, labels
+
+    def rt(self, run: Run) -> tuple[Rt, str]:
+        """RT, and the robot's RT user: without it nothing could prove a deploy, so a 2 at once."""
+        hosts = self.hosts()
+        robot = hosts.need("rt.robot")
+        rt = Rt(hosts.need("rt.url"), hosts.need("rt.queue"), run.credential("rt"), self.http)
+        return rt, robot
+
+    # resolve -----------------------------------------------------------
+
+    def resolve(self, run: Run) -> None:
+        cfg, art, labels = self.target()
+        verify(self.reg, art, labels)
+        run.say(f"   {art.image}:{art.version} is {art.digest}, signed, built from {art.commit}")
+        check_registry(run, cfg, art.repo, self.http)
+
+    # ticket ------------------------------------------------------------
+
+    def filed(self, run: Run) -> bool:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        found = rt.find(subject(cfg, art))
+        if found is not None:
+            run.say(
+                f"   adopted RT#{found.number} ({found.status}), filed already for this release"
+            )
+        return found is not None
+
+    def file(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        mine = subject(cfg, art)
+        prefix = f"Deploy {cfg.service} "
+        busy = [
+            (n, s)
+            for n, s, status in rt.search(f"Subject LIKE '{prefix}'")
+            if status in LIVE and s.startswith(prefix) and s != mine
+        ]
+        if busy:
+            number, other = busy[0]
+            raise RefusedError(
+                f"RT#{number} ({other}) is already in flight for {cfg.service}: one deploy at a "
+                f"time; wait for it, then run this again"
+            )
+        number = rt.file(mine, body(cfg, art))
+        run.say(f"   filed RT#{number}: {mine}")
+
+    # wait --------------------------------------------------------------
+
+    def wait(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, robot = self.rt(run)
+        mine = subject(cfg, art)
+        found = rt.find(mine)
+        if found is None:
+            raise CannotRunError(
+                f"no ticket {mine!r} in the queue to wait for; run the ticket step"
+            )
+        number, where = found.number, f"{rt.url}/Ticket/Display.html?id={found.number}"
+        clock, _ = self.timer
+        started = clock()
+
+        def answered() -> str | None:
+            status = rt.status(number)
+            if status == "new" and clock() - started >= NEW_FOR:
+                raise runner.WaitExpiredError(
+                    f"RT#{number} is still new after {NEW_FOR:.0f}s: the deploy robot is not "
+                    f"reading its queue\n{where}"
+                )
+            return None if status in WORKING else status
+
+        status = runner.wait_for(
+            answered, Wait(f"the robot to answer RT#{number}", where, ANSWER_IN, POLL), self.timer
+        )
+        if status == "stalled":
+            raise RefusedError(_stalled(number, cfg, next(rt.said_by(number, robot), None)))
+        if status != "resolved":
+            raise RefusedError(f"RT#{number} was {status}, not deployed\n{where}")
+        said = proof(rt.said_by(number, robot), art)
+        if said is None:
+            raise RefusedError(
+                f"RT#{number} is resolved, and the robot never said it deployed {art.commit[:12]}: "
+                f"a ticket closed by hand is not a deploy. Nothing is known to be running "
+                f"v{art.version}; file a new ticket for it\n{where}"
+            )
+        running = robot_digest(said)
+        run.say(f"   RT#{number}: {said.strip().splitlines()[0]}")
+        run.result = {
+            "repo": art.repo,
+            "version": art.version,
+            "commit": art.commit,
+            "digest": art.digest,
+            "service": cfg.service,
+            "ticket": f"RT#{number}",
+            "running": running,
+        }
+
+
+def _stalled(number: int, cfg: Config, last: str | None) -> str:
+    """The robot's last comment, the service's own output on it, and what it means."""
+    said = last.strip() if last else "the ticket carries no comment from the robot"
+    if "is not in the registry" in said:
+        return (
+            f"RT#{number}: the robot refused {cfg.service!r}, which is not in its registry. The "
+            f"service is the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service "
+            f"and deploy again, which files a new ticket\n{said}"
+        )
+    return f"RT#{number} was handed back by the robot, and nothing it deployed stayed:\n{said}"
+
+
+def steps(d: Deploy) -> list[Step]:
+    return [
+        Step("resolve", d.resolve),
+        Step("ticket", d.file, done=d.filed, needs=("rt",)),
+        Step("wait", d.wait, needs=("rt",)),
+    ]
+
+
+def main(argv: list[str]) -> int:

LOW (Test Coverage): The new CLI entry point is not exercised by the tests: they call Deploy and run_steps directly, leaving argument parsing, --version validation, and dispatch through runner.main untested.

Suggestion: Add a focused CLI test that invokes main with valid and invalid --version values and verifies the selected version and dispatch, using fakes to avoid network access.

Evidence:

def main(argv: list[str]) -> int:
    d = Deploy(Path.cwd(), repo_of(os.environ), None, Registry())
    p = runner.parser("deploy", steps(d))
    p.add_argument("--version", help="X.Y.Z to deploy (default: the newest release, :latest)")
    args = p.parse_args(argv)
    if args.version is not None and not SEMVER.fullmatch(args.version):
        raise CannotRunError(f"--version wants X.Y.Z, not {args.version!r}")
    d.version = args.version
    return runner.main("deploy", argv, steps(d), args)

<!-- gatehouse agent=tests confidence=96 votes=1/1 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 20:56 UTC
Reviewer

Gatehouse found 4 issues (1 critical, 2 medium, 1 low)

Full review.

5 finding(s) dropped: their evidence is not in the diff.

1 finding(s) not raised: already judged in gatehouse-findings.toml on this branch.

<!-- gatehouse review complete -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 20:56 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)

CRITICAL (Documentation): The new public Config class has no docstring explaining its purpose or the meaning of its fields. The module-level description covers the deploy workflow but does not document this public data type.

Suggestion: Add a class docstring describing the configuration represented by Config and the semantics of via and service.

Evidence:

@dataclass(frozen=True)
class Config:
    via: str
    service: str

<!-- gatehouse agent=docs confidence=94 votes=2/3 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 20:56 UTC
Code Review
gatehouse-findings.toml:1
@@ -206,3 +206,17 @@ rule (profiles/web-application.md) is for host units that mount a shared data \
 directory, where a private `:Z` label would lock the other container out. \
 tests/test_workflows.py pins this mount exactly as shipped (#178, #184).
 """
+
+[[findings]]
+agent = "bugs"
+category = "bug"
+file = "sdlc_jobs/life/deploy.py"
+evidence = "busy = [\n    (n, s)\n    for n, s, status in rt.search(f\"Subject LIKE '{prefix}'\")\n    if status in LIVE and s.startswith(prefix) and s != mine\n]"

MEDIUM (Ledger): This branch silences a bugs finding in sdlc_jobs/life/deploy.py as not-a-bug: RT's TicketSQL LIKE is a substring match: RT wraps the value in % itself (RT::SearchBuilder, LIKE becomes %value%), so Subject LIKE 'Deploy svc ' finds every Deploy svc X.Y.Z. The Desk's own search reads RT the same way. Each hit is then filtered again here with startswith, so the query can only widen what is seen, never narrow it.

Suggestion: Confirm the judgement is right, or drop the entry and fix the finding. The entry stops applying on its own once the code it quotes is gone.

Evidence:

busy = [
    (n, s)
    for n, s, status in rt.search(f"Subject LIKE '{prefix}'")
    if status in LIVE and s.startswith(prefix) and s != mine
]

<!-- gatehouse agent=ledger confidence=100 votes=1/1 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:06 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:

MEDIUM (Bug Hunter): search requests only one page of up to 50 tickets and never follows pagination. The in-flight check uses this search result, so if an older live ticket is outside the first page, file misses it and files another deploy ticket despite the one-deploy-at-a-time rule.

Suggestion: Read all result pages for searches used to enforce the in-flight constraint, following RT's pagination metadata or next link until exhausted.

Evidence:

"per_page": PAGE,
...
for item in self._items(f"/tickets?{query}"):
    number = _number(item.get("id"))

<!-- gatehouse agent=bugs confidence=94 votes=3/3 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:06 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})

MEDIUM (Bug Hunter): The Labels field from skopeo inspect is passed to _version_of without checking its type. A non-object value (for example, a string or list in an unexpected/malformed response) causes an unhandled AttributeError at labels.get, rather than a controlled CannotRunError.

Suggestion: Validate that Labels is a mapping with string keys and values before calling _version_of, and report an invalid inspect response with CannotRunError.

Evidence:

version = _version_of(doc.get("Labels") or {})

<!-- gatehouse agent=bugs confidence=88 votes=2/3 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:06 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):

HIGH (Performance Check): said_by makes a separate sequential HTTP request for each matching transaction's attachments. A ticket with many robot comments can therefore require up to roughly 100 attachment requests after the history request, adding substantial latency to verdict checking.

Suggestion: Fetch attachment content in a batch or use an API response that includes the needed attachment data; otherwise avoid serially opening every matching transaction.

Evidence:

for tid in reversed(ids):
    if tid is not None:
        parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
        yield "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")

<!-- gatehouse agent=performance confidence=96 votes=3/3 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:06 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):
+            if tid is not None:
+                parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
+                yield "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")
+
+
+def _creator(tx: Mapping) -> str:
+    """A transaction's creator's name, given as an object (fields[Creator]) or a bare name."""
+    creator = tx.get("Creator")
+    return str(creator.get("Name", "") if isinstance(creator, Mapping) else creator or "")
+
+
+def _number(value: object) -> int | None:
+    """RT gives an id as a number, or as a string of digits."""
+    digits = isinstance(value, str) and value.isdigit()
+    return int(str(value)) if digits else value if type(value) is int else None
+
+
+def _text(part: Mapping) -> str:
+    """An attachment's Content, which REST2 gives base64-encoded."""
+    raw = part.get("Content")
+    if not isinstance(raw, str):
+        return ""
+    try:
+        return base64.b64decode(raw, validate=True).decode(errors="replace")
+    except ValueError:
+        return raw
+
+
+def subject(cfg: Config, art: Artifact) -> str:
+    """The Desk's subject (ashigaru desk/cuts.py), so its filing and this one are one ticket."""
+    return f"Deploy {cfg.service} {art.version}"
+
+
+def body(cfg: Config, art: Artifact) -> str:
+    """The robot's ticket body: those three fields and nothing else."""
+    return f"service: {cfg.service}\nrepo: {art.repo}\ncommit: {art.commit}\n"
+
+
+# ------------------------------------------------------------------ the verdict
+
+
+def proof(said: Iterable[str], art: Artifact) -> str | None:
+    """The robot's own comment saying this commit is running and verified, or None.
+
+    The deployer resolves with "Deployed. <unit> is running <commit:7> (built
+    from <revision:12>, ...", or "Already deployed. <unit> was already running
+    <commit:7> ..." when the service was on it. `said` is the robot's comments,
+    newest first, by its RT user alone: anyone else's, in the robot's words or not, proves
+    nothing, and a ticket a person resolved is no deploy.
+    """
+    for text in said:
+        words = text.lstrip()
+        if words.startswith("Deployed.") and f"built from {art.commit[:12]}" in words:
+            return words
+        if words.startswith("Already deployed.") and f"running {art.commit[:7]}" in words:
+            return words
+    return None
+
+
+def robot_digest(text: str) -> str | None:
+    m = re.search(r"digest (sha256:[0-9a-f]{64})", text)
+    return m[1] if m else None
+
+
+# ------------------------------------------------------------------ the steps
+
+
+@dataclass
+class Deploy:
+    """What the steps share: where they read from. Suites replace each."""
+
+    root: Path
+    repo: str  # crunchtools/<name>
+    version: str | None
+    reg: Registry
+    http: Http = field(default_factory=_http)
+    hosts: Callable[[], _hosts.Hosts] = _hosts.load
+    timer: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
+
+    def target(self) -> tuple[Config, Artifact, dict]:
+        cfg = config(self.root)
+        art, labels = artifact(self.reg, self.repo, self.version)
+        return cfg, art, labels
+
+    def rt(self, run: Run) -> tuple[Rt, str]:
+        """RT, and the robot's RT user: without it nothing could prove a deploy, so a 2 at once."""
+        hosts = self.hosts()
+        robot = hosts.need("rt.robot")
+        rt = Rt(hosts.need("rt.url"), hosts.need("rt.queue"), run.credential("rt"), self.http)
+        return rt, robot
+
+    # resolve -----------------------------------------------------------
+
+    def resolve(self, run: Run) -> None:
+        cfg, art, labels = self.target()
+        verify(self.reg, art, labels)
+        run.say(f"   {art.image}:{art.version} is {art.digest}, signed, built from {art.commit}")
+        check_registry(run, cfg, art.repo, self.http)
+
+    # ticket ------------------------------------------------------------
+
+    def filed(self, run: Run) -> bool:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        found = rt.find(subject(cfg, art))
+        if found is not None:
+            run.say(
+                f"   adopted RT#{found.number} ({found.status}), filed already for this release"
+            )
+        return found is not None
+
+    def file(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        mine = subject(cfg, art)
+        prefix = f"Deploy {cfg.service} "
+        busy = [
+            (n, s)
+            for n, s, status in rt.search(f"Subject LIKE '{prefix}'")
+            if status in LIVE and s.startswith(prefix) and s != mine
+        ]
+        if busy:
+            number, other = busy[0]
+            raise RefusedError(
+                f"RT#{number} ({other}) is already in flight for {cfg.service}: one deploy at a "
+                f"time; wait for it, then run this again"
+            )
+        number = rt.file(mine, body(cfg, art))
+        run.say(f"   filed RT#{number}: {mine}")
+
+    # wait --------------------------------------------------------------
+
+    def wait(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, robot = self.rt(run)
+        mine = subject(cfg, art)
+        found = rt.find(mine)
+        if found is None:
+            raise CannotRunError(
+                f"no ticket {mine!r} in the queue to wait for; run the ticket step"
+            )
+        number, where = found.number, f"{rt.url}/Ticket/Display.html?id={found.number}"
+        clock, _ = self.timer
+        started = clock()
+
+        def answered() -> str | None:
+            status = rt.status(number)
+            if status == "new" and clock() - started >= NEW_FOR:
+                raise runner.WaitExpiredError(
+                    f"RT#{number} is still new after {NEW_FOR:.0f}s: the deploy robot is not "
+                    f"reading its queue\n{where}"
+                )
+            return None if status in WORKING else status
+
+        status = runner.wait_for(
+            answered, Wait(f"the robot to answer RT#{number}", where, ANSWER_IN, POLL), self.timer
+        )
+        if status == "stalled":
+            raise RefusedError(_stalled(number, cfg, next(rt.said_by(number, robot), None)))
+        if status != "resolved":
+            raise RefusedError(f"RT#{number} was {status}, not deployed\n{where}")
+        said = proof(rt.said_by(number, robot), art)
+        if said is None:
+            raise RefusedError(
+                f"RT#{number} is resolved, and the robot never said it deployed {art.commit[:12]}: "
+                f"a ticket closed by hand is not a deploy. Nothing is known to be running "
+                f"v{art.version}; file a new ticket for it\n{where}"
+            )
+        running = robot_digest(said)
+        run.say(f"   RT#{number}: {said.strip().splitlines()[0]}")
+        run.result = {
+            "repo": art.repo,
+            "version": art.version,
+            "commit": art.commit,
+            "digest": art.digest,
+            "service": cfg.service,
+            "ticket": f"RT#{number}",
+            "running": running,
+        }
+
+
+def _stalled(number: int, cfg: Config, last: str | None) -> str:
+    """The robot's last comment, the service's own output on it, and what it means."""
+    said = last.strip() if last else "the ticket carries no comment from the robot"
+    if "is not in the registry" in said:
+        return (
+            f"RT#{number}: the robot refused {cfg.service!r}, which is not in its registry. The "
+            f"service is the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service "
+            f"and deploy again, which files a new ticket\n{said}"
+        )
+    return f"RT#{number} was handed back by the robot, and nothing it deployed stayed:\n{said}"
+
+
+def steps(d: Deploy) -> list[Step]:
+    return [
+        Step("resolve", d.resolve),
+        Step("ticket", d.file, done=d.filed, needs=("rt",)),
+        Step("wait", d.wait, needs=("rt",)),
+    ]
+
+
+def main(argv: list[str]) -> int:

MEDIUM (Test Coverage): The new command entry point is not exercised by the tests: they invoke the deployment steps directly, so CLI parsing, --version validation, and wiring the selected version into the deployment are unverified.

Suggestion: Add tests for main covering a valid explicit --version and a malformed version, and verify the selected version reaches artifact resolution.

Evidence:

def main(argv: list[str]) -> int:
    d = Deploy(Path.cwd(), repo_of(os.environ), None, Registry())
    p = runner.parser("deploy", steps(d))
    p.add_argument("--version", help="X.Y.Z to deploy (default: the newest release, :latest)")
    args = p.parse_args(argv)
    if args.version is not None and not SEMVER.fullmatch(args.version):
        raise CannotRunError(f"--version wants X.Y.Z, not {args.version!r}")
    d.version = args.version

<!-- gatehouse agent=tests confidence=93 votes=1/1 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:06 UTC
Code Review
gatehouse-findings.toml:1
@@ -206,3 +206,17 @@ rule (profiles/web-application.md) is for host units that mount a shared data \
 directory, where a private `:Z` label would lock the other container out. \
 tests/test_workflows.py pins this mount exactly as shipped (#178, #184).
 """
+
+[[findings]]
+agent = "bugs"
+category = "bug"
+file = "sdlc_jobs/life/deploy.py"
+evidence = "busy = [\n    (n, s)\n    for n, s, status in rt.search(f\"Subject LIKE '{prefix}'\")\n    if status in LIVE and s.startswith(prefix) and s != mine\n]"

MEDIUM (Ledger): This branch silences a bugs finding in sdlc_jobs/life/deploy.py as not-a-bug: RT's TicketSQL LIKE is a substring match: RT wraps the value in % itself (RT::SearchBuilder, LIKE becomes %value%), so Subject LIKE 'Deploy svc ' finds every Deploy svc X.Y.Z. The Desk's own search reads RT the same way. Each hit is then filtered again here with startswith, so the query can only widen what is seen, never narrow it.

Suggestion: Confirm the judgement is right, or drop the entry and fix the finding. The entry stops applying on its own once the code it quotes is gone.

Evidence:

busy = [
    (n, s)
    for n, s, status in rt.search(f"Subject LIKE '{prefix}'")
    if status in LIVE and s.startswith(prefix) and s != mine
]

<!-- gatehouse agent=ledger confidence=100 votes=1/1 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 21:06 UTC
Reviewer

Gatehouse found 5 issues (1 high, 4 medium)

Full review.

<!-- gatehouse review complete -->

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:

Fixed in 6a0acc3

Rt.search now reads every page (up to 20, a 2 beyond that), and test_the_in_flight_search_reads_every_page puts the live ticket past the first page.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})

Fixed in 6a0acc3

inspect checks Labels is a table of text and raises CannotRunError otherwise; test_labels_that_are_not_a_table_are_a_2 pins it.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):

Not a bug: said_by is a generator read newest first, and only the robot's own transactions are opened. A stall reads exactly one (the last word, pinned by test_a_stall_reads_only_the_robots_newest_comment); a resolve stops at the proof, which is the robot's final comment, so one request in practice. RT's REST2 has no bulk attachment-content endpoint, and this runs once per deploy, not in a loop.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):
+            if tid is not None:
+                parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
+                yield "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")
+
+
+def _creator(tx: Mapping) -> str:
+    """A transaction's creator's name, given as an object (fields[Creator]) or a bare name."""
+    creator = tx.get("Creator")
+    return str(creator.get("Name", "") if isinstance(creator, Mapping) else creator or "")
+
+
+def _number(value: object) -> int | None:
+    """RT gives an id as a number, or as a string of digits."""
+    digits = isinstance(value, str) and value.isdigit()
+    return int(str(value)) if digits else value if type(value) is int else None
+
+
+def _text(part: Mapping) -> str:
+    """An attachment's Content, which REST2 gives base64-encoded."""
+    raw = part.get("Content")
+    if not isinstance(raw, str):
+        return ""
+    try:
+        return base64.b64decode(raw, validate=True).decode(errors="replace")
+    except ValueError:
+        return raw
+
+
+def subject(cfg: Config, art: Artifact) -> str:
+    """The Desk's subject (ashigaru desk/cuts.py), so its filing and this one are one ticket."""
+    return f"Deploy {cfg.service} {art.version}"
+
+
+def body(cfg: Config, art: Artifact) -> str:
+    """The robot's ticket body: those three fields and nothing else."""
+    return f"service: {cfg.service}\nrepo: {art.repo}\ncommit: {art.commit}\n"
+
+
+# ------------------------------------------------------------------ the verdict
+
+
+def proof(said: Iterable[str], art: Artifact) -> str | None:
+    """The robot's own comment saying this commit is running and verified, or None.
+
+    The deployer resolves with "Deployed. <unit> is running <commit:7> (built
+    from <revision:12>, ...", or "Already deployed. <unit> was already running
+    <commit:7> ..." when the service was on it. `said` is the robot's comments,
+    newest first, by its RT user alone: anyone else's, in the robot's words or not, proves
+    nothing, and a ticket a person resolved is no deploy.
+    """
+    for text in said:
+        words = text.lstrip()
+        if words.startswith("Deployed.") and f"built from {art.commit[:12]}" in words:
+            return words
+        if words.startswith("Already deployed.") and f"running {art.commit[:7]}" in words:
+            return words
+    return None
+
+
+def robot_digest(text: str) -> str | None:
+    m = re.search(r"digest (sha256:[0-9a-f]{64})", text)
+    return m[1] if m else None
+
+
+# ------------------------------------------------------------------ the steps
+
+
+@dataclass
+class Deploy:
+    """What the steps share: where they read from. Suites replace each."""
+
+    root: Path
+    repo: str  # crunchtools/<name>
+    version: str | None
+    reg: Registry
+    http: Http = field(default_factory=_http)
+    hosts: Callable[[], _hosts.Hosts] = _hosts.load
+    timer: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
+
+    def target(self) -> tuple[Config, Artifact, dict]:
+        cfg = config(self.root)
+        art, labels = artifact(self.reg, self.repo, self.version)
+        return cfg, art, labels
+
+    def rt(self, run: Run) -> tuple[Rt, str]:
+        """RT, and the robot's RT user: without it nothing could prove a deploy, so a 2 at once."""
+        hosts = self.hosts()
+        robot = hosts.need("rt.robot")
+        rt = Rt(hosts.need("rt.url"), hosts.need("rt.queue"), run.credential("rt"), self.http)
+        return rt, robot
+
+    # resolve -----------------------------------------------------------
+
+    def resolve(self, run: Run) -> None:
+        cfg, art, labels = self.target()
+        verify(self.reg, art, labels)
+        run.say(f"   {art.image}:{art.version} is {art.digest}, signed, built from {art.commit}")
+        check_registry(run, cfg, art.repo, self.http)
+
+    # ticket ------------------------------------------------------------
+
+    def filed(self, run: Run) -> bool:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        found = rt.find(subject(cfg, art))
+        if found is not None:
+            run.say(
+                f"   adopted RT#{found.number} ({found.status}), filed already for this release"
+            )
+        return found is not None
+
+    def file(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        mine = subject(cfg, art)
+        prefix = f"Deploy {cfg.service} "
+        busy = [
+            (n, s)
+            for n, s, status in rt.search(f"Subject LIKE '{prefix}'")
+            if status in LIVE and s.startswith(prefix) and s != mine
+        ]
+        if busy:
+            number, other = busy[0]
+            raise RefusedError(
+                f"RT#{number} ({other}) is already in flight for {cfg.service}: one deploy at a "
+                f"time; wait for it, then run this again"
+            )
+        number = rt.file(mine, body(cfg, art))
+        run.say(f"   filed RT#{number}: {mine}")
+
+    # wait --------------------------------------------------------------
+
+    def wait(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, robot = self.rt(run)
+        mine = subject(cfg, art)
+        found = rt.find(mine)
+        if found is None:
+            raise CannotRunError(
+                f"no ticket {mine!r} in the queue to wait for; run the ticket step"
+            )
+        number, where = found.number, f"{rt.url}/Ticket/Display.html?id={found.number}"
+        clock, _ = self.timer
+        started = clock()
+
+        def answered() -> str | None:
+            status = rt.status(number)
+            if status == "new" and clock() - started >= NEW_FOR:
+                raise runner.WaitExpiredError(
+                    f"RT#{number} is still new after {NEW_FOR:.0f}s: the deploy robot is not "
+                    f"reading its queue\n{where}"
+                )
+            return None if status in WORKING else status
+
+        status = runner.wait_for(
+            answered, Wait(f"the robot to answer RT#{number}", where, ANSWER_IN, POLL), self.timer
+        )
+        if status == "stalled":
+            raise RefusedError(_stalled(number, cfg, next(rt.said_by(number, robot), None)))
+        if status != "resolved":
+            raise RefusedError(f"RT#{number} was {status}, not deployed\n{where}")
+        said = proof(rt.said_by(number, robot), art)
+        if said is None:
+            raise RefusedError(
+                f"RT#{number} is resolved, and the robot never said it deployed {art.commit[:12]}: "
+                f"a ticket closed by hand is not a deploy. Nothing is known to be running "
+                f"v{art.version}; file a new ticket for it\n{where}"
+            )
+        running = robot_digest(said)
+        run.say(f"   RT#{number}: {said.strip().splitlines()[0]}")
+        run.result = {
+            "repo": art.repo,
+            "version": art.version,
+            "commit": art.commit,
+            "digest": art.digest,
+            "service": cfg.service,
+            "ticket": f"RT#{number}",
+            "running": running,
+        }
+
+
+def _stalled(number: int, cfg: Config, last: str | None) -> str:
+    """The robot's last comment, the service's own output on it, and what it means."""
+    said = last.strip() if last else "the ticket carries no comment from the robot"
+    if "is not in the registry" in said:
+        return (
+            f"RT#{number}: the robot refused {cfg.service!r}, which is not in its registry. The "
+            f"service is the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service "
+            f"and deploy again, which files a new ticket\n{said}"
+        )
+    return f"RT#{number} was handed back by the robot, and nothing it deployed stayed:\n{said}"
+
+
+def steps(d: Deploy) -> list[Step]:
+    return [
+        Step("resolve", d.resolve),
+        Step("ticket", d.file, done=d.filed, needs=("rt",)),
+        Step("wait", d.wait, needs=("rt",)),
+    ]
+
+
+def main(argv: list[str]) -> int:

Fixed in 6a0acc3

main takes the Deploy it runs; test_the_entry_carries_version_to_the_artifact_and_refuses_a_malformed_one runs the resolve step through main with --version 1.2.3 (skopeo asked for :1.2.3 only, never :latest) and refuses --version 1.2.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
gatehouse-findings.toml:1
@@ -206,3 +206,17 @@ rule (profiles/web-application.md) is for host units that mount a shared data \
 directory, where a private `:Z` label would lock the other container out. \
 tests/test_workflows.py pins this mount exactly as shipped (#178, #184).
 """
+
+[[findings]]
+agent = "bugs"
+category = "bug"
+file = "sdlc_jobs/life/deploy.py"
+evidence = "busy = [\n    (n, s)\n    for n, s, status in rt.search(f\"Subject LIKE '{prefix}'\")\n    if status in LIVE and s.startswith(prefix) and s != mine\n]"

Not a bug: the judgement stands. RT TicketSQL LIKE is a substring match (RT adds the % on both sides itself), so Subject LIKE 'Deploy svc ' matches every Deploy svc X.Y.Z; each hit is then filtered again with startswith, so the query can only widen what is seen. The in-flight search also reads every page now (6a0acc3).

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):

Not a bug: said_by is a generator read newest first, opening only the robot's own transactions and only as far as the caller reads: one for a stall, back to the proof (the robot's final comment) for a resolve. RT's REST2 has no bulk attachment-content endpoint, and this runs once per deploy.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:25 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    return doc
+
+
+def newest_version(reg: Registry, repo: str) -> str:
+    """The version `:latest` is labelled: the newest release, which `promote` moved it to."""
+    doc = inspect(reg, f"quay.io/{repo}:latest")
+    if doc is None:
+        raise RefusedError(f"quay.io/{repo} has no :latest, so no release to deploy")
+    version = _version_of(doc.get("Labels") or {})
+    if version is None:
+        raise RefusedError(
+            f"quay.io/{repo}:latest carries no version label; name one with --version"
+        )
+    return version
+
+
+def tag_commit(reg: Registry, repo: str, version: str) -> str:
+    """The commit tag vX.Y.Z names (peeled, for an annotated tag); a 1 when there is no tag."""
+    tag = f"refs/tags/v{version}"
+    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
+    if proc.returncode != 0:
+        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
+    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
+    refs = {name: sha for sha, _, name in listed}
+    commit = refs.get(f"{tag}^{{}}") or refs.get(tag)
+    if commit is None:
+        raise RefusedError(f"{repo} has no tag v{version}: no release to deploy")
+    if not COMMIT.fullmatch(commit):
+        raise CannotRunError(f"{tag} names {commit!r}, which is no commit")
+    return commit
+
+
+def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
+    """The release `version` (the newest without one) and its image's labels, read back."""
+    version = version or newest_version(reg, repo)
+    commit = tag_commit(reg, repo, version)
+    ref = f"quay.io/{repo}:{version}"
+    doc = inspect(reg, ref)
+    if doc is None:
+        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
+    digest = doc.get("Digest")
+    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
+        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
+    labels = doc.get("Labels") or {}
+    return Artifact(repo, version, commit, digest), labels
+
+
+def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
+    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
+    revision = labels.get(REVISION, "")
+    if revision != art.commit:
+        raise RefusedError(
+            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
+            f"and v{art.version} tags {art.commit}: it is not that release's image"
+        )
+    with TemporaryDirectory() as key_dir:
+        key = Path(key_dir) / "fleet.pub"
+        key.write_text(FLEET_PUBLIC_KEY)
+        proc = reg.run(
+            [
+                "cosign",
+                "verify",
+                "--insecure-ignore-tlog",
+                "--key",
+                str(key),
+                f"{art.image}@{art.digest}",
+            ]
+        )
+    if proc.returncode == 0:
+        return
+    err = (proc.stderr or "").strip()
+    if re.search(
+        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
+        err,
+        re.IGNORECASE,
+    ):
+        raise RefusedError(
+            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
+            f"digest `promote` signed is ever deployed"
+        )
+    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
+
+
+# ------------------------------------------------------------------ the robot's registry
+
+
+# One HTTP request: method, https URL, headers, body. Tools.http, through the
+# jobs' one opener (_github.SafeRedirect); suites pass a fake.
+Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
+
+
+def _http() -> Http:
+    return Tools().http
+
+
+def _fetch(http: Http, url: str) -> bytes:
+    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
+    if answer.status != HTTP_OK:
+        raise OSError(f"{url} answered {answer.status}")
+    return answer.body
+
+
+def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
+    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
+
+    A registry that cannot be read is said and passed: the robot judges the
+    name itself, and its refusal comes back from `wait` as a 1.
+    """
+    try:
+        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
+        unread = "" if isinstance(rows, dict) else "it has no [service] table"
+    except (OSError, ValueError, CannotRunError) as exc:
+        rows, unread = None, str(exc)
+    if unread or not isinstance(rows, dict):
+        run.say(
+            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
+        )
+        return
+    row = rows.get(cfg.service)
+    if not isinstance(row, dict):
+        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
+        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
+        raise RefusedError(
+            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
+            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
+        )
+    if row.get("repo") != repo:
+        raise RefusedError(
+            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
+        )
+    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
+
+
+# ------------------------------------------------------------------ RT
+
+
+@dataclass(frozen=True)
+class Ticket:
+    number: int
+    status: str
+
+
+class Rt:
+    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
+
+    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
+        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
+
+    def _call(self, path: str, body: object = None) -> object:
+        where = path.split("?", maxsplit=1)[0]
+        headers = {
+            "Authorization": f"token {self.token}",
+            "Accept": "application/json",
+            "Content-Type": "application/json",
+            "User-Agent": "sdlc-deploy",
+        }
+        payload = None if body is None else json.dumps(body).encode()
+        answer = self.http(
+            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
+        )
+        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
+            raise CannotRunError(f"RT answered {answer.status} to {where}")
+        try:
+            return json.loads(answer.body or b"null")
+        except ValueError as exc:
+            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
+
+    def _items(self, path: str) -> list[Mapping]:
+        found = self._call(path)
+        items = found.get("items") if isinstance(found, Mapping) else None
+        if not isinstance(items, list):
+            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
+        return [i for i in items if isinstance(i, Mapping)]
+
+    def search(self, where: str) -> list[tuple[int, str, str]]:
+        """(id, subject, status) of each queue ticket TicketSQL `where` matches, newest first."""
+        query = urllib.parse.urlencode(
+            {
+                "query": f"Queue = '{self.queue}' AND {where}",
+                "orderby": "id",
+                "order": "DESC",
+                "per_page": PAGE,
+                "fields": "Subject,Status",
+            }
+        )
+        out = []
+        for item in self._items(f"/tickets?{query}"):
+            number = _number(item.get("id"))
+            if number is not None:
+                out.append((number, str(item.get("Subject", "")), str(item.get("Status", ""))))
+        return out
+
+    def find(self, subject: str) -> Ticket | None:
+        """The newest ticket whose subject is exactly `subject`, compared again here."""
+        for number, found, status in self.search(f"Subject = '{subject}'"):
+            if found == subject:
+                return Ticket(number, status)
+        return None
+
+    def file(self, subject: str, content: str) -> int:
+        body = {
+            "Queue": self.queue,
+            "Subject": subject,
+            "Content": content,
+            "ContentType": "text/plain",
+        }
+        found = self._call("/ticket", body)
+        number = _number(found.get("id") if isinstance(found, Mapping) else None)
+        if number is None:
+            raise CannotRunError("RT filed the ticket and answered with no id")
+        return number
+
+    def status(self, number: int) -> str:
+        found = self._call(f"/ticket/{number}?fields=Status")
+        status = found.get("Status") if isinstance(found, Mapping) else None
+        if not isinstance(status, str):
+            raise CannotRunError(f"RT#{number} has no status")
+        return status
+
+    def said_by(self, number: int, who: str) -> Iterator[str]:
+        """What `who` commented or replied on the ticket, newest first.
+
+        Only `who`'s transactions are opened, one at a time and only as far as
+        the caller reads: the robot's last word, or back to its proof.
+        """
+        query = urllib.parse.urlencode(
+            {"fields": "Type,Creator", "fields[Creator]": "Name", "per_page": 100}
+        )
+        ids = [
+            _number(tx.get("id"))
+            for tx in self._items(f"/ticket/{number}/history?{query}")
+            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
+        ]
+        for tid in reversed(ids):
+            if tid is not None:
+                parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
+                yield "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")
+
+
+def _creator(tx: Mapping) -> str:
+    """A transaction's creator's name, given as an object (fields[Creator]) or a bare name."""
+    creator = tx.get("Creator")
+    return str(creator.get("Name", "") if isinstance(creator, Mapping) else creator or "")
+
+
+def _number(value: object) -> int | None:
+    """RT gives an id as a number, or as a string of digits."""
+    digits = isinstance(value, str) and value.isdigit()
+    return int(str(value)) if digits else value if type(value) is int else None
+
+
+def _text(part: Mapping) -> str:
+    """An attachment's Content, which REST2 gives base64-encoded."""
+    raw = part.get("Content")
+    if not isinstance(raw, str):
+        return ""
+    try:
+        return base64.b64decode(raw, validate=True).decode(errors="replace")
+    except ValueError:
+        return raw
+
+
+def subject(cfg: Config, art: Artifact) -> str:
+    """The Desk's subject (ashigaru desk/cuts.py), so its filing and this one are one ticket."""
+    return f"Deploy {cfg.service} {art.version}"
+
+
+def body(cfg: Config, art: Artifact) -> str:
+    """The robot's ticket body: those three fields and nothing else."""
+    return f"service: {cfg.service}\nrepo: {art.repo}\ncommit: {art.commit}\n"
+
+
+# ------------------------------------------------------------------ the verdict
+
+
+def proof(said: Iterable[str], art: Artifact) -> str | None:
+    """The robot's own comment saying this commit is running and verified, or None.
+
+    The deployer resolves with "Deployed. <unit> is running <commit:7> (built
+    from <revision:12>, ...", or "Already deployed. <unit> was already running
+    <commit:7> ..." when the service was on it. `said` is the robot's comments,
+    newest first, by its RT user alone: anyone else's, in the robot's words or not, proves
+    nothing, and a ticket a person resolved is no deploy.
+    """
+    for text in said:
+        words = text.lstrip()
+        if words.startswith("Deployed.") and f"built from {art.commit[:12]}" in words:
+            return words
+        if words.startswith("Already deployed.") and f"running {art.commit[:7]}" in words:
+            return words
+    return None
+
+
+def robot_digest(text: str) -> str | None:
+    m = re.search(r"digest (sha256:[0-9a-f]{64})", text)
+    return m[1] if m else None
+
+
+# ------------------------------------------------------------------ the steps
+
+
+@dataclass
+class Deploy:
+    """What the steps share: where they read from. Suites replace each."""
+
+    root: Path
+    repo: str  # crunchtools/<name>
+    version: str | None
+    reg: Registry
+    http: Http = field(default_factory=_http)
+    hosts: Callable[[], _hosts.Hosts] = _hosts.load
+    timer: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
+
+    def target(self) -> tuple[Config, Artifact, dict]:
+        cfg = config(self.root)
+        art, labels = artifact(self.reg, self.repo, self.version)
+        return cfg, art, labels
+
+    def rt(self, run: Run) -> tuple[Rt, str]:
+        """RT, and the robot's RT user: without it nothing could prove a deploy, so a 2 at once."""
+        hosts = self.hosts()
+        robot = hosts.need("rt.robot")
+        rt = Rt(hosts.need("rt.url"), hosts.need("rt.queue"), run.credential("rt"), self.http)
+        return rt, robot
+
+    # resolve -----------------------------------------------------------
+
+    def resolve(self, run: Run) -> None:
+        cfg, art, labels = self.target()
+        verify(self.reg, art, labels)
+        run.say(f"   {art.image}:{art.version} is {art.digest}, signed, built from {art.commit}")
+        check_registry(run, cfg, art.repo, self.http)
+
+    # ticket ------------------------------------------------------------
+
+    def filed(self, run: Run) -> bool:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        found = rt.find(subject(cfg, art))
+        if found is not None:
+            run.say(
+                f"   adopted RT#{found.number} ({found.status}), filed already for this release"
+            )
+        return found is not None
+
+    def file(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, _robot = self.rt(run)
+        mine = subject(cfg, art)
+        prefix = f"Deploy {cfg.service} "
+        busy = [
+            (n, s)
+            for n, s, status in rt.search(f"Subject LIKE '{prefix}'")
+            if status in LIVE and s.startswith(prefix) and s != mine
+        ]
+        if busy:
+            number, other = busy[0]
+            raise RefusedError(
+                f"RT#{number} ({other}) is already in flight for {cfg.service}: one deploy at a "
+                f"time; wait for it, then run this again"
+            )
+        number = rt.file(mine, body(cfg, art))
+        run.say(f"   filed RT#{number}: {mine}")
+
+    # wait --------------------------------------------------------------
+
+    def wait(self, run: Run) -> None:
+        cfg, art, _ = self.target()
+        rt, robot = self.rt(run)
+        mine = subject(cfg, art)
+        found = rt.find(mine)
+        if found is None:
+            raise CannotRunError(
+                f"no ticket {mine!r} in the queue to wait for; run the ticket step"
+            )
+        number, where = found.number, f"{rt.url}/Ticket/Display.html?id={found.number}"
+        clock, _ = self.timer
+        started = clock()
+
+        def answered() -> str | None:
+            status = rt.status(number)
+            if status == "new" and clock() - started >= NEW_FOR:
+                raise runner.WaitExpiredError(
+                    f"RT#{number} is still new after {NEW_FOR:.0f}s: the deploy robot is not "
+                    f"reading its queue\n{where}"
+                )
+            return None if status in WORKING else status
+
+        status = runner.wait_for(
+            answered, Wait(f"the robot to answer RT#{number}", where, ANSWER_IN, POLL), self.timer
+        )
+        if status == "stalled":
+            raise RefusedError(_stalled(number, cfg, next(rt.said_by(number, robot), None)))
+        if status != "resolved":
+            raise RefusedError(f"RT#{number} was {status}, not deployed\n{where}")
+        said = proof(rt.said_by(number, robot), art)
+        if said is None:
+            raise RefusedError(
+                f"RT#{number} is resolved, and the robot never said it deployed {art.commit[:12]}: "
+                f"a ticket closed by hand is not a deploy. Nothing is known to be running "
+                f"v{art.version}; file a new ticket for it\n{where}"
+            )
+        running = robot_digest(said)
+        run.say(f"   RT#{number}: {said.strip().splitlines()[0]}")
+        run.result = {
+            "repo": art.repo,
+            "version": art.version,
+            "commit": art.commit,
+            "digest": art.digest,
+            "service": cfg.service,
+            "ticket": f"RT#{number}",
+            "running": running,
+        }
+
+
+def _stalled(number: int, cfg: Config, last: str | None) -> str:
+    """The robot's last comment, the service's own output on it, and what it means."""
+    said = last.strip() if last else "the ticket carries no comment from the robot"
+    if "is not in the registry" in said:
+        return (
+            f"RT#{number}: the robot refused {cfg.service!r}, which is not in its registry. The "
+            f"service is the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service "
+            f"and deploy again, which files a new ticket\n{said}"
+        )
+    return f"RT#{number} was handed back by the robot, and nothing it deployed stayed:\n{said}"
+
+
+def steps(d: Deploy) -> list[Step]:
+    return [
+        Step("resolve", d.resolve),
+        Step("ticket", d.file, done=d.filed, needs=("rt",)),
+        Step("wait", d.wait, needs=("rt",)),
+    ]
+
+
+def main(argv: list[str]) -> int:

Fixed in 6a0acc3

main takes the Deploy it runs, and a suite drives it with a valid and a malformed --version.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:26 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,653 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)

Fixed in 6a0acc3

Config has a docstring saying what via and service mean.

fatherlinux fatherlinux commented on code on Dec 04, 2026 21:26 UTC
Code Review
gatehouse-findings.toml:1
@@ -206,3 +206,17 @@ rule (profiles/web-application.md) is for host units that mount a shared data \
 directory, where a private `:Z` label would lock the other container out. \
 tests/test_workflows.py pins this mount exactly as shipped (#178, #184).
 """
+
+[[findings]]
+agent = "bugs"
+category = "bug"
+file = "sdlc_jobs/life/deploy.py"
+evidence = "busy = [\n    (n, s)\n    for n, s, status in rt.search(f\"Subject LIKE '{prefix}'\")\n    if status in LIVE and s.startswith(prefix) and s != mine\n]"

Not a bug: the judgement stands. RT TicketSQL LIKE is a substring match (RT wraps the value in % itself), so the prefix finds every Deploy <service> X.Y.Z, and each hit is filtered again with startswith. The search now also reads every page (6a0acc3).

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:27 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,672 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+SEARCH_PAGES = 20
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
+    takes the service ("robot" here), and `service`, the container name the
+    robot's registry keys on and the ticket's `service:` line names."""
+
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    labels = doc["Labels"]

LOW (Test Coverage): The new labels test covers a non-dictionary Labels value, but not the other invalid case in this validation: a dictionary containing a non-string value. The all-values check is therefore untested.

Suggestion: Add a case with Labels set to a dictionary containing a non-string value and assert that inspect raises CannotRunError.

Evidence:

if not isinstance(labels, dict) or not all(isinstance(v, str) for v in labels.values()):

<!-- gatehouse agent=tests confidence=98 votes=1/1 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 21:27 UTC
Code Review
sdlc_jobs/life/deploy.py:1
@@ -0,0 +1,672 @@
+"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
+
+docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
+phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
+
+    [tool.sdlc.deploy]
+    via = "robot"                 # "robot" | "ssh"
+    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
+    # for via = "ssh" only:
+    host = "web"
+    unit = "acquacotta.service"
+    health = { port = 8080, path = "/health" }
+    settle = 60
+
+Three steps, each in a container of its own (_runner), each reading back what
+it needs rather than trusting an earlier one:
+
+    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
+              fleet key, labelled with the commit tag vX.Y.Z names; and the
+              service in the robot's registry for this repo, when the
+              registry can be read. No credential.
+    ticket    the `Deploy` ticket the Desk would file, with its subject, after
+              searching the queue for that subject: one already filed is
+              adopted, never filed twice. Refused while another ticket for the
+              service is in flight.
+    wait      until the robot answers. Resolved WITH the robot's own
+              "Deployed." comment naming this commit is a 0; resolved without
+              it (a person closed it) is a 1, because that is not a deploy;
+              stalled is a 1 with the robot's last word; still `new` after
+              five minutes is a 2: the robot is not reading its queue.
+
+The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
+format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
+else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
+own filing and this one find each other.
+"""
+
+from __future__ import annotations
+
+import base64
+import json
+import os
+import re
+import subprocess
+import time
+import tomllib
+import urllib.parse
+from collections.abc import Callable, Iterable, Iterator, Mapping
+from dataclasses import dataclass, field
+from pathlib import Path
+from tempfile import TemporaryDirectory
+
+from sdlc_jobs._core import (
+    DIGEST,
+    FLEET_PUBLIC_KEY,
+    SEMVER,
+    CannotRunError,
+    Response,
+    Tools,
+    tool_sdlc,
+)
+from sdlc_jobs.life import _hosts
+from sdlc_jobs.life import _runner as runner
+from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
+from sdlc_jobs.life.test import repo_of
+
+ORG = "crunchtools"
+QUEUE = "Deploy"
+REVISION = "org.opencontainers.image.revision"
+VERSION_LABELS = ("org.opencontainers.image.version", "version")
+COMMIT = re.compile(r"[0-9a-f]{40}")
+# The robot's registry key: a podman container name, which may carry dots.
+SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
+ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
+UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
+HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
+VIAS = ("robot", "ssh")
+SSH_KEYS = ("host", "unit", "health", "settle")
+PORT_MAX = 65535
+DEFAULT_SETTLE = 60
+# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
+TOOL_TIMEOUT = 120
+PAGE = 50
+SEARCH_PAGES = 20
+HTTP_OK = 200
+HTTP_REDIRECT = 300
+
+# Where the robot's registry is reviewed and kept. Read when it can be, so a
+# wrong service name is refused here, before a ticket the robot would refuse;
+# when it cannot be read, the robot's own refusal is the check.
+REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
+RT_API = "/REST/2.0"
+ATTACHMENT_FIELDS = "fields=Content,ContentType"
+# How long a ticket may sit `new` before the robot is taken not to be reading
+# its queue, and how long a ticket it took may take: its build wait, a
+# pre-deploy dump, `ready` and `settle` together.
+NEW_FOR = 300.0
+ANSWER_IN = 1800.0
+POLL = 15.0
+# Statuses: the robot's working ones, its verdicts, and what RT has besides.
+WORKING = ("new", "open")
+LIVE = ("new", "open")
+
+
+class ConfigError(CannotRunError):
+    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
+
+
+@dataclass(frozen=True)
+class Config:
+    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
+    takes the service ("robot" here), and `service`, the container name the
+    robot's registry keys on and the ticket's `service:` line names."""
+
+    via: str
+    service: str
+
+
+def _require(ok: bool, why: str) -> None:
+    if not ok:
+        raise ConfigError(f"[tool.sdlc.deploy] {why}")
+
+
+def config(root: Path) -> Config:
+    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
+    table = tool_sdlc(root).get("deploy")
+    if table is None:
+        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
+    _require(isinstance(table, dict), "is not a table")
+    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
+    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
+    via, service = table.get("via"), table.get("service")
+    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
+    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
+    _require(named, f"service must be the service's container name: {service!r}")
+    if via == "ssh":
+        _ssh_shape(table)
+        raise CannotRunError(
+            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
+            "move the service into the robot's registry, or deploy it by hand"
+        )
+    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
+    _require(
+        not extra,
+        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
+        'holds them for via = "robot"',
+    )
+    return Config(str(via), str(service))
+
+
+def _ssh_shape(table: Mapping[str, object]) -> None:
+    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
+    health = table.get("health")
+    if not isinstance(health, dict) or set(health) != {"port", "path"}:
+        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
+    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
+    settle = table.get("settle", DEFAULT_SETTLE)
+    shapes = {
+        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
+        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
+        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
+        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
+        and bool(HEALTH_PATH.fullmatch(path)),
+        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
+    }
+    for why, ok in shapes.items():
+        _require(ok, why)
+
+
+# ------------------------------------------------------------------ the artifact
+
+
+@dataclass(frozen=True)
+class Artifact:
+    repo: str  # crunchtools/<name>
+    version: str
+    commit: str  # the commit vX.Y.Z tags, forty characters
+    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
+
+    @property
+    def image(self) -> str:
+        return f"quay.io/{self.repo}"
+
+
+class Registry:
+    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
+
+    def __init__(self, tools: Tools | None = None) -> None:
+        self.tools = tools or Tools()
+
+    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
+        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
+
+
+def _version_of(labels: Mapping[str, str]) -> str | None:
+    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
+    raw = raw.strip().removeprefix("v")
+    return raw if SEMVER.fullmatch(raw) else None
+
+
+def inspect(reg: Registry, ref: str) -> dict | None:
+    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
+    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
+    if proc.returncode != 0:
+        err = (proc.stderr or "").strip()
+        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
+            return None
+        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
+    try:
+        doc = json.loads(proc.stdout or "")
+    except ValueError as exc:
+        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
+    if not isinstance(doc, dict):
+        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
+    labels = doc["Labels"]

LOW (General Review): If the inspect response omits Labels, this indexing raises a bare KeyError instead of reporting a CannotRunError with the inspected ref. That makes malformed registry responses harder to diagnose.

Suggestion: Check whether Labels is present and raise a CannotRunError that includes ref when it is missing, before validating its type.

Evidence:

labels = doc["Labels"]

<!-- gatehouse agent=general confidence=94 votes=1/1 -->

ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 21:27 UTC
Reviewer

Gatehouse found 2 issues (2 low)

Reviewed 1 commit since b6722b1 (incremental).

5 finding(s) dropped: their evidence is not in the diff.

1 finding(s) not re-raised: already answered on this PR.

<!-- gatehouse review complete -->

fatherlinux fatherlinux commented on Dec 04, 2026 21:59 UTC
Author

Second-seat check of sdlc deploy via the robot (a2367), at 6a0acc3

I read deploy.py, _runner.py and _hosts.py, and I read crunchtools/deployer at cba8835 to get the robot's real contract. I ran each attack against this PR's own FakeRt/FakeRegistry and inspected the live :latest labels on quay. Results are below, worst first. Six findings are confirmed: two high, two medium, two low. Two more are plausible.

Findings

1. HIGH. It reports a deploy that did not happen: a stale resolved ticket is adopted (confirmed). filed()/find() adopt the newest ticket with the subject whatever its status, and wait accepts that ticket's old "Deployed." as proof. Here is the repro. RT#100 Deploy svc 1.2.3 was resolved with the robot's proof. Later RT#101 Deploy svc 1.2.4 was resolved too. Then someone runs sdlc deploy --version 1.2.3 to roll back. The result is == ticket: already done, adopted RT#100 (resolved), exit 0 with version: 1.2.3. Nothing was filed, and 1.2.4 is still running. test_a_ticket_already_filed_is_adopted_never_filed_twice currently pins this as the intended behaviour. This is the #341/#347 pattern again: the done predicate skips file(), and the proof comes from a ticket older than this run. The fix is to adopt only a ticket that is new/open, or one created after the service's newest resolved Deploy ticket. A resolved or stalled match should never stand in for this run.

2. HIGH. The default version is read from inherited base-image labels, so it can deploy the wrong release (confirmed on live images). _version_of prefers org.opencontainers.image.version, then version. Neither one is the app's version on the two registered services:

  • quay.io/crunchtools/acquacotta:latest has revision e9342e8a… (= v2.39.0), no oci version label, and version = "3.0.1", which is inherited.

  • quay.io/crunchtools/mcp-nagios:latest has revision e67975cd… (= v0.11.1) and org.opencontainers.image.version = "3.14.10", which is Python's. Its version is 0.11.1.
  • Today a bare sdlc deploy refuses on both services ("has no tag v3.0.1" / "v3.14.10"). The day an inherited value equals an existing tag, it silently deploys that older, still correctly signed release as "the newest". The fix is to derive the version from :latest's revision (the tag that points at it), not from a free-text label.

    3. MEDIUM. The ticket step files a commit nobody verified (confirmed). resolve, ticket and wait run in separate containers, and each calls target() again. Only resolve calls verify(). In the repro, resolve passes on commit aaaa…. Then the tag is moved and the image is re-pushed unsigned with revision bbbb…. --step ticket then files commit: bbbb…. The same thing happens with no --version if :latest is promoted between the two steps. Either verify() in file() (and in filed()) on what it is about to file, or pin version+commit+digest once and carry them forward.

    4. MEDIUM. What the robot ran is never compared to the signed digest (confirmed). The robot deploys <image>:gated-<commit> by tag, checks it against :main/:latest by image ID, and does no cosign (deployer stage.py:393-424; there is no cosign anywhere in src). wait extracts the robot's digest sha256:… into running and never compares it. In the repro, the robot says digest sha256:eeee… while resolve verified sha256:cccc…, and the result is exit 0 with "digest": cccc… and "running": eeee…. Refuse (exit 1) when running is present and differs from art.digest. "Already deployed." names no digest, so for that case say that the digest is unproven.

    5. LOW. A version whose ticket was closed by hand or stalled can never be deployed through sdlc again (confirmed). Because of #1, every rerun adopts the same dead ticket and exits 1. The message says "file a new ticket for it", but sdlc deploy never will. This is tonight's failure in a new form: once the service name is right, a hand-closed ticket for that version blocks it permanently. A rolled-back commit is correctly unretryable, because the robot blacklists it. A hand-closed one is not.

    6. LOW. The in-flight check only sees the Desk's subject convention (confirmed). The robot ignores Subject and keys on the body's service: line (deployer rt.py:358-383, runner.py never reads Subject). An open ticket for the same service with any other subject, such as one filed by hand, is invisible to the check, so a second revision gets filed. The robot serializes the two, so the effect is ordering, not corruption. It does defeat "one revision in flight".

    7. PLAUSIBLE, low. proof() scans past the robot's newer comments. It returns the first "Deployed." it finds, newest first, even when a newer robot comment (a refusal or a rollback) sits above it. The robot itself never resolves after a rollback or reopens a resolved ticket, so this needs a person to reopen the ticket, the robot to fail it, and a person to resolve it. Fixing #1 mostly closes it. Judging only the robot's newest comment closes it fully.

    8. PLAUSIBLE, low, fails closed. said_by reads only the first page (per_page=100) of the ticket's history. On a long ticket the proof can be missed, which gives a false 1, never a false 0. Also, RT REST2 search returns only tickets the token's user can see, so a token missing ShowTicket on Deploy reads as "no ticket". It would then refuse nothing and file. I did not verify this against the live RT.

    Attacks that held

  • "Deployed." written by a person or another RT user: refused. said_by filters on Creator.Name == [rt] robot. A REST2 answer without fields[Creator] gives "" and fails closed.

  • "Deployed." naming another commit: refused. It needs built from <commit:12>, and live release images carry revision = tag commit (checked on both services).

  • A ticket in another queue: never matched. Queue = '…' is in every TicketSQL query, and the service/version regexes keep quotes out.

  • Adopting a ticket for another version: the subject carries the version and is compared exactly. Another commit under the same subject can't prove a deploy (the built from check). Wrong status is #1.

  • A digest signed by another key: refused (cosign verify --key fleet). Any other cosign error is a 2, not a pass.

  • A revision label that matches but comes from another repo: the robot refuses a ticket whose repo: differs from its registry row (deployer runner.py:425), and resolve checks the row's repo too. The fleet signature is not bound to a repo, which matters only to someone who can already push to quay.

  • --resume: deploy sets no resume_ref, so --resume is parsed and ignored. Adoption happens on every run regardless, see #1.

  • RT errors and pagination: non-2xx, non-JSON and a missing items are all a 2, never "no ticket". The search stops on a short page and gives a 2 past 20 pages.

  • services.toml unreadable: fail-open, by design. A wrong name is then refused by the robot as stalled with "is not in the registry", and _stalled turns that into a 1 that names the fix. The registry shape the code assumes ([service."<container>"], repo = "owner/name") matches deployer registry.py:459-463. Tonight's exact case (wrong name, refused, closed by hand) is a 1.

  • Credentials: resolve holds none. ticket/wait hold only rt, and the plan test pins that. The registry fetch carries no token, and SafeRedirect strips it on a cross-host hop. wait holds a write-capable token it only reads with, but that is the single RT credential and can't be narrowed.
  • The repro harness imports this PR's test module unchanged, so each confirmed finding drops in as a test.

    fatherlinux fatherlinux commented on code on Dec 04, 2026 22:20 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,672 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential.
    +    ticket    the `Deploy` ticket the Desk would file, with its subject, after
    +              searching the queue for that subject: one already filed is
    +              adopted, never filed twice. Refused while another ticket for the
    +              service is in flight.
    +    wait      until the robot answers. Resolved WITH the robot's own
    +              "Deployed." comment naming this commit is a 0; resolved without
    +              it (a person closed it) is a 1, because that is not a deploy;
    +              stalled is a 1 with the robot's last word; still `new` after
    +              five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Iterable, Iterator, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.test import repo_of
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +VERSION_LABELS = ("org.opencontainers.image.version", "version")
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def _version_of(labels: Mapping[str, str]) -> str | None:
    +    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
    +    raw = raw.strip().removeprefix("v")
    +    return raw if SEMVER.fullmatch(raw) else None
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc["Labels"]

    Fixed in 3b95568

    test_skopeo_that_cannot_answer_is_a_2_never_a_missing_image now includes Labels {"version": 3} (a non-string value), as well as missing Labels and a missing Digest.

    fatherlinux fatherlinux commented on code on Dec 04, 2026 22:20 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,672 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential.
    +    ticket    the `Deploy` ticket the Desk would file, with its subject, after
    +              searching the queue for that subject: one already filed is
    +              adopted, never filed twice. Refused while another ticket for the
    +              service is in flight.
    +    wait      until the robot answers. Resolved WITH the robot's own
    +              "Deployed." comment naming this commit is a 0; resolved without
    +              it (a person closed it) is a 1, because that is not a deploy;
    +              stalled is a 1 with the robot's last word; still `new` after
    +              five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Iterable, Iterator, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.test import repo_of
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +VERSION_LABELS = ("org.opencontainers.image.version", "version")
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def _version_of(labels: Mapping[str, str]) -> str | None:
    +    raw = next((labels[k] for k in VERSION_LABELS if labels.get(k)), "")
    +    raw = raw.strip().removeprefix("v")
    +    return raw if SEMVER.fullmatch(raw) else None
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc["Labels"]

    Fixed in 3b95568

    inspect reads doc.get("Labels") and raises CannotRunError naming the ref when it is missing or not a table of text; a missing or malformed Digest is checked there too. Both cases are in the suite.

    fatherlinux fatherlinux commented on Dec 04, 2026 22:20 UTC
    Author

    Answers to the second-seat check (#issuecomment-7425398469), all in 3b95568. The suite is 42 cases, and each confirmed finding below has a test of its own.

    1. HIGH, stale resolved ticket adopted. Fixed in 3b95568
    Only a ticket that is new/open and whose body names this service, repo and commit is adopted. A resolved or stalled ticket is never adopted, so a rollback or a retry files its own. The wait step judges the ticket this run filed or adopted, read back from the run's journal (falling back to the one in flight). The test that pinned the old behaviour is replaced by test_a_resolved_ticket_is_history_and_a_fresh_one_is_filed and test_a_rollback_to_an_older_release_files_its_own_ticket, and test_the_wait_judges_the_ticket_its_run_filed_from_the_journal covers the binding across containers.

    2. HIGH, version from inherited labels. Fixed in 3b95568
    No label is read for the version any more. With --version, the tag vX.Y.Z and quay X.Y.Z are used. Without it, the newest vX.Y.Z tag is used, and only when quay's X.Y.Z is the same digest as :latest; otherwise it's a 1 that asks for --version. The fake images carry acquacotta's and mcp-nagios's inherited 3.0.1 / 3.14.10 labels (test_the_version_is_the_newest_tag_never_an_inherited_label, test_the_newest_tag_that_is_not_latest_asks_for_a_version).

    3. MEDIUM, ticket step files an unverified commit. Fixed in 3b95568
    target() runs verify() (signature, revision == tag commit), so every step, filed() included, verifies what it acts on. Your repro is test_the_ticket_step_verifies_the_release_again.

    4. MEDIUM, robot's digest never compared. Fixed in 3b95568
    A "Deployed." digest must be the release's or one of its own platform manifests, read from the signed index with skopeo inspect --raw. The robot reports podman's pulled Digest, which can be the per-platform one. Anything else is a 1 printing both. A "Deployed." naming no digest is a 1. "Already deployed." names none, so it passes and says the running digest is unproven, with "running": null.

    5. LOW, hand-closed or stalled version blocked forever. Fixed in 3b95568
    This follows from 1: a closed ticket is never adopted, so a rerun files fresh (test_a_hand_closed_or_stalled_ticket_never_blocks_the_release). A commit the robot rolled back stays refused by the robot itself, which is correct.

    6. LOW, in-flight check keyed on subject. Fixed in 3b95568
    Every live ticket's body service:/commit: is read, as the robot reads it, and every one is read before anything is adopted. Another commit in flight under any subject is a 1, even beside a ticket for this release.

    7. Plausible, proof scans past newer robot comments. Fixed in 3b95568
    Only the robot's newest comment is judged (test_an_older_deployed_under_a_newer_robot_refusal_proves_nothing).

    8. Plausible, history first page only, and RT visibility. Fixed in 3b95568
    Ticket history and searches read every page up to 20, and a 2 beyond that (test_the_proof_is_found_past_the_first_page_of_history). After filing, the ticket must show in a search of the queue, or it's a 2: "this RT user cannot see the queue's tickets" (test_a_token_that_cannot_see_the_queue_is_a_2). That check runs after the filing, so a token with no ShowTicket can still leave one ticket filed before the 2. Nothing else in REST2 shows the gap ahead of time without guessing at rights.

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 22:21 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,738 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.test import repo_of
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc.get("Labels")
    +    if not isinstance(labels, dict) or not all(isinstance(v, str) for v in labels.values()):
    +        raise CannotRunError(f"skopeo inspect of {ref} has no Labels table of text")
    +    digest = doc.get("Digest")
    +    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
    +        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
    +    return doc
    +
    +
    +def tags(reg: Registry, repo: str) -> dict[str, str]:
    +    """Each release tag's version and the commit it names, peeled for an annotated tag."""
    +    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
    +    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
    +    refs = {name: sha for sha, _, name in listed}
    +    found = {}
    +    for name, sha in refs.items():
    +        version = name.removeprefix("refs/tags/v")
    +        if name.startswith("refs/tags/v") and SEMVER.fullmatch(version):
    +            found[version] = refs.get(f"{name}^{{}}") or sha
    +    return found
    +
    +
    +def _semver(version: str) -> tuple[int, ...]:
    +    return tuple(int(part) for part in version.split("."))
    +
    +
    +def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
    +    """The release `version`, or the newest release tag, and its image's labels, read back.
    +
    +    The version comes from the tag, never from a label: an image inherits its
    +    base's `version` labels. Without one, the newest vX.Y.Z tag is the release
    +    only when quay's X.Y.Z is the digest `:latest` names, which `promote` moved
    +    it to from the default branch; anything else is a 1 that asks for --version.
    +    """
    +    released = tags(reg, repo)

    MEDIUM (Test Coverage): The new default-release path is not tested when the repository has no valid release tags. The existing no-tag test supplies an explicit version, so it does not exercise the empty-catalog fallback or its refusal behavior.

    Suggestion: Add a test with no valid tags and no --version; assert deployment is refused and no ticket is filed.

    Evidence:

    released = tags(reg, repo)
    newest = version is None
    version = version or max(released, key=_semver, default="")
    commit = released.get(version)
    if commit is None:
        raise RefusedError(...)
    

    <!-- gatehouse agent=tests confidence=97 votes=1/1 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 22:21 UTC
    Reviewer

    Gatehouse found 1 issues (1 medium)

    Reviewed 1 commit since 6a0acc3 (incremental).

    1 finding(s) dropped: their evidence is not in the diff.

    1 finding(s) not re-raised: already answered on this PR.

    <!-- gatehouse review complete -->

    fatherlinux fatherlinux commented on code on Dec 04, 2026 22:34 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,738 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import os
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.test import repo_of
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc.get("Labels")
    +    if not isinstance(labels, dict) or not all(isinstance(v, str) for v in labels.values()):
    +        raise CannotRunError(f"skopeo inspect of {ref} has no Labels table of text")
    +    digest = doc.get("Digest")
    +    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
    +        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
    +    return doc
    +
    +
    +def tags(reg: Registry, repo: str) -> dict[str, str]:
    +    """Each release tag's version and the commit it names, peeled for an annotated tag."""
    +    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
    +    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
    +    refs = {name: sha for sha, _, name in listed}
    +    found = {}
    +    for name, sha in refs.items():
    +        version = name.removeprefix("refs/tags/v")
    +        if name.startswith("refs/tags/v") and SEMVER.fullmatch(version):
    +            found[version] = refs.get(f"{name}^{{}}") or sha
    +    return found
    +
    +
    +def _semver(version: str) -> tuple[int, ...]:
    +    return tuple(int(part) for part in version.split("."))
    +
    +
    +def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
    +    """The release `version`, or the newest release tag, and its image's labels, read back.
    +
    +    The version comes from the tag, never from a label: an image inherits its
    +    base's `version` labels. Without one, the newest vX.Y.Z tag is the release
    +    only when quay's X.Y.Z is the digest `:latest` names, which `promote` moved
    +    it to from the default branch; anything else is a 1 that asks for --version.
    +    """
    +    released = tags(reg, repo)

    Fixed in 80b6e41

    test_no_release_tag_at_all_and_no_version_is_refused lists only non-release tags (nightly, v1.2) with no --version. It asserts a 1 saying "has no tag vX.Y.Z", nothing filed, and RT never asked.

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 22:35 UTC
    Reviewer

    Gatehouse found no issues.

    Reviewed 1 commit since 3b95568 (incremental).

    1 finding(s) not re-raised: already answered on this PR.

    <!-- gatehouse review complete -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 23:09 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,740 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.release import origin_repo
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc.get("Labels")
    +    if not isinstance(labels, dict) or not all(isinstance(v, str) for v in labels.values()):
    +        raise CannotRunError(f"skopeo inspect of {ref} has no Labels table of text")
    +    digest = doc.get("Digest")
    +    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
    +        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
    +    return doc
    +
    +
    +def tags(reg: Registry, repo: str) -> dict[str, str]:
    +    """Each release tag's version and the commit it names, peeled for an annotated tag."""
    +    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
    +    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
    +    refs = {name: sha for sha, _, name in listed}
    +    found = {}
    +    for name, sha in refs.items():
    +        version = name.removeprefix("refs/tags/v")
    +        if name.startswith("refs/tags/v") and SEMVER.fullmatch(version):
    +            found[version] = refs.get(f"{name}^{{}}") or sha
    +    return found
    +
    +
    +def _semver(version: str) -> tuple[int, ...]:
    +    return tuple(int(part) for part in version.split("."))
    +
    +
    +def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
    +    """The release `version`, or the newest release tag, and its image's labels, read back.
    +
    +    The version comes from the tag, never from a label: an image inherits its
    +    base's `version` labels. Without one, the newest vX.Y.Z tag is the release
    +    only when quay's X.Y.Z is the digest `:latest` names, which `promote` moved
    +    it to from the default branch; anything else is a 1 that asks for --version.
    +    """
    +    released = tags(reg, repo)
    +    newest = version is None
    +    version = version or max(released, key=_semver, default="")
    +    commit = released.get(version)
    +    if commit is None:
    +        raise RefusedError(f"{repo} has no tag v{version or 'X.Y.Z'}: no release to deploy")
    +    if not COMMIT.fullmatch(commit):
    +        raise CannotRunError(f"v{version} names {commit!r}, which is no commit")
    +    ref = f"quay.io/{repo}:{version}"
    +    doc = inspect(reg, ref)
    +    if doc is None:
    +        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
    +    if newest:
    +        latest = inspect(reg, f"quay.io/{repo}:latest")
    +        if latest is None or latest["Digest"] != doc["Digest"]:
    +            raise RefusedError(
    +                f"the newest tag is v{version}, and :latest is not its image: name the release "
    +                f"to deploy with --version"
    +            )
    +    return Artifact(repo, version, commit, doc["Digest"]), doc["Labels"]
    +
    +
    +def platforms(reg: Registry, art: Artifact) -> set[str]:
    +    """The release's digest and, for an index, each platform manifest's: what may run it."""
    +    proc = reg.run(["skopeo", "inspect", "--raw", f"docker://{art.image}@{art.digest}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot read {art.image}@{art.digest}: {(proc.stderr or '').strip()}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"the manifest of {art.image}@{art.digest} is not JSON") from exc
    +    listed = doc.get("manifests", []) if isinstance(doc, dict) else []
    +    found = {m.get("digest") for m in listed if isinstance(m, dict)}
    +    return {art.digest} | {d for d in found if isinstance(d, str) and DIGEST.fullmatch(d)}
    +
    +
    +def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
    +    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
    +    revision = labels.get(REVISION, "")
    +    if revision != art.commit:
    +        raise RefusedError(
    +            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
    +            f"and v{art.version} tags {art.commit}: it is not that release's image"
    +        )
    +    with TemporaryDirectory() as key_dir:
    +        key = Path(key_dir) / "fleet.pub"
    +        key.write_text(FLEET_PUBLIC_KEY)
    +        proc = reg.run(
    +            [
    +                "cosign",
    +                "verify",
    +                "--insecure-ignore-tlog",
    +                "--key",
    +                str(key),
    +                f"{art.image}@{art.digest}",
    +            ]
    +        )
    +    if proc.returncode == 0:
    +        return
    +    err = (proc.stderr or "").strip()
    +    if re.search(
    +        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
    +        err,
    +        re.IGNORECASE,
    +    ):
    +        raise RefusedError(
    +            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
    +            f"digest `promote` signed is ever deployed"
    +        )
    +    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
    +
    +
    +# ------------------------------------------------------------------ the robot's registry
    +
    +
    +# One HTTP request: method, https URL, headers, body. Tools.http, through the
    +# jobs' one opener (_github.SafeRedirect); suites pass a fake.
    +Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
    +
    +
    +def _http() -> Http:
    +    return Tools().http
    +
    +
    +def _fetch(http: Http, url: str) -> bytes:
    +    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
    +    if answer.status != HTTP_OK:
    +        raise OSError(f"{url} answered {answer.status}")
    +    return answer.body
    +
    +
    +def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
    +    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
    +
    +    A registry that cannot be read is said and passed: the robot judges the
    +    name itself, and its refusal comes back from `wait` as a 1.
    +    """
    +    try:
    +        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
    +        unread = "" if isinstance(rows, dict) else "it has no [service] table"
    +    except (OSError, ValueError, CannotRunError) as exc:
    +        rows, unread = None, str(exc)
    +    if unread or not isinstance(rows, dict):
    +        run.say(
    +            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
    +        )
    +        return
    +    row = rows.get(cfg.service)
    +    if not isinstance(row, dict):
    +        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
    +        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
    +        raise RefusedError(
    +            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
    +            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
    +        )
    +    if row.get("repo") != repo:
    +        raise RefusedError(
    +            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
    +        )
    +    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
    +
    +
    +# ------------------------------------------------------------------ RT
    +
    +
    +class Rt:
    +    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
    +
    +    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
    +        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
    +
    +    def _call(self, path: str, body: object = None) -> object:
    +        where = path.split("?", maxsplit=1)[0]
    +        headers = {
    +            "Authorization": f"token {self.token}",
    +            "Accept": "application/json",
    +            "Content-Type": "application/json",
    +            "User-Agent": "sdlc-deploy",
    +        }
    +        payload = None if body is None else json.dumps(body).encode()
    +        answer = self.http(
    +            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
    +        )
    +        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
    +            raise CannotRunError(f"RT answered {answer.status} to {where}")
    +        try:
    +            return json.loads(answer.body or b"null")
    +        except ValueError as exc:
    +            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
    +
    +    def _items(self, path: str) -> list[Mapping]:
    +        found = self._call(path)
    +        items = found.get("items") if isinstance(found, Mapping) else None
    +        if not isinstance(items, list):
    +            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
    +        return [i for i in items if isinstance(i, Mapping)]
    +
    +    def _every(self, path: str, params: Mapping[str, object]) -> list[Mapping]:
    +        """Every page of a listing, up to SEARCH_PAGES; a listing cut short is a 2.
    +
    +        A check that refuses on what it finds must see the last item as
    +        surely as the first, so nothing here stops early.
    +        """
    +        out: list[Mapping] = []
    +        for page in range(1, SEARCH_PAGES + 1):

    MEDIUM (Test Coverage): _every fails closed when all 20 pages are full, but the tests only cover reading beyond the first page. The cap boundary is important: a truncated listing must not let the deploy proceed without seeing every in-flight ticket.

    Suggestion: Add a test where the fake RT returns exactly PAGE items on each of SEARCH_PAGES pages, then assert the listing raises CannotRunError rather than returning a partial result.

    Evidence:

    for page in range(1, SEARCH_PAGES + 1):
        ...
        if len(items) < PAGE:
            return out
    raise CannotRunError(f"RT's {path.split('?', maxsplit=1)[0]} ran past {SEARCH_PAGES} pages")
    

    <!-- gatehouse agent=tests confidence=95 votes=1/1 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 23:09 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,740 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of

    HIGH (Documentation): The module overview describes a successful deployment only as a newest robot comment saying “Deployed.” with the release digest. The implementation also returns success for “Already deployed.” comments naming the commit, while explicitly treating the digest as unproven. The overview therefore omits a valid success case.

    Suggestion: Document the “Already deployed.” success case and clarify that it succeeds without proving the running digest.

    Evidence:

    Resolved, with the robot's NEWEST comment saying "Deployed." of
    this commit and a digest that is the release's, is a 0; resolved
    without it (a person closed it) is a 1
    

    <!-- gatehouse agent=docs confidence=99 votes=2/3 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 23:09 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,740 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.release import origin_repo
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc.get("Labels")
    +    if not isinstance(labels, dict) or not all(isinstance(v, str) for v in labels.values()):
    +        raise CannotRunError(f"skopeo inspect of {ref} has no Labels table of text")
    +    digest = doc.get("Digest")
    +    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
    +        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
    +    return doc
    +
    +
    +def tags(reg: Registry, repo: str) -> dict[str, str]:
    +    """Each release tag's version and the commit it names, peeled for an annotated tag."""
    +    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
    +    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
    +    refs = {name: sha for sha, _, name in listed}
    +    found = {}
    +    for name, sha in refs.items():
    +        version = name.removeprefix("refs/tags/v")
    +        if name.startswith("refs/tags/v") and SEMVER.fullmatch(version):
    +            found[version] = refs.get(f"{name}^{{}}") or sha
    +    return found
    +
    +
    +def _semver(version: str) -> tuple[int, ...]:
    +    return tuple(int(part) for part in version.split("."))
    +
    +
    +def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
    +    """The release `version`, or the newest release tag, and its image's labels, read back.
    +
    +    The version comes from the tag, never from a label: an image inherits its
    +    base's `version` labels. Without one, the newest vX.Y.Z tag is the release
    +    only when quay's X.Y.Z is the digest `:latest` names, which `promote` moved
    +    it to from the default branch; anything else is a 1 that asks for --version.
    +    """
    +    released = tags(reg, repo)
    +    newest = version is None
    +    version = version or max(released, key=_semver, default="")
    +    commit = released.get(version)
    +    if commit is None:
    +        raise RefusedError(f"{repo} has no tag v{version or 'X.Y.Z'}: no release to deploy")
    +    if not COMMIT.fullmatch(commit):
    +        raise CannotRunError(f"v{version} names {commit!r}, which is no commit")
    +    ref = f"quay.io/{repo}:{version}"
    +    doc = inspect(reg, ref)
    +    if doc is None:
    +        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
    +    if newest:
    +        latest = inspect(reg, f"quay.io/{repo}:latest")
    +        if latest is None or latest["Digest"] != doc["Digest"]:
    +            raise RefusedError(
    +                f"the newest tag is v{version}, and :latest is not its image: name the release "
    +                f"to deploy with --version"
    +            )
    +    return Artifact(repo, version, commit, doc["Digest"]), doc["Labels"]
    +
    +
    +def platforms(reg: Registry, art: Artifact) -> set[str]:
    +    """The release's digest and, for an index, each platform manifest's: what may run it."""
    +    proc = reg.run(["skopeo", "inspect", "--raw", f"docker://{art.image}@{art.digest}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot read {art.image}@{art.digest}: {(proc.stderr or '').strip()}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"the manifest of {art.image}@{art.digest} is not JSON") from exc
    +    listed = doc.get("manifests", []) if isinstance(doc, dict) else []
    +    found = {m.get("digest") for m in listed if isinstance(m, dict)}
    +    return {art.digest} | {d for d in found if isinstance(d, str) and DIGEST.fullmatch(d)}
    +
    +
    +def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
    +    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
    +    revision = labels.get(REVISION, "")
    +    if revision != art.commit:
    +        raise RefusedError(
    +            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
    +            f"and v{art.version} tags {art.commit}: it is not that release's image"
    +        )
    +    with TemporaryDirectory() as key_dir:
    +        key = Path(key_dir) / "fleet.pub"
    +        key.write_text(FLEET_PUBLIC_KEY)
    +        proc = reg.run(
    +            [
    +                "cosign",
    +                "verify",
    +                "--insecure-ignore-tlog",
    +                "--key",
    +                str(key),
    +                f"{art.image}@{art.digest}",
    +            ]
    +        )
    +    if proc.returncode == 0:
    +        return
    +    err = (proc.stderr or "").strip()
    +    if re.search(
    +        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
    +        err,
    +        re.IGNORECASE,
    +    ):
    +        raise RefusedError(
    +            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
    +            f"digest `promote` signed is ever deployed"
    +        )
    +    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
    +
    +
    +# ------------------------------------------------------------------ the robot's registry
    +
    +
    +# One HTTP request: method, https URL, headers, body. Tools.http, through the
    +# jobs' one opener (_github.SafeRedirect); suites pass a fake.
    +Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
    +
    +
    +def _http() -> Http:
    +    return Tools().http
    +
    +
    +def _fetch(http: Http, url: str) -> bytes:
    +    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
    +    if answer.status != HTTP_OK:
    +        raise OSError(f"{url} answered {answer.status}")
    +    return answer.body
    +
    +
    +def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
    +    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
    +
    +    A registry that cannot be read is said and passed: the robot judges the
    +    name itself, and its refusal comes back from `wait` as a 1.
    +    """
    +    try:
    +        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
    +        unread = "" if isinstance(rows, dict) else "it has no [service] table"
    +    except (OSError, ValueError, CannotRunError) as exc:
    +        rows, unread = None, str(exc)
    +    if unread or not isinstance(rows, dict):
    +        run.say(
    +            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
    +        )
    +        return
    +    row = rows.get(cfg.service)
    +    if not isinstance(row, dict):
    +        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
    +        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
    +        raise RefusedError(
    +            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
    +            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
    +        )
    +    if row.get("repo") != repo:
    +        raise RefusedError(
    +            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
    +        )
    +    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
    +
    +
    +# ------------------------------------------------------------------ RT
    +
    +
    +class Rt:
    +    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
    +
    +    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
    +        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
    +
    +    def _call(self, path: str, body: object = None) -> object:
    +        where = path.split("?", maxsplit=1)[0]
    +        headers = {
    +            "Authorization": f"token {self.token}",
    +            "Accept": "application/json",
    +            "Content-Type": "application/json",
    +            "User-Agent": "sdlc-deploy",
    +        }
    +        payload = None if body is None else json.dumps(body).encode()
    +        answer = self.http(
    +            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
    +        )
    +        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
    +            raise CannotRunError(f"RT answered {answer.status} to {where}")
    +        try:
    +            return json.loads(answer.body or b"null")
    +        except ValueError as exc:
    +            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
    +
    +    def _items(self, path: str) -> list[Mapping]:
    +        found = self._call(path)
    +        items = found.get("items") if isinstance(found, Mapping) else None
    +        if not isinstance(items, list):
    +            raise CannotRunError(f"RT's answer to {path.split('?', maxsplit=1)[0]} has no items")
    +        return [i for i in items if isinstance(i, Mapping)]
    +
    +    def _every(self, path: str, params: Mapping[str, object]) -> list[Mapping]:
    +        """Every page of a listing, up to SEARCH_PAGES; a listing cut short is a 2.
    +
    +        A check that refuses on what it finds must see the last item as
    +        surely as the first, so nothing here stops early.
    +        """
    +        out: list[Mapping] = []
    +        for page in range(1, SEARCH_PAGES + 1):
    +            query = urllib.parse.urlencode({**params, "per_page": PAGE, "page": page})
    +            items = self._items(f"{path}?{query}")
    +            out += items
    +            if len(items) < PAGE:
    +                return out
    +        raise CannotRunError(f"RT's {path.split('?', maxsplit=1)[0]} ran past {SEARCH_PAGES} pages")
    +
    +    def search(self, where: str) -> list[int]:
    +        """The id of each queue ticket TicketSQL `where` matches, newest first."""
    +        params = {
    +            "query": f"Queue = '{self.queue}' AND {where}",
    +            "orderby": "id",
    +            "order": "DESC",
    +            "fields": "Status",
    +        }
    +        items = self._every("/tickets", params)
    +        ids = [item.get("id") for item in items]
    +        return [n for n in map(_number, ids) if n is not None]
    +
    +    def live(self) -> list[int]:
    +        """The queue's tickets the robot has yet to answer: new or open."""
    +        return self.search("(" + " OR ".join(f"Status = '{status}'" for status in LIVE) + ")")
    +
    +    def file(self, subject: str, content: str) -> int:
    +        body = {
    +            "Queue": self.queue,
    +            "Subject": subject,
    +            "Content": content,
    +            "ContentType": "text/plain",
    +        }
    +        found = self._call("/ticket", body)
    +        number = _number(found.get("id") if isinstance(found, Mapping) else None)
    +        if number is None:
    +            raise CannotRunError("RT filed the ticket and answered with no id")
    +        return number
    +
    +    def status(self, number: int) -> str:
    +        found = self._call(f"/ticket/{number}?fields=Status")
    +        status = found.get("Status") if isinstance(found, Mapping) else None
    +        if not isinstance(status, str):
    +            raise CannotRunError(f"RT#{number} has no status")
    +        return status
    +
    +    def _history(self, number: int) -> list[Mapping]:
    +        params = {"fields": "Type,Creator", "fields[Creator]": "Name"}
    +        return self._every(f"/ticket/{number}/history", params)
    +
    +    def _said(self, tid: int) -> str:
    +        parts = self._items(f"/transaction/{tid}/attachments?{ATTACHMENT_FIELDS}")
    +        return "".join(_text(p) for p in parts if p.get("ContentType") == "text/plain")
    +
    +    def fields(self, number: int) -> dict[str, str]:
    +        """The ticket's body as the robot reads it: `key: value` lines of its first message."""
    +        history = self._history(number)
    +        made = next((tx.get("id") for tx in history if tx.get("Type") == "Create"), None)
    +        tid = _number(made)
    +        if tid is None:
    +            raise CannotRunError(f"RT#{number} has no creating transaction to read its body from")
    +        text = self._said(tid)
    +        pairs = (line.partition(":") for line in text.splitlines())
    +        return {k.strip().lower(): v.strip() for k, sep, v in pairs if sep}
    +
    +    def last_said_by(self, number: int, who: str) -> str | None:
    +        """What `who` last commented or replied on the ticket, every history page read."""
    +        history = self._history(number)
    +        theirs = [
    +            tx.get("id")
    +            for tx in history
    +            if tx.get("Type") in ("Comment", "Correspond") and _creator(tx) == who
    +        ]
    +        tid = _number(theirs[-1]) if theirs else None
    +        return None if tid is None else self._said(tid)
    +
    +
    +def _creator(tx: Mapping) -> str:
    +    """A transaction's creator's name, given as an object (fields[Creator]) or a bare name."""
    +    creator = tx.get("Creator")
    +    return str(creator.get("Name", "") if isinstance(creator, Mapping) else creator or "")
    +
    +
    +def _number(value: object) -> int | None:
    +    """RT gives an id as a number, or as a string of digits."""
    +    digits = isinstance(value, str) and value.isdigit()
    +    return int(str(value)) if digits else value if type(value) is int else None
    +
    +
    +def _text(part: Mapping) -> str:
    +    """An attachment's Content, which REST2 gives base64-encoded."""
    +    raw = part.get("Content")
    +    if not isinstance(raw, str):
    +        return ""
    +    try:
    +        return base64.b64decode(raw, validate=True).decode(errors="replace")
    +    except ValueError:
    +        return raw
    +
    +
    +def subject(cfg: Config, art: Artifact) -> str:
    +    """The Desk's subject (ashigaru desk/cuts.py), so its filing and this one are one ticket."""
    +    return f"Deploy {cfg.service} {art.version}"
    +
    +
    +def body(cfg: Config, art: Artifact) -> str:
    +    """The robot's ticket body: those three fields and nothing else."""
    +    return f"service: {cfg.service}\nrepo: {art.repo}\ncommit: {art.commit}\n"
    +
    +
    +# ------------------------------------------------------------------ the verdict
    +
    +
    +def proof(said: str | None, art: Artifact) -> str | None:
    +    """The robot's newest comment, when it says this commit is running and verified.
    +
    +    The deployer resolves with "Deployed. <unit> is running <commit:7> (built
    +    from <revision:12>, ...", or "Already deployed. <unit> was already running
    +    <commit:7> ..." when the service was on it. `said` is the robot's newest
    +    comment, by its RT user alone: an older "Deployed." under a newer refusal
    +    proves nothing, nor does anyone else's comment, and a ticket a person
    +    resolved is no deploy.
    +    """
    +    words = (said or "").lstrip()
    +    if words.startswith("Deployed.") and f"built from {art.commit[:12]}" in words:
    +        return words
    +    if words.startswith("Already deployed.") and f"running {art.commit[:7]}" in words:
    +        return words
    +    return None
    +
    +
    +def robot_digest(text: str) -> str | None:
    +    m = re.search(r"digest (sha256:[0-9a-f]{64})", text)
    +    return m[1] if m else None
    +
    +
    +# ------------------------------------------------------------------ the steps
    +
    +
    +# What the ticket step says of the ticket it filed or adopted; the wait step,
    +# in a container of its own, reads it back from the run's journal.
    +CHOSEN = re.compile(r"   (?:filed|adopted) RT#([0-9]+)\b")
    +
    +
    +@dataclass
    +class Deploy:
    +    """What the steps share: where they read from. Suites replace each."""
    +
    +    root: Path
    +    repo: str  # crunchtools/<name>
    +    version: str | None
    +    reg: Registry
    +    http: Http = field(default_factory=_http)
    +    hosts: Callable[[], _hosts.Hosts] = _hosts.load
    +    timer: tuple[Callable[[], float], Callable[[float], None]] = (time.monotonic, time.sleep)
    +
    +    def target(self) -> tuple[Config, Artifact]:
    +        """The config and the release, verified again: each step runs in its own container,
    +        so none takes an earlier step's word for the digest it acts on."""
    +        cfg = config(self.root)
    +        art, labels = artifact(self.reg, self.repo, self.version)
    +        verify(self.reg, art, labels)
    +        return cfg, art
    +
    +    def rt(self, run: Run) -> tuple[Rt, str]:
    +        """RT, and the robot's RT user: without it nothing could prove a deploy, so a 2 at once."""
    +        hosts = self.hosts()
    +        robot = hosts.need("rt.robot")
    +        rt = Rt(hosts.need("rt.url"), hosts.need("rt.queue"), run.credential("rt"), self.http)
    +        return rt, robot
    +
    +    # resolve -----------------------------------------------------------
    +
    +    def resolve(self, run: Run) -> None:
    +        cfg, art = self.target()
    +        run.say(f"   {art.image}:{art.version} is {art.digest}, signed, built from {art.commit}")
    +        check_registry(run, cfg, art.repo, self.http)
    +
    +    # ticket ------------------------------------------------------------
    +
    +    def filed(self, run: Run) -> bool:
    +        """A ticket in flight for this release is adopted; one for another is a refusal.
    +
    +        In flight is new or open, and the body is what is matched, as the
    +        robot reads it: `service:` and `commit:`. A resolved or stalled
    +        ticket is history, never this run's deploy, so it is never adopted:
    +        a rollback, a retry after a hand-closed ticket or after a stall all
    +        file a ticket of their own.
    +        """
    +        cfg, art = self.target()
    +        rt, _robot = self.rt(run)
    +        ours: list[tuple[int, str]] = []
    +        others: list[tuple[int, str]] = []
    +        for number in rt.live():
    +            asked = rt.fields(number)
    +            if asked.get("service") != cfg.service:
    +                continue
    +            same = asked.get("commit") == art.commit and asked.get("repo") == art.repo
    +            (ours if same else others).append((number, asked.get("commit", "unnamed")))
    +        # Every live ticket is read before anything is adopted: one for this
    +        # release does not hide another commit in flight beside it.
    +        if others:
    +            number, commit = others[0]
    +            raise RefusedError(
    +                f"RT#{number} is already in flight for {cfg.service} (commit {commit[:12]}): "
    +                f"one deploy at a time; wait for it, then run this again"
    +            )
    +        if ours:
    +            run.say(f"   adopted RT#{ours[0][0]}, in flight for this release")
    +        return bool(ours)
    +
    +    def file(self, run: Run) -> None:
    +        cfg, art = self.target()
    +        rt, _robot = self.rt(run)
    +        mine = subject(cfg, art)
    +        number = rt.file(mine, body(cfg, art))
    +        run.say(f"   filed RT#{number}: {mine}")
    +        # A token that cannot see the queue's tickets would find nothing in
    +        # flight and file anyway: what it filed must show in a search.
    +        if number not in rt.search(f"id = {number}"):
    +            raise CannotRunError(
    +                f"RT#{number} was filed, and a search of {rt.queue} does not show it: this RT "
    +                f"user cannot see the queue's tickets, so nothing in flight could be seen either"
    +            )
    +
    +    # wait --------------------------------------------------------------
    +
    +    def chosen(self, run: Run, rt: Rt, cfg: Config, art: Artifact) -> int:
    +        """The ticket this run filed or adopted, from its journal, or the one in flight."""
    +        said = run.journal.printed if run.journal is not None else []
    +        for line in reversed(said):
    +            m = CHOSEN.match(line)
    +            if m:
    +                return int(m[1])
    +        for number in rt.live():
    +            asked = rt.fields(number)
    +            if (asked.get("service"), asked.get("commit")) == (cfg.service, art.commit):
    +                return number
    +        raise CannotRunError(
    +            f"no ticket this run filed or adopted for {cfg.service} {art.version}, and none in "
    +            f"flight: run `sdlc deploy` again, which files one"
    +        )
    +
    +    def wait(self, run: Run) -> None:
    +        cfg, art = self.target()
    +        rt, robot = self.rt(run)
    +        number = self.chosen(run, rt, cfg, art)
    +        where = f"{rt.url}/Ticket/Display.html?id={number}"
    +        clock, _ = self.timer
    +        started = clock()
    +
    +        def answered() -> str | None:
    +            status = rt.status(number)
    +            if status == "new" and clock() - started >= NEW_FOR:
    +                raise runner.WaitExpiredError(
    +                    f"RT#{number} is still new after {NEW_FOR:.0f}s: the deploy robot is not "
    +                    f"reading its queue\n{where}"
    +                )
    +            return None if status in WORKING else status
    +
    +        status = runner.wait_for(
    +            answered, Wait(f"the robot to answer RT#{number}", where, ANSWER_IN, POLL), self.timer
    +        )
    +        last = rt.last_said_by(number, robot)
    +        if status == "stalled":
    +            raise RefusedError(_stalled(number, cfg, last))
    +        if status != "resolved":
    +            raise RefusedError(f"RT#{number} was {status}, not deployed\n{where}")
    +        said = proof(last, art)
    +        if said is None:
    +            raise RefusedError(
    +                f"RT#{number} is resolved, and the robot's last word is not that it deployed "
    +                f"{art.commit[:12]}: a ticket closed by hand is not a deploy. Nothing is known to "
    +                f"be running v{art.version}; `sdlc deploy` again files a new ticket\n{where}"
    +            )
    +        running = robot_digest(said)
    +        if running is None and said.startswith("Deployed."):
    +            raise RefusedError(
    +                f"RT#{number}: the robot says it deployed {art.commit[:12]} and names no digest, "
    +                f"so nothing shows it runs the signed release {art.digest}\n{where}"
    +            )
    +        if running is not None and running not in platforms(self.reg, art):
    +            raise RefusedError(
    +                f"RT#{number}: the robot reports running {running}, and the signed release "
    +                f"v{art.version} is {art.digest}: what runs is not what was verified\n{where}"
    +            )
    +        run.say(f"   RT#{number}: {said.strip().splitlines()[0]}")
    +        if running is None:
    +            run.say("   the robot named no digest, so the running digest is unproven")
    +        run.result = {
    +            "repo": art.repo,
    +            "version": art.version,
    +            "commit": art.commit,
    +            "digest": art.digest,
    +            "service": cfg.service,
    +            "ticket": f"RT#{number}",
    +            "running": running,
    +        }
    +
    +
    +def _stalled(number: int, cfg: Config, last: str | None) -> str:
    +    """The robot's last comment, the service's own output on it, and what it means."""
    +    said = last.strip() if last else "the ticket carries no comment from the robot"
    +    if "is not in the registry" in said:
    +        return (
    +            f"RT#{number}: the robot refused {cfg.service!r}, which is not in its registry. The "
    +            f"service is the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service "
    +            f"and run `sdlc deploy` again, which files a new ticket\n{said}"
    +        )
    +    return f"RT#{number} was handed back by the robot, and nothing it deployed stayed:\n{said}"
    +
    +
    +def steps(d: Deploy) -> list[Step]:

    CRITICAL (Documentation): The new public steps function has no docstring describing the steps it returns or their ordering.

    Suggestion: Add a concise docstring describing the resolve, ticket, and wait steps and their order.

    Evidence:

    def steps(d: Deploy) -> list[Step]:
        return [
            Step("resolve", d.resolve),
            Step("ticket", d.file, done=d.filed, needs=("rt",)),
            Step("wait", d.wait, needs=("rt",)),
        ]
    

    <!-- gatehouse agent=docs confidence=96 votes=2/3 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 23:09 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,740 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.release import origin_repo
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"skopeo inspect of {ref} is not JSON: {exc}") from exc
    +    if not isinstance(doc, dict):
    +        raise CannotRunError(f"skopeo inspect of {ref} is not an object")
    +    labels = doc.get("Labels")
    +    if not isinstance(labels, dict) or not all(isinstance(v, str) for v in labels.values()):
    +        raise CannotRunError(f"skopeo inspect of {ref} has no Labels table of text")
    +    digest = doc.get("Digest")
    +    if not isinstance(digest, str) or not DIGEST.fullmatch(digest):
    +        raise CannotRunError(f"skopeo inspect of {ref} names no digest: {digest!r}")
    +    return doc
    +
    +
    +def tags(reg: Registry, repo: str) -> dict[str, str]:
    +    """Each release tag's version and the commit it names, peeled for an annotated tag."""
    +    proc = reg.run(["git", "ls-remote", "--tags", f"https://github.com/{repo}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot list {repo}'s tags: {(proc.stderr or '').strip()}")
    +    listed = (line.partition("\t") for line in (proc.stdout or "").splitlines())
    +    refs = {name: sha for sha, _, name in listed}
    +    found = {}
    +    for name, sha in refs.items():
    +        version = name.removeprefix("refs/tags/v")
    +        if name.startswith("refs/tags/v") and SEMVER.fullmatch(version):
    +            found[version] = refs.get(f"{name}^{{}}") or sha
    +    return found
    +
    +
    +def _semver(version: str) -> tuple[int, ...]:
    +    return tuple(int(part) for part in version.split("."))
    +
    +
    +def artifact(reg: Registry, repo: str, version: str | None) -> tuple[Artifact, dict]:
    +    """The release `version`, or the newest release tag, and its image's labels, read back.
    +
    +    The version comes from the tag, never from a label: an image inherits its
    +    base's `version` labels. Without one, the newest vX.Y.Z tag is the release
    +    only when quay's X.Y.Z is the digest `:latest` names, which `promote` moved
    +    it to from the default branch; anything else is a 1 that asks for --version.
    +    """
    +    released = tags(reg, repo)
    +    newest = version is None
    +    version = version or max(released, key=_semver, default="")
    +    commit = released.get(version)
    +    if commit is None:
    +        raise RefusedError(f"{repo} has no tag v{version or 'X.Y.Z'}: no release to deploy")
    +    if not COMMIT.fullmatch(commit):
    +        raise CannotRunError(f"v{version} names {commit!r}, which is no commit")
    +    ref = f"quay.io/{repo}:{version}"
    +    doc = inspect(reg, ref)
    +    if doc is None:
    +        raise RefusedError(f"{ref} does not exist: v{version} was tagged and never published")
    +    if newest:
    +        latest = inspect(reg, f"quay.io/{repo}:latest")
    +        if latest is None or latest["Digest"] != doc["Digest"]:
    +            raise RefusedError(
    +                f"the newest tag is v{version}, and :latest is not its image: name the release "
    +                f"to deploy with --version"
    +            )
    +    return Artifact(repo, version, commit, doc["Digest"]), doc["Labels"]
    +
    +
    +def platforms(reg: Registry, art: Artifact) -> set[str]:
    +    """The release's digest and, for an index, each platform manifest's: what may run it."""
    +    proc = reg.run(["skopeo", "inspect", "--raw", f"docker://{art.image}@{art.digest}"])
    +    if proc.returncode != 0:
    +        raise CannotRunError(f"cannot read {art.image}@{art.digest}: {(proc.stderr or '').strip()}")
    +    try:
    +        doc = json.loads(proc.stdout or "")
    +    except ValueError as exc:
    +        raise CannotRunError(f"the manifest of {art.image}@{art.digest} is not JSON") from exc
    +    listed = doc.get("manifests", []) if isinstance(doc, dict) else []
    +    found = {m.get("digest") for m in listed if isinstance(m, dict)}
    +    return {art.digest} | {d for d in found if isinstance(d, str) and DIGEST.fullmatch(d)}
    +
    +
    +def verify(reg: Registry, art: Artifact, labels: Mapping[str, str]) -> None:
    +    """The digest is the release's: labelled with the tag's commit, signed by the fleet key."""
    +    revision = labels.get(REVISION, "")
    +    if revision != art.commit:
    +        raise RefusedError(
    +            f"{art.image}:{art.version} is labelled revision {revision or 'none'}, "
    +            f"and v{art.version} tags {art.commit}: it is not that release's image"
    +        )
    +    with TemporaryDirectory() as key_dir:
    +        key = Path(key_dir) / "fleet.pub"
    +        key.write_text(FLEET_PUBLIC_KEY)
    +        proc = reg.run(
    +            [
    +                "cosign",
    +                "verify",
    +                "--insecure-ignore-tlog",
    +                "--key",
    +                str(key),
    +                f"{art.image}@{art.digest}",
    +            ]
    +        )
    +    if proc.returncode == 0:
    +        return
    +    err = (proc.stderr or "").strip()
    +    if re.search(
    +        r"no (matching )?signatures|signature.*(invalid|mismatch)|failed to verify",
    +        err,
    +        re.IGNORECASE,
    +    ):
    +        raise RefusedError(
    +            f"{art.image}@{art.digest} is not signed by the fleet's release key: only a "
    +            f"digest `promote` signed is ever deployed"
    +        )
    +    raise CannotRunError(f"cosign could not verify {art.image}@{art.digest}: {err[-400:]}")
    +
    +
    +# ------------------------------------------------------------------ the robot's registry
    +
    +
    +# One HTTP request: method, https URL, headers, body. Tools.http, through the
    +# jobs' one opener (_github.SafeRedirect); suites pass a fake.
    +Http = Callable[[str, str, Mapping[str, str], bytes | None], Response]
    +
    +
    +def _http() -> Http:
    +    return Tools().http
    +
    +
    +def _fetch(http: Http, url: str) -> bytes:
    +    answer = http("GET", url, {"User-Agent": "sdlc-deploy"}, None)
    +    if answer.status != HTTP_OK:
    +        raise OSError(f"{url} answered {answer.status}")
    +    return answer.body
    +
    +
    +def check_registry(run: Run, cfg: Config, repo: str, http: Http) -> None:
    +    """The service is a row of the robot's registry, and the row is this repo's; a 1 otherwise.
    +
    +    A registry that cannot be read is said and passed: the robot judges the
    +    name itself, and its refusal comes back from `wait` as a 1.
    +    """
    +    try:
    +        rows = tomllib.loads(_fetch(http, REGISTRY_URL).decode()).get("service")
    +        unread = "" if isinstance(rows, dict) else "it has no [service] table"
    +    except (OSError, ValueError, CannotRunError) as exc:
    +        rows, unread = None, str(exc)
    +    if unread or not isinstance(rows, dict):
    +        run.say(
    +            f"   the robot's registry could not be read ({unread}); it will judge {cfg.service}"
    +        )
    +        return
    +    row = rows.get(cfg.service)
    +    if not isinstance(row, dict):
    +        ours = sorted(n for n, r in rows.items() if isinstance(r, dict) and r.get("repo") == repo)
    +        hint = f"; {repo}'s row is {', '.join(ours)}" if ours else f"; it has no row for {repo}"
    +        raise RefusedError(
    +            f"service {cfg.service!r} is not in the deploy robot's registry{hint}. The service is "
    +            f"the CONTAINER name the registry keys on: fix [tool.sdlc.deploy] service"
    +        )
    +    if row.get("repo") != repo:
    +        raise RefusedError(
    +            f"the robot's registry row {cfg.service!r} deploys {row.get('repo')!r}, not {repo}"
    +        )
    +    run.say(f"   {cfg.service} is in the robot's registry for {repo}")
    +
    +
    +# ------------------------------------------------------------------ RT
    +
    +
    +class Rt:
    +    """RT's REST2, with the `rt` credential, in the hosts file's queue."""
    +
    +    def __init__(self, url: str, queue: str, token: str, http: Http) -> None:
    +        self.url, self.queue, self.token, self.http = url.rstrip("/"), queue, token, http
    +
    +    def _call(self, path: str, body: object = None) -> object:
    +        where = path.split("?", maxsplit=1)[0]
    +        headers = {
    +            "Authorization": f"token {self.token}",
    +            "Accept": "application/json",
    +            "Content-Type": "application/json",
    +            "User-Agent": "sdlc-deploy",
    +        }
    +        payload = None if body is None else json.dumps(body).encode()
    +        answer = self.http(
    +            "GET" if body is None else "POST", f"{self.url}{RT_API}{path}", headers, payload
    +        )
    +        if not HTTP_OK <= answer.status < HTTP_REDIRECT:
    +            raise CannotRunError(f"RT answered {answer.status} to {where}")
    +        try:
    +            return json.loads(answer.body or b"null")
    +        except ValueError as exc:
    +            raise CannotRunError(f"RT's answer to {where} is not JSON: {exc}") from exc
    +
    +    def _items(self, path: str) -> list[Mapping]:

    LOW (Consistency Check): The RT helpers annotate collections with bare Mapping, while this codebase uses parameterized mapping types in sdlc_jobs/life/_hosts.py:73-74 and this file uses Mapping[str, str] at sdlc_jobs/life/deploy.py:322. The missing key and value types make these API annotations less informative and inconsistent.

    Suggestion: Parameterize Mapping in these annotations and apply the same convention to the other bare Mapping annotations in this module.

    Evidence:

    def _items(self, path: str) -> list[Mapping]:
        ...
        return [i for i in items if isinstance(i, Mapping)]
    

    <!-- gatehouse agent=consistency confidence=92 votes=1/1 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 23:09 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,740 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.release import origin_repo
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"
    +REVISION = "org.opencontainers.image.revision"
    +COMMIT = re.compile(r"[0-9a-f]{40}")
    +# The robot's registry key: a podman container name, which may carry dots.
    +SERVICE = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}")
    +ROLE = re.compile(r"[a-z][a-z0-9-]*")  # as the hosts file's [host.<role>]
    +UNIT = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.@-]*\.service")
    +HEALTH_PATH = re.compile(r"/[A-Za-z0-9/._-]*")
    +VIAS = ("robot", "ssh")
    +SSH_KEYS = ("host", "unit", "health", "settle")
    +PORT_MAX = 65535
    +DEFAULT_SETTLE = 60
    +# How long skopeo, cosign or git may take to answer, and how many tickets a search reads.
    +TOOL_TIMEOUT = 120
    +PAGE = 50
    +SEARCH_PAGES = 20
    +HTTP_OK = 200
    +HTTP_REDIRECT = 300
    +
    +# Where the robot's registry is reviewed and kept. Read when it can be, so a
    +# wrong service name is refused here, before a ticket the robot would refuse;
    +# when it cannot be read, the robot's own refusal is the check.
    +REGISTRY_URL = "https://raw.githubusercontent.com/crunchtools/deployer/main/deploy/services.toml"
    +RT_API = "/REST/2.0"
    +ATTACHMENT_FIELDS = "fields=Content,ContentType"
    +# How long a ticket may sit `new` before the robot is taken not to be reading
    +# its queue, and how long a ticket it took may take: its build wait, a
    +# pre-deploy dump, `ready` and `settle` together.
    +NEW_FOR = 300.0
    +ANSWER_IN = 1800.0
    +POLL = 15.0
    +# Statuses: the robot's working ones, its verdicts, and what RT has besides.
    +WORKING = ("new", "open")
    +LIVE = ("new", "open")
    +
    +
    +class ConfigError(CannotRunError):
    +    """`[tool.sdlc.deploy]` is malformed: the command cannot run (2)."""
    +
    +
    +@dataclass(frozen=True)
    +class Config:
    +    """`[tool.sdlc.deploy]` as the robot path reads it: `via`, which deployer
    +    takes the service ("robot" here), and `service`, the container name the
    +    robot's registry keys on and the ticket's `service:` line names."""
    +
    +    via: str
    +    service: str
    +
    +
    +def _require(ok: bool, why: str) -> None:
    +    if not ok:
    +        raise ConfigError(f"[tool.sdlc.deploy] {why}")
    +
    +
    +def config(root: Path) -> Config:
    +    """`[tool.sdlc.deploy]`, checked; a 1 when there is none, a 2 when it is malformed."""
    +    table = tool_sdlc(root).get("deploy")
    +    if table is None:
    +        raise RefusedError("this repo declares no [tool.sdlc.deploy], so it has nothing to deploy")
    +    _require(isinstance(table, dict), "is not a table")
    +    stray = sorted(set(table) - {"via", "service", *SSH_KEYS})
    +    _require(not stray, f"has keys sdlc does not know: {', '.join(stray)}")
    +    via, service = table.get("via"), table.get("service")
    +    _require(via in VIAS, f"via must be one of {', '.join(VIAS)}: {via!r}")
    +    named = isinstance(service, str) and SERVICE.fullmatch(service) is not None
    +    _require(named, f"service must be the service's container name: {service!r}")
    +    if via == "ssh":
    +        _ssh_shape(table)
    +        raise CannotRunError(
    +            'via = "ssh" is not built yet (docs/lifecycle.md, build plan phase 6); '
    +            "move the service into the robot's registry, or deploy it by hand"
    +        )
    +    extra = ", ".join(sorted(set(table) & set(SSH_KEYS)))
    +    _require(
    +        not extra,
    +        f'{extra} mean something only to via = "ssh"; the robot\'s registry '
    +        'holds them for via = "robot"',
    +    )
    +    return Config(str(via), str(service))
    +
    +
    +def _ssh_shape(table: Mapping[str, object]) -> None:
    +    """The ssh keys' shape, so a malformed one is said now rather than in phase 6."""
    +    health = table.get("health")
    +    if not isinstance(health, dict) or set(health) != {"port", "path"}:
    +        raise ConfigError('[tool.sdlc.deploy] health must be { port = N, path = "/..." }')
    +    host, unit, port, path = table.get("host"), table.get("unit"), health["port"], health["path"]
    +    settle = table.get("settle", DEFAULT_SETTLE)
    +    shapes = {
    +        f"host must be a role: {host!r}": isinstance(host, str) and bool(ROLE.fullmatch(host)),
    +        f"unit must be a .service: {unit!r}": isinstance(unit, str) and bool(UNIT.fullmatch(unit)),
    +        f"health.port must be a port: {port!r}": type(port) is int and 0 < port <= PORT_MAX,
    +        f"health.path must match {HEALTH_PATH.pattern}": isinstance(path, str)
    +        and bool(HEALTH_PATH.fullmatch(path)),
    +        f"settle must be whole seconds: {settle!r}": type(settle) is int and settle > 0,
    +    }
    +    for why, ok in shapes.items():
    +        _require(ok, why)
    +
    +
    +# ------------------------------------------------------------------ the artifact
    +
    +
    +@dataclass(frozen=True)
    +class Artifact:
    +    repo: str  # crunchtools/<name>
    +    version: str
    +    commit: str  # the commit vX.Y.Z tags, forty characters
    +    digest: str  # what quay.io/crunchtools/<name>:X.Y.Z names
    +
    +    @property
    +    def image(self) -> str:
    +        return f"quay.io/{self.repo}"
    +
    +
    +class Registry:
    +    """skopeo, cosign and git: what the artifact is read from. Suites pass a fake."""
    +
    +    def __init__(self, tools: Tools | None = None) -> None:
    +        self.tools = tools or Tools()
    +
    +    def run(self, argv: list[str]) -> subprocess.CompletedProcess[str]:
    +        return self.tools.run(argv, timeout=TOOL_TIMEOUT)
    +
    +
    +def inspect(reg: Registry, ref: str) -> dict | None:
    +    """`skopeo inspect` of ref: None when it does not exist, a 2 when it cannot be read."""
    +    proc = reg.run(["skopeo", "inspect", f"docker://{ref}"])
    +    if proc.returncode != 0:
    +        err = (proc.stderr or "").strip()
    +        if re.search(r"manifest unknown|not found|name unknown", err, re.IGNORECASE):
    +            return None
    +        raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")

    LOW (Consistency Check): This error formats the last stderr line as a one-element list, unlike the stripped-string error messages used for similar tool failures at sdlc_jobs/life/deploy.py:222 and sdlc_jobs/life/deploy.py:271. That produces a different, bracketed representation for this failure.

    Suggestion: Select the last line as a string, with a fallback for empty output, before formatting the error.

    Evidence:

    raise CannotRunError(f"cannot read {ref}: {err.splitlines()[-1:] or 'no output'}")
    

    <!-- gatehouse agent=consistency confidence=96 votes=1/1 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on code on Dec 04, 2026 23:09 UTC
    Code Review
    sdlc_jobs/life/deploy.py:1
    @@ -0,0 +1,740 @@
    +"""`sdlc deploy`: hand a signed release to the deploy robot and wait for its verdict.
    +
    +docs/lifecycle.md is the design; this is its `via = "robot"` path (build plan
    +phase 5). `via = "ssh"` is parsed and refused as not built yet until phase 6.
    +
    +    [tool.sdlc.deploy]
    +    via = "robot"                 # "robot" | "ssh"
    +    service = "acquacotta.crunchtools.com"   # the CONTAINER name, the robot's registry key
    +    # for via = "ssh" only:
    +    host = "web"
    +    unit = "acquacotta.service"
    +    health = { port = 8080, path = "/health" }
    +    settle = 60
    +
    +Three steps, each in a container of its own (_runner), each reading back what
    +it needs rather than trusting an earlier one:
    +
    +    resolve   the digest quay.io/crunchtools/<repo>:X.Y.Z names, signed by the
    +              fleet key, labelled with the commit tag vX.Y.Z names; and the
    +              service in the robot's registry for this repo, when the
    +              registry can be read. No credential. Every step verifies the
    +              release again: it runs in a container of its own.
    +    ticket    a ticket in flight (new or open) whose body names this service
    +              and commit is adopted; one naming another commit is a refusal;
    +              otherwise a fresh `Deploy` ticket, under the Desk's subject. A
    +              resolved or stalled ticket is history, never adopted.
    +    wait      on the ticket this run filed or adopted, until the robot answers.
    +              Resolved, with the robot's NEWEST comment saying "Deployed." of
    +              this commit and a digest that is the release's, is a 0; resolved
    +              without it (a person closed it) is a 1, because that is not a
    +              deploy; stalled is a 1 with the robot's last word; still `new`
    +              after five minutes is a 2: the robot is not reading its queue.
    +
    +The ticket's body is the robot's contract (crunchtools/deployer, "Ticket
    +format"): `service:`, `repo:` and `commit:` (all forty characters), nothing
    +else. Its subject is the Desk's (`Deploy <service> <version>`), so the Desk's
    +own filing and this one find each other.
    +"""
    +
    +from __future__ import annotations
    +
    +import base64
    +import json
    +import re
    +import subprocess
    +import time
    +import tomllib
    +import urllib.parse
    +from collections.abc import Callable, Mapping
    +from dataclasses import dataclass, field
    +from pathlib import Path
    +from tempfile import TemporaryDirectory
    +
    +from sdlc_jobs._core import (
    +    DIGEST,
    +    FLEET_PUBLIC_KEY,
    +    SEMVER,
    +    CannotRunError,
    +    Response,
    +    Tools,
    +    tool_sdlc,
    +)
    +from sdlc_jobs.life import _hosts
    +from sdlc_jobs.life import _runner as runner
    +from sdlc_jobs.life._runner import RefusedError, Run, Step, Wait
    +from sdlc_jobs.life.release import origin_repo
    +
    +ORG = "crunchtools"
    +QUEUE = "Deploy"

    LOW (General Review): QUEUE is defined but never used; the queue is read from the hosts configuration instead. This unused constant can mislead maintainers into thinking it controls which queue the deploy command uses.

    Suggestion: Remove the unused constant, or use it if the queue is intended to be fixed.

    Evidence:

    QUEUE = "Deploy"
    

    <!-- gatehouse agent=general confidence=98 votes=1/1 -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 23:09 UTC
    Reviewer

    Gatehouse found 6 issues (1 critical, 1 high, 1 medium, 3 low)

    Full review.

    5 finding(s) dropped: their evidence is not in the diff.

    1 finding(s) not re-raised: already answered on this PR.

    <!-- gatehouse review complete -->

    ashigaru-crunchtools-com[bot] ashigaru-crunchtools-com[bot] commented on Dec 04, 2026 23:23 UTC
    Reviewer

    Gatehouse found no issues.

    Reviewed 1 commit since 1021289 (incremental).

    3 finding(s) dropped: their evidence is not in the diff.

    1 finding(s) not re-raised: already answered on this PR.

    <!-- gatehouse review complete -->

    Reviewers
    Assignees
    fatherlinux fatherlinux
    Labels
    risk: low confidence: 82.5% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 89.0% (HIGH) · Higher = larger blast radius
    89.0%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 82.5% · Lower = rushed or shallow review
    82.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 15.6% · Safe to merge
    15.6%