# Pathrule Pattern: NestJS Production Architecture (1.0.0)
# ::pathrule:package:nestjs

### [RULE] Make each module the owner of one capability  (path: /src/modules)
<!-- scope: folder | priority: high | strict -->

A Nest module is an ownership boundary. When every module imports every other module, providers become globally reachable, initialization order becomes fragile, and tests must boot half the application to exercise one capability.

- Group controllers, providers, and persistence adapters by capability, then export only the application service or token other modules are allowed to call.
- Treat `forwardRef` as a design alarm. Extract the shared contract or move orchestration to a higher-level module instead of adding reciprocal imports.
- Avoid global modules for feature behavior. Reserve global providers for truly universal infrastructure such as configuration, tracing, or a clock abstraction.
- Test a feature module with its explicit imports and overrides so undeclared dependencies fail in isolation rather than appearing only in the full application boot.

See /src/application for the adjacent decision or procedure that completes this constraint.

---

### [RULE] Validate and transform every transport boundary  (path: /src/common)
<!-- scope: folder | priority: high | strict -->

TypeScript types disappear at runtime, and Nest decorators do not make untrusted JSON valid. Invalid shapes must be rejected or transformed at the boundary before they reach services that rely on invariants.

- Enable a global validation pipe with an explicit allowlist and rejection policy; do not let unexpected properties flow into persistence or command objects.
- Validate route parameters and query values as their intended scalar types instead of accepting strings and relying on implicit coercion deep in the service.
- Apply the same runtime validation to queue messages, scheduled inputs, environment configuration, and webhook payloads, not only controller bodies.
- Map validation failures to a stable public error shape while retaining structured internal details for diagnostics without exposing secrets or stack traces.

See /src/application for the adjacent decision or procedure that completes this constraint.

---

### [MEMORY] Provider scope is a capacity decision  (path: /src/modules)

Changing one provider to request scope can pull every consumer above it into per-request instantiation. The cost is not visible at the decorator, so scope must be treated as a graph-wide capacity choice rather than a convenience for accessing request data.

- Keep stateless services singleton and pass actor, tenant, locale, or correlation context as method arguments when doing so keeps ownership clear.
- Use transient scope only when each injection site genuinely needs a separate stateful helper, and verify that lifecycle against retries and tests.
- If request scope is unavoidable, inspect which upstream providers inherit it and measure allocation and latency under representative concurrency.
- Do not store mutable per-request data on singleton providers. Use explicit context values or a bounded context mechanism with guaranteed cleanup.

See /src/common for the rule or workflow that puts this decision into practice.

---

### [MEMORY] Guards, pipes, interceptors, and filters have separate jobs  (path: /src/common)

Nest offers several extension points that can all run around a controller, but using them interchangeably makes execution order and test ownership impossible to reason about. Each stage should answer one kind of question.

- Guards decide whether the resolved actor may enter the handler. They should not perform the business transition or silently reshape the request.
- Pipes validate or transform an individual input before the handler. They do not fetch unrelated domain data or implement authorization policy.
- Interceptors wrap execution for cross-cutting behavior such as timing, serialization, caching, or tracing; they must preserve errors and cancellation.
- Exception filters translate known failures at the transport edge. They should not swallow unknown exceptions or turn every failure into a successful response envelope.

See /src/modules for the rule or workflow that puts this decision into practice.

---

### [MEMORY] Application services are independent of the active transport  (path: /src/application)

Nest decorators are convenient at controllers and consumers, but application logic coupled to `Request`, `Response`, acknowledgement objects, or transport exceptions cannot be reused safely and is difficult to retry.

- Translate transport input into a command before invoking the application service, including actor and idempotency context where required.
- Return a domain result or throw typed application failures. Let each adapter map those outcomes to HTTP status, message acknowledgement, or retry behavior.
- Inject repository and external-service ports through tokens so tests replace them without booting real network clients.
- Own the transaction around the complete use case and avoid holding it open while awaiting a slow remote dependency unless the consistency design explicitly requires it.

See /src/modules for the rule or workflow that puts this decision into practice.

---

### [SKILL] audit-nest-dependency-graph  (path: /)

---
name: audit-nest-dependency-graph
description: Audit a NestJS dependency graph after adding modules, providers, or a new transport adapter.
---

# Audit Nest Dependency Graph

Run this procedure when the affected surface changes, before the result is promoted to production. Record evidence for every step instead of accepting a plausible-looking result.

- [ ] Draw module imports and exports for the changed capability; identify reciprocal edges, global feature providers, and exports that expose implementation details.
- [ ] Trace every non-singleton provider upward through its consumers and estimate how many objects one request or message now creates.
- [ ] Inspect guards, pipes, interceptors, and filters for responsibilities that belong to application services or another lifecycle stage.
- [ ] Boot the feature module in isolation with test overrides and verify that every dependency is declared rather than inherited accidentally from the root app.
- [ ] Call the same application service from a non-HTTP adapter or a plain unit test and remove any request, response, or transport exception dependency that appears.

## Exit criteria

The change is complete only when the expected behavior, failure behavior, and rollback path have all been exercised with representative data. Preserve the evidence with the change so the next operator can repeat the same checks.
