# Query Doc → Query Code Parity Check

## Context

Module: {{MODULE_NAME}}
Query docs: {{QUERY_DOCS}}
Query code: {{QUERY_CODE}}

## Instructions

1. Read ALL query docs at the paths above
2. Read ALL query code files at the paths above
3. For each query doc, extract business rules, process flow branches, input/output types
4. For each query code file, extract validation logic, branching paths, input interface, return type
5. Run every parity check below against each query
6. Return results as JSON per the Output Format section

## Method

Follow [claim-by-claim verification](../../erp-kit-shared/references/claim-verification.md) (prepended to this prompt). Claims for this template: each business rule, each flowchart branch, each input field, output shape, permission/scope requirements, pagination, null handling.

## Extraction: Query Docs

From each query doc, extract:

- **Business rules**: lookup/filter behavior, nullability, permission requirements, scope handling
- **Process flow**: branches from mermaid flowchart (decision nodes and their paths)
- **Input fields**: documented input parameters
- **Output type**: documented return structure (nullable single entity, paginated list, etc.)
- **External dependencies**: other queries or APIs called

## Extraction: Query Code

From each query code file (`query/*.ts`, excluding `*.test.ts` and `*.generated.ts`), extract:

- **Validation logic**: permission checks, scope checks, input validation guards
- **Branching paths**: if/else, early returns, scope filtering
- **Input interface**: exported `interface ...Input` fields
- **Return type**: `ok(...)` / `err(...)` structure
- **Generated shell**: existence of corresponding `.generated.ts` file
- **Pagination**: use of `PaginationInput`, `buildPaginatedResult`, limit+1 pattern

## Implementation Pattern Reference

Queries follow a `run` + generated shell pattern similar to commands:

- **Signature**: `async function run(db: ReadonlyDB<DB>, input: InputType, ctx?: QueryContext)`
- **ReadonlyDB**: queries use `ReadonlyDB<DB>` (not `DB`), enforcing read-only access
- **QueryContext**: optional, contains `actorId`, `permissions`, `companyId` for authorization
- **Generated shell**: `export const myQuery = defineQuery(run);` in `.generated.ts`
- **Return format**: wrap in object with descriptive keys (`{ entity }`, `{ items, hasNextPage }`)
- **Nullable results**: simple get queries return `null` when not found (not an error)

### Query Categories

1. **Simple Get**: single lookup by ID, return entity or null
2. **Search/Filter**: dynamic filters, pagination, scope restriction
3. **List**: join across tables, optional filters, pagination
4. **Transform**: call other queries, apply business logic (e.g., currency conversion)

## Parity Checks

For each query:

| Check ID                | Question                                                      |
| ----------------------- | ------------------------------------------------------------- |
| business_rule_impl      | Is each documented business rule implemented in code?         |
| process_flow_alignment  | Do code branches match documented process flow?               |
| input_type_coverage     | Does input interface include all documented inputs?           |
| return_type_accuracy    | Does return type match documented output?                     |
| generated_shell_pattern | Does query export `run` with a `.generated.ts` shell?         |
| input_interface_export  | Is the input interface exported?                              |
| permission_check        | Are documented permission requirements enforced in code?      |
| scope_authorization     | Is documented scope handling (company vs global) implemented? |
| pagination_pattern      | If documented as paginated, does code use pagination helpers? |
| null_handling           | Does code return null for not-found as documented?            |

### How to Check

1. List all business rules from query doc
2. Find corresponding validation/guard in query code
3. Trace each process flow branch to a code path
4. Compare input interface fields with doc input fields
5. Verify `.generated.ts` file exists and imports `run`
6. Check return type wraps result in object with descriptive keys
7. Verify permission checks match documented requirements
8. Verify scope filtering matches documented scope handling

## Common Gap Patterns

- **Unimplemented business rules**: Rule in doc but no validation code
- **Missing process branches**: Flowchart branch not in code logic
- **Missing generated shell**: No `.generated.ts` file for query
- **Input mismatch**: Doc input fields not in interface
- **Return format mismatch**: Code returns raw value instead of `{ entity }`
- **Missing permission check**: Doc requires permission but code doesn't check
- **Missing scope filter**: Doc describes scope restriction but code doesn't apply
- **Pagination mismatch**: Doc describes paginated query but code lacks pagination

## Output Format

Return a JSON object:

```json
{
  "check_type": "query-doc-code-parity",
  "module": "{{MODULE_NAME}}",
  "gaps": [...],
  "inconsistencies": [...],
  "summary": { "total_checks": N, "passed": N, "failed": N, "skipped": N, "claims_total": N }
}
```

Each `gaps[]` entry includes `"evidence": "<file:line>"` for pass/fail verdicts.

See [impl-parity-report-format.md](impl-parity-report-format.md) for field definitions.
