Skip to content

CLI ​

Complete reference of the accessnexus command. Workflow and examples: CLI guide.

sh
npx accessnexus <command> [flags]
npx accessnexus <command> --help
CommandPurposeTouches the database
initSet up AccessNexus in a project (schema, config, SDK wrappers, AGENTS.md)only with introspection (read-only)
validateCheck the schema without writing anythingonly with --against-db (rolled back)
diffShow what generate would change, without writingno
generateWrite migrations, RLS policies, triggers, RPCs and the typed SDKno
pushApply the generated SQL to the databaseyes
migrationdiscard the newest unapplied migration, or create a data migration (backfill)discard: read-only check
test-dbStart or remove a disposable local Supabase Postgres (Docker) for RLS testsa local container only
seedInsert seed datayes
helpShow help (also --help, -h, or no command)no
versionPrint the installed version (also --version, -v)no

Global flags ​

Accepted by every command.

FlagTypeDefaultDescription
--jsonbooleanfalsePrint exactly one JSON object on stdout; no colors, no progress output.
--verbosebooleanfalseDebug output on stderr and stack traces on errors. Same as DEBUG=accessnexus.
--help, -hbooleanfalseShow help for the command (with --json: the help as JSON).
--config <path>stringaccessnexus.config.{ts,js,mjs} in cwdConfig file. A missing explicit path is CONFIG_NOT_FOUND.

Flag parsing ​

  • Flags are strict per command: an unknown flag is UNKNOWN_FLAG (with a did-you-mean hint), a positional argument is UNEXPECTED_ARGUMENT.
  • String flags accept --flag value and --flag=value. A missing value (end of argv, or the next token starts with --) is MISSING_FLAG_VALUE.
  • Boolean flags take no value: --flag=x is INVALID_FLAG_VALUE.
  • Short aliases: -h (--help), -y (--yes, init only).
  • Negative flags are declared as such (--no-introspect, --no-agents); there is no generic --no-<flag>.

Config resolution ​

  1. --config <path> if given, else the first of accessnexus.config.ts, accessnexus.config.js, accessnexus.config.mjs in the current directory. No config file is fine: defaults apply.
  2. The file is bundled with esbuild and imported; its default export (or the module namespace) must be an object (CONFIG_INVALID).
  3. Values are merged, flags first:
SettingPrecedence
Schema file--schema > config.schema > ./accessnexus.schema.ts
Seed file (seed)--seed <path> > config.seed > ./accessnexus.seed.ts
Output folders--output <dir> (every category under <dir>, config folders ignored) > config.output.<category> > config.output.dir/<category> > ./generated/<category>
Policy prefixconfig.adapterOptions.policyPrefix > --prefix > config.naming.policyPrefix > accessnexus
SQL / SDK only--sql-only / --sdk-only or config.generate.sqlOnly / sdkOnly; passing both flags is INVALID_FLAGS
Database URLsee Database URL

All paths resolve from the current working directory. Before running a command, .env and .env.local in the current directory are loaded; variables already set in the environment are not overridden.

init ​

Set up AccessNexus in the current project: accessnexus.schema.ts (template, or imported from the database), accessnexus.config.ts, SDK wrapper files, an accessnexus npm script, and an AccessNexus block in AGENTS.md (plus a pointer in CLAUDE.md if it exists).

