tribunal-kit 3.0.0 → 3.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 (226) hide show
  1. package/.agent/ARCHITECTURE.md +99 -99
  2. package/.agent/GEMINI.md +52 -52
  3. package/.agent/agents/accessibility-reviewer.md +187 -220
  4. package/.agent/agents/ai-code-reviewer.md +199 -233
  5. package/.agent/agents/backend-specialist.md +215 -238
  6. package/.agent/agents/code-archaeologist.md +161 -181
  7. package/.agent/agents/database-architect.md +184 -207
  8. package/.agent/agents/debugger.md +191 -218
  9. package/.agent/agents/dependency-reviewer.md +103 -136
  10. package/.agent/agents/devops-engineer.md +218 -238
  11. package/.agent/agents/documentation-writer.md +201 -221
  12. package/.agent/agents/explorer-agent.md +160 -180
  13. package/.agent/agents/frontend-reviewer.md +160 -194
  14. package/.agent/agents/frontend-specialist.md +248 -237
  15. package/.agent/agents/game-developer.md +48 -52
  16. package/.agent/agents/logic-reviewer.md +116 -149
  17. package/.agent/agents/mobile-developer.md +200 -223
  18. package/.agent/agents/mobile-reviewer.md +162 -195
  19. package/.agent/agents/orchestrator.md +181 -211
  20. package/.agent/agents/penetration-tester.md +157 -174
  21. package/.agent/agents/performance-optimizer.md +183 -203
  22. package/.agent/agents/performance-reviewer.md +178 -211
  23. package/.agent/agents/product-manager.md +142 -162
  24. package/.agent/agents/product-owner.md +6 -25
  25. package/.agent/agents/project-planner.md +142 -162
  26. package/.agent/agents/qa-automation-engineer.md +225 -242
  27. package/.agent/agents/security-auditor.md +174 -194
  28. package/.agent/agents/seo-specialist.md +193 -213
  29. package/.agent/agents/sql-reviewer.md +161 -194
  30. package/.agent/agents/supervisor-agent.md +184 -203
  31. package/.agent/agents/swarm-worker-contracts.md +17 -17
  32. package/.agent/agents/swarm-worker-registry.md +46 -46
  33. package/.agent/agents/test-coverage-reviewer.md +160 -193
  34. package/.agent/agents/test-engineer.md +0 -21
  35. package/.agent/agents/type-safety-reviewer.md +175 -208
  36. package/.agent/patterns/generator.md +9 -9
  37. package/.agent/patterns/inversion.md +12 -12
  38. package/.agent/patterns/pipeline.md +9 -9
  39. package/.agent/patterns/reviewer.md +13 -13
  40. package/.agent/patterns/tool-wrapper.md +9 -9
  41. package/.agent/rules/GEMINI.md +63 -63
  42. package/.agent/scripts/compress_skills.py +167 -0
  43. package/.agent/scripts/consolidate_skills.py +173 -0
  44. package/.agent/scripts/deep_compress.py +202 -0
  45. package/.agent/scripts/minify_context.py +80 -0
  46. package/.agent/scripts/security_scan.py +1 -1
  47. package/.agent/scripts/strip_tribunal.py +41 -0
  48. package/.agent/skills/agent-organizer/SKILL.md +92 -126
  49. package/.agent/skills/agentic-patterns/SKILL.md +0 -70
  50. package/.agent/skills/ai-prompt-injection-defense/SKILL.md +126 -160
  51. package/.agent/skills/api-patterns/SKILL.md +123 -215
  52. package/.agent/skills/api-security-auditor/SKILL.md +143 -177
  53. package/.agent/skills/app-builder/SKILL.md +326 -50
  54. package/.agent/skills/app-builder/templates/SKILL.md +13 -15
  55. package/.agent/skills/app-builder/templates/astro-static/TEMPLATE.md +16 -16
  56. package/.agent/skills/app-builder/templates/chrome-extension/TEMPLATE.md +22 -22
  57. package/.agent/skills/app-builder/templates/cli-tool/TEMPLATE.md +18 -18
  58. package/.agent/skills/app-builder/templates/electron-desktop/TEMPLATE.md +20 -20
  59. package/.agent/skills/app-builder/templates/express-api/TEMPLATE.md +17 -17
  60. package/.agent/skills/app-builder/templates/flutter-app/TEMPLATE.md +18 -18
  61. package/.agent/skills/app-builder/templates/monorepo-turborepo/TEMPLATE.md +21 -21
  62. package/.agent/skills/app-builder/templates/nextjs-fullstack/TEMPLATE.md +19 -19
  63. package/.agent/skills/app-builder/templates/nextjs-saas/TEMPLATE.md +26 -26
  64. package/.agent/skills/app-builder/templates/nextjs-static/TEMPLATE.md +26 -26
  65. package/.agent/skills/app-builder/templates/nuxt-app/TEMPLATE.md +19 -19
  66. package/.agent/skills/app-builder/templates/python-fastapi/TEMPLATE.md +18 -18
  67. package/.agent/skills/app-builder/templates/react-native-app/TEMPLATE.md +20 -20
  68. package/.agent/skills/appflow-wireframe/SKILL.md +87 -121
  69. package/.agent/skills/architecture/SKILL.md +82 -252
  70. package/.agent/skills/authentication-best-practices/SKILL.md +139 -173
  71. package/.agent/skills/bash-linux/SKILL.md +120 -154
  72. package/.agent/skills/behavioral-modes/SKILL.md +8 -69
  73. package/.agent/skills/brainstorming/SKILL.md +428 -104
  74. package/.agent/skills/building-native-ui/SKILL.md +143 -174
  75. package/.agent/skills/clean-code/SKILL.md +323 -360
  76. package/.agent/skills/code-review-checklist/SKILL.md +0 -62
  77. package/.agent/skills/config-validator/SKILL.md +107 -141
  78. package/.agent/skills/csharp-developer/SKILL.md +468 -528
  79. package/.agent/skills/database-design/SKILL.md +104 -369
  80. package/.agent/skills/deployment-procedures/SKILL.md +111 -145
  81. package/.agent/skills/devops-engineer/SKILL.md +295 -332
  82. package/.agent/skills/devops-incident-responder/SKILL.md +79 -113
  83. package/.agent/skills/doc.md +5 -5
  84. package/.agent/skills/documentation-templates/SKILL.md +19 -63
  85. package/.agent/skills/edge-computing/SKILL.md +123 -157
  86. package/.agent/skills/extract-design-system/SKILL.md +100 -134
  87. package/.agent/skills/framer-motion-expert/SKILL.md +111 -855
  88. package/.agent/skills/frontend-design/SKILL.md +151 -499
  89. package/.agent/skills/game-design-expert/SKILL.md +71 -105
  90. package/.agent/skills/game-engineering-expert/SKILL.md +88 -122
  91. package/.agent/skills/geo-fundamentals/SKILL.md +89 -124
  92. package/.agent/skills/github-operations/SKILL.md +279 -314
  93. package/.agent/skills/gsap-expert/SKILL.md +119 -826
  94. package/.agent/skills/i18n-localization/SKILL.md +104 -138
  95. package/.agent/skills/intelligent-routing/SKILL.md +159 -127
  96. package/.agent/skills/lint-and-validate/SKILL.md +8 -52
  97. package/.agent/skills/llm-engineering/SKILL.md +344 -357
  98. package/.agent/skills/local-first/SKILL.md +120 -154
  99. package/.agent/skills/mcp-builder/SKILL.md +84 -118
  100. package/.agent/skills/mobile-design/SKILL.md +213 -219
  101. package/.agent/skills/motion-engineering/SKILL.md +184 -0
  102. package/.agent/skills/nextjs-react-expert/SKILL.md +99 -698
  103. package/.agent/skills/nodejs-best-practices/SKILL.md +498 -559
  104. package/.agent/skills/observability/SKILL.md +293 -330
  105. package/.agent/skills/parallel-agents/SKILL.md +88 -122
  106. package/.agent/skills/performance-profiling/SKILL.md +217 -254
  107. package/.agent/skills/plan-writing/SKILL.md +84 -118
  108. package/.agent/skills/platform-engineer/SKILL.md +89 -123
  109. package/.agent/skills/playwright-best-practices/SKILL.md +128 -162
  110. package/.agent/skills/powershell-windows/SKILL.md +112 -146
  111. package/.agent/skills/python-patterns/SKILL.md +7 -35
  112. package/.agent/skills/python-pro/SKILL.md +148 -754
  113. package/.agent/skills/react-specialist/SKILL.md +123 -827
  114. package/.agent/skills/readme-builder/SKILL.md +15 -85
  115. package/.agent/skills/realtime-patterns/SKILL.md +269 -304
  116. package/.agent/skills/red-team-tactics/SKILL.md +10 -51
  117. package/.agent/skills/rust-pro/SKILL.md +623 -701
  118. package/.agent/skills/seo-fundamentals/SKILL.md +120 -154
  119. package/.agent/skills/server-management/SKILL.md +156 -190
  120. package/.agent/skills/shadcn-ui-expert/SKILL.md +172 -206
  121. package/.agent/skills/skill-creator/SKILL.md +18 -58
  122. package/.agent/skills/sql-pro/SKILL.md +579 -633
  123. package/.agent/skills/supabase-postgres-best-practices/SKILL.md +28 -68
  124. package/.agent/skills/swiftui-expert/SKILL.md +142 -176
  125. package/.agent/skills/systematic-debugging/SKILL.md +84 -118
  126. package/.agent/skills/tailwind-patterns/SKILL.md +516 -576
  127. package/.agent/skills/tdd-workflow/SKILL.md +103 -137
  128. package/.agent/skills/test-result-analyzer/SKILL.md +33 -73
  129. package/.agent/skills/testing-patterns/SKILL.md +512 -573
  130. package/.agent/skills/trend-researcher/SKILL.md +30 -71
  131. package/.agent/skills/ui-ux-pro-max/SKILL.md +0 -41
  132. package/.agent/skills/ui-ux-researcher/SKILL.md +51 -91
  133. package/.agent/skills/vue-expert/SKILL.md +127 -866
  134. package/.agent/skills/vulnerability-scanner/SKILL.md +354 -269
  135. package/.agent/skills/web-accessibility-auditor/SKILL.md +159 -193
  136. package/.agent/skills/web-design-guidelines/SKILL.md +17 -61
  137. package/.agent/skills/webapp-testing/SKILL.md +111 -145
  138. package/.agent/skills/whimsy-injector/SKILL.md +58 -132
  139. package/.agent/skills/workflow-optimizer/SKILL.md +28 -68
  140. package/.agent/workflows/api-tester.md +151 -151
  141. package/.agent/workflows/audit.md +127 -138
  142. package/.agent/workflows/brainstorm.md +110 -110
  143. package/.agent/workflows/changelog.md +112 -112
  144. package/.agent/workflows/create.md +124 -124
  145. package/.agent/workflows/debug.md +165 -189
  146. package/.agent/workflows/deploy.md +180 -189
  147. package/.agent/workflows/enhance.md +128 -151
  148. package/.agent/workflows/fix.md +114 -135
  149. package/.agent/workflows/generate.md +12 -4
  150. package/.agent/workflows/migrate.md +160 -160
  151. package/.agent/workflows/orchestrate.md +168 -168
  152. package/.agent/workflows/performance-benchmarker.md +114 -123
  153. package/.agent/workflows/plan.md +173 -173
  154. package/.agent/workflows/preview.md +80 -80
  155. package/.agent/workflows/refactor.md +161 -183
  156. package/.agent/workflows/review-ai.md +101 -129
  157. package/.agent/workflows/review.md +116 -116
  158. package/.agent/workflows/session.md +94 -94
  159. package/.agent/workflows/status.md +79 -79
  160. package/.agent/workflows/strengthen-skills.md +138 -139
  161. package/.agent/workflows/swarm.md +179 -179
  162. package/.agent/workflows/test.md +189 -211
  163. package/.agent/workflows/tribunal-backend.md +93 -113
  164. package/.agent/workflows/tribunal-database.md +94 -115
  165. package/.agent/workflows/tribunal-frontend.md +95 -118
  166. package/.agent/workflows/tribunal-full.md +92 -133
  167. package/.agent/workflows/tribunal-mobile.md +94 -119
  168. package/.agent/workflows/tribunal-performance.md +109 -133
  169. package/.agent/workflows/ui-ux-pro-max.md +122 -143
  170. package/package.json +1 -1
  171. package/.agent/skills/api-patterns/api-style.md +0 -42
  172. package/.agent/skills/api-patterns/auth.md +0 -24
  173. package/.agent/skills/api-patterns/documentation.md +0 -26
  174. package/.agent/skills/api-patterns/graphql.md +0 -41
  175. package/.agent/skills/api-patterns/rate-limiting.md +0 -31
  176. package/.agent/skills/api-patterns/response.md +0 -37
  177. package/.agent/skills/api-patterns/rest.md +0 -40
  178. package/.agent/skills/api-patterns/security-testing.md +0 -122
  179. package/.agent/skills/api-patterns/trpc.md +0 -41
  180. package/.agent/skills/api-patterns/versioning.md +0 -22
  181. package/.agent/skills/app-builder/agent-coordination.md +0 -71
  182. package/.agent/skills/app-builder/feature-building.md +0 -53
  183. package/.agent/skills/app-builder/project-detection.md +0 -34
  184. package/.agent/skills/app-builder/scaffolding.md +0 -118
  185. package/.agent/skills/app-builder/tech-stack.md +0 -40
  186. package/.agent/skills/architecture/context-discovery.md +0 -43
  187. package/.agent/skills/architecture/examples.md +0 -94
  188. package/.agent/skills/architecture/pattern-selection.md +0 -68
  189. package/.agent/skills/architecture/patterns-reference.md +0 -50
  190. package/.agent/skills/architecture/trade-off-analysis.md +0 -77
  191. package/.agent/skills/brainstorming/dynamic-questioning.md +0 -360
  192. package/.agent/skills/database-design/database-selection.md +0 -43
  193. package/.agent/skills/database-design/indexing.md +0 -39
  194. package/.agent/skills/database-design/migrations.md +0 -48
  195. package/.agent/skills/database-design/optimization.md +0 -36
  196. package/.agent/skills/database-design/orm-selection.md +0 -30
  197. package/.agent/skills/database-design/schema-design.md +0 -56
  198. package/.agent/skills/frontend-design/animation-guide.md +0 -331
  199. package/.agent/skills/frontend-design/color-system.md +0 -329
  200. package/.agent/skills/frontend-design/decision-trees.md +0 -418
  201. package/.agent/skills/frontend-design/motion-graphics.md +0 -306
  202. package/.agent/skills/frontend-design/typography-system.md +0 -363
  203. package/.agent/skills/frontend-design/ux-psychology.md +0 -1116
  204. package/.agent/skills/frontend-design/visual-effects.md +0 -383
  205. package/.agent/skills/intelligent-routing/router-manifest.md +0 -65
  206. package/.agent/skills/mobile-design/decision-trees.md +0 -516
  207. package/.agent/skills/mobile-design/mobile-backend.md +0 -491
  208. package/.agent/skills/mobile-design/mobile-color-system.md +0 -420
  209. package/.agent/skills/mobile-design/mobile-debugging.md +0 -122
  210. package/.agent/skills/mobile-design/mobile-design-thinking.md +0 -357
  211. package/.agent/skills/mobile-design/mobile-navigation.md +0 -458
  212. package/.agent/skills/mobile-design/mobile-performance.md +0 -767
  213. package/.agent/skills/mobile-design/mobile-testing.md +0 -356
  214. package/.agent/skills/mobile-design/mobile-typography.md +0 -433
  215. package/.agent/skills/mobile-design/platform-android.md +0 -666
  216. package/.agent/skills/mobile-design/platform-ios.md +0 -561
  217. package/.agent/skills/mobile-design/touch-psychology.md +0 -537
  218. package/.agent/skills/nextjs-react-expert/1-async-eliminating-waterfalls.md +0 -312
  219. package/.agent/skills/nextjs-react-expert/2-bundle-bundle-size-optimization.md +0 -240
  220. package/.agent/skills/nextjs-react-expert/3-server-server-side-performance.md +0 -490
  221. package/.agent/skills/nextjs-react-expert/4-client-client-side-data-fetching.md +0 -264
  222. package/.agent/skills/nextjs-react-expert/5-rerender-re-render-optimization.md +0 -581
  223. package/.agent/skills/nextjs-react-expert/6-rendering-rendering-performance.md +0 -432
  224. package/.agent/skills/nextjs-react-expert/7-js-javascript-performance.md +0 -684
  225. package/.agent/skills/nextjs-react-expert/8-advanced-advanced-patterns.md +0 -150
  226. package/.agent/skills/vulnerability-scanner/checklists.md +0 -121
