feat: add plan2code-bot with --resume capability and state cleanup

Add the autonomous workflow test runner (plan2code-bot) that uses the
Claude Agent SDK to run plan2code end-to-end. Includes --resume flag
to continue incomplete runs from saved state, and automatic state file
cleanup on successful completion.
This commit is contained in:
2026-03-01 21:30:45 -08:00
parent 63656d339d
commit c92865c395
22 changed files with 2267 additions and 3 deletions
+257 -3
View File
@@ -1405,8 +1405,10 @@ function runInteractive() {
console.log(''); console.log('');
const metricsResult = installPlan2CodeMetrics(); const metricsResult = installPlan2CodeMetrics();
console.log(''); console.log('');
const botResult = installPlan2CodeBot();
console.log('');
const installResult = install(); const installResult = install();
const exitCode = loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : installResult; const exitCode = loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : installResult;
process.exit(exitCode); process.exit(exitCode);
} }
@@ -1430,7 +1432,8 @@ function runInteractive() {
const uninstallResult = uninstallFiles(); const uninstallResult = uninstallFiles();
const loopResult = uninstallPlan2CodeLoop(); const loopResult = uninstallPlan2CodeLoop();
const metricsResult = uninstallPlan2CodeMetrics(); const metricsResult = uninstallPlan2CodeMetrics();
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult; const botResult = uninstallPlan2CodeBot();
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult;
process.exit(exitCode); process.exit(exitCode);
} else { } else {
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELLED${COLORS.RESET}\n`); console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELLED${COLORS.RESET}\n`);
@@ -1448,10 +1451,11 @@ function runInteractive() {
console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}L.${COLORS.RESET} ${COLORS.BLUE}LOCAL${COLORS.RESET} Show local (project) install instructions`, 65) + `${COLORS.CYAN}${COLORS.RESET}`); console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}L.${COLORS.RESET} ${COLORS.BLUE}LOCAL${COLORS.RESET} Show local (project) install instructions`, 65) + `${COLORS.CYAN}${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}O.${COLORS.RESET} ${COLORS.GREEN}LOOP CLI${COLORS.RESET} Install plan2code-loop CLI only`, 65) + `${COLORS.CYAN}${COLORS.RESET}`); console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}O.${COLORS.RESET} ${COLORS.GREEN}LOOP CLI${COLORS.RESET} Install plan2code-loop CLI only`, 65) + `${COLORS.CYAN}${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}M.${COLORS.RESET} ${COLORS.GREEN}METRICS${COLORS.RESET} Install plan2code-metrics CLI only`, 65) + `${COLORS.CYAN}${COLORS.RESET}`); console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}M.${COLORS.RESET} ${COLORS.GREEN}METRICS${COLORS.RESET} Install plan2code-metrics CLI only`, 65) + `${COLORS.CYAN}${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}B.${COLORS.RESET} ${COLORS.GREEN}BOT${COLORS.RESET} Install plan2code-bot CLI only`, 65) + `${COLORS.CYAN}${COLORS.RESET}`);
console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}Q.${COLORS.RESET} ${COLORS.DIM}BACK${COLORS.RESET} Return to main menu`, 65) + `${COLORS.CYAN}${COLORS.RESET}`); console.log(padEndVisible(`${COLORS.CYAN}${COLORS.RESET} ${COLORS.BRIGHT}Q.${COLORS.RESET} ${COLORS.DIM}BACK${COLORS.RESET} Return to main menu`, 65) + `${COLORS.CYAN}${COLORS.RESET}`);
console.log(`${COLORS.CYAN}╚════════════════════════════════════════════════════════════════╝${COLORS.RESET}`); console.log(`${COLORS.CYAN}╚════════════════════════════════════════════════════════════════╝${COLORS.RESET}`);
console.log(''); console.log('');
const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, Q) [Q]: `); const customAnswer = await question(`${COLORS.CYAN}${SYMBOLS.SELECT} SELECT OPTION${COLORS.RESET} (L, O, M, B, Q) [Q]: `);
const customInput = customAnswer.trim().toUpperCase() || 'Q'; const customInput = customAnswer.trim().toUpperCase() || 'Q';
// Task 2.6: C > L — show local install instructions // Task 2.6: C > L — show local install instructions
@@ -1474,6 +1478,13 @@ function runInteractive() {
process.exit(result); process.exit(result);
} }
// C > B — install bot CLI only
if (customInput === 'B') {
rl.close();
const result = installPlan2CodeBot();
process.exit(result);
}
// Task 2.8: C > Q — back to main menu // Task 2.8: C > Q — back to main menu
return main(); return main();
} }
@@ -2014,6 +2025,249 @@ function uninstallPlan2CodeMetrics() {
return 0; return 0;
} }
// ============================================================================
// PLAN2CODE-BOT INSTALLATION
// ============================================================================
/**
* Build plan2code-bot package
*/
function buildPlan2CodeBot() {
const botDir = path.join(__dirname, 'plan2code-bot');
if (!fs.existsSync(botDir)) {
console.log(`${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} plan2code-bot directory not found`);
return false;
}
console.log(`${COLORS.CYAN}${SYMBOLS.ACTIVE} Building plan2code-bot...${COLORS.RESET}`);
try {
console.log(` ${COLORS.DIM}Installing dependencies...${COLORS.RESET}`);
execSync('npm install', { cwd: botDir, stdio: 'pipe' });
console.log(` ${COLORS.DIM}Running build...${COLORS.RESET}`);
execSync('npm run build', { cwd: botDir, stdio: 'pipe' });
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Build complete`);
return true;
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Build failed: ${error.message}`);
return false;
}
}
/**
* Clean up existing plan2code-bot symlinks/files before creating new ones
*/
function cleanupExistingBotSymlinks() {
console.log(` ${COLORS.DIM}Cleaning up existing symlinks...${COLORS.RESET}`);
try {
const npmPrefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
const npmBinGlobal = process.platform === 'win32' ? npmPrefix : path.join(npmPrefix, 'bin');
const npmRootGlobal = path.join(npmPrefix, 'node_modules');
const binFiles = [
path.join(npmBinGlobal, 'plan2code-bot'),
path.join(npmBinGlobal, 'plan2code-bot.cmd'),
path.join(npmBinGlobal, 'plan2code-bot.ps1')
];
const nodeModulesLink = path.join(npmRootGlobal, 'plan2code-bot');
for (const file of binFiles) {
try {
const stats = fs.lstatSync(file);
if (stats) {
fs.unlinkSync(file);
console.log(` ${COLORS.DIM}Removed: ${path.basename(file)}${COLORS.RESET}`);
}
} catch (err) {
if (err.code !== 'ENOENT') {
try {
fs.rmSync(file, { force: true, recursive: true });
console.log(` ${COLORS.DIM}Removed: ${path.basename(file)}${COLORS.RESET}`);
} catch (rmErr) {
console.log(` ${COLORS.DIM}Could not remove: ${path.basename(file)}${COLORS.RESET}`);
}
}
}
}
try {
const stats = fs.lstatSync(nodeModulesLink);
if (stats) {
if (process.platform === 'win32') {
try {
fs.rmdirSync(nodeModulesLink);
console.log(` ${COLORS.DIM}Removed: node_modules/plan2code-bot (junction)${COLORS.RESET}`);
} catch (rmdirErr) {
fs.rmSync(nodeModulesLink, { force: true, recursive: true });
console.log(` ${COLORS.DIM}Removed: node_modules/plan2code-bot${COLORS.RESET}`);
}
} else {
fs.rmSync(nodeModulesLink, { force: true, recursive: true });
console.log(` ${COLORS.DIM}Removed: node_modules/plan2code-bot${COLORS.RESET}`);
}
}
} catch (err) {
if (err.code !== 'ENOENT') {
console.log(` ${COLORS.DIM}Could not remove node_modules symlink: ${err.message}${COLORS.RESET}`);
}
}
return true;
} catch (error) {
console.log(` ${COLORS.DIM}Cleanup skipped: ${error.message}${COLORS.RESET}`);
return true;
}
}
/**
* Create global symlink for plan2code-bot
*/
function createBotGlobalSymlink() {
const botDir = path.join(__dirname, 'plan2code-bot');
const distBin = path.join(botDir, 'dist', 'bin', 'plan2code-bot.js');
if (!fs.existsSync(distBin)) {
console.log(`${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} plan2code-bot binary not found. Run build first.`);
return false;
}
console.log(`${COLORS.CYAN}${SYMBOLS.ACTIVE} Creating global symlink...${COLORS.RESET}`);
cleanupExistingBotSymlinks();
if (process.platform === 'win32') {
try {
const npmPrefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
const symlinkCmd = path.join(npmPrefix, 'plan2code-bot.cmd');
const symlinkPs1 = path.join(npmPrefix, 'plan2code-bot.ps1');
const batchContent = `@echo off\r\nnode "${distBin}" %*\r\n`;
fs.writeFileSync(symlinkCmd, batchContent);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Created: plan2code-bot.cmd`);
const ps1Content = `#!/usr/bin/env pwsh\r\nnode "${distBin}" $args\r\n`;
fs.writeFileSync(symlinkPs1, ps1Content);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Created: plan2code-bot.ps1`);
console.log(` ${COLORS.DIM}Run 'plan2code-bot' from any directory${COLORS.RESET}`);
return true;
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to create wrappers: ${error.message}`);
return false;
}
}
try {
execSync('npm link', { cwd: botDir, stdio: 'pipe' });
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Global symlink created`);
console.log(` ${COLORS.DIM}Run 'plan2code-bot' from any directory${COLORS.RESET}`);
return true;
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Symlink failed: ${error.message}`);
return false;
}
}
/**
* Remove global symlink for plan2code-bot
*/
function removeBotGlobalSymlink() {
console.log(`${COLORS.CYAN}${SYMBOLS.ACTIVE} Removing global symlink...${COLORS.RESET}`);
let removedCount = 0;
try {
const npmPrefix = execSync('npm config get prefix', { encoding: 'utf8' }).trim();
const npmBinGlobal = process.platform === 'win32' ? npmPrefix : path.join(npmPrefix, 'bin');
const npmRootGlobal = path.join(npmPrefix, 'node_modules');
const filesToRemove = [
{ path: path.join(npmBinGlobal, 'plan2code-bot'), name: 'plan2code-bot' },
{ path: path.join(npmBinGlobal, 'plan2code-bot.cmd'), name: 'plan2code-bot.cmd' },
{ path: path.join(npmBinGlobal, 'plan2code-bot.ps1'), name: 'plan2code-bot.ps1' },
{ path: path.join(npmRootGlobal, 'plan2code-bot'), name: 'node_modules/plan2code-bot' }
];
for (const file of filesToRemove) {
try {
fs.lstatSync(file.path);
try {
fs.rmdirSync(file.path);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file.name}`);
removedCount++;
} catch (rmdirErr) {
try {
fs.unlinkSync(file.path);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file.name}`);
removedCount++;
} catch (unlinkErr) {
fs.rmSync(file.path, { force: true, recursive: true });
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file.name}`);
removedCount++;
}
}
} catch (err) {
// File doesn't exist, skip it
}
}
if (removedCount === 0) {
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No files found to remove${COLORS.RESET}`);
}
return true;
} catch (error) {
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Uninstall failed: ${error.message}`);
return false;
}
}
/**
* Install plan2code-bot (build + symlink)
*/
function installPlan2CodeBot() {
displaySectionHeader('PLAN2CODE-BOT', '[ BUILD & INSTALL ]');
const buildSuccess = buildPlan2CodeBot();
if (!buildSuccess) {
return 1;
}
const symlinkSuccess = createBotGlobalSymlink();
if (!symlinkSuccess) {
return 1;
}
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot installed successfully!${COLORS.RESET}`);
console.log('');
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
console.log(` ${COLORS.BRIGHT}plan2code-bot${COLORS.RESET} Run autonomous workflow test`);
console.log('');
return 0;
}
/**
* Uninstall plan2code-bot
*/
function uninstallPlan2CodeBot() {
displaySectionHeader('PLAN2CODE-BOT', '[ UNINSTALL ]');
removeBotGlobalSymlink();
console.log('');
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot uninstalled${COLORS.RESET}`);
console.log('');
return 0;
}
// ============================================================================ // ============================================================================
// MAIN // MAIN
// ============================================================================ // ============================================================================
+111
View File
@@ -0,0 +1,111 @@
# plan2code-bot
Autonomous workflow test runner for plan2code. Uses the Claude Agent SDK to simulate a human running through the entire plan2code workflow (init, plan, document, implement, finalize) end-to-end.
## Two Modes (Auto-Detected)
1. **New Project Mode** — No `AGENTS.md` in cwd: generates an app idea, creates a subdirectory, writes IDEA.md, runs init, then all 4 steps.
2. **Enhancement Mode**`AGENTS.md` exists in cwd: scans the existing codebase and proposes a realistic enhancement, writes IDEA.md, then runs plan through finalize.
## Installation
From the plan2code root:
```bash
node install.js
# Select C > B to install bot only, or I to install everything
```
Or manually:
```bash
cd plan2code-bot
npm install
npm run build
npm link
```
## Usage
```bash
# New project mode (run from an empty directory)
mkdir /tmp/test-bot && cd /tmp/test-bot
plan2code-bot
# Enhancement mode (run from an existing project with AGENTS.md)
cd my-project
plan2code-bot
# Seed the idea generator with a specific concept
plan2code-bot --idea "web app that displays the current weather as vector images"
# Resume a previous incomplete run
plan2code-bot --resume
```
### `--idea`
Pass a quoted string after `--idea` to seed the idea generator with a specific concept. The AI will use it as inspiration rather than generating a completely random idea. Wrap the value in double quotes so the shell treats it as a single argument.
```bash
# Specific app concept
plan2code-bot --idea "web app that displays the current weather as vector images"
# Short keyword to nudge the category
plan2code-bot --idea "markdown editor"
# Detailed constraint
plan2code-bot --idea "CLI tool that converts CSV files to SQLite databases with type inference"
# Works in enhancement mode too — guides what kind of enhancement to propose
cd my-existing-project
plan2code-bot --idea "add dark mode support"
```
Without `--idea`, the bot picks a random category (CLI tool or web app) and invents something on its own.
### `--resume`
Resume a previous incomplete run. The bot searches for a `.plan2code-bot-state.json` file in the current directory (enhancement mode) or in immediate subdirectories (new-project mode). If found, it restores the idea, config, and progress — skipping steps that already succeeded and continuing from where it left off.
```bash
# A run failed at the implement step — resume it
plan2code-bot --resume
# Can combine with --idea (idea is ignored when resuming since it's restored from state)
plan2code-bot --resume --idea "ignored when state exists"
```
If no state file is found, the bot starts a fresh run.
## How It Works
1. Detects mode based on presence of `AGENTS.md`
2. Generates an idea (new app or enhancement) via Claude, optionally guided by `--idea` seed
3. Writes `IDEA.md` to the project directory
4. Installs bot-friendly copies of plan2code skills (strips `disable-model-invocation` so sessions can invoke them)
5. Runs each workflow step as a separate Claude Agent SDK session:
- **init** — generates `AGENTS.md` (new-project mode only)
- **plan** — creates plan draft in `specs/<feature>/`
- **document** — produces `overview.md` and `phase-*.md` files
- **implement** — loops until all phases are complete (max 10 passes)
- **finalize** — validates and archives to `specs--completed/`
6. Validates expected artifacts after each step (aborts on missing artifacts)
7. Moves `IDEA.md` into `specs/<feature>/` after the plan step so it stays with its feature
8. Auto-responds to `AskUserQuestion` prompts (approvals, testing gates, name questions)
9. Saves state to `.plan2code-bot-state.json` after each step
## State File
After each step, the bot saves its state to `.plan2code-bot-state.json` in the project directory. This includes the config, all step results, and progress tracking.
- **On full success** — the state file is automatically deleted (clean finish)
- **On failure/incomplete** — the state file is preserved so you can `--resume` later
## Development
```bash
npm run build # Build with tsup
npm run dev # Watch mode
npm test # Run tests (vitest)
```
+36
View File
@@ -0,0 +1,36 @@
{
"name": "plan2code-bot",
"version": "1.0.0",
"description": "Plan2Code Bot - Autonomous workflow runner for testing plan2code end-to-end",
"type": "module",
"main": "dist/index.js",
"bin": {
"plan2code-bot": "./dist/bin/plan2code-bot.js"
},
"files": [
"dist"
],
"engines": {
"node": ">=18.0.0"
},
"scripts": {
"build": "tsup",
"dev": "tsup --watch",
"start": "node dist/bin/plan2code-bot.js",
"test": "vitest run",
"prepublishOnly": "npm run build"
},
"dependencies": {
"@anthropic-ai/claude-agent-sdk": "^0.2.63",
"chalk": "^5.6.2",
"fs-extra": "^11.3.3",
"ora": "^9.0.0"
},
"devDependencies": {
"@types/fs-extra": "^11.0.4",
"@types/node": "^25.0.3",
"tsup": "^8.5.1",
"typescript": "^5.9.3",
"vitest": "^4.0.18"
}
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, it, expect } from 'vitest';
import { createAutoResponder } from './auto-responder.js';
import type { BotConfig } from './types.js';
const config: BotConfig = {
workDir: '/tmp/work',
projectDir: '/tmp/work/my-app',
ideaDescription: 'A test app',
ideaName: 'test-app',
mode: 'new-project',
};
describe('createAutoResponder', () => {
it('returns allow for non-AskUserQuestion tools', async () => {
const responder = createAutoResponder(config, 'plan');
const result = await responder('Bash', { command: 'ls' });
expect(result.behavior).toBe('allow');
expect((result as any).updatedInput).toBeUndefined();
});
it('injects answers for AskUserQuestion with approval keywords', async () => {
const responder = createAutoResponder(config, 'plan');
const result = await responder('AskUserQuestion', {
questions: [
{
question: 'Do you approve this plan?',
options: [
{ label: 'Yes', description: 'Approve' },
{ label: 'No', description: 'Reject' },
],
},
],
});
expect(result.behavior).toBe('allow');
const updated = (result as any).updatedInput;
expect(updated.answers['Do you approve this plan?']).toBe('Yes');
});
it('selects skip/none for testing questions', async () => {
const responder = createAutoResponder(config, 'implement');
const result = await responder('AskUserQuestion', {
questions: [
{
question: 'How should we run tests?',
options: [
{ label: 'Full suite', description: 'Run all tests' },
{ label: 'Skip', description: 'Skip testing' },
],
},
],
});
expect(result.behavior).toBe('allow');
const updated = (result as any).updatedInput;
expect(updated.answers['How should we run tests?']).toBe('Skip');
});
it('uses project name for plan step name questions', async () => {
const responder = createAutoResponder(config, 'plan');
const result = await responder('AskUserQuestion', {
questions: [
{
question: 'What is the name of this feature?',
options: [
{ label: 'Feature A', description: 'First' },
{ label: 'Feature B', description: 'Second' },
],
},
],
});
expect(result.behavior).toBe('allow');
const updated = (result as any).updatedInput;
// Plan step + "name" keyword → uses config.ideaName
expect(updated.answers['What is the name of this feature?']).toBe('test-app');
});
it('falls back to first option for unknown questions', async () => {
const responder = createAutoResponder(config, 'init');
const result = await responder('AskUserQuestion', {
questions: [
{
question: 'What color is the sky?',
options: [
{ label: 'Blue', description: 'The usual' },
{ label: 'Red', description: 'Sunset' },
],
},
],
});
expect(result.behavior).toBe('allow');
const updated = (result as any).updatedInput;
expect(updated.answers['What color is the sky?']).toBe('Blue');
});
});
+117
View File
@@ -0,0 +1,117 @@
import type { BotConfig, StepName } from './types.js';
interface AskUserQuestionInput {
questions: Array<{
question: string;
options: Array<{
label: string;
description: string;
}>;
multiSelect?: boolean;
}>;
}
function findOption(
options: AskUserQuestionInput['questions'][0]['options'],
...keywords: string[]
): string | null {
for (const keyword of keywords) {
const match = options.find((o) =>
o.label.toLowerCase().includes(keyword.toLowerCase())
);
if (match) return match.label;
}
return null;
}
function buildAnswers(input: AskUserQuestionInput, config: BotConfig, step: StepName): Record<string, string> {
const answers: Record<string, string> = {};
for (const q of input.questions) {
const questionText = q.question.toLowerCase();
const options = q.options;
// Approval gates — find yes/approve/confirm option or pick first
if (
questionText.includes('approve') ||
questionText.includes('confirm') ||
questionText.includes('proceed') ||
questionText.includes('ready') ||
questionText.includes('look good') ||
questionText.includes('sign off') ||
questionText.includes('sign-off')
) {
const opt = findOption(options, 'approve', 'yes', 'confirm', 'proceed', 'ready');
answers[q.question] = opt ?? options[0].label;
continue;
}
// Testing questions — skip or none
if (
questionText.includes('test') ||
questionText.includes('testing')
) {
const opt = findOption(options, 'skip', 'none', 'no');
answers[q.question] = opt ?? options[0].label;
continue;
}
// Plan step: additional files/references
if (step === 'plan' && (questionText.includes('additional') || questionText.includes('reference'))) {
const opt = findOption(options, 'no', 'none', 'skip');
answers[q.question] = opt ?? options[0].label;
continue;
}
// Plan step: feature name question
if (step === 'plan' && questionText.includes('name')) {
answers[q.question] = config.ideaName;
continue;
}
// Implement step: pick first phase or approve
if (step === 'implement') {
const opt = findOption(options, 'approve', 'yes', 'continue', 'proceed');
answers[q.question] = opt ?? options[0].label;
continue;
}
// Finalize step: approve docs and give feedback
if (step === 'finalize') {
if (questionText.includes('rating') || questionText.includes('feedback')) {
const opt = findOption(options, '8', '9', '10');
answers[q.question] = opt ?? options[0].label;
continue;
}
const opt = findOption(options, 'approve', 'yes', 'confirm');
answers[q.question] = opt ?? options[0].label;
continue;
}
// Default: pick first option
answers[q.question] = options[0].label;
}
return answers;
}
export function createAutoResponder(config: BotConfig, step: StepName) {
return async (
toolName: string,
input: Record<string, unknown>,
): Promise<{ behavior: 'allow'; updatedInput?: Record<string, unknown> } | { behavior: 'deny'; message: string }> => {
// Auto-respond to AskUserQuestion
if (toolName === 'AskUserQuestion') {
const askInput = input as unknown as AskUserQuestionInput;
const answers = buildAnswers(askInput, config, step);
return {
behavior: 'allow',
updatedInput: { ...input, answers },
};
}
// Allow all other tools
return { behavior: 'allow' };
};
}
+25
View File
@@ -0,0 +1,25 @@
import { runCLI } from '../cli.js';
function parseArgs(): { idea?: string; resume?: boolean } {
const args = process.argv.slice(2);
const ideaIdx = args.indexOf('--idea');
const idea = ideaIdx !== -1 && ideaIdx + 1 < args.length ? args[ideaIdx + 1] : undefined;
const resume = args.includes('--resume');
return { idea, resume: resume || undefined };
}
async function main() {
try {
const { idea, resume } = parseArgs();
await runCLI({ idea, resume });
process.exit(0);
} catch (err) {
if (err instanceof Error && err.message.includes('User force closed')) {
process.exit(0);
}
console.error(err instanceof Error ? err.message : String(err));
process.exit(1);
}
}
main();
+121
View File
@@ -0,0 +1,121 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs-extra';
import path from 'path';
import os from 'os';
import { saveState, loadState, deleteState, findExistingState } from './bot-state.js';
import type { BotState } from './types.js';
function makeTmpDir(): string {
return fs.mkdtempSync(path.join(os.tmpdir(), 'bot-state-test-'));
}
function makeState(projectDir: string): BotState {
return {
config: {
workDir: path.dirname(projectDir),
projectDir,
ideaName: 'test-idea',
ideaDescription: 'A test idea',
mode: 'new-project',
},
steps: [],
currentStep: null,
implementPasses: 0,
allPhasesComplete: false,
};
}
describe('bot-state', () => {
let tmpDir: string;
beforeEach(() => {
tmpDir = makeTmpDir();
});
afterEach(() => {
fs.removeSync(tmpDir);
});
describe('saveState', () => {
it('writes valid JSON', () => {
const projectDir = path.join(tmpDir, 'project');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const filePath = path.join(projectDir, '.plan2code-bot-state.json');
expect(fs.existsSync(filePath)).toBe(true);
const parsed = fs.readJsonSync(filePath);
expect(parsed.config.ideaName).toBe('test-idea');
});
});
describe('loadState', () => {
it('returns state from file', () => {
const projectDir = path.join(tmpDir, 'project');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const loaded = loadState(projectDir);
expect(loaded).not.toBeNull();
expect(loaded!.config.ideaName).toBe('test-idea');
expect(loaded!.implementPasses).toBe(0);
});
it('returns null when file does not exist', () => {
const result = loadState(path.join(tmpDir, 'nonexistent'));
expect(result).toBeNull();
});
});
describe('deleteState', () => {
it('removes the file', () => {
const projectDir = path.join(tmpDir, 'project');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const filePath = path.join(projectDir, '.plan2code-bot-state.json');
expect(fs.existsSync(filePath)).toBe(true);
deleteState(projectDir);
expect(fs.existsSync(filePath)).toBe(false);
});
it('is a no-op when file does not exist', () => {
// Should not throw
deleteState(path.join(tmpDir, 'nonexistent'));
});
});
describe('findExistingState', () => {
it('finds state in workDir (enhancement mode)', () => {
const state = makeState(tmpDir);
state.config.projectDir = tmpDir;
state.config.mode = 'enhancement';
saveState(state);
const found = findExistingState(tmpDir);
expect(found).not.toBeNull();
expect(found!.config.ideaName).toBe('test-idea');
});
it('finds state in a subdirectory (new-project mode)', () => {
const projectDir = path.join(tmpDir, 'my-app');
fs.ensureDirSync(projectDir);
const state = makeState(projectDir);
saveState(state);
const found = findExistingState(tmpDir);
expect(found).not.toBeNull();
expect(found!.config.projectDir).toBe(projectDir);
});
it('returns null when no state exists', () => {
const found = findExistingState(tmpDir);
expect(found).toBeNull();
});
});
});
+48
View File
@@ -0,0 +1,48 @@
import fs from 'fs-extra';
import path from 'path';
import type { BotState } from './types.js';
const STATE_FILE = '.plan2code-bot-state.json';
export function saveState(state: BotState): void {
const filePath = path.join(state.config.projectDir, STATE_FILE);
fs.writeJsonSync(filePath, state, { spaces: 2 });
}
export function loadState(projectDir: string): BotState | null {
const filePath = path.join(projectDir, STATE_FILE);
if (!fs.existsSync(filePath)) {
return null;
}
return fs.readJsonSync(filePath) as BotState;
}
export function deleteState(projectDir: string): void {
const filePath = path.join(projectDir, STATE_FILE);
if (fs.existsSync(filePath)) {
fs.removeSync(filePath);
}
}
/**
* Search for an existing state file in workDir (enhancement mode)
* or in immediate subdirectories (new-project mode).
*/
export function findExistingState(workDir: string): BotState | null {
// Enhancement mode: state is in workDir directly
const direct = loadState(workDir);
if (direct) return direct;
// New-project mode: state is in a subdirectory
try {
for (const entry of fs.readdirSync(workDir, { withFileTypes: true })) {
if (entry.isDirectory()) {
const sub = loadState(path.join(workDir, entry.name));
if (sub) return sub;
}
}
} catch {
// workDir not readable — ignore
}
return null;
}
+195
View File
@@ -0,0 +1,195 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import { validateStepArtifacts, installSkillsForBot } from './cli.js';
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-cli-test-'));
});
afterEach(() => {
fs.removeSync(tmpDir);
});
// ── validateStepArtifacts ───────────────────────────────────────────
describe('validateStepArtifacts', () => {
describe('init', () => {
it('valid when AGENTS.md exists', () => {
fs.writeFileSync(path.join(tmpDir, 'AGENTS.md'), '# Agents');
const result = validateStepArtifacts('init', tmpDir);
expect(result.valid).toBe(true);
expect(result.missing).toEqual([]);
});
it('missing when AGENTS.md does not exist', () => {
const result = validateStepArtifacts('init', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('AGENTS.md');
});
});
describe('plan', () => {
it('valid when specs/feature/PLAN-DRAFT-*.md exists', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'PLAN-DRAFT-v1.md'), '# Plan');
const result = validateStepArtifacts('plan', tmpDir);
expect(result.valid).toBe(true);
});
it('missing when specs/ is absent', () => {
const result = validateStepArtifacts('plan', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/ directory');
});
it('missing when specs/ has dirs but no plan draft files', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'notes.md'), '# Notes');
const result = validateStepArtifacts('plan', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/*/PLAN-DRAFT-*.md');
});
});
describe('document', () => {
it('valid when overview.md and phase-*.md exist', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'overview.md'), '# Overview');
fs.writeFileSync(path.join(specDir, 'phase-1.md'), '# Phase 1');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(true);
});
it('missing overview.md when absent', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'phase-1.md'), '# Phase 1');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/*/overview.md');
});
it('missing phase files when absent', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(path.join(specDir, 'overview.md'), '# Overview');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs/*/phase-*.md files');
});
it('accepts phase files inside phases/ subdirectory', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
const phasesDir = path.join(specDir, 'phases');
fs.ensureDirSync(phasesDir);
fs.writeFileSync(path.join(specDir, 'overview.md'), '# Overview');
fs.writeFileSync(path.join(phasesDir, 'phase-1.md'), '# Phase 1');
const result = validateStepArtifacts('document', tmpDir);
expect(result.valid).toBe(true);
});
});
describe('finalize', () => {
it('valid when specs--completed/ has a subdirectory', () => {
fs.ensureDirSync(path.join(tmpDir, 'specs--completed', 'my-feature'));
const result = validateStepArtifacts('finalize', tmpDir);
expect(result.valid).toBe(true);
});
it('missing when specs--completed/ is absent', () => {
const result = validateStepArtifacts('finalize', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('specs--completed/ directory');
});
it('missing when specs--completed/ is empty', () => {
fs.ensureDirSync(path.join(tmpDir, 'specs--completed'));
const result = validateStepArtifacts('finalize', tmpDir);
expect(result.valid).toBe(false);
expect(result.missing).toContain('archived spec in specs--completed/');
});
});
});
// ── installSkillsForBot ─────────────────────────────────────────────
describe('installSkillsForBot', () => {
let fakeHome: string;
let projectDir: string;
let origHome: string | undefined;
let origUserProfile: string | undefined;
beforeEach(() => {
fakeHome = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-home-'));
projectDir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-proj-'));
origHome = process.env.HOME;
origUserProfile = process.env.USERPROFILE;
process.env.HOME = fakeHome;
process.env.USERPROFILE = fakeHome;
});
afterEach(() => {
process.env.HOME = origHome;
process.env.USERPROFILE = origUserProfile;
fs.removeSync(fakeHome);
fs.removeSync(projectDir);
});
it('copies skills from user dir to project .claude/skills/', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-init');
fs.ensureDirSync(srcDir);
fs.writeFileSync(path.join(srcDir, 'SKILL.md'), '---\nname: init\n---\nSome content');
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-init', 'SKILL.md');
expect(fs.existsSync(dest)).toBe(true);
expect(fs.readFileSync(dest, 'utf-8')).toContain('Some content');
});
it('strips disable-model-invocation: true from copied SKILL.md', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-1-plan');
fs.ensureDirSync(srcDir);
fs.writeFileSync(
path.join(srcDir, 'SKILL.md'),
'disable-model-invocation: true\n---\nname: plan\n---\nPlan content',
);
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-1-plan', 'SKILL.md');
const content = fs.readFileSync(dest, 'utf-8');
expect(content).not.toContain('disable-model-invocation');
expect(content).toContain('Plan content');
});
it('preserves rest of skill content', () => {
const srcDir = path.join(fakeHome, '.claude', 'skills', 'plan2code-2-document');
fs.ensureDirSync(srcDir);
const original = 'disable-model-invocation: true\n---\nname: doc\n---\nLine 1\nLine 2\nLine 3';
fs.writeFileSync(path.join(srcDir, 'SKILL.md'), original);
installSkillsForBot(projectDir);
const dest = path.join(projectDir, '.claude', 'skills', 'plan2code-2-document', 'SKILL.md');
const content = fs.readFileSync(dest, 'utf-8');
expect(content).toContain('Line 1');
expect(content).toContain('Line 2');
expect(content).toContain('Line 3');
expect(content).toContain('name: doc');
});
it('skips gracefully when source skill does not exist', () => {
// No skills in fakeHome — should not throw
expect(() => installSkillsForBot(projectDir)).not.toThrow();
// No .claude/skills/ created in project
expect(fs.existsSync(path.join(projectDir, '.claude', 'skills'))).toBe(false);
});
});
+498
View File
@@ -0,0 +1,498 @@
import fs from 'fs-extra';
import path from 'path';
import chalk from 'chalk';
import ora from 'ora';
import { generateNewAppIdea, generateEnhancementIdea } from './idea-generator.js';
import { runSession } from './session-runner.js';
import { buildStepPrompt } from './prompts/step-instructions.js';
import { checkAllPhasesComplete } from './step-detector.js';
import { saveState, loadState, deleteState, findExistingState } from './bot-state.js';
import type { BotConfig, BotMode, BotState, StepName, StepResult } from './types.js';
const BANNER = `
╔══════════════════════════════════════╗
║ plan2code-bot v1.0.0 ║
║ Autonomous Workflow Test Runner ║
╚══════════════════════════════════════╝
`;
const MAX_IMPLEMENT_PASSES = 10;
/** Skill name mapping: bot step name → installed skill directory name */
const SKILL_MAP: Record<StepName, string> = {
init: 'plan2code-init',
plan: 'plan2code-1-plan',
document: 'plan2code-2-document',
implement: 'plan2code-3-implement',
finalize: 'plan2code-4-finalize',
};
/**
* Install bot-friendly copies of plan2code skills into the project's .claude/skills/.
* The global skills have `disable-model-invocation: true` which prevents the autonomous
* session from invoking them via the Skill tool. We copy them with that flag removed
* so the session can invoke the real workflow prompts instead of guessing.
*/
export function installSkillsForBot(projectDir: string): void {
const userSkillsDir = path.join(
process.env.HOME || process.env.USERPROFILE || '',
'.claude',
'skills',
);
const projectSkillsDir = path.join(projectDir, '.claude', 'skills');
for (const skillName of Object.values(SKILL_MAP)) {
const srcFile = path.join(userSkillsDir, skillName, 'SKILL.md');
if (!fs.existsSync(srcFile)) continue;
const content = fs.readFileSync(srcFile, 'utf-8');
// Remove the disable-model-invocation line so the bot session can invoke the skill
const patched = content.replace(/^disable-model-invocation:\s*true\n?/m, '');
const destDir = path.join(projectSkillsDir, skillName);
fs.ensureDirSync(destDir);
fs.writeFileSync(path.join(destDir, 'SKILL.md'), patched);
}
}
export function validateStepArtifacts(step: StepName, projectDir: string): { valid: boolean; missing: string[] } {
const missing: string[] = [];
switch (step) {
case 'init': {
const agentsPath = path.join(projectDir, 'AGENTS.md');
if (!fs.existsSync(agentsPath)) missing.push('AGENTS.md');
break;
}
case 'plan': {
const specsDir = path.join(projectDir, 'specs');
if (!fs.existsSync(specsDir)) {
missing.push('specs/ directory');
} else {
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
const hasPlanDraft = specDirs.some((d) => {
const files = fs.readdirSync(path.join(specsDir, d.name));
return files.some((f) => /plan[-_]?draft/i.test(f));
});
if (!hasPlanDraft) missing.push('specs/*/PLAN-DRAFT-*.md');
}
break;
}
case 'document': {
const specsDir = path.join(projectDir, 'specs');
if (!fs.existsSync(specsDir)) {
missing.push('specs/ directory');
} else {
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
let foundOverview = false;
let foundPhaseFile = false;
for (const d of specDirs) {
const specPath = path.join(specsDir, d.name);
const files = fs.readdirSync(specPath);
if (files.some((f) => f === 'overview.md')) foundOverview = true;
if (files.some((f) => /^phase[-_]?\d+.*\.md$/i.test(f))) foundPhaseFile = true;
// Also check phases/ subdirectory
const phasesSubdir = path.join(specPath, 'phases');
if (fs.existsSync(phasesSubdir)) {
const subFiles = fs.readdirSync(phasesSubdir);
if (subFiles.some((f) => /phase/i.test(f))) foundPhaseFile = true;
}
}
if (!foundOverview) missing.push('specs/*/overview.md');
if (!foundPhaseFile) missing.push('specs/*/phase-*.md files');
}
break;
}
case 'finalize': {
const completedDir = path.join(projectDir, 'specs--completed');
if (!fs.existsSync(completedDir)) {
missing.push('specs--completed/ directory');
} else {
const entries = fs.readdirSync(completedDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
if (specDirs.length === 0) missing.push('archived spec in specs--completed/');
}
break;
}
}
return { valid: missing.length === 0, missing };
}
function detectMode(workDir: string): BotMode {
const agentsPath = path.join(workDir, 'AGENTS.md');
return fs.existsSync(agentsPath) ? 'enhancement' : 'new-project';
}
function formatDuration(ms: number): string {
const seconds = Math.floor(ms / 1000);
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes > 0) {
return `${minutes}m ${remainingSeconds}s`;
}
return `${seconds}s`;
}
async function runStep(
step: StepName,
config: BotConfig,
state: BotState,
): Promise<StepResult> {
const spinner = ora({
text: chalk.cyan(`Running ${step} step...`),
spinner: 'dots',
}).start();
const prompt = buildStepPrompt(step, config);
try {
const result = await runSession({
prompt,
config,
step,
maxTurns: step === 'implement' ? 80 : 50,
});
const stepResult: StepResult = {
step,
success: result.success,
sessionId: result.sessionId,
duration: result.duration,
error: result.success ? null : 'Session failed',
};
if (result.success) {
spinner.succeed(
chalk.green(`${step} completed in ${formatDuration(result.duration)}`)
);
} else {
spinner.fail(chalk.red(`${step} failed after ${formatDuration(result.duration)}`));
}
return stepResult;
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
spinner.fail(chalk.red(`${step} error: ${errorMsg}`));
return {
step,
success: false,
sessionId: null,
duration: 0,
error: errorMsg,
};
}
}
export interface CLIOptions {
idea?: string;
resume?: boolean;
}
/** Check if a step completed successfully in a saved state */
function stepSucceeded(state: BotState, step: StepName): boolean {
return state.steps.some((s) => s.step === step && s.success);
}
export async function runCLI(options: CLIOptions = {}): Promise<void> {
console.log(chalk.cyan(BANNER));
const workDir = process.cwd();
// Check for resumable state
let resuming = false;
let savedState: BotState | null = null;
if (options.resume) {
savedState = findExistingState(workDir);
if (savedState) {
resuming = true;
console.log(chalk.yellow('Resuming previous incomplete run...'));
} else {
console.log(chalk.dim('No previous state found, starting fresh.'));
}
}
const mode = resuming ? savedState!.config.mode : detectMode(workDir);
console.log(chalk.dim(`Working directory: ${workDir}`));
console.log(chalk.dim(`Mode: ${mode === 'new-project' ? 'New Project' : 'Enhancement'}`));
if (options.idea) {
console.log(chalk.dim(`Idea seed: ${options.idea}`));
}
console.log('');
let ideaName: string;
let ideaDescription: string;
let projectDir: string;
if (resuming) {
// Restore from saved state
ideaName = savedState!.config.ideaName;
ideaDescription = savedState!.config.ideaDescription;
projectDir = savedState!.config.projectDir;
console.log(chalk.green(`Restored idea: ${ideaName}`));
console.log(chalk.dim(` ${ideaDescription}`));
console.log('');
} else {
// Step 1: Generate idea
const ideaSpinner = ora({
text: chalk.cyan('Generating idea...'),
spinner: 'dots',
}).start();
try {
if (mode === 'new-project') {
const idea = await generateNewAppIdea(options.idea);
ideaName = idea.name;
ideaDescription = idea.description;
} else {
const idea = await generateEnhancementIdea(workDir, options.idea);
ideaName = idea.name;
ideaDescription = idea.description;
}
ideaSpinner.succeed(chalk.green(`Idea generated: ${ideaName}`));
} catch (error) {
ideaSpinner.fail(chalk.red('Failed to generate idea'));
throw error;
}
console.log(chalk.dim(` ${ideaDescription}`));
console.log('');
// Determine project directory
projectDir = mode === 'new-project'
? path.join(workDir, ideaName)
: workDir;
// Create project directory for new projects
if (mode === 'new-project') {
fs.ensureDirSync(projectDir);
}
}
// Install bot-friendly skills (without disable-model-invocation)
installSkillsForBot(projectDir);
console.log(chalk.dim('Installed plan2code skills for bot sessions'));
// Write IDEA.md (only if not resuming past plan step, since it gets moved)
if (!resuming || !stepSucceeded(savedState!, 'plan')) {
const ideaContent = `# ${ideaName}\n\n${ideaDescription}\n`;
fs.writeFileSync(path.join(projectDir, 'IDEA.md'), ideaContent);
console.log(chalk.dim(`Wrote IDEA.md to ${projectDir}`));
}
console.log('');
// Build config
const config: BotConfig = {
workDir,
projectDir,
ideaDescription,
ideaName,
mode,
};
// Initialize or restore state
const state: BotState = resuming
? { ...savedState!, config }
: {
config,
steps: [],
currentStep: null,
implementPasses: 0,
allPhasesComplete: false,
};
// Step 2: Run init (new project only)
if (mode === 'new-project') {
if (resuming && stepSucceeded(savedState!, 'init')) {
console.log(chalk.dim('--- Init (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Init ---'));
state.currentStep = 'init';
const initResult = await runStep('init', config, state);
state.steps.push(initResult);
saveState(state);
if (!initResult.success) {
console.log(chalk.red('\nInit failed. Aborting.'));
printSummary(state, workDir, false);
return;
}
const initValidation = validateStepArtifacts('init', projectDir);
if (!initValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${initValidation.missing.join(', ')}`));
initResult.success = false;
initResult.error = `Missing artifacts: ${initValidation.missing.join(', ')}`;
console.log(chalk.red('\nInit artifacts missing. Aborting.'));
printSummary(state, workDir, false);
return;
}
}
console.log('');
}
// Step 3: Plan
if (resuming && stepSucceeded(savedState!, 'plan')) {
console.log(chalk.dim('--- Plan (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Plan ---'));
state.currentStep = 'plan';
const planResult = await runStep('plan', config, state);
state.steps.push(planResult);
saveState(state);
if (!planResult.success) {
console.log(chalk.red('\nPlan step failed. Aborting.'));
printSummary(state, workDir, false);
return;
}
const planValidation = validateStepArtifacts('plan', projectDir);
if (!planValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${planValidation.missing.join(', ')}`));
planResult.success = false;
planResult.error = `Missing artifacts: ${planValidation.missing.join(', ')}`;
console.log(chalk.red('\nPlan artifacts missing. Aborting.'));
printSummary(state, workDir, false);
return;
}
// Move IDEA.md into the spec directory so it stays with its feature
const ideaPath = path.join(projectDir, 'IDEA.md');
if (fs.existsSync(ideaPath)) {
const specEntries = fs.readdirSync(path.join(projectDir, 'specs'), { withFileTypes: true });
const firstSpecDir = specEntries.find((e) => e.isDirectory());
if (firstSpecDir) {
const dest = path.join(projectDir, 'specs', firstSpecDir.name, 'IDEA.md');
fs.moveSync(ideaPath, dest, { overwrite: true });
console.log(chalk.dim(`Moved IDEA.md → specs/${firstSpecDir.name}/IDEA.md`));
}
}
}
console.log('');
// Step 4: Document
if (resuming && stepSucceeded(savedState!, 'document')) {
console.log(chalk.dim('--- Document (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Document ---'));
state.currentStep = 'document';
const docResult = await runStep('document', config, state);
state.steps.push(docResult);
saveState(state);
if (!docResult.success) {
console.log(chalk.red('\nDocument step failed. Aborting.'));
printSummary(state, workDir, false);
return;
}
const docValidation = validateStepArtifacts('document', projectDir);
if (!docValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${docValidation.missing.join(', ')}`));
docResult.success = false;
docResult.error = `Missing artifacts: ${docValidation.missing.join(', ')}`;
console.log(chalk.red('\nDocument artifacts missing. Aborting.'));
printSummary(state, workDir, false);
return;
}
}
console.log('');
// Step 5: Implement (loop until all phases complete)
if (resuming && savedState!.allPhasesComplete) {
console.log(chalk.dim('--- Implement (skipped — all phases already complete) ---'));
} else {
console.log(chalk.bold('--- Implement ---'));
while (state.implementPasses < MAX_IMPLEMENT_PASSES) {
state.implementPasses++;
state.currentStep = 'implement';
console.log(chalk.dim(` Pass ${state.implementPasses}/${MAX_IMPLEMENT_PASSES}`));
const implResult = await runStep('implement', config, state);
state.steps.push(implResult);
saveState(state);
if (!implResult.success) {
console.log(chalk.yellow(`\nImplement pass ${state.implementPasses} failed. Continuing...`));
}
// Check if all phases are complete
if (checkAllPhasesComplete(projectDir)) {
state.allPhasesComplete = true;
saveState(state);
console.log(chalk.green(' All phases complete!'));
break;
}
}
if (!state.allPhasesComplete && state.implementPasses >= MAX_IMPLEMENT_PASSES) {
console.log(chalk.yellow(`\nMax implement passes (${MAX_IMPLEMENT_PASSES}) reached.`));
}
}
console.log('');
// Step 6: Finalize
if (resuming && stepSucceeded(savedState!, 'finalize')) {
console.log(chalk.dim('--- Finalize (skipped — previously succeeded) ---'));
} else {
console.log(chalk.bold('--- Finalize ---'));
state.currentStep = 'finalize';
const finalizeResult = await runStep('finalize', config, state);
state.steps.push(finalizeResult);
saveState(state);
if (finalizeResult.success) {
const finalValidation = validateStepArtifacts('finalize', projectDir);
if (!finalValidation.valid) {
console.log(chalk.yellow(` ⚠ Missing artifacts: ${finalValidation.missing.join(', ')}`));
finalizeResult.success = false;
finalizeResult.error = `Missing artifacts: ${finalValidation.missing.join(', ')}`;
saveState(state);
}
}
}
console.log('');
// Determine overall success
const allSucceeded = state.steps.length > 0 && state.steps.every((s) => s.success);
printSummary(state, workDir, allSucceeded);
// Clean up state file on full success
if (allSucceeded) {
deleteState(projectDir);
console.log(chalk.dim('Cleaned up state file (run succeeded)'));
} else {
console.log(chalk.dim('State file preserved for resume (run incomplete)'));
}
console.log('');
}
function printSummary(state: BotState, workDir: string, allSucceeded: boolean): void {
const { ideaName, mode, projectDir } = state.config;
console.log(chalk.cyan('═══════════════════════════════════════'));
console.log(chalk.bold(' Bot Run Summary'));
console.log(chalk.cyan('═══════════════════════════════════════'));
console.log(chalk.dim(` Project: ${ideaName}`));
console.log(chalk.dim(` Mode: ${mode}`));
console.log(chalk.dim(` Directory: ${projectDir}`));
console.log('');
const totalDuration = state.steps.reduce((sum, s) => sum + s.duration, 0);
const successCount = state.steps.filter((s) => s.success).length;
for (const step of state.steps) {
const icon = step.success ? chalk.green('✓') : chalk.red('✗');
console.log(` ${icon} ${step.step.padEnd(12)} ${formatDuration(step.duration)}`);
}
console.log('');
console.log(chalk.dim(` Total: ${successCount}/${state.steps.length} steps succeeded in ${formatDuration(totalDuration)}`));
console.log(chalk.dim(` Implement passes: ${state.implementPasses}`));
if (!allSucceeded) {
console.log(chalk.dim(` State saved to: ${path.relative(workDir, projectDir)}/.plan2code-bot-state.json`));
}
console.log('');
}
+98
View File
@@ -0,0 +1,98 @@
import { query } from '@anthropic-ai/claude-agent-sdk';
interface IdeaResult {
name: string;
description: string;
}
function parseIdea(text: string): IdeaResult {
const nameMatch = text.match(/NAME:\s*(.+)/i);
const descMatch = text.match(/DESCRIPTION:\s*([\s\S]+?)(?:\n\n|$)/i);
const name = nameMatch?.[1]?.trim() ?? 'auto-project';
const description = descMatch?.[1]?.trim() ?? text.trim();
// Ensure kebab-case
const kebabName = name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
return { name: kebabName, description };
}
export async function generateNewAppIdea(seed?: string): Promise<IdeaResult> {
const category = Math.random() > 0.5 ? 'CLI tool' : 'small web app';
const seedClause = seed
? `\n\nUse this as inspiration for the idea: "${seed}"`
: '';
const prompt = `Generate a random, creative idea for a ${category} that a developer might build as a side project. The project should be achievable in a single coding session (1-2 hours) and should be interesting but not overly complex.${seedClause}
Respond in EXACTLY this format (no other text):
NAME: <kebab-case-project-name>
DESCRIPTION: <2-3 sentence description of what the app does, its key features, and the tech stack to use>`;
const session = query({
prompt,
options: {
maxTurns: 1,
systemPrompt: 'You are a creative software project idea generator. Respond only in the exact format requested.',
},
});
let output = '';
for await (const message of session) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') {
output += block.text;
}
}
}
}
return parseIdea(output);
}
export async function generateEnhancementIdea(projectDir: string, seed?: string): Promise<IdeaResult> {
const seedClause = seed
? `\n\nUse this as inspiration for the enhancement: "${seed}"`
: '';
const prompt = `You are in a project directory. Scan the existing codebase to understand what it does, then propose a realistic enhancement (new feature, refactor, improvement, or extension).
Use the Read, Glob, and Grep tools to explore the project. Look at:
- Package.json or similar config files for project info
- Source files for current functionality
- README or docs for context${seedClause}
Then respond in EXACTLY this format (no other text):
NAME: <kebab-case-enhancement-name>
DESCRIPTION: <2-3 sentence description of the enhancement, what it adds/changes, and why it would be valuable>`;
const session = query({
prompt,
options: {
maxTurns: 8,
cwd: projectDir,
tools: { type: 'preset', preset: 'claude_code' },
allowedTools: ['Read', 'Glob', 'Grep'],
systemPrompt: { type: 'preset', preset: 'claude_code' },
},
});
let output = '';
for await (const message of session) {
if (message.type === 'assistant') {
for (const block of message.message.content) {
if (block.type === 'text') {
output += block.text;
}
}
}
}
return parseIdea(output);
}
+2
View File
@@ -0,0 +1,2 @@
export { runCLI } from './cli.js';
export type { BotConfig, BotMode, BotState, StepName, StepResult } from './types.js';
@@ -0,0 +1,58 @@
import { describe, it, expect } from 'vitest';
import { buildStepPrompt } from './step-instructions.js';
import type { BotConfig } from '../types.js';
const config: BotConfig = {
workDir: '/tmp/work',
projectDir: '/tmp/work/my-app',
ideaDescription: 'A todo app with drag-and-drop',
ideaName: 'drag-todo',
mode: 'new-project',
};
describe('buildStepPrompt', () => {
it('each step includes the autonomous preamble', () => {
const steps = ['init', 'plan', 'document', 'implement', 'finalize'] as const;
for (const step of steps) {
const prompt = buildStepPrompt(step, config);
expect(prompt).toContain('running autonomously');
}
});
it('init prompt includes /plan2code-init skill invocation', () => {
const prompt = buildStepPrompt('init', config);
expect(prompt).toContain('/plan2code-init');
});
it('plan prompt includes /plan2code-1-plan skill invocation', () => {
const prompt = buildStepPrompt('plan', config);
expect(prompt).toContain('/plan2code-1-plan');
});
it('document prompt includes /plan2code-2-document skill invocation', () => {
const prompt = buildStepPrompt('document', config);
expect(prompt).toContain('/plan2code-2-document');
});
it('implement prompt includes /plan2code-3-implement skill invocation', () => {
const prompt = buildStepPrompt('implement', config);
expect(prompt).toContain('/plan2code-3-implement');
});
it('finalize prompt includes /plan2code-4-finalize skill invocation', () => {
const prompt = buildStepPrompt('finalize', config);
expect(prompt).toContain('/plan2code-4-finalize');
});
it('plan prompt includes project name and description', () => {
const prompt = buildStepPrompt('plan', config);
expect(prompt).toContain('drag-todo');
expect(prompt).toContain('A todo app with drag-and-drop');
});
it('init prompt includes project name and description', () => {
const prompt = buildStepPrompt('init', config);
expect(prompt).toContain('drag-todo');
expect(prompt).toContain('A todo app with drag-and-drop');
});
});
@@ -0,0 +1,86 @@
import type { BotConfig, StepName } from '../types.js';
const AUTONOMOUS_PREAMBLE = `You are running autonomously as part of an automated test pipeline. Do NOT pause for human input. When you encounter questions or approval gates, make reasonable decisions and proceed. If asked for confirmation, approve. If asked to choose, pick the most reasonable option. Complete the entire step without stopping.`;
export function buildStepPrompt(step: StepName, config: BotConfig): string {
switch (step) {
case 'init':
return buildInitPrompt(config);
case 'plan':
return buildPlanPrompt(config);
case 'document':
return buildDocumentPrompt(config);
case 'implement':
return buildImplementPrompt(config);
case 'finalize':
return buildFinalizePrompt(config);
}
}
function buildInitPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-init skill to generate an AGENTS.md file for this project.
The project idea is: ${config.ideaDescription}
The project name is: ${config.ideaName}
When asked questions:
- For the project description, use the idea above
- Accept all defaults and approve all gates
- Complete the init process fully`;
}
function buildPlanPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-1-plan skill to create a plan for this project.
Read the IDEA.md file first to understand the project. The project is: ${config.ideaDescription}
When making decisions during planning:
- Set confidence levels reasonably high (85-95%)
- Accept the generated tech stack without revision
- Do not request additional reference files
- Approve the plan when asked for sign-off
- Keep scope small and achievable (3-4 phases max)
- Use the project name: ${config.ideaName}`;
}
function buildDocumentPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-2-document skill to transform the plan into implementation specs.
Read the existing plan output in specs/ first to understand what was planned.
When making decisions:
- Accept all generated documentation
- Approve phase breakdowns and task lists
- Do not request changes to the generated docs`;
}
function buildImplementPrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-3-implement skill to implement the next available phase.
When making decisions:
- Pick the first available/unchecked phase
- Write working code that fulfills the spec tasks
- Mark tasks as complete as you finish them
- Approve and sign off when the phase is done
- Skip running tests if asked (or select the simplest test option)`;
}
function buildFinalizePrompt(config: BotConfig): string {
return `${AUTONOMOUS_PREAMBLE}
Run the /plan2code-4-finalize skill to validate and archive the completed project.
When making decisions:
- Approve all documentation updates
- Accept the completion summary
- If asked for a rating or feedback, give 8/10 and positive feedback
- Complete the archival process fully`;
}
+74
View File
@@ -0,0 +1,74 @@
import { describe, it, expect, vi } from 'vitest';
// Mock the SDK before importing session-runner
vi.mock('@anthropic-ai/claude-agent-sdk', () => ({
query: vi.fn(),
}));
import { query } from '@anthropic-ai/claude-agent-sdk';
import { runSession } from './session-runner.js';
import type { BotConfig } from './types.js';
const config: BotConfig = {
workDir: '/tmp/work',
projectDir: '/tmp/work/my-app',
ideaDescription: 'test app',
ideaName: 'test-app',
mode: 'new-project',
};
describe('runSession', () => {
it('returns success: false when output is empty', async () => {
// Simulate a session that yields an assistant message with empty text
const mockQuery = vi.mocked(query);
mockQuery.mockReturnValue(
(async function* () {
yield {
type: 'assistant' as const,
session_id: 'sess-1',
message: { content: [{ type: 'text' as const, text: '' }] },
};
yield {
type: 'result' as const,
session_id: 'sess-1',
};
})() as any,
);
const result = await runSession({
prompt: 'do something',
config,
step: 'init',
});
expect(result.success).toBe(false);
expect(result.output.trim()).toBe('');
});
it('returns success: true when output has content', async () => {
const mockQuery = vi.mocked(query);
mockQuery.mockReturnValue(
(async function* () {
yield {
type: 'assistant' as const,
session_id: 'sess-2',
message: { content: [{ type: 'text' as const, text: 'AGENTS.md has been created successfully' }] },
};
yield {
type: 'result' as const,
session_id: 'sess-2',
};
})() as any,
);
const result = await runSession({
prompt: 'do something',
config,
step: 'init',
});
expect(result.success).toBe(true);
expect(result.output).toContain('AGENTS.md');
expect(result.sessionId).toBe('sess-2');
});
});
+60
View File
@@ -0,0 +1,60 @@
import { query } from '@anthropic-ai/claude-agent-sdk';
import { createAutoResponder } from './auto-responder.js';
import type { BotConfig, StepName } from './types.js';
export interface SessionOptions {
prompt: string;
config: BotConfig;
step: StepName;
maxTurns?: number;
}
export interface SessionResult {
sessionId: string | null;
output: string;
success: boolean;
duration: number;
}
export async function runSession(options: SessionOptions): Promise<SessionResult> {
const { prompt, config, step, maxTurns = 50 } = options;
const startTime = Date.now();
let output = '';
let sessionId: string | null = null;
try {
const session = query({
prompt,
options: {
cwd: config.projectDir,
maxTurns,
permissionMode: 'bypassPermissions',
allowDangerouslySkipPermissions: true,
canUseTool: createAutoResponder(config, step),
systemPrompt: { type: 'preset', preset: 'claude_code' },
settingSources: ['user', 'project'],
},
});
for await (const message of session) {
if (message.type === 'assistant') {
sessionId = message.session_id ?? sessionId;
for (const block of message.message.content) {
if (block.type === 'text') {
output += block.text + '\n';
}
}
} else if (message.type === 'result') {
sessionId = message.session_id ?? sessionId;
}
}
const duration = Date.now() - startTime;
const hasOutput = output.trim().length > 0;
return { sessionId, output, success: hasOutput, duration };
} catch (error) {
const duration = Date.now() - startTime;
const errorMsg = error instanceof Error ? error.message : String(error);
return { sessionId, output, success: false, duration };
}
}
+164
View File
@@ -0,0 +1,164 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import fs from 'fs-extra';
import os from 'os';
import path from 'path';
import { checkAllPhasesComplete, detectStepCompletion } from './step-detector.js';
let tmpDir: string;
beforeEach(() => {
tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-test-'));
});
afterEach(() => {
fs.removeSync(tmpDir);
});
// ── checkAllPhasesComplete ──────────────────────────────────────────
describe('checkAllPhasesComplete', () => {
it('returns false when no specs/ directory exists', () => {
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns false when specs/ has no subdirectories', () => {
fs.ensureDirSync(path.join(tmpDir, 'specs'));
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns false when spec dir exists but has no overview.md and no phase files', () => {
// This is the false-positive bug we fixed — an empty spec dir should NOT be "complete"
fs.ensureDirSync(path.join(tmpDir, 'specs', 'my-feature'));
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns true when overview.md has all phases checked [x]', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'overview.md'),
`# Overview\n- [x] Phase 1: Setup\n- [x] Phase 2: Core\n- [x] Phase 3: Polish\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(true);
});
it('returns false when overview.md has unchecked [ ] phases', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'overview.md'),
`# Overview\n- [x] Phase 1: Setup\n- [ ] Phase 2: Core\n- [ ] Phase 3: Polish\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns true via fallback: phase-*.md files with all checked, no overview.md', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [x] Task B\n`,
);
fs.writeFileSync(
path.join(specDir, 'phase-2.md'),
`# Phase 2\n- [x] Task C\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(true);
});
it('returns false via fallback: phase-*.md with unchecked items', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
fs.ensureDirSync(specDir);
fs.writeFileSync(
path.join(specDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [ ] Task B\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
it('returns true via nested phases/ subdirectory fallback with all checked', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
const phasesDir = path.join(specDir, 'phases');
fs.ensureDirSync(phasesDir);
fs.writeFileSync(
path.join(phasesDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [x] Task B\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(true);
});
it('returns false via nested phases/ with unchecked items', () => {
const specDir = path.join(tmpDir, 'specs', 'my-feature');
const phasesDir = path.join(specDir, 'phases');
fs.ensureDirSync(phasesDir);
fs.writeFileSync(
path.join(phasesDir, 'phase-1.md'),
`# Phase 1\n- [x] Task A\n- [ ] Task B\n`,
);
expect(checkAllPhasesComplete(tmpDir)).toBe(false);
});
});
// ── detectStepCompletion ────────────────────────────────────────────
describe('detectStepCompletion', () => {
it('init: completed when output mentions agents.md created', () => {
const result = detectStepCompletion('AGENTS.md has been created successfully', 'init');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('plan');
});
it('init: not completed for unrelated output', () => {
const result = detectStepCompletion('Hello world, nothing happened', 'init');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('plan: completed when plan is saved', () => {
const result = detectStepCompletion('The plan has been saved and finalized', 'plan');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('document');
});
it('plan: not completed for unrelated output', () => {
const result = detectStepCompletion('Reading the codebase...', 'plan');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('document: completed when overview.md is mentioned', () => {
const result = detectStepCompletion('Created overview.md with all phases', 'document');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('implement');
});
it('document: not completed for unrelated output', () => {
const result = detectStepCompletion('Thinking about the design...', 'document');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('implement: completed when phase is done', () => {
const result = detectStepCompletion('Phase 1 is now complete!', 'implement');
expect(result.completed).toBe(true);
expect(result.nextStep).toBe('finalize');
});
it('implement: not completed for unrelated output', () => {
const result = detectStepCompletion('Working on some files', 'implement');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
it('finalize: completed when finalize is done', () => {
const result = detectStepCompletion('Finalize step is complete and archived', 'finalize');
expect(result.completed).toBe(true);
expect(result.nextStep).toBeNull(); // last step
});
it('finalize: not completed for unrelated output', () => {
const result = detectStepCompletion('Just starting...', 'finalize');
expect(result.completed).toBe(false);
expect(result.nextStep).toBeNull();
});
});
+151
View File
@@ -0,0 +1,151 @@
import fs from 'fs-extra';
import path from 'path';
import type { StepName } from './types.js';
export interface DetectionResult {
completed: boolean;
nextStep: StepName | null;
needsAnotherImplementPass: boolean;
}
const STEP_ORDER: StepName[] = ['init', 'plan', 'document', 'implement', 'finalize'];
export function detectStepCompletion(output: string, step: StepName): DetectionResult {
const lowerOutput = output.toLowerCase();
let completed = false;
switch (step) {
case 'init':
completed = lowerOutput.includes('agents.md') && (
lowerOutput.includes('created') ||
lowerOutput.includes('generated') ||
lowerOutput.includes('written')
);
break;
case 'plan':
completed = lowerOutput.includes('plan') && (
lowerOutput.includes('complete') ||
lowerOutput.includes('approved') ||
lowerOutput.includes('finalized') ||
lowerOutput.includes('saved')
);
break;
case 'document':
completed = lowerOutput.includes('overview.md') || (
lowerOutput.includes('document') && lowerOutput.includes('complete')
);
break;
case 'implement':
completed = lowerOutput.includes('phase') && (
lowerOutput.includes('complete') ||
lowerOutput.includes('done') ||
lowerOutput.includes('finished')
);
break;
case 'finalize':
completed = lowerOutput.includes('finalize') && (
lowerOutput.includes('complete') ||
lowerOutput.includes('archived') ||
lowerOutput.includes('done')
);
break;
}
// Determine next step
const currentIdx = STEP_ORDER.indexOf(step);
const nextStep = currentIdx < STEP_ORDER.length - 1 ? STEP_ORDER[currentIdx + 1] : null;
return {
completed,
nextStep: completed ? nextStep : null,
needsAnotherImplementPass: false,
};
}
export function checkAllPhasesComplete(projectDir: string): boolean {
const specsDir = path.join(projectDir, 'specs');
if (!fs.existsSync(specsDir)) {
return false;
}
const entries = fs.readdirSync(specsDir, { withFileTypes: true });
const specDirs = entries.filter((e) => e.isDirectory());
if (specDirs.length === 0) {
return false;
}
let foundPhaseTracking = false;
for (const dir of specDirs) {
const specPath = path.join(specsDir, dir.name);
// Try overview.md first
const overviewPath = path.join(specPath, 'overview.md');
if (fs.existsSync(overviewPath)) {
foundPhaseTracking = true;
if (hasUncheckedPhases(fs.readFileSync(overviewPath, 'utf-8'))) {
return false;
}
continue;
}
// Fallback: look for phase-*.md or PHASE-*.md in the spec dir
const phaseFiles = findPhaseFiles(specPath);
if (phaseFiles.length > 0) {
foundPhaseTracking = true;
for (const pf of phaseFiles) {
if (hasUncheckedPhases(fs.readFileSync(pf, 'utf-8'))) {
return false;
}
}
continue;
}
// Fallback: look inside a phases/ subdirectory
const phasesSubdir = path.join(specPath, 'phases');
if (fs.existsSync(phasesSubdir)) {
const subPhaseFiles = findPhaseFiles(phasesSubdir);
if (subPhaseFiles.length > 0) {
foundPhaseTracking = true;
for (const pf of subPhaseFiles) {
if (hasUncheckedPhases(fs.readFileSync(pf, 'utf-8'))) {
return false;
}
}
}
}
}
// Only return true if we positively confirmed all phases are checked off
return foundPhaseTracking;
}
function hasUncheckedPhases(content: string): boolean {
const lines = content.split('\n');
const phaseLines = lines.filter((line) =>
line.match(/^[-*]\s*\[[ x]\]/i) && line.toLowerCase().includes('phase')
);
if (phaseLines.length > 0) {
return phaseLines.some((line) => line.includes('[ ]'));
}
// No phase-specific checkboxes — check for any unchecked boxes
return lines.some((line) => /^[-*]\s*\[ \]/.test(line));
}
function findPhaseFiles(dir: string): string[] {
if (!fs.existsSync(dir)) return [];
const entries = fs.readdirSync(dir);
return entries
.filter((name) => /^phase[-_]?\d+.*\.md$/i.test(name))
.map((name) => path.join(dir, name));
}
+27
View File
@@ -0,0 +1,27 @@
export type BotMode = 'new-project' | 'enhancement';
export interface BotConfig {
workDir: string;
projectDir: string;
ideaDescription: string;
ideaName: string;
mode: BotMode;
}
export type StepName = 'init' | 'plan' | 'document' | 'implement' | 'finalize';
export interface StepResult {
step: StepName;
success: boolean;
sessionId: string | null;
duration: number;
error: string | null;
}
export interface BotState {
config: BotConfig;
steps: StepResult[];
currentStep: StepName | null;
implementPasses: number;
allPhasesComplete: boolean;
}
+20
View File
@@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2022"],
"outDir": "dist",
"rootDir": ".",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"declaration": true,
"declarationMap": true,
"sourceMap": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]
}
+15
View File
@@ -0,0 +1,15 @@
import { defineConfig } from 'tsup';
export default defineConfig({
entry: {
'bin/plan2code-bot': 'src/bin/plan2code-bot.ts',
index: 'src/index.ts',
},
format: ['esm'],
dts: false,
clean: true,
sourcemap: true,
banner: {
js: '#!/usr/bin/env node',
},
});
+7
View File
@@ -0,0 +1,7 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['src/**/*.test.ts'],
},
});