Documentation

Continuous deployment — factory self-deploy via a containerized runner

The factory manages its own repo (aif) as a project: the agent makes changes on per-issue branches and merges them to main. Deployment is a separate, standard CD concern handled by GitHub Actions — not by the factory pipeline — so the agent never holds any infra credentials.

On every push to a branch the AUTO_DEPLOYS variable lists (for aif, main → staging), and on every dispatch (Promote), .github/workflows/deploy.yml first confirms on a Ubicloud runner that the commit passed the green-gate check (the verify-gate job — it queries the check-run rather than re-running the suite, so it costs seconds and refuses to deploy an ungated commit) and that the mimi runner is online. Only then does the self-hosted runner that itself is a container on the docker host (mimi) safely redeploy each target environment's factory:

verify green-gate         # ungated commit => the deploy stops here, nothing is touched
docker compose build      # build the new image first — the running factory stays up if this fails
tag current image :prev   # for rollback
docker compose up -d      # swap
health-check the factory  # retry ~60s (over the shared network, by DNS)
rollback to :prev if the new container is unhealthy

Why a container runner (docker-out-of-docker)

The runner container mounts the host's docker socket, so when the deploy job runs factory.sh redeploy it builds and swaps the factory as a sibling container on the same host daemon — exactly as a manual factory.sh up would, on the host's ports. This is docker-out-of-docker (sharing the host daemon via its socket), not docker-in-docker (a nested daemon). It works cleanly here because the factory's compose uses a named volume (factory-data:/data), not host bind mounts, and the build context is streamed to the daemon — so nothing depends on paths inside the runner container.

The runner also joins the factory's shared network (FACTORY_NETWORK), so its health-check reaches the factory by its DNS alias on the container port. No SSH key and no deploy secret is ever exposed to GitHub, and no deploy credential ever lands in an agent-operated container.

One-time setup

1. Provide a GitHub registration credential

The runner registers itself with GitHub on first boot. Give it one of:

  • RUNNER_PAT — a repo-scoped GitHub personal access token (fine-grained: the aif repo with Administration: read & write, or a classic token with repo). The runner image uses it to mint registration tokens itself, and can re-register across restarts. Recommended.
  • RUNNER_TOKEN — a one-time registration token from repo → Settings → Actions → Runners → New self-hosted runner (valid ~1 hour, single use).

Create this token yourself in GitHub — never paste a token into chat, and never commit it.

Where to put it. Not in the main .env — that file is stored verbatim as the production's DEPLOY_ENV deploy secret and shipped to the deploy job, which has no need for the runner's registration credential. Instead, put it in .env.runner (gitignored; copy .env.runner.example), which factory.sh runner sources on its own:

cp .env.runner.example .env.runner
#   set RUNNER_PAT=... (recommended) — or RUNNER_TOKEN=... for a one-time token

Or skip the file and pass it inline: RUNNER_PAT=... ./scripts/factory.sh runner up. A short-lived RUNNER_TOKEN is best passed inline rather than saved.

2. Run everything from your operator machine — no shell on mimi

factory.sh drives mimi's docker daemon over DOCKER_HOST=ssh://$DEPLOY_SSH, so every runner command runs from the same machine you already deploy the factory from. runner up creates the container on mimi over that SSH tunnel; you never open a shell on mimi.

Running factory.sh runner ... ON mimi itself needs FACTORY_DEPLOY_LOCAL=1 (FACTORY_DEPLOY_LOCAL=1 ./scripts/factory.sh runner up). Without it the script reaches mimi's daemon over ssh://$DEPLOY_SSH — i.e. it SSHes into itself — and fails with "Too many authentication failures".

The one thing that isn't a CLI knob is a Docker Desktop GUI setting on mimi — but it's on by default, so usually there's nothing to do:

  • The runner mounts /var/run/docker.sock. On Docker Desktop for Mac that path is a symlink to ~/.docker/run/docker.sock, and bind-mounting it into a container works by default (verified: a sibling container reaches the daemon through it). runner up runs a preflight that confirms this from your machine and fails with a clear message if it can't.
  • If that preflight fails, enable Settings → Advanced → "Allow the default Docker socket to be used" on mimi, or set DOCKER_SOCK to the socket path as it exists on mimi (an absolute path — not $HOME, which would expand on your machine, not mimi):

    DOCKER_SOCK=/Users/<mimi-user>/.docker/run/docker.sock \
      RUNNER_PAT=<pat> ./scripts/factory.sh runner up

    factory.sh runner honors DOCKER_SOCK (default /var/run/docker.sock).

