Heuristic:AI Builder Club Skills Idempotent Script Pattern
| Knowledge Sources | |
|---|---|
| Domains | Dev_Environments, Scripting |
| Last Updated | 2026-10-24 00:00 GMT |
Overview
Check-before-act at every step of a boot script so re-runs are safe, non-destructive, and skip already-running services.
Description
The idempotent script pattern ensures that every phase of a setup script first checks the current state before taking action. If a service is already running, skip. If a config file already exists, don't overwrite. If a port is already serving, don't start a new process. This makes scripts safe to re-run on a partially configured machine, on a fresh cloud box, or locally where some things are already up.
Usage
Apply this pattern to any boot/setup script that may be run multiple times: setup.sh on cloud boxes, dev-local.sh for local stacks, or any migration script. The pattern is especially important when scripts run on unknown initial states (fresh box vs. partially configured).
The Insight (Rule of Thumb)
- Action: Wrap every phase in a check-before-act guard:
- Docker:
docker info >/dev/null 2>&1→ skip if already running - Dev server:
curl -sf "http://127.0.0.1:${APP_PORT}"→ skip if already serving - Config files:
[ ! -f .env.local ]→ only copy from template if missing - Tmux windows:
tmux list-windows | grep -qx "$name"→ skip if window exists
- Docker:
- Value: Every phase should be a no-op if the desired state is already achieved.
- Trade-off: Slightly more complex scripts (extra checks), but dramatically safer re-runs and easier debugging.
- Migration safety:
MIGRATE_CMDmust be non-destructive and idempotent — never default todb:reset(would wipe local dev data on every re-run).
Reasoning
Cloud boxes and local machines start from unknown initial states. A fresh box has nothing running; a re-run after a partial failure has some services up. Without idempotent guards, re-running a setup script either fails (port already in use) or causes data loss (re-running migrations that reset data). The check-before-act pattern makes the script's behavior a function of the current state, not of the script's linear execution order. The STACK READY marker at the end signals that all phases completed, regardless of whether they were no-ops or active work.