# Troubleshooting (Read This When Stuck)

Read this when a setup step fails or hangs, before guessing. It is ordered
like the setup steps. Each entry gives what you see, the likely cause, how to
find out, and the fix or the topic that holds the detail. Quoted messages are
the real ones; a symptom with no message of its own says what to look at
instead.

Two rules first:

- Read the whole error. A failed claim, `verify-env`, `run` or seed prints
  the failing step and the end of that script's stderr: the cause is
  there. Fix what it names, not what you suspect.
- Never put a secret or token into a command line, a definition, a log you
  paste or a feedback message. Secrets go through `secret set` (`secrets`).

## The tools you have

- `cofactor sandbox show <id>`: Status, the `error` line, per-port URLs,
  persona logins, seed steps with timings. First stop for a claim that
  failed or is slow.
- `cofactor sandbox claims`: Your live claims (find a lost id).
- `cofactor sandbox exec <id> -- <command>`: One shell command in a ready
  sandbox, from the definition's directory, with the environment actions
  get. No interactive shell.
- `cofactor sandbox exec <id> -- cofactor-sandbox status`: The supervisor's
  view of every service and the emulator.
- `cofactor sandbox exec <id> -- cofactor-sandbox restart <service>`:
  Restarts a service, waits until healthy, prints its status. An unknown
  name lists the sandbox's services.
- `cofactor sandbox exec <id> -- tail -n 100 /var/lib/cofactor/logs/<service>.log`:
  A service's log. The emulator's is `/var/lib/cofactor/logs/emulator.log`.
- `cofactor sandbox run <id> <action> --input k=v`: Runs one action by hand.


- `cofactor sandbox auth-check <id> --persona <name>`: Signs one persona in;
  exits nonzero on failure.


A snapshot that failed to build leaves no sandbox to `exec` into (the
builder is destroyed): see 5 and 8.

## 1. Login and account

- `"Error: No API token found."` followed by `"Run: canary login"`, or
  `"Error: No token stored for org "X"."`, or
  `"Error: No token found for "prod" profile."`

  Not signed in, or signed in to another organization or stage.
  Fix: `cofactor login` (with `--org <name>` or `--env <stage>` when the
  message says so), then `cofactor orgs` to confirm the organization.

- `cofactor github connect`: "this command needs a signed-in session with an
  organization. Run "cofactor login" and try again."

  The session has no organization. Sign in again.

- `exec` or `sync` refused when using an API key

  A key needs the `sandbox:exec` scope: see `cli`, the `exec` entry.

## 2. Application and repository

Which application? `cofactor application list` (alias `property list`).
"Error: Application "X" not found." is followed by the list. A new name
is created by `connect`, `push` or `claim --from-local`: you do not
create it first (`overview`). Linking a repository to the application for
the rest of Cofactor is `cofactor property repo link --application A
--repo owner/name`; sandbox delivery itself is `connect`.

- "GitHub repository owner/name is inaccessible to this organization", or
  "the organization's GitHub is not connected"

  The Cofactor GitHub App is not installed for the organization, or cannot
  see that repository (GitHub answers 404 for both).
  Diagnose: on a connected organization `cofactor github connect` prints
  the connected account and every repository the App can see.
  Fix: installing the App is the user's decision (see WHEN TO STOP AND
  ASK).

- `cofactor github connect` ends with "timed out waiting for the
  installation. Approve it in a browser signed in to Cofactor as a member of
  this organization ... then run "cofactor github connect" again."

  Nobody approved the install in the browser (it needs an organization
  admin). Ask the user; do not retry in a loop.

- `connect` fails with "the application's sandbox definition was not found at
  that version" or `"the application's sandbox definition is invalid: <path>:
  <message>"`

  Without `--at`, `connect` reads cofactor.sandbox.yaml at the default
  branch's head, and that version must hold a valid one. A refusal creates
  nothing.
  Fix: for a definition that is not merged, use `connect --at
  <full-branch-sha>` or `claim --from-local` (CLI 0.56.0 or later; no
  merge). In a monorepo pass `--dir <path>` to the directory holding the
  file. See `cli`, "Setting up a new GitHub application".

- "This application's sandboxes are not set up: connect its repository with
  `cofactor sandbox connect`, or push a built image with `cofactor sandbox
  push`."

  A claim for an application that was never connected or pushed. Do one.

