refactor: 重构项目为纯文档化架构,移除执行环境依赖

重构项目结构,将代码脚本转为AI工具描述文档,移除所有运行时依赖
更新文档说明项目为设计知识库,实际执行由外部AI工具完成
修改package.json移除dependencies并更新scripts为文档说明
统一所有脚本文件为伪代码描述,仅供AI参考实现逻辑
更新README和架构文档,明确项目为可移植的设计知识库
This commit is contained in:
dzq 2025-12-09 18:01:22 +08:00
parent 933ec0bf47
commit b964a3b9d6
8 changed files with 531 additions and 839 deletions

235
CLAUDE.md
View File

@ -4,91 +4,94 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project Overview ## Project Overview
MetaCraft is an AI-powered meta-development tool that transforms software development into a series of composable, executable prompts, scripts, and documents. The project itself is developed using this toolchain, creating a bootstrapping loop that validates and optimizes the development workflow. MetaCraft is an AI-powered meta-development tool that transforms software development into a series of composable, executable prompts, scripts, and documents. The project adopts a **documentation-only architecture** - containing only documents, designs, and AI tool scripts, with no execution environment or runtime services. External AI tools execute the logic described in these scripts.
## Common Commands ## Common Commands
### Development Workflow ### Development Workflow (AI Tool Reference)
These commands describe how an external AI tool should execute development workflows. The scripts in this project are **tool descriptions** for AI reference, not executable code.
```bash ```bash
# Run the bootstrap loop (self-development cycle) # How to execute the bootstrap loop logic (self-development cycle)
npm start # Reference: scripts/bootstrap.js for detailed steps
# External AI tool should implement: read todo.md, show tasks, execute prompts
# Execute a specific prompt file # How to execute a specific prompt file
npm run prompt -- prompts/example.md # Reference: scripts/run-prompt.js for detailed steps
# or directly: # External AI tool should implement: read prompt file, extract metadata, call Claude Code
node scripts/run-prompt.js prompts/example.md
# Plan the next development step # How to plan the next development step
npm run plan # Reference: scripts/plan-next.js for detailed steps
# or directly: # External AI tool should implement: analyze project state, recommend tasks, generate files
node scripts/plan-next.js
# Check if Claude Code CLI is installed
claude --version
# View current todo tasks # View current todo tasks
cat meta/todo.md cat meta/todo.md
``` ```
### Testing ### Testing (Design Concept)
```bash ```bash
# Run tests (currently just a placeholder) # Testing framework design - to be implemented by external AI tools
npm test # Reference: docs/ARCHITECTURE.md for testing strategy design
``` ```
### Installation ### Installation (Project Setup)
```bash ```bash
# Install dependencies (Node.js 18+ required) # This project requires no installation - it's a documentation and design repository
npm install # Clone the repository and explore the documentation
git clone <repository-url>
cd MetaCraft
``` ```
## Code Architecture ## Code Architecture
### Core Components ### Core Components (Design Concepts)
**1. Prompt Engine (`scripts/run-prompt.js`)** **1. Prompt Engine Design** (`scripts/run-prompt.js`)
- Loads and parses Markdown-based prompt files - Describes how to parse Markdown-based prompt files
- Extracts metadata (target, priority, etc.) - Explains metadata extraction (target, priority, etc.)
- Injects dynamic context (project structure, git status) - Outlines context injection (project structure, git status)
- Calls Claude Code CLI to execute prompts - Provides guidance on calling external AI tools
- Parses AI responses into actionable operations - Documents response parsing into actionable operations
**2. Bootstrap Loop (`scripts/bootstrap.js`)** **2. Bootstrap Loop Design** (`scripts/bootstrap.js`)
- Reads todo list from `meta/todo.md` - Describes reading todo list from `meta/todo.md`
- Prompts user to select a pending task - Explains user interaction for task selection
- Finds corresponding prompt file - Documents prompt file lookup logic
- Executes the prompt via `run-prompt.js` - Outlines prompt execution steps via external tools
- Updates task status after verification - Provides task status update procedures
**3. Plan Next Step (`scripts/plan-next.js`)** **3. Plan Next Step Design** (`scripts/plan-next.js`)
- Analyzes current project state (completed vs pending tasks) - Describes project state analysis (completed vs pending tasks)
- Recommends next task based on priority and category - Documents task recommendation algorithms based on priority and category
- Generates prompt files for recommended tasks - Explains prompt file generation logic
- Creates detailed next-step planning documents - Outlines next-step planning document creation
**4. Context Manager (conceptual)** **4. Context Manager Design** (conceptual)
- Maintains project state and structure - Describes project state maintenance strategies
- Provides relevant context to AI during prompt execution - Documents context provision techniques for AI during prompt execution
- Tracks dependencies, recent changes, and task history - Explains dependency tracking and change history management
Note: These are design documents for AI reference, not executable code.
### Directory Structure ### Directory Structure
``` ```
MetaCraft/ MetaCraft/
├── prompts/ # Prompt library for tasks ├── prompts/ # Prompt library for tasks
│ └── example.md # Example: creates welcome.js │ └── example.md # Example: creates welcome.js
├── scripts/ # Core automation scripts ├── scripts/ # AI tool scripts (design documents, not executable)
│ ├── run-prompt.js # Executes prompts via Claude Code │ ├── run-prompt.js # Prompt execution logic description
│ └── bootstrap.js # Self-development cycle │ ├── bootstrap.js # Bootstrap loop design document
│ └── plan-next.js # Next-step planning design document
├── docs/ # Project documentation ├── docs/ # Project documentation
│ ├── ARCHITECTURE.md # Detailed architecture │ ├── ARCHITECTURE.md # Detailed architecture design
│ ├── GETTING_STARTED.md # Quick start guide │ ├── GETTING_STARTED.md # Quick start guide
│ └── next-steps/ # Auto-generated next step plans │ └── next-steps/ # Auto-generated next step plans
├── meta/ # Tool metadata ├── meta/ # Tool metadata
│ └── todo.md # Pending development tasks │ └── todo.md # Pending development tasks
├── config/ # Configuration (currently empty) ├── config/ # Configuration (currently empty)
├── templates/ # File templates (currently empty) ├── templates/ # File templates (currently empty)
├── package.json ├── package.json # Project metadata (dependencies are design references)
└── README.md └── README.md # Project overview and architecture
``` ```
## Key Files ## Key Files
@ -115,86 +118,110 @@ Auto-injected project context
Expected deliverables Expected deliverables
``` ```
### Scripts ### Scripts (AI Tool Descriptions)
- **`run-prompt.js`**: Accepts a prompt file path, validates Claude Code CLI, executes prompt, displays AI response - **`run-prompt.js`**: Describes how to execute a prompt file - file validation, metadata extraction, external AI tool invocation
- **`bootstrap.js`**: Interactive loop for self-development - shows pending tasks, executes selected prompt, updates todo.md - **`bootstrap.js`**: Documents the self-development loop logic - task listing, user interaction, prompt execution, status updates
- **`plan-next.js`**: Analyzes project state, recommends next task, generates prompt files and planning documents - **`plan-next.js`**: Outlines project state analysis and next-step planning - task recommendation algorithms, file generation procedures
## Development Workflow ## Development Workflow
### Bootstrapping Process ### Bootstrapping Process (Design Logic)
1. View pending tasks: `cat meta/todo.md` 1. View pending tasks: Read `meta/todo.md`
2. Run bootstrap loop: `npm start` 2. Bootstrap loop logic: Reference `scripts/bootstrap.js` for implementation steps
3. Select a task number 3. Select a task number: User interaction design
4. Tool finds corresponding prompt file in `prompts/` 4. Find corresponding prompt file: File lookup algorithm in `prompts/` directory
5. Executes prompt via Claude Code CLI 5. Execute prompt: Call external AI tool (e.g., Claude Code) following `scripts/run-prompt.js` guidelines
6. Review AI-generated output 6. Review AI-generated output: Result processing and validation
7. Mark task as complete (updates `meta/todo.md`) 7. Mark task as complete: Update `meta/todo.md` status
### Adding New Tasks ### Adding New Tasks (Design Logic)
1. Edit `meta/todo.md` and add a new unchecked task: `- [ ] Task description` 1. Edit `meta/todo.md` and add a new unchecked task: `- [ ] Task description`
2. Create corresponding prompt file in `prompts/` (optional) 2. Create corresponding prompt file in `prompts/` (optional)
- Filename should relate to task (e.g., `implement-prompt-engine.md`) - Filename should relate to task (e.g., `implement-prompt-engine.md`)
3. Run bootstrap loop to execute 3. Execute via bootstrap loop logic: Reference `scripts/bootstrap.js` for implementation
### Planning Next Steps ### Planning Next Steps (Design Logic)
1. Run `npm run plan` to analyze project state and get task recommendations 1. Analyze project state: Reference `scripts/plan-next.js` for recommendation algorithms
2. Choose an action: generate prompt file, planning document, or both 2. Choose an action: generate prompt file, planning document, or both
3. Review generated files and adjust as needed 3. Review generated files and adjust as needed
4. Execute the task using `npm start` or directly via `run-prompt.js` 4. Execute the task: Use external AI tools following the described logic
### Example: Running the Example Prompt ### Example: Running the Example Prompt (Design Logic)
```bash ```bash
# Execute the example prompt # How to execute the example prompt:
node scripts/run-prompt.js prompts/example.md # 1. Reference scripts/run-prompt.js for execution logic
# 2. Read prompts/example.md for prompt content
# 3. Call external AI tool to execute the prompt
# This creates welcome.js with a timestamped welcome message # Expected outcome:
node welcome.js # Run the generated script # - AI generates welcome.js with timestamped welcome message
# - External tool can then execute welcome.js
``` ```
## Dependencies ## Dependencies (Design References)
### Runtime Dependencies ### Design Dependency Descriptions
- **commander**: CLI argument parsing - **commander**: CLI argument parsing design pattern reference
- **fs-extra**: Enhanced file system operations - **fs-extra**: Enhanced file system operation design patterns
- **marked**: Markdown parsing - **marked**: Markdown parsing design approach
- **simple-git**: Git operations - **simple-git**: Git operation design patterns
### Requirements ### Implementation Requirements
- Node.js 18+ - **External AI Tool**: For actual execution (e.g., Claude Code, other AI assistants)
- Claude Code CLI installed and configured - **File System Access**: Required by external tools to read project files
- Git - **Git**: For version control of the design documents
Note: This project contains no runtime dependencies or execution environment. The dependencies listed are **design references** describing how external tools should implement similar functionality.
## Important Notes ## Important Notes
### Architecture Philosophy
MetaCraft follows a **documentation-only architecture**:
- **No execution environment**: Scripts are design documents, not executable code
- **External tool execution**: All logic is implemented by external AI tools (e.g., Claude Code)
- **Portable knowledge**: Designs can be referenced by any AI system
- **Self-development concept**: The toolchain describes how to develop itself
### Current Implementation Status ### Current Implementation Status
- Core infrastructure exists with bootstrap loop, prompt execution, and planning functionality - **Design documents complete**: Bootstrap loop, prompt execution, and planning logic are fully documented
- Core components (prompt-engine, script-runner, context-manager) are not yet implemented - **No runtime components**: Core components (prompt-engine, script-runner, context-manager) exist only as design concepts
- Bootstrap loop, prompt execution, and plan-next are functional prototypes - **Pure documentation**: All scripts are descriptive, not functional
- Project is in early development phase (v0.0.1) - **Version**: Design phase v0.0.1
### Prompt Execution ### Prompt Execution (Design Concept)
- Requires Claude Code CLI to be installed and in PATH - **External tool requirement**: Execution requires external AI tools, not built-in runtime
- If Claude Code is unavailable, the script outputs the prompt content for manual execution - **Logic description**: `scripts/run-prompt.js` describes how to validate, extract metadata, and invoke AI tools
- Prompts are written to `.temp/` directory during execution - **Temporary files**: Design includes `.temp/` directory concept for intermediate files
### File Generation ### File Generation (Design Concept)
- Prompts can generate files (like `welcome.js` from the example) - **AI-generated artifacts**: Prompts can describe file generation (e.g., `welcome.js` from example)
- Generated files are gitignored (see `.gitignore`) - **Git integration**: Generated files would be gitignored in actual implementations
### Self-Development ### Self-Development (Design Concept)
This project uses itself to develop itself. The bootstrap loop: This project describes a self-development methodology. The bootstrap loop design:
1. Reads tasks from `meta/todo.md` 1. Describes reading tasks from `meta/todo.md`
2. Executes corresponding prompts 2. Documents executing corresponding prompts via external tools
3. Lets AI generate or modify code 3. Outlines AI code generation and modification processes
4. Updates task status 4. Provides status update procedures
This creates a closed loop where the tool improves its own capabilities. This creates a **design for a closed loop** where tools could theoretically improve themselves.
## Documentation ## Documentation
Key documentation files provide different perspectives: This project consists entirely of design documentation and AI tool descriptions:
- **README.md**: Vision, core concepts, quick overview
- **docs/ARCHITECTURE.md**: Detailed technical architecture, component design ### Core Design Documents
- **docs/GETTING_STARTED.md**: Step-by-step setup and usage guide - **README.md**: Project vision, architecture philosophy, and overview
- **meta/todo.md**: Current development priorities and status - **docs/ARCHITECTURE.md**: Detailed technical architecture design and component specifications
- **docs/GETTING_STARTED.md**: Design implementation guide and conceptual setup
### Development Planning
- **meta/todo.md**: Design task tracking and development priorities
- **docs/next-steps/**: Auto-generated next-step planning documents (design concepts)
### AI Tool Scripts (Design References)
- **scripts/run-prompt.js**: Prompt execution logic description
- **scripts/bootstrap.js**: Bootstrap loop design document
- **scripts/plan-next.js**: Next-step planning design document
All content is **design documentation** meant to be referenced by external AI tools for implementation guidance.

View File

@ -4,7 +4,18 @@
MetaCraft 是一个基于AI大语言模型的元开发工具旨在辅助任意大型项目的开发。其核心思想是**将软件开发过程转化为一系列可组合、可执行的prompt、脚本和文档**并通过Claude Code与AI智能体协作实现项目的迭代构建。 MetaCraft 是一个基于AI大语言模型的元开发工具旨在辅助任意大型项目的开发。其核心思想是**将软件开发过程转化为一系列可组合、可执行的prompt、脚本和文档**并通过Claude Code与AI智能体协作实现项目的迭代构建。
更特别的是MetaCraft 项目本身也使用这套工具进行开发形成“自举”bootstrapping的闭环从而验证和优化工具链的有效性。 更特别的是MetaCraft 项目本身也使用这套工具进行开发,形成"自举"bootstrapping的闭环从而验证和优化工具链的有效性。
## 架构理念
MetaCraft 采用**纯文档化架构**项目仅包含文档、设计说明和AI工具脚本不包含任何执行环境或运行服务。
- **文档**Markdown格式的设计文档、架构说明、使用指南
- **设计**:系统组件设计、接口规范、工作流描述
- **工具脚本**JavaScript文件描述自动化逻辑供AI参考执行
- **执行分离**具体执行由外部AI工具如Claude Code完成
这种架构使得MetaCraft成为**可移植的知识库**任何AI系统都可以参考其中的设计来实现类似功能。
## 核心概念 ## 核心概念
@ -14,9 +25,9 @@ MetaCraft 是一个基于AI大语言模型的元开发工具旨在辅助任
- 开发者与AI的对话历史成为项目演进的可追溯记录。 - 开发者与AI的对话历史成为项目演进的可追溯记录。
### 2. 可执行的知识 (Executable Knowledge) ### 2. 可执行的知识 (Executable Knowledge)
- **Node.js 脚本** 用于自动化重复操作(如文件生成、测试运行、依赖安装)。 - **AI工具脚本** 描述自动化操作的逻辑和步骤供AI参考执行(如文件生成、测试运行、依赖安装)。
- **Markdown 文档** 记录设计决策、架构说明、使用指南同时也可作为AI的上下文输入。 - **Markdown 文档** 记录设计决策、架构说明、使用指南同时也可作为AI的上下文输入。
- **Claude Code 执行** 作为与AI交互的桥梁执行prompt并获取结果 - **外部AI工具执行** 实际执行由外部AI工具如Claude Code完成本项目不包含执行环境
### 3. 自举 (Bootstrapping) ### 3. 自举 (Bootstrapping)
- MetaCraft 工具链本身通过MetaCraft定义的工作流进行开发。 - MetaCraft 工具链本身通过MetaCraft定义的工作流进行开发。
@ -32,11 +43,10 @@ MetaCraft/
│ ├── feature-add.md │ ├── feature-add.md
│ ├── bug-fix.md │ ├── bug-fix.md
│ └── refactor.md │ └── refactor.md
├── scripts/ # Node.js 自动化脚本 ├── scripts/ # AI工具脚本供AI参考不包含执行环境
│ ├── generate.js │ ├── run-prompt.js # 执行prompt文件的逻辑描述
│ ├── validate.js │ ├── bootstrap.js # 自举循环的逻辑描述
│ ├── deploy.js │ └── plan-next.js # 规划下一步的逻辑描述
│ └── bootstrap.js # 自举脚本
├── docs/ # 项目文档 ├── docs/ # 项目文档
│ ├── ARCHITECTURE.md │ ├── ARCHITECTURE.md
│ ├── WORKFLOW.md │ ├── WORKFLOW.md
@ -49,19 +59,21 @@ MetaCraft/
└── manifest.json # 描述工具组件及依赖 └── manifest.json # 描述工具组件及依赖
``` ```
### 核心组件 ### 核心组件(设计概念)
1. **Prompt 引擎**解析prompt文件注入上下文变量调用Claude Code执行。 1. **Prompt 引擎**描述如何解析prompt文件注入上下文变量调用外部AI工具执行。
2. **脚本执行器**运行Node.js脚本提供统一的API用于文件操作、Git操作、命令执行等。 2. **脚本执行器**描述如何运行自动化脚本的逻辑提供文件操作、Git操作、命令执行等步骤说明。
3. **上下文管理器**维护项目状态如当前模块、依赖关系、待办任务为AI提供连贯的上下文。 3. **上下文管理器**描述如何维护项目状态如当前模块、依赖关系、待办任务为AI提供连贯的上下文。
4. **自举循环**一个内置的工作流用于更新工具自身——检测新需求生成prompt执行脚本验证变更。 4. **自举循环**描述一个自举工作流——检测新需求生成prompt执行脚本验证变更。
注意这些组件是设计概念和逻辑描述实际执行由外部AI工具完成本项目不包含执行环境。
## 快速开始 ## 快速开始
### 前提条件 ### 前提条件
- Node.js 18+ - 外部AI工具如Claude Code CLI用于实际执行
- Claude Code CLI 已安装并配置 - Git用于版本控制
- Git - 注意本项目不包含执行环境scripts目录下的脚本是供AI参考的工具描述
### 初始化新项目 ### 初始化新项目
```bash ```bash
@ -71,13 +83,13 @@ npx meta-cli init my-project
### 开发一个功能 ### 开发一个功能
1. 在 `prompts/` 下创建一个新的prompt文件描述功能需求。 1. 在 `prompts/` 下创建一个新的prompt文件描述功能需求。
2. 运行 `node scripts/run-prompt.js prompts/my-feature.md`让AI生成代码草案。 2. 让AI参考 `scripts/run-prompt.js` 中的逻辑描述来执行prompt生成代码草案。
3. 审查生成的代码,运行测试,提交更改。 3. 审查生成的代码,运行测试,提交更改。
### 参与MetaCraft自举开发 ### 参与MetaCraft自举开发
1. 查看 `meta/todo.md` 获取待开发任务。 1. 查看 `meta/todo.md` 获取待开发任务。
2. 选择任务,在 `prompts/` 中编写或更新prompt。 2. 选择任务,在 `prompts/` 中编写或更新prompt。
3. 执行 `node scripts/bootstrap.js` 启动自举循环AI将协助实现该任务。 3. 让AI参考 `scripts/bootstrap.js` 中的自举循环逻辑来执行任务。
4. 提交Pull Request。 4. 提交Pull Request。
## 工作流示例 ## 工作流示例
@ -85,9 +97,9 @@ npx meta-cli init my-project
假设要添加一个REST API端点 假设要添加一个REST API端点
1. **任务描述**:创建 `prompts/add-rest-endpoint.md`,描述端点路径、方法、参数、返回类型。 1. **任务描述**:创建 `prompts/add-rest-endpoint.md`,描述端点路径、方法、参数、返回类型。
2. **上下文注入**工具自动注入现有项目结构、相关模块的代码片段 2. **上下文注入**AI参考项目结构、相关模块的代码片段作为上下文
3. **AI执行**Claude Code读取prompt生成或修改控制器、路由、模型文件。 3. **AI执行**外部AI工具Claude Code读取prompt生成或修改控制器、路由、模型文件。
4. **脚本验证**运行 `node scripts/validate.js` 检查语法、运行单元测试。 4. **脚本验证**AI参考验证逻辑描述来检查语法、运行单元测试。
5. **文档更新**AI同时更新API文档记录新端点。 5. **文档更新**AI同时更新API文档记录新端点。
## 贡献指南 ## 贡献指南

View File

@ -1,5 +1,16 @@
# MetaCraft 架构设计 # MetaCraft 架构设计
## 架构理念
MetaCraft 采用**纯文档化架构**项目仅包含设计文档和AI工具脚本描述不包含任何执行环境或运行服务。
- **设计文档**Markdown格式的架构设计、组件规范、接口定义
- **AI工具脚本**JavaScript文件描述自动化逻辑供AI参考执行
- **执行分离**具体实现由外部AI工具如Claude Code完成
- **可移植知识**任何AI系统都可以参考这些设计实现类似功能
所有组件描述都是**设计概念**不是可执行代码。实际运行时需要外部AI工具根据这些设计进行实现。
## 设计原则 ## 设计原则
1. **可自举**:工具链必须能够描述和实现自身的演进。 1. **可自举**:工具链必须能够描述和实现自身的演进。
@ -10,18 +21,19 @@
## 系统组件 ## 系统组件
### 1. Prompt 引擎 (`prompt-engine.js`) ### 1. Prompt 引擎设计 (`prompt-engine.js`)
负责加载、解析、执行prompt文件 描述如何加载、解析、执行prompt文件的设计概念
**功能** **设计功能**
- 读取Markdown格式的prompt文件。 - 描述读取Markdown格式prompt文件的逻辑
- 提取元数据(如`<!-- target: generate-controller -->` - 说明元数据提取方法(如`<!-- target: generate-controller -->`
- 注入动态上下文当前文件树、相关代码片段、Git状态等 - 概述上下文注入机制当前文件树、相关代码片段、Git状态等
- 调用Claude Code执行prompt获取AI响应。 - 提供调用外部AI工具如Claude Code执行prompt的指导
- 将响应解析为具体的操作指令(创建文件、修改代码、运行命令等)。 - 文档化AI响应解析为操作指令的过程
**接口示例** **设计接口示例**
```javascript ```javascript
// 设计概念外部AI工具应实现的接口
const { executePrompt } = require('./prompt-engine'); const { executePrompt } = require('./prompt-engine');
await executePrompt('prompts/add-feature.md', { await executePrompt('prompts/add-feature.md', {
projectRoot: '.', projectRoot: '.',
@ -29,18 +41,19 @@ await executePrompt('prompts/add-feature.md', {
}); });
``` ```
### 2. 脚本执行器 (`script-runner.js`) ### 2. 脚本执行器设计 (`script-runner.js`)
统一执行Node.js脚本提供工具函数 描述统一执行自动化脚本的设计概念
**内置工具函数** **设计工具函数**
- `fs` 增强:读写文件,保持格式。 - `fs` 增强:描述读写文件、保持格式的逻辑
- `git` 操作:提交、分支、对比。 - `git` 操作:说明提交、分支、对比的实现方法
- `command` 执行:运行shell命令捕获输出。 - `command` 执行:概述运行shell命令、捕获输出的设计
- `template` 渲染:基于模板生成文件。 - `template` 渲染:文档化基于模板生成文件的流程
- `validation`语法检查、测试运行、lint。 - `validation`描述语法检查、测试运行、lint的设计
**示例脚本** **设计示例脚本**
```javascript ```javascript
// 设计概念外部AI工具应实现的脚本模式
const { runScript, fs, git } = require('@metacraft/runner'); const { runScript, fs, git } = require('@metacraft/runner');
module.exports = async (args) => { module.exports = async (args) => {
const content = await fs.read('templates/component.js'); const content = await fs.read('templates/component.js');
@ -49,18 +62,18 @@ module.exports = async (args) => {
}; };
``` ```
### 3. 上下文管理器 (`context-manager.js`) ### 3. 上下文管理器设计 (`context-manager.js`)
维护项目状态为AI提供连贯的上下文 描述维护项目状态、为AI提供连贯上下文的设计概念
**存储内容** **设计存储内容**
- 项目结构树 - 项目结构树:描述如何存储和查询文件树结构
- 模块依赖图 - 模块依赖图:说明依赖关系的建模和管理方法
- 待办任务列表(从`meta/todo.md`解析)。 - 待办任务列表:文档化从`meta/todo.md`解析任务的逻辑
- 最近的操作历史(最近修改的文件、提交)。 - 操作历史:描述跟踪最近修改、提交的设计
- 自定义变量(如当前版本、环境配置)。 - 自定义变量:说明环境配置、版本等变量的存储机制
**上下文注入** **上下文注入设计**
在执行prompt前自动将相关上下文以Markdown注释的形式插入prompt中,例如: 描述在执行prompt前自动注入相关上下文的设计模式,例如:
``` ```
<!-- context --> <!-- context -->
项目结构: 项目结构:
@ -77,33 +90,39 @@ exports.getUser = async (id) => { ... }
<!-- endcontext --> <!-- endcontext -->
``` ```
### 4. 自举循环 (`bootstrap.js`) ### 4. 自举循环设计 (`bootstrap.js`)
核心自举逻辑读取待办任务选择优先级最高的任务执行对应prompt验证结果更新任务状态。 描述核心自举逻辑的设计概念读取待办任务选择优先级最高的任务执行对应prompt验证结果更新任务状态。
**步骤** **设计步骤**
1. 读取 `meta/todo.md`,解析任务列表 1. 读取 `meta/todo.md`,解析任务列表的设计方法
2. 选择下一个任务例如“实现prompt引擎” 2. 选择下一个任务:描述优先级算法和选择逻辑
3. 查找对应的prompt文件`prompts/implement-prompt-engine.md`)。 3. 查找对应的prompt文件:文档化文件查找和匹配机制
4. 执行prompt,生成或修改代码。 4. 执行prompt概述调用外部AI工具执行的流程
5. 运行验证脚本(测试、构建)。 5. 运行验证脚本:描述测试、构建等验证过程的设计
6. 如果成功,更新任务状态为完成,并提交更改。 6. 成功处理:说明状态更新和提交更改的设计
7. 如果失败,记录错误,并将任务标记为需要人工干预。 7. 失败处理:文档化错误记录和人工干预标记机制
**自动化程度** **自动化程度设计**
- 初期:需要人工审核每个变更。 - 初期:描述人工审核每个变更的设计模式
- 中期:AI可自动处理简单任务如文档更新、代码格式化 - 中期:概述AI自动处理简单任务文档更新、代码格式化的设计
- 长期:AI可处理复杂功能开发人类仅负责高层次设计。 - 长期:说明AI处理复杂功能开发、人类负责高层次设计的架构
## 数据流 ## 数据流设计
描述自举循环中数据流动的设计概念:
``` ```
[待办任务] -> [选择任务] -> [加载prompt] -> [注入上下文] -> [Claude Code执行] [待办任务] -> [选择任务] -> [加载prompt] -> [注入上下文] -> [外部AI工具执行]
^ | ^ |
| v | v
[更新状态] <- [验证结果] <- [执行脚本] <- [解析AI响应] [更新状态] <- [验证结果] <- [执行脚本] <- [解析AI响应]
``` ```
## 文件格式说明 注意这是设计概念图描述逻辑流程实际实现由外部AI工具完成。
## 文件格式设计说明
以下文件格式描述是**设计规范**为外部AI工具提供实现参考。实际使用时外部工具应遵循这些格式规范。
### Prompt 文件 (`*.md`) ### Prompt 文件 (`*.md`)
采用Markdown格式可包含元数据块。 采用Markdown格式可包含元数据块。

View File

@ -1,118 +1,111 @@
# 快速开始 # 快速开始
本指南将帮助你快速上手 MetaCraft包括安装、运行第一个 prompt以及参与自举开发 本指南介绍 MetaCraft 的设计概念和使用方法。**重要提示**MetaCraft 是一个纯文档化架构项目包含设计文档和AI工具脚本描述不包含任何执行环境或运行服务。所有逻辑实现由外部AI工具完成
## 安装 ## 项目设置
### 1. 克隆仓库 ### 1. 克隆仓库(获取设计文档)
```bash ```bash
git clone https://github.com/your-username/metacraft.git git clone https://github.com/your-username/metacraft.git
cd metacraft cd metacraft
``` ```
### 2. 安装依赖 ### 2. 了解项目结构
```bash MetaCraft 包含以下设计文档:
npm install - **架构设计** (`docs/ARCHITECTURE.md`):详细技术架构和组件设计
``` - **AI工具脚本** (`scripts/`):描述自动化逻辑的实现方法
- **任务管理** (`meta/todo.md`):开发任务跟踪和优先级
### 3. 安装 Claude Code CLI ### 3. 外部工具准备
确保已安装 Claude Code CLI 并配置好 API 密钥。请参考 [Claude Code 官方文档](https://claude.com/claude-code) 实际执行需要外部AI工具如 Claude Code CLI。请参考相应工具的安装文档
验证安装 验证外部工具
```bash ```bash
claude --version claude --version
``` ```
## 运行第一个 Prompt ## 理解 Prompt 执行设计
### 步骤 ### 设计概念
1. **查看示例 prompt**:打开 `prompts/example.md`,这是一个简单的任务:创建欢迎脚本。 Prompt 执行流程在 `scripts/run-prompt.js` 中描述。这是一个**设计文档**,说明如何:
2. **执行 prompt**
```bash
npm run prompt -- prompts/example.md
```
或者直接使用 Node.js
```bash
node scripts/run-prompt.js prompts/example.md
```
3. **与 AI 交互**:脚本会调用 Claude CodeAI 将生成 `welcome.js` 文件。按照提示操作。
4. **验证结果**:检查生成的 `welcome.js` 文件,并运行它:
```bash
node welcome.js
```
## 自举开发流程 1. **读取 prompt 文件**:解析 Markdown 格式的 prompt
2. **提取元数据**:识别任务目标、优先级等信息
3. **注入上下文**:为 AI 提供项目状态和相关代码
4. **调用外部 AI 工具**:执行 prompt 并获取响应
5. **解析 AI 输出**:将响应转换为具体操作
MetaCraft 的核心是自举bootstrapping——使用工具自身来开发工具。 ### 参考示例
1. **查看示例 prompt**:打开 `prompts/example.md`,这是一个描述创建欢迎脚本任务的设计示例。
2. **理解执行逻辑**:阅读 `scripts/run-prompt.js` 了解 prompt 执行的设计思路。
3. **外部工具实现**:外部 AI 工具应参考此设计来实现实际执行。
4. **预期结果**:设计预期 AI 会生成 `welcome.js` 文件,外部工具可执行该文件。
### 1. 查看待办任务 ## 自举开发设计概念
```bash
cat meta/todo.md
```
或者运行自举循环查看:
```bash
npm start
```
### 2. 选择一个任务 MetaCraft 的核心是自举bootstrapping设计——描述如何使用工具自身来开发工具。
例如“实现prompt引擎”。找到或创建对应的 prompt 文件(`prompts/implement-prompt-engine.md`)。
### 3. 编写 Prompt ### 1. 任务管理设计
Prompt 应清晰描述任务目标、上下文、输出要求。参考已有示例。 - **待办任务格式**`meta/todo.md` 描述任务跟踪的设计格式
- **优先级系统**:文档化任务分类和优先级映射逻辑
- **状态更新**:描述任务完成标记的设计机制
### 4. 执行自举循环 ### 2. Prompt 查找设计
```bash 描述如何根据任务描述查找对应 prompt 文件的逻辑:
npm start - 文件名匹配算法
``` - 目录搜索机制
选择任务编号,工具将自动执行对应 prompt并调用 AI 生成代码。 - 备用路径策略
### 5. 验证与提交 ### 3. 自举循环设计
- 运行测试(待实现)。 `scripts/bootstrap.js` 描述自举循环的设计概念:
- 确保构建通过。 - 任务列表显示逻辑
- 提交更改到 Git。 - 用户交互设计
- 外部工具调用流程
- 结果验证和状态更新设计
### 6. 更新任务状态 ### 4. 设计工作流
自举循环会询问是否标记任务为完成。确认后,`meta/todo.md` 中对应任务将被勾选。 1. **设计参考**:阅读 `scripts/bootstrap.js` 了解自举循环设计
2. **外部实现**AI工具参考此设计实现实际自举功能
3. **验证设计**:按照设计描述的验证步骤检查结果
4. **状态更新**:外部工具应遵循设计中的状态更新逻辑
## 项目结构速查 ## 项目结构速查
``` ```
metacraft/ metacraft/
├── prompts/ # 任务prompt库 ├── prompts/ # 任务prompt设计库
│ └── example.md # 示例prompt │ └── example.md # 示例prompt设计
├── scripts/ # 核心脚本 ├── scripts/ # AI工具脚本设计文档
│ ├── run-prompt.js # 执行prompt │ ├── run-prompt.js # Prompt执行逻辑设计描述
│ └── bootstrap.js # 自举循环 │ ├── bootstrap.js # 自举循环设计文档
├── docs/ # 文档 │ └── plan-next.js # 规划下一步设计文档
│ ├── ARCHITECTURE.md ├── docs/ # 设计文档
│ └── GETTING_STARTED.md │ ├── ARCHITECTURE.md # 详细架构设计
├── meta/ # 元数据 │ └── GETTING_STARTED.md # 设计概念快速开始
│ └── todo.md # 待办任务 ├── meta/ # 设计元数据
├── config/ # 配置(暂无) │ └── todo.md # 设计任务跟踪
├── templates/ # 模板(暂无) ├── config/ # 配置设计(暂无)
└── package.json ├── templates/ # 模板设计(暂无)
└── package.json # 项目元数据(设计依赖参考)
``` ```
## 常见问题 ## 常见问题
### Claude Code 命令未找到 ### MetaCraft 项目为什么不包含可执行代码?
确保已正确安装 Claude Code CLI并且 `claude` 命令在 PATH 中 MetaCraft 采用纯文档化架构仅包含设计文档和AI工具脚本描述。实际执行由外部AI工具完成使得设计知识可移植到不同AI系统
### 执行 prompt 时卡住 ### 如何使用这些设计文档?
可能是 Claude Code 需要交互式输入。尝试手动运行: 外部AI工具应参考设计文档实现类似功能。例如Claude Code可以参考 `scripts/run-prompt.js` 中的逻辑描述来实现prompt执行。
```bash
claude --file prompts/example.md
```
### 如何添加新任务? ### 如何添加新的设计任务?
1. 在 `meta/todo.md` 中添加一行 `- [ ] 任务描述` 1. 在 `meta/todo.md` 中添加一行 `- [ ] 任务描述`
2. 在 `prompts/` 中创建对应的 prompt 文件(可选)。如果不存在,自举循环会提示创建 2. 在 `prompts/` 中创建对应的prompt设计文件可选描述任务需求和实现方法
### 如何修改脚本行为 ### 如何理解脚本设计文档
直接编辑 `scripts/` 下的文件。修改后,可以运行 `npm test` 验证(测试待实现) `scripts/` 目录下的文件是**设计描述**不是可执行代码。它们描述逻辑流程、算法步骤和实现方法供外部AI工具参考实现
## 下一步 ## 下一步
- 阅读 [ARCHITECTURE.md](ARCHITECTURE.md) 了解设计细节 - 阅读 [ARCHITECTURE.md](ARCHITECTURE.md) 了解详细架构设计。
- 尝试修改 `prompts/example.md` 并观察效果 - 参考 `scripts/` 目录中的设计文档理解实现逻辑
- 参与开发:选择一个待办任务,编写 prompt 并提交 Pull Request。 - 参与设计改进:选择一个待办任务,更新设计文档并提交 Pull Request。

View File

@ -1,23 +1,17 @@
{ {
"name": "metacraft", "name": "metacraft",
"version": "0.0.1", "version": "0.0.1",
"description": "AI-Powered Meta-Development Tool", "description": "AI-Powered Meta-Development Tool - Documentation and Design Repository (No Execution Environment)",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node scripts/bootstrap.js", "start": "echo 'Bootstrap loop design - see scripts/bootstrap.js for implementation logic'",
"prompt": "node scripts/run-prompt.js", "prompt": "echo 'Prompt execution design - see scripts/run-prompt.js for implementation logic'",
"plan": "node scripts/plan-next.js", "plan": "echo 'Plan next step design - see scripts/plan-next.js for implementation logic'",
"test": "echo \"No tests yet\" && exit 0" "test": "echo 'Testing framework design - see docs/ARCHITECTURE.md for design concepts'"
}, },
"keywords": ["ai", "development", "tooling", "bootstrapping"], "keywords": ["ai", "development", "tooling", "bootstrapping"],
"author": "", "author": "",
"license": "MIT", "license": "MIT",
"dependencies": {
"commander": "^11.0.0",
"fs-extra": "^11.1.1",
"marked": "^12.0.0",
"simple-git": "^3.19.0"
},
"devDependencies": { "devDependencies": {
"@types/node": "^20.0.0" "@types/node": "^20.0.0"
}, },

231
scripts/bootstrap.js vendored
View File

@ -1,176 +1,87 @@
#!/usr/bin/env node
/** /**
* bootstrap.js - MetaCraft 自举循环入口 * bootstrap.js - MetaCraft 自举循环AI工具脚本
* *
* 1. 读取待办任务列表 * 此脚本描述MetaCraft的自举循环逻辑供AI参考使用
* 2. 显示可选任务 * 实际执行由外部AI工具完成本项目不包含执行环境
* 3. 执行选中的任务调用对应prompt *
* 4. 验证结果并更新任务状态 * 功能描述
* 1. 读取待办任务列表meta/todo.md
* 2. 解析任务分类和状态
* 3. 显示未完成的任务供用户选择
* 4. 查找与选中任务对应的prompt文件
* 5. 调用run-prompt执行选中的prompt
* 6. 询问用户是否标记任务为完成并更新任务状态
*
* 输入交互式
* 输出执行选中的prompt任务更新任务状态
*
* 伪代码逻辑
*/ */
const fs = require('fs'); // 主函数:自举循环入口
const path = require('path'); // 返回:无(交互式流程)
const readline = require('readline'); function bootstrapLoop() {
// 步骤1读取待办任务文件
// 使用文件系统API读取meta/todo.md内容
const TODO_FILE = path.join(__dirname, '../meta/todo.md'); // 步骤2解析任务
const PROMPTS_DIR = path.join(__dirname, '../prompts'); // 调用parseTodo函数解析任务列表得到tasks数组
// 解析待办任务文件 // 步骤3筛选未完成的任务
function parseTodo(content) { // 过滤出checked为false的任务得到pendingTasks
const lines = content.split('\n');
const tasks = [];
let currentCategory = '';
for (const line of lines) { // 步骤4显示任务列表
const categoryMatch = line.match(/^##\s+(.+)/); // 格式化输出每个未完成任务的序号、类别和描述
if (categoryMatch) {
currentCategory = categoryMatch[1].trim(); // 步骤5获取用户选择
continue; // 通过命令行交互询问用户选择任务编号或跳过
// 步骤6查找对应的prompt文件
// 调用findPromptForTask函数根据任务描述查找prompt文件
// 如果未找到,提示用户创建
// 步骤7执行prompt
// 调用executePromptFile函数来自run-prompt.js执行找到的prompt文件
// 步骤8确认完成状态
// 询问用户任务是否已完成如果是则调用updateTodo更新任务状态
// 注意此函数为伪代码描述实际实现由外部AI工具完成
} }
const taskMatch = line.match(/^- \[( |x)\]\s+(.+)/); // 辅助函数:解析待办任务内容
if (taskMatch) { // 参数todoContent - 待办任务文件的文本内容
const checked = taskMatch[1] === 'x'; // 返回任务对象数组每个对象包含category, description, checked, raw等属性
const description = taskMatch[2].trim(); function parseTodo(todoContent) {
tasks.push({ // 按行分割内容
category: currentCategory, // 遍历每一行,识别分类标题(## 分类名)
description, // 识别任务项(- [ ] 任务描述 或 - [x] 任务描述)
checked, // 构建任务对象并添加到数组
raw: line // 返回任务数组
});
}
} }
return tasks; // 辅助函数查找任务对应的prompt文件
} // 参数task - 任务对象
// 返回prompt文件路径或null
// 更新待办任务文件
function updateTodo(tasks, updatedTask) {
// 简化的实现:找到对应行并替换
const content = fs.readFileSync(TODO_FILE, 'utf-8');
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
if (lines[i].includes(updatedTask.description)) {
const newLine = lines[i].replace('- [ ]', '- [x]');
lines[i] = newLine;
break;
}
}
fs.writeFileSync(TODO_FILE, lines.join('\n'), 'utf-8');
}
// 查找对应prompt文件
function findPromptForTask(task) { function findPromptForTask(task) {
// 简单映射:将任务描述转换为文件名 // 将任务描述转换为kebab-case文件名
const name = task.description // 尝试多种可能的文件名格式:
.toLowerCase() // - 直接使用描述转换
.replace(/[^\w\s]/g, '') // - 添加implement-前缀
.replace(/\s+/g, '-'); // - 添加task-前缀
const possiblePaths = [ // 检查prompts目录下是否存在对应文件
path.join(PROMPTS_DIR, `${name}.md`), // 返回找到的路径否则返回null
path.join(PROMPTS_DIR, `implement-${name}.md`),
path.join(PROMPTS_DIR, `task-${name}.md`)
];
for (const p of possiblePaths) {
if (fs.existsSync(p)) {
return p;
}
}
return null;
} }
async function main() { // 辅助函数:更新待办任务状态
console.log('🚀 MetaCraft 自举循环启动\n'); // 参数tasks - 所有任务数组updatedTask - 要更新的任务对象
// 返回:无(直接写入文件)
if (!fs.existsSync(TODO_FILE)) { function updateTodo(tasks, updatedTask) {
console.error('❌ 待办任务文件不存在:', TODO_FILE); // 读取待办任务文件内容
process.exit(1); // 找到对应任务描述的行
// 将- [ ]替换为- [x]标记为完成
// 将更新后的内容写回文件
} }
const todoContent = fs.readFileSync(TODO_FILE, 'utf-8'); // 导出函数供AI参考
const tasks = parseTodo(todoContent); // 注意:这些函数不会实际执行,仅作为文档说明
const pendingTasks = tasks.filter(t => !t.checked);
if (pendingTasks.length === 0) {
console.log('🎉 所有任务已完成!');
return;
}
console.log('📋 待办任务列表:');
pendingTasks.forEach((task, index) => {
console.log(` ${index + 1}. [${task.category}] ${task.description}`);
});
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askQuestion(query) {
return new Promise(resolve => {
rl.question(query, answer => {
resolve(answer);
});
});
}
const answer = await askQuestion('\n请输入要执行的任务编号或按回车跳过');
rl.close();
if (!answer.trim()) {
console.log('⏭️ 跳过任务选择');
return;
}
const taskIndex = parseInt(answer) - 1;
if (isNaN(taskIndex) || taskIndex < 0 || taskIndex >= pendingTasks.length) {
console.error('❌ 无效的选择');
process.exit(1);
}
const selectedTask = pendingTasks[taskIndex];
console.log(`\n🎯 选中任务:${selectedTask.description}`);
const promptPath = findPromptForTask(selectedTask);
if (!promptPath) {
console.error(`❌ 未找到对应prompt文件请在 ${PROMPTS_DIR} 中创建。`);
console.log('提示prompt文件名应与任务描述相关如 "implement-prompt-engine.md"');
return;
}
console.log(`📄 找到prompt文件${promptPath}`);
// 执行prompt
const { main: runPrompt } = require('./run-prompt');
await runPrompt([promptPath]);
// 询问是否标记为完成
const confirm = await new Promise(resolve => {
const confirmRl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
confirmRl.question('\n✅ 任务是否已完成?(y/n) ', answer => {
confirmRl.close();
resolve(answer.toLowerCase() === 'y');
});
});
if (confirm) {
updateTodo(tasks, selectedTask);
console.log('📝 已更新待办任务状态');
} else {
console.log('⚠️ 任务状态未更新,请手动处理');
}
}
if (require.main === module) {
main().catch(err => {
console.error('自举循环错误:', err);
process.exit(1);
});
}
module.exports = { parseTodo, findPromptForTask };

