spec-and-loop 1.0.8 → 2.0.0-rc.2

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.
package/QUICKSTART.md CHANGED
@@ -24,17 +24,17 @@ brew install jq
24
24
  git init
25
25
  ```
26
26
 
27
+ > **Note:** No external `ralph` CLI needed — `spec-and-loop` includes its own internal
28
+ > mini Ralph loop engine. Just install `opencode` and you're ready to go. The
29
+ > runtime prompt is self-contained and does not depend on editor-specific slash
30
+ > commands or local-only skills.
31
+
27
32
  ## Installation
28
33
 
29
34
  ```bash
30
35
  npm install -g spec-and-loop
31
36
  ```
32
37
 
33
- **Prerequisites:** Install openspec and opencode:
34
- ```bash
35
- npm install -g @fission-ai/openspec@latest opencode-ai
36
- ```
37
-
38
38
  ## Quick Demo (5 Minutes)
39
39
 
40
40
  ```bash
@@ -58,8 +58,8 @@ ralph-run --change add-hello-world
58
58
 
59
59
  **That's it!** The script will:
60
60
  - Read your OpenSpec artifacts (proposal, specs, design, tasks)
61
- - Execute each task with full context using opencode
62
- - Create a git commit after each task
61
+ - Execute each task with full context using the internal mini Ralph engine
62
+ - Create a git commit after each task (unless `--no-commit` is passed)
63
63
  - Track progress in tasks.md
64
64
 
65
65
  ## What Just Happened?
@@ -70,13 +70,13 @@ ralph-run --change add-hello-world
70
70
  - `design.md`: Technical decisions
71
71
  - `tasks.md`: Implementation tasks as checkboxes
72
72
 
73
- 2. **Executed tasks** with opencode
74
- - Each task got full context (proposal + specs + design + git history)
73
+ 2. **Executed tasks** with opencode via mini Ralph
74
+ - Each task got full context (proposal + specs + design + fresh task snapshot)
75
75
  - Git commits created after each task
76
76
  - Task checkboxes marked as complete
77
77
 
78
78
  3. **Iterated** until all tasks done
79
- - Errors from previous tasks inform subsequent tasks
79
+ - Recent failures or no-progress iterations inform subsequent tasks
80
80
  - Each task builds on the previous commit
81
81
  - Full granular git history
82
82
 
@@ -91,6 +91,9 @@ ls -la openspec/changes/add-hello-world/
91
91
 
92
92
  # View the generated PRD (internal use)
93
93
  cat openspec/changes/add-hello-world/.ralph/PRD.md
94
+
95
+ # Check loop status
96
+ ralph-run --status
94
97
  ```
95
98
 
96
99
  ## Common Commands
@@ -109,10 +112,16 @@ openspec archive <name> # Archive completed change
109
112
  ### Ralph Loop Commands
110
113
 
111
114
  ```bash
112
- ralph-run # Auto-detect most recent change and run
113
- ralph-run --change <name> # Run for specific change
114
- ralph-run --verbose # Run with debug output
115
- ralph-run --help # Show help message
115
+ ralph-run # Auto-detect most recent change and run
116
+ ralph-run --change <name> # Run for specific change
117
+ ralph-run --verbose # Run with debug output
118
+ ralph-run --no-commit # Run without auto-committing
119
+ ralph-run --help # Show help message
120
+
121
+ # Observability and control
122
+ ralph-run --status # Show loop status dashboard
123
+ ralph-run --add-context "guidance text" # Inject context into next iteration
124
+ ralph-run --clear-context # Remove pending context
116
125
  ```
117
126
 
118
127
  ## Real-World Example
@@ -141,12 +150,16 @@ ralph-run --change user-authentication
141
150
  # 6. Watch the magic happen!
142
151
  # [INFO] Found 15 tasks to execute
143
152
  # [INFO] Executing task 1/15: Create User model
144
- # ✓ Complete
145
153
  # [INFO] Executing task 2/15: Implement password hashing
146
- # ✓ Complete
147
154
  # ...
148
155
 
149
- # 7. Verify the implementation
156
+ # 7. Add context mid-run if needed (from another terminal)
157
+ ralph-run --add-context "Prefer bcrypt over argon2 for password hashing"
158
+
159
+ # 8. Check status
160
+ ralph-run --status
161
+
162
+ # 9. Verify the implementation
150
163
  git log --oneline # 15 commits, one per task
151
164
  git diff HEAD~15 # See full implementation
152
165
  ```
