Moai skill

MoAI unified orchestrator for autonomous development.

by modu-ai·Apache-2.0 license·★ 1,230 Stars on the repo·GitHub ↗

Use now

Files of Moai

modu-ai/main1 file shown
SKILL.md
Show the full text401 lines

Pre-execution Context

!git status --porcelain 2>/dev/null || true !git branch --show-current 2>/dev/null || true

Essential Files

.moai/config/sections/*.yaml


Authority References

Rules and constraints governing all workflows are always loaded from these sources. Do NOT duplicate their content here:

  • Core identity, orchestration principles, agent catalog: AGENTS.md + .moai/config/sections/delegation.yaml
  • Quality gates, security boundaries: .claude/rules/moai/core/moai-constitution.md
  • SPEC workflow phases, token budgets: .claude/rules/moai/workflow/spec-workflow.md
  • Development methodologies (DDD/TDD): .claude/rules/moai/workflow/spec-workflow.md (Run Phase section)
  • Agent definitions: See .moai/config/sections/delegation.yaml. For agent creation, use builder-harness subagent (artifact_type=agent).
  • @MX tag rules and protocol: .claude/rules/moai/workflow/mx-tag-protocol.md

Routing Observation Ledger

When dispatching a subcommand or workflow, the orchestrator records the routing decision to the append-only routing-ledger (.moai/state/routing-ledger.jsonl) via moai harness ledger record at dispatch time — the request text is piped via stdin and only a privacy-preserving digest is stored, never verbatim user text. As the routed pipeline reaches gate points, machine evidence is appended via moai harness ledger evidence (gate exits, audit verdicts, verify-log paths). Outcome is never supplied as an input; it is finalized from machine evidence only. This observation is opt-in and fail-open — it never blocks routing. NOTE: recording depends on the orchestrator actually invoking moai harness ledger record at dispatch; when the observability opt-in is ON but that record call is not emitted, the ledger stays empty — an un-recorded dispatch, NOT an opt-in-off no-op. Do not read an empty routing-ledger as 'opt-in disabled'.


Intent Router

Raw User Input

$ARGUMENTS

Routing Instructions

[HARD] Route the Raw User Input above using the strict priority order below. Extract the FIRST WORD of the input for subcommand matching. All text after the subcommand keyword is CONTEXT to be passed to the matched workflow — it is NOT a routing signal and MUST NOT influence which workflow is selected.

Execution Mode Flags (mutually exclusive)

  • --team: Force agent-team of the Phase 4 4-mode catalog (.claude/rules/moai/workflow/orchestration-mode-selection.md §A), subject to its capability gate
  • --solo: Force serial (sub-agent — single sequential agent per phase)
  • No flag: The orchestrator auto-selects from the full 4-mode catalog at Phase 4; the complexity auto-select thresholds are stated once in orchestration-mode-selection.md §B.1 (machine source: workflow.yaml auto_selection) and are not restated here

The --team / --solo flags are forced overrides onto the catalog; the flag-free default resolves through the catalog decision tree (§B) and its capability gates. The --mode dispatch axis is a separate axis — see the crosswalk in orchestration-mode-selection.md §G.1 (correspondence, not merge).

Priority 1: Explicit Subcommand Matching

[HARD] Extract the FIRST WORD from the Raw User Input section above. If it matches any subcommand below (or its alias), route to that workflow IMMEDIATELY. Do NOT analyze the remaining text for routing — it is context for the matched workflow:

[HARD] Mixed-language guard: FIRST-WORD subcommand matching applies only when (a) the input is pure ASCII/Latin, OR (b) the message is prefixed with a literal /moai slash form. When the message contains non-Latin script (Korean/Japanese/Chinese/etc.) beyond the first token, do NOT route immediately on the leading English word — treat it as a possible embedded loanword and fall through to Priority 3 semantic classification of the ENTIRE message. Rationale: CJK technical writing embeds English loanwords such as 'goal', 'run', 'fix', 'plan' at sentence start; immediate first-word routing misfires on them.

  • plan (aliases: spec): SPEC document creation workflow
  • run (aliases: impl): DDD/TDD implementation workflow (per quality.yaml constitution.development_mode)
  • sync (aliases: docs, pr): Documentation synchronization and PR creation
  • project (aliases: init): Project documentation generation
  • feedback (aliases: fb): GitHub issue creation
  • fix: Auto-fix errors in a single pass
  • loop: Iterative auto-fix until completion conditions are satisfied
  • mx: MX tag scan and annotation for codebase
  • review (aliases: code-review): Code review with security and MX tag compliance
  • clean (aliases: dead-code): Identify and safely remove dead code
  • codemaps: Generate architecture documentation in .moai/project/codemaps/
  • gate (aliases: check, pre-commit): Lightweight pre-commit quality gate (lint+format+type-check+test)
  • e2e (aliases: e2e-test, end-to-end): Multi-platform end-to-end testing (web/mobile/desktop) with project-type auto-detection and CLI-first toolchain selection
  • harness (aliases: hrn): harness lifecycle management — learning-lifecycle verbs (status / apply / rollback <date> / disable) + v4-lifecycle verbs (list / edit / remove / doctor), all dispatching through the unified moai harness Go-binary Cobra subcommand tree; the slash command is the documented user-facing entry point
  • goal: Two compatible modes — a condition goal (/moai goal "<condition>") or an approved auto mission (/moai goal --auto "<mission>") with approve, run, status, revoke, and resume lifecycle verbs
  • todo (aliases: backlog): Canonical queue workflow — the operator's backlog queue (GTD task management)
  • gtd: Compatibility alias — route to the canonical todo workflow while preserving the supplied arguments
Priority 2: SPEC-ID Detection

Only if Priority 1 did not match: Check if the Raw User Input contains a pattern matching SPEC-XXX (such as SPEC-AUTH-001). If found, route to the run workflow automatically. The SPEC-ID becomes the target for DDD/TDD implementation.

Priority 3: Natural Language Classification

Only if BOTH Priority 1 AND Priority 2 did not match: Classify the intent of the ENTIRE Raw User Input as natural language. This priority is NEVER reached when the first word matches a known subcommand.

[HARD] The cue words listed below are English exemplars, NOT literal-match requirements. Classify intent semantically for any conversation_language — a Korean, Japanese, Chinese, or other-language request expressing the same intent routes identically. Do not require the literal English tokens to appear.

  • Planning and design language (design, architect, plan, spec, requirements, feature request) routes to plan
  • Quality gate language (format, check, pre-commit, quality gate) routes to gate
  • E2E and user-journey testing language (e2e, end-to-end test, browser test, mobile app test, desktop app test, user journey) routes to e2e — semantic exemplars; any conversation_language expressing e2e-testing intent routes identically
  • Security language (security, audit, owasp, vulnerability, injection, xss, csrf) routes to review (with --security scope)
  • Code-review language (review my code, code review, check my PR, look at my changes, take a look at my changes) routes to review
  • Error and fix language (fix, error, bug, broken, failing, lint) routes to fix
  • Iterative and repeat language (keep fixing, until done, repeat, iterate, all errors) routes to loop
  • Dead-code and cleanup language (dead code, unused code, safely remove, cleanup, orphaned code) routes to clean
  • Documentation language (document, sync, docs, readme, changelog, PR) routes to sync or project
  • Architecture-map language (architecture map, code maps, dependency graph, structure documentation) routes to codemaps
  • Feedback and bug report language (report, feedback, suggestion, issue) routes to feedback
  • MX tag language (mx tag, annotation, code context, legacy annotate) routes to mx
  • Backlog language (add to the backlog, note this for later, what should I work on next, remind me to) routes to todo — semantic exemplars; a request in any conversation_language expressing "queue this, do not start it now" routes identically
  • Implementation language (implement, build, create, add, develop) with clear scope routes to moai (default autonomous)
Priority 4: Default Behavior

If the intent remains ambiguous after all priority checks, use AskUserQuestion to present the top 2-3 matching workflows and let the user choose.

If the intent is clearly a development task with no specific routing signal, default to the moai workflow (plan -> run -> sync pipeline) for full autonomous execution.


Workflow Quick Reference

plan - SPEC Document Creation

Purpose: Create comprehensive specification documents using GEARS format with Research-Plan-Annotate cycle. Phases: Deep Research (research.md) -> SPEC Planning -> Annotation Cycle (1-6 iterations) -> SPEC Creation -> Independent Review (plan-auditor) Agents: manager-spec (primary), Explore (research), plan-auditor (quality gate), manager-git (conditional) Skills: moai-workflow-spec, moai-foundation-thinking (per delegation.yaml) Flags: --branch, --resume SPEC-XXX, --issue (opt-in; default skips GitHub Issue creation per the late-branch opt-in policy) For detailed orchestration: Read workflows/plan.md

run - DDD/TDD Implementation

Purpose: Implement SPEC requirements through configured development methodology. Agents: manager-develop (cycle_type=ddd|tdd per quality.yaml, primary), manager-git Skills: moai-workflow-tdd, moai-workflow-ddd (per delegation.yaml; cycle_type-selected) + domain moai-ref-* injected per mission Flags: --resume SPEC-XXX, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags) For detailed orchestration: Read workflows/run.md

sync - Documentation Sync and PR

Purpose: Synchronize documentation with code changes and prepare pull requests. Agents: manager-docs (primary), sync-auditor (quality gate), manager-git Skills: moai-workflow-project (per delegation.yaml) Modes: auto, force, status, project. Flags: --auto-merge, --merge (deprecated alias of --auto-merge), --skip-mx For detailed orchestration: Read workflows/sync.md

gate - Pre-Commit Quality Gate

Purpose: Lightweight pre-commit quality check running lint, format, type-check, and tests in parallel. Also integrated into run (Phase 15) and sync (Phase 1) workflows as automatic pre-checks. Agents: Direct execution (no agent delegation) Flags: --fix, --staged, --file PATH Integration: Automatically invoked by run workflow (Phase 15) and sync workflow (Phase 1) with --fix behavior. For detailed orchestration: Read workflows/gate.md

e2e - Multi-Platform End-to-End Testing

Purpose: Create and run E2E tests across web, mobile, and desktop applications with project-type auto-detection, CLI-first toolchain selection (Playwright, Maestro, Playwright-Electron, WebdriverIO + tauri-service), and token-minimized execution. Agents: e2e-tester (primary — detection, journey mapping, script creation, execution, recording) Skills: moai-foundation-quality, moai-ref-testing-pyramid (per delegation.yaml) Flags: --tool, --platform, --record, --url, --journey, --headless, --browser, --timeout, --retry For detailed orchestration: Read workflows/e2e.md

goal - Condition Goal and Approved Auto Mission

Purpose: Preserve condition-declared goal loops while exposing a distinct approved autonomous-mission lifecycle. Condition goal: /moai goal "<condition>" (register + arm), status [--all], clear, render. Auto mission: /moai goal --auto "<mission>", followed by approve, run, status, revoke, or resume. Flags: --auto selects mission_mode=auto; it does not mean progression_mode=autonomous. Shared metadata flags include --session and --json. Progression mode: autonomous (default) vs. semi-autonomous — chosen at Implementation Kickoff Approval; the gate stays mandatory in both modes. For detailed orchestration: Read workflows/goal.md

Where workflow.autonomy.mode: contract — the Kickoff approval named here is the contract signature checked by moai contract kickoff-check; the progression mode is chosen when a goal is armed after that check passes. See .claude/rules/moai/workflow/contract-autonomy.md § The signing gate.

todo - Queue Workflow and Backlog Queue

Purpose: Carry captured work through Capture, Clarify, Organize, Reflect, and Engage, and hold what the operator wants to work on next. backlog has no owning session, so admission to the board is always an operator act — this is that surface. Verbs — slash surface: /moai todo "<description>" (append), bare /moai todo (list). CLI only: moai todo next (print queued cards; moai todo next <n> [--spec <SPEC-ID>] marks one picked — the pick itself is presented through AskUserQuestion), moai todo done <n> (remove). GTD stages: capture, clarify, organize, reflect, engage, plus answer for a gate-blocked card. Captured items stay separate from the established development queue until an explicitly approved Engage publishes one. Compatibility: /moai gtd and moai gtd are the compat alias of the canonical /moai todo and moai todo — same database, same card identities, same ordering, archive, and restore path. State: ~/.moai/db/<project-key>/todo/backlog.db — home-scoped, project-keyed, not committed, a SQLite database every mutation takes a cross-process lock over. A backlog.json beside an existing database is an export or a legacy leftover; the read verbs report that distinction. Before migration, a legacy JSON-only queue remains readable. The pick is the operator's: never preselect, never reorder by inferred priority (the --auto cycle's own candidate ranking is the one auto-scoped ranking exception — selection order only), never auto-populate from TODO comments or issues. Enablement: when workflow.todo.enabled is false in .moai/config/sections/workflow.yaml, do NOT route to this workflow by inference — a backlog-shaped phrase the operator did not name a subcommand for is answered directly instead of being queued. The gate binds AUTOMATIC routing only: an explicit /moai todo or /moai todo "<description>" still runs normally, exactly as it does when the key is absent or true. The flag suppresses guidance, not the feature — the queue verbs stay registered and every one of them keeps working, so refusing or silently ignoring a named invocation is a defect, not the intended behavior. For detailed orchestration: Read workflows/gtd.md

fix - Auto-Fix Errors

Purpose: Autonomously detect and fix LSP errors, linting issues, and type errors. Agents: manager-develop (cycle_type=autofix), Agent(general-purpose) with domain whitelist (fixes) Skills: moai-workflow-ddd (per delegation.yaml) + domain moai-ref-* injected per mission Flags: --dry, --sequential, --level N, --resume, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags) For detailed orchestration: Read workflows/fix.md

loop - Iterative Auto-Fix

Purpose: Repeatedly fix issues until completion conditions are satisfied or max iterations reached. Agents: manager-develop (cycle_type=autofix), Agent(general-purpose) with domain whitelist Skills: moai-workflow-loop (per delegation.yaml) + domain moai-ref-* injected per mission Flags: --max N, --auto-fix, --seq For detailed orchestration: Read workflows/loop.md

mx - MX Tag Scan and Annotation

Purpose: Scan codebase and add @MX code-level annotations for AI agent context. Agents: Explore (scan), Agent(general-purpose) with backend scope (annotation) Flags: --all, --dry, --priority P1-P4, --force, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags) For detailed orchestration: Read workflows/mx.md

review - Code Review

Purpose: Multi-perspective code review with security, performance, quality, and UX analysis. Agents: sync-auditor (review), Agent(general-purpose) with security scope Skills: moai-foundation-quality, moai-ref-owasp-checklist (per delegation.yaml; per-perspective ref skills injected per lens) Flags: --staged, --branch, --security, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags) For detailed orchestration: Read workflows/review.md

clean - Dead Code Removal

Purpose: Identify and safely remove unused code with test verification. Agents: manager-develop, Agent(general-purpose) with refactoring scope Skills: moai-workflow-ddd (per delegation.yaml) Flags: --dry, --safe-only, --file PATH For detailed orchestration: Read workflows/clean.md

codemaps - Architecture Documentation

Purpose: Scan codebase and generate architecture documentation. Agents: Explore, manager-docs Flags: --force, --area AREA For detailed orchestration: Read workflows/codemaps.md

(default) - MoAI Autonomous Workflow

Purpose: Full autonomous research -> plan -> annotate -> run -> sync pipeline. Phases: Parallel Exploration (research.md) -> SPEC Generation -> Annotation Cycle -> Implementation -> Sync Agents: Explore, manager-spec, plan-auditor (quality gate), manager-develop, manager-docs, manager-git, sync-auditor (quality gate) Skills: moai-workflow-spec, moai-workflow-tdd (per delegation.yaml) + domain moai-ref-* injected per mission Flags: --loop, --max N, --branch, --pr, --resume SPEC-XXX, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags), --solo, --issue (opt-in; default skips GitHub Issue creation per the late-branch opt-in policy) For detailed orchestration: Read workflows/moai.md

project - Project Documentation

Purpose: Generate project documentation by analyzing the existing codebase. Agents: Explore, manager-docs, Agent(general-purpose) with devops scope (optional) Skills: moai-workflow-project (per delegation.yaml) Output: product.md, structure.md, tech.md in .moai/project/ For detailed orchestration: Read workflows/project.md

feedback - GitHub Issue Creation

Purpose: Collect user feedback and create GitHub issues. Agents: orchestrator-direct (records feedback via gh CLI) For detailed orchestration: Read workflows/feedback.md

harness - Harness Lifecycle + Natural-Language Build (argument-branching)

This single harness subcommand dispatches to ONE of two workflows based on the FIRST token of $ARGUMENTS (argument-based routing — no second command is introduced). Apply the routing rule before any workflow-specific logic:

  • Reserved verb (status / apply / rollback / disable) → route to the existing harness learning lifecycle workflow (Branch A below). This path is unchanged.
  • Reserved verb (list / edit / remove / doctor) → route to the harness-v4 lifecycle handler (Branch A.1 below). These enumerate / edit / atomically-remove harness-v4 entries and run the reference-integrity smoke gate (doctor) via the moai harness <verb> Go binary subcommand.
  • Anything else (a natural-language harness-creation request, e.g. "build a harness for CLI template development") → route to the harness build entry workflow (Branch B below).
Branch A — harness learning lifecycle (reserved verbs: status / apply / rollback / disable)

Purpose: Surface the harness learning subsystem (observer, 4-tier proposal ladder, 5-layer safety pipeline) to the user via the slash command path. The lifecycle verbs (status / apply / rollback / disable) dispatch through the unified moai harness Go-binary Cobra subcommand tree, which performs the file-system operations. Tier-4 application is gated by orchestrator-issued AskUserQuestion. Skills: moai-harness-learner (Tier-4 surfacing companion). Project-specific harness generation is handled by the v4 Builder (builder-harness agent, Branch B). Verbs: status (tier distribution + telemetry) | apply (next Tier-4 proposal → AskUserQuestion → 5-layer pipeline → snapshot + write) | rollback <YYYY-MM-DD> (restore snapshot) | disable (set learning.enabled: false) Artifacts: .moai/harness/usage-log.jsonl, .moai/harness/proposals/, .moai/harness/learning-history/snapshots/, .moai/harness/learning-history/applied/, .moai/harness/learning-history/frozen-guard-violations.jsonl Authoritative SPEC: the harness foundation policy (supersedes V3R3-HARNESS-001, V3R3-HARNESS-LEARNING-001, V3R3-PROJECT-HARNESS-001) For detailed orchestration: Read workflows/harness.md

Branch A.1 — harness-v4 lifecycle (reserved verbs: list / edit / remove / doctor)

Purpose: Manage harness-v4 entries — enumerate built harnesses, locate their manifest + specialist files for editing, atomically remove a harness with all its artifacts, or run the reference-integrity smoke gate. The four verbs dispatch to the moai harness <verb> Go binary subcommand which performs the filesystem work (scan .claude/commands/harness/*.md joined with manifest.json; atomic remove with fail-closed orphan prevention; doctor cross-references manifest/specialist/skill file existence). Verbs: list (enumerate all harnesses: name + domain + entry command, plus the declared schedule — interval + mechanism — when the manifest declares one; schedule-less harnesses render identically to the pre-schedule baseline) | edit <name> (show manifest + specialist + skill paths for editing — manifest is the SSOT) | remove <name> (atomic removal of command + workflow + specialists + skills + manifest; fail-closed if any artifact is missing; when the manifest declared a schedule, prints an unregister notice naming the declared mechanism — CronDelete for cron, session-scoped loop cancellation for loop — computed from the manifest before deletion) | doctor (reference-integrity smoke gate: verifies every built harness's manifest/specialist/skill files exist and cross-reference correctly; a schema-invalid schedule declaration is an ERROR-severity finding) CLI: moai harness list [--json], moai harness edit <name> [--json], moai harness remove <name>, moai harness doctor (all support --project-root) Artifacts: .claude/commands/harness/<name>.md (thin-wrapper command), .claude/commands/harness/<name>/manifest.json (SSOT), .claude/workflows/hns-<name>-run.js (Runner), .claude/agents/harness/hns-<name>*-specialist.md (specialists), .claude/skills/hns-<name>*/ (companion skills) Namespace: .claude/commands/harness/, .claude/workflows/hns-*.js, .claude/agents/harness/, and .claude/skills/hns-*/ are USER-OWNED — moai update preserves them (backup if needed, never overwrites). Legacy generations with the harness- or my-harness- prefix are equally preserved (recognition-based backward compatibility); the Builder emits hns- names only.