3. Bring the runner up (from your operator machine)

With your .env present (it supplies DEPLOY_SSH, FACTORY_NAME, FACTORY_NETWORK, FACTORY_HOSTNAME, DASHBOARD_CONTAINER_PORT):

# repo-scoped PAT (recommended):
RUNNER_PAT=<your-github-pat> ./scripts/factory.sh runner up

# ...or a one-time registration token:
RUNNER_TOKEN=<registration-token> ./scripts/factory.sh runner up

./scripts/factory.sh runner logs     # watch it register ("Listening for Jobs")
./scripts/factory.sh runner ps

runner up preflights the socket mount, pulls the current runner image, then starts the runner container on mimi on FACTORY_NETWORK, labeled mimi (the workflow targets runs-on: [self-hosted, mimi]), with the docker socket mounted. Manage it — all from your machine — with:

./scripts/factory.sh runner up|down|rm|logs|ps
#   down = stop (keep the work volume);  rm = stop + delete the volume

Confirm it appears Idle under repo → Settings → Actions → Runners.

4. Give each environment its runtime env — DEPLOY_ENV

The redeployed container must come up with the same runtime env it was first deployed with (same OAuth client, SERVICE_TOKEN, ports, FACTORY_NAME, network …) — otherwise the credentials/ports change out from under you. factory.sh redeploy refuses to run if GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET or SERVICE_TOKEN is missing from that env, because with no shared URL token left there would be no way back into the dashboard.

Every persistent GitHub environment (production, staging, …) stores its env file verbatim as ONE secret name, DEPLOY_ENV, scoped to that environment (AIF-735). Never paste it into GitHub's textarea, which mangles long lines. Pipe it with the script:

./scripts/push-env.sh --env production            # from ./.env
./scripts/push-env.sh --env staging               # from ./.env.staging
./scripts/push-env.sh --env qa path/to/qa.env     # any other environment, any file

It is gh secret set DEPLOY_ENV --env <name> underneath. Before it uploads anything, it refuses:

  • a file that does not source cleanly, or has CRLF line endings;
  • a preview-* environment name;
  • a file carrying the preview template's marker;
  • a file that collides with another local env. It compares the file against every other ./.env / ./.env.* (examples and the template excluded) using scripts/check-env-collision.sh: two persistent environments must not share a FACTORY_NAME, a network alias, a host port or a session cookie.

The env file contains FACTORY_NAME, DASHBOARD_PORT, DASHBOARD_CONTAINER_PORT, GOOGLE_CLIENT_ID, GOOGLE_CLIENT_SECRET, FACTORY_PUBLIC_URL, SERVICE_TOKEN, FACTORY_NETWORK, FACTORY_HOSTNAME, GH_TOKEN, GIT_AUTHOR_*, etc.

The deploy job declares environment: <name>, which is what makes GitHub hand it that environment's DEPLOY_ENV. It writes the secret to .env at deploy time, adds DEPLOY_ENVIRONMENT=<name> (and FACTORY_ENVIRONMENT=<name> for the dashboard badge, except on production), and removes the file afterwards. DEPLOY_SSH in that env is ignored — the workflow sets FACTORY_DEPLOY_LOCAL=1 so factory.sh redeploy uses the docker daemon reached through the mounted socket.

The repo-level DEPLOY_ENV is the preview template (AIF-737). GitHub hands an environment that has no DEPLOY_ENV of its own the repo-level one, silently. That is exactly what a preview-* environment wants, and exactly what a persistent one must never get. So the template carries the marker line DEPLOY_ENV_KIND=preview-template, and the deploy refuses it:

environment staging has no DEPLOY_ENV secret of its own (it fell back to the
repo-level preview template) — refusing to deploy.

An empty secret is refused the same way. Either way nothing on the host is touched.

Give each environment its URL as an environment-scoped variable, so the recorded Deployment links to it: gh variable set ENVIRONMENT_URL --env staging --body https://…. If it is unset, the Deployment is recorded without a link.

The health-check target is supplied by the runner container's environment (FACTORY_HEALTH_HOST = FACTORY_HOSTNAME, FACTORY_HEALTH_PORT = DASHBOARD_CONTAINER_PORT, set in runner/compose.yaml). The deploy job re-aims it at the alias and port of the env it just materialised, so each environment's deploy probes its own container by DNS over the shared network. The probe hits /health — the only unauthenticated route left; / now redirects an anonymous request to /login.

5. (Optional) Let the deploy notice a dead runner — RUNNER_STATUS_PAT

