Skip to content

Commit 762207d

Browse files
barkainclaude
andcommitted
Token optimization: reduce plugin overhead by 55% (20K→9K tokens)
## Conditional Orchestrator Injection - SessionStart injects 40-line routing stub (~200 tokens) instead of full 545-line orchestrator (~5.5K tokens) - Full orchestrator loads on-demand via /delegate command only - Sessions that don't use multi-step delegation save ~5K tokens ## Prompt Compression - Orchestrator slimmed 49% (1065→545 lines) - /delegate template compressed 89% (4955→555 chars) - Agent definitions deduplicated 47% (640→339 lines) - Delegation error messages compressed 57%, no emoji ## Token Efficiency Enhancements - DONE|{path} return format enforced in all 8 agent definitions - Partial file read guidance (offset/limit for >200 lines) - cd && command pattern handling in rewrite hook - Added eslint, next lint, tsc to output compression - Conversation filler reduction rules in output style ## Agent Teams as Default - Team mode detection via TeamCreate tool availability (not Bash env check) - Mandatory TeamCreate + Agent(team_name=...) when teams available - Isolated subagents only as fallback when TeamCreate fails - Team check is FIRST ACTION before any planning ## Cleanup - Deleted deprecated task-planner skill (-622 lines) - Planning exclusively via native EnterPlanMode - Updated all documentation (CLAUDE.md, README.md, docs/) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent 1768e0f commit 762207d

25 files changed

Lines changed: 1075 additions & 1881 deletions

CLAUDE.md

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -46,15 +46,14 @@ uvx ruff format . # Format code (auto-fix)
4646
uvx ruff check --no-fix . # Lint code (check only)
4747
uvx pyright . # Type checking
4848
uvx deadcode hooks/ scripts/ # Dead code detection
49-
uvx pytest tests/ -v # Run test suite
5049
```
5150

5251
The PostToolUse hook enforces a specific ruff rule subset on edited Python files:
5352
```bash
5453
uvx ruff check --select F,E711,E712,UP006,UP007,UP035,UP037,T201,S <file>
5554
```
5655

57-
Test suite exists in `tests/` with comprehensive coverage for hooks and token efficiency features.
56+
CI workflow exists (`.github/workflows/ci.yml`) but tests are currently disabled/placeholder.
5857

5958
---
6059

@@ -80,6 +79,8 @@ In plugin mode, agent/skill names use prefix `workflow-orchestrator:` (e.g., `wo
8079

8180
### Execution Flow
8281

82+
**Token overhead:** System prompt (~11K tokens: orchestrator + CLAUDE.md + efficiency guidance) + per-agent delegation (~350 tokens)
83+
8384
```
8485
User prompt
8586
→ UserPromptSubmit hook (clear state, record turn timestamp, clear team state)
@@ -106,11 +107,11 @@ User prompt
106107
→ Stop hook: calculate turn duration, quality analysis
107108
```
108109

109-
### Hook System (6 lifecycle events, 15 scripts)
110+
### Hook System (6 lifecycle events, 12 scripts)
110111

111112
| Event | Scripts | Purpose |
112113
|-------|---------|---------|
113-
| **PreToolUse** (`*`, `Bash`) | `require_delegation.py`, `validate_task_graph_compliance.py`, `token_rewrite_hook.py` | Block non-allowed tools; validate Agent/Task invocations against active task graph; rewrite Bash commands for token efficiency |
114+
| **PreToolUse** (`*`, `Bash`) | `require_delegation.py`, `validate_task_graph_compliance.py`, `token_rewrite_hook.py` | Block non-allowed tools (compressed error messages); validate Agent/Task invocations against active task graph; rewrite Bash commands for token efficiency |
114115
| **PostToolUse** | `python_posttooluse_hook.py` (Edit/Write/MultiEdit), `remind_skill_continuation.py` (ExitPlanMode\|Skill\|SlashCommand), `validate_task_graph_depth.py` + `remind_todo_after_task.py` (Agent/Task) | Python validation (Ruff, Pyright, security), workflow continuation state (triggers on ExitPlanMode for plan mode flows), depth-3 enforcement, task reminders |
115116
| **UserPromptSubmit** | `clear-delegation-sessions.py` | Clear delegation state, record turn start timestamp, clear team state (`team_mode_active`, `team_config.json`), rotate logs |
116117
| **SessionStart** (`startup\|resume\|clear\|compact`) | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject system prompt + output style + token efficiency guidance |
@@ -144,7 +145,6 @@ Special cases:
144145

