# Audit log, costs, run traces and analytics

> How the audit log, usage, costs, traces, metrics and visitor analytics are recorded.

Source: https://werker.cloud/docs/engineering/observability (updated 2026-12-02)

What Werker records about what happened, and how. What a person sees,
and how far each has been tested, is in
[costs and traces](../costs-and-traces.md).

| Record            | Question it answers                          | Store                                | State |
| ----------------- | -------------------------------------------- | ------------------------------------ | ----- |
| Audit log         | Who or what did something, to what, when?    | Postgres, append-only                | Built |
| Usage             | What did this run spend on models?           | Postgres                             | Built |
| Run trace         | What did this run actually do, turn by turn? | Postgres (`observability.run_spans`) | Built |
| Scores            | Did this run do what it should have?         | Postgres                             | Built |
| Visitor analytics | Who visits the site, and from where?         | Postgres                             | Built |

## Audit log

One append-only log of what people, Werker itself and agents did.

### Tables

- **`audit_events`:** one row per event. `action` (such as
  `sandbox.created`), `source` (`user`, `system` or `agent`), the
  person (`actor_user_id` and their email at the time, `actor_label`),
  `level`, a one-sentence `message`, and `data` for numbers and short
  facts such as a duration.
- **`audit_event_entities`:** the things each event touched, one row
  each: a type (`run`, `sandbox`, `connection`, `member`, `role`,
  `instance`), an ID, a label, and whether it is what the event is
  about (`primary`) or `related`. This is what finds every event about
  one run or one connection.
- **Per workspace:** row-level security, like every workspace table.
- **Append-only:** the app's database role can insert and read events
  and cannot change or delete them.
- **Instance events** (changes to what the whole instance shares) have
  no workspace. They are written and read through two database
  functions (`record_instance_audit_event`,
  `list_instance_audit_events`) after the web app has checked the user
  is an instance admin.

The lists of actions and entity types are in
`packages/domain/src/audit.ts`. Database functions are in
`packages/db/src/audit.ts`.

### What is recorded

Action names are `audit_actions` in `packages/domain/src/audit.ts`.

- **An operation** ([operations](api-and-cli.md#operations)) records
  itself, whichever way it was asked for. From the API, `data.via` is
  `api`, `cli` or `mcp`, as the client named itself, and the event
  also names the API key (`api_key`). The source is still `user`: the
  key's owner.
- **`factory.message_sent`** is about the room (`thread`), and names
  the factory and the runs it queued. It never holds the message. A
  retry with the same idempotency key is not recorded.
- **Sandbox events** carry the adapter, image, CPUs, memory and
  network, and link the sandbox and its run. Both adapters report them
  (`on_change` in `packages/connections/src/sandbox/types.ts`). A
  sandbox the sweep removes is recorded too.
- **`shell.ran`** carries the command (first 500 characters), its exit
  code and how long it took.
- **`service.called`** carries the connection, its adapter and service
  (such as `tavily`), the method and path without its query string,
  the HTTP status and how long it took. **`mcp.called`** carries the
  tool's name.
- **Run again** (`rerun_action` in `packages/core/src/audit.ts`) is a
  `run.queued` event about the new run with `data.from` = `rerun`, the
  run it repeats in `data.rerun_of` and that run's status then in
  `data.rerun_status`.
- **A run a schedule queued** (`run_due_schedules` in
  `packages/core/src/schedules.ts`) has `data.from` = `schedule` and
  the schedule's ID, and links the run, the schedule and its workflow
  or agent. A schedule that could not queue a run is not recorded
  here.
- **Scripts** record through `record_script_run` and
  `record_system_action` (`packages/core/src/audit.ts`), with the
  script's name in `data.script` (`enqueue`, `eval:generation`,
  `eval:factory`, `add-user`, `connect`). `queue_run`, `cancel_run`
  and `answer_run` do not record anything themselves, so a run the web
  app starts is recorded once, by the web app. A stop or answer is
  recorded only when it changed the run.
- **`pnpm add-user`** records only a membership it added: adding
  someone who is already a member records nothing. **`pnpm connect`**
  records the adapter, not the key.
- **Edits in the web app** carry the name the person typed where the
  remote function has one; otherwise the label is the ID's first 8
  characters.
- **Sign-ins** are recorded in the workspace that becomes active
  (`audit_sign_in` in `apps/app/src/lib/server/audit.ts`). A failed
  sign-in is a `warning` in the oldest workspace of the user with that
  email; an email no user has is not recorded, as there is no
  workspace to record it in. The automatic development sign-in is not
  recorded. Sign-out is recorded before the session ends.
- **A log that cannot be written is reported on the console**, not
  turned into a failed action or a failed run (`record_audit_event`).

### Reading it

- **Admin → Audit** lists the workspace's events in the paged table of
  [lists](ui.md#lists). Search, sorting and filters run in the
  database (`list_audit_events_page`). Needs the `view:audit`
  permission. Instance admins also see the instance's events there.
- **A run's page** has an Audit log section for people with
  `view:audit` (`audit-pages.svelte` in
  `apps/app/src/lib/components/audit/`).
- **Sandbox time per run** comes from the sandbox events
  (`read_sandbox_time`): each stretch from created or started to the
  next stopped or deleted.

## Usage

When a run finishes, stops or waits for input, the worker writes what
it has spent per model to `run_usage`: input, output and cached
tokens, and cost at the provider catalog's prices (an estimate; 0 when
the catalog has no price). The figures are the run's total from Pi
Durable's `pi.usage` (`usage_rows` in
`packages/runtime/src/tools/usage.ts`), so writing them again replaces
the row instead of adding to it.

