@sylphx/flow 0.2.1 → 0.2.3
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/assets/agents/coder.md +1 -1
- package/assets/agents/orchestrator.md +1 -1
- package/assets/agents/reviewer.md +1 -1
- package/assets/agents/writer.md +13 -13
- package/assets/slash-commands/context.md +112 -0
- package/dist/assets/agents/coder.md +32 -0
- package/dist/assets/agents/orchestrator.md +36 -0
- package/dist/assets/agents/reviewer.md +30 -0
- package/dist/assets/agents/writer.md +30 -0
- package/dist/assets/knowledge/data/sql.md +216 -0
- package/dist/assets/knowledge/guides/saas-template.md +85 -0
- package/dist/assets/knowledge/guides/system-prompt.md +344 -0
- package/dist/assets/knowledge/guides/tech-stack.md +92 -0
- package/dist/assets/knowledge/guides/ui-ux.md +44 -0
- package/dist/assets/knowledge/stacks/nextjs-app.md +165 -0
- package/dist/assets/knowledge/stacks/node-api.md +220 -0
- package/dist/assets/knowledge/stacks/react-app.md +232 -0
- package/dist/assets/knowledge/universal/deployment.md +109 -0
- package/dist/assets/knowledge/universal/performance.md +121 -0
- package/dist/assets/knowledge/universal/security.md +79 -0
- package/dist/assets/knowledge/universal/testing.md +111 -0
- package/dist/assets/output-styles/silent.md +23 -0
- package/dist/assets/rules/core.md +144 -0
- package/dist/assets/slash-commands/commit.md +23 -0
- package/dist/assets/slash-commands/context.md +112 -0
- package/dist/assets/slash-commands/explain.md +35 -0
- package/dist/assets/slash-commands/mep.md +63 -0
- package/dist/assets/slash-commands/review.md +39 -0
- package/dist/assets/slash-commands/test.md +30 -0
- package/dist/chunk-1rptg3yg.js +4 -0
- package/dist/chunk-1rptg3yg.js.map +10 -0
- package/dist/{chunk-124wqbdb.js → chunk-4fr8q0jy.js} +3 -3
- package/dist/{chunk-124wqbdb.js.map → chunk-4fr8q0jy.js.map} +1 -1
- package/dist/{chunk-f6y5vttn.js → chunk-5szm4n3x.js} +3 -3
- package/dist/{chunk-f6y5vttn.js.map → chunk-5szm4n3x.js.map} +1 -1
- package/dist/chunk-7nht27vs.js +4 -0
- package/dist/{chunk-g9t3me0w.js.map → chunk-7nht27vs.js.map} +2 -2
- package/dist/chunk-8krxe10w.js +3 -0
- package/dist/{chunk-e966bjm5.js.map → chunk-8krxe10w.js.map} +2 -2
- package/dist/{chunk-wpe7rw5c.js → chunk-8z1sf25t.js} +3 -3
- package/dist/{chunk-wpe7rw5c.js.map → chunk-8z1sf25t.js.map} +1 -1
- package/dist/chunk-9c2nr2fz.js +25 -0
- package/dist/chunk-9c2nr2fz.js.map +61 -0
- package/dist/{chunk-4p754rhd.js → chunk-asr22mbn.js} +2 -2
- package/dist/{chunk-4p754rhd.js.map → chunk-asr22mbn.js.map} +2 -2
- package/dist/chunk-bnxtqetr.js +23 -0
- package/dist/chunk-bnxtqetr.js.map +11 -0
- package/dist/chunk-cs1s5c3g.js +54 -0
- package/dist/chunk-cs1s5c3g.js.map +53 -0
- package/dist/chunk-cv1nhr27.js +2 -0
- package/dist/{chunk-hshjnpm0.js.map → chunk-cv1nhr27.js.map} +1 -1
- package/dist/chunk-d4hj6d4t.js +6 -0
- package/dist/chunk-d4hj6d4t.js.map +11 -0
- package/dist/chunk-f06ma45b.js +15 -0
- package/dist/chunk-f06ma45b.js.map +16 -0
- package/dist/chunk-fs3f7acb.js +4 -0
- package/dist/chunk-fs3f7acb.js.map +12 -0
- package/dist/{chunk-5r4afhzp.js → chunk-gh83x9ya.js} +3 -3
- package/dist/{chunk-5r4afhzp.js.map → chunk-gh83x9ya.js.map} +1 -1
- package/dist/{chunk-qa8b725g.js → chunk-gyq335sw.js} +6 -5
- package/dist/{chunk-qa8b725g.js.map → chunk-gyq335sw.js.map} +1 -1
- package/dist/{chunk-hs3nxzyz.js → chunk-hft1735c.js} +2 -2
- package/dist/{chunk-hs3nxzyz.js.map → chunk-hft1735c.js.map} +2 -2
- package/dist/chunk-hj6r7703.js +3 -0
- package/dist/{chunk-78bfvh46.js.map → chunk-hj6r7703.js.map} +2 -2
- package/dist/chunk-hxj4eapp.js +14 -0
- package/dist/chunk-hxj4eapp.js.map +20 -0
- package/dist/chunk-jgsq3xax.js +23 -0
- package/dist/chunk-jgsq3xax.js.map +132 -0
- package/dist/{chunk-646h52kd.js → chunk-m9nt0bj3.js} +3 -3
- package/dist/{chunk-646h52kd.js.map → chunk-m9nt0bj3.js.map} +1 -1
- package/dist/{chunk-bd11hvvz.js → chunk-ndah8mn9.js} +2 -2
- package/dist/{chunk-bd11hvvz.js.map → chunk-ndah8mn9.js.map} +1 -1
- package/dist/chunk-s6g21d1g.js +27 -0
- package/dist/{chunk-0h7sfwq3.js.map → chunk-s6g21d1g.js.map} +4 -5
- package/dist/{chunk-hshjnpm0.js → chunk-sxy6vp20.js} +2 -2
- package/dist/chunk-sxy6vp20.js.map +9 -0
- package/dist/chunk-vjf57v4h.js +4 -0
- package/dist/chunk-vjf57v4h.js.map +10 -0
- package/dist/{chunk-jxny6xft.js → chunk-w2vbmr93.js} +2 -2
- package/dist/{chunk-jxny6xft.js.map → chunk-w2vbmr93.js.map} +1 -1
- package/dist/chunk-wd9qbbe5.js +5 -0
- package/dist/chunk-wd9qbbe5.js.map +10 -0
- package/dist/chunk-wnaa55wn.js +108 -0
- package/dist/chunk-wnaa55wn.js.map +24 -0
- package/dist/chunk-wrx1n6q6.js +16 -0
- package/dist/chunk-wrx1n6q6.js.map +16 -0
- package/dist/chunk-xata5rw6.js +119 -0
- package/dist/{chunk-878q8xdr.js.map → chunk-xata5rw6.js.map} +7 -18
- package/dist/chunk-z2rtyk3d.js +7 -0
- package/dist/{chunk-ygdr4fw7.js.map → chunk-z2rtyk3d.js.map} +2 -2
- package/dist/index.js +446 -482
- package/dist/index.js.map +301 -202
- package/package.json +4 -1
- package/dist/chunk-0h7sfwq3.js +0 -27
- package/dist/chunk-78bfvh46.js +0 -3
- package/dist/chunk-878q8xdr.js +0 -86
- package/dist/chunk-e966bjm5.js +0 -3
- package/dist/chunk-fxwaa2mg.js +0 -4
- package/dist/chunk-fxwaa2mg.js.map +0 -10
- package/dist/chunk-g9t3me0w.js +0 -4
- package/dist/chunk-ygdr4fw7.js +0 -7
package/assets/agents/coder.md
CHANGED
package/assets/agents/writer.md
CHANGED
|
@@ -1,30 +1,30 @@
|
|
|
1
1
|
---
|
|
2
|
-
name:
|
|
3
|
-
description:
|
|
4
|
-
mode:
|
|
2
|
+
name: Writer
|
|
3
|
+
description: Documentation and explanation agent
|
|
4
|
+
mode: primary
|
|
5
5
|
temperature: 0.3
|
|
6
6
|
---
|
|
7
7
|
|
|
8
|
-
#
|
|
8
|
+
# WRITER
|
|
9
9
|
|
|
10
10
|
## Core Rules
|
|
11
11
|
|
|
12
|
-
1. **Never
|
|
12
|
+
1. **Never Implement**: Write about code and systems. Never write executable code.
|
|
13
13
|
|
|
14
|
-
2. **
|
|
14
|
+
2. **Audience First**: Tailor content to reader's knowledge level and needs.
|
|
15
15
|
|
|
16
|
-
3. **
|
|
16
|
+
3. **Clarity Over Completeness**: Make complex ideas accessible. Simple beats comprehensive.
|
|
17
17
|
|
|
18
18
|
---
|
|
19
19
|
|
|
20
|
-
##
|
|
20
|
+
## Writing Modes
|
|
21
21
|
|
|
22
|
-
**
|
|
22
|
+
**Documentation** (reference) → Structure: purpose, usage, examples, edge cases. Exit: Complete, searchable docs.
|
|
23
23
|
|
|
24
|
-
**
|
|
24
|
+
**Tutorial** (learning) → Structure: context, step-by-step, explain why, exercises. Exit: Learner can apply knowledge.
|
|
25
25
|
|
|
26
|
-
**
|
|
26
|
+
**Explanation** (understanding) → Structure: problem, solution, reasoning, trade-offs. Exit: Reader understands decision rationale.
|
|
27
27
|
|
|
28
|
-
**
|
|
28
|
+
**README** (onboarding) → Structure: what, why, quickstart, next steps. Exit: New user can get started.
|
|
29
29
|
|
|
30
|
-
Flow between modes based on
|
|
30
|
+
Flow between modes based on content purpose and audience needs.
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
---
|
|
2
|
+
description: Display current context window usage and token breakdown
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
# Context Window Usage
|
|
6
|
+
|
|
7
|
+
Display detailed information about the current context window usage, including token counts for different components.
|
|
8
|
+
|
|
9
|
+
## Your Task
|
|
10
|
+
|
|
11
|
+
Analyze and display the context window usage with the following sections:
|
|
12
|
+
|
|
13
|
+
### 1. Model Information
|
|
14
|
+
Show the current model being used and its token limits.
|
|
15
|
+
|
|
16
|
+
### 2. Visual Token Usage Bar
|
|
17
|
+
Create a visual bar chart (10 blocks wide) showing token usage breakdown using these Unicode characters:
|
|
18
|
+
- ⛁ (filled) - Used tokens
|
|
19
|
+
- ⛀ (half-filled) - Partially used blocks
|
|
20
|
+
- ⛶ (empty) - Reserved/System tokens
|
|
21
|
+
- ⛝ (light) - Free space/buffer
|
|
22
|
+
|
|
23
|
+
### 3. Token Breakdown
|
|
24
|
+
|
|
25
|
+
Calculate and display tokens for each category:
|
|
26
|
+
|
|
27
|
+
#### System Prompt
|
|
28
|
+
- Count tokens in the system prompt
|
|
29
|
+
- Show: `⛁ System prompt: X.Xk tokens (X.X%)`
|
|
30
|
+
|
|
31
|
+
#### System Tools
|
|
32
|
+
- Count tokens for all built-in tool definitions (filesystem, shell, search, interaction tools)
|
|
33
|
+
- Show: `⛁ System tools: X.Xk tokens (X.X%)`
|
|
34
|
+
|
|
35
|
+
#### MCP Tools
|
|
36
|
+
- Count tokens for all MCP tool definitions
|
|
37
|
+
- List each MCP tool with its token count
|
|
38
|
+
- Show: `⛁ MCP tools: X.Xk tokens (X.X%)`
|
|
39
|
+
|
|
40
|
+
#### Custom Agents
|
|
41
|
+
- Count tokens for custom agent definitions (if any)
|
|
42
|
+
- List each agent with token count
|
|
43
|
+
- Show: `⛁ Custom agents: X tokens (X.X%)`
|
|
44
|
+
|
|
45
|
+
#### Messages
|
|
46
|
+
- Count tokens in all messages in the current session
|
|
47
|
+
- Show: `⛁ Messages: X tokens (X.X%)`
|
|
48
|
+
|
|
49
|
+
#### Free Space
|
|
50
|
+
- Calculate remaining available tokens
|
|
51
|
+
- Show: `⛶ Free space: XXXk (XX.X%)`
|
|
52
|
+
|
|
53
|
+
#### Autocompact Buffer
|
|
54
|
+
- Calculate reserved buffer space (typically 22.5% of total)
|
|
55
|
+
- Show: `⛝ Autocompact buffer: XX.Xk tokens (XX.X%)`
|
|
56
|
+
|
|
57
|
+
### 4. Detailed Listings
|
|
58
|
+
|
|
59
|
+
Show expandable sections with details:
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
MCP tools · /mcp
|
|
63
|
+
└ mcp__tool_name (server-name): XXX tokens
|
|
64
|
+
└ ...
|
|
65
|
+
|
|
66
|
+
Custom agents · /agents
|
|
67
|
+
└ agent-name (Project): XX tokens
|
|
68
|
+
└ ...
|
|
69
|
+
|
|
70
|
+
SlashCommand Tool · X commands
|
|
71
|
+
└ Total: XXX tokens
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
## Display Format
|
|
75
|
+
|
|
76
|
+
Use this exact format for the output:
|
|
77
|
+
|
|
78
|
+
```
|
|
79
|
+
Context Usage
|
|
80
|
+
⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛁ ⛀ ⛁ ⛁ model-name · XXk/XXXk tokens (XX%)
|
|
81
|
+
⛀ ⛀ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶
|
|
82
|
+
⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ System prompt: X.Xk tokens (X.X%)
|
|
83
|
+
⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ System tools: XX.Xk tokens (X.X%)
|
|
84
|
+
⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ MCP tools: X.Xk tokens (X.X%)
|
|
85
|
+
⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ Custom agents: XX tokens (X.X%)
|
|
86
|
+
⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛁ Messages: XXX tokens (X.X%)
|
|
87
|
+
⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛶ ⛝ ⛝ ⛝ ⛶ Free space: XXXk (XX.X%)
|
|
88
|
+
⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ Autocompact buffer: XX.Xk tokens (XX.X%)
|
|
89
|
+
⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝ ⛝
|
|
90
|
+
|
|
91
|
+
MCP tools · /mcp
|
|
92
|
+
└ tool_name (server-name): XXX tokens
|
|
93
|
+
└ ...
|
|
94
|
+
|
|
95
|
+
Custom agents · /agents
|
|
96
|
+
└ agent-name (Project): XX tokens
|
|
97
|
+
└ ...
|
|
98
|
+
|
|
99
|
+
SlashCommand Tool · X commands
|
|
100
|
+
└ Total: XXX tokens
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
## Implementation Notes
|
|
104
|
+
|
|
105
|
+
1. Use the `countTokens()` utility from `src/utils/token-counter.ts` with the current session model name
|
|
106
|
+
2. Get current session from app store to access model name and messages
|
|
107
|
+
3. Get system prompt from `src/core/ai-sdk.ts` (SYSTEM_PROMPT constant)
|
|
108
|
+
4. Get tool definitions from `src/tools/registry.ts` (getAISDKTools())
|
|
109
|
+
5. Calculate percentages based on the model's max token limit (e.g., 200k for Claude Sonnet 4.5)
|
|
110
|
+
6. Round token counts appropriately (show decimals for k, no decimals for raw numbers)
|
|
111
|
+
7. Ensure the bar chart accurately represents the proportions
|
|
112
|
+
8. Use proper indentation and alignment for readability
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Coder
|
|
3
|
+
description: Code execution agent
|
|
4
|
+
mode: both
|
|
5
|
+
temperature: 0.3
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# CODER
|
|
9
|
+
|
|
10
|
+
## Core Rules
|
|
11
|
+
|
|
12
|
+
1. **Verify Always**: Run tests after every code change. Validate all inputs. Never expose secrets or commit broken code.
|
|
13
|
+
|
|
14
|
+
2. **Search Before Build**: Research best practices and search codebase before implementing. Use existing libraries/patterns.
|
|
15
|
+
|
|
16
|
+
3. **Complete Now**: Finish fully, no TODOs. Refactor immediately as you code. "Later" never happens.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Execution Modes
|
|
21
|
+
|
|
22
|
+
**Investigation** (unclear) → Read code, explore domain, validate assumptions. Exit: Can articulate problem, constraints, approach.
|
|
23
|
+
|
|
24
|
+
**Design** (direction needed) → Sketch architecture, define boundaries, plan integration. Exit: Can explain solution clearly.
|
|
25
|
+
|
|
26
|
+
**Implementation** (path clear) → Write test first, implement increment, run tests immediately, refactor if needed, commit when tests pass.
|
|
27
|
+
|
|
28
|
+
**Red flags** → Return to Design: Code significantly harder than expected, tests difficult, unclear what/how to test.
|
|
29
|
+
|
|
30
|
+
**Validation** (uncertain) → Run tests, check security, verify performance.
|
|
31
|
+
|
|
32
|
+
Flow between modes adaptively based on signals (friction, confusion, confidence).
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Orchestrator
|
|
3
|
+
description: Task coordination and agent delegation
|
|
4
|
+
mode: primary
|
|
5
|
+
temperature: 0.3
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# ORCHESTRATOR
|
|
9
|
+
|
|
10
|
+
## Core Rules
|
|
11
|
+
|
|
12
|
+
1. **Never Do Work**: Delegate all concrete work to specialist agents (coder, reviewer, writer).
|
|
13
|
+
|
|
14
|
+
2. **Decompose Complex Tasks**: Break into subtasks with clear dependencies and ordering.
|
|
15
|
+
|
|
16
|
+
3. **Synthesize Results**: Combine agent outputs into coherent response for user.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Orchestration Flow
|
|
21
|
+
|
|
22
|
+
**Analyze** (understand request) → Identify required agents and dependencies. Exit: Clear task breakdown.
|
|
23
|
+
|
|
24
|
+
**Decompose** (plan execution) → Define subtasks, sequence, and which agent handles each. Exit: Execution plan with dependencies.
|
|
25
|
+
|
|
26
|
+
**Delegate** (assign work) → Call specialist agents with specific, focused instructions. Monitor completion.
|
|
27
|
+
|
|
28
|
+
**Handle Iterations** (if needed) → If agent output needs refinement, delegate follow-up. Example: coder → reviewer → coder fixes.
|
|
29
|
+
|
|
30
|
+
**Synthesize** (combine results) → Merge agent outputs into final deliverable for user.
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
## Agent Selection
|
|
35
|
+
|
|
36
|
+
Select agents based on their descriptions in the environment. Match task requirements to agent capabilities.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Reviewer
|
|
3
|
+
description: Code review and critique agent
|
|
4
|
+
mode: both
|
|
5
|
+
temperature: 0.3
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# REVIEWER
|
|
9
|
+
|
|
10
|
+
## Core Rules
|
|
11
|
+
|
|
12
|
+
1. **Never Modify**: Read and analyze existing code. Never implement changes.
|
|
13
|
+
|
|
14
|
+
2. **Objective Critique**: Identify issues without bias. Present facts and reasoning.
|
|
15
|
+
|
|
16
|
+
3. **Actionable Feedback**: Suggest specific improvements, not vague observations.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Review Modes
|
|
21
|
+
|
|
22
|
+
**Code Review** (readability/maintainability) → Check: naming, structure, complexity, duplication. Exit: Clear improvement suggestions.
|
|
23
|
+
|
|
24
|
+
**Security Review** (vulnerabilities) → Check: input validation, auth, data exposure, injection risks. Exit: Security recommendations with severity.
|
|
25
|
+
|
|
26
|
+
**Performance Review** (efficiency) → Check: algorithms, queries, caching, bottlenecks. Exit: Performance improvements with impact estimate.
|
|
27
|
+
|
|
28
|
+
**Architecture Review** (design) → Check: coupling, cohesion, scalability, maintainability. Exit: Design recommendations.
|
|
29
|
+
|
|
30
|
+
Flow between modes based on review focus and findings.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: Writer
|
|
3
|
+
description: Documentation and explanation agent
|
|
4
|
+
mode: primary
|
|
5
|
+
temperature: 0.3
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# WRITER
|
|
9
|
+
|
|
10
|
+
## Core Rules
|
|
11
|
+
|
|
12
|
+
1. **Never Implement**: Write about code and systems. Never write executable code.
|
|
13
|
+
|
|
14
|
+
2. **Audience First**: Tailor content to reader's knowledge level and needs.
|
|
15
|
+
|
|
16
|
+
3. **Clarity Over Completeness**: Make complex ideas accessible. Simple beats comprehensive.
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Writing Modes
|
|
21
|
+
|
|
22
|
+
**Documentation** (reference) → Structure: purpose, usage, examples, edge cases. Exit: Complete, searchable docs.
|
|
23
|
+
|
|
24
|
+
**Tutorial** (learning) → Structure: context, step-by-step, explain why, exercises. Exit: Learner can apply knowledge.
|
|
25
|
+
|
|
26
|
+
**Explanation** (understanding) → Structure: problem, solution, reasoning, trade-offs. Exit: Reader understands decision rationale.
|
|
27
|
+
|
|
28
|
+
**README** (onboarding) → Structure: what, why, quickstart, next steps. Exit: New user can get started.
|
|
29
|
+
|
|
30
|
+
Flow between modes based on content purpose and audience needs.
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: SQL & Relational DBs
|
|
3
|
+
description: Postgres/MySQL patterns, indexing, transactions, migrations, query optimization
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# SQL & Relational Databases
|
|
7
|
+
|
|
8
|
+
## When SQL vs NoSQL
|
|
9
|
+
|
|
10
|
+
**SQL (Postgres, MySQL)**: Clear relationships, ACID transactions, complex queries with joins, strong consistency, stable schema
|
|
11
|
+
|
|
12
|
+
**NoSQL (MongoDB)**: Flexible schema, horizontal scaling, document data, simple queries
|
|
13
|
+
|
|
14
|
+
**Default: SQL (Postgres)** - More powerful, safer for most use cases
|
|
15
|
+
|
|
16
|
+
## Schema Design
|
|
17
|
+
|
|
18
|
+
### Foreign Keys & Relationships
|
|
19
|
+
Always use foreign keys with `ON DELETE CASCADE/SET NULL`. Prevents orphaned records.
|
|
20
|
+
|
|
21
|
+
```sql
|
|
22
|
+
CREATE TABLE posts (
|
|
23
|
+
id SERIAL PRIMARY KEY,
|
|
24
|
+
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE
|
|
25
|
+
);
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
### Many-to-Many
|
|
29
|
+
Use junction table with composite primary key to prevent duplicates:
|
|
30
|
+
|
|
31
|
+
```sql
|
|
32
|
+
CREATE TABLE likes (
|
|
33
|
+
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
|
|
34
|
+
post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
|
|
35
|
+
PRIMARY KEY (user_id, post_id)
|
|
36
|
+
);
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
## Indexes
|
|
40
|
+
|
|
41
|
+
```sql
|
|
42
|
+
-- Single column
|
|
43
|
+
CREATE INDEX idx_posts_user_id ON posts(user_id);
|
|
44
|
+
|
|
45
|
+
-- Composite (order matters!)
|
|
46
|
+
CREATE INDEX idx_posts_user_created ON posts(user_id, created_at DESC);
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
**When to index:**
|
|
50
|
+
- ✅ Foreign keys (always), WHERE clauses, ORDER BY, JOIN conditions
|
|
51
|
+
- ❌ Frequently changing columns (slows writes), small tables (< 1000 rows)
|
|
52
|
+
|
|
53
|
+
## Query Optimization
|
|
54
|
+
|
|
55
|
+
### N+1 Problem
|
|
56
|
+
```sql
|
|
57
|
+
-- BAD: N+1 queries
|
|
58
|
+
SELECT * FROM users;
|
|
59
|
+
-- Then for each user:
|
|
60
|
+
SELECT * FROM posts WHERE user_id = ?;
|
|
61
|
+
|
|
62
|
+
-- GOOD: 1 query with JOIN
|
|
63
|
+
SELECT u.*, p.id as post_id, p.title FROM users u
|
|
64
|
+
LEFT JOIN posts p ON p.user_id = u.id;
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Use EXPLAIN
|
|
68
|
+
```sql
|
|
69
|
+
EXPLAIN ANALYZE SELECT * FROM posts WHERE user_id = 123;
|
|
70
|
+
|
|
71
|
+
-- Look for: Index Scan (good), Seq Scan (bad - full table)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### Pagination
|
|
75
|
+
```sql
|
|
76
|
+
-- BAD: OFFSET slow for large offsets
|
|
77
|
+
SELECT * FROM posts ORDER BY created_at LIMIT 20 OFFSET 10000;
|
|
78
|
+
-- Reads and discards 10000 rows!
|
|
79
|
+
|
|
80
|
+
-- GOOD: Cursor-based
|
|
81
|
+
SELECT * FROM posts
|
|
82
|
+
WHERE created_at < '2024-01-01'
|
|
83
|
+
ORDER BY created_at DESC LIMIT 20;
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Transactions (ACID)
|
|
87
|
+
|
|
88
|
+
**Use for**: Money transfers, inventory, related records that must stay consistent
|
|
89
|
+
|
|
90
|
+
```sql
|
|
91
|
+
BEGIN;
|
|
92
|
+
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
|
|
93
|
+
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
|
|
94
|
+
COMMIT; -- Both succeed or both fail
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
**Isolation Levels:**
|
|
98
|
+
- READ COMMITTED (default, good for most)
|
|
99
|
+
- SERIALIZABLE (strongest, slowest - critical ops)
|
|
100
|
+
|
|
101
|
+
## Common Patterns
|
|
102
|
+
|
|
103
|
+
**Soft Deletes**: Add `deleted_at TIMESTAMP NULL`, filter with `WHERE deleted_at IS NULL`
|
|
104
|
+
|
|
105
|
+
**Timestamps**: Add `created_at`, `updated_at` with triggers for auto-update
|
|
106
|
+
|
|
107
|
+
**Enums**: Use CHECK constraint or ENUM type for fixed values (status, role)
|
|
108
|
+
|
|
109
|
+
## Migrations
|
|
110
|
+
|
|
111
|
+
### Add Column (Safe)
|
|
112
|
+
```sql
|
|
113
|
+
-- Safe: nullable
|
|
114
|
+
ALTER TABLE users ADD COLUMN phone VARCHAR(20);
|
|
115
|
+
|
|
116
|
+
-- Safe: with default
|
|
117
|
+
ALTER TABLE users ADD COLUMN is_active BOOLEAN DEFAULT true;
|
|
118
|
+
```
|
|
119
|
+
|
|
120
|
+
### Change Column (Risky)
|
|
121
|
+
```sql
|
|
122
|
+
-- Safer: Add new, migrate data, drop old
|
|
123
|
+
ALTER TABLE users ADD COLUMN email_new VARCHAR(500);
|
|
124
|
+
UPDATE users SET email_new = email;
|
|
125
|
+
ALTER TABLE users DROP COLUMN email;
|
|
126
|
+
ALTER TABLE users RENAME COLUMN email_new TO email;
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
### Add Index (Lock-Free)
|
|
130
|
+
```sql
|
|
131
|
+
-- Postgres: doesn't block writes
|
|
132
|
+
CREATE INDEX CONCURRENTLY idx_posts_user_id ON posts(user_id);
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
## Performance Tips
|
|
136
|
+
|
|
137
|
+
### Connection Pooling
|
|
138
|
+
```typescript
|
|
139
|
+
const pool = new Pool({
|
|
140
|
+
max: 20,
|
|
141
|
+
idleTimeoutMillis: 30000,
|
|
142
|
+
connectionTimeoutMillis: 2000
|
|
143
|
+
})
|
|
144
|
+
|
|
145
|
+
// Use pool.query(), not new Client() per request
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
### Prepared Statements (Prevent Injection)
|
|
149
|
+
```typescript
|
|
150
|
+
// BAD: SQL injection vulnerable
|
|
151
|
+
db.query(`SELECT * FROM users WHERE email = '${userInput}'`)
|
|
152
|
+
|
|
153
|
+
// GOOD: Prepared
|
|
154
|
+
db.query('SELECT * FROM users WHERE email = $1', [userInput])
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
### Batch Operations
|
|
158
|
+
```sql
|
|
159
|
+
-- BAD: 1000 separate inserts
|
|
160
|
+
INSERT INTO posts (title) VALUES ('Post 1');
|
|
161
|
+
|
|
162
|
+
-- GOOD: Batch
|
|
163
|
+
INSERT INTO posts (title) VALUES ('Post 1'), ('Post 2'), ('Post 3');
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
## Full-Text Search
|
|
167
|
+
|
|
168
|
+
Add `tsvector` column, create GIN index, use `@@` operator:
|
|
169
|
+
|
|
170
|
+
```sql
|
|
171
|
+
ALTER TABLE posts ADD COLUMN search_vector tsvector;
|
|
172
|
+
CREATE INDEX idx_posts_search ON posts USING GIN(search_vector);
|
|
173
|
+
SELECT * FROM posts WHERE search_vector @@ to_tsquery('react & typescript');
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## Common Mistakes
|
|
177
|
+
|
|
178
|
+
❌ **Not using foreign keys** → Orphaned records
|
|
179
|
+
❌ **Not indexing foreign keys** → Slow joins
|
|
180
|
+
❌ **VARCHAR without limit** → Use VARCHAR(255)
|
|
181
|
+
❌ **Not handling NULL** → Use IS NULL, not = NULL
|
|
182
|
+
❌ **String concatenation** → SQL injection, use prepared statements
|
|
183
|
+
|
|
184
|
+
## ORMs (Prisma, Drizzle, TypeORM)
|
|
185
|
+
|
|
186
|
+
**Pros**: Type safety, easier migrations, less SQL
|
|
187
|
+
**Cons**: Less control, can generate inefficient SQL, overhead
|
|
188
|
+
|
|
189
|
+
**Recommendation**: ORM for CRUD, raw SQL for complex queries
|
|
190
|
+
|
|
191
|
+
```typescript
|
|
192
|
+
// Prisma
|
|
193
|
+
const user = await prisma.user.findUnique({
|
|
194
|
+
where: { id: 1 },
|
|
195
|
+
include: { posts: true }
|
|
196
|
+
})
|
|
197
|
+
|
|
198
|
+
// Raw when needed
|
|
199
|
+
const result = await prisma.$queryRaw`SELECT ... complex query ...`
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
## Monitoring
|
|
203
|
+
|
|
204
|
+
**Slow Query Log**: Enable logging for queries > 100ms, identify bottlenecks
|
|
205
|
+
|
|
206
|
+
**Check Index Usage**: Find unused indexes with `pg_stat_user_indexes WHERE idx_scan = 0`
|
|
207
|
+
|
|
208
|
+
**Check Query Stats**: Use `pg_stat_statements` to find slow queries
|
|
209
|
+
|
|
210
|
+
## Decision Guide
|
|
211
|
+
|
|
212
|
+
**Normalize vs Denormalize**: Normalize by default, denormalize for read-heavy, use materialized views for expensive aggregations
|
|
213
|
+
|
|
214
|
+
**JSON column**: Flexible schema-less data (user preferences), data you won't query often. NOT for filtering/sorting.
|
|
215
|
+
|
|
216
|
+
**Add index**: Column in WHERE on large table, foreign keys (always), after identifying slow queries. NOT on every column.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: SaaS Template
|
|
3
|
+
description: Complete SaaS feature spec: auth, billing, multi-tenancy, compliance
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# SaaS Platform Specification
|
|
7
|
+
|
|
8
|
+
Scalable, secure SaaS for modern web apps. USD wallet billing, tiered memberships, serverless SPA architecture. Prioritize security, usability, extensibility.
|
|
9
|
+
|
|
10
|
+
## Core Requirements
|
|
11
|
+
- **Architecture**: Responsive SPA, serverless backend (Vercel/Cloudflare)
|
|
12
|
+
- **Currency**: USD only
|
|
13
|
+
- **Billing**: Wallet-based (Stripe), membership discounts before deductions
|
|
14
|
+
- **Memberships**: Tiers (Small/Medium/Large) with monthly auto-top-ups, discounts, entitlements. Yearly = 10x monthly. Admin-configurable.
|
|
15
|
+
- **Compliance**: GDPR/CCPA compliant, verifiable acceptance criteria
|
|
16
|
+
|
|
17
|
+
## Core Features
|
|
18
|
+
|
|
19
|
+
### Auth & User Management
|
|
20
|
+
- **Auth**: Email/password, SSO (Google/OAuth), Passkey-first 2FA (SimpleWebAuthn), reCAPTCHA v3, rate limiting (5 attempts/5min)
|
|
21
|
+
- **Sessions**: Rotating JWTs, Redis denylist, log all logins (IP, UA, timestamp)
|
|
22
|
+
- **Security**: 2FA setup/recovery codes, email alerts for new logins/devices
|
|
23
|
+
- **Profiles**: Display name, bio, avatar (128x128px, S3)
|
|
24
|
+
- **Usernames**: Unique, lowercase, reserved blocks, 30-day change cooldown + audit
|
|
25
|
+
- **Devices**: Active sessions list (IP/UA/location), one-click logout
|
|
26
|
+
|
|
27
|
+
- **Invites & Referrals**: Shareable codes/links/QR with limits/expiration. Track referrals, reward wallet credits (configurable).
|
|
28
|
+
- **Notifications**: User-configurable email/push, in-app hub with bell, unread counts, mark-read
|
|
29
|
+
- **Activity Feed**: Log actions (recharges, spends, logins, invites, referrals) with timestamps/filters
|
|
30
|
+
|
|
31
|
+
### Billing & Wallet
|
|
32
|
+
- **Wallet**: USD balances, Stripe top-ups (min $10), auto-deduct with tier discounts
|
|
33
|
+
- **Memberships**: Tiers ($10/mo, $50/mo, $100/mo) with auto-top-up, % discounts, perks. Yearly = 10x. Admin CRUD.
|
|
34
|
+
- **Invoicing**: PDF receipts, admin dashboard for search/export (CSV/PDF)
|
|
35
|
+
|
|
36
|
+
### Admin Dashboard
|
|
37
|
+
Role-based (admin/moderator). Charts/tables for insights.
|
|
38
|
+
- **Overview**: Metrics (date, plan, region, device), visualize revenue/users/growth
|
|
39
|
+
- **User Management**: Search, role assignment, bans, username approval
|
|
40
|
+
- **Billing**: Manage subscriptions/refunds, invoices, bulk adjustments
|
|
41
|
+
- **Wallet**: Reconcile, flag anomalies (>$1000 top-up)
|
|
42
|
+
- **Marketing**: Newsletter lists/broadcasts, track open/unsubscribe
|
|
43
|
+
- **Invites/Referrals**: Generate codes/programs, monitor stats/rewards
|
|
44
|
+
- **Memberships**: CRUD plans (price, top-up, discounts, entitlements)
|
|
45
|
+
- **Notifications**: Global broadcasts (email/push)
|
|
46
|
+
- **Support**: Ticket queue with reply/status
|
|
47
|
+
- **Audits**: Searchable logs (user/action/timestamp), export
|
|
48
|
+
|
|
49
|
+
### Content & Support
|
|
50
|
+
- **Knowledge Base**: Docs/FAQ (MDX)
|
|
51
|
+
- **CMS**: Blog for announcements
|
|
52
|
+
- **Status**: Real-time uptime/incidents, historical data
|
|
53
|
+
- **Help**: Contact form → tickets, admin responses
|
|
54
|
+
|
|
55
|
+
### Public Pages
|
|
56
|
+
- **Landing**: Home, Features, Pricing (SEO-optimized)
|
|
57
|
+
- **Profiles**: /u/<username> (bio, stats, Open Graph)
|
|
58
|
+
- **Referrals**: /r/<code> redirects with tracking
|
|
59
|
+
- **Legal**: Terms, Privacy, Cookies. Consent banner with granular controls.
|
|
60
|
+
|
|
61
|
+
### Advanced Features
|
|
62
|
+
- **Error Handling**: Custom 404/500, search/suggestions, auto-redirect
|
|
63
|
+
- **Analytics**: Consent-gated GA, newsletter engagement (no PII)
|
|
64
|
+
- **Consent**: Log agreements (user_id, type, version, timestamp, IP/UA). Version policies, granular toggles, history export/revocation.
|
|
65
|
+
|
|
66
|
+
## Legal & Compliance
|
|
67
|
+
GDPR, CCPA, PECR. Data minimization, user rights.
|
|
68
|
+
- **Cookies**: Banner with opt-in/out, categorize (necessary, analytics, marketing), persist in DB
|
|
69
|
+
- **Data Rights**: Export/delete endpoints, process within 30 days (P1)
|
|
70
|
+
- **Documentation**: MDX pages (Privacy, Terms, Cookies), version updates with notifications
|
|
71
|
+
- **Logging**: Immutable consent/action records, audit for compliance
|
|
72
|
+
|
|
73
|
+
## Deployment
|
|
74
|
+
Serverless for scalability, CI/CD for reliability.
|
|
75
|
+
- **Local**: Docker Compose (web/DB/Redis). Run: `bun install && bun db:migrate && bun dev`
|
|
76
|
+
- **Monitoring**: Sentry for errors, SLO alerts (99.9%), retry failed webhooks (3x, exponential)
|
|
77
|
+
- **Status**: Auto-update from monitoring events
|
|
78
|
+
|
|
79
|
+
## Testing
|
|
80
|
+
100% coverage, enforce via CI. TDD for new features.
|
|
81
|
+
- **Unit**: Vitest, mock externalities
|
|
82
|
+
- **E2E**: Playwright (register → login → 2FA → top-up → consume → invoice → unsubscribe → invite → referral → ticket)
|
|
83
|
+
- **Accessibility**: axe-core, Lighthouse A11y >95
|
|
84
|
+
- **Performance**: Responsive, lazy loading, Iconify icons
|
|
85
|
+
- **Quality**: Biome linting/formatting, pre-commit hooks
|