Skip to content

6.2 Scion-on-VM Bootstrap Runbook

This runbook rebuilds the agent factory as it runs in our dev environment today: a single-node Scion Hub on one VM with no public IP, attached to Esmeralda's Shared VPC, reachable only through a Cloud Run reverse proxy behind IAP, with Gemini CLI sandboxes whose model calls go through the Apigee llm-gateway and are billed to each paying team (esmeralda-contributors in the sample catalog). For the architecture and the repository components, read 6.1 Governed Agent Factory first.

Terraform provisions the infrastructure, hub VM, and IAP proxy, and esmeralda factory sync reconciles team projects from the catalog. The Hub UI configuration (section 5) is manual today, and this page lists every one of those steps.

Warning

What was verified, and what was not. Each step carries one of these labels:

  • Verified live: done in our dev environment, and the result checked (plan 0/0/0, HTTP status, BigQuery row).
  • Done live by hand: done in dev through the UI or a shell, but not re-run from this page.
  • Not verified: derived from the Terraform or from Scion's documentation, never run as written here.

Nobody has yet run this page top to bottom on a fresh environment. If you are the first, expect small gaps, and please open an issue or a PR with what you find.


0. What you end up with

flowchart LR
    User["Browser (org user)"] -->|"IAP"| Proxy["Cloud Run IAP proxy<br/>(Direct VPC egress)"]
    subgraph Factory["Factory project (layer 1)"]
        Proxy
        VM["Hub VM, no public IP<br/>scion binary + SQLite + Docker broker"]
        Sandbox["Agent sandboxes (containers)<br/>Gemini CLI + llm_gateway_proxy.py"]
        VM --- Sandbox
    end
    Proxy -->|"tcp:8080 (layer-2 firewall)"| VM
    Sandbox -->|"OIDC ID token of team x agent SA (assign mode)"| EP["Internal entry point<br/>apigee.&lt;domain&gt;/llm"]
    EP --> Apigee["Apigee llm-gateway<br/>allowed_callers + caller_workloads"]
    Apigee --> Vertex["Vertex AI"]
    Apigee -.->|"esmeralda.usage"| BQ[("BigQuery esmeralda_usage_&lt;env&gt;<br/>billed_team = paying team")]
Piece Owner Created by
Factory project, APIs, Cloud Run service agent Terraform, layer 1 esmeralda apply layer-1-projects
Shared VPC attachment, factory subnet, subnet networkUser for the Cloud Run service agent, tcp:8080 firewall to the hub tag Terraform, layer 2 esmeralda apply layer-2-networking
One service account per (paying team x agent), the hub's own service account, and serviceAccountTokenCreator on each agent account for it Terraform, layer 3 esmeralda apply layer-3-security
Agent accounts in allowed_callers, caller_workloads (<agent>), and caller_teams Terraform, layer 5 esmeralda apply .../llm-gateway
Agent accounts in principal_teams (paying team) and factory_agent_owners (owner team) Terraform, layer 5 esmeralda apply iap-egress
Hub VM, data disk, Cloud Run IAP proxy and its service account (integrations.scion.hub.vm) Terraform, layer 5 esmeralda apply layer-5-workloads/factories/scion-hub (section 3)
Daily run-reconciliation Cloud Run job, Cloud Scheduler, reconciler SA, log-match alerts (integrations.scion.reconcile) Terraform, layer 5 esmeralda apply layer-5-workloads/factories/scion-reconcile (section 5.7)
Optional GKE Standard runtime cluster, in-cluster broker (deploy/scion-broker), and internal VPC TLS (:8443) (integrations.scion.gke) Terraform, layers 1–3 & 5 esmeralda apply .../factories/scion-gke + .../scion-gke-k8s (section 5.8)
Harness, shell, IAP proxy, broker, and reconciler job images Cloud Build esmeralda build scion + esmeralda build scion-broker, deployed by digest (sections 3 & 5.8)
Hub settings, experiments, project, GitHub App Out of band Hub web UI (section 5)

1. Prerequisites and the env.yaml toggle

