# Monitoring and retention

## Health

| Endpoint | Answers |
|---|---|
| `GET /healthz` | `200` while the process serves requests. |
| `GET /readyz` | `200` when the database answers, `503` otherwise. |

Both are open without a token. In containers use `shipyard -healthcheck` — see [Run with Docker](/docker/).

## Prometheus metrics

Set `observability.metrics: true` and scrape `/metrics`:

```yaml
scrape_configs:
  - job_name: shipyard
    static_configs:
      - targets: ["127.0.0.1:8080"]
    authorization:
      credentials_file: /etc/prometheus/shipyard.token
```

Leave out `authorization` when no API token is configured. These gauges are read from the database, so a restart does not reset them:

| Metric | Labels | Meaning |
|---|---|---|
| `shipyard_runs` | `state`: `queued`, `waiting`, `running`, `cancelling`, `succeeded`, `failed`, `cancelled` | Stored runs |
| `shipyard_runs_held` | — | Runs under legal hold |
| `shipyard_infra_tasks` | `state`: `queued`, `leased`, `running`, `cancelling`, `succeeded`, `failed`, `cancelled`, `expired`, `unknown` | Stored infrastructure tasks |
| `shipyard_ships` | `status`: `online`, `offline`, `revoked` | Joined ships; online means seen in the last 15 seconds |
| `shipyard_retention_last_success_timestamp_seconds` | — | Last completed retention pass (0: never) |
| `shipyard_retention_last_failure_timestamp_seconds` | — | Last failed retention pass (0: never) |
| `shipyard_retention_last_reclaimed_bytes` | — | Log bytes the latest completed pass removed |
| `shipyard_db_bytes` / `shipyard_db_free_bytes` | — | Database size and its free pages; free pages return to the disk only after a vacuum |
| `shipyard_log_bytes` / `shipyard_log_budget_bytes` | — | Run logs and `retention.max_disk_size_mb`; at the budget new runs are refused |
| `shipyard_disk_total_bytes` / `shipyard_disk_free_bytes` | — | Filesystem holding the database (Linux, FreeBSD, macOS) |
| `shipyard_github_oldest_sync_timestamp_seconds` | — | Last reconciliation of the least recently synced GitHub repository (0: none yet) |
| `shipyard_github_sync_errors` | — | GitHub repositories whose last reconciliation failed |
| `shipyard_usage_findings` | `code`: `context_large`, `cache_read_share`, `background_wakeups`, `parallel_sessions`, `tool_output_heavy`, `instruction_fixed_cost`, `duplicate_rules` | Stored usage findings: rules a workstation session or repository crossed |

Counters and histograms are kept in memory and start at zero when the process starts; query them with `rate()` or `increase()`, which handle the reset. Run and provider series come from the embedded worker; a standalone `worker` process serves no `/metrics`.

