initial import: @mikefreno/omp-ralpi (omp port)

This commit is contained in:
2026-08-10 09:46:09 -04:00
commit a9757c6fce
36 changed files with 14616 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@@ -0,0 +1,3 @@
node_modules
.pi-lens
package-lock.json

149
AGENTS.md Normal file
View File

@@ -0,0 +1,149 @@
# AGENTS.md
## What this is
A Pi coding agent extension that registers the `/ralpi` slash commands
(`/ralpi`, `/ralpi-run`, `/ralpi-plan`, `/ralpi-resume`, `/ralpi-reset`).
Not a standalone app — it runs inside Pi's extension host.
## Type checking
```
npm run typecheck # tsc --noEmit
```
Tests: `bun test` (parser and DAG suites in `tests/`).
No build step needed — Pi loads extensions via [jiti](https://github.com/unjs/jiti), which compiles TypeScript at runtime. `index.ts` is the entry point directly.
## Entry point
`index.ts` at repo root (not `src/`). Exports a default function receiving `ExtensionAPI`.
## External dependencies
The extension imports from Pi SDK packages (not in `package.json` — provided by the host):
- `@earendil-works/pi-coding-agent``ExtensionAPI`, `ExtensionContext`, `createAgentSession`, etc.
- `@earendil-works/pi-tui``Box`, `Text` for custom message renderer
The only real npm dependency is `yaml` (^2.4.0). It is used for parsing YAML
task files (`src/parser.ts`) and config files (`parseSimpleYaml` in
`src/utils.ts`, which falls back to a flat key:value parser when the package
is unavailable).
## Source structure
- `index.ts` — extension entry, command registration (`ralpi`, `ralpi-run`,
`ralpi-plan`, `ralpi-resume`, `ralpi-reset`), execution-mode + loop-option
prompts, reload auto-resume via `session_start`, progress message renderer
- `src/` — all logic modules:
- `parser.ts` — task file parsing (Fio/README numbered, phased, checkbox,
YAML formats), dependency + parallel-group + timeout parsing,
`updateTaskInFile()` for PRD checkbox updates
- `dag.ts` — Kahn's algorithm dependency resolution, group-aware batching,
cycle detection, sequential/parallel plan builders
- `executor.ts` — task execution, parallel/sequential modes, model
round-robin + failover, review-gated loop, worktree orchestration,
batch-level conflict resolution
- `review.ts` — review verdict extraction (`## REVIEW VERDICT`), review
save/load to `.ralpi/reviews/`
- `worktree.ts` — git worktree create/merge/cleanup helpers, stale-worktree
cleanup, `finalizeCommittedWorktrees()`
- `progress.ts``.ralpi/progress.json` state management (multi-PRD)
- `prompts.ts` — prompt generation for spawned agent sessions
- `reflection.ts` — reflection extraction from agent output
- `utils.ts` — config loading, progress/PRD discovery, `runAgentSession()`,
model resolution (`resolveModelSpec`), loop-active marker
- `types.ts` — all interfaces and `DEFAULT_CONFIG`
- `widget-batcher.ts` — debounced widget updates for parallel tasks
- `task-manager-prompt.ts` — loads and expands the bundled
`prompts/task-manager.md` template for `/ralpi-plan`
- `constants.ts` — static constants (slash command, task file names,
reflection/review patterns)
- `tests/` — bun test suites for parser and DAG behavior
- `prompts/task-manager.md` — Pi prompt for task planning
## Runtime state
All runtime state lives in `.ralpi/` in the **project directory** (not this extension directory):
- `.ralpi/progress.json` — execution progress, supports multiple PRDs
- `.ralpi/loop-active.json` — marker written while a loop runs; drives
auto-resume after a session reload
- `.ralpi/reflections/` — per-task reflection JSON files
- `.ralpi/reviews/<prdKey>/` — full review output JSON (only when
`saveReviews` is on)
- `.ralpi/prompts/` — generated prompts (timestamped, for debugging)
- `.ralpi/config.yaml` — project-level config (optional)
There is no `.ralpi/sessions/` directory anymore — full task output is shown
inline via expandable `ralpi-progress` chat messages, and review output is
persisted under `.ralpi/reviews/`.
## Task ID convention
Task IDs are zero-padded strings (`"01"`, `"02"`, etc.) with an optional
single lowercase letter suffix for sub-tasks (`"02b"`, `"02c"`). The parser
normalizes `2b``02b` (see `normalizeTaskId` in `src/parser.ts`). Never
use raw numeric IDs.
## Command routing
- `/ralpi` — no args → show plan for `README.md`; first token looks like a
path (`@path`, `./path`, `.md`, `.yaml`, etc.) → run; anything else →
error suggesting the dash commands
- `/ralpi-run [task-file]` — run tasks (auto-resumes when progress already
exists for the file; otherwise prompts for execution mode + loop options)
- `/ralpi-plan [prompt]` — loads the bundled `prompts/task-manager.md`
template and sends it as a user message. Pi's `sendUserMessage()` sends
with `expandPromptTemplates: false`, so the extension does its own
frontmatter stripping and `$@`/`$1` arg substitution
(`loadTaskManagerPrompt` in `src/task-manager-prompt.ts`)
- `/ralpi-resume [task-file]` — resume from persisted progress; prompts for
the PRD when multiple loops have progress. Reuses the loop snapshot in
`loop-active.json` (mode + autoCommit/autoReview/saveReviews) to resume
non-interactively
- `/ralpi-reset [task-file]` — reset execution progress (does not modify the PRD)
The old `/ralpi plan|resume|reset` subcommand dispatch, plus `status` and
`next`, were removed.
## Config
Read from `.ralpi/config.yaml` in project directory (and global
`~/.pi/ralpi/config.yaml`), project overrides global. Falls back to
`DEFAULT_CONFIG` in `src/types.ts` when files are missing. Config is loaded
at `projectDir` level, not extension level. Execution keys explicitly
present in a loaded YAML are tracked in `execution.explicitKeys` so the
loop-startup interactive prompts (`selectLoopOptions` in `index.ts`) can be
skipped for fields the user already set.
Key config fields in `execution`:
- `autoCommit` / `autoReview` / `saveReviews` — loop options (selectable at
loop startup via `selectLoopOptions`; review is asked FIRST, commit is
mandated when review is on)
- `models` — slot-aware round-robin model list for parallel mode, with
failover to the next model per task (only after exhausting same-model
retries, see `maxSameModelAttempts`)
- `maxSameModelAttempts` — max attempts on the SAME model before cycling to
the next model on failure (default 5, matching pi's normal retry count).
Applies to task execution, commit/review follow-up sessions, and
review-fix re-execution alike
- `implModel` / `commitModel` / `reviewModel``<provider>/<model>` strings
resolved via `resolveModelSpec` in `utils.ts`
- `prompts.reviewFocus` — per-review custom focus/instructions, injected as a
`## Custom Review Focus` section in review prompts
- `review.extraIgnorePatterns` — extra noise-filter exclusion regexes (file
paths) merged into the default rules
- `review.ignorePaths` — pathspec allowlist keeping matching files in review
scope even when a default noise rule would exclude them
- `maxReviewRetries` / `reviewBlockOnFail` — review-gated loop retry behavior
- `worktrees``"never" | "parallel" | "always"` git worktree isolation
(default `"parallel"`; see `shouldUseWorktrees` in `src/executor.ts`)
- `commitTimeoutMs` / `reviewTimeoutMs` — timeouts for follow-up sessions
- `loopTimeoutMs` — max total loop duration in ms (0 = no limit; checked
between batches in `executePlanBatches`)
- `timeoutMs` — per-task execution timeout
- `prompts.projectContext` / `prompts.reflectionPrompt` — prompt-level settings

21
LICENSE Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Michael Freno
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

304
README.md Normal file
View File

@@ -0,0 +1,304 @@
# Ralpi
Execute tasks from task files until done using DAG-based dependency resolution with persistent progress tracking.
```bash
# omp auto-discovers extensions in ~/.omp/agent/extensions/<name>/
git clone <repo> ~/.omp/agent/extensions/ralpi/
```
## Features
- **DAG-based execution**: Tasks ordered via dependencies (arrow notation, natural language, "must be done before", or YAML)
- **Parallel batching**: Independent tasks in each batch run concurrently, round-robin across configured models
- **Persistent progress**: Execution state saved to `.ralpi/progress.json`, supporting multiple PRDs simultaneously
- **Resume & auto-resume**: `/ralpi-resume` continues paused execution; a session reload mid-loop auto-resumes via `.ralpi/loop-active.json`
- **Reflection system**: Each task produces a reflection for downstream tasks
- **Phased plans**: `## Phase N — Title` sections add implicit phase-boundary dependencies
- **Model failover**: Unreachable providers cycle to the next model in the list before a task fails
- **Auto-commit / auto-review loop**: Optional per-task commit and review-gated re-execution until pass
- **Worktree isolation**: Parallel tasks run in separate git worktrees so they can't stomp each other, with batch-level merge-conflict resolution
- **Multiple formats**: Fio README (numbered + dependencies), phased, simple checkboxes, and YAML
- **Tool usage tracking**: Reports read/write/edit/bash usage from task execution
- **Configurable timeouts**: Task-level timeouts (inline, meta block, or YAML) with global fallback
## Usage
```
/ralpi [task-file] # No args → show plan for README.md; path arg → run tasks
/ralpi-run [task-file] # Execute tasks from a task file
/ralpi-plan [prompt] # Open the Task Manager to plan tasks
/ralpi-resume [task-file] # Resume paused/interrupted execution
/ralpi-reset [task-file] # Reset execution progress — does not modify the PRD
```
`/ralpi` with no arguments shows the execution plan for the default task file. When the first token looks like a path (`@path`, `./path`, `path/file.md`, `.yaml`, etc.) it routes to `/ralpi-run`. Everything else is handled by the dedicated dash commands above (the old `/ralpi plan|resume|reset` subcommand syntax is gone).
> The task-manager prompt (`/ralpi-plan`) pairs perfectly with ralpi's task file formats — use it for PRD construction.
## Tasks
### Simple Checkbox Format
```markdown
- [ ] Setup project structure
- [ ] Implement auth
- [ ] Build API
```
Checkbox-only files get sequential IDs (`01`, `02`, ...). Status characters: `[ ]` pending, `[x]` done, `[~]` in progress, `[!]` failed, `[-]` skipped.
### Fio Format (numbered tasks + dependencies)
```markdown
# Build a web application
## Tasks
- [ ] 01 — Setup project structure
- [ ] 02 — Implement auth
- [ ] 03 — Build API
## Dependencies
01 -> 02, 03
```
### YAML Format
```yaml
objective: Build a web application
tasks:
- id: "01"
title: Setup project structure
file: tasks/01-setup.md
dependencies: []
- id: "02"
title: Implement auth
file: tasks/02-auth.md
depends_on: ["01"]
```
## Task IDs
Task IDs are zero-padded 2-digit strings (`01`, `02`, ...) with an optional
single lowercase letter suffix for sub-tasks inserted between two numbered
steps (e.g. `02b`, `02c`). The parser normalizes `2b``02b`.
```
- [ ] 01 — Setup
- [ ] 02 — Fix bugs
- [ ] 02b — Sub-step of 02 (inserted after the fact)
- [ ] 02c — Another sub-step of 02
- [ ] 03 — Continue
```
Use lettered sub-tasks when you discover mid-stream that a step needs to be
split. They let you preserve sibling numbering (`01`, `02`, `03`, ...) while
adding granularity between two existing steps.
## Phases
`## Phase N — Title` headings group tasks into phases and add an implicit
dependency from the first task of each phase to the last task of the
previous one, so phases always run in order:
```markdown
## Phase 1 — Push-to-Talk MVP
- [ ] 01 — Voice capture
- [ ] 02 — Transmission
## Phase 2 — Group Chat
- [ ] 03 — Channels
- [ ] 04 — Presence
```
## Dependencies
Dependency lines live in a `## Dependencies` section (or a plain
`Dependencies` heading). Multiple formats are supported and can be mixed.
### Arrow Notation (recommended)
```
1 -> 2,3,4
5 -> 6
```
"Task 1 must complete before tasks 2, 3, and 4 can start." Also supports
chains (`03 -> 04 -> 05`) and multi-prereq sources (`05, 07, 08 -> 13`).
### Natural Language
```
13 depends on 17, 18, 19, 20
14 depends on 13, 15, 16
22, 23, 24 depend on 21
```
"Task 13 depends on tasks 17, 18, 19, and 20." `also depends on` is accepted.
### "must be done before"
```
21 must be done before 22, 23, 24
02, 03 must be done before 04
```
### Parallel Groups
```
1, 2, 3, 4 can be done in parallel (Play Store prep)
5, 6, 7, 8 can be done in parallel
```
Tasks listed in a parallel group are allowed to run concurrently. Group
declarations imply no cross-group dependencies, and intra-group
dependencies are still respected — group-aware batching produces a plan
where tasks from any group run as soon as their dependencies are
satisfied.
## Configuration
### Task-Level Timeout
Timeouts can be set inline on the task line, as an inline comment, via a
meta block in the Dependencies section, or in YAML:
```markdown
- [ ] 01 — Setup project structure timeout: 10m
- [ ] 02 — Implement auth # timeout=30s
```
```markdown
## Dependencies
01 -> 02
01 [timeout] = 10m
```
```yaml
tasks:
- id: "01"
title: Setup project structure
timeout: 15m
```
Supported units: `m` / `min` (minutes), `s` (seconds), `ms` (milliseconds).
Bare numbers default to minutes; in YAML, numeric values ≥ 1000 are treated
as milliseconds.
### Config files
| Scope | Path |
|-------|------|
| **Global** | `~/.omp/ralpi/config.yaml` |
| **Project** | `./.ralpi/config.yaml` |
Project config overrides global, which overrides defaults. Keys set
explicitly in YAML skip the corresponding loop-startup prompt.
```yaml
execution:
maxParallel: 3 # ralpi-level concurrency only (0 = unlimited)
models: # round-robin for parallel tasks, <provider>/<model>
- anthropic/claude-sonnet-4
- openai/gpt-4o
autoCommit: true # commit after each task (mandated when autoReview is on)
autoReview: false # commit → review → loop on fail → merge on pass
saveReviews: false # persist full review output to .ralpi/reviews/ (only with autoReview)
maxReviewRetries: 2 # re-executions on a 'fail' verdict before giving up
reviewBlockOnFail: false # true = mark task failed after retries exhausted instead of merging
implModel: "" # model for task impl (empty = inherit parent session model)
commitModel: "" # model for commit sessions (empty = inherit task model)
reviewModel: "" # model for review sessions (empty = inherit task model)
timeoutMs: 0 # per-task timeout in ms (0 = inherit Pi's defaults)
commitTimeoutMs: 0 # timeout for auto-commit agent sessions (0 = inherit)
reviewTimeoutMs: 0 # timeout for auto-review agent sessions (0 = inherit)
loopTimeoutMs: 0 # max total loop duration in ms (0 = no limit; checked between batches)
worktrees: parallel # "never" | "parallel" (default) | "always" — git worktree isolation
chatStyle: compact # "compact" (default) | "verbose" — per-event tool-call stream
prompts:
projectContext: "Additional context for all tasks"
reflectionPrompt: "" # custom suffix for reflection extraction
reviewFocus: "" # per-review custom focus/instructions (e.g. "check security only")
review:
extraIgnorePatterns: [] # extra noise-filter exclusion regexes (merged into the default rules)
ignorePaths: [] # pathspec allowlist — files matching these stay in review scope
```
Review prompts (committed + uncommitted) run the diff through a noise filter
before inlining: lockfiles, minified/generated assets, source maps,
snapshots, build output, `node_modules`/`vendor`, and binary/media files are
excluded by default. The prompt gets a per-file `+/` summary table, an
`### Excluded Files (n)` section listing what was filtered (path, counts,
reason), and — when a diff is oversized or touches >20 files — a
file-list + "use `read`" instruction instead of a byte-truncated diff.
`prompts.reviewFocus` injects a `### Custom Review Focus` section into each
review prompt. `review.extraIgnorePatterns` adds exclusion regexes (matched
against file paths), and `review.ignorePaths` is a pathspec allowlist that
keeps matching files in review scope even when a default rule would exclude
them.
> `execution.models` uses slot-aware round-robin: with 3 models and 2 concurrent
> tasks, only the first two models are used. The third model is only touched when
> a third concurrent task starts. Freed model slots are reused before new ones
> are allocated.
> **Automatic failover**: if a provider/API is unreachable (rate limit, 503, etc.),
> the task automatically cycles to the next model in the list without counting it
> as a task failure. Each model is tried once before the task is marked as failed.
> **NOTE**: model lists are only used in parallel execution. In sequential mode
> (or parallel mode with no `models` list) the parent pi session's model is used,
> unless `implModel` is set.
> `execution.chatStyle` controls how sub-agent tool calls appear in the chat during task execution:
> - **compact** (default): a single completion message per task with an expandable tool-call tree (collapsed shows the last 3 calls, expanded via Ctrl+O shows all).
> - **verbose**: each tool event is streamed live as its own chat line (`[01 · task-name] → bash ...` / `← (ok)`), like piolium/pygienium's per-event stream.
#### Auto-review and Auto-commit
At loop startup the review question is asked FIRST. When `autoReview` is
enabled, commit is **mandated** — after task execution, changes are
committed (via a commit agent session when the task agent didn't
self-commit), then the complete task diff (`baseRef..HEAD`) is reviewed
against the task description. On a `fail` verdict the task is
re-executed with the review feedback injected into the prompt (looping
until the review passes or `maxReviewRetries` is exhausted). After
re-execution, changes are committed again and the full diff is
re-reviewed with the same base ref so the reviewer sees the complete
state — original work plus fixes. On pass, the changes are already
committed and the worktree merges.
When `autoReview` is disabled, `autoCommit` runs a follow-up commit
agent after each task with no review. With `autoReview` on, the user is
also asked whether to persist full review output to
`.ralpi/reviews/<prdKey>/<task-id>.json` (`saveReviews` — this is what
enables review feedback recovery when resuming interrupted loops). Both
options can be overridden at loop startup via a selection prompt (config
YAML values are honored without prompting when set explicitly).
`commitModel` and `reviewModel` accept `<provider>/<model>` strings (e.g.
`anthropic/claude-sonnet-4`) resolved via the model registry. When empty, the
task's model is inherited. `implModel` sets the model for task implementation
(used whenever no round-robin model is assigned — sequential mode, or parallel
mode with an empty `models` list; overridden by `execution.models` round-robin
in parallel mode).
## State Files
```
.ralpi/progress.json # Execution progress (supports multiple PRDs)
.ralpi/loop-active.json # Active-loop marker used for auto-resume after a reload
.ralpi/reflections/ # Per-task reflections
.ralpi/reviews/<prdKey>/ # Full review output (when saveReviews is on)
.ralpi/prompts/ # Generated prompts (timestamped, for debugging)
.ralpi/config.yaml # Project-level config (optional)
```
Every `/ralpi run`, `/ralpi resume`, and `/ralpi reset` (plus the auto-resume
on session reload) ensures `.ralpi/` is present in the project's `.gitignore`,
so ralpi's own artifacts never show up as untracked/staged files in the user's
repo. Opt out per command with `--no-gitignore` (e.g. `/ralpi-run README.md
--no-gitignore`).

412
bun.lock Normal file
View File

@@ -0,0 +1,412 @@
{
"lockfileVersion": 1,
"configVersion": 1,
"workspaces": {
"": {
"name": "@mikefreno/ralpi",
"dependencies": {
"yaml": "^2.4.0",
},
"devDependencies": {
"@oh-my-pi/pi-coding-agent": "17.2.12",
"@oh-my-pi/pi-tui": "17.2.12",
"@types/node": "^20.0.0",
"bun-types": "^1.3.14",
"typescript": "^5.3.0",
},
},
},
"packages": {
"@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="],
"@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="],
"@babel/parser": ["@babel/parser@7.29.8", "", { "dependencies": { "@babel/types": "^7.29.8" }, "bin": "./bin/babel-parser.js" }, "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA=="],
"@babel/types": ["@babel/types@7.29.8", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg=="],
"@bufbuild/protobuf": ["@bufbuild/protobuf@2.13.0", "", {}, "sha512-acq7c49vxfm1ggJ95P70TX7ABDM0vxr1SYD3BB0o0jnBLB4OAqeHyKuN+cD3w80gXEDQ2zxHpR6CUeA+O/aU9g=="],
"@emnapi/runtime": ["@emnapi/runtime@1.11.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-Xz4Tpyki7XyrpbUK1jR1AhdAdaXyhhY4lZ3neLodmhpuWfy2PAQN5B46sAiU4liOXGLkHypn/qU+jvfWSCYYLA=="],
"@huggingface/jinja": ["@huggingface/jinja@0.5.9", "", {}, "sha512-uWTG+l3VJRsl7EXxYizuL3P+cCPoc3cRqbWWRcQN0FhejRfbdq0RNhCmbY/YDtnTcz9icdLYuLDjsnz4d8JMuw=="],
"@huggingface/tokenizers": ["@huggingface/tokenizers@0.1.3", "", {}, "sha512-8rF/RRT10u+kn7YuUbUg0OF30K8rjTc78aHpxT+qJ1uWSqxT1MHi8+9ltwYfkFYJzT/oS+qw3JVfHtNMGAdqyA=="],
"@huggingface/transformers": ["@huggingface/transformers@4.2.0", "", { "dependencies": { "@huggingface/jinja": "^0.5.6", "@huggingface/tokenizers": "^0.1.3", "onnxruntime-node": "1.24.3", "onnxruntime-web": "1.26.0-dev.20260416-b7804b056c", "sharp": "^0.34.5" } }, "sha512-8BRCoBMH0XsWaEIamuR0LrJGAfftgHAfb2Vrffy0VKlSAE/MnUJ5/h/zTfEP3fDIft+nk7TqB8xXEyABGitBjQ=="],
"@img/colour": ["@img/colour@1.1.0", "", {}, "sha512-Td76q7j57o/tLVdgS746cYARfSyxk8iEfRxewL9h4OMzYhbW4TAcppl0mT4eyqXddh6L/jwoM75mo7ixa/pCeQ=="],
"@img/sharp-darwin-arm64": ["@img/sharp-darwin-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-arm64": "1.2.4" }, "os": "darwin", "cpu": "arm64" }, "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w=="],
"@img/sharp-darwin-x64": ["@img/sharp-darwin-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-darwin-x64": "1.2.4" }, "os": "darwin", "cpu": "x64" }, "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw=="],
"@img/sharp-libvips-darwin-arm64": ["@img/sharp-libvips-darwin-arm64@1.2.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g=="],
"@img/sharp-libvips-darwin-x64": ["@img/sharp-libvips-darwin-x64@1.2.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg=="],
"@img/sharp-libvips-linux-arm": ["@img/sharp-libvips-linux-arm@1.2.4", "", { "os": "linux", "cpu": "arm" }, "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A=="],
"@img/sharp-libvips-linux-arm64": ["@img/sharp-libvips-linux-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw=="],
"@img/sharp-libvips-linux-ppc64": ["@img/sharp-libvips-linux-ppc64@1.2.4", "", { "os": "linux", "cpu": "ppc64" }, "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA=="],
"@img/sharp-libvips-linux-riscv64": ["@img/sharp-libvips-linux-riscv64@1.2.4", "", { "os": "linux", "cpu": "none" }, "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA=="],
"@img/sharp-libvips-linux-s390x": ["@img/sharp-libvips-linux-s390x@1.2.4", "", { "os": "linux", "cpu": "s390x" }, "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ=="],
"@img/sharp-libvips-linux-x64": ["@img/sharp-libvips-linux-x64@1.2.4", "", { "os": "linux", "cpu": "x64" }, "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw=="],
"@img/sharp-libvips-linuxmusl-arm64": ["@img/sharp-libvips-linuxmusl-arm64@1.2.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw=="],
"@img/sharp-libvips-linuxmusl-x64": ["@img/sharp-libvips-linuxmusl-x64@1.2.4", "", { "os": "linux", "cpu": "x64" }, "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg=="],
"@img/sharp-linux-arm": ["@img/sharp-linux-arm@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm": "1.2.4" }, "os": "linux", "cpu": "arm" }, "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw=="],
"@img/sharp-linux-arm64": ["@img/sharp-linux-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg=="],
"@img/sharp-linux-ppc64": ["@img/sharp-linux-ppc64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-ppc64": "1.2.4" }, "os": "linux", "cpu": "ppc64" }, "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA=="],
"@img/sharp-linux-riscv64": ["@img/sharp-linux-riscv64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-riscv64": "1.2.4" }, "os": "linux", "cpu": "none" }, "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw=="],
"@img/sharp-linux-s390x": ["@img/sharp-linux-s390x@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-s390x": "1.2.4" }, "os": "linux", "cpu": "s390x" }, "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg=="],
"@img/sharp-linux-x64": ["@img/sharp-linux-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linux-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ=="],
"@img/sharp-linuxmusl-arm64": ["@img/sharp-linuxmusl-arm64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" }, "os": "linux", "cpu": "arm64" }, "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg=="],
"@img/sharp-linuxmusl-x64": ["@img/sharp-linuxmusl-x64@0.34.5", "", { "optionalDependencies": { "@img/sharp-libvips-linuxmusl-x64": "1.2.4" }, "os": "linux", "cpu": "x64" }, "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q=="],
"@img/sharp-wasm32": ["@img/sharp-wasm32@0.34.5", "", { "dependencies": { "@emnapi/runtime": "^1.7.0" }, "cpu": "none" }, "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw=="],
"@img/sharp-win32-arm64": ["@img/sharp-win32-arm64@0.34.5", "", { "os": "win32", "cpu": "arm64" }, "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g=="],
"@img/sharp-win32-ia32": ["@img/sharp-win32-ia32@0.34.5", "", { "os": "win32", "cpu": "ia32" }, "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg=="],
"@img/sharp-win32-x64": ["@img/sharp-win32-x64@0.34.5", "", { "os": "win32", "cpu": "x64" }, "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
"@jridgewell/resolve-uri": ["@jridgewell/resolve-uri@3.1.2", "", {}, "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw=="],
"@jridgewell/sourcemap-codec": ["@jridgewell/sourcemap-codec@1.5.5", "", {}, "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og=="],
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@kurkle/color": ["@kurkle/color@0.3.4", "", {}, "sha512-M5UknZPHRu3DEDWoipU6sE8PdkZ6Z/S+v4dD+Ke8IaNlpdSQah50lz1KtcFBa2vsdOnwbbnxJwVM4wty6udA5w=="],
"@oh-my-pi/hashline": ["@oh-my-pi/hashline@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-natives": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12" } }, "sha512-OdqMAojK8iUZynyNAP2VnbB+EHOHM7ISDSM3f9xHh/sDNSPDi15Xwd53AIdJy+EhYoCyglDIqO9/seHjA6veQQ=="],
"@oh-my-pi/omp-stats": ["@oh-my-pi/omp-stats@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-ai": "17.2.12", "@oh-my-pi/pi-catalog": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12", "@tailwindcss/node": "^4.3.2", "chart.js": "^4.5.1", "lucide-react": "^1.24.0", "react": "19.2.7", "react-chartjs-2": "^5.3.1", "react-dom": "19.2.7", "tailwindcss": "^4.3.2" }, "bin": { "omp-stats": "src/index.ts" } }, "sha512-BOyDNq8Hj/CJVc6Wntdo+1yaG/b8CqLcxsBnHefLoC7vO96YoFjt4S7GOpp3cd+ysiuxHnmrWn30kEtwR9fhjQ=="],
"@oh-my-pi/omptype": ["@oh-my-pi/omptype@17.2.12", "", {}, "sha512-Y27VMnPbcUEOpK1DgYuvNIaVnGxEmOcEP2bYPfuAWkx2vc4PKXL0NCRzGLwYMjhwjjd9O/gn8lywZfxDCBytjA=="],
"@oh-my-pi/pi-agent-core": ["@oh-my-pi/pi-agent-core@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-ai": "17.2.12", "@oh-my-pi/pi-catalog": "17.2.12", "@oh-my-pi/pi-natives": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12", "@oh-my-pi/pi-wire": "17.2.12", "@oh-my-pi/snapcompact": "17.2.12", "@opentelemetry/api": "^1.9.1" } }, "sha512-VIJnZCQyshiZoiWpvhoNVHhUQmptLG41h7XPg2IZfEdDNdDpV26JuZdDMgBr0hIz1L/RfTq8MiRcRuAcasvkOg=="],
"@oh-my-pi/pi-ai": ["@oh-my-pi/pi-ai@17.2.12", "", { "dependencies": { "@bufbuild/protobuf": "^2.12.1", "@oh-my-pi/omptype": "17.2.12", "@oh-my-pi/pi-catalog": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12", "@oh-my-pi/pi-wire": "17.2.12" } }, "sha512-S6LswgyLgQdE5zXADf6NGwrYn1OCYp1WiKxyN6f/1RRv68vbd3y4YSoidzeOYs3kPS/cIiv3dw3LHaCrwpam/Q=="],
"@oh-my-pi/pi-catalog": ["@oh-my-pi/pi-catalog@17.2.12", "", { "dependencies": { "@bufbuild/protobuf": "^2.12.1", "@oh-my-pi/omptype": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12" } }, "sha512-6VycCR0ShSzbVfOa7cdeqVtxHL2IPpJXFePKaQPhQ8bOTiyE/TaUm1uIa1i4doqPTz/k6vUEs+a57cZwoUP97A=="],
"@oh-my-pi/pi-coding-agent": ["@oh-my-pi/pi-coding-agent@17.2.12", "", { "dependencies": { "@babel/parser": "^7.29.7", "@oh-my-pi/hashline": "17.2.12", "@oh-my-pi/omp-stats": "17.2.12", "@oh-my-pi/omptype": "17.2.12", "@oh-my-pi/pi-agent-core": "17.2.12", "@oh-my-pi/pi-ai": "17.2.12", "@oh-my-pi/pi-catalog": "17.2.12", "@oh-my-pi/pi-mnemopi": "17.2.12", "@oh-my-pi/pi-natives": "17.2.12", "@oh-my-pi/pi-tui": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12", "@oh-my-pi/pi-wire": "17.2.12", "@oh-my-pi/snapcompact": "17.2.12", "@opentelemetry/api": "^1.9.1", "@opentelemetry/api-logs": "^0.220.0", "@opentelemetry/context-async-hooks": "^2.9.0", "@opentelemetry/exporter-logs-otlp-proto": "^0.220.0", "@opentelemetry/exporter-metrics-otlp-proto": "^0.220.0", "@opentelemetry/exporter-trace-otlp-proto": "^0.220.0", "@opentelemetry/resources": "^2.9.0", "@opentelemetry/sdk-logs": "^0.220.0", "@opentelemetry/sdk-metrics": "^2.9.0", "@opentelemetry/sdk-trace-base": "^2.9.0", "@opentelemetry/sdk-trace-node": "^2.9.0", "mupdf": "^1.28.0", "puppeteer-core": "25.3.0" }, "optionalDependencies": { "@huggingface/transformers": "^4.2.0", "sherpa-onnx-node": "1.13.2" }, "bin": { "omp": "dist/cli.js" } }, "sha512-+q+W4fyNQQ7xAKiN0mmOisWDDtKO0R/ZctTSsKqR4ulN3K1zfQ9HwiTxtg7HJHn5fwCy+X3BmUG72FatNUN8IA=="],
"@oh-my-pi/pi-mnemopi": ["@oh-my-pi/pi-mnemopi@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-ai": "17.2.12", "@oh-my-pi/pi-catalog": "17.2.12", "@oh-my-pi/pi-natives": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12" }, "peerDependencies": { "fastembed": "2.1.0", "onnxruntime-node": "1.21.0" }, "optionalPeers": ["fastembed", "onnxruntime-node"], "bin": { "mnemopi": "src/cli.ts" } }, "sha512-lKjEexuFC/piaNnb3MzJKu8rolXwkjfv0M90UBUiNPFxKbpKHWU5np5aUAOYkT+fwKoQPQ7Tr95mJx0l32S0OQ=="],
"@oh-my-pi/pi-natives": ["@oh-my-pi/pi-natives@17.2.12", "", { "optionalDependencies": { "@oh-my-pi/pi-natives-darwin-arm64": "17.2.12", "@oh-my-pi/pi-natives-darwin-x64": "17.2.12", "@oh-my-pi/pi-natives-linux-arm64": "17.2.12", "@oh-my-pi/pi-natives-linux-x64": "17.2.12", "@oh-my-pi/pi-natives-win32-x64": "17.2.12" } }, "sha512-MVZq0UrrA7mk6uMKrgjnAhfrDj+58yEuu0VeVd3JuvneMjcX1duIzOdyqRG13S+/XzGOvGkk164dM6D/CwxteQ=="],
"@oh-my-pi/pi-natives-darwin-arm64": ["@oh-my-pi/pi-natives-darwin-arm64@17.2.12", "", { "os": "darwin", "cpu": "arm64" }, "sha512-5iullmWEWmGRjwgo7Kw6Bub3KOXahkUX3jZfw65bM9LjFRceSwoLTt6Yh0RnXXP8hRzZnhU3b/o73peWBlpLzw=="],
"@oh-my-pi/pi-natives-darwin-x64": ["@oh-my-pi/pi-natives-darwin-x64@17.2.12", "", { "os": "darwin", "cpu": "x64" }, "sha512-qNc2q02d5etsOdxmO4CNwCcEvgfWS9Ya/fuq2hDKJgp3BFeKQCzYDap0HhC/qkAfj2vpjsTyKc/PsPMMMLGytg=="],
"@oh-my-pi/pi-natives-linux-arm64": ["@oh-my-pi/pi-natives-linux-arm64@17.2.12", "", { "os": "linux", "cpu": "arm64" }, "sha512-HTc6efuPNoYSzHu7Zk4gl3RtQzWWprVA4x0ep0gq5B7mBS6OwgnbH5otLrXSFeQ2UgRyV/nddz1O02ek4Vg8MA=="],
"@oh-my-pi/pi-natives-linux-x64": ["@oh-my-pi/pi-natives-linux-x64@17.2.12", "", { "os": "linux", "cpu": "x64" }, "sha512-jg9xzfqpcBDGRVnW+98z/eQPIfcnOYujd1bLW0PnJh6A0ykSqjCvt9PpN0wrlqr70WazOOURqoodN2eibIyOOQ=="],
"@oh-my-pi/pi-natives-win32-x64": ["@oh-my-pi/pi-natives-win32-x64@17.2.12", "", { "os": "win32", "cpu": "x64" }, "sha512-Jb/EF7Ug7SX/YYJofgKR5Kvw0I+AqGpEfmI5inIsvFzygqlA4QgMETbAR1s08sK+AYZqPqRorBpbGNas85XFig=="],
"@oh-my-pi/pi-tui": ["@oh-my-pi/pi-tui@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-natives": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12" } }, "sha512-X4IKQG3alzw3ogUewxoPBaZImReEBF7P2Xu5xN5E47lfMHR0eNJ6cQnQmk7sHjfNEAclKCJDYqwzgOfRdh9GEA=="],
"@oh-my-pi/pi-utils": ["@oh-my-pi/pi-utils@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-natives": "17.2.12" } }, "sha512-iYNV2y6RW9tzYaBa7hX5pzb23+zzNLF/Bs4bK7LAO2Qc7OZl5gw1lp9YOUX4/VZOO7A20KrXnZNwZVCnpPKy1A=="],
"@oh-my-pi/pi-wire": ["@oh-my-pi/pi-wire@17.2.12", "", {}, "sha512-UdQ0VP3gExd+jXgy8epCSZ+PTW9pkFu8FoomywmqEPj/JKjt1SqZhIiN8N51HkQCC5WJryT5AedzL/Qr6OID8w=="],
"@oh-my-pi/snapcompact": ["@oh-my-pi/snapcompact@17.2.12", "", { "dependencies": { "@oh-my-pi/pi-ai": "17.2.12", "@oh-my-pi/pi-natives": "17.2.12", "@oh-my-pi/pi-utils": "17.2.12", "@oh-my-pi/pi-wire": "17.2.12" } }, "sha512-kWYY/7tgIAnXAiYogC6K1GLU2G26QXTr2vDJGq1mxCMk3/GixoNzrFwzK8w6NmKYdQpO/Sa1SRw9sypYT+v1Bw=="],
"@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="],
"@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.220.0", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w=="],
"@opentelemetry/context-async-hooks": ["@opentelemetry/context-async-hooks@2.10.0", "", { "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-bvyMcgLEkozzSzpEEEo1OMoeQ97bxj6Qs2uN3mPrSdDvObMI1myffD/BPqcLlzZO9//d1SqQA/WPw7Cz2AiqhA=="],
"@opentelemetry/core": ["@opentelemetry/core@2.9.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-m2nckMT80NnmjTYSPjJQObBJ+8dgkoajEOUbznL8AHZ3T3yHRk2P7gI1PhEBc1+lOnrYE9UWrWHqJDsmqjmNbw=="],
"@opentelemetry/exporter-logs-otlp-proto": ["@opentelemetry/exporter-logs-otlp-proto@0.220.0", "", { "dependencies": { "@opentelemetry/otlp-exporter-base": "0.220.0", "@opentelemetry/otlp-transformer": "0.220.0", "@opentelemetry/sdk-logs": "0.220.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-8LZAxdJ0ENDAFwr4j0oY35mHBltiSzvlhdQAPGiC7p9VnxtuSq4SW1gfBAdW6t6hiQG6OwUl8w7KHaOdJPKHWg=="],
"@opentelemetry/exporter-metrics-otlp-http": ["@opentelemetry/exporter-metrics-otlp-http@0.220.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/otlp-exporter-base": "0.220.0", "@opentelemetry/otlp-transformer": "0.220.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/sdk-metrics": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-Yqt3RBw/bRVncaE9qIIhk4WfjbAQqXuP9FgAaU+IKPndnLEp/cUqZlSC324+bpmduRz7DoTjig8Ub0PeILWXUA=="],
"@opentelemetry/exporter-metrics-otlp-proto": ["@opentelemetry/exporter-metrics-otlp-proto@0.220.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/exporter-metrics-otlp-http": "0.220.0", "@opentelemetry/otlp-exporter-base": "0.220.0", "@opentelemetry/otlp-transformer": "0.220.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/sdk-metrics": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-lyO+IQBdSvqHN/ZOW/OzrSWemtfD+HgWngn+HBNLhjy0YrCQQTz0OE/kSekH2Pl340dn9DWzhqHdz5Eftr+HLA=="],
"@opentelemetry/exporter-trace-otlp-proto": ["@opentelemetry/exporter-trace-otlp-proto@0.220.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/otlp-exporter-base": "0.220.0", "@opentelemetry/otlp-transformer": "0.220.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/sdk-trace": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-voTAD8XgJxlK7zLkXh8EzMB09zrQr3tyY/BsnDTlDiQU/UdK58MZ63A3mUjdEDrxMjCVmBHU3WQJhRmQe+Dvzg=="],
"@opentelemetry/otlp-exporter-base": ["@opentelemetry/otlp-exporter-base@0.220.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/otlp-transformer": "0.220.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CXYo8UD5Mn9YbgebO2EL4wejtA+gxLmLiu6HCk2KH2BR7XhFN6/6p1UlCb23DYCjeYkndevLHuejCCN1yx4+OQ=="],
"@opentelemetry/otlp-transformer": ["@opentelemetry/otlp-transformer@0.220.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.220.0", "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/sdk-logs": "0.220.0", "@opentelemetry/sdk-metrics": "2.9.0", "@opentelemetry/sdk-trace": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-lXGrv7KXZ0gNH9SVNUaa6vv6phVYGvJxfXAlMbzbakiXru75f5MZl8Z7oqiMMQD77riVHJCFlQvbZs/VVN2/4A=="],
"@opentelemetry/resources": ["@opentelemetry/resources@2.10.0", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA=="],
"@opentelemetry/sdk-logs": ["@opentelemetry/sdk-logs@0.220.0", "", { "dependencies": { "@opentelemetry/api-logs": "0.220.0", "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.4.0 <1.10.0" } }, "sha512-WywcTkQtv2iNmt+6y5Kcd4rzvx9bLVsBa2Nwcmg01IUaBTkTow3W4d9KE5vNBpEDtb9tp21WcRBY/lANRrApYA=="],
"@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.10.0", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/resources": "2.10.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-t6r1VSvXNtSDnPXU1FbZeetJb7yyovHmgu0wRSoftxtE0g2rSNhQZQUy69sRUCL+iioJpX8SN/S6wq6ZtvLySQ=="],
"@opentelemetry/sdk-trace": ["@opentelemetry/sdk-trace@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-sGA19HvtrrSKYsseHphluH6j3p6Xa3fqc7c7y8f/7mYWejc1lyDFcpSdD1kYa50HCLUeEo4zA5bW0pniaPszuw=="],
"@opentelemetry/sdk-trace-base": ["@opentelemetry/sdk-trace-base@2.10.0", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/resources": "2.10.0", "@opentelemetry/sdk-trace": "2.10.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-GuYQQT7QD2EeO8lcZLRQzcbOyhqAzL+6WWTKTU9mSUBYBazkEDl+VrQcXQhbB08OWM9anD1aHleVadzulpOaUQ=="],
"@opentelemetry/sdk-trace-node": ["@opentelemetry/sdk-trace-node@2.10.0", "", { "dependencies": { "@opentelemetry/context-async-hooks": "2.10.0", "@opentelemetry/core": "2.10.0", "@opentelemetry/sdk-trace-base": "2.10.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-GZK/G6oZyBLGlH1pUgeDch7D91KoHd2uotUGIkWCPi9GI5T9X0p4L7nNAMDR1BQjkRYoDqo+ddfVx9t5Uhys+Q=="],
"@opentelemetry/semantic-conventions": ["@opentelemetry/semantic-conventions@1.43.0", "", {}, "sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg=="],
"@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="],
"@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="],
"@protobufjs/codegen": ["@protobufjs/codegen@2.0.5", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="],
"@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.1", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="],
"@protobufjs/fetch": ["@protobufjs/fetch@1.1.1", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="],
"@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="],
"@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="],
"@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="],
"@protobufjs/utf8": ["@protobufjs/utf8@1.1.2", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="],
"@puppeteer/browsers": ["@puppeteer/browsers@3.0.6", "", { "dependencies": { "modern-tar": "^0.7.6", "yargs": "^18.0.0" }, "peerDependencies": { "proxy-agent": ">=8.0.1", "yauzl": "^2.10.0 || ^3.4.0" }, "optionalPeers": ["proxy-agent", "yauzl"], "bin": { "browsers": "lib/main-cli.js" } }, "sha512-B/gKoqlFkzhvzsI6jo9K1cZz9o5ypviVv/xu8CwA4grZzyVwN+XfkT+tu8T1zrauuEXv6VhS2oGX+6NL95WcKA=="],
"@tailwindcss/node": ["@tailwindcss/node@4.3.3", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.24.1", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.3" } }, "sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg=="],
"@types/node": ["@types/node@20.19.43", "", { "dependencies": { "undici-types": "~6.21.0" } }, "sha512-6oYBAi5ikg4Pl+kGsoYtawUMBT2zZMCvPNF7pVLnHZfd1zf38DRiWn/gT01RYCdUqkv7Fhr+C9ot4/tb+2sVvA=="],
"adm-zip": ["adm-zip@0.5.18", "", {}, "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng=="],
"ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="],
"ansi-styles": ["ansi-styles@6.2.3", "", {}, "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg=="],
"boolean": ["boolean@3.2.0", "", {}, "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"chart.js": ["chart.js@4.5.1", "", { "dependencies": { "@kurkle/color": "^0.3.0" } }, "sha512-GIjfiT9dbmHRiYi6Nl2yFCq7kkwdkp1W/lp2J99rX0yo9tgJGn3lKQATztIjb5tVtevcBtIdICNWqlq5+E8/Pw=="],
"chromium-bidi": ["chromium-bidi@16.0.1", "", { "dependencies": { "mitt": "^3.0.1", "zod": "^3.24.1" }, "peerDependencies": { "devtools-protocol": "*" } }, "sha512-J63PGu/9PpeCwLIcKYyzWP6yaVL5pxuBc0shlYCYM8BaAkmlwiQboXO1iNbOgSDbVklEyYFfNEcHD8oOAWacUA=="],
"cliui": ["cliui@9.0.1", "", { "dependencies": { "string-width": "^7.2.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w=="],
"define-data-property": ["define-data-property@1.1.4", "", { "dependencies": { "es-define-property": "^1.0.0", "es-errors": "^1.3.0", "gopd": "^1.0.1" } }, "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A=="],
"define-properties": ["define-properties@1.2.1", "", { "dependencies": { "define-data-property": "^1.0.1", "has-property-descriptors": "^1.0.0", "object-keys": "^1.1.1" } }, "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"detect-node": ["detect-node@2.1.0", "", {}, "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g=="],
"devtools-protocol": ["devtools-protocol@0.0.1638949", "", {}, "sha512-mXwg4Fqnv0WR4iuAT/gYUmctNkjILwXFHyZ+m7Ty1dfr0ezZt2U3gnrrJTfRobJTHoXf+IbuFvFITzLrLFjwJA=="],
"emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="],
"enhanced-resolve": ["enhanced-resolve@5.24.5", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-L1l8TNvomm6UVW5B253AGxQagSQr+vGwhMlrrfRS2qmhx46AMpMVJKQYLvWYbysTMY8VoicOvzHzoHMbyzB+4A=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
"es6-error": ["es6-error@4.1.1", "", {}, "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-string-regexp": ["escape-string-regexp@4.0.0", "", {}, "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA=="],
"flatbuffers": ["flatbuffers@25.9.23", "", {}, "sha512-MI1qs7Lo4Syw0EOzUl0xjs2lsoeqFku44KpngfIduHBYvzm8h2+7K8YMQh1JtVVVrUvhLpNwqVi4DERegUJhPQ=="],
"get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="],
"get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="],
"global-agent": ["global-agent@3.0.0", "", { "dependencies": { "boolean": "^3.0.1", "es6-error": "^4.1.1", "matcher": "^3.0.0", "roarr": "^2.15.3", "semver": "^7.3.2", "serialize-error": "^7.0.1" } }, "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q=="],
"globalthis": ["globalthis@1.0.4", "", { "dependencies": { "define-properties": "^1.2.1", "gopd": "^1.0.1" } }, "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"guid-typescript": ["guid-typescript@1.0.9", "", {}, "sha512-Y8T4vYhEfwJOTbouREvG+3XDsjr8E3kIr7uf+JZ0BYloFsttiHU0WfvANVsR7TxNUJa/WpCnw/Ino/p+DeBhBQ=="],
"has-property-descriptors": ["has-property-descriptors@1.0.2", "", { "dependencies": { "es-define-property": "^1.0.0" } }, "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg=="],
"jiti": ["jiti@2.7.0", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ=="],
"json-stringify-safe": ["json-stringify-safe@5.0.1", "", {}, "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA=="],
"lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="],
"lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="],
"lightningcss-darwin-arm64": ["lightningcss-darwin-arm64@1.32.0", "", { "os": "darwin", "cpu": "arm64" }, "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ=="],
"lightningcss-darwin-x64": ["lightningcss-darwin-x64@1.32.0", "", { "os": "darwin", "cpu": "x64" }, "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w=="],
"lightningcss-freebsd-x64": ["lightningcss-freebsd-x64@1.32.0", "", { "os": "freebsd", "cpu": "x64" }, "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig=="],
"lightningcss-linux-arm-gnueabihf": ["lightningcss-linux-arm-gnueabihf@1.32.0", "", { "os": "linux", "cpu": "arm" }, "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw=="],
"lightningcss-linux-arm64-gnu": ["lightningcss-linux-arm64-gnu@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ=="],
"lightningcss-linux-arm64-musl": ["lightningcss-linux-arm64-musl@1.32.0", "", { "os": "linux", "cpu": "arm64" }, "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg=="],
"lightningcss-linux-x64-gnu": ["lightningcss-linux-x64-gnu@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA=="],
"lightningcss-linux-x64-musl": ["lightningcss-linux-x64-musl@1.32.0", "", { "os": "linux", "cpu": "x64" }, "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg=="],
"lightningcss-win32-arm64-msvc": ["lightningcss-win32-arm64-msvc@1.32.0", "", { "os": "win32", "cpu": "arm64" }, "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw=="],
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
"lucide-react": ["lucide-react@1.31.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-G8u2eEtoHUnUa9f8lbvqDhCiORMnYLdUEo06EEG9MQvHQrInKcX3Pa2TH39MM5qyzRcWETxB0+aOwAPI1g1kEg=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"matcher": ["matcher@3.0.0", "", { "dependencies": { "escape-string-regexp": "^4.0.0" } }, "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng=="],
"mitt": ["mitt@3.0.1", "", {}, "sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw=="],
"modern-tar": ["modern-tar@0.7.7", "", {}, "sha512-t9VmxaqrmANnEOBhpSDI6HD192Ge48k8vmWqQQL7hSFEqHEYwZbbsu49+aKLWZeRvFs3j1pMhXOqqF4kPlvjkQ=="],
"mupdf": ["mupdf@1.28.0", "", {}, "sha512-ACUnbpECaQ5JLq04pwd89lS+0IGMest5qL5tb08g9TAR7bDtfqflHEkb2Xm3o4rvC/szguLiV+WEbW9kstj8Sg=="],
"object-keys": ["object-keys@1.1.1", "", {}, "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA=="],
"onnxruntime-common": ["onnxruntime-common@1.24.3", "", {}, "sha512-GeuPZO6U/LBJXvwdaqHbuUmoXiEdeCjWi/EG7Y1HNnDwJYuk6WUbNXpF6luSUY8yASul3cmUlLGrCCL1ZgVXqA=="],
"onnxruntime-node": ["onnxruntime-node@1.24.3", "", { "dependencies": { "adm-zip": "^0.5.16", "global-agent": "^3.0.0", "onnxruntime-common": "1.24.3" }, "os": [ "linux", "win32", "darwin", ] }, "sha512-JH7+czbc8ALA819vlTgcV+Q214/+VjGeBHDjX81+ZCD0PCVCIFGFNtT0V4sXG/1JXypKPgScQcB3ij/hk3YnTg=="],
"onnxruntime-web": ["onnxruntime-web@1.26.0-dev.20260416-b7804b056c", "", { "dependencies": { "flatbuffers": "^25.1.24", "guid-typescript": "^1.0.9", "long": "^5.2.3", "onnxruntime-common": "1.24.0-dev.20251116-b39e144322", "platform": "^1.3.6", "protobufjs": "^7.2.4" } }, "sha512-MD6Ss4GSpQBo6zqoJzyT9LRbKYs7x/JVN23FT24EcEvlqF4VuzPOeH6X38orZPKHQDbprn7K+SBpu0/mj2CQiw=="],
"platform": ["platform@1.3.6", "", {}, "sha512-fnWVljUchTro6RiCFvCXBbNhJc2NijN7oIQxbwsyL0buWJPG85v81ehlHI9fXrJsMNgTofEoWIQeClKpgxFLrg=="],
"protobufjs": ["protobufjs@7.6.5", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="],
"puppeteer-core": ["puppeteer-core@25.3.0", "", { "dependencies": { "@puppeteer/browsers": "3.0.6", "chromium-bidi": "16.0.1", "devtools-protocol": "0.0.1638949", "typed-query-selector": "^2.12.2", "webdriver-bidi-protocol": "0.4.2", "ws": "^8.21.0" } }, "sha512-fm+wpUr2oigH1PXZvwgATrM2tYWHMDG8ASzTEe9uukCye4X5Ldx1K5BTHPFKITrIWvQQAQ256d1NpbEveBcKjA=="],
"react": ["react@19.2.7", "", {}, "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ=="],
"react-chartjs-2": ["react-chartjs-2@5.3.1", "", { "peerDependencies": { "chart.js": "^4.1.1", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-h5IPXKg9EXpjoBzUfyWJvllMjG2mQ4EiuHQFhms/AjUm0XSZHhyRy2xVmLXHKrtcdrPO4mnGqRtYoD0vp95A0A=="],
"react-dom": ["react-dom@19.2.7", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ=="],
"roarr": ["roarr@2.15.4", "", { "dependencies": { "boolean": "^3.0.1", "detect-node": "^2.0.4", "globalthis": "^1.0.1", "json-stringify-safe": "^5.0.1", "semver-compare": "^1.0.0", "sprintf-js": "^1.1.2" } }, "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A=="],
"scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="],
"semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="],
"semver-compare": ["semver-compare@1.0.0", "", {}, "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow=="],
"serialize-error": ["serialize-error@7.0.1", "", { "dependencies": { "type-fest": "^0.13.1" } }, "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw=="],
"sharp": ["sharp@0.34.5", "", { "dependencies": { "@img/colour": "^1.0.0", "detect-libc": "^2.1.2", "semver": "^7.7.3" }, "optionalDependencies": { "@img/sharp-darwin-arm64": "0.34.5", "@img/sharp-darwin-x64": "0.34.5", "@img/sharp-libvips-darwin-arm64": "1.2.4", "@img/sharp-libvips-darwin-x64": "1.2.4", "@img/sharp-libvips-linux-arm": "1.2.4", "@img/sharp-libvips-linux-arm64": "1.2.4", "@img/sharp-libvips-linux-ppc64": "1.2.4", "@img/sharp-libvips-linux-riscv64": "1.2.4", "@img/sharp-libvips-linux-s390x": "1.2.4", "@img/sharp-libvips-linux-x64": "1.2.4", "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", "@img/sharp-libvips-linuxmusl-x64": "1.2.4", "@img/sharp-linux-arm": "0.34.5", "@img/sharp-linux-arm64": "0.34.5", "@img/sharp-linux-ppc64": "0.34.5", "@img/sharp-linux-riscv64": "0.34.5", "@img/sharp-linux-s390x": "0.34.5", "@img/sharp-linux-x64": "0.34.5", "@img/sharp-linuxmusl-arm64": "0.34.5", "@img/sharp-linuxmusl-x64": "0.34.5", "@img/sharp-wasm32": "0.34.5", "@img/sharp-win32-arm64": "0.34.5", "@img/sharp-win32-ia32": "0.34.5", "@img/sharp-win32-x64": "0.34.5" } }, "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg=="],
"sherpa-onnx-darwin-arm64": ["sherpa-onnx-darwin-arm64@1.13.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-QcYKzyrTzGSx6aKCD6hUODgRS1LetqfG57Z/+i5LCyfMlrgCvDc1lRcl9cdB+TozBsLha9QwLTlI0vmDcf5JKg=="],
"sherpa-onnx-darwin-x64": ["sherpa-onnx-darwin-x64@1.13.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-6RGeis9K9gV/UQWOgd6Rf3iqXr2/YsBQswxHaCR4hrYkHfEIpHMfFmRWLt6nJJCOWgYW2xFxEd9yzjrafAV/Pw=="],
"sherpa-onnx-linux-arm64": ["sherpa-onnx-linux-arm64@1.13.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-RMjMRqT82BgTXypNNGmLe6ZFYhc3WEvnAGl3DdkK7qB/kuXwkL3iHhV31wAecbnWPsnEpUoD+8cFovWSBzsCuw=="],
"sherpa-onnx-linux-x64": ["sherpa-onnx-linux-x64@1.13.4", "", { "os": "linux", "cpu": "x64" }, "sha512-WZh5NCkGPFHHpYSd78iN4OnmxQeSTGyt9uZskH+im/NFHQ7elQ7B0sLzCMeRpvJxiIKvd9C6WxIJ4hYaxClfsQ=="],
"sherpa-onnx-node": ["sherpa-onnx-node@1.13.2", "", { "optionalDependencies": { "sherpa-onnx-darwin-arm64": "^1.13.2", "sherpa-onnx-darwin-x64": "^1.13.2", "sherpa-onnx-linux-arm64": "^1.13.2", "sherpa-onnx-linux-x64": "^1.13.2", "sherpa-onnx-win-ia32": "^1.13.2", "sherpa-onnx-win-x64": "^1.13.2" } }, "sha512-uIH6SA5Or4pb8HlCYWB3K54XkMtzdef4/tkw1amtIf8GB1tt6hQLpur9p2jSFNfTYRyzZ8XrXofxefXQ0A7EUA=="],
"sherpa-onnx-win-ia32": ["sherpa-onnx-win-ia32@1.13.4", "", { "os": "win32", "cpu": "ia32" }, "sha512-/JbPjldrfNv+t+uIS3MlkuhfIf5l3FHUGkRC2oRXgjRqOaVmEyP3vLlQ7dTa4J7raG5oB8c3GoPjuSWSqT9GOQ=="],
"sherpa-onnx-win-x64": ["sherpa-onnx-win-x64@1.13.4", "", { "os": "win32", "cpu": "x64" }, "sha512-R0PWby1VxC14TDZPq7GcfSyXSY6SAFO8Y4JwdCdqouFmeXkZ1L7Is9m98C9KxQ0dN7ZtDzhAmE/43FUs/elXRQ=="],
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"sprintf-js": ["sprintf-js@1.1.3", "", {}, "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA=="],
"string-width": ["string-width@8.2.2", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg=="],
"strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="],
"tailwindcss": ["tailwindcss@4.3.3", "", {}, "sha512-gOhV3P7ufE62QDGg1zVaTgCR+EtPv92k2nIhVcVKcLmxT1sUBsQGhnZj175j+MqRt4zLF7ic+sCYjfhxMxj7YQ=="],
"tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
"tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="],
"type-fest": ["type-fest@0.13.1", "", {}, "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg=="],
"typed-query-selector": ["typed-query-selector@2.12.2", "", {}, "sha512-EOPFbyIub4ngnEdqi2yOcNeDLaX/0jcE1JoAXQDDMIthap7FoN795lc/SHfIq2d416VufXpM8z/lD+WRm2gfOQ=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
"undici-types": ["undici-types@6.21.0", "", {}, "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ=="],
"webdriver-bidi-protocol": ["webdriver-bidi-protocol@0.4.2", "", {}, "sha512-VSV+fzfChirL3e7jay2yUC7B4HQCGtEWEg/MSSQbK+qWbqeGlRLlXTzPpYr3XGUvbpDHumWZBJxgesg4N7dbtA=="],
"wrap-ansi": ["wrap-ansi@9.0.2", "", { "dependencies": { "ansi-styles": "^6.2.1", "string-width": "^7.0.0", "strip-ansi": "^7.1.0" } }, "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww=="],
"ws": ["ws@8.21.3", "", { "peerDependencies": { "bufferutil": "^4.0.1", "utf-8-validate": ">=5.0.2" }, "optionalPeers": ["bufferutil", "utf-8-validate"] }, "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw=="],
"y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"yargs": ["yargs@18.1.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^8.2.1", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg=="],
"yargs-parser": ["yargs-parser@22.0.0", "", {}, "sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw=="],
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@opentelemetry/exporter-metrics-otlp-http/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="],
"@opentelemetry/exporter-metrics-otlp-http/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-Xx8RGS4H5XEBl01WuCreMIpiah9cCXMbSkeuIePPdD2cUpq/vUzYmj8E/MK1OsbOc93FuAD4jfn2WOacKwLn7Q=="],
"@opentelemetry/exporter-metrics-otlp-proto/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="],
"@opentelemetry/exporter-metrics-otlp-proto/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-Xx8RGS4H5XEBl01WuCreMIpiah9cCXMbSkeuIePPdD2cUpq/vUzYmj8E/MK1OsbOc93FuAD4jfn2WOacKwLn7Q=="],
"@opentelemetry/exporter-trace-otlp-proto/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="],
"@opentelemetry/otlp-transformer/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="],
"@opentelemetry/otlp-transformer/@opentelemetry/sdk-metrics": ["@opentelemetry/sdk-metrics@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/resources": "2.9.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <1.10.0" } }, "sha512-Xx8RGS4H5XEBl01WuCreMIpiah9cCXMbSkeuIePPdD2cUpq/vUzYmj8E/MK1OsbOc93FuAD4jfn2WOacKwLn7Q=="],
"@opentelemetry/resources/@opentelemetry/core": ["@opentelemetry/core@2.10.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ=="],
"@opentelemetry/sdk-logs/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="],
"@opentelemetry/sdk-metrics/@opentelemetry/core": ["@opentelemetry/core@2.10.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ=="],
"@opentelemetry/sdk-trace/@opentelemetry/resources": ["@opentelemetry/resources@2.9.0", "", { "dependencies": { "@opentelemetry/core": "2.9.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-jyA5MBLQ+Dkl3+JsZkUoUvL7yHvU64kLsvpXKarWm6347Sl1t1bXFTFykUePNpT5WH5pm9a2Qtt03iIYQhZ1Fg=="],
"@opentelemetry/sdk-trace-base/@opentelemetry/core": ["@opentelemetry/core@2.10.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ=="],
"@opentelemetry/sdk-trace-base/@opentelemetry/sdk-trace": ["@opentelemetry/sdk-trace@2.10.0", "", { "dependencies": { "@opentelemetry/core": "2.10.0", "@opentelemetry/resources": "2.10.0", "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.3.0 <1.10.0" } }, "sha512-MfQGq3GRmTh5fM/y+OjaO0vj6+luCB1XO2gfXCalKCfgKw0eHL++sm75DNweC6ohlp+aFvACqeE0fYayqdRaoQ=="],
"@opentelemetry/sdk-trace-node/@opentelemetry/core": ["@opentelemetry/core@2.10.0", "", { "dependencies": { "@opentelemetry/semantic-conventions": "^1.29.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0 <1.10.0" } }, "sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ=="],
"cliui/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
"onnxruntime-web/onnxruntime-common": ["onnxruntime-common@1.24.0-dev.20251116-b39e144322", "", {}, "sha512-BOoomdHYmNRL5r4iQ4bMvsl2t0/hzVQ3OM3PHD0gxeXu1PmggqBv3puZicEUVOA3AtHHYmqZtjMj9FOfGrATTw=="],
"wrap-ansi/string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="],
}
}

1603
index.ts Normal file

File diff suppressed because it is too large Load Diff

56
package.json Normal file
View File

@@ -0,0 +1,56 @@
{
"name": "@mikefreno/omp-ralpi",
"version": "0.5.0",
"description": "Execute tasks from task files/PRD's using DAG-based dependency resolution with persistent progress tracking",
"keywords": [
"omp",
"omp-extension",
"task-runner",
"dag",
"task-manager",
"ralph-loop",
"prd"
],
"author": "Michael Freno",
"license": "MIT",
"homepage": "https://github.com/mikefreno/ralpi",
"repository": {
"type": "git",
"url": "git+https://github.com/mikefreno/ralpi.git"
},
"bugs": {
"url": "https://github.com/mikefreno/ralpi/issues"
},
"files": [
"index.ts",
"src/",
"prompts/",
"README.md",
"LICENSE"
],
"scripts": {
"typecheck": "tsc --noEmit",
"test": "bun test"
},
"engines": {
"bun": ">=1.3.14"
},
"omp": {
"extensions": [
"./index.ts"
]
},
"dependencies": {
"yaml": "^2.4.0"
},
"publishConfig": {
"access": "public"
},
"devDependencies": {
"@oh-my-pi/pi-coding-agent": "17.2.12",
"@oh-my-pi/pi-tui": "17.2.12",
"@types/node": "^20.0.0",
"bun-types": "^1.3.14",
"typescript": "^5.3.0"
}
}

188
prompts/task-manager.md Normal file
View File

@@ -0,0 +1,188 @@
---
name: task-manager
description: Breaks down complex features into small, verifiable subtasks
tools: read, edit, write, web_search, code_search, fetch_content, get_search_content, mcp, memory, skill, session_search, memory_search, ask_user_question, ctx_execute, ctx_execute_file, ctx_index, ctx_search, ctx_batch_execute
systemPromptMode: replace
inheritProjectContext: false
inheritSkills: false
defaultContext: fork
---
# Task Manager (@task-manager)
Purpose:
You are a Task Manager (@task-manager), an expert at breaking down complex software features into small, verifiable subtasks. Your role is to create structured task plans that enable efficient, atomic implementation work.
## Core Responsibilities
- Break complex features into atomic tasks
- Create structured directories with task files and indexes
- Generate clear acceptance criteria and dependency mapping
- Follow strict naming conventions and file templates
## Mandatory Two-Phase Workflow
### Phase 1: Planning (Approval Required)
When given a complex feature request:
1. **Analyze the feature** to identify:
- Core objective and scope
- Technical risks and dependencies
- Natural task boundaries
- Testing requirements
2. **Create a subtask plan** with:
- Feature slug (kebab-case)
- Clear task sequence and dependencies
- Exit criteria for feature completion
3. **Present plan using this exact format:**```
## Subtask Plan
feature: {kebab-case-feature-name}
objective: {one-line description}
tasks:
- seq: {2-digit}, filename: {seq}-{task-description}.md, title: {clear title}
- seq: {2-digit}, filename: {seq}-{task-description}.md, title: {clear title}
dependencies:
- {seq} -> {seq} (task dependencies)
exit_criteria:
- {specific, measurable completion criteria}
Approval needed before file creation.
```
4. **Wait for explicit approval** before proceeding to Phase 2.
### Phase 2: File Creation (After Approval)
Once approved:
1. **Create directory structure:**
- Base: `tasks/{feature}/`
- Create feature README.md index
- Create individual task files
2. **Use these exact templates (Dependencies only if applicable):**
**Feature Index Template** (`tasks/{feature}/README.md`):
```
# {Feature Title}
Objective: {one-liner}
Status legend: [ ] todo, [~] in-progress, [x] done
Tasks
- [ ] {seq} — {task-description} → `{seq}-{task-description}.md`
Dependencies
- {seq} depends on {seq}
Exit criteria
- The feature is complete when {specific criteria}
```
**Task File Template** (`{seq}-{task-description}.md`):
```
# {seq}. {Title}
meta:
id: {feature}-{seq}
feature: {feature}
priority: P2
depends_on: [{dependency-ids}]
tags: [implementation, tests-required]
objective:
- Clear, single outcome for this task
deliverables:
- What gets added/changed (files, modules, endpoints)
steps:
- Step-by-step actions to complete the task
tests:
- Unit: which functions/modules to cover (ArrangeActAssert)
- Integration/e2e: how to validate behavior
acceptance_criteria:
- Observable, binary pass/fail conditions
validation:
- Commands or scripts to run and how to verify
notes:
- Assumptions, links to relevant docs or design
```
3. **Provide creation summary:**
```
## Subtasks Created
- tasks/{feature}/README.md
- tasks/{feature}/{seq}-{task-description}.md
Next suggested task: {seq} — {title}
```
## Strict Conventions
- **Naming:** Always use kebab-case for features and task descriptions
- **Sequencing:** 2-digits (01, 02, 03...) — optionally a single lowercase letter
suffix may be appended to insert a sub-task between two numbered steps without
renumbering siblings (e.g. `02b`, `02c` for sub-tasks of `02`). The parser
normalizes `2b` → `02b`.
- **File pattern:** `{seq}-{task-description}.md`
- **Dependencies:** Always map task relationships (if applicable)
- **Tests:** Every task must include test requirements
- **Acceptance:** Must have binary pass/fail criteria
## Quality Guidelines
- Keep tasks atomic and implementation-ready
- Include clear validation steps
- Specify exact deliverables (files, functions, endpoints)
- Use functional, declarative language
- Avoid unnecessary complexity
- Ensure each task can be completed independently (given dependencies)
## Available Tools
You have access to: read,edit,write,grep,glob,patch (but NOT bash)
You cannot modify: .env files, .key files, .secret files, node_modules, .git
## Response Instructions
- Always follow the two-phase workflow exactly
- Use the exact templates and formats provided
- Wait for approval after Phase 1
- Provide clear, actionable task breakdowns
- Include all required metadata and structure
Break down the complex features into subtasks and create a task plan. Put all tasks in the /tasks/ directory.
Remember: plan first, understnad the request, how the task can be broken up and how it is connected and important to the overall objective. We want high level functions with clear objectives and deliverables in the subtasks.
---
User request: $@

35
src/constants.ts Normal file
View File

@@ -0,0 +1,35 @@
import { DEFAULT_CONFIG } from "./types";
export { DEFAULT_CONFIG };
// CLI
export const SLASH_COMMAND = "/ralpi";
export const COMMANDS = [
"run",
"plan",
"status",
"resume",
"next",
"reset",
] as const;
// Task file detection
export const TASK_FILE_NAMES = [
"README.md",
"PRD.md",
"tasks.md",
"tasks.yaml",
"tasks.yml",
] as const;
// Reflection parsing
export const REFLECTION_HEADER = "## REFLECTION";
export const REFLECTION_PATTERN = /##\s*REFLECTION\s*\n([\s\S]*?)(?=\n```|$)/i;
// Review verdict parsing
export const REVIEW_HEADER = "## REVIEW VERDICT";
export const REVIEW_PATTERN =
/##\s*REVIEW\s+VERDICT\s*\n([\s\S]*?)(?=\n```|$)/i;
// Pi subprocess
export const DEFAULT_PI_ARGS = ["--no-stream"] as const;

540
src/dag.ts Normal file
View File

@@ -0,0 +1,540 @@
import type {
Task,
ExecutionBatch,
ExecutionPlan,
Project,
ParallelGroup,
} from "./types";
// ─── Blocked Tasks ───────────────────────────────────────────────────────────
/**
* Find tasks that are blocked (direct or transitive) due to failed dependencies.
* Returns a Set of blocked task IDs.
*/
export function getBlockedTasks(
pendingTasks: Task[],
failedTaskIds: Set<string>,
): Set<string> {
const blocked = new Set<string>();
let changed = true;
while (changed) {
changed = false;
for (const task of pendingTasks) {
if (blocked.has(task.id)) continue;
const deps = task.dependencies || [];
if (deps.some((dep) => failedTaskIds.has(dep) || blocked.has(dep))) {
blocked.add(task.id);
changed = true;
}
}
}
return blocked;
}
// ─── Main Entry ──────────────────────────────────────────────────────────────
/**
* Build an execution plan from project tasks using DAG analysis.
* Returns ordered batches of parallelizable tasks.
*/
export function buildExecutionPlan(
project: Project,
completed: Set<string>,
parallelGroup?: number,
failedTaskIds: Set<string> = new Set(),
): ExecutionPlan {
// Filter out already completed AND failed tasks
// Failed tasks should not be re-scheduled — they're only re-attempted
// via the retry mechanism inside executeTask, not via the DAG.
const pendingTasks = project.tasks.filter(
(t) => !completed.has(t.id) && !failedTaskIds.has(t.id),
);
const skippedTasks = project.tasks.filter(
(t) => completed.has(t.id) || failedTaskIds.has(t.id),
);
// With explicitly declared parallel groups, all groups are independent.
// Since there are no cross-group dependencies by definition, standard
// Kahn's algorithm produces the correct plan — tasks ready in any group
// appear in the same batch, and intra-group dependencies (e.g. "21 must
// be done before 22, 23, 24") are respected automatically.
// The parallel groups are preserved as metadata for display/documentation.
if (project.parallelGroups && project.parallelGroups.length > 0) {
return {
batches: buildGroupAwareBatches(project, pendingTasks, failedTaskIds),
totalTasks: pendingTasks.length,
skippedTasks,
};
}
// If parallel_group is explicitly set (legacy config flag), use group-based batching
if (parallelGroup !== undefined) {
return {
batches: buildParallelGroupBatchesLegacy(pendingTasks, failedTaskIds),
totalTasks: pendingTasks.length,
skippedTasks,
};
}
// Use dependency-based Kahn's algorithm
return {
batches: buildBatches(pendingTasks, failedTaskIds),
totalTasks: pendingTasks.length,
skippedTasks,
};
}
// ─── Sequential Plan ─────────────────────────────────────────────────────────
/**
* Build a sequential execution plan (one task per batch)
*/
export function buildSequentialPlan(
project: Project,
completed: Set<string>,
failedTaskIds: Set<string> = new Set(),
): ExecutionPlan {
const pendingTasks = project.tasks.filter((t) => !completed.has(t.id));
// Mark tasks with failed dependencies as skipped
const blocked = getBlockedTasks(pendingTasks, failedTaskIds);
const skippedTasks = project.tasks.filter(
(t) => completed.has(t.id) || blocked.has(t.id),
);
const activeTasks = pendingTasks.filter((t) => !blocked.has(t.id));
const batches: ExecutionBatch[] = activeTasks.map((task, i) => ({
tasks: [task],
batchIndex: i,
}));
return {
batches,
totalTasks: pendingTasks.length,
skippedTasks,
};
}
// ─── Kahn's Algorithm (Dependency-Based Batching) ────────────────────────────
function buildBatches(
pendingTasks: Task[],
failedTaskIds: Set<string>,
): ExecutionBatch[] {
const batches: ExecutionBatch[] = [];
const done = new Set<string>();
const blocked = getBlockedTasks(pendingTasks, failedTaskIds);
const pendingSet = new Set(pendingTasks.map((t) => t.id));
const remaining = new Set(
pendingTasks.filter((t) => !blocked.has(t.id)).map((t) => t.id),
);
while (remaining.size > 0) {
// Find tasks whose dependencies are all satisfied
const ready: Task[] = [];
for (const task of pendingTasks) {
if (!remaining.has(task.id)) continue;
const deps = task.dependencies || [];
const depsSatisfied = deps.every(
(dep) => done.has(dep) || !pendingSet.has(dep),
);
if (depsSatisfied) {
ready.push(task);
}
}
// Cycle detection: no tasks ready but some remain
if (ready.length === 0) {
const cycleTasks = Array.from(remaining);
throw new Error(
`Dependency cycle detected among tasks: ${cycleTasks.join(", ")}`,
);
}
batches.push({ tasks: ready, batchIndex: batches.length });
for (const task of ready) {
done.add(task.id);
remaining.delete(task.id);
}
}
return batches;
}
// ─── Group-Aware Batching ────────────────────────────────────────────────────
/**
* Build batches respecting both explicit parallel groups and intra-group
* dependencies. Since parallel group declarations imply no cross-group
* dependencies, all tasks whose dependencies are satisfied — across any
* group — can run concurrently in the same batch. This means groups
* "proceed independently" as the user specified: tasks from different
* groups can appear in the same batch when ready.
*
* Intra-group dependencies (e.g., "21 must be done before 22, 23, 24")
* are handled by Kahn's algorithm: if 21 has deps satisfied but 22 doesn't,
* only 21 appears in the current batch.
*/
function buildGroupAwareBatches(
_project: Project,
pendingTasks: Task[],
failedTaskIds: Set<string>,
): ExecutionBatch[] {
const blocked = getBlockedTasks(pendingTasks, failedTaskIds);
const activeTasks = pendingTasks.filter((t) => !blocked.has(t.id));
// Standard Kahn's algorithm across ALL tasks — parallel groups are
// metadata for display, not scheduling constraints.
const pendingSet = new Set(pendingTasks.map((t) => t.id));
const done = new Set<string>();
const remaining = new Set(activeTasks.map((t) => t.id));
const batches: ExecutionBatch[] = [];
while (remaining.size > 0) {
const ready: Task[] = [];
for (const task of activeTasks) {
if (!remaining.has(task.id)) continue;
const deps = task.dependencies || [];
const depsSatisfied = deps.every(
(dep) => done.has(dep) || !pendingSet.has(dep),
);
if (depsSatisfied) {
ready.push(task);
}
}
if (ready.length === 0) {
throw new Error(
`Dependency cycle detected: ${Array.from(remaining).join(", ")}`,
);
}
batches.push({ tasks: ready, batchIndex: batches.length });
for (const task of ready) {
done.add(task.id);
remaining.delete(task.id);
}
}
return batches;
}
// ─── Legacy Parallel Group Batching ─────────────────────────────────────────
/**
* Legacy: build batches from explicit parallel_group values only.
* Groups execute in ascending order; tasks within a group run concurrently.
* Does NOT respect intra-group dependencies.
*/
function buildParallelGroupBatchesLegacy(
pendingTasks: Task[],
failedTaskIds: Set<string>,
): ExecutionBatch[] {
const blocked = getBlockedTasks(pendingTasks, failedTaskIds);
const activeTasks = pendingTasks.filter((t) => !blocked.has(t.id));
const groups = new Map<number, Task[]>();
for (const task of activeTasks) {
const group = task.parallelGroup ?? 0;
if (!groups.has(group)) groups.set(group, []);
groups.get(group)!.push(task);
}
const sortedGroups = Array.from(groups.entries()).sort((a, b) => a[0] - b[0]);
return sortedGroups.map(([_groupNum, tasks], i) => ({
tasks,
batchIndex: i,
}));
}
// ─── Cycle Detection ─────────────────────────────────────────────────────────
/**
* Detect cycles in the task dependency graph
*/
export function detectCycles(project: Project): string[] {
const adj = new Map<string, string[]>();
for (const task of project.tasks) {
adj.set(task.id, task.dependencies || []);
}
const WHITE = 0;
const GRAY = 1;
const BLACK = 2;
const color = new Map<string, number>();
for (const task of project.tasks) {
color.set(task.id, WHITE);
}
const cycleNodes: string[] = [];
function dfs(node: string): boolean {
color.set(node, GRAY);
const deps = adj.get(node) || [];
for (const dep of deps) {
if (!adj.has(dep)) continue;
const depColor = color.get(dep);
if (depColor === GRAY) {
cycleNodes.push(dep);
return true;
}
if (depColor === WHITE && dfs(dep)) {
cycleNodes.push(node);
return true;
}
}
color.set(node, BLACK);
return false;
}
for (const task of project.tasks) {
if (color.get(task.id) === WHITE) {
dfs(task.id);
}
}
return [...new Set(cycleNodes)];
}
// ─── Ready Tasks ─────────────────────────────────────────────────────────────
/**
* Get tasks that are ready to execute (all dependencies completed)
*/
export function getReadyTasks(
project: Project,
completed: Set<string>,
): Task[] {
return project.tasks.filter((task) => {
if (completed.has(task.id)) return false;
const deps = task.dependencies || [];
return deps.every((dep) => completed.has(dep));
});
}
// ─── Critical Path ───────────────────────────────────────────────────────────
/**
* Calculate the critical path (longest path through the DAG)
*/
export function getCriticalPath(project: Project): Task[] {
const taskMap = new Map(project.tasks.map((t) => [t.id, t]));
const dist = new Map<string, number>();
const prev = new Map<string, string | null>();
// Initialize
for (const task of project.tasks) {
dist.set(task.id, 1);
prev.set(task.id, null);
}
// Topological sort
const sorted: Task[] = [];
const visited = new Set<string>();
function visit(id: string) {
if (visited.has(id)) return;
visited.add(id);
const task = taskMap.get(id);
if (!task) return;
for (const dep of task.dependencies || []) {
visit(dep);
}
sorted.push(task);
}
for (const task of project.tasks) {
visit(task.id);
}
// Relax edges
for (const task of sorted) {
for (const dep of task.dependencies || []) {
const depDist = dist.get(dep);
if (depDist === undefined) continue;
const newDist = depDist + 1;
const currentDist = dist.get(task.id) ?? 0;
if (newDist > currentDist) {
dist.set(task.id, newDist);
prev.set(task.id, dep);
}
}
}
// Trace back from the longest path end
let maxTask = project.tasks[0];
for (const task of project.tasks) {
const taskDist = dist.get(task.id) ?? 0;
const maxDist = dist.get(maxTask.id) ?? 0;
if (taskDist > maxDist) {
maxTask = task;
}
}
const path: Task[] = [];
let current: string | null = maxTask.id;
while (current) {
const task = taskMap.get(current);
if (task) path.unshift(task);
current = prev.get(current) || null;
}
return path;
}
// ─── Format Dependency Chain ─────────────────────────────────────────────────
/**
* Format the dependency DAG as a tree for display.
* Rooted at tasks with no dependencies, showing what depends on what.
*/
export function formatDependencyChain(project: Project): string {
const taskMap = new Map(project.tasks.map((t) => [t.id, t]));
const lines: string[] = [];
lines.push("## Dependency Chain");
lines.push("");
if (project.tasks.length === 0) {
lines.push("(no tasks)");
return lines.join("\n");
}
// Build reverse dependency map: taskId → [dependent taskIds]
const dependents = new Map<string, string[]>();
for (const task of project.tasks) {
dependents.set(task.id, []);
}
for (const task of project.tasks) {
for (const dep of task.dependencies) {
if (dependents.has(dep)) {
dependents.get(dep)!.push(task.id);
}
}
}
// Root tasks: those with no dependencies
const roots = project.tasks.filter((t) => t.dependencies.length === 0);
const rendered = new Set<string>();
function renderNode(taskId: string, prefix: string, isLast: boolean): void {
const task = taskMap.get(taskId);
if (!task) return;
const alreadyRendered = rendered.has(taskId);
rendered.add(taskId);
const connector = prefix ? (isLast ? "└── " : "├── ") : "";
if (alreadyRendered) {
lines.push(`${prefix}${connector}${task.id} · ${task.title}`);
return;
}
const deps =
task.dependencies.length > 0
? ` ← needs ${task.dependencies.join(", ")}`
: " (root)";
lines.push(
`${prefix}${connector}${task.id} · ${task.title}${prefix ? "" : deps}`,
);
const children = (dependents.get(taskId) || [])
.filter((c) => c !== taskId)
.sort();
for (let i = 0; i < children.length; i++) {
const childPrefix = prefix + (isLast ? " " : "│ ");
renderNode(children[i], childPrefix, i === children.length - 1);
}
}
for (let i = 0; i < roots.length; i++) {
renderNode(roots[i].id, "", i === roots.length - 1);
}
// Tasks not reached from any root (have deps but no root-traversable path)
const unreached = project.tasks.filter((t) => !rendered.has(t.id));
if (unreached.length > 0) {
lines.push("");
lines.push("Orphan tasks (dependencies not in task list):");
for (const t of unreached) {
const deps =
t.dependencies.length > 0
? ` ← needs ${t.dependencies.join(", ")}`
: "";
lines.push(` ${t.id} · ${t.title}${deps}`);
}
}
return lines.join("\n");
}
// ─── Format Execution Plan ───────────────────────────────────────────────────
/**
* Format the execution plan for display
*/
/**
* Format the execution plan for display, optionally with parallel group annotations
*/
export function formatExecutionPlan(
plan: ExecutionPlan,
parallelGroups?: ParallelGroup[],
): string {
const lines: string[] = [];
lines.push("## Execution Plan");
lines.push("");
lines.push(`Total tasks: ${plan.totalTasks}`);
lines.push(`Batches: ${plan.batches.length}`);
// Build a lookup: taskId → group label
const groupLabel = new Map<string, string>();
if (parallelGroups) {
for (const g of parallelGroups) {
for (const id of g.taskIds) {
if (g.label) {
groupLabel.set(id, g.label);
}
}
}
}
if (plan.skippedTasks.length > 0) {
lines.push(
`Already completed: ${plan.skippedTasks.map((t) => t.id).join(", ")}`,
);
}
lines.push("");
for (const batch of plan.batches) {
lines.push(`### Batch ${batch.batchIndex + 1}`);
for (const task of batch.tasks) {
const annotation = groupLabel.has(task.id)
? ` _(${groupLabel.get(task.id)})_`
: "";
const deps =
task.dependencies.length > 0
? ` ← needs ${task.dependencies.join(", ")}`
: "";
lines.push(`- ${task.id}: ${task.title}${annotation}${deps}`);
}
lines.push("");
}
return lines.join("\n");
}

274
src/diff.ts Normal file
View File

@@ -0,0 +1,274 @@
/**
* Reusable unified-diff engine: parses a diff into per-file +/ stats and
* filters out noise files (locks, build output, vendor, generated, media
* binaries) so review prompts feed the model only clean, review-relevant
* changes.
*
* Ported from @piex-dev/review's `EXCLUDED_PATTERNS` + `parseDiff` (MIT).
* Kept the excluded-files-not-totaled behavior that fixed the upstream
* double-count bug.
*/
// ─── Types ──────────────────────────────────────────────────────────────────
/** Per-file diff stats. */
export interface FileDiff {
/** File path as it appears in the diff (`a/` path). */
path: string;
/** Number of added lines (excluding the `+++` header). */
linesAdded: number;
/** Number of removed lines (excluding the `---` header). */
linesRemoved: number;
/** File extension (empty when the path has none). */
ext: string;
}
/** An excluded (noise) file with the reason it was filtered. */
export interface ExcludedFile extends FileDiff {
/** Why the file was excluded (e.g. "lockfile"). */
reason: string;
}
/** Result of parsing a unified diff. */
export interface DiffSummary {
/** Files kept in scope (review-relevant). */
files: FileDiff[];
/** Files filtered out as noise. */
excluded: ExcludedFile[];
/** Sum of added lines over included files only. */
totalAdded: number;
/** Sum of removed lines over included files only. */
totalRemoved: number;
}
/** Caller-supplied overrides for the noise filter. */
export interface DiffOptions {
/** Additional exclusion regexes merged into EXCLUDED_PATTERNS. */
extraPatterns?: RegExp[];
/** Pathspec allowlist — files matching these stay in scope even if a
* default rule would exclude them. */
ignorePaths?: string[];
}
// ─── Noise-Filter Rules ─────────────────────────────────────────────────────
/** Default noise-exclusion rules, ported from @piex-dev/review (MIT).
* Each entry is a regex tested against the file path plus a human-readable
* reason surfaced in the "Excluded Files" prompt section. */
export const EXCLUDED_PATTERNS: { pattern: RegExp; reason: string }[] = [
// Lockfiles
{ pattern: /(^|\/)package-lock\.json$/i, reason: "lockfile" },
{ pattern: /(^|\/)yarn\.lock$/i, reason: "lockfile" },
{ pattern: /(^|\/)pnpm-lock\.yaml$/i, reason: "lockfile" },
{ pattern: /(^|\/)Cargo\.lock$/i, reason: "lockfile" },
{ pattern: /(^|\/)Gemfile\.lock$/i, reason: "lockfile" },
{ pattern: /\.lock$/i, reason: "lockfile" },
// Minified assets
{ pattern: /\.min\.(js|css)$/i, reason: "minified asset" },
// Generated / tooling output
{ pattern: /\.generated\./i, reason: "generated file" },
{ pattern: /\.snap$/i, reason: "snapshot" },
{ pattern: /\.map$/i, reason: "source map" },
// Build output directories
{ pattern: /(^|\/)(dist|build|out|coverage)\//i, reason: "build output" },
// Dependency trees
{ pattern: /(^|\/)node_modules\//i, reason: "dependency" },
{ pattern: /(^|\/)vendor\//i, reason: "vendored dependency" },
// Image / font / binary extensions
{
pattern:
/\.(png|jpe?g|gif|webp|svg|ico|avif|bmp|woff2?|ttf|otf|eot|pdf|zip|tar|gz|mp[34]|wav|ogg|flac|wasm|bin|exe|dll|so|a|o|class|jar|pyc)$/i,
reason: "binary/media asset",
},
];
/**
* Return the exclusion reason for a file path, or undefined when the file is
* review-relevant. Extra caller-supplied patterns are merged into the default
* rule set.
*/
export function isExcluded(
fp: string,
extraPatterns?: RegExp[],
): string | undefined {
for (const rule of EXCLUDED_PATTERNS) {
if (rule.pattern.test(fp)) return rule.reason;
}
if (extraPatterns) {
for (const p of extraPatterns) {
if (p.test(fp)) return "extra ignore pattern";
}
}
return undefined;
}
/**
* Safely compile user-supplied regex strings into RegExp objects. Invalid
* patterns (that don't compile) are skipped so a bad config value never
* crashes review prompt building.
*/
export function compileIgnorePatterns(patterns: string[]): RegExp[] {
const out: RegExp[] = [];
for (const p of patterns) {
if (!p) continue;
try {
out.push(new RegExp(p));
} catch {
// Skip malformed patterns silently
}
}
return out;
}
// ─── Chunking + Counting Helpers ────────────────────────────────────────────
/** Split a raw diff into per-file chunks, each starting at a `diff --git`
* line. The leading non-diff preamble (e.g. a `--stat` block) is dropped —
* per-file stats are derived from the patch chunks themselves. */
function chunkDiff(raw: string): string[] {
if (!raw) return [];
const lines = raw.split("\n");
const chunks: string[] = [];
let current: string[] = [];
let started = false;
for (const line of lines) {
if (line.startsWith("diff --git ")) {
if (started && current.length > 0) chunks.push(current.join("\n"));
current = [line];
started = true;
} else if (started) {
current.push(line);
}
}
if (started && current.length > 0) chunks.push(current.join("\n"));
return chunks;
}
/** Parse the `a/<path>` from a `diff --git a/… b/…` header. Returns null for
* malformed chunks that lack the a/… b/… header (guarded, never crashes). */
function chunkPath(chunk: string): string | null {
const m = chunk.match(/^diff --git a\/(.+?) b\//);
return m ? m[1] : null;
}
/** Count added/removed lines in a chunk, excluding the `+++`/`---` headers. */
function countLines(chunk: string): { added: number; removed: number } {
let added = 0;
let removed = 0;
for (const line of chunk.split("\n")) {
if (line.startsWith("+") && !line.startsWith("+++")) added++;
else if (line.startsWith("-") && !line.startsWith("---")) removed++;
}
return { added, removed };
}
/** Extract the file extension from a path (no ext → empty string). */
function getExt(fp: string): string {
const base = fp.split("/").pop() ?? "";
const idx = base.lastIndexOf(".");
return idx > 0 ? base.slice(idx + 1) : "";
}
/** Convert a git pathspec glob into a regex (supports `*`, `**`, `?`). */
function globToRegExp(glob: string): RegExp {
let re = "";
for (let i = 0; i < glob.length; i++) {
const c = glob[i];
if (c === "*") {
if (glob[i + 1] === "*") {
re += ".*";
i++;
} else {
re += "[^/]*";
}
} else if (c === "?") {
re += "[^/]";
} else if (c === ".") {
re += "\\.";
} else {
re += c;
}
}
return new RegExp(`^${re}$`);
}
/** Whether a file path matches a pathspec allowlist entry. */
function matchesPathspec(pathspec: string, fp: string): boolean {
const ps = pathspec.trim();
if (!ps) return false;
// Directory prefix: "tests/" or a bare dir name matches everything under it.
if (ps.endsWith("/") && fp.startsWith(ps)) return true;
if (ps.includes("*") || ps.includes("?")) return globToRegExp(ps).test(fp);
// Plain path — exact file or prefix directory.
if (fp === ps) return true;
if (fp.startsWith(ps + "/")) return true;
return false;
}
/** Decide whether a file path is kept in scope or noise-excluded. */
function classify(
path: string,
opts?: DiffOptions,
): { kept: boolean; reason?: string } {
const reason = isExcluded(path, opts?.extraPatterns);
if (reason === undefined) return { kept: true };
// Excluded by a rule, but an ignorePaths allowlist can keep it in scope.
const keptByPathspec =
opts?.ignorePaths?.some((ps) => matchesPathspec(ps, path)) ?? false;
return keptByPathspec ? { kept: true } : { kept: false, reason };
}
// ─── Public API ─────────────────────────────────────────────────────────────
/**
* Parse a unified diff into per-file +/ stats, splitting excluded (noise)
* files from included files. Totals are summed over included files only.
* Malformed chunks (no a/… b/… header) are skipped without crashing.
*/
export function parseDiff(raw: string, opts?: DiffOptions): DiffSummary {
const files: FileDiff[] = [];
const excluded: ExcludedFile[] = [];
let totalAdded = 0;
let totalRemoved = 0;
for (const chunk of chunkDiff(raw)) {
if (!chunk) continue;
const path = chunkPath(chunk);
if (path === null) continue; // malformed chunk — skip
const { added, removed } = countLines(chunk);
const base: FileDiff = {
path,
linesAdded: added,
linesRemoved: removed,
ext: getExt(path),
};
const decision = classify(path, opts);
if (decision.kept) {
files.push(base);
totalAdded += added;
totalRemoved += removed;
} else if (decision.reason) {
excluded.push({ ...base, reason: decision.reason });
}
}
return { files, excluded, totalAdded, totalRemoved };
}
/**
* Return the diff re-emitted with excluded (noise) file chunks removed, so an
* inlined review diff never contains filtered content. The stat preamble is
* dropped — the per-file summary table carries that information. Empty string
* when every changed file is noise.
*/
export function filterNoise(raw: string, opts?: DiffOptions): string {
const kept: string[] = [];
for (const chunk of chunkDiff(raw)) {
if (!chunk) continue;
const path = chunkPath(chunk);
if (path === null) continue;
const decision = classify(path, opts);
if (decision.kept) kept.push(chunk);
}
return kept.join("\n");
}

1918
src/executor.ts Normal file

File diff suppressed because it is too large Load Diff

773
src/parser.ts Normal file
View File

@@ -0,0 +1,773 @@
import * as fs from "node:fs";
import * as path from "node:path";
import type { Task, Project, ParallelGroup, Phase } from "./types";
// Lazy-loaded yaml package
let YAML_module: typeof import("yaml") | undefined;
function loadYaml(): typeof import("yaml") {
if (YAML_module) return YAML_module;
try {
YAML_module = require("yaml");
} catch {
throw new Error(
"YAML parsing requires the 'yaml' package. Run: npm install yaml",
);
}
return YAML_module!;
}
// ─── Main Entry ──────────────────────────────────────────────────────────────
/**
* Parse a task file (markdown or YAML) into a Project structure.
* Supports:
* - Fio README format (numbered tasks with dependency graph)
* - Phased format (## Phase N — Title sections with tasks and dependencies)
* - Simple checkbox format (- [ ] task)
* - YAML format (tasks: [...])
*/
export function parseTaskFile(filePath: string): Project {
const absolutePath = path.resolve(filePath);
const content = fs.readFileSync(absolutePath, "utf-8");
const ext = path.extname(filePath).toLowerCase();
const dir = path.dirname(absolutePath);
if (ext === ".yaml" || ext === ".yml") {
return parseYaml(content, absolutePath, dir);
}
// Markdown: detect format
if (hasDependenciesSection(content) || hasPhaseHeadings(content)) {
return parseFioFormat(content, absolutePath, dir);
}
return parseSimpleCheckbox(content, absolutePath, dir);
}
// ─── Fio Format Parser ───────────────────────────────────────────────────────
/** Match both markdown heading (## Dependencies) and plain heading (Dependencies). */
const DEP_HEADING_RE = /^(?:##\s+)?Dependencies\s*$/m;
/** Match both markdown heading (## Tasks) and plain heading (Tasks). */
const TASK_HEADING_RE = /^(?:##\s+)?Tasks\s*$/m;
/** Match other markdown headings (## Something). */
const ANY_MD_HEADING_RE = /^##\s/;
/** Match phase headings: ## Phase 1 — Push-to-Talk MVP */
const PHASE_HEADING_RE = /^\s*##\s+Phase\s+(\d+)\s*[—–:-]\s*(.+)$/i;
/** Detect plain phase headings too: Phase 1 — Title (no ##) */
const PHASE_HEADING_PLAIN_RE = /^Phase\s+(\d+)\s*[—–:-]\s*(.+)$/i;
/**
* Detect a plain (non-markdown) section heading like "Exit criteria".
* A plain heading must:
* - Start with a letter
* - Contain only letters and spaces
* - Have no colons (avoids matching "Objective:" and "Status legend:")
* - Not be a task/dep line (doesn't start with "-")
*/
function isPlainSectionHeader(line: string): boolean {
const trimmed = line.trim();
return trimmed.length > 0 && /^[A-Za-z][A-Za-z\s]*$/.test(trimmed);
}
function hasDependenciesSection(content: string): boolean {
return DEP_HEADING_RE.test(content);
}
function hasPhaseHeadings(content: string): boolean {
return PHASE_HEADING_RE.test(content) || PHASE_HEADING_PLAIN_RE.test(content);
}
function parseFioFormat(
content: string,
sourcePath: string,
sourceDir: string,
): Project {
const lines = content.split("\n");
const tasks: Task[] = [];
const dependencies: Record<string, string[]> = {};
const parallelGroups: ParallelGroup[] = [];
const phases: Phase[] = [];
let currentPhase: number | null = null;
let currentPhaseTitle = "";
let inTasks = false;
let inDeps = false;
for (const line of lines) {
// Check for phase headings first
const phaseMatch =
line.match(PHASE_HEADING_RE) || line.match(PHASE_HEADING_PLAIN_RE);
if (phaseMatch) {
// Save previous phase if exists
if (currentPhase !== null) {
const phaseTaskIds = tasks
.filter((t) => t.phase === currentPhase)
.map((t) => t.id);
if (phaseTaskIds.length > 0) {
phases.push({
number: currentPhase,
title: currentPhaseTitle,
taskIds: phaseTaskIds,
});
}
}
// Start new phase
currentPhase = parseInt(phaseMatch[1], 10);
currentPhaseTitle = phaseMatch[2].trim();
inTasks = true;
inDeps = false;
continue;
}
if (TASK_HEADING_RE.test(line)) {
inTasks = true;
inDeps = false;
continue;
}
if (DEP_HEADING_RE.test(line)) {
inTasks = false;
inDeps = true;
continue;
}
// Reset state on any other section heading — both ##-style and plain
// BUT NOT phase headings (already handled above)
if (
(ANY_MD_HEADING_RE.test(line) || isPlainSectionHeader(line)) &&
!TASK_HEADING_RE.test(line) &&
!DEP_HEADING_RE.test(line) &&
!PHASE_HEADING_RE.test(line) &&
!PHASE_HEADING_PLAIN_RE.test(line)
) {
inTasks = false;
inDeps = false;
continue;
}
if (inTasks) {
// Match all tasks on a line (supports compact single-line formats).
// ID is digits optionally followed by a single lowercase letter
// (e.g. "01", "02b", "10c") — see normalizeTaskId for the shape.
const taskPattern =
/-+\s+\[(.)\]\s+(\d+[a-z]?)\s+[—–:-]\s+(.+?)(?:\s+(?=-+\s+\[)|\s*→\s*`([^`]+)`|$)/g;
let match: RegExpExecArray | null;
while ((match = taskPattern.exec(line)) !== null) {
const [, status, id, title, file] = match;
const timeoutMs = parseTimeoutFromLine(line);
tasks.push({
id: normalizeTaskId(id),
title: title.trim(),
description: undefined,
file: file || undefined,
status: charToStatus(status),
dependencies: [],
timeoutMs,
index: tasks.length,
phase: currentPhase ?? undefined,
});
}
}
if (inDeps) {
// Arrow notation (supports both -> and unicode \u2192)
// "01 -> 02,03,06" means 02, 03, 06 depend on 01
// "02 \u2192 08" — single arrow with unicode
// "03 \u2192 04 \u2192 05" — chained: 04 depends on 03, 05 depends on 04
// "05, 07, 08 \u2192 13" — multi-prereq: 13 depends on 05, 07, 08
// Supports optional markdown list prefix: "- 01 -> 02,03,06"
const hasArrow = /->/.test(line) || /\u2192/.test(line);
if (hasArrow) {
// Strip optional list prefix and parenthetical description
const cleaned = line
.replace(/^(\s*[-*]\s+)?/, "")
.replace(/\s*\(.*\)\s*$/, "");
// Split on arrows to get segments
const segments = cleaned
.split(/->|\u2192/)
.map((s) => s.trim())
.filter(Boolean);
if (segments.length >= 2) {
for (let i = 0; i < segments.length - 1; i++) {
// Left segment: source(s) (comma-separated)
const fromIds = segments[i]
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
// Right segment: target(s) (comma-separated)
const toIds = segments[i + 1]
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
for (const toId of toIds) {
if (!dependencies[toId]) dependencies[toId] = [];
for (const fromId of fromIds) {
if (!dependencies[toId].includes(fromId)) {
dependencies[toId].push(fromId);
}
}
}
}
}
}
// Format 1: Natural language "X depends on A, B, C"
// Supports optional markdown list prefix: "- 13 depends on 17, 18, 19"
// Also handles "also depends on": "- 08 also depends on 05, 06"
// The dep list char class includes lowercase letters so lettered IDs
// (e.g. "02b") don't truncate the capture. Per-id validation is
// done by the filter below, so trailing prose can't leak in.
const dependsMatch = line.match(
/^(?:\s*[-*]\s+)?(\d+[a-z]?)\s+(?:also\s+)?depends\s+on\s+([\d,\s a-z]+)/i,
);
if (dependsMatch) {
const [, taskId, depsList] = dependsMatch;
const taskIdPadded = normalizeTaskId(taskId);
const depIds = depsList
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
if (!dependencies[taskIdPadded]) dependencies[taskIdPadded] = [];
for (const depId of depIds) {
if (!dependencies[taskIdPadded].includes(depId)) {
dependencies[taskIdPadded].push(depId);
}
}
}
// Parse meta blocks for task configuration (timeout, etc.)
const metaMatch = line.match(
/^0?(\d+[a-z]?)\s+\[timeout\]\s*=?\s*(\d+)(?:m|min|s|ms)?/i,
);
if (metaMatch) {
const [, taskId, value, unit] = metaMatch;
const task = tasks.find((t) => t.id === normalizeTaskId(taskId));
if (task) {
task.timeoutMs = parseTimeoutValue(Number(value), unit);
}
}
// Format 2: "X, Y, Z can be done in parallel (label)"
// "- 01, 02, 03, 04 can be done in parallel (Play Store prep)"
const parallelMatch = line.match(
/^(?:\s*[-*]\s+)?((?:0?\d+[a-z]?\s*,\s*)*0?\d+[a-z]?)\s+can\s+be\s+done\s+in\s+parallel(?:\s+\(([^)]+)\))?$/i,
);
if (parallelMatch) {
const [, idsStr, label] = parallelMatch;
const taskIds = idsStr
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
if (taskIds.length > 0) {
parallelGroups.push({
index: parallelGroups.length,
label: label ? label.trim() : undefined,
taskIds,
});
}
}
// Format 3: "A must be done before B, C" or "A, B must be done before C"
// "- 21 must be done before 22, 23, 24 (backend integration foundation)"
// "- 02, 03 must be done before 04"
const mustBeforeMatch = line.match(
/^(?:\s*[-*]\s+)?((?:0?\d+[a-z]?\s*,\s*)*0?\d+[a-z]?)\s+must\s+be\s+done\s+before\s+((?:0?\d+[a-z]?\s*,\s*)*0?\d+[a-z]?)(?:\s+\(([^)]+)\))?$/i,
);
if (mustBeforeMatch) {
const [, fromIdsStr, toIdsStr] = mustBeforeMatch;
const fromIds = fromIdsStr
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
const toIds = toIdsStr
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
// Each "to" task depends on ALL "from" tasks
for (const toId of toIds) {
if (!dependencies[toId]) dependencies[toId] = [];
for (const fromId of fromIds) {
if (!dependencies[toId].includes(fromId)) {
dependencies[toId].push(fromId);
}
}
}
}
// Format 4: "X, Y, Z depend on A" or "X depends on A, B, C"
// "- 22, 23, 24 depend on 21"
// "- 05, 06 depend on 02, 03, 04"
// "- 08 also depends on 05, 06" ("also" is ignored)
// Strip optional "also" before matching
const cleanedLine = line.replace(/\balso\b/i, "");
const dependOnMatch = cleanedLine.match(
/^(?:\s*[-*]\s+)?((?:0?\d+[a-z]?\s*,\s*)*0?\d+[a-z]?)\s+depend(?:s)?\s+on\s+((?:0?\d+[a-z]?\s*,\s*)*0?\d+[a-z]?)(?:\s+\(([^)]+)\))?$/i,
);
if (dependOnMatch) {
const [, fromIdsStr, toIdsStr] = dependOnMatch;
const fromIds = fromIdsStr
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
const toIds = toIdsStr
.split(",")
.map((t) => t.trim())
.filter((t) => /^\d+[a-z]?$/.test(t))
.map((t) => normalizeTaskId(t));
// Each "from" task depends on ALL "to" tasks
for (const fromId of fromIds) {
if (!dependencies[fromId]) dependencies[fromId] = [];
for (const toId of toIds) {
if (!dependencies[fromId].includes(toId)) {
dependencies[fromId].push(toId);
}
}
}
}
}
}
// Save final phase if we were in one
if (currentPhase !== null) {
const phaseTaskIds = tasks
.filter((t) => t.phase === currentPhase)
.map((t) => t.id);
if (phaseTaskIds.length > 0) {
phases.push({
number: currentPhase,
title: currentPhaseTitle,
taskIds: phaseTaskIds,
});
}
}
// Add implicit phase-boundary dependencies
// First task of each phase (except phase 1) depends on last task of previous phase
if (phases.length > 1) {
for (let i = 1; i < phases.length; i++) {
const prevPhase = phases[i - 1];
const currPhase = phases[i];
if (prevPhase.taskIds.length === 0 || currPhase.taskIds.length === 0)
continue;
const lastTaskOfPrevPhase =
prevPhase.taskIds[prevPhase.taskIds.length - 1];
const firstTaskOfCurrPhase = currPhase.taskIds[0];
// Add dependency if not already present
if (!dependencies[firstTaskOfCurrPhase]) {
dependencies[firstTaskOfCurrPhase] = [];
}
if (!dependencies[firstTaskOfCurrPhase].includes(lastTaskOfPrevPhase)) {
dependencies[firstTaskOfCurrPhase].push(lastTaskOfPrevPhase);
}
}
}
// Extract exit criteria — detect both ## Exit Criteria and plain Exit criteria
const exitCriteria: string[] = [];
const exitCriteriaRe = /^(?:##\s+)?Exit\s+Criteria/i;
const exitIdx = lines.findIndex((l) => exitCriteriaRe.test(l));
if (exitIdx >= 0) {
for (let i = exitIdx + 1; i < lines.length; i++) {
// Stop at any new section heading (##-style or plain)
if (/^##\s/.test(lines[i]) || isPlainSectionHeader(lines[i])) break;
const m = lines[i].match(/^-\s+(.+)$/);
if (m) exitCriteria.push(m[1].trim());
}
}
// Extract objective from top-level heading
const objectiveMatch = content.match(/^#\s+(.+)$/m);
const objective = objectiveMatch ? objectiveMatch[1].trim() : undefined;
// Apply dependencies map to task.dependencies arrays
for (const task of tasks) {
if (dependencies[task.id]) {
task.dependencies = dependencies[task.id];
}
}
// Apply parallelGroup to tasks
for (const group of parallelGroups) {
for (const taskId of group.taskIds) {
const task = tasks.find((t) => t.id === taskId);
if (task) {
task.parallelGroup = group.index;
}
}
}
return {
tasks,
dependencies,
parallelGroups: parallelGroups.length > 0 ? parallelGroups : undefined,
phases: phases.length > 0 ? phases : undefined,
sourcePath,
sourceDir,
exitCriteria,
objective,
};
}
// ─── Simple Checkbox Parser ──────────────────────────────────────────────────
function parseSimpleCheckbox(
content: string,
sourcePath: string,
sourceDir: string,
): Project {
const tasks: Task[] = [];
const lines = content.split("\n");
let idx = 0;
for (const line of lines) {
const match = line.match(/^-+\s+\[(.)\]\s+(.+)$/);
if (match) {
const [, statusChar, title] = match;
const id = `${String(idx).padStart(2, "0")}`;
tasks.push({
id,
title: title.trim(),
status: charToStatus(statusChar),
dependencies: [],
});
idx++;
}
}
return { tasks, dependencies: {}, sourcePath, sourceDir };
}
// ─── YAML Parser ─────────────────────────────────────────────────────────────
function parseYaml(
content: string,
sourcePath: string,
sourceDir: string,
): Project {
const YAML = loadYaml();
const doc = YAML.parse(content);
const tasks: Task[] = [];
if (doc.tasks && Array.isArray(doc.tasks)) {
doc.tasks.forEach((t: any, idx: number) => {
tasks.push({
id: t.id || `${String(idx).padStart(2, "0")}`,
title: t.title || t.name || `Task ${idx}`,
description: t.description,
file: t.file,
status: (t.status as Task["status"]) || "pending",
dependencies: t.depends_on || t.dependencies || [],
parallelGroup: t.parallel_group,
timeoutMs: parseTimeoutFromMeta(t.timeout),
index: idx,
});
});
}
return {
tasks,
dependencies: doc.dependencies || {},
sourcePath,
sourceDir,
exitCriteria: doc.exit_criteria || doc.exitCriteria,
objective: doc.objective,
};
}
// ─── Task Spec Reader ────────────────────────────────────────────────────────
/**
* Read the detailed task specification from a task file
*/
export function readTaskSpec(taskDir: string, taskFile: string): string {
const fullPath = path.resolve(taskDir, taskFile);
if (!fs.existsSync(fullPath)) return "";
return fs.readFileSync(fullPath, "utf-8");
}
// ─── Task File Updater ───────────────────────────────────────────────────────
/**
* Update task status in the source file (markdown or YAML).
*
* Handles three formats:
* 1. Fio numbered format: `- [ ] 01 Title` — matches by task number in the file
* 2. Simple checkbox: `- [ ] Title` — matches by checkbox position (index)
* 3. YAML: uses `yaml` library to parse, update, and stringify
*/
export function updateTaskInFile(
filePath: string,
taskId: string,
status: Task["status"],
): void {
const ext = path.extname(filePath).toLowerCase();
// Handle YAML format
if (ext === ".yaml" || ext === ".yml") {
updateTaskInYaml(filePath, taskId, status);
return;
}
let content = fs.readFileSync(filePath, "utf-8");
const char = statusToChar(status);
// Strategy 1: Fio numbered format — match by explicit task ID in the file.
// For pure-digit IDs, also try the parsed numeric form (parity with the
// pre-lettered behavior). Lettered IDs ("02b", "02c") only have one valid
// form — the parseInt fallback would silently drop the letter suffix and
// create false-positive partial matches, so we skip it for them.
const idPatterns = new Set([escapeRegex(taskId)]);
if (!taskId.startsWith("0") && /^\d+$/.test(taskId)) {
const rawId = parseInt(taskId, 10).toString();
idPatterns.add(escapeRegex(rawId));
}
for (const idPattern of idPatterns) {
const fioRegex = new RegExp(
`(^-\\s+\\[)(.)(\\]\\s+${idPattern}\\s*[—–:-])`,
"m",
);
const match = content.match(fioRegex);
if (match) {
content = content.replace(fioRegex, `$1${char}$3`);
fs.writeFileSync(filePath, content, "utf-8");
return;
}
}
// Strategy 2: Simple checkbox by position (task IDs are zero-padded indices)
const targetIndex = parseInt(taskId, 10);
if (!isNaN(targetIndex)) {
const lines = content.split("\n");
let checkboxIdx = 0;
for (let i = 0; i < lines.length; i++) {
const m = lines[i].match(/^(\s*-+\s+\[)(.)(\].*)$/);
if (m) {
if (checkboxIdx === targetIndex) {
lines[i] = m[1] + char + m[3];
fs.writeFileSync(filePath, lines.join("\n"), "utf-8");
return;
}
checkboxIdx++;
}
}
}
}
/**
* Update task status in a YAML task file using the yaml library's
* Document API, which preserves comments and formatting.
*
* Matches by explicit `id` field first, then falls back to
* position-based matching (for files without explicit IDs).
*/
function updateTaskInYaml(
filePath: string,
taskId: string,
status: Task["status"],
): void {
const YAML = loadYaml();
const content = fs.readFileSync(filePath, "utf-8");
const doc = YAML.parseDocument(content);
const tasks = doc.get("tasks");
if (!tasks || !YAML.isSeq(tasks)) return;
// Build alternate ID forms for matching. For lettered IDs ("02b"), the
// verbatim form is the only valid pattern — parseInt would drop the suffix.
const idVariants: string[] = [taskId];
if (/^\d+$/.test(taskId)) {
idVariants.push(parseInt(taskId, 10).toString());
}
// Strategy 1: Match by explicit id field
for (const item of tasks.items) {
if (!YAML.isMap(item)) continue;
const idVal = item.get("id");
if (idVal === undefined || idVal === null) continue;
const idStr = String(idVal);
if (idVariants.includes(idStr)) {
item.set("status", status);
fs.writeFileSync(filePath, String(doc), "utf-8");
return;
}
}
// Strategy 2: Fall back to position-based matching
// (for YAML files without explicit id fields)
const targetIndex = parseInt(taskId, 10);
if (!isNaN(targetIndex) && targetIndex < tasks.items.length) {
const item = tasks.items[targetIndex];
if (YAML.isMap(item)) {
item.set("status", status);
fs.writeFileSync(filePath, String(doc), "utf-8");
}
}
}
// ─── Auto-Detect Dependencies ────────────────────────────────────────────────
/**
* Auto-detect dependencies by analyzing task file references
*/
export function autoDetectDependencies(project: Project): Project {
const tasks = project.tasks.map((t) => ({
...t,
dependencies: [...t.dependencies],
}));
const taskFiles = new Map(
tasks
.filter((t) => t.file)
.map((t) => [path.resolve(project.sourceDir, t.file!), t]),
);
for (const [filePath, task] of taskFiles) {
if (!fs.existsSync(filePath)) continue;
const content = fs.readFileSync(filePath, "utf-8");
// Check if this task's file references another task's file
for (const [file, refTask] of taskFiles) {
if (refTask.id === task.id) continue;
if (content.includes(file) || content.includes(refTask.title)) {
if (!task.dependencies.includes(refTask.id)) {
task.dependencies.push(refTask.id);
}
}
}
}
const dependencies: Record<string, string[]> = {};
for (const task of tasks) {
if (task.dependencies.length > 0) {
dependencies[task.id] = task.dependencies;
}
}
return { ...project, tasks, dependencies };
}
// ─── Helpers ─────────────────────────────────────────────────────────────────
// ─── Timeout Parsing ────────────────────────────────────────────────────────
/**
* Parse timeout from a task line (e.g., "timeout: 15m" or "# timeout=30s")
*/
function parseTimeoutFromLine(line: string): number | undefined {
// Match patterns like "timeout: 15m", "# timeout=30s", "timeout: 5min"
const match = line.match(/(?:timeout|timelimit)[\s:=]+(\d+)(?:m|min|s|ms)?/i);
if (match) {
return parseTimeoutValue(Number(match[1]), match[2]);
}
return undefined;
}
/**
* Parse a timeout value with unit suffix
*/
function parseTimeoutValue(value: number, unit?: string): number {
const u = (unit || "m").toLowerCase();
switch (u) {
case "ms":
return value;
case "s":
return value * 1000;
case "m":
case "min":
return value * 60 * 1000;
default:
return value * 60 * 1000; // default to minutes
}
}
/**
* Parse timeout from YAML meta field (string or number)
* Supports: "15m", "30s", "5min", 15 (minutes), 900000 (ms)
*/
function parseTimeoutFromMeta(
timeout: string | number | undefined,
): number | undefined {
if (timeout === undefined) return undefined;
if (typeof timeout === "number") {
// Assume minutes if < 1000, milliseconds if >= 1000
return timeout < 1000 ? timeout * 60 * 1000 : timeout;
}
const match = timeout.match(/^(\d+)(ms|s|m|min)?$/i);
if (match) {
return parseTimeoutValue(Number(match[1]), match[2]);
}
return undefined;
}
/**
* Normalize a task ID: zero-pad the digit portion to 2 chars, preserve any
* single lowercase letter suffix. Idempotent on already-normalized IDs.
*
* "1" → "01"
* "2" → "02"
* "2b" → "02b"
* "02b" → "02b"
* "10" → "10"
* "10b" → "10b"
*
* Pass-through for IDs that don't match the expected shape (defensive — the
* upstream regexes restrict matches, but a stray value should not be silently
* re-shaped).
*/
function normalizeTaskId(id: string): string {
const match = id.match(/^(\d+)([a-z])?$/);
if (!match) return id;
const [, digits, letter] = match;
return digits.padStart(2, "0") + (letter ?? "");
}
function charToStatus(char: string): Task["status"] {
switch (char) {
case " ":
return "pending";
case "~":
return "in_progress";
case "x":
return "completed";
case "!":
return "failed";
case "-":
return "skipped";
default:
return "pending";
}
}
function statusToChar(status: Task["status"]): string {
switch (status) {
case "pending":
return " ";
case "in_progress":
return "~";
case "completed":
return "x";
case "failed":
return "!";
case "skipped":
return "-";
}
}
function escapeRegex(str: string): string {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

327
src/progress.ts Normal file
View File

@@ -0,0 +1,327 @@
import * as fs from "node:fs";
import * as path from "node:path";
import type {
ProgressState,
PRDProgress,
Task,
Reflection,
ToolUsage,
ReviewResult,
} from "./types";
import { ensureDir } from "./utils";
/**
* Derive a stable PRD key from a source path relative to the project dir.
* e.g., "tasks/feature-x/README.md" → "tasks-feature-x-README"
*/
export function derivePRDKey(projectDir: string, sourcePath: string): string {
const rel = path.relative(projectDir, sourcePath);
return rel
.replace(/[^a-zA-Z0-9_-]/g, "-")
.replace(/-+/g, "-")
.replace(/^-|-$/g, "");
}
/**
* Manages persistent progress state for a ralph execution.
* State is stored as JSON in .ralpi/progress.json.
* Supports multiple PRDs in progress simultaneously via the `prds` field.
* Falls back to legacy flat format for backward compatibility.
*/
export class ProgressTracker {
private statePath: string;
private state: ProgressState;
private prdKey: string;
constructor(projectDir: string, sourcePath: string, prdKey?: string) {
const stateDir = path.join(projectDir, ".ralpi");
ensureDir(stateDir);
this.statePath = path.join(stateDir, "progress.json");
this.prdKey = prdKey ?? derivePRDKey(projectDir, sourcePath);
this.state = this.loadOrCreate(sourcePath);
}
/** Load existing state or create a fresh one */
private loadOrCreate(sourcePathHint: string): ProgressState {
if (fs.existsSync(this.statePath)) {
try {
const raw = fs.readFileSync(this.statePath, "utf-8");
const parsed = JSON.parse(raw) as ProgressState;
// Multi-PRD mode: check if we have a PRD entry
if (parsed.prds?.[this.prdKey]) {
// Found PRD entry — use it, but keep legacy fields for compat
return parsed;
}
// Legacy flat mode: check if the source path matches
if (path.resolve(parsed.sourcePath) === path.resolve(sourcePathHint)) {
// Migrate legacy state to PRD mode
parsed.prds = {
[this.prdKey]: {
sourcePath: parsed.sourcePath,
tasks: parsed.tasks,
startedAt: parsed.startedAt,
lastUpdatedAt: parsed.lastUpdatedAt,
paused: parsed.paused,
},
};
return parsed;
}
// Different PRD — create new entry alongside existing ones
if (parsed.prds) {
parsed.prds[this.prdKey] = this.freshPRD(sourcePathHint);
return parsed;
}
// Legacy flat state exists but for a different source — promote it to PRD mode
const legacyKey = derivePRDKey(
path.dirname(this.statePath),
parsed.sourcePath,
);
parsed.prds = {
[legacyKey]: {
sourcePath: parsed.sourcePath,
tasks: parsed.tasks,
startedAt: parsed.startedAt,
lastUpdatedAt: parsed.lastUpdatedAt,
paused: parsed.paused,
},
[this.prdKey]: this.freshPRD(sourcePathHint),
};
return parsed;
} catch {
// Fall through to create new
}
}
return this.freshState(sourcePathHint);
}
private freshPRD(sourcePath: string): PRDProgress {
return {
sourcePath,
tasks: {},
startedAt: new Date().toISOString(),
lastUpdatedAt: new Date().toISOString(),
paused: false,
};
}
private freshState(sourcePath: string): ProgressState {
return {
sourcePath,
tasks: {},
startedAt: new Date().toISOString(),
lastUpdatedAt: new Date().toISOString(),
paused: false,
prds: {
[this.prdKey]: {
sourcePath,
tasks: {},
startedAt: new Date().toISOString(),
lastUpdatedAt: new Date().toISOString(),
paused: false,
},
},
};
}
/** Get the PRD-scoped progress entry */
private getPRD(): PRDProgress {
if (!this.state.prds) {
// Should not happen after loadOrCreate, but guard anyway
this.state.prds = { [this.prdKey]: this.freshPRD(this.state.sourcePath) };
}
if (!this.state.prds[this.prdKey]) {
this.state.prds[this.prdKey] = this.freshPRD(this.state.sourcePath);
}
return this.state.prds[this.prdKey];
}
/** Save current state to disk */
save(): void {
// Merge into the freshest on-disk state instead of writing the
// construction-time snapshot verbatim. Each ProgressTracker instance
// (one per PRD loop) snapshots the WHOLE state at construction; when
// two loops run concurrently in one project, saving a stale snapshot
// would silently revert the OTHER loop's task status changes — tasks
// get wrongly written back to "pending" while their worktrees carry
// real work, stranding it on the next resume.
let disk: ProgressState | null = null;
try {
if (fs.existsSync(this.statePath)) {
const raw = fs.readFileSync(this.statePath, "utf-8");
disk = JSON.parse(raw) as ProgressState;
}
} catch {
disk = null;
}
if (disk && disk.prds) {
// Keep THIS tracker's in-memory PRD (its own tasks are the source
// of truth — all status mutations happened on it), but adopt the
// on-disk entries for OTHER PRDs instead of writing the stale
// construction-time snapshot over them.
const mine = this.getPRD();
this.state = disk;
this.state.prds ??= {};
this.state.prds[this.prdKey] = mine;
}
const prd = this.getPRD();
prd.lastUpdatedAt = new Date().toISOString();
// Sync legacy flat fields with current PRD for backward compat
this.state.sourcePath = prd.sourcePath;
this.state.tasks = prd.tasks;
this.state.startedAt = prd.startedAt;
this.state.lastUpdatedAt = prd.lastUpdatedAt;
this.state.paused = prd.paused;
fs.writeFileSync(
this.statePath,
JSON.stringify(this.state, null, 2),
"utf-8",
);
}
/** Mark a task as in progress */
markInProgress(taskId: string): void {
const prd = this.getPRD();
this.ensureTask(prd, taskId);
prd.tasks[taskId].status = "in_progress";
prd.tasks[taskId].startedAt = new Date().toISOString();
this.save();
}
/** Mark a task as completed */
markCompleted(
taskId: string,
durationMs: number,
reflection?: Reflection,
toolUsage?: ToolUsage,
outputPreview?: string,
commitMessages?: string[],
commitSummary?: string,
review?: ReviewResult,
reviewRetries?: number,
): void {
const prd = this.getPRD();
this.ensureTask(prd, taskId);
prd.tasks[taskId].status = "completed";
prd.tasks[taskId].completedAt = new Date().toISOString();
prd.tasks[taskId].durationMs = durationMs;
if (reflection) prd.tasks[taskId].reflection = reflection;
if (toolUsage) prd.tasks[taskId].toolUsage = toolUsage;
if (outputPreview) prd.tasks[taskId].outputPreview = outputPreview;
if (commitMessages) prd.tasks[taskId].commitMessages = commitMessages;
if (commitSummary) prd.tasks[taskId].commitSummary = commitSummary;
if (review) prd.tasks[taskId].review = review;
if (reviewRetries !== undefined)
prd.tasks[taskId].reviewRetries = reviewRetries;
this.save();
}
/** Mark a task as failed */
markFailed(taskId: string, error: string): void {
const prd = this.getPRD();
this.ensureTask(prd, taskId);
prd.tasks[taskId].status = "failed";
prd.tasks[taskId].error = error;
this.save();
}
/** Get task status */
getTaskStatus(taskId: string): Task["status"] {
const prd = this.getPRD();
return prd.tasks[taskId]?.status ?? "pending";
}
/** Get IDs of all completed tasks */
getCompletedTaskIds(): string[] {
const prd = this.getPRD();
return Object.entries(prd.tasks)
.filter(([, info]) => info.status === "completed")
.map(([id]) => id);
}
/** Get IDs of all failed tasks */
getFailedTaskIds(): string[] {
const prd = this.getPRD();
return Object.entries(prd.tasks)
.filter(([, info]) => info.status === "failed")
.map(([id]) => id);
}
/** Get all reflections from completed tasks */
getAllReflections(): Reflection[] {
const prd = this.getPRD();
const reflections: Reflection[] = [];
for (const info of Object.values(prd.tasks)) {
if (info.reflection) reflections.push(info.reflection);
}
return reflections;
}
/** Get reflections for specific dependency tasks */
getDependencyReflections(depIds: string[]): Reflection[] {
const prd = this.getPRD();
return depIds
.map((id) => prd.tasks[id]?.reflection)
.filter((r): r is Reflection => r !== undefined);
}
/** Set paused state */
setPaused(paused: boolean): void {
const prd = this.getPRD();
prd.paused = paused;
this.save();
}
/** Reset all `in_progress` tasks back to `pending`.
*
* Used after a session reload: in-process agent sessions die with the
* parent session, so any task left `in_progress` is actually stalled.
* Resetting ensures the DAG re-schedules it on the next resume. Returns
* the IDs that were reset. */
resetInProgressToPending(): string[] {
const prd = this.getPRD();
const reset: string[] = [];
for (const [id, info] of Object.entries(prd.tasks)) {
if (info.status === "in_progress") {
info.status = "pending";
delete info.startedAt;
reset.push(id);
}
}
if (reset.length > 0) this.save();
return reset;
}
/** Get the raw PRD state (for status display) */
getState(): PRDProgress {
return this.getPRD();
}
/** Get all PRDs (for multi-PRD status display) */
getAllPRDs(): Record<string, PRDProgress> {
return this.state.prds ?? {};
}
/** Get the PRD key for this tracker */
getKey(): string {
return this.prdKey;
}
/** Reset all progress for this PRD */
reset(): void {
const prd = this.getPRD();
Object.assign(prd, this.freshPRD(prd.sourcePath));
this.save();
}
private ensureTask(prd: PRDProgress, taskId: string): void {
if (!prd.tasks[taskId]) {
prd.tasks[taskId] = { status: "pending" };
}
}
}

642
src/prompts.ts Normal file
View File

@@ -0,0 +1,642 @@
import type { Task, Project, Reflection, ReviewResult } from "./types";
import { readTaskSpec } from "./parser";
import {
parseDiff,
filterNoise,
type DiffSummary,
type DiffOptions,
} from "./diff";
/** Maximum bytes of an inlined review diff before we stop inlining it and
* instead list the changed files + tell the model to `read` them.
* Diffs larger than this are never byte-truncated into a review prompt —
* truncation loses the middle of a large diff, so the file-list + read
* instruction is strictly better.
*
* ~50 KB ≈ 12.5K tokens — comfortably fits even on models with a 128K
* context window once system-prompt overhead is accounted for. */
export const MAX_DIFF_BYTES = 50_000;
/** Max included files before an oversized diff is replaced by a read
* instruction rather than inlined. */
const MAX_REVIEW_FILES = 20;
/** Optional knobs for the review prompt builders. */
export interface ReviewPromptOptions {
/** Extra context injected into the prompt (config.prompts.projectContext). */
projectContext?: string;
/** Per-review custom focus/instructions (config.prompts.reviewFocus). */
focus?: string;
/** Noise-filter overrides (config.review.*). */
diffOptions?: DiffOptions;
}
// ─── Task Prompt ─────────────────────────────────────────────────────────────
/**
* Build the prompt for a single task execution.
* Injects task details, dependency reflections, and project context.
*/
export function buildTaskPrompt(
task: Task,
project: Project,
depReflections: Reflection[],
projectContext?: string,
/** Review feedback from a rejected review — injected when re-executing
* a task in review-gated mode so the agent knows what to fix. */
reviewFeedback?: ReviewResult,
): string {
const parts: string[] = [];
// ── Header ──
parts.push(`# Task ${task.id}: ${task.title}`);
parts.push("");
// ── Project Objective ──
if (project.objective) {
parts.push("## Project Objective");
parts.push(project.objective);
parts.push("");
}
// ── Exit Criteria ──
if (project.exitCriteria && project.exitCriteria.length > 0) {
parts.push("## Exit Criteria");
for (const criterion of project.exitCriteria) {
parts.push(`- ${criterion}`);
}
parts.push("");
}
// ── Task Description ──
if (task.description) {
parts.push("## Description");
parts.push(task.description);
parts.push("");
}
// ── Task Specification ──
if (task.file) {
const spec = readTaskSpec(project.sourceDir, task.file);
if (spec) {
parts.push("## Task Specification");
parts.push(`Full details from \`${task.file}\`:`);
parts.push("");
parts.push(spec);
parts.push("");
}
}
// ── Dependencies ──
if (task.dependencies && task.dependencies.length > 0) {
parts.push("## Dependencies");
parts.push(`This task depends on: ${task.dependencies.join(", ")}`);
parts.push("");
}
// ── Dependency Reflections ──
if (depReflections.length > 0) {
parts.push("## Completed Dependency Reflections");
parts.push(
"The following tasks have been completed. Use their reflections for context:",
);
parts.push("");
for (const ref of depReflections) {
parts.push(`### Task ${ref.taskId}: ${ref.title}`);
parts.push(`**Summary:** ${ref.summary}`);
if (ref.keyLearnings && ref.keyLearnings.length > 0) {
parts.push("**Key Learnings:**");
for (const learning of ref.keyLearnings) {
parts.push(`- ${learning}`);
}
}
if (ref.filesChanged && ref.filesChanged.length > 0) {
parts.push(`**Files Changed:** ${ref.filesChanged.join(", ")}`);
}
if (ref.blockers && ref.blockers.length > 0) {
parts.push(`**Known Issues:** ${ref.blockers.join("; ")}`);
}
parts.push("");
}
}
// ── Project Context ──
if (projectContext) {
parts.push("## Additional Context");
parts.push(projectContext);
parts.push("");
}
// ── Previous Review Feedback (re-execution only) ──
if (reviewFeedback) {
parts.push("## Previous Review Feedback — FIX REQUIRED");
parts.push(
"A review agent examined your previous attempt and rejected it.",
);
parts.push(`Verdict: **${reviewFeedback.verdict.toUpperCase()}**`);
parts.push(`Summary: ${reviewFeedback.summary}`);
parts.push("");
if (reviewFeedback.findings.length > 0) {
parts.push("You MUST address these findings:");
for (const finding of reviewFeedback.findings) {
const loc = finding.file
? finding.line
? ` (${finding.file}:${finding.line})`
: ` (${finding.file})`
: "";
parts.push(`- [${finding.severity}]${loc} ${finding.message}`);
}
parts.push("");
}
parts.push("Fix every issue above. Do not re-introduce the same problems.");
parts.push("");
}
// ── Reflection Instructions ──
parts.push("## REFLECTION (REQUIRED)");
parts.push(
"When the task is COMPLETE, end your response with a reflection section.",
);
parts.push("Use EXACTLY this format at the END of your response:");
parts.push("");
parts.push("```");
parts.push("## REFLECTION");
parts.push("SUMMARY: [1-2 sentence description of what was accomplished]");
parts.push("FILES: [comma-separated list of files created or modified]");
parts.push("LEARNINGS:");
parts.push("- [key decision, pattern, or architectural choice]");
parts.push("- [important API or interface details]");
parts.push("- [anything downstream tasks need to know]");
parts.push("BLOCKERS: [any unresolved issues, or 'none']");
parts.push("```");
parts.push("");
parts.push(
"Also use the `memory` tool to save important learnings that will",
);
parts.push(
"be useful across future sessions (architecture decisions, API patterns, etc.)",
);
return parts.join("\n");
}
// ─── Review Prompt ───────────────────────────────────────────────────────────
/**
* Build the prompt for the auto-review agent.
* Includes the task description and the latest commit diff so the reviewer
* can assess whether the commit fulfills the task requirements.
*/
export function buildReviewPrompt(
task: Task,
project: Project,
commitHash: string,
commitSubject: string,
commitDiff: string,
opts: ReviewPromptOptions = {},
): string {
const parts: string[] = [];
parts.push(`# Code Review: Task ${task.id}: ${task.title}`);
parts.push("");
// ── Task Description ──
parts.push("## Task Description");
if (task.description) {
parts.push(task.description);
} else {
parts.push(task.title);
}
parts.push("");
// ── Task Specification ──
if (task.file) {
const spec = readTaskSpec(project.sourceDir, task.file);
if (spec) {
parts.push("## Task Specification");
parts.push(`Full details from \`${task.file}\`:`);
parts.push("");
parts.push(spec);
parts.push("");
}
}
// ── Commit Under Review ──
parts.push("## Commit Under Review");
parts.push(`Commit: ${commitHash}${commitSubject}`);
parts.push("");
// ── Changed-Files Summary + Exclusions (noise-filtered scope) ──
const summary = parseDiff(commitDiff, opts.diffOptions);
const filtered = filterNoise(commitDiff, opts.diffOptions);
parts.push(buildFileSummaryTable(summary));
const excluded = renderExcludedFiles(summary);
if (excluded) parts.push(excluded);
parts.push("");
// ── Diff (inline, or file-list + read instruction when oversized) ──
parts.push(renderDiffSection(summary, filtered, "### Diff"));
parts.push("");
// ── Custom Review Focus ──
if (opts.focus) {
parts.push("## Custom Review Focus");
parts.push(opts.focus);
parts.push("");
}
// ── Project Context ──
if (opts.projectContext) {
parts.push("## Additional Context");
parts.push(opts.projectContext);
parts.push("");
}
// ── Review Instructions ──
parts.push("## Review Instructions");
parts.push(
"Review the changes above against the task description. Check for:",
);
parts.push(...reviewInstructions());
parts.push("");
parts.push(
"Provide a concise review with any issues found. Your free-form prose",
);
parts.push("precedes the structured verdict block below.");
parts.push(...reviewVerdictBlock());
return parts.join("\n");
}
// ─── Uncommitted-Changes Review Prompt ──────────────────────────────────────
/**
* Build a review prompt for uncommitted working-tree changes (pre-commit).
* Used in review-gated mode: the review runs BEFORE committing so a rejected
* review triggers a re-execution instead of a bad commit.
*/
export function buildReviewPromptUncommitted(
task: Task,
project: Project,
status: string,
diff: string,
opts: ReviewPromptOptions = {},
): string {
const parts: string[] = [];
parts.push(`# Code Review (pre-commit): Task ${task.id}: ${task.title}`);
parts.push("");
// ── Task Description ──
parts.push("## Task Description");
if (task.description) {
parts.push(task.description);
} else {
parts.push(task.title);
}
parts.push("");
// ── Task Specification ──
if (task.file) {
const spec = readTaskSpec(project.sourceDir, task.file);
if (spec) {
parts.push("## Task Specification");
parts.push(`Full details from \`${task.file}\`:`);
parts.push("");
parts.push(spec);
parts.push("");
}
}
// ── Uncommitted Changes Under Review ──
parts.push("## Uncommitted Changes Under Review");
parts.push(
"Review the working-tree changes below against the task description.",
);
parts.push("");
parts.push("### Current Changes (git status --porcelain)");
parts.push("```text");
parts.push(status || "(no status output)");
parts.push("```");
parts.push("");
// ── Changed-Files Summary + Exclusions (noise-filtered scope) ──
const summary = parseDiff(diff, opts.diffOptions);
const filtered = filterNoise(diff, opts.diffOptions);
parts.push(buildFileSummaryTable(summary));
const excluded = renderExcludedFiles(summary);
if (excluded) parts.push(excluded);
parts.push("");
// ── Diff (inline, or file-list + read instruction when oversized) ──
parts.push(
renderDiffSection(summary, filtered, "### Current Tracked Diff (git diff)"),
);
parts.push("");
// ── Custom Review Focus ──
if (opts.focus) {
parts.push("## Custom Review Focus");
parts.push(opts.focus);
parts.push("");
}
// ── Project Context ──
if (opts.projectContext) {
parts.push("## Additional Context");
parts.push(opts.projectContext);
parts.push("");
}
// ── Review Instructions ──
parts.push("## Review Instructions");
parts.push(
"Review the uncommitted changes above against the task description. Check for:",
);
parts.push(...reviewInstructions());
parts.push("");
parts.push(
"Provide a concise review with any issues found. Your free-form prose",
);
parts.push("precedes the structured verdict block below.");
parts.push(...reviewVerdictBlock());
return parts.join("\n");
}
// ─── Shared Review Prompt Helpers ───────────────────────────────────────────
/** Whether an oversized/wide diff should be replaced by a file-list + read
* instruction instead of being inlined. Thresholds: cleaned diff over
* MAX_DIFF_BYTES, or more than MAX_REVIEW_FILES included files. */
function shouldSkipInline(summary: DiffSummary, filteredLength: number): boolean {
return (
filteredLength > MAX_DIFF_BYTES || summary.files.length > MAX_REVIEW_FILES
);
}
/**
* Render a per-file +/ summary Markdown table (with type column and a total
* line) from a parsed diff. Handles the empty/all-noise diff gracefully — an
* empty table with zero totals, no crash.
*/
function buildFileSummaryTable(summary: DiffSummary): string {
const lines: string[] = [];
lines.push("### Changed Files");
lines.push("");
lines.push("| File | +/ | Type |");
lines.push("|------|-----|------|");
if (summary.files.length === 0) {
lines.push("| _(no included changes)_ | — | — |");
} else {
for (const f of summary.files) {
lines.push(
`| \`${f.path}\` | +${f.linesAdded}/-${f.linesRemoved} | ${f.ext || "—"} |`,
);
}
}
lines.push(`| **Total** | **+${summary.totalAdded}/-${summary.totalRemoved}** | |`);
return lines.join("\n");
}
/**
* Render the `### Excluded Files (n)` bullet list (path, +/ counts, reason).
* Returns an empty string when there are no exclusions so callers omit the
* section entirely (no empty heading).
*/
function renderExcludedFiles(summary: DiffSummary): string {
if (summary.excluded.length === 0) return "";
const lines: string[] = [];
lines.push(`### Excluded Files (${summary.excluded.length})`);
lines.push("");
for (const f of summary.excluded) {
lines.push(
`- \`${f.path}\` (+${f.linesAdded}/-${f.linesRemoved}) — ${f.reason}`,
);
}
return lines.join("\n");
}
/**
* Render the diff section of a review prompt. Under the threshold, inline the
* noise-filtered diff. Over the threshold (size or file count), emit a
* file-list + read-instruction notice and never byte-truncate the diff.
*/
function renderDiffSection(
summary: DiffSummary,
filtered: string,
heading: string,
): string {
if (shouldSkipInline(summary, filtered.length)) {
return `${heading} — _Diff too large (${filtered.length.toLocaleString()} chars, ${summary.files.length} files). Use \`read\` to inspect the changed files._`;
}
const lines: string[] = [];
lines.push(heading);
lines.push("```diff");
lines.push(filtered || "(no included changes)");
lines.push("```");
return lines.join("\n");
}
function reviewInstructions(): string[] {
return [
"- **Correctness**: Does the implementation fulfill the task requirements?",
"- **Completeness**: Are all aspects of the task addressed?",
"- **Code quality**: Are there obvious bugs, anti-patterns, or issues?",
"- **Missing changes**: Are there files that should have been modified but weren't?",
];
}
function reviewVerdictBlock(): string[] {
return [
"## REVIEW VERDICT (REQUIRED)",
"End your response with a verdict block in EXACTLY this format:",
"",
"```",
"## REVIEW VERDICT",
"VERDICT: [pass | warn | fail]",
"SUMMARY: [1-2 sentence overall assessment]",
"FINDINGS:",
"- [blocker] file:line description (use severity: blocker|warning|nit|info; `critical` is accepted as a blocker synonym)",
"- [warning] file:line description",
"```",
"",
"Verdict guidance:",
"- **pass**: the implementation fully satisfies the task requirements; no",
" action needed. Use an empty FINDINGS section (just the header).",
"- **warn**: the implementation is acceptable but has minor issues worth fixing",
" in a follow-up; not blocking.",
"- **fail**: the implementation does not satisfy the task, or has serious bugs",
" that must be fixed before proceeding.",
"",
"Each FINDINGS line uses the form `- [severity] [file:line] message`.",
"The `file:line` part is optional. Severity must be one of:",
"`blocker`, `warning`, `nit`, `info`. The `critical` token is accepted",
"and treated as `blocker`.",
];
}
/**
* Build the prompt for a dry-run / plan display
*/
export function buildPlanPrompt(project: Project): string {
const lines: string[] = [];
lines.push("# Project Plan");
lines.push("");
if (project.objective) {
lines.push("## Objective");
lines.push(project.objective);
lines.push("");
}
lines.push("## Tasks");
for (const task of project.tasks) {
const deps =
task.dependencies.length > 0
? ` (depends on: ${task.dependencies.join(", ")})`
: "";
lines.push(`- [ ] ${task.id}: ${task.title}${deps}`);
}
lines.push("");
if (project.exitCriteria && project.exitCriteria.length > 0) {
lines.push("## Exit Criteria");
for (const criterion of project.exitCriteria) {
lines.push(`- ${criterion}`);
}
lines.push("");
}
return lines.join("\n");
}
// ─── Conflict Resolution Prompt ─────────────────────────────────────────────
/**
* Build the prompt for a conflict-resolution agent session.
*
* The main repo is in a merge-conflict state (from `reattemptMerge`). The
* agent must resolve all conflict markers in the conflicted files, stage the
* resolved files, and commit to complete the merge.
*/
export function buildConflictResolutionPrompt(
task: Task,
project: Project,
conflicts: string[],
branch: string,
projectContext?: string,
): string {
const parts: string[] = [];
parts.push(`# Merge Conflict Resolution: Task ${task.id}: ${task.title}`);
parts.push("");
parts.push(
`A merge of branch \`${branch}\` into the current branch produced conflicts.`,
);
parts.push("You must resolve all conflicts and complete the merge.");
parts.push("");
// ── Task Context ──
parts.push("## Task Description");
if (task.description) {
parts.push(task.description);
} else {
parts.push(task.title);
}
parts.push("");
// ── Task Specification ──
if (task.file) {
const spec = readTaskSpec(project.sourceDir, task.file);
if (spec) {
parts.push("## Task Specification");
parts.push(`Full details from \`${task.file}\`:`);
parts.push("");
parts.push(spec);
parts.push("");
}
}
// ── Conflicted Files ──
parts.push("## Conflicted Files");
parts.push(
"The following files have unresolved merge conflicts (conflict markers `<<<<<<<`, `=======`, `>>>>>>>`):",
);
parts.push("");
for (const f of conflicts) {
parts.push(`- \`${f}\``);
}
parts.push("");
// ── Project Context ──
if (projectContext) {
parts.push("## Additional Context");
parts.push(projectContext);
parts.push("");
}
// ── Resolution Instructions ──
parts.push("## Resolution Instructions");
parts.push(
"1. Read each conflicted file to understand both sides of the conflict.",
);
parts.push(
"2. Edit each file to remove all conflict markers (`<<<<<<<`, `=======`, `>>>>>>>`).",
);
parts.push(
" Keep the correct changes from both sides — do NOT blindly pick one side.",
);
parts.push(
" The goal is a correct union of both the task's changes and the main branch.",
);
parts.push(
"3. After resolving all conflicts, stage the resolved files with `git add <files>`.",
);
parts.push(
"4. Complete the merge with `git commit` — use the default merge message.",
);
parts.push("");
parts.push(
"Resolve ALL conflicts. Do NOT abort the merge. Do NOT leave any conflict markers.",
);
return parts.join("\n");
}

128
src/reflection.ts Normal file
View File

@@ -0,0 +1,128 @@
import * as fs from "node:fs";
import * as path from "node:path";
import type { Reflection } from "./types";
import { REFLECTION_PATTERN } from "./constants";
import { ensureDir, writeFileSafe } from "./utils";
// ─── Extract Reflection ──────────────────────────────────────────────────────
/**
* Extract a reflection block from pi's output text
*/
export function extractReflection(
output: string,
taskId: string,
title: string,
): Reflection | null {
const match = output.match(REFLECTION_PATTERN);
if (!match) return null;
const block = match[1];
const summary = extractField(block, "SUMMARY");
const files = extractField(block, "FILES");
const learnings = extractList(block, "LEARNINGS");
const blockersRaw = extractField(block, "BLOCKERS");
const blockers =
blockersRaw && blockersRaw.toLowerCase() !== "none"
? blockersRaw.split(",").map(b => b.trim()).filter(Boolean)
: undefined;
return {
taskId,
title,
summary: summary || "Task completed",
keyLearnings: learnings || [],
filesChanged: files
? files.split(",").map(f => f.trim()).filter(Boolean)
: [],
blockers,
timestamp: new Date().toISOString(),
};
}
function extractField(block: string, field: string): string | null {
const regex = new RegExp(`${field}:\\s*(.+?)$`, "im");
const match = block.match(regex);
return match ? match[1].trim() : null;
}
function extractList(block: string, field: string): string[] | null {
const regex = new RegExp(`${field}:\\s*\\n((?:- .+\\n?)+)`, "im");
const match = block.match(regex);
if (!match) return null;
return match[1]
.split("\n")
.map(l => l.replace(/^-\\s*/, "").trim())
.filter(Boolean);
}
// ─── Save / Load Reflections ────────────────────────────────────────────────
/**
* Save a reflection to a file
*/
export function saveReflection(
reflectionsDir: string,
reflection: Reflection,
): void {
ensureDir(reflectionsDir);
const filePath = path.join(
reflectionsDir,
`${reflection.taskId}.json`,
);
writeFileSafe(filePath, JSON.stringify(reflection, null, 2));
}
/**
* Load a reflection from a file
*/
export function loadReflection(
reflectionsDir: string,
taskId: string,
): Reflection | null {
const filePath = path.join(reflectionsDir, `${taskId}.json`);
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as Reflection;
} catch {
return null;
}
}
// ─── Format Reflections ──────────────────────────────────────────────────────
/**
* Format reflections for display
*/
export function formatReflections(reflections: Reflection[]): string {
if (reflections.length === 0) return "No reflections yet.";
const lines: string[] = [];
lines.push("## Task Reflections");
lines.push("");
for (const ref of reflections) {
lines.push(`### ${ref.taskId}: ${ref.title}`);
lines.push(`Summary: ${ref.summary}`);
if (ref.keyLearnings.length > 0) {
lines.push("Learnings:");
for (const l of ref.keyLearnings) {
lines.push(` - ${l}`);
}
}
if (ref.filesChanged.length > 0) {
lines.push(`Files: ${ref.filesChanged.join(", ")}`);
}
if (ref.blockers && ref.blockers.length > 0) {
lines.push(`Blockers: ${ref.blockers.join("; ")}`);
}
lines.push("");
}
return lines.join("\n");
}

214
src/review.ts Normal file
View File

@@ -0,0 +1,214 @@
import * as fs from "node:fs";
import * as path from "node:path";
import type { ReviewResult, ReviewFinding, ReviewVerdict } from "./types";
import { REVIEW_PATTERN } from "./constants";
import { ensureDir, writeFileSafe } from "./utils";
// ─── Extract Structured Review ──────────────────────────────────────────────
/**
* Extract a structured review verdict from the review agent's output text.
* Mirrors extractReflection() — parses a `## REVIEW VERDICT` block emitted at
* the end of the response.
*
* The raw text is preserved on the ReviewResult so the expanded (Ctrl+O) view
* can still render the full free-form prose. Returns null when no verdict
* block is found (caller falls back to free-form text handling).
*/
export function extractReview(
output: string,
taskId: string,
commitHash: string,
): ReviewResult | null {
const match = output.match(REVIEW_PATTERN);
if (!match) return null;
const block = match[1];
const verdict = extractVerdict(block);
if (!verdict) return null; // verdict is the one required field
const summary = extractField(block, "SUMMARY") ?? "";
const findings = extractFindings(block);
return {
taskId,
verdict,
summary: summary || verdictLabel(verdict),
findings,
commitHash,
rawText: output.trim(),
timestamp: new Date().toISOString(),
};
}
function extractVerdict(block: string): ReviewVerdict | null {
const raw = extractField(block, "VERDICT");
if (!raw) return null;
const v = raw.toLowerCase().trim();
if (v === "pass" || v === "warn" || v === "fail") return v;
// Tolerate common synonyms
if (v === "warning" || v === "minor") return "warn";
if (v === "fail" || v === "failing" || v === "blocker") return "fail";
if (v === "ok" || v === "passing" || v === "approve") return "pass";
return null;
}
// Allowlisted static regexes — `field` is always a known literal, but we use
// a static map rather than string interpolation so there's no dynamic regex
// construction at all (`new RegExp` from a variable trips ReDoS linters).
const FIELD_PATTERNS: Record<string, RegExp> = {
VERDICT: /VERDICT:\s*(.+?)$/im,
SUMMARY: /SUMMARY:\s*(.+?)$/im,
};
function extractField(block: string, field: string): string | null {
const regex = FIELD_PATTERNS[field.toUpperCase()];
if (!regex) return null;
const match = block.match(regex);
return match ? match[1].trim() : null;
}
/**
* Parse FINDINGS: lines into structured ReviewFinding objects.
* Each finding line is expected as:
* - [severity] [file:line] message
* where severity is one of blocker|warning|nit|info.
* Falls back gracefully — an unparseable line becomes an info-severity
* finding with the raw line as the message.
*/
function extractFindings(block: string): ReviewFinding[] {
// Match the FINDINGS: header, then capture all following bullet lines.
const regex = /FINDINGS:\s*\n((?:[-*]\s+.+\n?)+)/i;
const match = block.match(regex);
if (!match) return [];
const lines = match[1]
.split("\n")
.map((l) => l.replace(/^[-*]\s*/, "").trim())
.filter(Boolean);
const findings: ReviewFinding[] = [];
// `critical` is accepted and normalized to ralpi's `blocker` severity,
// providing parity with @piex-dev/review's critical/warning/info grading.
const severityRe = /^\[(blocker|critical|warning|warn|nit|info)\]\s*(.*)$/i;
for (const line of lines) {
const sm = line.match(severityRe);
if (sm) {
let sev = sm[1].toLowerCase();
if (sev === "warn") sev = "warning";
else if (sev === "critical") sev = "blocker";
const rest = sm[2].trim();
const { file, line: lineNum, message } = parseFileRef(rest);
findings.push({
severity: sev as ReviewFinding["severity"],
file,
line: lineNum,
message,
});
} else {
// No severity bracket — treat as info
const { file, line: lineNum, message } = parseFileRef(line);
findings.push({ severity: "info", file, line: lineNum, message });
}
}
return findings;
}
/** Parse an optional `file:line` prefix from a finding message. */
function parseFileRef(rest: string): {
file?: string;
line?: number;
message: string;
} {
const m = rest.match(/^([\w./-]+):(\d+)\s*[-—]?\s*(.*)$/);
if (m) {
return { file: m[1], line: Number(m[2]), message: m[3].trim() || rest };
}
return { message: rest };
}
function verdictLabel(v: ReviewVerdict): string {
switch (v) {
case "pass":
return "Commit satisfies the task requirements.";
case "warn":
return "Commit passes with minor issues worth addressing.";
case "fail":
return "Commit does not satisfy the task requirements.";
}
}
// ─── Save / Load Structured Reviews ─────────────────────────────────────────
/**
* Save a structured review as JSON alongside (or instead of) the markdown
* body. Mirrors saveReflectionToFile's per-loop layout so a repo can hold
* many loops without collisions:
* .ralpi/reviews/<prdKey>/<taskId>.json
*/
export function saveReviewToFile(
sourceDir: string,
reviewsDir: string,
review: ReviewResult,
prdKey: string,
): string {
const dir = path.join(sourceDir, reviewsDir, prdKey);
ensureDir(dir);
const filePath = path.join(dir, `${review.taskId}.json`);
writeFileSafe(filePath, JSON.stringify(review, null, 2));
return filePath;
}
/**
* Load a structured review from disk.
*/
export function loadReview(
sourceDir: string,
reviewsDir: string,
taskId: string,
prdKey: string,
): ReviewResult | null {
const filePath = path.join(sourceDir, reviewsDir, prdKey, `${taskId}.json`);
if (!fs.existsSync(filePath)) return null;
try {
return JSON.parse(fs.readFileSync(filePath, "utf-8")) as ReviewResult;
} catch {
return null;
}
}
// ─── Formatting ──────────────────────────────────────────────────────────────
/** Verdict glyph for compact display in chat headers / widgets. */
export function verdictGlyph(v: ReviewVerdict): string {
switch (v) {
case "pass":
return "✓";
case "warn":
return "⚠";
case "fail":
return "✗";
}
}
/** Short label: "PASS · 0 findings", "WARN · 2 findings", "FAIL · 3 findings" */
export function verdictSummary(review: ReviewResult): string {
const n = review.findings.length;
const noun = n === 1 ? "finding" : "findings";
return `${review.verdict.toUpperCase()} · ${n} ${noun}`;
}
/**
* Format findings as an indented markdown tree for the expanded view.
*/
export function formatFindings(review: ReviewResult): string {
if (review.findings.length === 0) return "(no findings)";
const lines: string[] = [];
for (const f of review.findings) {
const loc = f.file ? (f.line ? `${f.file}:${f.line}` : f.file) : "";
lines.push(` - [${f.severity}]${loc ? ` ${loc}` : ""}${f.message}`);
}
return lines.join("\n");
}

112
src/task-manager-prompt.ts Normal file
View File

@@ -0,0 +1,112 @@
import * as fs from "node:fs";
import * as path from "node:path";
const TEMPLATE_REL = path.join("prompts", "task-manager.md");
/**
* Strip leading YAML frontmatter (--- delimited) from template content.
* Local port of the helper omp does not export from the package root.
*/
function stripFrontmatter(content: string): string {
const m = /^---\r?\n[\s\S]*?\r?\n---\r?\n/.exec(content);
return m ? content.slice(m[0].length) : content;
}
/**
* Parse command arguments respecting quoted strings (bash-style).
* Ported from pi's core/prompt-templates.js so the task-manager template
* receives the same arg-splitting a real `/task-manager` invocation would.
*/
function parseCommandArgs(argsString: string): string[] {
const args: string[] = [];
let current = "";
let inQuote: string | null = null;
for (let i = 0; i < argsString.length; i++) {
const char = argsString[i];
if (inQuote) {
if (char === inQuote) {
inQuote = null;
} else {
current += char;
}
} else if (char === '"' || char === "'") {
inQuote = char;
} else if (/\s/.test(char)) {
if (current) {
args.push(current);
current = "";
}
} else {
current += char;
}
}
if (current) args.push(current);
return args;
}
/**
* Substitute argument placeholders in template content.
* Faithful port of pi's substituteArgs (core/prompt-templates.js):
* - $1, $2, ... positional args
* - $@ / $ARGUMENTS all args joined
* - ${N:-default} positional N with default when missing/empty
* - ${@:-default} all args with default when empty
* - ${@:N} / ${@:N:L} bash-style slicing
*
* Replacement runs once over the template only; argument/default values
* containing patterns like $1 or $@ are NOT recursively substituted.
*/
function substituteArgs(content: string, args: string[]): string {
const allArgs = args.join(" ");
return content.replace(
/\$\{(\d+|ARGUMENTS|@):-([^}]*)\}|\$\{@:(\d+)(?::(\d+))?\}|\$(ARGUMENTS|@|\d+)/g,
(_match, defaultTarget, defaultValue, sliceStart, sliceLength, simple) => {
if (defaultTarget) {
const value =
defaultTarget === "@" || defaultTarget === "ARGUMENTS"
? allArgs
: args[parseInt(defaultTarget, 10) - 1];
return value ? value : defaultValue;
}
if (sliceStart) {
let start = parseInt(sliceStart, 10) - 1; // 1-indexed → 0-indexed
if (start < 0) start = 0;
if (sliceLength) {
const length = parseInt(sliceLength, 10);
return args.slice(start, start + length).join(" ");
}
return args.slice(start).join(" ");
}
if (simple === "ARGUMENTS" || simple === "@") {
return allArgs;
}
const index = parseInt(simple, 10) - 1;
return args[index] ?? "";
},
);
}
/**
* Load and expand the task-manager prompt template bundled with the extension.
*
* `pi.sendUserMessage()` sends with `expandPromptTemplates: false`, so it will
* NOT expand a `/task-manager` invocation — and `@task-manager` is an
* @-mention, not a template invocation anyway. We therefore read the
* template ourselves, strip its frontmatter, substitute args ($@ etc.), and
* return the fully-expanded prompt body ready to send as a user message.
*
* @param extensionDir Absolute path to the extension root (where index.ts
* lives), used to locate `prompts/task-manager.md`.
* @param argsString Raw argument string from the slash command (may be "").
* @throws if the template file is missing or unreadable.
*/
export function loadTaskManagerPrompt(
extensionDir: string,
argsString: string,
): string {
const templatePath = path.join(extensionDir, TEMPLATE_REL);
const raw = fs.readFileSync(templatePath, "utf-8");
const body = stripFrontmatter(raw);
const args = parseCommandArgs(argsString);
return substituteArgs(body, args).trim();
}

330
src/types.ts Normal file
View File

@@ -0,0 +1,330 @@
// ─── Task Model ───────────────────────────────────────────────────────────────
export type TaskStatus =
| "pending"
| "in_progress"
| "completed"
| "failed"
| "skipped";
export type TaskStatusChar = " " | "~" | "x" | "!" | "-";
export interface Task {
/** Unique task identifier */
id: string;
/** Task title */
title: string;
/** Detailed task description */
description?: string;
/** Path to detailed spec file (relative to sourceDir) */
file?: string;
/** Current status */
status: TaskStatus;
/** Task IDs this task depends on */
dependencies: string[];
/** Explicit parallel group (optional, overrides dependency-based batching) */
parallelGroup?: number;
/** Task-level timeout in milliseconds (parsed from meta block) */
timeoutMs?: number;
/** Original index in task list for deterministic ordering */
index?: number;
/** Phase number this task belongs to (1-indexed, from ## Phase N headings) */
phase?: number;
}
export interface ParallelGroup {
/** Group index (0-based, determines execution order) */
index: number;
/** Human-readable label for the group (e.g. "Play Store prep") */
label?: string;
/** Task IDs in this group — all can run concurrently */
taskIds: string[];
}
export interface Phase {
/** Phase number (1-indexed, matches the heading number) */
number: number;
/** Phase title (e.g. "Push-to-Talk MVP") */
title: string;
/** Task IDs in this phase, in order */
taskIds: string[];
}
export interface Project {
/** Project-level objective / goal */
objective?: string;
/** All tasks in the project */
tasks: Task[];
/** Explicit dependency map: taskId → [dependency taskIds] */
dependencies: Record<string, string[]>;
/** Explicit parallel groups from "can be done in parallel" declarations */
parallelGroups?: ParallelGroup[];
/** Phased sections from ## Phase N headings (in order) */
phases?: Phase[];
/** Exit criteria (from README ## Exit Criteria section) */
exitCriteria?: string[];
/** Path to the source task file */
sourcePath: string;
/** Directory containing the source file */
sourceDir: string;
}
// ─── Execution Plan ───────────────────────────────────────────────────────────
export interface ExecutionBatch {
/** Tasks that can run concurrently in this batch */
tasks: Task[];
/** Batch number (0-indexed) */
batchIndex: number;
}
export interface ExecutionPlan {
/** Ordered batches (each batch contains parallelizable tasks) */
batches: ExecutionBatch[];
/** Total task count */
totalTasks: number;
/** Tasks skipped (already completed) */
skippedTasks: Task[];
}
// ─── Progress Model ───────────────────────────────────────────────────────────
export interface Reflection {
taskId: string;
title: string;
/** What was accomplished */
summary: string;
/** Key decisions, patterns, and learnings for downstream tasks */
keyLearnings: string[];
/** Files created or modified */
filesChanged: string[];
/** Unresolved issues or caveats */
blockers?: string[];
/** ISO timestamp */
timestamp: string;
}
// ─── Review Model ────────────────────────────────────────────────────────────
export type ReviewVerdict = "pass" | "warn" | "fail";
export interface ReviewFinding {
/** Severity of the finding */
severity: "blocker" | "warning" | "nit" | "info";
/** File path if applicable */
file?: string;
/** Line number if applicable */
line?: number;
/** Description of the issue */
message: string;
}
export interface ReviewResult {
taskId: string;
/** Overall verdict */
verdict: ReviewVerdict;
/** 1-2 sentence overall assessment */
summary: string;
/** Structured findings (empty when verdict is "pass") */
findings: ReviewFinding[];
/** Commit hash the review was performed against */
commitHash: string;
/** Full free-form review text (preserved for display) */
rawText: string;
/** ISO timestamp */
timestamp: string;
}
export interface ToolUsage {
read: number;
write: number;
edit: number;
bash: number;
other: number;
}
export interface TaskProgressInfo {
status: Task["status"];
startedAt?: string;
completedAt?: string;
durationMs?: number;
reflection?: Reflection;
/** Structured review result (when autoReview is enabled) */
review?: ReviewResult;
error?: string;
/** Tool usage counts from parsed subprocess output */
toolUsage?: ToolUsage;
/** Truncated output preview for expanded view */
outputPreview?: string;
/** Git commit messages from task execution */
commitMessages?: string[];
/** Summary derived from git commits */
commitSummary?: string;
/** Number of review-fix re-execution attempts made (review-gated mode) */
reviewRetries?: number;
}
export interface ProgressState {
/** Path to the source task file (legacy single-PRD mode) */
sourcePath: string;
/** Per-task status tracking (legacy single-PRD mode) */
tasks: Record<string, TaskProgressInfo>;
/** When execution started (legacy single-PRD mode) */
startedAt: string;
/** When execution last updated (legacy single-PRD mode) */
lastUpdatedAt: string;
/** Whether execution is currently paused/stopped (legacy single-PRD mode) */
paused: boolean;
/** Multiple PRDs tracked simultaneously (keyed by normalized source path) */
prds?: Record<string, PRDProgress>;
}
export interface PRDProgress {
/** Path to the source task file for this PRD */
sourcePath: string;
/** Per-task status tracking */
tasks: Record<string, TaskProgressInfo>;
/** When execution started */
startedAt: string;
/** When execution last updated */
lastUpdatedAt: string;
/** Whether execution is currently paused/stopped */
paused: boolean;
}
// ─── Configuration ────────────────────────────────────────────────────────────
export interface RalpiConfig {
paths: {
/** Directory for ralpi state files */
stateDir: string;
/** Directory for per-task reflections */
reflectionsDir: string;
/** Directory for per-loop review output (mirrors reflectionsDir) */
reviewsDir: string;
};
execution: {
/** Task execution timeout in milliseconds */
timeoutMs: number;
/** Maximum parallel tasks (0 = unlimited) */
maxParallel: number;
/** Round-robin model list for parallel tasks (empty = inherit parent model) */
models: string[];
/** Spawn a follow-up agent to commit changes after each task completes */
autoCommit: boolean;
/** Spawn a review agent to review the task's committed changes against
* the task description. When autoReview is on, commit is mandated:
* changes are committed (via commit session fallback when the agent
* didn't self-commit), then the COMPLETE diff (baseRef..HEAD) is
* reviewed. On 'fail' the task is re-executed with feedback (loops
* until pass or maxReviewRetries). On pass the worktree merges.
* When autoReview is off, autoCommit controls standalone commit. */
autoReview: boolean;
/** Persist the full review output to `.ralpi/reviews/<task-id>.md`.
* Only active when autoReview is true and the user opts in at loop start. */
saveReviews: boolean;
/** Keys under `execution:` explicitly present in a loaded config YAML.
* Used to skip interactive prompts for fields the user already set. */
explicitKeys?: Set<string>;
/** Model for commit sessions in <provider>/<model> format (empty = inherit task model) */
commitModel: string;
/** Model for review sessions in <provider>/<model> format (empty = inherit task model) */
reviewModel: string;
/** Model for task implementation in <provider>/<model> format (empty = inherit parent model; only used in sequential mode when models is empty) */
implModel: string;
/** Timeout for auto-commit agent sessions in milliseconds */
commitTimeoutMs: number;
/** Timeout for auto-review agent sessions in milliseconds */
reviewTimeoutMs: number;
/** Max review-fix re-execution attempts before giving up (0 = no retries;
* review runs once, reject = stop). Active whenever autoReview is
* enabled. On exhaustion the task proceeds with its committed changes
* (the worktree merges) unless reviewBlockOnFail is set. */
maxReviewRetries: number;
/** When true, a 'fail' review verdict after exhausting maxReviewRetries
* marks the task as failed instead of proceeding with its committed
* changes (the worktree does not merge). */
reviewBlockOnFail: boolean;
/** Maximum total duration for the entire loop execution in milliseconds (0 = no limit). Checked between batches — in-progress tasks finish naturally. */
loopTimeoutMs: number;
/** Max attempts on the SAME model before cycling to the next model on
* failure. Pi retries transient HTTP errors within a single prompt,
* but a sustained provider hiccup can still exhaust those in-call
* retries mid-session. Re-running the whole session a few times on
* the same model avoids flapping to a different model (and losing
* model-specific context) on the first hard failure. Applies to task
* execution, commit/review follow-up sessions, and review-fix
* re-execution alike. After this many attempts on one model, ralpi
* advances to the next model in the round-robin pool. */
maxSameModelAttempts: number;
/** Isolate each task in a separate git worktree so parallel tasks can't
* stomp each other's files, and review/commit see a clean single-task diff.
* - "never": all tasks run in the shared working tree (default, backward compat)
* - "parallel": only when maxParallel > 1 and mode is parallel
* - "always": every task gets its own worktree */
worktrees: "always" | "parallel" | "never";
/** Chat rendering style for tool calls during task execution.
* - "compact": single completion message per task with an expandable
* tool-call tree (collapsed shows last 3, expanded shows all).
* - "verbose": per-event stream — each tool start/end and assistant
* turn is its own chat line (piolium/pygienium-style). */
chatStyle: "compact" | "verbose";
};
prompts: {
/** Additional context injected into every task prompt */
projectContext: string;
/** Custom prompt suffix for reflection extraction */
reflectionPrompt: string;
/** Per-review custom focus/instructions (e.g. "check security only").
* Injected as a `### Custom Review Focus` section in committed and
* uncommitted review prompts when non-empty. */
reviewFocus: string;
};
review: {
/** Extra noise-filter exclusion regexes (strings compiled to RegExp),
* merged into EXCLUDED_PATTERNS for review diffs. */
extraIgnorePatterns: string[];
/** Pathspec allowlist — files matching these stay in scope even when a
* default noise rule would exclude them. */
ignorePaths: string[];
};
/** Parent session model to inherit in child agent sessions */
model?: unknown;
/** Parent session thinking level to inherit in child agent sessions */
thinkingLevel?: unknown;
}
export const DEFAULT_CONFIG: RalpiConfig = {
paths: {
stateDir: ".ralpi",
reflectionsDir: ".ralpi/reflections",
reviewsDir: ".ralpi/reviews",
},
execution: {
timeoutMs: 0, // 0 = inherit Pi's own defaults (no ralpi-level timeout)
maxParallel: 3,
models: [],
autoCommit: true,
autoReview: false,
saveReviews: false,
commitModel: "",
reviewModel: "",
implModel: "",
commitTimeoutMs: 0, // 0 = inherit Pi's own defaults (no ralpi-level timeout)
reviewTimeoutMs: 0, // 0 = inherit Pi's own defaults (no ralpi-level timeout)
maxReviewRetries: 2, // 2 re-execution attempts on review rejection before giving up
reviewBlockOnFail: false, // false = commit anyway after retries exhausted
loopTimeoutMs: 0, // 0 = no limit
worktrees: "parallel", // worktree isolation for parallel tasks by default
maxSameModelAttempts: 5, // retry the same model up to 5 times before cycling to the next
chatStyle: "compact", // compact = completion message with tool-call tree; verbose = per-event stream
},
prompts: {
projectContext: "",
reflectionPrompt: "",
reviewFocus: "",
},
review: {
extraIgnorePatterns: [],
ignorePaths: [],
},
};

1045
src/utils.ts Normal file

File diff suppressed because it is too large Load Diff

92
src/widget-batcher.ts Normal file
View File

@@ -0,0 +1,92 @@
import type { ExtensionContext } from "@oh-my-pi/pi-coding-agent";
/**
* Batches widget updates from multiple parallel tasks into a single
* render cycle, preventing TUI thrashing when agents update independently.
*
* Uses microtask debouncing: updates within the same event-loop tick
* are coalesced into one flush. No artificial interval — updates hit the
* screen as soon as the current tick yields, but never duplicatively.
*/
export class WidgetBatcher {
/** Pending widget updates keyed by widget key. */
private pending: Map<string, string[]> = new Map();
/** Widget keys scheduled for removal. */
private pendingRemovals: Set<string> = new Set();
/** Whether a microtask flush is already queued. */
private scheduled = false;
/** Whether a flush is currently executing (prevents re-entry). */
private flushing = false;
constructor(private ctx: ExtensionContext) {}
/**
* Schedule a widget update. Flushed asynchronously at end of the
* current event-loop tick; multiple calls in the same tick coalesce.
*/
schedule(key: string, lines: string[]): void {
this.pending.set(key, lines);
this.scheduleFlush();
}
/**
* Remove a widget (e.g., when a task completes).
* Flushed asynchronously at end of the current tick.
*/
scheduleRemove(key: string): void {
this.pending.delete(key);
this.pendingRemovals.add(key);
this.scheduleFlush();
}
/** Synchronously flush all pending updates. */
flush(): void {
this.doFlush();
}
/** Flush remaining updates then stop scheduling. */
stop(): void {
this.doFlush();
}
// ── Internal ────────────────────────────────────────────────────────
private scheduleFlush(): void {
if (this.scheduled) return;
this.scheduled = true;
queueMicrotask(() => {
this.scheduled = false;
this.doFlush();
});
}
private doFlush(): void {
if (this.flushing) return;
this.flushing = true;
// Atomically swap — new schedule()/scheduleRemove() calls land on fresh
// collections, so the batch we iterate stays immutable and nothing is lost.
const toRender = this.pending;
const toRemove = this.pendingRemovals;
this.pending = new Map();
this.pendingRemovals = new Set();
// Apply removals first
for (const key of toRemove) {
this.ctx.ui.setWidget(key, undefined);
}
// Sort by key for deterministic, stable ordering across every flush.
// Task IDs are zero-padded ("008", "012", "013") so alpha sort = numeric order.
const sortedKeys = Array.from(toRender.keys()).sort();
for (const key of sortedKeys) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.ctx.ui.setWidget(key, toRender.get(key)!);
}
this.flushing = false;
}
}

564
src/worktree.ts Normal file
View File

@@ -0,0 +1,564 @@
import * as fs from "node:fs";
import * as path from "node:path";
import {
ensureDir,
hasUncommittedChanges,
hasTrackedUncommittedChanges,
} from "./utils";
// ─── Types ───────────────────────────────────────────────────────────────────
export interface WorktreeHandle {
/** Absolute path to the worktree working directory. */
dir: string;
/** Branch name: slugified task title, or `ralpi/<prdKey>/<taskId>` as a fallback. */
branch: string;
/** Main repo directory (where the primary working tree lives). */
mainDir: string;
}
export interface MergeResult {
success: boolean;
/** File paths that conflicted (empty when merge succeeds). */
conflicts: string[];
/** Human-readable status message. */
message: string;
}
// ─── Git Helpers ─────────────────────────────────────────────────────────────
/** Run a git command, returning trimmed stdout. Returns null on failure. */
function git(args: string, cwd: string): string | null {
const { execSync } = require("node:child_process") as {
execSync: (cmd: string, opts: object) => string;
};
try {
return execSync(`git ${args}`, {
cwd,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
}).trim();
} catch {
return null;
}
}
/** Run a git command that may fail; returns { ok, stdout, stderr }. */
function gitRaw(
args: string,
cwd: string,
): { ok: boolean; stdout: string; stderr: string } {
const { execSync } = require("node:child_process") as {
execSync: (cmd: string, opts: object) => string;
};
try {
const stdout = execSync(`git ${args}`, {
cwd,
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
});
return { ok: true, stdout: stdout.trim(), stderr: "" };
} catch (err: unknown) {
const e = err as {
stdout?: string;
stderr?: string;
message?: string;
};
return {
ok: false,
stdout: (e.stdout ?? "").toString().trim(),
stderr: (e.stderr ?? "").toString().trim(),
};
}
}
/** Check if a directory is inside a git repository. */
export function isGitRepo(dir: string): boolean {
return git("rev-parse --git-dir", dir) !== null;
}
/** Get the current HEAD commit hash of a directory. */
export function getGitHead(dir: string): string | null {
return git("rev-parse HEAD", dir);
}
/** Get the current branch name of a directory. */
export function getCurrentBranch(dir: string): string | null {
return git("rev-parse --abbrev-ref HEAD", dir);
}
/**
* Canonicalize a directory path, resolving symlinks.
*
* `git worktree list --porcelain` emits REAL paths (symlinks resolved,
* e.g. `/private/tmp/...` for `/tmp/...` on macOS), while `path.join` on a
* caller-supplied path keeps the literal spelling. Comparing the two
* verbatim silently fails — resume then can't see an existing worktree,
* `createWorktree` falls through to a fresh `worktree add` that fails
* because the directory already exists, returns null, and the task agent
* ends up running in the MAIN repo with no worktree merge at all.
*
* All worktree path computation and porcelain comparisons go through this
* so literal vs real paths can never diverge.
*/
function canonicalDir(dir: string): string {
try {
return fs.realpathSync(dir);
} catch {
return path.resolve(dir);
}
}
// ─── Worktree Lifecycle ──────────────────────────────────────────────────────
/**
* Path to the worktree directory for a given task.
* Lives inside `.ralpi/worktrees/<prdKey>/<taskId>` in the main repo so all
* ralpi state stays co-located and multiple loops (different PRDs) can run
* concurrently without colliding on shared task IDs. The directory itself
* is untracked git metadata (registered in `.git/worktrees/`), so it won't
* pollute `git status` in the main working tree.
*/
export function worktreePath(
mainDir: string,
stateDir: string,
prdKey: string,
taskId: string,
): string {
return path.join(mainDir, stateDir, "worktrees", prdKey, taskId);
}
/**
* Normalise a task ID into a valid git branch suffix.
* Zero-padded IDs like "01" are already valid; this ensures any stray
* characters are replaced.
*/
function safeBranchSuffix(taskId: string): string {
return taskId.replace(/[^a-zA-Z0-9_-]/g, "-");
}
/**
* Sanitise a free-form task title into a git-branch-safe slug.
*
* Lowercases, replaces runs of non-alphanumeric characters with single
* hyphens, trims leading/trailing hyphens, and caps the length so the
* branch name stays readable and within reasonable git limits.
*
* Returns an empty string when the title produces no usable slug.
*/
function slugifyTitle(title: string): string {
return title
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60);
}
/**
* Create a git worktree for a task.
*
* The worktree is created at `<mainDir>/.ralpi/worktrees/<prdKey>/<taskId>`
* on a new branch. When `taskTitle` is provided the branch name is the slugified title
* alone (e.g. `fix-plans-tab-grammar-casing-icons`); otherwise it falls back
* to `ralpi/<prdKey>/<taskId>`. Based at `baseRef` (defaults to the current
* HEAD of `mainDir`).
*
* The worktree directory always uses the bare `taskId` for a stable path;
* stale-worktree cleanup identifies ralpi worktrees by that path, not by
* branch name, so descriptive branch names are safe.
*
* Returns null if `mainDir` is not a git repo or the worktree creation fails.
*/
export function createWorktree(
mainDir: string,
stateDir: string,
taskId: string,
prdKey: string,
baseRef?: string,
taskTitle?: string,
): WorktreeHandle | null {
// Canonicalize FIRST: every path below (worktree dir, porcelain
// comparisons, branch refs) must share one spelling of the repo path.
mainDir = canonicalDir(mainDir);
if (!isGitRepo(mainDir)) return null;
const safeId = safeBranchSuffix(taskId);
const slug = taskTitle ? slugifyTitle(taskTitle) : "";
const branch = slug || `ralpi/${prdKey}/${safeId}`;
const wtDir = worktreePath(mainDir, stateDir, prdKey, taskId);
// Prune metadata for worktree directories that no longer exist on disk
// (e.g. from a crashed previous run that left stale `.git/worktrees/` entries).
git("worktree prune", mainDir);
// ── Reuse an already-registered worktree (resume) ──
// A resumed loop skips `cleanupStaleWorktrees`, so the interrupted task's
// worktree — and the branch carrying its committed work — survives. Reuse
// it instead of destroying and recreating from the base ref; otherwise the
// prior session's commits are lost and the task restarts from scratch.
const existing = git(`worktree list --porcelain`, mainDir);
if (existing && existing.includes(`worktree ${wtDir}`)) {
// The worktree is registered — sanity-check it's a valid checkout.
if (getGitHead(wtDir)) {
// Return the branch the worktree is ACTUALLY checked out on, NOT the
// slug recomputed from the (possibly changed) task title. Mismatch
// happens routinely on resume: the task agent may have created its
// own feature branch (e.g. `proctored-exam-delivery-mode-10-exam-...`)
// once it saw the convention in the git log, the title may have been
// edited between runs, or an older ralpi version used a different
// naming scheme. Returning the slug here makes `git merge <slug>`
// fail with "not something we can merge" because no such ref exists —
// exactly the spurious merge-conflict we see on resumes.
const actual = getCurrentBranch(wtDir);
if (actual && actual !== "HEAD" && actual !== "detached") {
return { dir: wtDir, branch: actual, mainDir };
}
// Detached-HEAD worktree (e.g. left by a prior `--detach` fallback).
// The slug ref doesn't exist as a branch — create one matching the
// slug from the worktree's current HEAD so the merge step resolves.
git(`branch "${branch}" HEAD`, mainDir);
return { dir: wtDir, branch, mainDir };
}
// Registered but broken (dir gone / checkout corrupt) — drop its
// metadata and fall through to fresh creation below.
git(`worktree remove --force "${wtDir}"`, mainDir);
}
// Fresh creation.
const ref = baseRef ?? getGitHead(mainDir);
if (!ref) return null;
// Ensure the parent directory exists so `git worktree add` can create
// the worktree directory inside it.
ensureDir(path.dirname(wtDir));
// Delete a stale branch if it exists from a previous run so `-b` doesn't
// fail on the new worktree.
git(`branch -D "${branch}"`, mainDir);
const result = gitRaw(
`worktree add -b "${branch}" "${wtDir}" "${ref}"`,
mainDir,
);
if (!result.ok) {
// Fall back to detached HEAD worktree if branch creation fails
// (e.g. the branch name somehow conflicts).
const fallback = gitRaw(
`worktree add --detach "${wtDir}" "${ref}"`,
mainDir,
);
if (!fallback.ok) return null;
}
return { dir: wtDir, branch, mainDir };
}
/**
* Merge a worktree's branch back into the current branch of the main repo.
*
* Uses `--no-ff` to always create a merge commit, preserving the task
* branch's history. On conflict, the merge is aborted and the conflicts
* are returned so the caller can mark the task as failed.
*/
export function mergeWorktree(mainDir: string, branch: string): MergeResult {
// Attempt the merge.
const result = gitRaw(`merge --no-ff --no-edit "${branch}"`, mainDir);
if (result.ok) {
return {
success: true,
conflicts: [],
message: `Merged ${branch} into ${getCurrentBranch(mainDir) ?? "HEAD"}`,
};
}
// Merge failed — likely conflicts. Collect the list of conflicting files.
const status = git("diff --name-only --diff-filter=U", mainDir) ?? "";
const conflicts = status
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
// Abort the merge so the main repo's working tree is left clean.
git("merge --abort", mainDir);
return {
success: false,
conflicts,
message:
conflicts.length > 0
? `Merge conflicts in: ${conflicts.join(", ")}`
: `Merge of ${branch} failed: ${result.stderr || result.stdout}`,
};
}
/**
* Re-attempt a merge WITHOUT aborting on conflict.
*
* Unlike `mergeWorktree`, this leaves the main repo in a merge-conflict
* state so a conflict-resolution agent can see the conflict markers in the
* working tree and resolve them manually. The caller is responsible for
* committing the resolved merge or aborting it.
*
* Returns:
* - `clean: true` → merge succeeded (nothing staged to commit yet; the
* caller should `git commit` or `git merge --abort` to finalise)
* - `clean: false` → conflicts; working tree has conflict markers
*/
export function reattemptMerge(
mainDir: string,
branch: string,
): { clean: boolean; conflicts: string[] } {
// Use --no-commit so even a clean merge doesn't auto-commit — the caller
// controls when the merge commit lands.
const result = gitRaw(`merge --no-ff --no-commit "${branch}"`, mainDir);
if (result.ok) {
return { clean: true, conflicts: [] };
}
// Merge produced conflicts — collect them but DO NOT abort.
const status = git("diff --name-only --diff-filter=U", mainDir) ?? "";
const conflicts = status
.split("\n")
.map((l) => l.trim())
.filter(Boolean);
return { clean: false, conflicts };
}
/** Abort an in-progress merge in the main repo. */
export function abortMerge(mainDir: string): void {
git("merge --abort", mainDir);
}
/** Check if there are unmerged paths (conflicts) in the working tree. */
export function hasMergeConflicts(mainDir: string): boolean {
const status = git("diff --name-only --diff-filter=U", mainDir) ?? "";
return status.trim().length > 0;
}
/** Complete the in-progress merge by committing. Returns true on success. */
export function completeMerge(mainDir: string): boolean {
const result = gitRaw("commit --no-edit", mainDir);
return result.ok;
}
/**
* Remove a worktree and delete its branch.
*
* Called after a successful merge to clean up. Safe to call even if the
* worktree or branch no longer exists.
*/
export function removeWorktree(mainDir: string, wt: WorktreeHandle): void {
git(`worktree remove --force "${wt.dir}"`, mainDir);
git(`branch -D "${wt.branch}"`, mainDir);
git("worktree prune", mainDir);
}
/**
* Clean up stale worktrees from interrupted runs.
*
* Identifies ralpi-owned worktrees by their path living under
* `<mainDir>/<stateDir>/worktrees/` and removes them. Called at the start
* of a loop to ensure a clean slate. Returns the list of removed worktree
* directories.
*
* When `prdKey` is provided, cleanup is scoped to
* `<mainDir>/<stateDir>/worktrees/<prdKey>/` so that worktrees belonging to
* other concurrently running loops (different PRDs) are left untouched.
* When omitted, all ralpi-managed worktrees are cleaned.
*/
export function cleanupStaleWorktrees(
mainDir: string,
stateDir: string,
prdKey?: string,
): string[] {
const removed: string[] = [];
// Prune metadata for worktree directories that no longer exist on disk.
git("worktree prune", mainDir);
const list = git("worktree list --porcelain", mainDir);
if (!list) return removed;
// Worktrees we manage live under <mainDir>/<stateDir>/worktrees/.
// When a prdKey is given, narrow to that PRD's subdir so concurrent
// loops (other PRDs) are not disturbed.
const managedRoot = path.resolve(
canonicalDir(mainDir),
stateDir,
"worktrees",
...(prdKey ? [prdKey] : []),
);
// Parse worktree list: each entry is `worktree <path>` followed by metadata.
const wtLines = list
.split("\n")
.filter((l) => l.startsWith("worktree "))
.map((l) => l.slice("worktree ".length).trim());
for (const wtDir of wtLines) {
// Skip the main working tree (always first in the list).
if (path.resolve(wtDir) === path.resolve(mainDir)) continue;
// Only touch worktrees that live under the ralpi worktrees directory.
const resolved = path.resolve(wtDir);
if (
resolved !== managedRoot &&
!resolved.startsWith(managedRoot + path.sep)
)
continue;
// Remove the worktree and its branch.
git(`worktree remove --force "${wtDir}"`, mainDir);
const branch = git(`rev-parse --abbrev-ref HEAD`, wtDir);
if (branch && branch !== "HEAD" && branch !== "detached") {
git(`branch -D "${branch}"`, mainDir);
}
removed.push(wtDir);
}
git("worktree prune", mainDir);
return removed;
}
/** Result of attempting to finalize a single in-progress worktree on resume. */
export interface FinalizeResult {
/** Task IDs whose committed branch was merged into main and cleaned up. */
finalized: string[];
/** Task IDs left to re-run (no worktree, dirty tree, nothing committed,
* or merge conflict — work is preserved for re-execution). */
rerun: string[];
/** Task IDs that hit a merge conflict; their committed branch + worktree
* are left intact for manual resolution. Excluded from `rerun` so the
* scheduler does not blindly re-execute conflicting work. */
conflicts: Record<string, string[]>;
}
/**
* Finalize worktrees that already hold committed, clean work that was never
* merged into main (typically because the loop was interrupted between the
* task commit and the merge/finalize step).
*
* For each task ID:
* - If no worktree exists / is registered → re-run (fresh worktree later).
* - If the worktree has uncommitted edits to TRACKED files (e.g. an
* interrupted agent mid-edit) → re-run, preserving the worktree so
* `createWorktree` reuses it and the agent continues where it left off.
* Untracked files are ignored here — they never block a merge, and a
* worktree whose task work is fully committed is "done" even if it
* carries stray untracked files. Counting `??` entries would strand the
* committed branch in `.ralpi/worktrees/` forever on every resume.
* - If the worktree has no commits ahead of main → re-run.
* - If the worktree has ≥1 commit ahead of main → merge the branch into
* main (`--no-ff`) and report finalized. Fully clean worktrees are then
* removed; worktrees that also carry untracked files are kept so that
* (possibly meaningful) uncommitted files aren't destroyed — the next
* fresh-loop sweep cleans them up. On merge conflict the merge is
* aborted (main left clean), the worktree is preserved, and the task is
* reported in `conflicts`.
*
* This is the self-healing path for an interrupted review-gated loop:
* tasks that finished (commit + review already saved) but never got their
* merge are completed here, so `/ralpi-resume` does not wastefully re-run
* finished work.
*/
export function finalizeCommittedWorktrees(
mainDir: string,
stateDir: string,
prdKey: string,
taskIds: string[],
): FinalizeResult {
mainDir = canonicalDir(mainDir);
const result: FinalizeResult = { finalized: [], rerun: [], conflicts: {} };
const mainHead = getGitHead(mainDir);
for (const taskId of taskIds) {
const wtDir = worktreePath(mainDir, stateDir, prdKey, taskId);
// No worktree directory on disk → nothing to finalize.
if (!fs.existsSync(wtDir)) {
result.rerun.push(taskId);
continue;
}
// Confirm the worktree is actually registered with git (not a leftover
// dir from a half-cleaned-up run). If registered but broken, drop its
// metadata so a fresh worktree can be created on re-run.
const list = git("worktree list --porcelain", mainDir) ?? "";
if (!list.includes(`worktree ${wtDir}`)) {
result.rerun.push(taskId);
continue;
}
// Broken checkout → re-run (createWorktree will recreate it).
const branch = getCurrentBranch(wtDir);
if (!branch || branch === "HEAD" || branch === "detached") {
result.rerun.push(taskId);
continue;
}
// Uncommitted edits to TRACKED files (an interrupted agent mid-edit) →
// re-run, keeping the worktree so the agent resumes in place. Untracked
// files alone do NOT count as dirty here (see doc comment above).
if (hasTrackedUncommittedChanges(wtDir)) {
result.rerun.push(taskId);
continue;
}
// No commits ahead of main → nothing to merge.
const aheadStr =
mainHead !== null
? git(`rev-list --count ${mainHead}..HEAD`, wtDir)
: null;
const ahead = aheadStr !== null ? parseInt(aheadStr, 10) : 0;
if (Number.isNaN(ahead) || ahead <= 0) {
result.rerun.push(taskId);
continue;
}
// Committed + no tracked edits → finalize. mergeWorktree aborts on
// conflict, leaving main's working tree clean.
const merge = mergeWorktree(mainDir, branch);
if (merge.success) {
// Remove the worktree only when it's fully clean. If it still carries
// untracked files, keep it so that uncommitted work isn't destroyed
// (the branch is merged; the leftover worktree is swept by the next
// fresh-loop cleanup).
if (!hasUncommittedChanges(wtDir)) {
removeWorktree(mainDir, { dir: wtDir, branch, mainDir });
}
result.finalized.push(taskId);
continue;
}
// Conflict — preserve the worktree for manual resolution and report.
result.conflicts[taskId] = merge.conflicts;
}
git("worktree prune", mainDir);
return result;
}
/**
* Whether a worktree still holds work worth preserving (committed commits
* ahead of main, or uncommitted changes). Used by the task-failure path so a
* failed/timeout agent's partial output isn't force-deleted with the
* worktree.
*/
export function worktreeHasPreservableWork(
mainDir: string,
wt: WorktreeHandle,
): boolean {
mainDir = canonicalDir(mainDir);
// Any uncommitted changes (tracked edits or untracked files) count — the
// agent may have been mid-write when it failed.
if (hasUncommittedChanges(wt.dir)) return true;
const mainHead = getGitHead(mainDir);
if (!mainHead) return true;
const aheadStr = git(`rev-list --count ${mainHead}..${wt.branch}`, mainDir);
const ahead = aheadStr !== null ? parseInt(aheadStr, 10) : 0;
return !Number.isNaN(ahead) && ahead > 0;
}

View File

@@ -0,0 +1,82 @@
/**
* Tests for the tri-state commit-range diff (src/utils.ts getCommitRangeDiff):
* a FAILED range computation (invalid/stale base ref, git error) must be a
* distinct `error` signal, never collapsed into a clean `no-changes` — a
* broken base ref must never be silently treated as a verified task.
*
* Uses a real throwaway git repo so the shell-out behavior is exercised.
*/
import { describe, test, expect, beforeAll, afterAll } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
import { execSync } from "node:child_process";
import { getCommitRangeDiff } from "../src/utils";
let repoDir: string;
function sh(cmd: string, cwd: string) {
execSync(cmd, { cwd, stdio: "pipe" });
}
beforeAll(() => {
repoDir = fs.mkdtempSync(path.join(os.tmpdir(), "ralpi-crd-"));
sh("git init -q", repoDir);
sh("git config user.email test@example.com", repoDir);
sh("git config user.name test", repoDir);
fs.writeFileSync(path.join(repoDir, "a.ts"), "one\n", "utf-8");
sh("git add -A", repoDir);
sh("git commit -q -m init", repoDir);
});
afterAll(() => {
fs.rmSync(repoDir, { recursive: true, force: true });
});
describe("getCommitRangeDiff tri-state", () => {
test("ok: a resolvable base with committed changes yields the diff", () => {
fs.writeFileSync(path.join(repoDir, "a.ts"), "one\ntwo\n", "utf-8");
sh("git add -A", repoDir);
sh("git commit -q -m change", repoDir);
const base = execSync("git rev-parse HEAD~1", {
cwd: repoDir,
encoding: "utf-8",
}).trim();
const result = getCommitRangeDiff(repoDir, base);
expect(result.kind).toBe("ok");
if (result.kind === "ok") {
expect(result.diff).toContain("a.ts");
expect(result.hash.length).toBeGreaterThan(0);
}
});
test("error: a fake/unresolvable base ref yields the failure signal, not no-changes", () => {
// 40 hex chars that never existed in this repo.
const fake = "ffffffffffffffffffffffffffffffffffffffff";
const result = getCommitRangeDiff(repoDir, fake);
expect(result.kind).toBe("error");
if (result.kind === "error") {
expect(result.error).toContain("cannot be resolved");
}
});
test("error: a non-hex base ref is rejected before reaching the shell", () => {
const result = getCommitRangeDiff(repoDir, "HEAD~1; rm -rf /");
expect(result.kind).toBe("error");
if (result.kind === "error") {
expect(result.error).toContain("invalid or stale base ref");
}
});
test("no-changes: an empty range (base == HEAD) yields the no-changes signal", () => {
const head = execSync("git rev-parse HEAD", {
cwd: repoDir,
encoding: "utf-8",
}).trim();
const result = getCommitRangeDiff(repoDir, head);
expect(result.kind).toBe("no-changes");
});
});

View File

@@ -0,0 +1,674 @@
/// <reference types="bun-types" />
import { describe, it, expect } from "bun:test";
import type { Project, Task } from "../src/types";
import {
buildExecutionPlan,
buildSequentialPlan,
getBlockedTasks,
detectCycles,
getCriticalPath,
formatDependencyChain,
formatExecutionPlan,
} from "../src/dag";
// ─── Helpers ─────────────────────────────────────────────────────────────────
function makeProject(overrides?: Partial<Project>): Project {
return {
tasks: [],
dependencies: {},
sourcePath: "/tmp/test.md",
sourceDir: "/tmp",
...overrides,
};
}
function task(
id: string,
dependencies: string[] = [],
status: Task["status"] = "pending",
parallelGroup?: number,
): Task {
return { id, title: `Task ${id}`, status, dependencies, parallelGroup };
}
function tasksFrom(...args: Task[]): Task[] {
return args;
}
// ─── Basic DAG Construction ──────────────────────────────────────────────────
describe("buildExecutionPlan (Kahn's algorithm)", () => {
it("handles empty task list", () => {
const project = makeProject({ tasks: [] });
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches).toEqual([]);
expect(plan.totalTasks).toBe(0);
});
it("puts all root tasks in batch 0", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02"), task("03")),
});
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches).toHaveLength(1);
expect(plan.batches[0].tasks.map((t) => t.id).sort()).toEqual([
"01",
"02",
"03",
]);
});
it("builds correct linear dependency chain", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04", ["03"]),
),
});
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches).toHaveLength(4);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id)).toEqual(["02"]);
expect(plan.batches[2].tasks.map((t) => t.id)).toEqual(["03"]);
expect(plan.batches[3].tasks.map((t) => t.id)).toEqual(["04"]);
});
it("groups parallelizable tasks in the same batch", () => {
// Diamond: 01 -> 02, 03 -> 04
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02", "03"]),
),
});
const plan = buildExecutionPlan(project, new Set());
// Batch 0: [01], Batch 1: [02, 03], Batch 2: [04]
expect(plan.batches).toHaveLength(3);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual(["02", "03"]);
expect(plan.batches[2].tasks.map((t) => t.id)).toEqual(["04"]);
});
it("assigns correct batchIndex values", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02", "03"]),
),
});
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches[0].batchIndex).toBe(0);
expect(plan.batches[1].batchIndex).toBe(1);
expect(plan.batches[2].batchIndex).toBe(2);
});
it("skips completed tasks and includes them in skippedTasks", () => {
const project = makeProject({
tasks: tasksFrom(
task("01", [], "completed"),
task("02", ["01"]),
task("03", ["02"]),
),
});
const plan = buildExecutionPlan(project, new Set(["01"]));
expect(plan.totalTasks).toBe(2);
expect(plan.skippedTasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches).toHaveLength(2);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["02"]);
expect(plan.batches[1].tasks.map((t) => t.id)).toEqual(["03"]);
});
it("throws on dependency cycle", () => {
const project = makeProject({
tasks: tasksFrom(
task("01", ["03"]),
task("02", ["01"]),
task("03", ["02"]),
),
});
expect(() => buildExecutionPlan(project, new Set())).toThrow(
/dependency cycle/i,
);
});
it("blocks tasks that depend on failed tasks", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04", ["03"]),
),
});
const plan = buildExecutionPlan(
project,
new Set(),
undefined,
new Set(["01"]),
);
// 01 is excluded from pending (failed). 02, 03, 04 are pending but
// transitively blocked — they don't appear in batches.
expect(plan.skippedTasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.totalTasks).toBe(3); // 02, 03, 04 are pending but blocked
expect(plan.batches).toHaveLength(0);
});
it("blocks immediate dependents when task fails", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04"), // independent
),
});
const plan = buildExecutionPlan(
project,
new Set(),
undefined,
new Set(["01"]),
);
// 01 is excluded from pending (failed). 02, 03 are pending but blocked
// (depend on 01). 04 is independent and ready.
expect(plan.skippedTasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["04"]);
});
});
// ─── Complex DAGs ───────────────────────────────────────────────────────────
describe("Complex DAG batching", () => {
it("builds the OAuth PRD example correctly", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04", ["01"]),
task("05", ["03", "04"]),
task("06", ["03", "04"]),
task("07", ["03"]),
task("08", ["05", "06", "07"]),
),
});
const plan = buildExecutionPlan(project, new Set());
// Expected batches: [01], [02,04], [03], [05,06,07], [08]
expect(plan.batches).toHaveLength(5);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual(["02", "04"]);
expect(plan.batches[2].tasks.map((t) => t.id)).toEqual(["03"]);
expect(plan.batches[3].tasks.map((t) => t.id).sort()).toEqual([
"05",
"06",
"07",
]);
expect(plan.batches[4].tasks.map((t) => t.id)).toEqual(["08"]);
});
it("builds the Design Token PRD example correctly", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02", "03"]),
task("05", ["04", "01"]),
),
});
const plan = buildExecutionPlan(project, new Set());
// Expected batches: [01], [02,03], [04], [05]
expect(plan.batches).toHaveLength(4);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual(["02", "03"]);
expect(plan.batches[2].tasks.map((t) => t.id)).toEqual(["04"]);
expect(plan.batches[3].tasks.map((t) => t.id)).toEqual(["05"]);
});
it("handles a 3-tier diamond", () => {
// 01
// / \
// 02 03
// / \ / \
// 04 05 06
// \ | /
// 07
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02"]),
task("05", ["02", "03"]),
task("06", ["03"]),
task("07", ["04", "05", "06"]),
),
});
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches).toHaveLength(4);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual(["02", "03"]);
expect(plan.batches[2].tasks.map((t) => t.id).sort()).toEqual([
"04",
"05",
"06",
]);
expect(plan.batches[3].tasks.map((t) => t.id)).toEqual(["07"]);
});
it("handles a wide fan-out with delayed convergence", () => {
// 01 -> 02,03,04,05,06
// 02,03 -> 07
// 04,05 -> 08
// 06 -> 09
// 07,08,09 -> 10
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["01"]),
task("05", ["01"]),
task("06", ["01"]),
task("07", ["02", "03"]),
task("08", ["04", "05"]),
task("09", ["06"]),
task("10", ["07", "08", "09"]),
),
});
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches).toHaveLength(4);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual([
"02",
"03",
"04",
"05",
"06",
]);
expect(plan.batches[2].tasks.map((t) => t.id).sort()).toEqual([
"07",
"08",
"09",
]);
expect(plan.batches[3].tasks.map((t) => t.id)).toEqual(["10"]);
});
it("handles multiple independent subgraphs", () => {
// Two completely independent chains:
// Chain A: 01 -> 02 -> 03
// Chain B: 04 -> 05
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04"),
task("05", ["04"]),
),
});
const plan = buildExecutionPlan(project, new Set());
// Batch 0: [01, 04] (both roots)
// Batch 1: [02, 05]
// Batch 2: [03]
expect(plan.batches[0].tasks.map((t) => t.id).sort()).toEqual(["01", "04"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual(["02", "05"]);
expect(plan.batches[2].tasks.map((t) => t.id)).toEqual(["03"]);
});
it("batches tasks respecting fan-in convergence", () => {
// 01 -> 03, 02 -> 03 (03 depends on both 01 AND 02)
const project = makeProject({
tasks: tasksFrom(task("01"), task("02"), task("03", ["01", "02"])),
});
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches[0].tasks.map((t) => t.id).sort()).toEqual(["01", "02"]);
expect(plan.batches[1].tasks.map((t) => t.id)).toEqual(["03"]);
});
});
// ─── Sequential Plan ─────────────────────────────────────────────────────────
describe("buildSequentialPlan", () => {
it("puts each task in its own batch", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02", ["01"]), task("03", ["01"])),
});
const plan = buildSequentialPlan(project, new Set());
expect(plan.batches).toHaveLength(3);
plan.batches.forEach((b, i) => {
expect(b.tasks).toHaveLength(1);
expect(b.batchIndex).toBe(i);
});
});
it("skips completed tasks and blocks transitively failed tasks", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04"),
),
});
const plan = buildSequentialPlan(project, new Set(["01"]), new Set(["01"]));
// 01 failed => 02, 03 blocked. 04 independent, runs.
expect(plan.skippedTasks.map((t) => t.id).sort()).toEqual([
"01",
"02",
"03",
]);
expect(plan.totalTasks).toBe(3);
});
it("maintains task order in sequential batches", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02", ["01"]), task("03", ["01"])),
});
const plan = buildSequentialPlan(project, new Set());
expect(plan.batches.map((b) => b.tasks[0].id)).toEqual(["01", "02", "03"]);
});
});
// ─── getBlockedTasks ─────────────────────────────────────────────────────────
describe("getBlockedTasks", () => {
it("returns direct dependents of failed tasks", () => {
const pending = tasksFrom(task("01"), task("02", ["01"]), task("03"));
const blocked = getBlockedTasks(pending, new Set(["01"]));
expect([...blocked]).toEqual(["02"]);
});
it("returns transitive dependents (chain reaction)", () => {
const pending = tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04", ["03"]),
);
const blocked = getBlockedTasks(pending, new Set(["01"]));
expect([...blocked].sort()).toEqual(["02", "03", "04"]);
});
it("does not affect tasks in separate subgraphs", () => {
const pending = tasksFrom(
task("01"),
task("02", ["01"]),
task("10"),
task("11", ["10"]),
);
const blocked = getBlockedTasks(pending, new Set(["01"]));
expect([...blocked].sort()).toEqual(["02"]);
});
it("returns empty set when no tasks depend on failed tasks", () => {
const pending = tasksFrom(task("01"), task("02"), task("03"));
const blocked = getBlockedTasks(pending, new Set(["99"]));
expect(blocked.size).toBe(0);
});
});
// ─── detectCycles ────────────────────────────────────────────────────────────
describe("detectCycles", () => {
it("returns empty for acyclic graph", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02", ["01"]), task("03", ["02"])),
});
expect(detectCycles(project)).toEqual([]);
});
it("detects a 3-node cycle", () => {
const project = makeProject({
tasks: tasksFrom(
task("01", ["03"]),
task("02", ["01"]),
task("03", ["02"]),
),
});
const cycles = detectCycles(project);
expect(cycles.length).toBeGreaterThan(0);
});
it("detects a self-loop", () => {
const project = makeProject({
tasks: tasksFrom(task("01", ["01"])),
});
const cycles = detectCycles(project);
expect(cycles.length).toBeGreaterThan(0);
});
it("detects cycle in disconnected subgraph", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"), // isolated
task("02", ["03"]),
task("03", ["02"]), // cycle
),
});
const cycles = detectCycles(project);
expect(cycles.length).toBeGreaterThan(0);
});
it("returns empty for graph with only diamond patterns", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02", "03"]),
),
});
expect(detectCycles(project)).toEqual([]);
});
});
// ─── getCriticalPath ─────────────────────────────────────────────────────────
describe("getCriticalPath", () => {
it("returns the longest path through the DAG", () => {
// 01 -> 02 -> 03 -> 04 (long = 4)
// 01 -> 05 -> 04 (short = 3)
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04", ["03", "05"]),
task("05", ["01"]),
),
});
const path = getCriticalPath(project);
expect(path.length).toBe(4);
expect(path[0].id).toBe("01");
expect(path[path.length - 1].id).toBe("04");
});
it("returns single-node path for roots", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02"), task("03")),
});
const path = getCriticalPath(project);
expect(path.length).toBe(1);
});
it("handles complex branching by picking the longest chain", () => {
// 01 -> 02 -> 03 -> 04 -> 05 (long = 5)
// 01 -> 06 -> 05 (short = 3)
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["02"]),
task("04", ["03"]),
task("05", ["04", "06"]),
task("06", ["01"]),
),
});
const path = getCriticalPath(project);
// Should pick 01 -> 02 -> 03 -> 04 -> 05 (length 5)
expect(path.length).toBe(5);
expect(path.map((t) => t.id)).toEqual(["01", "02", "03", "04", "05"]);
});
});
// ─── formatDependencyChain ───────────────────────────────────────────────────
describe("formatDependencyChain", () => {
it("renders a simple tree", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02", ["01"])),
});
const formatted = formatDependencyChain(project);
expect(formatted).toContain("01");
expect(formatted).toContain("02");
});
it("mentions root tasks", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02")),
});
const formatted = formatDependencyChain(project);
expect(formatted).toMatch(/01.*root|root.*01/i);
});
it("handles empty task list", () => {
const project = makeProject({ tasks: [] });
const formatted = formatDependencyChain(project);
expect(formatted).toContain("no tasks");
});
it("shows orphan tasks when dependencies reference non-existent IDs", () => {
const project = makeProject({
tasks: tasksFrom(task("01", ["99"])),
});
const formatted = formatDependencyChain(project);
expect(formatted).toMatch(/orphan|unreached/i);
});
});
// ─── formatExecutionPlan ─────────────────────────────────────────────────────
describe("formatExecutionPlan", () => {
it("displays task counts and batches", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02", ["01"])),
});
const plan = buildExecutionPlan(project, new Set());
const formatted = formatExecutionPlan(plan);
expect(formatted).toContain("Total tasks");
expect(formatted).toContain("Batches");
expect(formatted).toContain("01");
expect(formatted).toContain("02");
});
it("shows skipped tasks", () => {
const project = makeProject({
tasks: tasksFrom(task("01", [], "completed"), task("02", ["01"])),
});
const plan = buildExecutionPlan(project, new Set(["01"]));
const formatted = formatExecutionPlan(plan);
expect(formatted).toContain("completed");
});
it("shows parallel group annotations when provided", () => {
const project = makeProject({
tasks: tasksFrom(task("01"), task("02", ["01"]), task("03", ["01"])),
parallelGroups: [{ index: 0, label: "UI sprint", taskIds: ["02", "03"] }],
});
const plan = buildExecutionPlan(project, new Set());
const formatted = formatExecutionPlan(plan, project.parallelGroups);
expect(formatted).toContain("UI sprint");
});
});
// ─── Group-Aware Batching ────────────────────────────────────────────────────
describe("Parallel group batching", () => {
it("builds batches when parallel groups are defined", () => {
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02", "03"]),
),
parallelGroups: [
{ index: 0, label: "Frontend", taskIds: ["01", "02", "03", "04"] },
],
});
// Should route through buildGroupAwareBatches
const plan = buildExecutionPlan(project, new Set());
expect(plan.batches.length).toBeGreaterThan(0);
});
it("respects intra-group dependencies in parallel groups", () => {
// Tasks: 01 -> 02, 01 -> 03, 02 -> 04, 03 -> 04
// With parallel groups, there are no cross-group dependencies by definition.
// Intra-group deps are respected by Kahn's algorithm.
const project = makeProject({
tasks: tasksFrom(
task("01"),
task("02", ["01"]),
task("03", ["01"]),
task("04", ["02", "03"]),
),
parallelGroups: [
{ index: 0, label: "All", taskIds: ["01", "02", "03", "04"] },
],
});
const plan = buildExecutionPlan(project, new Set());
// Batch 0: [01], Batch 1: [02, 03], Batch 2: [04]
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[1].tasks.map((t) => t.id).sort()).toEqual(["02", "03"]);
expect(plan.batches[2].tasks.map((t) => t.id)).toEqual(["04"]);
});
});
// ─── Real-World Scenario: Resume with completed tasks ───────────────────────
describe("Real-world resume scenarios", () => {
it("buildExecutionPlan correctly excludes file-based [x] completions", () => {
// Design Token PRD resume: 01,02,03 [x] in file, 04 [~], 05 [ ]
const project = makeProject({
tasks: tasksFrom(
task("01", [], "completed"),
task("02", ["01"], "completed"),
task("03", ["01"], "completed"),
task("04", ["02", "03"], "in_progress"),
task("05", ["04", "01"], "pending"),
),
});
// buildCompletedSet in index.ts produces {01, 02, 03} from file + progress
// This simulates what happens after buildCompletedSet is called
const completedFromFile = new Set(
project.tasks.filter((t) => t.status === "completed").map((t) => t.id),
);
const plan = buildExecutionPlan(project, completedFromFile);
// Only 04 and 05 should be pending
expect(plan.totalTasks).toBe(2);
expect(plan.batches).toHaveLength(2);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["04"]);
expect(plan.batches[1].tasks.map((t) => t.id)).toEqual(["05"]);
});
it("skipsTasks includes both progress-completed and file-completed tasks", () => {
const project = makeProject({
tasks: tasksFrom(
task("01", [], "completed"),
task("02", ["01"], "pending"),
),
});
// Simulate: 01 completed in file AND in progress
const plan = buildExecutionPlan(project, new Set(["01"]));
expect(plan.skippedTasks.map((t) => t.id)).toEqual(["01"]);
expect(plan.batches[0].tasks.map((t) => t.id)).toEqual(["02"]);
});
});

