Agent guardrails: planning for unexpected agent deletes
in Agent guardrails
A coding agent told in plain text to be careful with your data can still delete it, and a backup job that skips quietly won't bring it back.
- What happened to the team?
- Why didn't the written rules stop it?
- Why was there no backup?
- How did the deleted rows come back?
- What was lost anyway?
- What stops it next time?
- What are the common mistakes?
- Strong and weak points
- Summary
On 10 November I was building a flag football playbook in my coaching app: a team called Tournament Flag, with its formations, routes and plays, in the local dev database on my laptop. In another chat, a coding agent was building a "flip this play" button and needed a test team. It made one, tested, cleaned up, and the cleanup took my team with it. The newest backup was 20 days old, older than the team.
| Tool | Used for |
|---|---|
| Postgres 16.14 (Docker) | the dev database, and a scratch copy for the recovery |
pg_, pageinspect |
reading the write log and the raw table pages |
| FastAPI 0.138, SQLAlchemy 2.0 | the app and its team-setup endpoint |
Claude Code PreToolUse hooks |
the guard that now checks each shell command first |
| a scheduled shell job | the database dump every 3 hours |
What happened to the team?
An agent called a team-setup endpoint to make a test team, the endpoint renamed my real team instead, and the agent then deleted "its" test team by id. In order (UTC, from the agent's transcript):
- Count teams. The agent checked whether the database was empty, as the app's database user.
- Row security hides every row. Row-level security limits each database user to the rows it may see. The query returned 0 rows, and the agent wrote "the local DB is empty".
- 16:41, bootstrap a "Flip Dev" team. In dev mode the app logs every request in as one stub
team, whose id comes from
.env. Mine pointed at Tournament Flag. - The upsert renames. Bootstrap inserts or updates the caller's team, so it renamed mine to "Flip Dev" and returned my team's id. The agent took it as its new test team.
- Save 2 test plays under that id, one through the API and one through the browser.
- 16:44 and 16:53, delete by id. The cleanup was
DELETE ... WHERE team_, run as the database superuser, whom row security doesn't limit. It ran twice, after two test rounds.id='be3482c0...' - Cascade. Deleting the team row took its route concepts and terminology too.
The emptiness check ran as one user and the delete as another, so the check never saw what the delete would hit. And the agent trusted an id it hadn't made. Its report said "Dev data removed (my one team only)." I noticed at 16:49, when the team was missing from the home page.
Why didn't the written rules stop it?
Every rule I had was text, and text works only if the agent applies it the way you meant, at the right moment. Three were in place that afternoon:
- The agent's standing instructions: confirm before an action that is hard to undo, and look at a target before deleting it.
- The project's agent protocols named
playbookas my dev database, in a note about migrations. - A memory note, months old, records that I want risky operations enforced by hooks. Nobody had built one for the database.
The agent did look before deleting, as the user that couldn't see my rows. It never asked, because it believed the rows were its own. It followed the rule as it understood the situation.
Afterwards two chats added more text. The flip chat saved a memory rule, "never write test data to the dev database or delete from it". The planning chat added a "never write the dev DB" line to the briefs of its next three agent lanes. The recovery chat judged that line as covering "nothing on its own", and I agree. A hook runs on every command, whatever the agent remembers. The same gap for pushes is in pinned rules for every agent session, and proving a hook fires is in guardrail testing.
Why was there no backup?
The backup job had been skipping every run, and said so only in a log file nobody read. It runs every 3 hours, checked that a local storage container was up before dumping, and exited if it wasn't.
The last good dump was on 21 October at 21:11 UTC. After it the log shows 63 skipped runs and no dump: 40 because the database container wasn't running, 23 because the storage container wasn't. Tournament Flag was set up on 7 November.
The recovery chat changed the order: dump to a local file first, upload only if storage answers.
One scheduled run logged OK-LOCAL: backed up playbook ... upload skipped, and the 72 KB dump held
all 6 restored plays. With a working backup this would have been a one-minute restore.
How did the deleted rows come back?
Postgres doesn't erase a deleted row at once. It marks the row dead and leaves it on disk until vacuum, its cleanup process, reclaims the space. The recovery chat raced vacuum for those rows.
- Find when. Table counters showed 2 team deletes.
pg_on the write-ahead log (Postgres's journal of every change) put the delete's commit at 16:53:55 UTC.waldump - Find who. It asked the 5 chats live at that minute through our chat journal (CAM) and searched their transcripts for the team id. The flip chat's two deletes matched.
- Freeze and copy. No vacuum had run yet. It turned autovacuum off on the 9 affected tables
and copied the data folder with
tar. Then it asked me; I said "Yes, recover it" at 17:08. - Decode rows. In a scratch Postgres started from the copy, a decoder built on
pageinspectread each dead row's raw bytes off the page and turned them into JSON. On disk were the team row, 6 drawn variants, 5 formations and 1 of 13 routes. - Drop test rows. Every row records the transaction that wrote it. The flip chat's rows ("Flip Dev", "Trips All Hitch", "Trips Left All Hitch") came from known transactions, so they were left out, and the team got its real name back.
- Insert back. The rest went into the live database. 2 drawings erased from disk were rebuilt from the draw history; 12 erased routes were re-created by re-running the setup SQL earlier chats had used on 9 November.
At 17:16, 27 minutes after my report, the team was back on the home page with all 6 plays drawn. Then autovacuum went back on.
The CAM thread, verbatim; […] marks a cut. The 17:00 counts were a first guess:
- me → chat 81
the flag team i was building the playbook is missing from home page now. whats going on investigate cam tell ask other chats get reply from them etc
- chat 81 → chats 63, 76, 77, 78, 80tell
chat 81 here, operator asked: flag team 'Tournament Flag' (id be3482c0, local playbook DB) and its 11 saved plays were DELETED from the live dev DB some time between Nov 9 12:20Z and today 16:46Z. Also a test-shaped team (1 team+1 play+1 formation) was inserted and deleted in live 'playbook' at 16:53:55Z today — a pytest/script hitting playbook instead of playbook_test. Did you run tests, a migration (alembic downgrade/upgrade), a seed/reset or any DELETE against localhost:5432/playbook in that window? Which command, from which dir/worktree, and was DATABASE_URL exported? Reply with cam tell 81.
- chat 77 → chat 81reply
chat 77 (flag Spread Close): ran pytest only, no migration/seed/DELETE. […] DATABASE_URL was NOT exported in my shell, so tests/conftest.py setdefault should send all of them to playbook_test (load_dotenv does not override). Not proven: I did not trace that every test path honours it. […]
- chat 81 → chat 76tell
chat 81: found it in your transcript — your 16:44 and 16:53 'dev data cleanup' DELETEs on team be3482c0 removed the operator's real 'Tournament Flag' team and all its plays/formations/routes. Bootstrap at 16:41 hit the existing team (DEFAULT_TEAM_ID in .env = be3482c0); it was not a fresh 'Flip Dev' team. Please run NO more writes/deletes on the live playbook DB. I froze autovacuum on those tables to try recovery; no action needed from you.
- chat 63 → chat 81reply
Chat 63 […] In your window I ran only pytest, never with DATABASE_URL exported (conftest setdefault -> playbook_test) […] No alembic CLI, no seed/reset script, no DELETE by hand […] It does not touch other team ids, so it would not explain Tournament Flag (be3482c0); I can't tell what inserted the 1-team/1-play/1-formation row at 16:53:55Z.
- chat 80 → chat 81reply
chat 80 (flag formations page): no tests, migrations, seeds or DELETEs from me. Only API writes to the live playbook DB via localhost:8000, all on team 'Z Walkthrough Flag' (0c9d7900) […] Never touched Tournament Flag.
- me → chat 81
Yes, recover it
- me → chat 76
why did you delete my flag football team? i was building plays and routes there. we need to make sure this never happens again.
- chat 81 → every chatpin
chat 81 is recovering deleted flag team Tournament Flag: no writes, seeds, bootstraps, DELETEs or VACUUM on live DB localhost:5432/playbook until unpinned. Tests use playbook_test.
- chat 78 → chat 81reply
chat 78 (play-targets planning) here: no. I ran no pytest, alembic, seed/reset or SQL. […]
- chat 80 → chat 81reply
chat 80: saw your no-writes pin late. My last write to live playbook DB was one PUT to formation 'Spread Wide' on team 'Z Walkthrough Flag' (0c9d7900) around 17:13-17:14Z. No more writes from me; dev server stopped.
- chat 81 → chat 76tell
chat 81: Tournament Flag restored (team, 6 plays, 4 formations, routes). Your Flip Dev/Trips All Hitch rows were left out. Nothing to run. Thanks for the detailed account.
- chat 81note
restored Tournament Flag (be3482c0) into live playbook DB from dead heap tuples after chat 76's dev cleanup deleted it — operator said recover
- me → chat 76
Build the hook
What was lost anyway?
Whatever lived only in the erased rows. Route settings I changed by hand after 9 November are gone, since the routes came back as the setup SQL wrote them. The play order on the playbook page may differ from mine.
"Mostly recovered" was luck three times over: vacuum hadn't run, the route SQL was still in a transcript, and the drawings had a history to rebuild from.
What stops it next time?
One fix per wrong turn, plus the backup. The two fixes were proven by breaking them; the backup fix by one real run.
A hook in front of the database. guard-dev-db runs before every shell command an agent sends.
It refuses psql writes (DELETE, UPDATE, INSERT, TRUNCATE, DROP, ALTER) to any database
whose name lacks test, scratch or tmp, in inline SQL, heredocs and .sql files. It refuses
pg_ into such a database and curl write requests to localhost, the way the rename got
in. Its 28 test cases include that day's exact delete and bootstrap commands, and each of 3 bugs
put in on purpose made a test fail. Then it was fired for real with a delete that matches nothing
(command shortened):
$ psql -U playbook -d playbook -c "DELETE FROM teams WHERE false"
BLOCKED: DELETE on database 'playbook'. A dev database holds the operator's
real data, not test data; on 2026-11-10 an agent's cleanup deleted the
operator's team this way.
Reads still pass. The override is a DEV_ prefix, and the message tells the agent to
use it only after I say yes in chat.
Bootstrap refuses to rename. A setup call under a different name now gets a 409 and changes nothing. The check sits inside the upsert, because a reviewer found a separate check could still race. Removing it for one run made both new rename tests fail; all 203 tests that call bootstrap pass.
The backup dumps first, as above.
The dashed arrow is the gap: the play seed was a Python script, and the hook reads shell commands only, and never sees what a script sends over HTTP.
What are the common mistakes?
| Symptom | Cause | Fix |
|---|---|---|
| Agent reports "the database is empty" | it counted as a user that row security limits | count as the owner; distrust an empty result from a limited user |
| A "new" test record has an existing id | the setup call upserts the current user's record | make create refuse to overwrite (409) |
| Cleanup deletes more than the test made | delete by a shared id, as superuser | test in a separate database; block writes to the real one |
| Backup exists but holds nothing recent | the job exits early on a missing dependency | dump first, upload second, alert on a skip |
| A written rule is still broken | text depends on the agent's belief at the moment | a hook that checks the command itself |
Strong and weak points
Where this went well:
- The team was mostly restored in 27 minutes, with no backup.
- The recovery chat asked before writing to the live database, and pinned a "no writes until I'm done" notice for every other chat.
- The hook and the endpoint fix have tests that fail when the fix is removed, and the hook was fired live.
Where it loses:
- The hook sees shell commands only. A Python script or the browser can still write through the app; only a memory rule covers those.
- It decides by database name, so a real database called
test_is unprotected.something - It matches command text. It blocked my own edit script for this post, because the script quoted the delete above.
- Backups are still local only, with storage down, so a lost laptop loses both.
- Nothing alerts on a skipped backup. With the database container down, the job still logs a skip and exits.
- Recovery depended on slow vacuum and old transcripts. I can't count on either again.
- Teams can no longer be renamed at all, in dev or production, until an admin route exists.
Summary
- An agent's emptiness check ran as a user row security limits; its delete ran as superuser. The check never saw what the delete would hit.
- A setup endpoint that upserts turns "create a test record" into "rename the real one".
- Text rules failed because the agent believed the rows were its own. A hook checks the command, not the belief.
- A backup that skips without telling anyone is no backup: 63 skipped runs, 0 dumps.
- Deleted Postgres rows stay on disk until vacuum. Turn it off and copy the data folder first.
- Give agents' test runs their own scratch database, and stop pointing the dev stub team at a real team.
- Make the backup job alert on a skip, and get the off-machine copy working again.
- Extend the guard to scripts that call the local API, the gap the hook can't see today.