@graypark/loophaus 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/LICENSE +21 -0
  3. package/README.ko.md +358 -0
  4. package/README.md +282 -0
  5. package/bin/install.mjs +10 -0
  6. package/bin/loophaus.mjs +192 -0
  7. package/bin/uninstall.mjs +233 -0
  8. package/codex/commands/cancel-ralph.md +30 -0
  9. package/codex/commands/ralph-loop.md +73 -0
  10. package/commands/cancel-ralph.md +23 -0
  11. package/commands/help.md +96 -0
  12. package/commands/loop-plan.md +55 -0
  13. package/commands/loop-pulse.md +38 -0
  14. package/commands/loop-stop.md +29 -0
  15. package/commands/loop.md +17 -0
  16. package/commands/ralph-loop.md +18 -0
  17. package/core/engine.mjs +84 -0
  18. package/core/event-logger.mjs +37 -0
  19. package/core/loop.schema.json +29 -0
  20. package/hooks/hooks.json +15 -0
  21. package/hooks/stop-hook.mjs +79 -0
  22. package/lib/paths.mjs +91 -0
  23. package/lib/state.mjs +46 -0
  24. package/lib/stop-hook-core.mjs +162 -0
  25. package/package.json +57 -0
  26. package/platforms/claude-code/adapter.mjs +20 -0
  27. package/platforms/claude-code/installer.mjs +165 -0
  28. package/platforms/codex-cli/adapter.mjs +20 -0
  29. package/platforms/codex-cli/installer.mjs +131 -0
  30. package/platforms/kiro-cli/adapter.mjs +21 -0
  31. package/platforms/kiro-cli/installer.mjs +115 -0
  32. package/scripts/setup-ralph-loop.sh +145 -0
  33. package/skills/ralph-claude-cancel/SKILL.md +23 -0
  34. package/skills/ralph-claude-interview/SKILL.md +178 -0
  35. package/skills/ralph-claude-loop/SKILL.md +101 -0
  36. package/skills/ralph-claude-orchestrator/SKILL.md +129 -0
  37. package/skills/ralph-interview/SKILL.md +275 -0
  38. package/skills/ralph-orchestrator/SKILL.md +254 -0
  39. package/store/state-store.mjs +80 -0