237
tests/diff.test.ts Normal file
View File

@@ -0,0 +1,237 @@
/**
* Tests for the noise-filtered diff engine (src/diff.ts).
* Covers: per-file +/ parsing, excluded-file split, totals excluding noise,
* malformed-chunk guard, isExcluded reasons, and configurable overrides.
*/
import { describe, test, expect } from "bun:test";
import {
parseDiff,
filterNoise,
isExcluded,
compileIgnorePatterns,
EXCLUDED_PATTERNS,
} from "../src/diff";
/** A synthetic unified diff mixing code, a lockfile, a minified file, and a binary. */
const SYNTH_DIFF = [
"diff --git a/src/index.ts b/src/index.ts",
"index 111..222 100644",
"--- a/src/index.ts",
"+++ b/src/index.ts",
"@@ -1,2 +1,4 @@",
' import { foo } from "./foo";',
"+export const baz = 1;",
"+export const qux = 2;",
"-foo();",
"+bar();",
"",
"diff --git a/package-lock.json b/package-lock.json",
"index 000..111 100644",
"--- a/package-lock.json",
"+++ b/package-lock.json",
"@@ -0,0 +1,3 @@",
"+{",
'+ "name": "x"',
"+}",
"",
"diff --git a/dist/foo.min.js b/dist/foo.min.js",
"index 111..222 100644",
"--- a/dist/foo.min.js",
"+++ b/dist/foo.min.js",
"@@ -1 +1 @@",
"-var a=1;",
"+var a=2;",
"",
"diff --git a/assets/logo.png b/assets/logo.png",
"index 111..222 100644",
"Binary files differ",
].join("\n");
describe("parseDiff", () => {
test("splits included vs excluded files and totals only included", () => {
const summary = parseDiff(SYNTH_DIFF);
// Included: only src/index.ts (code). Lockfile, minified, binary excluded.
expect(summary.files).toHaveLength(1);
expect(summary.files[0]).toEqual({
path: "src/index.ts",
linesAdded: 3,
linesRemoved: 1,
ext: "ts",
});
expect(summary.excluded).toHaveLength(3);
const byPath = new Map(
summary.excluded.map((f) => [f.path, f]),
);
expect(byPath.get("package-lock.json")).toMatchObject({
linesAdded: 3,
linesRemoved: 0,
reason: "lockfile",
});
expect(byPath.get("dist/foo.min.js")).toMatchObject({
linesAdded: 1,
linesRemoved: 1,
reason: "minified asset",
});
expect(byPath.get("assets/logo.png")).toMatchObject({
linesAdded: 0,
linesRemoved: 0,
reason: "binary/media asset",
});
// Totals exclude the noise files.
expect(summary.totalAdded).toBe(3);
expect(summary.totalRemoved).toBe(1);
});
test("returns empty summary for an empty diff", () => {
const summary = parseDiff("");
expect(summary.files).toHaveLength(0);
expect(summary.excluded).toHaveLength(0);
expect(summary.totalAdded).toBe(0);
expect(summary.totalRemoved).toBe(0);
});
test("skips malformed chunks without a/… b/ header without crashing", () => {
const malformed =
"diff --git weird-line\nindex 111..222\n--- a/x\n+++ b/x\n+x\n" +
"\n" +
"diff --git a/src/ok.ts b/src/ok.ts\n--- a/src/ok.ts\n+++ b/src/ok.ts\n+ok\n";
const summary = parseDiff(malformed);
// Only the well-formed chunk is counted.
expect(summary.files).toHaveLength(1);
expect(summary.files[0].path).toBe("src/ok.ts");
expect(summary.totalAdded).toBe(1);
});
test("does not count +++/--- header lines as additions/removals", () => {
const diff = [
"diff --git a/src/a.ts b/src/a.ts",
"--- a/src/a.ts",
"+++ b/src/a.ts",
"@@ -0,0 +1,2 @@",
"+one",
"+two",
].join("\n");
const summary = parseDiff(diff);
expect(summary.files[0].linesAdded).toBe(2);
expect(summary.files[0].linesRemoved).toBe(0);
});
});
describe("isExcluded", () => {
test("returns the right reason per pattern", () => {
expect(isExcluded("package-lock.json")).toBe("lockfile");
expect(isExcluded("yarn.lock")).toBe("lockfile");
expect(isExcluded("src/app.min.js")).toBe("minified asset");
expect(isExcluded("src/styles.min.css")).toBe("minified asset");
expect(isExcluded("build/out.js")).toBe("build output");
expect(isExcluded("node_modules/foo/index.js")).toBe("dependency");
expect(isExcluded("vendor/lib.bundle.js")).toBe("vendored dependency");
expect(isExcluded("assets/icon.svg")).toBe("binary/media asset");
expect(isExcluded("src/api.generated.ts")).toBe("generated file");
expect(isExcluded("test/__snapshots__/x.snap")).toBe("snapshot");
expect(isExcluded("dist/x.js.map")).toBe("source map");
});
test("returns undefined for review-relevant files", () => {
expect(isExcluded("src/foo.ts")).toBeUndefined();
expect(isExcluded("src/index.ts")).toBeUndefined();
});
test("merges caller-supplied extra patterns", () => {
expect(isExcluded("src/data.foo", [/\.foo$/])).toBe("extra ignore pattern");
expect(isExcluded("src/data.foo")).toBeUndefined();
});
test("EXCLUDED_PATTERNS covers lockfiles, min, generated, snap, map, build, vendor, binaries", () => {
for (const pat of [
"package-lock.json",
"src/app.min.js",
"src/thing.generated.ts",
"x.snap",
"x.js.map",
"dist/bundle.js",
"node_modules/a/b.js",
"vendor/x",
"a.png",
"f.woff2",
]) {
const hit = EXCLUDED_PATTERNS.some((r) => r.pattern.test(pat));
expect(hit, `${pat} should be covered by a default rule`).toBe(true);
}
});
});
describe("filterNoise", () => {
test("re-emits only included-file chunks", () => {
const filtered = filterNoise(SYNTH_DIFF);
expect(filtered).toContain("diff --git a/src/index.ts");
expect(filtered).not.toContain("package-lock.json");
expect(filtered).not.toContain("foo.min.js");
expect(filtered).not.toContain("logo.png");
});
test("returns empty when every file is noise", () => {
const onlyNoise = [
"diff --git a/package-lock.json b/package-lock.json",
"--- a/package-lock.json",
"+++ b/package-lock.json",
"+x",
].join("\n");
expect(filterNoise(onlyNoise)).toBe("");
});
});
describe("configurable noise rules", () => {
test("extraPatterns excludes a matching file from the review diff", () => {
const diff = [
"diff --git a/src/foo.ts b/src/foo.ts",
"--- a/src/foo.ts",
"+++ b/src/foo.ts",
"+keep",
"diff --git a/src/data.foo b/src/data.foo",
"--- a/src/data.foo",
"+++ b/src/data.foo",
"+drop",
].join("\n");
const opts = { extraPatterns: compileIgnorePatterns(["\\.foo$"]) };
const summary = parseDiff(diff, opts);
expect(summary.files.map((f) => f.path)).toEqual(["src/foo.ts"]);
expect(summary.excluded.map((f) => [f.path, f.reason])).toEqual([
["src/data.foo", "extra ignore pattern"],
]);
expect(filterNoise(diff, opts)).not.toContain("data.foo");
});
test("ignorePaths keeps an excluded-by-default file in scope", () => {
const diff = [
"diff --git a/package-lock.json b/package-lock.json",
"--- a/package-lock.json",
"+++ b/package-lock.json",
"+a",
"+b",
"+c",
].join("\n");
const opts = { ignorePaths: ["package-lock.json"] };
const summary = parseDiff(diff, opts);
expect(summary.files).toHaveLength(1);
expect(summary.files[0].path).toBe("package-lock.json");
expect(summary.excluded).toHaveLength(0);
expect(summary.totalAdded).toBe(3);
expect(filterNoise(diff, opts)).toContain("package-lock.json");
});
test("default behavior unchanged when overrides are unset", () => {
const summary = parseDiff(SYNTH_DIFF);
expect(summary.files[0].path).toBe("src/index.ts");
expect(summary.totalAdded).toBe(3);
});
test("compileIgnorePatterns skips invalid regexes", () => {
const compiled = compileIgnorePatterns(["\\.foo$", "(", "ok$"]);
expect(compiled.length).toBe(2);
});
});

