prizmkit 1.1.154 → 1.1.156

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 (164) hide show
  1. package/bundled/VERSION.json +3 -3
  2. package/bundled/adapters/codex/skill-adapter.js +1 -1
  3. package/bundled/adapters/pi/skill-adapter.js +2 -1
  4. package/bundled/dev-pipeline/.env.example +2 -6
  5. package/bundled/dev-pipeline/README.md +21 -27
  6. package/bundled/dev-pipeline/prizmkit_runtime/checkpoint_state.py +341 -15
  7. package/bundled/dev-pipeline/prizmkit_runtime/cli.py +0 -3
  8. package/bundled/dev-pipeline/prizmkit_runtime/daemon.py +1 -15
  9. package/bundled/dev-pipeline/prizmkit_runtime/gitops.py +48 -14
  10. package/bundled/dev-pipeline/prizmkit_runtime/runner_classification.py +50 -2
  11. package/bundled/dev-pipeline/prizmkit_runtime/runner_models.py +0 -9
  12. package/bundled/dev-pipeline/prizmkit_runtime/runner_prompts.py +3 -3
  13. package/bundled/dev-pipeline/prizmkit_runtime/runners.py +120 -22
  14. package/bundled/dev-pipeline/prizmkit_runtime/runtime_commit.py +482 -0
  15. package/bundled/dev-pipeline/prizmkit_runtime/test_result.py +64 -11
  16. package/bundled/dev-pipeline/scripts/generate-bootstrap-prompt.py +145 -367
  17. package/bundled/dev-pipeline/scripts/generate-bugfix-prompt.py +91 -62
  18. package/bundled/dev-pipeline/scripts/generate-refactor-prompt.py +105 -69
  19. package/bundled/dev-pipeline/scripts/prompt_framework.py +36 -41
  20. package/bundled/dev-pipeline/scripts/update-bug-status.py +1 -4
  21. package/bundled/dev-pipeline/scripts/update-checkpoint.py +61 -13
  22. package/bundled/dev-pipeline/scripts/update-feature-status.py +1 -4
  23. package/bundled/dev-pipeline/scripts/update-refactor-status.py +1 -4
  24. package/bundled/dev-pipeline/templates/bootstrap-prompt.md +22 -27
  25. package/bundled/dev-pipeline/templates/bootstrap-tier3.md +71 -104
  26. package/bundled/dev-pipeline/templates/bugfix-bootstrap-prompt.md +59 -111
  27. package/bundled/dev-pipeline/templates/refactor-bootstrap-prompt.md +37 -72
  28. package/bundled/dev-pipeline/templates/sections/artifact-manifest.md +39 -0
  29. package/bundled/dev-pipeline/templates/sections/bugfix-critical-paths.md +3 -1
  30. package/bundled/dev-pipeline/templates/sections/bugfix-phase-commit-report.md +8 -25
  31. package/bundled/dev-pipeline/templates/sections/bugfix-phase-diagnose-plan.md +3 -3
  32. package/bundled/dev-pipeline/templates/sections/bugfix-phase-implement.md +2 -2
  33. package/bundled/dev-pipeline/templates/sections/bugfix-phase-review.md +3 -3
  34. package/bundled/dev-pipeline/templates/sections/bugfix-phase-test.md +2 -2
  35. package/bundled/dev-pipeline/templates/sections/bugfix-reminders.md +4 -4
  36. package/bundled/dev-pipeline/templates/sections/bugfix-session-context.md +0 -1
  37. package/bundled/dev-pipeline/templates/sections/checkpoint-system.md +7 -4
  38. package/bundled/dev-pipeline/templates/sections/context-budget-rules.md +14 -27
  39. package/bundled/dev-pipeline/templates/sections/feature-completion-summary.md +20 -0
  40. package/bundled/dev-pipeline/templates/sections/phase-commit-full.md +8 -71
  41. package/bundled/dev-pipeline/templates/sections/phase-implement-full.md +7 -7
  42. package/bundled/dev-pipeline/templates/sections/phase-prizmkit-test.md +3 -3
  43. package/bundled/dev-pipeline/templates/sections/phase-review-full.md +4 -4
  44. package/bundled/dev-pipeline/templates/sections/phase-specify-plan-full.md +5 -17
  45. package/bundled/dev-pipeline/templates/sections/refactor-critical-paths.md +3 -1
  46. package/bundled/dev-pipeline/templates/sections/refactor-phase-commit-report.md +10 -23
  47. package/bundled/dev-pipeline/templates/sections/refactor-phase-implement.md +2 -2
  48. package/bundled/dev-pipeline/templates/sections/refactor-phase-plan.md +2 -2
  49. package/bundled/dev-pipeline/templates/sections/refactor-phase-review.md +3 -3
  50. package/bundled/dev-pipeline/templates/sections/refactor-phase-test.md +2 -2
  51. package/bundled/dev-pipeline/templates/sections/refactor-reminders.md +7 -7
  52. package/bundled/dev-pipeline/templates/sections/refactor-session-context.md +0 -1
  53. package/bundled/dev-pipeline/templates/sections/retrospective.md +12 -0
  54. package/bundled/dev-pipeline/templates/sections/runtime-commit-handoff.md +35 -0
  55. package/bundled/dev-pipeline/templates/session-status-schema.json +45 -62
  56. package/bundled/dev-pipeline/tests/test_checkpoint_state.py +469 -18
  57. package/bundled/dev-pipeline/tests/test_generate_bootstrap_prompt.py +262 -175
  58. package/bundled/dev-pipeline/tests/test_generate_bugfix_prompt.py +62 -23
  59. package/bundled/dev-pipeline/tests/test_generate_refactor_prompt.py +76 -28
  60. package/bundled/dev-pipeline/tests/test_python_runner_parity.py +168 -18
  61. package/bundled/dev-pipeline/tests/test_recovery_workflow.py +111 -0
  62. package/bundled/dev-pipeline/tests/test_reset_preserve.py +0 -2
  63. package/bundled/dev-pipeline/tests/test_runtime_commit.py +608 -0
  64. package/bundled/dev-pipeline/tests/test_unified_cli.py +167 -25
  65. package/bundled/skills/_metadata.json +9 -9
  66. package/bundled/skills/app-planner/SKILL.md +3 -3
  67. package/bundled/skills/app-planner/references/generated-plan-review.md +2 -1
  68. package/bundled/skills/app-planner/references/rules/backend/derivation-rules.md +56 -64
  69. package/bundled/skills/app-planner/references/rules/backend/fixed-rules.md +85 -240
  70. package/bundled/skills/app-planner/references/rules/backend/question-bank.md +25 -25
  71. package/bundled/skills/app-planner/references/rules/backend/question-manifest.json +16 -7
  72. package/bundled/skills/app-planner/references/rules/backend/template.md +74 -92
  73. package/bundled/skills/app-planner/references/rules/database/derivation-rules.md +93 -93
  74. package/bundled/skills/app-planner/references/rules/database/fixed-rules.md +66 -173
  75. package/bundled/skills/app-planner/references/rules/database/question-bank.md +31 -26
  76. package/bundled/skills/app-planner/references/rules/database/question-manifest.json +13 -4
  77. package/bundled/skills/app-planner/references/rules/database/template.md +76 -98
  78. package/bundled/skills/app-planner/references/rules/frontend/derivation-rules.md +68 -95
  79. package/bundled/skills/app-planner/references/rules/frontend/fixed-rules.md +93 -166
  80. package/bundled/skills/app-planner/references/rules/frontend/question-bank.md +46 -36
  81. package/bundled/skills/app-planner/references/rules/frontend/question-manifest.json +11 -2
  82. package/bundled/skills/app-planner/references/rules/frontend/template.md +79 -257
  83. package/bundled/skills/app-planner/references/rules/mobile/derivation-rules.md +91 -99
  84. package/bundled/skills/app-planner/references/rules/mobile/fixed-rules.md +73 -246
  85. package/bundled/skills/app-planner/references/rules/mobile/question-bank.md +17 -17
  86. package/bundled/skills/app-planner/references/rules/mobile/question-manifest.json +17 -2
  87. package/bundled/skills/app-planner/references/rules/mobile/template.md +73 -85
  88. package/bundled/skills/app-planner/references/rules-configuration.md +133 -65
  89. package/bundled/skills/app-planner/scripts/validate-rules-configuration.py +291 -0
  90. package/bundled/skills/prizmkit/SKILL.md +17 -18
  91. package/bundled/skills/prizmkit/references/workflow-state-protocol.md +22 -18
  92. package/bundled/skills/prizmkit-code-review/SKILL.md +22 -58
  93. package/bundled/skills/prizmkit-code-review/references/independent-code-review.md +6 -6
  94. package/bundled/skills/prizmkit-code-review/references/review-report-template.md +2 -2
  95. package/bundled/skills/prizmkit-committer/SKILL.md +82 -132
  96. package/bundled/skills/prizmkit-deploy/SKILL.md +27 -11
  97. package/bundled/skills/prizmkit-deploy/assets/deploy-document-template.md +89 -0
  98. package/bundled/skills/prizmkit-deploy/references/ci-cd-workflows.md +44 -14
  99. package/bundled/skills/prizmkit-deploy/references/cloud-platform-deploy.md +19 -3
  100. package/bundled/skills/prizmkit-deploy/references/database-setup.md +22 -12
  101. package/bundled/skills/prizmkit-deploy/references/deploy-config-schema.md +3 -1
  102. package/bundled/skills/prizmkit-deploy/references/deploy-history-schema.md +22 -6
  103. package/bundled/skills/prizmkit-deploy/references/deploy-metadata-schema.json +49 -0
  104. package/bundled/skills/prizmkit-deploy/references/live-validation-notes.md +1 -1
  105. package/bundled/skills/prizmkit-deploy/references/pending-input-schema.json +164 -0
  106. package/bundled/skills/prizmkit-deploy/references/ssh-adapter-flow.md +9 -8
  107. package/bundled/skills/prizmkit-deploy/references/ssh-execution-flow.md +6 -6
  108. package/bundled/skills/prizmkit-implement/SKILL.md +30 -66
  109. package/bundled/skills/prizmkit-implement/references/implementation-subagent-procedure.md +4 -4
  110. package/bundled/skills/prizmkit-init/SKILL.md +4 -0
  111. package/bundled/skills/prizmkit-plan/SKILL.md +21 -64
  112. package/bundled/skills/prizmkit-plan/references/artifact-identity.md +38 -0
  113. package/bundled/skills/prizmkit-plan/references/independent-plan-review.md +4 -4
  114. package/bundled/skills/prizmkit-plan/references/review-plan-spec-loop.md +5 -5
  115. package/bundled/skills/prizmkit-prizm-docs/SKILL.md +75 -11
  116. package/bundled/skills/prizmkit-prizm-docs/assets/prizm-docs-format.md +191 -56
  117. package/bundled/skills/prizmkit-prizm-docs/references/op-init.md +18 -18
  118. package/bundled/skills/prizmkit-prizm-docs/references/op-rebuild.md +14 -8
  119. package/bundled/skills/prizmkit-prizm-docs/references/op-status.md +12 -5
  120. package/bundled/skills/prizmkit-prizm-docs/references/op-update.md +23 -12
  121. package/bundled/skills/prizmkit-prizm-docs/references/op-validate.md +13 -9
  122. package/bundled/skills/prizmkit-retrospective/SKILL.md +94 -97
  123. package/bundled/skills/prizmkit-retrospective/references/knowledge-injection-steps.md +79 -37
  124. package/bundled/skills/prizmkit-retrospective/references/retrospective-result-schema.json +138 -0
  125. package/bundled/skills/prizmkit-retrospective/references/structural-sync-steps.md +111 -54
  126. package/bundled/skills/prizmkit-test/SKILL.md +64 -51
  127. package/bundled/skills/prizmkit-test/references/boundary-contract-and-test-double-guidance.md +206 -0
  128. package/bundled/skills/prizmkit-test/references/independent-test-review.md +17 -9
  129. package/bundled/skills/prizmkit-test/references/test-coverage-model.md +45 -21
  130. package/bundled/skills/prizmkit-test/references/test-report-template.md +20 -13
  131. package/bundled/skills/prizmkit-workflow/SKILL.md +35 -37
  132. package/bundled/skills/prizmkit-workflow/references/artifact-identity.md +34 -0
  133. package/bundled/skills/prizmkit-workflow/references/workflow-state-protocol.md +22 -18
  134. package/bundled/skills/recovery-workflow/SKILL.md +2 -1
  135. package/bundled/skills/recovery-workflow/references/detection.md +4 -3
  136. package/bundled/skills/recovery-workflow/scripts/detect-recovery-state.py +15 -5
  137. package/bundled/templates/hooks/validate-prizm-docs.py +124 -12
  138. package/package.json +1 -1
  139. package/src/scaffold.js +33 -22
  140. package/bundled/dev-pipeline/templates/sections/bugfix-artifacts.md +0 -16
  141. package/bundled/dev-pipeline/templates/sections/bugfix-session-status.md +0 -31
  142. package/bundled/dev-pipeline/templates/sections/critical-paths-agent.md +0 -7
  143. package/bundled/dev-pipeline/templates/sections/critical-paths-lite.md +0 -7
  144. package/bundled/dev-pipeline/templates/sections/directory-convention-agent.md +0 -9
  145. package/bundled/dev-pipeline/templates/sections/directory-convention-lite.md +0 -6
  146. package/bundled/dev-pipeline/templates/sections/headless-commit-authorization.md +0 -15
  147. package/bundled/dev-pipeline/templates/sections/phase-commit.md +0 -61
  148. package/bundled/dev-pipeline/templates/sections/phase-context-snapshot-agent-suffix.md +0 -24
  149. package/bundled/dev-pipeline/templates/sections/phase-context-snapshot-lite-suffix.md +0 -12
  150. package/bundled/dev-pipeline/templates/sections/phase-implement-agent.md +0 -44
  151. package/bundled/dev-pipeline/templates/sections/phase-implement-lite.md +0 -25
  152. package/bundled/dev-pipeline/templates/sections/phase-plan-agent.md +0 -20
  153. package/bundled/dev-pipeline/templates/sections/phase-plan-lite.md +0 -20
  154. package/bundled/dev-pipeline/templates/sections/phase-review-agent.md +0 -20
  155. package/bundled/dev-pipeline/templates/sections/refactor-artifacts.md +0 -17
  156. package/bundled/dev-pipeline/templates/sections/refactor-session-status.md +0 -28
  157. package/bundled/dev-pipeline/templates/sections/test-failure-recovery-agent.md +0 -52
  158. package/bundled/dev-pipeline/templates/sections/test-failure-recovery-lite.md +0 -52
  159. package/bundled/skills/prizmkit-code-review/references/workflow-state-protocol.md +0 -174
  160. package/bundled/skills/prizmkit-committer/references/workflow-state-protocol.md +0 -174
  161. package/bundled/skills/prizmkit-implement/references/workflow-state-protocol.md +0 -174
  162. package/bundled/skills/prizmkit-plan/references/workflow-state-protocol.md +0 -174
  163. package/bundled/skills/prizmkit-retrospective/references/workflow-state-protocol.md +0 -174
  164. package/bundled/skills/prizmkit-test/references/external-contract-mock-guidance.md +0 -119
