Catalogue / nest-diagnosis-playbook
nest-diagnosis-playbook
Older skill: source not recordedSignedDiagnoses Nest application module boundaries, injection, requests, persistence, authentication, and tests using repository evidence. Use for Nest-specific implementation or debugging. Do not use as a substitute for specialist runtime, database-plan, frontend, or TypeScript-type analysis.--- name: nest-diagnosis-playbook description: >- Diagnoses Nest application module boundaries, injection, requests, persistence, authentication, and tests using repository evidence. Use for Nest-specific implementation or debugging. Do not use as a substitute for specialist runtime, database-plan, frontend, or TypeScript-type analysis. ---
Locate the fault and the installed contracts
Read package/lockfiles, nest-cli.json, tsconfig, bootstrap, modules, test configuration, database adapters, and authentication setup. Parse manifests rather than extracting versions with a fragile regex. Use one-shot diagnostics; avoid watch/serve modes. Preserve established naming, repository versus active-record data patterns, guards, and tests.
For a pure TypeScript type issue, Node runtime defect, database-plan optimization, or frontend problem, identify the appropriate specialist scope and pause Nest-specific changes. Do not assume a named subagent exists.
Require explicit confirmation before each of these: edits, file generation, package changes, test or build writes, service startup, database or config changes, and deployment. Independently installed verified tools are prerequisites; there is no remote installer or package-execution route.
Trace module construction first
For an unresolved constructor dependency, map the reported position to its parameter. Check @Injectable(), provider registration, exact injection token, importing module, exporting module, named database token, and barrel import order. Export a provider for consumers rather than accidentally listing the module itself where a service export was intended. Modules may legitimately re-export imported modules; do not ban that valid pattern.
Refactor circular responsibilities into a shared domain service/module first. Where a genuine unavoidable cycle remains, verify forwardRef on the applicable module/provider sides and test initialization; it can hide a design problem. Review default/request/transient scope and whether injection forces scope propagation.
import { DynamicModule, Inject, Injectable, Module } from '@nestjs/common';
export const ARCHIVE_OPTIONS = Symbol('ARCHIVE_OPTIONS');
type ArchiveOptions = { retentionDays: number };
@Injectable()
export class ArchivePolicy {
constructor(@Inject(ARCHIVE_OPTIONS) private readonly options: ArchiveOptions) {}
getRetentionDays() { return this.options.retentionDays; }
}
@Module({})
export class ArchiveModule {
static forRoot(options: ArchiveOptions): DynamicModule {
return {
module: ArchiveModule,
providers: [{ provide: ARCHIVE_OPTIONS, useValue: options }, ArchivePolicy],
exports: [ArchivePolicy],
};
}
}Use stable symbol tokens or deliberately documented tokens. A feature module composes domain/database/client imports, controllers, services/repositories, and intentional exports. Global modules should be rare and explicit.
Structural choices:
- simple controller/service modules — plain CRUD
- domain plus infrastructure modules — richer business logic
- shared exported modules — reusable logic across features
- separate message-pattern apps — microservices
HttpModuleclient modules — external API calls
Trace an HTTP request
Review middleware, guards, interceptor entry, pipes, handler, and interceptor response unwinding in that order. Exception filters handle uncaught exceptions; they are not a substitute for ordinary control flow. Correct route decorators/conflicts first, then DTO validation with compatible class-validator/class-transformer and ValidationPipe, then response serialization/interceptors.
Guards must use verified context and return or resolve authorization, or throw; await asynchronous work inside them. A composite decorator can combine applyDecorators, authentication/role guards, and role metadata, with each symbol defined in the actual project.
Catch HttpException in an exception filter using ArgumentsHost and the configured HTTP adapter; transform status safely and redact internals. Configure the Logger and propagate errors without unhandled promises.
Inspect configuration and authentication
Load ConfigModule with startup validation (for example, an already configured Joi schema), then resolve asynchronous integration configuration through ConfigService and imports. Missing JWT configuration should fail clearly without revealing values.
Authentication checks:
- strategy registration, and that JWT uses
passport-jwt, not the
local-password strategy
- signer/verifier key, algorithm, issuer/audience, and expiry policy agreement
- the
Authorization: Bearer ...shape and proxy forwarding
Decode sensitive tokens locally; never paste them into a public debugger or weaken production expiry to make a test pass.
Match auth to requirements: JWT/refresh for stateless APIs, approved session storage such as Redis for sessions, Passport provider strategies for OAuth, validated tenant claims for multi-tenancy, and reviewed mTLS for service-to-service identity. Authentication does not replace resource/tenant authorization.
Diagnose persistence errors below the headline
Per-adapter checks:
- TypeORM — entities registered with the proper module and injection
tokens; named connections consistent in configuration and in @InjectRepository/repository tokens.
- Mongoose — schema decorators, model registration, injected model name.
- Prisma — retain the established client/service lifecycle.
ORM choice depends on actual migrations, relational complexity, type requirements, document data, and legacy schema; no one library is universally best.
A connection error may originate in invalid entity metadata or an unsupported @Column type argument, not the network. Inspect decorators before changing credentials. Check SQLite absolute path, existing directory, permissions, and intended database. Never enable synchronization on valuable/production data as a repair. Review migrations, transactions, pooling, indexes, and connection cleanup.
Use bounded documented retryAttempts/retryDelay where supported and expose readiness/health accurately. Starting without a required database is unsafe unless the application explicitly supports degraded operation; catch-and-ignore cannot make broken persistence healthy. Test each named connection independently.
Construct focused tests
Use Test.createTestingModule with the unit under test and explicit useValue mocks. Compile and await the setup, retrieve the provider, and clean up the module or application afterward. Mock JwtService, outbound clients, and TypeORM repositories through the installed getRepositoryToken(Entity, connectionName) contract; mock DataSource when actually needed.
Constraints:
- never connect a real database from a unit test;
- optional mock helpers such as
createMockrequire an already verified
installed dependency;
- Bazel setups need their actual test configuration.
Run approved verification in order: typecheck, unit, integration, then e2e.
- API integration may use a disposable test database; user-flow e2e may use
Supertest.
- Validate business behavior with isolated mocks, load with configured
k6/Artillery, and security with approved scoped middleware or ZAP tests.
- Inspect package scripts before running them and ensure one-shot mode.
- CLI
nest infoand existing lint/build commands support diagnosis;
generation commands write files and require approval.
Improve performance from measurements
Profile heap growth with an approved isolated inspector and compare snapshots over time. Remove listeners/timers in onModuleDestroy, close data connections, and verify lifecycle cleanup. Reduce N+1 queries with request-scoped batching/DataLoader, measured indexes, and appropriate query builders. Use private development query logging.
Choose cache scope and invalidation: user-prefixed distributed Redis, bounded process-local global data, database result cache, CDN headers for static assets, or memoized computations. TTL follows volatility and authorization; cache interceptors must not mix private responses. Consider compression, large-response streaming, rate limits, and clustering when measurements justify them.
For a suspected version regression, produce a minimal local reproduction, compare supported installed versions/changelogs supplied locally, and propose an approved patch/downgrade with compatibility tests. Do not claim historical issue counts or security motives for generic errors as verified facts.
Review before closing
Confirm domain boundaries, provider exports/tokens/scopes, no new cycles, awaited operations, DTO/route correctness, guarded resource access, valid entity/model registration, named connections, retry/readiness behavior, mock isolation, cleanup, cache tenancy, and performance evidence. Report tests actually run, remaining integration gaps, and API/documentation changes.
Never
- Change code/configuration, generate files, start listeners, connect databases, or run external/state-changing actions without explicit confirmation.
- Fetch/install remote code, expose credentials/tokens, or use production synchronization to solve a test failure.
- Mask required-database failure as healthy or trust a misleading connection message without inspecting metadata.
- Introduce cycles, real database unit-test dependencies, or cross-user cache leakage.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 9.4 kB | 1a3490488a8c |
| examples.json | 2.2 kB | 16a8b2601002 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.1 Current | Not recorded | 6 Oct 2026 | |
| 1.0.0 | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.