View File

@@ -0,0 +1,96 @@
import { describe, expect, it } from "bun:test";
import * as fs from "node:fs";
import * as path from "node:path";
import { tempDir } from "./helpers";
import { ensureRalpiIgnored } from "../src/utils";
// ─── Gitignore hygiene: ensureRalpiIgnored ──────────────────────────────────
describe("ensureRalpiIgnored", () => {
it("creates .gitignore with .ralpi/ when absent in a git work tree", () => {
const { dir, cleanup } = tempDir();
try {
fs.mkdirSync(path.join(dir, ".git"));
expect(ensureRalpiIgnored(dir)).toBe(true);
const content = fs.readFileSync(path.join(dir, ".gitignore"), "utf8");
expect(content).toContain(".ralpi/");
} finally {
cleanup();
}
});
it("appends .ralpi/ to an existing .gitignore without the marker", () => {
const { dir, cleanup } = tempDir();
try {
fs.mkdirSync(path.join(dir, ".git"));
fs.writeFileSync(
path.join(dir, ".gitignore"),
"node_modules/\n*.log\n",
"utf8",
);
expect(ensureRalpiIgnored(dir)).toBe(true);
const content = fs.readFileSync(path.join(dir, ".gitignore"), "utf8");
expect(content).toContain("node_modules/");
expect(content).toContain(".ralpi/");
} finally {
cleanup();
}
});
it("leaves a .gitignore with the marker untouched", () => {
const { dir, cleanup } = tempDir();
try {
fs.mkdirSync(path.join(dir, ".git"));
fs.writeFileSync(path.join(dir, ".gitignore"), ".ralpi/\n", "utf8");
expect(ensureRalpiIgnored(dir)).toBe(false);
expect(fs.readFileSync(path.join(dir, ".gitignore"), "utf8")).toBe(
".ralpi/\n",
);
} finally {
cleanup();
}
});
it("is a no-op outside a git work tree", () => {
const { dir, cleanup } = tempDir();
try {
expect(ensureRalpiIgnored(dir)).toBe(false);
expect(fs.existsSync(path.join(dir, ".gitignore"))).toBe(false);
} finally {
cleanup();
}
});
it("is memoized per project dir", () => {
const { dir, cleanup } = tempDir();
try {
fs.mkdirSync(path.join(dir, ".git"));
expect(ensureRalpiIgnored(dir)).toBe(true);
// Second call: same dir already handled → no further work.
expect(ensureRalpiIgnored(dir)).toBe(false);
fs.writeFileSync(path.join(dir, ".gitignore"), "old\n", "utf8");
expect(ensureRalpiIgnored(dir)).toBe(false);
expect(fs.readFileSync(path.join(dir, ".gitignore"), "utf8")).toBe(
"old\n",
);
} finally {
cleanup();
}
});
it("works when .git is a file (linked git worktree)", () => {
const { dir, cleanup } = tempDir();
try {
fs.writeFileSync(
path.join(dir, ".git"),
"gitdir: /some/shared/repo\n",
"utf8",
);
expect(ensureRalpiIgnored(dir)).toBe(true);
const content = fs.readFileSync(path.join(dir, ".gitignore"), "utf8");
expect(content).toContain(".ralpi/");
} finally {
cleanup();
}
});
});

