agent-workflow-kit-cli 1.3.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/cli/commands/add.js +3 -1
  2. package/dist/cli/commands/doctor.js +8 -1
  3. package/dist/cli/commands/init.js +6 -0
  4. package/dist/cli/index.js +2 -2
  5. package/dist/core/analyzer.js +216 -1
  6. package/dist/core/awos/intelligence.js +30 -6
  7. package/dist/core/detector.js +54 -4
  8. package/package.json +1 -1
  9. package/templates/common/AGENTS.md.hbs +4 -0
  10. package/templates/common/GLOBAL_RULES.md +101 -0
  11. package/templates/dotnet/AGENTS.md.hbs +53 -0
  12. package/templates/dotnet/rules/api-structure.md +43 -0
  13. package/templates/dotnet/rules/csharp-style.md +33 -0
  14. package/templates/dotnet/rules/dependency-injection.md +54 -0
  15. package/templates/dotnet/rules/error-handling-validation.md +86 -0
  16. package/templates/dotnet/skills/dotnet-controller/SKILL.md +24 -0
  17. package/templates/express/AGENTS.md.hbs +41 -0
  18. package/templates/express/rules/error-handling.md +88 -0
  19. package/templates/express/rules/express-style.md +39 -0
  20. package/templates/express/rules/router-controller.md +27 -0
  21. package/templates/express/skills/express-endpoint/SKILL.md +24 -0
  22. package/templates/golang/AGENTS.md.hbs +36 -0
  23. package/templates/golang/rules/concurrency.md +71 -0
  24. package/templates/golang/rules/error-handling.md +42 -0
  25. package/templates/golang/rules/golang-style.md +24 -0
  26. package/templates/golang/rules/project-layout.md +39 -0
  27. package/templates/nestjs/AGENTS.md.hbs +38 -0
  28. package/templates/nestjs/rules/module-architecture.md +35 -0
  29. package/templates/nestjs/rules/nestjs-style.md +41 -0
  30. package/templates/nestjs/rules/validation-errors.md +46 -0
  31. package/templates/nestjs/skills/nestjs-module/SKILL.md +25 -0
  32. package/templates/next-js/AGENTS.md.hbs +41 -0
  33. package/templates/next-js/rules/data-fetching-mutations.md +36 -0
  34. package/templates/next-js/rules/next-style.md +32 -0
  35. package/templates/next-js/rules/seo-metadata.md +50 -0
  36. package/templates/next-js/rules/server-client-components.md +27 -0
  37. package/templates/next-js/skills/next-feature/SKILL.md +26 -0
  38. package/templates/react-ts/AGENTS.md.hbs +109 -32
  39. package/templates/react-ts/rules/data-fetching.md +45 -0
  40. package/templates/react-ts/rules/forms-validation.md +55 -0
  41. package/templates/react-ts/rules/premium-ui.md +45 -0
  42. package/templates/react-ts/rules/react-style.md +38 -26
  43. package/templates/react-ts/rules/routing-splitting.md +21 -0
  44. package/templates/react-ts/rules/seo-accessibility.md +34 -0
  45. package/templates/react-ts/skills/react-feature/SKILL.md +5 -5
  46. package/templates/rust/AGENTS.md.hbs +34 -0
  47. package/templates/rust/rules/error-handling.md +36 -0
  48. package/templates/rust/rules/memory-concurrency.md +47 -0
  49. package/templates/rust/rules/project-layout.md +49 -0
  50. package/templates/rust/rules/rust-style.md +26 -0