@@ -190,12 +203,12 @@ source ~/.bashrc
190
203
 
191
204
  ### "No tasks to execute"
192
205
 
193
- **Problem:** All tasks already complete!
206
+ **Problem:** All tasks already complete (or tasks.md has no unchecked items)
194
207
 
195
208
  **Solution:**
196
209
  ```bash
197
210
  # Check tasks.md
198
- grep "^\- \[x\]" openspec/changes/my-feature/tasks.md
211
+ grep "^\- \[ \]" openspec/changes/my-feature/tasks.md
199
212
 
200
213
  # Or create a new change
201
214
  openspec new another-feature
@@ -210,8 +223,9 @@ openspec new another-feature
210
223
  | **Iterative Loop** | Each task builds on previous commits |
211
224
  | **Error Propagation** | Failures inform subsequent tasks |
212
225
  | **Granular History** | One git commit per task |
213
- | **Auto-Resume** | Interrupted? Run again—picks up where left off |
214
- | **Context Injection** | Inject custom instructions during execution |
226
+ | **Auto-Resume** | Interrupted? Run again picks up where left off |
227
+ | **Context Injection** | `--add-context` injects guidance into the next iteration |
228
+ | **No External Ralph** | Self-contained mini Ralph engine — no `ralph` CLI needed |
215
229
 
216
230
  ## Testing
217
231
 
@@ -253,21 +267,18 @@ Tests run automatically on every push and pull request via GitHub Actions on bot
253
267
 
254
268
  1. **Read the full README.md** for detailed documentation
255
269
  2. **Try a real feature** in your project
256
- 3. **Explore the .ralph/** directory to see internal state
257
- 4. **Check out .hidden/** directory for advanced guides
258
- 5. **Review TESTING.md** for testing guidelines
270
+ 3. **Explore `openspec/changes/<name>/.ralph/`** to see the per-change loop state
271
+ 4. **Review TESTING.md** for testing guidelines
259
272
 
260
273
  ## Resources
261
274
 
262
275
  - [Full README](./README.md) - Comprehensive documentation
263
276
  - [OpenSpec](https://openspec.ai) - Specification workflow
264
277
  - [opencode](https://opencode.ai) - Agentic coding assistant
265
- - [open-ralph-wiggum](https://github.com/Th0rgal/open-ralph-wiggum) - Iterative execution loop
266
278
 
267
279
  ## Need Help?
268
280
 
269
281
  - Check the **Troubleshooting** section above
270
282
  - Review the **Full README.md** for detailed info
271
- - Check **.hidden/** directory for advanced guides
272
283
 
273
- Happy coding! 🚀
284
+ Happy coding!
package/README.md CHANGED
@@ -6,11 +6,13 @@ OpenSpec + Ralph Loop integration for iterative development with opencode.
6
6
  ![Coverage](https://img.shields.io/badge/coverage-0%25-red)
7
7
  [![npm version](https://badge.fury.io/js/spec-and-loop.svg)](https://badge.fury.io/js/spec-and-loop)
8
8
 
9
- **[🚀 Quick Start Guide](./QUICKSTART.md)** - Get up and running in 5 minutes!
9
+ **[Quick Start Guide](./QUICKSTART.md)** - Get up and running in 5 minutes!
10
10
 
11
11
  ## Why This Exists
12
12
 
13
- OpenSpec provides excellent structure for planning (proposal → specs → design → tasks) but leaves execution manual. Ralph Wiggum's iterative development loop (execute → commit → repeat) is powerful but requires PRD format instead of OpenSpec specs.
13
+ OpenSpec provides excellent structure for planning (proposal → specs → design → tasks) but leaves execution manual. This package provides an iterative development loop execute → commit → repeat driven by an internal mini Ralph implementation that works with OpenCode and eliminates the need for any external Ralph runtime.
14
+
15
+ The runtime prompt is self-contained: it does not depend on Cursor-only slash commands or editor-local skills.
14
16
 
15
17
  ## Installation
16
18
 
@@ -21,26 +23,20 @@ npm install -g spec-and-loop
21
23
  **Prerequisites:** You need OpenSpec and the OpenCode AI agent installed:
22
24
 
23
25
  ```bash