Branch B — harness build entry (natural-language request)

Purpose: Turn a natural-language harness-creation request into a concrete harness via Context-First Discovery (extract domain / goal / constraints / scope), harness <name> derivation (the name is derived from the request — NOT statically supplied by the user), explicit orchestrator-issued approval, then transition into the orchestrator-direct Builder (4 signal-driven phases: ANALYZE / PLAN / GENERATE / ACTIVATE). The orchestrator MUST conduct AskUserQuestion Socratic rounds (max 4 questions per round) when intent clarity is below 100%. Agent: builder-harness (v4 Builder — project-specific harness generation) Builder: orchestrator-direct processing (NOT a dynamic-workflow script) — the entry's Phases 0-3 hand off to workflows/harness-builder.md for the 4-phase creation logic. The orchestrator holds the PLAN→GENERATE AskUserQuestion approval gate directly; that gate round also carries the recurrence question (optional manifest schedule, discovery-only scheduled runs), and ACTIVATE registers a declared schedule after the smoke gate. A request referencing an EXISTING harness together with scheduling intent routes to the entry workflow's Schedule Retrofit branch (evaluated before name-collision handling) instead of the creation pipeline. For detailed orchestration: Read workflows/harness-build-entry.md


Execution Directive

When this skill is activated, execute the following steps in order:

Step 1 - Parse Arguments: Extract subcommand keywords and flags from the Raw User Input. Recognized global flags: --resume [ID], --seq, --team, --solo. Also detect ultrathink keyword in the input text.

CRITICAL: Deep analysis mode:

  • ultrathink keyword detected → Activate Claude's native extended reasoning (xhigh effort mode). This is native Claude behavior with no MCP dependency.

Step 1.5 - Flag-Subcommand Compatibility Validation: [HARD] After parsing the subcommand and flags (Step 1), validate flag-subcommand compatibility BEFORE routing. If a forbidden combination is detected, STOP all further processing and output an error in the user's conversation_language. Do NOT proceed to Step 2.

Forbidden flag-subcommand combinations:

Flag Allowed subcommands Forbidden subcommands
--branch plan, default (autonomous) run, sync

Rationale: --branch creates the feature branch at SPEC initialization, so /moai run and /moai sync MUST operate on the branch plan already established — re-creating it mid-lifecycle corrupts the SPEC lifecycle and is rejected at the router level.

The retired --worktree flag is handled separately: a request carrying it is not a forbidden-combination error but a retired flag. Tell the user that plan no longer creates a workspace, and that entering one first is the replacement.

Error message template (Korean conversation_language; substitute the actual flag and subcommand):

에러: --branch 플래그는 /moai plan 전용입니다.
/moai run 과 /moai sync 는 plan 단계에서 만든 브랜치를 그대로 씁니다.

