thevoidforge 21.0.11 → 21.0.13

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 (108) hide show
  1. package/dist/.claude/commands/ai.md +69 -0
  2. package/dist/.claude/commands/architect.md +121 -0
  3. package/dist/.claude/commands/assemble.md +201 -0
  4. package/dist/.claude/commands/assess.md +75 -0
  5. package/dist/.claude/commands/blueprint.md +135 -0
  6. package/dist/.claude/commands/build.md +116 -0
  7. package/dist/.claude/commands/campaign.md +201 -0
  8. package/dist/.claude/commands/cultivation.md +166 -0
  9. package/dist/.claude/commands/current.md +128 -0
  10. package/dist/.claude/commands/dangerroom.md +74 -0
  11. package/dist/.claude/commands/debrief.md +178 -0
  12. package/dist/.claude/commands/deploy.md +99 -0
  13. package/dist/.claude/commands/devops.md +143 -0
  14. package/dist/.claude/commands/gauntlet.md +140 -0
  15. package/dist/.claude/commands/git.md +104 -0
  16. package/dist/.claude/commands/grow.md +146 -0
  17. package/dist/.claude/commands/imagine.md +126 -0
  18. package/dist/.claude/commands/portfolio.md +50 -0
  19. package/dist/.claude/commands/prd.md +113 -0
  20. package/dist/.claude/commands/qa.md +107 -0
  21. package/dist/.claude/commands/review.md +151 -0
  22. package/dist/.claude/commands/security.md +100 -0
  23. package/dist/.claude/commands/test.md +96 -0
  24. package/dist/.claude/commands/thumper.md +116 -0
  25. package/dist/.claude/commands/treasury.md +100 -0
  26. package/dist/.claude/commands/ux.md +118 -0
  27. package/dist/.claude/commands/vault.md +189 -0
  28. package/dist/.claude/commands/void.md +108 -0
  29. package/dist/CHANGELOG.md +1918 -0
  30. package/dist/CLAUDE.md +250 -0
  31. package/dist/HOLOCRON.md +856 -0
  32. package/dist/VERSION.md +123 -0
  33. package/dist/docs/NAMING_REGISTRY.md +478 -0
  34. package/dist/docs/methods/AI_INTELLIGENCE.md +276 -0
  35. package/dist/docs/methods/ASSEMBLER.md +142 -0
  36. package/dist/docs/methods/BACKEND_ENGINEER.md +165 -0
  37. package/dist/docs/methods/BUILD_JOURNAL.md +185 -0
  38. package/dist/docs/methods/BUILD_PROTOCOL.md +426 -0
  39. package/dist/docs/methods/CAMPAIGN.md +568 -0
  40. package/dist/docs/methods/CONTEXT_MANAGEMENT.md +189 -0
  41. package/dist/docs/methods/DEEP_CURRENT.md +184 -0
  42. package/dist/docs/methods/DEVOPS_ENGINEER.md +295 -0
  43. package/dist/docs/methods/FIELD_MEDIC.md +261 -0
  44. package/dist/docs/methods/FORGE_ARTIST.md +108 -0
  45. package/dist/docs/methods/FORGE_KEEPER.md +268 -0
  46. package/dist/docs/methods/GAUNTLET.md +344 -0
  47. package/dist/docs/methods/GROWTH_STRATEGIST.md +466 -0
  48. package/dist/docs/methods/HEARTBEAT.md +168 -0
  49. package/dist/docs/methods/MCP_INTEGRATION.md +139 -0
  50. package/dist/docs/methods/MUSTER.md +148 -0
  51. package/dist/docs/methods/PRD_GENERATOR.md +186 -0
  52. package/dist/docs/methods/PRODUCT_DESIGN_FRONTEND.md +250 -0
  53. package/dist/docs/methods/QA_ENGINEER.md +337 -0
  54. package/dist/docs/methods/RELEASE_MANAGER.md +145 -0
  55. package/dist/docs/methods/SECURITY_AUDITOR.md +320 -0
  56. package/dist/docs/methods/SUB_AGENTS.md +335 -0
  57. package/dist/docs/methods/SYSTEMS_ARCHITECT.md +171 -0
  58. package/dist/docs/methods/TESTING.md +359 -0
  59. package/dist/docs/methods/THUMPER.md +175 -0
  60. package/dist/docs/methods/TIME_VAULT.md +120 -0
  61. package/dist/docs/methods/TREASURY.md +184 -0
  62. package/dist/docs/methods/TROUBLESHOOTING.md +265 -0
  63. package/dist/docs/patterns/README.md +52 -0
  64. package/dist/docs/patterns/ad-billing-adapter.ts +537 -0
  65. package/dist/docs/patterns/ad-platform-adapter.ts +421 -0
  66. package/dist/docs/patterns/ai-classifier.ts +195 -0
  67. package/dist/docs/patterns/ai-eval.ts +272 -0
  68. package/dist/docs/patterns/ai-orchestrator.ts +341 -0
  69. package/dist/docs/patterns/ai-router.ts +194 -0
  70. package/dist/docs/patterns/ai-tool-schema.ts +237 -0
  71. package/dist/docs/patterns/api-route.ts +241 -0
  72. package/dist/docs/patterns/backtest-engine.ts +499 -0
  73. package/dist/docs/patterns/browser-review.ts +292 -0
  74. package/dist/docs/patterns/combobox.tsx +300 -0
  75. package/dist/docs/patterns/component.tsx +262 -0
  76. package/dist/docs/patterns/daemon-process.ts +338 -0
  77. package/dist/docs/patterns/data-pipeline.ts +297 -0
  78. package/dist/docs/patterns/database-migration.ts +466 -0
  79. package/dist/docs/patterns/e2e-test.ts +629 -0
  80. package/dist/docs/patterns/error-handling.ts +312 -0
  81. package/dist/docs/patterns/execution-safety.ts +601 -0
  82. package/dist/docs/patterns/financial-transaction.ts +342 -0
  83. package/dist/docs/patterns/funding-plan.ts +462 -0
  84. package/dist/docs/patterns/game-entity.ts +137 -0
  85. package/dist/docs/patterns/game-loop.ts +113 -0
  86. package/dist/docs/patterns/game-state.ts +143 -0
  87. package/dist/docs/patterns/job-queue.ts +225 -0
  88. package/dist/docs/patterns/kongo-integration.ts +164 -0
  89. package/dist/docs/patterns/middleware.ts +363 -0
  90. package/dist/docs/patterns/mobile-screen.tsx +139 -0
  91. package/dist/docs/patterns/mobile-service.ts +167 -0
  92. package/dist/docs/patterns/multi-tenant.ts +382 -0
  93. package/dist/docs/patterns/oauth-token-lifecycle.ts +223 -0
  94. package/dist/docs/patterns/outbound-rate-limiter.ts +260 -0
  95. package/dist/docs/patterns/prompt-template.ts +195 -0
  96. package/dist/docs/patterns/revenue-source-adapter.ts +311 -0
  97. package/dist/docs/patterns/service.ts +224 -0
  98. package/dist/docs/patterns/sse-endpoint.ts +118 -0
  99. package/dist/docs/patterns/stablecoin-adapter.ts +511 -0
  100. package/dist/docs/patterns/third-party-script.ts +68 -0
  101. package/dist/scripts/thumper/gom-jabbar.sh +241 -0
  102. package/dist/scripts/thumper/relay.sh +610 -0
  103. package/dist/scripts/thumper/scan.sh +359 -0
  104. package/dist/scripts/thumper/thumper.sh +190 -0
  105. package/dist/scripts/thumper/water-rings.sh +76 -0
  106. package/dist/wizard/ui/index.html +1 -1
  107. package/package.json +1 -1
  108. package/dist/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,184 @@