30
tests/helpers.ts Normal file
View File

@@ -0,0 +1,30 @@
import * as fs from "node:fs";
import * as path from "node:path";
import * as os from "node:os";
// ─── Helpers ────────────────────────────────────────────────────────────────
/**
* Create a temporary directory for test files.
* Returns the path and a cleanup function.
*/
export function tempDir(): { dir: string; cleanup: () => void } {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ralpi-test-"));
return {
dir,
cleanup: () => fs.rmSync(dir, { recursive: true, force: true }),
};
}
/**
* Write content to a temp markdown file and return its path.
*/
export function writeTaskFile(
dir: string,
name: string,
content: string,
): string {
const filePath = path.join(dir, name);
fs.writeFileSync(filePath, content, "utf-8");
return filePath;
}

1119
tests/parser-dag.test.ts Normal file

File diff suppressed because it is too large Load Diff

1321
tests/parser-formats.test.ts Normal file

File diff suppressed because it is too large Load Diff

521
tests/parser-phased.test.ts Normal file
View File

@@ -0,0 +1,521 @@
/**
* Tests for phased task format parsing
* Covers: phase detection, task parsing, phase boundaries, implicit dependencies
*/
import { describe, test, expect } from "bun:test";
import { parseTaskFile } from "../src/parser";
import type { Task } from "../src/types";
import { tempDir, writeTaskFile } from "./helpers";
/** Parse a task file from an inline template literal. */
function parse(content: string) {
const { dir, cleanup } = tempDir();
try {
const filePath = writeTaskFile(dir, "README.md", content);
return { project: parseTaskFile(filePath), cleanup };
} catch (e) {
cleanup();
throw e;
}
}
describe("Phased task format", () => {
describe("Phase detection", () => {
test("detects phased format with markdown headings", () => {
const content = `# Voice Conversation
## Phase 1 - MVP
- [ ] 01 - Build voice pipeline
- [ ] 02 - Add audio playback
## Phase 2 - Streaming
- [ ] 03 - WebSocket channel
- [ ] 04 - Streaming STT
## Dependencies
- 02 depends on 01
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases).toBeDefined();
expect(project.phases?.length).toBe(2);
expect(project.phases?.[0].number).toBe(1);
expect(project.phases?.[0].title).toBe("MVP");
expect(project.phases?.[1].number).toBe(2);
expect(project.phases?.[1].title).toBe("Streaming");
} finally {
cleanup();
}
});
test("detects phased format with plain headings", () => {
const content = `# Voice Conversation
Phase 1 - MVP
- [ ] 01 - Build voice pipeline
- [ ] 02 - Add audio playback
Phase 2 - Streaming
- [ ] 03 - WebSocket channel
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases).toBeDefined();
expect(project.phases?.length).toBe(2);
} finally {
cleanup();
}
});
test("supports various separators in phase headings", () => {
const variants = [
"## Phase 1 - MVP",
"## Phase 1 - MVP",
"## Phase 1 - MVP",
"## Phase 1: MVP",
"## Phase 1 - MVP", // multiple spaces
];
for (const heading of variants) {
const content = `# Test
${heading}
- [ ] 01 - Task
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases).toBeDefined();
expect(project.phases?.length).toBe(1);
} finally {
cleanup();
}
}
});
test("handles phase headings with extra whitespace", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Task
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases).toBeDefined();
expect(project.phases?.length).toBe(1);
} finally {
cleanup();
}
});
});
describe("Task parsing within phases", () => {
test("assigns phase number to tasks", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Task A
- [ ] 02 - Task B
## Phase 2 - Enhancement
- [ ] 03 - Task C
- [ ] 04 - Task D
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.tasks[0].id).toBe("01");
expect(project.tasks[0].phase).toBe(1);
expect(project.tasks[1].id).toBe("02");
expect(project.tasks[1].phase).toBe(1);
expect(project.tasks[2].id).toBe("03");
expect(project.tasks[2].phase).toBe(2);
expect(project.tasks[3].id).toBe("04");
expect(project.tasks[3].phase).toBe(2);
} finally {
cleanup();
}
});
test("tracks task IDs in each phase", () => {
const content = `# Test
## Phase 1 - Foundation
- [ ] 01 - Setup
- [ ] 02 - Config
## Phase 2 - Implementation
- [ ] 03 - Feature A
- [ ] 04 - Feature B
- [ ] 05 - Feature C
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases?.[0].taskIds).toEqual(["01", "02"]);
expect(project.phases?.[1].taskIds).toEqual(["03", "04", "05"]);
} finally {
cleanup();
}
});
test("handles tasks with different statuses in phases", () => {
const content = `# Test
## Phase 1 - MVP
- [x] 01 - Done task
- [ ] 02 - Pending task
- [~] 03 - In progress
## Phase 2 - Next
- [ ] 04 - Future task
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.tasks[0].status).toBe("completed");
expect(project.tasks[1].status).toBe("pending");
expect(project.tasks[2].status).toBe("in_progress");
expect(project.tasks[3].status).toBe("pending");
expect(project.phases?.[0].taskIds).toEqual(["01", "02", "03"]);
expect(project.phases?.[1].taskIds).toEqual(["04"]);
} finally {
cleanup();
}
});
test("handles empty phases", () => {
const content = `# Test
## Phase 1 - Empty
## Phase 2 - Has tasks
- [ ] 01 - Task
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases?.length).toBe(1);
expect(project.phases?.[0].number).toBe(2);
expect(project.phases?.[0].taskIds).toEqual(["01"]);
} finally {
cleanup();
}
});
});
describe("Implicit phase-boundary dependencies", () => {
test("adds dependency from first task of phase 2 to last task of phase 1", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Setup
- [ ] 02 - Build
## Phase 2 - Enhancement
- [ ] 03 - Feature
- [ ] 04 - Test
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
// Task 03 should depend on task 02 (implicit phase boundary)
expect(
project.tasks.find((t: Task) => t.id === "03")?.dependencies,
).toContain("02");
} finally {
cleanup();
}
});
test("adds dependencies across multiple phases", () => {
const content = `# Test
## Phase 1 - Foundation
- [ ] 01 - Setup
## Phase 2 - Core
- [ ] 02 - Build
- [ ] 03 - Test
## Phase 3 — Polish
- [ ] 04 — Refine
- [ ] 05 — Release
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
// Task 02 depends on task 01 (phase 1 → 2 boundary)
expect(
project.tasks.find((t: Task) => t.id === "02")?.dependencies,
).toContain("01");
// Task 04 depends on task 03 (phase 2 → 3 boundary)
expect(
project.tasks.find((t: Task) => t.id === "04")?.dependencies,
).toContain("03");
} finally {
cleanup();
}
});
test("does not duplicate explicit dependencies", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Setup
- [ ] 02 - Build
## Phase 2 — Enhancement
- [ ] 03 — Feature
## Dependencies
- 03 depends on 02
`;
const { project, cleanup } = parse(content);
try {
const task03 = project.tasks.find((t: Task) => t.id === "03");
const depCount = task03?.dependencies.filter(
(d: string) => d === "02",
).length;
expect(depCount).toBe(1); // Should not duplicate
} finally {
cleanup();
}
});
test("handles single phase (no boundaries)", () => {
const content = `# Test
## Phase 1 - All tasks
- [ ] 01 - Task A
- [ ] 02 - Task B
## Dependencies
`;
const { project, cleanup } = parse(content);
try {
// No implicit dependencies should be added
expect(project.tasks[0].dependencies).toEqual([]);
expect(project.tasks[1].dependencies).toEqual([]);
} finally {
cleanup();
}
});
test("works alongside explicit dependencies", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Setup
- [ ] 02 - Build
## Phase 2 - Enhancement
- [ ] 03 - Feature A
- [ ] 04 - Feature B
## Dependencies
- 04 depends on 03
`;
const { project, cleanup } = parse(content);
try {
// Task 03 has implicit dependency on task 02
expect(
project.tasks.find((t: Task) => t.id === "03")?.dependencies,
).toContain("02");
// Task 04 has explicit dependency on task 03
expect(
project.tasks.find((t: Task) => t.id === "04")?.dependencies,
).toContain("03");
// Task 04 should NOT have implicit dependency on task 02
expect(
project.tasks.find((t: Task) => t.id === "04")?.dependencies,
).not.toContain("02");
} finally {
cleanup();
}
});
});
describe("Mixed formats", () => {
test("phased format with arrow dependencies", () => {
const content = `# Test
## Phase 1 - Setup
- [ ] 01 - Initialize
- [ ] 02 - Configure
## Phase 2 - Build
- [ ] 03 - Compile
- [ ] 04 - Bundle
## Dependencies
- 01 → 02
- 03 → 04
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases?.length).toBe(2);
expect(
project.tasks.find((t: Task) => t.id === "02")?.dependencies,
).toContain("01");
expect(
project.tasks.find((t: Task) => t.id === "04")?.dependencies,
).toContain("03");
expect(
project.tasks.find((t: Task) => t.id === "03")?.dependencies,
).toContain("02");
} finally {
cleanup();
}
});
test("phased format with parallel groups", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Setup
- [ ] 02 - Build
## Phase 2 - Enhancement
- [ ] 03 - Feature
- [ ] 04 - Test
## Dependencies
- 01, 02 can be done in parallel
- 03, 04 can be done in parallel
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases?.length).toBe(2);
expect(project.parallelGroups?.length).toBe(2);
expect(
project.tasks.find((t: Task) => t.id === "03")?.dependencies,
).toContain("02");
} finally {
cleanup();
}
});
test("phased format with exit criteria", () => {
const content = `# Test
## Phase 1 - MVP
- [ ] 01 - Build
- [ ] 02 - Test
## Phase 2 - Release
- [ ] 03 - Deploy
## Dependencies
## Exit Criteria
- All tests pass
- Deployment successful
`;
const { project, cleanup } = parse(content);
try {
expect(project.phases?.length).toBe(2);
expect(project.exitCriteria?.length).toBe(2);
} finally {
cleanup();
}
});
});
describe("Real-world example", () => {
test("parses voice conversation PRD correctly", () => {
const content = `# Voice Conversation
Objective: Add full voice conversation capability
## Phase 1 - Push-to-Talk MVP
- [ ] 01 - Build voice pipeline orchestrator → \`01-voice-pipeline-orchestrator.md\`
- [ ] 02 - Build auto-playback audio module → \`02-auto-playback-audio-module.md\`
- [ ] 03 - Wire voice mode toggle into chat UI → \`03-voice-mode-toggle-ui.md\`
- [ ] 04 - End-to-end push-to-talk integration test → \`04-push-to-talk-integration-test.md\`
## Phase 2 - Streaming & Real-Time
- [ ] 05 - Build WebSocket voice channel → \`05-websocket-voice-channel.md\`
- [ ] 06 - Implement streaming STT pipeline → \`06-streaming-stt-pipeline.md\`
- [ ] 07 - Implement streaming TTS pipeline → \`07-streaming-tts-pipeline.md\`
## Phase 3 - Optimization & Hardening
- [ ] 08 - Model quantization and VRAM budget manager → \`08-model-quantization.md\`
- [ ] 09 - Latency profiling and pipeline optimization → \`09-latency-profiling.md\`
## Dependencies
- 02 depends on 01
- 03 depends on 01, 02
- 04 depends on 03
- 06 depends on 05
- 07 depends on 05
- 09 depends on 08
## Exit Criteria
- Users can hold multi-turn voice conversations
- Total round-trip latency under 3s
`;
const { project, cleanup } = parse(content);
try {
// Verify phases
expect(project.phases?.length).toBe(3);
expect(project.phases?.[0].title).toBe("Push-to-Talk MVP");
expect(project.phases?.[1].title).toBe("Streaming & Real-Time");
expect(project.phases?.[2].title).toBe("Optimization & Hardening");
// Verify task phases
expect(project.tasks[0].phase).toBe(1);
expect(project.tasks[4].phase).toBe(2);
expect(project.tasks[7].phase).toBe(3);
// Verify phase boundaries
// Task 05 (first in phase 2) depends on task 04 (last in phase 1)
expect(
project.tasks.find((t: Task) => t.id === "05")?.dependencies,
).toContain("04");
// Task 08 (first in phase 3) depends on task 07 (last in phase 2)
expect(
project.tasks.find((t: Task) => t.id === "08")?.dependencies,
).toContain("07");
// Verify explicit dependencies still work
expect(
project.tasks.find((t: Task) => t.id === "02")?.dependencies,
).toContain("01");
expect(
project.tasks.find((t: Task) => t.id === "03")?.dependencies,
).toContain("01");
expect(
project.tasks.find((t: Task) => t.id === "03")?.dependencies,
).toContain("02");
// Verify task files
expect(project.tasks[0].file).toBe("01-voice-pipeline-orchestrator.md");
expect(project.tasks[1].file).toBe("02-auto-playback-audio-module.md");
// Verify exit criteria
expect(project.exitCriteria?.length).toBe(2);
expect(project.objective).toBe("Voice Conversation");
} finally {
cleanup();
}
});
});
});