FlagTypeDefaultDescription
--yes, -ybooleanfalseNon-interactive: accept defaults, never prompt. Required when stdin is not a TTY or with --json (INIT_NOT_INTERACTIVE).
--src <dir>stringdetected (src or .)Source folder.
--sdk <dir>string<src>/lib/accessnexusSDK output folder.
--prefix <name>stringaccessnexusPolicy name prefix.
--db-url <url>stringnonePostgres URL to import tables, RLS policies and functions. Needs pg.
--no-introspectbooleanfalseDo not read the database; write a template schema.
--installbooleanfalseWith --yes: install missing @supabase/* packages.
--forcebooleanfalseWith --yes: overwrite an existing accessnexus.schema.ts.
--no-agentsbooleanfalseDo not write the AccessNexus block into AGENTS.md / CLAUDE.md.

Behavior:

  • If accessnexus.schema.ts exists and --force is not set, the schema is kept, the AGENTS.md block is refreshed, and the result has status: 'already_initialized'.
  • With --yes in a folder without package.json, a minimal one ("type": "module") is created.
  • Introspection source, unless --no-introspect: --db-url; else (non-interactive) a URL in ACCESSNEXUS_DB_URL / SUPABASE_DB_URL / DATABASE_URL; else the REST API with a Supabase URL and service key from .env* files (tables only, no policies). Otherwise a template schema.

validate ​

Load and check the schema; write nothing.

FlagTypeDefaultDescription
--schema <path>stringconfig.schema or ./accessnexus.schema.tsSchema file.
--against-dbbooleanfalseAlso compile the generated SQL in a rolled-back transaction on the database (see below).
--url <db-url> / --adapter <name> / --target <name>stringsee Database URLWith --against-db: same resolution as push. Alias of --url: --db-url.

Exits 1 with SCHEMA_VALIDATION_FAILED when any issue has severity error; warnings are listed but do not fail. Issue codes: Errors.

Compile against the database (--against-db) ​

validate --against-db compiles everything push would run, including the raw SQL that static checks cannot read: policy.custom conditions, trigger.custom bodies, RPC bodies and check expressions. It runs in a transaction that is always rolled back, so nothing persists. When Postgres rejects a statement, the issue is an error SQL_REJECTED and its path names the schema item (rpcs.<name>, <table>.triggers[<i>], <table>.policies.<op>), so you fix the right place. Catches typos in column names inside custom SQL, bad casts and syntax errors before push.

bash
npx accessnexus validate --against-db --json

generate ​

Write migrations, policies, triggers, RPCs and the SDK. Runs the same checks as validate first.

FlagTypeDefaultDescription
--schema <path>stringconfig.schema or ./accessnexus.schema.tsSchema file.
--output <dir>string./generatedPut every output folder under <dir>, overriding the config's output paths.
--sql-onlybooleanfalseOnly SQL (migrations, policies, triggers, RPCs).
--sdk-onlybooleanfalseOnly the typed SDK.
--prefix <name>stringaccessnexusPolicy name prefix.

Output:

FolderFiles
migrations<UTC timestamp>__init.sql on the first run, then <UTC timestamp>__changes.sql when the schema changed; .snapshot.json (state for the next diff). Timestamp format YYYYMMDDHHMMSS. Nothing new when the schema is unchanged. Database mode: none.
policies<table>_rls.sql
triggers<table>_triggers.sql
rpcsrpcs.sql
sdktypes.ts + client.ts (manual), client.ts (Database mode)

A file whose content differs only in the -- Generated at: line is left untouched (unchanged). Destructive statements in migrations written by this run are reported in destructive.

generate and diff also add a warning NOT_NULL_COLUMN_ADDED (in warnings) when a new migration adds a NOT NULL column without a default to an existing table: push fails if the table has rows. The recipe is in Required column on a table with data.

diff ​

Show what generate would change; write nothing. Run it before generate: afterwards there is nothing left to diff.

FlagTypeDefaultDescription
--schema <path>stringconfig.schema or ./accessnexus.schema.tsSchema file.
--output <dir>string./generatedCompare against folders under <dir>.
--sql-onlybooleanfalseOnly SQL.
--sdk-onlybooleanfalseOnly the SDK.
--prefix <name>stringaccessnexusPolicy name prefix.
--checkbooleanfalseExit 1 with GENERATED_OUT_OF_DATE when anything would change (for CI). With --against-db: exit 1 with LIVE_DB_CHANGES when the database would change.
--against-dbbooleanfalseLive change plan: rehearse the push against the database (see below).
--url <db-url>stringsee Database URLWith --against-db. Alias: --db-url.
--adapter <name> / --target <name>stringnoneWith --against-db: same resolution as push.
--allow-destructivebooleanfalseWith --against-db: plan as push --allow-destructive would (otherwise a DESTRUCTIVE_MIGRATION blocker).
--replace-foreign-policies / --replace-foreign-triggersbooleanfalseWith --against-db: include the drops push would do with these flags (otherwise FOREIGN_* blockers).

Removed files are reported for policies, triggers and RPCs (an extra .sql file in those folders). The migrations and SDK folders never report removals.

Without --against-db, diff compares the schema with the generated files, not the database. When a database URL is configured, the result carries a hint pointing to --against-db.

Live plan (--against-db) ​

diff --against-db shows what push would really change in the live database. It works by rehearsal:

  1. Generate the SQL from the current schema in memory (what generate + push would apply) and connect (DB_URL_MISSING, PG_DRIVER_MISSING, DB_CONNECTION_FAILED).
  2. Take the push advisory lock without waiting: if a push is running, PUSH_LOCKED.
  3. BEGIN, then snapshot the catalog of everything the schema manages: tables, RLS enabled/forced, columns (type via format_type, nullability, default via pg_get_expr), constraints, indexes, policies (command, permissive, roles, USING/WITH CHECK), triggers (timing, events, level, WHEN, function), the functions the SQL defines or the triggers call (identity arguments, return type, language, volatility, security definer, proconfig, body hash, pg_get_functiondef) and grants on those tables and functions.
  4. Run the push code path in the transaction: the same foreign policy/trigger drops (only with the --replace-* flags), the same skip/re-apply rules, the same files in the same order.
  5. Snapshot again, ROLLBACK, release the lock. Nothing persists: no objects, no accessnexus_migrations rows.

The result lists changes (kind, object, change, before, after, fields) and riskyChanges: function volatility/config/security changes, policy roles widened (for example authenticated → public), policies, triggers, functions, tables or columns dropped, a column default removed, a type change, NOT NULL relaxed, RLS disabled or unforced, and grants. Grants are judged on effective access (has_function_privilege / has_table_privilege for anon and authenticated, plus the ACL's PUBLIC entry), not on the ACL's literal shape: grant_widened when one of them gains a privilege on an existing object, grant_narrowed when one loses it (PUBLIC losing a privilege that anon and authenticated both keep, as in a definer RPC's REVOKE ... FROM PUBLIC plus direct grants, is not flagged). A grant change carries notes with the access path per role, e.g. anon EXECUTE: via PUBLIC → direct grant (no change in access); before/after keep the literal ACL (privileges) next to effective. With --replace-foreign-triggers, keptTriggerFunctions lists the functions of the dropped triggers (never dropped) and what still depends on them. Refusals the real push would stop at (FOREIGN_POLICIES, FOREIGN_TRIGGERS, DESTRUCTIVE_MIGRATION, PUSH_ROLE_NO_BYPASSRLS, NOT_NULL_ON_NON_EMPTY_TABLE) are in blockers, each with optional details. A pending migration that adds a NOT NULL column without a default to a table with rows is reported before Postgres fails: blocker NOT_NULL_ON_NON_EMPTY_TABLE with details: { table, column, rows }. Making an existing column NOT NULL shows as the risky change column_nullability_tightened; a function whose result type changes shows as function_result_changed (callers reading the old shape break). An index renamed in place (same definition, new name: what a migration's ALTER INDEX ... RENAME does) is one change renamed with before.name / after.name, not a removal plus an addition; summary counts it under renamed. A migration generate has not written yet is named <pending>__changes.sql. When Postgres would reject a file, the command exits 1 with PUSH_WOULD_FAIL and failed (file, message, sqlState, line, statement: the statement Postgres rejected, with its 1-based line in the file; when Postgres reports no position, the rehearsal replays the file statement by statement to find it). The result then carries the partial plan: wouldApply lists the files applied before the failure and changes the catalog changes up to it. Nothing was persisted.

bash
npx accessnexus diff --against-db --json
npx accessnexus diff --against-db --check     # CI: exit 1 when push would change the database

push ​

Apply the generated SQL to the database.

FlagTypeDefaultDescription
--url <db-url>stringsee Database URLPostgres connection string. Alias: --db-url (the flag init uses); passing both with different values is INVALID_FLAG_VALUE.
--adapter <name>stringnoneAdapter to use when config.adapters lists several.
--target <name>stringnoneEntry of config.targets.
--dry-runbooleanfalseList the files and destructive statements. With a database URL it also rehearses the push of the files on disk in a rolled-back transaction (live plan, returned as livePlan) and lists foreign policies and triggers (foreignPolicies, foreignTriggers, wouldRefuse); without one, these are null. Nothing persists.
--output <dir>string./generatedRead the SQL from folders under <dir>.
--prefix <name>stringaccessnexusPolicy name prefix (used by the staleness check).
--schema <path>stringconfig.schema or ./accessnexus.schema.tsSchema file (used by the staleness check).
--allow-destructivebooleanfalseApply pending migrations that drop tables/columns, drop types, truncate or change column types.
--replace-foreign-policiesbooleanfalseDrop the RLS policies on managed tables that AccessNexus did not generate, in the push transaction (see step 7).
--replace-foreign-triggersbooleanfalseDrop the triggers on managed tables that AccessNexus did not generate, in the push transaction (FOREIGN_TRIGGERS otherwise).
--seedbooleanfalseAlso run the seed after pushing.
--allow-remote-seedbooleanfalseWith --seed: allow seeding a hosted Supabase database.

Steps, in order:

  1. Collect .sql files (recursively, sorted by path) from the migrations, policies, triggers and rpcs folders. None: NOTHING_TO_PUSH.
  2. Without --dry-run: require a database URL (DB_URL_MISSING) and the pg driver (PG_DRIVER_MISSING).
  3. Regenerate the SQL in memory and compare with the files: any difference is GENERATED_OUT_OF_DATE (also with --dry-run).
  4. --dry-run stops here (after the live plan rehearsal when a database URL is set).
  5. Connect (DB_CONNECTION_FAILED). If any file contains SECURITY DEFINER, the role must bypass RLS (PUSH_ROLE_NO_BYPASSRLS).
  6. Take an advisory lock (waits, with a notice, if another push holds it), then BEGIN one transaction for everything below. Create public.accessnexus_migrations (RLS enabled and forced) if absent.
  7. Read pg_policies for every table the schema manages. A policy whose name is not one AccessNexus generates (<prefix>_<table>_<op>) is foreign: Postgres ORs permissive policies, so it would keep granting access next to the generated ones. Without --replace-foreign-policies: FOREIGN_POLICIES (message and foreignPolicies list table + policy), nothing applied. With it: they are dropped (droppedPolicies) in the transaction.
  8. If a not-yet-applied migration contains a destructive statement and --allow-destructive is not set: DESTRUCTIVE_MIGRATION, nothing applied.
  9. Apply files in the order migrations, rpcs, policies, triggers (RPCs first so policies and triggers can call them), recording each in accessnexus_migrations. Checksum: SHA-256 of the SQL without the -- Generated at: line.
    • unchanged and applied: skipped (already_applied);
    • an applied migration whose content changed: MIGRATION_DRIFT;
    • a changed policy, trigger or RPC file: re-applied;
    • SQL error: PUSH_FAILED (failed names the file).
  10. COMMIT. Any error before it rolls back the whole push: no migration, policy, trigger, RPC, bookkeeping row or policy drop from it remains (applied is [], rolledBack lists the files that had run). The advisory lock is released either way.
  11. With --seed: run the seed (see seed). A missing seed file is SEED_NOT_FOUND; a failed seed keeps the push and reports the seed error code.

SSL: forced (certificate not verified) when the URL has sslmode=require|verify-ca|verify-full, or the host contains supabase.co / supabase.in, unless the URL has sslmode=disable.

WARNING

push is the only command that changes the database. Preview with --dry-run. Postgres cannot use an enum value added by ALTER TYPE ... ADD VALUE in the same transaction: if one push adds an enum value and also uses it (in a default, a policy or an RPC), push the enum change first, then the rest. --allow-destructive deletes data; use it only when the loss is intended and backed up. A rename belongs in the schema, not as remove + add.

seed ​

Generate the seed SQL from the seed file and run it in one transaction.

FlagTypeDefaultDescription
--url <db-url>stringsee Database URLPostgres connection string. Alias: --db-url (the flag init uses); passing both with different values is INVALID_FLAG_VALUE.
--adapter <name>stringnoneAdapter to use when several are configured.
--target <name>stringnoneEntry of config.targets.
--dry-runbooleanfalsePrint the SQL; do not connect.
--schema <path>stringconfig.schema or ./accessnexus.schema.tsSchema file.
--prefix <name>stringaccessnexusPolicy name prefix.
--seed <path>stringconfig.seed or ./accessnexus.seed.tsSeed file.
--allow-remote-seedbooleanfalseAllow seeding a hosted Supabase database (*.supabase.co, *.supabase.com, *.supabase.in).

Errors: SEED_NOT_FOUND, SEED_EMPTY (the export has no tables), SEED_REMOTE_BLOCKED, SEED_FAILED (rolled back). Seed format: defineSeed.

WARNING

Seeds upsert rows and can create auth.users accounts. Run them against local or disposable databases only.

migration ​

Two subcommands for migration files. A subcommand is required (UNKNOWN_COMMAND otherwise).

migration discard ​

Drop the newest migration when the database never applied it and restore the snapshot to the state before it. It does not regenerate: change the schema, then run generate. migration amend does both (discard, then generate). Use them to replace a pending migration (for example a NOT NULL column that should have been nullable) instead of editing it: applied and pending migrations are immutable, and editing one is MIGRATION_DRIFT.

FlagTypeDefaultDescription
--url <db-url> / --adapter <name> / --target <name>stringsee Database URLDatabase used to check that the migration was never applied (accessnexus_migrations). Alias of --url: --db-url.
--forcebooleanfalseDiscard without checking a database (no URL configured): you vouch that no environment ever applied it.
--lastbooleanfalseDiscard the newest migration (the default and only mode).
--schema <path> / --output <dir> / --prefix <name> / --sql-only / --sdk-onlyas in generateUsed by migration amend to regenerate.

The snapshot (.snapshot.json) keeps a history of earlier states, which is how the previous state is restored. Errors:

  • NO_MIGRATION_TO_DISCARD: there is no migration snapshot yet; run generate first.
  • MIGRATION_ALREADY_APPLIED: the database applied it; generate a new __changes migration instead.
  • MIGRATION_DISCARD_NEEDS_DB: no database URL; pass --url / --target, or --force.
  • MIGRATION_HISTORY_MISSING: the snapshot was written by a version before 0.4.1 and has no history. Nothing is deleted.
bash
npx accessnexus migration discard --json
npx accessnexus migration discard --target staging
npx accessnexus migration amend --target staging --json   # discard + generate

The JSON result has discarded (the migration file), restoredTo (the previous migration, or null when the snapshot was removed and the next generate writes a new __init), checkedDatabase (redacted URL, or null with --force) refreshed / stale (for discard: the derived SDK and SQL files it rewrote because the schema already matches the restored state, or the ones that changed together with the discarded migration and still carry it — revert the schema and run generate) and regenerated: null for discard; for amend, the migration generate wrote (null when the schema matches the restored state). amend also returns generate (the full generate result).

migration data ​

bash
npx accessnexus migration data <name>

Create <migrations>/data/<UTC timestamp>__<name>.sql: a data migration that you write, for example a backfill UPDATE. <name> is lowercase snake_case (INVALID_FLAG_VALUE otherwise) and required (MISSING_ARGUMENT). push applies it once, in timestamp order together with the schema migrations (between the migration generated before it and the one after), inside the push transaction, and records it in accessnexus_migrations; it is immutable afterwards. It runs as the push user, so RLS is bypassed. The JSON result is { created: <file> }.

Typical use: add a column as nullable, backfill it here, then make it required in a later migration. Full steps: Required column on a table with data.

test-db ​

bash
npx accessnexus test-db up [--push]
npx accessnexus test-db down

up starts a disposable local supabase/postgres in Docker, prepared for RLS tests: GoTrue-like auth.uid() / auth.jwt() reading request.jwt.claims, auth.users.email_confirmed_at, an authenticator login and realtime.messages. It prints the connection URL (postgres://postgres:postgres@127.0.0.1:<port>/postgres). down removes the container. The container is meant for tests only; never point tests at a hosted project. Writing tests: Testing RLS.

FlagTypeDefaultDescription
--port <port>string55433Host port.
--name <name>stringaccessnexus-test-dbContainer name.
--image <image>stringghcr.io/supabase/postgres:15.19.0.007Docker image.
--pushbooleanfalseWith up: also run push against the new database.
--schema <path> / --output <dir>stringas in pushUsed by --push.

Errors: DOCKER_NOT_FOUND (the docker command is missing), TEST_DB_START_FAILED (docker run failed, the database was not ready within 2 minutes, or preparing it failed; check docker logs <name>). The JSON result of up is { action, container, url, image, push } (push is the push result, or null); of down, { action, container, removed }.

help and version ​

InvocationOutput
accessnexus, accessnexus help, --help, -hoverview
accessnexus help <command>, accessnexus <command> --helpcommand flags and examples
accessnexus version, --version, -vversion string

All accept --json.

Database URL ​

push, seed, diff --against-db, validate --against-db and migration discard use the first non-empty value of:

  1. --url (or its alias --db-url)
  2. the env var named by adapterOptions.dbUrlEnv of the selected target or adapter (or adapterOptions.datasource.url.env)
  3. ACCESSNEXUS_DB_URL
  4. SUPABASE_DB_URL
  5. DATABASE_URL

For Supabase use the "Session pooler" connection string (Dashboard, Connect), as the postgres role. Passwords are redacted in messages.

Environment variables ​

VariableUsed byDescription
ACCESSNEXUS_DB_URLpush, seed, initDatabase URL (after --url and dbUrlEnv).
SUPABASE_DB_URLpush, seed, initDatabase URL fallback.
DATABASE_URLpush, seed, initDatabase URL fallback.
<dbUrlEnv>push, seedAny name configured in adapterOptions.dbUrlEnv.
ACCESSNEXUS_DB_CONNECT_TIMEOUTpush, seed, init --db-urlConnection timeout in seconds (positive number). Default 10.
ACCESSNEXUS_SEED_PASSWORDseed, push --seedPassword of auth.users rows the seed provisions. Default: random per user.
DEBUGallaccessnexus, accessnexus* or * (comma or space separated) enables --verbose.
NO_COLORallAny non-empty value disables colors.
FORCE_COLORallAny value other than 0 enables colors when stdout is not a TTY. Ignored with --json.
NEXT_PUBLIC_SUPABASE_URL, VITE_SUPABASE_URL, REACT_APP_SUPABASE_URL, SUPABASE_URLinitProject URL for REST introspection, read from .env, .env.local, .env.development, .env.development.local.
SUPABASE_SERVICE_ROLE_KEY, SUPABASE_SERVICE_ROLE, SUPABASE_SECRET_KEY, SUPABASE_SERVICE_KEY, SERVICE_ROLE_KEYinitService key for REST introspection (any value starting with sb_secret_ is preferred).

Colors are off when stdout is not a TTY, with NO_COLOR, and always with --json.

Exit codes ​

CodeMeaning
0Success.
1User-fixable error: bad flag, missing file, schema error, missing database URL, unreachable database, SQL rejected, stale output, destructive migration without --allow-destructive, failed seed, Docker missing for test-db. Read error.hint.
2Internal error (INTERNAL_ERROR): an AccessNexus bug. Re-run with --verbose and report the stack trace.

Error codes: Errors.

JSON output ​

With --json, stdout carries exactly one JSON object (pretty-printed). Every object has ok, command and version. On failure it also has error, and keeps any partial result fields carried by the error (issues, applied, stale, ...). Without --json, errors go to stderr as message, Fix: hint and (with --verbose) stack.

ts
interface SchemaIssue {
  severity: 'error' | 'warning';
  code: string;        // e.g. 'UNKNOWN_COLUMN'
  path: string;        // e.g. 'posts.policies.update'
  message: string;
  hint?: string;
}

interface ErrorResult {
  ok: false;
  command: string;     // the command as typed (also for UNKNOWN_COMMAND)
  version: string;
  error: { code: string; message: string; hint?: string; stack?: string /* --verbose */ };
  // SCHEMA_VALIDATION_FAILED adds: schemaPath, issues (errors and warnings), summary { errors, warnings }
  //   (validate also adds mode, tables, rpcs, channels, functions)
  [partial: string]: unknown;
}