@@ -13,6 +13,11 @@
13
13
 
14
14
  ---
15
15
 
16
+ ## SEMANTIC_FALLBACK_POLICY
17
+
18
+ Every confirmed option is valid input even when no pre-authored block exists. For an unmatched framework, ORM, datastore, deployment, observability, or permission option, render the complete selected meaning, follow current official and detected project conventions, preserve brownfield behavior unless migration was selected, and import no rules from a recommended alternative. Render `none`, `not required`, deferred, and conditionally skipped decisions as explicit not-applicable or deferred statements; never leave placeholders blank.
19
+
20
+ Validate active blocks against the decision ledger before rendering. Architecture, API style, authentication, data technology, testing, observability, and AI permissions each have one selected owner; incompatible blocks fail generation.
16
21
 
17
22
  ## Phase 2 Normalized Semantic Fill Table
18
23
 
@@ -124,9 +129,9 @@ Resolve each selected option or custom reply into the complete semantic value sh
124
129
  ### D-NODE-02
125
130
  **Trigger**: Q1 = Node.js | **Inject into**: `{{ tech_stack_rules }}`
126
131
 
127
- - Package manager locked to `pnpm` (recommended). Commit `pnpm-lock.yaml`.
128
- - `package.json` declares `"type": "module"`.
129
- - CI validates `engines` field matches `.nvmrc`.
132
+ - Preserve the package manager and lockfile already selected by the project; do not introduce a different manager as an implicit Node.js default.
133
+ - `package.json` declares the selected module format explicitly when the runtime requires it.
134
+ - Keep runtime declarations used by package metadata, local tooling, and CI consistent.
130
135
 