- `"repository pin "X" is repeated"`, `""X" is not a repository in this
  application"`, `"the pin for owner/name must be a 40-character commit SHA"`,
  `"an exact revision cannot be combined with repository pins"`

  A bad `--at` on a multi-repository claim. Pins need the full 40-character
  SHA, a repository the definition declares, each once; `--at rev-<id>`
  takes no other `--at` (`cli`).

- THE APP SPANS MANY REPOSITORIES

  GitHub delivery supports it: the definition's `repos` lists additional
  repositories, checked out beside the definition repository, and a claim
  pins each with `--at <repo>=<sha>` (CLI 0.58.0 or later; `definition`, `cli`). The limits
  are in `definition`: members must be under the same owner as the
  definition repository, and the GitHub App must see every one, or the
  claim fails with "GitHub repository owner/name is inaccessible to this
  organization". Use `repos` when every repository is under one owner
  the App can reach. Use a pushed image (`upload`) when the repositories
  are under different owners, the user will not give the App access to
  them, or the app is already built by CI from several checkouts: the
  image holds everything built, and `repos` and `repo` are not allowed in
  an uploaded definition.

  Building that image in GitHub Actions: the job's default GITHUB_TOKEN
  only reaches the workflow's own repository, so checking out other
  private repositories needs another credential. The options, from
  GitHub's docs:

  - A GitHub App installation token (actions/create-github-app-token):
    expires after 1 hour, limited to the listed repositories and
    read-only with `repositories:` and `permission-contents: read`, and
    not tied to a person; the user creates a private App and stores its
    client id and private key as secrets.
  - A fine-grained personal access token stored as a secret: the
    simplest to set up, but tied to a person, it expires, and each
    repository must be granted to it.
  - Deploy keys: read-only, but one key per repository, so several
    repositories need several keys.

  Present these to the user and let them choose (STOP AND ASK).
  `cofactor sandbox push` itself needs only an API key with the push
  scopes, as in `upload` (the CI API key paragraph before Nightly push from GitHub Actions).

## 3. Validate errors

`cofactor sandbox validate` is offline and prints one line per problem with
a dotted path:

```text
environments.default.seeds[0].input.workspace_id: references step "acme", which has not run yet (or does not exist)
environments.free-plan.extends: unknown environment "defualt"
ports.emulation: "emulation" is a reserved port name
```

Fix the field the path names and rerun. It catches unknown actions or
operations in a seed, a `${id.key}` pointing at a later step or an
undeclared output, an `extends` cycle, a duplicate step id, an unknown
emulation plugin, port 80 or 443 with emulation on, the 8-port cap and
more. It runs nothing, so it cannot prove a command, URL or seed works:
only a claim does. Topics: `verify`, `definition`, `environments`,
`seeds-and-actions`, `ports`.

Use `validate --upload` only for a pushed image (no `setup`) and plain
`validate` for a GitHub application. For a checkout without a GitHub
remote, pass `--repo owner/name` (CLI 0.58.0 or later).

A claim can still fail with "`<file>` is invalid:" plus the same problem
lines. When it adds "An unrecognized key is usually a feature this Cofactor
doesn't support yet; it works once Cofactor is updated.", upgrade the CLI
and check the key against `definition` before assuming a typo.

## 4. Connect, push and import