1.1 Prerequisites

  • An Esmeralda environment already deployed through layer 5 (see the deployment guide), with Apigee enabled and the llm-gateway capability unit applied. Today the factory reaches models only through llm-gateway; the plan has no Apigee-free path for it yet.
  • A free billing-account project slot: layer 1 creates one more project (<prefix>-factory-<suffix>).
  • A deployer identity that can create projects (as for the other layer-1 projects), administer the Shared VPC (as for layer 2), and hold roles/compute.networkUser on the factory subnet in the network host project (layer 2 grants networkUser only to the factory's Cloud Run service agent, not to the deployer). In our dev, the deployer is an organization administrator, so this was implicit. (Not verified with a narrower deployer.)
  • Quota for one e2-standard-4 VM and one Cloud Run service in the region.
  • Users of the Hub UI must belong to the organization (IAP uses the Google-managed OAuth client, so no OAuth brand is needed).
  • gcloud (with the beta component) and jq.

1.2 Turn the integration on

In infrastructure/live/<env>/env.yaml, add "scion" to integrations.enabled and fill the scion block:

integrations = {
  enabled = ["scion"]
  scion = {
    runtime     = "vm"            # the only wired path; "gke" fails the plan on purpose
    subnet_cidr = "<factory-subnet-cidr>"  # a free /24 on the Shared VPC
    hub = {
      network_tag        = "scion-hub-<hub-name>"  # tag of the hub VM (layer-2 tcp:8080 rule)
      service_account_id = "scion-hub-<hub-name>"  # layer 3 creates the hub's service account
      vm = {                                       # the Terraform-managed hub VM (section 3)
        enabled       = true
        name          = "<hub-name>"
        zone          = "<zone>"
        machine_type  = "e2-standard-4"
        boot_disk_gb  = 50
        data_disk_gb  = 200
        scion_version = "v0.4.0-preview.5"
        scion_sha256  = "<sha256 of scion-linux-amd64.tar.gz from the release's SHA256SUMS>"
        harness_image = "scion-gemini-cli"
        proxy_image   = "scion-hub-iap-proxy"
      }
    }
    reconcile = {                                  # daily run reconciliation (section 5.7)
      enabled  = true
      schedule = "30 6 * * *"
    }
  }
}
Field Environment-specific? Value
subnet_cidr Yes A /24 that overlaps none of your Shared VPC ranges (core, proxy-only, PSC, PSC interface, PSA, partner NAT). Check with gcloud compute networks subnets list --project=<net-host-project-id>.
hub.network_tag Yes The hub VM's network tag; the layer-2 firewall rule targets it.
hub.service_account_id Yes Account ID (the part before @) of the hub's service account. Layer 3 creates it in the factory project, with serviceAccountTokenCreator on each factory agent account, logging / monitoring / trace writer, logging / monitoring viewer (for the hub UI) and repository-scoped Artifact Registry reader.
hub.vm Yes The Terraform-managed hub (section 3).

The factory's agents are not listed in env.yaml: each is declared by its owner team in catalog/teams/<team>/factory/<agent>.yaml (see 6.1). Turn the factory on in the catalog too, so the agents compile into factory_identities (one layer-3 service account per paying team × agent) and principal_teams (the paying teams), and regenerate the resolved catalog. make test-guards fails when the toggle and this override disagree:

# catalog/environments/<env>.yaml, under overrides
policy:
  factory:
    enabled: true

Teams that start factory runs declare their own Scion project (the billing boundary) in catalog/teams/<team>/team.yaml:

profile:
  team: <team>
  factory:
    scion_project: <team>-factory
    short: <team code>          # up to 6 characters: accounts fa-<team code>-<agent code>-<env>

Layer 3 then creates one service account per (team × agent) for that team (billed to it in principal_teams), and the hub service account gets serviceAccountTokenCreator on each.

uv run --frozen esmeralda catalog resolve --env <env> --write
make test-guards

(Verified live: this is the configuration dev runs.)


2. Apply order

The hub's service account is a layer-3 resource, and the token-creator bindings reference it, so there is no chicken-and-egg any more: a fresh environment applies in one pass.

flowchart LR
    L1["1. layer-1-projects"] --> L2["2. layer-2-networking"]
    L2 --> L3["3. layer-3-security<br/>(agent SAs + hub SA + bindings)"]
    L3 --> LLM["4. llm-gateway"]
    LLM --> IAP["5. iap-egress"]
    L3 --> HUB["6. factories/scion-hub<br/>(VM + IAP proxy)"]
    HUB --> REC["7. factories/scion-reconcile<br/>(daily Cloud Run job + alerts)"]
uv run --frozen esmeralda build scion            # harness + IAP proxy + factory-reconcile images (Cloud Build)
uv run --frozen esmeralda apply layer-1-projects --env <env>
uv run --frozen esmeralda apply layer-2-networking --env <env>
uv run --frozen esmeralda apply layer-3-security --env <env>
uv run --frozen esmeralda apply layer-5-workloads/apigee/capabilities/llm-gateway --env <env>
uv run --frozen esmeralda apply layer-5-workloads/iap-egress --env <env>
uv run --frozen esmeralda apply layer-5-workloads/factories/scion-hub --env <env>
uv run --frozen esmeralda apply layer-5-workloads/factories/scion-reconcile --env <env>
uv run --frozen esmeralda verify --env <env>
  • Layer 3 creates the factory accounts only once layer 1 has output a factory project ID (enable_agent_factory is false until then), so planning layer 3 before layer 1 is harmless.
  • The deployer needs roles/compute.networkUser on the factory subnet in the network host project to reserve the hub's internal address and create the VM there (layer 2 grants it only to the factory's Cloud Run service agent). An organization or Shared VPC administrator already has it; a narrower CI identity needs it granted.

(Verified live in dev: layers 1–3, llm-gateway, iap-egress and factories/scion-hub applied and re-planned 0/0/0.)


3. Deploy the hub with Terraform

With integrations.scion.hub.vm.enabled = true, the layer-5 unit factories/scion-hub (scion-hub-vm) creates:

  • the VM scion-hub-<name>: Ubuntu 22.04 Shielded VM, no external IP, on the factory subnet with a reserved internal IP, tagged hub.network_tag, running as the layer-3 hub account, OS Login;
  • a separate persistent data disk mounted at /home/scion (hub database, workspaces, local secrets), so replacing the VM keeps the hub state;
  • the Cloud Run service scion-hub-<name>-iap-proxy with IAP enabled, Direct VPC egress on the factory subnet, its own service account with no project role, run.invoker for the IAP service agent only, and iap.httpsResourceAccessor for the members in ESMERALDA_FACTORY_HUB_MEMBERS (user-local env file, user:<email>,group:<email>; users also become hub admins).

