save-tokens · diff

git:20260410.c02999d to git:20260511.125144f

47 added, 46 removed. Audit A to A.

What this update changes in the checks

No check changed: every fixed check gives the same answer before and after this update.

A tripped check is a label, not a verdict: read the matched text and the lines below. This week's updates that newly trip a check.

---
name: save-tokens
description: Token-saving session automation — statusline, prompt guard, precompact handoffs, session rotation, and handoff commands for Claude Code
+ triggers:
+ files:
+ - src/commands/save-tokens.js
+ - src/lib/save-tokens.js
+ - src/templates/hooks/save-tokens*.sh
+ - src/templates/hooks/save-tokens.mjs
+ - src/templates/commands/save-handoff.md
+ - src/templates/commands/resume-handoff*.md
+ - tests/save-tokens*.test.js
+ keywords:
+ - save-tokens
+ - handoff
+ - statusline
+ - prompt-guard
+ - precompact
+ - session rotation
+ - token warning
---
- ## Activation
-
- This skill triggers when editing save-tokens files:
- - `src/commands/save-tokens.js`
- - `src/lib/save-tokens.js`
- - `src/templates/hooks/save-tokens*.sh`
- - `src/templates/hooks/save-tokens.mjs`
- - `src/templates/commands/save-handoff.md`
- - `src/templates/commands/resume-handoff*.md`
- - `tests/save-tokens*.test.js`
-
- Keywords: save-tokens, handoff, statusline, prompt-guard, precompact, session rotation, token warning
+ You are working on **save-tokens** — the feature that installs Claude Code hooks and commands to warn about token usage, auto-save handoffs before compaction, and support session rotation.
- ---
+ ## Domain purpose
+ `aspens save-tokens` installs three Claude Code hooks (statusline, prompt-guard, precompact) plus `/save-handoff`, `/resume-handoff-latest`, and `/resume-handoff` slash commands. The hooks observe Claude's own token telemetry and inject system messages telling Claude to rotate sessions before context blow-up. Handoff files persist enough state in `.aspens/sessions/` to resume seamlessly in a fresh session.
- You are working on **save-tokens** — the feature that installs Claude Code hooks and commands to warn about token usage, auto-save handoffs before compaction, and support session rotation.
+ ## Business rules / invariants
+ - **Claude-only feature.** Hooks and statusline only work with Claude Code; Codex has no save-tokens integration. Config lives in `.aspens.json` under `saveTokens`.
+ - **Config thresholds default 175k warn / 200k compact.** `Number.MAX_SAFE_INTEGER` is the disabled sentinel for either threshold; `target.js#isValidSaveTokensConfig()` validates shape, types, and threshold ordering — invalid config causes `readConfig()` to return `null`.
+ - **`writeConfig` preserves feature config** — `saveTokens` is preserved across `writeConfig` calls unless explicitly set to `null`.
+ - **Sessions dir gitignored** — `.aspens/sessions/.gitignore` excludes everything except `.gitignore` and `README.md`.
+ - **Settings backup** — first install creates `.claude/settings.json.bak` if settings exist and no backup exists yet.
+ - **StatusLine pre-existence guard** — `canInstallSaveTokensStatusLine()` refuses to overwrite an unrelated custom `statusLine.command`; when refused, `applyStatusLineAvailability()` forces both thresholds to `MAX_SAFE_INTEGER` and disables `sessionRotation`.
- ## Key Files
- - `src/commands/save-tokens.js` — Main command: interactive or `--recommended` install, `--remove` uninstall, installs hooks + commands + settings
- - `src/lib/save-tokens.js` — Config defaults (`DEFAULT_SAVE_TOKENS_CONFIG`), `buildSaveTokensConfig()`, `buildSaveTokensSettings()`, `buildSaveTokensGitignore()`, `buildSaveTokensReadme()`
- - `src/templates/hooks/save-tokens.mjs` — Runtime hook: `runStatusline()`, `runPromptGuard()`, `runPrecompact()`, telemetry recording, handoff saving/pruning
- - `src/templates/hooks/save-tokens-statusline.sh` — Shell wrapper for statusline hook
- - `src/templates/hooks/save-tokens-prompt-guard.sh` — Shell wrapper for prompt guard hook
- - `src/templates/hooks/save-tokens-precompact.sh` — Shell wrapper for precompact hook
- - `src/templates/commands/save-handoff.md` — Slash command to save a rich handoff summary
- - `src/templates/commands/resume-handoff-latest.md` — Slash command to resume from most recent handoff
- - `src/templates/commands/resume-handoff.md` — Slash command to list and pick a handoff to resume
+ ## Non-obvious behaviors
+ - **Three hook entry points dispatched by subcommand.** Shell wrappers (`*.sh`) read stdin, resolve project dir, and call `save-tokens.mjs` with `statusline`, `prompt-guard`, or `precompact`. `ASPENS_PROJECT_DIR` env var overrides `CLAUDE_PROJECT_DIR`; both fall back to `cwd`.
+ - **Statusline doubles as telemetry recorder.** `recordClaudeContextTelemetry()` writes `.aspens/sessions/claude-context.json` summing `input_tokens + cache_creation_input_tokens + cache_read_input_tokens + output_tokens` from `context_window.current_usage`. Telemetry older than 5 minutes is ignored by the prompt guard.
+ - **Prompt-guard speaks to Claude, not the user.** Above `compactAtTokens`: saves a handoff (reason `rotation-threshold` if `sessionRotation`, else `compact-threshold`) and stdout-prints an "IMPORTANT — you must tell the user" block instructing fresh session + `/resume-handoff-latest`. Above `warnAtTokens`: suggests `/save-handoff`. When telemetry is missing, prints a one-time link to the aspens issues page.
+ - **Precompact hook only fires when `saveHandoff` is enabled** and `claude.enabled !== false`; reason is `precompact`.
+ - **`extractSessionFacts()` parses the JSONL transcript** to extract `originalTask` (first user message, 500 char cap), `recentPrompts` (last 3, 200 char cap each), `filesModified` (Edit/Write tool_use `file_path`), `gitCommits` (regex on Bash `git commit -m "..."`), and `branch` (from `gitBranch` on user records). Transcript path is validated to be inside `projectDir`; falls back to `input.prompt` when transcript is missing or outside the project.
+ - **Transcript parsing is best-effort** — all errors caught, invalid JSON lines silently skipped; returns empty facts on failure.
+ - **`pruneOldHandoffs()` keeps newest 10** `*-handoff.md` files by lexicographic (timestamp) sort; older are unlinked. `latestHandoff()` uses the same sort.
+ - **`--recommended` install is non-interactive** — used standalone or invoked by `doc init --recommended` (which also installs agents and the doc-sync git hook).
+ - **`--remove` cleans legacy artifacts too** — removes both `.sh` and historic `.mjs` variants of each hook, plus the legacy `save-tokens-resume.md` command; strips `statusLine` if it points at save-tokens and filters any hook entry whose command contains `save-tokens-`; nulls `saveTokens` in `.aspens.json`.
- ## Key Concepts
- - **Claude-only feature:** Save-tokens hooks and statusline only work with Claude Code. Config is stored in `.aspens.json` under `saveTokens`.
- - **Three hook entry points:** Shell wrappers (`*.sh`) read stdin, resolve project dir, and call `save-tokens.mjs` with a subcommand (`statusline`, `prompt-guard`, `precompact`).
- - **Statusline:** Records Claude context telemetry to `.aspens/sessions/claude-context.json` on every status update. Displays `save-tokens Xk/Yk` in the Claude status bar.
- - **Prompt guard:** Checks token count against `warnAtTokens` (175k default) and `compactAtTokens` (200k default). Above compact threshold: saves a handoff and recommends starting a fresh session then running `/resume-handoff-latest`. Above warn threshold: suggests `/save-handoff`.
- - **Precompact:** Auto-saves a handoff before Claude compaction when `saveHandoff` is enabled.
- - **Handoff files:** Saved to `.aspens/sessions/<timestamp>-claude-handoff.md`. Structured with: metadata (tokens, working dir, branch), task summary, files modified, git commits, recent prompts, current state, next steps. Content extracted from JSONL transcript via `extractSessionFacts()`. Pruned to keep max 10.
- - **`extractSessionFacts(input)`:** Parses the session's JSONL transcript to extract: `originalTask` (first user message), `recentPrompts` (last 3 user messages, 200 char max each), `filesModified` (from Edit/Write tool_use blocks), `gitCommits` (from Bash git commit commands), `branch` (from user record `gitBranch` field). Falls back to `input.prompt` as task summary when no transcript is available. Task summary capped at 500 chars.
- - **Telemetry:** `recordClaudeContextTelemetry()` sums input/output/cache tokens from Claude's `context_window.current_usage`. Stale telemetry (>5 min) is ignored.
- - **Config thresholds:** `warnAtTokens` and `compactAtTokens` can be `Number.MAX_SAFE_INTEGER` as disabled sentinel.
- - **Settings merge:** `buildSaveTokensSettings()` produces `statusLine` + `hooks` config. Merged into existing `settings.json` via `mergeSettings()` which treats save-tokens hooks as aspens-managed.
- - **`--recommended` install:** Called standalone or from `doc init --recommended`. Installs hooks, commands, sessions dir, settings — no prompts.
- - **`--remove` uninstall:** Removes hook files (including legacy `.mjs` variants), commands, cleans settings.json entries, nulls `saveTokens` in `.aspens.json`.
+ ## Critical files (purpose, not inventory)
+ - `src/commands/save-tokens.js` — install/remove orchestration; interactive multiselect (`warnings`, `handoffs`), `--recommended`, `--remove`. Exports `installSaveTokensRecommended()` consumed by `doc-init.js`.
+ - `src/lib/save-tokens.js` — config + settings + template content builders (`DEFAULT_SAVE_TOKENS_CONFIG`, `buildSaveTokensConfig`, `buildSaveTokensSettings`, `buildSaveTokensGitignore`, `buildSaveTokensReadme`, `buildSaveTokensRecommendations`).
+ - `src/templates/hooks/save-tokens.mjs` — runtime library: `runStatusline`, `runPromptGuard`, `runPrecompact`, `saveHandoff`, `extractSessionFacts`, telemetry record/read, handoff pruning, `main()` subcommand dispatch.
+ - `src/templates/hooks/save-tokens-{statusline,prompt-guard,precompact}.sh` — shell wrappers; resolve `PROJECT_DIR` via `cd "$SCRIPT_DIR/../.." && pwd` and exec the `.mjs` with the matching subcommand.
+ - `src/templates/commands/{save-handoff,resume-handoff-latest,resume-handoff}.md` — slash command bodies installed under `.claude/commands/`.
## Critical Rules
- - **Shell wrappers resolve project dir from script location** — `SCRIPT_DIR` → `PROJECT_DIR` via `cd "$SCRIPT_DIR/../.." && pwd`. `ASPENS_PROJECT_DIR` env var overrides `CLAUDE_PROJECT_DIR`.
- - **Config validation in `target.js`** — `isValidSaveTokensConfig()` validates shape, types, and threshold ordering. Invalid config causes `readConfig()` to return `null`.
- - **`writeConfig` preserves feature config** — `saveTokens` is preserved across `writeConfig` calls unless explicitly set to `null`.
- - **Handoff pruning** — `pruneOldHandoffs()` keeps newest 10, deletes older. Only touches `*-handoff.md` files.
- - **Sessions dir gitignored** — `.aspens/sessions/.gitignore` excludes everything except `.gitignore` and `README.md`.
- - **Settings backup** — First install creates `.claude/settings.json.bak` if settings exist and no backup exists yet.
- - **`doc init --recommended`** — Calls `installSaveTokensRecommended()` from `save-tokens.js`, also installs agents and doc-sync git hook.
- - **Transcript parsing is best-effort** — `extractSessionFacts()` catches all errors and returns empty facts on failure. Invalid JSON lines are silently skipped.
+ - **Settings merge uses `mergeSettings()`** from `skill-writer.js` — save-tokens hooks are treated as aspens-managed; do not hand-edit `.claude/settings.json` to add/remove save-tokens entries.
+ - **Hooks write to stdout to inject into Claude's context** — comments in `runPromptGuard()` flag this; keep those messages addressed to Claude ("Tell the user...") not to a human reader.
+ - **Token sum includes cache tokens** — do not switch to just `input_tokens + output_tokens`; that under-counts Claude's effective context use.
## References
- **Impact integration:** `src/lib/impact.js` — `evaluateSaveTokensHealth()` validates installed state
---
- **Last Updated:** 2026-04-10
+ **Last Updated:** 2026-05-11