@aicgen/aicgen 1.0.0-beta.1

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 (287) hide show
  1. package/.claude/agents/architecture-reviewer.md +88 -0
  2. package/.claude/agents/guideline-checker.md +73 -0
  3. package/.claude/agents/security-auditor.md +108 -0
  4. package/.claude/guidelines/api-design.md +645 -0
  5. package/.claude/guidelines/architecture.md +2503 -0
  6. package/.claude/guidelines/best-practices.md +618 -0
  7. package/.claude/guidelines/code-style.md +304 -0
  8. package/.claude/guidelines/design-patterns.md +573 -0
  9. package/.claude/guidelines/devops.md +226 -0
  10. package/.claude/guidelines/error-handling.md +413 -0
  11. package/.claude/guidelines/language.md +782 -0
  12. package/.claude/guidelines/performance.md +706 -0
  13. package/.claude/guidelines/security.md +583 -0
  14. package/.claude/guidelines/testing.md +568 -0
  15. package/.claude/settings.json +98 -0
  16. package/.claude/settings.local.json +8 -0
  17. package/.env.example +23 -0
  18. package/.eslintrc.json +28 -0
  19. package/.github/workflows/release.yml +180 -0
  20. package/.github/workflows/test.yml +81 -0
  21. package/.gitmodules +3 -0
  22. package/.vs/ProjectSettings.json +3 -0
  23. package/.vs/VSWorkspaceState.json +16 -0
  24. package/.vs/aicgen.slnx/FileContentIndex/5f0ce2a3-fd68-4863-9e23-e428cf1794e3.vsidx +0 -0
  25. package/.vs/aicgen.slnx/v18/.wsuo +0 -0
  26. package/.vs/aicgen.slnx/v18/DocumentLayout.json +54 -0
  27. package/.vs/slnx.sqlite +0 -0
  28. package/AGENTS.md +121 -0
  29. package/CLAUDE.md +36 -0
  30. package/CONTRIBUTING.md +821 -0
  31. package/LICENSE +21 -0
  32. package/README.md +199 -0
  33. package/assets/icon.svg +34 -0
  34. package/assets/logo.svg +41 -0
  35. package/bun.lock +848 -0
  36. package/data/LICENSE +21 -0
  37. package/data/README.md +203 -0
  38. package/data/api/basics.md +292 -0
  39. package/data/api/index.md +8 -0
  40. package/data/api/pagination.md +142 -0
  41. package/data/api/rest.md +137 -0
  42. package/data/api/versioning.md +60 -0
  43. package/data/architecture/clean-architecture/index.md +7 -0
  44. package/data/architecture/clean-architecture/layers.md +111 -0
  45. package/data/architecture/ddd/index.md +8 -0
  46. package/data/architecture/ddd/strategic.md +89 -0
  47. package/data/architecture/ddd/tactical.md +132 -0
  48. package/data/architecture/event-driven/index.md +7 -0
  49. package/data/architecture/event-driven/messaging.md +242 -0
  50. package/data/architecture/event-driven/patterns.md +129 -0
  51. package/data/architecture/feature-toggles/index.md +7 -0
  52. package/data/architecture/feature-toggles/patterns.md +73 -0
  53. package/data/architecture/gui/index.md +7 -0
  54. package/data/architecture/gui/patterns.md +132 -0
  55. package/data/architecture/hexagonal/ports-adapters.md +132 -0
  56. package/data/architecture/index.md +12 -0
  57. package/data/architecture/layered/index.md +7 -0
  58. package/data/architecture/layered/layers.md +100 -0
  59. package/data/architecture/microservices/api-gateway.md +56 -0
  60. package/data/architecture/microservices/boundaries.md +80 -0
  61. package/data/architecture/microservices/communication.md +97 -0
  62. package/data/architecture/microservices/data.md +92 -0
  63. package/data/architecture/microservices/index.md +11 -0
  64. package/data/architecture/microservices/resilience.md +111 -0
  65. package/data/architecture/modular-monolith/boundaries.md +133 -0
  66. package/data/architecture/modular-monolith/structure.md +131 -0
  67. package/data/architecture/serverless/best-practices.md +322 -0
  68. package/data/architecture/serverless/index.md +7 -0
  69. package/data/architecture/serverless/patterns.md +80 -0
  70. package/data/architecture/solid/index.md +7 -0
  71. package/data/architecture/solid/principles.md +187 -0
  72. package/data/database/basics.md +365 -0
  73. package/data/database/design-patterns.md +68 -0
  74. package/data/database/index.md +8 -0
  75. package/data/database/indexing.md +136 -0
  76. package/data/database/nosql.md +223 -0
  77. package/data/database/schema.md +137 -0
  78. package/data/devops/ci-cd.md +66 -0
  79. package/data/devops/index.md +8 -0
  80. package/data/devops/observability.md +73 -0
  81. package/data/devops/practices.md +77 -0
  82. package/data/error-handling/basics.md +222 -0
  83. package/data/error-handling/index.md +7 -0
  84. package/data/error-handling/strategy.md +185 -0
  85. package/data/guideline-mappings.yml +1077 -0
  86. package/data/index.md +3 -0
  87. package/data/language/csharp/basics.md +210 -0
  88. package/data/language/csharp/testing.md +252 -0
  89. package/data/language/go/basics.md +158 -0
  90. package/data/language/go/testing.md +192 -0
  91. package/data/language/index.md +14 -0
  92. package/data/language/java/basics.md +184 -0
  93. package/data/language/java/testing.md +273 -0
  94. package/data/language/javascript/basics.md +217 -0
  95. package/data/language/javascript/testing.md +269 -0
  96. package/data/language/python/async.md +100 -0
  97. package/data/language/python/basics.md +100 -0
  98. package/data/language/python/index.md +10 -0
  99. package/data/language/python/testing.md +125 -0
  100. package/data/language/python/types.md +99 -0
  101. package/data/language/ruby/basics.md +227 -0
  102. package/data/language/ruby/testing.md +267 -0
  103. package/data/language/rust/basics.md +175 -0
  104. package/data/language/rust/testing.md +219 -0
  105. package/data/language/typescript/async.md +103 -0
  106. package/data/language/typescript/basics.md +87 -0
  107. package/data/language/typescript/config.md +95 -0
  108. package/data/language/typescript/error-handling.md +98 -0
  109. package/data/language/typescript/generics.md +85 -0
  110. package/data/language/typescript/index.md +14 -0
  111. package/data/language/typescript/interfaces-types.md +83 -0
  112. package/data/language/typescript/performance.md +103 -0
  113. package/data/language/typescript/testing.md +98 -0
  114. package/data/patterns/base-patterns.md +105 -0
  115. package/data/patterns/concurrency.md +87 -0
  116. package/data/patterns/data-access.md +83 -0
  117. package/data/patterns/distribution.md +86 -0
  118. package/data/patterns/domain-logic.md +81 -0
  119. package/data/patterns/gof.md +109 -0
  120. package/data/patterns/index.md +12 -0
  121. package/data/performance/async.md +148 -0
  122. package/data/performance/basics.md +324 -0
  123. package/data/performance/caching-strategies.md +68 -0
  124. package/data/performance/caching.md +152 -0
  125. package/data/performance/index.md +8 -0
  126. package/data/practices/code-review.md +52 -0
  127. package/data/practices/documentation.md +260 -0
  128. package/data/practices/index.md +11 -0
  129. package/data/practices/planning.md +142 -0
  130. package/data/practices/refactoring.md +91 -0
  131. package/data/practices/version-control.md +55 -0
  132. package/data/security/auth-jwt.md +159 -0
  133. package/data/security/headers.md +143 -0
  134. package/data/security/index.md +10 -0
  135. package/data/security/injection.md +119 -0
  136. package/data/security/secrets.md +148 -0
  137. package/data/style/index.md +8 -0
  138. package/data/style/naming.md +136 -0
  139. package/data/style/organization.md +162 -0
  140. package/data/templates/agents/architecture-reviewer.md +88 -0
  141. package/data/templates/agents/guideline-checker.md +73 -0
  142. package/data/templates/agents/security-auditor.md +108 -0
  143. package/data/templates/antigravity/rules/architecture.md.hbs +5 -0
  144. package/data/templates/antigravity/rules/code-style.md.hbs +5 -0
  145. package/data/templates/antigravity/rules/language.md.hbs +5 -0
  146. package/data/templates/antigravity/rules/performance.md.hbs +5 -0
  147. package/data/templates/antigravity/rules/security.md.hbs +5 -0
  148. package/data/templates/antigravity/rules/testing.md.hbs +5 -0
  149. package/data/templates/antigravity/workflows/add-documentation.md.hbs +23 -0
  150. package/data/templates/antigravity/workflows/generate-integration-tests.md.hbs +17 -0
  151. package/data/templates/antigravity/workflows/generate-unit-tests.md.hbs +20 -0
  152. package/data/templates/antigravity/workflows/performance-audit.md.hbs +24 -0
  153. package/data/templates/antigravity/workflows/refactor-extract-module.md.hbs +17 -0
  154. package/data/templates/antigravity/workflows/security-audit.md.hbs +20 -0
  155. package/data/templates/hooks/formatting.json +26 -0
  156. package/data/templates/hooks/security.json +35 -0
  157. package/data/templates/hooks/testing.json +17 -0
  158. package/data/testing/basics.md +151 -0
  159. package/data/testing/index.md +9 -0
  160. package/data/testing/integration.md +159 -0
  161. package/data/testing/unit-fundamentals.md +128 -0
  162. package/data/testing/unit-mocking.md +116 -0
  163. package/data/version.json +49 -0
  164. package/dist/commands/init.d.ts +8 -0
  165. package/dist/commands/init.d.ts.map +1 -0
  166. package/dist/commands/init.js +46 -0
  167. package/dist/commands/init.js.map +1 -0
  168. package/dist/config/profiles.d.ts +4 -0
  169. package/dist/config/profiles.d.ts.map +1 -0
  170. package/dist/config/profiles.js +30 -0
  171. package/dist/config/profiles.js.map +1 -0
  172. package/dist/config/settings.d.ts +7 -0
  173. package/dist/config/settings.d.ts.map +1 -0
  174. package/dist/config/settings.js +7 -0
  175. package/dist/config/settings.js.map +1 -0
  176. package/dist/index.d.ts +3 -0
  177. package/dist/index.d.ts.map +1 -0
  178. package/dist/index.js +58489 -0
  179. package/dist/index.js.map +1 -0
  180. package/dist/models/guideline.d.ts +15 -0
  181. package/dist/models/guideline.d.ts.map +1 -0
  182. package/dist/models/guideline.js +2 -0
  183. package/dist/models/guideline.js.map +1 -0
  184. package/dist/models/preference.d.ts +9 -0
  185. package/dist/models/preference.d.ts.map +1 -0
  186. package/dist/models/preference.js +2 -0
  187. package/dist/models/preference.js.map +1 -0
  188. package/dist/models/profile.d.ts +9 -0
  189. package/dist/models/profile.d.ts.map +1 -0
  190. package/dist/models/profile.js +2 -0
  191. package/dist/models/profile.js.map +1 -0
  192. package/dist/models/project.d.ts +13 -0
  193. package/dist/models/project.d.ts.map +1 -0
  194. package/dist/models/project.js +2 -0
  195. package/dist/models/project.js.map +1 -0
  196. package/dist/services/ai/anthropic.d.ts +7 -0
  197. package/dist/services/ai/anthropic.d.ts.map +1 -0
  198. package/dist/services/ai/anthropic.js +39 -0
  199. package/dist/services/ai/anthropic.js.map +1 -0
  200. package/dist/services/generator.d.ts +2 -0
  201. package/dist/services/generator.d.ts.map +1 -0
  202. package/dist/services/generator.js +4 -0
  203. package/dist/services/generator.js.map +1 -0
  204. package/dist/services/learner.d.ts +2 -0
  205. package/dist/services/learner.d.ts.map +1 -0
  206. package/dist/services/learner.js +4 -0
  207. package/dist/services/learner.js.map +1 -0
  208. package/dist/services/scanner.d.ts +3 -0
  209. package/dist/services/scanner.d.ts.map +1 -0
  210. package/dist/services/scanner.js +54 -0
  211. package/dist/services/scanner.js.map +1 -0
  212. package/dist/utils/errors.d.ts +15 -0
  213. package/dist/utils/errors.d.ts.map +1 -0
  214. package/dist/utils/errors.js +27 -0
  215. package/dist/utils/errors.js.map +1 -0
  216. package/dist/utils/file.d.ts +7 -0
  217. package/dist/utils/file.d.ts.map +1 -0
  218. package/dist/utils/file.js +32 -0
  219. package/dist/utils/file.js.map +1 -0
  220. package/dist/utils/logger.d.ts +6 -0
  221. package/dist/utils/logger.d.ts.map +1 -0
  222. package/dist/utils/logger.js +17 -0
  223. package/dist/utils/logger.js.map +1 -0
  224. package/dist/utils/path.d.ts +6 -0
  225. package/dist/utils/path.d.ts.map +1 -0
  226. package/dist/utils/path.js +14 -0
  227. package/dist/utils/path.js.map +1 -0
  228. package/docs/planning/memory-lane.md +83 -0
  229. package/package.json +64 -0
  230. package/packaging/linux/aicgen.spec +23 -0
  231. package/packaging/linux/control +9 -0
  232. package/packaging/macos/scripts/postinstall +12 -0
  233. package/packaging/windows/setup.nsi +92 -0
  234. package/planning/BRANDING-SUMMARY.md +194 -0
  235. package/planning/BRANDING.md +174 -0
  236. package/planning/BUILD.md +186 -0
  237. package/planning/CHUNK-IMPLEMENTATION-PLAN.md +87 -0
  238. package/planning/CHUNK-TAXONOMY.md +375 -0
  239. package/planning/CHUNKS-COMPLETE.md +382 -0
  240. package/planning/DESIGN.md +313 -0
  241. package/planning/DYNAMIC-GUIDELINES-DESIGN.md +265 -0
  242. package/planning/ENTERPRISE-UX-COMPLETE.md +281 -0
  243. package/planning/IMPLEMENTATION-PLAN.md +20 -0
  244. package/planning/PHASE1-COMPLETE.md +211 -0
  245. package/planning/PHASE2-COMPLETE.md +350 -0
  246. package/planning/PHASE3-COMPLETE.md +399 -0
  247. package/planning/PHASE4-COMPLETE.md +361 -0
  248. package/planning/PHASE4.5-CHUNKS.md +462 -0
  249. package/planning/STRUCTURE.md +170 -0
  250. package/scripts/add-categories.ts +87 -0
  251. package/scripts/build-binary.ts +46 -0
  252. package/scripts/embed-data.ts +105 -0
  253. package/scripts/generate-version.ts +150 -0
  254. package/scripts/test-decompress.ts +27 -0
  255. package/scripts/test-extract.ts +31 -0
  256. package/src/__tests__/services/assistant-file-writer.test.ts +400 -0
  257. package/src/__tests__/services/guideline-loader.test.ts +281 -0
  258. package/src/__tests__/services/tarball-extraction.test.ts +125 -0
  259. package/src/commands/add-guideline.ts +296 -0
  260. package/src/commands/clear.ts +61 -0
  261. package/src/commands/guideline-selector.ts +123 -0
  262. package/src/commands/init.ts +645 -0
  263. package/src/commands/quick-add.ts +586 -0
  264. package/src/commands/remove-guideline.ts +152 -0
  265. package/src/commands/stats.ts +49 -0
  266. package/src/commands/update.ts +240 -0
  267. package/src/config.ts +82 -0
  268. package/src/embedded-data.ts +1492 -0
  269. package/src/index.ts +67 -0
  270. package/src/models/profile.ts +24 -0
  271. package/src/models/project.ts +43 -0
  272. package/src/services/assistant-file-writer.ts +612 -0
  273. package/src/services/config-generator.ts +150 -0
  274. package/src/services/config-manager.ts +70 -0
  275. package/src/services/data-source.ts +248 -0
  276. package/src/services/first-run-init.ts +148 -0
  277. package/src/services/guideline-loader.ts +311 -0
  278. package/src/services/hook-generator.ts +178 -0
  279. package/src/services/subagent-generator.ts +310 -0
  280. package/src/utils/banner.ts +66 -0
  281. package/src/utils/errors.ts +27 -0
  282. package/src/utils/file.ts +67 -0
  283. package/src/utils/formatting.ts +172 -0
  284. package/src/utils/logger.ts +89 -0
  285. package/src/utils/path.ts +17 -0
  286. package/src/utils/wizard-state.ts +132 -0
  287. package/tsconfig.json +25 -0