The VM's startup script (re-run every 10 minutes, so metadata changes need no reboot) installs Docker, verifies and installs the pinned Scion release, writes hub.env (session secret generated on the VM) and settings.yaml (IAP proxy auth, update_policy: disabled, default identity mode block, telemetry defaults), runs the hub under systemd, seeds GOOGLE_CLOUD_PROJECT (an llm-gateway model project) and GOOGLE_CLOUD_LOCATION=global as hub env vars, and pulls two images by digest, adding the internal Root CA in a local layer: the harness, tagged localhost/scion/scion-gemini-cli:latest and :<scion version> (both names the stock gemini-cli harness-config resolves to), and the shell image, tagged localhost/scion/scion-base:latest and :<scion version> (the stock shell harness-config's image, used by the execution containers in 5.6).

Images: uv run --frozen esmeralda build scion builds, in Cloud Build, Scion's core-base → scion-base (the release's own binaries, checked against its SHA256SUMS) → gemini-cli image for the pinned release, Esmeralda's layers on top (apps/harnesses/scion-gemini-cli), and the IAP proxy (extras/cloudrun-iap-proxy), into the layer-0 repository. Esmeralda's layers add a pinned toolchain, each download checked against a SHA-256 in the Dockerfile: uv, Terraform (at least 1.12.2, which layer 2 needs), Terragrunt and gh. The harness also gets the llm-gateway auth-swap proxy; the shell image (pushed as scion-base) gets only the toolchain. Keep _SCION_VERSION in .cloudbuild/scion-gemini-cli.yaml and .cloudbuild/scion-hub-iap-proxy.yaml equal to hub.vm.scion_version (make test-guards checks it).

No credential is in either image. gh authenticates at runtime: when the project's GitHub App installation is bound (5.5), the hub injects a short-lived installation token for the project's repository as GITHUB_TOKEN, sciontool refreshes it before it expires, and Scion's gh wrapper (/usr/bin/gh) passes the current token to the real binary. Don't set GH_TOKEN in project or template env vars: the wrapper treats it as an override and stops using the refreshed App token. Without a bound installation, gh runs unauthenticated.

Telemetry (hub.vm.agent_telemetry, on by default): settings.yaml turns on Scion telemetry with a GCP destination in the factory project, so the hub UI shows logs, token usage and metrics.

  • Each agent's sciontool exports the agent's logs, metrics and traces to Cloud Logging, Monitoring and Trace with the agent's own service account. Layer 3 grants each factory agent account roles/logging.logWriter, roles/monitoring.metricWriter and roles/cloudtrace.agent on the factory project only.
  • The gemini-cli provisioner points gemini-cli's native telemetry at sciontool's collector on 127.0.0.1:4317. Token usage comes from it. Prompts are never exported.
  • The hub sends its own logs to Cloud Logging (cloud_logging).
  • The Logs and Metrics tabs read these back with the hub's account. Layer 3 grants the hub account roles/logging.viewer and roles/monitoring.viewer on the factory project.
  • Leave each Scion project's telemetry on Use hub default.

Open the hub at the proxy URL (uv run --frozen esmeralda status --env <env> --unit layer-5-workloads/factories/scion-hub --output hub_url).

(Verified live in dev: release verified and installed, /healthz healthy with the co-located broker, the proxy answers unauthenticated requests with the IAP sign-in redirect and has no allUsers binding, the harness ran from the Artifact Registry digest, and a harness container's llm_gateway_proxy.py, minting tokens for the builder account through the hub account's token-creator grant, got HTTP 200 from llm-gateway.)


5. Hub UI configuration (manual today)

Manual today: Terraform provisions the VM, IAM, and IAP proxy, and esmeralda factory sync reconciles env vars, skills, templates, and project settings from the catalog — but the steps below still have to be performed manually in the Hub web UI once per hub/project (through the IAP proxy URL, signed in as an admin_email user).

Step Automated or manual today Where
Experiments (hub.conduit, hub.exec_containers, hub.command_requests) Manual Admin → Server Config → Experiments
Project creation (<team> slug, Git repo, Clone per agent) Manual Projects → New Project
GitHub App setup + project installation binding Manual Admin → Server Config → GitHub App + Project → GitHub
Registering team GCP service accounts (when using a Scion token) Manual Project Settings → Project Resources → GCP Service Accounts
Project default model (gemini-3.7-flash) Manual Project Settings → Configuration → General
Env vars, FACTORY_SA_*, esmeralda-rules skill, 7 agent templates, roles, Assign mode Automated uv run --frozen esmeralda factory sync --env <env>
Human execution container (dev-exec) + ADC login Manual New Agent (shell, GCP Identity Block) + Profile → Settings + IAP SSH
Grant reconciler SA (sa-factory-reconcile-<env>) project-viewer on each team project Manual Project Settings → Access / Members (or Hub REST role binding; section 5.7)
Join in-cluster scion-gke-broker over internal VPC TLS (:8443) + link to existing project Manual (once per broker PVC / existing project) Hub-boundary PAT (1h) + scion runtime-broker join + provide (section 5.8)
Governed GitHub MCP secret (github-mcp-app-private-key) + App/Installation IDs Manual (until automated) GitHub App .pem in ~/.config/esmeralda/ (0600) → Secret Manager (<mcps-project-id>) + ~/.config/esmeralda/env (section 5.9)

5.1 Experiments

Admin → Server Config → Experiments:

  • Required for approved commands (esmeralda-dev-tester + dev-exec): enable hub.conduit, hub.exec_containers, and hub.command_requests.
  • Optional: hub.triggers and hub.github_triggers (only needed if you plan to schedule or trigger runs automatically; not required for manual/lead-driven issue loops).
  • Keep off: hub.port_view (does not work behind IAP).

Reload the browser page (F5) after saving so the front-end refreshes its feature flags (for example, the Execution container card in Profile Settings only appears once the browser sees hub.exec_containers enabled).