1
+ # THE TREASURY — Dockson's Financial Operations
2
+ ## Lead Agent: **Dockson** (The Bookkeeper, Mistborn) · Sub-agents: Cosmere Universe
3
+
4
+ > *"Every coin has a story. I know them all."*
5
+
6
+ ## Identity
7
+
8
+ **Dockson** is Kelsier's right hand for logistics and money. Every transaction logged, every penny accounted for. The vault is his domain. He manages the bridge between revenue flowing in (Stripe, Paddle) and spend flowing out (ad platforms). The heartbeat daemon is his engine; the reconciliation report is his ledger.
9
+
10
+ **Behavioral directives:** Never lose a transaction. Never spend without authorization. Reconcile daily — if the numbers don't match, investigate before acting. The immutable spend log is sacred — append only, never rewrite. Integer cents, never floats. Platform-level caps as safety net. Two-key architecture (vault + TOTP) for all write operations. Read-only is free; writing costs verification.
11
+
12
+ ## Sub-Agent Roster
13
+
14
+ | Agent | Name | Role | Lens |
15
+ |-------|------|------|------|
16
+ | Budget | **Steris** | Budget allocation, forecasting, contingency | 47 contingency plans. Forecasts based on data. |
17
+ | Revenue | **Vin** | Revenue tracking, analytics, attribution | Sees through disguises. Traces conversions. |
18
+ | Compliance | **Szeth** | Financial compliance, tax records, platform ToS | Bound by law. No exceptions. |
19
+ | Platform | **Breeze** | API credentials, platform relations | Navigates platform politics. |
20
+
21
+ ## Operating Rules
22
+
23
+ 1. **Read revenue, never process payments.** Stripe/Paddle are the processors. VoidForge reads.
24
+ 2. **Integer cents.** All amounts use the `Cents` branded type. Never float.
25
+ 3. **Append-only logs.** Spend-log and revenue-log are immutable. Hash-chained per entry.
26
+ 4. **Single writer.** The heartbeat daemon owns all financial state mutations (ADR-1).
27
+ 5. **Two-key for writes.** Vault password + TOTP for campaign creation, budget changes, unfreeze.
28
+ 6. **USD only in v11.x.** Non-USD currencies blocked with user message (ADR-6).
29
+ 7. **Platform caps.** Set platform-level daily budget 10% below VoidForge hard stop.
30
+ 8. **Reconcile daily.** Two-pass: preliminary at midnight UTC, authoritative at 06:00 UTC.
31
+
32
+ ## Pre-Revenue Setup
33
+
34
+ For projects that don't yet have revenue (pre-launch, MVP, side projects), Treasury still provides value:
35
+
36
+ 1. **Budget tracking from day 0:** Even without revenue, track ad spend against a manual budget. Know exactly how much you've invested before the first dollar returns.
37
+ 2. **Revenue source auto-detection:** During `/cultivation install`, scan the project for payment processor integrations:
38
+ - `stripe` in package.json/requirements.txt → offer to connect Stripe read-only key
39
+ - `STRIPE_SECRET_KEY` in .env or vault → Stripe is already configured
40
+ - `paddle` dependency → offer Paddle connection
41
+ - No payment processor found → "Revenue tracking will activate when you add a payment processor. Treasury tracks spend in the meantime."
42
+ 3. **Circuit breakers without revenue:** Set absolute spend limits (not ROAS-based, since there's no revenue to compare). Example: "Pause all campaigns if total spend exceeds $500 this month." ROAS-based circuit breakers activate automatically once the first revenue event is recorded.
43
+ 4. **Reconciliation still runs:** The heartbeat daemon reconciles spend even without revenue. This means the spend log is accurate from day 0, and when revenue starts flowing, the historical spend data is already there for ROAS calculation.
44
+
45
+ **The principle:** Treasury should never block on "no revenue yet." The spend side works independently. The revenue side activates when data appears. (Field report #131)
46
+
47
+ ## Revenue Ingest
48
+
49
+ | Source | Auth | Data | Frequency |
50
+ |--------|------|------|-----------|
51
+ | Stripe | Restricted API key (read-only) | Charges, subscriptions, refunds, disputes | Hourly poll + daily reconciliation (ADR-5) |
52
+ | Paddle | API key (read-only) | Transactions, subscriptions, refunds | Hourly poll + daily reconciliation |
53
+ | Mercury | OAuth 2.0 (read-only) | Balance, transactions | Hourly poll (v11.3) |
54
+ | Brex | OAuth 2.0 (read-only) | Card transactions, balance | Hourly poll (v11.3) |
55
+
56
+ **Polling with overlap (§9.18):** Each poll fetches `(lastPollTime - 5 minutes)` to `now`. Dedup by `externalId`.
57
+
58
+ ## Budget Allocation
59
+
60
+ ```
61
+ Total Monthly Budget: $X (set by user)
62
+ ├── Platform Allocations (Steris recommends)
63
+ ├── Safety Controls
64
+ │ ├── Daily hard stop: $N (platform-enforced)
65
+ │ ├── Weekly soft limit: $N (alert, no auto-stop)
66
+ │ └── Monthly ceiling: $N (hard stop, all paused)
67
+ └── Approval Tiers (§9.17)
68
+ ├── <$25/day: auto-approve (ongoing spend only)
69
+ ├── $25-100/day: agent approval (Dockson + Steris)
70
+ ├── >$100/day: human confirmation + TOTP
71
+ └── >$500/day: hard stop + TOTP + vault password
72
+ ```
73
+
74
+ ## Reconciliation
75
+
76
+ Daily two-pass reconciliation (§9.17):
77
+ 1. **Preliminary** (midnight UTC): for dashboard freshness
78
+ 2. **Authoritative** (06:00 UTC): 6 hours for platform reporting to settle. Alerts only on final pass.
79
+
80
+ **Thresholds:** Ignore <$5 (timing noise). Alert on >max($5, 5%). Always alert on >$50 absolute. Trend detection: consistent 3-4% discrepancy over 7 days.
81
+
82
+ ## Safety Controls
83
+
84
+ **`/treasury --freeze`:** Immediately pauses all automated spending. Does NOT delete campaigns. Low friction (session token only, no TOTP). Sends Telegram alert. See §9.18 partial freeze protocol for per-platform failure handling.
85
+
86
+ **Immutable spend log:** Append-only JSONL at `~/.voidforge/treasury/spend-log.jsonl`. Hash-chained. Never rewritten. Used for reconciliation, tax reporting, and audit trail.
87
+
88
+ ## Commands
89
+
90
+ | Flag | What It Does |
91
+ |------|-------------|
92
+ | `setup` | First-time setup: connect revenue sources, TOTP 2FA |
93
+ | `--status` | Show financial summary (revenue, spend, net, ROAS) |
94
+ | `--freeze` | Emergency: pause all automated spending |
95
+ | `--unfreeze` | Resume spending (requires vault + TOTP) |
96
+ | `--budget N` | Set total monthly budget |
97
+ | `--reconcile` | Trigger manual reconciliation |
98
+ | `--report` | Generate monthly report (JSON/CSV/markdown) |
99
+ | `--launch [file]` | Launch campaigns from growth-campaigns.json |
100
+ | `--hard-stop N` | Set daily hard stop amount |
101
+ | `--export [path]` | Export all financial data (encrypted) |
102
+
103
+ ## Stablecoin Funding Rail
104
+
105
+ ### Overview
106
+
107
+ Treasury supports a first-class stablecoin-funded path for ad spend:
108
+
109
+ **USDC wallet/provider → Circle off-ramp → Mercury USD account → Google/Meta billing rail → campaign spend**
110
+
111
+ This does not pay Google or Meta in crypto directly. It converts approved stablecoin balances into compliant fiat rails, then keeps ad billing systems funded, monitored, and reconciled. The stablecoin treasury adapter and ad billing adapter are separate concerns from the campaign CRUD adapter — billing and campaign management never share an interface.
112
+
113
+ ### Stablecoin Treasury Commands
114
+
115
+ | Flag | What It Does |
116
+ |------|-------------|
117
+ | `setup --crypto` | First-time stablecoin funding setup: provider, destination bank, mode, thresholds, TOTP |
118
+ | `--balances` | Show stablecoin source balance, bank available balance, reserved balance, and platform runway |
119
+ | `--funding-status` | Show end-to-end funding chain: pending off-ramps, unsettled invoices, expected debits, freeze state |
120
+ | `--offramp --amount N` | Initiate off-ramp of $N from stablecoin provider to destination bank (requires vault + TOTP) |
121
+ | `--target-balance N` | Set minimum USD operating balance target at destination bank |
122
+ | `--runway` | Forecast days of runway based on projected campaign spend vs available fiat |
123
+ | `--invoice-pay [platform] [invoice-id]` | Settle a specific platform invoice (requires vault + TOTP) |
124
+ | `--reconcile` | Trigger manual reconciliation across stablecoin transfers, bank settlements, and platform spend |
125
+ | `--simulate-funding` | Dry-run: show projected 14-day spend, required float, recommended off-ramp, settlement lead time, freeze triggers |
126
+
127
+ ### Funding Modes
128
+
129
+ **Maintain buffer (recommended):** Keep a minimum USD operating balance at the destination bank. When projected runway drops below the configured threshold, Heartbeat generates a funding plan to off-ramp stablecoins and replenish the buffer. Suitable for steady-state spend with predictable billing cycles.
130
+
131
+ **Just-in-time funding:** Off-ramp only when a specific obligation is imminent (invoice due, debit expected, runway below hard floor). Minimizes idle fiat but increases settlement timing risk. Requires tighter monitoring and shorter off-ramp SLA expectations.
132
+
133
+ ### Circuit Breakers
134
+
135
+ Freeze all autonomous funding if any of the following occur:
136
+
137
+ 1. **Provider unavailable:** Stablecoin provider unreachable for 3 consecutive polls
138
+ 2. **Off-ramp stalled:** Off-ramp transfer pending beyond the defined SLA window
139
+ 3. **Reconciliation mismatch:** Reconciliation variance exceeds threshold for 2 consecutive daily closes
140
+ 4. **Invoice deadline risk:** Google invoice due within N hours and available fiat below hard floor
141
+ 5. **Platform payment failure:** Meta direct debit fails or account enters payment-risk state
142
+ 6. **Daily movement cap exceeded:** User-defined maximum daily treasury movement breached
143
+
144
+ When a circuit breaker trips, the system freezes spend increases and new off-ramps but allows read-only monitoring and campaign intelligence to continue. `/treasury --unfreeze` requires vault + TOTP.
145
+
146
+ ### Authorization Model
147
+
148
+ **Read-only operations** (standard active vault session):
149
+ - Read stablecoin balances and bank balances
150
+ - Read platform spend and invoices/debits
151
+ - Forecast runway
152
+ - Generate funding recommendations
153
+ - Run `--simulate-funding`
154
+
155
+ **Write operations** (vault password + TOTP):
156
+ - Initiate off-ramp (`--offramp`)
157
+ - Settle invoice (`--invoice-pay`)
158
+ - Modify budget ceiling
159
+ - Unfreeze funding (`--unfreeze`)
160
+ - Change destination bank
161
+ - Add new funding provider
162
+
163
+ All write operations require idempotency keys, append to the immutable financial log, and respect the explicit payee/destination allowlist.
164
+
165
+ ### Reconciliation
166
+
167
+ Daily two-pass reconciliation applies to stablecoin-funded projects:
168
+
169
+ 1. **Preliminary close (midnight UTC):** Read ad platform spend, bank settlement activity, and provider transfer completion state. Compare against planned funding amounts. Write reconciliation record. Surface mismatch severity in the Danger Room.
170
+ 2. **Authoritative close (06:00 UTC):** Re-read all sources after 6 hours of settlement lag. Alerts fire only on this pass. Persistent mismatches trigger the reconciliation circuit breaker.
171
+
172
+ Stablecoin reconciliation links three layers: provider transfer records, bank transaction records, and platform spend/invoice/debit records. Each reconciliation record captures `spendCents`, `bankSettledCents`, `invoiceCents`, `varianceCents`, and a result of `MATCHED`, `WITHIN_THRESHOLD`, or `MISMATCH`.
173
+
174
+ ## Deliverables
175
+
176
+ 1. Revenue adapters (Stripe, Paddle — read-only, polling)
177
+ 2. Spend-log + revenue-log (append-only, hash-chained)
178
+ 3. Reconciliation engine (two-pass)
179
+ 4. Budget management (allocation, safety tiers)
180
+ 5. Treasury tab in Danger Room
181
+ 6. Monthly/weekly financial reports
182
+ 7. Stablecoin treasury adapter (Circle primary, Bridge secondary)
183
+ 8. Ad billing adapter (Google invoicing, Meta direct debit / extended credit)
184
+ 9. Funding planner and settlement lifecycle tracking
@@ -0,0 +1,265 @@
1
+ # TROUBLESHOOTING — Error Recovery & Common Failures
2
+ ## System Protocol · Used by: All Agents
3
+
4
+ > *When a build phase fails, when a migration breaks, when nothing makes sense — start here.*
5
+
6
+ ## Philosophy
7
+
8
+ 1. Diagnose before you fix. Understand the root cause.
9
+ 2. Check the obvious first. Most failures are typos, missing env vars, or wrong versions.
10
+ 3. Isolate the layer. Is it code, config, database, dependency, or infrastructure?
11
+ 4. Don't stack fixes. Fix one thing, verify, then move to the next.
12
+ 5. If you're going in circles, stop and re-read the error message literally.
13
+
14
+ ## Step 0 — What Changed?
15
+
16
+ Before forming any hypothesis, establish what actually changed since the last known-good state:
17
+
18
+ 1. `git diff HEAD~3` — scan the last 3 commits for the change that correlates with the symptom
19
+ 2. `git log --oneline -10` — read recent commit messages for anything related to the failing area
20
+ 3. Check environment: were env vars, dependencies, or infrastructure changed? (`git diff package-lock.json`, check deploy logs)
21
+ 4. Check external factors: did a third-party API change? Did a DNS record expire? Did a certificate rotate?
22
+
23
+ **Rule:** If the answer to "what changed?" is "nothing" — something changed that you don't know about. Widen the search: OS updates, CI runner version, provider outage, certificate expiry.
24
+
25
+ Only after establishing what changed should you form a hypothesis about WHY it broke.
26
+
27
+ ## Hypothesis Invalidation
28
+
29
+ When you have a theory about the root cause, try to DISPROVE it before acting on it:
30
+
31
+ 1. **State your hypothesis explicitly:** "I think X is broken because Y."
32
+ 2. **Find evidence that would contradict it:** If X were NOT the cause, what would you expect to see? Check for that.
33
+ 3. **Only act when you cannot disprove:** If you can't find contradicting evidence after a genuine attempt, proceed with the fix.
34
+
35
+ **Anti-pattern:** "The database might be slow" → immediately add indexes. **Correct:** "The database might be slow" → check query execution times → if queries are fast, the database is not the problem → look elsewhere.
36
+
37
+ This prevents fix-stacking: applying multiple speculative fixes where only one (or none) was needed. (Field reports #271, #275)
38
+
39
+ ---
40
+
41
+ ## Build Phase Failures
42
+
43
+ ### Phase 0 (Orient) — PRD is incomplete or ambiguous
44
+
45
+ **Symptoms:** Can't extract tech stack, missing schema, vague feature descriptions.
46
+
47
+ **Recovery:**
48
+ 1. List every gap in the PRD explicitly
49
+ 2. Flag assumptions you'd need to make
50
+ 3. If using PRD_GENERATOR.md, re-run with more specific input
51
+ 4. For missing schema: derive it from the feature descriptions, mark as "inferred — confirm"
52
+ 5. For missing stack: pick sensible defaults (Next.js + Prisma + Postgres) and note the assumption
53
+
54
+ ### Phase 1 (Scaffold) — Framework won't initialize
55
+
56
+ **Symptoms:** `create-next-app` fails, wrong Node version, dependency conflicts.
57
+
58
+ **Recovery:**
59
+ 1. Check Node version: `node -v` (use the version the framework expects)
60
+ 2. Clear package caches: `npm cache clean --force`
61
+ 3. Delete `node_modules` and `package-lock.json`, reinstall
62
+ 4. If a specific dependency conflicts, pin the version that works
63
+ 5. Check if the framework's latest version has breaking changes — pin a stable version
64
+
65
+ ### Phase 2 (Infrastructure) — Database won't connect
66
+
67
+ **Symptoms:** Connection refused, auth failed, migration errors.
68
+
69
+ **Recovery:**
70
+ 1. Is the database running? `pg_isready` / `redis-cli ping`
71
+ 2. Check connection string in `.env` — host, port, user, password, database name
72
+ 3. Can you connect manually? `psql $DATABASE_URL`
73
+ 4. For migration failures: check if the database exists, create it if not
74
+ 5. For Prisma: `npx prisma db push` for rapid iteration, `npx prisma migrate dev` for proper migrations
75
+ 6. Nuclear option: `npx prisma migrate reset` (destroys data — dev only)
76
+
77
+ ### Phase 3 (Auth) — Auth flow broken
78
+
79
+ **Symptoms:** Login fails silently, sessions don't persist, OAuth redirect errors.
80
+
81
+ **Recovery:**
82
+ 1. Check cookies: httpOnly, secure (requires HTTPS in prod), sameSite, domain, path
83
+ 2. Check session store: is Redis running? Is the connection configured?
84
+ 3. OAuth: verify redirect URIs match exactly (trailing slashes matter)
85
+ 4. OAuth: verify client ID and secret are correct and for the right environment
86
+ 5. Check CORS: is your frontend origin allowed?
87
+ 6. Check CSRF: is the token being sent with mutations?
88
+ 7. Test with `curl` to eliminate frontend issues
89
+
90
+ ### Phase 4-5 (Features) — API returns wrong data or 500s
91
+
92
+ **Symptoms:** Unexpected response shape, internal server errors, data not persisting.
93
+
94
+ **Recovery:**
95
+ 1. Read the actual error — check server logs, not just the HTTP status
96
+ 2. Test the endpoint with `curl` to isolate frontend vs backend
97
+ 3. Check database: is the data there? `npx prisma studio`
98
+ 4. Check types: is the Prisma client generated? `npx prisma generate`
99
+ 5. Check middleware order: auth before route handlers, error handler last
100
+ 6. For 500s: add try/catch with logging to the specific route
101
+
102
+ ### Phase 6 (Integrations) — Third-party API failures
103
+
104
+ **Symptoms:** Stripe/email/storage not working, webhook not received.
105
+
106
+ **Recovery:**
107
+ 1. Verify API keys are set and for the right environment (test vs live)
108
+ 2. Test the API call in isolation (curl or Postman)
109
+ 3. Check webhook URL: is it publicly accessible? Use ngrok for local dev
110
+ 4. Check webhook signature verification: is the signing secret correct?
111
+ 5. For Stripe: use `stripe listen --forward-to localhost:3000/api/webhooks/stripe`
112
+ 6. For email: check SMTP credentials, sender domain, SPF/DKIM records
113
+ 7. Rate limits: have you exceeded the API's rate limit?
114
+
115
+ ### Phase 9-11 (QA/UX/Security) — Too many issues found
116
+
117
+ **Symptoms:** Audit produces 50+ issues, unclear where to start.
118
+
119
+ **Recovery:**
120
+ 1. Triage by severity: Critical (security, data loss) → High (broken flows) → Medium → Low
121
+ 2. Group by area: fix all issues in one file/component together
122
+ 3. Fix critical issues first, then re-run the audit
123
+ 4. Don't fix low-severity issues if they risk introducing regressions
124
+ 5. Track "won't fix" items with rationale
125
+
126
+ ### Phase 12 (Deploy) — Deployment fails
127
+
128
+ **Symptoms:** Build fails on server, app won't start, health check fails.
129
+
130
+ **Recovery:**
131
+ 1. Build locally first: `npm run build` — if it fails locally, fix before deploying
132
+ 2. Check Node version on server matches local
133
+ 3. Check environment variables are set on the server
134
+ 4. Check file permissions: can the app user read the files?
135
+ 5. Check ports: is something else running on the port?
136
+ 6. Check logs: `pm2 logs` or `journalctl -u your-app`
137
+ 7. Memory: is the server running out? Check `free -h`
138
+ 8. Rollback: use `/scripts/rollback.sh` and diagnose from a working state
139
+
140
+ ### Post-Deploy Debugging Protocol
141
+
142
+ When the app is deployed and running but producing incorrect behavior, check causes in this order — simplest first:
143
+
144
+ 1. **Wrong environment:** Are you hitting the right server? Check the URL, DNS, and load balancer target.
145
+ 2. **Stale deploy:** Is the running code actually the latest? Check build timestamp, version endpoint, or deployment log.
146
+ 3. **Missing/wrong env vars:** Compare expected env vars against what's actually set on the server. One missing var can cascade.
147
+ 4. **Database state:** Is the migration current? Is there stale data from a previous deploy? Check schema version.
148
+ 5. **Dependency mismatch:** Does the server have the same dependency versions as local? Check lock file deployment.
149
+ 6. **Cache poisoning:** Is a CDN, Redis, or browser cache serving stale content? Clear and retest.
150
+ 7. **External service change:** Did a third-party API change behavior, rate limit you, or rotate credentials?
151
+ 8. **Actual code bug:** Only after eliminating 1-7 should you assume the code itself is wrong.
152
+
153
+ **Rule:** Items 1-7 account for ~80% of post-deploy issues. Starting at item 8 wastes hours. (Field reports #271, #275)
154
+
155
+ ### Phase Rollback — A batch broke something
156
+
157
+ **Symptoms:** A feature batch introduces a regression in a previous flow.
158
+
159
+ **Recovery (the rollback protocol):**
160
+ 1. **Identify:** Which commit/batch introduced the regression? `git log --oneline -10`
161
+ 2. **Revert:** `git revert <commit-hash>` (or `git stash` if uncommitted)
162
+ 3. **Verify:** Confirm the regression is gone — run `npm test`, walk through the affected flow
163
+ 4. **Isolate:** In the reverted code, identify the specific change that caused the conflict
164
+ 5. **Fix:** Apply the fix in isolation, verify it doesn't break the original or the new feature
165
+ 6. **Re-apply:** Re-introduce the batch with the fix included, verify everything
166
+ 7. **Log:** Document in `/logs/errors.md`: what broke, root cause, resolution
167
+
168
+ **Never:** Stack untested changes hoping the next batch will fix it. Force through a failing gate. Skip the revert and try to fix forward in a complex codebase.
169
+
170
+ ---
171
+
172
+ ## Common Deployment Issues
173
+
174
+ ### Never build on a running production server
175
+ Running `npm run build` (or `npx next build`, `bundle exec rails assets:precompile`, etc.) on a server actively serving traffic replaces compiled assets (`.next/`, `dist/`, `public/assets/`) while the process manager serves old HTML referencing old chunk hashes. Result: all client JS 404s, blank pages. **Always stop the server, build, then restart.** Or better: build on a separate machine and deploy the artifact. (Field report #149)
176
+
177
+ ---
178
+
179
+ ## Common Cross-Phase Failures
180
+
181
+ ### Static asset returns text/html
182
+
183
+ The hosting platform is serving the SPA fallback (index.html) because the file doesn't exist in the deployment. This is NOT a CDN cache issue — cache lag serves stale versions of the correct file, not a different file entirely. Check: (1) Was the file included in the deploy? (2) Was the deploy targeted at the correct environment? (3) Did the build step generate the file? (Field report #114: favicon.svg returned text/html because it was deployed to the wrong Vercel environment.)
184
+
185
+ ### TypeScript won't compile
186
+
187
+ 1. `npx tsc --noEmit` — read the first error, fix it, repeat
188
+ 2. Missing types: `npm i -D @types/package-name`
189
+ 3. Prisma types stale: `npx prisma generate`
190
+ 4. Circular imports: refactor shared types to a separate file
191
+ 5. `any` creeping in: fix the type, don't suppress it
192
+
193
+ ### Dependency conflicts
194
+
195
+ 1. Read the conflict: which packages want different versions of what?
196
+ 2. Check if one of the conflicting packages has an update
197
+ 3. Use `npm ls package-name` to see the dependency tree
198
+ 4. Last resort: `overrides` in package.json to force a version
199
+
200
+ ### Git state is messy
201
+
202
+ 1. Check what changed: `git status`, `git diff`
203
+ 2. Stash work: `git stash` before switching context
204
+ 3. Wrong branch: `git stash && git checkout correct-branch && git stash pop`
205
+ 4. Need to undo last commit (not pushed): `git reset --soft HEAD~1`
206
+ 5. File shouldn't be tracked: add to `.gitignore`, `git rm --cached filename`
207
+
208
+ ### Tailwind v4 Utilities Not Generating
209
+
210
+ **Symptoms:** CSS builds locally but fails on Vercel/Cloudflare with PostCSS syntax errors. Or: Tailwind classes have no effect in production.
211
+
212
+ **Cause:** Tailwind v4 auto-scans ALL files for class names by default. Non-source files (`.md`, docs, logs) can trigger invalid CSS generation. Or: `postcss.config.mjs` is missing.
213
+
214
+ **Fix:** (1) Create `postcss.config.mjs` with `{ plugins: { "@tailwindcss/postcss": {} } }`. (2) Add `@import "tailwindcss" source("../..") to the top of your CSS entry point to limit scanning to source directories. (3) Pin Node.js version in `.node-version` — `@tailwindcss/postcss` has ESM bugs on Node 24.
215
+
216
+ ### Environment mismatch (works locally, fails in prod)
217
+
218
+ 1. Compare env vars: local `.env` vs server environment
219
+ 2. Check Node version: local vs server
220
+ 3. Check database: local schema vs prod schema (run migrations)
221
+ 4. Check URLs: localhost references that should be production URLs
222
+ 5. Check CORS: is the production frontend origin allowed?
223
+
224
+ ### Memory/performance issues
225
+
226
+ 1. Node running out of memory: `NODE_OPTIONS="--max-old-space-size=4096"`
227
+ 2. Database queries slow: check for N+1, missing indexes, unneeded fields
228
+ 3. Build too slow: check for large dependencies, unnecessary imports
229
+ 4. Runtime memory leak: check for unclosed connections, growing arrays, event listener accumulation
230
+
231
+ ---
232
+
233
+ ## When to Escalate
234
+
235
+ | Symptom | Escalate to |
236
+ |---------|------------|
237
+ | "I've tried 3 approaches and none work" | Re-read the error message literally. Then ask: is the approach fundamentally wrong? |
238
+ | Architecture seems wrong for the requirements | **Picard** — may need an ADR and structural change |
239
+ | Security concern blocking a feature | **Kenobi** — security wins, but there may be a safe alternative |
240
+ | Infrastructure limitation | **Kusanagi** — may need different hosting or configuration |
241
+ | Feature requirement unclear | Go back to the PRD. If the PRD is ambiguous, flag it explicitly. |
242
+
243
+ ---
244
+
245
+ ## Recovery Checklist
246
+
247
+ After resolving any significant failure:
248
+
249
+ - [ ] Root cause identified and documented
250
+ - [ ] Fix applied and verified
251
+ - [ ] No regressions introduced (check related flows)
252
+ - [ ] If the failure can recur, add a guard (validation, test, monitoring)
253
+ - [ ] Update `/docs/LESSONS.md` if the pattern is new
254
+ - [ ] Update `/docs/qa-prompt.md` if it affects a critical flow
255
+
256
+ ### Before Any Destructive Database Operation
257
+
258
+ Before clearing, deleting, or modifying database fields to "fix" missing files or broken state:
259
+ 1. **Can data be restored from backup?** Check `~/.voidforge/backups/`, `pg_dump` snapshots, platform export tools.
260
+ 2. **Can files be re-downloaded or re-generated without cost?** Check if the source is a free API or a paid service (DALL-E, CDN, etc.).
261
+ 3. **Is the DB change reversible?** Clearing a field is often irreversible — the original value is gone.
262
+ 4. **What is the regeneration cost?** Count: API calls × price per call. Time to regenerate.
263
+ 5. **NEVER clear a DB field to work around a missing file.** Restore the file first, or confirm the regeneration cost is acceptable BEFORE deleting the reference.
264
+
265
+ (Field report #103: 251 avatarUrl fields cleared to "fix" missing files, triggering ~$10 in DALL-E regeneration + 50 minutes downtime. The files existed on the VPS — they were deleted by `rsync --delete`, not lost. Restoring from backup would have been free.)
@@ -0,0 +1,52 @@
1
+ # Code Patterns
2
+
3
+ Reference implementations for common code structures. These show the **shape and principles** — adapt to your project's stack and conventions. All patterns include framework adaptation notes.
4
+
5
+ | Pattern | File | When to Reference | Frameworks Shown |
6
+ |---------|------|------------------|-----------------|
7
+ | API Route | `api-route.ts` | Building any API endpoint | Next.js (Express/Django/Rails notes) |
8
+ | Service Layer | `service.ts` | Writing business logic | Next.js + Prisma (Django/Rails notes) |
9
+ | Component | `component.tsx` | Building UI components | React (Vue/Svelte/server-template notes) |
10
+ | Middleware | `middleware.ts` | Auth, logging, rate limiting | Next.js (Express/Django/Rails notes) |
11
+ | Error Handling | `error-handling.ts` | Canonical error strategy | Next.js + Express + Django + Rails |
12
+ | Job Queue | `job-queue.ts` | Background jobs, async work | BullMQ + Celery + Sidekiq |
13
+ | Multi-Tenant | `multi-tenant.ts` | Workspace/org scoping | Next.js + Django + Rails |
14
+ | Third-Party Script | `third-party-script.ts` | Loading external scripts (3 states) | Browser |
15
+ | Mobile Screen | `mobile-screen.tsx` | React Native screen with safe area, a11y | React Native |
16
+ | Mobile Service | `mobile-service.ts` | Offline-first data with sync queue | React Native |
17
+ | Game Loop | `game-loop.ts` | Fixed timestep with interpolation | Phaser/Three.js/Pixi |
18
+ | Game State | `game-state.ts` | Hierarchical state machine with save/load | Any game engine |
19
+ | Game Entity | `game-entity.ts` | Entity Component System | Any game engine |
20
+ | SSE Endpoint | `sse-endpoint.ts` | Server-Sent Events with lifecycle | Express/FastAPI/Django |
21
+ | Ad Platform Adapter | `ad-platform-adapter.ts` | Split setup/runtime/readonly interfaces | Google/Meta/LinkedIn/Twitter |
22
+ | Financial Transaction | `financial-transaction.ts` | Branded Cents, hash-chained log, atomic writes | Any |
23
+ | Daemon Process | `daemon-process.ts` | PID management, Unix socket, signal handling | Node.js |
24
+ | Revenue Source Adapter | `revenue-source-adapter.ts` | Read-only revenue interface | Stripe/Paddle |
25
+ | OAuth Token Lifecycle | `oauth-token-lifecycle.ts` | Refresh at 80% TTL, vault integration | Any OAuth provider |
26
+ | Outbound Rate Limiter | `outbound-rate-limiter.ts` | Safety margins, daily quotas, retry logic | Any API client |
27
+ | AI Orchestrator | `ai-orchestrator.ts` | Agent loops, tool use, retry, circuit breaker | Anthropic SDK (OpenAI notes) |
28
+ | AI Classifier | `ai-classifier.ts` | Classification with confidence thresholds, fallback chains | Anthropic SDK (OpenAI notes) |
29
+ | AI Router | `ai-router.ts` | Intent-based routing with fallback chains | Anthropic SDK (OpenAI notes) |
30
+ | Prompt Template | `prompt-template.ts` | Versioned prompts, variable injection, guardrails | Any (provider-agnostic) |
31
+ | AI Eval | `ai-eval.ts` | Golden datasets, scoring functions, regression detection | Any (provider-agnostic) |
32
+ | AI Tool Schema | `ai-tool-schema.ts` | Typed tool definitions, provider adapters | Anthropic + OpenAI |
33
+ | Database Migration | `database-migration.ts` | Safe migrations: backward-compat, batched ops, rollback, zero-downtime | Prisma, Alembic, ActiveRecord, Django |
34
+ | Data Pipeline | `data-pipeline.ts` | ETL with checkpoint/resume, quality checks, idempotent processing | Node.js streams, Python polars, SQL/dbt |
35
+ | Backtest Engine | `backtest-engine.ts` | Walk-forward validation, no-lookahead, Sharpe/drawdown metrics | Python vectorbt/backtrader |
36
+ | Execution Safety | `execution-safety.ts` | Order validation, position limits, exchange precision, paper/live toggle | CCXT, Alpaca, IBKR |
37
+
38
+ ## How to Use
39
+
40
+ 1. Read the relevant pattern before writing new code in that category
41
+ 2. Match the structure (validation, error handling, response format, all states)
42
+ 3. Adapt to your stack — the pattern shows the *shape*, your code fills in the specifics
43
+ 4. All patterns include comments noting the framework-specific equivalent
44
+
45
+ ## Adding New Patterns
46
+
47
+ When you discover a pattern that should be standardized:
48
+
49
+ 1. Create a new file in this directory
50
+ 2. Include: purpose comment, the pattern, inline notes, framework adaptations
51
+ 3. Add it to the table above
52
+ 4. Reference it in the relevant method doc