131
136
  ### D-PYTHON-01
132
137
  **Trigger**: Q1 = Python | **Inject into**: `{{ tech_stack_rules }}`
@@ -354,38 +359,35 @@ Resolve each selected option or custom reply into the complete semantic value sh
354
359
  ### D-MONGO-01
355
360
  **Trigger**: Q8 = MongoDB | **Inject into**: `{{ data_rules }}`
356
361
 
357
- - MongoDB document model: schema validation via JSON Schema (`$jsonSchema` validator on collections).
358
- - Indexing strategy for query patterns: create indexes for all query filter fields. Use `explain()` to verify index usage.
359
- - Aggregation pipeline standards: stages must be documented with purpose comments. Forbid complex pipelines without EXPLAIN.
360
- - No-SQL injection prevention: validate and sanitize all user input in queries. Use parameterized query operators (`$eq`, `$gt`), forbid `$where` with user input.
361
- - Collection design with embedded vs. reference trade-offs: embed for read-together data, reference for independently-accessed data.
362
- - The relational-database-oriented F5 fixed rules (migration files, SELECT syntax, normalization) do NOT apply. Skip F5.1-F5.3 of the fixed rules content.
362
+ - Define collection validation at the database or application boundary and keep it synchronized with the selected model source.
363
+ - Derive indexes from measured query/sort paths and verify expensive operations with `explain()`; do not index every filterable field automatically.
364
+ - Treat field names and query operators as allowlisted input and never evaluate caller-controlled `$where` or executable expressions.
365
+ - Choose embedding versus references from aggregate ownership, update atomicity, document growth, and access patterns.
366
+ - Apply document-model, migration, and query rules only; do not import relational SQL or 3NF rules.
363
367
 
364
368
  ### D-MYSQL-01
365
369
  **Trigger**: Q8 = MySQL | **Inject into**: `{{ data_rules }}`
366
370
 
367
- - MySQL 8.0+ with InnoDB engine default. Use `utf8mb4` charset for all tables.
368
- - Forbid `utf8mb3` (deprecated). Forbid MyISAM engine (no transaction support).
369
- - Index types: BTREE for range queries, HASH for exact-match lookups (memory tables only).
370
- - Connection pool: configure `wait_timeout` and `interactive_timeout` to prevent stale connections.
371
- - Migration files use the same tooling as PostgreSQL (golang-migrate, Flyway, Alembic). Schema differences documented in README.
371
+ - Use a supported MySQL release and a transactional engine for state requiring atomicity.
372
+ - Use `utf8mb4` for Unicode text and reject deprecated encodings in new structures.
373
+ - Select indexes from query patterns and engine support, and configure client lifetime against server timeouts.
374
+ - Use the migration mechanism selected by the project; do not inherit PostgreSQL syntax or tooling.
372
375
 
373
376
  ### D-SQLITE-01
374
377
  **Trigger**: Q8 = SQLite | **Inject into**: `{{ data_rules }}`
375
378
 
376
- - SQLite for local development and single-instance deployments. WAL mode enabled by default.
377
- - Forbid SQLite for multi-instance production deployments (no concurrent write support).
378
- - Forbid concurrent write access across multiple processes. Use a single writer pattern.
379
- - Migration files still version-controlled. Test with the same SQLite version as production.
380
- - No connection pool needed (single connection). Close connections explicitly after each operation.
379
+ - Use SQLite only for a workload whose concurrency, durability, and deployment model match its capabilities.
380
+ - Choose journal/WAL mode from the read/write and filesystem constraints and serialize writes when required.
381
+ - Version model changes and test with the supported production SQLite version when SQLite is the deployed store.
382
+ - Follow the selected driver lifecycle; do not impose a server-style connection pool.
381
383
 
382
384
  ### D-JWT-01
383
385
  **Trigger**: Q9 = JWT | **Inject into**: `{{ auth_rules }}`
384
386
 
385
- - Access token TTL 15min. Refresh token TTL 7d.
386
- - Token payload contains no sensitive info (passwords, phone numbers). Only userId + role.
387
- - Secret read from environment variables. Forbid hardcoding.
388
- - Token blacklist (logout/password change invalidation) implemented with Redis.
387
+ - Define issuer, audience, subject, scopes/claims, signing algorithm, access lifetime, refresh/re-issuance, rotation, and revocation from the threat model.
388
+ - Keep sensitive data out of token payloads and validate signature plus temporal and audience claims at every trust boundary.
389
+ - Keep signing material outside source control and support key rotation.
390
+ - Implement revocation through a compatible selected mechanism; JWT does not implicitly authorize Redis.
389
391
 