24
- # Install OpenSpec and OpenCode (recommended)
25
26
  npm install -g @fission-ai/openspec@latest opencode-ai
26
27
  ```
27
28
 
28
- Alternative OpenCode install methods (if you prefer):
29
+ Alternative OpenCode install methods:
29
30
 
30
31
  ```bash
31
- # npm (recommended)
32
- npm install -g opencode-ai
33
-
34
32
  # Install script (general use)
35
33
  curl -fsSL https://opencode.ai/install | bash
36
34
 
37
35
  # Homebrew (macOS / Linux)
38
36
  brew install anomalyco/tap/opencode
39
-
40
- # Windows: use WSL and install via one of the Linux methods above
41
37
  ```
42
38
 
43
- **[🚀 Get Started in 5 Minutes](./QUICKSTART.md)**
39
+ **[Get Started in 5 Minutes](./QUICKSTART.md)**
44
40
 
45
41
  ```bash
46
42
  # 1. Initialize OpenSpec in your project
@@ -58,13 +54,11 @@ ralph-run --change add-user-auth
58
54
 
59
55
  For detailed step-by-step instructions, see [QUICKSTART.md](./QUICKSTART.md).
60
56
 
61
- <!-- Duplicate Quick Start removed; see QUICKSTART.md for full instructions -->
62
-
63
57
  ## Testing
64
58
 
65
59
  Spec-and-loop includes a comprehensive test suite to ensure reliability and cross-platform compatibility.
66
60
 
67
- **[📋 Testing Guide](./TESTING.md)** - Detailed instructions for running tests
61
+ **[Testing Guide](./TESTING.md)** - Detailed instructions for running tests
68
62
 
69
63
  ### Quick Test Commands
70
64
 
@@ -93,81 +87,6 @@ npm run lint
93
87
 
94
88
  All tests are run automatically via GitHub Actions on every push and pull request.
95
89
 
96
- ### CI/CD Workflow
97
-
98
- The CI/CD pipeline is defined in `.github/workflows/test.yml` and performs the following steps:
99
-
100
- 1. **Checkout Code**: Pulls the latest code from the repository
101
- 2. **Setup Node.js**: Installs Node.js version 24 with npm caching
102
- 3. **Install System Dependencies**:
103
- - Linux: `apt-get install bats-core jq shellcheck`
104
- - macOS: `brew install bats-core jq shellcheck`
105
- 4. **Install npm Dependencies**: Runs `npm ci` to install dependencies
106
- 5. **Install Global CLIs**: Installs openspec, ralph, and opencode globally
107
- 6. **Run Shellcheck Linting**: Checks bash scripts for errors and best practices
108
- 7. **Run Unit Tests**: Executes bash and JavaScript unit tests
109
- 8. **Run Integration Tests**: Validates full workflow end-to-end
110
- 9. **Upload Artifacts**: Uploads test logs and coverage reports
111
-
112
- ### Triggering CI/CD
113
-
114
- The workflow runs automatically on:
115
- - Push to `main` or `develop` branches
116
- - Pull requests to `main` or `develop` branches
117
- - Manual trigger via GitHub Actions UI
118
-
119
- To manually trigger:
120
- 1. Go to Actions tab in GitHub
121
- 2. Select "Test Suite" workflow
122
- 3. Click "Run workflow"
123
- 4. Select branch and test suite (all/unit/integration)
124
-
125
- ### Troubleshooting CI/CD
126
-
127
- **Tests Failing on One Platform**
128
-
129
- If tests pass on Linux but fail on macOS (or vice versa):
130
- - Check for platform-specific command differences (GNU vs BSD tools)
131
- - Review platform-specific tests in `test-symlink-linux.bats`, `test-symlink-macos.bats`, etc.
132
- - Verify stat, md5sum/md5, and other commands use correct flags
133
-
134
- **Coverage Below Threshold**
135
-
136
- If coverage drops below 80%:
137
- - Review coverage reports uploaded as artifacts
138
- - Identify which functions lost coverage
139
- - Add tests to cover the missing code paths
140
-
141
- **Linting Failures**
142
-
143
- If shellcheck finds issues:
144
- - Review the warnings in the CI logs
145
- - Fix the issues locally: `npm run lint`
146
- - Commit the fixes
147
-
148
- **Timeout Issues**
149
-
150
- If tests timeout:
151
- - Integration tests may take longer than expected
152
- - Check for infinite loops or hanging processes
153
- - Review test fixture setup/teardown
154
-
155
- **Artifact Access**
156
-
157
- Download test logs and coverage reports:
158
- 1. Go to the failed workflow run
159
- 2. Scroll to "Artifacts" section
160
- 3. Download relevant artifacts (test logs, coverage reports)
161
- 4. Analyze locally to identify issues
162
-
163
- ### Test Coverage
164
-
165
- Critical functions have >80% test coverage. View detailed coverage reports:
166
- ```bash
167
- npm run test:coverage
168
- open coverage/index.html
169
- ```
170
-
171
90
  ## Prerequisites
