# postact CLI

Everything postact does is reachable from one command line tool, so a coding agent can build a
project's whole customer backend without a browser. This file is served verbatim at
<https://postact.app/docs/cli.md> — `curl` it, don't scrape the HTML docs.

If you are that agent: read *Building an action*, *The three shapes of an action* and
*Wiring up analytics*. They are the parts that are not guessable from `--help`.

---

## Install and sign in

```sh
npm i -g @postact-js/cli
postact login            # device flow: prints a URL + code, opens a browser if there is one
postact whoami
postact projects ls
postact projects use acme    # save the default project for every later command
```

`postact login` is headless-safe: it prints the URL and the code and polls, so approving on a
phone or another machine works. The session token and the default project land in
`$XDG_CONFIG_HOME/postact/config.json` (`%APPDATA%\postact\config.json` on Windows), written
`0600`.

The API base is `https://api.postact.app`. Override it with `POSTACT_API_URL` or `--api <url>`
per call (`--api` wins, then the env var, then the saved config). Working on the postact repo
itself, that means `POSTACT_API_URL=http://localhost:3001`.

**Pass `--json` to everything.** Without it the output is a human-readable table; with it you get
the raw JSON body, which is what you want to pipe into `jq`.

`-p/--project <slug|id>` overrides the saved default on any project command; both a slug and a
UUID work (a slug is resolved against your project list).

---

## Command reference

Every command below also takes `-p/--project <slug|id>`, `--json` and `--api <url>`.
`postact help <group>` prints the same table offline; `postact help --json` prints it as JSON.

### Auth

| Command | What it does |
|---|---|
| `postact login` | device-code login; stores the session token |
| `postact logout` | revoke the token and clear the local config |
| `postact whoami` | the signed-in user |

### projects — list, create and pick the project every other command acts on

| Command | What it does |
|---|---|
| `postact projects ls` | every project you can see |
| `postact projects get` | the current project plus its sidebar counts |
| `postact projects create <name>` | new project — **prints the sk exactly once** |
| `postact projects use <slug\|id>` | save the default project |

### actions — a trigger plus the ordered steps that run

| Command | What it does |
|---|---|
| `postact actions ls` | actions with their run, backlog and failure counts — no steps |
| `postact actions get <actionId>` | one action, steps included |
| `postact actions create -d '<json>'` | create; `--name --slug --trigger` are shortcuts |
| `postact actions update <actionId> -d '<json>'` | **full replace**, not a merge |
| `postact actions rm <actionId>` | delete |
| `postact actions run <actionId>` | run a manual/scheduled action against its saved view |

### people — the merged customer records

| Command | What it does |
|---|---|
| `postact people ls` | every person in the project |
| `postact people get <personId>` | one person with identifiers, events and emails |
| `postact people create <email> -d '<metadata>'` | create or merge; `--identifiers '{"id":"u_1"}'` |
| `postact people update <personId> -d '<metadata>'` | merge metadata keys; `--email` to change the anchor |
| `postact people rm <personId>` | soft-delete and free their identifiers |

### events — the queue, one row per action run

| Command | What it does |
|---|---|
| `postact events ls [filterId]` | a view's events; defaults to the `queue` built-in |
| `postact events reply <eventId> --body '<text>' [--close]` | reply on an event; `--template <id>` sends a template instead |
| `postact events status <eventId> <open\|closed>` | open or close it |

### filters — saved views: WHERE conditions plus one GROUP key

| Command | What it does |
|---|---|
| `postact filters ls` | saved views |
| `postact filters view <filterId>` | run a view: its rows plus full-set counts |
| `postact filters create --name '<name>' --scope <people\|events> -d '<json>'` | save a view |
| `postact filters rm <filterId>` | delete |

### templates — email templates

| Command | What it does |
|---|---|
| `postact templates ls` | every template |
| `postact templates get <templateId>` | one template |
| `postact templates create --name '<n>' --subject '<s>' --body '<html>' [--from <senderId\|email>]` | create; `--from` pins who it sends as |
| `postact templates update <templateId> --body '<html>' [--from <senderId\|email>]` | replace it — **no `--from` un-pins the sender** |
| `postact templates rm <templateId>` | delete |

### The rest