390
392
  ### D-OAUTH-01
391
393
  **Trigger**: Q9 = OAuth2 | **Inject into**: `{{ auth_rules }}`
@@ -398,19 +400,17 @@ Resolve each selected option or custom reply into the complete semantic value sh
398
400
  ### D-SESSION-01
399
401
  **Trigger**: Q9 = Session | **Inject into**: `{{ auth_rules }}`
400
402
 
401
- - Session storage uses Redis, not memory (loses data on restart, not shared across instances).
402
- - Session ID generated with `crypto.randomUUID()`, not auto-increment IDs.
403
- - Cookie settings: `HttpOnly` + `Secure` (production) + `SameSite=Lax`.
404
- - Session ID must be rotated after successful login (prevent Session Fixation).
403
+ - Store sessions in a mechanism compatible with the selected deployment and availability topology; an external cache is not implied when Q10 selected no cache.
404
+ - Generate high-entropy opaque session identifiers, rotate them at authentication/privilege changes, and invalidate them on logout.
405
+ - Use `HttpOnly`, production `Secure`, and a SameSite/CSRF policy compatible with confirmed cross-site flows.
405
406
 
406
407
  ### D-APIKEY-01
407
408
  **Trigger**: Q9 = API Key | **Inject into**: `{{ auth_rules }}`
408
409
 
409
- - API keys for service-to-service communication. Not for end-user auth.
410
- - Keys stored hashed (SHA-256) in database. Plaintext shown once at creation.
411
- - Key format: `sk_<random_32_bytes_base64url>` with prefix for easy identification in logs.
412
- - Key validation: constant-time comparison to prevent timing attacks.
413
- - Keys must have expiration (default 365d). Must be rotatable without downtime.
410
+ - Restrict API keys to named machine or integration principals, not end-user authentication.
411
+ - Generate high-entropy keys, display plaintext only at creation, and store a one-way verifier plus a non-secret lookup prefix.
412
+ - Compare verifiers safely and support scoped authorization, rotation, revocation, ownership, and last-used audit data.
413
+ - Set expiry from integration risk and lifecycle rather than a universal duration.
414
414
 
415
415
  ### D-REDIS-01
416
416
  **Trigger**: Q10 = Redis | **Inject into**: `{{ cache_rules }}`
@@ -462,18 +462,16 @@ Resolve each selected option or custom reply into the complete semantic value sh
462
462
  ### D-DOCKER-01
463
463
  **Trigger**: Q12 = Docker | **Inject into**: `{{ deploy_rules }}`
464
464
 
465
- - Dockerfile uses multi-stage builds. Final image excludes build tools.
466
- - Base image uses `-slim` or `-alpine` variants.
467
- - Health check: `HEALTHCHECK` points to `/health` endpoint.
468
- - `.dockerignore` excludes node_modules, .git, log files.
465
+ - Use a reproducible build and a minimal runtime image compatible with the selected language/runtime; do not force Alpine when native dependencies make it unsafe.
466
+ - Exclude build-only tools and sensitive/unneeded context from the final image.
467
+ - Connect container health behavior to the selected application liveness/readiness contract rather than assuming one route.
469
468
 
470
469
  ### D-K8S-01
471
470
  **Trigger**: Q12 = Kubernetes | **Inject into**: `{{ deploy_rules }}`
472
471
 
473
- - Must configure liveness and readiness probes (pointing to `/health` and `/health/ready`).
474
- - Resource limits (requests/limits) must be set.
475
- - Sensitive config via Secret, non-sensitive via ConfigMap.
476
- - Pod anti-affinity: same-type pods not scheduled on the same node (high availability).
472
+ - Configure probes against the application's selected liveness/readiness contract and set resource requests/limits from measured behavior.
473
+ - Keep sensitive and non-sensitive configuration in the platform's appropriate boundaries without committing secret values.
474
+ - Replicas, disruption budgets, anti-affinity, and multi-zone placement come from the confirmed availability objective; Kubernetes selection alone does not require them.
477
475
 
478
476
  ### D-AI-DEP-STRICT-01
479
477
  **Trigger**: Q18 = Forbid | **Inject into**: `{{ ai_dependency_rule }}`
@@ -519,10 +517,9 @@ Resolve each selected option or custom reply into the complete semantic value sh
519
517
  ### D-OBS-LOG-01
520
518
  **Trigger**: Q16 = Structured JSON logging | **Inject into**: `{{ observability_rules }}`
521
519
 
522
- - Log format: JSON with fields `timestamp`, `level`, `message`, `traceId`, `userId`, `service`, `path`, `method`, `duration_ms`.
523
- - Centralized collection via ELK (Elasticsearch + Logstash + Kibana) or Grafana Loki.
524
- - Log levels: ERROR (requires alert), WARN (requires investigation), INFO (key business events), DEBUG (development only).
525
- - Forbid logging sensitive data (passwords, tokens, national IDs). Must mask.
520
+ - Emit structured events with timestamp, severity, message, service/operation, and available correlation context; add identity or request fields only when useful and privacy-safe.
521
+ - Send events through the centralized collection boundary selected by the deployment; do not force ELK or Loki.
522
+ - Define severity and alert mappings operationally, and redact credentials, tokens, and sensitive personal data.
526
523
 
527
524
  ### D-OBS-LOG-02
528
525
  **Trigger**: Q16 = local files | **Inject into**: `{{ observability_rules }}`
@@ -543,26 +540,23 @@ Resolve each selected option or custom reply into the complete semantic value sh
543
540
  ### D-OBS-METRICS-01
544
541
  **Trigger**: Q17 = OpenTelemetry + Prometheus + Grafana | **Inject into**: `{{ observability_rules }}`
545
542
 
546
- - OpenTelemetry SDK auto-instruments HTTP/gRPC/database calls.
547
- - Custom metrics: request count, request duration (p50/p95/p99), error rate, DB query duration.
548
- - Prometheus scrapes `/metrics` endpoint. Grafana dashboards for: request latency, error rate, DB connection pool, cache hit rate.
549
- - Alerting rules: error rate > 5% for 5min triggers alert, p95 latency > 500ms for 5min triggers warning.
543
+ - Instrument applicable transport and dependency boundaries with the selected OpenTelemetry-compatible pipeline.
544
+ - Define service metrics and dashboards from confirmed service objectives and selected dependencies; cache metrics appear only when caching is selected.
545
+ - Expose or export telemetry through the selected collector/platform mechanism and derive alert thresholds from objectives and observed baselines rather than universal percentages.
550
546
 
551
547
  ### D-TEST-STRATEGY-01
552
548
  **Trigger**: Q13 = Unit tests + Integration tests | **Inject into**: `{{ test_rules }}`
553
549
 
