Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

ci(spaces): advance the staged rollout automatically with health gates and auto-pause (CUA-2322) (#5990)

cua-agents[bot]0e6c43a2f733
diff --git a/.github/scripts/release_rollout_auto.py b/.github/scripts/release_rollout_auto.py
new file mode 100644
index 0000000000..7cc31f95f5
--- /dev/null
+++ b/.github/scripts/release_rollout_auto.py
@@ -0,0 +1,284 @@
+#!/usr/bin/env python3
+"""Decide whether the Cua Spaces staged rollout advances, waits or pauses.
+
+Read-only. It reads the live feeds, works out the current stage and when it
+started, checks the health gates and prints one JSON decision. The workflow
+.github/workflows/release-rollout-auto.yml acts on it (dispatches
+release-rollout.yml, posts the alert); this script never changes anything.
+
+Stage and start, from the feeds (nothing else to keep in step):
+ stage 10 latest.yml stagingPercentage 10, newest stable appcast item has a 10-year
+ phasedRolloutInterval; started at its pubDate (the rollout sets it to now)
+ stage 50 stagingPercentage 50, interval 1 week; started at pubDate + 3 weeks
+ 100 / paused / anything that disagrees between the feeds: no action
+
+Decision (the Play Store / Firebase / Sentry release-health pattern):
+ hold a human said hold: never advance (a failing gate still pauses)
+ wait the stage is younger than --min-age-hours, or a gate has too little data
+ pause a gate is past its threshold: the workflow pauses and alerts
+ advance old enough, every gate has enough data and passes: 10 -> 50 -> 100
+
+Gates, PostHog project 56041 (EU), spaces_app events of the new version versus the
+previous stable (the most active non-prerelease version in the week before the stage):
+ adoption at least --min-installs installs of the new version sent cua_app_active
+ since the stage began (no data is not healthy, it waits)
+ space_create error share of cua_space_create on the new version is at most
+ --max-create-error-delta points above the previous version's over the
+ same window (needs --min-create-events on both sides)
+ update share of failed among found/failed cua_app_update from the previous version
+ since the stage began (the version that tries to install the new one) is at
+ most --max-update-failure-delta points above its share the week before
+ (needs --min-update-events)
+ incident no active incident.io incident with "spaces" in its name (needs
+ INCIDENT_IO_API_KEY; without it the gate is reported as skipped)
+Sentry is not wired into the Spaces app, so there is no crash-free gate: the app sends
+no crash event. Add one here when it does.
+
+Standard library only. Keys come from the environment: POSTHOG_API_KEY (query read),
+INCIDENT_IO_API_KEY (optional).
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+import urllib.error
+import urllib.request
+import xml.etree.ElementTree as ET
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parent))
+import release_rollout as rr # noqa: E402
+
+POSTHOG = "https://eu.posthog.com/api/projects/56041/query/"
+NEXT = {"10": "50", "50": "100"}
+
+
+def _num(text: str | None) -> int | None:
+ return int(text) if text and text.strip().isdigit() else None
+
+
+def read_state(feed_dir: Path) -> dict:
+ """{version, stage ('10'|'50'|'100'|'pause'), since (datetime|None), problem (str|None)}."""
+ out: dict = {"version": None, "stage": None, "since": None, "problem": None}
+ yml = feed_dir / "latest.yml"
+ if not yml.exists():
+ out["problem"] = "latest.yml is not on the feed"
+ return out
+ text = yml.read_text()
+ out["version"] = rr.feed_version(text)
+ m = re.search(r"^stagingPercentage:\s*(\d+)\s*$", text, re.M)
+ staging = m.group(1) if m else None
+ if staging == "0":
+ out["stage"] = "pause"
+ return out
+ if staging is None:
+ out["stage"] = "100"
+ return out
+ if staging not in ("10", "50"):
+ out["problem"] = f"stagingPercentage {staging} is not a stage"
+ return out
+ path = feed_dir / rr.APPCAST
+ if not path.exists():
+ out["problem"] = "no appcast, cannot tell when the stage started"
+ return out
+ items = rr._channel_items(ET.parse(path).getroot(), "stable")
+ if not items:
+ out["problem"] = "the appcast has no stable item (paused?) while latest.yml is staged"
+ return out
+ item = max(items, key=rr._version_key)
+ if item.findtext("title") != out["version"]:
+ out["problem"] = f"appcast newest is {item.findtext('title')}, latest.yml is {out['version']}"
+ return out
+ interval = _num(item.findtext(f"{{{rr.SP}}}phasedRolloutInterval"))
+ pub = item.findtext("pubDate")
+ want = rr.HOLD_SECONDS if staging == "10" else rr.WEEK
+ if interval != want or not pub:
+ out["problem"] = f"latest.yml is at {staging}% but the appcast item has interval {interval}: the feeds disagree"
+ return out
+ start = parsedate(pub)
+ out["stage"] = staging
+ out["since"] = start if staging == "10" else start + timedelta(seconds=3 * rr.WEEK)
+ return out
+
+
+def parsedate(text: str) -> datetime:
+ return datetime.strptime(text.strip(), "%a, %d %b %Y %H:%M:%S %z").astimezone(timezone.utc)
+
+
+def posthog(query: str, key: str) -> list[list]:
+ req = urllib.request.Request(
+ POSTHOG,
+ json.dumps({"query": {"kind": "HogQLQuery", "query": query}}).encode(),
+ {"Authorization": "Bearer " + key, "Content-Type": "application/json"},
+ )
+ with urllib.request.urlopen(req, timeout=120) as r:
+ return json.load(r).get("results", [])
+
+
+def lit(ts: datetime) -> str:
+ return "toDateTime('%s', 'UTC')" % ts.strftime("%Y-%m-%d %H:%M:%S")
+
+
+def previous_version(q, new: str, since: datetime) -> str | None:
+ rows = q(
+ "select properties.product_version v, count(distinct distinct_id) n from events "
+ "where event = 'cua_app_active' and properties.product = 'spaces_app' "
+ f"and timestamp >= {lit(since - timedelta(days=7))} and timestamp < {lit(since)} "
+ f"and properties.product_version != '{new}' and properties.product_version not like '%-%' "
+ "group by v order by n desc limit 1"
+ )
+ return rows[0][0] if rows else None
+
+
+def share(bad: int, total: int) -> float:
+ return 100.0 * bad / total if total else 0.0
+
+
+def gate_adoption(q, new, since, now, a) -> dict:
+ n = int(q(
+ "select count(distinct distinct_id) from events where event = 'cua_app_active' "
+ f"and properties.product = 'spaces_app' and properties.product_version = '{new}' "
+ f"and timestamp >= {lit(since)} and timestamp < {lit(now)}"
+ )[0][0])
+ ok = n >= a.min_installs
+ return {"gate": "adoption", "status": "pass" if ok else "wait",
+ "detail": f"{n} installs of {new} active since the stage began (need {a.min_installs})"}
+
+
+def gate_space_create(q, new, prev, since, now, a) -> dict:
+ def counts(v):
+ rows = q(
+ "select properties.outcome o, count() from events where event = 'cua_space_create' "
+ f"and properties.product = 'spaces_app' and properties.product_version = '{v}' "
+ f"and timestamp >= {lit(since)} and timestamp < {lit(now)} group by o"
+ )
+ total = sum(int(r[1]) for r in rows)
+ return sum(int(r[1]) for r in rows if r[0] == "error"), total
+
+ (eb, et), (pb, pt) = counts(new), (counts(prev) if prev else (0, 0))
+ if et < a.min_create_events or pt < a.min_create_events:
+ return {"gate": "space_create", "status": "wait",
+ "detail": f"{et} Space creates on {new}, {pt} on {prev} (need {a.min_create_events} each)"}
+ d = share(eb, et) - share(pb, pt)
+ return {"gate": "space_create", "status": "fail" if d > a.max_create_error_delta else "pass",
+ "detail": f"create errors {share(eb, et):.1f}% on {new} ({eb}/{et}) vs {share(pb, pt):.1f}% on {prev} ({pb}/{pt}), "
+ f"delta {d:+.1f} points (limit +{a.max_create_error_delta})"}
+
+
+def gate_update(q, prev, since, now, a) -> dict:
+ if not prev:
+ return {"gate": "update", "status": "wait", "detail": "no previous version to compare"}
+
+ def counts(lo, hi):
+ rows = q(
+ "select properties.action a, count() from events where event = 'cua_app_update' "
+ f"and properties.product = 'spaces_app' and properties.product_version = '{prev}' "
+ "and properties.channel = 'stable' and properties.action in ('found', 'failed') "
+ f"and timestamp >= {lit(lo)} and timestamp < {lit(hi)} group by a"
+ )
+ d = {r[0]: int(r[1]) for r in rows}
+ return d.get("failed", 0), d.get("found", 0) + d.get("failed", 0)
+
+ (fb, ft), (bb, bt) = counts(since, now), counts(since - timedelta(days=7), since)
+ if ft < a.min_update_events:
+ return {"gate": "update", "status": "wait",
+ "detail": f"{ft} update attempts from {prev} since the stage began (need {a.min_update_events})"}
+ d = share(fb, ft) - share(bb, bt)
+ return {"gate": "update", "status": "fail" if d > a.max_update_failure_delta else "pass",
+ "detail": f"update failures {share(fb, ft):.1f}% ({fb}/{ft}) vs {share(bb, bt):.1f}% the week before ({bb}/{bt}), "
+ f"delta {d:+.1f} points (limit +{a.max_update_failure_delta})"}
+
+
+def gate_incident(key: str | None, fetch=None) -> dict:
+ if not key:
+ return {"gate": "incident", "status": "skip", "detail": "INCIDENT_IO_API_KEY not set, gate skipped"}
+ try:
+ if fetch:
+ data = fetch()
+ else:
+ req = urllib.request.Request(
+ "https://api.incident.io/v2/incidents?status_category%5Bone_of%5D=active&page_size=100",
+ headers={"Authorization": "Bearer " + key})
+ with urllib.request.urlopen(req, timeout=30) as r:
+ data = json.load(r)
+ except (urllib.error.URLError, OSError, ValueError) as e:
+ return {"gate": "incident", "status": "wait", "detail": f"incident.io unreachable ({e}); not advancing blind"}
+ hits = [i for i in data.get("incidents", []) if "spaces" in (i.get("name") or "").lower()]
+ if hits:
+ names = ", ".join(f"{i.get('reference', '?')} {i.get('name')}" for i in hits[:3])
+ return {"gate": "incident", "status": "fail", "detail": f"active Spaces incident: {names}"}
+ return {"gate": "incident", "status": "pass", "detail": "no active incident naming Spaces"}
+
+
+def decide(state: dict, now: datetime, a, q=None, incident=None, hold: str = "") -> dict:
+ d: dict = {"version": state["version"], "stage": state["stage"],
+ "since": state["since"].isoformat() if state["since"] else None,
+ "action": "none", "next": None, "gates": [], "why": ""}
+ if state["problem"]:
+ d["why"] = "cannot decide: " + state["problem"]
+ return d
+ if state["stage"] not in NEXT:
+ d["why"] = {"100": "fully rolled out", "pause": "paused: resuming is a person's call"}.get(state["stage"], "nothing to do")
+ return d
+ since = state["since"]
+ age = (now - since).total_seconds() / 3600
+ d["age_hours"] = round(age, 1)
+ if age < 0:
+ d["why"] = "the stage start is in the future"
+ return d
+ new = state["version"]
+ prev = previous_version(q, new, since)
+ d["previous"] = prev
+ d["gates"] = [gate_adoption(q, new, since, now, a), gate_space_create(q, new, prev, since, now, a),
+ gate_update(q, prev, since, now, a), incident or gate_incident(os.environ.get("INCIDENT_IO_API_KEY"))]
+ failed = [g for g in d["gates"] if g["status"] == "fail"]
+ waiting = [g for g in d["gates"] if g["status"] == "wait"]
+ if failed:
+ d["action"] = "pause"
+ d["why"] = "gate failed: " + "; ".join(g["detail"] for g in failed)
+ elif hold:
+ d["action"] = "hold"
+ d["why"] = "hold is set (" + hold + "): not advancing"
+ elif age < a.min_age_hours:
+ d["action"] = "wait"
+ d["why"] = f"stage is {age:.1f}h old, needs {a.min_age_hours}h"
+ elif waiting:
+ d["action"] = "wait"
+ d["why"] = "not enough data: " + "; ".join(g["detail"] for g in waiting)
+ else:
+ d["action"] = "advance"
+ d["next"] = NEXT[state["stage"]]
+ d["why"] = f"{age:.1f}h at {state['stage']}%, every gate passes"
+ return d
+
+
+def main(argv: list[str] | None = None) -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--feed-dir", required=True, type=Path)
+ ap.add_argument("--now", help="ISO time (tests)")
+ ap.add_argument("--hold", default=os.environ.get("ROLLOUT_HOLD", ""), help="non-empty: do not advance")
+ ap.add_argument("--min-age-hours", type=float, default=24)
+ ap.add_argument("--min-installs", type=int, default=15)
+ ap.add_argument("--min-create-events", type=int, default=30)
+ ap.add_argument("--max-create-error-delta", type=float, default=10.0)
+ ap.add_argument("--min-update-events", type=int, default=20)
+ ap.add_argument("--max-update-failure-delta", type=float, default=15.0)
+ a = ap.parse_args(argv)
+ now = datetime.fromisoformat(a.now) if a.now else datetime.now(timezone.utc)
+ key = os.environ.get("POSTHOG_API_KEY", "")
+ state = read_state(a.feed_dir)
+ if not key and state["stage"] in NEXT and not state["problem"]:
+ print("::error::POSTHOG_API_KEY is not set", file=sys.stderr)
+ return 2
+ d = decide(state, now, a, q=lambda s: posthog(s, key), hold=a.hold.strip())
+ print(json.dumps(d, indent=2))
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/.github/scripts/tests/test_release_rollout_auto.py b/.github/scripts/tests/test_release_rollout_auto.py
new file mode 100644
index 0000000000..2a3bf16fa6
--- /dev/null
+++ b/.github/scripts/tests/test_release_rollout_auto.py
@@ -0,0 +1,114 @@
+"""Run: python3 .github/scripts/tests/test_release_rollout_auto.py"""
+
+import argparse
+import sys
+import tempfile
+import unittest
+from datetime import datetime, timedelta, timezone
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+import release_rollout_auto as ra # noqa: E402
+
+PUB = datetime(2026, 10, 25, 21, 47, 23, tzinfo=timezone.utc)
+SP = 'xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle"'
+
+
+def feeds(staging, interval, pub=PUB, title="0.16.0"):
+ d = Path(tempfile.mkdtemp())
+ yml = "version: %s\nreleaseDate: '2026-10-25T21:29:51Z'\n" % title
+ if staging is not None:
+ yml += "stagingPercentage: %s\n" % staging
+ (d / "latest.yml").write_text(yml)
+ iv = "<sparkle:phasedRolloutInterval>%s</sparkle:phasedRolloutInterval>" % interval if interval else ""
+ (d / "cua-spaces-appcast.xml").write_text(
+ "<rss %s version='2.0'><channel><item><title>%s</title><pubDate>%s</pubDate>%s<sparkle:version>%s.1</sparkle:version></item></channel></rss>"
+ % (SP, title, pub.strftime("%a, %d %b %Y %H:%M:%S +0000"), iv, title))
+ return d
+
+
+def args(**kw):
+ a = argparse.Namespace(min_age_hours=24, min_installs=15, min_create_events=30, max_create_error_delta=10.0,
+ min_update_events=20, max_update_failure_delta=15.0)
+ a.__dict__.update(kw)
+ return a
+
+
+def fake(installs=40, new_create=(50, 5), old_create=(100, 10), new_update=(100, 10), old_update=(100, 10), prev="0.15.0"):
+ """A PostHog stand-in keyed on the query text. *_create = (total, errors); *_update = (attempts, failed)."""
+ def q(sql):
+ if "count(distinct distinct_id) n" in sql:
+ return [[prev, 90]]
+ if "count(distinct distinct_id) from" in sql:
+ return [[installs]]
+ if "cua_space_create" in sql:
+ t, e = new_create if "'0.16.0'" in sql else old_create
+ return [["ok", t - e], ["error", e]]
+ if "cua_app_update" in sql:
+ lo = sql.split("timestamp >= toDateTime('")[1][:10]
+ t, f = new_update if lo >= "2026-10-25" else old_update
+ return [["found", t - f], ["failed", f]]
+ raise AssertionError(sql)
+ return q
+
+
+OK = lambda: ra.gate_incident("k", lambda: {"incidents": []}) # noqa: E731
+
+
+class State(unittest.TestCase):
+ def test_stage_10(self):
+ s = ra.read_state(feeds("10", ra.rr.HOLD_SECONDS))
+ self.assertEqual((s["stage"], s["since"]), ("10", PUB))
+
+ def test_stage_50_started_three_weeks_after_pubdate(self):
+ s = ra.read_state(feeds("50", ra.rr.WEEK, PUB - timedelta(weeks=3)))
+ self.assertEqual((s["stage"], s["since"]), ("50", PUB))
+
+ def test_100_pause_and_disagreement(self):
+ self.assertEqual(ra.read_state(feeds(None, None))["stage"], "100")
+ self.assertEqual(ra.read_state(feeds("0", None))["stage"], "pause")
+ self.assertTrue(ra.read_state(feeds("50", ra.rr.HOLD_SECONDS))["problem"])
+ self.assertTrue(ra.read_state(feeds("10", ra.rr.HOLD_SECONDS, title="0.16.1"))["problem"] is None)
+
+
+class Decide(unittest.TestCase):
+ def go(self, hours=25, hold="", q=None, stage="10"):
+ s = ra.read_state(feeds("10", ra.rr.HOLD_SECONDS)) if stage == "10" else ra.read_state(feeds(stage, None))
+ return ra.decide(s, PUB + timedelta(hours=hours), args(), q=q or fake(), incident=OK(), hold=hold)
+
+ def test_advance(self):
+ d = self.go()
+ self.assertEqual((d["action"], d["next"]), ("advance", "50"))
+
+ def test_too_young_waits_even_if_green(self):
+ self.assertEqual(self.go(hours=5)["action"], "wait")
+
+ def test_no_data_waits(self):
+ self.assertEqual(self.go(q=fake(installs=3))["action"], "wait")
+
+ def test_create_errors_pause(self):
+ d = self.go(q=fake(new_create=(50, 25)))
+ self.assertEqual(d["action"], "pause")
+
+ def test_update_failures_pause_even_when_young(self):
+ self.assertEqual(self.go(hours=2, q=fake(new_update=(100, 60)))["action"], "pause")
+
+ def test_incident_pauses(self):
+ s = ra.read_state(feeds("10", ra.rr.HOLD_SECONDS))
+ inc = ra.gate_incident("k", lambda: {"incidents": [{"reference": "INC-9", "name": "Spaces relay down"}]})
+ self.assertEqual(ra.decide(s, PUB + timedelta(hours=30), args(), q=fake(), incident=inc)["action"], "pause")
+
+ def test_hold_blocks_advance_not_pause(self):
+ self.assertEqual(self.go(hold="label")["action"], "hold")
+ self.assertEqual(self.go(hold="label", q=fake(new_create=(50, 25)))["action"], "pause")
+
+ def test_done_and_paused_do_nothing(self):
+ self.assertEqual(self.go(stage=None)["action"], "none")
+ self.assertEqual(self.go(stage="0")["action"], "none")
+
+ def test_incident_skipped_without_key(self):
+ self.assertEqual(ra.gate_incident(None)["status"], "skip")
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/.github/workflows/release-rollout-auto.yml b/.github/workflows/release-rollout-auto.yml
new file mode 100644
index 0000000000..7e34157216
--- /dev/null
+++ b/.github/workflows/release-rollout-auto.yml
@@ -0,0 +1,126 @@
+name: "Release: auto rollout (Cua Spaces)"
+
+# Advances the Cua Spaces staged rollout by itself (health-gated, with auto-pause),
+# the pattern of Play Store, Firebase and Sentry release health. Hourly it reads the
+# stage from the live feeds, and when a stage has run 24h and every health gate
+# passes it dispatches release-rollout.yml for the next one (10 -> 50 -> 100). If a
+# gate fails it dispatches `pause` and posts an alert. Gates and thresholds:
+# .github/scripts/release_rollout_auto.py. Manual dispatch of release-rollout.yml
+# keeps working and is what this workflow calls; a person can still pause or advance.
+#
+# Hold: set the repository variable SPACES_ROLLOUT_HOLD to any text (the reason), or
+# put the label `spaces-rollout-hold` on any open issue. A hold stops advancing; a
+# failing gate still pauses. Remove the variable or close the issue to release it.
+# Resuming after a pause is a person's call (run release-rollout.yml).
+#
+# Run it by hand with dry_run on (the default for a manual run) to see the decision
+# without dispatching, pausing or alerting anything. Scheduled runs act.
+
+on:
+ schedule:
+ - cron: "17 * * * *"
+ workflow_dispatch:
+ inputs:
+ dry_run:
+ description: "Print the decision, dispatch and alert nothing"
+ type: boolean
+ default: true
+
+permissions:
+ contents: read
+ actions: write
+ issues: read
+
+concurrency:
+ group: release-rollout-auto-spaces
+ cancel-in-progress: false
+
+jobs:
+ decide:
+ name: "Rollout decision${{ inputs.dry_run && ' (dry run)' || '' }}"
+ if: github.repository == 'trycua/cua'
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+ env:
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+ TAG: cua-spaces-latest
+ POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
+ INCIDENT_IO_API_KEY: ${{ secrets.INCIDENT_IO_API_KEY }}
+ ALERTMANAGER_INTAKE_TOKEN: ${{ secrets.ALERTMANAGER_INTAKE_TOKEN }}
+ HOLD_VAR: ${{ vars.SPACES_ROLLOUT_HOLD }}
+ DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || 'false' }}
+ steps:
+ - uses: actions/checkout@v4
+ with:
+ sparse-checkout: .github
+ persist-credentials: false
+ - name: Check the scripts
+ run: |
+ python3 .github/scripts/tests/test_release_rollout.py
+ python3 .github/scripts/tests/test_release_rollout_auto.py
+ - name: Fetch the feeds
+ run: |
+ set -euo pipefail
+ mkdir -p feed
+ for pattern in 'latest*.yml' cua-spaces-appcast.xml; do
+ gh release download "$TAG" --pattern "$pattern" --dir feed --clobber --repo "$GITHUB_REPOSITORY" 2>/dev/null || true
+ done
+ ls -l feed
+ - name: Look for a hold
+ id: hold
+ run: |
+ hold="${HOLD_VAR:-}"
+ if [ -z "$hold" ]; then
+ n=$(gh issue list --repo "$GITHUB_REPOSITORY" --label spaces-rollout-hold --state open --json number --jq 'map("#\(.number)") | join(" ")')
+ [ -n "$n" ] && hold="label spaces-rollout-hold on $n"
+ fi
+ echo "hold=$hold" >> "$GITHUB_OUTPUT"
+ - name: Decide
+ id: decide
+ run: |
+ set -euo pipefail
+ python3 .github/scripts/release_rollout_auto.py --feed-dir feed --hold "${{ steps.hold.outputs.hold }}" | tee decision.json
+ {
+ echo "action=$(jq -r .action decision.json)"
+ echo "next=$(jq -r '.next // ""' decision.json)"
+ } >> "$GITHUB_OUTPUT"
+ {
+ echo "## Spaces rollout: $(jq -r .action decision.json)$([ "$DRY_RUN" = true ] && echo ' (dry run)')"
+ echo
+ jq -r '"- version: \(.version), stage: \(.stage)%, since: \(.since // "n/a"), age: \(.age_hours // "n/a")h", "- why: \(.why)", (.gates[]? | "- gate \(.gate): **\(.status)**, \(.detail)")' decision.json
+ } >> "$GITHUB_STEP_SUMMARY"
+ - name: Advance
+ if: ${{ steps.decide.outputs.action == 'advance' && env.DRY_RUN != 'true' }}
+ run: |
+ gh workflow run release-rollout.yml --repo "$GITHUB_REPOSITORY" \
+ -f component=spaces -f platform=all -f channel=stable -f dry_run=false \
+ -f stage="${{ steps.decide.outputs.next }}" \
+ -f reason="auto: $(jq -r .why decision.json)"
+ - name: Pause and alert
+ if: ${{ steps.decide.outputs.action == 'pause' && env.DRY_RUN != 'true' }}
+ run: |
+ set -euo pipefail
+ why=$(jq -r .why decision.json)
+ gh workflow run release-rollout.yml --repo "$GITHUB_REPOSITORY" \
+ -f component=spaces -f platform=all -f channel=stable -f dry_run=false \
+ -f stage=pause -f reason="auto-pause: $why"
+ python3 - <<'PY'
+ import base64, json, os, urllib.request
+ d = json.load(open("decision.json"))
+ run = "%s/%s/actions/runs/%s" % (os.environ["GITHUB_SERVER_URL"], os.environ["GITHUB_REPOSITORY"], os.environ["GITHUB_RUN_ID"])
+ alert = [{
+ "labels": {"alertname": "SpacesRolloutAutoPaused", "source": "github-actions", "severity": "warning",
+ "environment": "release", "repo": os.environ["GITHUB_REPOSITORY"], "workflow": "release-rollout-auto"},
+ "annotations": {"summary": "Cua Spaces %s auto-paused at %s%%" % (d["version"], d["stage"]),
+ "description": d["why"] + " Resume with Release: staged rollout (Cua Spaces) after the fix.",
+ "run_url": run},
+ }]
+ auth = base64.b64encode(("alerts:" + os.environ["ALERTMANAGER_INTAKE_TOKEN"]).encode()).decode()
+ req = urllib.request.Request("https://am.cua.ai/api/v2/alerts", json.dumps(alert).encode(),
+ {"Content-Type": "application/json", "Authorization": "Basic " + auth,
+ "User-Agent": "workflow-alerts-" + os.environ["GITHUB_REPOSITORY"].replace("/", "-")})
+ urllib.request.urlopen(req, timeout=30).read()
+ PY
+ - name: Dry run note
+ if: ${{ env.DRY_RUN == 'true' }}
+ run: echo "Dry run, nothing was dispatched or posted." >> "$GITHUB_STEP_SUMMARY"
diff --git a/apps/cua-spaces-desktop/docs/staged-rollout.md b/apps/cua-spaces-desktop/docs/staged-rollout.md
index 882a228d0b..ae4fc1f807 100644
--- a/apps/cua-spaces-desktop/docs/staged-rollout.md
+++ b/apps/cua-spaces-desktop/docs/staged-rollout.md
@@ -20,6 +20,42 @@ Typical flow after a stable release: `10`, watch crash and update telemetry,
`50`, `100`. Bad build: `pause`. The release workflow still publishes feeds as
before (everyone); writing them at 10% on publish comes with phase 2.
+## Automatic advance (health gates, auto-pause)
+
+`release-rollout-auto.yml` ("Release: auto rollout (Cua Spaces)") runs hourly and
+does what the typical flow above asks of a person. It reads the stage from the
+live feeds (`stagingPercentage` plus the newest appcast item's interval and
+`pubDate`; stage 10 started at the `pubDate`, stage 50 at `pubDate` + 3 weeks)
+and dispatches `release-rollout.yml` itself, so the actor and reason land in that
+job summary as usual. Manual dispatch is unchanged.
+
+| Decision | When |
+|---|---|
+| advance (10 to 50, 50 to 100) | stage at least 24h old, every gate has enough data and passes |
+| wait | younger than 24h, or a gate has too little data (no data is not healthy) |
+| pause | a gate is past its threshold, at any stage age: dispatches `pause` and posts an Alertmanager alert (`SpacesRolloutAutoPaused`, source `github-actions`, to #alerts-staging; it does not page) |
+| hold | the variable `SPACES_ROLLOUT_HOLD` is set (the text is the reason) or an open issue has the label `spaces-rollout-hold`: never advances; a failing gate still pauses |
+| none | 100%, paused (resuming is a person's call), or the feeds disagree |
+
+Gates (PostHog project 56041, `spaces_app` events of the new version against the
+previous stable, the most active non-prerelease version the week before the stage):
+
+- adoption: at least 15 installs of the new version sent `cua_app_active` since the stage began;
+- space create: `cua_space_create` error share at most 10 points above the previous version's, at least 30 events each;
+- update: failed share of `cua_app_update` from the previous version (the one installing the new one) at most 15 points above its share the week before, at least 20 attempts;
+- incident: no active incident.io incident with "spaces" in its name (needs the `INCIDENT_IO_API_KEY` secret; skipped and said so in the summary until it is set).
+
+There is no crash-free gate: Spaces has no Sentry and sends no crash event. Add
+one to `.github/scripts/release_rollout_auto.py` when it does. Thresholds are
+flags of that script. Secrets: `POSTHOG_API_KEY` (query read), optional
+`INCIDENT_IO_API_KEY`, and the existing `ALERTMANAGER_INTAKE_TOKEN`.
+
+Dry run: **Actions > Release: auto rollout (Cua Spaces) > Run workflow** (dry run
+is on by default for a manual run). It prints the decision and every gate in the
+job summary and dispatches, pauses and alerts nothing. Scheduled runs act. Locally:
+`POSTHOG_API_KEY=... python3 .github/scripts/release_rollout_auto.py --feed-dir <dir>`
+prints the same decision as JSON.
+
## What each stage does
| Stage | electron-updater (Windows, Linux) | Sparkle (macOS) |