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.1.0 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_URL
DATABASE_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, -q
AUDITSTREAM_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 (v0.1.1+)

Subcommands

init

Introspects tables, validates --exclude columns, writes idempotent migrations (prisma, drizzle, sql), and updates auditstream.toml without storing secrets:

bash
auditstream init \
  --migrations prisma \
  --table public.invoice \
  --table public.users \
  --exclude public.users.password_hash

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:

bash
# 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_default rows (EXISTS ... LIMIT 1), pg_class.reltuples, and total_size_bytes.
  • Advisory exit: Exits 0 on successful catalog read; points operators to auditstream verify if problems_found > 0.

verify

Runs all drift checks inside a READ ONLY transaction and exits 1 when findings meet --fail-on (v0.1.1+, default error; pass --fail-on warning to fail on warnings too):

  • missing — auditstream_owner, history table, attached changes_default partition, 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_pkey or history index definition, child partition kind/DEFAULT name, or trigger definition/exclusions drifted.
  • partitioned_table (warning) — audited table is partitioned (direct child writes bypass statement triggers).
  • default_partition_rows — rows stranded in auditstream.changes_default, blocking partition attachment.
  • insufficient_partitions — fewer than two contiguous monthly partitions exist ahead of UTC now.
  • invalid_exclusion (v0.1.1+) — primary key, dropped/renamed, or unverified table column listed in capture.exclude or on an installed trigger.
  • unsafe_privileges (v0.1.1+) — unexpected PUBLIC/non-owner grants on audit objects or child partitions, unsafe auditstream_owner attributes/memberships, or session_replication_role grants/replica overrides.
  • invalid_ownership (v0.1.1+) — audit schema, history table/partitions, sequence, or helper function not owned by auditstream_owner.
  • tampered_history (v0.1.1+) — unexpected trigger, rewrite rule, or Row-Level Security on changes or its partitions, or unexpected helper function overload in the audit schema.
bash
# Non-zero exit (1) on any drift (suitable for CI / scheduled jobs)
auditstream verify --format json

# Create missing monthly partitions 3 months ahead before verifying
auditstream verify --fix

Schedule in GitHub Actions using the reusable subpath action (v0.1.1+; verifies SHA-256 before extraction — pin both the action ref >= auditstream-v0.1.1 or full commit SHA and version, and pass optional sha256 from sha256.sum using the -musl archive on Linux):

yaml
- uses: actions/checkout@v4
  with:
    persist-credentials: false

- uses: auditstream/auditstream/actions/setup@auditstream-v0.1.1
  with:
    version: "0.1.1"

- name: Verify PostgreSQL audit trail health
  env:
    AUDITSTREAM_DATABASE_URL: ${{ secrets.AUDITSTREAM_VERIFY_URL }}
  run: auditstream verify --format json

For read-only CI checks (v0.1.1+, 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):

sql
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 auditstream_owner 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:

bash
auditstream history \
  --table public.invoice \
  --record-id 1 \
  --actor usr_42 \
  --tenant org_acme \
  --since 2026-11-01 \
  --limit 20
  • --actor <ID> matches actor.id or actor.onBehalfOf.id.
  • --tenant <ID> matches actor.tenant or actor.onBehalfOf.tenant (self-asserted metadata; pair with --since/--until, does not replace RLS).
  • --limit accepts 1–1000 (default 100); pass --format json for event.schema.json lines with before/after, or --diff (v0.1.1+, --format table only) for field-level before -> after diffs. Both --format table and --diff strip ANSI/C0/C1 control sequences and Unicode BiDi overrides and normalize line breaks (v0.1.1+), including when redaction is active.
  • Automatic redaction (v0.1.1+): When [[export.redaction.rules]] are configured in auditstream.toml, history applies them automatically across --format table, --diff, and --format json before writing to stdout (mode = "mask" masks values with "[redacted]" while keeping column names in changed; mode = "remove" drops keys from before, after, and changed). An informational note prints to stderr whenever redaction is active and events are returned (formatted per --log-format, suppressed by -q/--quiet).
  • --redact and --unredacted (v0.1.1+): Pass --redact to require at least one configured [[export.redaction.rules]] rule (exits 2 without connecting if none exist — fail-closed for scripts and coding agents), or --unredacted as an explicit break-glass opt-out for local debugging (conflicts with --redact, exit 2).
  • --omit-payload (v0.1.1+): Sets before and after to null (keeping event.schema.json compliance, event metadata, and changed column names) for compact, payload-free incident timelines and agent inspection. Conflicts with --diff (exit 2); still applies mode = "remove" rules to changed unless --unredacted is also passed.
bash
# Compact, payload-free timeline (metadata + changed column names only; v0.1.1+)
auditstream history --table public.invoice --format json --omit-payload --limit 20

Default --format table output (wrapped across two lines for width):

text
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):

bash
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 (default 1000), and --from-start.
  • Cursor safety: Exits 2 if resumed against a different database, schema, filter set, sink format/path, or export.redaction policy.
  • Atomicity: Holds an OS lock (<cursor-file>.lock) and replaces checkpoint files atomically.
  • Pipes: Exits 0 cleanly on SIGPIPE for 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.

toml
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 in v0.1.1+): 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 in auditstream.changes; use [[export.redaction.rules]] for app events, history inspection (v0.1.1+), or two-tier exports.
  • Top-level keys only (record_id untouched in v0.1): Dot-paths (metadata.ssn) exit 2 at startup; untouched key order and arbitrary-precision PostgreSQL numeric values stay intact. record_id is never redacted in v0.1 — prefer surrogate primary keys and opaque log_event() target IDs (nested JSONB and record_id redaction are planned for v0.3).
  • Fail-closed: If a matching rule hits a non-object or malformed JSON payload, export exits 5 before writing or advancing the cursor, and history (v0.1.1+) exits 5 before emitting the redaction note or writing to stdout (unless --omit-payload or --unredacted is passed).

Exit codes

Exit codes are part of the public contract. By default (plain text; --log-format text in v0.1.1+), 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 (v0.1.1+), 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 (v0.1.1+, default error): drift, disabled triggers, unsafe privileges, invalid ownership, history tampering, invalid exclusions, changes_default rows, or fewer than 2 future partitions
2 Usage / config Invalid CLI flags, missing --config, unknown TOML key, invalid filter/redaction rule, --redact (v0.1.1+) 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