6.1 Governed Agent Factory (Scion Integration)¶
Running autonomous coding agents against an enterprise repository introduces the same production governance questions as customer-facing AI agents: which identity is calling the model, how many tokens can each role spend, how do agents reach internal MCP servers without static keys, and how do humans gate live deployments?
Esmeralda integrates with Scion to form a Governed Agent Factory. Rather than building a second governance stack for developer-facing coding agents, Scion agents reuse Esmeralda's existing Apigee llm-gateway, Envoy-for-MCP adapter, Layer 3 IAM identities, Service Catalog, and BigQuery esmeralda.usage FinOps views.
1. Two-Plane Governance Model¶
The integration separates responsibilities into two clean planes:
| Plane | Owned By | Responsibilities |
|---|---|---|
| Execution & Workspace Plane | Scion (integrations/scion/) |
Isolated per-agent containers, git clone-per-agent workspaces, fail-closed GCP identity injection (assign mode, Block default), least-privilege GitHub App event/schedule triggers, and human-in-the-loop Approved Commands (hub.command_requests) over Conduit. |
| Identity, Gateway & FinOps Plane | Esmeralda (catalog/teams/<team>/factory/, layer-3-security, layer-4-governance, layer-5-workloads) |
One GCP service account per factory agent (factory_identities.tf), declared by the agent's owner team in the catalog; model access through the Apigee llm-gateway; internal MCP routing via Envoy (token = "none") with CallerGuard; and esmeralda.usage chargeback in BigQuery under each agent's owner team. |
flowchart LR
subgraph Scion["1. Execution & Workspace Plane (Scion Container)"]
Agent["Gemini CLI Agent<br/>(lead / architect / builder / reviewer / ...)"]
LLMProxy["llm_gateway_proxy.py<br/>(127.0.0.1:8787)<br/>OIDC ID token swap"]
MCPProxy["mcp_oidc_proxy.py<br/>(127.0.0.1:8788)<br/>Per-service OIDC ID token"]
Meta["Scion / GKE Metadata Server<br/>(the agent's own SA)"]
end
subgraph Gateways["2. Esmeralda Gateway Plane (Layer 5)"]
EP["Internal HTTPS Entry Point<br/>(*.esmeralda.internal)"]
Apigee["Apigee llm-gateway<br/>(VerifyJWT • LLMTokenQuota per caller)"]
Envoy["Envoy Gateway Adapter<br/>(token = none • usage.lua)"]
end
subgraph Backends["3. Models, Tools & FinOps (Layers 4 & 5)"]
Vertex["Vertex AI<br/>(Gemini 3.7 Flash)"]
MCP["Cloud Run MCP Servers<br/>(IAM Invoker + CallerGuard)"]
BQ[("BigQuery FinOps Hub<br/>esmeralda.usage -> vw_monthly_agent_chargeback")]
end
Agent -->|"GOOGLE_VERTEX_BASE_URL"| LLMProxy
Agent -->|"mcpServers httpUrl"| MCPProxy
LLMProxy -.->|"Mint OIDC token"| Meta
MCPProxy -.->|"Mint OIDC token"| Meta
LLMProxy -->|"HTTPS + OIDC Bearer"| EP
MCPProxy -->|"HTTPS + OIDC Bearer"| EP
EP -->|"apigee.esmeralda.internal/llm"| Apigee
EP -->|"<svc>.esmeralda.internal/mcp"| Envoy
Apigee -->|"Authorized + metered"| Vertex
Envoy -->|"Original agent SA token"| MCP
Apigee -.->|"esmeralda.usage"| BQ
Envoy -.->|"esmeralda.usage"| BQ
MCP -.->|"esmeralda.usage"| BQ
2. Team-Owned Factory Agents, Identities & FinOps¶
Every factory agent is declared by the team that maintains it in the catalog, next to that team's other entries, and implemented under apps/factory/agents/. "Factory" is only the name of the integration, not a team. Two teams matter for every run:
- Owner team: maintains the agent (prompts, playbook, quota). It comes from the agent's catalog declaration.
- Paying team: the team that runs the factory pays for the whole run tree. Each team that uses the factory has its own Scion project (the billing boundary), declared in its
team.yaml(factory: { scion_project: <slug>, short: <team code> }), and Layer 3 (factory_identities.tf) creates one GCP service account per (paying team × agent):fa-<team code>-<agent code>-<env>. Itsprincipal_teamsrow maps it to the paying team (and its default cost centre), and thellm-gatewayrecords the agent name as the workload.esmeralda factory syncpublishes, on each team project, the agent → service account mapping (FACTORY_SA_<AGENT>) andESMERALDA_BILLED_TEAM/ESMERALDA_BILLED_COST_CENTER, so the lead started in a team's project dispatches every child with that team's accounts and nobody picks service accounts by hand. Each agent lists which teams may pay for it (allowed_payers, default: every internal team); only those get an account for it. The gateways check each run's declared payer and run tree against this (Run origin and chargeback); rejecting runs without a valid payer is a switch (enforce), off until the rollout ends.
Reports join both: the payer from the service account (principal_teams) and the owner from the agent name (factory_agent_owners, a table the iap-egress unit loads next to principal_teams in the governance dataset: agent, owner_team, owner_cost_center). The view vw_factory_hourly_cost does that join per hour: calls, tokens and estimated cost by paying team, agent, owner team and model, with an optional hourly budget alert per paying team (2.3 FinOps).
The sample catalog declares one paying team, esmeralda-contributors (code ec, project esmeralda-contributors: the maintainers using the factory on Esmeralda itself), so dev has fa-ec-lead-dev, fa-ec-arch-dev, and so on. A business team would declare its own project the same way (for example cx with scion_project: cx-factory, short: cx, giving fa-cx-*). The owner teams below are fictional, to show the multi-team model.
Agent (apps/factory/agents/<agent>/) |
Owner team | Agent code | Declared quota | Scope |
|---|---|---|---|---|
esmeralda-lead |
ai-coe |
lead |
200,000 TPM / 90 RPM | Reads the issue, plans and splits it, dispatches the other agents, reports |
esmeralda-architect |
architecture |
arch |
80,000 TPM / 40 RPM | Solution design and checks against the Esmeralda contracts (catalog, gateways, layers); drafts only |
esmeralda-builder |
platform |
bld |
120,000 TPM / 60 RPM | Implements one slice in its clone of the fork, runs offline checks, opens the PR on the fork |
esmeralda-mcp-builder |
ai-coe |
mcpbld |
120,000 TPM / 60 RPM | Builds MCP servers the Garimpo way (apps/services/_template, catalog entry, layer-5 unit, gateway routing) |
esmeralda-reviewer |
platform |
rev |
60,000 TPM / 30 RPM | Reviews a PR against its issue and the standards, checks the tests were red first, posts one review comment on the fork PR; never approves or merges |
esmeralda-security-reviewer |
security |
secrev |
60,000 TPM / 30 RPM | Least privilege, threat model, public-repository hygiene and the sensitive-content guard, for PRs touching IAM, gateways or data |
esmeralda-dev-tester |
platform |
devtst |
80,000 TPM / 40 RPM | Live dev tests through human-approved Scion Approved Commands; holds no credentials |
A declaration looks like this (catalog/teams/<owner team>/factory/<agent>.yaml):
schema: esmeralda.catalog
schema_version: 1
kind: factory_agent
name: esmeralda-architect
description: Writes the solution design for an issue and checks it against the Esmeralda contracts.
owner_team: architecture
short: arch # agent code: each paying team gets fa-<team code>-arch-<env>
quota: { tokens_per_minute: 80000, requests_per_minute: 40 }
# allowed_payers: [esmeralda-contributors] # optional: default every internal team
runtime:
scion:
template: apps/factory/agents/esmeralda-architect
esmeralda catalog resolve compiles the declarations into catalog/.resolved/<env>.json: factory_agents (owner team and cost centres, code, quota, explicit allowed_payers, template), factory_identities (one entry per <team>/<agent>: paying team, agent, owner team, service account id) and factory_projects (each team project with its billed team, default cost centre and agent → service account id), all empty unless the environment turns the factory on (policy: { factory: { enabled: true } } in catalog/environments/<env>.yaml, which make test-guards keeps equal to "scion" in integrations.enabled). Layer 3, the llm-gateway unit (allowed callers, workload = agent name), the iap-egress unit (principal_teams, factory_agent_owners) and esmeralda factory read that file, so adding an agent is one catalog file plus its template directory, and adding a paying team is one factory block in its team.yaml. Guard tests fail when an agent directory and its declaration don't match, when an owner team doesn't exist, or when a (team × agent) service account id is over 30 characters or not unique. The quotas are declared and compiled; the llm-gateway still applies one token quota per verified caller.
The codes keep every id within GCP's 30-character limit (team code up to 6 characters, agent code up to 8; the resolver checks the full id per environment).
All agents share the esmeralda-rules skill, which enforces public-repository hygiene, uv run --frozen, and verification gates.
Run origin and chargeback¶
A run tree (a lead and every child it starts) is billed to the team that started it, and every usage record says which run it belongs to. The proxies in the agent container add the run origin headers to each upstream call, and the gateways check, record and strip them:
| Header | Usage record field | Root run value | Child run value |
|---|---|---|---|
X-Esmeralda-Billed-Team |
billing.team |
project env ESMERALDA_BILLED_TEAM (factory sync) |
inherited |
X-Esmeralda-Cost-Center |
billing.cost_center |
ESMERALDA_COST_CENTER, else ESMERALDA_BILLED_COST_CENTER (factory sync); absent: the team default |
inherited |
X-Esmeralda-Scion-Project |
run.scion_project |
SCION_PROJECT_ID (the hub project id) |
own (same project) |
X-Esmeralda-Origin |
run.origin |
trigger[:<ESMERALDA_TRIGGER_SOURCE>] when SCION_TRIGGER_ID is set; schedule with ESMERALDA_ORIGIN=schedule; api when SCION_CREATOR is a service account; cli with ESMERALDA_ORIGIN=cli (esmeralda factory start sets it); else ui |
inherited |
X-Esmeralda-Initiated-By |
run.initiated_by |
SCION_CREATOR (else trigger:<id> / schedule:<ESMERALDA_SCHEDULE>) |
inherited |
X-Esmeralda-Root-Run |
run.root_run |
SCION_AGENT_ID |
inherited |
X-Esmeralda-Run |
run.run |
SCION_LAUNCH_ID (else SCION_AGENT_ID) |
own |
X-Esmeralda-Parent-Run |
run.parent_run |
— | the parent's SCION_AGENT_ID |
X-Esmeralda-Agent |
run.agent |
template env ESMERALDA_AGENT (each apps/factory/agents/<agent>/scion-agent.yaml) |
own |
X-Esmeralda-Issue |
run.issue |
ESMERALDA_ISSUE (esmeralda factory start --issue sets it) |
inherited |
traceparent |
trace_id |
trace id derived from the run id (run), a new parent span id per call |
own |
A child inherits through one env var, ESMERALDA_ROOT_CONTEXT (base64url JSON of the inherited fields plus parent_run). The parent prints it as a Scion inline agent config and pipes it into scion start, which the lead's playbook does for every child:
python3 /usr/local/bin/llm_gateway_proxy.py --print-child-config | scion start <name> -t <template> ... --config - "<task>"
Values that don't match the usage contract are dropped by the proxy, never sent, and headers the agent sends itself (X-Esmeralda-*, and inside a run traceparent / tracestate) are replaced. Both proxies in the agent container send them, from one shared code block that a guard test keeps identical: the model-call proxy of the harness image (apps/harnesses/scion-gemini-cli/llm_gateway_proxy.py) and the MCP proxy (integrations/scion/mcp/mcp_oidc_proxy.py). Because the trace id comes from the run id, a run's model calls (llm.call at the llm-gateway) and tool calls (gateway.request at Envoy) carry the same trace_id in usage_events.
The payer can't be forged. Everything in the container (env vars, proxies) is under the agent's control, so the gateways never take the payer from a header: billing.team is always the paying team of the verified service account (its catalog principal_teams row; each fa-<team>-<agent>-<env> account belongs to exactly one paying team). The declared values are checked against it, by the Apigee llm-gateway (JS-Validate-Run-Origin, details) for model calls and by Envoy (usage.lua) for MCP calls:
X-Esmeralda-Billed-Teammust equal that team;X-Esmeralda-Cost-Centermust be one of its cost centres;X-Esmeralda-RunorX-Esmeralda-Root-Runmust be present, and every run header well formed (X-Esmeralda-Agentmust also match the calling agent at thellm-gateway);- callers that are not factory service accounts are exempt.
One switch per environment, attribution.run_origin in env.yaml (dev: flag, prd: off), sets what a failed check does in both gateways:
| Mode | Failed check | Usage record |
|---|---|---|
off |
nothing is checked | no billing / run (caller.team is still recorded) |
flag |
the call goes through | billing.status = rejected_would_be, billing.reason (e.g. payer_mismatch) |
enforce |
403 {"error":"run_origin_rejected","reason":...} |
billing.status = rejected |
A call that passes is recorded with billing.status = catalog_checked, its run.* fields and caller.team; at the llm-gateway also workload.team (the agent's owner team) and gen_ai.conversation.id (the run id), so calls group by run. Both gateways strip the run headers before forwarding (Envoy keeps X-Esmeralda-Cost-Center, which the MCP servers' caller guard checks). usage_events exposes the fields as billing_team, billing_cost_center, billing_status, billing_reason, run_origin, run_initiated_by, run_root, run_id, run_parent, run_agent, run_issue and run_scion_project.
Daily reconciliation. The run tree itself is declared, so esmeralda factory reconcile compares a day's records with the hub's own record of the same runs: the agents of each team project (deleted ones included), their creator, labels and immutable ancestry (ancestry[0] is the root user, ancestry[1] the root agent, the last entry the parent):
uv run --frozen esmeralda factory reconcile --env dev # yesterday, live hub + BigQuery
uv run --frozen esmeralda factory reconcile --env dev --day 2026-12-01 --json
uv run --frozen esmeralda factory reconcile --env dev --hub-file agents.json --usage-file runs.json
It reports root_unknown, root_not_a_root, parent_unknown, parent_outside_tree, project_mismatch, payer_mismatch (against the catalog team of the root agent's project), initiator_mismatch (against the root agent's creator), origin_trigger_unlabelled and origin_api_not_a_service, and exits 3 when it finds any. It is read only. It reaches the hub the same way as factory status (--auth) and reads usage_events with your Application Default Credentials; --hub-file / --usage-file take exports instead.
The layer-5 unit factories/scion-reconcile (scion-reconcile, toggled by integrations.scion.reconcile.enabled in env.yaml: on in dev, off in prd) runs this check automatically every day in the governance project as a Cloud Run job triggered by Cloud Scheduler (esmeralda factory reconcile --scheduled, checking the previous UTC day). To reach the IAP-protected hub without a human, a stored key or a Scion token, the job uses --auth sa: its own service account (sa-factory-reconcile-<env>) calls the IAM Credentials API (signJwt on itself only, audience <hub_url>/*) and sends the short-lived JWT in Proxy-Authorization; Cloud Run IAP (roles/iap.httpsResourceAccessor on the hub proxy only) verifies it and forwards a signed X-Goog-IAP-JWT-Assertion to the hub, which provisions the service account email as a user. Granting that user the hub's project-viewer role on each team project is a one-time manual step (see the bootstrap runbook); until it is granted, the job fails loudly instead of flagging every run as root_unknown. Two log-match alert policies in the governance project (wired to layer-4's alert_notification_channels) alert on ESMERALDA_FACTORY_RECONCILE_DISCREPANCIES (logged at WARNING; exit 0 so Cloud Run does not retry a completed check) and on any job or scheduler ERROR (ESMERALDA_FACTORY_RECONCILE_FAILED, exit 2). Move run_origin to enforce after a clean week.
Cost per resolved issue (vw_factory_cost_per_issue). Because children inherit ESMERALDA_ISSUE via ESMERALDA_ROOT_CONTEXT, every model call in a run tree carries run_issue in usage_events. Layer 4 provisions the factory_issue_outcomes table and two FinOps views (2.3 FinOps):
vw_factory_cost_per_issue: joins gateway-meteredusage_events,factory_agent_owners, andfactory_issue_outcomesto compute total spend across all attempts (including failed runs), role split (lead_cost_usd,builder_cost_usd,reviewer_cost_usd), cache hit ratio, attempt count, and resolution status.vw_factory_cost_per_issue_monthly: monthly rollup bybilling_teamandowner_teamwith median, p90, resolution rate, and effective cost per resolved issue.
Sync GitHub issue and PR resolution outcomes manually or on a daily schedule via the optional layer-5 unit factories/scion-outcomes (integrations.scion.outcomes.enabled in env.yaml, default false in dev and prd, reusing the digest-pinned factory-reconcile image with dataset-scoped BigQuery IAM):
uv run --frozen esmeralda factory outcomes --env dev --repo google/esmeralda --dry-run
uv run --frozen esmeralda factory outcomes --env dev --repo google/esmeralda --fork-repo <owner>/esmeralda
Scion telemetry and OTel attribute parity¶
Chargeback vs. observability. The gateways (llm-gateway and Envoy) remain the sole authoritative emitters of billing records (esmeralda.usage in BigQuery). Scion's built-in telemetry pipeline (sciontool forwarding OTLP to Cloud Logging, Cloud Monitoring, and Cloud Trace in the factory project, powering the Hub UI's Logs and Metrics tabs) is for operational observability and debugging only, never billing.
Both runtimes configure identical GCP telemetry defaults in settings.yaml when agent_telemetry is enabled (the default): scion-hub-vm (converge.sh) for VM agents and scion-gke-k8s (broker.tf) for GKE broker-managed agents both enable telemetry.cloud.provider = gcp targeting the factory project (SCION_GCP_PROJECT_ID) while excluding agent.user.prompt so prompts are never exported.
Inside the harness container, apps/harnesses/scion-gemini-cli/entrypoint-wrapper.sh exports validated, non-empty RunContext fields (including fields inherited through ESMERALDA_ROOT_CONTEXT on child runs) into OTEL_RESOURCE_ATTRIBUTES before execing the harness: esmeralda.agent, esmeralda.billed_team, esmeralda.run_id, esmeralda.root_run_id, esmeralda.parent_run_id, esmeralda.origin, and esmeralda.issue. Values are percent-encoded per the OTel specification and merged with any pre-existing OTEL_RESOURCE_ATTRIBUTES. High-cardinality user identifiers (initiated_by), Scion-owned identity keys (scion.*), and keys containing forbidden Cloud Monitoring dimension substrings (such as conversation; esmeralda.run_id already carries the run/conversation id) are intentionally omitted. When SCION_TELEMETRY_CLOUD_PROVIDER=gcp and OTEL_METRICS_EXPORTER is unset, the wrapper also sets OTEL_METRICS_EXPORTER=none so harness-native metrics (whose default Node.js host/process resource dimensions sit outside Scion's Cloud Monitoring allowlist) do not interfere while sciontool continues deriving canonical gen_ai.api.calls and scion.usage.tokens from OTLP log events.
Turning the integration on (integrations in env.yaml)¶
One switch per environment, shaped like gateways.enabled: the integration is on when "scion" is listed in integrations.enabled in infrastructure/live/<env>/env.yaml (prd ships with enabled = []). The scion block keeps the same shape in every environment:
integrations = {
enabled = ["scion"]
scion = {
runtime = "vm" # "vm" (single-node hub) | "gke" (not wired yet: the plan fails)
subnet_cidr = "<factory-subnet-cidr>" # free /24 on the Shared VPC for the factory subnet
hub = {
network_tag = "<hub-vm-tag>" # the Cloud Run IAP proxy reaches the hub VM on tcp:8080
service_account_id = "<hub-sa-account>" # layer 3 creates it; serviceAccountTokenCreator on each agent SA
vm = { # the Terraform-managed hub VM (layer-5 unit factories/scion-hub)
enabled = true
name = "<hub-name>" # VM scion-hub-<hub-name>, proxy scion-hub-<hub-name>-iap-proxy
zone = "<zone>"
machine_type = "e2-standard-4"
boot_disk_gb = 50
data_disk_gb = 200 # /home/scion: hub.db, workspaces (survives a VM replacement)
scion_version = "v0.4.0-preview.5" # pinned release, checked against its SHA256SUMS
scion_sha256 = "<sha256 of scion-linux-amd64.tar.gz>"
harness_image = "scion-gemini-cli" # built by `esmeralda build scion`, deployed by digest
proxy_image = "scion-hub-iap-proxy"
}
}
reconcile = { # daily run reconciliation (layer-5 unit factories/scion-reconcile)
enabled = true # dev: true, prd: false
schedule = "30 6 * * *" # cron (UTC); checks the previous UTC day
}
}
}
With it on, layer 1 creates the factory project (<prefix>-factory-<suffix>), layer 2 attaches it to the Shared VPC (subnet, Cloud Run service agent compute.networkUser, hub firewall rule), layer 3 creates one service account per (paying team × agent) in that project and the hub's own service account (service_account_id, with serviceAccountTokenCreator on each of them, logging/monitoring/trace writer and repository-scoped Artifact Registry reader; no Vertex AI or IAM admin role), the Apigee llm-gateway unit adds the agent accounts to allowed_callers and records each as the workload <agent name>, the iap-egress unit loads their principal_teams rows (paying team) and factory_agent_owners, and, with hub.vm.enabled, the layer-5 unit factories/scion-hub creates the hub VM and its Cloud Run IAP proxy (scion-hub-vm). Because the hub account is a Terraform resource, a fresh environment applies layer-1-projects → layer-2-networking → layer-3-security → llm-gateway → iap-egress → factories/scion-hub in one pass. Who may open the hub through IAP (and its admins) comes from ESMERALDA_FACTORY_HUB_MEMBERS (user:<email>,group:<email>) in the user-local env file, never from the repository. The catalog switch must match (make test-guards fails when scion is enabled without policy: { factory: { enabled: true } } in catalog/environments/<env>.yaml, or the reverse). Then esmeralda factory sync (below) registers and verifies each team's accounts on its Scion project, publishes the agent → service account mapping, and puts the project in Assign mode with the team's lead account as default.
3. Repository Components¶
| Path | What Lives There |
|---|---|
apps/harnesses/scion-gemini-cli/ |
Custom Scion Gemini CLI container image wrapping sciontool init -- with an auto-starting localhost auth-swap proxy (llm_gateway_proxy.py on 127.0.0.1:8787) supporting both GCE/Scion metadata GSA tokens (metadata, default) and unbound GKE SPIFFE Agent Identity tokens (ESMERALDA_ID_TOKEN_MODE=agent-identity), streaming SSE responses through Apigee llm-gateway. Built with the pinned Scion release's image chain by uv run --frozen esmeralda build scion (.cloudbuild/scion-gemini-cli.yaml, .cloudbuild/scion-hub-iap-proxy.yaml, and .cloudbuild/scion-broker.yaml). |
apps/harnesses/scion-broker/ |
Slim non-root (uid 1000) image for the in-cluster Scion Kubernetes runtime broker, built from the checksum-verified pinned Scion release binary (.cloudbuild/scion-broker.yaml, uv run --frozen esmeralda build scion-broker). |
apps/harnesses/scion-hub-tls-proxy/ |
Zero-dependency pure-Go distroless TLS reverse proxy sidecar (:8443 -> 127.0.0.1:8080) for the Phase 3B in-cluster GKE Scion Hub: mounts Layer 3's esmeralda-scion-hub-tls-<env> JSON secret via GKE Secret Manager CSI, atomically reloads rotated certs, preserves HTTP/1.1 SSE/WebSocket upgrades, strips X-Goog-IAP-* headers, and forces X-Forwarded-Proto: https (.cloudbuild/scion-hub-tls-proxy.yaml, uv run --frozen esmeralda build scion-hub-tls-proxy). |
infrastructure/modules/5-workloads/factories/scion-hub-vm/ |
Terraform module for the single-node hub (runtime = "vm"): Shielded VM with no external IP and a separate data disk, checksum-verified pinned Scion release, IAP proxy auth, digest-pinned harness image, and the Cloud Run IAP proxy. Live unit layer-5-workloads/factories/scion-hub. |
infrastructure/modules/5-workloads/factories/scion-reconcile/ |
Terraform module for daily run-origin reconciliation: Cloud Run job (esmeralda factory reconcile --scheduled), Cloud Scheduler trigger, least-privilege reconciler SA (signJwt on itself, IAP access on the hub proxy, read-only BigQuery), and log-match alert policies on layer-4 channels. Live unit layer-5-workloads/factories/scion-reconcile. |
infrastructure/modules/5-workloads/factories/scion-outcomes/ |
Optional Terraform module for daily GitHub issue outcome syncing into BigQuery factory_issue_outcomes (esmeralda factory outcomes --scheduled), reusing the digest-pinned factory-reconcile image with dataset-scoped BigQuery IAM. Live unit layer-5-workloads/factories/scion-outcomes (enabled = false by default). |
apps/jobs/factory-reconcile/ |
Minimal non-root container image packaging the esmeralda CLI for the scheduled reconciliation Cloud Run job. Built by uv run --frozen esmeralda build factory-reconcile (or esmeralda build scion). |
apps/factory/agents/ |
One directory per factory agent (scion-agent.yaml, system-prompt.md, agents.md), each declared by its owner team in catalog/teams/<team>/factory/<agent>.yaml, plus the shared esmeralda-rules skill in _shared/skills/. |
packages/esmeralda/src/esmeralda/ops/factory.py |
esmeralda factory status \| sync \| start: reads the catalog's factory_agents and factory_projects and the hub's Terraform outputs, reports drift per team Scion project, and syncs it idempotently (env vars, billed team, agent → service account mapping, service account registration, Assign mode, the esmeralda-rules skill, one template per agent). Never starts agents, except start (one run). Hub REST client in ops/scion_hub.py. |
integrations/scion/mcp/ |
Zero-dependency Python localhost proxy (mcp_oidc_proxy.py on 127.0.0.1:8788) bridging Gemini CLI Streamable HTTP MCP calls to Esmeralda's Envoy gateway adapter (token = "none") with per-service OIDC ID tokens (ESMERALDA_ID_TOKEN_MODE=metadata for VM GSAs or agent-identity for GKE unbound SPIFFE JWTs, verified fail-closed) and the run origin headers (X-Esmeralda-Billed-Team, X-Esmeralda-Cost-Center, X-Esmeralda-Run, ...)—zero Apigee dependency for internal MCPs. |
integrations/scion/triggers/ |
Least-privilege GitHub App setup guide, declarative event triggers (issue-labeled-builder.yaml, pr-opened-reviewer.yaml), recurring schedule (weekly-docs-auditor.yaml), and offline schema/safety validator (validate_triggers.py). |
integrations/scion/approved-commands/ |
Scion hub.command_requests workflow and declarative command contract (policy.yaml) so esmeralda-dev-tester proposes dev build/apply/verify commands for interactive human approval (never holding dev or prd credentials). |
infrastructure/modules/5-workloads/factories/scion-gke/ |
Terraform module and live unit (layer-5-workloads/factories/scion-gke) provisioning a private GKE Standard cluster on Esmeralda's Shared VPC (RAPID, Dataplane V2, Workload Identity, Fleet), dedicated system and tainted agents node pools (GKE_METADATA), and broker/node GCP IAM + Hub IAP access. |
infrastructure/modules/5-workloads/factories/scion-gke-k8s/ |
Companion Terraform module (hashicorp/kubernetes) and live unit (layer-5-workloads/factories/scion-gke-k8s) declaratively managing namespaces, ResourceQuota/LimitRange, per-(team × agent) KSAs, ConfigMap/esmeralda-internal-ca, the admissionregistration.k8s.io/v1 SPIFFE + CA MutatingAdmissionPolicy, broker RBAC/PVC, and the digest-pinned scion-broker Deployment (zero manual kubectl apply). |
infrastructure/modules/5-workloads/factories/scion-hub-gke/ |
Phase 3B Terraform module and live unit (layer-5-workloads/factories/scion-hub-gke, gated by integrations.scion.hub.gke.enabled) running the standalone Scion Hub Deployment inside ns scion-system (pvc SQLite default in dev, cloudsql Postgres + GCS + Secret Manager in prd), fronted by a GKE Internal LoadBalancer Service and Esmeralda's Cloud Run IAP proxy, plus an optional isolated POST /api/v1/webhooks/github HTTPRoute. |
apps/mcps/github-mcp/ |
Opt-in Enterprise Governed GitHub MCP server (.cloudbuild/github-mcp.yaml, infrastructure/modules/5-workloads/mcps/github-mcp/, live unit layer-5-workloads/mcps/github-mcp): 9 least-privilege GitHub REST tools, fail-closed repo allowlists, ALLOW_PR_APPROVE=false default, server-side GitHub App installation token minting from Secret Manager, and CallerGuard + per-caller policies (see 6.3 Governed GitHub MCP Server). |
4. Live Single-Node VM Setup¶
For a single-node Scion Hub (v0.4.0-preview.5+) running inside or connected to your Esmeralda VPC:
- Build the Esmeralda harness, shell, and IAP proxy images in Cloud Build (
uv run --frozen esmeralda build scion, which runs.cloudbuild/scion-gemini-cli.yamland.cloudbuild/scion-hub-iap-proxy.yaml) and deploy the hub with Terraform (esmeralda apply layer-5-workloads/factories/scion-hub --env <env>). The VM's startup script pulls the harness and shell images by digest, adds the internal Root CA, and tagslocalhost/scion/scion-gemini-cli:{latest,<scion-version>}andlocalhost/scion/scion-base:{latest,<scion-version>}automatically. - Configure fail-closed Hub defaults in the Scion Web UI (full steps in
integrations/scion/README.md):- Set Default GCP Identity Mode to
Block(neverPassthrough). - Set Default Harness Config to
gemini-cliand Default Model togemini-3.7-flash. - Create each team's Scion project (the slug in its
team.yamlfactory.scion_project);esmeralda factory statuslists the missing ones.
- Set Default GCP Identity Mode to
- Sync the team projects from the catalog with
esmeralda factory(next section). - Optional — Enable internal MCP tools via Envoy: run
python3 integrations/scion/mcp/mcp_oidc_proxy.pyinside the container and point Gemini CLImcpServersathttp://127.0.0.1:8788/<service>/mcp(seeintegrations/scion/mcp/README.md). - Optional — Enable GitHub App, triggers & Approved Commands:
- GitHub App (short-lived installation tokens): Create a least-privilege GitHub App (Contents RW, Pull requests RW, Issues RW, Metadata RO — zero admin/merge permissions) with Setup URL
https://<your-hub-url>/github-app/setupand generate a.pemprivate key. In Scion Hub Server Config → GitHub App, enter the App ID, paste the Private Key (PEM), set Public Installation URL tohttps://github.com/apps/<your-app-slug>/installations/new, save, delete the local.pem, and restartscion-hubonce so the token minter attaches. Then install the App interactively in GitHub on your target repository (or a personal fork first if your GitHub organization requires admin approval for App installs) — the Setup URL redirects back to Scion Hub, or click Discover from GitHub under Installations. (Note: live webhook triggers behind Cloud Run IAP require a dedicated non-IAP webhook ingress forwarding onlyPOST /api/v1/webhooks/githubwith HMAC-SHA256 verification; seeintegrations/scion/triggers/README.md.) - Approved Commands (
esmeralda-dev-tester): Enablehub.conduit,hub.exec_containers, andhub.command_requests, start a personalshellexecution container (dev-exec, one per human approver — never shared across users), register it under Profile → Agent Executions (scion exec-container set dev-exec), and authenticate inside it withgcloud auth application-default login --no-launch-browser.- Current single-node VM workaround (
v0.4.0-preview.5): Because the Scion web terminal captures tmux pane borders (│) onShift-drag and drops leading characters onCtrl+Vpaste, run the one-timegcloudlogin from a native workstation terminal over IAP SSH (note the trailing-- -tto allocate a PTY fordocker exec -it), and optionally set the ADC quota project:gcloud compute ssh <hub-vm> --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 <hub-vm> --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 <governance-project-id>" - Harness-config restart note (
v0.4.0-preview.5): Restartingscion-hubre-syncs the globalgemini-cliharness-config alias (medium) back togemini-3.6-flash; keepmodel: gemini-3.7-flashexplicitly set in agent templates (scion-agent.yaml) and update Hub Resources → Harness Configs →gemini-cli→config.yamlif agents launch without an explicit template model. - See
integrations/scion/approved-commands/README.mdfor the full policy and workflow.
- Current single-node VM workaround (
- GitHub App (short-lived installation tokens): Create a least-privilege GitHub App (Contents RW, Pull requests RW, Issues RW, Metadata RO — zero admin/merge permissions) with Setup URL
For every step from an empty environment to a working hub (apply order, Terraform VM and IAP proxy setup, Hub UI steps, verification and teardown), follow the 6.2 Scion-on-VM Bootstrap Runbook.
Sync the hub from the catalog¶
esmeralda factory keeps every team Scion project equal to the catalog. It reads the hub URL, VM and factory project from the Terraform outputs (factories/scion-hub, layer-1-projects), never from the repository:
uv run --frozen esmeralda factory bootstrap --env dev --auth sa --dry-run
uv run --frozen esmeralda factory bootstrap --env dev --auth sa [--broker scion-gke-broker --set-default-broker]
uv run --frozen esmeralda factory status --env dev --auth sa
uv run --frozen esmeralda factory sync --env dev --auth sa --dry-run
uv run --frozen esmeralda factory sync --env dev --auth sa
bootstrapruns an idempotent, zero-touch hub setup from the catalog and Terraform outputs (recommended with--auth sa, which uses the hub's zero-GCP-privilege headless admin SAfactory_admin_sa_emailviasignJwt— no browser, no OAuth client secret, no Scion token, and no manual UI clicks): disablesdefault_scratchpadwhen GKE is enabled (or--no-default-scratchpad), creates missing team projects, registers and verifies every compiled(team × agent)GCP service account, grants least-privilegeproject-viewertosa-factory-reconcile-<env>(printing the one-linegcloud run jobs executecommand if not auto-provisioned yet), attaches an online--broker(and sets it as default with--set-default-broker), invokesfactory sync, and prints the direct UI link for any project still needing its one-step external GitHub App OAuth binding.statusshows hub health, who you are on the hub, and per team project the drift: the project missing, env vars missing or outdated, service accounts not registered or not verified, settings, theesmeralda-rulesskill not published or not auto-injected, templates missing or outdated (file by file), or a storedGITHUB_TOKENsecret. Items marked[manual]need the hub UI. Exit3when anything drifts.syncfixes the rest, per project: the model gateway env vars (GOOGLE_GENAI_USE_VERTEXAI,GOOGLE_VERTEX_BASE_URL,GOOGLE_CLOUD_PROJECT= the layer-1 CX agents project,GOOGLE_CLOUD_LOCATION=global,NODE_EXTRA_CA_CERTS),ESMERALDA_BILLED_TEAM/ESMERALDA_BILLED_COST_CENTER,FACTORY_SA_<AGENT>(that team's account for each agent), registration and verification of those accounts, Assign mode with the team's lead account as default anddefaultHarnessConfig=gemini-cli, the skill (published as--skill-version, default1.2.0, and auto-injected) and one template per agent (tests/stays in the repository). It is idempotent, never starts agents, and--team <team>limits it to one team.--dry-run --offlineprints the desired state without contacting the hub.startstarts one run in a team's project as that team's service account for the agent, labelled with the team, agent and issue, and prints its link:uv run --frozen esmeralda factory start --env dev --auth sa --team esmeralda-contributors --agent esmeralda-lead --issue 123(the lead gets agent rolefull, so it can dispatch children; use--auth saor--auth iapso Scion authenticates an interactive web-session admin rather than a UAT, which cannot holdproject.secret_read; add--dry-runto see the request first).
How the CLI reaches the IAP-protected hub (--auth, default auto):
| Mode | Hub identity | Needs (user-local env file ~/.config/esmeralda/env, never the repository) |
|---|---|---|
sa |
headless admin or job service account, through IAP via Proxy-Authorization (no browser, no OAuth client secret, no Scion token, no key; full admin & role=full) |
Automatically resolves factory_admin_sa_email from factories/scion-hub Terraform outputs (or override via --sa / ESMERALDA_FACTORY_HUB_SA). Signs a short-lived JWT via IAM Credentials signJwt (aud = <hub_url>/*) using your workstation ADC (granted serviceAccountTokenCreator via iap_members) or self-sign in CI/Cloud Run. Also used by factory reconcile --scheduled |
tunnel |
the user who created the Scion token | ESMERALDA_SCION_HUB_TOKEN: a Scion User Access Token (create it in the hub UI). The CLI opens an SSH port forward through IAP to the VM's 127.0.0.1:8080 (gcloud compute ssh --tunnel-through-iap), so you need IAP TCP forwarding and OS Login on the VM |
iap |
you (or impersonated SA), through IAP as an interactive web session (no Scion token; full admin & role=full) |
Sent in Proxy-Authorization: Bearer <id_token> (never Authorization). For human operators: Desktop OAuth PKCE via ESMERALDA_FACTORY_HUB_OAUTH_CLIENT_ID / _SECRET (caches refresh token in ~/.config/esmeralda/ mode 0600). For service accounts (or --impersonate-sa / ESMERALDA_FACTORY_IAP_IMPERSONATE_SA): gcloud auth print-identity-token with --iap-audience / ESMERALDA_FACTORY_IAP_CLIENT_ID / ESMERALDA_FACTORY_BROKER_IAP_CLIENT_ID |
token |
the token's user | ESMERALDA_SCION_HUB_TOKEN and --hub-url for a hub reachable without IAP (for example on the VM itself) |
auto picks iap when its client is configured, else tunnel, else sa. A Scion token cannot register GCP service accounts (the hub keeps that for interactive admin sessions): with tunnel or token, sync reports those items as failed with the UI path (Project Settings → GCP Service Accounts), and they sync on the next run once registered. Tokens are never printed.
Issue-driven loop (upstream issue → fork PR)¶
Once the GitHub App is installed on your fork and bound to a Scion project created from that fork, a human can run the first end-to-end loop by hand from the Hub UI, with no webhooks or schedules:
- Pick an issue on the public upstream repository (
ESMERALDA_UPSTREAM_REPO, defaultgoogle/esmeraldain the templates). - Start
esmeralda-builderfor a small issue (task:Implement upstream issue #<N> ...) oresmeralda-leadfor a bigger one. The builder reads the issue read-only, implements it in its clone of the fork, runs the offline checks, pushesscion/<agent>-<N>to the fork with the short-lived GitHub App installation token, and opens a PR on the fork againstmainthat links the upstream issue. The lead plans the issue (callingesmeralda-architectfirst for design-heavy issues) and starts one child per slice withscion start -t <agent> --service-account "$FACTORY_SA_<AGENT>" --role baselinefrom inside its container, addingesmeralda-security-reviewerfor PRs touching IAM, gateways or data andesmeralda-mcp-builderfor MCP servers; this needs the lead to run with agent rolefull(Scionv0.4.0-preview.5, no experiment flag), otherwise it prints ready-to-paste tasks instead. - Optionally start
esmeralda-revieweron the fork PR. It re-runs the acceptance tests againstmain, blocks a PR whose tests aren't proven red first, and posts its structured review as one comment on the fork PR and in the run's conversation (it never approves or merges). - Merging on the fork and opening the upstream PR stay human steps. Each agent's model usage shows up in BigQuery billed to the team whose project ran it (
vw_usage_billable.billed_team, workload = agent name), because each agent runs as that team's own service account for it; joinfactory_agent_ownerson the agent name for the owner team.
How the lead keeps the loop cheap and visible:
- Slices follow the issue's real asks. It reads the body and every comment, makes one slice per concrete deliverable, and writes acceptance tests that fail on current
main; a slice whose acceptance already passes is never dispatched. Each child'sscion starttask names the deliverable, the files it owns, the acceptance tests and the "do not" rules. - Red first. Builders write the acceptance tests before the change, push them alone as their first commit, and show them failing on the unmodified code (in a status line and the PR body); the reviewer reproduces that against
main. - No polling. After dispatching it signals
sciontool status blockedand ends its turn; the hub wakes it with each child's notifications (input needed, completed, limits exceeded). It never loops onscion look/scion list. - Checked approvals. gemini-cli asks to confirm shell commands that reuse arguments from earlier tool output, even in yolo mode. The lead reads the exact command and approves only read-only or in-workspace toolchain commands; anything touching credentials, pushing elsewhere than the fork branch or reaching other hosts goes to the human.
- Status in the chat. The plan, each slice's status and the final report go to one hub conversation, which is what the hub UI shows. Agents post inline (
scion message conv:<id> '<text>'), never through a heredoc or a/tmpfile: gemini-cli's untrusted-flag check splits a heredoc into words and can stall the agent on a confirmation prompt. - git push works on the first try. gemini-cli runs shell commands with an empty
credential.helperappended to the git config, which wipes any helper in~/.gitconfig; the harness image's entrypoint hands git Scion'ssciontool credential-helperforgithub.comthroughGIT_CONFIG_PARAMETERS, which survives it and serves the refreshed GitHub App token. No token is stored in the image. - Run limits in each
scion-agent.yaml:max_turns: 0(off: a factory agent works through one long task turn),max_durationas the real bound (lead 3h, builders 60m, reviewers and architect 45m, dev tester 2h), andmax_model_calls(lead 600, builders 400, reviewers and architect 250, dev tester 150). The model-call counts are inflated about 2.5× today, becausesciontoolcounts everyAfterModelhook event and gemini-cli sends several per request. Builders don't install toolchains (they are in the harness image), run the narrowest tests first and push a WIP commit early, so partial work survives a limit stop.
The Hub UI steps (project creation, installation binding, per-agent service accounts, agent roles) and ready-made task texts are in integrations/scion/README.md.
5. GKE Standard Runtime (Phase 3A) & FinOps Parity¶
For multi-tenant execution on Kubernetes, infrastructure/modules/5-workloads/factories/scion-gke/ (layer-5-workloads/factories/scion-gke) and infrastructure/modules/5-workloads/factories/scion-gke-k8s/ (layer-5-workloads/factories/scion-gke-k8s, both gated by integrations.scion.gke.enabled = true) run an in-cluster Scion Kubernetes runtime broker on a private GKE Standard cluster attached to Esmeralda's Shared VPC—coexisting with the Hub VM in Stage 1, with zero manual kubectl apply steps and sharing the same FinOps chargeback model as Vertex AI Agent Engine:
- Private GKE Standard (
google_container_cluster.scion):RAPIDrelease channel (min_master_version >= 1.37.2-gke.1042000), private nodes (enable_private_nodes = true, zero external node IPs), Shielded COS nodes, Dataplane V2 (ADVANCED_DATAPATH), Workload Identity Federation, Fleet membership, Kubernetes Gateway API, and Secret Manager CSI provider. Configurable per environment inenv.yaml(lean zonalus-central1-cwith1–2× e2-standard-2system pool and0–2× e2-standard-4tainted agent pool indev; regional HA defaults inprd). - Per-
(team × agent)SPIFFE Agent Identity (I1) with GSA fallback (I2): Layer 3 derives deterministicprincipal://strings per(paying team × agent)KSA (fa-<team>-<agent>-<env>inns scion-agents), grants them write-only factory telemetry roles, wires them into Apigeellm-gateway(allowed_callers,caller_workloads,caller_teams), wires both VM GSAs and GKE SPIFFE principals into Envoy (layer-5-workloads/gateways/envoy:roles/run.invokerwhen Envoy serves MCP hosts only, pluscaller_teamsforusage.luarun-origin checks while forwarding the caller's own ID token unchanged so upstream Cloud Run MCP IAM andCallerGuardfail closed with403for uncatalogued callers), and publishesprincipal_teamsrows viaiap-egress. Managed declaratively byscion-gke-k8s, anadmissionregistration.k8s.io/v1MutatingAdmissionPolicystampsiam.gke.io/identity,iam.gke.io/spiffe-identity-type: agent-identity,ESMERALDA_ID_TOKEN_MODE=agent-identity,ESMERALDA_CA_CERT, and mounts the read-onlyesmeralda-internal-caConfigMap onto every managedfa-*Pod so bothllm_gateway_proxy.pyandmcp_oidc_proxy.pyfetch unbound SPIFFE ID tokens fail-closed. - In-Cluster Scion Runtime Broker (
ns scion-system): Non-root digest-pinnedscion-brokerimage (.cloudbuild/scion-broker.yaml,uv run --frozen esmeralda build scion-broker) managed byscion-gke-k8swithstrategy: Recreate, least-privilege namespaced RBAC onscion-agents, persistent/home/scion/.scionPVC, loopback-only broker API (127.0.0.1:9800), and outbound HTTPS WebSocket transport to the Hub VM's Cloud Run IAP proxy (SCION_TRANSPORT_MODE=iap,roles/iap.httpsResourceAccessorforsa-scion-gke-brk-<env>, andgoogle_iap_settingsprogrammatic_clientsbound toESMERALDA_FACTORY_BROKER_IAP_CLIENT_ID). - Namespace Quotas & Phase 3C Hook: Configurable
ResourceQuota(max_pods = 8default indev,40inprd),LimitRange, andPriorityClassbound compute spend. Dedicated Secure Web Proxy (SWP), ambient networking, Private CA, and Agent Gateway egress enforcement are deferred to Phase 3C so Phase 3A keeps standard Shared VPC Cloud NAT egress without fixed SWP cost.
Automated End-to-End Factory Verification¶
esmeralda verify --scenario factory runs a self-cleaning end-to-end smoke check against the live Scion Hub, Apigee llm-gateway, and BigQuery usage_events:
uv run --frozen esmeralda verify --env dev --scenario factory --runtime vm
uv run --frozen esmeralda verify --env dev --scenario factory --runtime gke
The command verifies Hub health and target broker availability (--runtime auto|vm|gke), starts an ephemeral esmeralda-builder smoke agent (agentRole=baseline, no file edits or git pushes), polls completion, asserts the resulting usage_events row (http_status_code = 200, caller_verified = true, expected billing_team, workload_name = esmeralda-builder, and either the VM GSA or GKE SPIFFE principal://.../ns/scion-agents/sa/fa-... identity), and always deletes the ephemeral agent on exit unless --keep-agent is passed.
Scion Hub inside GKE (Phase 3B) & Lossless hub.db Cutover¶
Once the GKE runtime broker is proven in Stage 1, infrastructure/modules/5-workloads/factories/scion-hub-gke/ (layer-5-workloads/factories/scion-hub-gke, opt-in via integrations.scion.hub.gke.enabled = true) consolidates the Scion Hub inside ns scion-system and retires the standalone Hub VM (factories/scion-hub):
- Standalone Least-Privilege Hub (
ns scion-system): Reuses the digest-pinned non-root (uid 1000)scion-brokerimage (server start --foreground --hosted --enable-hub --enable-web --web-port 8080 --host 0.0.0.0 --global) without an in-process broker, so the Hub Pod holds zero Kubernetes RBAC onscion-agentsand disablesautomountServiceAccountToken. Workload Identity bindsServiceAccount/scion-hubto Layer 3'sfactory_hub_sa_email. - In-Cluster TLS Sidecar (
:8443 -> 127.0.0.1:8080) & Dataplane V2NetworkPolicy: Scionv0.4.0-preview.5has no native TLS listener on:8080and rejects plaintext non-loopback URLs across Hub (requireConfidentialArrival, HTTP 403transport_not_confidentialwith cleartext join-token revocation), Broker (CheckHubTransport), and Kubernetes agent start (checkAgentHubEndpoint). When Layer 3'sfactory_hub_tls_secret_idis wired, the Hub Pod runs the digest-pinned pure-Go distroless sidecarscion-hub-tls-proxymountingesmeralda-scion-hub-tls-<env>(SANs includescion-hub.<internal_domain>,scion-hub.scion-system.svc, andscion-hub.scion-system.svc.cluster.local) strictly insidetls-proxyvia GKE's managed Secret Manager CSI add-on (secrets-store-gke.csi.k8s.io,provider: gke, zero native Kubernetes Secrets). It atomically reloads rotated certs, strips allX-Goog-IAP-*headers, preserves HTTP/1.1 WebSocket/SSE upgrades, forcesX-Forwarded-Proto: https(with127.0.0.1/32and::1/128appended toserver.trusted_proxies; nevergke.pods_cidr), and exposeshttps://scion-hub.scion-system.svc.cluster.local:8443(internal_hub_urlandserver.hub.agent_endpoint).NetworkPolicy/scion-hub-ingressrestricts:8443todeploy/scion-brokerandns scion-agents, and locks plaintext:8080(the IAP assertion path) strictly to the factory subnet CIDR (iap_proxy_source_cidrs), blocking all direct Pod-to-:8080access. - IAP Front Door, Zero-Click Headless Admin SA & Optional HMAC Webhook Route: A static internal IP on the Shared VPC factory subnet backs
Service/scion-hub-ilb(networking.gke.io/load-balancer-type: "Internal"), fronted by Esmeralda's digest-pinned Cloud Run IAP proxy (iap_enabled = true,roles/run.invokergranted exclusively to the IAP service agent) for automatic*.run.appTLS and deterministic plan-timeiap_audience. It also provisions a dedicated zero-GCP-privilege headless admin SA (scion-hub-<name>-admin, exported asfactory_admin_sa_email,roles/iap.httpsResourceAccessoron the proxy only,roles/iam.serviceAccountTokenCreatorstrictly foriap_members+ self-sign, included inserver.hub.admin_emails) for 0-clickesmeralda factory --auth saparity withfactories/scion-hub. Whenhub.gke.enabled = trueandhub.vm.enabled = false,esmeralda factoryselectsfactories/scion-hub-gkeoutputs automatically. Settingwebhook_gatewayoptionally attaches a Gateway APIHTTPRoutematching onlyPOST /api/v1/webhooks/github(Exactpath match, HMAC-SHA256 verified by the Hub). - Persistence (
storage_mode):devdefaults to"pvc"(SQLite on a10Gistandard-rwopd-balancedPVC withstrategy: Recreateandreplicas = 1);prddefaults to"cloudsql"(Cloud SQL for PostgreSQL via digest-pinned Cloud SQL Auth Proxy native sidecar with--auto-iam-authn+ GCS blob storage + Secret Manager, zero DB passwords). - Lossless VM → GKE
hub.dbCutover (pvcmode):- Build
scion-hub-tls-proxy(uv run --frozen esmeralda build scion-hub-tls-proxy), applylayer-3-security(adds in-clusterscion-hub.scion-system.svc/.svc.cluster.localSANs withcreate_before_destroy), enableintegrations.scion.hub.gke.enabled = true, and applylayer-5-workloads/factories/scion-hub-gke(coexists safely alongsidefactories/scion-hubwith distinct proxy and ILB names). - Copy
SCION_SERVER_SESSION_SECRETfrom/home/scion/.scion/hub.envon the VM intoSecret/scion-hub-sessioninns scion-systemso existing sessions and signing keys carry over. - Stop
scion-hub.serviceon the VM and take a consistent snapshot:sqlite3 /home/scion/.scion/hub.db ".backup /tmp/hub-cutover.db". - Scale
deploy/scion-hubto0, copyhub-cutover.dbto/home/scion/.scion/hub.dbalong withhub-id,workspace-storage/, andattachments/onpvc/scion-hub-state(owner1000:1000,hub.db/hub-idmode0600, clearing stale-wal/-shmso hub-scoped secrets and template blobs stay intact), and scaledeploy/scion-hubback to1. - Verify
/readyz, IAP login on the newhub_url, headlessesmeralda factory status --env <env> --auth sa, and TLS onhttps://scion-hub.scion-system.svc.cluster.local:8443; re-registerdeploy/scion-brokeragainstinternal_hub_url, then setintegrations.scion.hub.vm.enabled = false(re-applyfactories/scion-gke-k8sto switchhub_endpointautomatically) and destroylayer-5-workloads/factories/scion-hub.
- Build
6. Offline Validation¶
All Scion integration components ship with offline unit tests that require no live Scion Hub or GCP credentials:
go test -C apps/harnesses/scion-hub-tls-proxy -race ./...
uv run --frozen pytest apps/harnesses/scion-gemini-cli/test_llm_gateway_proxy.py
uv run --frozen pytest integrations/scion/mcp/test_mcp_oidc_proxy.py
uv run --frozen pytest integrations/scion/triggers/validate_triggers.py
uv run --frozen --package esmeralda --extra dev pytest tests/security/test_factory_identities.py tests/security/test_factory_reconcile_unit.py tests/security/test_factory_gke.py tests/security/test_factory_hub_gke.py tests/security/test_factory_envoy_mcp.py tests/security/test_factory_telemetry.py
uv run --frozen --package esmeralda --extra dev pytest packages/esmeralda/tests/test_factory.py packages/esmeralda/tests/test_factory_bootstrap.py packages/esmeralda/tests/test_verify_factory.py
uv run --frozen --package esmeralda --extra dev pytest packages/esmeralda/tests/test_factory_reconcile.py packages/esmeralda/tests/test_factory_reconcile_scheduled.py packages/esmeralda/tests/test_factory_outcomes.py
uv run --frozen --package esmeralda --extra dev pytest tests/governance/test_factory_hourly_cost.py tests/governance/test_factory_cost_per_issue.py
uv run --frozen --package esmeralda --extra dev pytest tests/apigee/test_run_origin.py tests/gateway/test_run_origin.py
Next: For the generated Make target reference and contribution workflow, continue to 7.1 Make Targets.