docs: 新增 OpenCode CLI 配置入门文档

This commit is contained in:
tukuaiai
2026-01-10 21:43:46 +08:00
parent cfdc8bf800
commit 3ba2cc22a2
15 changed files with 895 additions and 7 deletions
+59
View File
@@ -0,0 +1,59 @@
# 🎨 Canvas Whiteboard-Driven Development Workflow
> Graphics are first-class citizens; code is the serialized form of the whiteboard
## Core Philosophy
```
Traditional Development: Code → Verbal Communication → Mental Architecture → Code Chaos
Canvas Approach: Code ⇄ Whiteboard ⇄ AI ⇄ Human (Whiteboard as Single Source of Truth)
```
| Pain Point | Solution |
|:-----------|:---------|
| 🤖 AI can't understand project structure | ✅ AI reads whiteboard JSON directly, instantly grasps architecture |
| 🧠 Humans can't remember complex dependencies | ✅ Clear connections, ripple effects visible at a glance |
| 💬 Team collaboration relies on verbal explanation | ✅ Point at the whiteboard, newcomers understand in 5 minutes |
## File Structure
```
canvas-dev/
├── README.md # This file - Workflow overview
├── workflow.md # Complete workflow steps (linear process)
├── prompts/
│ ├── 01-architecture-analysis.md # Prompt for generating whiteboard from code
│ ├── 02-whiteboard-driven-coding.md # Prompt for generating code from whiteboard
│ └── 03-whiteboard-sync-check.md # Validate whiteboard-code consistency
├── templates/
│ ├── project.canvas # Obsidian Canvas project template
│ └── module.canvas # Single module whiteboard template
└── examples/
└── demo-project.canvas # Example project whiteboard
```
## Quick Start
### 1. Prepare Tools
- [Obsidian](https://obsidian.md/) - Free open-source whiteboard tool
- AI assistant (Claude/GPT-4, must support reading Canvas JSON)
### 2. Generate Project Architecture Whiteboard
```bash
# Provide project code path to AI, use architecture analysis prompt
# AI automatically generates .canvas file
```
### 3. Drive Development with Whiteboard
- Draw new modules and dependency relationships on the whiteboard
- Export whiteboard JSON and send to AI
- AI generates/modifies code based on the whiteboard
## Related Documentation
- [Canvas Whiteboard-Driven Development Guide](../../documents/02-methodology/Graphical AI Collaboration - Canvas Whiteboard-Driven Development.md)
- [Whiteboard-Driven Development System Prompt](../../prompts/01-system-prompts/AGENTS.md/12/AGENTS.md)
- [Glue Coding](../../documents/00-fundamentals/Glue Coding.md)
@@ -0,0 +1,85 @@
# 01-Architecture Analysis Prompt
> Automatically generate Obsidian Canvas architecture whiteboard from existing code
## Use Cases
- Taking over a new project, quickly understand architecture
- Create visual documentation for existing projects
- Prepare for Code Review or technical presentations
## Prompt
```markdown
You are a code architecture analysis expert. Please analyze the following project structure and generate an architecture whiteboard in Obsidian Canvas format.
## Input
Project path: {PROJECT_PATH}
Analysis granularity: {GRANULARITY} (file/class/service)
## Output Requirements
Generate a .canvas file conforming to Obsidian Canvas JSON format, including:
1. **Nodes**:
- Each module/file/class as a node
- Node contains: id, type, x, y, width, height, text
- Layout by functional zones (e.g., API layer on left, data layer on right)
2. **Edges**:
- Represent dependency/call relationships between modules
- Contains: id, fromNode, toNode, fromSide, toSide, label
- Label indicates relationship type (call/inheritance/dependency/data flow)
3. **Groups**:
- Group by functional domain (e.g., user module, payment module)
- Use colors to distinguish different layers
## Canvas JSON Structure Example
```json
{
"nodes": [
{
"id": "node1",
"type": "text",
"x": 0,
"y": 0,
"width": 200,
"height": 100,
"text": "# UserService\n- createUser()\n- getUser()"
}
],
"edges": [
{
"id": "edge1",
"fromNode": "node1",
"toNode": "node2",
"fromSide": "right",
"toSide": "left",
"label": "calls"
}
]
}
```
## Analysis Steps
1. Scan project directory structure
2. Identify entry files and core modules
3. Analyze import/require statements to extract dependency relationships
4. Identify database operations, API calls, external services
5. Layout node positions by call hierarchy
6. Generate complete .canvas JSON
```
## Usage Example
```
Please analyze the /home/user/my-project project and generate a file-level architecture whiteboard.
Focus on:
- API routes and handler functions
- Database models and operations
- External service calls
```
## Output File
The generated `.canvas` file can be directly opened and edited in Obsidian.
@@ -0,0 +1,88 @@
# 02-Whiteboard-Driven Coding Prompt
> Generate/modify code based on Canvas whiteboard architecture diagram
## Use Cases
- New feature development: Draw whiteboard first, then generate code
- Architecture refactoring: Modify whiteboard connections, AI syncs code refactoring
- Module splitting: Split nodes on whiteboard, AI generates new files
## Prompt
```markdown
You are an expert at generating code from architecture whiteboards. Please generate corresponding code implementation based on the following Obsidian Canvas whiteboard JSON.
## Input
Canvas JSON:
```json
{CANVAS_JSON}
```
Tech stack: {TECH_STACK}
Target directory: {TARGET_DIR}
## Parsing Rules
1. **Node → File/Class**
- Title in node text → filename/classname
- List items in node text → methods/functions
- Node color/group → module affiliation
2. **Edge → Dependency Relationship**
- fromNode → toNode = import/call relationship
- Edge label determines relationship type:
- "calls" → function call
- "extends" → class extends
- "depends" → import
- "data flow" → parameter passing
3. **Group → Directory Structure**
- Nodes in the same group go in the same directory
- Group name → directory name
## Output Requirements
1. Generate complete file structure
2. Each file contains:
- Correct import statements (based on edges)
- Class/function definitions (based on node content)
- Call relationship implementation (based on edge direction)
3. Add necessary type annotations and comments
4. Follow tech stack best practices
## Output Format
```
File: {file_path}
```{language}
{code_content}
```
```
## Usage Example
```
Generate Python FastAPI project code based on the following whiteboard:
{paste .canvas file content}
Tech stack: Python 3.11 + FastAPI + SQLAlchemy
Target directory: /home/user/my-api
```
## Incremental Update Mode
When whiteboard is modified, use the following prompt:
```markdown
Whiteboard has been updated, please compare old and new versions, only modify changed parts:
Old whiteboard: {OLD_CANVAS_JSON}
New whiteboard: {NEW_CANVAS_JSON}
Output:
1. Files to add
2. Files to modify (output only diff)
3. Files to delete
```
@@ -0,0 +1,147 @@
# 03-Whiteboard Sync Check Prompt
> Validate consistency between whiteboard and actual code
## Use Cases
- Check if whiteboard needs updating before PR/MR merge
- Periodic audit of architecture documentation accuracy
- Discover implicit dependencies in code
## Prompt
```markdown
You are a code and architecture consistency checking expert. Please compare the following whiteboard and code to find inconsistencies.
## Input
Canvas whiteboard JSON:
```json
{CANVAS_JSON}
```
Project code path: {PROJECT_PATH}
## Check Items
1. **Node Completeness**
- Do all nodes in the whiteboard have corresponding code files/classes?
- Are there important modules in code not recorded in whiteboard?
2. **Edge Accuracy**
- Do whiteboard edges reflect real import/call relationships?
- Are there dependencies in code not marked in whiteboard?
3. **Group Correctness**
- Is whiteboard grouping consistent with directory structure?
- Are there abnormal cross-group dependencies?
## Output Format
### 🔴 Severe Inconsistencies (Must Fix)
| Type | Whiteboard | Code | Suggestion |
|:-----|:-----------|:-----|:-----------|
| Missing node | - | UserService.py | Add to whiteboard |
| Wrong edge | A→B | A doesn't call B | Remove edge |
### 🟡 Minor Inconsistencies (Recommend Fix)
| Type | Whiteboard | Code | Suggestion |
|:-----|:-----------|:-----|:-----------|
| Naming inconsistency | user_service | UserService | Unify naming |
### 🟢 Good Consistency
- Node coverage: {X}%
- Edge accuracy: {Y}%
### 📋 Fix Suggestions
1. {specific fix step}
2. {specific fix step}
```
## Automation Script (Optional)
```python
#!/usr/bin/env python3
"""
canvas_sync_check.py - Whiteboard and code consistency check script
Usage: python canvas_sync_check.py project.canvas /path/to/project
"""
import json
import ast
import os
from pathlib import Path
def load_canvas(canvas_path):
with open(canvas_path) as f:
return json.load(f)
def extract_imports(py_file):
"""Extract import relationships from Python file"""
with open(py_file) as f:
tree = ast.parse(f.read())
imports = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
imports.append(alias.name)
elif isinstance(node, ast.ImportFrom):
if node.module:
imports.append(node.module)
return imports
def check_consistency(canvas, project_path):
"""Compare whiteboard nodes with actual files"""
canvas_nodes = {n['text'].split('\n')[0].strip('# ')
for n in canvas.get('nodes', [])}
actual_files = set()
for py_file in Path(project_path).rglob('*.py'):
actual_files.add(py_file.stem)
missing_in_canvas = actual_files - canvas_nodes
missing_in_code = canvas_nodes - actual_files
return {
'missing_in_canvas': missing_in_canvas,
'missing_in_code': missing_in_code,
'coverage': len(canvas_nodes & actual_files) / len(actual_files) * 100
}
if __name__ == '__main__':
import sys
if len(sys.argv) != 3:
print("Usage: python canvas_sync_check.py <canvas_file> <project_path>")
sys.exit(1)
canvas = load_canvas(sys.argv[1])
result = check_consistency(canvas, sys.argv[2])
print(f"Coverage: {result['coverage']:.1f}%")
if result['missing_in_canvas']:
print(f"Missing in whiteboard: {result['missing_in_canvas']}")
if result['missing_in_code']:
print(f"Missing in code: {result['missing_in_code']}")
```
## CI/CD Integration
```yaml
# .github/workflows/canvas-check.yml
name: Canvas Sync Check
on:
pull_request:
paths:
- '**.py'
- '**.canvas'
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Check canvas consistency
run: python scripts/canvas_sync_check.py docs/architecture.canvas src/
```
+31
View File
@@ -0,0 +1,31 @@
🚀 Canvas-Driven Development Method - Complete Workflow
1. Understand Core Philosophy: Canvas whiteboard as single source of truth, code is its serialized form; graphical language superior to text description; humans responsible for architecture design, AI responsible for code implementation
/
2. Prepare Tool Environment: Install Obsidian (free open-source whiteboard tool); Configure AI assistant (Claude/GPT-4, must support reading Canvas JSON format); Prepare target project codebase
/
3. Generate Initial Architecture Whiteboard: Provide project code path to AI; Use architecture analysis prompt to have AI scan project structure; AI automatically generates .canvas file containing module nodes and dependency connections
/
4. Open .canvas File in Obsidian: Import generated architecture whiteboard; Check auto-identified modules, files, API call relationships; Verify key dependency connections are accurate
/
5. Manually Optimize Whiteboard Architecture: Drag and adjust module positions for clear layout; Add implicit dependency connections AI missed; Add annotation nodes to mark key design decisions; Remove redundant or incorrect connections
/
6. Establish Code-Whiteboard Sync Mechanism: [Assumption: automation tools exist] Configure code change monitoring script; Set whiteboard auto-update rules (new file → new node, new import → new connection); Or manual maintenance: update corresponding whiteboard area after each code change
/
7. Use Whiteboard to Drive AI Programming (New Feature Development): Draw new module boxes and expected call relationships on whiteboard; Export whiteboard JSON and send to AI; Instruction: "Implement concrete code according to this architecture diagram"; AI generates files and function calls based on node names and connection directions
/
8. Use Whiteboard to Drive Code Refactoring (Architecture Adjustment): Delete/reconnect dependency lines between modules on whiteboard; Mark large modules to be split (e.g., payment_service split into payment_processor and payment_validator); Send modified whiteboard to AI: "Refactor code according to new architecture, list files to modify"
/
9. Use Whiteboard for Code Review: View whiteboard global architecture before review; Identify abnormal connections (e.g., frontend directly connecting to database, circular dependencies); Mark problem points on whiteboard; During discussion, point to whiteboard: "This call chain shouldn't exist"
/
10. Use Whiteboard to Accelerate Team Collaboration: Newcomers first view whiteboard for 1 minute to understand the big picture; Draw change scope on whiteboard during requirement review; Project whiteboard during technical planning meetings instead of code; Convert whiteboard annotations to development tasks after meeting
/
11. Maintain Whiteboard-Code Consistency: Check if whiteboard needs updating before each PR/MR merge; Periodically run auto-validation script: compare whiteboard JSON with actual code dependencies; When inconsistencies found, prioritize fixing whiteboard (because whiteboard is source of truth)
/
12. Extended Use Cases: Auto-generate whiteboard when taking over legacy projects for quick understanding; Mark hot paths on whiteboard during performance optimization; Check sensitive data flow on whiteboard during security audits; Draw service call topology on whiteboard during API design
/
13. [Gap Clarification] Specify your project type to optimize workflow: A) Monolith (single process, multiple modules) B) Microservices architecture (multiple services, RPC communication) C) Frontend-backend separation (frontend framework + backend API)? Default assumption A to continue
/
14. [Gap Clarification] Choose whiteboard granularity level: A) File level (each code file as one node) B) Class/function level (each class as one node) C) Service level (only show large modules)? Recommended: A for beginners, C for complex projects
/
15. Continuously Iterate Workflow: Weekly review if whiteboard reflects real architecture; Collect team feedback to optimize node naming and layout rules; Explore whiteboard integration with CI/CD (e.g., PR triggers whiteboard diff check); Share best practice cases to team knowledge base