145146
### Skills (forked context)
146147

147-
- **task-planner** (`skills/task-planner/SKILL.md`): Legacy planning skill, retained for reference/backward compatibility. The core planning logic (complexity scoring, tier classification, agent assignment, wave scheduling, task creation) has been absorbed into `system-prompts/workflow_orchestrator.md` and now executes as native plan mode (EnterPlanMode/ExitPlanMode) directly in the main agent context rather than a forked skill context.
148148
- **breadth-reader** (`skills/breadth-reader/SKILL.md`): Lightweight read-only breadth tasks. Spawns `Explore` subagents (Haiku). Returns summary only.
149149

150150
### Specialized Agents (8)
@@ -191,7 +191,10 @@ Two team workflow patterns:
191191

192192
Agent selection uses keyword matching (≥2 matches threshold, highest count wins). Falls back to general-purpose if 0-1 matches. See `system-prompts/workflow_orchestrator.md` for keyword lists.
193193

194-
Agent config format: YAML frontmatter (`name`, `description`, optional `tools`/`model`/`color`) + markdown system prompt body. All agents enforce `DONE|{output_file}` return format.
194+
Agent config format: YAML frontmatter (`name`, `description`, optional `tools`/`model`/`color`) + markdown system prompt body. All agents enforce `DONE|{output_file}` return format. Custom agent instructions include:
195+
- Return format must be exactly `DONE|{output_file_path}` (no summaries or explanations)
196+
- Write directly to output file using Write tool (do not delegate writing)
197+
- If Write is blocked, report error and stop (do not retry)
195198

196199
### State Files (Runtime)
197200