A wedged runner does not make a deploy fail; it makes it wait. The job sits queued until GitHub cancels it at its 24-hour ceiling, and because the running factory is untouched the whole time, it reads as "deploy pending" rather than as a problem. timeout-minutes does not help — that bounds a job which is running, not one waiting to be picked up (measured: a job with timeout-minutes: 2 on a label no runner had was still queued at 2m25s).

The runner preflight step in deploy.yml's verify-gate job closes that gap by asking GitHub whether any online runner carries the mimi label before the deploy is queued. It runs on Ubicloud, never on mimi, since the point is to notice mimi being gone. It reads the repo's own runners and, when the repo is in an org, the org's — org-level runners (such as a pool serving every repo in the org) are only on the org's list. Those lists need repo Administration: read and org Self-hosted runners: read respectively, which GITHUB_TOKEN cannot be granted, so it takes a PAT:

  • Put it in .env as RUNNER_STATUS_PAT=… and run ./scripts/push-env.sh --env production. It sets the RUNNER_STATUS_PAT repo secret from that line and strips the line out of DEPLOY_ENV, so the token never reaches the deploy host (other environments strip it without setting it: it is repo-wide). Removing the line later leaves the secret alone; gh secret delete RUNNER_STATUS_PAT clears it.
  • Value: a fine-grained token for this repo with Administration: Read — plus, for org runners, the org's Self-hosted runners: Read (a classic token with repo and admin:org also works). For a repo-level container runner, the RUNNER_PAT in .env.runner already has the access — reuse it, or mint a read-only one.

It is optional by design. With no secret set, or with a token that cannot read the list, the step prints a warning and passes, so a factory that has not set one deploys exactly as it did before. Only a token that can read the list and finds no online mimi runner blocks the deploy — with the fix in the log:

./scripts/factory.sh runner down && ./scripts/factory.sh runner up

Note that is a recreate, not a restart. docker restart cannot fix a wedged runner — it is what causes it (see Notes / options).

If the runner is not merely offline but missing from the repo's runner list, look in ./scripts/factory.sh runner logs for "deprecated". The image is the floating myoung34/github-runner:latest with the runner's own auto-update disabled, so the runner version only changes when the image does. A host that kept an old cached image ends up on a version GitHub has retired: it registers, logs "Runner version vX is deprecated and cannot receive messages", and deregisters itself on exit. Re-run ./scripts/factory.sh runner up — it runs docker compose pull before starting, so it picks up the current image (AIF-716).


6. Persistent environments and auto-deploys (AIF-653, AIF-735)

Every persistent environment is its own factory on the same host. Each one is made by the same factory.sh redeploy with a different env file, so everything that follows from FACTORY_NAME — container, named volume, image, DNS alias — is its own. aif has two:

  • staging — every merge to main deploys it.
  • production — changes only when someone promotes a commit.