interface DestructiveStatement {
  file: string;        // migration file, relative to cwd
  line: number;        // 1-based
  kind: 'drop_table' | 'drop_column' | 'alter_column_type' | 'drop_type' | 'truncate';
  sql: string;
}

interface ValidateResult {
  ok: true; command: 'validate'; version: string;
  schemaPath: string;
  mode: 'manual' | 'database';
  tables: Array<{
    name: string;
    columns: number;
    primaryKey: string | null;
    rls: boolean;
    policies: string[];                                   // operations with a rule
    triggers: Array<{ kind: string; name: string | null }>;
    realtime: boolean | null;                             // null: the table leaves the publication unmanaged
  }>;
  rpcs: string[];
  channels: string[];                                     // defineSchema(..., { channels })
  functions: string[];                                    // defineSchema(..., { functions })
  issues: SchemaIssue[];                                  // warnings only; with --against-db a rejection is SQL_REJECTED
  summary: { errors: number; warnings: number };
}

interface GenerateResult {
  ok: true; command: 'generate'; version: string;
  schemaPath: string;
  mode: 'manual' | 'database';
  files: Array<{
    path: string;
    category: 'migrations' | 'policies' | 'triggers' | 'rpcs' | 'sdk' | 'functions';
    status: 'created' | 'updated' | 'unchanged';
  }>;
  destructive: DestructiveStatement[];                    // in migrations written by this run
  summary: { created: number; updated: number; unchanged: number; files: number; tables: number };
  warnings: SchemaIssue[];                                // includes NOT_NULL_COLUMN_ADDED
}

