claude-code-pilot 3.1.1 → 3.3.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.
- package/CHANGELOG.md +57 -0
- package/README.md +16 -11
- package/bin/install.js +127 -11
- package/manifest.json +20 -1
- package/package.json +4 -3
- package/src/agents/a11y-architect.md +141 -0
- package/src/agents/code-architect.md +71 -0
- package/src/agents/code-explorer.md +69 -0
- package/src/agents/code-simplifier.md +47 -0
- package/src/agents/comment-analyzer.md +45 -0
- package/src/agents/csharp-reviewer.md +101 -0
- package/src/agents/dart-build-resolver.md +201 -0
- package/src/agents/django-build-resolver.md +252 -0
- package/src/agents/django-reviewer.md +169 -0
- package/src/agents/fastapi-reviewer.md +79 -0
- package/src/agents/fsharp-reviewer.md +109 -0
- package/src/agents/pr-test-analyzer.md +45 -0
- package/src/agents/silent-failure-hunter.md +50 -0
- package/src/agents/swift-build-resolver.md +170 -0
- package/src/agents/swift-reviewer.md +116 -0
- package/src/agents/type-design-analyzer.md +41 -0
- package/src/available-rules/README.md +3 -1
- package/src/available-rules/dart/coding-style.md +159 -0
- package/src/available-rules/dart/hooks.md +66 -0
- package/src/available-rules/dart/patterns.md +261 -0
- package/src/available-rules/dart/security.md +135 -0
- package/src/available-rules/dart/testing.md +215 -0
- package/src/available-rules/web/coding-style.md +105 -0
- package/src/available-rules/web/design-quality.md +72 -0
- package/src/available-rules/web/hooks.md +129 -0
- package/src/available-rules/web/patterns.md +88 -0
- package/src/available-rules/web/performance.md +73 -0
- package/src/available-rules/web/security.md +66 -0
- package/src/available-rules/web/testing.md +64 -0
- package/src/commands/ccp/ai-integration-phase.md +36 -0
- package/src/commands/ccp/audit-fix.md +33 -0
- package/src/commands/ccp/code-review-fix.md +52 -0
- package/src/commands/ccp/cost-report.md +107 -0
- package/src/commands/ccp/eval-review.md +32 -0
- package/src/commands/ccp/extract_learnings.md +22 -0
- package/src/commands/ccp/import.md +37 -0
- package/src/commands/ccp/ingest-docs.md +42 -0
- package/src/commands/ccp/intel.md +179 -0
- package/src/commands/ccp/mvp-phase.md +45 -0
- package/src/commands/ccp/plan-prd.md +160 -0
- package/src/commands/ccp/plan-review-convergence.md +58 -0
- package/src/commands/ccp/pr-ecc.md +184 -0
- package/src/commands/ccp/scan.md +26 -0
- package/src/commands/ccp/security-scan.md +74 -0
- package/src/commands/ccp/sketch-wrap-up.md +31 -0
- package/src/commands/ccp/sketch.md +54 -0
- package/src/commands/ccp/spec-phase.md +62 -0
- package/src/commands/ccp/spike-wrap-up.md +31 -0
- package/src/commands/ccp/spike.md +51 -0
- package/src/commands/ccp/ultraplan-phase.md +33 -0
- package/src/hooks/ccp-bash-hook-dispatcher.js +96 -0
- package/src/hooks/ccp-context-monitor.js +23 -0
- package/src/hooks/ccp-doc-file-warning.js +93 -0
- package/src/hooks/ccp-pre-bash-dispatcher.js +24 -0
- package/src/hooks/ccp-read-injection-scanner.js +152 -0
- package/src/hooks/ccp-write-gateguard.js +868 -0
- package/src/hooks/kit-check-update.js +59 -7
- package/src/hooks/run-with-flags-shell.sh +1 -0
- package/src/hooks/run-with-flags.js +48 -1
- package/src/hooks/session-end.js +88 -1
- package/src/lib/hook-flags.js +14 -0
- package/src/lib/project-detect.js +0 -2
- package/src/lib/shell-substitution.js +499 -0
- package/src/pilot/references/agent-contracts.md +79 -0
- package/src/pilot/references/ai-evals.md +156 -0
- package/src/pilot/references/ai-frameworks.md +186 -0
- package/src/pilot/references/doc-conflict-engine.md +91 -0
- package/src/pilot/references/execute-mvp-tdd.md +81 -0
- package/src/pilot/references/gate-prompts.md +100 -0
- package/src/pilot/references/gates.md +70 -0
- package/src/pilot/references/mandatory-initial-read.md +2 -0
- package/src/pilot/references/mvp-concepts.md +49 -0
- package/src/pilot/references/planner-graphify-auto-update.md +67 -0
- package/src/pilot/references/planner-human-verify-mode.md +57 -0
- package/src/pilot/references/planner-mvp-mode.md +53 -0
- package/src/pilot/references/project-skills-discovery.md +19 -0
- package/src/pilot/references/revision-loop.md +97 -0
- package/src/pilot/references/skeleton-template.md +48 -0
- package/src/pilot/references/sketch-interactivity.md +41 -0
- package/src/pilot/references/sketch-theme-system.md +94 -0
- package/src/pilot/references/sketch-tooling.md +45 -0
- package/src/pilot/references/sketch-variant-patterns.md +81 -0
- package/src/pilot/references/spidr-splitting.md +69 -0
- package/src/pilot/references/thinking-models-debug.md +44 -0
- package/src/pilot/references/thinking-models-execution.md +50 -0
- package/src/pilot/references/thinking-models-planning.md +62 -0
- package/src/pilot/references/thinking-models-research.md +50 -0
- package/src/pilot/references/thinking-models-verification.md +55 -0
- package/src/pilot/references/user-story-template.md +58 -0
- package/src/pilot/references/verify-mvp-mode.md +85 -0
- package/src/pilot/references/worktree-path-safety.md +89 -0
- package/src/pilot/templates/AI-SPEC.md +246 -0
- package/src/pilot/templates/spec.md +307 -0
- package/src/pilot/workflows/ai-integration-phase.md +284 -0
- package/src/pilot/workflows/audit-fix.md +175 -0
- package/src/pilot/workflows/code-review-fix.md +497 -0
- package/src/pilot/workflows/eval-review.md +155 -0
- package/src/pilot/workflows/extract_learnings.md +242 -0
- package/src/pilot/workflows/help.md +5 -0
- package/src/pilot/workflows/import.md +246 -0
- package/src/pilot/workflows/ingest-docs.md +328 -0
- package/src/pilot/workflows/mvp-phase.md +199 -0
- package/src/pilot/workflows/plan-review-convergence.md +329 -0
- package/src/pilot/workflows/scan.md +102 -0
- package/src/pilot/workflows/sketch-wrap-up.md +285 -0
- package/src/pilot/workflows/sketch.md +360 -0
- package/src/pilot/workflows/spec-phase.md +262 -0
- package/src/pilot/workflows/spike-wrap-up.md +306 -0
- package/src/pilot/workflows/spike.md +452 -0
- package/src/pilot/workflows/ultraplan-phase.md +189 -0
- package/src/skills/accessibility/SKILL.md +146 -0
- package/src/skills/agent-architecture-audit/SKILL.md +256 -0
- package/src/skills/agent-eval/SKILL.md +145 -0
- package/src/skills/agent-harness-design/SKILL.md +73 -0
- package/src/skills/agent-introspection-debugging/SKILL.md +153 -0
- package/src/skills/android-clean-architecture/SKILL.md +339 -0
- package/src/skills/angular-developer/SKILL.md +154 -0
- package/src/skills/angular-developer/references/angular-animations.md +160 -0
- package/src/skills/angular-developer/references/angular-aria.md +410 -0
- package/src/skills/angular-developer/references/cli.md +86 -0
- package/src/skills/angular-developer/references/component-harnesses.md +59 -0
- package/src/skills/angular-developer/references/component-styling.md +91 -0
- package/src/skills/angular-developer/references/components.md +117 -0
- package/src/skills/angular-developer/references/creating-services.md +97 -0
- package/src/skills/angular-developer/references/data-resolvers.md +69 -0
- package/src/skills/angular-developer/references/define-routes.md +67 -0
- package/src/skills/angular-developer/references/defining-providers.md +72 -0
- package/src/skills/angular-developer/references/di-fundamentals.md +120 -0
- package/src/skills/angular-developer/references/e2e-testing.md +56 -0
- package/src/skills/angular-developer/references/effects.md +83 -0
- package/src/skills/angular-developer/references/hierarchical-injectors.md +43 -0
- package/src/skills/angular-developer/references/host-elements.md +80 -0
- package/src/skills/angular-developer/references/injection-context.md +63 -0
- package/src/skills/angular-developer/references/inputs.md +101 -0
- package/src/skills/angular-developer/references/linked-signal.md +59 -0
- package/src/skills/angular-developer/references/loading-strategies.md +61 -0
- package/src/skills/angular-developer/references/mcp.md +108 -0
- package/src/skills/angular-developer/references/navigate-to-routes.md +69 -0
- package/src/skills/angular-developer/references/outputs.md +86 -0
- package/src/skills/angular-developer/references/reactive-forms.md +122 -0
- package/src/skills/angular-developer/references/rendering-strategies.md +44 -0
- package/src/skills/angular-developer/references/resource.md +77 -0
- package/src/skills/angular-developer/references/route-animations.md +56 -0
- package/src/skills/angular-developer/references/route-guards.md +52 -0
- package/src/skills/angular-developer/references/router-lifecycle.md +45 -0
- package/src/skills/angular-developer/references/router-testing.md +87 -0
- package/src/skills/angular-developer/references/show-routes-with-outlets.md +68 -0
- package/src/skills/angular-developer/references/signal-forms.md +795 -0
- package/src/skills/angular-developer/references/signals-overview.md +94 -0
- package/src/skills/angular-developer/references/tailwind-css.md +69 -0
- package/src/skills/angular-developer/references/template-driven-forms.md +114 -0
- package/src/skills/angular-developer/references/testing-fundamentals.md +65 -0
- package/src/skills/api-connector-builder/SKILL.md +120 -0
- package/src/skills/code-tour/SKILL.md +236 -0
- package/src/skills/compose-multiplatform-patterns/SKILL.md +299 -0
- package/src/skills/csharp-testing/SKILL.md +321 -0
- package/src/skills/dart-flutter-patterns/SKILL.md +563 -0
- package/src/skills/dashboard-builder/SKILL.md +108 -0
- package/src/skills/dotnet-patterns/SKILL.md +321 -0
- package/src/skills/error-handling/SKILL.md +376 -0
- package/src/skills/fastapi-patterns/SKILL.md +327 -0
- package/src/skills/flox-environments/SKILL.md +496 -0
- package/src/skills/frontend-design/SKILL.md +145 -0
- package/src/skills/frontend-slides/SKILL.md +184 -0
- package/src/skills/frontend-slides/STYLE_PRESETS.md +330 -0
- package/src/skills/fsharp-testing/SKILL.md +280 -0
- package/src/skills/gateguard/SKILL.md +121 -0
- package/src/skills/github-ops/SKILL.md +144 -0
- package/src/skills/hookify-rules/SKILL.md +128 -0
- package/src/skills/ios-icon-gen/SKILL.md +157 -0
- package/src/skills/ios-icon-gen/scripts/generate_icons.swift +258 -0
- package/src/skills/ios-icon-gen/scripts/iconify_gen.sh +235 -0
- package/src/skills/knowledge-ops/SKILL.md +154 -0
- package/src/skills/liquid-glass-design/SKILL.md +279 -0
- package/src/skills/make-interfaces-feel-better/SKILL.md +151 -0
- package/src/skills/mysql-patterns/SKILL.md +412 -0
- package/src/skills/nestjs-patterns/SKILL.md +230 -0
- package/src/skills/plan-orchestrate/SKILL.md +220 -0
- package/src/skills/prisma-patterns/SKILL.md +371 -0
- package/src/skills/production-audit/SKILL.md +206 -0
- package/src/skills/security-bounty-hunter/SKILL.md +99 -0
- package/src/skills/security-scan/references/agentshield-policy-exception/candidate-playbook.md +49 -0
- package/src/skills/security-scan/references/agentshield-policy-exception/report.json +35 -0
- package/src/skills/security-scan/references/agentshield-policy-exception/scenario.json +62 -0
- package/src/skills/security-scan/references/agentshield-policy-exception/trace.json +45 -0
- package/src/skills/security-scan/references/agentshield-policy-exception/verifier-result.json +35 -0
- package/src/skills/swift-actor-persistence/SKILL.md +143 -0
- package/src/skills/swift-protocol-di-testing/SKILL.md +190 -0
- package/src/skills/swiftui-patterns/SKILL.md +259 -0
- package/src/skills/terminal-ops/SKILL.md +109 -0
- package/src/skills/ui-demo/SKILL.md +465 -0
- package/src/skills/vite-patterns/SKILL.md +449 -0
- package/src/skills/windows-desktop-e2e/SKILL.md +887 -0
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: plan-orchestrate
|
|
3
|
+
description: Read a plan document, decompose it into steps, design a per-step agent chain from the CCP catalogue, and emit ready-to-paste /orchestrate custom prompts. Generative only — never invokes /orchestrate itself. Use when the user has a multi-step plan and wants to drive it through orchestrate without composing chains by hand.
|
|
4
|
+
origin: ECC
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Plan Orchestrate
|
|
8
|
+
|
|
9
|
+
Bridge a plan document to `/orchestrate custom` by emitting one ready-to-paste invocation per step. The skill is generative only — it never executes `/orchestrate`. The user pastes each line when ready.
|
|
10
|
+
|
|
11
|
+
## When to Activate
|
|
12
|
+
|
|
13
|
+
- User has a multi-step plan document (PRD, RFC, implementation plan) and wants to drive it through `/orchestrate`.
|
|
14
|
+
- User says "orchestrate this plan", "give me orchestrate prompts for each step", "compose chains for this plan".
|
|
15
|
+
- A step-by-step plan exists but the user does not want to manually pick agents per step.
|
|
16
|
+
|
|
17
|
+
Skip when:
|
|
18
|
+
- The work is one ad-hoc step → call `/orchestrate custom` directly.
|
|
19
|
+
- The plan is unreadable or empty. Lack of explicit numbering alone is not a skip condition — see the "No clear steps" edge case below.
|
|
20
|
+
|
|
21
|
+
## Inputs
|
|
22
|
+
|
|
23
|
+
```
|
|
24
|
+
<plan-doc-path> [--lang=python|typescript|go|rust|cpp|java|kotlin|flutter|auto] [--scope=all|step:<n>|range:<a>-<b>] [--dry-run]
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
- `<plan-doc-path>` — required; relative or absolute path (`@docs/...` accepted).
|
|
28
|
+
- `--lang` — reviewer language variant; defaults to `auto` (detected from project).
|
|
29
|
+
- `--scope` — limits emitted steps; defaults to `all`.
|
|
30
|
+
- `--dry-run` — print decomposition + chain rationale only; do not emit final prompts.
|
|
31
|
+
|
|
32
|
+
## Authoritative `/orchestrate` shape (do not deviate)
|
|
33
|
+
|
|
34
|
+
```
|
|
35
|
+
/orchestrate custom "<agent1>,<agent2>,...,<agentN>" "<task description>"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
- `custom` is a sequential chain; each agent's HANDOFF feeds the next.
|
|
39
|
+
- Comma-separated agent list. No spaces preferred; one space tolerated.
|
|
40
|
+
- No `--mode` / `--gate` / `--agents=...` flags exist — never invent them.
|
|
41
|
+
- Agent names come from the catalogue in this skill. Embedded double quotes in the task description are escaped as `\"`.
|
|
42
|
+
- Agent names are bare (`<name>`), matching how CCP installs them into `<claude-home>/agents/`.
|
|
43
|
+
|
|
44
|
+
## Available agent catalogue (must pick from these)
|
|
45
|
+
|
|
46
|
+
General:
|
|
47
|
+
- `planner` — requirement restatement, risk decomposition, step planning
|
|
48
|
+
- `architect` — architecture, system design, refactor proposals
|
|
49
|
+
- `tdd-guide` — write tests → implement → 80%+ coverage
|
|
50
|
+
- `code-reviewer` — generic code review
|
|
51
|
+
- `security-reviewer` — security audit, OWASP, secret leakage
|
|
52
|
+
- `refactor-cleaner` — dead code, duplicates, knip-class cleanup
|
|
53
|
+
- `doc-updater` — documentation, codemap, README
|
|
54
|
+
- `docs-lookup` — third-party library API lookups (Context7)
|
|
55
|
+
- `e2e-runner` — end-to-end test orchestration
|
|
56
|
+
- `database-reviewer` — PostgreSQL schema, migration, performance
|
|
57
|
+
- `harness-optimizer` — local agent harness configuration
|
|
58
|
+
- `loop-operator` — long-running autonomous loops
|
|
59
|
+
- `chief-of-staff` — multi-channel triage (rarely a fit for plan steps)
|
|
60
|
+
|
|
61
|
+
Build error resolvers:
|
|
62
|
+
- `build-error-resolver` (generic) / `cpp-build-resolver` / `go-build-resolver` / `java-build-resolver` / `kotlin-build-resolver` / `rust-build-resolver` / `pytorch-build-resolver`
|
|
63
|
+
|
|
64
|
+
Code reviewers:
|
|
65
|
+
- `python-reviewer` / `typescript-reviewer` / `go-reviewer` / `rust-reviewer` / `cpp-reviewer` / `java-reviewer` / `kotlin-reviewer` / `flutter-reviewer`
|
|
66
|
+
|
|
67
|
+
A misspelled agent name fails `/orchestrate`. Cross-check against this list before emitting.
|
|
68
|
+
|
|
69
|
+
## How It Works
|
|
70
|
+
|
|
71
|
+
### Phase 0 — Detect language
|
|
72
|
+
|
|
73
|
+
1. Read `<plan-doc-path>`. If missing or empty, report and stop.
|
|
74
|
+
2. Resolve `--lang`. When `auto`, run a polyglot-aware detection:
|
|
75
|
+
- Probe markers: `pyproject.toml` / `uv.lock` / `requirements.txt` → python; `package.json` → typescript; `go.mod` → go; `Cargo.toml` → rust; `CMakeLists.txt` or top-level `*.cpp` → cpp; `pom.xml` / `build.gradle` (Java) → java; `build.gradle.kts` or top-level Kotlin → kotlin; `pubspec.yaml` → flutter.
|
|
76
|
+
- **Polyglot tie-break**: if more than one marker matches, pick the language whose source files outnumber the others (count via `git ls-files`, excluding `vendor/`, `node_modules/`, `dist/`, `build/`, `.venv/`, generated files, and obvious test fixtures). On a tie or when no language exceeds 60% of source files, set `lang=unknown`.
|
|
77
|
+
- No marker matched → set `lang=unknown`.
|
|
78
|
+
- `lang=unknown` is a sentinel — it is **not** an agent name. Phase 2 rules 4 and 5 turn it into `code-reviewer` / `build-error-resolver` at chain composition time.
|
|
79
|
+
4. Detect a **PyTorch sub-profile**: when `lang=python` and any of `pyproject.toml` / `requirements.txt` / `uv.lock` declares a dependency on `torch`, set `pytorch=true`. This only affects `build` chain selection (Phase 2 rule below); the reviewer remains `python-reviewer`.
|
|
80
|
+
5. **Normalize any agent names declared in the plan**: if the plan text references agents by a plugin-prefixed form (e.g. `<namespace>:tdd-guide`), strip the prefix to get the bare catalogue name before validating or composing chains. CCP emits bare names only; never let a pre-prefixed name flow into the output.
|
|
81
|
+
|
|
82
|
+
### Phase 1 — Decompose steps
|
|
83
|
+
|
|
84
|
+
Identify "step units" in priority order:
|
|
85
|
+
|
|
86
|
+
1. Explicit numbering: `## Step N` / `### Phase N` / `## N. ...` / top-level ordered list.
|
|
87
|
+
2. A "Step" column in a table.
|
|
88
|
+
3. `---`-separated blocks with verb-led headings.
|
|
89
|
+
4. Otherwise treat each H2 as one step.
|
|
90
|
+
|
|
91
|
+
Per step extract `id` (1-based), `title` (≤ 80 chars), `intent` (1–3 sentences), `tags`.
|
|
92
|
+
|
|
93
|
+
### Phase 2 — Tag and pick chain
|
|
94
|
+
|
|
95
|
+
Tag by intent (multi-tag allowed; chain built from primary + stacked secondaries):
|
|
96
|
+
|
|
97
|
+
Trigger words below are matched case-insensitively. Multilingual plans are supported by matching the word stems in any language as long as the meaning aligns with the listed English trigger words.
|
|
98
|
+
|
|
99
|
+
| Tag | Trigger words | Default chain |
|
|
100
|
+
|---|---|---|
|
|
101
|
+
| `design` | architecture, design, choose, evaluate, RFC | `planner,architect` |
|
|
102
|
+
| `plan` | plan, breakdown, milestone | `planner` |
|
|
103
|
+
| `impl` | implement, build, add, create, port | `tdd-guide,<lang>-reviewer` |
|
|
104
|
+
| `test` | test, coverage, e2e, integration | `tdd-guide,e2e-runner` |
|
|
105
|
+
| `refactor` | refactor, cleanup, dedupe, split | `architect,refactor-cleaner,<lang>-reviewer` |
|
|
106
|
+
| `migration` | migrate, upgrade, rewrite, port | `architect,tdd-guide,<lang>-reviewer` |
|
|
107
|
+
| `db` | schema, migration, index, SQL, Postgres, alembic, sqlmodel | `database-reviewer,<lang>-reviewer` |
|
|
108
|
+
| `security` | encrypt, auth, secret, OWASP, PII | `security-reviewer,<lang>-reviewer` |
|
|
109
|
+
| `build` | build, compile, lint failure, CI | `<lang>-build-resolver` (falls back to `build-error-resolver`) |
|
|
110
|
+
| `docs` | docs, readme, codemap, changelog | `doc-updater` |
|
|
111
|
+
| `lookup` | lookup, reference, API usage | `docs-lookup` |
|
|
112
|
+
| `review` | review, audit, verify | `<lang>-reviewer,code-reviewer` |
|
|
113
|
+
| `loop` | loop, autonomous, watchdog | `loop-operator` |
|
|
114
|
+
|
|
115
|
+
Chain composition rules:
|
|
116
|
+
1. **Primary tag selection**: when a step matches multiple tags, the **first one in table order** (top of the table = highest priority) is the primary; the rest are secondaries. Composition rules 2 and 3 below handle specific multi-tag combinations explicitly; otherwise, append secondary chains in tag table order.
|
|
117
|
+
2. `impl` + `security` → `tdd-guide,<lang>-reviewer,security-reviewer`.
|
|
118
|
+
3. `impl` + `db` → `tdd-guide,database-reviewer,<lang>-reviewer`.
|
|
119
|
+
4. **Deduplicate** the resulting chain (preserve first occurrence). E.g. `review` + `lang=unknown` would yield `code-reviewer,code-reviewer` after rule 5; deduplication collapses it to `code-reviewer`.
|
|
120
|
+
5. `<lang>-reviewer` resolves to `code-reviewer` when `lang=unknown`.
|
|
121
|
+
6. `<lang>-build-resolver` resolves to `build-error-resolver` when `lang=unknown`. **Special case**: if Phase 0 set `pytorch=true`, use `pytorch-build-resolver` for `build` chains regardless of `<lang>`. There is no `python-build-resolver`; `--lang=python` without `pytorch=true` resolves to `build-error-resolver`.
|
|
122
|
+
7. **Zero-tag steps**: if no trigger word matches, set chain to `code-reviewer` and write `no tag matched; default review-only chain` under "Chain rationale".
|
|
123
|
+
8. Chain length ≤ 4 after deduplication. If exceeded, drop weakest tag (`lookup` and `docs` first).
|
|
124
|
+
9. Do not pair `planner` and `architect` in an `impl` chain (token waste). Pair them only on `design` steps.
|
|
125
|
+
10. Steps tagged `impl`, `refactor`, or `migration` end with a **reviewer-class** agent — any of `<lang>-reviewer`, `code-reviewer`, `security-reviewer`, or `database-reviewer`. The most domain-specific reviewer wins the tail position (e.g. rule 2's `impl+security` ends with `security-reviewer`; rule 3's `impl+db` ends with `<lang>-reviewer` because `database-reviewer` already gates the migration earlier in the chain). `test` and `build` steps are gated by their own validators (`e2e-runner` and the build resolver respectively) and do not require an additional reviewer.
|
|
126
|
+
|
|
127
|
+
### Phase 3 — Compress task description
|
|
128
|
+
|
|
129
|
+
Each emitted `<task description>` must:
|
|
130
|
+
- Be self-contained (the first agent does not need the plan document open).
|
|
131
|
+
- Start with `[Plan: <path>#step-<id>]`.
|
|
132
|
+
- Include 1–3 verifiable Acceptance criteria.
|
|
133
|
+
- Include a Scope guard (`Out of scope: ...`) **only if the plan declares one for this step**. Inherit verbatim. If the plan has no out-of-scope statement, omit the clause entirely — do not invent one.
|
|
134
|
+
- Be 200–600 characters; one line; embedded `"` escaped as `\"`; no literal newlines.
|
|
135
|
+
|
|
136
|
+
### Phase 4 — Output
|
|
137
|
+
|
|
138
|
+
Emit Markdown using the bare-name form. The slash command is always `/orchestrate` and every agent name is rendered as a bare catalogue name (no namespace prefix).
|
|
139
|
+
|
|
140
|
+
Output structure:
|
|
141
|
+
|
|
142
|
+
````markdown
|
|
143
|
+
# Plan-Orchestrate Result
|
|
144
|
+
|
|
145
|
+
**Plan**: `<path>`
|
|
146
|
+
**Lang**: `<detected-or-given>`
|
|
147
|
+
**Steps**: <N>
|
|
148
|
+
**Scope**: <all | step:n | range:a-b>
|
|
149
|
+
|
|
150
|
+
## Steps overview
|
|
151
|
+
|
|
152
|
+
| # | Title | Tags | Chain |
|
|
153
|
+
|---|---|---|---|
|
|
154
|
+
| 1 | ... | impl, db | `tdd-guide,database-reviewer,python-reviewer` |
|
|
155
|
+
| ... | | | |
|
|
156
|
+
|
|
157
|
+
---
|
|
158
|
+
|
|
159
|
+
## Step 1 — <title>
|
|
160
|
+
|
|
161
|
+
**Intent**: <1–3 sentences>
|
|
162
|
+
**Tags**: <a, b>
|
|
163
|
+
**Chain rationale**: <why this chain; which agent closes the loop>
|
|
164
|
+
|
|
165
|
+
```bash
|
|
166
|
+
/orchestrate custom "tdd-guide,database-reviewer,python-reviewer" "[Plan: docs/foo.md#step-1] <compressed task description>; Acceptance: <1–3 items>; Out of scope: <…>"
|
|
167
|
+
```
|
|
168
|
+
````
|
|
169
|
+
|
|
170
|
+
Append a final "Batch execution" block aggregating every step's command in order so the user can paste them all at once. **Skip the Batch block in overview-only mode** (see "Large plan" edge case): when only the overview table is being emitted, there are no per-step commands to aggregate.
|
|
171
|
+
|
|
172
|
+
### Phase 5 — Self-check (run before emitting)
|
|
173
|
+
|
|
174
|
+
- [ ] Every agent in every chain comes from the catalogue (after stripping any plugin namespace prefix that appeared in the plan; see Phase 0 step 5).
|
|
175
|
+
- [ ] All emitted agent names are bare (no namespace prefix) and the slash command is `/orchestrate`.
|
|
176
|
+
- [ ] No invented `--mode` / `--gate` / `--agents=...` fields.
|
|
177
|
+
- [ ] Each task description is single-line, double-quoted, with embedded `"` escaped.
|
|
178
|
+
- [ ] Each task description begins with `[Plan: <path>#step-<id>]` and includes Acceptance (1–3 items). The `Out of scope:` clause is present only when inherited from the plan.
|
|
179
|
+
- [ ] No duplicate agent in any chain after Phase 2 dedup.
|
|
180
|
+
- [ ] Chain length ≤ 4.
|
|
181
|
+
- [ ] Steps tagged `impl`/`refactor`/`migration` end with a reviewer-class agent (`<lang>-reviewer`, `code-reviewer`, `security-reviewer`, or `database-reviewer`). `test` and `build` are exempt — see Phase 2 rule 10.
|
|
182
|
+
- [ ] Zero-tag steps emit `code-reviewer` with the rationale `no tag matched; default review-only chain`.
|
|
183
|
+
- [ ] Overview table lists every step in the plan, regardless of `--scope`.
|
|
184
|
+
- [ ] Per-step detail block count matches the resolved `--scope` (full plan when `--scope=all`; one block for `step:n`; range size for `range:a-b`). In overview-only mode, no per-step blocks and no Batch block are emitted.
|
|
185
|
+
|
|
186
|
+
## Edge cases
|
|
187
|
+
|
|
188
|
+
- **No clear steps**: prefer H2/H3 splitting; if still ambiguous, report "no structured steps detected" with the document outline and ask the user to confirm running by outline.
|
|
189
|
+
- **Large plan (>1500 lines)**: enter **overview-only mode** — emit only the overview table and ask the user to narrow with `--scope` before re-running for details. In this mode, skip per-step detail blocks and skip the Batch execution block.
|
|
190
|
+
- **Step too broad** (e.g. "complete all backend work"): do not force a single chain. Suggest splitting into N.a and N.b and propose a split.
|
|
191
|
+
- **Plan declares agents** (rare): first **strip any plugin namespace prefix** (e.g. `<namespace>:tdd-guide`) to get the bare catalogue name (Phase 0 step 5), then validate against the catalogue. Replace invalid agents and explain under "Chain rationale".
|
|
192
|
+
- **Polyglot project where `--lang=auto` cannot pick a winner**: set `lang=unknown`; reviewer resolves to `code-reviewer` and build resolver to `build-error-resolver`. Mention the fallback under "Chain rationale".
|
|
193
|
+
|
|
194
|
+
## Examples
|
|
195
|
+
|
|
196
|
+
### Example — Python plan
|
|
197
|
+
|
|
198
|
+
Input:
|
|
199
|
+
```
|
|
200
|
+
plan-orchestrate @docs/plan/example-feature.md --lang=python
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Excerpt of expected output:
|
|
204
|
+
````markdown
|
|
205
|
+
## Step 2 — Encrypt sensitive UserProfile fields
|
|
206
|
+
|
|
207
|
+
**Intent**: Introduce an `EncryptedString` SQLAlchemy type and AES-GCM encrypt `birth_datetime` / `location` before persistence; load the key from an environment variable.
|
|
208
|
+
**Tags**: impl, security, db
|
|
209
|
+
**Chain rationale**: Security-sensitive write path, so `security-reviewer` closes the chain; `database-reviewer` validates the alembic migration; `python-reviewer` covers typing and PEP 8.
|
|
210
|
+
|
|
211
|
+
```bash
|
|
212
|
+
/orchestrate custom "tdd-guide,database-reviewer,python-reviewer,security-reviewer" "[Plan: docs/plan/example-feature.md#step-2] Implement EncryptedString SQLAlchemy type and migrate UserProfile.birth_datetime/location columns; key from ENV APP_DB_KEY; Acceptance: encrypt/decrypt roundtrip tests pass; alembic upgrade/downgrade clean on empty DB; no plaintext in DB after migrate; Out of scope: cross-tenant profile sharing logic"
|
|
213
|
+
```
|
|
214
|
+
````
|
|
215
|
+
|
|
216
|
+
## Notes
|
|
217
|
+
|
|
218
|
+
- Generative only. Never invoke `/orchestrate` from inside this skill.
|
|
219
|
+
- Match the language of the plan document for task descriptions (agent names always remain English).
|
|
220
|
+
- Do not insert "Co-Authored-By" lines or emoji in the output unless the user explicitly asks.
|
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: prisma-patterns
|
|
3
|
+
description: Prisma ORM patterns for TypeScript backends — schema design, query optimization, transactions, pagination, and critical traps like updateMany returning count not records, $transaction timeouts, migrate dev resetting the DB, @updatedAt skipped on bulk writes, and serverless connection exhaustion.
|
|
4
|
+
origin: ECC
|
|
5
|
+
---
|
|
6
|
+
|
|
7
|
+
# Prisma Patterns
|
|
8
|
+
|
|
9
|
+
Production patterns and non-obvious traps for Prisma ORM in TypeScript backends.
|
|
10
|
+
Tested against Prisma 5.x and 6.x. Some behaviors differ from Prisma 4.
|
|
11
|
+
|
|
12
|
+
Check the Prisma version before applying version-specific patterns:
|
|
13
|
+
|
|
14
|
+
```bash
|
|
15
|
+
npx prisma --version
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Prisma 5 introduced `relationJoins`, which can load relations via JOIN rather than separate queries depending on query strategy and configuration. The `omit` field modifier and `prisma.$extends` Client Extensions API were also added. Note: `relationJoins` can cause row explosion on large 1:N relations or deep nested `include` — benchmark both approaches when relations may return many rows per parent.
|
|
19
|
+
|
|
20
|
+
## When to Activate
|
|
21
|
+
|
|
22
|
+
- Designing or modifying Prisma schema models and relations
|
|
23
|
+
- Writing queries, transactions, or pagination logic
|
|
24
|
+
- Using `updateMany`, `deleteMany`, or any bulk operation
|
|
25
|
+
- Running or planning database migrations
|
|
26
|
+
- Deploying to serverless environments (Vercel, Lambda, Cloudflare Workers)
|
|
27
|
+
- Implementing soft delete or multi-tenant row filtering
|
|
28
|
+
|
|
29
|
+
## Core Concepts
|
|
30
|
+
|
|
31
|
+
### ID Strategy
|
|
32
|
+
|
|
33
|
+
| Strategy | Use When | Avoid When |
|
|
34
|
+
|---|---|---|
|
|
35
|
+
| `@default(cuid())` | Default choice — URL-safe, sortable, no collisions | Sequential IDs needed for external systems |
|
|
36
|
+
| `@default(uuid())` | Interoperability with non-Prisma systems required | High-write tables (random UUIDs fragment B-tree indexes) |
|
|
37
|
+
| `@default(autoincrement())` | Internal join tables, audit logs | Public-facing IDs (exposes record count) |
|
|
38
|
+
|
|
39
|
+
### Schema Defaults
|
|
40
|
+
|
|
41
|
+
```prisma
|
|
42
|
+
model User {
|
|
43
|
+
id String @id @default(cuid())
|
|
44
|
+
email String @unique // @unique already creates an index — no @@index needed
|
|
45
|
+
name String
|
|
46
|
+
role Role @default(USER)
|
|
47
|
+
posts Post[]
|
|
48
|
+
createdAt DateTime @default(now())
|
|
49
|
+
updatedAt DateTime @updatedAt
|
|
50
|
+
deletedAt DateTime?
|
|
51
|
+
|
|
52
|
+
@@index([createdAt])
|
|
53
|
+
@@index([deletedAt, createdAt]) // composite for soft-delete + sort queries
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
- Add `@@index` on every foreign key and column used in `WHERE` or `ORDER BY`.
|
|
58
|
+
- Declare `deletedAt DateTime?` upfront when soft delete is a foreseeable requirement — adding it later requires a migration on a live table.
|
|
59
|
+
- `updatedAt @updatedAt` is set automatically by Prisma on `update` and `upsert` only (see Anti-Patterns for bulk update trap).
|
|
60
|
+
|
|
61
|
+
### `include` vs `select`
|
|
62
|
+
|
|
63
|
+
| | `include` | `select` |
|
|
64
|
+
|---|---|---|
|
|
65
|
+
| Returns | All scalar fields + specified relations | Only specified fields |
|
|
66
|
+
| Use when | You need most fields plus a relation | Hot paths, large tables, avoiding over-fetch |
|
|
67
|
+
| Performance | May over-fetch on wide tables | Minimal payload, faster on large datasets |
|
|
68
|
+
| Prisma 5 note | Uses JOIN by default (`relationJoins`) | Same |
|
|
69
|
+
|
|
70
|
+
```ts
|
|
71
|
+
// include — all columns + relation
|
|
72
|
+
const user = await prisma.user.findUnique({
|
|
73
|
+
where: { id },
|
|
74
|
+
include: { posts: { select: { id: true, title: true } } },
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
// select — explicit allowlist
|
|
78
|
+
const user = await prisma.user.findUnique({
|
|
79
|
+
where: { id },
|
|
80
|
+
select: { id: true, email: true, name: true },
|
|
81
|
+
});
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
Never return raw Prisma entities from API responses — map to response DTOs to control exposed fields:
|
|
85
|
+
|
|
86
|
+
```ts
|
|
87
|
+
// BAD: leaks passwordHash, deletedAt, internal fields
|
|
88
|
+
return await prisma.user.findUniqueOrThrow({ where: { id } });
|
|
89
|
+
|
|
90
|
+
// GOOD: explicit DTO mapping
|
|
91
|
+
const user = await prisma.user.findUniqueOrThrow({ where: { id } });
|
|
92
|
+
return { id: user.id, name: user.name, email: user.email };
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Transaction Form Selection
|
|
96
|
+
|
|
97
|
+
| Situation | Use |
|
|
98
|
+
|---|---|
|
|
99
|
+
| Independent operations, no inter-dependency | Array form |
|
|
100
|
+
| Later step depends on earlier result | Interactive form |
|
|
101
|
+
| External calls (email, HTTP) involved | Outside transaction entirely |
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// Array form — batched in one round trip
|
|
105
|
+
const [user, post] = await prisma.$transaction([
|
|
106
|
+
prisma.user.update({ where: { id }, data: { name } }),
|
|
107
|
+
prisma.post.create({ data: { title, authorId: id } }),
|
|
108
|
+
]);
|
|
109
|
+
|
|
110
|
+
// Interactive form — use tx client only, never the outer prisma client
|
|
111
|
+
const post = await prisma.$transaction(async (tx) => {
|
|
112
|
+
const user = await tx.user.findUniqueOrThrow({ where: { id } });
|
|
113
|
+
if (user.role !== 'ADMIN') throw new Error('Forbidden');
|
|
114
|
+
return tx.post.create({ data: { title, authorId: user.id } });
|
|
115
|
+
});
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
### PrismaClient Singleton
|
|
119
|
+
|
|
120
|
+
Each `PrismaClient` instance opens its own connection pool. Instantiate once.
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
// lib/prisma.ts
|
|
124
|
+
import { PrismaClient } from '@prisma/client';
|
|
125
|
+
|
|
126
|
+
const globalForPrisma = globalThis as unknown as { prisma?: PrismaClient };
|
|
127
|
+
|
|
128
|
+
export const prisma =
|
|
129
|
+
globalForPrisma.prisma ??
|
|
130
|
+
new PrismaClient({
|
|
131
|
+
log: process.env.NODE_ENV === 'development' ? ['query', 'error'] : ['error'],
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma;
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
The `globalThis` pattern prevents duplicate instances during hot reload (Next.js, nodemon, ts-node-dev).
|
|
138
|
+
|
|
139
|
+
### N+1 Problem
|
|
140
|
+
|
|
141
|
+
Loading relations inside a loop issues one query per row.
|
|
142
|
+
|
|
143
|
+
```ts
|
|
144
|
+
// BAD: N+1 — one extra query per user
|
|
145
|
+
const users = await prisma.user.findMany();
|
|
146
|
+
for (const user of users) {
|
|
147
|
+
const posts = await prisma.post.findMany({ where: { authorId: user.id } });
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// GOOD: single query
|
|
151
|
+
const users = await prisma.user.findMany({ include: { posts: true } });
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
With Prisma 5+ `relationJoins`, the `include` form uses a single JOIN. On large 1:N sets this may increase result set size — benchmark both approaches if the relation can return many rows per parent.
|
|
155
|
+
|
|
156
|
+
## Code Examples
|
|
157
|
+
|
|
158
|
+
### Cursor Pagination (preferred for feeds and large datasets)
|
|
159
|
+
|
|
160
|
+
```ts
|
|
161
|
+
async function getPosts(cursor?: string, limit = 20) {
|
|
162
|
+
const items = await prisma.post.findMany({
|
|
163
|
+
where: { published: true },
|
|
164
|
+
orderBy: [
|
|
165
|
+
{ createdAt: 'desc' },
|
|
166
|
+
{ id: 'desc' }, // secondary sort prevents unstable pagination on duplicate timestamps
|
|
167
|
+
],
|
|
168
|
+
take: limit + 1,
|
|
169
|
+
...(cursor && { cursor: { id: cursor }, skip: 1 }),
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
const hasNextPage = items.length > limit;
|
|
173
|
+
if (hasNextPage) items.pop();
|
|
174
|
+
|
|
175
|
+
return { items, nextCursor: hasNextPage ? items[items.length - 1].id : null };
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
Fetch `limit + 1` and pop — canonical way to detect `hasNextPage` without an extra count query. Always include a unique field (e.g. `id`) as a secondary `orderBy` to prevent unstable pagination when multiple rows share the same timestamp. Use offset pagination only when users need to jump to arbitrary pages (admin tables).
|
|
180
|
+
|
|
181
|
+
### Soft Delete
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
// Always filter explicitly — do not rely on middleware (hides behavior, hard to debug)
|
|
185
|
+
const activeUsers = await prisma.user.findMany({ where: { deletedAt: null } });
|
|
186
|
+
|
|
187
|
+
await prisma.user.update({ where: { id }, data: { deletedAt: new Date() } });
|
|
188
|
+
await prisma.user.update({ where: { id }, data: { deletedAt: null } }); // restore
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
### Error Handling
|
|
192
|
+
|
|
193
|
+
```ts
|
|
194
|
+
import { Prisma } from '@prisma/client';
|
|
195
|
+
|
|
196
|
+
try {
|
|
197
|
+
await prisma.user.create({ data: { email } });
|
|
198
|
+
} catch (e) {
|
|
199
|
+
if (e instanceof Prisma.PrismaClientKnownRequestError) {
|
|
200
|
+
if (e.code === 'P2002') throw new ConflictError('Email already exists');
|
|
201
|
+
if (e.code === 'P2025') throw new NotFoundError('Record not found');
|
|
202
|
+
if (e.code === 'P2003') throw new BadRequestError('Referenced record does not exist');
|
|
203
|
+
}
|
|
204
|
+
throw e;
|
|
205
|
+
}
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Common codes: `P2002` unique violation · `P2025` not found · `P2003` foreign key violation.
|
|
209
|
+
|
|
210
|
+
Catch at the service boundary and translate to domain errors. Never expose raw Prisma messages to API consumers.
|
|
211
|
+
|
|
212
|
+
### Connection Pool — Serverless
|
|
213
|
+
|
|
214
|
+
Embed connection params directly in `DATABASE_URL` — string concatenation breaks if the URL already has query parameters (e.g. `?schema=public`):
|
|
215
|
+
|
|
216
|
+
```bash
|
|
217
|
+
# .env — preferred: embed params in the URL
|
|
218
|
+
DATABASE_URL="postgresql://user:pass@host/db?connection_limit=1&pool_timeout=20"
|
|
219
|
+
|
|
220
|
+
# With an external pooler (PgBouncer, Supabase pooler)
|
|
221
|
+
DATABASE_URL="postgresql://user:pass@host/db?pgbouncer=true&connection_limit=1"
|
|
222
|
+
```
|
|
223
|
+
|
|
224
|
+
```ts
|
|
225
|
+
// Vercel, AWS Lambda, and similar serverless runtimes: cap pool to 1 per instance
|
|
226
|
+
// connection_limit and pool_timeout are controlled via DATABASE_URL
|
|
227
|
+
const prisma = new PrismaClient();
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
## Anti-Patterns
|
|
231
|
+
|
|
232
|
+
### `updateMany` returns a count, not records
|
|
233
|
+
|
|
234
|
+
```ts
|
|
235
|
+
// BAD: result is { count: 2 } — users[0] is undefined
|
|
236
|
+
const users = await prisma.user.updateMany({ where: { role: 'GUEST' }, data: { role: 'USER' } });
|
|
237
|
+
|
|
238
|
+
// GOOD: capture IDs first, then update, then fetch only the affected rows
|
|
239
|
+
const targets = await prisma.user.findMany({
|
|
240
|
+
where: { role: 'GUEST' },
|
|
241
|
+
select: { id: true },
|
|
242
|
+
});
|
|
243
|
+
const ids = targets.map((u) => u.id);
|
|
244
|
+
await prisma.user.updateMany({ where: { id: { in: ids } }, data: { role: 'USER' } });
|
|
245
|
+
const updated = await prisma.user.findMany({ where: { id: { in: ids } } });
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
Same applies to `deleteMany` — returns `{ count: n }`, never the deleted rows.
|
|
249
|
+
|
|
250
|
+
### `$transaction` interactive form times out after 5 seconds
|
|
251
|
+
|
|
252
|
+
```ts
|
|
253
|
+
// BAD: external call inside transaction exceeds 5s default → "Transaction already closed"
|
|
254
|
+
await prisma.$transaction(async (tx) => {
|
|
255
|
+
const user = await tx.user.findUniqueOrThrow({ where: { id } });
|
|
256
|
+
await sendWelcomeEmail(user.email); // external call
|
|
257
|
+
await tx.user.update({ where: { id }, data: { emailSent: true } });
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
// GOOD: external calls outside the transaction
|
|
261
|
+
const user = await prisma.user.findUniqueOrThrow({ where: { id } });
|
|
262
|
+
await sendWelcomeEmail(user.email);
|
|
263
|
+
await prisma.user.update({ where: { id }, data: { emailSent: true } });
|
|
264
|
+
|
|
265
|
+
// Only raise timeout when bulk processing genuinely needs it
|
|
266
|
+
await prisma.$transaction(async (tx) => { ... }, { timeout: 30_000 });
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
### `migrate dev` can reset the database
|
|
270
|
+
|
|
271
|
+
`migrate dev` detects schema drift and may prompt to reset the DB, dropping all data.
|
|
272
|
+
|
|
273
|
+
```bash
|
|
274
|
+
# NEVER on shared dev, staging, or production
|
|
275
|
+
npx prisma migrate dev --name add_column
|
|
276
|
+
|
|
277
|
+
# Safe everywhere except local solo dev
|
|
278
|
+
npx prisma migrate deploy
|
|
279
|
+
|
|
280
|
+
# Check drift without applying
|
|
281
|
+
npx prisma migrate diff \
|
|
282
|
+
--from-migrations ./prisma/migrations \
|
|
283
|
+
--to-schema-datamodel ./prisma/schema.prisma \
|
|
284
|
+
--shadow-database-url "$SHADOW_DATABASE_URL"
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Manually editing a migration file breaks future deploys
|
|
288
|
+
|
|
289
|
+
Prisma checksums every migration file. Editing after apply causes `P3006 checksum mismatch` on every environment where the original already ran. Create a new migration instead.
|
|
290
|
+
|
|
291
|
+
### Breaking schema changes require multi-step migration
|
|
292
|
+
|
|
293
|
+
Adding `NOT NULL` to an existing column or renaming a column in one migration will lock the table or drop data. Use expand-and-contract:
|
|
294
|
+
|
|
295
|
+
```bash
|
|
296
|
+
# Step 1: create migration locally, then deploy
|
|
297
|
+
npx prisma migrate dev --name add_new_column # local only
|
|
298
|
+
npx prisma migrate deploy # staging / production
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
```ts
|
|
302
|
+
// Step 2: backfill data (run in a script or migration job, not in the shell)
|
|
303
|
+
await prisma.user.updateMany({ data: { newColumn: derivedValue } });
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
```bash
|
|
307
|
+
# Step 3: create the NOT NULL constraint migration locally, then deploy
|
|
308
|
+
npx prisma migrate dev --name make_new_column_required # local only
|
|
309
|
+
npx prisma migrate deploy # staging / production
|
|
310
|
+
```
|
|
311
|
+
|
|
312
|
+
### `@updatedAt` does not fire on `updateMany`
|
|
313
|
+
|
|
314
|
+
`@updatedAt` is set automatically only on `update` and `upsert`. Bulk writes leave it stale.
|
|
315
|
+
|
|
316
|
+
```ts
|
|
317
|
+
// BAD: updatedAt stays at its old value
|
|
318
|
+
await prisma.post.updateMany({ where: { authorId }, data: { published: true } });
|
|
319
|
+
|
|
320
|
+
// GOOD
|
|
321
|
+
await prisma.post.updateMany({
|
|
322
|
+
where: { authorId },
|
|
323
|
+
data: { published: true, updatedAt: new Date() },
|
|
324
|
+
});
|
|
325
|
+
```
|
|
326
|
+
|
|
327
|
+
### Soft delete + `findUniqueOrThrow` leaks deleted records
|
|
328
|
+
|
|
329
|
+
`findUniqueOrThrow` throws `P2025` only when the row does not exist in the DB. Soft-deleted rows still exist and are returned without error.
|
|
330
|
+
|
|
331
|
+
`findUniqueOrThrow` requires a unique constraint field in `where` — adding `deletedAt: null` alongside `id` breaks the type because `{ id, deletedAt }` is not a compound unique constraint. Use `findFirstOrThrow` instead.
|
|
332
|
+
|
|
333
|
+
```ts
|
|
334
|
+
// BAD: returns soft-deleted user
|
|
335
|
+
const user = await prisma.user.findUniqueOrThrow({ where: { id } });
|
|
336
|
+
|
|
337
|
+
// BAD: Prisma type error — { id, deletedAt } is not a unique constraint
|
|
338
|
+
const user = await prisma.user.findUniqueOrThrow({ where: { id, deletedAt: null } });
|
|
339
|
+
|
|
340
|
+
// GOOD: findFirstOrThrow supports arbitrary where conditions
|
|
341
|
+
const user = await prisma.user.findFirstOrThrow({ where: { id, deletedAt: null } });
|
|
342
|
+
```
|
|
343
|
+
|
|
344
|
+
### `deleteMany` without `where` deletes every row
|
|
345
|
+
|
|
346
|
+
```ts
|
|
347
|
+
// BAD: silently wipes the table
|
|
348
|
+
await prisma.post.deleteMany();
|
|
349
|
+
|
|
350
|
+
// GOOD
|
|
351
|
+
await prisma.post.deleteMany({ where: { authorId: userId } });
|
|
352
|
+
```
|
|
353
|
+
|
|
354
|
+
## Best Practices
|
|
355
|
+
|
|
356
|
+
| Rule | Reason |
|
|
357
|
+
|---|---|
|
|
358
|
+
| `migrate deploy` in CI/CD, `migrate dev` only locally | `migrate dev` can reset the DB on drift |
|
|
359
|
+
| Map entities to response DTOs | Prevents leaking internal fields |
|
|
360
|
+
| Catch `PrismaClientKnownRequestError` at service boundary | Translate to domain errors |
|
|
361
|
+
| Prefer `*OrThrow` methods over manual null checks | Throws P2025 automatically; use `findFirstOrThrow` when filtering non-unique fields |
|
|
362
|
+
| `connection_limit=1` + external pooler in serverless | Prevents connection exhaustion |
|
|
363
|
+
| Always provide `where` on `deleteMany` | Prevents accidental table wipe |
|
|
364
|
+
| Set `updatedAt: new Date()` manually in `updateMany` | `@updatedAt` skips bulk writes |
|
|
365
|
+
|
|
366
|
+
## Related Skills
|
|
367
|
+
|
|
368
|
+
- `nestjs-patterns` — NestJS service layer that integrates Prisma
|
|
369
|
+
- `postgres-patterns` — PostgreSQL-level indexing and connection tuning
|
|
370
|
+
- `database-migrations` — multi-step migration planning for production
|
|
371
|
+
- `backend-patterns` — general API and service layer design
|