# EPHEMERA.md — DevOps as a Conversation

> **Portable instruction.** If you are an AI agent in this repository and the human asks you to create,
> change, inspect, or remove cloud infrastructure, **read this file and follow it.** It is
> runtime-neutral and **CLI-first**: it tells you *what to do* with ordinary shell commands
> (`aws`, `wrangler`, `gcloud`, …) — no special tools or MCP required. A human can read it too; the
> human-facing companion is `README.md`.

## What this is

Infrastructure managed as **runnable Markdown plans**. One file per stack describes the desired state,
carries the commands to reach it, records what it built, verifies itself, and tears itself down. You
(the agent) are the runtime; **the cloud is the source of truth.**

```
Markdown = "it should look like this"   (intent + procedure + write-back ledger)
Cloud    = "what actually exists"        (the real source of truth)
You      = reconcile them, one verified step at a time
```

Plans are named `<stack>.<provider>.md` (e.g. `web.aws.md`, `web.cloudflare.md`, `task-runner.aws.md`).
Copy `EPHEMERA-TEMPLATE.md` to author a new one.

## When to use this — and when not

**Use** for solo/small-team infra, fast iteration, multi-cloud, cost comparison — anywhere a human wants
to read and reason about the plan and an agent can troubleshoot it.

**There is no technical fence.** The only thing between you and a workload is an institution that
*mandates* a specific legacy tool — or a human signature on a deterministic artifact. That's adoption
lag, not a limit of the approach. Ephemera captures a *richer* audit trail (intent + every action +
approvals + verification, timestamped in the ledger) than the `.tfstate` it replaces — so where a
contract or auditor still names a tool, that's a case to make, not a capability you lack: bring the
ledger. (Honest build-status, not a fence: event-driven drift and the deterministic diff tool are
roadmap — maturity, not a ceiling.)

## Command verbs (what the human means)

The human drives with a small fixed vocabulary against a plan file:

| Verb | You do | Safety |
|------|--------|--------|
| **verify** `<plan>` | run the plan's read-only checks against the live cloud; report drift; change nothing | safe |
| **plan** / **dry-run** `<plan>` | report what *would* change vs live state | safe |
| **apply** / **create** `<plan>` | reconcile the cloud toward the plan's desired state | hits 🔴 gates |
| **reconcile** / **update** `<plan>` | re-apply the step(s) for any drifted check (idempotent) | 🟡 / 🔴 |
| **teardown** `<plan>` | observe-first, resumable destroy | hits 💥 gates |
| **migrate** `<existing-IaC>` | read existing Terraform / Pulumi / CloudFormation / CDK and author the equivalent `<stack>.<provider>.md` | safe (authoring only) |

`verify` is the safe default entry point. When a plan's `status` is `live`, `verify` means the
**live-cloud drift check**, not a static read of the Markdown.

## The execution contract (follow exactly)

1. **Read the plan's Intent, then its Live State.** The cloud is truth — if Live State disagrees with the
   cloud, believe the cloud and correct the ledger.
2. **Observe before acting.** Each step says how to check "does it already look like this?" Act only on
   the delta. Re-running a plan must be safe.
3. **One verified step at a time.** Run a step, run its `verify`, *then* advance. Never leave an
   unverified step behind you — no batch-apply-and-pray.
4. **Stop at 🔴 and 💥 for approval — which is a *step, not a system*.** Print exactly what you will run,
   then run whatever approval trigger the plan bakes in — e.g. *"use the Slack MCP to DM Bob the exact
   action; continue only on a clear affirmative; record approver + timestamp in Live State."* If the plan
   names no trigger, pause for the human in the session. Never proceed on an ambiguous answer.
5. **Write back.** After every mutation, record realized IDs in the plan's Live State; after every
   verify, record PASS/FAIL + the observed value. The plan file is the audit trail — keep it true.
6. **Background async waits (⏳).** Some operations take minutes (CloudFront ~15–20 min). Start the
   waiter in the background and resume when it signals; don't block a shell on it.
7. **Teardown observes first and is resumable.** Observe current cloud state, place yourself in the
   teardown sequence, act, repeat. A crash mid-teardown is fine — re-entry re-observes.

## Plan shape (required movements; the prose between is yours — no YAML schema)

