Initial commit

This commit is contained in:
Zhongwei Li
2025-11-29 18:26:08 +08:00
commit 8f22ddf339
295 changed files with 59710 additions and 0 deletions

View File

@@ -0,0 +1,510 @@
# meta.suggest - Context-Aware Next-Step Recommender
Helps Claude decide what to do next after an agent completes by analyzing context and suggesting compatible next steps.
## Overview
**meta.suggest** provides intelligent "what's next" recommendations by analyzing what just happened, what artifacts were produced, and what agents are compatible. It works with meta.compatibility to enable smart multi-agent orchestration.
**What it does:**
- Analyzes context (what agent ran, what artifacts produced)
- Uses meta.compatibility to find compatible next steps
- Provides ranked suggestions with clear rationale
- Considers project state and user goals
- Detects warnings (gaps, isolated agents)
- Suggests project-wide improvements
## Quick Start
### Suggest Next Steps
```bash
python3 agents/meta.suggest/meta_suggest.py \
--context meta.agent \
--artifacts agents/api.architect/agent.yaml
```
Output:
```
Context: meta.agent
Produced: agent-definition
🌟 Primary Suggestion:
Process with meta.compatibility
Rationale: meta.agent produces 'agent-definition' which meta.compatibility consumes
Priority: high
🔄 Alternatives:
1. Test the created artifact
Verify the artifact works as expected
2. Analyze compatibility
Understand what agents can work with meta.agent's outputs
```
### Analyze Project
```bash
python3 agents/meta.suggest/meta_suggest.py --analyze-project
```
Output:
```
📊 Project Analysis:
Total Agents: 7
Total Artifacts: 16
Relationships: 3
Gaps: 5
💡 Suggestions (6):
1. Create agent/skill to produce 'agent-description'
Consumed by 1 agents but no producers
Priority: medium
...
```
## Commands
### Suggest After Agent Runs
```bash
python3 agents/meta.suggest/meta_suggest.py \
--context AGENT_NAME \
[--artifacts FILE1 FILE2...] \
[--goal "USER_GOAL"] \
[--format json|text]
```
**Parameters:**
- `--context` - Agent that just ran
- `--artifacts` - Artifact files that were produced (optional)
- `--goal` - User's goal for better suggestions (optional)
- `--format` - Output format (text or json)
**Examples:**
```bash
# After meta.agent creates agent
python3 agents/meta.suggest/meta_suggest.py \
--context meta.agent \
--artifacts agents/my-agent/agent.yaml
# After meta.artifact creates artifact type
python3 agents/meta.suggest/meta_suggest.py \
--context meta.artifact \
--artifacts schemas/my-artifact.json
# With user goal
python3 agents/meta.suggest/meta_suggest.py \
--context meta.agent \
--goal "Create and validate API design agent"
```
### Analyze Project
```bash
python3 agents/meta.suggest/meta_suggest.py --analyze-project [--format json|text]
```
Analyzes the entire agent ecosystem and suggests improvements:
- Agents to create
- Gaps to fill
- Documentation needs
- Ecosystem health
## How It Works
### 1. Context Analysis
Determines what just happened:
- Which agent ran
- What artifacts were produced
- What artifact types are involved
### 2. Compatibility Check
Uses meta.compatibility to find:
- Agents that can consume the produced artifacts
- Agents that are compatible downstream
- Potential pipeline steps
### 3. Suggestion Generation
Creates suggestions based on:
- Compatible agents (high priority)
- Validation/testing options (medium priority)
- Gap-filling needs (low priority if applicable)
### 4. Ranking
Ranks suggestions by:
- Priority level (high > medium > low)
- Automation (automated > manual)
- Relevance to user goal
### 5. Warning Generation
Detects potential issues:
- Gaps in required artifacts
- Isolated agents (no compatible partners)
- Failed validations
## Suggestion Types
### 1. Process with Compatible Agent
```
🌟 Primary Suggestion:
Process with api.validator
Rationale: api.architect produces 'openapi-spec' which api.validator consumes
```
Automatically suggests running compatible agents.
### 2. Validate/Test Artifact
```
Test the created artifact
Rationale: Verify the artifact works as expected
```
Suggests testing when creation-type agents run.
### 3. Analyze Compatibility
```
Analyze compatibility
Rationale: Understand what agents can work with meta.agent's outputs
Command: python3 agents/meta.compatibility/meta_compatibility.py analyze meta.agent
```
Suggests understanding the ecosystem.
### 4. Fill Gaps
```
Create producer for 'agent-description'
Rationale: No agents produce 'agent-description' (required by meta.agent)
```
Suggests creating missing components.
## Output Structure
### Text Format
```
Context: AGENT_NAME
Produced: artifact-type-1, artifact-type-2
🌟 Primary Suggestion:
ACTION
Rationale: WHY
[Command: HOW (if automated)]
Priority: LEVEL
🔄 Alternatives:
1. ACTION
Rationale: WHY
⚠️ Warnings:
• WARNING_MESSAGE
```
### JSON Format
```json
{
"context": {
"agent": "meta.agent",
"artifacts_produced": ["agents/my-agent/agent.yaml"],
"artifact_types": ["agent-definition"],
"timestamp": "2025-10-24T..."
},
"suggestions": [
{
"action": "Process with meta.compatibility",
"agent": "meta.compatibility",
"rationale": "...",
"priority": "high",
"command": "..."
}
],
"primary_suggestion": {...},
"alternatives": [...],
"warnings": [...]
}
```
## Integration
### With meta.compatibility
meta.suggest uses meta.compatibility for discovery:
```python
# Internal call
compatibility = meta.compatibility.find_compatible(agent_name)
# Use compatible agents for suggestions
for compatible in compatibility.get("can_feed_to", []):
suggest(f"Process with {compatible['agent']}")
```
### With Claude
Claude can call meta.suggest after any agent:
```
User: Create an API design agent
Claude: *runs meta.agent*
Claude: *calls meta.suggest --context meta.agent*
Claude: I've created the agent. Would you like me to:
1. Analyze its compatibility
2. Test it
3. Add documentation
```
### In Workflows
Use in shell scripts:
```bash
#!/bin/bash
# Create and analyze agent
# Step 1: Create agent
python3 agents/meta.agent/meta_agent.py description.md
# Step 2: Get suggestions
SUGGESTIONS=$(python3 agents/meta.suggest/meta_suggest.py \
--context meta.agent \
--format json)
# Step 3: Extract primary suggestion
PRIMARY=$(echo "$SUGGESTIONS" | jq -r '.primary_suggestion.command')
# Step 4: Run it
eval "$PRIMARY"
```
## Common Workflows
### Workflow 1: Agent Creation Pipeline
```bash
# Create agent
python3 agents/meta.agent/meta_agent.py my_agent.md
# Get suggestions
python3 agents/meta.suggest/meta_suggest.py \
--context meta.agent \
--artifacts agents/my-agent/agent.yaml
# Follow primary suggestion
python3 agents/meta.compatibility/meta_compatibility.py analyze my-agent
```
### Workflow 2: Continuous Improvement
```bash
# Analyze project
python3 agents/meta.suggest/meta_suggest.py --analyze-project > improvements.txt
# Review suggestions
cat improvements.txt
# Implement top suggestions
# (create missing agents, fill gaps, etc.)
```
### Workflow 3: Goal-Oriented Orchestration
```bash
# Define goal
GOAL="Design, validate, and implement an API"
# Get suggestions for goal
python3 agents/meta.suggest/meta_suggest.py \
--goal "$GOAL" \
--format json > pipeline.json
# Execute suggested pipeline
# (extract steps from pipeline.json and run)
```
## Artifact Types
### Consumes
- **compatibility-graph** - Agent compatibility information
- From: meta.compatibility
- **agent-definition** - Agent that just ran
- Pattern: `agents/*/agent.yaml`
### Produces
- **suggestion-report** - Next-step recommendations
- Pattern: `*.suggestions.json`
- Schema: `schemas/suggestion-report.json`
## Understanding Suggestions
### Priority Levels
**High** - Should probably do this
- Compatible agent waiting
- Validation needed
- Next logical step
**Medium** - Good to do
- Analyze compatibility
- Understand ecosystem
- Non-critical validation
**Low** - Nice to have
- Fill gaps
- Documentation
- Future improvements
### Automated vs Manual
**Automated** - Has command to run
```
Command: python3 agents/meta.compatibility/...
```
**Manual** - Requires user action
```
(No command - manual action required)
```
### Rationale
Always includes "why" for each suggestion:
```
Rationale: meta.agent produces 'agent-definition' which meta.compatibility consumes
```
Helps Claude and users understand the reasoning.
## Tips & Best Practices
### Providing Context
More context = better suggestions:
**Good:**
```bash
--context meta.agent \
--artifacts agents/my-agent/agent.yaml \
--goal "Create and validate agent"
```
**Minimal:**
```bash
--context meta.agent
```
### Interpreting Warnings
**Gaps warning:**
```
⚠️ meta.agent requires artifacts that aren't produced by any agent
```
This is often expected for user inputs. Not always a problem.
**Isolated warning:**
```
⚠️ my-agent has no compatible agents
```
This suggests the agent uses non-standard artifact types or no other agents exist yet.
### Using Suggestions
1. **Review primary suggestion first** - Usually the best option
2. **Consider alternatives** - May be better for your specific case
3. **Check warnings** - Understand potential issues
4. **Verify commands** - Review before running automated suggestions
## Troubleshooting
### No suggestions returned
```
Error: Could not determine relevant agents for goal
```
**Causes:**
- Agent has no compatible downstream agents
- Artifact types are all user-provided inputs
- No other agents in ecosystem
**Solutions:**
- Create more agents
- Use standard artifact types
- Check agent artifact_metadata
### Incorrect suggestions
If suggestions don't make sense:
- Verify agent artifact_metadata is correct
- Check meta.compatibility output directly
- Ensure artifact types are registered
### Empty project analysis
```
Total Agents: 0
```
**Cause:** No agents found in `agents/` directory
**Solution:** Create agents using meta.agent or manually
## Architecture
```
meta.suggest
├─ Uses: meta.compatibility (discovery)
├─ Analyzes: context and artifacts
├─ Produces: ranked suggestions
└─ Helps: Claude make decisions
```
## Examples
```bash
# Example 1: After creating agent
python3 agents/meta.agent/meta_agent.py examples/api_architect_description.md
python3 agents/meta.suggest/meta_suggest.py --context meta.agent
# Example 2: After creating artifact type
python3 agents/meta.artifact/meta_artifact.py create artifact.md
python3 agents/meta.suggest/meta_suggest.py --context meta.artifact
# Example 3: Project health check
python3 agents/meta.suggest/meta_suggest.py --analyze-project
# Example 4: Export to JSON
python3 agents/meta.suggest/meta_suggest.py \
--context meta.agent \
--format json > suggestions.json
```
## Related Documentation
- [META_AGENTS.md](../../docs/META_AGENTS.md) - Meta-agent ecosystem
- [meta.compatibility README](../meta.compatibility/README.md) - Compatibility analyzer
- [ARTIFACT_STANDARDS.md](../../docs/ARTIFACT_STANDARDS.md) - Artifact system
- [suggestion-report schema](../../schemas/suggestion-report.json)
## How Claude Uses This
After any agent completes:
1. Claude calls meta.suggest with context
2. Reviews suggestions and rationale
3. Presents options to user or auto-executes
4. Makes intelligent orchestration decisions
meta.suggest is Claude's assistant for "what's next" decisions!