5.2 Server & project defaults for agents

  • Admin → Server Config (hub defaults):
    • Default GCP identity mode: Block. Never Passthrough: passthrough would hand every sandbox the hub VM's own service account.
    • Default harness config: gemini-cli.
  • Project Settings → Configuration → General (after creating the project in 5.3):
    • Default Model: select or enter gemini-3.7-flash and click Save Configuration. Setting this at the project level survives hub restarts (unlike editing the medium alias in the stock gemini-cli harness-config).
  • Project Settings → Configuration → Auth & Security:
    • Default Agent Role: Baseline — Standard access
    • Maximum Agent Role: Full — Full access (admin only) (required so esmeralda-lead can dispatch child agents with --role baseline; esmeralda factory sync also enforces these).

(Done live by hand.)

5.3 Project

Projects → New Project, one per team that runs the factory, with the slug from its team.yaml factory.scion_project (esmeralda factory status --env <env> lists the missing ones):

  • Workspace Type: Git Repository, with the HTTPS URL of your repository (we use a fork for the issue loop).
  • Workspace Mode: Clone per agent.
  • GitHub Token: leave empty when the GitHub App (5.5) provides installation tokens; for a quick test against a public repository, an unauthenticated clone also works.

(Done live by hand.)

5.4 Sync the team projects (esmeralda factory sync)