| Command | What it does |
|---|---|
| `postact emails ls` | the sent log |
| `postact keys show` | the pk, and the sk's fingerprint |
| `postact keys rotate` | new sk, **printed once**; the old one stops working |
| `postact vault ls` · `postact vault set <NAME> <value>` · `postact vault rm <secretId>` | encrypted per-project secrets |
| `postact domains ls` · `postact domains add <domain>` · `postact domains records <domainId>` · `postact domains verify <domainId>` · `postact domains rm <domainId>` | sending domains and the DNS records that verify them |
| `postact senders ls` · `postact senders add <email> [--name '<display name>']` · `postact senders default <senderId\|email\|none>` · `postact senders verify <senderId>` · `postact senders resend <senderId>` · `postact senders rm <senderId>` | one From address each — free under a domain of yours, otherwise confirmed by clicking a link. See **Sending as your own address** |
| `postact collaborators ls` · `postact collaborators invite <email>` · `postact collaborators resend <inviteId>` · `postact collaborators rm-invite <inviteId>` · `postact collaborators rm-member <memberId>` | members and invites |
| `postact branding show` · `postact branding set -d '{"logoUrl":"…","accentColor":"#4a86d0","footerText":"…"}'` | what every email looks like |
| `postact project rename --name '<n>' [--slug <s>]` | rename the project |
| `postact project rm --yes` | delete the project and everything in it |

There is no `scripts` group yet — script bodies are written in the dashboard. Scripts themselves
do run; see **Scripts** below for what a step gets and what it can do.

### `-d/--data`

`-d` takes inline JSON, `@path/to/file.json`, or `-` for stdin. It is the full request body;
the named shortcut flags (`--name`, `--slug`, `--trigger`, …) are merged over it, so a flag wins
over the same key inside `--data`. Anything a body accepts but has no flag for — `steps`,
`origins`, `transientKeys`, `conditions` — has to come in through `-d`.

```sh
postact actions create -d @signup-action.json --json
cat signup-action.json | postact actions create -d - --json
```

---

## Building an action from the CLI

An action is a **name**, a **slug** (its URL segment), a **trigger** and ordered **steps**.
Only name/slug/trigger have shortcut flags, so `steps` always arrives via `-d`.

Step shapes, exactly:

```jsonc
{ "type": "reply_email", "template": { "literal": "<templateId>" } }  // send a template
{ "type": "mark_closed" }                                             // close the event
{ "type": "script", "scriptId": "<uuid>" }                            // run a stored script
```

`template` is a *socket*: exactly one of `{"literal": "<uuid>"}` or `{"script": "<uuid>"}`,
never both and never neither. A `{"script": …}` socket is filled by what that script returns —
only a non-empty string fills one, so a script that fails, times out or returns nothing leaves
the socket empty and its step is skipped. A `reply_email` step may also carry an optional `to`
socket to send somewhere other than the person's own email.

Triggers: `post_server` (your backend, `sk_…`), `post_client` (the browser, `pk_…`, restricted to
the `origins` you list on the action), `schedule` (needs `scheduleHour` + `scheduleMinute`, plus a
`filterId` for who it goes to), `manual` (you run it from the dashboard or `postact actions run`).

A template first, then the action that points at it:

```sh
TPL=$(postact templates create --json \
  --name "Welcome" --subject "Welcome to Acme" \
  --body '<p>Hi {{person.metadata.name}}, thanks for signing up.</p>' | jq -r .id)

postact actions create --json -d "$(cat <<JSON
{
  "name": "Signup",
  "slug": "signup",
  "trigger": "post_server",
  "steps": [
    { "type": "reply_email", "template": { "literal": "$TPL" } },
    { "type": "mark_closed" }
  ]
}
JSON
)"
```

Your backend then fires it with the project's secret key:

```
POST https://api.postact.app/api/p/<project>/a/signup
Authorization: Bearer sk_…
{ "person": { "email": "…", "identifiers": {…}, "metadata": {…} }, "payload": {…} }
```

`actions update` is a **full replace** — send the whole body, including the steps you are not
changing, or `postact actions get <id> --json` first and edit that.

---

## Scripts

A `script` step, and a `{"script": …}` socket, run a stored script body when the run reaches it.
It is JavaScript in an isolated QuickJS interpreter: no network, no filesystem, no timers, no
`require`/`import`, 250ms and 32MB. There is no `await` — everything a script sees is already
there:

| It gets | What it is |
|---|---|
| `payload` | the body of the call that triggered the run, before transient keys are redacted |
| `person` | `{ email, metadata }`, plus `person.set(key, value)` and `person.unset(key)` |
| `event` | `{ id, status }` of the event this run created |
| `env` | the project's vault secrets by name — `env.STRIPE_KEY`. Readable here and nowhere else |

It can do two things:

- **`person.set(key, value)` / `person.unset(key)`** — queued during the run and written back
  when it finishes, with the same provenance a `sk_…` call has, so a later `pk_…` call cannot
  overwrite it. A step below the script renders the metadata it just wrote.
- **`return <value>`** — a non-empty string fills the socket that points at the script (a
  template id for `template`, an address for `to`). Anything else leaves the socket empty.

A script that throws, times out or returns nothing costs **its own step**, never the run: later
steps still execute. Whatever it `console.log`s is kept with the event and shown in the queue,
with any vault value it printed replaced by `[secret]`.

```js
// tag where a signup came from, then pick the mail to send
person.set("source", payload.utm_source ?? "direct");
return payload.plan === "team" ? "<team-welcome-template-uuid>" : "<welcome-template-uuid>";
```

Dry-run one without firing a real event (this is the API the dashboard editor uses; there is no
CLI verb for it yet):

```sh
POST /app/p/<projectId>/scripts/<scriptId>/test
{ "payload": { "utm_source": "hn" }, "person": { "email": "a@b.com", "metadata": {} } }
→ { "status": "ok", "value": "…", "logs": […], "patch": { "set": {…}, "unset": [] },
    "error": null, "durationMs": 3 }
```

It writes nothing — no person, no event — and `env` holds `"[secret]"` in place of every real
value, because the vault has no read path.

---

## The three shapes of an action

Nearly everything is one of three shapes. A new project ships with three actions covering two of
them — `reset-password` and `signup` are transactional, `support` is contact mail. **Nothing
analytics-shaped is seeded**; that one you write yourself. Read the real steps of a seeded action
with `postact actions get <actionId> --json` — `actions ls` lists actions and their counts, never
their steps.

### 1. Transactional mail — send something with a secret in it

The password-reset shape. Server-triggered, sends a template, closes the event.

```jsonc
{
  "name": "Reset password", "slug": "reset-password", "trigger": "post_server",
  "steps": [
    { "type": "reply_email", "template": { "literal": "<templateId>" } },
    { "type": "mark_closed" }
  ],
  "transientKeys": ["link"]
}
```

`transientKeys` is the rule to learn: `{{payload.link}}` renders into the mail with the real
value, and the *stored* event keeps `[REDACTED]`. Reset links, OTP codes, invoice URLs, signed
download links — anything that must reach the inbox but must not sit in your event log. List the
payload key here, never rely on deleting it afterwards.

### 2. Contact mail — a message from a human that a human answers

The support-form shape. Client-triggered so the browser can call it with the `pk_`, sends an
acknowledgement, and **deliberately has no `mark_closed`**: the open event *is* the ticket.

```jsonc
{
  "name": "Support", "slug": "support", "trigger": "post_client",
  "origins": ["https://acme.com"],
  "steps": [{ "type": "reply_email", "template": { "literal": "<ackTemplateId>" } }]
}
```

Work the resulting inbox from the CLI:

```sh
postact events ls --json                                   # the `queue` view = every open event
postact events reply <eventId> --body "Fixed — sorry!" --close
postact events status <eventId> closed                     # close without writing anything
```

A customer replying to any mail you sent routes back to the same action and reopens the event.

### 3. Analytics — the event *is* the point

No mail, nothing to answer. One action per meaningful thing that happens, whose only step closes
the event it just created.

```jsonc
{ "name": "Activated", "slug": "activated", "trigger": "post_server",
  "steps": [{ "type": "mark_closed" }] }
```

**The `mark_closed` is not optional, and leaving it out is the single most expensive mistake you
can make here.** Every event is created `open`, and the `queue` built-in view is exactly
`status = open` — your support inbox. An analytics action with no steps therefore drops every
single `page_view` into the same queue a customer's support mail lands in, and within a day the
real tickets are unfindable. If an action's events are never going to be read by a human one at a
time, it closes them.

---

## Wiring up analytics