`sandbox push` refusals (no docker, not linux/amd64, USER not root, bad
WORKDIR, a layer over 5 GB, an upload "was refused", "this Cofactor takes
pushes from an older cofactor CLI") each name their own fix: see `upload`,
WHAT THE IMAGE MUST BE. Alpine and distroless images do not work.

- `"push <id> failed: The Dockerfile build failed (build): ..."`

  A step of the Dockerfile failed while Cofactor built it; the build log
  `push` printed shows the step and its output. `(limit)` means the image
  or its build outgrew Cofactor's limits (8 GB of image, 127 layers);
  `(timeout)` that the build ran past 60 minutes. Fix the Dockerfile or
  the context and push again: an unchanged context reuses its build.

- `"push <id> failed: Cofactor could not start this image ..."`

  A service exited or never turned healthy while Cofactor booted the
  image. The message ends with that service's log. Reproduce with `docker
  run --rm -it --entrypoint bash <image>` and run the service's `run`
  command from the WORKDIR (in a sandbox it runs as uid 1000). See 7.

- `"this push carries Cofactor's sandbox helper vN, but sandboxes now need vM:
  push the image again"`, or a sandbox "saved on an older platform version"

  The image predates the current sandbox platform: `cofactor sandbox push`
  again. A claim that prints "updating this push to the current sandbox
  platform (once; the claim continues after)" upgrades it for you.

- "Cofactor is being updated: try this claim again in a few minutes"

  A deploy is in progress. Wait, then claim again.

- `"push <id> has not been imported"`, `"push <id> no longer exists"`

  The push never finished or was removed. Push again.

- `exec` says "This sandbox was built on an older platform; exec works once
  it is rebuilt on a newer one."

  Claim a sandbox from a fresh snapshot (a new push, or a new commit).

## 5. Build failures (GitHub)

A claim for a commit with no ready snapshot builds it first: `setup` and
`lifecycle.build` steps, then `prepare`, then the seeds. A failure in any
of them fails every claim waiting on it, with the step and the end of its
stderr:

```text
<step>: <message>
<label> failed (state <state>, exit <code>): <stderr>
```

The next claim of that commit builds again, so a failure that repeats
needs a changed source version, not a retry.

Diagnose: read the error from `claim --wait` or the `error` line of `show`.
No live sandbox exists for a failed snapshot, so reproduce by running the
same commands in the repository's checkout, not in a local container
(`overview`: a local Docker build proves nothing about a sandbox).
Exit 127 is a command the image lacks; secrets are not injected into
`setup` or `lifecycle.build` (`secrets`).
Fix without merging: `validate`, `claim --from-local --wait` (0.56.0 or
later), then `verify-env --at <source-sha>`.

## 6. Claims that hang, time out or fail

- `"Error: timed out waiting for sandbox <id> to become ready (N min)"`

  The CLI stopped waiting; the sandbox is still yours and its lease runs.
  Diagnose: `cofactor sandbox show <id>`. The first claim of a commit
  builds the snapshot (minutes for a cold toolchain, seconds once it
  exists); `show` splits the time into snapshot, restore and prepare. A
  second claim of the same commit and environment joins the same build, so
  starting more does not speed it up. Raise the limit with `claim
  --timeout`, and `destroy` claims you no longer need.

- `"the sandbox was not ready by its time limit; the last problem: <...>"`

  The claim hit its limit (2 hours unless `--timeout`). The tail is the
  last real problem it met: act on that. It can arrive up to about 10
  minutes after the limit.

- `claim --wait` exits 1 with the sandbox failed

  Read the `error` line it printed (the same as `show`) and go to the entry
  for that stage.

## 7. Services not starting, health and ports

A service that exits, or whose `health` never passes (the http path answers
below 400, or the command exits 0, within 5 minutes of starting), fails
the build or the push import, with that service's log at the end of the
message. In a ready sandbox:

- `exec <id> -- cofactor-sandbox status` for which service is down, then
  `exec <id> -- tail -n 100 /var/lib/cofactor/logs/<service>.log`;
- `exec <id> -- cofactor-sandbox restart <service>` after a fix;
- check the `run` command works from the definition's directory (or the
  image's WORKDIR) as an unprivileged user (uid 1000): anything the app
  writes must be under that directory or /tmp (`upload`).

A service that needs the copy's own values (its public URL, a
`{secret: true}` param, a stored secret) and sees a placeholder or nothing
needs `reload_on_prepare: true` (`env`, `secrets`, `upload`).
After `sync`, services keep running the old code: restart them, or `sync
<id> --build` (`local`).
A frontend that calls the wrong API origin (the production one, the
build machine's, `localhost`), or crashes on `new URL()` with a relative or
empty base: the bundle has an origin baked in at build time, or the app
detects sandboxes by a hostname pattern that a Sandboxes v2 host
(`<label>.sbx.<zone>`) does not match. Each port of each copy has
its own host, and `lifecycle.build` runs before any copy exists. Swap a
placeholder for the API origin when the page is served, or use a same-origin
`/api` path; see
"Each port and copy has its own origin" in `ports`. `exec <id> -- curl -s
localhost:<port>/` shows what the served page contains.

Port questions (the 8-port cap, ports 80 and 443 reserved with emulation
on, `{port}` params, OAuth callbacks on the port that serves them): `ports`.

## 8. Seeds and actions fail

A failed seed fails the snapshot, naming the step, its action and the
script's stderr (everything an action prints besides its final `{...}`
result line goes to stderr, so the real error is there). `run` prints "Run
failed: `<error>`" and then "stderr:" with the tail.

