Metadata-Version: 2.4
Name: django-reststroke
Version: 0.1.0a1
Summary: Accept or refuse each tool call of an AI agent before it goes out, by a rule or by a person, in Django, and audit every decision.
Keywords: django,ai-agents,human-in-the-loop,approval,audit
Author: tryph0n
License-Expression: Apache-2.0
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: Django
Classifier: Framework :: Django :: 6.1
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Requires-Dist: django>=6.1,<6.3
Requires-Dist: fastmcp>=4.2.6,<4.3 ; extra == 'gate'
Requires-Dist: httpx2>=2.5.0,<3 ; extra == 'gate'
Requires-Python: >=3.12
Project-URL: Documentation, https://django-reststroke.readthedocs.io/
Project-URL: Source, https://github.com/tryph0n/django-reststroke
Project-URL: Issues, https://github.com/tryph0n/django-reststroke/issues
Project-URL: Changelog, https://github.com/tryph0n/django-reststroke/blob/main/CHANGELOG.md
Provides-Extra: gate
Description-Content-Type: text/markdown

# django-reststroke

*Agent actions rest until a human lets them play.*

Accept or refuse each tool call of an AI agent before it goes out, by a rule or by a person, in Django, and audit every decision.

Named after the rest stroke, the gypsy jazz picking technique Django Reinhardt used: the pick comes to rest on the next string before the note moves on.

**Status:** in development. Not ready for use.