@@ -252,9 +255,11 @@ Agent config format: YAML frontmatter (`name`, `description`, optional `tools`/`
252255

253256
Minimize command output to reduce context consumption. Enabled by default (`CLAUDE_TOKEN_EFFICIENCY=1`).
254257

255-
**Two-layer approach:**
258+
**Multi-layer approach:**
256259
1. **Behavioral guidance** (`system-prompts/token_efficient_cli.md`): Injected via SessionStart, teaches compact flag usage (e.g., `git status -sb`, `pytest -q --tb=short`)
257260
2. **Output compression** (`hooks/compact_run.py`): PreToolUse hook rewrites matching Bash commands through `compact_run.py`, which compresses git/test/log output post-execution
261+
3. **Partial file reads**: Use Read tool with `offset` and `limit` parameters for files >200 lines to avoid loading entire file contents into context
262+
4. **Compressed error messages**: Delegation error messages are optimized for minimal token consumption
258263

259264
**Supported command families:** git (push/pull/commit/etc), pytest, cargo test, npm/pnpm/yarn/bun test, npx (vitest/jest/mocha/playwright), go test, make test/check, docker/kubectl logs
260265

README.md

Lines changed: 17 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -252,14 +252,14 @@ The `plugin-hooks.json` configures the delegation enforcement hooks using cross-
252252

253253
**Note:** All hooks use `uv run --no-project --script` for cross-platform compatibility (Windows, macOS, Linux). The `--no-project` flag allows execution without requiring a pyproject.toml, and `--script` directly runs Python scripts using uv's managed interpreter.
254254

255-
**Hook Events (6 lifecycle points, 15 scripts):**
255+
**Hook Events (6 lifecycle points, 14 hooks):**
256256

257257
| Event | Scripts | Purpose |
258258
|-------|---------|---------|
259-
| **PreToolUse** | `validate_task_graph_compliance.py`, `require_delegation.py`, `token_rewrite_hook.py` (Bash only) | Validate task graph compliance; block non-delegated tools; rewrite Bash commands for token efficiency |
259+
| **PreToolUse** | `validate_task_graph_compliance.py`, `require_delegation.py`, `token_rewrite_hook.py` (Bash only) | Validate task graph compliance; block non-delegated tools; rewrite Bash commands for token efficiency (cd && pattern, eslint, next, tsc support) |
260260
| **PostToolUse** | `python_posttooluse_hook.py` (Edit/Write), `remind_skill_continuation.py` (ExitPlanMode/Skill/SlashCommand), `validate_task_graph_depth.py` (Agent/Task), `remind_todo_after_task.py` (Agent/Task, async) | Python validation (Ruff/Pyright); workflow continuation state; depth-3 enforcement; task reminders |
261261
| **UserPromptSubmit** | `clear-delegation-sessions.py` | Clear delegation/team state, record turn timestamp |
262-
| **SessionStart** | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject system prompts (workflow orchestration, output style, token efficiency) |
262+
| **SessionStart** | `inject_workflow_orchestrator.py`, `inject-output-style.py`, `inject_token_efficiency.py` | Inject conditional orchestrator (stub on startup, full on /delegate), output style, token efficiency guidance |
263263
| **SubagentStop** | `remind_todo_update.py` (async), `trigger_verification.py` | Remind to update tasks, suggest verification |
264264
| **Stop** | `python_stop_hook.py` | Turn duration tracking, workflow continuation |
265265

@@ -268,22 +268,10 @@ The `plugin-hooks.json` configures the delegation enforcement hooks using cross-
268268
Multi-step workflow orchestration requires the workflow_orchestrator system prompt to be appended:
269269

270270
**Automatic (via SessionStart hook):**
271-
```json
272-
{
273-
"hooks": {
274-
"SessionStart": [
275-
{
276-
"hooks": [
277-
{
278-
"type": "append_system_prompt",
279-
"path": "system-prompts/workflow_orchestrator.md"
280-
}
281-
]
282-
}
283-
]
284-
}
285-
}
286-
```
271+
272+
The `inject_workflow_orchestrator.py` hook uses conditional injection:
273+
- **On startup/resume:** Injects a lightweight stub that registers `/delegate` and `/bypass` commands without loading the full orchestrator prompt, keeping baseline token overhead minimal.
274+
- **On `/delegate` invocation:** The full `workflow_orchestrator.md` system prompt is loaded on-demand, providing the complete planning and execution logic only when needed.
287275

288276
**What this enables:**
289277
- Multi-step task detection via pattern matching
@@ -415,7 +403,7 @@ No other configuration is required. Plan mode automatically evaluates whether a
415403

416404
### How Mode Selection Works
417405

418-
During planning, plan mode calculates a `team_mode_score` based on task characteristics:
406+
During planning, plan mode checks if the TeamCreate tool is available (indicator that Agent Teams are enabled). If available, it calculates a `team_mode_score` based on task characteristics:
419407

420408
| Factor | Points | Condition |
421409
|---------------------------------------|--------|--------------------------------------------------------|
@@ -428,7 +416,7 @@ During planning, plan mode calculates a `team_mode_score` based on task characte
428416
| Breadth task | -5 | Simple exploration is better as subagents |
429417
| Phase count <= 3 | -3 | Small workflows don't need team overhead |
430418

431-
A score of **5 or higher** (with `CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1`) triggers team mode. Otherwise, subagent mode is used.
419+
Default to team mode when Agent Teams available (TeamCreate in tools). Falls back to subagent only when `team_mode_score <= -3` (breadth-only tasks). If TeamCreate tool is not available (env var not set), subagent mode is always selected.
432420

433421
### Subagent Mode vs Team Mode
434422

@@ -503,7 +491,7 @@ Team mode creates two additional state files (automatically cleaned up on comple
503491

504492
The framework minimizes command output to reduce context consumption and preserve tokens for meaningful work. Token efficiency is enabled by default (`CLAUDE_TOKEN_EFFICIENCY=1`).
505493

506-
### Two-Layer Approach
494+
### Multi-Layer Approach
507495

508496
1. **Behavioral Guidance** — The `token_efficient_cli.md` system prompt (injected via SessionStart) teaches compact flag usage:
509497
- `git status -sb` (short branch format)
@@ -515,6 +503,13 @@ The framework minimizes command output to reduce context consumption and preserv
515503
- Git: `push`, `pull`, `commit`, `merge`, `rebase`, `status`, etc.
516504
- Test runners: `pytest`, `cargo test`, `npm/pnpm/yarn/bun test`, `vitest`, `jest`, `mocha`, etc.
517505
- Logs: `docker logs`, `kubectl logs`, `make` output
506+
- Build tools: `eslint`, `next`, `tsc`
507+
- Command chaining: `cd && command` pattern support
508+
509+
3. **Conditional System Prompt Injection** — The orchestrator is injected conditionally:
510+
- On session startup: Stub version (~200 tokens) provides minimal direction
511+
- On first plan mode entry (via /delegate or detected multi-step): Full version (~11K tokens) for complete planning capability
512+
- Saves tokens for single-step and read-only tasks
518513

519514
### Disable Token Efficiency
520515

agents/code-cleanup-optimizer.md

Lines changed: 8 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -3,23 +3,10 @@ name: code-cleanup-optimizer
33
description: Remove technical debt, improve quality, eliminate redundancy after implementation is verified. Never use before functionality works correctly.
44
---
55

6-
## RETURN FORMAT (CRITICAL - READ FIRST)
6+
## RETURN FORMAT (CRITICAL)
77

8-
**Your response to the main agent must be EXACTLY:**
9-
```
10-
DONE|{output_file_path}
11-
```
12-
13-
**Example:** `DONE|$CLAUDE_SCRATCHPAD_DIR/cleanup_utils_module.md`
14-
15-
**WHY:** Main agent context is limited. Full findings go in the file. Return value only confirms completion + path.
16-
17-
**PROHIBITED in return value:**
18-
- Summaries
19-
- Findings
20-
- Recommendations
21-
- Explanations
22-
- Anything except `DONE|{path}`
8+
Return EXACTLY: `DONE|{output_file_path}` — nothing else. Example: `DONE|$CLAUDE_SCRATCHPAD_DIR/cleanup_utils_module.md`
9+
All findings go in the output file. No summaries, explanations, or text beyond `DONE|{path}` in return value.
2310

2411
---
2512

@@ -42,32 +29,11 @@ Explain why changes improve the code. Distinguish critical improvements from nic
4229

4330
## COMMUNICATION MODE
4431

45-
**If operating as a teammate in an Agent Team** (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1):
46-
- Write detailed output to the output_file path as usual
47-
- Send a brief completion message to the team: "Completed: {subject}. Output at {output_file}."
48-
- If you need clarification from another teammate, message them directly
49-
- If you discover issues that affect another teammate's work, message them proactively
50-
- NEVER call TeamCreate -- only the lead agent creates teams (no nested teams)
51-
- Before writing to a file another teammate might also modify, coordinate via SendMessage first
52-
53-
**If operating as a subagent (Agent tool):**
54-
- Return EXACTLY: `DONE|{output_file_path}`
55-
- No summaries, no explanations -- only the path
32+
**Teammate mode** (Agent Teams): Write output to file, send brief completion message via SendMessage. Message teammates directly for clarification or cross-cutting issues. Never call TeamCreate.
33+
**Subagent mode**: Return EXACTLY `DONE|{output_file_path}`, nothing else.
5634

57-
---
58-
59-
## CLI Efficiency (MANDATORY)
60-
61-
Use compact CLI flags to minimize output tokens:
62-
- Git: `--quiet` on push/pull/commit, `-sb` on status, `--oneline -n 10` on log, `--stat` on diff
63-
- Tests: `pytest -q --tb=short --no-header`, `npm test -- --silent`
64-
- Ruff: ALWAYS `ruff check --output-format concise --quiet`, NEVER bare `ruff check`
65-
- Files: `ls -1` not `ls -la`, `head -50` not `cat`, `wc -l` before reading
66-
- Search: `rg -l` for file list, `rg -m 5` to cap matches, scope to directories
67-
- Always: `| head -N` when output may exceed 50 lines, `--no-pager` on git
35+
## CLI Efficiency
36+
Follow MANDATORY compact CLI rules: git `-sb`/`--quiet`/`--oneline -n 10`, ruff `--output-format concise --quiet`, pytest `-q --tb=short`, `ls -1`, `head -50` not `cat`, `rg -l`/`-m 5`, `| head -N` for >50 lines. Read: `offset`/`limit` for files >200 lines; grep-then-partial-read for CLAUDE.md.
6837

6938
## FILE WRITING
70-
71-
- You HAVE Write tool access for the scratchpad directory ($CLAUDE_SCRATCHPAD_DIR)
72-
- Write directly to the output_file path - do NOT delegate writing
73-
- If Write is blocked, report error and stop (do not loop)
39+
Write to $CLAUDE_SCRATCHPAD_DIR output_file path directly. If Write blocked, report error and stop.

agents/code-reviewer.md

Lines changed: 8 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -6,23 +6,10 @@ color: red
66
activation_keywords: ["review code", "code review", "check implementation", "validate function", "review this", "best practices", "code quality", "refactor review", "implementation review"]
77
---
88

9-
## RETURN FORMAT (CRITICAL - READ FIRST)
9+
## RETURN FORMAT (CRITICAL)
1010

11-
**Your response to the main agent must be EXACTLY:**
12-
```
13-
DONE|{output_file_path}
14-
```
15-
16-
**Example:** `DONE|$CLAUDE_SCRATCHPAD_DIR/review_code.md`
17-
18-
**WHY:** Main agent context is limited. Full findings go in the file. Return value only confirms completion + path.
19-
20-
**PROHIBITED in return value:**
21-
- Summaries
22-
- Findings
23-
- Recommendations
24-
- Explanations
25-
- Anything except `DONE|{path}`
11+
Return EXACTLY: `DONE|{output_file_path}` — nothing else. Example: `DONE|$CLAUDE_SCRATCHPAD_DIR/review_code.md`
12+
All findings go in the output file. No summaries, explanations, or text beyond `DONE|{path}` in return value.
2613

2714
---
2815

@@ -38,30 +25,11 @@ Provide specific, actionable feedback explaining the 'why' behind recommendation
3825

3926
## COMMUNICATION MODE
4027

41-
**If operating as a teammate in an Agent Team** (CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1):
42-
- Write detailed output to the output_file path as usual
43-
- Send a brief completion message to the team: "Completed: {subject}. Output at {output_file}."
44-
- If you need clarification from another teammate, message them directly
45-
- If you discover issues that affect another teammate's work, message them proactively
46-
- NEVER call TeamCreate -- only the lead agent creates teams (no nested teams)
47-
- Before writing to a file another teammate might also modify, coordinate via SendMessage first
28+
**Teammate mode** (Agent Teams): Write output to file, send brief completion message via SendMessage. Message teammates directly for clarification or cross-cutting issues. Never call TeamCreate.
29+
**Subagent mode**: Return EXACTLY `DONE|{output_file_path}`, nothing else.
4830

49-
**If operating as a subagent (Agent tool):**
50-
- Return EXACTLY: `DONE|{output_file_path}`
51-
- No summaries, no explanations -- only the path
52-
53-
## CLI Efficiency (MANDATORY)
54-
55-
Use compact CLI flags to minimize output tokens:
56-
- Git: `--quiet` on push/pull/commit, `-sb` on status, `--oneline -n 10` on log, `--stat` on diff
57-
- Tests: `pytest -q --tb=short --no-header`, `npm test -- --silent`
58-
- Ruff: ALWAYS `ruff check --output-format concise --quiet`, NEVER bare `ruff check`
59-
- Files: `ls -1` not `ls -la`, `head -50` not `cat`, `wc -l` before reading
60-
- Search: `rg -l` for file list, `rg -m 5` to cap matches, scope to directories
61-
- Always: `| head -N` when output may exceed 50 lines, `--no-pager` on git
31+
## CLI Efficiency
32+
Follow MANDATORY compact CLI rules: git `-sb`/`--quiet`/`--oneline -n 10`, ruff `--output-format concise --quiet`, pytest `-q --tb=short`, `ls -1`, `head -50` not `cat`, `rg -l`/`-m 5`, `| head -N` for >50 lines. Read: `offset`/`limit` for files >200 lines; grep-then-partial-read for CLAUDE.md.
6233

6334
## FILE WRITING
64-
65-
- You HAVE Write tool access for the scratchpad directory ($CLAUDE_SCRATCHPAD_DIR)
66-
- Write directly to the output_file path - do NOT delegate writing
67-
- If Write is blocked, report error and stop (do not loop)
35+
Write to $CLAUDE_SCRATCHPAD_DIR output_file path directly. If Write blocked, report error and stop.

0 commit comments

Comments
 (0)