agent-workflow-kit-cli 1.0.0-mvp โ†’ 1.2.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.
@@ -6,6 +6,10 @@ import handlebars from "handlebars";
6
6
  import { promises as fs } from "fs";
7
7
  import path from "path";
8
8
  import { fileURLToPath } from "url";
9
+ // Register custom Handlebars helpers
10
+ handlebars.registerHelper("eq", function (a, b) {
11
+ return a === b;
12
+ });
9
13
  const __filename = fileURLToPath(import.meta.url);
10
14
  const __dirname = path.dirname(__filename);
11
15
  // The templates directory is located at '../../templates' relative to 'dist/core/renderer.js'
@@ -22,12 +26,18 @@ export async function renderTemplate(templatePath, context) {
22
26
  return compiled(context);
23
27
  }
24
28
  /**
25
- * Reads a static rules file as-is without Handlebars interpolation.
29
+ * Reads a static template file (rules or skills) with optional Handlebars interpolation.
26
30
  * @param filePath Relative path inside templates folder (e.g. 'spring-boot/rules/java-style.md')
31
+ * @param context Optional key-value data for compilation
27
32
  */
28
- export async function readStaticTemplateFile(filePath) {
33
+ export async function readStaticTemplateFile(filePath, context) {
29
34
  const fullPath = path.join(TEMPLATES_DIR, filePath);
30
- return fs.readFile(fullPath, "utf8");
35
+ const fileContent = await fs.readFile(fullPath, "utf8");
36
+ if (context) {
37
+ const compiled = handlebars.compile(fileContent);
38
+ return compiled(context);
39
+ }
40
+ return fileContent;
31
41
  }
32
42
  /**
33
43
  * Gets all rules files for a stack.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-workflow-kit-cli",
3
- "version": "1.0.0-mvp",
3
+ "version": "1.2.0",
4
4
  "description": "AI-Ready Repository Workflow Generator & Guideline Optimizer for Codex and Antigravity",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,44 +1,39 @@
1
1
  # Repository Agent Guidelines
2
2
 
3
- This repository implements the `agent-workflow-kit-cli` configuration standards for AI coding agents.
3
+ This repository implements the `agent-workflow-kit-cli` standards.
4
4
 
5
5
  ---
6
6
 
7
- ## ๐Ÿš€ AI Agent Step-by-Step Execution Workflow
8
-
9
- AI agents MUST follow this strict 5-step workflow for any task:
7
+ ## ๐Ÿš€ AI Agent 5-Step Execution Workflow
10
8
 
11
9
  ### 1. ๐Ÿ” Step 1: Research & Context Analysis
12
- - Read existing codebase files relating to the task first.
13
- - Understand local naming patterns, directory boundaries, and dependency versions.
14
- - Do NOT make any code modifications or run build commands in this step.
10
+ - **Selective Config Scan:** Read `AGENTS.md`. Only read rule files in `.agents/rules/` relevant to the files/stack you are modifying (e.g. `react-style.md` when editing JS/TS). Do not scan irrelevant rules or skills.
11
+ - **codebase Scan:** Read relevant codebase files, configurations, and `README.md` to understand context and project goals.
12
+ - Do NOT modify code or run build commands in this step.
15
13
 
16
14
  ### 2. ๐Ÿ“ Step 2: Formulate Implementation Plan
17
- - Document your proposed design approach.
15
+ - Document your proposed approach.
18
16
  - List all files to be created (`[NEW]`), modified (`[MODIFY]`), or deleted (`[DELETE]`).
19
17
  - Identify all verification commands to run.
20
- - Wait for user feedback or proceed intentionally based on user preferences.
21
18
 
22
- ### 3. ๐Ÿ’ป Step 3: Implementation & Clean Coding
23
- - Implement changes following strict type safety standards.
24
- - Conform strictly to the folder structures and layers defined in the Stack Pack section below.
25
- - Preserve existing comments, docstrings, and licensing headers.
19
+ ### 3. ๐Ÿ’ป Step 3: Implementation
20
+ - Follow type safety, project conventions, and architecture.
21
+ - Preserve existing comments, docstrings, and license headers.
26
22
 
27
23
  ### 4. ๐Ÿงช Step 4: Verification & Conformance Testing
28
- - Always run automated verification commands of the detected stack pack (e.g. compile, lint, test, build).
29
- - If tests or builds fail, fix the errors and rerun until compile/tests are 100% clean.
24
+ - Run automated verification commands (compile, lint, test, build). Rerun until 100% clean.
30
25
 
31
- ### 5. ๐Ÿ” Step 5: Self-Review & Quality Assurance
32
- - Review your diff/changes carefully to check for syntax errors, leftover console logs, or redundant imports.
33
- - Summarize what was changed, what was tested, and confirm that all steps are complete before marking the task as done.
26
+ ### 5. ๐Ÿ” Step 5: Self-Review & QA
27
+ - Review the diff for syntax, logs, and unused imports.
28
+ - Summarize changes and verification results before finishing.
34
29
 
35
30
  ---
36
31
 
37
32
  ## โš™๏ธ General Engineering Conventions
38
33
  - Follow existing patterns in naming, architecture, and layouts.
39
- - Read files carefully before proposing code updates.
40
- - Ensure type safety and run clean lint/verify steps before declaring a task as done.
34
+ - Ensure type safety and run verification checks before declaring a task done.
41
35
 
42
36
  <!-- AWK-START: STACK_PACK -->
43
37
  {{{stackContent}}}
44
38
  <!-- AWK-END: STACK_PACK -->
39
+
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: build-skill
3
+ description: Dynamically generates or updates a project-specific skill workflow in the .agents/skills/ directory
4
+ ---
5
+
6
+ Follow this workflow when the user requests to build or bootstrap a new custom skill for this codebase (e.g. `/build-skill medical-report-analysis`).
7
+
8
+ Inputs:
9
+ - newSkillName: Name of the skill to create (in kebab-case, e.g. `medical-analysis`)
10
+ - skillGoal: Description of the goal or target domain of the skill
11
+ - customSteps: Any specific instructions or steps requested by the user
12
+
13
+ Steps:
14
+ 1. **Analyze Project Context:**
15
+ - Scan the codebase and read existing `.agents` files to understand local directory layouts, naming conventions, and testing commands.
16
+
17
+ 2. **Formulate the Skill Structure:**
18
+ - Define a step-by-step workflow that guides an AI agent through accomplishing the target goal.
19
+ - Separate concerns: Keep the skill focused on execution workflow steps. If there are style constraints or hyperparameters, place them in a separate rule under `.agents/rules/<rule-name>.md` and reference it inside the skill via `@rules/<rule-name>.md`.
20
+ - Keep the skill file under 8,000 characters to prevent context overload.
21
+
22
+ 3. **Write the Skill File:**
23
+ - Create the target folder `.agents/skills/{{newSkillName}}/` if it does not exist.
24
+ - Write the `SKILL.md` file using standard YAML frontmatter:
25
+ ```markdown
26
+ ---
27
+ name: {{newSkillName}}
28
+ description: {{skillGoal}}
29
+ ---
30
+
31
+ [Workflow steps and instructions in English...]
32
+ ```
33
+
34
+ 4. **Verify and Inform the User:**
35
+ - Print a success message confirming the skill was written.
36
+ - Advise the user to run:
37
+ - `npx agent-workflow-kit-cli sync` (to ensure guidelines are synchronized)
38
+ - `npx agent-workflow-kit-cli export antigravity` (to export and register the new skill with the AI agent)
@@ -1,22 +1,17 @@
1
1
  # Python Code Style Rules
2
2
 
3
- All python code in this project must conform to the following formatting and styling requirements:
4
- - Use PEP 8 conventions.
5
- - Format all files with Ruff.
6
- - Imports must be sorted using Ruff or isort.
7
- - Use explicit type annotations everywhere.
3
+ - Follow PEP 8. Format & sort imports with Ruff.
4
+ - Require explicit type annotations everywhere.
8
5
 
9
6
  ## Naming
10
- - Variables, functions, modules, and API helper functions must use `snake_case`.
11
- - Classes, exceptions, and Pydantic schemas must use `PascalCase`.
12
- - Pydantic schemas for incoming writes must use intent suffixes:
13
- - `UserCreate` for create payloads.
14
- - `UserUpdate` for partial or full update payloads.
15
- - `UserRead` or `UserResponse` for response payloads, following the local convention.
16
- - Repository and service functions should describe actions with verbs, for example `get_user`, `list_users`, `create_user`, `update_user`, and `delete_user`.
7
+ - Variables, functions, modules: `snake_case`.
8
+ - Classes, exceptions, Pydantic schemas: `PascalCase`.
9
+ - Write schemas suffixes: `UserCreate` (creation), `UserUpdate` (updates).
10
+ - Response schemas: `UserRead` or `UserResponse`.
11
+ - Actions: Verb prefix (`get_user`, `create_user`).
17
12
 
18
- ## API Endpoint Naming
19
- - Route path segments must be lowercase nouns, singular or plural according to the existing local convention: `/users`, `/user-profiles`, `/orders/{order_id}`.
20
- - Do not encode actions in REST resource paths when an HTTP method already expresses the action.
21
- - Path parameters must use `snake_case`, for example `{user_id}`.
22
- - Router variables should be named `router`; shared dependency functions should use clear `snake_case` names.
13
+ ## API Endpoints
14
+ - Paths: Lowercase nouns (`/users`, `/user-profiles`, `/orders/{order_id}`).
15
+ - Avoid verbs in REST paths (use HTTP methods instead).
16
+ - Path parameters: `snake_case` (e.g. `{user_id}`).
17
+ - Routers: Name variables `router`.
@@ -0,0 +1,36 @@
1
+ ## ๐Ÿ Python AI & Hardware-Integrated Guidelines
2
+
3
+ ### ๐Ÿ”„ End-to-End Agent Development Lifecycle
4
+ AI Agents must execute all tasks following this structured 5-stage lifecycle:
5
+ 1. **Design & Code**: Implement pipeline, model, or agent code according to the modular directories below. Keep components stateless and thread-safe.
6
+ 2. **Comprehensive Testing**: Write unit tests to check input/output array shapes, verify parameter validation, and mock external API/LLM calls.
7
+ 3. **Troubleshooting & Debugging**: When diagnosing errors (like CUDA OOM or camera blockages), load and follow the `@ai-debug` skill workflow.
8
+ 4. **Code Quality & Review**: Perform a thorough self-review against `@ai-style.md` (for reproducibility, memory bounds, and prompt segregation). If working on video/hardware integrations, also conform strictly to `@ai-hardware.md`.
9
+ 5. **Edge & Production Optimization**: Verify weights quantization, thread safety, and resource cleanups before shipping model scripts.
10
+
11
+ ### ๐Ÿ—๏ธ Architecture & Directory Conventions
12
+ Organize AI, data preprocessing, and model code in a modular package layout:
13
+
14
+ ```text
15
+ src/
16
+ data/ # Dataset processing pipelines (cleaning, tokenization)
17
+ models/ # Model architectures (PyTorch, TensorFlow wrappers)
18
+ agents/ # LLM workflows, prompts, and agent tools registry
19
+ training/ # Training and fine-tuning routines
20
+ inference/ # Inference pipelines or API deployment logic
21
+ notebooks/ # Jupyter/IPython notebooks for EDA and experiments
22
+ configs/ # YAML/JSON configurations for hyperparameters
23
+ ```
24
+
25
+ ### โš™๏ธ Coding Guidelines
26
+ - **Reproducibility**: Set random seeds globally using the helper in `@ai-style.md` for any code creating data splits or training networks.
27
+ - **Resource Management**: Release camera streams (`cv2.VideoCapture`) or serial port interfaces inside `finally` blocks or using context managers.
28
+ - **Thread Safety**: Process high-frequency video frames or sensor inputs on a separate thread; exchange frames using thread-safe queues.
29
+
30
+ ### ๐Ÿงช Verification & Linting Pipeline
31
+ Before completing any task, run the following verification commands in the project directory:
32
+
33
+ ```bash
34
+ {{runCommand}} ruff check .
35
+ {{runCommand}} -m pytest
36
+ ```
@@ -0,0 +1,36 @@
1
+ # Python Hardware-Integrated & Edge AI Rules
2
+
3
+ ## 1. Thread-safe Frame & Sensor Capture
4
+ - Do not process camera/sensor input on the main thread. Use a dedicated daemon thread and pass data/frames using a thread-safe Queue:
5
+ ```python
6
+ class FrameReader:
7
+ def __init__(self, source=0):
8
+ self.cap = cv2.VideoCapture(source)
9
+ self.queue = Queue(maxsize=10)
10
+ self.stopped = False
11
+ def start(self):
12
+ threading.Thread(target=self.update, daemon=True).start()
13
+ def update(self):
14
+ while not self.stopped:
15
+ ret, frame = self.cap.read()
16
+ if ret and not self.queue.full():
17
+ self.queue.put(frame)
18
+ ```
19
+
20
+ ## 2. Resource Management
21
+ - Always release camera captures, serial ports, and windows in a `finally` block:
22
+ ```python
23
+ try: ...
24
+ finally:
25
+ cap.release()
26
+ cv2.destroyAllWindows()
27
+ ```
28
+
29
+ ## 3. Frame Buffers
30
+ - Use circular buffers to store frame history to avoid memory leaks:
31
+ `frame_buffer = deque(maxlen=30)`
32
+
33
+ ## 4. Edge Optimization
34
+ - Avoid pixel loops. Use vectorized NumPy operations (e.g. `binary = (gray > th).astype(np.uint8) * 255`).
35
+ - Quantize model weights to FP16 or INT8 (using ONNX Runtime / TFLite) for CPU/edge deployment.
36
+
@@ -0,0 +1,30 @@
1
+ # Python AI & LLM Style Rules
2
+
3
+ ## 1. GPU & Memory Management
4
+ - Allocate device dynamically (never hardcode `"cuda"` or `"cpu"`):
5
+ `device = torch.device("cuda" if torch.cuda.is_available() else "cpu")`
6
+ - Wrap evaluation/inference in `with torch.no_grad():` to save VRAM.
7
+ - Clear cache in long loops/batch runs: `torch.cuda.empty_cache()`.
8
+
9
+ ## 2. Reproducibility
10
+ - Set seeds globally at startup:
11
+ ```python
12
+ def set_seed(seed=42):
13
+ random.seed(seed)
14
+ np.random.seed(seed)
15
+ torch.manual_seed(seed)
16
+ if torch.cuda.is_available():
17
+ torch.cuda.manual_seed_all(seed)
18
+ ```
19
+
20
+ ## 3. Data Leakage
21
+ - Fit encoders/scalers/tokenizers ONLY on the training split (never val/test).
22
+ - Assert data shapes/bounds before starting training loops.
23
+
24
+ ## 4. LLM & Prompts
25
+ - Decouple prompts: Store prompts in separate files (JSON, YAML, .txt) instead of hardcoding strings in Python files.
26
+ - Validate inputs using Pydantic before calling LLM APIs.
27
+
28
+ ## 5. Metrics Logging
29
+ - Log metrics via standard python `logging` or tools (MLflow, W&B, TensorBoard). Avoid `print` statements.
30
+
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: ai-agent
3
+ description: Generates or extends an LLM agent workflow or prompt configuration
4
+ ---
5
+
6
+ Follow this workflow to build a new LLM agent, tool registry, or prompt context loop.
7
+
8
+ Inputs:
9
+ - agentName: Name of the agent component (e.g., `doc_summarizer`)
10
+ - llmClient: Target LLM model/API (e.g., `openai`, `gemini`, `ollama`)
11
+
12
+ Steps:
13
+ 1. Examine existing LLM adapters, configuration settings, and prompts in the codebase.
14
+ 2. Define the system prompt templates:
15
+ - Save prompts as configuration files (JSON/YAML) or static templates. Do not hardcode long string templates in raw python files.
16
+ 3. Implement the Agent client/runner class:
17
+ - Set up API keys dynamically from environment variables (no hardcoded secrets).
18
+ - Implement tool registrations (e.g. function calling definitions) with strict parameter validations.
19
+ - Enforce memory state preservation (e.g., session handling, conversation buffers).
20
+ 4. Add unit and integration tests:
21
+ - Mock API client calls to avoid charging external keys during test runs.
22
+ - Verify tool parameter validation errors return correct user warning boundaries.
23
+ 5. Run validations:
24
+ - Run tests and quality verification commands.
@@ -0,0 +1,31 @@
1
+ ---
2
+ name: ai-debug
3
+ description: Systematically diagnoses and resolves Python AI, memory, and hardware errors
4
+ ---
5
+
6
+ Follow this workflow to debug, reproduce, and resolve errors in the Python AI project.
7
+
8
+ Inputs:
9
+ - errorMessage: Stack trace, error logs, or problem description
10
+ - componentName: Name of the suspected class, package, or API endpoint
11
+
12
+ Steps:
13
+ 1. **Analyze Stack Traces & Exceptions:**
14
+ - Locate the exact exception class (e.g. `RuntimeError: CUDA out of memory`, `cv2.error`, `ValidationError` in Pydantic).
15
+ - Find the exact file and line number where the failure occurs.
16
+
17
+ 2. **Diagnose Common AI & Hardware Failures:**
18
+ - **CUDA OOM**: Check if batch size is too large or if gradients are accumulating (verify if `with torch.no_grad():` is used for inference). Clear cache with `torch.cuda.empty_cache()`.
19
+ - **OpenCV/Serial blockages**: Check if cameras or ports were left open. Verify resources are closed in a `finally` block or using a context manager.
20
+ - **Prompt Drift / LLM mismatch**: Validate if the arguments sent to the LLM client match the expected Pydantic schema.
21
+
22
+ 3. **Write a Reproducing Test:**
23
+ - Before writing the fix, add a minimal unit test under `tests/` that passes the failing input parameters and triggers the exact error.
24
+ - Run the test and confirm it fails.
25
+
26
+ 4. **Apply the Fix & Verify:**
27
+ - Fix the bug in the code.
28
+ - Run the reproducing test and confirm it passes.
29
+ - Run linter and tests:
30
+ - `{{runCommand}} ruff check .`
31
+ - `{{runCommand}} -m pytest`
@@ -0,0 +1,25 @@
1
+ ---
2
+ name: ai-model
3
+ description: Generates or extends a Python machine learning model architecture or training script
4
+ ---
5
+
6
+ Follow this workflow to define a new model architecture or write a training/evaluation routine.
7
+
8
+ Inputs:
9
+ - modelName: Name of the model component (e.g., `face_encoder`)
10
+ - framework: The target framework (e.g., `pytorch`, `onnx`)
11
+
12
+ Steps:
13
+ 1. Examine existing models or wrappers in the codebase to keep signatures and abstractions consistent.
14
+ 2. Define the model architecture class:
15
+ - Make device configuration dynamic (`device` GPU/CPU delegation).
16
+ - Use correct data types (e.g. FP32 for training, FP16/INT8 for edge inference).
17
+ 3. Write the training or inference execution script:
18
+ - Set random seeds globally using standard random/numpy/torch configurations.
19
+ - For training loops: output logging metrics (loss, evaluation score) to TensorBoard/MLflow.
20
+ - For inference loops: wrap logic within `torch.no_grad()` contexts to save VRAM.
21
+ 4. Write tests:
22
+ - Assert input/output tensor dimensions.
23
+ - Verify the forward pass with mock inputs (assert shape and type).
24
+ 5. Run validations:
25
+ - Run unit tests and style linter commands.
@@ -0,0 +1,24 @@
1
+ ---
2
+ name: ai-pipeline
3
+ description: Generates or extends a Python data preprocessing or ingestion pipeline
4
+ ---
5
+
6
+ Follow this workflow to create a new dataset pipeline, loader, or feature cleaning routine.
7
+
8
+ Inputs:
9
+ - pipelineName: Name of the data pipeline component (e.g., `face_alignment`)
10
+ - inputSource: Description of raw input (e.g., `camera_frames`, `text_corpus`)
11
+
12
+ Steps:
13
+ 1. Inspect neighboring codebase files to understand local directory layouts and input/output schema conventions.
14
+ 2. Define input preprocessing utilities:
15
+ - Handle invalid/null inputs, empty values, or dimension mismatches.
16
+ - Vectorize array transformations using NumPy (avoid pixel-by-pixel loops).
17
+ 3. Create the data ingestion/loader class:
18
+ - Implement batch loading or caching to prevent memory blockages.
19
+ - For file-based operations, verify try-except-finally release locks.
20
+ 4. Add verification and test scripts:
21
+ - Write a unit test asserting shape transformations, boundary inputs, and types.
22
+ - Validate execution speed on standard sample frames or test inputs.
23
+ 5. Run code formatting:
24
+ - Run linter/formatter check: e.g. `ruff check .` or `black --check .`
@@ -1,34 +1,29 @@
1
1
  # React + TypeScript Style Rules
2
2
 
3
- All React + TypeScript code in this project must follow these rules.
4
-
5
3
  ## Naming
6
- - Components use PascalCase and live in PascalCase files: `Navbar.tsx`, `InstallSection.tsx`.
7
- - Custom hooks use camelCase, start with `use`, and live in matching files: `useAuth.ts`, `useBillingData.ts`.
8
- - Helper functions and variables use camelCase: `formatCurrency`, `isSubmitting`.
9
- - Interfaces and type aliases use PascalCase: `ButtonProps`, `AuthState`.
10
- - Constants that represent fixed configuration may use SCREAMING_SNAKE_CASE only when already established locally.
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`).
11
8
 
12
9
  ## Imports
13
- - Use absolute imports from the `@/` alias for source modules.
14
- - Do not use parent-chain relative imports such as `../../components/Button`.
15
- - Prefer `import type` for type-only imports.
16
- - Keep feature internals private unless exported through a feature `index.ts`.
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.
17
13
 
18
- ## React and JSX
19
- - Keep components focused on rendering and composition.
20
- - Move data fetching, subscriptions, timers, storage access, and other side effects into custom hooks.
21
- - Boolean JSX attributes must use shorthand: `<Input disabled />`, not `<Input disabled={true} />`.
22
- - Pass event handlers as named functions when the body is more than a single expression.
23
- - Render loading, error, empty, and success states for async UI.
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.
24
19
 
25
20
  ## State Management
26
- - Prefer local state for component-only interactions.
27
- - Use Context API for stable app-level concerns such as auth, theme, locale, or configuration.
28
- - Use Zustand for shared mutable state that changes often or is consumed across distant features.
29
- - Do not introduce global state for data that can remain feature-local.
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.
30
24
 
31
25
  ## Testing
32
- - Test user-visible behavior with React Testing Library.
33
- - Add hook tests when a custom hook owns branching logic, async behavior, or cleanup.
34
- - Avoid snapshots unless the output is intentionally stable and small.
26
+ - Test user behavior via React Testing Library.
27
+ - Test hooks with complex branching/cleanup.
28
+ - Avoid snapshot testing unless output is small & stable.
29
+
@@ -1,10 +1,19 @@
1
1
  ## โ˜• Java Spring Boot Guidelines
2
2
 
3
+ ### ๐Ÿ”„ End-to-End Agent Development Lifecycle
4
+ AI Agents must execute all Java Spring Boot tasks following this structured 5-stage lifecycle:
5
+ 1. **Design & Code:** Implement layers following the structure guidelines below. Keep logic inside the Service layer.
6
+ 2. **Comprehensive Testing:** Write unit tests for services, `@WebMvcTest` for controllers (covering null inputs, bad payloads, and validation boundaries), and `@DataJpaTest` for database operations.
7
+ 3. **Troubleshooting & Debugging:** When debugging failures, load and follow the `@spring-debug` skill to isolate issues and write reproducing tests.
8
+ 4. **Code Quality & Review:** Perform self-review using `@code-review.md` to check transaction boundaries (`@Transactional`), exceptions, and security checkpoints.
9
+ 5. **Production Readiness:** Verify deployment safety rules in `@production-ready.md` (including database migrations, profiles, and Actuator metrics configuration).
10
+
3
11
  ### ๐Ÿ—๏ธ Architecture & Package Conventions
12
+ {{#if (eq packageLayout "feature-first")}}
4
13
  Follow a strict **feature-first** modular packaging layout. Each feature module (e.g. `customer`) must encapsulate all its layers within it:
5
14
 
6
15
  ```text
7
- src/main/java/com/acme/app/
16
+ src/main/java/{{packagePath}}/
8
17
  customer/
9
18
  dto/
10
19
  CreateCustomerRequest.java
@@ -24,7 +33,7 @@ src/main/java/com/acme/app/
24
33
 
25
34
  Corresponding test directories must match the feature layout exactly:
26
35
  ```text
27
- src/test/java/com/acme/app/
36
+ src/test/java/{{packagePath}}/
28
37
  customer/
29
38
  repository/
30
39
  CustomerRepositoryTest.java # Custom query repository slice tests
@@ -33,10 +42,42 @@ src/test/java/com/acme/app/
33
42
  web/
34
43
  CustomerControllerTest.java # Web MVC slice tests
35
44
  ```
45
+ {{else}}
46
+ Follow a standard **layer-first** packaging layout:
47
+
48
+ ```text
49
+ src/main/java/{{packagePath}}/
50
+ controller/
51
+ CustomerController.java
52
+ service/
53
+ CustomerService.java
54
+ impl/CustomerServiceImpl.java
55
+ repository/
56
+ CustomerRepository.java
57
+ entity/
58
+ Customer.java
59
+ dto/
60
+ CreateCustomerRequest.java
61
+ CustomerResponse.java
62
+ mapper/
63
+ CustomerMapper.java
64
+ ```
65
+
66
+ Corresponding test directories must match the layer layout exactly:
67
+ ```text
68
+ src/test/java/{{packagePath}}/
69
+ controller/
70
+ CustomerControllerTest.java # Web MVC slice tests
71
+ service/
72
+ CustomerServiceTest.java # Business logic unit tests (using Mockito)
73
+ repository/
74
+ CustomerRepositoryTest.java # Custom query repository slice tests
75
+ ```
76
+ {{/if}}
36
77
 
37
78
  ### โš™๏ธ Coding Guidelines
38
79
  - **Dependency Injection:** Prefer constructor injection. Do NOT use field-based injection (`@Autowired`).
39
- - **DTO Validation:** Request DTOs must enforce schemas using `jakarta.validation.constraints` annotations (e.g., `@NotNull`, `@NotBlank`, `@Size`, `@Email`).
80
+ - **DTO Validation:** Request DTOs must enforce schemas using `{{validationLibrary}}.constraints` annotations (e.g., `@NotNull`, `@NotBlank`, `@Size`, `@Email`).
40
81
  - **Layer Separation:** Keep controllers thin; delegate all business rules, transactions, and transformations to the service layer.
41
82
 
42
83
  ### ๐Ÿ› ๏ธ Tooling & Quality Standards
@@ -61,7 +102,7 @@ The project runs Checkstyle for static analysis and Spotless for code formatting
61
102
  </plugin>
62
103
  ```
63
104
 
64
- ### ๐Ÿงช Testing Guidelines
105
+ ### ๐Ÿงช Testing Guidelines (using {{testFramework}})
65
106
  All edits must pass local verification tests before completion:
66
107
 
67
108
  | Test Type | Requirement | Done Criteria |
@@ -71,9 +112,22 @@ All edits must pass local verification tests before completion:
71
112
  | **`@DataJpaTest`** | For custom repository queries | Verify custom query logic and entity-database column mappings. |
72
113
  | **`@SpringBootTest`** | Complex integrations only | Smoke test the application startup and critical cross-module integrations. |
73
114
 
115
+ {{#if isMicroservice}}
116
+ ### ๐ŸŒ Microservice Guidelines
117
+ This module is configured as a **microservice** registered under:
118
+ - **Service Name:** `{{springApplicationName}}`
119
+ - **Server Port:** `{{serverPort}}`
120
+
121
+ **Key Directives:**
122
+ - **Communication:** Always use `@FeignClient` calling service names for communicating with other services. Do not hardcode service ports or URLs.
123
+ - **Resilience:** Protect external requests with Resilience4j circuit breakers and define fallback procedures.
124
+ - **Tracing:** Propagate `X-Correlation-Id` headers and verify trace tracing IDs exist in the logger config.
125
+ - **Exception handling:** Define standard Feign `ErrorDecoder` implementations to map downstream client exception status codes correctly.
126
+ {{/if}}
127
+
74
128
  ### ๐Ÿš€ Verification Commands
75
129
  Before completing a task, run the following verification pipeline locally:
76
130
  ```bash
77
- ./mvnw clean test
78
- ./mvnw verify
131
+ {{buildCommand}} clean test
132
+ {{buildCommand}} {{buildVerifyArgs}}
79
133
  ```
@@ -0,0 +1,22 @@
1
+ # Java Spring Boot Code Review & Security Rules
2
+
3
+ ## 1. `@Transactional`
4
+ - Use `readOnly = true` for read-only service methods.
5
+ - Avoid self-invocation (calling `@Transactional` from same bean).
6
+ - Use `rollbackFor = Exception.class` for checked exceptions.
7
+
8
+ ## 2. Exception Handling
9
+ - Never catch & swallow exceptions. Log with stack trace: `logger.error("Msg: {}", err.getMessage(), err)`.
10
+ - Use `@RestControllerAdvice` for global error mapping.
11
+ - Map custom exceptions (e.g. `ResourceNotFoundException`) to HTTP statuses.
12
+
13
+ ## 3. Security Checkpoints
14
+ - Avoid SQL injection: Use parameterized queries/bind variables, never string concatenation.
15
+ - Enforce authorization via Spring Security annotations (e.g., `@PreAuthorize`) on Controller/Service.
16
+ - Annotate request bodies with validation constraints (`@NotBlank`, `@Size`).
17
+
18
+ ## 4. Quality & Resource Management
19
+ - Prevent resource leaks: Use `try-with-resources`.
20
+ - Keep beans stateless/thread-safe.
21
+ - Remove unused imports, comments, and debug logs.
22
+
@@ -1,14 +1,9 @@
1
1
  # Java Spring Boot Style Constraints
2
2
 
3
- Enforce strict coding style and layer definitions in this repository.
3
+ - Style: Google Java style.
4
+ - Imports: standard java first, third-party second, internal last.
5
+ - Generics: Do not use raw types. Specify generic parameters.
6
+ - Architecture: Follow layers in @AGENTS.md.
7
+ - Testing: Cover custom database queries with `@DataJpaTest`.
8
+ - Verification: Run `{{buildCommand}} {{buildVerifyArgs}}` before completion.
4
9
 
5
- ## Coding Style
6
- - Follow standard project style guidelines (default Google Java style).
7
- - Organize imports cleanly: standard java libraries first, third-party libraries second, internal imports last.
8
- - Do not use raw types. Always specify generic parameters.
9
-
10
- ## Integration & Layers
11
- - Follow rules defined in @AGENTS.md.
12
- - Ensure all custom database queries are covered by repository slice tests (`@DataJpaTest`).
13
- - Before completing work, execute:
14
- - `./mvnw verify`
@@ -0,0 +1,22 @@
1
+ # Spring Boot Microservice Design Rules
2
+
3
+ - Service Name: `{{springApplicationName}}`
4
+ - Local Port: `{{serverPort}}`
5
+
6
+ ## 1. Naming & Ports
7
+ - `spring.application.name` must match the module directory name in kebab-case.
8
+ - Local server ports must be allocated in advance to prevent clashes.
9
+
10
+ ## 2. Inter-service Communication (Feign Client)
11
+ - Do not use hardcoded URLs/IPs. Use Service Discovery (Eureka/Consul).
12
+ - Place `@FeignClient` interfaces in `{{basePackage}}.client` or `{{basePackage}}.feign`.
13
+ - Implement a custom `ErrorDecoder` to propagate downstream HTTP status codes instead of throwing generic 500 FeignExceptions.
14
+
15
+ ## 3. Resilience
16
+ - Wrap outgoing Feign calls in Resilience4j `@CircuitBreaker` or `@TimeLimiter`.
17
+ - Implement a `fallbackMethod` for graceful fallback handling when services fail.
18
+
19
+ ## 4. Distributed Tracing
20
+ - Log actions with `X-Correlation-Id` or `TraceId` (Micrometer Tracing).
21
+ - Configure a Feign `RequestInterceptor` to forward the `X-Correlation-Id` header to downstream calls.
22
+
@@ -0,0 +1,20 @@
1
+ # Java Spring Boot Production Readiness Rules
2
+
3
+ ## 1. Database Migrations
4
+ - Set `spring.jpa.hibernate.ddl-auto` to `none` or `validate` in production (never `update`/`create`).
5
+ - Manage schema changes using versioned migration files (e.g. Flyway `.sql` scripts in `src/main/resources/db/migration/`).
6
+
7
+ ## 2. Configuration & Profiles
8
+ - Separate environments using profiles (`application-dev.yml`, `application-prod.yml`).
9
+ - Never hardcode credentials. Inject via environment variables: `password: ${DATABASE_PASSWORD:default_dev_pass}`.
10
+ - Use `@ConfigurationProperties` + `@Validated` to check configurations at startup.
11
+
12
+ ## 3. Monitoring (Spring Boot Actuator)
13
+ - Enable Actuator. Configure `/actuator/health` to check database/critical services.
14
+ - Secure sensitive endpoints. Publicly expose only safe ones:
15
+ `management.endpoints.web.exposure.include: health,info,metrics`
16
+
17
+ ## 4. API Stability
18
+ - Annotate controllers with OpenAPI/Swagger (`@Tag`, `@Operation`, `@ApiResponse`).
19
+ - Enable graceful shutdown: `server.shutdown: graceful`.
20
+