Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 108 additions & 23 deletions assets/opencode/skills/monitoring-deployments/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,16 @@
---
name: monitoring-deployments
description: Use when a merged PR's change still needs to reach its Kubernetes environments -- watching a merged commit roll out to UAT/PROD until the new image is live and pods are healthy, or diagnosing a stuck rollout (deploy not bumped, CrashLoopBackOff, ImagePullBackOff, restart spike), or when a merged commit has no deploy check because a merge queue batched it behind a later commit. Work-only; kubectl/AKS-based.
description: Use when a merged PR's change still needs to reach its Kubernetes environments -- watching a merged commit roll out to UAT/PROD until the new image is live and pods are healthy, or diagnosing a stuck rollout (deploy not bumped, CrashLoopBackOff, ImagePullBackOff, restart spike), or when a merged commit has no deploy check because a merge queue batched it behind a later commit. Also use when a rollout wake from lgtm-shepherd arrives, and when tempted to re-run monitor-rollout.py until a rollout finishes. Work-only; kubectl/AKS-based.
---

# Monitoring Deployments

Merged is not deployed. A PR can merge green and still fail to reach prod: the
image build breaks, the GitOps controller never bumps the deployment, or the
new pods crashloop. This skill is `shepherding-pull-requests` one lifecycle
phase later -- you hold the *rollout* the way that skill holds the PR, until
the merged commit is actually running and healthy, or until there's a real
decision (fix-forward vs roll back) for the user to make.
phase later, and holds the *rollout* the way that skill holds the PR: by
being wakeable, not by watching. Check once, act on what you find, and end
the turn; the rollout watcher brings you back when there is an outcome.

## When to use

