# OsBase: install and first undo

> Put the Osevel bridge in front of your Postgres database, give an AI agent its own key and undo its first change, step by step.

Source: https://osevel.com/docs/getting-started/install/

This page takes you from an empty install to a first undo. It assumes you can connect to your
database as a role that owns your application tables.

- [Before you start](#before-you-start)
- [1. Run init](#1-run-init)
- [2. What init installs](#2-what-init-installs)
- [3. Row-level security mode](#3-row-level-security-mode)
- [4. Capability risks you must accept by name](#4-capability-risks-you-must-accept-by-name)
- [5. Connect your MCP client](#5-connect-your-mcp-client)
- [6. Verify the install](#6-verify-the-install)
- [7. A first approval and undo](#7-a-first-approval-and-undo)
- [Supabase specifics](#supabase-specifics)
- [Uninstalling](#uninstalling)

## Before you start

- Node.js 22.22.0 or newer.
- PostgreSQL 15, 16, 17 or 18 (tested), or Supabase (tested on the local images
  `supabase/postgres:15.19.0.019` and `17.11.0.019`; hosted Supabase is untested).
- The **admin** connection: a role that owns the tables in the schemas you want the agent to use
  and has `CREATEROLE` (or is a superuser). On Supabase this is `postgres`. Prefer a non-superuser
  that owns the tables: approved schema changes run with the admin's rights (see
  [security](https://osevel.com/docs/security/model/#what-a-human-approval-does-and-does-not-protect-against)).
- The CLI, from npm: `npm i -g @osevel/cli` (Node.js 22.22 or newer). The command is `osevel`.
  npm holds back the plain package name `osevel` for now, so the package is scoped.

The admin password is asked for with a hidden prompt and is never stored. For scripted setups the
whole admin connection can instead come from the environment variable `OSEVEL_ADMIN_URL`
(`postgres://user:password@host:port/database`); it is never accepted on the command line. An
`sslmode` in that URL is ignored; use `--tls`.

## 1. Run init

```sh
osevel init
```

`init` must run in an interactive terminal (stdin and stdout both a TTY). It asks, in order:

| Prompt                                                    | Default                                     | Notes                                                                                                                               |
| --------------------------------------------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| Project name                                              | none                                        | 1 to 64 characters: `a-z`, `0-9`, `_`, `-`. Skipped with `--project`. The name must not exist locally yet.                          |
| Host, Port, Database, Admin user, Admin password (hidden) | `localhost`, `5432`, `postgres`, `postgres` | Skipped when `OSEVEL_ADMIN_URL` is set.                                                                                             |
| Schemas the agent may read and write (comma-separated)    | `public` if it exists                       | Lists the schemas with their table counts first. Skipped with `--schemas a,b`. Only lower-case, unquoted schema names are accepted. |
| `Type "<risk>" to accept this risk`, once per risk        | none                                        | Only if the database gives every role a risky capability. See [section 4](#4-capability-risks-you-must-accept-by-name).             |
| RLS mode (`bypass` or `policy`)                           | none                                        | Only if a managed table has row-level security. See [section 3](#3-row-level-security-mode).                                        |
| Confirmation code                                         | none                                        | A random 6-character code shown on screen; anything else cancels.                                                                   |

Before the risk and RLS prompts, `init` runs a database check and prints it: server version and
platform, admin attributes, risks, warnings (tables without a primary key, tables with RLS, foreign
keys cascading into other schemas, SECURITY DEFINER functions the agent could call, tables exposed
to the Supabase Data API without RLS, roles that already exist) and blockers. Install refuses on
any blocker, for example:

- PostgreSQL older than 13, or an admin with neither `SUPERUSER` nor `CREATEROLE`;
- a chosen schema that does not exist, or in which `PUBLIC` may `CREATE`
  (fix: `REVOKE CREATE ON SCHEMA <schema> FROM PUBLIC`);
- roles with the chosen prefix already used in another database (choose another `--role-prefix`);
- an existing installation with a different role prefix;
- on Supabase, event triggers that cannot be created (without the DDL guard any role could create
  network-capable extensions).

Options:

| Option                    | Meaning                                                                                                                                                       |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `-p, --project <name>`    | Project name (asked for when omitted).                                                                                                                        |
| `--schemas <a,b>`         | Schemas to manage (asked for when omitted).                                                                                                                   |
| `--role-prefix <prefix>`  | Role name prefix, default `ar`. 1 to 20 characters `[a-z0-9_]`, starting with a letter. Roles are cluster-wide.                                               |
| `--tls <mode>`            | `disable`, `verify-ca` or `verify-full`. Default: `disable` for localhost or a Unix socket, otherwise `verify-full`. `disable` is only allowed for localhost. |
| `--ca-cert <file>`        | PEM CA bundle for `verify-ca` / `verify-full` (required for `verify-ca`).                                                                                     |
| `--secret-backend <kind>` | `auto` (default: OS keychain, else a `0600` file), `keychain` (fail if unavailable) or `file`.                                                                |

When you confirm, the whole install runs in one transaction and is verified before it commits. Any
verification violation rolls everything back.

Afterwards `init` prints how many tables are managed, whether event triggers were installed, the
verification result, any skipped tables with the reason, and the MCP configuration.

**Where things are stored locally.** The project file (no secrets) is
`$XDG_CONFIG_HOME/osevel/projects/<project>.json` (default `~/.config/osevel/...`;
`%APPDATA%\osevel` on Windows). The six generated passwords go to the OS keychain under
accounts `<project>:<role>`, or, if no keychain is available, to one file per role,
`~/.config/osevel/secrets/<project>/<role>.json`, mode `0600`. With `auto`, falling back to the
file prints a warning that the passwords are stored unencrypted.

**Re-running init.** `init` refuses a project name that already exists locally. To accept a risk
after install, use `osevel risks accept` instead (it keeps all passwords; see
[usage](https://osevel.com/docs/getting-started/usage/#when-the-agent-is-cut-off)). To re-apply the install to change schemas or rotate
passwords, first forget the local project with
`osevel projects remove <project>` (the database is not changed), then run `init` again
with the same `--role-prefix` you used the first time. Existing roles are reused and **all five
passwords are replaced**, so restart your MCP client's osevel server afterwards. Risks are
asked for again: anything you do not accept this time is no longer accepted.

## 2. What init installs

`init` shows this list before you confirm. With the default prefix `ar`:

**Roles** (all `NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOINHERIT`, members of no role,
with connection limits and timeouts; login roles get random 43-character passwords):

| Role          | Login | Used by                                 | Purpose                                                                |
| ------------- | ----- | --------------------------------------- | ---------------------------------------------------------------------- |
| `ar_owner`    | no    | nobody                                  | Owns the journal objects. The admin becomes a member.                  |
| `ar_agent`    | yes   | MCP server                              | Runs the agent's SQL. Read/write on managed tables only.               |
| `ar_migrator` | yes   | MCP server, CLI `undo`                  | Runs approved schema changes, only through the database approval gate. |
| `ar_journal`  | yes   | MCP server, read-only CLI commands      | Records changes and approval requests. No access to your tables.       |
| `ar_approver` | yes   | CLI `approve`, `deny`, `policy`, `undo` | Records your decisions and policy. No access to your tables.           |
| `ar_undo`     | yes   | CLI `undo`                              | Reverts rows. Cannot see approvals or policy.                          |

The MCP server only ever loads the agent, migrator and journal passwords. See
[security.md](https://osevel.com/docs/security/model/#the-five-database-roles) for the reasoning.

**Schemas:**

- `agent_reverse`: the journal (`changes`, `row_log`, `ddl_log`, `approvals`, `policy`,
  `gate_log`, `install_settings`, `schema_migrations`);
- `agent_reverse_trash`: tables moved there by `DROP TABLE` and data saved before `TRUNCATE` or
  `DROP COLUMN`;
- `agent_reverse_api`: the approval gate and the impact function.

**On your tables:**

- a capture trigger (`agent_reverse_capture`, `ENABLE ALWAYS`) on every table in the managed
  schemas, and on every table reached from them by cascading foreign keys, inheritance or
  partitioning, in any schema (the agent gets no access to those extra tables);
- `SELECT, INSERT, UPDATE, DELETE` for `ar_agent` and `ar_undo` on managed tables;
- RLS handling, depending on the mode you choose.

**Event triggers** (if the admin may create them): a DDL guard that refuses every DDL statement of
the login roles except approved changes through the gate, management of new tables in managed
schemas (they get the capture trigger and grants immediately), and fail-closed reactions when a
capture trigger is disabled or a risky capability appears. Without event triggers, tables created
later stay unavailable to the agent until you run `osevel sync`, and there is no DDL guard.

**Not installed:** any policy rule. While the policy table is empty the built-in defaults apply
(see [usage](https://osevel.com/docs/getting-started/usage/#policy-rules)).

Tables that cannot be managed are skipped and listed with the reason, for example a table owned by
a role the admin cannot act as, a partition (captured through its root), a temporary table, a table
with a rewrite rule, or one whose cascade closure cannot be captured.

## 3. Row-level security mode

If any managed table has row-level security enabled, `init` requires an explicit choice. There is
no default.

| Mode     | What it does                                                                                                                                                                                                                              | When to use                                                                                                              |
| -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `bypass` | `BYPASSRLS` on `ar_agent` and `ar_undo`. They still see only the tables they were granted.                                                                                                                                                | Simplest. Requires an admin with `BYPASSRLS` or superuser (Supabase `postgres` has it).                                  |
| `policy` | A permissive policy `agent_reverse_agent` (`FOR ALL USING (true) WITH CHECK (true)`, to the agent role) and `agent_reverse_undo` (to the undo role) on each RLS table. Also added when RLS is enabled later (event trigger) or by `sync`. | When the admin lacks `BYPASSRLS` (then it is the only option offered), or when you prefer not to give a role attributes. |

Either way the agent can read and write every row of the managed tables. RLS is designed for your
application's users, not for the agent.

## 4. Capability risks you must accept by name

osevel journals and gates writes to the managed tables. Some database features reach outside
them. If the agent role could use one of these (usually because it is granted to `PUBLIC`), `init`
explains each one and asks you to type its exact name. Anything else aborts and nothing is
changed. There is no "accept all".

| Risk name                    | What the agent could do                                                                                                                                      |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `pg_net`                     | Send HTTP requests from the database server: copy data to the internet, reach internal services (SSRF). Requests leave even if the statement is rolled back. |
| `http`                       | Send HTTP requests from the database server (http extension).                                                                                                |
| `dblink`                     | Open connections to any host and database and run SQL there.                                                                                                 |
| `postgres_fdw`               | Connect to other PostgreSQL servers, read or write there.                                                                                                    |
| `foreign_data`               | Use a foreign-data wrapper or foreign server. Those writes are not journaled.                                                                                |
| `foreign_tables`             | Read or write foreign tables, or views over them (with `file_fdw`, server files).                                                                            |
| `pg_cron`                    | Schedule SQL that runs later as another role, outside the journal and approvals.                                                                             |
| `pgsodium`                   | Create keys, use server-held keys, write pgsodium tables.                                                                                                    |
| `supabase_vault`             | Create or read Vault secrets.                                                                                                                                |
| `wrappers`                   | Reach external systems through Supabase foreign data wrappers.                                                                                               |
| `pg_tle`                     | Register trusted-language extensions (code that runs for other users).                                                                                       |
| `server_files`               | Read or write files on the database server.                                                                                                                  |
| `security_definer_functions` | Call your SECURITY DEFINER functions, which run with their owner's rights. Their writes outside the managed tables are not journaled.                        |
| `security_definer_triggers`  | Fire SECURITY DEFINER trigger functions on managed tables. Their writes outside the managed tables are not journaled.                                        |

**What accepting means.** Accepting is a standing decision recorded in the database: from then on
the agent may use that capability, and whatever it does with it outside the managed tables is
neither journaled nor undoable. Accepting a SECURITY DEFINER function also accepts whatever that
function calls or reads.

- For `foreign_tables`, `security_definer_functions` and `security_definer_triggers` you accept
  exactly the items listed at that moment. The part of a function's identity after `#`
  fingerprints its body, settings and owner, so changing it makes it a new, unaccepted item. Any
  new or changed item cuts the agent off again (see
  [usage](https://osevel.com/docs/getting-started/usage/#when-the-agent-is-cut-off)).
- Any schema change approved through osevel while SECURITY DEFINER items are accepted
  re-opens all of them: the agent is cut off until you review and accept them again.

**The safer alternative** is to remove the capability instead: revoke it from `PUBLIC` and grant it
only to the roles that need it, then run `init` again (before install) or `osevel sync`
(after install). To accept a risk later, use `osevel risks accept`. For example
`REVOKE USAGE ON SCHEMA net FROM PUBLIC`, or
`REVOKE EXECUTE ON FUNCTION public.f(int) FROM PUBLIC`.

Large-object functions and `pg_notify` are executable by `PUBLIC` on every Postgres; they are
reported as warnings, not risks to accept (see [limitations](https://osevel.com/docs/reference/limitations/)).

## 5. Connect your MCP client

`init` prints a configuration object containing only the project name:

```text
{"command":"npx","args":["osevel","mcp","--project","myapp"]}
```

Add it under a server name in your MCP client's configuration. Clients that use an `mcpServers`
map (Claude Code's `.mcp.json`, Cursor's `.cursor/mcp.json` and others) look like this:

```json
{
  "mcpServers": {
    "osevel": { "command": "npx", "args": ["osevel", "mcp", "--project", "myapp"] }
  }
}
```

Other clients use their own format (Codex, for example, uses TOML); check your client's
documentation for where `command` and `args` go.

`npx @osevel/cli` fetches the published package on first use. From a checkout, use
`"command": "node"` with the absolute path to `packages/cli/dist/bin.js` as the first argument.

Options of `osevel mcp`:

| Option                 | Default          | Meaning                                                                                                                                        |
| ---------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `-p, --project <name>` | the only project | Project to serve. Give it explicitly in the client configuration.                                                                              |
| `--elicitation <mode>` | `reversible`     | Which approvals may be given in the MCP client's own prompt: `reversible`, `all` or `none`. See [usage](https://osevel.com/docs/getting-started/usage/#approving-in-the-mcp-client). |
| `--max-rows <n>`       | `500`            | Rows returned per `query` (1 to 100000).                                                                                                       |
| `--log-level <level>`  | `info`           | `debug`, `info`, `warn`, `error`. Logs go to stderr.                                                                                           |

The server verifies the installation at start-up and refuses to start (exit code 4) on any
verification violation.

**Remove the agent's other ways in.** If the agent still has a database URL in an environment
file, another database MCP server, or a shell from which it can run `psql` as the admin, it can go
around osevel. Also see [security](https://osevel.com/docs/security/model/#local-secrets-and-the-confirmation-code).

## 6. Verify the install

```sh
osevel status    # project, roles, verification, journal counts, approvals waiting
osevel verify    # exit code 4 if there is any violation
osevel doctor    # verification, tables needing attention, crash recovery
```

These run as the journal role and need no admin password. `verify` separates:

- **violations**: the MCP server refuses to start, and a running one refuses writes (and, for an
  unaccepted capability risk, every statement including reads);
- **warnings**: the server runs, but read them (for example tables without a primary key, large
  objects and `NOTIFY` usable by the agent, tables exposed to the Supabase Data API without RLS,
  no event triggers).

`osevel doctor --admin` prints the full pre-install check again, as the admin.

## 7. A first approval and undo

Ask the agent to make a change. A small `UPDATE ... WHERE id = 1` commits at once. A schema change
returns "NOT EXECUTED: this statement needs human approval" with an approval id. Then, in your
terminal:

```sh
osevel approvals
osevel approve 3      # read the facts and the SQL, type the code
```

Tell the agent you approved; it re-runs the same statement with the approval id. Then:

```sh
osevel log
osevel show 5
osevel undo 5 --dry-run
osevel undo 5
```

See [usage](https://osevel.com/docs/getting-started/usage/) for what each screen means.

## Supabase specifics

Verified on the local images `supabase/postgres:15.19.0.019` and `17.11.0.019`. Details and the
evidence are in [supabase.md](https://osevel.com/docs/guides/supabase/).

- **Admin is `postgres`, not a superuser.** On Supabase `postgres` has `CREATEROLE` and
  `BYPASSRLS` but is not a superuser (`supabase_admin` is). Install as `postgres`; it owns `public`
  and the tables created through the dashboard or migrations. Approved schema changes then run with
  `postgres`'s rights, not a superuser's.
- **Tables owned by other roles are skipped.** Tables `postgres` cannot act as (for example owned
  by `supabase_admin`) are skipped and reported.
- **Event triggers are required.** Supabase's `supautils` lets any role create network-capable
  extensions (`dblink`, `http`, `pg_net`, ...). The installer's DDL guard (an event trigger) stops
  that for the osevel roles. If event triggers cannot be created, install refuses.
- **RLS.** Most Supabase tables use row-level security, so you will be asked for the RLS mode.
  `postgres` has `BYPASSRLS`, so both modes are available.
- **Tables created through osevel are exposed to the Data API without RLS.** Supabase's
  default privileges grant `ALL` on new tables in `public` to `anon`, `authenticated` and
  `service_role`. A table the agent creates through an approved migration is owned by `postgres`,
  so it is immediately reachable through the Data API, with RLS off, until you enable RLS.
  `verify` and `doctor` warn about every such table (`exposed_without_rls`). Enable RLS on new
  tables yourself.
- **Foreign keys to `auth.users` are refused.** Every relation a schema change names must be in a
  managed schema, and `auth` is not managed. A `CREATE TABLE ... REFERENCES auth.users` from the
  agent is refused even after approval. Add such constraints through your own migrations.
- **Cascades from `auth.users`** into your tables are done by Supabase roles, not the agent, and
  are not journaled (like every application write).
- **Extensions enabled later.** Enabling `pg_net` (for example through Database Webhooks) or
  another network extension after install cuts the agent off until you remove or accept it (see
  [usage](https://osevel.com/docs/getting-started/usage/#when-the-agent-is-cut-off)).
- **Connection mode.** Use a direct connection or a session-mode pooler connection (on Neon the
  agent may use the transaction-mode `-pooler`; see [neon.md](https://osevel.com/docs/guides/neon/)). The executor
  needs a session-scoped transaction per statement, and undo uses a session-level advisory lock.
  Hosted Supabase, its network policies, SSL enforcement and Supavisor have not been tested.
- **TLS.** For a non-local host the default is `verify-full`. If your provider's certificate
  authority is not in Node's default trust store, pass it with `--ca-cert`.

## Uninstalling

```sh
osevel uninstall --project myapp
```

Needs the admin connection and a typed confirmation code. It shows what will be deleted, then, in
one transaction:

1. refuses if `agent_reverse_trash` still holds tables (tables the agent dropped, saved data),
   unless you pass `--force-trash`; restore what you need with `undo` first;
2. drops the event triggers, every capture trigger and every `agent_reverse_*` RLS policy;
3. drops the schemas `agent_reverse`, `agent_reverse_trash` and `agent_reverse_api`, with the
   whole journal: nothing the agent did can be shown or undone afterwards;
4. revokes the remaining privileges of the osevel roles in this database and drops the
   roles. A role that still has privileges or objects in another database is kept and reported
   (roles are cluster-wide);
5. removes the local project file and its stored passwords.

Your application tables and their data are not touched.

To forget a project on this machine only (config and stored passwords) without changing the
database, use `osevel projects remove <project>`.
