
# Workflow events and replay

When a business process has steps, the app prints one JSON line to stdout per step, and Agent Cloud turns those lines into a per-entity timeline. On your mirror, `agc replay booking:123` lists every event that names `booking:123`, oldest first. Success is `"count"` above zero in its answer.

```json
{"agc":"event","name":"waitlist.promoted","entity":"booking:123","related":["camp:7","waitlist:44"],"status":"ok","attrs":{"position":2}}
```

Events make "my booking disappeared" answerable later without reading production data: `agc capsule booking:123` reads the same events from production as shapes and counts.

## Ask your agent

```text
When a cancellation frees a camp spot and the next family on the waitlist gets it,
record each step as an Agent Cloud workflow event so we can replay what happened.
```

The agent adds event lines in the web app and worker, then shows you a replay from the mirror.

## Steps

Emit one line per step, from the web app or the worker:

```ts
type Ref = `${string}:${string}`;
export function step(name: string, entity: Ref, status: 'ok' | 'failed', related: Ref[] = [], attrs: Record<string, number | string> = {}) {
  // One line, compact, with "agc" first: the mirror's reader looks for {"agc" at the start of the JSON.
  process.stdout.write(JSON.stringify({ agc: 'event', name, entity, related, status, attrs }) + '\n');
}

step('booking.cancelled', `booking:${b.id}`, 'ok', [`camp:${b.camp_id}`]);
step('waitlist.promoted', `booking:${next.id}`, 'ok', [`camp:${b.camp_id}`, `waitlist:${w.id}`], { position: w.position });
step('payment.charged', `booking:${next.id}`, 'failed', [], { amount_cents: 12500 });
```

Run the flow on the mirror, then replay it:

```bash
agc up --detach
agc replay booking:124
```

```json
{
  "ok": true,
  "product": "agent.cloud",
  "command": "replay",
  "data": {
    "mirror": "main",
    "entity": "booking:124",
    "count": 2,
    "failed": 1,
    "events": [
      { "at": null, "name": "waitlist.promoted", "entity": "booking:124", "related": ["camp:7", "waitlist:44"], "status": "ok", "attrs": { "position": 2 } },
      { "at": null, "name": "payment.charged", "entity": "booking:124", "related": [], "status": "failed", "attrs": { "amount_cents": 12500 } }
    ]
  },
  "next": [{ "cmd": "agc replay booking:124", "why": "a step failed (payment.charged): follow that entity" }]
}
```

`at` is the event's own ISO timestamp if you include one. Otherwise it's `null`, and the order is the order of the log.

## How it works

**Which lines count.** A line is an event when it parses as a JSON object with `"agc":"event"`, a `name` matching `^[a-z][a-z0-9_.-]{0,63}$`, and an `entity` matching `type:id`. Anything else stays an ordinary log line. In production a valid event line goes to the events store instead of the logs, so it won't appear in `agc logs`. The app can't use it to hide other output.

**On the mirror**, `agc replay` reads the mirror's own log and keeps `attrs` as written, since the mirror's data is masked and yours. It finds events that name the entity as `entity` or in `related`.

**In production**, observability stores each event with the release and pod that wrote it. The console's Replay tab lists entities from the last 24 hours, failures first. An entity opens on its steps from the last 7 days, oldest first, with failed steps marked and gaps over a minute called out. Each rehearsal's events are on its release page. Agents get rehearsal results as pass or fail only, as always.

**No personal data.** `entity` ids are opaque keys, a number or uuid, never a name or email. `attrs` holds ids, amounts and counts. The owner reads production `attrs` in the console, so anything you put there is shown to them as written.

## Reference

| Field | Required | Rule (an event that fails a required rule is an ordinary log line) |
|---|---|---|
| `agc` | yes | Exactly `"event"` |
| `name` | yes | The step, `^[a-z][a-z0-9_.-]{0,63}$`: lowercase, dotted, `noun.verb_past` by convention (`booking.confirmed`) |
| `entity` | yes | What it happened to, `type:id`: type `[A-Za-z0-9_-]{1,32}`, id `[A-Za-z0-9_.-]{1,64}` (`booking:123`) |
| `related` | no | Up to 10 other entities, same format; extras and malformed ones are dropped |
| `status` | no | `ok` or `failed`; replay and the capsule treat `failed` as the failing step. Stored if it matches `^[a-z_]{0,16}$`, else blank |
| `attrs` | no | An object of ids, counts and amounts; anything that isn't an object becomes `{}` |
| `at` | no | ISO time, used only by `agc replay` on the mirror; production uses the log line's own time |

