### Quick Start Example with Bash Commands Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/phases/01_documentation_retcon.md This markdown snippet provides a concise 'Quick Start' example for a project. It includes shell commands for installation using `curl` and basic usage commands ('myapp init', 'myapp run'), demonstrating how to integrate code snippets within documentation for immediate user action. ```markdown ## Quick Start ### Step 1: Install (30 seconds) ```bash curl -sSL https://install.sh | sh ``` ### Step 2: Run (60 seconds) ```bash myapp init myapp run ``` **First time?** The init wizard guides you. [See detailed setup →](docs/USER_GUIDE.md#setup) ``` -------------------------------- ### Install Amplifier with Specific Version Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/phases/05_testing_and_verification.md Installs the Amplifier tool from a Git repository, specifying a version tag (e.g., 'next'). This command is used for initial setup or to get a specific release of the tool. ```bash uvx --from git+https://...@next amplifier ``` -------------------------------- ### Setup Command Example - Traditional Documentation Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/core_concepts/retcon_writing.md Illustrates the traditional, non-Retcon way of documenting a deprecated command. It includes historical context and warnings about deprecation. ```markdown ## Setup Command (Deprecated) The `amplifier setup` command was used in v1.0 to configure providers. As of v2.0, this is deprecated. Use `amplifier init` instead. Example (old way - don't use): amplifier setup Example (new way - recommended): amplifier init ``` -------------------------------- ### Example /ultrathink-task Prompt for Research Synthesizer Source: https://github.com/microsoft/amplifier/blob/main/docs/CREATE_YOUR_OWN_TOOLS.md An example demonstrating how to structure the prompt for `/ultrathink-task`. It includes a tool name, a clear goal, and a detailed, numbered list of steps outlining the desired workflow for the 'Research Synthesizer' tool. This format guides Amplifier in generating the tool. ```shell /ultrathink-task I want to create a tool called "Research Synthesizer". Goal: help me research a topic by finding sources, extracting key themes, then asking me to choose which themes to explore in depth, and finally producing a summarized report. Steps: 1. Do a preliminary web research on the topic and collect notes. 2. Extract the broad themes from the notes. 3. Present me the list of themes and highlight the top 2-3 you recommend focusing on (with reasons). 4. Allow me to refine or add to that theme list. 5. Do in-depth research on the refined list of themes. 6. Draft a report based on the deep research, ensuring the report stays within my requested length and style. 7. Offer the draft for my review and incorporate any feedback. ``` -------------------------------- ### Amplifier Hook Implementation: Session Start Hook Example Source: https://github.com/microsoft/amplifier/blob/main/ai_context/AMPLIFIER_CLAUDE_CODE_LEVERAGE.md A Python example for the 'hook_session_start.py' script. It demonstrates environment-aware activation of the memory system and graceful degradation if required modules are unavailable, automatically loading relevant memories at session start. ```python # From hook_session_start.py from amplifier.memory import MemoryStore from amplifier.search import MemorySearcher async def main(): """Read input, search memories, return context""" # Check if memory system is enabled memory_enabled = os.getenv("MEMORY_SYSTEM_ENABLED", "false").lower() in ["true", "1", "yes"] # Initialize memory store and searcher store = MemoryStore() searcher = MemorySearcher(store) # Retrieve relevant memories for context ``` -------------------------------- ### Advanced Claude Code SDK Configuration Example Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/sdk/CLAUDE_CODE_SDK_PYTHON.md Demonstrates advanced configuration options for ClaudeSDKClient, including custom working directories, additional context, model and thinking token limits, tool control, custom settings, and extra CLI arguments. This example requires the claude_code_sdk to be installed. ```python import asyncio from claude_code_sdk import ClaudeSDKClient, ClaudeCodeOptions async def advanced_agent(): """Example showcasing advanced configuration options""" async with ClaudeSDKClient( options=ClaudeCodeOptions( # Custom working directory and additional context cwd="/project/root", add_dirs=["/shared/libs", "/common/utils"], # Model and thinking configuration model="claude-3-5-sonnet-20241022", max_thinking_tokens=12000, # Advanced tool control allowed_tools=["Read", "Write", "Bash", "Grep"], disallowed_tools=["WebSearch", "Bash(rm*)"], # Custom settings and CLI args settings='{"editor": "vim", "theme": "dark"}', extra_args={ "--verbose": None, "--timeout": "300" } ) ) as client: await client.query("Analyze the codebase structure") async for message in client.receive_response(): if hasattr(message, 'content'): for block in message.content: if hasattr(block, 'text'): print(block.text, end='', flush=True) asyncio.run(advanced_agent()) ``` -------------------------------- ### Integrating Amplifier Agents and Knowledge Base Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md Demonstrates how to use Amplifier agents and access the shared knowledge base from different worktrees. It shows starting an agent and querying the knowledge base, highlighting that results are consistent across all worktrees. ```bash # In any worktree cd ../amplifier.my-experiment claude # Start Claude with all agents available # "Use zen-architect to design this experiment" # In any worktree make knowledge-query Q="authentication patterns" # Gets same results across all worktrees ``` -------------------------------- ### Install Python Dependencies Source: https://github.com/microsoft/amplifier/blob/main/docs/claude-code-sessions/examples/README.md Installs the required Python packages for the project using pip. This command reads dependencies from the 'requirements.txt' file. ```bash pip install -r requirements.txt ``` -------------------------------- ### Run Amplifier Initialization Wizard Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/phases/05_testing_and_verification.md Executes the Amplifier command, which automatically launches an initialization wizard for first-time setup. The wizard guides the user through selecting a provider, entering API keys, choosing models, and setting up profiles. ```bash amplifier ``` -------------------------------- ### Example: Historical References in Documentation Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/core_concepts/context_poisoning.md Highlights the ambiguity created by including both old and new command references in documentation. This snippet shows how the coexistence of `setup` and `init` commands can confuse AI about the current best practice. ```markdown # docs/MIGRATION.md Previously, use `amplifier setup`. Now, use `amplifier init` instead. The old `setup` command still works. # POISON: Should AI implement setup, init, or both? ``` -------------------------------- ### Cross-Machine Workflow with Worktrees (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md This example outlines a cross-machine workflow using Amplifier's Git worktrees. It shows how to push a branch from one machine and then adopt that branch as a worktree on another machine to continue development seamlessly. ```bash # Machine A (office): make worktree my-feature # ...work on feature... cd ../amplifier.my-feature git push -u origin my-feature # Machine B (home): make worktree-adopt my-feature cd ../amplifier.my-feature # ...continue work... ``` -------------------------------- ### Worktree Naming Conventions for Development (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md This code provides examples of recommended naming conventions for creating Git worktrees with Amplifier, categorized by purpose such as feature development, bug fixes, and experiments, including the use of namespaces. ```bash # Feature development make worktree feat-authentication # Bug fixes make worktree fix-login-error # Experiments make worktree exp-new-algorithm # With namespaces make worktree myname/feat-caching ``` -------------------------------- ### Shell Aliases for Worktree Navigation Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md Example shell aliases for `~/.bashrc` or `~/.zshrc` to quickly navigate between Amplifier worktrees and list active worktrees. These aliases streamline workflow by reducing repetitive commands. ```bash # In ~/.bashrc or ~/.zshrc alias wt-main='cd ~/repos/amplifier' alias wt-list='cd ~/repos/amplifier && make worktree-list' alias wt-cd='cd ~/repos/amplifier..$1' ``` -------------------------------- ### Install Project Dependencies (Shell) Source: https://github.com/microsoft/amplifier/blob/main/AGENTS.md Command to install project dependencies using 'uv', which is the preferred package manager for this project. This command typically sets up the virtual environment and installs necessary packages defined in the project configuration. ```shell make install ``` -------------------------------- ### AGENTS.md Example Content Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKSPACE_PATTERN.md An example of the content for an AGENTS.md file, including project overview, core principles, key technologies, project structure, development workflow, common tasks, and things to avoid. ```markdown # My Blog Platform Context This file provides guidance to AI assistants working on this blog platform. ## Project Overview A personal blog platform built with Next.js and Markdown, focused on fast static generation and rich media support. The architecture prioritizes simplicity over flexibility—we'd rather have less features done well than many features done poorly. ## Core Principles - **Ruthless simplicity**: Every feature must justify its existence - **Static-first**: Generate at build time, serve static HTML - **Markdown is truth**: Blog posts live in `/content` as Markdown files - **No database**: File system is our storage layer ## Key Technologies - Next.js 14 (App Router) - TypeScript (strict mode) - TailwindCSS for styling - gray-matter for frontmatter parsing - remark/rehype for Markdown processing ## Project Structure ```bash src/ ├── app/ # Next.js app router pages ├── components/ # React components ├── lib/ # Utilities and shared logic └── types/ # TypeScript type definitions content/ # Blog posts (Markdown) public/ # Static assets ``` ## Development Workflow 1. Run dev server: `pnpm dev` 2. Posts go in `content/posts/YYYY-MM-DD-slug.md` 3. Images go in `public/images/` 4. Test builds with `pnpm build` ## Common Tasks - **Add new post**: Create Markdown file in `content/posts/` - **Add component**: Create in `src/components/`, export from index - **Update types**: Modify `src/types/blog.ts` - **Deploy**: Push to main, Vercel auto-deploys ## Things to Avoid - Don't add a database (we're committed to file-based) - Don't create complex state management (keep it simple) - Don't add build-time external API calls (they slow builds) The key is making this document useful for both AI assistants and human developers. It should answer: What is this project? How is it architected? What conventions do we follow? What should I avoid? ``` -------------------------------- ### Clone Amplifier Repository and Install Dependencies Source: https://github.com/microsoft/amplifier/blob/main/README.md Clones the Amplifier repository from GitHub and installs its project dependencies using the 'make install' command. It also shows how to activate the created virtual environment. ```bash # Clone Amplifier repository git clone https://github.com/microsoft/amplifier.git amplifier cd amplifier # Install dependencies make install # Activate virtual environment source .venv/bin/activate # Linux/Mac/WSL # .venv\Scripts\Activate.ps1 # Windows PowerShell ``` -------------------------------- ### Install Amplifier Dependencies Source: https://github.com/microsoft/amplifier/blob/main/amplifier/README.md Installs optional dependencies for the Amplifier Memory System, including sentence-transformers for semantic search and the Claude Code SDK for AI extraction. Installation commands are provided for both Python and Node.js environments. ```bash # Install optional dependencies for full functionality uv add sentence-transformers # For semantic search npm install -g @anthropic-ai/claude-code # For AI extraction ``` -------------------------------- ### Install Dependencies and Activate Environment Source: https://github.com/microsoft/amplifier/blob/main/README.md Installs project dependencies using 'make install' and activates the Python virtual environment. Provides commands for both Linux/Mac/WSL and Windows PowerShell. ```bash # Install dependencies make install # Activate virtual environment source .venv/bin/activate # Linux/Mac/WSL # .venv\Scripts\Activate.ps1 # Windows PowerShell ``` -------------------------------- ### Install Ubuntu/Debian Prerequisites Source: https://github.com/microsoft/amplifier/blob/main/README.md Installs necessary packages on Ubuntu, Debian, or WSL systems. It includes system packages like Python and Node.js, global installation of pnpm, and installation of uv. ```bash # System packages sudo apt update && sudo apt install -y python3 python3-pip nodejs npm git # pnpm npm install -g pnpm pnpm setup && source ~/.bashrc # uv (Python package manager) curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Install Claude Code SDK (Bash) Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/README.md These commands install the necessary packages for using the Claude Code SDK. The first command installs the Python package 'claude-code-sdk' using pip. The second command installs the Claude CLI globally using npm. The third command is an alternative for installing the Python package if using the amplifier project. ```bash # Install Python package pip install claude-code-sdk # Install Claude CLI (required) npm install -g @anthropic-ai/claude-code # Or if using the amplifier project uv add claude-code-sdk ``` -------------------------------- ### Run Code Complexity Analyzer CLI Tool Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/README.md Shows how to use the Code Complexity Analyzer CLI tool. This example requires the Claude CLI to be installed and demonstrates analyzing single files, directories recursively, processing output as JSON, and resuming previous analysis sessions. It also highlights batch processing with the --limit flag. ```bash # First ensure Claude CLI is installed which claude # Should return a path # Run from project root directory cd /path/to/amplifier-ccsdk-sdk # Analyze a single file python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py main.py # Analyze directory recursively python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py src/ --recursive --pattern "*.py" # Output as JSON python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py src/ --json --output results.json # Resume previous session python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py src/ --resume session-id # Example analyzing the toolkit itself python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py amplifier/ccsdk_toolkit/core/__init__.py # Process large codebases in manageable chunks python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py src/ --recursive --pattern "*.py" --limit 5 # Process next batch of files using resume python amplifier/ccsdk_toolkit/examples/code_complexity_analyzer.py src/ --recursive --pattern "*.py" --limit 5 --resume session-id ``` -------------------------------- ### Install Mac Prerequisites Source: https://github.com/microsoft/amplifier/blob/main/README.md Installs essential development tools on macOS using Homebrew, including Python, Node.js, Git, pnpm, and uv. ```bash brew install python3 node git pnpm uv ``` -------------------------------- ### Run Tips Synthesizer with Make Source: https://github.com/microsoft/amplifier/blob/main/scenarios/tips_synthesizer/README.md This command initiates the tips synthesizer process using a Makefile. It specifies the input directory containing markdown tips and the desired output file for the synthesized guide. Optional arguments like VERBOSE can be added for detailed logging. ```bash make tips-synthesizer \ INPUT=path/to/tips/directory/ \ OUTPUT=synthesized_tips.md ``` ```bash make tips-synthesizer \ INPUT=my_tips/ \ OUTPUT=ultimate_guide.md \ VERBOSE=true ``` ```bash make tips-synthesizer \ INPUT=scattered_tips/ \ OUTPUT=organized_guide.md ``` ```bash make tips-synthesizer \ INPUT=scattered_tips/ \ OUTPUT=organized_guide.md \ RESUME=true ``` ```bash make tips-synthesizer \ INPUT=my_tips/ \ OUTPUT=guide.md \ --dry-run ``` -------------------------------- ### Manual venv Setup with make install (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_VENV_MANAGEMENT.md If automatic virtual environment setup fails, this command can be used to manually create the `.venv` and install dependencies within a specific worktree directory. ```bash cd ../amplifier-my-feature make install # This creates .venv and installs dependencies ``` -------------------------------- ### Set Up Amplifier Workspace and Add Project Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKSPACE_PATTERN.md This snippet demonstrates the initial steps to create a new Amplifier workspace by cloning the repository and adding an existing project as a git submodule. It also includes instructions for setting up project-specific context using an AGENTS.md file. ```bash # 1. Create your Amplifier workspace git clone https://github.com/microsoft/amplifier.git my-workspace cd my-workspace # 2. Add your project (existing or new) git submodule add my-project # OR: git submodule add git@github.com:yourname/your-project.git my-project # 3. Set up project context cd my-project cat > AGENTS.md << 'EOF' # My Project Context This file provides guidance to AI assistants working with this project. ## Project Overview [Brief description of what this project does] ## Working in This Project When working on this project: - All project files belong in this directory - Use `ai_working/` for temporary files - Reference files with `@my-project/` prefix - Follow our design principles at @my-project/docs/DESIGN.md ## Key Technologies - [List your main technologies/frameworks] ## Development Workflow - [Your specific workflow notes] EOF # 4. Start working cd .. claude ``` -------------------------------- ### Example: Example Conflicts in Documentation Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/core_concepts/context_poisoning.md Shows how differing command examples in various documentation files can confuse AI tools. This snippet presents a discrepancy in the `amplifier provider use` command syntax between the README and user guide. ```markdown # README.md amplifier provider use anthropic # docs/USER_GUIDE.md amplifier provider use anthropic --model claude-opus-4 # POISON: Which example is correct? ``` -------------------------------- ### SlashCommand Tool Invocation Example Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/CLAUDE_CODE_SLASH_COMMANDS.md This example illustrates how to instruct Claude to trigger the SlashCommand tool programmatically by referencing a custom command with its slash prefix. This guides Claude to invoke the command when appropriate during a conversation. ```bash > Run /write-unit-test when you are about to start writing tests. ``` -------------------------------- ### Python Configuration Reading Example Source: https://github.com/microsoft/amplifier/blob/main/AGENTS.md Demonstrates the correct way to read configuration from a `pyproject.toml` file using `tomllib` in Python, contrasting it with hardcoding values. This ensures consistency across the project. ```python # Good: Read from authoritative source config = tomllib.load(open("pyproject.toml", "rb")) excludes = config["tool"]["pyright"]["exclude"] # Bad: Hardcode the same values excludes = [".venv", "__pycache__", "node_modules"] ``` -------------------------------- ### Install uv Package Manager (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_VENV_MANAGEMENT.md This command downloads and installs the `uv` package manager using a script from its official distribution. It's a prerequisite for the automatic venv setup. ```bash curl -LsSf https://astral.sh/uv/install.sh | sh ``` -------------------------------- ### Create and Manage Worktrees (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md This snippet demonstrates the basic workflow for creating, navigating, and removing Git worktrees using Amplifier's `make worktree` command. It highlights the isolation of environments and ease of switching. ```bash # Create a new worktree for experimentation make worktree my-feature # Navigate to the new worktree cd ../amplifier.my-feature # Work on your feature (already has .venv set up!) # ...make changes, test, etc... # When done, remove it make worktree-rm my-feature ``` -------------------------------- ### Run Amplifier Knowledge Synthesis Sync Command Source: https://github.com/microsoft/amplifier/blob/main/docs/KNOWLEDGE_SYNTHESIS_PATHS.md Shows examples of how to run the Amplifier knowledge synthesis sync command using the command-line interface. It includes examples for using the default configuration and configuring custom paths via environment variables before syncing. ```bash # Use default configuration python -m amplifier.knowledge_synthesis.cli sync # Configure custom paths export AMPLIFIER_DATA_DIR="~/.amplifier" export AMPLIFIER_CONTENT_DIRS="~/content, ~/repos/articles, /shared/team" python -m amplifier.knowledge_synthesis.cli sync ``` -------------------------------- ### Simple Python Cache Implementation Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/DEVELOPER_GUIDE.md Demonstrates a basic Python dictionary for caching, adhering to the principle of starting simple and adding complexity only when necessary. ```python # Start simple cache = {} # Add complexity only when needed ``` -------------------------------- ### Avoid AI for Simple String Manipulation (Python) Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/DEVELOPER_GUIDE.md This snippet illustrates the anti-pattern of using AI for tasks that can be easily accomplished with standard code. The 'Wrong' example shows an AI call for simple capitalization, while the 'Right' example uses Python's built-in `.upper()` method, highlighting efficiency and simplicity. ```python # Wrong: Using AI for simple string manipulation async def capitalize_text_wrong(text): response = await claude_sdk.query(f"Capitalize this: {text}") return response # Right: Using standard code def capitalize_text_right(text): return text.upper() ``` -------------------------------- ### Execute example_parser.py Command-Line Tool (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/claude-code-sessions/examples/README.md Demonstrates various command-line arguments for the `example_parser.py` script, which analyzes Claude Code sessions. It covers default usage, custom output directories, listing projects/sessions, and parsing specific projects, sessions, or files. ```bash # Parse the most recent session across all projects python example_parser.py # Creates: ./output/{project}/{session}/analysis.md and session.jsonl # Use custom output directory python example_parser.py --output ./my-analysis # List all available projects and sessions python example_parser.py --list # Parse most recent session from a specific project python example_parser.py --project amplifier # Parse a specific session file python example_parser.py /path/to/session.jsonl ``` -------------------------------- ### Quick Start: Basic Query with Claude Agent SDK Source: https://github.com/microsoft/amplifier/blob/main/ai_context/git_collector/CLAUDE_CODE_SDK_PYTHON_REPO.md Demonstrates a basic asynchronous query to Claude Code using the `query` function from the `claude_agent_sdk`. It prints the response messages. Requires the `anyio` library for running async code. ```python import anyio from claude_agent_sdk import query async def main(): async for message in query(prompt="What is 2 + 2?"): print(message) anyio.run(main) ``` -------------------------------- ### Copy .env.example to .env using Bash Source: https://github.com/microsoft/amplifier/blob/main/amplifier/knowledge_mining/CONFIG_README.md Shows the command to copy the example environment file to a new file named .env, which is the first step in setting up custom configurations for the Knowledge Mining system. ```bash cp .env.example .env ``` -------------------------------- ### Utilize Parallel Processing for Independent Tasks (Python) Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/DEVELOPER_GUIDE.md This snippet demonstrates the anti-pattern of sequential processing when parallel execution is more efficient. The 'Wrong' example processes documents one by one, leading to slow performance. The 'Right' example uses `asyncio.gather` to process documents concurrently, significantly improving speed for independent operations. ```python # Wrong: Process one at a time # for doc in documents: # result = await process(doc) # Slow! # results.append(result) # Right: Process in parallel tasks = [process(doc) for doc in documents] results = await asyncio.gather(*tasks) ``` -------------------------------- ### Example of Mode Progression (TypeScript) Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/sdk/CLAUDE_CODE_SDK_HANDLING_PERMISSIONS.md Demonstrates a typical progression of permission modes in a TypeScript environment, starting with 'default' for controlled execution and switching to 'acceptEdits' for faster iteration. This pattern helps manage risk and efficiency. ```typescript // Start in default mode for controlled execution permissionMode: "default"; // Switch to acceptEdits for rapid iteration await q.setPermissionMode("acceptEdits"); ``` -------------------------------- ### Create Worktree with Automatic venv Setup (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_VENV_MANAGEMENT.md This command creates a new git worktree, automatically sets up a local virtual environment using `uv`, and installs dependencies. ```bash # Create worktree with automatic venv setup make worktree my-feature # The output will show: # 🐍 Setting up virtual environment for worktree... # ✅ Virtual environment created and dependencies installed! # Navigate to the worktree cd ../amplifier-my-feature # The venv is already set up and ready to use! ``` -------------------------------- ### Describe Tool Requirements using Ultrathink Task Source: https://github.com/microsoft/amplifier/blob/main/scenarios/web_to_md/HOW_TO_CREATE_YOUR_OWN.md This is an example of how to use the `/ultrathink-task` command to describe the functionality of a web page to markdown conversion tool. It includes placeholder text for specific details like saving locations and metadata requirements. The input is a natural language description of the desired tool's behavior and organization. ```bash /ultrathink-task I want to create a tool that converts web pages to markdown and saves them organized by domain. [Include details about where to save, what metadata to include, etc.] ``` -------------------------------- ### Separate AI Intelligence from Code Mechanics (Python) Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/DEVELOPER_GUIDE.md This code demonstrates the anti-pattern of mixing AI responsibilities with mechanical tasks. The 'Wrong' example includes a single AI prompt for entity extraction, validation, database saving, notifications, and caching. The 'Right' example separates these concerns: AI extracts entities, while Python code handles validation, database operations, and notifications. ```python # Wrong: AI doing everything # prompt = """ # Extract entities, validate format, save to database, # send notifications, and update cache for this document # """ # Right: AI for intelligence, code for mechanics entities = await ai_extract_entities(doc) validated = code_validate_format(entities) code_save_to_database(validated) code_send_notifications(validated) ``` -------------------------------- ### Initial Configuration Command - Retcon Example Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/core_concepts/retcon_writing.md Shows the Retcon approach for documenting the initial configuration command. It presents the command in the present tense, assuming it's the current and only method. ```bash amplifier init ``` -------------------------------- ### Parallel Testing with Transcripts in Worktrees Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md Illustrates how to perform parallel testing by using separate worktrees for different approaches and preserving conversation history using the `/compact` command. Includes a command to search across multiple transcripts. ```bash # In worktree 1 claude # Design approach A # /compact when needed (auto-saves transcript) # In worktree 2 claude # Design approach B # /compact when needed (separate transcript) # Later, compare transcripts make transcript-search TERM="performance" ``` -------------------------------- ### Implement Error Handling for AI Operations (Python) Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/DEVELOPER_GUIDE.md This code addresses the anti-pattern of lacking error handling in AI operations. The 'Wrong' example shows a direct call without checks, potentially leading to silent failures. The 'Right' example implements a try-except block to catch exceptions and check for successful results from the AI query, ensuring failures are explicitly handled. ```python # Wrong: No error handling = silent failures # result = await client.query(prompt) # process_result(result) # What if query failed? # Right: Always handle potential failures try: result = await client.query(prompt) if result and result.success: process_result(result) else: handle_failure("Query returned no results") except Exception as e: log_error(f"Query failed: {e}") raise # Or handle appropriately ``` -------------------------------- ### Clear Conversation History (TypeScript) Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/sdk/CLAUDE_CODE_SDK_SLASH_COMMANDS.md This TypeScript example shows how to use the `/clear` slash command to reset the conversation, effectively starting a fresh session. It logs confirmation and the new session ID. ```typescript import { query } from "@anthropic-ai/claude-code"; // Clear conversation and start fresh for await (const message of query({ prompt: "/clear", options: { maxTurns: 1 } })) { if (message.type === "system" && message.subtype === "init") { console.log("Conversation cleared, new session started"); console.log("Session ID:", message.session_id); } } ``` -------------------------------- ### Command-Line Usage for DOT to Mermaid Conversion Source: https://github.com/microsoft/amplifier/blob/main/ai_working/dot_to_mermaid/README.md Examples of using the DOT to Mermaid converter via the command line, demonstrating conversion of directories, single files, and various options like output directory, session management, and verbosity. ```bash # Convert all DOT files in a directory python -m ai_working.dot_to_mermaid.cli /path/to/dot/files # Convert a single file python -m ai_working.dot_to_mermaid.cli /path/to/file.dot # Using make (automatically stores session in .data/) make dot-to-mermaid INPUT="/path/to/dot/files" # Specify output directory python -m ai_working.dot_to_mermaid.cli input_path --output mermaid_output # Specify session file location (for progress tracking and resume) python -m ai_working.dot_to_mermaid.cli input_path --session-file /path/to/session.json # Clear previous session and start fresh python -m ai_working.dot_to_mermaid.cli input_path --clear-session # Verbose output for debugging python -m ai_working.dot_to_mermaid.cli input_path --verbose # Combine options python -m ai_working.dot_to_mermaid.cli /path/to/files \ --output mermaid_out \ --session-file .data/session.json \ --verbose ``` -------------------------------- ### Get Session ID and Resume Conversation (Python) Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/sdk/CLAUDE_CODE_SDK_SESSION_MANAGEMENT.md Shows how to obtain the session ID from the initial system message in a Python conversation and subsequently use it for session resumption. This example uses the 'claude_code_sdk'. ```python from claude_code_sdk import query, ClaudeCodeOptions session_id = None async for message in query( prompt="Help me build a web application", options=ClaudeCodeOptions( model="claude-sonnet-4-20250514" ) ): # The first message is a system init message with the session ID if hasattr(message, 'subtype') and message.subtype == 'init': session_id = message.data.get('session_id') print(f"Session started with ID: {session_id}") # You can save this ID for later resumption # Process other messages... print(message) # Later, you can use the saved session_id to resume if session_id: async for message in query( prompt="Continue where we left off", options=ClaudeCodeOptions( resume=session_id ) ): print(message) ``` -------------------------------- ### Initial Configuration Command - Retcon Example (Expanded) Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/core_concepts/retcon_writing.md Presents the Retcon approach for documenting the initial configuration command, including a brief explanation of its function. ```markdown ## Initial Configuration Configure Amplifier on first use: ```bash amplifier init ``` The init wizard guides you through provider and profile selection. ``` -------------------------------- ### Implement Interactive Tool Approval Callback (Python) Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/sdk/CLAUDE_CODE_SDK_HANDLING_PERMISSIONS.md This Python example shows how to implement the `can_use_tool` callback for interactive tool approval. It prints tool requests and parameters to the console and uses Python's `input()` function to get user consent. ```python from claude_code_sdk import query import json async def prompt_for_tool_approval(tool_name: str, input_params: dict): print(f"\n🔧 Tool Request:") print(f" Tool: {tool_name}") # Display parameters if input_params: print(" Parameters:") for key, value in input_params.items(): display_value = value if isinstance(value, str) and len(value) > 100: display_value = value[:100] + "..." elif isinstance(value, (dict, list)): display_value = json.dumps(value, indent=2) print(f" {key}: {display_value}") # Get user approval answer = input("\n Approve this tool use? (y/n): ") if answer.lower() in ['y', 'yes']: print(" ✅ Approved\n") return { "behavior": "allow", "updatedInput": input_params } else: print(" ❌ Denied\n") return { "behavior": "deny", "message": "User denied permission for this tool" } # Use the permission callback result = await query( prompt="Help me analyze this codebase", options={ "can_use_tool": prompt_for_tool_approval } ) ``` -------------------------------- ### Copying Amplifier Tool Template Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/DEVELOPER_GUIDE.md Provides the command to copy the base tool template when starting a new amplifier CLI tool. This ensures that all necessary defensive patterns discovered through real-world failures are included from the beginning. ```bash cp amplifier/ccsdk_toolkit/templates/tool_template.py [destination]/[tool_name].py ``` -------------------------------- ### Initialize and Use ContentLoader in Python Source: https://github.com/microsoft/amplifier/blob/main/amplifier/content_loader/README.md Demonstrates how to initialize the ContentLoader class, either by using an environment variable or by passing a list of directories directly. It also shows how to load all content, search for specific keywords, and retrieve content by its ID. ```python from amplifier.content_loader import ContentLoader, ContentItem # Initialize loader loader = ContentLoader() # Uses AMPLIFIER_CONTENT_DIRS env var # OR loader = ContentLoader(content_dirs=["/path/to/content", "/another/path"]) # Load all content for item in loader.load_all(): print(f"{item.title}: {item.content_id}") # Search content for item in loader.search("keyword"): print(f"Found in: {item.title}") # Get specific item item = loader.get_by_id("abc123def456") ``` -------------------------------- ### Context Injection Markdown Example Source: https://github.com/microsoft/amplifier/blob/main/ai_context/AMPLIFIER_CLAUDE_CODE_LEVERAGE.md Demonstrates the Context Injection implementation pattern using Markdown, showing how to reference specific implementation details within documents. ```markdown # In any document: For implementation details, see @ai_context/IMPLEMENTATION.md ``` -------------------------------- ### Create Worktrees with Namespaced Branches (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md This code shows how to create Git worktrees using Amplifier, including support for namespaced branches, which is useful for team collaboration. It details the directory structure, branch naming, and environment setup that occurs. ```bash # Basic usage make worktree feature-name # With namespaced branches (e.g., for teams) make worktree username/feature-name ``` -------------------------------- ### Progressive Documentation Organization Hierarchy Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/phases/01_documentation_retcon.md This markdown snippet visualizes a recommended documentation hierarchy, starting from a top-level README and branching out to more detailed sections like User Guides, API References, and Architecture. It emphasizes progressive reveal and audience-appropriateness. ```markdown README.md (Entry Point) ├─ Introduction (what is this?) ├─ Quick Start (working in 90 seconds) ├─ Key Concepts (3-5 ideas, brief) └─ Next Steps (where to learn more) ├─ → User Guide (detailed usage) ├─ → Developer Guide (contributing) ├─ → API Reference (technical) └─ → Architecture (system design) ``` -------------------------------- ### Bash: Test Environment Setup for Amplifier Source: https://github.com/microsoft/amplifier/blob/main/docs/document_driven_development/phases/05_testing_and_verification.md This snippet demonstrates setting up a clean test environment for the Amplifier tool by removing existing configuration directories. It includes verification steps to ensure the environment is clean before proceeding with tests. ```bash # Fresh environment rm -rf ~/.amplifier .amplifier # Verify clean state ls ~/.amplifier # Should not exist ``` -------------------------------- ### Execute example_transcript_builder.py Command-Line Tool (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/claude-code-sessions/examples/README.md Illustrates command-line usage for `example_transcript_builder.py`, a tool that generates readable transcripts from Claude Code session files. Examples include default execution, custom output, including system messages, and specifying projects/sessions. ```bash # Build a transcript from the most recent session python example_transcript_builder.py # Creates: ./output/{project}/{session}/transcript.md and session.jsonl # Use custom output directory python example_transcript_builder.py --output ./my-transcripts # Build transcript with system messages included python example_transcript_builder.py --include-system # Specify project and session python example_transcript_builder.py --project amplifier --session abc123 ``` -------------------------------- ### Interrupting Long-Running Tasks with Claude SDK Source: https://github.com/microsoft/amplifier/blob/main/ai_context/git_collector/CLAUDE_CODE_SDK_PYTHON_REPO.md Demonstrates how to interrupt a long-running task in the Claude SDK. This requires active message consumption. The example sends a task, starts a background consumer, sends an interrupt after a delay, and then sends a new message to show continued interaction. ```python # IMPORTANT: Interrupts require active message consumption. You must be # consuming messages from the client for the interrupt to be processed. from claude_agent_sdk import AssistantMessage, ClaudeSDKClient, TextBlock, ResultMessage import asyncio async with ClaudeSDKClient() as client: print("\n--- Sending initial message ---") # Send a long-running task print("User: Count from 1 to 100, run bash sleep for 1 second in between") await client.query("Count from 1 to 100, run bash sleep for 1 second in between") # Create a background task to consume messages messages_received = [] interrupt_sent = False async def consume_messages(): async for msg in client.receive_messages(): messages_received.append(msg) if isinstance(msg, AssistantMessage): for block in msg.content: if isinstance(block, TextBlock): print(f"Claude: {block.text}") # Check if we got a result after interrupt if isinstance(msg, ResultMessage) and interrupt_sent: break # Start consuming messages in the background consume_task = asyncio.create_task(consume_messages()) # Wait a bit then send interrupt await asyncio.sleep(10) print("\n--- Sending interrupt ---") interrupt_sent = True await client.interrupt() # Wait for the consume task to finish await consume_task # Send a new message after interrupt print("\n--- After interrupt, sending new message ---") await client.query("Just say 'Hello! I was interrupted.'") async for msg in client.receive_response(): if isinstance(msg, AssistantMessage): for block in msg.content: if isinstance(block, TextBlock): print(f"Claude: {block.text}") ``` -------------------------------- ### Test Interrupt Capability in Python Source: https://github.com/microsoft/amplifier/blob/main/ai_context/git_collector/CLAUDE_CODE_SDK_PYTHON_REPO.md Demonstrates how to interrupt a long-running task sent to the ClaudeSDKClient. It starts a task, waits for a short period, sends an interrupt signal, and then sends a new query. This example highlights the client's ability to handle interruptions and resume operations. ```python print("\n2. Testing interrupt capability...") # Start a long-running task print("User: Count from 1 to 20 slowly") await client.query("Count from 1 to 20 slowly, pausing between each number") # Start consuming messages in background to enable interrupt messages = [] async def consume(): async for msg in client.receive_response(): messages.append(msg) if isinstance(msg, AssistantMessage): for block in msg.content: if isinstance(block, TextBlock): # Print first 50 chars to show progress print(f"Claude: {block.text[:50]}...") break if isinstance(msg, ResultMessage): break consume_task = asyncio.create_task(consume()) # Wait a moment then interrupt await asyncio.sleep(2) print("\n[Sending interrupt after 2 seconds...]") try: await client.interrupt() print("✓ Interrupt sent successfully") except Exception as e: print(f"✗ Interrupt failed: {e}") # Wait for task to complete with contextlib.suppress(asyncio.CancelledError): await consume_task # Send new query after interrupt print("\nUser: Just say 'Hello!'") await client.query("Just say 'Hello!'") async for msg in client.receive_response(): if isinstance(msg, AssistantMessage): for block in msg.content: if isinstance(block, TextBlock): print(f"Claude: {block.text}") print("\n") ``` -------------------------------- ### Migration Example: External to In-Process MCP Servers Source: https://github.com/microsoft/amplifier/blob/main/ai_context/git_collector/CLAUDE_CODE_SDK_PYTHON_REPO.md Compares the configuration for using an external MCP server (running in a separate process) versus an in-process SDK MCP server. The in-process version simplifies setup by running tools directly within the Python application. ```python # BEFORE: External MCP server (separate process) options = ClaudeAgentOptions( mcp_servers={ "calculator": { "type": "stdio", "command": "python", "args": ["-m", "calculator_server"] } } ) # AFTER: SDK MCP server (in-process) from my_tools import add, subtract # Your tool functions calculator = create_sdk_mcp_server( name="calculator", tools=[add, subtract] ) options = ClaudeAgentOptions( mcp_servers={"calculator": calculator} ) ``` -------------------------------- ### Claude Code Text Output Example Source: https://github.com/microsoft/amplifier/blob/main/ai_context/claude_code/sdk/CLAUDE_CODE_SDK_HEADLESS_MODE.md This bash command shows a simple use case for getting text output from Claude Code in headless mode. It prompts the CLI to explain a specific file, and the expected output is a textual description of that file's content. ```bash claude -p "Explain file src/components/Header.tsx" # Output: This is a React component showing... ``` -------------------------------- ### Git Worktree Management Commands Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md Reference for common Git worktree operations within Amplifier, including creation, listing, removal, stashing, and adopting branches. These commands facilitate managing multiple isolated development environments. ```bash make worktree NAME make worktree-list make worktree-rm NAME make worktree-rm-force NAME make worktree-stash NAME make worktree-unstash NAME make worktree-list-stashed make worktree-adopt BRANCH ``` -------------------------------- ### Initialize Project Context with Claude Source: https://github.com/microsoft/amplifier/blob/main/README.md Sets up project-specific AI guidance by creating an AGENTS.md file and then invokes the 'claude' command to start interacting with the AI, providing initial context. ```bash # Set up project context & start Claude echo "# Project-specific AI guidance" > my-project/AGENTS.md claude ``` -------------------------------- ### Python: Handle Missing 'version' Field with Default Source: https://github.com/microsoft/amplifier/blob/main/docs/claude-code-sessions/troubleshooting.md This Python example shows how to safely access the 'version' field from a message dictionary, providing a default value ('unknown') if the field is missing. This prevents `KeyError` exceptions and ensures that a version value is always available for processing, even for older or malformed message entries. ```python version = message.get("version", "unknown") ``` -------------------------------- ### Information Gathering Example Source: https://github.com/microsoft/amplifier/blob/main/CLAUDE.md Shows how to gather information in parallel before implementing features. This includes searching for patterns, reading main implementation files, test files, and configuration files. ```tool_calls - Grep: Search for existing patterns - Read: Main implementation file - Read: Test file - Read: Related configuration ``` -------------------------------- ### Python: Basic Claude SDK Query Source: https://github.com/microsoft/amplifier/blob/main/ai_context/git_collector/CLAUDE_CODE_SDK_PYTHON_REPO.md Demonstrates a basic asynchronous query to the Claude API using the `query` function. It prints the assistant's text response. This example requires the `claude_agent_sdk` and `anyio` libraries. ```python #!/usr/bin/env python3 """Quick start example for Claude Code SDK.""" import anyio from claude_agent_sdk import ( AssistantMessage, ClaudeAgentOptions, ResultMessage, TextBlock, query, ) async def basic_example(): """Basic example - simple question.""" print("=== Basic Example ===") async for message in query(prompt="What is 2 + 2?"): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): print(f"Claude: {block.text}") print() async def with_options_example(): """Example with custom options.""" print("=== With Options Example ===") options = ClaudeAgentOptions( system_prompt="You are a helpful assistant that explains things simply.", max_turns=1, ) async for message in query( prompt="Explain what Python is in one sentence.", options=options ): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): print(f"Claude: {block.text}") print() async def with_tools_example(): """Example using tools.""" print("=== With Tools Example ===") options = ClaudeAgentOptions( allowed_tools=["Read", "Write"], system_prompt="You are a helpful file assistant.", ) async for message in query( prompt="Create a file called hello.txt with 'Hello, World!' in it", options=options, ): if isinstance(message, AssistantMessage): for block in message.content: if isinstance(block, TextBlock): print(f"Claude: {block.text}") elif isinstance(message, ResultMessage) and message.total_cost_usd > 0: print(f"\nCost: ${message.total_cost_usd:.4f}") print() async def main(): """Run all examples.""" await basic_example() await with_options_example() await with_tools_example() if __name__ == "__main__": anyio.run(main) ``` -------------------------------- ### Defensive LLM Response Processing in Python Source: https://github.com/microsoft/amplifier/blob/main/amplifier/ccsdk_toolkit/defensive/README.md Demonstrates a canonical example of using defensive utilities for LLM integration. It shows how to isolate user content using `isolate_prompt`, get an LLM response, parse the JSON output defensively with `parse_llm_json` (providing a default value), and save the result with cloud sync awareness using `write_json_with_retry`. ```python from amplifier.ccsdk_toolkit.defensive import parse_llm_json, isolate_prompt # 1. Isolate user content safe_content = isolate_prompt(user_text) # 2. Get LLM response response = await llm.complete(f"Analyze: {safe_content}") # 3. Parse defensively with fallback result = parse_llm_json(response, default={"status": "unknown"}) # 4. Save with cloud sync awareness write_json_with_retry(result, output_path) ``` -------------------------------- ### Parallel Experimentation Workflow (Bash) Source: https://github.com/microsoft/amplifier/blob/main/docs/WORKTREE_GUIDE.md This snippet illustrates a pattern for parallel experimentation using Amplifier's worktrees. It shows how to create multiple worktrees for different approaches, test them independently, and then remove the unsuccessful ones. ```bash # Create multiple approaches make worktree approach-redis make worktree approach-memcached make worktree approach-inmemory # Test each in parallel cd ../amplifier.approach-redis && make test cd ../amplifier.approach-memcached && make test cd ../amplifier.approach-inmemory && make test # Keep the winner, remove the rest make worktree-rm approach-memcached make worktree-rm approach-inmemory ```