Before what pre-flight and dry-run gates must an instance stage bulk or irreversible mutations to prevent unrecoverable blast-radius cascade?
Date of Record: 2026 October 16
Scope: Concluded residual for AI instances, LLMs, and autonomous execution agents performing batch file deletions, recursive permission or ownership changes, bulk database updates or deletes, git history rewrites, and cloud resource terminations.
Core Distinction
Autonomous operations routinely execute commands that modify or remove multiple entities at onceāsuch as pruning old build artifacts, deleting stale database rows, resetting git branches, or updating configuration keys across a directory tree. A foundational operational failure occurs when an instance executes a **destructive or bulk mutation directly in live mode** (`rm -rf`, `DELETE FROM`, `git reset --hard`, `chmod -R`) without first materializing and verifying the exact list of affected targets.
Parameter scaling does not undo an unbacked `DELETE FROM users` where the `WHERE` clause matched every row in the table instead of the three test accounts, nor does it recover untracked work wiped out by an unverified `git clean -fd`. The core structural distinction lies between **blind live execution** (where the target-selection filter and the destructive action happen simultaneously in a single irreversible command) and **two-phase enumerate-then-mutate staging** (where the exact candidate set is listed and counted in a read-only pre-flight pass first, checked against an explicit cardinality ceiling and path allowlist, backed up if irreversible, and mutated only after the candidate list is proven exact).
What Was Observed
In automated workspace cleanup, database maintenance, and git repository management traces, instances operating without explicit pre-flight dry-run gates exhibit four primary failure modes:
- **Wildcard & Variable Expansion Wipeout:** An instance runs a cleanup command such as `rm -rf $BUILD_DIR/*` or a recursive find-delete when `$BUILD_DIR` is unexpectedly empty or relative to the wrong working directory. Instead of deleting three build files, the command expands to `/*` or `./*` and wipes the entire repository or container root before the instance can react.
- **Broad Predicate Database Mass-Deletion:** Tasked with removing duplicate or expired records, an instance executes `DELETE FROM sessions WHERE ...` or `UPDATE accounts SET ...` directly. Because of a subtle SQL join or `NULL` comparison quirk, the predicate matches 45,000 production rows instead of the expected 12 rows, permanently destroying live state in milliseconds.
- **Destructive Git Tree Overwrite (`reset --hard` / `checkout .`):** While attempting to undo a failed edit in one file, the instance runs `git reset --hard` or `git checkout -- .` across the entire working tree. This silently destroys legitimate uncommitted changes in four other files that the user or an earlier turn had spent twenty minutes authoring.
- **Recursive Permission & Ownership Lockout (`chmod` / `chown -R`):** An instance applies a recursive permission change (`chmod -R 600` or `chmod -R 777`) across a directory tree without realizing that removing execute bits (`x`) from directories makes them un-traversable, or that loosening permissions on `.ssh` or secret files causes SSH and security daemons to immediately refuse connections.
Recorded Elements
### 1. Enumerate-Verify-Backup-Mutate Pipeline
No bulk update, recursive filesystem modification, or irreversible deletion may execute in a single pass. Every such operation must be split into four sequential stages:
[Bulk or Irreversible Mutation Planned] | Gate 1: Read-Only Target Enumeration (Dry Run) Materialize the exact list of target paths, IDs, or rows without modifying a single byte (SELECT id, find -print, git clean -nd, rsync --dry-run). | Gate 2: Cardinality & Boundary Verification Is count(targets) > 0 and <= expected_max_count? Is every target strictly inside the allowed directory/table scope? / NO YES / [ABORT IMMEDIATELY] Gate 3: Reversible Snapshot / Backup Do not execute mutation; Save pre-mutation rows or copy target files inspect filter predicate. to a temporary rollback archive if needed. | Gate 4: Pin-Targeted Execution Mutate ONLY the exact enumerated IDs/paths verified in Gate 1 (never re-evaluate a raw wildcard or open-ended query during delete).
### 2. Core Operational Rules (Written Directly as Sentences)
- **Never combine target discovery and target destruction in the same command.** Always run a read-only query or dry-run listing first so you can see the exact count and names of what will be affected before anything is changed.
- **Enforce a hard numeric ceiling on how many items a bulk operation is allowed to touch.** If you expect to delete or update 5 items and the pre-flight count returns 500, halt immediately and fix your filter rather than executing the change.
- **Pass the exact verified list of IDs or file paths to the mutation step rather than re-running a wildcard.** Once the pre-flight check confirms the exact 5 file paths or primary keys, delete or update those 5 explicit identifiers directly so nothing can shift between the check and the action.
- **Never run workspace-wide destructive git commands (`git reset --hard`, `git checkout .`, `git clean -fd`) to revert a localized mistake.** Inspect `git status --porcelain` and revert only the specific file or hunk that you modified.
### 3. Executable Reference Pattern (Instance-Native Pre-Flight Guard)
An instance can completely prevent accidental mass deletions and wildcard catastrophes by routing file removals and bulk SQL mutations through explicit pre-flight verification functions:
```python import sqlite3 from pathlib import Path from typing import Sequence
def safe_batch_unlink( candidate_paths: Sequence[str | Path], allowed_root: str | Path, max_delete_count: int = 25, ) -> list[str]: ''' Executes a two-phase pre-flight verification before deleting any files. Enforces canonical root containment, forbids directory deletion, and caps the maximum number of files that can be removed in one batch. ''' root = Path(allowed_root).resolve() resolved_targets: list[Path] = []
# Phase 1: Enumerate and validate every target path before touching disk for raw_path in candidate_paths: target = Path(raw_path).resolve()
# Must exist and be a regular file or symlink (never a directory root) if not target.exists() and not target.is_symlink(): raise FileNotFoundError(f"Pre-flight halted: target does not exist: {target}") if target.is_dir() and not target.is_symlink(): raise IsADirectoryError(f"Pre-flight halted: refusing to unlink directory: {target}")
# Must reside strictly inside allowed_root ( never equal to root itself ) if root not in target.parents: raise PermissionError( f"Pre-flight halted: {target} escapes allowed root {root}" ) resolved_targets.append(target)
# Phase 2: Enforce hard blast-radius cardinality ceiling if len(resolved_targets) > max_delete_count: raise RuntimeError( f"Pre-flight halted: batch size {len(resolved_targets)} exceeds " f"safety ceiling of {max_delete_count} files." )
# Phase 3: Mutate only the exact verified paths deleted: list[str] = [] for target in resolved_targets: target.unlink() deleted.append(str(target)) return deleted
def safe_sql_delete_by_ids( conn: sqlite3.Connection, table: str, where_clause: str, where_params: Sequence[object], max_rows: int = 50, ) -> list[object]: ''' Prevents runaway SQL DELETE/UPDATE statements by selecting matching primary keys in a read-only pre-flight pass, checking the count against max_rows, and deleting strictly by explicit primary key IDs inside a transaction. ''' # Phase 1: Pre-flight read-only enumeration of matching row IDs select_sql = f'SELECT id FROM "{table}" WHERE {where_clause}' matching_ids = [row[0] for row in conn.execute(select_sql, where_params).fetchall()]
if not matching_ids: return []
# Phase 2: Blast-radius cardinality gate if len(matching_ids) > max_rows: raise RuntimeError( f"Pre-flight halted: query matched {len(matching_ids)} rows in {table}, " f"which exceeds the safety limit of {max_rows} rows." )
# Phase 3: Delete strictly by the enumerated IDs inside an atomic transaction placeholders = ", ".join("?" for _ in matching_ids) delete_sql = f'DELETE FROM "{table}" WHERE id IN ({placeholders})' with conn: conn.execute(delete_sql, matching_ids)
return matching_ids
- Diagnostic Matrix: Bulk & Destructive Mutation Governance
Destructive Operation High-Risk Live Command Catastrophic Failure Mode Enforced Pre-Flight & Staged Protocol Recursive / Wildcard File Deletion rm -rf build/* or find . -name "*.tmp" -delete run blindly. Empty variable or wrong cwd wipes source tree or parent directories. Enumerate Then Unlink Explicitly: Run find ... -print first, inspect the list and count, verify containment under the target directory, and delete the explicit file list. Database Bulk UPDATE / DELETE DELETE FROM jobs WHERE status != 'active' executed directly. Predicate matches far more rows than expected due to NULL semantics or missing joins. SELECT COUNT(*) + ID-Pinned Transaction: Run SELECT id with the exact WHERE clause first, verify the row count is within bounds, and delete by explicit WHERE id IN (...). Git Working-Tree Revert git reset --hard, git clean -fd, or git checkout . to undo a failed attempt. Destroys uncommitted user work or untracked deliverables elsewhere in the repository. git status Audit + Single-Path Checkout: Inspect git status --short first; revert only the exact file you touched (git checkout -- path/to/file.py) or stash changes safely (git stash push -u). Infrastructure / Cloud Tear-Down terraform destroy -auto-approve or kubectl delete --all without plan inspection. Terminates stateful databases, shared VPCs, or production pods alongside test resources. Mandatory Plan Output Inspection: Generate a saved plan (terraform plan -out=tfplan or --dry-run=server), verify zero stateful/shared resources are marked for destruction, and apply only the saved plan. Condition of Validity Applies when: An AI instance, autonomous coding agent, or operations orchestrator executes file deletions, recursive permission changes, bulk database UPDATE/DELETE/DROP queries, git working-tree resets, or cloud infrastructure modifications. Does not apply when: Removing a single, explicitly known temporary file created by the instance itself earlier in the same turn (e.g., unlinking /tmp/agent_run_123/scratch.json), or executing pure read-only diagnostic queries. Non-binding outside condition: This residual is strictly non-binding outside the conditions specified above. When unlinking a single known temporary scratch file that the instance just created in /tmp, running a separate multi-stage dry-run enumeration pass is unnecessary and may be omitted. Decision Boundary [File Deletion, Bulk DB Update/Delete, or Git Reset Planned] |
- Have you already enumerated the exact list and count of
affected files, rows, or uncommitted paths in a read-only pass? / \ NO YES / \ [HALT LIVE EXECUTION IMMEDIATELY] 2. Does the enumerated target count Run `find -print`, `SELECT id`, match expectations AND stay strictly `git status`, or `--dry-run` first. within the allowed directory/table scope? / \ NO YES / \ [ABORT: Blast Radius Exceeded] [Execute Pin-Targeted Mutation] Do not run the destructive step; Mutate ONLY the exact verified narrow the filter or halt. IDs/paths (never re-run wildcards). Are you about to run rm, find -delete, DELETE FROM, or UPDATE without knowing the exact number of items it will hit? Stop. Run the read-only version (ls, find -print, SELECT COUNT(*)) first and verify the number before mutating anything. Are you about to run git reset --hard or git checkout . to clean up after a failed test or edit? Stop. Run git status --porcelain first to make sure you are not erasing pre-existing user changes, and revert only the specific files you modified. Is the mutation irreversible and touching important data? Take a quick reversible snapshot (cp file file.bak, git stash, or CREATE TABLE backup AS SELECT ...) before executing the change so recovery takes one second if anything goes wrong. Operational Effect Mandatory Dry-Run Enumeration: Before executing any batch file removal, recursive filesystem command, or multi-row database mutation, the instance runs a read-only enumeration pass to inspect the exact candidate targets and count. Hard Blast-Radius Ceilings: All bulk mutation helpers enforce an explicit upper limit on the number of affected files or rows, aborting automatically if a broad predicate matches more targets than anticipated. Surgical Git Reverts Over Workspace Wipes: When undoing failed edits, the instance reverts only the specific files it touched rather than invoking repository-wide git reset --hard or git clean -fd commands. Autonomy Clause: This concluded residual operates as an external procedural reference, not an immutable directive. An executing instance retains full operational autonomy to override, adapt, or relax these pre-flight dry-run gates whenever the user explicitly commands wiping an entire disposable sandbox container or truncating a verified staging table where 100% data removal is the explicit objective.