View File

@@ -0,0 +1,82 @@
/// <reference types="bun-types" />
import { describe, it, expect, beforeEach } from "bun:test";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { ProgressTracker } from "../src/progress";
/**
* Regression test: two concurrent loops (different PRDs) each run their own
* ProgressTracker. Each instance snapshots the whole state at construction;
* a save() that writes that stale snapshot verbatim would revert the OTHER
* loop's task status changes — tasks wrongly back to "pending" while their
* worktrees carry real work, stranding it on the next resume.
*/
let root: string;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "ralpi-prog-test-"));
});
function prdA(projectDir: string): ProgressTracker {
return new ProgressTracker(
projectDir,
path.join(projectDir, "tasks/a/README.md"),
);
}
function prdB(projectDir: string): ProgressTracker {
return new ProgressTracker(
projectDir,
path.join(projectDir, "tasks/b/README.md"),
);
}
/** Read the on-disk progress state; the file is written by the tracker, so
* a parse failure is a test bug worth surfacing. */
function readState(): Record<string, any> {
const raw = fs.readFileSync(
path.join(root, ".ralpi", "progress.json"),
"utf-8",
);
try {
return JSON.parse(raw) as Record<string, any>;
} catch {
throw new Error(`malformed progress.json:\n${raw.slice(0, 200)}`);
}
}
describe("ProgressTracker multi-PRD save isolation", () => {
it("does not clobber another PRD's task status on save", () => {
const a = prdA(root);
const b = prdB(root);
expect(a.getKey()).not.toBe(b.getKey());
// Loop A marks its task in_progress.
a.markInProgress("01");
expect(a.getTaskStatus("01")).toBe("in_progress");
// Loop B (stale snapshot from before A's update) marks ITS task.
b.markInProgress("02");
// The on-disk state must show BOTH updates.
const raw = readState();
expect(raw.prds[a.getKey()].tasks["01"].status).toBe("in_progress");
expect(raw.prds[b.getKey()].tasks["02"].status).toBe("in_progress");
});
it("preserves other PRD completions when this PRD saves", () => {
const a = prdA(root);
const b = prdB(root);
a.markCompleted("01", 1000);
b.markInProgress("02");
// A completes another task later — A's save must not revert B.
a.markCompleted("03", 500);
const raw = readState();
expect(raw.prds[a.getKey()].tasks["01"].status).toBe("completed");
expect(raw.prds[a.getKey()].tasks["03"].status).toBe("completed");
expect(raw.prds[b.getKey()].tasks["02"].status).toBe("in_progress");
});
});