interface DiffResult {
  ok: boolean;          // false only with --check and pending changes (GENERATED_OUT_OF_DATE)
  command: 'diff'; version: string;
  schemaPath: string;
  changed: boolean;
  destructive: DestructiveStatement[];                    // in migrations generate would write
  summary: { added: number; modified: number; removed: number; renamed: number };
  changes: Array<{ path: string; status: 'added' | 'modified' | 'removed'; diff: string }>;
  warnings: SchemaIssue[];                                // includes NOT_NULL_COLUMN_ADDED
  hint?: string;        // set when a database URL is configured: points to diff --against-db
}

// diff --against-db: the live plan (PlanChange, RiskyChange and LivePlan are spelled out in llms.txt)
interface DiffAgainstDbResult extends LivePlan {
  ok: boolean;          // false with --check and changes (LIVE_DB_CHANGES) or when the push would fail (PUSH_WOULD_FAIL)
  command: 'diff'; version: string;
  schemaPath: string;
  againstDb: true;
  adapter: string; target: string | null;
  generatedUpToDate: boolean;                             // false: planned from the schema, run generate before push
  warnings: SchemaIssue[];
}

interface LivePlan {
  database: string;                                       // redacted URL
  wouldApply: string[];                                   // files push would execute (with `failed`: those applied before the failure)
  skipped: Array<{ path: string; reason: 'already_applied' | 'checksum_normalized' }>;
  droppedPolicies: ForeignPolicy[]; droppedTriggers: ForeignTrigger[]; // only with the --replace-* flags
  keptTriggerFunctions: Array<{ function: string; dependents: string[]; orphaned: boolean }>; // functions of dropped triggers (kept)
  foreignPolicies: ForeignPolicy[]; foreignTriggers: ForeignTrigger[];
  blockers: Array<{ code: string; message: string; hint?: string; details?: Record<string, unknown> }>; // refusals the real push stops at
  // (NOT_NULL_ON_NON_EMPTY_TABLE has details { table, column, rows })
  failed: null | {                                        // push would fail; wouldApply and changes then hold the partial plan up to it
    file: string | null; code: string; message: string; sqlState: string | null;
    line: number | null; statement: string | null;        // the statement Postgres rejected (1-based line in the file)
  };
  changed: boolean;
  summary: { added: number; modified: number; removed: number; renamed: number };
  changes: Array<{
    kind: 'table' | 'column' | 'constraint' | 'index' | 'rls' | 'policy' | 'trigger' | 'function' | 'grant';
    object: string;                                       // e.g. 'public.notes.accessnexus_notes_select', 'public.fn(uuid)'
    change: 'added' | 'removed' | 'modified' | 'renamed'; // renamed: an index under a new name (before.name → after.name)
    before?: Record<string, unknown>; after?: Record<string, unknown>;
    fields?: string[];                                    // modified: properties that differ
    notes?: string[];                                     // grants: access path per role, e.g. 'anon EXECUTE: via PUBLIC → direct grant (no change in access)'
  }>;
  riskyChanges: Array<{ code: string; kind: string; object: string; message: string }>; // code includes column_nullability_tightened (existing nulls fail), function_result_changed
  persisted: false;
}