올바른 사용법:
  /moai plan SPEC-XXX --branch    (브랜치 생성)
  /moai run SPEC-XXX              (기존 브랜치 재사용)
  /moai sync SPEC-XXX             (기존 브랜치 재사용)

--branch 플래그를 뺀 형태로 다시 실행하세요.

Retired-flag message (--worktree):

안내: --worktree 플래그는 폐기됐습니다. plan 은 더 이상 작업 공간을 만들지 않습니다.

격리된 공간에서 작업하려면 먼저 들어간 뒤 plan 을 실행하세요:
  moai cc -w <이름>              (그 자리에서 진입)
  moai cc -w <이름> --spawn      (새 Claude 세션을 tmux 창으로 열고 현재 세션 유지)
  /moai plan "<설명>"

For English (en conversation_language), translate the message; the structure remains identical.

Step 2 - Route to Workflow: Apply the Intent Router (Priority 1 through Priority 4) to determine the target workflow. If ambiguous, use AskUserQuestion to clarify with the user.

Step 2.2 - Record Routing Decision: Immediately after routing resolves (Step 2), record the routing decision to the append-only routing-ledger (.moai/state/routing-ledger.jsonl) so that auto-invocation is observable. Run:

echo "<raw request text>" | moai harness ledger record --subcommand <matched> --mode <phase-4-mode> --tier <tier> --level <harness-level> --session <session-id>

The request text is piped via stdin and only a privacy-preserving digest is stored, never verbatim user text (policy source: § Routing Observation Ledger above). This step is opt-in and fail-open: if the moai CLI is absent from PATH or the command exits non-zero, log nothing and continue — it NEVER blocks routing, never gates the workflow, and never triggers a retry loop. An un-recorded dispatch is an observation gap, not an error.

Step 2.5 - Project Documentation Check: Before executing plan, run, sync, fix, loop, or default workflows, verify project documentation exists by checking for .moai/project/product.md. If product.md does NOT exist, use AskUserQuestion to ask the user (in their conversation_language):

Question: Project documentation not found. Would you like to create it first? Options:

  • Create project documentation (Recommended): Generates product.md, structure.md, tech.md through a guided interview. This helps MoAI understand your project context for better results in all subsequent workflows.
  • Skip and continue: Proceed without project documentation. MoAI will have less context about your project.

This check does NOT apply to: project, feedback subcommands.

[HARD] Beginner-Friendly Option Design: All AskUserQuestion calls throughout MoAI workflows MUST follow these rules:

  • The first option MUST always be the recommended choice, clearly marked with "(Recommended)" suffix — this is the push-mode branch; while interview.recommendation_mode is pull the suffix is withheld from every option and no option carries a preference claim (.claude/rules/moai/core/askuser-protocol.md § Recommendation Placement Principles)
  • Every option MUST include a detailed description explaining what it does and its implications

Step 2.8 - Requirement Analysis & Completion Condition: Before loading the workflow body (Step 3), produce a requirement-analysis record for the routed request:

  1. Requirement summary (1-3 sentences): what the user asked for, restated in the orchestrator's own words.
  2. Completion condition: the end state that means "done". Where the condition is machine-verifiable (test exit code, lint-clean state, grep count, bounded turn count), express it in /moai goal-compatible form per .claude/rules/moai/workflow/goal-directive.md (one measurable end state + a stated check + a bound clause). Do NOT invent a parallel evaluator: arm the condition via /moai goal when the goal engine is available (hooks enabled — the evaluator is the stop-goal Stop hook); otherwise the orchestrator evaluates the identical condition text per-turn (graceful degradation — no new machinery).
  3. Pipeline contract: full-pipeline (default natural-language route — run-phase completion auto-chains into sync) or single-phase (explicit run/sync subcommand — chaining is offered as the "(Recommended)" next-step option, never fired silently).
  4. Orchestration-shape pre-signal: an early input to the Phase 4 4-mode selection (orchestration-mode-selection.md §A) — noted here, decided at Phase 4.

Trivial-scope exemption: skip this step entirely for feedback, gate, codemaps, sync status mode, and any Stage-1-Clarify exception per askuser-protocol.md § Ambiguity Triggers and Exceptions. Socratic-first ordering: while intent clarity is below 100%, run the Socratic interview (per askuser-protocol.md) BEFORE deriving the completion condition — the condition encodes drained intent, never a guess. A derived completion condition NEVER authorizes autonomous run-phase entry — Implementation Kickoff Approval remains mandatory at the plan→run boundary.

Step 3 - Load Workflow Details: Read workflows/<name>.md for the target subcommand. (Agent Teams is experimental and re-allowed: a --team flag selects the Agent Teams layer, subject to the constraints in .claude/rules/moai/workflow/orchestration-mode-selection.md §C.1. Only the static layer stays retired, so there is no separate team/<name>.md workflow file — the same workflows/<name>.md is read either way. Historical: the retired era emitted MODE_TEAM_UNAVAILABLE and fell back to sub-agent mode; the sentinel is retained as documented history.)

