fix: correct token calculation in context-usage hook example

The hook was converting total_chars to string before calculating tokens,
resulting in ~0 tokens reported. Fixed to calculate directly from char count.

- Remove unused estimate_tokens() function
- Calculate tokens as total_chars // 4 directly
- Archive fix-context-usage-hook change
This commit is contained in:
Luong NGUYEN
2025-12-24 23:54:35 +01:00
parent ecd3dba49a
commit 513171332e
10 changed files with 132 additions and 28 deletions

View File

@@ -0,0 +1,41 @@
# 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`

View File

@@ -0,0 +1,99 @@
## 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`

View File

@@ -0,0 +1,50 @@
# 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

View File

@@ -0,0 +1,44 @@
# 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

View File

@@ -0,0 +1,24 @@
# 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

View File

@@ -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 implementation