A visual, example-driven guide to Claude Code — from basic concepts to advanced agents, with copy-paste templates that bring immediate value.
fix: correct token calculation in context-usage hook example
Luong NGUYEN513171332e20
diff --git a/06-hooks/README.md b/06-hooks/README.mdindex 1666ad0..a2823f2 100644--- a/06-hooks/README.md+++ b/06-hooks/README.md@@ -516,10 +516,6 @@ MODEL_LIMITS = {"haiku": 200000,}-def estimate_tokens(text: str) -> int:- """Estimate token count from text. ~4 characters per token on average."""- return len(text) // 4-def read_transcript(transcript_path: str) -> list:"""Read JSONL transcript file and return list of messages."""messages = []@@ -561,7 +557,7 @@ def calculate_usage(messages: list) -> tuple[int, int]:if tool_input:total_chars += len(json.dumps(tool_input))- estimated_tokens = estimate_tokens(str(total_chars))+ estimated_tokens = total_chars // 4 # ~4 characters per tokenreturn total_chars, estimated_tokensdef main():diff --git a/openspec/changes/add-cli-lesson/proposal.md b/openspec/changes/archive/2025-12-24-add-cli-lesson/proposal.mdsimilarity index 100%rename from openspec/changes/add-cli-lesson/proposal.mdrename to openspec/changes/archive/2025-12-24-add-cli-lesson/proposal.mddiff --git a/openspec/changes/add-cli-lesson/specs/cli-reference/spec.md b/openspec/changes/archive/2025-12-24-add-cli-lesson/specs/cli-reference/spec.mdsimilarity index 100%rename from openspec/changes/add-cli-lesson/specs/cli-reference/spec.mdrename to openspec/changes/archive/2025-12-24-add-cli-lesson/specs/cli-reference/spec.mddiff --git a/openspec/changes/add-cli-lesson/tasks.md b/openspec/changes/archive/2025-12-24-add-cli-lesson/tasks.mdsimilarity index 100%rename from openspec/changes/add-cli-lesson/tasks.mdrename to openspec/changes/archive/2025-12-24-add-cli-lesson/tasks.mddiff --git a/openspec/changes/fix-context-usage-hook/proposal.md b/openspec/changes/archive/2025-12-24-fix-context-usage-hook/proposal.mdsimilarity index 100%rename from openspec/changes/fix-context-usage-hook/proposal.mdrename to openspec/changes/archive/2025-12-24-fix-context-usage-hook/proposal.mddiff --git a/openspec/changes/fix-context-usage-hook/specs/hooks-documentation/spec.md b/openspec/changes/archive/2025-12-24-fix-context-usage-hook/specs/hooks-documentation/spec.mdsimilarity index 100%rename from openspec/changes/fix-context-usage-hook/specs/hooks-documentation/spec.mdrename to openspec/changes/archive/2025-12-24-fix-context-usage-hook/specs/hooks-documentation/spec.mddiff --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.mdnew file mode 100644index 0000000..c2b074a--- /dev/null+++ b/openspec/changes/archive/2025-12-24-fix-context-usage-hook/tasks.md@@ -0,0 +1,20 @@+# 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 implementationdiff --git a/openspec/changes/fix-context-usage-hook/tasks.md b/openspec/changes/fix-context-usage-hook/tasks.mddeleted file mode 100644index 6b1cf18..0000000--- a/openspec/changes/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-- [ ] Update line 564 in the context-usage.py example: change `estimate_tokens(str(total_chars))` to `total_chars // 4`-- [ ] Remove the now-unused `estimate_tokens()` function from the example--### 2. Update user's local hook file-- [ ] Fix `~/.claude/hooks/context-usage.py` with the same correction--### 3. Verification-- [ ] Test the hook by running Claude Code and confirming non-zero token count is displayed-- [ ] Verify the percentage calculation is reasonable (should show usage increasing during conversation)--## Acceptance Criteria--- [ ] After Claude responds, the Stop hook displays a non-zero token estimate-- [ ] The displayed percentage decreases as conversation grows-- [ ] Example in README.md matches the corrected implementationdiff --git a/openspec/specs/cli-reference/spec.md b/openspec/specs/cli-reference/spec.mdnew file mode 100644index 0000000..f12508c--- /dev/null+++ b/openspec/specs/cli-reference/spec.md@@ -0,0 +1,102 @@+# 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.mdindex 949c5da..640a9de 100644--- a/openspec/specs/hooks-documentation/spec.md+++ b/openspec/specs/hooks-documentation/spec.md@@ -125,16 +125,22 @@ The hooks lesson SHALL provide working example scripts that use JSON stdin input- **THEN** they find a working prompt-based stop hook example### 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.+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 UserPromptSubmit or Stop hooks+- **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** they understand the report is an estimate based on transcript analysis+- **AND** the output shows realistic token counts based on conversation size