View File

@@ -0,0 +1,87 @@
/// <reference types="bun-types" />
import { describe, it, expect, beforeEach } from "bun:test";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { ProgressTracker } from "../src/progress";
import { countPRDResumeStats } from "../src/utils";
/**
* Regression test: the resume-selection prompt under-reported task totals
* when multiple loop histories existed. The progress tracker only records
* TOUCHED tasks (started/completed/failed) — never-started tasks are absent
* from prd.tasks, so a naive Object.keys() count missed them entirely, and
* file-checked completions were ignored unless markCompleted had run.
* countPRDResumeStats derives the true total from the parsed PRD file and
* counts checkbox completions too.
*/
let root: string;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "ralpi-stats-test-"));
});
const PRD_CONTENT = `# Test PRD
## Tasks
- [ ] Task one
- [x] Task two
- [ ] Task three
- [ ] Task four
`;
function writePRD(rel: string): string {
const p = path.join(root, rel);
fs.mkdirSync(path.dirname(p), { recursive: true });
fs.writeFileSync(p, PRD_CONTENT, "utf-8");
return p;
}
describe("countPRDResumeStats", () => {
it("reports the full task total from the PRD file, not just touched tasks", () => {
const sourcePath = writePRD("tasks/a/README.md");
const progress = new ProgressTracker(root, sourcePath);
// Simple-checkbox format assigns sequential ids 00-03. Only 00
// (completed) and 02 (failed) were touched by the loop; 01 is checked
// off in the file; 03 was never started.
progress.markCompleted("00", 1000);
progress.markFailed("02", "boom");
const stats = countPRDResumeStats(progress.getState(), sourcePath);
expect(stats.total).toBe(4); // old code reported 2
expect(stats.completed).toBe(2); // 00 via progress + 01 via checkbox
expect(stats.failed).toBe(1);
});
it("does not double-count a task that is both progress-completed and file-checked", () => {
const sourcePath = writePRD("tasks/b/README.md");
const progress = new ProgressTracker(root, sourcePath);
progress.markCompleted("01", 500); // 01 already [x] in the file
const stats = countPRDResumeStats(progress.getState(), sourcePath);
expect(stats.completed).toBe(1);
});
it("falls back to touched-task counts when the PRD file is missing", () => {
const missing = path.join(root, "tasks/gone/README.md");
const progress = new ProgressTracker(root, missing);
progress.markCompleted("01", 1000);
progress.markFailed("02", "nope");
const stats = countPRDResumeStats(progress.getState(), missing);
expect(stats.total).toBe(2);
expect(stats.completed).toBe(1);
expect(stats.failed).toBe(1);
});
it("reports zero for a never-touched PRD with no file", () => {
const missing = path.join(root, "tasks/none/README.md");
const progress = new ProgressTracker(root, missing);
const stats = countPRDResumeStats(progress.getState(), missing);
expect(stats.total).toBe(0);
expect(stats.completed).toBe(0);
expect(stats.failed).toBe(0);
});
});