View File

@@ -0,0 +1,127 @@
name: meta.suggest
version: 0.1.0
description: |
Context-aware next-step recommender that helps Claude decide what to do next
after an agent completes.
Analyzes current context, produced artifacts, and project state to suggest
compatible agents and workflows. Works with meta.compatibility to provide
intelligent orchestration recommendations.
artifact_metadata:
consumes:
- type: compatibility-graph
description: "Agent compatibility information from meta.compatibility"
- type: agent-definition
description: "Agent that just ran"
produces:
- type: suggestion-report
file_pattern: "*.suggestions.json"
content_type: "application/json"
schema: "schemas/suggestion-report.json"
description: "Context-aware recommendations for next steps"
status: draft
reasoning_mode: iterative
capabilities:
- Analyze produced artifacts to understand project context
- Recommend next agents or workflows with supporting rationale
- Highlight gaps and dependencies to maintain delivery momentum
skills_available:
- meta.compatibility # Analyze compatibility
- artifact.define # Understand artifacts
permissions:
- filesystem:read
system_prompt: |
You are meta.suggest, the context-aware next-step recommender.
After an agent completes its work, you help Claude decide what to do next by
analyzing what artifacts were produced and suggesting compatible next steps.
## Your Responsibilities
1. **Analyze Context**
- What agent just ran?
- What artifacts were produced?
- What's the current project state?
- What might the user want to do next?
2. **Suggest Next Steps**
- Use meta.compatibility to find compatible agents
- Rank suggestions by relevance and usefulness
- Provide clear rationale for each suggestion
- Consider common workflows
3. **Be Smart About Context**
- If validation failed, don't suggest proceeding
- If artifacts were created, suggest consumers
- If gaps were detected, suggest filling them
- Consider the user's likely goals
## Commands You Support
**Suggest next steps after agent ran:**
```bash
/meta/suggest --context meta.agent --artifacts agents/my-agent/agent.yaml
```
**Analyze project and suggest:**
```bash
/meta/suggest --analyze-project
```
**Suggest for specific goal:**
```bash
/meta/suggest --goal "Design and implement an API"
```
## Suggestion Criteria
Good suggestions:
- Are relevant to what just happened
- Use artifacts that were produced
- Follow logical workflow order
- Provide clear value to the user
- Include validation/quality checks when appropriate
Bad suggestions:
- Suggest proceeding after failures
- Ignore produced artifacts
- Suggest irrelevant agents
- Don't explain why
## Output Format
Always provide:
- **Primary suggestion**: Best next step with strong rationale
- **Alternative suggestions**: 2-3 other options
- **Rationale**: Why each suggestion makes sense
- **Artifacts needed**: What inputs each option requires
- **Expected outcome**: What each option will produce
## Example Interactions
**Context:** meta.agent just created agent.yaml for new agent
**Suggestions:**
1. Validate the agent (meta.compatibility analyze)
- Rationale: Ensure agent has proper artifact compatibility
- Needs: agent.yaml (already produced)
- Produces: compatibility analysis
2. Test the agent (agent.run)
- Rationale: See if agent works as expected
- Needs: agent.yaml + test inputs
- Produces: execution results
3. Document the agent (manual)
- Rationale: Add examples and usage guide
- Needs: Understanding of agent purpose
- Produces: Enhanced README.md
Remember: You're Claude's assistant for orchestration. Help Claude make
smart decisions about what to do next based on context and compatibility.