172
91
 
173
92
  Before using spec-and-loop, ensure you have:
@@ -184,7 +103,6 @@ Before using spec-and-loop, ensure you have:
184
103
 
185
104
  3. **opencode** - Agentic coding assistant
186
105
  ```bash
187
- # Install via npm
188
106
  npm install -g opencode-ai
189
107
  ```
190
108
 
@@ -217,8 +135,20 @@ For complete installation instructions, see [QUICKSTART.md](./QUICKSTART.md).
217
135
 
218
136
  ### Ralph Loop Commands
219
137
 
220
- - `ralph-run --change <name>` - Run the ralph loop for a specific change
221
- - `ralph-run` - Auto-detect most recent change and run
138
+ ```
139
+ ralph-run [OPTIONS]
140
+
141
+ OPTIONS:
142
+ --change <name> OpenSpec change to execute (default: auto-detect)
143
+ --max-iterations <n> Maximum iterations (default: 50)
144
+ --no-commit Suppress automatic git commits
145
+ --verbose, -v Enable verbose output
146
+
147
+ OBSERVABILITY AND CONTROL:
148
+ --status Print loop status dashboard and exit
149
+ --add-context <text> Add context to inject into the next iteration
150
+ --clear-context Clear any pending context
151
+ ```
222
152
 
223
153
  ## How It Works
224
154
 
@@ -253,26 +183,29 @@ ralph-run --change my-feature
253
183
 
254
184
  **What happens:**
255
185
 
256
- 1. **Validation**: Checks for required OpenSpec artifacts
257
- 2. **PRD Generation**: Converts proposal + specs + design → PRD format (for internal use)
186
+ 1. **Validation**: Checks for required OpenSpec artifacts and git repository
187
+ 2. **PRD Generation**: Converts proposal + specs + design → PRD format for internal use
258
188
  3. **Task Execution**: For each incomplete task:
259
- - Generates context-rich prompt (task + specs + design + git history + errors)
260
- - Runs `opencode` with the prompt
261
- - Creates git commit with task description
189
+ - Generates context-rich prompt (full OpenSpec artifacts + a fresh task snapshot + recent loop signals)
190
+ - Runs `opencode` with the prompt via the internal mini Ralph engine
191
+ - Creates git commit with task description (unless `--no-commit`)
262
192
  - Marks task complete in tasks.md
263
- 4. **Completion**: All tasks done, errors cleared
193
+ 4. **Completion**: All tasks done
264
194
 
265
195
  ### Step 3: Monitor Progress
266
196
 
267
197
  ```bash
198
+ # Check loop status
199
+ ralph-run --status
200
+
268
201
  # Check remaining tasks
269
202
  grep "^- \[ \]" openspec/changes/my-feature/tasks.md
270
203
 
271
204
  # View git commits
272
205
  git log --oneline
273
206
 
274
- # See errors (if any failed)
275
- cat openspec/changes/my-feature/.ralph/errors.md
207
+ # Inject context into next iteration
208
+ ralph-run --add-context "Prefer async/await over callbacks"
276
209
  ```
