# Failure classification and optional autofix

Classification needs only uploaded runs and an organization owner enabling
`classify` in the web app at `$SHIPLIGHT_WEB_URL`. It needs no workflow step
and no `upload-report`: the backend already has the evidence. Both `classify`
and `autofix` start off. Enable `classify` before enabling `autofix`.

Autofix is optional, only when requested. Confirm autofix before adding it:
it runs an agent and opens PRs with proposed test changes. Diagnosis alone does
not authorize this workflow. Preserve existing test workflows and their uploads.

## Resolve the deployment and pins

Read [the secrets policy](../_shared/secrets.md) and
[the project layout](../_shared/project-layout.md). Read `SHIPLIGHT_API_URL`
from the shell first, then the test project's `.env` as text, never by sourcing
it. There is no default host. If absent, stop and ask for it; never guess a public
host. Resolve `SHIPLIGHT_WEB_URL` the same way before linking to the web app.
Require the repository variable `vars.SHIPLIGHT_API_URL` to point to the same
backend; if missing, ask the user to configure it.

An organization owner signs in to the web app at `$SHIPLIGHT_WEB_URL`, opens
organization token creation, and creates an organization token with **only**
the `autofix:run` scope. Store it as the repository secret `AUTOFIX_API_TOKEN`.
This scope is explicit-only: a full-access CLI token does not include it, and
cannot mint it through bearer authentication. Never expand the test token's
scopes to include it. Keep the autofix token only in `prepare` and `publish`.

For setup, accept the scoped token pasted by the user into a masked shell prompt;
never write its value to a file or echo it. For example, in Bash:

```bash
read -r -s -p 'Autofix token: ' AUTOFIX_API_TOKEN; printf '\n'
export AUTOFIX_API_TOKEN
curl -q -sS --proto '=https' --fail-with-body \
  -H "Authorization: Bearer $AUTOFIX_API_TOKEN" \
  "$SHIPLIGHT_API_URL/v1/autofix/runner"
unset AUTOFIX_API_TOKEN
```

Read the response's `current.version` and `current.sha256` and write them into
`AUTOFIX_RUNNER_VERSION` and `AUTOFIX_RUNNER_SHA256` in the asset. Never copy a
version or hash from this guide, and never use the download's `X-Content-SHA256`
header as the trust anchor. The index has `current` and, when available,
`previous`, each with `version` and `sha256`; it is served with `Cache-Control:
no-store`. The version route `/v1/autofix/runner/{version}` returns script bytes.

Authentication is checked first (401), then scope (403 naming `autofix:run`),
then the organization switch. On a missing-scope 403, stop setup and request the
scoped organization token. A 403 with exactly `{"error":"autofix_disabled"}` means
the token has the scope but an owner must enable autofix: stop setup and explain
that. If autofix is turned off later, the workflow's download step treats this
specific 403 as a green no-op with `tasks=[]`. All other download errors fail,
including network errors and other 403s. Pending classification polls for up to
300 seconds by default; if still pending, re-run the job later.

Every job checks the same SHA-256 pin before executing the runner. A mismatch
fails before execution; never pipe curl into a shell. For an intranet `http` URL
only, remove `--proto '=https'` from the setup command and download step.
Upgrading means fetching the index again and changing both pins together in one
commit. The previous release remains served for one deployment upgrade; older
pins fail with 404 naming the current version. A withdrawn unsafe version returns
410. Re-read the index and review the replacement before re-pinning either case.

## Adapt the four-job caller

Copy [assets/ci-autofix.yml](assets/ci-autofix.yml) to the repository root's
`.github/workflows/ci-autofix.yml`. Replace the workflow-name
placeholder with the exact test workflow's top-level `name:`; never watch itself.
Replace both pin placeholders from the index before enabling the workflow.

The `workflow_run` caller rejects forks in every job. `prepare` checks out the
trusted default branch, records `baseSha`, and uploads `autofix-prepare` with the
pinned runner and task data. `fix` checks out exactly `baseSha`, runs the agent
without a project install or tests, and uploads a candidate per task. `verify`
uses its own fresh machine and checkout at `baseSha`, installs the project and
browsers, applies the candidate, and re-runs tests twice. `publish` downloads the
artifacts, validates them, pushes and opens the PR without executing project code.
Every checkout uses `persist-credentials: false`.

Keep `prepare`'s `pull-requests: read` permission and its read token for checking
existing PRs. Keep `publish`'s per-target concurrency group
`autofix-publish-${{ github.repository }}-${{ matrix.task.slug }}` with
`cancel-in-progress: false`, to serialize publishers of the same target.
`verify` and `publish` retain `!cancelled()` so one failed matrix leg does not
suppress other tasks. Missing candidates or verification artifacts are tolerated:
a failed fix is skipped, and missing verification yields `not_run`.

Pass the Claude credential only to `fix`. The agent is Claude Code; there is no
Codex fallback. An optional `AUTOFIX_AGENT_GATEWAY=true` uses the deployment's
model gateway with `AUTOFIX_AGENT_GATEWAY_TOKEN` holding only `llm:invoke`.
Pass the test-only `SHIPLIGHT_API_TOKEN` and app test secrets only to `verify`;
its full-access CLI token lacks `autofix:run` and passes the scope probe. If `fix`
needs a backend credential, it too must lack that scope. Both untrusted jobs
probe every backend credential they receive and fail closed unless the response
positively reports the missing `autofix:run` scope. Neither `AUTOFIX_API_TOKEN`
nor `AUTOFIX_PUBLISH_TOKEN` belongs in `fix`, `verify`, workflow-wide env, project
files or `.env` files. Only `publish` gets `AUTOFIX_PUBLISH_TOKEN`.

