ndomo 0.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 (247) hide show
  1. package/.bun-version +1 -0
  2. package/.dockerignore +79 -0
  3. package/.editorconfig +18 -0
  4. package/.env.example +19 -0
  5. package/.github/CODEOWNERS +8 -0
  6. package/.github/ISSUE_TEMPLATE/bug_report.yml +62 -0
  7. package/.github/ISSUE_TEMPLATE/config.yml +2 -0
  8. package/.github/ISSUE_TEMPLATE/feature_request.yml +34 -0
  9. package/.github/dependabot.yml +36 -0
  10. package/.github/pull_request_template.md +24 -0
  11. package/.github/release.yml +30 -0
  12. package/.github/workflows/gitleaks.yml +28 -0
  13. package/.github/workflows/release-please.yml +27 -0
  14. package/.github/workflows/smoke.yml +29 -0
  15. package/.husky/commit-msg +1 -0
  16. package/CHANGELOG.md +114 -0
  17. package/Dockerfile +32 -0
  18. package/README.es.md +174 -0
  19. package/README.md +187 -0
  20. package/agents/chronicler.md +98 -0
  21. package/agents/ci-smith.md +136 -0
  22. package/agents/craftsman.md +341 -0
  23. package/agents/deploy-smith.md +138 -0
  24. package/agents/foreman.md +377 -0
  25. package/agents/go-smith.md +164 -0
  26. package/agents/guild.md +188 -0
  27. package/agents/inspector.md +83 -0
  28. package/agents/js-smith.md +127 -0
  29. package/agents/ops-scout.md +173 -0
  30. package/agents/painter.md +200 -0
  31. package/agents/python-smith.md +120 -0
  32. package/agents/ranger.md +307 -0
  33. package/agents/release-smith.md +165 -0
  34. package/agents/rust-smith.md +159 -0
  35. package/agents/sage.md +178 -0
  36. package/agents/scout.md +144 -0
  37. package/agents/scribe.md +156 -0
  38. package/agents/smith.md +201 -0
  39. package/agents/vue-smith.md +155 -0
  40. package/agents/warden.md +216 -0
  41. package/agents/zig-smith.md +156 -0
  42. package/bin/ndomo-analyses.ts +4 -0
  43. package/bin/ndomo-status.ts +4 -0
  44. package/biome.json +57 -0
  45. package/bun.lock +514 -0
  46. package/commitlint.config.js +3 -0
  47. package/config/ndomo.config.json +258 -0
  48. package/config/ndomo.schema.json +166 -0
  49. package/docs/agents.md +375 -0
  50. package/docs/bugs/plan-create-orphan-fk.md +131 -0
  51. package/docs/bugs/task_create_batch-order-index-collision.md +158 -0
  52. package/docs/configuration.md +276 -0
  53. package/docs/database.md +364 -0
  54. package/docs/features/feature-flexible-builder-v1.md +724 -0
  55. package/docs/features/feature-flexible-builder-v2.md +882 -0
  56. package/docs/features/feature-flexible-builder.md +974 -0
  57. package/docs/http-server.md +244 -0
  58. package/docs/installation.md +259 -0
  59. package/docs/integrations.md +129 -0
  60. package/docs/operations/anti-pattern-sub-agent-verify-2026-06-21.md +32 -0
  61. package/docs/operations/audit-v1.md +417 -0
  62. package/docs/operations/audit-v2.md +197 -0
  63. package/docs/operations/audit-v3.md +306 -0
  64. package/docs/operations/db-optimize-foundations.md +123 -0
  65. package/docs/operations/verify-gate-architecture.md +82 -0
  66. package/docs/workflows.md +448 -0
  67. package/opencode.json +5 -0
  68. package/package.json +65 -0
  69. package/release-please-config.json +11 -0
  70. package/scripts/dev-bust-cache.sh +164 -0
  71. package/scripts/install.sh +688 -0
  72. package/scripts/smoke-e2e.ts +704 -0
  73. package/scripts/smoke-hot.ts +417 -0
  74. package/scripts/smoke-http.sh +228 -0
  75. package/scripts/smoke-v4.ts +256 -0
  76. package/scripts/smoke-v5.ts +397 -0
  77. package/scripts/smoke.sh +9 -0
  78. package/scripts/uninstall.sh +224 -0
  79. package/skills/api-security-best-practices/SKILL.md +915 -0
  80. package/skills/bash-scripting/SKILL.md +201 -0
  81. package/skills/bun/SKILL.md +313 -0
  82. package/skills/cavecrew/SKILL.md +82 -0
  83. package/skills/caveman/SKILL.md +74 -0
  84. package/skills/caveman-review/README.md +33 -0
  85. package/skills/caveman-review/SKILL.md +55 -0
  86. package/skills/find-skills/SKILL.md +142 -0
  87. package/skills/frontend-design/LICENSE.txt +177 -0
  88. package/skills/frontend-design/SKILL.md +55 -0
  89. package/skills/golang-patterns/SKILL.md +674 -0
  90. package/skills/golang-security/SKILL.md +185 -0
  91. package/skills/golang-security/evals/evals.json +595 -0
  92. package/skills/golang-security/references/architecture.md +268 -0
  93. package/skills/golang-security/references/checklist.md +80 -0
  94. package/skills/golang-security/references/cookies.md +200 -0
  95. package/skills/golang-security/references/cryptography.md +424 -0
  96. package/skills/golang-security/references/filesystem.md +285 -0
  97. package/skills/golang-security/references/injection.md +315 -0
  98. package/skills/golang-security/references/logging.md +163 -0
  99. package/skills/golang-security/references/memory-safety.md +241 -0
  100. package/skills/golang-security/references/network.md +253 -0
  101. package/skills/golang-security/references/secrets.md +189 -0
  102. package/skills/golang-security/references/third-party.md +159 -0
  103. package/skills/golang-security/references/threat-modeling.md +189 -0
  104. package/skills/golang-testing/SKILL.md +720 -0
  105. package/skills/grill-me/SKILL.md +7 -0
  106. package/skills/javascript-testing-patterns/SKILL.md +537 -0
  107. package/skills/javascript-testing-patterns/references/advanced-testing-patterns.md +513 -0
  108. package/skills/modern-javascript-patterns/SKILL.md +43 -0
  109. package/skills/modern-javascript-patterns/references/advanced-patterns.md +487 -0
  110. package/skills/modern-javascript-patterns/references/details.md +457 -0
  111. package/skills/python-anti-patterns/SKILL.md +349 -0
  112. package/skills/python-design-patterns/SKILL.md +85 -0
  113. package/skills/python-design-patterns/references/details.md +353 -0
  114. package/skills/python-error-handling/SKILL.md +193 -0
  115. package/skills/python-error-handling/references/details.md +171 -0
  116. package/skills/python-testing-patterns/SKILL.md +278 -0
  117. package/skills/python-testing-patterns/references/advanced-patterns.md +411 -0
  118. package/skills/python-testing-patterns/references/details.md +349 -0
  119. package/skills/rust-patterns/SKILL.md +500 -0
  120. package/skills/rust-testing/SKILL.md +501 -0
  121. package/skills/security-review/SKILL.md +504 -0
  122. package/skills/security-review/cloud-infrastructure-security.md +361 -0
  123. package/skills/vue-best-practices/SKILL.md +154 -0
  124. package/skills/vue-best-practices/references/animation-class-based-technique.md +254 -0
  125. package/skills/vue-best-practices/references/animation-state-driven-technique.md +291 -0
  126. package/skills/vue-best-practices/references/component-async.md +97 -0
  127. package/skills/vue-best-practices/references/component-data-flow.md +307 -0
  128. package/skills/vue-best-practices/references/component-fallthrough-attrs.md +174 -0
  129. package/skills/vue-best-practices/references/component-keep-alive.md +137 -0
  130. package/skills/vue-best-practices/references/component-slots.md +216 -0
  131. package/skills/vue-best-practices/references/component-suspense.md +228 -0
  132. package/skills/vue-best-practices/references/component-teleport.md +108 -0
  133. package/skills/vue-best-practices/references/component-transition-group.md +128 -0
  134. package/skills/vue-best-practices/references/component-transition.md +125 -0
  135. package/skills/vue-best-practices/references/composables.md +290 -0
  136. package/skills/vue-best-practices/references/directives.md +162 -0
  137. package/skills/vue-best-practices/references/perf-avoid-component-abstraction-in-lists.md +159 -0
  138. package/skills/vue-best-practices/references/perf-v-once-v-memo-directives.md +182 -0
  139. package/skills/vue-best-practices/references/perf-virtualize-large-lists.md +187 -0
  140. package/skills/vue-best-practices/references/plugins.md +166 -0
  141. package/skills/vue-best-practices/references/reactivity.md +344 -0
  142. package/skills/vue-best-practices/references/render-functions.md +201 -0
  143. package/skills/vue-best-practices/references/sfc.md +310 -0
  144. package/skills/vue-best-practices/references/state-management.md +135 -0
  145. package/skills/vue-best-practices/references/updated-hook-performance.md +187 -0
  146. package/skills/vue-pinia-best-practices/SKILL.md +21 -0
  147. package/skills/vue-pinia-best-practices/reference/pinia-no-active-pinia-error.md +248 -0
  148. package/skills/vue-pinia-best-practices/reference/pinia-setup-store-return-all-state.md +227 -0
  149. package/skills/vue-pinia-best-practices/reference/pinia-store-destructuring-breaks-reactivity.md +193 -0
  150. package/skills/vue-pinia-best-practices/reference/state-url-for-ephemeral-filters.md +238 -0
  151. package/skills/vue-pinia-best-practices/reference/state-use-pinia-for-large-apps.md +262 -0
  152. package/skills/vue-pinia-best-practices/reference/store-method-binding-parentheses.md +191 -0
  153. package/skills/zig-0.16/SKILL.md +840 -0
  154. package/skills/zig-0.16/scripts/check-zig-version.sh +21 -0
  155. package/src/cli/analyses.ts +280 -0
  156. package/src/cli/index.ts +108 -0
  157. package/src/cli/serve.ts +192 -0
  158. package/src/cli/smoke.ts +131 -0
  159. package/src/cli/status.test.ts +204 -0
  160. package/src/cli/status.ts +263 -0
  161. package/src/cli/vacuum.test.ts +82 -0
  162. package/src/cli/vacuum.ts +96 -0
  163. package/src/config/schema.test.ts +88 -0
  164. package/src/config/schema.ts +64 -0
  165. package/src/db/analyses-migration.test.ts +210 -0
  166. package/src/db/analyses.test.ts +466 -0
  167. package/src/db/analyses.ts +375 -0
  168. package/src/db/auto-checkpoint.ts +131 -0
  169. package/src/db/client.test.ts +129 -0
  170. package/src/db/client.ts +55 -0
  171. package/src/db/fts-escape.ts +20 -0
  172. package/src/db/incidents.test.ts +201 -0
  173. package/src/db/incidents.ts +93 -0
  174. package/src/db/index.ts +86 -0
  175. package/src/db/migrations-v13.test.ts +141 -0
  176. package/src/db/migrations-v8.test.ts +301 -0
  177. package/src/db/migrations.ts +147 -0
  178. package/src/db/plan-archive.test.ts +180 -0
  179. package/src/db/plan-archive.ts +274 -0
  180. package/src/db/plan-create.test.ts +276 -0
  181. package/src/db/plan-create.ts +78 -0
  182. package/src/db/plan-files.test.ts +289 -0
  183. package/src/db/plan-update-status.ts +287 -0
  184. package/src/db/plans.test.ts +490 -0
  185. package/src/db/plans.ts +534 -0
  186. package/src/db/resolve-project-dir.test.ts +143 -0
  187. package/src/db/resolve-project-dir.ts +75 -0
  188. package/src/db/rollbacks.test.ts +150 -0
  189. package/src/db/rollbacks.ts +67 -0
  190. package/src/db/schema.ts +907 -0
  191. package/src/db/sessions.test.ts +80 -0
  192. package/src/db/sessions.ts +135 -0
  193. package/src/db/shutdown.test.ts +147 -0
  194. package/src/db/shutdown.ts +45 -0
  195. package/src/db/tasks.test.ts +921 -0
  196. package/src/db/tasks.ts +747 -0
  197. package/src/db/types.ts +619 -0
  198. package/src/http/__tests__/auth.test.ts +196 -0
  199. package/src/http/__tests__/routes.test.ts +465 -0
  200. package/src/http/__tests__/sse.test.ts +317 -0
  201. package/src/http/auth.ts +72 -0
  202. package/src/http/middleware/cors.ts +53 -0
  203. package/src/http/middleware/security-headers.ts +21 -0
  204. package/src/http/routes/events.ts +112 -0
  205. package/src/http/routes/health.ts +51 -0
  206. package/src/http/routes/plans.ts +66 -0
  207. package/src/http/routes/sessions.ts +50 -0
  208. package/src/http/routes/tasks.ts +60 -0
  209. package/src/http/server.ts +95 -0
  210. package/src/http/sse.ts +116 -0
  211. package/src/index.ts +37 -0
  212. package/src/lib.ts +65 -0
  213. package/src/mem/scoped.ts +65 -0
  214. package/src/orchestrator/background.test.ts +268 -0
  215. package/src/orchestrator/background.ts +293 -0
  216. package/src/orchestrator/memory-hook.ts +182 -0
  217. package/src/orchestrator/reconciler.ts +123 -0
  218. package/src/orchestrator/scheduler.test.ts +300 -0
  219. package/src/orchestrator/scheduler.ts +243 -0
  220. package/src/plugin.test.ts +2574 -0
  221. package/src/plugin.ts +1690 -0
  222. package/src/sdk/client.ts +66 -0
  223. package/src/worktrees/manager.ts +236 -0
  224. package/src/worktrees/state.ts +87 -0
  225. package/tests/integration/ranger-flow.test.ts +257 -0
  226. package/tools/analysis_archive.ts +28 -0
  227. package/tools/analysis_create.ts +55 -0
  228. package/tools/analysis_get.ts +33 -0
  229. package/tools/analysis_link_plan.ts +44 -0
  230. package/tools/analysis_list.ts +48 -0
  231. package/tools/analysis_search.ts +36 -0
  232. package/tools/analysis_update.ts +44 -0
  233. package/tools/plan_approve.ts +31 -0
  234. package/tools/plan_create.ts +58 -0
  235. package/tools/plan_get.ts +40 -0
  236. package/tools/plan_list.ts +37 -0
  237. package/tools/plan_search.ts +34 -0
  238. package/tools/plan_update_status.ts +71 -0
  239. package/tools/session_checkpoint.ts +31 -0
  240. package/tools/session_end.ts +26 -0
  241. package/tools/session_start.ts +43 -0
  242. package/tools/task_create_batch.ts +70 -0
  243. package/tools/task_list.ts +35 -0
  244. package/tools/task_next_for_agent.ts +30 -0
  245. package/tools/task_search.ts +34 -0
  246. package/tools/task_update_status.ts +37 -0
  247. package/tsconfig.json +31 -0
