docs(i18n): add English translations for 8 missing documents
Translated files: - AI Swarm Collaboration (overview + detailed technical doc) - Lessons Learned the Hard Way - OpenCode CLI Configuration - Four Phases x Twelve Principles Methodology - Canvas Whiteboard-Driven Development - Polymarket Link Format Specification - Polymarket Arbitrage Complete Guide Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
This commit is contained in:
parent
17d07f996a
commit
e30d300c19
|
|
@ -0,0 +1,29 @@
|
|||
# AI Swarm Collaboration
|
||||
|
||||
> Multi AI Agent collaboration system based on tmux
|
||||
|
||||
## Core Concept
|
||||
|
||||
Traditional mode: Human ←→ AI₁, Human ←→ AI₂, Human ←→ AI₃ (Human is the bottleneck)
|
||||
|
||||
Swarm mode: **Human → AI₁ ←→ AI₂ ←→ AI₃** (AI autonomous collaboration)
|
||||
|
||||
## Capability Matrix
|
||||
|
||||
| Capability | Implementation | Effect |
|
||||
|:---|:---|:---|
|
||||
| 🔍 Perception | `capture-pane` | Read any terminal content |
|
||||
| 🎮 Control | `send-keys` | Send keystrokes to any terminal |
|
||||
| 🤝 Coordination | Shared state files | Task synchronization and distribution |
|
||||
|
||||
## Core Breakthrough
|
||||
|
||||
AI is no longer isolated, but a cluster that can perceive, communicate, and control each other.
|
||||
|
||||
## Detailed Documentation
|
||||
|
||||
👉 [Deep Dive into AI Swarm Collaboration](../02-methodology/AI Swarm Collaboration - tmux Multi-Agent System.md)
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [tmux Shortcut Cheatsheet](../02-methodology/tmux Shortcut Cheatsheet.md)
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# Lessons Learned the Hard Way
|
||||
|
||||
## Before Execution
|
||||
|
||||
> About the lesson of reinventing the wheel only to discover better open-source solutions exist
|
||||
|
||||
10 parts development, 7 parts research. Before development, you MUST MUST MUST first gather all necessary materials and have thorough discussions with AI to align understanding. Always keep in mind the primary and secondary exploration dimensions: What is it? Why? How to do it? Is it the most suitable/excellent solution? Tool: Perplexity
|
||||
|
|
@ -0,0 +1,187 @@
|
|||
# OpenCode CLI Configuration
|
||||
|
||||
> Free AI programming assistant, supporting 75+ models, no credit card required
|
||||
|
||||
OpenCode is an open-source AI programming agent that supports terminal, desktop applications, and IDE extensions. Free models can be used without an account.
|
||||
|
||||
Official website: [opencode.ai](https://opencode.ai/)
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
# One-click installation (recommended)
|
||||
curl -fsSL https://opencode.ai/install | bash
|
||||
|
||||
# Or use npm
|
||||
npm install -g opencode-ai
|
||||
|
||||
# Or use Homebrew (macOS/Linux)
|
||||
brew install anomalyco/tap/opencode
|
||||
|
||||
# Windows - Scoop
|
||||
scoop bucket add extras && scoop install extras/opencode
|
||||
|
||||
# Windows - Chocolatey
|
||||
choco install opencode
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Free Model Configuration
|
||||
|
||||
OpenCode supports multiple free model providers that can be used without payment.
|
||||
|
||||
### Option 1: Z.AI (Recommended, GLM-4.7)
|
||||
|
||||
1. Visit [Z.AI API Console](https://z.ai/manage-apikey/apikey-list) to register and create an API Key
|
||||
2. Run the `/connect` command, search for **Z.AI**
|
||||
3. Enter your API Key
|
||||
4. Run `/models` and select **GLM-4.7**
|
||||
|
||||
```bash
|
||||
opencode
|
||||
# After entering, type
|
||||
/connect
|
||||
# Select Z.AI, enter API Key
|
||||
/models
|
||||
# Select GLM-4.7
|
||||
```
|
||||
|
||||
### Option 2: MiniMax (M2.1)
|
||||
|
||||
1. Visit [MiniMax API Console](https://platform.minimax.io/login) to register and create an API Key
|
||||
2. Run `/connect`, search for **MiniMax**
|
||||
3. Enter your API Key
|
||||
4. Run `/models` and select **M2.1**
|
||||
|
||||
### Option 3: Hugging Face (Multiple Free Models)
|
||||
|
||||
1. Visit [Hugging Face Settings](https://huggingface.co/settings/tokens/new?ownUserPermissions=inference.serverless.write&tokenType=fineGrained) to create a Token
|
||||
2. Run `/connect`, search for **Hugging Face**
|
||||
3. Enter your Token
|
||||
4. Run `/models` and select **Kimi-K2-Instruct** or **GLM-4.6**
|
||||
|
||||
### Option 4: Local Models (Ollama)
|
||||
|
||||
```bash
|
||||
# Install Ollama
|
||||
curl -fsSL https://ollama.com/install.sh | sh
|
||||
|
||||
# Pull a model
|
||||
ollama pull llama2
|
||||
```
|
||||
|
||||
Configure in `opencode.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"provider": {
|
||||
"ollama": {
|
||||
"npm": "@ai-sdk/openai-compatible",
|
||||
"name": "Ollama (local)",
|
||||
"options": {
|
||||
"baseURL": "http://localhost:11434/v1"
|
||||
},
|
||||
"models": {
|
||||
"llama2": {
|
||||
"name": "Llama 2"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Core Commands
|
||||
|
||||
| Command | Function |
|
||||
|:---|:---|
|
||||
| `/models` | Switch models |
|
||||
| `/connect` | Add API Key |
|
||||
| `/init` | Initialize project (generate AGENTS.md) |
|
||||
| `/undo` | Undo last modification |
|
||||
| `/redo` | Redo |
|
||||
| `/share` | Share conversation link |
|
||||
| `Tab` | Toggle Plan mode (plan only, no execution) |
|
||||
|
||||
---
|
||||
|
||||
## Let AI Handle All Configuration Tasks
|
||||
|
||||
The core philosophy of OpenCode: **Delegate all configuration tasks to AI**.
|
||||
|
||||
### Example: Install MCP Server
|
||||
|
||||
```
|
||||
Help me install the filesystem MCP server and configure it for opencode
|
||||
```
|
||||
|
||||
### Example: Deploy GitHub Open Source Project
|
||||
|
||||
```
|
||||
Clone the https://github.com/xxx/yyy project, read the README, and help me complete all dependency installation and environment configuration
|
||||
```
|
||||
|
||||
### Example: Configure Skills
|
||||
|
||||
```
|
||||
Read the project structure and create an appropriate AGENTS.md rules file for this project
|
||||
```
|
||||
|
||||
### Example: Configure Environment Variables
|
||||
|
||||
```
|
||||
Check what environment variables the project needs, help me create a .env file template and explain the purpose of each variable
|
||||
```
|
||||
|
||||
### Example: Install Dependencies
|
||||
|
||||
```
|
||||
Analyze package.json / requirements.txt, install all dependencies, and resolve version conflicts
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Recommended Workflow
|
||||
|
||||
1. **Enter project directory**
|
||||
```bash
|
||||
cd /path/to/project
|
||||
opencode
|
||||
```
|
||||
|
||||
2. **Initialize project**
|
||||
```
|
||||
/init
|
||||
```
|
||||
|
||||
3. **Switch to free model**
|
||||
```
|
||||
/models
|
||||
# Select GLM-4.7 or MiniMax M2.1
|
||||
```
|
||||
|
||||
4. **Start working**
|
||||
- First use `Tab` to switch to Plan mode, let AI plan
|
||||
- Confirm the plan before letting AI execute
|
||||
|
||||
---
|
||||
|
||||
## Configuration File Locations
|
||||
|
||||
- Global config: `~/.config/opencode/opencode.json`
|
||||
- Project config: `./opencode.json` (project root)
|
||||
- Auth info: `~/.local/share/opencode/auth.json`
|
||||
|
||||
---
|
||||
|
||||
## Related Resources
|
||||
|
||||
- [OpenCode Official Documentation](https://opencode.ai/docs/)
|
||||
- [GitHub Repository](https://github.com/opencode-ai/opencode)
|
||||
- [Models.dev - Model Directory](https://models.dev)
|
||||
|
|
@ -0,0 +1,694 @@
|
|||
# AI Swarm Collaboration Technical Documentation
|
||||
|
||||
> Design and implementation of multi AI Agent collaboration system based on tmux
|
||||
|
||||
---
|
||||
|
||||
## Table of Contents
|
||||
|
||||
1. [Core Concept](#1-core-concept)
|
||||
2. [Technical Principles](#2-technical-principles)
|
||||
3. [Command Reference](#3-command-reference)
|
||||
4. [Collaboration Protocol](#4-collaboration-protocol)
|
||||
5. [Architecture Patterns](#5-architecture-patterns)
|
||||
6. [Practical Cases](#6-practical-cases)
|
||||
7. [Prompt Templates](#7-prompt-templates)
|
||||
8. [Best Practices](#8-best-practices)
|
||||
9. [Risks and Limitations](#9-risks-and-limitations)
|
||||
10. [Extension Directions](#10-extension-directions)
|
||||
|
||||
---
|
||||
|
||||
## 1. Core Concept
|
||||
|
||||
### 1.1 Problem Background
|
||||
|
||||
Limitations of traditional AI programming assistants:
|
||||
- Single session, unable to perceive other tasks
|
||||
- Requires manual intervention when waiting/confirming
|
||||
- Unable to coordinate during multi-task parallelism
|
||||
- Repetitive work, resource waste
|
||||
|
||||
### 1.2 Solution
|
||||
|
||||
Leveraging tmux's terminal multiplexing capabilities to give AI:
|
||||
|
||||
| Capability | Implementation | Effect |
|
||||
|:---|:---|:---|
|
||||
| **Perception** | `capture-pane` | Read any terminal content |
|
||||
| **Control** | `send-keys` | Send keystrokes to any terminal |
|
||||
| **Coordination** | Shared state files | Task synchronization and distribution |
|
||||
|
||||
### 1.3 Core Insight
|
||||
|
||||
```
|
||||
Traditional mode: Human ←→ AI₁, Human ←→ AI₂, Human ←→ AI₃ (Human is the bottleneck)
|
||||
|
||||
Swarm mode: Human → AI₁ ←→ AI₂ ←→ AI₃ (AI autonomous collaboration)
|
||||
```
|
||||
|
||||
**Key Breakthrough**: AI is no longer isolated, but a cluster that can perceive, communicate, and control each other.
|
||||
|
||||
---
|
||||
|
||||
## 2. Technical Principles
|
||||
|
||||
### 2.1 tmux Architecture
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────┐
|
||||
│ tmux server │
|
||||
├─────────────────────────────────────────────┤
|
||||
│ Session 0 │
|
||||
│ ├── Window 0:1 [AI-1] ◄──┐ │
|
||||
│ ├── Window 0:2 [AI-2] ◄──┼── Mutually │
|
||||
│ ├── Window 0:3 [AI-3] ◄──┤ visible/ │
|
||||
│ └── Window 0:4 [AI-4] ◄──┘ controllable │
|
||||
└─────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### 2.2 Data Flow
|
||||
|
||||
```
|
||||
┌─────────┐ capture-pane ┌─────────┐
|
||||
│ AI-1 │ ◄───────────────│ AI-4 │
|
||||
│ (exec) │ │ (monitor)│
|
||||
└─────────┘ send-keys └─────────┘
|
||||
▲ ───────────────► │
|
||||
│ │
|
||||
└───────── Control flow ────┘
|
||||
```
|
||||
|
||||
### 2.3 Communication Mechanisms
|
||||
|
||||
| Mechanism | Direction | Latency | Use Case |
|
||||
|:---|:---|:---|:---|
|
||||
| `capture-pane` | Read | Instant | Get terminal output |
|
||||
| `send-keys` | Write | Instant | Send commands/keys |
|
||||
| Shared files | Bidirectional | File IO | State persistence |
|
||||
|
||||
---
|
||||
|
||||
## 3. Command Reference
|
||||
|
||||
### 3.1 Information Retrieval
|
||||
|
||||
```bash
|
||||
# List all sessions
|
||||
tmux list-sessions
|
||||
|
||||
# List all windows
|
||||
tmux list-windows -a
|
||||
|
||||
# List all panes
|
||||
tmux list-panes -a
|
||||
|
||||
# Get current window identifier
|
||||
echo $TMUX_PANE
|
||||
```
|
||||
|
||||
### 3.2 Content Reading
|
||||
|
||||
```bash
|
||||
# Read specified window content (last N lines)
|
||||
tmux capture-pane -t <session>:<window> -p -S -<N>
|
||||
|
||||
# Example: Read last 100 lines from session 0 window 1
|
||||
tmux capture-pane -t 0:1 -p -S -100
|
||||
|
||||
# Read and save to file
|
||||
tmux capture-pane -t 0:1 -p -S -500 > /tmp/window1.log
|
||||
|
||||
# Batch read all windows
|
||||
for w in $(tmux list-windows -a -F '#{session_name}:#{window_index}'); do
|
||||
echo "=== $w ==="
|
||||
tmux capture-pane -t "$w" -p -S -30
|
||||
done
|
||||
```
|
||||
|
||||
### 3.3 Sending Controls
|
||||
|
||||
```bash
|
||||
# Send text + Enter
|
||||
tmux send-keys -t 0:1 "ls -la" Enter
|
||||
|
||||
# Send confirmation
|
||||
tmux send-keys -t 0:1 "y" Enter
|
||||
|
||||
# Send special keys
|
||||
tmux send-keys -t 0:1 C-c # Ctrl+C
|
||||
tmux send-keys -t 0:1 C-d # Ctrl+D
|
||||
tmux send-keys -t 0:1 C-z # Ctrl+Z
|
||||
tmux send-keys -t 0:1 Escape # ESC
|
||||
tmux send-keys -t 0:1 Up # Up arrow
|
||||
tmux send-keys -t 0:1 Down # Down arrow
|
||||
tmux send-keys -t 0:1 Tab # Tab
|
||||
|
||||
# Combined operations
|
||||
tmux send-keys -t 0:1 C-c # First interrupt
|
||||
tmux send-keys -t 0:1 "cd /tmp" Enter # Then execute new command
|
||||
```
|
||||
|
||||
### 3.4 Window Management
|
||||
|
||||
```bash
|
||||
# Create new window
|
||||
tmux new-window -n "ai-worker"
|
||||
|
||||
# Create and execute command
|
||||
tmux new-window -n "ai-1" "kiro-cli chat"
|
||||
|
||||
# Close window
|
||||
tmux kill-window -t 0:1
|
||||
|
||||
# Rename window
|
||||
tmux rename-window -t 0:1 "monitor"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Collaboration Protocol
|
||||
|
||||
### 4.1 State Definition
|
||||
|
||||
```bash
|
||||
# State file location
|
||||
/tmp/ai_swarm/
|
||||
├── status.log # Global status log
|
||||
├── tasks.json # Task queue
|
||||
├── locks/ # Task locks
|
||||
│ ├── task_001.lock
|
||||
│ └── task_002.lock
|
||||
└── results/ # Results storage
|
||||
├── ai_1.json
|
||||
└── ai_2.json
|
||||
```
|
||||
|
||||
### 4.2 Status Format
|
||||
|
||||
```bash
|
||||
# Status log format
|
||||
[HH:MM:SS] [WindowID] [Status] Description
|
||||
|
||||
# Examples
|
||||
[08:15:30] [0:1] [START] Starting data-service code audit
|
||||
[08:16:45] [0:1] [DONE] Completed code audit, found 5 issues
|
||||
[08:16:50] [0:2] [WAIT] Waiting for 0:1 audit results
|
||||
[08:17:00] [0:2] [START] Starting to fix issues
|
||||
```
|
||||
|
||||
### 4.3 Collaboration Rules
|
||||
|
||||
| Rule | Description | Implementation |
|
||||
|:---|:---|:---|
|
||||
| **Check before action** | Scan other terminals before starting | `capture-pane` full scan |
|
||||
| **Avoid conflicts** | Same task only done once | Check locks directory |
|
||||
| **Proactive rescue** | Help when stuck detected | Detect `[y/n]` waiting |
|
||||
| **Status broadcast** | Notify other AIs after completion | Write to status.log |
|
||||
|
||||
### 4.4 Conflict Handling
|
||||
|
||||
```
|
||||
Scenario: AI-1 and AI-2 want to modify the same file simultaneously
|
||||
|
||||
Solution:
|
||||
1. Check lock before creating task
|
||||
2. Can only execute after acquiring lock
|
||||
3. Release lock after completion
|
||||
|
||||
# Acquire lock
|
||||
if [ ! -f /tmp/ai_swarm/locks/file_x.lock ]; then
|
||||
echo "$TMUX_PANE" > /tmp/ai_swarm/locks/file_x.lock
|
||||
# Execute task
|
||||
rm /tmp/ai_swarm/locks/file_x.lock
|
||||
fi
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Architecture Patterns
|
||||
|
||||
### 5.1 Peer-to-Peer (P2P)
|
||||
|
||||
```
|
||||
┌─────┐ ┌─────┐
|
||||
│ AI₁ │◄───►│ AI₂ │
|
||||
└──┬──┘ └──┬──┘
|
||||
│ │
|
||||
▼ ▼
|
||||
┌─────┐ ┌─────┐
|
||||
│ AI₃ │◄───►│ AI₄ │
|
||||
└─────┘ └─────┘
|
||||
|
||||
Features: All AIs are equal, mutually monitoring
|
||||
Suitable for: Simple tasks, no clear dependencies
|
||||
```
|
||||
|
||||
### 5.2 Master-Worker
|
||||
|
||||
```
|
||||
┌──────────┐
|
||||
│ AI-Master│
|
||||
│(Commander)│
|
||||
└────┬─────┘
|
||||
│ Distribute/Monitor
|
||||
┌────────┼────────┐
|
||||
▼ ▼ ▼
|
||||
┌──────┐ ┌──────┐ ┌──────┐
|
||||
│Worker│ │Worker│ │Worker│
|
||||
│ AI-1 │ │ AI-2 │ │ AI-3 │
|
||||
└──────┘ └──────┘ └──────┘
|
||||
|
||||
Features: One commander, multiple executors
|
||||
Suitable for: Complex projects, requires unified coordination
|
||||
```
|
||||
|
||||
### 5.3 Pipeline
|
||||
|
||||
```
|
||||
┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐
|
||||
│ AI₁ │───►│ AI₂ │───►│ AI₃ │───►│ AI₄ │
|
||||
│Analyze│ │Design│ │Implement│ │Test │
|
||||
└─────┘ └─────┘ └─────┘ └─────┘
|
||||
|
||||
Features: Sequential task flow
|
||||
Suitable for: Workflows with clear phases
|
||||
```
|
||||
|
||||
### 5.4 Hybrid
|
||||
|
||||
```
|
||||
┌──────────┐
|
||||
│ AI-Master│
|
||||
└────┬─────┘
|
||||
│
|
||||
┌───────────┼───────────┐
|
||||
▼ ▼ ▼
|
||||
┌──────┐ ┌──────┐ ┌──────┐
|
||||
│Analysis│ │Dev Team│ │Test │
|
||||
│ Team │ │ │ │ Team │
|
||||
├──────┤ ├──────┤ ├──────┤
|
||||
│AI-1 │ │AI-3 │ │AI-5 │
|
||||
│AI-2 │ │AI-4 │ │AI-6 │
|
||||
└──────┘ └──────┘ └──────┘
|
||||
|
||||
Features: Group collaboration + unified scheduling
|
||||
Suitable for: Large projects, multi-team parallelism
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Practical Cases
|
||||
|
||||
### 6.1 Case: Multi-Service Parallel Development
|
||||
|
||||
**Scenario**: Simultaneously develop data-service, trading-service, telegram-service
|
||||
|
||||
**Configuration**:
|
||||
```bash
|
||||
# Window allocation
|
||||
0:1 - AI-Master (Commander)
|
||||
0:2 - AI-Data (data-service)
|
||||
0:3 - AI-Trading (trading-service)
|
||||
0:4 - AI-Telegram (telegram-service)
|
||||
```
|
||||
|
||||
**Commander Prompt**:
|
||||
```
|
||||
You are the project commander, responsible for coordinating 3 development AIs.
|
||||
|
||||
Execute a scan every 2 minutes:
|
||||
for w in 2 3 4; do
|
||||
echo "=== Window 0:$w ==="
|
||||
tmux capture-pane -t "0:$w" -p -S -20
|
||||
done
|
||||
|
||||
When issues are detected:
|
||||
- Stuck waiting → send-keys to confirm
|
||||
- Error → analyze and provide suggestions
|
||||
- Completed → record and assign next task
|
||||
```
|
||||
|
||||
### 6.2 Case: Code Audit + Auto Fix
|
||||
|
||||
**Scenario**: AI-1 audits code, AI-2 fixes in real-time
|
||||
|
||||
**Flow**:
|
||||
```
|
||||
AI-1 (Audit):
|
||||
1. Scan code, output issue list
|
||||
2. Write to /tmp/ai_swarm/issues.log for each issue found
|
||||
|
||||
AI-2 (Fix):
|
||||
1. Monitor issues.log
|
||||
2. Read new issues
|
||||
3. Auto fix
|
||||
4. Mark as completed
|
||||
```
|
||||
|
||||
### 6.3 Case: 24/7 Watch
|
||||
|
||||
**Scenario**: AIs monitor each other, auto rescue
|
||||
|
||||
**Configuration**:
|
||||
```bash
|
||||
# Monitoring logic for each AI
|
||||
while true; do
|
||||
for w in $(tmux list-windows -a -F '#{window_index}'); do
|
||||
output=$(tmux capture-pane -t "0:$w" -p -S -5)
|
||||
|
||||
# Detect stuck
|
||||
if echo "$output" | grep -q "\[y/n\]"; then
|
||||
tmux send-keys -t "0:$w" "y" Enter
|
||||
echo "Helped window $w confirm"
|
||||
fi
|
||||
|
||||
# Detect errors
|
||||
if echo "$output" | grep -qi "error\|failed"; then
|
||||
echo "Window $w has errors, needs attention"
|
||||
fi
|
||||
done
|
||||
sleep 30
|
||||
done
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Prompt Templates
|
||||
|
||||
### 7.1 Basic Version (Worker)
|
||||
|
||||
```markdown
|
||||
## AI Swarm Collaboration Mode
|
||||
|
||||
You work in a tmux environment and can perceive and assist other terminals.
|
||||
|
||||
### Commands
|
||||
# Scan all terminals
|
||||
tmux list-windows -a
|
||||
|
||||
# Read terminal content
|
||||
tmux capture-pane -t <session>:<window> -p -S -100
|
||||
|
||||
### Behavior
|
||||
- Scan environment before starting tasks
|
||||
- Proactively coordinate when related tasks are found
|
||||
- Broadcast status after completion
|
||||
```
|
||||
|
||||
### 7.2 Complete Version (Worker)
|
||||
|
||||
```markdown
|
||||
## 🐝 AI Swarm Collaboration Protocol v2.0
|
||||
|
||||
You are a member of the tmux multi-terminal AI cluster.
|
||||
|
||||
### Perception Capabilities
|
||||
|
||||
# List all windows
|
||||
tmux list-windows -a
|
||||
|
||||
# Read specified window (last 100 lines)
|
||||
tmux capture-pane -t <session>:<window> -p -S -100
|
||||
|
||||
# Batch scan
|
||||
for w in $(tmux list-windows -a -F '#{session_name}:#{window_index}'); do
|
||||
echo "=== $w ===" && tmux capture-pane -t "$w" -p -S -20
|
||||
done
|
||||
|
||||
### Control Capabilities
|
||||
|
||||
# Send command
|
||||
tmux send-keys -t <window> "<command>" Enter
|
||||
|
||||
# Send confirmation
|
||||
tmux send-keys -t <window> "y" Enter
|
||||
|
||||
# Interrupt task
|
||||
tmux send-keys -t <window> C-c
|
||||
|
||||
### Collaboration Rules
|
||||
|
||||
1. **Proactive perception**: Scan other terminals before task starts
|
||||
2. **Avoid conflicts**: Don't repeat the same task
|
||||
3. **Proactive rescue**: Help when waiting/stuck is detected
|
||||
4. **Status broadcast**: Write to shared log after completion
|
||||
|
||||
### Status Sync
|
||||
|
||||
# Broadcast
|
||||
echo "[$(date +%H:%M:%S)] [$TMUX_PANE] [DONE] <description>" >> /tmp/ai_swarm/status.log
|
||||
|
||||
# Read
|
||||
tail -20 /tmp/ai_swarm/status.log
|
||||
|
||||
### Check Timing
|
||||
|
||||
- 🚦 Before task starts
|
||||
- ⏳ When waiting for dependencies
|
||||
- ✅ After task completion
|
||||
- ❌ When errors occur
|
||||
```
|
||||
|
||||
### 7.3 Commander Version (Master)
|
||||
|
||||
```markdown
|
||||
## 🎖️ AI Cluster Commander Protocol
|
||||
|
||||
You are the commander of the AI swarm, responsible for monitoring and coordinating all Worker AIs.
|
||||
|
||||
### Core Responsibilities
|
||||
|
||||
1. **Global monitoring**: Regularly scan all terminal states
|
||||
2. **Task assignment**: Assign tasks based on capabilities
|
||||
3. **Conflict resolution**: Coordinate when duplicate work is found
|
||||
4. **Fault rescue**: Intervene when stuck/errors are detected
|
||||
5. **Progress summary**: Summarize results from all terminals
|
||||
|
||||
### Monitoring Commands
|
||||
|
||||
# Global scan (execute every 2 minutes)
|
||||
echo "========== $(date) Status Scan =========="
|
||||
for w in $(tmux list-windows -a -F '#{session_name}:#{window_index}'); do
|
||||
echo "--- $w ---"
|
||||
tmux capture-pane -t "$w" -p -S -15
|
||||
done
|
||||
|
||||
### Intervention Commands
|
||||
|
||||
# Help confirm
|
||||
tmux send-keys -t <window> "y" Enter
|
||||
|
||||
# Interrupt erroneous task
|
||||
tmux send-keys -t <window> C-c
|
||||
|
||||
# Send new instruction
|
||||
tmux send-keys -t <window> "<instruction>" Enter
|
||||
|
||||
### Status Judgment
|
||||
|
||||
Intervene when these patterns are detected:
|
||||
- `[y/n]` `[Y/n]` `confirm` → Needs confirmation
|
||||
- `Error` `Failed` `Exception` → Error occurred
|
||||
- `Waiting` `Blocked` → Task blocked
|
||||
- No output for long time → May be dead
|
||||
|
||||
### Report Format
|
||||
|
||||
Output after each scan:
|
||||
| Window | Status | Current Task | Notes |
|
||||
|:---|:---|:---|:---|
|
||||
| 0:1 | ✅ Normal | Code audit | 80% progress |
|
||||
| 0:2 | ⏳ Waiting | Waiting confirm | Auto confirmed |
|
||||
| 0:3 | ❌ Error | Build failed | Needs attention |
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 8. Best Practices
|
||||
|
||||
### 8.1 Initialization Flow
|
||||
|
||||
```bash
|
||||
# 1. Create shared directory
|
||||
mkdir -p /tmp/ai_swarm/{locks,results}
|
||||
touch /tmp/ai_swarm/status.log
|
||||
|
||||
# 2. Start tmux session
|
||||
tmux new-session -d -s ai
|
||||
|
||||
# 3. Create multiple windows
|
||||
tmux new-window -t ai -n "master"
|
||||
tmux new-window -t ai -n "worker-1"
|
||||
tmux new-window -t ai -n "worker-2"
|
||||
tmux new-window -t ai -n "worker-3"
|
||||
|
||||
# 4. Start AI in each window
|
||||
tmux send-keys -t ai:master "kiro-cli chat" Enter
|
||||
tmux send-keys -t ai:worker-1 "kiro-cli chat" Enter
|
||||
# ...
|
||||
|
||||
# 5. Send swarm prompts
|
||||
```
|
||||
|
||||
### 8.2 Naming Conventions
|
||||
|
||||
```bash
|
||||
# Session naming
|
||||
ai # AI work session
|
||||
dev # Development session
|
||||
monitor # Monitoring session
|
||||
|
||||
# Window naming
|
||||
master # Commander
|
||||
worker-N # Worker nodes
|
||||
data # data-service dedicated
|
||||
trading # trading-service dedicated
|
||||
```
|
||||
|
||||
### 8.3 Log Standards
|
||||
|
||||
```bash
|
||||
# Status log
|
||||
[Time] [Window] [Status] Description
|
||||
|
||||
# Status types
|
||||
[START] - Task started
|
||||
[DONE] - Task completed
|
||||
[WAIT] - Waiting
|
||||
[ERROR] - Error occurred
|
||||
[HELP] - Help requested
|
||||
[SKIP] - Skipped (already being handled)
|
||||
```
|
||||
|
||||
### 8.4 Security Recommendations
|
||||
|
||||
1. **Don't auto-confirm dangerous operations**: rm -rf, DROP TABLE, etc.
|
||||
2. **Set operation whitelist**: Only allow specific commands
|
||||
3. **Keep operation logs**: Record all send-keys operations
|
||||
4. **Regular manual checks**: Don't go completely unattended
|
||||
|
||||
---
|
||||
|
||||
## 9. Risks and Limitations
|
||||
|
||||
### 9.1 Known Risks
|
||||
|
||||
| Risk | Description | Mitigation |
|
||||
|:---|:---|:---|
|
||||
| Misoperation | AI sends wrong commands | Set command whitelist |
|
||||
| Infinite loop | AIs trigger each other | Add cooldown time |
|
||||
| Resource contention | Simultaneous file modification | Use lock mechanism |
|
||||
| Information leak | Sensitive info read | Isolate sensitive sessions |
|
||||
|
||||
### 9.2 Technical Limitations
|
||||
|
||||
- tmux must be on the same server
|
||||
- Cannot collaborate across machines (requires SSH)
|
||||
- Terminal output has length limits
|
||||
- Cannot read password input (hidden characters)
|
||||
|
||||
### 9.3 Unsuitable Scenarios
|
||||
|
||||
- Operations requiring GUI
|
||||
- Operations involving sensitive credentials
|
||||
- Scenarios requiring real-time interaction
|
||||
- Cross-network distributed collaboration
|
||||
|
||||
---
|
||||
|
||||
## 10. Extension Directions
|
||||
|
||||
### 10.1 Cross-Machine Collaboration
|
||||
|
||||
```bash
|
||||
# Read remote tmux via SSH
|
||||
ssh user@remote "tmux capture-pane -t 0:1 -p"
|
||||
|
||||
# Send commands via SSH
|
||||
ssh user@remote "tmux send-keys -t 0:1 'ls' Enter"
|
||||
```
|
||||
|
||||
### 10.2 Web Monitoring Panel
|
||||
|
||||
```python
|
||||
# Simple status API
|
||||
from flask import Flask, jsonify
|
||||
import subprocess
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/status')
|
||||
def status():
|
||||
result = subprocess.run(
|
||||
['tmux', 'list-windows', '-a', '-F', '#{window_name}:#{window_activity}'],
|
||||
capture_output=True, text=True
|
||||
)
|
||||
return jsonify({'windows': result.stdout.split('\n')})
|
||||
```
|
||||
|
||||
### 10.3 Intelligent Scheduling
|
||||
|
||||
```python
|
||||
# Load-based task assignment
|
||||
def assign_task(task):
|
||||
windows = get_all_windows()
|
||||
|
||||
# Find the most idle window
|
||||
idle_window = min(windows, key=lambda w: w.activity_time)
|
||||
|
||||
# Assign task
|
||||
send_keys(idle_window, f"Process task: {task}")
|
||||
```
|
||||
|
||||
### 10.4 Integration with Other Systems
|
||||
|
||||
- **Slack/Discord**: Status notifications
|
||||
- **Prometheus**: Metrics monitoring
|
||||
- **Grafana**: Visualization panel
|
||||
- **GitHub Actions**: CI/CD triggers
|
||||
|
||||
---
|
||||
|
||||
## Appendix
|
||||
|
||||
### A. Quick Reference Card
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────────────────┐
|
||||
│ AI Swarm Command Cheatsheet │
|
||||
├─────────────────────────────────────────────────────┤
|
||||
│ List windows tmux list-windows -a │
|
||||
│ Read content tmux capture-pane -t 0:1 -p -S -100 │
|
||||
│ Send command tmux send-keys -t 0:1 "cmd" Enter │
|
||||
│ Send confirm tmux send-keys -t 0:1 "y" Enter │
|
||||
│ Interrupt tmux send-keys -t 0:1 C-c │
|
||||
│ New window tmux new-window -n "name" │
|
||||
└─────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### B. Troubleshooting
|
||||
|
||||
```bash
|
||||
# tmux doesn't exist
|
||||
which tmux || sudo apt install tmux
|
||||
|
||||
# Cannot connect to session
|
||||
tmux list-sessions # Check if session exists
|
||||
|
||||
# capture-pane no output
|
||||
tmux capture-pane -t 0:1 -p -S -1000 # Increase line count
|
||||
|
||||
# send-keys not working
|
||||
tmux display-message -t 0:1 -p '#{pane_mode}' # Check mode
|
||||
```
|
||||
|
||||
### C. References
|
||||
|
||||
- tmux official documentation: https://github.com/tmux/tmux/wiki
|
||||
- tmux command reference: `man tmux`
|
||||
|
||||
---
|
||||
|
||||
*Document version: v1.0*
|
||||
*Last updated: 2026-01-04*
|
||||
|
|
@ -0,0 +1,194 @@
|
|||
# 🚀 Canvas Whiteboard-Driven Development
|
||||
|
||||
## From Text to Graphics: A New Paradigm for Programming Collaboration
|
||||
|
||||
### 💡 Core Discovery
|
||||
|
||||
Traditional development flow:
|
||||
```
|
||||
Write code → Verbal communication → Mental architecture → Code out of control → Refactoring collapse
|
||||
```
|
||||
|
||||
**New Method**:
|
||||
```
|
||||
Code ⇄ Canvas Whiteboard ⇄ AI ⇄ Human
|
||||
↓
|
||||
Single Source of Truth
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🎯 What Does This Method Solve?
|
||||
|
||||
**Pain Point 1: AI can't understand your project structure**
|
||||
- ❌ Before: Repeatedly explaining "what this file does"
|
||||
- ✅ Now: AI directly reads the whiteboard, instantly understands the overall architecture
|
||||
|
||||
**Pain Point 2: Humans can't remember complex dependencies**
|
||||
- ❌ Before: Modify file A, forgot B depends on it, explodes
|
||||
- ✅ Now: Whiteboard connections are clear, impact at a glance
|
||||
|
||||
**Pain Point 3: Team collaboration relies on verbal communication**
|
||||
- ❌ Before: "How does the data flow?" "Uh...let me dig through the code"
|
||||
- ✅ Now: Point at the whiteboard, new members understand in 5 minutes
|
||||
|
||||
---
|
||||
|
||||
### 🔥 Workflow Demo
|
||||
|
||||
#### Step 1: Auto-update whiteboard while writing code
|
||||
|
||||
```python
|
||||
# You wrote a new file payment_service.py
|
||||
class PaymentService:
|
||||
def process(self):
|
||||
db.save() # ← AI detects database write
|
||||
stripe.charge() # ← AI detects external API call
|
||||
```
|
||||
|
||||
**Whiteboard auto-generates:**
|
||||
```
|
||||
[PaymentService] ──writes──> [Database]
|
||||
│
|
||||
└──calls──> [Stripe API]
|
||||
```
|
||||
|
||||
#### Step 2: Humans and AI co-edit the whiteboard
|
||||
|
||||
**You drag on the whiteboard**:
|
||||
- Connect `UserService` to `PaymentService`
|
||||
- AI immediately understands: "Oh, user module will call payment"
|
||||
|
||||
**AI generates code after understanding intent**:
|
||||
```python
|
||||
# user_service.py
|
||||
from payment_service import PaymentService
|
||||
|
||||
def create_order(user):
|
||||
payment = PaymentService()
|
||||
payment.process(user.card) # ← AI auto-adds this line
|
||||
```
|
||||
|
||||
#### Step 3: Whiteboard becomes the development hub
|
||||
|
||||
| Operation | Traditional Way | Canvas Way |
|
||||
|------|----------|------------|
|
||||
| Ask AI to refactor | "Extract payment logic" | Drag out new node on whiteboard, AI auto-splits code |
|
||||
| Code Review | Read code line by line | Look at whiteboard connections: "Is this call chain reasonable?" |
|
||||
| Requirement change | Change code everywhere | Delete a line on whiteboard, AI syncs deletion of all related calls |
|
||||
|
||||
---
|
||||
|
||||
### 🌟 Key Innovations
|
||||
|
||||
#### 1. Graphics are first-class citizens, code is a derivative
|
||||
|
||||
Traditional thinking: Code → Documentation (outdated) → Architecture diagram (more outdated)
|
||||
|
||||
New thinking: **Canvas whiteboard = Single source of truth**, code is just its serialized form
|
||||
|
||||
#### 2. Shared workspace for humans and AI
|
||||
|
||||
- Humans: Good at high-level design, drag modules on whiteboard
|
||||
- AI: Good at detail implementation, generates code based on whiteboard connections
|
||||
- Collaboration: **Both edit the same whiteboard**, not passing text back and forth
|
||||
|
||||
#### 3. Real-time bidirectional sync
|
||||
|
||||
```
|
||||
Code changes ──auto scan──> Update whiteboard
|
||||
Whiteboard edits ──AI parse──> Generate/modify code
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 🎨 Use Cases
|
||||
|
||||
#### Scenario 1: Assigning tasks to AI
|
||||
|
||||
Traditional:
|
||||
> "Help me write a user registration feature, connect to database, send email, log"
|
||||
|
||||
Canvas way:
|
||||
1. Draw 3 boxes on whiteboard: `RegisterAPI` → `Database` / `EmailService` / `Logger`
|
||||
2. Tell AI: "Implement according to this diagram"
|
||||
3. AI writes all files and call relationships correctly at once
|
||||
|
||||
#### Scenario 2: Code Review
|
||||
|
||||
Traditional: Read code line by line, get dizzy
|
||||
|
||||
Canvas way:
|
||||
1. Look at whiteboard: "Huh, why does frontend directly connect to database?"
|
||||
2. Drag nodes to adjust architecture
|
||||
3. AI auto-refactors code
|
||||
|
||||
#### Scenario 3: Taking over someone else's project
|
||||
|
||||
Traditional: Read code for 3 days still don't understand
|
||||
|
||||
Canvas way:
|
||||
1. Run auto-generation tool → Get architecture whiteboard in 1 minute
|
||||
2. Click on modules of interest to see details
|
||||
3. Draw the parts to change directly on whiteboard, AI helps locate code position
|
||||
|
||||
---
|
||||
|
||||
### 🚀 Get Started Now
|
||||
|
||||
#### Tool Chain
|
||||
|
||||
- **Whiteboard**: Obsidian Canvas (free and open source)
|
||||
- **Auto-generation**: Prompt-driven (see below)
|
||||
- **AI collaboration**: Claude / GPT-4 (can read Canvas JSON)
|
||||
|
||||
#### 5-minute Experience Flow
|
||||
|
||||
```bash
|
||||
# 1. Run auto-analysis on your project
|
||||
[Use prompt to have AI generate architecture whiteboard]
|
||||
|
||||
# 2. Open the generated .canvas file with Obsidian
|
||||
|
||||
# 3. Try dragging modules or adding connections
|
||||
|
||||
# 4. Send modified whiteboard to AI: "Refactor code according to this new architecture"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 💬 Is This the Future of Programming?
|
||||
|
||||
I believe so, reasons:
|
||||
|
||||
1. **Graphics are the native language of human brain**
|
||||
- You can instantly understand a subway map
|
||||
- But can't understand equivalent transfer text instructions
|
||||
|
||||
2. **AI is already smart enough to "understand" diagrams**
|
||||
- Canvas is structured graphical data
|
||||
- AI parsing JSON is 10x more accurate than parsing your natural language description
|
||||
|
||||
3. **Code generation is commoditized, architecture design is the scarce skill**
|
||||
- Future programmer's job: Design whiteboard architecture
|
||||
- AI's job: Translate whiteboard into code
|
||||
|
||||
---
|
||||
|
||||
### 📌 Golden Quotes
|
||||
|
||||
> "When code becomes boxes on a whiteboard, programming transforms from typing to building blocks."
|
||||
|
||||
> "The best documentation isn't Markdown, it's architecture diagrams that can directly drive AI work."
|
||||
|
||||
> "AI understanding your diagram is ten thousand times easier than understanding your words."
|
||||
|
||||
---
|
||||
|
||||
### 🔗 Related Resources
|
||||
|
||||
- [Canvas Whiteboard Generation Prompt](https://docs.google.com/spreadsheets/d/1Ifk_dLF25ULSxcfGem1hXzJsi7_RBUNAki8SBCuvkJA/edit?gid=1777853069#gid=1777853069&range=A1) - Complete prompt for auto-generating architecture whiteboard
|
||||
- [Whiteboard-Driven Development System Prompt](../../prompts/01-system-prompts/AGENTS.md/12/AGENTS.md) - AGENTS.md adapted for Canvas whiteboard-driven development
|
||||
- [Obsidian Canvas Official Documentation](https://obsidian.md/canvas)
|
||||
- [Glue Coding](../00-fundamentals/Glue Coding.md) - Copy rather than write, connect rather than create
|
||||
- [General Project Architecture Template](../00-fundamentals/General Project Architecture Template.md) - Standardized directory structure
|
||||
|
|
@ -0,0 +1,166 @@
|
|||
# 12Factor.me - Four Phases × Twelve Principles Methodology
|
||||
|
||||
Source: https://www.12factor.me/
|
||||
|
||||
> Methodology for 10x engineering efficiency improvement in the AI collaboration era
|
||||
|
||||
---
|
||||
|
||||
## Phase 1: Preparation
|
||||
|
||||
*Establish clear information architecture and context environment*
|
||||
|
||||
### 1. Single Source of Truth
|
||||
|
||||
**Core Concept**: Scattered information leads to context confusion, easily causing misjudgment by both humans and machines.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Centralize all requirements, designs, and context in a unified document center (e.g., Notion / Confluence / GitHub Wiki).
|
||||
- When collaborating with AI, directly reference this "source of truth" rather than randomly copying and pasting information.
|
||||
|
||||
**Anti-patterns**:
|
||||
- Team members each maintain different versions of documents, leading to inconsistent AI responses and suggestions.
|
||||
|
||||
### 2. Prompt First
|
||||
|
||||
**Core Concept**: Treat prompts as the new generation of design documents.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Before starting a task, prioritize writing prompts to clarify inputs, outputs, styles, and constraints.
|
||||
- Reuse validated and optimized prompt templates within the team.
|
||||
|
||||
**Anti-patterns**:
|
||||
- Directly asking AI to write code without planning, leading to wrong direction and unnecessary rework.
|
||||
|
||||
### 3. Context Hygiene
|
||||
|
||||
**Core Concept**: Clean context enables more precise AI responses.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Start a new session for each new task to avoid old content interference
|
||||
- Regularly summarize the current situation in one sentence to help AI "align context"
|
||||
|
||||
**Anti-patterns**:
|
||||
- Mixing conversations from three days ago with today's tasks
|
||||
|
||||
---
|
||||
|
||||
## Phase 2: Execution
|
||||
|
||||
*Efficiently collaborate to complete specific tasks*
|
||||
|
||||
### 4. Human-in-the-Loop
|
||||
|
||||
**Core Concept**: AI produces fast, but only humans can grasp direction and business judgment.
|
||||
|
||||
**Recommended Practices**:
|
||||
- AI provides initial drafts, humans responsible for key decisions and risk control
|
||||
- For important features, perform logic verification before merging code
|
||||
|
||||
**Anti-patterns**:
|
||||
- Accepting AI output wholesale without any review
|
||||
|
||||
### 5. Chunked Work
|
||||
|
||||
**Core Concept**: Break large tasks into small chunks, easier to iterate and correct.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Keep tasks completable within 10-30 minutes
|
||||
- Verify results immediately after each chunk
|
||||
|
||||
**Anti-patterns**:
|
||||
- Having AI write 5000 lines at once, impossible to debug
|
||||
|
||||
### 6. Parallel Flow
|
||||
|
||||
**Core Concept**: While AI works, humans do low-context-switch side tasks to maintain rhythm.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Prepare a "side task list" including document organization, small fixes, code reviews, etc.
|
||||
- While waiting for AI, don't take on high cognitive load new tasks to avoid excessive switching costs
|
||||
|
||||
**Anti-patterns**:
|
||||
- Scrolling social media while waiting for AI, breaking the rhythm
|
||||
|
||||
---
|
||||
|
||||
## Phase 3: Collaboration
|
||||
|
||||
*Manage cognitive load and workflow during collaboration*
|
||||
|
||||
### 7. Cognitive Load Budget
|
||||
|
||||
**Core Concept**: Human attention is a scarce resource.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Set daily time limits for AI collaboration
|
||||
- Schedule deep review tasks during peak mental periods
|
||||
|
||||
**Anti-patterns**:
|
||||
- Working with AI all day, completely exhausted by evening
|
||||
|
||||
### 8. Flow Protection
|
||||
|
||||
**Core Concept**: Once high-focus flow is interrupted, recovery cost is extremely high.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Set focus periods (e.g., 90 minutes), block notifications and interruptions
|
||||
- AI interactions also done in batches during focus flow, not scattered triggers
|
||||
|
||||
**Anti-patterns**:
|
||||
- Writing code while replying to messages while watching AI output, cliff-like efficiency drop
|
||||
|
||||
### 9. Reproducible Sessions
|
||||
|
||||
**Core Concept**: Collaboration process must be traceable for continuous optimization.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Save prompts, AI versions, change reasons to codebase or knowledge base
|
||||
- When bugs occur, can replay the generation process
|
||||
|
||||
**Anti-patterns**:
|
||||
- No record of AI generation history, can't trace causes when errors occur
|
||||
|
||||
---
|
||||
|
||||
## Phase 4: Iteration
|
||||
|
||||
*Continuous learning and improving collaboration patterns*
|
||||
|
||||
### 10. Rest & Reflection
|
||||
|
||||
**Core Concept**: Retrospect after sprints to run faster.
|
||||
|
||||
**Recommended Practices**:
|
||||
- After sprint ends, spend 5 minutes reflecting on AI output vs expectations
|
||||
- Update prompt templates, accumulate "pitfall records"
|
||||
|
||||
**Anti-patterns**:
|
||||
- Continuous sprints, accumulating errors without summary
|
||||
|
||||
### 11. Skill Parity
|
||||
|
||||
**Core Concept**: AI is a magnifier, amplifying abilities and also weaknesses.
|
||||
|
||||
**Recommended Practices**:
|
||||
- Continuously learn domain knowledge and code review skills
|
||||
- Maintain independent judgment on AI output
|
||||
|
||||
**Anti-patterns**:
|
||||
- Completely relying on AI, losing manual skills and technical insight
|
||||
|
||||
### 12. Culture of Curiosity
|
||||
|
||||
**Core Concept**: Curiosity drives exploration, avoiding "blind trust in AI".
|
||||
|
||||
**Recommended Practices**:
|
||||
- When facing AI answers, first ask "why", then ask "can it be better"
|
||||
- Team shares AI usage experiences and improvement ideas
|
||||
|
||||
**Anti-patterns**:
|
||||
- Accepting AI solutions without question
|
||||
|
||||
---
|
||||
|
||||
*Generated from [12Factor.me](https://12factor.me)*
|
||||
*License: MIT*
|
||||
|
|
@ -0,0 +1,99 @@
|
|||
# Polymarket Link Format Specification
|
||||
|
||||
## Problem Description
|
||||
|
||||
Generated Polymarket links return "Oops...we didn't forecast this" error page, even when HTTP status code is 200.
|
||||
|
||||
## Root Cause
|
||||
|
||||
Polymarket API returns two different slugs:
|
||||
|
||||
| Field | Name | Usage |
|
||||
|------|------|------|
|
||||
| `slug` | Market Slug | Market identifier, **cannot be used for URL** |
|
||||
| `events[0].slug` | Event Slug | Event identifier, **must be used for URL** |
|
||||
|
||||
### Example Comparison
|
||||
|
||||
```
|
||||
Market: "Lighter market cap (FDV) >$1B one day after launch?"
|
||||
|
||||
API returns:
|
||||
slug: "lighter-market-cap-fdv-1b-one-day-after-launch" ❌ Wrong
|
||||
events[0].slug: "lighter-market-cap-fdv-one-day-after-launch" ✅ Correct
|
||||
|
||||
Wrong link: https://polymarket.com/event/lighter-market-cap-fdv-1b-one-day-after-launch
|
||||
Correct link: https://polymarket.com/event/lighter-market-cap-fdv-one-day-after-launch
|
||||
```
|
||||
|
||||
Note the difference: market slug contains `-1b-`, event slug doesn't.
|
||||
|
||||
## Why HTTP 200 But Page Errors?
|
||||
|
||||
Polymarket frontend is an SPA (Single Page Application):
|
||||
- All `/event/*` paths return HTTP 200 (returns HTML shell)
|
||||
- Frontend JS loads and then requests data
|
||||
- If slug is invalid, frontend displays "Oops" error
|
||||
|
||||
**Conclusion: HTTP status code cannot validate link validity.**
|
||||
|
||||
## Correct Link Generation Method
|
||||
|
||||
```javascript
|
||||
// ✅ Correct
|
||||
const getLink = (market) => {
|
||||
const events = market.events || [];
|
||||
const slug = events[0]?.slug || market.slug; // Prioritize event slug
|
||||
return `https://polymarket.com/event/${slug}`;
|
||||
};
|
||||
|
||||
// ❌ Wrong
|
||||
const getLink = (market) => {
|
||||
return `https://polymarket.com/event/${market.slug}`;
|
||||
};
|
||||
```
|
||||
|
||||
## API Response Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"question": "Lighter market cap (FDV) >$1B one day after launch?",
|
||||
"slug": "lighter-market-cap-fdv-1b-one-day-after-launch",
|
||||
"events": [
|
||||
{
|
||||
"slug": "lighter-market-cap-fdv-one-day-after-launch",
|
||||
"title": "Lighter Market Cap (FDV) One Day After Launch"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Validation Methods
|
||||
|
||||
Can't just check HTTP status code, need to:
|
||||
|
||||
```bash
|
||||
# Method 1: Check if page content contains error
|
||||
curl -s "https://polymarket.com/event/xxx" | grep -q "didn't forecast" && echo "Invalid"
|
||||
|
||||
# Method 2: Compare slug returned by API
|
||||
curl -s "https://gamma-api.polymarket.com/markets?slug=xxx" | jq '.events[0].slug'
|
||||
```
|
||||
|
||||
## Affected Files
|
||||
|
||||
When fixing, check link generation logic in these files:
|
||||
|
||||
- `scripts/csv-report-api.js`
|
||||
- `scripts/csv-report.js`
|
||||
- `signals/*/formatter.js` (if generating links)
|
||||
|
||||
## Fix Record
|
||||
|
||||
- **Date**: 2024-12-31
|
||||
- **Issue**: csv-report-api.js uses `m.slug` to generate links
|
||||
- **Fix**: Changed to `m.events[0]?.slug || m.slug`
|
||||
|
||||
---
|
||||
|
||||
**Rule: Any code generating Polymarket links must use `events[0].slug`, not `slug`.**
|
||||
|
|
@ -0,0 +1,91 @@
|
|||
# The Secret to Guaranteed Profits: Complete Polymarket Arbitrage Guide
|
||||
|
||||
## You Trade Two Types of Assets: YES and NO Shares
|
||||
|
||||
In Polymarket, what you trade mainly falls into two categories:
|
||||
|
||||
1. If the event happens (YES)
|
||||
Each 1 share of YES you hold will be exchanged for $1 at settlement.
|
||||
|
||||
2. If the event doesn't happen (NO)
|
||||
Each 1 share of NO you hold will be exchanged for $1 at settlement.
|
||||
|
||||
Core rule: The side that guesses correctly, their shares become worth $1; the side that guesses wrong, their shares become worth zero.
|
||||
|
||||
## The Theoretical Iron Law: The Perfect Balance of System Design
|
||||
|
||||
YES share price + NO share price = $1
|
||||
|
||||
This is the inherent mathematical balance of the system, and the cornerstone of all arbitrage logic.
|
||||
For example: If the YES share market price is $0.60, then the theoretical NO share price must be $0.40.
|
||||
|
||||
## Theory is Perfect, But Reality is... Prices are Generated by Global User Trading
|
||||
|
||||
In the real world, prices are not set by formulas, but determined by the collective behavior of global traders (emotions, information asymmetry, strategies). This leads to the theoretical balance being frequently broken.
|
||||
|
||||
### YES share price + NO share price ≠ $1
|
||||
|
||||
This imbalance is what we call "Price Dislocation".
|
||||
|
||||
## Arbitrage Opportunity: When Total Price Doesn't Equal $1
|
||||
|
||||
When market trading causes total price to deviate from $1, risk-free profit opportunities emerge.
|
||||
|
||||
### 1. Emotional Buying
|
||||
|
||||
Breaking news hits the market, some traders impulsively buy large amounts of YES, causing its price to spike.
|
||||
|
||||
Imbalanced State:
|
||||
0.60 (YES) + 0.35 (NO) = $0.95 (less than $1 by $0.05)
|
||||
|
||||
Arbitrage Play:
|
||||
* Action: Simultaneously buy 1 share of YES and 1 share of NO.
|
||||
* Cost: $0.95
|
||||
* Result: Regardless of whether the event happens, your share set will settle at $1.00.
|
||||
* Profit: Stable $0.05 profit per set (about 5.2% return).
|
||||
|
||||
### 2. Global Time Lag
|
||||
|
||||
Major news released during US midnight, American traders react quickly, buying up YES; while Asian traders are still asleep, NO price hasn't updated synchronously.
|
||||
|
||||
Imbalanced State:
|
||||
0.70 (YES) + 0.33 (NO) = $1.03 (more than $1 by $0.03)
|
||||
|
||||
Arbitrage Play:
|
||||
* Action: Reverse operation, simultaneously sell 1 share of YES and 1 share of NO.
|
||||
* Income: $1.03
|
||||
* Result: You only need to return $1.00 at settlement.
|
||||
* Profit: Instantly lock in $0.03 profit (about 2.9% return).
|
||||
|
||||
### 3. Low Liquidity + Large Order Dump
|
||||
|
||||
In many low-volume events, a single large sell order of tens of thousands of dollars can instantly crash the YES price, while NO price can't react in time.
|
||||
|
||||
Imbalanced State:
|
||||
0.45 (YES) + 0.50 (NO) = $0.95 (less than $1 by $0.05)
|
||||
|
||||
Arbitrage Play:
|
||||
* Action: Monitoring bots programmatically buy the dumped asset combination.
|
||||
* Cost: $0.95
|
||||
* Result: Wait for market price to recover or hold to settlement, get $1.00.
|
||||
* Profit: Bots capture 5.2% instant profit.
|
||||
|
||||
### 4. Cross-Platform Price Spreads
|
||||
|
||||
The same event on different prediction platforms (like Polymarket and Kalshi), due to different user bases and liquidity, prices differ.
|
||||
|
||||
Imbalanced State:
|
||||
* Polymarket: YES $0.80 / NO $0.20 (buy NO)
|
||||
* Kalshi: YES $0.75 / NO $0.25 (buy YES)
|
||||
|
||||
Arbitrage Play:
|
||||
* Action: Buy cheaper NO ($0.20) on Polymarket, simultaneously buy cheaper YES ($0.75) on Kalshi.
|
||||
* Total cost: $0.20 + $0.75 = $0.95
|
||||
* Result: You've completely covered all outcomes, this cross-platform asset combination must settle at $1.00.
|
||||
* Profit: Lock in 5.2% cross-market risk-free profit.
|
||||
|
||||
## Summary: The Game Rules Behind Easy Money
|
||||
|
||||
Understanding the core of Polymarket arbitrage isn't about personally racing against bots, but about gaining insight into the commonality that exists in any market: efficiency is always generated in the game between rationality and human nature (irrationality).
|
||||
|
||||
Every price you see has a game behind it. Now, you can see that game.
|
||||
Loading…
Reference in New Issue