diff --git a/.gitignore b/.gitignore index ae23325..8517cba 100644 --- a/.gitignore +++ b/.gitignore @@ -64,3 +64,4 @@ __pycache__/ dist/ build/ blog-post/ +openspec/ diff --git a/openspec/AGENTS.md b/openspec/AGENTS.md deleted file mode 100644 index a3b6be2..0000000 --- a/openspec/AGENTS.md +++ /dev/null @@ -1,456 +0,0 @@ -# OpenSpec Instructions - -Instructions for AI coding assistants using OpenSpec for spec-driven development. - -## TL;DR Quick Checklist - -- Search existing work: `openspec spec list --long`, `openspec list` (use `rg` only for full-text search) -- Decide scope: new capability vs modify existing capability -- Pick a unique `change-id`: kebab-case, verb-led (`add-`, `update-`, `remove-`, `refactor-`) -- Scaffold: `proposal.md`, `tasks.md`, `design.md` (only if needed), and delta specs per affected capability -- Write deltas: use `## ADDED|MODIFIED|REMOVED|RENAMED Requirements`; include at least one `#### Scenario:` per requirement -- Validate: `openspec validate [change-id] --strict` and fix issues -- Request approval: Do not start implementation until proposal is approved - -## Three-Stage Workflow - -### Stage 1: Creating Changes -Create proposal when you need to: -- Add features or functionality -- Make breaking changes (API, schema) -- Change architecture or patterns -- Optimize performance (changes behavior) -- Update security patterns - -Triggers (examples): -- "Help me create a change proposal" -- "Help me plan a change" -- "Help me create a proposal" -- "I want to create a spec proposal" -- "I want to create a spec" - -Loose matching guidance: -- Contains one of: `proposal`, `change`, `spec` -- With one of: `create`, `plan`, `make`, `start`, `help` - -Skip proposal for: -- Bug fixes (restore intended behavior) -- Typos, formatting, comments -- Dependency updates (non-breaking) -- Configuration changes -- Tests for existing behavior - -**Workflow** -1. Review `openspec/project.md`, `openspec list`, and `openspec list --specs` to understand current context. -2. Choose a unique verb-led `change-id` and scaffold `proposal.md`, `tasks.md`, optional `design.md`, and spec deltas under `openspec/changes//`. -3. Draft spec deltas using `## ADDED|MODIFIED|REMOVED Requirements` with at least one `#### Scenario:` per requirement. -4. Run `openspec validate --strict` and resolve any issues before sharing the proposal. - -### Stage 2: Implementing Changes -Track these steps as TODOs and complete them one by one. -1. **Read proposal.md** - Understand what's being built -2. **Read design.md** (if exists) - Review technical decisions -3. **Read tasks.md** - Get implementation checklist -4. **Implement tasks sequentially** - Complete in order -5. **Confirm completion** - Ensure every item in `tasks.md` is finished before updating statuses -6. **Update checklist** - After all work is done, set every task to `- [x]` so the list reflects reality -7. **Approval gate** - Do not start implementation until the proposal is reviewed and approved - -### Stage 3: Archiving Changes -After deployment, create separate PR to: -- Move `changes/[name]/` → `changes/archive/YYYY-MM-DD-[name]/` -- Update `specs/` if capabilities changed -- Use `openspec archive --skip-specs --yes` for tooling-only changes (always pass the change ID explicitly) -- Run `openspec validate --strict` to confirm the archived change passes checks - -## Before Any Task - -**Context Checklist:** -- [ ] Read relevant specs in `specs/[capability]/spec.md` -- [ ] Check pending changes in `changes/` for conflicts -- [ ] Read `openspec/project.md` for conventions -- [ ] Run `openspec list` to see active changes -- [ ] Run `openspec list --specs` to see existing capabilities - -**Before Creating Specs:** -- Always check if capability already exists -- Prefer modifying existing specs over creating duplicates -- Use `openspec show [spec]` to review current state -- If request is ambiguous, ask 1–2 clarifying questions before scaffolding - -### Search Guidance -- Enumerate specs: `openspec spec list --long` (or `--json` for scripts) -- Enumerate changes: `openspec list` (or `openspec change list --json` - deprecated but available) -- Show details: - - Spec: `openspec show --type spec` (use `--json` for filters) - - Change: `openspec show --json --deltas-only` -- Full-text search (use ripgrep): `rg -n "Requirement:|Scenario:" openspec/specs` - -## Quick Start - -### CLI Commands - -```bash -# Essential commands -openspec list # List active changes -openspec list --specs # List specifications -openspec show [item] # Display change or spec -openspec validate [item] # Validate changes or specs -openspec archive [--yes|-y] # Archive after deployment (add --yes for non-interactive runs) - -# Project management -openspec init [path] # Initialize OpenSpec -openspec update [path] # Update instruction files - -# Interactive mode -openspec show # Prompts for selection -openspec validate # Bulk validation mode - -# Debugging -openspec show [change] --json --deltas-only -openspec validate [change] --strict -``` - -### Command Flags - -- `--json` - Machine-readable output -- `--type change|spec` - Disambiguate items -- `--strict` - Comprehensive validation -- `--no-interactive` - Disable prompts -- `--skip-specs` - Archive without spec updates -- `--yes`/`-y` - Skip confirmation prompts (non-interactive archive) - -## Directory Structure - -``` -openspec/ -├── project.md # Project conventions -├── specs/ # Current truth - what IS built -│ └── [capability]/ # Single focused capability -│ ├── spec.md # Requirements and scenarios -│ └── design.md # Technical patterns -├── changes/ # Proposals - what SHOULD change -│ ├── [change-name]/ -│ │ ├── proposal.md # Why, what, impact -│ │ ├── tasks.md # Implementation checklist -│ │ ├── design.md # Technical decisions (optional; see criteria) -│ │ └── specs/ # Delta changes -│ │ └── [capability]/ -│ │ └── spec.md # ADDED/MODIFIED/REMOVED -│ └── archive/ # Completed changes -``` - -## Creating Change Proposals - -### Decision Tree - -``` -New request? -├─ Bug fix restoring spec behavior? → Fix directly -├─ Typo/format/comment? → Fix directly -├─ New feature/capability? → Create proposal -├─ Breaking change? → Create proposal -├─ Architecture change? → Create proposal -└─ Unclear? → Create proposal (safer) -``` - -### Proposal Structure - -1. **Create directory:** `changes/[change-id]/` (kebab-case, verb-led, unique) - -2. **Write proposal.md:** -```markdown -# Change: [Brief description of change] - -## Why -[1-2 sentences on problem/opportunity] - -## What Changes -- [Bullet list of changes] -- [Mark breaking changes with **BREAKING**] - -## Impact -- Affected specs: [list capabilities] -- Affected code: [key files/systems] -``` - -3. **Create spec deltas:** `specs/[capability]/spec.md` -```markdown -## ADDED Requirements -### Requirement: New Feature -The system SHALL provide... - -#### Scenario: Success case -- **WHEN** user performs action -- **THEN** expected result - -## MODIFIED Requirements -### Requirement: Existing Feature -[Complete modified requirement] - -## REMOVED Requirements -### Requirement: Old Feature -**Reason**: [Why removing] -**Migration**: [How to handle] -``` -If multiple capabilities are affected, create multiple delta files under `changes/[change-id]/specs//spec.md`—one per capability. - -4. **Create tasks.md:** -```markdown -## 1. Implementation -- [ ] 1.1 Create database schema -- [ ] 1.2 Implement API endpoint -- [ ] 1.3 Add frontend component -- [ ] 1.4 Write tests -``` - -5. **Create design.md when needed:** -Create `design.md` if any of the following apply; otherwise omit it: -- Cross-cutting change (multiple services/modules) or a new architectural pattern -- New external dependency or significant data model changes -- Security, performance, or migration complexity -- Ambiguity that benefits from technical decisions before coding - -Minimal `design.md` skeleton: -```markdown -## Context -[Background, constraints, stakeholders] - -## Goals / Non-Goals -- Goals: [...] -- Non-Goals: [...] - -## Decisions -- Decision: [What and why] -- Alternatives considered: [Options + rationale] - -## Risks / Trade-offs -- [Risk] → Mitigation - -## Migration Plan -[Steps, rollback] - -## Open Questions -- [...] -``` - -## Spec File Format - -### Critical: Scenario Formatting - -**CORRECT** (use #### headers): -```markdown -#### Scenario: User login success -- **WHEN** valid credentials provided -- **THEN** return JWT token -``` - -**WRONG** (don't use bullets or bold): -```markdown -- **Scenario: User login** ❌ -**Scenario**: User login ❌ -### Scenario: User login ❌ -``` - -Every requirement MUST have at least one scenario. - -### Requirement Wording -- Use SHALL/MUST for normative requirements (avoid should/may unless intentionally non-normative) - -### Delta Operations - -- `## ADDED Requirements` - New capabilities -- `## MODIFIED Requirements` - Changed behavior -- `## REMOVED Requirements` - Deprecated features -- `## RENAMED Requirements` - Name changes - -Headers matched with `trim(header)` - whitespace ignored. - -#### When to use ADDED vs MODIFIED -- ADDED: Introduces a new capability or sub-capability that can stand alone as a requirement. Prefer ADDED when the change is orthogonal (e.g., adding "Slash Command Configuration") rather than altering the semantics of an existing requirement. -- MODIFIED: Changes the behavior, scope, or acceptance criteria of an existing requirement. Always paste the full, updated requirement content (header + all scenarios). The archiver will replace the entire requirement with what you provide here; partial deltas will drop previous details. -- RENAMED: Use when only the name changes. If you also change behavior, use RENAMED (name) plus MODIFIED (content) referencing the new name. - -Common pitfall: Using MODIFIED to add a new concern without including the previous text. This causes loss of detail at archive time. If you aren’t explicitly changing the existing requirement, add a new requirement under ADDED instead. - -Authoring a MODIFIED requirement correctly: -1) Locate the existing requirement in `openspec/specs//spec.md`. -2) Copy the entire requirement block (from `### Requirement: ...` through its scenarios). -3) Paste it under `## MODIFIED Requirements` and edit to reflect the new behavior. -4) Ensure the header text matches exactly (whitespace-insensitive) and keep at least one `#### Scenario:`. - -Example for RENAMED: -```markdown -## RENAMED Requirements -- FROM: `### Requirement: Login` -- TO: `### Requirement: User Authentication` -``` - -## Troubleshooting - -### Common Errors - -**"Change must have at least one delta"** -- Check `changes/[name]/specs/` exists with .md files -- Verify files have operation prefixes (## ADDED Requirements) - -**"Requirement must have at least one scenario"** -- Check scenarios use `#### Scenario:` format (4 hashtags) -- Don't use bullet points or bold for scenario headers - -**Silent scenario parsing failures** -- Exact format required: `#### Scenario: Name` -- Debug with: `openspec show [change] --json --deltas-only` - -### Validation Tips - -```bash -# Always use strict mode for comprehensive checks -openspec validate [change] --strict - -# Debug delta parsing -openspec show [change] --json | jq '.deltas' - -# Check specific requirement -openspec show [spec] --json -r 1 -``` - -## Happy Path Script - -```bash -# 1) Explore current state -openspec spec list --long -openspec list -# Optional full-text search: -# rg -n "Requirement:|Scenario:" openspec/specs -# rg -n "^#|Requirement:" openspec/changes - -# 2) Choose change id and scaffold -CHANGE=add-two-factor-auth -mkdir -p openspec/changes/$CHANGE/{specs/auth} -printf "## Why\n...\n\n## What Changes\n- ...\n\n## Impact\n- ...\n" > openspec/changes/$CHANGE/proposal.md -printf "## 1. Implementation\n- [ ] 1.1 ...\n" > openspec/changes/$CHANGE/tasks.md - -# 3) Add deltas (example) -cat > openspec/changes/$CHANGE/specs/auth/spec.md << 'EOF' -## ADDED Requirements -### Requirement: Two-Factor Authentication -Users MUST provide a second factor during login. - -#### Scenario: OTP required -- **WHEN** valid credentials are provided -- **THEN** an OTP challenge is required -EOF - -# 4) Validate -openspec validate $CHANGE --strict -``` - -## Multi-Capability Example - -``` -openspec/changes/add-2fa-notify/ -├── proposal.md -├── tasks.md -└── specs/ - ├── auth/ - │ └── spec.md # ADDED: Two-Factor Authentication - └── notifications/ - └── spec.md # ADDED: OTP email notification -``` - -auth/spec.md -```markdown -## ADDED Requirements -### Requirement: Two-Factor Authentication -... -``` - -notifications/spec.md -```markdown -## ADDED Requirements -### Requirement: OTP Email Notification -... -``` - -## Best Practices - -### Simplicity First -- Default to <100 lines of new code -- Single-file implementations until proven insufficient -- Avoid frameworks without clear justification -- Choose boring, proven patterns - -### Complexity Triggers -Only add complexity with: -- Performance data showing current solution too slow -- Concrete scale requirements (>1000 users, >100MB data) -- Multiple proven use cases requiring abstraction - -### Clear References -- Use `file.ts:42` format for code locations -- Reference specs as `specs/auth/spec.md` -- Link related changes and PRs - -### Capability Naming -- Use verb-noun: `user-auth`, `payment-capture` -- Single purpose per capability -- 10-minute understandability rule -- Split if description needs "AND" - -### Change ID Naming -- Use kebab-case, short and descriptive: `add-two-factor-auth` -- Prefer verb-led prefixes: `add-`, `update-`, `remove-`, `refactor-` -- Ensure uniqueness; if taken, append `-2`, `-3`, etc. - -## Tool Selection Guide - -| Task | Tool | Why | -|------|------|-----| -| Find files by pattern | Glob | Fast pattern matching | -| Search code content | Grep | Optimized regex search | -| Read specific files | Read | Direct file access | -| Explore unknown scope | Task | Multi-step investigation | - -## Error Recovery - -### Change Conflicts -1. Run `openspec list` to see active changes -2. Check for overlapping specs -3. Coordinate with change owners -4. Consider combining proposals - -### Validation Failures -1. Run with `--strict` flag -2. Check JSON output for details -3. Verify spec file format -4. Ensure scenarios properly formatted - -### Missing Context -1. Read project.md first -2. Check related specs -3. Review recent archives -4. Ask for clarification - -## Quick Reference - -### Stage Indicators -- `changes/` - Proposed, not yet built -- `specs/` - Built and deployed -- `archive/` - Completed changes - -### File Purposes -- `proposal.md` - Why and what -- `tasks.md` - Implementation steps -- `design.md` - Technical decisions -- `spec.md` - Requirements and behavior - -### CLI Essentials -```bash -openspec list # What's in progress? -openspec show [item] # View details -openspec validate --strict # Is it correct? -openspec archive [--yes|-y] # Mark complete (add --yes for automation) -``` - -Remember: Specs are truth. Changes are proposals. Keep them in sync. diff --git a/openspec/changes/add-context-tracking-hooks/design.md b/openspec/changes/add-context-tracking-hooks/design.md deleted file mode 100644 index 4521c14..0000000 --- a/openspec/changes/add-context-tracking-hooks/design.md +++ /dev/null @@ -1,163 +0,0 @@ -# Design: Context Usage Tracking via Hook Pairs - -## Context - -Users need visibility into token consumption during Claude Code sessions. While Claude Code provides internal context management, users lack tools to: -- Track token usage per request -- Monitor cumulative context growth -- Understand when they're approaching context limits - -The existing `Stop` hook example provides cumulative usage but not per-request deltas. - -## Goals / Non-Goals - -### Goals -- Document a reliable method to track per-request token consumption -- Provide a working example users can copy and modify -- Explain the methodology and its limitations clearly -- Use existing hook events (`UserPromptSubmit`, `Stop`) without requiring new capabilities - -### Non-Goals -- Implement actual token counting (we use character-based estimation) -- Access internal Claude Code context metrics -- Modify Claude Code's behavior or internal state -- Track system prompt tokens (not in transcript) - -## Decisions - -### Decision 1: Use UserPromptSubmit + Stop Hook Pair -**What**: Use `UserPromptSubmit` as the "pre-message" hook and `Stop` as the "post-response" hook. - -**Why**: These are the natural lifecycle points: -- `UserPromptSubmit` fires before the prompt is sent to the model -- `Stop` fires after Claude completes its response - -**Alternatives Considered**: -| Option | Pros | Cons | -|--------|------|------| -| SessionStart + Stop | Captures full session | No per-request granularity | -| PreToolUse + PostToolUse | Captures tool overhead | Missing prompt/response tokens | -| UserPromptSubmit + Stop | Natural request boundaries | Requires temp file for state | - -### Decision 2: Use Temp File for State Persistence -**What**: Store pre-message token count in a temp file keyed by session ID. - -**Why**: Hooks are stateless processes; we need persistence between the two hook invocations. - -**Implementation**: -```python -import tempfile -import os - -def get_state_file(session_id: str) -> str: - return os.path.join(tempfile.gettempdir(), f"claude-tokens-{session_id}.json") -``` - -### Decision 3: Single Script with Mode Detection -**What**: One Python script handles both hooks, detecting mode via `hook_event_name`. - -**Why**: -- Reduces file count and complexity -- Ensures consistent token calculation logic -- Easier for users to understand and modify - -**Structure**: -```python -def main(): - data = json.load(sys.stdin) - event = data.get("hook_event_name") - - if event == "UserPromptSubmit": - record_pre_message_count(data) - elif event == "Stop": - report_delta(data) -``` - -### Decision 4: Two Offline Token Counting Methods (No API Key) -**What**: Provide two offline methods - tiktoken-based and simple character estimation. - -**Why**: -- No API key should be required for context tracking hooks -- Anthropic hasn't released an official offline tokenizer -- Users have different dependency tolerance levels - -#### Method A: tiktoken with p50k_base (Recommended) - -```python -import tiktoken - -def count_tokens_tiktoken(text: str) -> int: - enc = tiktoken.get_encoding("p50k_base") - return len(enc.encode(text)) -``` - -**Characteristics**: -- ~90-95% accuracy compared to Claude's actual tokenizer -- Works completely offline -- Requires `tiktoken` dependency -- Fast execution (<10ms) - -#### Method B: Character-Based Estimation (Zero Dependencies) - -```python -def count_tokens_estimate(text: str) -> int: - return len(text) // 4 -``` - -**Characteristics**: -- ~80-90% accuracy for English text -- No dependencies at all -- Sub-millisecond latency -- Less accurate for code and non-English text - -**Trade-off Matrix**: - -| Factor | tiktoken | Estimation | -|--------|----------|------------| -| Accuracy | ~90-95% | ~80-90% | -| Speed | <10ms | <1ms | -| Dependencies | tiktoken | None | -| Offline | Yes | Yes | - -**Note**: Anthropic hasn't released their official tokenizer publicly. The `tiktoken` approach uses OpenAI's tokenizer with `p50k_base` encoding as a reasonable approximation since both use BPE (byte-pair encoding). - -## Token Delta Calculation Flow - -``` -UserPromptSubmit Stop - | | - v v -Read transcript Read transcript - | | - v v -Count characters Count characters - | | - v v -Estimate tokens (T1) Estimate tokens (T2) - | | - v v -Save T1 to temp file Calculate delta = T2 - T1 - | - v - Report: "Request used ~X tokens" -``` - -## Risks / Trade-offs - -| Risk | Mitigation | -|------|------------| -| Temp file not found (hook failures) | Graceful fallback to cumulative-only reporting | -| Inaccurate token estimates | Clear documentation of limitations | -| Race conditions (concurrent sessions) | Session ID in filename for isolation | -| Temp file cleanup | Use system temp directory (auto-cleaned) | - -## Example Output Format - -``` -Context Usage: ~12,500 tokens used (~125,000 remaining) -This request: ~850 tokens (+6.8% of total) -``` - -## Open Questions - -None - design is straightforward given existing hook capabilities. diff --git a/openspec/changes/add-context-tracking-hooks/proposal.md b/openspec/changes/add-context-tracking-hooks/proposal.md deleted file mode 100644 index b203fe1..0000000 --- a/openspec/changes/add-context-tracking-hooks/proposal.md +++ /dev/null @@ -1,100 +0,0 @@ -# Change: Add Context Usage Tracking Documentation via Pre-Message and Post-Response Hooks - -## Why - -Users want to monitor token consumption per request and overall context usage throughout a Claude Code session. Currently, the hooks documentation shows a basic context-usage example using the Stop hook, but it doesn't demonstrate how to track **per-request** token consumption by comparing measurements at two points in time. - -By documenting how to use `UserPromptSubmit` as a "pre-message" hook and `Stop` as a "post-response" hook, users can calculate the delta in token usage for each request, enabling accurate per-request consumption metrics. - -## What Changes - -- **ADDED**: Documentation for using `UserPromptSubmit` and `Stop` hooks together for context tracking -- **ADDED**: A new example demonstrating token delta calculation between pre-message and post-response -- **MODIFIED**: Enhance the existing context usage reporting requirement with delta-based tracking approach -- **ADDED**: Detailed explanation of token estimation methodology and its limitations - -## Impact - -- Affected specs: `hooks-documentation` -- Affected code: `06-hooks/README.md` (documentation updates) -- No breaking changes - purely additive documentation - -## Technical Analysis - -### Current Hook Events Mapping - -| Desired Hook | Claude Code Event | Trigger Point | -|--------------|-------------------|---------------| -| Pre-Message Hook | `UserPromptSubmit` | Before user prompt is processed by the model | -| Post-Response Hook | `Stop` | After model completes its full response | - -### Token Counting Methods (Offline, No API Key) - -Since we need offline token counting without an API key, we offer **two local approaches**: - -#### Method 1: tiktoken with p50k_base (More Accurate) - -Use OpenAI's `tiktoken` library with the `p50k_base` encoding as an approximation for Claude's tokenizer: - -```python -import tiktoken - -enc = tiktoken.get_encoding("p50k_base") -tokens = enc.encode(text) -token_count = len(tokens) -``` - -**Pros:** -- More accurate than character estimation (~90-95% accuracy) -- Works completely offline -- No API key required -- Fast execution - -**Cons:** -- Requires `tiktoken` dependency (`pip install tiktoken`) -- Not Claude's exact tokenizer (approximation) - -#### Method 2: Character-Based Estimation (Simplest) - -For zero-dependency estimation: - -```python -estimated_tokens = len(text) // 4 -``` - -**Pros:** -- No dependencies at all -- Works offline -- Extremely fast - -**Cons:** -- Less accurate (~80-90% for English text) -- Varies more with code and non-English text - -### Token Delta Calculation Approach - -1. **Pre-Message (UserPromptSubmit)**: Read transcript, count tokens (via tiktoken or estimation) -2. **Post-Response (Stop)**: Read transcript again, calculate new total, compute delta - -**Accuracy Evaluation:** - -| Factor | tiktoken Method | Character Estimation | -|--------|-----------------|---------------------| -| Token accuracy | ~90-95% | ~80-90% | -| Dependencies | tiktoken | None | -| Speed | Fast (<10ms) | Very fast (<1ms) | -| Offline | Yes | Yes | - -### Limitations - -- **No official offline Claude tokenizer exists** - Anthropic hasn't released their tokenizer publicly -- System prompts and internal Claude Code context are NOT in the transcript -- The delta includes: user prompt + Claude's response + any tool outputs -- Both methods are approximations; actual API token counts may differ slightly - -## Open Questions - -1. Should we persist the pre-message count to a file, or can we rely on the hook's transient state? - - **Recommendation**: Use a simple temp file in the session directory for reliability -2. Should the example be a single Python script handling both hooks, or two separate scripts? - - **Recommendation**: Single script with mode detection based on `hook_event_name` diff --git a/openspec/changes/add-context-tracking-hooks/specs/hooks-documentation/spec.md b/openspec/changes/add-context-tracking-hooks/specs/hooks-documentation/spec.md deleted file mode 100644 index fbb27b0..0000000 --- a/openspec/changes/add-context-tracking-hooks/specs/hooks-documentation/spec.md +++ /dev/null @@ -1,106 +0,0 @@ -# hooks-documentation Spec Delta - -## ADDED Requirements - -### Requirement: Pre-Message and Post-Response Hook Pairs Documentation -The hooks lesson SHALL document how to use `UserPromptSubmit` and `Stop` hooks together for context/token usage tracking. - -#### Scenario: Understanding hook event timing for context tracking -- **WHEN** a user wants to track per-request token consumption -- **THEN** they find documentation explaining that `UserPromptSubmit` fires before the prompt is processed (pre-message) -- **AND** they find documentation explaining that `Stop` fires after Claude completes its response (post-response) -- **AND** they understand how to calculate the delta between these two points - -#### Scenario: Token delta calculation methodology -- **WHEN** a user implements a context tracking hook pair -- **THEN** they find documentation explaining how to: - - Record token count at `UserPromptSubmit` time - - Calculate new token count at `Stop` time - - Compute the delta representing per-request consumption - -### Requirement: Context Tracking Hook Pair Example -The hooks lesson SHALL provide a working example script that tracks context usage using pre-message and post-response hooks. - -#### Scenario: Single script handles both hook events -- **WHEN** a user copies the context-tracker.py example -- **THEN** the script detects the hook event type via `hook_event_name` -- **AND** handles `UserPromptSubmit` by saving current token estimate to a temp file -- **AND** handles `Stop` by loading the saved count, calculating delta, and reporting usage - -#### Scenario: Complete configuration for hook pair -- **WHEN** a user wants to configure both hooks -- **THEN** they find a complete settings.json example showing: - - `UserPromptSubmit` hook configuration pointing to the context tracker script - - `Stop` hook configuration pointing to the same script - - Both hooks using the same script for consistent token calculation - -#### Scenario: Per-request usage reporting -- **WHEN** the context tracking hooks execute -- **THEN** the Stop hook outputs a report showing: - - Total estimated tokens used in session - - Tokens consumed by the current request (delta) - - Remaining capacity estimate - -### Requirement: Token Counting Methods Documentation -The hooks lesson SHALL document two offline token counting methods that require no API key. - -#### Scenario: tiktoken-based token counting documented -- **WHEN** a user wants more accurate offline token counts -- **THEN** they find documentation for using `tiktoken` with `p50k_base` encoding -- **AND** they see a Python example using `tiktoken.get_encoding("p50k_base")` -- **AND** they understand it provides ~90-95% accuracy compared to Claude's tokenizer -- **AND** they learn it requires the `tiktoken` dependency - -#### Scenario: Character estimation token counting documented -- **WHEN** a user wants zero-dependency token estimation -- **THEN** they find documentation for the ~4 characters per token estimation ratio -- **AND** they understand this provides ~80-90% accuracy for English text -- **AND** they learn it works with no external dependencies - -#### Scenario: Method comparison provided -- **WHEN** a user needs to choose between token counting methods -- **THEN** they find a comparison showing: - - tiktoken method: ~90-95% accuracy, requires tiktoken, <10ms latency - - Estimation method: ~80-90% accuracy, no dependencies, <1ms latency -- **AND** both methods work completely offline without API keys - -#### Scenario: Transcript contents explained -- **WHEN** a user wants to understand what's included in token counts -- **THEN** they find documentation explaining that the transcript includes: - - User prompts - - Claude's responses - - Tool inputs and outputs -- **AND** they understand that system prompts and internal context are NOT included - -#### Scenario: No official Claude tokenizer caveat -- **WHEN** a user reads about token counting accuracy -- **THEN** they understand that Anthropic hasn't released an official offline tokenizer -- **AND** they understand both methods are approximations based on similar BPE tokenizers - -## MODIFIED Requirements - -### Requirement: Context Usage Reporting Hook Example -The hooks lesson SHALL include a correct, working example showing how to create a hook that reports context/token usage after each Claude response. - -#### Scenario: Token calculation is correct -- **WHEN** a user copies the context-usage.py example -- **AND** runs it as a Stop hook -- **THEN** the hook correctly calculates estimated tokens from total character count -- **AND** displays a non-zero token count proportional to conversation length - -#### Scenario: User learns to create context monitoring hook -- **WHEN** a user reads the context usage reporter example -- **THEN** they find a complete Python script that reads the transcript file -- **AND** they understand how to estimate token usage from conversation history -- **AND** they see the configuration for Stop hooks -- **AND** they understand the limitations of token estimation - -#### Scenario: Hook output format is documented -- **WHEN** a user implements the context usage hook -- **THEN** they can generate a one-line report showing used tokens and remaining capacity -- **AND** the output shows realistic token counts based on conversation size - -#### Scenario: Delta-based tracking is documented -- **WHEN** a user wants per-request token consumption -- **THEN** they find documentation pointing to the pre-message/post-response hook pair approach -- **AND** they understand how to use `UserPromptSubmit` + `Stop` for delta calculation diff --git a/openspec/changes/add-context-tracking-hooks/tasks.md b/openspec/changes/add-context-tracking-hooks/tasks.md deleted file mode 100644 index 12939a5..0000000 --- a/openspec/changes/add-context-tracking-hooks/tasks.md +++ /dev/null @@ -1,36 +0,0 @@ -# Tasks: Add Context Usage Tracking Documentation - -## 1. Documentation Updates - -- [x] 1.1 Add "Context Tracking Hook Pairs" section to README explaining pre-message/post-response concept -- [x] 1.2 Document how UserPromptSubmit serves as pre-message hook -- [x] 1.3 Document how Stop serves as post-response hook -- [x] 1.4 Explain token delta calculation methodology - -## 2. Example Scripts - -- [x] 2.1 Create `context-tracker.py` example script with character estimation (zero dependencies) -- [x] 2.2 Create `context-tracker-tiktoken.py` example script with tiktoken method (more accurate) -- [x] 2.3 Implement UserPromptSubmit handler (save pre-message count) -- [x] 2.4 Implement Stop handler (calculate and report delta) -- [x] 2.5 Add clear inline comments explaining both approaches - -## 3. Configuration Examples - -- [x] 3.1 Add hook configuration example for UserPromptSubmit event -- [x] 3.2 Add hook configuration example for Stop event -- [x] 3.3 Provide combined configuration showing both hooks together - -## 4. Token Counting Methods Documentation - -- [x] 4.1 Document tiktoken with p50k_base method (more accurate, ~90-95%) -- [x] 4.2 Document character-based estimation method (simple, ~80-90%) -- [x] 4.3 Create comparison table of both offline methods -- [x] 4.4 Explain what's included/excluded from transcript -- [x] 4.5 Add caveat that no official Claude offline tokenizer exists - -## 5. Validation - -- [x] 5.1 Test example script with sample JSON input -- [x] 5.2 Verify configuration examples have valid JSON syntax -- [x] 5.3 Run openspec validate to confirm proposal is complete diff --git a/openspec/changes/archive/2025-12-24-add-cli-lesson/proposal.md b/openspec/changes/archive/2025-12-24-add-cli-lesson/proposal.md deleted file mode 100644 index 703fea6..0000000 --- a/openspec/changes/archive/2025-12-24-add-cli-lesson/proposal.md +++ /dev/null @@ -1,41 +0,0 @@ -# Change: Add CLI Reference Lesson - -## Why - -The Claude How To repository covers nine major Claude Code features (01-09), but lacks a dedicated lesson for the CLI reference - the command-line interface that users interact with directly. Understanding CLI commands, flags, and options is fundamental to using Claude Code effectively. Users need a comprehensive reference to leverage features like model selection, output formats, permission management, and session handling via CLI. - -## What Changes - -- **NEW** `10-cli/` directory with comprehensive CLI reference lesson -- **NEW** `10-cli/README.md` - Main lesson content following established structure -- **UPDATE** Root `README.md` - Add CLI lesson to navigation and learning path -- **UPDATE** Root `README.md` - Add CLI to feature comparison and use case matrix -- **UPDATE** `LEARNING-ROADMAP.md` - Include CLI lesson in learning progression - -## Key Content Areas - -1. **CLI Commands** - Start interactive REPL, query mode, continue/resume sessions, updates -2. **Core Flags** - Print mode, continue, resume, version -3. **Model Configuration** - Model selection, fallback models, agent configuration -4. **System Prompt Customization** - Replace, append, file-based prompts -5. **Tool & Permission Management** - Allowed/disallowed tools, permission modes -6. **Output & Format** - JSON, stream-JSON, text formats -7. **MCP Configuration** - Server loading, strict mode -8. **Session Management** - Session IDs, forking, resumption -9. **Advanced Features** - Chrome integration, IDE connection, debug mode - -## High-Value Use Cases - -1. **CI/CD Integration** - Headless mode with JSON output for automation pipelines -2. **Script Piping** - Process files, logs, and data through Claude -3. **Multi-Session Workflows** - Resume and fork sessions for complex projects -4. **Custom Agent Configurations** - Define specialized subagents via CLI -5. **Batch Processing** - Process multiple queries with consistent settings -6. **Security-Conscious Development** - Permission modes and tool restrictions -7. **API Integration** - Structured JSON output for programmatic consumption - -## Impact - -- Affected specs: None (new capability) -- Affected code: Root README.md, LEARNING-ROADMAP.md -- New files: `10-cli/README.md` diff --git a/openspec/changes/archive/2025-12-24-add-cli-lesson/specs/cli-reference/spec.md b/openspec/changes/archive/2025-12-24-add-cli-lesson/specs/cli-reference/spec.md deleted file mode 100644 index c1e49b2..0000000 --- a/openspec/changes/archive/2025-12-24-add-cli-lesson/specs/cli-reference/spec.md +++ /dev/null @@ -1,99 +0,0 @@ -## ADDED Requirements - -### Requirement: CLI Reference Lesson - -The repository SHALL provide a comprehensive CLI reference lesson at `10-cli/` that documents all command-line interface options, flags, and usage patterns for Claude Code. - -#### Scenario: User learns CLI basics -- **WHEN** a user navigates to `10-cli/README.md` -- **THEN** they find an overview of CLI capabilities with architecture diagram -- **AND** a quick reference table of all CLI commands -- **AND** examples demonstrating common usage patterns - -#### Scenario: User looks up specific CLI flag -- **WHEN** a user needs to understand a specific CLI flag (e.g., `--output-format`) -- **THEN** they find the flag documented with description, options, and example usage -- **AND** related flags are cross-referenced - -#### Scenario: User integrates Claude Code in CI/CD -- **WHEN** a user wants to use Claude Code in automation -- **THEN** they find practical examples for CI/CD integration -- **AND** examples show headless mode, JSON output, and error handling - -### Requirement: CLI Commands Documentation - -The CLI lesson SHALL document all primary CLI commands with their syntax and use cases. - -#### Scenario: Interactive mode commands documented -- **WHEN** a user reads the CLI commands section -- **THEN** they find `claude` for starting interactive REPL -- **AND** `claude "query"` for starting with initial prompt -- **AND** `claude -c` for continuing recent conversation -- **AND** `claude -r` for resuming specific session - -#### Scenario: Print mode commands documented -- **WHEN** a user reads the print mode section -- **THEN** they find `claude -p "query"` for non-interactive queries -- **AND** pipe input examples like `cat file | claude -p "query"` -- **AND** output format options (text, json, stream-json) - -### Requirement: CLI Flags Documentation - -The CLI lesson SHALL document all CLI flags organized by category with examples. - -#### Scenario: Core flags documented -- **WHEN** a user reads the core flags section -- **THEN** they find `-p/--print`, `-c/--continue`, `-r/--resume`, `-v/--version` -- **AND** each flag has description and example usage - -#### Scenario: Model configuration flags documented -- **WHEN** a user reads the model configuration section -- **THEN** they find `--model`, `--fallback-model`, `--agent`, `--agents` -- **AND** examples show model selection and custom agent definitions - -#### Scenario: Permission flags documented -- **WHEN** a user reads the permission section -- **THEN** they find `--tools`, `--allowedTools`, `--disallowedTools` -- **AND** `--dangerously-skip-permissions`, `--permission-mode` -- **AND** examples demonstrate security-conscious configurations - -### Requirement: High-Value Use Cases - -The CLI lesson SHALL include practical use case examples that demonstrate real-world CLI value. - -#### Scenario: CI/CD integration example provided -- **WHEN** a user reads the CI/CD use case -- **THEN** they find a complete GitHub Actions or Jenkins example -- **AND** the example demonstrates headless mode with JSON output -- **AND** error handling and exit codes are explained - -#### Scenario: Script piping example provided -- **WHEN** a user reads the script piping use case -- **THEN** they find examples of piping file contents to Claude -- **AND** examples show log analysis, code review via pipe -- **AND** output processing patterns are demonstrated - -#### Scenario: Multi-session workflow example provided -- **WHEN** a user reads the session management use case -- **THEN** they find examples of resuming and forking sessions -- **AND** session naming and organization patterns are shown - -### Requirement: Navigation Integration - -The root documentation SHALL be updated to include the CLI lesson in all navigation elements. - -#### Scenario: CLI appears in Quick Navigation -- **WHEN** a user views the README Quick Navigation table -- **THEN** they see CLI Reference listed with link to `10-cli/` - -#### Scenario: CLI appears in Learning Path -- **WHEN** a user views the Learning Path table -- **THEN** they see CLI Reference at position 10 with appropriate difficulty and timing - -#### Scenario: CLI appears in Feature Comparison -- **WHEN** a user views the Feature Comparison table -- **THEN** CLI Reference is included with invocation, persistence, and use case columns - -#### Scenario: CLI appears in Directory Structure -- **WHEN** a user views the Directory Structure tree -- **THEN** `10-cli/` directory is shown with `README.md` diff --git a/openspec/changes/archive/2025-12-24-add-cli-lesson/tasks.md b/openspec/changes/archive/2025-12-24-add-cli-lesson/tasks.md deleted file mode 100644 index 94f662d..0000000 --- a/openspec/changes/archive/2025-12-24-add-cli-lesson/tasks.md +++ /dev/null @@ -1,50 +0,0 @@ -# Tasks: Add CLI Reference Lesson - -## 1. Create CLI Lesson Content - -- [x] 1.1 Create `10-cli/` directory -- [x] 1.2 Create `10-cli/README.md` with: - - Overview section with architecture diagram - - CLI commands table (claude, claude "query", claude -p, etc.) - - Core flags section with examples - - Model & configuration flags - - System prompt customization section - - Tool & permission management section - - Output & format options - - Workspace & directory flags - - MCP configuration options - - Session management commands - - Advanced features (chrome, ide, debug) - - Agents flag format with JSON examples - - High-value use cases section with practical examples - - Installation/usage quick reference - - Troubleshooting section - - Related concepts links - -## 2. Add Use Case Examples - -- [x] 2.1 CI/CD integration example (GitHub Actions, Jenkins) -- [x] 2.2 Script piping example (log analysis, code processing) -- [x] 2.3 Multi-session workflow example -- [x] 2.4 Custom agent configuration example -- [x] 2.5 Batch processing example -- [x] 2.6 Security-conscious development example -- [x] 2.7 JSON API integration example - -## 3. Update Root Documentation - -- [x] 3.1 Add CLI to Quick Navigation table in `README.md` -- [x] 3.2 Add CLI to Learning Path table in `README.md` -- [x] 3.3 Add CLI section (section 10) in `README.md` -- [x] 3.4 Add CLI to Feature Comparison table -- [x] 3.5 Add CLI to Use Case Matrix -- [x] 3.6 Add CLI to Directory Structure tree -- [x] 3.7 Add CLI to Installation Quick Reference -- [x] 3.8 Update `LEARNING-ROADMAP.md` with CLI lesson - -## 4. Quality Assurance - -- [x] 4.1 Verify all code examples are valid and tested -- [x] 4.2 Ensure consistent style with other lessons (mermaid diagrams, tables) -- [x] 4.3 Check all internal links work correctly -- [x] 4.4 Review against official documentation for accuracy diff --git a/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/proposal.md b/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/proposal.md deleted file mode 100644 index 3950c1a..0000000 --- a/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/proposal.md +++ /dev/null @@ -1,18 +0,0 @@ -# Change: Add Context Usage Reporting Hook Example - -## Why - -Users want to monitor their context window usage during Claude Code sessions. The hooks documentation currently lacks a practical example showing how to create a hook that reports context/token usage after each user request. This is valuable for understanding when context is getting full and when auto-compaction might occur. - -## What Changes - -- Add a detailed example hook that reports context usage after each user prompt -- The hook will read the transcript file and estimate token usage -- Include step-by-step explanation of how the hook works -- Document the limitations (estimation vs exact token counts) - -## Impact - -- **Affected specs**: hooks-documentation (add new example) -- **Affected code**: `06-hooks/README.md` (add new example section) -- **User impact**: Users gain a practical example for monitoring context usage diff --git a/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/specs/hooks-documentation/spec.md b/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/specs/hooks-documentation/spec.md deleted file mode 100644 index 1646030..0000000 --- a/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/specs/hooks-documentation/spec.md +++ /dev/null @@ -1,18 +0,0 @@ -# Hooks Documentation Specification - -## ADDED Requirements - -### Requirement: Context Usage Reporting Hook Example -The hooks lesson SHALL include a detailed example showing how to create a hook that reports context/token usage after each user request. - -#### Scenario: User learns to create context monitoring hook -- **WHEN** a user reads the context usage reporter example -- **THEN** they find a complete Python script that reads the transcript file -- **AND** they understand how to estimate token usage from conversation history -- **AND** they see the configuration for UserPromptSubmit or Stop hooks -- **AND** they understand the limitations of token estimation - -#### Scenario: Hook output format is documented -- **WHEN** a user implements the context usage hook -- **THEN** they can generate a one-line report showing used tokens and remaining capacity -- **AND** they understand the report is an estimate based on transcript analysis diff --git a/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/tasks.md b/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/tasks.md deleted file mode 100644 index ac40737..0000000 --- a/openspec/changes/archive/2025-12-24-add-context-usage-hook-example/tasks.md +++ /dev/null @@ -1,9 +0,0 @@ -# Tasks: Add Context Usage Reporting Hook Example - -## 1. Documentation Update -- [x] 1.1 Add new example section "Context Usage Reporter" to 06-hooks/README.md -- [x] 1.2 Write Python hook script that reads transcript and estimates tokens -- [x] 1.3 Add configuration example for UserPromptSubmit hook -- [x] 1.4 Document how transcript_path provides access to conversation history -- [x] 1.5 Explain token estimation approach and limitations -- [x] 1.6 Show sample output format for the one-line report diff --git a/openspec/changes/archive/2025-12-24-fix-context-usage-hook/proposal.md b/openspec/changes/archive/2025-12-24-fix-context-usage-hook/proposal.md deleted file mode 100644 index 617a07a..0000000 --- a/openspec/changes/archive/2025-12-24-fix-context-usage-hook/proposal.md +++ /dev/null @@ -1,44 +0,0 @@ -# Change: Fix Context Usage Hook Token Calculation - -## Why - -The context-usage hook (Stop event) always reports 0 tokens because of a bug in line 68 of `context-usage.py`: - -```python -estimated_tokens = estimate_tokens(str(total_chars)) -``` - -This converts the integer `total_chars` (e.g., `156789`) to a string `"156789"` and then calculates tokens from that 6-character string, resulting in `6 // 4 = 1` token instead of `156789 // 4 = ~39,197` tokens. - -**Current behavior:** -``` -Stop says: Context: ~0/200,000 tokens (100.0% remaining) -``` - -**Expected behavior:** -``` -Stop says: Context: ~39,197/200,000 tokens (80.4% remaining) -``` - -## What - -Fix the token calculation bug in the context-usage.py example hook: -1. Remove the erroneous `str()` conversion -2. Calculate estimated tokens directly from character count - -## Scope - -- **Files affected:** - - `06-hooks/README.md` - Update the example code - - User's `~/.claude/hooks/context-usage.py` - Not managed by this repo, but fix will be documented - -## Out of Scope - -- Improving transcript parsing logic -- Adding more sophisticated token estimation -- Adding new hook features - -## Risks - -- **Low:** Simple bug fix with clear expected behavior -- Users who copied the broken example will need to update their hook manually diff --git a/openspec/changes/archive/2025-12-24-fix-context-usage-hook/specs/hooks-documentation/spec.md b/openspec/changes/archive/2025-12-24-fix-context-usage-hook/specs/hooks-documentation/spec.md deleted file mode 100644 index da084b0..0000000 --- a/openspec/changes/archive/2025-12-24-fix-context-usage-hook/specs/hooks-documentation/spec.md +++ /dev/null @@ -1,24 +0,0 @@ -# hooks-documentation Specification Delta - -## MODIFIED Requirements - -### Requirement: Context Usage Reporting Hook Example -The hooks lesson SHALL include a correct, working example showing how to create a hook that reports context/token usage after each Claude response. - -#### Scenario: Token calculation is correct -- **WHEN** a user copies the context-usage.py example -- **AND** runs it as a Stop hook -- **THEN** the hook correctly calculates estimated tokens from total character count -- **AND** displays a non-zero token count proportional to conversation length - -#### Scenario: User learns to create context monitoring hook -- **WHEN** a user reads the context usage reporter example -- **THEN** they find a complete Python script that reads the transcript file -- **AND** they understand how to estimate token usage from conversation history -- **AND** they see the configuration for Stop hooks -- **AND** they understand the limitations of token estimation - -#### Scenario: Hook output format is documented -- **WHEN** a user implements the context usage hook -- **THEN** they can generate a one-line report showing used tokens and remaining capacity -- **AND** the output shows realistic token counts based on conversation size diff --git a/openspec/changes/archive/2025-12-24-fix-context-usage-hook/tasks.md b/openspec/changes/archive/2025-12-24-fix-context-usage-hook/tasks.md deleted file mode 100644 index c2b074a..0000000 --- a/openspec/changes/archive/2025-12-24-fix-context-usage-hook/tasks.md +++ /dev/null @@ -1,20 +0,0 @@ -# Tasks: Fix Context Usage Hook Token Calculation - -## Implementation Tasks - -### 1. Fix the bug in 06-hooks/README.md example -- [x] Update line 564 in the context-usage.py example: change `estimate_tokens(str(total_chars))` to `total_chars // 4` -- [x] Remove the now-unused `estimate_tokens()` function from the example - -### 2. Update user's local hook file -- [x] Fix `~/.claude/hooks/context-usage.py` with the same correction - -### 3. Verification -- [x] Test the hook by running Claude Code and confirming non-zero token count is displayed -- [x] Verify the percentage calculation is reasonable (should show usage increasing during conversation) - -## Acceptance Criteria - -- [x] After Claude responds, the Stop hook displays a non-zero token estimate -- [x] The displayed percentage decreases as conversation grows -- [x] Example in README.md matches the corrected implementation diff --git a/openspec/changes/archive/2025-12-24-update-hooks-lesson/proposal.md b/openspec/changes/archive/2025-12-24-update-hooks-lesson/proposal.md deleted file mode 100644 index 9872f79..0000000 --- a/openspec/changes/archive/2025-12-24-update-hooks-lesson/proposal.md +++ /dev/null @@ -1,36 +0,0 @@ -# Change: Update Hooks Lesson Based on Official Documentation - -## Why - -The current hooks lesson (`blog-posts/06-hooks.md`) contains outdated and inaccurate information that doesn't match the official Claude Code hooks documentation. Key issues include: - -1. **Incorrect hook event names**: Uses `PreToolUse:Write`, `PreCommit`, `PostCommit`, `PrePush` which don't exist -2. **Missing hook events**: Doesn't cover `PermissionRequest`, `Stop`, `SubagentStop`, `PreCompact`, `SessionStart` (with matchers), `SessionEnd` -3. **Wrong configuration format**: Shows string-based hook commands instead of the array-based matcher/hooks structure -4. **Missing hook input/output**: Doesn't explain JSON stdin input or structured JSON output -5. **Missing exit code semantics**: Exit code 2 for blocking vs other non-zero codes -6. **Missing prompt-based hooks**: No coverage of `type: "prompt"` hooks for LLM-based evaluation -7. **Missing security considerations**: No disclaimer or security best practices from official docs -8. **Incorrect variable references**: Uses `${file_path}`, `${command}` instead of JSON stdin input - -## What Changes - -- **BREAKING**: Complete rewrite of hook event types and configuration format -- Update all code examples to use correct array-based configuration structure -- Add coverage of all 9 hook events: `PreToolUse`, `PermissionRequest`, `PostToolUse`, `Notification`, `UserPromptSubmit`, `Stop`, `SubagentStop`, `PreCompact`, `SessionStart`, `SessionEnd` -- Add JSON hook input/output documentation with examples -- Add hook matchers (tool patterns, regex support) -- Add prompt-based hooks for `Stop`/`SubagentStop` -- Add security considerations section with official disclaimer -- Add environment variables section (`CLAUDE_PROJECT_DIR`, `CLAUDE_ENV_FILE`, `CLAUDE_CODE_REMOTE`) -- Add plugin hooks documentation -- Add MCP tool hook patterns (`mcp____`) -- Update debugging section with `claude --debug` and verbose mode -- Remove incorrect/non-existent hook types (`PreCommit`, `PostCommit`, `PrePush`) - -## Impact - -- **Affected specs**: hooks-documentation (new capability) -- **Affected code**: `blog-posts/06-hooks.md` (complete rewrite) -- **Affected examples**: Any example hook scripts in the repo need updating to use JSON stdin -- **User impact**: Users following the current guide will have non-functional hooks; this update provides correct, working examples diff --git a/openspec/changes/archive/2025-12-24-update-hooks-lesson/specs/hooks-documentation/spec.md b/openspec/changes/archive/2025-12-24-update-hooks-lesson/specs/hooks-documentation/spec.md deleted file mode 100644 index 7e30819..0000000 --- a/openspec/changes/archive/2025-12-24-update-hooks-lesson/specs/hooks-documentation/spec.md +++ /dev/null @@ -1,124 +0,0 @@ -# Hooks Documentation Specification - -## ADDED Requirements - -### Requirement: Hook Event Types Documentation -The hooks lesson SHALL document all 9 official hook events with their correct names, matchers, and behavior. - -#### Scenario: Complete hook event coverage -- **WHEN** a user reads the hooks lesson -- **THEN** they find documentation for PreToolUse, PermissionRequest, PostToolUse, Notification, UserPromptSubmit, Stop, SubagentStop, PreCompact, SessionStart, and SessionEnd events - -#### Scenario: No deprecated hook events -- **WHEN** a user searches for PreCommit, PostCommit, or PrePush hooks -- **THEN** they do not find these as they are not valid Claude Code hook events - -### Requirement: Hook Configuration Format -The hooks lesson SHALL document the correct array-based configuration format with matchers and hooks arrays. - -#### Scenario: Configuration structure -- **WHEN** a user views hook configuration examples -- **THEN** they see the structure: `{ "hooks": { "EventName": [{ "matcher": "Pattern", "hooks": [{ "type": "command", "command": "..." }] }] } }` - -#### Scenario: Matcher patterns -- **WHEN** a user needs to match specific tools -- **THEN** they find documentation for exact string matching, regex patterns, and wildcards - -### Requirement: Hook Input Documentation -The hooks lesson SHALL document the JSON stdin input that hooks receive. - -#### Scenario: JSON input structure -- **WHEN** a user writes a hook script -- **THEN** they understand the input includes session_id, transcript_path, cwd, permission_mode, hook_event_name, tool_name, tool_input, and tool_use_id - -#### Scenario: Event-specific input fields -- **WHEN** a user writes a hook for a specific event -- **THEN** they find documentation for event-specific input fields (e.g., stop_hook_active for Stop event) - -### Requirement: Hook Output Documentation -The hooks lesson SHALL document hook output semantics including exit codes and JSON stdout structure. - -#### Scenario: Exit code semantics -- **WHEN** a user implements a hook -- **THEN** they understand exit code 0 means success, exit code 2 means blocking error (stderr used as error message), and other codes mean non-blocking error - -#### Scenario: JSON output format -- **WHEN** a hook needs to control behavior -- **THEN** the user can output JSON with continue, stopReason, suppressOutput, systemMessage, and hookSpecificOutput fields - -#### Scenario: Event-specific output -- **WHEN** a user writes a PreToolUse hook -- **THEN** they can output permissionDecision (allow/deny/ask), permissionDecisionReason, and updatedInput - -### Requirement: Prompt-Based Hooks Documentation -The hooks lesson SHALL document type="prompt" hooks for LLM-based evaluation on Stop and SubagentStop events. - -#### Scenario: Prompt hook configuration -- **WHEN** a user wants intelligent stop evaluation -- **THEN** they find documentation for configuring type="prompt" hooks with prompt text and timeout - -#### Scenario: LLM response schema -- **WHEN** using prompt-based hooks -- **THEN** the user understands the expected response schema with decision (approve/block), reason, continue, stopReason, and systemMessage - -### Requirement: Environment Variables Documentation -The hooks lesson SHALL document all environment variables available to hooks. - -#### Scenario: Standard environment variables -- **WHEN** a user writes a hook script -- **THEN** they can use CLAUDE_PROJECT_DIR for the absolute project path - -#### Scenario: SessionStart environment persistence -- **WHEN** using SessionStart hooks -- **THEN** the user can persist environment variables via CLAUDE_ENV_FILE - -#### Scenario: Remote environment detection -- **WHEN** running in web environment -- **THEN** hooks can check CLAUDE_CODE_REMOTE to detect this - -### Requirement: Security Documentation -The hooks lesson SHALL include security considerations and best practices from the official documentation. - -#### Scenario: Security disclaimer -- **WHEN** a user reads about hooks -- **THEN** they see a clear disclaimer that hooks execute arbitrary shell commands at their own risk - -#### Scenario: Security best practices -- **WHEN** a user implements hooks -- **THEN** they find guidance on input validation, shell variable quoting, path traversal prevention, and sensitive file handling - -### Requirement: MCP Tool Hook Patterns -The hooks lesson SHALL document how to create hooks for MCP tools. - -#### Scenario: MCP tool matching -- **WHEN** a user wants to hook into MCP tool calls -- **THEN** they find documentation for the pattern `mcp____` and regex matching - -### Requirement: Plugin Hooks Documentation -The hooks lesson SHALL document how plugins can provide hooks. - -#### Scenario: Plugin hook configuration -- **WHEN** a plugin needs to provide hooks -- **THEN** documentation covers hooks/hooks.json structure and ${CLAUDE_PLUGIN_ROOT} variable - -### Requirement: Debugging Documentation -The hooks lesson SHALL document how to debug hook execution. - -#### Scenario: Debug mode -- **WHEN** hooks are not working as expected -- **THEN** users can enable `claude --debug` for detailed hook execution logs - -#### Scenario: Verbose mode -- **WHEN** using Claude Code interactively -- **THEN** users can enable verbose mode (ctrl+o) to see hook execution progress - -### Requirement: Working Example Scripts -The hooks lesson SHALL provide working example scripts that use JSON stdin input. - -#### Scenario: Bash command validator -- **WHEN** a user wants to validate bash commands -- **THEN** they find a working Python script that reads JSON stdin and validates commands - -#### Scenario: Intelligent stop hook -- **WHEN** a user wants automatic task completion verification -- **THEN** they find a working prompt-based stop hook example diff --git a/openspec/changes/archive/2025-12-24-update-hooks-lesson/tasks.md b/openspec/changes/archive/2025-12-24-update-hooks-lesson/tasks.md deleted file mode 100644 index ec6c72a..0000000 --- a/openspec/changes/archive/2025-12-24-update-hooks-lesson/tasks.md +++ /dev/null @@ -1,69 +0,0 @@ -# Tasks: Update Hooks Lesson - -## 1. Content Structure Update -- [x] 1.1 Update introduction to explain hooks as event-driven automation scripts -- [x] 1.2 Replace hook architecture diagram with correct event flow -- [x] 1.3 Update hook types table with all 9 official hook events - -## 2. Configuration Format -- [x] 2.1 Rewrite configuration section with array-based matcher/hooks structure -- [x] 2.2 Add hook matcher documentation (exact match, regex patterns, wildcards) -- [x] 2.3 Add timeout configuration examples - -## 3. Hook Events Documentation -- [x] 3.1 Document PreToolUse event (matchers, decision control, updatedInput) -- [x] 3.2 Document PermissionRequest event (decision behavior, messages) -- [x] 3.3 Document PostToolUse event (block decision, additionalContext) -- [x] 3.4 Document Notification event (matchers: permission_prompt, idle_prompt, etc.) -- [x] 3.5 Document UserPromptSubmit event (block decision, context addition) -- [x] 3.6 Document Stop event (block continuation, stop_hook_active) -- [x] 3.7 Document SubagentStop event (subagent completion handling) -- [x] 3.8 Document PreCompact event (manual vs auto matchers) -- [x] 3.9 Document SessionStart event (startup/resume/clear/compact matchers, CLAUDE_ENV_FILE) -- [x] 3.10 Document SessionEnd event (reason field) - -## 4. Hook Input/Output -- [x] 4.1 Document JSON stdin input structure (session_id, transcript_path, cwd, etc.) -- [x] 4.2 Document exit code semantics (0=success, 2=blocking error, other=non-blocking) -- [x] 4.3 Document JSON stdout output structure (continue, stopReason, hookSpecificOutput) -- [x] 4.4 Add examples for each hook event's specific output format - -## 5. Prompt-Based Hooks -- [x] 5.1 Add section on type="prompt" hooks for Stop/SubagentStop -- [x] 5.2 Document LLM response schema (decision, reason, continue, stopReason) -- [x] 5.3 Add practical examples of intelligent stop hooks - -## 6. Environment Variables -- [x] 6.1 Document CLAUDE_PROJECT_DIR usage -- [x] 6.2 Document CLAUDE_ENV_FILE for SessionStart env persistence -- [x] 6.3 Document CLAUDE_CODE_REMOTE for web environment detection -- [x] 6.4 Document plugin hook variables (${CLAUDE_PLUGIN_ROOT}) - -## 7. Security Section -- [x] 7.1 Add official security disclaimer (USE AT YOUR OWN RISK) -- [x] 7.2 Document security best practices (input validation, quoting, path traversal) -- [x] 7.3 Add configuration safety notes (snapshot at startup, modification warnings) - -## 8. Advanced Features -- [x] 8.1 Add MCP tool hook patterns (mcp____) -- [x] 8.2 Add plugin hooks documentation -- [x] 8.3 Add project-specific hook script examples - -## 9. Debugging and Troubleshooting -- [x] 9.1 Update debugging section with claude --debug flag -- [x] 9.2 Add verbose mode (ctrl+o) documentation -- [x] 9.3 Update troubleshooting with correct error scenarios - -## 10. Example Scripts -- [x] 10.1 Rewrite format-code hook to use JSON stdin -- [x] 10.2 Rewrite security-scan hook with proper JSON input parsing -- [x] 10.3 Rewrite bash command validator example from official docs -- [x] 10.4 Add intelligent stop hook example with prompt type -- [x] 10.5 Remove non-existent PreCommit/PostCommit/PrePush examples - -## 11. Final Cleanup -- [x] 11.1 Update Mermaid diagrams for accuracy -- [x] 11.2 Update variable reference table to reflect JSON input -- [x] 11.3 Update best practices table -- [x] 11.4 Update directory structure section -- [x] 11.5 Verify all links and references diff --git a/openspec/changes/archive/2025-12-24-update-memory-lesson/proposal.md b/openspec/changes/archive/2025-12-24-update-memory-lesson/proposal.md deleted file mode 100644 index 2730607..0000000 --- a/openspec/changes/archive/2025-12-24-update-memory-lesson/proposal.md +++ /dev/null @@ -1,32 +0,0 @@ -# Change: Update Memory Lesson with Latest Documentation - -## Why - -The current memory lesson (`blog-posts/02-memory.md`) is based on older Claude Code documentation. The official documentation at `https://code.claude.com/docs/en/memory` includes several new features and updates that the lesson doesn't cover, making it incomplete for readers who want to learn about Claude Code's full memory capabilities. - -## What Changes - -### New Features to Add -- **Project Rules** (`.claude/rules/*.md`) - Modular, topic-specific markdown files for organizing instructions -- **Path-Specific Rules** - YAML frontmatter with `paths:` to scope rules to specific file patterns -- **Glob Pattern Support** - Examples of glob patterns for path-specific rules -- **Project Local Memory** (`CLAUDE.local.md`) - Personal project preferences that are auto-gitignored -- **Symlink Support** - Sharing rules across projects using symbolic links - -### Updates to Existing Content -- **Memory Hierarchy Table** - Update to include Project Rules and Project Local as additional memory types -- **Enterprise Policy Windows Path** - Correct to `C:\Program Files\ClaudeCode\CLAUDE.md` (currently shows `C:\ProgramData\ClaudeCode\CLAUDE.md`) -- **Memory Lookup Algorithm** - Add detailed explanation of recursive upward search behavior -- **Best Practices Section** - Add guidelines for `.claude/rules/` organization - -### Structure Improvements -- Add new section: "Modular Rules with `.claude/rules/`" -- Add new section: "Path-Specific Rules" -- Update directory structure example to show `.claude/rules/` organization -- Improve organization of content to match official documentation structure - -## Impact - -- **Affected files**: `blog-posts/02-memory.md` -- **User benefit**: Readers will learn about complete memory capabilities including modular rules and path-specific scoping -- **No breaking changes**: All existing content remains valid; this adds new sections and updates outdated information diff --git a/openspec/changes/archive/2025-12-24-update-memory-lesson/specs/memory-lesson/spec.md b/openspec/changes/archive/2025-12-24-update-memory-lesson/specs/memory-lesson/spec.md deleted file mode 100644 index efd0882..0000000 --- a/openspec/changes/archive/2025-12-24-update-memory-lesson/specs/memory-lesson/spec.md +++ /dev/null @@ -1,69 +0,0 @@ -## MODIFIED Requirements - -### Requirement: Memory Hierarchy Documentation -The memory lesson SHALL document the complete 5-level memory hierarchy including Enterprise Policy, Project Memory, Project Rules, User Memory, and Project Local memory types. - -#### Scenario: Complete hierarchy explanation -- **WHEN** a reader views the memory hierarchy section -- **THEN** they SHALL see all 5 memory levels with their locations, scopes, and sharing capabilities - -#### Scenario: Enterprise Policy Windows path -- **WHEN** a reader views the Enterprise Policy location for Windows -- **THEN** the path SHALL be `C:\Program Files\ClaudeCode\CLAUDE.md` - -#### Scenario: Memory type comparison table -- **WHEN** a reader views the memory type comparison table -- **THEN** it SHALL include Project Rules (`.claude/rules/*.md`) and Project Local (`CLAUDE.local.md`) as distinct types - -## ADDED Requirements - -### Requirement: Modular Rules Documentation -The memory lesson SHALL document the `.claude/rules/` directory for organizing instructions into topic-specific markdown files. - -#### Scenario: Rules directory structure -- **WHEN** a reader views the modular rules section -- **THEN** they SHALL see an example directory structure showing `.claude/rules/` with subdirectories - -#### Scenario: Benefits explanation -- **WHEN** a reader views the modular rules section -- **THEN** they SHALL understand the benefits of topic-specific rule files for organization - -### Requirement: Path-Specific Rules Documentation -The memory lesson SHALL document how to use YAML frontmatter with `paths:` directive to scope rules to specific file patterns. - -#### Scenario: YAML frontmatter example -- **WHEN** a reader views the path-specific rules section -- **THEN** they SHALL see an example of YAML frontmatter with `paths:` directive - -#### Scenario: Glob pattern table -- **WHEN** a reader views the path-specific rules section -- **THEN** they SHALL see a table of glob pattern examples with explanations - -### Requirement: Project Local Memory Documentation -The memory lesson SHALL document `CLAUDE.local.md` files for personal project preferences that are auto-gitignored. - -#### Scenario: Local memory explanation -- **WHEN** a reader views the project local memory section -- **THEN** they SHALL understand that `CLAUDE.local.md` is for personal preferences on shared projects - -#### Scenario: Auto-gitignore behavior -- **WHEN** a reader views the project local memory section -- **THEN** they SHALL understand that these files are automatically excluded from git - -### Requirement: Symlink Support Documentation -The memory lesson SHALL document how to share rules across projects using symbolic links. - -#### Scenario: Symlink examples -- **WHEN** a reader views the symlink support section -- **THEN** they SHALL see bash examples for creating symlinks to shared rule files and directories - -### Requirement: Memory Lookup Algorithm Documentation -The memory lesson SHALL document how Claude Code discovers and loads memory files recursively. - -#### Scenario: Recursive search explanation -- **WHEN** a reader views the memory lookup section -- **THEN** they SHALL understand the recursive upward search from current directory to root - -#### Scenario: Subtree discovery -- **WHEN** a reader views the memory lookup section -- **THEN** they SHALL understand that subtree files are discovered when those files are accessed diff --git a/openspec/changes/archive/2025-12-24-update-memory-lesson/tasks.md b/openspec/changes/archive/2025-12-24-update-memory-lesson/tasks.md deleted file mode 100644 index fa8cef1..0000000 --- a/openspec/changes/archive/2025-12-24-update-memory-lesson/tasks.md +++ /dev/null @@ -1,46 +0,0 @@ -## 1. Update Memory Hierarchy Section -- [x] 1.1 Update the memory hierarchy table to include 5 levels (Enterprise, Project, Project Rules, User, Project Local) -- [x] 1.2 Update the mermaid diagram to show the complete hierarchy -- [x] 1.3 Fix Windows Enterprise Policy path from `C:\ProgramData\ClaudeCode\CLAUDE.md` to `C:\Program Files\ClaudeCode\CLAUDE.md` -- [x] 1.4 Add explanation of precedence and loading order - -## 2. Add Modular Rules Section -- [x] 2.1 Create new section "Modular Rules with `.claude/rules/`" -- [x] 2.2 Add directory structure example showing `.claude/rules/` organization -- [x] 2.3 Explain benefits of topic-specific rule files -- [x] 2.4 Add examples of modular rule filenames (code-style.md, testing.md, security.md) - -## 3. Add Path-Specific Rules Section -- [x] 3.1 Create new section "Path-Specific Rules with Glob Patterns" -- [x] 3.2 Explain YAML frontmatter with `paths:` directive -- [x] 3.3 Add table of glob pattern examples (`**/*.ts`, `src/**/*`, etc.) -- [x] 3.4 Include practical example of path-scoped API rules - -## 4. Add Project Local Memory Section -- [x] 4.1 Add explanation of `CLAUDE.local.md` file -- [x] 4.2 Explain auto-gitignore behavior -- [x] 4.3 Add use case examples (personal preferences on shared projects) - -## 5. Add Symlink Support Section -- [x] 5.1 Add section on sharing rules across projects using symlinks -- [x] 5.2 Include bash examples for creating symlinks to shared rules - -## 6. Update Memory Lookup Algorithm -- [x] 6.1 Add detailed explanation of recursive upward search -- [x] 6.2 Explain subtree discovery behavior -- [x] 6.3 Add example of which files are loaded from different directories - -## 7. Update Best Practices -- [x] 7.1 Add best practices for `.claude/rules/` organization -- [x] 7.2 Add guidelines for using path-specific rules sparingly -- [x] 7.3 Add tips for symlink-based rule sharing - -## 8. Update Directory Structure Example -- [x] 8.1 Update the directory structure to show `.claude/rules/` hierarchy -- [x] 8.2 Include subdirectory examples (frontend/, backend/) - -## 9. Review and Polish -- [x] 9.1 Ensure all mermaid diagrams are updated -- [x] 9.2 Review table formatting consistency -- [x] 9.3 Update "Official Documentation" links if needed -- [x] 9.4 Verify all code examples are accurate diff --git a/openspec/changes/archive/2025-12-24-update-skills-lesson/proposal.md b/openspec/changes/archive/2025-12-24-update-skills-lesson/proposal.md deleted file mode 100644 index 0b43fe4..0000000 --- a/openspec/changes/archive/2025-12-24-update-skills-lesson/proposal.md +++ /dev/null @@ -1,48 +0,0 @@ -# Change: Update Agent Skills Lesson with Latest Documentation - -## Why - -The current Agent Skills lesson (03-skills) is missing several key features and best practices from the latest official Claude Code documentation at https://code.claude.com/docs/en/skills#agent-skills. Users need up-to-date information to effectively create, manage, debug, and share skills. - -## What Changes - -### Documentation Updates (README.md and blog-posts/03-skills.md) - -1. **Enhanced Managing Skills Section** - Add comprehensive guidance for: - - Viewing available skills (via Claude and filesystem) - - Testing skills effectively - - Updating skills (with restart requirements) - - Removing skills properly - -2. **Improved Debugging Section** - Add detailed troubleshooting for: - - Skills being skipped or non-functional - - Invalid YAML frontmatter detection - - Script permission issues - - Path format requirements (forward slashes) - - Multiple skills conflicting - -3. **Version History Best Practice** - Add guidance on documenting skill versions in SKILL.md - -4. **Enhanced allowed-tools Documentation** - Expand explanation of tool access control with: - - Use cases for read-only skills - - Security-sensitive workflow examples - - Note about permission prompts when not specified - -5. **Multi-File Skill Example** - Add comprehensive example showing: - - Directory structure for complex skills - - Multiple reference files - - Scripts subdirectory - - Templates organization - -6. **Plugin Skills Clarification** - Better explain how plugin-bundled skills work - -### Example Updates (03-skills/ directory) - -7. **Add Version History Example** - Update code-review SKILL.md to include version history section - -## Impact - -- Affected docs: `03-skills/README.md`, `blog-posts/03-skills.md` -- Affected examples: `03-skills/code-review/SKILL.md` -- No breaking changes - purely additive documentation improvements -- Improves user experience for skill creation and debugging diff --git a/openspec/changes/archive/2025-12-24-update-skills-lesson/specs/skills-lesson/spec.md b/openspec/changes/archive/2025-12-24-update-skills-lesson/specs/skills-lesson/spec.md deleted file mode 100644 index 323833d..0000000 --- a/openspec/changes/archive/2025-12-24-update-skills-lesson/specs/skills-lesson/spec.md +++ /dev/null @@ -1,64 +0,0 @@ -## ADDED Requirements - -### Requirement: Managing Skills Documentation -The skills lesson SHALL provide comprehensive guidance for managing skills including viewing available skills, testing skills, updating skills with restart requirements, and removing skills. - -#### Scenario: User wants to view available skills -- **WHEN** a user wants to see what skills are available -- **THEN** the documentation provides both CLI method (asking Claude "What Skills are available?") and filesystem method (ls ~/.claude/skills/ and ls .claude/skills/) - -#### Scenario: User wants to test a skill -- **WHEN** a user wants to test if their skill works -- **THEN** the documentation explains that skills activate automatically based on matching descriptions, with example test queries - -#### Scenario: User wants to update a skill -- **WHEN** a user modifies a SKILL.md file -- **THEN** the documentation explains that changes take effect on next Claude Code startup and restart is required if already running - -#### Scenario: User wants to remove a skill -- **WHEN** a user wants to remove a skill -- **THEN** the documentation provides rm -rf commands for both personal and project skills, with git commit for project skills - -### Requirement: Enhanced Debugging Guidance -The skills lesson SHALL provide detailed debugging guidance for common skill issues including skipped skills, YAML errors, script permissions, and path formats. - -#### Scenario: Skill not being discovered -- **WHEN** Claude doesn't use a user's skill -- **THEN** the documentation explains to check: description specificity, YAML syntax validity (opening/closing ---, no tabs), and correct file path location - -#### Scenario: Skill has errors -- **WHEN** a skill has runtime errors -- **THEN** the documentation explains to check: dependency installation, script execute permissions (chmod +x), and forward slash usage in paths - -#### Scenario: Multiple skills conflict -- **WHEN** multiple skills are activated unexpectedly -- **THEN** the documentation explains using distinct trigger terms in descriptions to help Claude choose the right skill - -### Requirement: Version History Documentation -The skills lesson SHALL include a best practice example for documenting skill version history in SKILL.md files. - -#### Scenario: User wants to track skill versions -- **WHEN** a user maintains a skill over time -- **THEN** the documentation provides a version history markdown template with date and description format - -### Requirement: Enhanced Tool Access Control Documentation -The skills lesson SHALL provide expanded documentation for the allowed-tools feature including use cases, security examples, and behavior when not specified. - -#### Scenario: User wants a read-only skill -- **WHEN** a user wants to create a skill that cannot modify files -- **THEN** the documentation provides an example with allowed-tools: Read, Grep, Glob - -#### Scenario: User wants security-sensitive workflow -- **WHEN** a user has a security-sensitive skill -- **THEN** the documentation explains how allowed-tools restricts Claude's capabilities within that skill context - -#### Scenario: allowed-tools not specified -- **WHEN** a user doesn't specify allowed-tools -- **THEN** the documentation explains that Claude will ask for permission as normal - -### Requirement: Multi-File Skill Example -The skills lesson SHALL include a comprehensive example of a multi-file skill showing directory structure with multiple reference files, scripts, and templates. - -#### Scenario: User wants to create complex skill -- **WHEN** a user needs a skill with supporting files -- **THEN** the documentation provides a complete directory structure example showing SKILL.md, reference files (FORMS.md, REFERENCE.md), scripts subdirectory, and progressive disclosure explanation diff --git a/openspec/changes/archive/2025-12-24-update-skills-lesson/tasks.md b/openspec/changes/archive/2025-12-24-update-skills-lesson/tasks.md deleted file mode 100644 index 6b0b771..0000000 --- a/openspec/changes/archive/2025-12-24-update-skills-lesson/tasks.md +++ /dev/null @@ -1,27 +0,0 @@ -# Tasks: Update Agent Skills Lesson - -## 1. Update Main README (03-skills/README.md) - -- [x] 1.1 Add "Managing Skills" section with viewing, testing, updating, removing guidance -- [x] 1.2 Expand "Troubleshooting Guide" with debugging tips for skipped skills, YAML errors, script permissions, path formats -- [x] 1.3 Add "Version History Best Practice" section with example -- [x] 1.4 Enhance "allowed-tools" documentation with use cases and security examples -- [x] 1.5 Add "Multi-File Skill Example" showing complex skill structure with multiple reference files - -## 2. Update Blog Post (blog-posts/03-skills.md) - -- [x] 2.1 Add "Managing Skills" section mirroring README updates -- [x] 2.2 Expand troubleshooting with debugging guidance from official docs -- [x] 2.3 Add version history best practice -- [x] 2.4 Enhance allowed-tools explanation -- [x] 2.5 Add multi-file skill example - -## 3. Update Example Skills - -- [x] 3.1 Add version history section to `03-skills/code-review/SKILL.md` - -## 4. Validation - -- [x] 4.1 Verify all code examples are syntactically correct -- [x] 4.2 Ensure consistency between README and blog post -- [x] 4.3 Test that existing examples still work with updated documentation diff --git a/openspec/changes/archive/2025-12-24-update-slash-commands-session/proposal.md b/openspec/changes/archive/2025-12-24-update-slash-commands-session/proposal.md deleted file mode 100644 index 8a1e994..0000000 --- a/openspec/changes/archive/2025-12-24-update-slash-commands-session/proposal.md +++ /dev/null @@ -1,33 +0,0 @@ -# Change: Update Slash Commands Documentation - -## Why - -The current slash commands documentation in `01-slash-commands/README.md` is outdated compared to the official Claude Code documentation at https://code.claude.com/docs/en/slash-commands. Several new features, built-in commands, and capabilities have been added that users should know about. - -## What Changes - -### Documentation Updates - -- **Add comprehensive built-in commands table** - Document all 40+ built-in slash commands with their purposes -- **Update custom command features** - Document new argument handling (`$ARGUMENTS`, `$1`, `$2`, etc.) -- **Add bash execution syntax** - Document the `!` prefix for executing bash commands within slash commands -- **Update frontmatter fields** - Document `allowed-tools`, `argument-hint`, `description`, `model`, `disable-model-invocation` -- **Add file reference syntax** - Document the `@` prefix for including file contents -- **Add Plugin commands section** - Document `/plugin-name:command-name` pattern -- **Add MCP slash commands section** - Document `/mcp____` pattern -- **Add SlashCommand Tool section** - Document programmatic invocation from Claude -- **Add Skills vs Slash Commands comparison** - Help users choose the right tool - -### Example Updates - -- Add example command with bash execution (`!git status`) -- Add example with file references (`@src/utils/helpers.js`) -- Add example with complete frontmatter -- Update existing examples to use official syntax - -## Impact - -- Affected specs: `slash-commands` (new capability spec to be created) -- Affected code: `01-slash-commands/README.md`, potentially new example files -- No breaking changes - additive documentation improvements -- Benefits all users learning about Claude Code slash commands diff --git a/openspec/changes/archive/2025-12-24-update-slash-commands-session/specs/slash-commands/spec.md b/openspec/changes/archive/2025-12-24-update-slash-commands-session/specs/slash-commands/spec.md deleted file mode 100644 index 101c509..0000000 --- a/openspec/changes/archive/2025-12-24-update-slash-commands-session/specs/slash-commands/spec.md +++ /dev/null @@ -1,147 +0,0 @@ -## ADDED Requirements - -### Requirement: Slash Command Types Documentation - -The documentation SHALL describe the four types of slash commands: -1. Built-in commands provided by Claude Code -2. Custom user-defined commands (project and personal) -3. Plugin commands -4. MCP (Model Context Protocol) slash commands - -#### Scenario: User learns about command types -- **WHEN** a user reads the slash commands documentation -- **THEN** they understand the different types of slash commands available -- **AND** they know when to use each type - ---- - -### Requirement: Built-in Commands Reference - -The documentation SHALL include a comprehensive reference table of all built-in slash commands with their purposes, including but not limited to: -- `/add-dir` - Add additional working directories -- `/agents` - Manage custom AI subagents -- `/clear` - Clear conversation history -- `/compact` - Compact conversation with optional focus instructions -- `/config` - Open Settings interface -- `/context` - Visualize current context usage -- `/cost` - Show token usage statistics -- `/doctor` - Check installation health -- `/export` - Export conversation to file or clipboard -- `/help` - Get usage help -- `/hooks` - Manage hook configurations -- `/init` - Initialize project with CLAUDE.md -- `/mcp` - Manage MCP server connections -- `/memory` - Edit CLAUDE.md memory files -- `/model` - Select or change AI model -- `/permissions` - View or update permissions -- `/resume` - Resume conversation by ID or name -- `/review` - Request code review -- `/sandbox` - Enable sandboxed bash tool -- `/vim` - Enter vim mode - -#### Scenario: User finds built-in command -- **WHEN** a user needs to perform a common operation -- **THEN** they can find the appropriate built-in command in the reference table -- **AND** they understand what the command does - ---- - -### Requirement: Argument Handling - -The documentation SHALL explain both argument handling methods: -1. `$ARGUMENTS` - Receives all arguments as a single string -2. `$1`, `$2`, `$3`, etc. - Individual positional arguments - -#### Scenario: User uses $ARGUMENTS placeholder -- **WHEN** a user creates a command with `$ARGUMENTS` placeholder -- **AND** invokes it with `/fix-issue 123 high-priority` -- **THEN** `$ARGUMENTS` contains "123 high-priority" - -#### Scenario: User uses positional arguments -- **WHEN** a user creates a command with `$1`, `$2`, `$3` placeholders -- **AND** invokes it with `/review-pr 456 high alice` -- **THEN** `$1` is "456", `$2` is "high", `$3` is "alice" - ---- - -### Requirement: Bash Command Execution - -The documentation SHALL explain the `!` prefix for executing bash commands within slash command files before the command runs. - -#### Scenario: User includes dynamic context -- **WHEN** a user adds `!git status` in their command file -- **THEN** the git status output is included in the command context -- **AND** Claude receives the current repository state - ---- - -### Requirement: File Reference Syntax - -The documentation SHALL explain the `@` prefix for including file contents in slash commands. - -#### Scenario: User references a file -- **WHEN** a user adds `@src/utils/helpers.js` in their command file -- **THEN** the contents of that file are included in the command context - ---- - -### Requirement: Frontmatter Fields - -The documentation SHALL document all supported frontmatter fields: -- `allowed-tools` - List of tools the command can use -- `argument-hint` - Expected arguments for auto-completion -- `description` - Brief description of the command -- `model` - Specific model to use for this command -- `disable-model-invocation` - Prevent SlashCommand tool from calling this command - -#### Scenario: User creates command with frontmatter -- **WHEN** a user creates a command with frontmatter fields -- **THEN** Claude Code respects those configuration options -- **AND** the command behaves according to the specified settings - ---- - -### Requirement: Plugin Commands Documentation - -The documentation SHALL explain the plugin command format: `/plugin-name:command-name` or simply `/command-name` when there are no naming conflicts. - -#### Scenario: User invokes plugin command -- **WHEN** a user types `/frontend-design:frontend-design` -- **THEN** the corresponding plugin command executes - ---- - -### Requirement: MCP Slash Commands Documentation - -The documentation SHALL explain the MCP slash command format: `/mcp____ [arguments]` - -#### Scenario: User invokes MCP command -- **WHEN** a user types `/mcp__github__list_prs` -- **THEN** the MCP server's prompt is executed - ---- - -### Requirement: SlashCommand Tool Documentation - -The documentation SHALL explain how Claude can programmatically invoke slash commands using the SlashCommand tool, including: -- How to enable this via prompt or CLAUDE.md references -- How to disable via permissions -- The character budget limit (default 15,000, configurable via `SLASH_COMMAND_TOOL_CHAR_BUDGET`) - -#### Scenario: User enables programmatic invocation -- **WHEN** a user adds "Run /write-unit-test when writing tests" to CLAUDE.md -- **THEN** Claude can automatically invoke that command when appropriate - ---- - -### Requirement: Skills vs Slash Commands Comparison - -The documentation SHALL include a comparison table helping users choose between Skills and Slash Commands based on: -- Best use cases for each -- File structure differences -- Invocation method (explicit vs automatic) -- Complexity level - -#### Scenario: User decides between skill and command -- **WHEN** a user needs to create a reusable capability -- **THEN** they can use the comparison to decide whether a slash command or skill is more appropriate diff --git a/openspec/changes/archive/2025-12-24-update-slash-commands-session/tasks.md b/openspec/changes/archive/2025-12-24-update-slash-commands-session/tasks.md deleted file mode 100644 index 57d9ebf..0000000 --- a/openspec/changes/archive/2025-12-24-update-slash-commands-session/tasks.md +++ /dev/null @@ -1,42 +0,0 @@ -## 1. Documentation Structure Updates - -- [x] 1.1 Add "Types of Slash Commands" section with overview of built-in, custom, plugin, and MCP commands -- [x] 1.2 Create comprehensive built-in commands reference table (40+ commands) -- [x] 1.3 Update custom commands section with new features - -## 2. Custom Command Features - -- [x] 2.1 Document `$ARGUMENTS` placeholder for all arguments -- [x] 2.2 Document individual argument placeholders (`$1`, `$2`, `$3`, etc.) -- [x] 2.3 Document bash execution with `!` prefix (e.g., `!git status`) -- [x] 2.4 Document file references with `@` prefix (e.g., `@src/file.js`) -- [x] 2.5 Document thinking mode trigger via keywords - -## 3. Frontmatter Updates - -- [x] 3.1 Update frontmatter section with official fields -- [x] 3.2 Document `allowed-tools` field with examples -- [x] 3.3 Document `argument-hint` field for auto-completion -- [x] 3.4 Document `description` field -- [x] 3.5 Document `model` field for specific model selection -- [x] 3.6 Document `disable-model-invocation` field - -## 4. New Sections - -- [x] 4.1 Add "Plugin Commands" section with `/plugin-name:command-name` pattern -- [x] 4.2 Add "MCP Slash Commands" section with `/mcp____` pattern -- [x] 4.3 Add "SlashCommand Tool" section for programmatic invocation -- [x] 4.4 Add "Skills vs Slash Commands" comparison table - -## 5. Example Files - -- [x] 5.1 Create new example showing bash execution feature (commit.md) -- [x] 5.2 Create new example showing file references (commit.md includes @package.json example in README) -- [x] 5.3 Update existing examples to use official frontmatter format (removed name/tags, added allowed-tools) -- [x] 5.4 Add commit command example (from official docs) - -## 6. Validation - -- [x] 6.1 Verify all links work correctly -- [x] 6.2 Test example commands format -- [x] 6.3 Review for consistency with official documentation diff --git a/openspec/changes/archive/2025-12-24-update-subagents-lesson/proposal.md b/openspec/changes/archive/2025-12-24-update-subagents-lesson/proposal.md deleted file mode 100644 index 1149856..0000000 --- a/openspec/changes/archive/2025-12-24-update-subagents-lesson/proposal.md +++ /dev/null @@ -1,98 +0,0 @@ -# Proposal: update-subagents-lesson - -## Why - -The existing subagents lesson lacks critical features documented in the official docs and uses outdated configuration formats. - -## What Changes - -- Update README with all official features (built-in subagents, /agents command, CLI config, resumable agents) -- Update example files to new YAML frontmatter format -- Add new example subagents (debugger, data-scientist) - -## Motivation - -The existing subagents lesson lacks critical features documented in the official docs: - -1. **Missing `/agents` command** - The interactive management interface -2. **Incomplete configuration fields** - Missing `model`, `permissionMode`, `skills` fields -3. **No built-in subagents section** - General-Purpose, Plan, and Explore agents not documented -4. **Missing resumable agents feature** - Agent continuation with `agentId` -5. **No CLI-based configuration** - `--agents` flag for session-specific agents -6. **Outdated file format** - Uses `system_prompt` instead of YAML frontmatter with markdown body -7. **Missing thoroughness levels** - Quick, Medium, Very thorough for Explore agent -8. **No proactive invocation guidance** - "use PROACTIVELY" description patterns - -## Scope - -### In Scope -- Update `04-subagents/README.md` with all official documentation features -- Update example subagent files to use correct YAML frontmatter format -- Add new example subagents (debugger, data-scientist) from official docs -- Document built-in subagents (General-Purpose, Plan, Explore) -- Add `/agents` command documentation -- Add CLI-based configuration section -- Document resumable agents feature -- Update installation and usage instructions - -### Out of Scope -- Plugin subagents in `07-plugins/` (separate concern) -- Creating new advanced tutorials -- Video or interactive content - -## Key Changes - -### 1. Configuration Format Update - -**Current** (incorrect): -```yaml ---- -name: agent-name -description: Brief description -tools: read, grep, diff ---- -``` - -**Updated** (per official docs): -```yaml ---- -name: agent-name -description: Description of when this subagent should be invoked -tools: tool1, tool2, tool3 # Optional - inherits all tools if omitted -model: sonnet # Optional - specify model alias or 'inherit' -permissionMode: default # Optional - permission mode -skills: skill1, skill2 # Optional - skills to auto-load ---- - -Your subagent's system prompt goes here in markdown. -``` - -### 2. Built-in Subagents Documentation - -Add new section documenting: -- **General-Purpose** - Sonnet model, all tools, complex tasks -- **Plan** - Sonnet model, research tools, plan mode -- **Explore** - Haiku model, read-only, fast codebase searching with thoroughness levels - -### 3. Management Features - -- `/agents` command for interactive management -- CLI `--agents` flag for session-specific configuration -- Resumable agents with `agentId` - -### 4. Example Updates - -Update existing examples and add: -- Debugger subagent (from official docs) -- Data Scientist subagent (from official docs) - -## Success Criteria - -- [ ] README covers all features from official documentation -- [ ] Configuration examples use correct YAML frontmatter format -- [ ] All 5 existing example agents updated to new format -- [ ] 2 new example agents added (debugger, data-scientist) -- [ ] Built-in subagents documented -- [ ] `/agents` command documented -- [ ] Resumable agents feature documented -- [ ] Installation instructions updated diff --git a/openspec/changes/archive/2025-12-24-update-subagents-lesson/specs/subagents-lesson/spec.md b/openspec/changes/archive/2025-12-24-update-subagents-lesson/specs/subagents-lesson/spec.md deleted file mode 100644 index bf10fed..0000000 --- a/openspec/changes/archive/2025-12-24-update-subagents-lesson/specs/subagents-lesson/spec.md +++ /dev/null @@ -1,101 +0,0 @@ -# Spec: Subagents Lesson Content - -## ADDED Requirements - -### Requirement: Configuration Format - -The subagent configuration MUST use YAML frontmatter with all supported fields. - -#### Scenario: Complete configuration example -- **Given**: A user wants to create a subagent -- **When**: They view the configuration documentation -- **Then**: The example shows all fields: name, description, tools (optional), model (optional), permissionMode (optional), skills (optional) - -#### Scenario: Tools field omission -- **Given**: A subagent configuration omits the tools field -- **When**: The documentation explains this -- **Then**: It states the subagent inherits all tools from the main agent - -### Requirement: Built-in Subagents Documentation - -The lesson MUST document the three built-in subagents. - -#### Scenario: General-Purpose subagent -- **Given**: A user reads about built-in subagents -- **When**: They view the General-Purpose section -- **Then**: They learn it uses Sonnet model, has all tools, and handles complex multi-step tasks - -#### Scenario: Plan subagent -- **Given**: A user reads about built-in subagents -- **When**: They view the Plan section -- **Then**: They learn it uses Sonnet model, has Read/Glob/Grep/Bash tools, and is used in plan mode - -#### Scenario: Explore subagent -- **Given**: A user reads about built-in subagents -- **When**: They view the Explore section -- **Then**: They learn it uses Haiku model, is read-only, fast, and supports thoroughness levels (quick, medium, very thorough) - -### Requirement: /agents Command - -The lesson MUST document the interactive /agents command. - -#### Scenario: User discovers management interface -- **Given**: A user wants to manage subagents interactively -- **When**: They read the documentation -- **Then**: They learn about `/agents` command to create, edit, delete, and view subagents - -### Requirement: Resumable Agents - -The lesson MUST document agent continuation with agentId. - -#### Scenario: User learns about resuming agents -- **Given**: A user wants to continue a previous agent conversation -- **When**: They read the resumable agents section -- **Then**: They learn agents return an agentId and can be resumed with full context - -### Requirement: CLI Configuration - -The lesson MUST document session-specific agent configuration via CLI. - -#### Scenario: User defines agents via command line -- **Given**: A user wants to define agents for a single session -- **When**: They read the CLI configuration section -- **Then**: They learn to use `--agents` flag with JSON configuration - -## ADDED Requirements - -### Requirement: Example Subagent - Debugger - -The lesson MUST include a debugger subagent example. - -#### Scenario: User needs debugging specialist -- **Given**: A user wants a debugging-focused subagent -- **When**: They view the examples -- **Then**: They find a complete debugger.md example with root cause analysis approach - -### Requirement: Example Subagent - Data Scientist - -The lesson MUST include a data scientist subagent example. - -#### Scenario: User needs data analysis specialist -- **Given**: A user wants a data analysis subagent -- **When**: They view the examples -- **Then**: They find a complete data-scientist.md example with SQL/BigQuery focus - -### Requirement: File Location Documentation - -The lesson MUST document where subagent files can be stored. - -#### Scenario: User learns storage locations -- **Given**: A user wants to know where to put subagent files -- **When**: They read the file locations section -- **Then**: They learn about project (.claude/agents/), user (~/.claude/agents/), plugin, and CLI locations with priority order - -### Requirement: Proactive Invocation Guidance - -The lesson MUST explain how to encourage automatic subagent use. - -#### Scenario: User wants subagent used automatically -- **Given**: A user wants Claude to proactively use their subagent -- **When**: They read the usage section -- **Then**: They learn to include "use PROACTIVELY" or "MUST BE USED" in the description field diff --git a/openspec/changes/archive/2025-12-24-update-subagents-lesson/tasks.md b/openspec/changes/archive/2025-12-24-update-subagents-lesson/tasks.md deleted file mode 100644 index bb9a8f1..0000000 --- a/openspec/changes/archive/2025-12-24-update-subagents-lesson/tasks.md +++ /dev/null @@ -1,90 +0,0 @@ -# Tasks: update-subagents-lesson - -## Phase 1: Update README.md Structure - -1. [x] **Update Overview section** - - Add `/agents` command mention - - Add built-in subagents overview - - Update key benefits with official wording - -2. [x] **Add File Locations section** - - Document project subagents (`.claude/agents/`) - - Document user subagents (`~/.claude/agents/`) - - Document plugin agents - - Document CLI-defined agents - -3. [x] **Update Configuration section** - - Update YAML frontmatter format with all fields - - Add configuration fields table (name, description, tools, model, permissionMode, skills) - - Add CLI-based configuration with `--agents` flag - -## Phase 2: Add New Sections - -4. [x] **Add Built-in Subagents section** - - Document General-Purpose subagent (Sonnet, all tools) - - Document Plan subagent (Sonnet, research tools) - - Document Explore subagent (Haiku, read-only, thoroughness levels) - -5. [x] **Add /agents Command section** - - Document interactive menu options - - Create, edit, delete operations - - View available subagents - -6. [x] **Add Resumable Agents section** - - Document agentId concept - - Show resume syntax - - List use cases - -7. [x] **Add Chaining Subagents section** - - Multi-agent workflows - - Sequential delegation - -## Phase 3: Update Example Files - -8. [x] **Update `code-reviewer.md`** - - Add model field - - Update to match official example format - - Add proactive usage hints - -9. [x] **Update `test-engineer.md`** - - Add model field - - Update system prompt format - -10. [x] **Update `documentation-writer.md`** - - Add model field - - Update format - -11. [x] **Update `secure-reviewer.md`** - - Update to minimal permission pattern - -12. [x] **Update `implementation-agent.md`** - - Update tool list format - -## Phase 4: Add New Example Files - -13. [x] **Create `debugger.md`** - - Copy from official docs example - - Adapt to project style - -14. [x] **Create `data-scientist.md`** - - Copy from official docs example - - Adapt to project style - -## Phase 5: Finalize - -15. [x] **Update Installation Instructions** - - Add `/agents` method - - Update verification steps - -16. [x] **Update Related Concepts** - - Link to new sections - - Update comparison table - -17. [x] **Update last modified date** - -## Validation - -- [x] All YAML frontmatter validates correctly -- [x] No broken internal links -- [x] Examples use consistent formatting -- [x] Built-in agents documented accurately diff --git a/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/proposal.md b/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/proposal.md deleted file mode 100644 index 563d8d2..0000000 --- a/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/proposal.md +++ /dev/null @@ -1,23 +0,0 @@ -# Change: Add Blog Post - 4 Essential Slash Commands for Development Workflow - -## Why - -The claude-howto project provides excellent reference documentation but lacks blog-style content that showcases real-world usage patterns. Users have found 4 slash commands particularly valuable across their development workflow, and a blog post explaining when/where/how to use each would help others adopt these productivity tools. - -## What Changes - -- Create new `blog-post/` directory for blog content -- Add blog post: "4 Essential Slash Commands I Use in Every Project" -- Cover 4 commands with practical guidance: - - `/push-all` - Quick deployment of coherent changes - - `/setup-ci-cd` - Post-POC quality infrastructure - - `/doc-refactor` - Post-MVP documentation polish - - `/unit-test-expand` - Milestone-driven test expansion -- Reference the first slash commands blog: [Discovering Claude Code Slash Commands](https://medium.com/@luongnv89/discovering-claude-code-slash-commands-cdc17f0dfb29) -- Link to full command files when content exceeds 30 lines - -## Impact - -- Affected specs: None (new capability) -- Affected code: New `blog-post/` directory and content -- No breaking changes diff --git a/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/specs/blog-post/spec.md b/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/specs/blog-post/spec.md deleted file mode 100644 index 95386b5..0000000 --- a/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/specs/blog-post/spec.md +++ /dev/null @@ -1,41 +0,0 @@ -## ADDED Requirements - -### Requirement: Blog Post Directory Structure - -The project SHALL provide a `blog-post/` directory for hosting blog-style content that complements the reference documentation. - -#### Scenario: Blog post directory exists -- **WHEN** a user navigates to the project root -- **THEN** a `blog-post/` directory is present containing blog content - -### Requirement: Slash Commands Usage Blog Post - -The blog SHALL document 4 essential slash commands with practical usage guidance covering when, where, and how to use each command in a development workflow. - -#### Scenario: Complete command coverage -- **WHEN** a user reads the blog post -- **THEN** they find documentation for `/push-all`, `/setup-ci-cd`, `/doc-refactor`, and `/unit-test-expand` - -#### Scenario: Command file linking for long content -- **WHEN** a command file exceeds 30 lines -- **THEN** the blog SHALL provide a link to the full command file in the claude-howto project - -#### Scenario: Inline content for short commands -- **WHEN** a command file is 30 lines or fewer -- **THEN** the blog MAY include the command content inline - -### Requirement: Development Workflow Context - -Each command section SHALL explain when to use the command in the development lifecycle (POC, MVP, milestone phases). - -#### Scenario: Workflow phase guidance -- **WHEN** a user reads a command section -- **THEN** they understand which development phase the command is most appropriate for - -### Requirement: Reference to First Blog - -The blog post SHALL reference the introductory slash commands blog: "Discovering Claude Code Slash Commands" for foundational context. - -#### Scenario: Blog reference present -- **WHEN** a user reads the introduction -- **THEN** they find a link to the original slash commands blog post on Medium diff --git a/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/tasks.md b/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/tasks.md deleted file mode 100644 index c38ed13..0000000 --- a/openspec/changes/archive/2025-12-26-add-blog-post-slash-commands/tasks.md +++ /dev/null @@ -1,25 +0,0 @@ -## 1. Setup - -- [x] 1.1 Create `blog-post/` directory at project root - -## 2. Blog Post Creation - -- [x] 2.1 Create blog post markdown file with proper structure -- [x] 2.2 Write introduction referencing first slash commands blog -- [x] 2.3 Document `/push-all` with link to full command (152 lines) -- [x] 2.4 Document `/setup-ci-cd` with inline content (25 lines) -- [x] 2.5 Document `/doc-refactor` with inline content (23 lines) -- [x] 2.6 Document `/unit-test-expand` with inline content (24 lines) -- [x] 2.7 Add workflow diagram showing when to use each command -- [x] 2.8 Write conclusion with development lifecycle integration - -## 3. Integration - -- [x] 3.1 Add blog-post to main README navigation -- [x] 3.2 Cross-reference from slash-commands README - -## 4. Verification - -- [x] 4.1 Verify all internal links work -- [x] 4.2 Verify external links are valid -- [x] 4.3 Review content for clarity and accuracy diff --git a/openspec/changes/update-slash-commands-readme/proposal.md b/openspec/changes/update-slash-commands-readme/proposal.md deleted file mode 100644 index cf346bd..0000000 --- a/openspec/changes/update-slash-commands-readme/proposal.md +++ /dev/null @@ -1,20 +0,0 @@ -# Change: Update Slash Commands README with New Commands - -## Why - -The `01-slash-commands/README.md` is outdated and needs to reflect: -1. Updated `push-all.md` command with enhanced safety checks (API key validation, confirmation workflow) -2. Three new slash commands added to the folder: `doc-refactor.md`, `setup-ci-cd.md`, `unit-test-expand.md` - -## What Changes - -- **Update push-all documentation**: Reflect the enhanced workflow including safety checks, API key validation, and confirmation prompts -- **Add doc-refactor command**: Document the new documentation restructuring command -- **Add setup-ci-cd command**: Document the new CI/CD pipeline setup command -- **Add unit-test-expand command**: Document the new test coverage expansion command -- Update "Available Commands" section count from 4 to 7 commands - -## Impact - -- Affected specs: `slash-commands` -- Affected code: `01-slash-commands/README.md` diff --git a/openspec/changes/update-slash-commands-readme/specs/slash-commands/spec.md b/openspec/changes/update-slash-commands-readme/specs/slash-commands/spec.md deleted file mode 100644 index 4831886..0000000 --- a/openspec/changes/update-slash-commands-readme/specs/slash-commands/spec.md +++ /dev/null @@ -1,66 +0,0 @@ -## ADDED Requirements - -### Requirement: Push-All Command with Safety Checks - -The documentation SHALL describe the `/push-all` command with its comprehensive safety workflow including: -1. Change analysis (git status, diff, log) -2. Safety checks for secrets, API keys, large files, build artifacts -3. API key validation distinguishing real keys from placeholders -4. Confirmation prompt before proceeding -5. Conventional commit message generation -6. Error handling guidance - -#### Scenario: User learns push-all safety workflow -- **WHEN** a user reads the push-all command documentation -- **THEN** they understand the multi-step safety workflow -- **AND** they know what types of files trigger warnings -- **AND** they understand they must confirm before execution - ---- - -### Requirement: Doc-Refactor Command Documentation - -The documentation SHALL describe the `/doc-refactor` command for restructuring project documentation including: -1. Project type analysis (library, API, web app, CLI, microservices) -2. Documentation centralization in `docs/` folder -3. Root README streamlining -4. Component-level documentation -5. Guide creation based on project type - -#### Scenario: User uses doc-refactor command -- **WHEN** a user reads the doc-refactor documentation -- **THEN** they understand how to invoke the command -- **AND** they know what documentation structure changes to expect -- **AND** they understand the command adapts to project type - ---- - -### Requirement: Setup-CI-CD Command Documentation - -The documentation SHALL describe the `/setup-ci-cd` command for implementing quality gates including: -1. Project analysis for language and tooling detection -2. Pre-commit hook configuration with language-specific tools -3. GitHub Actions workflow creation -4. Pipeline verification steps - -#### Scenario: User uses setup-ci-cd command -- **WHEN** a user reads the setup-ci-cd documentation -- **THEN** they understand the command creates pre-commit hooks -- **AND** they know GitHub Actions workflows will be generated -- **AND** they understand tools are selected based on project language - ---- - -### Requirement: Unit-Test-Expand Command Documentation - -The documentation SHALL describe the `/unit-test-expand` command for increasing test coverage including: -1. Coverage analysis to identify gaps -2. Gap identification (branches, error paths, boundaries) -3. Framework-specific test generation -4. Coverage verification - -#### Scenario: User uses unit-test-expand command -- **WHEN** a user reads the unit-test-expand documentation -- **THEN** they understand the command analyzes existing coverage -- **AND** they know it targets untested branches and edge cases -- **AND** they understand it works with their project's testing framework diff --git a/openspec/changes/update-slash-commands-readme/tasks.md b/openspec/changes/update-slash-commands-readme/tasks.md deleted file mode 100644 index 4670abf..0000000 --- a/openspec/changes/update-slash-commands-readme/tasks.md +++ /dev/null @@ -1,7 +0,0 @@ -## 1. Implementation - -- [x] 1.1 Update `/push-all` section in README to reflect enhanced safety checks (API key validation, confirmation workflow, detailed error handling) -- [x] 1.2 Add `/doc-refactor` section documenting the documentation restructuring command -- [x] 1.3 Add `/setup-ci-cd` section documenting the CI/CD pipeline setup command -- [x] 1.4 Add `/unit-test-expand` section documenting the test coverage expansion command -- [x] 1.5 Update section heading to reflect 8 available commands (was 4, added 4 new) diff --git a/openspec/project.md b/openspec/project.md deleted file mode 100644 index f5636ce..0000000 --- a/openspec/project.md +++ /dev/null @@ -1,125 +0,0 @@ -# Project Context - -## Purpose - -**Claude How To** is a comprehensive educational repository providing examples and documentation for Claude Code features and concepts. The project serves as: - -- A learning resource for developers new to Claude Code -- A reference collection of example configurations (slash commands, memory, skills, subagents, MCP, hooks, plugins, checkpoints, advanced features) -- A tool for generating offline documentation (EPUB format) - -**Goals:** -1. Provide clear, numbered learning paths (01-09) for Claude Code features -2. Include ready-to-use example configurations users can copy to their projects -3. Generate an EPUB ebook from the documentation for offline reading -4. Maintain high-quality Python tooling with CI/CD automation - -## Tech Stack - -### Primary Technologies -- **Python 3.10+** - EPUB builder script and tooling -- **Markdown** - Documentation content (all guides and examples) -- **JSON/YAML** - Configuration files (MCP configs, plugin definitions) -- **Shell Scripts** - Hook examples in `06-hooks/` - -### Python Dependencies -- `ebooklib` - EPUB generation -- `markdown` - Markdown to HTML conversion -- `beautifulsoup4` - HTML parsing/manipulation -- `httpx` - HTTP client (for Mermaid diagram rendering) -- `pillow` - Image processing -- `tenacity` - Retry logic for external API calls - -### Development Tools -- `uv` - Python package manager and virtual environment -- `ruff` - Linting and formatting (replaces black, isort, flake8) -- `bandit` - Security scanning -- `pytest` / `pytest-asyncio` - Testing framework -- `pre-commit` - Git hooks for code quality - -### CI/CD -- **GitHub Actions** - Automated linting, security scanning, testing, and EPUB builds -- Workflows in `.github/workflows/ci.yml` and `.github/workflows/release.yml` - -## Project Conventions - -### Code Style -- **Python**: Ruff for linting and formatting - - Line length: 88 characters - - Target: Python 3.10 - - Double quotes, space indentation - - Import sorting: isort rules via Ruff -- **Markdown**: Standard GitHub-Flavored Markdown -- **YAML/JSON**: Validated via pre-commit hooks - -### Architecture Patterns -- **Numbered directories** (01-09) for learning progression -- **Each feature folder** contains: - - Example files demonstrating the feature - - `README.md` with detailed explanations -- **Scripts directory** contains Python tooling: - - `build_epub.py` - Main EPUB builder with async Mermaid rendering - - `tests/` - pytest test suite - -### Testing Strategy -- **Unit tests** in `scripts/tests/` -- **Pytest** with `pytest-asyncio` for async code -- **CI runs tests** on every push/PR to `main` -- **Test coverage** focused on EPUB builder functionality - -### Git Workflow -- **Main branch**: `main` -- **PRs required** for contributions -- **Pre-commit hooks** enforce: - - Ruff lint and format - - Bandit security scan - - YAML/TOML validation - - Trailing whitespace and EOF fixes -- **Commit messages**: Descriptive, no co-author attribution required -- **No time estimates** in commits or PRs - -## Domain Context - -### Claude Code Concepts -This repository covers nine major Claude Code features: - -1. **Slash Commands** - User-invoked shortcuts (`/optimize`, `/pr`) -2. **Memory** - Persistent context via `CLAUDE.md` files -3. **Skills** - Auto-invoked reusable capabilities -4. **Subagents** - Specialized AI assistants with isolated contexts -5. **MCP Protocol** - External tool/API access -6. **Hooks** - Event-driven shell command automation -7. **Plugins** - Bundled feature collections -8. **Checkpoints** - Session snapshots and rewind -9. **Advanced Features** - Planning mode, extended thinking, background tasks - -### Installation Targets -Examples are designed to be copied to: -- `~/.claude/` - Personal/global configurations -- `.claude/` - Project-specific configurations -- Root project directory - For `CLAUDE.md` memory files - -## Important Constraints - -- **Python 3.10+** required for all scripts -- **Virtual environment** must be activated before running Python (configured in `~/.claude/CLAUDE.md`) -- **No Claude co-author** in commit messages (per user preferences) -- **No auto-commits/pushes** without explicit user request -- **Large files** limited to 1MB (pre-commit hook) -- **Security scans** must pass (Bandit) - -## External Dependencies - -### External Services -- **Mermaid.ink API** - Renders Mermaid diagrams to images for EPUB - - Used in `build_epub.py` with retry logic via `tenacity` - - Rate limiting handled with exponential backoff - -### GitHub Integration -- **GitHub Actions** for CI/CD -- **GitHub Releases** for versioned EPUB distribution -- Example MCP configurations reference GitHub API tokens - -### No Runtime External Dependencies -- Documentation is static markdown -- EPUB can be built offline (diagrams cached or skip rendering) diff --git a/openspec/specs/blog-post/spec.md b/openspec/specs/blog-post/spec.md deleted file mode 100644 index e2702b1..0000000 --- a/openspec/specs/blog-post/spec.md +++ /dev/null @@ -1,44 +0,0 @@ -# blog-post Specification - -## Purpose -TBD - created by archiving change add-blog-post-slash-commands. Update Purpose after archive. -## Requirements -### Requirement: Blog Post Directory Structure - -The project SHALL provide a `blog-post/` directory for hosting blog-style content that complements the reference documentation. - -#### Scenario: Blog post directory exists -- **WHEN** a user navigates to the project root -- **THEN** a `blog-post/` directory is present containing blog content - -### Requirement: Slash Commands Usage Blog Post - -The blog SHALL document 4 essential slash commands with practical usage guidance covering when, where, and how to use each command in a development workflow. - -#### Scenario: Complete command coverage -- **WHEN** a user reads the blog post -- **THEN** they find documentation for `/push-all`, `/setup-ci-cd`, `/doc-refactor`, and `/unit-test-expand` - -#### Scenario: Command file linking for long content -- **WHEN** a command file exceeds 30 lines -- **THEN** the blog SHALL provide a link to the full command file in the claude-howto project - -#### Scenario: Inline content for short commands -- **WHEN** a command file is 30 lines or fewer -- **THEN** the blog MAY include the command content inline - -### Requirement: Development Workflow Context - -Each command section SHALL explain when to use the command in the development lifecycle (POC, MVP, milestone phases). - -#### Scenario: Workflow phase guidance -- **WHEN** a user reads a command section -- **THEN** they understand which development phase the command is most appropriate for - -### Requirement: Reference to First Blog - -The blog post SHALL reference the introductory slash commands blog: "Discovering Claude Code Slash Commands" for foundational context. - -#### Scenario: Blog reference present -- **WHEN** a user reads the introduction -- **THEN** they find a link to the original slash commands blog post on Medium diff --git a/openspec/specs/cli-reference/spec.md b/openspec/specs/cli-reference/spec.md deleted file mode 100644 index f12508c..0000000 --- a/openspec/specs/cli-reference/spec.md +++ /dev/null @@ -1,102 +0,0 @@ -# cli-reference Specification - -## Purpose -TBD - created by archiving change add-cli-lesson. Update Purpose after archive. -## Requirements -### Requirement: CLI Reference Lesson - -The repository SHALL provide a comprehensive CLI reference lesson at `10-cli/` that documents all command-line interface options, flags, and usage patterns for Claude Code. - -#### Scenario: User learns CLI basics -- **WHEN** a user navigates to `10-cli/README.md` -- **THEN** they find an overview of CLI capabilities with architecture diagram -- **AND** a quick reference table of all CLI commands -- **AND** examples demonstrating common usage patterns - -#### Scenario: User looks up specific CLI flag -- **WHEN** a user needs to understand a specific CLI flag (e.g., `--output-format`) -- **THEN** they find the flag documented with description, options, and example usage -- **AND** related flags are cross-referenced - -#### Scenario: User integrates Claude Code in CI/CD -- **WHEN** a user wants to use Claude Code in automation -- **THEN** they find practical examples for CI/CD integration -- **AND** examples show headless mode, JSON output, and error handling - -### Requirement: CLI Commands Documentation - -The CLI lesson SHALL document all primary CLI commands with their syntax and use cases. - -#### Scenario: Interactive mode commands documented -- **WHEN** a user reads the CLI commands section -- **THEN** they find `claude` for starting interactive REPL -- **AND** `claude "query"` for starting with initial prompt -- **AND** `claude -c` for continuing recent conversation -- **AND** `claude -r` for resuming specific session - -#### Scenario: Print mode commands documented -- **WHEN** a user reads the print mode section -- **THEN** they find `claude -p "query"` for non-interactive queries -- **AND** pipe input examples like `cat file | claude -p "query"` -- **AND** output format options (text, json, stream-json) - -### Requirement: CLI Flags Documentation - -The CLI lesson SHALL document all CLI flags organized by category with examples. - -#### Scenario: Core flags documented -- **WHEN** a user reads the core flags section -- **THEN** they find `-p/--print`, `-c/--continue`, `-r/--resume`, `-v/--version` -- **AND** each flag has description and example usage - -#### Scenario: Model configuration flags documented -- **WHEN** a user reads the model configuration section -- **THEN** they find `--model`, `--fallback-model`, `--agent`, `--agents` -- **AND** examples show model selection and custom agent definitions - -#### Scenario: Permission flags documented -- **WHEN** a user reads the permission section -- **THEN** they find `--tools`, `--allowedTools`, `--disallowedTools` -- **AND** `--dangerously-skip-permissions`, `--permission-mode` -- **AND** examples demonstrate security-conscious configurations - -### Requirement: High-Value Use Cases - -The CLI lesson SHALL include practical use case examples that demonstrate real-world CLI value. - -#### Scenario: CI/CD integration example provided -- **WHEN** a user reads the CI/CD use case -- **THEN** they find a complete GitHub Actions or Jenkins example -- **AND** the example demonstrates headless mode with JSON output -- **AND** error handling and exit codes are explained - -#### Scenario: Script piping example provided -- **WHEN** a user reads the script piping use case -- **THEN** they find examples of piping file contents to Claude -- **AND** examples show log analysis, code review via pipe -- **AND** output processing patterns are demonstrated - -#### Scenario: Multi-session workflow example provided -- **WHEN** a user reads the session management use case -- **THEN** they find examples of resuming and forking sessions -- **AND** session naming and organization patterns are shown - -### Requirement: Navigation Integration - -The root documentation SHALL be updated to include the CLI lesson in all navigation elements. - -#### Scenario: CLI appears in Quick Navigation -- **WHEN** a user views the README Quick Navigation table -- **THEN** they see CLI Reference listed with link to `10-cli/` - -#### Scenario: CLI appears in Learning Path -- **WHEN** a user views the Learning Path table -- **THEN** they see CLI Reference at position 10 with appropriate difficulty and timing - -#### Scenario: CLI appears in Feature Comparison -- **WHEN** a user views the Feature Comparison table -- **THEN** CLI Reference is included with invocation, persistence, and use case columns - -#### Scenario: CLI appears in Directory Structure -- **WHEN** a user views the Directory Structure tree -- **THEN** `10-cli/` directory is shown with `README.md` diff --git a/openspec/specs/hooks-documentation/spec.md b/openspec/specs/hooks-documentation/spec.md deleted file mode 100644 index 640a9de..0000000 --- a/openspec/specs/hooks-documentation/spec.md +++ /dev/null @@ -1,146 +0,0 @@ -# hooks-documentation Specification - -## Purpose -TBD - created by archiving change update-hooks-lesson. Update Purpose after archive. -## Requirements -### Requirement: Hook Event Types Documentation -The hooks lesson SHALL document all 9 official hook events with their correct names, matchers, and behavior. - -#### Scenario: Complete hook event coverage -- **WHEN** a user reads the hooks lesson -- **THEN** they find documentation for PreToolUse, PermissionRequest, PostToolUse, Notification, UserPromptSubmit, Stop, SubagentStop, PreCompact, SessionStart, and SessionEnd events - -#### Scenario: No deprecated hook events -- **WHEN** a user searches for PreCommit, PostCommit, or PrePush hooks -- **THEN** they do not find these as they are not valid Claude Code hook events - -### Requirement: Hook Configuration Format -The hooks lesson SHALL document the correct array-based configuration format with matchers and hooks arrays. - -#### Scenario: Configuration structure -- **WHEN** a user views hook configuration examples -- **THEN** they see the structure: `{ "hooks": { "EventName": [{ "matcher": "Pattern", "hooks": [{ "type": "command", "command": "..." }] }] } }` - -#### Scenario: Matcher patterns -- **WHEN** a user needs to match specific tools -- **THEN** they find documentation for exact string matching, regex patterns, and wildcards - -### Requirement: Hook Input Documentation -The hooks lesson SHALL document the JSON stdin input that hooks receive. - -#### Scenario: JSON input structure -- **WHEN** a user writes a hook script -- **THEN** they understand the input includes session_id, transcript_path, cwd, permission_mode, hook_event_name, tool_name, tool_input, and tool_use_id - -#### Scenario: Event-specific input fields -- **WHEN** a user writes a hook for a specific event -- **THEN** they find documentation for event-specific input fields (e.g., stop_hook_active for Stop event) - -### Requirement: Hook Output Documentation -The hooks lesson SHALL document hook output semantics including exit codes and JSON stdout structure. - -#### Scenario: Exit code semantics -- **WHEN** a user implements a hook -- **THEN** they understand exit code 0 means success, exit code 2 means blocking error (stderr used as error message), and other codes mean non-blocking error - -#### Scenario: JSON output format -- **WHEN** a hook needs to control behavior -- **THEN** the user can output JSON with continue, stopReason, suppressOutput, systemMessage, and hookSpecificOutput fields - -#### Scenario: Event-specific output -- **WHEN** a user writes a PreToolUse hook -- **THEN** they can output permissionDecision (allow/deny/ask), permissionDecisionReason, and updatedInput - -### Requirement: Prompt-Based Hooks Documentation -The hooks lesson SHALL document type="prompt" hooks for LLM-based evaluation on Stop and SubagentStop events. - -#### Scenario: Prompt hook configuration -- **WHEN** a user wants intelligent stop evaluation -- **THEN** they find documentation for configuring type="prompt" hooks with prompt text and timeout - -#### Scenario: LLM response schema -- **WHEN** using prompt-based hooks -- **THEN** the user understands the expected response schema with decision (approve/block), reason, continue, stopReason, and systemMessage - -### Requirement: Environment Variables Documentation -The hooks lesson SHALL document all environment variables available to hooks. - -#### Scenario: Standard environment variables -- **WHEN** a user writes a hook script -- **THEN** they can use CLAUDE_PROJECT_DIR for the absolute project path - -#### Scenario: SessionStart environment persistence -- **WHEN** using SessionStart hooks -- **THEN** the user can persist environment variables via CLAUDE_ENV_FILE - -#### Scenario: Remote environment detection -- **WHEN** running in web environment -- **THEN** hooks can check CLAUDE_CODE_REMOTE to detect this - -### Requirement: Security Documentation -The hooks lesson SHALL include security considerations and best practices from the official documentation. - -#### Scenario: Security disclaimer -- **WHEN** a user reads about hooks -- **THEN** they see a clear disclaimer that hooks execute arbitrary shell commands at their own risk - -#### Scenario: Security best practices -- **WHEN** a user implements hooks -- **THEN** they find guidance on input validation, shell variable quoting, path traversal prevention, and sensitive file handling - -### Requirement: MCP Tool Hook Patterns -The hooks lesson SHALL document how to create hooks for MCP tools. - -#### Scenario: MCP tool matching -- **WHEN** a user wants to hook into MCP tool calls -- **THEN** they find documentation for the pattern `mcp____` and regex matching - -### Requirement: Plugin Hooks Documentation -The hooks lesson SHALL document how plugins can provide hooks. - -#### Scenario: Plugin hook configuration -- **WHEN** a plugin needs to provide hooks -- **THEN** documentation covers hooks/hooks.json structure and ${CLAUDE_PLUGIN_ROOT} variable - -### Requirement: Debugging Documentation -The hooks lesson SHALL document how to debug hook execution. - -#### Scenario: Debug mode -- **WHEN** hooks are not working as expected -- **THEN** users can enable `claude --debug` for detailed hook execution logs - -#### Scenario: Verbose mode -- **WHEN** using Claude Code interactively -- **THEN** users can enable verbose mode (ctrl+o) to see hook execution progress - -### Requirement: Working Example Scripts -The hooks lesson SHALL provide working example scripts that use JSON stdin input. - -#### Scenario: Bash command validator -- **WHEN** a user wants to validate bash commands -- **THEN** they find a working Python script that reads JSON stdin and validates commands - -#### Scenario: Intelligent stop hook -- **WHEN** a user wants automatic task completion verification -- **THEN** they find a working prompt-based stop hook example - -### Requirement: Context Usage Reporting Hook Example -The hooks lesson SHALL include a correct, working example showing how to create a hook that reports context/token usage after each Claude response. - -#### Scenario: Token calculation is correct -- **WHEN** a user copies the context-usage.py example -- **AND** runs it as a Stop hook -- **THEN** the hook correctly calculates estimated tokens from total character count -- **AND** displays a non-zero token count proportional to conversation length - -#### Scenario: User learns to create context monitoring hook -- **WHEN** a user reads the context usage reporter example -- **THEN** they find a complete Python script that reads the transcript file -- **AND** they understand how to estimate token usage from conversation history -- **AND** they see the configuration for Stop hooks -- **AND** they understand the limitations of token estimation - -#### Scenario: Hook output format is documented -- **WHEN** a user implements the context usage hook -- **THEN** they can generate a one-line report showing used tokens and remaining capacity -- **AND** the output shows realistic token counts based on conversation size diff --git a/openspec/specs/skills-lesson/spec.md b/openspec/specs/skills-lesson/spec.md deleted file mode 100644 index 6e12f5a..0000000 --- a/openspec/specs/skills-lesson/spec.md +++ /dev/null @@ -1,67 +0,0 @@ -# skills-lesson Specification - -## Purpose -TBD - created by archiving change update-skills-lesson. Update Purpose after archive. -## Requirements -### Requirement: Managing Skills Documentation -The skills lesson SHALL provide comprehensive guidance for managing skills including viewing available skills, testing skills, updating skills with restart requirements, and removing skills. - -#### Scenario: User wants to view available skills -- **WHEN** a user wants to see what skills are available -- **THEN** the documentation provides both CLI method (asking Claude "What Skills are available?") and filesystem method (ls ~/.claude/skills/ and ls .claude/skills/) - -#### Scenario: User wants to test a skill -- **WHEN** a user wants to test if their skill works -- **THEN** the documentation explains that skills activate automatically based on matching descriptions, with example test queries - -#### Scenario: User wants to update a skill -- **WHEN** a user modifies a SKILL.md file -- **THEN** the documentation explains that changes take effect on next Claude Code startup and restart is required if already running - -#### Scenario: User wants to remove a skill -- **WHEN** a user wants to remove a skill -- **THEN** the documentation provides rm -rf commands for both personal and project skills, with git commit for project skills - -### Requirement: Enhanced Debugging Guidance -The skills lesson SHALL provide detailed debugging guidance for common skill issues including skipped skills, YAML errors, script permissions, and path formats. - -#### Scenario: Skill not being discovered -- **WHEN** Claude doesn't use a user's skill -- **THEN** the documentation explains to check: description specificity, YAML syntax validity (opening/closing ---, no tabs), and correct file path location - -#### Scenario: Skill has errors -- **WHEN** a skill has runtime errors -- **THEN** the documentation explains to check: dependency installation, script execute permissions (chmod +x), and forward slash usage in paths - -#### Scenario: Multiple skills conflict -- **WHEN** multiple skills are activated unexpectedly -- **THEN** the documentation explains using distinct trigger terms in descriptions to help Claude choose the right skill - -### Requirement: Version History Documentation -The skills lesson SHALL include a best practice example for documenting skill version history in SKILL.md files. - -#### Scenario: User wants to track skill versions -- **WHEN** a user maintains a skill over time -- **THEN** the documentation provides a version history markdown template with date and description format - -### Requirement: Enhanced Tool Access Control Documentation -The skills lesson SHALL provide expanded documentation for the allowed-tools feature including use cases, security examples, and behavior when not specified. - -#### Scenario: User wants a read-only skill -- **WHEN** a user wants to create a skill that cannot modify files -- **THEN** the documentation provides an example with allowed-tools: Read, Grep, Glob - -#### Scenario: User wants security-sensitive workflow -- **WHEN** a user has a security-sensitive skill -- **THEN** the documentation explains how allowed-tools restricts Claude's capabilities within that skill context - -#### Scenario: allowed-tools not specified -- **WHEN** a user doesn't specify allowed-tools -- **THEN** the documentation explains that Claude will ask for permission as normal - -### Requirement: Multi-File Skill Example -The skills lesson SHALL include a comprehensive example of a multi-file skill showing directory structure with multiple reference files, scripts, and templates. - -#### Scenario: User wants to create complex skill -- **WHEN** a user needs a skill with supporting files -- **THEN** the documentation provides a complete directory structure example showing SKILL.md, reference files (FORMS.md, REFERENCE.md), scripts subdirectory, and progressive disclosure explanation diff --git a/openspec/specs/slash-commands/spec.md b/openspec/specs/slash-commands/spec.md deleted file mode 100644 index eee8233..0000000 --- a/openspec/specs/slash-commands/spec.md +++ /dev/null @@ -1,150 +0,0 @@ -# slash-commands Specification - -## Purpose -TBD - created by archiving change update-slash-commands-session. Update Purpose after archive. -## Requirements -### Requirement: Slash Command Types Documentation - -The documentation SHALL describe the four types of slash commands: -1. Built-in commands provided by Claude Code -2. Custom user-defined commands (project and personal) -3. Plugin commands -4. MCP (Model Context Protocol) slash commands - -#### Scenario: User learns about command types -- **WHEN** a user reads the slash commands documentation -- **THEN** they understand the different types of slash commands available -- **AND** they know when to use each type - ---- - -### Requirement: Built-in Commands Reference - -The documentation SHALL include a comprehensive reference table of all built-in slash commands with their purposes, including but not limited to: -- `/add-dir` - Add additional working directories -- `/agents` - Manage custom AI subagents -- `/clear` - Clear conversation history -- `/compact` - Compact conversation with optional focus instructions -- `/config` - Open Settings interface -- `/context` - Visualize current context usage -- `/cost` - Show token usage statistics -- `/doctor` - Check installation health -- `/export` - Export conversation to file or clipboard -- `/help` - Get usage help -- `/hooks` - Manage hook configurations -- `/init` - Initialize project with CLAUDE.md -- `/mcp` - Manage MCP server connections -- `/memory` - Edit CLAUDE.md memory files -- `/model` - Select or change AI model -- `/permissions` - View or update permissions -- `/resume` - Resume conversation by ID or name -- `/review` - Request code review -- `/sandbox` - Enable sandboxed bash tool -- `/vim` - Enter vim mode - -#### Scenario: User finds built-in command -- **WHEN** a user needs to perform a common operation -- **THEN** they can find the appropriate built-in command in the reference table -- **AND** they understand what the command does - ---- - -### Requirement: Argument Handling - -The documentation SHALL explain both argument handling methods: -1. `$ARGUMENTS` - Receives all arguments as a single string -2. `$1`, `$2`, `$3`, etc. - Individual positional arguments - -#### Scenario: User uses $ARGUMENTS placeholder -- **WHEN** a user creates a command with `$ARGUMENTS` placeholder -- **AND** invokes it with `/fix-issue 123 high-priority` -- **THEN** `$ARGUMENTS` contains "123 high-priority" - -#### Scenario: User uses positional arguments -- **WHEN** a user creates a command with `$1`, `$2`, `$3` placeholders -- **AND** invokes it with `/review-pr 456 high alice` -- **THEN** `$1` is "456", `$2` is "high", `$3` is "alice" - ---- - -### Requirement: Bash Command Execution - -The documentation SHALL explain the `!` prefix for executing bash commands within slash command files before the command runs. - -#### Scenario: User includes dynamic context -- **WHEN** a user adds `!git status` in their command file -- **THEN** the git status output is included in the command context -- **AND** Claude receives the current repository state - ---- - -### Requirement: File Reference Syntax - -The documentation SHALL explain the `@` prefix for including file contents in slash commands. - -#### Scenario: User references a file -- **WHEN** a user adds `@src/utils/helpers.js` in their command file -- **THEN** the contents of that file are included in the command context - ---- - -### Requirement: Frontmatter Fields - -The documentation SHALL document all supported frontmatter fields: -- `allowed-tools` - List of tools the command can use -- `argument-hint` - Expected arguments for auto-completion -- `description` - Brief description of the command -- `model` - Specific model to use for this command -- `disable-model-invocation` - Prevent SlashCommand tool from calling this command - -#### Scenario: User creates command with frontmatter -- **WHEN** a user creates a command with frontmatter fields -- **THEN** Claude Code respects those configuration options -- **AND** the command behaves according to the specified settings - ---- - -### Requirement: Plugin Commands Documentation - -The documentation SHALL explain the plugin command format: `/plugin-name:command-name` or simply `/command-name` when there are no naming conflicts. - -#### Scenario: User invokes plugin command -- **WHEN** a user types `/frontend-design:frontend-design` -- **THEN** the corresponding plugin command executes - ---- - -### Requirement: MCP Slash Commands Documentation - -The documentation SHALL explain the MCP slash command format: `/mcp____ [arguments]` - -#### Scenario: User invokes MCP command -- **WHEN** a user types `/mcp__github__list_prs` -- **THEN** the MCP server's prompt is executed - ---- - -### Requirement: SlashCommand Tool Documentation - -The documentation SHALL explain how Claude can programmatically invoke slash commands using the SlashCommand tool, including: -- How to enable this via prompt or CLAUDE.md references -- How to disable via permissions -- The character budget limit (default 15,000, configurable via `SLASH_COMMAND_TOOL_CHAR_BUDGET`) - -#### Scenario: User enables programmatic invocation -- **WHEN** a user adds "Run /write-unit-test when writing tests" to CLAUDE.md -- **THEN** Claude can automatically invoke that command when appropriate - ---- - -### Requirement: Skills vs Slash Commands Comparison - -The documentation SHALL include a comparison table helping users choose between Skills and Slash Commands based on: -- Best use cases for each -- File structure differences -- Invocation method (explicit vs automatic) -- Complexity level - -#### Scenario: User decides between skill and command -- **WHEN** a user needs to create a reusable capability -- **THEN** they can use the comparison to decide whether a slash command or skill is more appropriate diff --git a/openspec/specs/subagents-lesson/spec.md b/openspec/specs/subagents-lesson/spec.md deleted file mode 100644 index eb60257..0000000 --- a/openspec/specs/subagents-lesson/spec.md +++ /dev/null @@ -1,40 +0,0 @@ -# subagents-lesson Specification - -## Purpose -TBD - created by archiving change update-subagents-lesson. Update Purpose after archive. -## Requirements -### Requirement: Example Subagent - Debugger - -The lesson MUST include a debugger subagent example. - -#### Scenario: User needs debugging specialist -- **Given**: A user wants a debugging-focused subagent -- **When**: They view the examples -- **Then**: They find a complete debugger.md example with root cause analysis approach - -### Requirement: Example Subagent - Data Scientist - -The lesson MUST include a data scientist subagent example. - -#### Scenario: User needs data analysis specialist -- **Given**: A user wants a data analysis subagent -- **When**: They view the examples -- **Then**: They find a complete data-scientist.md example with SQL/BigQuery focus - -### Requirement: File Location Documentation - -The lesson MUST document where subagent files can be stored. - -#### Scenario: User learns storage locations -- **Given**: A user wants to know where to put subagent files -- **When**: They read the file locations section -- **Then**: They learn about project (.claude/agents/), user (~/.claude/agents/), plugin, and CLI locations with priority order - -### Requirement: Proactive Invocation Guidance - -The lesson MUST explain how to encourage automatic subagent use. - -#### Scenario: User wants subagent used automatically -- **Given**: A user wants Claude to proactively use their subagent -- **When**: They read the usage section -- **Then**: They learn to include "use PROACTIVELY" or "MUST BE USED" in the description field