@@ -1,701 +1,623 @@
1
- ---
2
- name: rust-pro
3
- description: Master Rust 1.75+ with modern async patterns, ownership/borrowing, lifetimes, traits, error handling with thiserror/anyhow, async Tokio runtime, axum web framework, serde serialization, and systems programming. Use when building Rust services, CLI tools, WebAssembly, or performance-critical systems.
4
- allowed-tools: Read, Write, Edit, Glob, Grep
5
- version: 2.0.0
6
- last-updated: 2026-03-30
7
- applies-to-model: gemini-2.5-pro, claude-3-7-sonnet
8
- ---
9
-
10
- # Rust Pro — Rust 1.75+ Systems Mastery
11
-
12
- > Rust doesn't have a garbage collector because YOU are the garbage collector.
13
- > Every `clone()` has a cost. Every `unwrap()` is a potential crash. Every lifetime annotation is a contract.
14
- > The borrow checker is not your enemy — it's your proof of correctness.
15
-
16
- ---
17
-
18
- ## Ownership & Borrowing
19
-
20
- ### The Three Rules
21
-
22
- ```rust
23
- // Rule 1: Each value has exactly ONE owner
24
- let s1 = String::from("hello");
25
- let s2 = s1; // s1 is MOVED to s2 — s1 is no longer valid
26
- // println!("{s1}"); // compile error: value borrowed after move
27
-
28
- // Rule 2: You can have EITHER one mutable reference OR any number of immutable references
29
- let mut data = vec![1, 2, 3];
30
- let r1 = &data; // immutable borrow
31
- let r2 = &data; // ✅ second immutable borrow — fine
32
- // let r3 = &mut data; // ❌ compile error: cannot borrow as mutable while immutable borrows exist
33
- println!("{r1:?} {r2:?}");
34
- // r1 and r2 go out of scope here (NLL Non-Lexical Lifetimes)
35
- let r3 = &mut data; // now fine — no immutable borrows active
36
- r3.push(4);
37
-
38
- // Rule 3: References must always be valid (no dangling pointers)
39
- // fn dangling() -> &String { // ❌ compile error
40
- // let s = String::from("hello");
41
- // &s // s is dropped at end of function — reference would dangle
42
- // }
43
- fn not_dangling() -> String {
44
- String::from("hello") // return owned value
45
- }
46
- ```
47
-
48
- ### Common Ownership Patterns
49
-
50
- ```rust
51
- // Clone when you need independent copies (has a cost — measure)
52
- let original = vec![1, 2, 3];
53
- let copy = original.clone(); // deep copy — both are independent
54
-
55
- // Rc<T> shared ownership (single-threaded)
56
- use std::rc::Rc;
57
- let shared = Rc::new(vec![1, 2, 3]);
58
- let also_shared = Rc::clone(&shared); // cheap reference count increment
59
- // Both shared and also_shared point to the same data
60
-
61
- // Arc<T> — shared ownership (thread-safe)
62
- use std::sync::Arc;
63
- let thread_safe = Arc::new(vec![1, 2, 3]);
64
- let for_thread = Arc::clone(&thread_safe);
65
- std::thread::spawn(move || {
66
- println!("{for_thread:?}");
67
- });
68
-
69
- // Cow<T> Clone on Write (zero-copy when not modified)
70
- use std::borrow::Cow;
71
- fn process(input: &str) -> Cow<'_, str> {
72
- if input.contains("bad") {
73
- Cow::Owned(input.replace("bad", "good")) // allocated only if needed
74
- } else {
75
- Cow::Borrowed(input) // zero-copy
76
- }
77
- }
78
- ```
79
-
80
- ---
81
-
82
- ## Lifetimes
83
-
84
- ```rust
85
- // Lifetime annotations tell the compiler how long references are valid
86
- // They DON'T change how long values live they DESCRIBE existing relationships
87
-
88
- // ✅ Explicit lifetime: return value lives as long as the input
89
- fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
90
- if x.len() > y.len() { x } else { y }
91
- }
92
-
93
- // Struct with references (requires lifetime annotation)
94
- struct Config<'a> {
95
- name: &'a str,
96
- version: &'a str,
97
- }
98
-
99
- impl<'a> Config<'a> {
100
- fn display(&self) -> String {
101
- format!("{} v{}", self.name, self.version)
102
- }
103
- }
104
-
105
- // 'static lifetime — lives for the entire program
106
- let s: &'static str = "I live forever"; // string literals are 'static
107
- // Owned types satisfy 'static (they own their data)
108
- fn takes_static(s: String) { /* String is 'static because it owns its data */ }
109
-
110
- // ❌ HALLUCINATION TRAP: Lifetime elision rules handle most cases
111
- // Don't add lifetimes unless the compiler asks for them
112
- // The compiler tells you exactly which annotations are needed
113
- ```
114
-
115
- ---
116
-
117
- ## Error Handling
118
-
119
- ### The `?` Operator & Result
120
-
121
- ```rust
122
- use std::fs;
123
- use std::io;
124
-
125
- // ✅ Propagate errors with ?
126
- fn read_config(path: &str) -> Result<Config, io::Error> {
127
- let content = fs::read_to_string(path)?; // returns early on error
128
- let config: Config = serde_json::from_str(&content)?;
129
- Ok(config)
130
- }
131
-
132
- // HALLUCINATION TRAP: NEVER use .unwrap() in production code
133
- // .unwrap() panics on error crashes the entire program
134
- // ❌ let file = File::open("config.json").unwrap();
135
- // ✅ let file = File::open("config.json")?;
136
- // let file = File::open("config.json").unwrap_or_default();
137
- // ✅ let file = File::open("config.json").map_err(|e| AppError::Io(e))?;
138
- ```
139
-
140
- ### thiserror (Library Errors)
141
-
142
- ```rust
143
- // thiserror for library code (structured error types)
144
- use thiserror::Error;
145
-
146
- #[derive(Debug, Error)]
147
- pub enum AppError {
148
- #[error("Database error: {0}")]
149
- Database(#[from] sqlx::Error),
150
-
151
- #[error("Validation error: {field} — {message}")]
152
- Validation { field: String, message: String },
153
-
154
- #[error("Not found: {0}")]
155
- NotFound(String),
156
-
157
- #[error("Unauthorized")]
158
- Unauthorized,
159
-
160
- #[error("IO error: {0}")]
161
- Io(#[from] std::io::Error),
162
-
163
- #[error("JSON error: {0}")]
164
- Json(#[from] serde_json::Error),
165
- }
166
-
167
- // #[from] auto-implements From<sqlx::Error> for AppError
168
- // So sqlx errors can be propagated with ? automatically
169
- ```
170
-
171
- ### anyhow (Application Errors)
172
-
173
- ```rust
174
- // anyhow for application code (quick error propagation)
175
- use anyhow::{Context, Result, bail, ensure};
176
-
177
- fn load_config(path: &str) -> Result<Config> {
178
- let content = fs::read_to_string(path)
179
- .context(format!("Failed to read config from {path}"))?;
180
-
181
- let config: Config = serde_json::from_str(&content)
182
- .context("Invalid JSON in config file")?;
183
-
184
- ensure!(config.port > 0, "Port must be positive, got {}", config.port);
185
-
186
- if config.name.is_empty() {
187
- bail!("Config name cannot be empty");
188
- }
189
-
190
- Ok(config)
191
- }
192
-
193
- // Use thiserror for libraries, anyhow for applications
194
- // ❌ HALLUCINATION TRAP: Don't use anyhow in library crates
195
- // Libraries should expose structured error types (thiserror)
196
- // anyhow erases type information — callers can't match on specific errors
197
- ```
198
-
199
- ---
200
-
201
- ## Traits
202
-
203
- ### Defining & Implementing
204
-
205
- ```rust
206
- trait Summarizable {
207
- fn summary(&self) -> String;
208
-
209
- // Default implementation
210
- fn preview(&self) -> String {
211
- let s = self.summary();
212
- if s.len() > 50 {
213
- format!("{}...", &s[..50])
214
- } else {
215
- s
216
- }
217
- }
218
- }
219
-
220
- struct Article {
221
- title: String,
222
- body: String,
223
- author: String,
224
- }
225
-
226
- impl Summarizable for Article {
227
- fn summary(&self) -> String {
228
- format!("{} by {} — {}", self.title, self.author, &self.body[..100.min(self.body.len())])
229
- }
230
- }
231
-
232
- // Trait bounds
233
- fn notify(item: &impl Summarizable) {
234
- println!("Breaking: {}", item.summary());
235
- }
236
-
237
- // Equivalent with generics (more flexible)
238
- fn notify_generic<T: Summarizable + std::fmt::Display>(item: &T) {
239
- println!("Breaking: {}", item.summary());
240
- }
241
-
242
- // where clause (cleaner for complex bounds)
243
- fn process<T, U>(t: &T, u: &U) -> String
244
- where
245
- T: Summarizable + Clone,
246
- U: std::fmt::Debug + Send,
247
- {
248
- format!("{} {:?}", t.summary(), u)
249
- }
250
-
251
- // Return impl Trait (hide concrete type)
252
- fn make_summarizer() -> impl Summarizable {
253
- Article { title: "News".into(), body: "Content".into(), author: "Author".into() }
254
- }
255
- ```
256
-
257
- ### Common Standard Traits
258
-
259
- ```rust
260
- // Derive common traits
261
- #[derive(Debug, Clone, PartialEq, Eq, Hash)]
262
- struct Point {
263
- x: i32,
264
- y: i32,
265
- }
266
-
267
- // Display for user-facing output
268
- use std::fmt;
269
- impl fmt::Display for Point {
270
- fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
271
- write!(f, "({}, {})", self.x, self.y)
272
- }
273
- }
274
-
275
- // From/Into — type conversion
276
- impl From<(i32, i32)> for Point {
277
- fn from((x, y): (i32, i32)) -> Self {
278
- Point { x, y }
279
- }
280
- }
281
- let p: Point = (10, 20).into(); // uses From automatically
282
-
283
- // Iterator
284
- struct Counter { count: u32, max: u32 }
285
- impl Iterator for Counter {
286
- type Item = u32;
287
- fn next(&mut self) -> Option<Self::Item> {
288
- if self.count < self.max {
289
- self.count += 1;
290
- Some(self.count)
291
- } else {
292
- None
293
- }
294
- }
295
- }
296
- ```
297
-
298
- ---
299
-
300
- ## Async with Tokio
301
-
302
- ### Runtime Setup
303
-
304
- ```rust
305
- // Cargo.toml
306
- // [dependencies]
307
- // tokio = { version = "1", features = ["full"] }
308
-
309
- #[tokio::main]
310
- async fn main() {
311
- let result = fetch_data("https://api.example.com/data").await;
312
- println!("{result:?}");
313
- }
314
-
315
- // For library code — don't use #[tokio::main], let the caller choose the runtime
316
- pub async fn fetch_data(url: &str) -> Result<String> {
317
- let response = reqwest::get(url).await?;
318
- let body = response.text().await?;
319
- Ok(body)
320
- }
321
- ```
322
-
323
- ### Concurrent Tasks
324
-
325
- ```rust
326
- use tokio::task;
327
-
328
- // Spawn concurrent tasks
329
- async fn parallel_fetch() -> Result<(Users, Posts)> {
330
- let users_handle = task::spawn(async { fetch_users().await });
331
- let posts_handle = task::spawn(async { fetch_posts().await });
332
-
333
- let users = users_handle.await??; // first ? for JoinError, second for app error
334
- let posts = posts_handle.await??;
335
-
336
- Ok((users, posts))
337
- }
338
-
339
- // tokio::join! — run concurrently, wait for all
340
- async fn fetch_all() -> Result<(Users, Posts, Analytics)> {
341
- let (users, posts, analytics) = tokio::join!(
342
- fetch_users(),
343
- fetch_posts(),
344
- fetch_analytics(),
345
- );
346
- Ok((users?, posts?, analytics?))
347
- }
348
-
349
- // tokio::select! race multiple futures, take first to complete
350
- async fn fetch_with_timeout(url: &str) -> Result<String> {
351
- tokio::select! {
352
- result = fetch_data(url) => result,
353
- _ = tokio::time::sleep(Duration::from_secs(5)) => {
354
- Err(anyhow!("Request timed out after 5s"))
355
- }
356
- }
357
- }
358
-
359
- // HALLUCINATION TRAP: tokio::spawn requires 'static + Send
360
- // You cannot spawn a task referencing local variables without Arc/clone
361
- // let data = &local_data;
362
- // tokio::spawn(async { process(data) }); // ❌ data doesn't live long enough
363
- // ✅ let data = Arc::new(local_data);
364
- // let data_clone = Arc::clone(&data);
365
- // tokio::spawn(async move { process(&data_clone) });
366
- ```
367
-
368
- ### Channels
369
-
370
- ```rust
371
- use tokio::sync::{mpsc, oneshot, broadcast};
372
-
373
- // mpsc — Multiple Producer, Single Consumer
374
- async fn worker_pattern() {
375
- let (tx, mut rx) = mpsc::channel::<String>(32); // buffer size
376
-
377
- tokio::spawn(async move {
378
- tx.send("hello".to_string()).await.unwrap();
379
- tx.send("world".to_string()).await.unwrap();
380
- });
381
-
382
- while let Some(msg) = rx.recv().await {
383
- println!("Got: {msg}");
384
- }
385
- }
386
-
387
- // oneshot — single response (request/response pattern)
388
- async fn request_response() {
389
- let (tx, rx) = oneshot::channel::<String>();
390
-
391
- tokio::spawn(async move {
392
- let result = expensive_computation().await;
393
- tx.send(result).unwrap();
394
- });
395
-
396
- let response = rx.await.unwrap();
397
- }
398
-
399
- // Mutex (async-safe)
400
- use tokio::sync::Mutex;
401
- let shared_state = Arc::new(Mutex::new(Vec::new()));
402
-
403
- let state = Arc::clone(&shared_state);
404
- tokio::spawn(async move {
405
- let mut guard = state.lock().await;
406
- guard.push("item");
407
- }); // lock released when guard is dropped
408
- ```
409
-
410
- ---
411
-
412
- ## Axum Web Framework
413
-
414
- ### Basic Server
415
-
416
- ```rust
417
- use axum::{
418
- extract::{Path, Query, State, Json},
419
- http::StatusCode,
420
- response::IntoResponse,
421
- routing::{get, post, delete},
422
- Router,
423
- };
424
- use serde::{Deserialize, Serialize};
425
-
426
- #[derive(Clone)]
427
- struct AppState {
428
- db: sqlx::PgPool,
429
- }
430
-
431
- #[tokio::main]
432
- async fn main() {
433
- let pool = sqlx::PgPool::connect("postgres://localhost/mydb").await.unwrap();
434
- let state = AppState { db: pool };
435
-
436
- let app = Router::new()
437
- .route("/users", get(list_users).post(create_user))
438
- .route("/users/{id}", get(get_user).delete(delete_user))
439
- .with_state(state);
440
-
441
- let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
442
- axum::serve(listener, app).await.unwrap();
443
- }
444
-
445
- // ❌ HALLUCINATION TRAP: axum 0.7+ uses {id} not :id for path params
446
- // ❌ .route("/users/:id", ...) ← old syntax
447
- // ✅ .route("/users/{id}", ...) ← axum 0.7+
448
- ```
449
-
450
- ### Handlers
451
-
452
- ```rust
453
- #[derive(Deserialize)]
454
- struct ListParams {
455
- page: Option<u32>,
456
- limit: Option<u32>,
457
- }
458
-
459
- async fn list_users(
460
- State(state): State<AppState>,
461
- Query(params): Query<ListParams>,
462
- ) -> Result<Json<Vec<User>>, AppError> {
463
- let page = params.page.unwrap_or(1);
464
- let limit = params.limit.unwrap_or(20).min(100);
465
- let offset = (page - 1) * limit;
466
-
467
- let users = sqlx::query_as!(
468
- User,
469
- "SELECT id, name, email FROM users ORDER BY id LIMIT $1 OFFSET $2",
470
- limit as i64,
471
- offset as i64,
472
- )
473
- .fetch_all(&state.db)
474
- .await?;
475
-
476
- Ok(Json(users))
477
- }
478
-
479
- #[derive(Deserialize)]
480
- struct CreateUserPayload {
481
- name: String,
482
- email: String,
483
- }
484
-
485
- async fn create_user(
486
- State(state): State<AppState>,
487
- Json(payload): Json<CreateUserPayload>,
488
- ) -> Result<(StatusCode, Json<User>), AppError> {
489
- let user = sqlx::query_as!(
490
- User,
491
- "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
492
- payload.name,
493
- payload.email,
494
- )
495
- .fetch_one(&state.db)
496
- .await?;
497
-
498
- Ok((StatusCode::CREATED, Json(user)))
499
- }
500
-
501
- async fn get_user(
502
- State(state): State<AppState>,
503
- Path(id): Path<i32>,
504
- ) -> Result<Json<User>, AppError> {
505
- let user = sqlx::query_as!(User, "SELECT id, name, email FROM users WHERE id = $1", id)
506
- .fetch_optional(&state.db)
507
- .await?
508
- .ok_or(AppError::NotFound(format!("User {id}")))?;
509
-
510
- Ok(Json(user))
511
- }
512
- ```
513
-
514
- ### Error Handling in Axum
515
-
516
- ```rust
517
- use axum::response::{IntoResponse, Response};
518
-
519
- #[derive(Debug, thiserror::Error)]
520
- pub enum AppError {
521
- #[error("Not found: {0}")]
522
- NotFound(String),
523
- #[error("Validation: {0}")]
524
- Validation(String),
525
- #[error("Database: {0}")]
526
- Database(#[from] sqlx::Error),
527
- #[error("Internal: {0}")]
528
- Internal(#[from] anyhow::Error),
529
- }
530
-
531
- impl IntoResponse for AppError {
532
- fn into_response(self) -> Response {
533
- let (status, message) = match &self {
534
- AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
535
- AppError::Validation(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
536
- AppError::Database(e) => {
537
- tracing::error!("DB error: {e}"); // log internal details
538
- (StatusCode::INTERNAL_SERVER_ERROR, "Database error".to_string())
539
- }
540
- AppError::Internal(e) => {
541
- tracing::error!("Internal error: {e}");
542
- (StatusCode::INTERNAL_SERVER_ERROR, "Internal error".to_string())
543
- }
544
- };
545
-
546
- (status, Json(serde_json::json!({ "error": message }))).into_response()
547
- }
548
- }
549
- ```
550
-
551
- ---
552
-
553
- ## Serde (Serialization)
554
-
555
- ```rust
556
- use serde::{Deserialize, Serialize};
557
-
558
- #[derive(Debug, Serialize, Deserialize)]
559
- #[serde(rename_all = "camelCase")] // JSON uses camelCase
560
- struct UserResponse {
561
- user_id: i32, // serialized as "userId"
562
- full_name: String, // serialized as "fullName"
563
- email: String,
564
-
565
- #[serde(skip_serializing_if = "Option::is_none")]
566
- phone: Option<String>, // omitted from JSON if None
567
-
568
- #[serde(default)] // defaults to 0 if missing in input
569
- login_count: u32,
570
-
571
- #[serde(rename = "type")] // rename for reserved keywords
572
- user_type: String,
573
-
574
- #[serde(skip)] // never serialized/deserialized
575
- internal_token: String,
576
- }
577
-
578
- // Enum serialization
579
- #[derive(Serialize, Deserialize)]
580
- #[serde(tag = "type", content = "data")] // adjacently tagged
581
- enum Event {
582
- #[serde(rename = "user_created")]
583
- UserCreated { id: i32, name: String },
584
- #[serde(rename = "user_deleted")]
585
- UserDeleted { id: i32 },
586
- }
587
- // Serializes as: {"type": "user_created", "data": {"id": 1, "name": "Alice"}}
588
- ```
589
-
590
- ---
591
-
592
- ## Iterator Patterns
593
-
594
- ```rust
595
- let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
596
-
597
- // Chain operations (lazy — no allocation until collect)
598
- let result: Vec<i32> = numbers.iter()
599
- .filter(|&&n| n % 2 == 0) // keep even
600
- .map(|&n| n * n) // square
601
- .take(3) // first 3
602
- .collect(); // [4, 16, 36]
603
-
604
- // fold (reduce)
605
- let sum: i32 = numbers.iter().fold(0, |acc, &n| acc + n);
606
-
607
- // find / position
608
- let first_even = numbers.iter().find(|&&n| n % 2 == 0); // Some(&2)
609
- let pos = numbers.iter().position(|&n| n > 5); // Some(5)
610
-
611
- // chunk / window
612
- let chunks: Vec<&[i32]> = numbers.chunks(3).collect();
613
- // [[1,2,3], [4,5,6], [7,8,9], [10]]
614
-
615
- let windows: Vec<&[i32]> = numbers.windows(3).collect();
616
- // [[1,2,3], [2,3,4], [3,4,5], ...]
617
-
618
- // Collecting into HashMap
619
- use std::collections::HashMap;
620
- let word_counts: HashMap<&str, usize> = words.iter()
621
- .fold(HashMap::new(), |mut map, word| {
622
- *map.entry(word.as_str()).or_insert(0) += 1;
623
- map
624
- });
625
- ```
626
-
627
- ---
628
-
629
- ## Output Format
630
-
631
- When this skill produces or reviews code, structure your output as follows:
632
-
633
- ```
634
- ━━━ Rust Pro Report ━━━━━━━━━━━━━━━━━━━━━━━━
635
- Skill: Rust Pro
636
- Rust Ver: 1.75+
637
- Scope: [N files · N functions]
638
- ─────────────────────────────────────────────────
639
- ✅ Passed: [checks that passed, or "All clean"]
640
- ⚠️ Warnings: [non-blocking issues, or "None"]
641
- ❌ Blocked: [blocking issues requiring fix, or "None"]
642
- ─────────────────────────────────────────────────
643
- VBC status: PENDING → VERIFIED
644
- Evidence: [cargo build / cargo test / clippy output]
645
- ```
646
-
647
- **VBC (Verification-Before-Completion) is mandatory.**
648
- Do not mark status as VERIFIED until concrete terminal evidence is provided.
649
-
650
- ---
651
-
652
- ## 🤖 LLM-Specific Traps
653
-
654
- AI coding assistants often fall into specific bad habits when generating Rust code. These are strictly forbidden:
655
-
656
- 1. **`.unwrap()` in Production:** Never use `.unwrap()` or `.expect()` outside of tests and examples. Use `?`, `match`, `unwrap_or`, `unwrap_or_else`, or `unwrap_or_default` for error handling.
657
- 2. **Unnecessary `.clone()`:** Don't clone to "fix" borrow checker errors. Restructure the code to avoid needing clones. Every clone has a cost — measure before accepting.
658
- 3. **`String` vs `&str` Confusion:** Use `&str` for function parameters (borrows, zero-copy). Use `String` for owned data (struct fields, return values). Never take `String` as a parameter when `&str` suffices.
659
- 4. **Blocking in Async:** Never use `std::thread::sleep()`, `std::fs::read()`, or synchronous HTTP clients inside `async` functions. Use `tokio::time::sleep()`, `tokio::fs::read()`, and `reqwest` (async).
660
- 5. **anyhow in Library Crates:** Libraries should use structured errors (thiserror). anyhow erases type information and prevents callers from matching on specific errors.
661
- 6. **Axum Path Syntax:** axum 0.7+ uses `{id}` for path parameters, NOT `:id`. Using `:id` compiles but doesn't extract parameters correctly.
662
- 7. **Missing `Send + 'static` Bounds:** `tokio::spawn` requires futures to be `Send + 'static`. Holding non-Send types (like `Rc`) across `.await` points causes compile errors.
663
- 8. **`Arc<Mutex<T>>` Without Need:** Don't reach for `Arc<Mutex<T>>` as default shared state. Consider channels (`mpsc`, `broadcast`), `tokio::sync::RwLock`, or atomic types first.
664
- 9. **Forgetting `?` Error Propagation:** Writing `match result { Ok(v) => v, Err(e) => return Err(e) }` instead of `result?`. The `?` operator is idiomatic and handles `From` conversion.
665
- 10. **Inventing Crate Names:** Only use real, published crates. There is no `rust-http`, `tokio-web`, or `async-json`. The correct crates are `reqwest`, `axum`/`actix-web`, and `serde_json`.
666
-
667
- ---
668
-
669
- ## 🏛️ Tribunal Integration (Anti-Hallucination)
670
-
671
- **Slash command: `/tribunal-backend`**
672
- **Active reviewers: `logic` · `security` · `dependency` · `type-safety`**
673
-
674
- ### ❌ Forbidden AI Tropes
675
-
676
- 1. **Blind Assumptions:** Never assume crate versions. Always check `Cargo.toml` with `// VERIFY: [crate version]`.
677
- 2. **Silent Degradation:** Using `.unwrap()` to suppress errors silently.
678
- 3. **Context Amnesia:** Forgetting whether the project uses Tokio or async-std, axum or actix-web.
679
- 4. **Over-Engineering:** Creating trait hierarchies and type-level programming where a simple enum suffices.
680
-
681
- ### ✅ Pre-Flight Self-Audit
682
-
683
- Review these questions before confirming output:
684
- ```
685
- ✅ Did I avoid .unwrap() in non-test code?
686
- ✅ Did I use &str for function parameters (not String)?
687
- ✅ Did I use thiserror for library errors (not anyhow)?
688
- ✅ Did I use async-compatible I/O (tokio::fs, reqwest)?
689
- ✅ Are spawned tasks Send + 'static?
690
- ✅ Did I use {id} syntax for axum 0.7+ path params?
691
- ✅ Did I derive necessary traits (Debug, Clone, Serialize)?
692
- ✅ Did I handle all Result/Option variants properly?
693
- ✅ Is every .clone() justified with a comment?
694
- ✅ Does cargo clippy pass with no warnings?
695
- ```
696
-
697
- ### 🛑 Verification-Before-Completion (VBC) Protocol
698
-
699
- **CRITICAL:** You must follow a strict "evidence-based closeout" state machine.
700
- - ❌ **Forbidden:** Declaring Rust code "correct" because it compiles. Compiling is necessary but not sufficient.
701
- - ✅ **Required:** You are explicitly forbidden from completing your task without providing **concrete terminal evidence** (e.g., `cargo build` success, `cargo test` pass, `cargo clippy` clean) proving the code is correct and idiomatic.
1
+ ---
2
+ name: rust-pro
3
+ description: Master Rust 1.75+ with modern async patterns, ownership/borrowing, lifetimes, traits, error handling with thiserror/anyhow, async Tokio runtime, axum web framework, serde serialization, and systems programming. Use when building Rust services, CLI tools, WebAssembly, or performance-critical systems.
4
+ allowed-tools: Read, Write, Edit, Glob, Grep
5
+ version: 2.0.0
6
+ last-updated: 2026-03-30
7
+ applies-to-model: gemini-2.5-pro, claude-3-7-sonnet
8
+ ---
9
+
10
+ # Rust Pro — Rust 1.75+ Systems Mastery
11
+
12
+ ---
13
+
14
+ ## Ownership & Borrowing
15
+
16
+ ### The Three Rules
17
+
18
+ ```rust
19
+ // Rule 1: Each value has exactly ONE owner
20
+ let s1 = String::from("hello");
21
+ let s2 = s1; // s1 is MOVED to s2 — s1 is no longer valid
22
+ // println!("{s1}"); // ❌ compile error: value borrowed after move
23
+
24
+ // Rule 2: You can have EITHER one mutable reference OR any number of immutable references
25
+ let mut data = vec![1, 2, 3];
26
+ let r1 = &data; // immutable borrow
27
+ let r2 = &data; // ✅ second immutable borrow — fine
28
+ // let r3 = &mut data; // compile error: cannot borrow as mutable while immutable borrows exist
29
+ println!("{r1:?} {r2:?}");
30
+ // r1 and r2 go out of scope here (NLL — Non-Lexical Lifetimes)
31
+ let r3 = &mut data; // ✅ now fine — no immutable borrows active
32
+ r3.push(4);
33
+
34
+ // Rule 3: References must always be valid (no dangling pointers)
35
+ // fn dangling() -> &String { // compile error
36
+ // let s = String::from("hello");
37
+ // &s // s is dropped at end of function — reference would dangle
38
+ // }
39
+ fn not_dangling() -> String {
40
+ String::from("hello") // ✅ return owned value
41
+ }
42
+ ```
43
+
44
+ ### Common Ownership Patterns
45
+
46
+ ```rust
47
+ // Clone when you need independent copies (has a cost — measure)
48
+ let original = vec![1, 2, 3];
49
+ let copy = original.clone(); // deep copy — both are independent
50
+
51
+ // Rc<T> shared ownership (single-threaded)
52
+ use std::rc::Rc;
53
+ let shared = Rc::new(vec![1, 2, 3]);
54
+ let also_shared = Rc::clone(&shared); // cheap reference count increment
55
+ // Both shared and also_shared point to the same data
56
+
57
+ // Arc<T> — shared ownership (thread-safe)
58
+ use std::sync::Arc;
59
+ let thread_safe = Arc::new(vec![1, 2, 3]);
60
+ let for_thread = Arc::clone(&thread_safe);
61
+ std::thread::spawn(move || {
62
+ println!("{for_thread:?}");
63
+ });
64
+
65
+ // Cow<T> — Clone on Write (zero-copy when not modified)
66
+ use std::borrow::Cow;
67
+ fn process(input: &str) -> Cow<'_, str> {
68
+ if input.contains("bad") {
69
+ Cow::Owned(input.replace("bad", "good")) // allocated only if needed
70
+ } else {
71
+ Cow::Borrowed(input) // zero-copy
72
+ }
73
+ }
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Lifetimes
79
+
80
+ ```rust
81
+ // Lifetime annotations tell the compiler how long references are valid
82
+ // They DON'T change how long values live — they DESCRIBE existing relationships
83
+
84
+ // ✅ Explicit lifetime: return value lives as long as the input
85
+ fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
86
+ if x.len() > y.len() { x } else { y }
87
+ }
88
+
89
+ // Struct with references (requires lifetime annotation)
90
+ struct Config<'a> {
91
+ name: &'a str,
92
+ version: &'a str,
93
+ }
94
+
95
+ impl<'a> Config<'a> {
96
+ fn display(&self) -> String {
97
+ format!("{} v{}", self.name, self.version)
98
+ }
99
+ }
100
+
101
+ // 'static lifetime — lives for the entire program
102
+ let s: &'static str = "I live forever"; // string literals are 'static
103
+ // Owned types satisfy 'static (they own their data)
104
+ fn takes_static(s: String) { /* String is 'static because it owns its data */ }
105
+
106
+ // HALLUCINATION TRAP: Lifetime elision rules handle most cases
107
+ // Don't add lifetimes unless the compiler asks for them
108
+ // The compiler tells you exactly which annotations are needed
109
+ ```
110
+
111
+ ---
112
+
113
+ ## Error Handling
114
+
115
+ ### The `?` Operator & Result
116
+
117
+ ```rust
118
+ use std::fs;
119
+ use std::io;
120
+
121
+ // ✅ Propagate errors with ?
122
+ fn read_config(path: &str) -> Result<Config, io::Error> {
123
+ let content = fs::read_to_string(path)?; // returns early on error
124
+ let config: Config = serde_json::from_str(&content)?;
125
+ Ok(config)
126
+ }
127
+
128
+ // ❌ HALLUCINATION TRAP: NEVER use .unwrap() in production code
129
+ // .unwrap() panics on error — crashes the entire program
130
+ // ❌ let file = File::open("config.json").unwrap();
131
+ // ✅ let file = File::open("config.json")?;
132
+ // let file = File::open("config.json").unwrap_or_default();
133
+ // let file = File::open("config.json").map_err(|e| AppError::Io(e))?;
134
+ ```
135
+
136
+ ### thiserror (Library Errors)
137
+
138
+ ```rust
139
+ // thiserror — for library code (structured error types)
140
+ use thiserror::Error;
141
+
142
+ #[derive(Debug, Error)]
143
+ pub enum AppError {
144
+ #[error("Database error: {0}")]
145
+ Database(#[from] sqlx::Error),
146
+
147
+ #[error("Validation error: {field} {message}")]
148
+ Validation { field: String, message: String },
149
+
150
+ #[error("Not found: {0}")]
151
+ NotFound(String),
152
+
153
+ #[error("Unauthorized")]
154
+ Unauthorized,
155
+
156
+ #[error("IO error: {0}")]
157
+ Io(#[from] std::io::Error),
158
+
159
+ #[error("JSON error: {0}")]
160
+ Json(#[from] serde_json::Error),
161
+ }
162
+
163
+ // #[from] auto-implements From<sqlx::Error> for AppError
164
+ // So sqlx errors can be propagated with ? automatically
165
+ ```
166
+
167
+ ### anyhow (Application Errors)
168
+
169
+ ```rust
170
+ // anyhow — for application code (quick error propagation)
171
+ use anyhow::{Context, Result, bail, ensure};
172
+
173
+ fn load_config(path: &str) -> Result<Config> {
174
+ let content = fs::read_to_string(path)
175
+ .context(format!("Failed to read config from {path}"))?;
176
+
177
+ let config: Config = serde_json::from_str(&content)
178
+ .context("Invalid JSON in config file")?;
179
+
180
+ ensure!(config.port > 0, "Port must be positive, got {}", config.port);
181
+
182
+ if config.name.is_empty() {
183
+ bail!("Config name cannot be empty");
184
+ }
185
+
186
+ Ok(config)
187
+ }
188
+
189
+ // Use thiserror for libraries, anyhow for applications
190
+ // ❌ HALLUCINATION TRAP: Don't use anyhow in library crates
191
+ // Libraries should expose structured error types (thiserror)
192
+ // anyhow erases type information — callers can't match on specific errors
193
+ ```
194
+
195
+ ---
196
+
197
+ ## Traits
198
+
199
+ ### Defining & Implementing
200
+
201
+ ```rust
202
+ trait Summarizable {
203
+ fn summary(&self) -> String;
204
+
205
+ // Default implementation
206
+ fn preview(&self) -> String {
207
+ let s = self.summary();
208
+ if s.len() > 50 {
209
+ format!("{}...", &s[..50])
210
+ } else {
211
+ s
212
+ }
213
+ }
214
+ }
215
+
216
+ struct Article {
217
+ title: String,
218
+ body: String,
219
+ author: String,
220
+ }
221
+
222
+ impl Summarizable for Article {
223
+ fn summary(&self) -> String {
224
+ format!("{} by {} — {}", self.title, self.author, &self.body[..100.min(self.body.len())])
225
+ }
226
+ }
227
+
228
+ // Trait bounds
229
+ fn notify(item: &impl Summarizable) {
230
+ println!("Breaking: {}", item.summary());
231
+ }
232
+
233
+ // Equivalent with generics (more flexible)
234
+ fn notify_generic<T: Summarizable + std::fmt::Display>(item: &T) {
235
+ println!("Breaking: {}", item.summary());
236
+ }
237
+
238
+ // where clause (cleaner for complex bounds)
239
+ fn process<T, U>(t: &T, u: &U) -> String
240
+ where
241
+ T: Summarizable + Clone,
242
+ U: std::fmt::Debug + Send,
243
+ {
244
+ format!("{} — {:?}", t.summary(), u)
245
+ }
246
+
247
+ // Return impl Trait (hide concrete type)
248
+ fn make_summarizer() -> impl Summarizable {
249
+ Article { title: "News".into(), body: "Content".into(), author: "Author".into() }
250
+ }
251
+ ```
252
+
253
+ ### Common Standard Traits
254
+
255
+ ```rust
256
+ // Derive common traits
257
+ #[derive(Debug, Clone, PartialEq, Eq, Hash)]
258
+ struct Point {
259
+ x: i32,
260
+ y: i32,
261
+ }
262
+
263
+ // Display — for user-facing output
264
+ use std::fmt;
265
+ impl fmt::Display for Point {
266
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267
+ write!(f, "({}, {})", self.x, self.y)
268
+ }
269
+ }
270
+
271
+ // From/Into type conversion
272
+ impl From<(i32, i32)> for Point {
273
+ fn from((x, y): (i32, i32)) -> Self {
274
+ Point { x, y }
275
+ }
276
+ }
277
+ let p: Point = (10, 20).into(); // uses From automatically
278
+
279
+ // Iterator
280
+ struct Counter { count: u32, max: u32 }
281
+ impl Iterator for Counter {
282
+ type Item = u32;
283
+ fn next(&mut self) -> Option<Self::Item> {
284
+ if self.count < self.max {
285
+ self.count += 1;
286
+ Some(self.count)
287
+ } else {
288
+ None
289
+ }
290
+ }
291
+ }
292
+ ```
293
+
294
+ ---
295
+
296
+ ## Async with Tokio
297
+
298
+ ### Runtime Setup
299
+
300
+ ```rust
301
+ // Cargo.toml
302
+ // [dependencies]
303
+ // tokio = { version = "1", features = ["full"] }
304
+
305
+ #[tokio::main]
306
+ async fn main() {
307
+ let result = fetch_data("https://api.example.com/data").await;
308
+ println!("{result:?}");
309
+ }
310
+
311
+ // For library code — don't use #[tokio::main], let the caller choose the runtime
312
+ pub async fn fetch_data(url: &str) -> Result<String> {
313
+ let response = reqwest::get(url).await?;
314
+ let body = response.text().await?;
315
+ Ok(body)
316
+ }
317
+ ```
318
+
319
+ ### Concurrent Tasks
320
+
321
+ ```rust
322
+ use tokio::task;
323
+
324
+ // Spawn concurrent tasks
325
+ async fn parallel_fetch() -> Result<(Users, Posts)> {
326
+ let users_handle = task::spawn(async { fetch_users().await });
327
+ let posts_handle = task::spawn(async { fetch_posts().await });
328
+
329
+ let users = users_handle.await??; // first ? for JoinError, second for app error
330
+ let posts = posts_handle.await??;
331
+
332
+ Ok((users, posts))
333
+ }
334
+
335
+ // tokio::join! — run concurrently, wait for all
336
+ async fn fetch_all() -> Result<(Users, Posts, Analytics)> {
337
+ let (users, posts, analytics) = tokio::join!(
338
+ fetch_users(),
339
+ fetch_posts(),
340
+ fetch_analytics(),
341
+ );
342
+ Ok((users?, posts?, analytics?))
343
+ }
344
+
345
+ // tokio::select! — race multiple futures, take first to complete
346
+ async fn fetch_with_timeout(url: &str) -> Result<String> {
347
+ tokio::select! {
348
+ result = fetch_data(url) => result,
349
+ _ = tokio::time::sleep(Duration::from_secs(5)) => {
350
+ Err(anyhow!("Request timed out after 5s"))
351
+ }
352
+ }
353
+ }
354
+
355
+ // ❌ HALLUCINATION TRAP: tokio::spawn requires 'static + Send
356
+ // You cannot spawn a task referencing local variables without Arc/clone
357
+ // ❌ let data = &local_data;
358
+ // tokio::spawn(async { process(data) }); // ❌ data doesn't live long enough
359
+ // let data = Arc::new(local_data);
360
+ // let data_clone = Arc::clone(&data);
361
+ // tokio::spawn(async move { process(&data_clone) });
362
+ ```
363
+
364
+ ### Channels
365
+
366
+ ```rust
367
+ use tokio::sync::{mpsc, oneshot, broadcast};
368
+
369
+ // mpsc — Multiple Producer, Single Consumer
370
+ async fn worker_pattern() {
371
+ let (tx, mut rx) = mpsc::channel::<String>(32); // buffer size
372
+
373
+ tokio::spawn(async move {
374
+ tx.send("hello".to_string()).await.unwrap();
375
+ tx.send("world".to_string()).await.unwrap();
376
+ });
377
+
378
+ while let Some(msg) = rx.recv().await {
379
+ println!("Got: {msg}");
380
+ }
381
+ }
382
+
383
+ // oneshot — single response (request/response pattern)
384
+ async fn request_response() {
385
+ let (tx, rx) = oneshot::channel::<String>();
386
+
387
+ tokio::spawn(async move {
388
+ let result = expensive_computation().await;
389
+ tx.send(result).unwrap();
390
+ });
391
+
392
+ let response = rx.await.unwrap();
393
+ }
394
+
395
+ // Mutex (async-safe)
396
+ use tokio::sync::Mutex;
397
+ let shared_state = Arc::new(Mutex::new(Vec::new()));
398
+
399
+ let state = Arc::clone(&shared_state);
400
+ tokio::spawn(async move {
401
+ let mut guard = state.lock().await;
402
+ guard.push("item");
403
+ }); // lock released when guard is dropped
404
+ ```
405
+
406
+ ---
407
+
408
+ ## Axum Web Framework
409
+
410
+ ### Basic Server
411
+
412
+ ```rust
413
+ use axum::{
414
+ extract::{Path, Query, State, Json},
415
+ http::StatusCode,
416
+ response::IntoResponse,
417
+ routing::{get, post, delete},
418
+ Router,
419
+ };
420
+ use serde::{Deserialize, Serialize};
421
+
422
+ #[derive(Clone)]
423
+ struct AppState {
424
+ db: sqlx::PgPool,
425
+ }
426
+
427
+ #[tokio::main]
428
+ async fn main() {
429
+ let pool = sqlx::PgPool::connect("postgres://localhost/mydb").await.unwrap();
430
+ let state = AppState { db: pool };
431
+
432
+ let app = Router::new()
433
+ .route("/users", get(list_users).post(create_user))
434
+ .route("/users/{id}", get(get_user).delete(delete_user))
435
+ .with_state(state);
436
+
437
+ let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
438
+ axum::serve(listener, app).await.unwrap();
439
+ }
440
+
441
+ // HALLUCINATION TRAP: axum 0.7+ uses {id} not :id for path params
442
+ // ❌ .route("/users/:id", ...) ← old syntax
443
+ // ✅ .route("/users/{id}", ...) ← axum 0.7+
444
+ ```
445
+
446
+ ### Handlers
447
+
448
+ ```rust
449
+ #[derive(Deserialize)]
450
+ struct ListParams {
451
+ page: Option<u32>,
452
+ limit: Option<u32>,
453
+ }
454
+
455
+ async fn list_users(
456
+ State(state): State<AppState>,
457
+ Query(params): Query<ListParams>,
458
+ ) -> Result<Json<Vec<User>>, AppError> {
459
+ let page = params.page.unwrap_or(1);
460
+ let limit = params.limit.unwrap_or(20).min(100);
461
+ let offset = (page - 1) * limit;
462
+
463
+ let users = sqlx::query_as!(
464
+ User,
465
+ "SELECT id, name, email FROM users ORDER BY id LIMIT $1 OFFSET $2",
466
+ limit as i64,
467
+ offset as i64,
468
+ )
469
+ .fetch_all(&state.db)
470
+ .await?;
471
+
472
+ Ok(Json(users))
473
+ }
474
+
475
+ #[derive(Deserialize)]
476
+ struct CreateUserPayload {
477
+ name: String,
478
+ email: String,
479
+ }
480
+
481
+ async fn create_user(
482
+ State(state): State<AppState>,
483
+ Json(payload): Json<CreateUserPayload>,
484
+ ) -> Result<(StatusCode, Json<User>), AppError> {
485
+ let user = sqlx::query_as!(
486
+ User,
487
+ "INSERT INTO users (name, email) VALUES ($1, $2) RETURNING id, name, email",
488
+ payload.name,
489
+ payload.email,
490
+ )
491
+ .fetch_one(&state.db)
492
+ .await?;
493
+
494
+ Ok((StatusCode::CREATED, Json(user)))
495
+ }
496
+
497
+ async fn get_user(
498
+ State(state): State<AppState>,
499
+ Path(id): Path<i32>,
500
+ ) -> Result<Json<User>, AppError> {
501
+ let user = sqlx::query_as!(User, "SELECT id, name, email FROM users WHERE id = $1", id)
502
+ .fetch_optional(&state.db)
503
+ .await?
504
+ .ok_or(AppError::NotFound(format!("User {id}")))?;
505
+
506
+ Ok(Json(user))
507
+ }
508
+ ```
509
+
510
+ ### Error Handling in Axum
511
+
512
+ ```rust
513
+ use axum::response::{IntoResponse, Response};
514
+
515
+ #[derive(Debug, thiserror::Error)]
516
+ pub enum AppError {
517
+ #[error("Not found: {0}")]
518
+ NotFound(String),
519
+ #[error("Validation: {0}")]
520
+ Validation(String),
521
+ #[error("Database: {0}")]
522
+ Database(#[from] sqlx::Error),
523
+ #[error("Internal: {0}")]
524
+ Internal(#[from] anyhow::Error),
525
+ }
526
+
527
+ impl IntoResponse for AppError {
528
+ fn into_response(self) -> Response {
529
+ let (status, message) = match &self {
530
+ AppError::NotFound(msg) => (StatusCode::NOT_FOUND, msg.clone()),
531
+ AppError::Validation(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
532
+ AppError::Database(e) => {
533
+ tracing::error!("DB error: {e}"); // log internal details
534
+ (StatusCode::INTERNAL_SERVER_ERROR, "Database error".to_string())
535
+ }
536
+ AppError::Internal(e) => {
537
+ tracing::error!("Internal error: {e}");
538
+ (StatusCode::INTERNAL_SERVER_ERROR, "Internal error".to_string())
539
+ }
540
+ };
541
+
542
+ (status, Json(serde_json::json!({ "error": message }))).into_response()
543
+ }
544
+ }
545
+ ```
546
+
547
+ ---
548
+
549
+ ## Serde (Serialization)
550
+
551
+ ```rust
552
+ use serde::{Deserialize, Serialize};
553
+
554
+ #[derive(Debug, Serialize, Deserialize)]
555
+ #[serde(rename_all = "camelCase")] // JSON uses camelCase
556
+ struct UserResponse {
557
+ user_id: i32, // serialized as "userId"
558
+ full_name: String, // serialized as "fullName"
559
+ email: String,
560
+
561
+ #[serde(skip_serializing_if = "Option::is_none")]
562
+ phone: Option<String>, // omitted from JSON if None
563
+
564
+ #[serde(default)] // defaults to 0 if missing in input
565
+ login_count: u32,
566
+
567
+ #[serde(rename = "type")] // rename for reserved keywords
568
+ user_type: String,
569
+
570
+ #[serde(skip)] // never serialized/deserialized
571
+ internal_token: String,
572
+ }
573
+
574
+ // Enum serialization
575
+ #[derive(Serialize, Deserialize)]
576
+ #[serde(tag = "type", content = "data")] // adjacently tagged
577
+ enum Event {
578
+ #[serde(rename = "user_created")]
579
+ UserCreated { id: i32, name: String },
580
+ #[serde(rename = "user_deleted")]
581
+ UserDeleted { id: i32 },
582
+ }
583
+ // Serializes as: {"type": "user_created", "data": {"id": 1, "name": "Alice"}}
584
+ ```
585
+
586
+ ---
587
+
588
+ ## Iterator Patterns
589
+
590
+ ```rust
591
+ let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
592
+
593
+ // Chain operations (lazy — no allocation until collect)
594
+ let result: Vec<i32> = numbers.iter()
595
+ .filter(|&&n| n % 2 == 0) // keep even
596
+ .map(|&n| n * n) // square
597
+ .take(3) // first 3
598
+ .collect(); // [4, 16, 36]
599
+
600
+ // fold (reduce)
601
+ let sum: i32 = numbers.iter().fold(0, |acc, &n| acc + n);
602
+
603
+ // find / position
604
+ let first_even = numbers.iter().find(|&&n| n % 2 == 0); // Some(&2)
605
+ let pos = numbers.iter().position(|&n| n > 5); // Some(5)
606
+
607
+ // chunk / window
608
+ let chunks: Vec<&[i32]> = numbers.chunks(3).collect();
609
+ // [[1,2,3], [4,5,6], [7,8,9], [10]]
610
+
611
+ let windows: Vec<&[i32]> = numbers.windows(3).collect();
612
+ // [[1,2,3], [2,3,4], [3,4,5], ...]
613
+
614
+ // Collecting into HashMap
615
+ use std::collections::HashMap;
616
+ let word_counts: HashMap<&str, usize> = words.iter()
617
+ .fold(HashMap::new(), |mut map, word| {
618
+ *map.entry(word.as_str()).or_insert(0) += 1;
619
+ map
620
+ });
621
+ ```
622
+
623
+