Stage starts with fresh data and loads no project (the repo's projects ship as .yaml.txt), so it never drives a real repo.

Adding one (staging is the worked example):

  1. Write .env.staging (git-ignored) from your production .env, changing: FACTORY_NAME=aif-stage, DASHBOARD_PORT and DEV_SSH_PORT to ports free on mimi, and FACTORY_PUBLIC_URL (if set) to its own address. Keep FACTORY_NETWORK (it joins production's network under its own alias). Leave out credentials it has no business holding — LINEAR_API_KEY, FLY_API_TOKEN, GH_TOKEN.

    FACTORY_NAME is the one that matters most. It keeps the environment off every other environment's container and data volume. It is also the environment's alias on the shared network, so it must be whatever its tunnel route points at. Leave it at production's value and the deploy rebuilds PRODUCTION with stage's env, and its health check passes anyway.

    Two guards catch that, and also catch a shared alias or host port:

    • scripts/check-env-collision.sh refuses it at push time.
    • The deploy job runs scripts/check-env-host.sh, which reads the conveyor.environment label compose.yaml puts on every factory container. It refuses a deploy whose container, or one of whose host ports, belongs to a different environment. A container from before the label only draws a warning, and its next deploy labels it.

    Give it its own SESSION_COOKIE_NAME (e.g. fsid_stage), and keep its SESSION_COOKIE_DOMAIN to its own host. Production scopes its fsid cookie to the parent domain, so the browser sends it to stage as well. Under the same name, stage reads production's session first, finds no such session in its own database, and every sign-in lands back on /login. The collision check refuses that too. Leave production on the default — the iOS and desktop apps look for fsid by name.

  2. Create the environment and its secret:

    • gh api -X PUT repos/<owner>/<repo>/environments/staging
    • ./scripts/push-env.sh --env staging
  3. Optionally, set its URL: gh variable set ENVIRONMENT_URL --env staging --body https://….
  4. To sign in to it in a browser, give it a tunnel route, and add <its url>/auth/google/callback to the Google OAuth client's redirect URIs.
  5. The production factory's GH_TOKEN needs Actions: read & write on this repo, so the Deployments tab can dispatch deploys and follow the run.

Until an environment has its own DEPLOY_ENV, its deploys fail with "environment X has no DEPLOY_ENV secret of its own". Every other environment is untouched.

Which pushes deploy where: AUTO_DEPLOYS. This is one repository variable holding a JSON list of rows:

gh variable set AUTO_DEPLOYS --body '[{"branch":"main","environment":"staging","tested":true,"transient":false}]'
  • A push to branch deploys environment.
  • One branch may feed several environments: one row each.
  • tested: true means the commit must have passed green-gate on its PR (verify-gate, below). tested: false ships it without asking. That suits a scratch environment, never production.
  • transient: true rows, and any preview-* environment, belong to the preview workflow (AIF-737) and are never redeployed by deploy.yml.
  • The Deployments tab edits this variable (AIF-733), because .factory/deployments.yaml names it under auto_deploys.
  • Unset means nothing auto-deploys. A malformed value also deploys nothing, and the run summary carries a warning.

deploy.yml's plan job runs scripts/deploy-plan.sh, which turns the variable (or a dispatch) into a matrix of environments. redeploy and record-deployment then run once per environment. Things worth knowing:

  • Concurrency is per environment (deploy-<environment>, never cancelling a running deploy), on the redeploy job itself. A merge never queues behind a promotion.
  • A push that selects nothing deploys nothing. It boots no runner unless its branch name appears somewhere in the variable, and even then only the few-second plan job runs. With no workflow-level group, such a run can never cancel a waiting deploy.
  • verify-gate fails closed for tested rows. It reports the verdict, and each tested row refuses on its own, so a red gate stops exactly those rows. A direct push, or a PR into a branch ci.yml's pull_request filter does not cover, has no gate. Widen that filter (as epic/** already is) if the branch should take PRs.

Any project can copy this workflow: the factory only reads and writes the variable, and the workflow has to honour it.

7. Migrating from FACTORY_ENV / DEPLOY_ON_MERGE (AIF-735, done once by a human)

Before AIF-735 there were two repo secrets:

  • FACTORY_ENV (production's env)
  • FACTORY_STAGE_ENV (stage's env)

and two repo variables:

  • DEPLOY_ON_MERGE (merges deploy production instead)
  • DEPLOY_BRANCH (which branch deploys)

Merging the change is safe before any of this. With AUTO_DEPLOYS unset a push deploys nothing, and a Promote fails with the "no DEPLOY_ENV" error without touching production. Run these from your operator machine, at the repo root:

R=fog-harbor/aif   # this repo

# 1. The two persistent environments (no-ops if they already exist).
gh api -X PUT repos/$R/environments/production
gh api -X PUT repos/$R/environments/staging

# 2. Their environment-scoped DEPLOY_ENV, from the same files as before.
./scripts/push-env.sh --env production                    # ./.env
mv .env.stage .env.staging && ./scripts/push-env.sh --env staging

# 3. Their URLs, for the recorded Deployments.
gh variable set ENVIRONMENT_URL --env production --body https://<production host>
gh variable set ENVIRONMENT_URL --env staging    --body https://<staging host>

# 4. main auto-deploys staging, gated.
gh variable set AUTO_DEPLOYS --body '[{"branch":"main","environment":"staging","tested":true,"transient":false}]'

# 5. Once one push has deployed staging and one Promote has deployed production:
gh secret delete FACTORY_ENV
gh secret delete FACTORY_STAGE_ENV
gh variable delete DEPLOY_ON_MERGE    # "not found" is fine
gh variable delete DEPLOY_BRANCH      # "not found" is fine

What the old variables did, now that they are gone:

  • DEPLOY_ON_MERGE=production becomes a row {"branch":"main","environment":"production","tested":true,"transient":false}.
  • DEPLOY_BRANCH=release becomes a row with "branch":"release".

The first deploy of each environment after the migration labels its container (conveyor.environment). Until then, check-env-host.sh warns about the unlabelled ones.

How a change ships

  1. You submit an aif issue; the agent works it (branch → build/typecheck → PR pushed). You review and approve; the merge stage lands it on main.
  2. The push to main triggers deploy-factory. plan finds the AUTO_DEPLOYS row for main, which points at staging, tested.

    • verify-gate confirms the commit's green-gate check passed. It follows the commit back to its PR, since the check-run lives on the PR head.
    • The mimi runner container then checks out that commit, materialises .env from staging's DEPLOY_ENV, checks the host for a collision, and runs ./scripts/factory.sh redeploy against the host daemon via the mounted socket.
    • A staging GitHub deployment is recorded (the record-deployment job, on Ubicloud), with the environment's ENVIRONMENT_URL.

    Where each job runs (AIF-686). Only redeploy is on mimi. plan, verify-gate (gate check + runner preflight) and record-deployment run on ubicloud-standard-2, like ci.yml and pages.yml, so none of this workflow uses GitHub-hosted minutes. GitHub bills every job a whole minute however short, which is why the preflight is a step in verify-gate and not a job of its own.

  3. Promote. The project's Deployments tab lists what is on staging but not on production. Its Promote button dispatches deploy-factory with that exact sha and environment=production.

    • The run verifies the gate on that sha, checks it out, redeploys production from production's DEPLOY_ENV, and records a production deployment.
    • That is also when the factory's issues get their deployed mark (AIF-459).
  4. Build fails → the running factory is untouched. New container unhealthy → it auto-rolls-back to the previous image. Healthy → you're on the new version.

The contract the tab reads is .factory/deployments.yaml (format in factory/server/src/deployconfig.ts). It takes each environment's commit from the latest successful GitHub deployment there — the ones record-deployment writes — rather than calling any factory's /health. The deploy jobs declare their environment with deployment: false, so GitHub records no Deployment of its own. Otherwise it would record one for the ref's head rather than the promoted sha.

Watch a deploy under the repo's Actions tab. You can also run deploy-factory by hand there (Run workflow). It deploys the environment you name — it is required, so nothing ships to production by omission — at sha, or the selected ref's head when sha is blank:

gh workflow run deploy.yml --ref main -f environment=staging

Roll back by promoting an older sha. The button takes a skip_gate_check input for the emergency case where you must redeploy a commit the gate never blessed.

Notes / options

  • Signing the Mac app is five more repo secrets, set by ./scripts/push-mac-signing.sh from a local .env.macsign, never pasted into GitHub. Without them the app is ad-hoc signed. See docs/mac-signing.md.
  • Publishing the site is one more repo secret, SITE_DEPLOY_KEY. On a Free org, GitHub serves Pages from public repos only, so a private repo can't serve its own site. pages.yml builds the site and pushes it to a separate PUBLIC site repo, which is what Pages serves. The secret holds the private half of a deploy key that has write access to that repo, and to nothing else. If it is missing, pages.yml stops at its publish step and says so. The site repo is generated: every publish replaces its whole tree, so never edit anything in it by hand. If your own repo is public, or on a paid plan, publish Pages from it directly and skip all of this.
  • A wedged runner is RECREATED, never restarted. A restart reuses the container's writable layer, so the registration from its first boot is still there — and the image's entrypoint clears .runner but not .credentials. That half-configured pair fails both ways (config.sh refuses with *"already configured"; removal fails with "Value cannot be null (configuredSettings)"*), the container exits 2, and restart: unless-stopped repeats it forever. So docker restart cannot fix this state — it is what produces it. Use ./scripts/factory.sh runner down && ./scripts/factory.sh runner up, which gives a fresh layer. runner/compose.yaml now clears both files in an entrypoint wrapper, so a host reboot re-registers on its own; the recreate is for a container created before that fix, or for any other stuck state.
  • Host runner instead of a container: if you'd rather run the runner as a raw host service, register it the usual way (GitHub's shown config.sh/svc.sh steps) with the label mimi and add its user to the docker group. The same workflow then health-checks the factory at 127.0.0.1:${DASHBOARD_PORT} (the published host port) — factory.sh redeploy defaults there when the container's FACTORY_HEALTH_* vars are absent.
  • Extra approval gate: the deploy job already declares its environment, so requiring reviewers on production (repo → Settings → Environments) adds a second human click before each production deploy. (The factory already gates via issue approval before merge, so this is optional.)
  • Config-only changes (tools/workflows YAML under config/) don't need a full redeploy — they take effect via factory.sh config-push/reload. The redeploy rebuilds the whole image, which also covers them.
  • Multiple factories on one host: give each its own runner (unique FACTORY_NAME → its own runner project/label) and a workflow per instance; environments on one runner are §6's model instead.