Move active CI tooling into scripts and archive plans

This commit is contained in:
notplants
2026-11-23 20:09:45 +00:00
parent bf1661b33b
commit 8b883fb59f
58 changed files with 7662 additions and 7629 deletions
-391
View File
@@ -1,391 +0,0 @@
# Advisory scan — specification
What `cc-ci-plan/advisory-scan.py` does, step by step, and why each step exists. This documents the
implementation as it stands (2026-08-11); if you change the code, change this file in the same commit.
`cc-ci-plan/test-advisory-scan.py` is the executable half of this spec — every rule below is asserted
there.
**Role.** A per-recipe CVE detector run as a **pre-step of `/recipe-upgrade`** (step 2a). It is
**strictly additive**: it never replaces the release-note reading the upgrade agent already does. The
CVE count reported for a recipe is the **union** of what the agent read and what this scan found; the
scan may never *lower* a count established by reading.
**Why it exists.** gitea 1.27.1 fixed CVE-2026-60004 and CVE-2026-59774 (both CVSS 9.8). The weekly
report printed gitea's CVE count as `1`, then `none`. The upgrade agent had read the GitHub *release
notes*, which name neither — both were announced only in the vendor's blog security section — and the
report then derived security content from those notes plus model knowledge, which predates the CVEs.
Nothing in the pipeline queried an advisory source. This scan closes that hole.
---
## Two passes
| | Pass 1 — measure | Pass 2 — judge (`--adjudicate`) |
|---|---|---|
| Who | Pure Python, no model | The calling agent, a model |
| Does | Collects evidence and decides every case it can by arithmetic | Weighs the collected evidence on cases arithmetic cannot settle |
| Output | A count, or `UNKNOWN` | FIXED / NOT-FIXED / STILL-UNKNOWN per open case |
| Rule | Deterministic and reproducible | May only **raise** the count, never lower it |
**Prefer pass 1.** Every case pass 1 decides is one that reproduces identically next week. Pass 2 exists
for evidence that is prose rather than data — a fallback, not a co-equal stage. When a class of case
keeps landing in pass 2, the fix is a new deterministic method in pass 1. §4c is exactly that: it moved
12 redis advisories out of pass 2 and into arithmetic.
---
## Inputs
```
advisory-scan.py <recipe> [--from <version>] [--to <version>]
[--image <name>=<from>:<to>]... [--adjudicate] [--json] [--registry DIR]
advisory-scan.py <recipe> --compose-to <URL> [--compose-from <URL>] # windows derived, not typed
```
| Input | Meaning |
|---|---|
| `<recipe>` | Recipe name; selects `cc-ci-plan/upstream/<recipe>.md` (the per-recipe URL registry) |
| `--from` / `--to` | The **primary app image's** version window being upgraded across |
| `--image NAME=FROM:TO` | A **sidecar image and the versions it moved between** (repeatable, all in ONE call). `NAME` is substring-matched against source repo names. Malformed values warn on stderr and are skipped. Without it that image's advisories stay unclassified. |
| `--compose-to URL` | **Derive every window by diffing this compose against its baseline**, instead of typing `--from/--to/--image`. Point it at a PR's `compose.yml`. |
| `--compose-from URL` | Baseline for the above. Default: the same repo's **default branch, resolved from the API** — never assumed to be `main`. |
| `--adjudicate` | Run pass 2: append the evidence dossier for judgement |
| `--registry` | Registry dir; also `CCCI_UPSTREAM_REGISTRY` |
| `GITHUB_TOKEN` / `GITHUB_TOKEN_FILE` | Read-only token; **rate limit only** (60/hr anonymous → 5000/hr). Default file `/srv/cc-ci/.github-token`, mode 600. Public advisories need **no scopes**. |
Exit code is always 0 — this is informational. Failures are *reported*, never raised.
For PR attribution, pin both compose URLs to commits: the PR head and its merge base with the
target branch. A previous release or warm canonical can include image changes already present
before the PR. A compose diff with only sidecar changes has no primary app window; every changed
sidecar is scanned under its own image name.
---
# Pass 1 — deterministic
## Step 1 — Collect source URLs from the registry
Read `cc-ci-plan/upstream/<recipe>.md` and extract every `http(s)://…` URL.
**Trailing markdown punctuation is stripped** (`` ` `` `'` `"` `*` `.` `,` `;` `:` `>` `)`). The registry
is markdown, so URLs appear inside backticks and quotes; capturing the punctuation produced fetches of
`https://docs.n8n.io/release-notes/\`` which 404, and made immich and n8n render `?` for no real reason.
> **Registry hygiene matters.** The scan can only look where the registry points. Two classes of defect
> have been found and fixed by running it: a **wrong URL** (`pgautoupgrade/pgautoupgrade`, which 404s —
> the repo is `pgautoupgrade/docker-pgautoupgrade`) and a **missing** one (gitea's CVEs are announced at
> `blog.gitea.com`, which the registry didn't list). When a vendor publishes security notes somewhere
> the registry lacks, add it.
## Step 2 — Query the sources
Three source classes, each recording **its own status** so *"checked, none found"* is never confused
with *"not checked"*.
### 2a. GitHub Security Advisories — PRIMARY
For every `github.com/<owner>/<repo>` URL in the registry:
`GET /repos/<owner>/<repo>/security-advisories`.
Captured per advisory: `cve_id`, `ghsa_id`, `severity`, `summary`, **`description`**, `published_at`,
and **all** `vulnerabilities[]` entries' `vulnerable_version_range` + `patched_versions` (joined `;`).
- **All entries, not just the first.** An advisory carries one entry **per patched release line** —
n8n patches three (1.123.32, 2.17.4, 2.18.1). Reading only `vulnerabilities[0]` silently dropped the
line a deployment was actually on, and misclassified CVE-2026-42231/42232 as out-of-window.
- **Pagination via the `Link rel="next"` cursor**, to exhaustion (cap 20 hops). This endpoint returns
at most 100 rows **and ignores `?page=`** — it re-returns the same rows, which silently truncates busy
projects. discourse has 286 advisories; a single page cannot even cover one upgrade window.
- **The description is kept from this response.** It is already present here, and pass 2 needs the
prose; re-fetching it per advisory would cost one request each.
- **HTTP 404 ⇒ `no-advisories-published`** — a benign absence (many sidecar images publish none), **not**
a failure. Conflating the two pushed nearly every recipe to `?` and destroyed the signal.
### 2b. Vendor release / security pages
Every other registry URL is fetched, HTML-stripped, and scanned for `CVE-\d{4}-\d{4,7}`, keeping ±160
characters of context per hit.
URLs containing `<`, `>`, `{`, `}`, `VERSION`, or `vX.Y.Z` are **skipped as templates** — they are
human documentation (`…/changelog/v<VERSION>/`), not fetchable, and counting them as failures is wrong.
This is the source that would have caught gitea: the vendor blog names both CVEs, the GitHub release
page names neither.
**When the page is a changelog organised by release, each CVE is attributed to the release heading it
appears under** (`Changes with nginx 1.31.3`, `## v1.31.3`, …) and that becomes its fixed-in version.
Without this, a project that publishes no advisory feed can never contribute a CVE:
> **nginx publishes NO GitHub security advisories.** Every nginx CVE we can see comes from
> `nginx.org/en/CHANGES`. Scraping ids out of it without attributing them to a release left them with
> no patched version, so they were never classifiable — and every nginx bump in the fleet reported
> **0** forever. nginx is a sidecar in most recipes. Measured: `1.31.1 → 1.31.3` fixes **six** CVEs
> (three in .2, three in .3); lasuite-docs#7 went 0 → 6 and lasuite-drive#6 went 0 → 3 on this alone.
A changelog CVE is tied to a window by the **image name appearing in the page URL** (window `nginx` ↔
`nginx.org/...`). A CVE found on a vendor page with no attributable release still has no version data,
so pass 1 cannot place it — it goes to pass 2 (§6).
### 2c. NVD by CPE — the fallback for projects that publish nothing
Declared per recipe in the registry as `nvd-cpe: <image-key> = <cpe:2.3:...>`.
> **Why it exists.** Two recipes could not see CVEs *at all*: `mattermost-lts` (empty GitHub advisory
> feed, security bulletins rendered client-side so a text sweep finds nothing) and `mumble` (nothing
> published anywhere the registry points). Their scans returned `?` — nothing measured. NVD is
> CPE-indexed and carries structured ranges, so it answers where the vendor does not: mattermost
> 10.5.0 → 10.12.4 now scores **165**, and mumble finds `CVE-2025-71264` (fixed 1.6.870).
Two range forms, both used:
| NVD field | meaning | how it is judged |
|---|---|---|
| `versionEndExcluding X` | fixed in X exactly | a normal patched version (§4a) |
| `versionEndIncluding X` | affected **up to and including** X; fix version unpublished | fixed when the upgrade crosses X, i.e. `from ≤ X < to` |
**NVD lags the vendor** — it had neither gitea CVSS-9.8 RCE at publication — so this is a fallback,
never a replacement for 2a/2b. Unauthenticated calls are rate-limited (~5/30s), hence the retry.
### 2d. OSV.dev — supplementary
Only when the recipe has an entry in `OSV_PACKAGES` (ecosystem + package) and a version is given.
> **Measured, not assumed.** For the two gitea CVEs, OSV **404'd on both** and returned only Go
> *dependency* advisories for the package; NVD's API had them by neither CPE, CVE id, nor keyword.
> **Advisory databases lag the vendor**, which is why 2a and 2b lead and this is supplementary.
## Step 3 — Union
All findings merge into one CVE map: id → `{sources[], severity, ghsa, vulnerable_range, patched,
description, published_at, url, cvss, context}`. A CVE seen by several sources keeps them all.
## Step 4 — Classify against the upgrade window
Two invariants govern this step, both learned from a wrong answer in production.
> **A. Every image is judged by its OWN versions.** The app repo uses `--from/--to`; each sidecar uses
> its own `--image NAME=FROM:TO`. **Pass them all in ONE invocation** — the count is a union across
> images, and the UNKNOWN guarantee in B only holds when a single run sees every one. An image with no
> window is **not** classified; its advisories are listed as unclassified so they stay visible without
> inflating the count. Each window is classified independently, so one may use version ranges while
> another falls back to dates.
> *Why:* discourse once reported **133**, of which **34 were redis CVEs** — including
> `CVE-2021-21309`, patched in redis 6.0.11 in 2021 — counted purely because 6.0.11 sits numerically
> inside discourse's `3.5.3 → 2026.7.1` range. The fix is not to ignore sidecars but to give each one
> the versions it actually moved through: with `--image redis=7.4:8.10`, discourse scores
> **140 = 123 (app, by date) + 17 (redis)**, and the redis seventeen include `CVE-2025-49844`,
> **critical**, invisible while sidecars went uncounted.
>
> **B. Never emit a number you cannot justify.** If no method can order a window, the count is
> `null` / `UNKNOWN`, never `0`. A `0` in a security column asserts safety. Equally, an advisory that
> cannot be judged is **indeterminate** (§4d) — never silently counted as "not fixed".
### 3b. Deriving the windows from a compose diff (`--compose-to`)
Typing `--from/--to/--image` by hand means someone has to remember that the recipe also bumped its
redis. That is how sidecar CVEs went uncounted for months. This mode reads the windows off the diff:
1. Fetch both compose files (baseline = the repo's **default branch from the API**, since several
recipes keep a stale `main` beside a live `master`).
2. Parse `{service: (image-repo, tag)}` — keyed by **service, not image repo**, because an upgrade
may change the repo itself (plausible moved `plausible/analytics` →
`ghcr.io/plausible/community-edition`; keyed by repo that reads as one image vanishing and an
unrelated one appearing, losing the app window entirely).
3. Every service whose tag or repo changed becomes a window. The `app` service drives `--from/--to`
(coop-cloud convention: it is the recipe's primary image); the rest become `--image` windows.
Unchanged images produce no window — inventing one would be a false count.
4. The derived windows are printed to stderr before the scan, so the inputs are auditable.
Image names are matched against advisory sources **both ways** — an image name is often longer than
its source repo (`clickhouse/clickhouse-server` vs `ClickHouse/ClickHouse`) and sometimes shorter
(`redis` vs `redis/redis`).
Verified on plausible PR #5: from the compose URL alone it derives `v2.0.0 → v3.2.1` plus
`clickhouse-server 23.4.2.11-alpine → 24.12-alpine`, and reports **6** — identical to the
hand-specified args.
`--from/--to/--image` remain available for finer-grained checks (scanning a window that is not a
literal compose diff, e.g. "what would the compatibility-safe target fix?").
### 4a. By patched version (preferred — exact)
**A fix on the line you are upgrading FROM was already yours.** Projects that maintain several lines
patch them all at once: mattermost fixed `CVE-2025-11794` in 10.11.4, 10.12.1 *and* 10.5.12. An
upgrade 10.11.22 → 10.12.4 crosses 10.12.1, so a naive window test counts it — but 10.11.22 is
already past 10.11.4, so the deployment had the fix before the upgrade. Counting it credits the
upgrade with work it did not do. This check is **skipped for placeholder versions** (`7.4.X` parses
to a bare `7.4`, which would read as "already fixed at 7.4" and silently drop a real fix — exactly
how redis `CVE-2024-46981` was lost when the rule was first added).
`patched_versions` is a **range expression** (`">= 2.18.1"`), possibly several joined by `;`. Extract
every version-looking token; the advisory is **fixed-by-this-upgrade** if **any** patched version `p`
satisfies `from < p <= to` — exclusive lower (a fix already in the version you were on is not this
upgrade's doing), inclusive upper.
**Comparison is zero-padded to equal length**, so `18` == `18.0` == `18.0.0` as semver means it.
Without padding, plain tuple order makes `(18,) < (18,0)`, i.e. a fix in 18.0 falls *outside* a window
ending at 18 — and bare major tags are the norm for sidecars (`postgres:18`, `redis:8-alpine`). Padding
is permissive at the lower bound and conservative at the upper: with `to = 18`, a fix in `18.5` is
**not** counted, because nothing proves which 18.x a floating tag resolved to.
### 4b. By advisory publish date (fallback — temporal)
Used **only** when 4a cannot be trusted: a **version-scheme change**, detected as the leading version
component jumping by ≥ `SCHEME_JUMP` (100) — e.g. semver `3.5.3` → calver `2026.7.1`.
Version strings are unorderable across such a jump (`2025.12.2` compares "newer" than `3.5.3` while
shipping earlier), but **release dates always order**. So:
1. Resolve `--from` and `--to` to **git tag dates** on that source (tries `v<version>` then
`<version>`; annotated tag → tagger date, else commit date).
2. An advisory counts as fixed when `date_from < published_at <= date_to` — the same exclusive/inclusive
boundaries as 4a, so the two methods agree at the edges.
This reproduces, automatically, the hand count that established discourse `3.5.3` (2025-12-30) →
`2026.7.1` (2026-07-31) = **123 CVEs**.
*Assumption:* the vendor publishes advisories at fix time (true for discourse). The count includes
**first-party plugin advisories** where the vendor files them on the same repo — which is why a
plugin-rich project scores far higher than a monolith, not a statement about relative security.
### 4c. By release notes naming the CVE (rescue — for advisories with no fix version)
Applied to advisories 4a/4b could not decide, **before** giving up on them. Fetch the source repo's
GitHub **releases** (cached per repo, 4 pages) and find every tag whose notes **name the CVE id**. If
any such tag falls inside the window by 4a's rule, the advisory is fixed by this upgrade, and the
naming tags are recorded in `fix_versions_from_release_notes` as the citation.
> **Why this is not optional.** Vendors routinely publish an advisory with `patched_versions: "TBD"`
> and then name the CVE in the release notes of every branch that got the fix. **All 12** redis
> advisories crossed by discourse's redis bump are exactly this shape — `TBD`, or a placeholder like
> `7.4.X`, with an open-ended `vulnerable_version_range` (`All`, `>= 7.0.0`) — yet each is named in
> concrete releases (`CVE-2025-32023` → 6.2.19, 7.2.10, 7.4.5, 8.0.3, 8.2.0). Without this method
> discourse's redis contribution reads 5; with it, 17. Six of the twelve are high severity.
### 4d. Otherwise — indeterminate, not excluded
An advisory from a **windowed** source that none of 4a–4c could decide — no usable `patched_versions`,
an open-ended vulnerable range, and no release note naming it — is recorded as **indeterminate**. It is:
- **not** added to the count (nothing justifies counting it), and
- **not** treated as unaffected (nothing justifies dismissing it either).
It is listed prominently, the headline reads *"(at least — see undetermined below)"*, and it becomes an
input to pass 2. Silently excluding these is the same defect class as printing `0` for an unscanned
recipe, one level down.
### 4e. Unorderable window
If neither 4a nor 4b can order a window at all, `count_known = false`, `cve_count_fixed = null`, and the
headline reads **"CVEs fixed by this upgrade: UNKNOWN — the scan could NOT determine a count"** with an
explicit *"This is NOT zero"*. If **any** requested window is unorderable the whole count is suppressed;
a partial number would understate a security figure.
## Step 5 — Output
Markdown (default) for pasting into the per-recipe upgrade log, or `--json`.
| Field | Meaning |
|---|---|
| `cve_count_fixed` | Union across all windows, or **`null`** if any window was unorderable |
| `count_known` | Distinguishes "counted zero" from "could not count" |
| `cve_count_indeterminate` / `indeterminate[]` | Judged by nothing; a **floor marker** on the count |
| `resolved_by_release_notes` | CVE → the tags that named it (4c citations) |
| `windows` | Every source classified, with its from/to |
| `classified_by` | **Per source**: which method decided it |
| `date_window` | **Per source**, when 4b was used |
| `fixed_by_this_upgrade[]` | CVE ids, with severity / GHSA / fixed-in per id |
| `unclassified[]` | Seen but not attributable (other images, or vendor-page-only) |
| `sources[]` / `sources_failed[]` / `sources_benign[]` | Per-source status; only genuine failures in `failed` |
---
# Pass 2 — adjudication (`--adjudicate`)
## Step 6 — What gets judged
Two kinds of open case, both real gaps rather than noise:
1. **Indeterminate** (§4d) — from an image *with* a window, but no fix version is knowable anywhere.
2. **Vendor-page-only** — a CVE seen only on a vendor security page, with no structured advisory
behind it. **gitea's two CVSS-9.8 RCEs are this shape.** They carry no version data, so no
arithmetic can place them, but the page prose usually states the fixed release.
## Step 7 — The evidence dossier
Pass 1 collects; pass 2 judges. Nothing in the dossier interprets — it assembles what was *measured*,
so the judgement is made against evidence rather than recollection. That distinction is the whole
point: the original failure was a report leaning on model knowledge that predated the CVEs, with no
source queried at all.
Per open case: severity, CVSS, sources, its window, why it is undecided, `patched_versions` and
`vulnerable_version_range` **as published**, summary, full description, references, affected ranges
with `first_patched_version`, and **every release tag naming the CVE** — whether or not in window, since
the model may reason about branch lines the arithmetic deliberately will not.
**Pass 2 also sees every decision pass 1 made** — a compact table of counted and excluded advisories
with the evidence behind each verdict. A deterministic verdict can still be wrong (a mis-parsed range,
a release note that mentions a CVE without fixing it), and only a reader with the evidence in front of
it can catch that. Silence means agreement.
## Step 8 — The verdict contract
For each open case: **FIXED** / **NOT-FIXED** / **STILL-UNKNOWN**, each with a one-line reason
**citing the evidence shown**. Every FIXED is added to the recipe's count — pass 1's number is a floor,
not a total. If the evidence does not settle it, **STILL-UNKNOWN**: do not infer from memory of the
project, and never record an undecided CVE as unaffected.
**No silent caps.** `MAX_ADJUDICATE` (25) and `MAX_REVIEW_ROWS` (400) bound the output; whenever either
truncates, the block says how many were dropped and that the unshown remain undetermined.
---
## How consumers must read it
`/recipe-report` renders the `cve` column from the **union** of this scan and the agent's own reading:
- a clean scan → its number, **including `0`**;
- **failed sources**, or `UNKNOWN` → **`?`**, never `none` — a blank reads as "clean", which is exactly
how two CVSS-9.8 gitea RCEs were published as `none`;
- **no upgrade this run** → `0`, not `?` — nothing an upgrade could have fixed;
- a count with **indeterminate advisories** → the number is a floor; say so in the notes;
- benign notes → never `?`.
`?` must stay **rare**: it means *we tried and could not tell*, not *we did not look*. A rash of `?` is
a bug to raise in the report's Addendum, not a normal outcome — every instance so far traced to a defect
in this tool or stale registry data.
## Testing
`test-advisory-scan.py` — 58 offline tests (fixtures, no network) plus 6 live regressions against the
counts published in week-2026-08-07. **The offline tier covers pass 1 only, by design**: pass 2's
judgement is a model's and cannot be asserted deterministically. What *is* tested about pass 2 is the
part that stays deterministic — which cases it selects, and that truncation is always announced.
```
python3 test-advisory-scan.py # offline
python3 test-advisory-scan.py --live # + historic report numbers
```
`audit-advisory-scan.py` re-derives the counts with a **separate** semver implementation and its own
release fetch, then diffs against the scanner. Run it after changing classification; it is what caught
the 12 undercounted redis CVEs.
## Known limits
1. **Versions must be supplied per image.** An image with no `--image` is not counted — the scan will
not guess a version range it was not given. `/recipe-upgrade` passes one per image it bumped.
2. **Date-based counts are temporal**, not exact — they assume publish-at-fix-time.
3. **Registry-bound.** Unlisted vendor security pages are invisible; the scan cannot know what it was
never pointed at.
4. **`NAME` matching is substring-against-source-name**, so a short or generic name can attach to more
than one repo (`postgres` matches `discourse/discourse-postgres`). The primary source is claimed
first and cannot be stolen. A name matching **nothing** is silently ignored — a typo costs coverage
without warning.
5. **Release-note rescue (4c) trusts that naming implies fixing.** A release note that merely mentions a
CVE would be read as fixing it. Pass 2's review table exists partly to catch this.
6. **Rate limit** without a token is 60/hr — a full weekly sweep will exhaust it and degrade to failed
sources (visibly, but degraded).
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/advisory-scan.SPEC.md
File diff suppressed because it is too large Load Diff
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/advisory-scan.py
-199
View File
@@ -1,199 +0,0 @@
#!/usr/bin/env python3
"""Clean, greppable transcript logs for the cc-ci agents.
Claude Code already writes a structured JSONL transcript of every session under
~/.claude/projects/<cwd-slug>/<session-uuid>.jsonl. This renders that into a readable, greppable
one-event-per-line log — WITHOUT touching the agent (read-only on a file it writes anyway, so no
slowdown and zero extra tokens). The raw `tmux pipe-pane` logs are TUI-escape soup; use these instead.
Usage:
agent-log.py render <agent> print the clean transcript to stdout
agent-log.py tail <agent> [N] print the last N (default 40) rendered events
agent-log.py follow-all loop: keep <agent>.clean.log up to date for every agent (run in tmux)
Agents: builder adversary upgrader assistant orchestrator
Output logs (follow-all): /srv/cc-ci/.cc-ci-logs/<agent>.clean.log
Each line: `HH:MM:SS [kind] …` — kinds: user, asst (assistant text), tool:<Name>, result, think(skipped
by default). Long text/results are truncated (full detail stays in the JSONL); newlines collapsed to ⏎.
"""
import json, os, sys, time
PROJ = "/home/loops/.claude/projects"
LOGDIR = "/srv/cc-ci/.cc-ci-logs"
MAXLEN = 800 # truncate any single rendered block to this many chars
# agent -> (project-slug dir, signature substring in the first user/kickoff message)
AGENTS = {
"builder": ("-srv-cc-ci-orch-cc-ci", "cc-ci SUB-PHASE"),
"adversary": ("-srv-cc-ci-orch-cc-ci-adv", "Adversary agent"),
"upgrader": ("-srv-cc-ci-orch", "cc-ci UPGRADER"),
"assistant": ("-srv-cc-ci-orch", "cc-ci ASSISTANT"),
"orchestrator": ("-srv-cc-ci-orch", "cc-ci orchestrator"),
}
def _first_user_text(path, limit=4000):
"""Read the start of a transcript; return the first user-message text (the kickoff signature)."""
try:
with open(path) as f:
for _ in range(60):
ln = f.readline()
if not ln:
break
try:
o = json.loads(ln)
except Exception:
continue
if o.get("type") == "user":
c = (o.get("message") or {}).get("content")
if isinstance(c, str):
return c[:limit]
if isinstance(c, list):
return " ".join(b.get("text", "") for b in c if isinstance(b, dict) and b.get("type") == "text")[:limit]
except FileNotFoundError:
return ""
return ""
def active_jsonl(agent):
"""The agent's current transcript: newest *.jsonl in its slug dir whose kickoff matches the
signature (disambiguates the shared -srv-cc-ci-orch dir; tracks restarts → new uuid)."""
slug, sig = AGENTS[agent]
d = os.path.join(PROJ, slug)
try:
files = [os.path.join(d, f) for f in os.listdir(d) if f.endswith(".jsonl")]
except FileNotFoundError:
return None
files.sort(key=lambda p: os.path.getmtime(p), reverse=True)
for p in files:
if sig in _first_user_text(p):
return p
return None
def _clip(s):
s = " ".join(str(s).split()) if s else "" # collapse all whitespace/newlines
return s if len(s) <= MAXLEN else s[:MAXLEN] + " …[+%d]" % (len(s) - MAXLEN)
def render_line(o, show_think=False):
"""Render one JSONL event to zero or more clean lines (list of strings)."""
t = o.get("type")
if t not in ("user", "assistant"):
return []
ts = (o.get("timestamp") or "")[11:19] or "--:--:--"
m = o.get("message") or {}
c = m.get("content")
out = []
if isinstance(c, str):
if c.strip():
out.append(f"{ts} [user] {_clip(c)}")
return out
if not isinstance(c, list):
return out
for b in c:
if not isinstance(b, dict):
continue
bt = b.get("type")
if bt == "text":
txt = b.get("text", "")
if txt.strip():
out.append(f"{ts} [{'asst' if t=='assistant' else 'user'}] {_clip(txt)}")
elif bt == "thinking":
if show_think:
out.append(f"{ts} [think] {_clip(b.get('thinking',''))}")
elif bt == "tool_use":
inp = b.get("input") or {}
brief = inp.get("command") or inp.get("file_path") or inp.get("path") or inp.get("prompt") or json.dumps(inp)[:200]
out.append(f"{ts} [tool:{b.get('name')}] {_clip(brief)}")
elif bt == "tool_result":
rc = b.get("content")
if isinstance(rc, list):
rc = " ".join(x.get("text", "") for x in rc if isinstance(x, dict))
out.append(f"{ts} [result] {_clip(rc)}")
return out
def render_file(path, show_think=False):
lines = []
with open(path) as f:
for ln in f:
try:
o = json.loads(ln)
except Exception:
continue
lines += render_line(o, show_think)
return lines
def cmd_render(agent, show_think=False):
p = active_jsonl(agent)
if not p:
print(f"(no transcript found for {agent})", file=sys.stderr); sys.exit(1)
print(f"# {agent} ← {p}")
for l in render_file(p, show_think):
print(l)
def cmd_tail(agent, n=40):
p = active_jsonl(agent)
if not p:
print(f"(no transcript found for {agent})", file=sys.stderr); sys.exit(1)
for l in render_file(p)[-n:]:
print(l)
def cmd_follow_all():
"""One cheap process: keep every agent's <agent>.clean.log current. Re-resolves the active
transcript each pass (handles restarts) and appends only newly-parsed events."""
os.makedirs(LOGDIR, exist_ok=True)
state = {} # agent -> (path, byte_offset)
while True:
for agent in AGENTS:
p = active_jsonl(agent)
if not p:
continue
prev_path, off = state.get(agent, (None, 0))
if p != prev_path:
off = 0 # new/restarted session → render from the top
try:
size = os.path.getsize(p)
if off > size: # file truncated/rotated
off = 0
with open(p) as f:
f.seek(off)
chunk = f.read()
new_off = f.tell()
except FileNotFoundError:
continue
if chunk:
rendered = []
for ln in chunk.splitlines():
try:
o = json.loads(ln)
except Exception:
continue
rendered += render_line(o)
if rendered:
with open(os.path.join(LOGDIR, f"{agent}.clean.log"), "a") as out:
out.write("\n".join(rendered) + "\n")
state[agent] = (p, new_off)
time.sleep(5)
def main():
a = sys.argv[1:] or ["follow-all"]
cmd = a[0]
if cmd == "render":
cmd_render(a[1], "--think" in a)
elif cmd == "tail":
cmd_tail(a[1], int(a[2]) if len(a) > 2 and a[2].isdigit() else 40)
elif cmd == "follow-all":
cmd_follow_all()
else:
print(__doc__); sys.exit(2)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/agent-log.py
-850
View File
@@ -1,850 +0,0 @@
#!/usr/bin/env python3
"""
cc-ci unified agent driver — one script, one config (agents.toml).
Replaces the five bespoke launchers (launch.py / launch-orchestrator.py / launch-assistant.py
/ launch-upgrader.py / launch-report.py) and the ~15 scattered dotfiles. Every agent — loop
pair, orchestrator, assistant, one-shot tasks — is declared in agents.toml; the watchdog reads
the SAME file, so there is no env-vs-file drift.
Usage:
agents.py up [name…] start enabled agents (or just the named ones); use-or-create
agents.py down [name…] stop agents (or all)
agents.py status one table: every agent — kind, backend, model, session, phase
agents.py watchdog the supervisor loop (reads agents.toml)
agents.py logs <name> tail an agent's session log
agents.py phase [set N|next|show] inspect / move the loop phase
agents.py selftest backend activity-detector regression checks
agents.py migrate seed state/ from the legacy dotfiles (resume ids, phase idx)
Options:
--config PATH config file (default: <script dir>/agents.toml)
Config is authoritative. A one-off override env AGENT_MODEL_<name> / AGENT_BACKEND_<name>
affects a single invocation only; the persisted watchdog always re-reads the file.
"""
import hashlib, json, os, re, shlex, subprocess, sys, time, tomllib
from datetime import datetime, timedelta
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
# ── config loading ──────────────────────────────────────────────────────────────
def _cfg_path(argv):
if "--config" in argv:
return Path(argv[argv.index("--config") + 1])
return SCRIPT_DIR / "agents.toml"
def load_config(path):
with open(path, "rb") as f:
raw = tomllib.load(f)
defaults = raw.get("defaults", {})
cfg = {
"watchdog": raw.get("watchdog", {}),
"backends": raw.get("backend", {}),
"defaults": defaults,
"loop": raw.get("loop", {}),
"plan_dir": str(SCRIPT_DIR),
"log_dir": defaults.get("log_dir", "/srv/cc-ci/.cc-ci-logs"),
"session_prefix": defaults.get("session_prefix", "cc-ci-"),
}
agents = {}
for a in raw.get("agent", []):
m = {**defaults, **a}
m["session"] = a.get("session", cfg["session_prefix"] + a["name"])
m["kind"] = a.get("kind", "persistent")
# one-off env override (single invocation; watchdog ignores via fresh load each tick)
env_model = os.environ.get(f"AGENT_MODEL_{a['name']}")
env_backend = os.environ.get(f"AGENT_BACKEND_{a['name']}")
if env_model: m["model"] = env_model
if env_backend: m["backend"] = env_backend
agents[a["name"]] = m
cfg["agents"] = agents
cfg["services"] = {s["name"]: {**defaults, **s, "session": cfg["session_prefix"] + s["name"]}
for s in raw.get("service", [])}
cfg["state_dir"] = os.path.join(cfg["log_dir"], "state")
Path(cfg["state_dir"]).mkdir(parents=True, exist_ok=True)
return cfg
def backend_of(cfg, agent):
b = cfg["backends"].get(agent["backend"])
if not b:
die(f"agent {agent['name']}: unknown backend {agent['backend']!r}")
return b
# ── logging ───────────────────────────────────────────────────────────────────
def log(msg):
print(f"[agents {datetime.now():%H:%M:%S}] {msg}", flush=True)
def die(msg):
log(f"ERROR: {msg}")
sys.exit(1)
# ── tmux helpers ────────────────────────────────────────────────────────────────
# ALWAYS target sessions with an exact-match "=" prefix. tmux does prefix/fnmatch on bare
# targets, so "-t cc-ci-assistant" would match "cc-ci-assistant3" — capturing or killing the
# wrong session. "=name" forces an exact match. (Bug found pre-cutover 2026-06-13.)
def TS(name): # exact target-SESSION (has-session, kill-session)
return "=" + name
def TP(name): # exact target-PANE: "=session:" anchors the exact session, current window/pane
return "=" + name + ":"
def session_alive(name):
return subprocess.run(["tmux", "has-session", "-t", TS(name)], capture_output=True).returncode == 0
def session_command(name):
r = subprocess.run(["tmux", "display-message", "-p", "-t", TP(name), "#{pane_current_command}"],
capture_output=True, text=True)
return r.stdout.strip() if r.returncode == 0 else ""
def kill_session(name):
subprocess.run(["tmux", "kill-session", "-t", TS(name)], capture_output=True)
def capture_pane(name, lines=40):
r = subprocess.run(["tmux", "capture-pane", "-p", "-t", TP(name)], capture_output=True, text=True)
return "\n".join(r.stdout.splitlines()[-lines:]) if r.returncode == 0 else ""
def pipe_to_log(session, log_path):
subprocess.run(["tmux", "pipe-pane", "-o", "-t", TP(session), f"cat >> '{log_path}'"])
def new_session(session, cwd, cmd, log_path):
Path(cwd).mkdir(parents=True, exist_ok=True)
subprocess.run(["tmux", "new-session", "-d", "-s", session, "-c", cwd, cmd])
pipe_to_log(session, log_path)
def ping_session(session, msg, submit_key="Enter"):
"""Type a message into a session and submit it; retry submit until the prefix clears."""
if not session_alive(session):
return
prefix = msg[:28]
subprocess.run(["tmux", "send-keys", "-t", TP(session), "-l", "--", msg], capture_output=True)
time.sleep(0.5)
for _ in range(10):
subprocess.run(["tmux", "send-keys", "-t", TP(session), submit_key], capture_output=True)
time.sleep(1)
if prefix not in capture_pane(session, 20):
return
# ── activity / limit / fatal detection (per-backend regexes from config) ─────────
def _re(backend, key):
pat = backend.get(key)
return re.compile(pat, re.I) if pat else None
def _session_log_path(cfg, session):
return Path(cfg["log_dir"]) / f"{session}.log"
def _log_recently_touched(cfg, session, age_seconds):
try:
return (time.time() - _session_log_path(cfg, session).stat().st_mtime) <= age_seconds
except FileNotFoundError:
return False
def pane_active(cfg, agent, pane, *, use_log=True):
backend = backend_of(cfg, agent)
active = _re(backend, "active_re")
if agent["backend"] == "opencode":
# completed opencode turns leave a static footer; only the bottom area = activity
bottom = "\n".join(pane.splitlines()[-10:])
hit = bool(active and active.search(bottom))
grace = int(backend.get("log_grace", 180))
return hit or (use_log and _log_recently_touched(cfg, agent["session"], grace))
return bool(active and active.search(pane))
# ── prompt assembly ───────────────────────────────────────────────────────────
DONE_PLACEHOLDER_RE = re.compile(
r"^\s*(not yet|not done|not complete|incomplete|pending\b|tbd\b|n/?a\b|"
r"written here only|only when|to be (written|filled)|when all|<.*>)", re.I)
def phases(cfg): return cfg["loop"].get("phases", [])
def phase_idx_file(cfg): return os.path.join(cfg["state_dir"], cfg["loop"].get("state_file", "phase-idx"))
def cur_idx(cfg):
try:
v = Path(phase_idx_file(cfg)).read_text().strip()
return int(v) if v.lstrip("-").isdigit() else 0
except FileNotFoundError:
return 0
def cur_phase(cfg):
ps = phases(cfg)
return ps[cur_idx(cfg)] if ps else {}
def resolve_state_file(repo_dir, basename):
p = Path(repo_dir) / "machine-docs" / basename
return p if p.exists() else Path(repo_dir) / basename
def phase_done(cfg, status_basename):
repo = cfg["loop"].get("handoff", {}).get("repo", "/srv/cc-ci/cc-ci")
try:
lines = resolve_state_file(repo, status_basename).read_text().splitlines()
except FileNotFoundError:
return False
marker = cfg["loop"].get("done_marker", "## DONE")
for i, line in enumerate(lines):
if not line.startswith(marker):
continue
body = next((nxt for nxt in lines[i+1:] if nxt.strip()), "")
if DONE_PLACEHOLDER_RE.match(body):
continue
return True
return False
def role_model(cfg, agent):
"""Per-phase override (phases[idx].models[role]) wins, else the agent's configured model."""
role = agent.get("role")
if role:
ov = (cur_phase(cfg).get("models") or {}).get(role)
if ov:
return ov
return agent.get("model", "")
def build_loop_kickoff(cfg, agent):
ph = cur_phase(cfg)
pid, plan, status = ph["id"], ph["plan"], ph["status"]
preamble = (
f"*** cc-ci SUB-PHASE {pid} ***\n"
f"SINGLE SOURCE OF TRUTH for THIS phase: /srv/cc-ci/cc-ci-plan/{plan} — read it in full "
f"now; it defines this phase's mission and Definition of Done.\n"
f"The general loop protocol still applies and lives in /srv/cc-ci/cc-ci-plan/plan.md "
f"(§6.1 coordination, §7 pacing, §9 guardrails) — read those sections too.\n"
f"Track loop state in PHASE-NAMESPACED files UNDER machine-docs/ in your repo clone "
f"(create the dir if missing): machine-docs/{status}, machine-docs/BACKLOG-{pid}.md, "
f"machine-docs/REVIEW-{pid}.md, machine-docs/JOURNAL-{pid}.md. machine-docs/DECISIONS.md "
f"is shared (append).\n"
f"FILE-LOCATION RULE (mandatory): ALL coordination / loop-state files live in "
f"machine-docs/, NEVER the repo root — that includes STATUS/BACKLOG/REVIEW/JOURNAL "
f"(phase-namespaced), DECISIONS.md, DEFERRED.md, and the ADVERSARY-INBOX.md / "
f"BUILDER-INBOX.md side-channels. If you ever find one at the root, git mv it into "
f"machine-docs/.\n"
f'"Done" for this phase = the Builder writes "## DONE" to machine-docs/{status} ONLY after '
f"every Definition-of-Done item is Adversary-verified with a fresh PASS in "
f"machine-docs/REVIEW-{pid}.md (handshake per §6.1).\n"
f"The repo's Phase-1 STATUS.md / BACKLOG.md / REVIEW.md are HISTORY from the completed "
f"Phase 1 — do NOT use them as your state; use the phase-namespaced files above.\n"
f'Wherever the standing rules below say "plan.md"/"STATUS.md"/"BACKLOG.md"/"REVIEW.md", '
f"substitute the phase plan and these machine-docs/ phase-namespaced files.\n\n"
f"=== standing role & rules ===\n"
)
role_prompt = (Path(cfg["plan_dir"]) / "prompts" / f"{agent['role']}.md").read_text()
return preamble + role_prompt
def agent_prompt(cfg, agent):
if agent["kind"] == "loop":
return build_loop_kickoff(cfg, agent)
if agent.get("prompt_file"):
return (Path(cfg["plan_dir"]) / agent["prompt_file"]).read_text()
return agent.get("prompt", "")
# ── resume id ───────────────────────────────────────────────────────────────────
_LEGACY_ID = {"orchestrator": ".orchestrator-session-id", "assistant": ".assistant-session-id"}
def resume_id(cfg, agent):
f = Path(cfg["state_dir"]) / f"{agent['name']}.id"
if f.exists():
v = f.read_text().strip()
if v:
return v
legacy = _LEGACY_ID.get(agent["name"])
if legacy:
lp = Path(cfg["log_dir"]) / legacy
if lp.exists():
v = lp.read_text().strip()
if v:
f.write_text(v) # seed state from legacy
return v
return None
# ── agent launch ────────────────────────────────────────────────────────────────
def start_agent(cfg, agent, *, force=False):
session = agent["session"]
if session_alive(session):
if not force:
log(f"{session} already running — leaving it")
return
kill_session(session)
backend = backend_of(cfg, agent)
model = role_model(cfg, agent)
prompt = agent_prompt(cfg, agent)
log_path = str(_session_log_path(cfg, session))
kf = Path(cfg["state_dir"]) / f"kickoff-{session}.txt"
kf.write_text(prompt)
cwd = agent.get("dir", "/srv/cc-ci-orch")
pid = cur_phase(cfg).get("id", "-") if agent["kind"] == "loop" else "-"
if agent["backend"] == "claude":
rc = f"--remote-control '{session}'" if backend.get("remote_control") else ""
rid = resume_id(cfg, agent) if agent.get("resume") and backend.get("supports_resume") else None
resume = f"--resume '{rid}'" if rid else ""
mflag = f"--model '{model}'" if model else ""
flags = backend.get("flags", "")
cmd = f"{backend['bin']} {resume} {rc} {mflag} {flags} \"$(cat '{kf}')\""
log(f"starting {session} (claude, kind={agent['kind']}, phase={pid}, "
f"model={model or 'default'}{', resume' if rid else ''})")
new_session(session, cwd, cmd, log_path)
elif agent["backend"] == "opencode":
cwd = "/srv/cc-ci-orch/cc-ci" if agent["kind"] == "loop" else cwd
model_env = (f"OPENCODE_CONFIG_CONTENT={shlex.quote(json.dumps({'model': model}))} "
if model else "")
preamble = backend.get("preamble", "")
cmd = (f"{preamble}; {model_env}NO_COLOR=1 {backend['bin']} "
f"attach {backend['server']} --dir {shlex.quote(cwd)}")
log(f"starting {session} (opencode, kind={agent['kind']}, phase={pid}, model={model or 'default'})")
new_session(session, cwd, cmd, log_path)
time.sleep(int(backend.get("connect_delay", 12)))
boot = f"Your full kickoff prompt is in {kf} — read it now with: `cat '{kf}'` — then follow it exactly."
ping_session(session, boot, submit_key=backend.get("submit_key", "C-m"))
else:
die(f"unknown backend {agent['backend']!r}")
def start_service(cfg, svc):
session = svc["session"]
if session_alive(session):
log(f"{session} already running — leaving it")
return
log(f"starting service {session}")
new_session(session, svc.get("dir", cfg["plan_dir"]), svc["command"],
str(_session_log_path(cfg, session)))
# ── usage-limit state machine (ported verbatim from launch.py) ───────────────────
RESET_RE = re.compile(r"resets?\s*(?:at\s*)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?", re.I)
def _limit_state_path(cfg, session): return Path(cfg["state_dir"]) / f"limited-{session}.json"
def _load_limit_state(cfg, session):
try: return json.loads(_limit_state_path(cfg, session).read_text())
except Exception: return None
def _save_limit_state(cfg, session, st): _limit_state_path(cfg, session).write_text(json.dumps(st))
def _clear_limit_state(cfg, session):
try: _limit_state_path(cfg, session).unlink()
except FileNotFoundError: pass
def _parse_reset_epoch(pane):
matches = list(RESET_RE.finditer(pane))
if not matches:
return None
m = matches[-1]
try:
hour, minute = int(m.group(1)), int(m.group(2) or 0)
ampm = (m.group(3) or "").lower()
if ampm == "pm" and hour != 12: hour += 12
elif ampm == "am" and hour == 12: hour = 0
if hour > 23 or minute > 59: return None
cand = datetime.now().replace(hour=hour, minute=minute, second=0, microsecond=0)
if cand.timestamp() <= time.time(): cand += timedelta(days=1)
return cand.timestamp()
except Exception:
return None
def _next_limit_until(cfg, pane, now):
fallback = int(cfg["watchdog"].get("limit_probe_fallback", 300))
slack = int(cfg["watchdog"].get("limit_reset_slack", 45))
parsed = _parse_reset_epoch(pane)
if parsed is not None and parsed - now <= 6 * 3600:
return parsed + slack, True
return now + fallback, False
def _limit_nudge_msg(kind):
if kind in ("persistent", "orchestrator"):
return ("watchdog probe: if the quota window has reset, RESUME now — re-check status "
"and continue from where you stopped.")
return ("watchdog probe: if the quota window has reset, RESUME your loop now — pull latest, "
"re-read your phase STATUS/REVIEW files, and continue; re-arm your loop pacing.")
def limit_tick(cfg, agent, pane):
"""True while the agent is inside a usage-limit window — callers suppress all healing."""
session = agent["session"]
backend = backend_of(cfg, agent)
limit_re = _re(backend, "limit_re")
submit = backend.get("submit_key", "Enter")
fallback = int(cfg["watchdog"].get("limit_probe_fallback", 300))
state = _load_limit_state(cfg, session)
limited_now = bool(limit_re and limit_re.search(pane))
if state is None:
if not limited_now or pane_active(cfg, agent, pane, use_log=False):
return False
now = time.time()
until, parsed = _next_limit_until(cfg, pane, now)
if parsed:
log(f"limit hit on {agent['name']} — banner says reset "
f"{datetime.fromtimestamp(until):%a %H:%M}; holding (no reboots)")
else:
log(f"limit hit on {agent['name']} — reset unparsable; flat "
f"{fallback//60}-min probe loop (no reboots)")
_save_limit_state(cfg, session, {"until": until, "nudges": 0})
return True
if pane_active(cfg, agent, pane, use_log=False) or not limited_now:
log(f"limit lifted on {agent['name']} — clearing limit state")
_clear_limit_state(cfg, session)
return False
now = time.time()
if now < state.get("until", 0):
return True
msg = _limit_nudge_msg(agent["kind"])
if msg[:28] in "\n".join(pane.splitlines()[-8:]):
return True
nudges = state.get("nudges", 0) + 1
log(f"limit probe #{nudges} on {agent['name']} — nudging to resume")
ping_session(session, msg, submit_key=submit)
time.sleep(3)
pane2 = capture_pane(session, 40)
if pane_active(cfg, agent, pane2, use_log=False) and not (limit_re and limit_re.search(pane2)):
log(f"limit lifted on {agent['name']} — probe resumed it")
_clear_limit_state(cfg, session)
return True
until, _ = _next_limit_until(cfg, pane2, now)
if nudges == 3:
log(f"WARNING: {agent['name']} still limited after {nudges} probes — flat probes; never rebooting")
_save_limit_state(cfg, session, {"until": until, "nudges": nudges})
return True
# ── stall detection (ported) ─────────────────────────────────────────────────────
_idle_since: dict[str, float] = {}
def _last_nonempty_line(text):
for line in reversed(text.splitlines()):
if line.strip():
return line.strip()
return ""
def _parse_waiting_until(agent, pane):
if agent["backend"] == "opencode":
line = _last_nonempty_line(pane)
if not line.startswith("WAITING-UNTIL:"):
return None
m = re.search(r"WAITING-UNTIL:\s*(\S+)", line)
else:
m = re.search(r"WAITING-UNTIL:\s*(\S+)", pane)
if not m:
return None
try:
return datetime.fromisoformat(m.group(1).replace("Z", "+00:00")).timestamp()
except Exception:
return None
def stall_check_one(cfg, agent):
session = agent["session"]
if not session_alive(session):
_idle_since[session] = 0.0
_clear_limit_state(cfg, session)
return
now = time.time()
pane = capture_pane(session, 40)
if limit_tick(cfg, agent, pane):
_idle_since[session] = 0.0
return
if pane_active(cfg, agent, pane):
_idle_since[session] = 0.0
return
since = _idle_since.get(session) or now
_idle_since[session] = since
idle = now - since
grace = int(cfg["watchdog"].get("stall_grace", 180))
until = _parse_waiting_until(agent, pane)
if until is not None:
if now <= until + grace:
return
reason = f"past its WAITING-UNTIL by {int(now-until)}s — self-wake did not fire"
else:
stall_idle = int(backend_of(cfg, agent).get("stall_idle", 300))
if idle < stall_idle:
return
reason = f"idle {int(idle)}s with no WAITING-UNTIL marker"
log(f"stall: {agent['name']} ({session}) {reason} — kill + reboot")
start_agent(cfg, agent, force=True)
_idle_since[session] = 0.0
# ── healing (ported, config-driven) ──────────────────────────────────────────────
def _expected_backend_cmd(agent):
return "opencode" if agent["backend"] == "opencode" else "claude"
def backend_mismatch(agent):
cmd = session_command(agent["session"])
# only a definite OTHER known backend is a mismatch; transient bash/sh during startup is not
if cmd not in ("claude", "opencode"):
return False
return cmd != _expected_backend_cmd(agent)
def heal_one(cfg, agent):
session = agent["session"]
backend = backend_of(cfg, agent)
if not session_alive(session):
log(f"{agent['name']} ({session}) gone — restarting")
start_agent(cfg, agent)
return
if backend_mismatch(agent):
log(f"{agent['name']} ({session}) is {session_command(session)!r}, expected "
f"{_expected_backend_cmd(agent)} — kill + restart")
start_agent(cfg, agent, force=True)
return
pane = capture_pane(session, 25)
if pane_active(cfg, agent, pane):
return
if limit_tick(cfg, agent, pane):
return
fatal = _re(backend, "fatal_re")
if fatal and fatal.search(pane):
log(f"FATAL session-state error on {agent['name']} ({session}) — kill + restart")
start_agent(cfg, agent, force=True)
# ── wake (persistent agents with a wake schedule) ────────────────────────────────
def wake_agent(cfg, agent):
"""Returns True when the wake landed (or is moot), False to retry next tick."""
wake = agent.get("wake")
if not wake:
return True
session = agent["session"]
if not session_alive(session):
return False
backend = backend_of(cfg, agent)
if pane_active(cfg, agent, capture_pane(session, 25)):
return False
pf = wake.get("prompt_file")
try:
msg = " ".join((Path(cfg["plan_dir"]) / pf).read_text().split())
except (FileNotFoundError, TypeError):
log(f"wake skipped for {agent['name']} — prompt file missing: {pf}")
return True
if not msg:
return True
log(f"waking {agent['name']} ({session}) for scheduled supervision pass")
ping_session(session, msg, submit_key=backend.get("submit_key", "Enter"))
return True
# ── handoff signalling (loop pair, ported) ───────────────────────────────────────
_hand = {"sha": "", "adv_inbox": "", "builder_inbox": ""}
def handoff_reset():
_hand["sha"] = _hand["adv_inbox"] = _hand["builder_inbox"] = ""
def _git(repo, args):
return subprocess.run(f"git -C {repo!r} {args}", shell=True, capture_output=True, text=True)
def _show_pushed(repo, path):
for loc in (f"origin/main:machine-docs/{path}", f"origin/main:{path}"):
r = _git(repo, f"show {loc!r}")
if r.returncode == 0:
return r.stdout
return ""
def handoff_check(cfg):
h = cfg["loop"].get("handoff")
if not h:
return
repo = h["repo"]
sub = lambda name: cfg["agents"].get(name, {}).get("session", cfg["session_prefix"] + name)
submit = backend_of(cfg, cfg["agents"]["builder"]).get("submit_key", "Enter")
_git(repo, "fetch -q origin")
head = _git(repo, "rev-parse origin/main").stdout.strip()
if head:
if not _hand["sha"]:
_hand["sha"] = head
elif head != _hand["sha"]:
subjects = _git(repo, f"log --format=%s {_hand['sha']}..origin/main").stdout
if re.search(r"^claim", subjects, re.M | re.I):
log("handoff: claim(...) commit → pinging adversary")
ping_session(sub(h.get("claim_pings", "adversary")),
"watchdog ping: the Builder pushed a gate CLAIM (claim(...) commit). "
"Pull and verify the claimed gate now.", submit_key=submit)
if re.search(r"^review", subjects, re.M | re.I):
log("handoff: review(...) commit → pinging builder")
ping_session(sub(h.get("review_pings", "builder")),
"watchdog ping: the Adversary pushed a verdict/finding (review(...) commit). "
"Pull REVIEW and act.", submit_key=submit)
_hand["sha"] = head
inboxes = h.get("inboxes", [])
md5 = lambda s: hashlib.md5(s.encode()).hexdigest()
for fname, key, target in (
(inboxes[0] if len(inboxes) > 0 else None, "adv_inbox", "adversary"),
(inboxes[1] if len(inboxes) > 1 else None, "builder_inbox", "builder"),
):
if not fname:
continue
content = _show_pushed(repo, fname)
if content:
hh = md5(content)
if hh != _hand[key]:
log(f"handoff: {fname} changed → pinging {target}")
ping_session(sub(target),
f"watchdog ping: the other loop pushed machine-docs/{fname} — pull, read it, "
f"act, then delete the file (commit + push) to mark it consumed.", submit_key=submit)
_hand[key] = hh
else:
_hand[key] = ""
# ── phase advance (loop machine, ported) ─────────────────────────────────────────
def loop_agents(cfg):
return [a for a in cfg["agents"].values() if a["kind"] == "loop" and a.get("enabled", True)]
def stop_loops(cfg):
for a in loop_agents(cfg):
if session_alive(a["session"]):
log(f"killing {a['session']}")
kill_session(a["session"])
def start_loops(cfg):
for a in loop_agents(cfg):
start_agent(cfg, a)
def phase_advance_check(cfg):
"""On heavy tick: if the current phase is DONE, advance (or finish the sequence).
Returns True only when it actually transitions/completes THIS tick (caller skips healing
that one tick). Once the sequence is already marked complete it is idempotent (returns
False, no re-log, no re-stop) so the watchdog keeps supervising the orchestrator without
spamming the log or churning the intentionally-stopped loops. If the operator APPENDS a
phase after completion, the current phase is no longer last → it advances and clears the
stale completion marker, resuming the loops on the new phase."""
ps = phases(cfg)
if not ps or not cfg["loop"].get("auto_advance", True):
return False
marker = Path(cfg["log_dir"]) / "SEQUENCE-COMPLETE"
idx = cur_idx(cfg)
ph = ps[idx]
if not phase_done(cfg, ph["status"]):
return False
nxt = idx + 1
if nxt < len(ps):
log(f"PHASE {ph['id']} DONE — auto-transitioning to {ps[nxt]['id']}")
stop_loops(cfg)
Path(phase_idx_file(cfg)).write_text(str(nxt))
if marker.exists():
marker.unlink() # resuming into a (freshly-appended) phase — clear stale completion
handoff_reset()
start_loops(cfg)
return True
# last phase is DONE → sequence complete
if marker.exists():
return False # already handled — idempotent (no re-log, no re-stop)
log(f"PHASE SEQUENCE COMPLETE (last phase {ph['id']} DONE) — stopping loops")
stop_loops(cfg)
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
marker.write_text(f"cc-ci phase sequence complete {ts}. Loops stopped; build finished.\n")
oc = cfg["loop"].get("on_complete")
if oc:
trig = Path(cfg["log_dir"]) / oc.get("trigger_file", ".run-upgrade-on-complete")
if trig.exists():
trig.unlink()
runname = oc.get("run", "upgrader")
log(f"on_complete: launching task agent {runname!r}")
if runname in cfg["agents"]:
start_agent(cfg, cfg["agents"][runname], force=True)
return True
# ── watchdog loop ────────────────────────────────────────────────────────────────
def watched(cfg):
return [a for a in cfg["agents"].values()
if a.get("enabled", True) and a.get("watch", "none") != "none"]
def watchdog_loop(cfg_path):
cfg = load_config(cfg_path)
sig = int(cfg["watchdog"].get("signal_interval", 30))
heavy = int(cfg["watchdog"].get("heavy_interval", 300))
ps = phases(cfg)
log(f"watchdog up — phase={cur_phase(cfg).get('id','-')} [{cur_idx(cfg)+1}/{len(ps)}] "
f"signal={sig}s heavy={heavy}s, watching: {[a['name'] for a in watched(cfg)]}")
elapsed = heavy # force a heavy check on first tick
wake_elapsed = {a["name"]: 0 for a in cfg["agents"].values() if a.get("wake")}
while True:
cfg = load_config(cfg_path) # re-read every tick: config is authoritative, no env drift
has_loops = bool(loop_agents(cfg))
seq_done = (Path(cfg["log_dir"]) / "SEQUENCE-COMPLETE").exists()
if has_loops:
handoff_check(cfg)
# signal-tick limit + stall care for every watched agent
for a in watched(cfg):
if a["watch"] == "heal+stall":
stall_check_one(cfg, a)
else:
# limit care only (low resume latency) for heal-only agents
if session_alive(a["session"]):
limit_tick(cfg, a, capture_pane(a["session"], 40))
# Scheduled wakes (e.g. the hourly orchestrator supervision ping). Suppressed once the
# build SEQUENCE is COMPLETE — nothing left to supervise, so stay fully at rest. Resumes
# automatically when new work is queued (that removes the SEQUENCE-COMPLETE marker).
if not seq_done:
for name, el in list(wake_elapsed.items()):
interval = int(cfg["agents"][name]["wake"].get("interval", 3600))
if el >= interval:
if wake_agent(cfg, cfg["agents"][name]):
wake_elapsed[name] = 0
if elapsed >= heavy:
elapsed = 0
advanced = phase_advance_check(cfg) if has_loops else False
if not advanced:
# When the build sequence is complete the loops are intentionally stopped —
# keep healing the orchestrator (and any persistent agent) but do NOT restart
# the finished loops. (seq_done computed at the top of the tick.)
for a in watched(cfg):
if seq_done and a["kind"] == "loop":
continue
heal_one(cfg, a)
time.sleep(sig)
elapsed += sig
for k in wake_elapsed:
wake_elapsed[k] += sig
def loop_sessions_alive(cfg):
return any(session_alive(a["session"]) for a in loop_agents(cfg))
# ── CLI commands ──────────────────────────────────────────────────────────────
def start_watchdog(cfg, cfg_path):
session = cfg["session_prefix"] + "watchdog"
if session_alive(session):
log("watchdog already running")
return
log("starting watchdog")
script = Path(__file__).resolve()
new_session(session, cfg["plan_dir"],
f"exec >>'{cfg['log_dir']}/{session}.log' 2>&1; "
f"python3 '{script}' watchdog --config '{cfg_path}'",
str(_session_log_path(cfg, session)))
def cmd_up(cfg, cfg_path, names):
if cfg["loop"].get("resume_phase") is False and not Path(phase_idx_file(cfg)).exists():
Path(phase_idx_file(cfg)).write_text("0")
targets = ([cfg["agents"][n] for n in names if n in cfg["agents"]]
if names else
[a for a in cfg["agents"].values() if a.get("enabled", True)])
for a in targets:
start_agent(cfg, a)
if not names:
for s in cfg["services"].values():
start_service(cfg, s)
start_watchdog(cfg, cfg_path)
else:
for n in names:
if n in cfg["services"]:
start_service(cfg, cfg["services"][n])
if n == "watchdog":
start_watchdog(cfg, cfg_path)
def cmd_down(cfg, names):
sessions = []
if names:
for n in names:
if n in cfg["agents"]: sessions.append(cfg["agents"][n]["session"])
elif n in cfg["services"]: sessions.append(cfg["services"][n]["session"])
elif n == "watchdog": sessions.append(cfg["session_prefix"] + "watchdog")
else:
sessions = [a["session"] for a in cfg["agents"].values()]
sessions += [s["session"] for s in cfg["services"].values()]
sessions.append(cfg["session_prefix"] + "watchdog")
for s in sessions:
if session_alive(s):
log(f"killing {s}")
kill_session(s)
def cmd_status(cfg):
idx, ps = cur_idx(cfg), phases(cfg)
if ps:
ph = ps[idx]
done = "## DONE" if phase_done(cfg, ph["status"]) else "in progress"
print(f" phase: {ph['id']} [{idx+1}/{len(ps)}] plan={ph['plan']} ({done})")
print(f" {'AGENT':<14} {'KIND':<11} {'BACKEND':<9} {'MODEL':<20} {'WATCH':<10} STATE")
for a in cfg["agents"].values():
st = "RUNNING" if session_alive(a["session"]) else "stopped"
en = "" if a.get("enabled", True) else " (disabled)"
rc = session_command(a["session"]) if st == "RUNNING" else ""
print(f" {a['name']:<14} {a['kind']:<11} {a['backend']:<9} "
f"{role_model(cfg,a) or 'default':<20} {a.get('watch','none'):<10} {st}{en}"
+ (f" [{rc}]" if rc else ""))
for s in cfg["services"].values():
st = "RUNNING" if session_alive(s["session"]) else "stopped"
print(f" {s['name']:<14} {'service':<11} {'-':<9} {'-':<20} {'-':<10} {st}")
wd = cfg["session_prefix"] + "watchdog"
print(f" {'watchdog':<14} {'service':<11} {'-':<9} {'-':<20} {'-':<10} "
f"{'RUNNING' if session_alive(wd) else 'stopped'}")
def cmd_phase(cfg, args):
if not args or args[0] == "show":
idx, ps = cur_idx(cfg), phases(cfg)
print(f"phase {ps[idx]['id']} [{idx+1}/{len(ps)}] seq: {' '.join(p['id'] for p in ps)}")
return
if args[0] == "next":
Path(phase_idx_file(cfg)).write_text(str(min(cur_idx(cfg)+1, len(phases(cfg))-1)))
elif args[0] == "set" and len(args) > 1:
Path(phase_idx_file(cfg)).write_text(str(int(args[1])))
print(f"phase idx now {cur_idx(cfg)} ({cur_phase(cfg).get('id')})")
def cmd_migrate(cfg):
"""Seed state/ from the legacy dotfiles so a cutover is seamless."""
legacy_phase = Path(cfg["log_dir"]) / ".phase-idx"
if legacy_phase.exists() and not Path(phase_idx_file(cfg)).exists():
log(f"NOTE: legacy .phase-idx={legacy_phase.read_text().strip()} — set state/phase-idx "
f"to the DE-DUPED index yourself (cf55: 10→9). Not auto-copied.")
for name in ("orchestrator", "assistant"):
a = cfg["agents"].get(name)
if a:
rid = resume_id(cfg, a) # seeds state/<name>.id from legacy
log(f"{name} resume id: {rid or '(none)'}")
log("migrate done — review state/ dir")
def cmd_selftest(cfg):
oc = {"name": "x", "backend": "opencode", "session": "x", "kind": "loop"}
idle = "\n ▣ Build · GPT-5.4 · 2m 19s\n 178.4K (17%) ctrl+p commands\n"
active = "\n ~ Preparing patch...\n ⬝⬝⬝■■ esc interrupt 137.6K\n"
checks = [
("opencode idle footer is idle", not pane_active(cfg, oc, idle, use_log=False)),
("opencode active footer is active", pane_active(cfg, oc, active, use_log=False)),
("limit banner+idle footer not active",
not pane_active(cfg, oc, idle + "\nYou've hit your weekly limit · resets Jun 16, 10pm\n", use_log=False)),
]
bad = [n for n, ok in checks if not ok]
for n, ok in checks:
print(f" {'PASS' if ok else 'FAIL'}: {n}")
sys.exit(1 if bad else 0)
# ── main ──────────────────────────────────────────────────────────────────────
def main():
argv = sys.argv[1:]
cfg_path = _cfg_path(argv)
argv = [a for i, a in enumerate(argv)
if a != "--config" and (i == 0 or argv[i-1] != "--config")]
cmd = argv[0] if argv else "status"
rest = argv[1:]
cfg = load_config(cfg_path)
if cmd == "up": cmd_up(cfg, cfg_path, rest)
elif cmd == "down": cmd_down(cfg, rest)
elif cmd == "status": cmd_status(cfg)
elif cmd == "watchdog": watchdog_loop(cfg_path)
elif cmd == "phase": cmd_phase(cfg, rest)
elif cmd == "migrate": cmd_migrate(cfg)
elif cmd == "selftest": cmd_selftest(cfg)
elif cmd == "logs":
if not rest:
die("usage: agents.py logs <name>")
sess = cfg["agents"].get(rest[0], {}).get("session") or (cfg["session_prefix"] + rest[0])
os.execvp("tail", ["tail", "-f", str(_session_log_path(cfg, sess))])
else:
print(__doc__)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/agents.py
-105
View File
@@ -1,105 +0,0 @@
# cc-ci unified agent configuration — the single source of truth.
#
# One file declares: which agents exist, their backend, model, prompt, kind, and how the
# watchdog supervises them. Read by agents.py (driver + watchdog). Runtime state (phase
# index, resume ids, limit windows) lives under <log_dir>/state/, NOT here.
#
# Precedence: this file is authoritative. A one-off CLI override (env AGENT_<field>_<name>)
# affects only a single `agents.py` invocation; the persisted watchdog always reads this file.
# ─────────────────────────── global watchdog cadence ───────────────────────────
[watchdog]
signal_interval = 30 # s between handoff / stall / limit checks (light)
heavy_interval = 300 # s between heal / phase-advance checks
limit_probe_fallback = 300 # flat probe cadence when a reset time can't be parsed
limit_reset_slack = 45 # s past a parsed reset before probing
# ─────────────────────────── backends (declared as data) ───────────────────────────
[backend.claude]
bin = "claude"
flags = "--dangerously-skip-permissions"
remote_control = true
supports_resume = true
prompt_delivery = "arg" # full prompt passed as a CLI argument
submit_key = "Enter"
stall_idle = 300
active_re = "esc to interrupt|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏|Running tool|▣|Build ·|· \\d+"
limit_re = "spend limit|usage limit|limit reached|reached your .*limit|out of (credits|tokens)"
fatal_re = "redacted_thinking|blocks cannot be modified|cannot be modified"
[backend.opencode]
bin = "/home/loops/.local/bin/opencode"
server = "http://127.0.0.1:4096"
supports_resume = false
prompt_delivery = "ping" # send after the TUI connects
connect_delay = 12
submit_key = "C-m"
preamble = "set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a"
stall_idle = 900
active_re = "esc interrupt|thinking|inferring|running tool|tool call|preparing patch|reading|searching"
limit_re = "spend limit|usage limit|limit reached|reached your .*limit|out of (credits|tokens)"
fatal_re = "redacted_thinking|blocks cannot be modified|cannot be modified"
# ─────────────────────────── defaults for every agent ───────────────────────────
[defaults]
backend = "claude"
model = "claude-sonnet-4-6"
dir = "/srv/cc-ci-orch"
watch = "heal" # none | heal | heal+stall
log_dir = "/srv/cc-ci/.cc-ci-logs"
# ─────────────────────────── agents ───────────────────────────
[[agent]]
name = "orchestrator" # tmux session: cc-ci-orchestrator
kind = "persistent"
backend = "opencode" # operator 2026-09-07 (evening): NO Claude on the cc-ci host — the
model = "opencode-go/glm-5.3-flash" # orchestrator is an opencode agent, steered via the opencode web UI
# (https://oc.ci.commoninternet.net). Claude sessions live on notplants-orchestrator.
resume = false # opencode backend has no --resume equivalent (fresh session each launch)
watch = "heal" # restart if dead / FATAL / backend-mismatch; never stall-reboot
wake = { interval = 3600, prompt_file = "ai-progress-monitor-prompt.txt" }
prompt = """
STARTUP (auto-launch): you are the cc-ci operator steering agent. Read AGENTS.md
and README.md, inspect the current host, weekly upgrade, report, and auto-update
status using /cc-ci-status, then report any concrete issue. The original
Builder/Adversary build is complete; do not relaunch its loops."""
[[agent]]
name = "assistant" # tmux session: cc-ci-assistant
kind = "persistent"
resume = true
watch = "none"
enabled = false
prompt = """
You are the cc-ci ASSISTANT. Read cc-ci-plan/JOURNAL.md for context, then wait for a specific \
plan/task from the orchestrator or operator. Work autonomously until the assigned task is \
complete, report the result, and then wait for the next assignment."""
[[agent]]
name = "upgrader" # tmux session: cc-ci-upgrader
kind = "task" # one-shot: run to completion, then idle
dir = "/srv/cc-ci"
watch = "none"
enabled = false # launched by the weekly timer or on demand
prompt = """
You are the cc-ci weekly UPGRADER. Invoke the /upgrade-all skill in DEFAULT mode (read \
/srv/cc-ci/.claude/skills/upgrade-all/SKILL.md for the full procedure), run it to completion, \
then report the summary of every PR opened and go idle."""
[[agent]]
name = "report" # tmux session: cc-ci-report
kind = "task"
dir = "/srv/cc-ci"
model = "claude-opus-4-8" # report is authored by opus even when the upgrader runs sonnet
watch = "none"
enabled = false
prompt = """
You generate the public weekly "Recipe Report". Run the /recipe-report skill now (full spec: \
/srv/cc-ci/.claude/skills/recipe-report/SKILL.md; creds in /srv/cc-ci/.testenv), then go idle."""
# Non-AI helper services (started by `up`, not AI sessions)
[[service]]
name = "cleanlogs" # tmux session: cc-ci-cleanlogs
command = "python3 cc-ci-plan/agent-log.py follow-all"
dir = "/srv/cc-ci-orch"
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/agents.toml
@@ -1,5 +0,0 @@
You are the cc-ci operator steering agent on the combined host. Check the
current weekly upgrade and report, host auto-update state, failed units, disk,
Swarm replicas, front doors, and the CI bridge using /cc-ci-status. Investigate
concrete failures and report the result. The original Builder/Adversary build
loops are complete and archived; do not relaunch them.
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/ai-progress-monitor-prompt.txt
-151
View File
@@ -1,151 +0,0 @@
#!/usr/bin/env python3
"""Independent audit of advisory-scan's counts.
Deliberately does NOT reuse the scanner's classifier. Re-parses patched versions with a separate
semver implementation and re-derives membership, then diffs against what the scanner concluded.
Anything the two disagree on is a miscategorization in one of them.
"""
import importlib.util, json, re, sys
spec = importlib.util.spec_from_file_location("A", "/srv/cc-ci-orch/cc-ci-plan/advisory-scan.py")
A = importlib.util.module_from_spec(spec); spec.loader.exec_module(A)
REG = "/srv/cc-ci-orch/cc-ci-plan/upstream"
def sv(s):
"""Independent semver parse: strict 3-tuple, missing parts are 0."""
m = re.match(r"^\s*v?(\d+)(?:\.(\d+))?(?:\.(\d+))?", s or "")
if not m:
return None
return tuple(int(x) if x else 0 for x in m.groups())
def in_window(f, t, patched_expr):
"""Independent membership: any patched token strictly above f and at most t."""
kf, kt = sv(f), sv(t)
for tok in re.findall(r"\d+(?:\.\d+)*", patched_expr or ""):
c = sv(tok)
if c and kf and kt and kf < c <= kt:
return True
return False
_RELS = {}
def fetch_releases(owner_repo):
"""Independent releases fetch — deliberately NOT the scanner's cache or pagination helper."""
if owner_repo in _RELS:
return _RELS[owner_repo]
import urllib.request
tok = None
try:
tok = open("/srv/cc-ci/.github-token").read().strip()
except OSError:
pass
h = {"User-Agent": "audit", "Accept": "application/vnd.github+json"}
if tok:
h["Authorization"] = f"Bearer {tok}"
out, url, pages = [], f"https://api.github.com/repos/{owner_repo}/releases?per_page=100", 0
while url and pages < 4:
req = urllib.request.Request(url, headers=h)
with urllib.request.urlopen(req, timeout=45) as r:
rows = json.load(r)
link = r.headers.get("Link", "") or ""
out += [(x.get("tag_name") or "", (x.get("body") or "") + " " + (x.get("name") or ""))
for x in rows]
url = None
for part in link.split(","):
if 'rel="next"' in part:
url = part.split(";")[0].strip().strip("<>")
pages += 1
_RELS[owner_repo] = out
return out
def audit(recipe, vf, vt, images=None, label=""):
rep = A.scan(recipe, vf, vt, REG, images)
print(f"\n{'='*78}\n{recipe} {vf} → {vt} {label}\n{'='*78}")
print(f"scanner count = {rep['cve_count_fixed']} known={rep['count_known']} "
f"failed_sources={rep['sources_failed']}")
counted = set(rep["fixed_by_this_upgrade"])
by_src = {}
for cve, e in rep["cves"].items():
by_src.setdefault(e["sources"][0], []).append((cve, e))
windows = rep["windows"]
total_mismatch = 0
for src, win in windows.items():
f, t = win["from"], win["to"]
method = rep["classified_by"][src]
rows = by_src.get(src, [])
scanner_here = {c for c, e in rows if c in counted}
print(f"\n ── {src} ({f} → {t}) method={method} advisories={len(rows)}")
if "publish date" in method:
dw = rep["date_window"][src]
indep = {c for c, e in rows
if e.get("published_at") and dw["from"] < e["published_at"] <= dw["to"]}
print(f" date window {dw['from'][:10]} → {dw['to'][:10]}")
else:
indep = {c for c, e in rows if in_window(f, t, e.get("patched"))}
# Independently redo the release-note method: fetch the repo's releases ourselves and
# confirm a tag NAMING the CVE really does fall inside (f, t].
kf, kt = sv(f), sv(t)
owner_repo = src.split(":", 1)[1]
rels = fetch_releases(owner_repo)
for c, e in rows:
if c in indep:
continue
naming = [tag for tag, body in rels if c in body]
if any(kf < sv(tag) <= kt for tag in naming if sv(tag)):
indep.add(c)
missed = indep - scanner_here
extra = scanner_here - indep
print(f" scanner counted {len(scanner_here)} | independent {len(indep)}"
f" | missed_by_scanner {len(missed)} | over_counted {len(extra)}")
if missed:
print(f" !! MISSED: {sorted(missed)}")
for c in sorted(missed):
print(f" {c} patched={dict(rows)[c].get('patched')!r}")
if extra:
print(f" !! OVER-COUNTED: {sorted(extra)}")
for c in sorted(extra):
print(f" {c} patched={dict(rows)[c].get('patched')!r}")
total_mismatch += len(missed) + len(extra)
# Anything counted that belongs to NO window would be a leak.
leaked = {c for c in counted if not any(s in rep["cves"][c]["sources"] for s in windows)}
if leaked:
print(f"\n !! COUNTED BUT OUTSIDE EVERY WINDOW: {sorted(leaked)}")
total_mismatch += len(leaked)
# Unclassified entries that belong to a WINDOWED source would mean a judged CVE was dropped.
dropped = [c for c in rep["unclassified"]
if any(s in rep["cves"][c]["sources"] for s in windows)]
if dropped:
print(f"\n !! UNCLASSIFIED DESPITE HAVING A WINDOW: {sorted(dropped)[:10]}")
total_mismatch += len(dropped)
unwindowed = {}
for cve in rep["unclassified"]:
unwindowed.setdefault(rep["cves"][cve]["sources"][0], []).append(cve)
if unwindowed:
print("\n unclassified by source (expected: images with no --image given):")
for s, cs in sorted(unwindowed.items()):
print(f" {len(cs):4d} {s}")
print(f"\n VERDICT: {'CLEAN' if total_mismatch == 0 else f'{total_mismatch} DISAGREEMENTS'}")
return total_mismatch, rep
if __name__ == "__main__":
bad = 0
bad += audit("gitea", "1.27.0", "1.27.1")[0]
bad += audit("discourse", "3.5.3", "2026.7.1")[0]
bad += audit("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")], "+redis sidecar")[0]
bad += audit("keycloak", "26.7.0", "26.7.1")[0]
bad += audit("mailu", "2024.06.55", "2024.06.57", [("redis", "8.8.0", "8.10.0")], "+redis")[0]
bad += audit("n8n", "1.123.0", "2.18.1")[0]
print(f"\n\n{'#'*78}\nOVERALL: {'CLEAN — no disagreements' if bad == 0 else f'{bad} DISAGREEMENTS'}")
sys.exit(1 if bad else 0)
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/audit-advisory-scan.py
-311
View File
@@ -1,311 +0,0 @@
#!/usr/bin/env python3
"""audit-sources — are we still looking in the right place for each recipe's updates?
A recipe tracks an image repo and a set of registry URLs. Upstreams move: they rename the image,
switch registry, archive the GitHub repo, or split a community edition out of the original. When that
happens nothing errors — the old repo simply stops receiving tags, and the recipe looks "up to date"
forever while real releases happen somewhere else.
plausible is the worked example. It tracked `plausible/analytics` on Docker Hub; upstream moved to
`ghcr.io/plausible/community-edition`. The old repo still exists and still serves v2.0.0, so every
survey said "no upgrades available" while v3 shipped elsewhere.
This reports the signals that catch that, per image and per registry URL:
* IMAGE GONE QUIET — newest tag is older than --quiet-days (default 365). The single strongest
signal that releases moved somewhere else.
* DEPRECATION WORDING — the registry description says deprecated / moved / no longer maintained.
* GITHUB REPO ARCHIVED — upstream archived it.
* GITHUB REPO RENAMED — the API redirects to a different owner/name than we ask for.
* GITHUB REPO GONE — 404.
Everything is a SIGNAL, not a verdict: a genuinely stable image (mumble, custom-html) can be quiet
for good reason. The output is for a human to judge, so each finding says what was measured.
audit-sources.py [recipe ...] [--ssh HOST] [--quiet-days N] [--json]
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import os
import re
import sys
import urllib.error
import urllib.request
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
_spec = importlib.util.spec_from_file_location("resolve_images", os.path.join(HERE, "resolve-images.py"))
RI = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(RI)
# advisory-scan supplies the source-fetching + changelog-attribution used by --security-sources
_aspec = importlib.util.spec_from_file_location("advisory_scan", os.path.join(HERE, "advisory-scan.py"))
A = importlib.util.module_from_spec(_aspec)
_aspec.loader.exec_module(A)
REGISTRY_DIR = os.environ.get("CCCI_UPSTREAM_REGISTRY", os.path.join(HERE, "upstream"))
USED_RECIPES = os.path.join(HERE, "used-recipes.md")
DEPRECATION_RE = re.compile(
r"\b(deprecat|no longer maintain|unmaintained|superseded|moved to|migrated to|"
r"has moved|discontinued|end.of.life|archived)\b", re.I)
def _days_since(iso: str | None) -> int | None:
if not iso:
return None
try:
d = datetime.fromisoformat(iso.replace("Z", "+00:00"))
except ValueError:
return None
return (datetime.now(timezone.utc) - d).days
def hub_repo_meta(repo: str) -> dict:
"""Docker Hub repo metadata: when it was last pushed to, and how it describes itself."""
try:
d = RI._json(f"https://hub.docker.com/v2/repositories/{repo}", RI._hub_auth())
except urllib.error.HTTPError as e:
return {"status": f"HTTP {e.code}"}
except Exception as e: # noqa: BLE001
return {"status": f"{type(e).__name__}"}
text = f"{d.get('description') or ''}\n{d.get('full_description') or ''}"
m = DEPRECATION_RE.search(text)
return {"status": "ok", "last_updated": d.get("last_updated"),
"deprecation_hint": (m.group(0) if m else None),
"archived": bool(d.get("is_archived") or d.get("status") == "inactive")}
def github_repo_meta(owner: str, repo: str) -> dict:
"""GitHub repo state — archived, renamed (the API answers with the CURRENT full_name), or gone."""
hdrs = {"Accept": "application/vnd.github+json"}
tok = RI._gh_token()
if tok:
hdrs["Authorization"] = f"Bearer {tok}"
try:
d = RI._json(f"https://api.github.com/repos/{owner}/{repo}", hdrs)
except urllib.error.HTTPError as e:
return {"status": f"HTTP {e.code}"}
except Exception as e: # noqa: BLE001
return {"status": f"{type(e).__name__}"}
asked, got = f"{owner}/{repo}".lower(), (d.get("full_name") or "").lower()
return {"status": "ok", "archived": bool(d.get("archived")), "pushed_at": d.get("pushed_at"),
"renamed_to": (d.get("full_name") if got and got != asked else None),
"description": d.get("description") or ""}
def newest_tag_date(registry: str, repo: str, tag: str) -> str | None:
"""When was the repo's newest same-shape tag pushed? Docker Hub only (it dates its tags)."""
if registry not in ("docker.io", "registry-1.docker.io"):
return None
try:
d = RI._json(f"https://hub.docker.com/v2/repositories/{repo}/tags"
f"?page_size=100&ordering=last_updated", RI._hub_auth())
except Exception: # noqa: BLE001
return None
want = RI.shape(tag)
for row in d.get("results", []):
if RI.shape(row.get("name") or "") == want:
return row.get("last_updated")
return (d.get("results") or [{}])[0].get("last_updated")
def security_source_audit(recipe: str) -> list[dict]:
"""Per source: are its CVEs USABLE, or merely visible?
The nginx lesson. nginx publishes no GitHub advisories; all its CVEs live in nginx.org/en/CHANGES.
The scan saw them and could do nothing with them, because nothing said which release fixed which
CVE — so every nginx bump in the fleet reported 0. Attribution (advisory-scan §2b) fixed that for
changelogs organised by release, but a page that lists CVEs with NO release structure is still a
blind spot: visible, uncountable. This finds those.
Per source: `advisory-feed` (structured, best), `changelog` (CVEs attributable to a release),
`unattributable` (CVEs present but no release structure — BLIND), or `no-cve-data`.
"""
urls, _ = _registry_urls(recipe)
out = []
# NVD CPE entries are a first-class source: for projects publishing nothing machine-readable
# (mattermost, mumble) they are the ONLY structured source, and omitting them here made two
# recipes look permanently blind after they had been fixed.
for key, cpe in A.registry_cpes(recipe, REGISTRY_DIR):
e = A.nvd_advisories(cpe, key)
n = len(e.get("advisories") or [])
out.append({"source": e["source"] + f" ({cpe.split(':')[4]}/{cpe.split(':')[3]})",
"kind": "advisory-feed", "verified_empty": n == 0,
"status": e["status"], "cves": n, "usable": n})
for entry in A.github_advisories(urls):
out.append({"source": entry["source"], "kind": "advisory-feed",
"status": entry["status"], "cves": len(entry.get("advisories") or []),
"usable": len(entry.get("advisories") or [])})
for entry in A.vendor_pages(urls):
if entry["status"].startswith("skipped"):
continue
n = len(entry.get("cves") or [])
attributed = len(entry.get("fixed_in") or {})
kind = ("no-cve-data" if n == 0 else
"changelog" if attributed else "unattributable")
out.append({"source": entry["source"], "kind": kind, "status": entry["status"],
"cves": n, "usable": attributed})
return out
def audit_recipe(recipe: str, ssh: str | None, quiet_days: int) -> dict:
out = {"recipe": recipe, "findings": [], "images": [], "sources": []}
try:
refs = (RI.compose_images_ssh(recipe, ssh, "~/.abra/recipes") if ssh
else RI.compose_images(recipe, RI.RECIPE_DIR))
except Exception as e: # noqa: BLE001
out["findings"].append({"level": "error", "what": f"could not read compose: {e}"})
return out
for ref in refs:
if "${" in ref:
continue
info = RI.parse_ref(ref)
row = {"ref": ref, "registry": info["registry"], "repo": info["repo"], "tag": info["tag"]}
if info["registry"] in ("docker.io", "registry-1.docker.io"):
meta = hub_repo_meta(info["repo"])
row.update(meta)
newest = newest_tag_date(info["registry"], info["repo"], info["tag"])
row["newest_tag_pushed"] = newest
age = _days_since(newest)
row["newest_tag_age_days"] = age
if age is not None and age > quiet_days:
out["findings"].append({
"level": "warn", "what": "image has gone quiet",
"detail": f"{info['repo']}: newest {RI.shape(info['tag'])}-shaped tag pushed "
f"{age} days ago — releases may have moved elsewhere"})
if meta.get("deprecation_hint"):
out["findings"].append({
"level": "warn", "what": "registry text suggests deprecation",
"detail": f"{info['repo']}: says {meta['deprecation_hint']!r}"})
if meta.get("archived"):
out["findings"].append({"level": "warn", "what": "registry repo archived/inactive",
"detail": info["repo"]})
out["images"].append(row)
urls, reg_path = ([], None)
try:
urls, reg_path = _registry_urls(recipe)
except Exception: # noqa: BLE001
pass
if reg_path is None:
out["findings"].append({"level": "warn", "what": "no upstream registry file",
"detail": f"cc-ci-plan/upstream/{recipe}.md is missing — the advisory "
f"scan has nowhere to look"})
seen = set()
for u in urls:
m = re.match(r"https?://github\.com/([^/]+)/([^/#?]+)", u)
if not m:
continue
owner, repo = m.group(1), m.group(2).removesuffix(".git")
if (owner, repo) in seen:
continue
seen.add((owner, repo))
meta = github_repo_meta(owner, repo)
row = {"repo": f"{owner}/{repo}", **meta}
age = _days_since(meta.get("pushed_at"))
row["pushed_age_days"] = age
out["sources"].append(row)
if meta.get("status") != "ok":
out["findings"].append({"level": "warn", "what": "registry source unreachable",
"detail": f"{owner}/{repo}: {meta['status']}"})
continue
if meta.get("renamed_to"):
out["findings"].append({"level": "alert", "what": "GitHub repo has MOVED",
"detail": f"{owner}/{repo} now answers as {meta['renamed_to']}"})
if meta.get("archived"):
out["findings"].append({"level": "alert", "what": "GitHub repo is ARCHIVED",
"detail": f"{owner}/{repo} — upstream development has stopped here"})
if age is not None and age > quiet_days:
out["findings"].append({"level": "warn", "what": "GitHub repo quiet",
"detail": f"{owner}/{repo}: last push {age} days ago"})
return out
def _registry_urls(recipe: str):
return A.registry_urls(recipe, REGISTRY_DIR)
def all_recipes() -> list[str]:
out = []
for ln in open(USED_RECIPES):
ln = ln.strip()
if not ln or ln.startswith("#") or ln.startswith("`"):
continue
parts = ln.split()
if len(parts) >= 2 and parts[1] in ("weekly", "external"):
out.append(parts[0])
return out
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("recipes", nargs="*")
ap.add_argument("--ssh", default=None)
ap.add_argument("--quiet-days", type=int, default=365)
ap.add_argument("--json", action="store_true")
ap.add_argument("--security-sources", action="store_true",
help="audit whether each recipe's CVE sources are USABLE (structured advisory "
"feed / release-attributable changelog) or merely visible")
a = ap.parse_args()
recipes = a.recipes or all_recipes()
if a.security_sources:
# What matters is whether the RECIPE can see CVEs at all — not whether some individual page
# is unparseable. A page with no release structure is harmless when the same project also
# publishes an advisory feed (redis, gitea, minio, clickhouse all do); it is only a blind
# spot when nothing else covers that project.
blind_recipes, noisy = [], 0
for r in recipes:
rows = security_source_audit(r)
feeds = [x for x in rows if x["kind"] == "advisory-feed"
and (x["cves"] > 0 or x.get("verified_empty"))
and x["status"] == "ok"]
logs = [x for x in rows if x["kind"] == "changelog" and x["status"] == "ok"]
unattr = [x for x in rows if x["kind"] == "unattributable"]
failed = [x for x in rows if x["status"].startswith("error:")]
noisy += len(unattr)
usable = len(feeds) + len(logs)
if usable == 0:
blind_recipes.append(r)
print(f"!! {r}: NO VERIFIED CVE SOURCE — {len(unattr)} unparseable page(s), "
f"0 populated advisory feeds, 0 attributable changelogs, {len(failed)} failed source(s)")
for x in rows:
unit = "advisories" if x["kind"] == "advisory-feed" else "CVE IDs"
print(f" {x['kind']:15} {x['source'][:64]} ({x['cves']} {unit}; {x['status']})")
else:
print(f"OK {r}: {len(feeds)} advisory-feed(s), {len(logs)} changelog(s)"
+ (f", {len(unattr)} unparseable page(s)" if unattr else "")
+ (f", {len(failed)} failed source(s) — counts incomplete" if failed else ""))
for x in logs:
print(f" changelog {x['source'][:62]} ({x['usable']}/{x['cves']})")
for x in failed:
print(f" FAILED {x['source'][:90]} ({x['status']})")
print(f"\n{len(recipes)} recipes · {len(blind_recipes)} with NO usable CVE source"
+ (f": {', '.join(blind_recipes)}" if blind_recipes else "")
+ f" · {noisy} unparseable page(s) elsewhere (harmless where a feed covers them)")
return 0
reports = [audit_recipe(r, a.ssh, a.quiet_days) for r in recipes]
if a.json:
print(json.dumps(reports, indent=2))
return 0
alerts = 0
for rep in reports:
fs = rep["findings"]
mark = "OK " if not fs else ("!! " if any(f["level"] == "alert" for f in fs) else " ? ")
print(f"{mark} {rep['recipe']}")
for f in fs:
alerts += f["level"] == "alert"
print(f" [{f['level']}] {f['what']}: {f.get('detail','')}")
print(f"\n{len(reports)} recipes audited · "
f"{sum(len(r['findings']) for r in reports)} findings · {alerts} alerts")
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/audit-sources.py
-159
View File
@@ -1,159 +0,0 @@
#!/usr/bin/env python3
"""
cc-ci assistant launcher — start/resume the assistant session in tmux.
The assistant is a long-lived helper session that shares the orchestrator's access and can work
through assigned plans autonomously, but it is NOT part of the Builder/Adversary loop pair.
Usage:
launch-assistant.py start resume the persistent session (default)
launch-assistant.py fresh start a NEW session
launch-assistant.py stop kill the tmux session
launch-assistant.py status show session state
launch-assistant.py attach tmux attach to the session
Env:
LOOP_BACKEND claude (default) | opencode
LOOP_MODEL model flag, e.g. "sonnet" or "tinfoil/deepseek-v4-pro"
ASSISTANT_SESSION tmux / remote-control session name
ASSISTANT_DIR cwd for the assistant
ASSISTANT_STARTUP_PROMPT startup nudge / assignment
"""
import os, sys, subprocess, time
from datetime import datetime
from pathlib import Path
SESSION = os.environ.get("ASSISTANT_SESSION", "cc-ci-assistant")
WORKDIR = os.environ.get("ASSISTANT_DIR", "/srv/cc-ci-orch")
LOG_DIR = os.environ.get("LOG_DIR", "/srv/cc-ci/.cc-ci-logs")
BACKEND = os.environ.get("LOOP_BACKEND", "claude")
LOOP_MODEL = os.environ.get("LOOP_MODEL", "")
CLAUDE_BIN = os.environ.get("CLAUDE_BIN", "claude")
CLAUDE_FLAGS = os.environ.get("CLAUDE_FLAGS", "--dangerously-skip-permissions")
REMOTE_CONTROL = os.environ.get("REMOTE_CONTROL", "1") == "1"
DEFAULT_ID = "9db267a4-9b9e-4818-8197-0a42dba443ea"
ID_FILE = os.environ.get("ASSISTANT_ID_FILE", f"{LOG_DIR}/.assistant-session-id")
STARTUP_PROMPT = os.environ.get("ASSISTANT_STARTUP_PROMPT", (
"You are the cc-ci ASSISTANT. Read cc-ci-plan/JOURNAL.md for context, then wait for a "
"specific plan/task from the orchestrator or operator. Work autonomously until the assigned "
"task is complete, report the result, and then wait for the next assignment."
))
OPENCODE_BIN = os.environ.get("OPENCODE_BIN", "/home/loops/.local/bin/opencode")
OPENCODE_SERVER = os.environ.get("OPENCODE_SERVER", "http://127.0.0.1:4096")
def log(msg):
ts = datetime.now().strftime("%H:%M:%S")
print(f"[assistant {ts}] {msg}", flush=True)
def die(msg):
log(f"ERROR: {msg}")
sys.exit(1)
def session_alive():
return subprocess.run(["tmux", "has-session", "-t", SESSION], capture_output=True).returncode == 0
def _ping(session, msg):
subprocess.run(["tmux", "send-keys", "-t", session, "-l", "--", msg], capture_output=True)
time.sleep(0.5)
submit_key = "C-m" if BACKEND == "opencode" else "Enter"
for _ in range(10):
subprocess.run(["tmux", "send-keys", "-t", session, submit_key], capture_output=True)
time.sleep(1)
r = subprocess.run(["tmux", "capture-pane", "-pt", session], capture_output=True, text=True)
if msg[:28] not in r.stdout:
return
def resume_id():
sid = os.environ.get("ASSISTANT_SESSION_ID")
if sid:
return sid
try:
v = Path(ID_FILE).read_text().strip()
return v or DEFAULT_ID
except FileNotFoundError:
return DEFAULT_ID
def start(mode="resume"):
import shutil
if not shutil.which("tmux"):
die("tmux not found")
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
if session_alive():
log(f"{SESSION} already running — leaving it (use 'stop' first to relaunch)")
return
model_flag = f"--model '{LOOP_MODEL}'" if LOOP_MODEL else ""
if BACKEND == "claude":
if not shutil.which(CLAUDE_BIN):
die(f"claude CLI not found — set CLAUDE_BIN (currently: {CLAUDE_BIN})")
if not Path(ID_FILE).exists():
Path(ID_FILE).write_text(DEFAULT_ID)
rc = f"--remote-control '{SESSION}'" if REMOTE_CONTROL else ""
resume = f"--resume '{resume_id()}'" if mode == "resume" else ""
prompt = f"'{STARTUP_PROMPT}'" if STARTUP_PROMPT else ""
cmd = f"{CLAUDE_BIN} {resume} {rc} {model_flag} {CLAUDE_FLAGS} {prompt}"
detail = f"resume={resume_id()}" if mode == "resume" else "fresh"
log(f"starting {SESSION} (backend=claude, {detail}, model={LOOP_MODEL or 'default'})")
elif BACKEND == "opencode":
if not Path(OPENCODE_BIN).exists():
die(f"opencode not found at {OPENCODE_BIN}")
cmd = (
f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; "
f"NO_COLOR=1 {OPENCODE_BIN} attach {OPENCODE_SERVER} --dir {WORKDIR}"
)
log(f"starting {SESSION} (backend=opencode, model={LOOP_MODEL or 'default'})")
log(" visible at https://oc.ci.commoninternet.net")
else:
die(f"unknown LOOP_BACKEND '{BACKEND}' — use 'claude' or 'opencode'")
subprocess.run(["tmux", "new-session", "-d", "-s", SESSION, "-c", WORKDIR, cmd])
subprocess.run(["tmux", "pipe-pane", "-o", "-t", SESSION, f"cat >> '{LOG_DIR}/{SESSION}.log'"])
log(f"started. attach: tmux attach -t {SESSION}")
if BACKEND == "opencode":
time.sleep(8)
_ping(SESSION, STARTUP_PROMPT)
def main():
cmd = sys.argv[1] if len(sys.argv) > 1 else "start"
if cmd == "start":
start("resume")
elif cmd == "fresh":
start("fresh")
elif cmd == "stop":
if session_alive():
log(f"killing {SESSION}")
subprocess.run(["tmux", "kill-session", "-t", SESSION])
else:
log(f"{SESSION} not running")
elif cmd == "status":
state = "RUNNING" if session_alive() else "stopped"
log(f"{SESSION}: {state}")
subprocess.run(f"ps -eo pid,etime,args | grep '[r]emote-control {SESSION}' || true", shell=True)
if BACKEND == "claude":
log(f"resume id: {resume_id()} (file: {ID_FILE})")
log(f"backend: {BACKEND} model: {LOOP_MODEL or '<default>'}")
elif cmd == "attach":
os.execvp("tmux", ["tmux", "attach", "-t", SESSION])
else:
print("usage: launch-assistant.py start|fresh|stop|status|attach")
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/launch-assistant.py
-174
View File
@@ -1,174 +0,0 @@
#!/usr/bin/env python3
"""cc-ci recipe-report launcher — one-shot agent that runs /recipe-report after the weekly upgrade.
The report agent's model is configured SEPARATELY from the upgrader (REPORT_BACKEND/REPORT_MODEL),
but defaults to the same OpenCode subscription as the upgrader (now OpenCode GO — the only tier
with a key on this host; ZEN models are dead here, see launch-upgrader.py). The model default tracks
the backend+tier (opencode+go→opencode-go/deepseek-v4.1-flash, opencode+zen→opencode/glm-5.2,
claude→opus). The report runs on DeepSeek while the upgrader/supervisor stay on GLM-5.3-Flash.
Usage:
launch-report.py start [DATE] use-or-create the session; runs /recipe-report [DATE]
launch-report.py fresh [DATE] always start a new session
launch-report.py stop kill the session
launch-report.py status show session state
Env: REPORT_BACKEND (default opencode), REPORT_MODEL (default tracks tier),
LOOP_TIER / REPORT_TIER (default 'go' — the only tier with a key on this host; ZEN
models are dead here; 'go' or 'zen'; only for opencode),
OPENCODE_SHARE (1=attach web server + public --share link), REPORT_SESSION, REPORT_DIR.
"""
import os, subprocess, sys, time
from pathlib import Path
from datetime import datetime, timezone
SESSION = os.environ.get("REPORT_SESSION", "cc-ci-report")
WORKDIR = os.environ.get("REPORT_DIR", "/srv/cc-ci")
LOG_DIR = os.environ.get("LOG_DIR", "/srv/cc-ci/.cc-ci-logs")
BACKEND = os.environ.get("REPORT_BACKEND", "opencode")
TIER = os.environ.get("LOOP_TIER", os.environ.get("REPORT_TIER", "go"))
_TIER_MODEL = {"go": "opencode-go/deepseek-v4.1-flash", "zen": "opencode/glm-5.2"}
_DEFAULT_MODEL = _TIER_MODEL.get(TIER, _TIER_MODEL["go"]) if BACKEND == "opencode" else "opus"
MODEL = os.environ.get("REPORT_MODEL", _DEFAULT_MODEL)
CLAUDE_BIN = os.environ.get("CLAUDE_BIN", "claude")
CLAUDE_FLAGS = os.environ.get("CLAUDE_FLAGS", "--dangerously-skip-permissions")
OPENCODE_BIN = os.environ.get("OPENCODE_BIN", "/home/loops/.local/bin/opencode")
OPENCODE_SERVER = os.environ.get("OPENCODE_SERVER", "http://127.0.0.1:4096")
OPENCODE_SHARE = os.environ.get("OPENCODE_SHARE", "1") == "1"
def log(m): print(f"[report {datetime.now(timezone.utc):%H:%M:%S}] {m}", flush=True)
def die(m): log(f"ERROR: {m}"); sys.exit(1)
def _sh(c): return subprocess.run(c, capture_output=True, text=True)
def session_alive(): return _sh(["tmux", "has-session", "-t", SESSION]).returncode == 0
def kill_session(): subprocess.run(["tmux", "kill-session", "-t", SESSION], capture_output=True)
def _busy(): return "esc to interrupt" in _sh(["tmux", "capture-pane", "-pt", SESSION]).stdout
def build_kickoff(date):
arg = f" {date}" if date else ""
return (
f"*** cc-ci RECIPE-REPORT — one-shot ***\n"
f"You generate the public weekly \"Recipe Report\". Run the /recipe-report skill now:\n"
f" invoke /recipe-report{arg}\n"
f"Full spec: {WORKDIR}/.claude/skills/recipe-report/SKILL.md. Creds in {WORKDIR}/.testenv; "
f"reach the CI server with `ssh cc-ci`.\n"
f"You are READ-ONLY: review the latest /upgrade-all run + every recipe's open PRs + CI verdicts, "
f"order the wire table by priority-to-address (CVE recipes first), and publish one HTML page per "
f"run to report.ci.commoninternet.net (+ regenerate the index). Public page — NO secrets/tokens/raw logs. "
f"Never merge/edit/comment on PRs. When done, print the report URL + 'RECIPE REPORT COMPLETE' and "
f"go idle (do NOT loop)."
)
def start(mode, date):
import shutil
if not shutil.which("tmux"):
die("tmux not found")
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
if session_alive():
# The report is a one-shot. Leave the session ONLY if it's actively producing a report;
# an idle/leftover session (e.g. last week's, gone idle) is killed so a new run starts.
if mode == "use-or-create" and _busy():
log(f"{SESSION} busy with a report — leaving it"); return
log(f"{SESSION} exists (idle/leftover) — killing first"); kill_session(); time.sleep(1)
# Unique-name invariant (same as upgrader/supervisor): archive-rename every older session
# titled SESSION so the one this launch creates is the ONLY 'cc-ci-report' in the web UI.
# Archived names start with 'archive-' (operator convention 2026-08-04).
#
# AND clear the stale session PIN. The pin file is what the shared watchdog resolves via
# lu._session_id(); if a PREVIOUS run's pin survives, the watchdog inspects that old (already
# DONE_MARKER-bearing) session, declares "run completed" and exits within one poll — leaving
# the new run unwatched. That regression silently un-watchdogged the 2026-08-07 finish-run's
# report step (pin dated 2026-08-04). The pin is re-established after launch, below.
_lu = None
_prev_ids = set()
try:
os.environ["UPGRADER_SESSION"] = SESSION # scope the shared helpers to THIS session name
import importlib.util as _ilu
_spec = _ilu.spec_from_file_location(
"launch_upgrader", os.path.join(os.path.dirname(os.path.realpath(__file__)), "launch-upgrader.py"))
_lu = _ilu.module_from_spec(_spec); _spec.loader.exec_module(_lu)
_lu._archive_stale_titles(SESSION)
_rows = _lu._server_get("/session") or []
_rows = _rows if isinstance(_rows, list) else _rows.get("data", [])
_prev_ids = {s.get("id") for s in _rows}
try:
_lu.STATE_SID_FILE.unlink()
except OSError:
pass
except Exception as e:
log(f" (archive-rename/pin-clear skipped: {e})")
kf = Path(LOG_DIR) / f".kickoff-{SESSION}.txt"
kf.write_text(build_kickoff(date))
model_flag = f"--model '{MODEL}'" if MODEL else ""
if BACKEND == "claude":
cmd = f"{CLAUDE_BIN} --remote-control '{SESSION}' {model_flag} {CLAUDE_FLAGS} \"$(cat '{kf}')\""
cwd = WORKDIR
elif BACKEND == "opencode":
# -m/--model/--attach/--title/--share are `run` SUBCOMMAND flags — must come AFTER `run`.
cwd = "/srv/cc-ci-orch/cc-ci"
share_flag = "--share" if OPENCODE_SHARE else ""
cmd = (
f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; "
f"{OPENCODE_BIN} run {model_flag} {share_flag} --attach '{OPENCODE_SERVER}' "
f"--title '{SESSION}' --dir {cwd} \"$(cat '{kf}')\""
)
else:
die(f"unknown REPORT_BACKEND '{BACKEND}'")
log(f"starting {SESSION} (backend={BACKEND}, tier={TIER}, model={MODEL}, date={date or 'today'})")
subprocess.run(["tmux", "new-session", "-d", "-s", SESSION, "-c", cwd, cmd])
subprocess.run(["tmux", "pipe-pane", "-o", "-t", SESSION, f"cat >> '{LOG_DIR}/{SESSION}.log'"])
if BACKEND == "opencode" and _lu is not None:
# Re-establish the pin on THIS run's session, so the watchdog (spawned below) resolves the
# new session rather than falling back to a title lookup or a stale pin.
_lu._pin_new_session(_prev_ids)
if BACKEND == "opencode":
if OPENCODE_SHARE:
log(f" attached to {OPENCODE_SERVER} → https://oc.ci.commoninternet.net +public --share link")
# Watchdog for the report too: it runs on deepseek-v4.1-flash sharing the same opencode-go budget the
# upgrade run just drained, so a 429 stall is likely. Reuse launch-upgrader.py's watchdog,
# pointed at THIS (cc-ci-report) session with a report-specific marker + resume prompt. It
# runs under the tmux server (survives the systemd oneshot like the run sessions).
if os.environ.get("REPORT_WATCHDOG", "1") == "1":
import shlex
LU = "/srv/cc-ci/cc-ci-plan/launch-upgrader.py"
rf = Path(LOG_DIR) / f".kickoff-{SESSION}-resume.txt"
rf.write_text(
"The opencode usage limit has reset (or the report stalled). CONTINUE generating and "
"publishing this week's public Recipe Report per /recipe-report: survey → write the spec "
"JSON → render with recipe-report.py → publish. Do NOT hand-write HTML (render() owns all "
"formatting). When the page is live, print 'RECIPE REPORT COMPLETE' and go idle.")
wenv = {"HOME": os.environ.get("HOME") or "/home/loops",
"UPGRADER_SESSION": SESSION, "UPGRADER_DIR": cwd, "LOG_DIR": LOG_DIR,
"UPGRADER_BACKEND": "opencode", "UPGRADER_MODEL": MODEL, "LOOP_TIER": TIER,
"OPENCODE_BIN": OPENCODE_BIN, "OPENCODE_SERVER": OPENCODE_SERVER,
"OPENCODE_SHARE": "1" if OPENCODE_SHARE else "0",
"UPGRADER_DONE_MARKER": "RECIPE REPORT COMPLETE",
"UPGRADER_RESUME_FILE": str(rf)}
envstr = " ".join(f"{k}={shlex.quote(str(v))}" for k, v in wenv.items())
wlog = f"{LOG_DIR}/{SESSION}-watchdog.log"
wcmd = f"env {envstr} python3 {shlex.quote(LU)} watchdog >> {shlex.quote(wlog)} 2>&1"
subprocess.run(["tmux", "kill-session", "-t", f"{SESSION}-watchdog"], capture_output=True)
subprocess.run(["tmux", "new-session", "-d", "-s", f"{SESSION}-watchdog", "-c", cwd, wcmd])
log(f" report watchdog spawned in tmux '{SESSION}-watchdog' — auto-resume on usage-limit stalls")
log(f"started. attach: tmux attach -t {SESSION}")
def main():
a = sys.argv[1:]
cmd = a[0] if a else "start"
date = a[1] if len(a) > 1 else ""
if cmd == "start": start("use-or-create", date)
elif cmd == "fresh": start("fresh", date)
elif cmd == "stop": kill_session(); log("stopped.")
elif cmd == "status":
log(f"{SESSION}: {'RUNNING' if session_alive() else 'stopped'} (backend={BACKEND} model={MODEL})")
else:
print(__doc__); sys.exit(2)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/launch-report.py
-198
View File
@@ -1,198 +0,0 @@
#!/usr/bin/env python3
"""
cc-ci weekly-run SUPERVISOR — hourly deepseek-v4.1-flash orchestrator wake-up.
Fired hourly by a systemd timer. It is a CHEAP deterministic GATE first: if this week's
/upgrade-all run is already complete, or is actively progressing, it does NOTHING and spends
ZERO model tokens. Only when the run has STALLED or died before completing — e.g. the host
disk-full crash on 2026-07-03 that the log-idle/429 watchdog does NOT cover — does it launch a
short-lived deepseek-v4.1-flash opencode agent that DIAGNOSES the blockage (disk, wedged deploy, dead
session, a stuck recipe) and DRIVES the run to completion (resume the upgrader, ensure the
summary + public report land). One-shot per fire; the next hour re-checks and no-ops if healthy.
This is the intelligent complement to launch-upgrader.py's watchdog: the watchdog only handles
opencode-go usage-limit (429) stalls (wait-out + `--continue`); the supervisor handles everything
else that can wedge a weekly run, using a real model instead of a fixed heuristic.
Usage:
launch-supervisor.py [check] default — the timer entrypoint (gate; may spawn the agent)
launch-supervisor.py force skip the gate; always launch the supervisor agent
launch-supervisor.py status show what the gate currently sees
launch-supervisor.py stop kill the supervisor agent session
"""
import os, re, sys, time, subprocess, importlib.util
from datetime import datetime
from pathlib import Path
# ── reuse launch-upgrader's server/session/completion helpers (single source of truth) ──────────
_HERE = os.path.dirname(os.path.realpath(__file__))
os.environ.setdefault("UPGRADER_SESSION", "cc-ci-upgrader") # the run we supervise
_spec = importlib.util.spec_from_file_location("launch_upgrader", os.path.join(_HERE, "launch-upgrader.py"))
lu = importlib.util.module_from_spec(_spec); _spec.loader.exec_module(lu)
# ── config ──────────────────────────────────────────────────────────────────────────────────────
SUP_SESSION = os.environ.get("SUPERVISOR_SESSION", "cc-ci-supervisor")
WORKDIR = os.environ.get("UPGRADER_DIR", "/srv/cc-ci")
LOG_DIR = os.environ.get("LOG_DIR", "/srv/cc-ci/.cc-ci-logs")
MODEL = os.environ.get("SUPERVISOR_MODEL", "opencode-go/deepseek-v4.1-flash")
OPENCODE_BIN = lu.OPENCODE_BIN
OPENCODE_SERVER = lu.OPENCODE_SERVER
OPENCODE_SHARE = os.environ.get("OPENCODE_SHARE", "1") == "1"
# Don't auto-resurrect a run whose session is older than this — a genuinely abandoned run should not
# be dragged back to life days later; the operator will look. Covers the Thu-night → weekend window.
WINDOW_HOURS = float(os.environ.get("SUPERVISOR_WINDOW_HOURS", "96"))
def log(m): print(f"[supervisor {datetime.now():%H:%M:%S}] {m}", flush=True)
def _sh(c): return subprocess.run(c, capture_output=True, text=True)
# ── gate helpers ────────────────────────────────────────────────────────────────────────────────
def _session_created_ms(sid):
rows = lu._server_get("/session") or []
rows = rows if isinstance(rows, list) else rows.get("data", [])
for s in rows:
if s.get("id") == sid:
return (s.get("time") or {}).get("created")
return None
def _sup_alive(): return _sh(["tmux", "has-session", "-t", SUP_SESSION]).returncode == 0
def _sup_busy():
r = _sh(["tmux", "capture-pane", "-pt", SUP_SESSION])
return bool(re.search(r"esc to interrupt|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏|Running tool", r.stdout)) if r.returncode == 0 else False
def _sup_kill(): _sh(["tmux", "kill-session", "-t", SUP_SESSION])
# ── the supervisor agent ─────────────────────────────────────────────────────────────────────────
def build_kickoff(sid, reason):
return f"""\
*** cc-ci WEEKLY-RUN SUPERVISOR — one-shot, deepseek-v4.1-flash ***
You are the hourly SUPERVISOR for the weekly cc-ci /upgrade-all run. A gate has determined the run
is INCOMPLETE and not currently progressing ({reason}). Your job: get this week's run to a clean
DONE — published report + summary — then STOP. You are NOT a perpetual loop.
Your cwd is {WORKDIR}; reach the CI server with `ssh cc-ci`; creds in {WORKDIR}/.testenv; skills in
{WORKDIR}/.claude/skills/. The stalled upgrader opencode session is {sid} (title "cc-ci-upgrader").
DO THIS, in order — stop as soon as the run is healthy again:
1. ENVIRONMENT FIRST. Check the CI server disk: `ssh cc-ci 'df -h / | tail -1'`. If root is > 85%
used, reclaim STALE images (unused AND older than a week, so this week's are kept):
`ssh cc-ci 'docker image prune -af --filter until=168h 2>&1 | tail -1; df -h / | tail -1'`.
Also glance for other infra wedges (a hung deploy, proxy VIP exhaustion — see upgrade-all §0).
2. ASSESS the run. Read the upgrader session's recent output (opencode server {OPENCODE_SERVER},
`GET /session/{sid}/message`) and the open recipe PRs to see which enrolled recipes already have
a PR this week and which remain. Do NOT redo any recipe that already has a PR.
3. DRIVE TO COMPLETION. Prefer to RESUME the existing run (context preserved) once the environment
is healthy: `python3 {WORKDIR}/cc-ci-plan/launch-upgrader.py resume`. Then CONFIRM it actually
restarted and is progressing (a fresh `opencode run … -s {sid} --continue` proc + the session
advancing). If the session is truly gone/unresumable, drive the remaining recipes yourself the
/upgrade-all way (per-recipe /recipe-upgrade DEFAULT-mode subagents, !testme verify), then make
sure the weekly summary is written to {WORKDIR}/.cc-ci-logs/upgrades/ and launch the public
report: `python3 {WORKDIR}/cc-ci-plan/launch-report.py fresh`.
4. If on inspection the run is actually FINE (progressing) or already COMPLETE, do NOTHING.
5. Print `SUPERVISOR DONE` and go idle. Do NOT loop.
GUARDRAILS: NEVER merge a PR. NEVER weaken a test. DEFAULT mode only. Single-writer on the shared
Swarm — don't pile concurrent deploys past DRONE_RUNNER_CAPACITY. Handing back to the resumed run
is preferred over doing the recipe work yourself — avoid two writers at once.
"""
def spawn_supervisor(sid, reason):
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
if _sup_alive():
_sup_kill(); time.sleep(1)
# Unique-name invariant (same as the upgrader): archive-rename every older session titled
# SUP_SESSION so the one this launch creates is the ONLY 'cc-ci-supervisor' in the web UI.
try:
lu._archive_stale_titles(SUP_SESSION)
except Exception:
pass
kf = Path(LOG_DIR) / f".kickoff-{SUP_SESSION}.txt"
kf.write_text(build_kickoff(sid, reason))
share = "--share" if OPENCODE_SHARE else ""
cmd = (f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; {OPENCODE_BIN} run --model '{MODEL}' {share} "
f"--attach '{OPENCODE_SERVER}' --title '{SUP_SESSION}' --dir {WORKDIR} \"$(cat '{kf}')\"")
_sh(["tmux", "new-session", "-d", "-s", SUP_SESSION, "-c", WORKDIR, cmd])
_sh(["tmux", "pipe-pane", "-o", "-t", SUP_SESSION, f"cat >> '{LOG_DIR}/{SUP_SESSION}.log'"])
log(f"launched deepseek-v4.1-flash supervisor (tmux '{SUP_SESSION}', model={MODEL}) — {reason}")
# ── gate ─────────────────────────────────────────────────────────────────────────────────────────
def _gate():
"""Return (should_spawn, sid, reason). Cheap — no model tokens."""
sid = lu._session_id()
if not sid:
return False, None, "no cc-ci-upgrader session exists — nothing to supervise"
if lu._completed():
return False, sid, "weekly run COMPLETE (DONE marker present) — nothing to do"
created = _session_created_ms(sid)
age_h = (time.time() * 1000 - created) / 3.6e6 if created else 0.0
# Belt-and-suspenders completion signal: the run wrote its weekly SUMMARY (Step 5 output) AFTER
# this session began. More reliable than the text marker — a run can finish the actual work +
# summary + report yet never print a clean sign-off (it may wedge afterwards, as on 2026-07-03).
# Without this the supervisor would try to "resume" an already-finished run every hour until the
# 96h window closes.
if created:
import glob
for f in glob.glob(os.path.join(WORKDIR, ".cc-ci-logs/upgrades/upgrade-all-*.md")):
try:
if os.path.getmtime(f) * 1000 > created:
return False, sid, f"weekly summary written ({os.path.basename(f)}) — run finished"
except OSError:
pass
if created and age_h > WINDOW_HOURS:
return False, sid, f"incomplete run is {age_h:.0f}h old (> {WINDOW_HOURS:.0f}h window) — not auto-resurrecting"
# "Progressing" for an opencode run is NOT session_busy() (its pane regex is claude-tuned and
# misreads a headless `opencode run` as idle). Trust the run PROCESS + the session log's mtime:
# a live `opencode run … -s <sid> --attach` proc, or a log touched within the stall window.
pids = lu._run_pids(sid)
idle = lu._session_idle_min()
advancing = idle is not None and idle < lu.STALL_MIN
# PROGRESS REQUIRES THE SESSION TO BE ADVANCING — a live proc alone is not enough. A run walled
# by the provider keeps its process alive and spinning while emitting nothing (2026-08-07: 3
# days, zero output). Treating "proc exists" as progress is what deadlocked the gate.
if advancing:
return False, sid, f"upgrader run progressing (session advanced {idle:.0f}m ago) — leaving it"
if pids and lu._billing_blocked():
# NEVER kill it: it may resume when the wall lifts, and its context is the run's state.
# Surface it loudly instead — this is an operator-actionable condition, not self-healing.
return False, sid, (
f"run BLOCKED on a provider billing/usage wall ({len(pids)} proc(s) alive, session idle "
f"{idle:.0f}m) — NOT killing (resumable once the wall lifts); operator action required"
)
if pids:
log(
f"note: {len(pids)} live run proc(s) but session idle {idle:.0f}m ≥ "
f"{lu.STALL_MIN:.0f}m — treating as stalled, not progressing"
)
# The per-run watchdog owns PROMPT recovery (resume on proc-death/stall) and is the single writer
# while it lives. Defer to it — it gives up (exits its tmux) only after MAX_RESUMES fail, i.e. the
# run is stuck in a way a bare resume can't fix (e.g. disk-full). THEN the supervisor takes over.
if lu._watchdog_alive():
return False, sid, "per-run watchdog alive — it owns recovery; supervisor stays back"
if _sup_alive() and _sup_busy():
return False, sid, "a supervisor agent is already working — skip"
idle_s = f"{idle:.0f}m" if idle is not None else "unknown"
return True, sid, f"run INCOMPLETE + not progressing (log idle {idle_s}, age {age_h:.0f}h)"
def check(force=False):
if force:
sid = lu._session_id()
spawn_supervisor(sid, "forced"); return
should, sid, reason = _gate()
log(reason)
if should:
spawn_supervisor(sid, reason)
# ── main ─────────────────────────────────────────────────────────────────────────────────────────
def main():
cmd = sys.argv[1] if len(sys.argv) > 1 else "check"
if cmd == "check": check()
elif cmd == "force": check(force=True)
elif cmd == "stop": _sup_kill(); log(f"{SUP_SESSION} stopped")
elif cmd == "status":
should, sid, reason = _gate()
log(f"gate: would {'SPAWN' if should else 'skip'} — {reason}")
log(f"supervisor session: {'RUNNING '+('(busy)' if _sup_busy() else '(idle)') if _sup_alive() else 'stopped'}")
log(f"model: {MODEL} window: {WINDOW_HOURS:.0f}h")
else:
print(__doc__); sys.exit(2)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/launch-supervisor.py
-667
View File
@@ -1,667 +0,0 @@
#!/usr/bin/env python3
"""
cc-ci upgrader launcher — one-shot weekly recipe-upgrade job agent.
The upgrader runs /upgrade-all to completion, then stops and stays idle so the
run + summary remain viewable in the web UI. The next weekly run starts a fresh
session (start clears any idle/finished session).
Usage:
launch-upgrader.py start use-or-create: leave an in-flight run alone, else start fresh
launch-upgrader.py fresh always kill any existing session and start fresh
launch-upgrader.py stop kill the session
launch-upgrader.py status show session state
launch-upgrader.py attach tmux attach to the session
Env:
LOOP_BACKEND opencode (default) | claude — also accepts UPGRADER_BACKEND
LOOP_TIER opencode subscription tier: "go" (OpenCode Go, DEFAULT — the only tier
with a key on this host) or "zen" (OpenCode ZEN, opt-in on a host that
has a ZEN key). Selects the default model + the usage-limit probe
endpoint/key. ZEN models are DEAD here (no key, gone from the
provider catalogue — see the TIER block below).
Only affects the opencode backend (ignored for claude).
LOOP_MODEL model flag (overrides UPGRADER_MODEL); default tracks backend+tier —
opencode+go→opencode-go/deepseek-v4.1-flash, opencode+zen→opencode/glm-5.2, claude→sonnet
UPGRADER_MODEL provider/model for opencode, e.g. opencode-go/deepseek-v4.1-flash (OpenCode Go, default),
opencode/glm-5.2 (OpenCode ZEN), or tinfoil/deepseek-v4-pro; sonnet for claude
UPGRADER_ARGS extra args passed to /upgrade-all (e.g. "n8n ghost", "--dry-run")
claude backend:
CLAUDE_BIN, CLAUDE_FLAGS, REMOTE_CONTROL
opencode backend:
OPENCODE_BIN, OPENCODE_SERVER, OPENCODE_SHARE (1=attach to web server + public --share link)
"""
import os, sys, subprocess, re
from datetime import datetime
from pathlib import Path
# ── config ────────────────────────────────────────────────────────────────────
SESSION = os.environ.get("UPGRADER_SESSION", "cc-ci-upgrader")
WORKDIR = os.environ.get("UPGRADER_DIR", "/srv/cc-ci")
LOG_DIR = os.environ.get("LOG_DIR", "/srv/cc-ci/.cc-ci-logs")
# LOOP_BACKEND / LOOP_MODEL take precedence (unified control from the operator).
# LOOP_TIER selects the OpenCode subscription: "go" (DEFAULT — the only tier with a key on
# this host) or "zen" (opt-in on a host that has a ZEN key). ZEN models are DEAD here — the
# endpoint errors server-side, and env loss in the tmux→agent→launch-report chain is exactly
# how it silently ate the 2026-09-18 weekly report. Never default back to zen.
# Only affects the opencode backend; claude ignores the tier.
BACKEND = os.environ.get("LOOP_BACKEND", os.environ.get("UPGRADER_BACKEND", "opencode"))
TIER = os.environ.get("LOOP_TIER", os.environ.get("UPGRADER_TIER", "go"))
_TIER_CFG = {
"go": {"model": "opencode-go/deepseek-v4.1-flash", "endpoint": "https://opencode.ai/zen/go/v1/chat/completions",
"auth": "opencode-go", "label": "OpenCode Go"},
"zen": {"model": "opencode/glm-5.2", "endpoint": "https://opencode.ai/zen/v1/chat/completions",
"auth": "opencode", "label": "OpenCode ZEN"},
}
if BACKEND == "opencode" and TIER not in _TIER_CFG:
print(f"[upgrader] ERROR: unknown LOOP_TIER '{TIER}' — use 'go' or 'zen'", flush=True)
sys.exit(1)
_tier = _TIER_CFG.get(TIER, _TIER_CFG["go"])
_DEFAULT_MODEL = _tier["model"] if BACKEND == "opencode" else "sonnet"
MODEL = os.environ.get("LOOP_MODEL", os.environ.get("UPGRADER_MODEL", _DEFAULT_MODEL))
CLAUDE_BIN = os.environ.get("CLAUDE_BIN", "claude")
CLAUDE_FLAGS = os.environ.get("CLAUDE_FLAGS", "--dangerously-skip-permissions")
REMOTE_CONTROL = os.environ.get("REMOTE_CONTROL", "1") == "1"
OPENCODE_BIN = os.environ.get("OPENCODE_BIN", "/home/loops/.local/bin/opencode")
OPENCODE_SERVER = os.environ.get("OPENCODE_SERVER", "http://127.0.0.1:4096")
# Web visibility for the opencode backend: attach the session to the shared opencode
# web server (viewable at https://oc.ci.commoninternet.net (basic auth)) AND optionally
# create a public opencode.ai --share link. Default both on so the run is monitorable.
OPENCODE_SHARE = os.environ.get("OPENCODE_SHARE", "1") == "1"
UPGRADER_ARGS = os.environ.get("UPGRADER_ARGS", "")
# First step of the weekly run: reclaim STALE docker images on the cc-ci server BEFORE the run so a
# heavy run can't fill the disk mid-flight (root cause of the 2026-07-03 stall — 100% ENOSPC killed
# lasuite-drive + wedged the run). "Stale" = unused by any container AND older than PRERECLAIM_UNTIL,
# so recently-built/pulled images (the ones this week's tests will reuse) are KEPT — we only evict
# leftovers from prior weeks. Best-effort; never fails the run.
PRERECLAIM = os.environ.get("UPGRADER_PRERECLAIM", "1") == "1"
PRERECLAIM_UNTIL = os.environ.get("UPGRADER_PRERECLAIM_UNTIL", "168h") # 7d: older than one run ago
PRERECLAIM_HOST = os.environ.get("UPGRADER_PRERECLAIM_HOST", "cc-ci")
# ── helpers ───────────────────────────────────────────────────────────────────
def log(msg):
ts = datetime.now().strftime("%H:%M:%S")
print(f"[upgrader {ts}] {msg}", flush=True)
def die(msg):
log(f"ERROR: {msg}")
sys.exit(1)
def session_alive():
return subprocess.run(
["tmux", "has-session", "-t", SESSION], capture_output=True
).returncode == 0
def session_busy():
"""True while a turn is actively in flight (not idle/finished/wedged)."""
r = subprocess.run(["tmux", "capture-pane", "-pt", SESSION],
capture_output=True, text=True)
pane = r.stdout if r.returncode == 0 else ""
return bool(re.search(r"esc to interrupt|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏|Running tool", pane))
def kill_session():
subprocess.run(["tmux", "kill-session", "-t", SESSION], capture_output=True)
def _watchdog_alive():
return subprocess.run(["tmux", "has-session", "-t", f"{SESSION}-watchdog"],
capture_output=True).returncode == 0
def prereclaim_cc_ci():
"""Weekly-run step 0: prune STALE (unused AND older than PRERECLAIM_UNTIL) docker images on the
cc-ci server so the run has disk headroom. Keeps recent images (reused this week); only clears
prior-weeks' leftovers. Best-effort — a reclaim failure must never abort the run."""
if not PRERECLAIM:
return
filt = f"--filter until={PRERECLAIM_UNTIL}"
remote = (f"docker image prune -af {filt} 2>&1 | tail -1; "
f"docker builder prune -af {filt} >/dev/null 2>&1 || true; "
f"df -h / | tail -1")
log(f" step 0: pre-reclaim stale docker images on {PRERECLAIM_HOST} (unused & >{PRERECLAIM_UNTIL})")
try:
r = subprocess.run(["ssh", "-o", "ConnectTimeout=15", PRERECLAIM_HOST, remote],
capture_output=True, text=True, timeout=900)
out = (r.stdout or r.stderr or "").strip()
for ln in out.splitlines():
if ln.strip():
log(f" {ln.strip()}")
except Exception as e:
log(f" pre-reclaim skipped (non-fatal): {e}")
# ── kickoff prompt ────────────────────────────────────────────────────────────
def build_kickoff():
args_note = f" with arguments: {UPGRADER_ARGS}" if UPGRADER_ARGS else ""
return f"""\
*** cc-ci UPGRADER — weekly recipe-upgrade job ***
You are the cc-ci Upgrader: a ONE-SHOT job agent, NOT a perpetual loop. Run the
recipe-upgrade sequence to completion, then STOP. Your cwd is {WORKDIR}; reach the CI
server with `ssh cc-ci`; creds are in {WORKDIR}/.testenv; skills in {WORKDIR}/.claude/skills/.
DO THIS:
1. Invoke the /upgrade-all skill in DEFAULT mode{args_note}
(read {WORKDIR}/.claude/skills/upgrade-all/SKILL.md for the full procedure). It surveys
every enrolled recipe and, for each upgradeable one, runs /recipe-upgrade in DEFAULT
mode — recipe PR only, verified by posting `!testme` on the PR (results visible in the
PR, iterate up to 3x). A genuinely stale test gets an explanatory PR COMMENT, never a
test edit.
2. Process recipes via per-recipe SUBAGENTS so your own context stays light. If your
context usage climbs (~80%), run /compact before continuing.
3. Write + push the weekly summary (the PR list is the actionable output for the operator).
4. WHEN THE RUN IS COMPLETE: STOP. Print the final summary (lead with the PR list) and an
`UPGRADE RUN COMPLETE` line, then go idle. Do NOT loop, do NOT re-run, and do NOT kill
your own session — leave it up so the operator can review the output in the web UI.
Next week's run starts a fresh session (the launcher clears this idle one).
GUARDRAILS: NEVER merge any PR. NEVER weaken a test. DEFAULT mode only — do NOT pass
--with-tests (updating cc-ci tests is the operator's per-recipe opt-in). Single-writer:
dedicated branches + separate clones, never push main, never touch the build loops'
/cc-ci /cc-ci-adv clones. The shared Swarm is stateful — go sequentially.
"""
# ── launch ────────────────────────────────────────────────────────────────────
def start(mode="use-or-create"):
import shutil
if not shutil.which("tmux"):
die("tmux not found")
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
if session_alive():
if mode == "use-or-create" and session_busy():
log(f"{SESSION} already running a job (busy) — leaving it")
return
log(f"{SESSION} exists but idle/stale (or fresh requested) — killing it first")
kill_session()
import time; time.sleep(1)
# Step 0 of the weekly run: clear STALE cc-ci docker images so a heavy run can't run the disk
# out mid-flight (root cause of the 2026-07-03 stall). Only for the actual upgrade run.
if SESSION == "cc-ci-upgrader":
prereclaim_cc_ci()
# Unique-name invariant: the run we are about to launch becomes THE 'cc-ci-upgrader' in the
# web UI; every older run gets an archive title. Also snapshot existing ids so the new
# session can be pinned unambiguously after launch.
_archive_stale_titles()
_prev_rows = _server_get("/session") or []
_prev_rows = _prev_rows if isinstance(_prev_rows, list) else _prev_rows.get("data", [])
_prev_ids = {s.get("id") for s in _prev_rows}
try:
STATE_SID_FILE.unlink()
except OSError:
pass
kf = Path(LOG_DIR) / f".kickoff-{SESSION}.txt"
kf.write_text(build_kickoff())
model_flag = f"--model '{MODEL}'" if MODEL else ""
tier_note = f", tier={TIER} ({_tier['label']})" if BACKEND == "opencode" else ""
log(f"starting {SESSION} (backend={BACKEND}{tier_note}, model={MODEL}, args='{UPGRADER_ARGS or '<none>'}')")
if BACKEND == "claude":
if not shutil.which(CLAUDE_BIN):
die(f"claude CLI not found — set CLAUDE_BIN (currently: {CLAUDE_BIN})")
rc = f"--remote-control '{SESSION}'" if REMOTE_CONTROL else ""
cmd = f"{CLAUDE_BIN} {rc} {model_flag} {CLAUDE_FLAGS} \"$(cat '{kf}')\""
elif BACKEND == "opencode":
if not Path(OPENCODE_BIN).exists():
die(f"opencode not found at {OPENCODE_BIN}")
# NOTE: -m/--model and --attach/--title/--share are flags on the `run` SUBCOMMAND,
# so they must come AFTER `run` (a global `opencode --model X run` is ignored).
share_flag = "--share" if OPENCODE_SHARE else ""
cmd = (
f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; "
f"{OPENCODE_BIN} run {model_flag} {share_flag} --attach '{OPENCODE_SERVER}' "
f"--title '{SESSION}' \"$(cat '{kf}')\""
)
log(f" attached to {OPENCODE_SERVER} → https://oc.ci.commoninternet.net"
+ (" +public --share link (printed in the session)" if OPENCODE_SHARE else ""))
else:
die(f"unknown LOOP_BACKEND '{BACKEND}' — use 'claude' or 'opencode'")
subprocess.run(["tmux", "new-session", "-d", "-s", SESSION, "-c", WORKDIR, cmd])
subprocess.run(["tmux", "pipe-pane", "-o", "-t", SESSION,
f"cat >> '{LOG_DIR}/{SESSION}.log'"])
log(f"started. attach: tmux attach -t {SESSION} log: {LOG_DIR}/{SESSION}.log")
if BACKEND == "opencode":
_pin_new_session(_prev_ids)
# For the opencode backend, spawn a watchdog that auto-resumes the run if the opencode
# usage-limit (429) stalls it mid-run (it does NOT self-resume). See watchdog().
if BACKEND == "opencode" and os.environ.get("UPGRADER_WATCHDOG", "1") == "1":
_spawn_watchdog()
# ── opencode stall-detect + auto-resume watchdog ────────────────────────────────
# The opencode subscription (Go or ZEN tier) enforces a rolling usage-limit (HTTP 429 + retry-after). When it
# trips mid-run, the `opencode run` agent loop ENDS and does NOT self-resume. This watchdog detects
# the stall (the session log stops growing), waits out the limit, and resumes the SAME session —
# context preserved — via `opencode run -s <id> --continue`. Standalone: launch-upgrader.py {resume|watchdog}.
import json as _json, urllib.request as _ureq, time as _time
STALL_MIN = float(os.environ.get("UPGRADER_STALL_MIN", "15")) # log-idle minutes ⇒ stalled
CHECK_EVERY = int(os.environ.get("UPGRADER_CHECK_SEC", "180")) # watchdog poll cadence
# Generic so the SAME watchdog also covers the report job (launch-report.py points it at the
# cc-ci-report session with its own marker + resume prompt via these env vars).
DONE_MARKER = os.environ.get("UPGRADER_DONE_MARKER", "UPGRADE RUN COMPLETE")
RESUME_FILE = os.environ.get("UPGRADER_RESUME_FILE") # optional path to a custom resume prompt
LIMIT_ENDPOINT = _tier["endpoint"] # tier-aware: zen or go
AUTH_JSON = os.path.expanduser("~/.local/share/opencode/auth.json")
LOG_FILE = f"{LOG_DIR}/{SESSION}.log"
def _server_get(path):
try:
with _ureq.urlopen(OPENCODE_SERVER + path, timeout=15) as r:
return _json.load(r)
except Exception:
return None
STATE_SID_FILE = Path(LOG_DIR) / f".{SESSION}-session-id"
def _server_patch(path, body):
req = _ureq.Request(OPENCODE_SERVER + path, method="PATCH",
headers={"Content-Type": "application/json"},
data=_json.dumps(body).encode())
try:
with _ureq.urlopen(req, timeout=15) as r:
return r.status
except Exception:
return None
def _db_created_ms(sid):
"""Session creation time from the opencode sqlite DB — the /session API rows carry NO
time fields, which is exactly how the 2026-08-04 watchdog resumed the WRONG (old, giant)
session: sorting on a missing key degraded to server list order."""
try:
import sqlite3
db = sqlite3.connect("file:" + os.path.expanduser(
"~/.local/share/opencode/opencode.db") + "?mode=ro", uri=True)
row = db.execute("SELECT time_created FROM session WHERE id=?", (sid,)).fetchone()
db.close()
return row[0] if row else 0
except Exception:
return 0
def _archive_stale_titles(title=None, label=None):
"""Rename every existing top-level session with the given canonical title to a dated
archive title, so EXACTLY ONE session ever carries the canonical name (the one the next
launch creates). Keeps the run trivially findable in the opencode web UI and makes the
title lookup in _session_id() unambiguous. Old runs stay browsable under
'<label> — <date>'. Also used by launch-supervisor.py for its own session name."""
title = title or SESSION
# Archive names always start with 'archive-' (operator convention 2026-08-04) so they
# sort/filter together in the web UI: 'archive-<original-title> — <date>'.
label = label or f"archive-{title} —"
rows = _server_get("/session") or []
rows = rows if isinstance(rows, list) else rows.get("data", [])
for s in rows:
if s.get("title") == title and not (s.get("parentID") or s.get("parentId")):
created = _db_created_ms(s["id"])
d = datetime.fromtimestamp(created / 1000).strftime("%Y-%m-%d") if created else "unknown-date"
_server_patch(f"/session/{s['id']}", {"title": f"{label} {d}"})
log(f" archived old session {s['id'][:20]} → '{label} {d}'")
def _session_id():
"""The opencode session this launcher manages. Prefers the pinned id recorded at launch
(LOG_DIR/.{SESSION}-session-id) — title lookup is only the fallback, and thanks to
_archive_stale_titles() at most one top-level session carries the title. Never trust
server list order (see _db_created_ms)."""
try:
pinned = STATE_SID_FILE.read_text().strip()
# Validate directly — the /session LIST is paginated (~100 rows), so membership
# scans miss older/newer sessions; a direct GET is authoritative.
if pinned and (_server_get(f"/session/{pinned}") or {}).get("id") == pinned:
return pinned
except OSError:
pass
rows = _server_get("/session") or []
rows = rows if isinstance(rows, list) else rows.get("data", [])
cands = [s for s in rows if s.get("title") == SESSION and not (s.get("parentID") or s.get("parentId"))]
cands.sort(key=lambda s: _db_created_ms(s.get("id")), reverse=True)
if cands:
try:
STATE_SID_FILE.write_text(cands[0]["id"])
except OSError:
pass
return cands[0]["id"]
return None
def _pin_new_session(prev_ids, wait_sec=45):
"""After launching a fresh run, discover the NEW top-level SESSION-titled session (one not
in prev_ids) and pin its id to the state file, so the watchdog can never grab an old one."""
deadline = _time.time() + wait_sec
while _time.time() < deadline:
rows = _server_get("/session") or []
rows = rows if isinstance(rows, list) else rows.get("data", [])
for s in rows:
if (s.get("title") == SESSION and not (s.get("parentID") or s.get("parentId"))
and s.get("id") not in prev_ids):
try:
STATE_SID_FILE.write_text(s["id"])
except OSError:
pass
log(f" pinned managed session id {s['id'][:20]} → {STATE_SID_FILE.name}")
return s["id"]
_time.sleep(3)
log(" WARNING: could not discover the new session id to pin (title lookup remains the fallback)")
return None
def _session_idle_min():
"""Minutes since the managed run last ADVANCED — measured across the whole session TREE (the
top-level cc-ci-upgrader session AND every descendant subagent). Uses the opencode SERVER's
time.updated (authoritative — bumps on every new message/part) rather than the tmux log mtime,
which FREEZES when a headless `opencode run --continue` doesn't stream to the pane (that froze
signal made the watchdog resume-storm). Crucially it must include CHILDREN: while a per-recipe
subagent runs (a deploy can take 20-40min) the PARENT's updated time is stale, so reading the
parent alone would look 'idle' and trigger a false resume that kills the productive run. Falls
back to the log mtime only when the server is unreachable."""
sid = _session_id()
if not sid:
try:
return (_time.time() - os.path.getmtime(LOG_FILE)) / 60.0
except Exception:
return None
rows = _server_get("/session") or []
rows = rows if isinstance(rows, list) else rows.get("data", [])
def _parent(s): return s.get("parentID") or s.get("parentId")
# Transitive closure of sid over parent links → the managed session + all its descendants.
tree = {sid}
for _ in range(8): # bounded fixpoint (subagents nest only a few deep)
grew = False
for s in rows:
if s.get("id") not in tree and _parent(s) in tree:
tree.add(s.get("id")); grew = True
if not grew:
break
newest = 0
for s in rows:
if s.get("id") in tree:
newest = max(newest, (s.get("time") or {}).get("updated") or 0)
if newest:
return max(0.0, (_time.time() * 1000 - newest) / 60000.0)
try:
return (_time.time() - os.path.getmtime(LOG_FILE)) / 60.0
except Exception:
return None
# Back-compat alias (older callers / the report watchdog import this name).
_log_idle_min = _session_idle_min
def _limit_key():
try:
return (_json.load(open(AUTH_JSON)).get(_tier["auth"]) or {}).get("key")
except Exception:
return None
def _limit_retry_after():
"""0 if the tier's opencode endpoint is available (HTTP 200); else the 429 retry-after seconds."""
key = _limit_key()
if not key:
return 0
body = _json.dumps({"model": (MODEL or "").split("/")[-1] or "deepseek-v4.1-flash", "max_tokens": 8,
"messages": [{"role": "user", "content": "hi"}]}).encode()
req = _ureq.Request(LIMIT_ENDPOINT, data=body, method="POST",
headers={"Authorization": "Bearer " + key, "content-type": "application/json"})
try:
_ureq.urlopen(req, timeout=20).read(); return 0
except _ureq.HTTPError as e:
if e.code == 429:
try: return max(1, int(e.headers.get("retry-after", "300")))
except Exception: return 300
return 0
except Exception:
return 0
def _run_pids(sid=None):
"""PIDs of live `opencode run` procs for THIS session (via /proc scan — never matches self).
Matches on FLAG VALUES (`--title <SESSION>` / `-s|--session <sid>`), never a substring of the
whole cmdline. The substring form caused the 2026-08-07 three-day deadlock: an agent's kickoff
PROMPT is passed as an argv element, and the supervisor's prompt text contains the literal
"cc-ci-upgrader", so the supervisor's own (billing-hung) agent matched as a live upgrader run —
the hourly gate then read its own corpse as "run progressing" and no-opped ~60 times."""
me, out = os.getpid(), []
for p in os.listdir("/proc"):
if not p.isdigit() or int(p) == me:
continue
try:
cl = [c for c in open(f"/proc/{p}/cmdline", "rb").read().split(b"\0") if c]
except Exception:
continue
if not cl or b"opencode" not in cl[0] or b"run" not in cl or b"--attach" not in cl:
continue
def _flag(names):
for i, a in enumerate(cl[:-1]):
if a in names:
return cl[i + 1]
return None
title = _flag((b"--title",))
s_val = _flag((b"-s", b"--session"))
if title == SESSION.encode() or (sid and s_val == sid.encode()):
out.append(int(p))
return out
def _billing_blocked(window_bytes=4000):
"""True when the tail of this run's log shows a provider billing/usage wall.
Such a process must NEVER be killed: it may resume when the wall lifts, and killing it can
lose in-flight work. It is also NOT progress — it can spin for days emitting nothing (observed
2026-08-07..10), so the gate reports it as BLOCKED and leaves recovery to the operator."""
try:
with open(LOG_FILE, "rb") as f:
f.seek(0, os.SEEK_END)
f.seek(max(0, f.tell() - window_bytes))
tail = f.read().decode(errors="replace").lower()
except OSError:
return False
return any(
s in tail
for s in ("spending limit", "insufficient balance", "usage limit", "usagelimiterror")
)
def _completed():
# Done only when the MODEL signs off with DONE_MARKER as its FINAL word: the marker in the LAST
# assistant TEXT (prose) message. This guards THREE false-positives that each abandoned a run:
# (1) the kickoff/resume PROMPT contains the marker — but that's a USER message (skipped).
# (2) the marker inside a TOOL part — a subagent `task` prompt or a bash command that echoes
# "print <marker>" — so we look ONLY at type=='text' prose, never tool-call args.
# (3) the model ECHOING the instruction mid-run ("…then I'll print <marker>") — only the FINAL
# assistant prose counts, so any further work after the echo means it's NOT done.
sid = _session_id()
msgs = _server_get(f"/session/{sid}/message") if sid else None
if msgs is not None:
msgs = msgs if isinstance(msgs, list) else msgs.get("data", [])
last_prose = None
for m in msgs:
if ((m.get("info") or {}).get("role")) != "assistant":
continue
prose = "".join(p.get("text", "") for p in (m.get("parts") or [])
if p.get("type") == "text" and isinstance(p.get("text"), str))
if prose.strip():
last_prose = prose
return bool(last_prose and DONE_MARKER in last_prose)
# Server unreachable → conservative log fallback that excludes the prompt's own mention.
try:
with open(LOG_FILE, errors="ignore") as f:
f.seek(0, 2); f.seek(max(0, f.tell() - 20000))
return any(DONE_MARKER in ln and "print" not in ln and "'" not in ln for ln in f)
except Exception:
return False
def resume(reason="manual"):
"""Resume the managed opencode session from where it stopped (context preserved)."""
import signal
sid = _session_id()
if not sid:
log(f"resume: no top-level '{SESSION}' session on {OPENCODE_SERVER} — cannot resume"); return False
log(f"resume ({reason}): continuing session {sid}")
for pid in _run_pids(sid):
try: os.kill(pid, signal.SIGTERM)
except Exception: pass
_time.sleep(2); kill_session(); _time.sleep(1)
kf = Path(LOG_DIR) / f".kickoff-{SESSION}-resume.txt"
if RESUME_FILE and os.path.exists(RESUME_FILE):
kf.write_text(open(RESUME_FILE).read()) # caller-supplied (e.g. the report job)
else:
kf.write_text(
"The opencode usage limit has reset (or the run stalled). You were mid-way through the weekly "
"cc-ci /upgrade-all run. CONTINUE from where you left off — do NOT start over. Process the enrolled "
"recipes not yet done this week, alphabetically; SKIP ones already done (their PRs exist — extend, "
"never duplicate). Per recipe: run /recipe-upgrade in DEFAULT mode via a subagent, verify with "
"!testme, open/extend the recipe PR (NEVER merge, NEVER weaken a test), <= DRONE_RUNNER_CAPACITY "
"concurrent. immich has a tag+digest image abra can't parse — do the upstream-direct cross-check "
"(recipe-upgrade SKILL §1), don't silently skip it. When all remaining recipes are done: "
"write+push the weekly summary, then `python3 /srv/cc-ci/cc-ci-plan/launch-report.py fresh`, print "
"'" + DONE_MARKER + "', and go idle.")
share = "--share" if OPENCODE_SHARE else ""
cmd = (f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; {OPENCODE_BIN} run -s {sid} --continue "
f"--model '{MODEL}' {share} --attach '{OPENCODE_SERVER}' --dir '{WORKDIR}' \"$(cat '{kf}')\"")
subprocess.run(["tmux", "new-session", "-d", "-s", SESSION, "-c", WORKDIR, cmd])
subprocess.run(["tmux", "pipe-pane", "-o", "-t", SESSION, f"cat >> '{LOG_FILE}'"])
try:
STATE_SID_FILE.write_text(sid) # a resume continues the SAME session — keep it pinned
except OSError:
pass
log(f"resume: relaunched {SESSION} (session {sid})")
# Every resume must be self-healing: ensure a watchdog is watching this run. Skip if one is
# already alive — notably when the watchdog ITSELF called resume (it lives in {SESSION}-watchdog),
# so this never spawns a duplicate watchdog-of-a-watchdog.
if os.environ.get("UPGRADER_WATCHDOG", "1") == "1" and not _watchdog_alive():
_spawn_watchdog()
return True
def _spawn_watchdog():
"""Start the watchdog inside the persistent tmux server (NOT a Popen child). A systemd-timer
`start` is a Type=oneshot whose cgroup is reaped on exit, which would kill a Popen child; a
tmux session lives under the long-running tmux server and survives. Env is passed explicitly so
the watchdog gets THIS run's config regardless of the tmux server's ambient environment."""
import shlex
wsess = f"{SESSION}-watchdog"
wlog = f"{LOG_DIR}/{SESSION}-watchdog.log"
env = {"HOME": os.environ.get("HOME") or os.path.expanduser("~"),
"UPGRADER_SESSION": SESSION, "UPGRADER_DIR": WORKDIR, "LOG_DIR": LOG_DIR,
"UPGRADER_BACKEND": "opencode", "UPGRADER_MODEL": MODEL, "LOOP_TIER": TIER,
"OPENCODE_BIN": OPENCODE_BIN, "OPENCODE_SERVER": OPENCODE_SERVER,
"OPENCODE_SHARE": "1" if OPENCODE_SHARE else "0"}
for k in ("UPGRADER_RESUME_FILE", "UPGRADER_DONE_MARKER", "UPGRADER_STALL_MIN", "UPGRADER_CHECK_SEC"):
if os.environ.get(k):
env[k] = os.environ[k]
envstr = " ".join(f"{k}={shlex.quote(str(v))}" for k, v in env.items())
cmd = f"env {envstr} python3 {shlex.quote(os.path.realpath(__file__))} watchdog >> {shlex.quote(wlog)} 2>&1"
subprocess.run(["tmux", "kill-session", "-t", wsess], capture_output=True)
subprocess.run(["tmux", "new-session", "-d", "-s", wsess, "-c", WORKDIR, cmd])
log(f" watchdog spawned in tmux '{wsess}' — auto-resume on usage-limit stalls (survives the oneshot)")
def watchdog():
"""Watch the opencode upgrader and keep it alive to completion. Two stall modes:
(a) PROC-DEATH — `opencode run` exits when the model ENDS ITS TURN (or crashes). For a long
autonomous /upgrade-all this happens repeatedly before the whole run is done; the log mtime
also freezes, so log-idle alone would take 15min to notice a run that died in 5. We detect
it directly: no live `opencode run` proc for the session + not completed ⇒ resume promptly.
(b) LOG-IDLE — a proc is alive but wedged (no output > STALL_MIN); resume after confirming.
Either way, wait out an opencode usage-limit (429) first rather than hammering. Exits when the
model prints DONE_MARKER, or after MAX_RESUMES consecutive resumes fail to get a live proc going
(truly broken — hand back to the hourly supervisor / operator). Spawned by start()/resume()."""
MAX_RESUMES = int(os.environ.get("UPGRADER_MAX_RESUMES", "20"))
log(f"watchdog: watching {SESSION} (proc-death + stall>{STALL_MIN}min session-idle, poll {CHECK_EVERY}s)")
misses = 0; resumes = 0
while True:
_time.sleep(CHECK_EVERY)
# A transient error (server blip, race) must NEVER kill the watchdog — that would silently
# abandon the run. Log and keep polling instead of letting the exception exit the loop.
try:
if _completed():
log("watchdog: run completed — exiting"); return
sid = _session_id()
pids = _run_pids(sid) if sid else []
idle = _session_idle_min()
dead = not pids
stalled = idle is not None and idle > STALL_MIN
if not dead and not stalled:
misses = 0; resumes = 0; continue # alive + session advancing — healthy
# Something's wrong (dead or wedged). Wait out a usage-limit before touching it.
retry = _limit_retry_after()
if retry > 0:
wait = min(retry + 30, 3600)
log(f"watchdog: {'proc dead' if dead else f'stalled {idle:.0f}min'} + usage-limited "
f"(retry-after {retry}s) — waiting {wait}s")
_time.sleep(wait); continue
if not dead:
# Alive but session not advancing — confirm really wedged (two misses) before acting.
misses += 1
if misses < 2:
continue
if resumes >= MAX_RESUMES:
log(f"watchdog: {MAX_RESUMES} resumes without completion — giving up (supervisor/operator needed)")
return
why = "run proc exited (turn ended/crashed)" if dead else f"stalled {idle:.0f}min, limit clear"
log(f"watchdog: {why} — auto-resuming (#{resumes + 1})")
resume("watchdog auto-resume"); resumes += 1; misses = 0
except Exception as e:
log(f"watchdog: poll error ({type(e).__name__}: {e}) — continuing")
# ── main ──────────────────────────────────────────────────────────────────────
def main():
cmd = sys.argv[1] if len(sys.argv) > 1 else "start"
if cmd == "start":
start("use-or-create")
elif cmd == "fresh":
start("fresh")
elif cmd == "stop":
if session_alive():
log(f"killing {SESSION}")
kill_session()
else:
log(f"{SESSION} not running")
elif cmd == "status":
if session_alive():
busy = "busy" if session_busy() else "idle/finishing"
log(f"{SESSION}: RUNNING ({busy})")
subprocess.run(
f"ps -eo pid,etime,args | grep '[r]emote-control {SESSION}' || true",
shell=True)
else:
log(f"{SESSION}: stopped")
log(f"backend: {BACKEND} tier: {TIER} model: {MODEL} args: '{UPGRADER_ARGS or '<none>'}'")
elif cmd == "attach":
os.execvp("tmux", ["tmux", "attach", "-t", SESSION])
elif cmd == "resume":
resume("manual")
elif cmd == "watchdog":
watchdog()
else:
print(f"""cc-ci upgrader launcher — one-shot weekly recipe-upgrade job
launch-upgrader.py start use-or-create (leave busy run alone, else start fresh)
launch-upgrader.py fresh always kill existing + start fresh
launch-upgrader.py stop kill the session
launch-upgrader.py status show session state
launch-upgrader.py attach tmux attach
launch-upgrader.py resume continue the opencode session from where it stalled (-s <id> --continue)
launch-upgrader.py watchdog watch + auto-resume the opencode run across usage-limit (429) stalls
Backend: {BACKEND} (LOOP_BACKEND or UPGRADER_BACKEND env var)
Tier: {TIER} (LOOP_TIER or UPGRADER_TIER env var; 'go' or 'zen'; only for opencode)
Model: {MODEL} (LOOP_MODEL or UPGRADER_MODEL env var)
Args: {UPGRADER_ARGS or '<none>'} (UPGRADER_ARGS env var, passed to /upgrade-all)
claude: viewable at claude.ai/code
opencode: viewable at https://oc.ci.commoninternet.net server={OPENCODE_SERVER}
""")
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/launch-upgrader.py
-17
View File
@@ -1,17 +0,0 @@
#!/usr/bin/env bash
# Load cc-ci runtime configuration. Source this file; do not execute it.
#
# Callers enable `set -a` so both files become exported environment variables.
# Public configuration is loaded first, then the secret file. This preserves a
# local secret override only where an emergency migration explicitly needs it.
if [ -r /srv/cc-ci/cc-ci/.env.public ]; then
. /srv/cc-ci/cc-ci/.env.public
fi
if [ ! -r /srv/cc-ci/.testenv ]; then
echo "cc-ci secret environment is missing: /srv/cc-ci/.testenv" >&2
return 1
fi
. /srv/cc-ci/.testenv
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/load-env.sh
@@ -1,80 +0,0 @@
# Policy + cleanup — cc-ci compose overlays (when they're justified) & upgrade-tier from-version
**Status:** POLICY (codifies `plan.md §9`) + a small set of follow-ups. **Owner:** Builder + Adversary.
**This file:** `/srv/cc-ci/cc-ci-plan/plan-ccci-compose-overlay-policy.md`
**Supersedes** the earlier `plan-prefer-env-over-compose-overlay.md` (its premise — parameterize
`start_period` via an env var — is **wrong: abra does not support an env value for `start_period`**).
---
## 0. Policy (operator, 2026-05-30)
A cc-ci-authored compose overlay (the single `compose.ccci.yml`, layered via `COMPOSE_FILE`) risks
**drift** from the recipe users run — so **avoid where possible and justify each use**. But it is a
**legitimate, uniform fallback pattern**, not forbidden:
- **Prefer an upstream recipe PR** in most cases — a real robustness fix, or exposing a knob the recipe
should expose. That's where a fix usually belongs.
- **A ccci overlay is the right tool when the value can't be supplied any other way** — notably a
healthcheck **`start_period`**, which **abra cannot take from an env var**. The ghost/discourse
`start_period` bumps therefore **stay as overlays** (an env PR is impossible for that field).
- **Uniform pattern (acceptable fallback):** a single, fixed-name **`compose.ccci.yml`** per recipe
(NOT per-purpose suffixes — one file holds all cc-ci-side deploy tweaks for that recipe), provided
into the checkout by `install_steps.sh`, wired by `recipe_meta` `COMPOSE_FILE`
(`compose.yml:compose.ccci.yml`), kept as an untracked file so it survives the upgrade
`git checkout -f` (`CHAOS_BASE_DEPLOY=True`; `assert_upgraded` strips the `+U` marker — see
DECISIONS 2026-05-30).
- **Each overlay must:** be **minimal + single-purpose**, **document WHY** in its header (the exact
abra/upstream limitation that forces it), and be **Adversary-confirmed** to not weaken a test or mask
a recipe defect. Where the fix also belongs upstream (e.g. a `start_period` too tight for any slow
host), **file the upstream PR too** — the overlay is the cc-ci-side fallback, not a reason to skip it.
## 1. Upgrade tier: always test the upgrade to LATEST
Don't drop the upgrade test because the *from* (older) version is awkward.
- **Always perform the upgrade to the latest version and run the full assertions on the latest.**
- If the older from-version can't be fully deployed/tested (image tag removed from the registry, or it
predates an overlay/feature), you do **NOT** need that older version's **custom tests** to run.
Deploy it minimally (a justified overlay is fine) or upgrade from the nearest deployable prior; skip
only the from-version's custom assertions, and **record** that.
- Skipping a from-version's custom tests = honest, recorded. Skipping upgrade-to-latest = not OK.
## 2. Disposition of the current overlays
- [ ] **RENAME the overlay files to the uniform `compose.ccci.yml`.** `tests/ghost/compose.ccci-health.yml`
and `tests/discourse/compose.ccci-health.yml` → `compose.ccci.yml`; update each recipe's
`install_steps.sh` (the `cp` target) and `recipe_meta` `COMPOSE_FILE`
(`compose.yml:compose.ccci-health.yml` → `compose.yml:compose.ccci.yml`). One fixed filename per
recipe going forward.
- [ ] **ghost `compose.ccci.yml` (start_period 900s) — KEEP, justified.** abra can't env-param
`start_period`; the fresh-DB migration needs the larger grace or swarm kills it → deadlock.
Confirm the header documents this; consider an upstream PR raising ghost's `start_period` (it's a
real slow-host fragility) — but the overlay stays regardless.
- [ ] **discourse `compose.ccci.yml` — KEEP, justified (both parts).** (a) `start_period 1200s`
(same reason as ghost). (b) The `bitnami/discourse:3.3.1 → bitnamilegacy/discourse:3.3.1` re-pin
makes the from-version (0.7.0, whose `bitnami/discourse` tag Docker Hub now 404s) **deployable so
the upgrade-to-latest test can run** — namespace-only, identical discourse version, applied to
base+head. This is the §1 case: keep the upgrade-to-latest test; the 0.7.0 custom tests need not
run. Document it; if a deployable prior without the re-pin exists, prefer upgrading from that.
- [ ] **mumble `compose.host-ports.yml` (cc-ci copy for the old base) — DROP it.** Deploying mumble
0.2.0 does NOT need host-ports (that overlay only *publishes* 64738 for on-host tests). Per §1:
deploy 0.2.0 without it, **skip 0.2.0's voice/on-host custom tests**, then upgrade to the latest
version (which ships `compose.host-ports.yml` natively) and run the voice tests on the latest.
Remove the cc-ci copy + its `install_steps`/`COMPOSE_FILE` wiring for the old base; the current
version's native overlay is untouched.
## 3. Definition of Done (Adversary cold-verifies)
- [ ] Every surviving cc-ci overlay is minimal, header-documents its justification (the abra/upstream
limitation), and is Adversary-confirmed to not weaken a test or mask a defect.
- [ ] The mumble old-base cc-ci host-ports copy is removed; mumble still **upgrades to latest** and runs
its voice tests **on the latest** (0.2.0's voice tests skipped + recorded).
- [ ] ghost + discourse still pass full suites; discourse still tests the upgrade to latest.
- [ ] Any upstream PR opened (e.g. ghost/discourse `start_period`) follows the recipe-PR rule
(cc-ci-green via `!testme` before operator merge); the overlay remains as the cc-ci fallback.
- [ ] No upgrade-to-latest test was dropped to avoid an awkward from-version.
## 4. Guardrails
- **Correctness first** — never weaken/skip/soften a check to make a deploy or upgrade pass; an
overlay tunes deploy/infra only (its header must say how), the real assertions stand.
- **Justify + document every overlay**; prefer the upstream PR where the fix belongs.
- **Real abra path** throughout.
+1
View File
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/plan-ccci-compose-overlay-policy.md
@@ -1,172 +0,0 @@
# Plan: migrate cc-ci domains from `*.commoninternet.net` to `ci.autonomic.zone`
**Date:** 2026-09-21 · **Status:** DRAFT — blocked only on operator DNS access (Gandi zone `autonomic.zone`)
**Principle:** same host, same IP (195.201.88.249), same services — only names change. Dual-run new
alongside old; old names retire last; rollback at any point is "change nothing further" because the
old DNS zone keeps answering until Phase 4.
---
## 1. Inventory — what answers on what today
| Name | Served by | Router/config source |
|---|---|---|
| `ci.commoninternet.net` | results dashboard + bridge `/hook` | `cc-ci/nix/modules/dashboard.nix`, `bridge.nix` (traefik Host rules) |
| `report.ci.commoninternet.net` | weekly report static site | `cc-ci/nix/modules/reports.nix` |
| `drone.ci.commoninternet.net` | Drone server | `cc-ci/nix/modules/drone.nix` (abra app; env `DOMAIN`, `DRONE_SERVER_HOST`); runner RPC: `drone-runner.nix` |
| `oc.ci.commoninternet.net` | opencode UI (traefik → host nginx basic auth) | `cc-ci-orch/nix/modules/orchestrator-host.nix` (`opencodeUiHost`), set in `nix/hosts/cc-ci/configuration.nix` |
| `traefik.ci.commoninternet.net` | traefik stack identity + deploy-proxy health gate | `cc-ci/nix/modules/proxy.nix` |
| `warm-*.ci.commoninternet.net` | warm canonical recipe stacks | `warm-keycloak.nix`, warm-bluesky-pds (caddy labels) |
| `<tag>-<6hex>.ci.commoninternet.net` | per-run recipe test deploys | `cc-ci/runner/harness/naming.py` `app_domain()` — **resolves via public DNS** (containers use 1.1.1.1/8.8.8.8) |
| `backups.ci.commoninternet.net` | backup-bot-two — stack name only, no web route | `backupbot.nix` |
| `acme.commoninternet.net` (NS `ns-acme`) | local acme-dns (systemd, port 53) | `cc-ci/nix/modules/acme-dns.nix` |
**Cert chain today:** nixos `security.acme` (lego) issues `ci.commoninternet.net` + `*.ci.commoninternet.net`
via DNS-01 through the local acme-dns; Gandi delegates `_acme-challenge.ci.commoninternet.net` CNAME →
`9d3f0428-eb97-4b14-bb07-da2f0f6c2073.acme.commoninternet.net`. `postRun` fires
`cc-ci-acme-traefik-handoff.service` → installs cert into `/var/lib/ci-certs/live` → restarts
`deploy-proxy.service`, whose reconciler re-derives the `traefik_ci_commoninternet_net_ssl_{cert,key}_v<hash>`
swarm secrets (traefik runs co-op-cloud wildcard/no-ACME mode off those secrets).
**DNS:** both zones on Gandi. IPv4-only (no AAAA records anywhere; none needed).
**External references:** Gitea OAuth app for Drone (redirect URI → drone.ci…); per-repo webhooks →
`/hook` — **only `recipe-maintainers/ghost` and `recipe-maintainers/discourse` have any** (everything
else is bridge-driven via the Drone API); ~60 doc references across cc-ci-orch (AGENTS.md, README,
plan.md, skills).
## 2. Target naming
| Old | New |
|---|---|
| ci.commoninternet.net | ci.autonomic.zone |
| report.ci.commoninternet.net | report.ci.autonomic.zone |
| drone.ci.commoninternet.net | drone.ci.autonomic.zone |
| oc.ci.commoninternet.net | oc.ci.autonomic.zone |
| traefik.ci.commoninternet.net | traefik.ci.autonomic.zone |
| *.ci.commoninternet.net (warm-\*, per-run apps, backups identity) | *.ci.autonomic.zone |
| acme.commoninternet.net | **stays** through Phases 1–2 (infra, not a front door); optional Phase 3 |
Swarm **stack names** (`traefik_ci_commoninternet_net`, `ccci-*`, warm stacks) are identifiers, not
domains — keep them where possible to avoid churn in keep-lists/prune filters, EXCEPT abra-managed
apps whose name **is** the domain (drone, backup-bot, per-run apps).
## 3. DNS records to set (zone `autonomic.zone`, Gandi — operator)
| # | Name | Type | Value | TTL | Purpose |
|---|---|---|---|---|---|
| 1 | `ci.autonomic.zone` | A | `195.201.88.249` | 300 | apex front door (wildcard does NOT cover the apex) |
| 2 | `*.ci.autonomic.zone` | A | `195.201.88.249` | 300 | report/drone/oc/traefik/warm-\*/`<tag>-<6hex>` run apps |
| 3 | `_acme-challenge.ci.autonomic.zone` | CNAME | `9d3f0428-eb97-4b14-bb07-da2f0f6c2073.acme.commoninternet.net.` | 300 | DNS-01 for the new wildcard — **reuses the existing restricted acme-dns account** (`disable_registration=true`; the lego *account* authenticates, not the FQDN, so one acme-dns subdomain serves both zones) |
Also: lower TTL to 300 on the old `ci`/`*.ci` records a few days ahead (fast rollback later).
Phase 3 (optional) adds: `acme.ci.autonomic.zone` + `ns-acme.ci.autonomic.zone` A records.
**DNS verification (before touching the host):**
```bash
dig +short ci.autonomic.zone A @ns-187-a.gandi.net # 195.201.88.249
dig +short report.ci.autonomic.zone @1.1.1.1 # 195.201.88.249 (via wildcard)
dig +short drone.ci.autonomic.zone @8.8.8.8 # 195.201.88.249
dig +short _acme-challenge.ci.autonomic.zone CNAME # 9d3f0428-….acme.commoninternet.net.
```
## 4. Phase 1a — certificate (issue BEFORE any routing change)
1. `cc-ci/nix/modules/acme-dns.nix`: add a second `security.acme.certs."ci.autonomic.zone"` entry
(domain + `*.ci.autonomic.zone` SAN, `dnsProvider = "acmedns"`, `dnsResolver = "1.1.1.1:53"`).
Split the lego env per cert — today `ACME_DNS_STORAGE_PATH` is baked to
`/var/lib/acme/ci.commoninternet.net/…`; generate one env file per cert so each keeps its own
acme-dns account file.
2. Extend `cc-ci-acme-traefik-handoff` to stage the new cert alongside the old
(`/var/lib/ci-certs/live` holds both, e.g. `fullchain.pem` = new + `fullchain-old.pem`).
3. Extend the **deploy-proxy reconciler** (`proxy.nix`) for **dual-cert SNI**: new wildcard pair as
`ssl_cert/ssl_key` (default store) + old pair as a second secret pair wired through a small
file-provider `[[tls.certificates]]` so `*.ci.commoninternet.net` keeps serving during the bake
window. This is the one fiddly bit — validate against the **Let's Encrypt staging** endpoint
first (the module already has the staging-marker pattern).
4. `nixos-rebuild test` → confirm both certs issued and served (`openssl s_client -servername` for a
name in each zone, check SANs) → `switch`.
## 5. Phase 1b — routing + service config (one stack at a time, health-gated)
During the bake window every router rule carries **both** hostnames
(`Host(`ci.autonomic.zone`) || Host(`ci.commoninternet.net`)`); old names drop out only in Phase 4.
- `dashboard.nix` + `bridge.nix` (share the `ci` host: dashboard `/` + bridge `/hook`), `reports.nix`,
and the traefik health-gate name in `proxy.nix`.
- `bridge.py` / `dashboard.py` code defaults for `DRONE_URL` / `DASH_URL`.
- `recipe-report.py` — footer, publish URL text and its verification curl → `report.ci.autonomic.zone`
(regenerate the index after, so the home page stops linking the old name).
- Drone **abra app rename** (name = domain, so this is a new stack):
1. Export enabled-repo list from the old Drone API.
2. Deploy new abra app `drone.ci.autonomic.zone` (same module; secrets `rpc_secret`,
`client_secret` re-insert from `/run/secrets` as today). **Fresh DB** — Drone data volume is
stack-name-prefixed; repos re-sync on Gitea login, build history is lost (accepted; export the
old repo list and re-enable via API).
3. Point `drone-runner.nix` `DRONE_RPC_HOST` at the new name; restart runner.
4. Re-run `scripts/bootstrap-drone-oauth.sh` with `DRONE=https://drone.ci.autonomic.zone`
(updates the Gitea OAuth redirect URI; script already uses `--resolve` to hit loopback).
5. Update the two webhooks (ghost, discourse) to `https://drone.ci.autonomic.zone/hook?secret=<same>`
— read the secret off the existing hook config before deleting it.
6. `abra app undeploy` + remove the old drone app once green.
- `configuration.nix`: `opencodeUiHost = "oc.ci.autonomic.zone"`; extend the `networking.hosts`
self-pin list with the new names (keep old pins during bake).
- Gitea `GITEA_SERVER` stays `git.autonomic.zone` — unchanged.
## 6. Phase 2 — harness / warm / per-run naming (the `_ci_commoninternet_net` blast radius)
- `cc-ci/runner/harness/naming.py` `app_domain()` → `.ci.autonomic.zone` (single source of truth).
- Regexes/patterns that match the derived names: `docker-prune.nix` run-app filter,
`tests/concurrency/concutil.py` (`DOMAIN` const + `RUN_APP_RE`), any separate `RUN_APP_RE` in
`lifecycle.py` / `warm.py` / `warm_reconcile.py` / `canonical.py` / `generic.py` / `http.py`,
`nightly-sweep` keep-list patterns, `tests/gitea/recipe_meta.py` comment.
- Redeploy warm stacks under new names (abra `warm-<recipe>.ci.autonomic.zone`), reconcile, drain old.
- `backupbot.nix` `DOMAIN` (stack-name-only change).
- Verify: full deterministic test suite + one live `!testme` run end-to-end.
## 7. Phase 3 (optional) — move acme-dns off commoninternet.net
Only if `commoninternet.net` is being dropped entirely: new `domain`/`nsname` in acme-dns config
(`acme.ci.autonomic.zone` / `ns-acme.ci.autonomic.zone` + Gandi records), briefly re-enable
registration or hand-migrate the account DB, re-point `_acme-challenge` CNAMEs, re-issue both certs.
## 8. Phase 4 — retirement (after ≥7 clean days)
Remove old names from the dual router rules → remove `security.acme.certs."ci.commoninternet.net"`
+ its env file + old cert secret pair → drop old `networking.hosts` pins → delete old Gandi records
(`ci`, `*.ci`, `_acme-challenge.ci`) → restore TTLs to 3600. Keep `acme.commoninternet.net` unless
Phase 3 was done.
## 9. Verification checklist
- **DNS:** the dig table in §3 against a Gandi NS and a public resolver.
- **Cert:** `openssl s_client -connect 195.201.88.249:443 -servername <name>` for one name per zone —
SANs correct for both, `ssl_verify_result=0`.
- **Front doors:** `ci` → 200 · `report.ci` → 200 · `drone.ci` → 200/303 · `oc.ci` → **401**
(basic auth intact) · `traefik.ci/api/version` → 200.
- **SSO:** Drone login through Gitea on the new redirect URI.
- **Webhook:** empty commit to `recipe-maintainers/ghost` main → build fires on the new host.
- **Bridge/!testme:** `!testme` on a scratch PR → build runs, `results.json` written, PR comment
contains **new** domain links.
- **Report:** publish one report page and verify it at `https://report.ci.autonomic.zone`.
- **Host:** `systemctl --failed` empty; `deploy-proxy` reconcile logs clean.
## 10. Risks / gotchas
- **Dual-cert SNI in the traefik reconciler** is the highest-risk change — stage-first, verify SNI
selection for both zones before switching.
- **Drone DB** does not follow the abra rename — accept fresh build history; export/re-apply the
enabled-repo list; re-insert secrets from `/run/secrets` (module already does).
- **Per-run recipe domains resolve via public DNS** — the `*.ci.autonomic.zone` wildcard A record is
load-bearing for every test deploy; never merge Phase 2 before it propagates.
- Old PR comments/badges link old names — they keep working until Phase 4 removes the old records.
- ~60 doc references (AGENTS.md, README, plan.md, skills, status skill) — one cosmetic doc PR at the
end so the docs don't lie.
- No domain-bearing secret values were found (webhook secrets are per-repo and copied as-is).
## 11. Sequencing
1. **Operator:** TTLs down + 3 Gandi records (§3) — 5 minutes.
2. **Agent:** cert PR (§4) → `test` → verify dual SNI → `switch`.
3. **Agent:** routing/env PRs (§5) stack-by-stack, health-gated; OAuth + webhooks + drone rename.
4. **Agent:** end-to-end verification (§9) + report republish under the new name.
5. **Bake ≥7 days** → Phase 2 PR → full suite → bake → Phase 4 retirement.
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/plan-domain-migration-ci-autonomic-zone.md
-54
View File
@@ -1,54 +0,0 @@
# Plan — debug & fix the ghost recipe upgrade PR
**Context:** during the 2026-06-12 weekly upgrade, ghost (ghost 6.42.0→6.44.1 + mysql bump) was the
recipe whose `!testme` kept wedging. Its test deploys (`ghos-bdd2f3` etc.) hung at 0/1 in Swarm
`New` state — which we now know was the **`proxy` VIP exhaustion** (see
[[proxy-vip-exhaustion-runbook]] / `plan-proxy-vip-exhaustion-fix.md`), NOT necessarily a ghost
defect. It also got run by a DUPLICATE subagent during the interrupt churn, so the PR/branch state
may be messy. This plan figures out what actually went wrong and leaves the ghost PR clean + green.
**Execute AFTER** the proxy VIP fix (so the infra confound is gone) and the current upgrade settles.
Owner: orchestrator, or a focused `/recipe-upgrade ghost` re-run.
## What the upgrader already found (2026-06-12 summary — start here)
ghost 6.42.0→6.44.1 (+ mysql 8.0→8.4). PR is **recipe-maintainers/ghost #4**, open with an analysis
comment. Three `!testme` attempts:
- run 1 (2026-06-05): **PASS** at 6.44.0 + mysql:8.4 (under lighter load).
- run 2 (2026-06-12): FAIL — **IPAM/proxy-VIP exhaustion** (infra; the [[proxy-vip-exhaustion-runbook]] issue).
- run 3 (2026-06-12): FAIL — **a REAL issue**: Swarm `UpdateStatus=paused` on the **mysql 8.0→8.4
data-dir upgrade race** — the default 5s `update_config.monitor` is too tight for the mysql
data-dir migration under load, so Swarm marks the update paused/failed.
The upgrader's suggested fix: add **`update_config.monitor: 300s`** (and likely
`failure_action: continue` / a longer `start_period`) to the ghost **app** service so the mysql
data-dir upgrade has time to converge. So the likely real fix is a small recipe-PR change to ghost's
`update_config`, then re-verify — NOT a test change.
## Steps
1. **Inventory the ghost PR state.** On recipe-maintainers/ghost: list open PRs — is there ONE
upgrade PR or a DUPLICATE (two branches/PRs from the two ghost subagents)? Capture each PR's
branch, diff (image tag + version-label bumps), and its `!testme` comment history / build
results. Read the upgrader transcript for both ghost subagents to see what each did.
2. **Separate infra failure from real failure.** The deploy wedges were proxy-VIP exhaustion
(infra). Determine whether ghost ALSO has a genuine upgrade problem: does ghost 6.44.1 + the
mysql bump deploy + pass its tests on a HEALTHY swarm? Re-run `!testme` on the ghost PR now that
the box is healthy (post docker-restart / post proxy fix) and watch the real result.
3. **Dedup.** If two ghost PRs/branches exist, keep the correct one (right version bump, clean
diff), close the duplicate with a note, and ensure no leftover `dev-ghost`/`ghos-*` stacks remain
(reap).
4. **Fix forward to green.** If `!testme` is RED for a REAL reason (e.g. ghost 6.44.1 needs a config
change, or the mysql major bump needs a migration step / a genuinely-stale test): apply the
minimal recipe fix per `/recipe-upgrade` rules — recipe PR changes only; if a cc-ci TEST is
genuinely stale, leave an explanatory PR COMMENT (do NOT edit tests in default mode). Iterate
`!testme` ≤3× to green.
5. **Leave it operator-ready.** One clean ghost PR, `!testme` GREEN (or a clear comment explaining a
legitimately-deferred issue), no duplicate, no leaked deploys. NEVER merge — operator merges.
## Acceptance
The ghost upgrade is represented by exactly one PR with a clear, green (or clearly-explained)
`!testme`, the duplicate-subagent mess cleaned, and a one-line note on whether ghost's original
failure was purely the proxy-VIP infra issue or a real upgrade problem (and how it was fixed).
## Guardrails
Recipe mirror = PR only, never merge / never push main. Reap any `dev-ghost`/`ghos-*` test stacks on
exit. No secrets in logs/commits. Don't run while the proxy recreate (maintenance window) is in
progress.
+1
View File
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/plan-ghostpr-debug-fix.md
@@ -1,97 +0,0 @@
# Plan — lasuite-drive OIDC-setup flakiness: harness restructure + recipe robustness PR
**Status:** QUEUED — picks up the deferred lasuite-drive `[~]` item (Q3.2) when the loops return to it.
The disk blocker is now lifted (host grew to 70 GB, 2026-05-29), so the upgrade tier can run too.
**Owner:** Builder + Adversary loops. **Two deliverables:** (A) a cc-ci harness change, (B) a
**lasuite-drive recipe PR** (we maintain the recipe via recipe-maintainer).
**This file:** `/srv/cc-ci/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md`
---
## 0. The problem (ground it in real logs FIRST)
lasuite-drive's `setup_custom_tests` wires OIDC by doing a **full 12-service `abra app deploy --chaos`
redeploy** of an already-running heavy stack. That reconverge is **flaky**: a collabora reconverge
race + a **transient backend gunicorn-perms / WOPI-404 window**. Only **backend/app** consume the
OIDC env, so re-converging collabora/onlyoffice/minio/db is unnecessary exposure. The Builder
correctly did NOT claim Q3.2 (a flaky setup isn't a reliable green) and filed this.
**Step 0 (do before fixing):** capture the actual failure from a flaky run — collabora WOPI-discovery
timing, the backend log at the 404, and the exact gunicorn perms error — so we fix the real root
cause, not a guess. Record in JOURNAL.
---
## Part A — cc-ci harness: wire OIDC at INSTALL, eliminate the redeploy
Leverage the now **live-warm keycloak** (WC1): instead of deploy-recipe-then-redeploy-with-OIDC, the
dep is already running, so configure OIDC **before the single deploy**:
1. Create the per-run namespaced realm+client in the **warm keycloak** (lightweight API calls — no
deploy).
2. Set lasuite-drive's OIDC env in its `.env` **before** the first `abra app deploy`.
3. Deploy lasuite-drive **once**, OIDC already wired. **No mid-run `--chaos` reconverge** → the flaky
window is gone.
- **Use REAL abra commands only** (operator decision, 2026-05-29): the install is a normal
`abra app deploy`. Do **NOT** use `docker service update`/`docker service scale` to surgically
patch services — CI must exercise the same abra path a real operator uses. If any redeploy ever
remains necessary, it is `abra app deploy` (+ proper readiness gating, §C), never a docker-level
bypass.
- **Generic-first invariant still holds.** keycloak is live-warm (persistent infra, ~always up), so
there's no per-run dep *deploy* that could fail and break a generic tier. Generic tiers still
assert serving recipe-alone; if realm creation or the provider is unreachable, only the OIDC
*custom* test fails (isolated). This is SAFE **iff** the recipe boots with OIDC-env-set even when
the provider isn't reachable at boot — which Part B guarantees (lazy OIDC). A and B reinforce each
other.
- **Revises `plan-sso-dep-testing.md`** for recipes whose app tolerates OIDC-at-boot: prefer
install-time wiring against the warm dep over the post-deploy `setup_custom_tests` redeploy. Keep
the redeploy path only for recipes that genuinely can't take OIDC env at first boot.
- **Verify:** lasuite-drive full suite green **without** a mid-run reconverge; run it repeatedly
(e.g. 3×) to show the flakiness is gone, not just absent once.
## Part B — lasuite-drive recipe PR (root-cause robustness, we're maintainers)
> **Broken out into its own sub-plan: `plan-lasuite-drive-recipe-pr.md`** (operator, 2026-05-29) —
> it now also folds in the F2-12 upgrade-convergence fix (collabora healthcheck) so cc-ci can return
> to abra-native convergence. The summary below is retained; the sub-plan is authoritative.
Fix the fragility in the recipe itself so it's robust under ANY reconverge — this helps real
operators, not just CI, and is the real payoff of maintaining the recipe. On a branch of the
lasuite-drive recipe (recipe-maintainer):
1. **Order backend behind collabora's WOPI readiness.** Add a Docker **healthcheck on collabora**
(WOPI discovery endpoint → 200) and make backend **wait for it / retry WOPI discovery with
backoff** instead of failing during collabora startup. Turns the race into deterministic ordering.
2. **Fix the gunicorn-perms race.** The transient perms error is a volume-permission race at startup
(gunicorn can't read/write a mount until perms are set). Fix in the entrypoint: set perms before
exec'ing gunicorn (or a proper init step).
3. **Make OIDC discovery lazy / retrying.** If backend validates the OIDC provider eagerly at boot
and dies when it's briefly unreachable, that's what forces the deploy-with-dep dance. Resolve OIDC
discovery lazily (at first login, with retry) so the app boots without the provider up. (This is
also the property Part A relies on for the generic-first invariant.)
### The PR is "working" ONLY when cc-ci verifies it green (operator rule, 2026-05-29)
A lasuite-drive recipe change is **not** considered done until **our CI server has run the full suite
on the PR and it passes** — install + upgrade + backup + restore + custom (incl. the OIDC login
test), repeatedly-green (no flakiness). Concretely: push the recipe branch/PR, trigger cc-ci
(`!testme` on the lasuite-drive PR), and require a clean green (Adversary cold-verified). **Only then
does the operator merge** the recipe PR. This dogfoods cc-ci: the CI that surfaced the bug also gates
its fix.
## C. If any redeploy must remain (fallback only)
If a recipe genuinely needs OIDC env applied after first boot, do it with **`abra app deploy`** (real
abra — never `docker service update`), and **gate readiness properly**: poll collabora WOPI = 200 +
backend health with retries/timeout before declaring ready. This is strictly a fallback; Part A +
Part B should remove the need.
## Definition of done
- [ ] Step 0 root-cause logs captured + recorded.
- [ ] Part A: lasuite-drive tested via install-time OIDC wiring against the warm keycloak, **no
mid-run reconverge**, full suite green **3× in a row** (flakiness gone), Adversary cold-verified.
- [ ] Part B: lasuite-drive recipe branch with the WOPI-healthcheck-gating + gunicorn-perms + lazy-OIDC
fixes; **cc-ci runs the full suite (incl. upgrade tier) on the PR and it is repeatedly green**;
Adversary cold-verifies; operator merges.
- [ ] Q3.2 (lasuite-drive) claimed + DEFERRED.md entry closed (flaky-OIDC item) — only after the above.
- [ ] `plan-sso-dep-testing.md` updated to prefer install-time OIDC wiring (warm dep) where the recipe
supports it.
+1
View File
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/plan-lasuite-drive-oidc-robustness.md
@@ -1,77 +0,0 @@
# Sub-plan — lasuite-drive recipe robustness PR (fix the root cause upstream)
**Status:** QUEUED — a **recipe-maintainer PR to the lasuite-drive recipe** (we maintain it). Picks up
after the Q3.2 lasuite-drive test work settles. Complements — and largely **obsoletes** — the
CI-side workarounds the harness currently uses for lasuite-drive's fragility.
**Owner:** Builder + Adversary loops. **This file:** `/srv/cc-ci/cc-ci-plan/plan-lasuite-drive-recipe-pr.md`
**Relationship:** this is the **recipe-side** deliverable. The cc-ci **harness-side** OIDC-at-install
work is `plan-lasuite-drive-oidc-robustness.md` Part A; this sub-plan is its Part B, broken out.
---
## 0. Why (CI surfaced real recipe bugs — fix them at the source)
cc-ci has surfaced genuine fragility in the lasuite-drive recipe that a **real operator would also
hit**, currently papered over by CI-side workarounds:
- **Install-time:** backend comes up before collabora's WOPI discovery is ready → transient
**WOPI-404** + a **gunicorn-perms** startup race. The flaky 12-service `--chaos` OIDC redeploy.
- **Upgrade-time (F2-12):** upgrading to the heavier new collabora (25.04.9.4.1) **does not converge
within abra's monitor window** → abra FATAs. The harness currently works around this by skipping
abra's convergence monitor (`-c`) and using its own collabora WOPI-200 `READY_PROBE`.
These are recipe defects. Fixing them upstream helps every lasuite-drive operator **and** lets cc-ci
**go back to abra's native convergence** (per the guardrail "prefer abra convergence; custom probe
only when necessary") — turning the harness `-c`/READY_PROBE from a *necessity* into a *backstop*.
## 1. The fixes (lasuite-drive recipe)
1. **Collabora healthcheck + start_period (the keystone).** Add a real Docker **healthcheck** to the
collabora service — WOPI discovery endpoint returns 200 — with a `start_period` generous enough
for the heavy 25.04 image to boot. Effect: (a) swarm/abra see collabora as *unhealthy until WOPI
is actually up*, so **abra's own convergence monitor waits correctly** (fixes F2-12 at the source
— no `-c` skip needed); (b) the install-time WOPI-404 window closes because dependents can gate on
collabora health.
2. **Backend tolerates / waits for collabora WOPI.** Make backend **retry WOPI discovery with
backoff** (and/or order it behind collabora health) instead of failing on the transient 404.
3. **Fix the gunicorn-perms startup race.** Set the volume permissions in the backend entrypoint
(or an init step) **before** exec'ing gunicorn, so there's no read/write race on a freshly-mounted
volume at startup.
4. **Lazy / retrying OIDC discovery.** Backend resolves the OIDC provider **at first login with
retry**, not eagerly at boot — so the app boots cleanly with OIDC env set even if the provider
isn't reachable yet. (This is also what the harness-side OIDC-at-install pattern relies on, and
what keeps the generic-first invariant safe.)
## 2. Mechanics — branch, PR, and the merge rule
- Make the change on a **lasuite-drive recipe branch** and open a PR via the **`recipe-create-pr`
skill** (`/srv/recipe-maintainer/.opencode/skills/recipe-create-pr/SKILL.md`) — mirror to
`git.autonomic.zone/recipe-maintainers/lasuite-drive` as needed; upstream is
`git.coopcloud.tech`.
- **The PR is "working" ONLY when cc-ci verifies it green** (operator rule): trigger cc-ci
(`!testme` on the lasuite-drive PR) and require the **full suite incl. the UPGRADE tier** to pass
**repeatedly-green** (e.g. 3 consecutive passes, not a one-off), **Adversary cold-verified**.
**Only then does the operator merge.** This dogfoods cc-ci: the CI that found the bugs gates the fix.
- **SCOPE (operator, 2026-05-29):** this repeated-green / 3× bar is **specific to lasuite-drive
because it was demonstrably FLAKY** — it's a *flakiness proof* (show the fix made it reliably
green, not green-by-luck-once). It is **NOT the general testing standard.** Normal recipe gates
remain **one Adversary cold-verified green** (`plan.md §6.1`); do not generalize 3× to other
recipes/gates.
## 3. Definition of done
- [ ] Recipe branch with fixes #1–#4; PR opened (recipe-create-pr).
- [ ] **cc-ci runs the full suite (install + upgrade + backup + restore + custom/OIDC) on the PR,
repeatedly green, Adversary cold-verified.**
- [ ] **Root-cause proof:** with the collabora healthcheck in place, demonstrate the upgrade tier
passes under **abra's NATIVE convergence** (i.e. drop `-c` for lasuite-drive and it still
converges + stays green) — confirming the recipe fix resolved F2-12 at the source. If it still
needs the harness backstop, say so honestly (record why).
- [ ] Operator merges the recipe PR. Then: cc-ci can **revert the lasuite-drive `-c`/READY_PROBE
workaround to abra-native convergence** (per the guardrail), and close the lasuite-drive flaky
items.
## 4. Guardrails
- **Don't weaken any test** to make the PR pass — the fixes must make the recipe genuinely robust,
proven by repeated-green cc-ci runs, not by loosening assertions.
- **Real abra path** throughout (no docker-level bypass).
- **Bounded** — the four targeted robustness fixes; not a recipe rewrite. Bigger recipe improvements
→ upstream issues / IDEAS, not this PR.
+1
View File
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/plan-lasuite-drive-recipe-pr.md
-210
View File
@@ -1,210 +0,0 @@
# SSO-dep testing pattern (OIDC + co-deployed provider) — reference plan
**Status:** active reference for Phase 2 (does not need its own phase; it's a pattern Phase 2
overlays apply per recipe).
**Operator clarification (2026-05-28):** integrating a recipe with an OIDC/SSO dep is **loop work,
not operator work**. Anything that was deferred citing "operator input needed for OIDC" should be
re-opened and done autonomously per this plan.
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-sso-dep-testing.md`
**Companion:** the running harness in `runner/harness/sso.py` (existing primitives:
`setup_keycloak_realm`, `oidc_password_grant`, `assert_discovery_endpoint`).
---
## 0. Why this plan
Several recipes test their authenticated functionality through an OIDC/SSO provider (keycloak,
authentik). The cc-ci pattern is to **co-deploy the provider with the recipe under test in the same
ephemeral run** — one shared deployment per dep, configured at install time, used by the
recipe-under-test's authenticated tests, torn down with it. This file is the canonical pattern for
how to wire that up so any recipe that declares `DEPS = ["keycloak"]` (or `["authentik"]`) Just Works
without per-recipe ad-hoc plumbing. Recipes that need OIDC are not blocked on the operator — they
follow this plan.
## 1. The DEPS model — deps deploy AFTER generic tiers (operator-2026-05-28)
**Critical ordering rule:** generic tiers (install / upgrade / backup / restore) run against the
**recipe alone, with no dep available**, so a failure in dep-deploy or OIDC setup **cannot break
generic-tier signal**. Deps + OIDC wiring move to a **`setup_custom_tests` step** that runs *after*
generic tiers and *before* the custom tier — its failure is isolated to the SSO-marked custom tests.
A recipe's `tests/<recipe>/recipe_meta.py` declares its SSO dep:
```python
DEPS = ["keycloak"] # or ["authentik"] when that backend lands
```
### Lifecycle order (single run, per recipe)
```
1. Deploy recipe-under-test ALONE (no deps, OIDC env unset or stubbed).
- app_new #1 for the recipe; generic install_steps.sh runs RECIPE-ONLY setup (no deps).
2. INSTALL tier: generic [+ overlay] assertions against the recipe alone.
3. UPGRADE tier: abra app upgrade in place, assertions against the recipe alone.
4. BACKUP tier: in place (if backup-capable), recipe-alone marker.
5. RESTORE tier: in place, recipe-alone marker.
6. setup_custom_tests step ← NEW (operator-2026-05-28)
a. For each dep in DEPS, deploy + provision realm/client via harness.sso.setup_<provider>_realm.
b. Write $CCCI_DEPS_FILE with each dep's {domain, realm, client_id, client_secret, admin_*}.
c. Run the per-recipe post-deps hook `tests/<recipe>/setup_custom_tests.sh` to wire the OIDC
env into the running recipe (abra app config set + abra app secret insert) and trigger an
in-place redeploy of the affected services so the env takes effect.
d. Mark deps-ready = True on success; on ANY failure mark deps-ready = False and CONTINUE
(log the error; do NOT abort the run).
7. CUSTOM tier:
- If deps-ready: run all custom tests, including those tagged @pytest.mark.requires_deps.
- If NOT deps-ready: still run custom tests, but tests tagged @pytest.mark.requires_deps are
reported as ERROR/SKIP (with the captured setup_custom_tests error attached). Non-deps
custom tests still run normally.
8. Teardown (in finally): recipe first; then each dep in reverse declaration order.
```
### DG4.1 deploy-count guard, generalised
The "one deploy per run" guard becomes **one `abra app new` per app in the run** (recipe + each
dep). In-place reconfigure-and-redeploy (the step 6c env update) is **NOT** a fresh `app_new` and
does NOT increment the per-recipe count. So a run with `DEPS = ["keycloak"]` has exactly 2
`app_new` calls (recipe + keycloak), no matter how many tiers ran. The per-run summary reports
deploy-count per app for verification.
### Why this ordering
- **Generic-tier signal is preserved** when SSO/dep setup is broken — the recipe's own deploy/
upgrade/backup/restore behaviour is still tested honestly.
- **Failure isolation**: a recipe whose generic tier passes but whose SSO setup is broken yields
per-op `pass/pass/pass/pass/skip(deps-not-ready)` — far more useful than the previous
all-or-nothing.
- A recipe that genuinely can't boot without OIDC fails its generic install honestly (the recipe
should accept a stubbed/empty OIDC env at install time and only require the env when an
authenticated endpoint is hit). That's a real recipe finding, not a CI artifact.
## 2. Provider pluggability
- **Provider-agnostic primitives** (today, in `harness/sso.py`) — these stay pluggable:
- `oidc_password_grant(discovery_url, client_id, client_secret, username, password) -> token` —
pure OIDC; works against any compliant provider.
- `assert_discovery_endpoint(discovery_url, expected_issuer)` — pure OIDC.
- **Provider-specific setup** (admin API calls) — one function per provider:
- `setup_keycloak_realm(domain, admin_user, admin_password, realm, client_id, redirect_uris) ->
{client_secret, discovery_url}` — exists today.
- `setup_authentik_realm(...)` — same shape, authentik admin API; **deferred** to a future Q4
enrollment that actually wants authentik (see `machine-docs/DEFERRED.md`). Pluggable: a recipe
declaring `DEPS = ["authentik"]` would just call this instead. No change to the per-recipe
`install_steps.sh` shape beyond which provider it asks for from `$CCCI_DEPS_FILE`.
- **Don't write per-recipe SSO logic.** All recipes use the same DEPS+install_steps shape.
## 3. Per-recipe hooks — two distinct scripts (recipe-only vs post-deps)
A recipe with `DEPS = ["keycloak"]` ships **two** optional hook scripts (either may be absent if
not needed):
### 3.1 `tests/<recipe>/install_steps.sh` — RECIPE-ONLY setup, runs at install time
This is the Phase-1d custom-install-steps hook. It runs **before** the recipe deploys, **with no
dep available** (the dep hasn't been deployed yet at this point). Use it only for recipe-only
setup that the recipe needs to boot at all (e.g. seed a fixture, set a non-OIDC env). **Do NOT
read `$CCCI_DEPS_FILE` here** — it doesn't exist yet. If the recipe requires OIDC to *boot at
all*, set a safe stub here (e.g. disable auth) so the recipe can come up for generic tiers; the
real OIDC wiring happens in §3.2.
### 3.2 `tests/<recipe>/setup_custom_tests.sh` — POST-DEPS wiring, runs after generic tiers
This is the new (operator-2026-05-28) hook that wires the recipe to its already-deployed dep,
*after* the generic tiers have run. The orchestrator has already deployed each dep and written
`$CCCI_DEPS_FILE` by the time this runs. Roughly:
```sh
#!/usr/bin/env bash
set -euo pipefail
# Read the dep's connection info from $CCCI_DEPS_FILE (orchestrator-written).
KC_DOMAIN=$(jq -r '.keycloak.domain' "$CCCI_DEPS_FILE")
KC_CLIENT=$(jq -r '.keycloak.client_id' "$CCCI_DEPS_FILE")
KC_SECRET=$(jq -r '.keycloak.client_secret' "$CCCI_DEPS_FILE")
KC_REALM=$( jq -r '.keycloak.realm' "$CCCI_DEPS_FILE")
# Inject the OIDC client secret as an abra app secret (recipe-conventional name varies — match
# the recipe's .env.sample SECRET_*).
echo "$KC_SECRET" | abra app secret insert -n "$CCCI_APP_DOMAIN" oidc_rpcs v1 -
# Write the OIDC env vars to the parent .env (names per the recipe's .env.sample).
abra app config set "$CCCI_APP_DOMAIN" \
OIDC_REALM="$KC_REALM" \
OIDC_OP_DISCOVERY_ENDPOINT="https://${KC_DOMAIN}/realms/${KC_REALM}/.well-known/openid-configuration" \
OIDC_OP_AUTHORIZATION_URL="https://${KC_DOMAIN}/realms/${KC_REALM}/protocol/openid-connect/auth" \
OIDC_OP_TOKEN_URL="https://${KC_DOMAIN}/realms/${KC_REALM}/protocol/openid-connect/token" \
OIDC_OP_USER_URL="https://${KC_DOMAIN}/realms/${KC_REALM}/protocol/openid-connect/userinfo" \
OIDC_RP_CLIENT_ID="$KC_CLIENT" \
OIDC_RP_REDIRECT_URI="https://${CCCI_APP_DOMAIN}/auth/oidc/callback"
# Force an in-place redeploy of the affected services to pick up the new env. This is NOT a fresh
# app_new (deploy-count guard still 1 for this recipe).
abra app deploy --force --chaos --no-input "$CCCI_APP_DOMAIN"
```
The OIDC env-var **names are recipe-specific** (`OIDC_OP_*` for lasuite-docs, different prefixes
elsewhere). Read the recipe's `.env.sample` to see which keys the recipe expects; the *values* follow
this template. If a recipe needs more than this (extra group/claim mappings, etc.), extend its
`setup_custom_tests.sh` only — never the shared harness.
## 4. Test pattern: authenticated endpoints (mark + isolate)
- **Mark dep-requiring tests:** every custom test that needs the dep up + OIDC wired must use
`@pytest.mark.requires_deps`. The orchestrator skips these with reason `"deps-not-ready: <err>"`
if `setup_custom_tests` failed. Non-deps custom tests are unaffected by SSO setup failures.
- **Headless API tests** — use `harness.sso.oidc_password_grant` to mint an access token, then call
the recipe's authenticated endpoint with `Authorization: Bearer <token>`. Asserts on the response.
- **Browser flows (Playwright)** — navigate to the recipe, follow the redirect to keycloak, fill the
pre-provisioned test user's credentials, return to the recipe, exercise the UI. (Use the
pre-provisioned `ci-user@example.com` / known password the realm setup creates.)
- **The realm/client is fresh per run** — no cross-run state, no shared accounts. The realm setup
creates one or more test users with known passwords (pass-through from a per-run secret) so the
tests can authenticate without prompts.
## 5. Concrete recipes that use this pattern (Phase-2 scope)
These are **loop work** under this plan, not deferred:
- **lasuite-docs** — `DEPS = ["keycloak"]`; ports the upstream `oidc_login.py` +
`upload_conversion.py` parity tests + the §4.3-prescribed `create-a-doc + read-back via
authenticated /api/v1.0/documents/`. (Re-enters `DEFERRED.md` entry #5 — this plan IS the
re-entry, not operator input.)
- **cryptpad** — `DEPS = ["keycloak"]` (cryptpad upstream tests use authentik, but a keycloak-backed
cryptpad OIDC test is equally valid and uses the same primitives). The cryptpad create-a-pad
Playwright test (DEFERRED #6) is a separate concern — that one really does need a stable
CryptPad app-launch contract; it stays deferred.
- **lasuite-drive, lasuite-meet** — same pattern when mirrored (`recipe-create-pr` skill — loop work).
- Any future recipe that requires OIDC follows this plan; no operator handoff.
## 6. What stays deferred (genuinely operator-input)
- **authentik enrollment + `setup_authentik_realm` backend** (DEFERRED #9) — **RESOLVED (operator,
2026-05-29): keycloak is our default SSO provider; default ALL recipe OIDC tests to keycloak.** Do
NOT test authentik↔keycloak integration, and do NOT enroll authentik just to "prove pluggability"
— **Phase-2 DONE is NOT gated on authentik.** Enroll authentik + add `setup_authentik_realm` ONLY
if/when a recipe genuinely **requires** authentik (won't work under keycloak). If a recipe works
with keycloak, use keycloak. So DEFERRED #9's re-entry trigger narrows to "a recipe requires
authentik" — the cross-provider-coverage trigger is dropped. (E.g. cryptpad: its upstream test
uses authentik, but test it under **keycloak** — equally valid.)
- The `--extra` flag IDEA is **not** a precondition for this plan; OIDC-dep tests are part
of the default suite for the recipes that need them.
## 7. Definition of done for this pattern
- [ ] `DEPS = [...]` honored by `runner/run_recipe_ci.py`, with the **deps-AFTER-generic** ordering
(§1): deps deploy + `setup_custom_tests` step runs between RESTORE and CUSTOM tiers;
`$CCCI_DEPS_FILE` written; deps torn down LAST in reverse order.
- [ ] **Failure isolation proven:** a forced `setup_custom_tests` failure (e.g. simulate keycloak
realm-setup error) yields a run where generic tiers report **pass** and CUSTOM
`requires_deps` tests report **skip(deps-not-ready)** — no false fail of the generic tier,
no aborted run.
- [ ] **lasuite-docs** ships `tests/lasuite-docs/setup_custom_tests.sh` per §3.2 + authenticated
tests per §4 marked `@pytest.mark.requires_deps` (closes DEFERRED #5 — keep the entry there
with the closing commit, do not re-defer).
- [ ] At least one other OIDC-dep recipe (cryptpad oidc_login or a lasuite-* once mirrored) lands
cold-green using the same pattern, demonstrating reuse.
- [ ] `docs/sso-dep-testing.md` (in the cc-ci repo) explains the pattern for future recipe
enrollments — link to this plan.
- [ ] Adversary cold-verifies the full run for one such recipe + the forced-failure isolation
case, posts PASS in `REVIEW-2.md`.
## 8. Mirror+enroll reminder (also loop work)
If a recipe in scope (e.g. `lasuite-drive`, `lasuite-meet`, `immich`) **isn't mirrored to
`git.autonomic.zone/recipe-maintainers/`**, mirror it autonomously via the `recipe-create-pr` skill
at `/srv/recipe-maintainer/.opencode/skills/recipe-create-pr/SKILL.md` (see also
`plan-phase2-recipe-tests.md §0b`). Mirror+enroll is **not** operator-pending; the bot is admin on
the org.
+1
View File
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/plan-sso-dep-testing.md
-234
View File
@@ -1,234 +0,0 @@
#!/usr/bin/env python3
"""pr-survey — deterministic facts about every open recipe PR, for /cc-ci-cleanup to judge.
Open recipe PRs rot in specific, detectable ways. This gathers the evidence; it does NOT decide
anything — closing a PR is a judgement the skill makes, with these facts in hand.
RUN `reconcile-upstream.sh --all` FIRST. Every signal below is measured against the mirror's `main`,
and an unreconciled mirror makes all of them wrong: on 2026-08-11 three PRs (discourse #6 carrying
140 CVEs, keycloak #6 carrying 12, n8n #5) looked pending against a stale mirror while upstream had
already merged them. This tool refuses to guess about that — see `reconciled_recently`.
Per PR:
behind_main commits on main not in the branch — the "out of date" measure
ahead commits on the branch not on main
mergeable gitea's own verdict (false = conflicts, needs a rebase)
diff_files files the PR touches (0 = nothing left to merge)
adds_images the `+ image:` lines it introduces
already_in_main those `+ image:` lines ALREADY present in main -> the bump landed another way
obsolete true when every image it adds is already in main (nothing to contribute)
ci newest `!testme` verdict + build number parsed from the PR comments
branch_kind upgrade / fix / ci-artifact (`ci/*` sweep + probe branches) / other
age_days, stale_days (since last update)
pr-survey.py [recipe ...] [--json]
"""
from __future__ import annotations
import argparse
import base64
import json
import os
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
from datetime import datetime, timezone
HERE = os.path.dirname(os.path.abspath(__file__))
USED_RECIPES = os.path.join(HERE, "used-recipes.md")
TESTENV = os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv")
PUBLIC_ENV = "/srv/cc-ci/cc-ci/.env.public"
NS = "recipe-maintainers"
def _env() -> dict:
e = {}
for path in (PUBLIC_ENV, TESTENV):
try:
lines = open(path)
except OSError:
continue
for ln in lines:
ln = ln.strip()
if "=" in ln and not ln.startswith("#"):
k, v = ln.split("=", 1)
e[k] = v.strip().strip('"').strip("'")
return e
ENV = _env()
GITEA = os.environ.get("GITEA_URL") or ENV.get("GITEA_URL", "git.autonomic.zone")
_AUTH = base64.b64encode(
f"{os.environ.get('GITEA_USERNAME') or ENV.get('GITEA_USERNAME','')}:"
f"{os.environ.get('GITEA_PASSWORD') or ENV.get('GITEA_PASSWORD','')}".encode()
).decode()
def _get(path: str, raw: bool = False):
req = urllib.request.Request(
f"https://{GITEA}{path}",
headers={"Authorization": f"Basic {_AUTH}", "User-Agent": "cc-ci-pr-survey"},
)
with urllib.request.urlopen(req, timeout=60) as r:
body = r.read()
return body.decode(errors="replace") if raw else json.loads(body)
def _days(iso: str | None) -> int | None:
if not iso:
return None
try:
d = datetime.fromisoformat(iso.replace("Z", "+00:00"))
except ValueError:
return None
return (datetime.now(timezone.utc) - d).days
def _branch_kind(ref: str) -> str:
if ref.startswith("ci/"):
return "ci-artifact" # regall/cfold sweeps + testme probes; never meant to merge
if ref.startswith("upgrade"):
return "upgrade"
if re.match(r"^(fix|feat|chore|revert)", ref):
return "fix"
return "other"
def _main_images(recipe: str) -> set[str]:
"""Image refs pinned on the mirror's main — the baseline a PR is judged against."""
out = set()
for f in ("compose.yml",):
try:
txt = _get(f"/{NS}/{recipe}/raw/branch/main/{f}", raw=True)
except Exception: # noqa: BLE001
continue
for m in re.finditer(r"^\s*image:\s*[\"']?([^\"'\s]+)", txt, re.M):
out.add(m.group(1))
return out
def _ci_verdict(recipe: str, number: int) -> dict:
"""Newest cc-ci !testme outcome recorded on the PR."""
try:
cs = _get(f"/api/v1/repos/{NS}/{recipe}/issues/{number}/comments?limit=100")
except Exception: # noqa: BLE001
return {"verdict": "unknown", "build": None}
for c in reversed(cs):
b = c.get("body") or ""
if "cc-ci:testme" not in b:
continue
m = re.search(r"/cc-ci/(\d+)", b)
if "✅" in b or "passed" in b:
return {"verdict": "passed", "build": m.group(1) if m else None}
if "❌" in b or "failure" in b:
return {"verdict": "failed", "build": m.group(1) if m else None}
if "⏳" in b or "in progress" in b:
return {"verdict": "running", "build": m.group(1) if m else None}
return {"verdict": "never-run", "build": None}
def survey_pr(recipe: str, pr: dict, main_images: set[str]) -> dict:
n = pr["number"]
head = pr["head"]["ref"]
row = {
"recipe": recipe, "number": n, "title": pr.get("title", ""), "head": head,
"url": pr.get("html_url"), "branch_kind": _branch_kind(head),
"age_days": _days(pr.get("created_at")), "stale_days": _days(pr.get("updated_at")),
"mergeable": pr.get("mergeable"),
}
try:
row["behind_main"] = _get(
f"/api/v1/repos/{NS}/{recipe}/compare/{urllib.parse.quote(head, safe='')}...main"
).get("total_commits", 0)
row["ahead"] = _get(
f"/api/v1/repos/{NS}/{recipe}/compare/main...{urllib.parse.quote(head, safe='')}"
).get("total_commits", 0)
except Exception: # noqa: BLE001
row["behind_main"], row["ahead"] = None, None
# A FAILED diff fetch must never look like an empty diff: gitea#4 404s on .diff (force-pushed
# branch) and would otherwise be flagged EMPTY-DIFF and closed — while being a verified, green,
# needed fix. Unknown is its own state.
diff = None
try:
body = _get(f"/{NS}/{recipe}/pulls/{n}.diff", raw=True)
if body.lstrip().startswith(("diff --git", "From ")) or not body.strip():
diff = body
except Exception: # noqa: BLE001
diff = None
row["diff_files"] = None if diff is None else len(re.findall(r"^diff --git ", diff, re.M))
adds = re.findall(r"^\+\s*image:\s*[\"']?([^\"'\s]+)", diff or "", re.M)
row["adds_images"] = sorted(set(adds))
row["already_in_main"] = sorted({i for i in set(adds) if i in main_images})
# Nothing left to contribute: it touches files but every image it introduces is already pinned.
# Only claim obsolete when the diff was actually READ. No diff, no verdict.
row["obsolete"] = diff is not None and bool(adds) and set(adds).issubset(main_images)
row["ci"] = _ci_verdict(recipe, n)
return row
def all_recipes() -> list[str]:
out = []
for ln in open(USED_RECIPES):
p = ln.split()
if len(p) >= 2 and not ln.startswith(("#", "`")) and p[1] in ("weekly", "external"):
out.append(p[0])
return out
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("recipes", nargs="*")
ap.add_argument("--json", action="store_true")
a = ap.parse_args()
rows = []
for r in (a.recipes or all_recipes()):
try:
prs = _get(f"/api/v1/repos/{NS}/{r}/pulls?state=open&limit=50")
except urllib.error.HTTPError as e:
rows.append({"recipe": r, "error": f"HTTP {e.code}"})
continue
if not prs:
continue
mi = _main_images(r)
for pr in prs:
rows.append(survey_pr(r, pr, mi))
if a.json:
print(json.dumps(rows, indent=2))
return 0
print(f"{len(rows)} open PR(s)\n")
for x in sorted(rows, key=lambda z: (z.get("recipe", ""), z.get("number", 0))):
if x.get("error"):
print(f" {x['recipe']}: {x['error']}")
continue
flags = []
if x["obsolete"]:
flags.append("OBSOLETE(images already in main)")
if x["branch_kind"] == "ci-artifact":
flags.append("CI-ARTIFACT")
if x["diff_files"] == 0:
flags.append("EMPTY-DIFF")
if x["diff_files"] is None:
flags.append("DIFF-UNREADABLE(do not close on this)")
if x["mergeable"] is False:
flags.append("CONFLICTS")
if (x["behind_main"] or 0) > 0:
flags.append(f"BEHIND-{x['behind_main']}")
print(f" {x['recipe']}#{x['number']:<3} {x['title'][:52]}")
print(f" {x['branch_kind']:12} age={x['age_days']}d idle={x['stale_days']}d "
f"ci={x['ci']['verdict']}({x['ci']['build'] or '-'}) files={x['diff_files'] if x['diff_files'] is not None else '?'}")
if x["adds_images"]:
print(f" adds: {', '.join(i.split('/')[-1] for i in x['adds_images'][:4])}")
if flags:
print(f" >> {' | '.join(flags)}")
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/pr-survey.py
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env bash
# Runs as ExecStartPre of cc-ci-loops.service. Appends ONE line to REBOOTS.md per genuine reboot.
# Uses the kernel boot_id to distinguish a real reboot from a mere `systemctl restart` of the unit:
# only logs when the current boot_id differs from the last one we recorded.
set -u
REBOOTS="/srv/cc-ci/cc-ci-plan/REBOOTS.md"
LAST_BOOT_FILE="/srv/cc-ci/.cc-ci-logs/.last-boot-id"
PHASE_IDX_FILE="/srv/cc-ci/.cc-ci-logs/.phase-idx"
cur_boot="$(cat /proc/sys/kernel/random/boot_id 2>/dev/null || echo unknown)"
last_boot="$(cat "$LAST_BOOT_FILE" 2>/dev/null || echo '')"
# Same boot_id => this is a manual service restart, not a reboot => do nothing.
[ "$cur_boot" = "$last_boot" ] && exit 0
idx="$(cat "$PHASE_IDX_FILE" 2>/dev/null || echo '?')"
ts="$(date '+%Y-%m-%d %H:%M:%S %Z')"
mkdir -p "$(dirname "$LAST_BOOT_FILE")"
printf '%s\n' "- $ts — reboot detected; loops auto-started by systemd (resuming phase index $idx). boot_id=$cur_boot" >> "$REBOOTS" 2>/dev/null || true
echo "$cur_boot" > "$LAST_BOOT_FILE" 2>/dev/null || true
exit 0
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/reboot-log.sh
-377
View File
@@ -1,377 +0,0 @@
#!/usr/bin/env python3
"""recipe-report — data + HTML helper for the weekly "Recipe Report" (/recipe-report skill).
A newspaper-style front page: masthead, a SHORT editorial LEAD, then the comprehensive table ("the
full wire" — priority-sorted, CVEs column), an ADDENDUM of special issues, a SECURITY BULLETIN, and a
per-recipe "what changed" section at the end.
Subcommands (the /recipe-report agent runs them around its own review/classification):
survey [DATE] JSON of the run + every recipe's open PRs + CI verdict + per-recipe upgrade
notes (breaking-change/CVE analysis), and the /upgrade-all summary.
render SPEC.json OUT.html render the agent's report spec -> a self-contained newspaper HTML page
publish OUT.html DATE [KIND] copy to cc-ci:/var/lib/cc-ci-reports/<KIND>-DATE.html and regen the
archive index. KIND is `week` (default, the weekly /recipe-report) or `cve`
(a /cve-check advisory sweep). BOTH kinds appear in the SAME archive index,
newest first, each row suffixed "full" or "CVE check"; the distinct
filename prefix just stops a sweep overwriting a weekly edition.
Page order: short lead → the full wire table (priority-sorted, CVEs column) → Addendum → Security
Bulletin → per-recipe "What changed".
The full-wire table has two distinct status columns:
TESTS — the CI/test verdict for the PR (GREEN/FAILED/STALE/SKIPPED/UPTODATE; from the `status` field).
STATUS — the PR's LIVE state, fetched client-side and refreshed every ~30s: `open` vs a ✓ for any
not-open state (merged OR closed). Derived from `recipe` + `pr`; the inline script GETs the
same-origin `/pr/<recipe>/<n>` proxy served by the ccci-reports nginx stack (cc-ci repo,
nix/modules/reports.nix). Needs the recipe mirrors public; degrades to a muted "?" if the
proxy/repo is unreachable. No spec-shape change — STATUS uses existing row fields.
SPEC SHAPE (the agent writes this JSON):
{"date":"YYYY-MM-DD","subtitle":"Week of <human date>",
"lead":"<ONE short paragraph>",
"table":[{"recipe":"x","change":"a → b","status":"GREEN|FAILED|STALE|SKIPPED|UPTODATE", # -> TESTS col
"cve":16, # CVE count; "YES" for advisory without CVE ID; "?" unknown
"ci":"build 154 ✓","ci_url":"…","pr":"#4","pr_url":"…","notes":"…"}],
# ROWS SORTED by recommended priority to address — recipes WITH CVEs first, then failures,
# then stale-tests, then routine green, then up-to-date/skipped.
"addendum":["a special issue to look into (multiple open PRs, a CI-run oddity, a possible
improvement) …"], # only real issues — omit/empty if everything's clean
"security":[{"title":"recipe — CVE-… (high)","body":"what it fixes","links":[{"text":"PR #","url":"…"}]}],
"changes":[{"recipe":"x","body":"what changed in this recipe's PR","links":[{"text":"PR #4","url":"…"}]}]}
# one `changes` entry per recipe that has a PR this week.
PUBLIC PAGE — include only public-safe data (no secrets/tokens/raw logs).
"""
import base64, html, json, os, re, subprocess, sys, urllib.request
from datetime import datetime, timezone
LOGDIR = "/srv/cc-ci/.cc-ci-logs"
TESTENV = "/srv/cc-ci/.testenv"
PUBLIC_ENV = "/srv/cc-ci/cc-ci/.env.public"
INFRA = {"cc-ci", "cc-ci-orchestrator", "cc-ci-secrets"}
HOST_REPORTS = "/var/lib/cc-ci-reports"
# Both kinds live in ONE archive, distinguished by a suffix on a common title.
# prefix -> (page title, index label)
KINDS = {"week": ("The Recipe Report", "Week of {d} — full"),
"cve": ("The Recipe Report — CVE check", "{d} — CVE check")}
def _env():
e = {}
for path in (PUBLIC_ENV, TESTENV):
try:
lines = open(path)
except FileNotFoundError:
continue
for ln in lines:
ln = ln.strip()
if "=" in ln and not ln.startswith("#"):
k, v = ln.split("=", 1)
e[k] = v.strip().strip('"').strip("'")
return e
def _gitea_get(path, env):
url = f"https://{env['GITEA_URL']}/api/v1{path}"
auth = base64.b64encode(f"{env['GITEA_USERNAME']}:{env['GITEA_PASSWORD']}".encode()).decode()
req = urllib.request.Request(url, headers={"Authorization": "Basic " + auth})
try:
with urllib.request.urlopen(req, timeout=20) as r:
return json.load(r)
except Exception:
return None
def survey(date):
env = _env()
out = {"date": date, "generated": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")}
sm = os.path.join(LOGDIR, "upgrades", f"upgrade-all-{date}.md")
out["upgrade_summary_md"] = open(sm).read() if os.path.exists(sm) else None
repos = _gitea_get("/orgs/recipe-maintainers/repos?limit=100", env) or []
recipes = sorted(r["name"] for r in repos if r["name"] not in INFRA and not r["name"].startswith("archived-"))
out["recipes"] = []
for r in recipes:
prs = _gitea_get(f"/repos/recipe-maintainers/{r}/pulls?state=open&limit=50", env) or []
rec = {"recipe": r, "open_prs": []}
for p in prs:
sha = p["head"]["sha"]
st = _gitea_get(f"/repos/recipe-maintainers/{r}/commits/{sha}/status", env) or {}
ci = {"state": st.get("state")}
for s in (st.get("statuses") or []):
if s.get("context") == "cc-ci/testme":
ci = {"state": s.get("state"), "url": s.get("target_url"), "desc": s.get("description")}
rec["open_prs"].append({"number": p["number"], "title": p["title"],
"url": p["html_url"], "head": sha,
"base": p.get("base", {}).get("sha"),
"created_at": p.get("created_at"),
"updated_at": p.get("updated_at"),
"mergeable": p.get("mergeable"), "ci": ci})
# Per-recipe upgrade plan/summary (has the breaking-change + CVE/security analysis) — the agent
# mines this to lead with critical-CVE upgrades.
nf = os.path.join(LOGDIR, "upgrades", f"{r}-upgrade-{date}.md")
rec["upgrade_notes_md"] = open(nf).read() if os.path.exists(nf) else None
out["recipes"].append(rec)
print(json.dumps(out, indent=2))
# ---------- newspaper HTML ----------
CSS = """
:root{--ink:#1a1a1a;--mut:#555;--rule:#111;--bg:#e8e4d9;--paper:#fbf9f3;--red:#9b1c1c;--accent:#6b4e00}
*{box-sizing:border-box}
body{font:18px/1.65 Georgia,'Times New Roman',serif;color:var(--ink);background:var(--bg);margin:0;padding:2rem 1rem 4rem}
.paper{max-width:62rem;margin:0 auto;background:var(--paper);padding:2.4rem 2.6rem 3rem;box-shadow:0 2px 10px rgba(0,0,0,.12)}
.mast{text-align:center;border-bottom:4px double var(--rule);padding-bottom:.4rem}
.mast .kicker{font-size:.78rem;font-weight:700;text-transform:uppercase;letter-spacing:.22em;color:var(--mut)}
.mast h1{font-size:3.7rem;line-height:1;margin:.25rem 0 .35rem;font-weight:900;letter-spacing:-.02em}
.dateline{display:flex;flex-wrap:wrap;gap:.5rem;justify-content:space-between;font-size:.76rem;text-transform:uppercase;letter-spacing:.09em;color:var(--mut);border-bottom:1px solid var(--rule);padding:.35rem 0;margin-bottom:1.5rem}
.lead{font-size:1.16rem;line-height:1.72}
.lead p{margin:.4rem 0}
.lead p:first-of-type::first-letter{float:left;font-size:3.6rem;line-height:.78;padding:.08rem .55rem .05rem 0;font-weight:900}
.kicker{font-size:.74rem;font-weight:700;text-transform:uppercase;letter-spacing:.14em;color:var(--red)}
h2{font-size:1.55rem;border-top:2px solid var(--rule);padding-top:.5rem;margin:2.1rem 0 .5rem;letter-spacing:-.01em}
.bulletin{border:2px solid var(--red);background:#fdf2f2;padding:1rem 1.2rem;margin:1.6rem 0}
.bulletin h2{border:0;margin:.1rem 0 .5rem;padding:0;color:var(--red);font-size:1.5rem}
.story{margin:.7rem 0;padding-bottom:.7rem;border-bottom:1px solid #d8d2c2}
.story .h{font-weight:700;font-size:1.1rem;line-height:1.3}
.story .b{margin:.2rem 0 .35rem;color:#2b2b2b}
.links a{font-size:.84rem;margin-right:.7rem}
a{color:#0b3d91;text-decoration:none}a:hover{text-decoration:underline}
.cols{column-count:2;column-gap:2.2rem}.cols .story{break-inside:avoid}
@media(max-width:640px){.cols{column-count:1}.mast h1{font-size:2.5rem}.paper{padding:1.4rem}}
table{border-collapse:collapse;width:100%;font:14px/1.45 Georgia,serif;margin-top:.5rem}
th,td{text-align:left;padding:.42rem .55rem;border-bottom:1px solid #ccc;vertical-align:top}
th{border-bottom:2px solid var(--rule);font-size:.72rem;text-transform:uppercase;letter-spacing:.05em;color:var(--mut)}
.s-GREEN{color:#1a7a3c;font-weight:700}.s-RED,.s-FAILED{color:var(--red);font-weight:700}
.s-STALE{color:var(--accent);font-weight:700}.s-SKIPPED,.s-UPTODATE{color:var(--mut)}
footer{margin-top:2.6rem;border-top:4px double var(--rule);padding-top:.8rem;font-size:.82rem;color:var(--mut);text-align:center}
.idx{list-style:none;padding:0}.idx li{padding:.55rem 0;border-bottom:1px solid #d8d2c2;font-size:1.1rem}
.idx .d{color:var(--mut);font-size:.85rem;float:right}
td .cve{color:var(--red);font-weight:800}.muted{color:#999}
.pr-status{white-space:nowrap}
.pr-open{display:inline-block;font:700 .66rem/1 Georgia,serif;text-transform:uppercase;letter-spacing:.07em;color:#9b6b00;background:#fff3d6;border:1px solid #e3c98a;border-radius:.2rem;padding:.13rem .42rem}
.pr-done{color:#1a7a3c;font-weight:800;font-size:1.05rem}
.addendum-h{font-size:1rem;font-weight:700;text-transform:uppercase;letter-spacing:.08em;margin:1.7rem 0 .3rem;color:var(--ink)}
ul.addendum{margin:.2rem 0 1.2rem 1.2rem;padding:0}ul.addendum li{margin:.35rem 0;line-height:1.55}
.change{margin:.8rem 0;padding-bottom:.7rem;border-bottom:1px solid #d8d2c2}
.change .ch{font-weight:700;font-size:1.12rem}.change .cb{margin:.2rem 0 .35rem;color:#2b2b2b}
"""
# Inline (CSP-safe, dependency-free) script that lights up the live PR-STATUS column. For each
# `.pr-status[data-pr]` cell it GETs the same-origin /pr/<recipe>/<n> proxy (see reports.nix in the
# cc-ci repo) and renders BINARY state: `state==='open'` -> an "open" badge; any other state
# (closed/merged) -> a green ✓ (the title shows merged vs closed). It refreshes every 30s so an open
# tab tracks state in realtime, and is fully resilient — a network/parse error leaves a muted "?" and
# never overwrites a value already resolved, so the page renders fully even if the proxy is down.
STATUS_JS = """
(function(){
function refresh(){
document.querySelectorAll('.pr-status[data-pr]').forEach(function(cell){
var repo=cell.getAttribute('data-repo'), pr=cell.getAttribute('data-pr');
if(!repo||!pr) return;
fetch('/pr/'+encodeURIComponent(repo)+'/'+encodeURIComponent(pr),{headers:{'Accept':'application/json'}})
.then(function(r){ if(!r.ok) throw 0; return r.json(); })
.then(function(d){
var st=d&&d.state;
if(st==='open'){ cell.innerHTML='<span class="pr-open">open</span>'; cell.dataset.ok='1'; }
else if(st){ cell.innerHTML='<span class="pr-done" title="'+(d.merged?'merged':'closed')+'">\\u2713</span>'; cell.dataset.ok='1'; }
else throw 0;
})
.catch(function(){ if(!cell.dataset.ok){ cell.innerHTML='<span class="muted" title="live status unavailable">?</span>'; } });
});
}
if(document.readyState!=='loading'){ refresh(); } else { document.addEventListener('DOMContentLoaded', refresh); }
setInterval(refresh, 30000);
})();
"""
def _esc(s):
return html.escape(str(s or ""))
def _linkify_recipes(text, repo_url):
"""Linkify whole-word recipe-name mentions to their mirror repo. ONE pass over the (already
HTML-escaped) text, longest names first so 'custom-html-tiny' wins over 'custom-html'; re.sub does
not re-scan inserted hrefs, so URLs that end in a recipe name aren't double-linked."""
if not repo_url:
return text
names = sorted(repo_url, key=len, reverse=True)
pat = re.compile(r"(?<![\w-])(" + "|".join(re.escape(n) for n in names) + r")(?![\w-])")
return pat.sub(lambda m: f'<a href="{repo_url[m.group(1)]}">{m.group(1)}</a>', text)
def _links(links):
if not links:
return ""
return '<div class="links">' + " · ".join(
f'<a href="{_esc(l["url"])}">{_esc(l["text"])}</a>' for l in links) + "</div>"
def _stories(items, repo_url=None):
if not items:
return "<p><em>Nothing this week.</em></p>"
lk = (lambda x: _linkify_recipes(_esc(x), repo_url)) if repo_url else _esc
return "\n".join(
f'<div class="story"><div class="h">{lk(it.get("title"))}</div>'
f'<div class="b">{lk(it.get("body"))}</div>{_links(it.get("links"))}</div>' for it in items)
def _table(rows, repo_url=None):
if not rows:
return ""
# TESTS = the CI/test verdict (GREEN/FAILED/STALE/…); STATUS = the PR's LIVE state, fetched
# client-side (open vs ✓ for any not-open state) by the inline script in _page().
head = ("<tr><th>Recipe</th><th>Change</th><th>TESTS</th><th>CVEs</th>"
"<th>CI</th><th>PR</th><th>STATUS</th><th>Notes</th></tr>")
trs = []
for r in rows:
scls = "s-" + str(r.get("status", "")).upper().replace("-", "").replace(" ", "")
name = _esc(r.get("recipe"))
if repo_url and r.get("recipe") in repo_url:
name = f'<a href="{repo_url[r["recipe"]]}">{name}</a>'
cve = r.get("cve")
# "?" = advisory scan absent or had failed sources → count NOT authoritative. Per the
# /recipe-report guardrail this must NEVER render as "none" (a blank-that-reads-clean is
# exactly how two CVSS-9.8 gitea RCEs were misreported as "none" on 2026-08-07). A positive
# int is the confirmed CVE count; 0/omit is a confirmed-clean scan.
if isinstance(cve, str) and cve.strip() == "?":
cve_cell = '<span class="muted" title="advisory scan incomplete or absent — CVE count unknown">?</span>'
elif isinstance(cve, str) and cve.strip().upper() == "YES":
cve_cell = '<span class="cve">YES</span>'
elif isinstance(cve, (int, float)) and cve:
cve_cell = f'<span class="cve">{int(cve)}</span>'
else:
cve_cell = '<span class="muted">none</span>'
ci = _esc(r.get("ci"))
if r.get("ci_url"):
ci = f'<a href="{_esc(r["ci_url"])}">{ci}</a>'
pr = _esc(r.get("pr"))
if r.get("pr_url"):
pr = f'<a href="{_esc(r["pr_url"])}">{pr}</a>'
# Live PR-STATUS cell: a JS hook carrying the repo + PR number derived from the existing
# `recipe` + `pr` fields. The inline script fills it from /pr/<recipe>/<n>. Blank when no PR.
recipe = r.get("recipe") or ""
m = re.search(r"\d+", str(r.get("pr") or ""))
if m and recipe:
status_cell = (f'<td class="pr-status" data-repo="{_esc(recipe)}" '
f'data-pr="{_esc(m.group(0))}"><span class="muted">…</span></td>')
else:
status_cell = "<td></td>"
trs.append(f"<tr><td>{name}</td><td>{_esc(r.get('change'))}</td>"
f'<td class="{scls}">{_esc(r.get("status"))}</td><td>{cve_cell}</td>'
f"<td>{ci}</td><td>{pr}</td>{status_cell}<td>{_esc(r.get('notes'))}</td></tr>")
return f"<table>{head}{''.join(trs)}</table>"
def _changes(items, repo_url=None):
"""Per-recipe 'what changed' sections (one per recipe that has a PR)."""
if not items:
return ""
lk = (lambda x: _linkify_recipes(_esc(x), repo_url)) if repo_url else _esc
out = []
for c in items:
name = c.get("recipe")
hdr = _esc(name)
if repo_url and name in repo_url:
hdr = f'<a href="{repo_url[name]}">{hdr}</a>'
out.append(f'<div class="change"><div class="ch">{hdr}</div>'
f'<div class="cb">{lk(c.get("body"))}</div>{_links(c.get("links"))}</div>')
return "\n".join(out)
def _page(title, body):
# The live-status script ships on every page (reports + archive index); harmless where there are
# no `.pr-status` cells. Self-contained: inline CSS + inline JS, no external requests.
return (f'<!doctype html><html lang="en"><head><meta charset="utf-8">'
f'<meta name="viewport" content="width=device-width,initial-scale=1">'
f"<title>{_esc(title)}</title><style>{CSS}</style></head>"
f'<body><div class="paper">{body}</div><script>{STATUS_JS}</script></body></html>')
def _mast():
return ('<div class="mast"><div class="kicker">Co-op Cloud Recipe CI · Weekly Edition</div>'
'<h1>The Recipe Report</h1></div>')
def render(spec_path, out_path):
s = json.load(open(spec_path))
kind = s.get("kind", "week")
title = KINDS.get(kind, KINDS["week"])[0]
gen = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")
sub = s.get("subtitle", ("Week of " if kind == "week" else "CVE check ") + s["date"])
lead = s.get("lead", "") or ""
# Auto-link recipe-name mentions in the lead to their mirror repos.
gitea = _env().get("GITEA_URL", "git.autonomic.zone")
repo_url = {r["recipe"]: f"https://{gitea}/recipe-maintainers/{r['recipe']}"
for r in (s.get("table") or []) if r.get("recipe")}
if lead and "<p>" not in lead:
lead = "".join(f"<p>{_linkify_recipes(_esc(p.strip()), repo_url)}</p>"
for p in lead.split("\n\n") if p.strip())
body = (_mast() +
f'<div class="dateline"><span>{_esc(sub)}</span>'
f'<span>report.ci.autonomic.zone</span><span>{gen}</span></div>'
f'<div class="lead">{lead}</div>')
# 1) the full wire — every recipe, in the agent's recommended priority order (CVEs first); CVEs column.
wire = ("The full wire — every recipe, in priority order" if kind == "week"
else "Advisory sweep — every recipe, worst first")
body += f'<h2>{wire}</h2>{_table(s.get("table"), repo_url)}'
# 2) addendum — special issues to look into (normal-size header); omitted entirely if there are none.
add = [a for a in (s.get("addendum") or []) if str(a).strip()]
if add:
body += ('<p class="addendum-h">Addendum</p><ul class="addendum">'
+ "".join(f"<li>{_linkify_recipes(_esc(b), repo_url)}</li>" for b in add) + "</ul>")
# 3) security bulletin
if s.get("security"):
body += ('<div class="bulletin"><div class="kicker">Security Bulletin</div>'
'<h2>🔒 Critical CVE upgrades</h2>' + _stories(s["security"], repo_url) + "</div>")
# 4) what changed — a short section per recipe that has a PR
if s.get("changes"):
body += f'<h2>What changed</h2>{_changes(s.get("changes"), repo_url)}'
body += (f'<footer>{title} · generated {gen} · '
f'<a href="https://ci.autonomic.zone/">dashboard</a> · <a href="./">archive</a></footer>')
open(out_path, "w").write(_page(f"{title} · " + s["date"], body))
print("wrote", out_path)
def publish(html_path, date, kind="week"):
if kind not in KINDS:
print(f"unknown kind {kind!r}; expected one of {', '.join(KINDS)}"); sys.exit(2)
page = f"{kind}-{date}.html"
subprocess.run(["ssh", "cc-ci", f"cat > {HOST_REPORTS}/{page}"], input=open(html_path, "rb").read(), check=True)
# One index over BOTH families, newest first, each row labelled by its kind — an operator looking
# for "the latest security picture" should not have to know which skill produced which page.
entries = []
for k in KINDS:
listing = subprocess.run(["ssh", "cc-ci", f"ls -1 {HOST_REPORTS}/{k}-*.html 2>/dev/null"],
capture_output=True, text=True).stdout.split()
for pth in listing:
d = os.path.basename(pth)[len(k) + 1:-5]
if re.fullmatch(r"\d{4}-\d{2}-\d{2}", d):
entries.append((d, k))
lis = "\n".join(
f'<li><a href="{k}-{d}.html">{KINDS[k][1].format(d=d)}</a><span class="d">{d}</span></li>'
for d, k in sorted(set(entries), reverse=True))
idx = _page("The Recipe Report — Archive", _mast() +
'<div class="dateline"><span>Weekly review of Co-op Cloud recipe upgrades &amp; CI</span>'
'<span>report.ci.autonomic.zone</span></div>'
f'<ul class="idx">{lis or "<li><em>No reports yet.</em></li>"}</ul>')
subprocess.run(["ssh", "cc-ci", f"cat > {HOST_REPORTS}/index.html"], input=idx.encode(), check=True)
print(f"published https://report.ci.autonomic.zone/{page} (+ index)")
def main():
a = sys.argv[1:]
cmd = a[0] if a else "survey"
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
if cmd == "survey":
survey(a[1] if len(a) > 1 else today)
elif cmd == "render":
render(a[1], a[2])
elif cmd == "publish":
publish(a[1], a[2], a[3] if len(a) > 3 else "week")
else:
print(__doc__); sys.exit(2)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/recipe-report.py
-63
View File
@@ -1,63 +0,0 @@
#!/usr/bin/env bash
# reconcile-upstream — sync recipe mirrors from TRUE upstream. Run this FIRST, always.
# ----------------------------------------------------------------------------------
# Every recipe we maintain is a MIRROR of a coopcloud recipe. Work done against a stale
# mirror is wasted or wrong, in three ways we have actually hit:
#
# 1. A PR whose changes upstream ALREADY MERGED. mailu #6 (2024.06.57 + redis 8.10,
# two internet-facing Roundcube CVEs) sat open and was reported as the fix for
# those CVEs — while upstream had merged and released it as 3.1.3+2024.06.57. The
# work was done; only our mirror was behind.
# 2. A survey that reads the stale mirror and reports "no upgrades available", so a
# recipe silently drops out of the weekly run.
# 3. Reading the WRONG BRANCH. Several coopcloud recipes keep a stale `main` beside
# the real default `master` — gitea's `main` is at 1.24.2-rootless while `master`
# has 1.27.1-rootless plus the merged PRs. Reading `main` there says the recipe is
# three releases behind and missing two CVSS-9.8 RCE fixes, which reads exactly
# like a real finding. open-recipe-pr.sh resolves the default branch itself
# (main OR master) — never hand-pick one.
#
# This is deterministic: it force-syncs each mirror's `main` to upstream's default
# branch and closes any mirror PR whose changes are already upstream. No AI judgement.
#
# reconcile-upstream.sh <recipe>... # specific recipes
# reconcile-upstream.sh --all # every recipe in used-recipes.md
#
# Safe to run repeatedly; a mirror already in sync is a no-op. Recipe work lives in
# BRANCHES, never on mirror `main`, so force-syncing `main` discards nothing.
set -o errexit -o nounset -o pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
ORCH="$(dirname "$HERE")"
SSH="${SSH:-cc-ci}"
RECONCILE="${RECONCILE:-$ORCH/.claude/skills/recipe-upgrade/open-recipe-pr.sh}"
USED_RECIPES="${USED_RECIPES:-$HERE/used-recipes.md}"
[ -f "$RECONCILE" ] || { echo "ERROR: reconcile helper not found: $RECONCILE" >&2; exit 1; }
set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a
: "${GITEA_USERNAME:?}"; : "${GITEA_PASSWORD:?}"; : "${GITEA_URL:=git.autonomic.zone}"
if [ "${1:-}" = "--all" ]; then
mapfile -t RECIPES < <(awk '!/^[[:space:]]*#/ && ($2=="weekly" || $2=="external") {print $1}' "$USED_RECIPES")
else
[ "$#" -gt 0 ] || { echo "usage: reconcile-upstream.sh <recipe>... | --all" >&2; exit 2; }
RECIPES=("$@")
fi
synced=0; closed=0; failed=0
for r in "${RECIPES[@]}"; do
echo "── $r"
if out="$(ssh "$SSH" "GITEA_USERNAME='$GITEA_USERNAME' GITEA_PASSWORD='$GITEA_PASSWORD' GITEA_URL='$GITEA_URL' bash -s $r --reconcile-only" < "$RECONCILE" 2>&1)"; then
printf '%s\n' "$out" | grep -E "Force-syncing|already in sync|closed PR|still open|✓" | sed 's/^/ /' || true
synced=$((synced + 1))
closed=$((closed + $(printf '%s' "$out" | grep -c "closed PR" || true)))
else
printf '%s\n' "$out" | tail -3 | sed 's/^/ /'
echo " ✗ FAILED — do NOT proceed against this mirror until it reconciles"
failed=$((failed + 1))
fi
done
echo
echo "reconcile-upstream: ${synced} mirror(s) synced, ${closed} already-upstream PR(s) closed, ${failed} failed"
[ "$failed" -eq 0 ]
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/reconcile-upstream.sh
-519
View File
@@ -1,519 +0,0 @@
#!/usr/bin/env python3
"""resolve-images — what version is each of a recipe's images on, and what is newest?
An abra-independent version resolver. `abra recipe upgrade` is the normal path, but it has a hard
failure mode: an image pinned with BOTH a tag and a digest makes it FATA and abandon the WHOLE
recipe — even images it already parsed. immich pins two that way:
ghcr.io/immich-app/postgres:14-vectorchord0.4.3-pgvectors0.2.0@sha256:bcf6…
docker.io/valkey/valkey:9@sha256:3acc…
so immich contributes NO version data at all and silently drops out of every survey. That is
indistinguishable from "up to date" unless a human notices the missing row — which is exactly how it
kept getting skipped, and why a CVE sweep reported it as unknown.
This reads the compose files directly and queries the registries itself, so a digest pin is just a
digest pin. Output is JSON (default) or a table.
resolve-images.py <recipe> [--ssh HOST] [--recipe-dir DIR] [--table] [--only IMAGE]
The cc-ci host has no python3, so `--ssh cc-ci` reads the compose files from that host's checkout
over ssh and does the resolving locally. That keeps the source of truth the SAME tree abra and CI
use, rather than a second copy that can drift.
TAG SHAPES. Registries mix wildly different tag conventions in one repo, so "newest" is meaningless
without a shape. Each tag is reduced to a signature by replacing digit runs with '#':
v3.1.0 -> v#.#.#
1.27.1-rootless -> #.#.#-rootless
8.10-alpine -> #.#-alpine
14-vectorchord0.4.3-pgvectors0.2.0 -> #-vectorchord#.#.#-pgvectors#.#.#
Only tags sharing the CURRENT pin's shape are candidates. That keeps `-alpine` on `-alpine`, and
stops a `latest`/`release`/`sha-…` tag from ever being proposed as an upgrade.
TWO ANSWERS, NOT ONE. It reports `newest_same_shape` AND `newest_within_major` (same leading number).
For a plain app image they usually agree. For a compatibility-pinned sidecar they do not, and taking
the max would be wrong: immich's postgres tag encodes the pg major plus the vectorchord/pgvectors
versions that immich-server is built against, so jumping pg major because a newer tag exists breaks
the deployment. The caller picks; this tool refuses to guess and shows both.
"""
from __future__ import annotations
import argparse
import glob
import shlex
import subprocess
import gzip
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
UA = "cc-ci-resolve-images (+https://git.autonomic.zone/recipe-maintainers/cc-ci)"
TIMEOUT = int(os.environ.get("RESOLVE_IMAGES_TIMEOUT", "45"))
RECIPE_DIR = os.environ.get("ABRA_RECIPE_DIR", os.path.expanduser("~/.abra/recipes"))
MAX_TAG_PAGES = int(os.environ.get("RESOLVE_IMAGES_MAX_PAGES", "40"))
IMAGE_RE = re.compile(r"""^\s*image:\s*["']?([^"'\s]+)["']?\s*$""", re.M)
RETRIES = int(os.environ.get("RESOLVE_IMAGES_RETRIES", "4"))
def _fetch(url: str, headers: dict | None = None) -> bytes:
"""GET with backoff on rate limits.
Docker Hub throttles anonymous clients hard, and a sweep re-reads the same popular repos
(nginx, redis, postgres) for recipe after recipe. A 429 mid-sweep used to surface as
'unresolved', which is indistinguishable from a real lookup failure — so retry, and let the
per-repo cache below remove most of the requests entirely."""
h = {"User-Agent": UA, "Accept-Encoding": "gzip"}
h.update(headers or {})
delay = 2.0
for attempt in range(RETRIES):
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=h), timeout=TIMEOUT) as r:
raw = r.read()
if r.headers.get("Content-Encoding") == "gzip":
raw = gzip.decompress(raw)
return raw
except urllib.error.HTTPError as e:
if e.code in (429, 503) and attempt < RETRIES - 1:
time.sleep(delay)
delay *= 2
continue
raise
raise RuntimeError("unreachable")
_HUB_JWT: list = []
def _hub_auth() -> dict:
"""Authenticated Docker Hub calls get a far higher rate limit than anonymous ones.
Credentials come from /srv/cc-ci/.testenv (DOCKERHUB_USERNAME / DOCKERHUB_TOKEN), the same pair
the CI host already uses. Absent creds are fine — the sweep just runs anonymous and slower."""
if _HUB_JWT:
return _HUB_JWT[0]
env = {}
try:
for ln in open(os.environ.get("CCCI_TESTENV", "/srv/cc-ci/.testenv")):
if "=" in ln and not ln.strip().startswith("#"):
k, v = ln.strip().split("=", 1)
env[k] = v.strip().strip("\"'")
except OSError:
pass
u = os.environ.get("DOCKERHUB_USERNAME") or env.get("DOCKERHUB_USERNAME")
t = os.environ.get("DOCKERHUB_TOKEN") or env.get("DOCKERHUB_TOKEN")
hdrs = {}
if u and t:
try:
body = json.dumps({"username": u, "password": t}).encode()
req = urllib.request.Request("https://hub.docker.com/v2/users/login",
data=body, method="POST",
headers={"Content-Type": "application/json", "User-Agent": UA})
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
tokj = json.load(r).get("token")
if tokj:
hdrs = {"Authorization": f"JWT {tokj}"}
except Exception: # noqa: BLE001 — anonymous is a valid fallback
hdrs = {}
_HUB_JWT.append(hdrs)
return hdrs
def _json(url: str, headers: dict | None = None):
return json.loads(_fetch(url, headers))
def shape(tag: str) -> str:
"""Signature of a tag with every digit run replaced by '#'. See module docstring."""
return re.sub(r"\d+", "#", tag)
def vkey(tag: str) -> tuple:
"""Ordering key: every number in the tag, in order. '1.27.10' > '1.27.9'; text ignored."""
return tuple(int(x) for x in re.findall(r"\d+", tag))
def parse_ref(ref: str) -> dict:
"""Split an image reference into registry / repo / tag / digest."""
digest = None
if "@" in ref:
ref, _, digest = ref.partition("@")
host, repo, tag = "docker.io", ref, "latest"
# A leading component is a REGISTRY only when there is a path after it. Without the slash test,
# a bare `postgres:15.18` looks like host "postgres:15.18" because of the tag's colon — which
# silently sent every library image to a nonexistent registry.
if "/" in ref:
first = ref.split("/")[0]
if "." in first or ":" in first or first == "localhost":
host, _, repo = ref.partition("/")
if ":" in repo.split("/")[-1]:
repo, _, tag = repo.rpartition(":")
if host == "docker.io" and "/" not in repo:
repo = f"library/{repo}" # bare `redis` is really `library/redis`
return {"registry": host, "repo": repo, "tag": tag, "digest": digest}
HUB_RECENT_PAGES = int(os.environ.get("RESOLVE_IMAGES_HUB_PAGES", "40"))
_HUB_TRUNCATED: set[str] = set()
def _hub_tag_exists(repo: str, tag: str) -> bool:
try:
_json(f"https://hub.docker.com/v2/repositories/{repo}/tags/{tag}", _hub_auth())
return True
except Exception: # noqa: BLE001
return False
def _hub_tags(repo: str) -> list[str]:
"""Recently-pushed tags, newest first.
Popular Docker Hub repos carry many thousands of tags, so enumerate a bounded recent window.
A rebuilt old tag can displace a newer version from that window, so callers MUST treat a
truncated listing with no detected upgrade as unverified, not current. (ghcr offers no recency
ordering, which is why that path needs a different strategy.)
"""
tags, url = [], (f"https://hub.docker.com/v2/repositories/{repo}/tags"
f"?page_size=100&ordering=last_updated")
auth = _hub_auth()
for _ in range(HUB_RECENT_PAGES):
d = _json(url, auth)
tags += [r["name"] for r in d.get("results", [])]
url = d.get("next")
if not url:
break
if url:
_HUB_TRUNCATED.add(repo)
return tags
def _oci_bearer(host: str, repo: str) -> dict:
"""Token for an OCI registry, discovered from its own auth challenge.
Registries do NOT share a token endpoint. ghcr answers at /token?scope=…&service=ghcr.io, but
lscr.io and dock.mau.dev advertise different realms, and assuming ghcr's shape made both 401 —
which then read as "could not resolve" rather than "asked the wrong URL". The registry tells us
where to go in its WWW-Authenticate header; use that."""
try:
urllib.request.urlopen(
urllib.request.Request(f"https://{host}/v2/{repo}/tags/list?n=1",
headers={"User-Agent": UA}), timeout=TIMEOUT)
return {} # no auth needed
except urllib.error.HTTPError as e:
if e.code != 401:
return {}
chal = e.headers.get("WWW-Authenticate", "") or ""
except Exception: # noqa: BLE001
return {}
if not chal.lower().startswith("bearer"):
return {}
parts = dict(re.findall(r'(\w+)="([^"]*)"', chal))
realm = parts.get("realm")
if not realm:
return {}
q = {"service": parts.get("service", host), "scope": parts.get("scope", f"repository:{repo}:pull")}
url = realm + ("&" if "?" in realm else "?") + urllib.parse.urlencode(q)
try:
tok = (_json(url) or {}).get("token") or (_json(url) or {}).get("access_token")
return {"Authorization": f"Bearer {tok}"} if tok else {}
except Exception: # noqa: BLE001
return {}
def _oci_tags(host: str, repo: str) -> list[str]:
"""Tags from any OCI/v2 registry, with challenge-derived auth and Link pagination.
ghcr paginates hard — immich-server has >40,000 tags — and a truncated listing silently hides
the newest release line, so follow the cursor and let the caller's integrity check catch a read
that never reached the current pin."""
hdrs = _oci_bearer(host, repo)
tags, url = [], f"https://{host}/v2/{repo}/tags/list?n=1000"
for _ in range(MAX_TAG_PAGES):
for attempt in range(RETRIES):
req = urllib.request.Request(url, headers={"User-Agent": UA, **hdrs})
try:
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
tags += (json.load(r) or {}).get("tags") or []
link = r.headers.get("Link", "") or ""
break
except urllib.error.HTTPError as e:
if e.code not in (429, 503) or attempt == RETRIES - 1:
raise
retry_after = e.headers.get("Retry-After") or ""
delay = min(int(retry_after) if retry_after.isdigit() else 2 ** (attempt + 1), 60)
time.sleep(delay)
m = re.search(r'<([^>]+)>;\s*rel="next"', link)
if not m:
break
nxt = m.group(1)
url = f"https://{host}{nxt}" if nxt.startswith("/") else nxt
else:
raise RuntimeError(f"tag listing truncated after {MAX_TAG_PAGES} pages")
return tags
def _gh_token() -> str | None:
tok = os.environ.get("GITHUB_TOKEN")
if tok:
return tok.strip()
try:
return open(os.environ.get("GITHUB_TOKEN_FILE", "/srv/cc-ci/.github-token")).read().strip() or None
except OSError:
return None
def github_release_tags(owner: str, repo: str, max_pages: int = 4) -> list[str]:
"""Release tag names for a GitHub repo, newest first.
FALLBACK for registries whose tag listing cannot be enumerated. ghcr has no ordering and no
server-side filter, and immich-machine-learning carries >40,000 tags — a full read is impractical
and a partial read silently hides the newest release line. The project's RELEASES are ordered,
small, and authoritative: container tags track them. (The GitHub Packages API would answer this
directly but needs a scoped token; this scan's token deliberately has none.)
"""
hdrs = {"Accept": "application/vnd.github+json"}
tok = _gh_token()
if tok:
hdrs["Authorization"] = f"Bearer {tok}"
out = []
for page in range(1, max_pages + 1):
try:
rows = _json(f"https://api.github.com/repos/{owner}/{repo}/releases"
f"?per_page=100&page={page}", hdrs)
except Exception: # noqa: BLE001
break
if not rows:
break
out += [r.get("tag_name") or "" for r in rows]
return [t for t in out if t]
def _release_fallback_repos(registry: str, repo: str) -> list[tuple[str, str]]:
"""Candidate GitHub repos whose releases track this image's tags."""
if "ghcr.io" not in registry:
return []
parts = repo.split("/")
if len(parts) < 2:
return []
owner, name = parts[0], parts[-1]
cands = [(owner, name)]
# ghcr.io/immich-app/immich-machine-learning is built from immich-app/immich.
if name.startswith(owner.split("-")[0]):
cands.append((owner, owner.split("-")[0]))
return cands
def _oci_tag_exists(host: str, repo: str, tag: str) -> bool:
"""Verify a release candidate is actually published as an image manifest."""
hdrs = {"User-Agent": UA,
"Accept": "application/vnd.oci.image.index.v1+json, "
"application/vnd.docker.distribution.manifest.list.v2+json, "
"application/vnd.oci.image.manifest.v1+json",
**_oci_bearer(host, repo)}
url = f"https://{host}/v2/{repo}/manifests/{urllib.parse.quote(tag, safe='')}"
try:
with urllib.request.urlopen(urllib.request.Request(url, headers=hdrs, method="HEAD"),
timeout=TIMEOUT) as response:
return response.status == 200
except urllib.error.HTTPError as e:
if e.code == 404:
return False
raise
def _release_manifest_fallback(registry: str, repo: str, current: str) -> tuple[list[str], str] | None:
"""For huge GHCR registries, use release tags only after checking actual manifests."""
for owner, name in _release_fallback_repos(registry, repo):
releases = github_release_tags(owner, name)
if current not in releases:
continue # incomplete release window; it cannot establish a current baseline
candidates = sorted((tag for tag in set(releases)
if shape(tag) == shape(current) and vkey(tag) >= vkey(current)),
key=vkey, reverse=True)
for tag in candidates:
if _oci_tag_exists(registry, repo, tag):
return [current, tag], f"github-releases+registry-manifest:{owner}/{name}"
return None
_TAG_CACHE: dict[tuple[str, str], tuple[list[str], str | None]] = {}
def list_tags(registry: str, repo: str) -> tuple[list[str], str | None]:
if (registry, repo) in _TAG_CACHE:
return _TAG_CACHE[(registry, repo)]
res = _list_tags_uncached(registry, repo)
_TAG_CACHE[(registry, repo)] = res
return res
def _list_tags_uncached(registry: str, repo: str) -> tuple[list[str], str | None]:
try:
return (_hub_tags(repo) if registry in ("docker.io", "registry-1.docker.io")
else _oci_tags(registry, repo)), None
except urllib.error.HTTPError as e:
return [], f"HTTP {e.code}"
except Exception as e: # noqa: BLE001
return [], f"{type(e).__name__}: {e}"
def resolve(ref: str) -> dict:
"""Current pin -> newest same-shape tag, and newest within the current major."""
if "${" in ref or "$(" in ref:
# The tag is a compose variable (ghost pins `ghost:${IMAGE_VERSION}-alpine`). Its real value
# lives in .env, not here. Report it as skipped, never as a failed lookup.
return {**parse_ref(ref), "ref": ref, "shape": None, "candidates": 0,
"newest_same_shape": None, "newest_within_major": None,
"upgrade_available": False,
"status": "skipped: templated ref (tag comes from a compose variable)"}
info = parse_ref(ref)
out = {**info, "ref": ref, "shape": shape(info["tag"]), "status": "ok",
"newest_same_shape": None, "newest_within_major": None, "candidates": 0,
"upgrade_available": False}
tags, err = list_tags(info["registry"], info["repo"])
if err:
try:
fallback = (_release_manifest_fallback(info["registry"], info["repo"], info["tag"])
if "tag listing truncated" in err else None)
except Exception as e: # noqa: BLE001 — a failed fallback must stay unresolved
out["status"] = f"error: registry {err}; release fallback {type(e).__name__}: {e}"
return out
if not fallback:
out["status"] = f"error: {err}"
return out
tags, out["source"] = fallback
out["tags_seen"] = len(set(tags))
# INTEGRITY CHECK: the tag we are currently running MUST appear in the listing. If it does not,
# the listing is incomplete and any "newest" derived from it is a guess — ghcr paginates to tens
# of thousands of tags and a truncated read silently hides whole release lines. immich's
# machine-learning image is pinned v3.1.0, which EXISTS, yet a short read reported v1.134.0 as
# newest; without this check that becomes a confident, wrong answer.
if info["tag"] not in set(tags):
# Docker Hub: the window is recency-ordered, so the pin being outside it just means the pin
# is old — which is fine, because anything NEWER is necessarily inside the window. Confirm
# the pin genuinely exists (so a typo is still caught) and carry on.
if info["registry"] in ("docker.io", "registry-1.docker.io") and _hub_tag_exists(info["repo"], info["tag"]):
out["source"] = f"docker-hub:recent-{HUB_RECENT_PAGES * 100}"
tags = list(tags) + [info["tag"]]
else:
for owner, name in _release_fallback_repos(info["registry"], info["repo"]):
rel = github_release_tags(owner, name)
if info["tag"] in rel:
tags = rel
out["source"] = f"github-releases:{owner}/{name}"
out["tags_seen"] = len(set(rel))
break
else:
out["status"] = ("error: tag listing incomplete — the current pin "
f"{info['tag']!r} is absent from {len(set(tags))} registry tags "
f"and from the project's GitHub releases")
return out
want, cur = out["shape"], vkey(info["tag"])
same = [t for t in set(tags) if shape(t) == want and vkey(t)]
out["candidates"] = len(same)
if not same:
# A floating or unusual tag cannot prove that an image is current. Keep it visible to
# callers rather than letting an empty candidate set become a false UPTODATE verdict.
out["status"] = "unverifiable: no comparable numeric tags"
return out
newest = max(same, key=vkey)
out["newest_same_shape"] = newest
if cur:
within = [t for t in same if vkey(t)[:1] == cur[:1]]
if within:
out["newest_within_major"] = max(within, key=vkey)
out["upgrade_available"] = bool(cur and vkey(newest) > cur)
if (info["registry"] in ("docker.io", "registry-1.docker.io")
and info["repo"] in _HUB_TRUNCATED and not out["upgrade_available"]):
out["status"] = (f"unverifiable: Docker Hub listing truncated after "
f"{HUB_RECENT_PAGES * 100} recent tags")
return out
def compose_images_ssh(recipe: str, host: str, recipe_dir: str) -> list[str]:
"""Same as compose_images, but the recipe tree lives on another host (cc-ci has no python3)."""
# NB: no shell-quoting of the directory — it may legitimately start with ~ or $HOME, and
# quoting it stops the remote shell expanding it, which yields an empty (and silent) result.
d = f"{recipe_dir}/{shlex.quote(recipe)}".replace("~", "$HOME")
cmd = (f'for f in {d}/compose*.yml; do case "$f" in *compose.ccci.yml) continue;; esac; '
f'[ -f "$f" ] && {{ cat "$f"; echo; }}; done; exit 0')
out = subprocess.run(["ssh", host, cmd], capture_output=True, text=True, timeout=120)
if out.returncode != 0:
raise RuntimeError(f"ssh {host}: {(out.stderr.strip() or 'no output')[:200]}")
if not out.stdout.strip():
raise RuntimeError(f"ssh {host}: no compose files found under {d}")
refs = []
for m in IMAGE_RE.finditer(out.stdout):
if m.group(1) not in refs:
refs.append(m.group(1))
return refs
def compose_images(recipe: str, recipe_dir: str) -> list[str]:
"""Every `image:` ref in the recipe's own compose files (the cc-ci overlay is NOT the recipe)."""
refs, base = [], os.path.join(recipe_dir, recipe)
for path in sorted(glob.glob(os.path.join(base, "compose*.yml"))):
if os.path.basename(path) == "compose.ccci.yml":
continue
try:
for m in IMAGE_RE.finditer(open(path).read()):
if m.group(1) not in refs:
refs.append(m.group(1))
except OSError:
continue
return refs
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("recipe")
ap.add_argument("--ssh", default=None, metavar="HOST",
help="read the recipe's compose files from HOST over ssh (e.g. --ssh cc-ci); "
"resolving still happens locally")
ap.add_argument("--recipe-dir", default=RECIPE_DIR)
ap.add_argument("--table", action="store_true", help="human-readable table instead of JSON")
ap.add_argument("--only", default=None, help="resolve just the images whose ref contains this")
a = ap.parse_args()
rdir = a.recipe_dir if a.recipe_dir != RECIPE_DIR or not a.ssh else "~/.abra/recipes"
refs = (compose_images_ssh(a.recipe, a.ssh, rdir) if a.ssh
else compose_images(a.recipe, a.recipe_dir))
if a.only:
refs = [r for r in refs if a.only in r]
results = [resolve(r) for r in refs]
report = {
"recipe": a.recipe,
"images": results,
"upgrades_available": [r["ref"] for r in results if r["upgrade_available"]],
"unresolved": [r["ref"] for r in results if r["status"].startswith(("error", "skipped", "unverifiable"))],
# The whole point: distinguish "checked, current" from "could not check".
"all_resolved": bool(results) and all(r["status"] == "ok" for r in results),
}
if not a.table:
print(json.dumps(report, indent=2))
return 0
print(f"{a.recipe} — {len(results)} images")
for r in results:
flag = "UPGRADE" if r["upgrade_available"] else ("UNKNOWN" if r["status"] != "ok" else "current")
print(f" [{flag:7}] {r['repo']}:{r['tag']}" + (" (digest-pinned)" if r["digest"] else ""))
print(f" shape={r['shape']} candidates={r['candidates']}"
f" newest_same_shape={r['newest_same_shape']}"
f" newest_within_major={r['newest_within_major']}")
if r["status"] != "ok":
print(f" status: {r['status']}")
return 0
if __name__ == "__main__":
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/resolve-images.py
-43
View File
@@ -1,43 +0,0 @@
# Assistant task — consolidate open recipe PRs (one open PR per recipe)
**Dispatched:** 2026-06-02 by the orchestrator. **Owner:** the Assistant (one-shot). **Not** the
Builder/Adversary loops — they are busy on the regression phase; do not touch their clones.
## Goal
Every recipe mirror should have **at most ONE open PR**. For any recipe with more than one open PR,
combine them into a single open PR (the union of their changes) and close the rest.
## Steps
1. **Survey.** Creds in `/srv/cc-ci/.testenv` (`GITEA_USERNAME`/`GITEA_PASSWORD`/`GITEA_URL`). For every
**recipe** mirror under the `recipe-maintainers` org, list its open PRs:
- `GET /api/v1/orgs/recipe-maintainers/repos?limit=100`
- `GET /api/v1/repos/recipe-maintainers/<recipe>/pulls?state=open`
Recipes = real recipe mirrors only — **exclude** infra repos: `cc-ci`, `cc-ci-orchestrator`,
`cc-ci-secrets`, `archived-*`. Build the list of recipes with **>1** open PR.
2. **Consolidate** each such recipe into ONE open PR holding the union of the changes, then close the others:
- Work in a **fresh clone** of the mirror (e.g. under `/tmp`). **Never** use the loops' clones
(`/srv/cc-ci/cc-ci`, `/srv/cc-ci/cc-ci-adv`).
- Combine the open PR branches onto one branch (cherry-pick/merge). **Never force-push over unmerged
work** — preserve every change. Prefer **extending the lowest-numbered open PR** by pushing the
combined branch onto its head (the no-force "commit on top" pattern in
`/srv/cc-ci/.claude/skills/recipe-upgrade/open-recipe-pr.sh`).
- **Conflict policy:** two upgrade PRs to different versions → keep the **newest** version. An upgrade
PR + a different-purpose PR (e.g. a backup/restore fix) → include **both** changes.
- **Close** the now-redundant PRs with a comment: `Consolidated into #<N> — one open PR per recipe.`
- **Re-test** the surviving consolidated PR by commenting `!testme` on it (real CI; results show in
the PR; iterate up to 3×). If a genuine pre-existing failure blocks it, leave an explanatory
comment — do **not** weaken/skip/delete any test.
3. **Report & stop.** Summarise: which recipes had >1 open PR, what you consolidated, the surviving PR
URL per recipe, conflicts resolved, and any PR left red with an explanatory comment. Then go idle
(one-shot — do not loop).
## Guardrails
- **NEVER merge any PR into `main`** — the operator merges. "Merge them together" = consolidate multiple
open PRs into ONE open PR, **not** merge to main.
- Only touch **recipe mirror** PRs. Do **not** touch cc-ci-repo PRs (build/test PRs).
- Recipes with 0 or 1 open PR: leave untouched.
- Known starting point (re-verify live — state may have changed): `custom-html` had 2 upgrade PRs
(#1 1.12.0, #2 1.13.0); `ghost` had #1 (backup fix) + #2 (upgrade). Survey fresh for the full set.
+1
View File
@@ -0,0 +1 @@
../archive/plans/cc-ci-plan/task-consolidate-recipe-prs.md
-955
View File
@@ -1,955 +0,0 @@
#!/usr/bin/env python3
"""Tests for advisory-scan.py.
Two tiers:
OFFLINE (default) — pure logic, fixtures injected in place of the network. Fast, deterministic,
no token, no rate limit. These encode every classification rule and every guarantee the CVE count
makes, including the specific production defects that motivated them.
LIVE (--live) — re-derives the CVE counts published in the week-2026-08-07 report against the real
advisory APIs. Slow, needs network + ideally a GitHub token. Run before changing classification.
Usage:
python3 test-advisory-scan.py # offline only
python3 test-advisory-scan.py --live # offline + historic report regressions
"""
from __future__ import annotations
import importlib.util
import io
import json
import os
import pathlib
import tempfile
import sys
import unittest
import unittest.mock
HERE = pathlib.Path(__file__).resolve().parent
_spec = importlib.util.spec_from_file_location("advisory_scan", HERE / "advisory-scan.py")
A = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(A)
# ── fixture helpers ───────────────────────────────────────────────────────────────────────────────
def adv(cve, patched=None, published=None, severity="high", ghsa=None):
"""One GitHub advisory row as github_advisories() would emit it."""
return {"cve": cve, "ghsa": ghsa or f"GHSA-fake-{cve[-4:]}", "severity": severity,
"summary": f"summary for {cve}", "vulnerable_range": None, "patched": patched,
"url": None, "published_at": published}
def gh(owner_repo, advisories, status="ok"):
return {"source": f"github-advisories:{owner_repo}", "status": status, "advisories": advisories}
def vendor(url, cves=(), status="ok"):
return {"source": url, "status": status, "cves": list(cves),
"context": {c: f"...{c}..." for c in cves}}
def run_scan(gh_entries=(), vendor_entries=(), tag_dates=None, *, v_from=None, v_to=None,
images=None, recipe="fixture", urls=None, releases=None, image_sources=None):
"""scan() with every network call replaced by fixtures.
`releases` maps CVE id -> tags whose release notes name it (the third, release-note method)."""
tag_dates = tag_dates or {}
releases = releases or {}
urls = urls if urls is not None else ["https://github.com/app/app"]
with unittest.mock.patch.object(A, "registry_urls", lambda r, d: (list(urls), "/fake/reg.md")), \
unittest.mock.patch.object(A, "github_advisories", lambda u: list(gh_entries)), \
unittest.mock.patch.object(A, "vendor_pages", lambda u: list(vendor_entries)), \
unittest.mock.patch.object(A, "registry_image_sources", lambda r, d: image_sources or {}), \
unittest.mock.patch.object(A, "osv", lambda r, v: None), \
unittest.mock.patch.object(A, "_tag_date", lambda o, r, v: tag_dates.get(v)), \
unittest.mock.patch.object(A, "release_fix_versions", lambda src, cve: list(releases.get(cve, []))):
return A.scan(recipe, v_from, v_to, "/fake", images)
def parse_image_args(argv):
"""Drive main()'s --image parsing exactly as the CLI does, returning the tuples scan() receives."""
captured = {}
def fake_scan(recipe, vf, vt, reg, images):
captured["images"] = images
return {"recipe": recipe, "from": vf, "to": vt, "registry": reg, "registry_urls": 0,
"sources": [], "cves": {}, "fixed_by_this_upgrade": [], "unclassified": [],
"sources_failed": [], "sources_benign": [], "count_known": True,
"cve_count_fixed": 0, "windows": {}, "classified_by": {}}
err = io.StringIO()
with unittest.mock.patch.object(A, "scan", fake_scan), \
unittest.mock.patch.object(sys, "argv", ["advisory-scan.py", *argv]), \
unittest.mock.patch.object(sys, "stdout", io.StringIO()), \
unittest.mock.patch.object(sys, "stderr", err):
A.main()
return captured["images"], err.getvalue()
# ── A. version ordering ───────────────────────────────────────────────────────────────────────────
class TestVersionKey(unittest.TestCase):
def test_strips_prefix_and_suffix(self):
self.assertEqual(A._vkey("v1.27.1"), (1, 27, 1))
self.assertEqual(A._vkey("1.27.1-rootless"), (1, 27, 1))
self.assertEqual(A._vkey("2024.06.55"), (2024, 6, 55))
def test_empty_and_none(self):
self.assertEqual(A._vkey(None), ())
self.assertEqual(A._vkey(""), ())
def test_dotted_minor_is_numeric_not_lexical(self):
# The bug this guards: "8.10" must be NEWER than "8.2.3". String compare says otherwise.
self.assertGreater(A._vkey("8.10"), A._vkey("8.2.3"))
self.assertGreater(A._vkey("1.27.10"), A._vkey("1.27.9"))
def test_shorter_prefix_orders_below_its_own_patch(self):
# 7.4 < 7.4.1, so a CVE patched in 7.4.1 IS fixed by moving off a bare 7.4 pin.
self.assertLess(A._vkey("7.4"), A._vkey("7.4.1"))
class TestWindowMembership(unittest.TestCase):
"""(from, to] membership — exclusive lower, inclusive upper, compared zero-padded."""
def _in(self, f, t, c):
return A._within(A._vkey(f), A._vkey(t), A._vkey(c))
def test_bounds(self):
self.assertTrue(self._in("1.27.0", "1.27.1", "1.27.1")) # upper inclusive
self.assertFalse(self._in("1.27.0", "1.27.1", "1.27.0")) # lower exclusive
self.assertFalse(self._in("1.27.0", "1.27.1", "1.26.9"))
self.assertFalse(self._in("1.27.0", "1.27.1", "1.28.0"))
def test_bare_major_upper_bound_includes_its_dot_zero(self):
# Regression: plain tuple order makes (18,) < (18,0), so a fix in 18.0 fell OUTSIDE a
# window ending at 18. Bare major tags are the norm for sidecars (postgres:18, redis:8).
self.assertTrue(self._in("17", "18", "18.0"))
self.assertTrue(self._in("7", "8", "8.0"))
self.assertTrue(self._in("7.4", "8.10", "8.0.4"))
def test_bare_major_upper_bound_excludes_later_patches(self):
# Conservative on the other side: nothing proves which 18.x a floating tag resolved to.
self.assertFalse(self._in("17", "18", "18.5"))
def test_bare_version_is_read_literally_as_dot_zero(self):
# from="8" means 8.0, so a fix in 8.0.4 is inside a window that ends at 9.
self.assertTrue(self._in("8", "9", "8.0.4"))
self.assertFalse(self._in("8", "9", "8.0")) # == the stated lower bound
def test_prefix_lower_bound_still_counts_its_patches(self):
self.assertTrue(self._in("7.4", "8.10", "7.4.1"))
self.assertTrue(self._in("7.4", "8.10", "7.4.6"))
def test_the_false_133_cve_stays_out(self):
self.assertFalse(self._in("7.4", "8.10", "6.0.11"))
# ── B. registry URL extraction ────────────────────────────────────────────────────────────────────
class TestRegistryUrls(unittest.TestCase):
def _write(self, tmp, text):
p = pathlib.Path(tmp) / "r.md"
p.write_text(text)
return A.registry_urls("r", tmp)
def test_prose_ellipsis_is_not_a_security_source(self):
with tempfile.TemporaryDirectory() as directory:
urls, _ = self._write(directory,
"https://github.com/cryptpad/cryptpad and example `https://…` URLs "
"http://docspec:3000/conversion http://127.0.0.1:3000/health")
self.assertEqual(urls, ["https://github.com/cryptpad/cryptpad"])
def test_image_source_table_maps_monorepo_images(self):
mapping = A.registry_image_sources("lasuite-drive", str(HERE / "upstream"))
self.assertIn("github-advisories:suitenumerique/drive", mapping["drive-backend"])
self.assertIn("github-advisories:CollaboraOnline/online", mapping["code"])
def test_common_database_cpes_follow_registry_images(self):
self.assertIn(("postgres", A.COMMON_IMAGE_CPES["postgres"]),
A.registry_cpes("immich", str(HERE / "upstream")))
self.assertIn(("mariadb", A.COMMON_IMAGE_CPES["mariadb"]),
A.registry_cpes("gitea", str(HERE / "upstream")))
self.assertIn(("rustdesk-server", "cpe:2.3:a:rustdesk:rustdesk_server:*:*:*:*:oss:*:*:*"),
A.registry_cpes("rustdesk-server", str(HERE / "upstream")))
def test_strips_trailing_markdown_punctuation(self):
# Production defect: a captured backtick 404'd the fetch and rendered n8n/immich as '?'.
import tempfile
with tempfile.TemporaryDirectory() as tmp:
urls, _ = self._write(tmp, "see `https://docs.n8n.io/release-notes/` and "
"**https://example.com/sec.html**, plus https://a.test/x.")
self.assertIn("https://docs.n8n.io/release-notes/", urls)
self.assertIn("https://example.com/sec.html", urls)
self.assertIn("https://a.test/x", urls)
self.assertFalse([u for u in urls if u.endswith(("`", "*", ".", ","))])
def test_dedupes_and_reports_missing_registry(self):
import tempfile
with tempfile.TemporaryDirectory() as tmp:
urls, path = self._write(tmp, "https://a.test/x https://a.test/x")
self.assertEqual(urls.count("https://a.test/x"), 1)
self.assertTrue(path.endswith("r.md"))
urls, path = A.registry_urls("does-not-exist", "/nonexistent-dir")
self.assertEqual((urls, path), ([], None))
class TestNvdCompleteness(unittest.TestCase):
def test_truncated_results_are_not_a_clean_zero(self):
payload = json.dumps({"totalResults": 2, "vulnerabilities": [{"cve": {"id": "CVE-2026-0001"}}]})
with unittest.mock.patch.object(A, "_fetch", return_value=payload):
row = A.nvd_advisories("cpe:2.3:a:example:server:*:*:*:*:*:*:*:*", "server")
self.assertEqual(row["status"], "error: NVD result set truncated")
self.assertEqual(row["advisories"], [])
def test_database_backport_is_not_credited_again_on_major_upgrade(self):
ranges = [
{"version": "*", "versionStartIncluding": "15.0", "versionEndExcluding": "15.14"},
{"version": "*", "versionStartIncluding": "16.0", "versionEndExcluding": "16.5"},
]
self.assertIs(A._nvd_affects("15.13", ranges), True)
self.assertIs(A._nvd_affects("15.19", ranges), False)
self.assertIs(A._nvd_affects("18.6", ranges), False)
self.assertIsNone(A._nvd_affects("15-alpine", ranges))
# ── C. --image argument parsing ───────────────────────────────────────────────────────────────────
class TestImageArgParsing(unittest.TestCase):
def test_single_and_repeated(self):
imgs, _ = parse_image_args(["r", "--image", "redis=7.4:8.10"])
self.assertEqual(imgs, [("redis", "7.4", "8.10")])
imgs, _ = parse_image_args(["r", "--image", "redis=7.4:8.10", "--image", "postgres=17:18"])
self.assertEqual(imgs, [("redis", "7.4", "8.10"), ("postgres", "17", "18")])
def test_malformed_is_skipped_with_a_warning_not_a_crash(self):
# It is an ADDITIVE pre-step: one typo must not abort the upgrade's scan step.
for bad in ("redis=7.4", "redis", "=7.4:8.10", "redis=:8.10", "redis=7.4:"):
imgs, err = parse_image_args(["r", "--image", bad])
self.assertEqual(imgs, [], f"{bad!r} should be rejected")
self.assertIn("malformed", err)
def test_good_and_bad_mixed_keeps_the_good(self):
imgs, err = parse_image_args(["r", "--image", "redis=7.4:8.10", "--image", "nope"])
self.assertEqual(imgs, [("redis", "7.4", "8.10")])
self.assertIn("malformed", err)
# ── D. classification ─────────────────────────────────────────────────────────────────────────────
class TestClassificationBoundaries(unittest.TestCase):
def _one(self, patched, v_from="1.27.0", v_to="1.27.1"):
rep = run_scan([gh("app/app", [adv("CVE-2026-0001", patched=patched)])],
v_from=v_from, v_to=v_to)
return rep
def test_patched_at_upper_bound_counts(self):
self.assertEqual(self._one("1.27.1")["fixed_by_this_upgrade"], ["CVE-2026-0001"])
def test_patched_at_lower_bound_does_not_count(self):
# Already fixed in the version we were ON — this upgrade did not fix it.
rep = self._one("1.27.0")
self.assertEqual(rep["fixed_by_this_upgrade"], [])
self.assertEqual(rep["cve_count_fixed"], 0)
def test_patched_below_and_above_window_do_not_count(self):
self.assertEqual(self._one("1.26.0")["fixed_by_this_upgrade"], [])
self.assertEqual(self._one("1.28.0")["fixed_by_this_upgrade"], [])
def test_any_of_several_patched_lines_counts(self):
# n8n regression: one advisory patches several release lines; reading only the first
# dropped the line the deployment was on (CVE-2026-42231/42232 misclassified).
rep = self._one("1.123.32; 2.17.4; 2.18.1", v_from="2.17.0", v_to="2.17.4")
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2026-0001"])
def test_no_patched_data_is_not_counted(self):
self.assertEqual(self._one(None)["fixed_by_this_upgrade"], [])
class TestPerImageWindows(unittest.TestCase):
"""The false-133 family of defects: an image must only ever be judged by its OWN versions."""
APP = gh("discourse/discourse", [adv("CVE-APP-0001", patched="3.5.4", published="2026-03-01T00:00:00Z")])
REDIS = gh("redis/redis", [
adv("CVE-2021-21309", patched="6.0.11", published="2021-02-01T00:00:00Z"),
adv("CVE-2025-49844", patched="7.4.6; 8.0.4; 8.2.2", published="2025-10-01T00:00:00Z",
severity="critical"),
])
URLS = ["https://github.com/discourse/discourse", "https://github.com/redis/redis"]
def test_sidecar_cve_is_not_judged_by_the_app_window(self):
# redis 6.0.11 sits numerically inside discourse 3.5.3 -> 2026.7.1. It must NOT count.
rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="2026.7.1",
tag_dates={"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"},
urls=self.URLS)
self.assertNotIn("CVE-2021-21309", rep["fixed_by_this_upgrade"])
self.assertIn("CVE-2021-21309", rep["unclassified"])
def test_unwindowed_image_is_unclassified_never_counted(self):
rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4", urls=self.URLS)
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-APP-0001"])
for cve in ("CVE-2021-21309", "CVE-2025-49844"):
self.assertIn(cve, rep["unclassified"])
def test_sidecar_window_counts_only_what_that_bump_fixed(self):
rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4",
images=[("redis", "7.4", "8.10")], urls=self.URLS)
self.assertIn("CVE-2025-49844", rep["fixed_by_this_upgrade"]) # patched 7.4.6, in window
self.assertNotIn("CVE-2021-21309", rep["fixed_by_this_upgrade"]) # patched 6.0.11, below it
self.assertEqual(rep["cve_count_fixed"], 2) # app 1 + redis 1
def test_count_is_the_union_across_images(self):
rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="3.5.4",
images=[("redis", "7.4", "8.10")], urls=self.URLS)
self.assertEqual(sorted(rep["fixed_by_this_upgrade"]), ["CVE-2025-49844", "CVE-APP-0001"])
def test_each_image_classified_independently(self):
# App crosses a scheme change (date method); redis does not (version method). Both resolve.
rep = run_scan([self.APP, self.REDIS], v_from="3.5.3", v_to="2026.7.1",
images=[("redis", "7.4", "8.10")], urls=self.URLS,
tag_dates={"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"})
methods = rep["classified_by"]
self.assertIn("publish date", methods["github-advisories:discourse/discourse"])
self.assertEqual(methods["github-advisories:redis/redis"], "patched version ranges")
self.assertTrue(rep["count_known"])
def test_image_name_matches_as_substring(self):
rep = run_scan([self.APP, gh("discourse/discourse-postgres", [adv("CVE-PG-1", patched="18.0")])],
v_from="3.5.3", v_to="3.5.4", images=[("postgres", "17", "18")],
urls=["https://github.com/discourse/discourse",
"https://github.com/discourse/discourse-postgres"])
self.assertIn("github-advisories:discourse/discourse-postgres", rep["windows"])
self.assertIn("CVE-PG-1", rep["fixed_by_this_upgrade"])
def test_primary_cannot_be_stolen_by_a_loose_image_name(self):
rep = run_scan([self.APP, gh("discourse/discourse-postgres", [adv("CVE-PG-1", patched="18.0")])],
v_from="3.5.3", v_to="3.5.4", images=[("discourse", "1", "2")],
urls=["https://github.com/discourse/discourse",
"https://github.com/discourse/discourse-postgres"])
self.assertEqual(rep["windows"]["github-advisories:discourse/discourse"],
{"from": "3.5.3", "to": "3.5.4"})
def test_unmatched_image_name_makes_count_unknown(self):
# A typo'd sidecar name must not silently turn its CVEs into a clean zero.
rep = run_scan([self.APP], v_from="3.5.3", v_to="3.5.4",
images=[("nosuchimage", "1", "2")], urls=self.URLS[:1])
self.assertEqual(list(rep["windows"]), ["github-advisories:discourse/discourse"])
self.assertFalse(rep["count_known"])
self.assertEqual(rep["unmatched_image_windows"], ["nosuchimage"])
self.assertIsNone(rep["cve_count_fixed"])
def test_registry_maps_image_to_differently_named_source(self):
rep = run_scan([self.APP, gh("suitenumerique/drive", [adv("CVE-DRIVE-1", patched="0.25.3")])],
v_from="3.5.3", v_to="3.5.4", images=[("drive-backend", "0.22.0", "0.25.3")],
urls=self.URLS,
image_sources={"drive-backend": {"github-advisories:suitenumerique/drive"}})
self.assertEqual(rep.get("unmatched_image_windows"), None)
self.assertIn("CVE-DRIVE-1", rep["fixed_by_this_upgrade"])
def test_monorepo_images_share_identical_window(self):
source = "github-advisories:suitenumerique/drive"
rep = run_scan([gh("suitenumerique/drive", [adv("CVE-DRIVE-1", patched="0.25.3")])],
v_from="0.22.0", v_to="0.25.3",
images=[("drive-backend", "0.22.0", "0.25.3")],
image_sources={"drive-backend": {source}})
self.assertTrue(rep["count_known"])
self.assertEqual(rep.get("unmatched_image_windows"), None)
self.assertEqual(rep["cve_count_fixed"], 1)
class TestSchemeChangeDateFallback(unittest.TestCase):
DATES = {"3.5.3": "2025-12-30T00:00:00Z", "2026.7.1": "2026-07-31T00:00:00Z"}
def _rep(self, advisories, dates=None):
return run_scan([gh("discourse/discourse", advisories)], v_from="3.5.3", v_to="2026.7.1",
tag_dates=self.DATES if dates is None else dates)
def test_counts_advisories_published_inside_the_date_window(self):
rep = self._rep([adv("CVE-IN-1", published="2026-03-01T00:00:00Z"),
adv("CVE-OUT-1", published="2025-06-01T00:00:00Z"),
adv("CVE-OUT-2", published="2026-09-01T00:00:00Z")])
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-IN-1"])
def test_date_boundaries_match_the_version_rule(self):
# Exclusive lower, inclusive upper — same as 4a, so the two methods agree at the edges.
rep = self._rep([adv("CVE-LOWER", published=self.DATES["3.5.3"]),
adv("CVE-UPPER", published=self.DATES["2026.7.1"])])
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-UPPER"])
def test_advisory_without_a_publish_date_is_not_counted(self):
self.assertEqual(self._rep([adv("CVE-NODATE", published=None)])["fixed_by_this_upgrade"], [])
def test_scheme_change_is_detected_not_version_compared(self):
rep = self._rep([adv("CVE-IN-1", patched="2026.1.0", published="2026-03-01T00:00:00Z")])
self.assertIn("publish date", rep["classified_by"]["github-advisories:discourse/discourse"])
self.assertIn("github-advisories:discourse/discourse", rep["date_window"])
def test_small_major_bump_still_uses_version_ranges(self):
rep = run_scan([gh("app/app", [adv("CVE-X", patched="3.0.0")])], v_from="2.9.0", v_to="3.0.0")
self.assertEqual(rep["classified_by"]["github-advisories:app/app"], "patched version ranges")
# ── E. count guarantees ───────────────────────────────────────────────────────────────────────────
class TestCountGuarantees(unittest.TestCase):
def test_unresolvable_window_yields_unknown_never_zero(self):
# Scheme change AND tag dates unresolvable -> must refuse to emit a number.
rep = run_scan([gh("app/app", [adv("CVE-1", published="2026-01-01T00:00:00Z")])],
v_from="3.5.3", v_to="2026.7.1", tag_dates={})
self.assertIs(rep["cve_count_fixed"], None)
self.assertFalse(rep["count_known"])
md = A.markdown(rep)
self.assertIn("UNKNOWN", md)
self.assertIn("NOT zero", md)
def test_one_unresolvable_image_makes_the_whole_count_unknown(self):
# A partial number would understate a security figure, so it is suppressed entirely.
rep = run_scan([gh("app/app", [adv("CVE-APP", patched="1.1")]),
gh("redis/redis", [adv("CVE-REDIS", patched="8.0")])],
v_from="1.0", v_to="1.1", images=[("redis", "7.4", "9999.1")],
tag_dates={}, urls=["https://github.com/app/app", "https://github.com/redis/redis"])
self.assertIs(rep["cve_count_fixed"], None)
self.assertFalse(rep["count_known"])
def test_genuine_zero_is_reported_as_zero(self):
rep = run_scan([gh("app/app", [adv("CVE-1", patched="9.9.9")])], v_from="1.0", v_to="1.1")
self.assertEqual(rep["cve_count_fixed"], 0)
self.assertTrue(rep["count_known"])
self.assertIn("0 identified", A.markdown(rep))
def test_ghsa_without_cve_is_preserved_as_security_advisory(self):
entry = {"cve": None, "ghsa": "GHSA-aaaa-bbbb-cccc", "severity": "low",
"patched": "1.1", "summary": "security fix", "published_at": None}
rep = run_scan([gh("app/app", [entry])], v_from="1.0", v_to="1.1")
self.assertTrue(rep["count_known"])
self.assertEqual(rep["cve_count_fixed"], 0)
self.assertEqual(rep["fixed_non_cve_advisories"], ["GHSA-aaaa-bbbb-cccc"])
self.assertIn("use YES", A.markdown(rep))
def test_404_advisory_feed_is_benign_not_a_failure(self):
rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")]),
gh("side/car", [], status="no-advisories-published")],
v_from="1.0", v_to="1.1")
self.assertEqual(rep["sources_failed"], [])
self.assertIn("github-advisories:side/car", rep["sources_benign"])
self.assertEqual(rep["cve_count_fixed"], 1)
def test_template_url_is_benign_not_a_failure(self):
rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")])],
[vendor("https://x.test/changelog/v<VERSION>/", status="skipped: template URL")],
v_from="1.0", v_to="1.1")
self.assertEqual(rep["sources_failed"], [])
def test_real_source_failure_is_surfaced(self):
rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")], status="error: HTTP 500")],
v_from="1.0", v_to="1.1")
self.assertIn("github-advisories:app/app", rep["sources_failed"])
self.assertIn("FAILED", A.markdown(rep))
self.assertFalse(rep["count_known"])
def test_only_404_feed_is_not_evidence_of_clean_scan(self):
rep = run_scan([gh("app/app", [], status="no-advisories-published")],
v_from="1.0", v_to="1.1")
self.assertTrue(rep["no_usable_sources"])
self.assertFalse(rep["count_known"])
def test_no_window_given_classifies_nothing(self):
rep = run_scan([gh("app/app", [adv("CVE-1", patched="1.1")])])
self.assertEqual(rep["fixed_by_this_upgrade"], [])
self.assertIn("CVE-1", rep["unclassified"])
class TestVendorOnlyCves(unittest.TestCase):
"""The gitea case: CVEs named ONLY on a vendor page, absent from the GitHub advisory feed."""
def test_vendor_only_cve_is_recorded_and_surfaced(self):
rep = run_scan([gh("go-gitea/gitea", [])],
[vendor("https://blog.gitea.com/release-1.27.1/", ["CVE-2026-60004"])],
v_from="1.27.0", v_to="1.27.1")
self.assertIn("CVE-2026-60004", rep["cves"])
self.assertIn("CVE-2026-60004", rep["unclassified"])
def test_vendor_only_cve_is_NOT_counted_but_IS_sent_for_judgement(self):
# It carries no version data, so no arithmetic can place it — the deterministic count must
# not include it. It must not be silently dropped either: pass 2 gets it with its evidence.
rep = run_scan([gh("go-gitea/gitea", [])],
[vendor("https://blog.gitea.com/release-1.27.1/", ["CVE-2026-60004"])],
v_from="1.27.0", v_to="1.27.1")
self.assertEqual(rep["fixed_by_this_upgrade"], [])
self.assertEqual(rep["cve_count_fixed"], 0)
self.assertIn("CVE-2026-60004", A.needs_judgement(rep))
def test_cve_in_both_vendor_and_advisory_feed_is_counted_once(self):
rep = run_scan([gh("go-gitea/gitea", [adv("CVE-2026-60004", patched="1.27.1")])],
[vendor("https://blog.gitea.com/x/", ["CVE-2026-60004"])],
v_from="1.27.0", v_to="1.27.1")
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2026-60004"])
self.assertEqual(rep["cve_count_fixed"], 1)
self.assertEqual(len(rep["cves"]["CVE-2026-60004"]["sources"]), 2)
class TestIndeterminateBucket(unittest.TestCase):
"""An advisory with no knowable fix version is neither counted nor dismissed."""
def test_tbd_patched_is_indeterminate_not_excluded(self):
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
self.assertEqual(rep["fixed_by_this_upgrade"], [])
self.assertIn("CVE-TBD", rep["indeterminate"])
self.assertEqual(rep["cve_count_indeterminate"], 1)
def test_placeholder_patched_is_indeterminate(self):
# "7.4.X" could be 7.4.1 — inside the window. Extracting a bare 7.4 and excluding it was
# how CVE-2024-46981 (high) went missing.
rep = run_scan([gh("redis/redis", [adv("CVE-X", patched="6.2.X, 7.2.X, 7.4.X")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
self.assertIn("CVE-X", rep["indeterminate"])
def test_real_versions_outside_the_window_are_decided_not_indeterminate(self):
rep = run_scan([gh("redis/redis", [adv("CVE-OLD", patched="6.0.11")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
self.assertEqual(rep["indeterminate"], [])
self.assertEqual(rep["cve_count_fixed"], 0)
def test_indeterminate_is_surfaced_in_the_markdown_and_not_read_as_zero(self):
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD", severity="critical")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
md = A.markdown(rep)
self.assertIn("could NOT be judged", md)
self.assertIn("must NOT be read as unaffected", md)
class TestReleaseNoteResolution(unittest.TestCase):
"""Third method: a release whose notes NAME the CVE supplies the fix version the advisory lacks."""
def test_release_naming_the_cve_inside_the_window_counts_it(self):
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"],
releases={"CVE-TBD": ["6.2.19", "7.2.10", "7.4.5", "8.0.3"]})
self.assertIn("CVE-TBD", rep["fixed_by_this_upgrade"])
self.assertEqual(rep["indeterminate"], [])
self.assertEqual(rep["resolved_by_release_notes"]["CVE-TBD"], ["7.4.5", "8.0.3"])
def test_naming_releases_all_below_the_window_means_ALREADY_fixed(self):
# Every known fix predates the version we were already on, so this upgrade did not deliver
# it. That is a DECISION, not an unknown — mailu's redis 8.8.0 → 8.10.0 crosses 12 such
# advisories, and calling them "could not judge" overstates the uncertainty.
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"],
releases={"CVE-TBD": ["6.2.19"]})
self.assertEqual(rep["fixed_by_this_upgrade"], [])
self.assertEqual(rep["indeterminate"], [])
self.assertIn("CVE-TBD", rep["already_fixed_before_upgrade"])
self.assertIn("outside-window", rep["cves"]["CVE-TBD"]["classification"])
def test_naming_releases_only_ABOVE_the_window_stays_indeterminate(self):
# The fix landed after our target, so we are still exposed. Deliberately NOT decided as a
# tidy "not fixed": it is an open vulnerability and must stay visible to the operator.
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"],
releases={"CVE-TBD": ["9.0.0"]})
self.assertEqual(rep["fixed_by_this_upgrade"], [])
self.assertIn("CVE-TBD", rep["indeterminate"])
def test_vendor_page_cve_on_the_same_repo_uses_release_notes(self):
# mailu announces its Roundcube CVEs only on github.com/Mailu/Mailu/releases. Requiring an
# advisory feed sent a deterministic case to pass 2; it is now decided in pass 1.
rep = run_scan([gh("Mailu/Mailu", [])],
[vendor("https://github.com/Mailu/Mailu/releases", ["CVE-2026-54432"])],
v_from="2024.06.55", v_to="2024.06.57",
urls=["https://github.com/Mailu/Mailu"],
releases={"CVE-2026-54432": ["2024.06.56"]})
self.assertIn("CVE-2026-54432", rep["fixed_by_this_upgrade"])
self.assertEqual(rep["cve_count_fixed"], 1)
def test_release_evidence_is_recorded_for_audit(self):
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"],
releases={"CVE-TBD": ["7.4.5"]})
e = rep["cves"]["CVE-TBD"]
self.assertEqual(e["fix_versions_from_release_notes"], ["7.4.5"])
self.assertIn("named in release notes", e["classification"])
def test_it_does_not_override_a_version_range_decision(self):
# A CVE already counted by patched ranges is untouched; the method only rescues undecided.
rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"],
releases={"CVE-OK": ["7.4.1"]})
self.assertNotIn("CVE-OK", rep.get("resolved_by_release_notes") or {})
class TestReleaseLineSemantics(unittest.TestCase):
"""A fix inside the numeric window is not a fix on the branch you actually land on."""
def test_fix_later_on_the_targets_own_line_is_not_counted(self):
# ClickHouse fixed CVE-2023-48704 in 23.9.6.20 AND 23.10.5.20. Landing on 23.10.4.25 crosses
# the 23.9 fix numerically but is BELOW its own line's fix, so it does not have it.
rep = run_scan([gh("ClickHouse/ClickHouse",
[adv("CVE-2023-48704", patched="v23.10.5.20; v23.9.6.20; v23.8.8.20")])],
v_from="23.4.2.11", v_to="23.10.4.25",
urls=["https://github.com/ClickHouse/ClickHouse"])
self.assertEqual(rep["fixed_by_this_upgrade"], [])
def test_fix_earlier_on_the_targets_own_line_is_counted(self):
rep = run_scan([gh("ClickHouse/ClickHouse",
[adv("CVE-2023-47118", patched="v23.10.2.13; v23.8.6.16")])],
v_from="23.4.2.11", v_to="23.10.4.25",
urls=["https://github.com/ClickHouse/ClickHouse"])
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2023-47118"])
def test_fix_exactly_at_the_target_is_counted(self):
rep = run_scan([gh("ClickHouse/ClickHouse",
[adv("CVE-2023-48298", patched="v23.10.4.25; v23.9.5.29")])],
v_from="23.4.2.11", v_to="23.10.4.25",
urls=["https://github.com/ClickHouse/ClickHouse"])
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2023-48298"])
def test_no_fix_on_the_target_line_falls_back_to_the_window(self):
# redis fixes 7.4.6/8.0.4/8.2.2 with no 8.10.x entry; landing on 8.10 still has them,
# because nothing on the 8.10 line is named as a LATER fix.
rep = run_scan([gh("redis/redis", [adv("CVE-2025-49844", patched="7.4.6; 8.0.4; 8.2.2")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2025-49844"])
class TestAlreadyFixedOnFromLine(unittest.TestCase):
"""A fix that landed on the line we upgrade FROM was already ours before the upgrade."""
def test_backport_to_our_own_line_is_not_credited(self):
# mattermost patches every maintained line at once. 10.11.22 -> 10.12.4 crosses 10.12.1, but
# 10.11.22 is already past 10.11.4, so the deployment HAD the fix. Counting it credits the
# upgrade with work it did not do.
rep = run_scan([gh("mattermost/mattermost",
[adv("CVE-1", patched="10.11.4; 10.12.1; 10.5.12")])],
v_from="10.11.22", v_to="10.12.4",
urls=["https://github.com/mattermost/mattermost"])
self.assertEqual(rep["fixed_by_this_upgrade"], [])
def test_a_fix_ABOVE_our_position_on_the_same_line_still_counts(self):
rep = run_scan([gh("mattermost/mattermost", [adv("CVE-2", patched="10.11.30; 10.12.1")])],
v_from="10.11.22", v_to="10.12.4",
urls=["https://github.com/mattermost/mattermost"])
self.assertEqual(rep["fixed_by_this_upgrade"], ["CVE-2"])
def test_placeholders_never_feed_this_rule(self):
# "7.4.X" parses to a bare 7.4, which would read as "already fixed at 7.4" and silently drop
# a real fix — this is exactly how redis CVE-2024-46981 was lost when the rule was added.
rep = run_scan([gh("redis/redis", [adv("CVE-3", patched="6.2.X, 7.2.X, 7.4.X")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
self.assertIn("CVE-3", rep["indeterminate"])
self.assertEqual(rep["fixed_by_this_upgrade"], [])
class TestChangelogAttribution(unittest.TestCase):
"""Projects that publish no advisory feed still say which release fixed what — in their changelog."""
CHANGES = """
Changes with nginx 1.31.3 11 Aug 2026
*) Security: a flaw ... (CVE-2026-60005)
*) Security: another ... (CVE-2026-56434)
Changes with nginx 1.31.2 04 Aug 2026
*) Security: something ... (CVE-2026-48142)
Changes with nginx 1.31.1 21 Jul 2026
*) Security: older ... (CVE-2026-9256)
Changes with nginx 1.20.0 01 Jan 2021
*) Security: ancient ... (CVE-2013-2028)
"""
def test_each_cve_is_attributed_to_the_release_that_fixed_it(self):
got = A._changelog_versions(self.CHANGES)
self.assertEqual(got["CVE-2026-60005"], "1.31.3")
self.assertEqual(got["CVE-2026-48142"], "1.31.2")
self.assertEqual(got["CVE-2026-9256"], "1.31.1")
self.assertEqual(got["CVE-2013-2028"], "1.20.0")
def _scan(self, wfrom, wto):
# nginx publishes NO GitHub advisories — the feed is empty and the changelog is everything.
return run_scan(
[gh("nginx/nginx", [])],
[{"source": "https://nginx.org/en/CHANGES", "status": "ok",
"cves": sorted(A._changelog_versions(self.CHANGES)),
"context": {}, "fixed_in": A._changelog_versions(self.CHANGES)}],
images=[("nginx", wfrom, wto)], urls=["https://github.com/nginx/nginx"])
def test_window_counts_only_the_releases_it_crosses(self):
rep = self._scan("1.31.1", "1.31.3") # 1.31.1 is the FROM, so its CVE is already fixed
self.assertEqual(set(rep["fixed_by_this_upgrade"]),
{"CVE-2026-48142", "CVE-2026-56434", "CVE-2026-60005"})
def test_a_narrower_window_counts_fewer(self):
rep = self._scan("1.31.2", "1.31.3")
self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-56434", "CVE-2026-60005"})
def test_ancient_entries_are_not_swept_in(self):
# The changelog lists the project's whole history; only the crossed releases may count.
rep = self._scan("1.31.1", "1.31.3")
self.assertNotIn("CVE-2013-2028", rep["fixed_by_this_upgrade"])
def test_evidence_is_recorded(self):
rep = self._scan("1.31.1", "1.31.3")
self.assertEqual(rep["resolved_by_changelog"]["CVE-2026-60005"], "1.31.3")
class TestComposeDerivedWindows(unittest.TestCase):
"""Windows read off a compose diff, so nobody has to remember which --image args an upgrade needs."""
OLD = """
services:
app:
image: "plausible/analytics:v2.0.0"
db:
image: pgautoupgrade/pgautoupgrade:18-alpine
plausible_events_db:
image: clickhouse/clickhouse-server:23.4.2.11-alpine
volumes:
data:
"""
NEW = """
services:
app:
image: "ghcr.io/plausible/community-edition:v3.2.1"
db:
image: pgautoupgrade/pgautoupgrade:18-alpine
plausible_events_db:
image: clickhouse/clickhouse-server:24.12-alpine
volumes:
data:
"""
def _windows(self, old=None, new=None):
pages = {"to": new if new is not None else self.NEW,
"from": old if old is not None else self.OLD}
with unittest.mock.patch.object(A, "_fetch", lambda u, h=None: pages["to" if "to" in u else "from"]), \
unittest.mock.patch.object(A, "_gitea_auth", lambda u: {}):
return A.windows_from_compose("http://x/to", "http://x/from")[0]
def test_app_service_leads_and_sidecars_follow(self):
w = self._windows()
self.assertEqual(w[0], ("community-edition", "v2.0.0", "v3.2.1"))
self.assertIn(("clickhouse-server", "23.4.2.11-alpine", "24.12-alpine"), w)
def test_unchanged_images_are_not_windows(self):
# pgautoupgrade is identical in both; inventing a window for it would be a false count.
self.assertNotIn("pgautoupgrade", [n for n, _, _ in self._windows()])
def test_a_changed_image_REPO_is_still_the_same_service(self):
# plausible/analytics -> ghcr.io/plausible/community-edition. Keyed by image repo this reads
# as one image vanishing and another appearing, and the app window is lost entirely.
w = self._windows()
self.assertTrue(any(n == "community-edition" and f == "v2.0.0" for n, f, _ in w))
def test_no_change_yields_no_windows(self):
self.assertEqual(self._windows(old=self.NEW, new=self.NEW), [])
def test_lasuite_docs_pr_does_not_claim_preexisting_valkey_upgrade(self):
base = """services:
app:
image: lasuite/impress-frontend:v6.0.4
yhub-valkey:
image: valkey/valkey:9.1.3-alpine
docspec:
image: ghcr.io/docspecio/api:3.0.2
"""
head = base.replace("ghcr.io/docspecio/api:3.0.2", "ghcr.io/docspec/api:1.21.4")
windows = self._windows(old=base, new=head)
self.assertEqual(windows, [("api", "3.0.2", "1.21.4")])
self.assertNotIn("valkey", [name for name, _, _ in windows])
captured = {}
def fake_scan(recipe, v_from, v_to, registry, images):
captured.update(from_version=v_from, to_version=v_to, images=images)
return {"recipe": recipe, "from": v_from, "to": v_to,
"count_known": True, "cve_count_fixed": 0, "cves": {}, "sources": [],
"fixed_by_this_upgrade": [], "unclassified": [], "registry_urls": 0,
"sources_failed": [], "sources_benign": [], "windows": {},
"classified_by": {}}
with unittest.mock.patch.object(A, "windows_from_compose",
return_value=(windows, "pinned base", False)), \
unittest.mock.patch.object(A, "scan", fake_scan), \
unittest.mock.patch.object(sys, "argv", ["advisory-scan.py", "lasuite-docs",
"--compose-from", "base", "--compose-to", "head"]), \
unittest.mock.patch.object(sys, "stdout", io.StringIO()), \
unittest.mock.patch.object(sys, "stderr", io.StringIO()):
A.main()
self.assertIsNone(captured["from_version"])
self.assertEqual(captured["images"], windows)
def test_templated_tags_are_skipped(self):
new = self.NEW.replace('ghcr.io/plausible/community-edition:v3.2.1', 'ghost:${IMAGE_VERSION}')
self.assertNotIn("ghost", [n for n, _, _ in self._windows(new=new)])
class TestImageNameMatching(unittest.TestCase):
"""An image name and its advisory source rarely spell each other exactly."""
def test_matches_when_the_image_name_is_LONGER_than_the_source(self):
# clickhouse/clickhouse-server vs source ClickHouse/ClickHouse — one-directional matching
# dropped this window silently when the key came from a compose file.
rep = run_scan([gh("ClickHouse/ClickHouse", [adv("CVE-1", patched="23.10.2.13")])],
images=[("clickhouse-server", "23.4.2.11", "24.12")],
urls=["https://github.com/ClickHouse/ClickHouse"])
self.assertIn("github-advisories:ClickHouse/ClickHouse", rep["windows"])
self.assertEqual(rep["cve_count_fixed"], 1)
def test_matches_when_the_image_name_is_SHORTER_than_the_source(self):
rep = run_scan([gh("redis/redis", [adv("CVE-2", patched="7.4.1")])],
images=[("redis", "7.4", "8.10")], urls=["https://github.com/redis/redis"])
self.assertEqual(rep["cve_count_fixed"], 1)
class TestAdjudicationEvidenceAssembly(unittest.TestCase):
"""Pass 2's JUDGEMENT is a model's and not testable; what IS testable is what it gets shown."""
def test_selects_indeterminate_and_vendor_only_cases(self):
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
[vendor("https://blog.test/sec", ["CVE-VENDOR"])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
todo = A.needs_judgement(rep)
self.assertIn("CVE-TBD", todo)
self.assertIn("CVE-VENDOR", todo)
def test_does_not_re_ask_about_cases_pass_1_settled(self):
rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
self.assertNotIn("CVE-OK", A.needs_judgement(rep))
def test_evidence_bundle_carries_the_window_and_published_fields(self):
rep = run_scan([gh("redis/redis", [adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \
unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []):
ev = A.evidence_bundle(rep, "CVE-TBD")
self.assertEqual(ev["window"], {"from": "7.4", "to": "8.10"})
self.assertEqual(ev["patched_as_published"], "TBD")
self.assertIn("no fix version", ev["why_undecided"])
def test_pass_1_decisions_are_included_for_review(self):
rep = run_scan([gh("redis/redis", [adv("CVE-OK", patched="7.4.1"),
adv("CVE-OLD", patched="6.0.11"),
adv("CVE-TBD", patched="TBD")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \
unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []):
block = A.adjudication_block(rep)
self.assertIn("Pass 1 decisions", block)
self.assertIn("CVE-OK", block) # counted
self.assertIn("CVE-OLD", block) # excluded as outside-window
self.assertIn("CVE-TBD", block) # needs judgement
def test_truncation_is_announced_never_silent(self):
advs = [adv(f"CVE-2026-{1000+i}", patched="TBD") for i in range(30)]
rep = run_scan([gh("redis/redis", advs)], v_from="7.4", v_to="8.10",
urls=["https://github.com/redis/redis"])
with unittest.mock.patch.object(A, "advisory_text", lambda g, s=None: {"status": "skipped"}), \
unittest.mock.patch.object(A, "release_fix_versions", lambda s, c: []), \
unittest.mock.patch.object(A, "MAX_ADJUDICATE", 5):
block = A.adjudication_block(rep)
self.assertIn("not shown", block)
self.assertIn("do not", block.lower())
class TestMarkdownOutput(unittest.TestCase):
def test_lists_every_window_with_its_method(self):
rep = run_scan([gh("discourse/discourse", [adv("CVE-A", patched="3.5.4")]),
gh("redis/redis", [adv("CVE-B", patched="8.0")])],
v_from="3.5.3", v_to="3.5.4", images=[("redis", "7.4", "8.10")],
urls=["https://github.com/discourse/discourse", "https://github.com/redis/redis"])
md = A.markdown(rep)
self.assertIn("discourse/discourse: 3.5.3 → 3.5.4", md)
self.assertIn("redis/redis: 7.4 → 8.10", md)
self.assertIn("**CVEs fixed by this upgrade: 2**", md)
def test_severity_and_fixed_in_are_rendered(self):
rep = run_scan([gh("redis/redis", [adv("CVE-2025-49844", patched="7.4.6; 8.2.2",
severity="critical")])],
v_from="7.4", v_to="8.10", urls=["https://github.com/redis/redis"])
md = A.markdown(rep)
self.assertIn("critical", md)
self.assertIn("7.4.6", md)
# ── F. live regressions against published historic reports ────────────────────────────────────────
class TestHistoricReportNumbers(unittest.TestCase):
"""Re-derive counts published in week-2026-08-07. Network + GitHub token; opt in with --live."""
REGISTRY = str(HERE / "upstream")
@classmethod
def setUpClass(cls):
if not os.environ.get("ADVISORY_SCAN_LIVE"):
raise unittest.SkipTest("live tests: re-run with --live")
def _count(self, recipe, v_from, v_to, images=None):
rep = A.scan(recipe, v_from, v_to, self.REGISTRY, images)
self.assertEqual(rep["sources_failed"], [], f"{recipe}: source failures make the count unsafe")
self.assertTrue(rep["count_known"], f"{recipe}: count came back UNKNOWN")
return rep
def test_gitea_1_27_0_to_1_27_1_is_2(self):
rep = self._count("gitea", "1.27.0", "1.27.1")
self.assertEqual(rep["cve_count_fixed"], 2)
# Both CVSS-9.8 RCEs — the pair whose omission is why this tool exists.
self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-59774", "CVE-2026-60004"})
def test_discourse_app_only_is_123(self):
rep = self._count("discourse", "3.5.3", "2026.7.1")
self.assertEqual(rep["cve_count_fixed"], 123)
self.assertIn("publish date", rep["classified_by"]["github-advisories:discourse/discourse"])
def test_discourse_with_redis_sidecar_is_140(self):
# 123 app + 17 redis. Five redis advisories carry a usable patched_versions; the other
# twelve say "TBD" and are resolved from the release notes that name them.
rep = self._count("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")])
self.assertEqual(rep["cve_count_fixed"], 140)
self.assertEqual(len(rep.get("resolved_by_release_notes") or {}), 12)
self.assertEqual(rep["cve_count_indeterminate"], 0)
# The five redis advisories that a sidecar-blind scan missed, incl. one critical.
for cve in ("CVE-2024-31227", "CVE-2024-31228", "CVE-2024-31449",
"CVE-2025-49844", "CVE-2025-62507"):
self.assertIn(cve, rep["fixed_by_this_upgrade"], f"{cve} missing from discourse+redis")
self.assertEqual(rep["cves"]["CVE-2025-49844"]["severity"], "critical")
def test_discourse_redis_delta_is_exactly_seventeen(self):
app = self._count("discourse", "3.5.3", "2026.7.1")
both = self._count("discourse", "3.5.3", "2026.7.1", [("redis", "7.4", "8.10")])
delta = set(both["fixed_by_this_upgrade"]) - set(app["fixed_by_this_upgrade"])
self.assertEqual(len(delta), 17)
for cve in delta:
self.assertIn("redis", both["cves"][cve]["sources"][0])
def test_mailu_finds_the_roundcube_pair_without_an_agent(self):
# Published as 2 on 2026-08-07, but only because an agent read the release notes; the scan
# itself contributed 0. It now reaches 2 deterministically: the CVEs appear only on
# github.com/Mailu/Mailu/releases, and release 2024.06.56 (inside the window) names them.
rep = self._count("mailu", "2024.06.55", "2024.06.57", [("redis", "8.8.0", "8.10.0")])
self.assertEqual(rep["cve_count_fixed"], 2)
self.assertEqual(set(rep["fixed_by_this_upgrade"]), {"CVE-2026-54432", "CVE-2026-54433"})
# The redis bump fixes nothing new — every advisory it crosses was fixed at or before 8.6.3.
self.assertEqual(rep["cve_count_indeterminate"], 0)
def test_keycloak_26_7_0_to_26_7_1_is_12(self):
# Was 7 while only the GHSA feed was consulted. keycloak lists five more CVEs in the 26.7.1
# release notes' fixed-issues section that it never filed as advisories — the gitea pattern.
rep = self._count("keycloak", "26.7.0", "26.7.1")
self.assertEqual(rep["cve_count_fixed"], 12)
self.assertEqual(len(rep.get("resolved_by_release_notes") or {}), 5)
def _main():
live = "--live" in sys.argv
if live:
sys.argv.remove("--live")
os.environ["ADVISORY_SCAN_LIVE"] = "1"
unittest.main(verbosity=2)
if __name__ == "__main__":
_main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/test-advisory-scan.py
-55
View File
@@ -1,55 +0,0 @@
#!/usr/bin/env python3
"""Offline regressions for the weekly image survey's false-current cases."""
import importlib.util
import pathlib
import unittest
from unittest import mock
HERE = pathlib.Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location("resolve_images", HERE / "resolve-images.py")
resolver = importlib.util.module_from_spec(spec)
spec.loader.exec_module(resolver)
class TestResolverCoverage(unittest.TestCase):
def test_cryptpad_calver_tag_is_found_independently_of_abra(self):
with mock.patch.object(resolver, "list_tags", return_value=(
["version-2026.5.1", "version-2026.10.0", "opendesk-2026.08.04"], None)):
row = resolver.resolve("cryptpad/cryptpad:version-2026.5.1")
self.assertTrue(row["upgrade_available"])
self.assertEqual(row["newest_same_shape"], "version-2026.10.0")
def test_floating_and_templated_tags_cannot_prove_current(self):
with mock.patch.object(resolver, "list_tags", return_value=(["alpine", "1.2.3"], None)):
floating = resolver.resolve("atmoz/sftp:alpine")
templated = resolver.resolve("ghost:${IMAGE_VERSION}-alpine")
self.assertTrue(floating["status"].startswith("unverifiable:"))
self.assertTrue(templated["status"].startswith("skipped:"))
def test_truncated_registry_listing_cannot_prove_current(self):
with mock.patch.object(resolver, "list_tags", return_value=(["1.2.3"], None)):
with mock.patch.object(resolver, "_HUB_TRUNCATED", {"library/example"}):
row = resolver.resolve("example:1.2.3")
self.assertTrue(row["status"].startswith("unverifiable:"))
def test_huge_ghcr_listing_uses_only_published_release_manifests(self):
ref = "ghcr.io/immich-app/immich-machine-learning:v3.3.5"
with mock.patch.object(resolver, "list_tags", return_value=([], "RuntimeError: tag listing truncated")), \
mock.patch.object(resolver, "github_release_tags",
return_value=["v3.3.6", "v3.3.5"]), \
mock.patch.object(resolver, "_oci_tag_exists", side_effect=lambda h, r, t: t == "v3.3.5"):
row = resolver.resolve(ref)
self.assertEqual(row["status"], "ok")
self.assertFalse(row["upgrade_available"]) # release exists; image does not yet
self.assertIn("registry-manifest", row["source"])
with mock.patch.object(resolver, "list_tags", return_value=([], "RuntimeError: tag listing truncated")), \
mock.patch.object(resolver, "github_release_tags",
return_value=["v3.3.6", "v3.3.5"]), \
mock.patch.object(resolver, "_oci_tag_exists", return_value=True):
upgraded = resolver.resolve(ref)
self.assertTrue(upgraded["upgrade_available"])
if __name__ == "__main__":
unittest.main()
+1
View File
@@ -0,0 +1 @@
../scripts/cc-ci/test-resolve-images.py