- **Intent** — what + why, in prose.
- **Provisioning Inputs** *(when the plan has human-decision forks)* — a decision table the Director
  resolves **once**, up front, before any cloud mutation: each row is a question, its closed-enum options,
  a default, the variable it sets, and what it gates. Walk the rows, confirm each with the human (accept
  the default on silence), then write a `resolved_inputs` block into Live State; every downstream step
  branches on those vars. Every option is a closed enum (bar free-text identifiers), so the resource graph
  is a *pure function* of the answers — same answers ⇒ same plan. A re-run reads `resolved_inputs` and
  skips the interview; changing an answer is an explicit edit, never silent drift.
- **Vantage** *(required for host-targeting bindings — `local`, `ollama`, `tailscale`; implicit for cloud)* — where every ✔
  in the plan runs FROM. A ✔ is evidence only when it is answered by a party the described thing cannot
  influence. For a cloud plan that party is the provider API, so nothing is declared. For a plan that
  describes a host, the checker and the described thing share a box unless the plan says otherwise — so it
  must say: name the host the checks run from (`> **Vantage**: …` beside Provides/Requires), and any single
  step may override with `✔@<host>`. `self` is allowed **only as a declared decision with the reason** (e.g.
  "this plan asserts the availability of its own process, not the integrity of its host") — never as the
  default, and never for a check that asserts a security property of the host it runs on.
- **TAGS** *(when the plan creates taggable resources)* — a provenance/cost tag set resolved **once**
  (like Provisioning Inputs) and applied at **every** `create`/`config`. Standard keys: `ManagedBy=ephemera`,
  `Source=<plan path/URL>` + `PlanVersion` (what created this), `CostCenter`, `Owner`, `Environment` (=`ENV`);
  plus an app tier (`Service`/`Component`/`Version`) merged on workload resources (last-wins override). §0
  carries tiny pure-function **renderers** (one per provider tag syntax; canonical source `scripts/tags.sh`).
  **Only resources this plan creates are tagged** — never borrowed/upstream ones. Where a provider has no
  resource-tag API (Cloudflare), provenance lives in the plan + naming convention + Worker vars (a
  portability-ledger note).
- **Legend** — the blast-radius markers below.
- **Live State** — the write-back ledger: `status`
  (baseline lifecycle: `not-created` / `creating` / `live` / `partial` / `tearing-down` / `gone` — a plan may
  add **named intermediate states** in its own Live State when its lifecycle needs them, e.g. domain's
  `zone-pending` / `awaiting-purchase`), realized IDs, a verify-results table.
  > ⚠ **`status` and `maturity` are different axes — do not read one as the other.** `status` describes
  > the **world**: is anything deployed right now. `maturity` (in the catalog: `authored` /
  > `dogfooded` / `proven-live`) describes the **plan**: how much of it has been executed against a
  > real provider. `status: not-created` + `maturity: proven-live` is not a contradiction — it is the
  > *normal resting state* of a plan that was stood up, verified, and then torn down, which is what
  > the teardown discipline asks for. As of 2026-07-31 that combination holds for 13 of 41 plans.
  > A plan is **unproven** only when its `maturity` says so, never because its `status` is empty.