Step 4 - Read Configuration: Load relevant configuration from the .moai/config/sections/*.yaml section files as needed.

Step 5 - Initialize Task Tracking: Use TaskCreate to register discovered work items with pending status.

Step 6 - Execute Workflow Phases: Follow the workflow-specific phase instructions. Delegate all implementation to appropriate agents via Agent(). Collect user approvals at designated checkpoints via AskUserQuestion. Before each implementation/review Agent() spawn, apply .claude/rules/moai/workflow/skill-routing.md §1: inject 0-3 At start, invoke Skill("<name>") for <reason> lines per the delegation map (.moai/config/sections/delegation.yaml).

Step 7 - Track Progress: Update task status using TaskUpdate as work progresses (pending to in_progress to completed).

Step 8 - Present Results: Display results to the user in their conversation_language using Markdown format.

Step 9 - Declare Completion: When all workflow phases complete successfully, state that the workflow is complete in the Completion Report (banner / prose) so the result is unambiguous.

Step 10 - Guide Next Steps: Use AskUserQuestion to present the user with logical next actions based on the completed workflow.


Version: 2.8.0

1---
2name: moai
3description: >
4 MoAI unified orchestrator for autonomous development. Routes natural
5 language or subcommands (plan, run, sync, project, fix, loop, mx,
6 feedback, review, clean, codemaps, gate, e2e, harness, goal, gtd, todo) to
7 specialized agents.
8allowed-tools: Agent, AskUserQuestion, Skill, TaskCreate, TaskUpdate, TaskList, TaskGet, Bash, Read, Write, Edit, Glob, Grep
9argument-hint: "[subcommand] [args] | \"natural language task\""
10---
11 
12## Pre-execution Context
13 
14!`git status --porcelain 2>/dev/null || true`
15!`git branch --show-current 2>/dev/null || true`
16 
17## Essential Files
18 
19.moai/config/sections/*.yaml
20 
21---
22 
23## Authority References
24 
25Rules and constraints governing all workflows are always loaded from these sources. Do NOT duplicate their content here:
26 
27- Core identity, orchestration principles, agent catalog: AGENTS.md + `.moai/config/sections/delegation.yaml`
28- Quality gates, security boundaries: .claude/rules/moai/core/moai-constitution.md
29- SPEC workflow phases, token budgets: .claude/rules/moai/workflow/spec-workflow.md
30- Development methodologies (DDD/TDD): .claude/rules/moai/workflow/spec-workflow.md (Run Phase section)
31- Agent definitions: See `.moai/config/sections/delegation.yaml`. For agent creation, use builder-harness subagent (artifact_type=agent).
32- @MX tag rules and protocol: .claude/rules/moai/workflow/mx-tag-protocol.md
33 
34---
35 
36## Routing Observation Ledger
37 
38When dispatching a subcommand or workflow, the orchestrator records the routing decision to the append-only routing-ledger (`.moai/state/routing-ledger.jsonl`) via `moai harness ledger record` at dispatch time — the request text is piped via stdin and only a privacy-preserving digest is stored, never verbatim user text. As the routed pipeline reaches gate points, machine evidence is appended via `moai harness ledger evidence` (gate exits, audit verdicts, verify-log paths). Outcome is never supplied as an input; it is finalized from machine evidence only. This observation is opt-in and fail-open — it never blocks routing. NOTE: recording depends on the orchestrator actually invoking `moai harness ledger record` at dispatch; when the observability opt-in is ON but that record call is not emitted, the ledger stays empty — an un-recorded dispatch, NOT an opt-in-off no-op. Do not read an empty routing-ledger as 'opt-in disabled'.
39 
40---
41 
42## Intent Router
43 
44### Raw User Input
45 
46$ARGUMENTS
47 
48### Routing Instructions
49 
50[HARD] Route the Raw User Input above using the strict priority order below. Extract the FIRST WORD of the input for subcommand matching. All text after the subcommand keyword is CONTEXT to be passed to the matched workflow — it is NOT a routing signal and MUST NOT influence which workflow is selected.
51 
52## Execution Mode Flags (mutually exclusive)
53 
54- `--team`: Force agent-team of the Phase 4 4-mode catalog (`.claude/rules/moai/workflow/orchestration-mode-selection.md` §A), subject to its capability gate
55- `--solo`: Force serial (sub-agent — single sequential agent per phase)
56- No flag: The orchestrator auto-selects from the full 4-mode catalog at Phase 4; the complexity auto-select thresholds are stated once in `orchestration-mode-selection.md` §B.1 (machine source: `workflow.yaml` `auto_selection`) and are not restated here
57 
58The `--team` / `--solo` flags are forced overrides onto the catalog; the flag-free default resolves through the catalog decision tree (§B) and its capability gates. The `--mode` dispatch axis is a separate axis — see the crosswalk in `orchestration-mode-selection.md` §G.1 (correspondence, not merge).
59 
60### Priority 1: Explicit Subcommand Matching
61 
62[HARD] Extract the FIRST WORD from the Raw User Input section above. If it matches any subcommand below (or its alias), route to that workflow IMMEDIATELY. Do NOT analyze the remaining text for routing — it is context for the matched workflow:
63 
64[HARD] Mixed-language guard: FIRST-WORD subcommand matching applies only when (a) the input is pure ASCII/Latin, OR (b) the message is prefixed with a literal `/moai ` slash form. When the message contains non-Latin script (Korean/Japanese/Chinese/etc.) beyond the first token, do NOT route immediately on the leading English word — treat it as a possible embedded loanword and fall through to Priority 3 semantic classification of the ENTIRE message. Rationale: CJK technical writing embeds English loanwords such as 'goal', 'run', 'fix', 'plan' at sentence start; immediate first-word routing misfires on them.
65 
66- **plan** (aliases: spec): SPEC document creation workflow
67- **run** (aliases: impl): DDD/TDD implementation workflow (per quality.yaml constitution.development_mode)
68- **sync** (aliases: docs, pr): Documentation synchronization and PR creation
69- **project** (aliases: init): Project documentation generation
70- **feedback** (aliases: fb): GitHub issue creation
71- **fix**: Auto-fix errors in a single pass
72- **loop**: Iterative auto-fix until completion conditions are satisfied
73- **mx**: MX tag scan and annotation for codebase
74- **review** (aliases: code-review): Code review with security and MX tag compliance
75- **clean** (aliases: dead-code): Identify and safely remove dead code
76- **codemaps**: Generate architecture documentation in `.moai/project/codemaps/`
77- **gate** (aliases: check, pre-commit): Lightweight pre-commit quality gate (lint+format+type-check+test)
78- **e2e** (aliases: e2e-test, end-to-end): Multi-platform end-to-end testing (web/mobile/desktop) with project-type auto-detection and CLI-first toolchain selection
79- **harness** (aliases: hrn): harness lifecycle management — learning-lifecycle verbs (status / apply / rollback &lt;date&gt; / disable) + v4-lifecycle verbs (list / edit / remove / doctor), all dispatching through the unified `moai harness` Go-binary Cobra subcommand tree; the slash command is the documented user-facing entry point
80- **goal**: Two compatible modes — a condition goal (`/moai goal "<condition>"`) or an approved auto mission (`/moai goal --auto "<mission>"`) with `approve`, `run`, `status`, `revoke`, and `resume` lifecycle verbs
81- **todo** (aliases: backlog): Canonical queue workflow — the operator's backlog queue (GTD task management)
82- **gtd**: Compatibility alias — route to the canonical **todo** workflow while preserving the supplied arguments
83 
84### Priority 2: SPEC-ID Detection
85 
86Only if Priority 1 did not match: Check if the Raw User Input contains a pattern matching SPEC-XXX (such as SPEC-AUTH-001). If found, route to the **run** workflow automatically. The SPEC-ID becomes the target for DDD/TDD implementation.
87 
88### Priority 3: Natural Language Classification
89 
90Only if BOTH Priority 1 AND Priority 2 did not match: Classify the intent of the ENTIRE Raw User Input as natural language. This priority is NEVER reached when the first word matches a known subcommand.
91 
92[HARD] The cue words listed below are **English exemplars**, NOT literal-match requirements. Classify intent semantically for any `conversation_language` — a Korean, Japanese, Chinese, or other-language request expressing the same intent routes identically. Do not require the literal English tokens to appear.
93 
94- Planning and design language (design, architect, plan, spec, requirements, feature request) routes to **plan**
95- Quality gate language (format, check, pre-commit, quality gate) routes to **gate**
96- E2E and user-journey testing language (e2e, end-to-end test, browser test, mobile app test, desktop app test, user journey) routes to **e2e** — semantic exemplars; any conversation_language expressing e2e-testing intent routes identically
97- Security language (security, audit, owasp, vulnerability, injection, xss, csrf) routes to **review** (with `--security` scope)
98- Code-review language (review my code, code review, check my PR, look at my changes, take a look at my changes) routes to **review**
99- Error and fix language (fix, error, bug, broken, failing, lint) routes to **fix**
100- Iterative and repeat language (keep fixing, until done, repeat, iterate, all errors) routes to **loop**
101- Dead-code and cleanup language (dead code, unused code, safely remove, cleanup, orphaned code) routes to **clean**
102- Documentation language (document, sync, docs, readme, changelog, PR) routes to **sync** or **project**
103- Architecture-map language (architecture map, code maps, dependency graph, structure documentation) routes to **codemaps**
104- Feedback and bug report language (report, feedback, suggestion, issue) routes to **feedback**
105- MX tag language (mx tag, annotation, code context, legacy annotate) routes to **mx**
106- Backlog language (add to the backlog, note this for later, what should I work on next, remind me to) routes to **todo** — semantic exemplars; a request in any conversation_language expressing "queue this, do not start it now" routes identically
107- Implementation language (implement, build, create, add, develop) with clear scope routes to **moai** (default autonomous)
108 
109### Priority 4: Default Behavior
110 
111If the intent remains ambiguous after all priority checks, use AskUserQuestion to present the top 2-3 matching workflows and let the user choose.
112 
113If the intent is clearly a development task with no specific routing signal, default to the **moai** workflow (plan -> run -> sync pipeline) for full autonomous execution.
114 
115---
116 
117## Workflow Quick Reference
118 
119### plan - SPEC Document Creation
120 
121Purpose: Create comprehensive specification documents using GEARS format with Research-Plan-Annotate cycle.
122Phases: Deep Research (research.md) -> SPEC Planning -> Annotation Cycle (1-6 iterations) -> SPEC Creation -> Independent Review (plan-auditor)
123Agents: manager-spec (primary), Explore (research), plan-auditor (quality gate), manager-git (conditional)
124Skills: moai-workflow-spec, moai-foundation-thinking (per delegation.yaml)
125Flags: --branch, --resume SPEC-XXX, --issue (opt-in; default skips GitHub Issue creation per the late-branch opt-in policy)
126For detailed orchestration: Read workflows/plan.md
127 
128### run - DDD/TDD Implementation
129 
130Purpose: Implement SPEC requirements through configured development methodology.
131Agents: manager-develop (cycle_type=ddd|tdd per quality.yaml, primary), manager-git
132Skills: moai-workflow-tdd, moai-workflow-ddd (per delegation.yaml; cycle_type-selected) + domain moai-ref-* injected per mission
133Flags: --resume SPEC-XXX, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags)
134For detailed orchestration: Read workflows/run.md
135 
136### sync - Documentation Sync and PR
137 
138Purpose: Synchronize documentation with code changes and prepare pull requests.
139Agents: manager-docs (primary), sync-auditor (quality gate), manager-git
140Skills: moai-workflow-project (per delegation.yaml)
141Modes: auto, force, status, project. Flags: --auto-merge, --merge (deprecated alias of --auto-merge), --skip-mx
142For detailed orchestration: Read workflows/sync.md
143 
144### gate - Pre-Commit Quality Gate
145 
146Purpose: Lightweight pre-commit quality check running lint, format, type-check, and tests in parallel. Also integrated into run (Phase 15) and sync (Phase 1) workflows as automatic pre-checks.
147Agents: Direct execution (no agent delegation)
148Flags: --fix, --staged, --file PATH
149Integration: Automatically invoked by run workflow (Phase 15) and sync workflow (Phase 1) with --fix behavior.
150For detailed orchestration: Read workflows/gate.md
151 
152### e2e - Multi-Platform End-to-End Testing
153 
154Purpose: Create and run E2E tests across web, mobile, and desktop applications with project-type auto-detection, CLI-first toolchain selection (Playwright, Maestro, Playwright-Electron, WebdriverIO + tauri-service), and token-minimized execution.
155Agents: e2e-tester (primary — detection, journey mapping, script creation, execution, recording)
156Skills: moai-foundation-quality, moai-ref-testing-pyramid (per delegation.yaml)
157Flags: --tool, --platform, --record, --url, --journey, --headless, --browser, --timeout, --retry
158For detailed orchestration: Read workflows/e2e.md
159 
160### goal - Condition Goal and Approved Auto Mission
161 
162Purpose: Preserve condition-declared goal loops while exposing a distinct approved autonomous-mission lifecycle.
163Condition goal: `/moai goal "<condition>"` (register + arm), `status [--all]`, `clear`, `render`.
164Auto mission: `/moai goal --auto "<mission>"`, followed by `approve`, `run`, `status`, `revoke`, or `resume`.
165Flags: `--auto` selects `mission_mode=auto`; it does not mean `progression_mode=autonomous`. Shared metadata flags include `--session` and `--json`.
166Progression mode: autonomous (default) vs. semi-autonomous — chosen at Implementation Kickoff Approval; the gate stays mandatory in both modes.
167For detailed orchestration: Read workflows/goal.md
168 
169<!-- moai:contract-mode-start id="contract-signing-router" -->
170Where `workflow.autonomy.mode: contract` — the Kickoff approval named here is the contract signature checked by `moai contract kickoff-check`; the progression mode is chosen when a goal is armed after that check passes. See `.claude/rules/moai/workflow/contract-autonomy.md` § The signing gate.
171 
172<!-- moai:contract-mode-end -->
173### todo - Queue Workflow and Backlog Queue
174 
175Purpose: Carry captured work through Capture, Clarify, Organize, Reflect, and Engage, and hold what the operator wants to work on next. `backlog` has no owning session, so admission to the board is always an operator act — this is that surface.
176Verbs — slash surface: `/moai todo "<description>"` (append), bare `/moai todo` (list). CLI only: `moai todo next` (print queued cards; `moai todo next <n> [--spec <SPEC-ID>]` marks one picked — the pick itself is presented through AskUserQuestion), `moai todo done <n>` (remove).
177GTD stages: `capture`, `clarify`, `organize`, `reflect`, `engage`, plus `answer` for a gate-blocked card. Captured items stay separate from the established development queue until an explicitly approved Engage publishes one.
178Compatibility: `/moai gtd` and `moai gtd` are the compat alias of the canonical `/moai todo` and `moai todo` — same database, same card identities, same ordering, archive, and restore path.
179State: `~/.moai/db/<project-key>/todo/backlog.db` — home-scoped, project-keyed, not committed, a SQLite database every mutation takes a cross-process lock over. A `backlog.json` beside an existing database is an export or a legacy leftover; the read verbs report that distinction. Before migration, a legacy JSON-only queue remains readable.
180The pick is the operator's: never preselect, never reorder by inferred priority (the `--auto` cycle's own candidate ranking is the one auto-scoped ranking exception — selection order only), never auto-populate from TODO comments or issues.
181Enablement: when `workflow.todo.enabled` is `false` in `.moai/config/sections/workflow.yaml`, do NOT route to this workflow by inference — a backlog-shaped phrase the operator did not name a subcommand for is answered directly instead of being queued. The gate binds AUTOMATIC routing only: an explicit `/moai todo` or `/moai todo "<description>"` still runs normally, exactly as it does when the key is absent or `true`. The flag suppresses guidance, not the feature — the queue verbs stay registered and every one of them keeps working, so refusing or silently ignoring a named invocation is a defect, not the intended behavior.
182For detailed orchestration: Read workflows/gtd.md
183 
184### fix - Auto-Fix Errors
185 
186Purpose: Autonomously detect and fix LSP errors, linting issues, and type errors.
187Agents: manager-develop (cycle_type=autofix), Agent(general-purpose) with domain whitelist (fixes)
188Skills: moai-workflow-ddd (per delegation.yaml) + domain moai-ref-* injected per mission
189Flags: --dry, --sequential, --level N, --resume, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags)
190For detailed orchestration: Read workflows/fix.md
191 
192### loop - Iterative Auto-Fix
193 
194Purpose: Repeatedly fix issues until completion conditions are satisfied or max iterations reached.
195Agents: manager-develop (cycle_type=autofix), Agent(general-purpose) with domain whitelist
196Skills: moai-workflow-loop (per delegation.yaml) + domain moai-ref-* injected per mission
197Flags: --max N, --auto-fix, --seq
198For detailed orchestration: Read workflows/loop.md
199 
200### mx - MX Tag Scan and Annotation
201 
202Purpose: Scan codebase and add @MX code-level annotations for AI agent context.
203Agents: Explore (scan), Agent(general-purpose) with backend scope (annotation)
204Flags: --all, --dry, --priority P1-P4, --force, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags)
205For detailed orchestration: Read workflows/mx.md
206 
207### review - Code Review
208 
209Purpose: Multi-perspective code review with security, performance, quality, and UX analysis.
210Agents: sync-auditor (review), Agent(general-purpose) with security scope
211Skills: moai-foundation-quality, moai-ref-owasp-checklist (per delegation.yaml; per-perspective ref skills injected per lens)
212Flags: --staged, --branch, --security, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags)
213For detailed orchestration: Read workflows/review.md
214 
215### clean - Dead Code Removal
216 
217Purpose: Identify and safely remove unused code with test verification.
218Agents: manager-develop, Agent(general-purpose) with refactoring scope
219Skills: moai-workflow-ddd (per delegation.yaml)
220Flags: --dry, --safe-only, --file PATH
221For detailed orchestration: Read workflows/clean.md
222 
223### codemaps - Architecture Documentation
224 
225Purpose: Scan codebase and generate architecture documentation.
226Agents: Explore, manager-docs
227Flags: --force, --area AREA
228For detailed orchestration: Read workflows/codemaps.md
229 
230### (default) - MoAI Autonomous Workflow
231 
232Purpose: Full autonomous research -> plan -> annotate -> run -> sync pipeline.
233Phases: Parallel Exploration (research.md) -> SPEC Generation -> Annotation Cycle -> Implementation -> Sync
234Agents: Explore, manager-spec, plan-auditor (quality gate), manager-develop, manager-docs, manager-git, sync-auditor (quality gate)
235Skills: moai-workflow-spec, moai-workflow-tdd (per delegation.yaml) + domain moai-ref-* injected per mission
236Flags: --loop, --max N, --branch, --pr, --resume SPEC-XXX, --team (experimental — Agent Teams re-allowed; see Execution Mode Flags), --solo, --issue (opt-in; default skips GitHub Issue creation per the late-branch opt-in policy)
237For detailed orchestration: Read workflows/moai.md
238 
239### project - Project Documentation
240 
241Purpose: Generate project documentation by analyzing the existing codebase.
242Agents: Explore, manager-docs, Agent(general-purpose) with devops scope (optional)
243Skills: moai-workflow-project (per delegation.yaml)
244Output: product.md, structure.md, tech.md in .moai/project/
245For detailed orchestration: Read workflows/project.md
246 
247### feedback - GitHub Issue Creation
248 
249Purpose: Collect user feedback and create GitHub issues.
250Agents: orchestrator-direct (records feedback via gh CLI)
251For detailed orchestration: Read workflows/feedback.md
252 
253### harness - Harness Lifecycle + Natural-Language Build (argument-branching)
254 
255This single `harness` subcommand dispatches to ONE of two workflows based on the FIRST token of `$ARGUMENTS` (argument-based routing — no second command is introduced). Apply the routing rule before any workflow-specific logic:
256 
257- **Reserved verb** (`status` / `apply` / `rollback` / `disable`) → route to the existing **harness learning lifecycle** workflow (Branch A below). This path is unchanged.
258- **Reserved verb** (`list` / `edit` / `remove` / `doctor`) → route to the **harness-v4 lifecycle** handler (Branch A.1 below). These enumerate / edit / atomically-remove harness-v4 entries and run the reference-integrity smoke gate (`doctor`) via the `moai harness <verb>` Go binary subcommand.
259- **Anything else** (a natural-language harness-creation request, e.g. "build a harness for CLI template development") → route to the **harness build entry** workflow (Branch B below).
260 
261#### Branch A — harness learning lifecycle (reserved verbs: status / apply / rollback / disable)
262 
263Purpose: Surface the harness learning subsystem (observer, 4-tier proposal ladder, 5-layer safety pipeline) to the user via the slash command path. The lifecycle verbs (status / apply / rollback / disable) dispatch through the unified `moai harness` Go-binary Cobra subcommand tree, which performs the file-system operations. Tier-4 application is gated by orchestrator-issued AskUserQuestion.
264Skills: moai-harness-learner (Tier-4 surfacing companion). Project-specific harness generation is handled by the v4 Builder (`builder-harness` agent, Branch B).
265Verbs: status (tier distribution + telemetry) | apply (next Tier-4 proposal → AskUserQuestion → 5-layer pipeline → snapshot + write) | rollback &lt;YYYY-MM-DD&gt; (restore snapshot) | disable (set learning.enabled: false)
266Artifacts: `.moai/harness/usage-log.jsonl`, `.moai/harness/proposals/`, `.moai/harness/learning-history/snapshots/`, `.moai/harness/learning-history/applied/`, `.moai/harness/learning-history/frozen-guard-violations.jsonl`
267Authoritative SPEC: the harness foundation policy (supersedes V3R3-HARNESS-001, V3R3-HARNESS-LEARNING-001, V3R3-PROJECT-HARNESS-001)
268For detailed orchestration: Read workflows/harness.md
269 
270#### Branch A.1 — harness-v4 lifecycle (reserved verbs: list / edit / remove / doctor)
271 
272Purpose: Manage harness-v4 entries — enumerate built harnesses, locate their manifest + specialist files for editing, atomically remove a harness with all its artifacts, or run the reference-integrity smoke gate. The four verbs dispatch to the `moai harness <verb>` Go binary subcommand which performs the filesystem work (scan `.claude/commands/harness/*.md` joined with `manifest.json`; atomic remove with fail-closed orphan prevention; doctor cross-references manifest/specialist/skill file existence).
273Verbs: list (enumerate all harnesses: name + domain + entry command, plus the declared schedule — interval + mechanism — when the manifest declares one; schedule-less harnesses render identically to the pre-schedule baseline) | edit &lt;name&gt; (show manifest + specialist + skill paths for editing — manifest is the SSOT) | remove &lt;name&gt; (atomic removal of command + workflow + specialists + skills + manifest; fail-closed if any artifact is missing; when the manifest declared a schedule, prints an unregister notice naming the declared mechanism — CronDelete for cron, session-scoped loop cancellation for loop — computed from the manifest before deletion) | doctor (reference-integrity smoke gate: verifies every built harness's manifest/specialist/skill files exist and cross-reference correctly; a schema-invalid schedule declaration is an ERROR-severity finding)
274CLI: `moai harness list [--json]`, `moai harness edit <name> [--json]`, `moai harness remove <name>`, `moai harness doctor` (all support `--project-root`)
275Artifacts: `.claude/commands/harness/<name>.md` (thin-wrapper command), `.claude/commands/harness/<name>/manifest.json` (SSOT), `.claude/workflows/hns-<name>-run.js` (Runner), `.claude/agents/harness/hns-<name>*-specialist.md` (specialists), `.claude/skills/hns-<name>*/` (companion skills)
276Namespace: `.claude/commands/harness/`, `.claude/workflows/hns-*.js`, `.claude/agents/harness/`, and `.claude/skills/hns-*/` are USER-OWNED — `moai update` preserves them (backup if needed, never overwrites). Legacy generations with the `harness-` or `my-harness-` prefix are equally preserved (recognition-based backward compatibility); the Builder emits `hns-` names only.
277 
278#### Branch B — harness build entry (natural-language request)
279 
280Purpose: Turn a natural-language harness-creation request into a concrete harness via Context-First Discovery (extract domain / goal / constraints / scope), harness `<name>` derivation (the name is derived from the request — NOT statically supplied by the user), explicit orchestrator-issued approval, then transition into the orchestrator-direct Builder (4 signal-driven phases: ANALYZE / PLAN / GENERATE / ACTIVATE). The orchestrator MUST conduct AskUserQuestion Socratic rounds (max 4 questions per round) when intent clarity is below 100%.
281Agent: builder-harness (v4 Builder — project-specific harness generation)
282Builder: orchestrator-direct processing (NOT a dynamic-workflow script) — the entry's Phases 0-3 hand off to `workflows/harness-builder.md` for the 4-phase creation logic. The orchestrator holds the PLAN→GENERATE AskUserQuestion approval gate directly; that gate round also carries the recurrence question (optional manifest `schedule`, discovery-only scheduled runs), and ACTIVATE registers a declared schedule after the smoke gate. A request referencing an EXISTING harness together with scheduling intent routes to the entry workflow's Schedule Retrofit branch (evaluated before name-collision handling) instead of the creation pipeline.
283For detailed orchestration: Read workflows/harness-build-entry.md
284 
285---
286 
287## Execution Directive
288 
289When this skill is activated, execute the following steps in order:
290 
291Step 1 - Parse Arguments:
292Extract subcommand keywords and flags from the Raw User Input. Recognized global flags: --resume [ID], --seq, --team, --solo. Also detect `ultrathink` keyword in the input text.
293 
294**CRITICAL: Deep analysis mode:**
295- `ultrathink` keyword detected → Activate Claude's native extended reasoning (xhigh effort mode). This is native Claude behavior with no MCP dependency.
296 
297Step 1.5 - Flag-Subcommand Compatibility Validation:
298[HARD] After parsing the subcommand and flags (Step 1), validate flag-subcommand compatibility BEFORE routing. If a forbidden combination is detected, STOP all further processing and output an error in the user's conversation_language. Do NOT proceed to Step 2.
299 
300Forbidden flag-subcommand combinations:
301 
302| Flag | Allowed subcommands | Forbidden subcommands |
303|------|---------------------|------------------------|
304| `--branch` | `plan`, default (autonomous) | `run`, `sync` |
305 
306Rationale: `--branch` creates the feature branch at SPEC initialization, so `/moai run` and `/moai sync` MUST operate on the branch `plan` already established — re-creating it mid-lifecycle corrupts the SPEC lifecycle and is rejected at the router level.
307 
308The retired `--worktree` flag is handled separately: a request carrying it is not a forbidden-combination error but a retired flag. Tell the user that plan no longer creates a workspace, and that entering one first is the replacement.
309 
310Error message template (Korean conversation_language; substitute the actual flag and subcommand):
311```
312에러: --branch 플래그는 /moai plan 전용입니다.
313/moai run 과 /moai sync 는 plan 단계에서 만든 브랜치를 그대로 씁니다.
314 
315올바른 사용법:
316 /moai plan SPEC-XXX --branch (브랜치 생성)
317 /moai run SPEC-XXX (기존 브랜치 재사용)
318 /moai sync SPEC-XXX (기존 브랜치 재사용)
319 
320--branch 플래그를 뺀 형태로 다시 실행하세요.
321```
322 
323Retired-flag message (`--worktree`):
324```
325안내: --worktree 플래그는 폐기됐습니다. plan 은 더 이상 작업 공간을 만들지 않습니다.
326 
327격리된 공간에서 작업하려면 먼저 들어간 뒤 plan 을 실행하세요:
328 moai cc -w <이름> (그 자리에서 진입)
329 moai cc -w <이름> --spawn (새 Claude 세션을 tmux 창으로 열고 현재 세션 유지)
330 /moai plan "<설명>"
331```
332 
333For English (`en` conversation_language), translate the message; the structure remains identical.
334 
335Step 2 - Route to Workflow:
336Apply the Intent Router (Priority 1 through Priority 4) to determine the target workflow. If ambiguous, use AskUserQuestion to clarify with the user.
337 
338Step 2.2 - Record Routing Decision:
339Immediately after routing resolves (Step 2), record the routing decision to the append-only routing-ledger (`.moai/state/routing-ledger.jsonl`) so that auto-invocation is observable. Run:
340 
341```
342echo "<raw request text>" | moai harness ledger record --subcommand <matched> --mode <phase-4-mode> --tier <tier> --level <harness-level> --session <session-id>
343```
344 
345The request text is piped via stdin and only a privacy-preserving digest is stored, never verbatim user text (policy source: § Routing Observation Ledger above). This step is opt-in and fail-open: if the `moai` CLI is absent from PATH or the command exits non-zero, log nothing and continue — it NEVER blocks routing, never gates the workflow, and never triggers a retry loop. An un-recorded dispatch is an observation gap, not an error.
346 
347Step 2.5 - Project Documentation Check:
348Before executing plan, run, sync, fix, loop, or default workflows, verify project documentation exists by checking for `.moai/project/product.md`. If product.md does NOT exist, use AskUserQuestion to ask the user (in their conversation_language):
349 
350Question: Project documentation not found. Would you like to create it first?
351Options:
352- Create project documentation (Recommended): Generates product.md, structure.md, tech.md through a guided interview. This helps MoAI understand your project context for better results in all subsequent workflows.
353- Skip and continue: Proceed without project documentation. MoAI will have less context about your project.
354 
355This check does NOT apply to: project, feedback subcommands.
356 
357[HARD] Beginner-Friendly Option Design:
358All AskUserQuestion calls throughout MoAI workflows MUST follow these rules:
359- The first option MUST always be the recommended choice, clearly marked with "(Recommended)" suffix — this is the `push`-mode branch; while `interview.recommendation_mode` is `pull` the suffix is withheld from every option and no option carries a preference claim (`.claude/rules/moai/core/askuser-protocol.md` § Recommendation Placement Principles)
360- Every option MUST include a detailed description explaining what it does and its implications
361 
362Step 2.8 - Requirement Analysis & Completion Condition:
363Before loading the workflow body (Step 3), produce a requirement-analysis record for the routed request:
364 
3651. **Requirement summary** (1-3 sentences): what the user asked for, restated in the orchestrator's own words.
3662. **Completion condition**: the end state that means "done". Where the condition is machine-verifiable (test exit code, lint-clean state, grep count, bounded turn count), express it in `/moai goal`-compatible form per `.claude/rules/moai/workflow/goal-directive.md` (one measurable end state + a stated check + a bound clause). Do NOT invent a parallel evaluator: arm the condition via `/moai goal` when the goal engine is available (hooks enabled — the evaluator is the `stop-goal` Stop hook); otherwise the orchestrator evaluates the identical condition text per-turn (graceful degradation — no new machinery).
3673. **Pipeline contract**: `full-pipeline` (default natural-language route — run-phase completion auto-chains into sync) or `single-phase` (explicit `run`/`sync` subcommand — chaining is offered as the "(Recommended)" next-step option, never fired silently).
3684. **Orchestration-shape pre-signal**: an early input to the Phase 4 4-mode selection (`orchestration-mode-selection.md` §A) — noted here, decided at Phase 4.
369 
370Trivial-scope exemption: skip this step entirely for `feedback`, `gate`, `codemaps`, `sync` status mode, and any Stage-1-Clarify exception per `askuser-protocol.md` § Ambiguity Triggers and Exceptions.
371Socratic-first ordering: while intent clarity is below 100%, run the Socratic interview (per `askuser-protocol.md`) BEFORE deriving the completion condition — the condition encodes drained intent, never a guess.
372A derived completion condition NEVER authorizes autonomous run-phase entry — Implementation Kickoff Approval remains mandatory at the plan→run boundary.
373 
374Step 3 - Load Workflow Details:
375Read `workflows/<name>.md` for the target subcommand. (Agent Teams is experimental and re-allowed: a `--team` flag selects the Agent Teams layer, subject to the constraints in `.claude/rules/moai/workflow/orchestration-mode-selection.md` §C.1. Only the static layer stays retired, so there is no separate `team/<name>.md` workflow file — the same `workflows/<name>.md` is read either way. Historical: the retired era emitted `MODE_TEAM_UNAVAILABLE` and fell back to sub-agent mode; the sentinel is retained as documented history.)
376 
377Step 4 - Read Configuration:
378Load relevant configuration from the .moai/config/sections/*.yaml section files as needed.
379 
380Step 5 - Initialize Task Tracking:
381Use TaskCreate to register discovered work items with pending status.
382 
383Step 6 - Execute Workflow Phases:
384Follow the workflow-specific phase instructions. Delegate all implementation to appropriate agents via Agent(). Collect user approvals at designated checkpoints via AskUserQuestion. Before each implementation/review Agent() spawn, apply `.claude/rules/moai/workflow/skill-routing.md` §1: inject 0-3 `At start, invoke Skill("<name>") for <reason>` lines per the delegation map (`.moai/config/sections/delegation.yaml`).
385 
386Step 7 - Track Progress:
387Update task status using TaskUpdate as work progresses (pending to in_progress to completed).
388 
389Step 8 - Present Results:
390Display results to the user in their conversation_language using Markdown format.
391 
392Step 9 - Declare Completion:
393When all workflow phases complete successfully, state that the workflow is complete in the Completion Report (banner / prose) so the result is unambiguous.
394 
395Step 10 - Guide Next Steps:
396Use AskUserQuestion to present the user with logical next actions based on the completed workflow.
397 
398---
399 
400Version: 2.8.0
401 

Discussion

Alternatives