| name | marsai:dev-cycle |
| description | Main orchestrator for the 8-gate development cycle system. Loads tasks/subtasks
from PM team output and executes through implementation → devops → SRE → unit testing → integration testing (write) → chaos testing (write) → review → validation
gates (Gates 0-7), with state persistence and metrics collection.
Gates 4-5 (integration/chaos) write and update test code per unit but only execute tests at end of cycle (deferred execution).
Multi-tenant dual-mode is implemented during Gate 0 and verified at Gate 0.5G (no separate post-cycle step).
|
| trigger | - Starting a new development cycle with a task file
- Resuming an interrupted development cycle (--resume flag)
- Need structured, gate-based task execution with quality checkpoints
|
| skip_when | - No tasks file exists or no structured subtasks to execute
- Task is documentation-only, research-only, or planning-only
- User explicitly requested manual workflow without gates
- Already inside a specific gate skill execution (avoid nesting)
- Frontend project (use marsai:dev-cycle-frontend instead)
|
| prerequisites | - Tasks file exists with structured subtasks
- Not already in a specific gate skill execution
- Human has not explicitly requested manual workflow
|
| NOT_skip_when | - "Task is simple" → Simple ≠ risk-free. Execute gates.
- "Tests already pass" → Tests ≠ review. Different concerns.
- "Time pressure" → Pressure ≠ permission. Document and proceed.
- "Already did N gates" → Sunk cost is irrelevant. Complete all gates.
|
| sequence | {"before":["marsai:dev-feedback-loop"]} |
| related | {"complementary":["marsai:dev-implementation","marsai:dev-devops","marsai:dev-sre","marsai:dev-unit-testing","marsai:requesting-code-review","marsai:dev-validation","marsai:dev-feedback-loop","marsai:dev-delivery-verification"]} |
| verification | {"automated":[{"command":"test -f docs/marsai:dev-cycle/current-cycle.json || test -f docs/marsai:dev-refactor/current-cycle.json","description":"State file exists (marsai:dev-cycle or marsai:dev-refactor)","success_pattern":"exit 0"},{"command":"cat docs/marsai:dev-cycle/current-cycle.json 2>/dev/null || cat docs/marsai:dev-refactor/current-cycle.json | jq '.current_gate'","description":"Current gate is valid","success_pattern":"[0-5]|0\\.5"}],"manual":["All gates for current task show PASS in state file","No tasks have status 'blocked' for more than 3 iterations"]} |
Development Cycle Orchestrator
Standards Loading (MANDATORY)
Before any gate execution, you MUST load MarsAI standards:
<fetch_required>
https://raw.githubusercontent.com/V4-Company/marsai/main/CLAUDE.md
</fetch_required>
Fetch URL above and extract: Agent Modification Verification requirements, Anti-Rationalization Tables requirements, and Critical Rules.
<block_condition>
- WebFetch fails or returns empty
- CLAUDE.md not accessible
</block_condition>
If any condition is true, STOP and report blocker. Cannot proceed without MarsAI standards.
Overview
The development cycle orchestrator loads tasks/subtasks from PM team output (or manual task files) and executes through 9 gates (Gate 0–7, including 0.5 Delivery Verification) with deferred execution for infrastructure-dependent tests:
- Gates 0-3, 6-7 (per unit): Write code + run tests per task/subtask
- Gates 4-5 (per unit): Write/update integration and chaos test code, verify compilation, but do not execute tests (no containers)
- Gates 4-5 (end of cycle): Execute all integration and chaos tests once after all units complete
This keeps test code current with each feature while avoiding redundant container spin-ups during development.
MUST announce at start: "I'm using the marsai:dev-cycle skill to orchestrate task execution through 9 gates (Gate 0–7, including 0.5 Delivery Verification). Gates 4-5 write tests per unit but execute at end of cycle."
⛔ CRITICAL: Specialized Agents Perform All Tasks
See shared-patterns/shared-orchestrator-principle.md for full ORCHESTRATOR principle, role separation, forbidden/required actions, gate-to-agent mapping, and anti-rationalization table.
Summary: You orchestrate. Agents execute. If using Read/Write/Edit/Bash on source code → STOP. Dispatch agent.
⛔ ORCHESTRATOR BOUNDARIES (HARD GATE)
This section defines exactly what the orchestrator CAN and CANNOT do.
What Orchestrator CAN Do (PERMITTED)
| Action | Tool | Purpose |
|---|
| Read task files | Read | Load task definitions from docs/pre-dev/*/tasks.md or docs/marsai:dev-refactor/*/tasks.md |
| Read state files | Read | Load/verify docs/marsai:dev-cycle/current-cycle.json or docs/marsai:dev-refactor/current-cycle.json |
| Read PROJECT_RULES.md | Read | Load project-specific rules |
| Write state files | Write | Persist cycle state to JSON |
| Track progress | TodoWrite | Maintain task list |
| Dispatch agents | Task | Send work to specialist agents |
| Ask user questions | AskUserQuestion | Get execution mode, approvals |
| WebFetch standards | WebFetch | Load MarsAI standards |
What Orchestrator CANNOT Do (FORBIDDEN)
- Read source code (`Read` on `*.ts`, `*.tsx`) - Agent reads code, not orchestrator
- Write source code (`Write`/`Create` on `*.ts`) - Agent writes code, not orchestrator
- Edit source code (`Edit` on `*.ts`, `*.tsx`) - Agent edits code, not orchestrator
- Run tests (`Execute` with `npm test`) - Agent runs tests in TDD cycle
- Analyze code (Direct pattern analysis) - `marsai:codebase-explorer` analyzes
- Make architectural decisions (Choosing patterns/libraries) - User decides, agent implements
Any of these actions by orchestrator = IMMEDIATE VIOLATION. Dispatch agent instead.
The 3-FILE RULE
If a task requires editing MORE than 3 files → MUST dispatch specialist agent.
This is not negotiable:
- 1-3 files of non-source content (markdown, json, yaml) → Orchestrator MAY edit directly
- 1+ source code files (
*.ts, *.tsx) → MUST dispatch agent
- 4+ files of any type → MUST dispatch agent
Orchestrator Workflow Order (MANDATORY)
┌─────────────────────────────────────────────────────────────────┐
│ CORRECT WORKFLOW ORDER │
├─────────────────────────────────────────────────────────────────┤
│ │
│ 1. Load task file (Read docs/pre-dev/*/tasks.md or docs/marsai:dev-refactor/*/tasks.md) │
│ 2. Ask execution mode (AskUserQuestion) │
│ 3. Determine state path + Check/Load state (see State Path Selection) │
│ 4. WebFetch MarsAI Standards │
│ 5. ⛔ LOAD SUB-SKILL for current gate (Skill tool) │
│ 6. Execute sub-skill instructions (dispatch agent via Task) │
│ 7. Wait for agent completion │
│ 8. Verify agent output (Standards Coverage Table) │
│ 9. Update state (Write to JSON) │
│ 10. Proceed to next gate │
│ │
│ ════════════════════════════════════════════════════════════ │
│ ❌ WRONG: Load → Mode → Standards → Task(agent) directly │
│ ✅ RIGHT: Load → Mode → Standards → Skill(sub) → Task(agent) │
│ ════════════════════════════════════════════════════════════ │
└─────────────────────────────────────────────────────────────────┘
⛔ SUB-SKILL LOADING IS MANDATORY (HARD GATE)
Before dispatching any agent, you MUST load the corresponding sub-skill first.
<cannot_skip>
- Gate 0:
Skill("marsai:dev-implementation") → then Task(subagent_type="marsai:backend-engineer-*", ...)
- Gate 0.5:
Skill("marsai:dev-delivery-verification") → Verify all requirements are DELIVERED (not just created). Catches dead code, unwired structs, unregistered middleware. Also runs 7 automated checks: (A) file size ≤300 lines, (B) license headers, (C) linting, (D) migration safety, (E) vulnerability scanning, (F) API backward compatibility, (G) multi-tenant dual-mode. FAIL → return to Gate 0 with explicit fix instructions.
- Gate 1:
Skill("marsai:dev-devops") → then Task(subagent_type="marsai:devops-engineer", ...)
- Gate 2:
Skill("marsai:dev-sre") → then Task(subagent_type="marsai:sre", ...)
- Gate 3:
Skill("marsai:dev-unit-testing") → then Task(subagent_type="marsai:qa-analyst", test_mode="unit", ...)
- Gate 4:
Skill("marsai:dev-integration-testing") → per unit: write/update tests + compile check (no execution); end of cycle: execute
- Gate 5:
Skill("marsai:dev-chaos-testing") → per unit: write/update tests + compile check (no execution); end of cycle: execute
- Gate 6:
Skill("marsai:requesting-code-review") → then 5x Task(...) in parallel
- Gate 7:
Skill("marsai:dev-validation") → N/A (verification only)
</cannot_skip>
Between "WebFetch standards" and "Task(agent)" there MUST be "Skill(sub-skill)".
The workflow for each gate is:
1. Skill("[sub-skill-name]") ← Load sub-skill instructions
2. Follow sub-skill instructions ← Sub-skill tells you HOW to dispatch
3. Task(subagent_type=...) ← Dispatch agent as sub-skill instructs
4. Validate agent output ← Per sub-skill validation rules
5. Update state ← Record results
Custom Instructions (Optional Second Argument)
Validation: See shared-patterns/custom-prompt-validation.md for max length (500 chars), sanitization rules, gate protection, and conflict handling.
If custom_prompt is set in state, inject it into ALL agent dispatches:
Task tool:
subagent_type: "marsai:backend-engineer-typescript"
prompt: |
**CUSTOM CONTEXT (from user):**
{state.custom_prompt}
---
**Standard Instructions:**
[... rest of agent prompt ...]
Rules for custom prompt:
- Inject at TOP of prompt - User context takes precedence
- Preserve in state - custom_prompt persists for resume
- Include in execution report - Document what context was used
- Forward via state - Sub-skills read
custom_prompt from state file and inject into their agent dispatches (no explicit parameter passing needed)
Example custom prompts and their effect:
| Custom Prompt | Effect on Agents |
|---|
| "Focus on error handling first" | Agents prioritize error-related acceptance criteria |
| "Use existing UserRepository interface" | Agents integrate with specified interface instead of creating new |
| "Deprioritize UI polish" | Gate 3 still enforces 85% coverage, but agents deprioritize non-functional UI tweaks |
| "Prioritize observability gaps" | SRE gate gets more attention, implementation focuses on instrumentation |
Anti-Rationalization for Skipping Sub-Skills
| Rationalization | Why It's WRONG | Required Action |
|---|
| "I know what the sub-skill does" | Knowledge ≠ execution. Sub-skill has iteration logic. | Load Skill() first |
| "Task() directly is faster" | Faster ≠ correct. Sub-skill has validation rules. | Load Skill() first |
| "Sub-skill just wraps Task()" | Sub-skills have retry logic, fix dispatch, validation. | Load Skill() first |
| "I'll follow the pattern manually" | Manual = error-prone. Sub-skill is the pattern. | Load Skill() first |
Between "WebFetch standards" and "Task(agent)" there MUST be "Skill(sub-skill)".
Anti-Rationalization for Direct Coding
| Rationalization | Why It's WRONG | Required Action |
|---|
| "It's just one small file" | File count doesn't determine agent need. Language does. | DISPATCH specialist agent |
| "I already loaded the standards" | Loading standards ≠ permission to implement. Standards are for AGENTS. | DISPATCH specialist agent |
| "Agent dispatch adds overhead" | Overhead ensures compliance. Skip = skip verification. | DISPATCH specialist agent |
| "I can write TypeScript" | Knowing language ≠ having MarsAI standards loaded. Agent has them. | DISPATCH specialist agent |
| "Just a quick fix" | "Quick" is irrelevant. all source changes require specialist. | DISPATCH specialist agent |
| "I'll read the file first to understand" | Reading source → temptation to edit. Agent reads for you. | DISPATCH specialist agent |
| "Let me check if tests pass first" | Agent runs tests in TDD cycle. You don't run tests. | DISPATCH specialist agent |
Red Flags - Orchestrator Violation in Progress
If you catch yourself doing any of these, STOP IMMEDIATELY:
🚨 RED FLAG: About to Read *.ts file
→ STOP. Dispatch agent instead.
🚨 RED FLAG: About to Write/Create source code
→ STOP. Dispatch agent instead.
🚨 RED FLAG: About to Edit source code
→ STOP. Dispatch agent instead.
🚨 RED FLAG: About to run "npm test"
→ STOP. Agent runs tests, not you.
🚨 RED FLAG: Thinking "I'll just..."
→ STOP. "Just" is the warning word. Dispatch agent.
🚨 RED FLAG: Thinking "This is simple enough..."
→ STOP. Simplicity is irrelevant. Dispatch agent.
🚨 RED FLAG: Standards loaded, but next action is not Task tool
→ STOP. After standards, IMMEDIATELY dispatch agent.
Recovery from Orchestrator Violation
If you violated orchestrator boundaries:
- STOP current execution immediately
- DISCARD any direct changes (
git checkout -- .)
- DISPATCH the correct specialist agent
- Agent implements from scratch following TDD
- Document the violation for feedback loop
Sunk cost of direct work is IRRELEVANT. Agent dispatch is MANDATORY.
Blocker Criteria - STOP and Report
<block_condition>
- Gate Failure: Tests not passing, review failed → STOP, cannot proceed to next gate
- Missing Standards: No PROJECT_RULES.md → STOP, report blocker and wait
- Agent Failure: Specialist agent returned errors → STOP, diagnose and report
- User Decision Required: Architecture choice, framework selection → STOP, present options
</block_condition>
You CANNOT proceed when blocked. Report and wait for resolution.
Cannot Be Overridden
<cannot_skip>
- All 9 gates must execute (0→0.5→1→2→3→4→5→6→7) - Each gate catches different issues
- All testing gates (3-5) are MANDATORY - Comprehensive test coverage ensures quality
- Gates execute in order (0→0.5→1→2→3→4→5→6→7) - Dependencies exist between gates
- Gate 6 requires all 7 reviewers - Different review perspectives are complementary
- Coverage threshold ≥ 85% - Industry standard for quality code
- PROJECT_RULES.md must exist - Cannot verify standards without target
</cannot_skip>
No exceptions. User cannot override. Time pressure cannot override.
Severity Calibration
| Severity | Criteria | Examples |
|---|
| CRITICAL | Blocks deployment, security risk, data loss | Gate violation, skipped mandatory step |
| HIGH | Major functionality broken, standards violation | Missing tests, wrong agent dispatched |
| MEDIUM | Code quality, maintainability issues | Incomplete documentation, minor gaps |
| LOW | Best practices, optimization | Style improvements, minor refactoring |
Report all severities. Let user prioritize.
Reviewer Verdicts Are Final
MEDIUM issues found in Gate 6 MUST be fixed. No exceptions.
| Request | Why It's WRONG | Required Action |
|---|
| "Can reviewer clarify if MEDIUM can defer?" | Reviewer already decided. MEDIUM means FIX. | Fix the issue, re-run reviewers |
| "Ask if this specific case is different" | Reviewer verdict accounts for context already. | Fix the issue, re-run reviewers |
| "Request exception for business reasons" | Reviewers know business context. Verdict is final. | Fix the issue, re-run reviewers |
Severity mapping is absolute:
- CRITICAL/HIGH/MEDIUM → Fix NOW, re-run all 7 reviewers
- LOW → Add TODO(review): comment
- Cosmetic → Add FIXME(nitpick): comment
No negotiation. No exceptions. No "special cases".
Pressure Resistance
See shared-patterns/shared-pressure-resistance.md for universal pressure scenarios.
Gate-specific note: Execution mode selection affects CHECKPOINTS (user approval pauses), not GATES (quality checks). all gates execute regardless of mode.
Common Rationalizations - REJECTED
See shared-patterns/shared-anti-rationalization.md for universal anti-rationalizations.
Gate-specific rationalizations:
| Excuse | Reality |
|---|
| "Automatic mode means faster" | Automatic mode skips CHECKPOINTS, not GATES. Same quality, less interruption. |
| "Automatic mode will skip review" | Automatic mode affects user approval pauses, not quality gates. all gates execute regardless. |
| "Defense in depth exists (frontend validates)" | Frontend can be bypassed. Backend is the last line. Fix at source. |
| "Backlog the Medium issue, it's documented" | Documented risk ≠ mitigated risk. Medium in Gate 4 = fix NOW, not later. |
| "Risk-based prioritization allows deferral" | Gates ARE the risk-based system. Reviewers define severity, not you. |
Red Flags - STOP
See shared-patterns/shared-red-flags.md for universal red flags.
If you catch yourself thinking any of those patterns, STOP immediately and return to gate execution.
Incremental Compromise Prevention
The "just this once" pattern leads to complete gate erosion:
Day 1: "Skip review just this once" → Approved (precedent set)
Day 2: "Skip testing, we did it last time" → Approved (precedent extended)
Day 3: "Skip implementation checks, pattern established" → Approved (gates meaningless)
Day 4: Production incident from Day 1 code
Prevention rules:
- No incremental exceptions - Each exception becomes the new baseline
- Document every pressure - Log who requested, why, outcome
- Escalate patterns - If same pressure repeats, escalate to team lead
- Gates are binary - Complete or incomplete. No "mostly done".
Gate Completion Definition (HARD GATE)
A gate is COMPLETE only when all components finish successfully:
| Gate | Components Required | Partial = FAIL |
|---|
| 0.1 | TDD-RED: Failing test written + failure output captured | Test exists but no failure output = FAIL |
| 0.2 | TDD-GREEN: Implementation passes test | Code exists but test fails = FAIL |
| 0 | Both 0.1 and 0.2 complete | 0.1 done without 0.2 = FAIL |
| 1 | Dockerfile + docker-compose + .env.example | Missing any = FAIL |
| 2 | Structured JSON logs with trace correlation | Partial structured logs = FAIL |
| 3 | Unit test coverage ≥ 85% + all AC tested | 84% = FAIL |
| 4 | Integration tests with testcontainers | No testcontainers = FAIL |
| 5 | Chaos tests for failure scenarios | Missing chaos tests = FAIL |
| 6 | All 7 reviewers PASS | 6/7 reviewers = FAIL |
| 7 | Explicit "APPROVED" from user | "Looks good" = not approved |
CRITICAL for Gate 6: Running 6 of 7 reviewers is not a partial pass - it's a FAIL. Re-run all 7 reviewers.
Anti-Rationalization for Partial Gates:
| Rationalization | Why It's WRONG | Required Action |
|---|
| "6 of 7 reviewers passed" | Gate 6 requires all 7. 6/7 = 0/7. | Re-run all 7 reviewers |
| "Gate mostly complete" | Mostly ≠ complete. Binary: done or not done. | Complete all components |
| "Can finish remaining in next cycle" | Gates don't carry over. Complete NOW. | Finish current gate |
| "Core components done, optional can wait" | No component is optional within a gate. | Complete all components |
| "No external dependencies, skip integration" | Integration testing is MANDATORY. Write tests per unit, execute at end of cycle. | Write Gate 4 tests per unit, execute at end |
Gate Order Enforcement (HARD GATE)
Gates MUST execute in order: 0 → 0.5 → 1 → 2 → 3 → 4(write) → 5(write) → 6 → 7. All 9 gates are MANDATORY.
Deferred Execution Model for Gates 4-5:
- Per unit: Write/update test code + verify compilation (no container execution)
- End of cycle: Execute all integration and chaos tests (containers spun up once), then verify multi-tenant dual-mode compliance (already implemented at Gate 0, verified at Gate 0.5G)
| Violation | Why It's WRONG | Consequence |
|---|
| Skip Gate 1 (DevOps) | "No infra changes" | Code without container = works on my machine only |
| Skip Gate 2 (SRE) | "Observability later" | Blind production = debugging nightmare |
| Skip Gate 4 (Integration) | "No external dependencies" | Internal integration bugs surface in production. Note: Gate 4 may SKIP if project lacks integration testing infrastructure — see marsai:dev-integration-testing Step 0.5 |
| Skip Gate 5 (Chaos) | "Infra is reliable" | System fails under real-world conditions. Note: Gate 5 may SKIP if project lacks chaos testing infrastructure — see marsai:dev-chaos-testing Step 0.5 |
| Reorder Gates | "Review before test" | Reviewing untested code wastes reviewer time |
| Parallel Gates | "Run 3 and 4 together" | Dependencies exist. Order is intentional. |
All testing gates (3-5) are MANDATORY. No exceptions. No skip reasons. Exception: Gates 4-5 perform an infrastructure assessment (Step 0.5) — if the project has no existing integration/chaos testing infrastructure, the gate SKIPs for non-critical tasks or runs in ephemeral mode for critical tasks (auth flows, payments). See each gate's SKILL.md for details.
Gates are not parallelizable across different gates. Sequential execution is MANDATORY.
The 8 Gates
| Gate | Skill | Purpose | Agent | Per Unit | Standards Module |
|---|
| 0 | marsai:dev-implementation | Write code following TDD (single-tenant) | Based on task language/domain | Write + Run | core.md, domain.md |
| 1 | marsai:dev-devops | Infrastructure and deployment | marsai:devops-engineer | Write + Run | devops.md |
| 2 | marsai:dev-sre | Observability (health, logging, tracing) | marsai:sre | Write + Run | sre.md |
| 3 | marsai:dev-unit-testing | Unit tests for acceptance criteria | marsai:qa-analyst (test_mode: unit) | Write + Run | testing-unit.md |
| 4 | marsai:dev-integration-testing | Integration tests with testcontainers | marsai:qa-analyst (test_mode: integration) | Write only | testing-integration.md |
| 5 | marsai:dev-chaos-testing | Chaos tests for failure scenarios | marsai:qa-analyst (test_mode: chaos) | Write only | testing-chaos.md |
| 6 | marsai:requesting-code-review | Parallel code review (7 reviewers) | marsai:code-reviewer, marsai:business-logic-reviewer, marsai:security-reviewer, marsai:nil-safety-reviewer, marsai:test-reviewer, marsai:consequences-reviewer, marsai:dead-code-reviewer | Run | N/A |
| 7 | marsai:dev-validation | Final acceptance validation | N/A (verification) | Run | N/A |
All gates are MANDATORY. No exceptions. No skip reasons. Gates 4-5 have an infrastructure-awareness carveout — see Step 0.5 in each gate's skill for skip/ephemeral logic.
Gates 4-5 Deferred Execution: When infrastructure exists, test code is written/updated per unit to stay current. Actual test execution (with containers) happens once at end of cycle. When infrastructure does NOT exist, gates skip or run ephemerally (see Step 0.5).
Integrated PM → Dev Workflow
PM Team Output → Dev Team Execution (/marsai:dev-cycle)
| Input Type | Path | Structure |
|---|
| Tasks only | docs/pre-dev/{feature}/tasks.md | T-001, T-002, T-003 with requirements + acceptance criteria |
| Tasks + Subtasks | docs/pre-dev/{feature}/ | tasks.md + subtasks/{task-id}/ST-XXX-01.md, ST-XXX-02.md... |
Execution Order
Core Principle: Each execution unit passes through all 9 gates. Gates 4-5 write test code per unit but defer execution to end of cycle.
Per-Unit Flow: Unit → Gate 0→0.5(delivery verify)→1→2→3→4(write)→5(write)→6→7 → 🔒 Unit Checkpoint → 🔒 Task Checkpoint → Next Unit
End-of-Cycle Flow: All units done → Gate 4(execute)→5(execute) → Multi-Tenant Verification → Final Commit → Feedback
| Scenario | Execution Unit | Gates Per Unit | End of Cycle |
|---|
| Task without subtasks | Task itself | 9 gates (4-5 write only) | Gate 4-5 execute |
| Task with subtasks | Each subtask | 9 gates per subtask (4-5 write only) | Gate 4-5 execute |
Why deferred execution for Gates 4-5:
- Integration tests require testcontainers (slow to spin up/tear down)
- Chaos tests require Toxiproxy infrastructure
- Running containers per subtask is wasteful when subsequent subtasks modify the same code
- Test code stays current (written per unit), infrastructure cost is paid once
Commit Timing
User selects when commits happen (Step 7 of initialization).
| Option | When Commit Happens | Use Case |
|---|
| (a) Per subtask | After each subtask passes Gate 7 | Fine-grained history, easy rollback per subtask |
| (b) Per task | After all subtasks of a task complete | Logical grouping, one commit per feature chunk |
| (c) At the end | After entire cycle completes | Single commit with all changes, clean history |
Commit Message Format
| Timing | Message Format | Example |
|---|
| Per subtask | feat({subtask_id}): {subtask_title} | feat(ST-001-02): implement user authentication handler |
| Per task | feat({task_id}): {task_title} | feat(T-001): implement user authentication |
| At the end | feat({cycle_id}): complete dev cycle for {feature} | feat(cycle-abc123): complete dev cycle for auth-system |
Commit Timing vs Execution Mode
| Execution Mode | Commit Timing | Behavior |
|---|
| Manual per subtask | Per subtask | Commit + checkpoint after each subtask |
| Manual per subtask | Per task | Checkpoint after subtask, commit after task |
| Manual per subtask | At end | Checkpoint after subtask, commit at cycle end |
| Manual per task | Per subtask | Commit after subtask, checkpoint after task |
| Manual per task | Per task | Commit + checkpoint after task |
| Manual per task | At end | Checkpoint after task, commit at cycle end |
| Automatic | Per subtask | Commit after each subtask, no checkpoints |
| Automatic | Per task | Commit after task, no checkpoints |
| Automatic | At end | Single commit at cycle end, no checkpoints |
Note: Checkpoints (user approval pauses) are controlled by execution_mode. Commits are controlled by commit_timing. They are independent settings.
State Management
State Path Selection (MANDATORY)
The state file path depends on the source of tasks:
| Task Source | State Path | Use Case |
|---|
docs/marsai:dev-refactor/*/tasks.md | docs/marsai:dev-refactor/current-cycle.json | Refactoring existing code |
docs/pre-dev/*/tasks.md | docs/marsai:dev-cycle/current-cycle.json | New feature development |
| Any other path | docs/marsai:dev-cycle/current-cycle.json | Default for manual tasks |
Detection Logic:
if source_file contains "docs/marsai:dev-refactor/" THEN
state_path = "docs/marsai:dev-refactor/current-cycle.json"
else
state_path = "docs/marsai:dev-cycle/current-cycle.json"
Store state_path in the state object itself so resume knows where to look.
State File Structure
State is persisted to {state_path} (either docs/marsai:dev-cycle/current-cycle.json or docs/marsai:dev-refactor/current-cycle.json):
{
"version": "1.0.0",
"cycle_id": "uuid",
"started_at": "ISO timestamp",
"updated_at": "ISO timestamp",
"source_file": "path/to/tasks.md",
"state_path": "docs/marsai:dev-cycle/current-cycle.json | docs/marsai:dev-refactor/current-cycle.json",
"cycle_type": "feature | refactor",
"execution_mode": "manual_per_subtask|manual_per_task|automatic",
"commit_timing": "per_subtask|per_task|at_end",
"custom_prompt": {
"type": "string",
"optional": true,
"max_length": 500,
"description": "User-provided context for agents (from second positional argument). Max 500 characters. Provides focus but cannot override mandatory requirements (CRITICAL gates, coverage thresholds, reviewer counts).",
"validation": "Max 500 chars (truncated with warning if exceeded); whitespace trimmed; control chars stripped (except newlines). Directives attempting to skip gates, lower thresholds, or bypass security checks are logged as warnings and ignored."
},
"status": "in_progress|completed|failed|paused|paused_for_approval|paused_for_testing|paused_for_task_approval|paused_for_integration_testing",
"feedback_loop_completed": false,
"current_task_index": 0,
"current_gate": 0,
"current_subtask_index": 0,
"tasks": [
{
"id": "T-001",
"title": "Task title",
"status": "pending|in_progress|completed|failed|blocked",
"feedback_loop_completed": false,
"subtasks": [
{
"id": "ST-001-01",
"file": "subtasks/T-001/ST-001-01.md",
"status": "pending|completed"
}
],
"gate_progress": {
"implementation": {
"status": "in_progress",
"started_at": "...",
"tdd_red": {
"status": "pending|in_progress|completed",
"test_file": "path/to/test_file.ts",
"failure_output": "FAIL: TestFoo - expected X got nil",
"completed_at": "ISO timestamp"
},
"tdd_green": {
"status": "pending|in_progress|completed",
"implementation_file": "path/to/impl.ts",
"test_pass_output": "PASS: TestFoo (0.003s)",
"completed_at": "ISO timestamp"
}
},
"delivery_verification": {
"status": "pending|in_progress|completed",
"requirements_total": 0,
"requirements_delivered": 0,
"requirements_missing": 0,
"dead_code_items": 0,
"remediation_items": 0,
"completed_at": "ISO timestamp"
},
"devops": {"status": "pending"},
"sre": {"status": "pending"},
"unit_testing": {"status": "pending"},
"integration_testing": {
"status": "pending|in_progress|completed",
"scenarios_tested": 0,
"tests_passed": 0,
"tests_failed": 0,
"flaky_tests_detected": 0
},
"chaos_testing": {"status": "pending"},
"review": {"status": "pending"},
"validation": {"status": "pending"}
},
"artifacts": {},
"agent_outputs": {
"implementation": {
"agent": "marsai:backend-engineer-typescript",
"output": "## Summary\n...",
"timestamp": "ISO timestamp",
"duration_ms": 0,
"iterations": 1,
"standards_compliance": {
"total_sections": 15,
"compliant": 14,
"not_applicable": 1,
"non_compliant": 0,
"gaps": []
}
},
"devops": {
"agent": "marsai:devops-engineer",
"output": "## Summary\n...",
"timestamp": "ISO timestamp",
"duration_ms": 0,
"iterations": 1,
"artifacts_created": ["Dockerfile", "docker-compose.yml", ".env.example"],
"verification_errors": [],
"standards_compliance": {
"total_sections": 8,
"compliant": 8,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"sre": {
"agent": "marsai:sre",
"output": "## Summary\n...",
"timestamp": "ISO timestamp",
"duration_ms": 0,
"iterations": 1,
"instrumentation_coverage": "92%",
"validation_errors": [],
"standards_compliance": {
"total_sections": 10,
"compliant": 10,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"unit_testing": {
"agent": "marsai:qa-analyst",
"test_mode": "unit",
"output": "## Summary\n...",
"verdict": "PASS",
"coverage_actual": 87.5,
"coverage_threshold": 85,
"iterations": 1,
"timestamp": "ISO timestamp",
"duration_ms": 0,
"failures": [],
"uncovered_criteria": [],
"standards_compliance": {
"total_sections": 6,
"compliant": 6,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"integration_testing": {
"agent": "marsai:qa-analyst",
"test_mode": "integration",
"output": "## Summary\n...",
"verdict": "PASS",
"scenarios_tested": 5,
"tests_passed": 5,
"tests_failed": 0,
"flaky_tests_detected": 0,
"iterations": 1,
"timestamp": "ISO timestamp",
"duration_ms": 0,
"standards_compliance": {
"total_sections": 10,
"compliant": 10,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"chaos_testing": {
"agent": "marsai:qa-analyst",
"test_mode": "chaos",
"output": "## Summary\n...",
"verdict": "PASS",
"failure_scenarios_tested": 4,
"recovery_verified": true,
"iterations": 1,
"timestamp": "ISO timestamp",
"duration_ms": 0,
"standards_compliance": {
"total_sections": 5,
"compliant": 5,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"review": {
"iterations": 1,
"timestamp": "ISO timestamp",
"duration_ms": 0,
"code_reviewer": {
"agent": "marsai:code-reviewer",
"output": "...",
"verdict": "PASS",
"timestamp": "...",
"issues": [],
"standards_compliance": {
"total_sections": 12,
"compliant": 12,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"business_logic_reviewer": {
"agent": "marsai:business-logic-reviewer",
"output": "...",
"verdict": "PASS",
"timestamp": "...",
"issues": [],
"standards_compliance": {
"total_sections": 8,
"compliant": 8,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
},
"security_reviewer": {
"agent": "marsai:security-reviewer",
"output": "...",
"verdict": "PASS",
"timestamp": "...",
"issues": [],
"standards_compliance": {
"total_sections": 10,
"compliant": 10,
"not_applicable": 0,
"non_compliant": 0,
"gaps": []
}
}
},
"validation": {
"result": "approved|rejected",
"timestamp": "ISO timestamp"
}
}
}
],
"metrics": {
"total_duration_ms": 0,
"gate_durations": {},
"review_iterations": 0,
"testing_iterations": 0
}
}
Structured Error/Issue Schemas
These schemas enable marsai:dev-feedback-loop to analyze issues without parsing raw output.
Standards Compliance Gap Schema
{
"section": "Error Handling (MANDATORY)",
"status": "❌",
"reason": "Missing error wrapping with context",
"file": "internal/handler/user.ts",
"line": 45,
"evidence": "return err // should wrap with additional context"
}
Test Failure Schema
{
"test_name": "TestUserCreate_InvalidEmail",
"test_file": "internal/handler/user.test.ts",
"error_type": "assertion",
"expected": "ErrInvalidEmail",
"actual": "nil",
"message": "Expected validation error for invalid email format",
"stack_trace": "user.test.ts:42 → user.ts:28"
}
Review Issue Schema
{
"severity": "MEDIUM",
"category": "error-handling",
"description": "Error not wrapped with context before returning",
"file": "internal/handler/user.ts",
"line": 45,
"suggestion": "Use fmt.Errorf(\"failed to create user: %w\", err)",
"fixed": false,
"fixed_in_iteration": null
}
DevOps Verification Error Schema
{
"check": "docker_build",
"status": "FAIL",
"error": "COPY failed: file not found in build context: package-lock.json",
"suggestion": "Ensure package-lock.json exists and is not in .dockerignore"
}
SRE Validation Error Schema
{
"check": "structured_logging",
"status": "FAIL",
"file": "internal/handler/user.ts",
"line": 32,
"error": "Using fmt.Printf instead of structured logger",
"suggestion": "Use logger.Info().Str(\"user_id\", id).Msg(\"user created\")"
}
Populating Structured Data
Each gate MUST populate its structured fields when saving to state:
| Gate | Fields to Populate |
|---|
| Gate 0 (Implementation) | standards_compliance (total, compliant, gaps[]) |
| Gate 1 (DevOps) | standards_compliance + verification_errors[] |
| Gate 2 (SRE) | standards_compliance + validation_errors[] |
| Gate 3 (Unit Testing) | standards_compliance + failures[] + uncovered_criteria[] |
| Gate 4 (Integration Testing) | standards_compliance + scenarios_tested + tests_passed + tests_failed + flaky_tests_detected |
| Gate 5 (Chaos Testing) | standards_compliance + failure_scenarios_tested + recovery_verified |
| Gate 6 (Review) | standards_compliance per reviewer + issues[] per reviewer |
All gates track standards_compliance:
total_sections: Count from agent's standards file (via standards-coverage-table.md)
compliant: Sections marked ✅ in Standards Coverage Table
not_applicable: Sections marked N/A
non_compliant: Sections marked ❌ (MUST be 0 to pass gate)
gaps[]: Detailed info for each ❌ section (even if later fixed)
Empty arrays [] indicate no issues found - this is valid data for feedback-loop.
⛔ State Persistence Rule (MANDATORY)
"Update state" means BOTH update the object and write to file. Not just in-memory.
After every Gate Transition
You MUST execute these steps after completing any gate (0, 1, 2, 3, 4, 5, 6, or 7):
state.tasks[current_task_index].gate_progress.[gate_name].status = "completed"
state.tasks[current_task_index].gate_progress.[gate_name].completed_at = "[ISO timestamp]"
state.current_gate = [next_gate_number]
state.updated_at = "[ISO timestamp]"
Write tool:
file_path: [state.state_path]
content: [full JSON state]
Read tool:
file_path: [state.state_path]
State Persistence Checkpoints
| Checkpoint | MUST Update | MUST Write File |
|---|
| Before Gate 0 (task start) | task.status = "in_progress" in JSON + tasks.md Status → 🔄 Doing | ✅ YES |
| Gate 0.1 (TDD-RED) | tdd_red.status, tdd_red.failure_output | ✅ YES |
| Gate 0.2 (TDD-GREEN) | tdd_green.status, implementation.status | ✅ YES |
| Gate 0.5 (Delivery Verification) | delivery_verification.status, delivery_verification.requirements_total, delivery_verification.requirements_delivered, delivery_verification.dead_code_items | ✅ YES |
| Gate 1 (DevOps) | devops.status, agent_outputs.devops | ✅ YES |
| Gate 2 (SRE) | sre.status, agent_outputs.sre | ✅ YES |
| Gate 3 (Unit Testing) | unit_testing.status, agent_outputs.unit_testing | ✅ YES |
| Gate 4 (Integration Testing) | integration_testing.status, agent_outputs.integration_testing | ✅ YES |
| Gate 5 (Chaos Testing) | chaos_testing.status, agent_outputs.chaos_testing | ✅ YES |
| Gate 6 (Review) | review.status, agent_outputs.review | ✅ YES |
| Gate 7 (Validation) | validation.status (execution unit only — do NOT touch task-level status here) | ✅ YES |
| Step 9.1 (Unit Approval) | status = "paused_for_approval" | ✅ YES |
| Step 9.2 (Task Approval) | task.status = "completed" in JSON + tasks.md Status → ✅ Done | ✅ YES |
| HARD BLOCK (any gate) | task.status = "failed" in JSON + tasks.md Status → ❌ Failed | ✅ YES |
tasks.md Status update rules (apply at the three checkpoints above):
If state.source_file is absent or file does not exist → log warning "tasks.md Status updates skipped: source_file missing" and skip all status updates for this cycle.
task_id = state.tasks[state.current_task_index].id
# Always the parent TASK ID — do NOT use current_subtask_index
# Rows where column 1 is "TOTAL" or empty → skip, not a task row
Use Edit tool on state.source_file (tasks.md):
- Find the row starting with `| {task_id} |` in the `## Summary` table
- Before Gate 0: replace `⏸️ Pending` with `🔄 Doing`
- If already `🔄 Doing` (resumed cycle) → skip, no change needed
- Step 9.2 (all subtasks done, user approved): replace `🔄 Doing` with `✅ Done`
- HARD BLOCK (any gate, task abandoned): replace `🔄 Doing` with `❌ Failed`
- If row shows `⏸️ Pending` (unexpected) → replace with target value anyway
- If row not found or no Status column → log warning "Status update skipped: task {task_id} row not found in {source_file}" and continue, do not abort
Anti-Rationalization for State Persistence
| Rationalization | Why It's WRONG | Required Action |
|---|
| "I'll save state at the end" | Crash/timeout loses all progress | Save after each gate |
| "State is in memory, that's updated" | Memory is volatile. File is persistent. | Write to JSON file |
| "Only save on checkpoints" | Gates without saves = unrecoverable on resume | Save after every gate |
| "Write tool is slow" | Write takes <100ms. Lost progress takes hours. | Write after every gate |
| "I updated the state variable" | Variable ≠ file. Without Write tool, nothing persists. | Use Write tool explicitly |
Verification Command
After each gate, the state file MUST reflect:
current_gate = next gate number
updated_at = recent timestamp
- Previous gate
status = "completed"
If verification fails → State was not persisted. Re-execute Write tool.
Step 0: Verify PROJECT_RULES.md Exists (HARD GATE)
NON-NEGOTIABLE. Cycle CANNOT proceed without project standards.
Step 0 Flow
┌─────────────────────────────────────────────────────────────────────────────┐
│ Check: Does docs/PROJECT_RULES.md exist? │
│ │
│ ├── YES → Proceed to Step 1 (Initialize or Resume) │
│ │ │
│ └── no → ASK: "How would you like to set up project context?" │
│ │ │
│ ├── (a) I have PM docs (PRD/TRD/Feature Map from pre-dev workflow) │
│ │ → ASK: "Please provide the file path(s)" │
│ │ → Read PRD/TRD/Feature Map → Extract info │
│ │ → Generate PROJECT_RULES.md │
│ │ → Ask supplementary questions if info is incomplete │
│ │ → Save and proceed to Step 1 │
│ │ │
│ ├── (b) Generate from code analysis (analyze existing codebase) │
│ │ Step 1: Dispatch marsai:codebase-explorer (technical info only) │
│ │ Step 2: Ask 3 questions (what agent can't determine): │
│ │ 1. What do you need help with? │
│ │ 2. Any external APIs not visible in code? │
│ │ 3. Any specific technology not in MarsAI Standards? │
│ │ Step 3: Generate PROJECT_RULES.md (deduplicated from MarsAI) │
│ │ Note: Business rules belong in PRD, not in PROJECT_RULES │
│ │ → Proceed to Step 1 │
│ │ │
│ └── (c) I don't have either → ⛔ HARD BLOCK: │
│ "Run /marsai:pre-dev-full or /marsai:pre-dev-feature first │
│ to create PM docs, or choose code analysis if you have │
│ an existing codebase." │
│ → STOP (cycle cannot proceed) │
└─────────────────────────────────────────────────────────────────────────────┘
Step 0.1: Check for PROJECT_RULES.md
Read tool:
file_path: "docs/PROJECT_RULES.md"
Step 0.2: Choose Project Context Source
Ask the User
Use AskUserQuestion:
┌─────────────────────────────────────────────────────────────────┐
│ 📋 PROJECT_RULES.md not FOUND │
├─────────────────────────────────────────────────────────────────┤
│ │
│ I need to create docs/PROJECT_RULES.md to understand your │
│ project's specific conventions and domain. │
│ │
│ How would you like to set up project context? │
│ │
│ (a) I have PM docs — PRD, TRD, or Feature Map created with │
│ /marsai:pre-dev-full or /marsai:pre-dev-feature │
│ │
│ (b) Generate from code analysis — I have an existing codebase │
│ and want to create PROJECT_RULES.md by analyzing it │
│ │
└─────────────────────────────────────────────────────────────────┘
Question
"How would you like to set up project context?"
Options
(a) I have PM docs (PRD/TRD/Feature Map from pre-dev workflow) (b) Generate from code analysis (analyze existing codebase)
If (a) — Has PM docs
Go to Step 0.3 (Check for PM Documents)
If (b) — Code analysis
Go to Step 0.2.1 (Code Analysis for PROJECT_RULES.md)
Step 0.2.1: Code Analysis for PROJECT_RULES.md (Technical Only)
Overview
For projects without PM docs, analyze codebase for TECHNICAL information only:
┌─────────────────────────────────────────────────────────────────┐
│ 📋 CODE ANALYSIS FOR PROJECT CONTEXT │
├─────────────────────────────────────────────────────────────────┤
│ │
│ I'll analyze the existing codebase to understand your project │
│ for TECHNICAL information (not business rules). │
│ │
│ Step 1: Automated analysis (marsai:codebase-explorer) │
│ Step 2: Ask for project-specific tech not in MarsAI Standards │
│ Step 3: Generate PROJECT_RULES.md (deduplicated) │
│ │
│ Note: Business rules belong in PRD/product docs, not here. │
│ │
└─────────────────────────────────────────────────────────────────┘
Step 0.2.1a: Automated Codebase Analysis (MANDATORY)
⛔ You MUST use the Task tool to dispatch marsai:codebase-explorer. This is not implicit.
Dispatch Agent
Dispatch marsai:codebase-explorer to analyze the existing codebase for TECHNICAL information:
Action: Use Task tool with EXACTLY these parameters:
┌─────────────────────────────────────────────────────────────────────────────────┐
│ ⛔ If Task tool not used → Analysis does not happen → PROJECT_RULES.md INVALID │
└─────────────────────────────────────────────────────────────────────────────────┘
Task tool:
subagent_type: "marsai:codebase-explorer"
description: "Analyze existing codebase for PROJECT_RULES.md"
prompt: |
Analyze this codebase to extract technical information for PROJECT_RULES.md.
This is an existing project. Your job is to understand what exists in the code.
**Extract:**
1. **Project Structure:** Directory layout, module organization
2. **Technical Stack:** Languages, frameworks, databases, external services
3. **Architecture Patterns:** Clean Architecture, MVC, microservices, etc.
4. **Existing Features:** Main modules, endpoints, capabilities
5. **Internal Libraries:** Shared packages, utilities
6. **Configuration:** Environment variables, config patterns
7. **Database:** Schema patterns, migrations, ORM usage
8. **External Integrations:** APIs consumed, message queues
**Output format:**
[What this project appears to do based on code analysis]
- Language: [detected]
- Framework: [detected]
- Database: [detected]
- External Services: [detected]
[Detected patterns]
[List of features/modules found]
[Directory layout explanation]
[Env vars, config files found]
[APIs, services detected]
Note: Business logic analysis is not needed for PROJECT_RULES.md. Business rules belong in PRD/product docs, not technical project rules.
Verification (MANDATORY)
After agent completes, confirm:
If agent failed or returned empty output → Re-dispatch. Cannot proceed without technical analysis.
Step 0.2.1b: Supplementary Questions (Only What Agents Can't Determine)
Post-Analysis Questions
After agents complete, ask only what they couldn't determine from code:
┌─────────────────────────────────────────────────────────────────┐
│ ✓ Codebase Analysis Complete │
├─────────────────────────────────────────────────────────────────┤
│ │
│ I've analyzed your codebase. Now I need a few details that │
│ only you can provide (not visible in the code). │
│ │
└─────────────────────────────────────────────────────────────────┘
Questions to Ask
Use AskUserQuestion for each:
| # | Question | Why Agents Can't Determine This |
|---|
| 1 | What do you need help with? (Current task/feature/fix) | Future intent, not in code |
| 2 | Any external APIs or services not visible in code? (Third-party integrations planned) | Planned integrations, not yet in code |
| 3 | Any specific technology not in MarsAI Standards? (Message broker, cache, etc.) | Project-specific tech not in MarsAI |
Note: Business rules belong in PRD/product docs, not in PROJECT_RULES.md.
Step 0.2.1c: Generate PROJECT_RULES.md
Combine Agent Outputs and User Answers
Create tool:
file_path: "docs/PROJECT_RULES.md"
content: |
# Project Rules
> MarsAI Standards apply automatically. This file documents only what MarsAI does not cover.
> For error handling, logging, testing, architecture → See MarsAI Standards (auto-loaded by agents)
> Generated from codebase analysis.
The following are defined in MarsAI Standards and MUST not be duplicated:
- Error handling patterns (no panic, wrap errors)
- Logging standards (structured JSON, zerolog/zap)
- Testing patterns (table-driven tests, mocks)
- Architecture patterns (Hexagonal, Clean Architecture)
- Observability (OpenTelemetry, trace correlation)
- API directory structure
---
[From marsai:codebase-explorer: Technologies not covered by MarsAI Standards]
[e.g., specific message broker, specific cache, DB if not PostgreSQL]
| Technology | Purpose | Notes |
|------------|---------|-------|
| [detected] | [purpose] | [notes] |
[From marsai:codebase-explorer: Directories that deviate from MarsAI's standard API structure]
[e.g., workers/, consumers/, polling/]
| Directory | Purpose | Pattern |
|-----------|---------|---------|
| [detected] | [purpose] | [pattern] |
[From marsai:codebase-explorer: Third-party services specific to this project]
| Service | Purpose | Docs |
|---------|---------|------|
| [detected] | [purpose] | [link] |
[From marsai:codebase-explorer: Project-specific env vars not covered by MarsAI]
| Variable | Purpose | Example |
|----------|---------|---------|
| [detected] | [purpose] | [example] |
[From codebase analysis: Technical names used in this codebase]
| Term | Definition | Used In |
|------|------------|---------|
| [detected] | [definition] | [location] |
---
*Generated: [ISO timestamp]*
*Source: Codebase analysis (marsai:codebase-explorer)*
*MarsAI Standards Version: [version from WebFetch]*
Present to User
┌─────────────────────────────────────────────────────────────────┐
│ ✓ PROJECT_RULES.md Generated from Code Analysis │
├─────────────────────────────────────────────────────────────────┤
│ │
│ I analyzed your codebase using: │
│ • marsai:codebase-explorer (technical patterns, stack, structure) │
│ │
│ Combined with your input on: │
│ • Current development goal │
│ • External integrations │
│ • Project-specific technology │
│ │
│ Generated: docs/PROJECT_RULES.md │
│ │
│ Note: MarsAI Standards (error handling, logging, testing, etc.) │
│ are not duplicated - agents load them automatically via WebFetch│
│ │
│ Please review the file and make any corrections needed. │
│ │
└─────────────────────────────────────────────────────────────────┘
Ask for Approval
Use AskUserQuestion:
- Question: "PROJECT_RULES.md has been generated. Would you like to review it before proceeding?"
- Options: (a) Proceed (b) Open for editing first
After Approval
Proceed to Step 1
Step 0.3: Check for PM Documents (PRD/TRD/Feature Map)
Collect PM Document Paths
The user indicated they have PM docs. Ask for file paths:
Ask for File Paths
"Please provide the file path(s) to your PM documents:
- PRD path (or 'skip' if none):
- TRD path (or 'skip' if none):
- Feature Map path (or 'skip' if none): "
Example Paths
Typical PM team output structure:
docs/pre-dev/{feature-name}/
├── prd.md → PRD path: docs/pre-dev/auth-system/prd.md
├── trd.md → TRD path: docs/pre-dev/auth-system/trd.md
├── feature-map.md → Feature Map path: docs/pre-dev/auth-system/feature-map.md
├── api-design.md
├── data-model.md
└── tasks.md
Common Patterns
/marsai:pre-dev-full output: docs/pre-dev/{feature}/prd.md, trd.md, feature-map.md
/marsai:pre-dev-feature output: docs/pre-dev/{feature}/prd.md, feature-map.md
- Custom locations: User may have docs in different paths (e.g.,
requirements/, specs/)
Then
Go to Step 0.3.1 (Generate from PM Documents)
Step 0.3.1: Generate from PM Documents (PRD/TRD/Feature Map)
Read the Provided Documents
Read tool:
file_path: "[user-provided PRD path]"
Read tool:
file_path: "[user-provided TRD path]"
Read tool:
file_path: "[user-provided Feature Map path]"
Extract PROJECT_RULES.md Content from PM Documents
⛔ DEDUPLICATION RULE: Extract only what MarsAI Standards DO NOT cover.
| From PRD | Extract For PROJECT_RULES.md | Note |
|---|
| Domain terms, entities | Domain Terminology | Technical names only |
| External service mentions | External Integrations | Third-party APIs |
Business rules | N/A | ❌ Stays in PRD, not PROJECT_RULES |
Architecture | N/A | ❌ MarsAI Standards covers this |
| From TRD | Extract For PROJECT_RULES.md | Note |
|---|
| Tech stack not in MarsAI | Tech Stack (Not in MarsAI) | Only non-standard tech |
| External APIs | External Integrations | Third-party services |
| Non-standard directories | Non-Standard Directory Structure | Workers, consumers, etc. |
Architecture decisions | N/A | ❌ MarsAI Standards covers this |
Database patterns | N/A | ❌ MarsAI Standards covers this |
| From Feature Map | Extract For PROJECT_RULES.md | Note |
|---|
| Technology choices not in MarsAI | Tech Stack (Not in MarsAI) | Only if not in MarsAI |
| External dependencies | External Integrations | Third-party services |
Architecture | N/A | ❌ MarsAI Standards covers this |
Generate PROJECT_RULES.md
Create tool:
file_path: "docs/PROJECT_RULES.md"
content: |
# Project Rules
> ⛔ IMPORTANT: MarsAI Standards are not automatic. Agents MUST WebFetch them before implementation.
> This file documents only project-specific information not covered by MarsAI Standards.
> Generated from PM documents (PRD/TRD/Feature Map).
>
> MarsAI Standards URLs:
> - TypeScript: https://raw.githubusercontent.com/V4-Company/marsai/main/dev-team/docs/standards/typescript.md
The following are defined in MarsAI Standards and MUST not be duplicated in this file:
- Error handling patterns (no panic, wrap errors)
- Logging standards (structured JSON)
- Testing patterns (table-driven tests, mocks)
- Architecture patterns (Hexagonal, Clean Architecture)
- Observability (OpenTelemetry)
- API directory structure (V4-Company pattern)
- Database connections (PostgreSQL, MongoDB, Redis)
**Agents MUST WebFetch MarsAI Standards and output Standards Coverage Table.**
---
[From TRD/Feature Map: only technologies not covered by MarsAI Standards]
| Technology | Purpose | Notes |
|------------|---------|-------|
| [detected] | [purpose] | [notes] |
[From TRD: Directories that deviate from MarsAI's standard API structure]
| Directory | Purpose | Pattern |
|-----------|---------|---------|
| [detected] | [purpose] | [pattern] |
[From TRD/PRD: Third-party services specific to this project]
| Service | Purpose | Docs |
|---------|---------|------|
| [detected] | [purpose] | [link] |
[From TRD: Project-specific env vars not covered by MarsAI]
| Variable | Purpose | Example |
|----------|---------|---------|
| [detected] | [purpose] | [example] |
[From PRD: Technical names used in this codebase]
| Term | Definition | Used In |
|------|------------|---------|
| [detected] | [definition] | [location] |
---
*Generated from: [PRD path], [TRD path], [Feature Map path]*
*MarsAI Standards Version: [version from WebFetch]*
*Generated: [ISO timestamp]*
Check for Missing Information
If any section is empty or incomplete, ask supplementary questions:
| Missing Section | Supplementary Question |
|---|
| Tech Stack (Not in MarsAI) | "Any technology not covered by MarsAI Standards (message broker, cache, etc.)?" |
| External Integrations | "Any third-party APIs or external services?" |
| Domain Terminology | "What are the main entities/classes in this codebase?" |
| Non-Standard Directories | "Any directories that don't follow standard API structure (workers, consumers)?" |
Note: Do not ask about architecture, error handling, logging, testing - MarsAI Standards covers these.
After Generation
Present to user for review, then proceed to Step 1.
Step 0.3.2: HARD BLOCK - No PM Documents and No Existing Codebase
When User Has Neither PM Documents Nor an Existing Codebase to Analyze
┌─────────────────────────────────────────────────────────────────┐
│ ⛔ CANNOT PROCEED - PM DOCUMENTS REQUIRED │
├─────────────────────────────────────────────────────────────────┤
│ │
│ Development cannot start without project context. │
│ │
│ You have two options: │
│ │
│ Option 1: Create PM docs first using pre-dev skills: │
│ /marsai:pre-dev-full → For features ≥2 days (9 gates) │
│ /marsai:pre-dev-feature → For features <2 days (4 gates) │
│ │
│ Option 2: If you have an existing codebase, go back and choose │
│ "Generate from code analysis" to create PROJECT_RULES.md │
│ from your existing code. │
│ │
│ After either option, run /marsai:dev-cycle again. │
│ │
└─────────────────────────────────────────────────────────────────┘
Action
STOP EXECUTION. Do not proceed to Step 1.
Step 0 Anti-Rationalization
| Rationalization | Why It's WRONG | Required Action |
|---|
| "Skip PM docs, I'll add them later" | Later = never. No PM docs = no project context = agents guessing. | Run /marsai:pre-dev-full or /marsai:pre-dev-feature NOW |
| "Project is simple, doesn't need PM docs" | Simple projects still need domain context defined upfront. | Create PM documents first |
| "I know what I want to build" | Your knowledge ≠ documented knowledge agents can use. | Document in PRD/TRD/Feature Map |
| "PM workflow takes too long" | PM workflow takes 30-60 min. Rework from unclear requirements takes days. | Invest time upfront |
| "Just let me start coding" | Coding without requirements = building the wrong thing. | Requirements first, code second |
| "I don't want to answer the analysis questions" | Code analysis takes ~5 min. Without it, agents have zero context. | Answer the 3 questions |
| "Project is too complex to explain" | Start with high-level answers. PROJECT_RULES.md can be refined later. | Provide what you know NOW |
Pressure Resistance
| User Says | Your Response |
|---|
| "Just skip this, I'll create PM docs later" | "PM documents are REQUIRED for new projects. Without them, agents cannot understand your project's domain context or technical requirements. Run /marsai:pre-dev-full or /marsai:pre-dev-feature first." |
| "I don't need formal documents" | "PM documents are the source of truth for PROJECT_RULES.md. Development cannot start without documented requirements." |
| "This is just a quick prototype" | "Even prototypes need clear requirements. /marsai:pre-dev-feature takes ~30 minutes and prevents hours of rework." |
| "I already explained what I want verbally" | "Verbal explanations cannot be used by agents. Requirements MUST be documented in PRD/TRD/Feature Map files." |
| "Skip the code analysis questions" | "The code analysis (marsai:codebase-explorer + 3 questions) is the only way I can understand your project. It takes ~5 minutes and enables me to help you effectively." |
| "I'll fill in PROJECT_RULES.md myself" | "That works! Create docs/PROJECT_RULES.md with: Tech Stack (not in MarsAI), External Integrations, Domain Terminology. Do not duplicate MarsAI Standards content. Then run /marsai:dev-cycle again." |
Step 1: Initialize or Resume
Instructions-Only Mode (no task file)
Input: Custom instructions string without a task file path
Example: /marsai:dev-cycle "Add webhook notification support for account status changes"
When custom instructions are provided without a tasks file, marsai:dev-cycle generates tasks internally:
- Detect instructions-only mode: No task file argument AND instructions string provided
- Analyze prompt: Extract intent, scope, and requirements from the prompt
- Explore codebase: Dispatch
marsai:codebase-explorer to understand project structure
- Generate tasks: Create task structure internally based on prompt + codebase analysis
Task tool:
subagent_type: "marsai:codebase-explorer"
prompt: |
Analyze this codebase to support the following implementation request:
**User Request:** {prompt}
Provide:
1. Relevant files and patterns for this request
2. Suggested task breakdown (T-001, T-002, etc.)
3. Acceptance criteria for each task
4. Files that will need modification
Output as structured task list compatible with marsai:dev-cycle.
- Present generated tasks: Show user the auto-generated task breakdown
- Confirm with user: "I generated X tasks from your prompt. Proceed?"
- Set state:
state_path = "docs/marsai:dev-cycle/current-cycle.json"
cycle_type = "prompt"
source_prompt = "[user's prompt]"
- Generate
tasks array from marsai:codebase-explorer output
- Continue to execution mode selection (Step 1 substeps 7-9)
Anti-Rationalization for Prompt-Only Mode:
| Rationalization | Why It's WRONG | Required Action |
|---|
| "Skip codebase exploration, I understand the prompt" | Prompt understanding ≠ codebase understanding. Explorer provides context. | Always run marsai:codebase-explorer |
| "Generate minimal tasks to go faster" | Minimal tasks = missed requirements. Comprehensive breakdown prevents rework. | Generate complete task breakdown |
| "User knows what they want, skip confirmation" | User intent ≠ generated tasks. Confirmation prevents wrong implementation. | Always confirm generated tasks |
New Cycle (with task file path)
Input: path/to/tasks.md or path/to/pre-dev/{feature}/ with optional second argument for custom instructions
Examples:
/marsai:dev-cycle tasks.md
/marsai:dev-cycle tasks.md "Focus on error handling"
- Detect input: File → Load directly | Directory → Load tasks.md + discover subtasks/
- Build order: Read tasks, check for subtasks (ST-XXX-01, 02...) or TDD autonomous mode
- Determine state path:
- if source_file contains
docs/marsai:dev-refactor/ → state_path = "docs/marsai:dev-refactor/current-cycle.json", cycle_type = "refactor"
- else →
state_path = "docs/marsai:dev-cycle/current-cycle.json", cycle_type = "feature"
- Capture and validate custom instructions: If second argument provided:
- Sanitize input: Trim whitespace, strip control characters (except newlines)
- Store validated value: Set
custom_prompt field (empty string if not provided)
- Note: Directives attempting to skip gates are logged as warnings and ignored at execution time
- Initialize state: Generate cycle_id, create state file at
{state_path}, set indices to 0
- Display plan: "Loaded X tasks with Y subtasks"
- ASK EXECUTION MODE (MANDATORY - AskUserQuestion):
- Options: (a) Manual per subtask (b) Manual per task (c) Automatic
- Do not skip: User hints ≠ mode selection. Only explicit a/b/c is valid.
- ASK COMMIT TIMING (MANDATORY - AskUserQuestion):
- Options: (a) Per subtask (b) Per task (c) At the end
- Store in
commit_timing field in state
- Start: Display mode + commit timing, proceed to Gate 0
Resume Cycle (--resume flag)
- Find existing state file:
- Check
docs/marsai:dev-cycle/current-cycle.json first
- If not found, check
docs/marsai:dev-refactor/current-cycle.json
- If neither exists → Error: "No cycle to resume"
- Load found state file, validate (state_path is stored in the state object)
- Display: cycle started, tasks completed/total, current task/subtask/gate, paused reason
- Handle paused states:
| Status | Action |
|---|
paused_for_approval | Re-present Step 9.1 checkpoint |
paused_for_testing | Ask if testing complete → continue or keep paused |
paused_for_task_approval | Re-present Step 9.2 checkpoint |
paused_for_integration_testing | Ask if integration testing complete |
paused (generic) | Ask user to confirm resume |
in_progress | Resume from current gate |
Input Validation
Task files are generated by /pre-dev-* or /marsai:dev-refactor, which handle content validation. The marsai:dev-cycle performs basic format checks:
Format Checks
| Check | Validation | Action |
|---|
| File exists | Task file path is readable | Error: abort |
| Task headers | At least one ## Task: found | Error: abort |
| Task ID format | ## Task: {ID} - {Title} | Warning: use line number as ID |
| Acceptance criteria | At least one - [ ] per task | Warning: task may fail validation gate |
Step 1.5: Detect External Dependencies (Cycle-Level Auto-Detection)
MANDATORY: Scan the codebase once at cycle start to detect external dependencies. Store in state.detected_dependencies for use by Gates 2, 6, and 7.
detected_dependencies = []
1. Scan docker-compose.yml / docker-compose.yaml for service images:
- Grep tool: pattern "postgres" in docker-compose* files → add "postgres"
- Grep tool: pattern "mongo" in docker-compose* files → add "mongodb"
- Grep tool: pattern "valkey" in docker-compose* files → add "valkey"
- Grep tool: pattern "redis" in docker-compose* files → add "redis"
- Grep tool: pattern "rabbitmq" in docker-compose* files → add "rabbitmq"
2. Scan dependency manifests:
if language == "typescript":
- Grep tool: pattern "\"pg\"" in package.json → add "postgres"
- Grep tool: pattern "@prisma/client" in package.json → add "postgres"
- Grep tool: pattern "\"mongodb\"" in package.json → add "mongodb"
- Grep tool: pattern "\"mongoose\"" in package.json → add "mongodb"
- Grep tool: pattern "\"redis\"" in package.json → add "redis"
- Grep tool: pattern "\"ioredis\"" in package.json → add "redis"
- Grep tool: pattern "@valkey" in package.json → add "valkey"
- Grep tool: pattern "\"amqplib\"" in package.json → add "rabbitmq"
- Grep tool: pattern "amqp-connection-manager" in package.json → add "rabbitmq"
3. Deduplicate detected_dependencies
4. Store: state.detected_dependencies = detected_dependencies
5. Log: "Auto-detected external dependencies: [detected_dependencies]"
### Multi-Tenant Detection (Optional)
```text
6. Detect existing multi-tenant code (if applicable):
multi_tenant_exists = false
if language == "typescript":
- Grep tool: pattern "MULTI_TENANT_ENABLED" in src/ --include="*.ts" → multi_tenant_exists = true
- Grep tool: pattern "tenant-manager" in package.json → multi_tenant_exists = true
state.multi_tenant_exists = multi_tenant_exists
else:
Log: "Multi-tenant NOT detected — Gate 0 agent will implement dual-mode, Gate 0.5G will verify"
MANDATORY: ⛔ Save state to file — Write tool → [state.state_path]
<auto_detect_reason>
PM team task files often omit external_dependencies. If the codebase uses postgres, mongodb, valkey, or rabbitmq, these MUST be detected and passed to Gates 6 (integration) and 7 (chaos). Auto-detection at cycle level avoids redundant scans per gate.
Multi-tenant state is detected here and passed to Gate 0 (implementation) and Gate 0.5G (verification).
</auto_detect_reason>
Step 1.7: Cycle Size Calibration (MANDATORY)
Classify each execution unit as small, medium, or large. The classification controls:
- Whether the unit is split into multiple sub-tasks (T-001 / T-002 / T-003 style) — small units are NEVER split
- How many reviewers Gate 6 dispatches — small: 3, medium: 5, large: 7
- How many review iterations are allowed — small: 1, medium: 2, large: 2
The goal is to stop over-engineering trivial features. A one-endpoint signout or a one-field rename does not need the 7-reviewer × 2-iteration cycle a green-field service does.
Sizing heuristics (apply in order — first match wins)
for each execution unit in state.tasks:
# Count implementation targets from the task description:
# - New aggregates/entities in domain/
# - New use cases in app/usecases/
# - New provider/gateway interfaces in domain/providers/ or domain/gateways/
# - Modified files explicitly referenced in acceptance criteria
new_domain_primitives = count(aggregates + entities + value_objects to CREATE)
new_usecases = count(usecases to CREATE)
new_routes = count(HTTP routes to CREATE)
touched_files_est = estimate from acceptance criteria + task description
if (new_domain_primitives == 0
and new_usecases <= 1
and new_routes <= 2
and touched_files_est <= 6):
unit.cycle_size = "small"
unit.reviewers = ["marsai:code-reviewer",
"marsai:security-reviewer",
"marsai:nil-safety-reviewer"]
unit.review_max_iterations = 1
unit.allow_subtasks = false
elif (new_domain_primitives <= 2
and new_usecases <= 3
and touched_files_est <= 15):
unit.cycle_size = "medium"
unit.reviewers = ["marsai:code-reviewer",
"marsai:business-logic-reviewer",
"marsai:security-reviewer",
"marsai:nil-safety-reviewer",
"marsai:test-reviewer"]
unit.review_max_iterations = 2
unit.allow_subtasks = true
else:
unit.cycle_size = "large"
unit.reviewers = ["marsai:code-reviewer",
"marsai:business-logic-reviewer",
"marsai:security-reviewer",
"marsai:nil-safety-reviewer",
"marsai:test-reviewer",
"marsai:consequences-reviewer",
"marsai:dead-code-reviewer"]
unit.review_max_iterations = 2
unit.allow_subtasks = true
Pressure to upgrade / downgrade
| Rationalization | Why It's WRONG | Required Action |
|---|
| "This is security-sensitive, force it to large" | Sensitivity triggers marsai:security-reviewer, which is in every tier. Size is about scope, not risk. | Use the heuristic result |
| "Small feels risky, let me run all 7 reviewers" | 7 reviewers on a 3-file feature add noise, not signal. | Respect the small tier |
| "Task description is vague, default to large" | Vague tasks need clarification, not more reviewers. | Ask the user to clarify acceptance criteria |
| "Splitting into T-001/T-002 is safer" | Small features MUST NOT be split. Splitting hides low scope behind artificial tasks. | No subtasks when unit.allow_subtasks == false |
| "The signout PR was small but had a security bug, so run large" | One miss ≠ pattern. Fix the standard that missed the bug (Gate 0.5), not the cycle size. | Use the heuristic result |
Output
Emit at the start of Gate 0 (implementation):
## Cycle Size Calibration
| Execution Unit | Size | Reviewers | Max Iterations | Subtasks Allowed |
|----------------|------|-----------|----------------|------------------|
| [unit_id] | [small/medium/large] | [N reviewers] | [N] | [yes/no] |
MANDATORY: ⛔ Save state to file — Write tool → [state.state_path]
When Gate 6 (review) dispatches reviewers, it MUST use unit.reviewers (not the default 7). When the implementation agent proposes splitting a small unit into subtasks, the orchestrator MUST refuse and proceed with a single task.
Step 2: Gate 0 - Implementation (Per Execution Unit)
REQUIRED SUB-SKILL: Use marsai:dev-implementation
Execution Unit: Task (if no subtasks) or Subtask (if task has subtasks)
Pre-Dispatch: Before Gate 0 Checkpoint (MANDATORY)
MUST execute the Before Gate 0 (task start) row from the State Persistence Checkpoints table before sub-steps 2.1–2.3:
- Set
task.status = "in_progress" in state JSON
- Update tasks.md Status →
🔄 Doing (per tasks.md Status update rules in that table)
- Write state to file
CANNOT proceed to sub-steps 2.1–2.3 without completing this checkpoint.
⛔ MANDATORY: Invoke marsai:dev-implementation Skill (not inline execution)
See shared-patterns/shared-orchestrator-principle.md for full details.
⛔ FORBIDDEN: Executing TDD-RED/GREEN logic directly from this step.
MUST invoke the marsai:dev-implementation skill via the Skill tool; it handles all TDD phases, agent selection, agent dispatch, standards verification, and fix iteration.
⛔ File Size Enforcement (MANDATORY — All Gates)
See shared-patterns/file-size-enforcement.md for thresholds, verification commands, split strategies, and agent instructions.
Summary: No source file may exceed 300 lines (>300 = loop back to agent; >500 = hard block). Implementation agents MUST split proactively. Enforcement points:
- Gate 0: Implementation agent receives file-size instructions; orchestrator runs verification command after agent completes and loops back if any file > 300 lines.
- Gate 0.5: Delivery verification skill runs 7 checks: (A) file-size, (B) license headers, (C) linting, (D) migration safety, (E) vulnerability scanning, (F) API backward compatibility, (G) multi-tenant dual-mode. Any FAIL → return to Gate 0 with specific fix instructions.
- Gate 6: Code reviewers MUST flag any file > 300 lines as a MEDIUM+ issue (blocking).
Step 2.1: Prepare Input for marsai:dev-implementation Skill
Gather from current execution unit:
implementation_input = {
// REQUIRED - from current execution unit
unit_id: state.current_unit.id,
requirements: state.current_unit.acceptance_criteria,
// REQUIRED - detected from project
language: state.current_unit.language, // "typescript" | "python"
service_type: state.current_unit.service_type, // "api" | "worker" | "batch" | "cli" | "frontend" | "bff"
// OPTIONAL - additional context
technical_design: state.current_unit.technical_design || null,
existing_patterns: state.current_unit.existing_patterns || [],
project_rules_path: "docs/PROJECT_RULES.md"
}
Step 2.2: Invoke marsai:dev-implementation Skill
1. Record gate start timestamp
2. REQUIRED: Invoke marsai:dev-implementation skill with structured input:
Skill("marsai:dev-implementation") with input:
unit_id: implementation_input.unit_id
requirements: implementation_input.requirements
language: implementation_input.language
service_type: implementation_input.service_type
technical_design: implementation_input.technical_design
existing_patterns: implementation_input.existing_patterns
project_rules_path: implementation_input.project_rules_path
The skill handles:
- Selecting appropriate agent (TS/Frontend based on language)
- TDD-RED phase (writing failing test, capturing failure output)