View File

@ -1,20 +1,20 @@
#!/usr/bin/env node
/** /**
* plan-next.js - 规划下一步功能 * plan-next.js - 规划下一步功能的AI工具脚本
* *
* 此脚本描述MetaCraft的规划下一步功能逻辑供AI参考使用
* 实际执行由外部AI工具完成本项目不包含执行环境
*
* 功能描述
* 1. 分析当前项目状态待办任务已完成任务 * 1. 分析当前项目状态待办任务已完成任务
* 2. 根据优先级推荐下一个要完成的任务 * 2. 根据优先级推荐下一个要完成的任务
* 3. 生成对应的prompt文件或下一步文档 * 3. 生成对应的prompt文件或下一步文档
*
* 输入读取meta/todo.md
* 输出推荐的任务生成的prompt文件或规划文档
*
* 伪代码逻辑
*/ */
const fs = require('fs');
const path = require('path');
const TODO_FILE = path.join(__dirname, '../meta/todo.md');
const PROMPTS_DIR = path.join(__dirname, '../prompts');
const OUTPUT_DIR = path.join(__dirname, '../docs/next-steps');
// 任务优先级映射 // 任务优先级映射
const PRIORITY_MAP = { const PRIORITY_MAP = {
'核心功能开发': 'high', '核心功能开发': 'high',
@ -24,370 +24,123 @@ const PRIORITY_MAP = {
'未来功能': 'low' '未来功能': 'low'
}; };
// 解析待办任务文件 // 主函数:规划下一步流程
function parseTodo(content) { // 返回:推荐的任务信息和生成的文件信息
const lines = content.split('\n'); function planNextStep() {
const tasks = []; // 步骤1读取待办任务文件
let currentCategory = ''; // 读取meta/todo.md内容
for (const line of lines) { // 步骤2解析任务
const categoryMatch = line.match(/^##\s+(.+)/); // 调用parseTodo函数解析任务列表
if (categoryMatch) {
currentCategory = categoryMatch[1].trim(); // 步骤3推荐下一个任务
continue; // 调用recommendNextTask函数根据优先级和类别推荐任务
// 输出推荐结果和项目统计信息
// 步骤4询问用户操作
// 提供选项:
// 1. 为推荐任务生成prompt文件
// 2. 生成下一步规划文档
// 3. 两者都生成
// 4. 只显示推荐,不生成文件
// 步骤5根据选择生成文件
// 如果选择1或3调用generatePromptForTask生成prompt文件
// 如果选择2或3调用generateNextStepDocument生成规划文档
// 步骤6输出生成结果和后续建议
// 注意此函数为伪代码描述实际实现由外部AI工具完成
} }
const taskMatch = line.match(/^- \[( |x)\]\s+(.+)/); // 辅助函数:解析待办任务内容
if (taskMatch) { // 参数todoContent - 待办任务文件的文本内容
const checked = taskMatch[1] === 'x'; // 返回任务对象数组每个对象包含category, description, checked, priority, raw等属性
const description = taskMatch[2].trim(); function parseTodo(todoContent) {
tasks.push({ // 按行分割内容
category: currentCategory, // 遍历每一行,识别分类标题(## 分类名)
description, // 识别任务项(- [ ] 任务描述 或 - [x] 任务描述)
checked, // 根据PRIORITY_MAP映射设置任务优先级
priority: PRIORITY_MAP[currentCategory] || 'medium', // 构建任务对象并添加到数组
raw: line // 返回任务数组
});
}
} }
return tasks; // 辅助函数:分析项目状态并推荐下一个任务
} // 参数tasks - 任务对象数组
// 返回包含recommended任务对象、stats统计数据和message推荐信息的对象
// 分析项目状态并推荐下一个任务
function recommendNextTask(tasks) { function recommendNextTask(tasks) {
// 只考虑未完成的任务 // 筛选未完成的任务checked为false
const pendingTasks = tasks.filter(t => !t.checked); // 如果所有任务都已完成返回null推荐和信息
if (pendingTasks.length === 0) {
return {
recommended: null,
message: '🎉 所有任务已完成!没有待推荐的任务。'
};
}
// 按优先级排序high > medium > low // 按优先级排序high > medium > low
const priorityOrder = { high: 1, medium: 2, low: 3 }; // 使用priorityOrder映射high:1, medium:2, low:3
pendingTasks.sort((a, b) => { // 同优先级按类别排序:核心功能开发 > 基础设施 > 文档 > 测试与质量 > 未来功能
if (priorityOrder[a.priority] !== priorityOrder[b.priority]) {
return priorityOrder[a.priority] - priorityOrder[b.priority];
}
// 同优先级按类别排序
const categoryOrder = ['核心功能开发', '基础设施', '文档', '测试与质量', '未来功能'];
return categoryOrder.indexOf(a.category) - categoryOrder.indexOf(b.category);
});
const recommendedTask = pendingTasks[0]; // 选择排序后的第一个任务作为推荐任务
// 计算统计数据 // 计算统计数据:
const totalTasks = tasks.length; // - totalTasks: 总任务数
const completedTasks = tasks.filter(t => t.checked).length; // - completedTasks: 已完成任务数
const pendingByCategory = {}; // - pendingTasks: 待完成任务数
pendingTasks.forEach(task => { // - completionRate: 完成率百分比
pendingByCategory[task.category] = (pendingByCategory[task.category] || 0) + 1; // - pendingByCategory: 按类别统计的待完成任务数
});
return { // 返回包含推荐任务、统计数据和消息的对象
recommended: recommendedTask,
stats: {
totalTasks,
completedTasks,
pendingTasks: pendingTasks.length,
completionRate: totalTasks > 0 ? Math.round((completedTasks / totalTasks) * 100) : 0,
pendingByCategory
},
message: `🎯 推荐下一个任务:${recommendedTask.description} (优先级: ${recommendedTask.priority}, 类别: ${recommendedTask.category})`
};
} }
// 为推荐的任务生成prompt文件 // 辅助函数为推荐的任务生成prompt文件
// 参数task - 任务对象
// 返回包含filePath, fileName, promptContent的对象或null
function generatePromptForTask(task) { function generatePromptForTask(task) {
if (!task) return null; // 如果task为null返回null
// 生成文件名将任务描述转换为kebab-case // 生成文件名:
// 保留中文字符、英文字母、数字,将其他字符替换为空格,然后转换为连字符 // - 将任务描述转换为小写
const fileName = task.description // - 保留中文字符、英文字母、数字、空格
.toLowerCase() // - 移除其他特殊字符
// 保留中文字符 (\u4e00-\u9fff)、英文字母、数字、空格 // - 将连续空格替换为单个空格
.replace(/[^\u4e00-\u9fffa-z0-9\s]/g, ' ') // - 将空格替换为连字符kebab-case
// 将连续的多个空格替换为单个空格 // - 移除开头的implement-前缀(如果存在)
.replace(/\s+/g, ' ') // - 添加.md扩展名
.trim()
// 将空格替换为连字符
.replace(/\s/g, '-')
.replace(/^implement-/, '') // 如果以implement-开头,去掉它
+ '.md';
const filePath = path.join(PROMPTS_DIR, fileName); // 生成prompt内容
// - 包含任务标题
// 生成prompt内容 // - 元数据注释target, priority, category
const promptContent = `# ${task.description} // - 描述、要求、上下文、输出、约束等部分
<!-- target: ${task.description.toLowerCase().replace(/[^\u4e00-\u9fffa-z0-9\s]/g, ' ').replace(/\s+/g, ' ').trim().replace(/\s/g, '-').replace(/^implement-/, '')} -->
<!-- priority: ${task.priority} -->
<!-- category: ${task.category} -->
## 描述
详细描述${task.description}的功能需求和实现目标
## 要求
1. 明确的功能边界和交付物
2. 与现有系统集成的考虑
3. 代码质量标准和最佳实践
4. 必要的测试覆盖
## 上下文
当前项目状态
- 项目MetaCraft (AI驱动的元开发工具)
- 阶段早期开发
- 已完成任务${task.checked ? '是' : '否'}
- 优先级${task.priority}
相关依赖和前置条件
根据任务分析添加具体依赖
## 输出
请提供
1. 完整的设计方案
2. 具体的实现代码
3. 必要的测试用例
4. 文档更新建议
## 约束
- 保持与现有代码风格一致
- 考虑可扩展性和维护性
- 遵循项目架构设计原则`;
// 确保prompts目录存在 // 确保prompts目录存在
if (!fs.existsSync(PROMPTS_DIR)) { // 写入文件
fs.mkdirSync(PROMPTS_DIR, { recursive: true });
// 返回文件信息和内容
} }
// 辅助函数:生成下一步文档
// 参数task - 任务对象stats - 统计信息对象
// 返回包含docFilePath, docFileName, docContent的对象或null
function generateNextStepDocument(task, stats) {
// 如果task为null返回null
// 确保输出目录docs/next-steps存在
// 生成文档文件名next-step-YYYY-MM-DD.md
// 生成文档内容:
// - 标题:下一步规划:任务描述
// - 生成时间
// - 项目状态概览(总任务数、已完成、待完成、完成率)
// - 按类别待完成任务列表
// - 推荐的下一个任务详情
// - 任务分析(为什么选择、预期影响)
// - 详细需求(功能要求、技术实现考虑)
// - 验收标准(复选框列表)
// - 时间规划建议(阶段划分)
// - 风险与缓解(技术风险、缓解措施)
// - 后续任务建议
// 写入文件 // 写入文件
fs.writeFileSync(filePath, promptContent, 'utf-8');
return { // 返回文档信息和内容
filePath,
fileName,
promptContent
};
} }
// 生成下一步文档 // 导出函数供AI参考
function generateNextStepDocument(task, stats) { // 注意:这些函数不会实际执行,仅作为文档说明
if (!task) return null;
// 确保输出目录存在
if (!fs.existsSync(OUTPUT_DIR)) {
fs.mkdirSync(OUTPUT_DIR, { recursive: true });
}
const timestamp = new Date().toISOString().split('T')[0];
const docFileName = `next-step-${timestamp}.md`;
const docFilePath = path.join(OUTPUT_DIR, docFileName);
const docContent = `# 下一步规划:${task.description}
生成时间${new Date().toLocaleString()}
## 项目状态概览
- 总任务数${stats.totalTasks}
- 已完成${stats.completedTasks}
- 待完成${stats.pendingTasks}
- 完成率${stats.completionRate}%
### 按类别待完成任务
${Object.entries(stats.pendingByCategory).map(([cat, count]) => `- ${cat}: ${count}`).join('\n')}
## 推荐的下一个任务
**任务描述**${task.description}
**优先级**${task.priority}
**类别**${task.category}
## 任务分析
### 为什么选择这个任务
1. **优先级最高**属于"${task.category}"类别在当前开发阶段最为关键
2. **依赖关系**可能是其他任务的前置条件
3. **价值最大**完成此任务将为后续开发奠定基础
### 预期影响
- 推动核心功能开发进度
- 为后续任务扫清障碍
- 验证工具链的有效性
## 详细需求
### 功能要求
1. 明确的功能定义和边界
2. 与现有系统的集成点
3. 输入/输出接口规范
4. 错误处理和边界情况
### 技术实现考虑
1. 代码结构和模块设计
2. 性能和安全要求
3. 测试策略和覆盖目标
4. 文档和示例代码
## 验收标准
- [ ] 功能实现完整且符合需求
- [ ] 代码质量符合项目标准
- [ ] 测试用例覆盖主要场景
- [ ] 文档更新及时准确
## 时间规划建议
**阶段1设计与规划** (1-2)
- 详细需求分析
- 技术方案设计
- 接口定义和原型验证
**阶段2实现与测试** (2-3)
- 核心功能实现
- 单元测试和集成测试
- 代码审查和优化
**阶段3集成与文档** (1)
- 系统集成和验证
- 文档编写和示例
- 部署和发布准备
## 风险与缓解
### 技术风险
- 与现有系统兼容性问题
- 性能瓶颈或扩展性限制
### 缓解措施
- 提前进行技术验证和原型测试
- 分阶段实现及时反馈和调整
## 后续任务建议
完成此任务后建议考虑
1. **${task.category}**中的其他高优先级任务
2. 依赖此任务的下游功能开发
3. 相关文档和测试完善
---
*本文档由MetaCraft的"规划下一步"功能自动生成*`;
fs.writeFileSync(docFilePath, docContent, 'utf-8');
return {
docFilePath,
docFileName,
docContent
};
}
async function main() {
console.log('🚀 MetaCraft 规划下一步功能启动\n');
// 读取待办任务文件
if (!fs.existsSync(TODO_FILE)) {
console.error('❌ 待办任务文件不存在:', TODO_FILE);
process.exit(1);
}
const todoContent = fs.readFileSync(TODO_FILE, 'utf-8');
const tasks = parseTodo(todoContent);
// 推荐下一个任务
const recommendation = recommendNextTask(tasks);
console.log(recommendation.message);
if (recommendation.recommended) {
// 显示统计信息
console.log('\n📊 项目状态统计:');
console.log(` 总任务数:${recommendation.stats.totalTasks}`);
console.log(` 已完成:${recommendation.stats.completedTasks}`);
console.log(` 待完成:${recommendation.stats.pendingTasks}`);
console.log(` 完成率:${recommendation.stats.completionRate}%`);
console.log('\n📈 按类别待完成任务:');
Object.entries(recommendation.stats.pendingByCategory).forEach(([cat, count]) => {
console.log(` ${cat}: ${count}`);
});
// 询问用户要做什么
const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askQuestion(query) {
return new Promise(resolve => {
rl.question(query, answer => {
resolve(answer.trim());
});
});
}
console.log('\n📝 请选择操作:');
console.log(' 1. 为推荐任务生成prompt文件');
console.log(' 2. 生成下一步规划文档');
console.log(' 3. 两者都生成');
console.log(' 4. 只显示推荐,不生成文件');
const choice = await askQuestion('\n请输入选择 (1-4默认3): ') || '3';
let promptResult = null;
let docResult = null;
switch(choice) {
case '1':
promptResult = generatePromptForTask(recommendation.recommended);
break;
case '2':
docResult = generateNextStepDocument(recommendation.recommended, recommendation.stats);
break;
case '3':
promptResult = generatePromptForTask(recommendation.recommended);
docResult = generateNextStepDocument(recommendation.recommended, recommendation.stats);
break;
case '4':
console.log('\n👌 已跳过文件生成。');
break;
default:
console.log(`\n❌ 无效的选择:"${choice}",跳过文件生成。`);
}
// 输出生成结果
if (promptResult) {
console.log(`\n✅ 已生成prompt文件${promptResult.filePath}`);
}
if (docResult) {
console.log(`\n📄 已生成下一步规划文档:${docResult.docFilePath}`);
}
rl.close();
// 给出后续建议
if (promptResult || docResult) {
console.log('\n💡 后续建议:');
console.log(' 1. 查看生成的文件,根据需要调整内容');
console.log(' 2. 运行 bootstrap.js 执行该任务');
console.log(' 3. 或直接运行 promptnode scripts/run-prompt.js prompts/...');
}
} else {
console.log(recommendation.message);
}
}
if (require.main === module) {
main().catch(err => {
console.error('规划下一步功能错误:', err);
process.exit(1);
});
}
module.exports = {
parseTodo,
recommendNextTask,
generatePromptForTask,
generateNextStepDocument
};

View File

@ -1,84 +1,67 @@
#!/usr/bin/env node
/** /**
* run-prompt.js - 执行一个prompt文件 * run-prompt.js - 执行一个prompt文件的AI工具脚本
* *
* 用法node run-prompt.js <prompt文件路径> * 此脚本描述如何执行一个prompt文件供AI参考使用
* 实际执行由外部AI工具完成本项目不包含执行环境
*
* 功能描述
* 1. 读取指定的prompt文件
* 2. 提取文件中的元数据targetpriority等
* 3. 检查Claude Code CLI是否可用外部环境
* 4. 调用Claude Code CLI执行prompt
* 5. 输出AI响应结果
*
* 输入prompt文件路径
* 输出AI生成的响应内容
*
* 伪代码逻辑
*/ */
const fs = require('fs'); // 主函数执行prompt文件
const path = require('path'); // 参数promptFilePath - prompt文件的路径
const { execSync } = require('child_process'); // 返回AI响应内容字符串
function executePromptFile(promptFilePath) {
// 步骤1验证文件存在
// 如果文件不存在,抛出错误或返回错误信息
async function main() { // 步骤2读取文件内容
const args = process.argv.slice(2); // 使用文件系统API读取文件内容得到promptContent字符串
if (args.length < 1) {
console.error('请指定prompt文件路径'); // 步骤3提取元数据
console.log('用法node run-prompt.js <prompt文件路径>'); // 从promptContent中匹配 <!-- target: xxx --> 格式的注释
process.exit(1); // 提取target值用于日志显示
// 步骤4检查Claude Code CLI是否可用
// 尝试执行命令 'claude --version',如果失败则提示用户手动执行
// 步骤5准备临时文件
// 在.temp目录下创建临时文件将prompt内容写入
// 步骤6调用Claude Code CLI
// 执行命令claude --file "临时文件路径"
// 捕获输出结果
// 步骤7清理临时文件
// 删除临时文件
// 步骤8返回AI响应
// 将Claude Code的输出返回给调用者
// 注意此函数为伪代码描述实际实现由外部AI工具完成
} }
const promptPath = path.resolve(args[0]); // 辅助函数提取prompt元数据
if (!fs.existsSync(promptPath)) { function extractPromptMetadata(promptContent) {
console.error(`文件不存在:${promptPath}`); // 从prompt内容中提取target、priority等元数据
process.exit(1); // 使用正则表达式匹配 <!-- key: value --> 格式
// 返回包含元数据的对象
} }
console.log(`📄 读取prompt文件${promptPath}`); // 辅助函数调用Claude Code CLI
const promptContent = fs.readFileSync(promptPath, 'utf-8'); function invokeClaudeCode(promptContent) {
// 调用外部Claude Code CLI工具执行prompt
// 提取元数据 // 返回AI生成的响应
const targetMatch = promptContent.match(/<!-- target: (.+?) -->/);
const target = targetMatch ? targetMatch[1].trim() : 'unknown';
console.log(`🎯 任务目标:${target}`);
// 检查Claude Code是否可用
try {
execSync('claude --version', { stdio: 'ignore' });
} catch (e) {
console.error('❌ 未检测到Claude Code CLI请确保已安装并配置。');
console.log('提示可以手动复制以下prompt内容到Claude Code中执行');
console.log('---');
console.log(promptContent);
console.log('---');
process.exit(1);
} }
// 构建临时文件路径 // 导出函数供AI参考
const tempDir = path.join(__dirname, '../.temp'); // 注意:这些函数不会实际执行,仅作为文档说明
if (!fs.existsSync(tempDir)) {
fs.mkdirSync(tempDir, { recursive: true });
}
const tempPromptFile = path.join(tempDir, `prompt-${Date.now()}.md`);
fs.writeFileSync(tempPromptFile, promptContent);
console.log(`🤖 正在调用Claude Code执行prompt...`);
try {
// 使用Claude Code执行临时文件
// 注意这里假设claude命令可以直接执行文件实际可能需要调整
const command = `claude --file "${tempPromptFile}"`;
console.log(`执行命令:${command}`);
const output = execSync(command, { encoding: 'utf-8' });
console.log('✅ AI响应');
console.log(output);
} catch (error) {
console.error('❌ 执行失败:', error.message);
console.log('建议请手动使用Claude Code打开该prompt文件进行交互。');
}
// 清理临时文件
try {
fs.unlinkSync(tempPromptFile);
} catch (e) {
// 忽略清理错误
}
}
if (require.main === module) {
main().catch(err => {
console.error('未预期的错误:', err);
process.exit(1);
});
}
module.exports = { main };