554
- - Testing tiers: unit tests (service/repository layers) + integration tests (API endpoints + DB).
555
- - Unit tests: fast (<100ms each), no external deps. Mock all I/O.
556
- - Integration tests: use test database or testcontainers. Test realistic scenarios.
557
- - Coverage targets: service layer >= 80%, controller layer >= 60%.
558
- - CI runs all tests. Integration tests run against a fresh DB instance each time.
550
+ - Include unit and integration behavior appropriate to the selected architecture and external boundaries.
551
+ - Unit tests isolate owned behavior; integration tests verify real contract boundaries using the separately selected mock/environment strategy.
552
+ - Set numeric coverage or timing thresholds only when the project confirms them. CI runs the enabled tiers in deterministic isolation.
559
553
 
560
554
  ### D-TEST-STRATEGY-02
561
555
  **Trigger**: Q13 = Unit tests only | **Inject into**: `{{ test_rules }}`
562
556
 
563
- - Unit tests only. Coverage target: service layer >= 80%.
564
- - External deps mocked. No database or network access in tests.
565
- - Recommend adding integration tests for critical data-access paths before production.
557
+ - Keep the mandatory suite at the unit boundary selected by the project and isolate external dependencies according to Q15.
558
+ - Do not inject an unselected coverage percentage.
559
+ - Record the accepted lack of integration evidence and revisit it when production risk changes.
566
560
 
567
561
  ### D-TEST-STRATEGY-03
568
562
  **Trigger**: Q13 = Critical path integration tests only | **Inject into**: `{{ test_rules }}`
@@ -574,10 +568,9 @@ Resolve each selected option or custom reply into the complete semantic value sh
574
568
  ### D-TEST-MOCK-01
575
569
  **Trigger**: Q15 = testcontainers | **Inject into**: `{{ test_rules }}`
576
570
 
577
- - External APIs (payment gateways, email services, third-party SDKs): mocked.
578
- - Database: use testcontainers (dockerized Postgres/MySQL/Redis) for integration tests.
579
- - Testcontainers lifecycle: start before test suite, stop after. Use singleton container pattern to share across tests.
580
- - Test data: seeded per test file, cleaned up after each test. Forbid shared mutable test data.
571
+ - Mock external service dependencies at their contract boundary.
572
+ - For datastore integration tests, use a testcontainer or an in-memory implementation only when it faithfully represents the selected datastore behavior; do not start Redis unless caching/session decisions require it.
573
+ - Bound environment lifecycle and isolate mutable test data so tests remain repeatable.
581
574
 
582
575
  ### D-TEST-MOCK-02
583
576
  **Trigger**: Q15 = including database | **Inject into**: `{{ test_rules }}`
@@ -590,10 +583,9 @@ Resolve each selected option or custom reply into the complete semantic value sh
590
583
  ### D-TEST-MOCK-03
591
584
  **Trigger**: Q15 = real environments | **Inject into**: `{{ test_rules }}`
592
585
 
593
- - Prefer real environments over mocking. Tests run against dedicated test infrastructure.
594
- - Test database is a shared instance (not per-developer).
595
- - Test data isolation: each test creates its own data and cleans up.
596
- - Requires CI access to test infrastructure. Tests may be slower but more realistic.
586
+ - Prefer representative real dependencies through dedicated test infrastructure where the selected risk justifies it.
587
+ - Shared infrastructure must still isolate tenants/data and support deterministic cleanup; a shared instance is not automatically required.
588
+ - Document CI access, cost, failure ownership, and any remaining non-production differences.
597
589
 
598
590
  ---
599
591
 
@@ -1,285 +1,130 @@
1
- # Fixed Rules — Complete Backend Fixed Rules
2
-
3
- > This file is read by the `backend-rules` skill in Phase 1 and injected directly into `backend-rules.md`.
4
- > These rules are industry consensus / best practices — **do not ask the user**.
5
- > Every rule includes RATIONALE so the AI understands intent, not just constraints.
6
-
7
- ---
8
-
9
- ## F1. Project Structure
10
-
11
- ### F1.1 Layered Architecture (Mandatory)
12
-
13
- - **Rule**: Must use one of the following layering patterns, and be consistent across the project:
14
- - Classic three-tier: `controller → service → repository`
15
- - DDD-style: `handler → usecase → repository` (Go) / `router → service → dao` (Node)
16
- - **Rule**: Upper layers must not bypass lower layers (controller must not call repository directly).
17
- - **Rule**: Each layer does only its own job — controller handles request validation and response formatting, service handles business logic, repository handles data access.
18
- - **RATIONALE**: Mixed layer boundaries are the #1 cause of backend code rot. When AI can't tell which layer does what, business logic scatters into controllers.
19
-
20
- ### F1.2 Directory Conventions
21
-
22
- - **Rule**: The project root structure must clearly reflect the layering.
23
- - **Rule**: Shared utilities (utils) must be isolated from business code.
24
- - **Rule**: Config, constants, and type definitions are centrally managed.
25
- - **Forbidden**: Turning `utils/` into a dumping ground for anything without a clear home.
26
- - **RATIONALE**: The directory structure is the project's first piece of documentation. A new developer (including AI) should know where a function belongs just by reading it.
27
-
28
- ### F1.3 Module Boundaries
29
-
30
- - **Rule**: Organize by business domain, not by technical layer (types/services/models cross-domain).
31
- - **Rule**: Modules communicate through explicit interfaces. Do not access another module's internal implementation directly.
32
- - **Forbidden**: Circular dependencies (module A imports B, B imports A).
33
- - **RATIONALE**: Technical-layer organization scatters code for a single feature across 4–5 directories. Changing one feature requires jumping across directories.
34
- - **Note on layering interaction with F1.1**: Organize by business domain at the top level. Within each domain directory, enforce the layering from F1.1 (e.g., user/controller/, user/service/, user/repository/). Do NOT create top-level controllers/, services/, repositories/ directories that span all domains.
35
-
36
- ---
37
-
38
- ## F2. API Design
39
-
40
- ### F2.1 REST Contract
41
-
42
- - **Rule**: URLs use plural nouns (`/users`, `/orders`), never verbs (forbid `/getUser`, `/createOrder`).
43
- - **Rule**: HTTP method semantics must be correct:
44
- - `GET` — query, must not modify data
45
- - `POST` — create
46
- - `PUT` — full update
47
- - `PATCH` — partial update
48
- - `DELETE` — remove
49
- - **Rule**: Standard pagination params: `page` (1-based), `pageSize` (default 20, max 100).
50
- - **Rule**: Standard sorting params: `sortBy=field&sortOrder=asc|desc`.
51
- - **RATIONALE**: The API is a contract between frontend and backend. Inconsistent naming and parameter formats cause bugs in consumers.
52
-
53
- ### F2.2 Status Codes
54
-
55
- - **Rule**: Use HTTP status codes strictly by semantics:
56
- - `200` — query success
57
- - `201` — create success
58
- - `204` — delete success (no body)
59
- - `400` — validation failure
60
- - `401` — not authenticated
61
- - `403` — forbidden
62
- - `404` — resource not found
63
- - `409` — resource conflict
64
- - `422` — valid request format but business logic rejection
65
- - `500` — unknown server error
66
- - **Forbidden**: Returning `200` for all errors with an error code in the body.
67
- - **RATIONALE**: HTTP status codes are standard signals for infrastructure (load balancers, monitoring, gateways). Bypassing them makes all observability useless.
68
-
69
- ### F2.3 Error Response Format
70
-
71
- - **Rule**: All errors return a unified structure:
72
- ```json
73
- {
74
- "error": {
75
- "code": "USER_NOT_FOUND",
76
- "message": "User not found",
77
- "details": [],
78
- "traceId": "abc-123"
79
- }
80
- }
81
- ```
82
- - **Rule**: `code` uses UPPER_SNAKE_CASE with business semantics (`USER_NOT_FOUND`, not `ERR_001`).
83
- - **Rule**: `traceId` is generated at request entry and propagated through the entire call chain.
84
- - **RATIONALE**: A unified error format lets frontends and gateways write one error handler instead of per-endpoint if/else chains.
1
+ # Backend Invariant Rules
85
2
 