@@ -0,0 +1,324 @@
1
+ # Performance Basics
2
+
3
+ ## Choose the Right Data Structure
4
+
5
+ Different data structures have different speeds for different operations.
6
+
7
+ ### Arrays vs Objects vs Maps
8
+
9
+ ```pseudocode
10
+ // ❌ Slow: Looking up in array (O(n))
11
+ users = [
12
+ { id: 1, name: 'Alice' },
13
+ { id: 2, name: 'Bob' },
14
+ // ... 1000 more
15
+ ]
16
+ user = users.find(u => u.id == 500) // Checks 500 items
17
+
18
+ // ✅ Fast: Looking up in Map (O(1))
19
+ users = Map()
20
+ users.set(1, { id: 1, name: 'Alice' })
21
+ users.set(2, { id: 2, name: 'Bob' })
22
+
23
+ user = users.get(500) // Instant lookup
24
+ ```
25
+
26
+ ### Arrays vs Sets
27
+
28
+ ```pseudocode
29
+ // ❌ Slow: Checking if item exists in array
30
+ items = [1, 2, 3, 4, 5, ... 1000 more]
31
+ if items.contains(500): // Checks every item
32
+
33
+ // ✅ Fast: Checking if item exists in Set
34
+ items = Set([1, 2, 3, 4, 5, ... 1000 more])
35
+ if items.has(500): // Instant check
36
+ ```
37
+
38
+ ### When to Use Each
39
+
40
+ | Data Structure | Good For |
41
+ |----------------|----------|
42
+ | **Array/List** | Ordered items, iteration |
43
+ | **Object/Dict** | Key-value pairs (string keys) |
44
+ | **Map** | Key-value pairs (any type keys), frequent lookups |
45
+ | **Set** | Unique values, membership checks |
46
+
47
+ ## Avoid N+1 Queries
48
+
49
+ One of the most common performance problems.
50
+
51
+ ```pseudocode
52
+ // ❌ BAD: N+1 queries (1 + N database calls)
53
+ orders = database.query("SELECT * FROM orders")
54
+
55
+ for each order in orders:
56
+ // Separate query for EACH order! 😱
57
+ customer = database.query(
58
+ "SELECT * FROM customers WHERE id = ?",
59
+ [order.customer_id]
60
+ )
61
+ order.customer = customer
62
+ // If 100 orders = 101 database calls!
63
+
64
+ // ✅ GOOD: Single query with JOIN
65
+ ordersWithCustomers = database.query("
66
+ SELECT
67
+ orders.*,
68
+ customers.name as customer_name,
69
+ customers.email as customer_email
70
+ FROM orders
71
+ JOIN customers ON orders.customer_id = customers.id
72
+ ")
73
+ // Only 1 database call!
74
+ ```
75
+
76
+ ## Don't Load What You Don't Need
77
+
78
+ ```pseudocode
79
+ // ❌ Bad: Fetching entire object when you only need one field
80
+ user = database.query("SELECT * FROM users WHERE id = ?", [id])
81
+ print(user.email)
82
+
83
+ // ✅ Good: Fetch only what you need
84
+ result = database.query(
85
+ "SELECT email FROM users WHERE id = ?",
86
+ [id]
87
+ )
88
+ print(result.email)
89
+
90
+ // ❌ Bad: Loading all records
91
+ users = database.query("SELECT * FROM users")
92
+
93
+ // ✅ Good: Add LIMIT
94
+ users = database.query("SELECT * FROM users LIMIT 100")
95
+ ```
96
+
97
+ ## Use Async for I/O Operations
98
+
99
+ Don't block the program waiting for slow operations.
100
+
101
+ ```pseudocode
102
+ // ❌ Slow: Blocking operations (synchronous)
103
+ file1 = readFileSync("file1.txt")
104
+ file2 = readFileSync("file2.txt")
105
+ file3 = readFileSync("file3.txt")
106
+ // Total: 300ms (100ms each, one after another)
107
+
108
+ // ✅ Fast: Async operations (parallel)
109
+ files = await Promise.all([
110
+ readFile("file1.txt"),
111
+ readFile("file2.txt"),
112
+ readFile("file3.txt")
113
+ ])
114
+ // Total: 100ms (all at once)
115
+ ```
116
+
117
+ ## Avoid Unnecessary Work in Loops
118
+
119
+ ```pseudocode
120
+ // ❌ Bad: Work done every iteration
121
+ for i in 0 to items.length:
122
+ total = calculateTotal(items) // Recalculated each time!
123
+ if items[i].price > total * 0.1:
124
+ // ...
125
+
126
+ // ✅ Good: Work done once
127
+ total = calculateTotal(items)
128
+ for i in 0 to items.length:
129
+ if items[i].price > total * 0.1:
130
+ // ...
131
+
132
+ // ❌ Bad: Array length calculated each time
133
+ for i in 0 to items.length:
134
+ // ...
135
+
136
+ // ✅ Good: Length cached (minor improvement)
137
+ len = items.length
138
+ for i in 0 to len:
139
+ // ...
140
+
141
+ // ✅ Best: Modern for-each loop
142
+ for each item in items:
143
+ // ...
144
+ ```
145
+
146
+ ## Index Your Database
147
+
148
+ Indexes make lookups fast, but slow down writes.
149
+
150
+ ```sql
151
+ -- Without index: Checks every row
152
+ SELECT * FROM users WHERE email = 'alice@example.com';
153
+ -- With 1 million users: ~1 second
154
+
155
+ -- Add index
156
+ CREATE INDEX idx_users_email ON users(email);
157
+
158
+ -- Now same query is instant
159
+ SELECT * FROM users WHERE email = 'alice@example.com';
160
+ -- With 1 million users: ~1 millisecond
161
+ ```
162
+
163
+ ### When to Add Indexes
164
+
165
+ - Columns used in WHERE clauses
166
+ - Columns used in JOIN conditions
167
+ - Columns used in ORDER BY
168
+
169
+ ```sql
170
+ -- Frequently queried
171
+ CREATE INDEX idx_orders_status ON orders(status);
172
+ CREATE INDEX idx_users_email ON users(email);
173
+
174
+ -- Used in joins
175
+ CREATE INDEX idx_orders_customer_id ON orders(customer_id);
176
+ ```
177
+
178
+ ## Cache Expensive Results
179
+
180
+ Don't recalculate the same thing repeatedly.
181
+
182
+ ```pseudocode
183
+ // ❌ Bad: Calculating every time
184
+ function getReport(userId):
185
+ data = expensiveCalculation(userId) // 5 seconds
186
+ return data
187
+
188
+ // Called 100 times = 500 seconds!
189
+
190
+ // ✅ Good: Cache results
191
+ cache = Map()
192
+
193
+ function getReport(userId):
194
+ if cache.has(userId):
195
+ return cache.get(userId) // Instant
196
+
197
+ data = expensiveCalculation(userId)
198
+ cache.set(userId, data)
199
+ return data
200
+
201
+ // First call: 5 seconds, next 99 calls: instant
202
+ ```
203
+
204
+ ## Batch Operations
205
+
206
+ Process multiple items together instead of one at a time.
207
+
208
+ ```pseudocode
209
+ // ❌ Bad: Individual database calls
210
+ for each user in users:
211
+ database.execute("INSERT INTO users (name) VALUES (?)", [user.name])
212
+ // 100 users = 100 database calls
213
+
214
+ // ✅ Good: Batch insert
215
+ database.execute("
216
+ INSERT INTO users (name)
217
+ VALUES " + users.map(u => "(?)").join(", "),
218
+ users.map(u => u.name)
219
+ )
220
+ // 100 users = 1 database call
221
+ ```
222
+
223
+ ## Profile Before Optimizing
224
+
225
+ Don't guess where the problem is - measure!
226
+
227
+ ```pseudocode
228
+ // Measure execution time
229
+ startTime = currentTime()
230
+ result = await slowOperation()
231
+ endTime = currentTime()
232
+ print("Operation took:", endTime - startTime, "ms")
233
+
234
+ // Measure specific parts
235
+ startDB = currentTime()
236
+ data = await database.query("...")
237
+ print("Database:", currentTime() - startDB, "ms")
238
+
239
+ startProcess = currentTime()
240
+ processed = processData(data)
241
+ print("Processing:", currentTime() - startProcess, "ms")
242
+ ```
243
+
244
+ ## Common Performance Mistakes
245
+
246
+ ### Mistake 1: Nested Loops with Database Queries
247
+
248
+ ```pseudocode
249
+ // ❌ TERRIBLE: Nested queries
250
+ for each user in users:
251
+ for each order in orders:
252
+ product = await database.query(
253
+ "SELECT * FROM products WHERE id = ?",
254
+ [order.product_id]
255
+ )
256
+ // 100 users × 50 orders = 5000 database calls!
257
+
258
+ // ✅ GOOD: Load all data first
259
+ products = await database.query("SELECT * FROM products")
260
+ productMap = Map()
261
+ for each p in products:
262
+ productMap.set(p.id, p)
263
+
264
+ for each user in users:
265
+ for each order in orders:
266
+ product = productMap.get(order.product_id) // Instant
267
+ ```
268
+
269
+ ### Mistake 2: Loading Everything into Memory
270
+
271
+ ```pseudocode
272
+ // ❌ Bad: Loading 1 million records
273
+ allUsers = await database.query("SELECT * FROM users")
274
+ // Crashes with out of memory!
275
+
276
+ // ✅ Good: Process in batches
277
+ BATCH_SIZE = 1000
278
+ offset = 0
279
+
280
+ while true:
281
+ users = await database.query(
282
+ "SELECT * FROM users LIMIT ? OFFSET ?",
283
+ [BATCH_SIZE, offset]
284
+ )
285
+
286
+ if users.length == 0:
287
+ break
288
+
289
+ await processUsers(users)
290
+ offset = offset + BATCH_SIZE
291
+ ```
292
+
293
+ ### Mistake 3: Not Using Indexes
294
+
295
+ ```sql
296
+ -- ❌ Slow: No index on email column
297
+ SELECT * FROM users WHERE email = 'alice@example.com';
298
+ -- 1 million rows: ~2 seconds
299
+
300
+ -- ✅ Fast: Add index
301
+ CREATE INDEX idx_users_email ON users(email);
302
+ -- Same query: ~2 milliseconds
303
+ ```
304
+
305
+ ## Quick Performance Checklist
306
+
307
+ - [ ] Use Map/Set for lookups instead of Array
308
+ - [ ] Avoid N+1 queries (use JOINs)
309
+ - [ ] Add database indexes on frequently queried columns
310
+ - [ ] Don't load all records (use LIMIT)
311
+ - [ ] Cache expensive calculations
312
+ - [ ] Run independent operations in parallel
313
+ - [ ] Move work outside of loops
314
+ - [ ] Batch database operations
315
+ - [ ] Profile before optimizing
316
+
317
+ ## When to Optimize
318
+
319
+ 1. **Measure first** - Is there actually a problem?
320
+ 2. **Find the bottleneck** - What's slow?
321
+ 3. **Fix the biggest problem** - Don't waste time on small gains
322
+ 4. **Measure again** - Did it help?
323
+
324
+ Don't optimize prematurely - write clear code first, optimize when needed!
@@ -0,0 +1,68 @@
1
+ # Caching Strategies
2
+
3
+ ## Cache Patterns
4
+
5
+ ### Cache-Aside (Lazy Loading)
6
+ ```typescript
7
+ async function getUser(id: string): Promise<User> {
8
+ const cached = await cache.get(`user:${id}`);
9
+ if (cached) return cached;
10
+
11
+ const user = await db.findUser(id);
12
+ await cache.set(`user:${id}`, user, { ttl: 3600 });
13
+ return user;
14
+ }
15
+ ```
16
+
17
+ ### Write-Through
18
+ ```typescript
19
+ async function updateUser(user: User): Promise<void> {
20
+ await db.saveUser(user);
21
+ await cache.set(`user:${user.id}`, user);
22
+ }
23
+ ```
24
+
25
+ ### Write-Behind (Write-Back)
26
+ ```typescript
27
+ async function updateUser(user: User): Promise<void> {
28
+ await cache.set(`user:${user.id}`, user);
29
+ await queue.add('sync-to-db', { user }); // Async persistence
30
+ }
31
+ ```
32
+
33
+ ## Cache Invalidation
34
+
35
+ ```typescript
36
+ // Time-based expiration
37
+ await cache.set('key', value, { ttl: 3600 });
38
+
39
+ // Event-based invalidation
40
+ eventBus.on('user.updated', async (userId) => {
41
+ await cache.delete(`user:${userId}`);
42
+ });
43
+
44
+ // Pattern-based invalidation
45
+ await cache.deleteByPattern('user:*');
46
+ ```
47
+
48
+ ## HTTP Caching
49
+
50
+ ```typescript
51
+ // Cache-Control headers
52
+ res.setHeader('Cache-Control', 'public, max-age=3600');
53
+ res.setHeader('ETag', etag(content));
54
+
55
+ // Conditional requests
56
+ if (req.headers['if-none-match'] === currentEtag) {
57
+ return res.status(304).end();
58
+ }
59
+ ```
60
+
61
+ ## Best Practices
62
+
63
+ - Cache at appropriate layers (CDN, app, DB)
64
+ - Use consistent cache keys
65
+ - Set appropriate TTLs
66
+ - Monitor cache hit rates
67
+ - Plan for cache failures (fallback to source)
68
+ - Avoid caching sensitive data
@@ -0,0 +1,152 @@
1
+ # Caching Strategies
2
+
3
+ ## In-Memory Caching
4
+
5
+ ```typescript
6
+ class Cache<T> {
7
+ private cache = new Map<string, { value: T; expiry: number }>();
8
+
9
+ set(key: string, value: T, ttlMs: number = 60000): void {
10
+ this.cache.set(key, {
11
+ value,
12
+ expiry: Date.now() + ttlMs
13
+ });
14
+ }
15
+
16
+ get(key: string): T | null {
17
+ const item = this.cache.get(key);
18
+ if (!item) return null;
19
+
20
+ if (Date.now() > item.expiry) {
21
+ this.cache.delete(key);
22
+ return null;
23
+ }
24
+
25
+ return item.value;
26
+ }
27
+ }
28
+
29
+ // Usage
30
+ const userCache = new Cache<User>();
31
+
32
+ async function getUser(id: string): Promise<User> {
33
+ const cached = userCache.get(id);
34
+ if (cached) return cached;
35
+
36
+ const user = await db.findUser(id);
37
+ userCache.set(id, user, 300000); // 5 minutes
38
+ return user;
39
+ }
40
+ ```
41
+
42
+ ## Redis Caching
43
+
44
+ ```typescript
45
+ import Redis from 'ioredis';
46
+
47
+ const redis = new Redis();
48
+
49
+ async function getCachedUser(id: string): Promise<User | null> {
50
+ const cached = await redis.get(`user:${id}`);
51
+ if (cached) return JSON.parse(cached);
52
+
53
+ const user = await db.findUser(id);
54
+ await redis.setex(`user:${id}`, 300, JSON.stringify(user)); // 5 min TTL
55
+ return user;
56
+ }
57
+
58
+ // Cache invalidation on update
59
+ async function updateUser(id: string, data: Partial<User>) {
60
+ const user = await db.updateUser(id, data);
61
+ await redis.del(`user:${id}`); // Invalidate cache
62
+ return user;
63
+ }
64
+ ```
65
+
66
+ ## HTTP Caching
67
+
68
+ ```typescript
69
+ // Cache-Control headers
70
+ app.get('/api/products', (req, res) => {
71
+ res.set('Cache-Control', 'public, max-age=300'); // 5 minutes
72
+ res.json(products);
73
+ });
74
+
75
+ // ETag for conditional requests
76
+ app.get('/api/user/:id', async (req, res) => {
77
+ const user = await getUser(req.params.id);
78
+ const etag = generateETag(user);
79
+
80
+ res.set('ETag', etag);
81
+
82
+ if (req.headers['if-none-match'] === etag) {
83
+ return res.status(304).end(); // Not Modified
84
+ }
85
+
86
+ res.json(user);
87
+ });
88
+ ```
89
+
90
+ ## Cache-Aside Pattern
91
+
92
+ ```typescript
93
+ // Also called "lazy loading"
94
+ async function getProduct(id: string): Promise<Product> {
95
+ // 1. Check cache
96
+ const cached = await redis.get(`product:${id}`);
97
+ if (cached) return JSON.parse(cached);
98
+
99
+ // 2. Cache miss - load from database
100
+ const product = await db.findProduct(id);
101
+
102
+ // 3. Store in cache
103
+ await redis.setex(`product:${id}`, 600, JSON.stringify(product));
104
+
105
+ return product;
106
+ }
107
+ ```
108
+
109
+ ## Memoization
110
+
111
+ ```typescript
112
+ const memoize = <T extends (...args: any[]) => any>(fn: T): T => {
113
+ const cache = new Map<string, ReturnType<T>>();
114
+
115
+ return ((...args: any[]) => {
116
+ const key = JSON.stringify(args);
117
+ if (cache.has(key)) return cache.get(key);
118
+
119
+ const result = fn(...args);
120
+ cache.set(key, result);
121
+ return result;
122
+ }) as T;
123
+ };
124
+
125
+ // Cache expensive computations
126
+ const calculateDiscount = memoize((price: number, tier: string) => {
127
+ // Complex calculation
128
+ return result;
129
+ });
130
+ ```
131
+
132
+ ## Cache Invalidation Strategies
133
+
134
+ ```typescript
135
+ // Time-based expiry
136
+ await redis.setex(key, 300, value); // Expires after 5 minutes
137
+
138
+ // Event-based invalidation
139
+ async function updateProduct(id: string, data: ProductUpdate) {
140
+ await db.updateProduct(id, data);
141
+ await redis.del(`product:${id}`);
142
+ await redis.del('products:list'); // Invalidate list cache too
143
+ }
144
+
145
+ // Cache warming
146
+ async function warmCache() {
147
+ const popularProducts = await db.getMostViewed(100);
148
+ for (const product of popularProducts) {
149
+ await redis.setex(`product:${product.id}`, 3600, JSON.stringify(product));
150
+ }
151
+ }
152
+ ```
@@ -0,0 +1,8 @@
1
+ # Performance Guidelines
2
+
3
+ This directory contains performance optimization patterns.
4
+
5
+ ## Available Chunks
6
+
7
+ - **caching.md** - In-memory, Redis, HTTP caching, memoization
8
+ - **async.md** - Parallel execution, batching, debouncing, throttling
@@ -0,0 +1,52 @@
1
+ # Code Review Practices
2
+
3
+ ## Review Checklist
4
+
5
+ - [ ] Code follows project style guidelines
6
+ - [ ] No obvious bugs or logic errors
7
+ - [ ] Error handling is appropriate
8
+ - [ ] Tests cover new functionality
9
+ - [ ] No security vulnerabilities introduced
10
+ - [ ] Performance implications considered
11
+ - [ ] Documentation updated if needed
12
+
13
+ ## Giving Feedback
14
+
15
+ **Good:**
16
+ ```
17
+ Consider using `Array.find()` here instead of `filter()[0]` -
18
+ it's more readable and stops at the first match.
19
+ ```
20
+
21
+ **Bad:**
22
+ ```
23
+ This is wrong.
24
+ ```
25
+
26
+ ## PR Description Template
27
+
28
+ ```markdown
29
+ ## Summary
30
+ Brief description of changes
31
+
32
+ ## Changes
33
+ - Added X feature
34
+ - Fixed Y bug
35
+ - Refactored Z
36
+
37
+ ## Testing
38
+ - [ ] Unit tests added
39
+ - [ ] Manual testing performed
40
+
41
+ ## Screenshots (if UI changes)
42
+ ```
43
+
44
+ ## Best Practices
45
+
46
+ - Review promptly (within 24 hours)
47
+ - Focus on logic and design, not style (use linters)
48
+ - Ask questions rather than make demands
49
+ - Praise good solutions
50
+ - Keep PRs small and focused
51
+ - Use "nitpick:" prefix for minor suggestions
52
+ - Approve with minor comments when appropriate