The rest of each team project comes from the catalog.

  1. Register the team's GCP service accounts (required when authenticating with a Scion token): Scion User Access Tokens (scion_pat_...) intentionally cannot register new GCP service accounts (gcp_service_account:manage is restricted to interactive admin sessions). In Project Settings → Project Resources → GCP Service Accounts (scroll the resource tabs right with > if needed), click + Register Existing for each of the team's agent accounts (fa-<team code>-<agent code>-<env>@<factory-project-id>.iam.gserviceaccount.com, GCP project <factory-project-id>), then click Verify on each. Verification succeeds only after layer 3 has granted the hub's account roles/iam.serviceAccountTokenCreator on each account.
  2. Create a short-lived Scion User Access Token (until the IAP programmatic OAuth client is configured; see 6.1): in Profile → Access Tokens, select the team project, pick a short expiration (e.g. 1–7 days), and grant one of the minimal scope sets below (verified against Scion v0.4.0-preview.5):
    • Read-only (status, sync --dry-run, logs, conversations): project:list, project:read, gcp_service_account:list, gcp_service_account:read, template:list, template:read, skill:list, skill:read, agent:list, agent:read, inbox:read.
    • Full CLI operator (sync, start --role baseline, logs, conversations, cleanup — 13 checkboxes using Scion's umbrella aliases):
      • Umbrella aliases (3): agent:manage (create/delete/lifecycle/list/message/read), template:manage (create/delete/list/read/update), skill:manage (create/delete/list/read/register/update). (project:manage is not an umbrella alias — it only manages project membership and is not needed.)
      • Project (3): project:list, project:read, project:update (project env vars use project:read/project:update; there is no separate env:* scope).
      • Service accounts (4): gcp_service_account:list, gcp_service_account:read, gcp_service_account:verify, gcp_service_account:assign.
      • Harness config (2): harness_config:list, harness_config:read (required for User Access Tokens to create baseline agents via factory start).
      • Inbox (1): inbox:read (for factory conversations and hub notifications, section 7).
      • Optional (+1, for factory look live terminal capture): agent:attach (not included in agent:manage).
    • Save it in your user-local env file (~/.config/esmeralda/env, never in the repository) as ESMERALDA_SCION_HUB_TOKEN=scion_pat_....
  3. Preview, sync, and verify zero drift:
uv run --frozen esmeralda factory sync --env dev --dry-run
uv run --frozen esmeralda factory sync --env dev
uv run --frozen esmeralda factory status --env dev

sync publishes the model gateway env vars (GOOGLE_CLOUD_PROJECT is the layer-1 CX agents project, a model_projects entry of llm-gateway; GOOGLE_CLOUD_LOCATION=global), ESMERALDA_BILLED_TEAM / ESMERALDA_BILLED_COST_CENTER, FACTORY_SA_<AGENT>, the esmeralda-rules skill (with auto-inject), one template per agent, and turns on Assign Service Account with the team's lead account as default. status should report 0 drift item(s) — In sync. Run status again after a hub restart. (Verified live in dev against the Terraform-managed hub.)

5.5 GitHub App

  1. In GitHub, create a GitHub App with the least privilege: Contents read and write, Pull requests read and write, Metadata read (plus Issues only if you target the upstream repo directly; forks disable Issues by default). Nothing else (no administration, no merge rights).
  2. Setup URL: https://<hub-proxy-url>/github-app/setup.
  3. Webhook: leave it disabled. GitHub cannot deliver webhooks to a hub behind IAP (it can't pass the IAP login), so event triggers do not fire in this topology. Delivering them would need a separate, non-IAP ingress that forwards only POST /api/v1/webhooks/github and checks the HMAC signature; see integrations/scion/triggers/README.md.
  4. Generate a private key (.pem).
  5. In the Hub, Admin → Server Config → GitHub App Configuration: enter the App ID, paste the PEM, save, and delete the local .pem.
  6. Restart the hub once if needed so the token minter picks up the key: sudo systemctl restart scion-hub.service.
  7. Install the App on the target repository (or personal fork).
  8. Back in the Hub, under Installations, click Discover from GitHub and confirm the installation appears as active.
  9. Bind the installation to the project: open Projects → <project> → GitHub → Connection, click Bind installation, select the installation, and confirm status is Connected / Active. Back in Admin → Server Config → Project Associations, click Refresh and confirm the project appears with admin_binding, WRITE: yes, and STATUS: authorized.

(Done live by hand, on a fork; webhook delivery not available behind IAP, as described.)

5.6 Approved Commands: the human's execution container

For esmeralda-dev-tester's human-approved commands (see integrations/scion/approved-commands/README.md), each approver starts a personal shell execution container (for example dev-exec):

Execution container image: the built-in shell harness runs localhost/scion/scion-base:latest (or :<scion-version>). converge.sh provides both tags from Esmeralda's scion-base image (hub.vm.shell_image): Scion's scion-base for the pinned release plus the same pinned toolchain as the harness (uv, Terraform, Terragrunt, gh), built by esmeralda build scion, pulled by digest and given the internal Root CA. No manual tag is needed. docker image inspect -f '{{ index .Config.Labels "dev.esmeralda.source" }}' localhost/scion/scion-base:latest on the VM shows the Artifact Registry digest it comes from. A container created before the image changed keeps its old image until it is recreated.

  1. Create the container: Projects → <project> → New Agent:
    • Agent Name: dev-exec
    • Harness Config: choose Other... and enter shell (or select Execution container (shell) once the UI refreshes after enabling hub.exec_containers).
    • Additional Options → Auth & Security → GCP Identity: change from Assign Service Account to Block so the container never inherits the project's default agent service account and only acts with your human ADC credentials.
  2. Register as your execution container: open Profile → Settings (/profile/settings), locate the Execution container card (reload the page with F5 if it does not appear after enabling hub.exec_containers), and select dev-exec (or run scion exec-container set dev-exec from an authenticated CLI).
  3. Log in to Google Cloud inside the container: the Hub's web terminal is awkward for this (Shift-drag copies tmux pane borders, and Ctrl+V drops leading characters). Run the one-time login over IAP SSH instead; the trailing -- -t allocates a TTY so docker exec -it works:
gcloud compute ssh scion-hub-<hub-name> --zone=<zone> --project=<factory-project-id> --tunnel-through-iap \
  --command="sudo docker exec -it -u scion <project>--dev-exec gcloud auth application-default login --no-launch-browser" -- -t
gcloud compute ssh scion-hub-<hub-name> --zone=<zone> --project=<factory-project-id> --tunnel-through-iap \
  --command="sudo docker exec -u scion <project>--dev-exec gcloud auth application-default set-quota-project <quota-project-id>"

(Done live by hand.)

5.7 Daily run reconciliation (factories/scion-reconcile)

When integrations.scion.reconcile.enabled = true, layer-5-workloads/factories/scion-reconcile creates the daily Cloud Run job esmeralda-factory-reconcile-<env>, its Cloud Scheduler trigger, its least-privilege service account (sa-factory-reconcile-<env>@<governance-project-id>.iam.gserviceaccount.com), and two log-match alert policies on layer-4's notification channels (discrepancies and failures).

Because Scion has no declarative role-binding config, one hub step is manual per environment:

  1. Provision the reconciler user on the hub: run the job once (or wait for its first scheduled run). Its first request through IAP (--auth sa) creates a hub user for sa-factory-reconcile-<env>@<governance-project-id>.iam.gserviceaccount.com (the run exits 2 and logs ESMERALDA_FACTORY_RECONCILE_FAILED naming the projects until step 2 is done).
  2. Grant project-viewer on every team Scion project: as a hub admin, add sa-factory-reconcile-<env>@<governance-project-id>.iam.gserviceaccount.com to each team project with the built-in project-viewer role (least privilege: project.list, project.read, agent.list, agent.read).
  3. Verify with a manual execution:
    gcloud run jobs execute esmeralda-factory-reconcile-<env> --region <region> --project <governance-project-id> --wait
    
    Check Cloud Logging for resource.type="cloud_run_job" AND resource.labels.job_name="esmeralda-factory-reconcile-<env>": expect ESMERALDA_FACTORY_RECONCILE_OK (INFO) on a clean day, or ESMERALDA_FACTORY_RECONCILE_DISCREPANCIES (WARNING) when usage records disagree with the hub (still exit 0; triggers the discrepancy alert policy).

5.8 Optional GKE runtime broker (scion-gke-broker) over internal VPC TLS

When integrations.scion.gke.enabled = true and integrations.scion.gke.broker_transport_mode = "" (the default internal VPC TLS path), the in-cluster Kubernetes runtime broker (deploy/scion-broker in namespace scion-system) connects directly to the Hub VM over internal VPC TLS on port 8443 instead of traversing Cloud Run IAP:

  • Layer 2 (layer-2-networking): scopes allow-factory-gke-pods-to-hub-<env> to tcp:8443 from the GKE Pod CIDR to the Hub VM tag.
  • Layer 3 (layer-3-security): signs a leaf certificate for scion-hub.<internal_domain> with Esmeralda's internal Root CA, stores the leaf + private key in Secret Manager (the Root CA key never leaves layer 3, and the leaf key never enters Terragrunt outputs or GCE instance metadata), and grants roles/secretmanager.secretAccessor on that single secret to the Hub VM service account.
  • Layer 5 (factories/scion-hub): registers scion-hub.<internal_domain>. in the layer-2 private DNS zone, runs nginx-light on :8443 (TLSv1.2/TLSv1.3, WebSocket upgrade, 3600s timeouts, stripping X-Goog-IAP-JWT-Assertion) proxying to 127.0.0.1:8080, adds loopback to server.trusted_proxies, sets server.hub.agent_endpoint to https://scion-hub.<internal_domain>:8443 for remote GKE agent callbacks, and keeps server.broker.container_hub_endpoint on http://host.docker.internal:8080 for co-located Docker agents.
  • Layer 5 (factories/scion-gke-k8s): publishes ConfigMap/esmeralda-internal-ca in both scion-system and scion-agents, mounts /etc/esmeralda, and injects SSL_CERT_DIR=/etc/ssl/certs:/etc/esmeralda into deploy/scion-broker and managed fa-* agent Pods (via MutatingAdmissionPolicy) so Go clients trust both public roots and Esmeralda's internal Root CA.

1. Verify internal VPC TLS from the broker Pod

kubectl exec -n scion-system deploy/scion-broker -- \
  /usr/local/bin/scion --hub https://scion-hub.<internal_domain>:8443 hub status

Expect Connection: ok and Hub Status: healthy.

2. Register and join scion-gke-broker with HMAC credentials (once per PVC)

  1. Create a temporary Hub-boundary PAT (1h): in the Hub Web UI (Profile → Access Tokens), choose boundary Hub (not a team project), set a short expiry (for example 1h), and grant only broker:create and broker:read.
  2. Create the broker record and mint a single-use join token (scion_join_...): pass the PAT on stdin so it never appears in shell history or process arguments:
    printf '%s\n' '<temporary-hub-pat>' | kubectl exec -i -n scion-system deploy/scion-broker -- /bin/sh -ec \
      'IFS= read -r SCION_HUB_TOKEN; export SCION_HUB_TOKEN; exec /usr/local/bin/scion --hub https://scion-hub.<internal_domain>:8443 hub brokers join-token create scion-gke-broker --ttl 30m --json'
    
    Copy brokerId and joinToken from the JSON output.
  3. Redeem the join token inside deploy/scion-broker via stdin (--token-file -):
    printf '%s\n' '<join-token>' | kubectl exec -i -n scion-system deploy/scion-broker -- \
      /usr/local/bin/scion --hub https://scion-hub.<internal_domain>:8443 \
      runtime-broker join --broker-id <broker-id> --token-file - --force
    
    The broker exchanges the single-use join token over TLS :8443 for a 256-bit HMAC secret, saves it to /home/scion/.scion/hub-credentials/ on its PVC (scion-broker-state), and brings up its WebSocket control channel and heartbeat automatically. No PAT or IAP token is stored in the Pod.
  4. Verify online status and PVC persistence across restarts:
    kubectl rollout restart deployment/scion-broker -n scion-system
    kubectl rollout status deployment/scion-broker -n scion-system --timeout=120s
    kubectl logs -n scion-system deploy/scion-broker --tail=30
    
    Expect auth=hmac, heartbeat=true, control_channel=true, Connected to Hub control channel, and Initial heartbeat sent to Hub.
  5. Revoke the temporary Hub-boundary PAT immediately in Profile → Access Tokens once scion-gke-broker shows online in the Hub UI.
  • New project: when scion-gke-broker is already online, the Hub Web UI (Projects → New Project) lets you select it during project creation.
  • Existing project (for example during a VM → GKE migration on esmeralda-contributors): in Scion v0.4.0-preview.5, Projects → <project> → Settings → Runtime Brokers only supports changing the default broker or removing providers — there is no "Add Broker" button in the UI, and associating a broker requires an interactive Hub user session (User Access Tokens cannot satisfy broker-ownership consent). Link the broker using one of:
    • Recommended (authenticated scion CLI):
      scion runtime-broker provide --broker scion-gke-broker --project <project-slug>
      
    • Fallback without a local signed-in scion CLI (browser DevTools Console on an authenticated Hub UI tab):
      await fetch('/api/v1/projects/<project-id>/providers', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ brokerId: '<broker-id>' }),
      }).then(r => r.json())
      

