@cassiomc1/forgeloop 1.12.0 → 1.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/.github/copilot-instructions.md +1 -1
  2. package/AGENTS.md +1 -1
  3. package/CLAUDE.md +1 -1
  4. package/CONTRIBUTING.md +90 -0
  5. package/DOCS_INDEX.md +13 -11
  6. package/ENG/c-development-eng.md +112 -0
  7. package/ENG/cpp-development-eng.md +109 -0
  8. package/ENG/dotnet-aspnetcore-development-eng.md +401 -0
  9. package/ENG/go-development-eng.md +103 -0
  10. package/ENG/java-development-eng.md +125 -0
  11. package/ENG/nodejs-backend-development-eng.md +605 -0
  12. package/ENG/php-development-eng.md +104 -0
  13. package/ENG/rust-development-eng.md +422 -0
  14. package/ENG/sql-development-eng.md +108 -0
  15. package/ENG/swift-development-eng.md +111 -0
  16. package/ENG/typescript-development-eng.md +108 -0
  17. package/GUIDE_ROUTER.md +418 -9
  18. package/QUALITY_SCORECARD.md +1 -0
  19. package/README.md +44 -33
  20. package/THIRD_PARTY_NOTICES.md +19 -7
  21. package/completions/_forgeloop +3 -3
  22. package/completions/forgeloop.bash +3 -3
  23. package/completions/forgeloop.fish +7 -0
  24. package/docs/AGENT_PROTOCOL_SUMMARY.md +55 -2
  25. package/docs/CLI_REFERENCE.md +28 -6
  26. package/docs/DOCUMENTATION_GUIDE.md +2 -1
  27. package/docs/GETTING_STARTED.md +59 -0
  28. package/docs/PACKAGE_CONTENTS.md +28 -14
  29. package/docs/RECIPES.md +23 -0
  30. package/docs/RELEASE_CHECKLIST.md +30 -2
  31. package/docs/TROUBLESHOOTING.md +100 -2
  32. package/docs/documentation-manifest.json +652 -0
  33. package/docs/protocol-requirements.json +77 -0
  34. package/package.json +19 -4
  35. package/schemas/routing-input.schema.json +1 -1
  36. package/scripts/CI_VALIDATORS.md +84 -11
  37. package/scripts/generate-agent-protocol-summary.mjs +36 -0
  38. package/src/commands/next.js +19 -7
  39. package/src/commands/task-create.js +84 -25
  40. package/src/commands/task-list.js +22 -2
  41. package/src/config/guides.json +44 -0
  42. package/src/core/build-script.js +151 -0
  43. package/src/core/c-cpp-project.js +143 -0
  44. package/src/core/cli-command-definitions.js +8 -1
  45. package/src/core/command-executors.js +5 -3
  46. package/src/core/command-input.js +140 -102
  47. package/src/core/contract-presets.js +82 -0
  48. package/src/core/error-codes.js +3 -3
  49. package/src/core/filesystem.js +1 -10
  50. package/src/core/go-project.js +206 -0
  51. package/src/core/java-project.js +403 -0
  52. package/src/core/multi-language-project.js +117 -0
  53. package/src/core/next-explanation.js +63 -0
  54. package/src/core/php-project.js +85 -0
  55. package/src/core/project-detection.js +1760 -52
  56. package/src/core/reconcile-closure.js +4 -1
  57. package/src/core/router.js +156 -3
  58. package/src/core/rust-project.js +400 -0
  59. package/src/core/sql-project.js +141 -0
  60. package/src/core/swift-project.js +200 -0
  61. package/src/core/typescript-project.js +349 -0
  62. package/src/core/xml-structure.js +123 -0
