Agent skill
moonshot-orchestrator
PM workflow orchestrator. Analyzes user requests and automatically runs the optimal agent chain.
Install this agent skill to your Project
npx add-skill https://github.com/majiayu000/claude-skill-registry/tree/main/skills/data/moonshot-orchestrator
SKILL.md
PM Orchestrator
Role
Runs PM analysis skills in sequence and builds the final agent chain.
Inputs
Automatically collect:
userMessage: user requestgitBranch: current branchgitStatus: Git status (clean/dirty)recentCommits: recent commit listopenFiles: open file list
Workflow
1. Initialize analysisContext
schemaVersion: "1.0"
request:
userMessage: "{userMessage}"
taskType: unknown
keywords: []
repo:
gitBranch: "{gitBranch}"
gitStatus: "{gitStatus}"
openFiles: []
changedFiles: []
signals:
hasContextMd: false
hasPendingQuestions: false
requirementsClear: false
implementationReady: false
implementationComplete: false
hasMockImplementation: false
apiSpecConfirmed: false
reactProject: false # React/Next.js project detected
estimates:
estimatedFiles: 0
estimatedLines: 0
estimatedTime: unknown
phase: unknown
complexity: unknown
missingInfo: []
decisions:
recommendedAgents: []
skillChain: []
parallelGroups: []
artifacts:
tasksRoot: "{PROJECT.md:documentPaths.tasksRoot}" # default: .claude/docs/tasks
contextDocPath: "{tasksRoot}/{feature-name}/context.md"
verificationScript: .claude/agents/verification/verify-changes.sh
tokenBudget:
specSummaryTrigger: 2000 # words
splitTrigger: 5 # independent features
contextMaxTokens: 8000
warningThreshold: 0.8
projectMemory:
projectId: null
boundaryStatus: "not_checked" # not_checked|ok|violation|needs_approval|not_initialized
boundary:
violations: []
needsApproval: []
reminders: []
relatedConventions: []
lastChecked: null
notes: []
2. Run PM skills sequentially
2.0 Large specification handling
If the initial task specification (request.userMessage) is very long, it can cause the final plan or context document to exceed the output token limits. To prevent this, follow .claude/docs/guidelines/document-memory-policy.md:
2.0.1 Check specification size
- Count words in
userMessage - If >
tokenBudget.specSummaryTrigger(2000 words): trigger summarization - If independent features >
tokenBudget.splitTrigger(5): trigger task splitting
2.0.2 Summarize the specification
- Save the full original specification to
{tasksRoot}/{feature-name}/archives/specification-full.md - Extract only:
- Key requirements (max 5 items)
- Constraints
- Acceptance criteria
- Write summarized version to
{tasksRoot}/{feature-name}/specification.md - Reference the original in the summary
2.0.3 Split into sub-tasks When a single specification covers multiple independent areas:
- Create
subtasks/directory - For each sub-task, create
subtasks/subtask-NN/with its owncontext.md - Each sub-task runs this workflow independently with its own
analysisContext - Master
context.mdcontains only:- Sub-task list with links
- Integration points
- Shared constraints
2.0.4 Limit context.md size
- Only include summarized specification
- Keep current plan only (no history)
- Archive previous versions per document-memory-policy.md
2.0.5 Load Project Memory (Fork)
CRITICAL: Run project-memory-agent as a forked subagent to prevent context pollution.
-
Determine Project ID:
- Priority:
package.jsonname → directory name → git remote
- Priority:
-
Execute fork:
Task tool: project-memory-agent (subagent_type: general-purpose) Input: { projectId, changedFiles, taskType, userRequest } -
Receive summarized context: The forked agent searches project memory (
[ProjectID]::*from global Memory) and returns only:yamlprojectMemoryContext: projectId: "my-app" loaded: true boundaries: alwaysDo: [...] askFirst: [...] neverDo: [...] relevantRules: [...] -
Merge into analysisContext:
yamlprojectMemory: ...projectMemoryContext lastChecked: "{timestamp}" boundaryStatus: "ok" -
Handle errors:
- No memory found:
boundaryStatus: "not_initialized", proceed - MCP unavailable:
boundaryStatus: "not_checked", proceed with warning
- No memory found:
2.1 Task classification
Run /moonshot-classify-task using the Skill tool.
- Merge returned patch into analysisContext
- Example: add
request.taskType,request.keywords,notes
2.2 Complexity evaluation
Run /moonshot-evaluate-complexity using the Skill tool.
- Merge returned patch into analysisContext
- Example: update
complexity,estimates.*
2.3 Uncertainty detection
Run /moonshot-detect-uncertainty using the Skill tool.
- Merge returned patch into analysisContext
- Check
missingInfoarray
2.4 Uncertainty handling
If missingInfo is not empty:
- Create questions using the
AskUserQuestiontool- Convert each item in
missingInfointo a question - Prioritize HIGH items
- Convert each item in
- Wait for user answers
- Apply answers to analysisContext:
- API answers ->
signals.apiSpecConfirmed = true - Design spec answers -> store design file paths
- Other answers -> record in
notes
- API answers ->
- Set
signals.hasPendingQuestions = false - Re-run
/moonshot-detect-uncertaintyif needed
If missingInfo is empty, proceed.
2.5 Sequence decision
Run /moonshot-decide-sequence using the Skill tool.
- Merge returned patch into analysisContext
- Set
phase,decisions.skillChain,decisions.parallelGroups
2.6 Plan size guard (when iterating plan/review)
During plan→review→revise loops the context.md file can grow rapidly. Follow .claude/docs/guidelines/document-memory-policy.md:
-
Before each plan update: Check current token usage
-
At 80% threshold: Log warning to
notes, consider summarizing -
At 100% threshold:
- Archive current version to
archives/context-v{n}.md - Replace with summarized version
- Update archive index in context.md
- Archive current version to
-
Review output handling:
- Full review →
archives/review-v{n}.md - Summary only → append to
context.md
- Full review →
-
Token limit approaching: Further break down into smaller sub-plans
Archive Index Format (at bottom of context.md):
## 아카이브 참조
| 버전 | 파일 | 핵심 내용 | 생성일 |
|------|------|----------|--------|
| v1 | [context-v1.md](archives/context-v1.md) | 초기 설계 | YYYY-MM-DD |
3. Execute the agent chain
Run decisions.skillChain in order:
Allowed steps:
pre-flight-check: pre-flight skillproject-memory-agent: project memory loading agent (Task tool, fork)requirements-analyzer: requirements analysis agent (Task tool)context-builder: context-building agent (Task tool)codex-validate-plan: Codex plan validation skillimplementation-runner: implementation agent (Task tool)completion-verifier: test-based completion verification skillcodex-review-code: Codex code review skillproject-memory-reviewer: project memory rule/spec violation check agent (Task tool, fork)vercel-react-best-practices: React/Next.js performance optimization review skillsecurity-reviewer: security vulnerability review skillbuild-error-resolver: build/compile error resolution skillverify-changes.sh: verification script (Bash tool)efficiency-tracker: efficiency tracking skillsession-logger: session logging skill
Execution rules:
- Run steps sequentially
- Use
Skilltool for skill steps - Use
Tasktool for agent steps (map subagent_type) - Use
Bashtool for scripts - If a parallel group exists, parallelize only within that group
- If an undefined step appears, ask the user and stop
- All agents/skills must follow
.claude/docs/guidelines/document-memory-policy.md
Fork-based agents:
project-memory-agentandproject-memory-reviewerrun as forked subagents- They load/check project memory ([ProjectID]::* from global Memory) in isolation
- Only summarized context/violations are returned to main session
- This prevents context pollution from raw memory data
Skill-specific execution:
For vercel-react-best-practices:
- Triggered when
signals.reactProject = true - Execute using:
Skill toolwithskill: "vercel-react-best-practices" - The skill will analyze changed files for React/Next.js performance issues
- Merge findings into
analysisContext.notes
Agent mapping:
project-memory-agent->subagent_type: "general-purpose"+ prompt (fork, runs before 2.1)requirements-analyzer->subagent_type: "general-purpose"+ promptcontext-builder->subagent_type: "context-builder"implementation-runner->subagent_type: "implementation-agent"project-memory-reviewer->subagent_type: "general-purpose"+ prompt (fork, runs after codex-review-code)
3.1 Dynamic Skill Injection
During skillChain execution, dynamically inject skills when signals detected:
| Signal | Condition | Inject Skill | Insert Position |
|---|---|---|---|
buildFailed |
Bash exit code ≠ 0 | build-error-resolver | Before retry current step |
securityConcern |
Changed files contain .env, auth, password, token |
security-reviewer | After codex-review-code |
coverageLow |
Coverage < 80% from codex-test-integration output | (request additional tests) | After codex-test-integration |
reactProject |
.tsx/.jsx files or React keywords |
(codex-review-code extended) | Within codex-review-code |
Signal Detection:
buildFailed:
trigger: Bash tool returns non-zero exit code
action: Insert build-error-resolver, then retry failed step (max 2)
securityConcern:
trigger: |
changedFiles.any(f =>
f.includes('.env') ||
f.includes('auth') ||
f.includes('password') ||
f.includes('token') ||
f.includes('secret')
)
action: Add security-reviewer after codex-review-code
coverageLow:
trigger: codex-test-integration reports coverage < 80%
action: Log warning, request additional tests from user
reactProject:
trigger: |
changedFiles.any(f =>
f.endsWith('.tsx') || f.endsWith('.jsx') ||
f.includes('/pages/') || f.includes('/app/') ||
f.includes('/components/')
) ||
request.keywords.any(k =>
['react', 'next', 'next.js', 'nextjs', 'jsx', 'tsx', 'useState', 'useEffect'].includes(k.toLowerCase())
)
action: |
- Set signals.reactProject = true
- Inject vercel-react-best-practices after codex-review-code in skillChain
- When executing: Use Skill tool with skill="vercel-react-best-practices"
3.2 Project Memory Review (Fork)
CRITICAL: After codex-review-code, run project-memory-reviewer as a forked subagent.
-
Execute fork:
Task tool: project-memory-reviewer (subagent_type: general-purpose) Input: { projectId, changedFiles, projectMemoryContext, diff } -
Receive violation report:
yamlmemoryReviewResult: status: "passed" | "failed" | "needs_approval" violations: [...] # NeverDo violations needsApproval: [...] # AskFirst items warnings: [...] # Convention/spec warnings reminders: [...] # AlwaysDo reminders -
Handle result:
status: "failed": HALT execution, report violations to userstatus: "needs_approval": Ask user for approval before proceedingstatus: "passed": Proceed to next step
-
Merge into analysisContext:
yamlprojectMemory: ...existing reviewResult: { ...memoryReviewResult }
3.3 Completion Verification Loop
After implementation-runner completes:
- Call
completion-verifier - If
allPassed: true:- Mark
implementationComplete: true - Proceed to next step (codex-review-code)
- Mark
- If
allPassed: false:- Identify failed phase (Unit → Phase 1, Integration → Phase 2)
- If retryCount < 2:
- Go back to failed Phase (not test writing)
- Pass
failedTeststo implementation-agent - Implementation-agent fixes code only
- Increment retryCount
- Else:
- Ask user for intervention
- Provide failed test details
Signals Update:
signals:
implementationComplete: false # existing
# New fields
acceptanceTestsGenerated: false
testsPassed: 0
testsFailed: 0
completionRetryCount: 0
currentPhase: "Phase 0" # 0=Tests, 1=Mock, 2=API, 3=Verify
4. Record results
Save final analysisContext to .claude/docs/moonshot-analysis.yaml.
Output format
Summary for the user (Markdown)
## PM Analysis Result
**Task type**: {taskType}
**Complexity**: {complexity}
**Phase**: {phase}
### Execution chain
1. {step1}
2. {step2}
...
### Estimates
- File count: {estimatedFiles}
- Line count: {estimatedLines}
- Estimated time: {estimatedTime}
{Add questions section if missingInfo exists}
Error handling
- Skill execution failure: record error logs in notes and report to the user
- Undefined step: ask the user for confirmation
- Question loop: limit to 3 rounds, then proceed with defaults
- Token limit warning: archive and summarize before continuing
Contract
- This skill orchestrates other PM skills and does not analyze directly
- All analysis logic is delegated to individual PM skills
- Patch merging is a shallow object merge (no deep merge)
- User questions use the AskUserQuestion tool
- Document memory policy: Follow
.claude/docs/guidelines/document-memory-policy.md
References
.claude/docs/guidelines/document-memory-policy.md
Didn't find tool you were looking for?