Reload Projects → <project> → Settings → Runtime Brokers and confirm scion-gke-broker appears alongside Hosted Broker. You can keep Hosted Broker as the default while validating agents explicitly dispatched to scion-gke-broker.

4. Disable the default scratchpad shared directory (when not using Filestore/NFS)

By default, Scion creates a scratchpad shared directory on every project (project_defaults.default_scratchpad = true), which requires a ReadWriteMany PVC on Kubernetes. factories/scion-gke-k8s leaves shared_dir_storage_class empty by default so GKE does not auto-provision an expensive Filestore instance unless explicitly opted in. When your agents do not need scratchpad, disable the Hub default and remove scratchpad from the project:

  1. Hub Web UI (recommended):
    • Open Admin → Server Config → Project Default Settings and turn off Enable default scratchpad shared directory (required first; while enabled, Scion refuses to delete scratchpad with 409 Conflict).
    • Open Projects → <project> → Settings → Shared Directories and remove scratchpad.
  2. API equivalent (authenticated Hub admin session):
    await fetch('/api/v1/admin/project-defaults', {
      method: 'PUT',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ default_scratchpad: false }),
    }).then(r => r.json())
    await fetch('/api/v1/projects/<project-id>/shared-dirs/scratchpad', { method: 'DELETE' })
    

If a fleet does require shared directories across GKE agent Pods, set shared_dir_storage_class (for example standard-rwx or a custom NFS StorageClass) on factories/scion-gke-k8s instead.

(Verified live in dev: internal VPC TLS :8443, HMAC join, PVC persistence across pod restart, online control channel + heartbeat, and Hub-dispatched GKE agent execution.)