`read_usage_overview` in `packages/db/src/observability/usage.ts`
reads the last 30 days for Admin → Usage.

## The cost of a unit of work

What one run, one step, one agent, one workflow or one factory cost,
in three parts:

| Part          | Where the number comes from                                                                                                      |
| ------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| Model calls   | Per run: `run_usage`, the authoritative total. Per step, agent, workflow, factory and day: the turns' `cost_usd` in `run_spans`. |
| Sandbox time  | `sandbox.*` audit events: seconds running, with the CPUs and memory on the event, times the adapter's prices.                    |
| Service calls | `service.called` audit events per service (`data.service`, else the adapter), times the service's price per call.                |

- **Prices:** `instance_prices`, set by instance admins in Admin →
  Sandboxes
  (`apps/app/src/lib/components/admin/price-settings.svelte`) and
  written only through `set_instance_prices` (SECURITY DEFINER). Per
  sandbox adapter: US dollars per CPU-second and per GiB-second. Per
  service: US dollars per call. Each save is an
  `instance.prices_changed` audit event.
- **Size when none was recorded:** `sandbox_default_size` in
  `packages/domain/src/observability.ts`: Daytona 1 CPU and 1 GiB;
  none for a Docker host, so that time has no price.
- **No price, no figure:** `cost_parts` in
  `packages/rules/src/observability/costs.ts`.
