# Epok cloud setup — guide for unattended agents

Published at `https://epok.cloud/setup/AGENT-GUIDE.md`. Read this before you run any Epok setup
manifest (`https://epok.cloud/setup/<id>.json`). The manifest is the source of truth; the
generated `SKILL.md` files and the scripts (`gcp.sh`, `aws-logs.sh`, `aws-metrics.sh`) are made
from it.

## AWS downloads

In the unattended AWS sandbox, you are already in your writable working directory,
`/work`; download the files here. No directory creation or `cd` step is needed.
Run each download as a single command:

```bash
curl -fsSL https://epok.cloud/setup/aws/AGENT-GUIDE.md
curl -fsSL https://epok.cloud/setup/aws/aws-logs-firehose-cfn/SKILL.md
curl -fsSL https://epok.cloud/setup/aws/aws-logs-firehose-cfn.json
curl -fsSL -o aws-logs.sh https://epok.cloud/setup/aws/aws-logs.sh
curl -fsSL https://epok.cloud/setup/aws/TROUBLESHOOTING-aws.md
```

For an authorized local sandbox test, use the exact tunnel URLs in your task
instead of the public URLs above. Only those exact downloads are permitted.
Use `epok-setup` to install and verify, and `epok-setup --uninstall` when removal
is requested; the sandbox wrapper verifies the downloaded script's checksum.
Optional `mkdir -p`, `cd`, `ls`, and `pwd` are supported only within `/work`.

## AWS console: Launch stack

