compact-agent 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (324) hide show
  1. package/README.md +394 -0
  2. package/bin/anycode.js +2 -0
  3. package/bin/crowcoder.js +19 -0
  4. package/bin/ecc-hooks.cjs +138 -0
  5. package/dist/agents.d.ts +17 -0
  6. package/dist/agents.js +1603 -0
  7. package/dist/agents.js.map +1 -0
  8. package/dist/api.d.ts +16 -0
  9. package/dist/api.js +115 -0
  10. package/dist/api.js.map +1 -0
  11. package/dist/autonomous-loops.d.ts +108 -0
  12. package/dist/autonomous-loops.js +526 -0
  13. package/dist/autonomous-loops.js.map +1 -0
  14. package/dist/codemaps.d.ts +53 -0
  15. package/dist/codemaps.js +325 -0
  16. package/dist/codemaps.js.map +1 -0
  17. package/dist/compaction.d.ts +30 -0
  18. package/dist/compaction.js +125 -0
  19. package/dist/compaction.js.map +1 -0
  20. package/dist/config.d.ts +5 -0
  21. package/dist/config.js +79 -0
  22. package/dist/config.js.map +1 -0
  23. package/dist/content-engine.d.ts +97 -0
  24. package/dist/content-engine.js +721 -0
  25. package/dist/content-engine.js.map +1 -0
  26. package/dist/cost-tracker.d.ts +49 -0
  27. package/dist/cost-tracker.js +150 -0
  28. package/dist/cost-tracker.js.map +1 -0
  29. package/dist/counter-button.d.ts +35 -0
  30. package/dist/counter-button.js +48 -0
  31. package/dist/counter-button.js.map +1 -0
  32. package/dist/counter.d.ts +21 -0
  33. package/dist/counter.js +31 -0
  34. package/dist/counter.js.map +1 -0
  35. package/dist/coverage.d.ts +23 -0
  36. package/dist/coverage.js +215 -0
  37. package/dist/coverage.js.map +1 -0
  38. package/dist/docs-sync.d.ts +23 -0
  39. package/dist/docs-sync.js +266 -0
  40. package/dist/docs-sync.js.map +1 -0
  41. package/dist/ecc.d.ts +41 -0
  42. package/dist/ecc.js +644 -0
  43. package/dist/ecc.js.map +1 -0
  44. package/dist/evaluation.d.ts +24 -0
  45. package/dist/evaluation.js +412 -0
  46. package/dist/evaluation.js.map +1 -0
  47. package/dist/export.d.ts +22 -0
  48. package/dist/export.js +109 -0
  49. package/dist/export.js.map +1 -0
  50. package/dist/git-workflow.d.ts +22 -0
  51. package/dist/git-workflow.js +197 -0
  52. package/dist/git-workflow.js.map +1 -0
  53. package/dist/hook-controls.d.ts +34 -0
  54. package/dist/hook-controls.js +90 -0
  55. package/dist/hook-controls.js.map +1 -0
  56. package/dist/hooks.d.ts +30 -0
  57. package/dist/hooks.js +130 -0
  58. package/dist/hooks.js.map +1 -0
  59. package/dist/html-parser.d.ts +18 -0
  60. package/dist/html-parser.js +101 -0
  61. package/dist/html-parser.js.map +1 -0
  62. package/dist/index.d.ts +12 -0
  63. package/dist/index.js +1230 -0
  64. package/dist/index.js.map +1 -0
  65. package/dist/learning.d.ts +35 -0
  66. package/dist/learning.js +238 -0
  67. package/dist/learning.js.map +1 -0
  68. package/dist/login.d.ts +37 -0
  69. package/dist/login.js +191 -0
  70. package/dist/login.js.map +1 -0
  71. package/dist/memory.d.ts +39 -0
  72. package/dist/memory.js +183 -0
  73. package/dist/memory.js.map +1 -0
  74. package/dist/model-router.d.ts +23 -0
  75. package/dist/model-router.js +145 -0
  76. package/dist/model-router.js.map +1 -0
  77. package/dist/modes.d.ts +17 -0
  78. package/dist/modes.js +217 -0
  79. package/dist/modes.js.map +1 -0
  80. package/dist/orchestration.d.ts +37 -0
  81. package/dist/orchestration.js +139 -0
  82. package/dist/orchestration.js.map +1 -0
  83. package/dist/package-detect.d.ts +36 -0
  84. package/dist/package-detect.js +529 -0
  85. package/dist/package-detect.js.map +1 -0
  86. package/dist/permissions.d.ts +25 -0
  87. package/dist/permissions.js +50 -0
  88. package/dist/permissions.js.map +1 -0
  89. package/dist/pm2-manager.d.ts +40 -0
  90. package/dist/pm2-manager.js +127 -0
  91. package/dist/pm2-manager.js.map +1 -0
  92. package/dist/query.d.ts +15 -0
  93. package/dist/query.js +278 -0
  94. package/dist/query.js.map +1 -0
  95. package/dist/refactor.d.ts +22 -0
  96. package/dist/refactor.js +226 -0
  97. package/dist/refactor.js.map +1 -0
  98. package/dist/retry.d.ts +20 -0
  99. package/dist/retry.js +88 -0
  100. package/dist/retry.js.map +1 -0
  101. package/dist/rules.d.ts +34 -0
  102. package/dist/rules.js +942 -0
  103. package/dist/rules.js.map +1 -0
  104. package/dist/schema.d.ts +23 -0
  105. package/dist/schema.js +12 -0
  106. package/dist/schema.js.map +1 -0
  107. package/dist/search-first.d.ts +17 -0
  108. package/dist/search-first.js +301 -0
  109. package/dist/search-first.js.map +1 -0
  110. package/dist/security.d.ts +10 -0
  111. package/dist/security.js +145 -0
  112. package/dist/security.js.map +1 -0
  113. package/dist/sessions.d.ts +21 -0
  114. package/dist/sessions.js +112 -0
  115. package/dist/sessions.js.map +1 -0
  116. package/dist/skill-create.d.ts +38 -0
  117. package/dist/skill-create.js +389 -0
  118. package/dist/skill-create.js.map +1 -0
  119. package/dist/skills.d.ts +34 -0
  120. package/dist/skills.js +161 -0
  121. package/dist/skills.js.map +1 -0
  122. package/dist/strategic-compaction.d.ts +24 -0
  123. package/dist/strategic-compaction.js +144 -0
  124. package/dist/strategic-compaction.js.map +1 -0
  125. package/dist/system-prompt.d.ts +3 -0
  126. package/dist/system-prompt.js +101 -0
  127. package/dist/system-prompt.js.map +1 -0
  128. package/dist/theme.d.ts +60 -0
  129. package/dist/theme.js +220 -0
  130. package/dist/theme.js.map +1 -0
  131. package/dist/tools/bash.d.ts +2 -0
  132. package/dist/tools/bash.js +49 -0
  133. package/dist/tools/bash.js.map +1 -0
  134. package/dist/tools/edit.d.ts +2 -0
  135. package/dist/tools/edit.js +76 -0
  136. package/dist/tools/edit.js.map +1 -0
  137. package/dist/tools/glob.d.ts +2 -0
  138. package/dist/tools/glob.js +54 -0
  139. package/dist/tools/glob.js.map +1 -0
  140. package/dist/tools/grep.d.ts +2 -0
  141. package/dist/tools/grep.js +64 -0
  142. package/dist/tools/grep.js.map +1 -0
  143. package/dist/tools/index.d.ts +5 -0
  144. package/dist/tools/index.js +27 -0
  145. package/dist/tools/index.js.map +1 -0
  146. package/dist/tools/list-dir.d.ts +2 -0
  147. package/dist/tools/list-dir.js +51 -0
  148. package/dist/tools/list-dir.js.map +1 -0
  149. package/dist/tools/read.d.ts +2 -0
  150. package/dist/tools/read.js +56 -0
  151. package/dist/tools/read.js.map +1 -0
  152. package/dist/tools/types.d.ts +45 -0
  153. package/dist/tools/types.js +2 -0
  154. package/dist/tools/types.js.map +1 -0
  155. package/dist/tools/web-fetch.d.ts +2 -0
  156. package/dist/tools/web-fetch.js +41 -0
  157. package/dist/tools/web-fetch.js.map +1 -0
  158. package/dist/tools/web-search.d.ts +27 -0
  159. package/dist/tools/web-search.js +139 -0
  160. package/dist/tools/web-search.js.map +1 -0
  161. package/dist/tools/write.d.ts +2 -0
  162. package/dist/tools/write.js +36 -0
  163. package/dist/tools/write.js.map +1 -0
  164. package/dist/types.d.ts +28 -0
  165. package/dist/types.js +57 -0
  166. package/dist/types.js.map +1 -0
  167. package/dist/users.d.ts +51 -0
  168. package/dist/users.js +193 -0
  169. package/dist/users.js.map +1 -0
  170. package/dist/verification.d.ts +73 -0
  171. package/dist/verification.js +269 -0
  172. package/dist/verification.js.map +1 -0
  173. package/dist/walkthrough.d.ts +10 -0
  174. package/dist/walkthrough.js +121 -0
  175. package/dist/walkthrough.js.map +1 -0
  176. package/package.json +58 -0
  177. package/resources/ecc/agents/architect.json +16 -0
  178. package/resources/ecc/agents/architect.md +212 -0
  179. package/resources/ecc/agents/build-error-resolver.json +17 -0
  180. package/resources/ecc/agents/build-error-resolver.md +116 -0
  181. package/resources/ecc/agents/chief-of-staff.json +17 -0
  182. package/resources/ecc/agents/chief-of-staff.md +153 -0
  183. package/resources/ecc/agents/code-reviewer.json +16 -0
  184. package/resources/ecc/agents/code-reviewer.md +238 -0
  185. package/resources/ecc/agents/database-reviewer.json +16 -0
  186. package/resources/ecc/agents/database-reviewer.md +92 -0
  187. package/resources/ecc/agents/doc-updater.json +16 -0
  188. package/resources/ecc/agents/doc-updater.md +108 -0
  189. package/resources/ecc/agents/e2e-runner.json +17 -0
  190. package/resources/ecc/agents/e2e-runner.md +109 -0
  191. package/resources/ecc/agents/go-build-resolver.json +17 -0
  192. package/resources/ecc/agents/go-build-resolver.md +96 -0
  193. package/resources/ecc/agents/go-reviewer.json +16 -0
  194. package/resources/ecc/agents/go-reviewer.md +77 -0
  195. package/resources/ecc/agents/harness-optimizer.json +15 -0
  196. package/resources/ecc/agents/harness-optimizer.md +34 -0
  197. package/resources/ecc/agents/loop-operator.json +16 -0
  198. package/resources/ecc/agents/loop-operator.md +36 -0
  199. package/resources/ecc/agents/planner.json +15 -0
  200. package/resources/ecc/agents/planner.md +212 -0
  201. package/resources/ecc/agents/python-reviewer.json +16 -0
  202. package/resources/ecc/agents/python-reviewer.md +99 -0
  203. package/resources/ecc/agents/refactor-cleaner.json +17 -0
  204. package/resources/ecc/agents/refactor-cleaner.md +87 -0
  205. package/resources/ecc/agents/security-reviewer.json +16 -0
  206. package/resources/ecc/agents/security-reviewer.md +109 -0
  207. package/resources/ecc/agents/tdd-guide.json +17 -0
  208. package/resources/ecc/agents/tdd-guide.md +93 -0
  209. package/resources/ecc/commands/add-language-rules.md +39 -0
  210. package/resources/ecc/commands/database-migration.md +36 -0
  211. package/resources/ecc/commands/feature-development.md +38 -0
  212. package/resources/ecc/prompts/build-fix.prompt.md +47 -0
  213. package/resources/ecc/prompts/code-review.prompt.md +56 -0
  214. package/resources/ecc/prompts/plan.prompt.md +52 -0
  215. package/resources/ecc/prompts/refactor.prompt.md +50 -0
  216. package/resources/ecc/prompts/security-review.prompt.md +70 -0
  217. package/resources/ecc/prompts/tdd.prompt.md +47 -0
  218. package/resources/ecc/rules/common-agents.md +53 -0
  219. package/resources/ecc/rules/common-coding-style.md +52 -0
  220. package/resources/ecc/rules/common-development-workflow.md +33 -0
  221. package/resources/ecc/rules/common-git-workflow.md +28 -0
  222. package/resources/ecc/rules/common-hooks.md +34 -0
  223. package/resources/ecc/rules/common-patterns.md +35 -0
  224. package/resources/ecc/rules/common-performance.md +59 -0
  225. package/resources/ecc/rules/common-security.md +33 -0
  226. package/resources/ecc/rules/common-testing.md +33 -0
  227. package/resources/ecc/rules/golang-coding-style.md +31 -0
  228. package/resources/ecc/rules/golang-hooks.md +16 -0
  229. package/resources/ecc/rules/golang-patterns.md +44 -0
  230. package/resources/ecc/rules/golang-security.md +33 -0
  231. package/resources/ecc/rules/golang-testing.md +30 -0
  232. package/resources/ecc/rules/kotlin-coding-style.md +39 -0
  233. package/resources/ecc/rules/kotlin-hooks.md +16 -0
  234. package/resources/ecc/rules/kotlin-patterns.md +50 -0
  235. package/resources/ecc/rules/kotlin-security.md +58 -0
  236. package/resources/ecc/rules/kotlin-testing.md +38 -0
  237. package/resources/ecc/rules/php-coding-style.md +25 -0
  238. package/resources/ecc/rules/php-hooks.md +21 -0
  239. package/resources/ecc/rules/php-patterns.md +23 -0
  240. package/resources/ecc/rules/php-security.md +24 -0
  241. package/resources/ecc/rules/php-testing.md +26 -0
  242. package/resources/ecc/rules/python-coding-style.md +42 -0
  243. package/resources/ecc/rules/python-hooks.md +19 -0
  244. package/resources/ecc/rules/python-patterns.md +39 -0
  245. package/resources/ecc/rules/python-security.md +30 -0
  246. package/resources/ecc/rules/python-testing.md +38 -0
  247. package/resources/ecc/rules/swift-coding-style.md +47 -0
  248. package/resources/ecc/rules/swift-hooks.md +20 -0
  249. package/resources/ecc/rules/swift-patterns.md +66 -0
  250. package/resources/ecc/rules/swift-security.md +33 -0
  251. package/resources/ecc/rules/swift-testing.md +45 -0
  252. package/resources/ecc/rules/typescript-coding-style.md +63 -0
  253. package/resources/ecc/rules/typescript-hooks.md +20 -0
  254. package/resources/ecc/rules/typescript-patterns.md +50 -0
  255. package/resources/ecc/rules/typescript-security.md +26 -0
  256. package/resources/ecc/rules/typescript-testing.md +16 -0
  257. package/resources/ecc/skills/agent-introspection-debugging/SKILL.md +152 -0
  258. package/resources/ecc/skills/agent-introspection-debugging/agents/openai.yaml +7 -0
  259. package/resources/ecc/skills/agent-sort/SKILL.md +214 -0
  260. package/resources/ecc/skills/agent-sort/agents/openai.yaml +7 -0
  261. package/resources/ecc/skills/api-design/SKILL.md +522 -0
  262. package/resources/ecc/skills/api-design/agents/openai.yaml +7 -0
  263. package/resources/ecc/skills/article-writing/SKILL.md +78 -0
  264. package/resources/ecc/skills/article-writing/agents/openai.yaml +7 -0
  265. package/resources/ecc/skills/backend-patterns/SKILL.md +597 -0
  266. package/resources/ecc/skills/backend-patterns/agents/openai.yaml +7 -0
  267. package/resources/ecc/skills/brand-voice/SKILL.md +96 -0
  268. package/resources/ecc/skills/brand-voice/agents/openai.yaml +7 -0
  269. package/resources/ecc/skills/brand-voice/references/voice-profile-schema.md +55 -0
  270. package/resources/ecc/skills/bun-runtime/SKILL.md +83 -0
  271. package/resources/ecc/skills/bun-runtime/agents/openai.yaml +7 -0
  272. package/resources/ecc/skills/coding-standards/SKILL.md +548 -0
  273. package/resources/ecc/skills/coding-standards/agents/openai.yaml +7 -0
  274. package/resources/ecc/skills/content-engine/SKILL.md +130 -0
  275. package/resources/ecc/skills/content-engine/agents/openai.yaml +7 -0
  276. package/resources/ecc/skills/crosspost/SKILL.md +110 -0
  277. package/resources/ecc/skills/crosspost/agents/openai.yaml +7 -0
  278. package/resources/ecc/skills/deep-research/SKILL.md +154 -0
  279. package/resources/ecc/skills/deep-research/agents/openai.yaml +7 -0
  280. package/resources/ecc/skills/dmux-workflows/SKILL.md +143 -0
  281. package/resources/ecc/skills/dmux-workflows/agents/openai.yaml +7 -0
  282. package/resources/ecc/skills/documentation-lookup/SKILL.md +89 -0
  283. package/resources/ecc/skills/documentation-lookup/agents/openai.yaml +7 -0
  284. package/resources/ecc/skills/e2e-testing/SKILL.md +325 -0
  285. package/resources/ecc/skills/e2e-testing/agents/openai.yaml +7 -0
  286. package/resources/ecc/skills/eval-harness/SKILL.md +235 -0
  287. package/resources/ecc/skills/eval-harness/agents/openai.yaml +7 -0
  288. package/resources/ecc/skills/everything-claude-code/SKILL.md +442 -0
  289. package/resources/ecc/skills/everything-claude-code/agents/openai.yaml +7 -0
  290. package/resources/ecc/skills/exa-search/SKILL.md +169 -0
  291. package/resources/ecc/skills/exa-search/agents/openai.yaml +7 -0
  292. package/resources/ecc/skills/fal-ai-media/SKILL.md +276 -0
  293. package/resources/ecc/skills/fal-ai-media/agents/openai.yaml +7 -0
  294. package/resources/ecc/skills/frontend-patterns/SKILL.md +647 -0
  295. package/resources/ecc/skills/frontend-patterns/agents/openai.yaml +7 -0
  296. package/resources/ecc/skills/frontend-slides/SKILL.md +183 -0
  297. package/resources/ecc/skills/frontend-slides/STYLE_PRESETS.md +330 -0
  298. package/resources/ecc/skills/frontend-slides/agents/openai.yaml +7 -0
  299. package/resources/ecc/skills/investor-materials/SKILL.md +95 -0
  300. package/resources/ecc/skills/investor-materials/agents/openai.yaml +7 -0
  301. package/resources/ecc/skills/investor-outreach/SKILL.md +90 -0
  302. package/resources/ecc/skills/investor-outreach/agents/openai.yaml +7 -0
  303. package/resources/ecc/skills/market-research/SKILL.md +74 -0
  304. package/resources/ecc/skills/market-research/agents/openai.yaml +7 -0
  305. package/resources/ecc/skills/mcp-server-patterns/SKILL.md +66 -0
  306. package/resources/ecc/skills/mcp-server-patterns/agents/openai.yaml +7 -0
  307. package/resources/ecc/skills/mle-workflow/SKILL.md +346 -0
  308. package/resources/ecc/skills/mle-workflow/agents/openai.yaml +7 -0
  309. package/resources/ecc/skills/nextjs-turbopack/SKILL.md +43 -0
  310. package/resources/ecc/skills/nextjs-turbopack/agents/openai.yaml +7 -0
  311. package/resources/ecc/skills/product-capability/SKILL.md +140 -0
  312. package/resources/ecc/skills/product-capability/agents/openai.yaml +7 -0
  313. package/resources/ecc/skills/security-review/SKILL.md +494 -0
  314. package/resources/ecc/skills/security-review/agents/openai.yaml +7 -0
  315. package/resources/ecc/skills/strategic-compact/SKILL.md +102 -0
  316. package/resources/ecc/skills/strategic-compact/agents/openai.yaml +7 -0
  317. package/resources/ecc/skills/tdd-workflow/SKILL.md +409 -0
  318. package/resources/ecc/skills/tdd-workflow/agents/openai.yaml +7 -0
  319. package/resources/ecc/skills/verification-loop/SKILL.md +125 -0
  320. package/resources/ecc/skills/verification-loop/agents/openai.yaml +7 -0
  321. package/resources/ecc/skills/video-editing/SKILL.md +307 -0
  322. package/resources/ecc/skills/video-editing/agents/openai.yaml +7 -0
  323. package/resources/ecc/skills/x-api/SKILL.md +229 -0
  324. package/resources/ecc/skills/x-api/agents/openai.yaml +7 -0
