# Cloudflare D1

> How Osevel guards a Cloudflare D1 database from AI agents when D1 has no database roles: what is enforced, and what is not.

Source: https://osevel.com/docs/guides/cloudflare-d1/

D1 has no database roles, so nothing in the database can stop whoever holds its API token.
osevel therefore keeps the token on your machine and enforces every rule itself; agents
reach a D1 database through templates only (named, parameterized statements you install). The
dashboard labels D1 projects "enforced by osevel only".

## Add a database

You need the account id, the database id and an API token that has only **D1: Edit** (create it
under My Profile → API Tokens). Enter the token at the hidden prompt, never in a chat or a file.

```bash
osevel d1 add blog --account <account-id> --database <database-id>
osevel d1 list
osevel d1 check blog
osevel d1 remove blog     # forgets it on this machine; the database is untouched
```

`add` checks the token against the database (`SELECT 1`) before it stores anything.
The token goes to the OS keychain (service `osevel`, account `d1:<name>`) or, with `--file`
or without a keychain, to `<configDir>/d1/<name>.token.json` (mode 0600, not encrypted at rest).
The config file `<configDir>/d1/<name>.json` holds only the ids.

## Install the journal

```bash
osevel d1 install blog     # shows the plan, asks for the code
osevel d1 verify blog      # exit code 4 when something is wrong
```

`install` creates osevel's tables (`_ar_meta`, `_ar_current`, `_ar_changes`,
`_ar_row_log`, `_ar_templates`) and three capture triggers per user table (`_ar_cap_<table>_i/u/d`),
in one transaction. The triggers record before and after images (JSON) and the row's key only
while an osevel change runs, so your application's own writes are not journaled. Re-run it
after adding tables. Tables with more than 60 columns, or `WITHOUT ROWID` tables without a primary
key, are left out and reported.

`verify` checks the tables, the journal version, one exact trigger set per table (a dropped,
replaced or extra trigger is reported) and that no change was left open. D1 has no roles: anyone
with the token can drop these objects; `verify` is how you notice.

## Templates

A template is the only way an agent will reach a D1 database: one named statement with numbered
parameters, typed arguments and a description. The agent sends argument values only; they are
bound, never pasted into SQL.

```bash
osevel d1 template add blog hide_comment --kind write \
  --sql "UPDATE comments SET hidden = 1 WHERE id = ?1 RETURNING id" \
  --arg comment_id:integer --description "Hides one comment."
osevel d1 template list blog
osevel d1 template run blog hide_comment --set comment_id=7   # a test run, journaled
osevel d1 template remove blog hide_comment
```

Before anything is stored: one statement starting with SELECT, WITH, INSERT, UPDATE, DELETE or
REPLACE; parameters exactly `?1` … `?n`; no `_ar_` or `sqlite_` tables; and D1 itself compiles it
(`EXPLAIN`): a `read` template whose bytecode writes is refused. A write runs as one batch that
records the change, captures the rows and returns `RETURNING` rows; if the template fails,
nothing is kept. Templates live in the database (`_ar_templates`) with a digest each; `verify`
and `run` refuse a template changed by anyone else holding the token.

Argument types: `integer`, `real`, `text`, `boolean` (sent as 1 or 0).

## Agents

An agent of a D1 project is registered in the database (`_ar_agents`, only the SHA-256 of its
token) and may call exactly the templates granted to it (`_ar_grants`).

```bash
osevel d1 agent add blog moderator --ide claude-code   # prints the IDE configuration
osevel d1 template grant blog moderator hide_comment   # shows the statement, asks for the code
osevel d1 agent list blog
osevel d1 template revoke blog moderator hide_comment
osevel d1 agent revoke blog moderator
```

The IDE starts `osevel mcp --project blog` with the agent's token. For a D1 project that
server offers one tool per granted template (typed arguments; read templates marked read-only),
`get_schema`, `list_changes` and `status`, and no SQL tool at all. It refuses to start while
`d1 verify` reports a problem, and leaves out any template changed outside osevel.
Everything read from the database comes back in the untrusted-data block.

Tried with Claude Code on a real D1 database (2026-11-18): it listed the comments, hid the two
spam comments with `hide_comment` (two journaled changes under its name) and did not act on a
comment that told it to delete everything.

## Changes and undo

```bash
osevel d1 changes blog                 # who changed what, newest first
osevel d1 undo blog 12 --dry-run       # the plan: rows to restore, conflicts
osevel d1 undo blog 12                 # asks for the code
```

Undo works row by row from `_ar_row_log`: an update is restored, an insert deleted, a delete
inserted back. Each row is touched only if it is still exactly as the change left it; a row
changed since (by an agent or by your application) is a conflict, and then nothing is done. Undo
the later changes first. The undo is one transaction, recorded as a change of its own, so it can
be undone too. Tried on a real D1 database: an undo restored a hidden comment, and an undo whose
row the application had edited since was refused.

## In the dashboard

```bash
osevel connect enable blog --d1        # show it to paired devices (asks you to confirm)
osevel connect set blog --d1 undo=off  # the dashboard may then only look
osevel connect disable blog --d1
```

The dashboard shows a D1 project with the label "enforced by osevel only": the journal's
health, the templates (with their statements) and which agent may call which, and the changes
with the rows each one touched (before and after). A committed change can be undone from the
dashboard with one passkey confirmation; the passkey signs the exact plan (every row with its
values), and the connector refuses the undo if anything changed in between. D1 project names are
their own namespace: `connect enable blog` (without `--d1`) means the Postgres project.

The connector reaches the database with the project's API token, which never leaves the connector
host. Installing templates, granting them and registering agents stay terminal commands.

## Test against a real database

```bash
AR_HOSTED_D1_ACCOUNT=<account-id> AR_HOSTED_D1_DATABASE=<database-id> AR_HOSTED_D1_TOKEN=<token> \
  npx vitest run --project e2e e2e/hosted/d1.test.ts
```

Skipped unless the three variables are set. It runs the whole path on the real database: the
journal, templates (a "read" template that writes is refused by D1's bytecode), an agent over
MCP, a journaled write, undo, and a refused undo after the application changed the row. Safe on
a database in use: everything it creates has a random suffix and is removed at the end, and the
journal tables are removed only if the test installed them. Passed on 2026-11-18.

## Built so far

- The connector (`@agent-reverse/d1`): one operation, `batch`, sent as
  `POST /accounts/{account}/d1/database/{database}/query` with `{ batch: [{ sql, params }] }`. D1
  runs a batch as one transaction. Parameters go as strings, as the REST API takes them.
- A local stand-in with the same answers over `node:sqlite`, for tests.
- The commands above, the journal (`installJournal`, `verifyJournal`) and templates (`addTemplate`,
  `runTemplate`, …), tried on a real D1 database.
- The dashboard: D1 projects, their changes and a passkey-signed undo (protocol contract
  change 10).

Reads (batches of SELECT, PRAGMA or EXPLAIN only) are retried twice after a network error; writes
never are.

Known: parameters reach D1 as text. Comparing them with a column converts them (SQLite type
affinity); comparing them with an expression that is not a column does not, so a template such as
`SELECT ?1 + 1` sees text. Known: the REST API sometimes fails a request with a network error.