`publish` opens the PR with `github.token`, which GitHub lets create pull requests
only when the repository allows it, even with `pull-requests: write`. Check before
adding the workflow: `gh api repos/OWNER/REPO/actions/permissions/workflow` must
report `"can_approve_pull_request_reviews": true`. If it is `false`, ask the user to
enable **Settings → Actions → General → Workflow permissions → Allow GitHub Actions
to create and approve pull requests**; otherwise `publish` pushes the branch and then
fails with `pr_failed`. If organization policy forbids that setting, set
`AUTOFIX_PUBLISH_TOKEN` in `publish` to a repository secret instead: a GitHub App
installation token or a fine-grained token limited to this repository with
Contents and Pull requests write. It still goes only to `publish`.

Set `AUTOFIX_WORKING_DIRECTORY` to the test project's repository-relative path
(default `.`), without `..`. Keep `AUTOFIX_ALLOWED_PATHS` narrow and identical in
fix, verify and publish; paths are relative to that project. For monorepos testing
several projects in one CI run, inspect the installed CLI version and confirm it
sends `projectPath`; upgrade if it does not. `project_unknown` warns that uploaded
runs cannot be distinguished reliably. Do not assume a historical version cutoff.

Write the install step from that project's lockfile: `package-lock.json` means
`npm ci`; `pnpm-lock.yaml` means `pnpm install --frozen-lockfile` (set up pnpm);
`yarn.lock` means `yarn install --immutable` (set up Yarn). If none exists, stop
and ask for the project's install command. The asset assumes npm; adapt it before
use. The install belongs in `verify`, before the runner, never in `fix`.
The CI machine needs browsers; the sample installs Chromium, so adapt that to the
project's Playwright configuration. Keep `AUTOFIX_TEST_COMMAND: npx shiplight test`
(or a supported direct CLI test invocation); shell chains and `npm run` wrappers
are refused. Verification adds `--no-publish` and forces upload settings off;
do not re-enable uploads in `.env` or test setup.

## Choose isolated machines

Confirm which machines `fix` and `verify` use before enabling the workflow.
The sample uses separate GitHub-hosted `ubuntu-latest` jobs, detected through
`RUNNER_ENVIRONMENT=github-hosted`, with no declaration needed. `prepare` and
`publish` also use hosted runners and need no browsers or project dependencies.

For self-hosted jobs, choose one supported configuration for each untrusted job:

- A fresh ephemeral or just-in-time machine per job: use its actual self-hosted
  labels in `runs-on` and set `AUTOFIX_FIX_RUNNER_EPHEMERAL: "true"` in `fix`,
  or `AUTOFIX_VERIFY_RUNNER_EPHEMERAL: "true"` in `verify`. One job's declaration
  does not cover the other.
- Separate runner groups per kind: put `fix`, `verify`, and `prepare` with
  `publish` on three disjoint groups using each group's actual labels (and group
  selector where needed). Set `AUTOFIX_SEPARATE_RUNNER_GROUPS: "true"` in both
  untrusted jobs. These groups must never run another kind of job.

Recommend ephemeral runners for `verify`: a reused verify machine can carry one
candidate's leftovers into another task. If neither configuration is available,
stop; it is unsupported (`runner_not_isolated`). Declarations are trusted, not
verified. Leftover marker/process checks (`untrusted_job_leftover`) are only a
best-effort tripwire. An agent or candidate can leave processes, home files,
caches or tool shims that steal later jobs' credentials or forge test results;
separate processes or checkouts on the same machine are insufficient.

## Review is always required

`verified` is advisory: **the tests passed in a separate verify job**, a reviewer
hint, not proof. The fix job can forge an artifact using its artifact runtime
token, and verification executes candidate-controlled test changes. No automation
may use `verified` to merge, approve, enable auto-merge or skip human review.
A human always reviews the PR. Every PR is titled with the prefix `[needs review]`,
including when verification says `verified`. Other statuses are `flaky`, `failed`
and `not_run`; none authorizes automatic approval or merging.

## Moving from ci-triage

Existing pinned upstream callers keep working with their own keys. To migrate,
upload runs to the configured backend, enable classification (and autofix when
requested), then replace the old reusable caller with these four jobs. Remove
`upload-report` from the test workflow; keep the normal run/report upload.
Move the Claude credential to `fix`, the existing full-access test token to
`verify`, and old `extra_env` entries to `verify`'s `env:`. Add the owner-minted
`AUTOFIX_API_TOKEN` for prepare/publish. Drop the old Codex `openai_api_key` fallback.
Move `install-project-deps` into verify's project install step. Select supported
machines afresh instead of carrying over an old runner label.

To keep your own classifier, retain its classification job and POST its verdict
to `/v1/test-classifications`; ingested classifications take precedence. Autofix
can still use the served runner. Consumers of `triage-context/verdict.json` must
switch to runner result files or `GET /v1/test-runs/{id}`; there is no artifact
compatibility shim. See [notifications.md](notifications.md) only when requested.
