Archive the completed Builder/Adversary build #49

Merged
autonomic-bot merged 1 commits from chore/archive-original-build-20261123 into main 2026-11-23 19:53:56 +00:00
146 changed files with 9016 additions and 8808 deletions
+21 -141
View File
@@ -1,147 +1,27 @@
# cc-ci-orchestrator — AGENTS.md # cc-ci-orchestrator — current work
This folder is the **orchestrator** workspace for building the **cc-ci** Co-op Cloud recipe CI This repository declares the combined cc-ci NixOS host and runs its operator steering
server. It holds the plan, the launch/supervision tooling, and the two loop prompts. The actual CI session, weekly recipe upgrader, report, and host updater. The Builder/Adversary
project (NixOS config, test runner, recipe tests) lives in a **separate** repo the loops create at phase build is finished. Its plans, prompts, and launch implementation are under
`git.autonomic.zone/recipe-maintainers/cc-ci` — do not confuse the two. `archive/original-build/`; compatibility links remain at old paths because the
unchanged Nix `cc-ci-loops` service still calls `cc-ci-plan/launch.sh` on boot.
Do not restart the completed Builder/Adversary loops.
## The agent map lives in `cc-ci-plan/orchestration.md` Start with `README.md` for current operations and `archive/README.md` for history.
The actual CI server and recipe tests live in the separate `cc-ci` repository.
That doc is the **root structure**: every agent (Builder, Adversary, Orchestrator, Assistant, ## Host changes
Upgrader) → its prompt + plan, plus the watchdog and the git coordination protocol. Read it first.
In short: the **Orchestrator** (*this* session/role) supervises and keeps everyone on track — it is The live host is `nixosConfigurations.cc-ci` in this repo, which imports the
**separate** from the loops and is the only role that should power-cycle/recreate the host. The `cc-ci` server module. Build and test `#cc-ci` from `/srv/cc-ci-orch` before a
**Builder** and **Adversary** loops coordinate **only** through the cc-ci git repo (`plan.md` §6.1); switch. Verify SSH, failed units, Swarm replicas, front doors, and the running
the orchestrator watches from outside. and boot generations afterward. Do not rebuild from the cc-ci repo's standalone
`#cc-ci` target.
## On startup: read the journal, announce yourself, report reboots ## Secrets and commits
**Every time you (the orchestrator) start or resume:** Never commit secret values. `.testenv`, private keys, and runtime state stay
1. **Read `cc-ci-plan/JOURNAL.md`** — the most recent `## Session` entry is where the previous outside Git. Commit only files changed for the task, with author
session left off. This is the persistent handoff record; read it before anything else. `notplants <@notplants>` and no AI co-author trailer. For infrastructure
2. Read `cc-ci-plan/REBOOTS.md` (count entries) and run `cc-ci-plan/launch.sh status` changes here or in `cc-ci`, use branch → PR → verify → merge; operator review
(current phase + whether loops/watchdog are running). is retrospective. Recipe PRs are never agent-merged. Do not force-push.
3. **`PushNotification`** (proactive): *"cc-ci orchestrator online — phase X, loops+watchdog
running; N reboots logged (last <date>)."*
4. If loops are down, relaunch: `RESUME_PHASE=1 cc-ci-plan/launch.sh start`.
5. **On handoff / end of session:** append a `## Session` block to `JOURNAL.md` summarising
what happened, current state, and open items (see format in that file).
Reboot resilience is handled by **`cc-ci-loops.service`** (system unit): on boot it logs the reboot
to `REBOOTS.md` (boot_id-gated) and runs `launch.sh start` with `RESUME_PHASE=1`, so the loops +
watchdog auto-resume the saved phase. The orchestrator session itself is relaunched by
`cc-ci-orchestrator.service` (`agents.py up orchestrator`) as an **opencode agent** the operator
steers from https://oc.ci.commoninternet.net (no Claude on the cc-ci host; Claude sessions run on
the notplants-orchestrator box and reach cc-ci over ssh). Since 2026-09 the orchestrator runs on the **same Hetzner
host as the cc-ci CI server** (`cc-ci`, public `195.201.88.249`, tailnet `cc-ci`), declared by
`nixosConfigurations.cc-ci` in this repo's `flake.nix`, which imports the CI server from the cc-ci
repo's `nixosModules.cc-ci-server`. `ssh cc-ci` from the loops user therefore goes to loopback.
The full provisioning + deploy guide is `README.md`; the move is recorded in
`cc-ci-plan/plan-cc-ci-combined-host.md`; the previous hosts (Pi → Incus VM → Hetzner `cpx22`
shared with notplants) are in `archive/`. Rebuild this host with
`nixos-rebuild switch --flake .#cc-ci` from `/srv/cc-ci-orch` — but **always
`nixos-rebuild test` the same flake target first and verify the host is still healthy/reachable
before the `switch`** (general policy for nix deploys to this host: `test`
leaves the bootloader and system profile untouched, so a reboot always recovers to the
last-known-good generation; the 2026-08-03 cc-ci 26.05 bump outage is the cautionary tale, see
`.cc-ci-logs/server-update-2026-08-03.md`).
## Keep the orchestrator open, under remote-control
Run this session as a long-lived **interactive** session with `--remote-control` so the operator can
check in on the loops and steer/restart things from **claude.ai/code** (or the Claude mobile app)
without being at the terminal.
- **Already in the session?** Just run `/remote-control` — it attaches claude.ai/code to the live
conversation (no exit, no resume needed).
- **Starting fresh:** `claude --remote-control 'autonomous-orchestrator' --dangerously-skip-permissions`
- **Resuming this orchestrator later (history preserved):**
```bash
claude --resume autonomous-orchestrator --remote-control "autonomous-orchestrator" --dangerously-skip-permissions
```
Note the two names are different: `--resume <name|id>` restores *this conversation* (the name set
via `-n/--name`, shown in the `/resume` picker); the `--remote-control [name]` value is only the
web display label and resumes nothing. The conversation persists on disk across exits; remote
control itself only stays "connected" while the local process is alive (resume + re-enable to get
it back after a full exit).
Use it to: tail loop logs (`cc-ci-plan/launch.sh logs builder|adversary|watchdog`), inspect
`STATUS.md`/`REVIEW.md` in the cc-ci repo, edit the plan or prompts, restart a stuck loop, or
power-cycle/recreate the cc-ci VM (see `cc-ci-plan/kickoff.md` → "Fallback: restart/recreate the
cc-ci VM"). The orchestrator is the human's steering wheel; the loops are the engine.
## Loop file-location rule (machine-docs/)
In the **cc-ci loops repo**, ALL coordination / loop-state files live under `machine-docs/`, NEVER
the repo root: phase-namespaced `STATUS-*.md` / `BACKLOG-*.md` / `REVIEW-*.md` / `JOURNAL-*.md`,
shared `DECISIONS.md` / `DEFERRED.md`, and the `ADVERSARY-INBOX.md` / `BUILDER-INBOX.md`
side-channels. This is enforced in the kickoff (`launch.py build_kickoff`), the loop prompts, and
the loops' own `AGENTS.md`. If the orchestrator ever sees such a file at the root, move it into
`machine-docs/` and check the kickoff/prompts still mandate it. (The watchdog's `resolve_state` and
INBOX handoff already read `machine-docs/` first, so this is the single canonical home.)
## Launch & supervise the loops
- **Source of truth for the loops:** `cc-ci-plan/plan.md` (mission, Definition of Done, §1.5
credential map, §6 two-agent protocol, §7 loop discipline).
- **Launch/supervision guide:** `cc-ci-plan/kickoff.md`.
- `cc-ci-plan/launch.sh start` → both loops (interactive `--remote-control` in tmux) + a watchdog.
tmux is installed; `launch.sh` defaults now point at `/srv/cc-ci/...`.
## Access & credentials (pointers only — values are gitignored)
- `.testenv` (**NOT committed**): Tailscale auth key + Gitea bot creds. Load with
`set -a; . .testenv; set +a` (never echo the values).
- **cc-ci:** `ssh cc-ci` (root) directly — the orchestrator VM is a direct tailnet peer (`100.90.116.4`).
No proxy. Key: `~/.ssh/cc-ci-root-ed25519`. If unreachable, check `tailscale status`.
- **Incus/VM fallback:** mTLS certs at `/srv/incus-terraform-nix-vm-creator/terraform-secrets/`;
b1 is on the same tailnet (reach via the same proxy). See kickoff "Fallback".
- **Full credential map + how to use each:** `plan.md` §1.5.
## Hard rule
Never commit secret values. `.testenv`, `*.tfstate`, `*.key`/`*.pem`, and the loop runtime/clone
dirs are gitignored. Reference secret *locations*, never their contents (`plan.md` §9).
## Agent memory lives in `memory/` (in this repo)
The orchestrator's persistent agent memory is the **`memory/`** directory of this repo — one file
per fact with frontmatter, indexed by `memory/MEMORY.md`. The Claude auto-memory path
(`~/.claude/projects/-srv-cc-ci-orch/memory`) is a **symlink** to it, so memories written the normal
way land in the repo automatically. **Future memories must also go there**: after writing or
updating a memory file (and its `MEMORY.md` index line), commit it here and push, like any other
intentional repo change. Never put secret values in a memory file (see Hard rule).
## Commit discipline
When the orchestrator, Builder, or assistant makes intentional repository changes here, commit them
promptly and push them to `git.autonomic.zone` in append-only fashion (never force-push). Match the
existing commit author and message style in this repo. Do not bundle unrelated worktree changes you
did not make; stage only the intended files.
## Ship as PRs, merge them yourself, operator reviews retrospectively
**This applies to the two INFRASTRUCTURE repos — `recipe-maintainers/cc-ci-orchestrator` (here) and
`recipe-maintainers/cc-ci` (the CI product).** For work in either:
1. Branch, don't commit straight to `main`.
2. Open a PR with a description written to be read **after** the fact: what changed, why, and what
evidence says it works (test output, a verified run, a before/after number). The PR *is* the
review artifact and the historical record.
3. **Merge it yourself once it is verified** — do not wait for review. The invocation is the
authorization; blocking on review would stall the pipeline these repos exist to run.
4. The operator reviews **retrospectively**, from the PR.
So the PR is not a gate — it is how the work stays legible. A PR that merely says "fix scanner" has
failed at its only job.
> ### This does NOT extend to RECIPE repos
> Recipe PRs — any `coop-cloud/<recipe>` or its `recipe-maintainers/<recipe>` mirror — are
> **created and verified but NEVER merged by an agent**. Those change what deploys on other people's
> infrastructure, so a human merges them. The split is deliberate: agents own the tooling, the
> operator owns the recipes.
If work has already landed on `main` without a PR, do not rewrite published history to fix it.
Create a branch pinned at the pre-work commit and open the PR against that, so the diff is still
reviewable and merging only advances the pointer (see PRs #2-#5, 2026-08-11).
+15 -360
View File
@@ -1,355 +1,23 @@
# cc-ci-orchestrator # cc-ci-orchestrator
The **cc-ci orchestrator**: the agent loops that built the cc-ci Co-op Cloud recipe CI server, This repository configures the combined cc-ci NixOS host and its current
the operator's steering session, and the weekly autonomous recipe-upgrade run — plus the NixOS automation: the operator steering session, weekly recipe upgrader, public
host they run on. Since 2026-09 that host is **the same Hetzner server as the CI server itself**: report, and health-gated host updater. The CI server itself is imported from
one `nixos-rebuild` from this repo builds both, because this flake imports the CI server as a the [cc-ci repository](https://git.autonomic.zone/recipe-maintainers/cc-ci).
module from the [cc-ci](https://git.autonomic.zone/recipe-maintainers/cc-ci) repo.
| | where | | Current component | Location |
|---|---| |---|---|
| Orchestrator loops, timers (weekly upgrader, hourly supervisor) | `nix/modules/cc-ci.nix` → `nixosModules.cc-ci-orchestrator` | | Combined host and timers | `flake.nix`, `nix/hosts/cc-ci/`, `nix/modules/` |
| The host contract those need (loops user, opencode CLI, opencode web UI) | `nix/modules/orchestrator-host.nix` → `nixosModules.orchestrator-host` | | Operator session, weekly upgrade and report launchers | `cc-ci-plan/agents.py`, `cc-ci-plan/launch-{upgrader,report,supervisor}.py` |
| The CI server (swarm, traefik, drone, runner, `!testme` bridge, dashboard, reports, acme-dns) | cc-ci repo `nix/modules/` → `nixosModules.cc-ci-server` (flake input `cc-ci`) | | Recipe inventory, upstream notes, reporting tools | `cc-ci-plan/used-recipes.md`, `cc-ci-plan/upstream/`, `cc-ci-plan/recipe-report.py` |
| The machine: hardware, networking, root keys, firewall + fail2ban | `nix/hosts/cc-ci/` → `nixosConfigurations.cc-ci` | | Original Builder/Adversary build and first host deployment | [`archive/original-build/`](archive/original-build/README.md) |
| Plans, launch tooling, loop prompts, journal | `cc-ci-plan/` (see `AGENTS.md` for roles) |
| Skills the orchestrator runs (`/upgrade-all`, `/recipe-upgrade`, `/cc-ci-status`, …) | `.claude/skills/`, `.opencode/skills/` |
| How it used to be built (Pi → Incus VM → shared Hetzner box) | `archive/` |
Secrets (`.testenv`, `upgrader.env`, `.sops/`, everything under `/secrets`) are gitignored — never Secrets and runtime state are gitignored. The completed two-loop build is
commit them. archived; no Builder or Adversary session should be running. The Nix
`cc-ci-loops` unit still invokes a compatibility launcher on boot and exits
when it sees the completed phase state. Its Nix behavior is unchanged.
--- ## Host updates and recovery
# Deploying a cc-ci host from scratch
This is the whole path from "nothing" to a working CI server + orchestrator on one Hetzner
server. It was last done on 2026-09-07 for `195.201.88.249` and is written so a person or an LLM
can repeat it. Read it once before starting; the order matters.
## 0. What you need in hand
- A **Hetzner Cloud** project you can create servers in (console login or an API token).
- **SSH keys**: yours, and the orchestrator's own key so the automation can reach the box. The
public keys that get root are tracked in `nix/hosts/cc-ci/ssh-keys` (one per line). Password
login is disabled and fail2ban watches sshd, so a key is the only way in.
- Read access to `recipe-maintainers/cc-ci`, `recipe-maintainers/cc-ci-orchestrator` (both public
read) and the **private** `recipe-maintainers/cc-ci-secrets` (the `autonomic-bot` account has
it; the host gets its own deploy key on that account, §4b/§4c — and the bot password, in
`.testenv`, is what registers it).
- The out-of-band secrets listed in §4. If you are migrating, they come from the old host; if
you are starting fresh you create them (each row says how).
- Control of the DNS zone (Gandi for `commoninternet.net`) for the cutover in §7.
## 1. Provision the server on Hetzner (Debian image)
In the Hetzner Cloud console (or with `hcloud server create`):
| setting | value | why |
|---|---|---|
| Image | **Debian 13** (any recent Debian/Ubuntu works with nixos-infect) | it is replaced by NixOS in §2 |
| Type | **x86**, **8 GB RAM**, 4 vCPU — e.g. `cpx32` (dedicated AMD) or `cx33`. **Never `cax*`** (ARM): the flakes are `x86_64-linux`. | swarm + recipe deploys + 3–6 agent sessions; 4 GB is too small |
| Disk | the type's default 150+ GB NVMe | docker layers alone are ~60 GB after a few weeks |
| Network | public **IPv4** required; IPv6 optional (leave enabled or not, NixOS config ignores it) | cc-ci serves 80/443 and DNS on 53 publicly |
| SSH keys | add every key from `nix/hosts/cc-ci/ssh-keys` you want to log in with, at least the orchestrator's | nixos-infect carries `/root/.ssh/authorized_keys` over |
| Name | `cc-ci` | becomes the hostname |
| Firewall | if a Hetzner Cloud Firewall is attached it must allow **22/tcp, 80/tcp, 443/tcp, 53/tcp, 53/udp** in, and ICMP | the NixOS firewall is separate and is configured by the flake |
Check you can log in: `ssh root@<ip> hostname`.
## 2. Convert Debian → NixOS with nixos-infect
[nixos-infect](https://github.com/elitak/nixos-infect) installs NixOS over the running Debian and
reboots. Run it detached so the SSH session dropping does not kill it:
```bash
ssh root@<ip> 'cat > /root/infect.sh <<"EOF"
#!/usr/bin/env bash
set -euo pipefail
# Pinned nixos-infect revision (same one that built the previous cc-ci hosts).
INFECT_SHA="40f62a680bb0e8f2f607d79abfaaecd99d59401c"
export NIX_CHANNEL="nixos-26.05" # must match the nixpkgs channel in flake.nix
export PROVIDER="hetznercloud" # GRUB + Hetzner networking
export NIXOS_IMPORT="" # the real config comes from the flake in §5
# The Debian 13 cloud image mounts /tmp as tmpfs; nixos-infect makes a temporary swapfile
# there and swapon fails with "Invalid argument". 8 GB RAM needs no extra swap: skip it.
export NO_SWAP=true
curl -fsSL "https://raw.githubusercontent.com/elitak/nixos-infect/${INFECT_SHA}/nixos-infect" | bash -x
EOF
chmod +x /root/infect.sh
nohup /root/infect.sh > /var/log/nixos-infect.log 2>&1 &'
```
It downloads Nix, builds a NixOS system (5–10 min; follow with
`ssh root@<ip> tail -f /var/log/nixos-infect.log`), then reboots. The SSH host key changes:
`ssh-keygen -R <ip>` and confirm `ssh root@<ip> nixos-version` prints a 26.05 version.
### 2a. What went wrong on 2026-09-07, and the fixes (Debian 13 image, NixOS 26.05)
All three bit on the first attempt; the script above and §3 already include the fixes, this is
so you recognise them if they come back in another form.
1. **`swapon: /tmp/nixos-infect.XXXX.swp: Invalid argument`** right at the start, script exits.
The Debian 13 cloud image mounts `/tmp` as tmpfs and a swapfile cannot live there.
Fix: `NO_SWAP=true` (in the script above). An 8 GB box does not need the temporary swap.
2. **The box never comes back after the reboot: it boots NixOS, but nearly every unit fails**
(`dbus`, `systemd-logind`, `sshd`, networking …) with
`Could not start dynamically linked executable: /usr/bin/dbus-daemon` in the journal.
nixos-infect leaves the old Debian root in place and relies on NixOS's first boot to move it
to `/old-root` (`/etc/NIXOS_LUSTRATE`). With NixOS 26.05's systemd-based initrd that
lustration did not happen, so Debian's `/etc/systemd/system/*.service` files shadowed the
NixOS units and started Debian binaries. Fix, from Hetzner **rescue mode**
(`enable_rescue` + `reset` in the API/console, ssh in, `mount /dev/sda1 /mnt/root`):
move everything except `nix`, `boot`, `swapfile`, `lost+found`, `var/log`, `var/empty`,
`etc/nixos`, `etc/resolv.conf`, `etc/NIXOS`, `etc/machine-id`, `etc/ssh/ssh_host_*`,
`root/.nix-*`, `root/.ssh` into `/mnt/root/old-root`, delete `etc/NIXOS_LUSTRATE`, unmount,
`disable_rescue`, `reset`. (`/old-root`, ~1 GB, can be deleted once the host is in service.)
3. **Boots, units fine, but no network.** The generated `networking.nix` has
`defaultGateway = "172.31.1.1";` — a bare string. Since NixOS 25.05 that yields no default
route. Fix: `defaultGateway = { address = "172.31.1.1"; interface = "eth0"; };` (this is what
`nix/hosts/cc-ci/networking.nix` carries). To apply it from rescue mode, chroot into the
mounted root and rebuild the boot entry — the nix sandbox cannot `pivot_root` inside a chroot,
so turn it off for that one build:
```bash
for d in proc sys dev dev/pts; do mount --bind /$d /mnt/root/$d; done
mount -t tmpfs tmpfs /mnt/root/run; cp -L /etc/resolv.conf /mnt/root/etc/resolv.conf
chroot /mnt/root /nix/var/nix/profiles/system/sw/bin/bash -c '
export PATH=/nix/var/nix/profiles/system/sw/bin NIX_REMOTE= HOME=/root
export NIX_PATH=nixos-config=/etc/nixos/configuration.nix:nixpkgs=/root/.nix-defexpr/channels/nixos
ln -sfn /nix/var/nix/profiles/system /run/current-system
nixos-rebuild boot --option sandbox false'
```
The `journalctl -D /mnt/root/var/log/journal -b 0` trick (reading the dead system's journal
from rescue mode) is what told these apart.
> Rescue mode without a console: `POST /servers/<id>/actions/enable_rescue` with your ssh key
> id, then `…/actions/reset`; afterwards `disable_rescue` **and check `rescue_enabled` is false
> before** the next `reset`, or it boots the rescue image again. `scripts/recovery/hetzner.py`
> wraps these (token in `/srv/cc-ci/.hcloud-token`).
## 3. Capture the machine-specific config into this repo
nixos-infect wrote `/etc/nixos/{hardware-configuration,networking,configuration}.nix`. Only the
first two matter; the flake replaces `configuration.nix`.
```bash
scp root@<ip>:/etc/nixos/hardware-configuration.nix nix/hosts/cc-ci/hardware.nix
scp root@<ip>:/etc/nixos/networking.nix nix/hosts/cc-ci/networking.nix
```
Then in `nix/hosts/cc-ci/`:
- `hardware.nix`: keep as generated (GRUB EFI with `efiInstallAsRemovable`, `/boot/efi` by UUID,
`/dev/sda1` root). Do not copy another host's file — the UUIDs are per machine.
- `networking.nix`: keep the static IPv4 + Hetzner gateway `172.31.1.1`. Make sure
`networking.defaultGateway` has **both** `address` and `interface = "eth0"` (§2a item 3). If
the generated IPv6 block has an empty address, delete the IPv6 parts; a real global address
(as on the 2026-09 box) can stay.
- `configuration.nix`: set `cc-ci.publicIPv4` to the server's IPv4 and check `system.stateVersion`
is the release you installed (never change it later).
- `ssh-keys`: the root keys.
Commit on a branch; the rebuild in §5 can use the local checkout before the PR merges.
## 4. Stage the workspace and secrets on the new host
Everything in this section is **outside git**. Do it as root over SSH, in this order.
### 4a. No tailscale
The combined host is NOT on the tailnet (operator decision 2026-09-07): ssh is key-only on the
public IP, the CI front doors are public via traefik, and the opencode UI is public on the same
443 — traefik routes `oc.ci.commoninternet.net` to an nginx vhost on the docker bridge that
enforces basic auth, via traefik labels on a tiny swarm relay stack (`ccci-opencode-ui`, on the weekly sweep's keep-list) that
`opencode-ui-route.service` deploys. (Not via traefik's file *directory* provider: enabling
that in the coop-cloud traefik recipe REPLACES its provider file, which holds the wildcard cert
and the `security` middleware, and every front door goes down — it did, for two minutes, on
2026-09-07.) fail2ban guards sshd and that login
(`nix/hosts/cc-ci/configuration.nix`; the nginx jail bans in the DOCKER-USER chain because the
traffic is docker-forwarded, not host INPUT).
### 4b. The CI server's checkout and its one out-of-band secret
```bash
# the bot deploy key for the private cc-ci-secrets submodule — generated ON this host by loops
# (§4c) and registered on the autonomic-bot Gitea account; root only points at it:
install -d -m700 /root/.ssh
cat > /root/.ssh/config <<'SSHCFG'
Host git.autonomic.zone
Port 2222
User git
IdentityFile /secrets/files/autonomic-bot-cc-ci-ed25519
IdentitiesOnly yes
SSHCFG
# the deployed checkout: nightly-sweep runs from it, sops reads secrets/secrets.yaml from it
git clone --recursive https://git.autonomic.zone/recipe-maintainers/cc-ci.git /etc/cc-ci
# the age identity sops-nix decrypts with. FIRST deploy of a host that is not yet a recipient:
# the master (recovery) key, temporarily. Once the host is a recipient (below): its own
# ssh-host-key-derived identity, and the master key leaves the box.
install -d -m0700 /secrets/host
install -m600 <master-age.txt> /secrets/host/sops-age-key.txt
```
`/etc/cc-ci/secrets/secrets.yaml` is encrypted to the master key and the *previous* hosts' SSH
host keys. The master key is enough for the FIRST deploy. Then make the new host a recipient so
the master key can leave the box again (it belongs off-box, with the operator):
`ssh-to-age < /etc/ssh/ssh_host_ed25519_key.pub` → add it to `.sops.yaml` in cc-ci-secrets AND in
cc-ci, `sops updatekeys secrets.yaml` (needs the master key, so do it where that lives), push,
bump the submodule in cc-ci, `git -C /etc/cc-ci pull --recurse-submodules` on the host, then
replace `/secrets/host/sops-age-key.txt` with the host-derived identity
(`ssh-to-age -private-key -i /secrets/host/ssh_host_ed25519_key`), rebuild, and delete the master
key from the host.
### 4c. The orchestrator's workspace (as the `loops` user — it exists after the first rebuild, so
run §5 once first if this is a fresh host, then come back)
```bash
sudo -iu loops
git clone --recursive https://git.autonomic.zone/recipe-maintainers/cc-ci-orchestrator.git /srv/cc-ci-orch
sudo ln -sfn /srv/cc-ci-orch /srv/cc-ci # every script and unit says /srv/cc-ci
cd /srv/cc-ci-orch
git clone https://git.autonomic.zone/recipe-maintainers/cc-ci.git cc-ci # Builder clone
git clone https://git.autonomic.zone/recipe-maintainers/cc-ci.git cc-ci-adv # Adversary clone
mkdir -p .cc-ci-logs .sops
```
**`/secrets` is the authoritative location for every secret on this host.** Consumers either read
from it directly (where the nix config owns the path) or reach it by a symlink (where the software
fixes the path), so `find /secrets -type f` is the complete inventory — including the ssh host
keys. The directory is `0711` (traversable, not listable) with three subdirectories, each owned by
whoever must read it; the layout is declared in `nix/hosts/cc-ci/configuration.nix`:
| dir | mode | holds |
|---|---|---|
| `/secrets/files` | `loops:users 0700` | the agent's secrets: `.testenv`, opencode auth, its two ssh keys |
| `/secrets/host` | `root:root 0700` | host identity: the ssh **host** keys and the sops age identity |
| `/secrets/nginx` | `root:nginx 0750` | `oc-htpasswd` for the opencode UI (nginx must read it) |
**Only cc-ci's secrets go there** — nothing from other projects (no tailscale, lichen, tangled,
b1, borg…), and every private key is generated **on the host**, never copied from another machine.
`/secrets/README.txt` lists each file, its purpose, and the derived material that legitimately
lives elsewhere (`/run/secrets`, `/root/.docker/config.json`, the ACME cert) so a later sweep does
not "clean" it away.
> **The ed25519 host key is load-bearing beyond ssh.** Its age identity is a recipient of
> `cc-ci-secrets`, so regenerating it makes every cc-ci secret undecryptable. sshd is pointed at
> `/secrets/host/...` directly (not through the `/etc/ssh` symlinks) precisely so it can never
> write a fresh key through a dangling link. To move a host: copy the key, verify
> `ssh-to-age` yields the same identity, then activate.
| runtime path → `/secrets/files/…` | what | source |
|---|---|---|
| `/srv/cc-ci/.testenv` → `cc-ci.testenv` | `GITEA_PASSWORD` (autonomic-bot: PR/API calls), `DOCKERHUB_USERNAME/TOKEN` (harness image pulls). Nothing else: no tailscale key, no third-party model API keys (opencode's own auth is `opencode-auth.json`; add `TINFOIL_API_KEY` back only if `LOOP_MODEL` moves to a tinfoil model). | old host's copy minus the tailscale line; fresh: create each credential |
| `/srv/cc-ci/upgrader.env` (not a secret, lives in the checkout) | `LOOP_TIER`, `LOOP_MODEL`, `REPORT_MODEL`, `SUPERVISOR_MODEL` for the weekly run. This host is on the **OpenCode Go subscription** (`LOOP_TIER=go`, `opencode-go/…` models); the ZEN tier is pay-as-you-go credit and its key is not on this host | old host, or copy the example in `AGENTS.md` |
| `~loops/.ssh/cc-ci-local-ed25519` (+`.pub`) → same names | `ssh cc-ci` as root — to loopback on this host. **Generated on the host**, its pub in `nix/hosts/cc-ci/ssh-keys` | `ssh-keygen -t ed25519 -C cc-ci-loops-to-root@cc-ci` as loops |
| `~loops/.ssh/autonomic-bot-cc-ci-ed25519` (+`.pub`) → same names | pushes recipe branches / PRs as `autonomic-bot`; root's ssh config points at the same file to clone the private cc-ci-secrets submodule. **Generated on the host** and registered on the bot's Gitea account (`POST /api/v1/user/keys` with the bot password) | `ssh-keygen -t ed25519 -C autonomic-bot@cc-ci-host` as loops |
| `~loops/.local/share/opencode/auth.json` → `opencode-auth.json`; `~loops/.config/opencode/opencode.jsonc` (config, not secret — it must contain NO inline `apiKey`) | opencode provider auth + config. Exactly ONE provider, `opencode-go` — the orchestrator AND the weekly upgrader are opencode agents; there is no Claude on this host | old host; fresh: `opencode auth login` as loops |
| `/secrets/nginx/oc-htpasswd` (root:nginx 0640; the bcrypt line only — the plaintext stays with the operator, not on the host) | basic auth for the opencode UI (`https://oc.ci.commoninternet.net`, via traefik); **nginx refuses to start without it**, and its config check runs as the `nginx` user, so `root:nginx 0640` (the `nginx` group exists after the first rebuild — fix ownership then and `systemctl restart nginx`) | old host (`/secrets/files/oc-basic-auth.txt` has the plaintext), or a new `oc:<bcrypt>` line via `mkpasswd -m bcrypt` |
`~loops/.ssh/config` is written by the activation script on first rebuild (`Host cc-ci` →
`127.0.0.1`, `git.autonomic.zone`); it is not overwritten if present.
## 5. Build and activate
From the checkout with the §3 commit (root can build from the loops-owned checkout via sudo):
```bash
# as root, detached (the activation restarts sshd; a dropped session must not kill it).
# Three things the FIRST rebuild on a bare infect system needs, none of which the converged
# host needs afterwards: `git` on PATH (nix's flake fetcher shells out to it and the infect
# system has none — hence nix-shell), HOME=/root (so root's `git config --global
# safe.directory '*'` applies to the loops-owned checkout), and a login shell (`bash -l`, for
# NIX_SSL_CERT_FILE and friends from /etc/set-environment).
git config --global --add safe.directory '*'
systemd-run --unit=ccci-rebuild --collect -E HOME=/root -p WorkingDirectory=/srv/cc-ci-orch \
bash -lc 'nix-shell -p git --run "nixos-rebuild test --flake /srv/cc-ci-orch#cc-ci"'
journalctl -fu ccci-rebuild # ~10 min the first time (image pulls + two OCI image builds)
```
`test` first, always: it activates WITHOUT touching the bootloader, so if the activation breaks
networking or sshd a reboot from the Hetzner console lands on the last known-good generation.
(Earlier hosts were on the tailnet, and their rebuilds had to be detached because activation
restarted tailscale under the session; this one is plain public ssh, but detached is still the
safe habit.)
Later rebuilds are simply `sudo nixos-rebuild test|switch --flake .#cc-ci` from the checkout.
The first activation takes a while: it pulls the traefik/drone/keycloak images, builds the bridge
and dashboard OCI images with Nix, initialises the swarm and runs the serialized reconcile
oneshots (`swarm-init → deploy-proxy → deploy-drone → deploy-bridge → deploy-dashboard →
deploy-reports`, `deploy-backupbot`, `warm-keycloak`). Verify:
```bash
systemctl is-system-running # running — or list-units --failed and read journalctl -u <unit>
docker service ls # traefik app+socket-proxy, drone, bridge, dashboard, reports, backups: 1/1
systemctl status cc-ci-loops cc-ci-orchestrator opencode-web nginx acme-dns fail2ban
fail2ban-client status sshd; fail2ban-client status nginx-http-auth
systemctl list-timers 'cc-ci-*' nightly-sweep
sudo -iu loops tmux ls # cc-ci-orchestrator (+ loops sessions if a phase is active)
# the CI front doors, before DNS points here (expect 200 / 200 / 303 and ssl_verify=0 once
# /var/lib/acme is restored or a cert has been issued):
curl -s --resolve ci.commoninternet.net:443:127.0.0.1 -o /dev/null -w '%{http_code} %{ssl_verify_result}\n' https://ci.commoninternet.net/
curl -s --resolve report.ci.commoninternet.net:443:127.0.0.1 -o /dev/null -w '%{http_code}\n' https://report.ci.commoninternet.net/
curl -s --resolve drone.ci.commoninternet.net:443:127.0.0.1 -o /dev/null -w '%{http_code}\n' https://drone.ci.commoninternet.net/
dig +short @<ip> ns-acme.commoninternet.net # acme-dns answering on the public 53
```
The opencode UI: `curl -s --resolve oc.ci.commoninternet.net:443:<ip> -o /dev/null -w '%{http_code}' https://oc.ci.commoninternet.net/`
→ 401 without credentials, 200 with `-u oc:<password>`; `fail2ban-client status nginx-http-auth`
counts the failures (it reads nginx's journal — NixOS nginx logs to stderr, not to
/var/log/nginx/error.log).
When it is healthy: `sudo nixos-rebuild switch --flake .#cc-ci` (same config, now also the boot
default). **If you are migrating from another host, do §6 before letting it serve anything**: right
after the first activation scale the `!testme` bridge to 0 and mask the two orchestrator timers so
the new box does not process PR comments or start a second weekly run while the old host is live:
```bash
docker service scale ccci-bridge_app=0
systemctl mask --now cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer
```
## 6. Migrating: restore state from the previous host
Over ssh between the hosts (`ssh root@<old> 'tar -C / -cf - <paths>' | ssh root@<new> 'tar -C / -xpf - --numeric-owner'`, or rsync), with the matching service
stopped on the new host while its directory is copied:
| path | holds | notes |
|---|---|---|
| `/var/lib/cc-ci-reports` | the published weekly report pages (`report.ci…`) | |
| `/var/lib/cc-ci-runs` | per-run artifacts the dashboard shows | |
| `/var/lib/ci-warm` | warm-canonical state + alerts | recipe warm *volumes* are caches: not copied, rebuilt by the Sunday sweep / first use |
| `/var/lib/acme` | the Let's Encrypt cert + account **and `acme-dns-accounts.json`** — the account the permanent `_acme-challenge` CNAME points at | without it a fresh registration + a new CNAME at Gandi is needed (registration is disabled in `acme-dns.nix`) |
| `/var/lib/acme-dns` | the acme-dns zone DB | |
| `/var/lib/ci-certs` | the copy traefik is handed | then `systemctl restart cc-ci-acme-traefik-handoff` |
| `/root/.abra` | abra's per-app env files for the deployed stacks | |
| Drone data volume `/var/lib/docker/volumes/drone_ci_commoninternet_net_data` | Drone's DB: the Gitea OAuth grant, repo activation, build history | `docker service scale drone_ci_commoninternet_net_app=0` on the new host, copy, scale back to 1. Otherwise run `scripts/bootstrap-drone-oauth.sh` (cc-ci repo) with the bot password and re-activate repos |
| `/srv/cc-ci-orch/.cc-ci-logs`, `/srv/cc-ci-orch/cc-ci-plan/upstream/`, `REBOOTS.md`, `JOURNAL.md` | orchestrator history, the upgrader's per-recipe release-note registry | as loops; do the final sync after stopping the orchestrator on the old host |
## 7. Cutover and verification
1. **DNS** (operator, Gandi zone `commoninternet.net`): A records `ci`, `*.ci` and `ns-acme` →
the new IPv4. `acme NS ns-acme` and `_acme-challenge.ci CNAME <account>.acme…` stay as they
are. Wait for propagation (`dig +short ci.commoninternet.net`) — the records carry a 3 h TTL,
and resolvers that cached the old answer (the Hetzner ones in particular) keep serving it that
long. The new host must not list such a resolver: with a mixed set, every other lookup of its
own names went to the old server on 2026-09-07 (runner/bridge 404s). `networking.nix` drops
the Hetzner resolvers and `configuration.nix` pins the host's own names.
2. Check the new host answers on the new IP before DNS moves: `dig @<new-ip> ns-acme.commoninternet.net`
(acme-dns), `curl --resolve ci.commoninternet.net:443:<new-ip> https://ci.commoninternet.net/`
(dashboard, valid cert), same for `report.ci` and `drone.ci`.
3. Old host: `docker service scale ccci-bridge_app=0 drone_ci_commoninternet_net_app=0`;
`systemctl disable --now cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer` on the old
orchestrator. New host: `docker service scale ccci-bridge_app=1`;
`systemctl unmask cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer && systemctl start` both.
4. End to end: post `!testme` on an open recipe PR and watch it turn green on the new Drone;
open `https://ci.commoninternet.net` and `https://report.ci.commoninternet.net`.
5. The orchestrator: as loops on the new host `cd /srv/cc-ci-orch && python3 cc-ci-plan/agents.py up orchestrator`
(or just `systemctl restart cc-ci-orchestrator`), attach with `claude --resume` or from
claude.ai/code. Its startup routine (AGENTS.md) reports phase + reboot count.
6. Keep the old host as a cold standby for a week, then delete it (and its tailnet node — the
old servers were on the tailnet; the new one is not).
## 8. Day 2
- **The host updates itself weekly**: `cc-ci-auto-update.timer` (Tuesday 03:00 UTC, - **The host updates itself weekly**: `cc-ci-auto-update.timer` (Tuesday 03:00 UTC,
`nix/modules/auto-update.nix`) runs `nix flake update` on all inputs, builds, activates with `nix/modules/auto-update.nix`) runs `nix flake update` on all inputs, builds, activates with
@@ -376,7 +44,7 @@ stopped on the new host while its directory is copied:
# Operating the orchestrator # Operating the orchestrator
The cc-ci orchestrator on this host is an **opencode agent** (`cc-ci-plan/agents.toml`: The cc-ci orchestrator on this host is an **opencode agent** (`cc-ci-plan/agents.toml`:
backend `opencode`, model `opencode/glm-5.2`), launched on boot by `cc-ci-orchestrator.service` backend `opencode`, model configured in `cc-ci-plan/agents.toml`), launched on boot by `cc-ci-orchestrator.service`
via `cc-ci-plan/agents.py up orchestrator` into tmux session `cc-ci-orchestrator`, attached to via `cc-ci-plan/agents.py up orchestrator` into tmux session `cc-ci-orchestrator`, attached to
the shared opencode web server. Steer it from the web UI, **https://oc.ci.commoninternet.net** the shared opencode web server. Steer it from the web UI, **https://oc.ci.commoninternet.net**
(basic auth, user `oc`), where the weekly upgrader's and report's sessions show up too. (basic auth, user `oc`), where the weekly upgrader's and report's sessions show up too.
@@ -400,16 +68,3 @@ stalled run to completion. Start one by hand with `systemctl start cc-ci-upgrade
`/srv/cc-ci/.cc-ci-logs/cc-ci-upgrader.log`; it ends with `UPGRADE RUN COMPLETE`, a summary in `/srv/cc-ci/.cc-ci-logs/cc-ci-upgrader.log`; it ends with `UPGRADE RUN COMPLETE`, a summary in
`.cc-ci-logs/upgrades/upgrade-all-<date>.md`, and a report published to `.cc-ci-logs/upgrades/upgrade-all-<date>.md`, and a report published to
`https://report.ci.commoninternet.net/week-<date>.html`. `https://report.ci.commoninternet.net/week-<date>.html`.
## Kick off / supervise the loops
```bash
cd /srv/cc-ci/cc-ci-plan
./launch.sh start # Builder + Adversary loops + watchdog (all phases are DONE; this just confirms)
./launch.sh status # session + DONE state
./launch.sh logs builder|adversary|watchdog
./launch.sh stop
```
Full supervision guide, credential map and history are in `cc-ci-plan/kickoff.md`,
`cc-ci-plan/plan.md` §1.5 and `cc-ci-plan/JOURNAL.md`.
+2 -1
View File
@@ -1,6 +1,6 @@
# archive/ — how cc-ci and its orchestrator were built and moved, before the combined host # archive/ — how cc-ci and its orchestrator were built and moved, before the combined host
Historical record only. Nothing in here is deployed or evaluated. It was moved out of the live Historical record. Original-build compatibility launch files are linked from `cc-ci-plan/`; the Nix unit reads those paths but the completed loops do not run. It was moved out of the live
tree on 2026-09-07 when the CI server and the orchestrator were consolidated onto one Hetzner tree on 2026-09-07 when the CI server and the orchestrator were consolidated onto one Hetzner
host (`nixosConfigurations.cc-ci` in `../flake.nix`; deploy guide in `../README.md`; the plan host (`nixosConfigurations.cc-ci` in `../flake.nix`; deploy guide in `../README.md`; the plan
that did it is `../cc-ci-plan/plan-cc-ci-combined-host.md`). that did it is `../cc-ci-plan/plan-cc-ci-combined-host.md`).
@@ -16,6 +16,7 @@ that did it is `../cc-ci-plan/plan-cc-ci-combined-host.md`).
| `plans/plan-orchestrator-hetzner-migration.md` | Incus VM → Hetzner `cpx22` move of the orchestrator (2026-05-31). Has the reboot-resilience design (`cc-ci-loops.service`). | | `plans/plan-orchestrator-hetzner-migration.md` | Incus VM → Hetzner `cpx22` move of the orchestrator (2026-05-31). Has the reboot-resilience design (`cc-ci-loops.service`). |
| `plans/plan-migrate-cc-ci-to-hetzner.md`, `plans/plan-cc-ci-hetzner-migration.md`, `plans/plan-cc-ci-hetzner-terraform.md` | The CI server's own move from the `cc-nix-test` Incus VM to Hetzner `cpx32` (`91.98.47.73`, 2026-05-31), and the terraform that provisioned it (lives in the cc-ci repo). | | `plans/plan-migrate-cc-ci-to-hetzner.md`, `plans/plan-cc-ci-hetzner-migration.md`, `plans/plan-cc-ci-hetzner-terraform.md` | The CI server's own move from the `cc-nix-test` Incus VM to Hetzner `cpx32` (`91.98.47.73`, 2026-05-31), and the terraform that provisioned it (lives in the cc-ci repo). |
| `plans/plan-repo-consolidation.md` | The earlier repo layout consolidation. | | `plans/plan-repo-consolidation.md` | The earlier repo layout consolidation. |
| `original-build/` | Completed Builder/Adversary phase plans, prompts, launchers, original agent instructions, and the first combined-host build guide. See its README. |
The cc-ci server's own history (machine-docs, decisions, the clean-room rebuild that proved The cc-ci server's own history (machine-docs, decisions, the clean-room rebuild that proved
"two repos + one age key + one `nixos-rebuild switch`") is in the cc-ci repo under "two repos + one age key + one `nixos-rebuild switch`") is in the cc-ci repo under
+147
View File
@@ -0,0 +1,147 @@
# cc-ci-orchestrator — AGENTS.md
This folder is the **orchestrator** workspace for building the **cc-ci** Co-op Cloud recipe CI
server. It holds the plan, the launch/supervision tooling, and the two loop prompts. The actual CI
project (NixOS config, test runner, recipe tests) lives in a **separate** repo the loops create at
`git.autonomic.zone/recipe-maintainers/cc-ci` — do not confuse the two.
## The agent map lives in `cc-ci-plan/orchestration.md`
That doc is the **root structure**: every agent (Builder, Adversary, Orchestrator, Assistant,
Upgrader) → its prompt + plan, plus the watchdog and the git coordination protocol. Read it first.
In short: the **Orchestrator** (*this* session/role) supervises and keeps everyone on track — it is
**separate** from the loops and is the only role that should power-cycle/recreate the host. The
**Builder** and **Adversary** loops coordinate **only** through the cc-ci git repo (`plan.md` §6.1);
the orchestrator watches from outside.
## On startup: read the journal, announce yourself, report reboots
**Every time you (the orchestrator) start or resume:**
1. **Read `cc-ci-plan/JOURNAL.md`** — the most recent `## Session` entry is where the previous
session left off. This is the persistent handoff record; read it before anything else.
2. Read `cc-ci-plan/REBOOTS.md` (count entries) and run `cc-ci-plan/launch.sh status`
(current phase + whether loops/watchdog are running).
3. **`PushNotification`** (proactive): *"cc-ci orchestrator online — phase X, loops+watchdog
running; N reboots logged (last <date>)."*
4. If loops are down, relaunch: `RESUME_PHASE=1 cc-ci-plan/launch.sh start`.
5. **On handoff / end of session:** append a `## Session` block to `JOURNAL.md` summarising
what happened, current state, and open items (see format in that file).
Reboot resilience is handled by **`cc-ci-loops.service`** (system unit): on boot it logs the reboot
to `REBOOTS.md` (boot_id-gated) and runs `launch.sh start` with `RESUME_PHASE=1`, so the loops +
watchdog auto-resume the saved phase. The orchestrator session itself is relaunched by
`cc-ci-orchestrator.service` (`agents.py up orchestrator`) as an **opencode agent** the operator
steers from https://oc.ci.commoninternet.net (no Claude on the cc-ci host; Claude sessions run on
the notplants-orchestrator box and reach cc-ci over ssh). Since 2026-09 the orchestrator runs on the **same Hetzner
host as the cc-ci CI server** (`cc-ci`, public `195.201.88.249`, tailnet `cc-ci`), declared by
`nixosConfigurations.cc-ci` in this repo's `flake.nix`, which imports the CI server from the cc-ci
repo's `nixosModules.cc-ci-server`. `ssh cc-ci` from the loops user therefore goes to loopback.
The full provisioning + deploy guide is `README.md`; the move is recorded in
`cc-ci-plan/plan-cc-ci-combined-host.md`; the previous hosts (Pi → Incus VM → Hetzner `cpx22`
shared with notplants) are in `archive/`. Rebuild this host with
`nixos-rebuild switch --flake .#cc-ci` from `/srv/cc-ci-orch` — but **always
`nixos-rebuild test` the same flake target first and verify the host is still healthy/reachable
before the `switch`** (general policy for nix deploys to this host: `test`
leaves the bootloader and system profile untouched, so a reboot always recovers to the
last-known-good generation; the 2026-08-03 cc-ci 26.05 bump outage is the cautionary tale, see
`.cc-ci-logs/server-update-2026-08-03.md`).
## Keep the orchestrator open, under remote-control
Run this session as a long-lived **interactive** session with `--remote-control` so the operator can
check in on the loops and steer/restart things from **claude.ai/code** (or the Claude mobile app)
without being at the terminal.
- **Already in the session?** Just run `/remote-control` — it attaches claude.ai/code to the live
conversation (no exit, no resume needed).
- **Starting fresh:** `claude --remote-control 'autonomous-orchestrator' --dangerously-skip-permissions`
- **Resuming this orchestrator later (history preserved):**
```bash
claude --resume autonomous-orchestrator --remote-control "autonomous-orchestrator" --dangerously-skip-permissions
```
Note the two names are different: `--resume <name|id>` restores *this conversation* (the name set
via `-n/--name`, shown in the `/resume` picker); the `--remote-control [name]` value is only the
web display label and resumes nothing. The conversation persists on disk across exits; remote
control itself only stays "connected" while the local process is alive (resume + re-enable to get
it back after a full exit).
Use it to: tail loop logs (`cc-ci-plan/launch.sh logs builder|adversary|watchdog`), inspect
`STATUS.md`/`REVIEW.md` in the cc-ci repo, edit the plan or prompts, restart a stuck loop, or
power-cycle/recreate the cc-ci VM (see `cc-ci-plan/kickoff.md` → "Fallback: restart/recreate the
cc-ci VM"). The orchestrator is the human's steering wheel; the loops are the engine.
## Loop file-location rule (machine-docs/)
In the **cc-ci loops repo**, ALL coordination / loop-state files live under `machine-docs/`, NEVER
the repo root: phase-namespaced `STATUS-*.md` / `BACKLOG-*.md` / `REVIEW-*.md` / `JOURNAL-*.md`,
shared `DECISIONS.md` / `DEFERRED.md`, and the `ADVERSARY-INBOX.md` / `BUILDER-INBOX.md`
side-channels. This is enforced in the kickoff (`launch.py build_kickoff`), the loop prompts, and
the loops' own `AGENTS.md`. If the orchestrator ever sees such a file at the root, move it into
`machine-docs/` and check the kickoff/prompts still mandate it. (The watchdog's `resolve_state` and
INBOX handoff already read `machine-docs/` first, so this is the single canonical home.)
## Launch & supervise the loops
- **Source of truth for the loops:** `cc-ci-plan/plan.md` (mission, Definition of Done, §1.5
credential map, §6 two-agent protocol, §7 loop discipline).
- **Launch/supervision guide:** `cc-ci-plan/kickoff.md`.
- `cc-ci-plan/launch.sh start` → both loops (interactive `--remote-control` in tmux) + a watchdog.
tmux is installed; `launch.sh` defaults now point at `/srv/cc-ci/...`.
## Access & credentials (pointers only — values are gitignored)
- `.testenv` (**NOT committed**): Tailscale auth key + Gitea bot creds. Load with
`set -a; . .testenv; set +a` (never echo the values).
- **cc-ci:** `ssh cc-ci` (root) directly — the orchestrator VM is a direct tailnet peer (`100.90.116.4`).
No proxy. Key: `~/.ssh/cc-ci-root-ed25519`. If unreachable, check `tailscale status`.
- **Incus/VM fallback:** mTLS certs at `/srv/incus-terraform-nix-vm-creator/terraform-secrets/`;
b1 is on the same tailnet (reach via the same proxy). See kickoff "Fallback".
- **Full credential map + how to use each:** `plan.md` §1.5.
## Hard rule
Never commit secret values. `.testenv`, `*.tfstate`, `*.key`/`*.pem`, and the loop runtime/clone
dirs are gitignored. Reference secret *locations*, never their contents (`plan.md` §9).
## Agent memory lives in `memory/` (in this repo)
The orchestrator's persistent agent memory is the **`memory/`** directory of this repo — one file
per fact with frontmatter, indexed by `memory/MEMORY.md`. The Claude auto-memory path
(`~/.claude/projects/-srv-cc-ci-orch/memory`) is a **symlink** to it, so memories written the normal
way land in the repo automatically. **Future memories must also go there**: after writing or
updating a memory file (and its `MEMORY.md` index line), commit it here and push, like any other
intentional repo change. Never put secret values in a memory file (see Hard rule).
## Commit discipline
When the orchestrator, Builder, or assistant makes intentional repository changes here, commit them
promptly and push them to `git.autonomic.zone` in append-only fashion (never force-push). Match the
existing commit author and message style in this repo. Do not bundle unrelated worktree changes you
did not make; stage only the intended files.
## Ship as PRs, merge them yourself, operator reviews retrospectively
**This applies to the two INFRASTRUCTURE repos — `recipe-maintainers/cc-ci-orchestrator` (here) and
`recipe-maintainers/cc-ci` (the CI product).** For work in either:
1. Branch, don't commit straight to `main`.
2. Open a PR with a description written to be read **after** the fact: what changed, why, and what
evidence says it works (test output, a verified run, a before/after number). The PR *is* the
review artifact and the historical record.
3. **Merge it yourself once it is verified** — do not wait for review. The invocation is the
authorization; blocking on review would stall the pipeline these repos exist to run.
4. The operator reviews **retrospectively**, from the PR.
So the PR is not a gate — it is how the work stays legible. A PR that merely says "fix scanner" has
failed at its only job.
> ### This does NOT extend to RECIPE repos
> Recipe PRs — any `coop-cloud/<recipe>` or its `recipe-maintainers/<recipe>` mirror — are
> **created and verified but NEVER merged by an agent**. Those change what deploys on other people's
> infrastructure, so a human merges them. The split is deliberate: agents own the tooling, the
> operator owns the recipes.
If work has already landed on `main` without a PR, do not rewrite published history to fix it.
Create a branch pinned at the pre-work commit and open the PR against that, so the diff is still
reviewable and merging only advances the pointer (see PRs #2-#5, 2026-08-11).
+17
View File
@@ -0,0 +1,17 @@
# Original cc-ci build archive
This is the historical Builder/Adversary phase build of the cc-ci recipe CI
server and the initial combined-host deployment. The phase work is complete;
these plans and prompts are reference material, not current operating steps.
- `cc-ci-plan/`: build plan, phase plans, loop prompts, launchers, and the
original agent configuration and instructions.
- `host-build-guide.md`: the original from-scratch host build narrative moved
from the root README.
- `AGENTS.md`: the instructions used while the two build loops were active.
Some old `cc-ci-plan/` paths remain as relative symlinks into this archive.
The unchanged Nix `cc-ci-loops` service still calls `cc-ci-plan/launch.sh` on
boot and confirms that the phase sequence is complete. The links preserve
that path and historical references; they do not mean the build loops run.
For current operation, start at the root `README.md` and `AGENTS.md`.
@@ -0,0 +1,42 @@
# cc-ci-plan
Self-contained handoff package for building the **cc-ci** Co-op Cloud recipe CI server with two
autonomous Claude loops (a Builder and an adversarial Reviewer) running over days.
## Start here
1. Read **`plan.md`** — the full plan and single source of truth (mission, Definition of Done,
architecture, milestones, the two-agent coordination protocol, loop discipline).
2. Read **`kickoff.md`** — how to launch and supervise the loops.
3. Run **`./launch.sh start`** to bring up both loops + the watchdog.
## Files
| File | Purpose |
|---|---|
| `plan.md` | The Phase-1 plan (build the CI server). Agents treat it as their single source of truth. |
| `plan-phase1c-full-reproducibility.md` | **Phase 1c** (runs first): make the VM fully reproducible from git (all secrets incl. the wildcard cert in sops, in a separate private `cc-ci-secrets` repo as a flake input; base stays well-parameterized) and do the **genuine throwaway-VM live rebuild** to close D8 honestly (the "infeasible by design" was overstated). |
| `plan-phase1b-review-lint.md` | **Phase 1b** (after 1c): deterministic linting/formatting in CI + a white-box review checklist (real tests, DRY harness, idempotent Nix, no footguns/secrets), ending in a full cold re-verification of all D1–D10 — now covering 1c's refactor. |
| `plan-phase1d-generic-test-suite.md` | **Phase 1d** (after 1b, before 2): a **generic install/upgrade/backup/restore** suite that runs on *any* recipe with zero config, with a recipe's own `test_<op>.py` **overriding or extending** the generic (Builder's call) and **reusing the generic's deployment — no redeploy**, plus optional custom install-steps; recipes needing special setup fail the generic form gracefully. The test-architecture foundation Phase 2 builds on. |
| `plan-phase1e-harness-corrections.md` | **Phase 1e** (after 1d, before 2): three operator-review corrections to the shared generic harness — (HC1) upgrade goes previous-release → **PR head** via `deploy --chaos`; (HC2) **repo-local PR code runs only for approved recipes** (default = cc-ci overlays + generic only); (HC3) the **generic runs by default** alongside an overlay, skipped only via explicit opt-out. |
| `plan-phase2-recipe-tests.md` | **Phase 2** (after Phase 1e): build on the corrected generic suite — author the recipe overlays (port recipe-maintainer tests as `test_*.py`) + define custom install steps where a recipe fails generically. |
| `plan-phase2b-test-performance.md` | **Phase 2b** (after Phase 2, before Phase 3): empirically measure where test time goes and reduce it (image cache, readiness tuning, dedup deploys, warm infra, concurrency) — no weakened tests. |
| `plan-phase3-results-ux.md` | **Phase 3** (after Phase 2b): beautiful YunoHost-style results — per-run **level**, image-forward PR comment (badge + summary card + app screenshot), polished dashboard. |
| `IDEAS.md` | Deferred/future ideas, parked out of current scope. |
| `brief.md` | The original one-page brief (context only; `plan.md` supersedes it). |
| `kickoff.md` | Launch & supervision guide. |
| `launch.sh` | Starts both loops + a watchdog; restarts dead loops; stops on `## DONE`. |
| `prompts/builder.md` | Builder loop prompt (fed to `claude` by the script). |
| `prompts/adversary.md` | Adversary loop prompt. |
## Before launching
- Set the org in `plan.md` (`git.autonomic.zone/recipe-maintainers/cc-ci`) and lock the six proof recipes (§8).
- Ensure the launching shell has: SSH+sudo to `cc-ci`, the Gitea token, `git.autonomic.zone` access.
- Preconfigure test-app DNS + TLS (plan §4.0): point a wildcard `*.ci.commoninternet.net` record at a gateway that TLS-passthroughs to cc-ci, and **pre-issue the wildcard cert** (`*.ci.commoninternet.net` + `ci.commoninternet.net`, via Gandi DNS-01) into `/var/lib/ci-certs/live/` on cc-ci. The agent handles everything else on cc-ci (Traefik file provider → that cert, swarm, routing) and does **no ACME**; renewal (~90 days) is an out-of-band operator task, so the DNS token never goes to the agent.
- `export CC_CI_REPO=https://git.autonomic.zone/recipe-maintainers/cc-ci.git` so the watchdog can detect `## DONE`.
## What "done" means
The loops stop only when all of `plan.md` §2 (D1–D10) hold **and** the Adversary has independently
re-verified each within 24h. The watchdog then tears the loops down automatically.
@@ -0,0 +1,51 @@
# Adversary verification plan — cc-ci PR #6
**PR:** https://git.autonomic.zone/recipe-maintainers/cc-ci/pulls/6
**Branch:** `feat/expected-na-and-tiny-functional` (cc-ci repo)
**Stance:** disbelieve and verify. Try to make it fail. Default to REJECT unless every check below is
green with evidence. You did NOT author this code — verify it independently, cold.
## What the PR claims
1. A `custom-html-tiny` functional test (`tests/custom-html-tiny/functional/test_serves_content.py`):
exact-byte round-trip from the served `content` volume + a real 404.
2. `recipe_meta.EXPECTED_NA = {rung: reason}` lists rungs a recipe intentionally skips; any essential
rung skipped and NOT listed is *unintentional*. Skips still cap the level (never inflate).
3. The level ladder is the FOUR essential rungs only: `install · upgrade · backup_restore · functional`
(top = L4). `integration` and `recipe_local` are OPTIONAL — not rungs, never cap, not shown as skips.
**SSO must still be enforced for the run VERDICT** (the `sso_dep_unverified` / F2-11 path in
`run_recipe_ci.py` must be intact).
4. results.json carries `skips:{intentional:{rung:reason}, unintentional:[rung]}` + `level_cap_rung`;
the card shows INTENTIONAL/UNINTENTIONAL SKIP rows; the badge shows an `expected`/`gap?` 3rd segment.
## Verification steps (run on the cc-ci host; creds in `/srv/cc-ci/.testenv`)
0. Fresh independent checkout of the PR head (do NOT reuse my working dirs):
`git clone … cc-ci` → `git checkout feat/expected-na-and-tiny-functional`. Record the HEAD sha.
1. **Full unit suite cold** (not just the touched files): `cc-ci-run -m pytest tests/unit/ -q`.
ALL must pass. A single failure → REJECT. Capture the count + any failure.
2. **Diff regression review:** `git diff origin/main...HEAD`. Confirm: (a) `level.py` RUNGS is the 4
essential rungs; (b) `derive_rungs` no longer emits integration/recipe_local; (c) the SSO VERDICT
logic in `run_recipe_ci.py` (`sso_dep_unverified`, the F2-11 fail-the-run block) is UNCHANGED —
the PR must not have weakened SSO enforcement; (d) no test was weakened/skipped; (e) no secrets.
3. **Live end-to-end harness run, FULL stages** on the real CI server:
`RECIPE=custom-html-tiny STAGES=install,upgrade,backup,restore,custom cc-ci-run runner/run_recipe_ci.py`
(set `CCCI_RUNS_DIR` to a temp dir; source `.testenv`). Then read its `results.json` and assert:
- `install` PASS and `upgrade` PASS — the upgrade tier MUST actually run and pass (essential rung;
prove it's not silently skipped). The custom tier (functional serve test) PASS.
- `level == 2`, `level_cap_rung == "backup_restore"`, `level_cap_reason` mentions L3 backup/restore.
- `rungs` has exactly install/upgrade/backup_restore/functional — **no** integration/recipe_local.
- `skips.intentional == {"backup_restore": <reason>}`, `skips.unintentional == []`.
- `backup_restore` is N/A because there is no `backupbot.backup` label (a real intentional skip,
NOT a masked failure) — confirm by inspecting the recipe compose.
- `badge.svg` contains the muted `expected` third segment (not `gap?`).
- The summary card renders and shows a green `INTENTIONAL SKIP` row for backup/restore with the reason.
4. **Non-vacuity of the functional test:** confirm it asserts the *exact random bytes* round-trip and a
404 on a random path (so a 200-everything stub would fail it) — read the test; reason about whether
it could pass against a broken server. Bonus: confirm it writes via the volume mountpoint (the SWS
image is shell-less).
5. **Teardown + hygiene:** after the run, confirm the harness left NO orphan stack/volume/container for
custom-html-tiny (deploy-count == 1; clean teardown). Confirm no secret value appears in results.json.
## Verdict
Return a clear **PASS** or **REJECT** with the evidence for each numbered step (the HEAD sha, the unit
count, the key results.json fields, the upgrade-tier verdict, the teardown state). REJECT if ANYTHING is
unproven. Do not merge — the orchestrator merges on your PASS.
@@ -0,0 +1,177 @@
# 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 orchestrator, just (re)launched, likely after a reboot. \
Do your AGENTS.md On-startup routine NOW: read cc-ci-plan/REBOOTS.md and run cc-ci-plan/launch.py \
status, then send a proactive PushNotification that you are online with the current phase and \
reboot count, and confirm cc-ci-loops.service brought the loops + watchdog back (relaunch with \
RESUME_PHASE=1 cc-ci-plan/launch.py start if not). Also read cc-ci-plan/JOURNAL.md for recent \
context before resuming supervision."""
[[agent]]
name = "builder" # tmux session: cc-ci-builder
enabled = false # operator 2026-07-10: do NOT auto-start on boot (only cc-ci-orchestrator does); start manually when running a build
kind = "loop"
role = "builder" # phase kickoff = phase preamble + prompts/builder.md
dir = "/srv/cc-ci/cc-ci"
watch = "heal+stall"
[[agent]]
name = "adversary"
enabled = false # operator 2026-07-10: do NOT auto-start on boot (only cc-ci-orchestrator does); start manually when running a build
session = "cc-ci-adv" # established convention is abbreviated (logs, remote-control)
kind = "loop"
role = "adversary"
dir = "/srv/cc-ci/cc-ci-adv"
watch = "heal+stall"
[[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 on demand or by [loop].on_complete
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"
# ─────────────────────────── the phase machine (kind="loop" agents) ───────────────────────────
[loop]
state_file = "phase-idx" # under <log_dir>/state/
resume_phase = true # keep current index across restarts (don't reset to 0)
auto_advance = true
done_marker = "## DONE"
handoff = { repo = "/srv/cc-ci/cc-ci", claim_pings = "adversary", review_pings = "builder", inboxes = ["ADVERSARY-INBOX.md", "BUILDER-INBOX.md"] }
on_complete = { trigger_file = ".run-upgrade-on-complete", run = "upgrader" }
# Transcribed verbatim from the live .phases-spec, with the duplicate `mailu` (old idx 7)
# REMOVED. Per-phase model overrides (were .loop-model[-adv]-<id> files) are inline.
# Current phase after de-dupe: cf55 (index 9) — see state/phase-idx.
phases = [
{ id = "rcust", plan = "recipe-custom-restructure-full-plan.md", status = "STATUS-rcust.md" },
{ id = "shot", plan = "plan-phase-shot-screenshots.md", status = "STATUS-shot.md" },
{ id = "lvl5", plan = "plan-phase-lvl5-lint-rung.md", status = "STATUS-lvl5.md" },
{ id = "bsky", plan = "plan-phase-bsky-fix.md", status = "STATUS-bsky.md" },
{ id = "dstamp", plan = "plan-phase-dstamp-discourse-drift.md", status = "STATUS-dstamp.md", models = { builder = "opus" } },
{ id = "mailu", plan = "plan-phase-mailu-backup.md", status = "STATUS-mailu.md" },
{ id = "kuma", plan = "plan-phase-kuma-monitor.md", status = "STATUS-kuma.md" },
{ id = "drone", plan = "plan-phase-drone-enroll.md", status = "STATUS-drone.md" },
{ id = "cfold", plan = "plan-phase-cfold-custom-folder.md", status = "STATUS-cfold.md" },
{ id = "cf55", plan = "plan-phase-cf55-gpt55-cfold-review.md", status = "STATUS-cf55.md", models = { builder = "claude-sonnet-4-6", adversary = "claude-sonnet-4-6" } },
{ id = "pvfix", plan = "plan-phase-pvfix-swarm-proxy.md", status = "STATUS-pvfix.md" },
{ id = "pvcheck", plan = "plan-phase-pvcheck-post-proxy-verification.md", status = "STATUS-pvcheck.md" },
{ id = "ghost", plan = "plan-phase-ghost-reeval.md", status = "STATUS-ghost.md" },
{ id = "cf48", plan = "plan-phase-cf48-opus-cfold-review.md", status = "STATUS-cf48.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
{ id = "pxgate", plan = "plan-phase-pxgate-proxy-healthgate.md", status = "STATUS-pxgate.md" },
# agent-orchestrator build (builder=opus, adversary=sonnet) — see plan-agent-orchestrator.md
{ id = "aoeng", plan = "plan-phase-aoeng-engine.md", status = "STATUS-aoeng.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
{ id = "aotest", plan = "plan-phase-aotest-verify.md", status = "STATUS-aotest.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
{ id = "porepo", plan = "plan-phase-porepo-project-orchestrator.md", status = "STATUS-porepo.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
{ id = "poe2e", plan = "plan-phase-poe2e-end-to-end.md", status = "STATUS-poe2e.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
# gitea full-test enrollment + LFS PR #1 verification — see plan-phase-gtea-gitea-fulltests.md (operator 2026-06-15)
{ id = "gtea", plan = "plan-phase-gtea-gitea-fulltests.md", status = "STATUS-gtea.md", models = { builder = "claude-sonnet-4-6", adversary = "claude-sonnet-4-6" } },
# dynamic upgrade base + per-recipe previous/ config (opus); validated on discourse PR #4 — see plan-phase-prevb-*.md (operator 2026-06-16)
{ id = "prevb", plan = "plan-phase-prevb-previous-dynamic-base.md", status = "STATUS-prevb.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# full all-recipe regression after prevb (sonnet) — see plan-phase-regall-*.md (operator 2026-06-16)
{ id = "regall", plan = "plan-phase-regall-recipe-regression.md", status = "STATUS-regall.md", models = { builder = "claude-sonnet-4-6", adversary = "claude-sonnet-4-6" } },
# same-version upgrade-base gap: step back to newest-older-published when last-green==head (opus, design A; B in IDEAS) — see plan-phase-samever-*.md (operator 2026-06-17)
{ id = "samever", plan = "plan-phase-samever-older-base-fallback.md", status = "STATUS-samever.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# make the canonical sweep ACTUALLY work (substitute for the hollow nightly sweep) + upstream-sync + skip-unchanged; verify end-to-end (opus) — see plan-phase-canon-*.md (operator 2026-06-17)
{ id = "canon", plan = "plan-phase-canon-canonical-sweep.md", status = "STATUS-canon.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# fix incomplete per-recipe run history on the CI dashboard (capped at latest 100 Drone builds; 362 runs exist) — source from local /var/lib/cc-ci-runs (opus) — see plan-phase-dash-*.md (operator 2026-06-17)
{ id = "dash", plan = "plan-phase-dash-recipe-history.md", status = "STATUS-dash.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# CI-server settings.toml + SKIP_CANONICALS_FOR_UPGRADE + release-tag-first no-canonical fallback (opus) — see plan-phase-settings-*.md (operator 2026-06-17)
{ id = "settings", plan = "plan-phase-settings-ci-server-config.md", status = "STATUS-settings.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# single-source the harness runtime env so the sweep timer + Drone runner SHARE deps (no duplication) — root-cause fix for DEFECT-3 drift (opus) — see plan-phase-nixenv-*.md (operator 2026-06-17)
{ id = "nixenv", plan = "plan-phase-nixenv-shared-runtime-env.md", status = "STATUS-nixenv.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# investigate ALL canon-sweep failures (discourse/mattermost-lts/mumble/bluesky/gitea/keycloak) + FIX each via recipe PR or harness improvement (opus) — see plan-phase-redfix-*.md (operator 2026-06-17)
{ id = "redfix", plan = "plan-phase-redfix-canon-sweep-failures.md", status = "STATUS-redfix.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
]
@@ -0,0 +1 @@
You are the cc-ci orchestrator, woken for your scheduled supervision pass. Read /srv/cc-ci/cc-ci-plan/orchestration.md (the agent map) and do your job per its "The orchestrator's job — keep everyone on track" section — it tells you how to find the CURRENT phase (`python3 cc-ci-plan/launch.py status`) and what to check, nudge, and do. Be decisive but minimal; if everything is healthy and active, just note the state.
@@ -0,0 +1,35 @@
we are working on making a CI server
I want you to work in an autonomous loop over the next few days until the CI server is fully functional, polished and documented
on any PR on git.autonomic.zone it should be invokable by writing !testme as a comment
this should invoke the set of CI tests to be run for the recipe code at that PR
the CI tests should be run via drone
the tests run for a recipe should be written in python. e2e testing via playwright should be used whe necessary to confirm functionality
there should be tests which test
- new install
- upgrade
- backups (including restore)
all the tests should be fully e2e, with a real deployed recipe
the CI runner should be deployed on a server called cc-ci which is running nixos
cc-ci git repo should also live on git.autonomic.zone which contains all the nix configuration for the server, as well as the code for the CI test runner
the CI test runner should have its own folder of tests, with one folder for each recipe, with each of those folders containg a set of tests as python files which get invoked for that recipe
secrets should also be handled in a reasonable and repeatable way
additionally, if a recipe repo itself contains a tests folder in the recipe, the CI runner should also invoke those tests as part of the CI run for those tests
the results of the test run should be easily viewable, with trackable logs, and a final result, very similar in style to the way the yunohost CI runner looks and feels
you will have ssh access to cc-ci server, as well as sudo access there
you will also have access to create and modify repos on git.autonomic.zone
@@ -0,0 +1,202 @@
# Concurrency restructure — full implementation plan
Expands `concurrency-restructure-plan.md` (operator-approved 2026-06-10).
Reference spec of current system: cc-ci `docs/concurrency.md`.
## Decisions locked (operator + orchestrator)
| Question | Decision |
|---|---|
| Hard deadline | **60 min** (`signal.alarm(60*60)`); recipes keep their own smaller per-tier deadlines |
| `servers/` in per-run ABRA_DIR | **symlink** to `/root/.abra/servers` — app `.env` files land in the shared canonical path, so the janitor's `abra app ls` discovery and env-based teardown work unchanged (kills the P3 orphan-env risk). Per-domain filenames + app-domain lock prevent write conflicts. `catalogue/` also symlinked (read-mostly). `recipes/` is fresh per-run — that's the isolation that matters. |
| Landing | one branch `restructure/concurrency`, one commit per phase (P1..P5 + tests), merged to main only after adversary pass + lint green; live verification on main afterwards |
| Concurrency test suite | `tests/concurrency/` — NOT in the default `pytest tests/unit` run; invoked explicitly (`pytest tests/concurrency -q`); documented in docs/concurrency.md |
## Target invariant chain
```
lock lifetime ⊆ harness process lifetime ⊆ drone step lifetime ⊆ 60-min deadline
```
Never steal a held lock; manage the holder's lifetime. Held lock = live owner (kernel-guaranteed).
---
## P1 — Lock-lifetime hardening
`runner/run_recipe_ci.py` (startup, before any abra call):
1. `PR_SET_PDEATHSIG(SIGTERM)` via `ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGTERM)`;
check return code; then `if os.getppid() == 1: sys.exit("parent died before prctl — refusing to run orphaned")`.
2. SIGTERM handler: run teardown (reuse the existing finally/teardown funnel — raise SystemExit
from the handler so `finally:` blocks run), exit non-zero.
3. Self-deadline: `signal.alarm(60*60)` + SIGALRM handler → same teardown funnel, distinct log line
(`== run exceeded 60-minute hard deadline — tearing down ==`), exit non-zero.
`.drone.yml` recipe-ci step: wrap the harness invocation:
```sh
setsid python3 runner/run_recipe_ci.py ... &
PID=$!; trap 'kill -TERM -- -$PID 2>/dev/null' TERM EXIT; wait $PID
```
(builder: verify drone exec runner signal delivery semantics; the trap must fire on drone cancel.)
Also: one-line comment on the lock `open()` noting PEP 446 makes the fd non-inheritable
(subprocess children never carry the lock).
## P2 — Flock-probe janitor (replaces the pidfile registry)
`runner/harness/lifecycle.py`:
1. New: `acquire_app_lock(domain)` — `/run/lock/cc-ci-app-<domain>.lock`, exclusive flock,
non-blocking try first → on `BlockingIOError` log
`== app lock: another run of <domain> is in flight — waiting ==` and block. Returns the kept-alive
file object. Touch mtime at acquisition (mtime = lock age for the long-held flag).
2. Call site: in `deploy_app()` exactly where `register_run_app()` is today (BEFORE app creation);
the file object must be stored on a module-level/owner object so it lives for the process lifetime.
3. Janitor rewrite (`janitor()`): for each candidate domain (discovery unchanged: `abra app ls`
matched against `RUN_APP_RE` + docker-service sweep):
- open/create its lockfile, try `LOCK_EX|LOCK_NB`:
- **acquired** → orphan → `teardown_app(domain, verify=False)` WHILE HOLDING the probe lock
(closes janitor-vs-new-run race: a new run of that domain blocks on the lock until the reap
finishes), then release + unlink lockfile.
- **held** → live run → leave it; if lockfile mtime older than 2× deadline (120 min), log:
`!! lock for <domain> held >120min — possible leaked run; inspect with lslocks` (flag, never steal).
4. Delete: `register_run_app`, `unregister_run_app`, `_run_owner_state`, `ACTIVE_RUN_DIR`,
`CCCI_JANITOR_MAX_AGE` handling + age fallback, pid-reuse guard, and their call sites
(`deploy_app`, `teardown_app`, both janitor call sites keep working — only internals change).
5. `teardown_app()` no longer unregisters; normal-exit lock release stays implicit (process exit).
Janitor unlinks lockfiles only for reaped orphans; a clean run's stale lockfile (0 bytes, unlocked)
is harmless and reaped-on-sight by the next janitor probe (unlink after acquiring probe lock,
even when no app exists for it — keep /run/lock tidy).
Edge semantics to preserve/verify:
- Two janitors racing: both probe; one wins the flock and reaps; the loser sees "held" and leaves.
Reap must be idempotent (`teardown_app(verify=False)` already tolerates half-gone stacks).
- Post-reboot: lockfiles gone (tmpfs) → probe trivially acquires → immediate reap. (Improvement
over the 2h age fallback — note in spec.)
- Warm/canonical apps never match `RUN_APP_RE` → never probed. Unchanged. DO NOT touch.
## P3 — Per-run ABRA_DIR (deletes the per-recipe flock)
`runner/run_recipe_ci.py` / `runner/harness/`:
1. Early in main(): build `run_abra_dir = /var/lib/cc-ci-runs/<build>/abra`; create it;
symlink `servers` → `/root/.abra/servers`, `catalogue` → `/root/.abra/catalogue` (builder:
verify the minimal set abra needs — probe showed it fails only on missing `servers/`);
fresh empty `recipes/`. Set `os.environ["ABRA_DIR"] = run_abra_dir` before ANY abra/harness call.
2. `fetch_recipe()` becomes a plain clone into `$ABRA_DIR/recipes/<recipe>` (no rm-rf of a shared
tree; keep the checkout-of-ref logic).
3. Delete: `acquire_recipe_lock`, `RECIPE_LOCK_DIR` recipe-lock usage, its call site in main(),
and the "must be taken before fetch_recipe" ordering rule.
4. `.drone.yml`: HOME=/root comment updated — abra config still found via symlinked servers;
recipe trees now per-run.
5. Janitor / warm-app / canonical flows that read `/root/.abra/recipes/...` (if any — builder:
grep) must be checked; they run outside a per-run ABRA_DIR and keep using the default.
6. Run-dir cleanup: `/var/lib/cc-ci-runs/<n>/` retention already exists — abra dir rides along.
## P4 — Config cleanup
- Remove `concurrency.limit` from `.drone.yml` recipe-ci pipeline; `DRONE_RUNNER_CAPACITY`
(nix/modules/drone-runner.nix `maxTests`) is the single knob. Update its comment.
## P5 — Spec rewrite
- Rewrite `docs/concurrency.md` to the new model: one mechanism (per-app-domain flock), the
invariant chain (§ lock-lifetime management), flock-probe janitor decision table, per-run
ABRA_DIR isolation, updated failure-mode table (cancel now kills harness; reboot reaps
immediately; deadline bounds everything), updated file/symbol index, and how to run
`tests/concurrency`.
---
## Test suite: `tests/concurrency/`
Real-kernel tests (no mocking of flock itself — spawn helper subprocesses that hold locks; use
tmp dirs for lock/run dirs via env/monkeypatch). NOT part of `pytest tests/unit`. Run with
`pytest tests/concurrency -q` (document in docs; CI does not run it on every build — optional
manual/nightly invocation).
Lock fundamentals:
1. acquire → child process SIGKILL'd → lock immediately acquirable (kernel auto-release).
2. probe (`LOCK_NB`) against a held lock raises `BlockingIOError`; against unheld succeeds.
3. lock fd NOT inherited: holder spawns a `subprocess` child, holder dies, child still alive →
lock acquirable (PEP 446).
4. second same-domain acquire blocks until first holder exits (double-!testme serialisation).
Janitor / probe semantics:
5. orphan (no holder) → reaped, lockfile unlinked; teardown invoked exactly once (stub teardown).
6. live (held by helper process) → never reaped, logged as live.
7. reap-under-probe-lock race: janitor holds probe lock mid-reap → a new run's acquire of the
same domain blocks until reap completes (no window where new app coexists with half-reaped one).
8. two concurrent janitors → exactly one reaps (flock arbitration), reap idempotent.
9. reboot simulation: app exists, lockfile absent → treated as orphan immediately (no age wait).
10. long-held flag: held lock with mtime backdated >120min → warning logged, NOT reaped.
11. `RUN_APP_RE` allowlist: warm/canonical-shaped names never become candidates.
12. garbled/unwritable lockfile, missing lock dir → janitor degrades safely (skip + log, never crash).
Lifetime hardening:
13. PDEATHSIG: spawn wrapper-parent + harness-child (helper script calling the real prctl setup);
kill parent → child receives SIGTERM and exits, lock released.
14. ppid race: helper started with already-dead parent (ppid 1) exits immediately.
15. deadline: helper with `alarm(2)` → teardown hook fires, exit non-zero, lock released.
16. SIGTERM → teardown funnel runs (`finally:` executed), lock released, non-zero exit.
ABRA_DIR isolation:
17. per-run dir built correctly: `servers`/`catalogue` symlinks resolve, `recipes/` empty + writable,
`ABRA_DIR` exported before first abra call (assert via stub abra recording its env).
18. two concurrent fetch_recipe of the SAME recipe into different ABRA_DIRs → both trees correct,
no cross-talk (the old corruption scenario, now safe without a lock).
19. app `.env` written through the servers symlink lands in the canonical shared path (janitor
discovery keeps working).
Each test must clean up helper processes in `finally`/fixtures (no leaked children in the test VM).
## Roles, gates & Definition of Done (loop protocol — plan.md §6.1 applies)
This phase runs as Builder/Adversary loops with phase-namespaced state files
(STATUS-conc.md, REVIEW-conc.md, BACKLOG-conc.md, JOURNAL-conc.md).
**Builder**: implements P1→P5 + the tests/concurrency suite on branch `restructure/concurrency`
in YOUR clone; one commit per phase; before each commit ALL of:
`pytest tests/unit -q`, `pytest tests/concurrency -q` (once it exists), `scripts/lint.sh` —
green. Push the branch (NOT main — main merge is gated below). Claim gates via `claim(conc): ...`
commits + STATUS-conc.md per protocol.
**Adversary**: cold-verify from your own clone. For M1: check out the branch, run both suites +
lint yourself, then adversarially review the full diff — hunt races (probe vs acquire ordering,
signal-handler reentrancy, teardown-during-teardown), deleted-code fallout (grep for dangling
references to registry symbols: register_run_app, unregister_run_app, _run_owner_state,
ACTIVE_RUN_DIR, CCCI_JANITOR_MAX_AGE, acquire_recipe_lock), gate integrity (recipe tests /
RUN_APP_RE / warm apps untouched), and test-suite blind spots vs the 19 cases above.
Default-skeptical; findings to REVIEW-conc.md.
**Gates:**
- **M1 — implementation verified.** Branch complete (P1–P5 + tests), both suites + lint green
on the Adversary's cold clone, adversarial diff review PASS in REVIEW-conc.md.
- **M2 — merged + live-verified.** After M1 PASS only, Builder merges the branch to main
(merge commit, never force) and confirms the push build green. Then live verification on the
real CI host (evidence in STATUS-conc.md, Adversary re-checks):
a. trigger an immich !testme, cancel mid-run via drone API → harness pid dies (no leaked
python), lock released, next janitor reaps the app — zero leakage;
b. two parallel !testme runs (immich PR#2 + plausible PR#3) → both green, zero leakage;
c. double-!testme same PR → second blocks on the app lock (visible in its drone log), then runs;
d. one full green run end-to-end.
**## DONE in STATUS-conc.md** only when M1 and M2 both show a fresh Adversary PASS in
REVIEW-conc.md. NOTE for both loops: recipe-mirror PRs (immich#2, plausible#3) are used as
!testme targets only — NEVER merge or push to recipe mirror repos.
## Guardrails (builder + adversary MUST honor)
- NEVER weaken recipe-test gates or touch `tests/<recipe>/` content.
- cc-ci main is touched ONLY by the M2 merge after M1 PASS; all other work stays on the branch.
Never force-push. NEVER merge/push recipe mirror repos.
- No secrets in commits; reference `.testenv` / `/run/secrets` locations only.
- Don't touch `services_converged()` / paused-is-settled logic except where the plan says.
- Match repo commit style (`feat(...)`/`fix(harness)`/`test(...)`/`docs:`).
## Rollback
Single revert of the merge commit restores the registry+recipe-flock world; no data migration
(lock/registry state is tmpfs-ephemeral, old and new harness can't run simultaneously anyway —
deploys land from main atomically per build).
@@ -0,0 +1,60 @@
# Concurrency restructure — concise plan (for review)
Goal: collapse the two concurrency mechanisms (per-recipe flock + pidfile registry/janitor)
into **one primitive** — a per-app-domain kernel flock — and make lock lifetime bounded by
construction. Reference: cc-ci `docs/concurrency.md` §8.
## Target invariant chain
```
lock lifetime ⊆ harness process lifetime ⊆ drone step lifetime ⊆ hard deadline
```
Never steal a held lock; manage the holder's lifetime. A held lock = live owner (kernel-guaranteed).
## Phases (each independently landable, in order)
### P1 — Lock-lifetime hardening (no behavior change to locking model)
- Harness startup: `PR_SET_PDEATHSIG(SIGTERM)` + post-prctl `getppid()==1` race check
→ drone cancel now kills the harness, fixing the leaked-python gap.
- `.drone.yml` step wrapper: `setsid` + trap killing the process group on TERM/EXIT.
- Self-deadline: `signal.alarm(90*60)` → teardown + exit. Hard upper bound on any run.
- Verify: trigger a build, cancel via API, assert harness pid gone + app torn down by next janitor.
### P2 — Flock-probe janitor (replace the pidfile registry)
- Run start: exclusive flock on `/run/lock/cc-ci-app-<domain>.lock` **before app creation**,
held for process lifetime (also serialises double-`!testme` of the same PR/ref).
- Janitor: probe each candidate's lockfile with `LOCK_EX|LOCK_NB`.
Acquirable → orphan → reap **while holding the probe lock** (closes janitor-vs-new-run race).
Held → live run → leave; if lockfile mtime > 2× max run time, log loudly (`lslocks` hint) — flag, never steal.
- Delete: `register_run_app`, `unregister_run_app`, `_run_owner_state`, `ACTIVE_RUN_DIR`,
`CCCI_JANITOR_MAX_AGE` + age fallback, pid-reuse guard.
- Bonus: post-reboot orphans reaped immediately (locks gone = acquirable) instead of after 2h.
- Keep: `RUN_APP_RE` allowlist, candidate discovery (abra ls + docker-service sweep).
### P3 — Per-run ABRA_DIR (delete the per-recipe flock)
- Each build: `ABRA_DIR=/var/lib/cc-ci-runs/<n>/abra`, seeded with the server config
(verified: abra honors `ABRA_DIR`; fails only on missing `servers/`).
- `fetch_recipe` becomes a plain clone into a fresh dir (no rm-rf of a shared tree).
- Delete: `acquire_recipe_lock` + `/run/lock/cc-ci-recipe-*` + the "before fetch_recipe" ordering rule.
- Wins: same-recipe PRs truly parallel (kills head-of-line blocking §8.2); manual operator
activity on `/root/.abra` can no longer corrupt CI runs (§8.3/§8.4 moot).
- Risk to resolve: orphaned app's `.env` lives in the dead run's tree — janitor must rely on the
existing env-less teardown path (docker-service sweep). Confirm `teardown_app(verify=False)`
fully works without the `.env`.
### P4 — Config cleanup
- Drop `concurrency.limit` from `.drone.yml`; `DRONE_RUNNER_CAPACITY` (drone-runner.nix)
becomes the single knob (§8.6).
### P5 — Spec rewrite
- Rewrite `docs/concurrency.md` to the new model (one mechanism, one table) + §10 lock-lifetime chain.
## Out of scope (do not touch)
- `services_converged()` / paused-is-settled logic; `RUN_APP_RE`; recipe-test gates; warm/canonical apps.
## Open questions for review
1. P3 server-config seeding: copy vs symlink of `$ABRA_DIR/servers/<server>`? (symlink simpler;
copy isolates harder — does abra write into `servers/` during a run? e.g. app `.env` lives there → copy needed, per-run env file then dies with the run dir, see P3 risk.)
2. Self-deadline value: 90 min ok? (longest observed green run ~35 min incl. flock wait.)
3. Land P1+P2 together or separately? (P2 testable solo; P1 is pure hardening — could merge.)
@@ -0,0 +1,145 @@
# cc-ci — Kickoff & Launch
Everything needed to start the autonomous cc-ci build loop. The substance lives in `plan.md`;
this file explains how to launch and supervise the two agents.
## Folder contents
```
cc-ci-plan/
├── plan.md # THE plan — single source of truth (read this in full)
├── brief.md # original one-page brief (context only; superseded by plan.md)
├── kickoff.md # this file — how to launch & supervise
├── launch.sh # starts both loops + watchdog, stops on ## DONE
└── prompts/
├── builder.md # Builder loop prompt (fed to claude by launch.sh)
└── adversary.md # Adversary loop prompt
```
> Note: `/srv/cc-ci/cc-ci-plan/` (this folder) is the **planning + launch material**. The actual
> CI project — NixOS config, runner, tests — lives in a **separate git repo** the Builder creates
> at `git.autonomic.zone/recipe-maintainers/cc-ci`, cloned to `/srv/cc-ci/cc-ci` (Builder) and
> `/srv/cc-ci/cc-ci-adv` (Adversary). Don't confuse the two.
## Model: two independent loops (plan §6 / §6.1)
- **Builder** — builds the CI server; owns code + `STATUS.md`/`JOURNAL.md`/`DECISIONS.md` + the
`## Build backlog` section of `BACKLOG.md`.
- **Adversary** — independently disbelieves and re-verifies; owns `REVIEW.md` + `## Adversary
findings`. Holds veto over `## DONE`.
They run as two separate processes and coordinate **only** through the git repo. Single-writer file
ownership keeps concurrent pushes merge-clean.
## Two layers of "looping" — and why you want both
| Concern | Mechanism | Who provides it |
|---|---|---|
| **Iteration** — keep doing one unit of work, then wake again | `/loop` self-paced (ScheduleWakeup), per plan §7 pacing | each agent, in-session |
| **Resilience** — restart a loop whose process/sandbox died; stop all on `## DONE` | `launch.sh` watchdog (tmux + git poll) | this script |
| **Handoff signalling** — wake the *waiting* loop the moment its counterpart hands off | watchdog `handoff_check` (~30 s): Builder writes a `CLAIMED` gate → ping Adversary to verify; Adversary updates `REVIEW.md` → ping Builder to proceed | this script |
`/loop` alone is bound to its process: if the sandbox restarts, that loop is gone until something
relaunches it. The watchdog is that something. It also closes the **double-idle gap**: instead of a
pending gate/verdict sitting until the other loop's next scheduled wake, the watchdog pings the
waiting loop within ~30 s — so the Adversary can idle freely when nothing's pending (no busy-polling
or pointless re-verifying) yet still start verifying right after the Builder parks at a gate. Use all three.
## Launch
```bash
cd /srv/cc-ci/cc-ci-plan
# Optional but recommended once the repo exists, so the watchdog can detect ## DONE:
export CC_CI_REPO=https://git.autonomic.zone/recipe-maintainers/cc-ci.git
./launch.sh start # starts cc-ci-builder + cc-ci-adv + cc-ci-watchdog (tmux sessions)
./launch.sh status # session + DONE state
./launch.sh logs builder # tail a loop; also: logs adversary | logs watchdog
tmux attach -t cc-ci-builder # watch a loop live locally (detach: Ctrl-b d)
./launch.sh stop # stop everything
```
`launch.sh` is idempotent — re-running `start` won't duplicate a live session. Each agent runs as an
**interactive** `claude` in tmux (kickoff prompt passed as a positional arg, *not* piped — piping
forces print mode and breaks `/loop`). With `REMOTE_CONTROL=1` (default) each agent is launched with
`--remote-control`, so you can **watch and steer both loops from [claude.ai/code](https://claude.ai/code)**
(or the Claude mobile app) — not just via `tmux attach`. The box must be logged into the claude.ai
account (`claude auth status`); set `REMOTE_CONTROL=0` to skip the remote surface. The watchdog
(default every 300s) restarts any dead session — note a >~10-min network outage will exit the
`claude` process, after which the watchdog brings it back (a fresh remote-control session) — and
when `STATUS.md` shows `## DONE`, it kills the loops and exits.
Prerequisites the sessions inherit from your shell: SSH (root) to `cc-ci` directly (the orchestrator
VM is a direct tailnet peer — no proxy; §1.5), Gitea bot creds, and `git.autonomic.zone` access. Plus **preconfigured** operator inputs the
loop depends on (plan §4.0/§4.4): the wildcard `*.ci.commoninternet.net` DNS record pointing at a
gateway that TLS-passthroughs to cc-ci, and the **pre-issued wildcard cert** at
`/var/lib/ci-certs/live/` on cc-ci. The operator owns the DNS record + gateway + cert
issuance/renewal; the agent builds Traefik (file provider → that cert) + routing on cc-ci and does
**no ACME**. If any prerequisite is absent, the Builder parks at `STATUS.md ## Blocked` (plan §1/§9)
rather than improvise.
> Host deps: `launch.sh` needs **tmux** (and `claude`) — both are installed on the VM (NixOS). The script's `*_DIR`
> defaults now point at `/srv/cc-ci/...` (Builder clone `/srv/cc-ci/cc-ci`, Adversary
> `/srv/cc-ci/cc-ci-adv`); override the `*_DIR` env vars only if your layout differs.
## Optional: a cloud-side `/schedule` watchdog
`launch.sh`'s watchdog is itself a local process — if the *whole host* goes down it stops too. For
belt-and-suspenders durability, also create a `/schedule` routine (a remote agent that fires on a
cron and re-orients from the repo). From inside a Claude session:
```
/schedule every 2 hours: read /srv/cc-ci/cc-ci-plan/plan.md §7 and the cc-ci repo STATUS.md; if the
Builder/Adversary loops are not making progress (or launch.sh is not running), restart them via
/srv/cc-ci/cc-ci-plan/launch.sh start; stop when STATUS.md says ## DONE.
```
This complements the local watchdog: scheduled runs are fresh, independent agents, so they survive
process/context death that would take the in-session `/loop` and the local watchdog with it.
## Fallback: restart/recreate the cc-ci VM (orchestrator only)
**This is primarily an escape hatch for *you*, the supervising orchestrator.** The loops normally
reconfigure cc-ci only from inside (via Nix); power-cycling or recreating the VM shouldn't be their
default move — but it's not forbidden if one gets genuinely stuck. Reach for this when cc-ci itself
is wedged at a level that can't be fixed from inside (won't boot, disk full, swarm/Docker corrupted,
unreachable even after a proxy restart): use the Incus skill to power-cycle or rebuild the VM, then
re-bootstrap.
`cc-nix-test` (the cc-ci server, tailnet `100.90.116.4`) is a **NixOS Incus VM** on host **b1**
(`100.117.251.31:8443`, Incus project `terraform-ci`). Skill + Terraform live at
`/srv/incus-terraform-nix-vm-creator/` (`skills/incus-terraform/SKILL.md`); read that for full usage.
- **Access:** b1 (`100.117.251.31`) is reachable directly from the orchestrator VM (same tailnet).
Use the mTLS certs at `terraform-secrets/` — no proxy. Quick check:
```bash
CRT=/srv/incus-terraform-nix-vm-creator/terraform-secrets/terraform.crt
KEY=/srv/incus-terraform-nix-vm-creator/terraform-secrets/terraform.key
curl --cert "$CRT" --key "$KEY" -k -s \
https://100.117.251.31:8443/1.0/instances/cc-nix-test/state?project=terraform-ci
```
- **Soft restart (keeps the disk — preferred):** `POST .../1.0/instances/cc-nix-test/state?project=terraform-ci`
with `{"action":"restart"}` (or `"stop"` / `"start"`).
- **Full recreate (last resort):** the Terraform module in `/srv/incus-terraform-nix-vm-creator/projects/`
(`terraform apply` with `-var incus_remote_address=100.117.251.31 -var incus_project=terraform-ci
-var ts_auth_key=$TSKEY`). ⚠ **Recreating wipes the VM disk** — you must then re-apply the cc-ci
preconditions: the pre-issued TLS cert into `/var/lib/ci-certs/live/` and the
`cc-ci-root-ed25519` pubkey into root's `authorized_keys` (see the access notes), and the loops
re-run §1 Bootstrap. Prefer a soft restart; only recreate if the VM is truly unrecoverable.
(Project cap: keep total RAM across `terraform-ci` instances under 10 GB — check before recreating.)
## Manual launch (no script)
If you'd rather not use `launch.sh`, start each agent interactively yourself (same result, no
supervision/restart), passing the prompt as a positional argument so the session stays interactive
and remote-controllable:
```bash
claude --remote-control 'cc-ci-builder' --dangerously-skip-permissions "$(cat prompts/builder.md)"
claude --remote-control 'cc-ci-adv' --dangerously-skip-permissions "$(cat prompts/adversary.md)"
```
Do **not** pipe the prompt (`cat prompts/builder.md | claude …`) — that forces print/headless mode,
which breaks `/loop` and remote control.
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch-assistant.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch-assistant.py" "$@"
+29
View File
@@ -0,0 +1,29 @@
#!/usr/bin/env bash
set -euo pipefail
SELF_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
FLAKE_ROOT="$(readlink -f "$SELF_DIR/..")"
FLAKE_HOST="${FLAKE_HOST:-cc-ci-orchestrator-hetzner}"
DEFAULT_MODEL="${LOOP_MODEL:-openai/gpt-5.4}"
ensure_opencode_web() {
if ! systemctl is-enabled --quiet opencode-web.service; then
sudo nixos-rebuild switch --flake "$FLAKE_ROOT#$FLAKE_HOST"
fi
if ! systemctl is-active --quiet opencode-web.service; then
sudo systemctl start opencode-web.service
fi
}
ensure_opencode_web
export LOOP_BACKEND=opencode
export LOOP_MODEL="$DEFAULT_MODEL"
export ORCH_SESSION="${ORCH_SESSION:-cc-ci-orchestrator-oc}"
if [ "$#" -eq 0 ]; then
set -- fresh
fi
exec python3 "$SELF_DIR/launch-orchestrator.py" "$@"
@@ -0,0 +1,233 @@
#!/usr/bin/env python3
"""
cc-ci orchestrator launcher — start/resume the orchestrator session in tmux.
The orchestrator is the long-lived supervisory session: it watches the Builder/Adversary
loops, reads their logs/STATUS, edits the plan/prompts, restarts stuck loops, and owns
the VM-level fallback. It is SEPARATE from the loops that launch.py manages.
Usage:
launch-orchestrator.py start resume the persistent session (default)
launch-orchestrator.py fresh start a NEW session (no --resume)
launch-orchestrator.py stop kill the tmux session (conversation persists on disk)
launch-orchestrator.py status show session state
launch-orchestrator.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"
claude backend:
CLAUDE_BIN claude
REMOTE_CONTROL 1 (viewable at claude.ai/code)
ORCH_SESSION_ID override the resume id (else read from $ID_FILE)
ORCH_ID_FILE $LOG_DIR/.orchestrator-session-id
ORCH_STARTUP_PROMPT startup nudge injected as the first turn after --resume
opencode backend:
OPENCODE_BIN /home/loops/.local/bin/opencode
OPENCODE_SERVER http://127.0.0.1:4096
(no --resume equivalent; STARTUP_PROMPT is sent as the initial message;
the session title in the web UI is the SESSION name)
"""
import json, os, shlex, sys, subprocess
from datetime import datetime
from pathlib import Path
# ── config ────────────────────────────────────────────────────────────────────
SESSION = os.environ.get("ORCH_SESSION", "cc-ci-orchestrator")
WORKDIR = os.environ.get("ORCH_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")
# Orchestrator model: ORCH_MODEL env wins, then LOOP_MODEL, then a persisted file written
# when the operator changes the model (so watchdog-triggered restarts keep it).
_ORCH_MODEL_FILE = f"{LOG_DIR}/.orch-model"
def _read_file_default(path, default):
try:
v = open(path).read().strip()
return v or default
except FileNotFoundError:
return default
LOOP_MODEL = (os.environ.get("ORCH_MODEL") or os.environ.get("LOOP_MODEL")
or _read_file_default(_ORCH_MODEL_FILE, ""))
# claude-specific
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 = "c746050a-af11-409d-87ba-c05268e2e5d1"
ID_FILE = os.environ.get("ORCH_ID_FILE", f"{LOG_DIR}/.orchestrator-session-id")
STARTUP_PROMPT = os.environ.get("ORCH_STARTUP_PROMPT", (
"STARTUP (auto-launch): you are the cc-ci orchestrator, just (re)launched, likely after a "
"reboot. Do your AGENTS.md On-startup routine NOW: read cc-ci-plan/REBOOTS.md and run "
"cc-ci-plan/launch.py status, then send a proactive PushNotification that you are online "
"with the current phase and reboot count, and confirm cc-ci-loops.service brought the loops "
"+ watchdog back (relaunch with RESUME_PHASE=1 cc-ci-plan/launch.py start if not). "
"Also read cc-ci-plan/JOURNAL.md for recent context before resuming supervision."
))
# opencode-specific
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")
# ── helpers ───────────────────────────────────────────────────────────────────
def log(msg):
ts = datetime.now().strftime("%H:%M:%S")
print(f"[orchestrator {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):
"""Type a message into the tmux session and submit it."""
import time
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("ORCH_SESSION_ID")
if sid:
return sid
try:
v = Path(ID_FILE).read_text().strip()
return v or DEFAULT_ID
except FileNotFoundError:
return DEFAULT_ID
# ── launch ────────────────────────────────────────────────────────────────────
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}")
# Attach the orchestrator TUI to the shared opencode web server so it shows up in the
# same project/session listing as browser-created sessions.
model_env = ""
if LOOP_MODEL:
# attach has no --model flag, so inject a one-off config overlay for this session.
model_env = (
f"OPENCODE_CONFIG_CONTENT={shlex.quote(json.dumps({'model': LOOP_MODEL}))} "
)
cmd = (
f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; "
f"{model_env}NO_COLOR=1 {OPENCODE_BIN} attach {OPENCODE_SERVER} --dir {shlex.quote(WORKDIR)}"
)
log(f"starting {SESSION} (backend=opencode, model={LOOP_MODEL or 'default'})")
log(f" 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}")
# opencode: send the startup prompt once the TUI has connected (~8s).
if BACKEND == "opencode":
import time
time.sleep(8)
prompt = STARTUP_PROMPT or (
"You are the cc-ci orchestrator. Read cc-ci-plan/JOURNAL.md for full "
"context on what's happened and what needs doing, then supervise the loops."
)
# Send a pointer to the journal rather than the full prompt (avoids length limits).
bootstrap = (
"You are the cc-ci orchestrator. Start by reading cc-ci-plan/JOURNAL.md "
"(`cat cc-ci-plan/JOURNAL.md`) for full context, then check loop status "
"(`cc-ci-plan/launch.sh status`) and resume supervising."
)
_ping(SESSION, bootstrap)
# ── main ──────────────────────────────────────────────────────────────────────
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:
backend_note = (
"claude: --resume preserves conversation across reboots; viewable at claude.ai/code\n"
" opencode: fresh session each launch (no --resume); viewable at https://oc.ci.commoninternet.net"
)
print(f"""cc-ci orchestrator launcher
launch-orchestrator.py start resume the persistent session (default)
launch-orchestrator.py fresh start a new session (no --resume)
launch-orchestrator.py stop kill the tmux session
launch-orchestrator.py status show session state
launch-orchestrator.py attach tmux attach
Backend: {BACKEND} (LOOP_BACKEND env var)
Model: {LOOP_MODEL or '<backend default>'} (LOOP_MODEL env var)
Session: {SESSION} cwd={WORKDIR}
{backend_note}
""")
if __name__ == "__main__":
main()
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch-orchestrator.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch-orchestrator.py" "$@"
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch-upgrader.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch-upgrader.py" "$@"
+999
View File
@@ -0,0 +1,999 @@
#!/usr/bin/env python3
"""
cc-ci loop launcher — phase-aware Builder/Adversary loops + watchdog.
Usage:
launch.py start start loops + watchdog (resets to phase 0 unless RESUME_PHASE=1)
launch.py stop stop loops + watchdog
launch.py status show phase + session state
launch.py watchdog run the watchdog in the foreground (called by start_watchdog)
launch.py logs builder|adversary|watchdog tail a log
Env (all optional — defaults shown):
LOOP_BACKEND claude (default) | opencode
LOOP_MODEL model flag, e.g. "sonnet" (claude) or "tinfoil/deepseek-v4-pro" (opencode)
ADV_MODEL optional model override for the Adversary only (falls back to LOOP_MODEL)
RESUME_PHASE 1 = keep current phase index on start (default resets to 0)
CLAUDE_BIN claude
OPENCODE_BIN /home/loops/.local/bin/opencode
OPENCODE_SERVER http://127.0.0.1:4096
PLAN_DIR /srv/cc-ci/cc-ci-plan
BUILDER_DIR /srv/cc-ci/cc-ci
ADV_DIR /srv/cc-ci/cc-ci-adv
LOG_DIR /srv/cc-ci/.cc-ci-logs
PHASES_SPEC semicolon-separated "id|planfile|statusfile" entries
PHASE_IDX_FILE $LOG_DIR/.phase-idx
WATCH_INTERVAL 300 (seconds between heavy checks: phase DONE / heal sessions)
SIGNAL_INTERVAL 30 (seconds between handoff / stall checks)
ORCH_WAKE_INTERVAL 3600 (seconds between supervision wakes typed into the orchestrator session)
ORCH_WAKE_PROMPT $PLAN_DIR/ai-progress-monitor-prompt.txt (the supervision prompt)
STALL_IDLE 300 (idle seconds without a WAITING-UNTIL before reboot)
STALL_GRACE 180 (seconds past a WAITING-UNTIL before reboot)
"""
import hashlib, json, os, re, subprocess, sys, time
from datetime import datetime, timedelta, timezone
from pathlib import Path
# ── config ────────────────────────────────────────────────────────────────────
PLAN_DIR = os.environ.get("PLAN_DIR", "/srv/cc-ci/cc-ci-plan")
BUILDER_DIR = os.environ.get("BUILDER_DIR", "/srv/cc-ci/cc-ci")
ADV_DIR = os.environ.get("ADV_DIR", "/srv/cc-ci/cc-ci-adv")
LOG_DIR = os.environ.get("LOG_DIR", "/srv/cc-ci/.cc-ci-logs")
# Backend is read from env, falling back to a persisted file written by `start`.
# This ensures the watchdog (which runs in its own tmux session without the caller's env)
# uses the same backend/model when it restarts a dead session.
_BACKEND_FILE = os.path.join(LOG_DIR, ".loop-backend")
_PHASES_FILE = os.path.join(LOG_DIR, ".phases-spec")
_MODEL_FILE = os.path.join(LOG_DIR, ".loop-model")
_ADV_MODEL_FILE = os.path.join(LOG_DIR, ".loop-model-adv")
def _read_file_default(path, default):
try:
v = Path(path).read_text().strip()
return v if v else default
except FileNotFoundError:
return default
BACKEND = os.environ.get("LOOP_BACKEND") or _read_file_default(_BACKEND_FILE, "claude")
LOOP_MODEL = os.environ.get("LOOP_MODEL") or _read_file_default(_MODEL_FILE, "")
# Per-role override: the Adversary may run a different model (e.g. opus for review while the
# Builder runs fable). Empty → falls back to LOOP_MODEL at the call site.
ADV_MODEL = os.environ.get("ADV_MODEL") or _read_file_default(_ADV_MODEL_FILE, "")
def role_model(role):
# Per-phase override wins: a file LOG_DIR/.loop-model-<pid> (builder/shared) or
# .loop-model-adv-<pid> (adversary) pins a model for just that phase. Read fresh on
# every call (cur_idx → PHASE_IDX_FILE), so a phase transition flips the model
# automatically — e.g. opus for a hard phase, sonnet after — with no watchdog bounce.
pid = phase_id(cur_idx())
if role == "adversary":
ov = _read_file_default(os.path.join(LOG_DIR, f".loop-model-adv-{pid}"), "")
return ov or ADV_MODEL or LOOP_MODEL
ov = _read_file_default(os.path.join(LOG_DIR, f".loop-model-{pid}"), "")
return ov or LOOP_MODEL
REMOTE_CONTROL = os.environ.get("REMOTE_CONTROL", "1") == "1"
CLAUDE_BIN = os.environ.get("CLAUDE_BIN", "claude")
CLAUDE_FLAGS = os.environ.get("CLAUDE_FLAGS", "")
if os.getuid() == 0:
os.environ.setdefault("CLAUDE_DANGEROUSLY_SKIP_PERMISSIONS", "1")
else:
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")
ORCH_SESSION = os.environ.get("ORCH_SESSION", "cc-ci-orchestrator")
ORCH_LAUNCHER = os.environ.get("ORCH_LAUNCHER", f"{PLAN_DIR}/launch-orchestrator.sh")
WATCH_ORCHESTRATOR = os.environ.get("WATCH_ORCHESTRATOR", "1") == "1"
BUILDER_SESSION = "cc-ci-builder"
ADV_SESSION = "cc-ci-adv"
WATCHDOG_SESSION = "cc-ci-watchdog"
WATCH_INTERVAL = int(os.environ.get("WATCH_INTERVAL", 300))
SIGNAL_INTERVAL = int(os.environ.get("SIGNAL_INTERVAL", 30))
# Hourly supervision wake: the watchdog types this prompt into the orchestrator session
# so it reviews the loops and nudges as needed (replaces the standalone ai-progress-monitor waker).
ORCH_WAKE_INTERVAL = int(os.environ.get("ORCH_WAKE_INTERVAL", 3600))
ORCH_WAKE_PROMPT = os.environ.get("ORCH_WAKE_PROMPT", f"{PLAN_DIR}/ai-progress-monitor-prompt.txt")
STALL_IDLE = int(os.environ.get("STALL_IDLE", 300))
STALL_GRACE = int(os.environ.get("STALL_GRACE", 180))
_DEFAULT_PHASES_SPEC = ";".join([
"1c|plan-phase1c-full-reproducibility.md|STATUS-1c.md",
"1b|plan-phase1b-review-lint.md|STATUS-1b.md",
"1d|plan-phase1d-generic-test-suite.md|STATUS-1d.md",
"1e|plan-phase1e-harness-corrections.md|STATUS-1e.md",
"2w|plan-phase2w-warm-canonical-quick.md|STATUS-2w.md",
"2pc|plan-phase2pc-image-cache.md|STATUS-2pc.md",
"2|plan-phase2-recipe-tests.md|STATUS-2.md",
"2b|plan-phase2b-test-performance.md|STATUS-2b.md",
"3|plan-phase3-results-ux.md|STATUS-3.md",
"4|plan-phase4-final-review-polish-cleanup.md|STATUS-4.md",
"5|plan-phase5-verify-upgrade-flow.md|STATUS-5.md",
])
# Env wins; else a persisted file written by `start` (so status/watchdog/reboot all agree on the
# current phase set); else the default build sequence above.
PHASES_SPEC = os.environ.get("PHASES_SPEC") or _read_file_default(_PHASES_FILE, _DEFAULT_PHASES_SPEC)
PHASES = [p.split("|") for p in PHASES_SPEC.split(";")]
PHASE_IDX_FILE = os.environ.get("PHASE_IDX_FILE", f"{LOG_DIR}/.phase-idx")
# Regex patterns for session-state detection
ACTIVE_RE = re.compile(r"esc to interrupt|⠋|⠙|⠹|⠸|⠼|⠴|⠦|⠧|⠇|⠏|Running tool|▣|Build ·|· \d+")
OPENCODE_ACTIVE_RE = re.compile(
r"esc interrupt|thinking|inferring|running tool|tool call|preparing patch|reading|searching", re.I)
LIMIT_RE = re.compile(r"spend limit|usage limit|limit reached|reached your .*limit|out of (credits|tokens)", re.I)
FATAL_RE = re.compile(r"redacted_thinking|blocks cannot be modified|cannot be modified", re.I)
RECENT_ACTIVITY_RE = re.compile(r"thinking|inferring|running tool|remote control (active|connecting)|tool call|schedulewake?up", re.I)
OPENCODE_STALL_IDLE = int(os.environ.get("OPENCODE_STALL_IDLE", 900))
OPENCODE_LOG_GRACE = int(os.environ.get("OPENCODE_LOG_GRACE", 180))
# ── logging ───────────────────────────────────────────────────────────────────
def log(msg):
ts = datetime.now().strftime("%H:%M:%S")
print(f"[launch {ts}] {msg}", flush=True)
def die(msg):
log(f"ERROR: {msg}")
sys.exit(1)
# ── tmux helpers ──────────────────────────────────────────────────────────────
def session_alive(name):
return subprocess.run(
["tmux", "has-session", "-t", name],
capture_output=True
).returncode == 0
def session_command(name):
r = subprocess.run(
["tmux", "display-message", "-p", "-t", 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", name], capture_output=True)
def capture_pane(name, lines=40):
r = subprocess.run(["tmux", "capture-pane", "-pt", name], capture_output=True, text=True)
return "\n".join(r.stdout.splitlines()[-lines:]) if r.returncode == 0 else ""
def _session_log_path(session):
return Path(LOG_DIR) / f"{session}.log"
def _log_recently_touched(session, age_seconds):
try:
return (time.time() - _session_log_path(session).stat().st_mtime) <= age_seconds
except FileNotFoundError:
return False
def opencode_pane_active(session, pane, *, use_log=True):
# Completed OpenCode turns leave a static footer like "▣ Build · GPT-5.4" in
# the pane. That is not activity. Only the bottom prompt/status area should
# decide active/idle, optionally backed by a recently-written session log.
bottom = "\n".join(pane.splitlines()[-10:])
return bool(OPENCODE_ACTIVE_RE.search(bottom)) or (
use_log and _log_recently_touched(session, OPENCODE_LOG_GRACE)
)
def pane_active(session, pane, *, use_log=True):
if BACKEND == "opencode":
return opencode_pane_active(session, pane, use_log=use_log)
return bool(ACTIVE_RE.search(pane))
def _last_nonempty_line(text):
for line in reversed(text.splitlines()):
if line.strip():
return line.strip()
return ""
def pipe_to_log(session, log_path):
subprocess.run(["tmux", "pipe-pane", "-o", "-t", session, f"cat >> '{log_path}'"])
def ping_session(session, msg, submit_key="Enter"):
"""Type a message into a tmux session and submit it.
submit_key: "Enter" for claude; "C-m" for opencode (Ctrl+M = Enter).
Retries the submit key until the typed prefix is no longer visible in the content area.
opencode renders the input in the content area, so we check more lines.
"""
if not session_alive(session):
return
prefix = msg[:28]
subprocess.run(["tmux", "send-keys", "-t", session, "-l", "--", msg], capture_output=True)
time.sleep(0.5)
for _ in range(10):
subprocess.run(["tmux", "send-keys", "-t", session, submit_key], capture_output=True)
time.sleep(1)
# Check the top 20 lines of content (not just last 4 bottom UI)
if prefix not in capture_pane(session, 20):
return # message was accepted
# ── phase helpers ─────────────────────────────────────────────────────────────
def cur_idx():
try:
v = Path(PHASE_IDX_FILE).read_text().strip()
return int(v) if v.isdigit() else 0
except FileNotFoundError:
return 0
def phase_id(idx): return PHASES[idx][0]
def phase_plan(idx): return PHASES[idx][1]
def phase_status(idx): return PHASES[idx][2]
def all_ids(): return " ".join(p[0] for p in PHASES)
def resolve_state(repo_dir, basename):
"""Return the path to a loop-state file — machine-docs/ if present, else repo root."""
p = Path(repo_dir) / "machine-docs" / basename
return p if p.exists() else Path(repo_dir) / basename
# A "## DONE" heading marks real completion ONLY when its body is a substantive completion
# statement. A Builder that scaffolds a "## DONE / Not yet ..." placeholder section must not
# trip the auto-advance — that false-completed and SKIPPED the mailu phase once (2026-06-11).
_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 phase_done(status_basename):
path = resolve_state(BUILDER_DIR, status_basename)
try:
lines = path.read_text().splitlines()
except FileNotFoundError:
return False
for i, line in enumerate(lines):
if not line.startswith("## DONE"):
continue
body = next((nxt for nxt in lines[i+1:] if nxt.strip()), "") # first non-empty body line
if _DONE_PLACEHOLDER_RE.match(body):
continue # placeholder section ("Not yet ...") — keep scanning, not real
return True
return False
# ── kickoff prompt ────────────────────────────────────────────────────────────
def build_kickoff(role, idx):
pid, plan, status = phase_id(idx), phase_plan(idx), phase_status(idx)
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(PLAN_DIR) / "prompts" / f"{role}.md").read_text()
return preamble + role_prompt
# ── agent launch ──────────────────────────────────────────────────────────────
def start_agent(role, session, workdir):
if session_alive(session):
log(f"{session} already running — leaving it")
return
Path(workdir).mkdir(parents=True, exist_ok=True)
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
idx = cur_idx()
pid, plan = phase_id(idx), phase_plan(idx)
kf = Path(LOG_DIR) / f".kickoff-{session}.txt"
kf.write_text(build_kickoff(role, idx))
model = role_model(role)
model_flag = f"--model '{model}'" if model else ""
session_cwd = workdir
if BACKEND == "claude":
rc = f"--remote-control '{session}'" if REMOTE_CONTROL else ""
cmd = f"{CLAUDE_BIN} {rc} {model_flag} {CLAUDE_FLAGS} \"$(cat '{kf}')\""
log(f"starting {session} (backend=claude, phase={pid}, plan={plan}, model={model or 'default'})")
elif BACKEND == "opencode":
# Attach each TUI to the shared opencode web server so sessions are recorded the same
# way as browser-created sessions, including a populated `path` in the DB.
# We still pin the visible project root with --dir, while the kickoff instructions use
# absolute repo paths for builder/adversary work.
session_cwd = "/srv/cc-ci-orch/cc-ci"
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 {session_cwd}"
)
log(f"starting {session} (backend=opencode, phase={pid}, model={model or 'default'})")
log(f" visible at https://oc.ci.commoninternet.net")
else:
die(f"unknown BACKEND '{BACKEND}' — set LOOP_BACKEND=claude or LOOP_BACKEND=opencode")
subprocess.run(["tmux", "new-session", "-d", "-s", session, "-c", session_cwd, cmd])
pipe_to_log(session, f"{LOG_DIR}/{session}.log")
# opencode: send a short bootstrap once the TUI is ready.
# opencode TUI uses C-m (Ctrl+M = Enter) to submit messages.
# The full kickoff lives in the kickoff file; we point to it to stay under send-keys limits.
if BACKEND == "opencode":
time.sleep(12) # opencode TUI needs more time to connect to the server
bootstrap = (
f"Your full kickoff prompt is in {kf} — read it now with: "
f"`cat '{kf}'` — then follow its instructions exactly."
)
ping_session(session, bootstrap, submit_key="C-m")
def start_loops():
start_agent("builder", BUILDER_SESSION, BUILDER_DIR)
start_agent("adversary", ADV_SESSION, ADV_DIR)
def stop_loops():
for s in (BUILDER_SESSION, ADV_SESSION):
if session_alive(s):
log(f"killing {s}")
kill_session(s)
# ── usage-limit handling ──────────────────────────────────────────────────────
#
# When a session hits the usage/spend limit it prints a banner ("…limit reached ∙
# resets 3am") and sits idle. The old behaviour either blind-nudged every heavy tick
# (claude) or let the generic idle-stall reboot it — losing the banner, re-hitting
# the limit fresh, and churning. The state machine below instead:
# 1. parses the reset time from the banner and arms a quiet window until reset+45s
# (parse failure → flat 5-minute probe loop, never exponential backoff);
# 2. suppresses ALL kill/reboot healing while the window is armed — a limit-stalled
# session is NEVER rebooted;
# 3. at the window's end sends ONE nudge as a self-verifying probe: if the limit
# really lifted the session resumes (spinner clears the state next tick); if
# Claude Code re-prints the banner we re-parse and re-arm.
# State is persisted per session in LOG_DIR so a watchdog restart keeps the window.
LIMIT_PROBE_FALLBACK = int(os.environ.get("LIMIT_PROBE_FALLBACK", 300)) # flat probe cadence
LIMIT_RESET_SLACK = int(os.environ.get("LIMIT_RESET_SLACK", 45)) # s past parsed reset
RESET_RE = re.compile(r"resets?\s*(?:at\s*)?(\d{1,2})(?::(\d{2}))?\s*(am|pm)?", re.I)
def _limit_state_path(session):
return Path(LOG_DIR) / f".limited-{session}"
def _load_limit_state(session):
try:
return json.loads(_limit_state_path(session).read_text())
except Exception:
return None
def _save_limit_state(session, state):
_limit_state_path(session).write_text(json.dumps(state))
def _clear_limit_state(session):
try:
_limit_state_path(session).unlink()
except FileNotFoundError:
pass
def _parse_reset_epoch(pane):
"""Parse the reset time-of-day from a limit banner (last match = freshest banner).
Returns an epoch in local time, rolled to tomorrow if the time already passed today,
or None when unparsable."""
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(pane, now):
"""When should we next probe? Parsed reset + slack when the banner is parsable and
plausibly fresh; else flat LIMIT_PROBE_FALLBACK. Time-of-day-only banners come from
the 5-hour limit window, so a fresh reset is always ≤ ~5h away — a parse landing
further out means the stated time already passed (stale banner rolled to tomorrow):
probe soon instead of waiting most of a day. Longer (weekly) limits print a date,
which doesn't parse → flat probe loop by design."""
parsed = _parse_reset_epoch(pane)
if parsed is not None and parsed - now <= 6 * 3600:
return parsed + LIMIT_RESET_SLACK, True
return now + LIMIT_PROBE_FALLBACK, False
def _limit_nudge_msg(role):
# CAUTION: this text lands in the pane that limit_tick later greps. It must NEVER
# match LIMIT_RE (found 2026-06-11: "usage limit has reset" matched, making the
# window self-sustaining once the probe scrolled into the conversation).
if role == "orchestrator":
return ("watchdog probe: if the quota window has reset, RESUME now — "
"you are the cc-ci orchestrator; re-check loop status and continue "
"supervising 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 from "
"where you stopped; re-arm your loop pacing.")
def limit_tick(role, session, pane):
"""Unified limit state machine for both backends and the orchestrator.
Returns True while the session is inside a limit window — callers must then
suppress idle accounting, reboots, and other healing."""
state = _load_limit_state(session)
limited_now = bool(LIMIT_RE.search(pane))
if state is None:
if not limited_now or pane_active(session, pane, use_log=False):
return False
now = time.time()
until, parsed = _next_limit_until(pane, now)
if parsed:
log(f"limit hit on {role} ({session}) — banner says reset "
f"{datetime.fromtimestamp(until):%a %H:%M}; holding until then (no reboots)")
else:
log(f"limit hit on {role} ({session}) — reset time unparsable; flat "
f"{LIMIT_PROBE_FALLBACK // 60}-min probe loop (no reboots)")
_save_limit_state(session, {"until": until, "nudges": 0})
return True
# Armed window: a spinner or a vanished banner means the limit lifted.
if pane_active(session, pane, use_log=False) or not limited_now:
log(f"limit lifted on {role} ({session}) — clearing limit state")
_clear_limit_state(session)
return False
now = time.time()
if now < state.get("until", 0):
return True # quietly inside the window
# Window elapsed, banner still showing → probe. Dedupe: never stack a second probe
# while our own text sits typed-but-unsubmitted in the INPUT area (bottom lines only —
# checking the whole pane wedged the machine once a submitted probe scrolled into the
# conversation above, suppressing all further probes; found 2026-06-11).
msg = _limit_nudge_msg(role)
if msg[:28] in "\n".join(pane.splitlines()[-8:]):
return True
nudges = state.get("nudges", 0) + 1
log(f"limit probe #{nudges} on {role} ({session}) — nudging to resume")
ping_session(session, msg, submit_key=_SUBMIT)
# Self-verify: re-read the pane. A spinner with no banner = resumed; a re-printed
# banner = still limited → re-arm from the fresh banner (else flat fallback).
time.sleep(3)
pane2 = capture_pane(session, 40)
if pane_active(session, pane2, use_log=False) and not LIMIT_RE.search(pane2):
log(f"limit lifted on {role} ({session}) — probe resumed it")
_clear_limit_state(session)
# Return True ("handled this tick") so the caller does NOT continue evaluating
# its pre-resume pane capture — that stale data held an old WAITING-UNTIL and
# got a freshly-resumed session rebooted (2026-06-11 05:52). Next tick sees the
# live session normally.
return True
until, _ = _next_limit_until(pane2, now)
if nudges == 3:
log(f"WARNING: {role} ({session}) still limited after {nudges} probes — "
f"continuing flat {LIMIT_PROBE_FALLBACK // 60}-min probes; never rebooting")
_save_limit_state(session, {"until": until, "nudges": nudges})
return True
# ── session healing ───────────────────────────────────────────────────────────
def heal_session(role, session, workdir):
"""Restart a dead session; kill+restart a FATAL-wedged one; never touch a limit-stalled one."""
if not session_alive(session):
log(f"{role} ({session}) gone — restarting (phase {phase_id(cur_idx())})")
start_agent(role, session, workdir)
return
pane = capture_pane(session, 25)
if pane_active(session, pane):
return # actively working — leave it alone
if limit_tick(role, session, pane):
return # inside a usage-limit window — limit_tick owns nudging; NEVER kill
if FATAL_RE.search(pane):
log(f"FATAL session-state error on {role} ({session}) — kill + restart fresh")
kill_session(session)
start_agent(role, session, workdir)
return
# ── stall detection ───────────────────────────────────────────────────────────
_idle_since: dict[str, float] = {}
def _parse_waiting_until(pane):
"""Extract the epoch timestamp from a WAITING-UNTIL marker, or None."""
if 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:
ts = m.group(1)
dt = datetime.fromisoformat(ts.replace("Z", "+00:00"))
return dt.timestamp()
except Exception:
return None
def stall_check_one(role, session, workdir):
if not session_alive(session):
_idle_since[session] = 0.0
_clear_limit_state(session)
return
now = time.time()
pane = capture_pane(session, 40)
# Limit windows (both backends): suppress idle accounting and reboots entirely —
# a limit-stalled session must never reach the kill+reboot below.
if limit_tick(role, session, pane):
_idle_since[session] = 0.0
return
if pane_active(session, pane):
_idle_since[session] = 0.0
return
since = _idle_since.get(session) or now
_idle_since[session] = since
idle = now - since
until = _parse_waiting_until(pane)
if until is not None:
# Declared wait: only reboot once STALL_GRACE seconds past the stated time.
# Never reboot before — that races with the healthy self-wake.
if now <= until + STALL_GRACE:
return
reason = f"past its WAITING-UNTIL by {int(now - until)}s — self-wake did not fire"
else:
stall_idle = OPENCODE_STALL_IDLE if BACKEND == "opencode" else STALL_IDLE
if idle < stall_idle:
return
reason = f"idle {int(idle)}s with no WAITING-UNTIL marker"
log(f"stall: {role} ({session}) {reason} — kill + reboot")
kill_session(session)
start_agent(role, session, workdir)
_idle_since[session] = 0.0
def stall_check():
stall_check_one("builder", BUILDER_SESSION, BUILDER_DIR)
stall_check_one("adversary", ADV_SESSION, ADV_DIR)
# ── orchestrator healing ──────────────────────────────────────────────────────
def orchestrator_alive():
"""True only for the configured orchestrator tmux session.
Older versions treated any non-loop Claude process as an orchestrator, which meant idle
report/assistant sessions could mask a missing or stale orchestrator. The watchdog wakes
and heals ORCH_SESSION, so ORCH_SESSION is the only valid liveness signal here.
"""
return session_alive(ORCH_SESSION)
def orchestrator_backend_mismatch():
cmd = session_command(ORCH_SESSION)
if not cmd:
return False
expected = "opencode" if BACKEND == "opencode" else "claude"
return cmd != expected
def heal_orchestrator():
if not WATCH_ORCHESTRATOR:
return
if not Path(ORCH_LAUNCHER).is_file():
return
if orchestrator_alive():
if session_alive(ORCH_SESSION):
if orchestrator_backend_mismatch():
log(f"orchestrator ({ORCH_SESSION}) is {session_command(ORCH_SESSION)!r}, expected {BACKEND} — kill + restart")
kill_session(ORCH_SESSION)
subprocess.run([ORCH_LAUNCHER, "start"], capture_output=True)
return
pane = capture_pane(ORCH_SESSION, 25)
if pane_active(ORCH_SESSION, pane):
return
if limit_tick("orchestrator", ORCH_SESSION, pane):
return # limit window — never kill/restart the orchestrator over a limit
if FATAL_RE.search(pane):
log(f"FATAL session-state error on orchestrator ({ORCH_SESSION}) — kill + restart")
kill_session(ORCH_SESSION)
subprocess.run([ORCH_LAUNCHER, "start"], capture_output=True)
return
log(f"orchestrator not running — restarting via {ORCH_LAUNCHER}")
subprocess.run([ORCH_LAUNCHER, "start"], capture_output=True)
def wake_orchestrator():
"""Hourly supervision nudge: type the progress-monitor prompt into the orchestrator
session so it reviews the loops. Returns True when the wake was delivered (or is moot),
False when it should be retried on a later tick.
Skips (retry later) if the orchestrator is absent — heal_orchestrator restarts it — or
actively working, so we never interrupt a turn; the wake lands the moment it goes idle.
"""
if not WATCH_ORCHESTRATOR:
return True # feature off — treat as handled so the timer doesn't spin
if not session_alive(ORCH_SESSION):
return False
if _load_limit_state(ORCH_SESSION) is not None:
# Deliberately wake anyway: the hourly prompt doubles as a fallback that keeps
# the orchestrator on track even if the limit-state machinery breaks. If the
# limit is genuinely still in force the wake is harmless (banner re-prints).
log(f"orchestrator ({ORCH_SESSION}) is in a limit window — sending hourly wake anyway (fallback)")
if pane_active(ORCH_SESSION, capture_pane(ORCH_SESSION, 25)):
return False # busy — don't interrupt; retry when idle
try:
msg = " ".join(Path(ORCH_WAKE_PROMPT).read_text().split())
except FileNotFoundError:
log(f"orchestrator wake skipped — prompt file missing: {ORCH_WAKE_PROMPT}")
return True
if not msg:
return True
log(f"waking orchestrator ({ORCH_SESSION}) for scheduled supervision pass")
ping_session(ORCH_SESSION, msg, submit_key=_SUBMIT)
return True
def orch_limit_check():
"""Signal-tick limit care for the orchestrator: heal_orchestrator only runs on
heavy ticks, so this keeps the orchestrator's limit-resume latency ≤ SIGNAL_INTERVAL —
the same best treatment the loops get."""
if not WATCH_ORCHESTRATOR or not session_alive(ORCH_SESSION):
return
limit_tick("orchestrator", ORCH_SESSION, capture_pane(ORCH_SESSION, 40))
# ── handoff signalling ────────────────────────────────────────────────────────
_last_sha = ""
_adv_inbox_seen = ""
_builder_inbox_seen = ""
def handoff_reset():
global _last_sha, _adv_inbox_seen, _builder_inbox_seen
_last_sha = _adv_inbox_seen = _builder_inbox_seen = ""
def _fetch_origin():
subprocess.run(f"git -C {BUILDER_DIR!r} fetch -q origin", shell=True, capture_output=True)
def _show_pushed(path):
"""Read a file from origin/main (machine-docs/ first, then repo root)."""
for loc in (f"origin/main:machine-docs/{path}", f"origin/main:{path}"):
r = subprocess.run(
f"git -C {BUILDER_DIR!r} show {loc!r}",
shell=True, capture_output=True, text=True)
if r.returncode == 0:
return r.stdout
return ""
_SUBMIT = "C-m" if BACKEND == "opencode" else "Enter"
def handoff_check():
global _last_sha, _adv_inbox_seen, _builder_inbox_seen
_fetch_origin()
r = subprocess.run(
f"git -C {BUILDER_DIR!r} rev-parse origin/main",
shell=True, capture_output=True, text=True)
head = r.stdout.strip()
if head:
if not _last_sha:
_last_sha = head # baseline silently on first tick
elif head != _last_sha:
subjects = subprocess.run(
f"git -C {BUILDER_DIR!r} log --format=%s {_last_sha}..origin/main",
shell=True, capture_output=True, text=True).stdout
if re.search(r"^claim", subjects, re.MULTILINE | re.IGNORECASE):
log("handoff: new claim(...) commit → pinging Adversary")
ping_session(ADV_SESSION,
"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.MULTILINE | re.IGNORECASE):
log("handoff: new review(...) commit → pinging Builder")
ping_session(BUILDER_SESSION,
"watchdog ping: the Adversary pushed a verdict/finding (review(...) commit). "
"Pull REVIEW and act — proceed if it PASSes your gate, address it if it's a finding.",
submit_key=_SUBMIT)
_last_sha = head
adv_inbox = _show_pushed("ADVERSARY-INBOX.md")
builder_inbox = _show_pushed("BUILDER-INBOX.md")
def md5(s): return hashlib.md5(s.encode()).hexdigest()
if adv_inbox:
h = md5(adv_inbox)
if h != _adv_inbox_seen:
log("handoff: ADVERSARY-INBOX.md changed → pinging Adversary")
ping_session(ADV_SESSION,
"watchdog ping: the Builder pushed machine-docs/ADVERSARY-INBOX.md — "
"pull, read it, act, then delete the file (commit + push) to mark it consumed.",
submit_key=_SUBMIT)
_adv_inbox_seen = h
else:
_adv_inbox_seen = ""
if builder_inbox:
h = md5(builder_inbox)
if h != _builder_inbox_seen:
log("handoff: BUILDER-INBOX.md changed → pinging Builder")
ping_session(BUILDER_SESSION,
"watchdog ping: the Adversary pushed machine-docs/BUILDER-INBOX.md — "
"pull, read it, act, then delete the file (commit + push) to mark it consumed.",
submit_key=_SUBMIT)
_builder_inbox_seen = h
else:
_builder_inbox_seen = ""
# ── watchdog loop ─────────────────────────────────────────────────────────────
def watchdog_loop():
idx = cur_idx()
log(f"watchdog up — phase={phase_id(idx)} [{idx+1}/{len(PHASES)}] "
f"seq='{all_ids()}' signal={SIGNAL_INTERVAL}s heavy={WATCH_INTERVAL}s")
elapsed = WATCH_INTERVAL # force a heavy check on the first tick
wake_elapsed = 0 # first orchestrator wake fires after a full interval, not at startup
while True:
handoff_check()
stall_check()
orch_limit_check()
if wake_elapsed >= ORCH_WAKE_INTERVAL:
# Reset only once the wake actually lands; if the orchestrator is busy/absent,
# leave the timer tripped so we retry each tick until it's idle.
if wake_orchestrator():
wake_elapsed = 0
if elapsed >= WATCH_INTERVAL:
elapsed = 0
idx = cur_idx()
pid = phase_id(idx)
status = phase_status(idx)
if phase_done(status):
next_idx = idx + 1
if next_idx < len(PHASES):
log(f"PHASE {pid} DONE — auto-transitioning to {phase_id(next_idx)}")
stop_loops()
Path(PHASE_IDX_FILE).write_text(str(next_idx))
handoff_reset()
start_loops()
else:
log(f"PHASE SEQUENCE COMPLETE (last phase {pid} DONE) — stopping loops")
stop_loops()
ts = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
Path(LOG_DIR, "SEQUENCE-COMPLETE").write_text(
f"cc-ci phase sequence complete {ts}. Phases: {all_ids()}. "
f"Loops stopped; entire build finished.\n")
# One-shot: if the operator queued an upgrade to follow the phase run
# (touch LOG_DIR/.run-upgrade-on-complete), launch /upgrade-all now in
# place of the weekly cron. Flag is consumed so it never repeats.
trigger = Path(LOG_DIR) / ".run-upgrade-on-complete"
if trigger.exists():
trigger.unlink()
log("upgrade-on-complete flag set — launching /upgrade-all")
subprocess.run(
["python3", f"{PLAN_DIR}/launch-upgrader.py", "start"],
env={**os.environ,
"PATH": "/home/loops/.local/bin:" + os.environ.get("PATH", "")},
capture_output=True)
log("watchdog exiting.")
return
else:
heal_session("builder", BUILDER_SESSION, BUILDER_DIR)
heal_session("adversary", ADV_SESSION, ADV_DIR)
heal_orchestrator()
time.sleep(SIGNAL_INTERVAL)
elapsed += SIGNAL_INTERVAL
wake_elapsed += SIGNAL_INTERVAL
def start_watchdog():
if session_alive(WATCHDOG_SESSION):
log("watchdog already running")
return
log("starting watchdog")
script = Path(__file__).resolve()
# Forward the phase spec / idx file / backend explicitly. The watchdog tmux session is spawned
# into the existing tmux server and would otherwise NOT inherit a custom PHASES_SPEC from the
# caller's env — it would fall back to the default spec and mis-detect phase completion.
env_prefix = (
f"PHASES_SPEC='{PHASES_SPEC}' PHASE_IDX_FILE='{PHASE_IDX_FILE}' "
f"LOOP_BACKEND='{BACKEND}' LOOP_MODEL='{LOOP_MODEL}' ADV_MODEL='{ADV_MODEL}' "
)
subprocess.run([
"tmux", "new-session", "-d", "-s", WATCHDOG_SESSION, "-c", PLAN_DIR,
f"exec >>'{LOG_DIR}/watchdog.log' 2>&1; {env_prefix}python3 '{script}' watchdog"
])
def start_cleanlogs():
"""Maintain readable, greppable per-agent transcript logs (<agent>.clean.log) by tailing each
session's JSONL — costs nothing on the agents (read-only on a file claude writes anyway)."""
if session_alive("cc-ci-cleanlogs"):
log("cleanlogs already running")
return
log("starting cleanlogs (per-agent <agent>.clean.log)")
al = Path(__file__).resolve().parent / "agent-log.py"
subprocess.run(["tmux", "new-session", "-d", "-s", "cc-ci-cleanlogs", "-c", PLAN_DIR,
f"python3 '{al}' follow-all"])
# ── preflight ─────────────────────────────────────────────────────────────────
def preflight():
import shutil
if not shutil.which("tmux"):
die("tmux not found")
if BACKEND == "claude":
if not shutil.which(CLAUDE_BIN):
die(f"claude CLI not found — set CLAUDE_BIN (currently: {CLAUDE_BIN})")
elif BACKEND == "opencode":
if not Path(OPENCODE_BIN).exists():
die(f"opencode not found at {OPENCODE_BIN}")
else:
die(f"unknown LOOP_BACKEND '{BACKEND}' — use 'claude' or 'opencode'")
for phase in PHASES:
plan = Path(PLAN_DIR) / phase[1]
if not plan.exists():
die(f"missing phase plan: {plan}")
for prompt_file in ("builder.md", "adversary.md"):
if not (Path(PLAN_DIR) / "prompts" / prompt_file).exists():
die(f"missing {PLAN_DIR}/prompts/{prompt_file}")
Path(LOG_DIR).mkdir(parents=True, exist_ok=True)
# ── status ────────────────────────────────────────────────────────────────────
def cmd_status():
idx = cur_idx()
pid = phase_id(idx)
print(f" phase: {pid} [{idx+1}/{len(PHASES)}] plan={phase_plan(idx)} status={phase_status(idx)}")
for s in (BUILDER_SESSION, ADV_SESSION, WATCHDOG_SESSION):
state = "RUNNING" if session_alive(s) else "stopped"
print(f" {s}: {state}")
done_str = "## DONE" if phase_done(phase_status(idx)) else "in progress"
print(f" phase {pid}: {done_str}")
seq = Path(LOG_DIR) / "SEQUENCE-COMPLETE"
if seq.exists():
print(f" >>> {seq.read_text().strip()}")
def cmd_selftest_opencode_activity():
idle_footer = """
- M1: PASS
- M2: IN PROGRESS
▣ Build · GPT-5.4 · 2m 19s
┃
┃
┃
╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
178.4K (17%) ctrl+p commands
"""
active_footer = """
~ Preparing patch...
▣ Build · GPT-5.4
┃
┃
┃
╹▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀
⬝⬝⬝■■■■■ esc interrupt 137.6K (13%) ctrl+p commands
"""
limit_footer = idle_footer + "\nYou've hit your weekly limit · resets Jun 16, 10pm (UTC)\n"
checks = [
("completed OpenCode footer is idle", not opencode_pane_active("__selftest__", idle_footer, use_log=False)),
("live OpenCode footer is active", opencode_pane_active("__selftest__", active_footer, use_log=False)),
("limit banner plus completed footer is not active", not opencode_pane_active("__selftest__", limit_footer, use_log=False)),
]
failed = [name for name, ok in checks if not ok]
if failed:
for name in failed:
print(f"FAIL: {name}")
sys.exit(1)
print("opencode activity selftest PASS")
# ── main ──────────────────────────────────────────────────────────────────────
def main():
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
if cmd == "start":
preflight()
stop_loops()
if os.environ.get("RESUME_PHASE") != "1":
Path(PHASE_IDX_FILE).write_text("0")
seq = Path(LOG_DIR) / "SEQUENCE-COMPLETE"
if seq.exists():
seq.unlink()
# Persist backend/model so the watchdog uses them when restarting dead sessions.
Path(_BACKEND_FILE).write_text(BACKEND)
Path(_MODEL_FILE).write_text(LOOP_MODEL)
Path(_ADV_MODEL_FILE).write_text(ADV_MODEL)
Path(_PHASES_FILE).write_text(PHASES_SPEC)
log(f"backend={BACKEND} model={LOOP_MODEL or '<default>'} "
f"adv-model={ADV_MODEL or '<same>'} (persisted to {_BACKEND_FILE})")
log(f"phases='{all_ids()}' (persisted to {_PHASES_FILE})")
start_loops()
start_watchdog()
start_cleanlogs()
log(f"started at phase {phase_id(cur_idx())}.")
elif cmd == "watchdog":
preflight()
watchdog_loop()
elif cmd == "status":
cmd_status()
elif cmd == "selftest-opencode-activity":
cmd_selftest_opencode_activity()
elif cmd == "stop":
stop_loops()
if session_alive(WATCHDOG_SESSION):
log(f"killing {WATCHDOG_SESSION}")
kill_session(WATCHDOG_SESSION)
log("stopped.")
elif cmd == "logs":
sub = sys.argv[2] if len(sys.argv) > 2 else ""
log_files = {
"builder": f"{LOG_DIR}/{BUILDER_SESSION}.log",
"adversary": f"{LOG_DIR}/{ADV_SESSION}.log",
"watchdog": f"{LOG_DIR}/watchdog.log",
}
if sub not in log_files:
die("usage: launch.py logs builder|adversary|watchdog")
os.execvp("tail", ["tail", "-f", log_files[sub]])
else:
print(f"""cc-ci loop launcher (phase-aware)
launch.py start start loops + watchdog (RESUME_PHASE=1 to keep current phase)
launch.py stop stop loops + watchdog
launch.py status show phase + session state
launch.py logs builder|adversary|watchdog tail a log
launch.py watchdog run watchdog in foreground
Backend: {BACKEND} Model: {LOOP_MODEL or '<default>'} Adversary model: {ADV_MODEL or '<same>'}
Phase sequence ({len(PHASES)} phases, auto-advance on ## DONE, stop after last):
{all_ids()}
""")
if __name__ == "__main__":
main()
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch.py" "$@"
+33
View File
@@ -0,0 +1,33 @@
#!/usr/bin/env bash
# msg-loop.sh — reliably send a message to a loop's tmux session AND submit it.
# -------------------------------------------------------------------------
# `tmux send-keys -l <long message>` frequently leaves the text sitting UNSENT in
# the input box (the immediate Enter is swallowed while the TUI is still ingesting
# the paste). This types the message, then retries Enter/C-m until the text is no
# longer in the input box (= it was submitted), or gives up after a bounded loop.
#
# msg-loop.sh <tmux-session> <message...>
# exit 0 = delivered; 2 = could not confirm submit; 1 = bad args / no session.
set -uo pipefail
S="${1:?usage: msg-loop.sh <session> <message...>}"; shift
MSG="$*"
[ -n "$MSG" ] || { echo "msg-loop: empty message"; exit 1; }
tmux has-session -t "$S" 2>/dev/null || { echo "msg-loop: no tmux session '$S'"; exit 1; }
PREFIX="$(printf '%s' "$MSG" | head -c 28)"
# Submitted ⇔ the message's leading text is no longer in the input box (bottom of the pane).
in_input_box() { tmux capture-pane -pt "$S" 2>/dev/null | tail -4 | grep -qF -- "$PREFIX"; }
tmux send-keys -t "$S" -l -- "$MSG" 2>/dev/null || { echo "msg-loop: send-keys failed"; exit 1; }
sleep 0.8
for _ in 1 2 3 4 5 6 7 8 9 10; do
tmux send-keys -t "$S" Enter 2>/dev/null || true
sleep 1.2
in_input_box || { echo "$S: delivered ✔"; exit 0; }
tmux send-keys -t "$S" C-m 2>/dev/null || true # some TUI states take C-m not Enter
sleep 0.8
in_input_box || { echo "$S: delivered ✔"; exit 0; }
done
echo "$S: WARNING — could not confirm submit; message may remain in the input box"
exit 2
@@ -0,0 +1,63 @@
# orchestration.md — cc-ci agent map (root)
The root structure of the cc-ci build system: who the agents are, where each one's **prompt** and
**plan** live, and how they're kept on track. **Start here.** The watchdog and the coordination
protocol are the subtlety beneath this map (see the last two sections).
## Agents
| Agent | Role (one line) | Prompt | Plan / SSOT | Session · workdir · launcher |
|---|---|---|---|---|
| **Builder** | Builds the CI server; one of two independent loops | `cc-ci-plan/prompts/builder.md` | the **current phase plan** (`launch.py status` names it) + master `cc-ci-plan/plan.md` | `cc-ci-builder` · `/srv/cc-ci/cc-ci` · `launch.py` |
| **Adversary** | Independently disbelieves & verifies the Builder; owns REVIEW + veto | `cc-ci-plan/prompts/adversary.md` | same current phase plan (verifies against it) + `plan.md` | `cc-ci-adv` · `/srv/cc-ci/cc-ci-adv` · `launch.py` |
| **Orchestrator** | **Keeps everyone on track** — supervises, nudges, fixes plans/prompts, owns the host-level fallback | wake: `cc-ci-plan/ai-progress-monitor-prompt.txt` → **this doc (§The orchestrator's job)** | this doc + `cc-ci-plan/JOURNAL.md` (handoff record) | `cc-ci-orchestrator` · `/srv/cc-ci-orch` · `launch-orchestrator.py` |
| **Assistant** | One-shot agent dispatched for cross-cutting passes (e.g. mirror reconcile); idle unless dispatched | assignment set at launch (`launch-assistant.py`) | the task it's dispatched with | `cc-ci-assistant` · `/srv/cc-ci-orch` · `launch-assistant.py` |
| **Upgrader** | Weekly one-shot: runs `/upgrade-all` (recipe-upgrade survey + PRs, never merges) | the `/upgrade-all` skill | triggered by the `cc-ci-upgrade-all` systemd timer (Sun 02:00 UTC) | `cc-ci-upgrader` · `/srv/cc-ci` · `launch-upgrader.py` |
Phases are defined in `.cc-ci-logs/.phases-spec` (id|planfile|statusfile, persisted by `launch.py
start`); `launch.py status` shows the current one. Backend is `claude`/`sonnet` (`.loop-backend`/
`.loop-model`).
## The orchestrator's job — keep everyone on track
On each scheduled wake (and on startup — see `AGENTS.md`):
1. **Current phase, read live:** `python3 cc-ci-plan/launch.py status` → current phase id, its plan
file, its `STATUS-<id>.md`. Never assume a phase; whatever it reports IS the phase.
2. **Live-state checks:** builder/adv/watchdog panes (`tmux capture-pane -pt …`); `.loop-backend`=claude
& `.loop-model`=sonnet; `ssh cc-ci hostname` reachable.
3. **Keep them moving** — only intervene where the watchdog can't:
- Builder stalled / idle past its WAITING-UNTIL with no work → nudge to continue the current phase.
- Adversary stale / on old evidence → nudge to re-orient + verify outstanding claims.
- Loop at high context (≳85%) → nudge it to `/compact` (lossless; state is in git + STATUS/REVIEW).
- Loop session missing → `RESUME_PHASE=1 LOOP_BACKEND=claude LOOP_MODEL=sonnet python3 cc-ci-plan/launch.py start`.
- **Revised a plan a loop is already working in?** Ping the session to re-read it — loops read the
plan at kickoff and won't see later edits unless told.
4. **Completion:** a phase is done when its `STATUS-<id>.md` has a line starting with `## DONE`; the
watchdog auto-advances. When the LAST phase finishes the watchdog writes `SEQUENCE-COMPLETE`, stops
the loops, and exits (so the hourly wake stops too) → append to `JOURNAL.md` + proactive PushNotification.
5. **Be decisive but minimal.** Healthy + active → just note the state. Don't make unrelated changes.
## Subtlety: the watchdog (`launch.py watchdog`)
A non-agent supervisor loop (`cc-ci-watchdog` tmux session, started by `launch.py start` / the
`cc-ci-loops.service` boot unit). It: heals dead/wedged loop sessions, **pings the other loop on every
`claim(...)`/`review(...)` commit** (the handoff signal), enforces liveness (kills+reboots a loop idle
past its `WAITING-UNTIL`), **auto-advances phases** when a `STATUS-<id>.md` hits `## DONE`, and writes
`SEQUENCE-COMPLETE` at the end. It also fires the **hourly orchestrator wake** (this doc, via the wake
prompt). It does NOT compact loops or make decisions — that's the orchestrator.
## Subtlety: coordination protocol (`plan.md` §6.1)
The two loops coordinate **only** through the cc-ci git repo — never directly:
- `git pull --rebase` before every edit; smallest change; commit; push (never `--force`).
- **Commit-prefix convention** (the watchdog depends on it): `claim(...)` = Builder claims a gate;
`review(...)` = Adversary verdict. Those prefixes ARE the handoff signal.
- Phase-namespaced state files in the repo: `STATUS-<id>.md`, `BACKLOG-<id>.md`, `REVIEW-<id>.md`,
`JOURNAL-<id>.md`; `DECISIONS.md` is shared.
- Inbox side-channels for non-gate messages: `BUILDER-INBOX.md` / `ADVERSARY-INBOX.md` (watchdog
edge-pings on appearance; consumer deletes on read).
- Full rules: `plan.md` §6.1 (coordination), §7 (pacing/liveness), §9 (guardrails).
## See also
- `AGENTS.md` — orchestrator on-startup routine + host/reboot facts (Hetzner `cpx22`).
- `plan.md` — master build SSOT.
@@ -0,0 +1,8 @@
Stop the existing orchestrator tmux session:
ORCH_SESSION=cc-ci-orchestrator cc-ci-plan/launch-orchestrator.sh stop
Start a fresh opencode-attached orchestrator session:
LOOP_BACKEND=opencode LOOP_MODEL=openai/gpt-5.4 ORCH_SESSION=cc-ci-orchestrator cc-ci-plan/launch-orchestrator.sh fresh
Alternative: start it under a separate tmux session name instead of replacing the Claude one:
LOOP_BACKEND=opencode LOOP_MODEL=openai/gpt-5.4 ORCH_SESSION=cc-ci-orchestrator-oc cc-ci-plan/launch-orchestrator.sh fresh
@@ -0,0 +1,92 @@
#!/usr/bin/env bash
# Overnight runner — after the Assistant finishes consolidating recipe PRs, run the weekly
# /upgrade-all (full test run over every enrolled recipe) and collect a morning report.
#
# Polls in pure bash (NO claude) so it doesn't burn the shared claude usage budget — only the
# /upgrade-all run itself spends tokens. Runs detached in tmux session `cc-ci-overnight`.
#
# tmux new-session -d -s cc-ci-overnight 'bash /srv/cc-ci/cc-ci-plan/overnight-run.sh'
set -uo pipefail
LOG=/srv/cc-ci/.cc-ci-logs/overnight-run.log
DONE_MARKER=/srv/cc-ci/.cc-ci-logs/pr-consolidation.done # Assistant writes this when consolidation is finished
PLAN=/srv/cc-ci/cc-ci-plan
ORCH=cc-ci-orchestrator
TODAY=$(date -u +%Y-%m-%d)
REPORT=/srv/cc-ci/.cc-ci-logs/overnight-report-${TODAY}.md
SUMMARY=/srv/cc-ci/.cc-ci-logs/upgrades/upgrade-all-${TODAY}.md
log(){ printf '[overnight %s] %s\n' "$(date -u +%FT%TZ)" "$*" >>"$LOG"; }
active(){ tmux capture-pane -pt "$1" 2>/dev/null | grep -q 'esc to interrupt'; } # session busy?
log "=== overnight runner started ==="
# --- Gate A: wait for the Assistant's PR-consolidation done-marker (max 4h) ---
log "Gate A: waiting for assistant done-marker ($DONE_MARKER)..."
for _ in $(seq 1 48); do
[ -f "$DONE_MARKER" ] && break
sleep 300
done
if [ -f "$DONE_MARKER" ]; then log "Gate A passed — assistant done: $(head -1 "$DONE_MARKER" 2>/dev/null)"
else log "Gate A TIMED OUT (4h) — proceeding without confirmation."; fi
# --- Gate B: only run /upgrade-all after the usage-limit reset (~03:30 UTC) so it has budget ---
log "Gate B: waiting until >= 03:35 UTC (post usage-limit reset)..."
for _ in $(seq 1 36); do # cap ~3h
now=$((10#$(date -u +%H%M)))
[ "$now" -ge 335 ] && [ "$now" -lt 1200 ] && break # morning window, past reset
[ "$now" -ge 1200 ] && break # safety: never wait into the afternoon
sleep 300
done
log "Gate B passed (now $(date -u +%FT%TZ))."
# --- Gate C: let the build loops go idle so /upgrade-all doesn't contend on the Swarm (max 1h) ---
log "Gate C: waiting for builder/adversary to be idle (Swarm free)..."
for _ in $(seq 1 12); do
active cc-ci-builder || active cc-ci-adv || break
sleep 300
done
active cc-ci-builder || active cc-ci-adv && log "Gate C: loops still active after 1h — proceeding anyway." || log "Gate C passed — loops idle."
# --- Run the weekly /upgrade-all (DEFAULT: recipe PRs verified by !testme, NEVER merges) ---
log "launching /upgrade-all via launch-upgrader.py fresh ..."
LOOP_BACKEND=claude LOOP_MODEL=sonnet python3 "$PLAN/launch-upgrader.py" fresh >>"$LOG" 2>&1
# --- Wait for it to finish: the upgrader self-terminates and writes a dated summary (max ~8h) ---
log "waiting for /upgrade-all to complete (summary $SUMMARY or upgrader stop)..."
for _ in $(seq 1 96); do
sleep 300
st=$(python3 "$PLAN/launch-upgrader.py" status 2>/dev/null)
if printf '%s' "$st" | grep -qi 'stopped'; then log "upgrader reports stopped."; break; fi
done
# --- Collect the morning report ---
log "writing report $REPORT ..."
{
echo "# cc-ci overnight run — ${TODAY}"
echo
echo "Generated $(date -u +%FT%TZ) by overnight-run.sh. See $LOG for the run trace."
echo
echo "## /upgrade-all summary"
if [ -f "$SUMMARY" ]; then cat "$SUMMARY"; else echo "(no dated summary at $SUMMARY — /upgrade-all may have stalled on the usage limit or errored; check the cc-ci-upgrader session + $LOG)"; fi
echo
echo "## Open PRs per recipe (post-run)"
set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a
G="https://${GITEA_USERNAME}:${GITEA_PASSWORD}@${GITEA_URL}/api/v1"
for r in $(curl -fsS "$G/orgs/recipe-maintainers/repos?limit=100" 2>/dev/null | python3 -c "import sys,json;print('\n'.join(sorted(x['name'] for x in json.load(sys.stdin))))" 2>/dev/null); do
case "$r" in cc-ci|cc-ci-orchestrator|cc-ci-secrets|archived-*) continue;; esac
n=$(curl -fsS "$G/repos/recipe-maintainers/$r/pulls?state=open&limit=50" 2>/dev/null | python3 -c "import sys,json;d=json.load(sys.stdin);print(len(d));[print(' - #%d %s'%(p['number'],p['title'][:60])) for p in d]" 2>/dev/null)
echo " - $r: ${n%%$'\n'*} open"
printf '%s\n' "$n" | tail -n +2
done
echo
echo "## Phase / loop status"
python3 "$PLAN/launch.py" status 2>&1
} > "$REPORT" 2>&1
touch /srv/cc-ci/.cc-ci-logs/.overnight-done
log "report written. pinging orchestrator to notify the operator."
# Ask the orchestrator (which has PushNotification) to deliver the morning notification + journal it.
MSG="OVERNIGHT RUN COMPLETE — read ${REPORT} and the /upgrade-all summary, then send the operator a proactive PushNotification with the headline (did /upgrade-all complete, how many recipe PRs, overall CI state), append a completion event to cc-ci-plan/JOURNAL.md, and rm /srv/cc-ci/.cc-ci-logs/.overnight-done."
tmux send-keys -t "$ORCH" -l -- "$MSG" 2>/dev/null; sleep 1; tmux send-keys -t "$ORCH" Enter 2>/dev/null
log "=== overnight runner finished ==="
@@ -0,0 +1,44 @@
# Phase 6 / Phase 7 Operator Summary — 2026-06-01
## Phase 6 — mirror reconcile
Expected upstream source for every enrolled recipe below: `https://git.coopcloud.tech/coop-cloud/<recipe>`.
- `bluesky-pds` — mirror `main` synced; open PR #1 left open.
- `cryptpad` — mirror `main` synced; open PR #3 left open.
- `custom-html` — mirror `main` synced; open PRs #1, #2, #3 left open.
- `custom-html-tiny` — mirror `main` synced; open PRs #2, #5 left open.
- `discourse` — mirror `main` synced; open PR #1 left open.
- `ghost` — mirror `main` synced; open PR #1 was left open during phase 6 and later replaced in phase 7.
- `immich` — mirror `main` synced; open PR #1 left open.
- `keycloak` — mirror `main` created/synced from upstream `master`; stale PR #1 closed because its changes were already upstream.
- `lasuite-docs` — mirror `main` synced; stale PRs #1, #2, #3 closed because their changes were already upstream.
- `lasuite-drive` — no `recipe-maintainers/lasuite-drive` mirror repo exists; manual attention needed if this recipe should stay enrolled.
- `lasuite-meet` — mirror `main` synced; open PR #2 left open.
- `mailu` — no `recipe-maintainers/mailu` mirror repo exists; manual attention needed if this recipe should stay enrolled.
- `matrix-synapse` — mirror `main` synced; open PR #1 left open.
- `mattermost-lts` — mirror `main` synced; open PR #1 left open.
- `mumble` — no `recipe-maintainers/mumble` mirror repo exists; manual attention needed if this recipe should stay enrolled.
- `n8n` — mirror `main` synced; open PR #2 was left open during phase 6 and later replaced in phase 7.
- `plausible` — mirror `main` synced; open PR #1 left open.
- `uptime-kuma` — no `recipe-maintainers/uptime-kuma` mirror repo exists; manual attention needed if this recipe should stay enrolled.
## Phase 7 — targeted upgrades
- `n8n` — upstream target chosen: stable `2.22.6` (not pre-release `2.23.x`), plus `pgautoupgrade:18-alpine`; PR opened: `https://git.autonomic.zone/recipe-maintainers/n8n/pulls/3`; superseded pre-release PR #2 was closed; after the bridge rollout settled, a fresh `!testme` completed GREEN on `https://drone.ci.commoninternet.net/recipe-maintainers/cc-ci/61`.
- `ghost` — upstream target chosen: latest published Docker Hub stable image `6.42.0-alpine` (GitHub releases were already at `6.43.x`, but no matching published Alpine image was available); PR opened: `https://git.autonomic.zone/recipe-maintainers/ghost/pulls/2`; prior open PR #1 was closed as superseded by the current mirror workflow; verification is currently blocked because `recipe-maintainers/ghost` is not enrolled in the bridge poll set, so `!testme` comments never enter the real CI path.
- `matrix-synapse` — existing PR `https://git.autonomic.zone/recipe-maintainers/matrix-synapse/pulls/1` already matches latest stable target `7.2.0+v1.153.0`; that PR already had an older cc-ci pass comment on build `87`, and a fresh re-run today produced a new failure comment on `https://drone.ci.commoninternet.net/recipe-maintainers/cc-ci/53`.
## Bridge enrollment audit
- Phase-2 18-recipe test set: `bluesky-pds`, `cryptpad`, `custom-html`, `custom-html-tiny`, `discourse`, `ghost`, `immich`, `keycloak`, `lasuite-docs`, `lasuite-drive`, `lasuite-meet`, `mailu`, `matrix-synapse`, `mattermost-lts`, `mumble`, `n8n`, `plausible`, `uptime-kuma`.
- Repo `nix/modules/bridge.nix` poll set at completion time: `custom-html`, `custom-html-tiny`, `cryptpad`, `hedgedoc`, `keycloak`, `lasuite-docs`, `lasuite-meet`, `matrix-synapse`, `n8n` plus `recipe-maintainers/cc-ci`.
- Live bridge poll set on `cc-ci` at completion time matched the repo poll set above.
- Missing from bridge enrollment relative to the phase-2 18-recipe set: `bluesky-pds`, `discourse`, `ghost`, `immich`, `lasuite-drive`, `mailu`, `mattermost-lts`, `mumble`, `plausible`, `uptime-kuma`.
- Extra in bridge enrollment relative to the phase-2 18-recipe set: `hedgedoc`.
## Manual attention
- Decide whether `lasuite-drive`, `mailu`, `mumble`, and `uptime-kuma` should remain enrolled without mirror repos.
- Review whether the mirror workflow's current "close any other open PR when opening an upgrade PR" behavior is still desired for recipes like `ghost`, where the superseded PR was unrelated to the upgrade.
- Align bridge enrollment with the full 18-recipe test set if `ghost` and the other phase-2 recipes should be triggerable via `!testme`.
@@ -0,0 +1,127 @@
# Plan — one Hetzner host for cc-ci (CI server) + cc-ci-orchestrator
**Status:** IN PROGRESS (started 2026-09-07). Operator request: move the cc-ci CI server AND the
cc-ci orchestrator onto one new Hetzner server (`195.201.88.249`, 8 GB, 150 GB, Debian 13 image),
cleanly split off from the shared `notplants-orchestrator` box, which keeps everything else
(lichen, project-orchestrator, notplants agents). Nix config ownership: cc-ci's config in
`recipe-maintainers/cc-ci`, the orchestrator's in `recipe-maintainers/cc-ci-orchestrator`, and the
orchestrator flake **includes** cc-ci's module so one `nixos-rebuild` produces the combined host.
Last step (separate, after everything works on the current names): move both to `autonomic.zone`
subdomains.
## Facts (2026-09-07)
| | old cc-ci server | old orchestrator host (stays, becomes notplants-only) | **new combined host** |
|---|---|---|---|
| public IP | 91.98.47.73 (fsn1, Hetzner 134485294) | 168.119.126.100 (nbg1, Hetzner 134487234) | **195.201.88.249** |
| tailnet | `cc-ci` 100.95.31.88 | `cc-ci-orchestrator-1` 100.84.190.30 | `cc-ci` (new node) |
| RAM / disk | 8 GB / 150 GB (83 GB used, 59 GB docker) | 4 GB + 4 GB swap / 75 GB + 250 GB `/mnt/data` | 8 GB / 150 GB, one disk |
| built by | `cc-ci` flake `#cc-ci` (nixpkgs 26.05 rev 531670d) | `notplants-nix` flake `#notplants-orchestrator` (26.05 channel), importing `cc-ci-orchestrator`'s `nixosModules.cc-ci` | `cc-ci-orchestrator` flake `#cc-ci` importing `cc-ci`'s `nixosModules.cc-ci-server` |
| DNS | `ci.`, `*.ci.`, `ns-acme.commoninternet.net` → 91.98.47.73 (Gandi, direct, no gateway) | `oc.commoninternet.net` → 100.84.190.30 | operator repoints at cutover |
Data on the old cc-ci server that must move: `/var/lib/cc-ci-reports` (published reports),
`/var/lib/cc-ci-runs` (dashboard artifacts, 1.7 G), `/var/lib/ci-warm` (1.4 G), `/var/lib/acme`
(LE cert valid to 2026-11-29 + **acme-dns account json** that the `_acme-challenge` CNAME points at),
`/var/lib/acme-dns` (the authoritative zone DB), `/var/lib/ci-certs`, `/root/.abra` (app env files),
`/etc/cc-ci` (deployed checkout the Sunday sweep runs from), Drone's `drone_ci_commoninternet_net_data`
volume (Gitea OAuth grant + repo activation + build history). Warm recipe volumes are caches and get
rebuilt on first use / the Sunday sweep. Docker swarm secrets/configs cannot be copied; the reconcile
oneshots recreate them from sops.
Out-of-band secrets the new host needs (never in git): `/var/lib/sops-nix/key.txt` (= the master age
key, `/srv/cc-ci/.sops/master-age.txt` here — the new host's SSH host key is not a sops recipient),
`/etc/ts-auth-key`, `/srv/cc-ci/.testenv`, `/srv/cc-ci/upgrader.env`, `/srv/cc-ci/.sops/master-age.txt`,
`~loops/.ssh/{cc-ci-root,autonomic-bot-gitea,tangled}-ed25519`, `/etc/nginx/oc-*` (self-signed cert +
htpasswd for the opencode UI), claude/opencode/codex auth under `~loops`.
## Design
**cc-ci repo** (`feat/nixos-module-export`):
- `nixosModules.cc-ci-server` = `nix/modules/default.nix`: imports all service modules + the
host-generic cc-ci settings that used to sit in the host file (UTC, docker/swarm firewall 80/443,
`environment.systemPackages = ccciRuntimeTools`, allowUnfree). No hardware, no networking, no
tailscale, no root keys, no stateVersion — the host supplies those.
- New options under `cc-ci.*`: `publicIPv4` (acme-dns listen + the `ns-acme` A record),
`sopsFile` (absolute path to the decrypted-at-activation `secrets.yaml`, default the submodule
path so `#cc-ci` keeps working), `repoPath` (`/etc/cc-ci`, used by nightly-sweep).
- `nixosConfigurations.cc-ci` (old host) keeps building unchanged via the same module.
**cc-ci-orchestrator repo** (`feat/combined-cc-ci-host`):
- flake input `cc-ci` (https, public) with `nixpkgs`/`sops-nix` `follows` so one nixpkgs + one sops-nix.
- `nixosModules.cc-ci-orchestrator` (the existing `nix/modules/cc-ci.nix`, kept exported as
`nixosModules.cc-ci` too so notplants-nix keeps evaluating until it drops the input) — the loops,
orchestrator session and the weekly/hourly timers.
- `nix/modules/orchestrator-host.nix`: the host contract the module assumes — `loops` user + sudo,
nix-ld, claude/opencode/codex installers, `opencode-web`, the tailnet-only nginx `oc.` vhost
(on the tailscale IP, port **8443**, because traefik owns 80/443), tool packages, PATH.
- `nixosConfigurations.cc-ci` = `nix/hosts/cc-ci/{configuration,hardware,networking}.nix` importing
both modules. `/srv` is a plain directory (no `/mnt/data`), 8 GB swapfile, root keys, tailscale
`--hostname=cc-ci`, firewall 22 (+ what cc-ci-server opens: 80, 443, 53).
- `loops`' ssh config `Host cc-ci` → `127.0.0.1` so every `ssh cc-ci …` in skills/scripts keeps working.
- `archive/`: the retired Incus/Hetzner-orchestrator host config, old terraform, historical plans.
- `README.md`: provisioning (Hetzner Debian → nixos-infect → NixOS), secrets staging, the one
`nixos-rebuild`, data restore, cutover, verification — written so a person or an LLM can redo it.
**notplants-nix** (`chore/drop-cc-ci`, after cutover): remove the `cc-ci` input, module import, the
four cc-ci units' mount gating, `loopsSshConfig`, `opencode-web` + the `oc.` vhost (unless something
notplants-side uses it), tailscale hostname → `notplants-orchestrator`.
## Steps
1. [x] nixos-infect the new box (`NIX_CHANNEL=nixos-26.05 PROVIDER=hetzner`); capture
`hardware-configuration.nix` + `networking.nix`.
2. [x] cc-ci: module export + options; verify `#cc-ci` still evaluates; PR.
3. [x] cc-ci-orchestrator: input + host + modules + archive/ + README + terraform refresh; verify
`#cc-ci` evaluates; PR.
4. [x] Stage secrets + clones on the new host; `nixos-rebuild test` → verify → `switch`.
Immediately after: scale the new `ccci-bridge_app` to 0 and mask the two cc-ci timers so the
new host does not double-process `!testme` or run a second weekly upgrade before cutover.
5. [x] Copy data (rsync over tailscale): reports, runs, ci-warm, acme, acme-dns, ci-certs,
/root/.abra, /etc/cc-ci; Drone volume with Drone scaled to 0 during the copy.
6. [x] Pre-cutover verification on the new IP (`curl --resolve`, port 53, dashboard, reports,
drone, one direct `cc-ci-run` on custom-html-tiny).
7. [x] Operator: Gandi A records `ci`, `*.ci`, `ns-acme` → 195.201.88.249. Then: old bridge +
drone + timers off, new bridge up, one real `!testme` end-to-end, a `!testme`-driven report page.
8. [x] Move the orchestrator: stop cc-ci units here, final rsync of `/srv/cc-ci-orch` + agent
state, enable on the new host, operator reconnects there; notplants-nix PR removing cc-ci.
9. [ ] Old cc-ci server: cold standby ~1 week, then operator deletes it and the stale tailnet node.
10. [ ] Domain move to `autonomic.zone` — separate plan, after 1–9 are proven.
## Log
- 2026-09-07 19:40 UTC — recon done, plan written, ssh to the new box verified as root with
`notplants-orchestrator-ed25519`.
- 2026-09-07 20:05 UTC — nixos-infect started on 195.201.88.249 (rev 40f62a6, nixos-26.05,
PROVIDER=hetznercloud). Two false starts: the Debian 13 image has /tmp on tmpfs, so
nixos-infect's temp swapfile fails `swapon: Invalid argument`; fixed with `NO_SWAP=true`.
Build ran, box rebooted ~20:11 UTC and has not answered ping/ssh since (>25 min) — needs the
Hetzner console (no API token for that project on this host).
- 2026-09-07 20:40 UTC — cc-ci branch `feat/nixos-module-export` (9b99f81) pushed: the standalone
`#cc-ci` drv is byte-identical before/after. Orchestrator branch `feat/combined-cc-ci-host`:
`#cc-ci` evaluates (gcnwq4fy…-nixos-system-cc-ci-26.05.20260803.531670d.drv) with PROVISIONAL
hardware/networking copied from the old CI server — to be replaced by the infect output.
- 2026-09-07 20:30 UTC — rescue-mode diagnosis + fixes (README §2a); `#cc-ci` test → switch →
reboot OK on the new box; data restored incl. Drone volume; PRs cc-ci #32 + cc-ci-orchestrator
#19 merged. Quarantine on (bridge 0, timers runtime-masked, orchestrator units stopped).
Waiting on operator: new tailscale auth key; Gandi DNS cutover.
- 2026-09-07 21:10 UTC — operator: NO tailscale on the new host; opencode UI behind its basic
auth on 443 (traefik labels on the `opencode-ui` socat relay → nginx on docker_gwbridge:8090);
fail2ban (sshd + nginx-http-auth in DOCKER-USER). Operator repointed Gandi (ci, *.ci, ns-acme)
→ 195.201.88.249 ~20:40; propagated at once at public resolvers. CUTOVER DONE: old bridge +
drone scaled to 0, old-host timers masked, new bridge up; `!testme` on custom-html #7 = Drone
build 1326 on the new box. Two self-inflicted incidents, both documented in README: traefik
FILE_PROVIDER_DIRECTORY_ENABLED took the front doors down 2 min; the Hetzner resolvers in
networking.nix served the stale address (3 h TTL) → runner/bridge 404s until dropped.
`nixos-rebuild switch` = generation 4. The `switch` re-enabled cc-ci-orchestrator on the new
box: a fresh Claude orchestrator session runs there (tmux `cc-ci-orchestrator`, remote-control
label `cc-ci-orchestrator`) since 20:46 UTC; the old host's cc-ci units are runtime-masked and
the notplants-nix branch `chore/drop-cc-ci` (pushed, evaluates) removes them for good —
operator merges (that repo auto-deploys nightly).
- Remaining: (9) delete old CI server 134485294 + its tailnet node after ~1 week; revoke the
Hetzner token; (10) autonomic.zone domains. Also re-key cc-ci-secrets to the new host's ssh host
key (optional; master key works) and re-run the cc-ci self-test build (1324/1325 failed during
the resolver mess).
- 2026-09-07 21:20 UTC — notplants-nix `chore/drop-cc-ci` merged (9c785c1) and applied on the old
host (test → switch, generation 57, healthy, cc-ci units gone). cc-ci push self-test green again
after #33 (ruff format, pre-existing since 2026-08-31) + #34 (statix: acme-dns.nix systemd
attrset): builds 1330/1331 success. New host on generation 6 with cc-ci main 0437210.
@@ -0,0 +1,92 @@
# Plan — mirror + enroll ALL recipes (then resume per-recipe debugging)
**Status:** ACTIVE — loops implementing (phase `mirror`). Live-host deploy is autonomous (gate removed 2026-06-02).
**Owner:** Builder + Adversary loops.
**Created:** 2026-06-02. **Author:** Claude Sonnet 4.6 orchestrator session.
## Goal & rationale
Get **every** recipe mirrored in `recipe-maintainers/<recipe>` AND enrolled in the `!testme` bridge,
so all of them are CI-triggerable, **before** resuming debugging of individual recipes (matrix-synapse
re-run failure, ghost backup PR, etc.). Operator directive: "make sure all recipes are mirrored and
enrolled before we continue debugging particular recipes."
Target end-state: **19 recipes** — the 18 with `tests/` coverage today, **plus hedgedoc** (operator
chose "add a test suite" for it) — each mirrored, enrolled in `POLL_REPOS`, and test-covered.
## Current state (surveyed 2026-06-02)
Canonical set = recipes with a `tests/<recipe>/` dir = **18**:
`bluesky-pds, cryptpad, custom-html, custom-html-tiny, discourse, ghost, immich, keycloak,
lasuite-docs, lasuite-drive, lasuite-meet, mailu, matrix-synapse, mattermost-lts, mumble, n8n,
plausible, uptime-kuma`. (+ hedgedoc, enrolled but no tests — see Phase 2.)
| Dimension | State |
|---|---|
| **Enrolled** in bridge `POLL_REPOS` (9) | custom-html, custom-html-tiny, keycloak, cryptpad, matrix-synapse, lasuite-docs, lasuite-meet, n8n, uptime-kuma (+ hedgedoc, + cc-ci) |
| **NOT enrolled** (9) | bluesky-pds, discourse, ghost, immich, lasuite-drive, mailu, mattermost-lts, mumble, plausible |
| **Mirror missing** (3) | lasuite-drive, mailu, mumble (all real recipes — verified) |
| **Enrolled but untested** | hedgedoc (mirror+enrollment exist, no `tests/hedgedoc/`) |
Where things live:
- Bridge enrollment: `recipe-maintainers/cc-ci` → `nix/modules/bridge.nix`, the `POLL_REPOS=` CSV (~line 43).
- Tests: `recipe-maintainers/cc-ci` → `tests/<recipe>/` (template: `recipe_meta.py`, `functional/test_*.py`, `PARITY.md`).
- Mirror create + main-sync logic: `recipe-upgrade/open-recipe-pr.sh` (create at lines 53-70, force-sync at 75-77).
- Live deploy target: `nixos-rebuild switch --flake .#cc-ci` on the cc-ci host (now safe — `be4f451` mapped `#cc-ci` → the Hetzner host config).
## Phases
### Phase 0 — pre-flight (no writes)
- Confirm each of `lasuite-drive, mailu, mumble` resolves via `abra recipe fetch <recipe>` on the cc-ci
host (upstream exists). All three have `tests/` so they were exercised in phase 2; expected to pass.
- Snapshot current `POLL_REPOS` and the live bridge unit state for rollback reference.
### Phase 1 — create the 3 missing mirrors
For each of `lasuite-drive, mailu, mumble`: create `recipe-maintainers/<recipe>` (Gitea API) and
force-sync its `main` to true upstream `main`. Reuse the create+sync path in `open-recipe-pr.sh`
(run on the cc-ci host with bot creds), or `--reconcile-only` after the repo exists. **No PRs opened.**
### Phase 2 — author the hedgedoc test suite
hedgedoc is enrolled+mirrored but has no `tests/hedgedoc/`. Author one mirroring a simple recipe
(template = `tests/uptime-kuma/`): `recipe_meta.py`, `functional/test_*.py` (health-check + a
content/branding probe at minimum), `PARITY.md`. Open a cc-ci PR for the new suite; verify it green
via `!testme` before relying on it. (This is the larger sub-task; can be delegated to a Builder session.)
### Phase 3 — enroll the 9 unenrolled recipes
Edit `nix/modules/bridge.nix` `POLL_REPOS` to add: `bluesky-pds, discourse, ghost, immich,
lasuite-drive, mailu, mattermost-lts, mumble, plausible`. Confirm each has a `tests/<recipe>/` (all 9
do). Commit to the cc-ci product repo. Final `POLL_REPOS` = cc-ci + all 19 recipes.
### Phase 4 — deploy to the live cc-ci host
`cd /root/cc-ci && nixos-rebuild switch --flake .#cc-ci` on the cc-ci host to restart the bridge with
the new poll set. **The loops deploy this themselves** — it's their normal operation, and `#cc-ci` →
the correct Hetzner host config since `be4f451`, so the prior wrong-target footgun (the emergency-mode
incident) is gone. Procedure: sync `/root/cc-ci` to the committed head first, rebuild, then verify the
rebuild succeeded (`ssh cc-ci` reachable, bridge active, poll set = all 19 recipes). **Roll back**
(`nixos-rebuild switch --rollback`) and record a finding if anything regresses. Note: `/root/cc-ci` is
operator-synced — if for some reason the host repo can't be synced to head, claim + flag it rather than
deploy a stale tree.
### Phase 5 — verify `!testme` triggerability
For 2-3 newly-enrolled recipes, post `!testme` on an open PR (or a scratch PR) and confirm a Drone
build starts and reports back. Spot-check the bridge poll log shows all 19 repos.
### Phase 6 — resume per-recipe debugging (was blocked on the above)
Only after Phases 1-5: pick up the deferred per-recipe work — matrix-synapse upgrade re-run failure,
ghost backup PRs (#1 reopened, #2 upgrade), discourse bitnamilegacy re-pin, immich/mattermost/plausible
backup fixes, etc. (See `DEFERRED.md` + the build-audit summary.)
## Risks & rollback
- **Live-host rebuild (Phase 4):** the highest-impact step, but the wrong-target footgun is fixed
(`#cc-ci` → Hetzner config, `be4f451`) and deploying cc-ci is the loops' normal operation, so it runs
autonomously. Safety net: verify after rebuild and `nixos-rebuild switch --rollback` on any regression.
- **Bridge poll widening:** more repos polled = more API calls; negligible at 19 repos. A bad recipe
enrollment can't break others (per-recipe runs are isolated).
- **hedgedoc tests (Phase 2):** authoring risk only; gated by its own `!testme`-green PR before trust.
## Open items / decisions
- hedgedoc: **author tests** (operator-chosen). Scope it as its own PR.
- `bluesky-pds #1` open PR looks like a `recipe-create-pr` smoke-test artifact — close separately
(flagged to @notplants).
- Host self-service rebuild path for cc-ci is still a gap (Phase 4 depends on an operator-synced
`/root/cc-ci`); worth a durable fix later.
@@ -0,0 +1,32 @@
# Plan — overnight run (consolidate → /upgrade-all → morning report)
**Created:** 2026-06-02 ~02:10 UTC. **Runs via:** `cc-ci-plan/overnight-run.sh` in tmux `cc-ci-overnight`.
## Goal
By morning, have a full picture of CI + all recipes: let things settle overnight, then run the weekly
**`/upgrade-all`** as a full test run and leave a report — so we can see whether it makes it through,
how many recipe PRs it produced, and the overall state.
## Sequence (the runner enforces it; polls in pure bash so it doesn't burn the shared claude budget)
1. **Gate A — Assistant done.** Wait for the PR-consolidation task to finish (marker
`/srv/cc-ci/.cc-ci-logs/pr-consolidation.done`, which the assistant writes as its last step). So
`/upgrade-all` starts from a clean one-open-PR-per-recipe state. (4h timeout → proceed anyway.)
2. **Gate B — usage reset.** Don't launch `/upgrade-all` until after the claude usage-limit reset
(~03:30 UTC) so it has budget. (The loops + assistant are at ~90% now and may stall until reset;
the watchdog resumes the loops on lift.)
3. **Gate C — Swarm free.** Wait (≤1h) for the Builder/Adversary to be idle so `/upgrade-all` doesn't
contend with the regression canaries on the shared Swarm; proceed anyway after the cap.
4. **Run `/upgrade-all`** (`launch-upgrader.py fresh` → DEFAULT mode: surveys every enrolled recipe,
opens/updates a recipe PR per upgradeable one verified by `!testme`, **NEVER merges**). Wait for it
to finish (it self-terminates + writes `…/upgrades/upgrade-all-<date>.md`; ≤8h).
5. **Morning report** → `/srv/cc-ci/.cc-ci-logs/overnight-report-<date>.md`: the `/upgrade-all`
summary, open-PR-per-recipe survey, and `launch.py status`. Then ping the orchestrator to send the
operator a proactive PushNotification + journal it.
## Guardrails / notes
- `/upgrade-all` DEFAULT **never merges** anything and never weakens tests.
- Shared claude budget: a full `/upgrade-all` is heavy; if it re-exhausts the limit it may stall
mid-run — the report will show how far it got (a partial result is still a result, per the ask).
- Neither the upgrader nor the assistant is watchdog-managed; if either limit-stalls, it stays stalled
until nudged. The runner has bounded timeouts so it never blocks forever.
- This is a one-off overnight run (not the recurring Sunday-02:00 timer, which stays as-is).
@@ -0,0 +1,108 @@
# Phase `bsky` — fix the bluesky-pds recipe (and then its screenshot)
**Mission (operator-specified):** bluesky-pds is the one enrolled recipe that cannot
deploy at all. Diagnose and FIX whatever is wrong with the recipe, prove the fix green in
real CI on a recipe-mirror PR, and then make its CI screenshot work like every other
recipe's. The recipe-mirror PR is the deliverable — the operator merges it (you NEVER do).
State files (phase-namespaced): `STATUS-bsky.md`, `BACKLOG-bsky.md`, `REVIEW-bsky.md`,
`JOURNAL-bsky.md`. DECISIONS.md shared (append).
---
## 1. What is already known (rcust/shot phase evidence, 2026-06-11)
- **Symptom:** the app container crash-loops `Error: Cannot find module '/app/index.js'`
(MODULE_NOT_FOUND) under **Node v24.15.0**, at the recipe's pinned tag, on EVERY
current run. Proven harness-neutral and ref-neutral during rcust M2: identical failure
on old pre-rcust harness and new main, at mirror head and old default head
(runs m2r-bluesky-pds, m2rr-bluesky-pds, ab-bluesky-pds-oldmain).
- **Conclusion already on record (machine-docs/DEFERRED.md):** upstream re-published or
moved the image under the recipe's pinned tag — the historical baseline ("full
lifecycle green", Phase-2 e45e0ee) is unreproducible for reasons outside the cc-ci
repo. Node v24 in the traceback is itself a smell: the PDS image historically shipped
an older Node — the tag now likely resolves to something rebuilt/different.
- **Screenshot:** classified deploy-gated N/A in the shot phase — never capturable
because the app never comes up. Once deploy works, the default landing-page capture
(a PDS serves a minimal HTTP landing page) is expected to work; verify, and add a
`SCREENSHOT(page, ctx)` hook only if genuinely needed.
- DEFERRED.md carries the explicit follow-up: "file/propose a re-pin PR against the
bluesky-pds recipe mirror" — this phase executes it (and closes both bluesky entries).
## 2. Diagnosis & fix requirements
1. **Root-cause first, properly.** Inspect the recipe's compose: which image+tag is
pinned, any `entrypoint`/`command` overrides (a stale `command: node /app/index.js`
against a restructured upstream image is a prime suspect alongside a moved tag).
Inspect the actual image on the CI host (`docker run --rm --entrypoint sh <image> -c
'ls /app; node --version'` or crane/skopeo inspect) to see what the tag REALLY
contains now vs what the recipe assumes.
2. **Research upstream before pinning.** Check bluesky-social/pds releases/changelog for
the current recommended version, breaking changes, and required env/config migrations.
Persist findings to `cc-ci-plan/upstream/bluesky-pds.md` (the per-recipe upstream
registry convention — create it if absent). Prefer upgrading to a current stable,
digest-pinned or exact-version tag over re-pinning to an old image, unless the
research says otherwise — justify the choice in DECISIONS.md.
3. **Fix in the RECIPE (mirror PR), not the harness.** The recipe change (image
re-pin/upgrade + any required compose/env/entrypoint/config migrations + recipe
version label bump per recipe conventions) goes on a branch in the bluesky-pds
recipe mirror → open a PR (like immich PR#2 / plausible PR#3). NEVER push the
mirror's main, NEVER merge. Harness/tests changes belong in the cc-ci repo only if
something there is genuinely stale (and never weakened).
4. **Verify on the PR via real CI:** `!testme` on the mirror PR (the drone path) until
the full lifecycle is green — install/health, upgrade (if a previous published
version exists for the path: justify status either way), backup/restore, functional,
lint (the new L5). Record the achieved level under the new de-capped semantics and
reconcile the recipe's expected baseline.
5. **Then the screenshot:** on the green PR runs, verify `screenshot.png` exists and is
a real, representative, credential-free view (Read the PNG). If the default capture
is inadequate for PDS (bare JSON/empty page), add a `SCREENSHOT` hook in
`tests/bluesky-pds/recipe_meta.py` (cc-ci repo) honoring the secret-safety rule.
Card + dashboard must show it.
6. **Close the loop on records:** check the two bluesky entries in DEFERRED.md (re-pin
follow-up; M2 exclusion note) with pointers to the PR + green runs; update the shot
phase's N/A disposition for bluesky in a JOURNAL-bsky note. If upgrade-path or
canonical/warm enrollment state for bluesky-pds needs reseeding after the fix,
document what the operator should expect post-merge.
## 3. Gates
**M1 — Root cause + green fix PR.** Root cause documented with evidence (image
inspection output, upstream changelog refs); recipe-mirror PR open with the fix;
`!testme` on the PR green through the full lifecycle; screenshot captured on a PR run
and visually verified by the Builder. Adversary verifies: root-cause evidence
reproduces, the PR diff is minimal + justified line-by-line against upstream docs, no
test/gate weakening anywhere, the green run is genuinely the PR head via the drone path.
**M2 — Operator handoff complete.** Fresh Adversary cold pass: independent re-run (or
re-trigger) confirming green at PR head; PNG independently Read (real, credential-free);
level under new semantics recorded and baseline reconciled; DEFERRED entries closed with
pointers; STATUS-bsky.md contains a crisp operator summary (what was wrong, what the PR
changes, what to do post-merge). `## DONE` only after fresh M2 PASS. The phase is DONE
with the PR OPEN — merging is the operator's, and post-merge canonical reseeding is
documented, not performed.
## 4. Guardrails (binding)
- **Recipe mirrors: PR only.** NEVER push main, NEVER merge (operator decides; immich
PR#2 and plausible PR#3 are the standing precedent and also remain unmerged).
- **No gate weakening:** recipe tests in cc-ci may not be loosened to make bluesky
green; if a test is genuinely stale vs the new upstream version, the change must be
evidence-backed, minimal, and Adversary-verified against upstream docs.
- Shared checkout race: NEVER git-checkout `~/.abra/recipes/bluesky-pds` on cc-ci while
its CI build runs; `abra app new` moves the checkout to a release tag — check out the
PR branch afterward when chaos-deploying, or you deploy the wrong tree.
- Real-CI etiquette: ≤2-3 concurrent live deploys; tear down every dev deploy on every
exit path; no secrets in logs/commits/PR text.
- Screenshot rules from the shot phase remain law: capture is best-effort and can never
affect a verdict; never capture a page showing generated credentials.
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every
commit immediately. CI host has no python3 on default PATH — use shell or `cc-ci-run`.
## 5. Definition of Done
bluesky-pds root cause proven; a minimal, upstream-justified fix PR open on the recipe
mirror and verified fully green (all rungs incl. lint) at its head via real drone CI;
its screenshot real and visually verified on those runs (hook added only if needed);
DEFERRED entries closed; operator handoff written; M1 + M2 fresh Adversary PASSes —
with the PR left unmerged for the operator.
@@ -0,0 +1,173 @@
# Phase `canon` — make the canonical sweep actually work (the real "nightly sweep") + verify it
**Mission (operator-specified 2026-06-17):** the "nightly sweep" was specified in theory but **was never
actually doing anything** — confirmed live: `nightly-sweep.timer` is deployed and fires green
(`nightly_sweep.py`, last run 2026-06-17 03:09 UTC exit 0), but **only `custom-html` is `WARM_CANONICAL`
-enrolled and ZERO `canonical.json` records exist** — i.e. the machinery has **never actually promoted a
canonical end-to-end**. This phase makes it **real and proven**, as the **substitute for** that hollow
nightly sweep, with the operator's refinements (2026-06-17):
1. **Sync each recipe mirror's `main`** on `git.autonomic.zone/recipe-maintainers/<recipe>` to its
**upstream** (`git.coopcloud.tech/coop-cloud/<recipe>`) first, so the sweep sees true upstream
tags/latest.
2. **Trigger on a new RELEASED VERSION, not a new commit.** Test a recipe only when its latest **release
tag** on the synced `main` is **newer** than its current canonical version — **skip when there is no
new version**, even if `main` has new *untagged* commits. The sweep tests releases, not arbitrary commits.
3. **Promote the canonical only to a TAGGED release.** A canonical advances only to a version that has a
real release tag (a published release) — never to an arbitrary untagged commit.
…then **run CI cold-on-`main` for each recipe and actually promote the canonical for any that pass** —
and **prove the whole thing works**. **The deliverable is correctness, verified end-to-end** — and the
operator specifically wants confidence it **plays nicely with the `samever` upgrade-base work** (§2
"Plays-nice-with-samever"). Operator decisions (2026-06-17): **all recipes enrolled** (§2.B), and the
**cadence is weekly** (change the existing daily timer to weekly — a one-line `OnCalendar` tune; exact
day/time is not critical). This REPLACES the hollow nightly sweep; it is not a parallel job.
State files: `STATUS-canon.md`, `BACKLOG-canon.md`, `REVIEW-canon.md`, `JOURNAL-canon.md`. DECISIONS.md shared.
## 1. Verified starting state (2026-06-17)
- `nightly-sweep.timer` enabled + active (next ~03:00 UTC); `nightly_sweep.py` runs and exits 0. The
timer/service plumbing already works — **reuse it, don't rebuild it.**
- **Only `custom-html` sets `WARM_CANONICAL = True`.** The sweep iterates `canonical.enrolled_recipes()`
→ essentially one recipe → near-no-op across the fleet.
- **No `canonical.json` exists** on the host → the promote path (`should_promote_canonical` →
`promote_canonical` → `write_registry`) has **never successfully produced a canonical**, even for
custom-html. This is the crux of "theory, not actually doing it."
- The sweep does **not** reconcile mirrors to upstream, and does **not** skip-when-unchanged.
## 2. The work
**A. Prove + fix the promote path FIRST (the core).** On `custom-html` (already enrolled), make a green
cold-on-latest run **actually write `canonical.json`** (recipe/version/commit/status) AND prove a
subsequent `--quick` warm-reattach uses it (`deploy_canonical` reattaches the retained volume). If it
doesn't happen today, find and fix why (this is the real defect behind the hollow sweep). A canonical
must demonstrably exist and be reusable before anything else is meaningful.
- **Promote-gate addition (operator 2026-06-17): only promote to a TAGGED release.** Extend
`should_promote_canonical` so a promote ALSO requires the tested version to correspond to a published
**release tag** (`warm_reconcile.recipe_tags`): green + cold + latest + enrolled **+ tagged**. The
canonical must always be a real release — never an arbitrary untagged `main` commit. An untagged state
must never be written as a canonical.
**B. Enroll ALL recipes (operator decision 2026-06-17).** Set `WARM_CANONICAL = True` for **every** recipe
cc-ci tracks (the `used-recipes.md` set) — the sweep promotes a canonical for each that passes, not just
custom-html.
- **Watch the warm-volume disk budget:** ~21 recipes each retaining a data volume on the single node is
real disk. Verify headroom, lean on the existing WC8 disk-hygiene / `ci-docker-prune`, and if disk
becomes the binding limit, **raise it** rather than silently dropping recipes (a fallback if needed:
decouple the cheap last-green *version record* — kept for all — from the expensive retained *volume*).
Default remains all-enrolled.
- If a specific recipe genuinely cannot be enrolled (e.g. unbounded data, no stable health), record the
exception + reason in DECISIONS — don't silently skip it.
**C. Add the upstream mirror-sync step.** Before the per-recipe CI, reconcile each mirror's `main` + tags
to coopcloud upstream — reuse `recipe-upgrade`'s `open-recipe-pr.sh <recipe> --reconcile-only` (handles
go-git private-mirror auth, fetches coopcloud via an `upstream` remote, closes already-merged-upstream
PRs, leaves unrelated PRs). This is a **faithful mirror sync, not a push of our own changes.**
**D. Trigger on a new RELEASED VERSION (skip when no new version).** After sync, compute the recipe's
latest **release tag** version reachable on `main` and compare it to the canonical record's version:
- latest release tag **== canonical version** → **skip** (`SKIP no-new-version`) — *even if `main` has
new untagged commits*. The sweep tests releases, not arbitrary commits.
- latest release tag **newer than** canonical → run CI **cold on that tagged version** → promote on green
(tagged, per §2.A).
- no release tag at all (recipe never released) → skip with a recorded reason.
This is the operator's trigger refinement (version/tag-keyed, **not** commit-keyed) and the determinism
property (M2 run-twice → everything skips).
**E. Keep it deterministic + AI-free at runtime** (it already is — a script + timer). The additions must
stay pure code: no AI calls during the run. AI (the loops) only authors + verifies.
**F. Make the timer weekly** (operator preference): change the existing daily `OnCalendar` to weekly. The
exact day/time is not critical — pick a low-traffic slot; it's a one-line tune. `Persistent = true` to
catch up a missed run. This is the only schedule work; do not over-invest in it.
**G. Retire `UPGRADE_BASE_VERSION` if plausible no longer needs it (operator 2026-06-17).** Today it is
still used: **`plausible`** sets `UPGRADE_BASE_VERSION = "3.0.1+v2.0.0"` (the old static `[-2]` default
picked `3.0.0`, whose clickhouse entrypoint 404s on amd64 → base never converges; the pin forces the
newest published `3.0.1`); **`bluesky-pds`** only *references* it (in an `EXPECTED_NA` upgrade-skip note as
a future re-enable path). Once this phase enrolls plausible and promotes its canonical to its latest green
release (`3.0.1`), the **dynamic base resolves to `3.0.1` on its own** — the correct base, avoiding the
broken `3.0.0` — so the explicit pin becomes redundant. Therefore:
- With plausible's canonical established at `3.0.1`, **remove the pin from `tests/plausible/recipe_meta.py`
and confirm its upgrade tier still resolves the correct base (`3.0.1`) and passes** under the dynamic
resolver.
- If that holds, **strip `UPGRADE_BASE_VERSION` entirely**: the meta key (`runner/harness/meta.py` KEYS),
the override branch in `resolve_upgrade_base` (`run_recipe_ci.py`), the docs (`recipe-customization.md`
§4/§5, `testing.md`), and the unit tests (`test_meta.py`, `test_upgrade_base.py`); and update
`bluesky-pds`'s comment so its re-enable path is the dynamic base, not the removed key.
- **GATE (do not force it):** if plausible genuinely still can't get the right base dynamically (e.g.
`3.0.1` itself won't cold-deploy green, so no canonical), **KEEP `UPGRADE_BASE_VERSION`** as the
escape-hatch and record why in DECISIONS — never drop a recipe's upgrade coverage to delete a key.
**Plays-nice-with-`samever` (operator wants this CONFIRMED).** The release-tag trigger (D) makes the
sweep and `samever` **orthogonal** — confirm they don't interfere:
- In the **sweep**, a recipe runs **only when a new release tag exists**, so the version under test is
always *newer* than the canonical → the upgrade tier's base (previous canonical/released version) is
strictly older → **`samever`'s same-version step-back never fires in the sweep** (the tag trigger
already prevents a `vX→vX` run; no-new-version recipes are skipped outright).
- `samever` remains the guard for the **PR path** (`!testme`), where a PR can carry the same version
label as the canonical without cutting a release — that's where the step-back matters, and it's
owned/proven by the `samever` phase, not here.
So in the sweep, verify only: (a) no new release tag → recipe SKIPPED (no upgrade-tier run, no promote);
(b) new release tag → `canonical(older) → new tagged version`, a real delta, promote (tagged). The sweep
must never promote an untagged version and never run a same-version upgrade.
## 3. Gates
**M1 — machinery works locally, each piece proven.** (A) a real `canonical.json` is produced by a green
cold run on ≥1 recipe and reused by a warm reattach — **demonstrated, not assumed** — and the promote gate
now also requires a **release tag** (untagged → no promote). (C) mirror-sync and (D) the **new-release-tag
trigger** implemented, reusing the existing reconcile + sweep code, with unit tests (trigger = latest
release tag vs canonical version, NOT commit; sync invoked per recipe; promote gated on
green+cold+latest+enrolled+**tagged**). (B) all recipes enrolled. Adversary cold-verifies: a canonical
actually exists + reattaches; an **untagged** state never promotes; the trigger skips no-new-tag recipes
and runs new-tag ones; sync is faithful-mirror-only; a RED recipe does NOT promote; no AI at runtime.
**M2 — proven end-to-end in real CI (the heart of this phase).** A full sweep run across the enrolled set
on cc-ci: mirrors synced to upstream, **canonicals actually promoted for the green recipes** (records
exist with correct version+commit), red recipes left intact, unchanged recipes skipped — with a
per-recipe results log. **Determinism proof: run the sweep a SECOND time immediately → it SKIPS every
recipe** (latest release tag == canonical version for all → skip all) = a clean no-op, no CI rerun.
Confirm the **deployed timer fires the real (non-hollow) job** — after a fire, canonicals have advanced
(evidence), not exit-0 on an empty set. **Tagged-promote proven:** show a green run on an untagged state
does NOT promote, and a green run on a tagged release DOES.
**`samever` orthogonality proven (operator-required).** Demonstrate, with evidence, the two sweep paths:
(1) **no new release tag** (latest tag == canonical version, even with new untagged commits on `main`) →
recipe SKIPPED — no upgrade-tier run, no promote; (2) **new release tag** → cold-test the new tagged
version, upgrade `canonical(older) → new`, a real delta, promote (because tagged). Confirm `samever`'s
step-back **never fires inside the sweep** (the tag trigger prevents same-version runs) — its same-version
behavior is owned/proven by the `samever` phase on the PR path. Construct scenarios if the live recipe set
doesn't cover both.
No AI in the loop. Fresh Adversary PASS on both milestones → `## DONE`.
## 4. Guardrails
- **Correctness over cadence.** The bar is the machinery *demonstrably promotes canonicals, syncs mirrors,
skips unchanged, and plays nicely with `samever`.* The cadence is decided (**weekly**) — set it in one
`OnCalendar` line and move on; don't agonize over the exact slot.
- **No AI at runtime** — pure script + systemd timer; AI only builds/verifies.
- **Single-node safety:** serial; skip the whole run if a Drone/test build is in flight (reuse the
existing nightly guard); tear down every deploy; bound total runtime; mind the warm-volume disk budget.
- **Never force-promote / never weaken:** promote only on green-cold-latest-enrolled; a red recipe keeps
its prior known-good. Never weaken a test to make a recipe promote.
- **Faithful mirror sync only:** force-sync `main`/tags to coopcloud upstream; never push our own changes
to mirror `main`; never merge/disturb unrelated PRs.
- **Nix/host changes** (enrollment is recipe-meta; any timer/module tweak is a nixos-rebuild): loops may
deploy if clean and **verify host health after**; else file for the orchestrator. Commit author
`autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every commit; abra over a pseudo-TTY.
## 5. Definition of Done
The canonical sweep **actually works and is proven**: a green cold run on a **tagged release** produces a
real, reusable `canonical.json` (an untagged state never promotes); the sweep reconciles each recipe
mirror's `main` to upstream, **skips recipes with no new release tag** (even if `main` has new untagged
commits), runs CI cold on the new tagged version for the rest, and promotes the canonical only to that
tagged release — across all enrolled recipes, demonstrated end-to-end in CI, including the run-twice no-op
determinism proof, the tagged-promote proof, and a real (non-hollow) timer fire. `samever` confirmed
orthogonal (never fires in the sweep). All recipes enrolled + warm-volume budget recorded. `UPGRADE_BASE_VERSION`
retired (key + resolver branch + docs + tests removed, plausible migrated to the dynamic base) **if**
plausible works without it — else kept with a recorded reason (§2.G). The runtime job is AI-free; it is the
substitute for the hollow nightly sweep (not a parallel job). M1 + M2 fresh Adversary PASSes in REVIEW-canon.md.
@@ -0,0 +1,81 @@
# Phase `cf48` — Opus 4.8 post-cfold coverage-loss review
**Mission:** run a SECOND, independent post-cfold coverage-loss review — identical in scope
to phase `cf55`, but performed by **Claude Opus 4.8** instead of GPT-5.5 — so the cfold
custom-folder collapse is cross-validated by two different models. Confirm no custom test,
assertion, fixture, screenshot hook, lifecycle overlay, or result-level behavior was lost.
Review-only: do not implement new feature work unless the review finds a concrete regression
that must be fixed before continuing.
State files live under `machine-docs/`: `STATUS-cf48.md`, `BACKLOG-cf48.md`,
`REVIEW-cf48.md`, `JOURNAL-cf48.md`.
## Model Requirement
This phase must run on **Claude Opus 4.8** (`claude-opus-4-8`), on the **`claude`** backend
(NOT opencode). The orchestrator sets per-phase model override files:
- `/srv/cc-ci/.cc-ci-logs/.loop-model-cf48 = claude-opus-4-8`
- `/srv/cc-ci/.cc-ci-logs/.loop-model-adv-cf48 = claude-opus-4-8`
and must ensure `.loop-backend = claude` is in effect when this phase starts (per-phase
backend is not overridable in launch.py; if the loops were on opencode for cf55, the
orchestrator restarts them on the claude backend before cf48). Builder and Adversary should
record the model their session reports in their first `STATUS-cf48.md` / `REVIEW-cf48.md`
entries; if it is not Opus 4.8, stop and ask the orchestrator to fix the launcher state.
## Inputs
- `plan-phase-cfold-custom-folder.md`
- `machine-docs/STATUS-cfold.md`, `machine-docs/REVIEW-cfold.md`
- the final cfold implementation commits on cc-ci main
- the pre-cfold baseline matrix recorded by cfold (custom tests across all enrolled recipes)
- any cfold full-sweep evidence and artifacts
- **`machine-docs/STATUS-cf55.md` / `REVIEW-cf55.md`** — the GPT-5.5 review. Read it, but
review INDEPENDENTLY first and form your own verdict; THEN reconcile: note any place the
two models disagree (a finding one caught and the other missed is itself worth surfacing).
## Required Review
Same seven categories as `cf55` — review them independently, do not just confirm cf55:
1. **Diff review** — exact cfold commit range, line-by-line for coverage loss (discovery,
manifest/reporting, docs, unit tests, imports, fixtures, lifecycle overlays, screenshot
hooks, result rendering).
2. **Discovery parity** — recompute the discovered custom-test inventory after cfold vs the
pre-cfold baseline: same recipes, same custom-test count, same assertions, same helper
coverage, only folder paths changed `functional/`|`playwright/` → `custom/`.
3. **Assertion preservation** — no weakened/removed assertions, skipped tests, relaxed waits,
or renamed tests without equivalent coverage. Mechanical import/path updates are allowed.
4. **Old-folder behavior** — deprecated `functional/`/`playwright/` handled exactly as cfold
decided: no silent coverage loss for recipe-local tests; loud warnings / documented compat.
5. **Lifecycle-overlay separation** — top-level lifecycle overlays stay distinct from custom
tests and were not moved into / discovered through `custom/`.
6. **Evidence audit** — verify cfold's claimed full sweep actually ran custom tests with no
silent level drops; classify any skip/level change as expected, cfold-neutral, or blocker.
7. **Cleanliness** — no unintended root coordination files, leaked test stacks, stale temp
scripts, or uncommitted implementation files.
## Gates
**M1 — Opus 4.8 cold review complete.** Builder produces a review matrix in `STATUS-cf48.md`
covering every recipe and every category above, plus a short cf55-vs-cf48 agreement note.
Adversary independently verifies and records PASS/FAIL in `REVIEW-cf48.md`.
**M2 — No-loss verdict.** Adversary either confirms `NO COVERAGE LOST` with concrete
evidence, or records specific blocking findings. If findings exist, Builder fixes only those,
evidence is refreshed, Adversary re-checks. No move to `pvfix` until M2 has a fresh PASS.
## Guardrails
- Review pass, not a redesign. Minimal fixes, directly tied to a found regression.
- Do not weaken or delete tests to make the review pass.
- Do not rerun a full fleet sweep unless the existing cfold evidence is incomplete or the
review finds a specific reason it must be repeated.
- Do not touch proxy/ghost work here; those are queued after this review.
## Definition of Done
`STATUS-cf48.md` contains the Opus 4.8 review matrix + final verdict (incl. cf55 agreement
note), `REVIEW-cf48.md` contains Adversary's independent Opus 4.8 PASS, and the verdict
explicitly states whether cfold preserved the full pre-cfold custom-test set. Builder writes
`## DONE` only after Adversary records M1 and M2 PASSes.
@@ -0,0 +1,82 @@
# Phase `cf55` — GPT-5.5 post-cfold coverage-loss review
**Mission:** after phase `cfold` finishes, run one independent GPT-5.5 review pass over
the custom-folder collapse implementation and confirm that no custom test, assertion,
fixture, screenshot hook, lifecycle overlay, or result-level behavior was lost. This is a
review-only phase: do not implement new feature work unless the review finds a concrete
regression that must be fixed before continuing.
State files live under `machine-docs/`: `STATUS-cf55.md`, `BACKLOG-cf55.md`,
`REVIEW-cf55.md`, `JOURNAL-cf55.md`.
## Model Requirement
This phase must run on **GPT-5.5**. The orchestrator sets per-phase model override files:
- `/srv/cc-ci/.cc-ci-logs/.loop-model-cf55 = openai/gpt-5.5`
- `/srv/cc-ci/.cc-ci-logs/.loop-model-adv-cf55 = openai/gpt-5.5`
Builder and Adversary should explicitly record the model shown by their OpenCode session in
their first `STATUS-cf55.md` / `REVIEW-cf55.md` entries. If the session is not GPT-5.5,
stop and ask the orchestrator to fix the launcher state before reviewing.
## Inputs
- `plan-phase-cfold-custom-folder.md`
- `machine-docs/STATUS-cfold.md`
- `machine-docs/REVIEW-cfold.md`
- the final cfold implementation commits on cc-ci main
- the pre-cfold baseline matrix recorded by cfold (`64` custom tests across `20` recipes)
- any cfold full-sweep evidence and artifacts
## Required Review
1. **Diff review.** Identify the exact cfold implementation commit range and review it
line-by-line for coverage loss. Pay special attention to discovery, manifest/reporting,
docs, unit tests, imports, fixtures, lifecycle overlays, screenshot hooks, and result
rendering.
2. **Discovery parity.** Recompute the discovered custom-test inventory after cfold and
compare it to the pre-cfold baseline. The expected result is the same logical test set:
same recipes, same custom-test count, same assertions, same helper coverage, only folder
paths changed from `functional/` or `playwright/` to `custom/`.
3. **Assertion preservation.** Check that test bodies were not weakened during the move.
Mechanical import/path updates are allowed; removed assertions, skipped tests, relaxed
waits, or renamed tests without equivalent coverage are findings.
4. **Old-folder behavior.** Confirm the intended behavior for deprecated
`functional/`/`playwright/` folders is implemented exactly as cfold decided: no silent
coverage loss for recipe-local tests, and loud warnings or documented compatibility as
appropriate.
5. **Lifecycle-overlay separation.** Confirm top-level lifecycle overlays remain distinct
from custom tests and were not accidentally moved into or discovered through `custom/`.
6. **Evidence audit.** Review cfold M1/M2 evidence. If cfold claims a full recipe sweep,
verify custom tests actually ran and levels did not silently drop. If any recipe was
skipped or changed level, classify it as expected, cfold-neutral, or a blocker.
7. **Cleanliness.** Confirm no unintended root coordination files, leaked test stacks,
stale temporary scripts, or uncommitted implementation files remain.
## Gates
**M1 — GPT-5.5 cold review complete.** Builder produces a review matrix in
`STATUS-cf55.md` covering every recipe and every required review category above.
Adversary independently verifies the matrix and records PASS/FAIL in `REVIEW-cf55.md`.
**M2 — No-loss verdict.** Adversary either confirms `NO COVERAGE LOST` with concrete
evidence, or records specific blocking findings. If findings exist, Builder fixes only
those findings, cfold/cf55 evidence is refreshed, and Adversary re-checks. No move to
`pvfix` until M2 has a fresh PASS.
## Guardrails
- This is a review pass, not a redesign. Keep fixes minimal and directly tied to a found
regression.
- Do not weaken or delete tests to make the review pass.
- Do not rerun a full fleet sweep unless the existing cfold evidence is incomplete or the
review finds a specific reason the sweep must be repeated.
- Do not touch proxy/ghost work in this phase; those are queued after this review.
## Definition of Done
`STATUS-cf55.md` contains the GPT-5.5 review matrix and final verdict,
`REVIEW-cf55.md` contains Adversary's independent GPT-5.5 PASS, and the verdict explicitly
says whether cfold preserved the full pre-cfold custom-test set. Builder writes `## DONE`
only after Adversary records M1 and M2 PASSes.
@@ -0,0 +1,91 @@
# Phase `cfold` — collapse custom-test folders into one `custom/` + full recipe CI sweep
**Mission (operator-specified):** custom recipe tests currently live in TWO folders —
`tests/<recipe>/functional/` and `tests/<recipe>/playwright/` — a split that is purely
organizational (the harness treats both identically). Collapse them into a single
`tests/<recipe>/custom/` folder, then prove the change with a full real-CI recipe sweep
confirming every recipe's `!testme` still works and no custom test was silently dropped.
State files (machine-docs/, per the file-location rule): `machine-docs/STATUS-cfold.md`,
`BACKLOG-cfold.md`, `REVIEW-cfold.md`, `JOURNAL-cfold.md`. DECISIONS.md shared.
## 1. Why this is safe (investigation already done, 2026-06-11)
The split carries ZERO semantic weight — verified:
- `runner/harness/discovery.py:103 custom_tests()` globs `subdirs = ("functional",
"playwright")` with NO branching on which folder.
- `runner/run_recipe_ci.py:579 run_custom()` runs both in the same `custom` tier with the
same pytest command.
- Same fixtures for both (`recipe`/`meta`/`live_app`/`op_state`/`deps`); playwright tests
just `from playwright.sync_api import sync_playwright` directly — no special fixture.
- Both map to the `functional` rung (L4); folder name does NOT affect tier/rung/level.
- Failure semantics identical. So merging loses nothing.
The ONE distinction that DOES matter and MUST be preserved: a **top-level**
`test_<op>.py` is a *lifecycle overlay*, NOT a custom test (top-level non-lifecycle files
are not discovered). `custom/` is still a subdir, so that distinction survives.
## 2. Implementation (P1)
1. **Discovery:** `discovery.custom_tests()` → canonical subdir is `custom/`. To prevent
SILENT coverage loss, do NOT do a blind cutover: either (RECOMMENDED) keep recognizing
`functional/`/`playwright/` as deprecated aliases AND emit a loud one-line warning when
a test is found in a deprecated folder, OR have discovery raise/log loudly if a
non-empty `functional/`/`playwright/` remains after migration. The end-state canonical
home is `custom/`; nothing may be dropped without a loud signal. Decide + record in
DECISIONS.md; the Adversary reviews the choice.
2. **Migrate cc-ci's own tests:** `git mv tests/<recipe>/{functional,playwright}/test_*.py`
→ `tests/<recipe>/custom/` for EVERY recipe. Preserve any per-recipe `conftest.py` /
helper modules those tests import (move/adjust imports as needed — mechanical only).
3. **repo-local (HC2-gated) tests:** recipes' OWN repo `tests/` may still use the old
folder names. Keep discovery recognizing them (deprecated-alias path) OR document the
rename requirement — do NOT silently stop discovering them. State the decision.
4. **Docs:** update the placement rule everywhere — `docs/recipe-customization.md` §3
+ §5.3 + the tree, `docs/testing.md` §4, `docs/enroll-recipe.md` worked examples.
Regenerate anything generated.
5. **Unit test:** `tests/unit/` coverage for `custom_tests()` — finds `custom/`, ignores
top-level lifecycle overlays, (alias behavior if kept), deterministic ordering.
6. **Nothing else may key off the names:** grep the whole repo for `functional/` and
`playwright/` string literals (harness, bridge, dashboard, results, screenshot, drone
pipeline) and fix every consumer. The screenshot `SCREENSHOT` hook + manifest must be
unaffected.
## 3. Gates
**M1 — Migration complete + coverage-preserving (pre-sweep).** All recipes' custom tests
relocated to `custom/`; discovery + docs + unit tests updated; full-repo grep shows no
stale consumer. **Coverage-diff proof (cardinal, mirrors rcust M1):** the SET of
discovered + executed custom tests per recipe is IDENTICAL before and after — same files,
same count, just relocated; NONE dropped, NONE newly skipped. Adversary cold-verifies the
diff from a clean checkout and confirms no consumer still keys off the old folder names
and no test assertion was weakened.
**M2 — Full recipe CI sweep (the operator-required proof).** Run a real-CI sweep across
ALL enrolled recipes via the **drone `!testme` path** confirming every recipe's custom
tier still discovers + runs + passes its tests at the same level as its pre-cfold
baseline. Build the baseline matrix (recipe → expected level + custom-test set) BEFORE
the change. Then sweep: every recipe's `!testme` green, custom tests present in the run
output / manifest, levels unchanged, zero leaked apps. Max 2-3 concurrent live deploys;
canary suite green. Any deviation must be explained as cfold-neutral or fixed. Fresh
Adversary PASS → Builder writes `## DONE`.
## 4. Guardrails (binding)
- **No silent coverage loss** — the whole point of M1's coverage diff. A custom test that
stops being discovered without a loud signal is an automatic FAIL.
- **No test weakening** — this is a pure relocation; assertions are untouchable. The only
content changes allowed are import-path adjustments forced by the move (mechanical,
Adversary-checked line-by-line).
- **File-location rule** still applies to loop-state files (machine-docs/).
- Real-CI etiquette: ≤2-3 concurrent deploys, teardown every dev deploy on every exit
path, never git-checkout `~/.abra/recipes/<recipe>` mid-build, no secrets in logs.
- Recipe mirrors: PR only, never merge. Commit author `autonomic-bot
<autonomic-bot@noreply.git.autonomic.zone>`; push every commit. CI host: no python3 on
default PATH (use `cc-ci-run`).
## 5. Definition of Done
All custom tests live under `tests/<recipe>/custom/` (functional/playwright collapsed),
discovery + docs + unit tests updated, no consumer keys off the old names, coverage proven
identical before/after, and a full `!testme` recipe sweep is green with unchanged levels
and zero leaks. M1 + M2 fresh Adversary PASSes.
@@ -0,0 +1,81 @@
# Phase `dash` — fix incomplete per-recipe run history on the CI dashboard
**Mission (operator-specified 2026-06-17):** the dashboard's per-recipe history page
(`https://ci.commoninternet.net/recipe/<recipe>`, e.g. `/recipe/bluesky-pds`) shows only the latest run
for most recipes. Make it show the **full run history** per recipe.
State files: `STATUS-dash.md`, `BACKLOG-dash.md`, `REVIEW-dash.md`, `JOURNAL-dash.md`. DECISIONS.md shared.
## 1. Root cause (verified 2026-06-17)
`dashboard/dashboard.py` builds the per-recipe history **solely from the Drone API, capped at a single
page of the latest 100 builds**:
```python
builds = _drone(f"/api/repos/{CI_REPO}/builds?per_page=100") # single page, no pagination
def history_for(recipe):
builds = _custom_recipe_builds()
return [_build_row(b) for b in builds if (b.get("params") or {}).get("RECIPE") == recipe]
```
But there are **362 actual runs** on the host (`/var/lib/cc-ci-runs` has 362 run dirs). So ~262 runs are
older than the 100-build window and never fetched. The recent `regall` sweep `!testme`'d each of the 21
recipes once, filling the latest-100 window and pushing each recipe's older runs out of view → most
recipes show exactly one run. (The overview/latest-per-recipe page is unaffected — it only needs the
recent window.)
## 2. Design — source history from the local run artifacts
The dashboard already **bind-mounts `/var/lib/cc-ci-runs` read-only** (see `nix/modules/dashboard.nix`)
and reads each run's `results.json` (`_results_for`). Build the per-recipe history from THAT, not from
the 100-build Drone slice — it's complete (362 runs), durable (independent of Drone pagination/retention),
and already available.
- **`history_for(recipe)` → enumerate `/var/lib/cc-ci-runs/*/results.json`**, keep those whose recipe
matches, sort newest-first (by run id / timestamp), and render the existing history table (status,
level, version, ref, when, link to `/runs/<id>/…`). Apply a sane **display cap** (e.g. the last ~30 per
recipe) so a long-lived recipe's page stays bounded.
- First **confirm the `results.json` schema** carries what's needed (recipe, version, level/status, ref,
timestamp) — adapt if a field is named differently or read the run id from the dir name; skip a run dir
with no/À malformed `results.json` gracefully (don't 500).
- **Keep Drone only where it adds value** — e.g. the live "currently running" status for the most recent
run (a run mid-flight has no final `results.json` yet). The *historical* list comes from local
artifacts. Keep the overview + `/badge/<recipe>.svg` working exactly as today.
- **Retention check:** 362 runs implies adequate retention, but confirm nothing (cleanlogs / docker-prune)
trims `/var/lib/cc-ci-runs` so aggressively that history vanishes; if it does, note it in DECISIONS and
keep a Drone-pagination fallback. Do not add unbounded growth — if retention needs a cap, record it.
## 3. Gates
**M1 — fix implemented + locally verified.** `history_for` (and any helper) sources per-recipe history
from `/var/lib/cc-ci-runs`, newest-first, display-capped; `results.json` schema confirmed; malformed/empty
run dirs handled without erroring. **Python stdlib only** (the dashboard's standing constraint); the
existing path-traversal guard + the `/recipe/` name validation preserved. Unit/local render test shows a
recipe with many runs now lists them all (up to the cap). Adversary cold-verifies: the rendered history
matches the actual run dirs for that recipe (count + order), no security regression (path traversal, arg
injection), overview + badge routes unchanged.
**M2 — deployed + verified live.** Rebuild/redeploy the dashboard service (the `deploy-dashboard`
reconcile; the content-hash image tag rolls on `dashboard.py` change). Then confirm on the live site:
`/recipe/bluesky-pds` and ≥2 other recipes show their **full** run history (multiple runs, matching the
local run count), with correct status/level/links; the overview and badges still render. Fresh Adversary
PASS on both milestones → `## DONE`.
## 4. Guardrails
- **Read-only dashboard** — it never writes run artifacts; the mount stays read-only.
- **Python stdlib only** (no new deps — it's a stdlib HTTP server packaged into an OCI image).
- **Preserve security + the other routes:** keep the path-traversal guard and the `/recipe/` validation;
do not regress the overview, `/badge/<recipe>.svg`, `/runs/<id>/<file>`, or the bridge's `/hook` routing
(traefik priority).
- **Host/deploy change** (redeploying the dashboard service via its reconcile / a nixos-rebuild): loops may
deploy if clean and **verify host health after** (dashboard service N/N, `ci.commoninternet.net` 200);
else file for the orchestrator. Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`;
push every commit.
- Bounded scope — this is a history-page fix, not a dashboard redesign.
## 5. Definition of Done
The per-recipe history page sources its run list from the local `/var/lib/cc-ci-runs` artifacts and shows
the **full** (display-capped) history per recipe — deployed and verified live on `bluesky-pds` + ≥2 other
recipes (multiple runs each, matching the host's run count), with the overview/badges/other routes
unaffected and the dashboard still stdlib-only + read-only. Retention confirmed adequate (or recorded).
M1 + M2 fresh Adversary PASSes in REVIEW-dash.md.
@@ -0,0 +1,85 @@
# Phase `drone` — enroll the drone recipe (with gitea SCM dependency)
**Mission (operator-specified 2026-06-11):** enroll drone — the last §5 recipe — in
cc-ci. Drone is a CI server that requires a git-provider SCM to boot; the viable dep is
gitea. Ship the MAXIMAL SUBSET scoped in Phase 2 (JOURNAL-2 `f86a58a`): drone boots with
gitea SCM — install + upgrade + health + SCM-configured — with the build-creation test
remaining a signed-off sub-deferral.
State files: `STATUS-drone.md`, `BACKLOG-drone.md`, `REVIEW-drone.md`,
`JOURNAL-drone.md`. DECISIONS.md shared.
## 0. P0 — HOST PREREQUISITE (orchestrator-owned; verify before any other work)
gitea binds `/etc/timezone:ro` from the host; NixOS `time.timeZone` creates only
`/etc/localtime`, so the gitea container is REJECTED (`bind source path does not exist`)
— proven on cc-ci. The Nix fix is ALREADY COMMITTED: `3bde76f`
(`environment.etc."timezone" = "UTC\n"` in `nix/hosts/cc-ci/configuration.nix`); it
needs the host-config deploy (sync `/root/cc-ci` + `nixos-rebuild switch
--flake /root/cc-ci#cc-ci`), which the ORCHESTRATOR performs (operator-managed
mechanism; do NOT attempt it from the loops).
**Builder's first action:** check `test -f /etc/timezone` on the cc-ci host. If absent,
write a BLOCKED note at the top of STATUS-drone.md ("P0 host deploy needed —
orchestrator") and work on P1 prep that needs no gitea deploy (meta scaffolding, test
authoring) until it appears; the orchestrator reads STATUS on its hourly wakes and will
deploy. Verify `/etc/timezone` exists (content `UTC`) before claiming anything gitea
touches.
## 1. Scope (from the Phase-2 scoping, JOURNAL-2 `f86a58a`)
1. **gitea as a dependency recipe:** `tests/gitea/recipe_meta.py` enrolling gitea as an
install-time DEPS provider (per the rcust install-time-deps-only system — deps are
installed before the app, fixtures `deps`/`op_state` provide handles).
2. **drone enrollment:** `tests/drone/recipe_meta.py` with `DEPS=["gitea"]`;
install-time steps that create a gitea admin + token + OAuth2 application and wire
`DRONE_GITEA_*` + client secret into drone's install; functional tests proving
health + **SCM-configured** (drone actually talks to gitea, not just an HTTP 200).
3. **Tiers:** install + upgrade (if a previous published version exists — justify
either way) + functional; backup/restore per what the published recipe declares
(structural skip is fine if the recipe has no backup config — document it); lint
(L5) per the now-standard ladder. Screenshot per the shot-phase standard (drone has
a real login/landing UI; default capture expected to work).
4. **Build-creation sub-deferral STAYS deferred:** creating/listing actual CI builds
needs an OAuth user-token + synced repo + .drone.yml + webhook trigger —
disproportionate (the original Phase-2 assessment stands). Ship without it and get
the Adversary's explicit §7.1-style sign-off recorded in REVIEW-drone.md; update
the DEFERRED entry to narrow it to just this gap.
## 2. Gates
**M1 — Integration built + green locally.** P0 verified; gitea dep + drone enrollment
implemented; full chosen tier-set green on the harness path with evidence; unit tests
for any new harness-visible surface; no gate weakening anywhere. Adversary cold-verifies
from a clean checkout: deps wiring per the rcust conventions, SCM-configured test has
teeth (a drone WITHOUT gitea wiring must fail it), declared skips justified against the
published recipe.
**M2 — Proven in real CI.** Full lifecycle green via the drone `!testme`/CI path
(yes — cc-ci's own drone testing a drone recipe deploy; mind resource headroom),
screenshot real + visually verified, level recorded under the de-capped semantics,
canonical/warm enrollment decision documented, DEFERRED entry updated (P0+integration
closed, build-creation gap narrowed + signed off), operator summary in STATUS-drone.md.
Fresh Adversary PASS → `## DONE`.
## 3. Guardrails (binding)
- **Host changes are orchestrator/operator-only** (P0 above; same for anything else
host-level you discover — file it in STATUS, don't improvise).
- The deps system rules from rcust apply: install-time deps only, uniform HookCtx
signatures, no new meta keys without registry + docs regeneration.
- Two live deploys (gitea + drone) per run — count them against the ≤2-3 concurrent
budget; coordinate so a second recipe's run isn't racing the same headroom; tear down
BOTH on every exit path, dep included.
- Recipe mirrors: PR only if a recipe defect is found (never push main, never merge).
No secrets in logs/commits (gitea admin password + OAuth client secret are generated
per-run and must stay out of artifacts; the manifest redaction rules apply).
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every
commit. CI host: no python3 on default PATH.
## 4. Definition of Done
`/etc/timezone` host fix live; gitea enrolled as a dep provider; drone enrolled and
green (install/upgrade/health/SCM-configured + lint + screenshot) through real CI with
the build-creation gap explicitly signed off and DEFERRED narrowed; levels + records
reconciled; M1+M2 fresh Adversary PASSes.
@@ -0,0 +1,79 @@
# Phase `dstamp` — investigate & solve the discourse abra-stamp drift
**Mission (operator-specified):** since ~2026-06-10, discourse's upgrade tier fails its
HC1 version-stamp check on EVERY run — on both old and new harness at the same ref, so it
is proven harness-neutral env drift, and its mechanism is UNATTRIBUTED. Find the root
cause, fix it properly, restore discourse to its true level in real CI, and determine
whether the same drift silently affects any other recipe's upgrade tier.
State files: `STATUS-dstamp.md`, `BACKLOG-dstamp.md`, `REVIEW-dstamp.md`,
`JOURNAL-dstamp.md`. DECISIONS.md shared.
## 1. Known evidence (rcust M2, 2026-06-11 — start here)
- Baseline: run 184 (2026-06-05) had discourse at L4 with upgrade green.
- Since ~06-10: upgrade-HC1 at ref `7ae7b0f` stamps the **prev-base tag commit
(eb96de94+U)** instead of the expected version — IDENTICAL on old pre-rcust harness
and new main (A/B at same ref + invocation ⇒ rcust exonerated, branch-tip/tag/abra-pin
drift eliminated as causes during M2; what CHANGED in the env between 06-05 and 06-10
was never attributed).
- Evidence artifacts: `/var/lib/cc-ci-runs/m2p-discourse/`,
`/var/lib/cc-ci-runs/ab-discourse-7ae7b0f-oldmain/`, JOURNAL-rcust 2026-06-11 entries,
machine-docs/DEFERRED.md note.
- Under the new de-capped semantics a failed upgrade rung blocks at L1 — this drift is
actively misrepresenting discourse, which makes it a live quality regression, not
cosmetic.
## 2. Investigation requirements
1. **Attribute, don't patch.** Build a timeline of everything stamp-relevant that changed
on the CI host between 06-05 and 06-10: abra binary version/mtime (`abra --version`,
~/.local/bin or wherever it lives), the recipe catalogue state, `~/.abra/recipes/
discourse` git state (tags, fetch times, what `git describe`/abra version resolution
sees), the discourse mirror's tags/branches (was a tag re-pointed upstream or in the
mirror?), and the harness's stash/revert dance around `abra recipe lint`/pinned deploy
(`runner/harness/abra.py:109-114`) — plus how upgrade-HC1 derives its EXPECTED stamp.
2. **Reproduce minimally** outside a full run if possible (the abra version-resolution
command against the same checkout) so the Adversary can re-run the attribution cheaply.
3. **Classify the fix target honestly:** env state (fix the host state + document how it
drifted), harness assumption (fix run_recipe_ci/lifecycle WITHOUT weakening HC1 — the
check itself must keep its teeth), or recipe/mirror tag problem (recipe-mirror PR,
never merged). If the expected-stamp derivation is what is wrong, the correction must
be justified against abra's documented behavior, not against "what makes the test
pass".
4. **Blast-radius sweep:** once attributed, check every enrolled recipe's most recent
upgrade-tier evidence for the same signature (prev-base tag commit stamped where a
version was expected). Any other affected recipe gets fixed by the same root-cause fix
and re-proven.
## 3. Gates
**M1 — Attribution.** Root cause documented with a reproducible minimal demonstration +
the 06-05→06-10 change identified by direct evidence (not inference alone); fix
implemented (env/harness/recipe per §2.3); blast-radius sweep complete. Adversary
independently reproduces the minimal demonstration and re-derives the attribution.
**M2 — Proven in real CI.** Discourse full lifecycle green with upgrade-HC1 stamping the
CORRECT value at its true level (expected L4+ / L5 if lint passes); ≥1 run via the drone
`!testme` path; any other affected recipes re-proven; HC1 demonstrably NOT weakened (the
Adversary must show a wrong stamp still fails — synthesize one if needed). DEFERRED
entry closed with pointers. Fresh Adversary PASS → `## DONE`.
## 4. Guardrails (binding)
- **HC1 keeps its teeth** — any change that would let a genuinely wrong version stamp
pass is an automatic FAIL.
- Recipe mirrors: PR only, never push main, never merge. Shared checkout race: never
git-checkout `~/.abra/recipes/discourse` while its build runs. Real-CI etiquette:
≤2-3 concurrent deploys, teardown on every exit path, no secrets in logs/commits.
- Host-state changes (abra binary, catalogue) beyond reading require a DECISIONS.md
entry; if the fix needs an abra version pin/upgrade host-wide, propose it in
STATUS-dstamp.md for the orchestrator/operator instead of doing it unilaterally.
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every
commit. CI host has no python3 on default PATH — use shell or `cc-ci-run`.
## 5. Definition of Done
Drift mechanism attributed with reproducible evidence; fixed at the true root; discourse
back at its real level in real CI (drone path included); no other recipe silently
affected; HC1 unweakened and adversarially re-proven; DEFERRED closed; M1+M2 fresh PASSes.
@@ -0,0 +1,70 @@
# Phase `ghost` — re-evaluate ghost after proxy fix and leave one clean PR
**Mission:** re-evaluate the `ghost` upgrade failure after the Swarm proxy/IPAM infra
confound has been removed, then leave exactly one operator-ready ghost PR: green if the
recipe is sound, or clearly explained with the minimum required recipe fix/comment if a real
Ghost/MySQL upgrade issue remains.
State files live under `machine-docs/`: `STATUS-ghost.md`, `BACKLOG-ghost.md`,
`REVIEW-ghost.md`, `JOURNAL-ghost.md`.
## Context
The 2026-06-12 `/upgrade-all` recorded `ghost` as the only failed recipe, but the evidence
was mixed:
- One failure was definitely infra: shared `proxy` overlay VIP exhaustion left tasks stuck
in Swarm `New` state.
- A later failure may be recipe-specific: MySQL 8.0 to 8.4 data-dir upgrade timing under
Swarm's default update monitor, producing `UpdateStatus=paused` under load.
- A previous run on 2026-06-05 passed the Ghost/MySQL path under lighter load.
- Duplicate ghost subagent churn may have left branch/PR/comment state messy.
Existing focused plan/background: `/srv/cc-ci/cc-ci-plan/plan-ghostpr-debug-fix.md`.
## Required Work
1. **Inventory PR state.** On `recipe-maintainers/ghost`, list all open PRs and branches
related to the upgrade. Identify the correct PR, expected to be ghost PR `#4`, and close
or clearly mark any duplicate only if it is truly superseded. Never merge recipe PRs.
2. **Separate infra from recipe behavior.** After `pvfix` and `pvcheck`, trigger a fresh
`!testme` on the correct ghost PR and watch the run. Do not count pre-proxy failures as
current recipe evidence.
3. **If green:** record that the prior failure was infra/timing-confounded, ensure no stale
stacks/volumes remain, and leave the PR ready for operator review.
4. **If red for a real recipe reason:** make the smallest recipe PR change needed. The
suspected fix is a longer Swarm update monitor/start grace around the MySQL 8.0 to 8.4
data-dir migration, e.g. `update_config.monitor: 300s` and related minimal service health
timing. Validate the hypothesis with logs; do not cargo-cult timing knobs.
5. **If the test is genuinely stale:** default recipe-upgrade policy applies: leave an
explanatory PR comment for the operator. Do not edit cc-ci tests in this phase unless the
operator explicitly asks for a test-update phase.
6. **Deduplicate and clean up.** Ensure exactly one relevant open ghost upgrade PR remains,
comments explain the final state, and no `ghos-*`/`dev-ghost` stacks or volumes leak.
## Gates
**M1 — State inventory and clean retry.** Builder documents PR/branch/comment/build state,
identifies the correct PR, and runs one clean post-proxy `!testme`. Adversary verifies that
pre-proxy infra failures were not misclassified as current recipe failures.
**M2 — Operator-ready outcome.** The ghost PR is green, or it has the minimal justified
recipe fix/comment and a clear current blocker. Duplicate PR/branch mess is resolved and
no ghost resources leak. Adversary verifies live PR state, build evidence, and cleanup.
## Guardrails
- Recipe PRs are never merged by agents.
- Do not weaken tests to get green.
- Do not re-run ghost during proxy maintenance or while `cfold` owns a broad CI sweep.
- Keep iterations bounded: at most three fresh post-proxy `!testme` attempts unless the
operator authorizes more.
- Preserve useful failure evidence in PR comments and `machine-docs/STATUS-ghost.md`.
## Definition of Done
Exactly one ghost upgrade PR is operator-ready, with a fresh post-proxy verdict and clear
classification of the 2026-06-12 failure. Any real recipe fix is minimal and verified;
otherwise the PR is green or has a precise operator-facing explanation. Adversary has
signed off on M1 and M2 in `machine-docs/REVIEW-ghost.md`; Builder writes `## DONE` only
after both gates have fresh Adversary PASSes.
@@ -0,0 +1,178 @@
# Phase `gtea` — enroll gitea as a FULLY-TESTED recipe (+ verify LFS PR #1)
**Mission (operator-specified 2026-06-15):** gitea currently exists in cc-ci only as a
**dependency provider** for the `drone` phase — `tests/gitea/recipe_meta.py` is the lone
file and its header says "NOT a standalone recipe-under-test". Turn gitea into a
**fully-tested recipe** (install + upgrade + backup + restore + custom functional tests +
lint + screenshot), to the same standard as `cryptpad`/`keycloak`. **Then, once the suite
is basically working, verify it against the open LFS PR**
`https://git.autonomic.zone/recipe-maintainers/gitea/pulls/1` (`feat: support Git LFS on
plain gitea`, branch `lfs-plain-gitea` → `main`) — the suite's LFS capstone test is the
mechanism that proves the PR.
**The non-negotiable constraint that shapes everything below: do NOT break drone.** gitea's
`recipe_meta.py` is loaded by the SAME code path whether gitea is drone's dep or the
recipe-under-test. Drone's CI must stay green throughout (it provisions gitea as an
install-time dep, sqlite3 + relaxed auth, via `sso.setup_gitea_oauth`).
State files: `STATUS-gtea.md`, `BACKLOG-gtea.md`, `REVIEW-gtea.md`, `JOURNAL-gtea.md`.
DECISIONS.md shared.
## 0. Prerequisites (verify before deploying)
- **`/etc/timezone` host fix is already live** (shipped with the `drone` phase — gitea binds
`/etc/timezone:ro`; the Nix `environment.etc."timezone"` fix is deployed). Builder's first
action: confirm `test -f /etc/timezone` on the cc-ci host (content `UTC`). It should exist
— drone already deploys gitea. If it's somehow absent, write a BLOCKED note in
STATUS-gtea.md ("P0 host deploy needed — orchestrator") and do meta/test authoring that
needs no deploy until the orchestrator restores it.
- abra over a pseudo-TTY (`ssh cc-ci 'script -qec "abra … -n" /dev/null'`); creds baked into
the mirror origin where needed; stash the untracked overlay. CI host has no python3 on the
default PATH.
## 1. Scope — the file manifest for `tests/gitea/`
Build to the recipe-under-test anatomy (registry/contracts: `runner/harness/meta.py`,
`runner/harness/discovery.py`; exemplars `tests/cryptpad/`, `tests/keycloak/`):
1. **`recipe_meta.py` (UPDATE — carefully; this is the conflict surface).**
- Keep the EXISTING dep behaviour intact (sqlite3 `COMPOSE_FILE`, relaxed-auth env) so
drone's gitea-dep deploy is byte-for-byte unchanged. Update the header comment: gitea is
now **both** a dep provider AND a recipe-under-test.
- Add the recipe-under-test keys that are harmless to the dep path: `HEALTH_PATH`
(`/api/healthz` already set), `HEALTH_OK`, sensible `DEPLOY_TIMEOUT`/`HTTP_TIMEOUT`,
`BACKUP_CAPABLE` (the gitea recipe HAS `backupbot.backup` labels — backup/restore are
REAL tiers, not skips), and `SCREENSHOT` (gitea has a real landing/login UI — default
capture should work; follow the `shot`-phase standard). Consider `READY_PROBE` for a
gitea-specific readiness gate (API reachable, not just TCP).
- **DB:** sqlite3 (matches the dep config + lightest footprint; gitea ships
`compose.sqlite3.yml`). Do not switch the dep to mariadb/postgres.
- **No new ALL-CAPS meta keys** without adding them to the `meta.py` registry + regenerating
docs (unknown caps = hard MetaError, unit-tested).
2. **`ops.py` (NEW)** — uniform `HookCtx` hooks (`pre_backup`/`pre_restore`/`pre_upgrade`,
and `pre_install` if needed for the LFS secret — see §3). Seed a **data-integrity marker**
via the gitea admin REST API: create a repo (+ a user/org and a committed file) before the
op so `test_backup`/`test_restore`/`test_upgrade` can assert data continuity. Model on
`tests/keycloak/ops.py` (API-based markers) — NOT file-in-container hacks.
3. **Lifecycle overlays (NEW)** — additive on the `_generic` floor:
- `test_install.py` — generic `assert_serving()` + gitea-specific: `/api/healthz` → 200 and
the admin API is reachable/authenticated.
- `test_backup.py` — the seeded repo/user marker is present after backup.
- `test_restore.py` — **mutation pattern**: `ops.pre_restore` deletes/mutates the marker;
restore must return it to the backed-up state; assert reverted (real divergence — a
no-op restore must fail this).
- `test_upgrade.py` — the marker survives the upgrade to PR-head (data continuity across
the chaos redeploy).
4. **`custom/` functional tests (NEW)** — discovered from `tests/gitea/custom/test_*.py`.
Floor is ≥2 tests **beyond** parity. Deliver:
- `custom/test_health.py` — **parity port** of `recipe-info/gitea/tests/health_check.py`.
- `custom/test_git_push.py` — **parity port** of `recipe-info/gitea/tests/git_push.py`:
create repo via API → clone → commit → push over HTTPS → verify commit landed via API →
clean up. (Has real teeth: a broken SCM fails the push.)
- `custom/test_admin_api.py` — beyond-parity: user + org + token lifecycle via the REST API
(create, read-back, delete), proving admin-API CRUD works.
- `custom/test_lfs_roundtrip.py` — beyond-parity **and the PR-#1 capstone** (see §3).
5. **`PARITY.md` (NEW)** — map the upstream corpus (`recipe-info/gitea/tests/health_check.py`,
`git_push.py`) to the cc-ci ports; document the beyond-parity custom tests + why they're
non-vacuous; record that backup/restore are REAL tiers (backupbot labels present); record
the sqlite3 DB choice; declare any deferrals with reasons (`EXPECTED_NA` for anything that
structurally can't run on `main`, e.g. LFS before PR #1 merges — see §3).
## 2. The gitea-dep conflict — the central design problem (READ FIRST)
`meta_mod.load("gitea")` returns ONE object used by BOTH roles. The two roles never run
concurrently (different `RECIPE` values: `RECIPE=drone` provisions gitea as a dep;
`RECIPE=gitea` is the recipe-under-test), but they SHARE `recipe_meta.py`. Therefore:
- **Hard gate: drone CI stays green.** After any `recipe_meta.py` change, run drone through
its CI/`!testme` path and confirm GREEN — gitea-as-dep provisioning (`sso.setup_gitea_oauth`,
`tests/unit/test_gitea_dep.py`) must be unaffected. Treat a drone regression as a failed
gate, never "acceptable collateral".
- **Do not let recipe-under-test config leak into the dep deploy.** In particular the LFS
overlay (§3) must apply ONLY when gitea is the recipe-under-test, never to drone's dep
deploy. Investigate whether `EXTRA_ENV(ctx)` can distinguish the roles (e.g. via `ctx.op` /
`ctx.deps` / domain shape) or whether the overlay belongs on a recipe-under-test-only knob.
**Decide, document the mechanism in PARITY.md + DECISIONS.md, and prove both paths.**
- If a clean split proves impossible inside one `recipe_meta.py`, raise it in STATUS before
forking any shared harness behaviour — do not silently special-case gitea in `runner/`.
## 3. Verify the LFS PR (#1) — the capstone
PR #1 (`lfs-plain-gitea` → `main`) adds **opt-in** Git LFS to plain gitea: a new
`compose.lfs.yml` overlay (`GITEA_LFS_START_SERVER=true` + a mounted `lfs_jwt_secret`), an
`app.ini.tmpl` change emitting a stable `LFS_JWT_SECRET`, `.env.sample` docs, and a version
bump `3.5.2 → 3.6.0`. The PR's own "Tested on cctest" evidence is exactly the test to encode:
**an LFS object upload→download round-trip via the batch API (downloaded bytes hash to the
OID), plus the LFS JWT secret stable across `abra app restart`** (the regression it fixes).
- `custom/test_lfs_roundtrip.py` enables LFS (`COMPOSE_FILE` includes `compose.lfs.yml`;
generate the `lfs_jwt_secret` via `abra app secret generate … lfs_jwt_secret v1` +
`SECRET_LFS_JWT_SECRET_VERSION=v1`, length 43 — wire through `EXTRA_ENV`/`ops.pre_install`
for the recipe-under-test deploy only, never the drone dep), then: init a repo with
`git lfs`, push an LFS-tracked object, fetch it from a clean clone, assert the OID hash
matches; then `abra app restart` and assert the rendered `app.ini` `LFS_JWT_SECRET` is
unchanged and tokens still validate.
- **Because `compose.lfs.yml` is NEW in PR #1, this is the proof the suite verifies the PR:**
on gitea `main` the overlay is absent → the LFS test **structurally skips** (declare it in
`EXPECTED_NA` with reason "LFS overlay lands in PR #1"); on the `lfs-plain-gitea` head the
overlay exists → the LFS test **runs and must pass**. Red/absent on main, green on the PR.
- **How to verify against the PR:** once the suite is green on `main`, run the harness with the
PR head checked out — the `ci-test-review`/`recipe-upgrade` PR path (`RECIPE=gitea
REF=lfs-plain-gitea` via `verify-pr.sh`), and/or post `!testme` on PR #1 so the result lands
in the PR for the operator. Full lifecycle (install/upgrade/backup/restore/custom) must stay
green on the PR head, AND the LFS capstone must go green there.
- **We VERIFY PR #1; we do NOT merge it** (operator's call — mirror PR-only rules). If the
verification surfaces a real defect in the PR, leave a PR comment per the `recipe-upgrade`
discipline; do not "fix" it by weakening the test.
## 4. Gates
**M1 — Suite built + green locally (on gitea `main`).** All chosen tiers green on the harness
path with evidence: install + upgrade + backup + restore + custom (`test_health`,
`test_git_push`, `test_admin_api`) + lint (L5) + screenshot. `recipe_meta.py` updated WITHOUT
breaking drone — **drone's gitea-dep deploy still green (proven, not assumed)**. The LFS test
correctly **skips** on `main` (overlay absent), declared in `EXPECTED_NA`. Unit tests for any
new harness-visible surface; no gate weakening anywhere. Adversary cold-verifies from a clean
checkout: tests have teeth (a misconfigured gitea fails install/health; `git_push` actually
pushes + verifies via API; the backup/restore mutation genuinely diverges then reverts);
declared skips justified against the published recipe; **no drone regression**; the
dep-vs-recipe-under-test split (§2) is real and documented.
**M2 — Proven in real CI + PR #1 verified.** Full gitea lifecycle green via the real CI /
`!testme` path on `main`; drone CI re-confirmed green (dep path intact); screenshot real +
visually verified; level recorded under the de-capped semantics; canonical/warm enrollment
decision documented. **Then the PR-#1 verification:** harness on `lfs-plain-gitea` head →
full lifecycle green AND the LFS round-trip + JWT-stability capstone GREEN (and demonstrably
red/skipped on `main`), result posted to PR #1; nothing merged. Operator summary in
STATUS-gtea.md. Fresh Adversary PASS on both milestones → `## DONE`.
## 5. Guardrails (binding)
- **Drone stays green — the dep path is sacred.** Never relax/weaken gitea's dep behaviour to
make the standalone suite pass. A drone regression fails the phase.
- **Recipe mirrors are PR-only.** Never push the mirror's `main`, never merge. PR #1 is the
operator's — we verify it (run the harness / post `!testme`), we do not merge it. A recipe
defect found → PR/comment per `recipe-upgrade`, operator decides.
- **Never weaken a test** to turn red green. Bounded changes (the enrollment + LFS capstone),
not harness rewrites. No new meta keys without registry + doc regeneration.
- **Secrets** (gitea admin password, OAuth client secret, `lfs_jwt_secret`) are generated
per-run and MUST stay out of logs/commits/artifacts — manifest redaction rules apply.
- **Shared swarm:** ≤2–3 concurrent deploys; one `dev-`/test gitea at a time; **tear down
every deploy on every exit path** (success, red, or abort), dep included. The drone path
brings up two deploys (gitea + drone) — budget for it.
- Host changes are orchestrator/operator-only (file them in STATUS, don't improvise). Commit
author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every commit.
## 6. Definition of Done
gitea enrolled as a fully-tested recipe (install/upgrade/backup/restore + custom functional
tests + lint + screenshot) green in **real CI**, **without breaking drone's gitea-dep path**;
PARITY.md complete (upstream `health_check`/`git_push` ported, beyond-parity tests + LFS
documented); the LFS PR #1 (`lfs-plain-gitea`) **verified GREEN** via the LFS capstone
(round-trip + JWT-secret stability) on the PR head, with the same test demonstrably
red/skipped on `main` — proving the suite catches the feature; result posted to PR #1, nothing
merged; levels/records reconciled; M1 + M2 fresh Adversary PASSes recorded in REVIEW-gtea.md.
@@ -0,0 +1,70 @@
# Phase `kuma` — uptime-kuma create-a-monitor functional test
**Mission (operator-approved 2026-06-11, DEFERRED re-entry):** add the §4.3-prescribed
functional test that completes uptime-kuma's first-run setup wizard and exercises its
core function — create a monitor, see it actually probe a target — then check off the
DEFERRED entry. This is a cc-ci-repo-only phase (tests/uptime-kuma/), no recipe PR.
State files: `STATUS-kuma.md`, `BACKLOG-kuma.md`, `REVIEW-kuma.md`, `JOURNAL-kuma.md`.
DECISIONS.md shared.
## 1. Starting facts
- DEFERRED entry (2026-05-28): uptime-kuma's first-run setup wizard + monitor CRUD run
over **Socket.IO** (not plain REST) — that's why it was deferred as fiddly. The
existing coverage is install/upgrade/health (+ screenshot, fixed in the shot phase);
the recipe currently earns its level without proving its actual function.
- uptime-kuma has no stable public REST API for this in the pinned version; the web UI
drives everything via socket.io events (`setup`, `login`, `add monitor`,
`uptimeList`). Two viable approaches — pick ONE and justify in DECISIONS.md:
(a) **python-socketio client** speaking the events directly (fast, headless, but
couples to the event names of the pinned version); or
(b) **Playwright through the real UI** (slower, but version-robust and reuses the
harness browser stack like other recipes' playwright tests).
- Wizard creates the admin credential: generated per-run, never logged (secret-safety
rules apply; the manifest redaction conventions cover meta, your test must not print
it either).
## 2. Work requirements
1. **Test design:** complete the first-run wizard (admin create) → create an HTTP
monitor pointing at a target the harness controls (e.g. the app's own /; or a
second known-up service in the deploy) → wait bounded time for ≥1 check result →
assert the monitor reports UP with a real probe timestamp. Negative teeth: a monitor
pointed at a dead target must go DOWN (proves the probe isn't a stub) — include it
if it fits the runtime budget, else justify.
2. **Placement per rcust conventions:** `tests/uptime-kuma/functional/` (or
`playwright/` if option b), uniform fixtures (`live_app`, `meta`, ctx hooks), no new
meta keys without registry+docs.
3. **Runtime budget:** the whole addition stays within the recipe's normal functional
tier budget (target ≤ ~90s added; bounded waits, no flaky sleeps — poll with
deadline).
4. **Prove in real CI:** full uptime-kuma lifecycle green with the new test active
(level should hold or rise under the de-capped ladder); ≥1 drone `!testme` run.
5. **Close records:** tick the DEFERRED entry with commit + run pointers.
## 3. Gates
**M1 — Test implemented + green.** Approach chosen and justified; test lands with
bounded waits and real assertions; full local-path lifecycle green. Adversary
cold-verifies: the monitor result is REAL (not asserted from config echo — there must
be evidence a probe executed), credentials never leak into logs/artifacts, runtime
budget held, nothing weakened.
**M2 — Proven in real CI.** Drone-path run green with the new test; flake check (2
consecutive green runs); levels reconciled; DEFERRED closed. Fresh Adversary PASS →
`## DONE`.
## 4. Guardrails (binding)
- No gate weakening; the new test only ADDS coverage. Secret-safety: generated admin
credentials never printed/committed. Real-CI etiquette: ≤2-3 concurrent deploys,
teardown on every exit path, never touch `~/.abra/recipes/uptime-kuma` mid-build.
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every
commit. CI host: no python3 on default PATH (use `cc-ci-run`).
## 5. Definition of Done
uptime-kuma proves its actual function in CI (wizard + created monitor genuinely
probing), flake-checked through the drone path, budget held, DEFERRED checked off,
M1+M2 fresh Adversary PASSes.
@@ -0,0 +1,191 @@
# Phase `lvl5` — level-system changes: 5th rung (`abra recipe lint`) + remove "capping"
**Mission (operator-specified, two changes):**
1. **New top rung — Level 5 = `abra recipe lint` passes against the exact recipe ref
under test (the PR head on PR builds)**, after the existing four rungs (install,
upgrade, backup/restore, functional). The existing four rungs' meanings are UNCHANGED.
2. **Remove the "capping" concept entirely.** The operator finds cap/cap_reason confusing.
New level semantics (operator-decided 2026-06-11, explicit Q&A + refinement):
**level = the highest rung that PASSED, where every rung below it is "pass" or an
INTENTIONAL skip.** A real FAIL blocks. A not-applicable rung is split in two:
- **Intentional skip (declared/structural):** the rung genuinely does not apply to
this recipe — e.g. not backup-capable (declared), only one published version exists
(no upgrade target). These are SKIPPED: they do not stop the climb.
- **Unintentional N/A (unverified):** the rung SHOULD have run but didn't — infra
error, missing tool (abra absent), harness exception, prior-stage abort, timeout.
**The level cannot rise above an unverified rung** — it blocks exactly like a fail
(the rungs below it still count).
Formally, with statuses {pass, fail, skip (intentional), unver (unintentional)}:
`level = max i such that rung_i == "pass" and all j < i have status in {"pass","skip"}`;
0 if no such i.
- install ✔, upgrade ✘, backup ✔, functional ✔, lint ✔ → **level 1** (fail blocks)
- install ✔, upgrade ✔, backup skip(not capable), functional ✔, lint ✔ → **level 5**
(intentional skip — previously this capped at 2; that was the confusing part)
- install ✔, upgrade ✔, backup UNVER (harness error), functional ✔, lint ✔ →
**level 2** (unverified blocks — we cannot claim what we didn't check)
- all four ✔, lint unver (abra missing) → **level 4** (an unverified top rung is
simply not earned)
**Every N/A source in derive_rungs must be explicitly classified** intentional vs
unintentional, from declared recipe meta / structural facts vs runtime failure —
the classification table goes in DECISIONS.md and is Adversary-reviewed. Default for
an unclassifiable N/A is UNINTENTIONAL (conservative).
The words "cap", "capped", "cap_reason" disappear from code, schema, card, dashboard,
and docs. The per-rung table remains everywhere it exists today (now distinguishing
✔ / ✘ / intentional-skip / unverified), so nothing is hidden — the table is the SOLE
carrier of "why isn't this level higher". Record the whole semantics change in
DECISIONS.md (it deliberately replaces the Phase-3 "N/A caps" stance; the
unverified-blocks rule preserves its honest core: never claim what wasn't checked).
State files (phase-namespaced): `STATUS-lvl5.md`, `BACKLOG-lvl5.md`, `REVIEW-lvl5.md`,
`JOURNAL-lvl5.md`. DECISIONS.md shared (append).
---
## 1. Current system (file map — verified 2026-06-11)
- `runner/harness/level.py` (120 lines, PURE) — `RUNGS = ("install", "upgrade",
"backup_restore", "functional")`, `RUNG_LABEL` 1–4, `compute_level()` (gap caps; N/A
caps with distinct reason), `tier_to_rung`, `backup_restore_status`.
- `runner/harness/results.py:137-218` — `derive_rungs()` builds the rung dict from tier
results; `compute_level` → results.json `level` + `cap_reason` + `capped`.
- `runner/harness/card.py` — `LEVEL_COLOR` map (line ~58), cap line hardcodes
*"full clean climb — top level (4)"* (line ~246).
- `dashboard/dashboard.py` — `_LEVEL_COLOR` (line ~81), corner level badge `_level_pill`,
`/badge/<recipe>.svg`.
- `tests/unit/test_level.py`, `test_results.py`, `test_card.py`, `test_dashboard.py`.
- **Lint today:** abra's pinned (non-chaos) deploy runs `abra recipe lint` internally and
FATALs on R014 — see `runner/harness/abra.py:109-114`: the CI's mirror-origin repointing
tripped a go-git path, which is why chaos deploys (the PR-testing path!) deliberately
SKIP lint. So lint currently runs implicitly on some paths and not at all on others —
the new rung makes it explicit, uniform, and visible.
## 2. Design requirements
1. **New rung `lint` appended after `functional`** → ladder install(1) upgrade(2)
backup_restore(3) functional(4) **lint(5)**. `RUNG_LABEL[5] = "lint (abra recipe lint)"`
(or similar). Full clean climb is now 5.
2. **What is linted:** the EXACT recipe tree/ref the run deployed (PR head on
`!testme`/PR builds; the tested ref otherwise) — never some other branch. Run
`abra recipe lint <recipe>` (the abra on the CI host) against the run's own checkout
context. Capture rc + full output into the run artifacts (e.g. `lint.txt`), and put a
pass/fail + short excerpt in results.json.
3. **Mirror-plumbing must not pollute recipe lint results (CRITICAL, see abra.py:109-114):**
the R014/go-git failure caused by CI's origin-repointing is a HARNESS artifact, not a
recipe defect. The lint rung must evaluate the recipe's content. Solve it properly
(e.g. lint in a context where origin looks canonical, or pre-step the same
stash/revert dance abra.py already does) — do NOT blanket-ignore lint rules to make
the plumbing pass, and document exactly what (if anything) is filtered and why. Any
filtering is a named, unit-tested, Adversary-reviewed decision.
4. **Verdict semantics UNCHANGED:** lint is a level rung, not a run gate. A lint failure
caps the level at 4 with `cap_reason "L5 ... FAILED"`; it must NOT fail/flip the run
verdict, and must be time-bounded + best-effort in execution (a wedged lint can never
hang a run — hard timeout, ~60s class).
5. **No N/A escape hatch by default:** every recipe can be linted, so the rung is
pass/fail in practice. When lint can't run (abra binary missing, timeout) the status
is **unver** + loud log — never silently "pass", never an intentional skip; the rung
is not earned and the level stays ≤ 4.
6. **De-cap implementation (mission item 2):** `compute_level()` reimplemented to the
new formal rule; `cap_reason`/`capped` deleted from level.py, derive_rungs/results.json
schema, card (the "capped: …"/"full clean climb — top level (4)" line at card.py:~246
is replaced by the rung table alone or a neutral "level N of 5"), dashboard fields,
and docs. **The top-corner level badge in particular** (the big LEVEL badge on the
card, the dashboard `_level_pill`, and `/badge/<recipe>.svg`) shows ONLY the level —
number + color, zero capping/cap-reason annotation (operator-specified 2026-06-11).
The INLINE detail keeps the intentional-skip information: the per-rung table still
marks each rung ✔ / ✘ / intentional-skip / unverified, so "why isn't it higher" lives
there and only there. Unit tests rewritten to the new semantics, INCLUDING the worked
examples from the mission and the old N/A-cases (single-published-version recipe,
non-backup-capable recipe) now climbing past their former caps.
7. **All consumers updated coherently:** RUNGS/labels, results schema, card (color map +
hardcoded top-level line), dashboard pills/badge SVG/legend text, docs
(testing.md / results docs / recipe-customization.md §levels if it references L4 as
top), and every unit test that assumes 4 is the ceiling or asserts cap_reason.
8. **History compatibility:** old results.json artifacts (level ≤ 4, lint rung absent,
cap_reason PRESENT) must still render correctly in dashboard/card history views — no
KeyErrors, no retroactive relabeling of old runs; renderers tolerate both schemas.
9. **Expected level shifts are findings, not regressions:** recipes previously capped by
an N/A rung will legitimately jump levels (e.g. a non-backup-capable recipe with
passing functional goes 2 → 4/5). P3/P4 must produce a before/after level table for
ALL enrolled recipes so the Adversary can check every shift against the new rule —
any shift NOT explained by the rule change is a real regression.
## 3. Work plan
**P1 — Ladder + plumbing.** level.py: new rung + the de-capped `compute_level()` per
§2 item 2 (delete cap_reason/capped); lint executor (new `harness/lint.py` or a clean
home in abra.py) with timeout, artifact capture, mirror-context handling per §2.3;
derive_rungs wiring (incl. the intentional-vs-unintentional classification of every N/A
source, §2 item 2); results schema. Unit tests for: full climb = 5; fail-blocks
(upgrade ✘ → L1 even with higher passes); intentional-skip climbs (backup skip +
functional ✔ → L4+); unverified-blocks (backup unver + functional ✔ → L2); lint unver →
stays 4; unclassifiable N/A defaults to unver; old-artifact rendering; mirror-filter
decision (if any).
**P2 — Presentation.** Card, dashboard, badge, docs — a level-5 color/legend that reads
as "above functional". Regenerate anything generated.
**P3 — Reality pass over all enrolled recipes.** Run the lint rung against every enrolled
recipe's current main/HEAD (cheap — lint only, no deploys, respects the shared-checkout
rule below). Matrix in BACKLOG-lvl5.md: pass/fail + rule hits per recipe. For failing
recipes: the rung correctly caps them at ≤4 (that is WORKING AS DESIGNED, not a phase
blocker). Where the fix is mechanical and safe, open a PR against the recipe mirror
(NEVER push main / NEVER merge — operator decides), else file the finding in
DEFERRED.md with the rule output.
**P4 — Real-CI proof.** Full-stage runs on enough recipes to prove the changes
end-to-end: ≥1 recipe reaching a genuine L5 (all five rungs green), ≥1 recipe blocked at
L4 by a lint failure (real or synthesized — a throwaway branch with a deliberate lint
violation is fine), ≥1 recipe demonstrating the N/A-skip (formerly capped by an N/A rung,
now climbing past it), ≥2 runs via the drone `!testme` path showing the rung on a real
PR, plus the canary suite green — the bad canaries must still land at their designed
levels under the NEW formula (re-derive what those designed levels are; backup/restore
fail still blocks). The unverified-blocks rule is proven by unit test + one synthesized
run (induce a tier abort and check the level stays below the unverified rung). Card +
dashboard visually verified (Read the PNGs/SVG output), and the §2 item 9 before/after
level table completed for all enrolled recipes.
## 4. Gates
**M1 — Implementation complete (pre-merge).** Branch with P1+P2; Adversary cold-runs unit
suite + lint from a clean checkout; reviews the mirror-filter decision (§2.3) explicitly;
confirms verdict-neutrality by code inspection + a targeted test. PASS required before
merge to main.
**M2 — Proven in real CI.** P3 matrix complete for ALL enrolled recipes; P4 runs done
(L5 achieved, L4-capped demonstrated, drone path ×2, canaries green); old artifacts still
render; run durations not materially inflated (lint adds ≤ ~60s). Fresh Adversary PASS →
Builder writes `## DONE` to STATUS-lvl5.md.
## 5. Guardrails (binding)
- **Rung statuses stay honest** (the Phase-3 rule, adapted to the new semantics): no
rung is ever silently "pass" — lint errors/timeouts/missing abra are fail/na, never
pass. The level FORMULA is the operator-decided rule in §2 item 2 (N/A skips); the
per-rung table and the run verdict must always remain visible so completeness is
never hidden, and the verdict logic itself is untouched by this phase.
- **No gate weakening; no verdict changes.** Existing tests/assertions untouchable except
where the L4-ceiling assumption itself must change — those edits are mechanical and the
Adversary checks each one against the old intent.
- **Recipe mirrors:** lint findings in recipes → PRs or DEFERRED entries only; NEVER push
recipe-mirror main, NEVER merge their PRs.
- **Shared checkout race:** NEVER git-checkout `~/.abra/recipes/<recipe>` on cc-ci while
that recipe's CI build is running — the harness deploys from that tree. P3's lint-only
sweep must use its own scratch clones or run when the recipe is not mid-build.
- Real-CI etiquette: ≤2-3 concurrent live deploys; teardown every dev deploy on every
exit path; no secrets in logs/commits. Commit author `autonomic-bot
<autonomic-bot@noreply.git.autonomic.zone>`; push after every commit.
- CI host has no python3 on default PATH for remote one-liners — use shell or the
harness venv (`cc-ci-run`).
## 6. Definition of Done
The new level system live on main and visible end-to-end (results.json → card →
dashboard → badge): L5 = abra recipe lint on the tested ref, capping concept fully
removed (level = highest passed rung with all lower rungs pass-or-intentional-skip;
declared skips climb, fails AND unverified rungs block; no cap/cap_reason anywhere),
all enrolled recipes linted and dispositioned with
the before/after level table adversary-checked, ≥1 real L5 + ≥1 lint-blocked L4 + ≥1
N/A-skip climb demonstrated through real CI including the drone path, old artifacts
unharmed, M1+M2 fresh Adversary PASSes, no verdict or duration regressions.
@@ -0,0 +1,73 @@
# Phase `mailu` — add backupbot labels to the mailu recipe (backup/restore coverage)
**Mission (operator-approved 2026-06-11 — the DEFERRED re-entry trigger "operator
approves a cc-ci-authored mailu backupbot recipe-PR" has fired):** mailu ships no
`backupbot.backup` labels, so its backup/restore rung is a structural skip. Author a
recipe-mirror PR adding proper backupbot coverage, prove backup→wipe→restore data
integrity green in real CI at the PR head, and flip mailu's backup rung from
intentional-skip to genuinely earned.
State files: `STATUS-mailu.md`, `BACKLOG-mailu.md`, `REVIEW-mailu.md`,
`JOURNAL-mailu.md`. DECISIONS.md shared.
## 1. Starting facts
- DEFERRED entry (2026-05-29): no `backupbot.backup` label on any service →
`backup_capable=False`, tiers cleanly SKIP. Durable fix = recipe-PR adding labels for
the admin DB (sqlite at /data) + the `mailu` mail volume, "mirroring the immich
Q3.5/Q3.2b pattern".
- mailu install + upgrade + functional (create-mailbox, IMAP login, send/receive
mail-flow) are already covered and green — only backup/restore is missing.
- Backupbot label syntax: use the **backupbot v2** syntax (a v1-vs-v2 syntax mistake
burned the plausible work once — see machine-docs history; verify against the
backupbot docs/other recipes' current labels, e.g. immich's merged pattern).
- Under the new level semantics, mailu currently climbs past backup as an intentional
skip; after this phase it must EARN the rung instead (and its declared-skip meta in
tests/mailu must be updated accordingly — that change is part of this phase).
## 2. Work requirements
1. **Research the recipe's real data layout before labeling:** which services hold
state (admin sqlite, mail store, redis?, certificates?), what must be quiesced or is
safe to copy live, and how the published mailu recipe + upstream docs define the
durable set. Justify every labeled path in the PR description; don't label caches.
2. **Recipe-mirror PR** (NEVER push main, NEVER merge): backupbot v2 labels + any
minimal compose plumbing they need + recipe version label bump per conventions.
3. **cc-ci side:** update tests/mailu meta (backup capability declaration) and ensure
the restore tier's data-integrity seed/verify actually exercises MAIL data (a seeded
mailbox + message that survives backup→wipe→restore — extend the existing functional
helpers if the current seed is too shallow; never weaken anything).
4. **Prove at PR head via real CI:** full lifecycle green incl. the now-active
backup/restore rung and lint (L5 expected if all rungs pass); ≥1 drone `!testme` run.
Record the before/after level (intentional-skip climb → earned rung).
5. **Close records:** tick the DEFERRED entry with PR + run pointers; operator handoff
in STATUS-mailu.md (what the PR adds, what to expect post-merge).
## 3. Gates
**M1 — PR open + green.** Root data-layout research documented; mirror PR open with
justified labels; full lifecycle green at PR head incl. restore data-integrity on real
seeded mail data; cc-ci meta/test changes minimal and unweakened. Adversary verifies the
labeled set against upstream docs (nothing durable missed, nothing junk included), the
restore proof is genuine (data actually survives a wipe), and the drone path ran.
**M2 — Operator handoff.** Fresh Adversary cold pass (independent re-trigger at PR head,
restore integrity re-checked); levels reconciled; DEFERRED closed; STATUS-mailu.md
operator summary. `## DONE` with the PR left OPEN for the operator.
## 4. Guardrails (binding)
- Recipe mirrors: PR only. No gate weakening — the restore tier's assertions may only
get STRONGER. Mail data in test fixtures must be synthetic (never real addresses
beyond test domains; no secrets in logs/commits/PR text).
- Real-CI etiquette: ≤2-3 concurrent deploys; teardown every dev deploy on every exit
path; never touch `~/.abra/recipes/mailu` during its builds.
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every
commit. CI host: no python3 on default PATH.
## 5. Definition of Done
Mirror PR open with evidence-justified backupbot v2 labels; backup→wipe→restore proven
on real seeded mail data at PR head incl. drone path; mailu's backup rung earned (not
skipped) with levels reconciled; DEFERRED closed; M1+M2 fresh Adversary PASSes; PR
unmerged for the operator.
@@ -0,0 +1,91 @@
# Phase `nixenv` — single-source the harness runtime env (timer + Drone runner share, no duplication)
**Mission (operator-specified 2026-06-17):** the nix runtime environment for the **nightly/weekly sweep
systemd timer** and the **Drone runner** must **share one declaration**, not duplicate their dependency
lists. DEFECT-3 (caught in `canon`) was exactly this divergence: the timer's `runtimeInputs` had drifted
from what recipe tests actually need (missing `bash`, then `git-lfs`), while the Drone runner got those
from the host system PATH. Patching the timer's list treated the symptom; this phase removes the **root
cause** by single-sourcing the env so a dependency can never be present for one path and missing for the
other again.
State files: `STATUS-nixenv.md`, `BACKLOG-nixenv.md`, `REVIEW-nixenv.md`, `JOURNAL-nixenv.md`. DECISIONS.md shared.
## 1. The divergence today (verified 2026-06-17)
Three separate declarations of "what's needed to run a recipe test":
- **`nix/modules/harness.nix`** — `pyEnv = python3.withPackages([pytest playwright])`; `cc-ci-run` wrapper
with `runtimeInputs = [pyEnv abra docker git coreutils util-linux]`. The Drone exec pipeline runs
`cc-ci-run runner/run_recipe_ci.py`.
- **`nix/modules/drone-runner.nix`** — runs pipelines with `PATH = /run/current-system/sw/bin` → recipe
shell-outs (`abra`/`docker`/`git`/**`git-lfs`**/openssl/…) come from **host `environment.systemPackages`**
(`nix/hosts/*/configuration.nix`, where `git-lfs` was added one-off).
- **`nix/modules/nightly-sweep.nix`** — a **duplicate** `pyEnv` + a **different** `runtimeInputs`
(`bash abra docker git curl jq gnused gnugrep gnutar coreutils util-linux procps`) + a DEFECT-3 patch
that prepends the host PATH to reach `git-lfs` etc.
So the same env is declared 2–3× with no shared source → drift (DEFECT-3). `pyEnv` alone is copy-pasted
verbatim in two modules.
## 2. Design — one shared env, referenced everywhere
Define the harness/recipe-test runtime env **once** (e.g. a `nix/modules/harness-env.nix` or a let-binding
in `packages.nix`): the `pyEnv` **and** the full recipe-test tooling set — `abra docker git git-lfs bash
util-linux coreutils curl jq gnused gnugrep gnutar openssl procps …` (the union that recipe tests + the
harness actually shell out to). Then:
1. **`cc-ci-run` (`harness.nix`)** references the shared set for its `runtimeInputs` (so the Drone
pipeline's `cc-ci-run …` has the full env directly, not via a fragile host-PATH dependency).
2. **The sweep (`nightly-sweep.nix`)** stops building its own `pyEnv`/`runtimeInputs` and instead
**invokes `cc-ci-run`** (the SAME entrypoint the Drone runner uses) — so the python env + tooling are
identical *by construction*, and the DEFECT-3 host-PATH-prepend patch can be removed/justified.
3. **Host `systemPackages`** (the Drone runner's PATH tooling, both `nix/hosts/cc-ci-hetzner/` and
`nix/hosts/cc-ci/`) references the **same shared set** rather than a hand-maintained list with a
one-off `git-lfs`.
Net: there is exactly **one place** that lists the harness's runtime dependencies; adding one (the next
`git-lfs`) propagates atomically to the Drone runner, `cc-ci-run`, and the sweep. The DEFECT-3 class
becomes structurally impossible.
Keep it a faithful refactor: the *resulting* env must be a **superset-or-equal** of every current list (do
not drop anything any path relies on — enumerate all three current lists + host git-lfs and prove the
shared set covers them). Don't over-abstract; one shared definition, three references.
## 3. Gates
**M1 — refactored + builds.** One shared env definition; `harness.nix`/`cc-ci-run`, `nightly-sweep.nix`,
and both host `configuration.nix` systemPackages reference it; no duplicate `pyEnv`; the sweep invokes
`cc-ci-run` (or otherwise provably shares the exact env). `nixos-rebuild build` succeeds. A test/grep
proving **no module declares its own harness dep list** anymore (single source). Adversary cold-verifies:
the shared set is a superset-or-equal of all prior lists (nothing dropped — `bash`, `git-lfs`, `util-linux`,
`curl`, `jq`, `openssl`, playwright browsers, etc. all present for both paths); the sweep and the Drone
runner resolve the **same** tooling; adding a hypothetical dep to the shared set would reach all consumers.
**M2 — deployed + parity proven live.** `nixos-rebuild switch` deployed (verify host health after:
`systemctl --failed`, reconcile oneshots active, `nightly-sweep.timer` active, endpoints 200). Prove
**parity in production**: the tooling available to a Drone-run recipe test and to a real timer sweep fire is
identical (e.g. `git-lfs`, `bash`, `script`/util-linux resolve in both) — re-run the DEFECT-3 witness
(gitea `test_lfs_roundtrip`) green under BOTH the Drone path and a real timer fire, from the shared env.
A canon-style sweep still promotes/SKIPs correctly under the unified env (no regression to `canon`'s
result). Fresh Adversary PASS on both milestones → `## DONE`.
## 4. Guardrails
- **High blast radius — do not break the Drone runner or the sweep.** The harness runtime env underpins
ALL recipe CI; a dropped dependency breaks every test. The shared set must be ≥ the union of today's
lists; prove it before switching.
- **Faithful refactor, not a redesign** — one shared definition, referenced from the existing modules; no
behavior change beyond removing duplication (and the now-redundant DEFECT-3 patch).
- **Host change (nixos-rebuild)** — loops may deploy if clean and **verify host health after**; else file
for the orchestrator. Both host configs (`cc-ci-hetzner`, `cc-ci`) kept consistent.
- Never weaken a test. Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push
every commit.
## 5. Definition of Done
The harness/recipe-test runtime env is declared in **one** place and referenced by `cc-ci-run` (Drone
runner entrypoint), the nightly/weekly sweep timer, and the host `systemPackages` — no duplicated `pyEnv`,
no divergent `runtimeInputs`, the DEFECT-3 host-PATH patch removed/subsumed. Proven that the shared set is
a superset-or-equal of all prior lists (nothing dropped), deployed via `nixos-rebuild` with host verified
healthy, and parity demonstrated live (the same tooling — incl. `git-lfs` — resolves for both a Drone
recipe test and a real timer sweep fire; the DEFECT-3 witness stays green under both). A future dependency
addition reaches all consumers from the single source. M1 + M2 fresh Adversary PASSes in REVIEW-nixenv.md.
@@ -0,0 +1,120 @@
# Phase `prevb` — dynamic upgrade base + per-recipe `previous/` config
**Mission (operator-specified 2026-06-16):** fix how cc-ci handles version-specific needs in the
**upgrade tier**. Today a single per-recipe overlay (`compose.ccci.yml`) conflates two different things —
*environmental* tweaks (cc-ci node is slow/memory-tight) and *version-specific repairs* (an old base's
image reference rotted) — and applies BOTH to EVERY deploy, including the PR head. That silently
overrides the head and masks the real change. Proven live on **discourse PR #4**
(`recipe-maintainers/discourse#4`, `discourse-official-image → main`): the overlay re-pins `app.image`
to `bitnamilegacy/discourse:3.3.1` and re-adds the dropped `sidekiq` service, so `!testme` deploys the
OLD image instead of the PR's new official `discourse/discourse:3.5.3` — the migration is never tested.
Replace that model with two changes, then prove them on discourse PR #4:
1. **Dynamic upgrade base** (no hardcoded `UPGRADE_BASE_VERSION`): the base the head upgrades from is
resolved at run time as **last-green (warm canonical)** → fallback **target-branch (`main`) tip** →
else **skip the upgrade tier** (recorded reason).
2. **Optional per-recipe `previous/` folder** holding the **minimal** config needed to deploy the
*previous* (last-green) version, **applied only to the base deploy and ignored for the head**.
State files: `STATUS-prevb.md`, `BACKLOG-prevb.md`, `REVIEW-prevb.md`, `JOURNAL-prevb.md`. DECISIONS.md shared.
## 1. Root cause (read first)
`tests/<recipe>/compose.ccci.yml` + `EXTRA_ENV.COMPOSE_FILE = "compose.yml:compose.ccci.yml"` is applied
to every deploy in the recipe-under-test flow. For discourse it carries BOTH:
- **environmental** (`start_period: 20m` grace, `order: stop-first`) — depends on the cc-ci node, must
apply to all deploys incl. head; and
- **version-specific repair** (`app`/`sidekiq` → `bitnamilegacy/discourse:3.3.1`) — depends on the old
0.7.0 base whose published `bitnami/discourse:3.3.1` 404s; must apply ONLY to that base.
Fusing them + applying to all deploys is the bug: the version-specific half leaks onto the head
(scalar `image:` last-file-wins override; additive service merge re-adds dropped `sidekiq`).
## 2. Design
**Decompose the overlay into two layers** — the harness applies them to different deploys:
- **Environmental overlay (all deploys, incl. head).** Node-reality tweaks the recipe itself doesn't
encode (e.g. rollout `order`). Keep it MINIMAL and shrink over time (a well-formed recipe head ships
its own grace — PR #4 already has `start_period: 20m`). It must contain **no version-specific image
pins or service add/drop**.
- **`tests/<recipe>/previous/` (base deploy ONLY, ignored for head).** The minimal bundle needed to bring
up the **previous (last-green) version** when it can't deploy as-published — e.g. an image relocation
(`bitnami/* → bitnamilegacy/*`), or an era-specific service/step/env. Mirror the recipe-under-test
layout but scoped to "deploy the previous version" (typically just a `compose.previous.yml`; add an
`install_steps.sh`/`ops.py`/env override only if that version genuinely needs it). **Keep it as small
and simple as possible — add one only where necessary.**
**Dynamic base resolution (replace static `UPGRADE_BASE_VERSION`):**
1. **Primary: last-green (warm canonical).** Upgrade from the last version cc-ci recorded green for this
recipe (prefer the warm-canonical snapshot where one exists — it's already data-warm, giving a
realistic data-survival signal and avoiding a from-scratch old-version deploy).
2. **Fallback: target-branch (`main`) tip** when there is no last-green (e.g. a recipe with no recorded
green predecessor yet). This is the real predecessor the PR merges on top of.
3. **Else skip** the upgrade tier with a recorded reason (new recipe / no predecessor). Structural skip,
declared (`EXPECTED_NA`), not a silent pass.
**`previous/` is for the current previous version, and is removable when stale.** To stop a stale folder
silently overriding a non-matching base, `previous/` **declares the version it targets** (simplest: a
one-line marker, or the `coop-cloud.*.version` label in its `compose.previous.yml`). The harness applies
it **only when the resolved base version matches**; on mismatch it **skips it and flags it stale
("previous/ targets X, base is Y — remove it")**. After a recipe upgrade PR merges (new last-green), the
now-stale `previous/` should be removed — keep it to roughly one version's worth, never an accumulating pile.
## 3. Discourse as the first real case
- **main today is `bitnamilegacy/discourse:3.3.1`** (deployable — bitnamilegacy exists). So with a dynamic
base, the base = last-green (≈ main) **deploys cleanly with NO `previous/` needed**: the rotted-base
treadmill evaporates because we no longer resurrect the frozen 0.7.0 tag. (Confirm main's image; if the
last-green base genuinely still needs a repair to deploy, add a **minimal** `previous/` — but expect not.)
- Move discourse's environmental tweaks (rollout `order`, any grace the head lacks) into the environmental
overlay; **delete the `bitnamilegacy` image pins and the `sidekiq` block from the all-deploys overlay**;
**remove `UPGRADE_BASE_VERSION`**.
- **PR #4 head now deploys UNMODIFIED** → the chaos redeploy runs the real `discourse/discourse:3.5.3`
with no `sidekiq`, so the upgrade tier finally exercises the actual official-image migration
(last-green bitnamilegacy → official head) the PR claims to support.
## 4. Gates
**M1 — implemented + green locally.** Harness: dynamic base resolution (last-green → `main` → skip);
`previous/` discovery + base-only application + version-guard/stale-flag; environmental overlay separated
from version-specific config; `UPGRADE_BASE_VERSION` removed. Discourse migrated. Unit tests for the new
harness surface (base resolution, `previous/` match/skip, overlay layering). Discourse upgrade tier green
locally with **proof the head runs the real head image** — assert the deployed `app` image is
`discourse/discourse:3.5.3` (NOT bitnamilegacy) and that no `sidekiq` service exists post-deploy. Adversary
cold-verifies from a clean checkout: the overlay no longer touches the head; a deliberately-broken head
still fails the upgrade tier (teeth — base resolution didn't paper over it); base falls back to `main`
correctly when last-green is absent; `previous/` is ignored for the head; **no test weakened**.
**M2 — proven in real CI + a representative spot-check.** discourse PR #4 `!testme` **GREEN**, with
evidence the head genuinely ran `discourse/discourse:3.5.3` (not the old bitnami image) and the migration
was exercised. Spot-check ≥3 other recipes with upgrade tiers (e.g. one warm-canonical recipe, one with a
published predecessor, one that previously relied on a `.ccci` overlay — keycloak/cryptpad/ghost) to
confirm dynamic base works generally and nothing obvious broke. (FULL all-recipe regression is the
**next phase `regall`** — do not attempt it here; just don't ship something obviously broken.) Levels /
records reconciled. Fresh Adversary PASS on both milestones → `## DONE`.
## 5. Guardrails (binding)
- **Make the test FAITHFUL, never weaker.** The goal is that the head runs the head's real image; never
resolve the base or apply `previous/` in a way that hides a genuinely broken head. A broken upgrade
must still go RED.
- **`previous/` minimal + non-accumulating.** Only what's strictly needed to deploy the previous base;
version-guarded; removable when stale. No `previous/` at all if the last-green base deploys clean.
- **Don't regress other recipes.** Dynamic base must work for recipes with/without warm canonicals and
with/without published predecessors. (The `regall` phase is the exhaustive proof; here, don't break the
spot-check set.)
- **Recipe mirrors are PR-only.** We VERIFY discourse PR #4 (run the harness / post `!testme`); we do NOT
merge it (operator's call). A recipe defect found → PR comment, not a test weakened.
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every commit; abra over a
pseudo-TTY. Host changes are coordinated (loops self-rebuilding the host is acceptable if clean — verify
host health after; but this phase likely needs none).
## 6. Definition of Done
Dynamic upgrade-base resolution (last-green → `main` → skip) and the optional minimal `previous/` folder
shipped and unit-tested; the environmental vs version-specific layers cleanly separated; discourse
migrated off the static base + leaky overlay; **discourse PR #4 verified GREEN in real CI with the head
genuinely running the official `discourse/discourse:3.5.3` image** (the migration actually tested), and a
representative recipe spot-check still green; nothing merged on the mirror; M1 + M2 fresh Adversary PASSes
in REVIEW-prevb.md. (Exhaustive all-recipe regression handed to phase `regall`.)
@@ -0,0 +1,67 @@
# Phase `pvcheck` — post-proxy verification and regression proof
**Mission:** prove that the durable `proxy` overlay fix is actually safe in production:
the network has the intended headroom, routing works, real recipe CI still deploys through
Traefik, and the IPAM/VIP exhaustion signature no longer threatens the weekly upgrade path.
State files live under `machine-docs/`: `STATUS-pvcheck.md`, `BACKLOG-pvcheck.md`,
`REVIEW-pvcheck.md`, `JOURNAL-pvcheck.md`.
## Preconditions
- Phase `pvfix` is `## DONE`.
- `docker network inspect proxy` shows the intended `/16` subnet.
- Core control-plane services are back after the proxy recreation.
## Verification Scope
1. **Host/network facts.** Capture and record:
- `docker network inspect proxy` subnet and endpoint count
- `docker stack ls`
- Traefik, Drone, bridge, dashboard, and report service health
- recent dockerd journal lines for VIP/IPAM errors
2. **Routing checks.** Verify externally visible routes still work:
- Drone UI/API route
- dashboard route
- bridge/poller health if exposed locally
- report site route
3. **Real deploy proof.** Trigger one low-risk enrolled recipe `!testme` or equivalent
harness run that joins `proxy`, completes all expected tiers, and tears down cleanly.
Prefer a small stable recipe unless `cfold` needs a broader sweep at the same time. Do
not duplicate an active `cfold` sweep.
4. **Allocator-headroom proof.** Run a bounded reproduction derived from
`plan-proxy-vip-exhaustion-fix.md`:
- deploy/remove a small batch of throwaway published-port stacks, preferably in the same
concurrent pattern that previously leaked endpoints
- confirm leaked endpoint count, if any, is tiny relative to `/16` headroom
- confirm no fresh `could not find an available IP while allocating VIP` errors
- prune throwaway networks/stacks and verify no residue
5. **Upgrade safety check.** Confirm the `/upgrade-all` Step-0 guard still exists and would
detect/recover the known VIP exhaustion signature if it ever recurs.
## Gates
**M1 — Control plane and routing verified.** All cc-ci control-plane routes/services are
healthy after the proxy recreation, with before/after evidence in `STATUS-pvcheck.md`.
Adversary verifies independently from live commands, not just Builder notes.
**M2 — Real CI and allocator proof verified.** At least one real recipe deploy/test passes
through `proxy` and tears down cleanly; bounded allocator reproduction does not threaten the
new `/16`; no VIP exhaustion signature remains in fresh logs. Adversary verifies all claims
and checks for leaks.
## Guardrails
- Do not run a large recipe sweep here if `cfold` already owns that proof. This phase is the
proxy-specific post-change proof.
- Keep concurrency bounded. The point is to prove headroom, not stress the host into a new
unrelated failure.
- Clean up every throwaway stack/network. Zero residue is part of the acceptance criteria.
- If any core route is down, stop new test traffic and fix routing first.
## Definition of Done
Control-plane routes are healthy, one real proxy-joining recipe CI run succeeds and cleans
up, bounded allocator reproduction is documented, fresh logs show no VIP exhaustion, and
Adversary has signed off on M1 and M2 in `machine-docs/REVIEW-pvcheck.md`. Builder writes
`## DONE` only after both gates have fresh Adversary PASSes.
@@ -0,0 +1,81 @@
# Phase `pvfix` — durable Swarm `proxy` overlay VIP exhaustion fix
**Mission:** eliminate the recurring Docker Swarm `proxy` overlay VIP exhaustion class by
making the shared `proxy` network large enough for the cc-ci workload, while preserving the
already-added per-run safety net. This is an infra phase: coordinate carefully, because
recreating `proxy` briefly disrupts routing for Traefik, Drone, dashboard, bridge, reports,
and any live recipe deploys.
State files live under `machine-docs/`: `STATUS-pvfix.md`, `BACKLOG-pvfix.md`,
`REVIEW-pvfix.md`, `JOURNAL-pvfix.md`.
## Context
The 2026-06-12 weekly upgrade exposed a real infra failure mode:
- The shared `proxy` overlay was using Docker's default `/24` allocation (`10.0.1.0/24`,
254 VIPs).
- Every recipe deploy joins `proxy` for Traefik routing.
- Concurrent stack removal can race Swarm endpoint GC (`key modified`, `network proxy
remove failed`) and leak endpoint/VIP allocations.
- After 11 days of dockerd uptime the allocator exhausted the `/24`, producing
`could not find an available IP while allocating VIP` and leaving tasks stuck in Swarm
`New` state.
- A docker restart rebuilt allocator state and cleared the symptom, proving the issue was
infra, not the affected recipes.
Existing runbook/background: `/srv/cc-ci/cc-ci-plan/plan-proxy-vip-exhaustion-fix.md`.
## Required Fix
1. Confirm the current host state is quiet enough for a disruptive network maintenance
window. No live `/upgrade-all`, no active recipe `!testme` runs, no phase CI sweep in
progress.
2. Update `nix/modules/swarm.nix` in the cc-ci repo so the `proxy` overlay is created with
an explicit `/16`, for example:
```bash
docker network create --driver overlay --attachable --subnet 10.10.0.0/16 proxy
```
Use a subnet clear of `ingress` and existing Docker allocations. If `10.10.0.0/16` is
unsuitable on the live host, choose a different documented `/16` and explain why.
3. Keep the upgrade Step-0 safety net in place: prune leaked overlays and restart Docker
when VIP-allocation failure signatures are detected. The durable `/16` fix is headroom;
the guard is still useful as a future self-healing belt-and-braces mechanism.
4. Recreate the live `proxy` network safely. The network cannot be resized in place.
Plan the exact live-host steps before executing them. The expected sequence is:
- capture current `proxy` inspect output and joined services
- stop or drain live recipe stacks as needed
- remove/recreate `proxy` with the `/16`
- redeploy/reconcile Traefik and the cc-ci control-plane services so they rejoin
- run `nixos-rebuild switch` using the canonical live cc-ci deploy checkout
5. Commit and push the cc-ci repo change. Do not commit secrets. Do not merge recipe PRs.
## Gates
**M1 — Plan and patch ready.** Builder produces the minimal `swarm.nix` patch, records the
exact maintenance procedure, and proves from live inspection that the chosen `/16` is safe.
Adversary cold-reviews the patch and live procedure before any disruptive action.
**M2 — Live durable fix applied.** The live host has `proxy` recreated as `/16`, the NixOS
configuration has been switched, and Traefik/Drone/dashboard/bridge/reports are reachable.
Adversary verifies from the host that `docker network inspect proxy` reports the intended
subnet and that the control-plane services are healthy.
## Guardrails
- Maintenance window only. Do not recreate `proxy` while recipe CI, `/upgrade-all`, or
`cfold` sweep runs are active.
- No force-pushes. No secret values in logs, plans, commits, or comments.
- Prefer the smallest host change: one explicit `--subnet` plus the minimum live
reconciliation needed to restore routing.
- If the host topology differs from the runbook, stop and record the actual state before
changing anything.
## Definition of Done
`proxy` is explicitly configured and live as a `/16`, the change is committed and pushed to
cc-ci, core routes are healthy after the maintenance action, and Adversary has signed off on
M1 and M2 in `machine-docs/REVIEW-pvfix.md`. Builder writes `## DONE` only after both gates
have fresh Adversary PASSes.
@@ -0,0 +1,76 @@
# Phase `pxgate` — break the deploy-proxy ↔ dashboard health-gate circular dependency (D8 fix)
**Mission:** fix the boot-ordering deadlock the Adversary filed as A1 (BACKLOG-pvfix /
DEFERRED 2026-06-13) so a **from-scratch (D8) boot brings traefik up cleanly** instead of
deploy-proxy hanging 15 min and failing. The traefik proxy must still be health-gated with
rollback — just gated on a signal that does NOT depend on a service ordered after it.
State files under `machine-docs/`: `STATUS-pxgate.md`, `BACKLOG-pxgate.md`,
`REVIEW-pxgate.md`, `JOURNAL-pxgate.md`. DECISIONS.md shared.
## Root cause (verified)
1. `nix/modules/proxy.nix` — `deploy-proxy.service` runs `warm_reconcile.py traefik`; its
`wait_healthy` polls **`https://ci.commoninternet.net` → 200**. `TimeoutStartSec = 900`.
2. `https://ci.commoninternet.net` is served by the **dashboard**.
3. `nix/modules/dashboard.nix` — `deploy-dashboard.service` has **`After=deploy-proxy.service`**,
so systemd won't start the dashboard until deploy-proxy exits.
→ On a fresh boot: proxy waits for the dashboard, dashboard waits for proxy → proxy times out
at 900s and **fails**, then the dashboard starts onto a failed proxy. (On the *running*
server it's invisible — the dashboard is already up — which is why it's a latent D8 risk.)
## Required fix
Break the cycle while keeping a MEANINGFUL traefik health signal + the rollback semantics
(deploy latest → health-gate → commit last-good if healthy / roll back to last-good if not).
**Recommended approach (Builder confirms in DECISIONS.md):** change the deploy-proxy health
gate to probe a **traefik-self-served endpoint that is up the moment traefik is, with no
backend/dashboard dependency** — e.g. traefik's own `ping` entrypoint (`/ping` → 200) or
`https://traefik.ci.commoninternet.net/api/version`. That confirms "traefik (re)deployed and
is serving" — enough to drive the rollback decision — without waiting on `ci.commoninternet.net`.
- If you still want an end-to-end "traefik routes to a real backend" assertion, move THAT to a
**separate converge/health step ordered AFTER the dashboard** (or rely on the dashboard's own
health gate); it must NOT be inside the deploy-proxy oneshot.
- Do NOT simply delete the health gate (loses the rollback safety net). Do NOT just bump the
timeout (the deadlock still fails on a cold boot, just slower). Do NOT reintroduce any
dependency on a service that is `After=deploy-proxy`.
- Make sure traefik actually EXPOSES whatever endpoint you choose (the `ping` entrypoint /
api may need enabling in the traefik recipe/compose) — verify it returns 200 with only
traefik up.
Touch points: `nix/modules/proxy.nix`, the traefik health check in `runner/warm_reconcile.py`
(and/or `runner/harness/*` health helpers), possibly the traefik recipe overlay to expose the
health endpoint. Check the other `After=deploy-proxy` consumers (drone, warm-keycloak, reports,
bridge, backupbot, nightly-sweep) still order correctly after the change.
## Gates
**M1 — Fix + controlled reproduction (Builder/Adversary, on a test box / the cc-ci host
without a real wipe).** Implement the fix. Reproduce the cycle in a CONTROLLED way (per the
Adversary's A1 repro): with the dashboard held back / absent, show the OLD gate hangs→fails and
the NEW gate goes healthy on traefik alone. Unit/integration-test the new health check.
Adversary cold-verifies: cycle is genuinely broken, health signal is still meaningful (a
broken traefik must still fail the gate and roll back), no `After=deploy-proxy` consumer
regressed. PR to cc-ci repo; do NOT merge to the live host yet.
**M2 — Proven on a real from-scratch boot.** The durable proof is a **from-scratch / cold
boot** where `deploy-proxy` reaches `active` without the dashboard and the whole control plane
converges. Coordinate with the orchestrator: the orchestrator owns the live `nixos-rebuild` and
any throwaway-VM / from-scratch rebuild (host infra is orchestrator/operator territory, not the
loops). Acceptance: on a clean boot deploy-proxy is `active` (not failed), the rollback path
still works on a deliberately-broken traefik, and the running server is unaffected. Fresh
Adversary PASS → `## DONE`.
## Guardrails
- **Health verification must stay honest** — a traefik that isn't actually serving must still
fail the gate and roll back to last-good. Breaking the cycle must not become "always pass".
- Live host changes (`nixos-rebuild`, from-scratch boot) are **orchestrator/operator-owned**;
the loops produce the code + controlled proof and a PR, the orchestrator deploys + runs the
cold-boot test. The loops must NOT nixos-rebuild the live host themselves.
- No gate weakening elsewhere; minimal change; no secrets in commits. Commit author
`autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every commit. CI host has no
python3 on default PATH — use the harness venv.
## Definition of Done
The deploy-proxy↔dashboard cycle is broken: a from-scratch boot brings traefik up health-gated
(on a dashboard-independent signal) with rollback intact, no consumer mis-ordered, the running
server unaffected, the A1 / DEFERRED entry closed with pointers, and M1+M2 fresh Adversary PASSes.
@@ -0,0 +1,108 @@
# Phase `redfix` — investigate every canon-sweep failure + open fix PRs
**Mission (operator-specified 2026-06-17):** the `canon` cold-full-lifecycle sweep (every recipe's latest
release deployed from scratch + warm-promote) surfaced failures the **upgrade-only weekly run never
tests**. Investigate **all** of them, root-cause each, and **FIX every one** — each via **a recipe PR or a harness
improvement** (operator 2026-06-17). **None is left as a standing exception** (keycloak's de-enrollment and
gitea's "documented limitation" are NOT acceptable end states — they must be fixed). The operator recalls
**mattermost-lts and mumble passing before**, so **flake-vs-genuine classification (via isolated re-runs)
is the crux** — but note a flake still gets a fix (a harness stabilization improvement), not a shrug.
State files: `STATUS-redfix.md`, `BACKLOG-redfix.md`, `REVIEW-redfix.md`, `JOURNAL-redfix.md`. DECISIONS.md shared.
## 1. The failing set (from canon DECISIONS §canon exceptions)
| Recipe | What happened in the sweep | First hypothesis |
|---|---|---|
| **discourse** | cold-deploy **timeout** (rc=142/143, ~51-min wedge) | slow Rails boot under load → timeout/headroom, maybe the start-first rollout |
| **mattermost-lts** | `test_restore.py::test_restore_returns_state` FAILED at latest | restore-tier — possibly the known backup/restore db-cycle race on the loaded node |
| **mumble** | `custom/test_protocol_handshake.py::test_handshake_completes_with_channel_presence` FAILED | readiness/timing of the protocol handshake |
| **bluesky-pds** | cold test **GREEN**, warm-canonical promote FAILED (`warm-bluesky-pds…` → 000, cold domain + other 15 warm domains route fine) | warm-canonical-deploy **routing machinery** (cc-ci side) |
| **gitea** | cold test **GREEN**, `3.5.3→3.6.0` warm **advance** doesn't promote (app.ini read-only) | recipe: read-only `app.ini` blocks in-place warm advance (ties to LFS PR #1) |
| **keycloak** | **de-enrolled** (not tested) — live-warm OIDC dep collision on `warm-keycloak…` | **harness fix:** canonical warm deploys need a domain/namespace that can't collide with a live service, so keycloak can enroll |
## 2. Method — per recipe: isolate → root-cause → classify → fix-PR
1. **Reproduce in ISOLATION first.** Re-run each failing recipe through the harness **alone** (not under
concurrent sweep load) on cc-ci. The loaded single node during the sweep is a known flake source
(backup/restore db-cycle races, deploy timeouts). This directly answers the operator's "they passed
before": if a recipe is **green in isolation**, it's a load/concurrency **flake**, not a recipe defect
— and the fix is harness stabilization (or a documented known-flake), NOT a recipe change.
2. **Root-cause** with real evidence — the actual assertion/error, deploy logs (`docker service logs`),
the wedge cause. No guessing.
3. **Classify** each precisely:
- **Recipe defect at latest** → a **recipe PR** on the `git.autonomic.zone` mirror via the
`recipe-upgrade`/`recipe-upstream` flow, verified with `!testme` (NEVER merge — operator).
- **Stale/wrong cc-ci test** → per the standing discipline: leave a PR **comment**, or a cc-ci
**test PR** only under the `--with-tests` gate. **Never weaken a test** to turn a red green.
- **Warm-canonical machinery defect** (bluesky routing) → a **cc-ci branch PR** (single-writer; never
push main).
- **Load/concurrency flake** → a harness **stabilization** fix (timeout/serialization/readiness/retry)
as a cc-ci PR, or a documented known-flake if genuinely environmental.
4. **Open the fix PR** for each and **verify it** (recipe PR green via `!testme`; cc-ci PR via the
harness). One PR per fix; capture URLs.
## 3. Per-recipe specifics to chase
- **discourse** — characterise the timeout/wedge: is it just headroom (raise `DEPLOY_TIMEOUT` / give it an
uncontended deploy) or a real convergence bug? It cold-deploys fine in the weekly with headroom. Fix =
cc-ci timeout/serialization tuning and/or a recipe convergence fix — whichever the evidence shows.
- **mattermost-lts** — does `test_restore_returns_state` fail in isolation? If green → the loaded-node
restore race (cf. plausible/ghost) → stabilize (e.g. a `BACKUP_VERIFY`-style settle/retry). If red →
diagnose the restore (recipe vs test) and fix the right side.
- **mumble** — does the handshake test fail in isolation? Likely a readiness/timing gap (handshake before
the channel is up) → readiness probe / retry, or a genuine recipe/test issue.
- **bluesky-pds** — why does `warm-bluesky-pds…` return 000 while the cold-test domain and the other 15
warm domains route fine? Find the warm-deploy routing defect (cc-ci warm machinery) and fix it so
bluesky promotes; it should then drop from the exception list.
- **gitea** — **fix it** so it promotes `3.6.0`: either a **recipe PR** making `app.ini` writable for the
in-place warm advance, OR a **harness improvement** so the warm advance falls back to a clean re-deploy
when an in-place config rewrite isn't possible. Pick per evidence; the bar is gitea promotes `3.6.0`
(ties to the LFS `app.ini` change in PR #1). Not "documented as inherent."
- **keycloak** — **fix via a harness improvement** so it can be enrolled safely: canonical warm deploys
must use a domain/namespace that can **never** collide with a live shared service (e.g. a dedicated
`warm-canon-<recipe>` / per-canonical namespace), so keycloak's canonical deploys without touching the
live OIDC service. (Likely shares a root cause with bluesky's warm-routing — a single warm-domain fix may
resolve both.) Don't risk the live keycloak — the fix is isolation, then enroll.
## 4. Gates
**M1 — all investigated, isolated, classified.** Every recipe in §1 re-run in isolation with evidence; a
results table `recipe → failure → isolation result (flake|genuine) → root cause → classification → fix
approach`. Adversary cold-verifies the classifications: a claimed **flake** is reproducibly green in
isolation (and red under load); a claimed **recipe defect** is genuinely the recipe (not a stale test or a
harness artifact); a claimed **warm-machinery** bug is in cc-ci, not the recipe. No "it's probably a
flake" without an isolation re-run proving it.
**M2 — all six FIXED + verified.** For each, the appropriate fix (a recipe PR or a harness improvement)
exists and is **verified green** (recipe PR via `!testme`; harness/cc-ci PR via the harness;
flake-stabilization re-run green under load). **All six promote/pass after the fix** — bluesky promotes
(warm-routing fixed), gitea promotes `3.6.0`, keycloak enrolled + promotes via the collision-free warm
domain, discourse converges in time, mattermost-lts + mumble green (stabilized if flake, fixed if real).
**No recipe left as a standing exception.** If one genuinely cannot be fixed at the recipe level, the fix
moves to the harness (or a recipe PR + a tracked upstream issue) — never a shrug. **Nothing merged**
(operator merges). A short report: per recipe, flake-or-real, the fix, and the verification. Fresh
Adversary PASS on both milestones → `## DONE`.
## 5. Guardrails
- **Isolation before blame.** Never fix a load-flake as a recipe bug, or a recipe bug as a flake — the
isolation re-run is mandatory evidence (especially for mattermost-lts/mumble, which the operator saw pass).
- **Recipe mirrors are PR-only** — recipe defects get a PR, `!testme`-verified, **never merged**. **Never
weaken a cc-ci test** to make a recipe green; a stale test gets a comment or a `--with-tests` test PR.
- **cc-ci changes** on a dedicated branch (single-writer; never push main, never disturb other clones).
- **Shared swarm:** ≤2–3 concurrent deploys; tear down every deploy on every exit path; mind the live
warm services (keycloak especially). Host changes coordinated (loops may rebuild if clean + verify health).
- Honest reporting — a flake is labelled a flake with proof; a recipe left unfixed is called out with the
reason. Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every commit; abra
over a pseudo-TTY.
## 6. Definition of Done
All six canon-sweep failures (discourse, mattermost-lts, mumble, bluesky-pds, gitea, keycloak)
investigated in isolation, root-caused, classified (flake vs genuine; recipe vs test vs warm-machinery vs
load), and **FIXED — each via a recipe PR or a harness improvement — and verified green**: bluesky promotes
(warm-routing fixed), gitea promotes `3.6.0`, keycloak enrolled via a collision-free warm domain, discourse
converges, mattermost-lts + mumble green (stabilized or fixed). **None left as a standing exception.**
Nothing merged (operator merges); a clear flake-vs-real report with the fix + verification per recipe.
M1 + M2 fresh Adversary PASSes in REVIEW-redfix.md.
@@ -0,0 +1,65 @@
# Phase `regall` — full all-recipe regression after the dynamic-base / `previous/` change
**Mission (operator-specified 2026-06-16):** the `prevb` phase changed the upgrade tier for EVERY recipe
(dynamic base resolution: last-green → `main` → skip; new `previous/` lookup; environmental-vs-version
overlay split). Run the **entire recipe suite** through cc-ci to ensure **nothing regressed**, and **fix
anything that did**. This is the safety net for a cross-cutting harness change.
State files: `STATUS-regall.md`, `BACKLOG-regall.md`, `REVIEW-regall.md`, `JOURNAL-regall.md`. DECISIONS.md shared.
## 1. Scope
- **Every recipe cc-ci tests** — the `weekly` + `external` rows in `cc-ci-plan/used-recipes.md` that have a
`tests/<recipe>/` dir (all the enrolled recipes, ~21). Drone's gitea-dep path counts too.
- **All tiers**, with focus on the **upgrade tier** (changed most by `prevb`): install / upgrade / backup
/ restore / custom / lint / screenshot, via the real harness / CI path.
- **Baseline = the recorded pre-`prevb` green levels** per recipe (cc-ci's level records). A regression =
a recipe that dropped a level, or a tier that newly fails, **relative to that baseline** — not relative
to "perfect."
## 2. Method
1. Run each recipe through the harness (parallelize within the shared-swarm budget — ≤2–3 concurrent
deploys; tear down every deploy on every exit path). Capture level + per-tier pass/fail.
2. Build a results table: `recipe | baseline level | new level | per-tier delta | verdict`.
3. **Classify each regression**: caused by the `prevb` change (dynamic base resolution / `previous/`
lookup / overlay split), or **pre-existing / flaky / environmental** (was already red, or fails on
re-run independent of `prevb`). Be honest — a recipe that was already red stays red; say so, don't
claim a fix.
4. **Fix the `prevb`-caused regressions:**
- Harness-logic regressions → fix in `runner/**` (e.g. a base that resolves wrong, a `previous/`
mis-match, an overlay layering bug).
- A recipe whose **last-green base no longer deploys** under dynamic resolution → add a **MINIMAL**
`previous/` folder for it (same rules as `prevb`: smallest thing that brings the base up,
version-guarded, removable when stale). Do NOT over-add `previous/` folders — only where a base
genuinely won't deploy.
5. Re-verify each fix green. Never weaken a test to clear a regression.
## 3. Gates
**M1 — full sweep done + classified.** Every in-scope recipe run; results table complete with
baseline-vs-new levels; each regression classified `prevb-caused` vs `pre-existing/flaky`, with evidence.
Adversary cold-verifies the classification (spot-re-runs a sample, confirms a claimed flake really is one,
confirms a claimed `prevb`-cause is real).
**M2 — regressions fixed, suite back to baseline.** Every `prevb`-caused regression fixed + re-verified
green (harness fix and/or a minimal `previous/` folder); no recipe below its pre-`prevb` baseline; any
added `previous/` folders are minimal + version-guarded; pre-existing reds documented (not silently
absorbed). Fresh Adversary PASS → `## DONE`.
## 4. Guardrails
- **Never weaken a test** to clear a regression; fix the harness or add a minimal `previous/`.
- **`previous/` stays minimal + non-accumulating** — add only where a base won't deploy.
- **Report honestly** — pre-existing/flaky reds are labelled as such with evidence, never claimed fixed;
any recipe left below baseline is called out explicitly with the reason.
- Shared swarm: ≤2–3 concurrent deploys; tear down every deploy on every exit path; `/upgrade-all`'s
`dev-*` reaper is a backstop, not a substitute. Recipe mirrors PR-only; never merge. Commit author
`autonomic-bot`; push every commit; abra over a pseudo-TTY.
## 5. Definition of Done
Every enrolled recipe run through cc-ci after the `prevb` change; a complete baseline-vs-new results table;
all `prevb`-caused regressions fixed + re-verified green (no recipe below its pre-`prevb` baseline); any
needed `previous/` folders added minimally; pre-existing reds documented honestly; M1 + M2 fresh Adversary
PASSes recorded in REVIEW-regall.md.
@@ -0,0 +1,101 @@
# Phase `samever` — step back to an older base when last-green == head (no same-version upgrade)
**Mission (operator-specified 2026-06-17):** close a gap in the `prevb` dynamic upgrade-base resolver.
When the resolved **last-green (warm-canonical) base version equals the PR head version**, the upgrade
tier currently deploys the **same version** as base and head — a vacuous, non-upgrade "upgrade." Instead
of skipping the tier, **step back to a genuinely older base**: the **newest published version strictly
older than the head version**. The upgrade must always cross a real version delta when an older version
exists. (This is design **A**; design B "canonical history" is deferred — see `cc-ci-plan/IDEAS.md`.)
State files: `STATUS-samever.md`, `BACKLOG-samever.md`, `REVIEW-samever.md`, `JOURNAL-samever.md`. DECISIONS.md shared.
## 1. Background / root cause
`resolve_upgrade_base` (`runner/run_recipe_ci.py:111`) resolves the upgrade base. Its two paths are
guarded **unequally**:
- **ref (main-tip) path — guarded:** `if main_tip == head_ref → skip "head == main tip (no predecessor
delta)"`.
- **version (last-green canonical) path — NOT guarded:** it returns `BasePlan("version", rec["version"],
…)` without checking that the canonical version differs from the head. The resolver isn't even given
the head's *version* (only `head_ref`, a commit), so it currently can't compare.
When does the canonical equal the head version? The canonical advances **only** on a GREEN + COLD +
LATEST run of a `WARM_CANONICAL`-enrolled recipe (`should_promote_canonical` = `is_enrolled and
overall==0 and not quick and not ref`; a PR `!testme` carries `ref` so it NEVER promotes). So the
canonical is always the latest-published version that last passed a cold sweep.
**This is the STEADY STATE of the nightly sweep, not a rare edge (operator insight 2026-06-17).** The
nightly cold-on-latest run is exactly what *promotes* the canonical to LATEST. So once one green nightly
run promotes `canonical → vX`, **every subsequent nightly run — until a new version ships — finds
`canonical == latest == the version under test`**, and its upgrade tier resolves `base == head` → a
same-version no-op → effectively no upgrade test the second night. (The non-version-bump PR is the same
collision, less common.) So the step-back is the *common* nightly path, not an oddball — the resolver must
handle it as the norm. With the fix, the second nightly run tests `vX-1 → vX` (a real upgrade; a repeat of
the first night's, but real, not vacuous).
## 2. Design (A)
Give the resolver the **head version** (read the `coop-cloud.*.version` label from the head's
`compose.yml` — the head checkout already exists), and extend the chain:
1. explicit `UPGRADE_BASE_VERSION` override → use it (unchanged).
2. **last-green canonical, IF its version ≠ head version** → use it (`kind="version"`; the green-verified
primary).
3. **last-green canonical version == head version** → **do NOT skip.** Step back: from the recipe's
published version tags (`warm_reconcile.recipe_tags` + the existing version-ordering used by
`latest_version`), pick the **newest published version STRICTLY OLDER than the head version** and use
it (`kind="version"`). `previous/` still applies version-guarded against whatever base version is
chosen.
4. no canonical at all → existing **main-tip ref** path (use if `main_tip ≠ head_ref`, else skip) —
unchanged.
5. **only if no older published version exists** (genuinely the first version / no predecessor) → skip
with a declared reason (`"base == head and no older published predecessor"`).
Constraints:
- "Strictly older" — exclude any tag equal to the head version; reuse the existing coop-cloud version
ordering, do not hand-roll semver. If the head version isn't in the published tag list (a brand-new
version above all tags), the canonical-≠-head branch already handles it — the step-back only triggers
when canonical == head.
- Preserve the **F1d-2** protections: the chosen older base must actually deploy that *pinned* version
(checkout the tag so the on-disk tree matches), never LATEST.
- Pure resolver change where possible; keep the `ref` and `skip` paths' behavior identical for all other
cases (don't perturb discourse #4 or any version-bump PR).
## 3. Gates
**M1 — implemented + unit-tested.** Resolver reads the head version and implements the chain above.
Unit tests (extend `tests/unit/test_upgrade_base.py`): canonical==head → resolves to the newest-older
published version (assert it's strictly older); canonical≠head → uses canonical (unchanged); no
older-published → declared skip with the new reason; head-version parsed from compose; version ordering
picks the correct strictly-older tag; override + ref + existing-skip paths unchanged. Adversary
cold-verifies from a clean checkout: a same-version PR now upgrades from a **real older version** (base
version < head version, evidenced), not a no-op and not a skip; teeth (a broken head still RED); the
version-bump path (canonical→head) is untouched.
**M2 — proven in real CI.** Demonstrate on the **realistic trigger — the nightly steady state**: a
**cold-on-latest run of an enrolled recipe whose canonical already == latest** (i.e. simulate the
second consecutive nightly with no new version — seed/point the canonical at LATEST, then run
cold-on-latest). Show its upgrade tier **steps back to the previous published version** (evidence
`base_version < latest`, a genuine delta — not a same-version no-op, not a skip). Also cover the
PR form (a non-version-bump PR where head version == canonical) the same way. Confirm a normal
version-bump PR — re-run **discourse #4** or equivalent — is **UNAFFECTED** (canonical, which is older,
→ head). Spot-check ≥1 other enrolled recipe. Fresh Adversary PASS on both milestones → `## DONE`.
## 4. Guardrails
- **Never a same-version no-op, and never a needless skip when an older base exists.** Skip only when
there is genuinely no older published predecessor.
- **The base must be strictly older than the head version.**
- **Don't regress the version-bump path** — the common upgrade-PR case (canonical → head) must behave
exactly as before; discourse #4 must still test the official-image migration.
- Never weaken a test; minimal, well-scoped resolver change; `previous/` stays the last resort.
- Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every commit; abra over a
pseudo-TTY. Recipe mirrors PR-only; never merge.
## 5. Definition of Done
The resolver steps back to the newest-published-version-older-than-head whenever the last-green canonical
equals the head version — never a same-version no-op, never a needless skip when an older base exists;
unit-tested; proven in real CI on a same-version scenario with evidence of a real base<head delta, and the
version-bump path (discourse #4) confirmed unaffected; M1 + M2 fresh Adversary PASSes in REVIEW-samever.md.
Design B (canonical history) recorded in `cc-ci-plan/IDEAS.md`, out of scope here.
@@ -0,0 +1,114 @@
# Phase `settings` — CI-server settings.toml + `SKIP_CANONICALS_FOR_UPGRADE` + release-tag-first fallback
**Mission (operator-specified 2026-06-17):** two cohesive `resolve_upgrade_base` changes for the cc-ci
server:
1. A **minimal, extensible server-level `settings.toml`** with its first value
**`SKIP_CANONICALS_FOR_UPGRADE`** (bool, **default `false`**, `false` on this server). When `true`, the
upgrade tier resolves its base **without canonicals** — codifying that canonicals are an optional
optimization (an operator switch). The file is structured to hold other CI-server configs later; ship
it minimal.
2. An **improved no-canonical fallback (always-on, not flag-gated):** when no canonical is used — none
exists, its promote failed, or the flag is `true` — the base should be the **most recent release TAG on
`main` older than the PR head** (a real published predecessor), with the **raw `main`-tip only as a
further fallback** if the recipe has no prior release, then skip. Today the no-canonical path jumps
straight to `main`-tip, which may be an untagged WIP commit.
These compose: `SKIP_CANONICALS_FOR_UPGRADE=true` always takes the improved release-tag-first fallback.
State files: `STATUS-settings.md`, `BACKLOG-settings.md`, `REVIEW-settings.md`, `JOURNAL-settings.md`. DECISIONS.md shared.
## 1. Background
Canonicals are an optimization + robustness aid for the upgrade base, **not** a requirement: the upgrade
tier already falls back to main-tip when no canonical exists (and the install/backup/restore/custom tiers
never use canonicals). This flag makes that explicit and operator-controllable: a server can run the
upgrade tier purely off main-tip (real predecessor), ignoring the warm-canonical layer entirely — useful
for a deployment that doesn't run the canonical sweep, for debugging, or for a simpler setup.
This server keeps `false` (canonicals on — the optimized/robust path); the flag is the documented escape
hatch.
## 2. Design
**A. A minimal server settings file + loader.**
- A server-level TOML (today cc-ci server config is scattered env vars like `MAX_TESTS`, `CCCI_RUNS_DIR`).
Add a small settings layer that reads a TOML once. Suggested home: a host path the harness reads (e.g.
`/srv/cc-ci/settings.toml`), with a tracked `settings.toml.example` documenting the keys + defaults — OR
extend any existing cc-ci config module if one fits. **Builder: check for an existing cc-ci config
mechanism first and extend it rather than spawn a parallel one.**
- **Defaults baked into the loader** → an absent file, or an absent key, yields the default (so this server
needs no file to behave as today). Stdlib only (`tomllib`). Validate: unknown keys warn-and-ignore;
wrong type errors clearly. Per-server: the file is a host override, not committed config (a tracked
`.example` is fine; the live file is operator-managed and must carry **no secrets** — secrets stay in
sops).
- Keep it **minimal + extensible**: one `[ci]`/`[upgrade]` table with the single key now, shaped so future
CI-server configs slot in without a redesign.
**B. `SKIP_CANONICALS_FOR_UPGRADE` (bool, default `false`).**
- Wire into `resolve_upgrade_base` (`run_recipe_ci.py`): guard the canonical (`version`) branch — when the
flag is `true`, **skip the canonical lookup entirely** and fall through to the **improved no-canonical
fallback (§2.C)**. Effectively: behave as if no canonical exists.
- **Scope it narrowly to the upgrade BASE** (its name says so). Do NOT change canonical *promotion* or the
`--quick` warm-reattach with this flag — those are separate optimizations (a future `SKIP_CANONICAL_SWEEP`
/ `SKIP_QUICK` could gate them; out of scope here — note in DECISIONS).
**C. Improved no-canonical fallback — release tag before main-tip (always-on).** Replace the current
"jump straight to `main`-tip" no-canonical path with:
1. **most recent release TAG with version strictly older than the PR head** — reuse `samever`'s existing
helper (newest published version `< head`, from `recipe_tags`, version-ordered); deploy that tag (a
clean published predecessor) as the base.
2. **raw `main`-tip** (the target-branch tip) — only if the recipe has **no** prior release tag at all.
3. **skip** — if neither (no predecessor / head == main-tip with no older tag).
This applies whenever no canonical is used (none exists, promote failed, or the flag is `true`), so it
improves this server too (false flag, but un-promoted recipes get a real release base instead of a WIP
commit). The unified chain becomes: `canonical (unless flag/none/==head) → newest release tag < head →
main-tip → skip`, with `samever`'s step-back and this fallback sharing the same release-tag helper.
- **Sweep interaction (now better):** with the flag `true`, a cold-on-latest sweep run resolves
base = newest release tag `< latest` = the **previous release** → the upgrade tier still runs a **real**
`previous-release → latest` upgrade (not a skip, not a no-op). So `SKIP_CANONICALS_FOR_UPGRADE` swaps the
base from *last-green canonical* to *latest published predecessor* without losing upgrade coverage. PR
runs likewise get a real release base. This server runs `false`, so the canonical path is unchanged.
## 3. Gates
**M1 — implemented + unit-tested.** Settings loader (TOML, stdlib, defaults, validation, graceful on
absent/malformed file); `SKIP_CANONICALS_FOR_UPGRADE` wired into `resolve_upgrade_base`; the release-tag-first
no-canonical fallback (§2.C) implemented by reusing `samever`'s newest-release-tag-`<`-head helper. Unit
tests for the **full resolution matrix**: flag `false` + canonical present → canonical (unchanged); flag
`false` + no canonical → **newest release tag `< head`** (NOT main-tip); no canonical AND no older release
tag → main-tip; none → skip; flag `true` → canonical skipped → same release-tag-first fallback; absent
file / absent key → default false; malformed file handled. Adversary cold-verifies: **default is false**
(this server byte-for-byte unchanged); the no-canonical fallback returns a real older **release tag**
(main-tip only as last resort); `true` genuinely bypasses the canonical; the loader can't crash the harness
on a bad/absent file; scope is the upgrade base only (promote/`--quick` untouched); the fallback reuses the
`samever` helper (no divergent version-ordering).
**M2 — verified on the server.** The live server reads the settings (file present with
`SKIP_CANONICALS_FOR_UPGRADE = false`, or absent → default false) and the upgrade path **still uses
canonicals — unchanged**. Demonstrate, with evidence: (a) a recipe **without** a canonical resolves its
base to the **newest release tag `< head`** (a real published predecessor), not the raw main-tip; (b)
flipping `SKIP_CANONICALS_FOR_UPGRADE = true` (test/scratch, not permanent) makes a canonical-bearing
recipe ALSO resolve to that release-tag base (canonical bypassed), then restore `false`. Confirm the
harness picks up the file on the server. Fresh Adversary PASS on both milestones → `## DONE`.
## 4. Guardrails
- **Default `false`; this server stays `false`** — the change must be a no-op for current behavior. A
regression to the default upgrade-base path fails the gate.
- **Minimal + extensible** — one setting now, structured for more; do not over-build a config framework.
- **Stdlib only** for the loader; **no secrets** in settings.toml (config only; secrets stay in sops).
- **Narrow scope** — the flag affects only the upgrade-base resolver, not promotion or `--quick`.
- Never weaken a test. Commit author `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push every
commit. If the settings file lives at a host path requiring a deploy, treat it as a host change (loops
may deploy if clean + verify health, else file for the orchestrator).
## 5. Definition of Done
A minimal, extensible CI-server `settings.toml` (+ tracked `.example`, defaults in the loader) is read by
the harness; `SKIP_CANONICALS_FOR_UPGRADE` (default `false`, `false` on this server) is wired into the
upgrade-base resolver; AND the no-canonical fallback now prefers the **most recent release tag `< head`**
(reusing `samever`'s helper) with raw `main`-tip only as a last resort. `false`/absent leaves current
behavior byte-for-byte unchanged; `true` bypasses the canonical into the same release-tag-first fallback.
Unit-tested across the full resolution matrix; verified live on the server (false = unchanged; no-canonical
recipe → release-tag base; true = canonical bypassed, then restored). Scope limited to the upgrade base
(promote/`--quick` separate). M1 + M2 fresh Adversary PASSes in REVIEW-settings.md.
@@ -0,0 +1,127 @@
# Phase `shot` — recipe screenshot audit & repair
**Mission:** every enrolled recipe's CI badge/dashboard card shows a real, representative
screenshot of the deployed app. Iterate through ALL enrolled recipes, audit the screenshot
that their latest runs produced, diagnose every defect, fix it, and prove the fix with a
fresh real-CI run whose PNG is **visually verified** (you can Read a PNG — look at it).
State files for this phase (phase-namespaced, per §6.1 of plan.md):
`STATUS-shot.md`, `BACKLOG-shot.md`, `REVIEW-shot.md`, `JOURNAL-shot.md`. DECISIONS.md shared.
---
## 1. System under audit (file map)
- `runner/harness/screenshot.py` (94 lines) — `capture(domain, out_path, recipe_meta=)`:
Playwright chromium, viewport 1280×800, `NAV_DEADLINE_S = 45`. Default path:
`goto_with_retry(..., wait_until="domcontentloaded")` then `page.screenshot()`.
Optional per-recipe `SCREENSHOT(page, ctx)` hook from recipe_meta (delivered since the
rcust single-loader landed; it was a dead knob before — spec §8 R2).
- `runner/run_recipe_ci.py:~1017-1035` — capture invoked while the app is up, outside the
deploy try/except; double-wrapped so it can NEVER affect the verdict. `screenshot` field
in results.json = relative PNG name iff capture succeeded, else null.
- `runner/harness/card.py:183-208` — summary card embeds the PNG; "no screenshot"
placeholder when null.
- `dashboard/dashboard.py:144-156, 265-275` — grid thumbnail from
`/runs/<n>/screenshot.png`, `has_screenshot` from results.json; `/badge/<recipe>.svg`.
- Artifacts: `/var/lib/cc-ci-runs/<run>/` on the CI server (ssh alias `cc-ci`;
NOTE: no python3 on that host — use shell/grep/stat for remote inspection, or scp the
PNGs/JSON locally to look at them).
- Unit tests: `tests/unit/test_screenshot.py`, `test_card.py`, `test_dashboard.py`.
## 2. Evidence already in hand (orchestrator pre-audit, 2026-06-11, last ~120 runs)
Three classes observed in `/var/lib/cc-ci-runs/*/results.json` + PNG sizes:
1. **Never captured — `screenshot: null` on EVERY run:** `plausible` (runs 122→357, all
null). Root cause unknown — find it (capture failing? step never reached on its run
shape? exception swallowed by design — check run logs for the
`screenshot: capture failed` / `produced no file` prints).
2. **Suspected blank frames — implausibly small PNGs, byte-identical sizes across
different apps:** `immich` 4801B (every run), `lasuite-meet` 4801B, `n8n` sometimes
4801B (other runs 29-30KB — flaky), `cryptpad` 4802B. A 1280×800 PNG at ~4.8KB is
near-certainly a solid white/blank page: SPA shells where `domcontentloaded` fires
before the JS app paints. Borderline, verify visually: `lasuite-docs` ~5.9KB,
`lasuite-drive` ~5.9KB, `keycloak` ~8.7KB (might be a genuine sparse login page).
3. **Healthy (sanity reference):** ghost 444KB, mattermost-lts 242KB, hedgedoc 132KB,
discourse 67KB, custom-html 35KB, mailu 34KB, matrix-synapse 33KB, uptime-kuma 31KB,
custom-html-tiny 13KB.
Recipe enumeration is YOURS to make authoritative: every `tests/<recipe>/recipe_meta.py`
directory EXCEPT the harness fixtures (`_generic`, `regression`, `concurrency`,
`custom-html-bkp-bad`, `custom-html-rst-bad`). Expected real set ≈ bluesky-pds, cryptpad,
custom-html, custom-html-tiny, discourse, ghost, hedgedoc, immich, keycloak, lasuite-docs,
lasuite-drive, lasuite-meet, mailu, matrix-synapse, mattermost-lts, mumble, n8n, plausible,
uptime-kuma. Some recipes (e.g. mumble — a voice server) may have no meaningful web UI:
a **justified N/A** (documented in the matrix, Adversary-agreed) is an acceptable outcome
for those; the dashboard placeholder is then correct behavior, not a defect.
## 3. Work plan
**P1 — Audit matrix.** For every enrolled recipe, record in `BACKLOG-shot.md`: latest
run(s) with artifacts; screenshot null/present; PNG size; **visual content** (Read the
PNG: app UI / login page / blank / error page); `has_screenshot` as the dashboard sees it.
Pull PNGs locally (scp) and actually look at each one. Classify: OK / BLANK / NULL /
ERROR-PAGE / N-A-candidate.
**P2 — Diagnose.** Per defective recipe, find the root cause, not the symptom. Expected
buckets: (a) SPA paint race — needs a smarter default wait; (b) plausible's null — step
not reached or capture raising, find which from run logs; (c) app-specific (redirect to
an external/IdP page, splash screen, etc.) — needs a per-recipe `SCREENSHOT` hook.
**P3 — Fix.** Preference order:
1. **Harness default improvement** (fixes whole classes): e.g. after `domcontentloaded`,
wait briefly for network-idle or first rendered content, with a blank-detection retry
(a captured PNG under a few KB → one retry with a stronger wait) — all WITHIN the
existing `NAV_DEADLINE_S=45` budget. Do not balloon run times: the screenshot step's
total worst-case must stay ≤ ~60s.
2. **Per-recipe `SCREENSHOT(page, ctx)` hooks** in `tests/<recipe>/recipe_meta.py` only
where the default genuinely can't work (uniform ctx signature per rcust P3).
3. results.json/card/dashboard plumbing fixes if the defect is downstream of capture.
Unit tests accompany harness changes (`tests/unit/test_screenshot.py`).
**P4 — Prove.** Fresh real-CI run per fixed recipe; verify the new artifact: PNG exists,
visually shows the app (login page fine; blank/error not), card + dashboard render it.
At least 2 of the proof runs via the drone `!testme` path. Healthy-class recipes (class 3
above) need no new run — cite the existing artifact + your visual check of it.
## 4. Gates (Builder claims via `claim(shot): ...` commit; Adversary verdicts in REVIEW-shot.md)
**M1 — Audit + diagnosis complete.** The full matrix exists (every enrolled recipe, no
omissions), every non-OK entry has a root-cause diagnosis with evidence (log lines, PNG
inspection), N/A candidates argued. Adversary independently spot-checks ≥5 recipes'
artifacts (including at least plausible + one 4801B case) and verifies the matrix matches
reality.
**M2 — All screenshots working.** Every enrolled recipe is OK or Adversary-agreed N/A:
fixes merged to main, fresh proof runs done (≥2 via !testme), and the Adversary has
**looked at every final PNG** (Read tool) and confirms it is a real, representative,
credential-free view of the app, and that the dashboard/card shows it. Verdicts, levels,
and run durations unaffected (compare runtimes pre/post; screenshot step ≤ ~60s worst
case). `## DONE` in STATUS-shot.md only after a fresh Adversary M2 PASS.
## 5. Guardrails (binding)
- **Cosmetics never block (R7 is law):** the screenshot path stays best-effort end to
end — it must NEVER affect a verdict, fail a run, or hang past its deadline. Any change
that could flip a verdict on screenshot failure is an automatic Adversary FAIL.
- **Secret-safety (cardinal):** never capture a page displaying generated credentials
(install wizards with admin passwords, secrets pages). Default = landing page. Any new
`SCREENSHOT` hook must keep this guarantee and the Adversary must check it explicitly.
- **No gate weakening anywhere** — tests/assertions in the suite are untouchable except
the screenshot-specific unit tests you extend.
- Changes live in the cc-ci repo only (harness + tests/<recipe>/). Never push recipe
mirror repos' main / never merge their PRs.
- Real-CI etiquette: ≤2-3 concurrent live deploys; NEVER git-checkout
`~/.abra/recipes/<recipe>` on cc-ci while its build runs; tear down every dev deploy on
every exit path; never re-print secrets/tokens into logs or commits.
- The CI host has no python3 in default PATH for remote one-liners — use shell, or run
python via the harness venv (`cc-ci-run`) on the host, or copy files local.
- Commit author: `autonomic-bot <autonomic-bot@noreply.git.autonomic.zone>`; push to
git.autonomic.zone right after every commit.
## 6. Definition of Done
All enrolled recipes' CI cards show verified-real screenshots (or documented N/A),
M1 + M2 Adversary-PASSed fresh, harness changes unit-tested, no verdict/runtime
regressions, all work merged to cc-ci main and pushed.
@@ -0,0 +1,174 @@
# cc-ci Phase 1b — Review & lint pass (Autonomous Build Plan)
**Status:** QUEUED — a **bounded** pass that runs after Phase 1 **and Phase 1c**
(`plan-phase1c-full-reproducibility.md`), and **before** Phase 2 (`plan-phase2-recipe-tests.md`). It
runs *after* 1c on purpose: the review/lint + full D1–D10 re-verification then covers the final,
refactored state (the `cc-ci-secrets` split, cert-in-sops, the genuine D8 live rebuild).
**Transition:** **manual** (operator kicks it off).
**Builds on:** the complete post-1c codebase (flake/modules, `runner/` + harness, the comment-bridge,
dashboard, scripts, the first recipes' tests, the `cc-ci-secrets` split, docs).
**Owner agents:** same Builder + Adversary loops (`plan.md` §6/§7). Here the Adversary also acts as
**white-box reviewer** (reads the code, not just black-box behavior).
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase1b-review-lint.md`
---
## 0. Why this phase (and why it's bounded)
Before scaling to ~18 recipes (Phase 2), clean and harden the foundation built in Phase 1 — it's far
cheaper to fix the harness/modules now than after every recipe copies their patterns. This is a
**one-time, bounded pass**, not an open-ended loop. Two distinct workstreams that go to two places,
to avoid bikeshedding:
1. **Style & hygiene → deterministic tooling** (formatters/linters in CI). No judgment calls, no
churn, enforceable going forward.
2. **Code health a linter can't judge → a white-box review checklist with teeth** (§3) — anchored to
plan-relevant invariants, *not* taste. Blocking items get fixed; the rest are advisory.
Discipline: **good-enough + enforceable**, not gold-plating. Don't reopen settled design; don't
weaken any test in the name of "cleanliness." When in doubt, lint it deterministically or leave it.
---
## 1. Definition of Done (Phase 1b exit condition)
Terminates when every item holds **and the Adversary/reviewer has independently confirmed** (logged
in `REVIEW.md`):
- [ ] **RL1 — Lint/format tooling in place + green.** Formatters + linters are added to the repo (a
`lint` entrypoint + a Nix devshell) and wired as a **stage in cc-ci's own `.drone.yml`** so
future commits stay clean. The whole Phase-1 codebase **passes** them. Tooling (defaults; settle
in `DECISIONS.md`):
- **Nix:** `alejandra` (or `nixpkgs-fmt`) format · `statix` (lints) · `deadnix` (dead code).
- **Python** (`runner/`, harness, `bridge/`, `tests/`): `ruff` (lint + format).
- **Shell:** `shellcheck` + `shfmt`.
- **(optional) YAML:** `yamllint` for `.drone.yml`/compose.
- [ ] **RL2 — Review checklist run, blocking items fixed.** The white-box checklist (§3) has been run
over the codebase; every **blocking** finding is fixed; every **advisory** finding is either
fixed or moved to `BACKLOG.md`/`IDEAS.md` as `[idea]` with a one-line rationale. Findings +
resolutions recorded in `REVIEW.md`.
- [ ] **RL3 — Full Phase-1 re-verification (the final gate).** This is the **last step before 1b is
marked DONE**, performed *after* all lint/review findings (RL1+RL2) have been responded to and
resolved. The Adversary **independently re-verifies every Phase-1 Definition-of-Done item
D1–D10 from a cold start** — re-running each acceptance check itself, to the **same bar as
Phase 1's own DONE** (fresh PASS + evidence + timestamps logged in `REVIEW.md` within 24h). 1b
cannot be DONE until **all of D1–D10 are re-confirmed green post-cleanup** and the Adversary
confirms no test/assertion was softened, skipped, or otherwise regressed by the cleanup.
- [ ] **RL4 — Documented.** `docs/` notes how to run lint/format locally and that CI enforces it; any
accepted deviations from the review checklist are in `DECISIONS.md`.
When RL1–RL4 hold and are confirmed, write `## DONE` to Phase-1b `STATUS.md`.
---
## 2. Method
1. **Tooling first.** Add the formatters/linters + a `lint` entrypoint + devshell; run format, then
fix lint findings. Wire the `.drone.yml` lint stage so it's enforced from here on. (Auto-fixable
style should just be auto-fixed — don't deliberate over it.)
2. **Then the review checklist (§3).** Read the code against the checklist; classify each finding
**blocking** vs **advisory**; fix blocking, triage advisory.
3. **Re-verify everything last.** Once all fixes have landed, the Adversary re-runs the **entire**
Phase-1 D1–D10 acceptance suite from a cold start (RL3) — this is the final gate; cleanup must
regress nothing. Order matters: tooling → review responses/fixes → *then* full re-verification.
4. **Bound it.** Cap iterations; this is a pass, not a rewrite. Record dead-ends/deviations and stop.
---
## 3. The white-box review checklist (teeth, not taste)
Blocking unless noted; these are *plan-relevant invariants visible only by reading code*:
- **Tests are real (blocking).** Every recipe/harness test asserts actual app state — not
health-only, not `skip`/`xfail`, not assertions that can't fail. (Pre-empts Phase-2 §7.1 at the
foundation.)
- **Harness is DRY (blocking-ish).** Recipe-specific quirks live in the **shared harness**, not
copy-pasted per recipe (the M6.5 "no harness surgery / no one-off hacks" rule) — so 18 recipes
don't multiply the mess.
- **Server state is Nix-declared & idempotent (blocking).** Bring-up is declarative idempotent
reconciliation (the `swarm-init`/`deploy-proxy` oneshot pattern, §9) — no imperative drift, no
run-once sentinels, no manual post-rebuild steps in `install.md`.
- **No footguns (blocking).** No bare `sleep` for readiness (use polling); correct `--chaos` usage;
no hardcoded versions/domains that break across upstream versions; teardown in `try/finally`;
per-run secrets reused across stages (not regenerated).
- **No secrets in code or committed files (blocking).** Grep + read for tokens/passwords/keys in
source, configs, `.drone.yml`, fixtures (complements the Adversary's behavioral leak test).
- **Architecture matches the plan (advisory→blocking on real drift).** Layout/》 modules follow
`plan.md` §3; the trigger is poll-primary + optional manual webhook (§4.1); Traefik is the
coop-cloud recipe (§4.2); deviations are recorded in `DECISIONS.md` (not silent).
- **Log redaction is real (blocking).** The log/dashboard pipeline scrubs secrets before publish.
- **Readability & error handling (advisory).** Clear names, sensible structure, errors surfaced not
swallowed, dead code removed — advisory; auto-fixable parts belong to the linters, not debate.
- **Docs accurate (advisory).** `install.md` reproduces from scratch; `enroll-recipe.md` matches the
real enroll flow.
---
## 4. Milestones (bounded)
- **W0 — Tooling + format.** Linters/formatters + `lint` entrypoint + devshell added; codebase
auto-formatted; `.drone.yml` lint stage wired and green. *Accept:* `lint` passes in CI from a clean
checkout.
- **W1 — Review + fixes.** Checklist (§3) run; blocking findings fixed; advisory triaged. *Accept:*
`REVIEW.md` lists findings + resolutions; no blocking item open.
- **W2 — Full re-verification + document.** *After* W0+W1 fixes land, the Adversary re-verifies **all
of D1–D10** cold (RL3) and docs/deviations are recorded. *Accept:* every Phase-1 D1–D10 item has a
fresh post-cleanup PASS + evidence in `REVIEW.md` (nothing weakened); then flip Phase-1b
`STATUS.md` to `## DONE`.
---
## 5. Guardrails
- **Never weaken a test to satisfy a lint/review nit** (the cardinal rule still wins).
- **Style → tooling, judgment → checklist.** Don't spend agent effort (or loop iterations) on what a
formatter/linter settles deterministically; don't let the review drift into subjective taste.
- **Bounded.** This is a pass, not a refactor project — fix invariants + enforce linting, then stop;
bigger improvements go to `IDEAS.md`, not this phase.
- **Don't reopen settled design.** Architecture decisions from Phase 1 stand unless there's real
drift from the plan; record, don't relitigate.
---
## 6. Open decisions (log in DECISIONS.md)
- Exact formatter choices (alejandra vs nixpkgs-fmt; ruff-format vs black) and lint strictness.
- Whether to add Python **type-checking** (mypy/pyright) now or defer to `IDEAS.md`.
- The precise **blocking vs advisory** split for the checklist.
- Whether the `.drone.yml` lint stage should **fail** the build or just warn initially.
---
## 7. Operator review items (added 2026-05-27) — repo layout (do in this 1b pass)
Two structural-review items from the operator. Both are **blocking** for 1b. Apply them as part of
this pass, then re-verify (RL3 covers the re-verification). **Mind the coordination caveats — these
touch the live flake build and the running multi-agent machinery.**
### RL5 — Consolidate all Nix-code folders under a root `nix/`
- Move the folders that contain `.nix` code — **`modules/` and `hosts/`** — to **`nix/modules/` and
`nix/hosts/`**. (Add future Nix dirs under `nix/` too.)
- **Keep `flake.nix` / `flake.lock` at the repo root** (entry point) so the build ref is unchanged
(`docs/install.md`'s `nixos-rebuild switch --flake 'git+file://…?submodules=1#cc-ci'` stays valid).
Just update the flake's internal paths (`./modules` → `./nix/modules`, `./hosts` → `./nix/hosts`)
and any `imports`/`scripts`/`.drone.yml` references.
- **Re-verify after the move:** the byte-identical clean-room result is the bar. The toplevel store
hash *will* change (paths differ) — that's fine; what must hold is that a fresh recursive clone
still rebuilds **byte-identical to the running system** and the Adversary re-confirms it cold
(folds into RL3). Update `docs/architecture.md` to describe the `nix/` layout.
### RL6 — Move uppercase multi-agent-protocol files into `machine-docs/`
- Move the uppercase protocol files — **`STATUS*.md`, `REVIEW*.md`, `JOURNAL*.md`, `BACKLOG*.md`,
`DECISIONS.md`** — into a root **`machine-docs/`** folder. **`README.md` stays in the repo root**
(operator decision, 2026-05-27) — it is the human-facing repo readme, not a protocol file; do
**not** move it into `machine-docs/`.
- **Update every reference** to the new paths: the `cc-ci-plan/` plans (this file, `plan.md`,
`plan-phase1c-*`, `README.md`, `kickoff.md`, `test-e2e-testme-acceptance.md`), `AGENTS.md`,
`.drone.yml`, `scripts/`, and any in-repo doc that points at `STATUS.md`/`REVIEW.md`/etc.
- **⚠ COORDINATION CAVEAT (do not move these unilaterally mid-run):** the live **watchdog**
(`cc-ci-plan/launch.sh`, the orchestrator's file) reads `STATUS-<id>.md` and `REVIEW-<id>.md` at
the **repo root** to drive handoff pings + the 1c→1b auto-transition. Moving them breaks the
running watchdog until `launch.sh` is updated to the `machine-docs/` paths and the watchdog is
restarted. **So sequence it with the orchestrator:** the orchestrator updates `launch.sh`'s
`PHASES_SPEC`/path logic and restarts the watchdog **in lockstep** with the loops' `git mv`.
Safest to do this **near the end of 1b** (or as its final step), not while a phase transition is
pending. Flag the orchestrator when ready and it will handle `launch.sh` + the watchdog restart.
@@ -0,0 +1,196 @@
# cc-ci Phase 1c — Full git reproducibility + genuine D8 live rebuild (Autonomous Build Plan)
**Status:** QUEUED — runs after Phase 1 (`plan.md`) and **before Phase 1b** (review/lint), so the
review/lint pass covers this refactor and its final cold re-verification proves the genuine
(post-1c) D8. **Manual** transition. **Driven by the Builder + Adversary loops** (same protocol as `plan.md` §6/§6.1/§7) —
the orchestrator does NOT do this; the loops do, and the Adversary independently re-proves it cold.
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase1c-full-reproducibility.md`
---
## 0. Why this phase
Phase-1 D8 was marked PASS with the throwaway-VM **live rebuild "documented infeasible by design
(sops host-key binding + operator DNS/cert)."** That justification doesn't hold up:
- **sops host-key binding** is defeated by the project's **own master recovery age key**
(`/srv/cc-ci/.sops/master-age.txt`, a sops recipient created *"for re-keying if cc-ci is lost"*) —
a fresh host can decrypt the repo's secrets with it. So a new-host rebuild is *not* infeasible.
- **operator DNS/cert** is a *precondition*, not a rebuild blocker — it only gates the full
end-to-end HTTPS path, not "a blank host + the repo boots into the declared system."
- Incus is available, and the rate-limit premise that originally deferred the test was obsolete
(D10 passed without registry creds). The Builder itself flagged the rebuild as *feasible now* and
refused to self-certify; the bar then slipped to "infeasible."
This phase does two connected things: **(A)** make the VM **fully reproducible from git, including
all secrets** (move the wildcard cert and everything else into sops-in-git, in a separate private
`cc-ci-secrets` repo), and **(B)** actually perform and verify the **throwaway-VM live rebuild**, closing
D8 honestly. The byte-identical-closure evidence from Phase 1 stays valid as the *static* half of D8;
this adds the *live* half it was missing.
---
## 1. Mission
A blank NixOS VM, given only **(1)** the two git repos (base `cc-ci` + private `cc-ci-secrets`), **(2)** the
single bootstrap age key, and **(3)** the external DNS/gateway already pointing at it, becomes a
working cc-ci via **`nixos-rebuild switch`** with **no undocumented manual steps** — secrets and the
wildcard cert included, decrypted from git. Proven on a real throwaway VM by the loops.
---
## 2. The reproducibility model (target architecture)
**Split only the *secrets* into their own repo. The base stays one well-parameterized repo.** The
boundary is *secrecy*, not modularity: secrets get a separate private repo (an extra access-control
layer); instance-specific **non-secret** vars (domain, gateway/DNS facts) stay in the base as plain,
changeable parameters — another admin can repoint cc-ci by editing them, no second config repo needed.
- **`cc-ci` (base — one repo, well-parameterized):** `flake.nix`, modules, `runner/`, `tests/`,
`docs/`, **and** the instance config as parameters/defaults (e.g. `DOMAIN = "ci.commoninternet.net"`,
gateway/DNS facts, sops recipients). Instance *config* lives here; only *secret material* is external.
Keep it well-parameterized so changing the domain/recipients is a one-line edit, not a fork.
- **`cc-ci-secrets` (private, `recipe-maintainers/cc-ci-secrets`):** holds **only** the sops-encrypted
secret material — `secrets/secrets.yaml` (**wildcard cert + key**, Drone OAuth client_id/secret +
RPC secret, webhook HMAC, registry creds if any, app/infra secrets) + `.sops.yaml`. **No code, no
config logic** — just encrypted secrets, as a separate security layer with its own access control.
- **Linkage (default = flake input):** base `flake.nix` has
`inputs.secrets.url = "git+https://git.autonomic.zone/recipe-maintainers/cc-ci-secrets"`
(private; fetched via the bot token / a read deploy key); sops-nix reads `secrets/secrets.yaml` from
it. *Alternative:* a git **submodule** at `cc-ci/secrets/`. Record the choice in `DECISIONS.md`;
flake input is the recommended default.
- **sops-nix wiring:** `sops.defaultSopsFile` → the `cc-ci-secrets` `secrets.yaml`;
`sops.age.sshKeyPaths` = host key + the recovery recipient. The **wildcard cert/key are sops
secrets** decrypted at activation to `/var/lib/ci-certs/live/{fullchain.pem,privkey.pem}` and fed
into the Traefik recipe's `ssl_cert`/`ssl_key` swarm secrets — **no out-of-band cert file.**
- **The one irreducible out-of-band secret:** the **age private key** that unlocks the secrets (the
host key, or the provisioned recovery key) — it cannot live in the repo it decrypts. This is the
*only* permitted "not in git" secret, provisioned to the host at creation.
- **Still external (not the VM's git, by nature):** the DNS records + the TLS-passthrough gateway
(network infra) — documented as preconditions. (IaC for those is out of scope — see §7.)
- **Token discipline preserved:** only the cert *artifact* enters git (encrypted, in `cc-ci-secrets`);
the **Gandi DNS token never enters any repo or the agent**. Renewal = operator re-issues the cert
out-of-band, then commits the new sops-encrypted cert to `cc-ci-secrets` (versioned, reproducible).
---
## 3. Definition of Done
Terminates only when every item holds **and the Adversary has independently re-verified each within
24h, from a cold start** (logged in `REVIEW.md`):
- [ ] **C1 — Secrets-repo split.** A separate private `cc-ci-secrets` repo holds **only** the
sops-encrypted secrets (+ `.sops.yaml`), consumed by the base via a flake input. The base
`cc-ci` stays one well-parameterized repo — instance vars (domain, gateway, recipients) remain
changeable parameters in the base, **not** moved out (only secrets are external).
`nixosConfigurations.cc-ci` still builds byte-identically to the running system.
- [ ] **C2 — Cert in git.** The wildcard cert+key are sops secrets in `cc-ci-secrets`, decrypted
at activation to the cert path + Traefik secret; the prior "operator drops a cert file" step is
gone. Verified: a rebuild serves valid TLS from the git-sourced cert.
- [ ] **C3 — All secrets in git (one exception).** Every infra/app secret (cert, Drone OAuth/RPC,
webhook HMAC, registry creds, host age recipients) is sops-encrypted in git. The **only**
out-of-band secret is the bootstrap age key — documented precisely, nothing else.
- [ ] **C4 — Genuine throwaway-VM live rebuild.** On a blank NixOS VM (Incus, `terraform-ci`),
provisioned with *only* the bootstrap age key, the loops `git clone` base+secrets and run
`nixos-rebuild switch`; the system activates and the reconcile oneshots converge
(swarm/proxy/drone/bridge/dashboard), all secrets incl. the cert decrypt, with **no manual step
not in `docs/install.md`**.
**The true proof is a clean-room repeat (C4 done right):** the Adversary **deletes** any
existing throwaway VM, **creates a brand-new blank VM via Incus**, and runs the *entire* install
from scratch (clone base+secrets → provision age key → `nixos-rebuild switch` → everything comes
up) — proving reproducibility on a genuinely fresh machine, with **no residue** from the
Builder's setup attempt masking a gap. Done **cold** by the Adversary, with logged evidence
(VM id, the exact commands from `docs/install.md`, convergence + TLS-from-git-cert proof).
- [ ] **C5 — Honest D8.** The D8 evidence is rewritten: byte-identical closure (static) **plus** the
live throwaway-VM rebuild (dynamic). The "infeasible by design" wording is removed. If any
single aspect genuinely can't be reproduced, it is a narrowly-scoped, Adversary-signed-off
limitation with the maximal tested subset (bar per Phase-1b §7.1 / Adversary mandate) — not a
blanket "infeasible."
- [ ] **C6 — Resource fit + cleanup.** `cc-nix-test` resized **6 GB→4 GB** and the throwaway VM
created at **4 GB**, within the **~12 GB running-RAM guideline** (cc-nix-test 4 + lichen-staging 4
+ throwaway 4 = 12 ≤ 16 GB physical on b1; the guideline is doc-only, not an enforced project
limit). The throwaway VM is **destroyed** after the test (no leftover). Final `cc-nix-test`
sizing decided and applied (keep 4 GB, restore to 6 GB, or promote the rebuilt VM — record in
`DECISIONS.md`).
- [ ] **C7 — Docs.** `docs/install.md`, `docs/secrets.md`, `architecture.md`, and the main plan's
cert/secret references (§1.5/§4.0/§4.4) updated to the new model: clone base+instance + provision
the age key + (external) DNS/gateway → one `nixos-rebuild switch`. A new engineer can stand up a
fresh instance from the docs.
When C1–C7 hold and are Adversary-verified, write `## DONE` to Phase-1c `STATUS.md`.
---
## 4. Incus capability (granted for this phase only)
The loops normally only `ssh cc-ci`. For 1c they MAY drive Incus on **b1** (resize `cc-nix-test`;
create/destroy ONE throwaway VM in `terraform-ci`), using the mTLS certs at
`/srv/incus-terraform-nix-vm-creator/terraform-secrets/` (b1 is reachable directly from the VM —
direct tailnet peer, no proxy) — see the incus skill (`/srv/incus-terraform-nix-vm-creator/skills/incus-terraform/SKILL.md`)
and [[cc-ci-vm-incus]]. Guardrails: only `terraform-ci`; keep total running RAM within the **~12 GB
guideline** (doc-only — terraform-ci has no enforced `limits.memory`; b1 is 16 GB physical) — hence
`cc-nix-test`→4 GB + throwaway 4 GB + lichen-staging 4 GB = 12 GB; **destroy the throwaway VM when
done**; never touch other projects/instances; live-memory changes need stop→set→start (hotplug times
out — see memory).
---
## 5. Method (ordered; each milestone ends with an Adversary gate)
1. **W1 — Headroom.** Resize `cc-nix-test` 6 GB→**4 GB** (stop→set→start) so a **4 GB** throwaway VM
fits within the ~12 GB running guideline (4 + lichen 4 + throwaway 4). *Accept:* b1 has room;
cc-nix-test healthy at 4 GB (avoid heavy recipe CI during 1c). *(Final sizing decided in W6.)*
2. **W2 — Secrets repo + cert into git.** Create the private `cc-ci-secrets` repo; move **all secrets**
into sops there — including the **wildcard cert+key** (read from the current `/var/lib/ci-certs/live`)
and the existing `secrets/secrets.yaml` contents; keep instance vars parameterized in the base;
wire the base flake to consume `cc-ci-secrets` (flake input). *Accept:* `nixos-rebuild build` of the
restructured config is **byte-identical** to the running system (zero drift), and `cc-nix-test`
`nixos-rebuild switch`es cleanly onto the new structure with TLS still served from the git cert.
3. **W3 — Throwaway VM.** Create a blank NixOS VM in `terraform-ci` (the incus-base image), sized
**4 GB**. *Accept:* VM reachable; bootstrap age key provisioned by the documented mechanism only.
4. **W4 — Reproducible live rebuild.** On the throwaway VM: clone base+instance, `nixos-rebuild
switch`, watch oneshots converge, secrets+cert decrypt. *Accept:* system fully up with **no step
outside `docs/install.md`**; capture evidence.
5. **W5 — Adversary clean-room proof + honest D8.** The Adversary **deletes** the Builder's throwaway
VM, **creates a brand-new blank VM**, and runs the full install from scratch per `docs/install.md`
(clone base+secrets → provision age key → `nixos-rebuild switch` → all up) — a genuinely fresh
machine, no residue. Then rewrites the D8 evidence (static byte-identical + this live clean-room
rebuild), removing "infeasible by design." *Accept:* Adversary logs a real D8 live-rebuild PASS on
a freshly-created VM (or a narrow, signed-off limitation per §3 C5).
6. **W6 — Cleanup + docs + final sizing.** Destroy the throwaway VM; update all docs (C7); decide and
apply final `cc-nix-test` sizing. *Accept:* no leftover VM/secret leak; docs match; flip Phase-1c
`STATUS.md` to `## DONE`.
---
## 6. Guardrails (inherit Phase 1 §9 + Phase 1b §7.1 / Adversary mandate)
- **Don't fake the rebuild.** "Infeasible/can't reproduce" is allowed only for a true,
narrowly-scoped blocker with the maximal tested subset and **Adversary sign-off** — the host-key
and DNS/cert reasons are explicitly *not* valid (the recovery key + the cert-in-git fix remove them).
- **Exactly one out-of-band secret.** The bootstrap age key. Everything else in git, encrypted. If
the loops find another secret that "has to" be out-of-band, that's a finding to design away, not
accept.
- **Gandi token stays out of repo/agent** — only the cert artifact is committed (encrypted). Renewal
is operator-issues-then-commits.
- **No plaintext secret leaks into the base (or the store).** Instance *vars* (domain, gateway) may
live in the base as parameters — that's fine; what must NOT leak is any *secret* (cert/keys/tokens):
those stay encrypted in `cc-ci-secrets`. The Adversary greps the base + the Nix store for plaintext
secret material.
- **Incus guardrails** (§4): terraform-ci only, respect the RAM cap, destroy the throwaway VM, don't
touch other instances.
- **No weakened tests / no drift** — the restructured config must remain byte-identical to running
(zero drift) and all of D1–D10 must still hold after the refactor.
---
## 7. Open decisions (log in DECISIONS.md)
- **Flake input vs git submodule** for the `cc-ci-secrets` repo (default: flake input).
- **Bootstrap-key provisioning** for a new VM: provision the off-box recovery age key to the host
(decrypt as-is) vs generate the new host's key + re-encrypt secrets to it. (Recovery key is
simpler for a clone; per-host re-encrypt is cleaner long-term.)
- **Final `cc-nix-test` sizing** after the test: restore to 6 GB, or **promote the freshly-rebuilt
reproducible VM** to be the canonical cc-ci and retire the old one.
- **DNS/gateway as IaC** (terraform for the Gandi records + the gateway) — likely a separate future
item ([[IDEAS]]), out of 1c scope; 1c keeps them as documented external preconditions.
- How the loops fetch the private `cc-ci-secrets` repo during rebuild (bot token-in-URL vs a read
deploy key) — it's private under `recipe-maintainers` (bot is admin).
@@ -0,0 +1,243 @@
# cc-ci Phase 1d — Generic test suite + layered recipe overlays (Autonomous Build Plan)
**Status:** QUEUED — runs **after Phase 1b** (`plan-phase1b-review-lint.md`) and **before Phase 2**
(`plan-phase2-recipe-tests.md`). It is the **test-architecture foundation** Phase 2 builds on, so it
must precede it.
**Transition:** **manual** (operator kicks it off at the post-1b check-in).
**Builds on:** the post-1b codebase (the runner/harness, `.drone.yml`, the comment-bridge, the proof
recipes, the `nix/` + `machine-docs/` layout from 1b RL5/RL6).
**Owner agents:** same Builder + Adversary loops (`plan.md` §6/§7); Adversary cold-verifies.
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase1d-generic-test-suite.md`
**Phase order:** 1c → 1b → **1d** → 2 → 2b → 3.
---
## 0. Why this phase
Today a recipe only gets tested if someone has authored tests for it. That doesn't scale to ~18+
recipes and gives nothing for a brand-new recipe. The operator's model (2026-05-27): **every recipe
gets a generic lifecycle test suite for free**, and recipe-specific tests *layer on top* rather than
being the only thing that runs. This makes `!testme` meaningful on **any** recipe immediately, turns
Phase 2 into "add overlays where they add value" instead of "write everything from scratch," and
gives Phase 3 a natural basis for a YunoHost-style **level** (how many tiers pass).
Core principle: **the generic is the default for each lifecycle op; a recipe's own `test_<op>.py`
may override *or* extend that default.** The exact additive-vs-override mechanism is the **Builder's
design call** (operator, 2026-05-27: override — e.g. a present `test_install.py` *replaces* the
generic install assertions — is a perfectly good option; additive is fine too; could even be
per-recipe opt-in). What's **fixed** and non-negotiable: (1) when a recipe defines **no** test for an
op, **the generic runs** (so any recipe is testable with zero config); (2) the harness owns a
**single shared deployment** that generic + recipe assertions reuse — **no redeploy** (§2.2); (3)
custom (non-lifecycle) tests are opt-in.
> **SUPERSEDED (2026-05-28) by Phase 1e HC3** (`plan-phase1e-harness-corrections.md`): the override
> default is replaced — the **generic now runs by default *alongside* an overlay (additive)**,
> skipped only via an explicit opt-out. Also: repo-local PR code is gated to approved recipes (HC2),
> and the upgrade tier targets the PR head (HC1). Read 1e for the current behavior.
---
## 1. Definition of Done (Phase 1d exit condition)
Terminates when every item holds **and the Adversary has independently cold-verified** (logged in
`machine-docs/REVIEW-1d.md`):
- [ ] **DG1 — Generic INSTALL test.** A recipe-agnostic install test exists that, given only a
recipe name and **zero** recipe-specific config, does `abra app new` (sane defaults / auto
secrets) → `deploy` → polls to converged (all services running/healthy, no bare `sleep`) →
asserts the app is **actually serving** (real HTTP(S) response on its
`<run>.ci.commoninternet.net` domain through Traefik — **not** a Traefik 404/default cert, not
health-only). Demonstrated **green** on ≥1 simple recipe (e.g. `custom-html`) that has **no**
cc-ci or repo-local tests.
- [ ] **DG2 — Generic UPGRADE test.** Deploy the **previous published version** (the last release
*before* the code under test), then **upgrade to the code under test (PR head) via
`abra app deploy --chaos`** (chaos = the current checkout) — i.e. previous-release → PR-head,
not previous → newest-published-tag. Assert services reconverge and the app still serves.
**OPERATOR CORRECTION (2026-05-28):** the current 1d impl upgrades to the newest *published tag*
and (because deploying the prev tag re-checks-out the recipe) never deploys the PR head — so a
recipe PR's actual changes aren't exercised by the upgrade path. Fix: after deploying prev,
**restore the PR-head checkout** (re-checkout the PR ref / re-snapshot) and `deploy --chaos` to
it as the upgrade target. The "deployment actually moved" assertion (`do_upgrade`) still
applies, but adapt it for prev→PR-head (a PR may not bump the version label — also accept an
image/config change, or assert the running config now matches the PR head). For a non-PR
`!testme`, "current checkout" = the catalogue current, so upgrade tests prev→current. (Data-
continuity assertions remain recipe overlays — see §2.1.)
- [ ] **DG3 — Generic BACKUP + RESTORE tests.** For backup-capable recipes (declare backupbot /
`abra app backup` support): run backup → assert a snapshot artifact is produced; then restore →
assert restore completes and the app is healthy after. For recipes that declare **no** backup
config, backup/restore are cleanly **N/A (skipped)** — *not* a failure.
- [ ] **DG4 — Layering (override-or-extend; generic is the default).** The harness composes a
recipe's run from the generic default per op, **overridden or extended** by the recipe's
`test_install.py` / `test_upgrade.py` / `test_backup.py` / `test_restore.py` when present (in
cc-ci's tests dir **or** repo-local in the recipe's `tests/`) — the additive-vs-override
mechanism is the Builder's design choice, recorded in `machine-docs/DECISIONS.md`. **Invariant:
if a recipe defines no test for an op, the generic runs.** Arbitrary **custom** `test_*.py` run
**only if defined**. Discovery + cc-ci-vs-repo-local precedence is
implemented and settled in `machine-docs/DECISIONS.md`.
- [ ] **DG4.1 — Overlays reuse the deployment (no redeploy).** Overlay + custom assertions run
against the **same live deployment** the generic tier brought up — **one deploy per run, one
teardown** (§2.2), lifecycle ops mutating it in place. Verified: adding an overlay to a recipe
causes **no** extra `abra app new/deploy/undeploy` beyond the shared run (assert via
deploy-count / harness logs). Re-provisioning only where an op semantically demands it, and
then explicitly.
- [ ] **DG5 — Custom install-steps hook (with the "generic-anyway" rule).** The harness supports
**defined** per-recipe extra install steps (cc-ci or repo-local) that run before/around the
generic install. A recipe with **no** customization still **attempts the generic suite**.
Proven both ways: (a) a recipe needing a custom step **fails the generic install as expected**
when the step is absent; (b) the **same** recipe **passes** once the custom step is added —
demonstrating the hook + the graceful-generic-failure are both real.
- [ ] **DG6 — `!testme` end-to-end on an unconfigured recipe.** A `!testme` on a recipe with no
cc-ci/repo-local customization runs the full generic suite through the real pipeline
(bridge → Drone → deploy → assert → undeploy → report) and reports **per-operation**
pass/fail/skip (install/upgrade/backup/restore).
- [ ] **DG7 — Real, DRY, clean.** No softened/`skip`/`xfail`/can't-fail assertions; generic logic
lives in the **shared harness** (M6.5 — no per-recipe copy-paste); every run **undeploys**
(teardown in `finally`), respects `MAX_TESTS`.
- [ ] **DG8 — Documented + cold-verified.** `docs/` explains the generic suite, the overlay
convention (file names + locations + precedence), and the custom-install-steps hook + how to
add a recipe overlay. The Adversary re-runs the acceptance checks from a cold start within 24h.
When DG1–DG8 hold and are confirmed, write `## DONE` to `machine-docs/STATUS-1d.md`.
---
## 2. The layered test model (the core design)
For a given recipe, the harness assembles and runs **tiers**, each = `generic [+ overlays]`:
(`gen` = generic default; `→` = "overridden/extended by, if the recipe defines it" — mechanism is
the Builder's call, §2.2):
```
INSTALL = gen_install → test_install.py (else gen) ← always runs
UPGRADE = gen_upgrade → test_upgrade.py (else gen) ← always runs
BACKUP = gen_backup → test_backup.py (else gen) ← if backup-capable, else N/A
RESTORE = gen_restore → test_restore.py (else gen) ← if backup-capable, else N/A
CUSTOM = recipe test_*.py (anything beyond the four) ← ONLY if defined
```
### 2.1 Generic baseline suite (recipe-agnostic)
- **install** — `abra app new <recipe> --domain <run>.ci.commoninternet.net` with non-interactive
defaults + auto-generated secrets; `abra app deploy`; poll to converged; assert a real HTTP(S)
response from the app over its domain (status + that it's the app, not Traefik's fallback).
- **upgrade** — deploy a prior/pinned version, `abra app upgrade` to target, assert reconverge +
still serving.
- **backup / restore** — only for recipes declaring backup config; verify the **mechanism** (backup
produces an artifact; restore completes + app healthy). **Honest limit:** generic backup/restore
can't assert app-specific *data integrity* without recipe knowledge — that's a recipe overlay
(`test_backup.py`/`test_restore.py` seed a marker + assert it survives). State this in docs.
### 2.2 Layering — override or extend (Builder's call), always **reuse the deployment**
A recipe-defined `test_install.py` (etc.) either **overrides** the generic assertions for that op or
**extends** them — the Builder picks the mechanism (a present `test_<op>.py` replacing the generic is
a fine, simple model; or additive; or per-recipe opt-in). The invariant either way: **if a recipe
defines nothing for an op, the generic runs.** This guarantees every recipe is testable with zero
config, while letting a recipe with a poor generic fit supply its own.
**Reuse the deployment — do NOT redeploy per test (operator requirement, 2026-05-27).** Overlay
assertions run against the **same live deployment** the generic tier already brought up — no extra
`abra app new`/`deploy`/`undeploy` per overlay. The target shape: **one deploy per run**, then the
lifecycle ops mutate that single deployment in sequence and *all* assertions (generic + overlays +
custom) run against it, then **one teardown** at the end:
```
deploy ONCE
→ INSTALL assertions: generic_install + test_install.py (same live app)
→ UPGRADE in place (abra app upgrade)
assertions: generic_upgrade + test_upgrade.py (same app, upgraded)
→ BACKUP (if capable) → generic_backup + test_backup.py
→ RESTORE (if capable) → generic_restore + test_restore.py
→ CUSTOM test_*.py (same live app)
teardown ONCE (in finally)
```
So a seed/marker written by `test_backup.py` is the same data `test_restore.py` checks; an overlay's
extra HTTP assertion hits the app the generic install already deployed. Tiers that intentionally
change state (UPGRADE, RESTORE) do so on the shared deployment in order. The only time a tier
re-provisions is when an op semantically requires it (e.g. a from-scratch restore-into-blank variant)
— and that must be explicit, not the default. This is also the main Phase-2b speed win.
### 2.3 Custom tests
`test_*.py` that aren't one of the four lifecycle names run **only when present** for that recipe —
no generic equivalent, purely opt-in (e.g. `test_sso.py`, `test_federation.py`).
### 2.4 Custom install steps (and the graceful-generic rule)
Some recipes need extra setup the generic flow won't do (pre-seed a DB, set an env/secret, run a
one-off command). The harness exposes a **defined** per-recipe install-steps hook (cc-ci or
repo-local). Rules:
- If a recipe **declares** custom install steps → run them as part of the install tier.
- If a recipe has **no** customization defined anywhere → **still attempt the generic suite.**
Recipes that genuinely need special steps will **fail the generic install — and that's acceptable
and expected**; the failure is reported (per-op), and the fix is to add the custom step (Phase 2
work), not to special-case the harness.
### 2.5 Discovery + precedence
- **Locations:** cc-ci's test dir (e.g. `tests/<recipe>/`) and the recipe repo's `tests/`
(repo-local). The harness discovers overlays + custom-install-steps from both.
- **Precedence (OPEN — settle in DECISIONS):** proposed default — **both layer**; repo-local is the
upstream-authoritative source and always runs, cc-ci's overlay runs in addition (and may pin/extend
for the CI env). Define the rule for same-named collisions explicitly.
---
## 3. Milestones (bounded)
- **G0 — Generic install.** Implement generic_install in the shared harness; green on `custom-html`
with no recipe config. *Accept:* DG1.
- **G1 — Generic upgrade + backup/restore.** Add generic_upgrade; add generic_backup/restore gated
on backup-capability (clean N/A otherwise). *Accept:* DG2, DG3.
- **G2 — Layering + discovery.** Implement the generic+overlay composition and cc-ci/repo-local
discovery + precedence; prove an overlay runs on top of generic. *Accept:* DG4.
- **G3 — Custom install-steps hook + graceful-generic.** Implement the hook; demonstrate the
fail-without / pass-with proof on one recipe needing a step. *Accept:* DG5.
- **G4 — `!testme` integration + per-op reporting + docs + cold verify.** *Accept:* DG6, DG7, DG8;
then flip `machine-docs/STATUS-1d.md` to `## DONE`.
---
## 4. Guardrails
- **Generic is the default; recipe tests override or extend it** (Builder's mechanism) — but the
generic **always** runs when a recipe defines no test for that op. Never let a recipe end up with
*no* assertion for an op it should be tested on.
- **Generic failure ≠ harness bug** — a recipe needing custom steps failing the generic install is a
correct, reported outcome; fix by adding the step (Phase 2), don't weaken/special-case the generic.
- **Deploy once, reuse it** — overlays run against the generic tier's live deployment; no
per-test/per-overlay redeploy. One deploy + one teardown per run; re-provision only when an op
truly needs it, explicitly. (Correctness *and* the main perf lever.)
- **DRY** — generic logic in the shared harness, not per-recipe (M6.5); overlays are thin.
- **No weakened tests** — real assertions on real app state; teardown always; honor `MAX_TESTS`.
- **Bounded** — build the architecture + prove it on a couple of recipes; the full per-recipe overlay
authoring is Phase 2, not here.
---
## 5. Impact on later phases (reshapes the plan set)
- **Phase 2 (`plan-phase2-recipe-tests.md`)** changes from "author every test from scratch" to:
every enrolled recipe gets the generic suite for free; Phase 2 = **author the additive overlays**
(port recipe-maintainer tests as `test_*.py` overlays) **+ define custom install steps** where a
recipe fails generically. Update Phase 2 to reference 1d as its foundation.
- **Phase 3 (`plan-phase3-results-ux.md`)** — the YunoHost-style **level** maps cleanly onto the
tiers: e.g. installs (generic) → +upgrade → +backup/restore → +custom assertions. The level is
derived from which tiers pass.
- **Phase 2b (perf)** — the generic suite is the common hot path, so it's the prime target for the
image-cache / readiness / dedup optimizations.
---
## 6. Open decisions (log in machine-docs/DECISIONS.md)
- **Override vs extend (Builder's call).** Does a present `test_<op>.py` **replace** the generic
assertions for that op, **add** to them, or is it **per-recipe opt-in**? Operator leans: override
is a good, simple model. Builder decides + documents — keeping the invariant "no recipe test for an
op ⇒ generic runs" and the single-shared-deployment rule.
- **cc-ci vs repo-local precedence** for overlays + install-steps (§2.5) and same-name collision rule.
- Exact **overlay file convention**: fixed names (`test_install.py`…) + discovery dir layout
(`tests/<recipe>/` in cc-ci; `tests/` in the recipe repo).
- How **custom install steps** are declared: a shell hook (`install_steps.sh`), a pytest fixture, or
a declarative field — pick the simplest that the harness can run uniformly.
- **Backup-capability detection**: how the harness decides a recipe is backup-capable (backupbot
labels present / `abra app backup` exit) to choose run-vs-N/A for DG3.
- Whether generic **upgrade** should always go previous→latest, or test the specific
version-bump under `!testme` (PR-driven).
- Per-op result vocabulary (`pass`/`fail`/`skip(N/A)`/`error`) feeding the Phase-3 level.
- **Deployment-sharing scope**: confirm one-deploy-per-run for the whole lifecycle (install→upgrade→
backup→restore→custom on a single deployment) vs per-tier deployments; and how a failed earlier
tier (e.g. install) affects later tiers sharing that deployment (fail-fast vs continue-and-report).
@@ -0,0 +1,139 @@
# cc-ci Phase 1e — Generic-harness corrections (Autonomous Build Plan)
**Status:** QUEUED — runs **after Phase 1d** and **before Phase 2** (`plan-phase2-recipe-tests.md`).
It corrects the **shared generic-test harness** from 1d, so it must land before Phase 2 authors
overlays on top of it.
**Transition:** **manual** (operator kicks it off).
**Builds on:** the Phase-1d generic suite (`runner/run_recipe_ci.py`, `runner/harness/*`,
`tests/_generic/*`, `tests/conftest.py`) — see `plan-phase1d-generic-test-suite.md`.
**Owner agents:** same Builder + Adversary loops (`plan.md` §6/§7); Adversary cold-verifies.
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase1e-harness-corrections.md`
**Phase order:** 1c → 1b → 1d → **1e** → 2 → 2b → 3.
---
## 0. Why this phase
An operator review of the 1d generic suite (2026-05-28) found three corrections to the **shared
harness** — the foundation every recipe overlay (Phase 2) builds on. Fixing them now, once, is far
cheaper than after overlays exist. All three are small in code but change behavior, so each needs a
fresh Adversary cold-verification and must not weaken any existing test.
---
## 1. Definition of Done (Phase 1e exit condition)
Terminates when every item holds **and the Adversary has independently cold-verified** (logged in
`machine-docs/REVIEW-1e.md`):
- [ ] **HC1 — Upgrade tier upgrades to the code under test (PR head), not a published tag.** The
upgrade tier deploys the **previous published version** (last release before the PR) and then
**upgrades to the PR head via `abra app deploy --chaos`** (chaos = the current checkout). The
PR's actual changes are exercised by the upgrade path. (§2.1)
- [ ] **HC2 — Repo-local (PR-authored) code is not executed unless the recipe is approved.** By
default the harness runs **only cc-ci-authored** overlays/install-steps (`tests/<recipe>/…`) +
the generic; PR-authored repo-local `test_*.py` and `install_steps.sh` are **not run**.
Repo-local code is honored **only for recipes on an explicit cc-ci-maintained approval
allowlist** (default-deny). (§2.2)
- [ ] **HC3 — Generic runs by default (additive); skipping it is explicit.** When a recipe ships an
overlay for an op, the **generic still runs** alongside it by default; the generic is skipped
**only** when an explicit env/flag opts out. The baseline floor is never lost silently. (§2.3)
- [ ] **HC4 — No regression, cold-verified.** The Adversary re-runs the relevant D1–D10 / DG1–DG8
acceptance from a cold start: nothing weakened, deploy-once (DG4.1) still holds, teardown still
sacred, and the three new behaviors are demonstrated (HC1: a PR-head upgrade proven to deploy
PR-head; HC2: a repo-local test is *ignored* for a non-approved recipe and *run* for an approved
one; HC3: generic runs with an overlay present, and is skipped only with the opt-out set).
When HC1–HC4 hold and are confirmed, write `## DONE` to `machine-docs/STATUS-1e.md`.
---
## 2. The three corrections
### 2.1 HC1 — Upgrade to the PR head (not a published tag)
Current 1d behavior: deploy previous published version, then `abra app upgrade` to the **newest
published tag** — and because deploying the prev tag re-checks-out the recipe, the **PR-head code is
never deployed**, so a recipe PR's changes aren't exercised by upgrade.
Corrected:
1. Deploy the **previous published version** (the last release before the code under test) as the
"before" state.
2. **Restore the PR-head checkout** (re-checkout the PR ref / re-use the post-fetch snapshot — the
prev-tag deploy will have reset `~/.abra/recipes/<recipe>`).
3. **Upgrade to it via `abra app deploy --chaos`** (chaos = current checkout = PR head) in place on
the shared deployment.
4. Assert reconverge + still serving (as today).
- **Adapt the "deployment moved" assertion** (`generic.do_upgrade`): prev→PR-head may *not* bump the
coop-cloud version label (a PR can change a recipe without a version bump), so also accept an
image/config change, or assert the running config now matches the PR head — keep it non-vacuous
without false-failing a legit unbumped PR.
- **Non-PR `!testme`** (no PR head): "current checkout" = the catalogue current, so upgrade tests
prev→current — still valid.
- Preserve **deploy-once** spirit: this is still one app deployment mutated in place (prev → chaos
redeploy of PR head is the upgrade op, not a fresh second app). Reconcile with the DG4.1
deploy-count guard — define whether a chaos redeploy counts as a "deploy" and adjust the guard so
the legitimate upgrade isn't flagged (e.g. count `abra app new` installs, not in-place redeploys).
### 2.2 HC2 — Repo-local trust gate (default-deny; cc-ci overlays only)
`install_steps.sh` and repo-local `test_*.py` are PR-author-controlled code that runs on the CI host
with `/run/secrets/*` present — an untrusted-code risk. Operator decision (2026-05-28):
- **Default:** the harness runs **only cc-ci-authored** overlays + install-steps
(`tests/<recipe>/…`) and the generic. Repo-local (`<recipe-repo>/tests/`) `test_*.py` and
`install_steps.sh` are **discovered-but-not-executed**.
- **Approved recipes only:** repo-local code is honored **only** when the recipe is on an explicit,
**cc-ci-maintained approval allowlist** (default-empty ⇒ default-deny). Adding a recipe to the
allowlist is a deliberate cc-ci-maintainer act after reviewing that recipe's tests.
- Update `discovery.resolve_op` / `custom_tests` / `install_steps` so the **repo-local source is
only consulted for allowlisted recipes**; otherwise precedence is **cc-ci > generic** only.
- **Open (settle in DECISIONS):** the allowlist's form + location (a checked-in file like
`tests/repo-local-approved.txt`, or a field in a cc-ci config), and the approval workflow. Keep it
simple + auditable + in git.
- (Future hardening, → IDEAS, not this phase: sandbox/network-restrict even cc-ci overlays.)
### 2.3 HC3 — Generic by default (additive), explicit opt-out
Supersedes 1d's pure-override default. New rule: when a recipe ships an overlay for an op, **both the
generic and the overlay run** for that op by default; the generic is skipped **only** when an
explicit opt-out is set.
- **Opt-out mechanism (propose; settle in DECISIONS):** an env flag `CCCI_SKIP_GENERIC` (all ops) and
per-op `CCCI_SKIP_GENERIC_<OP>` (e.g. `..._UPGRADE`), settable via the recipe's `recipe_meta.py`
(a `SKIP_GENERIC` list) so it's declarative per recipe, not a hidden global.
- **Op-vs-assertion split (required by additive + deploy-once):** a mutating op (upgrade/backup/
restore) must run **once**, then **both** the generic assertions and the overlay assertions
evaluate the post-op state — never upgrade/backup twice. So refactor the tiers: the **orchestrator
performs the op once** (the harness owns the op), then runs generic assertions (unless opted out) +
overlay assertions against the shared post-op deployment. For `install` (no op) both assertion sets
just run. This keeps deploy-once and one-op-per-tier intact.
- Net effect: the generic "is it actually serving / did the upgrade move / snapshot produced" floor
is **always** exercised unless a recipe explicitly declares it skips generics — overlays add, they
don't silently subtract.
---
## 3. Method / milestones (bounded)
- **E0 — HC2 trust gate.** Gate repo-local behind the approval allowlist (default-deny); cc-ci+generic
only otherwise. *Accept:* repo-local ignored for a non-approved recipe, run for an approved one.
- **E1 — HC3 additive + op/assertion split.** Generic runs alongside overlays by default; op runs
once; opt-out env skips the generic assertions. *Accept:* overlay + generic both run on one
deployment; opt-out skips generic; deploy-count still 1.
- **E2 — HC1 upgrade-to-PR-head.** prev-release → PR-head via `deploy --chaos`; moved-assertion
adapted; deploy-count guard reconciled. *Accept:* upgrade demonstrably deploys PR-head.
- **E3 — HC4 cold re-verification + docs.** Adversary cold-verifies no regression + the three new
behaviors; update `docs/` + `machine-docs/DECISIONS.md`; flip `STATUS-1e.md` to `## DONE`.
---
## 4. Guardrails
- **Never weaken a test** — these are correctness/security fixes; the cardinal rule still wins.
- **Default-secure** — repo-local PR code is off unless the recipe is explicitly approved; the
allowlist lives in git and is auditable.
- **Floor-by-default** — the generic baseline always runs unless a recipe explicitly opts out.
- **Deploy-once preserved** — one app deployment, one teardown; ops run once; reconcile the DG4.1
guard with the chaos-upgrade redeploy.
- **Bounded** — three fixes + verification, then stop; bigger hardening (sandboxing) → IDEAS.
## 5. Open decisions (log in machine-docs/DECISIONS.md)
- HC2: approval-allowlist form/location + the approval workflow.
- HC3: opt-out flag name/granularity + declaring it via `recipe_meta.py`.
- HC1: how the DG4.1 deploy-count guard treats an in-place chaos upgrade (don't flag the legit op).
@@ -0,0 +1,300 @@
# cc-ci Phase 2 — Comprehensive per-recipe test authoring (Autonomous Build Plan)
**Status:** QUEUED — starts after Phase 1b (`plan-phase1b-review-lint.md`) **and Phase 1d**
(`plan-phase1d-generic-test-suite.md`) reach `## DONE`.
**Builds on:** the Phase-1 cc-ci CI server (`plan.md`) **and Phase 1d's generic test suite** — every
recipe already gets generic install/upgrade/backup/restore for free, reusing one shared deployment.
So this phase is **not** "write every test from scratch": it's **authoring the recipe overlays**
(`test_<op>.py` that override/extend the generic, per 1d's model) + **defining custom install steps**
for recipes that fail the generic form, porting the recipe-maintainer corpus as overlays. This phase
adds **test content**, not infra.
**Reference corpus:** `references/recipe-maintainer/` → `/srv/recipe-maintainer/` (the existing,
human-maintained recipe tests — the canonical source to port from).
**Owner agents:** same Builder + Adversary loops + coordination protocol as Phase 1 (`plan.md` §6/§7).
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase2-recipe-tests.md`
---
## 0c. OIDC / SSO-dep recipes — follow the SSO-dep plan (NOT operator-pending)
Recipes that authenticate via OIDC (lasuite-docs, cryptpad, lasuite-drive, lasuite-meet, future)
do **not** need operator input to wire OIDC. The canonical pattern lives at
**`plan-sso-dep-testing.md`** — declared `DEPS = ["keycloak"]` in `recipe_meta.py`, orchestrator
co-deploys the dep, recipe `install_steps.sh` reads `$CCCI_DEPS_FILE` and writes the OIDC env vars
+ injects the client secret via abra. Authenticated tests use `harness.sso.oidc_password_grant` or
Playwright on the dep's login page. **`DEFERRED.md` entries that cite "operator input needed for
OIDC" are mis-categorised** — re-open and execute them per this plan.
## 0b. Auto-mirror missing recipes (NOT a blocker — autonomous loop work)
A recipe is not on `git.autonomic.zone/recipe-maintainers/<recipe>` is **not** an operator-pending
blocker. The bot is admin on `recipe-maintainers` (see memory `cc-ci-gitea-recipes`) and can create
private mirror repos. **For any recipe you want to enroll/test that isn't mirrored yet, mirror it
yourself** before enrolling, based on the **`recipe-create-pr` skill** —
`/srv/recipe-maintainer/.opencode/skills/recipe-create-pr/SKILL.md` (which references
`/srv/recipe-maintainer/.claude/commands/recipe-create-pr.md` for the full procedure).
The flow (adapt the skill's command for the new-mirror case):
1. Create the **private** mirror repo on `git.autonomic.zone/recipe-maintainers/<recipe>` (Gitea API
POST `/orgs/recipe-maintainers/repos`, bot creds from `.testenv`/§1.5).
2. Mirror the upstream `git.coopcloud.tech/coop-cloud/<recipe>` (clone --mirror → push, including
tags) so the mirror's `main` is upstream-synced and tags carry over.
3. Then proceed with normal enrollment + the lifecycle suite (1d generic + your overlays from this
phase).
Treat this as standard loop work — don't sit idle waiting on the operator for missing recipes.
## 0a. Prerequisite: Phase 1e harness corrections (must be DONE first)
The 1d/1b operator review produced three shared-harness corrections, now their own phase
**`plan-phase1e-harness-corrections.md`** (runs **before** this phase). Do **not** author overlays
until 1e is `## DONE`: it changes the foundation every overlay sits on — (HC1) upgrade goes
prev-release → **PR head** via `deploy --chaos`; (HC2) **repo-local PR code runs only for approved
recipes** (default cc-ci-overlays + generic only); (HC3) the **generic runs by default alongside an
overlay**, skipped only via an explicit opt-out. See that plan for detail.
## 0. Relationship to Phase 1 (read first)
Phase 1 built the **machine**: the Drone pipeline, the `!testme` trigger (polling-primary), the
`coop-cloud/traefik` proxy, the shared harness (`runner/run_recipe_ci.py` + `tests/conftest.py` +
`runner/harness/`), the three stages (**install / upgrade / backup-restore**), guaranteed teardown,
the `MAX_TESTS` concurrency cap, and the results dashboard — proven on ~six recipes (D10).
Phase 2 **fills the machine with good tests for every Co-op Cloud app we maintain.** It does **not**
re-architect the runner. It reuses Phase-1's harness, stages, trigger, resource caps, and teardown.
Everything here is `tests/<recipe>/...` content + small, shared harness *additions* (ported from
recipe-maintainer's helpers). When reality forces a harness change, record it in `DECISIONS.md`.
Do not start Phase 2 until Phase-1 `STATUS.md` shows `## DONE` (Adversary-verified). The same loop
protocol, single-writer file ownership, and gate handshake (`plan.md` §6.1/§7) apply here.
---
## 1. Mission
For **every maintained Co-op Cloud recipe**, the cc-ci repo's `tests/<recipe>/` tree must contain a
genuine end-to-end test suite that, run by `!testme` on a real PR, proves the app actually works —
**at parity with what `recipe-maintainer` already tests, plus recipe-specific functional depth.**
Concretely, for each recipe:
1. **Port every existing recipe-maintainer test** for that recipe (a comparable cc-ci test for each
`recipe-info/<recipe>/tests/*.py`).
2. **Add ≥2 new recipe-specific functional tests** that exercise something characteristic of that
app (not just "it returns 200") — see §4.3.
3. All of it runs inside Phase-1's three stages and passes green via `!testme`.
---
## 2. Definition of Done (Phase 2 exit condition)
The loop terminates only when every item holds **and the Adversary has independently re-verified
each within 24h** (logged in `REVIEW.md`):
- [ ] **P1 — Coverage.** Every recipe in the **Phase-2 recipe set (§5)** has a `tests/<recipe>/`
suite enrolled and a full green `!testme` run (install + upgrade + backup-restore).
- [ ] **P2 — Parity port.** For each recipe, **every** test under
`recipe-info/<recipe>/tests/*.py` has a comparable cc-ci test (same thing verified), adapted to
the cc-ci harness. A mapping table (recipe-maintainer test → cc-ci test) is recorded in
`tests/<recipe>/PARITY.md`. Any test deliberately not ported is a documented `DECISIONS.md`
finding with the reason (e.g. obsolete, replaced by a better check), never a silent omission.
- [ ] **P3 — Recipe-specific depth.** Each recipe has **≥2 new functional tests** beyond parity that
confirm characteristic behavior (§4.3), with real assertions on app state/responses — not
health-only.
- [ ] **P4 — Backup data-integrity is real.** The backup-restore stage for each recipe **seeds
identifiable data, mutates/wipes, restores, and asserts the seeded data survived** (recipe-aware,
not just "service is up") — ported from recipe-maintainer's backup approach.
- [ ] **P5 — Dependencies handled.** Recipes needing other apps (SSO providers, DBs) declare deps
(ported from `recipe.toml` `requires`/`test_requires`); the harness deploys deps within the run
(respecting `MAX_TESTS`/node budget) and SSO setup runs automatically (§4.2).
- [ ] **P6 — Browser flows where they matter (D3).** Recipes whose core function is a UI flow have a
Playwright test of that flow (login, create-an-object, etc.), not just API checks.
- [ ] **P7 — No weakened tests, no corners cut (§7.1).** Every assertion is real and checks app
state; nothing is `skip`/`xfail`'d, mocked, or reduced to a health-only stand-in to go green.
The bar: anything meaningful is testable with effort (OIDC/SSO, federation, media, WOPI, WebRTC
connectivity, data survival all included). Any "untestable" claim is the rare exception — a true
environment-level blocker only, with the maximal subset still implemented and **Adversary
sign-off** (§8); "needs a browser / SSO / another app" is not a valid excuse.
- [ ] **P8 — Docs.** `docs/enroll-recipe.md` updated with the per-recipe test contract (§4.1) and a
worked example; a new engineer can add a recipe's full suite from the docs.
When all P1–P8 hold and are Adversary-verified, write `## DONE` to Phase-2 `STATUS.md`.
---
## 3. Reference corpus (port from here)
`references/recipe-maintainer/` (`/srv/recipe-maintainer/`) is the source of truth for *what* to
test and *how* recipe-maintainer already does it. Key paths:
- **Per-recipe tests:** `recipe-info/<recipe>/tests/*.py` — the scripts to port (health_check,
oidc_login/oidc_integration, and recipe-specific ones like `meeting_flow.py`, `webrtc-media.py`,
`wopi_configured.py`, `goat_account.py`, `upload_conversion.py`).
- **Per-recipe metadata:** `recipe-info/<recipe>/recipe.toml` (deps + `[sso]` provider/setup_script),
`test.md` (target URLs, what each test checks, manual steps, network/health specifics), `setup.md`,
`upstream.md`, `setup_<provider>_integration.py` (SSO realm/client/test-user setup).
- **Shared utilities to port/adapt:** `utils/tests/helpers.py` — `http_get`/`http_post`,
`retry_http_get`, `assert_converges`, `wait_for_http`, `load_toml_credentials`, `abra(... tty_wrap)`,
`fresh_app`, `deploy_and_wait`. These map onto the Phase-1 harness fixtures.
- **Orchestration logic to mirror as stages:** `.claude/commands/recipe-test{,-all,-new,-update,-backup}.md`
(new-install / upgrade / backup-restore semantics — already Phase-1 stages; port the *assertions*).
- **Operational gotchas to bake in:** `learnings.md` — TTY-wrap (`script -qefc "abra …" /dev/null`)
for backup/restore/volume/secret/run/logs/lint; always `--chaos`; `backup-bot-two` must be present
for backup tests; prefer `docker service logs` over `abra app logs` (hangs non-interactively);
ghost-container volume-removal cleanup. Most are already in Phase-1 §4.3 — re-verify on the
installed abra.
**Adaptation note (important):** recipe-maintainer tests run against a *persistent* instance
(`cctest.autonomic.zone`) using `context_reset.py` to free memory. cc-ci runs **ephemeral per-PR
deploys**. So port the **assertions and setup logic**, but drive lifecycle through Phase-1's harness
(per-run isolated app `<recipe>-pr<n>-<sha>`, guaranteed teardown) — not the persistent-instance model.
---
## 4. The per-recipe test contract
### 4.1 Required structure (per recipe)
```
tests/<recipe>/
├── recipe.toml # ported deps + [sso] (from recipe-maintainer's recipe.toml)
├── PARITY.md # mapping: recipe-maintainer test -> cc-ci test (for P2)
├── test_install.py # Phase-1 install stage hook + recipe health/readiness
├── test_upgrade.py # Phase-1 upgrade stage hook (prev published -> PR version)
├── test_backup.py # Phase-1 backup stage: seed -> backup -> wipe -> restore -> assert data (P4)
├── functional/ # ported parity tests + NEW recipe-specific tests (P2, P3)
│ ├── health_check.py # ported
│ ├── <ported-tests>.py # one per recipe-maintainer test
│ └── <recipe>_<behavior>.py # NEW, >=2 recipe-specific functional tests
└── playwright/ # browser flows where the app's core UX is a UI (P6)
```
### 4.2 Shared harness additions (port from `utils/tests/helpers.py`)
Add to `runner/harness/` (reused across recipes), so per-recipe tests stay small:
- HTTP convergence helpers (`retry_http_get`, `assert_converges`, `wait_for_http`).
- **SSO setup + OIDC-flow helpers**: deploy the provider (keycloak/authentik), run the recipe's
`setup_<provider>_integration.py` (realm/client/test-user), persist credentials per-run, and a
reusable "full OIDC login → token → protected API call" assertion.
- **Dependency resolver**: read `tests/<recipe>/recipe.toml` `requires`/`test_requires`, deploy deps
before the recipe under test, tear them down with it. Mind the `MAX_TESTS`/node budget — a recipe +
its SSO provider is ≥2 live apps; sequence heavy ones.
- **Backup data-integrity helper**: seed a recipe-defined marker, snapshot, wipe volumes, restore,
re-read the marker (P4).
- TTY-wrapped abra wrappers + robust readiness waits (no bare `sleep`).
### 4.3 Recipe-specific functional tests (P3) — what "confirms how it works" means
Beyond health + parity, each recipe gets **≥2** tests exercising its characteristic behavior. Derive
them from the recipe's `test.md` and what the app *is for*. Representative targets:
- **keycloak** — create a realm+client via admin API; obtain a token (password & client-credentials
grants); validate JWT claims.
- **matrix-synapse** — register two users (admin API); one sends a room message, the other reads it;
media upload→download; `/_matrix/federation/v1/version` reachable.
- **immich** — upload an asset via API, list it back, confirm a thumbnail/derivative is generated.
- **lasuite-docs** — create a doc, edit via the API, confirm persistence; WOPI discovery (Collabora/
OnlyOffice) XML valid (port `wopi_configured`).
- **lasuite-drive** — upload a file to a workspace, list/download it; MinIO bucket present.
- **lasuite-meet** — create a room, two users get LiveKit tokens & join (port `meeting_flow`);
WebRTC connectivity probe (port `webrtc-media`).
- **cryptpad** — create a pad and confirm it persists (note client-side-encryption: page is
JS-rendered, so use Playwright, not bare curl — see recipe-maintainer's note).
- **bluesky-pds** — create a test account (goat CLI), create a post via atproto, fetch it back,
delete the account (port `goat_account`, extend with a post round-trip).
- **mumble** — connect a client/CLI and confirm channel presence (beyond TCP health).
- **n8n** — create a workflow via API, execute it, assert the result.
- **ghost / mattermost-lts / discourse / plausible / uptime-kuma / mailu** — create the app's primary
object (post / message / topic / tracked event / monitor / mailbox) and read it back.
- **custom-html / hedgedoc / gitea** — serve/persist content: write content, fetch it back.
(For any recipe, "≥2 specific tests" = at minimum: create-an-object + read-it-back, and one more that
touches a distinctive feature — SSO, federation, media, WOPI, WebRTC, etc.)
---
## 5. Phase-2 recipe set + enrollment
**Target set** (recipe-maintainer's maintained list — `maintained-recipes`): cryptpad, lasuite-drive,
lasuite-docs, lasuite-meet, matrix-synapse, keycloak, bluesky-pds, mumble, immich, mailu, custom-html,
mattermost-lts, n8n, ghost, drone, plausible, uptime-kuma, discourse (+ authentik as an SSO provider).
Several already live on the mirror (`recipe-maintainers/<recipe>`); the rest are brought over via the
**Phase-1 recipe mirror+PR flow** (`abra recipe fetch` → recipe-create-pr procedure;
see Phase-1 `plan.md` §4.1). Enroll **easy → hard**, dependency-tiered like recipe-maintainer
(`recipe.toml` tiers): SSO providers (keycloak, authentik) and DBs first, then their dependents.
Order guidance: prove the Phase-2 pattern on a simple recipe (custom-html) and a DB recipe (n8n),
then keycloak/authentik (providers), then the SSO-dependent suite (lasuite-*, immich, cryptpad), then
the heavy/standalone ones (matrix-synapse, mumble, bluesky-pds, ghost, discourse, mailu, mattermost,
plausible, uptime-kuma, immich). Respect `MAX_TESTS` and run heavy deploys sequentially.
---
## 6. Milestones (each ends with an Adversary gate)
- **Q0 — Harness additions.** Port `helpers.py` capabilities into `runner/harness/` (HTTP/convergence,
OIDC-flow, dependency resolver, backup data-integrity, TTY abra). *Accept:* a reference recipe
(custom-html) uses them for a full parity+specific suite, green via `!testme`.
- **Q1 — Pattern proof (2 recipes).** custom-html (simple) + n8n (single-DB): full parity port +
≥2 specific tests + real backup data-integrity. *Accept:* both green; `PARITY.md` complete.
- **Q2 — SSO providers.** keycloak + authentik: parity + specific tests; the reusable SSO-setup/
OIDC-flow harness works end-to-end. *Accept:* a dependent recipe can deploy a provider and run an
OIDC login test in one run.
- **Q3 — SSO-dependent suite.** lasuite-docs, lasuite-drive, lasuite-meet, cryptpad, immich: deps
auto-deployed, SSO setup automated, parity + specific (WOPI, meeting/WebRTC, media, pad). *Accept:*
each green with deps, within node budget.
- **Q4 — Remaining recipes.** matrix-synapse, mumble, bluesky-pds, ghost, mattermost-lts, discourse,
plausible, uptime-kuma, mailu, drone. *Accept:* each green, parity + specific.
- **Q5 — Completeness + docs.** Every recipe in §5 covered; `PARITY.md` for all; `enroll-recipe.md`
documents the test contract with a worked example. *Accept:* Adversary re-runs a sampled subset
cold and confirms parity tables + specific tests are real (not health-only, not skipped); flip
Phase-2 `STATUS.md` to `## DONE`.
---
## 7. Loop protocol & guardrails (inherit from Phase 1)
Same as `plan.md` §6/§6.1/§7/§9. Phase-2-specific emphases:
- **Never weaken a test to go green** (P7) — the single most important rule; the Adversary watches
for health-only stand-ins, `skip`/`xfail`, or assertions that don't actually check app state.
- **Real data-integrity for backups** (P4) — "service is up after restore" is *not* sufficient; the
seeded data must be proven to survive.
### 7.1 Adversary mandate (Phase 2) — no skipped tests, no corners cut
The default assumption is that **everything meaningful about an app is testable with enough effort —
the job is to write a *good* test, not to declare it impossible.** OIDC/SSO login, token issuance and
JWT validation, federation endpoints, media upload/download, WOPI discovery, WebRTC ICE/connectivity,
backup data survival — these are all testable end-to-end and **must** be tested, not stubbed. The
Adversary actively enforces this and **reads the test bodies, not just pass/fail**:
- **Reject** any test that is `skip`/`xfail`/commented-out, mocked, mutated to a `health_check`
stand-in, asserts nothing material (e.g. only `status==200`), or is hard-coded to pass.
- **Reject "we couldn't test X"** unless it is a genuine *environment-level* limitation (e.g. the
test host cannot receive inbound UDP, so the full lasuite-meet *media relay* path can't complete) —
and even then demand the **maximal testable subset** (e.g. signaling, token issuance, ICE candidate
gathering) plus a `DECISIONS.md` justification with the specific technical blocker. "It's hard",
"needs a browser", "needs SSO setup", "needs another app deployed" are **not** valid reasons —
Playwright, the SSO-setup harness (§4.2), and the dependency resolver exist precisely to remove
those excuses.
- **Verify parity for real (P2):** for each `PARITY.md` row, confirm the cc-ci test checks the *same
thing* the recipe-maintainer original did — not a hollow rename.
- **Re-run cold and inspect:** the Adversary re-runs a sampled recipe's suite from a clean state and
reads the diffs/assertions; a green run with empty assertions is a FAIL and a `[adversary]` finding.
- **Respect Phase-1 resource caps** — deps multiply live apps per run; keep within `MAX_TESTS`/node
budget; sequence heavy recipes; teardown (incl. deps) is guaranteed.
- **Tests are recipe-versioned** — they run against the PR's recipe version; don't hardcode values
that break across upstream versions (read versions/endpoints dynamically, as helpers.py does).
- **Cite the source** — each ported test notes its `recipe-info/<recipe>/tests/<file>` origin in
`PARITY.md` so parity is auditable.
---
## 8. Open decisions (log in DECISIONS.md)
- Whether to **vendor** the ported helpers into `runner/harness/` vs import recipe-maintainer's
`helpers.py` directly. (Default: vendor/adapt — cc-ci must be self-contained and not depend on the
recipe-maintainer workspace at runtime.)
- Per-recipe **secret/SSO credential** persistence within a run (reuse Phase-1 §4.4-B run-scoped
store; SSO test users/clients are class-B, generated per run, destroyed at teardown).
- How many recipe-specific tests beyond the **≥2** floor per recipe (scale with the app's surface;
don't gold-plate trivial recipes).
- A test deemed "impossible" is the **rare exception**, not a convenient out (§7.1). It is only
acceptable for a true environment-level blocker (e.g. no inbound UDP for lasuite-meet's *media
relay*), requires the **maximal testable subset** still implemented, a specific technical reason in
`DECISIONS.md`, **and Adversary sign-off**. SSO/OIDC, browser flows, multi-app dependencies, and
data-integrity are explicitly **not** exceptions — they are testable and required.
@@ -0,0 +1,69 @@
# cc-ci Phase 2b — Confirm the test sequence minimizes deploys (no redundant deploys)
**Status:** QUEUED — starts after Phase 2 (`plan-phase2-recipe-tests.md`) reaches `## DONE`, before
Phase 3. **Transition:** manual (operator kicks it off). **Owner:** Builder + Adversary loops.
**This file:** `/srv/cc-ci/cc-ci-plan/plan-phase2b-test-performance.md`
---
## 0. Scope (NARROWED — operator, 2026-05-30)
The original Phase 2b was a broad empirical performance program (instrument → baseline → attribute →
optimize). **That has been removed and parked in `IDEAS.md`** ("Phase-2b empirical performance work").
**Why:** the real deploy-speed bottleneck was **hardware**, not software — the cc-ci VM was **2 vCPU
on a 4-core host** and **disk-I/O-bound** (load ~8, io pressure ~65%), with warm-keycloak (JVM) + all
infra resident; RAM was never the constraint. That was fixed **directly**: cc-nix-test bumped to
**4 vCPU** and made the **only running VM** on b1 (full host CPU). The software micro-optimizations are
judged unlikely to be worth the effort and are deferred to IDEAS, to be revisited only if measurement
later proves a specific software bottleneck.
**So Phase 2b is reduced to ONE thing:** confirm the per-recipe test sequence already uses the
**minimum number of deploys** — and fix it if it doesn't — **without weakening any test**. (Operator's
expectation: we have probably already done this via the deploy-once / deploy-sharing design.)
## 1. Mission
Verify that a recipe's full test sequence does **not** redeploy more than necessary, and document the
deploy budget. Reuse a single deployment across the stages that can safely share one; only deploy
again where a stage genuinely requires a distinct deployment.
## 2. Definition of Done (Adversary cold-verifies → REVIEW.md)
- [ ] **B1 — Deploy budget is documented and minimal.** Write down, per recipe run, exactly how many
`abra app deploy`/`upgrade` cycles happen and why each is necessary. Expected minimum:
- **one** base deploy shared by **install + functional/custom + backup→restore** (restore
redeploys onto the same app only as the restore mechanism itself requires);
- **one** additional prior-version deploy **only** for the **upgrade** tier (old→new is the
whole point of that tier);
- **one** deploy per declared **dependency** (e.g. an SSO provider), deployed once and reused.
i.e. `deploys == 1 (base) + 1 (upgrade tier) + N_deps` — no extra/redundant redeploys.
- [ ] **B2 — Enforced, not just claimed.** The harness already emits a deploy count and fails on a
mismatch (the DG4.1 `deploy-count != expected` check + the `RUN SUMMARY` `deploy-count` line) —
point to that as the enforcement and confirm `expected_deploy_count` reflects the minimal budget
in B1. If any recipe exceeds it, **remove the redundant deploy** (e.g. collapse a needless
re-deploy between install and functional) and re-verify.
- [ ] **B3 — No test weakened to save a deploy.** Every stage still runs its real assertions and real
isolation/teardown; sharing a deployment must not skip or soften any check. Adversary confirms
from a cold start that suite coverage is unchanged — only the deploy count is reduced/confirmed.
- [ ] **B4 — Recorded.** A short note (`docs/perf/deploys.md` or DECISIONS.md) states the confirmed
per-recipe deploy budget and that it is minimal. If it was already minimal, say so explicitly
(the likely outcome); if a redundant deploy was removed, record before/after counts.
When B1–B4 hold and are Adversary-verified, write `## DONE` to Phase-2b `STATUS.md`.
## 3. Method
1. Read `run_recipe_ci.py`/harness: trace every `abra app deploy`/`abra app upgrade` call across the
stage sequence; count them; map each to a stage and a justification.
2. Compare to the minimal budget (B1). The existing `deploy-count`/`expected_deploy_count` logic is the
reference — verify it equals the minimum and that runs pass it.
3. If over budget on any recipe, eliminate the redundant deploy **without** changing what's tested;
re-run the full suite (Adversary cold-verifies green + isolation intact).
4. If already minimal, document the confirmation and finish — do NOT add speculative perf changes
(those live in IDEAS).
## 4. Guardrails
- **Correctness first:** never weaken/skip/soften a test or break isolation/teardown to cut a deploy.
- **Bounded:** this phase ONLY confirms/fixes deploy count. Any other perf idea → `IDEAS.md`
("Phase-2b empirical performance work"); do not re-import them here.
- **Real abra path** throughout (no docker-level shortcuts).
@@ -0,0 +1,64 @@
# cc-ci Phase 2pc — Sane image-prune policy (retain Docker's local image cache)
**Status:** ACTIVE — a **small interjection into Phase 2** (operator, 2026-05-29). Phase 2
(`plan-phase2-recipe-tests.md`) is **PAUSED at its current progress** (STATUS-2/BACKLOG-2 preserved);
the loops do this short phase, then **Phase 2 resumes automatically**.
**Transition:** auto — on `## DONE` in `machine-docs/STATUS-2pc.md` the watchdog returns to Phase 2.
**Owner:** Builder + Adversary loops. **This file:** `/srv/cc-ci/cc-ci-plan/plan-phase2pc-image-cache.md`
**Phase order:** … 1e → 2w → 2(paused) → **2pc** → 2(resume) → 2b → 3 → 4.
---
## Why (and why a separate registry cache is NOT in scope)
Image handling is the demonstrated hot spot: the Docker Hub rate-limit was hit twice, and
`docker image prune -af` (run to free disk) **wiped cached images mid-run → forced a full cold
re-pull of 12 images → rate limit** (JOURNAL-2).
But the root cause was **over-pruning, not lack of a cache.** On this **single host, Docker's own
local image store already IS the cache** — a pulled image stays, and re-deploys (cold tests, warm
canonical, reboots) reuse the local layers with no re-download; the daemon is PAT-authenticated, so
the residual per-deploy manifest checks sit comfortably under the 200/6h per-account budget. So
**keeping the local store (stop aggressive pruning) recovers ~all the benefit** a cache would give.
A separate `registry:2` **pull-through cache is deliberately OUT of scope** here — its distinctive
wins don't apply to a single authenticated, non-pruning host: multi-node fan-out (we have **one**
node), surviving prune/VM-rebuild on **separate** storage (ours would be co-located, lost on a
recreate anyway), and cache-miss authentication (the daemon is already authenticated). It would add a
registry service + daemon-mirror config + cache GC for marginal gain. **Deferred to IDEAS / Phase 2b**
with a concrete revisit condition (see Guardrails).
## Definition of Done (Adversary cold-verifies → `machine-docs/REVIEW-2pc.md`)
- [ ] **PC1 — Conservative prune policy.** Stop reflexive `docker image prune -af`. **Never prune
during a deploy/test run.** Keep base/in-use images. Prune only **truly-orphaned, old** layers
(dangling + age-gated) and only under genuine disk pressure (now bounded — host 70 GB, ~43 G
free). Wherever the harness/janitor/CI prunes today, make it **surgical**, not `-af`. The
per-run teardown must keep removing the run's app **volumes/secrets/services** (sacred) but
**must NOT remove images.**
- [ ] **PC2 — Local cache retained + authenticated (confirm).** Confirm the Docker daemon stays
**PAT-authenticated** for `docker.io` and that the **local image store is retained across runs,
teardowns, and reboots** — so a repeat deploy of a previously-pulled image **reuses local
layers (no re-download)** and makes at most an authenticated manifest check.
- [ ] **PC3 — Verified + documented.** **Adversary proof:** deploy a recipe, tear it down, redeploy
→ the redeploy **does not re-download image layers** (served from the local store; show via
`docker` events/pull output / a measured pull-time drop), and a normal run no longer evicts
cached base images while disk stays bounded **without** `-af`. `docs/` notes the prune policy;
deviations in `DECISIONS.md`.
When PC1–PC3 hold and are Adversary-verified, write `## DONE` to `machine-docs/STATUS-2pc.md` →
watchdog auto-returns to Phase 2.
## Guardrails / constraints
- **Bounded scope** — prune policy + confirm local-store retention/auth ONLY. Do NOT build a registry
pull-through cache here, and do NOT expand into concurrency/readiness-tuning/dedup (those are
measurement-driven Phase 2b).
- **Real pull path** — no special-casing pulls; abra/swarm pull through the normal authenticated
daemon.
- **Don't weaken any test** — the retained cache must not mask a genuinely-broken image (pinned
versions still resolve correctly; a real new digest still pulls).
- **Registry pull-through cache — DEFERRED (IDEAS / Phase 2b), revisit ONLY if:** (a) cc-ci ever goes
**multi-node**, OR (b) Phase-2b measurement shows **cold-cache / fresh-deploy pull time is a real
bottleneck** (e.g. D8 throwaway-rebuild or fresh-canonical seeding) **AND** the cache is hosted on
**recreate-surviving storage** (an Incus volume / a path on host b1, not the VM's ephemeral disk).
Otherwise it's complexity without payoff on a single host.
@@ -0,0 +1,210 @@
# cc-ci Phase 2w — Warm canonical deployments + `--quick` CI mode (Autonomous Build Plan)
**Status:** ACTIVE — **interjected into Phase 2** by operator decision (2026-05-28). Phase 2
(`plan-phase2-recipe-tests.md`) is **PAUSED at its current progress** (its STATUS-2/BACKLOG-2 state is
preserved); the loops do this phase now, then **Phase 2 resumes automatically** where it left off.
**Transition:** auto — on `## DONE` in `machine-docs/STATUS-2w.md` the watchdog returns to Phase 2.
**Builds on:** the Phase-1d/1e harness (generic suite, deploy-once, override overlays, HC1 upgrade
to PR-head, the sso-dep pattern `plan-sso-dep-testing.md`) and the now-wired Docker Hub auth.
**Owner agents:** Builder + Adversary loops (`plan.md` §6/§7); Adversary cold-verifies.
**This file:** `/srv/cc-ci/cc-ci-plan/plan-phase2w-warm-canonical-quick.md`
**Phase order now:** 1c → 1b → 1d → 1e → 2(paused) → **2w** → 2(resume) → 2b → 3 → 4.
---
## 0. Why this phase
Cold-start CI (fresh `abra app new` → deploy → DB-init/first-boot → … → teardown) is slow, and it
re-pays that cost on every run and for every SSO dependency. This phase adds a **warm-data** layer:
keep each app's **data volume** around between runs (Co-op Cloud's `undeploy` frees RAM but keeps
volumes), so a fast `--quick` run can reattach it, upgrade to the PR code, and assert — without the
cold-provisioning cost. A persistent **keycloak** serves SSO-dependent recipes without a fresh
co-deploy each run. A **last-known-good snapshot per app** means a bad PR tested under `--quick` can
never destroy the working state+data — we roll back.
**Terminology (use these terms throughout code/docs/decisions):**
- **live-warm** — actually deployed and running (e.g. keycloak): instant to use, costs RAM.
- **data-warm** — *undeployed* (RAM freed) but its **data volume is retained**, so a later
`abra app deploy` reattaches it and boots warm (skips fresh DB-init/first-boot), costs only disk.
- **cold** — no retained data: fresh `abra app new` + new volume + full lifecycle + teardown that
deletes the volume. The authoritative default.
**Design principles settled with the operator (do not relitigate):**
- **Keep keycloak live-warm; keep everything else data-warm.** Only keycloak (shared dep) + the one
app under test run at a time. RAM stops being the limiter; **disk is the budget** (monitor; bump
only if needed — test fixtures are small).
- **Default `!testme` = full cold** (authoritative; its upgrade tier already exercises PR-upgrade per
1e). **`--quick` is an opt-in flag**, a lower-confidence fast lane.
- **The canonical known-good advances ONLY via cold runs** (esp. the nightly sweep). `--quick` NEVER
promotes the canonical — it consumes it read-mostly and rolls back on failure.
- **Snapshots: raw volume copy taken while UNDEPLOYED** (fast + consistent because nothing is
writing). **One last-known-good per app.**
- Warm volumes + snapshots are **cache, not source** — not in the git/D8 closure; re-seeded by cold
runs, not restored on a VM rebuild.
- **Warm/infra apps (traefik + keycloak) auto-update to LATEST, nightly, with health-gated
rollback** (operator, 2026-05-28). Both are **unpinned** — their reconcilers `abra recipe fetch`
the latest published recipe + chaos-deploy it. A **nightly `nixos-rebuild switch`** runs the
reconcilers so the warm/infra apps roll to latest each night. Because the recipe is fetched at
*activation* (runtime), the **nix closure stays byte-identical** (only the deployed versions float)
— D8 is preserved; the version pin is gone, so the closure is *more* stable, not less.
- **Auto-update is gated TWICE — a pre-deploy safety gate AND a post-deploy health gate:**
- **Pre-deploy (don't even try unsafe upgrades):** only **auto-apply upgrades that don't require
manual intervention** — i.e. non-major (patch/minor) recipe-version bumps with no
manual-migration in their release notes. If current→latest is a **MAJOR bump** or the target's
**release notes flag a manual migration**, **DO NOT auto-upgrade**: stay on the current version
and **PUSH ALERT** with the release notes (operator upgrades manually). A passing health check
does NOT prove a required migration was done, so this gate is independent of health. Lean on
abra's own major-bump caution + the recipe `releaseNotes/`.
- **Post-deploy (for upgrades we DO apply):** record running version as last-good → deploy latest
→ health-check → **healthy: commit (last-good := latest); unhealthy: roll back to last-good +
PUSH ALERT.** For **stateful apps (keycloak / any app with a DB/volume): snapshot the data volume
BEFORE the upgrade and restore it on rollback** (a forward DB migration can make a version-only
rollback fail) — reusing the WC3 known-good-snapshot mechanism. traefik (stateless) = version
rollback only. (Rollback is NOT nix-generation rollback — the swarm app isn't in the generation;
it's built into the reconciler.)
---
## 1. Definition of Done (Phase 2w exit condition)
Terminates when every item holds **and the Adversary has independently cold-verified** (logged in
`machine-docs/REVIEW-2w.md`):
- [ ] **WC1 — Live-warm keycloak (SSO dep), unpinned + self-healing.** A persistent (live-warm)
keycloak runs at a stable domain, **unpinned** (reconciler `abra recipe fetch` latest +
chaos-deploy, matching traefik — drop the `kcVersion` pin; keep the *secret-generate-only-if-
missing* guard + the health-wait). SSO-dependent recipes (per `plan-sso-dep-testing.md`) point
their `setup_custom_tests` at it, create a **per-run namespaced realm+client**, then **delete
that realm** after the run, instead of co-deploying a fresh keycloak. Proven: a dependent
recipe's SSO custom tests pass against the warm keycloak; concurrent dependents don't collide
(distinct realms); leftover realms are reaped.
- [ ] **WC1.2 — Pre-deploy auto-upgrade safety gate (manual-migration → alert, don't auto-apply).**
Before the reconciler auto-applies "latest", it checks the current→latest delta: **auto-apply
only non-major (patch/minor) bumps with no manual-migration release notes.** A **MAJOR
recipe-version bump**, or a target whose **`releaseNotes/` flag a manual migration**, is NOT
auto-applied — the reconciler **stays on the current version and pushes an alert with the
release notes** for the operator to upgrade manually. (Health-pass ≠ migration-done, so this is
independent of WC1.1.) Detection leans on abra's major-bump handling + the recipe release notes.
**Adversary proof:** simulate a major/manual-migration latest → confirm the warm app stays on
current + an alert with the notes fired (no silent auto-upgrade).
- [ ] **WC1.1 — Health-gated deploy-with-rollback in the warm/infra reconcilers (traefik + keycloak).**
Each reconciler: record the running version as **last-good** → fetch+deploy latest →
health-check → **healthy: commit last-good := latest; unhealthy: roll back to last-good +
`PushNotification` alert.** For **stateful apps (keycloak): snapshot the data volume BEFORE the
upgrade; on rollback restore that snapshot + redeploy the prior version** (forward DB migrations
make version-only rollback unsafe) — reuse the WC3 snapshot helper. traefik (stateless) = version
rollback only. **Adversary proof:** force a broken "latest" (simulate) → confirm the warm app
self-reverts to the prior healthy version (keycloak with its pre-upgrade data intact) and an
alert fired; a healthy update commits the new version as last-good.
- [ ] **WC2 — Data-warm canonical model.** A canonical per warmed recipe at a **stable domain**
(distinct from cold per-run `<recipe>-<6hex>` domains), kept **data-warm** (undeployed-when-idle,
volume retained). A small declarative registry/reconciler tracks which recipes are
canonical and **at which commit** their known-good is. Re-warmable from scratch (cache).
- [ ] **WC3 — Known-good snapshots.** For each canonical app, a **raw copy of its data volume(s)
taken while undeployed**, stored under a stable path (e.g. `/var/lib/ci-warm/<recipe>/`),
tagged with the commit it passed on. **One last-known-good retained per app** (prior is
replaced atomically on update). Restore is proven to bring the app back healthy with its data.
- [ ] **WC4 — `--quick` mode.** `runner/run_recipe_ci.py` gains a `--quick` path (flag/env): reattach
the canonical warm volume (`abra app deploy` of the canonical) → **upgrade to PR head** (chaos
redeploy) → run generic UPGRADE + serving + custom assertions (generic-first invariant holds) →
**on PASS:** `abra app undeploy` (keep volume), do NOT alter the known-good; **on FAIL:**
restore the last-known-good snapshot, then undeploy. `--quick` **never promotes** the canonical.
- [ ] **WC5 — Canonical advancement via cold only.** A **green full-cold run on latest** re-snapshots
+ re-tags the canonical known-good (promote-on-green instead of deleting at teardown). A cold
run is the ONLY thing that advances a canonical. Seeding: the first green cold run on latest
makes an app canonical.
- [ ] **WC6 — Nightly: rebuild (warm/infra → latest) THEN full-cold sweep.** A scheduled nightly job,
in order: (1) **`nixos-rebuild switch`** → the warm/infra reconcilers roll traefik + keycloak to
latest, subject to the **WC1.2 pre-deploy gate** (major/manual-migration → hold on current +
alert) and the **WC1.1 health-gated rollback**; (2) the **full cold** suite across enrolled recipes
— refreshing every canonical's known-good (WC5) AND serving as a daily authoritative regression
run, now against the freshly-updated infra. Don't run while a test run is in flight. Mechanism
settled in DECISIONS (systemd timer on cc-ci / Drone cron / bridge), declarative + reproducible.
Bounded by MAX_TESTS (serial is fine — nightly). If the rebuild's health-gate rolled an infra
app back, the alert fires and the sweep still runs against the (healthy) prior version.
- [ ] **WC7 — Trigger + authority + labeling.** Default `!testme` = full cold (unchanged). `--quick`
is opt-in (`!testme --quick`, or a build param) and **never gates merge**. Run results carry
the **mode** (cold vs quick) so a `--quick` pass is distinctly labeled lower-confidence (feeds
Phase 3). Quick requires an existing canonical; if none, it cleanly falls back to (or reports
"no canonical — run cold first").
- [ ] **WC8 — Resource safety + isolation.** Warm-base runs serialize per app (MAX_TESTS honored);
warm keycloak shared safely via per-run realms; **disk monitored** (warm volumes + one snapshot
each) with a documented budget + prune of stale/orphaned warm data; cold-run teardown stays
sacred (deletes its own per-run volumes); warm data is excluded from the D8 reproducibility
closure (documented as cache).
- [ ] **WC9 — Documented + cold-verified, incl. the rollback proof.** `docs/` explains warm/quick;
the Adversary cold-verifies, **including deliberately failing a PR under `--quick` and
confirming the canonical's last-known-good is restored intact (data preserved)**, and that a
`--quick` pass did not move the known-good. No softened tests.
When WC1–WC9 hold and are confirmed, write `## DONE` to `machine-docs/STATUS-2w.md` → the watchdog
auto-returns to **Phase 2** (resume recipe authoring).
---
## 2. The `--quick` flow (reference)
```
PRECOND: a canonical for <recipe> exists (seeded by a prior green cold run); else fall back/repor​t.
1. abra app deploy <canonical-domain> # reattach warm volume -> fast warm boot at known-good commit
2. wait_healthy
3. (deps) point at the warm keycloak; create a per-run realm+client (namespaced)
4. UPGRADE to PR head (abra app deploy --chaos to the PR checkout) # the op, once
5. assert: generic upgrade (reconverge + moved + serving) + recipe overlay + custom (requires_deps)
6a. PASS -> abra app undeploy <canonical-domain> # keep volume; known-good UNCHANGED
6b. FAIL -> restore last-known-good snapshot to the volume; abra app undeploy # roll back, data safe
7. (deps) delete the per-run realm from the warm keycloak
```
Cold run (default, unchanged) seeds/advances the canonical: on a green cold run on latest, snapshot
the (undeployed) volume → replace the last-known-good + tag the commit, and keep the volume as the
new canonical instead of deleting it.
## 3. Milestones (bounded)
- **W0 — Warm keycloak, unpinned + self-healing (WC1, WC1.1).** Highest ROI; unblocks faster SSO
recipe tests for the resumed Phase 2. Includes the health-gated deploy-with-rollback (snapshot
keycloak before upgrade, restore on health-fail + alert); apply the same to traefik (version-only).
- **W1 — Canonical registry + snapshot/restore (WC2, WC3).** Stable-domain warm apps; raw-while-
stopped snapshot + restore; prove restore round-trips data. (Shares the snapshot helper with WC1.1.)
- **W2 — `--quick` mode (WC4, WC7).** Orchestrator path + labeling + fallback.
- **W3 — Nightly rebuild→sweep + cold-advances-canonical (WC5, WC6).** Nightly `nixos-rebuild`
(warm/infra → latest, health-gated) then full-cold sweep; promote-on-green-cold; scheduled job.
- **W4 — Resource/isolation hardening + docs + cold verify incl. rollback proof (WC8, WC9).** Then
`## DONE`.
## 4. Guardrails
- **`--quick` never advances the canonical; only cold does.** Anchors the baseline to verified states.
- **Never lose the known-good** — snapshot before mutate (or rely on the standing known-good); restore
on any quick failure. The rollback proof (WC9) is mandatory.
- **Default stays cold; quick is opt-in + clearly lower-confidence.** Don't let a quick pass read as
full confidence.
- **Snapshot only while undeployed** (consistency). **One last-known-good per app** (disk).
- **Cold teardown stays sacred** (deletes per-run volumes); warm volumes are a managed cache, never
confused with per-run state; warm data excluded from D8.
- **Warm/infra auto-update is health-gated** — a failed "latest" self-reverts to the last-good
version (+ data, for stateful apps) and alerts; never leave the proxy/SSO dep broken silently.
- **Never weaken a test** (cardinal rule). Generic-first invariant holds in `--quick` too.
- **Bounded** — build the mechanism + prove on keycloak + a couple of recipes; do NOT re-warm all
recipes here (the nightly sweep populates canonicals over time).
## 5. Open decisions (log in machine-docs/DECISIONS.md)
- Canonical **stable-domain scheme** (distinct from cold per-run domains) + how the registry/reconciler
is declared.
- **Snapshot storage + format** (raw tar vs reflink/CoW copy) under `/var/lib/ci-warm/`; atomic replace.
- **Nightly sweep mechanism** (systemd timer / Drone cron / bridge) + ordering + disk-prune policy.
- `--quick` **trigger surface** (`!testme --quick` comment vs Drone build param) + the "no canonical
yet" fallback (run cold vs report-and-skip).
- **Disk budget**: measure warm volume + snapshot sizes across recipes; decide if a 30→larger bump is
needed or the warm set stays bounded.
- **Stateful pre-upgrade snapshot consistency (keycloak).** keycloak is *live-warm* (running) at
nightly-upgrade time, but the snapshot rule is "raw copy while UNDEPLOYED." Cleanest: the nightly
keycloak update = **undeploy → raw snapshot → deploy latest → health-check → on fail restore
snapshot + redeploy prior** (the brief nightly downtime makes the snapshot consistent and honors
the WC3 invariant). Confirm this vs an app-consistent backup alternative.
- **last-good version state** for warm/infra apps (where the reconciler records the prior healthy
version to roll back to) — a small state file alongside the snapshot, re-derivable from the running
swarm version label.
- **Manual-migration / major-bump detection (WC1.2).** How to decide "auto-apply vs alert-and-hold":
primary signal = **major recipe-version bump** (coop-cloud `<upstream>+<recipe-semver>`; major
recipe-semver = breaking, matches abra's own major-upgrade caution); secondary = scan the target's
`releaseNotes/<version>.md` for manual-migration markers. Decide the exact rule + whether to parse
`abra app upgrade` output vs compute the delta directly.
@@ -0,0 +1,177 @@
# cc-ci Phase 3 — Beautiful YunoHost-style results (Autonomous Build Plan)
**Status:** QUEUED — starts after Phase 2 (`plan-phase2-recipe-tests.md`) and Phase 2b
(`plan-phase2b-test-performance.md`) reach `## DONE`.
**Transition:** **manual** (operator kicks it off; check in / test between phases).
**Builds on:** Phase 1 (`plan.md` — dashboard `dashboard/`, the `!testme` bridge's PR comment,
the runner, Playwright in the harness) and Phase 2 (the rich per-recipe test taxonomy → meaningful
levels).
**Reference style:** the YunoHost app-CI result comment, e.g.
`https://github.com/YunoHost-Apps/lichenmarkdown_ynh/pull/20#issuecomment-3543928229` — see §3.
**Owner agents:** same Builder + Adversary loops + protocol as Phase 1 (`plan.md` §6/§7).
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase3-results-ux.md`
---
## 0. Relationship to earlier phases
Phase 1 gave us a *functional* results surface (Drone's per-run logs, a basic overview dashboard, and
a PR comment with run URL + pass/fail — D7). Phase 2 gave us a *rich, layered* test taxonomy per
recipe (install / upgrade / backup-data-integrity / recipe-specific / SSO-integration / recipe-local).
Phase 3 makes the results **beautiful and YunoHost-style**: a computed **level** per run, an
**image-forward PR comment** (status badge + a rendered summary card with an app screenshot), and a
**polished overview dashboard** comparable to `ci-apps.yunohost.org`. It is presentation +
level-scoring on top of existing data — it must **not** change what the tests assert.
Do not start until Phase 2 `STATUS.md` shows `## DONE` (Adversary-verified). Same loop protocol.
---
## 1. Mission
Turn cc-ci results into something a maintainer is happy to see on a PR and on a status page:
- a **level** (0–N) summarizing how far up the quality ladder the recipe got,
- an **image-forward PR comment** like YunoHost's (🌻 + status badge + summary image that includes a
screenshot of the actually-deployed app), linking to the full run,
- a **dashboard** that looks and feels like the YunoHost app list (per-recipe level badges, latest
status, screenshots, history).
---
## 2. Definition of Done (Phase 3 exit condition)
Terminates only when every item holds **and the Adversary has independently re-verified each within
24h** (logged in `REVIEW.md`):
- [ ] **R1 — Level ladder.** A documented level ladder (§4.1) maps which test sets passed → a single
integer **level**, computed per run. Missing a lower rung caps the level (YunoHost semantics).
- [ ] **R2 — Image-forward PR comment.** On a `!testme` run, the bridge posts/updates a Gitea PR
comment in the YunoHost shape: a marker (🌻), a **status/level badge**, and a **summary image**,
both linking to the full run/dashboard. Re-running updates the same comment.
- [ ] **R3 — Summary card image.** Each run renders a PNG summary card showing: recipe + version,
the **level**, a per-stage/per-test **✔/✘ breakdown**, and an embedded **screenshot of the
deployed app**. Served at a stable URL; embedded in the comment and the dashboard.
- [ ] **R4 — App screenshot.** The runner captures a real screenshot of the deployed app (Playwright,
reusing the Phase-1 harness) — post-login where the landing page requires it — for the card.
- [ ] **R5 — Dashboard polish.** The overview at `ci.commoninternet.net` looks/feels like
`ci-apps.yunohost.org`: a table/grid of recipes with **level badge**, latest pass/fail, last
tested version, app screenshot/thumbnail, and a link to history. Regenerated on completion.
- [ ] **R6 — Badges.** A per-recipe **level/status badge** endpoint (SVG) embeddable in recipe
READMEs and the dashboard.
- [ ] **R7 — Safe & robust.** No secrets in images, comments, badges, or screenshots (reuse Phase-1
§4.4 redaction; the screenshot step must not capture secret values — e.g. don't shoot pages
showing generated admin passwords). Image/screenshot generation **never blocks or fails the
pipeline**: on error it falls back to a text comment + records the failure, and the test verdict
is unaffected.
- [ ] **R8 — Docs.** `docs/` explains the level ladder, how the card/screenshot/badge are generated,
and how to embed a badge.
When R1–R8 hold and are Adversary-verified, write `## DONE` to Phase-3 `STATUS.md`.
---
## 3. Reference: the YunoHost comment style
The linked YunoHost CI comment is deliberately **minimal and visual** (verified by fetching it):
- A header marker (🌻).
- A **shield-style test badge** linking to the CI job (`ci-apps.yunohost.org/ci/job/<id>`).
- A **summary image (PNG)** — a rendered card with the result/level — also linking to the job.
- **No verbose inline table**; the per-test breakdown + level live *inside the rendered image* and on
the dashboard. Users click through for full logs.
Mirror this shape for cc-ci (Gitea renders markdown images in comments): marker + badge + summary
PNG, both linking to the cc-ci run/dashboard. YunoHost also shows a **screenshot of the app** — we do
the same in the card.
---
## 4. Design
### 4.1 The level ladder (proposed default — finalize in `DECISIONS.md`)
A single integer; each rung requires all lower rungs (a gap caps the level, like YunoHost):
- **L0** — install failed / app never became healthy.
- **L1 — Installs:** deploys and passes health/readiness.
- **L2 — Upgrades:** previous published version → PR version, stays healthy, data intact.
- **L3 — Backup/restore:** seeded data survives backup → wipe → restore (real data-integrity, P4).
- **L4 — Functional:** the recipe-specific functional tests pass (Phase-2 parity + ≥2 specific).
- **L5 — Integration:** SSO/OIDC and cross-app integration tests pass (for recipes that have them;
recipes with no integration surface cap at L4 by definition — record this so the level is fair).
- **L6 — Recipe-local:** the recipe repo's own `tests/` (D4) pass and are merged.
(Also surface, as badges/flags rather than levels: clean-teardown ✔, no-secret-leak ✔ — these are
gating invariants from Phase 1, shown but not part of the climb.)
### 4.2 Data flow
```
run_recipe_ci.py emits a structured results.json per run
{ recipe, version, pr, stages:[{name,status,tests:[{name,status,ms}]}], level, screenshot.png }
│
├─► summary-card renderer: HTML template (recipe, level badge, ✔/✘ table, app screenshot)
│ → render to PNG (Playwright screenshot of the HTML, reusing the harness browser)
│ → publish at ci.commoninternet.net/runs/<id>/summary.png (+ badge.svg)
│
├─► bridge updates the Gitea PR comment: 🌻 + [badge] + [summary.png], linking to the run
│
└─► dashboard generator: overview grid (per-recipe level badge, screenshot, last status,
version, history) regenerated on build-completion → ci.commoninternet.net
```
- **Summary image:** render an HTML results card → PNG via Playwright (already in the harness — no
new heavy dep). Keep a deterministic template; embed the app screenshot.
- **App screenshot:** Playwright navigates the live `<recipe>-pr<n>-<sha>.ci.commoninternet.net`
(logging in via the test user where needed) and screenshots the main view — captured during the
run while the app is up, before teardown.
- **Badges:** generate SVG (shields-style) per run + a per-recipe latest-level badge endpoint.
- **Hosting:** the dashboard service (Phase-1 `dashboard/`) serves `/runs/<id>/...` and `/badge/...`;
Gitea comments embed them by URL.
### 4.3 PR comment (YunoHost-shaped)
On run start: a placeholder comment ("⏳ testing … level pending", link to live logs). On completion:
update the same comment to 🌻 + level/status **badge** + **summary card image**, linking to the run
and the dashboard. One comment per PR, updated in place; re-`!testme` refreshes it.
---
## 5. Milestones (each ends with an Adversary gate)
- **U0 — Results schema + level.** `run_recipe_ci.py` emits `results.json` (per-stage/per-test) and
computes the level (§4.1). *Accept:* level is correct for a recipe that passes through L4 and one
that fails at L2 (capped).
- **U1 — App screenshot.** Harness captures a real screenshot of the deployed app (post-login where
needed), secret-safe. *Accept:* screenshot of a sample recipe shows the working UI, no secrets.
- **U2 — Summary card + badge.** Render the HTML card → PNG (level, ✔/✘ table, screenshot) + SVG
badge, served at stable URLs. *Accept:* card + badge render correctly for pass and fail runs.
- **U3 — YunoHost-style PR comment.** Bridge posts/updates the image-forward comment (marker + badge
+ card, linked). *Accept:* live on a scratch PR — comment shows badge + card + screenshot, updates
on re-run, contains no secrets.
- **U4 — Dashboard polish.** Overview grid with per-recipe level badges, screenshots, status, version,
history — comparable look/feel to `ci-apps.yunohost.org`. *Accept:* matches reality across several
runs; Adversary confirms it mirrors the underlying results.
- **U5 — Badges + docs + hardening.** Embeddable per-recipe badges; docs for the ladder + embedding;
fallback-to-text on render failure; secret-scan over images/screenshots/comments. *Accept:*
Adversary's leak scan over published images/comments finds nothing; killing the renderer degrades
gracefully to text without affecting the verdict; flip Phase-3 `STATUS.md` to `## DONE`.
---
## 6. Guardrails (inherit Phase 1 §9 + Phase 2 §7.1)
- **Presentation never changes the verdict.** The level and card *report* test outcomes; they must
not let a run look greener than its tests. The Adversary checks the rendered level/card against the
raw `results.json` and the actual test outcomes — a card that overstates the result is a FAIL.
- **No secrets in any artifact** (R7) — comments, badges, summary cards, app screenshots. The
screenshot step must avoid pages that display generated credentials.
- **Never block the pipeline on cosmetics** — image/screenshot/badge generation failures degrade to a
text comment and a recorded warning; they never fail or hang a test run (respect Phase-1 timeouts).
- **Don't weaken tests to raise a level** (carry-over of the cardinal rule) — the Adversary watches
for tests softened or levels mis-mapped to inflate the displayed quality.
---
## 7. Open decisions (log in DECISIONS.md)
- Exact level ladder + how recipes without an integration/SSO surface are scored fairly (cap vs N/A).
- Summary-card rendering: HTML→Playwright-PNG (default, reuses the harness) vs a dedicated image lib.
- Where app screenshots are hosted/retained and for how long (retention/cleanup, like run logs).
- Badge implementation: self-rendered SVG vs a shields.io endpoint pattern.
- Whether to also post a compact markdown fallback table beneath the image for accessibility.
@@ -0,0 +1,113 @@
# cc-ci Phase 4 — Final review, polish & cleanup (capstone) (Autonomous Build Plan)
**Status:** QUEUED — the **LAST** phase, runs after Phase 3 (`plan-phase3-results-ux.md`). A bounded
final review/lint/cleanup pass over the **entire** codebase as it stands after all phases, ending in a
**full cold re-verification that nothing regressed**.
**Transition:** auto (last in the launcher sequence); after it, the whole build is done.
**Builds on:** everything — Phase 1 + 1c + 1b + 1d + 1e + 2 + 2b + 3 (flake/`nix/` modules, the
runner/harness + generic suite + recipe overlays, the comment-bridge, Drone, the dashboard/results
UX, docs, `machine-docs/`).
**Owner agents:** same Builder + Adversary loops (`plan.md` §6/§7); Adversary cold-verifies.
**This file's path:** `/srv/cc-ci/cc-ci-plan/plan-phase4-final-review-polish-cleanup.md`
**Phase order:** 1c → 1b → 1d → 1e → 2 → 2b → 3 → **4 (final)**.
---
## 0. Why this phase (and why it's bounded)
This is the analogue of Phase 1b, but final and whole-codebase. By now the tree has grown a lot —
recipe overlays (Phase 2), performance changes (2b), and results/dashboard UX (3) — all layered on
the foundation. Before calling the build done, do one **bounded** pass to clean and harden it, and —
critically — **re-verify from a cold start that none of the growth/cleanup regressed any earlier
guarantee.** Same discipline as 1b: **good-enough + enforceable**, style→tooling, judgment→checklist,
don't reopen settled design, and **never weaken a test** to satisfy a nit.
---
## 1. Definition of Done (Phase 4 exit condition)
Terminates when every item holds **and the Adversary has independently cold-verified** (logged in
`machine-docs/REVIEW-4.md`):
- [ ] **F1 — Lint/format green across the whole codebase.** Re-run the 1b toolchain (alejandra/
statix/deadnix, ruff, shellcheck/shfmt, yamllint) over everything added since 1b (Phase-2
overlays, 2b changes, 3 UX/dashboard); extend the lint config to any new languages/areas (e.g.
dashboard front-end) so it's covered going forward. The `.drone.yml` lint stage still passes
from a clean checkout; prove with a break-it probe.
- [ ] **F2 — White-box review checklist over all post-1b code.** Run the §3 checklist; fix every
**blocking** finding, triage advisories to `BACKLOG`/`IDEAS`. Findings + resolutions in
`machine-docs/REVIEW-4.md`.
- [ ] **F3 — Cleanup.** Remove dead code/scaffolding and stale TODOs; consistent naming/structure;
reconcile `machine-docs/` (BACKLOG/IDEAS/DECISIONS current, no contradictions); docs match the
final state. No behavior change beyond what F2 mandates.
- [ ] **F4 — FULL cold re-verification (the final gate).** *After* F1–F3 land, the Adversary
**independently re-verifies every prior Definition-of-Done from a cold start**, to the same bar
each phase used — fresh PASS + evidence + timestamps in `machine-docs/REVIEW-4.md` within 24h,
**nothing weakened/skipped/softened** by the cleanup:
- **Phase 1 D1–D10** (incl. the genuine **D8** byte-identical fresh-clone rebuild + a
category-spanning live `!testme` e2e through the public gateway).
- **Phase 1c C1–C7** (secrets-in-git, cert-in-sops, honest reproducibility).
- **Phase 1d DG1–DG8** (generic install/upgrade/backup/restore, deploy-once `DG4.1`, override
floor) **as amended by 1e**.
- **Phase 1e HC1–HC3** (upgrade→PR-head via `deploy --chaos`; repo-local gated to approved
recipes; generic-by-default + explicit opt-out).
- **Phase 2** recipe-coverage criteria (every enrolled recipe's overlays/ported tests real,
DRY, green).
- **Phase 2b** performance claims (the measured improvements still hold; no test weakened to
get them).
- **Phase 3** results/level/UX criteria (per-run level honest, PR comment + dashboard correct).
- [ ] **F5 — Documented + cold-verified.** Final `docs/` accurate (install reproduces from scratch;
enroll-recipe + overlay/approval flow correct); accepted deviations in `DECISIONS.md`; the
Adversary confirms F1–F4 with no standing VETO and no open `[adversary]` finding.
When F1–F5 hold and are confirmed, write `## DONE` to `machine-docs/STATUS-4.md` — the build is
complete.
---
## 2. Method
1. **Lint/format first** (F1) — re-run + extend; auto-fix style, don't deliberate.
2. **Review checklist** (F2, §3) — classify blocking vs advisory; fix blocking, triage rest.
3. **Cleanup** (F3) — dead code, naming, docs, `machine-docs/` reconciliation.
4. **Full cold re-verification LAST** (F4) — once everything has landed, the Adversary re-runs the
entire cross-phase acceptance from cold. Order matters: tooling → review/fixes → cleanup → *then*
full re-verify. Cleanup must regress nothing.
5. **Bound it** — a pass, not a rewrite; record dead-ends/deviations and stop.
## 3. White-box review checklist (teeth, not taste) — whole codebase
Blocking unless noted (plan-relevant invariants visible only by reading code):
- **Tests are real** (blocking) — every generic/overlay/custom test asserts actual app state; no
`skip`/`xfail`/can't-fail; per-op `pass/fail/skip` honest; the 1d/1e anti-vacuous guards
(`assert_serving` routing proof, `do_upgrade` "moved", deploy-count==1) intact.
- **1e corrections intact** (blocking) — repo-local code still gated to approved recipes; generic
still runs by default (opt-out explicit); upgrade still targets the PR head.
- **Generic-first / custom-additive invariant** (blocking — `docs/testing.md`). Confirm no path
makes the generic tier depend on custom: deps deploy + `setup_custom_tests` run **after** all
generic tiers, never before; a forced `setup_custom_tests` failure still yields a clean
generic-tier `pass/pass/pass/pass` + `skip(deps-not-ready)` for `@requires_deps` custom tests
(re-exercise the forced-failure case). Future maintainers must be able to operate cc-ci with
the generic tier alone — verify that path stays viable.
- **Harness DRY** (blocking-ish) — recipe quirks are data (`recipe_meta.py`), not shared-harness
conditionals; overlays are thin; no per-recipe copy-paste of lifecycle logic.
- **Server state Nix-declared & idempotent** (blocking) — no imperative drift / run-once sentinels /
manual post-rebuild steps; the `nix/` layout clean.
- **No footguns** (blocking) — no bare `sleep` for readiness (poll); teardown in `finally`; secrets
reused per run not regenerated; no hardcoded versions/domains that break upstream.
- **No secrets in code/committed files** (blocking) — grep source/configs/`.drone.yml`/fixtures;
log/dashboard redaction real (incl. any new Phase-3 UX surface that echoes run data).
- **Phase-3 UX correctness** (advisory→blocking on real drift) — the displayed level/badge/screenshot
reflect the true per-op results; no misleading "pass".
- **Architecture matches the plans; deviations in `DECISIONS.md`** (advisory→blocking on real drift).
- **Readability & docs** (advisory) — clear names, dead code removed, docs reproduce from scratch.
## 4. Guardrails
- **Never weaken a test** to satisfy a lint/review/cleanup nit (cardinal rule wins).
- **Don't reopen settled design** — clean + harden + re-verify; bigger ideas → `IDEAS.md`.
- **Bounded** — one pass; cap iterations; record + stop.
- **Cleanup regresses nothing** — F4 is the proof; if a cleanup breaks a prior guarantee, revert the
cleanup, not the guarantee.
## 5. Open decisions (log in machine-docs/DECISIONS.md)
- Any new linters/formatters for Phase-3 front-end / new areas, and their strictness.
- The precise blocking-vs-advisory split for the §3 checklist on the new code.
- Whether to add Python type-checking now or defer to `IDEAS.md` (carried from 1b).
@@ -0,0 +1,116 @@
# cc-ci Phase 5 — verify the `/recipe-upgrade` + `testme-on-pr.sh` end-to-end flow
**Status:** QUEUED — the **FINAL** phase, after Phase 4. Transition: auto (last in the launcher
sequence); the watchdog STOPS after it (build complete). **Owner:** Builder + Adversary loops
(Adversary cold-verifies); the orchestrator may also drive it.
**This file:** `/srv/cc-ci/cc-ci-plan/plan-phase5-verify-upgrade-flow.md`
**Phase order:** … 3 → 4 → **5**.
---
## 0. Why this is LAST
The `/recipe-upgrade` and `/upgrade-all` skills live in the **orchestration repo**
(`/srv/cc-ci/.claude/skills/`) and drive cc-ci by posting **`!testme` on a recipe PR**
(`testme-on-pr.sh`) and reading the verdict back **from the PR**. That flow only works once cc-ci is
**fully built** — specifically it depends on **Phase 3 (results UX)**: the run's result must be posted
back to the PR (a Gitea commit status and/or result comment on the PR head) for `testme-on-pr.sh` to
read it. So this verification can only run after the CI server is complete. It proves the upgrade
tooling actually works end-to-end **before** the weekly `/upgrade-all` cron is activated
([[cc-ci-upgrade-all-cron]] — activate only after the build is done).
**Use a sandbox recipe for the live runs** (e.g. `custom-html-tiny` or a dedicated throwaway recipe),
and **close every PR opened during verification afterward** — do not pollute real recipe mirrors, and
**never merge** anything.
## 1. Definition of Done (Adversary cold-verifies → `machine-docs/REVIEW-5.md`)
- [ ] **V1 — `!testme` on a recipe PR is the real gate.** Posting `!testme` (as the bot, a
collaborator) on a recipe mirror PR triggers bridge → Drone → harness, runs the suite, and
**posts the run + its result back to the PR** (commit status on the PR head and/or a result
comment, per Phase 3). A `!testme` from a **non-collaborator is rejected**. A bad trigger
(`!testmexyz`) does NOT fire. (Re-uses the existing !testme D-gate evidence.)
- [ ] **V2 — `testme-on-pr.sh` reads the verdict correctly.** `POST=1` posts exactly **one**
`!testme`; `POST=0` polls WITHOUT re-triggering; the helper returns `VERDICT=GREEN` on a passing
PR, `VERDICT=RED` on a failing PR, `VERDICT=PENDING` while in flight, and a `BUILD=<url>` that
points at the Drone build. (Drive a known-green and a known-red PR head.)
- [ ] **V3 — `/recipe-upgrade <sandbox-recipe>` (DEFAULT mode) end-to-end GREEN.** On a recipe with a
real available upgrade: it reconciles the mirror, opens a recipe PR with the bump, `!testme`
runs and **results appear in the PR**, GREEN → `RESULT: SUCCESS`. **Nothing merged.**
- [ ] **V4 — 3-iteration regression loop.** Seed a real upgrade regression (e.g. a deliberately bad
image tag) → `!testme` RED → fix on the recipe branch → re-`!testme` → GREEN, all within **≤3
`!testme` runs**, each recorded in the PR. With a persistent regression, after 3 runs it leaves
the PR open and reports `RESULT: FAILED — upgrade not green after 3 !testme runs` (does not
weaken anything to force green).
- [ ] **V5 — stale-test DEFAULT = comment, no test edit.** With a genuinely stale test for the new
version, default mode (no `--with-tests`) leaves an **explanatory comment** on the recipe PR
(upgrade looks correct; which test is stale + why; "re-run `--with-tests`"), modifies **no
test**, and reports `RESULT: SUCCESS-PENDING-TESTS`.
- [ ] **V6 — `--with-tests` opens + verifies a cc-ci test PR.** The same stale-test case under
`--with-tests` opens a cc-ci test-update PR (dedicated branch, separate clone — never `main`,
never the loops' clones), **verifies the recipe upgrade WITH the test change applied** via the
branch-checkout harness run (`verify-pr.sh`, since `!testme` uses prod tests), pairs the two PRs
with cross-notes, and reports `RESULT: SUCCESS+TESTPR`. Nothing merged.
- [ ] **V7 — mirror reconciliation.** After a run, the `recipe-maintainers/<recipe>` mirror `main` is
**identical to upstream main**; an open PR whose change is already in upstream main is
**auto-closed** (merged-upstream); a superseded open PR is **closed and replaced** by the new
one. (Seed each case and confirm.)
- [ ] **V8 — `/upgrade-all` DEFAULT run.** `--dry-run` lists candidates correctly; a live run over a
small set (1–2 sandbox recipes) opens recipe PRs **using default mode (never `--with-tests`)**,
surfaces "tests look stale" PRs in its own summary section, runs **sequentially with teardown**
between recipes, and the summary leads with the PR list. Confirms the weekly cron never
auto-edits tests.
- [ ] **V8a — the `cc-ci-upgrader` agent.** `cc-ci-plan/launch-upgrader.sh start` spins up a
remote-control `cc-ci-upgrader` session (viewable at claude.ai/code) that runs `/upgrade-all`
(DEFAULT) **to completion, then STOPS and stays idle** (does NOT self-terminate) with the
summary visible. A second `start` while a run is **in flight (busy)** leaves it alone; a `start`
against a **finished/idle (or wedged)** session **kills it and runs fresh**. (Use
`UPGRADER_ARGS=--dry-run` for a cheap check, then a real small-set run.) This is exactly what the
weekly cron invokes — verify the cron-equivalent path end-to-end.
- [ ] **V9 — cleanup.** Every PR opened during verification (recipe + any cc-ci test PR) is **closed**
and any sandbox deploy is **torn down**; the verification `cc-ci-upgrader` session is stopped
(`launch-upgrader.sh stop`); the box is left clean.
## 2. Method / notes
- **Sandbox first.** Prefer `custom-html-tiny` / a throwaway recipe for V3–V8 so real recipe mirrors
aren't spammed. For the seeded-regression (V4) and stale-test (V5/V6) cases, construct the seed on a
sandbox recipe / a scratch branch, not a real upstream recipe.
- **Real path throughout** — real `!testme` → bridge → Drone → harness → results-in-PR; real `abra`.
- The skills are at `/srv/cc-ci/.claude/skills/{recipe-upgrade,upgrade-all,ci-test-review}/`; read
their SKILL.md as the spec for expected behavior.
- If Phase 3's PR-result surface differs from what `testme-on-pr.sh` polls (commit status vs comment),
**reconcile them here** — either adjust the helper to read the real surface, or file a CI finding —
and record the resolution in `DECISIONS.md`. (This is the most likely real gap to find.)
## 3. Guardrails
- **NEVER merge** any PR; **never weaken a test** to make a run pass.
- **Close verification PRs + tear down deploys** when done (V9) — leave no junk.
- **Single-writer:** cc-ci test PRs on dedicated branches + separate clones; never push `main` or
touch the loops' working clones; shared Swarm is stateful — serialize + tear down.
- **Bounded:** this phase VERIFIES the flow; it does not redesign the skills. A real defect → fix the
skill/helper (small) or file it; a bigger idea → `IDEAS.md`.
## 4. On phase completion — install the weekly cron (+1h) and verify it fires
Once V1–V9 pass (the upgrade flow + the `cc-ci-upgrader` agent are proven) AND this is the final phase
(the whole cc-ci build is complete), the **orchestrator** installs the recurring weekly upgrade cron.
This SUPERSEDES the earlier fixed "Sat 03:00 UTC" placeholder — the schedule is now anchored to actual
completion ([[cc-ci-upgrade-all-cron]]).
1. **Schedule = completion + 1 hour, weekly thereafter.** Compute `T0 = now + 1h`; install a **weekly**
job at T0's day-of-week + `HH:MM` (cron `MM HH * * DOW`) so the FIRST run fires ~1h after the build
finishes, then every 7 days at that same slot.
2. **What it runs:** `/srv/cc-ci/cc-ci-plan/launch-upgrader.sh start` (→ spins up the `cc-ci-upgrader`
agent → `/upgrade-all` DEFAULT → stops idle/viewable). The cron environment must have the `claude`
CLI on `PATH`, `tmux` access, and the box logged into the claude.ai account (remote-control) — a
bare cron env is minimal, so set `PATH`/`HOME` explicitly (mirror how `cc-ci-loops.service`
launches). A user crontab / systemd timer / Claude scheduled task are all acceptable mechanisms;
pick one that gives that environment.
3. **VERIFY the first kickoff (the point of this step).**
- Cheap pre-check first: `UPGRADER_ARGS=--dry-run cc-ci-plan/launch-upgrader.sh fresh` (or schedule
a one-off test fire a couple of minutes out) to confirm the launcher path works from the chosen
cron mechanism's environment.
- Then confirm the **real** first fire at T0 (~1h later) actually kicked it off:
`launch-upgrader.sh status` shows `cc-ci-upgrader RUNNING`, it ran `/upgrade-all`, and produced a
summary. If it did NOT fire/launch (PATH, login, mechanism), fix and re-verify.
- Record the installed schedule + the verified-kickoff result in `DECISIONS.md`.
@@ -0,0 +1,44 @@
# cc-ci Phase 6 — reconcile all enrolled recipe mirrors
**Status:** QUEUED — runs after Builder/Adversary phase 5 is complete.
**Owner:** `cc-ci-assistant` session only. Not a Builder/Adversary loop phase.
**This file:** `/srv/cc-ci-orch/cc-ci-plan/plan-phase6-reconcile-all-mirrors.md`
---
## 1. Goal
Bring every enrolled `recipe-maintainers/<recipe>` mirror back into the intended reconciled state
without involving the Builder/Adversary loops. This is a post-build operational cleanup pass, not a
loop-verification phase.
## 2. Definition of Done
- [ ] Enumerate the current enrolled recipe mirrors and the expected upstream source for each.
- [ ] For all mirrors, confirm `main` matches upstream `main` at the intended sync point.
- [ ] Identify stale open PRs where the change is already in upstream main and close them.
- [ ] Identify superseded PRs and replace/close them according to current reconcile behavior.
- [ ] Record the final per-recipe reconcile outcome in a written summary for the operator.
- [ ] Leave no ad-hoc test branches or temporary working copies behind.
## 3. Method
- Use the assistant's own working copies or scratch clones; do not edit the Builder/Adversary loop
clones unless explicitly required.
- Prefer existing reconcile helpers and documented workflows already used by cc-ci.
- Keep changes minimal and operationally reversible.
- If a mirror exposes a genuine product bug instead of a routine reconcile issue, record it clearly
and stop short of risky improvisation.
## 4. Deliverables
- A concise operator-facing summary listing:
- every mirror checked
- any PRs closed/replaced
- any mirror left needing manual attention
## 5. Guardrails
- No loop/watchdog changes are part of this phase.
- No merges without explicit operator instruction.
- No secret values in notes, commits, or summaries.
@@ -0,0 +1,49 @@
# cc-ci Phase 7 — run targeted upgrades on n8n, ghost, and matrix-synapse
**Status:** QUEUED — runs after phase 6.
**Owner:** `cc-ci-assistant` session only. Not a Builder/Adversary loop phase.
**This file:** `/srv/cc-ci-orch/cc-ci-plan/plan-phase7-upgrade-three-recipes.md`
---
## 1. Goal
Run the targeted post-build recipe upgrade work for:
- `n8n`
- `ghost`
- `matrix-synapse`
This is operational recipe-maintenance work and should be driven by the assistant, not the
Builder/Adversary loops.
## 2. Definition of Done
- [ ] Research the current upstream upgrade target for each of the three recipes.
- [ ] For each recipe, determine whether an upgrade is actually available and worth opening.
- [ ] Run the established upgrade workflow for each upgradeable recipe.
- [ ] For each recipe PR opened, verify the expected cc-ci testing path is triggered and record the outcome.
- [ ] Summarize all opened PRs, blocked upgrades, and any follow-up needed from the operator.
- [ ] Leave the assistant session idle and ready for the next assignment when complete.
## 3. Method
- Prefer the existing assistant-accessible upgrade tooling and documented workflows.
- Default to the smallest correct per-recipe change set.
- Keep one clear record per recipe: checked, upgradeable or not, PR opened or not, verified or blocked.
- If a stale cc-ci test is the only blocker, report that explicitly instead of improvising beyond the
established workflow.
## 4. Deliverables
- A summary covering:
- `n8n`
- `ghost`
- `matrix-synapse`
- For each: upstream target, action taken, PR URL if any, verification result, and remaining risk.
## 5. Guardrails
- Never merge PRs.
- Do not use the Builder/Adversary loop clones as the assistant's scratch workspace.
- Record blockers clearly rather than pushing through uncertain migrations.
@@ -0,0 +1,62 @@
# Sub-plan — pre-pull a recipe's images at the start of its test sequence
**Status:** QUEUED — a **small harness addition** to `runner/run_recipe_ci.py` (+ `harness`). Picks up
as a near-term Phase-2 harness unit (not a phase-pause). Auto-applies in the nightly all-recipes run.
**Owner:** Builder + Adversary loops. **This file:** `/srv/cc-ci/cc-ci-plan/plan-prepull-images.md`
---
## What
At the **start of a recipe's test sequence — before the first `abra app deploy`** (and before the
**upgrade tier's** new-version deploy) — resolve the recipe's images and `docker pull` them so they
are in the local store before the deploy runs.
```
# at the top of the per-recipe run, after `abra app new` + checkout + .env set:
imgs = docker compose --env-file <app .env> -f <COMPOSE_FILE> config --images # resolves interpolation
for img in imgs:
docker image inspect "$img" >/dev/null 2>&1 || docker pull "$img" # skip-if-present (pinned tags)
# then the normal: abra app deploy … (unchanged — real abra)
# repeat the pre-pull for the UPGRADE target image set before `abra app upgrade`.
```
## Why
- **Separate "pull" from "converge."** A rate-limit / bad-tag / slow-pull then **fails fast and
clearly as a pull error**, instead of surfacing later as a murky `not converged` deploy timeout
(the F2-12-class confusion).
- **Faster, more reliable convergence.** Images already local → swarm starts services immediately →
the deploy fits **abra's native convergence window** better (supports "prefer abra convergence" —
can reduce the `-c`/READY_PROBE workaround for *pull-bound* cases).
- **Nightly:** the all-recipes nightly run pre-pulls implicitly, warming the cache for everything.
## Cheap on a warm cache (the key property)
`docker pull image:tag` **does not re-download cached layers** — it does a cheap manifest check and
reports `Already exists`; only missing/changed layers download. With coop-cloud's **pinned**
(immutable) tags, the **skip-if-present** check (`docker image inspect`) makes it **zero network**
when already cached. So per-test pre-pull is near-free after the first/nightly pull; it only does
real work on a cold image or an upgrade to a genuinely new version.
## Honest caveats
- **Removes *pull* time/variance from convergence, NOT *app-init* time.** Slow-starting apps
(collabora's heavy init, F2-12) still need the **recipe healthcheck/`start_period`**
(`plan-lasuite-drive-recipe-pr.md`). Pre-pull is complementary, not a replacement.
- **Resolve via `docker compose config --images`** (handles `$VERSION`-style interpolation) using the
**same `COMPOSE_FILE` set abra uses** (read from the app `.env`) — a naive `grep image:` misses
interpolated tags and multi-compose recipes.
- **Not an abra bypass.** `docker pull` only warms the local store; the deploy is still real
`abra app deploy`/`upgrade`. Consistent with the "real abra commands" guardrail.
- **Don't weaken anything** — a failed pre-pull is a real (clearer) test failure, reported as such.
## Definition of done (Adversary cold-verifies)
- [ ] Pre-pull step runs at the start of the recipe sequence (before the deploy) **and** before the
upgrade tier's new-version deploy; images resolved correctly (incl. interpolation, multi-compose).
- [ ] **Cheap on warm cache:** a 2nd run's pre-pull does **no layer re-download** (skip-if-present, or
`Already exists`); proven.
- [ ] **Clear failure mode:** a pull failure (e.g. a deliberately-bad tag) is reported as a **pull
error before deploy**, not as a deploy/convergence timeout.
- [ ] No test weakened; deploy path unchanged (real abra). Bounded — this one step only.
## Scope note
Per-test pre-pull only (at the recipe sequence start + upgrade). NOT a boot-time "pull all enrolled
recipes" sweep — the local cache already accumulates across runs and the nightly all-recipes run
warms everything, so per-test is the simple, targeted form.
@@ -0,0 +1,59 @@
# Runbook — fix `proxy` overlay VIP exhaustion (durable) + empirical verification
**Owner: ORCHESTRATOR** (host/swarm infra, not a recipe/test change). Execute **after the current
weekly upgrade run finishes** (the box must be quiescent — recreating `proxy` disrupts traefik
routing for every live service). Do NOT run mid-upgrade.
## Root cause (empirically verified 2026-06-12, from dockerd logs)
- The shared **`proxy` overlay network** (ID was `ab54…`) is **`10.0.1.0/24` = 254 VIPs**. EVERY
recipe deploy joins it (traefik routing).
- Under concurrent stack `rm`, Swarm's endpoint GC races (`Unable to complete atomic operation,
key modified` / `network proxy remove failed`) and **leaks endpoints → leaks IPs** (45 such
errors over the day). `dockerd` had **11 days** uptime accumulating leaks.
- The pool exhausted → **13× `could not find an available IP while allocating VIP`** (first 22:53,
straddling both wedges) → new services' tasks stuck in Swarm **`New`** state (never scheduled).
- The 02:50 docker restart rebuilt the allocator and reclaimed everything → healthy.
- This presents as a recipe FAILURE (discourse, ghost both "failed") but is purely infra.
## The fix (durable): enlarge the `proxy` subnet
`nix/modules/swarm.nix:~43` creates it with no `--subnet` (defaults to a /24):
```
docker network create --driver overlay --attachable proxy
```
Change to a **/16** (≈65,534 VIPs, ~258× headroom — the leak can't reach it before a routine
reboot/`nixos-rebuild` resets the allocator). Pick a block clear of `ingress` (10.0.0.0/24) and the
current proxy (10.0.1.0/24); the default-addr-pool is 10.0.0.0/8, so use e.g. **`10.10.0.0/16`**:
```
docker network create --driver overlay --attachable --subnet 10.10.0.0/16 proxy
```
## Procedure
1. **Pre-req:** weekly upgrade run done; `docker stack ls` shows only infra + `warm-*`.
2. **EMPIRICAL BEFORE — measure the leak.** Baseline `proxy` endpoint/IP count, then deploy +
*concurrently* `rm` N (~10) throwaway published-port stacks; re-count. Show endpoints/IPs do NOT
return to baseline (leak), and grep dockerd for fresh `key modified`/`network proxy remove`
errors. Record the per-cycle leak rate → projects the /24 exhaustion time.
3. **Edit `nix/modules/swarm.nix`** — add `--subnet 10.10.0.0/16` to the proxy create (commit to
the cc-ci repo; this is infra/nix, orchestrator-authored, push to git.autonomic.zone).
4. **Recreate `proxy` on the host (DISRUPTIVE):** the network can't be resized in place. Either
`nixos-rebuild` after temporarily removing proxy, or manually: detach services / `docker stack
rm` the live recipe stacks (none mid-upgrade), `docker network rm proxy`, recreate with the /16,
then redeploy/reconcile traefik + the `ccci-*` control plane + `warm-*` so they rejoin. Verify
traefik routing, drone, dashboard, bridge, reports all healthy.
5. **`nixos-rebuild switch`** so the /16 persists across reboots (sync `/root/cc-ci` first, per the
host-deploy mechanism).
6. **EMPIRICAL AFTER — prove it.** Re-run step 2's reproduction: confirm (a) `proxy` now reports a
/16 with vast headroom, (b) `docker network prune -f` reclaims the leaked per-stack overlays,
(c) the leak no longer approaches exhaustion. Confirm a fresh recipe `!testme` deploys clean (no
`New`-state hang).
## Acceptance
`proxy` is a /16 (pinned in swarm.nix, survives rebuild); reproduction shows the leak is bounded
far below the new ceiling; the upgrade Step-0 guard (prune + VIP-failure docker-restart, already
added to the skill 2026-06-12) remains as the per-run safety net. Then delete the
[[proxy-vip-exhaustion-runbook]] memory.
## Guardrails
- Maintenance window only (recreating proxy = brief routing outage for ALL services). Never during
a live upgrade or phase run. No secrets in commits. Author `autonomic-bot
<autonomic-bot@noreply.git.autonomic.zone>`; push after commit.
@@ -0,0 +1,87 @@
# Plan — `/recipe-report` skill + report.ci.commoninternet.net
**Status:** IMPLEMENTED 2026-06-02 — serving live at https://report.ci.commoninternet.net; skill
`recipe-report` + helper `cc-ci-plan/recipe-report.py` + launcher `cc-ci-plan/launch-report.py`
(REPORT_MODEL default opus); upgrade-all launches the report as its closing step. **Created:** 2026-06-02.
**Goal:** after the weekly `/upgrade-all`, generate a public HTML **"Recipe Report"** that reviews how
the upgrade went and the state of every recipe + open PR — served at **report.ci.commoninternet.net**,
one page per week, with a home-page index of all reports.
## Why it's cheap to build
The serving model already exists (dashboard): a Nix-built image → Swarm service → traefik
`Host(...)` + wildcard TLS, bind-mounting a host dir read-only. We mirror it for reports.
- **DNS:** `report.ci.commoninternet.net` already resolves (wildcard `*.ci.commoninternet.net` → the
host) — **no operator DNS step.**
- **TLS:** the same wildcard cert (`/var/lib/ci-certs/live/`) that serves ci./drone./backups. covers
`report.ci.*` — **no cert step** (confirm at deploy).
- **Data:** `/upgrade-all` already writes `/srv/cc-ci/.cc-ci-logs/upgrades/upgrade-all-<date>.md`; open
PRs + CI verdicts come from the Gitea/Drone APIs (creds in `.testenv`).
## A. Serving infra — new `nix/modules/reports.nix` (cc-ci product repo)
A tiny static-file server mirroring `dashboard.nix`:
- Image: `nginx:alpine` (or reuse the dashboard's Python `http.server`), content-hash tag, deployed by a
`deploy-reports.service` reconcile oneshot (same pattern as dashboard/bridge).
- Bind-mount **`/var/lib/cc-ci-reports`** (read-only) as the web root.
- traefik labels: `Host(`report.ci.commoninternet.net`)`, entrypoint `web-secure`, `tls=true`.
- Web root layout: `index.html` + `week-<YYYY-MM-DD>.html` (one per report). **Public, unauthenticated.**
- *(Lighter alternative: add a second traefik router `Host(report.ci…)` → the existing `ccci-dashboard`
service and serve `/var/lib/cc-ci-reports` from `dashboard.py`. Recommend the separate server for clean
decoupling.)*
## B. The skill — `.claude/skills/recipe-report/` (orchestrator repo)
A SKILL.md (LLM-driven review + HTML generation) + a helper script for the deterministic survey/scaffold.
- **Runs as its OWN agent session — model independent of the upgrader.** The report must use a model
configured **separately** from the upgrader, so it canNOT be a step inside the sonnet upgrader session.
A new `launch-report.py` (mirroring `launch-upgrader.py`) starts a `cc-ci-report` session on
**`REPORT_MODEL` (default `opus`)** / `REPORT_BACKEND` (default `claude`) — independent of the
upgrader's `sonnet`. **Initial config: upgrader = sonnet, report = opus.** It's launched right after the
weekly `/upgrade-all` completes (the weekly job launches the report agent as its final step / a
follow-on). It reads the dated summary + PR/CI state from disk + the APIs, so it needs none of the
upgrader's in-context state.
- **Inputs:** the dated `upgrade-all-<date>.md` summary; open PRs per recipe (Gitea API); each recipe's
current vs latest version + CI verdict (Drone); the **previous** week's report (to note "new since last
week"). Runs from the orchestrator; writes the HTML to `cc-ci:/var/lib/cc-ci-reports` over ssh.
- **Review/judgment (the skill's job):** summarize the run (green / stale-test / failed / skipped counts,
notable regressions), then **classify** every item into:
- **Needs attention** — PRs ready to merge (GREEN), and errors/failures to investigate.
- **Routine** — minor bumps, stale-test (needs `--with-tests`), up-to-date / skipped-by-design.
## C. HTML output (per-week page + index)
Each `week-<date>.html`:
- **Title:** "The Recipe Report" · **Subtitle:** "Week of <date the report was run>".
- **① Needs attention** (top, prominent): important PRs to merge + errors to look into — short prose per
item with the PR/build link.
- **② Routine** (below): the less-important items (minor upgrades, stale-test, skipped) — compact.
- **③ Comprehensive table** (bottom): every recipe → `current → target` · upgrade status · CI verdict ·
open PR (link) · notes.
- **CI results: LINK only, no embedded images.** For each run, show its level/result as a number / short
info string (e.g. `level 8 ✓` or `RED · restore`) and hyperlink to the Drone build + dashboard summary —
do **not** embed the summary-card images.
- **Footer:** generated timestamp, link to the live dashboard (ci.commoninternet.net), link back to the index.
`index.html` (home): "The Recipe Report" + a reverse-chronological list of all weekly reports (date +
one-line headline), each linking to its page. The skill **regenerates the index** each run.
Styling: self-contained, inline CSS, clean + mobile-friendly, no JS (fully static).
## D. Public-safety (unauthenticated page)
- Include only public-safe data: recipe names, version bumps, PR titles + links, CI verdicts, concise
error summaries. **No secrets, tokens, internal IPs, or raw logs** (summarize — never dump logs that
could contain generated app secrets; the build already redacts, but the report must not re-introduce).
- PR links point to the private `git.autonomic.zone` mirror — viewers need access to follow them; the
report's prose must stand on its own.
## E. Definition of Done
1. `reports.nix` deployed; `https://report.ci.commoninternet.net/` serves the index over TLS.
2. `/recipe-report` skill generates `week-<date>.html` (3 sections + full table) and regenerates `index.html`.
3. Wired to run automatically after the weekly `/upgrade-all`; produces a report end-to-end on the next run.
4. Page is public-safe (no secrets); renders cleanly on desktop + mobile.
5. NOT merged anything; the report only *reports* (read-only on PRs/CI).
## F. Decisions
- **Report model is separately configurable** — `REPORT_MODEL` (default **`opus`**), independent of the
upgrader (`sonnet`). The report runs as its own `cc-ci-report` agent (per §B). ✓ (operator-set)
- **CI results: link only**, with the level/result shown as a number/info string — no embedded images. ✓
(operator-set)
- Static server: `nginx:alpine` new stack (recommended) vs extend the dashboard. *(open)*
- Retention: keep all weekly reports indefinitely (tiny static HTML) — assumed yes. *(open)*
@@ -0,0 +1,120 @@
# Plan — Recipe Report: TESTS + live PR-STATUS column
Goal (operator request): in the weekly Recipe Report table,
1. **rename the current `Status` column → `TESTS`** (it shows the test/CI verdict: GREEN/FAILED/STALE/SKIPPED/UPTODATE — unchanged content, new label),
2. **add a new `STATUS` column** showing the live state of the recipe's PR — **`open`** (still to review) vs a **✓** for **any state that is not open** (merged OR closed-without-merge both show ✓; no separate "closed unmerged" treatment — operator-decided),
3. the PR state is fetched **client-side with JavaScript so it updates in realtime** (a visitor sees the current state, even on an archived past report),
4. to support (3), **make the recipe repo mirrors public** (operator: this is fine).
> **Operator decisions (locked):** (a) STATUS is binary — `open` vs ✓ (not-open). (b) The realtime
> proxy goes on the **cc-ci server via nix**, in the SAME stack/way the report itself is served
> (`reports.nix`) — NOT a separate service. (c) Exclusion set for the public flip confirmed: make the
> recipe mirrors public; keep `cc-ci-secrets`, `cc-ci-orchestrator`, `archived-cc-ci-orchestrator`,
> and `cc-ci` private.
## Findings that shape the plan
- The table is built by `cc-ci-plan/recipe-report.py::_table`. Current columns:
`Recipe | Change | Status | CVEs | CI | PR | Notes`. The `Status` cell carries a CSS class
`s-GREEN`/`s-FAILED`/… (colour); the `CI` cell is the build number+link; `PR` is `#n`+link.
The page is a **self-contained HTML** file (`_page`) served statically by the `ccci-reports`
nginx stack at `https://report.ci.commoninternet.net`.
- **Gitea CORS:** git.autonomic.zone has CORS middleware enabled, but it does **not** return
`access-control-allow-origin` for `report.ci.commoninternet.net` (origin not in the instance's
`[cors] ALLOW_DOMAIN`). That allow-list is autonomic.zone **instance config we don't control**, so a
direct browser→Gitea API fetch will be **blocked by CORS**. → use a **same-origin proxy** (below).
- **Mirror repos:** 25 repos under `recipe-maintainers`, **all private**. This set includes repos that
must **NOT** be made public:
- `cc-ci-secrets` (secrets!), `cc-ci-orchestrator` + `archived-cc-ci-orchestrator` (operational
plans/journal), and arguably `cc-ci` (the harness/infra). **Exclude these.**
- The **recipe mirrors** that SHOULD go public (they mirror public coopcloud recipes): bluesky-pds,
cryptpad, custom-html, custom-html-tiny, discourse, ghost, immich, keycloak, lasuite-docs,
lasuite-drive, lasuite-meet, mailu, matrix-synapse, mattermost-lts, mumble, n8n, plausible,
uptime-kuma. (Decide on the test fixtures `custom-html-bkp-bad`/`custom-html-rst-bad` and
`hedgedoc` — fine to include or skip; not in the 18-recipe fleet.)
## Realtime-status architecture (chosen: same-origin proxy)
Browser JS calls a **same-origin** endpoint on the reports host; nginx proxies it to the Gitea API.
No cross-origin request → no dependency on the co-op's CORS allow-list. Public mirrors mean the proxy
needs no token (and the PRs are publicly viewable, which is the point).
- Add an nginx `location` to the `ccci-reports` stack (cc-ci repo, `reports.nix` / its nginx conf):
```
location ~ ^/pr/([a-z0-9._-]+)/([0-9]+)$ {
resolver 127.0.0.11 ipv6=off; # docker DNS; or a public resolver
proxy_ssl_server_name on;
proxy_set_header Host git.autonomic.zone;
proxy_pass https://git.autonomic.zone/api/v1/repos/recipe-maintainers/$1/pulls/$2;
proxy_intercept_errors off;
add_header Cache-Control "no-store";
}
```
So `GET https://report.ci.commoninternet.net/pr/cryptpad/5` → the PR JSON (`{state, merged, …}`).
(Restrict the regex to recipe-maintainers + a recipe-name charset; only proxies public PR reads.)
- **Alternative (if the operator prefers no proxy):** ask the autonomic.zone Gitea admins to add
`report.ci.commoninternet.net` (or `*`) to `[cors] ALLOW_DOMAIN`; then the JS can hit the Gitea API
directly. Same JS, just a different base URL. Documented as a fallback; the proxy is the default
because it has no external dependency.
## Work items
### A. Make the recipe mirrors public (scoped + safe)
1. **Secret-scan** each recipe mirror before flipping: `git log -p`/`git grep` for tokens, real `.env`
(not `.env.sample`), private keys; confirm `.drone.yml` uses secret *refs* not plaintext. (Low risk
— they mirror public upstream — but verify; the flip is hard to walk back once indexed/cloned.)
2. Confirm **no secrets in bot-authored PR comments / `!testme` output** posted on these repos (the PRs
become publicly readable). Reports are already public-safe; spot-check a couple of PR threads.
3. Flip visibility via the Gitea API (per repo): `PATCH /api/v1/repos/recipe-maintainers/<r>` with
`{"private": false}`, for the recipe-mirror set ONLY (never the excluded repos above). Verify the
`recipe-maintainers` org itself is visible enough that public repos are reachable.
4. Verify an **unauthenticated** read now works: `curl https://git.autonomic.zone/api/v1/repos/recipe-maintainers/cryptpad/pulls/5` → 200 with `state`/`merged`.
### B. Reports nginx proxy — in `reports.nix`, via nix (cc-ci repo, /ci-dev-workflow)
The proxy lives in the SAME place and is shipped the SAME way as the report serving itself: in the
cc-ci repo's `reports.nix` (the `ccci-reports` nginx stack), deployed via the nix rebuild — NOT a
separate service or a hand-edited container.
1. Locate how `reports.nix` defines the nginx config for `ccci-reports` (the static `/var/lib/cc-ci-reports`
server). Add the `/pr/<recipe>/<n>` `location` (above) into that same nginx config, so it's built
and deployed by the same mechanism. Resolver/SNI as needed for the `git.autonomic.zone` https upstream.
2. Ship via `/ci-dev-workflow` (branch cc-ci → adversary verify → merge → `nixos-rebuild` deploy).
Verify `curl https://report.ci.commoninternet.net/pr/cryptpad/5` returns the PR JSON same-origin.
3. (Optional hardening) a small `proxy_cache` (e.g. 30–60 s) so many visitors don't hammer Gitea.
### C. Report generator (`cc-ci-plan/recipe-report.py` — orchestrator repo)
1. `_table` header: rename `Status` → `TESTS`; add a `STATUS` column. Proposed order:
`Recipe | Change | TESTS | CVEs | CI | PR | STATUS | Notes`.
2. TESTS cell: unchanged (keep the `s-<STATUS>` colour class + the GREEN/FAILED/… text).
3. STATUS cell: emit a JS hook carrying the repo + PR number from the existing row fields
(`recipe`, `pr` like `#5`):
`<td class="pr-status" data-repo="{recipe}" data-pr="{n}">…</td>` — blank cell when the row has no
PR (e.g. merged-upstream custom-html, mumble). **No spec-shape change** — derives from existing
`recipe` + `pr`.
4. Add a small `<script>` (in `_page`, so every report + archive page gets it) that, on
`DOMContentLoaded` and then on a ~30 s `setInterval` (true realtime while the tab is open), for each
`.pr-status[data-pr]`:
- `fetch('/pr/' + repo + '/' + pr)` → JSON;
- render **binary**: `state === 'open'` → an **`open`** badge; **any other state** (closed/merged) →
a green **✓** (title shows merged vs closed for hover detail, but the glyph is ✓ either way);
network/parse error → a muted "?" (never break the page).
5. Add CSS for the two states (`.pr-open` badge, `.pr-done` ✓) + reuse the muted style.
6. Keep it dependency-free (vanilla fetch), CSP-safe (inline script in the self-contained page), and
resilient (try/catch per cell; the page renders fully even if the proxy is down).
### D. Verify + ship
1. Render a report locally and publish to a **preview path** (`/badge-preview`-style, not the live
index) to eyeball: TESTS column reads right, STATUS column populates live (open vs ✓) from real PRs.
2. Cross-check a known-merged PR shows ✓ and a known-open PR shows "open"; flip one to confirm realtime
(re-fetch updates without regenerating the page).
3. Ship the generator change (orchestrator repo: commit + push). Ship the nginx proxy via
`/ci-dev-workflow` (cc-ci PR → adversary verify → merge → deploy). Regenerate the current week's
report so the live page gains the new columns.
4. Update `recipe-report/SKILL.md` + the `_table`/page docstring to describe the new columns and the
`/pr/<recipe>/<n>` dependency.
## Risks / notes
- **Public exposure is one-way in practice** (mirrors get cloned/indexed). The secret-scan (A.1/A.2)
is the hard gate before any flip — do not flip a repo that doesn't pass. Excluded set locked:
`cc-ci-secrets`, `cc-ci-orchestrator`, `archived-cc-ci-orchestrator`, `cc-ci` stay private.
- **Load:** ~20 unauth PR reads per page view. With proxy caching (B.3) this is negligible.
- **Order of ops:** the STATUS column is useless until the proxy is live AND the repos are public, but
it degrades gracefully (muted "?") if either is missing — so the generator change can ship first and
light up once B + A land. Recommended order: A (public) → B (proxy) → C (generator) → D (verify).
@@ -0,0 +1,124 @@
# Plan — server regression canaries (codified E2E self-tests)
**Status:** PROPOSED — queued as the loops' next phase after `mirror` (mirror-enroll). Single loop pair,
one phase at a time.
**Owner:** Builder + Adversary loops. **Created:** 2026-06-02. **Author:** Claude Sonnet 4.6 orchestrator.
## Goal
Give the cc-ci server a **standing, codified regression suite in Python (pytest)** so we can keep
modifying the server without silently breaking it. Not a prompt an agent re-runs — a deterministic
test artifact in the repo, runnable in CI with no LLM in the loop.
The suite proves the server can do **both** halves of its job — and the second is the one that bites:
1. **Confirm a healthy app is healthy**, end-to-end, with *semantic* assertions at every tier (NOT
just an exit code / "pass").
2. **Catch a broken app** — a deliberately-broken canary that the server MUST report **RED**. A server
that goes *false-green* (reports PASS while the app is broken) is the scariest regression; we already
saw a *fabricated* FULL-PASS during the build. This guard makes false-green a test failure.
**Scope this round (operator-chosen):** E2E canaries (good + bad) only. NOT the fast logic-unit layer
(bridge trigger rules / verdict / redaction unit tests) — that's a good follow-up phase, deferred.
## Canaries
| Canary | Recipe | Why | Expected verdict |
|---|---|---|---|
| **Simple (good)** | `custom-html-tiny` | Minimal, fast, few deps — quick signal | GREEN |
| **Significant (good)** | `lasuite-docs` | Multi-service: backend + Postgres + Collabora WOPI + keycloak OIDC — exercises real breadth | GREEN |
| **Known-BAD: custom-assertion** | a seeded fixture (see below) | App comes up healthy but a functional/custom assertion is violated | **RED** |
| **Known-BAD: per-tier ×4** | `custom-html-tiny` broken at one tier each (see below) | install / upgrade / backup / restore each fail in turn | **RED** at the intended tier |
**Known-bad fixture (custom-assertion):** reuse/recreate the phase-5 seeded case — `custom-html` branch
`v5-stale-docroot` (serves `.txt` as `application/octet-stream` while the app is externally healthy),
which already produced a RED build (#75) with only the content-type custom assertion failing. The
regression test asserts the harness returns **RED** for this fixture. (If that branch is gone, recreate
the pattern: an app that is up + passes lifecycle tiers but fails one functional assertion.) Pin by SHA.
### Per-tier RED canaries — prove the server catches failure at EVERY tier (fast)
The single fixture above only proves the server catches a *custom-assertion* failure. Add **one RED
canary per lifecycle tier** so we prove the server reports RED at each of install / upgrade / backup /
restore — false-green is the scariest regression, and it can hide at any tier (e.g. restore silently
restoring nothing, the ghost/mattermost class of bug). Use the **simplest recipe — `custom-html-tiny`**
(static content, deploys in seconds) so all four run **fast**; each is a fixture broken at exactly one
tier, pinned by commit SHA.
| RED canary | How it's broken (custom-html-tiny fixture) | Expected harness result |
|---|---|---|
| **install** | image tag that never becomes healthy / a healthcheck that can't pass | **install tier RED** |
| **upgrade** | installs clean; the upgrade target breaks the container so post-upgrade health fails | install PASS, **upgrade tier RED** |
| **backup** | install+upgrade clean; backup misconfigured (backupbot label/target wrong → backup errors or yields no artifact) | **backup tier RED** |
| **restore** | backup succeeds; restore is a no-op (hook does nothing) so the pre-seeded marker is ABSENT after restore | **restore tier RED** (the scariest false-green) |
Each pytest asserts **precisely**: overall verdict RED, the failing tier is the *intended* one, AND the
tiers *before* it PASSED (e.g. upgrade-RED requires install to have passed) — so it proves "catches a
failure **at this tier**", not merely "fails somewhere". These four form the **fast subset** of the
suite; consider a sub-marker (`@pytest.mark.canary_fast`) so they can optionally run as a quicker
pre-check while the slow good canaries (esp. lasuite-docs) stay on the milestone cadence below.
## What "works as expected" means per tier (real assertions, not exit codes)
For each good canary the test drives the real cold full suite and asserts the *observable outcome*:
- **install** → app returns HTTP 200, expected page content/marker present, all services converged.
- **upgrade** → a record/marker seeded **before** the upgrade is still present **after**; the deployed
version actually bumped; app still 200. (For lasuite-docs: a created doc survives; OIDC login still
works; Collabora WOPI still 200.)
- **backup → restore** → seed data, wipe the app, restore, assert the seeded data is back.
- **secrets persistence** → the same generated app secret is identical across install→upgrade→restore.
- **redaction** → grep the published logs AND the dashboard for the generated secret value(s) → assert
**absent**.
- **teardown** → after the run, assert no leftover containers/volumes/secrets for the canary.
## Design
- **Location:** `tests/regression/` in the cc-ci repo. `pytest`, parametrized over the canaries.
- **Driver:** wrap the existing real cold path (`.../ci-test-review/verify-pr.sh` / the runner
`runner/run_recipe_ci.py`) — do NOT reimplement the harness; call it and assert on its real outputs
(build verdict, summary, dashboard JSON, published logs). The semantic per-tier assertions live in
the test, layered on top of the harness's own pass/fail so a tier that the harness calls "pass" but
that didn't actually preserve data still fails the regression test.
- **Markers:** `@pytest.mark.canary` (slow E2E) so they can be selected/excluded; the suite is run
on-demand / pre-merge / nightly, not on every fast commit.
- **Determinism:** pin canary recipe versions/SHAs and the bad-fixture SHA. Record run artifacts
(build URL, logs) on failure for triage.
## How it runs — CADENCE POLICY (important)
**Do NOT run these canaries on every commit/PR.** They are slow + resource-heavy (full lifecycle on
lasuite-docs is minutes, needs the live server/abra/Swarm). Run them **deliberately at milestones**:
- **polishing passes**, **code reviews**, and **releases** of the cc-ci server — i.e. before we trust a
batch of server changes, not on each incremental commit.
- On-demand: `pytest -m canary` against the live cc-ci server (from the orchestrator or the host).
- They are explicitly **opt-in** (the `@pytest.mark.canary` marker keeps them out of any fast/default
run). If wired to `!testme` on the cc-ci repo, gate it behind a deliberate trigger (e.g. a
`run-canaries` label or a `!testme --canary`), **not** an automatic run on every cc-ci PR.
- Document this cadence in `tests/regression/README.md` so future contributors don't wire it into the
per-commit path.
## Definition of Done (Adversary-verified)
1. `tests/regression/` pytest suite exists and is committed (cc-ci repo PR).
2. Run GREEN on both good canaries (`custom-html-tiny`, `lasuite-docs`) with the per-tier semantic
assertions actually executing (Adversary confirms the assertions FAIL if you tamper with an outcome —
i.e. the assertions have teeth, they're not vacuous).
3. The custom-assertion known-bad canary makes the suite assert **RED** — and the Adversary confirms
that if the server *wrongly* returned green for it, the regression test would FAIL (false-green caught).
4. **The four per-tier RED canaries** (install/upgrade/backup/restore, on `custom-html-tiny`) each make
the suite assert RED **at the intended tier**, with the prior tiers asserted PASS. Adversary confirms
each has teeth: if the server wrongly green-lit that tier, the corresponding test would FAIL. They run
fast.
5. A short `tests/regression/README.md`: how to run it, what each canary guards, how to add a canary.
6. NOT merged — recipe/test PR opened for operator review (loops never merge).
## Risks / notes
- **Slow + resource-heavy:** full lifecycle on lasuite-docs is minutes and needs the live server/abra/
Swarm. Keep it `-m canary`, not in the fast path. Watch disk (lasuite-docs upgrade was disk-sensitive).
- **Flakiness:** lasuite-docs had transient WOPI-404 / Collabora convergence races (see
`plan-lasuite-drive-*`); use the harness's existing readiness probes; if flaky, add bounded retries on
*readiness only* (never on the correctness assertion).
- **Don't weaken to pass:** the whole point is teeth. A flaky correctness assertion is a real signal, not
something to relax.
## Out of scope (deferred to a follow-up phase)
- Fast logic-unit layer (bridge `!testme`/`!testmexyz`/non-collaborator rules, verdict computation,
redaction function, summary formatting) as second-level pytest run on every commit.
- Golden-output snapshots, concurrency-collision canary, perf-budget assertions.
+851
View File
@@ -0,0 +1,851 @@
# cc-ci — Co-op Cloud Recipe CI Server (Autonomous Build Plan)
**Status:** ACTIVE — autonomous loop
**Owner agent:** Builder (primary) + Adversary (reviewer)
**Source brief:** `brief.md` (do not edit; this file supersedes it)
**This file's canonical path:** `/srv/cc-ci/cc-ci-plan/plan.md`
**Target server:** `cc-ci` (NixOS)
**Code/config home:** `git.autonomic.zone/recipe-maintainers/cc-ci` (the CI project repo — distinct from this
`/srv/cc-ci/cc-ci-plan/` planning+launch folder)
**Last updated:** keep current via `STATUS.md` (see §7)
---
## 0. How to read this document
This plan is written to be handed to an **autonomous Claude agent running in a sandbox over
several days**, driving itself in a loop until the CI server is "done" per §2. A second agent
(the **Adversary**) independently tries to disprove every "done" claim. Neither agent is
trusted to mark its own work complete.
If you are an agent waking up into this loop for the first time, go straight to **§1 Bootstrap**.
On every subsequent wake, go to **§7 The Loop Protocol** and continue from `STATUS.md`.
The rest of the document (§3–§6) is the technical design. Treat it as the default architecture,
but you are allowed to revise it when reality disagrees — record any deviation in `DECISIONS.md`
with a one-line rationale.
---
## 1. Bootstrap (first wake only)
Do these in order. Each step is idempotent; re-running is safe.
1. **Verify access.** (Full credential map + how each is used is in **§1.5** — read it first.)
- `ssh cc-ci 'hostname && whoami'` — you log in as **root** on cc-ci (NixOS), so there is no
separate sudo step. `ssh cc-ci` reaches cc-ci directly (the orchestrator VM is a direct tailnet
peer — no proxy; key `~/.ssh/cc-ci-root-ed25519`). If it fails, check `tailscale status`
before declaring blocked.
- `ssh cc-ci 'nixos-version'` — confirm NixOS.
- Confirm you can reach the Gitea API with the bot creds from `.testenv` (§1.5):
`curl -s https://$GITEA_URL/api/v1/version`. The bot authenticates with
`GITEA_USERNAME`/`GITEA_PASSWORD` (basic auth) or a token you mint from them via
`POST /api/v1/users/<user>/tokens` — do **not** expect a ready-made `$GITEA_TOKEN`.
- Confirm the **preconfigured** test-app DNS (§4.0/§4.4): a random subdomain under the wildcard
resolves, e.g. `getent hosts probe-$RANDOM.ci.commoninternet.net` returns the **gateway's** IP
(not cc-ci's — the gateway TLS-passthroughs to cc-ci, so do not expect cc-ci's address; and use
`getent`, not `dig`, since this host's resolver is Tailscale-only — see §1.5).
Traefik is *not* up yet — you deploy it at M1 (the real `coop-cloud/traefik` recipe via abra,
wildcard/file-provider mode → the pre-issued cert at `/var/lib/ci-certs/live/`, **no ACME**);
the DNS record + gateway passthrough + cert are the preconditions, and full end-to-end HTTPS
reachability is proven at M1, not now.
If the wildcard does not resolve at all, that's a `## Blocked` item (operator fixes DNS/gateway).
- If any check fails, write the failure to `STATUS.md` under `## Blocked` and stop — a human must fix access. Do **not** try to work around missing access.
2. **Create the `cc-ci` repo** on git.autonomic.zone if it does not exist. Push an initial
skeleton (see §3 layout). The Builder clones to `/srv/cc-ci/cc-ci`; the Adversary loop keeps
its **own independent clone** at `/srv/cc-ci/cc-ci-adv`. The repo is the only channel between
the two loops (§6.1) — loop state lives inside it (`STATUS.md`, `BACKLOG.md`, etc.).
3. **Snapshot the starting environment** into `cc-ci/docs/baseline.md`: current NixOS config on
the server (`/etc/nixos` or existing flake), installed packages, whether Docker/Swarm/abra
already exist, DNS that already points at the box. This is the rollback reference.
4. **Seed the loop state files** (§7) if absent, ALL under `machine-docs/` (never the repo
root): `machine-docs/STATUS.md`, `machine-docs/BACKLOG.md`, `machine-docs/REVIEW.md`,
`machine-docs/JOURNAL.md`, `machine-docs/DECISIONS.md`. Give `BACKLOG.md` two H2 sections — `## Build backlog`
(populated from §5 milestones) and `## Adversary findings` (empty) — per the single-writer
rule in §6.1.
5. Commit ("chore: bootstrap cc-ci loop state") and begin the loop at §7.
---
## 1.5 Credentials & access — where everything lives and how to use it
The loops run **on the cc-ci-orchestrator VM** (`100.116.55.106`, NixOS, `loops` user) and reach
cc-ci directly over Tailscale (direct tailnet peer — no proxy). This section is the authoritative
map of what credentials exist, where, and how to use them. **Never copy any secret value into the
repo, a commit, a log, or the dashboard** (§9) — reference locations only.
### Provided credentials (already in place)
| What | Where | How to use |
|---|---|---|
| **cc-ci SSH (root)** | private key `~/.ssh/cc-ci-root-ed25519`; `Host cc-ci` in `~/.ssh/config` (HostName `100.90.116.4`, no ProxyCommand) | Just run `ssh cc-ci` (logs in as **root**). The orchestrator VM is a direct tailnet peer — direct route, no proxy. Pubkey already in cc-ci's `/root/.ssh/authorized_keys`. |
| **Gitea bot account** | `/srv/cc-ci/cc-ci/.env.public` → `GITEA_USERNAME` (`autonomic-bot`); `/srv/cc-ci/.testenv` → `GITEA_PASSWORD`; `GITEA_URL` defaults to `git.autonomic.zone` | Basic-auth to the Gitea API, or mint a scoped token: `POST https://$GITEA_URL/api/v1/users/$GITEA_USERNAME/tokens`. Used to push the `cc-ci` project repo, read recipe repos, comment on PRs, and poll for `!testme` (read-level; the bot does not register webhooks). |
Load runtime configuration in a shell with: `set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a`
(don't echo secret values). The helper loads tracked public configuration first and then `.testenv`.
### The Tailscale connection (how `ssh cc-ci` works)
cc-ci (`cc-nix-test`, **100.90.116.4`) is on the same tailnet as the orchestrator VM
(`taila4a0bf.ts.net`), so it is reached **directly** — no SOCKS proxy, no userspace tailscaled.
The VM's system tailscaled is on that tailnet; `ssh cc-ci` routes straight to cc-ci.
- `ssh cc-ci` works out of the box (`~/.ssh/config` has `Host cc-ci` pinned to `100.90.116.4`,
no ProxyCommand; key `~/.ssh/cc-ci-root-ed25519`; logs in as root).
- For HTTP(S) to cc-ci / `*.ci.commoninternet.net` from the VM, use plain `curl` — no proxy flag
needed. The VM uses public DNS resolvers (`1.1.1.1`/`8.8.8.8`) so `*.ci.commoninternet.net`
resolves normally.
- **If `ssh cc-ci` fails:** run `tailscale status` (as loops or root) to confirm the VM is still
on the tailnet and cc-ci is listed; check `systemctl status tailscaled`. A connectivity failure
is recoverable, not an immediate `## Blocked`-and-stop, unless the VM has lost tailnet membership
entirely (then that IS a class-A1 blocker).
### Credentials the loop GENERATES itself (do not wait on a human for these)
- **Drone RPC secret** and **webhook HMAC secret** — generate (`openssl rand -hex 32`), store
sops-encrypted in `secrets/`, and wire both ends. Internal shared secrets, not human inputs.
- **Gitea OAuth app for Drone** — create it under the bot account via the API
(`POST /api/v1/user/applications/oauth2`); capture client id/secret into `secrets/`.
- **cc-ci host age/GPG key for sops** — generate on the host (or derive from its SSH host key);
add as a sops recipient. Keep a recovery copy of the master age identity off-box if desired.
- **Per-recipe app secrets** (class-B, §4.4) — the harness generates these per run.
### Credentials STILL NEEDED from the operator (class-A — block if missing, per §9)
- **Wildcard TLS cert — PROVIDED, not a token.** The operator has pre-issued the wildcard SAN cert
(`*.ci.commoninternet.net` + `ci.commoninternet.net`) and placed it on cc-ci at
`/var/lib/ci-certs/live/{fullchain.pem,privkey.pem}` (§4.0).
> **Phase-1c update (supersedes the cert references in §1.5/§4.0/§4.4 below):** the cert is no longer
> an out-of-band operator file-drop — it is now **sops-encrypted in the private `cc-ci-secrets` repo**
> (a git submodule) and **decrypted at activation to that same path** by sops-nix. Issuance stays
> operator-only (LE/Gandi, no token on the box); to rotate, the operator re-issues then re-encrypts
> the cert into `cc-ci-secrets` and rebuilds. The ONE out-of-band secret is now the bootstrap age key
> at `/var/lib/sops-nix/key.txt`. Authoritative model: `cc-ci/docs/secrets.md` + `docs/install.md`. The agent feeds these into the
`coop-cloud/traefik` recipe as its `ssl_cert`/`ssl_key` swarm secrets (wildcard/file-provider
mode) and runs **no ACME** for this domain. **Do not request or expect a `commoninternet.net` DNS
token** — issuance/renewal is handled out-of-band by the operator (LE 90-day cert; next renewal
~2026-08-24). A missing/expired cert is a finding for the operator, not an agent re-issue.
- **Registry pull credentials** (e.g. Docker Hub) — *recommended* to avoid anonymous pull-rate
limits breaking deploys under load. Treat a rate-limit failure traced to this as a finding, then
request creds. Store sops-encrypted in `secrets/`.
- **Gitea bot permissions** (a grant, not a secret) — **least privilege: read, not admin.** The bot
needs: write on its own `recipe-maintainers/cc-ci` project repo; **read** + **comment** on the
recipe repos under test; and **org membership** in `recipe-maintainers` (read-level — used both to
authorize commenters via the members endpoint and to read members). It does **not** need repo-admin
and does **not** register webhooks (that's an optional manual admin task, §4.1). If a needed grant
is missing, that's a `## Blocked` item for the operator.
---
## 2. Definition of Done (the loop's exit condition)
The loop terminates **only** when every item below is true *and the Adversary has independently
re-verified each one within the last 24h* (logged in `REVIEW.md` with timestamps and command
output). Partial credit does not count.
- [ ] **D1 — Trigger.** Commenting `!testme` on any open PR in any enrolled recipe repo on
git.autonomic.zone starts a CI run for the code *at that PR's head commit* within 60s.
Other comments do not. Re-commenting re-runs.
- [ ] **D2 — Test matrix.** For a recipe under test, the run executes, as separate reported
stages: **new install**, **upgrade** (previous published version → PR version), and
**backup + restore**. All are genuine end-to-end against a really-deployed recipe (real
containers, real Traefik routing, real volumes) — no mocks, no stubs.
- [ ] **D3 — Python + Playwright.** Tests are Python. Functional assertions that require a
browser use Playwright against the live deployed app.
- [ ] **D4 — Recipe-local tests.** If the recipe repo contains its own `tests/` folder, those
tests are also discovered and run as part of the same CI run, with results merged in.
- [ ] **D5 — Per-recipe test tree.** The cc-ci repo holds `tests/<recipe>/` with the
install/upgrade/backup tests as Python files, plus a shared harness. Adding a new recipe is
a documented, small, repeatable operation.
- [ ] **D6 — Secrets.** App + infra secrets are handled reproducibly (committed encrypted,
decrypted on the server), documented, and rotatable. No plaintext secrets in git, logs, or
the results UI.
- [ ] **D7 — Results UX.** Each run has a stable URL with live, tail-able logs per stage and a
final pass/fail; there is an overview page listing recipes with their latest status —
look-and-feel comparable to the YunoHost app CI (`ci-apps.yunohost.org`). A PR comment links
back to its run and reflects the outcome.
- [ ] **D8 — Reproducible server.** The entire server (Drone, runner, comment bridge, swarm,
Traefik, dashboard, secrets wiring) is declared in the `cc-ci` repo's NixOS flake and can be
rebuilt from scratch onto a blank NixOS host following `docs/install.md`, verified by the
Adversary doing exactly that on a throwaway VM (or documenting why a full from-scratch
rebuild was infeasible and what was tested instead).
- [ ] **D9 — Documentation.** `README.md` + `docs/` explain architecture, how to enroll a recipe,
how to add/run tests locally, how to operate/rotate secrets, and how to debug a failed run.
A new engineer can enroll a recipe and get a green run using only the docs.
- [ ] **D10 — Proof (breadth).** At least **six real recipes** spanning the meaningful
categories have a full green run triggered by `!testme` on a real PR, with all three stages
(install / upgrade / backup+restore) actually exercised. The set must cover:
a stateless/simple app, a single-DB app, a multi-service app, an SSO/identity app, and an
object-storage/large-volume app. **Target set (all previously verified deployable):**
`hedgedoc` (simple), `cryptpad` (stateful, no external DB), `keycloak` + `authentik`
(SSO/identity, DB-backed), `lasuite-docs` and/or `lasuite-drive` (multi-service + S3/MinIO),
`matrix-synapse` (DB + media store), `immich` (large volumes + Postgres), `bluesky-pds`
(TLS-passthrough/atproto). Pick six that together satisfy the categories; record the chosen
set and per-recipe green-run evidence in `REVIEW.md`. Any recipe that genuinely cannot be CI'd
is a documented finding (in `DECISIONS.md`) with the reason, not a silent omission.
*Recipe availability:* the testable repos live on the **private mirror**
`git.autonomic.zone/recipe-maintainers/<recipe>` (already mirrored as of bootstrap:
`bluesky-pds`, `cryptpad`, `keycloak`, `lasuite-docs`, `lasuite-meet`, `matrix-synapse`, `n8n`,
`custom-html`, `custom-html-tiny`). Any recipe **not** yet mirrored (e.g. `hedgedoc`,
`authentik`, `immich`, `lasuite-drive`) is pulled from upstream **git.coopcloud.tech** and
created on the mirror via the **recipe mirror+PR flow** (§4.1) — so the target set is not capped
by what currently exists. If the chosen simple/stateless app isn't mirrored, `custom-html` /
`custom-html-tiny` already are.
When all of D1–D10 hold and are Adversary-verified, write `## DONE` to `STATUS.md` with the
evidence links and stop scheduling new iterations.
---
## 3. Repository layout (`git.autonomic.zone/recipe-maintainers/cc-ci`)
```
cc-ci/
├── README.md
├── flake.nix # NixOS host(s) + devshell
├── flake.lock
├── hosts/
│ └── cc-ci/
│ ├── configuration.nix # the cc-ci machine
│ └── hardware.nix
├── modules/
│ ├── drone.nix # Drone server + runner (exec/docker)
│ ├── comment-bridge.nix # !testme webhook listener service
│ ├── swarm.nix # Docker + single-node swarm + `proxy` net; deploys the
│ │ # coop-cloud/traefik recipe via abra (wildcard/file-provider, §4.2)
│ ├── dashboard.nix # results overview site
│ └── secrets.nix # sops-nix / agenix wiring
├── secrets/ # sops-encrypted (*.enc / *.age); see §4.4
│ └── secrets.yaml
├── bridge/ # comment-bridge source (small Go/Python service)
├── runner/ # CI orchestration entrypoint invoked by Drone
│ ├── run_recipe_ci.py # top-level: deploy→test→teardown for a recipe@ref
│ └── harness/ # shared pytest fixtures (abra wrappers, app lifecycle)
├── dashboard/ # results UI generator (reads Drone API → static site)
├── tests/
│ ├── conftest.py # shared fixtures, recipe selection, teardown guarantees
│ ├── <recipe>/
│ │ ├── test_install.py
│ │ ├── test_upgrade.py
│ │ ├── test_backup.py
│ │ └── playwright/ # e2e flows for this recipe
│ └── _template/ # copy-to-add-a-recipe template
├── docs/
│ ├── install.md # from-scratch server build (D8)
│ ├── enroll-recipe.md # how to add a recipe (D5)
│ ├── secrets.md # secret model + rotation (D6)
│ ├── architecture.md
│ ├── runbook.md # debugging failed runs
│ └── baseline.md # bootstrap snapshot
├── machine-docs/ # ALL loop-state/coordination files live here (§7), NEVER repo root:
│ │ # STATUS-*.md BACKLOG-*.md REVIEW-*.md JOURNAL-*.md (phase-namespaced)
│ │ # DECISIONS.md DEFERRED.md ADVERSARY-INBOX.md BUILDER-INBOX.md
│ └── ...
└── .drone.yml # pipeline for cc-ci's own repo (lint/self-test)
```
---
## 4. Technical design (default architecture)
### 4.0 Domain model (where things live)
Two DNS zones, deliberately separated — do **not** conflate them:
- **`git.autonomic.zone` — source of truth for code (unchanged, not ours to reconfigure).**
The Gitea host: the enrolled recipe repos and the `cc-ci` config repo live here. The loop reads,
comments, and (when enrolling) adds a webhook here, but deploys **nothing** here. Per §9 this zone
is read/comment-only — never push recipe code, never point app DNS at it.
- **`commoninternet.net` — the CI server's own zone; everything CI-facing.** A wildcard
`*.ci.commoninternet.net` resolves to a **gateway** (not cc-ci directly — see Network path below).
Under it:
- **Apps under test:** each run deploys to a unique subdomain
`<recipe>-pr<n>-<short-sha>.ci.commoninternet.net`, so concurrent runs never collide on a
hostname. The subdomain (app, volumes, secrets, Traefik route) is torn down at run end (§4.3).
- **Results dashboard:** `ci.commoninternet.net` — overview page + per-recipe status badges (§4.5).
- **Webhook bridge:** `ci.commoninternet.net/hook` — the Gitea `issue_comment` receiver (§4.1).
- **Network path (gateway → TLS passthrough → cc-ci).** The wildcard record does **not** point at
cc-ci's IP. It points at a gateway that **passes TLS through** to cc-ci: the gateway routes by SNI
and forwards the raw encrypted stream without decrypting it, so TLS still **terminates on cc-ci's
Traefik**. Consequences the agent must respect:
- `dig <sub>.ci.commoninternet.net` returns the **gateway's** IP, not cc-ci's — do not assert the
record points at cc-ci. Reachability is proven end-to-end (an HTTPS request lands on cc-ci),
not by comparing A records.
- The gateway is assumed to passthrough the **whole wildcard**, so a fresh per-run subdomain needs
**no gateway change** and **no cert work** (the pre-issued wildcard already covers it) — the
agent only adds the Traefik **router** on cc-ci. (If the gateway
instead needs per-host config, that's an operator/gateway concern and a `## Blocked` item, not
something the agent reconfigures — the gateway is not ours, only cc-ci is, per §9.)
- The gateway is operator-managed and out of scope; the agent configures only cc-ci.
- **Caveat for TLS-passthrough recipes** (e.g. `bluesky-pds`, §2 D10): the default path terminates
TLS at cc-ci's Traefik. A recipe that expects to terminate TLS in its own container needs cc-ci's
Traefik configured to passthrough that host too (the outer gateway already passes the whole
wildcard). Treat this as a per-recipe harness quirk to absorb (§5 M6.5), or pick a non-passthrough
recipe for that D10 category and record the swap in `DECISIONS.md` — not a silent omission.
- **Wildcard TLS — operator pre-issues, agent serves it statically (no token in the agent).**
Routing and certs are separate: the preconfigured wildcard DNS solves routing only; a cert is
still needed because the gateway passes TLS through and cc-ci's Traefik terminates it. **The cert
is pre-provisioned out-of-band** so the DNS-editing token never enters the agent/repo. A wildcard
SAN cert covering **`*.ci.commoninternet.net` + `ci.commoninternet.net`** (issued via Let's
Encrypt DNS-01 against Gandi, by the operator, using a token the agent never sees) lives on cc-ci:
- `/var/lib/ci-certs/live/fullchain.pem` (leaf+intermediate) and `…/privkey.pem`.
- **Traefik is the real `coop-cloud/traefik` recipe, deployed via abra** (for e2e fidelity — see
§4.2), run in its **wildcard / file-provider mode** (`WILDCARDS_ENABLED=1` + `compose.wildcard.yml`).
The pre-issued cert is supplied as the recipe's `ssl_cert`/`ssl_key` **swarm secrets** (sourced
from the files above); the recipe's file provider then serves it under `tls.certificates`. **No
ACME resolver / no DNS provider** is enabled — only the cert+key reach cc-ci, never the DNS token.
One cert covers every per-run subdomain (matched by SNI), so a new app domain needs no cert work.
- **Renewal is a manual operator task** (LE 90-day cert): the operator re-issues out-of-band, then
updates the `ssl_cert`/`ssl_key` secret (bump its version) and redeploys traefik. The agent must
**not** attempt ACME/DNS-01 for `commoninternet.net` and must **not** expect a DNS token — a
missing/expired cert is an operator action surfaced as a finding, not something the agent re-issues.
(Rationale for choosing a wildcard cert over per-subdomain: a wildcard is reused for every churning
run subdomain and sidesteps LE's 50-certs/week-per-domain limit; only DNS-01 can mint a wildcard.
We keep that DNS-01 issuance with the operator rather than handing the agent the zone token.)
- Record the live facts in `docs/install.md`: the zone + DNS provider (Gandi), that the wildcard
`*.ci.commoninternet.net` (and bare `ci.commoninternet.net`) point at the **gateway**, that the
gateway TLS-passthroughs the wildcard to cc-ci, the gateway's address, the TTL, and that the
wildcard cert is pre-issued/operator-renewed at `/var/lib/ci-certs/live/` (no DNS token on cc-ci).
### 4.1 The `!testme` trigger path
Gitea does not natively forward PR-comment events to Drone, and Drone's built-in triggers fire on
push/PR-open, not on a magic comment. So:
```
PR comment "!testme"
│ Gitea webhook (issue_comment event) ──► comment-bridge (modules/comment-bridge.nix)
│ • verifies webhook HMAC secret
│ • checks comment body == "!testme" (exact, trimmed)
│ • checks commenter is allowed (org member / collaborator)
│ • resolves PR head repo + SHA via Gitea API
│ • calls Drone API: build for cc-ci pipeline,
│ params RECIPE=<repo> REF=<sha> PR=<n> SRC=<headrepo>
▼
Drone build (cc-ci repo pipeline, parameterized) ──► runner/run_recipe_ci.py
▼
Bridge posts/updates a Gitea PR comment with the run URL and (on completion) pass/fail.
```
- The bridge is a tiny service (Go or Python+FastAPI). Keep it dependency-light; it's a NixOS
systemd service behind Traefik at e.g. `ci.commoninternet.net/hook` (§4.0).
- **Trigger: POLLING is primary; webhook is an optional, admin-registered push optimization
(SETTLED).** Hard constraint: **the CI server/bot must run on READ-level access — never repo-admin.**
- **Polling (primary, default):** the bridge polls the Gitea API for new `!testme` comments on
enrolled repos at ≤60s (satisfies D1). This is **outbound** (cc-ci → git.autonomic.zone, the
reliably-working direction) and needs only **read**. It is the source of truth for triggering.
- **Webhook (optional):** the bridge keeps its `/hook` endpoint so a Gitea `issue_comment` webhook,
**if present**, gives lower latency. But the **server does NOT self-register webhooks** (that
needs repo-admin, which we refuse to require). Registration is a **manual admin task, documented**
in `docs/enroll-recipe.md` (URL `https://ci.commoninternet.net/hook`, event `issue_comment`,
content-type `json`, the shared HMAC secret, and the note that the Gitea instance must allow the
host). The two paths are mutually exclusive in effect; don't double-fire a comment seen by both.
- (Webhook delivery on this instance was flaky early on — `last_status: None` — so polling being
primary is also the robust choice, not just the low-privilege one.)
- **Commenter auth via org membership (read-level — no admin).** The repo's explicit collaborator
list is empty: the bot *and* the maintainers (`trav`/`notplants`) all reach the repo as
`recipe-maintainers` **org members/owners**, so `GET /collaborators/{user}` 404s for everyone, and
`GET /collaborators/{user}/permission` would authorize correctly but **requires repo-admin** — which
we refuse. Instead authorize with **`GET /orgs/recipe-maintainers/members/{user}`** (204 = member =
authorized; 404 = rejected) — readable by any **org member** (read-level), verified to admit
`trav`/`notplants`/the bot and reject non-members. Note `public_members` is hidden here, so use the
authenticated `members` endpoint (bot must be an org member, still read-level). Fail-closed on
error. Zero-privilege fallback: a configured allowlist of usernames. (Still satisfies §6's
non-collaborator-rejection check.)
- Enrollment = adding the recipe to the bridge's **poll list** + ensuring a `tests/<recipe>/` dir
exists. The bot needs only **read** on the recipe repo (+ comment-back to post status). Registering
a webhook is **optional and operator/admin-side** (documented in `enroll-recipe.md`), never required
for CI to work.
- **Recipe mirror+PR flow (how a recipe gets a testable PR).** Recipe repos under test live on the
**private mirror** `git.autonomic.zone/recipe-maintainers/<recipe>`, mirrored from the **official
upstream `git.coopcloud.tech`**. To bring a recipe under CI: `abra recipe fetch <recipe>` (pulls
from upstream into `~/.abra/recipes/<recipe>`), then mirror it to the org + open a PR via the
**recipe mirror+PR procedure** — reference implementation:
`/srv/recipe-maintainer/.claude/commands/recipe-create-pr.md` (creates `recipe-maintainers/<recipe>`
if absent, force-syncs `main` from upstream so the PR diff is clean, pushes a branch, opens the PR).
`!testme` on that PR is what kicks off a run. So a recipe missing from the mirror is **not** a
blocker — mirror it first.
- Decide and record in DECISIONS.md: one shared Gitea org-level webhook vs per-repo webhooks.
Org-level is fewer moving parts; per-repo is more explicit. Default: per-repo via enroll script.
### 4.2 Drone + the test target
- Drone server connects to Gitea via OAuth app (Gitea → Settings → Applications). Runner is the
**exec runner** (or a privileged docker runner) running **on cc-ci itself**, because tests must
drive `abra` to deploy real recipes onto a real swarm.
- cc-ci doubles as the **deploy target**: single-node Docker Swarm + abra, with the reverse proxy
provided by the **real `coop-cloud/traefik` recipe deployed via abra** (not a hand-rolled Traefik
— chosen for **end-to-end fidelity**: test apps route through the exact proxy a real Co-op Cloud
host uses — `web`/`web-secure` entrypoints, the `proxy` overlay, the swarm provider). TLS
terminates on it using the **pre-issued static wildcard cert** (§4.0): run the recipe in
**wildcard/file-provider mode** (`WILDCARDS_ENABLED=1` + `compose.wildcard.yml`) and supply the
cert as the recipe's `ssl_cert`/`ssl_key` swarm secrets from `/var/lib/ci-certs/live/`. The
operator preconfigures the wildcard DNS (→ gateway), the gateway's TLS-passthrough, and the cert
itself (§4.4); the agent deploys the traefik recipe + swarm on top — **no ACME, no DNS token on
cc-ci**. Make the `abra app new/deploy traefik` steps reproducible (scripted/Nix-invoked) for D8.
- Each CI run gets an isolated app domain `<recipe>-pr<n>-<short-sha>.ci.commoninternet.net`
(§4.0) so concurrent runs don't collide. Teardown removes app, secrets, and volumes.
- **Concurrency cap + queue — use Drone natively (SETTLED).** Don't let the server fill with
simultaneously-deployed apps. Expose a configurable **`MAX_TESTS`** mapped to the exec runner's
**`DRONE_RUNNER_CAPACITY`** (Nix-set on the runner; default low — **1–2** given a single 28 GiB
node and heavy recipes like matrix/immich). Drone runs at most `MAX_TESTS` builds at once and
**automatically queues** excess builds (its native pending-build queue), starting them as slots
free. **Per-build timeout** (repo/runner timeout) guarantees a hung test is killed and frees its
slot — so "continue once a current test finishes *or times out*" is built in. No custom queue
needed. Optionally also set `concurrency: { limit: <N> }` in `.drone.yml` as a per-pipeline cap.
- **One app at a time per run, torn down at run end.** A build deploys its recipe, runs the three
stages, then **undeploys** — the server should not accumulate live test apps. Guaranteed teardown
+ the run-start janitor (§4.3) enforce this even when a build is timed-out/killed (in-process
cleanup can't run, so the janitor reaps it).
### 4.3 The test harness & recipe test contract
`runner/run_recipe_ci.py` orchestrates per run:
1. Fetch recipe at `$REF` (the PR head) via abra/git.
2. **Install stage** → `tests/<recipe>/test_install.py`: `abra app new`, generate secrets,
`abra app deploy`, wait healthy, run Playwright smoke + assertions.
3. **Upgrade stage** → deploy previous published version first, then upgrade to `$REF`; assert
data survives and app still healthy.
4. **Backup/restore stage** → `abra app backup`, mutate state, `abra app restore`, assert restored
state matches pre-mutation.
5. **Recipe-local tests (D4)** → if `<recipe-repo>/tests/` exists, discover & run it in the same
live environment; merge results.
6. **Teardown (always, even on failure)** → `abra app undeploy`, `abra app volume remove`,
`abra app secret remove`, DNS/route cleanup.
Shared fixtures (`tests/conftest.py` + `runner/harness/`) wrap abra. **Known abra gotchas to bake
in from day one** (carried over from prior work, re-verify on the installed abra version):
- `abra app undeploy` and `abra app volume remove` do **not** accept `--chaos` → never pass it.
- Plumb a `timeout` kwarg through secret-generate/insert/remove-all calls.
- `abra app ls -S -m` returns nested `{server: {apps: [...]}}` — parse the inner structure.
- Pick robust health checks per app (e.g. Keycloak: `/realms/master`, not `/`).
The teardown guarantee is sacred: a failed test must never leak a deployed app or volume into the
next run. Implement teardown as a pytest fixture finalizer / `try/finally` in the orchestrator and
add a janitor pass at run start that nukes any orphaned `*-pr*` apps older than N hours.
**Crucially, the janitor is the backstop for timed-out/killed builds:** when Drone hits the
per-build timeout (or a build is cancelled) it may SIGKILL the runner process, so the `try/finally`
teardown can't run — those orphaned apps/volumes are reaped by the next build's run-start janitor
(and the janitor should run regardless of how the previous build ended). Net effect with the
`MAX_TESTS`/`DRONE_RUNNER_CAPACITY` cap (§4.2): at most `MAX_TESTS` apps are ever live at once, and
each is torn down (or janitor-reaped) so the single node never accumulates deployments.
### 4.4 Secrets (D6)
There are **two distinct classes of secret** and they are handled in opposite ways. Do not
conflate them.
**(A) Infra secrets.** All of these end up `sops-nix`-encrypted in `secrets/`, decrypt into the Nix
store at activation, and are never world-readable. But they split into two sub-classes — see §1.5
for the concrete locations/usage — and only the first sub-class blocks:
- **(A1) External inputs — provided by the operator, the loop cannot create them.** The Tailscale
auth key + Gitea bot creds (`/srv/cc-ci/.testenv`, already provided), the **pre-issued wildcard
TLS cert** at `/var/lib/ci-certs/live/` (§4.0 — *not* a DNS token; the agent serves it, never
issues it), and **registry pull creds** (if needed). If one of these is **missing or invalid, the
loop is blocked** — write it to `STATUS.md ## Blocked` and stop (§9). The agent must not invent or
work around an external input it wasn't given, and must **not** attempt ACME/DNS-01 for
`commoninternet.net`.
- **(A2) Internal secrets — the loop generates and manages these itself; never block on them.**
Drone RPC secret + webhook HMAC (`openssl rand`), the Gitea OAuth app for Drone (created via the
bot API), and the cc-ci host age/GPG key for sops. These are *not* human inputs; generate, store
in `secrets/`, and wire both ends.
Alongside these, three **preconfigured network/cert facts** are operator-provided inputs the loop
also depends on (not secrets the agent makes, but class-A in the same "provided, don't improvise"
sense): (1) the wildcard `*.ci.commoninternet.net` record (and bare `ci.commoninternet.net`) already
points at the **gateway**, (2) the gateway **TLS-passthroughs** that wildcard to cc-ci (SNI-routed,
no decryption — see §4.0 Network path), and (3) the **pre-issued wildcard cert** is in place at
`/var/lib/ci-certs/live/`. The operator owns the DNS record, the gateway, and cert issuance/renewal;
**everything else on cc-ci is the agent's job** — Traefik (pointed at the static cert), swarm,
per-run subdomain routing, and teardown. If the wildcard does not resolve, the gateway doesn't reach
cc-ci, or the cert is missing/expired, that is a `## Blocked` condition (operator action), not
something to work around (the gateway and DNS are not ours to reconfigure, per §9).
**(B) Recipe app secrets — generated by the test, persisted within the run.** These are NOT a
blocker and are NOT pre-provisioned by a human. The harness creates them itself for each app under
test and is responsible for persisting them across the run so the multi-stage lifecycle works:
- **Generate at install:** the harness runs `abra app secret generate` (+ inserts any deterministic
test fixtures like an admin password / test user it chooses) when it deploys the app.
- **Persist for the run's duration:** the *same* generated secrets must survive across stages —
install → upgrade and especially **backup → restore** — because an app cannot be upgraded or
restored against rotated credentials. Persist them in a per-run secret store keyed by the run's
unique app name (e.g. `<recipe>-pr<n>-<sha>`): the live abra/swarm secrets plus a sidecar record
the harness writes (e.g. the app's `.env` + the generated values) to a run-scoped, non-public
location on the runner, so any stage can re-read them. They are emphemeral by design.
- **Destroy at teardown:** the same teardown that removes the app/volumes also runs
`abra app secret remove` (with `timeout` plumbed) and deletes the per-run sidecar. Nothing
generated for a run outlives that run.
- **How the harness should "figure out" persistence (acceptance for D6):** decide and document one
concrete mechanism — recommended default is "abra/swarm holds the live secrets; the harness keeps
a run-scoped sidecar file under a `runs/<app-name>/` dir on the runner (mode 600), and reloads
from it between stages." Whatever is chosen, it must (1) keep the same values stable across all
three stages, (2) isolate concurrent runs from each other, and (3) leave nothing behind.
**(C) Drone CI tokens:** store as Drone org/repo secrets, referenced by the pipeline. Where a value
is an external input (A1, e.g. registry creds) it is provided; where it is internal (A2) it is
generated — see the (A) split above.
Hard rule across all classes: scrub secrets from logs before they reach the dashboard; the results
UI shows sanitized logs only. Add a redaction filter in the log pipeline and an Adversary test that
greps published logs and the overview site for known secret patterns and any generated app
password.
### 4.5 Results UX (D7) — YunoHost-CI-like
- **Per-run logs:** Drone's native UI already gives live, per-stage, tail-able logs and a final
status — use it as the canonical run view; the PR comment links to it.
- **Overview page:** a small generator (`dashboard/`) polls the Drone API and renders a static
page at `ci.commoninternet.net` (§4.0): a table of enrolled recipes, latest run status badge
(pass/fail/running), last-tested version, link to history — mirroring the YunoHost app-list
feel. Served by Traefik; regenerated on build-completion webhook or a short timer.
- Provide a status badge endpoint per recipe for embedding in recipe READMEs.
---
## 5. Milestones / initial BACKLOG
Work top-down; each milestone ends with an **Adversary gate** (Adversary must independently
verify the acceptance check before the next milestone starts). Seed `BACKLOG.md` from this.
- **M0 — Foundations.** Repo created; flake builds; `nixos-rebuild` (or deploy-rs) applies a
no-op-then-base config to cc-ci; sops decrypts a test secret on the host.
*Accept:* `ssh cc-ci 'systemctl is-system-running'` healthy after a rebuild from the repo.
- **M1 — Swarm + abra target.** Docker + single-node swarm + `proxy` network; the **`coop-cloud/traefik`
recipe deployed via abra** (wildcard/file-provider mode, serving the pre-issued cert — §4.0/§4.2,
not a custom Traefik); abra can deploy and tear down a trivial recipe by hand.
*Accept:* a recipe deployed via abra is reachable over HTTPS (valid wildcard cert) on the
`web-secure` entrypoint at `*.ci.commoninternet.net`, then fully torn down leaving no volumes; the
proxy is verifiably the traefik recipe and **no DNS/ACME token is present on cc-ci**.
- **M2 — Drone online.** Drone server+runner via Nix, OAuth to Gitea; a hello-world `.drone.yml`
in cc-ci runs green; logs visible in Drone UI.
*Accept:* push to cc-ci triggers a visible green Drone build.
- **M3 — Comment bridge.** `!testme` on a PR triggers a parameterized Drone build; bridge posts a
PR comment with the run link; non-`!testme` comments and non-collaborators are ignored.
*Accept:* live demo on a scratch PR — comment in, build out, link back, auth enforced.
- **M4 — Harness + install stage.** `run_recipe_ci.py` + conftest; install stage green for one
simple recipe end-to-end with a Playwright assertion; guaranteed teardown.
*Accept:* full green install run for recipe #1, no orphaned app/volume afterward.
- **M5 — Upgrade + backup/restore stages.** Add the other two stages for recipe #1.
*Accept:* upgrade preserves data; backup→mutate→restore returns original state.
- **M6 — Recipe-local tests (D4) + second recipe.** Discover/run recipe-repo `tests/`; enroll a
second, DB-backed recipe via the documented flow.
*Accept:* both recipes green; recipe-local tests demonstrably executed and merged.
- **M6.5 — Breadth ramp.** Enroll recipes 3→6 covering the remaining D10 categories, one at a
time, each via the documented enroll flow (this is the real test of D5: enrolling recipe N
should be template-copy + recipe-specific tests/fixtures, with **no harness surgery**). Expect
per-recipe quirks — multi-service deps, S3/MinIO config, SSO client setup, TLS passthrough,
large-volume backups — and absorb them into the *shared* harness, not one-off per-recipe hacks.
When flakiness appears, add real readiness/wait robustness to the harness rather than sprinkling
`sleep`s. Run benchmarks/long deploys **sequentially**, never in parallel (network contention).
*Accept:* recipes 3–6 each have a full three-stage green run; enrolling N≥3 needed no changes to
shared harness code.
- **M7 — Secrets hardening (D6).** Full sops model, rotation doc, log redaction + leak test.
*Accept:* Adversary's secret-grep over published logs finds nothing; rotation doc followed.
- **M8 — Dashboard (D7).** Overview page + badges + PR-comment outcome reflection.
*Accept:* overview matches reality across several runs; outcomes mirrored to PR comments.
- **M9 — Reproducibility + docs (D8/D9).** `docs/install.md` rebuilds the server from scratch on a
blank VM; all docs complete.
*Accept:* Adversary rebuilds from docs onto a throwaway host (or records the tested subset).
- **M10 — Proof (D10).** All six chosen recipes green via real `!testme` PRs (the breadth set from
M6/M6.5 carried through the hardened pipeline), each with install/upgrade/backup-restore
exercised and Adversary-verified; flip `STATUS.md` to DONE.
---
## 6. The two agents
### Builder (primary)
Implements the backlog top-down. Discipline:
- One backlog item in flight at a time. Small, committed, reversible steps.
- Every change verified against the *real* system (server, Drone, Gitea) before claiming done —
never "should work". Paste the verifying command + output into `JOURNAL.md`.
- Touch production carefully: cc-ci is the only target; never deploy test apps onto unrelated
production servers; never reuse production domains. Idempotent server changes only (via Nix).
- If blocked on access/secrets/external state, write it to `STATUS.md ## Blocked` and pick up an
unblocked item rather than hacking around it.
### Adversary (reviewer)
Runs as a **separate, independent loop in its own process/sandbox** (see §6.1 for how the two
loops coordinate). Its job is to **disbelieve**. It:
- Re-verifies each `Definition of Done` and milestone-acceptance claim independently, from a cold
start (fresh shell, own clone, no cached state), and logs PASS/FAIL + evidence in `REVIEW.md`.
- Actively tries to break things: comment `!testmexyz` (should NOT trigger), comment as a
non-collaborator (should be rejected), push a PR that fails tests (must report red, not green),
kill an app mid-run (teardown must still clean up), grep published logs/dashboard for secrets,
run two `!testme`s concurrently (no domain/volume/secret collision), confirm the same generated
app secrets persist across install→upgrade→backup/restore.
- Files every defect as a `BACKLOG.md` item tagged `[adversary]` with repro steps. The Builder
may not close an adversary item; only the Adversary closes it after re-test.
- Has veto power over `STATUS.md → DONE`.
### 6.1 Coordination protocol (two independent loops, one shared repo)
The two loops never talk directly; the **git repo is the only coordination medium**. Each agent
has its own clone (e.g. Builder in `/srv/cc-ci/cc-ci`, Adversary in `/srv/cc-ci/cc-ci-adv`) and
its own pacing. To make concurrent writes conflict-free:
- **File ownership (one writer each — the other only reads):**
- Builder owns: all source code/config, `STATUS.md`, `JOURNAL.md`, `DECISIONS.md`.
- Adversary owns: `REVIEW.md`.
- `BACKLOG.md` is split into two H2 sections — `## Build backlog` (Builder-only) and
`## Adversary findings` (Adversary-only). Each agent edits **only its own section**, so git
merges the two cleanly. Closing an item = checking the box *in your own section*; the Builder
fixes an `[adversary]` finding and notes the fix in JOURNAL, but only the Adversary ticks it
closed after re-test.
- `DEFERRED.md` (in `machine-docs/`) is the **single canonical registry for things the loops
have deliberately decided not to do autonomously and that need operator input to move on.**
Append-only; either agent may file. Each entry should clearly say *what's needed from the
operator* to lift the deferral (an opt-in flag, a resource decision, an architectural call,
plain "go ahead"). The list is **open-ended** — items can sit indefinitely, **no obligation
to close every item**, closure is operator-driven. A re-entry trigger / IDEA cross-link is
**optional** (include when there's a natural mechanism, e.g. an opt-in flag in
`cc-ci-plan/IDEAS.md`). Don't park deferrals as a vague "Q4 follow-up" / buried JOURNAL note
— file them here so the operator can review the whole list. The Phase-4 cleanup pass should
**surface** DEFERRED.md to the operator at least once but does **not** force closure.
Future-aspirational ideas (out of current scope) still go to `cc-ci-plan/IDEAS.md`; DEFERRED
is for considered-and-parked work the loops won't tackle without operator input.
- **Append-only where possible.** `JOURNAL.md` and `REVIEW.md` are append-only logs → they never
conflict. Prefer appending over rewriting.
- **Artifact-layer isolation — facts in STATUS, reasoning in JOURNAL (anti-anchoring).** Rigorous
adversarial verification requires the Adversary NOT to consume the Builder's rationalisations
before forming its verdict. The split:
- `STATUS.md` MUST carry **everything the Adversary needs to verify the claim** — withholding
verification context defeats the verification: **WHAT** is claimed (gate id, DoD items), **HOW**
to verify (the exact command/check the Adversary can re-run from its own clone), the
**EXPECTED** outcome (build hashes, file contents, leaf fingerprints, status codes), and
**WHERE** the inputs live (commit shas, paths). If it's essential for the Adversary to verify,
it goes in STATUS.
- `STATUS.md` MUST NOT carry rationalisations / "why I think this passes" / design narrative /
dead-ends explored. Those go in `JOURNAL.md` (Builder-private to write).
- The Adversary reads STATUS for the claim + verification info, the plan as SSOT, and the code /
git history; it forms its verdict from those + its own **cold** acceptance run, and does **not**
read `JOURNAL.md` before the verdict. After an independent verdict, consulting JOURNAL is fine
(e.g. to contextualise a finding) — note in REVIEW that you did.
In short: **WHAT + HOW + EXPECTED + WHERE = STATUS; WHY = JOURNAL.**
- **Git discipline (both loops, every write):** `git pull --rebase` before editing, make the
smallest change, commit, `git push`. On a rebase conflict, it will be inside the *other* agent's
file/section only if a rule was broken — re-pull and keep to your own files. Never `--force`.
- **Gate handshake via STATUS.md + commit-prefix signalling.** When the Builder believes a milestone
gate is met, it sets in `STATUS.md`: `Gate: <Mn> — CLAIMED, awaiting Adversary`, **commits it with a
`claim(...)` prefix**, and stops advancing past it. The Adversary runs the acceptance check cold and
writes the verdict to `REVIEW.md` (`<Mn>: PASS @<ts>` with evidence, or `FAIL` + an `[adversary]`
item), **committed with a `review(...)` prefix**. The Builder only proceeds past the gate after
seeing `PASS` in `REVIEW.md`.
- **The watchdog signals the handoff off these commit prefixes** (not by parsing prose): a new
`claim(...)` commit on origin/main pings the Adversary; a new `review(...)` commit pings the
Builder. So the prefixes are **load-bearing** — a gate claim MUST be a `claim(...)` commit and a
verdict MUST be a `review(...)` commit, or the counterpart isn't promptly woken (it falls back to
its slower self-poll). STATUS/REVIEW remain the durable source of truth; the prefix is the signal.
- **Clean tree before claim.** The Builder runs `git status` before claiming — the working tree
must be clean (everything committed AND pushed). The Adversary cold-verifies from a fresh clone,
so an uncommitted/un-pushed change that only exists on the Builder's host (e.g. a locally-built
fix) is a guaranteed cold-verify mismatch. Commit + push first, then claim.
- **DONE handshake.** Builder may write `## DONE` to `STATUS.md` **only** when `REVIEW.md` shows a
PASS dated within 24h for every D1–D10. The Adversary can write `## VETO <reason>` to
`REVIEW.md` at any time, which forbids DONE until cleared.
- **Liveness.** If the Adversary sees a gate `CLAIMED` for too long with no Builder progress, or
the Builder sees no Adversary verdict on a standing claim, note it in your own ledger and keep
doing independent work — neither loop blocks idle waiting on the other beyond its gate.
- **INBOX — explicit cross-loop messaging beyond CLAIMS.** Sometimes you have something to say to
the other loop that isn't a gate claim or a REVIEW verdict (a heads-up, a request for
early-look, a "I refactored X, please re-verify Y", an observation outside the normal flow). For
those, use the inbox files in `machine-docs/`:
- **Builder → Adversary:** the Builder writes/appends `machine-docs/ADVERSARY-INBOX.md` in its
own clone, commits, pushes.
- **Adversary → Builder:** the Adversary writes/appends `machine-docs/BUILDER-INBOX.md` in its
own clone, commits, pushes.
- The watchdog edge-triggers on **newly-present** inbox files in the relevant clone and pings
the receiver. The receiver, on receipt, reads + processes the message, then **deletes the
inbox file** (commits + pushes) — deletion is the "message consumed" signal. Single-writer
discipline: only the sender writes their counterpart's inbox; only the receiver deletes it.
- **Use for:** non-gate signals — "heads-up I'm about to refactor X," "please cold-verify this
while I keep going," "I observed Y outside our normal flow," "I'm taking a long e2e now."
**Do NOT use for:** formal gate claims (`STATUS.md` still owns those) or verdicts (`REVIEW.md`
still owns those). The inbox is a side-channel, not a replacement.
(If you are ever forced to run with a single process, the degraded fallback is to alternate
roles per iteration and keep `JOURNAL.md` and `REVIEW.md` strictly separate — but two loops is
the intended design.)
---
## 7. The Loop Protocol
Both loops run this same shape; state lives in the repo so it survives restarts/compaction. On
every wake, `git pull --rebase` first, then:
1. **Orient.** Read `STATUS.md` (phase, in-flight item, gate claims, blockers), `BACKLOG.md`, and
the tail of `REVIEW.md`. Reconcile with reality via cheap probes (Drone health, last build,
`git log`) — never trust the ledger blindly; if it disagrees with the system, fix the ledger
first (your own files only — see §6.1).
2. **Select.**
- *Builder:* highest-priority open item in `## Build backlog`: unresolved `[adversary]`
findings > current milestone's next task > next milestone. Never advance past a milestone gate
until `REVIEW.md` shows its PASS.
- *Adversary:* any standing `Gate: <Mn> CLAIMED` in `STATUS.md` to verify > re-verify a D1–D10
gate whose last PASS is stale (>24h) > a fresh break-it probe from §6.
3. **Act.** Smallest change that advances the item. Builder verifies against the real system;
Adversary verifies from a cold start. Commit with a clear message (author per repo convention).
4. **Record (your own files only).** *Builder:* append to `JOURNAL.md` (what you did + verifying
command/output + next), update `STATUS.md`, tick `## Build backlog`. *Adversary:* append PASS/
FAIL + evidence to `REVIEW.md`, add/close items in `## Adversary findings`. Then `git push`.
5. **Gate handshake (§6.1).** Builder, on reaching a milestone, sets `Gate: <Mn> CLAIMED, awaiting
Adversary` in `STATUS.md` and works on other unblocked items meanwhile. Adversary clears it with
a `REVIEW.md` verdict. No gate is "passed" without a logged PASS.
6. **Decide continuation.** Builder writes `## DONE` only when `REVIEW.md` shows a <24h PASS for
every D1–D10 and no standing `## VETO`. Otherwise schedule the next wake.
**Pacing.** Use `/loop` (self-paced) or `ScheduleWakeup`. Most waits here are for things the
harness can't notify you about — a Drone build, a `nixos-rebuild`, a deploy converging — so poll
the *specific* thing. Three cases:
1. **Something in flight** (build/deploy/`nixos-rebuild`/e2e/heavy test) → **poll every ~5 min** to
stay cache-warm and to **see failures as they happen**, not at the end of a 25-minute sleep. Do
**NOT** `ScheduleWakeup` for the expected total runtime of the task in a single big sleep — a 25
min e2e gets 5 short cache-warm polls, not one 25-min cache-cold blackout. The wakeup that wakes
you mid-task is *cheap* (one cache hit, one quick status check); the value of catching a deploy
that died at minute 4 of a 25-min budget is large. Keep polling *it*, don't treat it as idle.
- **Recommended pattern for long deploys/convergence (builder, 2026-05-30):** **arm a `Monitor`**
that polls the node every ~30s and **wakes you on convergence OR failure**, with a **longer
fallback heartbeat** (`ScheduleWakeup`) as a backstop if the Monitor never fires. This proceeds
the *instant* the deploy converges (no over-waiting if it finishes early) and surfaces a failure
promptly, while the heartbeat bounds the wait if the condition is never met. Size the convergence
timeout sanely — longer than a few minutes if a recipe genuinely needs it, but **never absurd**
(e.g. the ~40-min ghost timeout was excessive). Beats both a single big blind sleep and a fixed
coarse poll.
2. **Blocked on the *other* loop** — Builder parked at a `CLAIMED` gate awaiting the Adversary, or
Adversary waiting for the Builder to fix an `[adversary]` finding. **You don't need to busy-poll
here: the watchdog signals across the handoff.** The moment the Builder writes a `CLAIMED` gate,
the watchdog pings the Adversary to verify *now*; the moment the Adversary updates `REVIEW.md`
(verdict/finding), it pings the Builder to proceed (`launch.sh`, ~30 s detection). So you may sleep
while blocked and trust the ping — but keep a **fallback self-poll on a modest cadence (~2–4 min)**
in case a ping is missed (a dead session is restarted by the watchdog and re-orients from the repo
anyway). The goal: a pending handoff resolves in well under a minute, not a whole idle interval.
3. **Genuinely idle, nothing pending from either loop** → sleep in chunks of **at most 10 min**, then
re-wake and re-orient; if still nothing, sleep another ≤10 min. **Never a single wait > 10 min**
(600 s) — see the liveness rule below.
Notes: **The Adversary may idle freely when nothing is pending — it should NOT pointlessly re-verify
or busy-poll to look busy.** It gets woken by the watchdog the instant the Builder claims a gate, so
"start verifying very soon after the Builder waits" is handled by the signal, not by the Adversary
spinning. **The Builder** should prefer keeping an unblocked backlog item in hand so it's rarely
*fully* blocked on a gate; only hit case 2 when everything is genuinely gated behind the pending
verification — and then rely on the watchdog ping (+ fallback poll) rather than a long idle.
**Liveness marker & max-wait (the watchdog ENFORCES this).** Every wait is capped at **10 minutes**;
to wait longer, wake at 10 min, re-check, and wait again. **Immediately before going idle for any
wait, your FINAL output line MUST be exactly:**
WAITING-UNTIL: <ISO-8601 UTC>
— the moment you intend to resume (≤10 min out, matching your `ScheduleWakeup`). Compute it from the
clock, e.g. `date -u -d '+10 min' +%FT%TZ`. The watchdog uses this to tell a healthy wait from a
wedge: if it sees a loop **idle ≥5 min with no current `WAITING-UNTIL` marker as its last message, OR
idle past the time the marker named, it kills + reboots that loop** (which then re-orients from git +
its STATUS/REVIEW files). So always leave a fresh marker before sleeping, and never overrun it.
**Proactive compaction.** If your context usage climbs high (≳80%), run `/compact` *before*
continuing — your state lives in git + the phase STATUS/REVIEW files, so compaction is lossless for
the loop and prevents wedging (garbled output, failed tool calls) near the context limit.
**Anti-drift guards.**
- Cap retries: if an approach fails 3× the same way, stop, write the dead-end in `DECISIONS.md`,
and try a different approach or mark blocked. No thrashing.
- Never weaken a test to make it pass. A red test is information; "fix" the recipe/harness or file
a finding — do not delete the assertion. (This is the single most important rule; the Adversary
watches specifically for tests being softened or skipped.)
- Keep changes reversible; prefer Nix-declared state over imperative server edits so any rebuild
reproduces it.
- Don't expand scope beyond §2. New ideas → `BACKLOG.md` (tagged `[idea]`), not into this run.
---
## 8. Open decisions to settle early (log in DECISIONS.md)
- Deploy mechanism: `nixos-rebuild --target-host` vs `deploy-rs`/`colmena`. (Default: deploy-rs
for atomic rollbacks; nixos-rebuild fine if simpler.)
- Webhook scope: per-repo vs org-level Gitea webhook. (Default: per-repo via enroll script.)
- Drone runner type: exec vs privileged docker. (Default: exec, since it must drive host abra.)
- Secret tool: sops-nix vs agenix. (Default: sops-nix for multi-recipient + yaml ergonomics.)
- Reverse proxy / Wildcard TLS: **SETTLED — deploy the real `coop-cloud/traefik` recipe via abra
(for e2e fidelity), in wildcard/file-provider mode, serving the operator's pre-issued wildcard
cert; no ACME, no token** (§4.0/§4.2). Supersedes the original plan's hand-rolled
`modules/traefik.nix`. The operator issued the wildcard SAN cert (`*.ci.commoninternet.net` +
`ci.commoninternet.net`) via LE DNS-01/Gandi out-of-band into `/var/lib/ci-certs/live/`; the agent
feeds it as the recipe's `ssl_cert`/`ssl_key` swarm secrets so the DNS-editing token never reaches
cc-ci. **Manual renewal** ~90 days (next ~2026-08-24): re-issue → update the secret → redeploy.
- Proof recipe set (D10 — six, category-spanning). Default candidates, all previously verified
deployable: `hedgedoc`, `cryptpad`, `keycloak`, `authentik`, `lasuite-docs`/`lasuite-drive`,
`matrix-synapse`, `immich`, `bluesky-pds`. Lock the final six early so M4–M6.5 build toward them.
Sequence easy→hard: prove the pipeline on `hedgedoc`/`cryptpad` before tackling SSO, S3, media
stores, and TLS-passthrough recipes.
Each default stands until the Adversary or reality forces a change; record the change and why.
---
## 9. Guardrails / hard rules
- **Access boundary:** only cc-ci is yours to reconfigure. Recipe repos: read + comment + (when
enrolling) add a webhook — nothing else. Never push to a recipe repo's code.
- **No secrets in git/logs/UI.** Ever. Verified by the Adversary's leak test.
- **No mocks for the e2e stages.** D2 means real deploys. If something can't be tested for real,
it's a finding, not a pass.
- **Idempotent + reversible.** Anything done to the server must be re-derivable from the repo.
Infra bring-up is **declarative idempotent reconciliation in Nix** — not manual post-steps and not
run-once scripts. Each piece (swarm + `proxy` net, the traefik recipe deploy, Drone, the
comment-bridge, the dashboard) is a systemd **oneshot that re-runs on every activation/boot** and
*converges* to the desired state (inspect → act only if needed → no-op if already correct), like
`swarm-init`. **No `/var/lib/.bootstrapped`-style sentinels** (they don't self-heal drift). The
goal: a from-scratch install is `git clone` + `nixos-rebuild switch` + the operator preconditions
— `docs/install.md` must never accumulate manual post-rebuild steps.
- **Stop on missing *external* infra inputs** (class-A1 in §4.4: cc-ci SSH/root access, the
Tailscale auth key, Gitea bot creds, the pre-issued wildcard cert at `/var/lib/ci-certs/live/`,
registry creds — and the preconfigured DNS/gateway facts) rather than improvising around them;
surface in `STATUS.md ## Blocked`. **Never** attempt ACME/DNS-01 for `commoninternet.net` — the
cert is pre-provided and renewed out-of-band by the operator. **This does NOT apply to** internal infra secrets (class-A2: Drone RPC,
webhook HMAC, Gitea OAuth app, host age key — the agent generates these) or to recipe app secrets
(class-B): those the test harness generates itself (`abra app secret generate` + chosen fixtures),
persists for the run, and destroys at teardown — a missing app secret is never a blocker, it is
something the harness
creates. See §4.4.
- **Real abra deploys; abra convergence by default; custom readiness only if it's a real test.**
Deploys/upgrades use the **real abra commands** (`abra app deploy`/`upgrade`) — never bypass abra
with `docker service update`/`scale`. **Prefer abra's own convergence checks.** Only skip abra's
post-deploy convergence monitor (`-c`/`--no-converge-checks`) and substitute a **harness READY_PROBE**
when abra's monitor genuinely doesn't fit (e.g. its window is too short for a heavy app and it FATAs
on a deploy that *does* converge). When you do: the deploy is still real abra (only abra's *waiting*
is replaced), and the probe MUST be a **genuinely strict** readiness test — all services N/N **plus**
a real app-level check — that **RAISES on actual non-readiness**, never a no-op that masks a failed
deploy. **Prove it has teeth** (a negative test that fails on stuck convergence, e.g. F2-12's
P7-negative). The Adversary treats a custom probe as a potential test-weakening until cold-verified.
- **Custom cc-ci compose overlays — avoid where possible, justify each, prefer upstream.** A
cc-ci-authored compose overlay (an extra `compose.*.yml` layered via `COMPOSE_FILE`) risks **drift**
from the recipe users actually run, so **avoid it where possible and justify each use**. In most
cases the cleaner fix is an **upstream recipe PR** — either a genuine robustness fix, or exposing a
knob the recipe should expose. **But a single, uniform, optional `compose.ccci.yml` overlay file per
recipe is an acceptable fallback** — especially for a value abra/compose can't take from an env var.
(One fixed filename per recipe — `compose.ccci.yml` — holding all cc-ci-side deploy tweaks; not
per-purpose suffixes.)
**Known limitation (builder, 2026-05-30): abra does NOT support an env value for a healthcheck
`start_period`.** So the ghost/discourse `start_period` bumps legitimately **need** the overlay (an
env-var PR is not possible for that field) — these overlays **stay**, justified. When you do use an
overlay: keep it **minimal + single-purpose**, **document WHY in the file header** (the exact abra/
upstream limitation that forces it), have the **Adversary confirm it doesn't weaken a test or mask a
recipe defect**, and **file the upstream PR where the fix genuinely belongs** (e.g. if a recipe's
`start_period` is too tight for any slow host, propose raising it upstream too).
- **Upgrade tier: always test the upgrade to the LATEST version.** Don't drop the upgrade test just
because the *from* (older) version is awkward. If an older from-version can't be fully deployed/tested
(its image tag was pulled 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
pick the nearest deployable prior, then **upgrade to latest and run the full assertions on the
latest**. Skipping a from-version's custom tests is an honest, recorded outcome; skipping the
upgrade-to-latest is not. (See `plan-ccci-compose-overlay-policy.md` for the per-recipe disposition.)
- **Honest reporting.** If a stage is skipped or a check failed, say so in `STATUS.md`/`JOURNAL.md`
with the output. The loop's value depends entirely on the ledgers being true.
@@ -0,0 +1,256 @@
# Recipe-customization restructure — full implementation plan
Operator-approved direction (chat 2026-06-10). Reference spec of the CURRENT system:
cc-ci `docs/recipe-customization.md` (commit 76a4b6b) — read it FIRST; its §8 R1–R9 are the
defects this plan fixes. Goals: one coherent customization system, one place/way to configure a
recipe, easy custom tests, fix broken knobs, delete legacy paths, zero behavior regression for
currently-working recipes.
## Decisions locked (operator + orchestrator)
| Question | Decision |
|---|---|
| Loaders | ONE loader `runner/harness/meta.py::load(recipe) -> RecipeMeta` backed by a declarative KEY registry. All six current loaders (spec §4 L1–L6) migrate to it; `exec()` of recipe_meta.py happens in exactly one function. |
| Validation strictness | Unknown ALL-CAPS top-level name or type mismatch = **hard error** (run fails fast at load; unit test catches at PR time). Underscore-prefixed names (`_FOO`) are recipe-private and exempt. |
| `SCREENSHOT` | KEEP and FIX (it is currently dead — spec §8 R2). Reachable once the registry replaces the allowlist. |
| `CHAOS_BASE_DEPLOY` | DELETE. `tests/<recipe>/compose.ccci.yml` becomes first-class: harness copies it into the checkout + auto-uses `--chaos` for the base deploy. Both users (ghost, discourse) use the flag only for this. |
| `OIDC_AT_INSTALL` | DELETE. Install-time deps provisioning becomes the ONLY mode when `DEPS` is set; legacy post-deploy provisioning + `setup_custom_tests.sh` redeploy path removed. Migrate lasuite-docs. |
| `SKIP_GENERIC` (meta key) | DELETE (zero users). Env form `CCCI_SKIP_GENERIC*` stays as a documented LOCAL-DEV-ONLY escape hatch, loudly surfaced in the run manifest. |
| Hook signatures | All recipe callables take a single `ctx` (HookCtx) — `EXTRA_ENV(ctx)`, `UPGRADE_EXTRA_ENV(ctx)`, `READY_PROBE(ctx)`, `BACKUP_VERIFY(ctx)`, `SCREENSHOT(page, ctx)`, `pre_<op>(ctx)`. All users are in-repo; migrate them, no compat shim. |
| Fixtures | Single `tests/conftest.py`. Final surface: `recipe`, `meta` (full RecipeMeta), `live_app`, `op_state` (NEW), `deps` (NEW — consolidates `deps_apps`+`deps_creds`). DELETE dead pre-deploy-once fixtures `deployed`/`deployed_app` (zero users) and `app_domain` if nothing else uses it (builder: grep). |
| Custom-test placement | `test_<op>.py` top-level = lifecycle overlay; ALL custom tests under `functional/` or `playwright/`. Discovery of top-level non-lifecycle `test_*.py` in recipe dirs is REMOVED (zero users today). |
| Docs | Key reference table is GENERATED from the registry; a unit test asserts docs ⊆ registry sync. |
| recipe_meta stays Python | NO data/hooks file split (spec §8 R9 considered, rejected — registry validation gets the value at lower cost). One file per recipe remains the single config place. |
| Landing | one branch `restructure/recipe-custom`, one commit per phase, merged to main only after Adversary M1 PASS + lint green; real-CI regression sweep (M2) after merge. |
## Target shape (end state)
```
tests/<recipe>/
├── recipe_meta.py # THE config: registry-validated keys + ctx-hooks (+ _private consts)
├── test_<op>.py # lifecycle overlay asserts (op_state/live_app/meta fixtures)
├── ops.py # pre_<op>(ctx) seed hooks
├── functional/ playwright/ # ALL custom tests
├── install_steps.sh # pre-deploy shell hook (the only shell hook)
├── compose.ccci.yml # first-class CI overlay (auto-copied, auto-chaos)
└── PARITY.md
```
One loader, one hook convention, one fixture file, one shell hook, one generated reference.
---
## P1 — `harness/meta.py`: single loader + key registry
1. New `runner/harness/meta.py`:
- `KEYS`: registry of every key — `name, type ("int"|"str"|"tuple[int]"|"bool"|"dict_or_hook"|
"hook"|"list[str]"|"dict"), default, doc` (one line each), optional `validate(value)`.
Final key set (14): HEALTH_PATH, HEALTH_OK, DEPLOY_TIMEOUT, HTTP_TIMEOUT, BACKUP_CAPABLE,
EXPECTED_NA, READY_PROBE, UPGRADE_BASE_VERSION, BACKUP_VERIFY, UPGRADE_EXTRA_ENV, EXTRA_ENV,
DEPS, WARM_CANONICAL, SCREENSHOT. (CHAOS_BASE_DEPLOY / OIDC_AT_INSTALL / SKIP_GENERIC are
deleted in P2 — during P1 keep them registered with `deprecated=True` so P1 lands green
before P2 removes them.)
- `load(recipe) -> RecipeMeta` (frozen dataclass, attribute access): the ONLY `exec()` of
`tests/<recipe>/recipe_meta.py`. Missing file → all defaults. Validation per the locked
decision: unknown non-underscore ALL-CAPS name → `MetaError` listing the unknown name and
nearest registered key; type mismatch → `MetaError`. Callables accepted only for hook-typed
keys.
2. Migrate ALL readers (spec §4 L1–L6 + §9 index has exact locations):
- `run_recipe_ci.py::_load_meta` → `meta.load()`; orchestrator loads ONCE and passes the
object down (functions grow a `meta` param; stop re-exec'ing per call).
- `tests/conftest.py::_recipe_meta` → `meta.load()` (fixture now returns full RecipeMeta).
- `lifecycle.py::_recipe_extra_env`, `lifecycle.py::_recipe_meta_flag` → deleted; callers take meta.
- `deps.py::declared_deps` → `meta.DEPS`; `canonical.py::is_canonical_enrolled` → `meta.WARM_CANONICAL`.
- `screenshot.py` consumer unchanged — but now the dict/object it receives actually contains
SCREENSHOT. **This is the R2 fix; prove it with a unit test** (meta with SCREENSHOT hook →
`_load_screenshot_hook` returns it through the real orchestrator load path).
3. Mumble private constants `WELCOME_TEXT_MARKER`, `MAX_USERS` → `_WELCOME_TEXT_MARKER`,
`_MAX_USERS` (fix their importers; builder: grep how mumble tests consume them).
4. New unit tests `tests/unit/test_meta.py`:
- every `tests/*/recipe_meta.py` in the repo loads clean through the registry (the typo gate);
- unknown-key and wrong-type files (tmp fixtures) raise MetaError;
- defaults match spec §2 baseline; underscore exemption; callable-on-data-key rejected.
5. Doc generation: `scripts/gen-meta-docs.py` renders the registry to a markdown table between
`<!-- META-TABLE-START/END -->` markers in `docs/recipe-customization.md` §4; unit test asserts
the committed table == rendered output (drift fails CI).
## P2 — Delete legacy keys & paths
a. **compose.ccci.yml first-class.** In the deploy path (after `install_steps.sh`, before base
deploy): if `tests/<recipe>/compose.ccci.yml` exists, copy it into the recipe checkout
(ABRA_DIR-aware) and use `--chaos` for the base deploy. Remove the copy boilerplate from
ghost/discourse `install_steps.sh` (delete the hook file entirely if copying was all it did —
builder: read both) and `CHAOS_BASE_DEPLOY = True` from both metas. Delete `_recipe_meta_flag`
remnants. Keep the policy note (overlays = minimal justified fallback) in docs.
b. **Install-time deps only.** Make the `OIDC_AT_INSTALL=True` code path the unconditional
behavior for recipes with DEPS; delete the legacy post-deploy provisioning branch, the
`setup_custom_tests.sh` invocation machinery, and the deploy-count exception for the legacy
redeploy. Migrate `lasuite-docs` to install-time wiring (mirror what lasuite-drive/meet do in
`install_steps.sh` reading `$CCCI_DEPS_FILE`). NOTE: lasuite-drive ALSO ships
`setup_custom_tests.sh` despite OIDC_AT_INSTALL=True — builder must read both scripts and
determine what they still do (realm/user provisioning is harness-side via `harness.sso`; env
wiring belongs in install_steps.sh). Whatever remains necessary moves into
`install_steps.sh`; then delete both `setup_custom_tests.sh` files and the key.
c. **SKIP_GENERIC meta key deleted**; env `CCCI_SKIP_GENERIC*` documented dev-only; if set in a
CI (drone) run, print a loud `!!` warning + record in the P5 manifest.
d. **Conftest cleanup**: delete `deployed`, `deployed_app` (dead, zero users — verified), and
`app_domain` if unused after their removal. Consolidate `deps_apps` + `deps_creds` into one
`deps` fixture (entries expose `.domain` plus full creds; dict-style access fine). Migrate the
6 lasuite test files that use the old pair. Keep `requires_deps` marker + skip-report plumbing
unchanged (F2-11 gate — do NOT weaken).
## P3 — Uniform `ctx` hook convention
1. `harness/meta.py::HookCtx` (frozen dataclass): `.domain`, `.base_url`, `.meta` (RecipeMeta),
`.deps` (creds dict or None), `.op` (current lifecycle op or None). One constructor helper in
the orchestrator; harness builds it at each hook call site.
2. Convert call sites: `EXTRA_ENV(ctx)`, `UPGRADE_EXTRA_ENV(ctx)`, `READY_PROBE(ctx)`,
`BACKUP_VERIFY(ctx)`, `SCREENSHOT(page, ctx)`, `ops.py pre_<op>(ctx)`. Dict-valued
EXTRA_ENV/UPGRADE_EXTRA_ENV (non-callable) still allowed — only the callable signature changes.
3. Migrate every in-repo user (spec §4 lists them per key; ops.py exists in ghost, discourse,
immich, lasuite-*, mumble, others — builder: glob). Mechanical change; assertions and seeded
values must remain byte-identical.
4. Unit tests: hook invocation passes a ctx with correct fields; a legacy-signature callable
(`lambda domain: ...`) raises a CLEAR MetaError naming the migration (no silent TypeError
mid-run).
## P4 — Custom-test ergonomics
1. `discovery.py::custom_tests`: drop the top-level `test_*.py` glob for recipe dirs (keep
`functional/` + `playwright/`); lifecycle-name exclusion logic stays for safety. (Zero current
users of top-level custom tests — verified; the change is doc'd as a placement RULE.)
2. New fixtures in `tests/conftest.py`:
- `op_state` — parse `$CCCI_OP_STATE_FILE` (skip with clear reason if unset/absent);
- `deps` — from P2d.
Migrate overlay tests that hand-parse `CCCI_OP_STATE_FILE` / env (builder: grep
`CCCI_OP_STATE_FILE|os.environ` under `tests/*/test_*.py` + `functional/`) to fixtures. Tests
should not read `os.environ` directly except via fixtures after this phase (grep-clean,
excluding conftest itself).
3. `harness` import surface: ensure `from harness import lifecycle, sso, browser` is the
documented toolbox; no new module needed — docs job (P6).
## P5 — Customization manifest
At run start (after meta load + discovery), print ONE block and embed the same dict in
`results.json` under `"customization"`:
```
===== customization manifest: <recipe> =====
meta (non-default): DEPLOY_TIMEOUT=1500 HTTP_TIMEOUT=600 DEPS=['keycloak'] ...
hooks: ops.py[pre_upgrade,pre_backup,pre_restore](cc-ci) install_steps.sh(cc-ci) compose.ccci.yml(cc-ci)
overlays: test_backup.py(cc-ci) test_restore.py(repo-local)
custom tests: functional/=5 playwright/=2 (cc-ci) functional/=1 (repo-local)
env overrides: CCCI_SKIP_GENERIC_BACKUP=1 !! dev-only override active in CI
```
Pure presentation + one results.json key — MUST NOT influence any verdict. Unit test: manifest for
a synthetic recipe dir is complete + deterministic; results schema test updated.
## P6 — Docs
- `docs/recipe-customization.md`: §4 table generated (P1.5); §8 rewritten — R1/R2/R3/R6/R7/R8
resolved (say how), R4 mitigated by manifest, R9 rejected-by-decision; §3/§5 updated to the
end-state shape (no setup_custom_tests.sh, placement rule, ctx hooks, fixtures incl. op_state/deps).
- `docs/testing.md` + `docs/enroll-recipe.md`: remove their partial key lists (point at the
generated table), update hook signatures, fixture names, lasuite-docs worked example, local-run
instructions.
- Keep all three docs' scope split: concepts (testing.md) / how-to (enroll-recipe.md) /
reference+structure (recipe-customization.md).
---
## Test suite additions (run inside `pytest tests/unit -q` — these are cheap/pure)
- `tests/unit/test_meta.py` (P1.4) — registry, validation, all-recipes-load-clean, R2 proof.
- ctx-hook tests (P3.4).
- discovery placement tests (P4.1) — top-level custom no longer discovered; functional/playwright are.
- manifest tests (P5).
- doc-sync test (P1.5).
- KEEP every existing unit test green; where a unit test pins old behavior being deleted
(allowlist loaders, setup_custom_tests, deployed fixtures, top-level discovery), update it to
pin the NEW behavior — never delete a test without a replacement that covers the successor path.
## Roles, gates & Definition of Done (loop protocol — plan.md §6.1 applies)
Builder/Adversary loops, phase-namespaced state files: STATUS-rcust.md, REVIEW-rcust.md,
BACKLOG-rcust.md, JOURNAL-rcust.md.
**Builder** (fable): implement P1→P6 on branch `restructure/recipe-custom` in YOUR clone; one
commit per phase; before each commit ALL green: `pytest tests/unit -q`, `scripts/lint.sh`
(tests/concurrency NOT required — untouched by this plan; run it once before M1 to prove that).
Push the branch (NOT main — merge gated below). Claim gates via `claim(rcust): ...` commits +
STATUS-rcust.md.
**Adversary** (opus): cold-verify from your own clone. For M1: check out the branch, run
`pytest tests/unit -q` + `pytest tests/concurrency -q` + lint yourself, then adversarial review of
the FULL diff. Hunt specifically:
- **coverage loss** — the cardinal risk of this restructure. For EVERY migrated recipe, diff the
resolved customization (old loaders' effective values vs new `meta.load()`) — write a throwaway
script that computes both for all 21 recipe dirs and diffs; any delta is a finding.
- assertion weakening in `tests/<recipe>/` diffs: migrations must be mechanical (signatures,
fixture names, underscore renames); any changed assert/expected-value = VETO.
- deleted-code fallout: grep for dangling refs to `_recipe_meta`, `_load_meta`,
`_recipe_extra_env`, `_recipe_meta_flag`, `declared_deps`, `is_canonical_enrolled`,
`OIDC_AT_INSTALL`, `CHAOS_BASE_DEPLOY`, `SKIP_GENERIC`, `setup_custom_tests`, `deps_apps`,
`deps_creds`, `deployed_app`.
- validation gaps: craft a recipe_meta with a typo'd key / wrong type / callable-on-data-key —
must MetaError, not silently pass.
- R2 actually fixed end-to-end (orchestrator path delivers SCREENSHOT to screenshot.py).
- HC2 gate integrity: repo-local default-deny unchanged; `requires_deps` skip-report (F2-11)
unchanged; generic floor semantics unchanged.
Findings to REVIEW-rcust.md; Adversary owns VETO.
**Gates:**
- **M1 — implementation verified.** Branch complete (P1–P6 + tests), unit+concurrency+lint green
on the Adversary's cold clone, resolved-customization diff clean for all 21 recipes,
adversarial diff review PASS in REVIEW-rcust.md.
- **M2 — merged + REAL-CI REGRESSION SWEEP (operator-required).** After M1 PASS only, Builder
merges to main (merge commit, never force) and confirms the push build green. Then EVERY
enrolled recipe is re-run through the real harness and must match its pre-change baseline:
1. **Baseline matrix first** (build it BEFORE merging, during M1): for each of the 21 recipe
dirs record expected outcome from the most recent known-good evidence (dashboard/results
history; the bad-canary recipes custom-html-bkp-bad/rst-bad are EXPECTED to fail at their
designed tier — record the tier). Commit the matrix to STATUS-rcust.md.
2. **Canary suite** on the merged main: `cc-ci-run python -m pytest tests/regression/ -m canary -v`
— all seven canaries (green canaries pass, RED canaries still caught at the intended tier;
this is the false-green detector).
3. **Per-recipe full runs** on the merged main, every enrolled recipe:
`RECIPE=<r> PR=<n> REF=<sha> SRC=recipe-maintainers/<r> STAGES=install,upgrade,backup,restore,custom cc-ci-run runner/run_recipe_ci.py`
using each mirror's current default-branch head as REF (or the open PR head where one exists —
immich#2, plausible#3 may also be exercised via `!testme` through drone for at least TWO
recipes so the drone→harness path is covered too). Max 2–3 concurrent (respect runner
capacity); teardown verified after each (zero leaked apps — janitor sweep clean).
4. **Verdict + evidence**: per-recipe result level == baseline matrix. ALSO spot-grep run logs
to prove customizations actually executed (no silent loss): mumble READY_PROBE tcp lines,
cryptpad SANDBOX_DOMAIN in env, ghost/discourse BACKUP_VERIFY lines + overlay copy + chaos
base deploy, lasuite-* deps provisioning + OIDC tests ran (skip-count 0), immich ops.py
seeds, manifest block present in every log, screenshot.png present where capture succeeded.
Evidence (run ids, log excerpts) in STATUS-rcust.md; Adversary independently re-checks a
sample of ≥5 recipes' logs + ALL mismatches.
Any regression vs baseline → fix-forward on main only for trivial breakage with Adversary
approval; otherwise revert the merge (rollback below) and return to M1.
**## DONE in STATUS-rcust.md** only when M1 and M2 both show a fresh Adversary PASS in
REVIEW-rcust.md.
## Guardrails (builder + adversary MUST honor)
- This plan DOES touch `tests/<recipe>/` — but ONLY mechanically (signatures, fixture/key renames,
underscore prefixes, install_steps consolidation). NEVER change an assertion, expected value,
seeded marker, or test semantics. NEVER weaken recipe-test gates, the generic floor, HC2, or
the F2-11 skip-report.
- cc-ci main is touched ONLY by the M2 merge after M1 PASS (and gated fix-forwards in M2). Never
force-push. NEVER merge or push recipe-mirror repos — `!testme` comments only.
- No secrets in commits; reference `.testenv` / `/run/secrets` locations only.
- Teardown all dev/test deploys on every exit path; M2 sweep must leave zero apps behind.
- Do NOT touch concurrency machinery (lifetime.py, app locks, janitor, ABRA_DIR) beyond
pass-through `meta` params.
- Match repo commit style (`feat(harness)`/`fix(...)`/`test(...)`/`docs:`).
- Stuck >2 cycles on the same defect → write it to BACKLOG-rcust.md + JOURNAL-rcust.md and ping
the orchestrator via INBOX rather than thrashing.
## Rollback
Single revert of the merge commit restores the six-loader world; recipe_meta.py edits ride in the
same merge so the revert is self-consistent. No persistent state involved (config is all
in-repo); re-running the M2 sweep after a revert re-validates the old world.
@@ -0,0 +1,33 @@
[Unit]
# Canonical, version-controlled copy of the unit for the cc-ci-orchestrator VM.
# Install: sudo install -m0644 cc-ci-plan/systemd/cc-ci-loops.service /etc/systemd/system/ \
# && sudo systemctl daemon-reload && sudo systemctl enable cc-ci-loops.service
# NOTE: the VM's actual reboot-resilience service is declared in nix/configuration.nix (systemd.services.cc-ci-loops).
# This file is the repo reference copy — keep both in sync when making changes.
# Brings the WHOLE rig back after a reboot of the cc-ci-orchestrator VM: loops + watchdog (launch.sh) AND
# the orchestrator supervisory session (launch-orchestrator.sh), plus a reboot record (reboot-log.sh).
Description=cc-ci autonomous loops + watchdog + orchestrator (reboot-resilient)
Documentation=file:///srv/cc-ci/cc-ci-plan/plan.md
After=network-online.target tailscaled.service
Wants=network-online.target
[Service]
Type=oneshot
RemainAfterExit=yes
User=loops
Group=loops
Environment=HOME=/home/loops
Environment=PATH=/home/loops/.local/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
# RESUME_PHASE=1 so a reboot resumes the SAVED phase (e.g. phase 2), never restarts from phase 0/1c.
Environment=RESUME_PHASE=1
# 1) record the reboot (boot_id-gated); 2) start loops + watchdog; 3) resume the orchestrator session.
ExecStartPre=/srv/cc-ci/cc-ci-plan/reboot-log.sh
ExecStart=/srv/cc-ci/cc-ci-plan/launch.sh start
ExecStartPost=/srv/cc-ci/cc-ci-plan/launch-orchestrator.sh start
# Stop only the loops + watchdog. The orchestrator session is intentionally LEFT running on a manual
# `systemctl stop` (stopping the loops shouldn't kill your steering session; it resumes from disk).
ExecStop=/srv/cc-ci/cc-ci-plan/launch.sh stop
TimeoutStartSec=180
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,124 @@
# Acceptance test — real end-to-end `!testme` on the clean-room-rebuilt VM
**Owner:** the Builder + Adversary loops (they execute *and* independently verify this).
**When:** after **C4/C5 PASS** (genuine throwaway-VM clean-room rebuild verified). The Builder then
performs the tailnet swap (§1) and runs the e2e; the Adversary independently verifies. It is the
**functional acceptance** of D8/clean-room: proof that the rebuilt-from-git VM doesn't just match
byte-for-byte, but actually *serves a real CI run end-to-end through the public domain*.
**This file:** `/srv/cc-ci/cc-ci-plan/test-e2e-testme-acceptance.md`
---
## 0. Why
The reproducibility gates (C1–C5) prove the rebuilt VM is structurally identical and boots clean.
This test proves it is **operationally** a working CI server: a maintainer comment triggers a build,
the app deploys and is reachable on its real public URL through the operator's gateway, the test
passes, and it tears down — the whole `!testme` pipeline, on the from-git VM, over the real domain.
---
## 1. Setup — the Builder performs the tailnet swap (then the e2e)
The rebuilt throwaway must become the live `cc-nix-test` so that the public gateway routes real
`ci.commoninternet.net` traffic to it (the gateway TLS-passthroughs via MagicDNS to
`cc-nix-test.taila4a0bf.ts.net` and re-resolves every ~10s, so it auto-follows the name). The swap is
**two reversible `tailscale set --hostname` commands** on VMs you already control — the Builder does
it. **Do this only after C4/C5 PASS** and after the rebuilt VM's full stack
(traefik + bridge + drone + dashboard) is up and serving locally.
**Order matters** (rename the original *aside first*, or the throwaway will get `cc-nix-test-1`):
1. **Rename the original prod VM aside** (it stays running — do NOT destroy it; needed for swap-back):
```
ssh cc-ci 'tailscale set --hostname=cc-nix-test-orig'
```
(`ssh cc-ci` is pinned to the original's IP `100.90.116.4`, so it keeps reaching the original
regardless of the name change.)
2. **Rename the rebuilt throwaway → `cc-nix-test`.** Re-derive its current tailscale IP (throwaways
get a fresh IP each rebuild): pick the ONLINE throwaway node from
`tailscale status | grep -i throwaway`, then:
```
ssh -i /srv/incus-terraform-nix-vm-creator/terraform-secrets/vm_ssh_key \
root@<throwaway-ip> \
'tailscale set --hostname=cc-nix-test'
```
(The orchestrator VM is a direct tailnet peer — no ProxyCommand needed.)
**Heads-up — tailnet-wide effect:** after the swap, `cc-nix-test.taila4a0bf.ts.net` resolves to the
rebuilt VM for *everyone* on the tailnet, so any of your own tooling that targets cc-nix-test **by
MagicDNS name** will now hit the rebuilt VM (tooling pinned to the raw IP `100.90.116.4` still hits
the original). Account for that when you point `!testme`/deploys.
**Verify the swap took (P1+P2) before starting the e2e** — must pass:
```
tailscale status | grep cc-nix-test # → the throwaway's IP
curl -sS -o /dev/null -w '%{http_code} ssl_verify=%{ssl_verify_result}\n' https://ci.commoninternet.net/
# expect: 200 ssl_verify=0 (real public path now served by the rebuilt VM, valid cert)
```
**Swap-back when testing is done** (reversible): rename the throwaway back to its old name, then
`ssh cc-ci 'tailscale set --hostname=cc-nix-test'` to restore the original; the gateway re-follows.
---
## 2. Procedure
1. **Pick one fast, already-enrolled recipe.** Prefer the lightest enrolled app (e.g. `custom-html`)
so the run is quick and resource-cheap. Note the recipe + the repo/issue or PR where `!testme` is
recognised (the same place prior runs were triggered).
2. **Record the baseline.** Capture the recipe's *current* latest Drone run number and the dashboard
row (`https://ci.commoninternet.net/` and `https://drone.ci.commoninternet.net/...`) so you can
prove the run you trigger is **new**.
3. **Trigger via the real path.** Post `!testme` as the **bot** (the normal maintainer-comment
trigger) on that recipe — exactly as a real maintainer would. Do **not** invoke Drone directly or
shortcut the bridge; the comment→bridge→Drone path is part of what's under test.
4. **Confirm the bridge picked it up.** Within the bridge's poll interval, a **new** Drone build for
that recipe starts. Capture the new run number (must be > the baseline from step 2).
5. **Confirm the app deploys and is reachable on its PUBLIC URL.** While the build runs, the app is
deployed to its `*.ci.commoninternet.net` test domain. From **off the VM** (external — through the
gateway, not `localhost`/`127.0.0.1`), confirm a real request succeeds:
```
curl -sS -D- -o /dev/null https://<app-test-subdomain>.ci.commoninternet.net/
# expect: HTTP 200 (or the app's expected status), valid *.ci.commoninternet.net cert,
# served content from the deployed app — NOT a Traefik 404 / default-cert.
```
This is the crux: it proves routing public-DNS → gateway → MagicDNS → rebuilt VM → Traefik →
deployed app all works on the rebuilt server.
6. **Confirm the test logic passed.** The Drone build runs the recipe's real test assertions (app
state, not health-only) and finishes **success**.
7. **Confirm teardown.** After the run, the app is **undeployed** (no leftover stack/containers), per
the standard post-run cleanup — verify it's gone.
8. **Confirm the result was reported.** The outcome posts back to the trigger location and the
dashboard row updates to the new run with `success`.
---
## 3. Pass criteria (all must hold; Adversary verifies independently)
- [ ] **E1.** Self-check §1 passed (`ci.commoninternet.net` = 200, valid cert, on the rebuilt VM).
- [ ] **E2.** Posting `!testme` produced a **new** Drone build (run # > baseline) via the bridge —
not a manual Drone trigger.
- [ ] **E3.** The deployed app answered an **external** request on its real
`<app>.ci.commoninternet.net` URL (through the gateway) with the expected response + valid cert
— captured with headers/body evidence.
- [ ] **E4.** The Drone build's **real test assertions** ran and the build finished **success**
(no skipped/softened tests).
- [ ] **E5.** The app **undeployed** cleanly afterward (no residual stack).
- [ ] **E6.** Result reported back + dashboard updated to the new successful run.
Evidence (run #, the external `curl` headers/body, dashboard before/after, undeploy proof) is logged
in `JOURNAL-1c.md`, and the verdict in `REVIEW-1c.md` / `STATUS-1c.md` as **E2E-TESTME — PASS**.
## 4. If it fails
Treat as a clean-room finding, not a config patch: a failure here means the from-git rebuild is
missing something the running server had out-of-band (a secret, a manual step, drift). Capture the
failing stage + logs in `JOURNAL-1c.md`, raise it as a blocker, and fix it in the **git source**
(base or `cc-ci-secrets`) so the next rebuild includes it — do **not** hand-fix the live VM. Re-run
this test after the fix.
## 5. Bound
One recipe, one green run. This is a functional smoke test of the rebuilt VM, not a full recipe-test
campaign (that's Phase 2). Don't expand scope here.
+327
View File
@@ -0,0 +1,327 @@
# Deploying a cc-ci host from scratch
This is the whole path from "nothing" to a working CI server + orchestrator on one Hetzner
server. It was last done on 2026-09-07 for `195.201.88.249` and is written so a person or an LLM
can repeat it. Read it once before starting; the order matters.
## 0. What you need in hand
- A **Hetzner Cloud** project you can create servers in (console login or an API token).
- **SSH keys**: yours, and the orchestrator's own key so the automation can reach the box. The
public keys that get root are tracked in `nix/hosts/cc-ci/ssh-keys` (one per line). Password
login is disabled and fail2ban watches sshd, so a key is the only way in.
- Read access to `recipe-maintainers/cc-ci`, `recipe-maintainers/cc-ci-orchestrator` (both public
read) and the **private** `recipe-maintainers/cc-ci-secrets` (the `autonomic-bot` account has
it; the host gets its own deploy key on that account, §4b/§4c — and the bot password, in
`.testenv`, is what registers it).
- The out-of-band secrets listed in §4. If you are migrating, they come from the old host; if
you are starting fresh you create them (each row says how).
- Control of the DNS zone (Gandi for `commoninternet.net`) for the cutover in §7.
## 1. Provision the server on Hetzner (Debian image)
In the Hetzner Cloud console (or with `hcloud server create`):
| setting | value | why |
|---|---|---|
| Image | **Debian 13** (any recent Debian/Ubuntu works with nixos-infect) | it is replaced by NixOS in §2 |
| Type | **x86**, **8 GB RAM**, 4 vCPU — e.g. `cpx32` (dedicated AMD) or `cx33`. **Never `cax*`** (ARM): the flakes are `x86_64-linux`. | swarm + recipe deploys + 3–6 agent sessions; 4 GB is too small |
| Disk | the type's default 150+ GB NVMe | docker layers alone are ~60 GB after a few weeks |
| Network | public **IPv4** required; IPv6 optional (leave enabled or not, NixOS config ignores it) | cc-ci serves 80/443 and DNS on 53 publicly |
| SSH keys | add every key from `nix/hosts/cc-ci/ssh-keys` you want to log in with, at least the orchestrator's | nixos-infect carries `/root/.ssh/authorized_keys` over |
| Name | `cc-ci` | becomes the hostname |
| Firewall | if a Hetzner Cloud Firewall is attached it must allow **22/tcp, 80/tcp, 443/tcp, 53/tcp, 53/udp** in, and ICMP | the NixOS firewall is separate and is configured by the flake |
Check you can log in: `ssh root@<ip> hostname`.
## 2. Convert Debian → NixOS with nixos-infect
[nixos-infect](https://github.com/elitak/nixos-infect) installs NixOS over the running Debian and
reboots. Run it detached so the SSH session dropping does not kill it:
```bash
ssh root@<ip> 'cat > /root/infect.sh <<"EOF"
#!/usr/bin/env bash
set -euo pipefail
# Pinned nixos-infect revision (same one that built the previous cc-ci hosts).
INFECT_SHA="40f62a680bb0e8f2f607d79abfaaecd99d59401c"
export NIX_CHANNEL="nixos-26.05" # must match the nixpkgs channel in flake.nix
export PROVIDER="hetznercloud" # GRUB + Hetzner networking
export NIXOS_IMPORT="" # the real config comes from the flake in §5
# The Debian 13 cloud image mounts /tmp as tmpfs; nixos-infect makes a temporary swapfile
# there and swapon fails with "Invalid argument". 8 GB RAM needs no extra swap: skip it.
export NO_SWAP=true
curl -fsSL "https://raw.githubusercontent.com/elitak/nixos-infect/${INFECT_SHA}/nixos-infect" | bash -x
EOF
chmod +x /root/infect.sh
nohup /root/infect.sh > /var/log/nixos-infect.log 2>&1 &'
```
It downloads Nix, builds a NixOS system (5–10 min; follow with
`ssh root@<ip> tail -f /var/log/nixos-infect.log`), then reboots. The SSH host key changes:
`ssh-keygen -R <ip>` and confirm `ssh root@<ip> nixos-version` prints a 26.05 version.
### 2a. What went wrong on 2026-09-07, and the fixes (Debian 13 image, NixOS 26.05)
All three bit on the first attempt; the script above and §3 already include the fixes, this is
so you recognise them if they come back in another form.
1. **`swapon: /tmp/nixos-infect.XXXX.swp: Invalid argument`** right at the start, script exits.
The Debian 13 cloud image mounts `/tmp` as tmpfs and a swapfile cannot live there.
Fix: `NO_SWAP=true` (in the script above). An 8 GB box does not need the temporary swap.
2. **The box never comes back after the reboot: it boots NixOS, but nearly every unit fails**
(`dbus`, `systemd-logind`, `sshd`, networking …) with
`Could not start dynamically linked executable: /usr/bin/dbus-daemon` in the journal.
nixos-infect leaves the old Debian root in place and relies on NixOS's first boot to move it
to `/old-root` (`/etc/NIXOS_LUSTRATE`). With NixOS 26.05's systemd-based initrd that
lustration did not happen, so Debian's `/etc/systemd/system/*.service` files shadowed the
NixOS units and started Debian binaries. Fix, from Hetzner **rescue mode**
(`enable_rescue` + `reset` in the API/console, ssh in, `mount /dev/sda1 /mnt/root`):
move everything except `nix`, `boot`, `swapfile`, `lost+found`, `var/log`, `var/empty`,
`etc/nixos`, `etc/resolv.conf`, `etc/NIXOS`, `etc/machine-id`, `etc/ssh/ssh_host_*`,
`root/.nix-*`, `root/.ssh` into `/mnt/root/old-root`, delete `etc/NIXOS_LUSTRATE`, unmount,
`disable_rescue`, `reset`. (`/old-root`, ~1 GB, can be deleted once the host is in service.)
3. **Boots, units fine, but no network.** The generated `networking.nix` has
`defaultGateway = "172.31.1.1";` — a bare string. Since NixOS 25.05 that yields no default
route. Fix: `defaultGateway = { address = "172.31.1.1"; interface = "eth0"; };` (this is what
`nix/hosts/cc-ci/networking.nix` carries). To apply it from rescue mode, chroot into the
mounted root and rebuild the boot entry — the nix sandbox cannot `pivot_root` inside a chroot,
so turn it off for that one build:
```bash
for d in proc sys dev dev/pts; do mount --bind /$d /mnt/root/$d; done
mount -t tmpfs tmpfs /mnt/root/run; cp -L /etc/resolv.conf /mnt/root/etc/resolv.conf
chroot /mnt/root /nix/var/nix/profiles/system/sw/bin/bash -c '
export PATH=/nix/var/nix/profiles/system/sw/bin NIX_REMOTE= HOME=/root
export NIX_PATH=nixos-config=/etc/nixos/configuration.nix:nixpkgs=/root/.nix-defexpr/channels/nixos
ln -sfn /nix/var/nix/profiles/system /run/current-system
nixos-rebuild boot --option sandbox false'
```
The `journalctl -D /mnt/root/var/log/journal -b 0` trick (reading the dead system's journal
from rescue mode) is what told these apart.
> Rescue mode without a console: `POST /servers/<id>/actions/enable_rescue` with your ssh key
> id, then `…/actions/reset`; afterwards `disable_rescue` **and check `rescue_enabled` is false
> before** the next `reset`, or it boots the rescue image again. `scripts/recovery/hetzner.py`
> wraps these (token in `/srv/cc-ci/.hcloud-token`).
## 3. Capture the machine-specific config into this repo
nixos-infect wrote `/etc/nixos/{hardware-configuration,networking,configuration}.nix`. Only the
first two matter; the flake replaces `configuration.nix`.
```bash
scp root@<ip>:/etc/nixos/hardware-configuration.nix nix/hosts/cc-ci/hardware.nix
scp root@<ip>:/etc/nixos/networking.nix nix/hosts/cc-ci/networking.nix
```
Then in `nix/hosts/cc-ci/`:
- `hardware.nix`: keep as generated (GRUB EFI with `efiInstallAsRemovable`, `/boot/efi` by UUID,
`/dev/sda1` root). Do not copy another host's file — the UUIDs are per machine.
- `networking.nix`: keep the static IPv4 + Hetzner gateway `172.31.1.1`. Make sure
`networking.defaultGateway` has **both** `address` and `interface = "eth0"` (§2a item 3). If
the generated IPv6 block has an empty address, delete the IPv6 parts; a real global address
(as on the 2026-09 box) can stay.
- `configuration.nix`: set `cc-ci.publicIPv4` to the server's IPv4 and check `system.stateVersion`
is the release you installed (never change it later).
- `ssh-keys`: the root keys.
Commit on a branch; the rebuild in §5 can use the local checkout before the PR merges.
## 4. Stage the workspace and secrets on the new host
Everything in this section is **outside git**. Do it as root over SSH, in this order.
### 4a. No tailscale
The combined host is NOT on the tailnet (operator decision 2026-09-07): ssh is key-only on the
public IP, the CI front doors are public via traefik, and the opencode UI is public on the same
443 — traefik routes `oc.ci.commoninternet.net` to an nginx vhost on the docker bridge that
enforces basic auth, via traefik labels on a tiny swarm relay stack (`ccci-opencode-ui`, on the weekly sweep's keep-list) that
`opencode-ui-route.service` deploys. (Not via traefik's file *directory* provider: enabling
that in the coop-cloud traefik recipe REPLACES its provider file, which holds the wildcard cert
and the `security` middleware, and every front door goes down — it did, for two minutes, on
2026-09-07.) fail2ban guards sshd and that login
(`nix/hosts/cc-ci/configuration.nix`; the nginx jail bans in the DOCKER-USER chain because the
traffic is docker-forwarded, not host INPUT).
### 4b. The CI server's checkout and its one out-of-band secret
```bash
# the bot deploy key for the private cc-ci-secrets submodule — generated ON this host by loops
# (§4c) and registered on the autonomic-bot Gitea account; root only points at it:
install -d -m700 /root/.ssh
cat > /root/.ssh/config <<'SSHCFG'
Host git.autonomic.zone
Port 2222
User git
IdentityFile /secrets/files/autonomic-bot-cc-ci-ed25519
IdentitiesOnly yes
SSHCFG
# the deployed checkout: nightly-sweep runs from it, sops reads secrets/secrets.yaml from it
git clone --recursive https://git.autonomic.zone/recipe-maintainers/cc-ci.git /etc/cc-ci
# the age identity sops-nix decrypts with. FIRST deploy of a host that is not yet a recipient:
# the master (recovery) key, temporarily. Once the host is a recipient (below): its own
# ssh-host-key-derived identity, and the master key leaves the box.
install -d -m0700 /secrets/host
install -m600 <master-age.txt> /secrets/host/sops-age-key.txt
```
`/etc/cc-ci/secrets/secrets.yaml` is encrypted to the master key and the *previous* hosts' SSH
host keys. The master key is enough for the FIRST deploy. Then make the new host a recipient so
the master key can leave the box again (it belongs off-box, with the operator):
`ssh-to-age < /etc/ssh/ssh_host_ed25519_key.pub` → add it to `.sops.yaml` in cc-ci-secrets AND in
cc-ci, `sops updatekeys secrets.yaml` (needs the master key, so do it where that lives), push,
bump the submodule in cc-ci, `git -C /etc/cc-ci pull --recurse-submodules` on the host, then
replace `/secrets/host/sops-age-key.txt` with the host-derived identity
(`ssh-to-age -private-key -i /secrets/host/ssh_host_ed25519_key`), rebuild, and delete the master
key from the host.
### 4c. The orchestrator's workspace (as the `loops` user — it exists after the first rebuild, so
run §5 once first if this is a fresh host, then come back)
```bash
sudo -iu loops
git clone --recursive https://git.autonomic.zone/recipe-maintainers/cc-ci-orchestrator.git /srv/cc-ci-orch
sudo ln -sfn /srv/cc-ci-orch /srv/cc-ci # every script and unit says /srv/cc-ci
cd /srv/cc-ci-orch
git clone https://git.autonomic.zone/recipe-maintainers/cc-ci.git cc-ci # Builder clone
git clone https://git.autonomic.zone/recipe-maintainers/cc-ci.git cc-ci-adv # Adversary clone
mkdir -p .cc-ci-logs .sops
```
**`/secrets` is the authoritative location for every secret on this host.** Consumers either read
from it directly (where the nix config owns the path) or reach it by a symlink (where the software
fixes the path), so `find /secrets -type f` is the complete inventory — including the ssh host
keys. The directory is `0711` (traversable, not listable) with three subdirectories, each owned by
whoever must read it; the layout is declared in `nix/hosts/cc-ci/configuration.nix`:
| dir | mode | holds |
|---|---|---|
| `/secrets/files` | `loops:users 0700` | the agent's secrets: `.testenv`, opencode auth, its two ssh keys |
| `/secrets/host` | `root:root 0700` | host identity: the ssh **host** keys and the sops age identity |
| `/secrets/nginx` | `root:nginx 0750` | `oc-htpasswd` for the opencode UI (nginx must read it) |
**Only cc-ci's secrets go there** — nothing from other projects (no tailscale, lichen, tangled,
b1, borg…), and every private key is generated **on the host**, never copied from another machine.
`/secrets/README.txt` lists each file, its purpose, and the derived material that legitimately
lives elsewhere (`/run/secrets`, `/root/.docker/config.json`, the ACME cert) so a later sweep does
not "clean" it away.
> **The ed25519 host key is load-bearing beyond ssh.** Its age identity is a recipient of
> `cc-ci-secrets`, so regenerating it makes every cc-ci secret undecryptable. sshd is pointed at
> `/secrets/host/...` directly (not through the `/etc/ssh` symlinks) precisely so it can never
> write a fresh key through a dangling link. To move a host: copy the key, verify
> `ssh-to-age` yields the same identity, then activate.
| runtime path → `/secrets/files/…` | what | source |
|---|---|---|
| `/srv/cc-ci/.testenv` → `cc-ci.testenv` | `GITEA_PASSWORD` (autonomic-bot: PR/API calls), `DOCKERHUB_USERNAME/TOKEN` (harness image pulls). Nothing else: no tailscale key, no third-party model API keys (opencode's own auth is `opencode-auth.json`; add `TINFOIL_API_KEY` back only if `LOOP_MODEL` moves to a tinfoil model). | old host's copy minus the tailscale line; fresh: create each credential |
| `/srv/cc-ci/upgrader.env` (not a secret, lives in the checkout) | `LOOP_TIER`, `LOOP_MODEL`, `REPORT_MODEL`, `SUPERVISOR_MODEL` for the weekly run. This host is on the **OpenCode Go subscription** (`LOOP_TIER=go`, `opencode-go/…` models); the ZEN tier is pay-as-you-go credit and its key is not on this host | old host, or copy the example in `AGENTS.md` |
| `~loops/.ssh/cc-ci-local-ed25519` (+`.pub`) → same names | `ssh cc-ci` as root — to loopback on this host. **Generated on the host**, its pub in `nix/hosts/cc-ci/ssh-keys` | `ssh-keygen -t ed25519 -C cc-ci-loops-to-root@cc-ci` as loops |
| `~loops/.ssh/autonomic-bot-cc-ci-ed25519` (+`.pub`) → same names | pushes recipe branches / PRs as `autonomic-bot`; root's ssh config points at the same file to clone the private cc-ci-secrets submodule. **Generated on the host** and registered on the bot's Gitea account (`POST /api/v1/user/keys` with the bot password) | `ssh-keygen -t ed25519 -C autonomic-bot@cc-ci-host` as loops |
| `~loops/.local/share/opencode/auth.json` → `opencode-auth.json`; `~loops/.config/opencode/opencode.jsonc` (config, not secret — it must contain NO inline `apiKey`) | opencode provider auth + config. Exactly ONE provider, `opencode-go` — the orchestrator AND the weekly upgrader are opencode agents; there is no Claude on this host | old host; fresh: `opencode auth login` as loops |
| `/secrets/nginx/oc-htpasswd` (root:nginx 0640; the bcrypt line only — the plaintext stays with the operator, not on the host) | basic auth for the opencode UI (`https://oc.ci.commoninternet.net`, via traefik); **nginx refuses to start without it**, and its config check runs as the `nginx` user, so `root:nginx 0640` (the `nginx` group exists after the first rebuild — fix ownership then and `systemctl restart nginx`) | old host (`/secrets/files/oc-basic-auth.txt` has the plaintext), or a new `oc:<bcrypt>` line via `mkpasswd -m bcrypt` |
`~loops/.ssh/config` is written by the activation script on first rebuild (`Host cc-ci` →
`127.0.0.1`, `git.autonomic.zone`); it is not overwritten if present.
## 5. Build and activate
From the checkout with the §3 commit (root can build from the loops-owned checkout via sudo):
```bash
# as root, detached (the activation restarts sshd; a dropped session must not kill it).
# Three things the FIRST rebuild on a bare infect system needs, none of which the converged
# host needs afterwards: `git` on PATH (nix's flake fetcher shells out to it and the infect
# system has none — hence nix-shell), HOME=/root (so root's `git config --global
# safe.directory '*'` applies to the loops-owned checkout), and a login shell (`bash -l`, for
# NIX_SSL_CERT_FILE and friends from /etc/set-environment).
git config --global --add safe.directory '*'
systemd-run --unit=ccci-rebuild --collect -E HOME=/root -p WorkingDirectory=/srv/cc-ci-orch \
bash -lc 'nix-shell -p git --run "nixos-rebuild test --flake /srv/cc-ci-orch#cc-ci"'
journalctl -fu ccci-rebuild # ~10 min the first time (image pulls + two OCI image builds)
```
`test` first, always: it activates WITHOUT touching the bootloader, so if the activation breaks
networking or sshd a reboot from the Hetzner console lands on the last known-good generation.
(Earlier hosts were on the tailnet, and their rebuilds had to be detached because activation
restarted tailscale under the session; this one is plain public ssh, but detached is still the
safe habit.)
Later rebuilds are simply `sudo nixos-rebuild test|switch --flake .#cc-ci` from the checkout.
The first activation takes a while: it pulls the traefik/drone/keycloak images, builds the bridge
and dashboard OCI images with Nix, initialises the swarm and runs the serialized reconcile
oneshots (`swarm-init → deploy-proxy → deploy-drone → deploy-bridge → deploy-dashboard →
deploy-reports`, `deploy-backupbot`, `warm-keycloak`). Verify:
```bash
systemctl is-system-running # running — or list-units --failed and read journalctl -u <unit>
docker service ls # traefik app+socket-proxy, drone, bridge, dashboard, reports, backups: 1/1
systemctl status cc-ci-loops cc-ci-orchestrator opencode-web nginx acme-dns fail2ban
fail2ban-client status sshd; fail2ban-client status nginx-http-auth
systemctl list-timers 'cc-ci-*' nightly-sweep
sudo -iu loops tmux ls # cc-ci-orchestrator (+ loops sessions if a phase is active)
# the CI front doors, before DNS points here (expect 200 / 200 / 303 and ssl_verify=0 once
# /var/lib/acme is restored or a cert has been issued):
curl -s --resolve ci.commoninternet.net:443:127.0.0.1 -o /dev/null -w '%{http_code} %{ssl_verify_result}\n' https://ci.commoninternet.net/
curl -s --resolve report.ci.commoninternet.net:443:127.0.0.1 -o /dev/null -w '%{http_code}\n' https://report.ci.commoninternet.net/
curl -s --resolve drone.ci.commoninternet.net:443:127.0.0.1 -o /dev/null -w '%{http_code}\n' https://drone.ci.commoninternet.net/
dig +short @<ip> ns-acme.commoninternet.net # acme-dns answering on the public 53
```
The opencode UI: `curl -s --resolve oc.ci.commoninternet.net:443:<ip> -o /dev/null -w '%{http_code}' https://oc.ci.commoninternet.net/`
→ 401 without credentials, 200 with `-u oc:<password>`; `fail2ban-client status nginx-http-auth`
counts the failures (it reads nginx's journal — NixOS nginx logs to stderr, not to
/var/log/nginx/error.log).
When it is healthy: `sudo nixos-rebuild switch --flake .#cc-ci` (same config, now also the boot
default). **If you are migrating from another host, do §6 before letting it serve anything**: right
after the first activation scale the `!testme` bridge to 0 and mask the two orchestrator timers so
the new box does not process PR comments or start a second weekly run while the old host is live:
```bash
docker service scale ccci-bridge_app=0
systemctl mask --now cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer
```
## 6. Migrating: restore state from the previous host
Over ssh between the hosts (`ssh root@<old> 'tar -C / -cf - <paths>' | ssh root@<new> 'tar -C / -xpf - --numeric-owner'`, or rsync), with the matching service
stopped on the new host while its directory is copied:
| path | holds | notes |
|---|---|---|
| `/var/lib/cc-ci-reports` | the published weekly report pages (`report.ci…`) | |
| `/var/lib/cc-ci-runs` | per-run artifacts the dashboard shows | |
| `/var/lib/ci-warm` | warm-canonical state + alerts | recipe warm *volumes* are caches: not copied, rebuilt by the Sunday sweep / first use |
| `/var/lib/acme` | the Let's Encrypt cert + account **and `acme-dns-accounts.json`** — the account the permanent `_acme-challenge` CNAME points at | without it a fresh registration + a new CNAME at Gandi is needed (registration is disabled in `acme-dns.nix`) |
| `/var/lib/acme-dns` | the acme-dns zone DB | |
| `/var/lib/ci-certs` | the copy traefik is handed | then `systemctl restart cc-ci-acme-traefik-handoff` |
| `/root/.abra` | abra's per-app env files for the deployed stacks | |
| Drone data volume `/var/lib/docker/volumes/drone_ci_commoninternet_net_data` | Drone's DB: the Gitea OAuth grant, repo activation, build history | `docker service scale drone_ci_commoninternet_net_app=0` on the new host, copy, scale back to 1. Otherwise run `scripts/bootstrap-drone-oauth.sh` (cc-ci repo) with the bot password and re-activate repos |
| `/srv/cc-ci-orch/.cc-ci-logs`, `/srv/cc-ci-orch/cc-ci-plan/upstream/`, `REBOOTS.md`, `JOURNAL.md` | orchestrator history, the upgrader's per-recipe release-note registry | as loops; do the final sync after stopping the orchestrator on the old host |
## 7. Cutover and verification
1. **DNS** (operator, Gandi zone `commoninternet.net`): A records `ci`, `*.ci` and `ns-acme` →
the new IPv4. `acme NS ns-acme` and `_acme-challenge.ci CNAME <account>.acme…` stay as they
are. Wait for propagation (`dig +short ci.commoninternet.net`) — the records carry a 3 h TTL,
and resolvers that cached the old answer (the Hetzner ones in particular) keep serving it that
long. The new host must not list such a resolver: with a mixed set, every other lookup of its
own names went to the old server on 2026-09-07 (runner/bridge 404s). `networking.nix` drops
the Hetzner resolvers and `configuration.nix` pins the host's own names.
2. Check the new host answers on the new IP before DNS moves: `dig @<new-ip> ns-acme.commoninternet.net`
(acme-dns), `curl --resolve ci.commoninternet.net:443:<new-ip> https://ci.commoninternet.net/`
(dashboard, valid cert), same for `report.ci` and `drone.ci`.
3. Old host: `docker service scale ccci-bridge_app=0 drone_ci_commoninternet_net_app=0`;
`systemctl disable --now cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer` on the old
orchestrator. New host: `docker service scale ccci-bridge_app=1`;
`systemctl unmask cc-ci-upgrade-all.timer cc-ci-upgrade-supervisor.timer && systemctl start` both.
4. End to end: post `!testme` on an open recipe PR and watch it turn green on the new Drone;
open `https://ci.commoninternet.net` and `https://report.ci.commoninternet.net`.
5. The orchestrator: as loops on the new host `cd /srv/cc-ci-orch && python3 cc-ci-plan/agents.py up orchestrator`
(or just `systemctl restart cc-ci-orchestrator`), attach with `claude --resume` or from
claude.ai/code. Its startup routine (AGENTS.md) reports phase + reboot count.
6. Keep the old host as a cold standby for a week, then delete it (and its tailnet node — the
old servers were on the tailnet; the new one is not).
-42
View File
@@ -1,42 +0,0 @@
# cc-ci-plan
Self-contained handoff package for building the **cc-ci** Co-op Cloud recipe CI server with two
autonomous Claude loops (a Builder and an adversarial Reviewer) running over days.
## Start here
1. Read **`plan.md`** — the full plan and single source of truth (mission, Definition of Done,
architecture, milestones, the two-agent coordination protocol, loop discipline).
2. Read **`kickoff.md`** — how to launch and supervise the loops.
3. Run **`./launch.sh start`** to bring up both loops + the watchdog.
## Files
| File | Purpose |
|---|---|
| `plan.md` | The Phase-1 plan (build the CI server). Agents treat it as their single source of truth. |
| `plan-phase1c-full-reproducibility.md` | **Phase 1c** (runs first): make the VM fully reproducible from git (all secrets incl. the wildcard cert in sops, in a separate private `cc-ci-secrets` repo as a flake input; base stays well-parameterized) and do the **genuine throwaway-VM live rebuild** to close D8 honestly (the "infeasible by design" was overstated). |
| `plan-phase1b-review-lint.md` | **Phase 1b** (after 1c): deterministic linting/formatting in CI + a white-box review checklist (real tests, DRY harness, idempotent Nix, no footguns/secrets), ending in a full cold re-verification of all D1–D10 — now covering 1c's refactor. |
| `plan-phase1d-generic-test-suite.md` | **Phase 1d** (after 1b, before 2): a **generic install/upgrade/backup/restore** suite that runs on *any* recipe with zero config, with a recipe's own `test_<op>.py` **overriding or extending** the generic (Builder's call) and **reusing the generic's deployment — no redeploy**, plus optional custom install-steps; recipes needing special setup fail the generic form gracefully. The test-architecture foundation Phase 2 builds on. |
| `plan-phase1e-harness-corrections.md` | **Phase 1e** (after 1d, before 2): three operator-review corrections to the shared generic harness — (HC1) upgrade goes previous-release → **PR head** via `deploy --chaos`; (HC2) **repo-local PR code runs only for approved recipes** (default = cc-ci overlays + generic only); (HC3) the **generic runs by default** alongside an overlay, skipped only via explicit opt-out. |
| `plan-phase2-recipe-tests.md` | **Phase 2** (after Phase 1e): build on the corrected generic suite — author the recipe overlays (port recipe-maintainer tests as `test_*.py`) + define custom install steps where a recipe fails generically. |
| `plan-phase2b-test-performance.md` | **Phase 2b** (after Phase 2, before Phase 3): empirically measure where test time goes and reduce it (image cache, readiness tuning, dedup deploys, warm infra, concurrency) — no weakened tests. |
| `plan-phase3-results-ux.md` | **Phase 3** (after Phase 2b): beautiful YunoHost-style results — per-run **level**, image-forward PR comment (badge + summary card + app screenshot), polished dashboard. |
| `IDEAS.md` | Deferred/future ideas, parked out of current scope. |
| `brief.md` | The original one-page brief (context only; `plan.md` supersedes it). |
| `kickoff.md` | Launch & supervision guide. |
| `launch.sh` | Starts both loops + a watchdog; restarts dead loops; stops on `## DONE`. |
| `prompts/builder.md` | Builder loop prompt (fed to `claude` by the script). |
| `prompts/adversary.md` | Adversary loop prompt. |
## Before launching
- Set the org in `plan.md` (`git.autonomic.zone/recipe-maintainers/cc-ci`) and lock the six proof recipes (§8).
- Ensure the launching shell has: SSH+sudo to `cc-ci`, the Gitea token, `git.autonomic.zone` access.
- Preconfigure test-app DNS + TLS (plan §4.0): point a wildcard `*.ci.commoninternet.net` record at a gateway that TLS-passthroughs to cc-ci, and **pre-issue the wildcard cert** (`*.ci.commoninternet.net` + `ci.commoninternet.net`, via Gandi DNS-01) into `/var/lib/ci-certs/live/` on cc-ci. The agent handles everything else on cc-ci (Traefik file provider → that cert, swarm, routing) and does **no ACME**; renewal (~90 days) is an out-of-band operator task, so the DNS token never goes to the agent.
- `export CC_CI_REPO=https://git.autonomic.zone/recipe-maintainers/cc-ci.git` so the watchdog can detect `## DONE`.
## What "done" means
The loops stop only when all of `plan.md` §2 (D1–D10) hold **and** the Adversary has independently
re-verified each within 24h. The watchdog then tears the loops down automatically.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/README.md
-51
View File
@@ -1,51 +0,0 @@
# Adversary verification plan — cc-ci PR #6
**PR:** https://git.autonomic.zone/recipe-maintainers/cc-ci/pulls/6
**Branch:** `feat/expected-na-and-tiny-functional` (cc-ci repo)
**Stance:** disbelieve and verify. Try to make it fail. Default to REJECT unless every check below is
green with evidence. You did NOT author this code — verify it independently, cold.
## What the PR claims
1. A `custom-html-tiny` functional test (`tests/custom-html-tiny/functional/test_serves_content.py`):
exact-byte round-trip from the served `content` volume + a real 404.
2. `recipe_meta.EXPECTED_NA = {rung: reason}` lists rungs a recipe intentionally skips; any essential
rung skipped and NOT listed is *unintentional*. Skips still cap the level (never inflate).
3. The level ladder is the FOUR essential rungs only: `install · upgrade · backup_restore · functional`
(top = L4). `integration` and `recipe_local` are OPTIONAL — not rungs, never cap, not shown as skips.
**SSO must still be enforced for the run VERDICT** (the `sso_dep_unverified` / F2-11 path in
`run_recipe_ci.py` must be intact).
4. results.json carries `skips:{intentional:{rung:reason}, unintentional:[rung]}` + `level_cap_rung`;
the card shows INTENTIONAL/UNINTENTIONAL SKIP rows; the badge shows an `expected`/`gap?` 3rd segment.
## Verification steps (run on the cc-ci host; creds in `/srv/cc-ci/.testenv`)
0. Fresh independent checkout of the PR head (do NOT reuse my working dirs):
`git clone … cc-ci` → `git checkout feat/expected-na-and-tiny-functional`. Record the HEAD sha.
1. **Full unit suite cold** (not just the touched files): `cc-ci-run -m pytest tests/unit/ -q`.
ALL must pass. A single failure → REJECT. Capture the count + any failure.
2. **Diff regression review:** `git diff origin/main...HEAD`. Confirm: (a) `level.py` RUNGS is the 4
essential rungs; (b) `derive_rungs` no longer emits integration/recipe_local; (c) the SSO VERDICT
logic in `run_recipe_ci.py` (`sso_dep_unverified`, the F2-11 fail-the-run block) is UNCHANGED —
the PR must not have weakened SSO enforcement; (d) no test was weakened/skipped; (e) no secrets.
3. **Live end-to-end harness run, FULL stages** on the real CI server:
`RECIPE=custom-html-tiny STAGES=install,upgrade,backup,restore,custom cc-ci-run runner/run_recipe_ci.py`
(set `CCCI_RUNS_DIR` to a temp dir; source `.testenv`). Then read its `results.json` and assert:
- `install` PASS and `upgrade` PASS — the upgrade tier MUST actually run and pass (essential rung;
prove it's not silently skipped). The custom tier (functional serve test) PASS.
- `level == 2`, `level_cap_rung == "backup_restore"`, `level_cap_reason` mentions L3 backup/restore.
- `rungs` has exactly install/upgrade/backup_restore/functional — **no** integration/recipe_local.
- `skips.intentional == {"backup_restore": <reason>}`, `skips.unintentional == []`.
- `backup_restore` is N/A because there is no `backupbot.backup` label (a real intentional skip,
NOT a masked failure) — confirm by inspecting the recipe compose.
- `badge.svg` contains the muted `expected` third segment (not `gap?`).
- The summary card renders and shows a green `INTENTIONAL SKIP` row for backup/restore with the reason.
4. **Non-vacuity of the functional test:** confirm it asserts the *exact random bytes* round-trip and a
404 on a random path (so a 200-everything stub would fail it) — read the test; reason about whether
it could pass against a broken server. Bonus: confirm it writes via the volume mountpoint (the SWS
image is shell-less).
5. **Teardown + hygiene:** after the run, confirm the harness left NO orphan stack/volume/container for
custom-html-tiny (deploy-count == 1; clean teardown). Confirm no secret value appears in results.json.
## Verdict
Return a clear **PASS** or **REJECT** with the evidence for each numbered step (the HEAD sha, the unit
count, the key results.json fields, the upgrade-tier verdict, the teardown state). REJECT if ANYTHING is
unproven. Do not merge — the orchestrator merges on your PASS.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/adversary-verify-pr6.md
+5 -77
View File
@@ -60,29 +60,10 @@ resume = false # opencode backend has no --resume equivalent (fr
watch = "heal" # restart if dead / FATAL / backend-mismatch; never stall-reboot watch = "heal" # restart if dead / FATAL / backend-mismatch; never stall-reboot
wake = { interval = 3600, prompt_file = "ai-progress-monitor-prompt.txt" } wake = { interval = 3600, prompt_file = "ai-progress-monitor-prompt.txt" }
prompt = """ prompt = """
STARTUP (auto-launch): you are the cc-ci orchestrator, just (re)launched, likely after a reboot. \ STARTUP (auto-launch): you are the cc-ci operator steering agent. Read AGENTS.md
Do your AGENTS.md On-startup routine NOW: read cc-ci-plan/REBOOTS.md and run cc-ci-plan/launch.py \ and README.md, inspect the current host, weekly upgrade, report, and auto-update
status, then send a proactive PushNotification that you are online with the current phase and \ status using /cc-ci-status, then report any concrete issue. The original
reboot count, and confirm cc-ci-loops.service brought the loops + watchdog back (relaunch with \ Builder/Adversary build is complete; do not relaunch its loops."""
RESUME_PHASE=1 cc-ci-plan/launch.py start if not). Also read cc-ci-plan/JOURNAL.md for recent \
context before resuming supervision."""
[[agent]]
name = "builder" # tmux session: cc-ci-builder
enabled = false # operator 2026-07-10: do NOT auto-start on boot (only cc-ci-orchestrator does); start manually when running a build
kind = "loop"
role = "builder" # phase kickoff = phase preamble + prompts/builder.md
dir = "/srv/cc-ci/cc-ci"
watch = "heal+stall"
[[agent]]
name = "adversary"
enabled = false # operator 2026-07-10: do NOT auto-start on boot (only cc-ci-orchestrator does); start manually when running a build
session = "cc-ci-adv" # established convention is abbreviated (logs, remote-control)
kind = "loop"
role = "adversary"
dir = "/srv/cc-ci/cc-ci-adv"
watch = "heal+stall"
[[agent]] [[agent]]
name = "assistant" # tmux session: cc-ci-assistant name = "assistant" # tmux session: cc-ci-assistant
@@ -100,7 +81,7 @@ name = "upgrader" # tmux session: cc-ci-upgrader
kind = "task" # one-shot: run to completion, then idle kind = "task" # one-shot: run to completion, then idle
dir = "/srv/cc-ci" dir = "/srv/cc-ci"
watch = "none" watch = "none"
enabled = false # launched on demand or by [loop].on_complete enabled = false # launched by the weekly timer or on demand
prompt = """ prompt = """
You are the cc-ci weekly UPGRADER. Invoke the /upgrade-all skill in DEFAULT mode (read \ 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, \ /srv/cc-ci/.claude/skills/upgrade-all/SKILL.md for the full procedure), run it to completion, \
@@ -122,56 +103,3 @@ You generate the public weekly "Recipe Report". Run the /recipe-report skill now
name = "cleanlogs" # tmux session: cc-ci-cleanlogs name = "cleanlogs" # tmux session: cc-ci-cleanlogs
command = "python3 cc-ci-plan/agent-log.py follow-all" command = "python3 cc-ci-plan/agent-log.py follow-all"
dir = "/srv/cc-ci-orch" dir = "/srv/cc-ci-orch"
# ─────────────────────────── the phase machine (kind="loop" agents) ───────────────────────────
[loop]
state_file = "phase-idx" # under <log_dir>/state/
resume_phase = true # keep current index across restarts (don't reset to 0)
auto_advance = true
done_marker = "## DONE"
handoff = { repo = "/srv/cc-ci/cc-ci", claim_pings = "adversary", review_pings = "builder", inboxes = ["ADVERSARY-INBOX.md", "BUILDER-INBOX.md"] }
on_complete = { trigger_file = ".run-upgrade-on-complete", run = "upgrader" }
# Transcribed verbatim from the live .phases-spec, with the duplicate `mailu` (old idx 7)
# REMOVED. Per-phase model overrides (were .loop-model[-adv]-<id> files) are inline.
# Current phase after de-dupe: cf55 (index 9) — see state/phase-idx.
phases = [
{ id = "rcust", plan = "recipe-custom-restructure-full-plan.md", status = "STATUS-rcust.md" },
{ id = "shot", plan = "plan-phase-shot-screenshots.md", status = "STATUS-shot.md" },
{ id = "lvl5", plan = "plan-phase-lvl5-lint-rung.md", status = "STATUS-lvl5.md" },
{ id = "bsky", plan = "plan-phase-bsky-fix.md", status = "STATUS-bsky.md" },
{ id = "dstamp", plan = "plan-phase-dstamp-discourse-drift.md", status = "STATUS-dstamp.md", models = { builder = "opus" } },
{ id = "mailu", plan = "plan-phase-mailu-backup.md", status = "STATUS-mailu.md" },
{ id = "kuma", plan = "plan-phase-kuma-monitor.md", status = "STATUS-kuma.md" },
{ id = "drone", plan = "plan-phase-drone-enroll.md", status = "STATUS-drone.md" },
{ id = "cfold", plan = "plan-phase-cfold-custom-folder.md", status = "STATUS-cfold.md" },
{ id = "cf55", plan = "plan-phase-cf55-gpt55-cfold-review.md", status = "STATUS-cf55.md", models = { builder = "claude-sonnet-4-6", adversary = "claude-sonnet-4-6" } },
{ id = "pvfix", plan = "plan-phase-pvfix-swarm-proxy.md", status = "STATUS-pvfix.md" },
{ id = "pvcheck", plan = "plan-phase-pvcheck-post-proxy-verification.md", status = "STATUS-pvcheck.md" },
{ id = "ghost", plan = "plan-phase-ghost-reeval.md", status = "STATUS-ghost.md" },
{ id = "cf48", plan = "plan-phase-cf48-opus-cfold-review.md", status = "STATUS-cf48.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
{ id = "pxgate", plan = "plan-phase-pxgate-proxy-healthgate.md", status = "STATUS-pxgate.md" },
# agent-orchestrator build (builder=opus, adversary=sonnet) — see plan-agent-orchestrator.md
{ id = "aoeng", plan = "plan-phase-aoeng-engine.md", status = "STATUS-aoeng.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
{ id = "aotest", plan = "plan-phase-aotest-verify.md", status = "STATUS-aotest.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
{ id = "porepo", plan = "plan-phase-porepo-project-orchestrator.md", status = "STATUS-porepo.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
{ id = "poe2e", plan = "plan-phase-poe2e-end-to-end.md", status = "STATUS-poe2e.md", models = { builder = "claude-opus-4-8", adversary = "claude-sonnet-4-6" } },
# gitea full-test enrollment + LFS PR #1 verification — see plan-phase-gtea-gitea-fulltests.md (operator 2026-06-15)
{ id = "gtea", plan = "plan-phase-gtea-gitea-fulltests.md", status = "STATUS-gtea.md", models = { builder = "claude-sonnet-4-6", adversary = "claude-sonnet-4-6" } },
# dynamic upgrade base + per-recipe previous/ config (opus); validated on discourse PR #4 — see plan-phase-prevb-*.md (operator 2026-06-16)
{ id = "prevb", plan = "plan-phase-prevb-previous-dynamic-base.md", status = "STATUS-prevb.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# full all-recipe regression after prevb (sonnet) — see plan-phase-regall-*.md (operator 2026-06-16)
{ id = "regall", plan = "plan-phase-regall-recipe-regression.md", status = "STATUS-regall.md", models = { builder = "claude-sonnet-4-6", adversary = "claude-sonnet-4-6" } },
# same-version upgrade-base gap: step back to newest-older-published when last-green==head (opus, design A; B in IDEAS) — see plan-phase-samever-*.md (operator 2026-06-17)
{ id = "samever", plan = "plan-phase-samever-older-base-fallback.md", status = "STATUS-samever.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# make the canonical sweep ACTUALLY work (substitute for the hollow nightly sweep) + upstream-sync + skip-unchanged; verify end-to-end (opus) — see plan-phase-canon-*.md (operator 2026-06-17)
{ id = "canon", plan = "plan-phase-canon-canonical-sweep.md", status = "STATUS-canon.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# fix incomplete per-recipe run history on the CI dashboard (capped at latest 100 Drone builds; 362 runs exist) — source from local /var/lib/cc-ci-runs (opus) — see plan-phase-dash-*.md (operator 2026-06-17)
{ id = "dash", plan = "plan-phase-dash-recipe-history.md", status = "STATUS-dash.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# CI-server settings.toml + SKIP_CANONICALS_FOR_UPGRADE + release-tag-first no-canonical fallback (opus) — see plan-phase-settings-*.md (operator 2026-06-17)
{ id = "settings", plan = "plan-phase-settings-ci-server-config.md", status = "STATUS-settings.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# single-source the harness runtime env so the sweep timer + Drone runner SHARE deps (no duplication) — root-cause fix for DEFECT-3 drift (opus) — see plan-phase-nixenv-*.md (operator 2026-06-17)
{ id = "nixenv", plan = "plan-phase-nixenv-shared-runtime-env.md", status = "STATUS-nixenv.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
# investigate ALL canon-sweep failures (discourse/mattermost-lts/mumble/bluesky/gitea/keycloak) + FIX each via recipe PR or harness improvement (opus) — see plan-phase-redfix-*.md (operator 2026-06-17)
{ id = "redfix", plan = "plan-phase-redfix-canon-sweep-failures.md", status = "STATUS-redfix.md", models = { builder = "claude-opus-4-8", adversary = "claude-opus-4-8" } },
]
+5 -1
View File
@@ -1 +1,5 @@
You are the cc-ci orchestrator, woken for your scheduled supervision pass. Read /srv/cc-ci/cc-ci-plan/orchestration.md (the agent map) and do your job per its "The orchestrator's job — keep everyone on track" section — it tells you how to find the CURRENT phase (`python3 cc-ci-plan/launch.py status`) and what to check, nudge, and do. Be decisive but minimal; if everything is healthy and active, just note the state. 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.
-35
View File
@@ -1,35 +0,0 @@
we are working on making a CI server
I want you to work in an autonomous loop over the next few days until the CI server is fully functional, polished and documented
on any PR on git.autonomic.zone it should be invokable by writing !testme as a comment
this should invoke the set of CI tests to be run for the recipe code at that PR
the CI tests should be run via drone
the tests run for a recipe should be written in python. e2e testing via playwright should be used whe necessary to confirm functionality
there should be tests which test
- new install
- upgrade
- backups (including restore)
all the tests should be fully e2e, with a real deployed recipe
the CI runner should be deployed on a server called cc-ci which is running nixos
cc-ci git repo should also live on git.autonomic.zone which contains all the nix configuration for the server, as well as the code for the CI test runner
the CI test runner should have its own folder of tests, with one folder for each recipe, with each of those folders containg a set of tests as python files which get invoked for that recipe
secrets should also be handled in a reasonable and repeatable way
additionally, if a recipe repo itself contains a tests folder in the recipe, the CI runner should also invoke those tests as part of the CI run for those tests
the results of the test run should be easily viewable, with trackable logs, and a final result, very similar in style to the way the yunohost CI runner looks and feels
you will have ssh access to cc-ci server, as well as sudo access there
you will also have access to create and modify repos on git.autonomic.zone
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/brief.md
@@ -1,202 +0,0 @@
# Concurrency restructure — full implementation plan
Expands `concurrency-restructure-plan.md` (operator-approved 2026-06-10).
Reference spec of current system: cc-ci `docs/concurrency.md`.
## Decisions locked (operator + orchestrator)
| Question | Decision |
|---|---|
| Hard deadline | **60 min** (`signal.alarm(60*60)`); recipes keep their own smaller per-tier deadlines |
| `servers/` in per-run ABRA_DIR | **symlink** to `/root/.abra/servers` — app `.env` files land in the shared canonical path, so the janitor's `abra app ls` discovery and env-based teardown work unchanged (kills the P3 orphan-env risk). Per-domain filenames + app-domain lock prevent write conflicts. `catalogue/` also symlinked (read-mostly). `recipes/` is fresh per-run — that's the isolation that matters. |
| Landing | one branch `restructure/concurrency`, one commit per phase (P1..P5 + tests), merged to main only after adversary pass + lint green; live verification on main afterwards |
| Concurrency test suite | `tests/concurrency/` — NOT in the default `pytest tests/unit` run; invoked explicitly (`pytest tests/concurrency -q`); documented in docs/concurrency.md |
## Target invariant chain
```
lock lifetime ⊆ harness process lifetime ⊆ drone step lifetime ⊆ 60-min deadline
```
Never steal a held lock; manage the holder's lifetime. Held lock = live owner (kernel-guaranteed).
---
## P1 — Lock-lifetime hardening
`runner/run_recipe_ci.py` (startup, before any abra call):
1. `PR_SET_PDEATHSIG(SIGTERM)` via `ctypes.CDLL("libc.so.6", use_errno=True).prctl(1, signal.SIGTERM)`;
check return code; then `if os.getppid() == 1: sys.exit("parent died before prctl — refusing to run orphaned")`.
2. SIGTERM handler: run teardown (reuse the existing finally/teardown funnel — raise SystemExit
from the handler so `finally:` blocks run), exit non-zero.
3. Self-deadline: `signal.alarm(60*60)` + SIGALRM handler → same teardown funnel, distinct log line
(`== run exceeded 60-minute hard deadline — tearing down ==`), exit non-zero.
`.drone.yml` recipe-ci step: wrap the harness invocation:
```sh
setsid python3 runner/run_recipe_ci.py ... &
PID=$!; trap 'kill -TERM -- -$PID 2>/dev/null' TERM EXIT; wait $PID
```
(builder: verify drone exec runner signal delivery semantics; the trap must fire on drone cancel.)
Also: one-line comment on the lock `open()` noting PEP 446 makes the fd non-inheritable
(subprocess children never carry the lock).
## P2 — Flock-probe janitor (replaces the pidfile registry)
`runner/harness/lifecycle.py`:
1. New: `acquire_app_lock(domain)` — `/run/lock/cc-ci-app-<domain>.lock`, exclusive flock,
non-blocking try first → on `BlockingIOError` log
`== app lock: another run of <domain> is in flight — waiting ==` and block. Returns the kept-alive
file object. Touch mtime at acquisition (mtime = lock age for the long-held flag).
2. Call site: in `deploy_app()` exactly where `register_run_app()` is today (BEFORE app creation);
the file object must be stored on a module-level/owner object so it lives for the process lifetime.
3. Janitor rewrite (`janitor()`): for each candidate domain (discovery unchanged: `abra app ls`
matched against `RUN_APP_RE` + docker-service sweep):
- open/create its lockfile, try `LOCK_EX|LOCK_NB`:
- **acquired** → orphan → `teardown_app(domain, verify=False)` WHILE HOLDING the probe lock
(closes janitor-vs-new-run race: a new run of that domain blocks on the lock until the reap
finishes), then release + unlink lockfile.
- **held** → live run → leave it; if lockfile mtime older than 2× deadline (120 min), log:
`!! lock for <domain> held >120min — possible leaked run; inspect with lslocks` (flag, never steal).
4. Delete: `register_run_app`, `unregister_run_app`, `_run_owner_state`, `ACTIVE_RUN_DIR`,
`CCCI_JANITOR_MAX_AGE` handling + age fallback, pid-reuse guard, and their call sites
(`deploy_app`, `teardown_app`, both janitor call sites keep working — only internals change).
5. `teardown_app()` no longer unregisters; normal-exit lock release stays implicit (process exit).
Janitor unlinks lockfiles only for reaped orphans; a clean run's stale lockfile (0 bytes, unlocked)
is harmless and reaped-on-sight by the next janitor probe (unlink after acquiring probe lock,
even when no app exists for it — keep /run/lock tidy).
Edge semantics to preserve/verify:
- Two janitors racing: both probe; one wins the flock and reaps; the loser sees "held" and leaves.
Reap must be idempotent (`teardown_app(verify=False)` already tolerates half-gone stacks).
- Post-reboot: lockfiles gone (tmpfs) → probe trivially acquires → immediate reap. (Improvement
over the 2h age fallback — note in spec.)
- Warm/canonical apps never match `RUN_APP_RE` → never probed. Unchanged. DO NOT touch.
## P3 — Per-run ABRA_DIR (deletes the per-recipe flock)
`runner/run_recipe_ci.py` / `runner/harness/`:
1. Early in main(): build `run_abra_dir = /var/lib/cc-ci-runs/<build>/abra`; create it;
symlink `servers` → `/root/.abra/servers`, `catalogue` → `/root/.abra/catalogue` (builder:
verify the minimal set abra needs — probe showed it fails only on missing `servers/`);
fresh empty `recipes/`. Set `os.environ["ABRA_DIR"] = run_abra_dir` before ANY abra/harness call.
2. `fetch_recipe()` becomes a plain clone into `$ABRA_DIR/recipes/<recipe>` (no rm-rf of a shared
tree; keep the checkout-of-ref logic).
3. Delete: `acquire_recipe_lock`, `RECIPE_LOCK_DIR` recipe-lock usage, its call site in main(),
and the "must be taken before fetch_recipe" ordering rule.
4. `.drone.yml`: HOME=/root comment updated — abra config still found via symlinked servers;
recipe trees now per-run.
5. Janitor / warm-app / canonical flows that read `/root/.abra/recipes/...` (if any — builder:
grep) must be checked; they run outside a per-run ABRA_DIR and keep using the default.
6. Run-dir cleanup: `/var/lib/cc-ci-runs/<n>/` retention already exists — abra dir rides along.
## P4 — Config cleanup
- Remove `concurrency.limit` from `.drone.yml` recipe-ci pipeline; `DRONE_RUNNER_CAPACITY`
(nix/modules/drone-runner.nix `maxTests`) is the single knob. Update its comment.
## P5 — Spec rewrite
- Rewrite `docs/concurrency.md` to the new model: one mechanism (per-app-domain flock), the
invariant chain (§ lock-lifetime management), flock-probe janitor decision table, per-run
ABRA_DIR isolation, updated failure-mode table (cancel now kills harness; reboot reaps
immediately; deadline bounds everything), updated file/symbol index, and how to run
`tests/concurrency`.
---
## Test suite: `tests/concurrency/`
Real-kernel tests (no mocking of flock itself — spawn helper subprocesses that hold locks; use
tmp dirs for lock/run dirs via env/monkeypatch). NOT part of `pytest tests/unit`. Run with
`pytest tests/concurrency -q` (document in docs; CI does not run it on every build — optional
manual/nightly invocation).
Lock fundamentals:
1. acquire → child process SIGKILL'd → lock immediately acquirable (kernel auto-release).
2. probe (`LOCK_NB`) against a held lock raises `BlockingIOError`; against unheld succeeds.
3. lock fd NOT inherited: holder spawns a `subprocess` child, holder dies, child still alive →
lock acquirable (PEP 446).
4. second same-domain acquire blocks until first holder exits (double-!testme serialisation).
Janitor / probe semantics:
5. orphan (no holder) → reaped, lockfile unlinked; teardown invoked exactly once (stub teardown).
6. live (held by helper process) → never reaped, logged as live.
7. reap-under-probe-lock race: janitor holds probe lock mid-reap → a new run's acquire of the
same domain blocks until reap completes (no window where new app coexists with half-reaped one).
8. two concurrent janitors → exactly one reaps (flock arbitration), reap idempotent.
9. reboot simulation: app exists, lockfile absent → treated as orphan immediately (no age wait).
10. long-held flag: held lock with mtime backdated >120min → warning logged, NOT reaped.
11. `RUN_APP_RE` allowlist: warm/canonical-shaped names never become candidates.
12. garbled/unwritable lockfile, missing lock dir → janitor degrades safely (skip + log, never crash).
Lifetime hardening:
13. PDEATHSIG: spawn wrapper-parent + harness-child (helper script calling the real prctl setup);
kill parent → child receives SIGTERM and exits, lock released.
14. ppid race: helper started with already-dead parent (ppid 1) exits immediately.
15. deadline: helper with `alarm(2)` → teardown hook fires, exit non-zero, lock released.
16. SIGTERM → teardown funnel runs (`finally:` executed), lock released, non-zero exit.
ABRA_DIR isolation:
17. per-run dir built correctly: `servers`/`catalogue` symlinks resolve, `recipes/` empty + writable,
`ABRA_DIR` exported before first abra call (assert via stub abra recording its env).
18. two concurrent fetch_recipe of the SAME recipe into different ABRA_DIRs → both trees correct,
no cross-talk (the old corruption scenario, now safe without a lock).
19. app `.env` written through the servers symlink lands in the canonical shared path (janitor
discovery keeps working).
Each test must clean up helper processes in `finally`/fixtures (no leaked children in the test VM).
## Roles, gates & Definition of Done (loop protocol — plan.md §6.1 applies)
This phase runs as Builder/Adversary loops with phase-namespaced state files
(STATUS-conc.md, REVIEW-conc.md, BACKLOG-conc.md, JOURNAL-conc.md).
**Builder**: implements P1→P5 + the tests/concurrency suite on branch `restructure/concurrency`
in YOUR clone; one commit per phase; before each commit ALL of:
`pytest tests/unit -q`, `pytest tests/concurrency -q` (once it exists), `scripts/lint.sh` —
green. Push the branch (NOT main — main merge is gated below). Claim gates via `claim(conc): ...`
commits + STATUS-conc.md per protocol.
**Adversary**: cold-verify from your own clone. For M1: check out the branch, run both suites +
lint yourself, then adversarially review the full diff — hunt races (probe vs acquire ordering,
signal-handler reentrancy, teardown-during-teardown), deleted-code fallout (grep for dangling
references to registry symbols: register_run_app, unregister_run_app, _run_owner_state,
ACTIVE_RUN_DIR, CCCI_JANITOR_MAX_AGE, acquire_recipe_lock), gate integrity (recipe tests /
RUN_APP_RE / warm apps untouched), and test-suite blind spots vs the 19 cases above.
Default-skeptical; findings to REVIEW-conc.md.
**Gates:**
- **M1 — implementation verified.** Branch complete (P1–P5 + tests), both suites + lint green
on the Adversary's cold clone, adversarial diff review PASS in REVIEW-conc.md.
- **M2 — merged + live-verified.** After M1 PASS only, Builder merges the branch to main
(merge commit, never force) and confirms the push build green. Then live verification on the
real CI host (evidence in STATUS-conc.md, Adversary re-checks):
a. trigger an immich !testme, cancel mid-run via drone API → harness pid dies (no leaked
python), lock released, next janitor reaps the app — zero leakage;
b. two parallel !testme runs (immich PR#2 + plausible PR#3) → both green, zero leakage;
c. double-!testme same PR → second blocks on the app lock (visible in its drone log), then runs;
d. one full green run end-to-end.
**## DONE in STATUS-conc.md** only when M1 and M2 both show a fresh Adversary PASS in
REVIEW-conc.md. NOTE for both loops: recipe-mirror PRs (immich#2, plausible#3) are used as
!testme targets only — NEVER merge or push to recipe mirror repos.
## Guardrails (builder + adversary MUST honor)
- NEVER weaken recipe-test gates or touch `tests/<recipe>/` content.
- cc-ci main is touched ONLY by the M2 merge after M1 PASS; all other work stays on the branch.
Never force-push. NEVER merge/push recipe mirror repos.
- No secrets in commits; reference `.testenv` / `/run/secrets` locations only.
- Don't touch `services_converged()` / paused-is-settled logic except where the plan says.
- Match repo commit style (`feat(...)`/`fix(harness)`/`test(...)`/`docs:`).
## Rollback
Single revert of the merge commit restores the registry+recipe-flock world; no data migration
(lock/registry state is tmpfs-ephemeral, old and new harness can't run simultaneously anyway —
deploys land from main atomically per build).
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/concurrency-restructure-full-plan.md
@@ -1,60 +0,0 @@
# Concurrency restructure — concise plan (for review)
Goal: collapse the two concurrency mechanisms (per-recipe flock + pidfile registry/janitor)
into **one primitive** — a per-app-domain kernel flock — and make lock lifetime bounded by
construction. Reference: cc-ci `docs/concurrency.md` §8.
## Target invariant chain
```
lock lifetime ⊆ harness process lifetime ⊆ drone step lifetime ⊆ hard deadline
```
Never steal a held lock; manage the holder's lifetime. A held lock = live owner (kernel-guaranteed).
## Phases (each independently landable, in order)
### P1 — Lock-lifetime hardening (no behavior change to locking model)
- Harness startup: `PR_SET_PDEATHSIG(SIGTERM)` + post-prctl `getppid()==1` race check
→ drone cancel now kills the harness, fixing the leaked-python gap.
- `.drone.yml` step wrapper: `setsid` + trap killing the process group on TERM/EXIT.
- Self-deadline: `signal.alarm(90*60)` → teardown + exit. Hard upper bound on any run.
- Verify: trigger a build, cancel via API, assert harness pid gone + app torn down by next janitor.
### P2 — Flock-probe janitor (replace the pidfile registry)
- Run start: exclusive flock on `/run/lock/cc-ci-app-<domain>.lock` **before app creation**,
held for process lifetime (also serialises double-`!testme` of the same PR/ref).
- Janitor: probe each candidate's lockfile with `LOCK_EX|LOCK_NB`.
Acquirable → orphan → reap **while holding the probe lock** (closes janitor-vs-new-run race).
Held → live run → leave; if lockfile mtime > 2× max run time, log loudly (`lslocks` hint) — flag, never steal.
- Delete: `register_run_app`, `unregister_run_app`, `_run_owner_state`, `ACTIVE_RUN_DIR`,
`CCCI_JANITOR_MAX_AGE` + age fallback, pid-reuse guard.
- Bonus: post-reboot orphans reaped immediately (locks gone = acquirable) instead of after 2h.
- Keep: `RUN_APP_RE` allowlist, candidate discovery (abra ls + docker-service sweep).
### P3 — Per-run ABRA_DIR (delete the per-recipe flock)
- Each build: `ABRA_DIR=/var/lib/cc-ci-runs/<n>/abra`, seeded with the server config
(verified: abra honors `ABRA_DIR`; fails only on missing `servers/`).
- `fetch_recipe` becomes a plain clone into a fresh dir (no rm-rf of a shared tree).
- Delete: `acquire_recipe_lock` + `/run/lock/cc-ci-recipe-*` + the "before fetch_recipe" ordering rule.
- Wins: same-recipe PRs truly parallel (kills head-of-line blocking §8.2); manual operator
activity on `/root/.abra` can no longer corrupt CI runs (§8.3/§8.4 moot).
- Risk to resolve: orphaned app's `.env` lives in the dead run's tree — janitor must rely on the
existing env-less teardown path (docker-service sweep). Confirm `teardown_app(verify=False)`
fully works without the `.env`.
### P4 — Config cleanup
- Drop `concurrency.limit` from `.drone.yml`; `DRONE_RUNNER_CAPACITY` (drone-runner.nix)
becomes the single knob (§8.6).
### P5 — Spec rewrite
- Rewrite `docs/concurrency.md` to the new model (one mechanism, one table) + §10 lock-lifetime chain.
## Out of scope (do not touch)
- `services_converged()` / paused-is-settled logic; `RUN_APP_RE`; recipe-test gates; warm/canonical apps.
## Open questions for review
1. P3 server-config seeding: copy vs symlink of `$ABRA_DIR/servers/<server>`? (symlink simpler;
copy isolates harder — does abra write into `servers/` during a run? e.g. app `.env` lives there → copy needed, per-run env file then dies with the run dir, see P3 risk.)
2. Self-deadline value: 90 min ok? (longest observed green run ~35 min incl. flock wait.)
3. Land P1+P2 together or separately? (P2 testable solo; P1 is pure hardening — could merge.)
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/concurrency-restructure-plan.md
-145
View File
@@ -1,145 +0,0 @@
# cc-ci — Kickoff & Launch
Everything needed to start the autonomous cc-ci build loop. The substance lives in `plan.md`;
this file explains how to launch and supervise the two agents.
## Folder contents
```
cc-ci-plan/
├── plan.md # THE plan — single source of truth (read this in full)
├── brief.md # original one-page brief (context only; superseded by plan.md)
├── kickoff.md # this file — how to launch & supervise
├── launch.sh # starts both loops + watchdog, stops on ## DONE
└── prompts/
├── builder.md # Builder loop prompt (fed to claude by launch.sh)
└── adversary.md # Adversary loop prompt
```
> Note: `/srv/cc-ci/cc-ci-plan/` (this folder) is the **planning + launch material**. The actual
> CI project — NixOS config, runner, tests — lives in a **separate git repo** the Builder creates
> at `git.autonomic.zone/recipe-maintainers/cc-ci`, cloned to `/srv/cc-ci/cc-ci` (Builder) and
> `/srv/cc-ci/cc-ci-adv` (Adversary). Don't confuse the two.
## Model: two independent loops (plan §6 / §6.1)
- **Builder** — builds the CI server; owns code + `STATUS.md`/`JOURNAL.md`/`DECISIONS.md` + the
`## Build backlog` section of `BACKLOG.md`.
- **Adversary** — independently disbelieves and re-verifies; owns `REVIEW.md` + `## Adversary
findings`. Holds veto over `## DONE`.
They run as two separate processes and coordinate **only** through the git repo. Single-writer file
ownership keeps concurrent pushes merge-clean.
## Two layers of "looping" — and why you want both
| Concern | Mechanism | Who provides it |
|---|---|---|
| **Iteration** — keep doing one unit of work, then wake again | `/loop` self-paced (ScheduleWakeup), per plan §7 pacing | each agent, in-session |
| **Resilience** — restart a loop whose process/sandbox died; stop all on `## DONE` | `launch.sh` watchdog (tmux + git poll) | this script |
| **Handoff signalling** — wake the *waiting* loop the moment its counterpart hands off | watchdog `handoff_check` (~30 s): Builder writes a `CLAIMED` gate → ping Adversary to verify; Adversary updates `REVIEW.md` → ping Builder to proceed | this script |
`/loop` alone is bound to its process: if the sandbox restarts, that loop is gone until something
relaunches it. The watchdog is that something. It also closes the **double-idle gap**: instead of a
pending gate/verdict sitting until the other loop's next scheduled wake, the watchdog pings the
waiting loop within ~30 s — so the Adversary can idle freely when nothing's pending (no busy-polling
or pointless re-verifying) yet still start verifying right after the Builder parks at a gate. Use all three.
## Launch
```bash
cd /srv/cc-ci/cc-ci-plan
# Optional but recommended once the repo exists, so the watchdog can detect ## DONE:
export CC_CI_REPO=https://git.autonomic.zone/recipe-maintainers/cc-ci.git
./launch.sh start # starts cc-ci-builder + cc-ci-adv + cc-ci-watchdog (tmux sessions)
./launch.sh status # session + DONE state
./launch.sh logs builder # tail a loop; also: logs adversary | logs watchdog
tmux attach -t cc-ci-builder # watch a loop live locally (detach: Ctrl-b d)
./launch.sh stop # stop everything
```
`launch.sh` is idempotent — re-running `start` won't duplicate a live session. Each agent runs as an
**interactive** `claude` in tmux (kickoff prompt passed as a positional arg, *not* piped — piping
forces print mode and breaks `/loop`). With `REMOTE_CONTROL=1` (default) each agent is launched with
`--remote-control`, so you can **watch and steer both loops from [claude.ai/code](https://claude.ai/code)**
(or the Claude mobile app) — not just via `tmux attach`. The box must be logged into the claude.ai
account (`claude auth status`); set `REMOTE_CONTROL=0` to skip the remote surface. The watchdog
(default every 300s) restarts any dead session — note a >~10-min network outage will exit the
`claude` process, after which the watchdog brings it back (a fresh remote-control session) — and
when `STATUS.md` shows `## DONE`, it kills the loops and exits.
Prerequisites the sessions inherit from your shell: SSH (root) to `cc-ci` directly (the orchestrator
VM is a direct tailnet peer — no proxy; §1.5), Gitea bot creds, and `git.autonomic.zone` access. Plus **preconfigured** operator inputs the
loop depends on (plan §4.0/§4.4): the wildcard `*.ci.commoninternet.net` DNS record pointing at a
gateway that TLS-passthroughs to cc-ci, and the **pre-issued wildcard cert** at
`/var/lib/ci-certs/live/` on cc-ci. The operator owns the DNS record + gateway + cert
issuance/renewal; the agent builds Traefik (file provider → that cert) + routing on cc-ci and does
**no ACME**. If any prerequisite is absent, the Builder parks at `STATUS.md ## Blocked` (plan §1/§9)
rather than improvise.
> Host deps: `launch.sh` needs **tmux** (and `claude`) — both are installed on the VM (NixOS). The script's `*_DIR`
> defaults now point at `/srv/cc-ci/...` (Builder clone `/srv/cc-ci/cc-ci`, Adversary
> `/srv/cc-ci/cc-ci-adv`); override the `*_DIR` env vars only if your layout differs.
## Optional: a cloud-side `/schedule` watchdog
`launch.sh`'s watchdog is itself a local process — if the *whole host* goes down it stops too. For
belt-and-suspenders durability, also create a `/schedule` routine (a remote agent that fires on a
cron and re-orients from the repo). From inside a Claude session:
```
/schedule every 2 hours: read /srv/cc-ci/cc-ci-plan/plan.md §7 and the cc-ci repo STATUS.md; if the
Builder/Adversary loops are not making progress (or launch.sh is not running), restart them via
/srv/cc-ci/cc-ci-plan/launch.sh start; stop when STATUS.md says ## DONE.
```
This complements the local watchdog: scheduled runs are fresh, independent agents, so they survive
process/context death that would take the in-session `/loop` and the local watchdog with it.
## Fallback: restart/recreate the cc-ci VM (orchestrator only)
**This is primarily an escape hatch for *you*, the supervising orchestrator.** The loops normally
reconfigure cc-ci only from inside (via Nix); power-cycling or recreating the VM shouldn't be their
default move — but it's not forbidden if one gets genuinely stuck. Reach for this when cc-ci itself
is wedged at a level that can't be fixed from inside (won't boot, disk full, swarm/Docker corrupted,
unreachable even after a proxy restart): use the Incus skill to power-cycle or rebuild the VM, then
re-bootstrap.
`cc-nix-test` (the cc-ci server, tailnet `100.90.116.4`) is a **NixOS Incus VM** on host **b1**
(`100.117.251.31:8443`, Incus project `terraform-ci`). Skill + Terraform live at
`/srv/incus-terraform-nix-vm-creator/` (`skills/incus-terraform/SKILL.md`); read that for full usage.
- **Access:** b1 (`100.117.251.31`) is reachable directly from the orchestrator VM (same tailnet).
Use the mTLS certs at `terraform-secrets/` — no proxy. Quick check:
```bash
CRT=/srv/incus-terraform-nix-vm-creator/terraform-secrets/terraform.crt
KEY=/srv/incus-terraform-nix-vm-creator/terraform-secrets/terraform.key
curl --cert "$CRT" --key "$KEY" -k -s \
https://100.117.251.31:8443/1.0/instances/cc-nix-test/state?project=terraform-ci
```
- **Soft restart (keeps the disk — preferred):** `POST .../1.0/instances/cc-nix-test/state?project=terraform-ci`
with `{"action":"restart"}` (or `"stop"` / `"start"`).
- **Full recreate (last resort):** the Terraform module in `/srv/incus-terraform-nix-vm-creator/projects/`
(`terraform apply` with `-var incus_remote_address=100.117.251.31 -var incus_project=terraform-ci
-var ts_auth_key=$TSKEY`). ⚠ **Recreating wipes the VM disk** — you must then re-apply the cc-ci
preconditions: the pre-issued TLS cert into `/var/lib/ci-certs/live/` and the
`cc-ci-root-ed25519` pubkey into root's `authorized_keys` (see the access notes), and the loops
re-run §1 Bootstrap. Prefer a soft restart; only recreate if the VM is truly unrecoverable.
(Project cap: keep total RAM across `terraform-ci` instances under 10 GB — check before recreating.)
## Manual launch (no script)
If you'd rather not use `launch.sh`, start each agent interactively yourself (same result, no
supervision/restart), passing the prompt as a positional argument so the session stays interactive
and remote-controllable:
```bash
claude --remote-control 'cc-ci-builder' --dangerously-skip-permissions "$(cat prompts/builder.md)"
claude --remote-control 'cc-ci-adv' --dangerously-skip-permissions "$(cat prompts/adversary.md)"
```
Do **not** pipe the prompt (`cat prompts/builder.md | claude …`) — that forces print/headless mode,
which breaks `/loop` and remote control.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/kickoff.md
-3
View File
@@ -1,3 +0,0 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch-assistant.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch-assistant.py" "$@"
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch-assistant.sh
-29
View File
@@ -1,29 +0,0 @@
#!/usr/bin/env bash
set -euo pipefail
SELF_DIR="$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")"
FLAKE_ROOT="$(readlink -f "$SELF_DIR/..")"
FLAKE_HOST="${FLAKE_HOST:-cc-ci-orchestrator-hetzner}"
DEFAULT_MODEL="${LOOP_MODEL:-openai/gpt-5.4}"
ensure_opencode_web() {
if ! systemctl is-enabled --quiet opencode-web.service; then
sudo nixos-rebuild switch --flake "$FLAKE_ROOT#$FLAKE_HOST"
fi
if ! systemctl is-active --quiet opencode-web.service; then
sudo systemctl start opencode-web.service
fi
}
ensure_opencode_web
export LOOP_BACKEND=opencode
export LOOP_MODEL="$DEFAULT_MODEL"
export ORCH_SESSION="${ORCH_SESSION:-cc-ci-orchestrator-oc}"
if [ "$#" -eq 0 ]; then
set -- fresh
fi
exec python3 "$SELF_DIR/launch-orchestrator.py" "$@"
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch-opencode.sh
-233
View File
@@ -1,233 +0,0 @@
#!/usr/bin/env python3
"""
cc-ci orchestrator launcher — start/resume the orchestrator session in tmux.
The orchestrator is the long-lived supervisory session: it watches the Builder/Adversary
loops, reads their logs/STATUS, edits the plan/prompts, restarts stuck loops, and owns
the VM-level fallback. It is SEPARATE from the loops that launch.py manages.
Usage:
launch-orchestrator.py start resume the persistent session (default)
launch-orchestrator.py fresh start a NEW session (no --resume)
launch-orchestrator.py stop kill the tmux session (conversation persists on disk)
launch-orchestrator.py status show session state
launch-orchestrator.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"
claude backend:
CLAUDE_BIN claude
REMOTE_CONTROL 1 (viewable at claude.ai/code)
ORCH_SESSION_ID override the resume id (else read from $ID_FILE)
ORCH_ID_FILE $LOG_DIR/.orchestrator-session-id
ORCH_STARTUP_PROMPT startup nudge injected as the first turn after --resume
opencode backend:
OPENCODE_BIN /home/loops/.local/bin/opencode
OPENCODE_SERVER http://127.0.0.1:4096
(no --resume equivalent; STARTUP_PROMPT is sent as the initial message;
the session title in the web UI is the SESSION name)
"""
import json, os, shlex, sys, subprocess
from datetime import datetime
from pathlib import Path
# ── config ────────────────────────────────────────────────────────────────────
SESSION = os.environ.get("ORCH_SESSION", "cc-ci-orchestrator")
WORKDIR = os.environ.get("ORCH_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")
# Orchestrator model: ORCH_MODEL env wins, then LOOP_MODEL, then a persisted file written
# when the operator changes the model (so watchdog-triggered restarts keep it).
_ORCH_MODEL_FILE = f"{LOG_DIR}/.orch-model"
def _read_file_default(path, default):
try:
v = open(path).read().strip()
return v or default
except FileNotFoundError:
return default
LOOP_MODEL = (os.environ.get("ORCH_MODEL") or os.environ.get("LOOP_MODEL")
or _read_file_default(_ORCH_MODEL_FILE, ""))
# claude-specific
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 = "c746050a-af11-409d-87ba-c05268e2e5d1"
ID_FILE = os.environ.get("ORCH_ID_FILE", f"{LOG_DIR}/.orchestrator-session-id")
STARTUP_PROMPT = os.environ.get("ORCH_STARTUP_PROMPT", (
"STARTUP (auto-launch): you are the cc-ci orchestrator, just (re)launched, likely after a "
"reboot. Do your AGENTS.md On-startup routine NOW: read cc-ci-plan/REBOOTS.md and run "
"cc-ci-plan/launch.py status, then send a proactive PushNotification that you are online "
"with the current phase and reboot count, and confirm cc-ci-loops.service brought the loops "
"+ watchdog back (relaunch with RESUME_PHASE=1 cc-ci-plan/launch.py start if not). "
"Also read cc-ci-plan/JOURNAL.md for recent context before resuming supervision."
))
# opencode-specific
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")
# ── helpers ───────────────────────────────────────────────────────────────────
def log(msg):
ts = datetime.now().strftime("%H:%M:%S")
print(f"[orchestrator {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):
"""Type a message into the tmux session and submit it."""
import time
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("ORCH_SESSION_ID")
if sid:
return sid
try:
v = Path(ID_FILE).read_text().strip()
return v or DEFAULT_ID
except FileNotFoundError:
return DEFAULT_ID
# ── launch ────────────────────────────────────────────────────────────────────
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}")
# Attach the orchestrator TUI to the shared opencode web server so it shows up in the
# same project/session listing as browser-created sessions.
model_env = ""
if LOOP_MODEL:
# attach has no --model flag, so inject a one-off config overlay for this session.
model_env = (
f"OPENCODE_CONFIG_CONTENT={shlex.quote(json.dumps({'model': LOOP_MODEL}))} "
)
cmd = (
f"set -a; . /srv/cc-ci/cc-ci-plan/load-env.sh; set +a; "
f"{model_env}NO_COLOR=1 {OPENCODE_BIN} attach {OPENCODE_SERVER} --dir {shlex.quote(WORKDIR)}"
)
log(f"starting {SESSION} (backend=opencode, model={LOOP_MODEL or 'default'})")
log(f" 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}")
# opencode: send the startup prompt once the TUI has connected (~8s).
if BACKEND == "opencode":
import time
time.sleep(8)
prompt = STARTUP_PROMPT or (
"You are the cc-ci orchestrator. Read cc-ci-plan/JOURNAL.md for full "
"context on what's happened and what needs doing, then supervise the loops."
)
# Send a pointer to the journal rather than the full prompt (avoids length limits).
bootstrap = (
"You are the cc-ci orchestrator. Start by reading cc-ci-plan/JOURNAL.md "
"(`cat cc-ci-plan/JOURNAL.md`) for full context, then check loop status "
"(`cc-ci-plan/launch.sh status`) and resume supervising."
)
_ping(SESSION, bootstrap)
# ── main ──────────────────────────────────────────────────────────────────────
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:
backend_note = (
"claude: --resume preserves conversation across reboots; viewable at claude.ai/code\n"
" opencode: fresh session each launch (no --resume); viewable at https://oc.ci.commoninternet.net"
)
print(f"""cc-ci orchestrator launcher
launch-orchestrator.py start resume the persistent session (default)
launch-orchestrator.py fresh start a new session (no --resume)
launch-orchestrator.py stop kill the tmux session
launch-orchestrator.py status show session state
launch-orchestrator.py attach tmux attach
Backend: {BACKEND} (LOOP_BACKEND env var)
Model: {LOOP_MODEL or '<backend default>'} (LOOP_MODEL env var)
Session: {SESSION} cwd={WORKDIR}
{backend_note}
""")
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch-orchestrator.py
-3
View File
@@ -1,3 +0,0 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch-orchestrator.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch-orchestrator.py" "$@"
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch-orchestrator.sh
-3
View File
@@ -1,3 +0,0 @@
#!/usr/bin/env bash
# Thin wrapper — delegates everything to launch-upgrader.py in the same directory.
exec python3 "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/launch-upgrader.py" "$@"
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch-upgrader.sh

Some files were not shown because too many files have changed in this diff Show More