package/dist/rules.js ADDED
@@ -0,0 +1,942 @@
1
+ /**
2
+ * Rules engine — per-language coding standards.
3
+ * Loads rules from ~/.crowcoder/rules/ and injects into system prompt.
4
+ * Ships with built-in presets for common languages.
5
+ */
6
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import chalk from 'chalk';
9
+ import { getConfigDir } from './config.js';
10
+ const RULES_DIR = join(getConfigDir(), 'rules');
11
+ // ── Built-in rule presets ─────────────────────────────────
12
+ const BUILTIN_RULES = {
13
+ typescript: `# TypeScript Rules
14
+ - Use strict mode; enable all strict compiler options
15
+ - Prefer const over let; never use var
16
+ - Use explicit return types on exported functions
17
+ - Use interfaces for object shapes, types for unions/intersections
18
+ - Prefer readonly arrays and properties where possible
19
+ - Use nullish coalescing (??) over OR (||) for defaults
20
+ - Use optional chaining (?.) for deep property access
21
+ - Handle all Promise rejections — no floating promises
22
+ - Use template literals over string concatenation
23
+ - Use ESM imports (import/export), not CommonJS (require)
24
+ - File naming: kebab-case for files, PascalCase for components/classes
25
+ - Max file length: 300 lines — split if larger
26
+ - Prefer early returns over deeply nested conditionals`,
27
+ python: `# Python Rules
28
+ - Follow PEP 8 style guidelines
29
+ - Use type hints on all function signatures
30
+ - Use dataclasses or Pydantic for structured data
31
+ - Prefer f-strings over .format() or % formatting
32
+ - Use pathlib.Path instead of os.path for file operations
33
+ - Use context managers (with) for resource management
34
+ - Use list/dict/set comprehensions where readable
35
+ - Prefer enumerate() over range(len())
36
+ - Never use mutable default arguments (use None + factory)
37
+ - Use logging module, not print(), for non-user-facing output
38
+ - Max function length: 30 lines — extract if larger
39
+ - Write docstrings for all public functions (Google style)`,
40
+ go: `# Go Rules
41
+ - Follow Effective Go and Go Proverbs
42
+ - Use gofmt/goimports for formatting
43
+ - Handle every error — no _ for errors unless explicitly justified
44
+ - Use short variable declarations (:=) inside functions
45
+ - Keep interfaces small — 1-3 methods, defined where used
46
+ - Use context.Context as the first parameter for long-running ops
47
+ - Use table-driven tests
48
+ - Prefer returning errors over panicking
49
+ - Use defer for cleanup
50
+ - Package naming: short, lowercase, no underscores
51
+ - Avoid init() functions — prefer explicit initialization
52
+ - Use struct embedding for composition, not inheritance`,
53
+ rust: `# Rust Rules
54
+ - Follow Rust API Guidelines (RFC 430)
55
+ - Use clippy lints: #![warn(clippy::all)]
56
+ - Prefer &str over String for function parameters
57
+ - Use Result<T, E> for fallible operations, not panics
58
+ - Implement Display for error types
59
+ - Use iterators and combinators over manual loops where clear
60
+ - Prefer owned types in struct fields, borrows in function params
61
+ - Use derive macros for Debug, Clone, PartialEq where appropriate
62
+ - Keep unsafe blocks minimal and well-documented
63
+ - Use cargo fmt for formatting
64
+ - Prefer match over if-let chains for >2 variants`,
65
+ java: `# Java Rules
66
+ - Follow Google Java Style Guide
67
+ - Use records for value objects (Java 16+)
68
+ - Use var for local variables with clear initialization
69
+ - Prefer List.of(), Map.of() over mutable collections
70
+ - Use Optional instead of null for potentially absent values
71
+ - Use try-with-resources for all Closeable resources
72
+ - Prefer streams over explicit loops for collection transforms
73
+ - Use @Override annotation always
74
+ - Final fields by default; minimize mutability
75
+ - One class per file; class name matches filename
76
+ - Use SLF4J for logging`,
77
+ kotlin: `# Kotlin Rules
78
+ - Follow Kotlin Coding Conventions
79
+ - Use data classes for value objects
80
+ - Prefer val over var — immutability by default
81
+ - Use sealed classes for restricted hierarchies
82
+ - Use when instead of if-else chains (>2 branches)
83
+ - Use scope functions (let, run, apply, also) appropriately
84
+ - Use coroutines for async — avoid callbacks
85
+ - Prefer extension functions for utility operations
86
+ - Use string templates over concatenation
87
+ - Use named arguments for functions with >3 parameters`,
88
+ cpp: `# C++ Rules
89
+ - Follow C++ Core Guidelines
90
+ - Use smart pointers (unique_ptr, shared_ptr) — no raw owning pointers
91
+ - Use RAII for resource management
92
+ - Prefer references over pointers where nullability is not needed
93
+ - Use const correctly and consistently
94
+ - Use auto for complex types where the type is obvious from context
95
+ - Prefer range-based for loops
96
+ - Use std::string_view for non-owning string parameters
97
+ - Use [[nodiscard]] for functions where ignoring return is an error
98
+ - Use std::optional for values that may not exist
99
+ - Keep headers minimal — forward-declare where possible
100
+ - Use namespaces to avoid name collisions`,
101
+ php: `# PHP Rules
102
+ - Use PHP 8.1+ features: enums, fibers, readonly properties
103
+ - Use strict types: declare(strict_types=1) in every file
104
+ - Use type declarations for all parameters, return types, and properties
105
+ - Follow PSR-12 coding style
106
+ - Use constructor promotion for simple classes
107
+ - Use match() over switch for value mapping
108
+ - Use null coalescing (??) and nullsafe (?->) operators
109
+ - Use named arguments for clarity
110
+ - Prefer arrays + array functions over manual loops
111
+ - Use Composer autoloading (PSR-4)`,
112
+ sql: `# SQL Rules
113
+ - Use parameterized queries to prevent injection
114
+ - Avoid SELECT * — specify needed columns
115
+ - Use proper indexes on WHERE, JOIN, ORDER BY columns
116
+ - Avoid N+1 query patterns — use joins or eager loading
117
+ - Write migrations that are reversible
118
+ - Use foreign keys for referential integrity
119
+ - Follow naming conventions: snake_case for tables/columns
120
+ - Add CHECK constraints for business rule validation
121
+ - Use transactions for multi-step operations
122
+ - Document complex queries with comments`,
123
+ csharp: `# C# Rules
124
+ - Follow Microsoft C# Coding Conventions
125
+ - Use PascalCase for public members, camelCase for private
126
+ - Use LINQ where appropriate over manual loops
127
+ - Use async/await for I/O operations
128
+ - Use nullable reference types (C# 8+)
129
+ - Prefer pattern matching in switch statements
130
+ - Use dependency injection for testability
131
+ - Follow SOLID principles
132
+ - Use records for immutable data types
133
+ - Document public APIs with XML comments`,
134
+ };
135
+ function ensureDir() {
136
+ mkdirSync(RULES_DIR, { recursive: true });
137
+ }
138
+ /**
139
+ * Load rules for a specific language.
140
+ * Checks user rules first, falls back to built-in.
141
+ */
142
+ export function loadRules(language) {
143
+ ensureDir();
144
+ const userFile = join(RULES_DIR, `${language}.md`);
145
+ if (existsSync(userFile)) {
146
+ return readFileSync(userFile, 'utf-8');
147
+ }
148
+ return BUILTIN_RULES[language] || null;
149
+ }
150
+ /**
151
+ * Save custom rules for a language.
152
+ */
153
+ export function saveRules(language, rules) {
154
+ ensureDir();
155
+ writeFileSync(join(RULES_DIR, `${language}.md`), rules, 'utf-8');
156
+ }
157
+ /**
158
+ * List all available rule sets (built-in + custom).
159
+ */
160
+ export function listRuleSets() {
161
+ ensureDir();
162
+ const result = [];
163
+ // Custom rules
164
+ const customFiles = readdirSync(RULES_DIR).filter((f) => f.endsWith('.md'));
165
+ for (const f of customFiles) {
166
+ result.push({ language: f.replace('.md', ''), source: 'custom' });
167
+ }
168
+ // Built-in (not overridden)
169
+ for (const lang of Object.keys(BUILTIN_RULES)) {
170
+ if (!result.find((r) => r.language === lang)) {
171
+ result.push({ language: lang, source: 'builtin' });
172
+ }
173
+ }
174
+ return result.sort((a, b) => a.language.localeCompare(b.language));
175
+ }
176
+ /**
177
+ * Auto-detect languages in the project by file extensions.
178
+ */
179
+ export function detectLanguages(cwd) {
180
+ const extMap = {
181
+ '.ts': 'typescript', '.tsx': 'typescript', '.js': 'typescript', '.jsx': 'typescript',
182
+ '.py': 'python', '.pyw': 'python',
183
+ '.go': 'go',
184
+ '.rs': 'rust',
185
+ '.java': 'java',
186
+ '.kt': 'kotlin', '.kts': 'kotlin',
187
+ '.cpp': 'cpp', '.cc': 'cpp', '.cxx': 'cpp', '.h': 'cpp', '.hpp': 'cpp',
188
+ '.php': 'php',
189
+ };
190
+ const detected = new Set();
191
+ try {
192
+ const files = readdirSync(cwd, { recursive: true, withFileTypes: true });
193
+ for (const f of files) {
194
+ if (!f.isFile())
195
+ continue;
196
+ const name = f.name;
197
+ const ext = name.slice(name.lastIndexOf('.'));
198
+ if (extMap[ext])
199
+ detected.add(extMap[ext]);
200
+ if (detected.size >= 5)
201
+ break; // enough
202
+ }
203
+ }
204
+ catch {
205
+ // can't read dir
206
+ }
207
+ return Array.from(detected);
208
+ }
209
+ /**
210
+ * Build rules section for system prompt based on detected languages.
211
+ */
212
+ export function buildRulesPrompt(cwd) {
213
+ const languages = detectLanguages(cwd);
214
+ if (languages.length === 0)
215
+ return '';
216
+ const sections = [];
217
+ for (const lang of languages) {
218
+ const rules = loadRules(lang);
219
+ if (rules)
220
+ sections.push(rules);
221
+ }
222
+ if (sections.length === 0)
223
+ return '';
224
+ return `\n# Coding Standards\n${sections.join('\n\n')}`;
225
+ }
226
+ /**
227
+ * Get detailed coding rules for a specific language.
228
+ * Loads custom rules if available, falls back to comprehensive built-in rules.
229
+ */
230
+ export function getLanguageRules(language) {
231
+ // Load custom rules if available
232
+ const customRules = loadRules(language);
233
+ if (customRules) {
234
+ return customRules;
235
+ }
236
+ // Return comprehensive built-in rules with additional detail
237
+ const detailedRules = {
238
+ typescript: `# TypeScript Code Standards
239
+
240
+ ## Type System & Strict Mode
241
+ - Enforce \`"strict": true\` in tsconfig.json for all strict compiler options
242
+ - Prefer const over let; never use var for any reason
243
+ - Explicitly declare return types on all exported functions and public methods
244
+ - Use interfaces for object shapes and contracts; use types for unions, intersections, and aliases
245
+ - Prefer readonly arrays and properties to prevent accidental mutations
246
+ - Always provide explicit generic type parameters; don't rely on inference for complex types
247
+ - Use discriminated unions for type-safe pattern matching
248
+
249
+ ## Null & Undefined Safety
250
+ - Use nullish coalescing (??) over logical OR (||) for proper falsy value handling
251
+ - Use optional chaining (?.) for deep property access
252
+ - Avoid non-null assertions (!) unless absolutely necessary and well-documented
253
+ - Handle all Promise rejections—no floating promises
254
+ - Never assume values exist; always add type guards or assertions
255
+
256
+ ## Async Patterns & Promises
257
+ - Mark async operations with explicit async/await or return Promise<T>
258
+ - Handle all .catch() blocks; use try-catch in async functions
259
+ - Ensure Promise.all() and Promise.race() have error handling
260
+ - Set timeouts on long-running async operations
261
+ - Avoid mixing callbacks with promises
262
+
263
+ ## Imports & Module System
264
+ - Use ESM (import/export); never CommonJS (require)
265
+ - Import order: Node.js built-ins → npm packages → local files
266
+ - Use named imports when importing specific exports
267
+ - Avoid circular dependencies—refactor shared logic to a common module
268
+ - Include file extensions in relative imports (.js, .ts)
269
+ - Use index.ts for directory exports to control public API
270
+
271
+ ## Code Organization & Naming
272
+ - Max function length: 50 lines; extract if larger
273
+ - Max file length: 300 lines; split into multiple files if exceeded
274
+ - Use kebab-case for filenames, PascalCase for classes/components
275
+ - Use camelCase for functions and variables
276
+ - Use UPPER_SNAKE_CASE for constants
277
+ - Place public functions before private in file order
278
+
279
+ ## Code Quality & Maintainability
280
+ - No console.log in production—use a logger (winston, pino, etc.)
281
+ - Avoid deeply nested conditionals; use early returns for guard clauses
282
+ - DRY: extract duplicated logic into reusable functions
283
+ - No magic numbers—use named constants with descriptive names
284
+ - Add comments explaining "why", not "what"
285
+ - Keep cyclomatic complexity reasonable (<5 per function)
286
+
287
+ ## Performance & Memory
288
+ - Avoid N+1 database queries by batch loading or joining data
289
+ - Memoize expensive computations (use memoization libraries)
290
+ - Remove event listeners (removeEventListener) to prevent memory leaks
291
+ - Unsubscribe from subscriptions in cleanup functions
292
+ - Don't hold large objects in memory longer than necessary
293
+
294
+ ## Testing
295
+ - Write unit tests for all business logic and utilities
296
+ - Cover happy paths and at least 3 edge cases per function
297
+ - Add JSDoc comments to public functions with @param, @returns, @throws
298
+ - Document non-obvious logic with inline comments`,
299
+ python: `# Python Code Standards
300
+
301
+ ## Type Hints & Static Typing
302
+ - Add type hints to all function parameters and return types
303
+ - Use type hints on class attributes using typing module or PEP 526
304
+ - Use complex type aliases (TypeAlias) for clarity
305
+ - Run mypy or pyright to validate types
306
+ - Use Union[X, Y] or X | Y (3.10+) for multiple types
307
+ - Never use implicit Any—always be explicit
308
+
309
+ ## PEP 8 Compliance
310
+ - Use 4 spaces for indentation; never tabs
311
+ - Keep lines ≤79 characters (100 for comments/docstrings)
312
+ - Use CamelCase for classes; snake_case for functions and variables
313
+ - Use UPPER_SNAKE_CASE for module-level constants
314
+ - Place 2 blank lines between top-level definitions, 1 between methods
315
+ - Use trailing commas in multi-line collections
316
+
317
+ ## Strings & Documentation
318
+ - Always use f-strings (f"...") for string formatting
319
+ - Never use % formatting or .format() unless f-string unavailable
320
+ - Write docstrings in Google style for all public functions/classes
321
+ - Use triple double quotes (""") for docstrings
322
+ - Use raw strings (r"...") for regex patterns
323
+ - Avoid string concatenation in loops—collect in list, then join
324
+
325
+ ## Async & Concurrency
326
+ - Use async/await; don't mix with threading without careful consideration
327
+ - Manage asyncio event loop explicitly; understand run_until_complete
328
+ - Never block I/O in async functions (no time.sleep(); use asyncio.sleep())
329
+ - Set timeouts on all async operations using asyncio.wait_for()
330
+ - Use asyncio.gather() or asyncio.TaskGroup for concurrent tasks
331
+ - Understand GIL implications when using threading
332
+
333
+ ## Exception Handling
334
+ - Never use bare except:; always catch specific exceptions
335
+ - Use custom exception classes for domain errors
336
+ - Use finally blocks for cleanup or context managers (with statement)
337
+ - Log exceptions with context before re-raising
338
+ - Don't silently swallow exceptions
339
+ - Use context managers for all resource management
340
+
341
+ ## File I/O & Paths
342
+ - Always use pathlib.Path instead of os.path
343
+ - Use context managers for file operations: with open(...) as f:
344
+ - Always specify encoding explicitly (utf-8 is typical)
345
+ - Never hardcode absolute paths—use config or environment variables
346
+ - Check file existence before operations using if path.exists()
347
+
348
+ ## Data Structures & Functions
349
+ - Limit function length to ~30 lines; extract if larger
350
+ - Limit function parameters to 3-4; use dataclass if more needed
351
+ - Never use mutable defaults: def foo(items=[]) is wrong; use None + factory
352
+ - Prefer dataclasses or Pydantic for structured data
353
+ - Use enumerate() instead of range(len())
354
+ - Use list/dict/set comprehensions for readability
355
+ - Use generator expressions for large datasets
356
+
357
+ ## Testing & Documentation
358
+ - Write docstrings for all public functions using Google style
359
+ - Use pytest for unit tests; organize with fixtures and markers
360
+ - Cover happy paths, edge cases, and error conditions
361
+ - Use mocks/patches to isolate external dependencies
362
+ - Never use print() in production—use logging module
363
+ - Configure logging with proper levels: DEBUG, INFO, WARNING, ERROR
364
+
365
+ ## Performance & Best Practices
366
+ - Avoid N+1 queries using select_related() or prefetch_related() in ORMs
367
+ - Use pagination for large result sets
368
+ - Cache expensive computations (consider functools.lru_cache)
369
+ - Avoid algorithms with O(n²) or worse without justification
370
+ - Profile before optimizing`,
371
+ go: `# Go Code Standards
372
+
373
+ ## Error Handling (Go Proverbs: "Errors are values")
374
+ - Always handle every error; use _ = err only with explicit justification comment
375
+ - Wrap errors with context: fmt.Errorf("doing X: %w", err)
376
+ - Define custom error types for domain-specific errors
377
+ - Never panic in libraries; only in main or tests
378
+ - Provide helpful error messages to users
379
+ - Use error chains to understand error context
380
+
381
+ ## Interface Design & Struct Composition
382
+ - Keep interfaces small: 1-3 methods, defined where they're needed
383
+ - Prefer composition over inheritance; use embedding for type reuse
384
+ - Use pointer receivers when modifying receiver; value otherwise
385
+ - Don't create interfaces for every type; only when needed
386
+ - Use unexported (lowercase) fields by default; export only what's public
387
+ - Document exported identifiers with comments starting with the name
388
+
389
+ ## Context & Concurrency
390
+ - Pass context.Context as the first parameter in long-running functions
391
+ - Always respect context cancellation in loops
392
+ - Set timeouts on contexts: ctx, cancel := context.WithTimeout(ctx, time.Minute)
393
+ - Never store context in struct fields; pass as parameter
394
+ - Use context.Background() only at application entry point
395
+ - Never block indefinitely—always have timeout or cancellation
396
+
397
+ ## Goroutines & Channel Safety
398
+ - Prevent goroutine leaks by ensuring all goroutines exit
399
+ - Use sync.WaitGroup or context cancellation to coordinate goroutines
400
+ - Test with go run -race to detect data races
401
+ - Always close channels from the sender; receivers don't close
402
+ - Use select with timeout to prevent deadlocks
403
+ - Protect shared memory with sync.Mutex or use channels
404
+
405
+ ## Code Style & Organization
406
+ - Run gofmt automatically; never commit unformatted code
407
+ - Run goimports to organize imports correctly
408
+ - Keep function comments at the top, starting with function name
409
+ - Document packages with a package comment at the top of the file
410
+ - Group related code; use blank lines to separate logical blocks
411
+ - File structure: package comment → imports → constants → vars → types → interfaces → functions
412
+
413
+ ## Function & File Structure
414
+ - Place exported functions before unexported ones
415
+ - Keep functions focused on a single task
416
+ - Table-driven tests for testing multiple scenarios
417
+ - Use subtests (t.Run) for test clarity and isolation
418
+ - Max cyclomatic complexity ~5; refactor if exceeded
419
+ - Package names: short, lowercase, no underscores
420
+
421
+ ## Testing Strategy
422
+ - Use table-driven tests: test different inputs with same logic
423
+ - Use t.Run for subtests and clearer test organization
424
+ - Mock external dependencies; unit tests shouldn't call external services
425
+ - Write benchmarks for performance-critical code
426
+ - Fuzz tests for parsers and validators
427
+ - Test error paths, not just happy paths
428
+
429
+ ## Common Go Patterns
430
+ - Use defer for cleanup (files, locks, connections)
431
+ - Check type assertions with v, ok := x.(Type)
432
+ - Avoid init() functions; prefer explicit initialization
433
+ - Use iota for enum-like constants
434
+ - Prefer if err != nil { return err } over else blocks`,
435
+ rust: `# Rust Code Standards
436
+
437
+ ## Ownership & Lifetimes
438
+ - Understand and follow Rust's ownership rules strictly
439
+ - Annotate lifetimes explicitly when the compiler can't infer
440
+ - Use references (&T) for non-owning access; Box<T> for owned allocations
441
+ - Pass &str instead of &String for function parameters
442
+ - Pass &[T] instead of &Vec<T> for function parameters
443
+ - Use &T for immutable access; &mut T for exclusive mutable access
444
+
445
+ ## Error Handling & Results
446
+ - Use Result<T, E> for all fallible operations—never panic in libraries
447
+ - Implement Error + Display traits for custom error types
448
+ - Use the ? operator for error propagation
449
+ - Add context to errors when wrapping
450
+ - Never use unwrap() or expect() in production code (tests OK)
451
+ - Consider custom error types instead of generic String errors
452
+
453
+ ## Smart Pointers & Memory Safety
454
+ - Use Box<T> for owned heap allocations
455
+ - Use Arc<T> for shared ownership; Rc<T> only in single-threaded contexts
456
+ - Break circular references with Weak<T>
457
+ - Understand Arc overhead and use judiciously
458
+ - Never use raw pointers (*const T, *mut T) outside unsafe blocks
459
+ - Never hold references across .await points without understanding
460
+
461
+ ## Unsafe Code
462
+ - Minimize unsafe blocks; they should be last resort
463
+ - Document safety invariants above every unsafe block
464
+ - Include a SAFETY comment explaining why it's safe
465
+ - Verify bounds before any pointer dereference
466
+ - Use high-level safe abstractions instead of unsafe when possible
467
+ - Review unsafe code with extra scrutiny during code review
468
+
469
+ ## Const Correctness & Generics
470
+ - Use const for compile-time constant values
471
+ - Use const fn for functions that can run at compile time
472
+ - Use const generics for compile-time parameterization
473
+ - Annotate mutable references only when mutation happens
474
+ - Use &self for immutable methods; &mut self for mutating
475
+ - Default to immutable bindings (let, not let mut)
476
+
477
+ ## Clippy & Code Quality
478
+ - Enable #![warn(clippy::all)] or stricter in lib.rs/main.rs
479
+ - Address all clippy warnings; understand before dismissing
480
+ - Use cargo clippy to find idiomatic Rust patterns
481
+ - Apply rustfmt for consistent formatting
482
+ - Keep function length reasonable; extract if complex
483
+ - DRY: refactor duplicated logic into helpers
484
+
485
+ ## Code Style & Documentation
486
+ - Use snake_case for functions/variables, CamelCase for types/traits
487
+ - Run cargo fmt before committing
488
+ - Document all public functions with /// doc comments
489
+ - Include examples in doc comments; they're compiled with cargo test --doc
490
+ - Add SAFETY comments for all unsafe blocks explaining why it's safe
491
+ - Write INVARIANT comments for complex data structures
492
+
493
+ ## Testing & Verification
494
+ - Write unit tests in modules with #[cfg(test)]
495
+ - Write integration tests in tests/ directory
496
+ - Include examples in doc comments with /// \`\`\`
497
+ - Test error paths and edge cases
498
+ - Use property-based testing (proptest) for combinatorial coverage
499
+ - Profile before optimizing; use cargo flamegraph
500
+
501
+ ## Trait & Generic Design
502
+ - Keep traits cohesive; single responsibility
503
+ - Use explicit generic bounds: fn foo<T: Clone + Display>(...)
504
+ - Use associated types to avoid over-generalization
505
+ - Follow orphan rule: implement foreign traits only on local types
506
+ - Use HRTB (for<'a>) for advanced lifetime scenarios
507
+ - Prefer composition over trait objects when possible`,
508
+ java: `# Java Code Standards
509
+
510
+ ## Null Safety & Optional
511
+ - Use Optional<T> instead of returning null
512
+ - Use Optional.orElse(), orElseThrow(), orElseGet()
513
+ - Never call Optional.get() without isPresent() check
514
+ - Use @Nullable/@NonNull annotations for clarity
515
+ - Handle NullPointerException in tests
516
+ - Understand Optional is not a general-purpose wrapper
517
+
518
+ ## Resource Management (Try-With-Resources)
519
+ - Always use try-with-resources for Closeable resources
520
+ - Never use try-finally for resource cleanup
521
+ - Connection/Statement always closed in try-with-resources
522
+ - Stream/Reader/Writer closed in try-with-resources
523
+ - Test for resource leaks with tools like NetBeans Profiler
524
+
525
+ ## Collections & Streams
526
+ - Prefer Stream API over explicit loops for transformations
527
+ - Use List.of(), Map.of(), Set.of() for immutable collections
528
+ - Never create unnecessary new ArrayList/HashMap
529
+ - Terminal operations required in Stream chains
530
+ - Avoid nested flatMap; limit depth for readability
531
+ - Use Collectors.groupingBy, toMap, etc. appropriately
532
+
533
+ ## Spring Boot & Dependency Injection
534
+ - Constructor injection preferred over @Autowired on fields
535
+ - Use @Autowired on constructor for single dependency
536
+ - Avoid circular dependencies; refactor if found
537
+ - Use @Service, @Repository, @Controller on appropriate classes
538
+ - @Transactional on service methods, not on getters
539
+ - Use @ConfigurationProperties for externalized configuration
540
+
541
+ ## JPA & ORM Patterns
542
+ - Use fetch joins to prevent N+1 query problems
543
+ - Avoid lazy loading issues; use eager loading when needed
544
+ - Ensure entities only modified within transactions
545
+ - Set @Transactional(readOnly=true) on query methods
546
+ - Careful with cascade configuration—avoid unintended deletes
547
+ - Use projections for read-only queries
548
+
549
+ ## Code Style & Conventions
550
+ - 4-space indentation; never tabs
551
+ - Max 100 characters per line
552
+ - CamelCase for classes; camelCase for methods/variables
553
+ - UPPER_SNAKE_CASE for constants
554
+ - Always use @Override annotation
555
+ - Comments explain "why", not "what"
556
+
557
+ ## Type Safety & Generics
558
+ - Specify generic type bounds: <T extends SomeClass>
559
+ - Use wildcard types appropriately: ? extends, ? super
560
+ - Minimize unchecked casts; document when necessary
561
+ - Never use raw types (List instead of List<String>)
562
+ - Understand type erasure implications
563
+
564
+ ## Testing
565
+ - Use JUnit 5 with @Test annotations
566
+ - Mock external dependencies with Mockito
567
+ - Test names describe what is tested
568
+ - Follow Arrange-Act-Assert pattern
569
+ - Document public APIs with Javadoc
570
+ - Use @param, @return, @throws in Javadoc
571
+
572
+ ## Object-Oriented Design
573
+ - Use inheritance sparingly; prefer composition
574
+ - Mark immutable classes as final
575
+ - Encapsulate fields; provide getters
576
+ - Follow SOLID principles
577
+ - Single Responsibility per class
578
+ - No "god classes" with too many responsibilities`,
579
+ cpp: `# C++ Code Standards
580
+
581
+ ## Memory Management (RAII, Smart Pointers)
582
+ - Use std::unique_ptr for single ownership
583
+ - Use std::shared_ptr for shared ownership
584
+ - Never use raw owning pointers (new/delete)
585
+ - Use std::make_unique/make_shared
586
+ - Ensure all resources have destructors
587
+ - No memory leaks possible even in exception paths
588
+
589
+ ## Const Correctness
590
+ - Mark methods const when they don't modify state
591
+ - Use const references: const T& for parameters
592
+ - Propagate const correctness up the call chain
593
+ - Use mutable only for truly mutable implementation details
594
+ - Mark data members const by default
595
+ - const in templates: template<const T>
596
+
597
+ ## Pointer & Reference Safety
598
+ - Use std::string_view for non-owning string parameters
599
+ - Prefer references over pointers when nullability unnecessary
600
+ - Use bounds checking in array operations
601
+ - Check pointers before dereference
602
+ - Use std::span<T> for array ranges (C++20)
603
+ - Use std::optional<T> for optional values
604
+
605
+ ## RAII & Destructors
606
+ - Every resource has a constructor (acquire) and destructor (release)
607
+ - Define move constructor and move assignment
608
+ - Copy constructor and assignment operator when deep copying needed
609
+ - No resource leaks in exception paths
610
+ - Use scopedexits pattern for cleanup
611
+ - RAII applies to locks, files, network connections, memory
612
+
613
+ ## Standard Library
614
+ - Use std::vector for dynamic arrays
615
+ - Use std::string for text (not char arrays)
616
+ - Use std::array for fixed-size arrays
617
+ - Use std::map/unordered_map for key-value
618
+ - Understand iterator validity before/after operations
619
+ - Use range-based for loops: for(auto& x : container)
620
+ - Use <algorithm> library functions
621
+
622
+ ## Error Handling
623
+ - Exceptions preferred to error codes in modern C++
624
+ - Provide strong or basic exception safety guarantee
625
+ - Use noexcept appropriately; default to not noexcept
626
+ - Custom exception types for domain errors
627
+ - Avoid exception specifications; use noexcept only
628
+ - Test exception paths in unit tests
629
+
630
+ ## Code Style & Quality
631
+ - Run clang-format automatically; never commit unformatted code
632
+ - Never use using namespace std (except in function scope)
633
+ - Meaningful variable/function names
634
+ - Single responsibility per function
635
+ - Reasonable cyclomatic complexity
636
+ - Named constants instead of magic numbers
637
+ - Comments explain non-obvious logic
638
+
639
+ ## Testing & Documentation
640
+ - Unit tests for critical functions
641
+ - Integration tests for module interactions
642
+ - Doxygen comments for public API
643
+ - Include examples for complex APIs
644
+ - README explains build and usage
645
+ - Use Valgrind/AddressSanitizer for testing
646
+
647
+ ## Template Metaprogramming
648
+ - Template complexity justified
649
+ - Use SFINAE or C++20 concepts for overload resolution
650
+ - Minimize template instantiation bloat
651
+ - Document explicit instantiations
652
+ - Use static_assert for compile-time checks
653
+ - C++20 concepts preferred over enable_if
654
+
655
+ ## Performance
656
+ - Use move semantics to avoid copies
657
+ - Minimize allocations in hot loops
658
+ - Reasonable algorithm complexity
659
+ - Profile before optimizing
660
+ - Cache-friendly data layout
661
+ - Inline hints used conservatively`,
662
+ kotlin: `# Kotlin Code Standards
663
+
664
+ ## Null Safety & Type System
665
+ - Non-nullable types (T) preferred; nullable (T?) explicit
666
+ - Safe calls (.?) and assertions (!!); assert only in tests
667
+ - Elvis operator (?:) for defaults
668
+ - Use val by default; var only when needed
669
+ - lateinit for late initialization; lazy for computed values
670
+ - Never use !!
671
+
672
+ ## Data Classes & Immutability
673
+ - data class for value objects with auto-generated equals, hashCode, toString
674
+ - Use copy() for "modifications" (maintains immutability)
675
+ - val everywhere; var sparingly
676
+ - Destructuring: val (x, y) = pair
677
+ - Private constructors for controlled creation
678
+ - sealed class for restricted hierarchies
679
+
680
+ ## Coroutines & Async
681
+ - async/await instead of callbacks
682
+ - Proper scope: GlobalScope avoided; use lifecycle scopes
683
+ - Exception handling in coroutine builders
684
+ - Cancellation respected in loops
685
+ - launch vs async: launch for fire-and-forget, async for results
686
+ - Job/Task properly awaited
687
+
688
+ ## Control Flow & When Expressions
689
+ - when instead of if-else chains (>2 branches)
690
+ - when exhaustive or explicit else
691
+ - Scope functions (let, run, apply, also) appropriately used
692
+ - if-expressions return values when possible
693
+ - Early returns to avoid nesting
694
+ - Guard clauses instead of nested blocks
695
+
696
+ ## Extension Functions & Higher-Order Functions
697
+ - Extension functions for utility operations
698
+ - Receiver clarity in extension scopes
699
+ - No extensions on Any/Object
700
+ - Lambdas single-expression when possible
701
+ - it implicit parameter understood
702
+ - Function types clear in signatures
703
+
704
+ ## Collections & Sequences
705
+ - listOf, mapOf, setOf for immutable collections
706
+ - Sequences for lazy evaluation chains
707
+ - map/filter/reduce chains clear and efficient
708
+ - groupBy for grouping; associate for map creation
709
+ - No unnecessary list conversions
710
+ - forEach/forEachIndexed over manual loops
711
+
712
+ ## Strings & Text
713
+ - String templates (with ${'${}'}) instead of concatenation
714
+ - Triple quotes (""" """) for multiline
715
+ - Raw strings for regex/JSON
716
+ - No string building in loops
717
+
718
+ ## Testing & Spring Integration
719
+ - JUnit 5 with @Test
720
+ - Mockk or similar for mocking
721
+ - Test names describe behavior
722
+ - Arrange-Act-Assert pattern
723
+ - KDoc for public APIs
724
+ - @SpringBootTest for integration tests
725
+
726
+ ## Code Style & Conventions
727
+ - ktlint for consistent formatting
728
+ - No redundant modifiers (public, final)
729
+ - camelCase for functions; PascalCase for types
730
+ - Comments explain "why" not "what"
731
+ - Function length ~30 lines; file length ~300 lines
732
+ - Named arguments for functions with >3 parameters`,
733
+ php: `# PHP Code Standards
734
+
735
+ ## Type Safety & Strict Types
736
+ - declare(strict_types=1) at the top of EVERY file
737
+ - Type all parameters and return types
738
+ - Type class properties
739
+ - Avoid mixed type; be specific
740
+ - Use typed properties (PHP 7.4+)
741
+ - Static analysis with phpstan or psalm
742
+
743
+ ## Null Safety & Error Handling
744
+ - Null coalescing (??) over isset checks
745
+ - Nullsafe operator (?->) for deep property access
746
+ - No silent null failures
747
+ - Type hints include ? for nullable types
748
+ - Guard clauses for early returns
749
+ - Specific exception handling, not catch(Exception)
750
+
751
+ ## PSR Standards & Code Style
752
+ - PSR-1: Basic Coding Standard
753
+ - PSR-12: Extended Coding Style
754
+ - PSR-4: Autoloading via Composer
755
+ - 4-space indentation
756
+ - CamelCase for classes; camelCase for methods
757
+ - php_eol for line endings
758
+
759
+ ## Modern PHP Features (8.1+)
760
+ - Enums for restricted value sets
761
+ - Readonly properties for immutability
762
+ - Match expressions instead of switch
763
+ - Named arguments for clarity
764
+ - Constructor promotion (public __construct(private string $name))
765
+ - Fibers for async control flow
766
+
767
+ ## Eloquent & Database
768
+ - Model relationships defined clearly
769
+ - Eager loading (with()) prevents N+1
770
+ - select() for specific columns
771
+ - Query scopes for reusable logic
772
+ - Soft deletes for historical data
773
+ - Mass assignment protection ($guarded, $fillable)
774
+
775
+ ## Validation & Security
776
+ - Request validation classes for input
777
+ - Validate ALL user input
778
+ - Custom validation messages
779
+ - Gate/Policy for authorization
780
+ - CSRF protection enabled
781
+ - Parameterized queries (ORM handles this)
782
+
783
+ ## Collections & Functional
784
+ - Illuminate\Support\Collection methods
785
+ - map/filter/reduce for transformations
786
+ - array functions for simple operations
787
+ - No manual loops when collection methods suffice
788
+ - Null-safe operations with collection methods
789
+ - Type-safe collection usage
790
+
791
+ ## Laravel Patterns
792
+ - Service/Repository for business logic
793
+ - Middleware for cross-cutting concerns
794
+ - Jobs/Queues for async operations
795
+ - Service providers for registration
796
+ - Facades appropriately used
797
+ - Dependency injection via constructor
798
+
799
+ ## Testing
800
+ - PHPUnit for unit tests
801
+ - Feature tests for user workflows
802
+ - Mocking external dependencies
803
+ - Test database transactions
804
+ - Meaningful assertion messages
805
+ - Good test organization
806
+
807
+ ## Documentation & Strings
808
+ - Docblock comments on public methods
809
+ - README explains setup and usage
810
+ - PHPDoc for parameter/return types
811
+ - Heredoc/Nowdoc for multiline strings
812
+ - No hardcoded values (use config)
813
+ - Localization for user-facing strings`,
814
+ sql: `# SQL Code Standards
815
+
816
+ ## Security (SQL Injection Prevention)
817
+ - Always use parameterized queries (? or :name)
818
+ - Never string-interpolate user input
819
+ - Input validation before SQL operations
820
+ - User input never directly in WHERE/SELECT
821
+ - Prepared statements cached and reused
822
+ - Stored procedures with parameter binding
823
+ - ORM systems with parameterization
824
+
825
+ ## Query Optimization
826
+ - N+1 query prevention; use JOINs
827
+ - SELECT specific columns, never SELECT *
828
+ - Pagination for large result sets
829
+ - EXPLAIN PLAN for complex queries
830
+ - Indexes on WHERE, JOIN, ORDER BY columns
831
+ - Join order matters for optimizer
832
+ - Subqueries not in SELECT list
833
+
834
+ ## Schema Design & Constraints
835
+ - Primary keys on every table
836
+ - Foreign keys establish relationships
837
+ - Data types match actual values
838
+ - NOT NULL constraints explicit
839
+ - UNIQUE constraints for natural keys
840
+ - Normalization (3NF minimum)
841
+ - No magic numbers as IDs
842
+
843
+ ## Migrations & Version Control
844
+ - Migrations reversible (up/down)
845
+ - Schema changes safe (add before remove)
846
+ - Data migrations with rollback path
847
+ - Test migrations up and down
848
+ - Breaking changes documented
849
+ - Backward compatibility maintained
850
+ - One migration per change
851
+
852
+ ## Performance & Indexing
853
+ - Indexes on high-cardinality columns
854
+ - Composite indexes for multi-column filters
855
+ - Covering indexes for hot queries
856
+ - No redundant indexes
857
+ - Index maintenance cost considered
858
+ - Statistics updated regularly
859
+
860
+ ## Data Integrity & Testing
861
+ - Audit columns (created_at, updated_at)
862
+ - Soft deletes for historical data
863
+ - Archival strategy documented
864
+ - Backup/restore tested
865
+ - Consistent validation rules
866
+ - Temporal data handled correctly
867
+
868
+ ## Comments & Documentation
869
+ - Comments on complex queries
870
+ - Document table purposes
871
+ - Explain non-obvious indexes
872
+ - Record any known performance issues
873
+ - Database version requirements noted`,
874
+ csharp: `# C# Code Standards
875
+
876
+ ## Code Style & Conventions
877
+ - Follow Microsoft C# Coding Conventions
878
+ - PascalCase for public members; camelCase for private
879
+ - 4-space indentation
880
+ - Meaningful names for all identifiers
881
+ - Max function length ~30 lines
882
+ - Single Responsibility Principle
883
+
884
+ ## Language Features
885
+ - LINQ for collection queries (not loops)
886
+ - async/await for I/O operations
887
+ - Nullable reference types (C# 8+)
888
+ - Pattern matching in switch statements
889
+ - Records for immutable data types
890
+ - Tuples for returning multiple values
891
+ - String interpolation ($"...")
892
+
893
+ ## Null Safety
894
+ - Enable nullable reference types in csproj
895
+ - Non-null types by default; ? for nullable
896
+ - Use null-conditional operators (?., ?[])
897
+ - Guard clauses for null checks
898
+ - Null coalescing (??) for defaults
899
+
900
+ ## Dependency Injection & Architecture
901
+ - Constructor injection for dependencies
902
+ - Interface-based design
903
+ - Dependency Injection containers
904
+ - Inversion of Control pattern
905
+ - SOLID principles
906
+
907
+ ## Testing & Documentation
908
+ - Unit tests with xUnit or NUnit
909
+ - Mock dependencies with Moq
910
+ - Test names describe behavior
911
+ - Integration tests for workflows
912
+ - XML documentation on public APIs
913
+ - Examples in documentation
914
+
915
+ ## async/await & Threading
916
+ - async/await for I/O operations
917
+ - ConfigureAwait(false) in libraries
918
+ - Proper exception handling in async
919
+ - Avoid sync-over-async patterns
920
+ - Task.Run for CPU-bound work
921
+ - Cancellation tokens passed through
922
+
923
+ ## Collections & Generics
924
+ - LINQ over manual loops
925
+ - Generic constraints explicit
926
+ - Immutable collections for safety
927
+ - IEnumerable for lazy evaluation
928
+ - Choose collection type by use case
929
+ - No unnecessary allocations`,
930
+ };
931
+ return detailedRules[language] || BUILTIN_RULES[language] || `# Rules for ${language}\n(No rules defined for this language)`;
932
+ }
933
+ export function printRules() {
934
+ const sets = listRuleSets();
935
+ console.log(chalk.cyan(`\n Rule Sets (${sets.length}):`));
936
+ for (const s of sets) {
937
+ console.log(chalk.dim(` ${s.language.padEnd(15)} [${s.source}]`));
938
+ }
939
+ console.log(chalk.dim(' \n Custom rules: ~/.crowcoder/rules/<language>.md'));
940
+ console.log();
941
+ }
942
+ //# sourceMappingURL=rules.js.map