CLI & Day-2 Operations
All five auditstream subcommands (init, status, verify, history, export), auditstream.toml configuration, CI drift gating, and exit codes.
On this page
The static auditstream v0.2.2 CLI handles migrations, drift checks, history, and xid8 exports — data writes to stdout; logs and diagnostics write to stderr.
Global options
| Flag & environment | Default | Purpose |
|---|---|---|
--config <PATH>AUDITSTREAM_CONFIG |
./auditstream.toml |
Path to TOML configuration file |
--database-url <URL>AUDITSTREAM_DATABASE_URLDATABASE_URL |
none | PostgreSQL URL (env value hidden in --help, redacted in logs and errors) |
--schema <SCHEMA>AUDITSTREAM_SCHEMA |
auditstream |
Schema holding changes, functions, and triggers |
-v, -vv, -qAUDITSTREAM_LOG |
warn |
Stderr verbosity (-v info, -vv debug, -q error; env overrides flags) |
--log-format <text|json>AUDITSTREAM_LOG_FORMAT |
text |
Format stderr logs, notes, and fatal errors as plain text or single-line JSON |
Subcommands
init
Introspects tables, validates --exclude columns, writes idempotent migrations (prisma, drizzle, sql), and updates auditstream.toml without storing secrets:
auditstream init \
--migrations prisma \
--table public.invoice \
--table public.users \
--exclude public.users.password_hash \
--app-role app_user--app-role (repeatable) adds to capture.app_roles: the migration lets the role read the history and call log_event(). Use --dry-run to preview SQL on stdout, or --out <dir> to override default migration folders (prisma/migrations, drizzle, migrations).
status
Summarizes capture coverage and partition health from PostgreSQL system catalogs — never running count(*) over monthly partitions:
# Default human-readable text output
auditstream status --format text
# Machine-readable JSON output
auditstream status --format json- Formats:
--format text(default) or--format json. - Coverage: Lists every table (
captured/uncaptured), TOML presence, trigger state (enabled,disabled,partial,none), and excluded columns. - Partition stats: Reports
months_covered_ahead,changes_defaultrows (EXISTS ... LIMIT 1),pg_class.reltuples, andtotal_size_bytes. - Advisory exit: Exits 0 on successful catalog read; points operators to
auditstream verifyifproblems_found > 0.
verify
Runs all drift checks inside a READ ONLY transaction and exits 1 when findings meet --fail-on (default error; pass --fail-on warning to fail on warnings too):
missing— owner role, history table, attachedchanges_defaultpartition,changes_pkey, required history index, helper function, audited table, or expected trigger is missing.disabled— trigger or child-partition clone is disabled (tgenabled = 'D') or replica-only ('R').outdated— helper function body/signature/security settings,changes_pkeyor history index definition, child partition kind/DEFAULTname, or trigger definition/exclusions drifted.partitioned_table(warning) — audited table is partitioned (direct child writes bypass statement triggers).default_partition_rows— rows stranded inauditstream.changes_default, blocking partition attachment;--fixprints the SQL that moves them (repair_sqlin JSON).insufficient_partitions— the partition of the current UTC month is missing, or fewer than three contiguous monthly partitions exist ahead of it.invalid_exclusion— primary key, dropped/renamed, or unverified table column listed incapture.excludeor on an installed trigger.unsafe_privileges— unexpectedPUBLIC/non-owner grants on audit objects or child partitions, unsafe owner role attributes/memberships, an application role that is a superuser, hasCREATEROLE, owns an audited table or belongs to the owner role, orsession_replication_rolegrants/replicaoverrides.invalid_ownership— audit schema, history table/partitions, sequence, or helper function not owned by the database’s owner role.tampered_history— unexpected trigger, rewrite rule, or Row-Level Security onchangesor its partitions, or unexpected helper function overload in the audit schema.
# Non-zero exit (1) on any drift (suitable for CI / scheduled jobs)
auditstream verify --format json
# Create missing monthly partitions 4 months ahead before verifying
auditstream verify --fixSchedule in GitHub Actions using the reusable subpath action (verifies SHA-256 before extraction — pin both the action ref >= auditstream-v0.2.2 or full commit SHA and version, and pass optional sha256 from sha256.sum using the -musl archive on Linux):
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: auditstream/auditstream/actions/setup@auditstream-v0.2.2
with:
version: "0.2.2"
- name: Verify PostgreSQL audit trail health
env:
AUDITSTREAM_DATABASE_URL: ${{ secrets.AUDITSTREAM_VERIFY_URL }}
run: auditstream verify --format jsonFor read-only CI checks (without --fix), use a dedicated SELECT-only PostgreSQL role and enforce verified TLS (sslmode=verify-full for non-loopback hosts, plus sslrootcert for custom CAs):
CREATE ROLE auditstream_verify
LOGIN PASSWORD '<strong-password>'
NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT;
GRANT CONNECT ON DATABASE <your_db> TO auditstream_verify;
GRANT USAGE ON SCHEMA auditstream TO auditstream_verify;
GRANT SELECT ON auditstream.changes TO auditstream_verify;Run GRANT CONNECT ON DATABASE as the database owner or admin role. Run GRANT USAGE and GRANT SELECT as a superuser (or on managed PostgreSQL such as RDS, Cloud SQL, Neon, or Supabase inside a transaction that temporarily elevates to the owner role and revokes the temporary membership before committing). Never grant write privileges, WITH GRANT OPTION, or direct privileges on child partitions (auditstream.changes_* — verify probes changes_default via auditstream.changes and flags child grants as unsafe_privileges). Run scheduled --fix partition maintenance in a separate job with a direct (non-pooled) migration URL (Cloud, Poolers & Security).
history
Queries recent changes newest-first (occurred_at DESC, id DESC), matching direct actors, tenants, and delegated onBehalfOf entries:
auditstream history \
--table public.invoice \
--record-id 1 \
--actor usr_42 \
--tenant org_acme \
--since 2026-11-01 \
--limit 20--actor <ID>matchesactor.idoractor.onBehalfOf.id.--tenant <ID>matchesactor.tenantoractor.onBehalfOf.tenant(self-asserted metadata; pair with--since/--until, does not replace RLS).--limitaccepts1–1000(default100); pass--format jsonforevent.schema.jsonlines withbefore/after, or--diff(--format tableonly) for field-levelbefore -> afterdiffs. Both--format tableand--diffstrip ANSI/C0/C1 control sequences and Unicode BiDi overrides and normalize line breaks, including when redaction is active.- Automatic redaction: When
[[export.redaction.rules]]are configured inauditstream.toml,historyapplies them automatically across--format table,--diff, and--format jsonbefore writing to stdout (mode = "mask"masks values with"[redacted]"while keeping column names inchanged;mode = "remove"drops keys frombefore,after, andchanged). An informational note prints to stderr whenever redaction is active and events are returned (formatted per--log-format, suppressed by-q/--quiet). --redactand--unredacted: Pass--redactto require at least one configured[[export.redaction.rules]]rule (exits2without connecting if none exist — fail-closed for scripts and coding agents), or--unredactedas an explicit break-glass opt-out for local debugging (conflicts with--redact, exit2).--omit-payload: Setsbeforeandaftertonull(keepingevent.schema.jsoncompliance, event metadata, andchangedcolumn names) for compact, payload-free incident timelines and agent inspection. Conflicts with--diff(exit2); still appliesmode = "remove"rules tochangedunless--unredactedis also passed.
# Compact, payload-free timeline (metadata + changed column names only)
auditstream history --table public.invoice --format json --omit-payload --limit 20Default --format table output (wrapped across two lines for width):
OCCURRED_AT OP TABLE RECORD_ID
ACTOR ACTOR_SOURCE CHANGED
2026-11-24T04:11:09.184000Z UPDATE public.invoice {"id":1}
ai_agent:billing-agent for user:usr_42 comment status,paid_at
2026-11-24T04:08:12.004120Z INSERT public.invoice {"id":1}
user:usr_42 comment -export
Streams committed events in the lossless xid8 window (xact_id >= cursor AND xact_id < pg_snapshot_xmin()), advancing checkpoints only after flush (How Capture Works):
auditstream export \
--format jsonl \
--output audit.jsonl \
--cursor-file cursor.json \
--tenant org_acme \
--batch-size 1000- Flags:
--format jsonl|csv,--since,--until,--actor,--tenant,--source db|app,--batch-size N(default1000), and--from-start. - Cursor safety: Exits 2 if resumed against a different database, schema, filter set, sink format/path, or
export.redactionpolicy. - Atomicity: Holds an OS lock (
<cursor-file>.lock) and replaces checkpoint files atomically. - Pipes: Exits 0 cleanly on
SIGPIPEfor stateless stdout pipes (auditstream export | head -n 5).
Configuration
Precedence: CLI flag → env var (global options) → auditstream.toml → default; unknown keys or invalid types exit 2.
schema = "auditstream"
[capture]
tables = ["public.invoice", "public.line_item"]
# Stripped at trigger capture time
exclude = ["public.invoice.password_hash"]
[migrations]
format = "prisma" # "prisma", "drizzle", or "sql"
dir = "prisma/migrations"
[export]
cursor_file = ".auditstream.cursor"
batch_size = 1000
[export.sink]
type = "jsonl" # "jsonl" (default) or "csv"
path = "events.jsonl" # omit to stream to stdout
# Redaction for export (and history): mask ("[redacted]") or remove
# top-level keys in before/after payloads
[[export.redaction.rules]]
table = "public.invoice" # "table", "schema.table", or "*"
columns = ["ssn", "tax_id"]
mode = "mask" # "mask" (default) or "remove"
[[export.redaction.rules]]
action = "invoice.exported" # app-event op (source = "app"), or "*"
columns = ["recipient_email"]
mode = "remove"- Secrets in
capture.exclude: Strip password hashes, credentials, PAN/CVV, and tokens at capture time so triggers never store them inauditstream.changes; use[[export.redaction.rules]]for app events,historyinspection, or two-tier exports. - Top-level keys only (
record_iduntouched in v0.2): Dot-paths (metadata.ssn) exit2at startup; untouched key order and arbitrary-precision PostgreSQLnumericvalues stay intact.record_idis never redacted in v0.1 — prefer surrogate primary keys and opaquelog_event()targetIDs (nested JSONB andrecord_idredaction are planned for v0.3). - Fail-closed: If a matching rule hits a non-object or malformed JSON payload,
exportexits5before writing or advancing the cursor, andhistoryexits5before emitting the redaction note or writing to stdout (unless--omit-payloador--unredactedis passed).
Exit codes
Exit codes are part of the public contract. By default (plain text; --log-format text), every failure other than CLI argument parse errors writes one error: line to stderr without writing error diagnostics to stdout; with --log-format json / AUDITSTREAM_LOG_FORMAT=json, all fatal failures (including CLI argument parse errors) emit a single-line JSON ERROR record with exit_code on stderr only.
| Code | Name | Meaning |
|---|---|---|
| 0 | Success | Command succeeded (including --help, --version, empty history, and BrokenPipe on stateless stdout streams) |
| 1 | Check failed | auditstream verify found problems meeting --fail-on (default error): drift, disabled triggers, unsafe privileges, invalid ownership, history tampering, invalid exclusions, changes_default rows, a missing current month, or fewer than 3 future partitions |
| 2 | Usage / config | Invalid CLI flags, missing --config, unknown TOML key, invalid filter/redaction rule, --redact without configured rules, or incompatible checkpoint |
| 3 | Database error | PostgreSQL connection, permission, query, migration, or verify --fix failure |
| 4 | Output / cursor | Filesystem I/O error, held cursor lock, corrupt cursor, truncated output file, or BrokenPipe with --cursor-file |
| 5 | Internal error | Fail-closed redaction error on a non-object/malformed payload or unexpected internal error |
| 101 | Panic | Uncaught Rust runtime panic |