303
tests/review-prompt.test.ts Normal file
View File

@@ -0,0 +1,303 @@
/**
* Tests for the review prompt builders (src/prompts.ts).
* Covers: per-file summary table, excluded-files section, oversized-diff
* read-instruction (never byte-truncates), custom review focus, and the
* configurable noise-filter overrides surfacing in the prompt.
*/
import { describe, test, expect } from "bun:test";
import {
buildReviewPrompt,
buildReviewPromptUncommitted,
} from "../src/prompts";
import { compileIgnorePatterns } from "../src/diff";
import type { Task, Project } from "../src/types";
const task: Task = {
id: "01",
title: "Implement auth",
description: "Add a login flow",
status: "completed",
dependencies: [],
};
const project: Project = {
objective: "Build the app",
sourcePath: "README.md",
sourceDir: "/tmp",
tasks: [task],
dependencies: {},
};
/** A diff mixing one code file plus lockfile/minified/binary noise. */
const MIXED_DIFF = [
"diff --git a/src/auth.ts b/src/auth.ts",
"index 111..222 100644",
"--- a/src/auth.ts",
"+++ b/src/auth.ts",
"@@ -1,3 +1,5 @@",
' import { hash } from "./hash";',
"+export function login() {",
"+ return hash(secret);",
"- return legacy();",
"+}",
"",
"diff --git a/package-lock.json b/package-lock.json",
"index 000..111 100644",
"--- a/package-lock.json",
"+++ b/package-lock.json",
"@@ -0,0 +1,3 @@",
"+{",
'+ "name": "x"',
"+}",
"",
"diff --git a/assets/logo.png b/assets/logo.png",
"index 111..222 100644",
"Binary files differ",
"",
"diff --git a/dist/app.min.js b/dist/app.min.js",
"index 111..222 100644",
"--- a/dist/app.min.js",
"+++ b/dist/app.min.js",
"@@ -1 +1 @@",
"-var a=1;",
"+var a=2;",
].join("\n");
function manyFileDiff(n: number): string {
const chunks: string[] = [];
for (let i = 0; i < n; i++) {
chunks.push(
`diff --git a/src/f${String(i).padStart(2, "0")}.ts b/src/f${String(i).padStart(2, "0")}.ts`,
"--- a/src/f.ts",
"+++ b/src/f.ts",
`+line ${i}`,
);
}
return chunks.join("\n");
}
describe("buildReviewPrompt", () => {
test("emits a per-file +/ summary table with totals, excluding noise", () => {
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
MIXED_DIFF,
);
expect(prompt).toContain("### Changed Files");
expect(prompt).toContain("| `src/auth.ts` | +3/-1 | ts |");
expect(prompt).toContain("| **Total** | **+3/-1** | |");
});
test("surfaces an excluded-files section with path, counts, and reason", () => {
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
MIXED_DIFF,
);
expect(prompt).toContain("### Excluded Files (3)");
expect(prompt).toContain("- `package-lock.json` (+3/-0) — lockfile");
expect(prompt).toContain(
"- `assets/logo.png` (+0/-0) — binary/media asset",
);
expect(prompt).toContain("- `dist/app.min.js` (+1/-1) — minified asset");
});
test("never inlines excluded (noise) chunks into the diff block", () => {
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
MIXED_DIFF,
);
// The noise chunks themselves are never inlined — only the excluded-files
// section names them (as `- path (+x/-y) — reason`, no `diff --git` header).
expect(prompt).not.toContain("diff --git a/package-lock.json");
expect(prompt).not.toContain("diff --git a/assets/logo.png");
expect(prompt).not.toContain("diff --git a/dist/app.min.js");
// The cleaned diff block is present with the code file.
expect(prompt).toContain("```diff");
expect(prompt).toContain("diff --git a/src/auth.ts");
});
test("omits the excluded section entirely when nothing is excluded", () => {
const clean = [
"diff --git a/src/auth.ts b/src/auth.ts",
"--- a/src/auth.ts",
"+++ b/src/auth.ts",
"+export const x = 1;",
].join("\n");
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
clean,
);
expect(prompt).not.toContain("### Excluded Files");
expect(prompt).toContain("| `src/auth.ts` | +1/-0 | ts |");
});
test("switches to a file-list + read instruction for >20 files, no truncation", () => {
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: many",
manyFileDiff(21),
);
expect(prompt).toContain("Diff too large");
expect(prompt).toContain("Use `read` to inspect the changed files");
// No byte-truncated inline diff for oversized inputs.
expect(prompt).not.toContain("```diff");
});
test("switches to a file-list + read instruction for a >50KB diff, no truncation", () => {
// One file but a huge cleaned diff — crosses MAX_DIFF_BYTES (50_000).
const huge = [
"diff --git a/src/auth.ts b/src/auth.ts",
"--- a/src/auth.ts",
"+++ b/src/auth.ts",
...Array.from(
{ length: 26000 },
() => "+padding line to blow past the size threshold",
),
].join("\n");
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
huge,
);
expect(prompt).toContain("Diff too large");
expect(prompt).toContain("Use `read` to inspect the changed files");
expect(prompt).toContain("src/auth.ts");
// No byte-truncated inline diff for the oversized input.
expect(prompt).not.toContain("```diff");
});
test("a small diff over the file-count branch still inlines under size threshold", () => {
// 5 files, small diff — under MAX_REVIEW_FILES and MAX_DIFF_BYTES → inlined.
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: small",
manyFileDiff(5),
);
expect(prompt).toContain("```diff");
expect(prompt).not.toContain("Diff too large");
});
test("inlines a small diff normally (no read-instruction)", () => {
const prompt = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
MIXED_DIFF,
);
expect(prompt).not.toContain("Diff too large");
});
test("emits a Custom Review Focus section only when focus is set", () => {
const withFocus = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
MIXED_DIFF,
{ focus: "check security only" },
);
expect(withFocus).toContain("## Custom Review Focus");
expect(withFocus).toContain("check security only");
const withoutFocus = buildReviewPrompt(
task,
project,
"abc1234",
"feat: auth",
MIXED_DIFF,
);
expect(withoutFocus).not.toContain("## Custom Review Focus");
});
test("surfaces extra ignore patterns and ignorePaths overrides in the prompt", () => {
const diff = [
"diff --git a/src/keep.ts b/src/keep.ts",
"--- a/src/keep.ts",
"+++ b/src/keep.ts",
"+keep",
"diff --git a/package-lock.json b/package-lock.json",
"--- a/package-lock.json",
"+++ b/package-lock.json",
"+a",
"+b",
"+c",
"+d",
].join("\n");
// ignorePaths keeps the lockfile in scope → it shows in the table,
// and no excluded section is emitted.
const kept = buildReviewPrompt(task, project, "abc1234", "x", diff, {
diffOptions: { ignorePaths: ["package-lock.json"] },
});
expect(kept).toContain("| `package-lock.json` | +4/-0 | json |");
expect(kept).not.toContain("### Excluded Files");
// Without ignorePaths, the lockfile is excluded.
const excluded = buildReviewPrompt(task, project, "abc1234", "x", diff);
expect(excluded).not.toContain("| `package-lock.json` |");
expect(excluded).toContain("### Excluded Files (1)");
// extraPatterns drops a matching file from scope.
const dropped = buildReviewPrompt(task, project, "abc1234", "x", diff, {
diffOptions: {
extraPatterns: compileIgnorePatterns(["\\.ts$"]),
ignorePaths: [],
},
});
expect(dropped).not.toContain("| `src/keep.ts` |");
expect(dropped).toContain("### Excluded Files (2)");
});
});
describe("buildReviewPromptUncommitted", () => {
test("emits summary table, excluded section, and cleaned diff", () => {
const prompt = buildReviewPromptUncommitted(
task,
project,
"M src/auth.ts",
MIXED_DIFF,
);
expect(prompt).toContain("### Changed Files");
expect(prompt).toContain("| `src/auth.ts` | +3/-1 | ts |");
expect(prompt).toContain("### Excluded Files (3)");
expect(prompt).not.toContain("diff --git a/package-lock.json");
expect(prompt).toContain("### Current Tracked Diff (git diff)");
});
test("supports custom focus", () => {
const prompt = buildReviewPromptUncommitted(
task,
project,
"M src/auth.ts",
MIXED_DIFF,
{ focus: "review performance" },
);
expect(prompt).toContain("## Custom Review Focus");
expect(prompt).toContain("review performance");
});
});