Expand All @@ -20,6 +20,11 @@ decision (fix-forward vs roll back) for the user to make.
- Your merge commit has no deploy check at all and you need to tell "the
pipeline never ran" from "the merge queue batched you behind a later commit"
(see "Merge queues" below — assume batching first).
- A rollout wake from `lgtm-shepherd` arrived. Do the payload's `YOUR TASK`;
the invocation it carries is one pass, not the start of a loop. Report and
end the turn. An interim wake ("landed in UAT ... N deployment(s) ship at
the scheduled build ...; checked then") has no task: PROD is not live yet,
and the watcher checks it after that build. Report that and end the turn.

**When NOT to use:** non-k8s deploy targets (Lambda, serverless, static
hosting); pre-merge work (that's `shepherding-pull-requests`).
Expand All @@ -39,34 +44,98 @@ If `INTERNAL.md` is absent (not yet fetched, or the page doesn't exist), the
tooling still works — supply `--target` values directly. Never paste real
cluster/namespace/registry names back into this SKILL.md or the script.

## Tooling: monitor-rollout.py
## One pass, then end the turn

A companion script polls the rollout and prints the next action. Each
invocation has a ~60s wall-clock budget (Anthropic prompt-cache TTL is 5 min; a longer blocking call
expires warm cache), so **you re-invoke it in a loop** — the script owns the
within-60s pacing, you own the loop and the fix step.
**Do not re-invoke `monitor-rollout.py` in a loop.** `lgtm-shepherd`'s rollout
sweep already watches merges to the repos it is configured for: it runs this
same script every 4-6 minutes and wakes the PR's author session (on any host)
when every watched target is live and healthy, when a pod wedges, or when it
gives up: 30 hours after the merge, longer where PROD ships only at a
scheduled build. Such a merge gets an interim wake first, when the targets
that ship at merge have landed. A wedge or an expiry also reaches the human as
a shepherd chat line, whether or not you are around. Polling it yourself pays
for a watch that exists.

```bash
python ~/.agents/skills/monitoring-deployments/monitor-rollout.py \
--pr <PR> \
--merge-sha <sha> --repo <owner>/<repo> \
--target <ENV:CTX:NS:DEPLOY> [--target ...]
```

It waits for the PR to merge, derives the image tag from the merge commit's
short SHA (prefix match, tolerant of a `_N` build-attempt suffix), then watches
each target's deployment spec image and pod health.
One invocation is one pass: it polls for up to 60 seconds and exits. It
derives the image tag from the merge commit's short SHA (prefix match,
tolerant of a `_N` build-attempt suffix), then reads each target's deployment
spec image and pod health. Always pass `--repo`: without it a merge-queue
batch (below) reads as exit 3 forever. `--pr <n>` instead of `--merge-sha`
waits for the merge first; `--pod-selector` if pods aren't labeled
`app=<deployment>`; `--help` for the rest.

| Exit code | Meaning | What to do |
| Exit | Meaning | Do |
|---|---|---|
| `0` | All targets on the new tag, pods Running and pod-level `Ready` | Done. |
| `1` | A new-revision pod is wedged — CrashLoopBackOff / image-pull error in **any** of its containers (sidecars included), or a restart spike **on a pod that is still unready** | Read stdout (it names the container), investigate (step below), then re-invoke or escalate. |
| `2` | Unrecoverable (gh/kubectl failed, unknown context, missing deployment) | Surface to user; don't silently retry. |
| `3` | Still rolling (merge pending, spec not bumped, pods updating) | Re-invoke immediately. |
| `4` | Deployed **as an ancestor** of a later commit, pods healthy (merge-queue batch — see below) | Done. Record the batch head as the deployed SHA, not yours. |
| `0` | All targets on the new tag, pods Running and pod-level `Ready` | Report it live. |
| `1` | A new-revision pod is wedged — CrashLoopBackOff / image-pull error in **any** of its containers (sidecars included), or a restart spike **on a pod that is still unready** | Investigate now ("The fix step" below). It will not self-heal. |
| `2` | Unrecoverable (gh/kubectl failed, unknown context, missing deployment) | Tell the user; do not retry. |
| `3` | Still rolling (merge pending, spec not bumped, pods updating) | **Who is watching?** (below) |
| `4` | Deployed **as an ancestor** of a later commit, pods healthy (merge-queue batch — see below) | Report it live under the batch head's SHA, not yours. |

Pass `--merge-sha <sha>` instead of `--pr` to skip merge polling; `--repo
owner/repo` if not in the repo dir; `--pod-selector` if pods aren't labeled
`app=<deployment>`. Run `--help` for the rest.
### Exit 3: who is watching?

On cloudbox, the sweep watches the repos under `repos:` in its rollout config:

```bash
sed -n '/^repos:/,/^$/p' ~/.config/lgtm/rollout.yml # cloudbox only
```

- **Watched, and you opened the PR** (the shepherd finds you by the
`agent-wait add --pr ... --watch` record from `shepherding-pull-requests`):
**end the turn.** Report "still rolling as of `<time>`; the rollout watcher
wakes this session when it is live or wedges". Urgency ("make sure it gets
to PROD", "before the 9am batch") does not change this, and neither does a
repo's instruction to confirm the deploy: the wake is how you confirm it.
The wake lists the `Targets watched`; a target you care about that is not
on that list is unwatched (below).
- **Off cloudbox**, you cannot read the config: end the turn anyway. A watched
merge brings a rollout wake; any other brings a merge notice saying "no
rollout is being watched for these", and that notice is your cue for the
unwatched case.
- **You did not open the PR:** the watcher's wakes go to the session that did,
and a wedge or expiry to the human. Report what your pass saw and end the
turn. If the human asked you to see it live, take it over with
`agent-wait add --pr ... --watch` and it is watched for you.
- **Unwatched:** the repo is not in the list, the notice said so, or the wake
left out your target. Nobody will look, so this is the one place a wait is
allowed.

### The one allowed wait

Only for an **unwatched** rollout, and only when the human asked to hear that
it is live, or a repo's instructions require confirming the deploy, or your
next action is a change that needs this one running first (a second rollout
stacked on it). Otherwise report "still rolling; nothing watches it" and end
the turn.

The cap is **per merge, for the whole session**; a new turn does not reset
it, and passes already run count against it:

1. **At most 15 passes in total**, back to back, with no `sleep` between them
(each pass already waits up to 60 seconds). Do any work that does not
depend on the rollout before you start.
2. **Still exit 3 at the cap:** end the turn and schedule **one** wake an
hour out (`scheduling-wakes`; there is no rollout checker, so it is a timed
wake). On cloudbox, `agent-wait add --at +1h --note "<payload>"`: a merged
branch's worktree is pruned nightly, and a `swarm_schedule` wake into a
deleted directory never runs. Elsewhere, `swarm_schedule` with
`after: "1h"`. The payload carries the full invocation, "wake 1 of 2", and
that the 15 passes are spent, so the count survives compaction. On that
wake: one pass, no new 15.
3. **At most two such wakes.** Still rolling after the second: stop and tell
the human it has not landed and nothing is watching it.

On a **watched** repo the same cap applies in one case only: the human told
you in this conversation, in so many words, to stay in this turn until it is
live. "Make sure it gets to PROD" is not that; the wake is how you make sure.

A fix-forward is a new merge with its own cap.

## Merge queues: the deploy runs on the batch head, not on your commit

Expand All @@ -93,6 +162,10 @@ means *look for a batch head*, not *the pipeline is broken*.

### Procedure (also what the script automates)

The script runs this check on every pass, including the watcher's. Run it by
hand only to diagnose: an unwatched rollout inside its cap, or an outcome you
need to explain. On a watched repo it is not a reason for another pass.

```bash
# 1. Newest trunk commit at or above your merge commit -- the batch head.
gh api repos/<owner>/<repo>/commits --jq '.[0:5][] | "\(.sha[0:7]) \(.commit.message | split("\n")[0])"'
Expand Down Expand Up @@ -150,7 +223,19 @@ yours:
- **Forbidden on a write you attempt** (rollback, restart) → see
`escalating-azure-aks-rbac`.

A wedged rollout will not self-heal. Don't idle-poll it — act or escalate.
A wedged rollout will not self-heal. Don't idle-poll it — act or escalate. A
fix-forward is a new merge: one pass on it, as above.

## Red flags

| Thought | Reality |
|---|---|
| "The human needs it in PROD by morning; I'll keep re-invoking until it lands" | Watching lands nothing. On a watched repo the wake follows the outcome, usually within minutes, and a wedge reaches the human too; end the turn |
| "I've already run it three times; a few more and it'll be done" | Sunk cost. Watched: end the turn. Unwatched: the cap counts those three |
| "Unwatched, so I'll stay until it finishes" | 15 passes per merge, then at most two scheduled wakes, then the human |
| "They said make sure it lands" / "the repo says confirm it" | On a watched repo the wake is how you make sure. End the turn |
| "UAT is quiet after a few minutes; let me check for a batch head and re-run" | On a watched repo the script does that on every sweep. One pass |
| "I'll schedule a wake to check the watched rollout" | The watcher already wakes you. A wake is for unwatched rollouts only |

## Manual fallback (script not deployed)

Expand Down
55 changes: 31 additions & 24 deletions assets/opencode/skills/monitoring-deployments/monitor-rollout.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,15 @@
trigger never fires, the new pods crashloop). This script holds the rollout
the way monitor-pr.py holds the PR.

Each invocation polls for up to --budget-seconds (default 60), then returns.
The caller re-invokes in a loop until exit 0/1/2. The 60s cap is
deliberate: Anthropic prompt-cache TTL is 5 min, so any
single bash call that blocks the model longer than that expires warm cache
and costs full prompt input on the next turn. Capping at 60s keeps the model
in the loop for fix-as-you-go work AND keeps the cache warm. Do NOT raise the
budget to "just wait it out" -- re-invoke instead.
Each invocation is ONE PASS: it polls for up to --budget-seconds (default
60), then returns. Do not wrap it in a loop. lgtm-shepherd's rollout sweep
already runs this script every few minutes for the repos in its rollout
config and wakes the PR's author on an outcome; the skill says when an
agent may wait instead, and caps it (SKILL.md, "Exit 3: who is watching?").
The 60s cap is deliberate: Anthropic prompt-cache TTL is 5 min, so a single
bash call that blocks the model longer than that expires warm cache and
costs full prompt input on the next turn. Do NOT raise the budget to "just
wait it out".

This script is intentionally topology-agnostic: it takes every cluster
context, namespace, and deployment as arguments and hardcodes nothing about
Expand All @@ -35,7 +37,8 @@
deployment, bad args, malformed JSON). Surface to the user; do not
silently retry.
3 Still rolling -- PR not merged yet, deployment spec not yet bumped to the
new tag, or pods mid-update. Legitimate idle-wait; re-invoke.
new tag, or pods mid-update. Not a cue to run again: see SKILL.md,
"Exit 3: who is watching?".
4 Rolled out AS AN ANCESTOR of a later commit, and healthy. The deployed
tag is not your commit's tag, but the commit it names provably CONTAINS
your commit, so your change IS live. This is the merge-queue batching
Expand Down Expand Up @@ -64,19 +67,10 @@
cannot resolve or cannot prove containment for stays "still rolling"
(exit 3), which is the safe direction to be wrong in.

Usage in the SKILL.md loop body:
while true; do
python monitor-rollout.py --pr 1234 \
--target UAT:my-uat-ctx:uat-ns:my-service \
--target PROD:my-prod-ctx:prod-ns:my-service
case $? in
0) break ;; # rolled out & healthy
1) <investigate per stdout>; ;; # then re-invoke
2) <surface to user>; exit ;;
3) ;; # still rolling, re-invoke
4) break ;; # live as an ancestor of a batch head
esac
done
Usage (one pass; the exit code decides what happens next, per SKILL.md):
python monitor-rollout.py --merge-sha <sha> --repo <owner>/<repo> \
--target UAT:my-uat-ctx:uat-ns:my-service \
--target PROD:my-prod-ctx:prod-ns:my-service
"""
import argparse
import hashlib
Expand Down Expand Up @@ -863,7 +857,7 @@ def parse_args(argv=None):
"--budget-seconds", type=int, default=DEFAULT_BUDGET_SEC,
help=f"Max wall-clock budget per invocation (default: "
f"{DEFAULT_BUDGET_SEC}). Capped by the Anthropic prompt-cache TTL; "
f"re-invoke in a loop rather than raising this.",
f"do not raise it to wait out a rollout.",
)
parser.add_argument(
"--interval", type=int, default=DEFAULT_INTERVAL_SEC,
Expand All @@ -873,6 +867,17 @@ def parse_args(argv=None):
return parser.parse_args(argv)


# Last line of every exit-3 run. It used to say "Re-invoke.", and agents re-ran
# the script for as long as a deploy took (lgtm-0q1b.53). lgtm-shepherd's sweep
# judges by exit code, but lgtm --rollout-check forwards the stdout tail to
# eng-agent-platform's rollout lane, whose agent reads it too: so this says
# only what is true for every caller.
STILL_ROLLING_NEXT = (
"Exit 3 is not a cue to re-run this in a loop; "
"see monitoring-deployments, \"Exit 3: who is watching?\"."
)


def main(argv=None):
args = parse_args(argv)

Expand Down Expand Up @@ -902,7 +907,8 @@ def main(argv=None):
break
print(f" PR #{args.pr}: state={state}, not merged yet")
if not sleep_within_budget(deadline, args.interval):
print("\nBudget elapsed; PR not merged yet. Re-invoke.")
print("\nBudget elapsed; PR not merged yet.")
print(STILL_ROLLING_NEXT)
sys.exit(EXIT_STILL_WAITING)

if len(merge_sha) < SHORT_SHA_LEN:
Expand Down Expand Up @@ -947,7 +953,8 @@ def main(argv=None):
print(f"\n{msg}")
sys.exit(code)
if not sleep_within_budget(deadline, args.interval):
print(f"\nBudget elapsed; still rolling ({msg}). Re-invoke.")
print(f"\nBudget elapsed; still rolling ({msg}).")
print(STILL_ROLLING_NEXT)
sys.exit(EXIT_STILL_WAITING)
print(f" ...sleeping {args.interval}s ({msg})")

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,53 @@ def test_still_rolling_when_intermediate_pod_is_unresolvable(self):
self.assertIn("pods updating", msg)


class StillRollingMessage(unittest.TestCase):
"""Exit 3 is read by agents, and its last line is what they act on. It said
"Re-invoke.", and agents re-ran the script for as long as a deploy took,
although lgtm-shepherd's rollout sweep already watches configured repos
(lgtm-0q1b.53). The sweep judges by exit code; the text is for agents,
including eng-agent-platform's rollout lane, which receives the stdout tail
through lgtm --rollout-check, so it points at the skill rather than
telling any one caller to end its turn."""

def run_main(self, argv, fake):
buf = io.StringIO()
original = mr.run_cmd
mr.run_cmd = fake
try:
with redirect_stdout(buf), self.assertRaises(SystemExit) as cm:
mr.main(argv)
finally:
mr.run_cmd = original
return cm.exception.code, buf.getvalue()

def assert_no_loop_instruction(self, out):
last = out.strip().splitlines()[-1]
self.assertNotIn("re-invoke", out.lower())
self.assertIn("monitoring-deployments", last)
self.assertIn("who is watching", last)

def test_still_rolling_does_not_tell_the_caller_to_loop(self):
fake = FakeCluster(OLDER[:9], [pod_simple("p1", OLDER[:9], OLDER[:9])])
code, out = self.run_main(
["--merge-sha", OURS, "--repo", REPO, "--target", TARGET,
"--budget-seconds", "0", "--no-batch-head-detect"],
fake,
)
self.assertEqual(code, mr.EXIT_STILL_WAITING)
self.assert_no_loop_instruction(out)

def test_unmerged_pr_does_not_tell_the_caller_to_loop(self):
def fake(cmd):
return json.dumps({"state": "OPEN", "mergeCommit": None})
code, out = self.run_main(
["--pr", "1", "--repo", REPO, "--target", TARGET, "--budget-seconds", "0"],
fake,
)
self.assertEqual(code, mr.EXIT_STILL_WAITING)
self.assert_no_loop_instruction(out)


class SpecImageTag(unittest.TestCase):
def test_deployment_spec_tag_is_read_from_the_first_container(self):
fake = FakeCluster(LATER, [])
Expand Down
3 changes: 2 additions & 1 deletion assets/opencode/skills/shepherding-pull-requests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -272,5 +272,6 @@ longer poll or self-wake:
## After merge

On a repo that deploys, merged is not live. When the user cares that it
deploys, hand off to `monitoring-deployments`. Any other post-merge step is in
deploys, hand off to `monitoring-deployments`: one pass, and where lgtm watches
the rollout, its wake brings you back, so no loop there either. Any other post-merge step is in
the repo's `AGENTS.md` or skills, or in your instructions.
7 changes: 5 additions & 2 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -4007,6 +4007,9 @@
# (PersistentLookupCache): the rollout sweep's repeated lookups were
# emptying the GitHub REST quota hourly, and a lost "served from disk"
# test would bring that back while still printing "OK".
#
# 34 -> 36 on 2026-12-01 (StillRollingMessage): exit 3 must not tell the
# caller to re-invoke in a loop (lgtm-0q1b.53).
monitor-rollout = devboxPkgs.runCommand "monitor-rollout-tests" {
nativeBuildInputs = [ devboxPkgs.python3 devboxPkgs.gnugrep ];
} ''
Expand All @@ -4018,8 +4021,8 @@
python3 ${self}/assets/opencode/skills/monitoring-deployments/test_monitor_rollout.py 2>&1 \
| tee "$TMPDIR/out.txt"

grep -q '^Ran 34 tests' "$TMPDIR/out.txt" || {
echo "GATE FAILURE: expected 'Ran 34 tests'. If you added or removed" >&2
grep -q '^Ran 36 tests' "$TMPDIR/out.txt" || {
echo "GATE FAILURE: expected 'Ran 36 tests'. If you added or removed" >&2
echo "tests deliberately, update the count here in the same commit." >&2
exit 1
}
Expand Down
Loading