@@ -0,0 +1,500 @@
1
+ ---
2
+ name: rust-patterns
3
+ description: Idiomatic Rust patterns, ownership, error handling, traits, concurrency, and best practices for building safe, performant applications.
4
+ metadata:
5
+ origin: ECC
6
+ ---
7
+
8
+ # Rust Development Patterns
9
+
10
+ Idiomatic Rust patterns and best practices for building safe, performant, and maintainable applications.
11
+
12
+ ## When to Use
13
+
14
+ - Writing new Rust code
15
+ - Reviewing Rust code
16
+ - Refactoring existing Rust code
17
+ - Designing crate structure and module layout
18
+
19
+ ## How It Works
20
+
21
+ This skill enforces idiomatic Rust conventions across six key areas: ownership and borrowing to prevent data races at compile time, `Result`/`?` error propagation with `thiserror` for libraries and `anyhow` for applications, enums and exhaustive pattern matching to make illegal states unrepresentable, traits and generics for zero-cost abstraction, safe concurrency via `Arc<Mutex<T>>`, channels, and async/await, and minimal `pub` surfaces organized by domain.
22
+
23
+ ## Core Principles
24
+
25
+ ### 1. Ownership and Borrowing
26
+
27
+ Rust's ownership system prevents data races and memory bugs at compile time.
28
+
29
+ ```rust
30
+ // Good: Pass references when you don't need ownership
31
+ fn process(data: &[u8]) -> usize {
32
+ data.len()
33
+ }
34
+
35
+ // Good: Take ownership only when you need to store or consume
36
+ fn store(data: Vec<u8>) -> Record {
37
+ Record { payload: data }
38
+ }
39
+
40
+ // Bad: Cloning unnecessarily to avoid borrow checker
41
+ fn process_bad(data: &Vec<u8>) -> usize {
42
+ let cloned = data.clone(); // Wasteful — just borrow
43
+ cloned.len()
44
+ }
45
+ ```
46
+
47
+ ### Use `Cow` for Flexible Ownership
48
+
49
+ ```rust
50
+ use std::borrow::Cow;
51
+
52
+ fn normalize(input: &str) -> Cow<'_, str> {
53
+ if input.contains(' ') {
54
+ Cow::Owned(input.replace(' ', "_"))
55
+ } else {
56
+ Cow::Borrowed(input) // Zero-cost when no mutation needed
57
+ }
58
+ }
59
+ ```
60
+
61
+ ## Error Handling
62
+
63
+ ### Use `Result` and `?` — Never `unwrap()` in Production
64
+
65
+ ```rust
66
+ // Good: Propagate errors with context
67
+ use anyhow::{Context, Result};
68
+
69
+ fn load_config(path: &str) -> Result<Config> {
70
+ let content = std::fs::read_to_string(path)
71
+ .with_context(|| format!("failed to read config from {path}"))?;
72
+ let config: Config = toml::from_str(&content)
73
+ .with_context(|| format!("failed to parse config from {path}"))?;
74
+ Ok(config)
75
+ }
76
+
77
+ // Bad: Panics on error
78
+ fn load_config_bad(path: &str) -> Config {
79
+ let content = std::fs::read_to_string(path).unwrap(); // Panics!
80
+ toml::from_str(&content).unwrap()
81
+ }
82
+ ```
83
+
84
+ ### Library Errors with `thiserror`, Application Errors with `anyhow`
85
+
86
+ ```rust
87
+ // Library code: structured, typed errors
88
+ use thiserror::Error;
89
+
90
+ #[derive(Debug, Error)]
91
+ pub enum StorageError {
92
+ #[error("record not found: {id}")]
93
+ NotFound { id: String },
94
+ #[error("connection failed")]
95
+ Connection(#[from] std::io::Error),
96
+ #[error("invalid data: {0}")]
97
+ InvalidData(String),
98
+ }
99
+
100
+ // Application code: flexible error handling
101
+ use anyhow::{bail, Result};
102
+
103
+ fn run() -> Result<()> {
104
+ let config = load_config("app.toml")?;
105
+ if config.workers == 0 {
106
+ bail!("worker count must be > 0");
107
+ }
108
+ Ok(())
109
+ }
110
+ ```
111
+
112
+ ### `Option` Combinators Over Nested Matching
113
+
114
+ ```rust
115
+ // Good: Combinator chain
116
+ fn find_user_email(users: &[User], id: u64) -> Option<String> {
117
+ users.iter()
118
+ .find(|u| u.id == id)
119
+ .map(|u| u.email.clone())
120
+ }
121
+
122
+ // Bad: Deeply nested matching
123
+ fn find_user_email_bad(users: &[User], id: u64) -> Option<String> {
124
+ match users.iter().find(|u| u.id == id) {
125
+ Some(user) => match &user.email {
126
+ email => Some(email.clone()),
127
+ },
128
+ None => None,
129
+ }
130
+ }
131
+ ```
132
+
133
+ ## Enums and Pattern Matching
134
+
135
+ ### Model States as Enums
136
+
137
+ ```rust
138
+ // Good: Impossible states are unrepresentable
139
+ enum ConnectionState {
140
+ Disconnected,
141
+ Connecting { attempt: u32 },
142
+ Connected { session_id: String },
143
+ Failed { reason: String, retries: u32 },
144
+ }
145
+
146
+ fn handle(state: &ConnectionState) {
147
+ match state {
148
+ ConnectionState::Disconnected => connect(),
149
+ ConnectionState::Connecting { attempt } if *attempt > 3 => abort(),
150
+ ConnectionState::Connecting { .. } => wait(),
151
+ ConnectionState::Connected { session_id } => use_session(session_id),
152
+ ConnectionState::Failed { retries, .. } if *retries < 5 => retry(),
153
+ ConnectionState::Failed { reason, .. } => log_failure(reason),
154
+ }
155
+ }
156
+ ```
157
+
158
+ ### Exhaustive Matching — No Catch-All for Business Logic
159
+
160
+ ```rust
161
+ // Good: Handle every variant explicitly
162
+ match command {
163
+ Command::Start => start_service(),
164
+ Command::Stop => stop_service(),
165
+ Command::Restart => restart_service(),
166
+ // Adding a new variant forces handling here
167
+ }
168
+
169
+ // Bad: Wildcard hides new variants
170
+ match command {
171
+ Command::Start => start_service(),
172
+ _ => {} // Silently ignores Stop, Restart, and future variants
173
+ }
174
+ ```
175
+
176
+ ## Traits and Generics
177
+
178
+ ### Accept Generics, Return Concrete Types
179
+
180
+ ```rust
181
+ // Good: Generic input, concrete output
182
+ fn read_all(reader: &mut impl Read) -> std::io::Result<Vec<u8>> {
183
+ let mut buf = Vec::new();
184
+ reader.read_to_end(&mut buf)?;
185
+ Ok(buf)
186
+ }
187
+
188
+ // Good: Trait bounds for multiple constraints
189
+ fn process<T: Display + Send + 'static>(item: T) -> String {
190
+ format!("processed: {item}")
191
+ }
192
+ ```
193
+
194
+ ### Trait Objects for Dynamic Dispatch
195
+
196
+ ```rust
197
+ // Use when you need heterogeneous collections or plugin systems
198
+ trait Handler: Send + Sync {
199
+ fn handle(&self, request: &Request) -> Response;
200
+ }
201
+
202
+ struct Router {
203
+ handlers: Vec<Box<dyn Handler>>,
204
+ }
205
+
206
+ // Use generics when you need performance (monomorphization)
207
+ fn fast_process<H: Handler>(handler: &H, request: &Request) -> Response {
208
+ handler.handle(request)
209
+ }
210
+ ```
211
+
212
+ ### Newtype Pattern for Type Safety
213
+
214
+ ```rust
215
+ // Good: Distinct types prevent mixing up arguments
216
+ struct UserId(u64);
217
+ struct OrderId(u64);
218
+
219
+ fn get_order(user: UserId, order: OrderId) -> Result<Order> {
220
+ // Can't accidentally swap user and order IDs
221
+ todo!()
222
+ }
223
+
224
+ // Bad: Easy to swap arguments
225
+ fn get_order_bad(user_id: u64, order_id: u64) -> Result<Order> {
226
+ todo!()
227
+ }
228
+ ```
229
+
230
+ ## Structs and Data Modeling
231
+
232
+ ### Builder Pattern for Complex Construction
233
+
234
+ ```rust
235
+ struct ServerConfig {
236
+ host: String,
237
+ port: u16,
238
+ max_connections: usize,
239
+ }
240
+
241
+ impl ServerConfig {
242
+ fn builder(host: impl Into<String>, port: u16) -> ServerConfigBuilder {
243
+ ServerConfigBuilder { host: host.into(), port, max_connections: 100 }
244
+ }
245
+ }
246
+
247
+ struct ServerConfigBuilder { host: String, port: u16, max_connections: usize }
248
+
249
+ impl ServerConfigBuilder {
250
+ fn max_connections(mut self, n: usize) -> Self { self.max_connections = n; self }
251
+ fn build(self) -> ServerConfig {
252
+ ServerConfig { host: self.host, port: self.port, max_connections: self.max_connections }
253
+ }
254
+ }
255
+
256
+ // Usage: ServerConfig::builder("localhost", 8080).max_connections(200).build()
257
+ ```
258
+
259
+ ## Iterators and Closures
260
+
261
+ ### Prefer Iterator Chains Over Manual Loops
262
+
263
+ ```rust
264
+ // Good: Declarative, lazy, composable
265
+ let active_emails: Vec<String> = users.iter()
266
+ .filter(|u| u.is_active)
267
+ .map(|u| u.email.clone())
268
+ .collect();
269
+
270
+ // Bad: Imperative accumulation
271
+ let mut active_emails = Vec::new();
272
+ for user in &users {
273
+ if user.is_active {
274
+ active_emails.push(user.email.clone());
275
+ }
276
+ }
277
+ ```
278
+
279
+ ### Use `collect()` with Type Annotation
280
+
281
+ ```rust
282
+ // Collect into different types
283
+ let names: Vec<_> = items.iter().map(|i| &i.name).collect();
284
+ let lookup: HashMap<_, _> = items.iter().map(|i| (i.id, i)).collect();
285
+ let combined: String = parts.iter().copied().collect();
286
+
287
+ // Collect Results — short-circuits on first error
288
+ let parsed: Result<Vec<i32>, _> = strings.iter().map(|s| s.parse()).collect();
289
+ ```
290
+
291
+ ## Concurrency
292
+
293
+ ### `Arc<Mutex<T>>` for Shared Mutable State
294
+
295
+ ```rust
296
+ use std::sync::{Arc, Mutex};
297
+
298
+ let counter = Arc::new(Mutex::new(0));
299
+ let handles: Vec<_> = (0..10).map(|_| {
300
+ let counter = Arc::clone(&counter);
301
+ std::thread::spawn(move || {
302
+ let mut num = counter.lock().expect("mutex poisoned");
303
+ *num += 1;
304
+ })
305
+ }).collect();
306
+
307
+ for handle in handles {
308
+ handle.join().expect("worker thread panicked");
309
+ }
310
+ ```
311
+
312
+ ### Channels for Message Passing
313
+
314
+ ```rust
315
+ use std::sync::mpsc;
316
+
317
+ let (tx, rx) = mpsc::sync_channel(16); // Bounded channel with backpressure
318
+
319
+ for i in 0..5 {
320
+ let tx = tx.clone();
321
+ std::thread::spawn(move || {
322
+ tx.send(format!("message {i}")).expect("receiver disconnected");
323
+ });
324
+ }
325
+ drop(tx); // Close sender so rx iterator terminates
326
+
327
+ for msg in rx {
328
+ println!("{msg}");
329
+ }
330
+ ```
331
+
332
+ ### Async with Tokio
333
+
334
+ ```rust
335
+ use tokio::time::Duration;
336
+
337
+ async fn fetch_with_timeout(url: &str) -> Result<String> {
338
+ let response = tokio::time::timeout(
339
+ Duration::from_secs(5),
340
+ reqwest::get(url),
341
+ )
342
+ .await
343
+ .context("request timed out")?
344
+ .context("request failed")?;
345
+
346
+ response.text().await.context("failed to read body")
347
+ }
348
+
349
+ // Spawn concurrent tasks
350
+ async fn fetch_all(urls: Vec<String>) -> Vec<Result<String>> {
351
+ let handles: Vec<_> = urls.into_iter()
352
+ .map(|url| tokio::spawn(async move {
353
+ fetch_with_timeout(&url).await
354
+ }))
355
+ .collect();
356
+
357
+ let mut results = Vec::with_capacity(handles.len());
358
+ for handle in handles {
359
+ results.push(handle.await.unwrap_or_else(|e| panic!("spawned task panicked: {e}")));
360
+ }
361
+ results
362
+ }
363
+ ```
364
+
365
+ ## Unsafe Code
366
+
367
+ ### When Unsafe Is Acceptable
368
+
369
+ ```rust
370
+ // Acceptable: FFI boundary with documented invariants (Rust 2024+)
371
+ /// # Safety
372
+ /// `ptr` must be a valid, aligned pointer to an initialized `Widget`.
373
+ unsafe fn widget_from_raw<'a>(ptr: *const Widget) -> &'a Widget {
374
+ // SAFETY: caller guarantees ptr is valid and aligned
375
+ unsafe { &*ptr }
376
+ }
377
+
378
+ // Acceptable: Performance-critical path with proof of correctness
379
+ // SAFETY: index is always < len due to the loop bound
380
+ unsafe { slice.get_unchecked(index) }
381
+ ```
382
+
383
+ ### When Unsafe Is NOT Acceptable
384
+
385
+ ```rust
386
+ // Bad: Using unsafe to bypass borrow checker
387
+ // Bad: Using unsafe for convenience
388
+ // Bad: Using unsafe without a Safety comment
389
+ // Bad: Transmuting between unrelated types
390
+ ```
391
+
392
+ ## Module System and Crate Structure
393
+
394
+ ### Organize by Domain, Not by Type
395
+
396
+ ```text
397
+ my_app/
398
+ ├── src/
399
+ │ ├── main.rs
400
+ │ ├── lib.rs
401
+ │ ├── auth/ # Domain module
402
+ │ │ ├── mod.rs
403
+ │ │ ├── token.rs
404
+ │ │ └── middleware.rs
405
+ │ ├── orders/ # Domain module
406
+ │ │ ├── mod.rs
407
+ │ │ ├── model.rs
408
+ │ │ └── service.rs
409
+ │ └── db/ # Infrastructure
410
+ │ ├── mod.rs
411
+ │ └── pool.rs
412
+ ├── tests/ # Integration tests
413
+ ├── benches/ # Benchmarks
414
+ └── Cargo.toml
415
+ ```
416
+
417
+ ### Visibility — Expose Minimally
418
+
419
+ ```rust
420
+ // Good: pub(crate) for internal sharing
421
+ pub(crate) fn validate_input(input: &str) -> bool {
422
+ !input.is_empty()
423
+ }
424
+
425
+ // Good: Re-export public API from lib.rs
426
+ pub mod auth;
427
+ pub use auth::AuthMiddleware;
428
+
429
+ // Bad: Making everything pub
430
+ pub fn internal_helper() {} // Should be pub(crate) or private
431
+ ```
432
+
433
+ ## Tooling Integration
434
+
435
+ ### Essential Commands
436
+
437
+ ```bash
438
+ # Build and check
439
+ cargo build
440
+ cargo check # Fast type checking without codegen
441
+ cargo clippy # Lints and suggestions
442
+ cargo fmt # Format code
443
+
444
+ # Testing
445
+ cargo test
446
+ cargo test -- --nocapture # Show println output
447
+ cargo test --lib # Unit tests only
448
+ cargo test --test integration # Integration tests only
449
+
450
+ # Dependencies
451
+ cargo audit # Security audit
452
+ cargo tree # Dependency tree
453
+ cargo update # Update dependencies
454
+
455
+ # Performance
456
+ cargo bench # Run benchmarks
457
+ ```
458
+
459
+ ## Quick Reference: Rust Idioms
460
+
461
+ | Idiom | Description |
462
+ |-------|-------------|
463
+ | Borrow, don't clone | Pass `&T` instead of cloning unless ownership is needed |
464
+ | Make illegal states unrepresentable | Use enums to model valid states only |
465
+ | `?` over `unwrap()` | Propagate errors, never panic in library/production code |
466
+ | Parse, don't validate | Convert unstructured data to typed structs at the boundary |
467
+ | Newtype for type safety | Wrap primitives in newtypes to prevent argument swaps |
468
+ | Prefer iterators over loops | Declarative chains are clearer and often faster |
469
+ | `#[must_use]` on Results | Ensure callers handle return values |
470
+ | `Cow` for flexible ownership | Avoid allocations when borrowing suffices |
471
+ | Exhaustive matching | No wildcard `_` for business-critical enums |
472
+ | Minimal `pub` surface | Use `pub(crate)` for internal APIs |
473
+
474
+ ## Anti-Patterns to Avoid
475
+
476
+ ```rust
477
+ // Bad: .unwrap() in production code
478
+ let value = map.get("key").unwrap();
479
+
480
+ // Bad: .clone() to satisfy borrow checker without understanding why
481
+ let data = expensive_data.clone();
482
+ process(&original, &data);
483
+
484
+ // Bad: Using String when &str suffices
485
+ fn greet(name: String) { /* should be &str */ }
486
+
487
+ // Bad: Box<dyn Error> in libraries (use thiserror instead)
488
+ fn parse(input: &str) -> Result<Data, Box<dyn std::error::Error>> { todo!() }
489
+
490
+ // Bad: Ignoring must_use warnings
491
+ let _ = validate(input); // Silently discarding a Result
492
+
493
+ // Bad: Blocking in async context
494
+ async fn bad_async() {
495
+ std::thread::sleep(Duration::from_secs(1)); // Blocks the executor!
496
+ // Use: tokio::time::sleep(Duration::from_secs(1)).await;
497
+ }
498
+ ```
499
+
500
+ **Remember**: If it compiles, it's probably correct — but only if you avoid `unwrap()`, minimize `unsafe`, and let the type system work for you.