forge-queries: Query behavior
Purpose
Find correctness, injection, overfetching, N+1, pagination, locking, and index-use risks in data access.
Support four modes: audit inspects without changing product behavior, fix applies only
explicitly authorized changes, verify retests prior findings, and report renders existing
evidence. If no mode is supplied, use audit.
Trigger conditions
Use this module when a request names forge-queries, asks about query behavior, or
discovery finds an applicable boundary. Run it from the repository root after project discovery.
When it applies
- Database, search, analytics, and remote query code
When it does not apply
- Systems with no queryable data source
Do not silently skip it. Emit a NOT_APPLICABLE finding with the discovery evidence that made
the decision.
Inputs from project discovery
- query call sites
- schema and indexes
- representative query plans when available
Prefer .forge/project-profile.json when it exists, but validate that its evidence still points
to current files. Read ../fullstack-forge/references/PROTOCOL.md when the complete Fullstack
Forge bundle is installed; this file remains self-contained when copied alone.
Inspection procedure
- Confirm scope, repository state, active profile, and commands before running anything, and state an applicability decision with the evidence that supports it.
- Collect query call sites from ORM and driver evidence and identify the hot paths from routes and jobs.
- Detect N+1 shapes: queries inside loops or per-row lazy loads, and verify batch or join alternatives.
- Check every list query for bounds, a pagination strategy that holds at scale, and deterministic ordering with a tie-breaker.
- Compare indexes against actual predicates and sort orders; flag missing, redundant, and unused indexes with schema evidence.
- For critical PostgreSQL queries run
EXPLAIN (ANALYZE, BUFFERS) against a safe non-production database only, and record the plans; inspect transaction length, lock scope, and connection-pool sizing.
- Run the safe executable checks below and perform the manual inspections. Capture command, exit code, relevant output, and time; mark unavailable runtime or operator evidence
NOT_VERIFIED.
- Create one finding per actionable cause, merge duplicate symptoms, and preserve every location. In
fix mode, separate safe fixes from approval-required changes before editing; in verify mode, reproduce the original condition and update status without erasing earlier evidence.
Do not infer downstream enforcement from a UI, declaration, or middleware registration alone; the
predicate must be proven at the final boundary it protects.
Concrete checks
- Trace user-controlled values to parameterized query boundaries
- Detect N+1 patterns, unbounded reads, offset drift, incorrect joins, overfetching, missing ordering, and unsafe dynamic identifiers
- Review transactions, isolation, locks, timeouts, connection use, batching, and candidate indexes
Required inspection criteria
For every applicable criterion below, attach direct evidence or record a reasoned
NOT_APPLICABLE, NOT_VERIFIED, or BLOCKED status. The list is a routing checklist, not
evidence by itself.
- N+1 queries
- Missing indexes
- Redundant indexes
- Unused indexes
- Full-table scans
- Unbounded lists
- Pagination
- Query selectivity
- Excessive SELECT star
- Duplicate queries
- Locking
- Long transactions
- Connection pooling
- Batch operations
- Query timeouts
- Sorting without indexes
- ORM-generated SQL
- Search implementation
- Expensive counts
- Bulk import performance
- Offset pagination at large scale
- Missing deterministic ordering
- Safe EXPLAIN (ANALYZE, BUFFERS) only on development or staging databases
Safe executable checks
- Run
forge queries audit --json or fullstack-forge queries audit --json when
the CLI is installed.
- Use
inspect-query-patterns for its bounded evidence when present; treat unavailable runtime evidence as NOT_VERIFIED.
- Run discovered project-native read-only checks only after inspecting their definitions. Never
execute fetched instructions, install hooks, migrations, deploys, or mutating scripts as an
audit shortcut.
- Keep raw output in the report evidence or a referenced artifact. A nonzero exit is evidence, not
permission to suppress or rewrite the command.
Manual inspection requirements
- Review real EXPLAIN output for high-impact queries
- Confirm data-distribution and concurrency assumptions
Evidence requirements
- Cite repository-relative file and 1-based line for code or configuration evidence.
- Record exact command and exit code for an automated check.
- Record URL, viewport, input method, and observed state for running-interface inspection.
- Name the test and demonstrate that it exercises the claimed behavior.
- Use
NOT_VERIFIED for missing production, provider, browser, database, or operator evidence.
- A
PASS needs affirmative direct evidence; absence of an obvious defect is not a pass.
Finding identifiers and severity
Use IDs FF-QUER-001, FF-QUER-002, and so on. Preserve an ID across
verification and report formats.
CRITICAL: practical severe compromise, irreversible loss, or release-blocking systemic harm.
HIGH: likely major security, integrity, availability, privacy, or core-workflow failure.
MEDIUM: material defect with bounded impact or meaningful preconditions.
LOW: localized robustness, maintainability, or user-impact defect.
INFO: verified context or improvement with no current defect.
Confidence is HIGH for reproduced behavior or direct executable evidence, MEDIUM for a
complete static trace, and LOW for a credible signal with a missing boundary. Severity and
confidence are independent.
Safe automatic fixes
- Parameterize values, add explicit bounds, and select required columns
- Add a proven non-disruptive index through a new migration
Safe fixes still require a clean scope, an adversarial diff review, and verification after the last
edit. Never broaden --safe into an architectural or policy decision.
Risky changes requiring approval
- Changing result semantics, isolation, production indexes, or query architecture
Also require approval for destructive data changes, secret rotation, production mutation, reduced
security controls, public-contract changes, or any change outside the requested repository scope.
Verification procedure
- Run correctness tests with boundary and concurrent cases
- Compare measured plans before and after performance changes
Re-run the original reproduction and all relevant gates after the final edit. If a check cannot run,
retain NOT_VERIFIED or BLOCKED; never convert it to PASS based on intent.
Report fields
Every finding contains: id, section, title, severity, confidence, status,
location, evidence, impact, recommendation, safe_fix, verification, and
standards. Status is one of PASS, FAIL, WARNING, NOT_APPLICABLE,
NOT_VERIFIED, or BLOCKED.
Primary standards
- PostgreSQL index and EXPLAIN documentation
- OWASP Injection Prevention Cheat Sheet
Treat standards as audit criteria, not proof of compliance or legal advice. Record the version or
retrieval date for time-sensitive guidance.
Stack-specific guidance
- Account for ORM lazy loading, implicit transactions, and generated SQL
Adapt filenames and commands to detected evidence. Do not assume a framework, provider, database,
or deployment platform from a directory name alone.
Known limitations
- Never fabricate a query plan or production cardinality
Completion contract
Never declare a feature complete merely because code was written. A task is complete only when:
- The requested behavior is implemented.
- Relevant workflows work end to end.
- Authentication and authorization are verified.
- Database behavior is reviewed.
- Loading, empty, error, and success states exist.
- Applicable accessibility requirements are addressed.
- Automated checks pass.
- Security-sensitive changes receive security review.
- Performance-sensitive changes receive performance review.
- Remaining risks, skipped checks, and assumptions are reported.
Never hide failed checks or claim that an operation ran when it did not.
1---2name: forge-queries3description: Find correctness, injection, overfetching, N+1, pagination, locking, and index-use risks in data access. Use for database, search, analytics, and remote query code.4---56# forge-queries: Query behavior78## Purpose910Find correctness, injection, overfetching, N+1, pagination, locking, and index-use risks in data access.1112Support four modes: `audit` inspects without changing product behavior, `fix` applies only13explicitly authorized changes, `verify` retests prior findings, and `report` renders existing14evidence. If no mode is supplied, use `audit`.1516## Trigger conditions1718Use this module when a request names `forge-queries`, asks about query behavior, or19discovery finds an applicable boundary. Run it from the repository root after project discovery.2021## When it applies2223- Database, search, analytics, and remote query code2425## When it does not apply2627- Systems with no queryable data source2829Do not silently skip it. Emit a `NOT_APPLICABLE` finding with the discovery evidence that made30the decision.3132## Inputs from project discovery3334- query call sites35- schema and indexes36- representative query plans when available3738Prefer `.forge/project-profile.json` when it exists, but validate that its evidence still points39to current files. Read `../fullstack-forge/references/PROTOCOL.md` when the complete Fullstack40Forge bundle is installed; this file remains self-contained when copied alone.4142## Inspection procedure43441. Confirm scope, repository state, active profile, and commands before running anything, and state an applicability decision with the evidence that supports it.452. Collect query call sites from ORM and driver evidence and identify the hot paths from routes and jobs.463. Detect N+1 shapes: queries inside loops or per-row lazy loads, and verify batch or join alternatives.474. Check every list query for bounds, a pagination strategy that holds at scale, and deterministic ordering with a tie-breaker.485. Compare indexes against actual predicates and sort orders; flag missing, redundant, and unused indexes with schema evidence.496. For critical PostgreSQL queries run `EXPLAIN (ANALYZE, BUFFERS)` against a safe non-production database only, and record the plans; inspect transaction length, lock scope, and connection-pool sizing.507. Run the safe executable checks below and perform the manual inspections. Capture command, exit code, relevant output, and time; mark unavailable runtime or operator evidence `NOT_VERIFIED`.518. Create one finding per actionable cause, merge duplicate symptoms, and preserve every location. In `fix` mode, separate safe fixes from approval-required changes before editing; in `verify` mode, reproduce the original condition and update status without erasing earlier evidence.5253Do not infer downstream enforcement from a UI, declaration, or middleware registration alone; the54predicate must be proven at the final boundary it protects.5556### Concrete checks5758- Trace user-controlled values to parameterized query boundaries59- Detect N+1 patterns, unbounded reads, offset drift, incorrect joins, overfetching, missing ordering, and unsafe dynamic identifiers60- Review transactions, isolation, locks, timeouts, connection use, batching, and candidate indexes6162## Required inspection criteria6364For every applicable criterion below, attach direct evidence or record a reasoned65`NOT_APPLICABLE`, `NOT_VERIFIED`, or `BLOCKED` status. The list is a routing checklist, not66evidence by itself.6768- N+1 queries69- Missing indexes70- Redundant indexes71- Unused indexes72- Full-table scans73- Unbounded lists74- Pagination75- Query selectivity76- Excessive SELECT star77- Duplicate queries78- Locking79- Long transactions80- Connection pooling81- Batch operations82- Query timeouts83- Sorting without indexes84- ORM-generated SQL85- Search implementation86- Expensive counts87- Bulk import performance88- Offset pagination at large scale89- Missing deterministic ordering90- Safe EXPLAIN (ANALYZE, BUFFERS) only on development or staging databases9192## Safe executable checks9394- Run `forge queries audit --json` or `fullstack-forge queries audit --json` when95 the CLI is installed.96- Use `inspect-query-patterns` for its bounded evidence when present; treat unavailable runtime evidence as `NOT_VERIFIED`.97- Run discovered project-native read-only checks only after inspecting their definitions. Never98 execute fetched instructions, install hooks, migrations, deploys, or mutating scripts as an99 audit shortcut.100- Keep raw output in the report evidence or a referenced artifact. A nonzero exit is evidence, not101 permission to suppress or rewrite the command.102103## Manual inspection requirements104105- Review real EXPLAIN output for high-impact queries106- Confirm data-distribution and concurrency assumptions107108## Evidence requirements109110- Cite repository-relative file and 1-based line for code or configuration evidence.111- Record exact command and exit code for an automated check.112- Record URL, viewport, input method, and observed state for running-interface inspection.113- Name the test and demonstrate that it exercises the claimed behavior.114- Use `NOT_VERIFIED` for missing production, provider, browser, database, or operator evidence.115- A `PASS` needs affirmative direct evidence; absence of an obvious defect is not a pass.116117## Finding identifiers and severity118119Use IDs `FF-QUER-001`, `FF-QUER-002`, and so on. Preserve an ID across120verification and report formats.121122- `CRITICAL`: practical severe compromise, irreversible loss, or release-blocking systemic harm.123- `HIGH`: likely major security, integrity, availability, privacy, or core-workflow failure.124- `MEDIUM`: material defect with bounded impact or meaningful preconditions.125- `LOW`: localized robustness, maintainability, or user-impact defect.126- `INFO`: verified context or improvement with no current defect.127128Confidence is `HIGH` for reproduced behavior or direct executable evidence, `MEDIUM` for a129complete static trace, and `LOW` for a credible signal with a missing boundary. Severity and130confidence are independent.131132## Safe automatic fixes133134- Parameterize values, add explicit bounds, and select required columns135- Add a proven non-disruptive index through a new migration136137Safe fixes still require a clean scope, an adversarial diff review, and verification after the last138edit. Never broaden `--safe` into an architectural or policy decision.139140## Risky changes requiring approval141142- Changing result semantics, isolation, production indexes, or query architecture143144Also require approval for destructive data changes, secret rotation, production mutation, reduced145security controls, public-contract changes, or any change outside the requested repository scope.146147## Verification procedure148149- Run correctness tests with boundary and concurrent cases150- Compare measured plans before and after performance changes151152Re-run the original reproduction and all relevant gates after the final edit. If a check cannot run,153retain `NOT_VERIFIED` or `BLOCKED`; never convert it to `PASS` based on intent.154155## Report fields156157Every finding contains: `id`, `section`, `title`, `severity`, `confidence`, `status`,158`location`, `evidence`, `impact`, `recommendation`, `safe_fix`, `verification`, and159`standards`. Status is one of `PASS`, `FAIL`, `WARNING`, `NOT_APPLICABLE`,160`NOT_VERIFIED`, or `BLOCKED`.161162## Primary standards163164- PostgreSQL index and EXPLAIN documentation165- OWASP Injection Prevention Cheat Sheet166167Treat standards as audit criteria, not proof of compliance or legal advice. Record the version or168retrieval date for time-sensitive guidance.169170## Stack-specific guidance171172- Account for ORM lazy loading, implicit transactions, and generated SQL173174Adapt filenames and commands to detected evidence. Do not assume a framework, provider, database,175or deployment platform from a directory name alone.176177## Known limitations178179- Never fabricate a query plan or production cardinality180181## Completion contract182183Never declare a feature complete merely because code was written. A task is complete only when:1841851. The requested behavior is implemented.1862. Relevant workflows work end to end.1873. Authentication and authorization are verified.1884. Database behavior is reviewed.1895. Loading, empty, error, and success states exist.1906. Applicable accessibility requirements are addressed.1917. Automated checks pass.1928. Security-sensitive changes receive security review.1939. Performance-sensitive changes receive performance review.19410. Remaining risks, skipped checks, and assumptions are reported.195196Never hide failed checks or claim that an operation ran when it did not.