| Metric | Labels | Meaning |
|---|---|---|
| `shipyard_http_requests_total` | `route` (the route pattern, `unmatched` otherwise), `code` | Answered HTTP requests |
| `shipyard_http_request_duration_seconds` | `route` | Time to answer (histogram) |
| `shipyard_webhook_events_total` | `source`: `github` (`recorded`, `duplicate`, `ignored`), `alertmanager` (`recorded`, `quarantined`, `diagnostic_queued`, `suppressed_cooldown`, `suppressed_debounce`, `suppressed_halted`, `suppressed_budget`, `suppressed_concurrency`, `truncated`), `custom` (the same without `quarantined` and `truncated`, plus `stale`) | What accepted webhooks carried |
| `shipyard_ship_events_skipped_total` | — | Ship events skipped because their type is unknown to this Shipyard (a ship newer than the server) |
| `shipyard_alert_deliveries_total` | `result`: `delivered`, `pending` (will retry), `dead` | Outbound incident webhook attempts |
| `shipyard_alert_issues_total` | `result`: `created`, `pending` (will retry), `dead` | GitHub issue attempts of `create_issue` alert rules |
| `shipyard_runs_finished_total` | `kind`, `state` (`succeeded`, `failed`, `waiting`) | Runs the worker finished or parked on a usage limit |
| `shipyard_run_duration_seconds` | `kind` | Execution time of finished runs (histogram) |
| `shipyard_provider_requests_total` | `host`, `code` (`error`: no answer) | Requests to model providers and Prometheus |
| `shipyard_provider_request_duration_seconds` | `host` | Latency of one provider request (histogram) |
| `shipyard_provider_retries_total` | `host` | Requests repeated after a transient provider error |
| `shipyard_merge_gate_total` | `decision`: `pass`, `wait`, `fail` | Merge gate decisions of `merge` steps |
| `shipyard_releases_total` | `outcome`: `tagged`, `skipped`, `failed` | Release windows settled by scheduled release runs |
| `shipyard_research_total` | `outcome`: `collected`, `skipped`, `failed` | Content windows settled by research runs |
| `shipyard_research_topics_total` | `outcome`: `accepted`, `skipped` | Topics recorded by research runs, by review outcome |
| `shipyard_analytics_total` | `outcome`: `collected`, `failed` | Analytics runs that read their sources |
| `shipyard_drafts_total` | `outcome`: `written`, `rejected`, `proposed`, `changed`, `published` | Article drafts settled by draft and publish runs |
| `shipyard_ai_calls_total` | `usage`: `reported`, `unreported` | Completed model calls, by whether the provider reported token counts (from runs on this Shipyard and on ships) |
| `shipyard_ai_tokens_total` | `direction`: `input`, `output`, `cache_read`, `cache_write` | Tokens providers reported; cached prompt tokens count under `cache_read` and `cache_write`, not `input` |
| `shipyard_usage_tokens_total` | `source`: `provider`, `agent`, `workstation`; `kind`: `input`, `output`, `cache_read`, `cache_write` | Tokens of stored usage by where the call ran; a replayed report adds nothing. No session, run or file label |
| `shipyard_ai_cost_usd_total` | — | Estimated cost of priced calls, from the model prices in the configuration; unpriced or unreported calls add nothing, so compare with `shipyard_ai_calls_total` |

Labels are fixed sets: route patterns, states, kinds and the hosts in your configuration; no run, task or ship IDs, prompts or secrets. A ready scrape job and alert rules (queue stalled, failing runs, retention stalled or failing, ships offline, tasks with unknown outcome, stale or failing GitHub sync, API server errors, failing providers) are in `deploy/prometheus/`; load `shipyard-alerts.yml` with `rule_files`. `deploy/grafana/shipyard-dashboard.json` is a dashboard over the same series; import it and pick the Prometheus data source.

## Alertmanager

Shipyard receives grouped notifications on `POST /webhooks/alertmanager`:

```yaml
# alertmanager.yml
receivers:
  - name: shipyard
    webhook_configs:
      - url: http://127.0.0.1:8080/webhooks/alertmanager
        http_config:
          authorization:
            credentials_file: /etc/alertmanager/shipyard.token
```

```yaml
# .shipyard.yaml
alerts:
  token_env: ALERTMANAGER_TOKEN
  project_label: shipyard_project
  enqueue_diagnostics: true
```

