# Rails behind the CARLOS edge (Classic/Pro staging PoC) Implementation Plan

> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.

**Goal:** Serve Tito Classic and Tito Pro staging — full process tree, real staging dependencies — at `classic.platform.tito.io` / `pro.platform.tito.io` through the CARLOS edge, from two tofu-provisioned boxes running the Buildkite amd64 images.

**Architecture:** Two x86 EC2 boxes in the `tito-tito-staging` VPC (native SG access to the staging Aurora/Valkey/Memcached), a new default↔staging VPC peering with `/32` routes for just the two box IPs (the default VPC already routes all of `10.0.0.0/16` to the *production* peering, so only host routes are safe), docker + systemd units running the k8s images, env from SSM Parameter Store, deploys over SSM RunCommand, and two `carlos add -kind service -addr` routes on the IE edge.

**Tech Stack:** OpenTofu (`platform-infrastructure/tito/`), cloud-init, systemd, docker, AWS SSM, the `carlos` CLI on the IE box.

**Spec:** `docs/superpowers/specs/2026-08-11-rails-behind-carlos-edge-poc-design.md` (this repo).

## Global Constraints

- AWS account `665106592142`, region `eu-west-1`, CLI profile `titogo`; tofu state `s3://carlos-tfstate-665106592142/tito/`.
- **Targeted plans/applies only** in `platform-infrastructure/tito/` — the tree carries drift from open PRs and a full apply would strip live tcp/25 SMTP ingress (recorded in `tito/object-store.tf`'s commit message).
- No SSH anywhere. All box operation via SSM (`aws ssm send-command` / session-manager).
- Images are the Buildkite amd64 builds, **unmodified** — no rebuilds.
- Secrets never in tofu, the repo, or terminal output — SSM Parameter Store `SecureString` only.
- Never set `-hibernate` on the edge routes; the edge registry is `/data/registry.db`, written by `carlos add` run **as user `carlos`** on the IE box.
- Staging only is applied; production tofu is written gated off (`rails_poc_prod_enabled = false`) and NOT applied.
- Both repos use worktree discipline: infra work on a branch in a `platform-infrastructure` worktree; this plan/spec live on branch `rails-behind-edge-poc-spec` in `platform`.

## Facts (preflighted 2026-08-11 — verify only if something disagrees)

| Fact | Value |
|---|---|
| Default VPC (edge lives here) | `vpc-02416de3913753989`, `172.31.0.0/16`, main rtb `rtb-08863e575439a6377` |
| IE edge box | `i-025a0b70f3d93304d`, private IP `172.31.4.137`, SG `carlos-tito-ie` (`module.host_ie.security_group_id`) |
| Staging VPC | `vpc-03be5678d08549203` (`tito-tito-staging`), `10.0.0.0/16`; subnets `10.0.0.0/23`, `10.0.2.0/23`, `10.0.4.0/23`; igw rtb `rtb-041f57e000fb5797e`, main rtb `rtb-0a01ed1a14d1a52ce` |
| Production VPC | `vpc-90dffef5`, also `10.0.0.0/16`; **existing peering** `pcx-056b55b69cbf89143`; default VPC routes `10.0.0.0/16 → pcx-056b…` already |
| Classic staging DB | `tito-classic-mysql-staging-writer.cefg7n9rzaz0.eu-west-1.rds.amazonaws.com` (aurora-**mysql**, 3306) |
| Pro staging DB | `tito-pro-postgres-staging-writer.cefg7n9rzaz0.eu-west-1.rds.amazonaws.com` (aurora-**postgresql**, 5432) |
| Staging caches | `tito-classic-memcached-staging` (11211), `tito-classic-redis-staging-001` (valkey, 6379), `tito-pro-memcached-staging`, `tito-pro-redis-staging-001` |
| Edge env | `PLATFORM_APPS_DOMAIN=platform.tito.io`, `CARLOS_WILDCARD_DOMAINS=go.tito.io` → `classic.`/`pro.platform.tito.io` get per-host HTTP-01 certs automatically once routed |
| DNS | `*.platform.tito.io` A → IE EIP already live (`tito/dns.tf`) |

**CIDR overlap rule:** staging subnets overlap production's `10.0.0.x–10.0.5.x` subnets exactly. The default VPC may only ever get `/32` routes toward staging, at addresses verified to have **no ENI in the production VPC** (that check is Task 1).

---

### Task 1: Discovery — record the execution facts the tofu needs

Read-only. Everything lands in `tito/rails-poc-facts.md` in the infra worktree so later tasks (and the prod apply later) never re-derive it.

**Files:**
- Create: `platform-infrastructure/tito/rails-poc-facts.md`

**Interfaces:**
- Produces: chosen box IPs (`classic_ip`, `pro_ip`), image refs (`classic_image`, `pro_image`), process commands (`WEB_COMMAND`, `WORKER_COMMAND`, `CLOCK_COMMAND` per app), web port + health path per app, staging DB/cache security-group IDs, box subnet ID. Task 2/3/6 consume these verbatim.

- [ ] **Step 1: Create the infra worktree**

```bash
cd ~/github.com/carlosframework/platform-infrastructure
git fetch origin
git worktree add .claude/worktrees/rails-poc -b rails-poc origin/main
cd .claude/worktrees/rails-poc
```

- [ ] **Step 2: Find where Buildkite pushes the Classic/Pro images**

```bash
aws --profile titogo --region eu-west-1 ecr describe-repositories \
  --query 'repositories[].repositoryUri' --output table | grep -i -E 'classic|pro|tito'
```

If nothing matches, the images live outside ECR — ask Paul where Buildkite pushes (and how the boxes should authenticate); record the answer. Record the full image URI and the tag currently deployed to k8s staging for each app.

- [ ] **Step 3: Record each app's process tree from the k8s staging manifests**

Requires kubectl access to the staging cluster (Paul has it; if the session doesn't, ask Paul to paste the output):

```bash
kubectl get deploy -n <staging-namespace> -o jsonpath='{range .items[*]}{.metadata.name}{"  cmd: "}{.spec.template.spec.containers[0].command}{" "}{.spec.template.spec.containers[0].args}{"  port: "}{.spec.template.spec.containers[0].ports}{"\n"}{end}'
```

Record per app: the web command + container port, worker command(s), clock/cron command (if any), and the HTTP health path the k8s probes use (`.livenessProbe.httpGet.path`).

- [ ] **Step 4: Record the staging DB/cache security groups**

```bash
aws --profile titogo --region eu-west-1 rds describe-db-clusters \
  --query 'DBClusters[?contains(DBClusterIdentifier,`staging`)].{id:DBClusterIdentifier,sg:VpcSecurityGroups[].VpcSecurityGroupId}' --output json
aws --profile titogo --region eu-west-1 elasticache describe-cache-clusters \
  --query 'CacheClusters[?contains(CacheClusterId,`staging`)].{id:CacheClusterId,sg:SecurityGroups[].SecurityGroupId}' --output json
```

- [ ] **Step 5: Choose the two box IPs and prove the /32s shadow nothing**

Pick the box subnet: whichever staging subnet is associated with the igw route table `rtb-041f57e000fb5797e` (check `aws ec2 describe-route-tables --route-table-ids rtb-041f57e000fb5797e --query 'RouteTables[].Associations'`). Pick two free IPs high in that subnet's range (e.g. `.200`/`.201` of its last /24), then verify **both** VPCs:

```bash
for ip in <candidate1> <candidate2>; do
  aws --profile titogo --region eu-west-1 ec2 describe-network-interfaces \
    --filters Name=addresses.private-ip-address,Values=$ip \
    --query 'NetworkInterfaces[].{vpc:VpcId,desc:Description}' --output json
done
```

Requirement: no ENI at that address in `vpc-90dffef5` (production — the /32 would shadow it from the default VPC) and none in `vpc-03be5678d08549203` (staging — the IP must be free to assign). Record IPs + the empty query output.

- [ ] **Step 6: Commit the facts file**

```bash
git add tito/rails-poc-facts.md
git commit -m "tito: record rails-poc execution facts (IPs, images, commands, SGs)"
```

---

### Task 2: Networking tofu — peering and host routes

**Files:**
- Create: `platform-infrastructure/tito/rails-poc-network.tf`

**Interfaces:**
- Consumes: `classic_ip`, `pro_ip`, box subnet id from Task 1.
- Produces: `aws_vpc_peering_connection.rails_poc_staging` and `local.rails_poc` locals; Task 3 references both.

- [ ] **Step 1: Write `tito/rails-poc-network.tf`**

```hcl
# 🤖 Rails-behind-the-edge PoC (see platform repo spec 2026-08-11): the
# edge (default VPC) reaches two staging Rails boxes over a peering.
# The default VPC ALREADY routes 10.0.0.0/16 to the PRODUCTION peering
# (pcx-056b55b69cbf89143) and staging shares that CIDR, so only /32
# host routes are safe here — each verified ENI-free in the production
# VPC before choosing (tito/rails-poc-facts.md).

locals {
  rails_poc = {
    default_vpc_id  = "vpc-02416de3913753989"
    staging_vpc_id  = "vpc-03be5678d08549203"
    default_rtb_id  = "rtb-08863e575439a6377"
    staging_rtb_id  = "<igw rtb from Task 1 step 5>"
    box_subnet_id   = "<subnet from Task 1 step 5>"
    edge_private_ip = "172.31.4.137"
    classic_ip      = "<from facts>"
    pro_ip          = "<from facts>"
  }
}

resource "aws_vpc_peering_connection" "rails_poc_staging" {
  vpc_id      = local.rails_poc.default_vpc_id
  peer_vpc_id = local.rails_poc.staging_vpc_id
  auto_accept = true
  tags        = { Name = "carlos-tito-rails-poc-staging" }
}

resource "aws_route" "rails_poc_to_classic" {
  route_table_id            = local.rails_poc.default_rtb_id
  destination_cidr_block    = "${local.rails_poc.classic_ip}/32"
  vpc_peering_connection_id = aws_vpc_peering_connection.rails_poc_staging.id
}

resource "aws_route" "rails_poc_to_pro" {
  route_table_id            = local.rails_poc.default_rtb_id
  destination_cidr_block    = "${local.rails_poc.pro_ip}/32"
  vpc_peering_connection_id = aws_vpc_peering_connection.rails_poc_staging.id
}

# Return path: the box subnet's route table learns the default VPC.
# 172.31.0.0/16 previously fell through to the igw (dropped); no live
# traffic changes meaning.
resource "aws_route" "rails_poc_return" {
  route_table_id            = local.rails_poc.staging_rtb_id
  destination_cidr_block    = "172.31.0.0/16"
  vpc_peering_connection_id = aws_vpc_peering_connection.rails_poc_staging.id
}
```

Replace the three `<…>` values from `rails-poc-facts.md` — they are Task 1 outputs, not decisions.

- [ ] **Step 2: Targeted plan, verify it creates exactly 4 resources**

```bash
tofu -chdir=tito plan \
  -target=aws_vpc_peering_connection.rails_poc_staging \
  -target=aws_route.rails_poc_to_classic \
  -target=aws_route.rails_poc_to_pro \
  -target=aws_route.rails_poc_return
```

Expected: `4 to add, 0 to change, 0 to destroy`. Anything else — stop, do not apply, diagnose.

- [ ] **Step 3: Commit**

```bash
git add tito/rails-poc-network.tf
git commit -m "tito: rails-poc peering + /32 host routes (staging PoC networking)"
```

---

### Task 3: Box tofu — SGs, IAM, AMI, instances, cloud-init

**Files:**
- Create: `platform-infrastructure/tito/rails-poc-boxes.tf`
- Create: `platform-infrastructure/tito/rails-poc-init.sh.tpl`

**Interfaces:**
- Consumes: `local.rails_poc` (Task 2), image URIs + ports + commands (Task 1 facts).
- Produces: `aws_security_group.rails_poc["classic"|"pro"]` (Task 6 references), boxes tagged `carlos-tito-rails-classic-staging` / `carlos-tito-rails-pro-staging` (Tasks 5/8 find them by that tag), output `rails_poc_ips`.

- [ ] **Step 1: Write `tito/rails-poc-boxes.tf`**

```hcl
# svc-pdf pattern scaled up: SSM-only IAM, SG trust, docker via
# cloud-init. x86 because the Buildkite images are amd64 (spec §1) —
# the fleet's shared AMI is arm64, so a separate amd64 data source.

data "aws_ami" "rails_poc_debian_amd64" {
  most_recent = true
  owners      = ["136693071363"] # Debian official
  filter {
    name   = "name"
    values = ["debian-13-amd64-*"]
  }
  filter {
    name   = "architecture"
    values = ["x86_64"]
  }
}

locals {
  rails_poc_apps = {
    classic = { ip = local.rails_poc.classic_ip, port = <classic web port>, image = "<classic image uri>" }
    pro     = { ip = local.rails_poc.pro_ip, port = <pro web port>, image = "<pro image uri>" }
  }
}

resource "aws_security_group" "rails_poc" {
  for_each    = local.rails_poc_apps
  name        = "carlos-tito-rails-${each.key}-staging"
  description = "Rails PoC ${each.key}: web port from the IE edge only"
  vpc_id      = local.rails_poc.staging_vpc_id
  ingress {
    from_port   = each.value.port
    to_port     = each.value.port
    protocol    = "tcp"
    cidr_blocks = ["${local.rails_poc.edge_private_ip}/32"]
  }
  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }
}

resource "aws_iam_role" "rails_poc" {
  for_each = local.rails_poc_apps
  name     = "carlos-tito-rails-${each.key}-staging"
  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
      Action    = "sts:AssumeRole"
    }]
  })
}

resource "aws_iam_role_policy_attachment" "rails_poc_ssm" {
  for_each   = local.rails_poc_apps
  role       = aws_iam_role.rails_poc[each.key].name
  policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}

resource "aws_iam_role_policy" "rails_poc_pull_and_env" {
  for_each = local.rails_poc_apps
  name     = "pull-and-env"
  role     = aws_iam_role.rails_poc[each.key].id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      { Effect = "Allow", Action = ["ecr:GetAuthorizationToken"], Resource = "*" },
      { Effect = "Allow",
        Action = ["ecr:BatchGetImage", "ecr:GetDownloadUrlForLayer", "ecr:BatchCheckLayerAvailability"],
        Resource = "<repo arn(s) for ${each.key} from Task 1>" },
      { Effect = "Allow", Action = ["ssm:GetParameter"],
        Resource = "arn:aws:ssm:eu-west-1:665106592142:parameter/tito/rails-poc/${each.key}-staging/*" },
    ]
  })
}

resource "aws_iam_instance_profile" "rails_poc" {
  for_each = local.rails_poc_apps
  name     = "carlos-tito-rails-${each.key}-staging"
  role     = aws_iam_role.rails_poc[each.key].name
}

resource "aws_instance" "rails_poc" {
  for_each                    = local.rails_poc_apps
  ami                         = data.aws_ami.rails_poc_debian_amd64.id
  instance_type               = "t3a.large"
  subnet_id                   = local.rails_poc.box_subnet_id
  private_ip                  = each.value.ip
  associate_public_ip_address = true # egress for SSM/ECR/apt; ingress is SG-closed
  vpc_security_group_ids      = [aws_security_group.rails_poc[each.key].id]
  iam_instance_profile        = aws_iam_instance_profile.rails_poc[each.key].name
  user_data = templatefile("${path.module}/rails-poc-init.sh.tpl", {
    app  = each.key
    port = each.value.port
  })
  user_data_replace_on_change = false
  root_block_device {
    volume_size = 40
    volume_type = "gp3"
    encrypted   = true
  }
  tags = { Name = "carlos-tito-rails-${each.key}-staging" }
  # Same floating-AMI trap as svc-pdf.tf: without this a newer Debian
  # image turns `tofu apply` into "replace the box".
  lifecycle {
    ignore_changes = [ami]
  }
}

output "rails_poc_ips" {
  value = { for k, v in aws_instance.rails_poc : k => v.private_ip }
}
```

- [ ] **Step 2: Write `tito/rails-poc-init.sh.tpl`**

```bash
#!/bin/bash
# 🤖 Rails PoC box init (${app}): docker + ECR helper + env from SSM +
# systemd units for the full process tree. Deploys happen via
# scripts/rails-poc-deploy.sh over SSM — first boot starts nothing
# until a deploy writes /etc/rails-poc/image.
set -euo pipefail
export DEBIAN_FRONTEND=noninteractive
apt-get update
apt-get install -y docker.io amazon-ecr-credential-helper awscli jq

mkdir -p /root/.docker /etc/rails-poc
cat > /root/.docker/config.json <<'EOF'
{ "credsStore": "ecr-login" }
EOF

# App env from SSM (SecureString), 0600. Refreshed on every deploy too.
cat > /usr/local/bin/rails-poc-fetch-env <<'EOF'
#!/bin/bash
set -euo pipefail
aws ssm get-parameter --region eu-west-1 --with-decryption \
  --name /tito/rails-poc/${app}-staging/env \
  --query Parameter.Value --output text > /etc/rails-poc/app.env.new
chmod 600 /etc/rails-poc/app.env.new
mv /etc/rails-poc/app.env.new /etc/rails-poc/app.env
EOF
chmod 755 /usr/local/bin/rails-poc-fetch-env

# One runner for every role; the role's command comes from the env file
# (WEB_COMMAND / WORKER_COMMAND / CLOCK_COMMAND, recorded from the k8s
# manifests in rails-poc-facts.md).
cat > /usr/local/bin/rails-poc-run <<'EOF'
#!/bin/bash
set -euo pipefail
role="$1"
image="$(cat /etc/rails-poc/image)"
source /etc/rails-poc/app.env
var="$(echo "$role" | tr a-z A-Z)_COMMAND"
publish=""
[ "$role" = web ] && publish="-p ${port}:${port}"
exec docker run --rm --name "rails-$role" $publish \
  --env-file /etc/rails-poc/app.env "$image" $${!var}
EOF
chmod 755 /usr/local/bin/rails-poc-run

for role in web worker clock; do
cat > /etc/systemd/system/rails-$role.service <<EOF
[Unit]
Description=Rails PoC ${app} $role
After=docker.service network-online.target
Requires=docker.service
[Service]
ExecStartPre=-/usr/bin/docker rm -f rails-$role
ExecStart=/usr/local/bin/rails-poc-run $role
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
EOF
done
systemctl daemon-reload
# Deliberately NOT enabled/started: the first deploy does that, once
# /etc/rails-poc/image exists and the env parameter is populated.
/usr/local/bin/rails-poc-fetch-env || true
```

Note the tpl escaping: `${app}` / `${port}` are template vars; `$${!var}` renders as shell `${!var}`. If an app has no clock process (Task 1 facts), that unit simply never gets enabled.

- [ ] **Step 3: Targeted plan**

```bash
tofu -chdir=tito plan $(printf ' -target=%s' \
  aws_security_group.rails_poc 'aws_iam_role.rails_poc' \
  'aws_iam_role_policy_attachment.rails_poc_ssm' 'aws_iam_role_policy.rails_poc_pull_and_env' \
  'aws_iam_instance_profile.rails_poc' 'aws_instance.rails_poc')
```

Expected: adds only (2 SGs, 2 roles, 2 attachments, 2 policies, 2 profiles, 2 instances = 12), zero change/destroy. Verify the plan shows `t3a.large` and an `debian-13-amd64` AMI.

- [ ] **Step 4: Commit**

```bash
git add tito/rails-poc-boxes.tf tito/rails-poc-init.sh.tpl
git commit -m "tito: rails-poc staging boxes (x86, docker+systemd, SSM-only)"
```

---

### Task 4: SSM env parameters (operator step with Paul)

**Files:** none (parameters live in SSM only, per Global Constraints).

**Interfaces:**
- Produces: `/tito/rails-poc/classic-staging/env` and `/tito/rails-poc/pro-staging/env` (SecureString, env-file format). Task 3's boxes and Task 5 depend on them existing.

- [ ] **Step 1: Assemble each app's env from the k8s staging config**

The k8s deployment's env (ConfigMap + Secrets) IS the source; dump it with Paul (values must not land in the transcript — pipe to a root-owned temp file, or Paul runs it):

```bash
kubectl -n <staging-namespace> exec deploy/<web-deploy> -- env | sort > /tmp/classic-staging.env
```

Then append the three process-command lines from `rails-poc-facts.md`:

```
WEB_COMMAND=<web command>
WORKER_COMMAND=<worker command>
CLOCK_COMMAND=<clock command, omit line if none>
```

Prune k8s-runtime noise (`KUBERNETES_*`, `*_SERVICE_HOST`, `*_SERVICE_PORT`, `HOSTNAME`, `PATH`, `HOME`). Everything Rails reads stays.

- [ ] **Step 2: Store as SecureString and shred the temp file**

```bash
aws --profile titogo --region eu-west-1 ssm put-parameter \
  --name /tito/rails-poc/classic-staging/env --type SecureString \
  --value file:///tmp/classic-staging.env
shred -u /tmp/classic-staging.env
```

Repeat for pro. Verify with `aws ssm get-parameter --name … --query Parameter.Version` (never `--with-decryption` in the transcript).

---

### Task 5: Apply and boot the boxes

**Interfaces:**
- Consumes: Tasks 2–4 all landed.
- Produces: two running boxes answering SSM, env fetched; nothing serving yet (first deploy is Task 8).

- [ ] **Step 1: Targeted apply — networking first, then boxes**

```bash
tofu -chdir=tito apply \
  -target=aws_vpc_peering_connection.rails_poc_staging \
  -target=aws_route.rails_poc_to_classic \
  -target=aws_route.rails_poc_to_pro \
  -target=aws_route.rails_poc_return
tofu -chdir=tito apply $(printf ' -target=%s' \
  aws_security_group.rails_poc 'aws_iam_role.rails_poc' \
  'aws_iam_role_policy_attachment.rails_poc_ssm' 'aws_iam_role_policy.rails_poc_pull_and_env' \
  'aws_iam_instance_profile.rails_poc' 'aws_instance.rails_poc')
```

Review each plan before confirming — adds only, and the route apply must show exactly the two `/32`s + return route + peering.

- [ ] **Step 2: Verify both boxes via SSM**

```bash
for tag in classic pro; do
  iid=$(aws --profile titogo --region eu-west-1 ec2 describe-instances \
    --filters Name=tag:Name,Values=carlos-tito-rails-$tag-staging Name=instance-state-name,Values=running \
    --query 'Reservations[].Instances[].InstanceId' --output text)
  cid=$(aws --profile titogo --region eu-west-1 ssm send-command --instance-ids "$iid" \
    --document-name AWS-RunShellScript \
    --parameters 'commands=["docker --version; ls -l /etc/rails-poc/app.env; systemctl list-unit-files rails-*"]' \
    --query Command.CommandId --output text)
  sleep 8
  aws --profile titogo --region eu-west-1 ssm get-command-invocation \
    --command-id "$cid" --instance-id "$iid" --query '{s:Status,o:StandardOutputContent}' --output json
done
```

Expected: docker installed, `app.env` present mode 0600, three `rails-*.service` unit files. If `app.env` is missing, cloud-init ran before Task 4's parameters existed — rerun `/usr/local/bin/rails-poc-fetch-env` via SSM.

- [ ] **Step 3: Commit the facts-file update (instance IDs)**

```bash
git add tito/rails-poc-facts.md
git commit -m "tito: rails-poc boxes applied; record instance ids"
```

---

### Task 6: Open the staging dependencies to the boxes

**Files:**
- Create: `platform-infrastructure/tito/rails-poc-deps.tf`

**Interfaces:**
- Consumes: staging DB/cache SG IDs (Task 1 facts), `aws_security_group.rails_poc` (Task 3).

- [ ] **Step 1: Write `tito/rails-poc-deps.tf`**

```hcl
# Ingress on the (externally-managed) staging dependency SGs admitting
# the PoC boxes. aws_security_group_rule against SG ids this tree does
# not own — removal of the PoC removes exactly these rules and nothing
# else. Classic is MySQL, Pro is Postgres (rails-poc-facts.md).

locals {
  rails_poc_dep_rules = {
    classic_mysql     = { sg = "<classic staging DB sg>", port = 3306,  app = "classic" }
    classic_valkey    = { sg = "<classic staging redis sg>", port = 6379,  app = "classic" }
    classic_memcached = { sg = "<classic staging memcached sg>", port = 11211, app = "classic" }
    pro_postgres      = { sg = "<pro staging DB sg>", port = 5432,  app = "pro" }
    pro_valkey        = { sg = "<pro staging redis sg>", port = 6379,  app = "pro" }
    pro_memcached     = { sg = "<pro staging memcached sg>", port = 11211, app = "pro" }
  }
}

resource "aws_security_group_rule" "rails_poc_dep" {
  for_each                 = local.rails_poc_dep_rules
  type                     = "ingress"
  security_group_id        = each.value.sg
  from_port                = each.value.port
  to_port                  = each.value.port
  protocol                 = "tcp"
  source_security_group_id = aws_security_group.rails_poc[each.value.app].id
  description              = "rails-poc ${each.value.app} staging box"
}
```

(Same-VPC SG references — the boxes live in the staging VPC precisely so this works.)

- [ ] **Step 2: Targeted plan (6 adds only), apply, commit**

```bash
tofu -chdir=tito plan -target=aws_security_group_rule.rails_poc_dep
tofu -chdir=tito apply -target=aws_security_group_rule.rails_poc_dep
git add tito/rails-poc-deps.tf
git commit -m "tito: rails-poc staging dependency SG ingress"
```

- [ ] **Step 3: Prove connectivity from each box (SSM)**

```bash
# on the classic box via send-command:
timeout 3 bash -c '</dev/tcp/tito-classic-mysql-staging-writer.cefg7n9rzaz0.eu-west-1.rds.amazonaws.com/3306' && echo mysql-ok
timeout 3 bash -c '</dev/tcp/<classic redis endpoint>/6379' && echo valkey-ok
timeout 3 bash -c '</dev/tcp/<classic memcached endpoint>/11211' && echo memcached-ok
# pro box: postgres 5432 + its two caches
```

Expected: three `*-ok` lines per box. A hang means the SG rule or a subnet route is wrong — fix before proceeding.

---

### Task 7: Edge routes

**Interfaces:**
- Consumes: box IPs + web ports (facts), boxes booted (Task 5).
- Produces: `classic.platform.tito.io` / `pro.platform.tito.io` routed (503/refused until Task 8 deploys).

- [ ] **Step 1: Add both routes on the IE box via SSM, as user `carlos`**

```bash
aws --profile titogo --region eu-west-1 ssm send-command --instance-ids i-025a0b70f3d93304d \
  --document-name AWS-RunShellScript --parameters 'commands=[
    "sudo -u carlos /opt/carlos/carlos add -kind service -addr <classic_ip>:<classic port> classic.platform.tito.io",
    "sudo -u carlos /opt/carlos/carlos add -kind service -addr <pro_ip>:<pro port> pro.platform.tito.io"
  ]' --query Command.CommandId --output text
```

Fetch the invocation output; each line must say `added` (or `updated … (existing route)` on a re-run — `carlos add` upserts; that is also how an upstream gets repointed). **No `-hibernate`, ever, on these routes.**

- [ ] **Step 2: Verify TLS + routing end to end**

```bash
curl -sv https://classic.platform.tito.io/ -o /dev/null 2>&1 | grep -E 'subject:|HTTP/'
curl -sv https://pro.platform.tito.io/ -o /dev/null 2>&1 | grep -E 'subject:|HTTP/'
```

Expected: a Let's Encrypt cert for each exact hostname (first hit may take a few seconds while HTTP-01 completes), then `502`/`503` — the edge is up, nothing listens on the box yet. A TLS `internal error` alert means the route didn't land in `/data/registry.db`; re-check Step 1's output.

---

### Task 8: Deploy script + first deploy

**Files:**
- Create: `platform-infrastructure/scripts/rails-poc-deploy.sh`

**Interfaces:**
- Consumes: everything above; image tag currently on k8s staging (facts).
- Produces: `rails-poc-deploy.sh <classic|pro> <image-ref>` — THE deploy path from here on.

- [ ] **Step 1: Write `scripts/rails-poc-deploy.sh`**

```bash
#!/bin/bash
# 🤖 Deploy a Rails PoC box over SSM: refresh env, point at the image,
# restart the tree, wait for health through the edge.
# Usage: rails-poc-deploy.sh <classic|pro> <image-ref>
set -euo pipefail
app="$1"; image="$2"
region=eu-west-1; profile=titogo
iid=$(aws --profile $profile --region $region ec2 describe-instances \
  --filters Name=tag:Name,Values=carlos-tito-rails-$app-staging Name=instance-state-name,Values=running \
  --query 'Reservations[].Instances[].InstanceId' --output text)
[ -n "$iid" ] || { echo "no running box for $app" >&2; exit 1; }

cid=$(aws --profile $profile --region $region ssm send-command --instance-ids "$iid" \
  --document-name AWS-RunShellScript --parameters commands="[
    \"/usr/local/bin/rails-poc-fetch-env\",
    \"docker pull $image\",
    \"echo $image > /etc/rails-poc/image\",
    \"systemctl enable rails-web rails-worker\",
    \"systemctl restart rails-web rails-worker\",
    \"systemctl is-enabled rails-clock >/dev/null 2>&1 && systemctl restart rails-clock || true\"
  ]" --query Command.CommandId --output text)

for i in $(seq 1 60); do
  st=$(aws --profile $profile --region $region ssm get-command-invocation \
    --command-id "$cid" --instance-id "$iid" --query Status --output text)
  [ "$st" = Success ] && break
  [ "$st" = Failed ] && { aws --profile $profile --region $region ssm get-command-invocation \
    --command-id "$cid" --instance-id "$iid" --query StandardErrorContent --output text >&2; exit 1; }
  sleep 5
done

url="https://$app.platform.tito.io<health path from facts>"
for i in $(seq 1 30); do
  code=$(curl -s -o /dev/null -w '%{http_code}' "$url") && [ "$code" = 200 ] && { echo "$app healthy: $url"; exit 0; }
  sleep 5
done
echo "$app not healthy after deploy ($url last code $code)" >&2; exit 1
```

`chmod +x scripts/rails-poc-deploy.sh`. (Apps with a clock process get it enabled once, manually, via SSM: `systemctl enable rails-clock` — the script then keeps restarting it.)

- [ ] **Step 2: First deploys, with the tag k8s staging currently runs**

```bash
./scripts/rails-poc-deploy.sh classic <classic image:tag from facts>
./scripts/rails-poc-deploy.sh pro <pro image:tag from facts>
```

Expected: both end with `healthy`. Debug path if not: `journalctl -u rails-web -n 100` via SSM on the box. Likely first-boot issues: a missing env var (fix the SSM parameter, redeploy), or the app binding localhost only (the k8s manifests' web command already binds 0.0.0.0 — reuse it exactly).

- [ ] **Step 3: Verify the full tree and the replica behavior**

```bash
# via SSM on each box:
docker ps --format '{{.Names}} {{.Status}}'   # rails-web, rails-worker (+ rails-clock)
```

Then the shared-queue proof: with Paul, enqueue a staging background job through the **k8s** app (or its console) and watch it get picked up on a PoC box: `journalctl -u rails-worker -f` via an SSM session. A job processed on the PoC box while k8s workers also run = the parallel-replica claim, proven.

- [ ] **Step 4: Commit**

```bash
git add scripts/rails-poc-deploy.sh
git commit -m "scripts: rails-poc deploy over SSM (pull, restart, edge health)"
```

---

### Task 9: Production tofu — written, gated off

**Files:**
- Create: `platform-infrastructure/tito/rails-poc-prod.tf`

- [ ] **Step 1: Write the gated file**

```hcl
# 🤖 Production twin of the staging PoC — WRITTEN, NOT APPLIED (spec:
# staging first; flipping this variable is the post-PoC decision).
# Networking is SIMPLER than staging: the default VPC already routes
# 10.0.0.0/16 to the existing production peering pcx-056b55b69cbf89143,
# so prod boxes need NO new peering and NO new routes — only boxes,
# SG rules on the prod dependency SGs, and /tito/rails-poc/<app>-prod/env
# parameters. Fill the <…> values from a prod re-run of Task 1
# (rails-poc-facts.md gets a prod section) before ever enabling.

variable "rails_poc_prod_enabled" {
  type    = bool
  default = false
}

resource "aws_instance" "rails_poc_prod" {
  for_each = var.rails_poc_prod_enabled ? {
    classic = { ip = "<prod classic ip — ENI-free check vs BOTH VPCs>", port = <port>, subnet = "<prod subnet>" }
    pro     = { ip = "<prod pro ip>", port = <port>, subnet = "<prod subnet>" }
  } : {}
  ami                    = data.aws_ami.rails_poc_debian_amd64.id
  instance_type          = "t3a.large"
  subnet_id              = each.value.subnet
  private_ip             = each.value.ip
  vpc_security_group_ids = [] # prod SGs defined alongside when enabling
  user_data = templatefile("${path.module}/rails-poc-init.sh.tpl", {
    app  = each.key
    port = each.value.port
  })
  root_block_device {
    volume_size = 40
    volume_type = "gp3"
    encrypted   = true
  }
  tags      = { Name = "carlos-tito-rails-${each.key}-prod" }
  lifecycle { ignore_changes = [ami] }
}
```

- [ ] **Step 2: Prove it is inert, commit**

```bash
tofu -chdir=tito plan -target=aws_instance.rails_poc_prod
# Expected: "No changes." — the empty for_each makes it a no-op.
git add tito/rails-poc-prod.tf
git commit -m "tito: rails-poc production twin, gated off (post-PoC decision)"
```

---

### Task 10: Runbook, PRs, and the evaluation record

**Files:**
- Modify: `platform-infrastructure/tito/README.md` (append a `## Rails PoC` section)
- Modify (platform repo, branch `rails-behind-edge-poc-spec`): the spec's §7 — check off what was actually met

- [ ] **Step 1: Append the runbook to `tito/README.md`**

```markdown
## Rails PoC (classic/pro staging behind the edge)

Spec + plan: platform repo `docs/superpowers/{specs,plans}/2026-08-11-rails-behind-carlos-edge-poc*`.
Facts (IPs, images, SGs): `tito/rails-poc-facts.md`.

- Deploy: `scripts/rails-poc-deploy.sh <classic|pro> <image-ref>` (SSM; no SSH).
- Routes live in the IE box's `/data/registry.db` (`carlos add` as user
  `carlos`; re-run to repoint; NEVER `-hibernate` on these).
- Logs: `journalctl -u rails-{web,worker,clock}` via SSM on the box.
- Teardown: remove the routes on the IE box, then targeted destroys of
  `aws_instance.rails_poc`, `aws_security_group_rule.rails_poc_dep`,
  the two `/32` `aws_route.rails_poc_to_*`, `aws_route.rails_poc_return`,
  `aws_vpc_peering_connection.rails_poc_staging`; delete the
  `/tito/rails-poc/*` SSM parameters.
- The default VPC's `10.0.0.0/16 → pcx-056b55b69cbf89143` (production)
  route is why staging only ever gets `/32` routes — do not "simplify".
- Fallback if a shared cache is unreachable (spec §"Decisions"): an
  on-box memcached is one unit away —
  `docker run -d --restart=always -p 127.0.0.1:11211:11211 memcached:1.6`
  plus pointing the app's cache env var at `127.0.0.1:11211`. Documented
  fallback only; the default is the shared staging Elasticache.
```

- [ ] **Step 2: During the parallel-run week, record the §7 gap list against reality**

In the spec (platform repo), annotate each §7 item with what actually happened (e.g. "config delivery: hand-rolled SSM fetch worked but rotation is manual — a real `appconfig` gap"). This annotated list is the deliverable of the evaluation.

- [ ] **Step 3: Open the PRs**

```bash
# infra:
cd ~/github.com/carlosframework/platform-infrastructure/.claude/worktrees/rails-poc
git push -u origin rails-poc
gh pr create --title "tito: Rails-behind-the-edge staging PoC (classic/pro)" \
  --body "Boxes, peering, dep SG rules, deploy script per the platform repo spec 2026-08-11-rails-behind-carlos-edge-poc-design.md. Targeted applies only — see plan.

🤖 Generated with [Claude Code](https://claude.com/claude-code)"
# spec+plan:
cd ~/github.com/carlosframework/platform/.claude/worktrees/rails-behind-edge-poc-spec
git push -u origin rails-behind-edge-poc-spec
gh pr create --title "docs: Rails-behind-the-edge PoC — design record + implementation plan" \
  --body "Design + plan for serving Tito Classic/Pro staging through the CARLOS edge (spec approved by Paul 2026-08-11).

🤖 Generated with [Claude Code](https://claude.com/claude-code)"
```

---

## Execution notes

- Tasks 1→8 are strictly ordered; 9 and 10 can follow any time after 3 and 8 respectively.
- Applies (Tasks 5, 6) and anything touching the IE box (Task 7) or k8s (Tasks 1, 4, 8) are operator-visible actions — do them deliberately, one at a time, reading every plan before confirming.
- If any targeted plan proposes a change or destroy outside the `rails_poc*` names, STOP — that is the known tree drift; never apply through it.