277
210
 
278
211
  ## Example Workflow
@@ -288,9 +221,7 @@ ralph-run --change user-auth
288
221
  # Output:
289
222
  # [INFO] Found 15 tasks to execute
290
223
  # [INFO] Executing task 1/15: Create User model with password field
291
- # ✓ Complete
292
224
  # [INFO] Executing task 2/15: Implement password hashing
293
- # ✓ Complete
294
225
  # ...
295
226
 
296
227
  # 3. Verify implementation
@@ -305,21 +236,28 @@ git diff HEAD~15 # See full implementation
305
236
  | **Structured Planning** | OpenSpec workflow: proposal → specs → design → tasks |
306
237
  | **Agentic Execution** | opencode executes tasks with full context |
307
238
  | **Iterative Loop** | Each task builds on previous commits |
308
- | **Error Propagation** | Failures inform subsequent tasks |
239
+ | **Iteration Feedback** | Recent failures and no-progress iterations inform the next pass |
309
240
  | **Granular History** | One git commit per task |
310
- | **Auto-Resume** | Interrupted? Run again—picks up where left off |
311
- | **Context Injection** | Inject custom instructions during execution |
312
-
313
- For detailed feature descriptions, see below.
241
+ | **Auto-Resume** | Interrupted? Run again picks up where left off |
242
+ | **Context Injection** | `--add-context` injects guidance into the next iteration |
243
+ | **Loop Status** | `--status` shows active state, history, and struggle indicators |
244
+ | **No External Ralph** | Self-contained mini Ralph engine — no external `ralph` CLI needed |
314
245
 
315
246
  ## Features
316
247
 
317
- ### Ralph Wiggum + Agentic Coding
248
+ ### Mini Ralph Loop Engine
249
+
250
+ `spec-and-loop` includes a first-party mini Ralph implementation (`lib/mini-ralph/`) that
251
+ provides the core iterative loop without any external Ralph dependency:
252
+
253
+ - **Iterative execution**: Each task builds on previous commits with full context
254
+ - **State and history**: Loop state, iteration history, and struggle indicators stored in each change's `.ralph/`
255
+ - **Prompt templates**: Context-aware prompts generated from OpenSpec artifacts
256
+ - **Completion promises**: Loop exits when a completion signal is detected
257
+ - **Task progression**: Synchronized with `tasks.md` checkboxes as the source of truth
318
258
 
319
- - **Iterative refinement**: Each task builds on previous commits with full context
320
- - **Error propagation**: Failures inform subsequent iterations—don't repeat mistakes
321
- - **Granular history**: Commit per task makes debugging and rollback easy
322
- - **Context awareness**: AI sees proposal, specs, design, git history, and errors
259
+ The supported subset intentionally excludes upstream features that are out of scope for
260
+ this repository's OpenSpec-first workflow (multi-agent rotation, plugin toggles, etc.).
323
261
 
324
262
  ### OpenSpec + opencode Synergy
325
263
 
@@ -331,25 +269,43 @@ For detailed feature descriptions, see below.
331
269
 
332
270
  ### Script Features
333
271
 
334
- - **Auto-resume**: Interrupted? Run again—picks up where left off
335
- - **Context injection**: Inject custom instructions during execution
336
- - **Error recovery**: Errors propagate to guide subsequent tasks
337
- - **Bidirectional tracking**: Tasks.md and .ralph/tracking.json stay synced
272
+ - **Auto-resume**: Interrupted? Run again picks up where left off
273
+ - **Context injection**: `--add-context` / `--clear-context` via each change's `.ralph/ralph-context.md`
274
+ - **Error recovery**: Recent loop signals help guide subsequent tasks
275
+ - **Task synchronization**: `tasks.md` and the per-change `.ralph/ralph-tasks.md` symlink stay in sync
338
276
  - **Idempotent**: Run multiple times safely
339
277
 
340
278
  ## Advanced Usage
341
279
 
342
280
  ### Context Injection
343
281
 