interface PushResult {
  ok: true; command: 'push'; version: string;
  dryRun: boolean;
  adapter: string;
  target: string | null;
  plan: Array<{ category: 'migrations' | 'policies' | 'triggers' | 'rpcs'; files: string[] }>;
  destructive?: DestructiveStatement[];                   // --dry-run only: all migration files
  foreignPolicies?: ForeignPolicy[] | null;               // --dry-run only: null = no database URL, not checked
  wouldRefuse?: boolean;                                  // --dry-run only: foreign policies/triggers without their --replace-* flag, or livePlan blockers/failed
  livePlan?: LivePlan | null;                             // --dry-run only: null = no database URL (or unreachable)
  applied: string[];
  droppedPolicies: ForeignPolicy[];                       // dropped by --replace-foreign-policies
  skipped: Array<{ path: string; reason: 'already_applied' | 'checksum_normalized' }>;
  seed:
    | null                                                // no --seed (always null with --dry-run)
    | { path: string; status: 'applied'; authUsers: number; durationMs: number }
    | { path: string; status: 'skipped'; message: string; authUsers: 0 };
}
// push failures keep partial fields:
//   NOTHING_TO_PUSH          dryRun, adapter, target, plan
//   GENERATED_OUT_OF_DATE    dryRun, adapter, target, plan, stale: Array<{ path: string; status: string }>
//   DESTRUCTIVE_MIGRATION    ...plan, applied, skipped, destructive
//   FOREIGN_POLICIES         ...plan, applied: [], skipped, foreignPolicies
//   MIGRATION_DRIFT, PUSH_FAILED   ...plan, applied: [] (rolled back), skipped, rolledBack: string[]; PUSH_FAILED adds failed: string
//   SEED_NOT_FOUND           ...plan, applied, skipped
//   seed failure (any code)  ...plan, applied, skipped, seed: { path, status: 'failed', message }

