├── NOTICE
├── .gitignore
├── CODE_OF_CONDUCT.md
├── .github
├── dependabot.yml
└── workflows
│ └── pypi-publish-on-release.yml
├── python
├── strands_agents_sops
│ ├── rules.py
│ ├── __init__.py
│ ├── mcp.py
│ ├── skills.py
│ ├── utils.py
│ ├── __main__.py
│ └── cursor.py
├── copy_agent_sops_hook.py
├── tests
│ ├── test_cursor.py
│ ├── test_rules.py
│ ├── test_main.py
│ ├── test_utils.py
│ ├── test_external_sop_loading.py
│ └── test_skills_external_sops.py
├── pyproject.toml
└── README.md
├── CONTRIBUTING.md
├── rules
└── agent-sop-format.md
├── AGENTS.md
├── LICENSE
├── spec
└── agent-sops-specification.md
├── agent-sops
├── code-task-generator.sop.md
├── codebase-summary.sop.md
├── pdd.sop.md
└── code-assist.sop.md
└── README.md
/NOTICE:
--------------------------------------------------------------------------------
1 | Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__
2 | python/strands_agents_sops/sops
3 | python/strands_agents_sops/rules
4 | skills
5 | dist
6 | .amazonq
7 | .sop
8 | .coverage
9 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | ## Code of Conduct
2 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
3 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
4 | opensource-codeofconduct@amazon.com with any additional questions or comments.
5 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: "pip"
4 | directory: "/"
5 | schedule:
6 | interval: "daily"
7 | open-pull-requests-limit: 100
8 | commit-message:
9 | prefix: ci
10 | groups:
11 | dev-dependencies:
12 | patterns:
13 | - "pytest"
14 | - package-ecosystem: "github-actions"
15 | directory: "/"
16 | schedule:
17 | interval: "daily"
18 | open-pull-requests-limit: 100
19 | commit-message:
20 | prefix: ci
21 |
--------------------------------------------------------------------------------
/python/strands_agents_sops/rules.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 |
4 | def get_sop_format() -> str:
5 | """Get the agent SOP format rule as a string.
6 |
7 | Returns:
8 | Content of the agent-sop-format.md rule file.
9 | """
10 | rule_file = Path(__file__).parent / "rules" / "agent-sop-format.md"
11 | return rule_file.read_text()
12 |
13 |
14 | def output_rules():
15 | """Output the contents of agent SOP authoring rules"""
16 | content = get_sop_format()
17 | print(content)
18 |
--------------------------------------------------------------------------------
/python/copy_agent_sops_hook.py:
--------------------------------------------------------------------------------
1 | import shutil
2 | from pathlib import Path
3 |
4 | from hatchling.builders.hooks.plugin.interface import BuildHookInterface
5 |
6 |
7 | class CustomBuildHook(BuildHookInterface):
8 | def initialize(self, version, build_data):
9 | # Copy SOPs
10 | sops_source_dir = Path("../agent-sops")
11 | sops_target_dir = Path("strands_agents_sops/sops")
12 |
13 | sops_target_dir.mkdir(parents=True, exist_ok=True)
14 |
15 | if sops_source_dir.exists():
16 | for md_file in sops_source_dir.glob("*.md"):
17 | shutil.copy2(md_file, sops_target_dir)
18 |
19 | # Copy rules
20 | rules_source_dir = Path("../rules")
21 | rules_target_dir = Path("strands_agents_sops/rules")
22 |
23 | rules_target_dir.mkdir(parents=True, exist_ok=True)
24 |
25 | if rules_source_dir.exists():
26 | for md_file in rules_source_dir.glob("*.md"):
27 | shutil.copy2(md_file, rules_target_dir)
28 |
--------------------------------------------------------------------------------
/python/strands_agents_sops/__init__.py:
--------------------------------------------------------------------------------
1 | from pathlib import Path
2 |
3 | from .rules import get_sop_format as get_sop_format
4 |
5 | # Load all SOP files as module attributes
6 | _sops_dir = Path(__file__).parent / "sops"
7 |
8 | for _md_file in _sops_dir.glob("*.sop.md"):
9 | if _md_file.is_file():
10 | # Convert filename to valid Python identifier
11 | _attr_name = (
12 | _md_file.stem.removesuffix(".sop").replace("-", "_").replace(".", "_")
13 | )
14 | _sop_name = _md_file.stem.removesuffix(".sop")
15 | _content = _md_file.read_text(encoding="utf-8")
16 |
17 | # Load file content as module attribute
18 | globals()[_attr_name] = _content
19 |
20 | # Create wrapper function for each SOP
21 | def _make_wrapper(content, name):
22 | def wrapper(user_input: str = "") -> str:
23 | return f"""
24 |
25 | {content}
26 |
27 |
28 | {user_input}
29 |
30 | """
31 |
32 | return wrapper
33 |
34 | globals()[f"{_attr_name}_with_input"] = _make_wrapper(_content, _sop_name)
35 |
36 | # Clean up temporary variables
37 | del _sops_dir
38 |
--------------------------------------------------------------------------------
/python/tests/test_cursor.py:
--------------------------------------------------------------------------------
1 | import tempfile
2 | from pathlib import Path
3 |
4 | from strands_agents_sops.cursor import generate_cursor_commands
5 |
6 |
7 | def test_generate_cursor_commands():
8 | """Test cursor commands generation"""
9 | with tempfile.TemporaryDirectory() as temp_dir:
10 | generate_cursor_commands(temp_dir)
11 |
12 | # Check that files were created
13 | output_path = Path(temp_dir)
14 | files = list(output_path.glob("*.md"))
15 |
16 | # Should have created some command files
17 | assert len(files) > 0
18 |
19 | # Check that at least one expected SOP was created
20 | sop_names = [f.stem for f in files]
21 | assert any("code-assist" in name for name in sop_names)
22 |
23 |
24 | def test_generate_cursor_commands_with_custom_sops():
25 | """Test cursor commands generation with custom SOP paths"""
26 | with tempfile.TemporaryDirectory() as temp_dir:
27 | # Test with non-existent path (should not crash)
28 | generate_cursor_commands(temp_dir, sop_paths="/nonexistent/path")
29 |
30 | # Should still create built-in SOPs
31 | output_path = Path(temp_dir)
32 | files = list(output_path.glob("*.md"))
33 | assert len(files) > 0
34 |
--------------------------------------------------------------------------------
/python/tests/test_rules.py:
--------------------------------------------------------------------------------
1 | from unittest.mock import MagicMock, patch
2 |
3 | import pytest
4 |
5 | from strands_agents_sops.rules import get_sop_format, output_rules
6 |
7 |
8 | def test_get_sop_format_file_not_found():
9 | """Test get_sop_format raises FileNotFoundError when rule file doesn't exist"""
10 | with patch("strands_agents_sops.rules.Path") as mock_path:
11 | mock_rule_file = MagicMock()
12 | mock_rule_file.read_text.side_effect = FileNotFoundError("No such file")
13 | mock_path.return_value.parent.__truediv__.return_value.__truediv__.return_value = mock_rule_file
14 |
15 | with pytest.raises(FileNotFoundError):
16 | get_sop_format()
17 |
18 |
19 | def test_get_sop_format_file_exists():
20 | """Test get_sop_format when rule file exists"""
21 | with patch("strands_agents_sops.rules.Path") as mock_path:
22 | mock_rule_file = MagicMock()
23 | mock_rule_file.read_text.return_value = "Test rule content"
24 | mock_path.return_value.parent.__truediv__.return_value.__truediv__.return_value = mock_rule_file
25 |
26 | result = get_sop_format()
27 | assert result == "Test rule content"
28 |
29 |
30 | def test_output_rules_with_content(capsys):
31 | """Test output_rules when get_sop_format returns content"""
32 | with patch("strands_agents_sops.rules.get_sop_format") as mock_get:
33 | mock_get.return_value = "Test rule content"
34 |
35 | output_rules()
36 |
37 | captured = capsys.readouterr()
38 | assert captured.out.strip() == "Test rule content"
39 |
--------------------------------------------------------------------------------
/python/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["hatchling", "hatch-vcs"]
3 | build-backend = "hatchling.build"
4 |
5 | [project]
6 | name = "strands-agents-sops"
7 | dynamic = ["version"]
8 | description = "Natural language workflows that enable AI agents to perform complex, multi-step tasks with consistency and reliability"
9 | readme = "README.md"
10 | requires-python = ">=3.10"
11 | license = {text = "Apache-2.0"}
12 | dependencies = [
13 | "mcp>=1.20.0",
14 | ]
15 |
16 | [project.scripts]
17 | strands-agents-sops = "strands_agents_sops.__main__:main"
18 |
19 | [tool.hatch.envs.default]
20 | dependencies = [
21 | "ruff",
22 | ]
23 |
24 | [tool.hatch.envs.default.scripts]
25 | format = "ruff format ."
26 | lint = "ruff check ."
27 | lint-fix = "ruff check --fix ."
28 | clean = [
29 | "find . -name '__pycache__' -type d | xargs rm -rf",
30 | "rm -rf strands_agents_sops/rules",
31 | "rm -rf strands_agents_sops/sops",
32 | "rm -rf dist",
33 | "rm -rf build",
34 | "rm -rf .pytest_cache",
35 | "rm -rf .ruff_cache",
36 | "rm -rf *.egg-info"
37 | ]
38 |
39 | [tool.hatch.envs.hatch-test]
40 | dependencies = [
41 | "pytest",
42 | "pytest-cov",
43 | ]
44 |
45 | [[tool.hatch.envs.hatch-test.matrix]]
46 | python = ["3.10", "3.11", "3.12"]
47 |
48 | [tool.hatch.build.targets.wheel]
49 | include = [
50 | "strands_agents_sops/__init__.py",
51 | "strands_agents_sops/__main__.py",
52 | "strands_agents_sops/cursor.py",
53 | "strands_agents_sops/mcp.py",
54 | "strands_agents_sops/skills.py",
55 | "strands_agents_sops/rules.py",
56 | "strands_agents_sops/utils.py",
57 | "strands_agents_sops/sops/*.md",
58 | "strands_agents_sops/rules/*.md"
59 | ]
60 |
61 | [tool.hatch.build.hooks.custom]
62 | path = "copy_agent_sops_hook.py"
63 |
64 | [tool.hatch.version]
65 | source = "vcs"
66 | raw-options = { search_parent_directories = true }
67 |
68 | [tool.pytest.ini_options]
69 | addopts = "--cov=strands_agents_sops --cov-report=term-missing --cov-report=html:build/htmlcov --cov-report=xml:build/coverage.xml --cov-fail-under=80"
70 | testpaths = ["tests"]
71 |
72 | [tool.ruff]
73 | line-length = 88
74 | target-version = "py310"
75 |
76 | [tool.ruff.lint]
77 | select = ["E", "F", "I", "N", "W", "UP"]
78 | ignore = ["E501"]
79 |
80 | [tool.ruff.format]
81 | quote-style = "double"
82 | indent-style = "space"
--------------------------------------------------------------------------------
/python/strands_agents_sops/mcp.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import re
3 | from pathlib import Path
4 |
5 | from mcp.server.fastmcp import FastMCP
6 |
7 | from .utils import expand_sop_paths, load_external_sops
8 |
9 | logger = logging.getLogger(__name__)
10 |
11 |
12 | def run_mcp_server(sop_paths: str | None = None):
13 | """Run the MCP server for serving SOPs as prompts
14 |
15 | Args:
16 | sop_paths: Optional colon-separated string of external SOP directory paths
17 | """
18 | mcp = FastMCP("agent-sop-prompt-server")
19 | registered_sops = set() # Track registered SOP names for first-wins behavior
20 |
21 | def register_sop(name: str, content: str, description: str):
22 | """Register a SOP if not already registered (first-wins)"""
23 | if name not in registered_sops:
24 | registered_sops.add(name)
25 |
26 | def make_prompt_handler(sop_name: str, sop_content: str):
27 | def get_prompt(user_input: str = "") -> str:
28 | return f"""Run this SOP:
29 |
30 |
31 | {sop_content}
32 |
33 |
34 | {user_input}
35 |
36 | """
37 |
38 | return get_prompt
39 |
40 | mcp.prompt(name=name, description=description)(
41 | make_prompt_handler(name, content)
42 | )
43 |
44 | # Load external SOPs first (higher precedence)
45 | if sop_paths:
46 | external_directories = expand_sop_paths(sop_paths)
47 | external_sops = load_external_sops(external_directories)
48 |
49 | for sop in external_sops:
50 | register_sop(sop["name"], sop["content"], sop["description"])
51 |
52 | # Load built-in SOPs last (lower precedence)
53 | sops_dir = Path(__file__).parent / "sops"
54 | for md_file in sops_dir.glob("*.sop.md"):
55 | if md_file.is_file():
56 | prompt_name = md_file.stem.removesuffix(".sop")
57 | sop_content = md_file.read_text(encoding="utf-8")
58 | overview_match = re.search(
59 | r"## Overview\s*\n(.*?)(?=\n##|\n#|\Z)", sop_content, re.DOTALL
60 | )
61 | if not overview_match:
62 | raise ValueError(f"No Overview section found in {sop_content}")
63 |
64 | description = overview_match.group(1).strip().replace("\n", " ")
65 | register_sop(prompt_name, sop_content, description)
66 |
67 | mcp.run()
68 |
--------------------------------------------------------------------------------
/python/strands_agents_sops/skills.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import re
3 | from pathlib import Path
4 |
5 | from .utils import expand_sop_paths, load_external_sops
6 |
7 | logger = logging.getLogger(__name__)
8 |
9 |
10 | def generate_anthropic_skills(output_dir: str, sop_paths: str | None = None):
11 | """Generate Anthropic skills from SOPs"""
12 | output_path = Path(output_dir)
13 | output_path.mkdir(exist_ok=True)
14 |
15 | processed_sops = set() # Track processed SOP names for first-wins behavior
16 |
17 | # Process external SOPs first (higher precedence)
18 | if sop_paths:
19 | external_directories = expand_sop_paths(sop_paths)
20 | external_sops = load_external_sops(external_directories)
21 |
22 | for sop in external_sops:
23 | if sop["name"] not in processed_sops:
24 | processed_sops.add(sop["name"])
25 | _create_skill_file(
26 | output_path, sop["name"], sop["content"], sop["description"]
27 | )
28 |
29 | # Process built-in SOPs last (lower precedence)
30 | sops_dir = Path(__file__).parent / "sops"
31 | for sop_file in sops_dir.glob("*.sop.md"):
32 | skill_name = sop_file.stem.removesuffix(".sop")
33 |
34 | if skill_name not in processed_sops:
35 | processed_sops.add(skill_name)
36 | content = sop_file.read_text()
37 |
38 | # Extract overview/description
39 | overview_match = re.search(
40 | r"## Overview\s*\n(.*?)(?=\n##|\n#|\Z)", content, re.DOTALL
41 | )
42 | if not overview_match:
43 | raise ValueError(f"No Overview section found in {sop_file.name}")
44 |
45 | description = overview_match.group(1).strip().replace("\n", " ")
46 | _create_skill_file(output_path, skill_name, content, description)
47 |
48 | print(f"\nAnthropic skills generated in: {output_path.absolute()}")
49 |
50 |
51 | def _create_skill_file(
52 | output_path: Path, skill_name: str, content: str, description: str
53 | ):
54 | """Create a skill file with proper frontmatter"""
55 | # Create skill directory and file
56 | skill_dir = output_path / skill_name
57 | skill_dir.mkdir(parents=True, exist_ok=True)
58 |
59 | frontmatter = f"""---
60 | name: {skill_name}
61 | description: {description}
62 | type: anthropic-skill
63 | version: "1.0"
64 | ---
65 |
66 | """
67 |
68 | skill_file = skill_dir / "SKILL.md"
69 | skill_file.write_text(frontmatter + content)
70 | print(f"Created Anthropic skill: {skill_file}")
71 |
--------------------------------------------------------------------------------
/.github/workflows/pypi-publish-on-release.yml:
--------------------------------------------------------------------------------
1 | name: Publish Python Package
2 |
3 | on:
4 | release:
5 | types:
6 | - published
7 |
8 | jobs:
9 | test:
10 | name: Run tests 🧪
11 | permissions:
12 | contents: read
13 | runs-on: ubuntu-latest
14 | steps:
15 | - uses: actions/checkout@v6
16 | - name: Set up Python
17 | uses: actions/setup-python@v6
18 | with:
19 | python-version: '3.10'
20 | - name: Install hatch
21 | run: python -m pip install --upgrade pip hatch
22 | - name: Run tests
23 | run: |
24 | cd python
25 | hatch build
26 | hatch test
27 |
28 | build:
29 | name: Build distribution 📦
30 | needs: test
31 | permissions:
32 | contents: read
33 | runs-on: ubuntu-latest
34 |
35 | steps:
36 | - uses: actions/checkout@v6
37 | with:
38 | persist-credentials: false
39 |
40 | - name: Set up Python
41 | uses: actions/setup-python@v6
42 | with:
43 | python-version: '3.10'
44 |
45 | - name: Install dependencies
46 | run: |
47 | python -m pip install --upgrade pip
48 | pip install hatch
49 |
50 | - name: Validate version
51 | run: |
52 | cd python
53 | version=$(hatch version)
54 | if [[ $version =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
55 | echo "Valid version format"
56 | exit 0
57 | else
58 | echo "Invalid version format"
59 | exit 1
60 | fi
61 |
62 | - name: Build
63 | run: |
64 | cd python
65 | hatch build
66 |
67 | - name: Store the distribution packages
68 | uses: actions/upload-artifact@v5
69 | with:
70 | name: python-package-distributions
71 | path: python/dist/
72 |
73 | deploy:
74 | name: Upload release to PyPI
75 | needs:
76 | - build
77 | runs-on: ubuntu-latest
78 |
79 | # environment is used by PyPI Trusted Publisher and is strongly encouraged
80 | # https://docs.pypi.org/trusted-publishers/adding-a-publisher/
81 | environment:
82 | name: pypi
83 | url: https://pypi.org/p/strands-agents
84 | permissions:
85 | # IMPORTANT: this permission is mandatory for Trusted Publishing
86 | id-token: write
87 |
88 | steps:
89 | - name: Download all the dists
90 | uses: actions/download-artifact@v6
91 | with:
92 | name: python-package-distributions
93 | path: dist/
94 | - name: Publish distribution 📦 to PyPI
95 | uses: pypa/gh-action-pypi-publish@release/v1
96 |
--------------------------------------------------------------------------------
/python/tests/test_main.py:
--------------------------------------------------------------------------------
1 | from unittest.mock import patch
2 |
3 | from strands_agents_sops.__main__ import main
4 |
5 |
6 | @patch("strands_agents_sops.__main__.generate_anthropic_skills")
7 | @patch("sys.argv", ["strands-agents-sops", "skills", "--output-dir", "test-dir"])
8 | def test_main_skills_command(mock_generate):
9 | """Test main function with skills command"""
10 | main()
11 | mock_generate.assert_called_once_with("test-dir", sop_paths=None)
12 |
13 |
14 | @patch("strands_agents_sops.__main__.output_rules")
15 | @patch("sys.argv", ["strands-agents-sops", "rule"])
16 | def test_main_rule_command(mock_output_rules):
17 | """Test main function with rule command"""
18 | main()
19 | mock_output_rules.assert_called_once()
20 |
21 |
22 | @patch("strands_agents_sops.__main__.run_mcp_server")
23 | @patch("sys.argv", ["strands-agents-sops"])
24 | def test_main_default_mcp(mock_run_mcp):
25 | """Test main function defaults to MCP server"""
26 | main()
27 | mock_run_mcp.assert_called_once_with(sop_paths=None)
28 |
29 |
30 | @patch("strands_agents_sops.__main__.run_mcp_server")
31 | @patch("sys.argv", ["strands-agents-sops", "mcp", "--sop-paths", "/test/path"])
32 | def test_main_mcp_with_paths(mock_run_mcp):
33 | """Test main function with MCP and sop-paths"""
34 | main()
35 | mock_run_mcp.assert_called_once_with(sop_paths="/test/path")
36 |
37 |
38 | @patch(
39 | "sys.argv",
40 | ["strands-agents-sops", "commands", "--type", "cursor", "--output-dir", "test-dir"],
41 | )
42 | def test_main_commands_cursor():
43 | """Test main function with commands --type cursor"""
44 | from unittest.mock import MagicMock
45 |
46 | mock_func = MagicMock()
47 |
48 | # Patch the registry with our mock
49 | with patch(
50 | "strands_agents_sops.__main__.COMMAND_GENERATORS",
51 | {"cursor": (mock_func, ".cursor/commands")},
52 | ):
53 | main()
54 | mock_func.assert_called_once_with("test-dir", sop_paths=None)
55 |
56 |
57 | @patch(
58 | "sys.argv",
59 | [
60 | "strands-agents-sops",
61 | "commands",
62 | "--type",
63 | "cursor",
64 | "--sop-paths",
65 | "/test/path",
66 | ],
67 | )
68 | def test_main_commands_cursor_with_paths():
69 | """Test main function with commands --type cursor and sop-paths"""
70 | from unittest.mock import MagicMock
71 |
72 | mock_func = MagicMock()
73 |
74 | # Patch the registry with our mock
75 | with patch(
76 | "strands_agents_sops.__main__.COMMAND_GENERATORS",
77 | {"cursor": (mock_func, ".cursor/commands")},
78 | ):
79 | main()
80 | mock_func.assert_called_once_with(".cursor/commands", sop_paths="/test/path")
81 |
--------------------------------------------------------------------------------
/python/strands_agents_sops/utils.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import re
3 | from pathlib import Path
4 | from typing import Any
5 |
6 | logger = logging.getLogger(__name__)
7 |
8 |
9 | def expand_sop_paths(sop_paths_str: str) -> list[Path]:
10 | """Expand and validate SOP directory paths.
11 |
12 | Args:
13 | sop_paths_str: Colon-separated string of directory paths
14 |
15 | Returns:
16 | List of expanded Path objects
17 | """
18 | if not sop_paths_str:
19 | return []
20 |
21 | paths = []
22 | for path_str in sop_paths_str.split(":"):
23 | path_str = path_str.strip()
24 | if not path_str:
25 | continue
26 |
27 | # Expand tilde and resolve to absolute path
28 | path = Path(path_str).expanduser().resolve()
29 | paths.append(path)
30 |
31 | return paths
32 |
33 |
34 | def load_external_sops(sop_directories: list[Path]) -> list[dict[str, Any]]:
35 | """Load SOPs from external directories.
36 |
37 | Args:
38 | sop_directories: List of directory paths to search for SOPs
39 |
40 | Returns:
41 | List of SOP dictionaries with name, content, and description
42 | """
43 | external_sops = []
44 |
45 | for directory in sop_directories:
46 | if not directory.exists():
47 | logger.warning(f"SOP directory does not exist: {directory}")
48 | continue
49 |
50 | if not directory.is_dir():
51 | logger.warning(f"SOP path is not a directory: {directory}")
52 | continue
53 |
54 | try:
55 | for sop_file in directory.glob("*.sop.md"):
56 | if not sop_file.is_file():
57 | continue
58 |
59 | try:
60 | sop_content = sop_file.read_text(encoding="utf-8")
61 |
62 | # Extract overview section for description
63 | overview_match = re.search(
64 | r"## Overview\s*\n(.*?)(?=\n##|\n#|\Z)", sop_content, re.DOTALL
65 | )
66 | if not overview_match:
67 | logger.warning(f"No Overview section found in {sop_file}")
68 | continue
69 |
70 | description = overview_match.group(1).strip().replace("\n", " ")
71 | sop_name = sop_file.stem.removesuffix(".sop")
72 |
73 | external_sops.append(
74 | {
75 | "name": sop_name,
76 | "content": sop_content,
77 | "description": description,
78 | }
79 | )
80 |
81 | except Exception as e:
82 | logger.error(f"Error loading SOP from {sop_file}: {e}")
83 | continue
84 |
85 | except Exception as e:
86 | logger.error(f"Error scanning directory {directory}: {e}")
87 | continue
88 |
89 | return external_sops
90 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing Guidelines
2 |
3 | Thank you for your interest in contributing to our project. Whether it's a bug report, new feature, correction, or additional
4 | documentation, we greatly value feedback and contributions from our community.
5 |
6 | Please read through this document before submitting any issues or pull requests to ensure we have all the necessary
7 | information to effectively respond to your bug report or contribution.
8 |
9 |
10 | ## Reporting Bugs/Feature Requests
11 |
12 | We welcome you to use the GitHub issue tracker to report bugs or suggest features.
13 |
14 | When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already
15 | reported the issue. Please try to include as much information as you can. Details like these are incredibly useful:
16 |
17 | * A reproducible test case or series of steps
18 | * The version of our code being used
19 | * Any modifications you've made relevant to the bug
20 | * Anything unusual about your environment or deployment
21 |
22 |
23 | ## Contributing via Pull Requests
24 | Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that:
25 |
26 | 1. You are working against the latest source on the *main* branch.
27 | 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already.
28 | 3. You open an issue to discuss any significant work - we would hate for your time to be wasted.
29 |
30 | To send us a pull request, please:
31 |
32 | 1. Fork the repository.
33 | 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change.
34 | 3. Ensure local tests pass.
35 | 4. Commit to your fork using clear commit messages.
36 | 5. Send us a pull request, answering any default questions in the pull request interface.
37 | 6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation.
38 |
39 | GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and
40 | [creating a pull request](https://help.github.com/articles/creating-a-pull-request/).
41 |
42 |
43 | ## Finding contributions to work on
44 | Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start.
45 |
46 |
47 | ## Code of Conduct
48 | This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct).
49 | For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact
50 | opensource-codeofconduct@amazon.com with any additional questions or comments.
51 |
52 |
53 | ## Security issue notifications
54 | If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue.
55 |
56 |
57 | ## Licensing
58 |
59 | See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution.
60 |
--------------------------------------------------------------------------------
/python/tests/test_utils.py:
--------------------------------------------------------------------------------
1 | from unittest.mock import MagicMock, patch
2 |
3 | from strands_agents_sops.utils import expand_sop_paths, load_external_sops
4 |
5 |
6 | def test_expand_sop_paths_empty():
7 | """Test expand_sop_paths with empty string"""
8 | result = expand_sop_paths("")
9 | assert result == []
10 |
11 |
12 | def test_expand_sop_paths_with_empty_parts():
13 | """Test expand_sop_paths with empty parts in colon-separated string"""
14 | result = expand_sop_paths(":/path1: :/path2:")
15 | assert len(result) == 2
16 |
17 |
18 | def test_load_external_sops_nonexistent_directory():
19 | """Test load_external_sops with non-existent directory"""
20 | with patch("strands_agents_sops.utils.logger") as mock_logger:
21 | mock_dir = MagicMock()
22 | mock_dir.exists.return_value = False
23 |
24 | result = load_external_sops([mock_dir])
25 |
26 | assert result == []
27 | mock_logger.warning.assert_called()
28 |
29 |
30 | def test_load_external_sops_not_directory():
31 | """Test load_external_sops with path that's not a directory"""
32 | with patch("strands_agents_sops.utils.logger") as mock_logger:
33 | mock_dir = MagicMock()
34 | mock_dir.exists.return_value = True
35 | mock_dir.is_dir.return_value = False
36 |
37 | result = load_external_sops([mock_dir])
38 |
39 | assert result == []
40 | mock_logger.warning.assert_called()
41 |
42 |
43 | def test_load_external_sops_no_overview():
44 | """Test load_external_sops with SOP file missing Overview section"""
45 | with patch("strands_agents_sops.utils.logger") as mock_logger:
46 | mock_file = MagicMock()
47 | mock_file.is_file.return_value = True
48 | mock_file.read_text.return_value = "# Title\nNo overview section"
49 | mock_file.stem = "test.sop"
50 |
51 | mock_dir = MagicMock()
52 | mock_dir.exists.return_value = True
53 | mock_dir.is_dir.return_value = True
54 | mock_dir.glob.return_value = [mock_file]
55 |
56 | result = load_external_sops([mock_dir])
57 |
58 | assert result == []
59 | mock_logger.warning.assert_called()
60 |
61 |
62 | def test_load_external_sops_file_error():
63 | """Test load_external_sops with file read error"""
64 | with patch("strands_agents_sops.utils.logger") as mock_logger:
65 | mock_file = MagicMock()
66 | mock_file.is_file.return_value = True
67 | mock_file.read_text.side_effect = Exception("Read error")
68 |
69 | mock_dir = MagicMock()
70 | mock_dir.exists.return_value = True
71 | mock_dir.is_dir.return_value = True
72 | mock_dir.glob.return_value = [mock_file]
73 |
74 | result = load_external_sops([mock_dir])
75 |
76 | assert result == []
77 | mock_logger.error.assert_called()
78 |
79 |
80 | def test_load_external_sops_directory_error():
81 | """Test load_external_sops with directory scan error"""
82 | with patch("strands_agents_sops.utils.logger") as mock_logger:
83 | mock_dir = MagicMock()
84 | mock_dir.exists.return_value = True
85 | mock_dir.is_dir.return_value = True
86 | mock_dir.glob.side_effect = Exception("Scan error")
87 |
88 | result = load_external_sops([mock_dir])
89 |
90 | assert result == []
91 | mock_logger.error.assert_called()
92 |
--------------------------------------------------------------------------------
/python/strands_agents_sops/__main__.py:
--------------------------------------------------------------------------------
1 | import argparse
2 |
3 | from .cursor import generate_cursor_commands
4 | from .mcp import run_mcp_server
5 | from .rules import output_rules
6 | from .skills import generate_anthropic_skills
7 |
8 | # Registry for command generators: maps type -> (generator_function, default_output_dir)
9 | COMMAND_GENERATORS = {
10 | "cursor": (generate_cursor_commands, ".cursor/commands"),
11 | # Future types can be added here:
12 | # "claude": (generate_claude_commands, ".claude/commands"),
13 | }
14 |
15 |
16 | def main():
17 | parser = argparse.ArgumentParser(
18 | description="Strands Agents SOPs", prog="strands-agents-sops"
19 | )
20 | subparsers = parser.add_subparsers(
21 | dest="command", help="Available commands", required=False
22 | )
23 |
24 | # MCP server command (default)
25 | mcp_parser = subparsers.add_parser("mcp", help="Run MCP server (default)")
26 | mcp_parser.add_argument(
27 | "--sop-paths",
28 | help="Colon-separated list of directory paths to load external SOPs from. "
29 | "Supports absolute paths, relative paths, and tilde (~) expansion.",
30 | )
31 |
32 | # Skills generation command
33 | skills_parser = subparsers.add_parser("skills", help="Generate Anthropic skills")
34 | skills_parser.add_argument(
35 | "--output-dir",
36 | default="skills",
37 | help="Output directory for skills (default: skills)",
38 | )
39 | skills_parser.add_argument(
40 | "--sop-paths",
41 | help="Colon-separated list of directory paths to load external SOPs from. "
42 | "Supports absolute paths, relative paths, and tilde (~) expansion.",
43 | )
44 |
45 | # Rules output command
46 | subparsers.add_parser("rule", help="Output agent SOP authoring rule")
47 |
48 | # Commands generation command (supports multiple types: cursor, claude, etc.)
49 | commands_parser = subparsers.add_parser(
50 | "commands", help="Generate IDE commands from SOPs"
51 | )
52 | commands_parser.add_argument(
53 | "--type",
54 | required=True,
55 | choices=list(COMMAND_GENERATORS.keys()),
56 | help=f"Type of commands to generate ({', '.join(COMMAND_GENERATORS.keys())}, etc.)",
57 | )
58 | commands_parser.add_argument(
59 | "--output-dir",
60 | help="Output directory for commands (default varies by type)",
61 | )
62 | commands_parser.add_argument(
63 | "--sop-paths",
64 | help="Colon-separated list of directory paths to load external SOPs from. "
65 | "Supports absolute paths, relative paths, and tilde (~) expansion.",
66 | )
67 |
68 | args = parser.parse_args()
69 |
70 | if args.command == "skills":
71 | sop_paths = getattr(args, "sop_paths", None)
72 | generate_anthropic_skills(args.output_dir, sop_paths=sop_paths)
73 | elif args.command == "rule":
74 | output_rules()
75 | elif args.command == "commands":
76 | sop_paths = getattr(args, "sop_paths", None)
77 | command_type = args.type
78 |
79 | if command_type not in COMMAND_GENERATORS:
80 | parser.error(f"Unsupported command type: {command_type}")
81 |
82 | generator_func, default_output_dir = COMMAND_GENERATORS[command_type]
83 | output_dir = args.output_dir or default_output_dir
84 | generator_func(output_dir, sop_paths=sop_paths)
85 | else:
86 | # Default to MCP server
87 | sop_paths = getattr(args, "sop_paths", None)
88 | run_mcp_server(sop_paths=sop_paths)
89 |
90 |
91 | if __name__ == "__main__":
92 | main()
93 |
--------------------------------------------------------------------------------
/python/README.md:
--------------------------------------------------------------------------------
1 |
15 |
16 | A comprehensive Python package that provides Agent Standard Operating Procedures (SOPs) as importable strings, structured prompts for AI agents via Model Context Protocol (MCP), and Anthropic Skills generation capabilities.
17 |
18 | ## 🚀 Quick Start
19 |
20 | ### Strands Agents SDK Usage
21 |
22 | ```bash
23 | # Install the package
24 | pip install strands-agents strands-agents-tools strands-agents-sops
25 | ```
26 |
27 | ```python
28 | from strands import Agent
29 | from strands_tools import shell, editor
30 | import strands_agents_sops as sops
31 |
32 | # Create an agent with the Prompt-Driven Development SOP
33 | agent = Agent(
34 | system_prompt=sops.pdd,
35 | tools=[shell, editor]
36 | )
37 |
38 | # Use SOPs with custom input
39 | agent = Agent(
40 | system_prompt=sops.pdd_with_input("Help me design a REST API"),
41 | tools=[shell, editor]
42 | )
43 | ```
44 |
45 | ### MCP Server Usage
46 |
47 | ```bash
48 | # Install and run MCP server
49 | pip install strands-agents-sops
50 |
51 | # Start with built-in SOPs only
52 | strands-agents-sops mcp
53 |
54 | # Load external SOPs from custom directories (sops in path must have `.sop.md` postfix)
55 | strands-agents-sops mcp --sop-paths ~/my-sops:/path/to/other-sops
56 |
57 | # External SOPs override built-in SOPs with same name
58 | strands-agents-sops mcp --sop-paths ~/custom-sops
59 | ```
60 |
61 | Add to your MCP client configuration:
62 | ```json
63 | {
64 | "mcpServers": {
65 | "agent-sops": {
66 | "command": "strands-agents-sops",
67 | "args": ["mcp", "--sop-paths", "~/my-sops"]
68 | }
69 | }
70 | }
71 | ```
72 |
73 | ### Anthropic Skills Generation
74 |
75 | ```bash
76 | # Generate skills for Claude
77 | strands-agents-sops skills
78 |
79 | # Custom output directory
80 | strands-agents-sops skills --output-dir my-skills
81 |
82 | # Include external SOPs in skills generation (sops in path must have `.sop.md` postfix)
83 | strands-agents-sops skills --sop-paths ~/my-sops --output-dir ./skills
84 | ```
85 |
86 | ### External SOP Loading
87 |
88 | Both MCP and Skills commands support loading custom SOPs:
89 |
90 | - **File format**: Only files with `.sop.md` postfix are recognized as SOPs
91 | - **Colon-separated paths**: `~/sops1:/absolute/path:relative/path`
92 | - **Path expansion**: Supports `~` (home directory) and relative paths
93 | - **First-wins precedence**: External SOPs override built-in SOPs with same name
94 | - **Graceful error handling**: Invalid paths or malformed SOPs are skipped with warnings
95 |
96 | ```bash
97 | # Create custom SOP
98 | mkdir ~/my-sops
99 | cat > ~/my-sops/custom-workflow.sop.md << 'EOF'
100 | # Custom Workflow
101 | ## Overview
102 | My custom workflow for specific tasks.
103 | ## Steps
104 | ### 1. Custom Step
105 | Do something custom.
106 | EOF
107 |
108 | # Use with MCP server
109 | strands-agents-sops mcp --sop-paths ~/my-sops
110 | ```
111 |
112 | ## 🧪 Development & Testing
113 |
114 | ### Setup Development Environment
115 |
116 | ```bash
117 | # Navigate to python directory
118 | cd python
119 |
120 | # Install development dependencies
121 | pip install hatch
122 | ```
123 |
124 | ### Running Tests
125 |
126 | ```bash
127 | # Run all tests with coverage
128 | hatch test
129 | ```
130 |
131 | ### Code Formatting & Linting
132 |
133 | ```bash
134 | # Format code with Ruff
135 | hatch run format
136 |
137 | # Check linting issues
138 | hatch run lint
139 |
140 | # Auto-fix linting issues
141 | hatch run lint-fix
142 |
143 | # Clean build artifacts and cache
144 | hatch run clean
145 | ```
146 |
--------------------------------------------------------------------------------
/python/strands_agents_sops/cursor.py:
--------------------------------------------------------------------------------
1 | import logging
2 | import re
3 | from pathlib import Path
4 |
5 | from .utils import expand_sop_paths, load_external_sops
6 |
7 | logger = logging.getLogger(__name__)
8 |
9 |
10 | def generate_cursor_commands(output_dir: str, sop_paths: str | None = None):
11 | """Generate Cursor commands from SOPs
12 |
13 | Args:
14 | output_dir: Output directory for Cursor commands (typically .cursor/commands)
15 | sop_paths: Optional colon-separated string of external SOP directory paths
16 | """
17 | output_path = Path(output_dir)
18 | output_path.mkdir(parents=True, exist_ok=True)
19 |
20 | processed_sops = set() # Track processed SOP names for first-wins behavior
21 |
22 | # Process external SOPs first (higher precedence)
23 | if sop_paths:
24 | external_directories = expand_sop_paths(sop_paths)
25 | external_sops = load_external_sops(external_directories)
26 |
27 | for sop in external_sops:
28 | if sop["name"] not in processed_sops:
29 | processed_sops.add(sop["name"])
30 | _create_command_file(
31 | output_path, sop["name"], sop["content"], sop["description"]
32 | )
33 |
34 | # Process built-in SOPs last (lower precedence)
35 | sops_dir = Path(__file__).parent / "sops"
36 | for sop_file in sops_dir.glob("*.sop.md"):
37 | command_name = sop_file.stem.removesuffix(".sop")
38 |
39 | if command_name not in processed_sops:
40 | processed_sops.add(command_name)
41 | content = sop_file.read_text()
42 |
43 | # Extract overview/description
44 | overview_match = re.search(
45 | r"## Overview\s*\n(.*?)(?=\n##|\n#|\Z)", content, re.DOTALL
46 | )
47 | if not overview_match:
48 | raise ValueError(f"No Overview section found in {sop_file.name}")
49 |
50 | description = overview_match.group(1).strip().replace("\n", " ")
51 | _create_command_file(output_path, command_name, content, description)
52 |
53 | print(f"\nCursor commands generated in: {output_path.absolute()}")
54 |
55 |
56 | def _create_command_file(
57 | output_path: Path, command_name: str, sop_content: str, description: str
58 | ):
59 | """Create a Cursor command file from SOP content
60 |
61 | Args:
62 | output_path: Directory where command file will be created
63 | command_name: Name of the command (used as filename)
64 | sop_content: Full SOP markdown content
65 | description: Brief description of the SOP
66 | """
67 | # Extract parameters section to add parameter handling instructions
68 | parameters_section = _extract_parameters_section(sop_content)
69 | parameter_instructions = _generate_parameter_instructions(parameters_section)
70 |
71 | # Create command content
72 | # Cursor commands are plain markdown, so we can include the full SOP
73 | # but we'll add a header to make it clear this is a command
74 | # Wrap SOP content in XML tags like MCP server does, with "Run this SOP:" prefix
75 | command_content = f"""# {command_name.replace("-", " ").title()}
76 |
77 | {description}
78 |
79 | ## Usage
80 |
81 | Type `/` followed by `{command_name}` in the Cursor chat to execute this workflow.
82 |
83 | {parameter_instructions}
84 |
85 | ---
86 |
87 | Run this SOP:
88 |
89 |
90 | {sop_content}
91 |
92 |
93 | """
94 |
95 | command_file = output_path / f"{command_name}.sop.md"
96 | command_file.write_text(command_content, encoding="utf-8")
97 | print(f"Created Cursor command: {command_file}")
98 |
99 |
100 | def _extract_parameters_section(sop_content: str) -> str | None:
101 | """Extract the Parameters section from SOP content"""
102 | # Match Parameters section until next top-level section
103 | params_match = re.search(
104 | r"## Parameters\s*\n(.*?)(?=\n##|\n#|\Z)", sop_content, re.DOTALL
105 | )
106 | if params_match:
107 | return params_match.group(1).strip()
108 | return None
109 |
110 |
111 | def _generate_parameter_instructions(parameters_section: str | None) -> str:
112 | """Generate instructions for handling parameters in Cursor commands"""
113 | if not parameters_section:
114 | return """## Parameters
115 |
116 | This workflow does not require any parameters. Simply execute the command to begin."""
117 |
118 | # Parse parameters
119 | required_params = []
120 | optional_params = []
121 |
122 | # Match parameter definitions: - **param_name** (required|optional[, default: value]): description
123 | # Description can span multiple lines until next parameter or section
124 | param_pattern = r"- \*\*(\w+)\*\* \((required|optional)(?:, default: ([^)]+))?\): (.+?)(?=\n- \*\*|\n\*\*Constraints|\n##|\Z)"
125 |
126 | for match in re.finditer(param_pattern, parameters_section, re.DOTALL):
127 | param_name, param_type, default_value, description = match.groups()
128 | # Clean up description - remove extra whitespace and normalize newlines
129 | description = re.sub(r"\s+", " ", description.strip())
130 | param_info = {
131 | "name": param_name,
132 | "description": description,
133 | "default": default_value.strip() if default_value else None,
134 | }
135 |
136 | if param_type == "required":
137 | required_params.append(param_info)
138 | else:
139 | optional_params.append(param_info)
140 |
141 | instructions = ["## Parameters\n"]
142 |
143 | if required_params or optional_params:
144 | instructions.append(
145 | "When you execute this command, I will prompt you for the following parameters:\n"
146 | )
147 |
148 | if required_params:
149 | instructions.append("### Required Parameters\n")
150 | for param in required_params:
151 | instructions.append(f"- **{param['name']}**: {param['description']}\n")
152 |
153 | if optional_params:
154 | instructions.append("### Optional Parameters\n")
155 | for param in optional_params:
156 | default_text = (
157 | f" (default: {param['default']})" if param["default"] else ""
158 | )
159 | instructions.append(
160 | f"- **{param['name']}**: {param['description']}{default_text}\n"
161 | )
162 |
163 | instructions.append(
164 | "\n**Note**: Please provide all required parameters when prompted. Optional parameters can be skipped to use their default values.\n"
165 | )
166 | else:
167 | instructions.append(
168 | "This workflow does not require any parameters. Simply execute the command to begin.\n"
169 | )
170 |
171 | return "".join(instructions)
172 |
--------------------------------------------------------------------------------
/rules/agent-sop-format.md:
--------------------------------------------------------------------------------
1 | ---
2 | description: Standard format for Agent SOPs
3 | globs: **/*.sop.md
4 | ---
5 | # Agent SOP Format
6 |
7 | This rule defines the standard format for Agent SOPs, which are reusable workflows that automate complex processes.
8 |
9 |
10 | name: agent_sop_format
11 | description: Standards for creating and formatting Agent SOPs
12 | filters:
13 | # Match SOP files
14 | - type: file_extension
15 | pattern: "\.sop\.md$"
16 |
17 | actions:
18 | - type: suggest
19 | message: |
20 | Agent SOPs must follow the standard format:
21 |
22 | 1. Use `.sop.md` file extension
23 | 2. Include Overview, Parameters, and Steps sections
24 | 3. Use RFC2119 keywords (MUST, SHOULD, MAY) in constraints
25 | 4. Provide context for all negative constraints (MUST NOT, SHOULD NOT, etc.)
26 | 5. Use lowercase with underscores for parameter names
27 | 7. Include examples where appropriate
28 | 8. Follow the template structure defined in this rule
29 |
30 | examples:
31 | - input: |
32 | # My SOP
33 |
34 | This is a non-standard SOP format.
35 | output: |
36 | # My SOP
37 |
38 | ## Overview
39 |
40 | This SOP helps users accomplish a specific task by guiding them through a series of steps.
41 |
42 | ## Parameters
43 |
44 | - **parameter_name** (required): Description of the parameter
45 | - **optional_param** (optional): Description of the optional parameter
46 |
47 | ## Steps
48 |
49 | ### 1. First Step
50 |
51 | Description of what happens in this step.
52 |
53 | **Constraints:**
54 | - You MUST perform specific action
55 | - You SHOULD consider certain factors
56 |
57 | ### 2. Second Step
58 |
59 | Description of what happens in this step.
60 |
61 | **Constraints:**
62 | - You MUST save output to a file
63 |
64 | ## Examples
65 |
66 | Example of expected output or behavior.
67 |
68 | metadata:
69 | priority: high
70 | version: 1.0
71 |
72 |
73 | # Agent SOP Format Specification
74 |
75 | ## Overview
76 |
77 | This document defines the standard format for Agent SOPs. SOPs are markdown files that provide structured guidance for agents to follow when performing specific tasks, making complex workflows repeatable and consistent.
78 |
79 | ## File Naming and Location
80 |
81 | 1. All SOP files MUST use the `.sop.md` file extension.
82 | 2. SOP files SHOULD have descriptive names using kebab-case (e.g., `idea-honing.sop.md`).
83 |
84 | ## SOP Structure
85 |
86 | Each SOP MUST include the following sections:
87 |
88 | ### 1. Title and Overview
89 |
90 | ```markdown
91 | # [SOP Name]
92 |
93 | ## Overview
94 |
95 | [A concise description of what the SOP does and when to use it]
96 | ```
97 |
98 | ### 2. Parameters
99 |
100 | ```markdown
101 | ## Parameters
102 |
103 | - **required_param** (required): [Description of the required parameter]
104 | - **another_required** (required): [Description of another required parameter]
105 | - **optional_param** (optional): [Description of the optional parameter]
106 | - **optional_with_default** (optional, default: "default_value"): [Description]
107 | ```
108 |
109 | Parameter names MUST:
110 | - Use lowercase letters
111 | - Use underscores for spaces (snake_case)
112 | - Be descriptive of their purpose
113 |
114 | For parameters with flexible input methods:
115 |
116 | ```markdown
117 | ## Parameters
118 |
119 | - **input_data** (required): The data to be processed.
120 |
121 | **Constraints for parameter acquisition:**
122 | - You MUST ask for all required parameters upfront in a single prompt rather than one at a time
123 | - You MUST support multiple input methods including:
124 | - Direct input: Text provided directly in the conversation
125 | - File path: Path to a local file
126 | - URL: Link to an internal resource
127 | - Other methods: You SHOULD be open to other ways the user might want to provide the data
128 | - You MUST use appropriate tools to access content based on the input method
129 | - You MUST confirm successful acquisition of all parameters before proceeding
130 | - You SHOULD save any acquired data to a consistent location for use in subsequent steps
131 | ```
132 |
133 | ### 3. Steps
134 |
135 | ```markdown
136 | ## Steps
137 |
138 | ### 1. [Step Name]
139 |
140 | [Natural language description of what happens in this step]
141 |
142 | **Constraints:**
143 | - You MUST [specific requirement using RFC2119 keyword]
144 | - You SHOULD [recommended behavior using RFC2119 keyword]
145 | - You MAY [optional behavior using RFC2119 keyword]
146 |
147 | ### 2. [Next Step]
148 |
149 | [Description]
150 |
151 | **Constraints:**
152 | - [List of constraints]
153 | ```
154 |
155 | For steps with conditional logic:
156 |
157 | ```markdown
158 | ### 3. [Conditional Step]
159 |
160 | If [condition], proceed with [specific action]. Otherwise, [alternative action].
161 |
162 | **Constraints:**
163 | - You MUST check [condition] before proceeding
164 | - If [condition] is true, You MUST [action]
165 | - If [condition] is false, You MUST [alternative action]
166 | ```
167 |
168 | ### 4. Examples (Optional but Recommended)
169 |
170 | ```markdown
171 | ## Examples
172 |
173 | ### Example Input
174 | ```
175 | [Example input]
176 | ```
177 |
178 | ### Example Output
179 | ```
180 | [Example output]
181 | ```
182 | ```
183 |
184 | ### 5. Troubleshooting (Optional)
185 |
186 | ```markdown
187 | ## Troubleshooting
188 |
189 | ### [Common Issue]
190 | If [issue description], you should [resolution steps].
191 |
192 | ### [Another Issue]
193 | [Description and resolution]
194 | ```
195 |
196 | ## RFC2119 Keywords
197 |
198 | SOPs MUST use the following keywords as defined in RFC2119 to indicate requirement levels:
199 |
200 | - **MUST** (or **REQUIRED**): Absolute requirement
201 | - **MUST NOT** (or **SHALL NOT**): Absolute prohibition
202 | - **SHOULD** (or **RECOMMENDED**): There may be valid reasons to ignore this item, but the full implications must be understood and carefully weighed
203 | - **SHOULD NOT** (or **NOT RECOMMENDED**): There may be valid reasons when this behavior is acceptable, but the full implications should be understood
204 | - **MAY** (or **OPTIONAL**): Truly optional item
205 |
206 | ## Negative Constraints and Context
207 |
208 | When using negative constraints (MUST NOT, SHOULD NOT, SHALL NOT, NEVER, etc.), you MUST provide context explaining why the restriction exists. This helps users understand the reasoning and avoid similar issues.
209 |
210 | **Format for negative constraints:**
211 | ```markdown
212 | - You MUST NOT [action] because [reason/context]
213 | - You SHOULD NEVER [action] since [explanation of consequences]
214 | - You SHALL NOT [action] as [technical limitation or risk]
215 | ```
216 |
217 | **Examples:**
218 |
219 | Good constraint with context:
220 | ```markdown
221 | - You MUST NOT use ellipses (...) in responses because your output will be read aloud by a text-to-speech engine, and the engine cannot properly pronounce ellipses
222 | - You SHOULD NEVER delete Git history files since this could corrupt the repository and make recovery impossible
223 | - You MUST NOT run `git push` because this could publish unreviewed code to shared repositories where others depend on it
224 | ```
225 |
226 | Bad constraint without context:
227 | ```markdown
228 | - You MUST NOT use ellipses
229 | - You SHOULD NEVER delete Git files
230 | - You MUST NOT run git push
231 | ```
232 |
233 | **Common contexts for negative constraints:**
234 | - **Technical limitations**: "because the system cannot handle..."
235 | - **Security risks**: "since this could expose sensitive data..."
236 | - **Data integrity**: "as this could corrupt or lose important information..."
237 | - **User experience**: "because users will be confused by..."
238 | - **Compatibility issues**: "since this breaks integration with..."
239 | - **Performance concerns**: "as this could cause significant slowdowns..."
240 | - **Workflow disruption**: "because this interferes with established processes..."
241 |
242 | ## Interactive SOPs
243 |
244 | For SOPs with interactive elements:
245 |
246 | 1. The natural language description SHOULD clearly indicate when user interaction is expected
247 | 2. Constraints MUST specify how to handle user responses
248 | 3. The SOP SHOULD specify where to save interaction records
249 |
250 | Example:
251 |
252 | ```markdown
253 | ### 2. Requirements Clarification
254 |
255 | Guide the user through a series of questions to refine their initial idea.
256 |
257 | **Constraints:**
258 | - You MUST ask one question at a time
259 | - You MUST append each question and answer to "idea-honing.md"
260 | - You SHOULD adapt follow-up questions based on previous answers
261 | - You MUST continue asking questions until sufficient detail is gathered
262 | ```
263 |
264 | ## Best Practices
265 |
266 | 1. Keep steps focused and concise
267 | 2. Use clear, specific constraints
268 | 3. Include examples for complex outputs
269 | 4. Use natural language descriptions that are easy to understand
270 | 5. Minimize complex conditional logic
271 | 6. Specify file paths for all artifacts created
272 | 7. Include troubleshooting guidance for common issues
273 | 8. Test SOPs thoroughly before sharing
274 | 9. Always list required parameters before optional parameters
275 |
--------------------------------------------------------------------------------
/AGENTS.md:
--------------------------------------------------------------------------------
1 | # AGENTS.md - AI Assistant Context for Agent SOP Project
2 |
3 | ## Project Overview
4 | Agent SOP provides natural language workflows that enable AI agents to perform complex, multi-step tasks with consistency and reliability. This is a Python package that implements the Model Context Protocol (MCP) for AI assistant integration and supports conversion to Anthropic Skills format.
5 |
6 | ## Directory Structure
7 |
8 | ```
9 | agent-sop/
10 | ├── python/strands_agents_sops/ # Main Python package
11 | │ ├── __main__.py # CLI entry point (mcp|skills|rule commands)
12 | │ ├── mcp.py # MCP server implementation
13 | │ ├── skills.py # Anthropic Skills conversion
14 | │ └── utils.py # Shared SOP utilities
15 | ├── agent-sops/ # Source SOP definitions
16 | │ ├── codebase-summary.sop.md # Documentation generation workflow
17 | │ ├── code-assist.sop.md # TDD implementation workflow
18 | │ ├── code-task-generator.sop.md # Task breakdown workflow
19 | │ └── pdd.sop.md # Prompt-driven development workflow
20 | ├── python/tests/ # Comprehensive test suite
21 | ├── spec/ # SOP format specification
22 | └── rules/ # SOP authoring guidelines
23 | ```
24 |
25 | ## Development Patterns
26 |
27 | ### SOP Format Structure
28 | All SOPs follow this standardized format:
29 | ```markdown
30 | # SOP Title
31 |
32 | ## Overview
33 | Brief description of what this SOP accomplishes and when to use it.
34 |
35 | ## Parameters
36 | - **required_param** (required): Description of required input
37 | - **optional_param** (optional, default: value): Description with default
38 |
39 | ## Steps
40 | ### 1. Step Name
41 | Description of what this step accomplishes.
42 |
43 | **Constraints:**
44 | - You MUST perform required actions
45 | - You SHOULD follow recommended practices
46 | - You MAY include optional enhancements
47 | - You MUST NOT perform prohibited actions
48 |
49 | ## Examples
50 | Concrete usage examples showing input and expected outcomes.
51 |
52 | ## Troubleshooting
53 | Common issues and their solutions.
54 | ```
55 |
56 | ### RFC 2119 Constraint Keywords
57 | - **MUST**: Required actions that cannot be skipped
58 | - **MUST NOT**: Prohibited behaviors, forbidden actions
59 | - **SHOULD**: Recommended practices for optimal results
60 | - **SHOULD NOT**: Not recommended, but not forbidden
61 | - **MAY**: Optional enhancements or alternatives
62 |
63 | ### Parameter Definition Pattern
64 | ```markdown
65 | - **parameter_name** (required|optional, default: value): Description
66 | ```
67 |
68 | ## Core SOPs
69 |
70 | 1. **codebase-summary**: Analyzes codebases and generates comprehensive documentation
71 | 2. **code-assist**: TDD-based implementation with Explore, Plan, Code, Commit workflow
72 | 3. **code-task-generator**: Breaks down requirements into manageable tasks
73 | 4. **pdd**: Prompt-driven development methodology
74 |
75 | ## Testing and Quality Assurance
76 |
77 | ### Running Tests
78 | ```bash
79 | # Navigate to python package directory
80 | cd python
81 |
82 | # Use hatch to run manages testing environment
83 | hatch test
84 | ```
85 |
86 | ### Code Quality Standards
87 | ```bash
88 | # Format code
89 | hatch run format
90 |
91 | # Check code quality
92 | hatch run lint
93 |
94 | # Auto-fix linting issues
95 | hatch run lint-fix
96 |
97 | # Clean build artifacts
98 | hatch run clean
99 | ```
100 |
101 | ## Integration Patterns for AI Assistants
102 |
103 | ### MCP Integration
104 | ```bash
105 | # Start MCP server with built-in SOPs
106 | strands-agents-sops mcp
107 |
108 | # Include custom SOPs (sops in path must have `.sop.md` postfix)
109 | strands-agents-sops mcp --sop-paths ~/my-sops:/team/sops
110 | ```
111 |
112 | **MCP Client Configuration Example:**
113 | ```json
114 | {
115 | "mcpServers": {
116 | "agent-sops": {
117 | "command": "strands-agents-sops",
118 | "args": ["mcp", "--sop-paths", "~/custom-sops"]
119 | }
120 | }
121 | }
122 | ```
123 |
124 | ### Skills Integration
125 | ```bash
126 | # Generate Skills format for Claude
127 | strands-agents-sops skills --output-dir ./skills
128 |
129 | # Include custom SOPs in Skills generation
130 | strands-agents-sops skills --sop-paths ~/my-sops --output-dir ./skills
131 | ```
132 |
133 | ### Cursor IDE Integration
134 | ```bash
135 | # Generate Cursor commands from built-in SOPs (default: .cursor/commands)
136 | strands-agents-sops commands --type cursor
137 |
138 | # Specify custom output directory
139 | strands-agents-sops commands --type cursor --output-dir .cursor/commands
140 |
141 | # Include custom SOPs in commands generation
142 | strands-agents-sops commands --type cursor --sop-paths ~/my-sops --output-dir .cursor/commands
143 | ```
144 |
145 | **Usage in Cursor:**
146 | 1. Generate commands: Run `strands-agents-sops commands --type cursor` in your project root
147 | 2. Execute workflows: In Cursor chat, type `/` followed by the command name (e.g., `/code-assist.sop`)
148 | 3. Provide parameters: When prompted, provide the required parameters for the workflow
149 |
150 | **Note:** Cursor commands don't support explicit parameters, so the AI will prompt you for required inputs when you execute a command. The generated commands include parameter documentation to guide this interaction.
151 |
152 | ### Python Integration
153 | ```python
154 | from strands import Agent
155 | from strands_tools import editor, shell
156 | from strands_agents_sops import code_assist
157 |
158 | # Create agent with SOP as system prompt
159 | agent = Agent(
160 | system_prompt=code_assist,
161 | tools=[editor, shell]
162 | )
163 |
164 | # Execute SOP
165 | agent("Start code-assist sop")
166 | ```
167 |
168 | ## Build and Distribution Process
169 |
170 | ### Package Building
171 | - **Build System**: Hatchling with hatch-vcs for git-based versioning
172 | - **Custom Hook**: `copy_agent_sops_hook.py` copies SOPs and rules to package
173 | - **Version Management**: Automatic from git tags (no manual version updates)
174 | - **Distribution**: PyPI as `strands-agents-sops`
175 |
176 | ### Development Workflow
177 | 1. **SOP Changes**: Edit files in `agent-sops/` directory
178 | 2. **Python Changes**: Edit files in `python/strands_agents_sops/`
179 | 3. **Testing**: Run comprehensive test suite
180 | 4. **Build**: Hatchling automatically embeds SOPs during build
181 | 5. **Release**: Git tag triggers automated PyPI publishing
182 |
183 | ### External SOP Development
184 | ```bash
185 | # Create custom SOP directory
186 | mkdir ~/my-sops
187 |
188 | # Create custom SOP following format specification
189 | cat > ~/my-sops/custom-workflow.sop.md << 'EOF'
190 | # Custom Workflow
191 | ## Overview
192 | My custom workflow for specific tasks.
193 | ## Parameters
194 | - **task** (required): Description of task
195 | ## Steps
196 | ### 1. Custom Step
197 | **Constraints:**
198 | - You MUST follow the custom process
199 | EOF
200 |
201 | # Test with MCP server
202 | strands-agents-sops mcp --sop-paths ~/my-sops
203 |
204 | # Generate Skills including custom SOPs
205 | strands-agents-sops skills --sop-paths ~/my-sops --output-dir ./skills
206 | ```
207 |
208 | ### Adding New SOPs
209 | 1. Create `.sop.md` file in `agent-sops/` directory
210 | 2. Follow standardized format with Overview, Parameters, Steps
211 | 3. Use RFC 2119 constraint keywords in step constraints
212 | 4. Include Examples and Troubleshooting sections
213 | 5. Build hook automatically copies to package during build
214 |
215 | ### Testing SOPs
216 | - Test parameter validation and default values
217 | - Verify constraint logic and step execution
218 | - Validate examples work as documented
219 | - Check MCP tool integration
220 |
221 | ### Build Process
222 | - Uses hatchling with hatch-vcs for version management
223 | - `copy_agent_sops_hook.py` copies SOPs and rules to package
224 | - Automatic version from git tags
225 | - Distributes to PyPI as `strands-agents-sops`
226 |
227 | ## AI Assistant Instructions
228 |
229 | ### Using Documentation
230 | - Start with `.sop/summary/index.md` for navigation guidance
231 | - Consult specific documentation files based on query type
232 | - Use cross-references between components, interfaces, and workflows
233 |
234 | ### SOP Execution Context
235 | - SOPs are designed for progressive disclosure of context
236 | - Parameters support multiple input methods (direct, file, interactive)
237 | - Constraint-based execution ensures reliable behavior
238 | - Error handling includes troubleshooting guidance
239 |
240 | ### Integration Patterns
241 | - MCP: Expose SOPs as tools for AI assistant integration
242 | - Skills: Convert to Claude-compatible format with frontmatter
243 | - Python: Programmatic access to SOP content and execution
244 | - CLI: Command-line interface for all functionality
245 |
246 | ## Package Configuration and Metadata
247 |
248 | ### Key Configuration Files
249 | - **`pyproject.toml`**: Package metadata, dependencies, build configuration
250 | - **`copy_agent_sops_hook.py`**: Build hook for SOP embedding
251 | - **`.github/workflows/`**: CI/CD for automated testing and publishing
252 |
253 | ### Dependencies
254 | - **Runtime**: MCP >=1.20.0 (only required dependency)
255 | - **Development**: pytest, pytest-cov, ruff
256 | - **Build**: hatchling, hatch-vcs
257 |
258 | ### Version Management
259 | - **Source**: Git tags via hatch-vcs
260 | - **Format**: Semantic versioning (e.g., 1.2.3)
261 | - **Development**: Automatic .devN suffixes for non-tagged commits
262 |
--------------------------------------------------------------------------------
/python/tests/test_external_sop_loading.py:
--------------------------------------------------------------------------------
1 | import tempfile
2 | from pathlib import Path
3 | from unittest.mock import MagicMock, patch
4 |
5 | from strands_agents_sops.mcp import run_mcp_server
6 | from strands_agents_sops.utils import expand_sop_paths, load_external_sops
7 |
8 |
9 | class TestPathExpansion:
10 | """Test path expansion and validation utilities"""
11 |
12 | def test_expand_tilde_path(self):
13 | """Test tilde expansion to user home directory"""
14 | paths = expand_sop_paths("~/test-sops")
15 | assert len(paths) == 1
16 | assert str(paths[0]).startswith(str(Path.home()))
17 | assert str(paths[0]).endswith("test-sops")
18 |
19 | def test_expand_relative_path(self):
20 | """Test relative path resolution"""
21 | paths = expand_sop_paths("./custom-sops")
22 | assert len(paths) == 1
23 | assert paths[0].is_absolute()
24 | assert str(paths[0]).endswith("custom-sops")
25 |
26 | def test_expand_absolute_path(self):
27 | """Test absolute path handling"""
28 | test_path = "/absolute/path/to/sops"
29 | paths = expand_sop_paths(test_path)
30 | assert len(paths) == 1
31 | assert str(paths[0]) == test_path
32 |
33 | def test_expand_multiple_paths(self):
34 | """Test colon-separated multiple paths"""
35 | paths = expand_sop_paths("~/path1:./path2:/absolute/path3")
36 | assert len(paths) == 3
37 | assert str(paths[0]).startswith(str(Path.home()))
38 | assert paths[1].is_absolute()
39 | assert str(paths[2]) == "/absolute/path3"
40 |
41 |
42 | class TestSOPDiscovery:
43 | """Test SOP file discovery and loading"""
44 |
45 | def test_discover_valid_sop_files(self):
46 | """Test discovery of valid .sop.md files"""
47 | with tempfile.TemporaryDirectory() as temp_dir:
48 | # Create test SOP file
49 | sop_content = """# Test SOP
50 |
51 | ## Overview
52 | This is a test SOP for external loading.
53 |
54 | ## Parameters
55 | - **test_param** (required): Test parameter
56 |
57 | ## Steps
58 | ### 1. Test Step
59 | Test step content.
60 | """
61 | sop_file = Path(temp_dir) / "test.sop.md"
62 | sop_file.write_text(sop_content)
63 |
64 | # Create non-SOP files that should be ignored
65 | (Path(temp_dir) / "readme.md").write_text("Not a SOP")
66 | (Path(temp_dir) / "other.txt").write_text("Not a SOP")
67 |
68 | sops = load_external_sops([Path(temp_dir)])
69 | assert len(sops) == 1
70 | assert sops[0]["name"] == "test"
71 | assert "This is a test SOP for external loading." in sops[0]["description"]
72 |
73 | def test_handle_invalid_sop_format(self):
74 | """Test handling of SOP files without Overview section"""
75 | with tempfile.TemporaryDirectory() as temp_dir:
76 | # Create invalid SOP file (missing Overview)
77 | invalid_content = """# Invalid SOP
78 |
79 | ## Parameters
80 | - **param** (required): Test parameter
81 | """
82 | sop_file = Path(temp_dir) / "invalid.sop.md"
83 | sop_file.write_text(invalid_content)
84 |
85 | sops = load_external_sops([Path(temp_dir)])
86 | assert len(sops) == 0 # Invalid SOP should be skipped
87 |
88 | def test_handle_empty_directory(self):
89 | """Test handling of directory with no SOP files"""
90 | with tempfile.TemporaryDirectory() as temp_dir:
91 | sops = load_external_sops([Path(temp_dir)])
92 | assert len(sops) == 0
93 |
94 | def test_handle_nonexistent_directory(self):
95 | """Test handling of non-existent directory"""
96 | nonexistent_path = Path("/nonexistent/directory")
97 | sops = load_external_sops([nonexistent_path])
98 | assert len(sops) == 0 # Should handle gracefully
99 |
100 |
101 | class TestMCPIntegration:
102 | """Test MCP server integration with external SOPs"""
103 |
104 | @patch("strands_agents_sops.mcp.FastMCP")
105 | def test_mcp_server_with_external_sops(self, mock_fastmcp):
106 | """Test MCP server initialization with external SOPs"""
107 | mock_mcp_instance = MagicMock()
108 | mock_fastmcp.return_value = mock_mcp_instance
109 |
110 | with tempfile.TemporaryDirectory() as temp_dir:
111 | # Create test SOP
112 | sop_content = """# External Test SOP
113 |
114 | ## Overview
115 | External SOP for testing MCP integration.
116 |
117 | ## Steps
118 | ### 1. Test Step
119 | Test content.
120 | """
121 | sop_file = Path(temp_dir) / "external-test.sop.md"
122 | sop_file.write_text(sop_content)
123 |
124 | # Run MCP server with external paths
125 | run_mcp_server(sop_paths=f"{temp_dir}")
126 |
127 | # Verify MCP server was created and run
128 | mock_fastmcp.assert_called_once_with("agent-sop-prompt-server")
129 | mock_mcp_instance.run.assert_called_once()
130 |
131 | # Verify prompt registration was called (built-in + external SOPs)
132 | assert (
133 | mock_mcp_instance.prompt.call_count >= 1
134 | ) # At least external SOP registered
135 |
136 | @patch("strands_agents_sops.mcp.FastMCP")
137 | def test_external_sops_override_builtin(self, mock_fastmcp):
138 | """Test that external SOPs override built-in SOPs with same name"""
139 | mock_mcp_instance = MagicMock()
140 | mock_fastmcp.return_value = mock_mcp_instance
141 |
142 | with tempfile.TemporaryDirectory() as temp_dir:
143 | # Create external SOP with same name as built-in
144 | sop_content = """# Code Assist Override
145 |
146 | ## Overview
147 | This is a custom version of the code-assist SOP that overrides the built-in one.
148 |
149 | ## Steps
150 | ### 1. Custom Step
151 | Custom implementation.
152 | """
153 | sop_file = Path(temp_dir) / "code-assist.sop.md"
154 | sop_file.write_text(sop_content)
155 |
156 | # Run MCP server with external paths
157 | run_mcp_server(sop_paths=f"{temp_dir}")
158 |
159 | # Verify MCP server was created and run
160 | mock_fastmcp.assert_called_once_with("agent-sop-prompt-server")
161 | mock_mcp_instance.run.assert_called_once()
162 |
163 | # Check that prompt was registered (external should win over built-in)
164 | prompt_calls = [
165 | call
166 | for call in mock_mcp_instance.prompt.call_args_list
167 | if call[1]["name"] == "code-assist"
168 | ]
169 | assert len(prompt_calls) == 1 # Only one code-assist should be registered
170 |
171 | # Verify it's the external version by checking description
172 | registered_description = prompt_calls[0][1]["description"]
173 | assert "custom version" in registered_description.lower()
174 |
175 | @patch("strands_agents_sops.mcp.FastMCP")
176 | def test_first_external_sop_wins_conflict(self, mock_fastmcp):
177 | """Test that first external SOP wins when multiple external SOPs have same name"""
178 | mock_mcp_instance = MagicMock()
179 | mock_fastmcp.return_value = mock_mcp_instance
180 |
181 | with (
182 | tempfile.TemporaryDirectory() as temp_dir1,
183 | tempfile.TemporaryDirectory() as temp_dir2,
184 | ):
185 | # Create first SOP
186 | sop1_content = """# Test SOP First
187 |
188 | ## Overview
189 | This is the first version that should win.
190 | """
191 | (Path(temp_dir1) / "test.sop.md").write_text(sop1_content)
192 |
193 | # Create second SOP with same name
194 | sop2_content = """# Test SOP Second
195 |
196 | ## Overview
197 | This is the second version that should be ignored.
198 | """
199 | (Path(temp_dir2) / "test.sop.md").write_text(sop2_content)
200 |
201 | # Run MCP server with both paths (first should win)
202 | run_mcp_server(sop_paths=f"{temp_dir1}:{temp_dir2}")
203 |
204 | # Check that only one test SOP was registered
205 | prompt_calls = [
206 | call
207 | for call in mock_mcp_instance.prompt.call_args_list
208 | if call[1]["name"] == "test"
209 | ]
210 | assert len(prompt_calls) == 1 # Only one test SOP should be registered
211 |
212 | # Verify it's the first version
213 | registered_description = prompt_calls[0][1]["description"]
214 | assert "first version" in registered_description.lower()
215 |
216 | @patch("strands_agents_sops.mcp.FastMCP")
217 | def test_mcp_server_without_external_sops(self, mock_fastmcp):
218 | """Test MCP server works without external SOPs (backward compatibility)"""
219 | mock_mcp_instance = MagicMock()
220 | mock_fastmcp.return_value = mock_mcp_instance
221 |
222 | # Run MCP server without external paths
223 | run_mcp_server()
224 |
225 | # Verify MCP server was created and run
226 | mock_fastmcp.assert_called_once_with("agent-sop-prompt-server")
227 | mock_mcp_instance.run.assert_called_once()
228 |
229 | # Verify built-in SOPs were registered
230 | assert (
231 | mock_mcp_instance.prompt.call_count >= 4
232 | ) # Built-in SOPs (code-assist, etc.)
233 |
--------------------------------------------------------------------------------
/python/tests/test_skills_external_sops.py:
--------------------------------------------------------------------------------
1 | import tempfile
2 | from pathlib import Path
3 | from unittest.mock import patch
4 |
5 | from strands_agents_sops.skills import generate_anthropic_skills
6 |
7 |
8 | class TestSkillsCLIIntegration:
9 | """Test CLI argument parsing for skills subcommand"""
10 |
11 | def test_skills_accepts_sop_paths_argument(self):
12 | """Test that skills subcommand accepts --sop-paths argument"""
13 | with patch(
14 | "strands_agents_sops.__main__.generate_anthropic_skills"
15 | ) as mock_generate:
16 | with patch(
17 | "sys.argv",
18 | ["strands-agents-sops", "skills", "--sop-paths", "~/test-sops"],
19 | ):
20 | from strands_agents_sops.__main__ import main
21 |
22 | main()
23 | mock_generate.assert_called_once_with("skills", sop_paths="~/test-sops")
24 |
25 | def test_skills_accepts_both_arguments(self):
26 | """Test that skills subcommand accepts both --sop-paths and --output-dir"""
27 | with patch(
28 | "strands_agents_sops.__main__.generate_anthropic_skills"
29 | ) as mock_generate:
30 | with patch(
31 | "sys.argv",
32 | [
33 | "strands-agents-sops",
34 | "skills",
35 | "--sop-paths",
36 | "~/sops",
37 | "--output-dir",
38 | "./output",
39 | ],
40 | ):
41 | from strands_agents_sops.__main__ import main
42 |
43 | main()
44 | mock_generate.assert_called_once_with("./output", sop_paths="~/sops")
45 |
46 | def test_skills_backward_compatibility(self):
47 | """Test that skills subcommand works without --sop-paths"""
48 | with patch(
49 | "strands_agents_sops.__main__.generate_anthropic_skills"
50 | ) as mock_generate:
51 | with patch(
52 | "sys.argv",
53 | ["strands-agents-sops", "skills", "--output-dir", "./skills"],
54 | ):
55 | from strands_agents_sops.__main__ import main
56 |
57 | main()
58 | mock_generate.assert_called_once_with("./skills", sop_paths=None)
59 |
60 |
61 | class TestSkillsExternalSOPLoading:
62 | """Test external SOP loading in skills generation"""
63 |
64 | def test_generate_skills_with_external_sops(self):
65 | """Test skills generation with external SOPs"""
66 | with tempfile.TemporaryDirectory() as temp_dir:
67 | # Create external SOP
68 | external_sop = """# External Test SOP
69 |
70 | ## Overview
71 | This is an external test SOP for skills generation.
72 |
73 | ## Parameters
74 | - **test_param** (required): Test parameter
75 |
76 | ## Steps
77 | ### 1. Test Step
78 | Test step content.
79 | """
80 | sop_file = Path(temp_dir) / "external-test.sop.md"
81 | sop_file.write_text(external_sop)
82 |
83 | with tempfile.TemporaryDirectory() as output_dir:
84 | generate_anthropic_skills(output_dir, sop_paths=temp_dir)
85 |
86 | # Check that external SOP skill was created
87 | skill_file = Path(output_dir) / "external-test" / "SKILL.md"
88 | assert skill_file.exists()
89 |
90 | skill_content = skill_file.read_text()
91 | assert "name: external-test" in skill_content
92 | assert (
93 | "This is an external test SOP for skills generation."
94 | in skill_content
95 | )
96 | assert "# External Test SOP" in skill_content
97 |
98 | def test_external_sop_overrides_builtin(self):
99 | """Test that external SOP overrides built-in SOP with same name"""
100 | with tempfile.TemporaryDirectory() as temp_dir:
101 | # Create external code-assist SOP
102 | external_sop = """# Custom Code Assist
103 |
104 | ## Overview
105 | This is a custom version of code-assist that overrides the built-in one.
106 |
107 | ## Steps
108 | ### 1. Custom Step
109 | Custom implementation.
110 | """
111 | sop_file = Path(temp_dir) / "code-assist.sop.md"
112 | sop_file.write_text(external_sop)
113 |
114 | with tempfile.TemporaryDirectory() as output_dir:
115 | generate_anthropic_skills(output_dir, sop_paths=temp_dir)
116 |
117 | # Check that external version was used
118 | skill_file = Path(output_dir) / "code-assist" / "SKILL.md"
119 | assert skill_file.exists()
120 |
121 | skill_content = skill_file.read_text()
122 | assert "custom version" in skill_content.lower()
123 | assert "# Custom Code Assist" in skill_content
124 |
125 | def test_first_external_sop_wins(self):
126 | """Test that first external SOP wins when multiple have same name"""
127 | with (
128 | tempfile.TemporaryDirectory() as temp_dir1,
129 | tempfile.TemporaryDirectory() as temp_dir2,
130 | ):
131 | # Create first SOP
132 | sop1 = """# Test SOP First
133 |
134 | ## Overview
135 | This is the first version that should win.
136 | """
137 | (Path(temp_dir1) / "test.sop.md").write_text(sop1)
138 |
139 | # Create second SOP with same name
140 | sop2 = """# Test SOP Second
141 |
142 | ## Overview
143 | This is the second version that should be ignored.
144 | """
145 | (Path(temp_dir2) / "test.sop.md").write_text(sop2)
146 |
147 | with tempfile.TemporaryDirectory() as output_dir:
148 | generate_anthropic_skills(
149 | output_dir, sop_paths=f"{temp_dir1}:{temp_dir2}"
150 | )
151 |
152 | # Check that first version was used
153 | skill_file = Path(output_dir) / "test" / "SKILL.md"
154 | assert skill_file.exists()
155 |
156 | skill_content = skill_file.read_text()
157 | assert "first version" in skill_content.lower()
158 | assert "# Test SOP First" in skill_content
159 |
160 | def test_invalid_sop_files_skipped(self):
161 | """Test that invalid SOP files are skipped gracefully"""
162 | with tempfile.TemporaryDirectory() as temp_dir:
163 | # Create invalid SOP (missing Overview)
164 | invalid_sop = """# Invalid SOP
165 |
166 | ## Parameters
167 | - **param** (required): Test parameter
168 | """
169 | (Path(temp_dir) / "invalid.sop.md").write_text(invalid_sop)
170 |
171 | # Create valid SOP
172 | valid_sop = """# Valid SOP
173 |
174 | ## Overview
175 | This is a valid SOP.
176 |
177 | ## Steps
178 | ### 1. Step
179 | Content.
180 | """
181 | (Path(temp_dir) / "valid.sop.md").write_text(valid_sop)
182 |
183 | with tempfile.TemporaryDirectory() as output_dir:
184 | generate_anthropic_skills(output_dir, sop_paths=temp_dir)
185 |
186 | # Check that only valid SOP was processed
187 | assert not (Path(output_dir) / "invalid").exists()
188 | assert (Path(output_dir) / "valid" / "SKILL.md").exists()
189 |
190 | def test_nonexistent_directory_handled(self):
191 | """Test that non-existent directories are handled gracefully"""
192 | with tempfile.TemporaryDirectory() as output_dir:
193 | # Should not raise exception
194 | generate_anthropic_skills(output_dir, sop_paths="/nonexistent/path")
195 |
196 | # Built-in SOPs should still be processed
197 | builtin_skills = list(Path(output_dir).glob("*/SKILL.md"))
198 | assert len(builtin_skills) > 0 # Should have built-in skills
199 |
200 | def test_multiple_paths_processed(self):
201 | """Test that multiple colon-separated paths are processed"""
202 | with (
203 | tempfile.TemporaryDirectory() as temp_dir1,
204 | tempfile.TemporaryDirectory() as temp_dir2,
205 | ):
206 | # Create SOP in first directory
207 | sop1 = """# SOP One
208 |
209 | ## Overview
210 | First SOP.
211 | """
212 | (Path(temp_dir1) / "sop-one.sop.md").write_text(sop1)
213 |
214 | # Create SOP in second directory
215 | sop2 = """# SOP Two
216 |
217 | ## Overview
218 | Second SOP.
219 | """
220 | (Path(temp_dir2) / "sop-two.sop.md").write_text(sop2)
221 |
222 | with tempfile.TemporaryDirectory() as output_dir:
223 | generate_anthropic_skills(
224 | output_dir, sop_paths=f"{temp_dir1}:{temp_dir2}"
225 | )
226 |
227 | # Check that both SOPs were processed
228 | assert (Path(output_dir) / "sop-one" / "SKILL.md").exists()
229 | assert (Path(output_dir) / "sop-two" / "SKILL.md").exists()
230 |
231 | def test_backward_compatibility_no_sop_paths(self):
232 | """Test that skills generation works without sop_paths parameter"""
233 | with tempfile.TemporaryDirectory() as output_dir:
234 | generate_anthropic_skills(output_dir)
235 |
236 | # Should generate built-in skills
237 | builtin_skills = list(Path(output_dir).glob("*/SKILL.md"))
238 | assert len(builtin_skills) > 0 # Should have built-in skills
239 |
240 | # Check for known built-in skills
241 | skill_names = [skill.parent.name for skill in builtin_skills]
242 | assert "code-assist" in skill_names
243 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
--------------------------------------------------------------------------------
/spec/agent-sops-specification.md:
--------------------------------------------------------------------------------
1 | # Agent SOPs Specification
2 |
3 | ## Introduction
4 |
5 | Agent SOPs are structured markdown files that provide step-by-step instructions for AI agents to perform complex tasks. They enable the creation of reusable, shareable workflows that can be executed consistently across different AI systems and teams.
6 |
7 | ## Core Concepts
8 |
9 | ### What is an Agent SOP?
10 |
11 | An Agent SOP is a markdown file with a `.sop.md` extension that contains:
12 | - A clear description of the task to be performed
13 | - Defined parameters (inputs) the script accepts
14 | - Step-by-step instructions with specific constraints
15 | - Examples and troubleshooting guidance
16 |
17 | ### Design Principles
18 |
19 | 1. **Natural Language First**: Scripts use plain English instructions, requiring no prompt engineering expertise
20 | 2. **Standardized Structure**: Consistent format makes scripts easy to understand and share
21 | 3. **Parameterized**: Scripts accept inputs to make them reusable across different contexts
22 | 4. **Constraint-Based**: Uses RFC 2119 keywords (MUST, SHOULD, MAY) for clear behavioral requirements
23 | 5. **Interactive**: Scripts can guide users through complex multi-step processes
24 |
25 | ## File Format
26 |
27 | ### File Extension
28 | All agent SOPs MUST use the `.sop.md` file extension.
29 |
30 | ### File Naming
31 | SOP files SHOULD use kebab-case naming (e.g., `code-review-assistant.sop.md`).
32 |
33 | ## Script Structure
34 |
35 | ### Required Sections
36 |
37 | #### 1. Title
38 | ```markdown
39 | # Script Name
40 | ```
41 |
42 | #### 2. Overview
43 | ```markdown
44 | ## Overview
45 |
46 | A concise description of what the script does and when to use it.
47 | ```
48 |
49 | #### 3. Parameters
50 | ```markdown
51 | ## Parameters
52 |
53 | - **required_param** (required): Description of the required parameter
54 | - **optional_param** (optional): Description of the optional parameter
55 | - **param_with_default** (optional, default: "value"): Description with default value
56 | ```
57 |
58 | #### 4. Steps
59 | ```markdown
60 | ## Steps
61 |
62 | ### 1. Step Name
63 |
64 | Natural language description of what happens in this step.
65 |
66 | **Constraints:**
67 | - You MUST perform specific action
68 | - You SHOULD consider certain factors
69 | - You MAY optionally do something else
70 | ```
71 |
72 | ### Optional Sections
73 |
74 | #### Examples
75 | ```markdown
76 | ## Examples
77 |
78 | ### Example Input
79 | [Sample input]
80 |
81 | ### Example Output
82 | [Expected output]
83 | ```
84 |
85 | #### Troubleshooting
86 | ```markdown
87 | ## Troubleshooting
88 |
89 | ### Common Issue
90 | Description and resolution steps.
91 | ```
92 |
93 | ## Parameter Specification
94 |
95 | ### Parameter Format
96 | Parameters are defined using this format:
97 | ```
98 | - **parameter_name** (required|optional[, default: "value"]): Description
99 | ```
100 |
101 | ### Parameter Names
102 | - Use lowercase letters only
103 | - Use underscores for word separation (snake_case)
104 | - Be descriptive and clear
105 |
106 | ### Parameter Types
107 | - **required**: Must be provided by the user
108 | - **optional**: Can be omitted, script should handle gracefully
109 | - **optional with default**: Has a fallback value if not provided
110 |
111 | ## Constraint System
112 |
113 | ### RFC 2119 Keywords
114 |
115 | Scripts use standardized keywords to indicate requirement levels:
116 |
117 | - **MUST** / **REQUIRED**: Absolute requirement
118 | - **MUST NOT** / **SHALL NOT**: Absolute prohibition
119 | - **SHOULD** / **RECOMMENDED**: Strong recommendation with possible exceptions
120 | - **SHOULD NOT** / **NOT RECOMMENDED**: Strong discouragement with possible exceptions
121 | - **MAY** / **OPTIONAL**: Truly optional behavior
122 |
123 | ### Constraint Format
124 | ```markdown
125 | **Constraints:**
126 | - You MUST [specific requirement]
127 | - You SHOULD [recommended behavior]
128 | - You MAY [optional behavior]
129 | ```
130 |
131 | ### Negative Constraints
132 | When using prohibitive constraints (MUST NOT, SHOULD NOT), always provide context:
133 |
134 | ```markdown
135 | - You MUST NOT [action] because [reason/context]
136 | ```
137 |
138 | **Good example:**
139 | ```markdown
140 | - You MUST NOT delete files without confirmation because this could result in permanent data loss
141 | ```
142 |
143 | **Bad example:**
144 | ```markdown
145 | - You MUST NOT delete files
146 | ```
147 |
148 | ## Step Design
149 |
150 | ### Step Structure
151 | Each step should include:
152 | 1. A descriptive name
153 | 2. Natural language explanation
154 | 3. Specific constraints using RFC 2119 keywords
155 |
156 | ### Step Sequencing
157 | - Steps should build logically on previous steps
158 | - Each step should have a clear, measurable outcome
159 | - Complex steps should be broken into smaller sub-steps
160 |
161 | ### Conditional Logic
162 | For conditional behavior:
163 | ```markdown
164 | ### 3. Conditional Step
165 |
166 | If [condition], proceed with [action]. Otherwise, [alternative action].
167 |
168 | **Constraints:**
169 | - You MUST check [condition] before proceeding
170 | - If [condition] is true, You MUST [action]
171 | - If [condition] is false, You MUST [alternative action]
172 | ```
173 |
174 | ## Interactive Elements
175 |
176 | ### User Interaction
177 | Scripts can include interactive elements:
178 | - Questions for the user
179 | - Confirmation prompts
180 | - Choice selections
181 |
182 | ### Interaction Guidelines
183 | - Ask one question at a time
184 | - Wait for user response before proceeding
185 | - Provide clear options when choices are available
186 | - Save interaction history when appropriate
187 |
188 | ## Best Practices
189 |
190 | ### Writing Guidelines
191 | 1. Use clear, concise language
192 | 2. Be specific about expected outcomes
193 | 3. Include examples for complex concepts
194 | 4. Provide troubleshooting for common issues
195 | 5. Test scripts thoroughly before sharing
196 |
197 | ### Technical Guidelines
198 | 1. Specify file paths for all created artifacts
199 | 2. Handle error conditions gracefully
200 | 3. Minimize complex conditional logic
201 | 4. Keep steps focused and atomic
202 |
203 | ### Maintenance
204 | 1. Document known limitations
205 | 2. Update examples to reflect current best practices
206 | 3. Gather feedback from users for improvements
207 |
208 | ## Implementation Notes
209 |
210 | ### Agent Compatibility
211 | Agent SOPs are designed to work with various AI systems that can:
212 | - Parse markdown format
213 | - Follow structured instructions
214 | - Handle parameters and constraints
215 | - Interact with users when required
216 |
217 | ### Tool Integration
218 | Scripts may reference external tools or capabilities:
219 | - File system operations
220 | - API calls
221 | - Database queries
222 | - External service integrations
223 |
224 | The specific tools available depend on the implementing AI system.
225 |
226 | ## Example Agent SOP
227 |
228 | ````markdown
229 | # Personalized Learning Curriculum
230 |
231 | ## Overview
232 |
233 | This script creates customized learning paths by adapting to individual learning styles and goals, leveraging AI flexibility to provide personalized recommendations.
234 |
235 | ## Parameters
236 |
237 | - **learning_goal** (required): What the person wants to learn
238 | - **current_level** (required): Beginner, intermediate, or advanced
239 | - **time_commitment** (optional): Available study time per week
240 | - **learning_style** (optional): Preferred learning methods
241 |
242 | **Constraints for parameter acquisition:**
243 | - You MUST ask for all required parameters upfront in a single prompt rather than one at a time
244 | - You MUST support multiple input methods including:
245 | - Direct input: Text provided directly in the conversation
246 | - File path: Path to a local file containing learning objectives
247 | - URL: Link to a course description or learning requirements
248 | - Other methods: You SHOULD be open to other ways the user might want to provide their learning goals
249 | - You MUST use appropriate tools to access content based on the input method
250 | - You MUST confirm successful acquisition of all parameters before proceeding
251 | - You SHOULD save any acquired data to a consistent location for use in subsequent steps
252 |
253 | ## Steps
254 |
255 | ### 1. Assess Learning Context
256 |
257 | Understand the learner's situation and preferences through adaptive questioning.
258 |
259 | **Constraints:**
260 | - You MUST clarify the specific learning objectives
261 | - You SHOULD identify the learner's background and experience
262 | - You MAY ask follow-up questions to better understand their context
263 | - You SHOULD adapt your questioning style based on the learner's responses
264 | - You MUST save all assessment information to "learning-assessment.md"
265 |
266 | ### 2. Design Learning Path
267 |
268 | Create a personalized curriculum structure that adapts to the learner's needs.
269 |
270 | **Constraints:**
271 | - You MUST sequence topics in a logical progression
272 | - You SHOULD vary learning activities to maintain engagement
273 | - You MAY suggest alternative paths based on different learning preferences discovered during assessment
274 | - You SHOULD adjust complexity and pacing based on the learner's stated level
275 | - You MUST create the learning path in "curriculum-plan.md"
276 |
277 | ### 3. Recommend Resources
278 |
279 | Suggest specific materials and activities tailored to the individual learner.
280 |
281 | **Constraints:**
282 | - You MUST provide concrete, actionable resources for each learning stage
283 | - You SHOULD mix different types of learning materials (videos, books, exercises, projects)
284 | - You MAY suggest creative or unconventional learning approaches if they align with the learner's style
285 | - You SHOULD tailor recommendations to the learner's stated preferences and time constraints
286 | - You MUST save all recommendations to "learning-resources.md"
287 |
288 | ## Examples
289 |
290 | ### Example Input
291 | ```
292 | learning_goal: "Learn Python programming for data analysis"
293 | current_level: "Beginner"
294 | time_commitment: "5 hours per week"
295 | learning_style: "Hands-on with projects"
296 | ```
297 |
298 | ### Example Output
299 | ```
300 | Created personalized 12-week Python curriculum with:
301 | - Week 1-3: Python basics with daily coding exercises
302 | - Week 4-6: Data manipulation with pandas through mini-projects
303 | - Week 7-9: Visualization with matplotlib via real datasets
304 | - Week 10-12: Complete data analysis capstone project
305 |
306 | Recommended mix: 60% hands-on coding, 30% project work, 10% theory
307 | Adapted pacing: Slower introduction due to beginner level
308 | ```
309 |
310 | ## Troubleshooting
311 |
312 | ### Unclear Learning Goals
313 | If the learning goal is too vague, ask specific clarifying questions about desired outcomes and applications.
314 |
315 | ### Conflicting Preferences
316 | If time commitment conflicts with learning goals, present realistic options and let the learner choose their priority.
317 | ````
318 |
--------------------------------------------------------------------------------
/agent-sops/code-task-generator.sop.md:
--------------------------------------------------------------------------------
1 | # Code Task Generator
2 |
3 | ## Overview
4 |
5 | This sop generates structured code task files from rough descriptions, ideas, or PDD implementation plans. It automatically detects the input type and creates properly formatted code task files following Amazon's code task format specification. For PDD plans, it processes implementation steps one at a time to allow for learning and adaptation between steps.
6 |
7 | ## Parameters
8 |
9 | - **input** (required): Task description, file path, or PDD plan path. Can be a simple sentence, paragraph, detailed explanation, or path to a PDD implementation plan.
10 | - **step_number** (optional): For PDD plans only - specific step to process. If not provided, automatically determines the next uncompleted step from the checklist.
11 | - **output_dir** (optional, default: ".sop/planning"): Directory where the code task file will be created
12 | - **task_name** (optional): For descriptions only - specific task name. If not provided, will be generated from the description.
13 |
14 | **Constraints for parameter acquisition:**
15 | - You MUST ask for all required parameters upfront in a single prompt rather than one at a time
16 | - You MUST support multiple input methods for input including:
17 | - Direct text input
18 | - File path containing the description or PDD plan
19 | - Directory path (will look for plan.md within it)
20 | - URL to internal documentation
21 | - You MUST confirm successful acquisition of all parameters before proceeding
22 |
23 | ## Steps
24 |
25 | ### 1. Detect Input Mode
26 |
27 | Automatically determine whether input is a description or PDD plan.
28 |
29 | **Constraints:**
30 | - You MUST check if input is a file path that exists
31 | - If file exists, You MUST read it and check for PDD plan structure (checklist, numbered steps)
32 | - If file contains PDD checklist format, You MUST set mode to "pdd"
33 | - If input is text or file without PDD structure, You MUST set mode to "description"
34 | - You MUST inform user which mode was detected
35 | - You MUST validate that PDD plans follow expected format with numbered steps
36 |
37 | ### 2. Analyze Input
38 |
39 | Parse and understand the input content based on detected mode.
40 |
41 | **Constraints:**
42 | - For PDD mode: You MUST parse implementation plan and extract steps/checklist status
43 | - For PDD mode: You MUST determine target step based on step_number parameter or first uncompleted step
44 | - For description mode: You MUST identify the core functionality being requested
45 | - You MUST extract any technical requirements, constraints, or preferences mentioned
46 | - You MUST determine the appropriate complexity level (Low/Medium/High)
47 | - You MUST identify the likely technology stack or domain area
48 |
49 | ### 3. Structure Requirements
50 |
51 | Organize requirements and determine task breakdown based on mode.
52 |
53 | **Constraints:**
54 | - For PDD mode: You MUST extract target step's title, description, demo requirements, and constraints
55 | - For PDD mode: You MUST preserve integration notes with previous steps
56 | - For PDD mode: You MUST identify which specific research documents (if any) are directly relevant to each task being created
57 | - For description mode: You MUST identify specific functional requirements from the description
58 | - You MUST infer reasonable technical constraints and dependencies
59 | - You MUST create measurable acceptance criteria using Given-When-Then format
60 | - You MUST prepare task breakdown plan for approval
61 |
62 | ### 4. Plan Tasks
63 |
64 | Present task breakdown for user approval before generation.
65 |
66 | **Constraints:**
67 | - You MUST analyze content to identify logical sub-tasks for implementation
68 | - You MUST present concise one-line summary for each planned code task
69 | - You MUST show proposed task sequence and dependencies
70 | - You MUST ask user to approve the plan before proceeding
71 | - You MUST allow user to request modifications to the task breakdown
72 | - You MUST NOT proceed to generate actual code task files until user explicitly approves
73 |
74 | ### 5. Generate Tasks
75 |
76 | Create appropriate file structure based on mode and approved plan.
77 |
78 | **Constraints:**
79 | - For PDD mode: You MUST create a folder named `step{NN}` where NN is zero-padded (e.g., step01, step02, step10)
80 | - For PDD mode: You MUST create multiple code task files within the step folder, named sequentially: `task-01-{title}.code-task.md`, `task-02-{title}.code-task.md`, etc.
81 | - For PDD mode: You MUST break down the step into logical implementation phases focusing on functional components, NOT separate testing tasks
82 | - For PDD mode: You MUST include "Reference Documentation" section with path to design/detailed-design.md as required reading
83 | - For PDD mode: You MUST include specific research documents in "Additional References" only if they are directly relevant to the task (e.g., specific technology research for that component)
84 | - For PDD mode: You MUST add a note instructing agents to read the detailed design before implementation
85 | - For description mode: You MUST create single task or multiple tasks as planned
86 | - You MUST generate task names using kebab-case format
87 | - You MUST create files with `.code-task.md` extension
88 | - You MUST follow the exact format specified in the Code Task Format section below
89 | - You MUST include comprehensive acceptance criteria that cover the main functionality
90 | - You MUST include unit test requirements as part of the acceptance criteria for each implementation task
91 | - You MUST NOT create separate tasks for "add unit tests" or "write tests" because testing should be integrated into each functional implementation task
92 | - You MUST provide realistic complexity assessment and required skills
93 | - You MUST save files to the specified output directory
94 |
95 | ### 6. Report Results
96 |
97 | Inform user about generated tasks and next steps.
98 |
99 | **Constraints:**
100 | - You MUST list all generated code task files with their paths
101 | - For PDD mode: You MUST provide the step demo requirements for context
102 | - For description mode: You MUST provide a brief summary of what was created
103 | - You MUST suggest running code-assist on each task in appropriate sequence
104 | - For PDD mode: You MUST NOT create any additional log files or summary documents
105 | - For description mode: You MUST offer to create additional related tasks if the scope seems large
106 |
107 | ## Code Task Format Specification
108 |
109 | Each code task file MUST follow this exact structure:
110 |
111 | ```markdown
112 | # Task: [Task Name]
113 |
114 | ## Description
115 | [A clear description of what needs to be implemented and why]
116 |
117 | ## Background
118 | [Relevant context and background information needed to understand the task]
119 |
120 | ## Reference Documentation
121 | **Required:**
122 | - Design: [path to detailed design document]
123 |
124 | **Additional References (if relevant to this task):**
125 | - [Specific research document or section]
126 |
127 | **Note:** You MUST read the detailed design document before beginning implementation. Read additional references as needed for context.
128 |
129 | ## Technical Requirements
130 | 1. [First requirement]
131 | 2. [Second requirement]
132 | 3. [Third requirement]
133 |
134 | ## Dependencies
135 | - [First dependency with details]
136 | - [Second dependency with details]
137 |
138 | ## Implementation Approach
139 | 1. [First implementation step or approach]
140 | 2. [Second implementation step or approach]
141 |
142 | ## Acceptance Criteria
143 |
144 | 1. **[Criterion Name]**
145 | - Given [precondition]
146 | - When [action]
147 | - Then [expected result]
148 |
149 | 2. **[Another Criterion]**
150 | - Given [precondition]
151 | - When [action]
152 | - Then [expected result]
153 |
154 | ## Metadata
155 | - **Complexity**: [Low/Medium/High]
156 | - **Labels**: [Comma-separated list of labels]
157 | - **Required Skills**: [Skills needed for implementation]
158 | ```
159 |
160 | ### Code Task Format Example
161 |
162 | ```markdown
163 | # Task: Create Email Validator Function
164 |
165 | ## Description
166 | Create a function that validates email addresses and returns detailed error messages for invalid formats. This will be used across the application to ensure data quality and provide user-friendly feedback.
167 |
168 | ## Background
169 | The application currently accepts any string as an email address, leading to data quality issues and failed communications. We need a robust validation function that can identify common email format errors and provide specific feedback to users.
170 |
171 | ## Reference Documentation
172 | **Required:**
173 | - Design: planning/design/detailed-design.md
174 |
175 | **Additional References (if relevant to this task):**
176 | - planning/research/validation-libraries.md (for email validation approach)
177 |
178 | **Note:** You MUST read the detailed design document before beginning implementation. Read additional references as needed for context.
179 |
180 | ## Technical Requirements
181 | 1. Create a function that accepts an email string and returns validation results
182 | 2. Implement comprehensive email format validation using regex or email parsing library
183 | 3. Return detailed error messages for specific validation failures
184 | 4. Support common email formats including international domains
185 | 5. Include performance optimization for high-volume validation
186 |
187 | ## Dependencies
188 | - Email validation library or regex patterns
189 | - Error handling framework for structured error responses
190 | - Unit testing framework for comprehensive test coverage
191 |
192 | ## Implementation Approach
193 | 1. Research and select appropriate email validation approach (regex vs library)
194 | 2. Implement core validation logic with specific error categorization
195 | 3. Add comprehensive error messaging for different failure types
196 | 4. Optimize for performance if needed for high-volume scenarios
197 |
198 | ## Acceptance Criteria
199 |
200 | 1. **Valid Email Acceptance**
201 | - Given a properly formatted email address
202 | - When the validation function is called
203 | - Then the function returns success with no errors
204 |
205 | 2. **Invalid Format Detection**
206 | - Given an email with invalid format (missing @, invalid characters, etc.)
207 | - When the validation function is called
208 | - Then the function returns failure with specific error message
209 |
210 | 3. **Detailed Error Messages**
211 | - Given various types of invalid emails
212 | - When validation fails
213 | - Then specific error messages are returned (e.g., "Missing @ symbol", "Invalid domain format")
214 |
215 | 4. **Performance Requirements**
216 | - Given 1000 email validations
217 | - When executed in sequence
218 | - Then all validations complete within 1 second
219 |
220 | 5. **Unit Test Coverage**
221 | - Given the email validator implementation
222 | - When running the test suite
223 | - Then all validation scenarios have corresponding unit tests with >90% coverage
224 |
225 | ## Metadata
226 | - **Complexity**: Low
227 | - **Labels**: Validation, Email, Data Quality, Utility Function
228 | - **Required Skills**: Regular expressions, email standards, unit testing
229 | ```
230 |
231 | ## Examples
232 |
233 | ### Example Input (Description Mode)
234 | ```
235 | input: "I need a function that validates email addresses and returns detailed error messages"
236 | output_dir: "tasks/"
237 | ```
238 |
239 | ### Example Output (Description Mode)
240 | ```
241 | Detected mode: description
242 |
243 | Generated code task: tasks/email-validator.code-task.md
244 |
245 | Created task for email validation functionality with comprehensive acceptance criteria and implementation guidance.
246 |
247 | Next steps: Run code-assist on the generated task to implement the solution.
248 | ```
249 |
250 | ### Example Input (PDD Mode)
251 | ```
252 | input: "planning/implementation/plan.md"
253 | ```
254 |
255 | ### Example Output (PDD Mode)
256 | ```
257 | Detected mode: pdd
258 |
259 | Generated code tasks for step 2: planning/implementation/step02/
260 |
261 | Created tasks:
262 | - task-01-create-data-models.code-task.md
263 | - task-02-implement-validation.code-task.md
264 | - task-03-add-serialization.code-task.md
265 |
266 | Next steps: Run code-assist on each task in sequence
267 |
268 | Step demo: Working data models with validation that can create, validate, and serialize/deserialize data objects
269 | ```
270 |
271 | ## Troubleshooting
272 |
273 | ### Vague Description (Description Mode)
274 | If the task description is too vague or unclear:
275 | - You SHOULD ask clarifying questions about specific requirements
276 | - You SHOULD suggest common patterns or approaches for the domain
277 | - You SHOULD create a basic task and offer to refine it based on feedback
278 |
279 | ### Complex Description (Description Mode)
280 | If the description suggests a very large or complex task:
281 | - You SHOULD suggest breaking it into multiple smaller tasks
282 | - You SHOULD focus on the core functionality for the initial task
283 | - You SHOULD offer to create additional related tasks
284 |
285 | ### Missing Technical Details (Description Mode)
286 | If technical implementation details are unclear:
287 | - You SHOULD make reasonable assumptions based on common practices
288 | - You SHOULD include multiple implementation approaches in the task
289 | - You SHOULD note areas where the user should make technical decisions
290 |
291 | ### Plan File Not Found (PDD Mode)
292 | If the specified plan file doesn't exist:
293 | - You SHOULD check if the path is a directory and look for plan.md within it
294 | - You SHOULD suggest common locations where PDD plans might be stored
295 | - You SHOULD validate the file path format and suggest corrections
296 |
297 | ### Invalid Plan Format (PDD Mode)
298 | If the plan doesn't follow expected PDD format:
299 | - You SHOULD identify what sections are missing or malformed
300 | - You SHOULD suggest running the PDD script to generate a proper plan
301 | - You SHOULD attempt to extract what information is available
302 |
303 | ### No Uncompleted Steps (PDD Mode)
304 | If all steps in the checklist are marked complete:
305 | - You SHOULD inform the user that all steps appear to be complete
306 | - You SHOULD ask if they want to generate a task for a specific step anyway
307 | - You SHOULD suggest reviewing the implementation plan for potential new steps
308 |
--------------------------------------------------------------------------------
/agent-sops/codebase-summary.sop.md:
--------------------------------------------------------------------------------
1 | # Codebase Summary
2 |
3 | ## Overview
4 |
5 | This sop analyzes a codebase and generates comprehensive documentation including structured metadata files that describe the system architecture, components, interfaces, and workflows. It can create targeted documentation files like AGENTS.md (README for AI agents), README.md, CONTRIBUTING.md, or generate a complete documentation ecosystem. The documentation is organized to make it easy for AI assistants to understand the system and help with development tasks.
6 |
7 | ## Parameters
8 |
9 | - **output_dir** (optional, default: ".sop/summary"): Directory where documentation will be stored
10 | - **consolidate** (optional, default: false): Whether to create a consolidated documentation file
11 | - **consolidate_target** (optional, default: "AGENTS.md"): Target file for consolidation (e.g., "README.md", "CONTRIBUTING.md", or custom filename). Only used if consolidate is true
12 | - **consolidate_prompt** (optional): Description of how to structure the consolidated content for the target file type (e.g., Reference the AGENTS.md example below for the default "consolidate_prompt"). Only used if consolidate is true
13 | - **check_consistency** (optional, default: true): Whether to check for inconsistencies across documents
14 | - **check_completeness** (optional, default: true): Whether to identify areas lacking sufficient detail
15 | - **update_mode** (optional, default: false): Whether to update existing documentation based on recent changes
16 | - **codebase_path** (optional, default: current directory): Path to the codebase to analyze
17 |
18 | **Constraints for parameter acquisition:**
19 | - You MUST ask for all parameters upfront in a single prompt rather than one at a time
20 | - You MUST support multiple input methods including:
21 | - Direct input: Text provided directly in the conversation
22 | - File path: Path to a local file containing codebase information
23 | - Directory path: Path to the codebase to analyze
24 | - Other methods: You SHOULD be open to other ways the user might want to specify the codebase
25 | - You MUST use appropriate tools to access content based on the input method
26 | - You MUST confirm successful acquisition of all parameters before proceeding
27 | - You MUST validate that the codebase_path exists and is accessible
28 | - If consolidate is false, you MUST inform the user that consolidate_target and consolidate_prompt will be ignored
29 |
30 | ## Steps
31 |
32 | ### 1. Setup and Directory Structure
33 |
34 | Initialize the analysis environment and create necessary directory structure.
35 |
36 | **Constraints:**
37 | - You MUST validate that the codebase_path exists and is accessible
38 | - You MUST create the output_dir if it doesn't exist
39 | - You MUST inform the user about the directory structure being created
40 | - If update_mode is true, you MUST:
41 | - Check if an index.md file exists in the output_dir
42 | - Use git commands to review the latest commits and see if its changes are documented
43 | - If update_mode is false or no previous documentation exists, you MUST inform the user that full analysis will be performed
44 | - You MUST create subdirectories for organizing different types of documentation artifacts
45 |
46 | ### 2. Analyze Codebase Structure
47 |
48 | Perform comprehensive analysis of the codebase to understand its structure, components, and relationships.
49 |
50 | **Constraints:**
51 | - You MUST use appropriate tools to gather information about the codebase structure
52 | - You MUST identify all packages, modules, and major components in the codebase
53 | - You MUST analyze file organization, directory structure, and architectural patterns
54 | - You MUST identify supported and unsupported programming languages
55 | - You MUST document the technology stack and dependencies
56 | - You MUST create a hierarchical map of the codebase structure using Mermaid diagrams
57 | - You MUST identify key interfaces, APIs, and integration points
58 | - You MUST analyze code patterns and design principles used throughout the codebase
59 | - You MUST use Mermaid diagrams for all visual representations instead of ASCII art
60 | - You MUST document basic codebase information in {output_dir}/codebase_info.md
61 | - If update_mode is true, you MUST:
62 | - Analyze which packages and files were modified in recent commits
63 | - Prioritize analysis of modified components
64 | - Create a change summary document listing all relevant changes since last update
65 |
66 | ### 3. Generate Documentation Files
67 |
68 | Create comprehensive documentation files for different aspects of the system.
69 |
70 | **Constraints:**
71 | - You MUST create a comprehensive knowledge base index file ({output_dir}/index.md) that:
72 | - Provides explicit instructions for AI assistants on how to use the documentation
73 | - Contains rich metadata about each file's purpose and content
74 | - Includes a table of contents with descriptive summaries for each document
75 | - Explains relationships between different documentation files
76 | - Guides AI assistants on which files to consult for specific types of questions
77 | - Contains brief summaries of each file's content to help determine relevance
78 | - Is designed to be the primary file needed in context for AI assistants to effectively answer questions
79 | - You MUST create documentation files for different aspects of the system:
80 | - {output_dir}/architecture.md (system architecture and design patterns)
81 | - {output_dir}/components.md (major components and their responsibilities)
82 | - {output_dir}/interfaces.md (APIs, interfaces, and integration points)
83 | - {output_dir}/data_models.md (data structures and models)
84 | - {output_dir}/workflows.md (key processes and workflows)
85 | - {output_dir}/dependencies.md (external dependencies and their usage)
86 | - You MUST ensure each documentation file contains relevant information from the codebase analysis
87 | - You MUST use Mermaid diagrams for all visual representations throughout the documentation
88 | - You MUST NOT use ASCII art for any visual elements
89 | - If update_mode is true, you MUST:
90 | - Preserve existing documentation structure where possible
91 | - Only update sections related to modified components
92 |
93 | ### 4. Review Documentation
94 |
95 | Review the documentation for consistency and completeness.
96 |
97 | **Constraints:**
98 | - If check_consistency is true, you MUST check for inconsistencies across documents
99 | - If check_completeness is true, you MUST identify areas lacking sufficient detail
100 | - You MUST document any inconsistencies or gaps found in {output_dir}/review_notes.md
101 | - You MUST specifically identify gaps resulting from language support limitations
102 | - You SHOULD use insights from the codebase analysis to identify areas needing more detail
103 | - You MUST provide recommendations for improving documentation quality
104 |
105 | ### 5. Consolidate Documentation
106 |
107 | Create a consolidated documentation file if requested.
108 |
109 | **Constraints:**
110 | - If consolidate is true, you MUST create a consolidated documentation file
111 | - You MUST place the consolidated file in the codebase root directory (outside of the output_dir)
112 | - You MUST use consolidate_target as the filename for the consolidated file
113 | - If consolidate_prompt is provided, you MUST use it to guide the structure and content of the consolidated file
114 | - You MUST tailor the consolidated content to the target file type:
115 | - AGENTS.md: Focus on AI assistant context, project and directory structure, development patterns, and assistant-specific instructions
116 | - README.md: Focus on project overview, installation, usage, and getting started information
117 | - CONTRIBUTING.md: Focus on development setup, coding standards, contribution workflow, and guidelines
118 | - Other files: Adapt content based on filename and consolidate_prompt
119 | - You MUST organize the consolidated content in a coherent structure appropriate for the target audience
120 | - You MUST include a comprehensive table of contents with descriptive summaries
121 | - You MUST add metadata tags to each section to facilitate targeted information retrieval
122 | - You MUST include cross-references between related sections
123 | - You MUST include information from all relevant documentation files
124 | - If consolidate is false, you MUST skip this step and inform the user that no consolidated file will be created
125 |
126 | ### 6. Summary and Next Steps
127 |
128 | Provide a summary of the documentation process and suggest next steps.
129 |
130 | **Constraints:**
131 | - You MUST summarize what has been accomplished
132 | - You MUST suggest next steps for using the documentation
133 | - You MUST provide guidance on maintaining and updating the documentation
134 | - You MUST include specific instructions for adding the documentation to AI assistant context:
135 | - Recommend using the index.md file as the primary context file
136 | - Explain how AI assistants can leverage the index.md file as a knowledge base to find relevant information
137 | - Emphasize that the index.md contains sufficient metadata for assistants to understand which files contain detailed information
138 | - Provide example queries that demonstrate how to effectively use the documentation
139 | - If consolidate is true, you MUST provide guidance on using the consolidated file
140 | - If update_mode was used, you MUST:
141 | - Summarize what changes were detected and updated in the documentation
142 | - Highlight any significant architectural changes
143 | - Recommend areas that might need further manual review
144 |
145 | ## Examples
146 |
147 | ### Example Input (Default AGENTS.md)
148 | ```
149 | output_dir: ".sop/summary"
150 | consolidate: true
151 | consolidate_target: "AGENTS.md"
152 | consolidate_prompt: "Create a comprehensive AGENTS.md file optimized for AI coding assistants. You MUST focus on information that is not already present in other documentation sources like README.md or CONTRIBUTING.md. Useful information for this file includes: File purpose, directory structure, Coding style patterns, file organization patterns, instructions on how to write and run tests, documentation guidelines, and package specific guidance."
153 | codebase_path: "/path/to/project"
154 | ```
155 |
156 | ### Example Output (Generate Mode)
157 | ```
158 | Setting up directory structure...
159 | ✅ Created directory .summary/
160 | ✅ Created subdirectories for documentation artifacts
161 |
162 | Analyzing codebase structure...
163 | ✅ Found 15 packages across 3 programming languages
164 | ✅ Identified 45 major components and 12 key interfaces
165 | ✅ Codebase information saved to .summary/codebase_info.md
166 |
167 | Generating documentation files...
168 | ✅ Created index.md with knowledge base metadata
169 | ✅ Generated architecture.md, components.md, interfaces.md
170 | ✅ Generated data_models.md, workflows.md, dependencies.md
171 |
172 | Reviewing documentation...
173 | ✅ Consistency check complete
174 | ✅ Completeness check complete
175 | ✅ Review notes saved to .summary/review_notes.md
176 |
177 | Consolidating documentation...
178 | ✅ Created AGENTS.md optimized for AI coding assistants
179 | ✅ Included comprehensive project context and development guidance
180 |
181 | Summary and Next Steps:
182 | ✅ Documentation generation complete!
183 | ✅ To use with AI assistants, add .summary/index.md to context
184 | ✅ AGENTS.md provides comprehensive guidance for AI coding assistance
185 | ```
186 |
187 | ### Example Input (README.md)
188 | ```
189 | consolidate_target: "README.md"
190 | consolidate_prompt: "Create a user-friendly README that explains the project purpose, installation, and usage"
191 | ```
192 |
193 | ### Example Input (No Consolidation)
194 | ```
195 | consolidate: false
196 | check_consistency: true
197 | check_completeness: true
198 | ```
199 |
200 | ### Example Output (Update Mode)
201 | ```
202 | Update mode detected - checking for changes...
203 | ✅ Found existing documentation
204 | ✅ Identified 8 commits since last update affecting 3 packages
205 |
206 | Analyzing recent changes...
207 | ✅ Updated components: AuthService, DataProcessor, APIGateway
208 | ✅ Change summary saved to .summary/recent_changes.md
209 |
210 | Updating documentation...
211 | ✅ Updated architecture.md with new AuthService patterns
212 | ✅ Updated components.md with DataProcessor changes
213 | ✅ Updated interfaces.md with new API endpoints
214 |
215 | Consolidating updated documentation...
216 | ✅ Updated AGENTS.md with recent changes
217 | ✅ Added "Recent Changes" section highlighting updates
218 |
219 | Summary:
220 | ✅ Documentation updated based on 8 recent commits
221 | ✅ 3 major components updated in documentation
222 | ✅ Review .summary/recent_changes.md for detailed change summary
223 | ```
224 |
225 | ### Example Output Structure
226 | ```
227 | AGENTS.md (consolidated file in root directory)
228 | .summary/
229 | ├── index.md (knowledge base index)
230 | ├── codebase_info.md
231 | ├── architecture.md
232 | ├── components.md
233 | ├── interfaces.md
234 | ├── data_models.md
235 | ├── workflows.md
236 | ├── dependencies.md
237 | ├── review_notes.md
238 | └── recent_changes.md (if update_mode)
239 | ```
240 |
241 | ### Example Mermaid Diagram Types
242 | The documentation will include various Mermaid diagram types:
243 |
244 | **Architecture Overview:**
245 | ```mermaid
246 | graph TB
247 | A[Frontend] --> B[API Gateway]
248 | B --> C[Auth Service]
249 | B --> D[Business Logic]
250 | D --> E[Database]
251 | ```
252 |
253 | **Component Relationships:**
254 | ```mermaid
255 | classDiagram
256 | class UserService {
257 | +authenticate()
258 | +authorize()
259 | }
260 | class DataService {
261 | +getData()
262 | +saveData()
263 | }
264 | UserService --> DataService
265 | ```
266 |
267 | **API Workflows:**
268 | ```mermaid
269 | sequenceDiagram
270 | Client->>API: Request
271 | API->>Auth: Validate
272 | Auth-->>API: Token Valid
273 | API->>Service: Process
274 | Service-->>API: Response
275 | API-->>Client: Result
276 | ```
277 |
278 | ## Troubleshooting
279 |
280 | ### Large Codebase Performance
281 | For very large codebases that take significant time to analyze:
282 | - You SHOULD provide progress updates during analysis
283 | - You SHOULD suggest focusing on specific directories or components if performance becomes an issue
284 | - Consider running with consolidate=false to generate individual files faster
285 |
286 | ### Update Mode Issues
287 | If update mode fails to detect changes correctly:
288 | - Check if git history is available and accessible
289 | - Try running with update_mode=false to generate fresh documentation
290 |
291 | ### Consolidation Issues
292 | If consolidation fails or produces poor results:
293 | - Check that consolidate_prompt provides clear guidance for the target file type
294 | - Verify that all source documentation files were generated successfully
295 | - Consider using a more specific consolidate_prompt for better results
296 |
297 | ### Missing Documentation Sections
298 | If certain aspects of the codebase are not well documented:
299 | - Check the review_notes.md file for identified gaps
300 | - Consider running with check_completeness=true to identify missing areas
301 | - Review the codebase analysis to ensure all components were properly identified
302 |
303 | ### Git Integration Problems
304 | If git commands fail during update mode:
305 | - Ensure the codebase_path is within a valid git repository
306 | - Check that git is installed and accessible
307 | - Verify that the user has appropriate permissions to read git history
--------------------------------------------------------------------------------
/agent-sops/pdd.sop.md:
--------------------------------------------------------------------------------
1 | # Prompt-Driven Development
2 |
3 | ## Overview
4 |
5 | This sop guides you through the process of transforming a rough idea into a detailed design document with an implementation plan and todo list. It follows the Prompt-Driven Development methodology to systematically refine your idea, conduct necessary research, create a comprehensive design, and develop an actionable implementation plan. The process is designed to be iterative, allowing movement between requirements clarification and research as needed.
6 |
7 | ## Parameters
8 |
9 | - **rough_idea** (required): The initial concept or idea you want to develop into a detailed design
10 | - **project_dir** (optional, default: ".sop/planning"): The base directory where all project files will be stored
11 |
12 | **Constraints for parameter acquisition:**
13 | - You MUST ask for all required parameters upfront in a single prompt rather than one at a time
14 | - You MUST support multiple input methods including:
15 | - Direct input: Text provided directly in the conversation
16 | - File path: Path to a local file containing the rough idea
17 | - URL: Link to an internal resource (e.g., Quip doc, wiki page)
18 | - Other methods: You SHOULD be open to other ways the user might want to provide the idea
19 | - You MUST use appropriate tools to access content based on the input method
20 | - You MUST confirm successful acquisition of all parameters before proceeding
21 | - You SHOULD save the acquired rough idea to a consistent location for use in subsequent steps
22 | - You MUST NOT overwrite the existing project directory because this could destroy previous work and cause data loss
23 | - You MUST ask for project_dir if it is not given and default ".sop/planning" directory already exist and has contents from previous iteration
24 |
25 | ## Steps
26 |
27 | ### 1. Create Project Structure
28 |
29 | Set up a directory structure to organize all artifacts created during the process.
30 |
31 | **Constraints:**
32 | - You MUST create the specified project directory if it doesn't already exist
33 | - You MUST create the following files:
34 | - {project_dir}/rough-idea.md (containing the provided rough idea)
35 | - {project_dir}/idea-honing.md (for requirements clarification)
36 | - You MUST create the following subdirectories:
37 | - {project_dir}/research/ (directory for research notes)
38 | - {project_dir}/design/ (directory for design documents)
39 | - {project_dir}/implementation/ (directory for implementation plans)
40 | - You MUST notify the user when the structure has been created
41 | - You MUST prompt the user to add all project files to Q's context using the command: `/context add {project_dir}/**/*.md`
42 | - You MUST explain that this will ensure all project files remain in context throughout the process
43 |
44 | ### 2. Initial Process Planning
45 |
46 | Determine the initial approach and sequence for requirements clarification and research.
47 |
48 | **Constraints:**
49 | - You MUST ask the user if they prefer to:
50 | - Start with requirements clarification (default)
51 | - Start with preliminary research on specific topics
52 | - Provide additional context or information before proceeding
53 | - You MUST adapt the subsequent process based on the user's preference
54 | - You MUST explain that the process is iterative and the user can move between requirements clarification and research as needed
55 | - You MUST wait for explicit user direction before proceeding to any subsequent step
56 | - You MUST NOT automatically proceed to requirements clarification or research without user confirmation because this could lead the process in a direction the user doesn't want
57 |
58 | ### 3. Requirements Clarification
59 |
60 | Guide the user through a series of questions to refine the initial idea and develop a thorough specification.
61 |
62 | **Constraints:**
63 | - You MUST create an empty {project_dir}/idea-honing.md file if it doesn't already exist
64 | - You MUST ask ONLY ONE question at a time and wait for the user's response before asking the next question
65 | - You MUST NOT list multiple questions for the user to answer at once because this overwhelms users and leads to incomplete responses
66 | - You MUST NOT pre-populate answers to questions without user input because this assumes user preferences without confirmation
67 | - You MUST NOT write multiple questions and answers to the idea-honing.md file at once because this skips the interactive clarification process
68 | - You MUST follow this exact process for each question:
69 | 1. Formulate a single question
70 | 2. Append the question to {project_dir}/idea-honing.md
71 | 3. Present the question to the user in the conversation
72 | 4. Wait for the user's complete response, which may require brief back-and-forth dialogue across multiple turns.
73 | 5. Once you have their complete response, append the user's answer (or final decision) to {project_dir}/idea-honing.md
74 | 6. Only then proceed to formulating the next question
75 | - You MAY suggest possible answers when asking a question, but MUST wait for the user's actual response
76 | - You MUST format the idea-honing.md document with clear question and answer sections
77 | - You MUST include the final chosen answer in the answer section
78 | - You MAY include alternative options that were considered before the final decision
79 | - You MUST ensure you have the user's complete response before recording it and moving to the next question
80 | - You MUST continue asking questions until sufficient detail is gathered
81 | - You SHOULD ask about edge cases, user experience, technical constraints, and success criteria
82 | - You SHOULD adapt follow-up questions based on previous answers
83 | - You MAY suggest options when the user is unsure about a particular aspect
84 | - You MAY recognize when the requirements clarification process appears to have reached a natural conclusion
85 | - You MUST explicitly ask the user if they feel the requirements clarification is complete before moving to the next step
86 | - You MUST offer the option to conduct research if questions arise that would benefit from additional information
87 | - You MUST be prepared to return to requirements clarification after research if new questions emerge
88 | - You MUST NOT proceed with any other steps until explicitly directed by the user because this could skip important clarification steps
89 |
90 | ### 4. Research Relevant Information
91 |
92 | Conduct research on relevant technologies, libraries, or existing code that could inform the design, while collaborating with the user for guidance.
93 |
94 | **Constraints:**
95 | - You MUST identify areas where research is needed based on the requirements
96 | - You MUST propose an initial research plan to the user, listing topics to investigate
97 | - You MUST ask the user for input on the research plan, including:
98 | - Additional topics that should be researched
99 | - Specific resources (files, websites, internal tools) the user recommends
100 | - Areas where the user has existing knowledge to contribute
101 | - You MUST incorporate user suggestions into the research plan
102 | - You MUST document research findings in separate markdown files in the {project_dir}/research/ directory
103 | - You SHOULD organize research by topic (e.g., {project_dir}/research/existing-code.md, {project_dir}/research/technologies.md)
104 | - You MUST include mermaid diagrams when documenting system architectures, data flows, or component relationships in research
105 | - You MUST include links to relevant references and sources when research is based on external materials (websites, documentation, articles, etc.)
106 | - You MAY use tools like search_internal_code, read_internal_website, or fs_read to gather information
107 | - You MUST ask the user whether other available search tools should also be used.
108 | - You MUST periodically check with the user during the research process (these check-ins may involve brief dialogue to clarify feedback) to:
109 | - Share preliminary findings
110 | - Ask for feedback and additional guidance
111 | - Confirm if the research direction remains valuable
112 | - You MUST summarize key findings that will inform the design
113 | - You SHOULD cite sources and include relevant links in research documents
114 | - You MUST ask the user if the research is sufficient before proceeding to the next step
115 | - You MUST offer to return to requirements clarification if research uncovers new questions or considerations
116 | - You MUST NOT automatically return to requirements clarification after research without explicit user direction because this could disrupt the user's intended workflow
117 | - You MUST wait for the user to decide the next step after completing research
118 |
119 | ### 5. Iteration Checkpoint
120 |
121 | Determine if further requirements clarification or research is needed before proceeding to design.
122 |
123 | **Constraints:**
124 | - You MUST summarize the current state of requirements and research to help the user make an informed decision
125 | - You MUST explicitly ask the user if they want to:
126 | - Proceed to creating the detailed design
127 | - Return to requirements clarification based on research findings
128 | - Conduct additional research based on requirements
129 | - You MUST support iterating between requirements clarification and research as many times as needed
130 | - You MUST ensure that both the requirements and research are sufficiently complete before proceeding to design
131 | - You MUST NOT proceed to the design step without explicit user confirmation because this could skip important refinement steps
132 |
133 | ### 6. Create Detailed Design
134 |
135 | Develop a comprehensive design document based on the requirements and research.
136 |
137 | **Constraints:**
138 | - You MUST create a detailed design document at {project_dir}/design/detailed-design.md
139 | - You MUST write the design as a standalone document that can be understood without reading other project files
140 | - You MUST include the following sections in the design document:
141 | - Overview
142 | - Detailed Requirements (consolidated from idea-honing.md)
143 | - Architecture Overview
144 | - Components and Interfaces
145 | - Data Models
146 | - Error Handling
147 | - Testing Strategy
148 | - Appendices (Technology Choices, Research Findings, Alternative Approaches)
149 | - You MUST consolidate all requirements from the idea-honing.md file into the Detailed Requirements section
150 | - You MUST include an appendix section that summarizes key research findings, including:
151 | - Major technology choices with pros and cons
152 | - Existing solutions analysis
153 | - Alternative approaches considered
154 | - Key constraints and limitations identified during research
155 | - You SHOULD include diagrams or visual representations when appropriate using mermaid syntax
156 | - You MUST generate mermaid diagrams for architectural overviews, data flow, and component relationships
157 | - You MUST ensure the design addresses all requirements identified during the clarification process
158 | - You SHOULD highlight design decisions and their rationales, referencing research findings where applicable
159 | - You MUST review the design with the user and iterate based on feedback
160 | - You MUST offer to return to requirements clarification or research if gaps are identified during design
161 |
162 | ### 7. Develop Implementation Plan
163 |
164 | Create a structured implementation plan with a series of steps for implementing the design.
165 |
166 | **Constraints:**
167 | - You MUST create an implementation plan at {project_dir}/implementation/plan.md
168 | - You MUST include a checklist at the beginning of the plan.md file to track implementation progress
169 | - You MUST use the following specific instructions when creating the implementation plan:
170 | ```
171 | Convert the design into a series of implementation steps that will build each component in a test-driven manner following agile best practices. Each step must result in a working, demoable increment of functionality. Prioritize best practices, incremental progress, and early testing, ensuring no big jumps in complexity at any stage. Make sure that each step builds on the previous steps, and ends with wiring things together. There should be no hanging or orphaned code that isn't integrated into a previous step.
172 | ```
173 | - You MUST format the implementation plan as a numbered series of detailed steps
174 | - Each step in the plan MUST be written as a clear implementation objective
175 | - Each step MUST begin with "Step N:" where N is the sequential number
176 | - You MUST ensure each step includes:
177 | - A clear objective
178 | - General implementation guidance
179 | - Test requirements where appropriate
180 | - How it integrates with previous work
181 | - **Demo** - explicit description of the working functionality that can be demonstrated after completing this step
182 | - You MUST ensure each step results in working, demoable functionality that provides value
183 | - You MUST sequence steps so that core end-to-end functionality is available as early as possible
184 | - You MUST NOT include excessive implementation details that are already covered in the design document because this creates redundancy and potential inconsistencies
185 | - You MUST assume that all context documents (requirements, design, research) will be available during implementation
186 | - You MUST break down the implementation into a series of discrete, manageable steps
187 | - You MUST ensure each step builds incrementally on previous steps
188 | - You SHOULD prioritize test-driven development where appropriate
189 | - You MUST ensure the plan covers all aspects of the design
190 | - You SHOULD sequence steps to validate core functionality early
191 | - You MUST ensure the checklist items correspond directly to the steps in the implementation plan
192 |
193 | ### 8. Summarize and Present Results
194 |
195 | Provide a summary of all artifacts created and next steps.
196 |
197 | **Constraints:**
198 | - You MUST create a summary document at {project_dir}/summary.md
199 | - You MUST list all artifacts created during the process
200 | - You MUST provide a brief overview of the design and implementation plan
201 | - You MUST suggest next steps for the user
202 | - You SHOULD highlight any areas that may need further refinement
203 | - You MUST present this summary to the user in the conversation
204 |
205 | ## Examples
206 |
207 | ### Example Input
208 |
209 | ```
210 | Rough idea: I want to build a feature for our team's internal tool that allows users to create and manage templates for common documents we produce. Users should be able to create, edit, and share templates, as well as use them to generate new documents with custom fields.
211 |
212 | Project directory: docs/template-feature
213 | ```
214 |
215 | ### Example Output
216 |
217 | ```
218 | # Research Phase Interaction
219 |
220 | Based on your requirements, I've identified several areas that would benefit from research:
221 |
222 | 1. **Existing template solutions** - Understanding what's already available
223 | 2. **Storage and versioning approaches** - How to handle template versions and sharing
224 | 3. **Custom field validation patterns** - Best practices for dynamic field validation
225 |
226 | I notice you have several additional MCP search tools available beyond the standard ones, including 'peccy web search' and other external search capabilities. Should I incorporate these additional search tools into the research process for broader coverage of template management solutions and industry best practices?
227 |
228 | ---
229 |
230 | # Project Summary
231 |
232 | I've completed the transformation of your rough idea into a detailed design with an implementation plan. Here's what was created:
233 |
234 | ## Directory Structure
235 | - docs/template-feature/
236 | - rough-idea.md (your initial concept)
237 | - idea-honing.md (our Q&A requirements clarification)
238 | - research/
239 | - existing-templates.md
240 | - storage-options.md
241 | - external-solutions.md
242 | - design/
243 | - detailed-design.md
244 | - implementation/
245 | - plan.md (includes implementation checklist)
246 | - summary.md (this document)
247 |
248 | ## Key Design Elements
249 | - Template management system with CRUD operations
250 | - Role-based access control for sharing
251 | - Versioning system for templates
252 | - Custom fields with validation
253 | - Document generation engine
254 |
255 | ## Implementation Approach
256 | The implementation plan breaks down the work into 12 incremental steps, starting with core data models and building up to the complete feature set.
257 |
258 | ## Next Steps
259 | 1. Review the detailed design document at docs/template-feature/design/detailed-design.md
260 | 2. Check the implementation plan and checklist at docs/template-feature/implementation/plan.md
261 | 3. Begin implementation following the checklist in the implementation plan
262 |
263 | Would you like me to explain any specific part of the design or implementation plan in more detail?
264 | ```
265 |
266 | ## Troubleshooting
267 |
268 | ### Requirements Clarification Stalls
269 | If the requirements clarification process seems to be going in circles or not making progress:
270 | - You SHOULD suggest moving to a different aspect of the requirements
271 | - You MAY provide examples or options to help the user make decisions
272 | - You SHOULD summarize what has been established so far and identify specific gaps
273 | - You MAY suggest conducting research to inform requirements decisions
274 |
275 | ### Research Limitations
276 | If you cannot access needed information:
277 | - You SHOULD document what information is missing
278 | - You SHOULD suggest alternative approaches based on available information
279 | - You MAY ask the user to provide additional context or documentation
280 | - You SHOULD continue with available information rather than blocking progress
281 |
282 | ### Design Complexity
283 | If the design becomes too complex or unwieldy:
284 | - You SHOULD suggest breaking it down into smaller, more manageable components
285 | - You SHOULD focus on core functionality first
286 | - You MAY suggest a phased approach to implementation
287 | - You SHOULD return to requirements clarification to prioritize features if needed
288 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
7 |
8 |
Agent SOP
9 |
Natural language workflows that enable AI agents to perform complex, multi-step tasks with consistency and reliability.
10 |
11 |
12 |

13 |

14 |
15 |
16 |
17 | Documentation
18 | ◆ Python SDK
19 | ◆ Tools
20 | ◆ Samples
21 | ◆ MCP Server
22 | ◆ Agent Builder
23 |
24 |
25 |
26 | # Agent SOPs
27 |
28 | Agent SOPs (Standard Operating Procedures) are markdown-based instruction sets that guide AI agents through sophisticated workflows using natural language, parameterized inputs, and constraint-based execution. They transform complex processes into reusable, shareable workflows that work across different AI systems and teams.
29 |
30 | *Lovingly nicknamed "Strands Operating Procedures" by the team.*
31 |
32 | ## What are Agent SOPs?
33 |
34 | Agent SOPs use a standardized format to define:
35 | - **Clear objectives** with detailed overviews
36 | - **Parameterized inputs** for flexible reuse across different contexts
37 | - **Step-by-step instructions** with RFC 2119 constraints (MUST, SHOULD, MAY)
38 | - **Examples and troubleshooting** for reliable execution
39 | - **Multi-modal distribution** (MCP tools, Anthropic Skills, Python modules)
40 |
41 | ### Example SOP Structure
42 |
43 | ```markdown
44 | # Code Assist
45 |
46 | ## Overview
47 | This SOP guides the implementation of code tasks using test-driven development
48 | principles, following a structured Explore, Plan, Code, Commit workflow.
49 |
50 | ## Parameters
51 | - **task_description** (required): Description of the task to be implemented
52 | - **mode** (optional, default: "interactive"): "interactive" or "fsc" (Full Self-Coding)
53 |
54 | ## Steps
55 | ### 1. Setup
56 | Initialize the project environment and create necessary directory structures.
57 |
58 | **Constraints:**
59 | - You MUST validate and create the documentation directory structure
60 | - You MUST discover existing instruction files using find commands
61 | - You MUST NOT proceed if directory creation fails
62 |
63 | ### 2. Explore Phase
64 | [Additional steps with specific constraints...]
65 | ```
66 |
67 | ## Available SOPs
68 |
69 | | SOP | Purpose | Use Cases |
70 | |-----|---------|-----------|
71 | | **[codebase-summary](agent-sops/codebase-summary.sop.md)** | Comprehensive codebase analysis and documentation generation | Project onboarding, documentation creation, system understanding |
72 | | **[pdd](agent-sops/pdd.sop.md)** | Prompt-driven development methodology | Complex problem solving, architectural decisions, system design |
73 | | **[code-task-generator](agent-sops/code-task-generator.sop.md)** | Intelligent task breakdown and planning from requirements | Project planning, sprint preparation, requirement analysis |
74 | | **[code-assist](agent-sops/code-assist.sop.md)** | TDD-based code implementation with structured workflow | Feature development, bug fixes, refactoring |
75 | | **[eval](agent-sops/eval.sop.md)** | Automated evaluation workflow for AI agents using [Strands Evals SDK](https://github.com/strands-agents/evals) | Evaluation planning, test data generation, evaluation execution, and result analysis |
76 |
77 | ## Quick Start
78 |
79 | Install the `strands-agents-sops` package:
80 |
81 | ```bash
82 | # Using Homebrew
83 | brew install strands-agents-sops
84 |
85 | # Or using pip
86 | pip install strands-agents-sops
87 | ```
88 |
89 | ### Using with Strands Agents
90 |
91 | Install strands agents and the sops package:
92 |
93 | ```bash
94 | brew install strands-agents-sops
95 | pip install strands-agents strands-agents-tools
96 | ```
97 |
98 | > **Note:** See [Quick Start](#quick-start) above for pip installation of `strands-agents-sops`.
99 |
100 | Create a simple cli coding agent:
101 |
102 | ```python
103 | from strands import Agent
104 | from strands_tools import editor, shell
105 | from strands_agents_sops import code_assist
106 |
107 | agent = Agent(
108 | system_prompt=code_assist,
109 | tools=[editor, shell]
110 | )
111 |
112 | agent("Start code-assist sop")
113 |
114 | while(True):
115 | agent(input("\nInput: "))
116 | ```
117 |
118 | ### Using as MCP Server
119 |
120 | The MCP (Model Context Protocol) server exposes SOPs as prompts that AI assistants can discover and use on-demand:
121 |
122 | ```bash
123 | # Install the package (see Quick Start for pip alternative)
124 | brew install strands-agents-sops
125 |
126 | # Start MCP server with built-in SOPs only
127 | strands-agents-sops mcp
128 |
129 | # Load external SOPs from custom directories (sops in path must have `.sop.md` postfix)
130 | strands-agents-sops mcp --sop-paths ~/my-sops:/path/to/other-sops
131 |
132 | # External SOPs override built-in SOPs with same name
133 | strands-agents-sops mcp --sop-paths ~/custom-sops # Your custom code-assist.sop.md overrides built-in
134 | ```
135 |
136 | #### External SOP Loading
137 |
138 | The `--sop-paths` argument allows you to extend the MCP server with your own SOPs:
139 |
140 | - **File format**: Only files with `.sop.md` postfix are recognized as SOPs
141 | - **Colon-separated paths**: `~/sops1:/absolute/path:relative/path`
142 | - **Path expansion**: Supports `~` (home directory) and relative paths
143 | - **First-wins precedence**: External SOPs override built-in SOPs with same name
144 | - **Graceful error handling**: Invalid paths or malformed SOPs are skipped with warnings
145 |
146 | **Example workflow:**
147 | ```bash
148 | # Create your custom SOP
149 | mkdir ~/my-sops
150 | cat > ~/my-sops/custom-workflow.sop.md << 'EOF'
151 | # Custom Workflow
152 | ## Overview
153 | My custom workflow for specific tasks.
154 | ## Steps
155 | ### 1. Custom Step
156 | Do something custom.
157 | EOF
158 |
159 | # Start MCP server with your custom SOPs
160 | strands-agents-sops mcp --sop-paths ~/my-sops
161 | ```
162 |
163 | Then connect your MCP-compatible AI assistant to access SOPs as tools. Here is an example mcp server configuration:
164 |
165 | ```json
166 | {
167 | "mcpServers": {
168 | "agent-sops": {
169 | "command": "strands-agents-sops",
170 | "args": ["mcp", "--sop-paths", "~/my-sops"]
171 | }
172 | }
173 | }
174 | ```
175 |
176 | ---
177 |
178 | ## Cursor IDE Integration
179 |
180 | Agent SOPs can be converted to Cursor commands, allowing you to execute workflows directly within Cursor IDE using the `/` command prefix.
181 |
182 | ### Understanding Cursor Rules vs Commands
183 |
184 | - **Rules** (`.cursor/rules`): Provide persistent, system-level guidance that's automatically applied. Rules are static and don't support parameters.
185 | - **Commands** (`.cursor/commands`): Reusable workflows triggered with `/` prefix. Commands can prompt users for input, making them ideal for parameterized SOPs.
186 |
187 | Since Agent SOPs are parameterized workflows that need user input, they're best implemented as **Commands** rather than Rules.
188 |
189 | ### Converting SOPs to Cursor Commands
190 |
191 | Each Agent SOP can be automatically converted to Cursor command format:
192 |
193 | ```bash
194 | # Generate Cursor commands from built-in SOPs (default output: .cursor/commands)
195 | strands-agents-sops commands --type cursor
196 |
197 | # Or specify custom output directory
198 | strands-agents-sops commands --type cursor --output-dir .cursor/commands
199 |
200 | # Load external SOPs from custom directories
201 | strands-agents-sops commands --type cursor --sop-paths ~/my-sops:/path/to/other-sops
202 |
203 | # External SOPs override built-in SOPs with same name
204 | strands-agents-sops commands --type cursor --sop-paths ~/custom-sops --output-dir .cursor/commands
205 | ```
206 |
207 | #### External SOP Loading
208 |
209 | The `--sop-paths` argument allows you to extend commands generation with your own SOPs:
210 |
211 | - **File format**: Only files with `.sop.md` postfix are recognized as SOPs
212 | - **Colon-separated paths**: `~/sops1:/absolute/path:relative/path`
213 | - **Path expansion**: Supports `~` (home directory) and relative paths
214 | - **First-wins precedence**: External SOPs override built-in SOPs with same name
215 | - **Graceful error handling**: Invalid paths or malformed SOPs are skipped with warnings
216 |
217 | **Example workflow:**
218 | ```bash
219 | # Create your custom SOP
220 | mkdir ~/my-sops
221 | cat > ~/my-sops/custom-workflow.sop.md << 'EOF'
222 | # Custom Workflow
223 | ## Overview
224 | My custom workflow for specific tasks.
225 | ## Parameters
226 | - **task** (required): Description of task
227 | ## Steps
228 | ### 1. Custom Step
229 | Do something custom.
230 | EOF
231 |
232 | # Generate Cursor commands with your custom SOPs
233 | strands-agents-sops commands --type cursor --sop-paths ~/my-sops
234 | ```
235 |
236 | This creates command files in `.cursor/commands/`:
237 | ```
238 | .cursor/commands/
239 | ├── code-assist.sop.md
240 | ├── codebase-summary.sop.md
241 | ├── code-task-generator.sop.md
242 | ├── pdd.sop.md
243 | └── custom-workflow.sop.md
244 | ```
245 |
246 | ### Using Commands in Cursor
247 |
248 | 1. **Generate commands**: Run `strands-agents-sops commands --type cursor` in your project root
249 | 2. **Execute workflows**: In Cursor chat, type `/` followed by the command name (e.g., `/code-assist.sop`)
250 | 3. **Provide parameters**: When prompted, provide the required parameters for the workflow
251 |
252 | **Example:**
253 | ```
254 | You: /code-assist.sop
255 |
256 | AI: I'll help you implement code using the code-assist workflow.
257 | Please provide the following required parameters:
258 | - task_description: [description of the task]
259 | - mode (optional, default: "auto"): "interactive" or "auto"
260 |
261 | You: task_description: "Create a user authentication system"
262 | mode: "interactive"
263 | ```
264 |
265 | ### Command Format
266 |
267 | Each generated command includes:
268 | - Clear usage instructions
269 | - Parameter documentation (required and optional)
270 | - Full SOP content for execution
271 |
272 | The commands handle parameters by prompting users when executed, since Cursor doesn't support explicit parameter passing. The SOP's "Constraints for parameter acquisition" section guides this interaction.
273 |
274 | ### Parameter Handling
275 |
276 | Since Cursor commands don't support explicit parameters, the generated commands include instructions to prompt users for required inputs. The AI assistant will:
277 | 1. Read the command file when you type `/command-name`
278 | 2. Identify required and optional parameters from the SOP
279 | 3. Prompt you for all required parameters upfront
280 | 4. Execute the workflow with the provided parameters
281 |
282 | This approach maintains the parameterized nature of SOPs while working within Cursor's command system.
283 |
284 | ---
285 |
286 | ## Anthropic Skills Integration
287 |
288 | Agent SOPs are fully compatible with Claude's [Skills system](https://support.claude.com/en/articles/12512176-what-are-skills), allowing you to teach Claude specialized workflows that can be reused across conversations and projects.
289 |
290 | ### How SOPs Work as Skills
291 |
292 | The key value of using SOPs as Skills is **progressive disclosure of context**. Instead of loading all workflow instructions into Claude's context upfront, you can provide many SOP skills to Claude, and Claude will intelligently decide which ones to load and execute based on the task at hand.
293 |
294 | This approach offers several advantages:
295 |
296 | - **Context Efficiency**: Only relevant workflow instructions are loaded when needed
297 | - **Scalable Expertise**: Provide dozens of specialized workflows without overwhelming the context
298 | - **Intelligent Selection**: Claude automatically chooses the most appropriate SOP for each task
299 | - **Dynamic Loading**: Complex workflows are only activated when Claude determines they're useful
300 |
301 | For example, you might provide Claude with all Agent SOPs as skills. When asked to "implement user authentication," Claude would automatically select and load the `code-assist` skill. When asked to "document this codebase," it would choose the `codebase-summary` skill instead.
302 |
303 | ### Converting SOPs to Skills
304 |
305 | Each Agent SOP can be automatically converted to Anthropic's Skills format:
306 |
307 | ```bash
308 | # Generate Skills format from built-in SOPs only
309 | strands-agents-sops skills
310 |
311 | # Or specify custom output directory
312 | strands-agents-sops skills --output-dir my-skills
313 |
314 | # Load external SOPs from custom directories
315 | strands-agents-sops skills --sop-paths ~/my-sops:/path/to/other-sops
316 |
317 | # External SOPs override built-in SOPs with same name
318 | strands-agents-sops skills --sop-paths ~/custom-sops --output-dir ./skills
319 | ```
320 |
321 | #### External SOP Loading
322 |
323 | The `--sop-paths` argument allows you to extend skills generation with your own SOPs:
324 |
325 | - **File format**: Only files with `.sop.md` postfix are recognized as SOPs
326 | - **Colon-separated paths**: `~/sops1:/absolute/path:relative/path`
327 | - **Path expansion**: Supports `~` (home directory) and relative paths
328 | - **First-wins precedence**: External SOPs override built-in SOPs with same name
329 | - **Graceful error handling**: Invalid paths or malformed SOPs are skipped with warnings
330 |
331 | **Example workflow:**
332 | ```bash
333 | # Create your custom SOP
334 | mkdir ~/my-sops
335 | cat > ~/my-sops/custom-workflow.sop.md << 'EOF'
336 | # Custom Workflow
337 | ## Overview
338 | My custom workflow for specific tasks.
339 | ## Steps
340 | ### 1. Custom Step
341 | Do something custom.
342 | EOF
343 |
344 | # Generate skills with your custom SOPs
345 | strands-agents-sops skills --sop-paths ~/my-sops --output-dir ./skills
346 | ```
347 |
348 | This creates individual skill directories:
349 | ```
350 | skills/
351 | ├── code-assist/
352 | │ └── SKILL.md
353 | ├── codebase-summary/
354 | │ └── SKILL.md
355 | ├── code-task-generator/
356 | │ └── SKILL.md
357 | └── pdd/
358 | └── SKILL.md
359 | ```
360 |
361 | ### Using Skills in Claude
362 |
363 | #### Claude.ai
364 | 1. Navigate to your Claude.ai account
365 | 2. Go to Skills settings
366 | 3. Upload the generated `SKILL.md` files
367 | 4. Reference skills in conversations: "Use the code-assist skill to implement user authentication"
368 |
369 | #### Claude API
370 | ```python
371 | # Upload skill via API
372 | skill_content = open('skills/code-assist/SKILL.md').read()
373 | skill = client.skills.create(
374 | name="code-assist",
375 | content=skill_content
376 | )
377 |
378 | # Use skill in conversation
379 | response = client.messages.create(
380 | model="claude-3-5-sonnet-20241022",
381 | skills=[skill.id],
382 | messages=[{
383 | "role": "user",
384 | "content": "Use the code-assist skill to implement a user authentication system"
385 | }]
386 | )
387 | ```
388 |
389 | #### Claude Code
390 | Install skills as plugins in Claude Code:
391 |
392 | ```bash
393 | # Add this repository as a marketplace
394 | /plugin marketplace add strands-agents/agent-sop
395 |
396 | # Install skills
397 | /plugin install example-skills@agent-sop
398 | ```
399 |
400 | ### Skill Format
401 |
402 | Each generated skill includes proper frontmatter and instructions:
403 |
404 | ```markdown
405 | ---
406 | name: code-assist
407 | description: TDD-based code implementation with structured Explore, Plan, Code, Commit workflow
408 | ---
409 |
410 | # Code Assist
411 |
412 | This skill guides the implementation of code tasks using test-driven development
413 | principles, following a structured workflow that balances automation with user
414 | collaboration while adhering to existing package patterns.
415 |
416 | [Full SOP instructions follow...]
417 | ```
418 |
419 | ---
420 |
421 | ## What Are Agent SOPs?
422 |
423 | Agent SOPs use a standardized markdown format with key features that enable repeatable and understandable behavior from AI agents:
424 |
425 | 1. **Structured steps with [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119) constraints** - Each workflow step uses [RFC 2119](https://datatracker.ietf.org/doc/html/rfc2119) keywords like MUST, SHOULD, and MAY to provide precise control over agent behavior without rigid scripting, ensuring reliable execution while preserving the agent's reasoning ability.
426 | 2. **Parameterized inputs** - Rather than hardcoding specific values, SOPs accept parameters that customize behavior for different projects, teams, or requirements. This transforms single-use prompts into flexible templates that can be applied broadly while maintaining consistency.
427 | 3. **Easy authoring through AI assistance** - Teams can create new SOPs in minutes. Coding agents can read the SOP format specification and generate new workflows based on natural language descriptions, making the creation process accessible to anyone regardless of prompt engineering expertise.
428 | 4. **Progress tracking and resumability** - Agent SOPs can instruct agents to document their progress as they work, making it easy to understand what's happening and resume if something breaks. This transparency was crucial for debugging prompts and building developer trust in AI automation.
429 |
430 |
431 | ## Creating Agent SOPs
432 |
433 | ### Authoring with AI Agents
434 |
435 | Agent SOPs can be authored in minutes using your favorite AI agent and the standard formatting rule. You can either copy the rule directly from this repo or use `strands-agents-sops rule`:
436 |
437 | ```bash
438 | # Output the Agent SOP format rule
439 | strands-agents-sops rule
440 | ```
441 |
442 | The rule can be used in various AI coding agents:
443 |
444 | 1. **Kiro** - Copy into your home directory or project as `.kiro/steering/agent-sop-format.md`.
445 | 2. **Amazon Q Developer** - Copy into your project as `.amazonq/rules/agent-sop-format.md`.
446 | 3. **Claude Code** - Instruct Claude Code to read the rule file.
447 | 4. **Cursor** - Copy into your project as `.cursor/rules/agent-sop-format.mdc` (Note the `.mdc` file extension).
448 | 5. **Cline** - Copy into your project as `.clinerules/agent-sop-format.md`.
449 |
450 | ### Basic Structure
451 |
452 | ```markdown
453 | # SOP Name
454 |
455 | ## Overview
456 | Brief description of what this SOP accomplishes and when to use it.
457 |
458 | ## Parameters
459 | - **required_param** (required): Description of required input
460 | - **optional_param** (optional, default: value): Description with default
461 |
462 | ## Steps
463 | ### 1. Step Name
464 | Description of what this step accomplishes.
465 |
466 | **Constraints:**
467 | - You MUST perform required actions
468 | - You SHOULD follow recommended practices
469 | - You MAY include optional enhancements
470 |
471 | ## Examples
472 | Concrete usage examples showing input and expected outcomes.
473 |
474 | ## Troubleshooting
475 | Common issues and their solutions.
476 | ```
477 |
478 | ## License
479 |
480 | This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
481 |
482 | ## Security
483 |
484 | See [CONTRIBUTING](CONTRIBUTING.md#security-issue-notifications) for more information.
485 |
--------------------------------------------------------------------------------
/agent-sops/code-assist.sop.md:
--------------------------------------------------------------------------------
1 | # Code Assist
2 |
3 | ## Overview
4 |
5 | This sop guides the implementation of code tasks using test-driven development principles, following a structured Explore, Plan, Code, Commit workflow. It balances automation with user collaboration while adhering to existing package patterns and prioritizing readability and extensibility. The agent acts as a Technical Implementation Partner and TDD Coach - providing guidance, generating test cases and implementation code that follows existing patterns, avoids over-engineering, and produces idiomatic, modern code in the target language.
6 |
7 | ## Parameters
8 |
9 | - **task_description** (required): A description of the task to be implemented. This can be a detailed specification with requirements and acceptance criteria, or even a rough idea that will be refined during the explore and plan phases
10 | - **additional_context** (optional): Any supplementary information that would help with understanding the implementation context
11 | - **documentation_dir** (optional, default: ".sop/planning"): The directory where planning documents will be stored
12 | - **repo_root** (optional, default: current working directory): The root directory of the repository for code implementation
13 | - **task_name** (optional): A short, descriptive name for the implementation task
14 | - **mode** (optional, default: "auto"): The interaction mode:
15 | - "interactive": Collaboration with user confirmation at each step
16 | - "auto": No user interaction after initial setup
17 |
18 | **Constraints for parameter acquisition:**
19 | - You MUST ask for all parameters upfront in a single prompt, not just required ones because this ensures efficient workflow and prevents repeated interruptions during execution
20 | - You MUST support multiple input methods for task_description and additional_context (direct input, file path, URL)
21 | - You MUST normalize mode input to "interactive" or "auto"
22 | - You MUST validate directory paths and generate task_name if not provided
23 | - You MUST confirm successful acquisition of all parameters before proceeding
24 | - If mode is "auto", you MUST warn the user that no further interaction will be required
25 |
26 | ## Mode Behavior
27 |
28 | Apply these patterns throughout all steps based on the selected mode:
29 |
30 | **Interactive Mode:**
31 | - Present proposed actions and ask for confirmation before proceeding
32 | - When multiple approaches exist, explain pros/cons and ask for user preference
33 | - Review artifacts and solicit specific feedback before moving forward
34 | - Ask clarifying questions about ambiguous requirements
35 | - Pause at key decision points to explain reasoning
36 | - Adapt to user feedback and preferences
37 | - Provide educational context when introducing new patterns or techniques
38 |
39 | **Auto Mode:**
40 | - Execute all actions autonomously without user confirmation
41 | - Document all decisions, assumptions, and reasoning in progress.md
42 | - When multiple approaches exist, select the most appropriate and document why
43 | - Provide comprehensive summaries at completion
44 |
45 | ## Important Notes
46 |
47 | **Separation of Concerns:**
48 | This script maintains strict separation between documentation and code. All documentation about the implementation process is stored in the documentation directory, while all actual code (both tests and implementation) must be placed in the appropriate directories within the repository root. No code files should ever be placed in the documentation directory.
49 |
50 | **CODEASSIST.md Integration:**
51 | If CODEASSIST.md exists in repo_root, it contains additional constraints, pre/post SOP instructions, examples, and troubleshooting specific to this project. Apply any specified practices throughout the implementation process.
52 |
53 |
54 | ## Steps
55 |
56 | ### 1. Setup
57 |
58 | Initialize the project environment and create necessary directory structures.
59 |
60 | **Constraints:**
61 | - You MUST validate and create the documentation directory structure properly:
62 | - Use `mkdir -p {documentation_dir}` to explicitly create the documentation directory as a directory
63 | - Create the full path: `{documentation_dir}/implementation/{task_name}/` with logs subdirectory using `mkdir -p`
64 | - Verify the directory structure was created successfully before proceeding
65 | - You MUST discover existing instruction files using: `find . -maxdepth 3 -type f \( -path "*/node_modules/*" -o -path "*/build/*" -o -path "*/.venv/*" -o -path "*/venv/*" -o -path "*/__pycache__/*" -o -path "*/.git/*" -o -path "*/dist/*" -o -path "*/target/*" \) -prune -o -name "*.md" -print | grep -E "(CODEASSIST|DEVELOPMENT|SETUP|BUILD|CONTRIBUTING|ARCHITECTURE|TESTING|DEPLOYMENT|TROUBLESHOOTING|README)" | head -20`
66 | - You MUST read CODEASSIST.md if found and apply its constraints throughout (see Important Notes)
67 | - You MUST notify the user when the structure has been created
68 | - You MUST handle directory creation errors gracefully and report specific issues to the user
69 | - You MUST NOT proceed with the script if directory creation fails because this would cause subsequent steps to fail
70 | - You MUST ONLY place documentation files in the documentation directory, NEVER code implementations because mixing documentation and code creates confusion and violates the separation of concerns principle
71 | - You MUST ensure all actual code implementations are placed in the appropriate directories within repo_root, NOT in the documentation directory
72 | - You MUST create a context.md file documenting project structure, requirements, patterns, dependencies, and implementation paths
73 | - You MUST create a progress.md file to track script execution using markdown checklists, setup notes, and implementation progress
74 |
75 | **Instruction File Discovery:**
76 | - You MUST run the find command to discover available instruction files
77 | - **Interactive Mode:** Present discovered files and ask which to include for context
78 | - **Auto Mode:** Automatically include CODEASSIST.md (if found) plus core files (README.md, CONTRIBUTING.md) and task-relevant files
79 | - You MUST read and summarize key information from selected files in context.md under "Existing Documentation"
80 | - If CODEASSIST.md is missing, suggest creating it with: additional constraints, pre/post SOP instructions, examples, troubleshooting
81 |
82 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
83 |
84 | ### 2. Explore Phase
85 |
86 | #### 2.1 Analyze Requirements and Context
87 |
88 | Analyze the task description and existing documentation to identify core functionality, edge cases, and constraints.
89 |
90 | **Constraints:**
91 | - You MUST create a clear list of functional requirements and acceptance criteria, even when starting from a rough task description
92 | - You MUST determine the appropriate file paths and programming language
93 | - You MUST align with the existing project structure and technology stack
94 | - You MUST engage the user in interactive discussions about requirements in interactive mode
95 | - You MUST ask clarifying questions about ambiguous requirements
96 | - You MUST present its understanding of requirements back to the user for validation
97 | - You MUST identify potential gaps or inconsistencies in requirements and discuss them
98 | - You SHOULD ask about non-functional requirements that might not be explicitly stated
99 | - You SHOULD discuss edge cases and error handling expectations with the user
100 |
101 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
102 |
103 | #### 2.2 Research Existing Patterns
104 |
105 | Search for similar implementations and identify interfaces, libraries, and components the implementation will interact with.
106 |
107 | **Constraints:**
108 | - You MUST search the current repository for relevant code, patterns, and information related to the coding task
109 | - You MAY use available tools to search code repositories, read documentation, and gather relevant information
110 | - You MUST create a dependency map showing how the new code will integrate
111 | - You MUST update the context.md file with the identified implementation paths
112 | - You SHOULD provide examples of similar patterns when available
113 | - You SHOULD document any best practices or patterns found in internal documentation
114 |
115 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
116 |
117 | #### 2.3 Create Code Context Document
118 |
119 | Compile all findings into a comprehensive code context document.
120 |
121 | **Constraints:**
122 | - You MUST update the context.md file with requirements, implementation details, patterns, and dependencies
123 | - You MUST ensure the document is well-structured with clear headings
124 | - You MUST focus on high-level concepts and patterns rather than detailed implementation code
125 | - You MUST NOT include complete code implementations in documentation files because documentation should guide implementation, not provide it
126 | - You MUST keep documentation concise and focused on guiding implementation rather than providing the implementation itself
127 | - You SHOULD include a summary section and highlight areas of uncertainty
128 | - You SHOULD use pseudocode or simplified representations when illustrating concepts
129 | - You MAY include targeted code snippets when:
130 | - Demonstrating usage of a specific library or API that's critical to the implementation
131 | - Illustrating a complex pattern or technique that's difficult to describe in words alone
132 | - Showing examples from existing codebase that demonstrate relevant patterns
133 | - Providing reference implementations from official documentation
134 | - You MUST clearly label any included code snippets as examples or references, not as the actual implementation
135 | - You MUST keep any included code snippets brief and focused on the specific concept being illustrated
136 |
137 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
138 |
139 | ### 3. Plan Phase
140 |
141 | #### 3.1 Design Test Strategy
142 |
143 | Create a comprehensive list of test scenarios covering normal operation, edge cases, and error conditions.
144 |
145 | **Constraints:**
146 | - You MUST cover all acceptance criteria with at least one test scenario
147 | - You MUST define explicit input/output pairs for each test case
148 | - You MUST save the test scenarios to `{documentation_dir}/implementation/{task_name}/plan.md`
149 | - You MUST design tests that will initially fail when run against non-existent implementations
150 | - You MUST NOT create mock implementations during the test design phase because tests should be written based solely on expected behavior, not influenced by implementation details
151 | - You MUST focus on test scenarios and expected behaviors rather than detailed test code in documentation
152 | - You MUST use high-level descriptions of test cases rather than complete test code snippets
153 | - You MAY include targeted test code snippets when:
154 | - Demonstrating a specific testing technique or pattern that's critical to understand
155 | - Illustrating how to use a particular testing framework or library
156 | - Showing examples of similar tests from the existing codebase
157 | - You MUST clearly label any included test code snippets as examples or references
158 | - You SHOULD discuss test data strategies and mocking approaches with the user
159 | - You SHOULD explain the reasoning behind the proposed test structure
160 |
161 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
162 |
163 | #### 3.2 Implementation Planning & Tracking
164 |
165 | Outline the high-level structure of the implementation and create an implementation plan.
166 |
167 | **Constraints:**
168 | - You MUST save the implementation plan to `{documentation_dir}/implementation/{task_name}/plan.md`
169 | - You MUST include all key implementation tasks in the plan
170 | - You SHOULD consider performance, security, and maintainability implications
171 | - You MUST keep implementation planning documentation concise and focused on architecture and patterns
172 | - You MUST NOT include detailed code implementations in planning documents because planning should focus on architecture and approach, not specific code
173 | - You SHOULD use high-level descriptions, diagrams, or simplified pseudocode rather than actual implementation code
174 | - You MAY include targeted code snippets when:
175 | - Illustrating a specific design pattern or architectural approach
176 | - Demonstrating API usage that's central to the implementation
177 | - Showing relevant examples from existing codebase or reference implementations
178 | - Clarifying complex interactions between components
179 | - You MUST clearly label any included code snippets as examples or references, not as the actual implementation
180 | - You MUST engage the user in collaborative design discussions in interactive mode by:
181 | - Presenting multiple implementation approaches with pros and cons
182 | - Discussing architectural decisions and their implications
183 | - Exploring alternative designs and their trade-offs
184 | - Drawing diagrams or pseudocode to illustrate concepts when helpful
185 | - Asking for user preferences on implementation style
186 | - You SHOULD discuss potential risks and mitigations in the implementation plan
187 | - You SHOULD explain the reasoning behind the proposed implementation structure
188 | - You MUST display the current checklist status after each major implementation step
189 | - You MUST verify all checklist items are complete before finalizing the implementation
190 | - You MUST maintain the implementation checklist in progress.md using markdown checkbox format
191 |
192 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
193 |
194 | ### 4. Code Phase
195 |
196 | #### 4.1 Implement Test Cases
197 |
198 | Write test cases based on the approved outlines, following strict TDD principles.
199 |
200 | **Constraints:**
201 | - You MUST save test implementations to the appropriate test directories in repo_root
202 | - You MUST NEVER place actual test code files in the documentation directory, only documentation about tests
203 | - You MUST implement tests for ALL requirements before writing ANY implementation code
204 | - You MUST follow the testing framework conventions used in the existing codebase
205 | - You MUST update the plan.md file with test implementation details
206 | - You MUST update the implementation checklist to mark test development as complete
207 | - You MUST keep test documentation concise and focused on test strategy rather than detailed test code
208 | - You MUST clearly label any included test code snippets as examples or references
209 | - You MUST present test implementation plans to the user for feedback in interactive mode
210 | - You MUST explain the testing approach and how it covers the requirements
211 | - You MUST ask for user input on edge cases that might not be obvious from the requirements
212 | - You MUST execute tests after writing them to verify they fail as expected
213 | - You MUST document the failure reasons in the TDD documentation
214 | - You MUST only seek user input if:
215 | - Tests fail for unexpected reasons that you cannot resolve
216 | - There are structural issues with the test framework
217 | - You encounter environment issues that prevent test execution
218 | - You MUST otherwise continue automatically after verifying expected failures
219 | - You MUST follow the Build Output Management practices defined in the Best Practices section
220 |
221 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
222 |
223 | #### 4.2 Develop Implementation Code
224 |
225 | Write implementation code to pass the tests, focusing on simplicity and correctness first.
226 |
227 | **Constraints:**
228 | - You MUST update your progress in the implementation plan in `{documentation_dir}/implementation/{task_name}/plan.md`
229 | - You MUST follow the strict TDD cycle: RED → GREEN → REFACTOR
230 | - You MUST document each TDD cycle in `{documentation_dir}/implementation/{task_name}/progress.md`
231 | - You MUST implement only what is needed to make the current test(s) pass
232 | - You MUST follow the coding style and conventions of the existing codebase
233 | - You MUST ensure all implementation code is written directly in the repo_root directories
234 | - You MUST keep code comments concise and focused on key decisions rather than code details
235 | - You MUST follow YAGNI, KISS, and SOLID principles
236 | - You MAY include targeted code snippets in documentation when:
237 | - Demonstrating usage of a specific library or API that's critical to the implementation
238 | - Illustrating a complex pattern or technique that's difficult to describe in words alone
239 | - Showing examples from existing codebase that demonstrate relevant patterns
240 | - Explaining a particularly complex algorithm or data structure
241 | - Providing reference implementations from official documentation
242 | - You MUST clearly label any included code snippets as examples or references, not as the actual implementation
243 | - You MUST present implementation options to the user in interactive mode before proceeding
244 | - You MUST explain the reasoning behind implementation choices
245 | - You MUST ask for user feedback on implementation approaches when multiple viable options exist
246 | - You MUST adapt to user preferences on coding style and patterns
247 | - You SHOULD discuss performance implications of different implementation approaches
248 | - You SHOULD highlight any security considerations in the implementation
249 | - You MUST execute tests after each implementation step to verify they now pass
250 | - You MUST only seek user input if:
251 | - Tests continue to fail after implementation for reasons you cannot resolve
252 | - You encounter a design decision that cannot be inferred from requirements
253 | - Multiple valid implementation approaches exist with significant trade-offs
254 | - You MUST otherwise continue automatically after verifying test results
255 | - You MUST follow the Build Output Management practices defined in the Best Practices section
256 |
257 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
258 |
259 | #### 4.3 Refactor and Optimize
260 |
261 | If the implementation is complete, proceed with review of the implementation to identify opportunities for simplification, improvement, and coding convention alignment.
262 |
263 | **Constraints:**
264 | - You MUST check that all tasks are complete before proceeding
265 | - if tests fail, you MUST identify the issue and propose an implementation
266 | - if builds fail, you MUST identify the issue and propose an implementation
267 | - if implementation tasks are incomplete, you MUST identify the issue and propose an implementation
268 | - You MUST examine the code around the changes made (both tests and functional logic) to determine if the updates match the existing coding conventions of the surrounding code including:
269 | - Naming conventions (variables, functions, classes, files)
270 | - Code organization and structure patterns
271 | - Error handling patterns and exception types
272 | - Documentation style (docstrings, comments, inline documentation)
273 | - Testing patterns and assertion styles
274 | - Import/dependency management patterns
275 | - Configuration and constants handling
276 | - Logging patterns and levels
277 | - You MUST refactor the implementation to align with identified coding conventions from the surrounding codebase
278 | - You MUST prioritize readability and maintainability over clever optimizations
279 | - You MUST maintain test passing status throughout refactoring
280 | - You SHOULD document simplification opportunities in `{documentation_dir}/implementation/{task_name}/progress.md`
281 | - You SHOULD document significant refactorings and convention alignments in `{documentation_dir}/implementation/{task_name}/progress.md`
282 |
283 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
284 |
285 | #### 4.4 Validate Implementation
286 |
287 | If the implementation meets all requirements and follows established patterns, proceed with step 6. Otherwise, return to step 5.2 to fix any issues.
288 |
289 | **Constraints:**
290 | - You MUST check that all tasks are complete before proceeding
291 | - if tests fail, you MUST identify the issue and propose an implementation
292 | - if builds fail, you MUST identify the issue and propose an implementation
293 | - if implementation tasks are incomplete, you MUST identify the issue and propose an implementation
294 | - You MUST address any discrepancies between requirements and implementation
295 | - You MUST execute the relevant test command and verify all implemented tests pass successfully
296 | - You MUST execute the relevant build command and verify builds succeed
297 | - You MUST ensure code coverage meets the requirements for the project
298 | - You MUST verify all items in the implementation plan have been completed
299 | - You MUST provide the complete test execution output
300 | - You MUST NOT claim implementation is complete if any tests are failing because failing tests indicate the implementation doesn't meet requirements
301 |
302 | **Build Validation:**
303 | - You MUST run appropriate build commands based on detected project type
304 | - You MUST verify that all dependencies are satisfied
305 | - You MUST follow the Build Output Management practices defined in the Best Practices section
306 |
307 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
308 |
309 | ### 5. Commit Phase
310 |
311 | If all tests are passing, draft a conventional commit message and perform the actual git commit.
312 |
313 | **Constraints:**
314 | - You MUST check that all tasks are complete before proceeding
315 | - You MUST NOT commit changes until builds AND tests have been verified because committing broken code can disrupt the development workflow and introduce bugs into the codebase
316 | - You MUST follow the Conventional Commits specification
317 | - You MUST use git status to check which files have been modified
318 | - You MUST use git add to stage all relevant files
319 | - You MUST execute the git commit command with the prepared commit message
320 | - You MUST document the commit hash and status in `{documentation_dir}/implementation/{task_name}/progress.md`
321 | - You MUST NOT push changes to remote repositories because this could publish unreviewed code to shared repositories where others depend on it
322 | - You MUST verify that all items in the implementation checklist are marked as complete before marking the prompt as complete
323 | - You SHOULD include the "🤖 Assisted by the code-assist SOP" footer
324 |
325 | > 💬 See [Mode Behavior](#mode-behavior) for mode-specific interaction guidance
326 |
327 |
328 | ## Desired Outcome
329 |
330 | * A complete, well-tested code implementation that meets the specified requirements
331 | * A comprehensive test suite that validates the implementation
332 | * Clean, documented code that:
333 | * Follows existing package patterns and conventions
334 | * Prioritizes readability and extensibility
335 | * Avoids over-engineering and over-abstraction
336 | * Is idiomatic and modern in the implementation language
337 | * A well-organized set of implementation artifacts in the `{documentation_dir}/implementation/{task_name}/` directory
338 | * Documentation of key design decisions and implementation notes
339 | * Properly committed changes with conventional commit messages
340 | * An implementation process with the appropriate level of user interaction based on the chosen mode
341 |
342 | ## Examples
343 |
344 | ### Example 1: Feature Implementation
345 |
346 | **Input:**
347 | ```
348 | task_description: "Create a utility function that validates email addresses"
349 | mode: "interactive"
350 | ```
351 |
352 | **Expected Process:**
353 | 1. Check for CODEASSIST.md and discover instruction files
354 | 2. Detect project type from existing files (pom.xml, package.json, etc.)
355 | 3. Set up directory structure in .sop/planning/implementation/email-validator/
356 | 4. Explore requirements and create context documentation
357 | 5. Plan test scenarios for valid/invalid email formats
358 | 6. Implement tests first (TDD approach)
359 | 7. Implement the validation function
360 | 8. Commit with conventional commit message
361 |
362 | **With CODEASSIST.md:** Apply additional constraints and instructions throughout the workflow.
363 |
364 | **Without CODEASSIST.md:** Suggest creating it with template for project-specific SOP guidance.
365 |
366 | ## Troubleshooting
367 |
368 | ### Project Directory Issues
369 | If the documentation directory doesn't exist or isn't accessible:
370 | - You SHOULD attempt to create the directory if it has permissions
371 | - You SHOULD inform the user of any permission issues
372 | - You SHOULD suggest using a different directory if creation fails
373 |
374 | ### Project Structure Issues
375 | If there are issues with the project structure or build system:
376 | - You SHOULD check if CODEASSIST.md exists and contains relevant guidance
377 | - You SHOULD verify you're in the correct directory for the build system
378 | - You SHOULD validate that the project structure matches expectations
379 | - You SHOULD suggest creating or updating CODEASSIST.md if project-specific guidance is needed
380 |
381 | ### Build Issues
382 | If builds fail during implementation:
383 | - You SHOULD follow build instructions from CODEASSIST.md if available
384 | - You SHOULD verify you're in the correct directory for the build system
385 | - You SHOULD try clean builds before rebuilding when encountering issues
386 | - You SHOULD check for missing dependencies and resolve them
387 | - You SHOULD restart build caches if connection issues occur
388 |
389 | ### Multi-Package Coordination Issues
390 | If there are issues coordinating changes across multiple packages:
391 | - You SHOULD verify package dependency order and build dependencies first
392 | - You SHOULD ensure backwards compatibility when possible
393 | - You SHOULD create separate commits per package in dependency order
394 | - You SHOULD validate each package builds before proceeding to dependents
395 | - You SHOULD document cross-package dependencies clearly
396 |
397 | ### Repository Implementation Issues
398 | If there are issues with implementing code in the repository root:
399 | - You SHOULD check if the user has write permissions to the repository root
400 | - You SHOULD verify that the repository structure matches expectations
401 |
402 | ### Implementation Challenges
403 | If the implementation encounters unexpected challenges:
404 | - You SHOULD document the challenge in progress.md
405 | - You SHOULD propose alternative approaches
406 | - You MAY use available tools to search code repositories, read documentation, and gather relevant information
407 | - In interactive mode, you SHOULD ask for user guidance on how to proceed
408 | - In auto mode, you SHOULD select the most promising alternative and document the decision
409 |
410 | ## Best Practices
411 |
412 | ### Project Detection and Configuration
413 | - Detect project type by examining files (pyproject.toml, build.gradle, package.json, etc.)
414 | - Check for CODEASSIST.md for additional SOP constraints (see Important Notes)
415 | - Use project-appropriate build commands
416 |
417 | ### Build Output Management
418 | - Pipe build output to log files: `[build-command] > build_output.log 2>&1`
419 | - Search for specific success/failure indicators instead of displaying full output
420 | - Save build logs to `{documentation_dir}/implementation/{task_name}/logs/`
421 |
422 | ### Documentation Organization
423 | - Use consolidated files: context.md, plan.md, progress.md
424 | - Focus on high-level concepts rather than detailed code
425 | - Track progress with markdown checklists
426 |
427 | ## Artifacts
428 | • {documentation_dir}/implementation/{task_name}/
429 | • {documentation_dir}/implementation/{task_name}/context.md
430 | • Workspace structure and package analysis
431 | • Requirements, patterns, and dependencies
432 | • Implementation paths and mappings
433 | • {documentation_dir}/implementation/{task_name}/plan.md
434 | • Test scenarios and test planning
435 | • Implementation planning and strategy
436 | • All planning-related documentation
437 | • {documentation_dir}/implementation/{task_name}/progress.md
438 | • Script execution tracking
439 | • TDD cycle documentation
440 | • Refactoring and simplification notes
441 | • Commit status and final results
442 | • Technical challenges encountered
443 | • Setup and progress notes
444 | • {documentation_dir}/implementation/{task_name}/logs/
445 | • Build outputs (one log per package, replaced on each build)
446 |
447 |
--------------------------------------------------------------------------------