@@ -0,0 +1,45 @@
1
+ # Asynchronous Server-State & API Call Rules
2
+
3
+ This ruleset governs network communication, caching, server-state syncing, and component integration logic to guarantee high performance, security, and clean separation of concerns.
4
+
5
+ ---
6
+
7
+ ## 🚫 No Raw useEffect Fetching
8
+ - **Forbidden**: Do not write raw `useEffect` blocks to fetch remote data inside UI components. Raw effects are prone to memory leaks, state sync race conditions, lack of cache validation, and component bloatedness.
9
+
10
+ ---
11
+
12
+ ## 🔌 Centralized API Client
13
+ - **Single Instance**: Route all HTTP/HTTPS outgoing traffic through a unified API client instance (e.g. located at `src/lib/api-client.ts`).
14
+ - **Responsibility**:
15
+ - Configure core variables (e.g. `baseURL`, `timeout`).
16
+ - Attach authorization tokens dynamically via request interceptors.
17
+ - Implement unified global error handling (e.g. intercepting `401 Unauthorized` for token refresh, `403 Forbidden`, `500 Server Error`).
18
+
19
+ ---
20
+
21
+ ## 🔄 Server-State Management
22
+ - **Library Selection**: Use **TanStack Query (React Query)** or **SWR** to manage asynchronous server-state (fetching, caching, caching invalidation, background updates).
23
+ - **Separation of Concerns**: UI components must never deal with query functions or endpoints. Components only request custom query hooks and render the layout based on:
24
+ - `isLoading`: displays placeholder/Skeleton UI.
25
+ - `isError`: displays recovery panel/notification.
26
+ - `data`: displays final UI.
27
+ - **Hook Encapsulation**: Declare data fetching inside specialized feature-local custom hooks:
28
+
29
+ ```typescript
30
+ // src/features/roadmap/api/use-roadmap.ts
31
+ import { useQuery } from "@tanstack/react-query";
32
+ import { apiClient } from "@/lib/api-client";
33
+
34
+ export const useRoadmap = (roadmapId: string) => {
35
+ return useQuery({
36
+ queryKey: ["roadmaps", roadmapId],
37
+ queryFn: async () => {
38
+ const response = await apiClient.get(`/roadmaps/${roadmapId}`);
39
+ return response.data;
40
+ },
41
+ staleTime: 5 * 60 * 1000, // consider data fresh for 5 minutes
42
+ gcTime: 10 * 60 * 1000, // keep in cache for 10 minutes before garbage collection
43
+ });
44
+ };
45
+ ```
@@ -0,0 +1,55 @@
1
+ # Form Management & Schema Validation Rules
2
+
3
+ This ruleset governs the design and implementation of input fields, submissions, validations, and custom component bindings inside React forms.
4
+
5
+ ---
6
+
7
+ ## ⚡ Form Performance (React Hook Form)
8
+ - **High Performance**: Use **React Hook Form (RHF)** to handle form state through uncontrolled inputs. This isolates rendering, preventing expensive keypress lag or component bottlenecks on large forms.
9
+ - **Controlled Integration**: For custom/third-party UI controls that cannot be controlled natively (such as Rich Text Editors, custom Select dropdowns, calendar selectors), wrap them within RHF's `<Controller>` component to synchronize state efficiently.
10
+
11
+ ---
12
+
13
+ ## 🛡️ Schema-Driven Validation (Zod)
14
+ - **No manual checking**: Never use complex if/else blocks or custom validation scripts inside submit handlers to check forms.
15
+ - **Zod Resolving**: Use **Zod** to declare form schemas. Bind them to React Hook Form using `zodResolver` to automatically map validator rules and throw clean, localized error messages:
16
+
17
+ ```tsx
18
+ // Example feature form implementation
19
+ import { useForm } from "react-hook-form";
20
+ import { zodResolver } from "@hookform/resolvers/zod";
21
+ import * as z from "zod";
22
+ import { cn } from "@/utils/cn";
23
+
24
+ const loginSchema = z.object({
25
+ email: z.string().min(1, "Email cannot be empty").email("Invalid email format"),
26
+ password: z.string().min(8, "Password must contain at least 8 characters"),
27
+ });
28
+
29
+ type LoginFields = z.infer<typeof loginSchema>;
30
+
31
+ export const LoginForm = () => {
32
+ const { register, handleSubmit, formState: { errors, isSubmitting } } = useForm<LoginFields>({
33
+ resolver: zodResolver(loginSchema),
34
+ });
35
+
36
+ const onSubmit = async (data: LoginFields) => {
37
+ // Execute authentication pipeline
38
+ };
39
+
40
+ return (
41
+ <form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
42
+ <div>
43
+ <input
44
+ {...register("email")}
45
+ className={cn("border px-3 py-2 rounded", errors.email && "border-red-500")}
46
+ />
47
+ {errors.email && <p className="text-red-500 text-sm mt-1">{errors.email.message}</p>}
48
+ </div>
49
+ <button type="submit" disabled={isSubmitting} className="px-4 py-2 bg-primary text-white rounded">
50
+ {isSubmitting ? "Processing..." : "Login"}
51
+ </button>
52
+ </form>
53
+ );
54
+ };
55
+ ```
@@ -0,0 +1,45 @@
1
+ # Aesthetics, Styling & Premium UI Rules
2
+
3
+ This ruleset outlines strict requirements for styling, responsiveness, and micro-animations to ensure premium visual excellence and high UX fidelity.
4
+
5
+ ---
6
+
7
+ ## 🎨 Tailwind CSS Guidelines
8
+ - **No inline custom CSS**: All interface elements must be constructed using Tailwind utility classes. Do not write inline custom CSS (e.g. style properties or stylesheet files containing static layouts) unless standard utility classes are insufficient.
9
+ - **Dynamic Classes handling**: Never use string interpolation or string addition (e.g. `isActive ? 'bg-blue-500' : 'bg-gray-500'`) to concatenate dynamic class names. This causes CSS specificity issues and classes override failure.
10
+ - **Helper cn() usage**: Always use the custom `cn()` helper utility that integrates `clsx` and `tailwind-merge` for combining dynamic class values:
11
+
12
+ ```typescript
13
+ // src/utils/cn.ts
14
+ import { ClassValue, clsx } from "clsx";
15
+ import { twMerge } from "tailwind-merge";
16
+
17
+ export function cn(...inputs: ClassValue[]) {
18
+ return twMerge(clsx(inputs));
19
+ }
20
+ ```
21
+
22
+ * **Incorrect (❌ Forbidden)**:
23
+ ```tsx
24
+ <button className={`px-4 py-2 text-white ${isActive ? 'bg-blue-500' : 'bg-gray-500'} ${customClass}`}>
25
+ ```
26
+ * **Correct (✔️ Required)**:
27
+ ```tsx
28
+ <button className={cn("px-4 py-2 text-white transition-all", isActive ? "bg-blue-500" : "bg-gray-500", customClass)}>
29
+ ```
30
+
31
+ ---
32
+
33
+ ## 📱 Mobile-First Responsiveness
34
+ - **Default Styles**: Apply classes for the smallest screen size (mobile viewport) by default.
35
+ - **Breakpoint Overrides**: Use breakpoints (`sm:`, `md:`, `lg:`, `xl:`, `2xl:`) to introduce or change styling parameters for larger viewports.
36
+ - **Layout Checking**: Always verify flex direction (`flex-col` vs `flex-row`), grid layout templates (`grid-cols-1` vs `md:grid-cols-3`), padding, margin, and typography scales on both small and large viewports to avoid layout issues.
37
+
38
+ ---
39
+
40
+ ## ⚡ Micro-animations & Motion
41
+ - **Libraries**: Use `framer-motion` (or the core `motion` package) for micro-animations and physical state changes.
42
+ - **Natural Transitions**:
43
+ - Keep animations fast and responsive: transition duration must range between `0.2s` and `0.3s`.
44
+ - Use natural, fluid easing curves (like `easeOut` or `easeInOut`) or spring-based models for buttons, toggles, hover states, and modals.
45
+ - **Unmounting Transitions**: When components unmount or disappear from the DOM, they must be wrapped within the `<AnimatePresence>` component to ensure exit animations complete smoothly without sudden visual disappearance.
@@ -1,29 +1,41 @@
1
1
  # React + TypeScript Style Rules