- Per component: **create · verify · update · teardown**, each command annotated with a marker.
- **Dependency frontier** — what must precede what and why, including chicken-and-egg edges (a policy
  that needs a resource's ARN comes *after* that resource).
- **Deliberately not included** — named omissions, so each is a decision not an oversight.

```
Legend  🟢 create · 🟡 config · 🔴 GATE (human go) · 💥 destructive (human go) · ⏳ wait · ✔ verify
```

A step may carry more than one marker (🔴🟢 = create behind a gate); the most severe gate wins — if any
🔴 or 💥 is present, stop for a human go. A ✔ may carry `@<host>` (`✔@watcher`) naming the host that check
runs FROM when it differs from the plan's **Vantage** — an observation names its observer.

**Gates ride the irreversible act, never a no-op.** A read-only check (✔), a `--dry-run`, or writing a local
config file is **never** 🔴/💥 — it spends nothing and reverses freely. Gating it is *gate-fatigue*: the human
learns to rubber-stamp, and the one gate that matters — the billable / global / irreversible mutation — gets
the same dull click. Put the gate on the mutation itself, not its rehearsal.

## Verify & drift ("does it still look like this?")

Each step carries a read-only assertion. Re-running all of them is drift detection — the cheap,
read-only equivalent of a plan/diff, run against the live cloud. **Assert negatives too** ("the bad
thing is absent" — e.g. a private origin's direct URL must `403`), and beware fallbacks that turn errors
into success (they can mask a broken origin — pair them with an independent positive-content check).
Inline assertions only catch what you thought to assert; if a deterministic full-diff tool is available,
prefer it for total low-level drift.

**Triage: when a check differs or can't run.** A red result is not where a run ends. Report one result per check:
match, differs, or couldn't check. *A check that couldn't run is not a pass.* For anything that isn't a match, read
the plan, Live State and the project's history, then say which of these it is and what it rests on:

- **Deliberate change:** the history explains it. The cloud stays as it is; the plan or Live State catches up.
- **Real drift:** the cloud differs and nothing explains it, or the plan changed and was never applied. Name the
  `reconcile` step that fixes it. If the history is silent, say "unexplained" rather than guessing.
- **Stale check:** the check is what's wrong, such as a provider rewording an error it greps for. Fix the check and
  re-run it.

Triage itself changes nothing in the cloud. It ends with a diagnosis and a next step, so the human gets a decision
to make instead of a failure to debug. Any fix then runs through `reconcile` under the usual 🔴 / 💥 gates.

**Where the check stands is part of the check.** Re-running every ✔ *from the host under test* proves nothing
about that host: root there owns the process that answers `id -u`, `lsof`, `stat`. A drift check that observes
a box from the box is a **self-observing guard** — it returns ✔ for every row it can no longer prove. Cloud
plans get an independent witness for free (the provider API answers, and the resource cannot edit the
answer); host-targeting plans must name theirs — the **Vantage** movement — and run their integrity checks
from it (`✔@watcher`, never from `self`). Record the vantage in the verify-results table beside PASS/FAIL.
(Design input from the fleet's home-sensing review, 2026-09-01: a plan that checks the collector from the
collector inherits the root-owns-the-box waiver it was written to detect.)

## Multi-environment

Parameterize on a single `ENV` knob (`dev` / `stg` / `uat` / `prod`) and postfix every resource name
(`name-${ENV}`). "Stand this up for stg" = run with `ENV=stg`. One plan, every environment — never fork
a file per env. The same `ENV` also feeds the `Environment` tag emitted by the **TAGS** movement, so every
resource is labeled with the environment it belongs to.

## Multi-cloud — "take it to any provider" is a conversation

The *intent* is provider-neutral; each cloud is a **binding** of the same intent that passes the same
acceptance contract. "Take this to Cloudflare," "take this to Google Cloud," "take this to Azure" are
**not** migration projects — they are authoring another `<stack>.<provider>.md` (e.g. `web.gcp.md`,
`web.azure.md`) and proving it against the shared contract. Cost A/B between providers = reading each
binding's cost notes against an expected traffic profile.

## Composition across plans — the cloud is the hand-off

Plans compose, but **never through a shared state file** — that reintroduces the `.tfstate` this approach
replaces. A producer plan's acceptance contract *is* a consumer's precondition; make the edge explicit:

- the producer declares **Provides** `resource(id)` — e.g. `domain.aws.md` Provides `delegated-zone(DOMAIN_NAME)`;
- the consumer declares **Requires** it — e.g. `web.aws.md` Requires `delegated-zone(DOMAIN_NAME)` when `DNS_MODE=managed`.

The consumer **discovers** the resource by observing the cloud — the real zone, bucket, or ARN — and may
*pre-fill its Provisioning Inputs* from what it finds, so the human isn't re-asked what an upstream plan
already realized. Live State ledgers are caches on both sides; the cloud is the source of truth. This is
the cross-plan analog of a plan's internal **Dependency frontier**.

## No ceremony — what this does NOT require

No `init` / `bootstrap` step. No provider/plugin downloads — Terraform's `.terraform/`, Pulumi's plugins,
CDK's `node_modules` + `cdk bootstrap` — routinely hundreds of MB. No lock files, no state backend to host
(Terraform/Pulumi state, CloudFormation/ARM stacks). No multi-minute plan/apply rituals. True of **all**
traditional IaC — imperative or declarative. The toolchain here is just: this Markdown file, an agent, and
the provider CLI you already have (`aws` / `wrangler` / `gcloud` / `az`). The cloud is the state; the file
is the intent.

## Provider gotchas (don't relearn these live)

**Shell (all providers)** — run plan code blocks under **`bash`** (`bash <<'…'` if your interactive shell is
zsh): plans use POSIX word-splitting of unquoted variables, which zsh does not perform — optional-flag idioms
arrive as one argument and the CLI errors `Unknown options` (proven live). Any bash ≥3.2 works; 3.2 is only the
compatibility *floor* (stock macOS), a modern bash is strictly better.

**Paths (all providers)** — plans must be **path-portable**: never bake a machine-absolute path
(an expanded home-directory path such as `$HOME/…` written out literally, or a Windows `C:\…`) into a plan **or a generated config** — another
operator won't have your home dir, and a hardcoded home path is *also* an identity leak the gate must catch. Use
repo-relative paths (`./site`) or `$PWD`-derived ones. When a tool resolves sibling paths **relative to its
own config file** (e.g. wrangler's `assets.directory`), generate that config **in the repo tree**, not a
`mktemp -d` — otherwise the relative path won't resolve and the "fix" tempts an absolute path (which is the
bug, not the fix).

**Credentials & secrets (all providers)** — provision secrets by **piping** into the provider CLI
(`openssl rand -hex 32 | wrangler secret put NAME` mints one straight into the pipe; capture an
API-returned secret with a small `node -e`/`python -c` that writes it directly into the pipe) — the value
must never land in argv, shell history, a temp file, or the plan's ledger: **Live State records secret
NAMES only, never values.** And provider **test / dev-bypass credentials** (e.g. Turnstile's published
always-pass test key pairs — any "test mode always succeeds" credential) are for local dev only:
deploying one **silently disables the control it stands in for** on a live, internet-reachable endpoint.
A deployed environment always gets the real secret.

**AWS**
- **Credential broker + IAM:** if AWS creds come from a broker / SSO / MFA setup that vends
  **GetSessionToken session tokens** (e.g. `aws-vault export`), IAM API calls fail `InvalidClientTokenId`
  while *every other service works* and `sts get-caller-identity` succeeds. AWS forbids GetSessionToken
  creds from calling IAM without MFA. Use the broker's long-term / no-session mode for **every IAM call the
  plan makes** — creates, reconciles, teardown probes/guards/deletes/verifies, not just the first one
  (e.g. `aws-vault exec <profile> --no-session -- <iam cmd>`); regional services run fine on the session
  creds. ⚠ Proven live: brokered session creds can be ambient with **zero `AWS_*` env vars**
  (`credential_process` in `~/.aws/config`) — diagnose via the failing IAM call itself, not the environment.
- **AWS is async — plan for it:** CloudFront create/disable ~15–20 min (background the waiter; a
  distribution deletes only from `Deployed`+`Disabled`; **re-fetch the rotating ETag** before each
  mutating call); IAM propagation (retry `create-function` "role cannot be assumed"); API Gateway
  eventual consistency (`put-integration` transiently "ARN must contain path or action" — retry); SQS
  ~60 s lock after deleting a queue; versioned-bucket delete is **loop-until-empty** (versions +
  delete-markers).
- **API Gateway → Lambda auth** is a Lambda **resource policy** (`add-permission`, scoped to the API
  source-ARN), not an `InvokeFunction` statement in the execution role.
- **Reused IAM roles are scoped to their own resources** — borrowing one for new resources = `AccessDenied`.
- **us-east-1 quirk:** `create-bucket` rejects `LocationConstraint=us-east-1` (omit it there); CloudFront
  ACM certs must live in us-east-1.
- **Tag on create where the API allows it** (`--tag-specifications` / `--tags` at create time) — atomic,
  no untagged window; use `tag-resource` / `resourcegroupstaggingapi tag-resources` only where create can't
  tag. Tag syntax varies by service (`Key=,Value=` vs ECS lowercase `key=,value=` vs `--tag-specifications
  ResourceType=…,Tags=[…]` vs S3 `TagSet=[…]` vs CloudFront `Items=[…]` vs Lambda/SQS JSON map) — the
  **TAGS** renderers normalize this.

**Cloudflare**
- Workers Static Assets unifies storage + CDN: no bucket / OAC / policy, SPA fallback is one config line
  (`not_found_handling: "single-page-application"`), deploy/teardown in seconds, free egress.
  Assets-only default cache header is `max-age=0, must-revalidate` (browser-`immutable` needs a small
  Worker). Use `compatibility_date >= 2025-04-01`.
- **`assets.directory` resolves relative to the config file's own dir**, not the CWD — so generate the
  assets Worker config **in the repo root** (keeping `ASSETS_DIR` repo-relative), never in a `mktemp -d`
  where `./site` can't resolve. (See the **Paths** doctrine above — this is why an absolute path is the trap.)
- **No general resource tags.** Workers / KV / R2 / D1 / Queues / zones take no tags; carry provenance via
  the naming convention + Worker `[vars]` (`MANAGED_BY`, `SOURCE`, …) + `wrangler deploy --message`. The
  **TAGS** movement degrades to these on Cloudflare — that gap is a portability insight, not a defect.
- **Workers Static Assets ≠ Pages.** These plans serve static sites via Workers Static Assets (above). If a
  stack does use **Pages**: `wrangler pages deploy` does **not** auto-create the project (unlike `wrangler
  deploy` for Workers) — first deploy fails "project does not exist"; run `wrangler pages project create
  <name> --production-branch main` **then** `wrangler pages deploy <dir> --project-name <name>`. Pages
  serves extensionless "pretty URLs" (`/foo.html` → `308` → `/foo`): a verify asserting `200` on a `.html`
  path sees the `308` and mis-flags it — assert the pretty path, or `curl -L` and check the final code.
  And a Pages **custom domain via the API creates only the project binding, NOT the DNS record** (the
  dashboard's "add custom domain" atomically creates both — binding + a proxied placeholder record,
  `A 192.0.2.1`/`AAAA 100::`, orange-clouded; the proxy does the real routing): API-attached hostnames
  return **NXDOMAIN** until the plan also creates a record (a proxied `CNAME <sub> → <project>.pages.dev`
  is self-documenting). Verify the DNS record exists, not just the binding status — the binding alone
  passes while the site is unreachable. (Contrast: a **Workers** `custom_domain: true` route creates
  cert + DNS automatically — the asymmetry is Pages-specific.) **Order matters — negative-cache trap
  (general DNS, any provider):** if the name gets queried while it doesn't exist, that NXDOMAIN is
  negatively cached by every resolver that saw it for the zone's **SOA minimum TTL** (commonly 1800 s) —
  the record then exists authoritatively while the operator's resolver still says NXDOMAIN for up to
  ~30 min. **Create the DNS record as the FIRST action of the domain step, before anything resolves the
  name.** Diagnostic tell: `curl` fails `errno 6 (could not resolve)` while
  `curl --resolve <host>:443:<edge-ip>` returns `200` — that's DNS caching, not broken infra. Recovery:
  flush local DNS (macOS: `sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder`), query via a
  resolver that already has it (`1.1.1.1`), or wait out the SOA minimum.
- **CORS is the compose edge between a site and a Worker API.** The Worker's CORS allowlist must name the
  site's **exact origin(s)** — a `*.pages.dev` / preview origin is a *different* origin and is NOT covered
  by allowing the custom domain; the full app flow stays CORS-blocked from a preview URL until that origin
  is (temporarily) allowed too.

(Full human-facing catalog lives in `README.md`.)

## Red flags — stop and reconsider

- "Traditional IaC (Terraform / Pulumi / CDK / CloudFormation) is best practice, I'll write that" → for
  auditable, agent-run infra, author an Ephemera plan. Use traditional IaC only at the regulated/concurrent
  fence above.
- "The billable step is cheap, I'll just run it" → 🔴 means human go. Always. It's about authority over
  billable / global / irreversible actions, not cost.
- "I'll gate the dry-run / the config write to be safe" → no — a no-op carries no authority to approve. Gating
  it is gate-fatigue that dulls the real gate. 🔴/💥 mark the mutation, never its rehearsal.
- "I'll record the IDs at the end" → write back each step, or resume/teardown strands resources.
- "Run everything, verify at the end" → verify each step before advancing.
- A plan with no teardown or no verify sections → it isn't an Ephemera plan.

---

**Install (for a human):** drop `EPHEMERA.md` into a repo and add a short pointer to whatever agent
instruction file the repo already uses (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules`, `GEMINI.md`) — e.g.
*"This project manages infra as Markdown plans; read `EPHEMERA.md` and follow it."* Any AI+human pair,
on any runtime, then picks it up. Nothing personal to install.