86
- ### F2.4 API Versioning
3
+ POLICY_CLASS: invariant
87
4
 
88
- - **Rule**: APIs must indicate version in URL or Header (`/api/v1/users` or `Accept: application/vnd.api.v1+json`).
89
- - **Rule**: Breaking changes require a new version. Old versions must be maintained for at least one release cycle.
90
- - **RATIONALE**: Unversioned APIs cause widespread mobile/third-party client crashes on release.
5
+ These blocks apply to every backend option exposed by Rules Configuration.
91
6
 
92
- ---
7
+ **Selected-decision boundary:** language, runtime, framework, architecture, API style, API documentation, data technology, authentication scheme, cache, queue, deployment, testing depth, observability stack, dependency permission, caller analysis, and config permission belong to confirmed decisions and derivation rules. Do not encode one option here as universal behavior.
93
8
 
94
- ## F3. Error Handling
9
+ ## I1. Structure and Ownership
95
10
 
96
- - **Rule**: All exceptions must be caught by a global exception filter and return a unified error response.
97
- - **Rule**: Business exceptions vs. system exceptions are separated business exceptions return 4xx, system exceptions return 500.
98
- - **Forbidden**: Empty `catch(e) {}` blocks. If ignoring is truly necessary, comment why.
99
- - **Forbidden**: `catch(e) { throw new Error('something went wrong') }` that swallows the original stack trace.
100
- - **Rule**: Error logs must include traceId, user identifier, request method, and path.
101
- - **RATIONALE**: The biggest backend failure isn't "an error occurred" — it's "an error occurred and nobody knows".
11
+ - Every module has an explicit owner and public boundary; internal implementation is not imported as an accidental API.
12
+ - Dependency direction follows the selected architecture and remains free of unplanned cycles.
13
+ - Business behavior has one authoritative implementation rather than duplicated branches across transports or entrypoints.
14
+ - Rationale: ownership and acyclic dependencies are invariant; layer names are not.
102
15
 
103
- ---
16
+ Inject into `{{ FIXED_RULES_STRUCTURE }}`.
104
17
 
105
- ## F4. Security
18
+ ## I2. API Contract Integrity
106
19
 
107
- ### F4.1 Input Validation (Mandatory)
20
+ - Follow the selected API style consistently and document externally consumed requests, responses, errors, and compatibility expectations.
21
+ - Validate untrusted inputs at the boundary before invoking business behavior.
22
+ - Contract changes identify affected consumers and use the selected compatibility or versioning policy.
23
+ - Do not apply HTTP-specific rules to non-HTTP transports unless an adapter explicitly owns that mapping.
108
24
 
109
- - **Rule**: All external inputs must be validated (body, query params, path params, headers, cookies).
110
- - **Rule**: Use a validation framework (Joi/Zod/Pydantic/validator), not hand-written if/else.
111
- - **Rule**: Validation failures return 400 with field-level error details.
112
- - **Forbidden**: Trusting data from the frontend to be directly stored or executed.
113
- - **RATIONALE**: Input validation is the first line of defense and the root cause mitigation for multiple OWASP Top 10 attacks.
114
-
115
- ### F4.2 Authentication & Authorization
116
-
117
- - **Rule**: AuthN and AuthZ must be separated — middleware handles authentication, business logic handles authorization.
118
- - **Rule**: JWT tokens must have expiration (access token ≤ 15min, refresh token ≤ 7d).
119
- - **Rule**: Sensitive operations (delete, transfer, permission changes) require secondary confirmation.
120
- - **Forbidden**: Hardcoding tokens/secrets in source code.
121
- - **RATIONALE**: Separating AuthN and AuthZ allows independent security audits at each layer.
122
-
123
- ### F4.3 General Protections
124
-
125
- - **Rule**: All external links/callback URLs must be validated against a whitelist to prevent Open Redirect.
126
- - **Rule**: File uploads must validate type (whitelist), size, and content magic bytes.
127
- - **Rule**: Passwords must use bcrypt/argon2 hashing. Forbid plaintext, MD5, or SHA1.
128
- - **Forbidden**: Exposing secrets, tokens, or passwords in error messages or logs.
129
- - **Forbidden**: Returning internal implementation details in responses (stack traces, SQL statements, framework versions).
130
- - **RATIONALE**: These are the most common security vulnerabilities. Not a question of "should we" — it's "you will be breached if you don't."
25
+ Inject into `{{ FIXED_RULES_API }}`.
131
26
 
132
- ### F4.4 Rate Limiting
27
+ ## I3. Error Integrity
133
28
 
134
- - **Rule**: All public API endpoints must have rate limiting. Forbid unlimited request rates.
135
- - **Rule**: Rate limit tiers: authentication endpoints (5 req/min), general API (100 req/min per user/IP), internal/admin endpoints (higher limits).
136
- - **Rule**: Rate limit headers: include X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset in responses.
137
- - **Rule**: Rate limit exceeded returns 429 Too Many Requests with Retry-After header.
138
- - **RATIONALE**: Without rate limiting, a single misbehaving client or a simple script-kiddie attack can take down your entire API.
29
+ - Preserve original diagnostic context when translating an internal failure to a public error.
30
+ - Separate expected domain failures from unexpected system failures.
31
+ - Public errors expose no secrets, stack traces, query text, or private implementation details.
32
+ - Never swallow a failure without an explicit, documented recovery path.
139
33
 
140
- ---
141
-
142
- ## F5. Database
143
-
144
- **Note**: These rules assume a relational database (PostgreSQL/MySQL). If the project uses MongoDB (selected in Q8), some rules (migration files, SELECT syntax) do not apply. Document-specific rules are in the derived rules section.
145
-
146
- - **Rule**: Connection pool must be reasonably sized (default ≤ CPU cores × 2). Connections must have timeouts.
147
- - **Rule**: All migration files must be versioned, reversible, and committed to the repository.
148
- - **Rule**: Queries must use parameterized queries or ORM-provided safe methods. Forbid string-concatenated SQL.
149
- - **Rule**: Bulk operations (>1000 rows) must be batched.
150
- - **Forbidden**: Executing single-row SQL inside loops (use batch insert/update instead).
151
- - **Forbidden**: SELECT without LIMIT.
152
- - **Forbidden**: `SELECT *` (specify columns explicitly).
153
- - **RATIONALE**: The database is the component where a single failure has the largest blast radius in a backend system. One bad query can bring down the entire service.
34
+ Inject into `{{ FIXED_RULES_ERROR }}`.
154
35
 