2
2
 
3
- ## Naming
4
- - Components: PascalCase (`Navbar.tsx`, `InstallSection.tsx`).
5
- - Custom hooks: camelCase starting with `use` (`useAuth.ts`).
6
- - Helpers & variables: camelCase (`formatCurrency`).
7
- - Types & interfaces: PascalCase (`ButtonProps`).
8
-
9
- ## Imports
10
- - Use `@/` absolute alias paths. Avoid relative parent paths (`../../`).
11
- - Use `import type` for types.
12
- - Keep feature internals private; expose via `index.ts` only when needed.
13
-
14
- ## React & JSX
15
- - Components must focus on UI/composition.
16
- - Move side effects (fetching, subscriptions, timers) to custom hooks.
17
- - Use shorthand for boolean props: `<Input disabled />`.
18
- - Handle async UI states: loading, error, empty, success.
19
-
20
- ## State Management
21
- - Prefer local component state.
22
- - Use Context API for stable app-level state (auth, theme).
23
- - Use Zustand for frequent, cross-feature state updates.
24
-
25
- ## Testing
26
- - Test user behavior via React Testing Library.
27
- - Test hooks with complex branching/cleanup.
28
- - Avoid snapshot testing unless output is small & stable.
3
+ This ruleset outlines base conventions for React + TypeScript projects. Detail guidelines are split into specialized modules which the agent MUST follow:
4
+ - Styling & Aesthetics: See `@premium-ui.md`
5
+ - Data Fetching & Server-State: See `@data-fetching.md`
6
+ - Form Handling & Zod Validation: See `@forms-validation.md`
7
+ - Code Splitting & Routing: See `@routing-splitting.md`
8
+ - SEO & Accessibility (a11y): See `@seo-accessibility.md`
29
9
 