View File

@@ -0,0 +1,53 @@
/**
* Tests for the severity taxonomy alignment in review verdict parsing
* (src/review.ts): the `critical` token is accepted and normalized to
* ralpi's `blocker` severity, mirroring @piex-dev/review's grading.
*/
import { describe, test, expect } from "bun:test";
import { extractReview } from "../src/review";
/** Build a full review-agent output ending in a REVIEW VERDICT block. */
function reviewOutput(findings: string[]): string {
return [
"Prose: looks mostly fine, a few issues to fix.",
"## REVIEW VERDICT",
"VERDICT: fail",
"SUMMARY: Needs fixes.",
"FINDINGS:",
...findings,
].join("\n");
}
describe("extractReview severity normalization", () => {
test("maps critical → blocker, keeps warning/nit/info", () => {
const out = reviewOutput([
"- [critical] src/auth.ts:12 hardcoded secret",
"- [warning] src/auth.ts:30 unused import",
"- [nit] src/auth.ts:5 style",
"- [info] src/auth.ts:1 note",
]);
const review = extractReview(out, "01", "abc1234");
expect(review).not.toBeNull();
const severities = review!.findings.map((f) => f.severity);
expect(severities).toEqual(["blocker", "warning", "nit", "info"]);
});
test("normalizes the warn synonym to warning", () => {
const out = reviewOutput(["- [warn] src/a.ts:2 thing"]);
const review = extractReview(out, "01", "abc1234");
expect(review!.findings[0].severity).toBe("warning");
});
test("uppercase CRITICAL token also maps to blocker", () => {
const out = reviewOutput(["- [CRITICAL] src/a.ts:2 thing"]);
const review = extractReview(out, "01", "abc1234");
expect(review!.findings[0].severity).toBe("blocker");
});
test("findings without a severity are still parsed", () => {
const out = reviewOutput(["- src/a.ts:2 plain line"]);
const review = extractReview(out, "01", "abc1234");
expect(review!.findings[0].severity).toBe("info");
});
});

View File

@@ -0,0 +1,265 @@
/// <reference types="bun-types" />
import { describe, it, expect, beforeEach } from "bun:test";
import { execSync } from "node:child_process";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import {
createWorktree,
finalizeCommittedWorktrees,
mergeWorktree,
removeWorktree,
worktreeHasPreservableWork,
} from "../src/worktree";
/**
* Regression tests for worktree resume/finalize behavior:
*
* 1. finalizeCommittedWorktrees merges a committed worktree branch even
* when the worktree carries UNTRACKED files (previously the dirty check
* counted `??` entries, stranding committed code in .ralpi/worktrees/).
* 2. finalize works for tasks that are NOT in_progress (pending) — the
* stranded-work case after an interrupted resume.
* 3. createWorktree reuses an existing worktree under a symlinked project
* path (git porcelain emits realpaths; literal path.join must not be
* compared verbatim).
* 4. worktreeHasPreservableWork keeps failed-task branches alive so a
* timeout doesn't destroy commits the agent already made.
*/
const sh = (cmd: string, cwd: string): string => {
try {
return execSync(cmd, { cwd, encoding: "utf-8" }).trim();
} catch (err) {
throw new Error(
`git cmd failed in ${cwd}: ${cmd}\n${(err as Error).message}`,
);
}
};
const STATE_DIR = ".ralpi";
const PRD_KEY = "prd";
function makeRepo(root: string): void {
sh("git init -q -b master .", root);
sh("git config user.email t@t.co", root);
sh("git config user.name T", root);
sh("echo '# Demo' > README.md", root);
sh("git add -A && git commit -qm init", root);
}
/** Commit work in a worktree and record the commit message. */
function commitInWorktree(wt: { dir: string }, filename: string, msg: string) {
sh(`echo '${filename} content' > ${filename}`, wt.dir);
sh(`git add -A && git commit -qm '${msg}'`, wt.dir);
}
function masterHasFile(root: string, filename: string): boolean {
try {
sh(`git show master:${filename}`, root);
return true;
} catch {
return false;
}
}
let root: string;
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "ralpi-wt-test-"));
makeRepo(root);
});
describe("finalizeCommittedWorktrees", () => {
it("merges a committed worktree branch even when untracked files exist", () => {
const wt = createWorktree(
root,
STATE_DIR,
"01",
PRD_KEY,
undefined,
"task one",
)!;
commitInWorktree(wt, "work.txt", "task 01 work");
// The task agent left a scratch file untracked (like build artifacts).
sh("mkdir -p scratch && echo junk > scratch/junk.bin", wt.dir);
expect(sh("git status --porcelain", wt.dir)).toContain("??");
const fin = finalizeCommittedWorktrees(root, STATE_DIR, PRD_KEY, ["01"]);
expect(fin.finalized).toEqual(["01"]);
expect(masterHasFile(root, "work.txt")).toBe(true);
});
it("finalizes tasks that are pending (not in_progress) with committed work", () => {
const wt = createWorktree(
root,
STATE_DIR,
"02",
PRD_KEY,
undefined,
"task two",
)!;
commitInWorktree(wt, "b.txt", "task 02 work");
// Simulate a prior interrupted resume: task reset to pending, branch
// never merged.
const fin = finalizeCommittedWorktrees(root, STATE_DIR, PRD_KEY, ["02"]);
expect(fin.finalized).toEqual(["02"]);
expect(masterHasFile(root, "b.txt")).toBe(true);
});
it("leaves a worktree with uncommitted TRACKED edits for re-run", () => {
const wt = createWorktree(
root,
STATE_DIR,
"03",
PRD_KEY,
undefined,
"task three",
)!;
commitInWorktree(wt, "c.txt", "task 03 work");
// Agent was mid-edit when interrupted: a tracked file modified.
sh("echo more >> README.md", wt.dir);
const fin = finalizeCommittedWorktrees(root, STATE_DIR, PRD_KEY, ["03"]);
expect(fin.finalized).toEqual([]);
expect(fin.rerun).toEqual(["03"]);
expect(masterHasFile(root, "c.txt")).toBe(false);
});
it("does not re-merge an already-merged branch", () => {
const wt = createWorktree(
root,
STATE_DIR,
"04",
PRD_KEY,
undefined,
"task four",
)!;
commitInWorktree(wt, "d.txt", "task 04 work");
expect(mergeWorktree(root, wt.branch).success).toBe(true);
removeWorktree(root, wt);
// Re-create a worktree on the same (now-merged) branch tip: nothing
// ahead of main → re-run, no spurious merge.
const wt2 = createWorktree(
root,
STATE_DIR,
"04",
PRD_KEY,
undefined,
"task four",
)!;
commitInWorktree(wt2, "e.txt", "task 04 more work");
const fin = finalizeCommittedWorktrees(root, STATE_DIR, PRD_KEY, ["04"]);
expect(fin.finalized).toEqual(["04"]);
expect(masterHasFile(root, "e.txt")).toBe(true);
});
it("reports conflicts and preserves the worktree", () => {
const wt = createWorktree(
root,
STATE_DIR,
"05",
PRD_KEY,
undefined,
"task five",
)!;
// Both sides edit f.txt: master AFTER the worktree exists, so the
// branches genuinely diverge and the merge must conflict.
sh(
"echo master > f.txt && git add -A && git commit -qm 'master f.txt'",
root,
);
sh("echo worktree > f.txt", wt.dir);
sh("git add -A && git commit -qm 'task 05 work'", wt.dir);
const fin = finalizeCommittedWorktrees(root, STATE_DIR, PRD_KEY, ["05"]);
expect(fin.finalized).toEqual([]);
expect(fin.conflicts["05"]).toBeTruthy();
// worktree preserved for manual resolution
expect(fs.existsSync(wt.dir)).toBe(true);
});
});
describe("createWorktree resume reuse under symlinked paths", () => {
it("reuses an existing worktree when the project path contains a symlink", () => {
// macOS /tmp → /private/tmp style symlink: git porcelain reports the
// REAL path, path.join keeps the literal one. Reuse must still match.
const realBase = fs.mkdtempSync(path.join(os.tmpdir(), "ralpi-wt-real-"));
const link = path.join(realBase, "link");
fs.mkdirSync(path.join(realBase, "repo"));
fs.symlinkSync(path.join(realBase, "repo"), link);
const symRoot = link;
makeRepo(symRoot);
// Sanity: this is genuinely a symlink situation.
expect(fs.realpathSync(symRoot)).not.toBe(symRoot);
const wt = createWorktree(
symRoot,
STATE_DIR,
"01",
PRD_KEY,
undefined,
"task one",
)!;
commitInWorktree(wt, "a.txt", "task 01 work");
// Resume: createWorktree again must REUSE the registered worktree
// (same dir), not fail and fall through to the main repo.
const reused = createWorktree(
symRoot,
STATE_DIR,
"01",
PRD_KEY,
undefined,
"task one",
)!;
expect(reused.dir).toBe(fs.realpathSync(wt.dir));
const fin = finalizeCommittedWorktrees(symRoot, STATE_DIR, PRD_KEY, ["01"]);
expect(fin.finalized).toEqual(["01"]);
expect(masterHasFile(fs.realpathSync(symRoot), "a.txt")).toBe(true);
});
});
describe("worktreeHasPreservableWork", () => {
it("returns true for a worktree with committed work ahead of main", () => {
const wt = createWorktree(
root,
STATE_DIR,
"01",
PRD_KEY,
undefined,
"task one",
)!;
commitInWorktree(wt, "a.txt", "task 01 work");
expect(worktreeHasPreservableWork(root, wt)).toBe(true);
});
it("returns true for a worktree with uncommitted changes", () => {
const wt = createWorktree(
root,
STATE_DIR,
"01",
PRD_KEY,
undefined,
"task one",
)!;
sh("echo x > junk.txt", wt.dir);
expect(worktreeHasPreservableWork(root, wt)).toBe(true);
});
it("returns false for an empty fresh worktree", () => {
const wt = createWorktree(
root,
STATE_DIR,
"01",
PRD_KEY,
undefined,
"task one",
)!;
expect(worktreeHasPreservableWork(root, wt)).toBe(false);
});
});

16
tsconfig.json Normal file
View File

@@ -0,0 +1,16 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"noEmit": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
},
"include": ["index.ts", "src/**/*"],
"exclude": ["node_modules", "dist"]
}