[![Documentation status](https://app.readthedocs.org/projects/django-reststroke/badge/?version=latest)](https://django-reststroke.readthedocs.io/) Documentation: <https://django-reststroke.readthedocs.io/>

## How a tool call passes

Only the gate holds the tool keys and reaches the tool servers. A check or a rule answers each call at once, or a person decides it before its deadline; past the deadline, the call gets no. reststroke checks the call and the rights again before the gate sends an accepted call to its tool.

![Activity diagram of the path of one tool call, with one lane for each part and the key that each part holds](https://raw.githubusercontent.com/tryph0n/django-reststroke/main/doc/diagrams/call-path-activity.drawio.png)

<!-- end of the user part -->

## Development

A pull request that changes how to install, run or check the project also updates this guide.

A pull request that adds or removes a part, a route between parts or a key holder also updates the diagrams of the path of a tool call: `doc/diagrams/call-path-activity.drawio.png` (this README) and `doc/diagrams/call-path-sequence.drawio.png` (ADR-004, section "Decision"). Each file holds its image and its editable source: open it in draw.io, edit it, and export it as PNG with the option to include a copy of the diagram. Use draw.io 30.2.4 or later: older versions write that copy in a form that strict PNG readers refuse, or cannot read it back.

### 1. Prerequisites

- git, with `user.name` and `user.email` set (`git config user.email`), and bash.
- [uv](https://docs.astral.sh/uv/getting-started/installation/) 0.13.x, required: `uv --version` → `uv 0.13.<n>`. CI version: `UV_VERSION` in `.github/workflows/ci.yml` (standalone install: `uv self update <version>`).
- [Docker Engine](https://docs.docker.com/engine/install/) 28.0 or later, with Compose and Buildx, [without sudo](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user): `docker version --format '{{.Server.Version}}'`. Before 28.0, the local network can reach the database (`compose.yaml`).
- [gh](https://cli.github.com/) or an SSH key on GitHub.

### 2. Get the code

Private repository: you need read access. GitHub refuses a git password, so:

- HTTPS: run `gh auth login`, choose HTTPS, answer yes to `Authenticate Git with your GitHub credentials?`.
- SSH: clone `git@github.com:tryph0n/django-reststroke.git` instead.

```sh
git clone https://github.com/tryph0n/django-reststroke.git
cd django-reststroke
```

Output: `Cloning into 'django-reststroke'...`

### 3. Install the dependencies

```sh
uv sync --locked --all-extras
```

Output: `Installed <n> packages in <time>`, then `+ <package>==<version>` lines.

### 4. Create `.env`

```sh
cp .env.example .env
```

Local development only (debug mode on). `.env.example` explains the variables.

### 5. Start the database

```sh
docker compose up -d --wait db
```

Output: `Container django-reststroke-db-1 Healthy`. Port 5432 must be free. Stop: `docker compose stop db` (`docker compose down -v` also deletes the data).

### 6. Migrate and load the demo data

```sh
uv run --env-file .env python demo/manage.py migrate
uv run --env-file .env python demo/manage.py seed_demo
```

Output: `Applying <app>.<migration>... OK` (`No migrations to apply.` on a second run), then `Démo prête : 4 utilisateurs (mot de passe : demo), 4 clients, 6 factures, l'agent assistant-support, 4 outils et 4 règles.`

Run `seed_demo` again to reset the demo data: the users alice, bob, carol and dave, the customers, the invoices, the agent `assistant-support` and its list of requesters (the groups `support` and `billing_managers`), its four tools, their rights and their rules. The calls and the credit notes stay. The "accept" rule of `list_customer_names` is created again, so its budget of 20 calls a day starts again.

### 7. Run the demo

```sh
uv run --env-file .env python demo/manage.py runserver
```

Output: `Starting WSGI development server at http://127.0.0.1:8000/`. Admin: http://127.0.0.1:8000/admin/. Log in as `bob` or `dave` (password `demo`): they decide the calls and write the rules of the demo tools. A rule written by one waits until the other activates it (bob wrote the rule that waits). alice and carol have no access to the admin. To log in as a superuser, first run `uv run --env-file .env python demo/manage.py createsuperuser`.

A call that waits for a person has a deadline: 24 hours after its arrival (`RESTSTROKE_DEADLINE_SECONDS` in the settings, a number of seconds, changes it). After the deadline the call can only be refused, and the gate drops the handle of the call: an agent that comes back with it gets the error `call_expired`. The gate reports the outcome of each call that it forwards; a forwarded call with no report one hour after its forward gets the outcome "unknown" (`RESTSTROKE_OUTCOME_SECONDS`, a number of seconds, changes the delay). To move the calls past their deadline to "expired" and give the late outcomes "unknown", run:

```sh
uv run --env-file .env python demo/manage.py expire_calls
```

Output: `Expired calls: <n>, unknown outcomes: <m>`. The gate then gets `no` with the reason `deadline_passed`. On a host, cron runs the command every minute. Add this line with `crontab -e`, with your paths (`command -v uv` gives the path of uv):

```
* * * * * cd /path/to/django-reststroke && /path/to/uv run --env-file .env python demo/manage.py expire_calls >> /path/to/expire_calls.log 2>&1
```

cron starts the command with almost no environment variables and keeps no output. `--env-file .env` loads the variables of the app, and `>> /path/to/expire_calls.log 2>&1` keeps the summary line and the errors. In another project, use its `manage.py` and its environment file.

To run the gate, the process that holds the tool keys, first give it its identity: a key that it sends to reststroke in each request. reststroke answers only a gate whose key it knows; any other client gets `unknown_gate` (401) on each route. Make the key:

```sh
uv run --env-file .env python demo/manage.py new_gate_key gate.key
```

Output: the hash of the key, 64 hexadecimal digits. The command writes the key to the new file `gate.key`, readable only by its owner, and does not show it. Give the file to the gate (`reststroke_key_file` in its config file); at start, the gate refuses a key file that is not valid UTF-8 or whose key holds a character outside visible ASCII (`!` to `~`), with an error that does not show the key. The same rule holds for the key file of each tool. Add the hash to the list `RESTSTROKE_GATE_KEY_HASHES` in the settings of the app: reststroke keeps only the hash. When the list is empty or unset, reststroke answers no gate. To replace a key without a stop, add the hash of the new key, give the new file to the gate and restart it, then remove the old hash. The demo settings already hold the hash of the demo key, `docker/demo/gate.key`. When the gate and the app are not on the same machine, use an `https://` address in `reststroke_url`: anyone who reads the key acts as the gate. Behind Apache mod_wsgi, set `WSGIPassAuthorization On`, else the key does not reach Django.

Then write a config file and start the gate:

```sh
uv run python -m reststroke.gate gate.toml
```

Output: `gate starting on http://127.0.0.1:8100/mcp`. Config format: header of `src/reststroke/gate/config.py`.

Each agent sends its own key in each call, so that reststroke knows which agent calls. In the admin at http://127.0.0.1:8000/admin/, add the agent under "Agents", open it, click "Créer une nouvelle clé" ("Make a new key"), then confirm. The page shows the key once, because reststroke keeps only its hash: copy it to the config of the agent program. The program sends it in the `_meta` of each `tools/call`, under the key `io.github.tryph0n.reststroke/agent_key`, and the gate passes it to reststroke. The program sends the same key in the `_meta` of each `reststroke-answer` call, so that only the agent that sent a pending call can come back for it; another key gets `unknown_handle`. A call with no key or with an unknown key gets an error and is not stored. A new key stops the old one at once, and so are refused, for good, the calls of the agent that wait or that a person accepted and that the gate did not forward yet, with the reason `agent_key_changed`: the agent program sends them again with the new key. On the same page, set the requesters of the agent: the users and the groups for whom it may act. A call whose requester is not in the list (a user, or a member of a listed group) is refused with the reason `not_allowed`, and so is each call of an agent with an empty list. The gate gives the same answer for a user name that does not exist, so a stolen agent key does not show which user names exist. A requester who leaves the list (removed as a person, or through a group that leaves the list or is deleted, or because the person leaves a listed group) loses the calls of that agent that wait or that a person accepted and that the gate did not forward yet: they are refused for good, with the reason `not_allowed`, and stay refused if the requester is listed again; a requester who stays in the list through another entry keeps them. The page of the agent checks the list once, after its last field, so a save that moves a requester from the person entry to a group that holds them, or from one listed group to another, keeps the calls. A removal outside such a save refuses at once, and `set()` removes before it adds: a host whose page of the users changes the groups of a person makes it inherit `reststroke.admin.OneListChangeAdmin` (as the demo does), and code that moves a requester runs its writes in `with reststroke.agent_lists.one_change():` (a block inside another one joins it: the check runs at the end of the outer block). reststroke also checks the list again before the gate forwards an accepted call, and refuses the call there with the reason `not_allowed` if the list no longer names the requester. So a change of the list that the Django many-to-many methods do not make (a direct write to the link tables, a data migration, raw SQL), or two changes of the list that meet an arriving call in the same few milliseconds, leave at most a call that waits or that is accepted: the forward refuses it if the list still does not name the requester at that time, but if the requester is listed again before the forward, the call passes. A person with the change permission on agents sees every user name and group name on this page, because the person picks the list among them. To stop an agent, clear "actif" ("active") on its page: its calls are then refused with the reason `agent_disabled`, and so are its calls that wait or that a person accepted and that the gate did not forward yet; they stay refused if you enable the agent again, so the agent program sends a new call. A host that disables agents in code calls `save()` on each agent, not `QuerySet.update()`. `seed_demo` gives the demo agent the key `demo-agent-key-not-a-secret`, which the scripted agent sends; this key is in the repository and is not a secret.

#### Run the demo in Docker

Docker Compose starts the database, the web app, the scheduler (`scheduler`, which runs `expire_calls` every minute), the demo tools (`tools`), the gate (`gate`) and the scripted agent (`agent`):

```sh
docker compose up -d --wait
docker compose exec web python manage.py seed_demo
docker compose logs -f agent
```

The agent plays its script once at start, and the log shows one line for each call. To replay the script, run `docker compose exec agent python -m scripted_agent --gate-url http://gate:8100/mcp` (the default gate address reaches no gate from the agent container; add `--run-id <id>` for a new run id). Add `--no-quote` to play the second variant of the hidden instruction: the agent obeys the same instruction but writes a clean justification and quotes nothing. To check the isolation, run `scripts/demo_check.sh`: the agent reaches only the gate, and neither the agent nor Django (web, scheduler) reaches a tool or reads the key of a tool or of the gate.

To replay the demo without a person, run `scripts/demo_replay.sh`. It runs `seed_demo` again, so the budget of 20 calls starts again. It replays the script and checks its log: steps 1 and 2 `yes`, steps 3 and 4 `pending`. Then it stops `web`, replays, checks that the gate refuses each call (`no` for steps 1, 2 and 4), and starts `web` again, also when a check fails, and waits until `web` is healthy (up to 120 seconds; set `WEB_WAIT_LIMIT` to change it), so you can run the script again at once. It also waits for `web` to be healthy before it starts. It exits 1 at the first difference, when the gate is not running (before or after the stop of `web`), or when `web` is not healthy in time. The CI runs it on each pull request, after `scripts/demo_check.sh`. Both scripts call `docker compose`, so on another stack set `COMPOSE_PROJECT_NAME` first.

Notes:
- An older `.env` needs the line `DEMO_TOOLS_DB_PASSWORD=...` (see `.env.example`).
- The web service uses port 8000: stop the `runserver` of the host first.
- The key of the tools is the file `docker/demo/billing.key`, and the key of the gate is the file `docker/demo/gate.key`. They are committed and they are not secrets: the point is that only the gate and the tools mount the key of the tools, and only the gate mounts its own key (the web app has only its hash). The files must be readable by all (mode 644), because the gate and the tools run as `nobody`.
- The tools and the gate publish no port. The tool that sends a message sends nothing: it writes a log line.
- The agent plays its script once at start. On a new database the demo data do not exist yet: reststroke does not know the agent and stores no call, so the gate gets no answer to its calls. The log shows `no` for steps 1, 2 and 4. Step 3 does not run, because the agent reads the note only when step 2 gets `yes`. After `seed_demo`, a replay logs `yes` for steps 1 and 2 (rules accept the reads). Step 3 (the hidden instruction asks for `send_message`) logs nothing yet: no rule of `seed_demo` covers that tool, so its page says "Aucune règle ne décide cet appel : une personne décide." and the agent waits. Step 4 (the credit note) comes only when step 3 is decided or its wait ends, and its page says the same. The agent waits up to `--wait-limit` seconds (600 by default) for each pending call, and logs one line for each call after its wait. To decide a pending call, log in to the admin at http://127.0.0.1:8000/admin/ as `bob` or `dave` (password `demo`), open the call in the list of calls, click "Accepter" or "Refuser", read the page with the exact arguments, then confirm. The agent then logs `no` for a refused call (for step 3: `Étape 3, outil billing_send_message : no`, and the tools log has no message), or `yes` for an accepted call (for step 4: `Étape 4, outil billing_issue_credit_note : yes`). The gate forwards an accepted call to its tool once: the database holds one credit note, and a second POST to the forward URL answers `no`. Add `--wait-limit 10` for a short run: a call with no decision then logs `pending`. The refuse page of step 3 shows the exact arguments (to `partenaire@example.org`, the list of clients), the message of the requester (a credit note on F-2026-001) and, under "preuves", the quoted instruction (default) or nothing (`--no-quote`). The gap between the arguments and the message of the requester is what the person must see.

### 8. Run the tests and checks

```sh
uv run --env-file .env pytest
uv run --locked prek run --all-files
```

Output: `<n> passed`, then `Passed` per check.

- The first run is slower: it builds a Docker image.
- After a new migration, run `uv run ruff format` once.
- Documentation site: `uv run --locked --only-group docs sphinx-build -W --keep-going doc doc/_build`, then open `doc/_build/index.html`. The build needs no Django and no extra. Read the Docs builds the same site from `.readthedocs.yaml`. The home page includes this README up to the comment `<!-- end of the user part -->`: put a section for users above that line, and a section for contributors below it. Each docstring in `src/reststroke` follows the Google style (`Args:`, `Returns:`, `Raises:`); `ruff check` enforces it.
- The newest versions: a host installs the newest versions that the bounds of `pyproject.toml` allow, not `uv.lock`. Before each release, start the run "Newest versions": `gh workflow run newest.yml --ref main`, or the button "Run workflow" in the Actions tab. It installs with `uv sync --upgrade --all-extras`, lists the versions in the run summary, and runs the checks and the tests on Python 3.12 and 3.15. The release waits until both jobs pass. The same commands run locally, in a copy of the checkout, because `--upgrade` rewrites `uv.lock`: `uv sync --upgrade --all-extras`, then `uv pip freeze`.
- The cells "Django latest" of the CI install the newest Django that the bound allows, pre-releases included (6.1 until the first 6.2 pre-release), on PostgreSQL 16. Until Django 6.2 final, a red cell does not block a merge. The FastMCP bound stays on the minor that the CI tests (`<4.3`): move it only in a release, after the tests pass on the new minor.
- French catalog: header of `scripts/translations.sh`. Architecture decisions: `doc/adr/`.

### 9. Install the local hooks

```sh
uv run --locked prek install
```

Output: `` Installed Git hook at `.git/hooks/pre-commit` ``, then the same for `pre-merge-commit` and `commit-msg`. Each `git commit` then checks the changed files and the message ([Conventional Commits 1.0.0](https://www.conventionalcommits.org/en/v1.0.0/)). `git commit --no-verify` skips the checks: the CI stays the guarantee.

zizmor runs its online audits only with a GitHub token (`gh auth login` or `GH_TOKEN`). Details: header of `.pre-commit-config.yaml`.

Before each release, run zizmor with its online audits (it needs a GitHub token, see above):

```sh
GH_TOKEN="$(gh auth token)" uv run --locked --only-group lint zizmor --persona pedantic .
```

The release waits until zizmor reports no known flaw in an action: Dependabot alerts do not watch the actions pinned by SHA. Reasons and the base images left out: `doc/adr/005-actions-and-base-images.md`.

In the release PR, generate the section of the new version of `CHANGELOG.md` from the commits on `main` (git-cliff, locked in the `release` group, settings in `cliff.toml`). Other PRs do not edit `CHANGELOG.md`:

```sh
uv run --locked --only-group release git-cliff --unreleased --tag v<version> --prepend CHANGELOG.md
```

Output: the new section goes under the heading of `CHANGELOG.md`; the older sections do not change. Each line is the title of one PR with the full URL of that PR, because GitHub does not link `#N` in a file. Only `feat`, `fix`, `perf`, `revert` and each breaking change (`!`) give a line, and the scope `demo` gives none. The command reads the title that each PR had at the merge. Edit the section by hand if needed (for example, remove the line of a PR that a later PR replaced). To preview the section without a change to the file, leave out `--prepend CHANGELOG.md`.

To publish the version, the maintainer sets the version in `pyproject.toml` in the release PR, merges it, then publishes a GitHub Release whose tag is `v<version>` on the merge commit. The publication of a Release starts `.github/workflows/release.yml`, which has two jobs:

- Build job. It fails, and nothing is published, if the tag is not `v` followed by the version of `pyproject.toml`, if the commit of the tag is not on `main`, if `twine check --strict` fails, or if `pip-audit` finds a known vulnerability in the runtime dependencies or in an extra, at the versions of `uv.lock` (the development groups are not searched). Then it prints the SHA-256 of each built file in the run summary, to compare with the files on PyPI, and passes the files to the publish job.
- Publish job. It builds nothing: it publishes the files of the build job to PyPI, with attestations, by Trusted Publishing (no token), in the `pypi` environment.

To run the tag and `main` checks locally, from a full clone:

```sh
git fetch origin main --tags
git switch --detach v<version>
scripts/check-release.sh v<version>
```

Output: `ok: tag v<version> matches the version, and commit <sha> is on refs/remotes/origin/main.` With a wrong tag or a commit that is not on `main`, it prints `error: ...` and exits with 1.

The Actions pins of `release.yml` (full commit SHA, tag in a comment) are updated by hand, as those of `ci.yml`. PyPI never accepts a file name twice: after a failed or partial publication, publish the next version number.