- `run` with bad input prints the action's input schema instead of
  running; "unknown action or operation "X"" lists the real actions and
  operations; "unknown input "k". Known: ..." lists the declared inputs.
- A seed that signs in can trip the app's login rate limit: `personas`.

The procedure (claim without the failing step, run the action by hand with
the same inputs, fix, re-prove) is `verify`, WHEN A SEED FAILS. Rules for
writing them: `seeds-and-actions`. Stale dates in a dump:
`data-fast-forward`.

## 9. Persona sign-in and auth-check fail

`verify-env` prints `signed in` per persona, or FAILED with the script's
exit code and the end of its stderr; `auth-check` checks one:

```text
sandbox authentication failed: script_failed (persona "admin":
sandbox/auth.sh exited 127). Its stderr ended:
sandbox/auth.sh: line 4: curl: command not found
```

Exit 127 is a command the image lacks. Reason codes, the script contract and
what to print are in `authentication`.

- `show` prints "(no authentication.run: native Login nodes fail with
  script_not_declared)": the definition has no `authentication`; add it
  (`authentication`).
- The password is rejected: `lifecycle.prepare` must read
  `COFACTOR_PERSONAS` and make each login work, read per sign-in rather
  than once at startup; clear any first-run gate (terms, email
  verification, onboarding) there too (`personas`).
- Frontend-only sandbox: the generated password is unknown to the
  backend; the script reads `<PERSONA>_PASSWORD` from the secret store
  (`feasibility`, THE ESCAPE HATCH).
- Google sign-in (`authentication.emulated`) fails with a reason code
  (`sign_in_unreachable`, `callback_origin`, ...): see `authentication`;
  the emulator log is /var/lib/cofactor/logs/emulator.log.
- `sync` does not apply persona or prepare changes: claim again
  (`local`).

A person signs in by hand with the email and password `show` prints. No
command returns a signed-in browser session (`personas`).

## 10. Emulator issues

`emulation` holds the detail for each plugin; these are the first checks.