344
- Inject custom instructions during execution:
282
+ Inject custom instructions into the next iteration:
283
+
284
+ ```bash
285
+ ralph-run --add-context "Use Redis instead of Memcached"
286
+
287
+ # Check current pending context
288
+ ralph-run --status
289
+
290
+ # Clear pending context
291
+ ralph-run --clear-context
292
+ ```
293
+
294
+ ### Loop Status Dashboard
345
295
 
346
296
  ```bash
347
- # Create injection file
348
- echo "Use Redis instead of Memcached" > openspec/changes/my-feature/.ralph/.context_injection
297
+ ralph-run --status
298
+ ```
299
+
300
+ Shows: active loop state, current task, prompt summary, pending context, iteration history,
301
+ and struggle indicators if the loop appears stuck.
302
+
303
+ ### No-Commit Mode
349
304
 
350
- # Next opencode invocation includes:
351
- ## Injected Context
352
- Use Redis instead of Memcached
305
+ Run without automatic git commits (useful for reviewing changes before committing):
306
+
307
+ ```bash
308
+ ralph-run --change my-feature --no-commit
353
309
  ```
354
310
 
355
311
  ### Verbose Mode
@@ -366,36 +322,27 @@ ralph-run --verbose --change my-feature
366
322
  cat openspec/changes/my-feature/.ralph/PRD.md
367
323
  ```
368
324
 
369
- ### Manually Inject Context
370
-
371
- ```bash
372
- echo "Consider performance implications" > openspec/changes/my-feature/.ralph/.context_injection
373
- ```
374
-
375
325
  ## Architecture
376
326
 
377
327
  This package integrates:
378
328
  - **OpenSpec**: Structured specification workflow
379
329
  - **opencode**: Agentic coding assistant for task execution
380
- - **Ralph Loop**: Iterative development with commits per task, error tracking
330
+ - **Mini Ralph** (`lib/mini-ralph/`): Internal iterative loop engine
381
331
 
382
332
  ### Context Propagation
383
333
 
384
334
  Each task execution includes:
385
- - **Task description**: What to implement
386
- - **Proposal summary**: Why this change matters
387
- - **Relevant specs**: Requirements to satisfy
388
- - **Design decisions**: Architectural constraints
389
- - **Git history**: Last 10 commits (what's already done)
390
- - **Previous errors**: What failed before (to avoid repeating)
335
+ - **OpenSpec artifacts**: Proposal, design, and spec content from the generated PRD
336
+ - **Fresh task snapshot**: Raw `tasks.md` content plus the current task and completed-task summary rendered each iteration
337
+ - **Recent loop signals**: Compact reminders about prior failed or no-progress iterations
338
+ - **Pending context**: Any `--add-context` injection
391
339
 
392
340
  ### Task Tracking
393
341
 
394
- Bidirectional synchronization:
395
- - **tasks.md**: Human-readable checkboxes `[ ]` → `[x]`
396
- - **.ralph/tracking.json**: Machine-readable state
397
- - **Atomic updates**: Both succeed or both fail
398
- - **Stable IDs**: Line numbers persist across script runs
342
+ Synchronized tracking:
343
+ - **tasks.md**: Human-readable checkboxes `[ ]` → `[x]` (source of truth)
344
+ - **.ralph/ralph-tasks.md**: Symlink to `tasks.md` for the loop engine
345
+ - **Atomic updates**: Checkboxes updated after each completed task
399
346
 
400
347
  ### File Structure
401
348
 
@@ -403,18 +350,19 @@ Bidirectional synchronization:
403
350
  openspec/changes/<name>/
404
351
  ├── proposal.md # Your "why"
405
352
  ├── design.md # Your "how"
406
- ├── tasks.md # Your "what" (checkboxes)
407
- └── specs/ # Your requirements
408
- ├── auth/
409
- │ └── spec.md
410
- └── api/
411
- └── spec.md
412
- └── .ralph/ # Internal state (auto-generated)
413
- ├── PRD.md # Generated from artifacts
414
- ├── tracking.json # Task completion state
415
- ├── errors.md # Failure history
416
- ├── context-injections.md # Manual injections log
417
- └── .context_injection # Pending injection
353
+ ├── tasks.md # Your "what" (checkboxes, source of truth)
354
+ ├── specs/ # Your requirements
355
+ ├── auth/
356
+ └── spec.md
357
+ └── api/
358
+ └── spec.md
359
+ └── .ralph/ # Internal loop state (auto-generated, per change)
360
+ ├── PRD.md
361
+ ├── ralph-tasks.md
362
+ ├── ralph-context.md
363
+ ├── ralph-history.json
364
+ ├── ralph-loop.state.json
365
+ └── prompt-template.md
418
366
  ```