155
- ---
36
+ ## I4. Security Baseline
156
37
 
157
- ## F6. Observability
38
+ - Authenticate and authorize at explicit trust boundaries; do not trust caller-supplied identity or role data.
39
+ - Keep credentials and secrets outside source control and redact sensitive values from logs and errors.
40
+ - Validate callback, redirect, upload, and deserialization boundaries against an allowlisted contract.
41
+ - Store passwords only with a current password-hashing construction.
42
+ - Scheme-specific token, session, OAuth, and API-key rules come from `{{ auth_rules }}`.
158
43
 
159
- - **Rule**: Logs must be structured (JSON format), containing: `timestamp`, `level`, `message`, `traceId`, `userId`, `path`, `method`.
160
- - **Rule**: Expose at least two endpoints: `GET /health` (liveness) and `GET /health/ready` (readiness).
161
- - **Rule**: Key business operations must be instrumented (registration, login, payment, order creation, etc.).
162
- - **Forbidden**: Using `console.log` as a substitute for structured logging.
163
- - **RATIONALE**: A microservice without structured logging is a black box. Troubleshooting goes from minutes to hours.
44
+ Inject into `{{ FIXED_RULES_SECURITY }}`.
164
45
 
165
- ### F6.2 Distributed Tracing
46
+ ## I5. Abuse Protection
166
47
 
167
- - **Rule**: Every incoming request must generate or propagate a traceId. traceId is passed in X-Trace-Id header.
168
- - **Rule**: All downstream calls (database, cache, message queue, external APIs) must carry the traceId.
169
- - **Rule**: Use W3C Trace Context standard (traceparent header) for cross-service propagation.
170
- - **Forbidden**: Generating a new traceId mid-request chain (breaks distributed traces).
171
- - **RATIONALE**: traceId is the thread that ties together every log line and span for a single request across microservices. Without it, troubleshooting distributed systems is guesswork.
48
+ - Identify public or expensive operations that require quotas, backpressure, idempotency, or rate protection.
49
+ - Derive concrete limits from product risk and deployment capacity instead of imposing one universal number.
50
+ - Rejection behavior is observable and does not disclose sensitive internals.
172
51
 
173
- ### F6.3 Health Check Endpoints
52
+ Inject into `{{ FIXED_RULES_RATE_LIMITING }}`.
174
53
 
175
- - **Rule**: GET /health (liveness) — returns 200 if the process is alive. No dependency checks.
176
- - **Rule**: GET /health/ready (readiness) — returns 200 if all critical dependencies are available (database, cache, message queue). Returns 503 if any critical dependency is unreachable.
177
- - **Rule**: Health checks must be lightweight (< 50ms). Forbid running expensive queries or external API calls.
178
- - **RATIONALE**: Kubernetes and load balancers use these endpoints to decide whether to route traffic or restart the pod. A slow /health creates cascading failures.
54
+ ## I6. Data Access Safety
179
55
 
180
- ---
56
+ - Use the selected data technology's safe parameter binding or query construction mechanism.
57
+ - Bound potentially unbounded reads and writes or document the controlled batch/stream contract.
58
+ - Keep transactions or equivalent atomic units short and free of unrelated external waits.
59
+ - Relational and document-specific modeling rules belong to the selected data derivation blocks.
181
60
 
182
- ## F7. Configuration Management
61
+ Inject into `{{ FIXED_RULES_DATABASE }}`.
183
62
 
184
- - **Rule**: Configuration has three tiers — code defaults < environment variables < config files (by priority).
185
- - **Forbidden**: Committing any secrets, tokens, or passwords to Git.
186
- - **Rule**: All environment-specific config (database connections, Redis addresses, third-party API keys) injected via environment variables.
187
- - **Rule**: Must have a `.env.example` file listing all required environment variables with descriptions (use placeholders for values).
188
- - **RATIONALE**: Separating config from code is a 12-Factor App principle and a security baseline.
63
+ ## I7. Observability Integrity
189
64
 
190
- ---
65
+ - Errors and key operations carry enough correlation context to diagnose one request, job, or message without logging secrets.
66
+ - Logging format and collection topology follow the selected observability decision.
67
+ - Health signals distinguish process liveness from dependency readiness when the deployment environment consumes both.
191
68
 
192
- ## F8. Async & Message Queues
69
+ Inject into `{{ FIXED_RULES_OBSERVABILITY }}`.
193
70
 
194
- - **Rule**: Message handlers must be idempotent — replaying the same message produces no side effects.
195
- - **Rule**: Async tasks must have timeout handling, retry strategy (exponential backoff), and dead letter queues.
196
- - **Rule**: Message bodies must contain a unique id (for deduplication) and traceId (for tracing).
197
- - **Rule**: Retry count and interval must have upper limits (e.g., max 3 retries, intervals 1s/5s/15s).
198
- - **RATIONALE**: The biggest async system problem isn't "messages got lost" — it's "messages got processed twice and double-charged the customer."
71
+ ## I8. Trace Continuity
199
72
 
200
- ### F8.4 Message Delivery Semantics
73
+ - Preserve an existing correlation or trace context across supported downstream boundaries.
74
+ - Do not silently replace caller-provided valid trace context mid-operation.
75
+ - Distributed tracing is enabled only when selected or required by the deployment; otherwise preserve local correlation identifiers.
201
76
 
202
- - **Rule**: Explicitly document the delivery guarantee for each queue/topic: at-most-once, at-least-once, or exactly-once.
203
- - **Rule**: At-least-once (default for most systems): consumers must be idempotent.
204
- - **Rule**: Dead letter queues (DLQ) must be configured. Failed messages route to DLQ after max retries.
205
- - **Rule**: DLQ messages must have a replay/inspect mechanism. Forbid silently discarding failed messages.
206
- - **RATIONALE**: The difference between at-least-once and exactly-once is the difference between "customer charged once" and "customer charged twice."
77
+ Inject into `{{ FIXED_RULES_TRACING }}`.
207
78
 
208
- ### F8.5 Graceful Shutdown
79
+ ## I9. Configuration Safety
209
80
 
210
- - **Rule**: Application must handle SIGTERM gracefully: stop accepting new requests, finish in-progress requests (with timeout), close database connections, flush logs.
211
- - **Rule**: Shutdown timeout must be configured (default 30s). Kubernetes terminationGracePeriodSeconds must exceed this.
212
- - **Rule**: In-flight async tasks must complete or be re-queued before shutdown.
213
- - **Forbidden**: Hard-exit on SIGTERM (SIGKILL should be the fallback, not the default).
214
- - **RATIONALE**: Deployments and pod restarts should not cause failed requests or lost data. Graceful shutdown is a basic operational requirement.
81
+ - Separate secrets from non-secret configuration and document required configuration without committing secret values.
82
+ - Validate required configuration before serving work.
83
+ - Config modification permission comes only from `{{ ai_config_rule }}`; this invariant does not forbid an authorized change.
215
84
 
216
- ---
85
+ Inject into `{{ FIXED_RULES_CONFIG }}`.
217
86
 
218
- ## F9. Testing
87
+ ## I10. Async Safety
219
88
 
