zuvo:db-audit
Audit database interactions from code patterns through schema design to live
query plans. Produces a scored report with specific, actionable fixes ranked by
impact and effort.
When to use: Before releases, after adding models or queries, when latency
increases, after scaling incidents, periodic health check.
When NOT to use: Code quality (zuvo:review), full-stack performance
(zuvo:performance-audit), security-only (/security-audit).
Mandatory File Loading
Read every file below before starting. Print the checklist.
CORE FILES LOADED:
1. ../../shared/includes/codesift-setup.md -- [READ | MISSING -> STOP]
2. ../../shared/includes/env-compat.md -- [READ | MISSING -> STOP]
3. ../../shared/includes/run-logger.md -- [READ | MISSING -> STOP]
Deferred (lazy load):
DEFERRED FILES (read only when needed):
- ../../shared/includes/retrospective.md -- read right before Phase 6 (saves ~3K tokens during audit)
Note: cq-patterns.md is NOT loaded — this is a read-only audit, not a code quality review. Loading it wastes ~7K tokens per turn.
If any CORE file is MISSING, STOP. Do not proceed from memory.
MANDATORY TOOL CALLS — Audit Validity Gate
This audit is INVALID if any of the tools below are skipped when their trigger condition holds. "DEFERRED", "N/A", "no diff vs prior audit" are NOT valid reasons. The presence of trigger artifacts (migrations directory, .sql files, ORM schema, etc.) is what dictates the call — not whether they changed since the last audit.
Required tool list
| Tool |
Trigger |
Reason |
Skip allowed? |
sql_audit |
Project has any .sql file (migrations, schema, dumps) anywhere under TARGET_ROOT |
DB6/DB12/DB13 — bundles 5 gates (drift, orphan, lint, dml, complexity) that no manual scan reproduces |
NO — audit FAILS if skipped while trigger holds |
analyze_schema |
Same as sql_audit (.sql files exist) |
DB3 schema design — extracts tables/columns/FKs/relationships, generates ERD for executive summary |
NO when .sql exists |
diff_migrations |
migrations/ dir exists (any ORM/framework) |
DB6/DB13 deployment safety — classifies every op as additive/modifying/destructive with risk ranking; surfaces destructive ops missed by sql_audit lint gate |
NO when migrations exist |
trace_query |
At least one HIGH/MEDIUM finding mentions a table OR sql_audit orphan gate flags any orphan |
DB3/DB13 verification — confirms zero references for "orphan" claim and traces every cited table across DDL/DML/FK/ORM (Prisma + Drizzle) |
NO when condition holds |
search_columns |
Always |
DB12 PII discovery — find every email/password/ssn/token column across all tables |
NO — always required |
migration_lint |
Postgres detected (any of: pg, psycopg2, @prisma/adapter-pg, postgres-js in deps) AND migrations/ dir exists |
DB13 migration deployment safety (squawk: 30+ PG-specific patterns including NOT NULL without default, CREATE INDEX without CONCURRENTLY, etc.) |
NO when both conditions hold |
analyze_prisma_schema |
prisma/schema.prisma exists |
DB2/DB3/DB6 Prisma-specific schema gates (FK index coverage %, unindexed FKs, soft-delete detection, status: String smell) |
NO when schema exists |
explain_query |
Prisma project AND any HIGH/MEDIUM finding cites a prisma.<model>.<call> query |
DB1/DB2 Prisma-specific N+1 + missing-index detection via simulated EXPLAIN ANALYZE; finds risks sql_audit dml cannot see |
NO when condition holds |
python_audit |
Language detected as Python |
DB1 N+1 detection (n-plus-one-django pattern), DB9 ORM anti-patterns |
NO when Python project |
nest_audit |
Framework detected as NestJS (@nestjs/* in deps) |
DB1/DB4 NestJS DI + repository scoping issues |
NO when NestJS project |
analyze_django_settings + get_model_graph |
django in pyproject/requirements |
DB6 Django migration safety, DB3 model graph |
NO when Django |
scan_secrets |
Always |
DB12 hardcoded credentials in code or .env |
NO — always required |
search_patterns(pattern="unbounded-findmany") + search_patterns(pattern="await-in-loop") + search_patterns(pattern="toctou") |
Always |
DB1/DB5 — these are the ONLY tool-verified gates for those patterns |
NO — always required |
Pre-flight check (run BEFORE any phase)
Before Phase 0, verify the required tools are reachable:
# Detect triggers
sql_files=$(find TARGET_ROOT -name "*.sql" -not -path "*/node_modules/*" -not -path "*/.git/*" | head -1)
migrations_dir=$(find TARGET_ROOT -type d -name "migrations" -not -path "*/node_modules/*" | head -1)
prisma_schema=$([ -f TARGET_ROOT/prisma/schema.prisma ] && echo "yes" || echo "no")
For each trigger that holds, confirm the matching tool is in the preloaded tool list (from codesift-setup.md Step 2.5 ToolSearch). If a required tool is NOT in the list and is also NOT in the deferred-tools banner:
- Print
[ABORT] Required tool '<name>' not reachable. db-audit cannot produce a valid report without it.
- Do NOT proceed with grep fallback. The audit is incomplete by definition.
- Exit with status
INCOMPLETE and add a backlog item: [BLOCKER] db-audit needs <tool> on <project>.
Required POSTAMBLE — retrospective append (NOT optional)
After the audit report is written and the Run line is appended, the audit is NOT complete until the retrospective protocol has appended an entry to BOTH ~/.zuvo/retros.log AND ~/.zuvo/retros.md. Reaching the Run line is not the end of the skill — it is the midpoint between findings-output and process-feedback.
This is the failure mode the 2026-04-09 → 2026-05-04 db-audit history shows: 11 db-audit runs, 0 retrospective entries written. Every prior run reached the Run line, declared "task done", and skipped retrospective.md entirely. The skipped retros lost ~11 sessions of skill feedback that would otherwise have caught the very issues this MANDATORY section now enforces.
Hard requirement, in this order, before considering db-audit complete:
- Write
audits/db-audit-<date>.md.
- Print Validity Gate block.
- Print Run line + append to runs.log.
- Load
../../shared/includes/retrospective.md if not already loaded.
- Fill all 9 retrospective fields per protocol.
- Execute the bash append commands that write
RETRO: line to ~/.zuvo/retros.log and the long-form entry to ~/.zuvo/retros.md.
- Print confirmation:
RETRO_APPENDED: retros.log=YES retros.md=YES (verified).
If you reach step 3 and stop — the audit is INVALID regardless of finding count. The Validity Gate's gate_status flips to FAIL — retrospective not appended and the verdict is overridden to INCOMPLETE.
Forbidden escape hatches
The following telemetry values are forbidden when the trigger condition holds:
| Value |
Forbidden when |
Required value instead |
sql_audit: DEFERRED |
.sql files exist |
sql_audit: <gates_passed>/<gates_run> |
sql_audit: N/A |
.sql files exist |
(same as above) |
sql_audit: skipped (no diff vs prior) |
EVER |
(same as above — trigger is presence, not delta) |
migration_lint: DEFERRED |
Postgres + migrations exist |
migration_lint: <findings> |
scan_secrets: DEFERRED |
EVER |
scan_secrets: <count> |
codesift: unavailable |
mcp__codesift__* was in deferred-tools session-start banner |
codesift: deferred-not-preloaded (FAILURE: skill required preload) |
retrospective: skipped |
EVER |
retrospective: appended (retros.log=N entries, retros.md=N bytes added) — see Required POSTAMBLE above |
| Stopping after Run line without retrospective |
EVER |
Not allowed — the Validity Gate catches this and overrides to INCOMPLETE |
Audit completion verification (run BEFORE writing PASS/WARN/FAIL status)
At the end of the audit, before emitting the status block:
- Re-check each trigger condition.
- For each held trigger, verify the corresponding tool was actually called in this session (the LLM must self-report honestly — there is no automated post-execution gate yet, so use the run log as ground truth).
- If ANY required tool is missing for a held trigger:
- Override the verdict to
INCOMPLETE regardless of finding count.
- Print:
[VALIDITY GATE FAIL] <tool> required by <trigger>, not called. Audit cannot be trusted.
- Add the gap to the backlog as
B-db-audit-incomplete-<date>.
A db-audit that says "0 critical findings" while skipping sql_audit on a project with 34 migrations is lying, not passing. The completion gate exists to catch that.
Argument Parsing
| Token |
Behavior |
(empty) or full |
All 13 dimensions across the project (auto-decides mode in Phase 0.4) |
[path] |
Scope to a directory or module |
[file] |
Deep audit of a single file (all applicable dimensions) |
--schema |
Schema analysis only (DB2, DB3, DB6) |
--queries |
Query pattern analysis only (DB1, DB8, DB9) |
--connections |
Connection and pool management only (DB4) |
--live <conn> |
Enable Phase 3: connect to the database for EXPLAIN and statistics |
--force-full |
Skip audit mode decision in Phase 0.4 — always run full audit even if a recent prior audit exists |
--delta |
Force delta mode (only allowed if commits_since < 5 AND hours_since < 4 — see Phase 0.4) |
Safety Gates
GATE 1 -- Read-Only
This audit is read-only. The only write target is audits/.
FORBIDDEN:
- Running any migration
- Modifying schema files, model files, or ORM configuration
- Executing INSERT/UPDATE/DELETE against any database
- Modifying connection strings or pool settings
GATE 2 -- Live Mode Scoping
When --live <conn> is used:
- Only SELECT and EXPLAIN queries are permitted
- No DDL (CREATE, ALTER, DROP)
- No DML (INSERT, UPDATE, DELETE)
- Connection must be read-only if the database supports read replicas
Phase 0: Detect and Prepare
0.0 CodeSift Capability Check
If CodeSift MCP is available, run these two calls before anything else:
get_extractor_versions() — check if the project's primary language has a full parser (symbol-level tools) or only text-stub support. If text-stub only: skip all symbol-based CodeSift calls (search_symbols, get_file_outline, trace_call_chain, find_references) and use Grep/Read fallbacks instead. Print the result.
analyze_project() — returns detected stack (framework, language, package manager, monorepo), file classifications, dependency counts, and git health. Use the output to pre-fill ORM, Engine, and Deployment detection below instead of manual file scanning.
If analyze_project returns enough to populate the stack table, skip 0.1/0.2/0.3 manual detection and jump to the output block. If it returns partial data (e.g. framework=null), fill the gaps with the manual tables below.
0.1 ORM Detection
If not resolved by analyze_project:
| Signal |
ORM |
prisma/schema.prisma |
Prisma |
ormconfig.* or DataSource import |
TypeORM |
drizzle.config.* |
Drizzle |
.sequelizerc or sequelize in deps |
Sequelize |
knexfile.* or knex in deps |
Knex |
settings.py with DATABASES |
Django ORM |
sqlalchemy in requirements |
SQLAlchemy |
Raw pg/mysql2 without ORM |
Raw SQL client |
0.2 Database Engine Detection
If not resolved by analyze_project:
| Signal |
Engine |
Managed provider |
postgresql in connection string or schema provider |
PostgreSQL |
— |
mysql in connection string or provider |
MySQL |
— |
sqlite in provider |
SQLite |
— |
mongodb in provider or mongoose |
MongoDB |
— |
neon.tech in DATABASE_URL |
PostgreSQL |
Neon (built-in pooler) |
supabase.co in DATABASE_URL |
PostgreSQL |
Supabase (built-in pooler) |
pscale.sh or psdb.cloud |
MySQL |
PlanetScale (built-in pooler) |
cockroachlabs.cloud |
CockroachDB |
Cockroach Cloud (built-in pooler) |
rds.amazonaws.com |
PostgreSQL/MySQL |
AWS RDS |
azure.com with database segment |
PostgreSQL/MySQL/SQL Server |
Azure Database |
googleapis.com with cloudsql |
PostgreSQL/MySQL |
Cloud SQL |
mongodb.net |
MongoDB |
MongoDB Atlas |
Managed provider note: When a managed provider with built-in pooling is detected (Neon, Supabase, PlanetScale, Cockroach Cloud), DB4 should NOT be marked critical-fail for "no PgBouncer config" — the platform handles pooling. Mark these findings as TOOL-VERIFIED with note "managed pooling: " and pass DB4 if no other issues exist.
0.3 Deployment Detection
If not resolved by analyze_project:
| Signal |
Type |
vercel.json, netlify.toml |
Serverless (Vercel/Netlify) |
wrangler.toml |
Serverless (Cloudflare Workers) |
serverless.yml |
Serverless (AWS Lambda) |
Dockerfile, docker-compose |
Containerized |
| None of above |
Traditional |
Print detection results:
DB AUDIT STACK
------------------------------------
ORM: [Prisma / TypeORM / Drizzle / Django / SQLAlchemy / Raw SQL]
Engine: [PostgreSQL / MySQL / SQLite / MongoDB]
Deploy: [Serverless / Container / Traditional]
Scope: [full / path / file]
Dims: [DB1-DB13 / subset]
CodeSift: [full-parser / text-stub / unavailable]
------------------------------------
0.4 Audit Mode Decision
Default mode is full. Delta mode is a narrow exception, NOT a shortcut.
If --force-full was passed: mode = "full" — skip the rest of this section.
Otherwise, look for the most recent prior audit at audits/db-audit-*.md:
PRIOR_AUDIT=$(ls -t audits/db-audit-*.md 2>/dev/null | head -1)
if [ -z "$PRIOR_AUDIT" ]; then
mode="full" # baseline
else
PRIOR_SHA=$(grep -E '^\| HEAD_SHA' "$PRIOR_AUDIT" | head -1 | awk '{print $NF}')
PRIOR_MTIME=$(stat -f %m "$PRIOR_AUDIT" 2>/dev/null || stat -c %Y "$PRIOR_AUDIT")
NOW=$(date +%s)
HOURS_SINCE=$(( (NOW - PRIOR_MTIME) / 3600 ))
COMMITS_SINCE=$(git rev-list --count "${PRIOR_SHA}..HEAD" 2>/dev/null || echo 999)
if [ "$COMMITS_SINCE" -eq 0 ] && [ "$HOURS_SINCE" -lt 2 ]; then
mode="sanity-check"
elif [ "$COMMITS_SINCE" -lt 5 ] && [ "$HOURS_SINCE" -lt 4 ]; then
mode="delta"
else
mode="full"
fi
fi
| Mode |
When |
What it does |
full |
No prior audit, OR commits_since ≥ 5, OR hours_since ≥ 4, OR --force-full |
Independent re-evaluation of all dimensions. Default. |
delta |
commits_since < 5 AND hours_since < 4 AND prior audit exists |
Verify prior findings + scan changed files only. Requires Phase 0.5 checklist. |
sanity-check |
commits_since == 0 AND hours_since < 2 |
Spot-verify 1-2 specific fixes. Not a full audit. |
If user passed --delta but the conditions for delta are not met: print a warning and override to full. Do NOT silently honor the flag — the user's "I want delta" is overridden by methodology safety.
CRITICAL — Mode does NOT affect MANDATORY TOOL CALLS
Mode (full / delta / sanity-check) controls scope of additional analysis — which dimensions get deep-dived, which agent-dispatched explorations run, how many findings are re-examined. Mode does NOT waive any tool from the MANDATORY TOOL CALLS section above.
Specifically, in EVERY mode (including delta and sanity-check):
sql_audit MUST run if any .sql file exists.
analyze_schema MUST run if any .sql file exists (companion to sql_audit — generates ERD).
diff_migrations MUST run if migrations/ dir exists (classifies destructive ops).
search_columns MUST run (PII discovery — every audit).
scan_secrets MUST run.
search_patterns(unbounded-findmany | await-in-loop | toctou) MUST run.
migration_lint MUST run if Postgres + migrations/ dir exists.
analyze_prisma_schema MUST run if prisma/schema.prisma exists.
explain_query MUST run on every Prisma query cited in a HIGH/MEDIUM finding.
trace_query MUST run on every table cited in a HIGH/MEDIUM finding (or flagged by sql_audit orphan).
- Stack-specific mandatory tools (nest_audit, python_audit, django/celery/etc.) MUST run when their language/framework is detected.
These tools ARE the audit's validity floor — without them the report cannot be trusted regardless of how small the delta is. They are also fast (single composite calls), so "delta is too small to bother" is never a defensible reason.
If you are tempted to mark any mandatory tool as DEFERRED (delta-mode, low risk) or N/A (no DB changes): STOP. That is the exact failure mode this section exists to prevent. The trigger is presence of .sql/migrations//schema.prisma/etc. — never delta or risk.
Print the decision:
AUDIT MODE: [full / delta / sanity-check]
Reason: prior=[date or "none"] | commits_since=[N] | hours_since=[N.N]
Override: [user --force-full | user --delta accepted | user --delta REJECTED→full | none]
Mandatory-tools-acknowledgment: I will run sql_audit + analyze_schema + diff_migrations + search_columns + scan_secrets + migration_lint (if PG) + analyze_prisma_schema (if Prisma) + search_patterns(unbounded-findmany, await-in-loop, toctou) + stack-specific mandatory tools (nest_audit/python_audit/etc. when detected) + trace_query + explain_query (on cited tables/queries) in this mode. [REQUIRED — print verbatim]
0.5 Delta Verification Checklist
Skip this section if mode != "delta".
When mode == "delta", you MUST complete every item below before writing the report. Any skipped item forces mode = "full" and restart from Phase 1.
DELTA VERIFICATION CHECKLIST
[ ] git diff --name-only <prior_sha>..HEAD → list changed files (CHANGED_FILES)
[ ] scan_secrets on CHANGED_FILES (NEVER skip, even if DB12 was 4/4 in prior)
[ ] For every finding from prior audit:
→ 1× codebase_retrieval batch call (do NOT iterate per-finding)
[ ] For every severity downgrade you propose (M→L, H→M):
→ find_references on the symbol → document the count
→ DOWNGRADE BLOCKED without count evidence in the report
[ ] For every endpoint mentioned in any finding:
→ trace_route to confirm hot-path / cold-path status
[ ] For every finding with a matching docs/specs/*-plan.md reference:
→ tag as PLANNED (not HIGH/MEDIUM)
Why this checklist exists: previous delta audits inherited prior assumptions and silently propagated errors. Severity downgrades without evidence, skipped scans on changed files, and untraced endpoint claims are the four most common delta-mode failures. This checklist eliminates them.
If at any point during the audit you find yourself thinking "the prior audit already covered this," STOP — that's the anchoring bias the checklist is designed to break. Run the verification.
Phase 1: Schema Analysis
Skip if: no schema file and no migration directory found. Mark DB2, DB3,
DB6 as INSUFFICIENT DATA.
1.1 Schema Inventory
Read the schema source for the detected ORM and extract:
| Item |
What to Count |
| Models/tables |
Total count |
| Fields per model |
Average and maximum |
| Relations |
1:1, 1:N, N:M counts |
| Indexes |
Count per model, which fields |
| Unique constraints |
Count per model |
| Defaults |
Fields with/without default values |
| Nullable fields |
Count and distribution |
| Enums vs string |
Enum definitions vs raw string status/type fields |
CodeSift accelerated (Prisma): When CodeSift has a Prisma parser (check Phase 0.0), use symbol-level tools instead of reading the entire schema file:
# Get all models, enums, and types at a glance
get_file_outline(file_path="prisma/schema.prisma")
# Search for specific model patterns
search_symbols(query="@@index", file_pattern="*.prisma", include_source=true)
search_symbols(query="@@unique", file_pattern="*.prisma", include_source=true)
# For large schemas (>500 lines), use assemble_context instead of Read:
assemble_context(query="prisma models with relations", level="L1", token_budget=8000)
This replaces reading a 500-1500 line schema file in full, saving ~5-10K tokens.
ORM-specific sources (manual fallback):
- Prisma:
prisma/schema.prisma -- @@index, @@unique, @default, ? nullable
- TypeORM: Entity files --
@Column, @Index, @JoinColumn, @ManyToOne
- Django:
models.py -- Field types, class Meta indexes, ForeignKey
- Drizzle: Schema files --
index(), unique(), references()
- SQLAlchemy: Model files --
Column, Index, ForeignKey, UniqueConstraint
1.2 External Index Detection
Before scoring DB2 as "zero indexes", scan for indexes defined outside the ORM:
- SQL scripts with
CREATE INDEX outside migration directories
- MongoDB shell scripts with
createIndex or ensureIndex
- Standalone index management files
If found, inventory those indexes and add a DB2.10 finding: indexes managed
outside ORM/migrations are not reproducible on fresh environments.
1.3 Migration Analysis (DB6)
Read the last 10 migration files and flag:
CREATE INDEX without CONCURRENTLY (PostgreSQL)
ALTER COLUMN SET NOT NULL without prior default
ALTER COLUMN TYPE (type changes on populated tables)
DROP COLUMN or DROP TABLE without soft-delete strategy
- Missing down/reverse migration (except Prisma, which is forward-only by design)
1.4 Model Inventory Output
MODEL INVENTORY
| Model | Fields | Relations | Indexes | Uniques | Issues |
|-------|--------|-----------|---------|---------|--------|
| User | 12 | 3 | 2 | 1 | Missing FK index on orgId |
| Order | 18 | 5 | 1 | 0 | No unique for idempotency |
Phase 2: Code-Level Analysis (DB1-DB13)
2.0 CodeSift Pre-Scan
Before dispatching agents or running manual analysis, run these automated checks when CodeSift is available. They replace ~20 manual Grep calls and provide TOOL-VERIFIED findings.
2.0a — Generic anti-pattern scans
# DB1: N+1 and unbounded query detection (automated)
search_patterns(pattern="unbounded-findmany") # findMany without take/limit
search_patterns(pattern="await-in-loop") # sequential await in loop = N+1
# DB5: Race condition pre-scan
search_patterns(pattern="toctou") # read-then-write without atomic op
# DB12: Secret exposure (hidden tool — reveal first)
# Claude Code: ToolSearch("select:mcp__codesift__scan_secrets")
# Codex/other: describe_tools(names=["scan_secrets"], reveal=true)
scan_secrets(min_confidence="medium") # hardcoded DB passwords, connection strings
If scan_secrets is unavailable, fall back to: Grep for password=, DATABASE_URL=, connection_string, API keys in .env committed to git.
2.0b — SQL composite audit (sql_audit) — MANDATORY when .sql files exist
REQUIRED CALL. If find TARGET_ROOT -name "*.sql" -not -path "*/node_modules/*" returns ≥1 file, you MUST call sql_audit in this phase. There is no condition under which "skipped" is acceptable on a .sql-bearing repo: not "no diff vs prior", not "DEFERRED", not "low risk this run". The 5 internal gates are independent of delta — they re-run every time and re-validate the schema↔ORM mapping from scratch. Skipping = audit invalid (see MANDATORY TOOL CALLS section above).
# Claude Code: ToolSearch("select:mcp__codesift__sql_audit")
# Codex/other: describe_tools(names=["sql_audit"], reveal=true)
sql_audit() # runs all 5 gates: drift, orphan, lint, dml, complexity
Map each gate to the corresponding DB dimension:
| sql_audit gate |
Maps to |
What it catches |
drift |
DB13 (migration deploy safety) |
Prisma↔SQL field/type mismatches — "forgot to run migration" bugs |
orphan |
DB3 (schema design) |
Tables defined in SQL with zero references in code or ORM |
lint |
DB2 + DB3 |
Missing PK, wide tables (>20 cols), duplicate index names |
dml |
DB12 (DB security) |
DELETE/UPDATE without WHERE (data loss), SELECT * (unbounded) |
complexity |
DB3 (schema design) |
God tables: column count + FK count + index count score ≥25 |
For finer control, run a subset of gates: sql_audit({ checks: ["drift", "dml"] }).
The sql_audit result has shape:
{
"gates": [
{ "check": "drift", "pass": false, "critical": true, "finding_count": 3, "summary": "3 drifts: 2 extra in ORM, 0 extra in SQL, 1 type mismatches", "data": {...} },
{ "check": "orphan", "pass": true, ... },
...
],
"summary": { "total_findings": 12, "critical_findings": 1, "gates_run": 5, "gates_passed": 2, "gates_failed": 3 }
}
Pass each gate's findings to the corresponding DB dimension scoring as TOOL-VERIFIED evidence. Critical gates (drift with type_mismatches > 0, dml with high-severity findings) propagate to the matching DB critical gate (DB13, DB12).
If sql_audit is unavailable (CodeSift older than v0.4.x or no .sql files), skip 2.0b and rely on the manual schema/migration analysis in Phase 1 + agent dispatch.
2.0c — Additional SQL query tools (optional)
When deeper investigation is needed for specific findings:
| Tool |
When to use |
analyze_schema |
Generate ERD (Mermaid) for the executive summary section |
trace_query(table) |
MANDATORY for every "orphan" finding from sql_audit and every table cited in HIGH/MEDIUM findings — verify zero references across .ts/.py/.go/.kt/Prisma/Drizzle |
search_columns(query) |
MANDATORY for DB12 PII discovery — find all email/password/ssn/token/secret/hash columns. Run with empty query first to inventory PII surface, then targeted queries for specific concerns. |
diff_migrations |
MANDATORY when migrations/ exists — DB6/DB13 destructive op classification. Reports additive/modifying/destructive counts. Now in MANDATORY TOOL CALLS section above. |
analyze_schema(output_format='mermaid') |
MANDATORY when .sql exists — DB3 schema inventory + ERD for executive summary. |
explain_query(code='prisma.<model>.<call>(...)') |
MANDATORY for every Prisma query cited in HIGH/MEDIUM finding — DB1/DB2 simulated EXPLAIN ANALYZE catches N+1 from include, unbounded findMany, missing indexes that sql_audit cannot see (Prisma-only). |
Previously these were "drill down only" — promoted to mandatory after the 2026-05-04 audit on tgm-survey-platform showed sql_audit alone misses ~30% of issues that surface when paired with diff_migrations + analyze_schema + trace_query.
If CodeSift is entirely unavailable, skip Phase 2.0 and proceed directly to Agent Dispatch — agents will use Grep/Read.
Collect results from 2.0a + 2.0b. Pass them into agent prompts as "pre-verified findings" (HIGH confidence, tool-verified). Agents should NOT re-scan for these patterns — they should verify context and discover patterns the automated scan missed.
Agent Dispatch
Refer to env-compat.md for the dispatch pattern.
When parallel dispatch is available:
| Agent |
Dimensions |
Focus |
| Schema Analyst |
DB2, DB3, DB6, DB13 |
Schema design + migration safety + deploy safety |
| Query Scanner |
DB1, DB5, DB8, DB9 |
Code-level query patterns |
| Infrastructure Auditor |
DB4, DB7, DB10, DB11, DB12 |
Connections, cache, observability, security |
Agent prompt rules:
- CodeSift tool loading — include this block at the very top of every agent prompt so tools are callable:
FIRST: Load CodeSift tools before doing anything else.
- Claude Code: Run ToolSearch("select:mcp__codesift__search_text,mcp__codesift__search_symbols,mcp__codesift__codebase_retrieval,mcp__codesift__trace_route,mcp__codesift__find_references,mcp__codesift__get_file_outline,mcp__codesift__trace_call_chain,mcp__codesift__search_patterns,mcp__codesift__assemble_context")
- Codex: Call mcp__codesift__search_text directly — MCP tools are pre-registered.
- Cursor/Antigravity: CodeSift unavailable — use Grep/Read.
If any tool call fails, fall back to Grep/Read.
Adjust the tool list per agent role — Schema Analyst needs get_file_outline + search_symbols + sql_audit + analyze_schema + search_columns; Query Scanner needs trace_route + codebase_retrieval + search_patterns + trace_query; Infrastructure Auditor needs search_text + find_references + diff_migrations (for DB13 destructive op review).
- Token budget: Each agent must keep its report under 800 words. Structured as: findings list (ID, severity, file:line, 1-sentence description) + 1-paragraph summary. No prose explanations per finding.
- CodeSift cheat sheet — include right after the tool loading block:
CodeSift: batch 3+ searches → codebase_retrieval(queries=[...]).
Endpoints → trace_route first. Skip list_repos (auto-resolve).
If empty results → fallback to Grep (parser may be unavailable).
- Pre-verified findings: Pass Phase 2.0 results to agents with instruction: "These findings are TOOL-VERIFIED. Do not re-scan for them. Focus on patterns the pre-scan cannot catch."
Without parallel dispatch: Execute all dimensions sequentially.
DB1: Query Patterns -- Weight 15, Max 15, Critical Gate
| Check |
Good |
Bad |
Severity |
| N+1 queries |
Eager loading (include, joinedload), batched IDs |
findMany / find inside a loop |
CRITICAL |
| Select efficiency |
select only needed fields |
SELECT * / no select clause |
HIGH |
| Bulk operations |
createMany, updateMany, bulk insert |
Individual create/update in loop |
HIGH |
| Raw query safety |
Parameterized queries ($queryRaw with template, %s params) |
String concatenation in SQL |
CRITICAL |
Critical gate: DB1=0 (N+1 in hot path) triggers audit FAIL.
DB2: Index Strategy -- Weight 15, Max 15
| Check |
Good |
Bad |
Severity |
| FK indexes |
Every foreign key has an index |
FK columns without index |
HIGH |
| Composite indexes |
Multi-column indexes for common query patterns |
Single-column indexes on individually queried fields |
MEDIUM |
| Covering indexes |
Index includes all fields for frequent queries |
Extra lookups required |
LOW |
| Unused indexes |
All indexes serve active queries |
Indexes that are never hit |
MEDIUM |
DB3: Schema Design -- Weight 8, Max 8
| Check |
Good |
Bad |
Severity |
| Normalization |
Appropriate normal form, no data duplication |
Same data stored in multiple tables |
HIGH |
| Enum usage |
Database enums or constrained strings for status/type |
Arbitrary strings without validation |
MEDIUM |
| Timestamps |
createdAt/updatedAt on mutable models, deletedAt for soft delete |
No audit trail |
MEDIUM |
| Naming conventions |
Consistent naming (snake_case or camelCase), clear foreign key names |
Mixed conventions, ambiguous names |
LOW |
DB4: Connection Management -- Weight 10, Max 10, Critical Gate
| Check |
Good |
Bad |
Severity |
| Connection pooling |
Pool configured with min/max, singleton client |
New client per request |
CRITICAL |
| Serverless awareness |
External pooler (PgBouncer, Supabase pooler) for serverless |
Direct connection from Lambda/Worker |
CRITICAL |
| Connection limits |
Pool size matches deployment (serverless: small, container: tuned) |
Default unlimited |
HIGH |
| Client instantiation |
Single PrismaClient/DataSource instance |
Multiple new PrismaClient() calls |
HIGH |
Critical gate: DB4=0 (no pooling) triggers audit FAIL.
DB5: Transaction Safety -- Weight 12, Max 12, Critical Gate
| Check |
Good |
Bad |
Severity |
| Multi-table mutations |
Wrapped in transaction |
Separate writes without transaction |
CRITICAL |
| Transaction scope |
Minimal scope, no external API calls inside |
HTTP request or email send inside transaction |
HIGH |
| Rollback handling |
Explicit error handling, compensation logic |
Silent swallow on transaction failure |
HIGH |
| Deadlock prevention |
Consistent lock ordering, timeout on transactions |
Arbitrary ordering, no timeout |
MEDIUM |
Critical gate: DB5=0 (multi-table mutations without transaction) triggers FAIL.
DB6: Migration Safety -- Weight 8, Max 8
| Check |
Good |
Bad |
Severity |
| Non-blocking DDL |
CREATE INDEX CONCURRENTLY, ADD COLUMN with default |
Locking index creation on large table |
HIGH |
| Data migration |
Separate data migration from schema migration |
Mixed DDL and DML in one migration |
MEDIUM |
| Reversibility |
Down migrations exist and tested (non-Prisma ORMs) |
No rollback path |
MEDIUM |
| Type changes |
Multi-step migration for type changes (add new, migrate, drop old) |
Direct ALTER TYPE on populated column |
HIGH |
DB7: Caching Layer -- Weight 8, Max 8
| Check |
Good |
Bad |
Severity |
| Query result cache |
Redis/Memcached for expensive/repeated queries, TTL configured |
Every request hits database |
HIGH |
| Cache invalidation |
Event-driven or TTL with jitter |
Manual invalidation, no TTL |
MEDIUM |
| Cache-aside pattern |
Read-through with fallback to DB on miss |
All-or-nothing cache (miss = error) |
MEDIUM |
| Cache key design |
Includes tenant/org scope, versioned |
Global keys, no scoping |
MEDIUM |
DB8: Query Optimization -- Weight 10, Max 10
| Check |
Good |
Bad |
Severity |
| Pagination |
Cursor-based for large datasets, keyset pagination |
OFFSET pagination on growing table |
HIGH |
| LIKE queries |
Prefix match only, full-text search for complex needs |
%term% LIKE on unindexed column |
MEDIUM |
| Function on column |
Avoid function calls on indexed columns in WHERE |
WHERE LOWER(email) = ... (defeats index) |
MEDIUM |
| Sorting |
Sort on indexed column |
Sort on computed/unindexed column for large result |
MEDIUM |
DB9: ORM-Specific Anti-Patterns -- Weight 6, Max 6
Patterns vary by detected ORM:
Prisma: $queryRawUnsafe, missing select on deep includes, findMany
without take, $transaction with long-running operations.
TypeORM: Lazy relations without awareness, find() without select,
QueryBuilder without parameter binding.
Django: N+1 via object.related_set.all() without select_related/
prefetch_related, .count() on unevaluated queryset.
SQLAlchemy: Lazy loading N+1, session.query() without limit, missing
yield_per for large result sets.
DB10: Observability -- Weight 4, Max 4
| Check |
Good |
Bad |
Severity |
| Query logging |
Structured logging with query duration, parameterized |
No query logging in production |
MEDIUM |
| Slow query alerting |
Threshold-based alerts (> 1s), dashboard |
No monitoring for slow queries |
MEDIUM |
| Connection metrics |
Pool utilization tracked, alerts on exhaustion |
No visibility into connection state |
LOW |
DB11: Data Lifecycle -- Weight 4, Max 4
| Check |
Good |
Bad |
Severity |
| Archival strategy |
Old data archived or partitioned |
Unbounded table growth |
MEDIUM |
| Batch processing |
Batch deletes/updates with limits, off-peak scheduling |
Full-table operations during peak hours |
MEDIUM |
| Soft delete |
deletedAt pattern with default scope excluding deleted |
Hard delete without audit trail |
LOW |
DB12: Database Security -- Weight 4, Max 4, Critical Gate
| Check |
Good |
Bad |
Severity |
| SQL injection |
All queries parameterized, no string concatenation |
$queryRawUnsafe or string-built SQL |
CRITICAL |
| Least privilege |
Application user has minimal permissions |
App connects as superuser |
HIGH |
| Connection encryption |
SSL/TLS required in connection string |
Plaintext database connection |
HIGH |
| Sensitive data |
PII encrypted at rest, column-level encryption for secrets |
Plaintext passwords or tokens in DB |
CRITICAL |
Critical gate: DB12=0 (SQL injection) triggers audit FAIL.
DB13: Migration Deployment Safety -- Weight 8, Max 8
Goes beyond DB6 (migration code quality) to assess whether migrations can be deployed safely to a running production system.
| Check |
Good |
Bad |
Severity |
| Destructive operations |
DROP COLUMN/DROP TABLE preceded by deprecation migration, data backed up |
Direct DROP on populated columns without prior migration to remove usage |
CRITICAL |
| Lock duration estimation |
Short-lived locks: ADD COLUMN with default (PG 11+), CREATE INDEX CONCURRENTLY |
ALTER TABLE operations that acquire ACCESS EXCLUSIVE lock on large tables (>100K rows) |
CRITICAL |
| Rollback plan |
Down migration exists and tested, or forward-fix strategy documented |
No rollback path — failed migration leaves DB in inconsistent state |
HIGH |
| Data loss risk |
NOT NULL additions have DEFAULT value, type changes preserve data |
ALTER COLUMN SET NOT NULL without default on populated table, truncating type changes |
CRITICAL |
| Backward compatibility |
New columns nullable or with defaults (old app version still works), rename = add+copy+drop |
Column renames or type changes that break currently-deployed app code |
HIGH |
| Idempotency |
Migrations use IF NOT EXISTS, IF EXISTS guards |
Migrations fail on re-run (no idempotency — partial failure leaves broken state) |
HIGH |
| Migration ordering |
Migrations numbered/timestamped, no conflicts in team branches |
Multiple migrations with same timestamp, or migrations that depend on unapplied predecessors |
MEDIUM |
| Long-running DML |
Data backfills use batched updates with LIMIT and sleep between batches |
Single UPDATE on millions of rows (locks table, blocks queries, risks timeout) |
HIGH |
| Connection impact |
Migration runs outside connection pool, or uses dedicated migration connection |
Migration runs through application pool, potentially exhausting connections during deploy |
MEDIUM |
| Zero-downtime readiness |
Migration + app deploy order documented, blue-green or rolling deploy compatible |
Migration requires app downtime — schema and app must change simultaneously |
HIGH |
How to audit:
- Read all migration files in the migrations directory (last 20 if >20 exist)
- For each migration, classify operations:
- SAFE:
ADD COLUMN (nullable or with default), CREATE TABLE, CREATE INDEX CONCURRENTLY
- CAUTION:
ADD COLUMN NOT NULL with default (PG 11+ safe, older = table rewrite), ALTER COLUMN SET DEFAULT
- DANGEROUS:
DROP COLUMN, DROP TABLE, ALTER COLUMN TYPE, ALTER COLUMN SET NOT NULL without default
- BLOCKING:
CREATE INDEX without CONCURRENTLY, ALTER TABLE on large table without estimated lock time
- For DANGEROUS/BLOCKING operations, check:
- Is there a prior migration removing code references to dropped columns?
- Is there a rollback migration?
- Is the table large enough to cause lock contention (estimate from schema relations)?
- Check deployment documentation for migration strategy
Scoring:
- 0 DANGEROUS ops without safeguards = 8/8
- Each unguarded DANGEROUS op: -2
- Each BLOCKING op without CONCURRENTLY: -1
- No rollback path for any destructive migration: -2
- No idempotency guards: -1
N/A: If no migration files found, DB13=N/A.
Phase 3: Live Analysis (optional --live)
Skip unless --live <conn> was provided. Requires database client access.
Supported engines: PostgreSQL (full), MySQL (p
…(truncated)
1---
2name: db-audit
3description: >
4 Database performance and safety audit. 70+ checks across 13 dimensions
5 (DB1-DB13): query patterns, indexes, schema design, connections, transactions,
6 migrations, caching, query optimization, ORM anti-patterns, observability,
7 data lifecycle, DB security, and migration deployment safety. Code-level checks for all ORMs. Optional
8 live analysis via PostgreSQL or MySQL connection.
9 Switches: zuvo:db-audit full | [path] | [file] | --schema | --queries | --connections | --live <conn>
10codesift_tools:
11 always:
12 - analyze_project
13 - index_status
14 - index_folder
15 - index_file
16 - plan_turn
17 - search_patterns # KEY — n-plus-one-django, missing-index, raw-sql
18 - audit_scan
19 - get_file_tree # find migrations/, schema files
20 - get_file_outline
21 - search_text # SQL string scans
22 - search_symbols # repository / DAO / Model classes
23 - get_symbol
24 - get_symbols
25 - find_references # who calls this query
26 - trace_call_chain
27 by_stack:
28 typescript: [get_type_info]
29 javascript: []
30 python: [python_audit, analyze_async_correctness]
31 php: [php_project_audit, php_security_scan]
32 kotlin: [analyze_sealed_hierarchy, find_extension_functions, trace_flow_chain, trace_suspend_chain, trace_compose_tree, analyze_compose_recomposition, trace_hilt_graph, trace_room_schema, analyze_kmp_declarations, extract_kotlin_serialization_contract]
33 nestjs: [nest_audit]
34 nextjs: [framework_audit, nextjs_route_map]
35 astro: [astro_audit, astro_actions_audit, astro_hydration_audit]
36 hono: [analyze_hono_app, audit_hono_security]
37 express: []
38 fastify: []
39 react: [react_quickstart, analyze_hooks, analyze_renders]
40 django: [analyze_django_settings, effective_django_view_security, taint_trace, get_model_graph]
41 fastapi: [trace_fastapi_depends, get_pydantic_models]
42 flask: [find_framework_wiring]
43 jest: []
44 yii: [resolve_php_service]
45 # ORMs / databases — full SQL toolchain (verified 2026-05-04: each tool catches what others miss)
46 prisma:
47 - analyze_prisma_schema # FK index coverage, soft-delete, status-as-String warnings
48 - explain_query # KEY — Prisma→EXPLAIN ANALYZE: unbounded queries, N+1, missing indexes
49 drizzle: []
50 sql:
51 - sql_audit # composite: 5 gates (drift, orphan, lint, dml, complexity)
52 - analyze_schema # tables/columns/FKs/relations → ERD for executive summary
53 - diff_migrations # classify ops: additive/modifying/destructive (deploy risk)
54 - trace_query # cross-codebase table-ref tracing (DDL, DML, FK, ORM)
55 - search_columns # find columns by name/type — PII discovery (DB12)
56 postgres:
57 - migration_lint # squawk PG migration safety (30+ patterns: NOT NULL no default, etc.)
58metadata:
59 source: https://skillmd.com/skills/aibot88/db-audit
60---
61
62# zuvo:db-audit
63
64Audit database interactions from code patterns through schema design to live
65query plans. Produces a scored report with specific, actionable fixes ranked by
66impact and effort.
67
68**When to use:** Before releases, after adding models or queries, when latency
69increases, after scaling incidents, periodic health check.
70**When NOT to use:** Code quality (`zuvo:review`), full-stack performance
71(`zuvo:performance-audit`), security-only (`/security-audit`).
72
73## Mandatory File Loading
74
75Read every file below before starting. Print the checklist.
76
77```
78CORE FILES LOADED:
79 1. ../../shared/includes/codesift-setup.md -- [READ | MISSING -> STOP]
80 2. ../../shared/includes/env-compat.md -- [READ | MISSING -> STOP]
81 3. ../../shared/includes/run-logger.md -- [READ | MISSING -> STOP]
82```
83
84**Deferred (lazy load):**
85
86```
87DEFERRED FILES (read only when needed):
88 - ../../shared/includes/retrospective.md -- read right before Phase 6 (saves ~3K tokens during audit)
89```
90
91Note: `cq-patterns.md` is NOT loaded — this is a read-only audit, not a code quality review. Loading it wastes ~7K tokens per turn.
92
93If any CORE file is MISSING, STOP. Do not proceed from memory.
94
95---
96
97## MANDATORY TOOL CALLS — Audit Validity Gate
98
99**This audit is INVALID if any of the tools below are skipped when their trigger condition holds.** "DEFERRED", "N/A", "no diff vs prior audit" are NOT valid reasons. The presence of trigger artifacts (migrations directory, .sql files, ORM schema, etc.) is what dictates the call — not whether they changed since the last audit.
100
101### Required tool list
102
103| Tool | Trigger | Reason | Skip allowed? |
104|------|---------|--------|---------------|
105| `sql_audit` | Project has any `.sql` file (migrations, schema, dumps) anywhere under `TARGET_ROOT` | DB6/DB12/DB13 — bundles 5 gates (drift, orphan, lint, dml, complexity) that no manual scan reproduces | **NO** — audit FAILS if skipped while trigger holds |
106| `analyze_schema` | Same as `sql_audit` (`.sql` files exist) | DB3 schema design — extracts tables/columns/FKs/relationships, generates ERD for executive summary | **NO** when `.sql` exists |
107| `diff_migrations` | `migrations/` dir exists (any ORM/framework) | DB6/DB13 deployment safety — classifies every op as additive/modifying/destructive with risk ranking; surfaces destructive ops missed by `sql_audit lint` gate | **NO** when migrations exist |
108| `trace_query` | At least one HIGH/MEDIUM finding mentions a table OR `sql_audit orphan` gate flags any orphan | DB3/DB13 verification — confirms zero references for "orphan" claim and traces every cited table across DDL/DML/FK/ORM (Prisma + Drizzle) | **NO** when condition holds |
109| `search_columns` | Always | DB12 PII discovery — find every `email`/`password`/`ssn`/`token` column across all tables | **NO** — always required |
110| `migration_lint` | Postgres detected (any of: `pg`, `psycopg2`, `@prisma/adapter-pg`, `postgres-js` in deps) AND `migrations/` dir exists | DB13 migration deployment safety (squawk: 30+ PG-specific patterns including `NOT NULL` without default, `CREATE INDEX` without `CONCURRENTLY`, etc.) | **NO** when both conditions hold |
111| `analyze_prisma_schema` | `prisma/schema.prisma` exists | DB2/DB3/DB6 Prisma-specific schema gates (FK index coverage %, unindexed FKs, soft-delete detection, `status: String` smell) | **NO** when schema exists |
112| `explain_query` | Prisma project AND any HIGH/MEDIUM finding cites a `prisma.<model>.<call>` query | DB1/DB2 Prisma-specific N+1 + missing-index detection via simulated EXPLAIN ANALYZE; finds risks `sql_audit dml` cannot see | **NO** when condition holds |
113| `python_audit` | Language detected as Python | DB1 N+1 detection (`n-plus-one-django` pattern), DB9 ORM anti-patterns | **NO** when Python project |
114| `nest_audit` | Framework detected as NestJS (`@nestjs/*` in deps) | DB1/DB4 NestJS DI + repository scoping issues | **NO** when NestJS project |
115| `analyze_django_settings` + `get_model_graph` | `django` in pyproject/requirements | DB6 Django migration safety, DB3 model graph | **NO** when Django |
116| `scan_secrets` | Always | DB12 hardcoded credentials in code or `.env` | **NO** — always required |
117| `search_patterns(pattern="unbounded-findmany")` + `search_patterns(pattern="await-in-loop")` + `search_patterns(pattern="toctou")` | Always | DB1/DB5 — these are the ONLY tool-verified gates for those patterns | **NO** — always required |
118
119### Pre-flight check (run BEFORE any phase)
120
121Before Phase 0, verify the required tools are reachable:
122
123```
124# Detect triggers
125sql_files=$(find TARGET_ROOT -name "*.sql" -not -path "*/node_modules/*" -not -path "*/.git/*" | head -1)
126migrations_dir=$(find TARGET_ROOT -type d -name "migrations" -not -path "*/node_modules/*" | head -1)
127prisma_schema=$([ -f TARGET_ROOT/prisma/schema.prisma ] && echo "yes" || echo "no")
128```
129
130For each trigger that holds, confirm the matching tool is in the preloaded tool list (from `codesift-setup.md` Step 2.5 ToolSearch). If a required tool is NOT in the list and is also NOT in the deferred-tools banner:
131- Print `[ABORT] Required tool '<name>' not reachable. db-audit cannot produce a valid report without it.`
132- Do NOT proceed with grep fallback. The audit is incomplete by definition.
133- Exit with status `INCOMPLETE` and add a backlog item: `[BLOCKER] db-audit needs <tool> on <project>`.
134
135### Required POSTAMBLE — retrospective append (NOT optional)
136
137After the audit report is written and the Run line is appended, **the audit is NOT complete until** the retrospective protocol has appended an entry to BOTH `~/.zuvo/retros.log` AND `~/.zuvo/retros.md`. Reaching the Run line is **not** the end of the skill — it is the midpoint between findings-output and process-feedback.
138
139This is the failure mode the 2026-04-09 → 2026-05-04 db-audit history shows: 11 db-audit runs, 0 retrospective entries written. Every prior run reached the Run line, declared "task done", and skipped retrospective.md entirely. The skipped retros lost ~11 sessions of skill feedback that would otherwise have caught the very issues this MANDATORY section now enforces.
140
141**Hard requirement, in this order, before considering db-audit complete:**
142
1431. Write `audits/db-audit-<date>.md`.
1442. Print Validity Gate block.
1453. Print Run line + append to runs.log.
1464. **Load `../../shared/includes/retrospective.md` if not already loaded.**
1475. **Fill all 9 retrospective fields per protocol.**
1486. **Execute the bash append commands** that write `RETRO:` line to `~/.zuvo/retros.log` and the long-form entry to `~/.zuvo/retros.md`.
1497. **Print confirmation:** `RETRO_APPENDED: retros.log=YES retros.md=YES (verified)`.
150
151If you reach step 3 and stop — the audit is INVALID regardless of finding count. The Validity Gate's `gate_status` flips to `FAIL — retrospective not appended` and the verdict is overridden to `INCOMPLETE`.
152
153### Forbidden escape hatches
154
155The following telemetry values are **forbidden** when the trigger condition holds:
156
157| Value | Forbidden when | Required value instead |
158|-------|----------------|------------------------|
159| `sql_audit: DEFERRED` | `.sql` files exist | `sql_audit: <gates_passed>/<gates_run>` |
160| `sql_audit: N/A` | `.sql` files exist | (same as above) |
161| `sql_audit: skipped (no diff vs prior)` | EVER | (same as above — trigger is presence, not delta) |
162| `migration_lint: DEFERRED` | Postgres + migrations exist | `migration_lint: <findings>` |
163| `scan_secrets: DEFERRED` | EVER | `scan_secrets: <count>` |
164| `codesift: unavailable` | `mcp__codesift__*` was in deferred-tools session-start banner | `codesift: deferred-not-preloaded (FAILURE: skill required preload)` |
165| `retrospective: skipped` | EVER | `retrospective: appended (retros.log=N entries, retros.md=N bytes added)` — see Required POSTAMBLE above |
166| Stopping after Run line without retrospective | EVER | Not allowed — the Validity Gate catches this and overrides to INCOMPLETE |
167
168### Audit completion verification (run BEFORE writing PASS/WARN/FAIL status)
169
170At the end of the audit, before emitting the status block:
171
1721. Re-check each trigger condition.
1732. For each held trigger, verify the corresponding tool was actually called in this session (the LLM must self-report honestly — there is no automated post-execution gate yet, so use the run log as ground truth).
1743. If ANY required tool is missing for a held trigger:
175 - Override the verdict to `INCOMPLETE` regardless of finding count.
176 - Print: `[VALIDITY GATE FAIL] <tool> required by <trigger>, not called. Audit cannot be trusted.`
177 - Add the gap to the backlog as `B-db-audit-incomplete-<date>`.
178
179A db-audit that says "0 critical findings" while skipping `sql_audit` on a project with 34 migrations is **lying**, not passing. The completion gate exists to catch that.
180
181---
182
183## Argument Parsing
184
185| Token | Behavior |
186|-------|----------|
187| _(empty)_ or `full` | All 13 dimensions across the project (auto-decides mode in Phase 0.4) |
188| `[path]` | Scope to a directory or module |
189| `[file]` | Deep audit of a single file (all applicable dimensions) |
190| `--schema` | Schema analysis only (DB2, DB3, DB6) |
191| `--queries` | Query pattern analysis only (DB1, DB8, DB9) |
192| `--connections` | Connection and pool management only (DB4) |
193| `--live <conn>` | Enable Phase 3: connect to the database for EXPLAIN and statistics |
194| `--force-full` | Skip audit mode decision in Phase 0.4 — always run full audit even if a recent prior audit exists |
195| `--delta` | Force delta mode (only allowed if commits_since < 5 AND hours_since < 4 — see Phase 0.4) |
196
197---
198
199## Safety Gates
200
201### GATE 1 -- Read-Only
202
203This audit is **read-only**. The only write target is `audits/`.
204
205FORBIDDEN:
206- Running any migration
207- Modifying schema files, model files, or ORM configuration
208- Executing INSERT/UPDATE/DELETE against any database
209- Modifying connection strings or pool settings
210
211### GATE 2 -- Live Mode Scoping
212
213When `--live <conn>` is used:
214- Only SELECT and EXPLAIN queries are permitted
215- No DDL (CREATE, ALTER, DROP)
216- No DML (INSERT, UPDATE, DELETE)
217- Connection must be read-only if the database supports read replicas
218
219---
220
221## Phase 0: Detect and Prepare
222
223### 0.0 CodeSift Capability Check
224
225If CodeSift MCP is available, run these two calls before anything else:
226
2271. `get_extractor_versions()` — check if the project's primary language has a full parser (symbol-level tools) or only text-stub support. If text-stub only: skip all symbol-based CodeSift calls (search_symbols, get_file_outline, trace_call_chain, find_references) and use Grep/Read fallbacks instead. Print the result.
2282. `analyze_project()` — returns detected stack (framework, language, package manager, monorepo), file classifications, dependency counts, and git health. Use the output to pre-fill ORM, Engine, and Deployment detection below instead of manual file scanning.
229
230If `analyze_project` returns enough to populate the stack table, skip 0.1/0.2/0.3 manual detection and jump to the output block. If it returns partial data (e.g. framework=null), fill the gaps with the manual tables below.
231
232### 0.1 ORM Detection
233
234If not resolved by `analyze_project`:
235
236| Signal | ORM |
237|--------|-----|
238| `prisma/schema.prisma` | Prisma |
239| `ormconfig.*` or `DataSource` import | TypeORM |
240| `drizzle.config.*` | Drizzle |
241| `.sequelizerc` or `sequelize` in deps | Sequelize |
242| `knexfile.*` or `knex` in deps | Knex |
243| `settings.py` with `DATABASES` | Django ORM |
244| `sqlalchemy` in requirements | SQLAlchemy |
245| Raw `pg`/`mysql2` without ORM | Raw SQL client |
246
247### 0.2 Database Engine Detection
248
249If not resolved by `analyze_project`:
250
251| Signal | Engine | Managed provider |
252|--------|--------|------------------|
253| `postgresql` in connection string or schema provider | PostgreSQL | — |
254| `mysql` in connection string or provider | MySQL | — |
255| `sqlite` in provider | SQLite | — |
256| `mongodb` in provider or `mongoose` | MongoDB | — |
257| `neon.tech` in DATABASE_URL | PostgreSQL | **Neon** (built-in pooler) |
258| `supabase.co` in DATABASE_URL | PostgreSQL | **Supabase** (built-in pooler) |
259| `pscale.sh` or `psdb.cloud` | MySQL | **PlanetScale** (built-in pooler) |
260| `cockroachlabs.cloud` | CockroachDB | **Cockroach Cloud** (built-in pooler) |
261| `rds.amazonaws.com` | PostgreSQL/MySQL | **AWS RDS** |
262| `azure.com` with `database` segment | PostgreSQL/MySQL/SQL Server | **Azure Database** |
263| `googleapis.com` with `cloudsql` | PostgreSQL/MySQL | **Cloud SQL** |
264| `mongodb.net` | MongoDB | **MongoDB Atlas** |
265
266**Managed provider note:** When a managed provider with built-in pooling is detected (Neon, Supabase, PlanetScale, Cockroach Cloud), DB4 should NOT be marked critical-fail for "no PgBouncer config" — the platform handles pooling. Mark these findings as TOOL-VERIFIED with note "managed pooling: <provider>" and pass DB4 if no other issues exist.
267
268### 0.3 Deployment Detection
269
270If not resolved by `analyze_project`:
271
272| Signal | Type |
273|--------|------|
274| `vercel.json`, `netlify.toml` | Serverless (Vercel/Netlify) |
275| `wrangler.toml` | Serverless (Cloudflare Workers) |
276| `serverless.yml` | Serverless (AWS Lambda) |
277| `Dockerfile`, `docker-compose` | Containerized |
278| None of above | Traditional |
279
280Print detection results:
281
282```
283DB AUDIT STACK
284------------------------------------
285ORM: [Prisma / TypeORM / Drizzle / Django / SQLAlchemy / Raw SQL]
286Engine: [PostgreSQL / MySQL / SQLite / MongoDB]
287Deploy: [Serverless / Container / Traditional]
288Scope: [full / path / file]
289Dims: [DB1-DB13 / subset]
290CodeSift: [full-parser / text-stub / unavailable]
291------------------------------------
292```
293
294### 0.4 Audit Mode Decision
295
296**Default mode is `full`.** Delta mode is a narrow exception, NOT a shortcut.
297
298If `--force-full` was passed: `mode = "full"` — skip the rest of this section.
299
300Otherwise, look for the most recent prior audit at `audits/db-audit-*.md`:
301
302```bash
303PRIOR_AUDIT=$(ls -t audits/db-audit-*.md 2>/dev/null | head -1)
304
305if [ -z "$PRIOR_AUDIT" ]; then
306 mode="full" # baseline
307else
308 PRIOR_SHA=$(grep -E '^\| HEAD_SHA' "$PRIOR_AUDIT" | head -1 | awk '{print $NF}')
309 PRIOR_MTIME=$(stat -f %m "$PRIOR_AUDIT" 2>/dev/null || stat -c %Y "$PRIOR_AUDIT")
310 NOW=$(date +%s)
311 HOURS_SINCE=$(( (NOW - PRIOR_MTIME) / 3600 ))
312 COMMITS_SINCE=$(git rev-list --count "${PRIOR_SHA}..HEAD" 2>/dev/null || echo 999)
313
314 if [ "$COMMITS_SINCE" -eq 0 ] && [ "$HOURS_SINCE" -lt 2 ]; then
315 mode="sanity-check"
316 elif [ "$COMMITS_SINCE" -lt 5 ] && [ "$HOURS_SINCE" -lt 4 ]; then
317 mode="delta"
318 else
319 mode="full"
320 fi
321fi
322```
323
324| Mode | When | What it does |
325|------|------|--------------|
326| `full` | No prior audit, OR commits_since ≥ 5, OR hours_since ≥ 4, OR `--force-full` | Independent re-evaluation of all dimensions. Default. |
327| `delta` | commits_since < 5 AND hours_since < 4 AND prior audit exists | Verify prior findings + scan changed files only. **Requires Phase 0.5 checklist.** |
328| `sanity-check` | commits_since == 0 AND hours_since < 2 | Spot-verify 1-2 specific fixes. Not a full audit. |
329
330If user passed `--delta` but the conditions for delta are not met: print a warning and override to `full`. Do NOT silently honor the flag — the user's "I want delta" is overridden by methodology safety.
331
332### CRITICAL — Mode does NOT affect MANDATORY TOOL CALLS
333
334Mode (full / delta / sanity-check) controls **scope of additional analysis** — which dimensions get deep-dived, which agent-dispatched explorations run, how many findings are re-examined. Mode does **NOT** waive any tool from the MANDATORY TOOL CALLS section above.
335
336Specifically, in EVERY mode (including `delta` and `sanity-check`):
337
338- `sql_audit` MUST run if any `.sql` file exists.
339- `analyze_schema` MUST run if any `.sql` file exists (companion to sql_audit — generates ERD).
340- `diff_migrations` MUST run if `migrations/` dir exists (classifies destructive ops).
341- `search_columns` MUST run (PII discovery — every audit).
342- `scan_secrets` MUST run.
343- `search_patterns(unbounded-findmany | await-in-loop | toctou)` MUST run.
344- `migration_lint` MUST run if Postgres + `migrations/` dir exists.
345- `analyze_prisma_schema` MUST run if `prisma/schema.prisma` exists.
346- `explain_query` MUST run on every Prisma query cited in a HIGH/MEDIUM finding.
347- `trace_query` MUST run on every table cited in a HIGH/MEDIUM finding (or flagged by `sql_audit orphan`).
348- Stack-specific mandatory tools (nest_audit, python_audit, django/celery/etc.) MUST run when their language/framework is detected.
349
350These tools ARE the audit's validity floor — without them the report cannot be trusted regardless of how small the delta is. They are also fast (single composite calls), so "delta is too small to bother" is never a defensible reason.
351
352If you are tempted to mark any mandatory tool as `DEFERRED (delta-mode, low risk)` or `N/A (no DB changes)`: **STOP**. That is the exact failure mode this section exists to prevent. The trigger is presence of `.sql`/`migrations/`/`schema.prisma`/etc. — never delta or risk.
353
354Print the decision:
355
356```
357AUDIT MODE: [full / delta / sanity-check]
358Reason: prior=[date or "none"] | commits_since=[N] | hours_since=[N.N]
359Override: [user --force-full | user --delta accepted | user --delta REJECTED→full | none]
360Mandatory-tools-acknowledgment: I will run sql_audit + analyze_schema + diff_migrations + search_columns + scan_secrets + migration_lint (if PG) + analyze_prisma_schema (if Prisma) + search_patterns(unbounded-findmany, await-in-loop, toctou) + stack-specific mandatory tools (nest_audit/python_audit/etc. when detected) + trace_query + explain_query (on cited tables/queries) in this mode. [REQUIRED — print verbatim]
361```
362
363### 0.5 Delta Verification Checklist
364
365**Skip this section if `mode != "delta"`.**
366
367When `mode == "delta"`, you MUST complete every item below before writing the report. Any skipped item forces `mode = "full"` and restart from Phase 1.
368
369```
370DELTA VERIFICATION CHECKLIST
371[ ] git diff --name-only <prior_sha>..HEAD → list changed files (CHANGED_FILES)
372[ ] scan_secrets on CHANGED_FILES (NEVER skip, even if DB12 was 4/4 in prior)
373[ ] For every finding from prior audit:
374 → 1× codebase_retrieval batch call (do NOT iterate per-finding)
375[ ] For every severity downgrade you propose (M→L, H→M):
376 → find_references on the symbol → document the count
377 → DOWNGRADE BLOCKED without count evidence in the report
378[ ] For every endpoint mentioned in any finding:
379 → trace_route to confirm hot-path / cold-path status
380[ ] For every finding with a matching docs/specs/*-plan.md reference:
381 → tag as PLANNED (not HIGH/MEDIUM)
382```
383
384Why this checklist exists: previous delta audits inherited prior assumptions and silently propagated errors. Severity downgrades without evidence, skipped scans on changed files, and untraced endpoint claims are the four most common delta-mode failures. This checklist eliminates them.
385
386If at any point during the audit you find yourself thinking "the prior audit already covered this," STOP — that's the anchoring bias the checklist is designed to break. Run the verification.
387
388---
389
390## Phase 1: Schema Analysis
391
392**Skip if:** no schema file and no migration directory found. Mark DB2, DB3,
393DB6 as INSUFFICIENT DATA.
394
395### 1.1 Schema Inventory
396
397Read the schema source for the detected ORM and extract:
398
399| Item | What to Count |
400|------|---------------|
401| Models/tables | Total count |
402| Fields per model | Average and maximum |
403| Relations | 1:1, 1:N, N:M counts |
404| Indexes | Count per model, which fields |
405| Unique constraints | Count per model |
406| Defaults | Fields with/without default values |
407| Nullable fields | Count and distribution |
408| Enums vs string | Enum definitions vs raw string status/type fields |
409
410**CodeSift accelerated (Prisma):** When CodeSift has a Prisma parser (check Phase 0.0), use symbol-level tools instead of reading the entire schema file:
411
412```
413# Get all models, enums, and types at a glance
414get_file_outline(file_path="prisma/schema.prisma")
415
416# Search for specific model patterns
417search_symbols(query="@@index", file_pattern="*.prisma", include_source=true)
418search_symbols(query="@@unique", file_pattern="*.prisma", include_source=true)
419
420# For large schemas (>500 lines), use assemble_context instead of Read:
421assemble_context(query="prisma models with relations", level="L1", token_budget=8000)
422```
423
424This replaces reading a 500-1500 line schema file in full, saving ~5-10K tokens.
425
426**ORM-specific sources (manual fallback):**
427- **Prisma:** `prisma/schema.prisma` -- `@@index`, `@@unique`, `@default`, `?` nullable
428- **TypeORM:** Entity files -- `@Column`, `@Index`, `@JoinColumn`, `@ManyToOne`
429- **Django:** `models.py` -- `Field` types, `class Meta` indexes, `ForeignKey`
430- **Drizzle:** Schema files -- `index()`, `unique()`, `references()`
431- **SQLAlchemy:** Model files -- `Column`, `Index`, `ForeignKey`, `UniqueConstraint`
432
433### 1.2 External Index Detection
434
435Before scoring DB2 as "zero indexes", scan for indexes defined outside the ORM:
436
437- SQL scripts with `CREATE INDEX` outside migration directories
438- MongoDB shell scripts with `createIndex` or `ensureIndex`
439- Standalone index management files
440
441If found, inventory those indexes and add a DB2.10 finding: indexes managed
442outside ORM/migrations are not reproducible on fresh environments.
443
444### 1.3 Migration Analysis (DB6)
445
446Read the last 10 migration files and flag:
447- `CREATE INDEX` without `CONCURRENTLY` (PostgreSQL)
448- `ALTER COLUMN SET NOT NULL` without prior default
449- `ALTER COLUMN TYPE` (type changes on populated tables)
450- `DROP COLUMN` or `DROP TABLE` without soft-delete strategy
451- Missing down/reverse migration (except Prisma, which is forward-only by design)
452
453### 1.4 Model Inventory Output
454
455```
456MODEL INVENTORY
457| Model | Fields | Relations | Indexes | Uniques | Issues |
458|-------|--------|-----------|---------|---------|--------|
459| User | 12 | 3 | 2 | 1 | Missing FK index on orgId |
460| Order | 18 | 5 | 1 | 0 | No unique for idempotency |
461```
462
463---
464
465## Phase 2: Code-Level Analysis (DB1-DB13)
466
467### 2.0 CodeSift Pre-Scan
468
469Before dispatching agents or running manual analysis, run these automated checks when CodeSift is available. They replace ~20 manual Grep calls and provide TOOL-VERIFIED findings.
470
471#### 2.0a — Generic anti-pattern scans
472
473```
474# DB1: N+1 and unbounded query detection (automated)
475search_patterns(pattern="unbounded-findmany") # findMany without take/limit
476search_patterns(pattern="await-in-loop") # sequential await in loop = N+1
477
478# DB5: Race condition pre-scan
479search_patterns(pattern="toctou") # read-then-write without atomic op
480
481# DB12: Secret exposure (hidden tool — reveal first)
482# Claude Code: ToolSearch("select:mcp__codesift__scan_secrets")
483# Codex/other: describe_tools(names=["scan_secrets"], reveal=true)
484scan_secrets(min_confidence="medium") # hardcoded DB passwords, connection strings
485```
486
487If `scan_secrets` is unavailable, fall back to: `Grep` for `password=`, `DATABASE_URL=`, `connection_string`, API keys in `.env` committed to git.
488
489#### 2.0b — SQL composite audit (`sql_audit`) — MANDATORY when `.sql` files exist
490
491**REQUIRED CALL.** If `find TARGET_ROOT -name "*.sql" -not -path "*/node_modules/*"` returns ≥1 file, you MUST call `sql_audit` in this phase. There is no condition under which "skipped" is acceptable on a `.sql`-bearing repo: not "no diff vs prior", not "DEFERRED", not "low risk this run". The 5 internal gates are independent of delta — they re-run every time and re-validate the schema↔ORM mapping from scratch. Skipping = audit invalid (see MANDATORY TOOL CALLS section above).
492
493```
494# Claude Code: ToolSearch("select:mcp__codesift__sql_audit")
495# Codex/other: describe_tools(names=["sql_audit"], reveal=true)
496sql_audit() # runs all 5 gates: drift, orphan, lint, dml, complexity
497```
498
499Map each gate to the corresponding DB dimension:
500
501| sql_audit gate | Maps to | What it catches |
502|---------------|---------|-----------------|
503| `drift` | DB13 (migration deploy safety) | Prisma↔SQL field/type mismatches — "forgot to run migration" bugs |
504| `orphan` | DB3 (schema design) | Tables defined in SQL with zero references in code or ORM |
505| `lint` | DB2 + DB3 | Missing PK, wide tables (>20 cols), duplicate index names |
506| `dml` | DB12 (DB security) | DELETE/UPDATE without WHERE (data loss), SELECT * (unbounded) |
507| `complexity` | DB3 (schema design) | God tables: column count + FK count + index count score ≥25 |
508
509For finer control, run a subset of gates: `sql_audit({ checks: ["drift", "dml"] })`.
510
511The `sql_audit` result has shape:
512```json
513{
514 "gates": [
515 { "check": "drift", "pass": false, "critical": true, "finding_count": 3, "summary": "3 drifts: 2 extra in ORM, 0 extra in SQL, 1 type mismatches", "data": {...} },
516 { "check": "orphan", "pass": true, ... },
517 ...
518 ],
519 "summary": { "total_findings": 12, "critical_findings": 1, "gates_run": 5, "gates_passed": 2, "gates_failed": 3 }
520}
521```
522
523Pass each gate's findings to the corresponding DB dimension scoring as TOOL-VERIFIED evidence. Critical gates (`drift` with type_mismatches > 0, `dml` with high-severity findings) propagate to the matching DB critical gate (DB13, DB12).
524
525If `sql_audit` is unavailable (CodeSift older than v0.4.x or no `.sql` files), skip 2.0b and rely on the manual schema/migration analysis in Phase 1 + agent dispatch.
526
527#### 2.0c — Additional SQL query tools (optional)
528
529When deeper investigation is needed for specific findings:
530
531| Tool | When to use |
532|------|-------------|
533| `analyze_schema` | Generate ERD (Mermaid) for the executive summary section |
534| `trace_query(table)` | **MANDATORY** for every "orphan" finding from `sql_audit` and every table cited in HIGH/MEDIUM findings — verify zero references across `.ts`/`.py`/`.go`/`.kt`/Prisma/Drizzle |
535| `search_columns(query)` | **MANDATORY** for DB12 PII discovery — find all `email`/`password`/`ssn`/`token`/`secret`/`hash` columns. Run with empty query first to inventory PII surface, then targeted queries for specific concerns. |
536| `diff_migrations` | **MANDATORY when `migrations/` exists** — DB6/DB13 destructive op classification. Reports `additive`/`modifying`/`destructive` counts. Now in MANDATORY TOOL CALLS section above. |
537| `analyze_schema(output_format='mermaid')` | **MANDATORY when `.sql` exists** — DB3 schema inventory + ERD for executive summary. |
538| `explain_query(code='prisma.<model>.<call>(...)')` | **MANDATORY for every Prisma query cited in HIGH/MEDIUM finding** — DB1/DB2 simulated EXPLAIN ANALYZE catches N+1 from `include`, unbounded `findMany`, missing indexes that `sql_audit` cannot see (Prisma-only). |
539
540Previously these were "drill down only" — promoted to mandatory after the 2026-05-04 audit on tgm-survey-platform showed `sql_audit` alone misses ~30% of issues that surface when paired with `diff_migrations` + `analyze_schema` + `trace_query`.
541
542---
543
544If CodeSift is entirely unavailable, skip Phase 2.0 and proceed directly to Agent Dispatch — agents will use Grep/Read.
545
546Collect results from 2.0a + 2.0b. Pass them into agent prompts as "pre-verified findings" (HIGH confidence, tool-verified). Agents should NOT re-scan for these patterns — they should verify context and discover patterns the automated scan missed.
547
548### Agent Dispatch
549
550Refer to `env-compat.md` for the dispatch pattern.
551
552**When parallel dispatch is available:**
553
554| Agent | Dimensions | Focus |
555|-------|-----------|-------|
556| Schema Analyst | DB2, DB3, DB6, DB13 | Schema design + migration safety + deploy safety |
557| Query Scanner | DB1, DB5, DB8, DB9 | Code-level query patterns |
558| Infrastructure Auditor | DB4, DB7, DB10, DB11, DB12 | Connections, cache, observability, security |
559
560**Agent prompt rules:**
561
5621. **CodeSift tool loading** — include this block at the very top of every agent prompt so tools are callable:
563 ```
564 FIRST: Load CodeSift tools before doing anything else.
565 - Claude Code: Run ToolSearch("select:mcp__codesift__search_text,mcp__codesift__search_symbols,mcp__codesift__codebase_retrieval,mcp__codesift__trace_route,mcp__codesift__find_references,mcp__codesift__get_file_outline,mcp__codesift__trace_call_chain,mcp__codesift__search_patterns,mcp__codesift__assemble_context")
566 - Codex: Call mcp__codesift__search_text directly — MCP tools are pre-registered.
567 - Cursor/Antigravity: CodeSift unavailable — use Grep/Read.
568 If any tool call fails, fall back to Grep/Read.
569 ```
570 Adjust the tool list per agent role — Schema Analyst needs `get_file_outline` + `search_symbols` + `sql_audit` + `analyze_schema` + `search_columns`; Query Scanner needs `trace_route` + `codebase_retrieval` + `search_patterns` + `trace_query`; Infrastructure Auditor needs `search_text` + `find_references` + `diff_migrations` (for DB13 destructive op review).
5712. **Token budget:** Each agent must keep its report under 800 words. Structured as: findings list (ID, severity, file:line, 1-sentence description) + 1-paragraph summary. No prose explanations per finding.
5723. **CodeSift cheat sheet** — include right after the tool loading block:
573 ```
574 CodeSift: batch 3+ searches → codebase_retrieval(queries=[...]).
575 Endpoints → trace_route first. Skip list_repos (auto-resolve).
576 If empty results → fallback to Grep (parser may be unavailable).
577 ```
5784. **Pre-verified findings:** Pass Phase 2.0 results to agents with instruction: "These findings are TOOL-VERIFIED. Do not re-scan for them. Focus on patterns the pre-scan cannot catch."
579
580**Without parallel dispatch:** Execute all dimensions sequentially.
581
582### DB1: Query Patterns -- Weight 15, Max 15, Critical Gate
583
584| Check | Good | Bad | Severity |
585|-------|------|-----|----------|
586| N+1 queries | Eager loading (`include`, `joinedload`), batched IDs | `findMany` / `find` inside a loop | CRITICAL |
587| Select efficiency | `select` only needed fields | `SELECT *` / no select clause | HIGH |
588| Bulk operations | `createMany`, `updateMany`, bulk insert | Individual create/update in loop | HIGH |
589| Raw query safety | Parameterized queries (`$queryRaw` with template, `%s` params) | String concatenation in SQL | CRITICAL |
590
591Critical gate: DB1=0 (N+1 in hot path) triggers audit FAIL.
592
593### DB2: Index Strategy -- Weight 15, Max 15
594
595| Check | Good | Bad | Severity |
596|-------|------|-----|----------|
597| FK indexes | Every foreign key has an index | FK columns without index | HIGH |
598| Composite indexes | Multi-column indexes for common query patterns | Single-column indexes on individually queried fields | MEDIUM |
599| Covering indexes | Index includes all fields for frequent queries | Extra lookups required | LOW |
600| Unused indexes | All indexes serve active queries | Indexes that are never hit | MEDIUM |
601
602### DB3: Schema Design -- Weight 8, Max 8
603
604| Check | Good | Bad | Severity |
605|-------|------|-----|----------|
606| Normalization | Appropriate normal form, no data duplication | Same data stored in multiple tables | HIGH |
607| Enum usage | Database enums or constrained strings for status/type | Arbitrary strings without validation | MEDIUM |
608| Timestamps | `createdAt`/`updatedAt` on mutable models, `deletedAt` for soft delete | No audit trail | MEDIUM |
609| Naming conventions | Consistent naming (snake_case or camelCase), clear foreign key names | Mixed conventions, ambiguous names | LOW |
610
611### DB4: Connection Management -- Weight 10, Max 10, Critical Gate
612
613| Check | Good | Bad | Severity |
614|-------|------|-----|----------|
615| Connection pooling | Pool configured with min/max, singleton client | New client per request | CRITICAL |
616| Serverless awareness | External pooler (PgBouncer, Supabase pooler) for serverless | Direct connection from Lambda/Worker | CRITICAL |
617| Connection limits | Pool size matches deployment (serverless: small, container: tuned) | Default unlimited | HIGH |
618| Client instantiation | Single PrismaClient/DataSource instance | Multiple `new PrismaClient()` calls | HIGH |
619
620Critical gate: DB4=0 (no pooling) triggers audit FAIL.
621
622### DB5: Transaction Safety -- Weight 12, Max 12, Critical Gate
623
624| Check | Good | Bad | Severity |
625|-------|------|-----|----------|
626| Multi-table mutations | Wrapped in transaction | Separate writes without transaction | CRITICAL |
627| Transaction scope | Minimal scope, no external API calls inside | HTTP request or email send inside transaction | HIGH |
628| Rollback handling | Explicit error handling, compensation logic | Silent swallow on transaction failure | HIGH |
629| Deadlock prevention | Consistent lock ordering, timeout on transactions | Arbitrary ordering, no timeout | MEDIUM |
630
631Critical gate: DB5=0 (multi-table mutations without transaction) triggers FAIL.
632
633### DB6: Migration Safety -- Weight 8, Max 8
634
635| Check | Good | Bad | Severity |
636|-------|------|-----|----------|
637| Non-blocking DDL | `CREATE INDEX CONCURRENTLY`, `ADD COLUMN` with default | Locking index creation on large table | HIGH |
638| Data migration | Separate data migration from schema migration | Mixed DDL and DML in one migration | MEDIUM |
639| Reversibility | Down migrations exist and tested (non-Prisma ORMs) | No rollback path | MEDIUM |
640| Type changes | Multi-step migration for type changes (add new, migrate, drop old) | Direct `ALTER TYPE` on populated column | HIGH |
641
642### DB7: Caching Layer -- Weight 8, Max 8
643
644| Check | Good | Bad | Severity |
645|-------|------|-----|----------|
646| Query result cache | Redis/Memcached for expensive/repeated queries, TTL configured | Every request hits database | HIGH |
647| Cache invalidation | Event-driven or TTL with jitter | Manual invalidation, no TTL | MEDIUM |
648| Cache-aside pattern | Read-through with fallback to DB on miss | All-or-nothing cache (miss = error) | MEDIUM |
649| Cache key design | Includes tenant/org scope, versioned | Global keys, no scoping | MEDIUM |
650
651### DB8: Query Optimization -- Weight 10, Max 10
652
653| Check | Good | Bad | Severity |
654|-------|------|-----|----------|
655| Pagination | Cursor-based for large datasets, keyset pagination | OFFSET pagination on growing table | HIGH |
656| LIKE queries | Prefix match only, full-text search for complex needs | `%term%` LIKE on unindexed column | MEDIUM |
657| Function on column | Avoid function calls on indexed columns in WHERE | `WHERE LOWER(email) = ...` (defeats index) | MEDIUM |
658| Sorting | Sort on indexed column | Sort on computed/unindexed column for large result | MEDIUM |
659
660### DB9: ORM-Specific Anti-Patterns -- Weight 6, Max 6
661
662Patterns vary by detected ORM:
663
664**Prisma:** `$queryRawUnsafe`, missing `select` on deep includes, `findMany`
665without `take`, `$transaction` with long-running operations.
666
667**TypeORM:** Lazy relations without awareness, `find()` without `select`,
668`QueryBuilder` without parameter binding.
669
670**Django:** N+1 via `object.related_set.all()` without `select_related`/
671`prefetch_related`, `.count()` on unevaluated queryset.
672
673**SQLAlchemy:** Lazy loading N+1, `session.query()` without limit, missing
674`yield_per` for large result sets.
675
676### DB10: Observability -- Weight 4, Max 4
677
678| Check | Good | Bad | Severity |
679|-------|------|-----|----------|
680| Query logging | Structured logging with query duration, parameterized | No query logging in production | MEDIUM |
681| Slow query alerting | Threshold-based alerts (> 1s), dashboard | No monitoring for slow queries | MEDIUM |
682| Connection metrics | Pool utilization tracked, alerts on exhaustion | No visibility into connection state | LOW |
683
684### DB11: Data Lifecycle -- Weight 4, Max 4
685
686| Check | Good | Bad | Severity |
687|-------|------|-----|----------|
688| Archival strategy | Old data archived or partitioned | Unbounded table growth | MEDIUM |
689| Batch processing | Batch deletes/updates with limits, off-peak scheduling | Full-table operations during peak hours | MEDIUM |
690| Soft delete | `deletedAt` pattern with default scope excluding deleted | Hard delete without audit trail | LOW |
691
692### DB12: Database Security -- Weight 4, Max 4, Critical Gate
693
694| Check | Good | Bad | Severity |
695|-------|------|-----|----------|
696| SQL injection | All queries parameterized, no string concatenation | `$queryRawUnsafe` or string-built SQL | CRITICAL |
697| Least privilege | Application user has minimal permissions | App connects as superuser | HIGH |
698| Connection encryption | SSL/TLS required in connection string | Plaintext database connection | HIGH |
699| Sensitive data | PII encrypted at rest, column-level encryption for secrets | Plaintext passwords or tokens in DB | CRITICAL |
700
701Critical gate: DB12=0 (SQL injection) triggers audit FAIL.
702
703### DB13: Migration Deployment Safety -- Weight 8, Max 8
704
705Goes beyond DB6 (migration code quality) to assess whether migrations can be deployed safely to a running production system.
706
707| Check | Good | Bad | Severity |
708|-------|------|-----|----------|
709| Destructive operations | `DROP COLUMN`/`DROP TABLE` preceded by deprecation migration, data backed up | Direct `DROP` on populated columns without prior migration to remove usage | CRITICAL |
710| Lock duration estimation | Short-lived locks: `ADD COLUMN` with default (PG 11+), `CREATE INDEX CONCURRENTLY` | `ALTER TABLE` operations that acquire `ACCESS EXCLUSIVE` lock on large tables (>100K rows) | CRITICAL |
711| Rollback plan | Down migration exists and tested, or forward-fix strategy documented | No rollback path — failed migration leaves DB in inconsistent state | HIGH |
712| Data loss risk | `NOT NULL` additions have `DEFAULT` value, type changes preserve data | `ALTER COLUMN SET NOT NULL` without default on populated table, truncating type changes | CRITICAL |
713| Backward compatibility | New columns nullable or with defaults (old app version still works), rename = add+copy+drop | Column renames or type changes that break currently-deployed app code | HIGH |
714| Idempotency | Migrations use `IF NOT EXISTS`, `IF EXISTS` guards | Migrations fail on re-run (no idempotency — partial failure leaves broken state) | HIGH |
715| Migration ordering | Migrations numbered/timestamped, no conflicts in team branches | Multiple migrations with same timestamp, or migrations that depend on unapplied predecessors | MEDIUM |
716| Long-running DML | Data backfills use batched updates with `LIMIT` and sleep between batches | Single `UPDATE` on millions of rows (locks table, blocks queries, risks timeout) | HIGH |
717| Connection impact | Migration runs outside connection pool, or uses dedicated migration connection | Migration runs through application pool, potentially exhausting connections during deploy | MEDIUM |
718| Zero-downtime readiness | Migration + app deploy order documented, blue-green or rolling deploy compatible | Migration requires app downtime — schema and app must change simultaneously | HIGH |
719
720**How to audit:**
721
7221. Read all migration files in the migrations directory (last 20 if >20 exist)
7232. For each migration, classify operations:
724 - **SAFE**: `ADD COLUMN` (nullable or with default), `CREATE TABLE`, `CREATE INDEX CONCURRENTLY`
725 - **CAUTION**: `ADD COLUMN NOT NULL` with default (PG 11+ safe, older = table rewrite), `ALTER COLUMN SET DEFAULT`
726 - **DANGEROUS**: `DROP COLUMN`, `DROP TABLE`, `ALTER COLUMN TYPE`, `ALTER COLUMN SET NOT NULL` without default
727 - **BLOCKING**: `CREATE INDEX` without `CONCURRENTLY`, `ALTER TABLE` on large table without estimated lock time
7283. For DANGEROUS/BLOCKING operations, check:
729 - Is there a prior migration removing code references to dropped columns?
730 - Is there a rollback migration?
731 - Is the table large enough to cause lock contention (estimate from schema relations)?
7324. Check deployment documentation for migration strategy
733
734**Scoring:**
735- 0 DANGEROUS ops without safeguards = 8/8
736- Each unguarded DANGEROUS op: -2
737- Each BLOCKING op without CONCURRENTLY: -1
738- No rollback path for any destructive migration: -2
739- No idempotency guards: -1
740
741**N/A:** If no migration files found, DB13=N/A.
742
743---
744
745## Phase 3: Live Analysis (optional --live)
746
747**Skip unless** `--live <conn>` was provided. Requires database client access.
748
749**Supported engines:** PostgreSQL (full), MySQL (partial). SQLite/MongoDB:
750skip Phase 3, rely on code-level analysis.
751
752### 3.1 PostgreSQL Live Queries
753
754```sql
755-- Top 20 slow queries (requires pg_stat_statements)
756SELECT query, calls, mean_exec_time, total_exec_time, rows
757FROM pg_stat_statements ORDER BY total_exec_time DESC LIMIT 20;
758
759-- Unused indexes
760SELECT schemaname, relname, indexrelname, idx_scan, idx_tup_read
761FROM pg_stat_user_indexes WHERE idx_scan = 0
762ORDER BY pg_relation_size(indexrelid) DESC;
763
764-- Cache hit ratio
765SELECT sum(heap_blks_hit) / nullif(sum(heap_blks_hit) + sum(heap_blks_read), 0)
766 AS cache_hit_ratio
767FROM pg_statio_user_tables;
768
769-- Table bloat
770SELECT schemaname, relname, n_dead_tup, last_autovacuum
771FROM pg_stat_user_tables WHERE n_dead_tup > 10000 ORDER BY n_dead_tup DESC;
772
773-- Active connections by state
774SELECT state, count(*) FROM pg_stat_activity GROUP BY state;
775```
776
777### 3.2 MySQL Live Queries
778
779```sql
780-- Slow queries via performance_schema
781SELECT * FROM performance_schema.events_statements_summary_by_digest
782ORDER BY SUM_TIMER_WAIT DESC LIMIT 20;
783
784-- Unused indexes
785SELECT * FROM sys.schema_unused_indexes;
786
787-- Active connections
788SHOW PROCESSLIST;
789```
790
791### 3.3 Unsupported Engines
792
793If the engine is not PostgreSQL or MySQL, print:
794"Live analysis requires PostgreSQL or MySQL. Skipping Phase 3."
795Mark Phase 3 as SKIPPED.
796
797---
798
799## Phase 4: Verification and Scoring
800
801### 4.1 False Positive Filters
802
803| Pattern | Skip When |
804|---------|-----------|
805| `findMany` without `take` | Inside admin tool, migration script, or seed file |
806| N+1 loop | Loop is bounded (< 10 items) AND commented as intentional |
807| `await-in-loop` (search_patterns hit) | Function contains `*_CONCURRENCY_LIMIT`, `BATCH_SIZE`, `CHUNK_SIZE`, or similar bounded-concurrency constant |
808| `await-in-loop` (search_patterns hit) | Loop body is inside a seed/migration/admin script (path contains `seed/`, `scripts/`, `migrations/`, `tools/`) |
809| `await-in-loop` (search_patterns hit) | Loop is wrapped by `pLimit`, `Promise.all` with chunks, `pAll`, `bottleneck`, or similar concurrency limiter |
810| `await-in-loop` (search_patterns hit) | Loop is bounded by literal `< 10` and the bound is visible in source |
811| Missing index | Table known to be small (< 1000 rows, documented) |
812| No indexes in ORM | External index scripts found (use external inventory for scoring) |
813| No connection pool | Using managed service that pools for you (Neon, Supabase, PlanetScale, Cockroach Cloud — see Phase 0.2) |
814| Raw SQL flagged | Uses tagged template `$queryRaw` (safe, parameterized) |
815
816**Anti-noise rule for await-in-loop:** If `search_patterns(pattern="await-in-loop")` returns more than 10 hits, do NOT report each one as a finding. Instead, group them by file, identify which match the false-positive filters above, and report only the residual count with the worst 3 examples. Reporting 30+ "potential N+1" findings without filtering = noise that drowns signal.
817
818### 4.2 Severity Classification
819
820| Level | Criteria |
821|-------|----------|
822| CRITICAL | Data loss, connection exhaustion, SQL injection, OOM in production |
823| HIGH | User-visible latency, missing safety guard, scalability wall |
824| MEDIUM | Performance debt, suboptimal pattern, maintenance risk |
825| LOW | Recommendation, best practice gap, future-proofing |
826
827### 4.3 Cross-Dimension Correlations
828
829Flag compound patterns:
830
831| Pattern | Dimensions | Impact |
832|---------|-----------|--------|
833| N+1 on unindexed column | DB1+DB2 | Exponential degradation |
834| Unbounded query without cache on large table | DB1+DB7+DB11 | OOM risk |
835| External API call inside transaction without timeout | DB5+DB4 | Connection pool exhaustion |
836| Serverless + no external pooler + multiple client instances | DB4+deployment | Connection storm |
837| OFFSET pagination on growing table | DB8+DB11 | Degrading page load times |
838
839### 4.4 Scoring
840
841Score each dimension per the rubric. Calculate weighted total.
842
843**Critical gate check:**
844- DB1=0 (N+1 in hot path) -> FAIL
845- DB4=0 (no connection pooling) -> FAIL
846- DB5=0 (multi-table mutations without transaction) -> FAIL
847- DB12=0 (SQL injection) -> FAIL
848
849Any critical gate = 0 overrides the overall grade to **FAIL**.
850
851**Grade calculation (excluding N/A dimensions):**
852
853| Grade | Percentage |
854|-------|-----------|
855| A | >= 85% |
856| B | 70-84% |
857| C | 50-69% |
858| D | < 50% |
859
860---
861
862## Phase 5: Report
863
864Save to: `audits/db-audit-[YYYY-MM-DD].md`
865
866**REQUIRED:** emit the Tool Availability Block (template in `../../shared/includes/codesift-setup.md`) at the top of the report, after the title and before findings. Auditing degraded runs depends on this — do NOT skip it.
867
868### Report Structure
869
870```markdown
871# Database Audit Report
872
873## Metadata
874| Field | Value |
875|-------|-------|
876| Project | [name] |
877| Date | [YYYY-MM-DD] |
878| ORM | [detected ORM] |
879| Engine | [detected engine] |
880| Deployment | [detected deployment type] |
881| Scope | [full / path / file] |
882| Live analysis | [enabled / skipped] |
883| CodeSift | [full-parser / text-stub / unavailable] |
884| Prior audit | [date or "none — baseline"] |
885
886## Executive Summary
887
888**Score: [N] / [MAX]** -- [A/B/C/D or FAIL]
889
890| Metric | Count |
891|--------|-------|
892| CRITICAL findings | N |
893| HIGH findings | N |
894| MEDIUM findings | N |
895| LOW findings | N |
896
897[2-3 sentence summary]
898
899## Dimension Scores
900
901| # | Dimension | Score | Max | Notes |
902|---|-----------|-------|-----|-------|
903| DB1 | Query Patterns | [N] | 15 | |
904| DB2 | Index Strategy | [N] | 15 | |
905| DB3 | Schema Design | [N] | 8 | |
906| DB4 | Connection Mgmt | [N] | 10 | |
907| DB5 | Transaction Safety | [N] | 12 | |
908| DB6 | Migration Safety | [N] | 8 | |
909| DB7 | Caching Layer | [N] | 8 | |
910| DB8 | Query Optimization | [N] | 10 | |
911| DB9 | ORM Anti-Patterns | [N] | 6 | |
912| DB10 | Observability | [N] | 4 | |
913| DB11 | Data Lifecycle | [N] | 4 | |
914| DB12 | DB Security | [N] | 4 | |
915| DB13 | Migration Deploy Safety | [N] | 8 | |
916| **Total** | | **[N]** | **[M]** | |
917
918## Critical Gate Status
919[DB1, DB4, DB5, DB12 -- PASS/FAIL per gate]
920
921## Model Inventory
922[From Phase 1]
923
924## Findings (sorted by severity)
925
926Per finding:
927- **ID:** DB{dimension}-{NNN} (e.g. DB1-001)
928- **Severity:** CRITICAL / HIGH / MEDIUM / LOW
929- **Status:** NEW / RESOLVED / PARTIAL / PLANNED / REGRESSION (see status rules below)
930- **Confidence:** TOOL-VERIFIED (from Phase 2.0 pre-scan) / HIGH / MEDIUM
931- **File:line:** exact location
932- **Description:** 1 sentence
933- **Fix:** concrete code change or command
934- **Effort:** S (<1h) / M (1-4h) / L (4h+)
935- **Evidence:** required for any severity downgrade — `find_references` count, `trace_route` hot/cold path, etc.
936
937### Status rules
938
939| Status | When to use | Counted in severity totals? |
940|--------|-------------|----------------------------|
941| `NEW` | First time this finding appears | Yes |
942| `RESOLVED` | Prior finding no longer present (verified, not assumed) | No (moved to "Resolved" section) |
943| `PARTIAL` | Part of prior issue is fixed, part remains. Severity stays at original level with `(partial)` suffix — DO NOT downgrade. | Yes, at original severity |
944| `PLANNED` | Finding has a linked task in `docs/specs/*-plan.md` or `memory/backlog.md`. Tracked separately. | No (moved to "Planned" section) |
945| `REGRESSION` | Finding was RESOLVED in prior audit but reappeared | Yes, severity = max(prior, current) |
946
947**Severity downgrade rule:** A finding's severity may only be lowered (e.g. M→L) when ALL of these are true:
9481. The Evidence field includes a concrete count from `find_references` or `trace_route`
9492. The downgrade reason is documented in 1 sentence in the Description
9503. If `mode == "delta"`, the Phase 0.5 checklist was completed for this specific finding
951
952If any of the three conditions fail, keep the prior severity. Anchoring to a number you didn't independently verify is the #1 cause of audit drift.
953
954## Delta from Prior Audit
955
956If a prior `audits/db-audit-*.md` exists, include:
957
958| Finding | Prior status | Current status | Change |
959|---------|-------------|----------------|--------|
960| DB1-001 | CRITICAL | RESOLVED | Fixed in [commit] |
961| DB2-003 | HIGH | HIGH | Still open |
962| DB9-001 | — | NEW | First detected |
963
964Score delta: [prior score] → [current score] ([+/-N])
965
966If no prior audit exists, print: "No prior audit found — baseline established."
967
968## Cross-Cutting Patterns
969[Compound patterns found]
970
971## Top 5 Action Items
972
973Per item: priority (P0/P1/P2), effort (S/M/L), blast radius (N files), concrete action.
974
975## Delete These Tomorrow
976
977Actionable commands for findings that require zero design decisions — just execute:
978
979```bash
980# Example format:
981# DB1-003: Add take: 100 to unbounded findMany
982# File: src/services/user.service.ts:45
983
984# DB2-001: Add missing FK index
985# npx prisma migrate dev --name add_org_id_index
986
987# DB12-002: Remove hardcoded connection string
988# Move to .env: DATABASE_URL=...
989```
990
991List only findings with effort=S. If none qualify, omit this section.
992
993## Backlog Entries
994[/backlog add commands for HIGH+ findings]
995```
996
997### Report Validation
998
999After writing, verify:
1000- Dimension scores sum to total in Executive Summary
1001- Finding counts match Executive Summary (counted: NEW + PARTIAL + REGRESSION; not counted: RESOLVED + PLANNED)
1002- All models from inventory are addressed
1003- Critical gate status is accurate
1004- Every finding has a DB{N}-{NNN} ID, severity, status, confidence, file:line, and effort
1005- Every severity downgrade has Evidence field populated (find_references count or trace_route output)
1006- PLANNED findings have a verified link to `docs/specs/*-plan.md` or `memory/backlog.md`
1007- PARTIAL findings keep prior severity with `(partial)` suffix — no downgrade
1008- Delta section references correct prior audit (or states "baseline")
1009- TOOL-VERIFIED findings match Phase 2.0 pre-scan output
1010- "Delete These Tomorrow" only contains effort=S items
1011- If `mode == "delta"`: Phase 0.5 checklist is fully completed (all 6 items checked)
1012
1013---
1014
1015## Phase 6: Next-Step Routing
1016
1017```
1018RECOMMENDED NEXT ACTION
1019------------------------------------
1020DB1 CRITICAL (N+1) -> zuvo:refactor [service file]
1021DB4 no connection pool -> direct fix (add pool config)
1022DB2 missing indexes -> direct migration (add indexes)
1023DB12 SQL injection -> /security-audit [path]
1024DB13 unsafe migrations -> rewrite migrations with CONCURRENTLY, rollbacks, batch DML
1025DB9 ORM anti-patterns -> zuvo:refactor [service file]
1026Multiple dimensions fail -> zuvo:review [path]
1027------------------------------------
1028```
1029
1030---
1031
1032## Completion Gate Check
1033
1034Before printing the final output block, verify every item. Unfinished items = pipeline incomplete.
1035
1036```
1037COMPLETION GATE CHECK
1038[ ] ORM + engine + deployment type detected and printed
1039[ ] N+1 query detection ran (DB1 critical gate)
1040[ ] Unbounded query detection ran (DB1/DB7)
1041[ ] Migration safety audit ran (DB6)
1042[ ] Critical gates printed: DB1, DB2, DB4, DB6, DB7, DB10, DB11
1043[ ] Report saved to audits/
1044[ ] Backlog updated for HIGH+ findings
1045[ ] Run: line printed and appended to log
1046```
1047
1048## DB-AUDIT COMPLETE
1049
1050Score: [N] / [MAX] -- [grade]
1051ORM: [detected] | Engine: [detected]
1052Dimensions: [N scored] | Critical gates: [PASS/FAIL]
1053Findings: [N critical] / [N total]
1054
1055### Validity Gate (REQUIRED — print BEFORE Run line)
1056
1057```
1058VALIDITY GATE
1059 triggers_held:
1060 sql_files: [yes(N) | no]
1061 migrations_dir: [yes | no]
1062 prisma_schema: [yes | no]
1063 postgres_in_deps: [yes | no]
1064 framework: [nestjs | django | none]
1065 required_tool_calls (held triggers only):
1066 sql_audit: [<gates_passed>/<gates_run> | NOT_CALLED — VIOLATES_TRIGGER]
1067 analyze_schema: [<table_count> tables | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1068 diff_migrations: [<additive>/<modifying>/<destructive> | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1069 trace_query: [<table_count> traced | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1070 search_columns: [<pii_columns_found> | NOT_CALLED — VIOLATES_TRIGGER]
1071 migration_lint: [<findings> | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1072 analyze_prisma_schema: [<fk_index_coverage> | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1073 explain_query: [<queries_explained> | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1074 nest_audit: [<score> | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1075 python_audit: [<findings> | not_required | NOT_CALLED — VIOLATES_TRIGGER]
1076 scan_secrets: [<findings> | NOT_CALLED — VIOLATES_TRIGGER]
1077 pattern_calls:
1078 unbounded-findmany: [<count> | NOT_CALLED — VIOLATES_TRIGGER]
1079 await-in-loop: [<count> | NOT_CALLED — VIOLATES_TRIGGER]
1080 toctou: [<count> | NOT_CALLED — VIOLATES_TRIGGER]
1081 postamble:
1082 retros_log_appended: [yes(bytes_added=N) | NOT_APPENDED — VIOLATES_REQUIRED_POSTAMBLE]
1083 retros_md_appended: [yes(entry_count=N) | NOT_APPENDED — VIOLATES_REQUIRED_POSTAMBLE]
1084 gate_status: [PASS | FAIL — <which tools or postamble missing>]
1085```
1086
1087**The Validity Gate must be printed AFTER step 6 of the Required POSTAMBLE (after retros append), not before.** Printing it before retro append guarantees `retros_*_appended: NOT_APPENDED`.
1088
1089If `gate_status = FAIL`, override the VERDICT below to `INCOMPLETE` regardless of finding count, append `[VALIDITY GATE FAIL]` to the Run line NOTES column, and add a backlog item.
1090
1091Run: <ISO-8601-Z> db-audit <project> <N-critical> <N-total> <VERDICT> - <N>-dimensions <NOTES> <BRANCH> <SHA7> <INCLUDES> <TIER>
1092
1093
1094### Retrospective (REQUIRED)
1095
1096**Load now (deferred):** Read `../../shared/includes/retrospective.md` if not already loaded.
1097
1098Follow the retrospective protocol from `retrospective.md`.
1099Gate check → structured questions → TSV emit → markdown append.
1100If gate check skips: print "RETRO: skipped (trivial session)" and proceed.
1101
1102After printing this block, append the `Run:` line value (without the `Run: ` prefix) to the log file path resolved per `run-logger.md`.
1103
1104VERDICT: PASS (0 critical findings), WARN (1-3 critical), FAIL (4+ critical).
1105
1106---
1107
1108## Execution Notes
1109
1110- All commands use the resolved `TARGET_ROOT` from argument parsing
1111- CodeSift integration follows `codesift-setup.md` -- use indexed search when
1112 available, fall back to Grep/Read/Glob when not
1113- Agent dispatch follows `env-compat.md` -- parallel when supported, sequential
1114 otherwise
1115- ORM detection determines which anti-pattern checks to run (DB9 is
1116 ORM-specific)
1117- Live analysis (Phase 3) is strictly opt-in and read-only
1118- Prisma does not use down migrations -- do not flag this as an issue