docs: archive completed cc-ci build loops

This commit is contained in:
notplants
2026-11-23 19:53:30 +00:00
parent e490e4d884
commit 301843e5dc
146 changed files with 9016 additions and 8808 deletions
-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
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"
STARTUP (auto-launch): you are the cc-ci operator steering agent. Read AGENTS.md
and README.md, inspect the current host, weekly upgrade, report, and auto-update
status using /cc-ci-status, then report any concrete issue. The original
Builder/Adversary build is complete; do not relaunch its loops."""
[[agent]]
name = "assistant" # tmux session: cc-ci-assistant
@@ -100,7 +81,7 @@ 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
enabled = false # launched by the weekly timer or on demand
prompt = """
You are the cc-ci weekly UPGRADER. Invoke the /upgrade-all skill in DEFAULT mode (read \
/srv/cc-ci/.claude/skills/upgrade-all/SKILL.md for the full procedure), run it to completion, \
@@ -122,56 +103,3 @@ You generate the public weekly "Recipe Report". Run the /recipe-report skill now
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" } },
]
+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
-999
View File
@@ -1,999 +0,0 @@
#!/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()
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch.py
-3
View File
@@ -1,3 +0,0 @@
#!/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" "$@"
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/launch.sh
-33
View File
@@ -1,33 +0,0 @@
#!/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
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/msg-loop.sh
-63
View File
@@ -1,63 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/orchestration.md
@@ -1,8 +0,0 @@
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
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/orchestrator-opencode-restart.txt
-92
View File
@@ -1,92 +0,0 @@
#!/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 ==="
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/overnight-run.sh
@@ -1,44 +0,0 @@
# 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`.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/phase6-phase7-summary-2026-06-01.md
-127
View File
@@ -1,127 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-cc-ci-combined-host.md
@@ -1,92 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-mirror-enroll-all-recipes.md
-32
View File
@@ -1,32 +0,0 @@
# 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).
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-overnight-run.md
-108
View File
@@ -1,108 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-bsky-fix.md
@@ -1,173 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-canon-canonical-sweep.md
@@ -1,81 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-cf48-opus-cfold-review.md
@@ -1,82 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-cf55-gpt55-cfold-review.md
@@ -1,91 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-cfold-custom-folder.md
@@ -1,81 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-dash-recipe-history.md
-85
View File
@@ -1,85 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-drone-enroll.md
@@ -1,79 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-dstamp-discourse-drift.md
-70
View File
@@ -1,70 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-ghost-reeval.md
@@ -1,178 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-gtea-gitea-fulltests.md
-70
View File
@@ -1,70 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-kuma-monitor.md
-191
View File
@@ -1,191 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-lvl5-lint-rung.md
-73
View File
@@ -1,73 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-mailu-backup.md
@@ -1,91 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-nixenv-shared-runtime-env.md
@@ -1,120 +0,0 @@
# 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`.)
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-prevb-previous-dynamic-base.md
@@ -1,67 +0,0 @@
# 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 @@
../archive/original-build/cc-ci-plan/plan-phase-pvcheck-post-proxy-verification.md
@@ -1,81 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-pvfix-swarm-proxy.md
@@ -1,76 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-pxgate-proxy-healthgate.md
@@ -1,108 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-redfix-canon-sweep-failures.md
@@ -1,65 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-regall-recipe-regression.md
@@ -1,101 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-samever-older-base-fallback.md
@@ -1,114 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-settings-ci-server-config.md
-127
View File
@@ -1,127 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase-shot-screenshots.md
-174
View File
@@ -1,174 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase1b-review-lint.md
@@ -1,196 +0,0 @@
# 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).
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase1c-full-reproducibility.md
@@ -1,243 +0,0 @@
# 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).
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase1d-generic-test-suite.md
@@ -1,139 +0,0 @@
# 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).
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase1e-harness-corrections.md
-300
View File
@@ -1,300 +0,0 @@
# 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.
+1
View File
@@ -0,0 +1 @@
../archive/original-build/cc-ci-plan/plan-phase2-recipe-tests.md

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