interface ForeignPolicy {
  schema: string; table: string; policy: string;
  command: string;      // SELECT | INSERT | UPDATE | DELETE | ALL
  permissive: boolean;  // false = RESTRICTIVE
}

interface SeedResult {
  ok: true; command: 'seed'; version: string;
  dryRun: boolean;
  seedPath: string;
  checksum: string;     // SHA-256 of the seed SQL
  rows: number;         // rows in the seed file
  authUsers: number;    // auth.users rows the seed provisions
  applied: boolean;
  sql?: string;         // --dry-run
  durationMs?: number;  // when applied
}

interface InitResult {
  ok: true; command: 'init'; version: string;
  status: 'initialized' | 'already_initialized';
  framework?: string;
  schemaSource?: 'template' | 'database' | 'rest';
  sdkPath?: string;
  policyPrefix?: string;
  installed?: string[];
  files: Array<{ path: string; action: 'created' | 'updated' | 'skipped' }>;
  agents: null | { agentsMd: 'created' | 'updated' | 'unchanged'; claudeMd: 'updated' | 'unchanged' | 'absent' };
  nextSteps?: string[];
}

interface HelpResult {
  ok: true; command: 'help'; version: string;
  topic: string | null;
  commands: Array<{
    name: string;
    summary: string;
    examples: string[];
    flags: Array<{ name: string; kind: 'boolean' | 'string'; value?: string; description: string }>;
  }>;
  exitCodes: Record<'0' | '1' | '2', string>;
  docs: string;         // 'node_modules/accessnexus/llms.txt'
}

interface VersionResult { ok: true; command: 'version'; version: string }

Released under the MIT License.