419
367
 
420
368
  ## Troubleshooting
@@ -440,7 +388,6 @@ export PATH="$PATH:$(npm root -g)/.bin"
440
388
  ## Resources
441
389
 
442
390
  - [OpenSpec](https://openspec.ai) - Structured specification workflow
443
- - [open-ralph-wiggum](https://github.com/Th0rgal/open-ralph-wiggum) - Iterative execution loop
444
391
  - [opencode](https://opencode.ai) - Agentic coding assistant
445
392
 
446
393
  ## License
@@ -0,0 +1,99 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * context.js - Pending context management for mini-ralph.
5
+ *
6
+ * Manages reading, writing, adding, clearing, and consuming pending context
7
+ * from .ralph/ralph-context.md. Context is injected into the next iteration's
8
+ * prompt and then consumed (removed) so it does not carry forward indefinitely.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const path = require('path');
13
+
14
+ const CONTEXT_FILE = 'ralph-context.md';
15
+
16
+ /**
17
+ * Return the absolute path to the context file.
18
+ *
19
+ * @param {string} ralphDir
20
+ * @returns {string}
21
+ */
22
+ function contextPath(ralphDir) {
23
+ return path.join(ralphDir, CONTEXT_FILE);
24
+ }
25
+
26
+ /**
27
+ * Read the current pending context. Returns empty string if none.
28
+ *
29
+ * @param {string} ralphDir
30
+ * @returns {string}
31
+ */
32
+ function read(ralphDir) {
33
+ const file = contextPath(ralphDir);
34
+ if (!fs.existsSync(file)) return '';
35
+ return fs.readFileSync(file, 'utf8').trim();
36
+ }
37
+
38
+ /**
39
+ * Append text to the pending context file.
40
+ *
41
+ * @param {string} ralphDir
42
+ * @param {string} text
43
+ */
44
+ function add(ralphDir, text) {
45
+ if (!text || !text.trim()) return;
46
+ _ensureDir(ralphDir);
47
+ const file = contextPath(ralphDir);
48
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
49
+ const separator = existing && !existing.endsWith('\n') ? '\n\n' : (existing ? '\n' : '');
50
+ fs.writeFileSync(file, `${existing}${separator}${text.trim()}`, 'utf8');
51
+ }
52
+
53
+ /**
54
+ * Clear all pending context.
55
+ *
56
+ * @param {string} ralphDir
57
+ */
58
+ function clear(ralphDir) {
59
+ const file = contextPath(ralphDir);
60
+ if (fs.existsSync(file)) {
61
+ fs.unlinkSync(file);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Read pending context and then clear it (consume it for one iteration).
67
+ * Returns the context string, or null if there was nothing pending.
68
+ *
69
+ * @param {string} ralphDir
70
+ * @returns {string|null}
71
+ */
72
+ function consume(ralphDir) {
73
+ const text = read(ralphDir);
74
+ if (!text) return null;
75
+ clear(ralphDir);
76
+ return text;
77
+ }
78
+
79
+ /**
80
+ * Check whether there is pending context.
81
+ *
82
+ * @param {string} ralphDir
83
+ * @returns {boolean}
84
+ */
85
+ function hasPending(ralphDir) {
86
+ return !!read(ralphDir);
87
+ }
88
+
89
+ // ---------------------------------------------------------------------------
90
+ // Internal helpers
91
+ // ---------------------------------------------------------------------------
92
+
93
+ function _ensureDir(ralphDir) {
94
+ if (!fs.existsSync(ralphDir)) {
95
+ fs.mkdirSync(ralphDir, { recursive: true });
96
+ }
97
+ }
98
+
99
+ module.exports = { read, add, clear, consume, hasPending, contextPath };