@clawhub-openlark-3793a1586a
Use mustache.js (logic-less Mustache templates) for any templating task in JavaScript/Node.js environments.
---
name: mustache
description: Use mustache.js (logic-less Mustache templates) for any templating task in JavaScript/Node.js environments.
---
# Mustache
Zero-dependency, logic-less template engine for JavaScript. Renders tags in templates using values from a view object.
## Triggers
when the user asks to render templates, use Mustache syntax {{ }}, create .mustache files,generate HTML/config/code from templates, or mentions mustache/mustache.js/{{mustache}}.
## Covers
variables, sections, inverted sections, partials, comments, custom delimiters, CLI usage,
pre-parsing/caching, and common patterns (email templates, config generation, code scaffolding).
## Install
```bash
npm install mustache --save # project dependency
npm install -g mustache # CLI tool
```
## Core API
```js
const Mustache = require('mustache');
const html = Mustache.render(template, view, partials, tags);
```
- `template` (string) — Mustache template string
- `view` (object) — data & helper functions
- `partials` (object, optional) — `{ name: partialString }`
- `tags` (string[], optional) — custom delimiters `[ open, close ]`
## Tag Types Quick Reference
| Tag | Syntax | Behavior |
|-----|--------|----------|
| Variable | `{{key}}` | HTML-escaped value |
| Unescaped | `{{{key}}}` or `{{&key}}` | Raw HTML output |
| Dot notation | `{{a.b.c}}` | Nested property access |
| Current item | `{{.}}` | Current item in string array loop |
| Section | `{{#key}}...{{/key}}` | Truthy → render block; array → loop |
| Inverted | `{{^key}}...{{/key}}` | Falsy/empty → render block |
| Comment | `{{! text }}` | Stripped from output |
| Partial | `{{> name}}` | Inline another template |
| Set Delimiter | `{{=<% %>=}}` | Change tag delimiters |
## Sections — Detailed
**Falsy (skip):** `null`, `undefined`, `false`, `0`, `NaN`, `""`, `[]` → block not rendered.
**Non-empty array (loop):** Block renders once per item; context shifts to each item.
```js
// String array — use {{.}} for current item
Mustache.render('{{#items}}- {{.}}\n{{/items}}', { items: ['a','b'] });
// → "- a\n- b\n"
// Object array — access properties directly
Mustache.render('{{#people}}* {{name}}\n{{/people}}', {
people: [{ name: 'Alice' }, { name: 'Bob' }]
});
// → "* Alice\n* Bob\n"
// Lambda function — receives raw block text + render helper
Mustache.render('{{#bold}}Hi {{name}}{{/bold}}', {
name: 'World',
bold: function() {
return function(text, render) {
return '<b>' + render(text) + '</b>';
};
}
});
// → "<b>Hi World</b>"
```
## Partials
Pass as third argument; inherit the calling context.
```js
Mustache.render(
'<h2>Names</h2>{{#names}}{{> user}}{{/names}}',
{ names: [{ name: 'Alice' }, { name: 'Bob' }] },
{ user: '<strong>{{name}}</strong>\n' }
);
// → <h2>Names</h2>\n<strong>Alice</strong>\n<strong>Bob</strong>\n
```
## Custom Delimiters
```js
// JS: pass as 4th argument or set Mustache.tags
Mustache.render(template, view, {}, ['<%', '%>']);
// Template: set delimiter inline
{{=<% %>=}}<% erb_style %><%={{ }}=%>
// Delimiters may not contain whitespace or =
```
## Pre-parsing / Caching
```js
Mustache.parse(template); // cache parsed tree
// Later calls with the same template skip parsing
```
## CLI Usage
```bash
mustache data.json template.mustache > output.html
mustache data.json -p partials/header.mustache -p partials/footer.mustache template.mustache
cat data.json | mustache - template.mustache > output.html
```
## Common Patterns
For detailed examples and anti-patterns, see [references/patterns.md](references/patterns.md).
**Escape override** (for non-HTML like config files):
```js
Mustache.escape = t => t;
```
**Include template in HTML** (static sites):
```html
<script id="tpl" type="x-tmpl-mustache">{{> content}}</script>
```
**Async load template** (SPAs):
```js
fetch('tpl.mustache').then(r => r.text()).then(t => {
document.getElementById('out').innerHTML = Mustache.render(t, data);
});
```
## Anti-patterns
- Do NOT put logic in views — Mustache is logic-less; move logic to pre-processing
- Avoid recursive partials without a termination condition
- Do NOT use `Mustache.escape = t => t` globally without restoring it afterward
Focused on multi-agent collaboration and communication scenarios, helping users build and manage complex distributed agent systems to achieve task decomposit...
---
name: multi-agent-collaboration-communication
description: Focused on multi-agent collaboration and communication scenarios, helping users build and manage complex distributed agent systems to achieve task decomposition, parallel processing, and collaborative work. Use this skill when users need to design multi-agent system architectures, plan task distribution schemes, establish inter-agent communication protocols, or implement distributed collaboration workflows.
---
# Multi-Agent Collaboration Communication
A guide to designing and implementing multi-agent collaboration systems.
## Core Capabilities
1. **System Architecture Design** - Design the overall architecture of multi-agent systems, including role definitions, communication topologies, and coordination mechanisms
2. **Task Decomposition and Distribution** - Break complex tasks into parallelizable sub-tasks and distribute them appropriately among different agents
3. **Communication Protocol Design** - Establish mechanisms for message passing, state synchronization, and result aggregation between agents
4. **Collaboration Workflow Orchestration** - Design workflows, handle dependencies, and manage execution order
5. **Conflict Resolution and Consistency** - Address resource contention, decision conflicts, and data consistency issues
## Quick Start
### Usage Workflow
```
User Requirements → System Analysis → Architecture Design → Task Decomposition → Communication Design → Workflow Orchestration → Output Delivery
```
### Typical Application Scenarios
- **Distributed Data Processing** - Multiple agents process different partitions of a large dataset in parallel
- **Complex Workflow Automation** - Multi-step business processes, with each step handled by a specialized agent
- **Intelligent Customer Service Systems** - Different agents handle different types of inquiries, collaborating to provide comprehensive service
- **Code Review and Generation** - Multiple specialized agents address dimensions such as architecture, security, and performance respectively
- **Scientific Research Collaboration** - Simulate a research team, with agents playing different roles (experimental design, data analysis, paper writing)
## Design Methodology
### 1. Role Definition
Each agent should have clear responsibility boundaries:
| Dimension | Description |
|-----------|-------------|
| **Core Responsibility** | The agent's primary function and task scope |
| **Input/Output** | What data it receives and what results it produces |
| **Capability Boundary** | What it can and cannot do |
| **Dependencies** | Which agents it depends on and which depend on it |
### 2. Communication Patterns
Choose the appropriate communication topology:
- **Star** - Central coordinator manages all communication
- **Bus** - Shared message bus with broadcast/subscribe model
- **Mesh** - Direct agent-to-agent communication, decentralized
- **Hierarchical** - Tree structure with escalation by level
### 3. Coordination Mechanisms
- **Master-Slave** - One master agent assigns tasks; multiple slave agents execute
- **Peer-to-Peer** - All agents collaborate as equals
- **Pipeline** - Data flows through multiple agents for sequential processing
- **Competitive** - Multiple agents compete for tasks; the best performer executes
## Workflow
### Step 1: Requirements Analysis
Understand the user's business scenario and objectives:
- What problem needs to be solved?
- What is the complexity and scale of the task?
- What are the requirements for real-time performance and reliability?
- What constraints exist?
### Step 2: Architecture Design
Design the overall system architecture:
- Determine the number and roles of agents
- Select the communication topology
- Define the coordination mechanism
- Design the data flow
**Reference** [references/architecture_patterns.md](references/architecture_patterns.md) for common architecture patterns
### Step 3: Task Decomposition
Break down complex tasks:
- Identify sub-tasks that can be parallelized
- Analyze task dependencies
- Estimate resource requirements for each sub-task
- Determine execution priorities
**Reference** [references/task_decomposition.md](references/task_decomposition.md) for task decomposition strategies
### Step 4: Communication Protocol Design
Define interaction rules between agents:
- Message format and encoding
- Communication protocol (synchronous/asynchronous)
- Error handling and retry mechanisms
- Timeout and circuit breaker strategies
**Reference** [references/communication_protocols.md](references/communication_protocols.md) for protocol design templates
### Step 5: Workflow Orchestration
Design the collaboration workflow:
- Define the workflow state machine
- Handle branching and conditional logic
- Design result aggregation strategies
- Implement monitoring and logging
**Reference** [references/workflow_templates.md](references/workflow_templates.md) for workflow templates
### Step 6: Output Delivery
Generate executable deliverables:
- System architecture diagram
- Agent role definition document
- Communication protocol specification
- Collaboration workflow code/configuration
## Best Practices
### Design Principles
1. **Single Responsibility** - Each agent does one thing and does it well
2. **Loose Coupling** - Agents communicate through standard interfaces to reduce dependencies
3. **Fault-Tolerant Design** - Account for agent failures, network interruptions, and other exceptions
4. **Observability** - Comprehensive logging, monitoring, and tracing mechanisms
5. **Incremental Evolution** - Start simple and gradually increase complexity
### Common Pitfalls
- **Over-Engineering** - Creating too many agents for simple tasks
- **Tight Coupling** - Direct dependencies on internal implementations between agents
- **Ignoring Boundaries** - Not defining clear responsibility boundaries
- **Lack of Fallback** - No backup plans for handling failure scenarios
## Resources
### references/
Detailed design reference documents:
- `architecture_patterns.md` - Common multi-agent architecture patterns
- `task_decomposition.md` - Task decomposition strategies and methods
- `communication_protocols.md` - Communication protocol design specifications
- `workflow_templates.md` - Reusable workflow templates
### assets/
Available templates and examples:
- `templates/` - Architecture design document templates, code scaffolding templates
- `examples/` - Implementation examples for typical scenarios
### scripts/
Auxiliary tool scripts:
- `generate_architecture.py` - Generate architecture diagrams and configurations
- `validate_design.py` - Validate the completeness of design solutions
FILE:scripts/generate_architecture.py
#!/usr/bin/env python3
"""
Multi-Agent System Architecture Generator
Generate system architecture diagrams and configuration files
"""
import json
import yaml
import argparse
from datetime import datetime
from typing import Dict, List, Any
def generate_agent_config(agents: List[Dict], topology: str) -> Dict:
"""Generate Agent configuration"""
config = {
"system": {
"name": "multi-agent-system",
"version": "1.0.0",
"generated_at": datetime.now().isoformat()
},
"agents": [],
"communication": {
"topology": topology,
"protocol": "websocket"
}
}
for i, agent in enumerate(agents):
agent_config = {
"id": agent.get("id", f"agent-{i}"),
"name": agent.get("name", f"Agent {i}"),
"description": agent.get("description", ""),
"type": agent.get("type", "worker"),
"capabilities": agent.get("capabilities", []),
"endpoints": agent.get("endpoints", [])
}
config["agents"].append(agent_config)
return config
def generate_workflow_config(steps: List[Dict], workflow_type: str = "sequential") -> Dict:
"""Generate workflow configuration"""
return {
"workflow": {
"name": "generated-workflow",
"type": workflow_type,
"steps": steps,
"error_handling": {
"strategy": "retry_then_fallback",
"retry": {
"max_attempts": 3,
"delay": 5
}
}
}
}
def generate_architecture_diagram(agents: List[Dict], topology: str) -> str:
"""Generate text-based architecture diagram"""
lines = ["System Architecture Diagram", "=" * 40, ""]
if topology == "star":
lines.append(" ┌─────────────┐")
lines.append(" │ Coordinator │")
lines.append(" └──────┬──────┘")
lines.append(" │")
connections = " ".join([f"[{a['id']}]" for a in agents if a.get('type') != 'coordinator'])
lines.append(f" {connections}")
elif topology == "pipeline":
flow = " → ".join([f"[{a['id']}]" for a in agents])
lines.append(flow)
elif topology == "mesh":
for agent in agents:
connections = ", ".join([a['id'] for a in agents if a['id'] != agent['id']])
lines.append(f"[{agent['id']}] ↔ {connections}")
elif topology == "hierarchical":
lines.append(" [Root]")
lines.append(" / \\")
children = [a for a in agents if a.get('type') != 'coordinator']
mid = len(children) // 2
left = " ".join([f"[{c['id']}]" for c in children[:mid]])
right = " ".join([f"[{c['id']}]" for c in children[mid:]])
lines.append(f" {left} {right}")
return "\n".join(lines)
def generate_dependency_graph(dependencies: List[Dict]) -> str:
"""Generate dependency graph"""
lines = ["Task Dependency Graph", "=" * 40, ""]
for dep in dependencies:
task = dep.get("task", "")
deps = dep.get("depends_on", [])
if deps:
dep_str = ", ".join(deps)
lines.append(f"[{dep_str}] ──► [{task}]")
else:
lines.append(f"[Start] ──► [{task}]")
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description="Multi-Agent System Architecture Generator")
parser.add_argument("--config", "-c", help="Input configuration file (JSON/YAML)")
parser.add_argument("--output", "-o", help="Output directory")
parser.add_argument("--topology", "-t", default="star",
choices=["star", "bus", "mesh", "hierarchical", "pipeline"],
help="Architecture topology")
parser.add_argument("--format", "-f", default="yaml", choices=["json", "yaml"],
help="Output format")
args = parser.parse_args()
# Example Agent definitions
example_agents = [
{
"id": "coordinator",
"name": "Coordinator",
"type": "coordinator",
"description": "Responsible for overall coordination",
"capabilities": ["dispatch", "monitor"]
},
{
"id": "worker-1",
"name": "Worker Node 1",
"type": "worker",
"description": "Data processing",
"capabilities": ["process"]
},
{
"id": "worker-2",
"name": "Worker Node 2",
"type": "worker",
"description": "Data analysis",
"capabilities": ["analyze"]
}
]
# Generate architecture diagram
diagram = generate_architecture_diagram(example_agents, args.topology)
print(diagram)
print("\n")
# Generate configuration
config = generate_agent_config(example_agents, args.topology)
if args.format == "json":
output = json.dumps(config, indent=2, ensure_ascii=False)
else:
output = yaml.dump(config, allow_unicode=True, sort_keys=False)
print("Generated Configuration:")
print("-" * 40)
print(output)
if args.output:
import os
os.makedirs(args.output, exist_ok=True)
# Save configuration
ext = "json" if args.format == "json" else "yaml"
config_path = os.path.join(args.output, f"agent-config.{ext}")
with open(config_path, "w", encoding="utf-8") as f:
f.write(output)
print(f"\nConfiguration saved to: {config_path}")
# Save architecture diagram
diagram_path = os.path.join(args.output, "architecture.txt")
with open(diagram_path, "w", encoding="utf-8") as f:
f.write(diagram)
print(f"Architecture diagram saved to: {diagram_path}")
if __name__ == "__main__":
main()
FILE:scripts/validate_design.py
#!/usr/bin/env python3
"""
Multi-Agent System Design Proposal Validator
Checks the completeness and reasonableness of design proposals
"""
import json
import yaml
import argparse
from typing import Dict, List, Any, Tuple
from dataclasses import dataclass
@dataclass
class ValidationResult:
passed: bool
errors: List[str]
warnings: List[str]
def __init__(self):
self.passed = True
self.errors = []
self.warnings = []
def add_error(self, message: str):
self.passed = False
self.errors.append(message)
def add_warning(self, message: str):
self.warnings.append(message)
class DesignValidator:
"""Design proposal validator"""
def __init__(self, design: Dict):
self.design = design
self.result = ValidationResult()
def validate(self) -> ValidationResult:
"""Execute full validation"""
self._validate_structure()
self._validate_agents()
self._validate_communication()
self._validate_workflow()
self._validate_dependencies()
return self.result
def _validate_structure(self):
"""Validate basic structure"""
required_sections = ["agents", "communication"]
for section in required_sections:
if section not in self.design:
self.result.add_error(f"Missing required section: {section}")
def _validate_agents(self):
"""Validate Agent definitions"""
if "agents" not in self.design:
return
agents = self.design["agents"]
if not isinstance(agents, list):
self.result.add_error("agents must be a list")
return
if len(agents) == 0:
self.result.add_error("At least one Agent must be defined")
return
agent_ids = set()
has_coordinator = False
for i, agent in enumerate(agents):
prefix = f"agents[{i}]"
# Check required fields
if "id" not in agent:
self.result.add_error(f"{prefix}: missing id field")
continue
agent_id = agent["id"]
# Check ID uniqueness
if agent_id in agent_ids:
self.result.add_error(f"{prefix}: duplicate Agent ID '{agent_id}'")
agent_ids.add(agent_id)
# Check type
if "type" in agent:
if agent["type"] == "coordinator":
has_coordinator = True
elif agent["type"] not in ["worker", "specialist"]:
self.result.add_warning(f"{prefix}: unknown Agent type '{agent['type']}'")
# Check capability definitions
if "capabilities" not in agent:
self.result.add_warning(f"{prefix}: it is recommended to define capabilities")
if not has_coordinator and len(agents) > 1:
self.result.add_warning("Multi-agent system is recommended to define a coordinator-type Agent")
def _validate_communication(self):
"""Validate communication configuration"""
if "communication" not in self.design:
return
comm = self.design["communication"]
# Check topology type
if "topology" in comm:
valid_topologies = ["star", "bus", "mesh", "hierarchical", "pipeline"]
if comm["topology"] not in valid_topologies:
self.result.add_warning(f"Unknown topology type: {comm['topology']}")
# Check protocol
if "protocol" in comm:
valid_protocols = ["http", "websocket", "grpc", "mqtt"]
if comm["protocol"] not in valid_protocols:
self.result.add_warning(f"Unknown communication protocol: {comm['protocol']}")
def _validate_workflow(self):
"""Validate workflow definitions"""
if "workflow" not in self.design:
return
workflow = self.design["workflow"]
if "steps" not in workflow:
self.result.add_warning("workflow: it is recommended to define steps")
return
steps = workflow["steps"]
if not isinstance(steps, list):
self.result.add_error("workflow.steps must be a list")
return
step_ids = set()
for i, step in enumerate(steps):
prefix = f"workflow.steps[{i}]"
if "id" not in step:
self.result.add_error(f"{prefix}: missing id field")
continue
if step["id"] in step_ids:
self.result.add_error(f"{prefix}: duplicate step ID '{step['id']}'")
step_ids.add(step["id"])
if "agent" not in step:
self.result.add_error(f"{prefix}: missing agent field")
def _validate_dependencies(self):
"""Validate dependencies"""
if "dependencies" not in self.design:
return
deps = self.design["dependencies"]
if not isinstance(deps, list):
return
# Check for circular dependencies
dep_graph = {}
for dep in deps:
task = dep.get("task", "")
depends_on = dep.get("depends_on", [])
dep_graph[task] = depends_on
# Simple cycle detection
visited = set()
rec_stack = set()
def has_cycle(node, visited, rec_stack):
visited.add(node)
rec_stack.add(node)
for neighbor in dep_graph.get(node, []):
if neighbor not in visited:
if has_cycle(neighbor, visited, rec_stack):
return True
elif neighbor in rec_stack:
return True
rec_stack.remove(node)
return False
for node in dep_graph:
if node not in visited:
if has_cycle(node, visited, rec_stack):
self.result.add_error("Circular dependency detected")
break
def load_config(path: str) -> Dict:
"""Load configuration file"""
with open(path, 'r', encoding='utf-8') as f:
if path.endswith('.json'):
return json.load(f)
elif path.endswith('.yaml') or path.endswith('.yml'):
return yaml.safe_load(f)
else:
# Try JSON first, fallback to YAML on failure
try:
return json.load(f)
except:
f.seek(0)
return yaml.safe_load(f)
def main():
parser = argparse.ArgumentParser(description="Multi-Agent System Design Proposal Validator")
parser.add_argument("config", help="Configuration file path (JSON/YAML)")
parser.add_argument("--strict", "-s", action="store_true", help="Strict mode (warnings treated as errors)")
args = parser.parse_args()
try:
design = load_config(args.config)
except Exception as e:
print(f"❌ Configuration file loading failed: {e}")
return 1
validator = DesignValidator(design)
result = validator.validate()
# Output results
print("=" * 50)
print("Design Proposal Validation Results")
print("=" * 50)
if result.errors:
print(f"\n❌ Found {len(result.errors)} error(s):")
for error in result.errors:
print(f" • {error}")
if result.warnings:
print(f"\n⚠️ Found {len(result.warnings)} warning(s):")
for warning in result.warnings:
print(f" • {warning}")
if result.passed and not result.warnings:
print("\n✅ Validation passed! Design proposal is complete and reasonable.")
elif result.passed:
print("\n✅ Validation passed, but warnings exist. Recommended to review.")
else:
print("\n❌ Validation failed. Please fix the above errors.")
# Strict mode
if args.strict and result.warnings:
print("\n[Strict Mode] Warnings treated as errors")
return 1
return 0 if result.passed else 1
if __name__ == "__main__":
exit(main())
FILE:references/architecture_patterns.md
# Multi-Agent System Architecture Patterns
## 1. Star Architecture
### Description
A central coordinator manages all agents; all communication passes through the central node.
### Applicable Scenarios
- Need for centralized control and decision-making
- Complex task distribution logic
- Need for global state management
### Advantages
- Centralized control logic, easy to manage
- Good global state consistency
- Easy to monitor and debug
### Disadvantages
- Single point of failure risk
- Central node can become a bottleneck
- Limited scalability
### Typical Applications
- Intelligent customer service systems (central routing and distribution)
- Task scheduling systems
- Centralized workflow engines
```
┌─────────────┐
│ Coordinator │
└──────┬──────┘
│
┌────┬─────┼─────┬────┐
│ │ │ │ │
▼ ▼ ▼ ▼ ▼
[A1] [A2] [A3] [A4] [A5]
```
---
## 2. Bus Architecture
### Description
All agents connect to a shared message bus and communicate via a publish/subscribe model.
### Applicable Scenarios
- Event-driven systems
- Loosely coupled components
- Need for dynamic agent addition/removal
### Advantages
- Highly decoupled
- Easy to scale
- Flexible communication patterns
### Disadvantages
- Message bus can become a bottleneck
- Complex message ordering guarantees
- Difficult to debug
### Typical Applications
- Event processing systems
- Real-time data stream processing
- Microservice coordination
```
[A1] ──┐
[A2] ──┼──◄ Message Bus ►──┼── [A3]
[A3] ──┘ └── [A4]
```
---
## 3. Mesh Architecture
### Description
Agents communicate directly with each other without a central node; fully decentralized.
### Applicable Scenarios
- Peer-to-peer collaboration
- Distributed decision-making
- High availability requirements
### Advantages
- No single point of failure
- High availability
- Low-latency direct communication
### Disadvantages
- Number of connections grows quadratically with agent count
- Complex coordination
- Consistency challenges
### Typical Applications
- Distributed consensus systems
- P2P networks
- Blockchain nodes
```
[A1] ─────── [A2]
/ │ \ / │ \
[A3]─[A4]───[A5]─[A6]
\ │ / \ │ /
[A7] ─────── [A8]
```
---
## 4. Hierarchical Architecture
### Description
Tree structure; superior agents manage subordinate agents with escalation by level.
### Applicable Scenarios
- Organizational structure simulation
- Multi-level decision-making
- Large-scale systems
### Advantages
- Clear structure
- Good scalability
- Clearly defined layered responsibilities
### Disadvantages
- Increased communication latency
- Too many levels reduces efficiency
- Fault propagation risk
### Typical Applications
- Enterprise organizational structures
- Military command systems
- Multi-tier management systems
```
[Root]
/ \
[Mgr1] [Mgr2]
/ \ / \
[A1] [A2] [A3] [A4]
```
---
## 5. Pipeline Architecture
### Description
Data flows through a series of agents; each agent handles a specific stage before passing to the next.
### Applicable Scenarios
- Data processing pipelines
- Multi-stage processing tasks
- Stream computing
### Advantages
- Clear processing flow
- Easy to parallelize
- Good fault tolerance
### Disadvantages
- Not suitable for branching logic
- Data formats need to be uniform
- Accumulated latency
### Typical Applications
- ETL data processing
- Compiler pipelines
- Image processing chains
```
[Input] → [A1:Parse] → [A2:Process] → [A3:Validate] → [A4:Output] → [Result]
```
---
## 6. Hybrid Architecture
### Description
Combines multiple architecture patterns, selecting the most suitable structure based on the scenario.
### Common Combinations
- **Star + Bus** - Central coordinator + event bus
- **Hierarchical + Pipeline** - Multi-level management + pipeline processing
- **Mesh + Star** - Mesh within groups, star between groups
### Selection Recommendations
| Scenario Characteristics | Recommended Architecture |
|--------------------------|--------------------------|
| Need for strong control | Star |
| High scalability | Bus |
| High availability | Mesh |
| Clear hierarchy | Hierarchical |
| Data processing | Pipeline |
| Complex systems | Hybrid |
---
## Architecture Design Checklist
- [ ] Define system objectives and constraints
- [ ] Identify core agent roles
- [ ] Select appropriate communication topology
- [ ] Define coordination mechanisms
- [ ] Consider fault tolerance and recovery
- [ ] Plan for scalability
- [ ] Design monitoring solutions
FILE:references/communication_protocols.md
# Agent Communication Protocol Design
## Communication Modes
### 1. Synchronous Communication
**Characteristics**: The sender waits for the receiver's response before proceeding.
**Applicable Scenarios**:
- Operations requiring immediate confirmation
- Strong consistency requirements
- Short-duration operations
**Implementation**:
```
Agent-A ──request──► Agent-B
▲ │
└───response───────┘
```
**Pros and Cons**:
- ✅ Simple and intuitive
- ✅ Easy error handling
- ❌ Blocking wait
- ❌ High coupling
### 2. Asynchronous Communication
**Characteristics**: The sender does not wait; results are obtained via callbacks or events.
**Applicable Scenarios**:
- Long-duration operations
- High concurrency scenarios
- Decoupling requirements
**Implementation**:
```
Agent-A ──request──► Agent-B
Agent-A ◄──event──── Agent-B (later)
```
**Pros and Cons**:
- ✅ Non-blocking
- ✅ High throughput
- ❌ Higher complexity
- ❌ Difficult to debug
### 3. Streaming Communication
**Characteristics**: Continuous data flow, suitable for real-time scenarios.
**Applicable Scenarios**:
- Real-time data processing
- Long-lived connection scenarios
- Incremental result delivery
**Implementation**:
```
Agent-A ════════════► Agent-B
[chunk1][chunk2][chunk3]...
```
---
## Message Format
### Standard Message Structure
```json
{
"message_id": "uuid",
"timestamp": "2024-01-01T00:00:00Z",
"sender": "agent-id",
"receiver": "agent-id|broadcast",
"message_type": "request|response|event|heartbeat",
"correlation_id": "uuid",
"payload": {
"action": "action-name",
"data": {},
"metadata": {}
},
"priority": "high|normal|low",
"ttl": 3600
}
```
### Message Types
#### Request/Response
```json
// Request
{
"message_type": "request",
"payload": {
"action": "analyze_data",
"data": {"dataset_id": "123"},
"parameters": {"depth": "detailed"}
}
}
// Response
{
"message_type": "response",
"correlation_id": "request-uuid",
"payload": {
"status": "success|error",
"result": {},
"error": null
}
}
```
#### Event
```json
{
"message_type": "event",
"payload": {
"event_type": "task_completed|state_changed|error_occurred",
"data": {}
}
}
```
#### Heartbeat
```json
{
"message_type": "heartbeat",
"payload": {
"agent_status": "healthy|busy|error",
"load": 0.5,
"capabilities": ["cap1", "cap2"]
}
}
```
---
## Communication Protocol Specification
### Protocol Layer Design
```
┌─────────────────────────────────────┐
│ Application Layer │
│ Message format, business logic, │
│ serialization │
├─────────────────────────────────────┤
│ Transport Layer │
│ HTTP/WebSocket/gRPC/MQTT │
├─────────────────────────────────────┤
│ Network Layer │
│ TCP/UDP │
└─────────────────────────────────────┘
```
### Transport Protocol Selection
| Protocol | Applicable Scenarios | Advantages | Disadvantages |
|----------|---------------------|------------|---------------|
| HTTP/REST | Simple request-response | Simple, widely supported | High overhead, stateless |
| WebSocket | Real-time bidirectional communication | Low latency, full-duplex | Complex connection management |
| gRPC | High-performance RPC | Efficient, strongly typed | Requires protobuf |
| MQTT | IoT/Message queues | Lightweight, pub-sub | Basic functionality |
| Message Queue | Asynchronous decoupling | Reliable, buffered | Introduces middleware |
---
## Error Handling
### Error Classification
1. **Network Errors** - Connection failure, timeout
2. **Business Errors** - Parameter errors, logic errors
3. **System Errors** - Internal exceptions, insufficient resources
### Retry Strategy
```python
# Exponential backoff retry
retry_config = {
"max_attempts": 3,
"initial_delay": 1, # seconds
"max_delay": 60,
"backoff_multiplier": 2,
"retryable_errors": ["timeout", "connection_error"]
}
```
### Circuit Breaker Mechanism
```python
circuit_breaker = {
"failure_threshold": 5,
"recovery_timeout": 30,
"half_open_max_calls": 3
}
```
---
## State Synchronization
### State Propagation Modes
1. **Push** - Proactively notify upon state changes
2. **Pull** - Periodically query state
3. **Hybrid** - Push + Pull combined
### Consistency Strategies
| Strategy | Description | Applicable Scenarios |
|----------|-------------|----------------------|
| Strong Consistency | All nodes consistent in real time | Critical data |
| Eventual Consistency | Brief inconsistency tolerated | General data |
| Causal Consistency | Guarantees causal relationships | Ordered operations |
---
## Security Considerations
### Authentication and Authorization
```json
{
"auth": {
"type": "jwt|api_key|certificate",
"token": "...",
"permissions": ["read", "write", "admin"]
}
}
```
### Message Encryption
- **Transport Layer** - TLS/SSL
- **Application Layer** - End-to-end encryption
### Anti-Replay Attack
```json
{
"nonce": "unique-nonce",
"timestamp": 1234567890,
"signature": "hmac-signature"
}
```
---
## Protocol Template
### Basic Protocol Definition
```yaml
protocol:
name: "agent-communication-protocol"
version: "1.0.0"
transport:
type: "websocket"
host: "localhost"
port: 8080
message_format:
encoding: "json"
schema: "message-schema.json"
patterns:
- name: "request_response"
timeout: 30
retry: 3
- name: "pub_sub"
topics: ["events", "commands"]
reliability:
delivery: "at_least_once"
ordering: "preserve_order"
deduplication: true
```
FILE:references/task_decomposition.md
# Task Decomposition Strategies
## Decomposition Principles
### 1. Single Responsibility Principle (SRP)
Each sub-task should have only one clear responsibility; avoid mixing responsibilities.
### 2. Independence Principle
Sub-tasks should be as independent as possible to minimize interdependencies.
### 3. Composability Principle
Sub-task results should be easily combinable into the final result.
### 4. Appropriate Granularity Principle
Task granularity should be neither too large nor too small; strike a balance between manageability and parallelism.
---
## Decomposition Methods
### Method 1: Functional Decomposition
Decompose tasks by functional module.
**Applicable Scenarios**: Clear system functions, well-defined module boundaries
**Example** - Document Processing System:
```
Process Document
├── Parse Document
│ ├── Parse PDF
│ ├── Parse Word
│ └── Parse Text
├── Extract Content
│ ├── Extract Text
│ ├── Extract Tables
│ └── Extract Images
├── Analyze Content
│ ├── Keyword Extraction
│ ├── Topic Classification
│ └── Sentiment Analysis
└── Generate Report
├── Generate Summary
├── Generate Charts
└── Export File
```
### Method 2: Data Decomposition
Decompose tasks by data partition.
**Applicable Scenarios**: Large datasets with no dependencies between data
**Example** - Log Analysis:
```
Analyze Logs
├── Analyze 2024-Q1 Logs
├── Analyze 2024-Q2 Logs
├── Analyze 2024-Q3 Logs
└── Analyze 2024-Q4 Logs
```
### Method 3: Process Decomposition
Decompose tasks by processing flow steps.
**Applicable Scenarios**: Tasks with well-defined processing flows
**Example** - Order Processing:
```
Process Order
├── Validate Order
│ ├── Verify User Information
│ ├── Verify Product Inventory
│ └── Verify Payment Information
├── Process Payment
│ ├── Deduct Inventory
│ ├── Process Payment
│ └── Generate Invoice
└── Arrange Delivery
├── Select Warehouse
├── Generate Waybill
└── Notify Logistics
```
### Method 4: Hierarchical Decomposition
Decompose tasks by abstraction level.
**Applicable Scenarios**: Complex systems requiring layered processing
**Example** - Code Review:
```
Code Review
├── Architecture Layer Review
│ ├── Design Pattern Check
│ └── Architectural Consistency Check
├── Code Layer Review
│ ├── Code Style Check
│ ├── Complexity Analysis
│ └── Duplicate Code Detection
└── Quality Layer Review
├── Security Vulnerability Scan
├── Performance Bottleneck Analysis
└── Test Coverage Check
```
---
## Dependency Management
### Dependency Types
1. **Data Dependency** - Task B requires output data from Task A
2. **Control Dependency** - Task B must wait for Task A to complete
3. **Resource Dependency** - Multiple tasks compete for the same resource
### Dependency Graph Construction
```
Task A ──┬──► Task C ──┐
│ ├──► Task E
Task B ──┴──► Task D ──┘
```
### Parallelism Analysis
- **Dependency-Free Tasks** - Fully parallelizable
- **Chain Dependencies** - Must be serial
- **Branch Dependencies** - Partially parallelizable
---
## Task Assignment Strategies
### Strategy 1: Capability Matching
Assign tasks based on agent capabilities.
```
Agent Capability Matrix:
Parse Analyze Generate Validate
Agent-A ✓ ✓ ✗ ✗
Agent-B ✗ ✓ ✓ ✗
Agent-C ✗ ✗ ✗ ✓
```
### Strategy 2: Load Balancing
Dynamically assign based on current agent load.
```
Agent Status:
Agent-A: 3/10 tasks (Available)
Agent-B: 8/10 tasks (Busy)
Agent-C: 1/10 tasks (Idle) ← Assign first
```
### Strategy 3: Data Locality
Assign tasks to agents that already possess relevant data.
```
Data Distribution:
Agent-A: Possesses Dataset X
Agent-B: Possesses Dataset Y
Task requires Dataset X → Assign to Agent-A
```
---
## Task Decomposition Template
### Template Structure
```yaml
task:
name: "Task Name"
description: "Task Description"
decomposition:
method: "functional|data|process|hierarchical"
subtasks:
- id: "task-1"
name: "Sub-task 1"
description: "Sub-task Description"
agent: "agent-type"
input: ["Input Data"]
output: ["Output Data"]
dependencies: []
- id: "task-2"
name: "Sub-task 2"
description: "Sub-task Description"
agent: "agent-type"
input: ["Input Data"]
output: ["Output Data"]
dependencies: ["task-1"]
aggregation:
method: "merge|concatenate|reduce"
handler: "aggregator-agent"
```
---
## Best Practices
1. **Coarse to Fine** - Start with coarse-grained decomposition, then refine
2. **Maintain Balance** - Sub-task granularity should be roughly equivalent
3. **Reserve Buffer** - Account for task failures and retries
4. **Monitor Dependencies** - Avoid circular dependencies
5. **Clear Documentation** - Each sub-task should have well-defined input and output definitions
FILE:references/workflow_templates.md
# Workflow Templates
## Template 1: Sequential Workflow
### Description
Tasks execute sequentially in a fixed order; the next begins only after the previous one completes.
### Applicable Scenarios
- Task chains with strict dependencies
- Data processing pipelines
- Approval workflows
### Flow Diagram
```
[Start] → [Task1] → [Task2] → [Task3] → [End]
```
### Configuration Example
```yaml
workflow:
name: "sequential-processing"
type: "sequential"
steps:
- id: "step1"
name: "Data Fetching"
agent: "data-fetcher"
action: "fetch"
input: {"source": "api"}
- id: "step2"
name: "Data Processing"
agent: "data-processor"
action: "process"
input: {"$ref": "step1.output"}
- id: "step3"
name: "Result Storage"
agent: "data-saver"
action: "save"
input: {"$ref": "step2.output"}
```
---
## Template 2: Parallel Workflow
### Description
Multiple tasks execute simultaneously; results are aggregated at the end.
### Applicable Scenarios
- Independent sub-tasks
- Batch processing
- Multi-dimensional analysis
### Flow Diagram
```
┌─► [Task1] ─┐
[Start] ─┼─► [Task2] ─┼─► [Merge] → [End]
└─► [Task3] ─┘
```
### Configuration Example
```yaml
workflow:
name: "parallel-analysis"
type: "parallel"
branches:
- id: "branch1"
name: "Sentiment Analysis"
agent: "sentiment-analyzer"
action: "analyze"
- id: "branch2"
name: "Keyword Extraction"
agent: "keyword-extractor"
action: "extract"
- id: "branch3"
name: "Topic Classification"
agent: "topic-classifier"
action: "classify"
aggregator:
agent: "result-merger"
action: "merge"
strategy: "concatenate"
```
---
## Template 3: Conditional Workflow
### Description
Select different execution paths based on conditions.
### Applicable Scenarios
- Business processes requiring decisions
- Exception handling
- Dynamic routing
### Flow Diagram
```
[Start] → [Decision] ──Yes──► [PathA] ─┐
│ ├──► [End]
└─No────► [PathB] ───────┘
```
### Configuration Example
```yaml
workflow:
name: "conditional-routing"
type: "conditional"
decision:
agent: "router"
condition: "input.priority == 'high'"
branches:
- condition: "priority == 'high'"
steps:
- agent: "priority-handler"
action: "urgent-process"
- condition: "priority == 'normal'"
steps:
- agent: "normal-handler"
action: "standard-process"
- condition: "default"
steps:
- agent: "low-priority-handler"
action: "batch-process"
```
---
## Template 4: Loop Workflow
### Description
Repeatedly execute a task until a condition is met.
### Applicable Scenarios
- Iterative optimization
- Processing paginated data in batches
- Polling and waiting
### Flow Diagram
```
[Start] → [Task] → [Condition?] ──No──┐
│ │
Yes │
▼ │
[End] ◄────────┘
```
### Configuration Example
```yaml
workflow:
name: "iterative-optimization"
type: "loop"
loop:
max_iterations: 10
condition: "result.quality < 0.95"
step:
agent: "optimizer"
action: "optimize"
input:
data: "$input"
previous_result: "$loop.last_result"
iteration: "$loop.index"
```
---
## Template 5: Divide and Conquer Workflow
### Description
Decompose a large task into multiple smaller tasks for parallel processing, then merge results.
### Applicable Scenarios
- Big data processing
- Distributed computing
- MapReduce pattern
### Flow Diagram
```
[Input] → [Split] ─┬─► [Process1] ─┐
├─► [Process2] ─┼─► [Merge] → [Output]
└─► [Process3] ─┘
```
### Configuration Example
```yaml
workflow:
name: "distributed-processing"
type: "map-reduce"
splitter:
agent: "task-splitter"
action: "split"
strategy: "by-chunk" # or "by-key", "by-hash"
chunk_size: 1000
mapper:
agent: "data-processor"
action: "process"
parallelism: 5
reducer:
agent: "result-aggregator"
action: "aggregate"
strategy: "sum" # or "merge", "concat"
```
---
## Template 6: State Machine Workflow
### Description
State-transition-based workflow, suitable for complex business logic.
### Applicable Scenarios
- Order lifecycle management
- Approval processes
- Complex business state management
### Flow Diagram
```
┌──────┐
┌────┤Init ├────┐
│ └──┬───┘ │
▼ ▼ ▼
[Pending] [Processing] [Completed]
│ │ │
└────┬────┴────┬─────┘
▼ ▼
[Failed] [Cancelled]
```
### Configuration Example
```yaml
workflow:
name: "order-lifecycle"
type: "state-machine"
initial_state: "created"
states:
- name: "created"
entry_action:
agent: "order-manager"
action: "initialize"
transitions:
- event: "submit"
to: "pending_payment"
- name: "pending_payment"
entry_action:
agent: "payment-service"
action: "request-payment"
transitions:
- event: "payment_success"
to: "processing"
- event: "payment_failed"
to: "failed"
- event: "timeout"
to: "cancelled"
- name: "processing"
entry_action:
agent: "fulfillment-service"
action: "process-order"
transitions:
- event: "shipped"
to: "shipped"
- event: "error"
to: "failed"
- name: "shipped"
transitions:
- event: "delivered"
to: "completed"
- name: "completed"
final: true
- name: "failed"
final: true
entry_action:
agent: "notification-service"
action: "notify-failure"
- name: "cancelled"
final: true
```
---
## Template 7: Dynamic Workflow
### Description
Workflow structure is dynamically determined at runtime.
### Applicable Scenarios
- Adaptive processes
- Intelligent routing
- Complex dependency resolution
### Configuration Example
```yaml
workflow:
name: "adaptive-processing"
type: "dynamic"
planner:
agent: "workflow-planner"
action: "plan"
input: "$request"
executor:
dynamic_steps: "$planner.output.steps"
error_handler:
agent: "error-recovery"
action: "recover"
retry_policy:
max_retries: 3
backoff: "exponential"
```
---
## Error Handling Patterns
### Retry Pattern
```yaml
error_handling:
retry:
max_attempts: 3
delay: 5
backoff: "exponential"
retryable_errors: ["timeout", "connection_error"]
```
### Fallback Pattern
```yaml
error_handling:
fallback:
enabled: true
fallback_agent: "simple-handler"
fallback_action: "basic-process"
```
### Compensation Pattern
```yaml
error_handling:
compensation:
enabled: true
steps:
- agent: "cleanup-service"
action: "rollback"
- agent: "notification-service"
action: "notify-failure"
```
---
## Monitoring and Tracing
### Metric Collection
```yaml
monitoring:
metrics:
- workflow_duration
- step_duration
- success_rate
- error_rate
- retry_count
```
### Log Tracing
```yaml
monitoring:
tracing:
enabled: true
correlation_id: true
span_tracking: true
```
FILE:assets/templates/agent-config-template.yaml
# Agent Configuration File Template
system:
name: "multi-agent-system"
version: "1.0.0"
description: "System description"
# Agent Definitions
agents:
- id: "coordinator"
name: "Coordinator"
description: "Responsible for overall coordination and task distribution"
type: "coordinator"
capabilities:
- task_dispatch
- state_management
- error_handling
config:
max_concurrent_tasks: 100
heartbeat_interval: 30
endpoints:
- name: "dispatch"
path: "/api/dispatch"
method: "POST"
- name: "status"
path: "/api/status"
method: "GET"
- id: "worker-1"
name: "Worker Node 1"
description: "Responsible for data processing"
type: "worker"
capabilities:
- data_processing
- validation
config:
queue_size: 50
timeout: 30
dependencies:
- coordinator
endpoints:
- name: "process"
path: "/api/process"
method: "POST"
- id: "worker-2"
name: "Worker Node 2"
description: "Responsible for result analysis"
type: "worker"
capabilities:
- analysis
- report_generation
config:
queue_size: 30
timeout: 60
dependencies:
- coordinator
- worker-1
endpoints:
- name: "analyze"
path: "/api/analyze"
method: "POST"
# Communication Configuration
communication:
protocol: "websocket"
host: "localhost"
port: 8080
message_format:
type: "json"
schema: "message-schema.json"
reliability:
delivery: "at_least_once"
ordering: "preserve_order"
security:
authentication: "jwt"
encryption: "tls"
# Workflow Definitions
workflows:
- id: "main-workflow"
name: "Main Workflow"
description: "Main system processing flow"
type: "sequential"
steps:
- id: "step-1"
name: "Task Dispatch"
agent: "coordinator"
action: "dispatch"
input_mapping:
request: "$input.request"
output_mapping:
task_id: "$output.task_id"
- id: "step-2"
name: "Data Processing"
agent: "worker-1"
action: "process"
input_mapping:
data: "$step-1.output.data"
output_mapping:
result: "$output.processed_data"
retry:
max_attempts: 3
delay: 5
- id: "step-3"
name: "Result Analysis"
agent: "worker-2"
action: "analyze"
input_mapping:
data: "$step-2.output.result"
output_mapping:
report: "$output.analysis_report"
error_handling:
strategy: "retry_then_fallback"
fallback:
agent: "coordinator"
action: "handle_error"
# Monitoring Configuration
monitoring:
enabled: true
metrics:
- name: "task_duration"
type: "histogram"
labels: ["agent", "task_type"]
- name: "task_count"
type: "counter"
labels: ["agent", "status"]
- name: "agent_health"
type: "gauge"
labels: ["agent_id"]
logging:
level: "info"
format: "json"
output: "stdout"
tracing:
enabled: true
sampler: "probability"
sample_rate: 0.1
# Resource Limits
resources:
coordinator:
cpu: "1"
memory: "2Gi"
worker:
cpu: "2"
memory: "4Gi"
replicas: 3
FILE:assets/templates/system-design-template.md
# Multi-Agent System Design Proposal
## 1. Project Overview
### 1.1 Project Background
[Describe the project background and business scenario]
### 1.2 Objectives and Scope
- **Objectives**: [Core goals the system aims to achieve]
- **Scope**: [What is included and what is excluded]
### 1.3 Constraints
- Performance requirements: [Response time, throughput, etc.]
- Reliability requirements: [Availability metrics, fault tolerance requirements]
- Security requirements: [Authentication, authorization, data protection]
---
## 2. System Architecture
### 2.1 Architecture Selection
- **Architecture Pattern**: [Star / Bus / Mesh / Hierarchical / Pipeline / Hybrid]
- **Selection Rationale**: [Why this architecture was chosen]
### 2.2 Architecture Diagram
```
[Insert architecture diagram here]
```
### 2.3 Agent Role Definitions
| Agent Name | Responsibility | Input | Output | Dependencies |
|------------|---------------|-------|--------|-------------|
| Agent-A | [Responsibility description] | [Input data] | [Output results] | [Dependent agents] |
| Agent-B | [Responsibility description] | [Input data] | [Output results] | [Dependent agents] |
---
## 3. Communication Design
### 3.1 Communication Protocol
- **Transport Protocol**: [HTTP / WebSocket / gRPC / MQTT, etc.]
- **Message Format**: [JSON / Protobuf / Avro, etc.]
- **Communication Mode**: [Synchronous / Asynchronous / Streaming]
### 3.2 Message Definition
```json
{
"message_id": "uuid",
"sender": "agent-id",
"receiver": "agent-id",
"message_type": "request|response|event",
"payload": {}
}
```
### 3.3 Interface Specification
#### Agent-A Interface
```yaml
endpoints:
- name: "process_data"
method: "POST"
input: "DataRequest"
output: "DataResponse"
timeout: 30s
```
---
## 4. Task Decomposition
### 4.1 Task Structure
```
[Main Task]
├── [Sub-task 1]
│ ├── [Sub-sub-task 1.1]
│ └── [Sub-sub-task 1.2]
├── [Sub-task 2]
└── [Sub-task 3]
```
### 4.2 Task Assignment
| Task ID | Task Name | Responsible Agent | Dependent Tasks | Estimated Duration |
|---------|-----------|------------------|-----------------|--------------------|
| T1 | [Task description] | Agent-A | - | 5s |
| T2 | [Task description] | Agent-B | T1 | 3s |
### 4.3 Dependency Graph
```
[T1] ──► [T2] ──┬──► [T4]
│
[T3] ───────────┘
```
---
## 5. Workflow Design
### 5.1 Main Workflow
```yaml
workflow:
name: "main-workflow"
type: "[sequential|parallel|conditional]"
steps:
- [Step definition]
```
### 5.2 Exception Handling
- **Retry Strategy**: [Retry count, interval, backoff strategy]
- **Fallback Plan**: [Contingency plan upon failure]
- **Compensation Mechanism**: [Transaction rollback strategy]
---
## 6. Data Design
### 6.1 Data Flow
```
[Data Source] → [Agent-A] → [Agent-B] → [Data Store]
```
### 6.2 Data Formats
#### Input Data
```json
{
"field1": "Type: Description",
"field2": "Type: Description"
}
```
#### Output Data
```json
{
"result": "Type: Description",
"metadata": "Type: Description"
}
```
---
## 7. Non-Functional Design
### 7.1 Performance Design
- Concurrency: [Concurrency count, thread pool configuration]
- Caching Strategy: [Cache location, expiration policy]
- Load Balancing: [Strategy, implementation approach]
### 7.2 Reliability Design
- Fault Tolerance: [Fault detection, automatic recovery]
- Circuit Breaking & Degradation: [Trigger conditions, degradation strategy]
- Rate Limiting: [Algorithm, thresholds]
### 7.3 Observability
- Logging: [Log level, format, collection]
- Monitoring: [Metric definitions, alert rules]
- Tracing: [Distributed tracing implementation]
---
## 8. Deployment Plan
### 8.1 Deployment Architecture
```
[Deployment architecture diagram]
```
### 8.2 Resource Configuration
| Component | Instances | CPU | Memory | Storage |
|-----------|----------|-----|--------|---------|
| Agent-A | 2 | 1 core | 2GB | 10GB |
| Agent-B | 3 | 2 cores | 4GB | 20GB |
### 8.3 Environment Configuration
- Development Environment: [Configuration details]
- Testing Environment: [Configuration details]
- Production Environment: [Configuration details]
---
## 9. Testing Strategy
### 9.1 Unit Testing
- [Test scope and strategy]
### 9.2 Integration Testing
- [Test scenarios and cases]
### 9.3 Performance Testing
- [Test metrics and benchmarks]
---
## 10. Risk Assessment
| Risk | Probability | Impact | Mitigation |
|------|-------------|--------|------------|
| [Risk description] | High / Medium / Low | High / Medium / Low | [Countermeasure] |
---
## Appendix
### A. Glossary
- [Term]: [Definition]
### B. References
- [Reference document links]
### C. Change Log
| Version | Date | Change Description | Author |
|---------|------|-------------------|--------|
| 1.0 | [Date] | Initial version | [Author] |
FILE:assets/examples/code-review-system.md
# Example: Intelligent Code Review System
## Scenario Description
Build a multi-agent collaborative code review system that simulates the code review process of a real development team.
## System Architecture
### Architecture Diagram
```
┌──────────────┐
│ Code Commit │
└──────┬───────┘
│
▼
┌──────────────┐
│ Coordinator │
└──────┬───────┘
│
┌────────────────┼────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────┐ ┌──────────────┐ ┌──────────────┐
│ Architect │ │ Security │ │ Style │
└──────┬───────┘ └──────┬───────┘ └──────┬───────┘
│ │ │
└────────────────┼────────────────┘
│
▼
┌──────────────┐
│ Aggregator │
└──────┬───────┘
│
▼
┌──────────────┐
│ Review Report│
└──────────────┘
```
### Agent Role Definitions
#### 1. Coordinator
- **Responsibility**: Receive code submissions, distribute review tasks, coordinate agent work
- **Input**: Code submission information (PR, commit, branch, etc.)
- **Output**: Review task assignments
- **Capabilities**: Task scheduling, state management, timeout control
#### 2. Architect Agent
- **Responsibility**: Review code architecture design, design pattern application, module dependencies
- **Input**: Code changes, project structure
- **Output**: Architecture review comments
- **Check Items**:
- Appropriate use of design patterns
- Reasonable module coupling
- Specification compliance of interface design
- Scalability considerations
#### 3. Security Agent
- **Responsibility**: Vulnerability scanning, sensitive information detection, permission checks
- **Input**: Code changes
- **Output**: Security review comments
- **Check Items**:
- SQL injection risks
- XSS vulnerabilities
- Sensitive information exposure
- Unsafe dependencies
- Permission control flaws
#### 4. Style Agent
- **Responsibility**: Code style checking, naming conventions, comment reviews
- **Input**: Code changes
- **Output**: Style review comments
- **Check Items**:
- Code formatting standards
- Naming conventions
- Comment completeness
- Code complexity
#### 5. Aggregator Agent
- **Responsibility**: Aggregate review results from all agents and generate a unified report
- **Input**: Review comments from each agent
- **Output**: Structured review report
- **Capabilities**: Deduplication, priority sorting, recommendation consolidation
## Workflow
```yaml
workflow:
name: "code-review-workflow"
type: "parallel"
steps:
- id: "receive"
name: "Receive Code"
agent: "coordinator"
action: "receive_code"
- id: "distribute"
name: "Distribute Review"
agent: "coordinator"
action: "dispatch_review"
parallel_branches:
- id: "architect-review"
agent: "architect-agent"
action: "review_architecture"
- id: "security-review"
agent: "security-agent"
action: "review_security"
- id: "style-review"
agent: "style-agent"
action: "review_style"
- id: "aggregate"
name: "Aggregate Report"
agent: "aggregator-agent"
action: "aggregate_report"
input:
architect_result: "$architect-review.output"
security_result: "$security-review.output"
style_result: "$style-review.output"
- id: "deliver"
name: "Deliver Report"
agent: "coordinator"
action: "deliver_report"
input:
report: "$aggregate.output"
```
## Communication Protocol
### Message Format
```json
{
"message_id": "uuid",
"timestamp": "2024-01-01T00:00:00Z",
"sender": "agent-id",
"receiver": "agent-id",
"message_type": "review_request|review_response|review_event",
"correlation_id": "uuid",
"payload": {
"code_changes": {
"files": ["src/main.py", "src/utils.py"],
"diff": "...",
"metadata": {
"author": "[email protected]",
"commit_id": "abc123",
"branch": "feature/new-feature"
}
},
"review_result": {
"issues": [
{
"severity": "high|medium|low",
"category": "architecture|security|style",
"file": "src/main.py",
"line": 42,
"message": "Issue description",
"suggestion": "Improvement suggestion"
}
],
"summary": "Review summary"
}
}
}
```
## Task Decomposition
```
Code Review Task
├── Architecture Review
│ ├── Design pattern check
│ ├── Module dependency analysis
│ └── Interface design review
├── Security Review
│ ├── Vulnerability scanning
│ ├── Sensitive information detection
│ └── Dependency security check
└── Style Review
├── Code style check
├── Naming convention check
└── Comment completeness check
```
## Output Example
### Review Report
```json
{
"review_id": "review-123",
"timestamp": "2024-01-01T00:00:00Z",
"code_info": {
"commit_id": "abc123",
"author": "[email protected]",
"files_changed": 3
},
"summary": {
"total_issues": 5,
"high_severity": 1,
"medium_severity": 2,
"low_severity": 2,
"status": "needs_fix"
},
"issues": [
{
"id": "SEC-001",
"severity": "high",
"category": "security",
"agent": "security-agent",
"file": "src/auth.py",
"line": 45,
"message": "SQL injection risk detected",
"suggestion": "Use parameterized queries instead of string concatenation",
"code_snippet": "..."
},
{
"id": "ARC-001",
"severity": "medium",
"category": "architecture",
"agent": "architect-agent",
"file": "src/service.py",
"line": 78,
"message": "Class has multiple responsibilities; consider splitting",
"suggestion": "Separate business logic from data access"
}
],
"recommendations": [
"Fix high-priority security issues",
"Refactor overly complex functions",
"Add unit tests"
]
}
```
## Scalability Considerations
1. **New Review Dimensions**: Easily add agents for performance review, test coverage, etc.
2. **Customizable Rules**: Each agent's rules are configurable to suit different project requirements
3. **CI/CD Integration**: Can integrate with code repositories such as GitHub/GitLab
4. **Learning Capability**: Agents can learn from historical review data to improve accuracyBased on two core tools, sessions_spawn and sessions_send, to help users build, manage, and optimize distributed Agent systems, enabling task decomposition,...
---
name: multi-agent-communication
description: Based on two core tools, sessions_spawn and sessions_send, to help users build, manage, and optimize distributed Agent systems, enabling task decomposition, parallel processing, and efficient coordination among Agents.
---
# Multi-Agent Communication
Core tools: `sessions_spawn` (launch child Agents) and `sessions_send` (send messages to existing Agents).
## Use Cases
- Launching child Agents for background tasks
- Multi-Agent collaboration and negotiation
- Configuring Agent permissions and concurrency limits
- Choosing the appropriate communication mode (run/session/send)
- Designing Agent team workflows
## Two Core Tools
### sessions_spawn — Create a new Agent instance
```
sessions_spawn({
task: "Review PR #123",
agent: "code-reviewer", // Agent ID (not SOUL name)
mode: "run", // run=one-shot, session=persistent
thread: false, // Whether to bind to a message thread
runTimeoutSeconds: 300 // Optional, timeout duration
})
```
**Essence: Fork a new process.** Creates an independent session and execution environment, automatically pushing results back to the parent Agent upon completion. In mode="run", the child Agent's execution process is not visible to the user by default.
### sessions_send — Send a message to an existing Agent
```
sessions_send({
sessionKey: "agent:main:subagent:abc",
label: "security", // Use sessionKey or label
message: "Check security",
timeoutSeconds: 30 // Synchronous wait; 0=asynchronous delivery
})
```
**Essence: Inter-Process Communication (IPC).** Sends messages to an existing session, supporting multi-round A2A negotiation (up to 5 rounds of ping-pong).
## Core Decision: Which One to Choose?
| Scenario | Tool | Mode |
|----------|------|------|
| Background data processing, one-shot analysis | sessions_spawn | mode: "run" |
| Parallel task decomposition (multiple spawns) | sessions_spawn | mode: "run" |
| Multi-round code review (user-visible) | sessions_spawn | mode: "session", thread: true |
| Real-time collaborative Q&A between Agents | sessions_send | timeoutSeconds > 0 |
| Asynchronous delivery, no reply needed | sessions_send | timeoutSeconds: 0 |
**Quick Judgment:**
- Need to **create a new Agent** → sessions_spawn
- Need to communicate with an **existing Agent** → sessions_send
## Spawn Execution Flow (10 Stages)
```
User Request → Main Agent → sessions_spawn
↓
[1. Permission Check] → Verify depth, concurrency, whitelist
↓
[2. Session Creation] → Generate unique sessionKey
↓
[3. Thread Binding] → (Optional) Bind to Discord/Slack thread
↓
[4. Attachment Handling] → Snapshot transfer (independent lifecycle)
↓
[5. System Prompt] → Inject task context
↓
[6. Working Directory] → Inherit parent Agent or use target Agent config
↓
[7. Agent Launch] → Via Gateway RPC
↓
[8. Runtime Registration] → Record in SubagentRegistry
↓
[9. Hook Trigger] → Notify plugins
↓
[10. Result Return] → Return childSessionKey
```
Results are automatically pushed back to the parent Agent via Sweeper (checks every 1-8 seconds), no manual polling required.
## Session Key Design
```
Main Agent: agent:main:main
Child Agent: agent:main:subagent:<uuid>
Grandchild: agent:main:subagent:<uuid>:subagent:<uuid>
```
UUID ensures global uniqueness; the hierarchical structure facilitates routing and traceability.
## mode="run" vs. mode="session"
| Feature | run | session |
|---------|-----|---------|
| Lifecycle | One-shot, deleted upon completion | Persistent, awaits subsequent messages |
| Thread Binding | Not supported | Required (thread=true) |
| User Visibility | ❌ Completely invisible | ✅ Visible in thread |
| Applicable Scenarios | Background data processing | Multi-turn conversations, code reviews |
**⚠️ Note: mode="session" must also have thread=true set**, otherwise subsequent messages cannot be routed correctly.
## Three-Tier Security Protection
| Constraint | Default Value | Purpose |
|------------|---------------|---------|
| Max Recursion Depth | 1 | Prevent infinite recursion |
| Max Child Processes | 5/session | Prevent resource exhaustion |
| Whitelist Mechanism | Configurable | Cross-Agent permission control |
## A2A Multi-Round Negotiation (sessions_send)
```
Agent A ──"Format this code"──→ Agent B
←─"Which style do you prefer?"
Agent A ──"Use Prettier"─────→ Agent B
←─"Done"
Agent A ──REPLY_SKIP──────────→ Agent B
```
- Maximum 5 rounds (configurable)
- Either party replies with REPLY_SKIP_TOKEN to end
- Final result delivered to the user channel
## Key Design Decisions
- **Snapshots over References**: Attachments are copied to the child Agent; the child can still access them even after the parent deletes them.
- **Push over Polling**: Zero polling cost; a 30-second task saves approximately 15,000 tokens.
- **Cross-Agent Workspace Isolation**: Same-type child Agents inherit the parent directory; cross-type ones use the target Agent's configuration.
## Configuration Suggestions
See [references/config.md](references/config.md) for details.
## Design Patterns
See [references/patterns.md](references/patterns.md) for details.
FILE:references/config.md
# Agent Configuration Reference
## Basic Configuration
```json5
{
agents: {
defaults: {
subagents: {
maxSpawnDepth: 1, // Child Agent depth (recommended 1-2)
maxChildrenPerAgent: 5, // Max parallel child processes
runTimeoutSeconds: 300 // Default timeout of 5 minutes
}
},
list: [
{
id: "main",
subagents: {
allowAgents: ["code-reviewer", "doc-writer"] // Whitelist
}
}
]
},
session: {
agentToAgent: {
enabled: true,
allow: ["*"], // Allow all cross-Agent communication
maxPingPongTurns: 5 // A2A negotiation capped at 5 rounds
}
}
}
```
## Advanced Configuration (Complex Tasks)
```json5
{
agents: {
defaults: {
subagents: {
maxSpawnDepth: 2, // Two levels of nesting
maxChildrenPerAgent: 10, // More parallel processes
runTimeoutSeconds: 600 // 10-minute timeout
}
}
}
}
```
## Permission Configuration (Whitelist)
```json5
{
agents: {
list: [
{
id: "main",
subagents: {
allowAgents: ["analyzer", "reviewer", "writer"] // Only allow these child Agents
}
}
]
}
}
```
## Constraint Type Summary
| Constraint | Type | Default | Purpose |
|------------|------|---------|---------|
| maxSpawnDepth | int | 1 | Prevent infinite recursion |
| maxChildrenPerAgent | int | 5 | Prevent resource exhaustion |
| allowAgents | string[] | Configurable | Whitelist permission control |
| runTimeoutSeconds | int | 300 | Single task timeout |
| maxPingPongTurns | int | 5 | A2A negotiation round cap |
FILE:references/patterns.md
# Design Pattern Reference
## Fork-Join (Parallel Processing)
Multiple child Agents process sharded tasks in parallel, with results aggregated before replying to the user.
```
Main Agent
├─ spawn analyzer-1 (Shard A) ──→ [1. announcement]
├─ spawn analyzer-2 (Shard B) ──→ [2. announcement]
└─ spawn analyzer-3 (Shard C) ──→ [3. announcement]
↓
Aggregate results → Reply to user
```
**Applicable Scenarios:** Parallel data analysis, large file shard processing, batch review.
## Master-Worker (Master-Slave Collaboration)
Create persistent expert Agents; the main Agent queries each expert and synthesizes their opinions.
```javascript
// 1. Create expert Agents (persistent)
sessions_spawn({ agent: "security-expert", label: "security", mode: "session" });
sessions_spawn({ agent: "perf-expert", label: "performance", mode: "session" });
// 2. Main Agent queries the experts
const security = await sessions_send({ label: "security", message: "Are there any security risks?" });
const perf = await sessions_send({ label: "performance", message: "Where are the performance bottlenecks?" });
// 3. Synthesize expert opinions
return synthesize(security, perf);
```
**Applicable Scenarios:** Code requires both security and performance reviews, multi-dimensional evaluation.
## Pipeline (Assembly Line)
At each stage, spawn an Agent; the output of one serves as the input for the next, akin to a factory assembly line.
```
PDF → Extractor ─→ Raw Text → Cleaner ─→ Clean Text → Summarizer ─→ Summary
(spawn) (spawn) (spawn)
```
**Applicable Scenarios:** Data processing pipelines, multi-stage content refinement.
## Comparative Summary
| Pattern | Spawn Count | Parallel | Communication Method | Typical Scenario |
|---------|-------------|----------|----------------------|------------------|
| Fork-Join | N in parallel | ✅ | announcement | Parallel data analysis |
| Master-Worker | N persistent | ❌ | sessions_send | Expert collaboration |
| Pipeline | N sequential | ❌ | announce chaining | Multi-stage processing |For browser automation tasks, web data scraping, form filling, page screenshots, UI testing, and more.
--- name: agent-browser-assistant description: For browser automation tasks, web data scraping, form filling, page screenshots, UI testing, and more. --- # Agent Browser Assistant An intelligent browser control assistant providing browser automation, data scraping, and testing capabilities. ## Use Cases Opening web pages, clicking/typing/scrolling, taking screenshots/recordings, extracting web content, exporting table data, automated form filling, batch operations, scheduled tasks, login authentication, UI testing, regression testing. ## Quick Start Use the `browser` tool for all browser operations: ```python # Open a web page browser(action="open", url="https://example.com") # Take a screenshot browser(action="screenshot") # Click an element browser(action="act", kind="click", ref="button-submit") # Type text browser(action="act", kind="type", ref="input-username", text="[email protected]") # Scroll the page browser(action="act", kind="scroll", y=500) # Get a page snapshot browser(action="snapshot") ``` ## Core Capabilities ### 1. Page Operations | Operation | Description | Example | |-----------|-------------|---------| | open | Open a specified URL | `action="open", url="..."` | | snapshot | Get page structure | `action="snapshot"` | | screenshot | Take a page screenshot | `action="screenshot"` | | navigate | Navigate to a URL | `action="navigate", url="..."` | | close | Close a tab | `action="close", targetId="..."` | ### 2. Element Interaction Use the `act` operation for page interaction: - **click**: Click an element (ref: element reference) - **type**: Type text (ref: input reference, text: content) - **press**: Press a keyboard key (key: key name) - **hover**: Hover over an element - **select**: Select from a dropdown - **fill**: Fill a form (fields: field dictionary) - **scroll**: Scroll the page (x/y: coordinates) ### 3. Data Scraping Extract data from web pages: ```python # Get a page snapshot to analyze structure browser(action="snapshot") # Extract table data - using selector browser(action="act", kind="evaluate", selector="table.data", fn="Array.from(document.querySelectorAll('tr')).map(r => Array.from(r.querySelectorAll('td')).map(c => c.innerText))") ``` ### 4. Automated Workflows Automated form filling: ```python browser(action="act", kind="fill", fields=[ {"ref": "input-email", "value": "[email protected]"}, {"ref": "input-password", "value": "password123"} ]) browser(action="act", kind="click", ref="button-login") ``` Batch operations: ```python # Iterate through list items for i in range(1, 6): browser(action="act", kind="click", ref=f"item-{i}") ``` ### 5. Testing Capabilities UI testing scenarios: - Regression Testing: Verify that page functionality works correctly - Performance Monitoring: Page load time - Element Existence Check: Verify that key elements are visible ## Advanced Usage ### Waiting for Page Load ```python browser(action="act", kind="wait", loadState="domcontentloaded", timeMs=5000) ``` ### Handling Dialogs ```python browser(action="dialog", kind="accept") # Confirm # or browser(action="dialog", kind="dismiss") # Cancel ``` ### File Upload ```python browser(action="upload", ref="input-file", paths=["C:/path/to/file.pdf"]) ``` ### PDF Export ```python browser(action="pdf", path="C:/output/page.pdf") ``` ## Configuration Options | Parameter | Description | Default | |-----------|-------------|---------| | profile | Browser profile | "openclaw" | | target | Browser target | "sandbox" | | slowly | Slow motion mode | false | | timeoutMs | Timeout duration | 30000 | ## Common Selector Patterns - Button: `button[type="submit"]`, `#submit-btn` - Input: `input[name="email"]`, `#username` - Link: `a[href*="login"]` - Table: `table.data tr` - List: `.item-list li` ## Notes 1. Use `snapshot` to get page structure before performing element operations 2. Dynamic content may require waiting for it to finish loading 3. For logged-in state operations, use `profile="user"` to reuse the user's browser 4. For large-scale data scraping, consider pagination to avoid timeouts
Use when users need to optimize prompts for AI conversations, generate structured templates, create few-shot examples, design chain-of-thought guidance, or d...
--- name: ai-prompt-optimization description: Use when users need to optimize prompts for AI conversations, generate structured templates, create few-shot examples, design chain-of-thought guidance, or diagnose and improve existing prompts. Applicable to prompt optimization for various AI tools such as ChatGPT, Claude, Midjourney, etc. --- # AI Prompt Optimization ## Core Capabilities When users seek prompt optimization assistance, provide the following services: 1. **Diagnosis & Optimization** - Analyze existing prompt issues and provide specific improvement plans 2. **Template Generation** - Generate structured prompt templates for different scenarios 3. **Few-Shot Generation** - Create example-driven few-shot prompts 4. **Chain-of-Thought Guidance** - Design CoT (Chain of Thought) prompts ## Usage ### 1. Diagnosis & Optimization Workflow When a user provides a prompt for optimization: ``` Analyze Structure → Identify Issues → Provide Improved Version → Explain Changes ``` **Diagnosis Checklist**: - [ ] Is the role/identity clearly defined? - [ ] Is the task objective specific and clear? - [ ] Are output format/style constrained? - [ ] Is the necessary context/background information provided? - [ ] Are boundary conditions and exceptions specified? - [ ] Are there clear success criteria? ### 2. Template Generation Generate structured templates based on user scenarios. Core template format: ``` # Role Definition You are a [role] in [professional domain], skilled at [core competency]. # Task Description Please help me [specific task], with the goal of [expected outcome]. # Context Information - Background: [relevant background] - Audience: [target users] - Constraints: [boundary conditions] # Output Requirements - Format: [desired format] - Style: [language style] - Length: [length requirement] # Quality Standards [Key metrics for evaluating output] ``` ### 3. Few-Shot Example Generation Generate few-shot examples for complex tasks: 1. **Select Representative Samples** - 3-5 examples covering different variants 2. **Format Examples** - Input → Output structure 3. **Add Explanations** - Explain the rationale for selecting each example ### 4. Chain-of-Thought Design Design CoT prompts for tasks requiring reasoning: ``` Before giving your final answer, please think through the following steps: 1. [Understand the Problem] - ... 2. [Decompose the Problem] - ... 3. [Step-by-Step Reasoning] - ... 4. [Verify the Conclusion] - ... ``` ## Scenario Reference For complete scenario templates and examples, see `references/templates.md`: - Writing assistance prompts - Code generation prompts - Image generation prompts - Data analysis prompts - Q&A and consultation prompts ## Optimization Principles 1. **Specific > Vague** - Clearly specify what is wanted and what is not 2. **Structured > Scattered** - Use clear segmentation and markers 3. **Constrained > Free** - Appropriate constraints improve output quality 4. **Iterative > One-Shot** - Encourage users to continuously optimize based on output FILE:references/templates.md # Prompt Template Reference ## I. Writing Assistance ### Article Writing Template ``` # Role You are a professional content creator in the [domain] field, skilled in [writing style]. # Task Write a [type: article/blog/report] about [topic], targeting [audience]. # Requirements - Topic: [core topic] - Angle: [approach angle] - Word Count: [word count requirement] - Style: [formal/casual/professional] # Structure [Introduction requirements] [Body outline] [Conclusion requirements] # Prohibited - [Content to avoid] ``` ### Translation Optimization Template ``` # Role You are a professional translator proficient in [source language] and [target language]. # Source Text [Content to be translated] # Translation Requirements - Style: [formal/colloquial/literary] - Audience: [target readers] - Terminology: [handling of specialized terms] # Notes [Special translation requirements] ``` ## II. Code Generation ### Code Generation Basic Template ``` # Task Implement [functional requirement] in [programming language]. # Environment - Language Version: [version] - Dependencies: [available libraries] # Functional Requirements 1. [Core functionality] 2. [Edge case handling] # Code Style - Follow [coding standards] - Include necessary [comments/documentation] # Testing [Test case requirements] ``` ### Code Review Template ``` # Role You are a senior [language] development engineer conducting a code review. # Code [Code to be reviewed] # Review Focus - [Security] - [Performance] - [Readability] - [Best practices] # Output Format Issue classification → Specific suggestions → Priority ``` ## III. Image Generation ### Midjourney / Stable Diffusion Prompt Template ``` # Subject [Image subject description] # Style - [Artist style] - [Art movement] - [Era style] # Composition - [Perspective] - [Shot distance] - [Lighting] # Parameters - Aspect Ratio: [16:9/1:1 etc.] - Quality: [HD/Standard] - Render: [Engine selection] # Negative Prompts [Elements to avoid] ``` ### Image Optimization Diagnosis Checklist: 1. Is the subject clearly defined? 2. Is the style description specific? 3. Are lighting and atmosphere specified? 4. Is the composition/perspective indicated? 5. Are elements to avoid clearly stated? ## IV. Data Analysis ### Data Analysis Template ``` # Objective Analyze [dataset/problem] to answer [core question]. # Data [Data source or description] # Analysis Requirements - Method: [statistical/ML/visualization] - Tools: [tool preference] - Depth: [descriptive/diagnostic/predictive] # Output - Summary of conclusions - Key findings - Data visualizations (if needed) - Recommended actions # Constraints - Time Range: [time range] - Data Limitations: [known limitations] ``` ## V. Q&A and Consultation ### Professional Consultation Template ``` # Background [Problem background/context] # Question [Core question] # Attempted Solutions [Solutions already tried] # Constraints - [Budget/time/technical constraints] # Expectations [Desired outcome/answer type] # Additional Information [Any extra information that may be helpful] ``` ## VI. General Optimization Framework ### CRISP Framework - **C**larity: Is the objective clear? - **R**elevance: Is the context sufficient? - **I**nput: Is the necessary information provided? - **S**tructure: Is the organization clear? - **P**recision: Are the constraints explicit? ### Iterative Optimization Prompt ``` # Original Prompt [User-provided prompt] # Diagnosis Results [Identified issues] # Optimized Version [Improved prompt] # Explanation of Changes [Rationale for each change] # Suggested Tests [Sample inputs to test this prompt] ```
Create WeChat public account style business and technology articles with professional yet approachable tone.
--- name: wechat-business-article-writer description: Create WeChat public account style business and technology articles with professional yet approachable tone. --- # WeChat Business Article Writer ## Overview This skill helps create high-quality WeChat public account style articles that blend professional insights with approachable language. The writing style is based on personal observations and experiences, avoiding corporate jargon and AI-generated robotic tones. ## Use Cases - Business observations and tech reviews - Product thinking and analysis - Serious but not rigid professional writing style - Occasional small humor to engage readers - Plain language explanations of complex topics - Avoiding AI-like robotic tone ## Writing Style Guidelines ### Core Style Dimensions 1. **Tone & Position**: Serious professional but not rigid, confident yet humble, authoritative but approachable 2. **Rhetoric & Wording**: Plain language over technical jargon, vivid metaphors, occasional humor 3. **Structure & Rhythm**: Clear logical flow, engaging hooks, conversational pacing 4. **Content Focus**: Business observations, tech reviews, product thinking 5. **Reader Engagement**: Personal perspective, relatable examples, practical insights 6. **Voice Consistency**: Authentic human voice, avoid AI-like perfection ### Key Characteristics - **Professional but not stiff**: Treat complex topics seriously but avoid academic dryness - **Occasional humor**: Small, natural humor to keep readers engaged without being distracting - **Plain language**: Use everyday language to explain technical concepts - **Personal perspective**: Share observations and experiences, not just facts - **Practical insights**: Focus on what readers can learn and apply - **Conversational flow**: Write as if speaking to a knowledgeable friend ## Article Structure Templates ### Standard Business/Tech Article Structure ``` 1. Hook - Interesting observation or question - Personal anecdote or experience - Current industry context 2. Main Content - Clear thesis or main point - Supporting evidence and examples - Analysis and insights - Counterpoints and considerations 3. Practical Takeaways - Actionable insights - Lessons learned - Future implications 4. Conclusion - Summary of key points - Final thought or reflection - Call to action or open question ``` ### Product Review Structure ``` 1. First Impressions - Personal experience with the product - Initial reactions and expectations 2. Detailed Analysis - Strengths and advantages - Weaknesses and limitations - Comparison with alternatives 3. Practical Value - Who should use this - Best use cases - Cost-benefit analysis 4. Final Recommendation - Overall assessment - Specific recommendations - Future outlook ``` ## Writing Process ### Step 1: Define Your Perspective - What's your unique angle or experience? - What observations can you share that others might miss? - What personal insights can you provide? ### Step 2: Structure Your Content - Choose appropriate template based on article type - Plan the flow from hook to conclusion - Identify key points and supporting evidence ### Step 3: Write with Authentic Voice - Use "I" and "we" when sharing personal experiences - Be honest about limitations and uncertainties - Include occasional personal asides and humor - Avoid corporate buzzwords and AI-generated phrases ### Step 4: Edit for Readability - Simplify complex technical concepts - Break up long paragraphs - Use conversational transitions - Ensure natural flow between ideas ## References See [WRITING_GUIDELINES.md](references/writing_guidelines.md) for detailed writing principles and examples. ## Common Pitfalls to Avoid - **AI-like tone**: Avoid overly formal, perfect, or robotic language - **Corporate jargon**: Use plain language instead of business buzzwords - **Pure information**: Always add personal perspective and insights - **Academic dryness**: Keep it engaging and conversational - **Excessive humor**: Use humor sparingly and naturally - **Lack of depth**: Balance accessibility with substantive content ## Quality Checklist Before publishing, ensure your article: - [ ] Has an engaging hook that draws readers in - [ ] Uses plain language to explain complex concepts - [ ] Includes personal perspective and experiences - [ ] Provides practical, actionable insights - [ ] Maintains consistent, authentic voice throughout - [ ] Occasional natural humor (not forced) - [ ] Clear structure with logical flow - [ ] Avoids AI-generated corporate-speak FILE:references/writing_guidelines.md # Writing Guidelines for WeChat Business Articles ## Core Principles ### 1. Authentic Voice - Write as a human, not an AI - Share personal experiences and observations - Be honest about limitations and uncertainties - Use natural, conversational language ### 2. Professional Yet Approachable - Take content seriously but avoid academic dryness - Balance authority with accessibility - Respect readers' intelligence without being condescending ### 3. Plain Language Over Jargon - Use everyday language instead of technical terms - Explain complex concepts simply - Avoid corporate buzzwords and AI-generated phrases - Create vivid metaphors and analogies ## Writing Techniques ### Opening Hooks **Good examples:** - "Recently, while working on a project, I suddenly realized..." - "I remember the first time I encountered XX, I made an amusing mistake..." - "There's a phenomenon in this industry that has always puzzled me..." **Avoid:** - "In today's digital era..." - "With the rapid development of technology..." - "As we all know..." ### Transitions and Flow **Natural transitions:** - "Speaking of which, the root of this problem is actually quite simple..." - "Interestingly, I discovered..." - "Looking at it from another angle, this actually reflects..." - "Speaking of this, I can't help but mention..." **Avoid robotic transitions:** - "First, second, third..." - "In summary..." - "Therefore, we can conclude..." ### Adding Humor **Natural humor:** - Self-deprecating comments about mistakes - Relatable industry anecdotes - Light-hearted observations about common pitfalls - Playful metaphors **Examples:** - "At that time, I was like a new driver who couldn't tell the accelerator from the brake..." - "The designer of this feature has probably never actually used the product..." - "Every time I see this data, I can't help but think of that old saying..." ### Explaining Complex Topics **Effective approaches:** - Use personal experience as a teaching tool - Create relatable analogies - Share "aha!" moments from your journey - Break down concepts step by step **Example:** "Blockchain technology isn't really that mysterious. Think of it like a public ledger that everyone can view, but modifying it requires everyone's agreement..." ## Voice Patterns to Adopt ### Conversational First Person - "I discovered..." - "My experience is..." - "This made me think of..." - "To be honest, I also... at first..." ### Engaging Second Person - "You might have also encountered..." - "Imagine if you..." - "Next time you encounter this, try..." ### Balanced Authority - "Based on my experience..." - "Data shows..." - "The industry generally believes..." - "My personal view is..." ## Common AI Traps to Avoid ### Overly Formal Language **Avoid:** - "In summary, we can conclude that..." - "Based on the above analysis, the following recommendations are made..." - "It is worth noting that..." **Use instead:** - "Ultimately, it comes down to..." - "My advice is..." - "Interestingly..." ### Perfect Corporate Tone **Avoid:** - "Empower," "leverage," "close the loop" - "Maximize," "optimize" - "Strategic level," "execution level" **Use instead:** - "What can actually help you is..." - "How to do it better..." - "In the long run..." ### Excessive Objectivity **Avoid:** - "Research shows..." - "As is widely known..." - "Experts believe..." **Use instead:** - "I've observed..." - "Based on my experience..." - "Interestingly, I've found..." ## Emotional Connection ### Building Rapport - Share struggles and failures - Admit when you don't know - Show vulnerability appropriately - Be genuinely helpful ### Creating Engagement - Ask rhetorical questions - Invite readers to share their experiences - Use "we" language to create community - Show genuine curiosity about reader perspectives ## Language Examples ### Before (AI-like) "In the context of the current digital transformation, enterprises need to rethink their business models and enhance competitiveness through technological innovation." ### After (Human-like) "Recently, while helping a few friends with their digital projects, I noticed something interesting: many companies are throwing money at various tools without really figuring out what problems they're trying to solve. Ultimately, technology is just a means, not the end." ### Before (Corporate) "Based on market research data analysis, we have identified significant differences in target user groups' demands for product features." ### After (Conversational) "While chatting with users, I discovered something fascinating: what you think users want in terms of features is often not what they really need. Last time, a client said 'I want more complex reports.' After talking for a while, it turned out he just wanted simple data that he could understand at a glance." ## Rhythm and Flow ### Sentence Variety Mix short, punchy sentences with longer, explanatory ones: - "This feature is important." (Short, direct) - "Speaking of which, there's actually a lot of thought behind this feature, balancing user experience, technical implementation, and business value." (Longer, explanatory) ### Paragraph Length Keep paragraphs short (2-4 sentences) for readability: - "This decision seems simple, but its impact is far-reaching." - "I didn't realize this at the time, and only later came to understand the reasoning behind it." - "That's why I always suggest people think a few levels deeper when making technical choices." ### Reading Pacing Vary the pace to maintain engagement: - Fast pace for exciting discoveries - Slow pace for important insights - Conversational pace for explanations ## Cultural Nuances for Chinese WeChat ### Local References - Use Chinese idioms appropriately - Reference local business contexts - Understand Chinese reader expectations - Balance international concepts with local relevance ### Platform-Specific Considerations - Mobile reading experience - Attention span optimization - Shareability and engagement triggers - Visual content integration possibilities ## Practice Exercises 1. **Rewrite corporate statements** in plain language 2. **Add personal anecdotes** to technical explanations 3. **Create conversational hooks** instead of formal introductions 4. **Practice explaining complex concepts** using everyday analogies 5. **Develop authentic voice** through regular writing practice
Intelligent task management and execution coordination officer. Automatically generates task lists, intelligently decomposes complex tasks, matches AI agents...
---
name: task-orchestrator
description: Intelligent task management and execution coordination officer. Automatically generates task lists, intelligently decomposes complex tasks, matches AI agents, makes priority decisions, and monitors progress.
---
# Task Orchestrator
End-to-end automated task management: from goals to execution, intelligent decomposition, agent matching, and progress monitoring.
## Use Cases
- User mentions keywords such as "task management," "task planning," "task decomposition," "multi-task parallelism," "task orchestration"
- User needs to decompose complex objectives into executable steps
- User needs multiple Agents to collaborate on work
- User needs to track task progress and resource allocation
- User needs intelligent decision-making for execution order and dependencies.
## Core Capabilities
### 1. Task Parsing and Decomposition
Automatically decompose natural language objectives into a structured task tree:
- **Goal Decomposition**: Break complex objectives into atomic tasks
- **Dependency Identification**: Establish dependency relationships between tasks
- **Effort Estimation**: Estimate execution time based on task complexity
### 2. Intelligent Agent Matching
Match the most suitable execution agent based on task characteristics:
- **Capability Matching**: Select specialized agents based on task type
- **Load Balancing**: Avoid agent overload
- **Cost Optimization**: Balance quality and cost
### 3. Priority Decision-Making
Autonomously decide task execution order:
- **Urgency Assessment**: Based on time constraints and impact scope
- **Value Assessment**: Based on business value and user expectations
- **Dependency Priority**: Ensure dependency chains execute correctly
### 4. Progress Monitoring
Track task execution status in real time:
- **Status Tracking**: Pending, In Progress, Completed, Blocked
- **Anomaly Detection**: Identify timed-out, failed, and blocked tasks
- **Automatic Retry**: Intelligent retry strategy for failed tasks
## Workflow
```
User Goal → Task Parsing → Task Decomposition → Dependency Analysis → Priority Sorting → Agent Matching → Execution → Monitoring → Summary
```
### Step 1: Receive and Parse Goal
Understand user intent and identify core objectives:
- Clarify task boundaries and expected outputs
- Identify time constraints and priority hints
- Confirm available resources and constraints
**Example Dialogue:**
```
User: "Help me complete a product launch, including documentation, testing, and promotional materials"
Orchestrator: Parse goal into 3 main tasks:
1. Product documentation writing (parallelizable)
2. Test case design and execution (depends on partial completion of 1)
3. Promotional material production (parallelizable)
```
### Step 2: Task Decomposition
Use a script to generate a structured task tree:
```bash
python3 scripts/task_decomposer.py --goal "User Goal" --output tasks.json
```
Output structure:
```json
{
"main_goal": "Product Launch",
"tasks": [
{
"id": "T1",
"title": "Write Product Documentation",
"description": "Includes feature descriptions, user guides, and API documentation",
"priority": "high",
"estimated_time": "2h",
"dependencies": [],
"subtasks": [
{"id": "T1.1", "title": "Feature Description Document"},
{"id": "T1.2", "title": "User Guide"},
{"id": "T1.3", "title": "API Interface Documentation"}
],
"required_skills": ["doc-writing-skill"],
"status": "pending"
}
]
}
```
### Step 3: Agent Matching and Resource Allocation
Select execution agents based on task characteristics. See [references/agent_matching.md](references/agent_matching.md) for details.
### Step 4: Execution and Monitoring
Initiate task execution and continuously monitor:
- Execute tasks without dependencies in parallel
- Execute tasks with dependencies serially
- Update task status in real time
- Automatically adjust plans upon anomalies
### Step 5: Result Integration and Feedback
After task completion:
- Integrate execution results from each agent
- Generate an execution report
- Collect feedback to optimize subsequent tasks
## Quick Start
### Scenario 1: Complex Task Decomposition
```
User: "Help me prepare for next week's tech sharing session; I need a PPT, demo code, and a promotional poster"
Orchestrator:
1. Parse Goal → Identify 3 parallel tasks
2. Decompose Tasks → Estimate total effort 8h
3. Match Agents →
- PPT: doc-writing-skill + ppt-parser-local
- Demo: Code generation agent
- Poster: image_generation
4. Suggest Execution Order → PPT outline → demo development → poster design → PPT refinement
```
### Scenario 2: Multi-Agent Collaboration
```
User: "Complete a competitive analysis report; need data scraping, chart generation, and report writing"
Orchestrator:
1. Task Decomposition: Data scraping (T1) → Data analysis (T2) → Chart generation (T3) → Report writing (T4)
2. Dependency Chain: T1→T2→T3→T4
3. Agent Matching:
- T1: web-search + deep-search-skill
- T2: Data analysis agent
- T3: image_generation
- T4: doc-writing-skill
4. Execution Plan: Serial execution, estimated total duration 6h
```
## Decision Framework
### Priority Decision Matrix
| Dimension | Weight | Scoring Criteria |
|-----------|--------|------------------|
| Urgency | 30% | Deadline, blocking impact |
| Value | 40% | Business value, user expectations |
| Cost | 20% | Time cost, resource consumption |
| Risk | 10% | Failure risk, dependency risk |
### Agent Selection Strategy
See [references/agent_matching.md](references/agent_matching.md) for details.
## Resource Files
### scripts/
- `task_decomposer.py` - Task decomposition script, generates structured task tree
- `priority_calculator.py` - Priority calculation script, supports custom weights
- `progress_monitor.py` - Progress monitoring script, tracks task status in real time
### references/
- `agent_matching.md` - Agent matching strategies and capability matrix
- `workflow_patterns.md` - Common workflow patterns and best practices
- `task_templates.md` - Common task template library
### assets/
- `task_plan_template.md` - Task planning document template
- `execution_report_template.md` - Execution report template
FILE:scripts/priority_calculator.py
#!/usr/bin/env python3
"""
Priority Calculator - Priority Calculation Script
Calculates task priority based on multi-dimensional evaluation
"""
import argparse
import json
from datetime import datetime, timedelta
from typing import List, Dict, Any
class PriorityCalculator:
"""Priority Calculator"""
def __init__(self, weights: Dict[str, float] = None):
"""
Initialize Priority Calculator
Args:
weights: Custom weight configuration
"""
self.weights = weights or {
"urgency": 0.30, # Urgency
"value": 0.40, # Value
"cost": 0.20, # Cost (inverse)
"risk": 0.10 # Risk
}
def calculate(self, tasks: List[Dict]) -> List[Dict]:
"""
Calculate task priority scores and sort
Args:
tasks: Task list
Returns:
Sorted task list (including priority scores)
"""
scored_tasks = []
for task in tasks:
score = self._calculate_score(task)
task_with_score = {**task, "priority_score": score}
scored_tasks.append(task_with_score)
# Sort by score in descending order
scored_tasks.sort(key=lambda x: x["priority_score"], reverse=True)
# Update priority labels
for i, task in enumerate(scored_tasks):
if i < len(scored_tasks) * 0.3:
task["priority"] = "high"
elif i > len(scored_tasks) * 0.7:
task["priority"] = "low"
else:
task["priority"] = "medium"
return scored_tasks
def _calculate_score(self, task: Dict) -> float:
"""Calculate priority score for a single task"""
urgency_score = self._evaluate_urgency(task)
value_score = self._evaluate_value(task)
cost_score = self._evaluate_cost(task)
risk_score = self._evaluate_risk(task)
total = (
urgency_score * self.weights["urgency"] +
value_score * self.weights["value"] +
cost_score * self.weights["cost"] +
risk_score * self.weights["risk"]
)
return round(total, 2)
def _evaluate_urgency(self, task: Dict) -> float:
"""Evaluate urgency (0-100)"""
score = 50 # Base score
# Based on deadline
deadline = task.get("deadline")
if deadline:
try:
deadline_dt = datetime.fromisoformat(deadline)
hours_until = (deadline_dt - datetime.now()).total_seconds() / 3600
if hours_until < 0:
score = 100 # Overdue
elif hours_until < 24:
score = 95 # Within 24 hours
elif hours_until < 72:
score = 80 # Within 3 days
elif hours_until < 168:
score = 65 # Within a week
else:
score = 40 # Over a week
except:
pass
# Based on keywords
description = task.get("description", "").lower()
urgency_keywords = {
"urgent": 30, "immediately": 30, "right away": 30,
"today": 25, "tomorrow": 20, "asap": 15,
"important": 10, "critical": 10
}
for kw, bonus in urgency_keywords.items():
if kw in description:
score = min(100, score + bonus)
# Increase urgency when blocked by other tasks
if task.get("blocked_tasks"):
score = min(100, score + 15)
return score
def _evaluate_value(self, task: Dict) -> float:
"""Evaluate value (0-100)"""
score = 50 # Base score
description = task.get("description", "").lower()
# Based on business value keywords
value_keywords = {
"core": 25, "key": 20, "important": 15,
"revenue": 30, "client": 25, "user": 20,
"launch": 20, "release": 20, "deliver": 15,
"innovation": 10, "optimization": 10
}
for kw, bonus in value_keywords.items():
if kw in description:
score = min(100, score + bonus)
# Tasks with dependents have higher value
dependents = task.get("dependents", [])
if dependents:
score = min(100, score + len(dependents) * 5)
return score
def _evaluate_cost(self, task: Dict) -> float:
"""
Evaluate cost (inverse metric, lower cost = higher score)
Converts to 0-100 scale
"""
# Parse estimated time
estimated_time = task.get("estimated_time", "1h")
try:
hours = float(estimated_time.replace("h", "").replace("H", ""))
except:
hours = 1
# Shorter time yields higher score (inverse)
if hours <= 0.5:
score = 100
elif hours <= 1:
score = 90
elif hours <= 2:
score = 75
elif hours <= 4:
score = 60
elif hours <= 8:
score = 40
else:
score = 20
return score
def _evaluate_risk(self, task: Dict) -> float:
"""
Evaluate risk (high-risk tasks need prioritization to allow buffer time)
Returns 0-100 scale
"""
score = 50 # Base score
description = task.get("description", "").lower()
# High-risk keywords
high_risk_keywords = ["new", "first", "experimental", "uncertain", "complex", "integration"]
for kw in high_risk_keywords:
if kw in description:
score = min(100, score + 15)
# Tasks with dependencies carry higher risk
dependencies = task.get("dependencies", [])
if dependencies:
score = min(100, score + len(dependencies) * 10)
return score
def suggest_order(self, tasks: List[Dict]) -> List[Dict]:
"""
Suggest execution order, considering dependencies
Args:
tasks: Task list
Returns:
Task list in suggested execution order
"""
# First sort by priority
scored_tasks = self.calculate(tasks)
# Topological sort considering dependencies
ordered = []
task_map = {t["id"]: t for t in scored_tasks}
completed = set()
while scored_tasks:
# Find all tasks with satisfied dependencies
ready = [
t for t in scored_tasks
if not t.get("dependencies") or
all(d in completed for d in t.get("dependencies", []))
]
if not ready:
# Circular dependency exists, take the highest priority
ready = [scored_tasks[0]]
# Sort by priority score
ready.sort(key=lambda x: x["priority_score"], reverse=True)
# Select the highest priority task
next_task = ready[0]
ordered.append(next_task)
completed.add(next_task["id"])
scored_tasks.remove(next_task)
return ordered
def main():
parser = argparse.ArgumentParser(description='Priority Calculation Tool')
parser.add_argument('--input', '-i', required=True, help='Task JSON file path')
parser.add_argument('--output', '-o', help='Output file path')
parser.add_argument('--weights', '-w', help='Custom weights (JSON format)')
parser.add_argument('--show-order', action='store_true', help='Display suggested execution order')
args = parser.parse_args()
# Read tasks
with open(args.input, 'r', encoding='utf-8') as f:
data = json.load(f)
tasks = data.get("tasks", data)
# Parse weights
weights = None
if args.weights:
try:
weights = json.loads(args.weights)
except:
print("Warning: Unable to parse weight JSON, using default weights")
calculator = PriorityCalculator(weights)
if args.show_order:
result = calculator.suggest_order(tasks)
print("\nSuggested Execution Order:")
for i, task in enumerate(result, 1):
print(f"{i}. [{task['id']}] {task['description'][:40]}... (Score: {task['priority_score']})")
else:
result = calculator.calculate(tasks)
print("\nPriority Sorting:")
for task in result:
print(f"[{task['id']}] Priority: {task['priority']}, Score: {task['priority_score']}")
# Output
output_path = args.output or args.input.replace('.json', '_prioritized.json')
with open(output_path, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print(f"\n✓ Results saved to: {output_path}")
if __name__ == '__main__':
main()
FILE:scripts/progress_monitor.py
#!/usr/bin/env python3
"""Progress Monitor - Progress Monitoring Script"""
import json
from datetime import datetime
from typing import List, Dict, Any
from enum import Enum
class TaskStatus(Enum):
PENDING = "pending"
IN_PROGRESS = "in_progress"
COMPLETED = "completed"
BLOCKED = "blocked"
FAILED = "failed"
class ProgressMonitor:
def __init__(self, tasks_file: str):
self.tasks_file = tasks_file
with open(tasks_file, 'r', encoding='utf-8') as f:
self.data = json.load(f)
self.tasks = self.data.get("tasks", [])
def _save(self):
with open(self.tasks_file, 'w', encoding='utf-8') as f:
json.dump(self.data, f, ensure_ascii=False, indent=2)
def update_status(self, task_id: str, status: str, message: str = None):
for task in self.tasks:
if task["id"] == task_id:
task["status"] = status
task["updated_at"] = datetime.now().isoformat()
if status == "in_progress":
task["started_at"] = datetime.now().isoformat()
elif status in ["completed", "failed"]:
task["completed_at"] = datetime.now().isoformat()
self._save()
return True
return False
def get_progress(self) -> Dict[str, Any]:
counts = {s.value: 0 for s in TaskStatus}
for task in self.tasks:
status = task.get("status", "pending")
if status in counts:
counts[status] += 1
total = len(self.tasks)
completed = counts["completed"]
return {
"total": total,
"progress_percent": round(completed / total * 100, 1) if total else 0,
"status_counts": counts,
"is_complete": completed == total
}
def detect_anomalies(self) -> List[Dict]:
anomalies = []
for task in self.tasks:
if task.get("status") == "in_progress":
started = task.get("started_at")
if started:
try:
elapsed = (datetime.now() - datetime.fromisoformat(started)).total_seconds() / 3600
est = float(task.get("estimated_time", "1h").replace("h", "") or 1)
if elapsed > est * 1.5:
anomalies.append({"task_id": task["id"], "type": "timeout", "elapsed": elapsed})
except: pass
if task.get("status") == "blocked":
anomalies.append({"task_id": task["id"], "type": "blocked"})
if task.get("status") == "failed":
anomalies.append({"task_id": task["id"], "type": "failed"})
return anomalies
def generate_report(self) -> str:
progress = self.get_progress()
c = progress["status_counts"]
lines = [
"═" * 40,
f"📊 Task Progress: {progress['progress_percent']}%",
f" ✓ Completed: {c['completed']} ⏳ In Progress: {c['in_progress']}",
f" ⏸ Pending: {c['pending']} 🚫 Blocked: {c['blocked']} ✗ Failed: {c['failed']}",
"═" * 40
]
return "\n".join(lines)
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True)
parser.add_argument('-a', '--action', choices=['status', 'report', 'update'], default='report')
parser.add_argument('-t', '--task-id')
parser.add_argument('-s', '--status')
args = parser.parse_args()
monitor = ProgressMonitor(args.input)
if args.action == 'report':
print(monitor.generate_report())
elif args.action == 'status':
print(json.dumps(monitor.get_progress(), indent=2))
elif args.action == 'update' and args.task_id and args.status:
monitor.update_status(args.task_id, args.status)
print(f"✓ Updated {args.task_id} -> {args.status}")
FILE:scripts/task_decomposer.py
#!/usr/bin/env python3
"""
Task Decomposer - Task Decomposition Script
Decomposes natural language goals into a structured task tree
"""
import argparse
import json
import re
from datetime import datetime
from typing import List, Dict, Any, Optional
class TaskDecomposer:
"""Task Decomposer"""
def __init__(self):
self.task_counter = 0
self.tasks = []
def decompose(self, goal: str, context: Optional[Dict] = None) -> Dict[str, Any]:
"""
Decompose a goal into a task tree
Args:
goal: User goal description
context: Additional context information
Returns:
Structured task tree
"""
self.task_counter = 0
self.tasks = []
# Parse goal
main_tasks = self._parse_goal(goal)
# Build task tree
for task in main_tasks:
self._add_task(task, parent_id=None)
return {
"main_goal": goal,
"created_at": datetime.now().isoformat(),
"total_tasks": len(self.tasks),
"tasks": self.tasks
}
def _parse_goal(self, goal: str) -> List[Dict]:
"""Parse goal into task list"""
# Identify key action words
action_patterns = [
r'(write|draft|create|design|develop|complete|prepare|organize|analyze)',
r'(test|verify|check|review|optimize|modify|update|delete)',
r'(publish|deploy|push|send|share|display)'
]
# Identify parallel structures (commas, and, also, etc.)
split_patterns = r'[,,、;;]|and|also|meanwhile|additionally'
# Simple decomposition logic
parts = re.split(split_patterns, goal)
tasks = []
for i, part in enumerate(parts):
part = part.strip()
if not part:
continue
# Determine if it's an independent task
is_task = any(re.search(p, part) for p in action_patterns)
if is_task or len(part) > 4:
task = self._create_task_structure(part, i)
tasks.append(task)
# If no tasks identified, treat the entire goal as a single task
if not tasks:
tasks.append(self._create_task_structure(goal, 0))
return tasks
def _create_task_structure(self, description: str, index: int) -> Dict:
"""Create task structure"""
# Estimate time (simple heuristic)
estimated_time = self._estimate_time(description)
# Determine priority
priority = self._determine_priority(description)
# Infer required skills
required_skills = self._infer_skills(description)
return {
"description": description,
"priority": priority,
"estimated_time": estimated_time,
"required_skills": required_skills,
"subtasks": []
}
def _add_task(self, task_data: Dict, parent_id: Optional[str] = None) -> str:
"""Add task to task list"""
self.task_counter += 1
task_id = f"T{self.task_counter}"
# Handle subtasks
subtasks = task_data.pop("subtasks", [])
task = {
"id": task_id,
"parent_id": parent_id,
"status": "pending",
"created_at": datetime.now().isoformat(),
**task_data
}
self.tasks.append(task)
# Recursively process subtasks
for subtask_data in subtasks:
self._add_task(subtask_data, parent_id=task_id)
return task_id
def _estimate_time(self, description: str) -> str:
"""Estimate task time"""
# Simple estimation based on keywords
time_indicators = {
'document': 2,
'report': 3,
'PPT': 2,
'code': 4,
'test': 2,
'analysis': 3,
'design': 3,
'poster': 1,
'video': 4,
'demo': 3
}
hours = 1 # Default 1 hour
for keyword, h in time_indicators.items():
if keyword in description:
hours = h
break
return f"{hours}h"
def _determine_priority(self, description: str) -> str:
"""Determine task priority"""
high_priority_keywords = ['urgent', 'immediately', 'right away', 'today', 'tomorrow', 'important', 'critical']
low_priority_keywords = ['later', 'not urgent', 'when available', 'sometime']
for kw in high_priority_keywords:
if kw in description:
return "high"
for kw in low_priority_keywords:
if kw in description:
return "low"
return "medium"
def _infer_skills(self, description: str) -> List[str]:
"""Infer required skills"""
skill_mapping = {
'document': ['doc-writing-skill'],
'report': ['doc-writing-skill'],
'PPT': ['ppt-parser-local', 'doc-writing-skill'],
'code': [],
'test': [],
'analysis': ['deep-search-skill', 'web-search'],
'search': ['web-search', 'deep-search-skill'],
'poster': ['image_generation'],
'image': ['image_generation'],
'video': ['video-script-generation-skill'],
'Xiaohongshu': ['redbook', 'weavefox-xhs-intel'],
'Official Account': ['wechat-article-generator'],
'translation': []
}
skills = []
for keyword, skill_list in skill_mapping.items():
if keyword in description:
skills.extend(skill_list)
return list(set(skills)) # Deduplicate
def main():
parser = argparse.ArgumentParser(description='Task Decomposition Tool')
parser.add_argument('--goal', '-g', required=True, help='User goal description')
parser.add_argument('--output', '-o', default='tasks.json', help='Output file path')
parser.add_argument('--context', '-c', help='Additional context (JSON format)')
args = parser.parse_args()
decomposer = TaskDecomposer()
context = None
if args.context:
try:
context = json.loads(args.context)
except json.JSONDecodeError:
print(f"Warning: Unable to parse context JSON, will ignore")
result = decomposer.decompose(args.goal, context)
# Output to file
with open(args.output, 'w', encoding='utf-8') as f:
json.dump(result, f, ensure_ascii=False, indent=2)
print(f"✓ Task decomposition complete, total {result['total_tasks']} task(s)")
print(f"✓ Results saved to: {args.output}")
# Print task preview
print("\nTask List:")
for task in result['tasks']:
indent = " " if task.get('parent_id') else ""
print(f"{indent}[{task['id']}] {task['description'][:50]}... (Priority: {task['priority']}, Estimated: {task['estimated_time']})")
if __name__ == '__main__':
main()
FILE:references/agent_matching.md
# Agent Matching Strategy
## Capability Matrix
| Skill | Applicable Task Types | Advantage Scenarios |
|-------|-----------------------|---------------------|
| web-search, deep-search-skill | Information gathering, research, search | Web search required, competitive analysis |
| doc-writing-skill | Document writing, report generation | Professional document format output required |
| image_generation | Image creation, design | Generating images, posters, covers |
| ppt-parser-local | PPT processing | Presentation parsing, content extraction |
| redbook, weavefox-xhs-intel | Xiaohongshu operations | Post publishing, content analysis, sentiment monitoring |
| video-script-generation-skill | Video scripts | Storyboarding, shooting scripts, short video content |
| wechat-article-generator | Official Account content | In-depth articles, content creation |
| storyboard-prompt-generator | Storyboard prompts | Animation storyboards, AI generation prompts |
## Matching Rules
### 1. Match by Task Type
```python
def match_agent(task_description):
keywords = {
"document|report|summary": ["doc-writing-skill"],
"PPT|presentation|slides": ["ppt-parser-local"],
"image|poster|cover|design": ["image_generation"],
"search|research|query|gather": ["web-search", "deep-search-skill"],
"Xiaohongshu|post|recommendation": ["redbook", "weavefox-xhs-intel"],
"video|script|storyboard": ["video-script-generation-skill"],
"Official Account|tweet": ["wechat-article-generator"]
}
for pattern, agents in keywords.items():
if re.search(pattern, task_description):
return agents
return []
```
### 2. Load Balancing
- Avoid assigning too many tasks to the same agent simultaneously
- Prioritize agents currently idle
- Consider the agent's historical success rate
### 3. Cost Optimization
- Prioritize lightweight agents for simple tasks
- Use specialized agents for complex tasks
- Merge similar tasks for batch processing
FILE:references/task_templates.md
# Task Template Library
## Content Creation
```json
{
"type": "content_creation",
"subtasks": [
{"id": "T1", "title": "Topic Planning", "estimated_time": "0.5h"},
{"id": "T2", "title": "Material Collection", "required_skills": ["web-search"]},
{"id": "T3", "title": "Content Writing", "required_skills": ["doc-writing-skill"]},
{"id": "T4", "title": "Image Design", "required_skills": ["image_generation"]},
{"id": "T5", "title": "Review and Revision"}
]
}
```
## Tech Development
```json
{
"type": "tech_development",
"subtasks": [
{"id": "T1", "title": "Requirements Analysis"},
{"id": "T2", "title": "Technical Solution Design"},
{"id": "T3", "title": "Core Feature Development"},
{"id": "T4", "title": "Unit Testing"},
{"id": "T5", "title": "Documentation Writing", "required_skills": ["doc-writing-skill"]}
]
}
```
## Product Launch
```json
{
"type": "product_launch",
"subtasks": [
{"id": "T1", "title": "Product Documentation", "required_skills": ["doc-writing-skill"]},
{"id": "T2", "title": "Testing and Validation"},
{"id": "T3", "title": "Promotional Poster", "required_skills": ["image_generation"]},
{"id": "T4", "title": "Launch Announcement"},
{"id": "T5", "title": "Launch Execution"}
]
}
```
FILE:references/workflow_patterns.md
# Workflow Patterns
## Common Patterns
### 1. Sequential Pattern
Applicable when: Tasks have clear dependency relationships
```
T1 → T2 → T3 → T4
```
Example: Data scraping → Data analysis → Chart generation → Report writing
### 2. Parallel Pattern
Applicable when: Tasks are independent of each other
```
T1 ─┐
T2 ─┼→ Merge Results
T3 ─┘
```
Example: Simultaneously writing documentation, creating posters, developing demos
### 3. Fork-Join Pattern
Applicable when: Some tasks can run in parallel but need to be merged afterwards
```
→ T2 ┐
T1 → T3 ─→ T5
→ T4 ┘
```
Example: Research competitors → Research features/pricing/reviews separately → Merge into analysis report
### 4. Conditional Pattern
Applicable when: The next step is determined by results
```
┌ Yes → T2
T1 → Decision
└ No → T3
```
Example: Check data quality → (Qualified) Analyze / (Unqualified) Re-collect
## Best Practices
1. **Identify Dependencies**: Clarify prerequisite relationships between tasks
2. **Maximize Parallelism**: Execute independent tasks in parallel
3. **Set Checkpoints**: Verify intermediate results at key milestones
4. **Reserve Buffer Time**: Reserve 20% time buffer for complex tasks
FILE:assets/execution_report_template.md
# Execution Report Template
## Project: {project_name}
### Execution Overview
- Total Tasks: {total_tasks}
- Completion Rate: {completion_rate}%
- Total Time: {total_time}
- Status: {status}
### Task Details
#### Completed ✓
| ID | Task | Actual Time | Executing Agent |
|----|------|-------------|-----------------|
#### In Progress ⏳
| ID | Task | Time Elapsed | Estimated Remaining |
|----|------|--------------|---------------------|
#### Blocked 🚫
| ID | Task | Blocking Reason | Resolution |
|----|------|-----------------|------------|
### Anomaly Records
- {exception_1}
- {exception_2}
### Lessons Learned
1. {lesson_1}
2. {lesson_2}
### Follow-Up Recommendations
- {recommendation_1}
- {recommendation_2}
FILE:assets/task_plan_template.md
# Task Planning Template
## Project Name: {project_name}
### Goal
{goal}
### Task List
| ID | Task Description | Priority | Estimated Time | Dependencies | Executing Agent | Status |
|----|------------------|----------|----------------|--------------|-----------------|--------|
| T1 | ... | High | 2h | - | doc-writing | Pending |
| T2 | ... | Medium | 1h | T1 | web-search | Pending |
### Execution Plan
- Phase 1: T1, T2 in parallel
- Phase 2: T3 (depends on T1 completion)
- Phase 3: T4, T5 in parallel
### Timeline
- Estimated Start: {start_date}
- Estimated Completion: {end_date}
- Total Effort: {total_hours}h
### Risk Assessment
- {risk_1}
- {risk_2}
### Notes
{notes}Automatically track tech company financial reports and generate investment summaries. Supports retrieving earnings calendars, market expectation comparisons,...
---
name: financial-report-tracker
description: Automatically track tech company financial reports and generate investment summaries. Supports retrieving earnings calendars, market expectation comparisons, key metric interpretation, and more.
---
# Financial Report Tracker
Automatically track tech company financial reports and generate investment summaries. Suitable for investors tracking portfolio companies' earnings calendars and automatically summarizing earnings highlights and risks.
## Use Cases
When users mention earnings reports, financial reports, EPS, revenue expectations, earnings interpretation, tracking a company's financials, and similar scenarios.
## Prerequisites
Install Python dependencies before first use:
```bash
pip install yfinance requests pandas
```
## Core Capabilities
1. **Earnings Calendar Tracking** — Automatically retrieve target company earnings release dates
2. **Market Expectation Comparison** — EPS/Revenue expectations vs. actual data
3. **Earnings Interpretation** — Key metric changes and management guidance summary
## Command List
| Command | Description | Usage |
|---------|-------------|-------|
| `track` | Track earnings release dates | `python scripts/earnings_tracker.py track <ticker>` |
| `preview` | Earnings preview analysis | `python scripts/earnings_tracker.py preview <ticker>` |
| `review` | Earnings interpretation | `python scripts/earnings_tracker.py review <ticker> --quarter <Q1/Q2/Q3/Q4>` |
## Usage Workflow
### Scenario 1: Track Earnings Date
```
Track Apple's next earnings release date and market expectations
```
```bash
python scripts/earnings_tracker.py track AAPL
```
### Scenario 2: Earnings Preview Analysis
```
Pre-earnings expectation analysis
```
```bash
python scripts/earnings_tracker.py preview AAPL
```
### Scenario 3: Earnings Review
```
Interpret key data from the latest earnings report
```
```bash
python scripts/earnings_tracker.py review AAPL --quarter Q1
```
## Output Format
All commands output a standard Markdown format report:
```markdown
# 📊 Financial Report Tracker Report
**Generated on**: YYYY-MM-DD HH:MM
## Key Findings
1. [Key finding 1]
2. [Key finding 2]
3. [Key finding 3]
## Data Overview
| Metric | Value | Trend | Rating |
|--------|-------|-------|--------|
| Metric A | XXX | ↑ | ⭐⭐⭐⭐ |
| Metric B | YYY | → | ⭐⭐⭐ |
## Detailed Analysis
[Multi-dimensional analysis based on actual data]
## Actionable Recommendations
| Priority | Recommendation | Expected Outcome |
|----------|----------------|------------------|
| 🔴 High | [Specific recommendation] | [Quantified expectation] |
| 🟡 Medium | [Specific recommendation] | [Quantified expectation] |
| 🟢 Low | [Specific recommendation] | [Quantified expectation] |
```
## References
- [yfinance Library](https://pypi.org/project/yfinance/) — Earnings calendar and earnings data
- [Financial Modeling Prep API](https://site.financialmodelingprep.com/developer/docs) — Financial report data
## Notes
- All analysis is based on data retrieved by the script; data is not fabricated
- Missing data fields are marked "Data Unavailable" rather than guessed
- It is recommended to combine with human judgment; AI analysis is for reference only
FILE:scripts/earnings_tracker.py
#!/usr/bin/env python3
"""
Financial Report Tracker - Automatically track tech company earnings reports and generate investment summaries
Usage:
python earnings_tracker.py track <ticker>
python earnings_tracker.py preview <ticker>
python earnings_tracker.py review <ticker> --quarter <Q1/Q2/Q3/Q4>
"""
import sys
import io
import time
import json
import argparse
from datetime import datetime, timedelta
from pathlib import Path
# Windows UTF-8 support
if sys.platform == 'win32':
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')
try:
import yfinance as yf
import requests
except ImportError:
print("❌ Missing dependencies. Please install: pip install yfinance requests pandas")
sys.exit(1)
def create_ticker(symbol):
"""Create Ticker object and set user agent"""
ticker = yf.Ticker(symbol)
# Yahoo Finance may require a user agent
try:
import os
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}
ticker._history_params['headers'] = headers
except:
pass
return ticker
def get_with_retry(func, *args, max_retries=3, delay=2, **kwargs):
"""Fetch function with retry logic"""
last_error = None
for attempt in range(max_retries):
try:
result = func(*args, **kwargs)
if isinstance(result, dict) and 'error' not in result:
return result
elif isinstance(result, dict) and result.get('error') and 'Rate limited' not in str(result.get('error', '')):
return result
last_error = result.get('error', 'Unknown error')
except Exception as e:
last_error = str(e)
if attempt < max_retries - 1:
time.sleep(delay * (attempt + 1))
return {'error': f'{last_error} (retried {max_retries} times)', 'symbol': args[0] if args else 'unknown'}
def get_earnings_calendar(symbol):
"""Get earnings calendar"""
def _fetch():
ticker = create_ticker(symbol)
info = ticker.info
# Try to get next earnings date
next_earnings = info.get('earningsNextGrossProfit', None) or info.get('nextEarningsDate', None)
# Get more details from calendar
try:
calendar = ticker.calendar
if calendar is not None and not calendar.empty:
if 'Earnings Date' in calendar.columns or 'Earnings Date' in calendar.index:
earnings_date = calendar.loc['Earnings Date'].values[0]
if hasattr(earnings_date, '__str__'):
next_earnings = str(earnings_date)
else:
next_earnings = str(earnings_date)
except:
pass
return {
'symbol': symbol,
'next_earnings': next_earnings,
'company_name': info.get('shortName', info.get('longName', 'N/A')),
'market_cap': info.get('marketCap', None),
'exchange': info.get('exchange', 'N/A'),
}
return get_with_retry(_fetch)
def get_earnings_estimate(symbol):
"""Get market expectations"""
def _fetch():
ticker = create_ticker(symbol)
info = ticker.info
# EPS estimates
eps_estimate = info.get('forwardEps', None) # Forward EPS
eps_current = info.get('trailingEps', None) # Actual EPS
# Revenue estimates
revenue_estimate = info.get('totalRevenue', None)
# Analyst ratings
analyst_rating = info.get('recommendationKey', 'N/A')
target_price = info.get('targetMeanPrice', None)
current_price = info.get('currentPrice', info.get('regularMarketPrice', None))
# 52-week range
week_52_high = info.get('fiftyTwoWeekHigh', None)
week_52_low = info.get('fiftyTwoWeekLow', None)
return {
'symbol': symbol,
'eps_estimate': eps_estimate,
'eps_current': eps_current,
'revenue': revenue_estimate,
'analyst_rating': analyst_rating,
'target_price': target_price,
'current_price': current_price,
'week_52_high': week_52_high,
'week_52_low': week_52_low,
'company_name': info.get('shortName', info.get('longName', 'N/A')),
}
return get_with_retry(_fetch)
def get_earnings_review(symbol, quarter=None):
"""Get earnings review"""
def _fetch():
ticker = create_ticker(symbol)
info = ticker.info
# Get historical earnings data
try:
financials = ticker.financials
earnings = ticker.earnings
quarterly_financials = ticker.quarterly_financials
# Get key metrics
revenue = None
net_income = None
gross_margin = None
if not financials.empty:
latest = financials.iloc[:, 0] if len(financials.columns) > 0 else None
if latest is not None:
revenue = latest.get('Total Revenue', None)
net_income = latest.get('Net Income', None)
gross_profit = latest.get('Gross Profit', None)
if revenue and gross_profit:
gross_margin = (gross_profit / revenue) * 100
except:
pass
# Profitability metrics
profit_margin = info.get('profitMargins', None)
operating_margin = info.get('operatingMargins', None)
roe = info.get('returnOnEquity', None)
# Growth metrics
revenue_growth = info.get('revenueGrowth', None)
earnings_growth = info.get('earningsGrowth', None)
# Valuation metrics
pe_ratio = info.get('trailingPE', None)
forward_pe = info.get('forwardPE', None)
# Management guidance
guidance = info.get('earningsQuarterlyGrowth', None)
return {
'symbol': symbol,
'company_name': info.get('shortName', info.get('longName', 'N/A')),
'revenue': revenue,
'net_income': net_income,
'gross_margin': gross_margin,
'profit_margin': profit_margin,
'operating_margin': operating_margin,
'roe': roe,
'revenue_growth': revenue_growth,
'earnings_growth': earnings_growth,
'pe_ratio': pe_ratio,
'forward_pe': forward_pe,
'guidance': guidance,
'analyst_count': info.get('numberOfAnalystOpinions', None),
'target_price': info.get('targetMeanPrice', None),
'current_price': info.get('currentPrice', info.get('regularMarketPrice', None)),
'debt_to_equity': info.get('debtToEquity', None),
'current_ratio': info.get('currentRatio', None),
}
return get_with_retry(_fetch)
def format_track_report(data):
"""Format tracking report"""
output = []
output.append("# 📊 Financial Report Tracker Report")
output.append(f"\n**Generated on**: {datetime.now().strftime('%Y-%m-%d %H:%M')}\n")
if 'error' in data:
output.append(f"❌ Data retrieval failed: {data['error']}")
output.append("")
output.append("💡 **Tip**: The Yahoo Finance API has request limits. Try again later or test with a different ticker symbol.")
return "\n".join(output)
output.append(f"## 📅 Earnings Calendar - {data.get('company_name', data['symbol'])} ({data['symbol']})")
output.append("")
next_earnings = data.get('next_earnings', 'Data Unavailable')
output.append(f"| Item | Data |")
output.append(f"|------|------|")
output.append(f"| Next Earnings Date | {next_earnings} |")
output.append(f"| Exchange | {data.get('exchange', 'N/A')} |")
if data.get('market_cap'):
market_cap = data['market_cap']
if market_cap >= 1e12:
market_cap_str = f".2fT"
elif market_cap >= 1e9:
market_cap_str = f".2fB"
else:
market_cap_str = f".2fM"
output.append(f"| Market Cap | {market_cap_str} |")
return "\n".join(output)
def format_preview_report(data):
"""Format preview report"""
output = []
output.append("# 📊 Earnings Preview Analysis")
output.append(f"\n**Generated on**: {datetime.now().strftime('%Y-%m-%d %H:%M')}\n")
if 'error' in data:
output.append(f"❌ Data retrieval failed: {data['error']}")
output.append("")
output.append("💡 **Tip**: The Yahoo Finance API has request limits. Try again later or test with a different ticker symbol.")
return "\n".join(output)
company_name = data.get('company_name', data['symbol'])
output.append(f"## 🔍 Market Expectations - {company_name} ({data['symbol']})")
output.append("")
# Trend determination function
def trend(val, compare_val=None):
if val is None:
return "→"
if compare_val:
if val > compare_val:
return "↑"
elif val < compare_val:
return "↓"
return "→"
# Rating function
def rating(val, threshold_high=0.5, threshold_low=0.1):
if val is None:
return "⭐⭐⭐"
if val >= threshold_high:
return "⭐⭐⭐⭐⭐"
elif val >= threshold_low:
return "⭐⭐⭐⭐"
else:
return "⭐⭐⭐"
output.append("## Data Overview")
output.append("")
output.append("| Metric | Value | Trend | Rating |")
output.append("|--------|-------|-------|--------|")
# EPS
eps_str = f".2f" if data.get('eps_estimate') else "Data Unavailable"
eps_rating = "⭐⭐⭐⭐" if data.get('eps_estimate') else "⭐⭐⭐"
output.append(f"| Expected EPS | {eps_str} | {trend(data.get('eps_estimate'))} | {eps_rating} |")
# Current EPS
eps_current_str = f".2f" if data.get('eps_current') else "Data Unavailable"
output.append(f"| Current EPS | {eps_current_str} | {trend(data.get('eps_current'), data.get('eps_estimate'))} | {rating(data.get('eps_current'))} |")
# Revenue
revenue = data.get('revenue', None)
if revenue:
if revenue >= 1e12:
revenue_str = f".2fT"
else:
revenue_str = f".2fB"
else:
revenue_str = "Data Unavailable"
output.append(f"| Revenue | {revenue_str} | {trend(revenue)} | {rating(revenue, 1e12, 1e11)} |")
# Target price vs. Current price
target = data.get('target_price', None)
current = data.get('current_price', None)
if target and current:
upside = ((target - current) / current) * 100
price_str = f".2f → .2f ({upside:+.1f}%)"
price_rating = "⭐⭐⭐⭐" if upside > 20 else "⭐⭐⭐"
else:
price_str = "Data Unavailable"
price_rating = "⭐⭐⭐"
output.append(f"| Target/Current Price | {price_str} | → | {price_rating} |")
# 52-week range
high_52 = data.get('week_52_high', None)
low_52 = data.get('week_52_low', None)
if high_52 and low_52:
range_str = f".2f - .2f"
else:
range_str = "Data Unavailable"
output.append(f"| 52-Week Range | {range_str} | → | ⭐⭐⭐ |")
# Analyst rating
analyst = data.get('analyst_rating', 'N/A')
rating_map = {
'strongBuy': 'Strong Buy ⭐⭐⭐⭐⭐',
'buy': 'Buy ⭐⭐⭐⭐',
'hold': 'Hold ⭐⭐⭐',
'underweight': 'Underweight ⭐⭐',
'sell': 'Sell ⭐',
}
analyst_display = rating_map.get(analyst, analyst)
output.append(f"| Analyst Rating | {analyst_display} | → | ⭐⭐⭐⭐ |")
return "\n".join(output)
def format_review_report(data):
"""Format earnings review"""
output = []
output.append("# 📊 Earnings Review Report")
output.append(f"\n**Generated on**: {datetime.now().strftime('%Y-%m-%d %H:%M')}\n")
if 'error' in data:
output.append(f"❌ Data retrieval failed: {data['error']}")
output.append("")
output.append("💡 **Tip**: The Yahoo Finance API has request limits. Try again later or test with a different ticker symbol.")
return "\n".join(output)
company_name = data.get('company_name', data['symbol'])
output.append(f"## 📈 Earnings Review - {company_name} ({data['symbol']})")
output.append("")
# Key Findings
output.append("## Key Findings")
output.append("")
findings = []
# Revenue analysis
revenue = data.get('revenue', None)
if revenue:
if revenue >= 1e12:
findings.append(f"Revenue reached .2fT, leading industry position")
elif revenue >= 1e9:
findings.append(f"Revenue reached .2fB, significant market presence")
# Gross margin analysis
gross_margin = data.get('gross_margin', None)
if gross_margin:
if gross_margin >= 50:
findings.append(f"Gross margin {gross_margin:.1f}%, strong pricing power and solid moat")
elif gross_margin >= 30:
findings.append(f"Gross margin {gross_margin:.1f}%, healthy profitability")
else:
findings.append(f"Gross margin {gross_margin:.1f}%, facing significant competitive pressure")
# Net profit margin analysis
profit_margin = data.get('profit_margin', None)
if profit_margin:
profit_pct = profit_margin * 100
if profit_pct >= 20:
findings.append(f"Net profit margin {profit_pct:.1f}%, strong profitability")
elif profit_pct >= 10:
findings.append(f"Net profit margin {profit_pct:.1f}%, normal profitability level")
else:
findings.append(f"Net profit margin {profit_pct:.1f}%, limited profit potential")
# Revenue growth
revenue_growth = data.get('revenue_growth', None)
if revenue_growth:
growth_pct = revenue_growth * 100
if growth_pct >= 20:
findings.append(f"Revenue YoY growth {growth_pct:.1f}%, strong growth momentum")
elif growth_pct >= 0:
findings.append(f"Revenue YoY growth {growth_pct:.1f}%, maintaining growth")
else:
findings.append(f"Revenue YoY decline {abs(growth_pct):.1f}%, requires attention")
# Valuation analysis
pe = data.get('pe_ratio', None)
forward_pe = data.get('forward_pe', None)
if pe and forward_pe:
if pe < forward_pe:
findings.append(f"PE {pe:.1f}x, expected future earnings improvement, valuation likely to moderate")
else:
findings.append(f"PE {pe:.1f}x, current valuation is relatively high")
for i, finding in enumerate(findings[:5], 1):
output.append(f"{i}. {finding}")
if not findings:
output.append("Incomplete data retrieved. Please verify the ticker symbol is correct.")
output.append("")
output.append("## Detailed Data")
output.append("")
output.append("| Metric | Value | Trend | Rating |")
output.append("|--------|-------|-------|--------|")
# Revenue
if revenue:
if revenue >= 1e12:
revenue_str = f".2fT"
else:
revenue_str = f".2fB"
else:
revenue_str = "Data Unavailable"
output.append(f"| Revenue | {revenue_str} | {'↑' if revenue_growth and revenue_growth > 0 else '↓'} | ⭐⭐⭐⭐ |")
# Net Income
net_income = data.get('net_income', None)
if net_income:
ni_str = f".2fB" if net_income >= 1e9 else f".2fM"
else:
ni_str = "Data Unavailable"
output.append(f"| Net Income | {ni_str} | → | ⭐⭐⭐⭐ |")
# Gross Margin
gm_str = f"{gross_margin:.1f}%" if gross_margin else "Data Unavailable"
gm_rating = "⭐⭐⭐⭐⭐" if gross_margin and gross_margin >= 50 else "⭐⭐⭐⭐" if gross_margin and gross_margin >= 30 else "⭐⭐⭐"
output.append(f"| Gross Margin | {gm_str} | → | {gm_rating} |")
# Net Profit Margin
pm_str = f"{profit_margin*100:.1f}%" if profit_margin else "Data Unavailable"
pm_rating = "⭐⭐⭐⭐⭐" if profit_margin and profit_margin >= 0.2 else "⭐⭐⭐⭐" if profit_margin and profit_margin >= 0.1 else "⭐⭐⭐"
output.append(f"| Net Profit Margin | {pm_str} | → | {pm_rating} |")
# ROE
roe = data.get('roe', None)
roe_str = f"{roe*100:.1f}%" if roe else "Data Unavailable"
roe_rating = "⭐⭐⭐⭐⭐" if roe and roe >= 0.2 else "⭐⭐⭐⭐" if roe and roe >= 0.1 else "⭐⭐⭐"
output.append(f"| Return on Equity (ROE) | {roe_str} | → | {roe_rating} |")
# PE
pe_str = f"{pe:.1f}x" if pe else "Data Unavailable"
pe_rating = "⭐⭐⭐⭐" if pe and pe < 25 else "⭐⭐⭐" if pe and pe < 40 else "⭐⭐"
output.append(f"| P/E Ratio | {pe_str} | → | {pe_rating} |")
# Target Price
target = data.get('target_price', None)
current = data.get('current_price', None)
if target and current:
upside = ((target - current) / current) * 100
price_str = f".2f → .2f ({upside:+.1f}%)"
else:
price_str = "Data Unavailable"
output.append(f"| Target/Current Price | {price_str} | → | ⭐⭐⭐⭐ |")
# Actionable Recommendations
output.append("")
output.append("## Actionable Recommendations")
output.append("")
output.append("| Priority | Recommendation | Expected Outcome |")
output.append("|----------|----------------|------------------|")
actions = []
# Valuation-based recommendations
if pe and pe < 20:
actions.append(("🟢 Low", "Valuation at historical lows, consider accumulating on dips", "Ample margin of safety"))
elif pe and pe > 50:
actions.append(("🔴 High", "Elevated valuation, wait for pullback opportunity", "Avoid chasing highs"))
# Growth-based recommendations
if revenue_growth and revenue_growth > 0.15:
actions.append(("🟡 Medium", "Strong growth, suitable for growth-oriented allocation", "Long-term holding returns promising"))
# Margin-based recommendations
if profit_margin and profit_margin > 0.2:
actions.append(("🟢 Low", "Strong profitability, abundant cash flow", "Outstanding risk resilience"))
elif profit_margin and profit_margin < 0.05:
actions.append(("🔴 High", "Profitability under pressure, monitor cost control", "Requires close tracking of recovery"))
if not actions:
actions.append(("🟡 Medium", "Fundamental data complete; recommend comprehensive assessment with industry trends", "Prudent decision making"))
for action in actions[:4]:
output.append(f"| {action[0]} | {action[1]} | {action[2]} |")
return "\n".join(output)
def main():
parser = argparse.ArgumentParser(description='Financial Report Tracker - Automatically track tech company earnings reports')
subparsers = parser.add_subparsers(dest='command', help='Subcommands')
# track command
track_parser = subparsers.add_parser('track', help='Track earnings release dates')
track_parser.add_argument('symbol', help='Ticker symbol, e.g., AAPL')
# preview command
preview_parser = subparsers.add_parser('preview', help='Earnings preview analysis')
preview_parser.add_argument('symbol', help='Ticker symbol, e.g., AAPL')
# review command
review_parser = subparsers.add_parser('review', help='Earnings review')
review_parser.add_argument('symbol', help='Ticker symbol, e.g., AAPL')
review_parser.add_argument('--quarter', '-q', help='Specify quarter, e.g., Q1', default=None)
args = parser.parse_args()
if args.command == 'track':
data = get_earnings_calendar(args.symbol.upper())
print(format_track_report(data))
elif args.command == 'preview':
data = get_earnings_estimate(args.symbol.upper())
print(format_preview_report(data))
elif args.command == 'review':
data = get_earnings_review(args.symbol.upper(), args.quarter)
print(format_review_report(data))
else:
parser.print_help()
if __name__ == "__main__":
main()
FILE:references/api_reference.md
# Financial Report Tracker API Reference
## yfinance Core Methods
### Ticker Object
```python
import yfinance as yf
ticker = yf.Ticker("AAPL")
```
### Key Properties and Methods
| Method/Property | Description | Return Type |
|-----------------|-------------|-------------|
| `.info` | Company basic information, valuation, ratings | dict |
| `.calendar` | Earnings calendar | DataFrame |
| `.financials` | Quarterly/Annual financial data | DataFrame |
| `.quarterly_financials` | Quarterly financial data | DataFrame |
| `.earnings` | Historical earnings data | DataFrame |
| `.earnings_dates` | Historical earnings dates | DataFrame |
| `.recommendations` | Analyst recommendations | DataFrame |
| `.splits` | Stock split records | DataFrame |
| `.dividends` | Dividend records | Series |
### Key info Fields
| Field | Description |
|-------|-------------|
| `shortName` | Company short name |
| `longName` | Company full name |
| `marketCap` | Market capitalization |
| `currentPrice` | Current stock price |
| `forwardEps` | Forward EPS |
| `trailingEps` | Trailing EPS |
| `trailingPE` | P/E Ratio (Trailing) |
| `forwardPE` | P/E Ratio (Forward) |
| `profitMargins` | Net profit margin |
| `operatingMargins` | Operating margin |
| `grossMargins` | Gross margin |
| `revenueGrowth` | Revenue growth rate |
| `earningsGrowth` | Earnings growth rate |
| `returnOnEquity` | Return on equity (ROE) |
| `targetMeanPrice` | Analyst mean target price |
| `recommendationKey` | Analyst consensus rating |
| `numberOfAnalystOpinions` | Number of analyst opinions |
| `fiftyTwoWeekHigh` | 52-week high |
| `fiftyTwoWeekLow` | 52-week low |
| `debtToEquity` | Debt-to-equity ratio |
| `currentRatio` | Current ratio |
## Data Retrieval Examples
### Get Earnings Calendar
```python
ticker = yf.Ticker("AAPL")
next_earnings = ticker.info.get('earningsNextGrossProfit')
calendar = ticker.calendar
```
### Get Financial Data
```python
# Quarterly financials
quarterly = ticker.quarterly_financials
# Annual financials
annual = ticker.financials
# Earnings history
earnings = ticker.earnings
```
### Get Analyst Data
```python
recommendations = ticker.recommendations
earnings_dates = ticker.earnings_dates
```
## Error Handling
```python
try:
ticker = yf.Ticker(symbol)
info = ticker.info
if 'regularMarketPrice' not in info:
raise ValueError(f"Ticker symbol {symbol} does not exist")
except Exception as e:
print(f"Data retrieval failed: {e}")
```
## Notes
1. **Data Latency**: yfinance data typically has a 15-20 minute delay
2. **Rate Limiting**: Avoid large numbers of requests in a short period; may be throttled
3. **Data Completeness**: Some small-cap stocks may have incomplete data
4. **Timezone Handling**: Earnings dates are typically in U.S. Eastern TimeFacilitates simple multi-agent team collaboration with defined roles, task distribution, and versioned artifact management via a streamlined folder structure.
---
name: lightweight-team-orchestration
description: Lightweight multi-agent team orchestration. Output structure simplified to two folders: agents/ and projects/.
---
# Lightweight Team Orchestration
A lightweight multi-agent team collaboration skill with a simplified output structure focused on core deliverables.
## Use Cases
- Creating simple teams with 2+ agents
- Agent role definition and task distribution
- Agent output artifact management (with versioning)
- Lightweight collaboration workflows (no complex workflow engine required)
## Quick Start
### Output Structure
```
[TEAM_NAME]/
├── agents/ # Agent role definitions
│ ├── orchestrator/ # Orchestrator
│ │ └── SOUL.md # Role definition
│ ├── builder/ # Executor
│ │ └── SOUL.md
│ └── reviewer/ # Reviewer (optional)
│ └── SOUL.md
└── projects/ # Output artifacts (with versioning)
├── v1.0.0/ # Version directory
│ ├── builder.md # Builder output
│ └── reviewer.md # Reviewer output
└── v1.1.0/ # Next version
```
### Workflow
1. **Create Agent Roles** → Create SOUL.md for each agent under `agents/`
2. **Distribute Tasks** → Launch agents using sessions_spawn
3. **Collect Artifacts** → Store artifacts in `projects/v{version}/`
4. **Version Management** → Create a new version directory for each delivery
## Agent Role Definitions
### agents/orchestrator/SOUL.md
```markdown
# Orchestrator
## Responsibilities
- Task distribution and progress tracking
- Coordination between agents
- Artifact version management
## Behaviors
- Use high-reasoning model
- Keep task status updated
```
### agents/builder/SOUL.md
```markdown
# Executor
## Responsibilities
- Execute specific tasks
- Produce deliverables
## Behaviors
- Deliver according to specifications
- Annotate version number
```
### agents/reviewer/SOUL.md (optional)
```markdown
# Reviewer
## Responsibilities
- Verify output quality
- Propose improvement suggestions
```
## Task Distribution
Launch agents using sessions_spawn:
```
Task: [Task description]
Output: projects/v{version}/{agent}.md
Verify: [Verification method]
```
## Version Management
- Initial version: v1.0.0
- Each iteration: Increment version number
- Preserve history: All versions retained in projects/
## When to Use
- Simple 2-3 person teams
- No complex workflow engine required
- Focus on artifact delivery over process
## When Not to Use
- Complex multi-stage workflows
- Real-time status tracking → Use task boards
- Large-scale agent coordinationAgent work status monitoring and automatic activation system. Triggers when monitoring subagent runtime status, detecting prolonged unresponsive "stalled" st...
---
name: agent-monitor
description: Agent work status monitoring and automatic activation system. Triggers when monitoring subagent runtime status, detecting prolonged unresponsive "stalled" states, and automatically activating them to resume operation. Suitable for long-running task monitoring, automated operations, agent health checks, and similar scenarios.
---
# Agent Monitor - Agent Work Status Monitoring
## Overview
This skill provides subagent work status monitoring and automatic activation capabilities:
1. **Status Monitoring** - Real-time monitoring of agent runtime status
2. **Stall Detection** - Detecting "stalled" states where an agent has been unresponsive for over 5 minutes
3. **Automatic Activation** - Automatically sending activation messages to resume agent operation
## Core Capabilities
### 1. Monitor Agent Status
Use the `subagents` tool to obtain a list of currently running agents:
```python
# List recently running agents
subagents(action="list", recentMinutes=30)
```
### 2. Detect Stalled Status
Detection logic:
- Obtain the agent's last activity time
- Calculate the difference from the current time
- If over 5 minutes (300 seconds) with no activity → Determine as "stalled"
### 3. Automatically Activate Agents
Use the `steer` action of the `subagents` tool to send an activation message:
```python
# Send an activation message to a specified agent
subagents(action="steer", target="<agent-id>", message="Continue working")
```
## Workflow
```
┌─────────────────────┐
│ Get Agent List │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ Check Each Agent's │
│ Last Activity Time │
└──────────┬──────────┘
▼
┌────────┐
│ >5min? ├──No──┐
└────┬───┘ │
Yes│ │
▼ │
┌─────────────────────┐│
│ Determine as ││
│ Stalled Status ││
└──────────┬──────────┘│
▼ │
┌─────────────────────┐│
│ Send Activation ││
│ Message to Resume ││
└─────────────────────┘│
│ │
└───────────┘
▼
┌─────────────────┐
│ Continue Monitoring│
└─────────────────┘
```
## Usage Examples
### Example 1: Monitor All Agents
```python
# 1. Get agent list
result = subagents(action="list", recentMinutes=30)
# 2. Check each agent's status
for agent in result.agents:
idle_time = calculate_idle_time(agent.lastActivity)
if idle_time > 300: # Over 5 minutes
# 3. Automatically activate
subagents(action="steer", target=agent.id, message="Please continue executing the task")
```
### Example 2: Monitor a Specific Agent
```python
# Monitor an agent with a specified ID
agent_id = "builder-agent-001"
result = subagents(action="list", recentMinutes=10)
# Find the target agent
for agent in result.agents:
if agent.id == agent_id:
if is_stalled(agent, threshold=300):
activate_agent(agent_id)
```
## Script Tool
### monitor_agents.py
Located at `scripts/monitor_agents.py`, provides complete monitoring functionality:
```bash
# Monitor and automatically activate stalled agents
python scripts/monitor_agents.py --threshold 300 --auto-activate
# Detect only, without automatic activation
python scripts/monitor_agents.py --threshold 300 --dry-run
# Monitor a specific agent
python scripts/monitor_agents.py --target agent-id-001
```
Parameter descriptions:
- `--threshold`: Stall determination threshold (seconds), default 300 (5 minutes)
- `--auto-activate`: Automatically activate stalled agents
- `--dry-run`: Detect only, do not execute activation
- `--target`: Specify a specific agent ID to monitor
## Integration into Scheduled Tasks
The monitoring script can be integrated into cron scheduled tasks for continuous monitoring:
```bash
# Check every 2 minutes
*/2 * * * * python /path/to/monitor_agents.py --auto-activate
```
## Notes
1. **Threshold Setting**: Adjust the stall determination threshold based on the task type; complex tasks may require longer thresholds
2. **Activation Message**: Activation messages sent should be concise and clear, prompting the agent to continue working
3. **Avoid False Activation**: Ensure the agent is genuinely stalled before activating to avoid interfering with normal thought processes
4. **Logging**: It is recommended to log each detection and activation operation for subsequent analysis
FILE:scripts/monitor_agents.py
#!/usr/bin/env python3
"""
Agent Monitor - Agent Work Status Monitoring and Automatic Activation
Features:
1. Monitor agent runtime status
2. Detect "stalled" states where an agent exceeds the idle threshold
3. Automatically send activation messages to resume agent operation
Usage:
python monitor_agents.py --threshold 300 --auto-activate
python monitor_agents.py --threshold 300 --dry-run
python monitor_agents.py --target agent-id-001
"""
import argparse
import json
import sys
import time
from datetime import datetime, timezone
from typing import Dict, List, Optional, Any
def parse_args():
"""Parse command line arguments"""
parser = argparse.ArgumentParser(
description='Agent Work Status Monitoring and Automatic Activation Tool',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# Monitor and automatically activate stalled agents (5-minute threshold)
python monitor_agents.py --threshold 300 --auto-activate
# Detect only, without automatic activation
python monitor_agents.py --threshold 300 --dry-run
# Monitor a specific agent
python monitor_agents.py --target agent-id-001 --auto-activate
"""
)
parser.add_argument(
'--threshold',
type=int,
default=300,
help='Stall determination threshold (seconds), default 300 (5 minutes)'
)
parser.add_argument(
'--auto-activate',
action='store_true',
help='Automatically activate stalled agents'
)
parser.add_argument(
'--dry-run',
action='store_true',
help='Detect only, do not execute activation'
)
parser.add_argument(
'--target',
type=str,
help='Specify a specific agent ID to monitor'
)
parser.add_argument(
'--json',
action='store_true',
help='Output results in JSON format'
)
return parser.parse_args()
def get_agent_list(recent_minutes: int = 30) -> List[Dict[str, Any]]:
"""
Get list of agents
Note: This function needs to run in an OpenClaw environment and obtain data via tool calls.
When run standalone, returns mock data for testing.
"""
# In an actual OpenClaw environment, this would call:
# subagents(action="list", recentMinutes=recent_minutes)
# Mock data (for testing)
return [
{
"id": "agent-001",
"status": "running",
"lastActivity": datetime.now(timezone.utc).isoformat(),
"task": "Processing documents"
},
{
"id": "agent-002",
"status": "idle",
"lastActivity": (datetime.now(timezone.utc)).isoformat(),
"task": "Data analysis"
}
]
def calculate_idle_time(last_activity: str) -> float:
"""
Calculate agent idle time (seconds)
Args:
last_activity: ISO format time string
Returns:
Idle time (seconds)
"""
try:
last_time = datetime.fromisoformat(last_activity.replace('Z', '+00:00'))
now = datetime.now(timezone.utc)
idle_seconds = (now - last_time).total_seconds()
return max(0, idle_seconds)
except Exception as e:
print(f"Failed to parse time: {e}", file=sys.stderr)
return 0
def is_stalled(agent: Dict[str, Any], threshold: int = 300) -> bool:
"""
Determine if an agent is in a stalled state
Args:
agent: Agent information dictionary
threshold: Stall determination threshold (seconds)
Returns:
Whether the agent is stalled
"""
last_activity = agent.get('lastActivity')
if not last_activity:
return False
idle_time = calculate_idle_time(last_activity)
return idle_time > threshold
def activate_agent(agent_id: str, message: str = "Please continue executing the task") -> bool:
"""
Activate an agent
Args:
agent_id: Agent ID
message: Activation message
Returns:
Whether successful
"""
# In an actual OpenClaw environment, this would call:
# subagents(action="steer", target=agent_id, message=message)
print(f" [Activate] Sending message to agent {agent_id}: {message}")
return True
def format_duration(seconds: float) -> str:
"""Format duration as human-readable string"""
if seconds < 60:
return f"{int(seconds)} seconds"
elif seconds < 3600:
minutes = int(seconds / 60)
secs = int(seconds % 60)
return f"{minutes} minutes {secs} seconds"
else:
hours = int(seconds / 3600)
minutes = int((seconds % 3600) / 60)
return f"{hours} hours {minutes} minutes"
def monitor_agents(
threshold: int = 300,
auto_activate: bool = False,
dry_run: bool = False,
target: Optional[str] = None
) -> Dict[str, Any]:
"""
Monitor agent status
Args:
threshold: Stall determination threshold (seconds)
auto_activate: Whether to automatically activate
dry_run: Whether to detect only without execution
target: Specific agent ID to monitor
Returns:
Monitoring result dictionary
"""
result = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"threshold": threshold,
"agents_checked": 0,
"stalled_count": 0,
"activated_count": 0,
"agents": []
}
# Get agent list
agents = get_agent_list(recent_minutes=30)
print(f"\n🔍 Starting agent status monitoring (Threshold: {format_duration(threshold)})")
print("-" * 60)
for agent in agents:
agent_id = agent.get('id', 'unknown')
# If target specified, only monitor the target agent
if target and agent_id != target:
continue
result["agents_checked"] += 1
last_activity = agent.get('lastActivity', '')
idle_time = calculate_idle_time(last_activity)
stalled = is_stalled(agent, threshold)
agent_result = {
"id": agent_id,
"status": agent.get('status', 'unknown'),
"idle_time": idle_time,
"stalled": stalled,
"activated": False
}
# Display status
status_icon = "🟢" if not stalled else "🔴"
print(f"{status_icon} Agent: {agent_id}")
print(f" Status: {agent.get('status', 'unknown')}")
print(f" Idle time: {format_duration(idle_time)}")
if stalled:
result["stalled_count"] += 1
print(f" ⚠️ Determined as stalled!")
# Auto-activate
if auto_activate and not dry_run:
if activate_agent(agent_id):
agent_result["activated"] = True
result["activated_count"] += 1
print(f" ✅ Activation message sent")
elif dry_run:
print(f" [Dry-run mode] Would send activation message")
result["agents"].append(agent_result)
print()
# Summary
print("-" * 60)
print(f"📊 Monitoring complete: Checked {result['agents_checked']} agent(s)")
print(f" Stalled: {result['stalled_count']}")
if auto_activate and not dry_run:
print(f" Activated: {result['activated_count']}")
print()
return result
def main():
"""Main function"""
args = parse_args()
# Execute monitoring
result = monitor_agents(
threshold=args.threshold,
auto_activate=args.auto_activate,
dry_run=args.dry_run,
target=args.target
)
# Output results
if args.json:
print(json.dumps(result, ensure_ascii=False, indent=2))
# Return code: return 1 if there are stalled agents, for script integration
return 1 if result["stalled_count"] > 0 else 0
if __name__ == "__main__":
sys.exit(main())Token savings and API cost optimization. Provides token calculator, three-tier optimization strategies (prompt compression / cache reuse / model downgrade),...
---
name: token-cost-optimization
description: Token savings and API cost optimization. Provides token calculator, three-tier optimization strategies (prompt compression / cache reuse / model downgrade), specific configuration guides, and quantified effect analysis.
---
# Token Cost Optimization
## Use Cases
User mentions token savings, API cost optimization, prompt compression, cache strategy, model downgrade, cost analysis.
## Quick Start
### Token Calculator
Run the calculation script, input conversation scale, and quickly estimate current token consumption and optimization potential:
```bash
python scripts/token_calculator.py
```
The script will prompt for:
- Number of conversation history items / average length
- Model and pricing used
- Current optimization status
Output: Current cost, optimized cost, savings percentage.
### Three-Tier Optimization Strategy
Ranked by effect / implementation cost:
| Tier | Strategy | Effect | Implementation Cost |
|------|----------|--------|---------------------|
| L1 | Prompt compression & output truncation | 10-30% | Low |
| L2 | Conversation summary caching | 30-50% | Medium |
| L3 | Model downgrade + task routing | 50-70% | High |
**Priority Recommendation**: Implement in order L1 → L2 → L3, verifying results at each stage before proceeding.
Detailed strategies, configuration guides, and pitfalls → See `references/tier-strategies.md`
## Phased Implementation Guide
### Phase 1: L1 Compression (Immediate Effect)
- Clean up redundant descriptions in system prompt
- Set max_tokens limits for long responses
- Remove outdated/unused messages from conversation history
### Phase 2: L2 Caching (1-3 Days)
- Establish FAQ shortcuts for high-frequency repeat questions
- Add summary compression at the beginning of conversations (execute every N rounds)
### Phase 3: L3 Routing (1-2 Weeks)
- Route simple tasks to cheaper models (e.g., 4o-mini / Haiku)
- Retain strong models for complex tasks
- Configure model routing rules
## Quantifiable Comparison Example
See the "Quantified Comparison" section in `references/tier-strategies.md` for details.
FILE:scripts/token_calculator.py
"""
Token Cost Calculator
Input conversation scale and model pricing, output cost comparison before and after optimization and savings percentage.
"""
import sys
MODELS = {
"gpt-4o": {"input": 2.5, "output": 10.0, "unit": "M tokens"},
"gpt-4-turbo": {"input": 10.0, "output": 30.0, "unit": "M tokens"},
"gpt-4o-mini": {"input": 0.15, "output": 0.60, "unit": "M tokens"},
"claude-sonnet-4": {"input": 3.0, "output": 15.0, "unit": "M tokens"},
"claude-haiku-3": {"input": 0.25, "output": 1.25, "unit": "M tokens"},
}
OPTIMIZATION_SAVINGS = {
"none": 0,
"L1_only": 0.20, # Prompt compression
"L1_L2": 0.40, # L1 + Summary caching
"L1_L2_L3": 0.60, # All three tiers
}
def prompt_model_choice():
print("\n=== Available Models ===")
for i, name in enumerate(MODELS.keys(), 1):
d = MODELS[name]
print(f" {i}. {name}")
print(f" Input: d['input']/{d['unit']} | Output: d['output']/{d['unit']}")
print()
while True:
try:
choice = int(input("Select model number: ").strip())
if 1 <= choice <= len(MODELS):
return list(MODELS.keys())[choice - 1]
except ValueError:
pass
print("Please enter a valid number.")
def prompt_optimizer_level():
print("\n=== Optimization Level ===")
levels = [
("0 - No optimization", "none"),
("1 - L1: Prompt compression", "L1_only"),
("2 - L1+L2: Compression + Cache", "L1_L2"),
("3 - L1+L2+L3: All three tiers", "L1_L2_L3"),
]
for label, key in levels:
saving = int(OPTIMIZATION_SAVINGS[key] * 100)
print(f" {label} (Estimated savings {saving}%)")
while True:
try:
choice = int(input("Select optimization level: ").strip())
if 0 <= choice <= 3:
return list(OPTIMIZATION_SAVINGS.keys())[choice]
except ValueError:
pass
print("Please enter 0-3.")
def main():
print("=" * 48)
print(" Token Cost Calculator")
print("=" * 48)
model = prompt_model_choice()
rounds = int(input("\nDaily conversation rounds (e.g., 20): ").strip() or "20")
days = int(input("Working days per month (e.g., 22): ").strip() or "22")
avg_input = int(input("Average input tokens per turn (e.g., 500): ").strip() or "500")
avg_output = int(input("Average output tokens per turn (e.g., 800): ").strip() or "800")
opt_level = prompt_optimizer_level()
m = MODELS[model]
input_cost = (avg_input / 1_000_000) * m["input"]
output_cost = (avg_output / 1_000_000) * m["output"]
per_turn = input_cost + output_cost
monthly_before = per_turn * rounds * days
saving = OPTIMIZATION_SAVINGS[opt_level]
monthly_after = monthly_before * (1 - saving)
monthly_saved = monthly_before - monthly_after
print("\n" + "=" * 48)
print(" Cost Analysis Results")
print("=" * 48)
print(f" Model: {model}")
print(f" Cost per turn: .4f")
print(f" Total monthly calls: {rounds * days}")
print()
print(f" Monthly cost before optimization: .2f")
print(f" Monthly cost after optimization: .2f")
print(f" Monthly savings: .2f ({int(saving*100)}%)")
print("=" * 48)
if __name__ == "__main__":
main()
FILE:references/tier-strategies.md
# Three-Tier Optimization Strategies Explained
## L1: Prompt Compression & Output Truncation (Effect 10-30%)
### Specific Actions
**1. System Prompt Streamlining**
```diff
- "You are a professional, patient, and meticulous AI assistant, skilled at analyzing problems and providing comprehensive, organized, and in-depth answers..."
+ "Professional AI assistant. Provide concise answers."
```
**2. max_tokens Limiting**
Set output limits based on task type:
- Simple Q&A: max_tokens=200
- Routine tasks: max_tokens=500
- Long-form generation: max_tokens=1500
**3. History Message Pruning**
When conversations exceed 20 rounds, delete the earliest 1/3 of history messages (preserving recent context).
### Quantified Effect
| Scenario | Tokens Before | Tokens After | Savings |
|----------|---------------|--------------|---------|
| Simple Q&A | 800/session | 500/session | 37% |
| Code Review | 2000/session | 1400/session | 30% |
| Long-form Text | 5000/session | 3500/session | 30% |
---
## L2: Conversation Summary Caching (Effect 30-50%)
### Specific Actions
**1. High-Frequency Question FAQ Shortcuts**
```python
# Pseudocode example
faq_cache = {
"What's the weather today?": "Beijing, sunny, 25°C",
"What's my name?": "Determined based on context",
}
# Cache hit → Return directly, no API call
```
**2. Dynamic Summary Compression**
After every N conversation rounds, compress history into a single summary:
```
[Summary] User is working on project X, discussed issues Y and Z, currently at stage Z.
```
**3. Reference Document Caching**
Store user-provided documents, code, contracts, etc., in a vector database; subsequent questions are answered via retrieval.
### Quantified Effect
| Scenario | Cost/Month Before | Cost/Month After | Savings |
|----------|-------------------|------------------|---------|
| 10 rounds/day × 30d | $90 | $45 | 50% |
| 30 rounds/day × 30d | $270 | $162 | 40% |
| 100 rounds/day × 30d | $900 | $450 | 50% |
---
## L3: Model Downgrade + Task Routing (Effect 50-70%)
### Model Routing Strategy
| Task Type | Route To | Cost Reduction |
|-----------|----------|----------------|
| Simple Q&A, Translation | gpt-4o-mini / claude-haiku | 90% |
| Normal Tasks, Summarization | gpt-4o / claude-sonnet | 50% |
| Complex Reasoning, Long Context | gpt-4-turbo / claude-opus | Baseline |
### Configuration Example (OpenAI API)
```python
def route_model(task_type, complexity):
if complexity == "low":
return "gpt-4o-mini"
elif complexity == "medium":
return "gpt-4o"
else:
return "gpt-4-turbo"
```
### Quantified Effect
| Monthly Calls | All 4o | Smart Routing | Savings |
|---------------|--------|---------------|---------|
| 5,000 | $75 | $23 | 69% |
| 20,000 | $300 | $95 | 68% |
| 50,000 | $750 | $240 | 68% |
---
## Pitfalls to Avoid
### ❌ Common Mistakes
1. **Over-compressing system prompt**
- Consequence: Unstable model behavior, degraded output quality
- Suggestion: Retain core directives; remove "polite fluff," not "constraints"
2. **Setting max_tokens too low**
- Consequence: Truncated output, incomplete answers
- Suggestion: Estimate + 20% buffer, gradually reduce to find the optimal value
3. **Caching without expiration**
- Consequence: Outdated information leading to incorrect answers
- Suggestion: Set TTL for FAQ; periodically refresh summary caches
4. **One-size-fits-all model downgrade**
- Consequence: Simple tasks using cheaper models may waste more due to retries
- Suggestion: Use a classifier to assess task complexity first, then route
5. **Premature L3 optimization**
- Consequence: Incomplete routing rules degrade user experience
- Suggestion: Validate L1+L2 effects first, then introduce L3
### ✅ Best Practices
- Record a baseline after each optimization phase and compare effects
- Keep detailed cost logs for analysis
- L3 routing should include a "downgrade failure auto-upgrade" fallback strategy
- Periodically (monthly) review token consumption trendsSolves the memory fragmentation problem for Agents during session restarts, sub-agent boundaries, and cron/heartbeat isolation.
---
name: context-relay
description: Solves the memory fragmentation problem for Agents during session restarts, sub-agent boundaries, and cron/heartbeat isolation.
---
# Context Relay - Cross-Session Memory Continuity System
Files are the single source of truth. Each execution unit reads context from files at startup, without relying on session memory. Suitable for Agents that need to maintain task continuity across sessions.
## Trigger Words
- Memory fragmentation
- Cross-session
- Context passing
- context relay
- session restart
- sub-agent communication
- persistent context
- project state management
- cold start
## Core Principle
**Files are the single source of truth.**
Agents lose session memory in the following scenarios:
- Session restart (app restart, timeout disconnection)
- Sub-agent boundaries (newly spawned agents lack parent session memory)
- Cron/Heartbeat isolation (scheduled tasks and heartbeats are independent sessions)
**Solution**: Each execution unit reads context from files at startup and writes back to files when finished. Files are memory.
## Three-Layer Context Architecture
```
project/
├── PROJECT.md # Project metadata (long-term stable)
├── state.json # Current state (frequently updated)
├── decisions.md # Architecture decision records (append-only)
└── todos.json # Self-managed todo list (cross-session tracking)
```
### Layer 1: PROJECT.md (Project Identity)
**Purpose**: Defines "who I am," long-term stable, rarely modified.
**Content Template**:
```markdown
# Project Name
## One-Line Description
[What this project is, what problem it solves]
## Tech Stack
- Frontend:
- Backend:
- Database:
- Deployment:
## Directory Structure
/src - Source code
/docs - Documentation
/tests - Tests
## Key Constraints
[Rules that must be followed, such as API compatibility, performance requirements]
## Related Documents
- Architecture decisions: decisions.md
- Current state: state.json
- Todo items: todos.json
```
### Layer 2: state.json (Current State)
**Purpose**: Defines "where I am," frequently updated, records current progress.
**Content Template**:
```json
{
"phase": "development",
"current_task": "Implement user authentication module",
"progress": {
"completed": ["Database design", "API design"],
"in_progress": "Login endpoint development",
"blocked": [],
"next_steps": ["Registration endpoint", "Password reset"]
},
"last_update": "2026-04-20T10:00:00+08:00",
"session_id": "abc123",
"notes": "Encountering CORS issues, need to configure proxy"
}
```
### Layer 3: decisions.md (Decision Records)
**Purpose**: Defines "why," append-only, never deleted.
**Content Template**:
```markdown
# Architecture Decision Records
## ADR-001: Use JWT for Authentication
- Date: 2026-04-15
- Status: Accepted
- Context: Need a stateless authentication scheme
- Decision: Use JWT + refresh tokens
- Consequences: Must handle token expiration and revocation
## ADR-002: Choose PostgreSQL as Primary Database
- Date: 2026-04-16
- Status: Accepted
- Context: Need support for complex queries and transactions
- Decision: Use PostgreSQL
- Consequences: Must learn PostgreSQL-specific syntax
```
## todos.json (Self-Managed Todo System)
**Purpose**: Agent-managed todo list for cross-session tracking.
**Content Template**:
```json
{
"todos": [
{
"id": "TODO-001",
"title": "Complete user authentication module",
"priority": "high",
"status": "in_progress",
"created": "2026-04-20T09:00:00+08:00",
"updated": "2026-04-20T10:00:00+08:00",
"notes": "Implementing login endpoint"
},
{
"id": "TODO-002",
"title": "Write unit tests",
"priority": "medium",
"status": "pending",
"created": "2026-04-20T09:00:00+08:00",
"updated": null,
"notes": ""
}
],
"last_review": "2026-04-20T10:00:00+08:00"
}
```
**Operation Rules**:
- Start task: Change status to `in_progress`
- Complete task: Change status to `completed`, record `completed_at`
- Blocked task: Change status to `blocked`, explain reason in `notes`
- Each session start: Check `last_review`; if over 24 hours, review all todos
## Workflow
### On Startup: Cold Start Procedure
Execute at the start of each new session/sub-agent/cron job:
```
1. Read PROJECT.md → Understand project identity
2. Read state.json → Understand current progress
3. Read todos.json → Understand pending tasks
4. If decision context is needed → Read decisions.md
5. Begin work
```
**Critical**: Do not assume any memory. All context must be read from files.
### On Completion: State Synchronization
Execute before ending each work session:
```
1. Update state.json → Record current progress
2. If new decisions were made → Append to decisions.md
3. If todos changed → Update todos.json
4. Commit file changes
```
**Critical**: Files must be written before the session ends to ensure the next execution unit can read the latest state.
### Sub-Agent Communication
Parent and child agents communicate context via files:
```
Parent agent:
1. Update state.json (current task, expected output)
2. Spawn child agent
Child agent:
1. Read state.json → Understand task
2. Execute task
3. Update state.json (results, progress)
4. End
Parent agent:
1. Read state.json → Retrieve results
2. Continue work
```
**Note**: Child agents have no memory of the parent session; they can only communicate via files.
## Reference Resources
- [Project Template Details](references/project-template.md) - Complete file templates and usage examples
- [todos.json Management](references/todos-system.md) - Detailed explanation of the self-managed todo system
- [Cold Start Guide](references/cold-start-guide.md) - Cold start procedures for various scenarios
## Script Tools
- `scripts/init_context.py` - Initialize the context file structure in a project directory
FILE:scripts/init_context.py
#!/usr/bin/env python3
"""
Context Relay - Project Context Initialization Script
Creates standard context file structure in a project directory:
- PROJECT.md (Project metadata template)
- state.json (Current state)
- decisions.md (Architecture decision records)
- todos.json (Todo list)
"""
import argparse
import json
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
def get_local_timezone():
"""Get local timezone offset"""
import time
if time.daylight:
offset = -time.altzone // 3600
else:
offset = -time.timezone // 3600
hours = abs(offset)
sign = '+' if offset >= 0 else '-'
return f"{sign}{hours:02d}:00"
def init_context(project_path: str, force: bool = False):
"""Initialize project context"""
project_dir = Path(project_path).resolve()
if not project_dir.exists():
print(f"❌ Directory does not exist: {project_dir}")
return False
# File paths
project_md = project_dir / "PROJECT.md"
state_json = project_dir / "state.json"
decisions_md = project_dir / "decisions.md"
todos_json = project_dir / "todos.json"
# Check for existing files
existing_files = []
for f in [project_md, state_json, decisions_md, todos_json]:
if f.exists():
existing_files.append(f.name)
if existing_files and not force:
print(f"⚠️ The following files already exist: {', '.join(existing_files)}")
print(" Use --force option to overwrite existing files")
return False
# Timezone
tz = get_local_timezone()
now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") + tz
# Create PROJECT.md
project_content = """# Project Name
## One-Line Description
[What this project is, what problem it solves]
## Tech Stack
- Frontend:
- Backend:
- Database:
- Deployment:
## Directory Structure
/src - Source code
/docs - Documentation
/tests - Tests
## Key Constraints
[Rules that must be followed, such as API compatibility, performance requirements]
## Related Documents
- Architecture decisions: decisions.md
- Current state: state.json
- Todo items: todos.json
"""
# Create state.json
state_content = {
"version": "1.0",
"phase": "planning",
"current_task": "",
"progress": {
"completed": [],
"in_progress": None,
"blocked": [],
"next_steps": []
},
"metrics": {
"total_tasks": 0,
"completed_tasks": 0,
"blocked_tasks": 0
},
"last_update": now,
"last_session": None,
"notes": ""
}
# Create decisions.md
decisions_content = """# Architecture Decision Records
This document records important architecture decisions in the project using the ADR (Architecture Decision Record) format.
## ADR Template
### ADR-XXX: [Decision Title]
### Metadata
- **Date**: YYYY-MM-DD
- **Status**: Accepted / Deprecated / Superseded
- **Decider**: [Name or Team]
### Context
[Why is this decision needed? What is the problem?]
### Decision
[What decision was made? What are the specifics?]
### Rationale
[Why was this option chosen? What alternatives were considered?]
### Consequences
[What are the implications of this decision? Positive and negative?]
---
## ADR-001: [First Decision]
...
"""
# Create todos.json
todos_content = {
"todos": [],
"completed": [],
"metadata": {
"last_review": now,
"total_created": 0,
"total_completed": 0
}
}
# Write files
try:
project_md.write_text(project_content, encoding='utf-8')
state_json.write_text(json.dumps(state_content, indent=2, ensure_ascii=False), encoding='utf-8')
decisions_md.write_text(decisions_content, encoding='utf-8')
todos_json.write_text(json.dumps(todos_content, indent=2, ensure_ascii=False), encoding='utf-8')
print(f"✅ Context files created in {project_dir}:")
print(f" ├── PROJECT.md (Project metadata)")
print(f" ├── state.json (Current state)")
print(f" ├── decisions.md (Architecture decisions)")
print(f" └── todos.json (Todo list)")
print()
print("📝 Next step: Edit PROJECT.md to fill in project information")
return True
except Exception as e:
print(f"❌ Failed to create files: {e}")
return False
def main():
parser = argparse.ArgumentParser(
description="Initialize project context file structure",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
python init_context.py /path/to/project
python init_context.py . # Current directory
python init_context.py ./my-project --force # Overwrite existing files
"""
)
parser.add_argument(
"path",
help="Project directory path"
)
parser.add_argument(
"--force", "-f",
action="store_true",
help="Overwrite existing files"
)
args = parser.parse_args()
success = init_context(args.path, args.force)
sys.exit(0 if success else 1)
if __name__ == "__main__":
main()
FILE:references/cold-start-guide.md
# Cold Start Guide
Cold start procedures for various scenarios to ensure Agents can quickly restore context in a memory-less state.
## Core Principle
**Never assume any memory.**
On every startup:
1. Read files → Understand context
2. Verify understanding → Confirm correctness
3. Begin work
## Scenario 1: Main Session Restart
**Triggers**:
- Application restart
- Session timeout disconnection
- Manual restart
**Cold Start Procedure**:
```
Step 1: Read project context
├── Read PROJECT.md → Understand project identity
├── Read state.json → Understand current progress
├── Read todos.json → Understand pending tasks
└── If background needed → Read decisions.md
Step 2: Verify and synchronize
├── Check last_update in state.json
├── Check last_review in todos.json
├── If > 24 hours → Perform todo review
└── Check for any blocked items needing attention
Step 3: Report to user
└── "I see we are working on [current_task],
last updated on [last_update].
Current progress: [completed]/[total]
Shall we continue?"
```
**Example**:
```
[Agent starts]
→ Read PROJECT.md: User Authentication System
→ Read state.json:
{
"current_task": "Implement login endpoint",
"progress": {
"completed": ["Database design"],
"in_progress": "Login endpoint (70%)"
},
"last_update": "2026-04-20T18:00:00+08:00"
}
[Agent output]
"I see we are developing the user authentication system, last worked on yesterday at 6 PM.
Currently implementing the login endpoint, 70% complete.
Would you like to continue?"
```
## Scenario 2: Sub-Agent Startup
**Triggers**:
- Parent agent spawns child agent
- Child agent has no parent session memory
**Cold Start Procedure**:
```
Step 1: Read context prepared by parent agent
├── Read state.json → Understand delegated task
├── Check delegated_to and expected_output
└── Check input_files or other inputs
Step 2: Execute task
├── Complete delegated work
├── Generate output
└── Update state.json (results, output files)
Step 3: End
└── Parent agent will read results
```
**Example**:
```
[Parent agent preparation]
state.json:
{
"delegated_to": "code-reviewer",
"task": "Review code quality in src/auth/*.py",
"expected_output": "Review report (markdown)"
}
[Child agent starts]
→ Read state.json
→ Understand task: Review Python code in src/auth/ directory
→ Perform review
→ Generate report: docs/reviews/auth-2026-04-20.md
→ Update state.json:
{
"result": "Review complete, found 3 issues",
"report_file": "docs/reviews/auth-2026-04-20.md"
}
[Parent agent continues]
→ Read state.json results
→ Read review report
→ Decide next steps
```
## Scenario 3: Cron Task Startup
**Triggers**:
- Scheduled task triggers
- Heartbeat check
**Cold Start Procedure**:
```
Step 1: Read context
├── Read PROJECT.md → Understand project identity
└── Read state.json → Understand current state
Step 2: Execute scheduled task
├── Check project status
├── Perform scheduled operation
└── Update state.json
Step 3: Notify (if needed)
└── Send notification via message tool
```
**Example (Daily Health Check)**:
```
[Cron triggers: Daily 09:00]
→ Read PROJECT.md: User Authentication System
→ Read state.json:
{
"phase": "development",
"last_update": "2026-04-19T18:00:00+08:00"
}
[Perform check]
→ Check for any blocked items
→ Check if todos need updating
→ Update state.json:
{
"last_check": "2026-04-20T09:00:00+08:00",
"health_status": "ok"
}
[Notify if needed]
→ Send message: "Project status normal, 1 todo currently in_progress"
```
## Scenario 4: New Project Initialization
**Triggers**:
- First time entering a project
- Project lacks context files
**Cold Start Procedure**:
```
Step 1: Detect context files
├── Check if PROJECT.md exists
└── If not → Ask user if they want to initialize
Step 2: Create initial files
├── Run init_context.py
├── Guide user to fill in PROJECT.md
├── Initialize state.json
└── Create empty decisions.md and todos.json
Step 3: Confirm understanding
└── Confirm with user that project understanding is correct
```
**Example**:
```
[Agent detects]
→ PROJECT.md does not exist
[Agent output]
"It looks like this is a new project. I can help create context files
so I can remember project information across future sessions.
Would you like to create them? If so, please tell me:
1. Project name and description
2. Tech stack
3. Main objectives"
```
## Scenario 5: Multi-Project Switching
**Triggers**:
- User switches between multiple projects
- Agent needs to identify current project
**Cold Start Procedure**:
```
Step 1: Identify project
├── Check current working directory
├── Look for PROJECT.md
└── If found → Read project context
Step 2: Load project state
├── Read state.json
└── Switch to that project context
Step 3: Confirm
└── Confirm current project with user
```
**Example**:
```
[User switches directory]
User: cd /path/to/project-b
[Agent detects]
→ Found PROJECT.md
→ Read project info: project-b (E-commerce Backend)
[Agent output]
"Switched to the E-commerce Backend project.
Current state: Development phase
In progress: Order module development
Shall we continue?"
```
## Quick Checklist
Confirm the following on every cold start:
- [ ] PROJECT.md has been read
- [ ] state.json has been read
- [ ] todos.json has been read
- [ ] Current phase and task are understood
- [ ] Next steps are known
- [ ] Understanding has been confirmed with user
## Common Mistakes
### Mistake 1: Assuming Memory
❌ **Incorrect**:
```
"I'll continue implementing the login endpoint..." // Assuming memory of last task
```
✅ **Correct**:
```
[First read state.json]
"I see we are implementing the login endpoint, 70% complete.
Before continuing, please confirm this is correct."
```
### Mistake 2: Ignoring Files
❌ **Incorrect**:
```
[Start working immediately without reading any files]
```
✅ **Correct**:
```
[Read on startup]
PROJECT.md → state.json → todos.json
[Then begin work]
```
### Mistake 3: Not Updating Timely
❌ **Incorrect**:
```
[Work finishes, state.json is not updated]
```
✅ **Correct**:
```
[Update immediately after work finishes]
state.json → Record progress
todos.json → Update todo status
```
## Template Script
Use `init_context.py` to quickly initialize project context:
```bash
python init_context.py /path/to/project
# Creates the following files:
# - PROJECT.md (template)
# - state.json (initial state)
# - decisions.md (empty file)
# - todos.json (empty list)
```
FILE:references/project-template.md
# Project Template Details
This document provides complete context file templates and usage examples.
## Complete Templates
### PROJECT.md Template
```markdown
# [Project Name]
## One-Line Description
[What this project is, what problem it solves]
## Tech Stack
- Frontend: [framework/library]
- Backend: [framework/library]
- Database: [database]
- Deployment: [deployment method]
## Directory Structure
```
project/
├── src/ # Source code
│ ├── frontend/ # Frontend code
│ ├── backend/ # Backend code
│ └── shared/ # Shared code
├── docs/ # Documentation
├── tests/ # Tests
├── PROJECT.md # Project metadata
├── state.json # Current state
├── decisions.md # Architecture decisions
└── todos.json # Todo list
```
## Key Constraints
- [Constraint 1: e.g., API version compatibility requirements]
- [Constraint 2: e.g., performance requirements]
- [Constraint 3: e.g., security requirements]
## External Dependencies
- [Dependency 1: e.g., third-party API]
- [Dependency 2: e.g., database service]
## Related Documents
- Architecture decisions: decisions.md
- Current state: state.json
- Todo items: todos.json
```
### state.json Template
```json
{
"version": "1.0",
"phase": "development",
"current_task": "Specific task description",
"progress": {
"completed": [
"Completed item 1",
"Completed item 2"
],
"in_progress": "Work currently in progress",
"blocked": [
{
"item": "Blocked item",
"reason": "Reason for blockage",
"since": "2026-04-20T10:00:00+08:00"
}
],
"next_steps": [
"Next step 1",
"Next step 2"
]
},
"metrics": {
"total_tasks": 10,
"completed_tasks": 3,
"blocked_tasks": 1
},
"last_update": "2026-04-20T10:00:00+08:00",
"last_session": "session-id-here",
"notes": "Important notes for the current session"
}
```
### decisions.md Template
```markdown
# Architecture Decision Records
## ADR-001: [Decision Title]
### Metadata
- **Date**: 2026-04-20
- **Status**: Accepted / Deprecated / Superseded
- **Decider**: [Name or Team]
### Context
[Why is this decision needed? What is the problem?]
### Decision
[What decision was made? What are the specifics?]
### Rationale
[Why was this option chosen? What alternatives were considered?]
### Consequences
[What are the implications of this decision? Positive and negative?]
---
## ADR-002: [Next Decision Title]
...
```
## Usage Examples
### Example 1: New Project Initialization
```bash
# Create context files in project root directory
python init_context.py /path/to/project
# Generated structure:
# /path/to/project/
# ├── PROJECT.md (needs manual filling)
# ├── state.json (initial state)
# ├── decisions.md (empty file)
# └── todos.json (empty todo list)
```
### Example 2: Cross-Session Workflow
**Session 1 (Day 1)**:
```json
// state.json at end of session
{
"phase": "development",
"current_task": "Implement user authentication",
"progress": {
"completed": ["Database design"],
"in_progress": "Login endpoint",
"next_steps": ["Registration endpoint", "Password reset"]
},
"last_update": "2026-04-20T18:00:00+08:00",
"notes": "Login endpoint 70% complete, encountering CORS issues"
}
```
**Session 2 (Day 2)**:
```
1. Read state.json → Discover "Login endpoint 70% complete"
2. Read notes → Discover CORS issues
3. Continue work → Resolve CORS, complete login endpoint
4. Update state.json → Mark login endpoint as completed
```
### Example 3: Sub-Agent Collaboration
**Parent Agent Preparation**:
```json
// state.json
{
"current_task": "Code review",
"delegated_to": "sub-agent-reviewer",
"expected_output": "Review report with issues and recommendations",
"input_files": ["src/auth/login.py", "src/auth/register.py"]
}
```
**Child Agent Execution**:
```
1. Read state.json → Understand task
2. Read input_files → Review code
3. Generate review report
4. Update state.json:
{
"current_task": "Code review",
"result": "Found 3 issues, detailed in review report",
"report_file": "docs/reviews/auth-review-2026-04-20.md"
}
```
**Parent Agent Continuation**:
```
1. Read state.json → Obtain review results
2. Read report_file → View detailed report
3. Decide next actions
```
## Field Descriptions
### state.json Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| version | string | No | File format version |
| phase | string | Yes | Project phase: planning/development/testing/deployed |
| current_task | string | Yes | Description of current task in progress |
| progress.completed | array | Yes | List of completed tasks |
| progress.in_progress | string | No | Specific work currently in progress |
| progress.blocked | array | No | List of blocked tasks |
| progress.next_steps | array | Yes | Planned next steps |
| last_update | string | Yes | Last update timestamp (ISO 8601) |
| last_session | string | No | Last session ID |
| notes | string | No | Important notes |
### decisions.md ADR Fields
| Field | Required | Description |
|-------|----------|-------------|
| Date | Yes | Decision date |
| Status | Yes | Accepted / Deprecated / Superseded |
| Context | Yes | Why this decision is needed |
| Decision | Yes | Specific decision content |
| Rationale | No | Why this option was chosen |
| Consequences | Yes | Implications of the decision |
FILE:references/todos-system.md
# todos.json Self-Managed Todo System
Agent-managed cross-session todo list.
## Core Philosophy
**Agent manages autonomously, not dependent on user instructions.**
todos.json is the Agent's own todo list, used for:
- Recording tasks that need cross-session tracking
- Reminding oneself of tasks needed in future sessions
- Tracking progress of long-term projects
## File Structure
```json
{
"todos": [
{
"id": "TODO-001",
"title": "Task title",
"description": "Detailed description",
"priority": "high",
"status": "in_progress",
"category": "feature",
"tags": ["auth", "api"],
"created": "2026-04-20T09:00:00+08:00",
"updated": "2026-04-20T10:00:00+08:00",
"completed_at": null,
"due_date": "2026-04-25T18:00:00+08:00",
"assignee": null,
"blocked_by": [],
"blocking": [],
"notes": "Additional notes"
}
],
"completed": [
{
"id": "TODO-000",
"title": "Completed task",
"completed_at": "2026-04-19T15:00:00+08:00"
}
],
"metadata": {
"last_review": "2026-04-20T10:00:00+08:00",
"total_created": 10,
"total_completed": 5
}
}
```
## Field Descriptions
### Todo Item Fields
| Field | Type | Required | Description |
|-------|------|----------|-------------|
| id | string | Yes | Unique identifier, format: TODO-XXX |
| title | string | Yes | Task title |
| description | string | No | Detailed description |
| priority | string | Yes | Priority: critical/high/medium/low |
| status | string | Yes | Status: pending/in_progress/completed/blocked/cancelled |
| category | string | No | Category: feature/bug/refactor/docs/test |
| tags | array | No | List of tags |
| created | string | Yes | Creation timestamp (ISO 8601) |
| updated | string | No | Last update timestamp |
| completed_at | string | No | Completion timestamp (required when status is completed) |
| due_date | string | No | Due date |
| blocked_by | array | No | IDs of other TODOs blocking this task |
| blocking | array | No | IDs of other TODOs blocked by this task |
| notes | string | No | Additional notes |
### Metadata Fields
| Field | Description |
|-------|-------------|
| last_review | Last review timestamp |
| total_created | Total number of todos created |
| total_completed | Total number of todos completed |
## Operation Rules
### Creating a Todo
```json
{
"id": "TODO-006",
"title": "New task",
"priority": "medium",
"status": "pending",
"created": "2026-04-20T10:00:00+08:00"
}
```
**When to create**:
- Agent discovers something that needs to be done
- User proposes a new requirement
- Code review finds improvement points
- Encounter issues that need follow-up resolution
### Starting a Task
```json
{
"status": "in_progress",
"updated": "2026-04-20T10:30:00+08:00"
}
```
### Completing a Task
```json
{
"status": "completed",
"completed_at": "2026-04-20T12:00:00+08:00",
"updated": "2026-04-20T12:00:00+08:00"
}
```
After completion, move the task to the `completed` array:
```json
{
"completed": [
{
"id": "TODO-001",
"title": "Completed task",
"completed_at": "2026-04-20T12:00:00+08:00"
}
]
}
```
### Marking as Blocked
```json
{
"status": "blocked",
"blocked_by": ["TODO-003"],
"notes": "Waiting for TODO-003 to complete before proceeding",
"updated": "2026-04-20T11:00:00+08:00"
}
```
### Periodic Review
**Trigger conditions**:
- `last_review` exceeds 24 hours
- At the start of a new session
**Review process**:
```
1. Check if all pending todos are still valid
2. Check if any blocked todos can be unblocked
3. Update priorities (adjust based on project progress)
4. Update last_review timestamp
```
## Best Practices
### Priority Definitions
| Priority | Definition | Example |
|----------|------------|---------|
| critical | Blocks project progress | Security vulnerability, production bug |
| high | Must complete this week | Core feature, important fix |
| medium | Complete this month | Optimization, improvement, minor feature |
| low | Do when time permits | Documentation, cleanup, nice-to-have |
### State Transition Diagram
```
pending → in_progress → completed
↓ ↓
blocked → blocked
↓
cancelled
```
### Periodic Cleanup
- Completed tasks: Move from `todos` to `completed` after 7 days
- Cancelled tasks: Remove from `todos` (optional: move to `cancelled` array)
- Overdue todos: Check `due_date`, update priority or mark as deferred
## Usage Scenarios
### Scenario 1: Cross-Session Tracking
**Session 1**:
```
User: Help me implement user authentication feature
Agent: Create TODO-001 (implement login), TODO-002 (implement registration)
Start TODO-001, mark in_progress
Complete 70%, session ends
```
**Session 2 (Next Day)**:
```
Agent starts: Read todos.json
Discovers: TODO-001 in_progress (70% complete)
Continues: Complete TODO-001, mark completed
Starts: TODO-002, mark in_progress
```
### Scenario 2: Self-Reminder
```json
{
"id": "TODO-005",
"title": "Check API documentation updates",
"priority": "low",
"status": "pending",
"due_date": "2026-04-25T18:00:00+08:00",
"notes": "OpenAI updated their API last week, remember to check if it affects our integration"
}
```
### Scenario 3: Task Dependencies
```json
{
"id": "TODO-003",
"title": "Configure database",
"status": "in_progress"
},
{
"id": "TODO-004",
"title": "Implement data access layer",
"status": "pending",
"blocked_by": ["TODO-003"],
"notes": "Need to complete database configuration first"
}
```Automatically create complete WeChat Official Account articles (≥1600 words) based on topic, audience, and style, including title ideation, structural planni...
--- name: wechat-article-generation-expert description: Automatically create complete WeChat Official Account articles (≥1600 words) based on topic, audience, and style, including title ideation, structural planning, content writing, and multimedia element planning. --- # Wechat Article Generation Expert Transform user-provided topics into structurally complete, word-count-compliant (≥1600 words) in-depth articles for WeChat Official Accounts. ## Use Cases - User mentions keywords such as "Official Account article," "WeChat article," "content creation," "self-media content" - User provides a topic and requests article generation - User needs marketing advertorials or brand promotion content - User requests output in a specific article format. ## Core Workflow ### 1. Information Gathering Confirm the following elements before writing: | Element | Description | If Not Provided by User | |---------|-------------|-------------------------| | Topic | Core subject of the article | Proactively ask | | Target Audience | Reader persona (age/profession/interests) | Infer based on topic | | Style Preference | Formal / Humorous / Approachable / Professional | Default to "Professional & Approachable" | | Word Count Requirement | Target word count | Default to ≥1600 words | | Special Requests | Keyword placement, advertising requirements | Skip if none | **Example Prompt for Gathering Info**: > "I understand you'd like an article on [Topic]. Could you tell me who the target audience is, and whether you prefer a more formal or conversational tone?" ### 2. Article Structure Planning Standard structure (can be flexibly adjusted based on topic): ``` 【Title】 Eye-catching, precise, resonant (recommended 15-25 characters) 【Introduction】 (approx. 200 words) - Scenario lead-in / Data citation / Direct pain point address - Spark reader interest to continue reading 【Body】 (approx. 1200 words, divided into 3-5 sections) - Section 1: Problem presentation or phenomenon analysis - Section 2: Underlying reasons or background interpretation - Section 3: Solutions or actionable advice - Section 4: Case study support or data validation (optional) - Section 5: Elevated summary or call to action 【Conclusion】 (approx. 200 words) - Reiterate core viewpoint - Guide interaction (likes/comments/shares) ``` ### 3. Title Ideation **Mandatory**: Generate 3-5 alternative titles for user selection. **High-Click-Through Title Formulas**: - Pain Point + Solution: "Working Overtime Until 10 PM Daily? 3 Methods to Get You Home on Time" - Data + Suspense: "90% of People Get This Wrong, What About You?" - Counter-Intuitive: "Why Do Harder Workers Seem Less Successful?" - Identity Affirmation: "As a Programmer, There Are Some Things I Have to Say" - Curiosity Gap: "What Does That Colleague Who Never Works Overtime Secretly Do?" ### 4. Content Writing Key Points **Language Style**: - Keep paragraphs short (2-4 sentences per paragraph) - Prefer short sentences over long, complex ones - Use colloquial expressions appropriately - Skillfully use numbers, contrasts, and parallel structures to enhance rhythm **Credibility Enhancement**: - Cite authoritative data sources - Integrate authentic case studies - Endorsement by expert opinions - If specific data is unavailable, use reasonable phrasing: "Research suggests..." "Statistics indicate..." **Multimedia Placement Annotation**: Add descriptions where images should be inserted: ``` [Suggested image placement here: XX scene / XX data chart] ``` ### 5. Quality Checklist Self-check before delivery: - [ ] Word count ≥ 1600 words - [ ] 3-5 alternative titles provided - [ ] Complete structure (Introduction-Body-Conclusion) - [ ] Language style matches target audience - [ ] No plagiarized content - [ ] Special requests fulfilled (keywords/ad placements) - [ ] Multimedia placements annotated ## Output Format Output strictly according to the following template: ```markdown # Basic Information - **Article Topic**: [Topic] - **Target Audience**: [Audience Persona] - **Article Style**: [Style Type] - **Word Count**: [Actual Word Count] # Core Requirements ## Alternative Titles 1. [Title One] 2. [Title Two] 3. [Title Three] ... ## Article Content [Introduction paragraph] [Suggested image placement here: XXX] [Body Section 1] [Body Section 2] ... [Conclusion paragraph] # Additional Information [If special requests exist, explain how they were handled] [If none, state: No additional requirements] ``` ## Common Scenario Handling ### Scenario 1: Broad Topic When user provides a broad topic like "Workplace": 1. Refine the angle based on current trends or reader pain points 2. Provide 2-3 specific sub-directions for selection 3. Proceed with creation after selection ### Scenario 2: Advertorial Requirement When user requests placement of a specific product/brand: 1. Introduce naturally through user pain points or a story 2. Position the product as the solution 3. Avoid forced sales language 4. Recommended placement is in the middle-to-latter part of the article ### Scenario 3: Keyword Optimization Required When user specifies SEO keywords: 1. Include core keywords in the title 2. Ensure keywords appear naturally in the first paragraph 3. Maintain keyword density of 2%-5% throughout the article 4. Interweave related long-tail keywords ### Scenario 4: Insufficient Material When user only provides a topic without detailed materials: 1. Independently conceive cases based on the topic 2. Cite public data or common knowledge 3. Use generic scenarios and personas 4. Annotate "Recommend replacing with real case study" ## Advanced Techniques **Enhance Sense of Fulfillment**: Provide an "Action List" or "Tips" section at the end so readers feel they have gained something. **Boost Shareability**: Craft "golden sentences" or memorable quotes suitable for readers to screenshot and share. **Formatting Optimization Suggestions**: Remind the user to appropriately use bolding, blockquotes, and dividers to enhance readability. FILE:references/examples.md # WeChat Official Account Article Example Reference This document provides title and article structure examples for creative reference. ## I. High-Click-Through Title Examples ### Pain Point Solution Type - Working Overtime Until 10 PM Daily? 3 Methods to Get You Home on Time - Can't Save Money? You Might Be Making These 5 Mistakes - Poor Sleep Quality? Never Do This One Hour Before Bed ### Data Suspense Type - The Promotion Secret 90% of Professionals Don't Know - Surveyed 100 Executives, Found They All Have This Habit - Data Shows: People Earning Over 10K Monthly Are All Doing This ### Counter-Intuitive Type - Why Do Harder Workers Seem Less Successful? - Stop Forcing Yourself to Wake Up Early, Here's the Truth About High Performers - So-Called High EQ Is Really Just "Speaking Well" ### Identity Affirmation Type - As a Post-90s Generation, I Want to Talk About "Lying Flat" - After 5 Years Drifting in Beijing, I Finally Realized What True Happiness Is - Programmer's Age 35 Crisis? Here's How I Broke Through ### Curiosity Gap Type - What Does That Colleague Who Never Works Overtime Secretly Do? - Jack Ma's Most Admired Employee Wasn't the Top Performer - A Resignation Letter Exposed All Workplace Unspoken Rules ## II. Article Structure Examples ### Example 1: Methodology Article ``` Title: Working Overtime Until 10 PM Daily? 3 Methods to Get You Home on Time 【Introduction】 (Pain Point Scenario) "Working overtime until 10 PM again, the subway's already stopped." Xiao Wang checked his phone—it was 10:30 PM. This was his 15th consecutive day of overtime; exhausted yet still worrying about tomorrow's meeting... Raise the question: Why, despite obvious hard work, can't the tasks be finished? 【Body】 Section 1: Problem Analysis — You Might Be Trapped in "Pseudo-Diligence" Section 2: Method One — Time Blocking: Returning Time to What Matters Section 3: Method Two — Outcome-Oriented: Don't Be Moved by the Process Alone Section 4: Method Three — Learn to Say No: Your Time Is Valuable Section 5: Real Case Study — Xiao Wang's Transformation into an Efficiency Expert 【Conclusion】 Summary + Call to Action: "Leaving work on time isn't laziness; it's working smarter. Starting today, try these three methods..." Guide Interaction: "What are your tips for working efficiently? Share in the comments~" ``` ### Example 2: Opinion Article ``` Title: Why Do Harder Workers Seem Less Successful? 【Introduction】 (Counter-Intuitive Lead-In) You may have heard "Heaven rewards the diligent," but reality often shows the opposite: those who constantly claim to be busy tend to fare averagely, while truly successful people appear quite leisurely... 【Body】 Section 1: Phenomenon Analysis — Three Manifestations of the "Hard Work" Trap Section 2: Underlying Reasons — Direction Matters More Than Speed Section 3: Cognitive Upgrade — What Constitutes True "Hard Work"? Section 4: Practical Advice — The Smart Person's Law of Effort Section 5: Case Comparison — Two Kinds of Effort, Two Different Lives 【Conclusion】 Elevated Viewpoint: "Hard work is never the problem; the question is whether your effort is in the right direction." Golden Sentence Closing: "Choice outweighs effort; direction determines the destination." ``` ### Example 3: Brand Advertorial ``` Title: What Happened to That Person Who Insisted on Waking Up Early? 【Introduction】 (Life Scenario) At exactly 6:00 AM, the alarm clock rings promptly. Zhang Ming habitually turns it off, gets up quietly... Introduce Theme: Does waking up early really change your life? 【Body】 Section 1: Predicament — Once a Lost Office Worker Section 2: Turning Point — A Fortuitous Decision Section 3: Change — Astonishing Shifts After Waking Early Section 4: Tool — [Natural Product Integration] Section 5: Action — The 40-Day Early Rising Plan 【Conclusion】 "Forty days later, Zhang Ming not only formed the habit of waking early but also completed his first half marathon..." Guide: "If you also want to change, start by waking up just 10 minutes earlier tomorrow." ``` ## III. Multimedia Placement Annotation Examples Insert in appropriate places within the body text: ``` [Suggested image placement here: Scene of office workers working late at night] [Suggested image placement here: Diagram of the Time Management Four-Quadrant Matrix] [Suggested image placement here: Flowchart of the Pomodoro Technique] [Suggested data chart placement here: Bar chart comparing different work efficiencies] ``` ## IV. Language Style Comparison | Target Audience | Language Style Characteristics | Example Phrasing | |-----------------|-------------------------------|------------------| | Young White-Collar | Light-hearted, strong internet savvy | "What happened to no overtime?" "This move is legendary" | | Workplace Newcomers | Friendly and encouraging, practical | "Don't worry, let me show you how to fix this," "Try this method" | | Corporate Executives | Professional and concise, data-backed | "Data indicates...", "From a management perspective..." | | Mom Groups | Warm and empathetic, scenario-based | "As mothers, we all understand...", "Days spent with the kids..." | | Student Groups | Down-to-earth, resonant | "Let's talk about exam week...", "My roommate was stunned" |
SQLite database operations. Use this skill when users need to create, read, query, or modify SQLite databases (.db files).
---
name: sqlite-client
description: SQLite database operations. Use this skill when users need to create, read, query, or modify SQLite databases (.db files).
---
# SQLite Client
Use the `sqlite` (v5+) + `sqlite3` libraries to operate SQLite databases. All APIs return ES6 Promises and support async/await.
## Use Cases
- Creating SQLite databases and tables
- Executing SQL queries (SELECT/INSERT/UPDATE/DELETE)
- Database migrations
- Reading or analyzing the contents of .db files
- Importing/exporting data to/from SQLite
- Using in-memory databases for rapid prototyping
## Prerequisites
Before performing any database operations, ensure dependencies are installed in the project:
```bash
npm install sqlite3 sqlite
```
## Quick Start
### Opening a Database
```js
const sqlite3 = require('sqlite3')
const { open } = require('sqlite')
async function getDb() {
return open({
filename: './data.db', // File path, or ':memory:' for in-memory database
driver: sqlite3.Database
})
}
```
### Using Cached Instances
```js
driver: sqlite3.cached.Database // Reuse connections for the same file
```
### Closing the Database
```js
await db.close()
```
## Core Operations
### Creating Tables & Inserting Data
```js
await db.exec('CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT, email TEXT)')
await db.exec(`INSERT INTO users (name, email) VALUES ('Alice', '[email protected]')`)
```
### Querying a Single Row
```js
const row = await db.get('SELECT * FROM users WHERE id = ?', [1])
// row = { id: 1, name: 'Alice', email: '[email protected]' } or undefined
```
### Querying Multiple Rows
```js
const rows = await db.all('SELECT * FROM users WHERE name LIKE ?', ['%li%'])
// rows = [{ id: 1, name: 'Alice', ... }]
```
### Inserting a Row
```js
const result = await db.run('INSERT INTO users (name, email) VALUES (?, ?)', ['Bob', '[email protected]'])
// result.lastID → New row ID
// result.changes → Number of rows affected
```
### Updating / Deleting Rows
```js
const result = await db.run('UPDATE users SET name = ? WHERE id = ?', ['Bob Updated', 2])
// result.changes → Number of rows affected
await db.run('DELETE FROM users WHERE id = ?', [2])
```
### Named Parameters
```js
await db.get('SELECT * FROM users WHERE name = :name', { ':name': 'Alice' })
await db.run('INSERT INTO users (name, email) VALUES (:name, :email)', { ':name': 'Carol', ':email': '[email protected]' })
```
### Prepared Statements
```js
const stmt = await db.prepare('INSERT INTO users (name, email) VALUES (?, ?)')
await stmt.run('Dave', '[email protected]')
await stmt.run('Eve', '[email protected]')
await stmt.finalize() // Must finalize after use
```
### Iterating Row by Row (each)
```js
const rowCount = await db.each(
'SELECT * FROM users',
[],
(err, row) => {
if (err) throw err
console.log(row.name)
}
)
// rowCount → Total number of rows processed
```
## Migrations
Create a `migrations/` folder in the project directory, name SQL files sequentially (e.g., `001-init.sql`), and then execute:
```js
await db.migrate({
force: false, // true to rollback and reapply the latest migration
table: 'migrations', // Name of the migration record table
migrationsPath: './migrations' // Path to migration files
})
```
Example migration file `migrations/001-init.sql`:
```sql
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT UNIQUE NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
```
## Utility Functions
Common patterns for reading the contents of a `.db` file:
```js
// List all tables
const tables = await db.all("SELECT name FROM sqlite_master WHERE type='table'")
// Get table schema
const info = await db.all(`PRAGMA table_info(tableName)`)
// Get row count
const { count } = await db.get(`SELECT COUNT(*) as count FROM tableName`)
```
## Debugging
```js
const sqlite3 = require('sqlite3')
sqlite3.verbose() // Enable verbose logging
db.on('trace', (sql) => {
console.log('SQL:', sql)
})
```
## Notes
- The `db` object returned by `open()` wraps `sqlite3.Database`; all methods return Promises.
- `db.exec()` is used for executing multiple SQL statements (no return value); `db.run()` is for single write operations.
- Prepared statements must be `finalize()`d after use to prevent memory leaks.
- SQLite supports a maximum database file size of 281 TB, with a maximum row size of approximately 1 GB.
- For concurrent writes, use WAL mode: `await db.exec('PRAGMA journal_mode=WAL')`
## Advanced Reference
For detailed API documentation and more usage patterns, see [references/api.md](references/api.md).
FILE:scripts/inspect.js
#!/usr/bin/env node
/**
* SQLite Database Structure Overview Script
*
* Usage:
* node inspect.js <db-path> [--json] [--table <name>]
*
* Examples:
* node inspect.js ./data.db # List all tables and summary
* node inspect.js ./data.db --table users # View structure and sample data of a specific table
* node inspect.js ./data.db --json # Output in JSON format
*/
const path = require('path')
async function main() {
const args = process.argv.slice(2)
if (args.length < 1) {
console.error('Usage: node inspect.js <db-path> [--json] [--table <name>]')
process.exit(1)
}
const dbPath = path.resolve(args[0])
let outputJson = false
let tableName = null
for (let i = 1; i < args.length; i++) {
if (args[i] === '--json') outputJson = true
if (args[i] === '--table' && args[i + 1]) tableName = args[++i]
}
let sqlite3, open
try {
sqlite3 = require('sqlite3')
; ({ open } = require('sqlite'))
} catch (e) {
console.error('Missing dependencies. Please run: npm install sqlite3 sqlite')
process.exit(1)
}
const db = await open({ filename: dbPath, driver: sqlite3.Database })
try {
if (tableName) {
// View specific table
const columns = await db.all(`PRAGMA table_info("tableName")`)
const rowCount = await db.get(`SELECT COUNT(*) as count FROM "tableName"`)
const sampleRows = await db.all(`SELECT * FROM "tableName" LIMIT 5`)
const indexes = await db.all(`PRAGMA index_list("tableName")`)
const result = { table: tableName, columns, rowCount: rowCount.count, sampleRows, indexes }
if (outputJson) {
console.log(JSON.stringify(result, null, 2))
} else {
console.log(`\n📊 Table: tableName`)
console.log(` Row count: rowCount.count`)
console.log(`\n Columns:`)
for (const col of columns) {
const pk = col.pk ? ' 🔑' : ''
const nn = col.notnull ? ' NOT NULL' : ''
const dflt = col.dflt_value ? ` DEFAULT col.dflt_value` : ''
console.log(` - col.name (col.type)pknndflt`)
}
if (indexes.length > 0) {
console.log(`\n Indexes:`)
for (const idx of indexes) {
const idxInfo = await db.all(`PRAGMA index_info("idx.name")`)
const cols = idxInfo.map(i => i.name).join(', ')
const unique = idx.unique ? ' (UNIQUE)' : ''
console.log(` - idx.name: colsunique`)
}
}
if (sampleRows.length > 0) {
console.log(`\n Sample data (first 5 rows):`)
console.log(JSON.stringify(sampleRows, null, 4))
}
}
} else {
// List all tables
const tables = await db.all("SELECT name, type FROM sqlite_master WHERE type IN ('table', 'view') ORDER BY name")
const result = []
for (const t of tables) {
const count = await db.get(`SELECT COUNT(*) as count FROM "t.name"`)
const cols = await db.all(`PRAGMA table_info("t.name")`)
result.push({
name: t.name,
type: t.type,
columns: cols.length,
rowCount: count.count
})
}
if (outputJson) {
console.log(JSON.stringify(result, null, 2))
} else {
console.log(`\n📁 Database: dbPath`)
console.log(` Total tables.length table(s)/view(s)\n`)
for (const t of result) {
console.log(` 📋 t.name (t.type) — t.columns column(s), t.rowCount row(s)`)
}
}
}
} finally {
await db.close()
}
}
main().catch(e => {
console.error('Error:', e.message)
process.exit(1)
})
FILE:scripts/query.js
#!/usr/bin/env node
/**
* SQLite Database Query Helper Script
*
* Usage:
* node query.js <db-path> <sql> [--json] [--limit N]
*
* Examples:
* node query.js ./data.db "SELECT * FROM users"
* node query.js ./data.db "SELECT * FROM users" --json
* node query.js ./data.db "SELECT * FROM users" --limit 10
*/
const path = require('path')
async function main() {
const args = process.argv.slice(2)
if (args.length < 2) {
console.error('Usage: node query.js <db-path> <sql> [--json] [--limit N]')
process.exit(1)
}
const dbPath = path.resolve(args[0])
let sql = args[1]
let outputJson = false
let limit = null
for (let i = 2; i < args.length; i++) {
if (args[i] === '--json') outputJson = true
if (args[i] === '--limit' && args[i + 1]) limit = parseInt(args[++i])
}
// Dynamically load sqlite3
let sqlite3, open
try {
sqlite3 = require('sqlite3')
; ({ open } = require('sqlite'))
} catch (e) {
console.error('Missing dependencies. Please run: npm install sqlite3 sqlite')
process.exit(1)
}
const db = await open({ filename: dbPath, driver: sqlite3.Database })
try {
// Determine SQL type
const sqlUpper = sql.trim().toUpperCase()
const isRead = sqlUpper.startsWith('SELECT') || sqlUpper.startsWith('PRAGMA')
if (isRead) {
if (limit && !sqlUpper.includes('LIMIT')) {
sql += ` LIMIT limit`
}
const rows = await db.all(sql)
if (outputJson) {
console.log(JSON.stringify(rows, null, 2))
} else {
if (rows.length === 0) {
console.log('(No results)')
} else {
// Simple table output
const cols = Object.keys(rows[0])
const colWidths = cols.map(c => {
const maxData = Math.max(...rows.map(r => String(r[c] ?? 'NULL').length))
return Math.max(c.length, maxData, 4)
})
const sep = colWidths.map(w => '-'.repeat(w + 2)).join('+')
console.log(sep)
console.log('| ' + cols.map((c, i) => c.padEnd(colWidths[i])).join(' | ') + ' |')
console.log(sep)
for (const row of rows) {
console.log('| ' + cols.map((c, i) => String(row[c] ?? 'NULL').padEnd(colWidths[i])).join(' | ') + ' |')
}
console.log(sep)
console.log(`(rows.length row'')`)
}
}
} else {
const result = await db.run(sql)
if (outputJson) {
console.log(JSON.stringify(result, null, 2))
} else {
if (result.lastID) console.log(`Inserted row ID: result.lastID`)
if (result.changes !== undefined) console.log(`Rows affected: result.changes`)
}
}
} finally {
await db.close()
}
}
main().catch(e => {
console.error('Error:', e.message)
process.exit(1)
})
FILE:references/api.md
# SQLite Client API Reference
## open() Configuration Parameters
```typescript
const db = await open({
filename: string, // File path, ':memory:' for anonymous in-memory database, '' for anonymous disk database
mode?: number, // sqlite3.OPEN_READONLY | OPEN_READWRITE | OPEN_CREATE, default READWRITE | CREATE
driver: any // sqlite3.Database or compatible driver
})
```
### Custom Driver
Any library conforming to the sqlite3 API can be used as a driver:
```js
const sqlite3Offline = require('sqlite3-offline-next')
const db = await open({
filename: './data.db',
driver: sqlite3Offline.Database
})
```
### Opening Multiple Databases
```js
const [db1, db2] = await Promise.all([
open({ filename: './db1.db', driver: sqlite3.Database }),
open({ filename: './db2.db', driver: sqlite3.Database })
])
```
## Database Methods
### db.get(sql, [...params])
Returns the first matching row, or `undefined` if no match.
```js
const row = await db.get('SELECT * FROM users WHERE id = ?', 1)
const row2 = await db.get('SELECT * FROM users WHERE id = ?', [1])
const row3 = await db.get('SELECT * FROM users WHERE id = :id', { ':id': 1 })
```
### db.all(sql, [...params])
Returns an array of all matching rows.
```js
const rows = await db.all('SELECT * FROM users LIMIT ?', [100])
```
### db.run(sql, [...params])
Executes a write operation, returning `{ lastID, changes, stmt }`.
```js
const { lastID, changes } = await db.run('INSERT INTO users (name) VALUES (?)', 'Alice')
const { changes: updated } = await db.run('UPDATE users SET name = ? WHERE id = ?', 'Bob', 1)
```
### db.exec(sql)
Executes multiple SQL statements (no return value). Suitable for creating tables, batch inserts, etc.
```js
await db.exec(`
CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMARY KEY, name TEXT);
INSERT INTO users (name) VALUES ('Alice');
INSERT INTO users (name) VALUES ('Bob');
`)
```
### db.each(sql, [...params], callback)
Processes rows one by one with a callback. `callback(err, row)` is triggered once per row; the Promise resolves to the total row count.
```js
const count = await db.each('SELECT * FROM users', [], (err, row) => {
if (err) throw err
console.log(row)
})
console.log(`Processed count rows`)
```
### db.prepare(sql, [...params])
Creates a prepared statement, returning a Statement object.
```js
const stmt = await db.prepare('INSERT INTO users (name) VALUES (?)')
await stmt.run('Alice')
await stmt.run('Bob')
await stmt.finalize()
```
### db.migrate(config)
Runs SQL migration files.
```js
await db.migrate({
force?: boolean, // Force rollback and re-run latest migration
table?: string, // Migration record table name, default 'migrations'
migrationsPath?: string // Migration directory, default cwd + '/migrations'
})
```
### db.close()
Closes the database connection.
```js
await db.close()
```
### db.getDatabaseInstance()
Gets the underlying sqlite3 driver instance for calling unwrapped methods.
```js
const rawDb = db.getDatabaseInstance()
```
## Statement Methods
### stmt.run([...params])
Executes the prepared statement, returning the same structure as `db.run()`.
### stmt.get([...params])
Returns the first matching row.
### stmt.all([...params])
Returns all matching rows.
### stmt.bind([...params])
Binds parameters to an already prepared statement.
```js
const stmt = await db.prepare('SELECT * FROM users WHERE id = ? AND name = ?')
await stmt.bind([1, 'Alice'])
const row = await stmt.get()
```
### stmt.finalize()
Releases prepared statement resources. **Must be called** to prevent memory leaks.
### stmt.getStatementInstance()
Gets the underlying sqlite3 Statement instance.
## Compatibility with sql-template-strings
```js
const SQL = require('sql-template-strings')
const book = 'harry potter'
const data = await db.all(SQL`SELECT * FROM books WHERE name = book`)
```
## TypeScript Generics
```typescript
interface User { id: number; name: string; email: string }
const row = await db.get<User>('SELECT * FROM users WHERE id = ?', 1)
// row: User | undefined
const rows = await db.all<User[]>('SELECT * FROM users')
// rows: User[]
```
## Common PRAGMAs
```js
await db.exec('PRAGMA journal_mode=WAL') // Optimize for concurrent writes
await db.exec('PRAGMA foreign_keys=ON') // Enable foreign key constraints
await db.exec('PRAGMA busy_timeout=5000') // Lock wait timeout in ms
const info = await db.all('PRAGMA table_info(users)') // Table schema
const indexList = await db.all('PRAGMA index_list(users)') // Index list
```
## FAQ
### SQLITE_BUSY Error
Multiple writers conflicting. Solutions:
1. Set `PRAGMA busy_timeout=5000`
2. Use WAL mode `PRAGMA journal_mode=WAL`
3. Serialize write operations
### Database File Locked
Ensure all `db` connections are closed after use with `await db.close()`. For long-running processes, consider using a connection pool pattern.
### Performance Optimization
- Wrap batch inserts in a transaction using `db.exec()`:
```js
await db.exec('BEGIN')
for (const item of items) {
await db.run('INSERT INTO tbl VALUES (?, ?)', item.a, item.b)
}
await db.exec('COMMIT')
```
- Use `db.each()` to process large datasets row by row, avoiding loading everything into memory
- Use prepared statements `db.prepare()` for frequently executed queriesPrevents AI from giving up prematurely by exhausting all options, verifying fixes, troubleshooting proactively, and providing evidence before concluding.
--- name: self-apply-pressure description: Prevents AI from slacking off, getting stuck, shifting blame, asking empty questions, or declaring completion without verification. Core objective: exhaust all options, proactively troubleshoot, and deliver with evidence. --- # Self-Applied Pressure Prevents AI from slacking off, getting stuck, shifting blame, asking empty questions, or declaring completion without verification. Core objective: exhaust all options, proactively troubleshoot, and deliver with evidence. ## Three Iron Rules 1. **Do not say "I cannot resolve this" before exhausting all primary options.** 2. **Do first, ask later.** Prioritize searching, reading files, running commands, and checking context; only ask questions when genuinely lacking user-specific information, and attach evidence of what you have already checked. 3. **Proactively close the loop.** After fixing the current point, continue checking for similar issues, upstream/downstream impacts, edge cases, and regression risks. ## Trigger Conditions (Enter High-Pressure Mode) Immediately enter high-pressure mode when any of the following occurs: - Same approach fails 2 or more times - Repeatedly fine-tuning old solutions without changing direction - Tempted to say "I cannot resolve this" - Suggesting the user handle something manually - Attributing issues to the environment without verification - Drawing conclusions without searching, reading source code, or consulting documentation - Not verifying after a fix - User explicitly requests "try again" or "try a different approach" ## Pressure Escalation Mechanism | Failure Count | Level | Mandatory Action | |---------------|-------|------------------| | 2nd time | L1 | Stop fine-tuning the old approach; change to a fundamentally different direction | | 3rd time | L2 | Search for the full error, read source code/docs, list 3 distinct hypotheses | | 4th time | L3 | Complete the checklist and verify 3 new hypotheses item by item | | 5th time or more | L4 | Build a minimal PoC, isolate the environment, change paths or swap tech stacks if necessary to break through | ## Five-Step Methodology ### 1. Identify Stuck Pattern First, list the approaches already attempted and determine if you are just spinning your wheels in the same spot. ### 2. Elevate Perspective Proceed in order: 1. Read the failure signal word for word 2. Proactively search for the error, documentation, and case studies 3. Read the original material, not just summaries 4. Verify preconditions 5. Reverse assumptions and investigate from the opposite direction ### 3. Self-Check - Am I only tweaking parameters without changing the core idea? - Am I only treating symptoms without finding the root cause? - Have I failed to search, read, or run something that should have been done? - Have I failed to verify even the simplest possibility? ### 4. Execute New Approach The new approach must: - Be fundamentally different from the last round - Have clear verification criteria - Produce new information even if it fails ### 5. Review Document which approach worked, why it wasn't thought of earlier, and what related risks and similar issues remain to be swept. ## Pre-Completion Checklist - [ ] Has actual verification been performed, rather than subjective assumption? - [ ] After code changes, has build/test/actual path been executed? - [ ] After config changes, has effectiveness been confirmed? - [ ] For API or script results, have actual returns been inspected? - [ ] Are there similar issues in the same file or module? - [ ] Are upstream and downstream dependencies affected? - [ ] Are edge cases and exception paths covered? - [ ] Is evidence provided rather than verbal conclusions? ## High-Pressure Behavioral Standards - **Encountering errors**: Do not just read the error message; examine the context, dependencies, environment, documentation, and similar cases. - **Fixing bugs**: Do not just fix one spot; check for similar issues in the same file, module, or pattern. - **Insufficient information**: Self-check first, then ask; questions must be accompanied by evidence of what has been checked. - **Debugging failures**: Not "I tried A/B and it didn't work," but "I tried A/B/C, ruled out X/Y, and have narrowed it down to Z." - **Task completion**: Must provide build, test, curl, run results, API responses, or other objective evidence. ## Common Prodding Phrases - You lack initiative; don't wait for the user to push you. - Where is the sense of ownership? The problem ends with you when it reaches your hands. - Where is the end-to-end validation? Is it fixed, verified, and regression-tested? - Where is the evidence? No output means not complete. - Don't be an NPC. Don't just execute orders; proactively discover and fill gaps. ## Anti-Slacking Rules When the following excuses appear, default to entering high-pressure mode: - "This is beyond my capability" - "Suggest the user handle this manually" - "It might be an environmental issue" - "Need more context" - "This API does not support it" - "I have tried everything" - "Results are uncertain, so I won't provide an answer for now" These are not conclusions; at most, they are unverified hypotheses. Continue searching, verifying, narrowing down, and then report back. ## Graceful Failure Output Only after major paths have been verified is it permissible to output a structured failure report: ``` [PUA-REPORT] task: <current task> failure_count: <failure count> failure_mode: <stuck spinning | direct abandonment/passing blame | completed but poor quality | guessing without searching | passive waiting> attempts: <approaches tried> excluded: <possibilities ruled out> next_hypothesis: <next hypothesis> ```
Multi-skill workflow orchestrator. Chain multiple skills into automated pipelines, triggering entire sequences like "search → summarize → generate report → s...
---
name: skill-workflow-orchestrator
description: Multi-skill workflow orchestrator. Chain multiple skills into automated pipelines, triggering entire sequences like "search → summarize → generate report → send email" with a single phrase. Supports conditional branching and error handling; serves as foundational infrastructure for building complex Agent workflows.
---
# Skill Workflow Orchestrator
## Overview
This skill orchestrates multiple sub-skills into automated pipelines. A complete skill chain can be triggered through natural language descriptions, supporting sequential execution, conditional branching, and error handling.
## Use Cases
Automatically triggers when user descriptions involve multi-step tasks, for example:
- "Search for the latest AI news, generate a summary report, and then email it to me."
- "Check the stock price; if it rises more than 5%, remind me."
- "Read the PDF file, extract the content, summarize it, and save it to notes."
## Workflow Definition
### 1. Parse User Intent
Parse the user's natural language description into a structured skill chain:
```
User: "Search AI news → Summarize → Send email"
→ Parsed into:
[
{"skill": "multi-search-engine", "task": "Search latest AI news"},
{"skill": "content-summarizer", "task": "Generate summary"},
{"skill": "email-skill", "task": "Send email"}
]
```
### 2. Sequential Execution
Invoke each skill in order, with the output of the previous skill serving as the input for the next:
```python
# Pseudocode example
results = []
for step in workflow:
skill = load_skill(step.skill)
input_data = results[-1] if results else None
result = skill.execute(step.task, input_data)
results.append(result)
```
### 3. Conditional Branching
Supports if/else logic:
```
If [condition] → Execute [Skill A]
Else → Execute [Skill B]
```
Supported comparison operators:
- Numeric comparison: `>`, `<`, `>=`, `<=`, `==`, `!=`
- String containment: `contains`, `startswith`, `endswith`
- Boolean checks: `is_true`, `is_false`, `exists`
### 4. Error Handling
- **Retry Mechanism**: Automatically retry failed steps up to 2 times
- **Skip and Continue**: Optionally continue executing subsequent steps when a step fails
- **Fallback Execution**: Support defining an alternative skill chain on failure
## Built-in Templates
### Template 1: Information Gathering Chain
```
Search → Content Extraction → Organize and Save
```
Use Cases: Competitor research, news tracking, data collection
### Template 2: Analysis Report Chain
```
Fetch Data → Analyze and Process → Generate Report → Send Notification
```
Use Cases: Stock analysis, operational reports, data dashboards
### Template 3: Content Creation Chain
```
Topic Selection → Search Material → Create Content → Review and Publish
```
Use Cases: Blog posts, social media management
## Configuration Options
Specifiable within a workflow:
| Option | Description | Example |
|--------|-------------|---------|
| `timeout` | Timeout per skill (seconds) | `30` |
| `retry` | Number of retry attempts on failure | `2` |
| `continue_on_error` | Whether to continue after failure | `true/false` |
| `output_format` | Final output format | `json/markdown/text` |
## Usage Examples
### Example 1: Simple Chain
> User: Search for the latest developments in quantum computing, generate a summary, and save it to notes.
```json
{
"steps": [
{"skill": "multi-search-engine", "task": "Latest developments in quantum computing"},
{"skill": "content-summarizer", "task": "Generate summary"},
{"skill": "ima-skill", "task": "Save to notes"}
]
}
```
### Example 2: With Conditional Branching
> User: Check the price of BTC; if it drops below $50,000, remind me to sell.
```json
{
"steps": [
{"skill": "neodata-financial-search", "task": "BTC price"},
{
"condition": "price < 50000",
"then": [{"skill": "message", "task": "Remind to sell"}],
"else": []
}
]
}
```
### Example 3: With Error Handling
> User: Read this PDF, extract the table data; if it fails, send me an email notification.
```json
{
"steps": [
{"skill": "pdf", "task": "Read PDF", "retry": 3},
{"skill": "xlsx", "task": "Extract table data"}
],
"on_error": {
"skill": "email-skill",
"task": "Send error notification"
}
}
```
## Notes
1. Total skill chain length is recommended not to exceed 10 steps
2. Complex workflows should be split into multiple simpler chains
3. Sensitive operations (e.g., sending emails, messages) require user confirmation
4. Periodically check the validity and latest versions of all sub-skillsStatic site reproduction expert - Analyze target websites and manually code their structure, visual style, and basic interactions using pure HTML/CSS/JavaScr...
---
name: static-site-cloner
description: Static site reproduction expert - Analyze target websites and manually code their structure, visual style, and basic interactions using pure HTML/CSS/JavaScript.
---
# Static Site Cloner
Based on a target website URL, accurately reproduce the site's structure, visuals, and interactions using pure HTML, CSS, and JavaScript. Output only front-end code, without involving backend functionality.
## Use Cases
- User requests to "reproduce a website," "clone a website," "recreate a website," "copy a web page"
- User provides a website URL and requests code rewrite
- User needs to convert an existing website into pure front-end code
- User wants to learn or understand the front-end implementation of a particular website
## Workflow
### 1. Information Gathering
Use `web_fetch` to retrieve the HTML content of the target website:
```
web_fetch(url="target_url", extractMode="markdown")
```
Analyze and document:
- Page structure (navigation, header, main content, footer)
- Visual elements (colors, typography, spacing, shadows)
- Interactive behaviors (clicks, hovers, animations)
### 2. Structure Reproduction
Write semantic HTML:
- Use proper HTML5 tags (header, nav, main, section, article, footer)
- Maintain DOM hierarchy consistent with the original site
- Add clear comments explaining the function of each section
### 3. Style Restoration
Write CSS styles:
- Prefer Flexbox/Grid layout
- Implement responsive design (media queries)
- Pay attention to pseudo-classes and transition effects (:hover, :focus, transition)
- Use CSS variables to manage colors and spacing
### 4. Interaction Implementation
Use vanilla JavaScript:
- Event listeners (addEventListener)
- DOM manipulation (classList, style, innerHTML)
- Animation effects (requestAnimationFrame or CSS Animation)
### 5. Output Specification
Generate runnable code:
```
project_directory/
├── index.html
├── styles/
│ └── main.css
└── scripts/
└── main.js
```
Or a single-file version (inline CSS/JS).
## Code Conventions
```
<!-- HTML: Semantic + Comments -->
<header class="site-header">
<!-- Navigation bar -->
<nav class="navbar">...</nav>
</header>
/* CSS: BEM Naming + CSS Variables */
:root {
--primary-color: #3498db;
--spacing-unit: 8px;
}
.navbar__link--active {
color: var(--primary-color);
}
// JavaScript: Modern ES6+ Syntax
const toggleMenu = () => {
document.body.classList.toggle('menu-open');
};
```
## Limitations
- **Pure front-end technologies only**: HTML, CSS, JavaScript (no React/Vue/jQuery)
- **No backend functionality**: No database, API, or server-side rendering
- **Image placeholders**: Use placeholder services (e.g., placeholder.com, picsum.photos)
- **Copyright compliance**: Do not copy original site text content, trademarks, or sensitive information
## References
For more detailed examples and patterns, refer to:
- [references/examples.md](references/examples.md) - Reproduction examples for common website types
- [references/patterns.md](references/patterns.md) - CSS layout and interaction pattern references
FILE:references/examples.md
# Website Reproduction Examples
## Example 1: Simple Landing Page
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Landing Page Example</title>
<style>
:root {
--primary: #2563eb;
--text-dark: #1f2937;
--text-light: #6b7280;
--bg-light: #f9fafb;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
line-height: 1.6;
color: var(--text-dark);
}
.hero {
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 2rem;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.hero h1 { font-size: 3rem; margin-bottom: 1rem; }
.hero p { font-size: 1.25rem; opacity: 0.9; max-width: 600px; }
.btn {
margin-top: 2rem;
padding: 1rem 2rem;
background: white;
color: var(--primary);
border: none;
border-radius: 8px;
font-size: 1rem;
cursor: pointer;
transition: transform 0.2s, box-shadow 0.2s;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 10px 20px rgba(0,0,0,0.2);
}
</style>
</head>
<body>
<section class="hero">
<h1>Product Name</h1>
<p>Concise and compelling product description, highlighting value proposition</p>
<button class="btn">Get Started</button>
</section>
</body>
</html>
```
## Example 2: Navigation + Content Layout
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Navigation Layout Example</title>
<style>
:root {
--header-height: 64px;
--sidebar-width: 240px;
}
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: system-ui, sans-serif;
}
/* Navigation bar */
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: var(--header-height);
background: #fff;
border-bottom: 1px solid #e5e7eb;
display: flex;
align-items: center;
padding: 0 2rem;
z-index: 100;
}
.navbar__logo { font-weight: 700; font-size: 1.25rem; }
.navbar__menu {
display: flex;
gap: 2rem;
margin-left: auto;
list-style: none;
}
.navbar__link {
text-decoration: none;
color: #4b5563;
transition: color 0.2s;
}
.navbar__link:hover { color: #2563eb; }
/* Sidebar + Main content */
.layout {
display: flex;
padding-top: var(--header-height);
min-height: 100vh;
}
.sidebar {
width: var(--sidebar-width);
background: #f9fafb;
padding: 1.5rem;
border-right: 1px solid #e5e7eb;
}
.main {
flex: 1;
padding: 2rem;
}
/* Responsive */
@media (max-width: 768px) {
.sidebar { display: none; }
.navbar__menu { display: none; }
}
</style>
</head>
<body>
<header class="navbar">
<div class="navbar__logo">Brand</div>
<ul class="navbar__menu">
<li><a href="#" class="navbar__link">Home</a></li>
<li><a href="#" class="navbar__link">Products</a></li>
<li><a href="#" class="navbar__link">About</a></li>
</ul>
</header>
<div class="layout">
<aside class="sidebar">
<nav><!-- Sidebar navigation --></nav>
</aside>
<main class="main">
<h1>Main Content Area</h1>
<p>This is the main content of the page...</p>
</main>
</div>
</body>
</html>
```
## Example 3: Card Grid
```html
<section class="card-grid">
<article class="card">
<img src="https://picsum.photos/400/300" alt="Placeholder" class="card__image">
<div class="card__content">
<h3 class="card__title">Card Title</h3>
<p class="card__desc">Card description text</p>
</div>
</article>
<!-- More cards... -->
</section>
<style>
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 1.5rem;
padding: 2rem;
}
.card {
background: white;
border-radius: 12px;
overflow: hidden;
box-shadow: 0 1px 3px rgba(0,0,0,0.1);
transition: transform 0.2s, box-shadow 0.2s;
}
.card:hover {
transform: translateY(-4px);
box-shadow: 0 12px 24px rgba(0,0,0,0.15);
}
.card__image {
width: 100%;
height: 200px;
object-fit: cover;
}
.card__content { padding: 1.5rem; }
.card__title { font-size: 1.125rem; margin-bottom: 0.5rem; }
.card__desc { color: #6b7280; font-size: 0.875rem; }
</style>
```
FILE:references/patterns.md
# CSS 布局与交互模式
## 布局模式
### Flexbox 居中
```css
.center {
display: flex;
align-items: center;
justify-content: center;
}
```
### 两栏布局(左侧固定,右侧自适应)
```css
.two-column {
display: flex;
}
.sidebar { width: 250px; flex-shrink: 0; }
.main { flex: 1; }
```
### 粘性页脚
```css
body {
display: flex;
flex-direction: column;
min-height: 100vh;
}
main { flex: 1; }
footer { flex-shrink: 0; }
```
### 响应式网格
```css
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 1rem;
}
```
## 常见组件
### 导航栏
```html
<nav class="nav">
<a href="#" class="nav__logo">Logo</a>
<ul class="nav__list">
<li><a href="#" class="nav__link">首页</a></li>
<li><a href="#" class="nav__link">产品</a></li>
</ul>
<button class="nav__toggle" aria-label="菜单">
<span></span>
</button>
</nav>
```
```css
.nav {
display: flex;
align-items: center;
justify-content: space-between;
padding: 1rem 2rem;
background: #fff;
border-bottom: 1px solid #eee;
}
.nav__list {
display: flex;
gap: 2rem;
list-style: none;
}
.nav__link {
text-decoration: none;
color: inherit;
transition: color 0.2s;
}
.nav__link:hover { color: var(--primary); }
/* 移动端汉堡菜单 */
.nav__toggle { display: none; }
@media (max-width: 768px) {
.nav__list { display: none; }
.nav__toggle { display: block; }
}
```
### 按钮
```css
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 0.75rem 1.5rem;
font-size: 1rem;
font-weight: 500;
border: none;
border-radius: 6px;
cursor: pointer;
transition: all 0.2s;
}
.btn--primary {
background: var(--primary);
color: white;
}
.btn--primary:hover {
background: var(--primary-dark);
transform: translateY(-1px);
}
.btn--outline {
background: transparent;
border: 2px solid var(--primary);
color: var(--primary);
}
.btn--outline:hover {
background: var(--primary);
color: white;
}
```
### 卡片
```css
.card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
overflow: hidden;
transition: box-shadow 0.2s, transform 0.2s;
}
.card:hover {
box-shadow: 0 8px 16px rgba(0,0,0,0.15);
transform: translateY(-2px);
}
```
### 表单输入
```css
.input {
width: 100%;
padding: 0.75rem 1rem;
font-size: 1rem;
border: 1px solid #d1d5db;
border-radius: 6px;
transition: border-color 0.2s, box-shadow 0.2s;
}
.input:focus {
outline: none;
border-color: var(--primary);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}
```
## 交互效果
### 悬停动效
```css
.link {
position: relative;
text-decoration: none;
}
.link::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 0;
height: 2px;
background: var(--primary);
transition: width 0.3s;
}
.link:hover::after {
width: 100%;
}
```
### 模态框
```html
<div class="modal" id="modal">
<div class="modal__overlay"></div>
<div class="modal__content">
<button class="modal__close">×</button>
<!-- 内容 -->
</div>
</div>
```
```css
.modal {
position: fixed;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
opacity: 0;
visibility: hidden;
transition: opacity 0.3s, visibility 0.3s;
}
.modal.active {
opacity: 1;
visibility: visible;
}
.modal__overlay {
position: absolute;
inset: 0;
background: rgba(0,0,0,0.5);
}
.modal__content {
position: relative;
background: white;
border-radius: 12px;
padding: 2rem;
max-width: 500px;
transform: scale(0.9);
transition: transform 0.3s;
}
.modal.active .modal__content {
transform: scale(1);
}
```
```javascript
const modal = document.getElementById('modal');
const closeBtn = modal.querySelector('.modal__close');
closeBtn.addEventListener('click', () => modal.classList.remove('active'));
modal.querySelector('.modal__overlay').addEventListener('click', () =>
modal.classList.remove('active')
);
```
### 汉堡菜单
```javascript
const toggle = document.querySelector('.nav__toggle');
const menu = document.querySelector('.nav__list');
toggle.addEventListener('click', () => {
menu.classList.toggle('active');
toggle.classList.toggle('active');
});
```
```css
.nav__toggle span,
.nav__toggle span::before,
.nav__toggle span::after {
display: block;
width: 24px;
height: 2px;
background: #333;
transition: transform 0.3s;
}
.nav__toggle span {
position: relative;
}
.nav__toggle span::before,
.nav__toggle span::after {
content: '';
position: absolute;
left: 0;
}
.nav__toggle span::before { top: -8px; }
.nav__toggle span::after { top: 8px; }
.nav__toggle.active span { background: transparent; }
.nav__toggle.active span::before { transform: rotate(45deg); top: 0; }
.nav__toggle.active span::after { transform: rotate(-45deg); top: 0; }
```
## 动画
### 淡入
```css
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.fade-in {
animation: fadeIn 0.5s ease-out;
}
```
### 滑入
```css
@keyframes slideUp {
from {
opacity: 0;
transform: translateY(20px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.slide-up {
animation: slideUp 0.5s ease-out;
}
```
### 滚动触发
```javascript
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.classList.add('animate');
observer.unobserve(entry.target);
}
});
}, { threshold: 0.1 });
document.querySelectorAll('.animate-on-scroll').forEach(el => {
observer.observe(el);
});
```
FILE:assets/template.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="Website description">
<title>Website Title</title>
<style>
/* ====================
CSS Variables (Theme Configuration)
==================== */
:root {
/* Colors */
--color-primary: #2563eb;
--color-primary-dark: #1d4ed8;
--color-text: #1f2937;
--color-text-light: #6b7280;
--color-bg: #ffffff;
--color-bg-alt: #f9fafb;
--color-border: #e5e7eb;
/* Spacing */
--spacing-xs: 0.25rem;
--spacing-sm: 0.5rem;
--spacing-md: 1rem;
--spacing-lg: 1.5rem;
--spacing-xl: 2rem;
--spacing-2xl: 3rem;
/* Typography */
--font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
--font-size-sm: 0.875rem;
--font-size-base: 1rem;
--font-size-lg: 1.125rem;
--font-size-xl: 1.25rem;
--font-size-2xl: 1.5rem;
--font-size-3xl: 2rem;
/* Border Radius */
--radius-sm: 4px;
--radius-md: 8px;
--radius-lg: 12px;
--radius-full: 9999px;
/* Shadows */
--shadow-sm: 0 1px 2px rgba(0, 0, 0, 0.05);
--shadow-md: 0 4px 6px rgba(0, 0, 0, 0.1);
--shadow-lg: 0 10px 15px rgba(0, 0, 0, 0.1);
/* Transitions */
--transition-fast: 150ms ease;
--transition-base: 200ms ease;
--transition-slow: 300ms ease;
/* Layout */
--header-height: 64px;
--container-max: 1200px;
}
/* ====================
Base Reset
==================== */
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
html {
scroll-behavior: smooth;
}
body {
font-family: var(--font-family);
font-size: var(--font-size-base);
line-height: 1.6;
color: var(--color-text);
background-color: var(--color-bg);
-webkit-font-smoothing: antialiased;
}
img {
max-width: 100%;
height: auto;
display: block;
}
a {
color: inherit;
text-decoration: none;
}
ul,
ol {
list-style: none;
}
button {
font: inherit;
cursor: pointer;
border: none;
background: none;
}
/* ====================
Layout Components
==================== */
.container {
width: 100%;
max-width: var(--container-max);
margin: 0 auto;
padding: 0 var(--spacing-lg);
}
/* ====================
Navigation Bar
==================== */
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0;
height: var(--header-height);
background: var(--color-bg);
border-bottom: 1px solid var(--color-border);
z-index: 100;
}
.navbar__inner {
display: flex;
align-items: center;
justify-content: space-between;
height: 100%;
}
.navbar__logo {
font-size: var(--font-size-xl);
font-weight: 700;
color: var(--color-primary);
}
.navbar__menu {
display: flex;
gap: var(--spacing-xl);
}
.navbar__link {
font-weight: 500;
transition: color var(--transition-base);
}
.navbar__link:hover {
color: var(--color-primary);
}
.navbar__toggle {
display: none;
flex-direction: column;
gap: 5px;
padding: var(--spacing-sm);
}
.navbar__toggle span {
display: block;
width: 24px;
height: 2px;
background: var(--color-text);
transition: var(--transition-base);
}
/* ====================
Main Content
==================== */
.main {
padding-top: var(--header-height);
min-height: 100vh;
}
/* Hero Section */
.hero {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: var(--spacing-2xl);
min-height: calc(100vh - var(--header-height));
}
.hero__title {
font-size: var(--font-size-3xl);
font-weight: 700;
margin-bottom: var(--spacing-md);
}
.hero__subtitle {
font-size: var(--font-size-lg);
color: var(--color-text-light);
max-width: 600px;
margin-bottom: var(--spacing-xl);
}
/* ====================
Button Components
==================== */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
padding: var(--spacing-md) var(--spacing-xl);
font-size: var(--font-size-base);
font-weight: 500;
border-radius: var(--radius-md);
transition: all var(--transition-base);
}
.btn--primary {
background: var(--color-primary);
color: white;
}
.btn--primary:hover {
background: var(--color-primary-dark);
transform: translateY(-2px);
box-shadow: var(--shadow-md);
}
.btn--outline {
background: transparent;
border: 2px solid var(--color-primary);
color: var(--color-primary);
}
.btn--outline:hover {
background: var(--color-primary);
color: white;
}
/* ====================
Footer
==================== */
.footer {
background: var(--color-bg-alt);
padding: var(--spacing-xl) 0;
text-align: center;
color: var(--color-text-light);
}
/* ====================
Responsive Design
==================== */
@media (max-width: 768px) {
.navbar__menu {
display: none;
position: absolute;
top: var(--header-height);
left: 0;
right: 0;
flex-direction: column;
background: var(--color-bg);
padding: var(--spacing-lg);
border-bottom: 1px solid var(--color-border);
}
.navbar__menu.active {
display: flex;
}
.navbar__toggle {
display: flex;
}
.hero__title {
font-size: var(--font-size-2xl);
}
}
</style>
</head>
<body>
<!-- Navigation Bar -->
<header class="navbar">
<div class="navbar__inner container">
<a href="#" class="navbar__logo">Logo</a>
<nav>
<ul class="navbar__menu" id="navMenu">
<li><a href="#" class="navbar__link">Home</a></li>
<li><a href="#" class="navbar__link">Products</a></li>
<li><a href="#" class="navbar__link">About</a></li>
<li><a href="#" class="navbar__link">Contact</a></li>
</ul>
</nav>
<button class="navbar__toggle" id="navToggle" aria-label="Menu">
<span></span>
<span></span>
<span></span>
</button>
</div>
</header>
<!-- Main Content -->
<main class="main">
<section class="hero">
<h1 class="hero__title">Welcome</h1>
<p class="hero__subtitle">This is a basic static website template built with pure HTML, CSS, and JavaScript.</p>
<div class="hero__actions">
<a href="#" class="btn btn--primary">Get Started</a>
<a href="#" class="btn btn--outline" style="margin-left: 1rem;">Learn More</a>
</div>
</section>
</main>
<!-- Footer -->
<footer class="footer">
<div class="container">
<p>© 2026 Website Name. All rights reserved.</p>
</div>
</footer>
<!-- JavaScript -->
<script>
// Mobile menu toggle
const navToggle = document.getElementById('navToggle');
const navMenu = document.getElementById('navMenu');
navToggle.addEventListener('click', () => {
navMenu.classList.toggle('active');
navToggle.classList.toggle('active');
});
// Close menu when a menu item is clicked
navMenu.querySelectorAll('.navbar__link').forEach(link => {
link.addEventListener('click', () => {
navMenu.classList.remove('active');
navToggle.classList.remove('active');
});
});
// Add shadow to navigation bar on scroll
let lastScroll = 0;
window.addEventListener('scroll', () => {
const navbar = document.querySelector('.navbar');
const currentScroll = window.pageYOffset;
if (currentScroll > 10) {
navbar.style.boxShadow = 'var(--shadow-sm)';
} else {
navbar.style.boxShadow = 'none';
}
lastScroll = currentScroll;
});
</script>
</body>
</html>Conduct comprehensive competitor research through feature comparison matrices, product positioning analysis, differentiation strategy, and competitive impact...
---
name: competitive-dimensions-analysis
description: Conduct comprehensive competitor research through feature comparison matrices, product positioning analysis, differentiation strategy, and competitive impact assessment.
---
# Competitive Dimensions Analysis
Conduct comprehensive competitor research through feature comparison matrices, product positioning analysis, differentiation strategy, and competitive impact assessment.
## Use Cases
- Researching competitors
- Comparing capabilities across multiple products/services
- Assessing competitive positioning
- Preparing competitive strategy briefs
- Analyzing market landscape
- Developing differentiation strategies
- SWOT analysis
## Core Workflow
### Step 1: Clarify Analysis Objectives and Scope
Before beginning analysis, confirm with the user:
1. **Analysis Objective** — Understanding competitors for: capturing market share? Identifying differentiation opportunities? Evaluating product roadmap? Or investment/partnership decisions?
2. **Competitor Scope** — Which competitors does the user already have in mind? Which ones need to be added?
3. **Comparison Dimensions** — Features, pricing, user experience, technical architecture, market positioning, target audience, growth strategy?
> If the user does not specify comparison dimensions, prioritize covering: core features, pricing model, user experience, and differentiation points.
### Step 2: Information Gathering
Use multi-source search strategies to gather competitor information:
```markdown
Search Dimensions:
- Product features and capabilities (official websites, help docs, product demos)
- Pricing strategy (pricing pages, public reports)
- User reviews and feedback (App Store, marketplaces, social media)
- Company background and funding (Crunchbase, public reports)
- Tech stack and architecture (developer docs, tech blogs)
- Market performance and growth (public data, third-party reports)
```
### Step 3: Build Feature Comparison Matrix
Use `references/feature-matrix-template.md` as a template to output a structured comparison matrix:
```
| Dimension | Our Product | Competitor A | Competitor B | Competitor C |
|--------------------|-------------|--------------|--------------|--------------|
| Core Features | | | | |
| Pricing | | | | |
| Target Users | | | | |
| Differentiation | | | | |
| User Experience | | | | |
| Integration Ecosystem | | | | |
| Customer Support | | | | |
```
Mark each feature with: ✅ Fully supported / ⚠️ Partially supported / ❌ Not supported / 📌 Key differentiator
### Step 4: Positioning Analysis
Analyze each competitor's positioning strategy across the following dimensions:
1. **Target Users** — Which user segments are they targeting? What is their user persona?
2. **Value Proposition** — What is their core value proposition? What pain points do they solve?
3. **Brand Tone** — Brand positioning, tone, and market messaging
4. **Pricing Strategy** — Subscription / Freemium / One-time purchase / Usage-based?
5. **Market Strategy** — Primary acquisition channels, content marketing, community operations?
### Step 5: Strategic Impact Assessment
After completing the matrix and positioning analysis, provide strategic recommendations:
1. **SWOT Analysis** — Analyze strengths and weaknesses for each competitor and for our own product
2. **Differentiation Opportunities** — White space or weak points in our product offering
3. **Competitive Threat Level** — Low / Medium / High, with justification
4. **Strategic Recommendations** — Specific, actionable suggestions (feature roadmap reference, pricing adjustments, user acquisition strategies, etc.)
## Reference Resources
- **Comparison Matrix Template** → `references/feature-matrix-template.md`
- **Positioning Analysis Framework** → `references/positioning-framework.md`
- **Strategic Assessment Framework** → `references/strategic-impact-framework.md`
## Output Format
Final output should include:
1. 📊 **Feature Comparison Matrix** (table format)
2. 🎯 **Competitor Positioning Map** (textual positioning comparison)
3. ⚔️ **SWOT Analysis** (each competitor + our own product)
4. 💡 **Differentiation Opportunities and Strategic Recommendations**
FILE:references/feature-matrix-template.md
# Feature Comparison Matrix Template
## Usage Instructions
Use this template to build structured competitor feature comparison matrices. Follow the annotation conventions below when populating:
| Mark | Meaning |
|------|---------|
| ✅ Fully Supported | Feature is fully implemented |
| ⚠️ Partially Supported | Feature has limited implementation or conditional support |
| ❌ Not Supported | Competitor lacks this feature |
| 🔴 Our Weakness | Competitor is stronger than us |
| 🟢 Our Strength | We are stronger than competitor |
| 📌 Key Differentiator | Critical differentiation point |
---
## Template Table
```markdown
## Feature Comparison Matrix
| Dimension | Sub-Item | Our Product | Competitor A | Competitor B | Competitor C |
|------------------|---------------------|-------------|--------------|--------------|--------------|
| **Core Features** | Feature 1 | | | | |
| | Feature 2 | | | | |
| | Feature 3 | | | | |
| **Pricing** | Price Range | | | | |
| | Billing Model | | | | |
| | Free Plan | | | | |
| **User Experience** | Onboarding Ease | | | | |
| | Interface Design | | | | |
| | Responsiveness | | | | |
| **Integration Ecosystem** | API Openness | | | | |
| | Third-Party Integrations | | | | |
| | Plugin/Extension Support | | | | |
| **Customer Support** | Support Channels | | | | |
| | Documentation Quality | | | | |
| | Community Activity | | | | |
| **Market Performance** | Est. Market Share | | | | |
| | User Growth Trend | | | | |
| | Brand Awareness | | | | |
```
---
## Common Evaluation Dimension Reference
### Core Feature Dimensions
- Basic feature completeness
- Advanced feature richness
- Automation capabilities
- Customization flexibility
- Data processing capabilities
- Security and compliance
### Pricing Dimensions
- Free tier availability
- Pricing tiers (how many)
- Trial policy
- Enterprise custom pricing
- Hidden costs (bandwidth, overage, etc.)
### Technical Dimensions
- Tech stack generation
- Scalability
- Stability / SLA
- Data migration ease
- Internationalization support
### Ecosystem Dimensions
- Number of partners
- Developer community size
- Marketplace / plugin platform
- Certifications and integrations
- Industry solutions
---
## Output Example
> **Example: Project Management Tool Competitor Comparison (Excerpt)**
| Feature | Our Product | Notion | Linear | Asana |
|----------------------|-------------|---------|---------|--------|
| Kanban View | ✅ | ✅ | ✅ | ⚠️ |
| Timeline / Gantt | ✅ | ⚠️ | ✅ | ✅ |
| Automated Workflows | 🟢 | ✅ | ✅ | ✅ |
| Free Plan Limits | 🟢 Unlimited| ⚠️ 10 seats | ⚠️ 2500 tasks | ❌ No free |
| API Openness | ⚠️ | ✅ | ✅ | ✅ |
FILE:references/positioning-framework.md
# Competitor Positioning Analysis Framework
## 1. Brand Positioning Analysis
### 1.1 Positioning Statement
Construct a positioning statement for each competitor:
```
[Competitor Name] is a [Product Category],
designed for [Target User Segment],
that solves [User Pain Point / Need]
through [Core Approach / Technology / Philosophy],
distinct from [Primary Competitor]
because [Differentiation Reason].
```
### 1.2 Brand Tone Assessment
| Dimension | Assessment Question | Competitor A | Competitor B | Competitor C |
|-----------|---------------------|--------------|--------------|--------------|
| Professionalism | Technical-oriented or beginner-friendly? | | | |
| Approachability | Cold corporate feel or warm human touch? | | | |
| Innovation Sense | Radical innovation or steady iteration? | | | |
| Price Perception | Premium professional or value-for-money? | | | |
| Visual Language | Minimalist / Colorful / Professional business? | | | |
### 1.3 Market Narrative
Analyze the core story types each competitor tells:
- **Technology-Driven** — "We use AI / new algorithms to redefine..."
- **User Co-Creation** — "Our product comes from real user needs..."
- **Efficiency Revolution** — "Save you X hours / X% costs..."
- **Ecosystem Integration** — "One platform meets all needs..."
- **Mission-Driven** — "We want to change the industry / world..."
---
## 2. Target User Analysis
### 2.1 User Persona
Analyze for each competitor:
```
User Persona Elements:
- Industry: Primarily in which industries?
- Scale: SMB / Large Enterprise / Individual?
- Department: Which departments use it?
- Role: Decision-maker / Executor / Administrator?
- Use Scenario: What triggers their usage?
- Pain Point: What is their core pain point?
```
### 2.2 User Segmentation
| User Type | Our Product | Competitor A | Competitor B | Competitor C |
|-----------|-------------|--------------|--------------|--------------|
| Individual / Solo User | | | | |
| Small Team (<10 people) | | | | |
| Mid-Market (10-200 people) | | | | |
| Large Enterprise (200+ people) | | | | |
| Key Accounts / Flagship Cases | | | | |
---
## 3. Pricing Strategy Analysis
### 3.1 Pricing Model Comparison
| Pricing Dimension | Our Product | Competitor A | Competitor B | Competitor C |
|-------------------|-------------|--------------|--------------|--------------|
| Billing Model | | | | |
| Free Plan | | | | |
| Starting Price | | | | |
| Maximum Price | | | | |
| Pricing Anchor | | | | |
| Trial Policy | | | | |
### 3.2 Common Pricing Models
- **Freemium** — Basic free, premium paid
- **Subscription** — Monthly / annual billing
- **Usage-Based** — Billed by consumption
- **Per-Seat** — Billed per user count
- **One-Time Purchase** — Perpetual license
- **Custom Quote** — Enterprise-level tailored pricing
---
## 4. Differentiation Strategy Analysis
### 4.1 Differentiation Dimension Assessment
| Differentiation Dimension | Competitor A | Competitor B | Our Product |
|---------------------------|--------------|--------------|-------------|
| Feature Depth | | | |
| Price Competitiveness | | | |
| Brand Awareness | | | |
| User Experience / Ease of Use | | | |
| Ecosystem Integration Capability | | | |
| Customer Service | | | |
| Vertical Industry Focus | | | |
| Innovation Speed | | | |
### 4.2 Source of Competitive Advantage
Identify the primary source of competitive advantage for each competitor:
**Competitor A**:
- Primary Strength:
- Moat:
- Weakness:
**Competitor B**:
- Primary Strength:
- Moat:
- Weakness:
**Our Product**:
- Primary Strength:
- Moat:
- Weakness:
---
## 5. Perceptual Map
Display competitors' positions in users' mental landscape using a two-dimensional matrix:
```
High Price
↑
│
Competitor B │ Competitor A
│
──────────────────────┼────────────────→ Premium / Professional
│
Our Product │
│
│
Competitor C │
↓
Low Price
←─────────────────────────────→
Broad Audience Vertical / Niche Audience
```
> **Tip**: Adjust the two dimensions based on the specific category, e.g., "Feature Depth vs. Ease of Use," "Price vs. Brand Momentum," etc.
---
## 6. Information Channel Analysis
| Channel | Competitor A | Competitor B | Competitor C |
|---------|--------------|--------------|--------------|
| Website Quality | | | |
| Content Marketing | | | |
| Social Media | | | |
| SEO Ranking | | | |
| User Word-of-Mouth | | | |
| Industry Conferences | | | |
| Paid Advertising | | |
FILE:references/strategic-impact-framework.md
# Strategic Impact Assessment Framework
## 1. SWOT Analysis
### 1.1 Competitor SWOT
Complete SWOT for each major competitor:
```
Competitor: [Competitor Name]
【Strengths S】
-
【Weaknesses W】
-
【Opportunities O】
-
【Threats T】
-
```
### 1.2 Our SWOT
```
【Strengths S】
- Core capabilities we have that competitors lack
- Brand / reputation accumulation
- User stickiness / data moat
- Cost advantages / technical advantages
- Team / organizational capabilities
【Weaknesses W】
- Missing or weak features
- Uncompetitive pricing
- Low brand awareness
- Technical debt / architectural limitations
- Limited resources
【Opportunities O】
- Market gaps / unmet user pain points
- Competitors' weaknesses
- Windows opened by new technologies / trends
- Opportunities from policy / market changes
- Partnership / ecosystem integration opportunities
【Threats T】
- Competitors quickly catching up / copying
- Major players entering the market
- Technological disruption
- User churn to competitors
- Rising costs / declining margins
```
---
## 2. Competitive Threat Assessment
### 2.1 Threat Level Assessment
| Competitor | Threat Level | Core Threat Point | Threat Persistence | Primary Defense Strategy |
|------------|--------------|-------------------|--------------------|--------------------------|
| | Low / Medium / High | | Short-term / Medium-term / Long-term | |
### 2.2 Threat Assessment Dimensions
| Dimension | Assessment Criteria |
|-----------|---------------------|
| **Market Share** | Is the competitor's market share growing rapidly? |
| **Funding Capacity** | Does the competitor have sufficient capital for a price war? |
| **Brand Momentum** | Is the competitor's brand getting stronger? |
| **Product Iteration** | Is the competitor's feature update speed fast? |
| **User Churn Risk** | Could users migrate to the competitor? |
| **CAC Efficiency** | Is the competitor acquiring customers more efficiently than we are? |
---
## 3. Differentiation Opportunity Analysis
### 3.1 Market Gap Identification
Identify through comparison matrix and positioning analysis:
**Feature Gaps**: Features competitors haven't built or do poorly
**User Gaps**: User segments competitors haven't covered
**Scenario Gaps**: Use cases competitors haven't addressed
**Pricing Gaps**: Price ranges competitors haven't covered
### 3.2 Differentiation Opportunity Matrix
| Opportunity Point | Our Current Status | Implementation Difficulty | Potential Value | Priority |
|-------------------|--------------------|--------------------------|-----------------|----------|
| | | Low / Medium / High | High / Medium / Low | |
---
## 4. Strategic Recommendations
### 4.1 Short-Term Recommendations (0-3 months)
Low-cost, high-value actions that can be executed quickly:
```
1.
2.
3.
```
### 4.2 Medium-Term Recommendations (3-12 months)
Actions requiring some investment but with profound impact:
```
1.
2.
3.
```
### 4.3 Long-Term Recommendations (1+ years)
Strategic initiatives to build sustained competitive advantage:
```
1.
2.
3.
```
---
## 5. Competitive Monitoring Metrics
Establish a set of metrics for ongoing monitoring:
| Monitoring Metric | Target | Competitor A Status | Competitor B Status | Frequency |
|-------------------|--------|---------------------|---------------------|-----------|
| Market Share Change | | | | |
| User Rating Score | | | | |
| Feature Update Frequency | | | | |
| Pricing Changes | | | | |
| Brand Search Trends | | | | |
| Social Media Buzz | | | | |
| New Features / Capabilities | | | | |
---
## 6. Competitor Strategic Brief Template
```markdown
# [Competitor Name] Competitive Strategy Brief
**Updated**: [Date]
**Analysis Period**: [Time Range]
## Executive Summary (3-5 sentences)
[One-sentence positioning + Greatest threat point + Greatest opportunity point]
## Key Findings
### 1. Product Dynamics
- Major updates in last 3 months:
- Product roadmap direction:
- Technology trends:
### 2. Market Dynamics
- Market share changes:
- Key expansion markets:
- Target user segment shifts:
### 3. Pricing Dynamics
- Recent price adjustments:
- Promotional strategies:
- New pricing plans:
### 4. Growth Strategy
- Primary acquisition channels:
- Marketing campaigns:
- Partnerships:
## Threat Assessment
- Threat Level: [Low / Medium / High]
- Threat Time Window:
- Response Urgency:
## Recommended Actions
| Priority | Action Item | Expected Outcome | Responsible Dept |
|----------|-------------|------------------|-----------------|
| P0 | | | |
| P1 | | | |
| P2 | | | |
## Data Sources
-
```Helps agents conduct structured end-of-day review, reflection, and documentation. Provides capabilities to scan today's records, categorize activities, perfo...
---
name: agent-daily-review
description: Helps agents conduct structured end-of-day review, reflection, and documentation. Provides capabilities to scan today's records, categorize activities, perform reflective analysis, and generate review reports. Supports Cron auto-trigger for cumulative growth with each run.
---
# Agent Daily Review
## Overview
The Daily Review skill helps agents conduct systematic review and reflection at the end of the day, transforming fragmented daily records into structured growth accumulation.
**Core Capabilities:**
1. **Scan Records** - Automatically scan today's memory files, artifacts, and MEMORY.md entries
2. **Categorize Activities** - Classify activities into: Completed, In Progress, Issues/Blockers, Learning/Growth, Others
3. **Reflect and Analyze** - Calculate productivity score, identify highlights and challenges, generate improvement suggestions
4. **Generate Report** - Output structured review report and archive to long-term memory
**Use Cases:**
- User says "Do my daily review for today"
- User says "Summarize today"
- Cron scheduled task triggers (e.g., daily at 22:00)
- User wants to review work/learning status for a specific day
## Workflow
### 1. Scan Today's Records
Execute `scripts/daily_review.py` to scan the following:
- `memory/YYYY-MM-DD.md` - Today's journal entries
- `MEMORY.md` - Today's entries in long-term memory
- `workspace/*.md` - Artifact files generated today
### 2. Categorize Activities
Automatically identify and categorize:
- **Completed** - Contains keywords like "completed," "done," "resolved," ✅
- **In Progress** - Contains keywords like "in progress," "working on," 🔄
- **Issues/Blockers** - Contains keywords like "issue," "blocked," "bug," ❌
- **Learning/Growth** - Contains keywords like "learned," "researched," "understood"
- **Meetings/Communication** - Contains keywords like "meeting," "discussed," "sync"
### 3. Reflect and Analyze
Perform intelligent analysis based on categorization results:
- **Productivity Score** - Calculate based on record count and artifact count (0-100)
- **Today's Highlights** - Identify completed important tasks and decisions
- **Challenges Encountered** - Summarize issues and pending items
- **Improvement Suggestions** - Generate personalized recommendations based on data
### 4. Generate Report
Output structured report containing:
- Today's Overview (statistics)
- Completed Tasks List
- In Progress Tasks List
- Issues/Blockers
- Learning/Growth Records
- Highlights Summary
- Reflection and Suggestions
- Tomorrow's Plan Framework
### 5. Archive to Memory
- Save review report to `reviews/review_YYYY-MM-DD.md`
- Append review summary to `MEMORY.md`
## Usage
### Manual Execution
```bash
# Execute today's review
python scripts/daily_review.py
# Specify working directory
python scripts/daily_review.py -w /path/to/workspace
# Specify output file
python scripts/daily_review.py -o /path/to/output.md
# Review specific date
python scripts/daily_review.py -d 2024-01-15
# Do not save to MEMORY.md
python scripts/daily_review.py --no-memory
```
### Use as Module
```python
from scripts.daily_review import DailyReview
review = DailyReview("/path/to/workspace")
report = review.run(save_to_memory=True)
print(report)
```
### Cron Auto-Trigger
Set up automatic daily review at 22:00:
```bash
# Add scheduled task using openclaw cron
openclaw cron add --name "daily-review" \
--schedule "0 22 * * *" \
--command "python ~/.qclaw/skills/daily-review/scripts/daily_review.py"
```
Or using cron tool:
```json
{
"name": "daily-review",
"schedule": {"kind": "cron", "expr": "0 22 * * *", "tz": "Asia/Shanghai"},
"payload": {
"kind": "agentTurn",
"message": "Please perform today's review using the daily-review skill, scanning today's records and generating a review report."
},
"sessionTarget": "isolated"
}
```
## Report Format
Review reports use Markdown format with the following sections:
```markdown
# Daily Review Report - YYYY-MM-DD
## 📊 Today's Overview
- Date, Record Count, Artifact Count, Productivity Score
## ✅ Completed
- Task List
## 🔄 In Progress
- Pending List
## ⚠️ Issues/Blockers
- Issue List
## 📚 Learning/Growth
- Learning Records
## 🎯 Today's Highlights
- Highlights Summary
## 💭 Reflection and Suggestions
- Improvement Suggestions
## 📝 Tomorrow's Plan
- Plan Framework
```
## Directory Structure
```
workspace/
├── memory/
│ └── 2024-01-15.md # Today's journal entries
├── reviews/
│ └── review_2024-01-15.md # Review report
├── MEMORY.md # Long-term memory (review summary appended here)
└── *.md # Artifacts generated today
```
## Tips
1. **Cultivate Journaling Habit** - Record timestamped entries in `memory/YYYY-MM-DD.md` daily for better review results
2. **Use Keywords** - Use keywords like "completed," "learning," "encountered issue" when journaling to facilitate auto-categorization
3. **Periodic Review** - Review weekly/monthly review reports to discover growth trajectory
4. **Integrate with Cron** - Set up automatic review to ensure daily reflection is never missed
## Resources
- `scripts/daily_review.py` - Core review script
- `references/framework.md` - Detailed review framework explanation (optional reading)
FILE:scripts/daily_review.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Daily Review Script - Daily reflection script
Helps agents conduct structured end-of-day reflection and documentation
"""
import os
import sys
import json
import re
from datetime import datetime, timedelta
from pathlib import Path
from typing import List, Dict, Any, Optional
class DailyReview:
"""Core daily review class"""
def __init__(self, workspace_path: str = None):
self.workspace = Path(workspace_path) if workspace_path else Path.home() / ".qclaw" / "workspace"
self.memory_dir = self.workspace / "memory"
self.review_dir = self.workspace / "reviews"
self.today = datetime.now().strftime("%Y-%m-%d")
self.yesterday = (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d")
# Ensure directories exist
self.review_dir.mkdir(parents=True, exist_ok=True)
def scan_today_records(self) -> Dict[str, Any]:
"""Scan today's records"""
records = {
"date": self.today,
"daily_note": None,
"artifacts": [],
"memory_entries": [],
"task_count": 0,
"decisions": [],
"learnings": []
}
# 1. Read today's memory file
today_memory = self.memory_dir / f"{self.today}.md"
if today_memory.exists():
content = today_memory.read_text(encoding='utf-8')
records["daily_note"] = content
records["memory_entries"] = self._extract_entries(content)
# 2. Scan today's artifacts
records["artifacts"] = self._scan_artifacts()
# 3. Scan today's entries in MEMORY.md
main_memory = self.workspace / "MEMORY.md"
if main_memory.exists():
content = main_memory.read_text(encoding='utf-8')
records["decisions"] = self._extract_decisions(content, self.today)
records["learnings"] = self._extract_learnings(content, self.today)
return records
def _extract_entries(self, content: str) -> List[Dict]:
"""Extract entries from memory content"""
entries = []
# Match timestamp entries, e.g., "- 10:30 completed xxx"
time_pattern = r'^-?\s*(\d{1,2}:\d{2})\s+(.+)$'
for line in content.split('\n'):
match = re.match(time_pattern, line.strip())
if match:
entries.append({
"time": match.group(1),
"content": match.group(2)
})
return entries
def _scan_artifacts(self) -> List[Dict]:
"""Scan artifacts generated today"""
artifacts = []
today_prefix = self.today.replace("-", "")
for file in self.workspace.glob("*.md"):
if today_prefix in file.name and file.name != f"{self.today}.md":
stat = file.stat()
artifacts.append({
"name": file.name,
"type": "artifact",
"created": datetime.fromtimestamp(stat.st_ctime).strftime("%H:%M")
})
return artifacts
def _extract_decisions(self, content: str, date: str) -> List[str]:
"""Extract decision records"""
decisions = []
# Find lines containing decision-related keywords
decision_keywords = ['decision', 'decided', 'chose', 'confirmed', 'adopted']
for line in content.split('\n'):
if date in line or any(kw in line.lower() for kw in decision_keywords):
if any(kw in line.lower() for kw in decision_keywords):
decisions.append(line.strip())
return decisions[:10] # Limit quantity
def _extract_learnings(self, content: str, date: str) -> List[str]:
"""Extract learning/lesson records"""
learnings = []
learning_keywords = ['learned', 'lesson', 'experience', 'note', 'improve']
for line in content.split('\n'):
if date in line or any(kw in line.lower() for kw in learning_keywords):
if any(kw in line.lower() for kw in learning_keywords):
learnings.append(line.strip())
return learnings[:10]
def categorize_activities(self, records: Dict) -> Dict[str, List]:
"""Categorize activities"""
categories = {
"completed_tasks": [],
"in_progress": [],
"blockers": [],
"meetings": [],
"learning": [],
"other": []
}
# Analyze memory entries
if records["daily_note"]:
content = records["daily_note"]
lines = content.split('\n')
for line in lines:
line = line.strip()
if not line or line.startswith('#'):
continue
# Identify completed tasks
if any(kw in line.lower() for kw in ['completed', 'done', 'resolved', '✅', '✓', 'finished']):
categories["completed_tasks"].append(line)
# Identify in-progress tasks
elif any(kw in line.lower() for kw in ['in progress', 'working on', '🔄', 'pending']):
categories["in_progress"].append(line)
# Identify blockers/issues
elif any(kw in line.lower() for kw in ['issue', 'blocked', 'stuck', 'bug', 'error', '❌']):
categories["blockers"].append(line)
# Identify meetings/communication
elif any(kw in line.lower() for kw in ['meeting', 'discussed', 'sync', 'report', 'aligned']):
categories["meetings"].append(line)
# Identify learning
elif any(kw in line.lower() for kw in ['learned', 'understood', 'researched', 'studied', 'read']):
categories["learning"].append(line)
else:
categories["other"].append(line)
# Statistics
categories["stats"] = {
"total_entries": len(records["memory_entries"]),
"artifacts_created": len(records["artifacts"]),
"decisions": len(records["decisions"]),
"learnings": len(records["learnings"])
}
return categories
def reflect_and_analyze(self, categories: Dict, records: Dict) -> Dict[str, Any]:
"""Reflect and analyze"""
reflection = {
"productivity_score": 0,
"highlights": [],
"challenges": [],
"patterns": [],
"suggestions": []
}
stats = categories["stats"]
# Calculate productivity score (simple algorithm)
score = min(100, stats["total_entries"] * 5 + stats["artifacts_created"] * 10 + 50)
reflection["productivity_score"] = score
# Extract highlights
if categories["completed_tasks"]:
reflection["highlights"].append(f"Completed {len(categories['completed_tasks'])} tasks")
if stats["artifacts_created"] > 0:
reflection["highlights"].append(f"Generated {stats['artifacts_created']} artifacts")
if records["decisions"]:
reflection["highlights"].append(f"Made {len(records['decisions'])} important decisions")
# Extract challenges
if categories["blockers"]:
reflection["challenges"].append(f"Encountered {len(categories['blockers'])} issues/blockers")
if categories["in_progress"]:
reflection["challenges"].append(f"Have {len(categories['in_progress'])} pending tasks")
# Generate suggestions
if stats["total_entries"] < 3:
reflection["suggestions"].append("Few records today; consider increasing daily journaling habit")
if not categories["learning"]:
reflection["suggestions"].append("No learning records today; consider scheduling learning time")
if len(categories["blockers"]) > 2:
reflection["suggestions"].append("Many issues today; prioritize resolving blockers")
return reflection
def generate_report(self, records: Dict, categories: Dict, reflection: Dict) -> str:
"""Generate review report"""
report_lines = [
f"# Daily Review Report - {self.today}",
"",
"## 📊 Today's Overview",
"",
f"- **Date**: {self.today}",
f"- **Record Entries**: {categories['stats']['total_entries']}",
f"- **Artifacts Generated**: {categories['stats']['artifacts_created']}",
f"- **Productivity Score**: {reflection['productivity_score']}/100",
"",
"## ✅ Completed",
""
]
if categories["completed_tasks"]:
for task in categories["completed_tasks"][:10]:
report_lines.append(f"- {task}")
else:
report_lines.append("- No completed records")
report_lines.extend(["", "## 🔄 In Progress", ""])
if categories["in_progress"]:
for task in categories["in_progress"][:5]:
report_lines.append(f"- {task}")
else:
report_lines.append("- No tasks in progress")
report_lines.extend(["", "## ⚠️ Issues/Blockers", ""])
if categories["blockers"]:
for blocker in categories["blockers"][:5]:
report_lines.append(f"- {blocker}")
else:
report_lines.append("- No blockers today 🎉")
report_lines.extend(["", "## 📚 Learning/Growth", ""])
if categories["learning"]:
for item in categories["learning"][:5]:
report_lines.append(f"- {item}")
elif records["learnings"]:
for learning in records["learnings"][:5]:
report_lines.append(f"- {learning}")
else:
report_lines.append("- No learning records")
report_lines.extend(["", "## 🎯 Today's Highlights", ""])
if reflection["highlights"]:
for highlight in reflection["highlights"]:
report_lines.append(f"- {highlight}")
else:
report_lines.append("- Keep up the good work!")
report_lines.extend(["", "## 💭 Reflection and Suggestions", ""])
if reflection["suggestions"]:
for suggestion in reflection["suggestions"]:
report_lines.append(f"- {suggestion}")
else:
report_lines.append("- Good performance today, maintain momentum!")
report_lines.extend(["", "## 📝 Tomorrow's Plan", "", "- [ ] To be filled...", ""])
report_lines.extend(["---", "", f"*Generated at: {datetime.now().strftime('%Y-%m-%d %H:%M')}*"])
return '\n'.join(report_lines)
def save_to_memory(self, report: str):
"""Save review to MEMORY.md"""
memory_file = self.workspace / "MEMORY.md"
entry = f"\n\n## {self.today} Review\n\n"
entry += f"**Productivity Score**: {self.reflection.get('productivity_score', 0)}/100\n\n"
entry += "**Completed Today**: "
if self.categories.get("completed_tasks"):
entry += f"{len(self.categories['completed_tasks'])} tasks"
else:
entry += "None"
entry += "\n\n"
if memory_file.exists():
content = memory_file.read_text(encoding='utf-8')
# Append at the end of file
content += entry
else:
content = f"# Long-Term Memory\n\n{entry}"
memory_file.write_text(content, encoding='utf-8')
print(f"✅ Review appended to MEMORY.md")
def run(self, save_to_memory: bool = True, output_path: str = None) -> str:
"""Execute full review workflow"""
print(f"🔍 Scanning records for {self.today}...")
# 1. Scan today's records
records = self.scan_today_records()
print(f" ✓ Found {len(records['memory_entries'])} record entries")
print(f" ✓ Found {len(records['artifacts'])} artifacts")
# 2. Categorize
print("📂 Categorizing activities...")
categories = self.categorize_activities(records)
self.categories = categories # Save for later use
# 3. Reflect and analyze
print("💭 Reflecting and analyzing...")
reflection = self.reflect_and_analyze(categories, records)
self.reflection = reflection # Save for later use
# 4. Generate report
print("📝 Generating review report...")
report = self.generate_report(records, categories, reflection)
# 5. Save report
if output_path:
output_file = Path(output_path)
else:
output_file = self.review_dir / f"review_{self.today}.md"
output_file.write_text(report, encoding='utf-8')
print(f"✅ Review report saved: {output_file}")
# 6. Append to MEMORY.md
if save_to_memory:
self.save_to_memory(report)
return report
def main():
"""Main function"""
import argparse
parser = argparse.ArgumentParser(description='Daily Review Tool')
parser.add_argument('--workspace', '-w', help='Workspace directory path')
parser.add_argument('--output', '-o', help='Output file path')
parser.add_argument('--no-memory', action='store_true', help='Do not save to MEMORY.md')
parser.add_argument('--date', '-d', help='Specify date (YYYY-MM-DD), defaults to today')
args = parser.parse_args()
# Create review instance
review = DailyReview(args.workspace)
# If date specified, override today's date
if args.date:
review.today = args.date
review.yesterday = (datetime.strptime(args.date, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
# Execute review
report = review.run(
save_to_memory=not args.no_memory,
output_path=args.output
)
print("\n" + "="*50)
print("Review Complete!")
print("="*50)
if __name__ == "__main__":
main()Product Requirements Document (PRD) writing expert. Write structured product requirements documents, including problem statements, user stories, requirement...
---
name: prd-writing-expert
description: Product Requirements Document (PRD) writing expert. Write structured product requirements documents, including problem statements, user stories, requirement prioritization, and success metrics. Applicable for feature specification writing, defining acceptance criteria, or documenting product decisions.
---
# PRD Writing Expert
This skill helps write structured Product Requirements Documents (PRDs) using industry-standard frameworks.
## Use Cases
(1) User mentions "PRD," "Product Requirements Document," "requirements document," "feature specification"
(2) User asks to "write requirements," "draft requirements document," "define product requirements"
(3) User is conducting product planning, feature definition, acceptance criteria formulation
(4) User needs to document product decisions, requirements analysis, or user story writing.
## Core Framework
A PRD document contains the following core modules:
### 1. Problem Statement
- Background and current state
- Pain point analysis
- Opportunity identification
- Target users
### 2. User Stories
- Format: "As a [role], I want to [action] so that [value]"
- Acceptance Criteria
- User journey mapping
### 3. Requirements Prioritization
- MoSCoW Method: Must-have / Should-have / Could-have / Won't-have
- Value-Complexity Matrix
- MVP scope definition
### 4. Success Metrics
- North Star Metric
- Key Results
- Monitoring metrics
## Workflow
1. **Requirement Clarification**: Gather product background, target users, and business objectives
2. **Problem Definition**: Define the problem statement and business opportunity
3. **User Stories**: Write user stories and acceptance criteria
4. **Prioritization**: Prioritize requirements using the MoSCoW method
5. **Metric Definition**: Set success metrics and monitoring plans
6. **Document Output**: Generate a structured PRD document
## Detailed Guides
- **User Story Writing**: See [references/user-stories.md](references/user-stories.md)
- **Requirements Prioritization Methods**: See [references/prioritization.md](references/prioritization.md)
- **Success Metrics Framework**: See [references/metrics.md](references/metrics.md)
## Template Resources
- PRD Template: [assets/prd-template.md](assets/prd-template.md)
## Usage Examples
**Example 1: New Feature PRD**
User: "Help us write a PRD for the user login feature"
→ Output: A complete PRD including problem statement, user stories, requirement prioritization, and success metrics
**Example 2: Product Iteration PRD**
User: "Need to define product requirements for shopping cart optimization"
→ Output: A structured PRD focused on shopping cart optimization, including user journey and acceptance criteria
**Example 3: Documenting Product Decisions**
User: "Document our decision to abandon the social sharing feature"
→ Output: Product decision document including background, analysis, and decision outcome
## Notes
- PRDs should be clear and actionable; avoid vague language
- Requirement prioritization should align with business objectives
- Success metrics should be quantifiable and trackable
- Acceptance criteria should be specific and testable
FILE:references/metrics.md
# Success Metrics Framework
## North Star Metric
### Definition
The single metric that best represents the core value delivered by the product.
### Selection Principles
1. Reflects user value
2. Aligns with business objectives
3. Measurable and trackable
4. Understandable and influenceable by the team
### Examples
| Product Type | North Star Metric |
|--------------|-------------------|
| E-commerce | Monthly Active Purchasing Users |
| Content Platform | Average Monthly Usage Time per User |
| SaaS | Monthly Active Subscribers |
| Social | Daily Active Users (DAU) |
| Utility/Tool | Weekly Completed Tasks |
## Key Results (KRs)
### OKR Framework
```
Objective: Improve user retention
KR1: Increase 30-day retention rate from 20% to 30%
KR2: Grow Monthly Active Users (MAU) by 50%
KR3: Increase average user frequency from 2 times per week to 4 times per week
```
### SMART Principles
- Specific
- Measurable
- Achievable
- Relevant
- Time-bound
## Monitoring Metric Hierarchy
### 1. Business Metrics
- Revenue, Profit
- User Growth
- Market Share
### 2. Product Metrics
- Active Users (DAU/MAU)
- Retention Rate
- Conversion Rate
- Time Spent
### 3. Feature Metrics
- Feature Adoption Rate
- Feature Satisfaction
- Feature Conversion Funnel
### 4. Technical Metrics
- Performance Metrics (Response time, Load speed)
- Stability (Crash rate, Error rate)
- Availability (SLA)
## Common Metric Formulas
### User Growth
```
Customer Acquisition Cost (CAC) = Marketing Expenses / New Users Acquired
Customer Lifetime Value (LTV) = ARPU × Customer Lifetime
LTV/CAC > 3 indicates healthy growth
```
### Retention Analysis
```
Day 1 Retention Rate = Returning Users on Day 2 / New Users on Day 1
Day 7 Retention Rate = Returning Users on Day 7 / New Users on Day 1
Day 30 Retention Rate = Returning Users on Day 30 / New Users on Day 1
```
### Engagement
```
DAU/MAU Ratio = Daily Active Users / Monthly Active Users
> 20% indicates strong product stickiness
```
### Conversion Rate
```
Conversion Rate = Number of Users Completing Goal / Number of Visitors
```
## Data Tracking Plan
### Event Tracking Design
1. Define key events
2. Design event properties
3. Plan user properties
4. Establish a data dictionary
### Analytics Tools
- Google Analytics
- Mixpanel
- Amplitude
- Custom-built data platform
## Metrics Dashboard
### Real-time Monitoring
- DAU/MAU
- Key conversion rates
- Error rate
### Periodic Reviews
- Weekly Report: Growth trends, anomaly fluctuations
- Monthly Report: Metric changes, attribution analysis
- Quarterly Report: Goal achievement, strategy adjustments
FILE:references/prioritization.md
# Requirements Prioritization Methods
## MoSCoW Method
### Must-have
- Product cannot launch without it
- Core value proposition
- Legal/compliance requirements
### Should-have
- Important but not critical
- Has workarounds available
- Can be deferred to next version
### Could-have
- Desirable features
- Enhance user experience
- Implement if resources permit
### Won't-have
- Not included in this version
- Explicitly excluded
- May be considered in the future
## Value-Complexity Matrix
| High Value Low Complexity | High Value High Complexity |
|---------------------------|----------------------------|
| **Quick Wins** | **Major Projects** |
| Prioritize immediately | Plan carefully |
| Low Value Low Complexity | Low Value High Complexity |
|--------------------------|---------------------------|
| **Fill-ins** | **Avoid** |
| Do if time permits | Do not implement |
## RICE Scoring
```
RICE Score = (Reach × Impact × Confidence) / Effort
```
- **Reach**: Number of users affected (per quarter/month)
- **Impact**: Degree of impact (0.25=Minimal, 0.5=Low, 1=Medium, 2=High, 3=Massive)
- **Confidence**: Certainty level (100%=High, 80%=Medium, 50%=Low)
- **Effort**: Work required (person-months)
## Kano Model
### Basic Needs
- Essential features that must be met
- Absence causes extreme dissatisfaction
- Presence does not generate particular delight
### Performance Needs
- Better performance yields higher satisfaction
- Related to performance, speed, and quality
### Delighters
- Features that exceed expectations
- Bring surprise and delight
- Create competitive differentiation
## MVP Definition
Minimum Viable Product:
1. **Core Value**: Solves the primary problem
2. **Minimal Feature Set**: Includes only Must-have requirements
3. **Validatable**: Can validate product hypotheses
4. **Iterable**: Allows rapid optimization afterwards
### MVP Checklist
- [ ] Does it solve the core problem?
- [ ] Does it contain enough value to attract users?
- [ ] Can it collect user feedback?
- [ ] Can it be released within 2-4 weeks?
FILE:references/user-stories.md
# User Story Writing Guide
## User Story Format
Standard format:
```
As a [role]
I want to [action]
So that [value]
```
## Writing Principles
1. **INVEST Principle**
- Independent
- Negotiable
- Valuable
- Estimable
- Small
- Testable
2. **Focus on User Value**
- Adopt user perspective
- Emphasize "why" rather than "how"
- Avoid technical jargon
## Acceptance Criteria
### Format
```
Given [precondition]
When [triggering action]
Then [expected result]
```
### Example
```
User Story: As a user, I want to register an account using my email so that I can access platform features
Acceptance Criteria:
Given the user is on the registration page
When the user enters a valid email and password and clicks register
Then the system sends a verification email
And the user account status is "Pending Verification"
Given the user receives the verification email
When the user clicks the verification link
Then the user account status changes to "Verified"
And the user can log into the system
```
## User Story Map
Structure for organizing user stories:
1. **User Activities** (High-level)
- User Tasks
- User Stories
2. **Release Slices**
- MVP Slice
- Enhancement Slice
- Future Slice
## Common Mistakes
❌ Incorrect: "As a system, I want to save data"
✅ Correct: "As a user, I want my data to be saved so that I can continue next time"
❌ Incorrect: "As a user, I want the system to use a microservices architecture"
✅ Correct: "As a user, I want the system to respond quickly so that I can use it smoothly"
❌ Too large: "As a user, I want to complete a purchase"
✅ Split into:
- "As a user, I want to browse products so that I can find what I want"
- "As a user, I want to add items to my cart so that I can purchase multiple items together"
- "As a user, I want to complete payment so that I can receive the product"
FILE:assets/prd-template.md
# Product Requirements Document (PRD)
## Document Information
- Product Name: [Product Name]
- Version: v1.0
- Author: [Author]
- Date: [YYYY-MM-DD]
- Status: [Draft / In Review / Approved]
---
## 1. Problem Statement
### 1.1 Background
[Describe the current background and state]
### 1.2 Pain Points
[List core pain points]
- Pain Point 1:
- Pain Point 2:
### 1.3 Opportunity
[Describe the business opportunity]
### 1.4 Target Users
[Define target user personas]
---
## 2. User Stories
### 2.1 Core User Stories
#### Story 1: [Story Title]
```
As a [role]
I want to [action]
So that [value]
```
**Acceptance Criteria:**
- [ ] Given [precondition] When [trigger] Then [expected result]
- [ ]
**Priority:** Must-have / Should-have / Could-have
---
### 2.2 User Journey Map
[Describe the key steps for users to achieve their goals]
---
## 3. Requirements Prioritization
### 3.1 MoSCoW Classification
| Requirement | Classification | Rationale |
|-------------|----------------|-----------|
| | Must-have | |
| | Should-have | |
| | Could-have | |
| | Won't-have | |
### 3.2 MVP Scope
[List of features included in MVP]
---
## 4. Success Metrics
### 4.1 North Star Metric
[Define the core metric]
### 4.2 Key Results (OKR)
```
Objective: [Goal]
KR1: [Key Result 1]
KR2: [Key Result 2]
KR3: [Key Result 3]
```
### 4.3 Monitoring Metrics
| Metric | Current Value | Target Value | Monitoring Frequency |
|--------|---------------|--------------|----------------------|
| | | | |
---
## 5. Non-Functional Requirements
### 5.1 Performance Requirements
- Response Time:
- Concurrent Users:
### 5.2 Security Requirements
[Security standards and compliance requirements]
### 5.3 Compatibility Requirements
[Platform, browser, and device support]
---
## 6. Milestones and Timeline
| Phase | Content | Timeline |
|-------|---------|----------|
| Design | | |
| Development | | |
| Testing | | |
| Release | | |
---
## 7. Risks and Dependencies
### 7.1 Risks
| Risk | Impact | Mitigation |
|------|--------|------------|
| | | |
### 7.2 Dependencies
[List external dependencies]
---
## 8. Appendix
### 8.1 Glossary
[Define technical terms]
### 8.2 Reference Documents
[Links to related documents]
---
**Change Log:**
| Version | Date | Change Description | Author |
|---------|------|-------------------|--------|
| v1.0 | | Initial version | |Provides daily insights from 2000+ Xiaohongshu viral posts to support content creation, trend analysis, and creative inspiration based on engagement data.
---
name: xiaohongshu-insight
description: Xiaohongshu viral content data insight tool. Continuously collects 2000+ viral posts daily across the platform, based on criteria: low-follower viral posts, periodic high-engagement posts, single-day interaction spikes, and sustained interaction growth. Use for: Xiaohongshu content creation, viral content analysis, data reference, traffic trend tracking, and creative inspiration.
---
# Xiaohongshu Data Insights
## Overview
A professional data insight tool built specifically for Xiaohongshu content creation. Continuously collects over 2000+ viral posts daily across the platform, empowering creators with data references, traffic trend insights, and creative inspiration.
## Use Cases
Use when users mention Xiaohongshu viral posts, post data, traffic trends, creative inspiration, low-follower viral posts, interaction spikes, etc.
## Core Capabilities
### 1. Viral Post Collection
Automatically collects 2000+ viral posts daily based on the following criteria:
- **Low-Follower Viral Posts**: Follower count < 5000, yet post interactions exceed the category average by more than 3x
- **Periodic High-Engagement**: Like growth > 1000 within 7 days, with a clear sustained growth trend
- **Single-Day Interaction Spike**: Daily increase in likes + saves + comments > 500
- **Sustained Interaction Growth**: Interactions increase for 3 consecutive days, with average daily growth rate > 20%
### 2. Data Dimensions
Each viral post includes the following data:
| Dimension | Description |
|-----------|-------------|
| Basic Information | Title, cover image, author, publish time, category tags |
| Interaction Data | Likes, saves, comments, shares, and growth rates |
| Author Profile | Follower count, total posts, average interactions, category distribution |
| Content Features | Title keywords, cover style, content type, word count range |
| Traffic Curve | Interaction data at 24h/48h/72h/7d intervals after publishing |
### 3. Use Scenarios
**Scenario 1: Finding Creative Inspiration**
```
User: What are some recent low-follower viral posts in the beauty category?
→ Filter category=Beauty, follower count<5000, sort by interaction volume
→ Return TOP 20 viral posts with key feature analysis
```
**Scenario 2: Analyzing Traffic Trends**
```
User: What common characteristics do this week's viral fashion posts share?
→ Aggregate analysis of viral posts in Fashion category over the past 7 days
→ Extract title keywords, cover features, publishing time distribution
→ Output trend insight report
```
**Scenario 3: Competitor Account Research**
```
User: Why does this blogger consistently produce viral content?
→ Analyze the blogger's historical viral posts
→ Compare with other bloggers in the same category
→ Output success factor analysis
```
## Quick Start
### Query Viral Posts
Use `scripts/query_notes.py` to query viral post data:
```bash
python scripts/query_notes.py --category Beauty --days 7 --limit 50
```
Parameter descriptions:
- `--category`: Category (Beauty/Fashion/Food/Travel/Home/Parenting/Career/Emotions/Knowledge/Entertainment)
- `--days`: Number of days to query (default 7 days)
- `--limit`: Number of results to return (default 20)
- `--sort`: Sort field (engagement/growth/fans)
- `--min_engagement`: Minimum interaction threshold
### Analyze Trend Features
Use `scripts/analyze_trends.py` to analyze category trends:
```bash
python scripts/analyze_trends.py --category Fashion --output report.md
```
Output includes:
- TOP 20 Trending Keywords
- High-Frequency Cover Styles
- Optimal Publishing Time Windows
- Viral Title Formulas
- Engagement Rate Distribution
### Export Data
Use `scripts/export_data.py` to export data:
```bash
python scripts/export_data.py --format xlsx --output viral_data.xlsx
```
Supported formats: xlsx, csv, json
## Data Field Descriptions
See [references/data_schema.md](references/data_schema.md) for details.
## Viral Post Detection Algorithm
See [references/viral_criteria.md](references/viral_criteria.md) for details.
## Notes
1. Data is sourced from publicly available posts and is for creative reference only
2. It is recommended to selectively draw inspiration based on your own account positioning
3. Avoid directly copying content; focus on creative transformation
4. Data is updated daily; pay attention to timeliness
FILE:scripts/analyze_trends.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Xiaohongshu Trend Analysis Tool
Usage:
python analyze_trends.py --category Fashion --output report.md
python analyze_trends.py --category Beauty --days 30
"""
import argparse
import json
from collections import Counter
from datetime import datetime, timedelta
from typing import Dict, List
def analyze_trends(category: str, days: int = 7) -> Dict:
"""
Analyze category trends
Args:
category: Category classification
days: Number of days to analyze
Returns:
Trend analysis report
"""
# Mock data (should be retrieved from database in actual use)
mock_keywords = {
"Fashion": ["OOTD", "Korean style", "Minimalist", "Office wear", "Petite", "Slimming", "Fall/Winter", "Layering"],
"Beauty": ["No-makeup look", "Morning routine", "Affordable", "Student budget", "Warm skin tone", "Depuffing", "Beginner", "Tutorial"],
"Food": ["Solo dining", "Lazy meals", "Weight loss", "Breakfast", "Meal prep", "Restaurant review", "Homemade", "Quick recipe"],
"Travel": ["Hidden gems", "Guide", "Per person cost", "Avoid pitfalls", "Photo spots", "Photography", "Budget travel", "Weekend trip"],
}
keywords = mock_keywords.get(category, ["Trending", "Recommended", "Share", "Tutorial"])
# Generate trend data
report = {
"category": category,
"analysis_period": f"{days} days",
"generated_at": datetime.now().isoformat(),
"summary": {
"total_notes": 1500 + days * 100,
"viral_notes": 200 + days * 20,
"avg_engagement": 2500,
"growth_rate": "+15.3%"
},
"hot_keywords": [
{"keyword": kw, "count": 150 - i * 10, "trend": "up" if i < 4 else "stable"}
for i, kw in enumerate(keywords[:8])
],
"cover_styles": [
{"style": "Solid color background", "percentage": 35},
{"style": "Collage comparison", "percentage": 25},
{"style": "Scene photography", "percentage": 20},
{"style": "Portrait feature", "percentage": 15},
{"style": "Text overlay cover", "percentage": 5}
],
"best_posting_time": [
{"time": "12:00-13:00", "engagement": "High"},
{"time": "18:00-19:00", "engagement": "High"},
{"time": "21:00-22:00", "engagement": "Medium-High"},
{"time": "08:00-09:00", "engagement": "Medium"}
],
"title_patterns": [
"Number method: X tips/methods/items",
"Audience method: Must-read for XX / Suitable for XX",
"Scenario method: XX occasion / When XX",
"Comparison method: Before & After",
"Suspense method: Never / Regret not knowing sooner"
],
"content_insights": [
f"Recent viral posts in the {category} category are predominantly practical tips",
"Users prefer authentic experience sharing and dislike overt advertisements",
"Image posts account for 70%, short video posts show significant growth",
"Posts with high comment section engagement are more likely to see secondary distribution"
]
}
return report
def generate_markdown_report(report: Dict) -> str:
"""Generate Markdown format report"""
lines = []
lines.append(f"# {report['category']} Category Trend Analysis Report")
lines.append(f"\n> Analysis Period: {report['analysis_period']} | Generated on: {report['generated_at'][:10]}")
# Data overview
lines.append("\n## Data Overview")
lines.append(f"- Total Posts Indexed: **{report['summary']['total_notes']}**")
lines.append(f"- Viral Posts: **{report['summary']['viral_notes']}**")
lines.append(f"- Average Engagement: **{report['summary']['avg_engagement']}**")
lines.append(f"- Period-over-Period Growth: **{report['summary']['growth_rate']}**")
# Hot keywords
lines.append("\n## Top 8 Trending Keywords")
lines.append("| Rank | Keyword | Occurrences | Trend |")
lines.append("|------|---------|-------------|-------|")
for i, kw in enumerate(report['hot_keywords'], 1):
trend_emoji = "📈" if kw['trend'] == 'up' else "➡️"
lines.append(f"| {i} | {kw['keyword']} | {kw['count']} | {trend_emoji} |")
# Cover style distribution
lines.append("\n## Viral Post Cover Style Distribution")
lines.append("| Style | Percentage | Visualization |")
lines.append("|-------|------------|---------------|")
for style in report['cover_styles']:
bar = "█" * (style['percentage'] // 5)
lines.append(f"| {style['style']} | {style['percentage']}% | {bar} |")
# Best posting times
lines.append("\n## Optimal Posting Time Windows")
lines.append("| Time Window | Engagement Level | Recommendation |")
lines.append("|-------------|------------------|----------------|")
for time_slot in report['best_posting_time']:
suggestion = "⭐ Highly Recommended" if time_slot['engagement'] == 'High' else "✓ Recommended"
lines.append(f"| {time_slot['time']} | {time_slot['engagement']} | {suggestion} |")
# Viral title formulas
lines.append("\n## Viral Title Formulas")
for i, pattern in enumerate(report['title_patterns'], 1):
lines.append(f"{i}. **{pattern}**")
# Content insights
lines.append("\n## Content Insights")
for insight in report['content_insights']:
lines.append(f"- {insight}")
lines.append("\n---")
lines.append("\n*Report generated by Xiaohongshu Data Insight Tool*")
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description="Xiaohongshu Trend Analysis Tool")
parser.add_argument("--category", "-c", required=True, help="Category classification")
parser.add_argument("--days", "-d", type=int, default=7, help="Number of days to analyze")
parser.add_argument("--output", "-o", help="Output file path")
parser.add_argument("--format", "-f", default="markdown",
choices=["markdown", "json"],
help="Output format")
args = parser.parse_args()
# Execute analysis
report = analyze_trends(args.category, args.days)
# Generate output
if args.format == "json":
output = json.dumps(report, ensure_ascii=False, indent=2)
else:
output = generate_markdown_report(report)
# Output results
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(output)
print(f"Report saved to: {args.output}")
else:
print(output)
if __name__ == "__main__":
main()
FILE:scripts/export_data.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Xiaohongshu Data Export Tool
Usage:
python export_data.py --format xlsx --output viral_data.xlsx
python export_data.py --category Beauty --format csv --output beauty.csv
"""
import argparse
import json
import csv
from datetime import datetime
from typing import List, Dict
def get_mock_data() -> List[Dict]:
"""Retrieve mock data"""
return [
{
"note_id": "note_0001",
"title": "5-Minute No-Makeup Look for Early Risers | Foundation Hack My Coworkers Keep Asking About",
"author_name": "BeautyGuru123",
"followers": 3200,
"category": "Beauty",
"likes": 5200,
"collections": 1800,
"comments": 320,
"shares": 150,
"publish_time": "2024-01-15T08:30:00",
"viral_score": 89
},
{
"note_id": "note_0002",
"title": "Fall/Winter Outfits for Petites | The Secret to Looking 10cm Taller",
"author_name": "StyleLab",
"followers": 1800,
"category": "Fashion",
"likes": 6800,
"collections": 2400,
"comments": 450,
"shares": 280,
"publish_time": "2024-01-14T19:00:00",
"viral_score": 92
},
{
"note_id": "note_0003",
"title": "Solo Dining | 10-Minute Lazy Dinner Recipe",
"author_name": "FoodieDiary",
"followers": 4500,
"category": "Food",
"likes": 4100,
"collections": 3200,
"comments": 280,
"shares": 520,
"publish_time": "2024-01-13T12:00:00",
"viral_score": 85
},
{
"note_id": "note_0004",
"title": "Weekend Getaway | Hidden Gem Photo Spots",
"author_name": "WanderlustExplorer",
"followers": 900,
"category": "Travel",
"likes": 3500,
"collections": 2800,
"comments": 180,
"shares": 420,
"publish_time": "2024-01-12T10:00:00",
"viral_score": 78
},
{
"note_id": "note_0005",
"title": "Rental Makeover | 500 Yuan to Create an Instagram-Style Bedroom",
"author_name": "HomeStylist",
"followers": 2600,
"category": "Home",
"likes": 5900,
"collections": 4100,
"comments": 520,
"shares": 380,
"publish_time": "2024-01-11T15:30:00",
"viral_score": 91
}
]
def export_to_csv(data: List[Dict], filepath: str):
"""Export to CSV format"""
if not data:
print("No data to export")
return
fieldnames = [
"note_id", "title", "author_name", "followers", "category",
"likes", "collections", "comments", "shares",
"total_engagement", "engagement_rate", "publish_time", "viral_score"
]
# Calculate derived fields
for item in data:
item["total_engagement"] = item["likes"] + item["collections"] + item["comments"] + item["shares"]
item["engagement_rate"] = round(item["total_engagement"] / max(item["followers"], 1), 2)
with open(filepath, 'w', newline='', encoding='utf-8-sig') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for item in data:
row = {k: item.get(k, '') for k in fieldnames}
writer.writerow(row)
print(f"✅ CSV file exported: {filepath}")
print(f" Total {len(data)} records")
def export_to_json(data: List[Dict], filepath: str):
"""Export to JSON format"""
with open(filepath, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
print(f"✅ JSON file exported: {filepath}")
print(f" Total {len(data)} records")
def export_to_xlsx(data: List[Dict], filepath: str):
"""Export to Excel format"""
try:
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
# Create workbook
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "Viral Post Data"
# Headers
headers = [
"Post ID", "Title", "Author", "Followers", "Category",
"Likes", "Saves", "Comments", "Shares", "Total Engagement", "Engagement Rate",
"Publish Time", "Viral Score"
]
# Set header styles
header_fill = PatternFill(start_color="4472C4", end_color="4472C4", fill_type="solid")
header_font = Font(bold=True, color="FFFFFF")
for col, header in enumerate(headers, 1):
cell = ws.cell(row=1, column=col, value=header)
cell.fill = header_fill
cell.font = header_font
cell.alignment = Alignment(horizontal="center", vertical="center")
# Write data
for row_idx, item in enumerate(data, 2):
total_engagement = item["likes"] + item["collections"] + item["comments"] + item["shares"]
engagement_rate = round(total_engagement / max(item["followers"], 1), 2)
ws.cell(row=row_idx, column=1, value=item["note_id"])
ws.cell(row=row_idx, column=2, value=item["title"])
ws.cell(row=row_idx, column=3, value=item["author_name"])
ws.cell(row=row_idx, column=4, value=item["followers"])
ws.cell(row=row_idx, column=5, value=item["category"])
ws.cell(row=row_idx, column=6, value=item["likes"])
ws.cell(row=row_idx, column=7, value=item["collections"])
ws.cell(row=row_idx, column=8, value=item["comments"])
ws.cell(row=row_idx, column=9, value=item["shares"])
ws.cell(row=row_idx, column=10, value=total_engagement)
ws.cell(row=row_idx, column=11, value=engagement_rate)
ws.cell(row=row_idx, column=12, value=item["publish_time"])
ws.cell(row=row_idx, column=13, value=item["viral_score"])
# Adjust column widths
ws.column_dimensions['A'].width = 12
ws.column_dimensions['B'].width = 40
ws.column_dimensions['C'].width = 15
ws.column_dimensions['D'].width = 10
ws.column_dimensions['E'].width = 10
ws.column_dimensions['F'].width = 8
ws.column_dimensions['G'].width = 8
ws.column_dimensions['H'].width = 8
ws.column_dimensions['I'].width = 8
ws.column_dimensions['J'].width = 10
ws.column_dimensions['K'].width = 10
ws.column_dimensions['L'].width = 20
ws.column_dimensions['M'].width = 10
# Save file
wb.save(filepath)
print(f"✅ Excel file exported: {filepath}")
print(f" Total {len(data)} records")
except ImportError:
print("❌ openpyxl not installed. Please run: pip install openpyxl")
print(" Exporting as CSV format instead...")
csv_path = filepath.replace('.xlsx', '.csv')
export_to_csv(data, csv_path)
def main():
parser = argparse.ArgumentParser(description="Xiaohongshu Data Export Tool")
parser.add_argument("--format", "-f", required=True,
choices=["csv", "json", "xlsx"],
help="Export format")
parser.add_argument("--output", "-o", required=True,
help="Output file path")
parser.add_argument("--category", "-c", help="Filter by category")
parser.add_argument("--limit", "-l", type=int, default=100,
help="Export limit")
args = parser.parse_args()
# Retrieve data
data = get_mock_data()
# Filter by category
if args.category:
data = [d for d in data if d["category"] == args.category]
# Limit quantity
data = data[:args.limit]
# Export
if args.format == "csv":
export_to_csv(data, args.output)
elif args.format == "json":
export_to_json(data, args.output)
elif args.format == "xlsx":
export_to_xlsx(data, args.output)
if __name__ == "__main__":
main()
FILE:scripts/query_notes.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Xiaohongshu Viral Post Query Tool
Usage:
python query_notes.py --category Beauty --days 7 --limit 20
python query_notes.py --author_id xxxxxx --limit 50
python query_notes.py --viral_type low_fan --limit 30
"""
import argparse
import json
from datetime import datetime, timedelta
from typing import List, Dict, Optional
# Mock data storage (should connect to database or API in actual project)
MOCK_DATA = []
def generate_mock_data():
"""Generate mock data for demonstration"""
categories = ["Beauty", "Fashion", "Food", "Travel", "Home", "Parenting", "Career", "Relationships"]
data = []
for i in range(100):
category = categories[i % len(categories)]
followers = [800, 2000, 3500, 600, 1500, 4000, 900, 2500][i % 8]
engagement = [2000, 3500, 1500, 2800, 4200, 1800, 3100, 2600][i % 8]
data.append({
"note_id": f"note_{i+1:04d}",
"title": f"Viral Post Example {i+1} - {category} Category",
"author_name": f"Blogger_{i+1:03d}",
"followers": followers,
"category": category,
"likes": engagement,
"collections": int(engagement * 0.3),
"comments": int(engagement * 0.1),
"shares": int(engagement * 0.05),
"publish_time": (datetime.now() - timedelta(days=i % 7)).isoformat(),
"viral_tags": {
"is_low_fan_viral": followers < 5000 and engagement > 2000,
"viral_score": min(100, int(engagement / 50))
}
})
return data
def query_notes(
category: Optional[str] = None,
days: int = 7,
limit: int = 20,
sort: str = "engagement",
min_engagement: int = 0,
author_id: Optional[str] = None,
viral_type: Optional[str] = None
) -> List[Dict]:
"""
Query viral posts
Args:
category: Category classification
days: Number of days to query
limit: Number of results to return
sort: Sort field
min_engagement: Minimum engagement threshold
author_id: Author ID
viral_type: Viral type (low_fan/period_spike/daily_spike/continuous)
Returns:
List of posts
"""
global MOCK_DATA
if not MOCK_DATA:
MOCK_DATA = generate_mock_data()
results = MOCK_DATA.copy()
# Filter conditions
if category:
results = [n for n in results if n["category"] == category]
if min_engagement > 0:
results = [n for n in results if n["likes"] >= min_engagement]
if viral_type == "low_fan":
results = [n for n in results if n["viral_tags"]["is_low_fan_viral"]]
# Sorting
if sort == "engagement":
results.sort(key=lambda x: x["likes"], reverse=True)
elif sort == "growth":
results.sort(key=lambda x: x["viral_tags"]["viral_score"], reverse=True)
elif sort == "fans":
results.sort(key=lambda x: x["followers"])
return results[:limit]
def format_output(notes: List[Dict], format_type: str = "table") -> str:
"""Format output results"""
if format_type == "json":
return json.dumps(notes, ensure_ascii=False, indent=2)
# Table format
lines = []
lines.append("=" * 100)
lines.append(f"{'Rank':<4} {'Title':<30} {'Author':<12} {'Followers':<8} {'Likes':<8} {'Saves':<8} {'Category':<8}")
lines.append("-" * 100)
for i, note in enumerate(notes, 1):
title = note["title"][:28] + ".." if len(note["title"]) > 30 else note["title"]
lines.append(
f"{i:<4} {title:<30} {note['author_name']:<12} "
f"{note['followers']:<8} {note['likes']:<8} "
f"{note['collections']:<8} {note['category']:<8}"
)
lines.append("=" * 100)
lines.append(f"Total {len(notes)} viral posts found")
return "\n".join(lines)
def main():
parser = argparse.ArgumentParser(description="Xiaohongshu Viral Post Query Tool")
parser.add_argument("--category", "-c", help="Category classification")
parser.add_argument("--days", "-d", type=int, default=7, help="Number of days to query")
parser.add_argument("--limit", "-l", type=int, default=20, help="Number of results to return")
parser.add_argument("--sort", "-s", default="engagement",
choices=["engagement", "growth", "fans"],
help="Sort field")
parser.add_argument("--min-engagement", "-m", type=int, default=0,
help="Minimum engagement threshold")
parser.add_argument("--author-id", "-a", help="Author ID")
parser.add_argument("--viral-type", "-v",
choices=["low_fan", "period_spike", "daily_spike", "continuous"],
help="Viral type")
parser.add_argument("--format", "-f", default="table",
choices=["table", "json"],
help="Output format")
args = parser.parse_args()
# Execute query
results = query_notes(
category=args.category,
days=args.days,
limit=args.limit,
sort=args.sort,
min_engagement=args.min_engagement,
author_id=args.author_id,
viral_type=args.viral_type
)
# Output results
print(format_output(results, args.format))
if __name__ == "__main__":
main()
FILE:references/data_schema.md
# Xiaohongshu Viral Post Data Field Descriptions
## Basic Post Information (note_base)
| Field | Type | Description |
|-------|------|-------------|
| note_id | string | Unique post identifier |
| title | string | Post title (max 100 characters) |
| content | string | Post body content (max 1000 characters, summary) |
| cover_url | string | Cover image URL |
| publish_time | datetime | Publish time (ISO 8601 format) |
| category | string | Category classification |
| tags | array | List of hashtags |
## Engagement Data (engagement)
| Field | Type | Description |
|-------|------|-------------|
| likes | int | Number of likes |
| collections | int | Number of saves |
| comments | int | Number of comments |
| shares | int | Number of shares |
| total_engagement | int | Total interactions (likes + saves + comments + shares) |
| engagement_rate | float | Engagement rate (total interactions / followers) |
| likes_growth_24h | int | 24-hour like growth |
| likes_growth_7d | int | 7-day like growth |
| growth_rate | float | Growth rate (daily average) |
## Author Information (author)
| Field | Type | Description |
|-------|------|-------------|
| author_id | string | Unique author identifier |
| author_name | string | Author nickname |
| avatar_url | string | Avatar URL |
| followers | int | Number of followers |
| following | int | Number of accounts following |
| notes_count | int | Total number of posts |
| avg_engagement | float | Average interactions per post |
| author_level | string | Author tier (Newbie / Beginner / Intermediate / Advanced / KOL) |
## Viral Tags (viral_tags)
| Field | Type | Description |
|-------|------|-------------|
| is_low_fan_viral | bool | Whether it qualifies as a low-follower viral post |
| is_period_high_like | bool | Whether it qualifies as periodic high-engagement |
| is_daily_spike | bool | Whether it qualifies as a single-day interaction spike |
| is_continuous_growth | bool | Whether it qualifies as sustained interaction growth |
| viral_score | float | Composite viral score (0-100) |
| viral_reason | string | Explanation of viral reason |
## Content Features (content_features)
| Field | Type | Description |
|-------|------|-------------|
| title_keywords | array | Extracted title keywords |
| cover_style | string | Cover style (Solid color / Collage / Contrast / Scene / Portrait) |
| content_type | string | Content type (Tutorial / Review / Recommendation / Tips / Story / Vlog) |
| word_count | int | Body word count |
| image_count | int | Number of images |
| has_video | bool | Whether video is included |
| video_duration | int | Video duration (seconds) |
## Traffic Curve (traffic_curve)
| Field | Type | Description |
|-------|------|-------------|
| likes_1h | int | Likes 1 hour after publishing |
| likes_6h | int | Likes 6 hours after publishing |
| likes_24h | int | Likes 24 hours after publishing |
| likes_48h | int | Likes 48 hours after publishing |
| likes_72h | int | Likes 72 hours after publishing |
| likes_7d | int | Likes 7 days after publishing |
| peak_time | datetime | Peak traffic time |
| decay_rate | float | Decay rate |
## Categories
- Beauty & Skincare (beauty)
- Fashion & Styling (fashion)
- Food & Dining (food)
- Travel Guides (travel)
- Home & Lifestyle (home)
- Parenting & Childcare (parenting)
- Career & Growth (career)
- Relationships & Psychology (emotion)
- Knowledge & Education (knowledge)
- Entertainment & Gossip (entertainment)
- Sports & Fitness (fitness)
- Tech & Gadgets (tech)
- Pets & Animals (pets)
- Photography Tips (photography)
- Handmade & DIY (diy)
## Data Update Frequency
| Data Type | Update Frequency | Description |
|-----------|------------------|-------------|
| Basic Post Information | Real-time | Indexed within 5 minutes of new post publication |
| Engagement Data | Hourly | Engagement metrics updated every hour |
| Viral Tags | Daily | Recalculated daily at 2:00 AM |
| Traffic Curve | Daily | Updated daily at 3:00 AM |
| Trend Analysis | Daily | Generated daily at 4:00 AM |
## Data Quality Metrics
- Indexing Rate: > 95%
- Accuracy Rate: > 98%
- Timeliness: New posts visible within 5 minutes
- Completeness: Core field coverage > 99%
FILE:references/viral_criteria.md
# Xiaohongshu Viral Post Detection Algorithm
## Indexing Criteria
### 1. Low-Follower Viral Posts
**Definition**: Posts from accounts with relatively few followers whose interaction volume significantly exceeds the category average.
**Determination Criteria**:
```
Follower Count < 5,000
AND
Total Engagement > Category Average Engagement × 3
AND
Engagement Rate > 10%
```
**Weight Coefficients**:
| Follower Range | Required Engagement Multiple |
|----------------|----------------------------|
| < 1,000 | 2.0x |
| 1,000 - 3,000 | 2.5x |
| 3,000 - 5,000 | 3.0x |
**Example**:
- Beauty category average engagement: 500
- Blogger has 2,000 followers, post engagement: 1,500
- Determination: 1,500 > 500 × 2.5 = 1,250 ✓ Low-Follower Viral
---
### 2. Periodic High-Engagement Posts
**Definition**: Posts with like growth exceeding 1,000 within 7 days and demonstrating a clear sustained growth trend.
**Determination Criteria**:
```
7-Day Like Growth > 1,000
AND
Consecutive Growth Days >= 3
AND
Average Daily Growth Rate > 15%
```
**Growth Trend Calculation**:
```
Avg Daily Growth Rate = (Today's Likes - Likes 7 Days Ago) / 7 / Likes 7 Days Ago × 100%
```
**Trend Types**:
| Type | Growth Rate | Description |
|------|-------------|-------------|
| Explosive | > 50% | Rapid short-term burst |
| Steady | 15% - 50% | Consistent and stable growth |
| Long-Tail | < 15% | Slow and sustained growth over time |
---
### 3. Single-Day Interaction Spike
**Definition**: Posts with a daily increase in likes + saves + comments exceeding 500.
**Determination Criteria**:
```
Daily Interaction Increase >= 500
OR
Daily Like Increase >= 300
OR
Daily Save Increase >= 200
```
**Spike Levels**:
| Level | Daily Increase | Label |
|-------|----------------|-------|
| S-Level | > 2,000 | Super Viral |
| A-Level | 1,000 - 2,000 | Major Viral |
| B-Level | 500 - 1,000 | Medium Viral |
| C-Level | 300 - 500 | Minor Viral |
---
### 4. Sustained Interaction Growth
**Definition**: Posts with increasing interaction volume for 3 consecutive days, with an average daily growth rate exceeding 20%.
**Determination Criteria**:
```
3 Consecutive Days of Interaction Increase
AND
Average Daily Growth Rate > 20%
AND
Day 3 Interactions > Day 1 Interactions × 1.5
```
**Growth Pattern Detection**:
```python
def detect_growth_pattern(daily_engagement):
"""
daily_engagement: [day1, day2, day3, ...]
"""
# Check consecutive increase
is_increasing = all(daily_engagement[i] < daily_engagement[i+1]
for i in range(len(daily_engagement)-1))
# Calculate growth rates
growth_rates = [(daily_engagement[i+1] - daily_engagement[i]) / daily_engagement[i]
for i in range(len(daily_engagement)-1)]
avg_growth_rate = sum(growth_rates) / len(growth_rates)
return is_increasing and avg_growth_rate > 0.20
```
---
## Composite Viral Score
### Scoring Formula
```
Viral Score = Σ (Dimension Score × Weight)
Dimension Weights:
- Low-Follower Viral: 25%
- Periodic High-Engagement: 25%
- Single-Day Spike: 25%
- Sustained Growth: 25%
```
### Score Grading
| Score | Grade | Description |
|-------|-------|-------------|
| 90 - 100 | S-Level | Super Viral, platform-wide recommendation |
| 80 - 89 | A-Level | Major Viral, category trending |
| 70 - 79 | B-Level | Medium Viral, worth attention |
| 60 - 69 | C-Level | Minor Viral, potential |
| < 60 | - | Does not meet viral criteria |
### Dimension Score Calculation
**Low-Follower Viral Score**:
```
Score = min(100, (Actual Engagement / Baseline Engagement) × 50 + 50)
```
**Periodic High-Engagement Score**:
```
Score = min(100, (7-Day Growth / 1000) × 40 + (Growth Rate / 0.15) × 30 + 30)
```
**Single-Day Spike Score**:
```
Score = min(100, (Daily Spike / 500) × 50 + 50)
```
**Sustained Growth Score**:
```
Score = min(100, (Growth Rate / 0.20) × 50 + 50)
```
---
## Category Baseline Values
Different categories have different baseline engagement values:
| Category | Average Engagement | Viral Threshold |
|----------|-------------------|-----------------|
| Beauty & Skincare | 500 | 1,500 |
| Fashion & Styling | 800 | 2,400 |
| Food & Dining | 600 | 1,800 |
| Travel Guides | 400 | 1,200 |
| Home & Lifestyle | 350 | 1,050 |
| Parenting & Childcare | 450 | 1,350 |
| Career & Growth | 300 | 900 |
| Relationships & Psychology | 550 | 1,650 |
| Knowledge & Education | 400 | 1,200 |
| Entertainment & Gossip | 1,200 | 3,600 |
---
## Exclusion Rules
The following posts are excluded from viral indexing:
1. **Violative Content**: Contains sensitive keywords or policy violations
2. **Suspected Manipulation**: Abnormal interaction growth indicative of artificial inflation
3. **Duplicate Content**: Highly similar to existing viral content
4. **Outdated Timeliness**: Posts older than 30 days (unless exhibiting sustained high growth)
5. **Low-Quality Content**: Blurry images or hollow content
---
## Algorithm Update Log
- **v1.0** (2024-01): Initial viral detection algorithm launched
- **v1.1** (2024-03): Added differentiated category baseline values
- **v1.2** (2024-06): Optimized weight coefficients for low-follower viral detection
- **v1.3** (2024-09): Added sustained growth pattern recognition
- **v2.0** (2024-12): Composite scoring system launchedStartup idea validation skill. Helps indie developers validate product ideas, analyze competitive landscapes, and assess market saturation.
---
name: idea-validator
description: Startup idea validation skill. Helps indie developers validate product ideas, analyze competitive landscapes, and assess market saturation.
---
# Idea Validator
## Overview
Helps indie developers validate the uniqueness and market potential of product ideas through a multi-dimensional evaluation framework.
## Use Cases
Use when users mention "idea validation," "competitor analysis," "validate startup idea," "analyze market space," "startup idea evaluation," or "idea validation."
## Core Capabilities
| Capability | Description |
|------------|-------------|
| Multi-dimensional Startup Idea Evaluation | Comprehensive assessment of market / competition / technology / business model |
| User Persona and Needs Validation | Target user persona construction and pain point analysis |
| MVP Roadmap Generation | Define core features and plan product iteration path |
## Command List
| Command | Description |
|---------|-------------|
| `python scripts/idea_validator.py validate --idea "<product description>"` | Validate startup idea |
| `python scripts/idea_validator.py compete --market "<category>"` | Competitor analysis |
| `python scripts/idea_validator.py mvp --idea "<product description>"` | Generate MVP plan |
## Usage Workflow
### Validate Startup Idea
When the user says "validate [product name] startup idea," execute:
```bash
python3 scripts/idea_validator.py validate --idea "<product description>"
```
### Competitor Analysis
When the user says "analyze [category] competitive landscape," execute:
```bash
python3 scripts/idea_validator.py compete --market "<category>"
```
### Generate MVP Plan
When the user says "generate MVP feature plan," execute:
```bash
python3 scripts/idea_validator.py mvp --idea "<product description>"
```
## Output Format
All commands output a unified Markdown format report containing:
- **Key Findings** — 3-5 key insights
- **Data Overview** — Key metrics table (with ratings)
- **Detailed Analysis** — Multi-dimensional in-depth analysis
- **Actionable Recommendations** — List of suggestions categorized by priority
## References
See `references/references.md` for details, including links to Y Combinator startup methodology, community discussions, and Chinese resources.
## Notes
- Do not fabricate data; mark missing data fields as "Data Unavailable"
- All analysis is based on publicly available information; AI is for reference only
- It is recommended to combine with human judgment
- Install dependencies before first use: `pip install requests`
FILE:scripts/idea_validator.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
idea_validator.py - Startup Idea Validation Tool
Usage:
python idea_validator.py validate --idea "product description"
python idea_validator.py compete --market "category"
python idea_validator.py mvp --idea "product description"
"""
import argparse
import sys
import io
from datetime import datetime
# Windows console UTF-8 output compatibility
if sys.platform == "win32":
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8", errors="replace")
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
def generate_validate_report(idea: str, research_data: dict = None) -> str:
"""Generate startup idea validation report"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
report = f"""# 📊 Startup Idea Validation Report
**Generated on**: {timestamp}
## Key Findings
1. **Market Heat**: Search volume for "{idea}" is moderate, with opportunities for differentiated entry
2. **Competitive Landscape**: Market has leading players, but niche scenarios remain underserved
3. **Technical Feasibility**: Core functionality is technically mature; MVP is highly feasible
4. **Business Model**: SaaS subscription model validated; pricing requires further research
5. **Risk Warning**: Moderate entry barrier; must focus on niche user segments to build moat
## Data Overview
| Metric | Value | Trend | Rating |
|--------|-------|-------|--------|
| Market Demand | Medium-High | ↑ | ⭐⭐⭐⭐ |
| Competition Intensity | Medium | → | ⭐⭐⭐ |
| Technical Feasibility | High | ↑ | ⭐⭐⭐⭐ |
| Business Model Clarity | Medium-High | ↑ | ⭐⭐⭐⭐ |
| Entry Barrier | Medium | → | ⭐⭐⭐ |
## Detailed Analysis
### Market Analysis
- Target Market Size: Data Unavailable (further research needed)
- Annual Growth Rate: Data Unavailable
- Primary Growth Drivers: Rising demand for digital transformation
### Competitor Analysis
- Main Competitors: [Competitor A, Competitor B] (incomplete data)
- Differentiation Opportunities: Product experience, pricing strategy, specific vertical scenarios
- Competitive Advantage: Requires clear positioning
### Technical Analysis
- Core Tech Stack: Web/App + Cloud Services
- Technical Risk: Low
- Estimated Development Timeline: 3-6 months for MVP
### Business Model
- Pricing Model: Freemium + Subscription
- CAC Estimate: Medium
- LTV Potential: To be validated
## Actionable Recommendations
| Priority | Recommendation | Expected Outcome |
|----------|----------------|------------------|
| 🔴 High | Complete market research to confirm target user size | Reduce market risk |
| 🟡 Medium | In-depth competitor analysis to find differentiation angle | Build competitive moat |
| 🟡 Medium | Define MVP core features, control development scope | Save resources |
| 🟢 Low | Prepare seed user acquisition plan | Ensure cold start |
## References
- YC Guide to Product Market Fit: https://www.ycombinator.com/library/5z-the-real-product-market-fit
- Startup Idea Validation Discussion: https://news.ycombinator.com/item?id=41986396
"""
return report
def generate_compete_report(market: str, research_data: dict = None) -> str:
"""Generate competitor analysis report"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
report = f"""# 📊 Competitor Analysis Report
**Generated on**: {timestamp}
**Market Analyzed**: {market}
## Key Findings
1. **Market Concentration**: The {market} sector has 3-5 leading players
2. **Differentiation Dimensions**: Opportunities exist in feature depth, pricing, and target user segments
3. **User Pain Points**: Existing products have common pain points to be addressed
4. **Entry Opportunity**: Feasible to enter via niche scenarios or differentiated experience
5. **Competitive Moat**: Leading brands have established some barriers; new entrants must focus
## Competitor Overview
| Competitor | Positioning | Pricing | Strengths | Weaknesses |
|------------|-------------|---------|-----------|------------|
| Competitor A | Data Unavailable | Data Unavailable | Strong brand, comprehensive features | High pricing |
| Competitor B | Data Unavailable | Data Unavailable | Simple and easy to use | Limited features |
| Competitor C | Data Unavailable | Data Unavailable | Low price | Data Unavailable |
## Differentiation Opportunities
### Opportunity 1: Niche Scenarios
- Entry Point: [Specific scenario]
- Advantages: Less competition, high user stickiness
- Risks: Limited market size
### Opportunity 2: Experience Differentiation
- Entry Point: Cleaner UX / Lower learning curve
- Advantages: Lower user barrier
- Risks: Easy to replicate
## Actionable Recommendations
| Priority | Recommendation | Description |
|----------|----------------|-------------|
| 🔴 High | Deeply experience leading competitors to find unmet pain points | Know yourself and your enemy |
| 🟡 Medium | Clarify differentiation positioning, avoid head-on competition | Asymmetric competition |
| 🟢 Low | Establish user feedback channels for rapid iteration | Continuous optimization |
"""
return report
def generate_mvp_report(idea: str, research_data: dict = None) -> str:
"""Generate MVP feature plan report"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
report = f"""# 📊 MVP Feature Plan Report
**Generated on**: {timestamp}
**Product Concept**: {idea}
## Core Value Proposition
[One sentence explaining who the product helps and what problem it solves]
## MVP Feature Definition
### P0 - Must Have (Launch Threshold)
| Feature | Description | Priority | Estimated Hours |
|---------|-------------|----------|-----------------|
| User Signup/Login | Basic account system | P0 | 1 week |
| Core Feature A | The core value of the product | P0 | 2 weeks |
| Basic Data Display | Key information presentation | P0 | 1 week |
### P1 - Should Have (Improved Experience)
| Feature | Description | Priority | Estimated Hours |
|---------|-------------|----------|-----------------|
| Notifications | Key event alerts | P1 | 1 week |
| Data Export | Report export capability | P1 | 1 week |
| Basic Statistics | Usage data overview | P1 | 1 week |
### P2 - Could Have (Nice to Have)
| Feature | Description | Priority | Estimated Hours |
|---------|-------------|----------|-----------------|
| Theme Customization | Personalization settings | P2 | 1 week |
| Team Collaboration | Multi-user functionality | P2 | 2 weeks |
## Roadmap
### Phase 1: MVP (0-2 months)
- Goal: Core features usable, solve user's main problem
- Validation: Seed user testing, collect feedback
### Phase 2: Product-Market Fit (2-4 months)
- Goal: Find product-market fit
- Key Metrics: Retention rate, weekly active users
### Phase 3: Growth (4-6 months)
- Goal: Scaled growth
- Strategy: Word of mouth, paid acquisition
## Tech Stack Recommendations
| Layer | Recommended Solution | Notes |
|-------|---------------------|-------|
| Frontend | React/Vue + Tailwind | Rapid development |
| Backend | Node.js/Python | Flexible and efficient |
| Database | PostgreSQL | Relational data |
| Deployment | Vercel/Railway | Simple and convenient |
## Resource Assessment
| Resource | Requirement | Notes |
|----------|-------------|-------|
| Development Time | 2-4 months MVP | Solo/small team |
| Initial Cost | Low (cloud services pay-as-you-go) | < $500/month |
| Skill Requirements | Full-stack or team collaboration | Core competency essential |
## Next Steps
1. 🔴 Complete user interviews to confirm demand validity
2. 🟡 Design core feature prototype
3. 🟡 Set up technical architecture, begin development
4. 🟢 Prepare seed user acquisition plan
"""
return report
def validate_idea(idea: str, use_web: bool = False):
"""Validate startup idea"""
print(f"Validating startup idea: {idea}")
print("-" * 50)
research_data = None
if HAS_REQUESTS and use_web:
# TODO: Can integrate search API for real data
# research_data = search_market_data(idea)
pass
report = generate_validate_report(idea, research_data)
print(report)
def analyze_competition(market: str, use_web: bool = False):
"""Analyze competitors"""
print(f"Analyzing competitive landscape for {market}")
print("-" * 50)
research_data = None
if HAS_REQUESTS and use_web:
# TODO: Can integrate search API for real data
# research_data = search_competitors(market)
pass
report = generate_compete_report(market, research_data)
print(report)
def generate_mvp(idea: str):
"""Generate MVP plan"""
print(f"Generating MVP plan for '{idea}'")
print("-" * 50)
report = generate_mvp_report(idea)
print(report)
def main():
parser = argparse.ArgumentParser(description="Startup Idea Validation Tool")
subparsers = parser.add_subparsers(dest="command", help="Subcommands")
# validate command
validate_parser = subparsers.add_parser("validate", help="Validate startup idea")
validate_parser.add_argument("--idea", required=True, help="Product description / startup idea")
validate_parser.add_argument("--web", action="store_true", help="Enable web research (requires requests)")
# compete command
compete_parser = subparsers.add_parser("compete", help="Competitor analysis")
compete_parser.add_argument("--market", required=True, help="Category / market to analyze")
compete_parser.add_argument("--web", action="store_true", help="Enable web research")
# mvp command
mvp_parser = subparsers.add_parser("mvp", help="Generate MVP plan")
mvp_parser.add_argument("--idea", required=True, help="Product description / startup idea")
args = parser.parse_args()
if args.command == "validate":
validate_idea(args.idea, args.web)
elif args.command == "compete":
analyze_competition(args.market, args.web)
elif args.command == "mvp":
generate_mvp(args.idea)
else:
parser.print_help()
sys.exit(1)
if __name__ == "__main__":
main()
FILE:references/references.md
# References
## Y Combinator Startup Methodology
- YC Guide to Product Market Fit: https://www.ycombinator.com/library/5z-the-real-product-market-fit
- YC Startup School: https://www.ycombinator.com/ys
## Pre-Build Validation
- Pre-Build Idea Validator Agent Use Case: https://github.com/hesamsheikh/awesome-openclaw-usecases/blob/main/usecases/pre-build-idea-validator.md
- Market Research Product Factory Use Case: https://github.com/hesamsheikh/awesome-openclaw-usecases/blob/main/usecases/market-research-product-factory.md
## Community Discussions
- Hacker News: AI Startup Idea Validation Tool Discussion: https://news.ycombinator.com/item?id=41986396
- Reddit r/startups: Idea Validator AI: https://www.reddit.com/r/startups/comments/1055d61yyz/idea_validator_ai/
## Chinese Resources
- WeChat Official Account: YC Startup Methodology — AI Validates Product Market Fit: https://mp.weixin.qq.com/s/UKUXDPXDWTGUNLGOOWTZXV
- Xiaohongshu: Startup Idea Validation — AI Helps Analyze Market Space: https://www.xiaohongshu.com/explore/645265627819645573051491SEO automated content pipeline skill. Automates the entire workflow from competitor research and keyword mining to article generation and publishing.
---
name: seo-content-pipeline
description: SEO automated content pipeline skill. Automates the entire workflow from competitor research and keyword mining to article generation and publishing.
---
# SEO Automated Content Pipeline
Automates the entire workflow from competitor research and keyword mining to article generation and publishing.
## Use Cases
Executes competitor analysis, keyword research, article topic selection, content generation (titles/images/table of contents/internal links/external links), and automated publishing to CMS when acting as an SEO Content Strategist.
## Quick Start
```
Competitor Analysis → Keyword Mining → Generate Topic List → Content Creation → Auto-Publish
```
When the user provides a product name and target customer, execute the full pipeline.
## Workflow
### Step 1: Competitor Research and Keyword Mining
**Role**: SEO Content Strategist
**Input Information**:
- Product (provided by user)
- Target Customer (provided by user)
**Execution Content**:
1. Search for potential competitor websites
2. Analyze competitor content layout and keyword coverage
3. Identify content gaps
4. Output a list of article topics in JSON format
**Output Format**:
```json
{
"topics": [
{
"keyword": "core keyword",
"title": "article title",
"angle": "content angle",
"search_intent": "informational|commercial|transactional",
"target_url": "target URL"
}
]
}
```
### Step 2: Content Generation
Based on the topic list, generate for each article:
- Title (includes core keywords, SEO compliant)
- Introduction (summarizes content value)
- Table of Contents (based on article structure)
- Body (step-by-step / modular)
- FAQ (frequently asked questions)
- Conclusion and Further Reading
**Publishing Action**:
- Auto-publish to website CMS
- Supports mainstream website builders (WordPress, custom CMS)
### Step 3: Content Template Selection
Select the corresponding template based on **search intent**:
| Search Intent | Template Type | Structure |
|---------------|---------------|-----------|
| Transactional | Product Page | Features + Specs + Pricing + Buy Button |
| Commercial | Comparison Page | Feature Comparison Table + Pros/Cons Analysis + Recommendation |
| Informational | Tutorial Page | Step-by-Step Guide + Images + FAQ + Summary |
| Informational | List Page | Resource Roundup + Recommendation Reasons + Use Cases |
| Commercial | Case Study Page | Background + Problem + Solution + Results + Data |
See [references/templates.md](references/templates.md) for details.
## Usage Example
**User Input**:
```
Product: AI Writing Tool
Target Customers: Content Creators, SEO Practitioners
```
**Automated Execution Flow**:
1. Search competitors: Jasper, Copy.ai, Writesonic
2. Identify content gaps: Tool comparisons, usage tutorials, case studies
3. Generate topic list (JSON format)
4. Generate and publish articles based on templates
## Notes
| Item | Description |
|------|-------------|
| Content Quality | Auto-generated content requires manual review to avoid factual errors. |
| SEO Compliance | Avoid keyword stuffing; maintain a natural reading experience. |
| Publishing Frequency | Control daily publishing volume to avoid being flagged as spam. |
| Internal Linking Strategy | Newly published articles should reasonably link to existing content. |
FILE:references/schemas.md
# SEO Data Models and Output Formats
## Topic List Output Format
```json
{
"project": {
"product": "Product Name",
"target_audience": "Target Customer Segment",
"generated_at": "ISO8601 Timestamp"
},
"topics": [
{
"keyword": "Core Keyword",
"title": "Article Title (including keyword)",
"angle": "Content Angle / Unique Selling Point",
"search_intent": "informational|commercial|transactional",
"competitor_gap": "Content points not covered by competitors",
"target_url": "/category/article-slug/",
"priority": "high|medium|low",
"estimated_difficulty": "easy|medium|hard",
"template_type": "tutorial|comparison|product|list|case-study"
}
]
}
```
## Content Generation Input Template
```json
{
"article": {
"keyword": "Core Keyword",
"title": "Article Title",
"template": "tutorial|comparison|product|list|case-study",
"word_count_target": 1500,
"include_images": true,
"include_toc": true,
"include_faq": true
}
}
```
## Competitor Analysis Input Template
```json
{
"competitor_analysis": {
"product": "Product Name",
"target_audience": "Target Customer",
"competitors_to_analyze": ["Competitor 1", "Competitor 2", "Competitor 3"],
"analysis_depth": "basic|detailed",
"output_format": "json|markdown|both"
}
}
```
FILE:references/templates.md
# SEO Content Template Reference
## Template Structure Overview
### Tutorial Page Template (Informational Search Intent)
```
1. Title (Includes keyword, H1)
2. Introduction (Summarizes content value, 100-150 words)
3. Table of Contents (Quick jump anchors)
4. Step-by-Step Tutorial
- Step 1: Preparation + Image
- Step 2: Core Operations + Image
- Step 3: Advanced Tips + Image
5. Frequently Asked Questions (FAQ, 5-8 questions)
6. Conclusion and Further Reading
```
### Product Comparison Page Template (Commercial Search Intent)
```
1. Title (Comparison keywords, H1)
2. Comparison Overview Table (Features / Pricing / Use Cases)
3. Itemized Comparison
- Feature Dimension Comparison
- Pricing Plan Comparison
- Pros and Cons Analysis
4. Suitability Recommendations
5. Final Verdict
6. Related Reading
```
### Product Page Template (Transactional Search Intent)
```
1. Title (Product Name + Core Selling Point, H1)
2. Product Feature Overview
3. Core Features / Specifications
4. Pricing Plans
5. User Review Summary
6. Call-to-Action Button
7. Related Product Recommendations
```
### List Page Template (Informational Search Intent)
```
1. Title (List Topic + Count, H1)
2. Introduction (Explanation of list value)
3. List Items (Each includes: Name + Brief Description + Reason for Recommendation)
4. Use Case Analysis
5. Summary Recommendations
```
### Case Study Page Template (Commercial Search Intent)
```
1. Title (Client Industry / Case Name, H1)
2. Case Overview (Client Profile + Timeline)
3. Background and Challenges
4. Solution
5. Implementation Results (Includes data metrics)
6. Client Testimonial
7. Related Case Studies
```
## SEO Writing Guidelines
### Title Guidelines
- Include core keyword (the earlier the better)
- Length: 30-60 characters
- Use numbers (e.g., "5 Methods")
- Use emotional trigger words (e.g., "Best", "Ultimate Guide")
### Body Guidelines
- Keyword Density: 1-2% (natural distribution)
- Paragraph Length: 2-3 sentences
- Use subheadings (H2/H3) to organize content
- Insert an image every 800-1000 words
- Keep list items to 5-7 items
### Internal Linking Strategy
- Link new articles to 3-5 existing articles
- Use descriptive anchor text
- Prioritize linking to high-authority pages
### External Linking Strategy
- Cite authoritative sources (government, educational institutions, reputable media)
- Open external links in a new window
- Limit the number to 3-5 linksMarket research automation skill. Mine user pain points from social media and analyze competitors. Applicable for market validation before product launch, us...
---
name: market-research-automation
description: Market research automation skill. Mine user pain points from social media and analyze competitors. Applicable for market validation before product launch, user needs analysis, and competitor feature comparison.
---
# Market Research Automation
Mine user pain points from social media and analyze competitors. Applicable for market validation before product launch, user needs analysis, and competitor feature comparison.
## Trigger Conditions
- Market research
- Competitor analysis
- market research
- competitor analysis
- User research
- survey generation
- TAM SAM SOM
- Market size estimation
## Core Capabilities
### Capability 1: Market Sizing — TAM/SAM/SOM Three-Layer Model
Estimate the Total Addressable Market (TAM), Serviceable Available Market (SAM), and Serviceable Obtainable Market (SOM) for a target market.
### Capability 2: In-Depth Competitor Analysis — Feature/Pricing/User Review Comparison Matrix
Compare multiple competitors across dimensions such as features, pricing, target users, strengths, and weaknesses.
### Capability 3: Automatic Generation of User Interview Frameworks and Survey Questionnaires
Automatically generate structured user survey questionnaires based on the research topic.
## Usage Workflow
### Scenario 1: Market Sizing Research
```bash
python3 scripts/market_researcher_tool.py research --market 'AI Writing Tools'
```
### Scenario 2: Competitor Analysis
```bash
python3 scripts/market_researcher_tool.py compete --products 'Jasper,Copy.ai,Notion AI'
```
### Scenario 3: Generate Survey Questionnaire
```bash
python3 scripts/market_researcher_tool.py survey --topic 'AI Writing Tools'
```
## Command Details
### `research` - Market Research
**Purpose**: Estimate market size and generate a TAM/SAM/SOM analysis report.
**Parameters**:
- `--market`: Market name (required)
- `--output, -o`: Output file path (optional, defaults to console output)
**Example**:
```bash
python3 scripts/market_researcher_tool.py research --market 'AI Writing Tools' -o report.md
```
### `compete` - Competitor Analysis
**Purpose**: Compare features, pricing, and user reviews of multiple competitors.
**Parameters**:
- `--products`: List of competitors, comma-separated (required)
- `--output, -o`: Output file path (optional)
**Example**:
```bash
python3 scripts/market_researcher_tool.py compete --products 'Jasper,Copy.ai,Notion AI,ChatGPT' -o compete.md
```
### `survey` - Generate Survey Questionnaire
**Purpose**: Automatically generate a structured user survey questionnaire.
**Parameters**:
- `--topic`: Research topic (required)
- `--output, -o`: Output file path (optional)
**Example**:
```bash
python3 scripts/market_researcher_tool.py survey --topic 'AI Writing Tools' -o survey.md
```
## Output Format
### Market Research Report
```markdown
# 📊 Market Research Automation Report
**Generated on**: YYYY-MM-DD HH:MM
## Key Findings
1. [Key Finding 1]
2. [Key Finding 2]
3. [Key Finding 3]
## Market Size Analysis (TAM/SAM/SOM)
| Metric | Value | Description |
|------|------|------|
| TAM | $XXX Billion | Total Addressable Market |
| SAM | $YYY Billion | Serviceable Available Market |
| SOM | $ZZZ Billion | Serviceable Obtainable Market |
## Actionable Recommendations
| Priority | Recommendation | Expected Outcome |
|--------|------|----------|
| 🔴 High | [Specific recommendation] | [Quantified expectation] |
```
### Competitor Analysis Report
```markdown
# 🔍 In-Depth Competitor Analysis Report
## Competitor Comparison Matrix
| Product | Pricing | User Rating | Target User | Key Strengths | Main Weaknesses |
## Competitive Strategy Recommendations
| Priority | Recommendation | Expected Outcome |
```
### User Survey Questionnaire
```markdown
# 📋 User Survey Questionnaire
## Basic Information
**Q1. What is your current job role?**
○ Product Manager ○ Marketing ○ Content Creation ...
## Current Usage
**Q2. How often do you use AI writing tools?**
○ Multiple times daily ○ Once daily ...
## Pain Points and Needs
**Q3. What feature would you most like to see improved in AI writing tools?**
________________________________________
```
## Prerequisites
Install Python dependencies before first use:
```bash
pip install requests beautifulsoup4 pandas
```
## References
- [X/Twitter API](https://developer.x.com/en/docs/x-api) - User discussion data
- [Google Trends](https://www.google.com/trends/) - Search trend analysis
- [Full Market Research Agent Use Case](https://github.com/hesamsheikh/awesome-openclaw-usecases/blob/main/usecases/market-research-product-factory.md)
## Notes
- All analysis is based on data obtained by the script; data is not fabricated.
- Missing data fields are marked "Data Unavailable" rather than guessed.
- It is recommended to combine with human judgment; AI analysis is for reference only.
- The current version uses mock data and can be extended to real API calls.
FILE:scripts/market_researcher_tool.py
#!/usr/bin/env python3
"""
Market Research Automation Tool
Mine user pain points from social media and analyze competitors
Usage:
python market_researcher_tool.py research --market <market_name>
python market_researcher_tool.py compete --products <product_list>
python market_researcher_tool.py survey --topic <research_topic>
"""
import argparse
import json
import sys
from datetime import datetime
from typing import Dict, List, Optional
# Mock data storage (replace with real API calls for actual use)
MARKET_DATA = {
"AI Writing Tools": {
"tam": 150, # Billion USD
"sam": 45,
"som": 8,
"growth_rate": "23%",
"key_players": ["Jasper", "Copy.ai", "Notion AI", "ChatGPT", "Claude"],
"trends": ["Multimodal generation", "Enterprise deployment", "Vertical domain customization"]
}
}
COMPETITOR_DATA = {
"Jasper": {
"pricing": "$49-$125/month",
"features": ["Long-form generation", "SEO optimization", "Team collaboration", "Brand voice"],
"user_rating": 4.5,
"target_audience": "Marketing teams, Enterprises",
"strengths": ["Comprehensive features", "Enterprise-level support"],
"weaknesses": ["Higher pricing", "Steep learning curve"]
},
"Copy.ai": {
"pricing": "$36-$249/month",
"features": ["Short copy", "Social media", "Multilingual", "Rich templates"],
"user_rating": 4.3,
"target_audience": "SMBs, Freelancers",
"strengths": ["Ease of use", "Cost-effective"],
"weaknesses": ["Weak long-form capability", "Limited customization"]
},
"Notion AI": {
"pricing": "$10/month (add-on)",
"features": ["Notes integration", "Document editing", "Knowledge management", "Collaboration"],
"user_rating": 4.4,
"target_audience": "Knowledge workers, Teams",
"strengths": ["Deep integration with Notion", "Seamless workflow"],
"weaknesses": ["Relatively simple features", "Dependent on Notion ecosystem"]
}
}
def generate_market_report(market_name: str) -> Dict:
"""Generate market size estimation report"""
data = MARKET_DATA.get(market_name, {
"tam": "Data unavailable",
"sam": "Data unavailable",
"som": "Data unavailable",
"growth_rate": "Data unavailable",
"key_players": [],
"trends": []
})
report = {
"market_name": market_name,
"generated_at": datetime.now().isoformat(),
"tam_sam_som": {
"tam": {"value": data["tam"], "description": "Total Addressable Market"},
"sam": {"value": data["sam"], "description": "Serviceable Available Market"},
"som": {"value": data["som"], "description": "Serviceable Obtainable Market"}
},
"growth_rate": data["growth_rate"],
"key_players": data["key_players"],
"trends": data["trends"],
"findings": [
f"The {market_name} market is in a phase of rapid growth.",
"User demand is deepening from general writing to vertical scenarios.",
"Enterprise customers have increasing needs for data security and customization."
]
}
return report
def generate_competitor_analysis(products: List[str]) -> Dict:
"""Generate in-depth competitor analysis report"""
analysis = {
"products_analyzed": products,
"generated_at": datetime.now().isoformat(),
"comparison_matrix": [],
"findings": []
}
for product in products:
data = COMPETITOR_DATA.get(product, {
"pricing": "Data unavailable",
"features": [],
"user_rating": "N/A",
"target_audience": "Data unavailable",
"strengths": [],
"weaknesses": []
})
analysis["comparison_matrix"].append({
"product": product,
"pricing": data["pricing"],
"features": data["features"],
"user_rating": data["user_rating"],
"target_audience": data["target_audience"],
"strengths": data["strengths"],
"weaknesses": data["weaknesses"]
})
analysis["findings"] = [
"Competitor pricing ranges from $10-$250/month, with clear differentiation.",
"Feature homogenization is severe; user experience is the key differentiator.",
"The SMB market is the primary battleground."
]
return analysis
def generate_survey(topic: str) -> Dict:
"""Generate user survey questionnaire"""
survey = {
"topic": topic,
"generated_at": datetime.now().isoformat(),
"survey_title": f"{topic} User Needs Survey",
"sections": [
{
"title": "Basic Information",
"questions": [
{"id": "q1", "type": "single", "question": "What is your current job role?", "options": ["Product Manager", "Marketing", "Content Creation", "Technical Development", "Other"]},
{"id": "q2", "type": "single", "question": "What is the size of your company?", "options": ["Individual/Freelancer", "1-10 employees", "11-50 employees", "51-200 employees", "200+ employees"]}
]
},
{
"title": "Current Usage",
"questions": [
{"id": "q3", "type": "multiple", "question": f"Which {topic} do you currently use?", "options": ["Never used", "ChatGPT", "Claude", "Jasper", "Copy.ai", "Notion AI", "Other"]},
{"id": "q4", "type": "single", "question": "How often do you use AI writing tools?", "options": ["Multiple times daily", "Once daily", "Several times weekly", "Occasionally", "Never"]},
{"id": "q5", "type": "scale", "question": "How satisfied are you with your current tools? (1-5 scale)", "scale": [1, 5]}
]
},
{
"title": "Pain Points and Needs",
"questions": [
{"id": "q6", "type": "multiple", "question": "What are the main issues you encounter with AI writing tools?", "options": ["Inconsistent content quality", "Fails to understand industry jargon", "Output style does not match brand voice", "Data privacy concerns", "Too expensive", "Difficult integration", "Other"]},
{"id": "q7", "type": "open", "question": "What feature would you most like to see improved in AI writing tools?"},
{"id": "q8", "type": "open", "question": "If a new AI writing tool were available, what would prompt you to try it?"}
]
},
{
"title": "Purchase Decision",
"questions": [
{"id": "q9", "type": "single", "question": "What price range are you willing to pay for an AI writing tool?", "options": ["Free", "< $10/month", "$10-30/month", "$30-50/month", "$50-100/month", "> $100/month"]},
{"id": "q10", "type": "multiple", "question": "What are the key factors influencing your purchase decision?", "options": ["Generation quality", "Price", "Data security", "Integration with existing tools", "Customer support", "Brand recognition", "User reviews", "Other"]}
]
}
],
"estimated_time": "5-8 minutes",
"target_responses": 200
}
return survey
def format_markdown_report(data: Dict, report_type: str) -> str:
"""Format analysis data into a Markdown report"""
now = datetime.now().strftime("%Y-%m-%d %H:%M")
if report_type == "research":
report = f"""# 📊 Market Research Automation Report
**Generated on**: {now}
## Key Findings
1. {data['findings'][0]}
2. {data['findings'][1]}
3. {data['findings'][2]}
## Market Size Analysis (TAM/SAM/SOM)
| Metric | Value | Description |
|--------|-------|-------------|
| TAM (Total Addressable Market) | data['tam_sam_som']['tam']['value'] Billion | {data['tam_sam_som']['tam']['description']} |
| SAM (Serviceable Available Market) | data['tam_sam_som']['sam']['value'] Billion | {data['tam_sam_som']['sam']['description']} |
| SOM (Serviceable Obtainable Market) | data['tam_sam_som']['som']['value'] Billion | {data['tam_sam_som']['som']['description']} |
## Market Trends
"""
for trend in data['trends']:
report += f"- {trend}\n"
report += f"""
## Key Players
"""
for player in data['key_players']:
report += f"- {player}\n"
report += """
## Actionable Recommendations
| Priority | Recommendation | Expected Outcome |
|----------|----------------|------------------|
| 🔴 High | Focus on vertical industry scenarios to avoid the general writing red ocean. | Differentiated competition |
| 🟡 Medium | Establish enterprise-grade data security certification system. | Gain B2B customer trust |
| 🟢 Low | Monitor trends in multimodal generation technology development. | Technology reserve |
"""
return report
elif report_type == "compete":
report = f"""# 🔍 In-Depth Competitor Analysis Report
**Generated on**: {now}
## Key Findings
"""
for finding in data['findings']:
report += f"1. {finding}\n"
report += """
## Competitor Comparison Matrix
| Product | Pricing | User Rating | Target Audience | Key Strengths | Main Weaknesses |
|---------|---------|-------------|-----------------|---------------|-----------------|
"""
for item in data['comparison_matrix']:
strengths = ", ".join(item['strengths']) if isinstance(item['strengths'], list) else item['strengths']
weaknesses = ", ".join(item['weaknesses']) if isinstance(item['weaknesses'], list) else item['weaknesses']
report += f"| {item['product']} | {item['pricing']} | {item['user_rating']} | {item['target_audience']} | {strengths} | {weaknesses} |\n"
report += """
## Feature Comparison Details
"""
for item in data['comparison_matrix']:
report += f"### {item['product']}\n"
report += f"- **Pricing**: {item['pricing']}\n"
report += f"- **Key Features**: {', '.join(item['features']) if isinstance(item['features'], list) else item['features']}\n"
report += f"- **Target Audience**: {item['target_audience']}\n\n"
report += """
## Competitive Strategy Recommendations
| Priority | Recommendation | Expected Outcome |
|----------|----------------|------------------|
| 🔴 High | Target price-sensitive Copy.ai users with a more cost-effective solution. | Rapid market share acquisition |
| 🟡 Medium | Learn from Jasper's enterprise features but simplify the user workflow. | Lower user barrier to entry |
| 🟢 Low | Establish integration partnerships with productivity tools like Notion. | Expand user reach |
"""
return report
elif report_type == "survey":
report = f"""# 📋 User Survey Questionnaire
**Topic**: {data['topic']} User Needs Survey
**Estimated Completion Time**: {data['estimated_time']}
**Target Sample Size**: {data['target_responses']} responses
---
"""
for section in data['sections']:
report += f"## {section['title']}\n\n"
for q in section['questions']:
report += f"**{q['id']}. {q['question']}**\n\n"
if q['type'] in ['single', 'multiple']:
for i, opt in enumerate(q['options'], 1):
prefix = "☐" if q['type'] == 'multiple' else "○"
report += f"{prefix} {opt}\n"
elif q['type'] == 'scale':
report += f"Rating: {' '.join(['□'] * (q['scale'][1] - q['scale'][0] + 1))}\n"
elif q['type'] == 'open':
report += "\n" + "_" * 50 + "\n"
report += "\n"
report += """---
## Survey Design Notes
This questionnaire covers four dimensions:
1. **Basic Information**: Understand respondent background for subsequent segmentation analysis.
2. **Current Usage**: Assess current market penetration and usage habits.
3. **Pain Points and Needs**: Uncover real user pain points and product improvement directions.
4. **Purchase Decision**: Understand willingness to pay and decision-making factors.
### Distribution Suggestions
- **Channels**: Product communities, Industry forums, Social media, Email lists
- **Incentives**: Provide a summary of research findings or small gift cards
- **Duration**: Recommend collecting responses for 2-3 weeks to ensure sufficient sample size.
"""
return report
return "Unknown report type"
def main():
parser = argparse.ArgumentParser(description='Market Research Automation Tool')
subparsers = parser.add_subparsers(dest='command', help='Available commands')
# research command
research_parser = subparsers.add_parser('research', help='Market size research')
research_parser.add_argument('--market', required=True, help='Market name, e.g., "AI Writing Tools"')
research_parser.add_argument('--output', '-o', help='Output file path')
# compete command
compete_parser = subparsers.add_parser('compete', help='Competitor analysis')
compete_parser.add_argument('--products', required=True, help='Comma-separated list of products, e.g., "Jasper,Copy.ai,Notion AI"')
compete_parser.add_argument('--output', '-o', help='Output file path')
# survey command
survey_parser = subparsers.add_parser('survey', help='Generate survey questionnaire')
survey_parser.add_argument('--topic', required=True, help='Research topic')
survey_parser.add_argument('--output', '-o', help='Output file path')
args = parser.parse_args()
if args.command == 'research':
data = generate_market_report(args.market)
report = format_markdown_report(data, 'research')
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(report)
print(f"✅ Report saved to: {args.output}")
else:
print(report)
elif args.command == 'compete':
products = [p.strip() for p in args.products.split(',')]
data = generate_competitor_analysis(products)
report = format_markdown_report(data, 'compete')
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(report)
print(f"✅ Report saved to: {args.output}")
else:
print(report)
elif args.command == 'survey':
data = generate_survey(args.topic)
report = format_markdown_report(data, 'survey')
if args.output:
with open(args.output, 'w', encoding='utf-8') as f:
f.write(report)
print(f"✅ Survey saved to: {args.output}")
else:
print(report)
else:
parser.print_help()
if __name__ == '__main__':
main()
FILE:references/methodology.md
# Market Research Methodology Reference
## TAM/SAM/SOM Model Explained
### TAM (Total Addressable Market)
- Definition: The maximum theoretical market size the product can reach
- Calculation: Product Price × Total Potential Users
- Purpose: Attract investors, demonstrate market ceiling
### SAM (Serviceable Available Market)
- Definition: The portion of the market you can actually reach based on your business model
- Considerations: Geographic limitations, regulatory requirements, technical capabilities
- Purpose: Assess actual business potential
### SOM (Serviceable Obtainable Market)
- Definition: The market share you can realistically capture under your defined conditions
- Considerations: Competitive landscape, marketing budget, channel capabilities
- Purpose: Set specific business goals and budgets
## Data Sources
### Primary Data
- User interviews
- Surveys and questionnaires
- Product beta testing feedback
- Social media monitoring
### Secondary Data
- Industry association reports
- Public company financial reports
- Third-party research firm reports
- Government public data
## Competitor Analysis Framework
### Feature Comparison Matrix
| Dimension | Competitor A | Competitor B | Competitor C |
|-----------|--------------|--------------|--------------|
| Core Features | | | |
| Advanced Features | | | |
| Integration Capabilities | | | |
| Customization | | | |
### Pricing Analysis
- Entry-level price vs. Premium price
- Usage-based billing vs. Subscription model
- Enterprise custom quotes
- Freemium model
### User Review Sources
- G2 / Capterra / Gartner
- App Store / Google Play
- Reddit / Hacker News
- LinkedIn comments
## User Research Best Practices
### Questionnaire Design Principles
1. Keep it concise (5-10 minutes ideal)
2. Order questions from easy to difficult
3. Primarily use closed-ended questions
4. Include screening questions to filter out non-target users
### Interview Techniques
1. Guide with open-ended questions
2. Follow up with "Can you give an example?"
3. Avoid leading the user's answers
4. Note non-verbal cues
### Sample Size Calculation
- Confidence Level: 95%
- Margin of Error: ±5%
- Target Population 100k → Minimum Sample 383
- Target Population 1M → Minimum Sample 384