- **Where it shows:** the run page's Trace tab
  (`apps/app/src/lib/components/observability/trace/run-cost.svelte`),
  Observability → Costs, and the typical cost in the
  [metrics per piece of work](#metrics-per-piece-of-work).
- **The run page prices from the current price list each time.** Costs
  and the metrics read `run_totals`, where each run's cost was stored
  when it ended.
- **The Costs table**, read from `run_totals`:
  `apps/app/src/lib/components/observability/costs/view.svelte`, on
  the shared [data table](ui.md#lists), and
  `apps/app/src/lib/components/observability/costs/detail.svelte`,
  read when opened by `get_cost_detail` (`cost_work_limit`).
- **What a row counts** (`get_cost_rows` in
  `packages/core/src/observability/cost-rollups.ts`, `read_cost_rows`
  in `packages/db/src/totals/costs.ts`): a workflow's row is its runs.
  A factory's row is its requests, so its typical cost is per request,
  not per member turn. An agent's row is its model spend in every run
  it took part in (`run_agent_totals`: the step's agent in
  `runs.workflow`, else the factory member in `factory_turns`, else
  `runs.agent_id`), with sandbox time and service calls only for a run
  that had that one agent.
- **Turns against `run_usage`:** the run page says so when the turns
  add up to a model cost more than 1% away from `run_usage`.
- These records are what credits would be charged from
  ([#12](https://github.com/werker-ai/werker/issues/12)).

## Metrics per piece of work

Five metrics shown for the workspace and for each workflow, agent and
factory, with the change from the period before.

### A piece of work

| Where             | A piece of work is                                                                                   |
| ----------------- | ---------------------------------------------------------------------------------------------------- |
| A workflow        | One run.                                                                                             |
| An agent          | One run of its own, or one turn it took as a factory member. Its steps inside workflows are not its. |
| A factory, a room | One request: a person's message and every member turn it set off (`factory_turns.wave_id`).          |
| The workspace     | Each of the above once: a request's turns are one piece of work, any other run is one.               |

A room is `factory_threads`; a turn is one member answering one
message, stored as one run. Rooms and factories add their requests up.
A run that writes a factory's team from its brief is a piece of that
factory's work with no room.

### The five

Over the pieces of work that **began** in the period (`WorkMetrics` in
`packages/domain/src/work-metrics.ts`):

| Metric               | Definition                                                                                                                                                                 |
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Finished             | How many have ended: done, failed or stopped. A request has ended when every turn of it has.                                                                               |
| Succeeded            | The share of the ended that are done; for a request, every turn done. Beside it, the judge's pass rate over the verdicts on their runs (`run_scores`).                     |
| Typical cost         | The median cost of an ended piece of work: model, sandbox and services, as priced when each run ended. "High" is the 90th percentile.                                      |
| Typical time working | The median of time in model turns and top-level tool calls, added up. Not elapsed time: waiting for a person is not counted, and a request's turns running at once add up. |
| Stepped in           | [Interventions](#interventions) on the ended work, divided by how many ended.                                                                                              |

What each figure means to a reader is in
[costs and traces](../costs-and-traces.md#metrics-per-piece-of-work).

- **Change from the period before** (`work_figures` in
  `packages/rules/src/observability/work-metrics.ts`). Not shown below
  `metric_change_minimum`.
- **Where they show**
  (`apps/app/src/lib/components/metrics/work-metrics.svelte`):
  Observability → Overview, over the chosen range; and each
  workflow's, agent's and factory's page, over the last 30 days.

### Comparing by version, model and task

Under the five metrics on a workflow's, agent's and factory's page,
the same metrics split one of three ways
(`apps/app/src/lib/components/metrics/work-breakdown.svelte`,
`read_work_breakdown` in `packages/db/src/totals/breakdown.ts`):

| Compare by | A row is                                                                                                                                                                                                                                         |
| ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Version    | The saved version (`definition_versions`) of that workflow, agent or factory when the work began: a request's when it was sent, a run's when queued. An edit shows as a new row, so the rows before and after it can be read against each other. |
| Model      | The model the run was given (`runs.model_id`). A request whose turns ran on different models is "More than one model".                                                                                                                           |
| Task       | The same thing asked again: the request's message, or the run's instructions, matched with case and spacing evened out. The most asked first.                                                                                                    |

- **Each row** shows finished, succeeded, typical and high cost,
  typical time working, stepped in per piece of work and the total,
  with when its first and latest work began. At most 20 rows
  (`work_group_limit`).
- **"Before the first saved version":** a run that created the
  workflow it then ran, which began before that workflow's first
  version was saved.
- **No changes or judge figures per row**, and no minimum count.
- **Stored on each run:** `run_totals.model_id`, `workflow_version`,
  `agent_version`, `factory_version`, `task_key` and `task_title`,
  written with the run's totals.

### More of the same

The line under the tiles uses the **average** cost of work that ended
in the period (`cost_mean`), not the typical cost. Not shown for the
workspace.

### Rooms

A factory's page and its row in Costs list its rooms
(`apps/app/src/lib/components/metrics/rooms-table.svelte`,
`read_room_metrics` in `packages/db/src/totals/metrics.ts`): per room,
the requests ended, the share done, typical and high cost, the median
member turns a request set off, typical time working, times a person
stepped in and the total. Rooms with no request in the period are left
out.

### `run_totals`

One row per run with what it came to
(`packages/db/sql/001_schema.sql`):

- **What is in it:** the piece of work it belongs to (`work_id`,
  `work_started_at`), its workflow, agent, factory and room, what it
  is compared across (model, versions, task), its status, turns,
  tokens, time working, the three cost parts with the sandbox seconds
  and service calls behind them, and interventions. `run_agent_totals`
  holds the model spend per agent within a run.
- **Who writes it** (`packages/runtime/src/loops/totals.ts`): the
  worker, when a run pauses for input and when it ends, from the same
  sources as the run page (`read_run_totals_source` in
  `packages/db/src/totals/write.ts`). A worker also sweeps once a
  minute for runs with no row, a changed status, or a row that is not
  final (`runs_needing_totals`).
- **Priced once.** A row becomes final when its run has ended and its
  sandbox has stopped (or an hour after it ended, whatever the sandbox
  events say). From then its costs are not worked out again, so a new
  price list does not change past work; only its interventions are
  updated, since a rerun after a failure is counted on the run that
  failed.
- **Usage with no price when the run ended stays unpriced.** To price
  such runs after setting the price, delete their rows as the database
  owner (`DELETE FROM run_totals WHERE service_cost IS NULL`); the
  next sweep writes them again at the current prices.
- **Read with plain aggregates:** `percentile_cont`, `FILTER` and
  `GROUP BY` over indexed rows (`packages/db/src/totals/metrics.ts`,
  `costs.ts`). No extension is used.

## Interventions

How many times a person had to step in on a run, counted from the
audit log (`interventions` in
`packages/db/src/runs/interventions.ts`). Only events a signed-in
person caused (`source = 'user'`) count:

| Part      | Events counted                                                                                                                     |
| --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `answers` | `run.answered` about the run: one per question answered, including creation's `request_details` and continuing after a setup stop. |
| `stops`   | `run.cancelled` about the run.                                                                                                     |
| `reruns`  | `run.queued` for a new run with `data.rerun_of` = this run and `data.rerun_status` = `failed`. Counts for the run that failed.     |

A run's interventions are the three added up.

- **Not counted:** starting, archiving or restoring a run; Run again
  on a run that did not fail; anything a script, an eval or a schedule
  did (`source = 'system'`); editing the agent or workflow afterwards;
  messages in a factory room.
- **Limits:** an event that could not be written is not counted. A
  failed run started again from an agent's or workflow's own page, or
  described again in `/new`, is not linked to the run that failed.
- **Where it shows:** the run page and the "Stepped in" metric
  ([metrics per piece of work](#metrics-per-piece-of-work)).
- **Stored per run** in `run_totals.interventions` when the run's
  totals are written, and updated afterwards when a failed run is run
  again.

## Run traces

### What is stored

`run_spans`: one row per model turn and per tool call, per workspace
with row-level security. The worker reads them from the run's durable
conversations (`read_spans`, `spans_of` in
`packages/runtime/src/spans.ts`) and writes them (`save_run_spans` in
`packages/db/src/observability/spans.ts`).

- **When:** a conversation taking turns (generation, a step, or a run
  without a workflow) every 2 seconds while it runs, when its spans
  changed (`run_trace` in `packages/runtime/src/run/trace.ts`); a
  step's conversation once its turns end (the `spans` hook in
  `packages/runtime/src/workflow/step/phase.ts`); and all the run's
  conversations whenever usage is saved: when it finishes, fails, is
  stopped or waits for input. A turn or tool call is written once it
  has ended, not while it is in progress.
- **Told to the page:** each write notifies the `run_spans` channel
  with the run's ID; the run's event stream
  (`apps/app/src/routes/(app)/runs/[id]/events/+server.ts`) passes it
  on as an empty `run-trace` event.
- **Written once:** keyed on run, conversation and span
  (`turn:<entry>:<message>`, `tool:<call id>`,
  `nested:<parent call id>:<call id>`), so writing again after a
  resume or restart replaces rows. A row keeps its step when the run's
  end writes it again without one.
- **Which step:** `step_resume` (the run segment) and `step_position`.
  `conversation_kind` is `generation`, `step`, `factory_turn` (a
  factory member's step), `run` (a run without a workflow) or `other`.
- **Columns:** `turn_index`, `tool_call_id`, `tool_name`,
  `parent_tool_call_id`, `is_error`, `error_text`, `exit_code`,
  `duration_ms`, `stop_reason`, token counts and `cost_usd`, plus
  `model` and `response_model`.
- **Durations:** a turn's `durationMs`; a tool call's `durationMs`,
  else from the end of its turn to its result. Calls a tool made
  (nested calls, such as the shell from Code Mode) have a duration but
  no start: they are laid out one after another from the start of the
  call that made them, and the drawer says so.
- **Redaction and size** (`packages/runtime/src/redact.ts`): values of
  keys like api key, authorization, bearer, client secret, cookie,
  password, secret and token (not token counts) become `[REDACTED]`,
  as do JWT-shaped strings and provider keys. Werker adds a credential
  after its label in text (`Authorization: Bearer x`, `api_key=x`).
  Limits: 500 characters per string, 4,000 for a prompt, 2,000 for a
  tool input's value (a command, a Code Mode script), 16,000 for an
  assistant's visible text and a failure's output. Thinking is never
  stored.

### What is shown

Components are in `apps/app/src/lib/components/observability/` (the
run page's trace is in `trace/run-trace.svelte`, needs `view:run`).
Trace shapes are built from stored rows by
`packages/rules/src/observability/trace.ts`. `/observability` (needs
`view:run`) has Overview, Runs, Tools and Costs, over 24 hours, 7, 30
or 90 days. Data comes from `run_spans` through remote functions
(`apps/app/src/lib/remote/observability.remote.ts` → `packages/core` →
`packages/db`). A turn's tool time adds up top-level calls only; tool
counts include nested calls. Copy is in `observability_copy`
(`apps/app/src/lib/messaging.ts`).

## Scores

A judge (`classify@1`) answers each of a workspace's questions about a
sample of its finished runs, pass or fail with one of eight fixed
reasons, and Observability → Scores shows each question's pass rate
and failing runs; a run's page shows its verdicts. Judging cost is
kept on the verdict, apart from the run's cost. [Scores](scores.md)
has what the judge sees, the limits and what is not built (no
automatic proposals, no replay).

## Visitor analytics

How people use the app and the public site: page views, pages,
referring sites, devices and browsers. Shown to instance admins in
Admin → Analytics.

The public site (`apps/site`) is on another origin with no database,
so it records nothing itself. Each page it shows posts its path and
referrer to the app's `POST /api/visit` (`apps/site/src/lib/visit.ts`,
`apps/app/src/routes/api/visit/+server.ts`), which records a
signed-out page view in the same table, under the same rules as below
(`apps/app/src/lib/server/visits/site-visits.ts`). The endpoint exists
only when `WERKER_SITE_ORIGIN` is set, and answers only that origin.
The `Origin` header is all that is checked, so a script can post
made-up views; the path must be a plain pathname of at most 300
characters.

### What is recorded

The server hook (`apps/app/src/hooks.server.ts`) calls `record_visit`
in `apps/app/src/lib/server/visits/page-views.ts` after the response
is made, without awaiting it; a failure is only logged
(`page view was not recorded: …`). A request is recorded only when all
of these hold (`should_record`, `classify_user_agent`):

- `GET`, answered 2xx or 404 with `text/html`.
- Loaded as a document: `Sec-Fetch-Dest` is `document` (or absent) and
  `Sec-Fetch-Mode` is `navigate` (or absent).
- Not `/api/…`, `/_app/…` (SvelteKit files and remote functions),
  `…/__data.json`, `/.well-known/…`, or a file such as `/favicon.ico`.
- Not a prefetch or prerender (`Sec-Purpose`, `Purpose`, `X-Purpose`,
  `X-Moz`).
- No `DNT: 1` or `Sec-GPC: 1` header.
- The user agent starts with `Mozilla/` and does not match the bot
  pattern (crawlers, link previews, uptime checks, headless browsers,
  `curl` and other scripts).

Navigation inside the app after the first page load happens in the
browser and fetches data, not a document, so it is **not** a page
view. Page views count full page loads only.

### What is stored

One row in `page_views` per page view
(`packages/db/sql/001_schema.sql`):

| Column          | What                                                                                                        |
| --------------- | ----------------------------------------------------------------------------------------------------------- |
| `at`            | When.                                                                                                       |
| `path`          | The route with groups removed (`/runs/[id]`, so no IDs); the pathname for a 404. Never a query string.      |
| `referrer_host` | The referring site's host without `www.`; null for none or the same site. Never the full URL.               |
| `signed_in`     | Whether the visitor was signed in.                                                                          |
| `workspace_id`  | The signed-in visitor's workspace; null when signed out or in none.                                         |
| `device`        | `desktop`, `mobile`, `tablet` or `other`, from the user agent.                                              |
| `browser`       | Browser family (`Chrome`, `Edge`, `Firefox`, `Safari`, `Opera`, `Samsung Internet`, `Other`).               |
| `country`       | Two-letter code from the header named by `WERKER_COUNTRY_HEADER` (such as `cf-ipcountry`); null when unset. |
| `visitor_day`   | sha256 of the day's salt, the IP address and the user agent.                                                |

Not stored: the IP address, the raw user agent, query strings, full
referrer URLs, or any cookie. No cookie is set for analytics.

**Unique visitors.** `page_view_salt` holds one row: a random salt and
its UTC day. The first call of `page_view_salt()` on a new UTC day
overwrites it, so every web process uses the same salt that day and
the previous day's salt is gone. The web app hashes salt + IP + user
agent (`visitor_hash`). The same visitor counts once a day, so visitor
counts over 30 days are visitor-days.

**Country.** Taken only from the header `WERKER_COUNTRY_HEADER` names
(`apps/app/src/env.ts`). `XX` and `T1` are dropped.

**Access.** `page_views` and `page_view_salt` belong to the instance,
not a workspace. The app role has no grant on either table; it writes
and reads only through `record_page_view`, `page_view_salt`,
`page_view_overview` and `delete_old_page_views` (SECURITY DEFINER).
`page_view_overview` returns totals only, and the web app calls it
only for instance admins (`get_analytics` in
`apps/app/src/lib/remote/admin.remote.ts`, `require_instance_admin`).

**Retention.** Every worker deletes page views older than 400 days
every 6 hours (`prune_page_views` in
`packages/runtime/src/worker.ts`).

### What is shown

Admin → Analytics
(`apps/app/src/lib/components/admin/analytics-panel.svelte`), instance
admins only: the last 30 days, with top pages, referrers, devices,
browsers and countries (top 100 of each).