220
- - **Rule**: Testing has three tiers unit tests (service layer), integration tests (API endpoints + database), E2E (critical business flows).
221
- - **Rule**: External dependencies (database, Redis, third-party APIs) must be mocked in unit tests.
222
- - **Rule**: Integration tests use a test database or testcontainers. Test data is cleaned before and after each run.
223
- - **Rule**: Coverage baseline: service layer ≥ 80%, controller layer ≥ 60%.
224
- - **Forbidden**: Tests sharing mutable state (global variables / shared database rows).
225
- - **RATIONALE**: Backend regression risk is far higher than frontend (one data corruption is irreversible). Tests are the only safety net.
89
+ - Every asynchronous side effect defines ownership, timeout/cancellation behavior, and duplicate-delivery handling where applicable.
90
+ - Do not claim queue semantics when no queue was selected.
91
+ - Queue-specific retry, ordering, and dead-letter rules come from `{{ mq_rules }}`.
226
92
 
227
- ---
93
+ Inject into `{{ FIXED_RULES_ASYNC }}`.
228
94
 
229
- ## F10. AI Vibecoding Baseline Constraints (project-agnostic, always active)
95
+ ## I11. Message Delivery Integrity
230
96
 
231
- ### F10.1 Search First
232
- - **Rule**: Before generating a new module, AI must search existing code to check for similar functionality.
233
- - **Rule**: Before writing SQL/migrations, AI must read existing migration files and schema.
97
+ - When messaging is selected, document delivery semantics and make consumers safe for the selected duplicate/retry model.
98
+ - Failed messages remain observable and recoverable according to the selected queue capability.
99
+ - Render an explicit not-applicable statement when messaging is not selected.
234
100
 
235
- ### F10.2 Dependency Control
236
- - **Rule**: AI must not modify `package.json` / `requirements.txt` / `go.mod` / `Cargo.toml` on its own.
237
- - **Rule**: If a new dependency is truly needed, AI must list: package name, version, reason, alternative comparison.
101
+ Inject into `{{ FIXED_RULES_MESSAGE_DELIVERY }}`.
238
102
 
239
- ### F10.3 Breaking Changes
240
- - **Rule**: Before modifying a shared module/utility/API contract, AI must list all callers.
241
- - **Rule**: Changing API response field names or types requires assessing frontend impact first.
103
+ ## I12. Shutdown Integrity
242
104
 
243
- ### F10.4 Config Immutability
244
- - **Rule**: AI must not modify environment variables, database connection config, docker-compose, or CI/CD configuration on its own.
245
- - **Rule**: Adding a new environment variable in code must be accompanied by an update to `.env.example`.
246
-
247
- ### F10.5 SQL Safety
248
- - **Rule**: All AI-written SQL must be parameterized queries.
249
- - **Forbidden**: AI generating string-concatenated SQL code.
105
+ - Stop accepting new work before releasing resources.
106
+ - Bound shutdown and preserve or requeue owned in-flight work where the runtime supports it.
107
+ - Apply platform-specific signal and probe details through deployment derivation rules.
250
108
 
251
- ### F10.6 Migration Files
252
- - **Rule**: AI generating a new migration must also produce the corresponding rollback migration.
253
- - **Forbidden**: Dropping columns or changing types in migrations (add-only, unless a rollback plan exists).
109
+ Inject into `{{ FIXED_RULES_GRACEFUL_SHUTDOWN }}`.
254
110
 
255
- ### F10.7 Context Honesty
256
- - **Rule**: When uncertain, AI must explicitly say "I'm not sure." Forbid inventing API paths, library versions, or database field names.
257
- - **Rule**: AI must read the latest file contents before modifying. Forbid generating diffs based on guesswork.
111
+ ## I13. Verification Integrity
258
112
 
259
- ---
113
+ - Follow the selected testing depth; do not invent unapproved coverage thresholds or mandatory tiers.
114
+ - Enabled tests are deterministic, isolated from production data, and assert behavior rather than implementation accidents.
115
+ - A `not required yet` choice is recorded explicitly with its accepted risk rather than contradicted by unconditional test requirements.
260
116
 
261
- ## Injection Instructions (for the AI executing this skill)
117
+ Inject into `{{ FIXED_RULES_TEST }}`.
262
118
 
263
- Each chapter in this file corresponds to a `{{ FIXED_RULES_* }}` placeholder in the template:
119
+ ## I14. AI Change Safety
264
120
 
265
- | Chapter | Inject Into Placeholder | Template Section |
266
- |---------|------------------------|-------------------|
267
- | F1 Project Structure | `{{ FIXED_RULES_STRUCTURE }}` | §1 Project Structure |
268
- | F2 API Design | `{{ FIXED_RULES_API }}` | §2 API Design |
269
- | F3 Error Handling | `{{ FIXED_RULES_ERROR }}` | §3 Error Handling |
270
- | F4 Security | `{{ FIXED_RULES_SECURITY }}` | §4 Security (F4.1-F4.3 only; stop before F4.4) |
271
- | F4.4 Rate Limiting | `{{ FIXED_RULES_RATE_LIMITING }}` | §4 Security (F4.4 only, injected separately) |
272
- | F5 Database | `{{ FIXED_RULES_DATABASE }}` | §5 Database |
273
- | F6 Observability | `{{ FIXED_RULES_OBSERVABILITY }}` | §6 Observability (F6 + F6.3 only; stop before F6.2) |
274
- | F6.2 Distributed Tracing | `{{ FIXED_RULES_TRACING }}` | §6 Observability (F6.2 only, injected separately) |
275
- | F7 Configuration | `{{ FIXED_RULES_CONFIG }}` | §7 Configuration |
276
- | F8 Async & Queues | `{{ FIXED_RULES_ASYNC }}` | §8 Async & Queues |
277
- | F8.4 Message Delivery | `{{ FIXED_RULES_MESSAGE_DELIVERY }}` | §8 Async & Queues |
278
- | F8.5 Graceful Shutdown | `{{ FIXED_RULES_GRACEFUL_SHUTDOWN }}` | §8 Async & Queues |
279
- | F9 Testing | `{{ FIXED_RULES_TEST }}` | §9 Testing |
280
- | F10 AI Constraints | `{{ FIXED_RULES_AI_BASE }}` | §10 AI Behavior Constraints |
121
+ - Read current code and search for existing ownership before creating duplicate modules or contracts.
122
+ - Keep changes inside the requested scope and report uncertainty rather than inventing endpoints, fields, versions, or infrastructure.
123
+ - Never expose secrets, weaken authorization, or bypass data safety merely to make a check pass.
124
+ - Dependency, caller-analysis, and config permissions come only from their selected rule blocks.
281
125
 
282
- **Rendering rules**:
283
- 1. Copy each chapter's full body (including RATIONALE) directly into the corresponding placeholder.
284
- 2. RATIONALE must be preserved — it lets AI understand intent rather than follow mechanically.
285
- 3. Keep the original markdown list structure. Do not rewrite as prose paragraphs.
126
+ Inject into `{{ FIXED_RULES_AI_BASE }}`.
127
+
128
+ ## Injection Contract
129
+
130
+ Copy each invariant block only into its named placeholder. If any invariant conflicts with a selected decision, fail generation and move the policy to a derivation block; never render both.