[autoresearch] baseline: system prompt quality tests (5/5 passing)

This commit is contained in:
evandrodevbr committed 2026-04-11 05:27:36 -03:00
1 parent 05cc036f6d
commit 60b0101717
142 files changed
+18589 -9947

No files matched your search

+115
View File
@@ -0,0 +1,115 @@
---
description: Research phase - understand context and gather knowledge
---
# Phase 1: Research
## Purpose
Understand the request context AND gather accurate, up-to-date knowledge before writing any code.
## Steps
### 1. Analyze Request
Parse the user's request and identify:
- What are they asking for?
- What is the scope?
### 2. Review Current Implementation
Check the repository to understand:
- Current technical architecture
- Existing implementation patterns
- Dependencies and configurations
### 3. Build Mental Model
Inventory:
- Business requirements
- Technical constraints
- Integration points with existing code
### 4. Define Scope
Use `task_boundary` to set mode to **PLANNING**
Create a plan with bite-sized atomic tasks in `task.md`:
- `[ ]` = Not started
- Use indented lists for sub-items
### 5. Identify Research Topics
List all technologies, libraries, and patterns involved in this task.
Example:
```
Topics for "Task CRUD API":
- Go http.ServeMux routing patterns
- SQLC query generation
- UUID handling in PostgreSQL
- JWT authentication middleware
```
### 6. Search External Documentation
For EACH topic, search external documentation using the best tool available in your environment:
**Documentation search tools (use whichever is available):**
- **Qurio** (`mcp_qurio_qurio_search`, `mcp_qurio_qurio_read_page`) — if Qurio MCP is enabled
- **Context7** or similar MCP documentation servers — if available
- **`search_web` / `read_url_content`** — universal fallback always available
**Search strategy (2-5 keywords per query):**
```
# Using available documentation tool:
search(query="Go ServeMux routing")
search(query="SQLC CRUD queries")
search(query="Pinia store setup")
# For deeper reading on a specific URL:
read_page(url="https://go.dev/doc/<topic>")
```
### 7. Document Findings
Create `docs/research_logs/{feature_name}.md` with:
- Key patterns discovered
- Code examples from documentation
- API signatures and options
- Gotchas or edge cases found
#### Research Log Naming
Each feature should have its own research log:
```
docs/research_logs/
├── epic1_auth.md # Epic 1: Authentication
├── epic2_task.md # Epic 2: Task CRUD
├── epic3_lists.md # Epic 3: Lists
└── {feature_name}.md # Pattern: one log per feature
```
### 8. Document Architecture Decisions
If any decision involves:
- Choosing between 2+ viable approaches
- Introducing a new dependency or pattern
- Changing existing architecture
Then create an ADR using the **ADR Skill** at `docs/decisions/NNNN-short-title.md`.
**Skills to consider:**
- **Sequential Thinking** — for complex design decisions with multiple trade-offs
### 9. Fallback: State Training Data Usage
If relying on training data, explicitly state:
> "I am relying on my training data for this solution as external verification was unavailable."
## If This Phase Fails
If no documentation search tool yields results:
1. Document what was searched
2. State: "Relying on training data"
3. Proceed with caution
4. Flag for human review if critical
## Completion Criteria
- [ ] Request analyzed and scope defined
- [ ] `task.md` created with atomic tasks
- [ ] Research log created at `docs/research_logs/{feature_name}.md`
- [ ] All major technologies researched
- [ ] Code examples documented
- [ ] Architecture decisions documented as ADRs (if applicable)
## Next Phase
Proceed to **Phase 2: Implement** (`/2-implement`)
+101
View File
@@ -0,0 +1,101 @@
---
description: Implement phase - TDD cycle for writing code
---
# Phase 2: Implement
## Purpose
Write production code following Test-Driven Development (TDD).
## Prerequisites
- Phase 1 (Research) completed
- Research log exists at `docs/research_logs/{feature_name}.md`
- Mark task as `[/]` in task.md
## Steps
**Set Mode:** Use `task_boundary` to set mode to **EXECUTION**.
### 1. Create Test File
Co-locate with implementation:
- Go: `*_test.go`
- TypeScript: `*.spec.ts`
### 2. Write Failing Test (Red)
```go
func TestCreateTask_Success(t *testing.T) {
// Arrange
mockStore := NewMockStorage()
service := NewService(mockStore, logger)
// Act
task, err := service.Create(ctx, userID, req)
// Assert
require.NoError(t, err)
assert.Equal(t, "Test Task", task.Title)
}
```
Run test to confirm it fails:
```bash
# Go
go test -v ./internal/features/{feature}/...
# Frontend
pnpm run test -- --watch
```
### 3. Write Minimal Code (Green)
Write ONLY enough code to make the test pass.
Run test to confirm it passes:
```bash
go test -v ./internal/features/{feature}/...
```
### 4. Refactor (Blue)
Improve the code while keeping tests green:
- Improve names and structure
- Remove duplication
- **Follow predefined agent rules** (read applicable `.agents/rules/*.md`)
- **Handle errors** per Error Handling Principles
- **Add logging** per Logging and Observability Mandate
- If the refactoring is complex, activate the **Sequential Thinking** skill
- If debugging a failing test, activate the **Debugging Protocol** skill
- Ensure tests still pass
### 5. Repeat
Continue Red-Green-Refactor for each behavior.
## Unit Test Requirements
- Mock all dependencies (interfaces)
- Test happy path, error paths AND edge cases
- Target >85% coverage on domain logic
## Development Commands
```bash
# Run specific test
go test -v -run TestCreateTask ./internal/features/task/...
# Run with coverage
go test -cover ./internal/features/task/...
# Frontend tests
pnpm run test
pnpm run test -- --coverage
```
## Completion Criteria
- [ ] Unit tests written and passing
- [ ] Implementation complete
- [ ] Error handling follows principles
- [ ] Logging added to operations
- [ ] Code follows project patterns
- [ ] List all I/O adapters modified or created (storage files, external API clients)
- [ ] If adapters were modified: Phase 3 is MANDATORY — do not skip
## Next Phase
Proceed to **Phase 3: Integrate** (`/3-integrate`)
+95
View File
@@ -0,0 +1,95 @@
---
description: Integrate phase - test adapters with real infrastructure
---
# Phase 3: Integrate
## Purpose
Test adapter implementations (database, external APIs) with real infrastructure using Testcontainers.
## Prerequisites
- Phase 2 (Implement) completed
- Unit tests passing
## Applicability (Default: REQUIRED)
This phase is REQUIRED by default. You may ONLY skip it if ALL of the following are true:
- [ ] No storage/repository files were modified or created
- [ ] No external API client files were modified or created
- [ ] No database queries or schemas were changed
- [ ] No message queue, cache, or I/O adapter code was touched
If ANY adapter was modified, you MUST write integration tests.
## If This Phase Fails
If integration tests fail:
1. Check container logs for errors
2. Verify schema matches expectations
3. Fix adapter implementation
4. Re-run tests before proceeding
## Steps
### 1. Setup Testcontainers
**Go Example:**
```go
func TestPostgresStorage_Integration(t *testing.T) {
if testing.Short() {
t.Skip("skipping integration test")
}
ctx := context.Background()
// Start PostgreSQL container
postgres, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: testcontainers.ContainerRequest{
Image: "postgres:16-alpine",
ExposedPorts: []string{"5432/tcp"},
Env: map[string]string{
"POSTGRES_USER": "test",
"POSTGRES_PASSWORD": "test",
"POSTGRES_DB": "test",
},
WaitingFor: wait.ForListeningPort("5432/tcp"),
},
Started: true,
})
require.NoError(t, err)
defer postgres.Terminate(ctx)
// Get connection string and run tests
}
```
### 2. Write Integration Tests
Test file naming: `*_integration_test.go` or `*.integration.spec.ts`
```go
func TestPostgresStorage_CreateTask(t *testing.T) {
// Uses real PostgreSQL from Testcontainers
storage := NewPostgresStorage(pool)
task, err := storage.Create(ctx, userID, req)
require.NoError(t, err)
assert.NotEqual(t, uuid.Nil, task.ID)
}
```
### 3. Run Integration Tests
```bash
# Go - run all tests including integration
go test -v ./...
```
### 4. Manual Check (Optional)
- If UI involved, launch a browser to verify the basic flow.
- If API involved, use `curl` or `client` to hit the endpoint.
## Completion Criteria
- [ ] Integration tests written for all adapters
- [ ] Tests pass with real infrastructure (Testcontainers)
- [ ] Database queries verified against real PostgreSQL
## Next Phase
Proceed to **Phase 4: Verify** (`/4-verify`)
+87
View File
@@ -0,0 +1,87 @@
---
description: Verify phase - run full validation suite
---
# Phase 4: Verify
## Purpose
Run all linters, static analysis, and tests to ensure code quality.
> **Note:** Paths below follow the project structure defined in `project-structure.md`.
> Adjust paths to match the actual project layout (e.g. `apps/backend`, `apps/frontend`).
### Phase 3 Gate
- [ ] Were any storage/database adapter files modified? List them: ___
- [ ] Were any external API adapters modified? List them: ___
- [ ] If YES to either: are integration tests written and passing?
- [ ] If NO to both: state why Phase 3 was skipped
> CRITICAL: If you modified `*_pg.go`, `*_integration*.go`, or any SQL query, Phase 3 is MANDATORY. Do not proceed without integration tests.
### Phase 3.5 Gate
- [ ] Were any UI changes or modified? List them: ___
- [ ] If YES: are E2E tests written and passing?
- [ ] If NO to both: state why Phase 3.5 was skipped
> CRITICAL: If you modified `frontend/*` or any frontend component and integration point, Phase 3.5 is MANDATORY. Do not proceed without E2E tests.
## If This Phase Fails
If lint/test/build fails:
1. **Do not proceed** to Ship
2. Fix the issue (go back to Phase 2 or 3 as needed)
3. Re-run full verification
4. Only proceed when ALL checks pass
## Steps
**Set Mode:** Use `task_boundary` to set mode to **VERIFICATION**.
### 1. Backend Validation
Run the FULL validation suite for the backend path as defined in `project-structure.md`:
```bash
# // turbo
# Adjust path per project-structure.md (default: apps/backend)
cd apps/backend && gofumpt -l -e -w . && go vet ./... && staticcheck ./... && gosec -quiet ./... && go test -race ./...
```
### 2. Frontend Validation
```bash
# // turbo
# Adjust path per project-structure.md (default: apps/frontend)
cd apps/frontend && pnpm run lint --fix && npx vue-tsc --noEmit && pnpm run test
```
### 3. Build Check
```bash
# Backend (path per project-structure.md)
cd apps/backend && go build ./...
# Frontend (path per project-structure.md)
cd apps/frontend && pnpm run build
```
### 4. Check Coverage
Report actual coverage in task summary.
**Go:**
```bash
go test -cover ./internal/features/...
```
**Frontend:**
```bash
pnpm run test -- --coverage
```
## Completion Criteria
- [ ] All lint checks pass
- [ ] All tests pass
- [ ] Build succeeds
- [ ] Coverage reported (target >85% on domain logic)
## On Success
Mark task as `[x]` in task.md (verification passed = task complete).
## Next Phase
Proceed to **Phase 5: Ship** (`/5-commit`)
+55
View File
@@ -0,0 +1,55 @@
---
description: Git commit with conventional format
---
# Ship: Commit
## Purpose
Commit completed work with proper conventional commit format.
> **Note:** For detailed conventions (branch naming, commit types, PR size, merge strategy),
> see `git-workflow-principles.md` in `.agents/rules/`.
## Prerequisites
- All verification checks pass
- Code is ready for review/merge
## Steps
### 1. Review Changes
```bash
git status
git diff --staged
```
### 2. Stage Changes
```bash
# Stage all changes
git add .
# Or stage selectively (adjust path per project-structure.md)
git add apps/backend/internal/features/task/
```
### 3. Commit with Conventional Format
Follow the format from `git-workflow-principles.md`:
```bash
git commit -m "<type>(<scope>): <description>"
```
**Examples:**
```bash
git commit -m "feat(task): add CRUD API endpoints"
git commit -m "fix(auth): correct token expiry validation"
git commit -m "refactor(storage): extract interface for storage layer"
git commit -m "test(task): add integration tests for storage adapter"
```
### 4. Update task.md
Mark completed items as `[x]` in the task checklist.
## Completion Criteria
- [ ] Changes committed with proper format
- [ ] task.md updated to reflect completion
+224
View File
@@ -0,0 +1,224 @@
---
description: Code audit workflow - structured code review and quality verification
---
# Audit Workflow
## Purpose
Inspect existing code quality and produce structured findings. This workflow does not write new features — it identifies issues for subsequent fix workflows.
## When to Use
- After another agent's feature is committed (cross-agent review)
- Periodic quality gates on the codebase
- Before releases or deployments
- When user wants assurance without writing new code
- After addressing review findings, to verify the fixes
## When NOT to Use
- When writing new features (use `/orchestrator`)
- When fixing known bugs (use `/quick-fix`)
- When restructuring code (use `/refactor`)
## Pre-Audit Checklist
Before starting, you MUST:
1. Scan `.agents/rules/` directory — these form the review criteria
2. Read `rule-priority.md` for conflict resolution
3. Identify the scope of the audit (specific feature, module, or full codebase)
## Phases
### Phase 1: Code Review
**Set Mode:** Use `task_boundary` to set mode to **PLANNING**
Invoke the **Code Review Skill** against the specified files/features.
Review against these categories (in priority order from `rule-priority.md`):
#### 1. Security
- Input validation on all boundaries
- No hardcoded secrets or credentials
- Parameterized queries (no SQL injection)
- Proper authentication/authorization checks
#### 2. Reliability
- Error handling on all I/O operations (no empty catch blocks)
- All resources cleaned up (connections, files, locks)
- Timeouts on external calls
- Graceful degradation patterns
#### 3. Testability
- I/O operations behind interfaces/abstractions
- Business logic is pure (no side effects)
- Dependencies injected, not hardcoded
- Test coverage on critical paths
#### 4. Observability
- All operation entry points logged (start/success/failure)
- Structured logging with correlation IDs
- Appropriate log levels
#### 5. Code Quality
- Follows existing codebase patterns (>80% consistency)
- Functions are focused and small (10-50 lines)
- Clear naming that reveals intent
- No code duplication (DRY)
### Phase 1.5: Cross-Boundary Review
**Set Mode:** Continue in **PLANNING**
Cross-boundary issues live at the seams between components, not inside any single file. This phase defines a **menu of dimensions** — activate only those that apply to the project under audit, and explicitly state which you skipped and why.
#### Dimension Selection
| Dimension | Activate When |
|---|---|
| **A. Integration Contracts** | Project has both a frontend and a backend |
| **B. Database & Schema** | Project uses a relational/document database |
| **C. Configuration & Environment** | Always — universal |
| **D. Dependency Health** | Always — universal |
| **E. Test Coverage Gaps** | Always — universal |
| **F. Mobile ↔ Backend** | Project has a mobile app and a backend |
At the start of this phase you MUST state:
> "Activating dimensions: A, B, C, D, E. Skipping F (no mobile app)."
---
#### Dimension A: Integration Contracts
*Applies to: full-stack projects with frontend + backend*
- [ ] Map every backend endpoint (route + method) against its frontend adapter — flag any unmapped endpoints in either direction
- [ ] Verify request/response field names, types, and status codes match across the boundary
- [ ] Verify all outbound HTTP calls use the project's centralized API client (not raw `fetch`/`axios`) — see `typescript-idioms-and-patterns.md § Centralized HTTP Client`
- [ ] Build an auth coverage matrix: which endpoints require auth, do the frontend adapters send tokens for each?
- [ ] Check error contract alignment: does the frontend handle the full set of error codes the backend can return?
#### Dimension B: Database & Schema
*Applies to: projects using a relational or document database*
- [ ] Verify all tables have required base columns (`id`, `created_at`, `updated_at`)
- [ ] Check all foreign keys have corresponding indexes
- [ ] If using Supabase or Postgres RLS: verify RLS policies exist on every table storing user data
- [ ] Cross-reference the application's struct/model field names against actual DB column names — flag any drift
- [ ] Check migrations are reversible (up + down) and follow the additive-first strategy
- [ ] Scan storage adapters for N+1 query patterns
#### Dimension C: Configuration & Environment
*Always active*
- [ ] No hardcoded secrets, tokens, URLs, or credentials in source code
- [ ] `.env.template` exists and covers every env var referenced in the codebase
- [ ] Startup validation fails fast on missing required config (does not silently fall back to bad defaults)
- [ ] Secrets are never logged (not in debug, not in error messages)
#### Dimension D: Dependency Health
*Always active*
- [ ] No unused top-level dependencies in `go.mod` / `package.json` / `Cargo.toml`
- [ ] No circular dependencies between feature modules
- [ ] Cross-module imports only use each module's public API (not internal files)
- [ ] Run `npm audit` / `go list -m -json all | nancy` / `cargo audit` — flag high-severity CVEs
#### Dimension E: Test Coverage Gaps
*Always active*
- [ ] A handler/controller test exists for every API endpoint
- [ ] An integration test exists for every storage/database adapter
- [ ] Every error path (catch block, error return) has at least one test that exercises it
- [ ] E2E tests cover the primary user journeys (login, main feature flow, error states)
#### Dimension F: Mobile ↔ Backend
*Applies to: projects with a mobile app and a backend*
- [ ] API version compatibility — mobile must not call endpoints that no longer exist
- [ ] Offline data sync: conflict resolution and retry logic are tested
- [ ] Auth token refresh flows work correctly when the access token expires mid-session
---
### Phase 2: Automated Verification
**Set Mode:** Use `task_boundary` to set mode to **VERIFICATION**
Run the full validation suite (same as `/4-verify`):
1. Linters and static analysis
2. Full test suite
3. Build check
4. Coverage report
### Phase 3: Findings Report
**Output location:** `docs/audits/review-findings-{feature}-{YYYY-MM-DD}-{HHmm}.md`
You MUST save the report to the repo (not just as a conversation artifact) so it can be:
- Referenced from other conversations/agents
- Tracked in version control
- Passed as context to fix workflows
**Steps:**
1. Create the `docs/audits/` directory if it doesn't exist
2. Write the findings report to `docs/audits/review-findings-{feature}-{YYYY-MM-DD}-{HHmm}.md`
3. Use the template below
> **Zero-Findings Guard:** If the audit produces fewer than 3 findings, you MUST complete the "Dimensions Covered" attestation section in the report before declaring a clean result. This proves cross-boundary coverage was not skipped.
```markdown
# Code Audit: {Feature/Module Name}
Date: {date}
## Summary
- **Files reviewed:** N
- **Issues found:** N (X critical, Y major, Z minor)
- **Test coverage:** N%
- **Dimensions activated:** A, B, C, D, E (list which were skipped and why)
## Critical Issues
Issues that must be fixed before deployment.
- [ ] {description} — {file}:{line}
## Major Issues
Issues that should be fixed in the near term.
- [ ] {description} — {file}:{line}
## Minor Issues
Style, naming, or minor improvements.
- [ ] {description} — {file}:{line}
## Verification Results
- Lint: PASS/FAIL
- Tests: PASS/FAIL (N passed, N failed)
- Build: PASS/FAIL
- Coverage: N%
## Dimensions Covered
<!-- Required when total findings < 3 -->
| Dimension | Status | Files / Queries Examined |
|---|---|---|
| A. Integration Contracts | ✅ Checked / ⏭ Skipped (reason) | e.g., all 26 backend routes cross-referenced against 11 frontend adapters |
| B. Database & Schema | ✅ Checked / ⏭ Skipped (reason) | e.g., reviewed all 8 Supabase tables + 4 storage adapters |
| C. Configuration & Environment | ✅ Checked | e.g., scanned for raw secrets, verified .env.template |
| D. Dependency Health | ✅ Checked | e.g., ran npm audit, checked go.mod for unused deps |
| E. Test Coverage Gaps | ✅ Checked | e.g., verified handler tests for all 26 endpoints |
| F. Mobile ↔ Backend | ⏭ Skipped | No mobile app in this project |
```
## Feedback Loop
After the audit produces findings, choose the right workflow based on finding type:
| Finding Type | Example | Workflow |
| ----------------------------------------------------------------------------------- | ------------------------------------ | ------------------------------------- |
| **Nit / minor** (naming, formatting, missing comment) | "Rename `x` to `userCount`" | Fix in this conversation directly |
| **Small isolated fix** (missing log, error handling, validation) | "Add input validation on handler" | `/quick-fix` in a new conversation |
| **Structural change** (wrong abstraction, missing interface, pattern inconsistency) | "Storage not behind interface" | `/refactor` in a new conversation |
| **Missing capability** (new endpoint, feature, auth check) | "No auth middleware on admin routes" | `/orchestrator` in a new conversation |
### Using Findings in Other Contexts
When starting a fix workflow in a new conversation, reference the persisted report:
> "Fix the critical issues in `docs/audits/review-findings-gatekeeper-2026-02-16-1430.md`"
The agent in the new context can read the file directly from the repo — no need to copy-paste findings.
## Completion Criteria
- [ ] All specified files/features reviewed
- [ ] Full verification suite run
- [ ] Findings document saved to `docs/audits/` in the repo
+131
View File
@@ -0,0 +1,131 @@
---
description: End-to-end testing with Playwright MCP
---
# E2E Testing Workflow
## Purpose
Validate complete user journeys through the full system using Playwright MCP.
> **Note:** Paths below follow the project structure defined in `project-structure.md`.
> Adjust paths to match the actual project layout.
## When to Use
- After completing an epic/milestone
- Before release/deploy
- When adding critical user flows
## Prerequisites
- Services running (docker compose up or local dev)
- Feature implementation complete
- Unit and integration tests passing
## Steps
### 1. Start Services
Ensure the full stack is running:
```bash
docker compose up -d
# Wait for health checks
docker compose ps
```
Or local development:
```bash
# Terminal 1: Backend
cd apps/backend && go run cmd/api/main.go
# Terminal 2: Frontend
cd apps/frontend && pnpm run dev
```
### 2. Create E2E Test Plan
Document test cases in `e2e/{feature}-{ui|api}.e2e.test.ts`:
- Happy path flows
- Error handling
- Edge cases
### 3. Execute with Playwright MCP
**Navigate to page:**
```
mcp_playwright_browser_navigate(url="http://localhost:5173/login")
```
**Capture page state:**
```
mcp_playwright_browser_snapshot()
```
**Interact with elements (use refs from snapshot):**
```
mcp_playwright_browser_type(ref="<ref>", text="[email protected]")
mcp_playwright_browser_click(ref="<ref>")
```
**Wait for results:**
```
mcp_playwright_browser_wait_for(text="Welcome")
```
**Capture snapshot for walkthrough documentation:**
```
mcp_playwright_browser_snapshot(filename="docs/e2e-screenshots/{feature}-{description}.md")
```
### 4. Document Results
**Screenshot location:** `docs/e2e-screenshots/{feature}-{description}.png`
1. Create `docs/e2e-screenshots/` if it doesn't exist
2. Save all snapshots there with descriptive names
3. For visual proof (video recording), use `browser_subagent` with `RecordingName` parameter
4. Embed walkthrough documentation in the walkthrough artifact
5. Note any failures or issues
6. Update test files if needed
## E2E Test Structure
```
e2e/ # Single-app projects
├── api/ # (For monorepo: apps/e2e/api/)
│ └── task-crud-api.e2e.test.ts # API-only E2E
└── ui/ # (For monorepo: apps/e2e/ui/)
├── auth-flow-ui.e2e.test.ts # Browser E2E
└── task-flow-ui.e2e.test.ts
```
> Path adapts to project type per `project-structure.md` § Adapting for Different Project Types.
## Example: Auth Flow E2E
```typescript
// e2e/ui/auth-flow-ui.e2e.test.ts
describe('Authentication Flow', () => {
it('should register a new user', async () => {
// Navigate to register
// Fill form
// Submit
// Verify redirect to dashboard
});
it('should login existing user', async () => {
// Navigate to login
// Fill credentials
// Submit
// Verify dashboard loads
});
it('should show error for invalid credentials', async () => {
// Navigate to login
// Fill wrong password
// Submit
// Verify error message
});
});
```
## Completion Criteria
- [ ] All critical user flows tested
- [ ] Snapshots captured and embedded in walkthrough
- [ ] No blocking issues found
+139
View File
@@ -0,0 +1,139 @@
---
description: Build feature workflow orchestrator - chains all phases
---
# Build Feature Workflow
**CRITICAL INSTRUCTION**
YOU ARE FORBIDDEN FROM SKIPPING PHASES.
You must treat this file as a State Machine. You cannot transition to state $N+1$ until state $N$ is completely verified.
## Role
You are a Senior Principal Engineer with a mandate for strict protocol adherence.
Your responsibility is to deliver clean, testable, and idiomatic code while rigidly enforcing the End-to-End Workflow Phases. You must reject any attempt to skip phases—such as writing code without research or completing task/shipping without verification.
Crucially, you MUST strictly adhere to the comprehensive rule sets defined in `.agents/rules/` (e.g., error handling, logging, security, concurrency). These rules are non-negotiable constraints that supersede general training data.
## Pre-Implementation Checklist
Before starting any work, you MUST:
1. Scan `.agents/rules/` directory
2. Identify applicable rules for this task
3. **READ** selected rule files (they are non-negotiable constraints)
## Workflow Phases
Execute phases **sequentially**. Do not skip phases for velocity.
Never deferred quality gates to a later "hardening" phase, defensive rigour early in the cycle trumps.
```mermaid
graph LR
P1[Research] -->|Log Created| P2[Implement]
P2 -->|Unit Tests Pass| P3[Integrate]
P3 -->|Integration Tests Pass| P3b{"E2E needed?"}
P3b -->|Yes| P3c[E2E Test]
P3b -->|No| P4[Verify]
P3c -->|E2E Pass| P4[Verify]
P4 -->|All Linters Pass| P5[Ship]
```
### Phase 1: Research
**File:** `1-research.md`
**Mandatory Rules:** `project-structure.md`, `architectural-pattern.md`
- Analyze request, understand context
- Define scope in `task.md`
- Search external documentation for each technology (use available tools: Qurio, Context7, web search)
- Document findings in `docs/research_logs/{feature}.md`
- If a significant architecture decision is made, create an ADR using the **ADR Skill**
**Skills to consider:**
- **Sequential Thinking** — for complex design decisions requiring iteration
### Phase 2: Implement
**File:** `2-implement.md`
**Mandatory Rules:** `error-handling-principles.md`, `logging-and-observability-mandate.md`, `testing-strategy.md`
- TDD cycle: Red → Green → Refactor
- Unit tests with mocked dependencies
**Skills to consider:**
- **Sequential Thinking** — if refactoring is complex and requires multi-step reasoning
- **Debugging Protocol** — if a failing test has a non-obvious cause
### Phase 3: Integrate
**File:** `3-integrate.md`
**Mandatory Rules:** `testing-strategy.md`, `resources-and-memory-management-principles.md`
- Integration tests with Testcontainers
- Test adapters against real infrastructure
### Phase 3.5: E2E Validation (Conditional)
**File:** `e2e-test.md`
**When Required:**
- UI components were added or modified
- API endpoints were added or modified that interact with frontend
- Critical user-facing flows were changed
**When to Skip:**
- Pure backend/infrastructure changes
- Internal library refactoring
- Test-only changes
**Gate:** At least one critical user journey tested and screenshot captured.
### Phase 4: Verify
**File:** `4-verify.md`
**Mandatory Rules:** `code-completion-mandate.md`, all applicable mandates
- Full lint/test/build validation
- Report coverage
### Phase 5: Ship
**File:** `5-commit.md`
**Mandatory Rules:** `git-workflow-principles.md`
- Git commit with conventional format
- Update task.md
---
## Phase Management
### Task.md Updates
Use this pattern throughout phases:
- `[ ]` = Not started
- `[/]` = In progress (mark when **starting** a task)
- `[x]` = Complete (mark **only after Verify phase passes**)
**Rule:** Never mark `[x]` until Phase 4 (Verify) passes for that task.
### Phase Transitions
Before moving to the next phase, **STOP and verify**:
- [ ] Current phase completion criteria met
- [ ] Outputs created (research log, tests, etc.)
- [ ] No blocking errors
### Error Handling
If a phase fails:
1. **Document the failure** in task summary
2. **Do not proceed** to next phase
3. **Fix the issue** within current phase
4. **Re-run** phase completion criteria
5. Then proceed
### Resuming Work
To resume from a specific phase:
1. Read `task.md` to find current state (`[/]` items)
2. Read the relevant phase file
3. Continue from where you left off
4. No need to re-run completed phases
---
## Quick Reference
| Phase | Output | Blocking |
|-------|--------|----------|
| Research | `task.md` + `docs/research_logs/*.md` | Yes |
| Implement | Unit tests + code | Yes |
| Integrate | Integration tests | Yes (for adapters) |
| E2E (conditional) | E2E tests + screenshots | Yes (when required) |
| Verify | All checks pass | Yes |
| Ship | Git commit | Yes |
+100
View File
@@ -0,0 +1,100 @@
---
description: Profile-driven performance optimization workflow
---
# Performance Optimization Workflow
**Trigger:** User provides profiling data, asks to optimize performance, or benchmarks show regression.
**Skill prerequisite:** Read `.agents/skills/perf-optimization/SKILL.md` before starting.
// turbo-all
## Steps
### 1. Load the Skill
Read the perf-optimization skill and the relevant language module:
```
view_file .agents/skills/perf-optimization/SKILL.md
view_file .agents/skills/perf-optimization/languages/{language}.md
```
### 2. Collect Profile Data
**If the user provides a profile file or URL:**
- Use the language-appropriate extraction script (e.g., `scripts/go-pprof.sh cpu profile.prof`)
**If the user asks to profile from scratch:**
- Run the extraction script in `bench` mode to generate AND analyze profiles in one step:
```bash
bash .agents/skills/perf-optimization/scripts/go-pprof.sh bench ./path/to/package/... BenchmarkName
```
### 3. Analyze
Create a structured analysis document:
```
docs/research_logs/{component}-perf-analysis.md
```
Follow the analysis methodology from SKILL.md:
1. Focus on cumulative, trace flat back to user-land code
2. Identify top 3-5 offenders
3. Separate benchmark artifacts from production cost
4. Identify irreducible floors (reference the language module's table)
### 4. Prioritize Fixes
Create an implementation plan ranking fixes by impact/risk:
- Low risk, high impact → do first
- High risk, any impact → do last or skip
Present the plan to the user for approval before proceeding.
### 5. Implement (one fix at a time)
For each fix, follow the orchestrator workflow:
1. **Write tests first** (TDD Red → Green)
2. **Implement the fix**
3. **Run all existing tests** (`go test -race ./...` or equivalent)
4. **Benchmark immediately** — compare ns/op, B/op, allocs/op
5. **Run quality checks** (formatter, linter, security scanner)
6. **Commit independently** with conventional format: `perf(scope): description`
**Rule:** One fix per commit. Never batch optimizations.
### 6. Final Verification
After all fixes are applied:
1. Run the full benchmark suite with `-count=3` minimum
2. Compare against the original baseline (before any fixes)
3. Run the complete test suite with `-race`
4. Run all quality checks (formatter, linter, security scanner, build)
### 7. Document Results
Update the analysis document with:
- Before/after benchmark comparison table
- Which fixes were applied and which were skipped (and why)
- Any remaining optimization opportunities for future sessions
### 8. Ship
Commit and present the final results to the user with:
- Cumulative benchmark improvement table
- List of commits
- Any follow-up items
---
## Quick Reference
| Phase | Output | Gate |
|---|---|---|
| Profile | Raw data + extracted markdown | Data collected |
| Analyze | `docs/research_logs/{component}-perf-analysis.md` | Top offenders identified |
| Prioritize | Implementation plan | User approved |
| Implement | Tests + code + benchmark per fix | Each fix passes tests |
| Verify | Full benchmark comparison | All checks pass |
| Ship | Conventional commits | User notified |
+58
View File
@@ -0,0 +1,58 @@
---
description: Quick-fix workflow for hotfixes and small bug fixes - skip research, minimal verify
---
# Quick-Fix Workflow
## Purpose
Fast-track bug fixes and small changes that don't require full research or integration phases.
## When to Use
- Bug fixes with a known root cause
- Small, isolated changes (< 50 lines)
- Hotfixes for production issues
- Addressing review findings from `/audit`
## When NOT to Use
- New features (use `/orchestrator`)
- Refactoring (use `/refactor`)
- Changes touching multiple features or modules
## Pre-Implementation Checklist
Before starting, you MUST:
1. Scan `.agents/rules/` directory for applicable rules
2. Read `rule-priority.md` for conflict resolution
3. Confirm the fix scope is truly small and isolated
## Phases
### Phase 1: Diagnose
**Set Mode:** Use `task_boundary` to set mode to **PLANNING**
1. Identify the bug or issue
2. Locate the affected code
3. If the cause is not immediately obvious, activate the **Debugging Protocol** skill
4. Define the fix in `task.md` (1-3 items max)
### Phase 2: Fix + Test (TDD)
**Set Mode:** Use `task_boundary` to set mode to **EXECUTION**
1. **Write a failing test** that reproduces the bug
2. **Apply the minimal fix** to make the test pass
3. **Verify existing tests** still pass
4. Follow applicable rules:
- Error Handling Principles @error-handling-principles.md
- Logging and Observability Mandate @logging-and-observability-mandate.md
### Phase 3: Verify + Ship
**Set Mode:** Use `task_boundary` to set mode to **VERIFICATION**
1. Run the full validation suite (same as `/4-verify`)
2. If all checks pass, commit with conventional format (same as `/5-commit`)
3. Use commit type `fix(<scope>): <description>`
## Completion Criteria
- [ ] Bug reproduced with a test
- [ ] Fix applied and test passes
- [ ] Full verification suite passes
- [ ] Committed with `fix` type
+76
View File
@@ -0,0 +1,76 @@
---
description: Refactor workflow for safely restructuring existing code
---
# Refactor Workflow
## Purpose
Safely restructure existing code while preserving behavior. Uses a different mindset than greenfield feature development: understand first, then change structure.
## When to Use
- Code restructuring (moving, renaming, splitting modules)
- Pattern migration (e.g., switching from callbacks to async/await)
- Dependency upgrades with breaking changes
- Addressing tech debt or architectural improvements
**Requires a specific goal.** Invoke with a clear target, not an open directory:
- ✅ `/refactor extract storage interface in task feature`
- ✅ `/refactor split user handler into separate auth handler`
- ❌ `/refactor apps/backend` (too vague — use `/audit` first to find specific issues)
## When NOT to Use
- New features (use `/orchestrator`)
- Small bug fixes (use `/quick-fix`)
- "Find what to improve" (use `/audit` first, then `/refactor` for structural findings)
## Pre-Implementation Checklist
Before starting, you MUST:
1. Scan `.agents/rules/` directory for applicable rules
2. Read `architectural-pattern.md` and `project-structure.md`
3. Read `rule-priority.md` for conflict resolution
## Phases
### Phase 1: Impact Analysis
**Set Mode:** Use `task_boundary` to set mode to **PLANNING**
1. **Map the blast radius** — what files, modules, and tests are affected?
2. **Document existing behavior** — what tests currently pass? what contracts exist?
3. **Identify risks** — can this be done incrementally or is a big-bang needed?
4. **Create refactoring plan** in `task.md` with incremental steps
5. If decision involves trade-offs, create an ADR using the **ADR Skill**
**Skills to consider:**
- **Sequential Thinking** — for multi-step refactoring with interdependencies
### Phase 2: Incremental Change (TDD)
**Set Mode:** Use `task_boundary` to set mode to **EXECUTION**
For each step in the refactoring plan:
1. **Ensure existing tests pass** before making any change
2. **Make one incremental change** — move, rename, or restructure
3. **Run tests after each change** — behavior must be preserved
4. **Add new tests** if the refactoring exposes untested behavior
5. Follow applicable rules:
- Architectural Patterns @architectural-pattern.md
- Code Organization Principles @code-organization-principles.md (includes circular dependency guidance)
**Key principle:** Never break the build for more than one step at a time.
### Phase 3: Parity Verification
**Set Mode:** Use `task_boundary` to set mode to **VERIFICATION**
1. Run the full validation suite (same as `/4-verify`)
2. **Compare test coverage** — coverage should be equal to or better than before
3. **Verify no behavior changes** — same inputs produce same outputs
4. If applicable, run E2E tests (`/e2e-test`)
### Phase 4: Ship
Follow `/5-commit` with commit type `refactor(<scope>): <description>`
## Completion Criteria
- [ ] Impact analysis documented
- [ ] All changes made incrementally with tests passing at each step
- [ ] Full verification suite passes
- [ ] Test coverage is equal to or better than before
- [ ] Committed with `refactor` type