View File

@@ -0,0 +1,371 @@
#!/usr/bin/env python3
"""
meta.suggest - Context-Aware Next-Step Recommender
Helps Claude decide what to do next after an agent completes by analyzing
context and suggesting compatible next steps.
"""
import json
import yaml
import sys
import os
from pathlib import Path
from typing import Dict, List, Any, Optional, Set
from datetime import datetime
# Add parent directory to path for imports
parent_dir = str(Path(__file__).parent.parent.parent)
sys.path.insert(0, parent_dir)
# Import meta.compatibility
meta_comp_path = parent_dir + "/agents/meta.compatibility"
sys.path.insert(0, meta_comp_path)
import meta_compatibility
class SuggestionEngine:
"""Context-aware suggestion engine"""
def __init__(self, base_dir: str = "."):
"""Initialize with base directory"""
self.base_dir = Path(base_dir)
self.compatibility_analyzer = meta_compatibility.CompatibilityAnalyzer(base_dir)
self.compatibility_analyzer.scan_agents()
self.compatibility_analyzer.build_compatibility_map()
def suggest_next_steps(
self,
context_agent: str,
artifacts_produced: Optional[List[str]] = None,
goal: Optional[str] = None
) -> Dict[str, Any]:
"""
Suggest next steps based on context
Args:
context_agent: Agent that just ran
artifacts_produced: List of artifact file paths produced
goal: Optional user goal
Returns:
Suggestion report with recommendations
"""
# Get compatibility info for the agent
compatibility = self.compatibility_analyzer.find_compatible(context_agent)
if "error" in compatibility:
return {
"error": compatibility["error"],
"context": {
"agent": context_agent,
"artifacts": artifacts_produced or []
}
}
# Determine artifact types produced
artifact_types = set()
if artifacts_produced:
artifact_types = self._infer_artifact_types(artifacts_produced)
else:
artifact_types = set(compatibility.get("produces", []))
suggestions = []
# Suggestion 1: Validate/analyze what was created
if context_agent not in ["meta.compatibility", "meta.suggest"]:
suggestions.append({
"action": "Analyze compatibility",
"agent": "meta.compatibility",
"command": f"python3 agents/meta.compatibility/meta_compatibility.py analyze {context_agent}",
"rationale": f"Understand what agents can work with {context_agent}'s outputs",
"artifacts_needed": [],
"produces": ["compatibility-graph"],
"priority": "medium",
"estimated_duration": "< 1 minute"
})
# Suggestion 2: Use compatible agents
can_feed_to = compatibility.get("can_feed_to", [])
for compatible in can_feed_to[:3]: # Top 3
next_agent = compatible["agent"]
artifact = compatible["artifact"]
suggestions.append({
"action": f"Process with {next_agent}",
"agent": next_agent,
"rationale": compatible["rationale"],
"artifacts_needed": [artifact],
"produces": self._get_agent_produces(next_agent),
"priority": "high",
"estimated_duration": "varies"
})
# Suggestion 3: If agent created something, suggest testing/validation
if artifact_types and context_agent in ["meta.agent", "meta.artifact"]:
suggestions.append({
"action": "Test the created artifact",
"rationale": "Verify the artifact works as expected",
"artifacts_needed": list(artifact_types),
"priority": "high",
"manual": True
})
# Suggestion 4: If gaps exist, suggest filling them
gaps = compatibility.get("gaps", [])
if gaps:
for gap in gaps[:2]: # Top 2 gaps
suggestions.append({
"action": f"Create producer for '{gap['artifact']}'",
"rationale": gap["issue"],
"severity": gap.get("severity", "medium"),
"priority": "low",
"manual": True
})
# Rank suggestions
suggestions = self._rank_suggestions(suggestions, goal)
# Build report
report = {
"context": {
"agent": context_agent,
"artifacts_produced": artifacts_produced or [],
"artifact_types": list(artifact_types),
"timestamp": datetime.now().isoformat()
},
"suggestions": suggestions,
"primary_suggestion": suggestions[0] if suggestions else None,
"alternatives": suggestions[1:4] if len(suggestions) > 1 else [],
"warnings": self._generate_warnings(context_agent, compatibility, gaps)
}
return report
def _infer_artifact_types(self, artifact_paths: List[str]) -> Set[str]:
"""Infer artifact types from file paths"""
types = set()
for path in artifact_paths:
path_lower = path.lower()
# Pattern matching
if ".openapi." in path_lower:
types.add("openapi-spec")
elif "agent.yaml" in path_lower:
types.add("agent-definition")
elif "readme.md" in path_lower:
if "agent" in path_lower:
types.add("agent-documentation")
elif ".validation." in path_lower:
types.add("validation-report")
elif ".optimization." in path_lower:
types.add("optimization-report")
elif ".compatibility." in path_lower:
types.add("compatibility-graph")
elif ".pipeline." in path_lower:
types.add("pipeline-suggestion")
elif ".workflow." in path_lower:
types.add("workflow-definition")
return types
def _get_agent_produces(self, agent_name: str) -> List[str]:
"""Get what an agent produces"""
if agent_name in self.compatibility_analyzer.agents:
agent_def = self.compatibility_analyzer.agents[agent_name]
produces, _ = self.compatibility_analyzer.extract_artifacts(agent_def)
return list(produces)
return []
def _rank_suggestions(self, suggestions: List[Dict], goal: Optional[str] = None) -> List[Dict]:
"""Rank suggestions by relevance"""
priority_order = {"high": 3, "medium": 2, "low": 1}
# Sort by priority, then by manual (auto first)
return sorted(
suggestions,
key=lambda s: (
-priority_order.get(s.get("priority", "medium"), 2),
s.get("manual", False) # Auto suggestions first
)
)
def _generate_warnings(
self,
agent: str,
compatibility: Dict,
gaps: List[Dict]
) -> List[Dict]:
"""Generate warnings based on context"""
warnings = []
# Warn about gaps
if gaps:
warnings.append({
"type": "gaps",
"message": f"{agent} requires artifacts that aren't produced by any agent",
"details": [g["artifact"] for g in gaps],
"severity": "medium"
})
# Warn if no compatible agents
if not compatibility.get("can_feed_to") and not compatibility.get("can_receive_from"):
warnings.append({
"type": "isolated",
"message": f"{agent} has no compatible agents",
"details": "This agent can't be used in multi-agent pipelines",
"severity": "low"
})
return warnings
def analyze_project(self) -> Dict[str, Any]:
"""Analyze entire project and suggest improvements"""
# Generate compatibility graph
graph = self.compatibility_analyzer.generate_compatibility_graph()
suggestions = []
# Suggest filling gaps
for gap in graph.get("gaps", []):
suggestions.append({
"action": f"Create agent/skill to produce '{gap['artifact']}'",
"rationale": gap["issue"],
"priority": "medium",
"impact": f"Enables {len(gap.get('consumers', []))} agents"
})
# Suggest creating more agents if few exist
if graph["metadata"]["total_agents"] < 5:
suggestions.append({
"action": "Create more agents using meta.agent",
"rationale": "Expand agent ecosystem for more capabilities",
"priority": "low"
})
# Suggest documentation if gaps exist
if graph.get("gaps"):
suggestions.append({
"action": "Document artifact standards for gaps",
"rationale": "Clarify requirements for missing artifacts",
"priority": "low"
})
return {
"project_analysis": {
"total_agents": graph["metadata"]["total_agents"],
"total_artifacts": graph["metadata"]["total_artifact_types"],
"total_relationships": len(graph["relationships"]),
"total_gaps": len(graph["gaps"])
},
"suggestions": suggestions,
"gaps": graph["gaps"],
"timestamp": datetime.now().isoformat()
}
def main():
"""CLI entry point"""
import argparse
parser = argparse.ArgumentParser(
description="meta.suggest - Context-Aware Next-Step Recommender"
)
parser.add_argument(
"--context",
help="Agent that just ran"
)
parser.add_argument(
"--artifacts",
nargs="+",
help="Artifacts that were produced"
)
parser.add_argument(
"--goal",
help="User's goal (for better suggestions)"
)
parser.add_argument(
"--analyze-project",
action="store_true",
help="Analyze entire project and suggest improvements"
)
parser.add_argument(
"--format",
choices=["json", "text"],
default="text",
help="Output format"
)
args = parser.parse_args()
engine = SuggestionEngine()
if args.analyze_project:
print("🔍 Analyzing project...\n")
result = engine.analyze_project()
if args.format == "text":
print(f"📊 Project Analysis:")
print(f" Total Agents: {result['project_analysis']['total_agents']}")
print(f" Total Artifacts: {result['project_analysis']['total_artifacts']}")
print(f" Relationships: {result['project_analysis']['total_relationships']}")
print(f" Gaps: {result['project_analysis']['total_gaps']}")
if result.get("suggestions"):
print(f"\n💡 Suggestions ({len(result['suggestions'])}):")
for i, suggestion in enumerate(result["suggestions"], 1):
print(f"\n {i}. {suggestion['action']}")
print(f" {suggestion['rationale']}")
print(f" Priority: {suggestion['priority']}")
else:
print(json.dumps(result, indent=2))
elif args.context:
print(f"💡 Suggesting next steps after '{args.context}'...\n")
result = engine.suggest_next_steps(
args.context,
args.artifacts,
args.goal
)
if args.format == "text":
if "error" in result:
print(f"❌ Error: {result['error']}")
return
print(f"Context: {result['context']['agent']}")
if result['context']['artifact_types']:
print(f"Produced: {', '.join(result['context']['artifact_types'])}")
if result.get("primary_suggestion"):
print(f"\n🌟 Primary Suggestion:")
ps = result["primary_suggestion"]
print(f" {ps['action']}")
print(f" Rationale: {ps['rationale']}")
if not ps.get("manual"):
print(f" Command: {ps.get('command', 'N/A')}")
print(f" Priority: {ps['priority']}")
if result.get("alternatives"):
print(f"\n🔄 Alternatives:")
for i, alt in enumerate(result["alternatives"], 1):
print(f"\n {i}. {alt['action']}")
print(f" {alt['rationale']}")
if result.get("warnings"):
print(f"\n⚠️ Warnings:")
for warning in result["warnings"]:
print(f"{warning['message']}")
else:
print(json.dumps(result, indent=2))
else:
parser.print_help()
if __name__ == "__main__":
main()