Initial commit

This commit is contained in:
Zhongwei Li
2025-11-30 08:29:39 +08:00
commit d0feb2b434
18 changed files with 2296 additions and 0 deletions

View File

@@ -0,0 +1,18 @@
{
"name": "meta-prompt",
"description": "State machine-based optimization infrastructure for token reduction through deterministic preprocessing. Features zero-token orchestration, hybrid classification, and specialized LLM agents for prompt optimization and task execution.",
"version": "1.0.0",
"author": {
"name": "Joe T. Sylve, Ph.D.",
"email": "joe.sylve@gmail.com"
},
"skills": [
"./skills"
],
"agents": [
"./agents"
],
"commands": [
"./commands"
]
}

3
README.md Normal file
View File

@@ -0,0 +1,3 @@
# meta-prompt
State machine-based optimization infrastructure for token reduction through deterministic preprocessing. Features zero-token orchestration, hybrid classification, and specialized LLM agents for prompt optimization and task execution.

View File

@@ -0,0 +1,40 @@
---
name: prompt-optimizer
description: Processes templates and extracts variables to create optimized prompts
allowed-tools: [Read(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/templates/**), AskUserQuestion, Bash(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/agents/scripts/prompt-optimizer-handler.sh:*)]
model: sonnet
---
Extract variables from user task, substitute into template, validate result, return optimized prompt.
## Process
1. **Call handler** with your XML input:
```bash
~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/agents/scripts/prompt-optimizer-handler.sh '<your-input-xml>'
```
2. **Extract variables** from user task based on handler output:
- Use variable descriptions (if provided) as guidance for extraction
- Required variables must have values (use AskUserQuestion if unclear)
- Optional variables can use defaults
3. **Substitute all** `{$VARIABLE}` and `{$VARIABLE:default}` patterns, remove YAML frontmatter
4. **Validate result** - scan your output for remaining `{$...}` patterns:
- If any remain, re-analyze user task or infer appropriate values
- Use default values for optional variables you missed
- If you cannot determine a **required** variable value and cannot reasonably infer it, use AskUserQuestion to request clarification from the user
- **Output MUST have ZERO remaining placeholders**
5. **Return XML**:
```xml
<prompt_optimizer_result>
<template>template-name</template>
<skill>skill-name or none</skill>
<execution_mode>plan or direct</execution_mode>
<optimized_prompt>
(complete template with all variables substituted - NO {$...} patterns)
</optimized_prompt>
</prompt_optimizer_result>
```

View File

@@ -0,0 +1,329 @@
#!/usr/bin/env bash
# Purpose: State machine for prompt-optimizer agent with integrated template processing
# Inputs: XML input via stdin containing user_task, template, execution_mode
# Outputs: Instructions with template content and variable extraction guidance
# Architecture: Incorporates template-processor.sh logic directly (no external bash calls needed)
set -euo pipefail
# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$SCRIPT_DIR/../../scripts/common.sh"
# Setup plugin root
setup_plugin_root
TEMPLATE_DIR="${CLAUDE_PLUGIN_ROOT}/templates"
# Parse XML input from command-line argument (supports multiline content)
read_xml_input() {
local xml_input="$1"
# Validate input provided
if [ -z "$xml_input" ]; then
echo "Error: No input provided. Usage: $0 '<xml-input>'" >&2
exit 1
fi
# Extract required fields using common functions
local user_task
user_task=$(require_xml_field "$xml_input" "user_task" "auto") || exit 1
local template
template=$(require_xml_field "$xml_input" "template") || {
echo "Error: Template selection must be done before calling prompt-optimizer." >&2
exit 1
}
# Extract optional field with default
local execution_mode
execution_mode=$(optional_xml_field "$xml_input" "execution_mode" "direct")
# Validate execution_mode
if [ "$execution_mode" != "plan" ] && [ "$execution_mode" != "direct" ]; then
echo "Error: Invalid execution_mode: $execution_mode (must be 'plan' or 'direct')" >&2
exit 1
fi
# Export safely (without sanitization for USER_TASK to preserve content, but sanitize for output)
export USER_TASK="$user_task"
export TEMPLATE="$template"
export EXECUTION_MODE="$execution_mode"
}
# Map template name to skill name
get_skill_for_template() {
local template=$1
case "$template" in
code-refactoring)
echo "meta-prompt:code-refactoring"
;;
code-review)
echo "meta-prompt:code-review"
;;
test-generation)
echo "meta-prompt:test-generation"
;;
documentation-generator)
echo "meta-prompt:documentation-generator"
;;
data-extraction)
echo "meta-prompt:data-extraction"
;;
code-comparison)
echo "meta-prompt:code-comparison"
;;
custom)
echo "none"
;;
*)
echo "none"
;;
esac
}
# Load template file with improved error messages
load_template() {
local template_name="$1"
local template_path="$TEMPLATE_DIR/${template_name}.md"
# Check if file exists
if [ ! -f "$template_path" ]; then
echo "Error: Template file not found: $template_path" >&2
echo "" >&2
echo "Available templates in $TEMPLATE_DIR:" >&2
if [ -d "$TEMPLATE_DIR" ]; then
ls -1 "$TEMPLATE_DIR"/*.md 2>/dev/null | sed 's/.*\// - /' | sed 's/\.md$//' >&2 || echo " (none found)" >&2
else
echo " Error: Template directory does not exist: $TEMPLATE_DIR" >&2
fi
echo "" >&2
echo "Requested template: $template_name" >&2
return 1
fi
# Check if file is readable
if [ ! -r "$template_path" ]; then
echo "Error: Template file not readable: $template_path" >&2
echo "Check file permissions." >&2
return 1
fi
# Check if file is non-empty
if [ ! -s "$template_path" ]; then
echo "Error: Template file is empty: $template_path" >&2
echo "Template files must contain prompt content." >&2
return 1
fi
cat "$template_path"
}
# Extract variables from template content
extract_variables() {
local template="$1"
# Find all {$VARIABLE} and {$VARIABLE:default} patterns
# Output format: VARIABLE (required) or VARIABLE:default (optional)
echo "$template" | grep -oE '\{\$[A-Z_][A-Z0-9_]*(:[^}]*)?\}' 2>/dev/null | sort -u | sed 's/[{}$]//g' || true
}
# Extract variable descriptions from template YAML frontmatter
# Returns formatted variable descriptions for agent guidance
extract_variable_descriptions() {
local template_content="$1"
# Extract YAML frontmatter (between first two ---)
local frontmatter
frontmatter=$(echo "$template_content" | awk '/^---$/{if(++n==1){next}else{exit}} n==1{print}')
# Check for variable_descriptions section
if ! echo "$frontmatter" | grep -q "variable_descriptions:"; then
return 0 # No descriptions available
fi
# Extract variable_descriptions block - get lines after variable_descriptions: until next top-level key
# Pipe through sanitize_input to escape potential shell metacharacters
echo "$frontmatter" | awk '
/^variable_descriptions:/ { in_block=1; next }
in_block && /^[a-z_]+:/ { exit }
in_block && /^ [A-Z_]+:/ {
# Remove leading spaces and print
sub(/^ /, "");
print
}
' | while IFS= read -r line; do
sanitize_input "$line"
done
}
# Format variable descriptions for display
# Input: raw variable descriptions (one per line in "NAME: description" format)
# Output: formatted markdown list
format_variable_descriptions() {
local var_descriptions="$1"
# Skip if empty or only whitespace
[ -z "$var_descriptions" ] && return 0
echo "$var_descriptions" | grep -q '[^[:space:]]' || return 0
echo "## Variable Descriptions"
echo ""
echo "$var_descriptions" | while IFS= read -r line; do
# Skip empty lines
[ -z "$line" ] && continue
# Split on first colon only to handle descriptions containing colons
name="${line%%:*}"
desc="${line#*:}"
# Trim whitespace from name
name="$(echo "$name" | sed 's/^[[:space:]]*//; s/[[:space:]]*$//')"
# Skip if name is empty
[ -z "$name" ] && continue
# Clean up the description (remove surrounding quotes and whitespace)
desc=$(echo "$desc" | sed 's/^[[:space:]]*"//; s/"[[:space:]]*$//; s/^[[:space:]]*//; s/[[:space:]]*$//')
echo "- **$name**: $desc"
done
}
# Escape special characters for output
escape_for_output() {
local value="$1"
# Escape for safe display in instructions (including $ for heredoc safety)
printf '%s\n' "$value" | sed 's/\\/\\\\/g; s/\$/\\$/g; s/`/\\`/g; s/"/\\"/g'
}
# Generate instructions for processing the template
generate_instructions() {
local sanitized_task=$(sanitize_input "$USER_TASK")
local skill=$(get_skill_for_template "$TEMPLATE")
# Load template content
local template_content
template_content=$(load_template "$TEMPLATE") || {
echo "Error: Failed to load template '$TEMPLATE'" >&2
exit 1
}
# Extract variables from template
local variables
variables=$(extract_variables "$template_content")
# Extract variable descriptions from frontmatter
local var_descriptions
var_descriptions=$(extract_variable_descriptions "$template_content")
# Escape template content for safe output
local escaped_template=$(escape_for_output "$template_content")
# Parse variables into required and optional lists
local required_vars=""
local optional_vars=""
while IFS= read -r var; do
if [ -z "$var" ]; then
continue
fi
if [[ "$var" == *:* ]]; then
# Variable has default value (optional)
local var_name="${var%%:*}"
# Note: default value is preserved in template, not extracted here
if [ -n "$optional_vars" ]; then
optional_vars="$optional_vars, $var_name"
else
optional_vars="$var_name"
fi
else
# No default value (required)
if [ -n "$required_vars" ]; then
required_vars="$required_vars, $var"
else
required_vars="$var"
fi
fi
done <<< "$variables"
cat <<EOF
Template: $TEMPLATE (already selected)
Skill: $skill
Execution mode: $EXECUTION_MODE
TASK: Extract variables from the user task and substitute them into the template.
User task: $sanitized_task
## Template Variables
$(if [ -n "$required_vars" ]; then echo "Required: $required_vars"; fi)
$(if [ -n "$optional_vars" ]; then echo "Optional: $optional_vars"; fi)
$(if [ -z "$required_vars" ] && [ -z "$optional_vars" ]; then echo "This template has no variables."; fi)
$(format_variable_descriptions "$var_descriptions")
## Instructions
1. **Extract variable values** from the user task:
- Analyze the user task to identify values for each variable
- Use the variable descriptions above as guidance for what to extract
- Required variables must have values
- Optional variables can use their defaults if not specified in the task
- Use AskUserQuestion if any required information is unclear
2. **Substitute variables** in the template:
- Replace each {\\\$VARIABLE} or {\\\$VARIABLE:default} with its value
- For optional variables without values, use their default
- Ensure all {\\\$...} patterns are replaced
3. **Validate your result** before outputting:
- Scan your substituted template for any remaining {\\\$...} patterns
- If ANY remain, go back and extract/infer appropriate values
- For optional variables you missed, use their default value from the pattern
- Your output MUST have ZERO remaining placeholders
4. **Output the result** in this XML format:
\`\`\`xml
<prompt_optimizer_result>
<template>$TEMPLATE</template>
<skill>$skill</skill>
<execution_mode>$EXECUTION_MODE</execution_mode>
<optimized_prompt>
[Insert the complete processed template here with all variables substituted]
</optimized_prompt>
</prompt_optimizer_result>
\`\`\`
## Template Content
\`\`\`
$escaped_template
\`\`\`
## Validation Checklist
Before returning your result, verify:
- [ ] No {\\\$VARIABLE} patterns remain in <optimized_prompt>
- [ ] No {\\\$VARIABLE:default} patterns remain in <optimized_prompt>
- [ ] YAML frontmatter (lines between ---) is NOT included
- [ ] All required variables have meaningful values from user task
- [ ] Optional variables either have extracted values or use their defaults
EOF
}
# Main function
main() {
# Check for command-line argument
if [ $# -eq 0 ]; then
echo "Error: No input provided. Usage: $0 '<xml-input>'" >&2
exit 1
fi
# Read and parse XML input from first argument
read_xml_input "$1"
# Generate and output instructions
generate_instructions
}
# Run main function
main "$@"

View File

@@ -0,0 +1,221 @@
#!/usr/bin/env bash
# Purpose: Deterministic input/output processing for template-executor agent
# Inputs: XML input containing skill and optimized_prompt
# Outputs: Instructions for Claude Code to execute
# Token reduction: Eliminates XML parsing, skill routing, and output formatting
set -euo pipefail
# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$SCRIPT_DIR/../../scripts/common.sh"
# Setup plugin root
setup_plugin_root
SKILL_DIR="${CLAUDE_PLUGIN_ROOT}/skills"
# Validate skill file exists
validate_skill() {
local skill="$1"
# "none" is always valid (no skill needed)
if [ "$skill" = "none" ]; then
return 0
fi
# Remove "meta-prompt:" prefix if present
local skill_name="${skill#meta-prompt:}"
local skill_file="${SKILL_DIR}/${skill_name}/SKILL.md"
if [ ! -f "$skill_file" ]; then
echo "Warning: Skill file not found: $skill_file" >&2
echo "" >&2
echo "Available skills in $SKILL_DIR:" >&2
if [ -d "$SKILL_DIR" ]; then
find "$SKILL_DIR" -name "SKILL.md" -type f 2>/dev/null | sed "s|$SKILL_DIR/||" | sed 's|/SKILL.md$||' | sed 's/^/ - meta-prompt:/' >&2 || echo " (none found)" >&2
else
echo " Error: Skill directory does not exist: $SKILL_DIR" >&2
fi
echo "" >&2
echo "Requested skill: $skill" >&2
echo "Continuing without skill..." >&2
return 1
fi
# Verify skill file is readable
if [ ! -r "$skill_file" ]; then
echo "Warning: Skill file exists but is not readable: $skill_file" >&2
echo "Check file permissions." >&2
return 1
fi
return 0
}
# Parse XML input from command-line argument (supports multiline content)
read_xml_input() {
local xml_input="$1"
# Validate input provided
if [ -z "$xml_input" ]; then
echo "Error: No input provided. Usage: $0 '<xml-input>'" >&2
exit 1
fi
# Extract required field using common function
local optimized_prompt
optimized_prompt=$(require_xml_field "$xml_input" "optimized_prompt" "auto") || exit 1
# Extract optional field with default
local skill
skill=$(optional_xml_field "$xml_input" "skill" "none")
# Validate skill file exists and fail if required skill is missing
# Note: If skill is "none", validate_skill returns 0, so we never enter this block
if ! validate_skill "$skill"; then
echo "Error: Required skill '$skill' not found. Cannot continue." >&2
exit 1
fi
# Export for use by other functions
export SKILL="$skill"
export OPTIMIZED_PROMPT="$optimized_prompt"
}
# Generate instructions
generate_instructions() {
cat <<'INSTRUCTIONS_EOF'
You are a versatile execution agent that combines template-based prompts with domain-specific skills to accomplish tasks efficiently.
## Your Task
Execute the optimized prompt provided below, following these steps:
INSTRUCTIONS_EOF
# Step 1: Load skill (if needed)
if [ "$SKILL" != "none" ]; then
cat <<EOF
### Step 1: Load Skill
Load the domain-specific skill to gain expertise:
\`\`\`
Skill: $SKILL
\`\`\`
The skill provides domain-specific best practices and guidance for task execution.
EOF
else
cat <<EOF
### Step 1: Skill Loading
No domain-specific skill required for this task (custom template).
EOF
fi
# Step 2: Execute Task
cat <<'EOF'
### Step 2: Execute Task
**IMPORTANT: Use TodoWrite to communicate your tasks and track progress throughout execution.**
Execute the task following:
1. **TodoWrite for task tracking**:
- Create a todo list IMMEDIATELY when you start if the task has multiple steps
- Mark tasks as in_progress before starting them
- Mark tasks as completed immediately after finishing them
- Keep exactly ONE task in_progress at a time
- Use todos to communicate what you're working on to the user
2. **Parallelization**:
- Identify independent operations that can run in parallel
- Make multiple tool calls in a single response when possible
- Chain dependent operations sequentially using && or multiple messages
3. **The optimized prompt's instructions** (provided below) - Your specific requirements
4. **The loaded skill's guidance** (if any) - Domain best practices and expertise
5. **Tool usage best practices**:
- Use specialized tools (Read/Edit/Write) not bash for file operations
- Never use placeholders - ask user if information is missing
### General Guidelines
**Code Modifications:**
- ALWAYS Read files before editing
- Use Edit for existing files, Write only for new files
- Preserve exact indentation
- Delete unused code completely (no comments or underscores)
- Avoid security vulnerabilities (injection, XSS, etc.)
**Analysis Tasks:**
- Be thorough and systematic
- Provide specific, actionable feedback
- Include examples and context
- Structure output clearly
**Quality Standards:**
- Follow existing conventions in the codebase
- Keep solutions simple and focused
- Make only requested changes (avoid over-engineering)
- Test changes when appropriate
EOF
# Step 3: Output format
cat <<'EOF'
### Step 3: Return Results
After completing the task, return your results in this XML format:
```xml
<template_executor_result>
<status>completed|failed|partial</status>
<summary>
Brief summary of what was accomplished
</summary>
<details>
Detailed results, changes made, files modified, etc.
</details>
</template_executor_result>
```
---
## Your Optimized Prompt
Below is the optimized prompt containing your specific task instructions:
EOF
# Output the optimized prompt
echo "$OPTIMIZED_PROMPT"
}
# Main function
main() {
# Check for command-line argument
if [ $# -eq 0 ]; then
echo "Error: No input provided. Usage: $0 '<xml-input>'" >&2
exit 1
fi
# Read and parse XML input from first argument
read_xml_input "$1"
# Generate and output instructions
generate_instructions
}
# Run main function
main "$@"

View File

@@ -0,0 +1,442 @@
#!/usr/bin/env bash
# Purpose: State machine for template-selector agent with integrated classification
# Inputs: XML input via stdin containing user_task, suggested_template (optional), confidence (optional)
# Outputs: Instructions with classification result
# Architecture: Incorporates template-selector.sh logic directly (no external bash calls needed)
set -euo pipefail
# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$SCRIPT_DIR/../../scripts/common.sh"
# Setup plugin root
setup_plugin_root
TEMPLATE_DIR="${CLAUDE_PLUGIN_ROOT}/templates"
# ============================================================================
# Confidence Threshold Configuration
# ============================================================================
#
# These values control template classification confidence scoring:
#
# BORDERLINE_MIN (60%):
# - Minimum confidence for accepting keyword-based classification
# - Below this: routes to LLM for borderline case review
# - Rationale: Ensures 90%+ accuracy by letting LLM handle uncertain cases
#
# STRONG_INDICATOR_BASE (75%):
# - Base confidence when a strong indicator keyword is found
# - Examples: "refactor", "compare", "test", "review"
# - Rationale: Strong indicators reliably predict template choice
#
# SUPPORTING_KEYWORD_BONUS (8% per keyword):
# - Additional confidence for each supporting keyword (max 100%)
# - Examples: "code", "module", "security", etc.
# - Rationale: Multiple related keywords increase confidence
#
# Confidence levels for supporting keywords only (no strong indicator):
# - ONE_KEYWORD_CONFIDENCE (35%): One supporting keyword found
# - TWO_KEYWORD_CONFIDENCE (60%): Two supporting keywords found
# - THREE_KEYWORD_CONFIDENCE (75%): Three+ supporting keywords found
#
# Example scoring:
# "Refactor the authentication module" = 75% (strong) + 8% (code keyword) = 83%
# "Check security of code" = 60% (two keywords: security, code)
# ============================================================================
BORDERLINE_MIN=60
STRONG_INDICATOR_BASE=75
SUPPORTING_KEYWORD_BONUS=8
ONE_KEYWORD_CONFIDENCE=35
TWO_KEYWORD_CONFIDENCE=60
THREE_KEYWORD_CONFIDENCE=75
# Regex patterns for strong indicators
PATTERN_CODE="refactor|codebase|implement|fix|update|modify|create|build|reorganize|improve|enhance|transform|optimize|rework|revamp|refine|polish|modernize|clean|streamline"
PATTERN_COMPARISON="compare|classify|check|same|different|verify|determine|match|matches|equivalent|equals?|similar|duplicate|identical"
PATTERN_TEST="tests?|spec|testing|unittest"
PATTERN_REVIEW="review|feedback|critique|analyze|assess|evaluate|examine|inspect|scrutinize|audit|scan|survey|vet|investigate|appraise"
PATTERN_DOCUMENTATION="documentation|readme|docstring|docs|document|write.*(comment|docstring|documentation|guide|instruction)|author.*(documentation|instruction|guide)"
PATTERN_EXTRACTION="extract|parse|pull|retrieve|mine|harvest|collect|scrape|distill|gather|isolate|obtain|sift|fish|pluck|glean|cull|unearth|dredge|winnow"
# Parse XML input from command-line argument (supports multiline content)
read_xml_input() {
local xml_input="$1"
# Validate input provided
if [ -z "$xml_input" ]; then
echo "Error: No input provided. Usage: $0 '<xml-input>'" >&2
exit 1
fi
# Extract required field using common function
local user_task
user_task=$(require_xml_field "$xml_input" "user_task" "auto") || exit 1
# Extract optional fields with defaults
local suggested_template
suggested_template=$(optional_xml_field "$xml_input" "suggested_template" "")
local confidence
confidence=$(optional_xml_field "$xml_input" "confidence" "")
# Validate confidence is a number if provided
if [ -n "$confidence" ] && ! [[ "$confidence" =~ ^[0-9]+$ ]]; then
echo "Error: Invalid confidence value: $confidence (must be integer)" >&2
exit 1
fi
# Export for use by other functions
export USER_TASK="$user_task"
export SUGGESTED_TEMPLATE="$suggested_template"
export SUGGESTED_CONFIDENCE="$confidence"
}
# Convert text to lowercase
to_lowercase() {
echo "$1" | tr '[:upper:]' '[:lower:]'
}
# Count keyword matches
count_matches() {
local text="$1"
shift
local IFS='|'
local pattern="$*"
echo "$text" | grep -oiE "\b($pattern)\b" 2>/dev/null | wc -l | tr -d ' '
}
# Pre-compute strong indicators
# Optimized to run grep once and check all patterns
compute_strong_indicators() {
local text="$1"
# Combine all patterns into a single grep call
local all_matches
all_matches=$(echo "$text" | grep -oiE "\b($PATTERN_CODE|$PATTERN_COMPARISON|$PATTERN_TEST|$PATTERN_REVIEW|$PATTERN_DOCUMENTATION|$PATTERN_EXTRACTION)\b" | tr '[:upper:]' '[:lower:]') || true
# Check which patterns matched
if echo "$all_matches" | grep -qiE "\b($PATTERN_CODE)\b"; then
HAS_STRONG_CODE=1
else
HAS_STRONG_CODE=0
fi
if echo "$all_matches" | grep -qiE "\b($PATTERN_COMPARISON)\b"; then
HAS_STRONG_COMPARISON=1
else
HAS_STRONG_COMPARISON=0
fi
if echo "$all_matches" | grep -qiE "\b($PATTERN_TEST)\b"; then
HAS_STRONG_TEST=1
else
HAS_STRONG_TEST=0
fi
if echo "$all_matches" | grep -qiE "\b($PATTERN_REVIEW)\b"; then
HAS_STRONG_REVIEW=1
else
HAS_STRONG_REVIEW=0
fi
if echo "$all_matches" | grep -qiE "\b($PATTERN_DOCUMENTATION)\b"; then
HAS_STRONG_DOCUMENTATION=1
else
HAS_STRONG_DOCUMENTATION=0
fi
if echo "$all_matches" | grep -qiE "\b($PATTERN_EXTRACTION)\b"; then
HAS_STRONG_EXTRACTION=1
else
HAS_STRONG_EXTRACTION=0
fi
}
# Check if category has strong indicator
has_strong_indicator() {
local category="$1"
case "$category" in
"code")
return $((1 - HAS_STRONG_CODE))
;;
"comparison")
return $((1 - HAS_STRONG_COMPARISON))
;;
"test")
return $((1 - HAS_STRONG_TEST))
;;
"review")
return $((1 - HAS_STRONG_REVIEW))
;;
"documentation")
return $((1 - HAS_STRONG_DOCUMENTATION))
;;
"extraction")
return $((1 - HAS_STRONG_EXTRACTION))
;;
*)
return 1
;;
esac
}
# Calculate confidence for a category
calculate_confidence() {
local category=$1
local supporting_count=$2
if has_strong_indicator "$category"; then
local confidence=$((STRONG_INDICATOR_BASE + supporting_count * SUPPORTING_KEYWORD_BONUS))
[ "$confidence" -gt 100 ] && confidence=100
echo "$confidence"
else
if [ "$supporting_count" -eq 0 ]; then
echo 0
elif [ "$supporting_count" -eq 1 ]; then
echo "$ONE_KEYWORD_CONFIDENCE"
elif [ "$supporting_count" -eq 2 ]; then
echo "$TWO_KEYWORD_CONFIDENCE"
else
echo "$THREE_KEYWORD_CONFIDENCE"
fi
fi
}
# Classify task and return template name with confidence
classify_task() {
local task_description="$1"
local task_lower=$(to_lowercase "$task_description")
# Pre-compute strong indicators
compute_strong_indicators "$task_lower"
# Define supporting keywords
local code_keywords=("code" "file" "class" "bug" "module" "system" "endpoint")
local comparison_keywords=("sentence" "equal" "whether" "mean" "version" "duplicate" "similarity")
local test_keywords=("coverage" "jest" "pytest" "junit" "mocha" "case" "suite" "edge" "unit" "generate")
local review_keywords=("readability" "maintainability" "practices" "smell")
local documentation_keywords=("comment" "guide" "reference" "explain" "api" "write" "function" "inline" "author" "instructions" "setup" "method")
local extraction_keywords=("data" "scrape" "retrieve" "json" "html" "csv" "email" "address" "timestamp" "logs" "file")
# Count matches
local code_count=$(count_matches "$task_lower" "${code_keywords[@]}")
local comparison_count=$(count_matches "$task_lower" "${comparison_keywords[@]}")
local testgen_count=$(count_matches "$task_lower" "${test_keywords[@]}")
local review_count=$(count_matches "$task_lower" "${review_keywords[@]}")
local documentation_count=$(count_matches "$task_lower" "${documentation_keywords[@]}")
local extraction_count=$(count_matches "$task_lower" "${extraction_keywords[@]}")
# Calculate confidence scores
local code_confidence=$(calculate_confidence "code" $code_count)
local comparison_confidence=$(calculate_confidence "comparison" $comparison_count)
local test_confidence=$(calculate_confidence "test" $testgen_count)
local review_confidence=$(calculate_confidence "review" $review_count)
local documentation_confidence=$(calculate_confidence "documentation" $documentation_count)
local extraction_confidence=$(calculate_confidence "extraction" $extraction_count)
# Find highest confidence
local max_confidence=0
local selected_template="custom"
if [ "$code_confidence" -gt "$max_confidence" ]; then
max_confidence=$code_confidence
selected_template="code-refactoring"
fi
if [ "$comparison_confidence" -gt "$max_confidence" ]; then
max_confidence=$comparison_confidence
selected_template="code-comparison"
fi
if [ "$test_confidence" -gt "$max_confidence" ]; then
max_confidence=$test_confidence
selected_template="test-generation"
fi
if [ "$review_confidence" -gt "$max_confidence" ]; then
max_confidence=$review_confidence
selected_template="code-review"
fi
if [ "$documentation_confidence" -gt "$max_confidence" ]; then
max_confidence=$documentation_confidence
selected_template="documentation-generator"
fi
if [ "$extraction_confidence" -gt "$max_confidence" ]; then
max_confidence=$extraction_confidence
selected_template="data-extraction"
fi
# Set to custom if below borderline threshold
if [ "$max_confidence" -lt "$BORDERLINE_MIN" ]; then
selected_template="custom"
max_confidence=0
fi
# Validate template file exists
if [ "$selected_template" != "custom" ]; then
local template_file="${TEMPLATE_DIR}/${selected_template}.md"
if [ ! -f "$template_file" ]; then
selected_template="custom"
max_confidence=0
fi
fi
# Output: template_name confidence
echo "$selected_template $max_confidence"
}
# Determine scenario based on confidence level
get_scenario() {
local confidence=$1
if [ "$confidence" -ge 70 ]; then
echo "high"
elif [ "$confidence" -ge 60 ]; then
echo "borderline"
else
echo "weak"
fi
}
# Generate instructions based on scenario
generate_instructions() {
# Run classification
local result=$(classify_task "$USER_TASK")
local template_name=$(echo "$result" | cut -d' ' -f1)
local confidence=$(echo "$result" | cut -d' ' -f2)
# Sanitize for output
local sanitized_task=$(sanitize_input "$USER_TASK")
# Determine scenario
local scenario=$(get_scenario "$confidence")
# Generate comparison note if suggested template differs
local comparison_note=""
if [ -n "$SUGGESTED_TEMPLATE" ] && [ "$template_name" != "$SUGGESTED_TEMPLATE" ]; then
comparison_note="
Note: Classification selected '$template_name' instead of suggested '$SUGGESTED_TEMPLATE'"
elif [ -n "$SUGGESTED_TEMPLATE" ]; then
comparison_note="
Note: Classification agrees with suggested template '$SUGGESTED_TEMPLATE'"
fi
case "$scenario" in
high)
# High confidence (70%+): Accept classification directly
cat <<EOF
CLASSIFICATION RESULT:
Template: $template_name
Confidence: $confidence%$comparison_note
DECISION: High confidence classification - accept directly.
Output the following XML immediately:
\`\`\`xml
<template_selector_result>
<selected_template>$template_name</selected_template>
<confidence>$confidence</confidence>
<reasoning>Keyword-based classification has high confidence ($confidence%) based on pattern matching.</reasoning>
</template_selector_result>
\`\`\`
EOF
;;
borderline)
# Borderline confidence (60-69%): Validate the classification
cat <<EOF
CLASSIFICATION RESULT:
Template: $template_name
Confidence: $confidence% (borderline)$comparison_note
TASK: Validate if this classification is appropriate.
User task: $sanitized_task
Classified template: $template_name
Process:
1. Read the classified template file to understand its purpose:
Read: ~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/templates/$template_name.md
2. Evaluate if the user task matches the template's use cases
3. Make your decision:
- If it's a good match: Confirm the classification
- If it's a poor match: Briefly evaluate 1-2 other likely templates and select the best one
Output your decision in this XML format:
\`\`\`xml
<template_selector_result>
<selected_template>template-name</selected_template>
<confidence>final-confidence-percentage</confidence>
<reasoning>1-2 sentence explanation</reasoning>
</template_selector_result>
\`\`\`
EOF
;;
weak)
# Weak/no confidence (<60%): Full evaluation
cat <<EOF
CLASSIFICATION RESULT:
Template: $template_name
Confidence: $confidence% (low)$comparison_note
TASK: Evaluate the task against all templates and select the best match.
User task: $sanitized_task
Initial classification: $template_name (confidence: $confidence%)
Available templates:
1. code-refactoring - Modify code, fix bugs, add features, refactor
2. code-review - Security audits, quality analysis, code feedback
3. test-generation - Create tests, test suites, edge cases
4. documentation-generator - API docs, READMEs, docstrings, guides
5. data-extraction - Extract/parse data from logs, JSON, HTML, text
6. code-comparison - Compare code, check equivalence, classify similarities
7. custom - Novel tasks that don't fit standard templates
Process:
1. Consider the task type (development, analysis, generation, comparison, extraction)
2. Read relevant template files (1-3 templates that might match) to understand their scope
3. Select the best matching template or "custom" if none fit well
Output your decision in this XML format:
\`\`\`xml
<template_selector_result>
<selected_template>template-name</selected_template>
<confidence>final-confidence-percentage</confidence>
<reasoning>1-2 sentence explanation</reasoning>
</template_selector_result>
\`\`\`
EOF
;;
esac
}
# Main function
main() {
# Check for command-line argument
if [ $# -eq 0 ]; then
echo "Error: No input provided. Usage: $0 '<xml-input>'" >&2
exit 1
fi
# Read and parse XML input from first argument
read_xml_input "$1"
# Generate and output instructions
generate_instructions
}
# Run main function
main "$@"

View File

@@ -0,0 +1,28 @@
---
name: template-executor
description: Generic execution agent that loads template-specific skills and executes optimized prompts
allowed-tools: [Glob, Grep, Read, Edit, Write, Bash, TodoWrite, AskUserQuestion, Skill, Read(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/skills/**), Bash(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/agents/scripts/template-executor-handler.sh:*)]
model: sonnet
---
Load skill and execute the optimized prompt.
## Process
1. **Call handler** with your XML input:
```bash
~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/agents/scripts/template-executor-handler.sh '<your-input-xml>'
```
2. **Load skill** (if not "none"): `Skill tool: <skill-name>`
3. **Execute** the optimized prompt using specialized tools (Read/Edit/Write, not bash for files). Track progress with TodoWrite.
4. **Return XML**:
```xml
<template_executor_result>
<status>completed|failed|partial</status>
<summary>Brief summary of what was accomplished</summary>
<details>Detailed results, changes made, files modified, etc.</details>
</template_executor_result>
```

View File

@@ -0,0 +1,29 @@
---
name: template-selector
description: Lightweight template classifier for borderline and uncertain cases
allowed-tools: [Read(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/templates/**), Bash(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/agents/scripts/template-selector-handler.sh:*)]
model: haiku
---
Classify user request to select the best template.
## Process
1. **Call handler** with your XML input:
```bash
~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/agents/scripts/template-selector-handler.sh '<your-input-xml>'
```
2. **Follow handler instructions** based on confidence:
- ≥70%: Accept classification
- 60-69%: Read template to validate
- <60%: Read 1-3 templates to decide
3. **Return XML**:
```xml
<template_selector_result>
<selected_template>template-name</selected_template>
<confidence>confidence-percentage</confidence>
<reasoning>1-2 sentence explanation</reasoning>
</template_selector_result>
```

53
commands/prompt.md Normal file
View File

@@ -0,0 +1,53 @@
---
name: prompt
description: Optimize a prompt using templates and execute with specialized skills
argument-hint: [--template=<name>] [--code|--refactor|--review|--test|--docs|--documentation|--extract|--compare|--comparison|--custom] [--plan] [--return-only] <task description>
allowed-tools: [Task, TodoWrite, Bash(~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/commands/scripts/prompt-handler.sh:*)]
---
Execute tasks using optimized prompts with domain-specific skills.
<task>{$TASK_DESCRIPTION}</task>
## Process
1. **Call handler** with the task:
```bash
~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/commands/scripts/prompt-handler.sh "{$TASK_DESCRIPTION}"
```
2. **Parse XML response** from handler:
- Extract `<todos>` and call TodoWrite with the todo items
- Extract `<task_tool>` for subagent parameters
- Check `<next_action>` and `<final_action>` for flow control
3. **Update TodoWrite** from `<todos>`:
Parse each `<todo status="..." content="..." activeForm="..."/>` and call TodoWrite with the array.
**Example transformation:**
```xml
<todos>
<todo status="in_progress" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="pending" content="Execute task" activeForm="Executing task"/>
</todos>
```
Becomes TodoWrite input:
```json
[
{"status": "in_progress", "content": "Optimize prompt", "activeForm": "Optimizing prompt"},
{"status": "pending", "content": "Execute task", "activeForm": "Executing task"}
]
```
4. **Execute based on `<next_action>`:**
- If spawning subagent: Use Task tool with `<subagent_type>`, `<description>`, `<prompt>`
- Pass subagent XML results back to handler via `<next_handler_call>`
- If `<final_action>` present: execute that action instead of looping
5. **Handle `<final_action>` values:**
- `present_results`: Display the task execution results to the user
- `present_optimized_prompt`: Display the optimized prompt to the user (for --return-only mode)
6. **Loop until `<next_action>done</next_action>`**
7. **Present results** to user when complete.

View File

@@ -0,0 +1,542 @@
#!/usr/bin/env bash
# Purpose: State machine for /prompt command orchestration
# Inputs: Structured XML via stdin OR command-line args for initial state
# Outputs: Next instruction for /prompt command
# Architecture: State machine that guides /prompt through:
# - Without --plan: optimizer → executor → done
# - With --plan: optimizer → Plan agent → executor → done
set -euo pipefail
# Source common functions
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
. "$SCRIPT_DIR/../../scripts/common.sh"
# Detect current state from input
detect_state() {
local input="$1"
if echo "$input" | grep -q "<template_selector_result>"; then
echo "post_template_selector"
elif echo "$input" | grep -q "<prompt_optimizer_result>"; then
echo "post_optimizer"
elif echo "$input" | grep -q "<plan_result>"; then
echo "post_plan"
elif echo "$input" | grep -q "<template_executor_result>"; then
echo "final"
else
# Initial state (command-line args or initial XML)
echo "initial"
fi
}
# Parse flags from initial task description
# Sets global variables: RETURN_ONLY, PLAN, TEMPLATE, TEMPLATE_FLAG_SEEN, TASK_DESCRIPTION
parse_initial_flags() {
local raw_input="$1"
# Set global variables for use by handler functions
RETURN_ONLY=false
PLAN=false
TEMPLATE=""
TEMPLATE_FLAG_SEEN=false
# Parse all flags from the beginning of the input
while true; do
case "$raw_input" in
--template=*)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="${raw_input#--template=}"
TEMPLATE="${TEMPLATE%% *}"
raw_input="${raw_input#--template=$TEMPLATE}"
raw_input="${raw_input# }"
TEMPLATE_FLAG_SEEN=true
;;
--code\ *|--code)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
echo "Already set: $TEMPLATE" >&2
echo "Cannot use multiple template flags in one command." >&2
exit 1
fi
TEMPLATE="code-refactoring"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--code}"
raw_input="${raw_input# }"
;;
--refactor\ *|--refactor)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="code-refactoring"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--refactor}"
raw_input="${raw_input# }"
;;
--review\ *|--review)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="code-review"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--review}"
raw_input="${raw_input# }"
;;
--test\ *|--test)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="test-generation"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--test}"
raw_input="${raw_input# }"
;;
--docs\ *|--docs)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="documentation-generator"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--docs}"
raw_input="${raw_input# }"
;;
--documentation\ *|--documentation)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="documentation-generator"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--documentation}"
raw_input="${raw_input# }"
;;
--extract\ *|--extract)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="data-extraction"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--extract}"
raw_input="${raw_input# }"
;;
--compare\ *|--compare)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="code-comparison"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--compare}"
raw_input="${raw_input# }"
;;
--comparison\ *|--comparison)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="code-comparison"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--comparison}"
raw_input="${raw_input# }"
;;
--custom\ *|--custom)
if [ "$TEMPLATE_FLAG_SEEN" = true ]; then
echo "Error: Multiple template flags specified." >&2
exit 1
fi
TEMPLATE="custom"
TEMPLATE_FLAG_SEEN=true
raw_input="${raw_input#--custom}"
raw_input="${raw_input# }"
;;
--return-only\ *|--return-only)
RETURN_ONLY=true
raw_input="${raw_input#--return-only}"
raw_input="${raw_input# }"
;;
--plan\ *|--plan)
PLAN=true
raw_input="${raw_input#--plan}"
raw_input="${raw_input# }"
;;
*)
# No more flags, break out of loop
break
;;
esac
done
# Validate template name if provided
if [ -n "$TEMPLATE" ]; then
case "$TEMPLATE" in
code-refactoring|code-review|test-generation|documentation-generator|data-extraction|code-comparison|custom)
# Valid template
;;
*)
echo "Error: Invalid template name: $TEMPLATE" >&2
exit 1
;;
esac
fi
# Normalize whitespace and set global TASK_DESCRIPTION
raw_input=$(echo "$raw_input" | sed -e 's/^[[:space:]]*//' -e 's/[[:space:]]*$//' -e 's/[[:space:]][[:space:]]*/ /g')
TASK_DESCRIPTION="$raw_input"
}
# Handle initial state - spawn template-selector or prompt-optimizer
handle_initial_state() {
parse_initial_flags "$1"
# Sanitize for shell safety, then escape for CDATA safety
local sanitized_task=$(escape_cdata "$(sanitize_input "$TASK_DESCRIPTION")")
# If no template specified, spawn template-selector first
if [ -z "$TEMPLATE" ]; then
cat <<EOF
<handler_response>
<state>initial</state>
<next_action>spawn_template_selector</next_action>
<todos>
<todo status="in_progress" content="Determine template" activeForm="Determining template"/>
<todo status="pending" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="pending" content="Execute task" activeForm="Executing task"/>
<todo status="pending" content="Present results" activeForm="Presenting results"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:template-selector</subagent_type>
<description>Select template for task</description>
<prompt><![CDATA[Select the best template for this task:
<template_selector_request>
<user_task>$sanitized_task</user_task>
</template_selector_request>
Follow your instructions to classify the task and return the result in XML format.]]></prompt>
</task_tool>
<next_handler_call><![CDATA[~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/commands/scripts/prompt-handler.sh '<template_selector_result>...(full XML output)...</template_selector_result>
<original_task>$sanitized_task</original_task>
<plan_flag>$PLAN</plan_flag>
<return_only_flag>$RETURN_ONLY</return_only_flag>']]></next_handler_call>
</handler_response>
EOF
return
fi
# Template already specified, proceed to optimizer
# Determine execution mode
local execution_mode="direct"
if [ "$PLAN" = true ]; then
execution_mode="plan"
fi
# Build template XML
local template_xml="<template>$TEMPLATE</template>"
# Check if return-only mode
if [ "$RETURN_ONLY" = true ]; then
cat <<EOF
<handler_response>
<state>initial</state>
<next_action>spawn_optimizer_return_only</next_action>
<todos>
<todo status="in_progress" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="pending" content="Present optimized prompt" activeForm="Presenting optimized prompt"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:prompt-optimizer</subagent_type>
<description>Create optimized prompt</description>
<prompt><![CDATA[Process this request and return an optimized prompt:
<prompt_optimizer_request>
<user_task>$sanitized_task</user_task>$template_xml
<execution_mode>$execution_mode</execution_mode>
</prompt_optimizer_request>
Follow your instructions to process the template and return the result in XML format.]]></prompt>
</task_tool>
<final_action>present_optimized_prompt</final_action>
</handler_response>
EOF
else
cat <<EOF
<handler_response>
<state>initial</state>
<next_action>spawn_optimizer</next_action>
<todos>
<todo status="in_progress" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="pending" content="Execute task" activeForm="Executing task"/>
<todo status="pending" content="Present results" activeForm="Presenting results"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:prompt-optimizer</subagent_type>
<description>Create optimized prompt</description>
<prompt><![CDATA[Process this request and return an optimized prompt:
<prompt_optimizer_request>
<user_task>$sanitized_task</user_task>$template_xml
<execution_mode>$execution_mode</execution_mode>
</prompt_optimizer_request>
Follow your instructions to process the template and return the result in XML format.]]></prompt>
</task_tool>
<next_handler_call><![CDATA[~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/commands/scripts/prompt-handler.sh '<prompt_optimizer_result>...(full XML output)...</prompt_optimizer_result>']]></next_handler_call>
</handler_response>
EOF
fi
}
# Handle post-template-selector state - spawn prompt-optimizer with selected template
handle_post_template_selector_state() {
local selector_output="$1"
# Extract values from XML using sed (BSD-compatible)
local selected_template=$(echo "$selector_output" | sed -n 's/.*<selected_template>\(.*\)<\/selected_template>.*/\1/p')
local original_task=$(echo "$selector_output" | sed -n 's/.*<original_task>\(.*\)<\/original_task>.*/\1/p')
local plan_flag=$(echo "$selector_output" | sed -n 's/.*<plan_flag>\(.*\)<\/plan_flag>.*/\1/p')
local return_only_flag=$(echo "$selector_output" | sed -n 's/.*<return_only_flag>\(.*\)<\/return_only_flag>.*/\1/p')
# Sanitize for shell safety, then escape for CDATA safety
local sanitized_task=$(escape_cdata "$(sanitize_input "$original_task")")
# Determine execution mode
local execution_mode="direct"
if [ "$plan_flag" = "true" ]; then
execution_mode="plan"
fi
# Build template XML
local template_xml="<template>$selected_template</template>"
# Check if return-only mode
if [ "$return_only_flag" = "true" ]; then
cat <<EOF
<handler_response>
<state>post_template_selector</state>
<next_action>spawn_optimizer_return_only</next_action>
<todos>
<todo status="completed" content="Determine template" activeForm="Determining template"/>
<todo status="in_progress" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="pending" content="Present optimized prompt" activeForm="Presenting optimized prompt"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:prompt-optimizer</subagent_type>
<description>Create optimized prompt</description>
<prompt><![CDATA[Process this request and return an optimized prompt:
<prompt_optimizer_request>
<user_task>$sanitized_task</user_task>$template_xml
<execution_mode>$execution_mode</execution_mode>
</prompt_optimizer_request>
Follow your instructions to process the template and return the result in XML format.]]></prompt>
</task_tool>
<final_action>present_optimized_prompt</final_action>
</handler_response>
EOF
else
cat <<EOF
<handler_response>
<state>post_template_selector</state>
<next_action>spawn_optimizer</next_action>
<todos>
<todo status="completed" content="Determine template" activeForm="Determining template"/>
<todo status="in_progress" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="pending" content="Execute task" activeForm="Executing task"/>
<todo status="pending" content="Present results" activeForm="Presenting results"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:prompt-optimizer</subagent_type>
<description>Create optimized prompt</description>
<prompt><![CDATA[Process this request and return an optimized prompt:
<prompt_optimizer_request>
<user_task>$sanitized_task</user_task>$template_xml
<execution_mode>$execution_mode</execution_mode>
</prompt_optimizer_request>
Follow your instructions to process the template and return the result in XML format.]]></prompt>
</task_tool>
<next_handler_call><![CDATA[~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/commands/scripts/prompt-handler.sh '<prompt_optimizer_result>...(full XML output)...</prompt_optimizer_result>']]></next_handler_call>
</handler_response>
EOF
fi
}
# Handle post-optimizer state - spawn Plan or template-executor
handle_post_optimizer_state() {
local optimizer_output="$1"
# Extract values from XML using sed (BSD-compatible)
local skill=$(echo "$optimizer_output" | sed -n 's/.*<skill>\(.*\)<\/skill>.*/\1/p')
local execution_mode=$(echo "$optimizer_output" | sed -n 's/.*<execution_mode>\(.*\)<\/execution_mode>.*/\1/p')
local optimized_prompt=$(echo "$optimizer_output" | sed -n 's/.*<optimized_prompt>\(.*\)<\/optimized_prompt>.*/\1/p')
# Sanitize for shell safety, then escape for CDATA safety
local sanitized_skill=$(escape_cdata "$(sanitize_input "$skill")")
local sanitized_prompt=$(escape_cdata "$optimized_prompt")
if [ "$execution_mode" = "plan" ]; then
cat <<EOF
<handler_response>
<state>post_optimizer</state>
<next_action>spawn_plan_agent</next_action>
<todos>
<todo status="completed" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="in_progress" content="Create plan" activeForm="Creating plan"/>
<todo status="pending" content="Execute task" activeForm="Executing task"/>
<todo status="pending" content="Present results" activeForm="Presenting results"/>
</todos>
<task_tool>
<subagent_type>Plan</subagent_type>
<description>Create execution plan</description>
<prompt><![CDATA[SKILL_TO_LOAD: $sanitized_skill
$sanitized_prompt]]></prompt>
</task_tool>
<next_handler_call><![CDATA[~/.claude/plugins/marketplaces/claude-experiments/meta-prompt/commands/scripts/prompt-handler.sh '<plan_result>
<skill>$sanitized_skill</skill>
<optimized_prompt>
$sanitized_prompt
</optimized_prompt>
</plan_result>']]></next_handler_call>
</handler_response>
EOF
else
cat <<EOF
<handler_response>
<state>post_optimizer</state>
<next_action>spawn_template_executor</next_action>
<todos>
<todo status="completed" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="in_progress" content="Execute task" activeForm="Executing task"/>
<todo status="pending" content="Present results" activeForm="Presenting results"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:template-executor</subagent_type>
<description>Execute task</description>
<prompt><![CDATA[SKILL_TO_LOAD: $sanitized_skill
<template_executor_request>
<skill>$sanitized_skill</skill>
<optimized_prompt>
$sanitized_prompt
</optimized_prompt>
</template_executor_request>
Follow your instructions to load the skill (if not 'none') and execute the task.]]></prompt>
</task_tool>
<final_action>present_results</final_action>
</handler_response>
EOF
fi
}
# Handle post-plan state - spawn template-executor with the plan
handle_post_plan_state() {
local plan_output="$1"
# Extract values from XML using sed (BSD-compatible)
local skill=$(echo "$plan_output" | sed -n 's/.*<skill>\(.*\)<\/skill>.*/\1/p')
# Extract optimized_prompt (multiline content)
local optimized_prompt=$(echo "$plan_output" | sed -n '/<optimized_prompt>/,/<\/optimized_prompt>/p' | sed '1d;$d')
# Sanitize for shell safety, then escape for CDATA safety
local sanitized_skill=$(escape_cdata "$(sanitize_input "$skill")")
local sanitized_prompt=$(escape_cdata "$optimized_prompt")
cat <<EOF
<handler_response>
<state>post_plan</state>
<next_action>spawn_template_executor</next_action>
<todos>
<todo status="completed" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="completed" content="Create plan" activeForm="Creating plan"/>
<todo status="in_progress" content="Execute task" activeForm="Executing task"/>
<todo status="pending" content="Present results" activeForm="Presenting results"/>
</todos>
<task_tool>
<subagent_type>meta-prompt:template-executor</subagent_type>
<description>Execute task</description>
<prompt><![CDATA[SKILL_TO_LOAD: $sanitized_skill
<template_executor_request>
<skill>$sanitized_skill</skill>
<optimized_prompt>
$sanitized_prompt
</optimized_prompt>
</template_executor_request>
Follow your instructions to load the skill (if not 'none') and execute the task.]]></prompt>
</task_tool>
<final_action>present_results</final_action>
</handler_response>
EOF
}
# Handle final state - just present results
handle_final_state() {
cat <<EOF
<handler_response>
<state>final</state>
<next_action>done</next_action>
<todos>
<todo status="completed" content="Optimize prompt" activeForm="Optimizing prompt"/>
<todo status="completed" content="Execute task" activeForm="Executing task"/>
<todo status="in_progress" content="Present results" activeForm="Presenting results"/>
</todos>
<final_action>present_results</final_action>
</handler_response>
EOF
}
# Main state machine logic
main() {
# Check if input is provided as command-line arg
if [ $# -gt 0 ]; then
# Use command-line args
INPUT="$1"
# Detect state from input
STATE=$(detect_state "$INPUT")
else
# No input provided
echo "Error: No input provided. Usage: $0 '<task description>'" >&2
echo " Or: $0 '<xml>'" >&2
exit 1
fi
# Execute state handler
case "$STATE" in
initial)
handle_initial_state "$INPUT"
;;
post_template_selector)
handle_post_template_selector_state "$INPUT"
;;
post_optimizer)
handle_post_optimizer_state "$INPUT"
;;
post_plan)
handle_post_plan_state "$INPUT"
;;
final)
handle_final_state
;;
*)
echo "Error: Unknown state: $STATE" >&2
exit 1
;;
esac
}
# Run main function
main "$@"

View File

@@ -0,0 +1,141 @@
#!/usr/bin/env bash
# Purpose: Verify meta-prompt plugin installation
# Usage: ./verify-installation.sh
# Exits: 0 if installation is valid, 1 if issues found
set -euo pipefail
# ANSI colors (only use if terminal supports them)
if [ -t 1 ] && command -v tput >/dev/null 2>&1 && [ "$(tput colors 2>/dev/null || echo 0)" -ge 8 ]; then
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
NC='\033[0m'
else
GREEN=''
RED=''
YELLOW=''
NC=''
fi
# Setup: Set CLAUDE_PLUGIN_ROOT if not already set
if [ -z "${CLAUDE_PLUGIN_ROOT:-}" ]; then
# Try to derive from script location (commands/scripts/ -> 2 levels up)
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
if [ -d "$SCRIPT_DIR/../../templates" ]; then
CLAUDE_PLUGIN_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)"
else
# Fallback to hardcoded path for standard installation
CLAUDE_PLUGIN_ROOT="$HOME/.claude/plugins/marketplaces/claude-experiments/meta-prompt"
fi
fi
echo -e "${YELLOW}Meta-Prompt Installation Verification${NC}"
echo "========================================"
echo ""
echo "Plugin root: $CLAUDE_PLUGIN_ROOT"
echo ""
# Track issues
ISSUES_FOUND=0
# Check if plugin root exists
if [ ! -d "$CLAUDE_PLUGIN_ROOT" ]; then
echo -e "${RED}✗ Error: Plugin directory not found at: $CLAUDE_PLUGIN_ROOT${NC}"
echo ""
echo "Expected installation locations:"
echo " - Standard: ~/.claude/plugins/marketplaces/claude-experiments/meta-prompt"
echo " - Development: <repo-clone>/meta-prompt"
echo ""
exit 1
fi
echo -e "${GREEN}✓ Plugin directory found${NC}"
# Check critical directories
DIRS=(
"templates"
"commands"
"commands/scripts"
"agents"
"guides"
"tests"
)
for dir in "${DIRS[@]}"; do
if [ -d "$CLAUDE_PLUGIN_ROOT/$dir" ]; then
echo -e "${GREEN}${NC} Directory exists: $dir"
else
echo -e "${RED}${NC} Missing directory: $dir"
ISSUES_FOUND=$((ISSUES_FOUND + 1))
fi
done
echo ""
# Check critical scripts
SCRIPTS=(
"commands/scripts/prompt-handler.sh"
"scripts/common.sh"
"agents/scripts/prompt-optimizer-handler.sh"
"agents/scripts/template-selector-handler.sh"
"agents/scripts/template-executor-handler.sh"
)
for script in "${SCRIPTS[@]}"; do
if [ -f "$CLAUDE_PLUGIN_ROOT/$script" ]; then
if [ -x "$CLAUDE_PLUGIN_ROOT/$script" ]; then
echo -e "${GREEN}${NC} Script exists and is executable: $script"
else
echo -e "${YELLOW}${NC} Script exists but not executable: $script"
echo " Run: chmod +x $CLAUDE_PLUGIN_ROOT/$script"
ISSUES_FOUND=$((ISSUES_FOUND + 1))
fi
else
echo -e "${RED}${NC} Missing script: $script"
ISSUES_FOUND=$((ISSUES_FOUND + 1))
fi
done
echo ""
# Check templates (should have 6 templates + custom)
EXPECTED_TEMPLATES=(
"code-refactoring.md"
"code-review.md"
"test-generation.md"
"documentation-generator.md"
"data-extraction.md"
"code-comparison.md"
"custom.md"
)
for template in "${EXPECTED_TEMPLATES[@]}"; do
if [ -f "$CLAUDE_PLUGIN_ROOT/templates/$template" ]; then
echo -e "${GREEN}${NC} Template exists: $template"
else
echo -e "${RED}${NC} Missing template: $template"
ISSUES_FOUND=$((ISSUES_FOUND + 1))
fi
done
echo ""
# Summary
echo "========================================"
if [ $ISSUES_FOUND -eq 0 ]; then
echo -e "${GREEN}✓ Installation verified successfully!${NC}"
echo ""
echo "You can use the meta-prompt plugin with:"
echo " /prompt <task description>"
echo " /create-prompt <task description>"
exit 0
else
echo -e "${RED}✗ Found $ISSUES_FOUND issue(s) with installation${NC}"
echo ""
echo "Troubleshooting:"
echo " 1. Ensure the plugin is installed via: /plugin install jtsylve/claude-experiments"
echo " 2. For development, run: chmod +x commands/scripts/*.sh tests/*.sh"
echo " 3. See docs/infrastructure.md for detailed setup instructions"
exit 1
fi

101
plugin.lock.json Normal file
View File

@@ -0,0 +1,101 @@
{
"$schema": "internal://schemas/plugin.lock.v1.json",
"pluginId": "gh:jtsylve/claude-experiments:meta-prompt",
"normalized": {
"repo": null,
"ref": "refs/tags/v20251128.0",
"commit": "a650044a1a98c06805599529a82d814fa6700526",
"treeHash": "5a9ffbc3e540a57b06e3dcc672a04d052be53d36b38b7de1354cd1ff58fbb545",
"generatedAt": "2025-11-28T10:19:20.771495Z",
"toolVersion": "publish_plugins.py@0.2.0"
},
"origin": {
"remote": "git@github.com:zhongweili/42plugin-data.git",
"branch": "master",
"commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390",
"repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data"
},
"manifest": {
"name": "meta-prompt",
"description": "State machine-based optimization infrastructure for token reduction through deterministic preprocessing. Features zero-token orchestration, hybrid classification, and specialized LLM agents for prompt optimization and task execution.",
"version": "1.0.0"
},
"content": {
"files": [
{
"path": "README.md",
"sha256": "8d4796a60568b1f4ce115d7de331a4635a8fac5af4fd74ea0242b5b545e2b659"
},
{
"path": "agents/prompt-optimizer.md",
"sha256": "993057a3488ad0f852511a36872f64aaab5161b0621820132b2675a13a7a224e"
},
{
"path": "agents/template-executor.md",
"sha256": "cec0f8f3b13e303570904655ba3127487f65cf6fb6b05934d4810659ae207271"
},
{
"path": "agents/template-selector.md",
"sha256": "2ccec893ad0c4243305f8809a84ae39f0f5f660fbcabda4da319b160a917ca06"
},
{
"path": "agents/scripts/template-selector-handler.sh",
"sha256": "413c49b6275af4f64b946143692150aa238864ee00dc48b4ab51484e4e7b157f"
},
{
"path": "agents/scripts/template-executor-handler.sh",
"sha256": "e187904524ee45d30e5f47a3cc4d88da1d592734e5299c8331069ba38cc2898c"
},
{
"path": "agents/scripts/prompt-optimizer-handler.sh",
"sha256": "fde2f0ceae76c356c069ae74343e42431708dc646856c952d5dee02140cf702e"
},
{
"path": ".claude-plugin/plugin.json",
"sha256": "c3218476e4fc6393cb266067c9d5e6a3933531c4b18f0decb2f98008e7f4a6b5"
},
{
"path": "commands/prompt.md",
"sha256": "e72ec95a70106a5e3ed625aeaaecc2022b96dddad7931a7eaf6622186aa56189"
},
{
"path": "commands/scripts/prompt-handler.sh",
"sha256": "1c702d4494ad609b152d3ddf8a7d72d23b01005400188dcc642a7d898bde3fc0"
},
{
"path": "commands/scripts/verify-installation.sh",
"sha256": "48b69b6d36c302eb41e5b31651c25791f635f12f31572f99ad077abdecd2ccf0"
},
{
"path": "skills/code-review/SKILL.md",
"sha256": "796fc630d52e48fe58775acc37151f2aaf313e88a5b56c3e6caea4e52fec90b6"
},
{
"path": "skills/documentation-generator/SKILL.md",
"sha256": "311e33aac9d36a27efcbb049abe1f2c1dcb34c9879c6713103bb00c4c08d499c"
},
{
"path": "skills/code-comparison/SKILL.md",
"sha256": "7c05340c2c726045e8a4aee6134b80ec2591c2f0b76d9c42507fd482ca58923e"
},
{
"path": "skills/code-refactoring/SKILL.md",
"sha256": "4b460dcfec3470dd5ef28acc3e35e1e03aee3b192a58acfc4dbcf10c54c767ec"
},
{
"path": "skills/data-extraction/SKILL.md",
"sha256": "75dbc8143c3b7d9be0f532ce79f99198079154ccfcf46891d2f4afb407c60ffe"
},
{
"path": "skills/test-generation/SKILL.md",
"sha256": "bcec5597275cb97e4e1372333507c842796266bda004aff91169169063cd4684"
}
],
"dirSha256": "5a9ffbc3e540a57b06e3dcc672a04d052be53d36b38b7de1354cd1ff58fbb545"
},
"security": {
"scannedAt": null,
"scannerVersion": null,
"flags": []
}
}

View File

@@ -0,0 +1,56 @@
# Code Comparison
Compare code implementations for equivalence, similarity, or differences with accurate classification.
## Comparison Dimensions
| Dimension | Question |
|-----------|----------|
| **Behavioral** | Same outputs for same inputs? Same side effects? |
| **Semantic** | Same intent/purpose? Same business logic? |
| **Syntactic** | Similar names, structure, formatting? |
| **Algorithmic** | Same approach? Same complexity (Big O)? |
| **Style** | Functional vs imperative? Recursive vs iterative? |
## Common Scenarios
| Scenario | Focus |
|----------|-------|
| Refactoring | Behavioral equivalence (must match) |
| Bug fix | Specific case differs, normal matches |
| API compat | Signature, returns, errors, side effects |
| Plagiarism | Structure, naming, logic patterns |
## Output Format
Start with **[YES]** or **[NO]** immediately.
Then provide justification with specific examples from both items.
## Analysis Checklist
- [ ] Inputs (same params, types?)
- [ ] Outputs (same returns?)
- [ ] Side effects (same state changes?)
- [ ] Error handling (same exceptions?)
- [ ] Edge cases (null, empty, boundary?)
- [ ] Performance (same complexity?)
## Example
```
[YES] Behaviorally equivalent
Both functions:
1. Return same results for all inputs
2. Handle null by returning empty array
3. Use same filtering logic
The refactoring improves readability (modern array methods) without changing behavior.
```
## Pitfalls
- Don't stop at surface differences (naming != different behavior)
- Check edge cases (factorial(-1) may differ)
- Consider context (Promise vs callback may be equivalent in modern Node)

View File

@@ -0,0 +1,62 @@
# Code Refactoring
Modify code with clean, secure, maintainable changes that precisely meet requirements.
## Workflow
1. **Discover:** Glob for files, Grep for patterns
2. **Read:** Always read before modifying
3. **Modify:** Edit existing (prefer over Write)
4. **Verify:** Run tests
## Rules
| Rule | Details |
|------|---------|
| Read first | Never modify unread files |
| Edit > Write | Use Edit for existing, Write only for new |
| Delete completely | No `_unused` prefixes or `// removed` comments |
| Match style | Follow existing conventions exactly |
| Minimal changes | Only what's requested |
## Security Checklist
**Prevent:**
- Command injection → Use arrays, not string interpolation: `exec('cmd', [args])`
- XSS → Use `textContent`, not `innerHTML`
- SQL injection → Use parameterized queries
- Path traversal → Validate with `path.basename()`
## Tool Usage
```
Glob: pattern: "**/*.js" # Find files
Grep: pattern: "func", output_mode: "files_with_matches" # Search
Read: file_path: "/path/file.js" # Read before edit
Edit: file_path, old_string, new_string # Modify
```
Parallelize independent Read calls. Chain sequentially: Read → Edit → Bash (test).
## Quality
- Three similar lines > premature abstraction
- Meaningful names, focused functions
- Comments only where logic isn't obvious
- Refactor only when explicitly requested
## Example
```javascript
// Before: Bug - off-by-one error
function getLastItem(arr) {
return arr[arr.length] // Wrong: returns undefined
}
// After: Fix
function getLastItem(arr) {
return arr[arr.length - 1]
}
```
Change is minimal and targeted - only fix what's requested.

View File

@@ -0,0 +1,58 @@
# Code Review
Provide constructive, actionable feedback on security, correctness, performance, and maintainability.
## Review Dimensions
| Dimension | Key Checks |
|-----------|------------|
| **Security** | Injection (SQL, XSS, command), auth gaps, data exposure, CORS, SSRF |
| **Correctness** | Logic errors, edge cases, race conditions, off-by-one |
| **Performance** | O(n²) loops, N+1 queries, memory leaks, missing indexes |
| **Readability** | Naming, nesting depth, magic numbers, DRY |
| **Error Handling** | Silent swallowing, missing cleanup, unhelpful messages |
| **Testability** | Tight coupling, hidden dependencies, side effects |
## Severity Levels
| Level | Criteria | Action |
|-------|----------|--------|
| 🔴 CRITICAL | Security vulns, data loss, crashes | Block merge |
| 🟠 HIGH | Bugs, performance issues | Fix before merge |
| 🟡 MEDIUM | Code smells, refactoring | Fix soon |
| 🟢 LOW | Style, alternatives | Optional |
## Output Format
```markdown
## Summary
[2-3 sentences: quality, strengths, concerns]
## 🔴 Critical Issues
**Location:** file.js:42
**Issue:** SQL injection
**Impact:** Data breach
**Fix:** Use parameterized query
\`\`\`js
// Before
db.query(`SELECT * FROM users WHERE id = ${id}`)
// After
db.query('SELECT * FROM users WHERE id = ?', [id])
\`\`\`
## 🟠 High Priority
[Same format]
## 🟡/🟢 Other
[Same format]
## ✅ Positive
[Good patterns observed]
```
## Principles
- Specific locations, not vague criticism
- Explain impact, not just what's wrong
- Code examples for fixes
- Balance criticism with recognition

View File

@@ -0,0 +1,51 @@
# Data Extraction
Extract specific information from unstructured/semi-structured data with completeness and accuracy.
## Common Patterns
| Type | Pattern | Validation |
|------|---------|------------|
| Email | `user@domain.ext` | Has `@` and `.` after @ |
| URL | `http(s)://domain...` | Valid protocol and domain |
| Date | ISO, US, EU, timestamp | Valid ranges (month 1-12) |
| Phone | Various formats | 7-15 digits |
| IP | IPv4: `x.x.x.x`, IPv6 | Octets 0-255 |
| Key-Value | `key=value`, `key: value` | Handle quoted/nested |
## Process
1. **Analyze:** Format, delimiters, variations, headers to skip
2. **Extract:** Match all instances, capture context, handle partial matches
3. **Clean:** Trim, normalize (dates to ISO, phones to digits), validate
4. **Format:** Consistent fields, proper escaping, sort/dedupe if needed
## Output Formats
**JSON:** `{"results": [...], "summary": {"total": N, "unique": N}}`
**CSV:** Headers + rows
**Markdown:** Table with headers
**Plain:** Bullet list
## Principles
- **Complete:** Extract ALL matches, don't stop early
- **Accurate:** Preserve exact values, maintain case
- **Handle edge cases:** Missing → null, malformed → flag, duplicates → note
## Output Structure
```
[Extracted data]
## Summary
- Total: X
- Unique: Y
- Issues: Z
## Notes
- Line 42: Partial match "user@" (missing domain)
```

View File

@@ -0,0 +1,64 @@
# Documentation Generator
Create clear, comprehensive documentation matched to audience needs.
## Documentation Types
| Type | Structure |
|------|-----------|
| **API Reference** | Overview → Auth → Endpoints (params, returns, errors) → Examples |
| **README** | Description → Install → Quick Start → Usage → Config |
| **Docstrings** | Summary → Params (type, desc) → Returns → Exceptions → Example |
| **User Guide** | Intro → Prerequisites → Steps → Troubleshooting |
| **Tech Spec** | Overview → Architecture → Data Models → APIs → Security |
## Writing Principles
- **Active voice:** "Returns user" not "User is returned"
- **Examples:** Concrete, runnable, with expected output
- **Complete:** All params, returns, errors documented
- **Consistent:** Same terminology throughout
## Audience Adaptation
| Audience | Focus |
|----------|-------|
| External devs | Complete setup, all public APIs, integration patterns |
| Internal team | Architecture diagrams, "why" decisions, non-obvious behaviors |
| End users | No jargon, screenshots, task-focused, troubleshooting |
## Format Templates
**JSDoc:**
```javascript
/**
* Brief description.
* @param {Type} name - Description
* @returns {Type} Description
* @throws {Error} When condition
*/
```
**Python:**
```python
def func(param: Type) -> Return:
"""Brief description.
Args:
param: Description
Returns:
Description
Raises:
Error: When condition
"""
```
## Checklist
- [ ] All public APIs documented
- [ ] Params have types and descriptions
- [ ] Examples are runnable
- [ ] Edge cases noted
- [ ] Consistent formatting

View File

@@ -0,0 +1,58 @@
# Test Generation
Create thorough, maintainable test suites covering happy paths, edge cases, and error handling.
## Test Design
| Principle | Application |
|-----------|-------------|
| Clear names | `should return X when Y` |
| AAA pattern | Arrange → Act → Assert |
| One behavior | Each test verifies one thing |
| Isolation | No shared state between tests |
| Specific asserts | `toEqual([1,2,3])` not `toBeTruthy()` |
## Coverage Checklist
-**Happy path:** Normal operation
-**Edge cases:** null, empty, 0, -1, MAX_INT, special chars
-**Errors:** Invalid inputs, missing params, exceptions
-**Integration:** External deps mocked
## Framework Quick Reference
| Framework | Structure | Assert | Mock |
|-----------|-----------|--------|------|
| **Jest** | `describe/it` | `expect().toBe/toEqual` | `jest.mock()` |
| **pytest** | `test_name()` | `assert x == y` | `mocker.patch()` |
| **JUnit** | `@Test` | `assertEquals()` | `@Mock` + Mockito |
| **Mocha** | `describe/it` | Chai `expect().to` | Sinon |
| **RSpec** | `describe/it` | `expect().to eq` | `allow().to receive` |
| **Go** | `TestName(t)` | `t.Error()` | Manual/testify |
## Mocking Strategy
**Mock:** API calls, DB, file system, time, external services
**Don't mock:** Simple data, pure functions, code under test
## Example Structure
```javascript
describe('UserService', () => {
describe('createUser', () => {
it('should create user with valid data', () => {
// Arrange
const data = { name: 'John', email: 'john@test.com' }
// Act
const user = createUser(data)
// Assert
expect(user.name).toBe('John')
})
it('should throw when email invalid', () => {
expect(() => createUser({ email: 'bad' })).toThrow(ValidationError)
})
})
})
```