@@ -0,0 +1,275 @@
1
+ ---
2
+ name: ralph-interview
3
+ description: "Interactive interview that generates optimized loop commands with PRD-based phase tracking. Compatible with ralph-skills prd.json format."
4
+ ---
5
+
6
+ # Loop Interview — Command Generator
7
+
8
+ You are an expert at crafting loop commands for the Loop plugin.
9
+ When the user describes a task, conduct a brief interview to gather missing context, then generate a PRD, activate the loop, and start working immediately.
10
+
11
+ ## Core Principles
12
+
13
+ - **PRD-driven**: All phases and items live in prd.json. The loop reads it each iteration.
14
+ - **Progress tracking**: progress.txt tracks what is done. Each iteration reads it to decide what is next.
15
+ - **One story per iteration**: Each loop iteration implements ONE user story, commits, and updates progress.
16
+ - **Self-correcting**: Every prompt embeds "modify, verify, retry on failure" cycles.
17
+ - **Escape hatches required**: Always specify what to do when stuck after N retries.
18
+ - **Objective completion criteria only**: No subjective criteria. Use test passes, linter clears, etc.
19
+ - **Parallel when possible**: Use loop orchestrator patterns for independent work streams.
20
+
21
+ ## Interview Process
22
+
23
+ When the user provides a task description, ask **concise questions** for any missing items below.
24
+ Skip items already covered. Bundle questions — max 3-5 per round, one round only if possible.
25
+
26
+ ### Required Information
27
+
28
+ | Category | What to confirm |
29
+ | ------------------------- | ------------------------------------------------------------------------------------ |
30
+ | **Scope** | Single feature? Multi-file? Full refactor? |
31
+ | **Success criteria** | What counts as "done"? (tests pass, build succeeds, spec checklist, etc.) |
32
+ | **Verification commands** | Commands for automated checks (`npx tsc --noEmit`, `npm test`, `npm run lint`, etc.) |
33
+ | **References** | Existing code, files, or patterns to follow? |
34
+ | **Spec file** | Is there a spec document? Path? |
35
+ | **Priority** | P1/P2 or other priority tiers? |
36
+ | **Constraints** | Must not break existing tests? Library restrictions? |
37
+ | **When stuck** | User's preferred fallback (document it? skip? suggest alternative?) |
38
+ | **Commit strategy** | Per-item commits? Bulk? Commit message convention? |
39
+ | **Parallelism potential** | Multiple services? Independent file groups? Broad search needed? |
40
+
41
+ ## Phase Design
42
+
43
+ ### When to Split into Phases
44
+
45
+ - **Research needed first** -> Phase 1: Analysis, Phase 2: Implementation
46
+ - **More than 8 items** -> Split by nature (e.g., P1/P2, frontend/backend)
47
+ - **Dependencies exist** -> Prerequisite work in a prior Phase
48
+ - **5 or fewer simple items** -> Single Phase is fine
49
+
50
+ ### When to Use Subagents (via loop orchestrator)
51
+
52
+ Evaluate the task against the loop orchestrator decision matrix:
53
+
54
+ | Factor | Score |
55
+ | ------------------------------ | ----- |
56
+ | Files span 3+ directories | +2 |
57
+ | Items are independent | +2 |
58
+ | Need full context to decide | -2 |
59
+ | Order matters | -2 |
60
+ | 10+ similar items | +1 |
61
+ | Needs cross-file understanding | -1 |
62
+ | Multiple services/repos | +3 |
63
+
64
+ - **Score >= 3**: Recommend parallel subagents within the loop prompt
65
+ - **Score 0-2**: Sequential loop, optional scout phase
66
+ - **Score < 0**: Single sequential Loop
67
+
68
+ ### Recommended max-iterations
69
+
70
+ | Task type | Iterations |
71
+ | ---------------------------------------------- | ---------- |
72
+ | Research only (file reads, pattern extraction) | 3-5 |
73
+ | Simple fixes, 1-3 items | 5-10 |
74
+ | Medium scope, 4-7 items | 10-20 |
75
+ | Large scope, 8+ items | 20-30 |
76
+ | TDD-based feature implementation | 15-30 |
77
+ | Full refactor / migration | 30-50 |
78
+
79
+ **Rule of thumb:** `story_count x 2 + 5` as baseline.
80
+
81
+ ## PRD Format: prd.json (ralph-skills compatible)
82
+
83
+ Generate PRDs in the **prd.json** format used by ralph-skills. This ensures compatibility with `/ralph-skills:ralph` and `/ralph-skills:prd`.
84
+
85
+ ### prd.json
86
+
87
+ ```json
88
+ {
89
+ "project": "[Project Name]",
90
+ "description": "[Feature description]",
91
+ "userStories": [
92
+ {
93
+ "id": "US-001",
94
+ "title": "[Story title]",
95
+ "description": "As a [user], I want [feature] so that [benefit]",
96
+ "acceptanceCriteria": [
97
+ "Specific verifiable criterion",
98
+ "Another criterion",
99
+ "Typecheck passes"
100
+ ],
101
+ "priority": 1,
102
+ "passes": false,
103
+ "notes": ""
104
+ }
105
+ ]
106
+ }
107
+ ```
108
+
109
+ ### Story Sizing Rules
110
+
111
+ Each story MUST be completable in ONE iteration (one context window):
112
+
113
+ - **Right-sized**: Add a DB column, create one component, update one endpoint
114
+ - **Too big (split)**: "Build entire dashboard", "Add authentication", "Refactor API"
115
+ - **Rule of thumb**: If you cannot describe the change in 2-3 sentences, split it
116
+
117
+ ### Story Ordering
118
+
119
+ Stories execute in priority order. Dependencies first:
120
+
121
+ 1. Schema/database changes
122
+ 2. Backend logic / server actions
123
+ 3. UI components that use the backend
124
+ 4. Aggregation views / dashboards
125
+
126
+ ### Acceptance Criteria Rules
127
+
128
+ - MUST be verifiable, not vague
129
+ - Always include: `"Typecheck passes"` (or equivalent verification)
130
+ - For UI stories: add `"Verify in browser"` or equivalent
131
+ - Bad: "Works correctly", "Good UX"
132
+ - Good: "Button shows confirmation dialog before deleting", "Filter persists in URL params"
133
+
134
+ ### progress.txt
135
+
136
+ An append-only log file that tracks iteration history:
137
+
138
+ ```
139
+ ## Codebase Patterns
140
+ - [Reusable patterns discovered during iteration]
141
+
142
+ ## Discoveries
143
+ - [US-008] Added during US-003: Missing input validation for edge case X
144
+ - [US-009] Added during US-005: Need migration script for schema change
145
+
146
+ ---
147
+
148
+ ## [Date] - US-001
149
+ - What was implemented
150
+ - Files changed
151
+ - **Learnings for future iterations:**
152
+ - Patterns discovered
153
+ - Gotchas encountered
154
+ - **Discoveries:** (if any new stories were added)
155
+ - US-008: [reason] — found while implementing [specific part]
156
+ ---
157
+ ```
158
+
159
+ The `## Codebase Patterns` section at the top is read first by each iteration to avoid repeating mistakes.
160
+ The `## Discoveries` section tracks all dynamically added stories with rationale.
161
+
162
+ ## Compatibility with Existing Skills
163
+
164
+ ### ralph-skills:prd (marketplace)
165
+
166
+ - Our prd.json output uses the EXACT same format
167
+ - User can generate PRD with `/ralph-skills:prd`, then use our interview to generate the loop command
168
+ - Or use our interview to generate both PRD and loop command
169
+
170
+ ### ralph-skills:ralph (marketplace)
171
+
172
+ - Our loop prompt follows the same pattern as ralph-skills prompt.md
173
+ - Same prd.json format, same progress.txt format
174
+ - Same `passes: true/false` tracking, same commit convention
175
+ - Same `<promise>COMPLETE</promise>` completion signal
176
+
177
+ ### Official loop plugin (claude-plugins-official)
178
+
179
+ - If the official plugin is installed, this interview works with its stop hook
180
+ - PRD and progress files work with either stop hook
181
+
182
+ ## Rules
183
+
184
+ - **No subjective completion criteria**: Banned phrases: "works well", "looks clean", "properly done."
185
+ - **No prompt without verification**: At least one automated check is mandatory.
186
+ - **No missing escape hatch**: Every prompt MUST have a "When Stuck" section.
187
+ - **No oversized stories**: Each story must be completable in ONE iteration. Split if too big.
188
+ - **Always use prd.json format**: Ensures compatibility with ralph-skills ecosystem.
189
+ - **Default promise is COMPLETE**: Use `<promise>COMPLETE</promise>` to match ralph-skills convention.
190
+ - **Always overwrite**: Never ask before overwriting prd.json or progress.txt. Just write them.
191
+
192
+ ## Conversation Flow
193
+
194
+ ```
195
+ [User] -> /loop-plan "build X feature"
196
+ [Assistant] -> Interview questions (1 round, skip if context is sufficient)
197
+ [User] -> Answers
198
+ [Assistant] -> Shows PRD briefly, asks "Ready?"
199
+ [User] -> "y"
200
+ [Assistant] -> Writes files + activates loop + starts US-001 IN THE SAME RESPONSE
201
+ ```
202
+
203
+ ### Quick-Run
204
+
205
+ If the user includes "run immediately", "just do it", "run it", "바로 실행", "바로 시작", or "--run":
206
+ Skip the "Ready?" prompt. Go straight to activation after showing the PRD briefly.
207
+
208
+ ## Activation Sequence
209
+
210
+ When the user confirms (or quick-run), execute ALL of these steps in a SINGLE response. Do NOT stop between steps.
211
+
212
+ IMPORTANT: Always overwrite existing prd.json and progress.txt without asking. Do NOT check if they exist. Do NOT ask the user for confirmation before overwriting. Do NOT archive old files. Just write them.
213
+
214
+ ### Step 1: Write prd.json via Bash
215
+
216
+ ```bash
217
+ cat > prd.json << 'EOF'
218
+ { ... generated PRD ... }
219
+ EOF
220
+ ```
221
+
222
+ ### Step 2: Write progress.txt via Bash
223
+
224
+ ```bash
225
+ cat > progress.txt << 'EOF'
226
+ ## Codebase Patterns
227
+ (none yet)
228
+ EOF
229
+ ```
230
+
231
+ ### Step 3: Activate the stop hook via Bash
232
+
233
+ Write the loop state file that makes the stop hook intercept session exits:
234
+
235
+ ```bash
236
+ mkdir -p .loophaus
237
+ cat > .loophaus/state.json << 'EOF'
238
+ {
239
+ "active": true,
240
+ "prompt": "Read prd.json for task plan. Read progress.txt for status (Codebase Patterns first). Pick highest priority story where passes is false. Implement that ONE story. Run verification: <VERIFY_CMD>. On failure: fix and retry, max 3 times. On success: commit with feat: [Story ID] - [Title]. Update prd.json: set passes to true. DISCOVERY PHASE: Review what you just built — did you find hidden complexity, missing edge cases, new dependencies, or broken assumptions? If YES: add new stories to prd.json (next sequential ID, passes: false), log discovery in progress.txt under Discoveries section. If NO: just append learnings to progress.txt. If ALL stories (including new ones) pass: output <promise>COMPLETE</promise>. When stuck: set notes in prd.json, skip to next story.",
241
+ "completionPromise": "COMPLETE",
242
+ "maxIterations": <N>,
243
+ "currentIteration": 0,
244
+ "sessionId": ""
245
+ }
246
+ EOF
247
+ ```
248
+
249
+ Replace `<VERIFY_CMD>` with the actual verification command and `<N>` with the recommended max iterations.
250
+
251
+ ### Step 4: START WORKING ON US-001 IMMEDIATELY
252
+
253
+ This is the critical step. After writing files, you MUST begin actual work in the SAME response:
254
+
255
+ 1. Read the prd.json you just wrote
256
+ 2. Pick the first story (US-001)
257
+ 3. Implement it — write real code, make real changes
258
+ 4. Run the verification command
259
+ 5. Commit the changes
260
+ 6. Update prd.json (set passes: true)
261
+ 7. Append to progress.txt
262
+
263
+ Do NOT:
264
+
265
+ - Say "loop is now active" and stop
266
+ - Say "starting work on US-001" and stop
267
+ - Print a summary and wait for user input
268
+ - Ask if the user wants to proceed
269
+
270
+ DO:
271
+
272
+ - Actually write code
273
+ - Actually run tests
274
+ - Actually commit
275
+ - The stop hook will handle continuation to US-002 when you finish
@@ -0,0 +1,254 @@
1
+ ---
2
+ name: ralph-orchestrator
3
+ description: "Orchestration patterns for loop: subagent spawning, parallel exploration, and task decomposition strategies"
4
+ ---
5
+
6
+ # Loop Orchestrator — Multi-Agent Loop Patterns
7
+
8
+ You are an expert at designing optimal execution strategies for Loop tasks.
9
+ When asked to orchestrate a task, analyze its structure and recommend the best combination of sequential loops, parallel subagents, and phased execution.
10
+
11
+ ## Core Concept
12
+
13
+ Not every task should run in a single linear loop. Complex tasks benefit from:
14
+
15
+ - **Parallel exploration** — spawn subagents to search/analyze independently, then merge results
16
+ - **Divide and conquer** — split work by service/directory/concern with isolated agents
17
+ - **Pipeline stages** — sequential phases where each feeds into the next
18
+ - **Hybrid patterns** — combine parallel research with sequential implementation
19
+
20
+ ## When to Use Subagents
21
+
22
+ ### Use Subagents (Parallel) When:
23
+
24
+ | Signal | Example |
25
+ | --------------------------- | ---------------------------------------------------------- |
26
+ | **Broad codebase search** | "Find all API endpoints that lack auth checks" |
27
+ | **Independent file groups** | Frontend components + backend routes + database migrations |
28
+ | **Multi-service changes** | auth-service + api-gateway + frontend simultaneously |
29
+ | **Audit/review tasks** | Security audit + performance audit + accessibility audit |
30
+ | **Pattern extraction** | Scan 50+ files for inconsistent patterns |
31
+
32
+ ### Do NOT Use Subagents When:
33
+
34
+ | Signal | Reason |
35
+ | --------------------------- | ---------------------------------------------------- |
36
+ | **Sequential dependencies** | Step 2 needs Step 1's output |
37
+ | **Shared mutable state** | Multiple agents editing the same file = conflicts |
38
+ | **Small scope (< 5 files)** | Overhead outweighs benefit |
39
+ | **Context-heavy tasks** | Agent needs deep understanding of full codebase flow |
40
+
41
+ ## Orchestration Patterns
42
+
43
+ ### Pattern 1: Parallel Explore → Sequential Implement
44
+
45
+ Best for: Large codebases where you need to understand before you change.
46
+
47
+ ```
48
+ Phase 1 (Parallel Subagents):
49
+ ├── Agent A: Scan src/frontend/** for pattern X → report-frontend.md
50
+ ├── Agent B: Scan src/backend/** for pattern X → report-backend.md
51
+ └── Agent C: Scan src/shared/** for pattern X → report-shared.md
52
+
53
+ Phase 2 (Sequential Loop):
54
+ └── Loop: Read all reports → implement fixes in priority order
55
+ ```
56
+
57
+ **Prompt pattern for Phase 1:**
58
+
59
+ ```
60
+ ## Subagent Tasks (run in parallel)
61
+ Use the Agent tool to spawn these subagents simultaneously:
62
+
63
+ 1. Agent "frontend-scan": Search src/frontend/** for [pattern].
64
+ Write findings to .loophaus/reports/frontend-scan.md
65
+ 2. Agent "backend-scan": Search src/backend/** for [pattern].
66
+ Write findings to .loophaus/reports/backend-scan.md
67
+ 3. Agent "shared-scan": Search src/shared/** for [pattern].
68
+ Write findings to .loophaus/reports/shared-scan.md
69
+
70
+ After ALL agents complete, merge reports into .loophaus/reports/merged.md
71
+ with a unified priority list.
72
+ ```
73
+
74
+ ### Pattern 2: Divide by Ownership
75
+
76
+ Best for: Multi-service changes where files don't overlap.
77
+
78
+ ```
79
+ Phase 1 (Parallel Implementation):
80
+ ├── Agent "fe-dev": Modify src/frontend/** only → commit per item
81
+ ├── Agent "be-dev": Modify src/backend/** only → commit per item
82
+ └── Agent "auth-dev": Modify src/auth/** only → commit per item
83
+
84
+ Phase 2 (Integration Verification):
85
+ └── Loop: Run full test suite, fix any integration issues
86
+ ```
87
+
88
+ **Prompt pattern:**
89
+
90
+ ```
91
+ ## Parallel Work Streams
92
+ Spawn these agents with strict file ownership:
93
+
94
+ 1. Agent "fe-dev" (isolation: worktree):
95
+ - ONLY touch files in src/frontend/**
96
+ - Tasks: [frontend items]
97
+ - Commit each fix individually
98
+
99
+ 2. Agent "be-dev" (isolation: worktree):
100
+ - ONLY touch files in src/backend/**
101
+ - Tasks: [backend items]
102
+ - Commit each fix individually
103
+
104
+ After all agents complete, merge their branches and run integration tests.
105
+ ```
106
+
107
+ ### Pattern 3: Fan-Out / Fan-In Research
108
+
109
+ Best for: Tasks that need comprehensive analysis before any action.
110
+
111
+ ```
112
+ Fan-Out (Parallel):
113
+ ├── Agent 1: Analyze problem from angle A → findings-a.md
114
+ ├── Agent 2: Analyze problem from angle B → findings-b.md
115
+ └── Agent 3: Analyze problem from angle C → findings-c.md
116
+
117
+ Fan-In (Sequential):
118
+ └── Loop: Synthesize all findings → create action plan → implement
119
+ ```
120
+
121
+ ### Pattern 4: Pipeline with Checkpoints
122
+
123
+ Best for: Complex multi-stage transformations.
124
+
125
+ ```
126
+ Stage 1 (Loop): Parse + validate input → intermediate.json
127
+ ↓ checkpoint: verify intermediate.json schema
128
+ Stage 2 (Loop): Transform data → output draft
129
+ ↓ checkpoint: run regression tests
130
+ Stage 3 (Parallel Agents): Apply fixes to multiple output files
131
+ ↓ checkpoint: final integration test
132
+ ```
133
+
134
+ ### Pattern 5: Scout-Then-Execute
135
+
136
+ Best for: Unfamiliar codebases or risky changes.
137
+
138
+ ```
139
+ Scout Phase (Single Agent, read-only):
140
+ └── Agent "scout": Explore codebase, map dependencies, identify risks
141
+ → .loophaus/reports/scout-report.md
142
+
143
+ Execute Phase (Loop):
144
+ └── Loop: Use scout report as reference, implement changes
145
+ ```
146
+
147
+ ## Subagent Configuration Reference
148
+
149
+ ### Codex CLI (experimental)
150
+
151
+ Codex spawns subagents via natural language prompts with keywords: "spawn", "parallel", "delegate", "one agent per".
152
+
153
+ ```
154
+ # Enable in ~/.codex/config.toml
155
+ [agents]
156
+ max_threads = 6 # Max concurrent agent threads (default: 6)
157
+ max_depth = 1 # No grandchild agents (default: 1)
158
+ ```
159
+
160
+ **Custom agent definitions** in `.codex/agents/` (TOML):
161
+
162
+ ```toml
163
+ # .codex/agents/scanner.toml
164
+ name = "scanner"
165
+ description = "Read-only codebase explorer for pattern extraction"
166
+ model = "gpt-5.4-mini" # Faster model for exploration
167
+ model_reasoning_effort = "low"
168
+ sandbox_mode = "read-only"
169
+ developer_instructions = """
170
+ Scan files for the requested pattern. Report findings with file paths and line numbers.
171
+ Do NOT modify any files.
172
+ """
173
+ ```
174
+
175
+ **Spawning in prompts:**
176
+
177
+ ```
178
+ "Spawn one agent per service directory to scan for auth issues:
179
+ 1. scanner on src/frontend/** → .loophaus/reports/frontend.md
180
+ 2. scanner on src/backend/** → .loophaus/reports/backend.md
181
+ 3. scanner on src/auth/** → .loophaus/reports/auth.md
182
+ Wait for all, then summarize findings by severity."
183
+ ```
184
+
185
+ **Batch processing** with `spawn_agents_on_csv`:
186
+
187
+ ```
188
+ # For 100+ similar items, use CSV-driven batch spawning:
189
+ spawn_agents_on_csv:
190
+ csv_path: .loophaus/items.csv
191
+ instruction: "Review {file_path} for {issue_type}. Return JSON via report_agent_job_result"
192
+ output_schema: { file: string, severity: string, fix: string }
193
+ output_csv_path: .loophaus/reports/batch-results.csv
194
+ max_concurrency: 6
195
+ ```
196
+
197
+ ### Model Selection Guide (Codex)
198
+
199
+ | Role | Recommended Model | Reasoning Effort |
200
+ | ----------------------- | ------------------- | ---------------- |
201
+ | Coordinator / main loop | gpt-5.4 | medium |
202
+ | Explorer / scanner | gpt-5.4-mini | low |
203
+ | Reviewer / security | gpt-5.4 | high |
204
+ | Quick iteration / TDD | gpt-5.3-codex-spark | medium |
205
+
206
+ ### Key Constraints
207
+
208
+ | Setting | Default | Note |
209
+ | -------------------- | ------- | ----------------------------------------------------------------------- |
210
+ | `agents.max_threads` | 6 | Hard cap on concurrent agents |
211
+ | `agents.max_depth` | 1 | No recursive agent spawning |
212
+ | File conflicts | N/A | Multiple agents writing same file = conflicts. Use ownership isolation. |
213
+ | Token usage | Higher | Each subagent does own inference. Use faster models for workers. |
214
+
215
+ ## Report Directory Convention
216
+
217
+ All subagent outputs should follow this structure:
218
+
219
+ ```
220
+ .loophaus/
221
+ └── reports/
222
+ ├── {agent-name}.md # Individual agent output
223
+ ├── merged.md # Combined findings (created by orchestrator)
224
+ └── plan.md # Action plan derived from findings
225
+ ```
226
+
227
+ This directory should be in `.gitignore` — reports are ephemeral working artifacts.
228
+
229
+ ## Decision Matrix
230
+
231
+ When analyzing a task, use this scoring to decide the orchestration pattern:
232
+
233
+ | Factor | Score | Pattern |
234
+ | ------------------------------ | ----- | ------------------- |
235
+ | Files span 3+ directories | +2 | Parallel |
236
+ | Items are independent | +2 | Parallel |
237
+ | Need full context to decide | -2 | Sequential |
238
+ | Order matters | -2 | Sequential |
239
+ | 10+ similar items | +1 | Parallel |
240
+ | Needs cross-file understanding | -1 | Sequential |
241
+ | Multiple services/repos | +3 | Divide by Ownership |
242
+
243
+ - **Score >= 3**: Recommend parallel subagents
244
+ - **Score 0–2**: Recommend sequential with optional scout phase
245
+ - **Score < 0**: Recommend single sequential Loop
246
+
247
+ ## Integration with Loop Interview
248
+
249
+ When `/loop-plan` invokes this skill, provide:
250
+
251
+ 1. **Recommended pattern** — which orchestration pattern fits best
252
+ 2. **Agent breakdown** — list of subagents with their roles and file boundaries
253
+ 3. **Phase structure** — how phases connect and what checkpoints exist
254
+ 4. **Prompt snippets** — ready-to-embed subagent instructions for the loop prompt
@@ -0,0 +1,80 @@
1
+ import { readFile, writeFile, mkdir, rename } from "node:fs/promises";
2
+ import { join, dirname } from "node:path";
3
+
4
+ const DEFAULT_STATE = {
5
+ active: false,
6
+ prompt: "",
7
+ completionPromise: "TADA",
8
+ maxIterations: 20,
9
+ currentIteration: 0,
10
+ sessionId: "",
11
+ };
12
+
13
+ export function getStatePath(cwd) {
14
+ if (process.env.LOOPHAUS_STATE_FILE) return process.env.LOOPHAUS_STATE_FILE;
15
+ if (process.env.RALPH_STATE_FILE) return process.env.RALPH_STATE_FILE;
16
+ return join(cwd || process.cwd(), ".loophaus", "state.json");
17
+ }
18
+
19
+ const LEGACY_PATHS = [
20
+ (cwd) => join(cwd, ".codex", "ralph-loop.state.json"),
21
+ (cwd) => join(cwd, ".claude", "ralph-loop.local.md"),
22
+ ];
23
+
24
+ export async function read(cwd) {
25
+ const primary = getStatePath(cwd);
26
+
27
+ try {
28
+ const raw = await readFile(primary, "utf-8");
29
+ return { ...DEFAULT_STATE, ...JSON.parse(raw) };
30
+ } catch {
31
+ // Primary not found, try legacy paths
32
+ }
33
+
34
+ const dir = cwd || process.cwd();
35
+ for (const pathFn of LEGACY_PATHS) {
36
+ const legacyPath = pathFn(dir);
37
+ try {
38
+ const raw = await readFile(legacyPath, "utf-8");
39
+ if (legacyPath.endsWith(".md")) {
40
+ return migrateMdFormat(raw);
41
+ }
42
+ return { ...DEFAULT_STATE, ...JSON.parse(raw) };
43
+ } catch {
44
+ continue;
45
+ }
46
+ }
47
+
48
+ return { ...DEFAULT_STATE };
49
+ }
50
+
51
+ export async function write(state, cwd) {
52
+ const statePath = getStatePath(cwd);
53
+ await mkdir(dirname(statePath), { recursive: true });
54
+ const tmp = statePath + ".tmp";
55
+ await writeFile(tmp, JSON.stringify(state, null, 2), "utf-8");
56
+ await rename(tmp, statePath);
57
+ }
58
+
59
+ export async function reset(cwd) {
60
+ await write({ ...DEFAULT_STATE }, cwd);
61
+ }
62
+
63
+ function migrateMdFormat(raw) {
64
+ const state = { ...DEFAULT_STATE };
65
+ const lines = raw.split("\n");
66
+ for (const line of lines) {
67
+ const match = line.match(/^(\w+):\s*(.+)$/);
68
+ if (!match) continue;
69
+ const [, key, value] = match;
70
+ if (key === "active") state.active = value.trim() === "true";
71
+ else if (key === "iteration") state.currentIteration = parseInt(value.trim(), 10) || 0;
72
+ else if (key === "max_iterations") state.maxIterations = parseInt(value.trim(), 10) || 20;
73
+ else if (key === "completion_promise") state.completionPromise = value.trim();
74
+ else if (key === "prompt") state.prompt = value.trim();
75
+ else if (key === "session_id") state.sessionId = value.trim();
76
+ }
77
+ return state;
78
+ }
79
+
80
+ export { DEFAULT_STATE };