| | Production and rehearsals | Mirror (`agc replay`) |
|---|---|---|
| Where the line must be | The whole stdout line must be the JSON object | Anything before `{"agc"` on the line is ignored |
| Log | A valid event is removed from the logs (`agc logs` won't show it) | It stays in the mirror's log |
| `attrs` | Kept up to 4,000 characters of JSON, else `{"truncated":true}`; shown to the app's owner, never to agents | Kept whole, shown by `agc replay` |
| `at` | Ignored | Used when it's a valid date |
| Retention | 30 days; a rehearsal's events 1 day, owner only | The mirror's log file |

| Reader | Sees |
|---|---|
| `agc replay <entity>` | Every event on your mirror whose `entity` or `related` names it, oldest first, with `attrs` |
| `agc capsule <entity>` | Production's steps for that entity: names, entities, statuses, releases and timing, never `attrs` |
| Console Replay tab | The owner's full view of production, `attrs` included |
| A ship's release page | The rehearsal's replay |

## Errors

| code | exit | cause | fix |
|---|---|---|---|
| `replay.entity` | 2 | No entity, or not `type:id` | `agc replay booking:123` with an id from your mirror |
| `capsule.about` | 2 | `agc capsule` got something that is neither an entity nor an incident id | Pass `type:id`, `inc_…`, or `--from` and `--to` |
| `mirror.not_running` | 1 | No local mirror to read | `agc up` |

```json
{"ok":false,"product":"agent.cloud","command":"replay","error":{"retryable":false,"code":"replay.entity","message":"Name the entity to replay, as type:id (for example booking:123).","fix":"Run `agc replay booking:123`, using an id from your mirror."},"next":[{"cmd":"agc help replay","why":"how apps record workflow events"}]}
```

A replay that finds nothing isn't an error: `count` is 0 and `next` says whether the mirror has events for other entities or none at all. An event line that breaks a rule isn't an error either: it's kept as a log line.


A CLI setup failure, before the operation runs: if the machine has an identity but the current folder has no manifest, `agc replay` exits 1. Run it from the linked app folder, or initialize that repository.

```json
{
  "ok": false,
  "product": "agent.cloud",
  "command": "replay",
  "error": {
    "retryable": false,
    "code": "app.not_linked",
    "message": "No agentcloud.toml in this directory or above it.",
    "fix": "Run `agc init` in the app repository.",
    "docs": "agc help onboarding"
  },
  "next": [
    {
      "cmd": "agc init",
      "why": "create the app on agent.cloud and write agentcloud.toml"
    }
  ]
}
```

## Limits

| What | Limit |
|---|---|
| `name` | 64 characters |
| `entity` type / id | 32 / 64 characters |
| `related` | 10 entities |
| `status` | 16 characters |
| `attrs` in production | 4,000 characters of JSON; larger becomes `{"truncated":true}` |
| Production event retention | 30 days; rehearsal events, 1 day |
| Console Replay | Entities from the last 24 hours; an entity's steps from the last 7 days |

## Agent notes

- `agc replay` reads your mirror. For production, use `agc capsule <entity>` for its steps' shapes and counts, and the console's Replay tab for the person.
- `agc events` is a different list: the app's platform timeline (releases, approvals, rehearsals, failures), newest first, `--limit` 1 to 100 (default 30), `--failed` for failures only. It holds no workflow events.

- Print the event as the whole line, compact, with `"agc":"event"` as the first key: `console.log(JSON.stringify(…))` or `print(json.dumps(…))`. Pretty-printed JSON, or a logger that adds a timestamp or level prefix, works on your mirror and silently doesn't in production.
- Never put an email, a name or free text in `entity` or `attrs`. Owners see `attrs` unmasked.
- One event per step, named for what happened, with the entity a person would report (`booking:123`, not `request:abc`). That's what makes `agc capsule booking:123` useful later.
- Emit a `failed` event when a step fails, not only an error log: replay's `next` follows failed steps. With no event lines yet, `next` says so.

## Related

- [Investigating a reported problem](/docs/ship/investigating-a-reported-problem.md)
- [Logs](/docs/ship/investigating-a-reported-problem.md#logs)
- [Background work and workers](/docs/build/background-work-and-workers.md)

<!-- feedback:start -->
---
Wrong, outdated or unclear? Run `agc feedback docs "build/workflow-events-and-replay: <what is wrong>" --body <file>` with the sentence quoted in the file. No code or app data is sent.
<!-- feedback:end -->