10
+ ---
11
+
12
+ ## 🏷️ Naming Conventions
13
+ - **Components**: PascalCase (e.g. `Navbar.tsx`, `InstallSection.tsx`).
14
+ - **Custom hooks**: camelCase starting with `use` (e.g. `useAuth.ts`, `useCustomers.ts`).
15
+ - **Helpers & variables**: camelCase (e.g. `formatCurrency`, `customerData`).
16
+ - **Types & interfaces**: PascalCase (e.g. `ButtonProps`, `CustomerData`).
17
+ - **Routes**: `<name>.route.tsx` (e.g. `customers.route.tsx`).
18
+ - **Feature Folders**: kebab-case or lowercase (e.g. `billing`, `user-profile`).
19
+
20
+ ---
21
+
22
+ ## 📦 Imports
23
+ - **Absolute imports**: Always use absolute alias paths starting with `@/` (e.g. `import { Button } from "@/shared/components"`). Avoid deep relative parent imports (e.g. `../../components`).
24
+ - **Type imports**: Always use `import type` when importing types or interfaces to optimize bundle compilation.
25
+ - **Encapsulation**: Keep feature-internal files private. Only export public features via the module `index.ts`.
26
+
27
+ ---
28
+
29
+ ## ⚙️ React & JSX Guidelines
30
+ - **UI Composition**: Components must focus solely on rendering UI/composition and delegating logic.
31
+ - **Logic Delegation**: Keep side effects (fetching, subscriptions, timers, complex state transitions) inside custom hooks.
32
+ - **Shorthand Props**: Prefer shorthand for boolean flags (e.g. `<Input disabled />` instead of `<Input disabled={true} />`).
33
+ - **Async UI States**: Always explicitly handle async UI transitions (e.g. loading, error, empty, success).
34
+
35
+ ---
36
+
37
+ ## 💾 State Management
38
+ - **Local State**: Prefer component-local state (`useState`, `useReducer`) for isolated UI interactions.
39
+ - **Context API**: Use the Context API only for low-frequency global values (e.g. theme, locale, user session credentials).
40
+ - **Zustand**: Use Zustand for frequent, cross-feature state updates or complex frontend state orchestration.
41
+ - **Locality**: Keep state as close to the components consuming it as possible before lifting it up.
@@ -0,0 +1,21 @@
1
+ # Code Splitting & Routing Rules
2
+
3
+ This ruleset outlines expectations for structuring router declarations, loading performance optimization, and runtime boundary protections.
4
+
5
+ ---
6
+
7
+ ## ⚡ Code Splitting (Dynamic Imports)
8
+ - **Dynamic Pages**: Do not statically import full page components at the top level of router files. This bundles the entire application code into a single file and degrades initial page load performance.
9
+ - **Lazy Loading**: Use `React.lazy()` to import page components dynamically, dividing route destinations into separate bundles:
10
+ ```typescript
11
+ const DashboardPage = React.lazy(() => import("@/features/dashboard/components/DashboardPage"));
12
+ ```
13
+ - **Fallback Suspension**: Wrap lazy-loaded components in a `<Suspense>` component. Provide a high-fidelity shimmer skeleton loader or loading indicator as the fallback property to maintain visual continuity.
14
+
15
+ ---
16
+
17
+ ## 🗺️ Centralized Routing Architecture (React Router v6+)
18
+ - **Data Router**: Define routes as data configuration arrays using `createBrowserRouter` instead of JSX-based `<Routes>` declarations.
19
+ - **Data Loaders**: Utilize router Loaders to pre-fetch required data in parallel with route navigation.
20
+ - **Data Actions**: Utilize router Actions to handle data modification (mutations and forms submissions).
21
+ - **Page Crash Isolation**: Define a dedicated `errorElement` on all primary parent route levels. When a page encounters a crash (e.g. invalid API response, parsing failure), the local `ErrorBoundary` will intercept the error and render a recovery screen without crashing the rest of the application.
@@ -0,0 +1,34 @@
1
+ # SEO & Accessibility (a11y) Rules
2
+
3
+ This ruleset governs semantic document structures, title/meta tag updates, and accessibility integrations to ensure excellent indexing and keyboard/screen-reader compatibility.
4
+
5
+ ---
6
+
7
+ ## 🔍 SEO & Semantic HTML
8
+ - **Dynamic SEO Metadata**: Update document headers dynamically (e.g. `document.title`, description tags, and Open Graph tags) on page transitions using `react-helmet-async` (or the routing framework's metadata controller).
9
+ - **Semantic Structure**: Do not use `<div>` tags for all layouts. Utilize HTML5 semantic elements to establish logical document outline sections:
10
+ - `<header>`: Site or section navigation header.
11
+ - `<nav>`: Core navigation links.
12
+ - `<main>`: Singular primary content of the body.
13
+ - `<section>`: Generic thematic block.
14
+ - `<article>`: Self-contained composition (posts, articles, cards).
15
+ - `<footer>`: Copyright, contact, and structural footers.
16
+ - **Heading Hierarchy**: Align heading tags (`<h1>` to `<h6>`) logically. Ensure there is only one `<h1>` per page, and header levels are nested sequentially.
17
+
18
+ ---
19
+
20
+ ## ♿ Accessibility (a11y) Standards
21
+ - **Image alt attributes**:
22
+ - All `<img>` tags must have an `alt` attribute.
23
+ - Provide short, descriptive descriptions for informative images.
24
+ - For decorative images, write `alt=""` so that screen readers skip reading their filenames aloud.
25
+ - **Icon-Only Controls**: Every button, link, or clickable component that wraps only an icon (e.g. SVG close button `X`, favorite button heart, menu hamburger icon) must include a descriptive `aria-label` or `aria-labelledby` attribute.
26
+ - **Visual Keyboard Focus**: Do not strip or disable the browser's default blue focus rings without adding an alternative visual indicator. All interactive inputs, buttons, and links must display a prominent border ring when navigated via keyboard:
27
+ ```css
28
+ /* Example utility or class selector */
29
+ .focus-indicator:focus-visible {
30
+ outline: none;
31
+ box-shadow: 0 0 0 2px var(--color-primary-offset), 0 0 0 4px var(--color-primary);
32
+ }
33
+ ```
34
+ In Tailwind: `focus-visible:ring-2 focus-visible:ring-primary focus-visible:outline-none`.
@@ -15,11 +15,11 @@ Steps:
15
15
  2. Define feature-local types first, including loading, error, empty, and success state shapes.
16
16
  3. Create or update the custom hook that owns fetching, side effects, derived state, and cleanup.
17
17
  4. Create or update PascalCase components that render UI and delegate logic to hooks.
18
- 5. Add styles using the project's existing styling approach; do not introduce a new styling system.
18
+ 5. Add styles using Tailwind CSS utility classes and Framer Motion for micro-animations; do not write custom inline CSS.
19
19
  6. Wire the feature into the route or parent component through the smallest public API needed.
20
20
  7. Add tests for component behavior and hook logic when branching, async work, or cleanup is present.
21
21
  8. Run validations:
22
- - `npm run lint`
23
- - `npm run typecheck`
24
- - `npm run test -- --run`
25
- - `npm run build`
22
+ - `{{runCommand}} lint`
23
+ - `{{runCommand}} typecheck`
24
+ - `{{runCommand}} test`
25
+ - `{{runCommand}} build`
@@ -0,0 +1,34 @@
1
+ ## 🗺️ Rust Development Guide
2
+
3
+ ### 🔄 Agent Development Lifecycle
4
+ The AI Agent must execute all Rust tasks following this 4-step workflow:
5
+ 1. **Design & Implementation:** Implement business logic adhering to Rust conventions. Enforce structural separation: `main.rs` (for binary application setup) and `lib.rs` (for core business logic that can be reused and tested).
6
+ 2. **Comprehensive Testing:** Write unit tests inside internal test modules and integration tests in the `/tests` directory. Run tests with: `cargo test`.
7
+ 3. **Code Quality & Linting:** Run check tools regularly to ensure a warning-free state:
8
+ - Formatting: `cargo fmt`
9
+ - Linting: `cargo clippy --all-targets -- -D warnings`
10
+ - Build Validation: `cargo build`
11
+ 4. **Dependency Management:** Add external libraries using `cargo add [library_name]`. Never manually edit the `Cargo.lock` file.
12
+
13
+ ---
14
+
15
+ ### 🏗️ Template Blueprint
16
+ Refer to the detailed rules below:
17
+ - Idiomatic Rust, clippy lints, and cloning optimizations: `@rust-style.md`
18
+ - Crate modules, Cargo Workspaces, and Trait-based Dependency Injection: `@project-layout.md`
19
+ - Failures management, Result/Option, `thiserror`, and `anyhow`: `@error-handling.md`
20
+ - Lifetimes `'a`, Smart Pointers, and async Tokio safety: `@memory-concurrency.md`
21
+
22
+ ---
23
+
24
+ ### 🏛️ Strict Development Rules
25
+
26
+ #### 1. Ownership & Borrowing
27
+ - **Avoid Over-Cloning:** Call `.clone()` on Heap types only when you must own an independent copy. Otherwise, design functions to receive read references `&T` or write references `&mut T`.
28
+ - **Exclusive Mutable Borrow:** Ensure only one mutable reference `&mut T` exists at a time, and never let it coexist with any read references `&T` in the same scope.
29
+
30
+ #### 2. Safe Error Handling
31
+ - **No Unwraps:** Never use `.unwrap()` or `.expect()` in production code (except in tests). Propagate errors using `Result<T, E>` or `Option<T>` to ensure system reliability.
32
+
33
+ #### 3. Async Concurrency (Tokio)
34
+ - **CPU-Bound Tasks:** Never run heavy CPU operations (e.g., encryption, intensive loops) directly inside async contexts. Offload them using `tokio::task::spawn_blocking`.
@@ -0,0 +1,36 @@
1
+ # Error Handling & Fault Control in Rust
2
+
3
+ This document defines strict rules for handling, wrapping, and propagating failures using idiomatic Rust patterns.
4
+
5
+ ---
6
+
7
+ ## 🚫 Avoid Panics in Production
8
+ - **Strict Rule:** Never use `panic!`, `.unwrap()`, or `.expect()` in production application code. Doing so triggers process termination, resulting in service interruption.
9
+ - **Exceptions:** Only use panics in:
10
+ - Unit and Integration Tests.
11
+ - Initial bootstrapping (e.g., parsing critical files at startup) when missing items make recovery impossible.
12
+ - Invariants where the logic guarantees a failure is impossible.
13
+
14
+ ---
15
+
16
+ ## 🔄 Result Propagation with the `?` Operator
17
+ - All fallible business logic operations must return `Result<T, E>` or `Option<T>`.
18
+ - Use the `?` operator to propagate errors up the call stack, maintaining a clean syntax.
19
+
20
+ ---
21
+
22
+ ## 📚 Error Libraries: `thiserror` vs `anyhow`
23
+ Never mix these libraries arbitrarily. Comply with the following separation:
24
+ - **Use `thiserror` for Library Crates / Domain Modules:** Creates strongly-typed, detailed error definitions with custom display messages.
25
+ ```rust
26
+ use thiserror::Error;
27
+
28
+ #[derive(Error, Debug)]
29
+ pub enum DatabaseError {
30
+ #[error("User not found with ID {0}")]
31
+ UserNotFound(i64),
32
+ #[error("Database connection failure: {0}")]
33
+ ConnectionFailed(String),
34
+ }
35
+ ```
36
+ - **Use `anyhow` for Application Entrypoints (API Gateway / CLI main):** Ideal for general error grouping and stack propagation without complex type mapping.
@@ -0,0 +1,47 @@
1
+ # Memory Management & Concurrency in Rust
2
+
3
+ This document details conventions for lifetimes, smart pointer usage, and async Tokio runtime operations.
4
+
5
+ ---
6
+
7
+ ## ⏳ Lifetime Annotations ('a)
8
+ - When a struct or function references a borrowing context, annotate lifetimes explicitly to guarantee spatial memory safety:
9
+ ```rust
10
+ pub struct TokenValidator<'a> {
11
+ pub secret_key: &'a str,
12
+ }
13
+ ```
14
+ - Avoid bypassing the borrow checker with unnecessary `.clone()` calls or `'static` lifetime modifiers if the scope can be expressed with valid lifetime relationships.
15
+
16
+ ---
17
+
18
+ ## 🧠 Smart Pointer Matrix
19
+ Select the correct smart pointer types according to the allocation scope:
20
+
21
+ | Smart Pointer | Environment | Memory Allocation Characteristics | Application Use Case |
22
+ | :--- | :--- | :--- | :--- |
23
+ | **`Box<T>`** | Single / Multi-thread | Allocates large types on the Heap | Flattens recursive data structures (Sized types) |
24
+ | **`Rc<T>`** | Single-thread Only | Reference count without thread safety | Shares immutable data across a single-threaded runtime |
25
+ | **`Arc<T>`** | Multi-thread | Thread-safe Reference Count (Atomic) | Shares immutable resources across thread pools (e.g., Web Server) |
26
+ | **`RefCell<T>`** | Single-thread Only | Interior Mutability (Checked at Runtime) | Mutates fields inside an immutable single-threaded struct |
27
+ | **`Mutex<T>`** | Multi-thread | Thread safety via OS or runtime lock | Protects mutable resources shared across multiple threads |
28
+
29
+ ---
30
+
31
+ ## 🚦 Async Runtime (Tokio) CPU vs I/O Bound Tasks
32
+ Blocking the executor threads in an async environment will starve the thread pool, degrading throughput.
33
+ - **I/O Bound Tasks:** (DB Queries, Async file read/write, HTTP calls). Use standard `async/await` syntax.
34
+ - **CPU Bound Tasks:** (Password hashing, image processing, complex computations). Never run these directly in the async thread pool. Use `tokio::task::spawn_blocking`:
35
+ ```rust
36
+ let hashed_password = tokio::task::spawn_blocking(move || {
37
+ bcrypt::hash(password, bcrypt::DEFAULT_COST)
38
+ })
39
+ .await
40
+ .unwrap()?;
41
+ ```
42
+
43
+ ---
44
+
45
+ ## 🔒 Send + Sync Traits & MutexGuard Safety
46
+ - Shared items sent across task boundaries (`tokio::spawn`) must implement `Send` and `Sync`.
47
+ - **MutexGuard across Await:** Never hold a non-thread-safe guard (like `std::sync::MutexGuard`) across `.await` points. Doing so will lead to compilation errors or runtime deadlocks. If a lock must span an await point, use `tokio::sync::Mutex`.
@@ -0,0 +1,49 @@
1
+ # Rust Crate Layout & Modular Architecture
2
+
3
+ This document defines module structures, visibility scopes, Cargo Workspace configurations, and dependency injection in Rust.
4
+
5
+ ---
6
+
7
+ ## 🏗️ Modules & Crate Separation
8
+ - **Separating Binary & Library:**
9
+ - `src/main.rs`: Entrypoint of the binary application. Responsible only for parsing arguments, reading configuration, and starting the runtime.
10
+ - `src/lib.rs`: Holds 100% of the core business logic, enabling testability and decoupling.
11
+ - **Visibility Scope Control:** Do not expose symbols using `pub` indiscriminately. Prefer `pub(crate)` to limit access to within the same crate, maintaining strict encapsulation.
12
+
13
+ ---
14
+
15
+ ## 📦 Cargo Workspaces (Multi-Crate Monorepos)
16
+ For large monorepo systems, split the project into a Cargo Workspace containing isolated crates to enable parallel compilation:
17
+ ```toml
18
+ # Cargo.toml at the root directory
19
+ [workspace]
20
+ members = [
21
+ "crates/api-gateway",
22
+ "crates/user-domain",
23
+ "crates/core-engine",
24
+ "crates/shared-utils"
25
+ ]
26
+ ```
27
+
28
+ ---
29
+
30
+ ## 💉 Trait-Based Dependency Injection (DI)
31
+ Due to Rust's strict lifetimes and borrow checker, decouple dependencies by implementing **Traits** combined with thread-safe smart pointers: `Arc<dyn Trait + Send + Sync>`.
32
+ ```rust
33
+ use std::sync::Arc;
34
+
35
+ pub trait UserRepository: Send + Sync {
36
+ fn find_by_id(&self, id: i64) -> Result<User, AppError>;
37
+ }
38
+
39
+ pub struct UserService {
40
+ // Thread-safe pointer to dynamic trait implementation
41
+ repo: Arc<dyn UserRepository>,
42
+ }
43
+
44
+ impl UserService {
45
+ pub fn new(repo: Arc<dyn UserRepository>) -> Self {
46
+ Self { repo }
47
+ }
48
+ }
49
+ ```
@@ -0,0 +1,26 @@
1
+ # Idiomatic Rust Style & Optimization
2
+
3
+ This document outlines standard conventions for writing idiomatic Rust code, optimizing borrowing, and complying with Clippy.
4
+
5
+ ---
6
+
7
+ ## 🦀 Idiomatic Rust Conventions
8
+ - **Pattern Matching:** Leverage Pattern Matching (`match`, `if let`, `let-else`) instead of deep nested `if/else` checks to handle control flow safely.
9
+ - **Naming Conventions:**
10
+ - `snake_case` for functions, methods, variables, and modules.
11
+ - `PascalCase` for Structs, Enums, Traits, and Unions.
12
+ - `SCREAMING_SNAKE_CASE` for constants and statics.
13
+
14
+ ---
15
+
16
+ ## 🧠 Borrowing & Cloning Optimizations
17
+ AI models often overuse `.clone()` to satisfy the Rust Borrow Checker, which degrades performance and negates Rust's zero-cost abstraction benefits.
18
+ - **Minimize Cloning:** Use `.clone()` or `.to_string()` on Heap-allocated objects (e.g., `String`, `Vec`) only when you absolutely need independent ownership.
19
+ - **Leverage References:** Pass read references `&T` or write references `&mut T`. For strings, prefer `&str` over `String` parameter types.
20
+ - **Exclusive Write Access:** Restrict code to have only one active mutable reference `&mut T` in a given scope, with no concurrent immutable reference `&T`.
21
+
22
+ ---
23
+
24
+ ## 🛠️ Clippy Specifications
25
+ - Code generated by the AI Agent must strictly follow all optimizations suggested by Clippy.
26
+ - Run validation checks: `cargo clippy -- -D warnings` and guarantee **Zero Warnings** before submitting pull requests.