Each alert needs the label `shipyard_project` with the ID of an enabled project. Shipyard records firing and resolved alerts; with `enqueue_diagnostics` a firing alert also queues one diagnostic run, stored in the same transaction as the alert, so a failure keeps neither and Alertmanager's retry starts clean. A repeated notification for the same alert does not queue a second run. The project's [run policy](/configuration/#projects) applies: a refused kind or a used-up daily budget records the alert without a run. An alert whose label names no enabled project goes to quarantine: it is stored, queues nothing and reaches no repository. The Incidents tab and `GET /api/v1/alerts/quarantine` list it so you can fix the label. A malformed alert (no fingerprint, unknown status) rejects the whole batch. When the receiver sets `max_alerts` and Alertmanager cuts a notification, Shipyard logs a warning with the number of alerts left out and returns it as `truncated`; those alerts never arrive, so raise `max_alerts` (Shipyard accepts up to 100 per batch).

Besides the bearer token, Alertmanager can authenticate with basic auth or a client certificate. Any configured method is enough:

```yaml
alerts:
  basic_auth:                 # http_config.basic_auth
    username: alertmanager
    password_env: ALERTMANAGER_PASSWORD
  tls:                        # http_config.tls_config with cert_file/key_file
    listen: ":9443"
    cert_file: /etc/shipyard/alerts.pem
    key_file: /etc/shipyard/alerts-key.pem
    client_ca_file: /etc/shipyard/alertmanager-ca.pem
    client_names: [alertmanager]   # optional: DNS names or common name
```

The `tls` listener serves only the webhook routes and accepts only clients with a certificate from `client_ca_file`. Changes to it need a restart.

## Custom webhooks

Other systems can send events to `POST /webhooks/custom/<name>`. Each source gets its own secret and a fixed project; the payload never picks the project.

```yaml
alerts:
  custom:
    uptime:
      secret_env: UPTIME_WEBHOOK_SECRET
      project: shop
      replay_window: 5m
      enqueue_diagnostics: true
```

The body is `{"id": "...", "status": "firing" | "resolved"}`; other fields are ignored. Sign every request:

```
X-Shipyard-Timestamp: <Unix seconds>
X-Shipyard-Signature: sha256=<hex HMAC-SHA256 of "<timestamp>.<body>">
```

```sh
body='{"id":"check-42","status":"firing"}'
ts=$(date +%s)
sig=$(printf '%s.%s' "$ts" "$body" | openssl dgst -sha256 -hmac "$UPTIME_WEBHOOK_SECRET" -hex | sed 's/^.* //')
curl -sS https://shipyard.example/webhooks/custom/uptime \
  -H "X-Shipyard-Timestamp: $ts" -H "X-Shipyard-Signature: sha256=$sig" --data "$body"
```

A wrong signature answers `401 invalid_signature`. A timestamp more than `replay_window` away from Shipyard's clock answers `401 stale_signature`, so a captured request cannot be sent again later; keep clocks in sync. A repeat of the same `id` and `status` is recorded once and queues nothing; give each new occurrence a new `id`. Diagnostic runs follow the project's [run policy](/configuration/#projects). An optional `labels` object in the body selects an alert rule.

## Alert rules

Rules decide what an alert does, on both routes. The first match wins; an alert no rule matches follows `enqueue_diagnostics`.

```yaml
alerts:
  rules:
    - name: page
      severity: [critical]
      action: diagnose      # or record: store only
      cooldown: 30m         # one run per project per 30 minutes
      budget: 5             # and at most 5 per project per day
      max_concurrent: 2     # at most 2 unfinished runs of this rule
      escalate: [ops]       # tell this outbound target when a limit says no
    - name: warnings
      labels: { team: web }
      action: diagnose
      debounce: 10m         # firing again within 10 minutes of a resolve is a flap
```

Cooldown and debounce are kept per rule and project in the database, so a restart does not reset them and a flood of matching alerts queues one run. `budget` and `max_concurrent` cap the runs a rule queues over a day or at once; when they refuse a run, the incident escalates once to the rule's `escalate` targets. Responses report suppressed alerts as `suppressed`.

## Incidents

Alerts of one occurrence form an incident: it opens on the first firing event and closes once on the resolve. The **Incidents** tab in the console, and `GET /api/v1/incidents`, show each incident with a timeline of its events and what each one did, including alerts a rule or the halt kept from acting.

**Halt alert actions** on that tab (or `PUT /api/v1/alerts/halt`) is the emergency stop: alerts are still recorded, but queue no runs and send no webhooks until you resume. It survives restarts.

## Outbound webhooks

```yaml
alerts:
  outbound:
    ops:
      url: https://hooks.example/shipyard
      secret_env: OPS_WEBHOOK_SECRET
      events: [opened, resolved]
```

Each target gets a signed `POST` when an incident opens or resolves, with the incident fields only, never alert labels. Signing matches incoming custom webhooks; deduplicate on `X-Shipyard-Delivery`. Failed deliveries retry with growing waits for about an hour (8 attempts), then become dead letters, listed on the Incidents tab with a Retry button.

## Traces

Set `observability.otel_endpoint` to an OTLP collector: `http://127.0.0.1:4318` over HTTP (default), or `http://127.0.0.1:4317` with `observability.otel_protocol: grpc`. Without an endpoint nothing is exported and Shipyard works offline as before.

**What is traced.** Every API request and webhook is a server span named after its route, with the method, status and `shipyard.request_id` (the `X-Request-Id` header). A run queued by a request keeps that request's trace in the database, so even after a restart the worker continues it: the `run` span, each pipeline `stage` and every `provider request` (host, method, status; never paths, headers or bodies) join the same trace. A caller that sends a W3C `traceparent` header puts all of this into its own trace. Run log lines carry the `trace_id`; the console shows it when you hover a line's time. Ships receive the trace with the run, so their spans join it too when they export to a collector. Infrastructure tasks work the same way: the trace of the creating request is stored with the task and sent in the lease, the ship's `infra.task` and `infra.execute` spans join it, and every journal event of the task carries the trace ID as `traceId`. The event routes take `?traceId=` to list the events of one trace, and Docks → **History** shows the trace ID on each event and narrows the list to it. A task created without a valid `traceparent` runs as before, with no trace ID on its events.

**Configuration.** The standard variables apply: `OTEL_EXPORTER_OTLP_HEADERS` (for example a collector API key), `OTEL_EXPORTER_OTLP_CERTIFICATE`, `OTEL_EXPORTER_OTLP_CLIENT_CERTIFICATE` / `_CLIENT_KEY` for TLS, `OTEL_TRACES_SAMPLER` / `OTEL_TRACES_SAMPLER_ARG` for sampling, and `OTEL_RESOURCE_ATTRIBUTES` for extra resource attributes such as `deployment.environment.name=prod`. Each process identifies itself with `service.name` (`shipyard` or `shipyard-worker`), `service.version`, a random `service.instance.id` per start and `host.name`. A malformed value stops startup instead of exporting unlabelled traces.

**Limits.** Spans wait in a queue of 256 and are sent in batches with a 5 s timeout; when the queue is full new spans are dropped, never waited for, so a slow or missing collector cannot hold up a run. `shipyard_otel_spans_total{result}` counts `ended`, `exported` and `failed` spans; the difference is what was dropped. Shutdown flushes the queue for up to 5 s. Before export, string attributes, events and status messages pass through the same credential redaction as run logs. Sampling applies to traces only: run logs, the run audit and the infrastructure journal are always written in full.

**Collector.** `deploy/otel/collector.yaml` is an example for the Collector contrib distribution: OTLP in for traces, the `prometheus` receiver scraping `/metrics`, and the `filelog` receiver tailing run logs, through `memory_limiter`, `redaction` and `batch` to backends you choose. Validate it against your Collector version before use. Shipyard does not push metrics over OTLP, so scraping `/metrics` counts nothing twice. Retention in those backends is separate from Shipyard's own retention settings.

## Service logs

Under systemd, Shipyard's own log goes to the journal:

```sh
journalctl -u shipyard -f
journalctl -u shipyard --since today -o short-iso
```

Journal size and retention are host settings (`SystemMaxUse` in `journald.conf`). Run logs are separate — they live in `logging.directory` and follow Shipyard's retention.

## Retention

Shipyard cleans up at worker start and every hour:

- run logs older than `retention.logs_days` are deleted, with the run's artifacts; the run stays in the history marked *logs expired*;
- finished runs older than `retention.completed_runs_days` are deleted;
- workstation usage sessions whose last activity is older than `retention.logs_days` are deleted with their usage findings;
- audit entries and alert records older than `retention.audit_days` are deleted.

Queued and running work is never touched. A run under legal hold (`PUT /api/v1/runs/{id}/hold`, lifted with `DELETE`) keeps its logs and history past every cutoff; both changes are audited. Each run's log is capped at `logging.max_run_size_mb`, and single log messages at 16 KiB. When the log directory reaches `retention.max_disk_size_mb`, new runs are refused with `507` until retention frees space — newer logs are never deleted to make room.

`shipyard retention` shows what the next pass would remove and how many log bytes it would free, without changing anything; `shipyard retention -apply` runs a pass now, and `shipyard retention -vacuum` returns the database's free pages to the disk (stop Shipyard first: it needs exclusive access and up to twice the file size). Every pass and dry run is kept in the retention history: `GET /api/v1/retention` returns it with the current usage (logs against their budget, database, free disk), and the console shows both under Projects → Storage. Passes are idempotent, so two workers running one at the same time remove nothing twice; raw webhook payloads are never stored, so they need no retention of their own.

The database file itself is not counted against the budget. Back it up while Shipyard runs with `shipyard backup -out /backups/shipyard-$(date +%F).db`: the copy is consistent, readable only by its owner and checked for integrity and schema version; an existing file is never overwritten. To restore, stop Shipyard, put the copy at `storage.path` and start it again, then run `shipyard journal verify -expect <saved head>` to confirm the infrastructure history.