1. **One action per meaningful event, all closing.** `signup`, `activated`, `invited-teammate`,
   `upgraded`, `churned`. Not `track` with an `event` key in the payload: actions are the axis
   the dashboard groups, counts and filters on, so a single generic action collapses into one
   undifferentiated number.

   ```sh
   for slug in signup activated upgraded churned; do
     postact actions create --json -d "{\"name\":\"$slug\",\"slug\":\"$slug\",
       \"trigger\":\"post_server\",\"steps\":[{\"type\":\"mark_closed\"}]}"
   done
   ```

2. **Identity travels on the person, not in the payload.** Every call carries
   `person.identifiers` (your ids — `{"id":"u_102","session":"s_88"}`) and `person.metadata`
   (`plan`, `company`, `cohort`, anything). Metadata *is* the schema: there is nothing to declare,
   keys merge latest-value-wins, and a key written with the `sk_` can never be overwritten from
   the browser with the `pk_`. Two keys are read by the product: `name` becomes the person's card
   title and `last_seen_at` (ISO timestamp) drives the activity chip. `payload` is for what was
   true about *this one call* — the plan they upgraded to, the page they were on.

3. **Read it back as views.** A view is WHERE conditions plus one GROUP key, over `people` or
   `events`.

   ```sh
   postact filters create --name "Old trials" --scope people --json -d '{
     "conditions": [
       { "field": "metadata.plan", "op": "eq",              "value": "trial" },
       { "field": "created_at",    "op": "older_than_days", "value": 7 }
     ],
     "groupKey": "metadata.plan"
   }'
   postact filters view <filterId> --json     # rows + full-set counts, not just the page
   ```

   Fields: on `people` — `email`, `created_at`, `last_event_status`, and any `metadata.<key>`;
   on `events` — `status`, `action`, `created_at`, and any `payload.<key>`. Ops: `eq`, `neq`,
   `contains`, `gt`, `lt`, `exists`, `not_exists`, `older_than_days`, `within_days`. A field the
   registry cannot resolve is rejected when you save it, rather than quietly matching nothing.

   **Not every op works on every field, and the wrong pairing is a 400 when you save it.** A
   `metadata.<key>` / `payload.<key>` is read out of jsonb as *text*, so:

   - `older_than_days` and `within_days` compare against a real timestamp — they only work on
     the fixed timestamp column, `created_at`. Point one at `metadata.last_seen_at` and the save
     is refused with the reason ("`older than days` needs a timestamp field — metadata.last_seen_at
     is text"). Store your own recency as a `metadata.last_seen_at` string for display if you
     like, but filter recency on `created_at`.
   - `contains` is the mirror image: it is `ilike`, so it works on text and not on `created_at`.
     A `created_at` value has to be a date (`2026-01-01`, `2026-01-01T09:00:00Z`).
   - `gt` and `lt` cast a jsonb key to `numeric`, so they are number-only. **This one is not
     caught at save time**, because it depends on the rows rather than on the condition: `gt` on
     a key that holds text errors on read, once one person's value isn't a number.
   - `eq`, `neq`, `exists` and `not_exists` are safe on anything.

   A view written before this was enforced still exists and still reads — a condition the
   database cannot plan matches nobody rather than erroring, the same way an unknown field does.
   So a view that silently returns 0 with conditions that look right is worth re-saving: the
   400 will tell you which pairing is wrong.

4. **Counts without writing a query.** `postact actions ls --json` gives every action a
   `runs7d` (trailing-seven-day runs), an `open` (all-time queue depth) and a `failed`
   (permanently-failed jobs) — the fastest read on whether your instrumentation is actually
   firing. An analytics action with a climbing `open` is one that forgot its `mark_closed`.

5. **Act on a view.** A `schedule`-triggered action with a `filterId` runs for everyone the view
   matches, on a timer:

   ```sh
   postact actions create --json -d '{
     "name": "Trial nudge", "slug": "trial-nudge", "trigger": "schedule",
     "scheduleHour": 9, "scheduleMinute": 0, "filterId": "<filterId>",
     "steps": [{ "type": "reply_email", "template": { "literal": "<templateId>" } },
               { "type": "mark_closed" }]
   }'
   ```

   A view's conditions are re-read every run, never frozen when you bind them — editing the view
   changes who the action mails tomorrow morning.

---

## Sending as your own address

Out of the box mail leaves from the shared postact address. To send as yourself, register the
domain and let its DKIM cover every address under it:

```sh
postact domains add acme.com --json
postact domains records <domainId>                # publish every row at your DNS host
postact domains verify <domainId>                 # re-check until it says verified
```

With `acme.com` verified, an address under it costs one command and **no confirmation mail** —
the domain's signature already authorises it, and `senders add` says so:

```sh
postact senders add support@acme.com --name "Acme Support"
# support@acme.com is authorised by your verified domain — nothing to confirm.

postact senders add billing@acme.com --name "Acme Billing"
postact senders default support@acme.com          # everything sends as Acme Support <support@acme.com>
postact senders ls                                # displayName, status and isDefault per row
```

Adding the addresses before the domain verifies is fine: they come back `pending`, `senders add`
points you at `domains verify` rather than at a mailbox, and the domain verifying flips every
address under it in one go — you never run `senders verify` on one of these.

An address whose domain lives somewhere you cannot add DNS to (Gmail, Workspace) is confirmed
out of band instead — `senders add` mails it a link and tells you to click it, then
`postact senders verify <senderId>`.

Then pin the invoices to the other address, leaving everything else on the default:

```sh
postact templates update <templateId> --from billing@acme.com \
  --name "Invoice" --subject "Your invoice" --body '<p>…</p>'
```

`--from` takes a sender id or the address itself. **`templates update` is a full replace**, so
send `--name`, `--subject` and `--body` with it — and note that a later update *without*
`--from` un-pins the sender again, the same way it would drop a subject you did not resend.

The From address of any one email is the first of these that exists: the sender its template is
pinned to, then `senders default`, then your oldest confirmed sender, then `no-reply@` at your
verified domain, then the shared postact address. A sender that is still `pending` is skipped
rather than blocking the send, so nominating one before its domain verifies is safe.
`postact senders default none` clears the nomination and falls back to the rest of that chain.

---

## Gotchas

- **`--json` on everything.** The default output is a table meant for a human.
- **`actions update` and `templates update` replace the whole body.** Read, edit, send back. On a
  template that includes its `--from`: omitting the flag un-pins the sender, and `templates
  update <id> --from x` on its own is a 400, because `--name`, `--subject` and `--body` are the
  rest of the body you just replaced.
- **The sk is shown exactly once** — by `projects create` and by `keys rotate`. There is no
  command that prints it again; losing it means rotating, which invalidates the old one.
- **`project rm` refuses without `--yes`.** It cascades every person, event, action and email.
- **`people update` merges the metadata keys you send** and leaves the rest alone; it never
  removes a key. Pass `--email` only when you actually mean to change the anchor.
- **`events ls` defaults to the `queue` view** (open events), not to everything. Pass a saved
  view's id to see another slice. `queue` and `people` are built-in pseudo-views: they always
  resolve, but they have no row to save over, so `filters rm queue` is a 404.
- **A filter's op has to match its field's type.** `older_than_days` / `within_days` only work on
  `created_at`, `contains` only on text, and a `created_at` value has to be a date: those are
  refused at save time, with the reason in the `error`. `gt` / `lt` on a `metadata.*` or
  `payload.*` key are numeric-only, and that one depends on the data, so it still errors on read
  — see *Wiring up analytics*.
- **A `pk_` cannot call a `post_server` action**, and a `post_client` action only answers the
  origins listed on it (`localhost` is allowed outside production).
- **Email needs a verified sending domain, or one confirmed address.** Either
  `postact domains add acme.com`, publish everything `postact domains records <id>` lists (the
  provider's CNAMEs, plus the `_dmarc` TXT — a domain with no DMARC policy at or above it never
  verifies, because its mail would land in spam), then `postact domains verify <id>` — or, when
  the domain has to stay where it is (Gmail /
  Workspace), `postact senders add website@acme.com`, click the link mailed to that address, then
  `postact senders verify <id>`. A confirmed address wins over the domain's `no-reply@`; with
  neither, mail goes out from the shared postact address. Which address exactly, and how to pin
  one template to another sender: **Sending as your own address**.
- **`senders add` under a domain you have verified mails nothing.** The domain's DKIM already
  authorises the address, so the row comes back `verified` and there is no link to click:
  `senders resend` on it is a 400 by design, not a fault.
- **Slugs are lowercase letters, digits and dashes**, and a taken project slug gets a random
  suffix (`acme` → `acme-9f2c`). `projects create` prints only the id and the sk, so read the
  slug you actually got from `postact projects ls --json` before you put it in a URL.