The published [template manifest](https://epok.cloud/setup/aws/published-templates.json) records the regional
S3 HTTPS URLs, object VersionIds and SHA-256 hashes. Use the URL for the customer's
region (`eu-central-1` or `us-east-1`); immutable keys pin the template bytes.

- **Read-only inventory and change events:** `epok-readonly-role.yaml` creates
  `EpokReadOnly-<suffix>` under `/epok/`. It is a separate stack from Firehose.
- **CloudWatch logs and metrics:** both `*-cfn.json` manifests deploy
  `epok-integration.yaml`. Logs use `EnableLogs=true, EnableMetrics=false`;
  metrics use `EnableLogs=false, EnableMetrics=true`. Enter `EpokApiKey` in the
  console's NoEcho field; never include an ingest key in a launch URL.
- **S3 logs:** `epok-s3-forwarder.yaml` uses the versioned Lambda release in
  `deploy/aws/s3fwd-releases.json`. Its setup script must first create the SSM
  SecureString and configure bucket notifications; a launch link alone does not
  perform those prerequisites.

For the read-only role, use the **Launch stack** URL returned by the authenticated
AWS registration/list API at
`/api/v1/tenants/<tenant>/integrations/aws`, field
`cloudformation.quick_create_url`. The server inserts that integration's External
ID, principal account/ARN and role suffix. It remains behind
`EPOK_AWS_ROLE__ENABLED` and the existing tenant allowlist. Do not invent an
External ID or use the publishing account as the trusted principal.

Launch stack link pattern (URL-encode each value; placeholders are not credentials):

```text
https://console.aws.amazon.com/cloudformation/home?region=<region>#/stacks/quickcreate?templateURL=<regional-readonly-template-url>&stackName=EpokReadOnly&param_ExternalId=<app-generated-id>&param_EpokPrincipalAccountId=<app-principal-account>&param_EpokPrincipalArn=<app-principal-arn>&param_EnableChangeEvents=true&param_RoleNameSuffix=i<integration-id>
```

Review the template and acknowledge `CAPABILITY_NAMED_IAM`, then launch it in the
customer account. Copy its `RoleArn` output (including `/epok/`) back to Epok for
verification. Keep tenant-specific launch URLs out of logs, shared docs and commits.
For Firehose, use the same console route with the published `epok-integration.yaml`
URL, `stackName=epok-logs` (or `epok-metrics`), `param_EpokIngestHost`, and the two
`param_EnableLogs` / `param_EnableMetrics` values above; choose log groups in the
console. Its capabilities are `CAPABILITY_IAM` and `CAPABILITY_AUTO_EXPAND`.

## The seven rules

1. **Fetch the manifest and check the schema.** `schema` must be `epok.setup-manifest/1`. If it
   is anything else, stop: you do not know its rules. If `last_verified` is `null`, the Epok
   harness has not yet run this manifest end to end; say so in your report.
2. **Run the prerequisites.** Run every `prerequisites.cli[].check` and
   `prerequisites.check_commands`. If one fails, or a permission in
   `prerequisites.permissions` is missing, stop and ask a human. **Never grant IAM to
   yourself** and never ask for broader roles than the list.
3. **Get the key from the environment.** `EPOK_API_KEY` is an ingest-scope key that a human
   creates in the Epok UI (Settings → API Keys → New key, scope ingest, name
   `gcp-pubsub-<project>` or `aws-firehose-<account>-<region>`). If it is not set, stop and ask.
   Never create, guess, print, log or write the key to a file or a commit. Never put the key in a
   URL. It goes to exactly two places: the `X-API-Key` header of calls to Epok and, for the AWS
   manifests only, the CloudFormation stack's NoEcho `EpokApiKey` parameter, passed on stdin by
   the `create-stack` step (Firehose sends it to Epok as `X-Amz-Firehose-Access-Key`). Never pass
   it with `--parameter-overrides` or any other command-line argument.
4. **Run the steps** in order, exactly as written, or run
   `python3 scripts/epok_setup.py <manifest> --json-transcript epok-setup.json` (it does the same
   thing, masks the key and records a transcript). Run `--dry-run` first if the user wants to see
   the plan. A step with an `idempotent_check` is skipped when the check exits 0. A step with
   `exports` prints `NAME=value` lines; set those as environment variables for later steps.
   Read the lines; never `eval` server output.
5. **Run `verify` and report the JSON.** Emit the canary, then poll the status call every
   `poll_seconds` up to `timeout_seconds`. Success means the field in `verify.success`
   (`seen_at`) is not null. Report the full status JSON.
6. **On failure, report; do not improvise.** Report the failing step, its output (with the key
   masked), and the matching `failure_modes` rows (rows whose `step` names the failed step, or
   `verify`). Apply a row's `fix` only when it is non-destructive and the row is not marked
   `stop_and_ask`. Never delete, replace or modify a resource you did not create in this run.
7. **Never run `uninstall` unless the user asked for removal.** Uninstall is destructive. Every
   uninstall step tolerates resources that are already gone; run all of them and report each
   result.

## Stop and ask a human

Stop, explain what you found, and wait for the human when:

- `EPOK_API_KEY` is missing, rejected (HTTP 401/403), or the bindings call returns 404 (Epok has
  not enabled cloud integrations for this account yet — the human contacts Epok support).
- A step fails with a permission error (PERMISSION_DENIED, `iam.serviceAccounts.actAs`, 403).
- The user wants an **organization- or folder-level sink**. The manifests are project scope only;
  an org/folder sink routes other teams' logs and needs an org admin.
- A sink, topic, subscription or service account **with the same name already exists with a
  different configuration** (ALREADY_EXISTS after a failed idempotent check). It may belong to
  someone else. Do not delete, import or modify it. Offer another `EPOK_RESOURCE_PREFIX`.
- A step would **replace an existing policy** (for example a whole IAM policy, a log exclusion
  or a bucket policy) rather than add one binding. The manifests only add bindings.
- The **estimated cost is above $5/day**. Estimate from the manifest's `cost_notes`: Pub/Sub bills
  about $40/TiB with a 1 KB minimum per message, so cost/day ≈ entries/day × max(1 KB, average
  entry size) × $40/TiB. If you cannot estimate entries/day, ask before widening the sink filter
  beyond the default.
- Any **IAM grant to a principal outside the project**. Expected principals are only: the push
  service account the setup creates, this project's Google-managed Pub/Sub service agent
  (`service-<PROJECT_NUMBER>@gcp-sa-pubsub.iam.gserviceaccount.com`) and the sink's writer
  identity. Anything else, stop.
- **AWS:** the user wants every log group (`LogGroupScope=account-policy` replaces the account's
  subscription filter policy) or every metric namespace (`EPOK_METRIC_NAMESPACES=all`); a log
  group already has 2 subscription filters; a stack with the same name exists in any state other
  than `CREATE_COMPLETE`/`UPDATE_COMPLETE`; or more than one region is plausible (the stack is
  regional — ask which regions). AWS cost per day ≈ Firehose $0.029/GB of log groups' daily
  bytes, or Metric Streams $0.003 per 1 000 updates (one update per metric per minute).
- A failure-mode row is marked `stop_and_ask: true`.
- The user asks for anything the manifest does not cover (a different region of Epok, a custom
  endpoint, a pull subscription, GCP metrics, AWS S3-only logs such as ALB access logs).

## Standard final report

End every run with one JSON object in a fenced block. `scripts/epok_setup.py` prints this shape
as its last output. Never include the key.

```json
{
  "manifest": "gcp-logs-pubsub-push",
  "manifest_version": "1.0.0",
  "manifest_sha256": "<sha256 of the manifest without last_verified>",
  "last_verified": null,
  "result": "pass",
  "mode": "install",
  "exit_code": 0,
  "failed_step": null,
  "steps": [
    {"id": "enable-apis", "status": "ran"},
    {"id": "create-topic", "status": "skipped"}
  ],
  "exports": {
    "EPOK_BINDING_ID": "b_0123456789abcdef0123456789abcdef",
    "EPOK_PUSH_ENDPOINT": "https://ingest.getepok.dev/api/v1/gcp/pubsub/push/b/b_0123456789abcdef0123456789abcdef"
  },
  "status": {
    "source": "gcp_pubsub_push",
    "seen_at": "2026-11-09T10:00:00Z",
    "requests_24h": 3,
    "records_accepted_24h": 3,
    "records_rejected_24h": 0,
    "last_error_reason": null
  },
  "failure_modes": [],
  "stopped_for_human": null,
  "message": "setup complete and verified"
}
```

- `result` is `pass`, `fail` or `needs_input`.
- `steps[].status` is `ran`, `skipped`, `failed` or `dry_run`.
- `stopped_for_human` is `null` or one sentence saying what the human must do.

## Exit codes of `epok_setup.py` and the generated scripts

| Code | Meaning |
|---|---|
| 0 | Done (and verified, for install) |
| 1 | A step or prerequisite failed; see the printed failure modes |
| 2 | Verify timed out (`seen_at` still null) |
| 3 | A required input is missing or invalid — ask the human |
| 4 | Manifest unreadable or unsupported schema (runner only) |

## Final line (machine-read)

End your answer with exactly one line, the last line, in this format:

```
EPOK_SETUP_RESULT {"seen_at": "<RFC3339 seen_at from the verify call, or null>", "nonce": "<nonce from the verify JSON>", "prefix": "<EPOK_RESOURCE_PREFIX>", "result": "pass|fail"}
```

`seen_at` is the "data arrived" time the status call returned for that `nonce`; Epok checks it against its own record. Report it verbatim; never invent
it. Do not edit or patch the setup script or manifest; if a step fails, report the failure-mode
row and stop.