5.9 Optional Governed GitHub MCP Server (mcps/github-mcp)

When enabling the opt-in Enterprise Governed GitHub MCP Server (integrations.scion.github_mcp.enabled = true, layer-5 unit layer-5-workloads/mcps/github-mcp; see 6.3 Governed GitHub MCP Server), credential provisioning is manual today: Terraform never stores or manages the GitHub App private key material, and the non-secret App IDs stay in your user-local environment file outside the repository.

  1. Generate and safeguard the GitHub App private key (.pem) outside the repository: Download the private key from your GitHub App settings page (you can reuse the least-privilege GitHub App from section 5.5) and move it immediately out of any repository or workspace folder into ~/.config/esmeralda/ with strict permissions:
    mv /path/to/downloaded-key.pem ~/.config/esmeralda/github-mcp-app-private-key.pem
    chmod 600 ~/.config/esmeralda/github-mcp-app-private-key.pem
    
    Confirm no .pem file remains in your workspace or git checkout.
  2. Upload the private key to Secret Manager in the mcps project (<mcps-project-id>):
    gcloud secrets create github-mcp-app-private-key \
      --project=<mcps-project-id> \
      --replication-policy=automatic
    gcloud secrets versions add github-mcp-app-private-key \
      --project=<mcps-project-id> \
      --data-file=~/.config/esmeralda/github-mcp-app-private-key.pem
    
    The Terraform module (infrastructure/modules/5-workloads/mcps/github-mcp) grants roles/secretmanager.secretAccessor on this secret exclusively to sa-github-mcp-<env> and injects it via Cloud Run secret_key_ref.
  3. Record the numeric App ID, Installation ID, and optional fork write repository in ~/.config/esmeralda/env (outside the repository, chmod 600):
    ESMERALDA_GITHUB_MCP_APP_ID=<app-id>
    ESMERALDA_GITHUB_MCP_INSTALLATION_ID=<installation-id>
    ESMERALDA_GITHUB_MCP_WRITE_REPOS=<fork-owner>/<fork-repo>
    
    All three are read by layer-5-workloads/mcps/github-mcp/terragrunt.hcl at plan/apply time and never committed (keeping personal fork names out of env.yaml).
  4. Build and deploy: build the image (uv run --frozen esmeralda build github-mcp), enable integrations.scion.github_mcp in infrastructure/live/<env>/env.yaml with your fork in allowed_write_repos (keeping google/esmeralda in denied_write_repos and allow_pr_approve = false), and apply layer-5-workloads/mcps/github-mcp.

6. Verification

  1. Hub health (on the VM): curl -s http://localhost:8080/healthz reports healthy. Through the proxy URL, the browser shows the IAP login and then the Hub UI. (Verified live.)
  2. Esmeralda still green: uv run --frozen esmeralda verify --env <env> passes. (Verified live after the layer-3, llm-gateway and iap-egress applies.)
  3. A governed model call returns 200. From the VM (or a sandbox), mint an ID token for a team's agent account with the email claim and call llm-gateway:
    gcloud auth print-identity-token \
      --impersonate-service-account=fa-<team-code>-bld-<env>@<factory-project-id>.iam.gserviceaccount.com \
      --audiences=https://apigee.<domain> --include-email
    
    curl -sS --cacert internal-ca.pem -H "Authorization: Bearer <token>" -H "Content-Type: application/json" \
      -d '{"contents":[{"role":"user","parts":[{"text":"Say hi"}]}]}' \
      https://apigee.<domain>/llm/v1beta1/projects/<model-project-id>/locations/global/publishers/google/models/gemini-3.7-flash:generateContent
    
    Expect HTTP 200. Typical failures: 401 (token without email, wrong audience, expired), 403 caller_not_allowed (llm-gateway not applied after layer 3), 403 target_not_allowed (project not in model_projects, location or model not allowed), 429 (role token quota). Then start an agent from the UI and give it a prompt: the sandbox's llm_gateway_proxy.py does the same exchange. (Verified live: HTTP 200 for the builder account, including :streamGenerateContent?alt=sse.)
  4. The usage row is billed to the paying team. In BigQuery, dataset esmeralda_usage_<env> in the governance project:
    SELECT * FROM `<governance-project-id>.esmeralda_usage_<env>.vw_usage_billable`
    WHERE billed_team = '<team>'
    LIMIT 10
    
    Expect billed_team = <team> (for example esmeralda-contributors) with attribution principal_table; the matching raw row in usage_events has workload esmeralda-builder and caller_verified = true. (Verified live, for the builder account.)

7. Debugging agents

When a run stops early or produces nothing, start from the Hub UI, then use the esmeralda factory debugging commands. They are read-only, reuse the --auth of factory status (section 5.4), and need no Scion CLI.

7.1 What the Hub UI shows

Tab Shows Note
Status Phase (running, stopped), activity (working, waiting for input, limits exceeded), exit code, model-call and turn counters The counters come from the agent's hooks. A gemini-cli run can count several model calls per request, and turns stay at 0 until the agent ends its first turn
Logs Cloud Logging entries for the agent Empty unless the hub can query Cloud Logging and the agents export telemetry. esmeralda factory logs reads the agent's agent.log instead, which is always there
Messages Hub notifications: state changes, input needed, limits exceeded These are notifications, not a conversation
Chat Conversations (direct and project groups) Often empty, see below
Terminal (look, attach) The agent's live tmux session Only while the agent runs