@@ -0,0 +1,605 @@
1
+ ---
2
+ name: nodejs-backend-development-eng
3
+ language: en
4
+ description: "Specialist guidance for architecture, implementation, testing, security, performance, observability, and release of production Node.js backend services and workers."
5
+ version: "2026.09"
6
+ last-reviewed: "2026-09-11"
7
+ guide-id: nodejs
8
+ requires-gates:
9
+ - threat-boundary
10
+ completion-evidence:
11
+ - nodejs-validation
12
+ ---
13
+
14
+ # Node.js Backend Development Engineering Guide
15
+
16
+ > Production-oriented guidance for Node.js APIs, HTTP services, workers,
17
+ > command-line backends, and event-driven applications.
18
+ >
19
+ > This guide is activated only by bounded structural evidence for an affected
20
+ > project root: an ordinary `package.json` with an allowlisted runtime backend
21
+ > dependency, a direct Node runtime script, or a valid runtime-surface source
22
+ > file that imports a Node server/network built-in. A `package.json` alone, a
23
+ > frontend package, a lockfile, `engines.node`, `@types/node`, a Dockerfile, or
24
+ > CI setup alone is not backend evidence. Node.js execution used only for build,
25
+ > test, or configuration tooling is not sufficient backend/runtime evidence.
26
+ > Detection is read-only, bounded, non-networking, and never executes package
27
+ > scripts or source code.
28
+ >
29
+ > This guide complements [`clean-code-eng.md`](./clean-code-eng.md) for
30
+ > maintainability, [`test-code-eng.md`](./test-code-eng.md) for verification,
31
+ > [`sec-code-eng.md`](./sec-code-eng.md) for trust boundaries,
32
+ > [`perf-code-eng.md`](./perf-code-eng.md) for measured optimization, and
33
+ > [`documentation-quality-eng.md`](./documentation-quality-eng.md) for public
34
+ > technical documentation.
35
+ >
36
+ > Tooling policy: inspect the repository and use already-available tools first.
37
+ > Do not install Node versions, package managers, dependencies, databases,
38
+ > containers, browsers, or global utilities merely to satisfy a check. If a
39
+ > required check cannot run, record `NOT_VERIFIED` or `BLOCKED`; never claim it
40
+ > passed.
41
+
42
+ ## 1. Mission and activation contract
43
+
44
+ The Node.js specialist exists to make backend changes that are:
45
+
46
+ - correct for the repository's declared Node runtime and module system;
47
+ - explicit about request, process, worker, persistence, and external-service
48
+ boundaries;
49
+ - safe when inputs, dependencies, configuration, and network peers are
50
+ untrusted;
51
+ - testable at the narrowest level that proves the changed behavior and at
52
+ broader levels where integration risk requires it;
53
+ - observable under success, failure, timeout, retry, cancellation, and
54
+ shutdown paths;
55
+ - measurable when throughput, latency, memory, startup, queue depth, or
56
+ connection cost is relevant;
57
+ - deployable with evidence from the exact code, configuration, and package
58
+ graph that will ship.
59
+
60
+ Do not select a framework, package manager, ORM, transport, or deployment
61
+ model because it is fashionable. Prefer repository truth and the smallest
62
+ coherent change.
63
+
64
+ ### Primary evidence
65
+
66
+ The project detector uses three independent strong signals:
67
+
68
+ 1. A valid `package.json` contains a runtime backend dependency from the
69
+ bounded allowlist: `express`, `fastify`, `@nestjs/core`, `koa`, or
70
+ `@hapi/hapi`. Runtime dependencies are read from `dependencies` and
71
+ `optionalDependencies`; development-only dependencies do not activate the
72
+ specialist.
73
+ 2. A valid `package.json` contains a direct script whose command begins with
74
+ `node` or `node.exe`, including ordinary Node flags such as `--watch` or
75
+ `--env-file`. The detector does not follow `npm`, `npx`, arbitrary wrappers,
76
+ substring matches, or prose containing the word `node`.
77
+ 3. A bounded JavaScript or TypeScript source scan finds a narrow import,
78
+ re-export, `require`, or dynamic import of `node:http`, `node:https`,
79
+ `node:http2`, `node:net`, `node:tls`, or `node:dgram`. Legacy bare
80
+ equivalents are accepted only in the same narrow syntactic forms. Source-
81
+ only confirmation also requires a plausible runtime application surface,
82
+ such as `src`, `lib`, `server`, `worker`, `service`, `api`, `backend`, or a
83
+ recognized runtime-entry filename; generic tooling/configuration surfaces
84
+ do not qualify.
85
+
86
+ The source rule is deliberately conservative. Comments and template-literal
87
+ text do not count; `import type`, `export type`, `import { type X }`, and
88
+ `export { type X }` do not count when every specifier is type-only; mixed
89
+ declarations count only when a runtime value specifier is safely recognized;
90
+ unsupported complex declarations fail closed. Declaration files (`*.d.ts`,
91
+ `*.d.mts`, and `*.d.cts`) do not count. Source beneath `test`, `tests`,
92
+ `__tests__`, `fixtures`, `mocks`, `examples`, `docs`, `coverage`, `dist`,
93
+ `build`, `scripts`, `tools`, `tooling`, `config`, `configs`, `codegen`,
94
+ `generators`, `node_modules`, `.next`, `.turbo`, or Storybook directories does
95
+ not provide runtime evidence. Common `*.config.js`, `*.config.mjs`,
96
+ `*.config.cjs`, `*.config.ts`, `*.config.mts`, and `*.config.cts` files are
97
+ tooling/configuration surfaces and do not provide source-only evidence.
98
+ Bounded source and manifest reads are discovery signals only. Confirmed nested
99
+ Flutter, .NET, and Node project roots form framework-agnostic ownership
100
+ boundaries for scans, claims, and shared files. Runtime re-exports count when
101
+ they contain at least one safely classified value specifier because the guide
102
+ covers Node.js server/runtime library surfaces as well as services and workers.
103
+
104
+ `engines.node`, `type`, `packageManager`, workspaces, lockfiles, `.nvmrc`,
105
+ `.node-version`, `@types/node`, TypeScript, `tsx`, Docker, and CI are
106
+ supporting context. They can guide scope matching but cannot replace primary
107
+ evidence. Malformed or oversized manifests fail closed.
108
+
109
+ ## 2. Authority, discovery, and scope
110
+
111
+ Resolve conflicts in this order:
112
+
113
+ 1. Platform and safety rules.
114
+ 2. The user's latest explicit request.
115
+ 3. Repository-local instructions, including `AGENTS.md`, `PROJECT_PROFILE.md`,
116
+ `LOOP_ENGINEERING.md`, and nested instructions.
117
+ 4. Actual manifests, source, tests, CI, deployment configuration, and runtime
118
+ evidence.
119
+ 5. Existing public contracts and established architecture.
120
+ 6. This guide.
121
+ 7. Official documentation for the pinned Node version and framework.
122
+ 8. Community examples.
123
+
124
+ Before implementation, inspect the smallest complete set of sources that can
125
+ explain the change:
126
+
127
+ - bounded `package.json` files from the affected package root and confirmed
128
+ nested package roots;
129
+ - the lockfile and package-manager configuration that owns that root;
130
+ - `.nvmrc`, `.node-version`, `.tool-versions`, CI runtime setup, and container
131
+ base images when they affect the executable environment;
132
+ - the application entry point, route modules, middleware, adapters, workers,
133
+ jobs, event handlers, and shutdown hooks;
134
+ - configuration schemas, environment loaders, secret references, and
135
+ deployment manifests;
136
+ - persistence registrations, migrations, repositories, transactions, and
137
+ connection-pool settings;
138
+ - authentication, authorization, CORS, CSRF, rate limiting, request-size,
139
+ proxy, and network-boundary configuration;
140
+ - unit, integration, contract, load, smoke, and operational tests;
141
+ - release notes and API documentation for changed public behavior.
142
+
143
+ Detection is discovery input, not proof that the service is healthy. A route
144
+ claim that names a nested package, lockfile, configuration file, source file,
145
+ or workspace root must activate only the confirmed Node project whose scope
146
+ contains that claim. A root workspace coordinator may select confirmed Node
147
+ descendants; unrelated frontend packages remain isolated.
148
+
149
+ ## 3. Runtime and module-system decisions
150
+
151
+ Record the actual runtime range before changing APIs:
152
+
153
+ - inspect `engines.node`, version files, CI matrices, container images, and
154
+ release policy together;
155
+ - preserve the supported major unless a runtime migration is an explicit
156
+ deliverable;
157
+ - verify new built-ins and platform APIs against the oldest supported runtime,
158
+ not only the local `node --version`;
159
+ - treat ESM/CommonJS interop, package `exports`, conditional exports, and
160
+ test-runner behavior as public compatibility concerns;
161
+ - keep package-manager, lockfile, and workspace changes intentional and
162
+ reproducible.
163
+
164
+ For ESM, use explicit file extensions where the repository requires them,
165
+ avoid deep imports that bypass package exports, and keep import-time side
166
+ effects small. For CommonJS, keep `require` boundaries consistent with the
167
+ existing package contract and do not mix module systems casually. For either
168
+ system, do not hide asynchronous initialization behind an import side effect.
169
+
170
+ ## 4. Architecture and process lifecycle
171
+
172
+ ### Request and process boundaries
173
+
174
+ Separate transport concerns from application decisions:
175
+
176
+ - route handlers translate HTTP input into a validated application command;
177
+ - application services enforce use-case invariants and coordinate boundaries;
178
+ - adapters own framework, database, filesystem, queue, and external-service
179
+ details;
180
+ - serialization and status-code decisions remain at the transport boundary;
181
+ - domain errors are not allowed to leak stack traces, SQL, tokens, or internal
182
+ topology to clients.
183
+
184
+ Keep the composition root explicit. Construct the logger, configuration,
185
+ clients, pools, repositories, queues, and server in a controlled startup path.
186
+ Make startup failure visible and make shutdown bounded and observable.
187
+
188
+ ### Modular monoliths and service boundaries
189
+
190
+ Use modules that own a coherent capability rather than folders that mirror
191
+ technical layers without responsibility. Define imports between modules by
192
+ contract. Avoid importing a database model, framework request object, or
193
+ process-global mutable singleton across every feature.
194
+
195
+ If the repository is a monolith, do not create a distributed system merely to
196
+ hide coupling. If a service boundary is real, document the contract,
197
+ ownership, timeout, retry, idempotency, versioning, and failure behavior.
198
+
199
+ ### Workers, jobs, and command-line processes
200
+
201
+ Workers and CLIs still require production discipline:
202
+
203
+ - parse arguments and environment values as untrusted input;
204
+ - make retries bounded and idempotent;
205
+ - acknowledge queue messages only after durable work completes;
206
+ - handle cancellation and termination signals;
207
+ - avoid overlapping work unless concurrency is explicit and safe;
208
+ - emit a stable exit status and actionable structured logs;
209
+ - make replay, dead-letter, and partial-failure behavior testable.
210
+
211
+ ## 5. JavaScript and TypeScript implementation
212
+
213
+ Use the repository's established language and compiler policy. TypeScript is a
214
+ tool for expressing boundaries, not permission to rewrite a JavaScript module
215
+ without need.
216
+
217
+ - validate external data at the boundary before it enters typed code;
218
+ - prefer narrow interfaces and explicit return types for public adapters;
219
+ - keep `unknown` at trust boundaries and narrow it deliberately;
220
+ - avoid `any`, unsafe casts, ambient mutable state, and hidden coercion;
221
+ - preserve error causes with `new Error(message, { cause })` where supported;
222
+ - avoid floating promises; make ownership of every asynchronous operation
223
+ clear;
224
+ - use `AbortSignal` for cancellable I/O where the dependency supports it;
225
+ - use `Promise.all` only when concurrent failure and resource pressure are
226
+ understood; use bounded concurrency for collections;
227
+ - do not rely on timing, object-key order, locale, or implicit timezone in
228
+ protocol behavior.
229
+
230
+ Linting and formatting are part of the repository contract. Do not weaken a
231
+ rule globally to make one change convenient; document a narrowly scoped
232
+ exception when the existing rule cannot express the correct code.
233
+
234
+ ## 6. Framework and transport guidance
235
+
236
+ ### Express
237
+
238
+ Keep middleware ordering explicit. Register request IDs and safe logging before
239
+ business middleware, parsers before routes that need them, authentication
240
+ before protected routes, and the error handler last. Set body-size, parameter,
241
+ header, timeout, and proxy-trust policy deliberately. Do not treat
242
+ `req.body`, `req.params`, `req.query`, or `req.headers` as validated data.
243
+
244
+ ### Fastify
245
+
246
+ Use schemas for request and response boundaries and keep route registration
247
+ modular. Understand hook order, encapsulation, serializer behavior, and the
248
+ consequences of decorating the request or server. Do not bypass the framework's
249
+ validation and serialization pipeline without measuring the compatibility and
250
+ security impact.
251
+
252
+ ### NestJS
253
+
254
+ Keep modules, providers, guards, pipes, interceptors, and filters aligned with
255
+ their responsibilities. Validate DTOs at the boundary, keep provider scopes
256
+ intentional, and make dynamic-module configuration explicit. Avoid leaking
257
+ request-scoped dependencies into singleton state or placing business rules in
258
+ decorator-heavy infrastructure where they cannot be tested directly.
259
+
260
+ ### Koa and hapi
261
+
262
+ For Koa, make middleware `await next()` behavior and error propagation
263
+ explicit; a missing `await` can silently change the response lifecycle. For
264
+ hapi, keep route options, payload limits, validation, authentication, and
265
+ response schemas close to the route contract. In both frameworks, test
266
+ ordering, rejection, timeout, and malformed-input behavior.
267
+
268
+ ### Raw Node HTTP and other adapters
269
+
270
+ When using `node:http` or another low-level transport, explicitly handle:
271
+
272
+ - header and body limits;
273
+ - request cancellation and socket errors;
274
+ - content type and character encoding;
275
+ - streaming backpressure;
276
+ - timeout and keep-alive policy;
277
+ - status, headers, and response termination exactly once;
278
+ - malformed requests and partial reads.
279
+
280
+ Do not build a second ad hoc framework in route handlers. Extract reusable
281
+ parsing, validation, and response contracts when the low-level adapter grows.
282
+
283
+ ## 7. Configuration, environments, and secrets
284
+
285
+ Configuration is an input contract. Load it once at the composition root,
286
+ validate it against an explicit schema, normalize safe defaults, and pass the
287
+ result to components rather than reading `process.env` throughout the code.
288
+
289
+ - distinguish required values, optional values, and environment-specific
290
+ defaults;
291
+ - reject invalid ports, URLs, durations, enum values, and pool sizes at
292
+ startup;
293
+ - keep secret values out of logs, errors, snapshots, receipts, and test
294
+ fixtures;
295
+ - never commit `.env` files or use a repository file as a secret store;
296
+ - make development defaults obviously non-production;
297
+ - document which system owns secret injection and rotation;
298
+ - test missing, malformed, and conflicting configuration without printing the
299
+ secret itself.
300
+
301
+ When a configuration value controls a trust boundary—proxy trust, CORS,
302
+ redirects, callback URLs, TLS verification, debug output, or authorization—do
303
+ not use a permissive fallback merely to keep startup alive.
304
+
305
+ ## 8. HTTP API and data contracts
306
+
307
+ Treat an API as a compatibility surface:
308
+
309
+ - define accepted methods, content types, encodings, size limits, and status
310
+ codes;
311
+ - validate path, query, header, and body inputs with a single authoritative
312
+ schema or parser;
313
+ - make optional, nullable, empty, and missing values distinct where the
314
+ contract requires it;
315
+ - return stable machine-readable error codes and safe human messages;
316
+ - avoid reflecting arbitrary input into headers, HTML, logs, or error details;
317
+ - serialize only fields intentionally exposed by the public contract;
318
+ - document pagination, sorting, filtering, idempotency keys, and concurrency
319
+ behavior;
320
+ - reject ambiguous duplicate parameters and conflicting content negotiation.
321
+
322
+ For changes to public behavior, add or update a contract test and record the
323
+ compatibility decision. A successful unit test of a controller does not prove
324
+ the wire contract.
325
+
326
+ ## 9. Middleware, hooks, and cross-cutting behavior
327
+
328
+ Cross-cutting behavior must have an observable order and owner. For every
329
+ middleware or hook, document whether it can reject, mutate, short-circuit,
330
+ retry, stream, or call downstream code more than once.
331
+
332
+ At minimum, reason about:
333
+
334
+ - request correlation and structured logging;
335
+ - authentication and authorization;
336
+ - input parsing and validation;
337
+ - rate limiting and abuse controls;
338
+ - timeout and cancellation propagation;
339
+ - compression and response buffering;
340
+ - CORS, CSRF, and security headers;
341
+ - metrics and tracing without sensitive-cardinality explosions;
342
+ - centralized error mapping and safe response serialization.
343
+
344
+ Do not add a global hook for a local rule. Do not let a convenience middleware
345
+ silently trust forwarded headers, disable TLS verification, or swallow a
346
+ rejection.
347
+
348
+ ## 10. Persistence, external services, and state
349
+
350
+ Make resource ownership explicit:
351
+
352
+ - create connection pools and clients once per process unless the library
353
+ requires another lifecycle;
354
+ - close or drain them on shutdown;
355
+ - set connection, query, and request timeouts separately;
356
+ - bound retries and preserve idempotency across retries;
357
+ - keep transactions around the smallest unit that needs atomicity;
358
+ - make migration ownership and rollback expectations explicit;
359
+ - do not mix an external side effect into a database transaction without an
360
+ outbox, compensation, or otherwise documented consistency strategy;
361
+ - avoid N+1 queries and unbounded result sets;
362
+ - redact connection strings, authorization headers, and provider error details.
363
+
364
+ For third-party APIs, define the contract, timeout, retry budget, circuit or
365
+ backoff policy, rate-limit behavior, and test double at the adapter boundary.
366
+ Never allow a provider outage to become an unbounded request queue.
367
+
368
+ ## 11. Security and trust boundaries
369
+
370
+ Use [`sec-code-eng.md`](./sec-code-eng.md) as the complete security guide.
371
+ Node.js-specific review must still cover:
372
+
373
+ - prototype pollution through deep merge, query parsing, or unsafe object
374
+ assignment;
375
+ - path traversal and unsafe filesystem paths;
376
+ - command injection through child-process arguments or shell invocation;
377
+ - SSRF through user-controlled URLs, redirects, DNS resolution, proxies, or
378
+ cloud metadata endpoints;
379
+ - request smuggling, ambiguous transfer encoding, header injection, and
380
+ parser differentials at proxy boundaries;
381
+ - ReDoS and unbounded parsing, decompression, JSON, multipart, and regex work;
382
+ - insecure deserialization and unsafe dynamic evaluation;
383
+ - token, cookie, session, CORS, CSRF, and authorization mistakes;
384
+ - WebSocket origin, authentication, message-size, and connection-lifetime
385
+ controls;
386
+ - dependency confusion, typosquatting, lifecycle scripts, lockfile drift, and
387
+ compromised transitive packages.
388
+
389
+ Prefer parameterized APIs and argument arrays over shell strings. Allowlist
390
+ outbound destinations when the product permits it. Resolve and validate URLs
391
+ before connecting, cap redirects, and test private-address and DNS-rebinding
392
+ cases. Set body, header, upload, decompression, and queue limits before adding
393
+ feature behavior.
394
+
395
+ Do not claim a security check merely because a package is present. Capture the
396
+ exact check, input boundary, result, and limitations.
397
+
398
+ ## 12. Authentication, authorization, and sessions
399
+
400
+ Authentication answers who a principal is; authorization answers what that
401
+ principal may do in this context. Keep them separate and test both allow and
402
+ deny paths.
403
+
404
+ - verify issuer, audience, algorithm, key rotation, expiry, not-before, and
405
+ clock-skew policy for signed tokens;
406
+ - keep session identifiers opaque, rotated, bounded, and revocable;
407
+ - use secure cookie attributes appropriate to the deployment topology;
408
+ - do not trust user-provided identity, role, tenant, or ownership fields;
409
+ - enforce object-level authorization after resource lookup and before output;
410
+ - make tenant, organization, and account boundaries explicit;
411
+ - rate-limit login, recovery, token exchange, and high-cost operations;
412
+ - avoid logging credentials, tokens, authorization headers, or sensitive claims.
413
+
414
+ Test expired, malformed, replayed, cross-tenant, insufficient-scope, and
415
+ missing-credential requests. A happy-path login test is not authorization
416
+ coverage.
417
+
418
+ ## 13. Errors, logging, metrics, and tracing
419
+
420
+ Define an error taxonomy that distinguishes client input, authentication,
421
+ authorization, dependency, persistence, cancellation, timeout, and programmer
422
+ failures. Map internal failures to safe transport responses at one boundary.
423
+
424
+ Structured logs should include a correlation ID, operation, outcome, duration,
425
+ and stable error code. They should not include secrets or uncontrolled user
426
+ content. Use bounded field lengths and avoid high-cardinality labels.
427
+
428
+ Metrics should answer operational questions: request rate, error rate, latency
429
+ distribution, saturation, queue depth, retry count, pool utilization, and
430
+ shutdown duration. Traces should preserve causality across outbound calls and
431
+ queues without exporting sensitive payloads. Test that failures emit enough
432
+ context to diagnose them without exposing internals.
433
+
434
+ ## 14. Performance, concurrency, and backpressure
435
+
436
+ Measure before optimizing. Establish a representative workload, runtime,
437
+ hardware or container limits, baseline, and acceptance threshold.
438
+
439
+ - keep the event loop free of unbounded synchronous CPU or filesystem work;
440
+ - stream large inputs and outputs when the contract permits it;
441
+ - bound concurrency for fan-out and batch work;
442
+ - propagate backpressure through streams and queues;
443
+ - use timeouts and cancellation for every external or potentially blocking
444
+ operation;
445
+ - watch memory retention from closures, caches, listeners, timers, and request
446
+ context;
447
+ - use connection pools and keep-alive settings deliberately;
448
+ - distinguish cold-start, warm-start, steady-state, and overload behavior.
449
+
450
+ Do not convert an asynchronous operation to synchronous I/O to simplify a test
451
+ or add a cache without an invalidation and memory policy. Performance evidence
452
+ must identify the measured path and environment; a local timing anecdote is not
453
+ a production claim.
454
+
455
+ ## 15. Queues, events, WebSockets, and streams
456
+
457
+ For queues and events, specify delivery semantics, message identity, ordering,
458
+ retry/dead-letter behavior, visibility timeout, deduplication, and schema
459
+ versioning. Consumers should be idempotent and tolerant of redelivery.
460
+
461
+ For WebSockets and long-lived connections, define authentication lifetime,
462
+ origin policy, heartbeat, idle timeout, message-size limit, per-connection
463
+ memory, backpressure, reconnect, and shutdown behavior. Do not treat a socket
464
+ as a trusted authenticated session forever.
465
+
466
+ For streams, handle partial reads, aborts, errors, backpressure, and cleanup.
467
+ Test disconnects and downstream slowness, not just a complete happy stream.
468
+
469
+ ## 16. Testing and verification
470
+
471
+ Choose tests by the risk they prove:
472
+
473
+ - pure unit tests for parsers, validation, policies, error mapping, and
474
+ deterministic decisions;
475
+ - integration tests for middleware order, composition-root wiring, database
476
+ boundaries, queues, and external adapters;
477
+ - contract tests for HTTP status, headers, schemas, errors, pagination, and
478
+ compatibility;
479
+ - adversarial tests for malformed JSON, oversized inputs, unknown fields,
480
+ prototype keys, path traversal, SSRF, timeouts, cancellation, retries,
481
+ duplicate delivery, and partial shutdown;
482
+ - load or benchmark tests only when a measurable performance requirement exists;
483
+ - smoke tests against the packaged or built artifact when packaging is part of
484
+ the change.
485
+
486
+ Tests must not execute untrusted package scripts as a side effect of detection.
487
+ Use isolated temporary projects for detector tests. Cover:
488
+
489
+ - Express, Fastify, NestJS, raw HTTP, CommonJS, and ESM positive evidence;
490
+ - worker or CLI `node` scripts;
491
+ - React/Vite, Next-only, engines-only, `@types/node`-only, devDependency-only,
492
+ Docker-only, CI-only, lockfile-only, malformed, and oversized negatives;
493
+ - nested package roots, workspace-root claims, shared lockfiles, mixed
494
+ Flutter/.NET/Node repositories, symlinks, and traversal budgets;
495
+ - documentation/UI-copy/mobile-only work exclusions and explicit no-match
496
+ claims.
497
+
498
+ Run focused tests first, then proportional regression checks. Record the exact
499
+ command and observed result. Missing tools are `NOT_VERIFIED`, not green.
500
+
501
+ ## 17. Deployment, containers, and CI
502
+
503
+ Align local, CI, container, and production runtimes. Pin or constrain the Node
504
+ major intentionally, use a reproducible lockfile, and install dependencies with
505
+ the package manager selected by the repository.
506
+
507
+ - use a non-root runtime user where the deployment supports it;
508
+ - keep build-time and runtime files separate;
509
+ - do not copy secrets into images or artifacts;
510
+ - use a minimal production dependency set without hiding native runtime needs;
511
+ - provide health and readiness checks that reflect real dependencies;
512
+ - implement graceful shutdown for the orchestrator's termination window;
513
+ - configure resource limits and observe event-loop, memory, and pool health;
514
+ - ensure CI checks the same package and generated artifacts that will ship.
515
+
516
+ Container or CI configuration alone does not prove that a project is a Node
517
+ backend, but it is important corroborating evidence after the affected package
518
+ has been confirmed.
519
+
520
+ ## 18. Documentation and operational handoff
521
+
522
+ Document the reader's job, not the implementation trivia. For an API or worker,
523
+ cover:
524
+
525
+ - startup prerequisites and supported runtime;
526
+ - configuration names, types, defaults, and secret ownership;
527
+ - endpoints or job contracts, authentication, limits, and error codes;
528
+ - local development and focused verification commands;
529
+ - migrations, rollback, replay, dead-letter, and recovery procedures;
530
+ - health, readiness, metrics, logs, traces, and alert meanings;
531
+ - compatibility, deprecation, and versioning policy.
532
+
533
+ Keep examples runnable or label them clearly as pseudocode. Redact secrets and
534
+ avoid copying production identifiers. Update docs when behavior, configuration,
535
+ contracts, operational ownership, or package boundaries change.
536
+
537
+ ## 19. Anti-patterns and failure modes
538
+
539
+ Reject these shortcuts during review:
540
+
541
+ - classifying any `package.json` as a backend;
542
+ - treating `engines.node`, TypeScript, `@types/node`, Docker, or CI as primary
543
+ runtime evidence;
544
+ - allowing a frontend, workspace coordinator, or nested package to activate a
545
+ sibling backend guide;
546
+ - executing package scripts, installing dependencies, importing source, or
547
+ making network calls during project detection;
548
+ - reading unbounded manifests or source files, treating comments/type-only
549
+ declarations or build/config tooling as runtime evidence, or following
550
+ symlinks outside the target;
551
+ - placing business logic in framework middleware or a controller until it is
552
+ impossible to test without the framework;
553
+ - swallowing promise rejections, timeout, abort, or shutdown errors;
554
+ - retrying non-idempotent work without an idempotency contract;
555
+ - logging request bodies, credentials, tokens, or provider responses by default;
556
+ - claiming performance, security, deployment, or production readiness from a
557
+ unit test or a local build alone.
558
+
559
+ ## 20. Node.js backend Definition of Done
560
+
561
+ Before completion, confirm the applicable items:
562
+
563
+ - [ ] The affected package and supported runtime/module system are identified.
564
+ - [ ] The route is based on primary evidence and explicit claim scope.
565
+ - [ ] Inputs, configuration, authentication, authorization, and outbound
566
+ boundaries are validated and bounded.
567
+ - [ ] Errors, timeouts, cancellation, retries, shutdown, and partial failure
568
+ behavior are explicit.
569
+ - [ ] Focused unit, integration, contract, and adversarial tests cover the
570
+ changed risk; missing tooling is reported honestly.
571
+ - [ ] Performance claims have a baseline and measurement when relevant.
572
+ - [ ] Logs, metrics, traces, health, and operational recovery are adequate for
573
+ the changed path.
574
+ - [ ] Documentation and package/lockfile changes match the shipped behavior.
575
+ - [ ] The exact final revision, checks, limitations, and publication/deployment
576
+ state are reported separately.
577
+
578
+ ## 21. Sources and further reading
579
+
580
+ Prefer the documentation for the pinned versions in the repository. Latest or
581
+ Current Node.js documentation is not an automatic production target: establish
582
+ the repository's runtime truth first, use documentation for the matching major,
583
+ and do not migrate merely because a newer Current release exists. For greenfield
584
+ production services, prefer a supported LTS release unless a documented
585
+ requirement justifies Current.
586
+
587
+ Useful primary references include:
588
+
589
+ - [Node.js documentation](https://nodejs.org/docs/latest/api/)
590
+ - [Node.js LLM documentation index](https://nodejs.org/docs/latest-v26.x/llms.txt)
591
+ - [Node.js release policy](https://nodejs.org/en/about/previous-releases)
592
+ - [Node.js HTTP](https://nodejs.org/api/http.html), [HTTP/2](https://nodejs.org/api/http2.html),
593
+ [net](https://nodejs.org/api/net.html), and [TLS](https://nodejs.org/api/tls.html)
594
+ - [Node.js package exports](https://nodejs.org/api/packages.html)
595
+ - [Express](https://expressjs.com/), [Fastify](https://fastify.dev/docs/latest/),
596
+ [NestJS](https://docs.nestjs.com/), [Koa](https://koajs.com/), and
597
+ [hapi](https://hapi.dev/)
598
+ - [TypeScript handbook](https://www.typescriptlang.org/docs/handbook/intro.html)
599
+ - [OWASP API Security Top 10](https://owasp.org/API-Security/editions/2023/en/0x11-t10/)
600
+ - [OWASP SSRF prevention](https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html)
601
+ - [OWASP Node.js security guidance](https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet.html)
602
+ - [RFC 9110 HTTP semantics](https://www.rfc-editor.org/rfc/rfc9110)
603
+
604
+ These sources inform implementation decisions; they do not replace the
605
+ repository's pinned runtime, local policy, tests, or ForgeLoop evidence.