- The app calls a service with no emulator. In this order:
  1. Check the current list. There is no live registry to query: the
     plugin list in `emulation` and the table in `feasibility` are
     bundled in the CLI, so they are as new as the CLI. Upgrade it
     (`cofactor upgrade`), then reread both. A service
     the table marks `native` or `real` needs no emulator.
  2. Write your own: `emulation.scripted` runs a script from your
     repository that answers the service's domains (`emulation`,
     SCRIPTED EMULATORS). It is any HTTP server on a loopback port, in
     any language you can install in `setup` or the image; the guide's
     example is Python (standard library only).
  3. A STATEFUL service (a search index, vector database, queue,
     document store, a self-hosted auth server holding users) is more than a
     script should fake: run an open-source server for it as a service
     (`definition`, its `services` key) and bridge the app to it. How, from what
     the platform does today:
     - Domain interception (`emulation`) reverse-proxies each HTTP
       request on your declared domains to `http://127.0.0.1:<port>`. No
       plugin forwards a domain to a service on its own.
     - The app's client takes an endpoint setting (for example
       `AWS_ENDPOINT_URL_SQS`): set it in `env` to the service. This
       needs no interception; the `feasibility` table already names
       stand-ins this way. A non-HTTP protocol (Kafka) can only be
       reached this way.
     - The app hardcodes the provider's domain and the server speaks
       the provider's HTTP API (wire-compatible): declare the server as
       the scripted emulator itself (`run: exec <server>`, `port`: the
       server's own port), or run it as a service and put a thin
       proxy script in front. The scripted emulator's health check is
       `GET /` below 400, so confirm the server answers it.
     - Not wire-compatible: the scripted emulator is a translator,
       turning the provider's calls into the server's API, with the
       state kept in the server. Run it in a claimed copy to prove the
       script can reach the server on 127.0.0.1; nothing here shows a
       translator working end to end.

     Verified from each project's or provider's own docs:

     - Wire-compatible: ElasticMQ implements a subset of the SQS query
       (REST) interface (a stand-in for SQS; check the operations the
       app uses); Azurite emulates Azure Blob, Queue and Table (Table is
       in preview; it uses the account name in the URL path unless you
       set up production-style URLs); Redpanda is compatible with the
       Kafka API (reached by endpoint setting, not a domain); the Firebase Local Emulator Suite covers Firestore and
       Authentication, among other products.
     - Needs translation: Meilisearch (MIT, its own REST API) for
       Algolia, whose docs offer a migration guide and no API
       compatibility; Qdrant (Apache 2.0, its own REST and gRPC APIs)
       for Pinecone, with no Pinecone compatibility claimed.

     Auth0 and Okta need no server: `emulation.oidc` covers them
     (`feasibility`, `authentication`). DynamoDB, Pub/Sub, Postgres and
     the rest of the `native` rows are in the `feasibility` table.
     Data in such a service is seeded like any other, through seeds
     and actions (`seeds-and-actions`).
  4. If no alternative exists and the state matters to the journey, it
     is unsupported for now: stop, tell the user, and ask them how to
     proceed with your question tool (STOP AND ASK).
- `validate` reports an unknown emulation plugin, or port 80 or 443
  declared while emulation is on.
- The app still reaches the real provider: the calling service lacks
  `reload_on_prepare: true` or does not trust /etc/emulation/ca.crt, or
  the app uses an SDK client for a service the definition gives no
  section (`feasibility`, the AWS paragraph).
- The build fails with: emulation references the secret "NAME", which is
  not set for environment "E"; set it with `cofactor sandbox secret set
  NAME --application <application>`.
- See what the emulator did: `cofactor sandbox envs --application A`
  lists the operations, `cofactor sandbox run <id> <plugin.op>` runs one
  (for example `email.sent-emails`), and
  `exec <id> -- tail -n 100 /var/lib/cofactor/logs/emulator.log` shows
  its log.

## 11. Secrets

`secret set` refusals (bad name, value not 8 to 8192 bytes, stdin a
terminal) name the rule: `secrets`. "No secret with that name and scope."
from `secret rm`: `secret list` shows names and scopes.
A service sees no secret: only `reload_on_prepare` services, prepare, seeds,
actions and `authentication.run` receive them, never `setup` or
`lifecycle.build`.
A changed or removed secret has no effect on existing snapshots
(`secrets`, ROTATION). Never ask for a value in chat.

## 12. Verify-env fails

A failed environment prints "claim failed: ..." (go to 5 to 8) or a persona
FAILED (9). "Error: environment "X" not found. Known: ..." lists the
definition's environments. Prove the final source with `verify-env --at
<source-sha>` (`verify`, `cli`).

## When to stop and ask the user

These decisions are theirs. Stop, say what you found, and ask:

- Installing or approving the Cofactor GitHub App, or granting it a
  repository (`cofactor github connect` needs an organization admin in a
  browser).
- Any secret value, and which provider test key to use. Give the user
  `printf %s "$KEY" | cofactor sandbox secret set NAME --application A`
  to run in their own shell; never use a real credential where the
  provider has a test mode.
- A GitHub App-versus-token choice for building a multi-repository image,
  and giving the Cofactor GitHub App access to extra repositories.
- Anything `cofactor sandbox guide feasibility` marks unsupported,
  unknown on a journey the user cares about, or `real` with no test mode
  and no stand-in: leave the journey out, disable the feature, stub it,
  sign in another way, or the frontend-only escape hatch.
- Which backend a frontend-only sandbox points at (never production).
- Merging the definition to the default branch.

Also stop when the same error comes back after two real fixes, and report
it rather than looping.

## Reporting a problem to Cofactor

When a guide topic, message or command was wrong, missing or confusing, or
a platform failure is not yours to fix:

```bash
cofactor feedback "<what happened and what would have helped>" --topic <topic> --command "<command>"
```

`<topic>` is one of skill, instructions, tool, confusing, bug, other.
The text is limited to 4 KB, and only the CLI version and your agent kind
are attached. Sanitize it: no secrets, tokens, customer data, real names,
emails or URLs. Name the step and the command, and quote the error with
values removed, using neutral examples (Acme, example.com).