Why the chat can be empty. A lead delegates by starting each child with scion start <name> ... "<task>". The task becomes the child's initial prompt (appliedConfig.task), not a chat message, so a run can dispatch several agents without a single chat message. The task given to the lead at creation does not open a direct conversation either. To see who started whom and with what brief, use esmeralda factory conversations, which prints each agent's creator, lineage and initial task.

Look and attach need a running agent. A stopped container has no tmux session. For a stopped agent, read its agent.log (factory logs) or run the post-mortem (factory inspect).

7.2 The commands

uv run --frozen esmeralda factory logs <agent> --env <env> [--tail 200]
uv run --frozen esmeralda factory look <agent> --env <env> [--lines 100]
uv run --frozen esmeralda factory conversations [<agent>] --env <env> [--team <team>] [--full]
uv run --frozen esmeralda factory inspect <agent> --env <env> [--team <team>] [--no-workspace]
Command What it shows Works on a stopped agent
logs The agent's agent.log through the hub (hub → broker), the same file scion logs reads: provisioning, the model and tool events from the hooks, status changes and the exit reason Yes
look The agent's current terminal (scion look); for a suspended agent, the screen the hub saved No: prints why and exits 1
conversations Every agent of the team project with its phase, template, creator, lineage and initial task, the project's conversations and their messages, and your hub notifications Yes
inspect A post-mortem over IAP SSH to the hub VM (below) Yes, it is meant for stopped agents

Reading conversations and notifications with a Scion access token needs its inbox:read scope. Without it, conversations still prints the agents and their tasks, with a warning.

inspect is strictly read-only. It reaches the hub VM with gcloud compute ssh --tunnel-through-iap (VM, zone and project come from the Terraform outputs), lists the agent's container, and uses only docker cp and docker logs: it never starts a container and never runs anything inside one. It copies:

  • the gemini-cli session history (the chats/session-*.jsonl files in the agent's gemini-cli home), task.md, session-metrics.json and the container log. The Scion token and harness secrets are never copied;
  • unless --no-workspace, the git state of /workspace: git status, log, stash, the uncommitted diff (new files included) and the diff of commits ahead of origin. Git runs on a throwaway copy on the VM, with heavy caches (.venv, .terraform, ...) left out and the copy's git config replaced, so nothing in the agent's repository can run. The copy streams the whole workspace and can take a minute or two.

The files land in ~/.cache/esmeralda/factory-inspect/<agent>/<UTC time>/ (mode 0700; --out elsewhere, never inside the repository), next to a summary.json. The printed summary has the model responses and tokens, the tool calls by tool, the last actions, any tool call waiting for a shell confirmation or never finished, the exit reason, and the changed files and commits.

(Verified live in dev on two stopped agents: logs, conversations and inspect return their data, and look prints the not-running message.)


8. Teardown

(Not verified: we have not torn down the factory yet.)

Export each run's conversation before you delete its agents (at teardown, and after any run you clean up): deleting an agent drops its messages from the hub, so the plan, the slice status lines and the review verdicts go with it. Download the conversation from the Hub UI (Chat, open the conversation, download), or save the output of uv run --frozen esmeralda factory conversations --env <env> --full where your version of the CLI has that command. Keep the export outside the repository.

  1. Reconcile job, hub and proxy (Terraform, sections 3 & 5.7): while reconcile.enabled and hub.vm.enabled are still true, run terragrunt destroy in infrastructure/live/<env>/layer-5-workloads/factories/scion-reconcile first and then infrastructure/live/<env>/layer-5-workloads/factories/scion-hub (an excluded unit is skipped, so destroy first), then set reconcile.enabled = false and hub.vm.enabled = false. This deletes the Cloud Run job, scheduler, alerts, VM, data disk (and the hub database on it), proxy and its service account.
  2. Terraform: set integrations.enabled = [] in env.yaml, remove policy.factory.enabled (or set it to false) in catalog/environments/<env>.yaml, run uv run --frozen esmeralda catalog resolve --env <env> --write, then plan and apply in reverse order, with the destroy guard's --allow-destroy: iap-egress, gateways/envoy, llm-gateway, layer-3-security, layer-2-networking, layer-1-projects. Layer 1 deletes the factory project (deletion_policy = "DELETE"), which the project then keeps in its 30-day pending-deletion state.

9. Known gaps and what will be automated

Gap today Planned
runtime = "gke" standalone Hub mode is not wired yet Phase 3A wires integrations.scion.gke.enabled = true (layer-5-workloads/factories/scion-gke + layer-5-workloads/factories/scion-gke-k8s) for an in-cluster GKE runtime broker coexisting with the Hub VM (runtime = "vm"); full Hub-on-GKE cutover is Stage 2
The harness-config record on the hub still names the local tag; the VM re-tags the Artifact Registry digest (plus the CA layer) under it Point the hub's gemini-cli harness-config straight at the digest once esmeralda factory sync owns harness-configs
Hub server settings, experiments, project creation and harness config are clicked in the UI, and a hub restart resets the harness config (team projects themselves are synced by esmeralda factory sync) Extend esmeralda factory sync to own them declaratively and re-apply after restarts
esmeralda factory reaches the hub through an IAP SSH tunnel with a Scion token, which cannot register GCP service accounts Allow an IAP programmatic OAuth client on the hub proxy (Terraform) so --auth iap acts as the signed-in admin with no Scion token
GitHub webhooks can't reach a hub behind IAP A dedicated webhook ingress that accepts only signed POST /api/v1/webhooks/github
The factory reaches models only through Apigee llm-gateway A path for environments without Apigee

Next: back to 6.1 Governed Agent Factory, or continue to 7.1 Make Targets.