Commit Graph

10 Commits

Author SHA1 Message Date
Florian BRUNIAUX f447a3d5b1 feat: rtk rewrite — single source of truth for LLM hook rewrites (#241)
* feat: add `rtk rewrite` command — single source of truth for hook rewrites

Implements `rtk rewrite <cmd>` as the canonical rewrite engine for all
LLM hook integrations (Claude Code, Gemini CLI, future tools).

- Add `rewrite_prefixes` field to `RtkRule` in discover/registry.rs
- Add public `rewrite_command()` with compound command support (&&, ||, ;, |)
- Add `rewrite_segment()`, `rewrite_compound()`, `strip_word_prefix()` helpers
- Handle already-rtk commands (exit 0, identical output)
- Handle unsupported/ignored commands (exit 1, no output)
- Add 20 unit tests covering all branches and edge cases
- Create `src/rewrite_cmd.rs` thin CLI wrapper
- Register `Commands::Rewrite` in main.rs
- Simplify `.claude/hooks/rtk-rewrite.sh` from 357 → 60 lines

Hooks no longer need duplicate mapping logic — a single
`REWRITTEN=$(rtk rewrite "$CMD") || exit 0` handles everything.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: fix version references and module count for 0.22.2

- README.md, CLAUDE.md, ARCHITECTURE.md: 0.20.1 → 0.22.2
- ARCHITECTURE.md: module count 48 → 51 (added rewrite_cmd + 2 from master)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ci: update hook coverage check to verify registry (not hook script)

Since PR #241, the hook delegates to `rtk rewrite` — command mappings
live in src/discover/registry.rs, not the bash hook script.

Update the "Verify hook coverage" CI step to:
- Check that the hook calls `rtk rewrite` (new architecture)
- Check that registry.rs has rewrite_prefixes for all Python/Go commands

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: support single `&` background operator in compound rewrites

Per feedback from @xDelph: AI agents increasingly use `cmd1 & cmd2`
for parallel execution. This commit adds support alongside existing
`&&`, `||`, `;`, and `|` operators.

Changes:
- rewrite_compound: add match arm for single `&` (after `&&` check)
- rewrite_command: add `" & "` to has_compound detection
- init: show "installed/updated" vs "already up to date" so users
  know whether rtk init changed the hook on re-run

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: add Python/Go commands to rewrite registry

Add `ruff`, `pytest`, `pip`, `go`, and `golangci-lint` to both
PATTERNS and RULES in registry.rs so the CI coverage check passes
and `rtk rewrite` correctly identifies these commands.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference to 0.23.0 in README

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference to 0.23.0 in CLAUDE.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version and module count to 0.23.0/52 in ARCHITECTURE.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: address P0 review feedback on rtk-rewrite PR

P0.1 - Replace 218-line bash hook with 58-line thin delegating hook.
  All rewrite logic now lives exclusively in `rtk rewrite` (Rust registry).
  `rtk init` installs the thin hook via include_str!.

P0.2 - Fix `head -20 file` crash at runtime.
  Generic prefix replacement produced `rtk read -20 file` (invalid clap args).
  Now translates `head -N file` → `rtk read file --max-lines N` and skips
  unsupported head flags (e.g. -c) by returning exit 1.

P0.3 - Add version guard in hook for rtk < 0.23.0.
  Prints a warning to stderr instead of silently doing nothing.

Also adds missing registry entries vs old hook:
  - gh release, cargo install
  - docker run/exec/build, kubectl describe/apply
  - tree, diff

474 tests pass, 0 clippy warnings.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* style: cargo fmt

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(discover): extract rules/patterns into rules.rs

Per aeppling review: registry.rs was too large (~1500 lines).
Extract all static data into src/discover/rules.rs:
- RtkRule struct (with pub fields)
- PATTERNS const array
- RULES const array
- IGNORED_PREFIXES and IGNORED_EXACT const arrays

registry.rs now contains only logic + tests.
rules.rs is the single place to add a new command mapping.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update version reference to 0.24.0 in README

* docs: update version references to 0.24.0 in CLAUDE.md and ARCHITECTURE.md

* fix(discover): add aws and psql to rewrite registry

rtk aws and rtk psql modules exist since PR #216 but were missing
from the registry rules — rewrite was silently skipping them.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test(discover): exhaustive regression tests for rewrite registry

Cover all command categories added in PR #241 and missing from
the previous test suite:
- aws / psql (PR #216 modules, gap detected during non-reg run)
- Python: ruff, pytest, python -m pytest, pip, uv pip
- Go: go test/build/vet, golangci-lint
- JS/TS: vitest, pnpm vitest, prisma, prettier, pnpm list
- Compound operators: || and ; rewrites, 4-segment chains,
  mixed supported/unsupported segments, all-unsupported → None
- sudo prefix rewrite, env var prefix rewrite
- find with native flags
- Registry invariants: PATTERNS/RULES aligned, all rules valid,
  all patterns are valid regex

Before: 559 tests. After: 607 tests.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(migration): document breaking change + detect outdated hook in rtk config

CHANGELOG [Unreleased]:
- Migration required: rtk init --global needed after upgrade
- Documents upgrade path and explains no immediate breakage

rtk init --show / rtk config now detects old hook (inline if-else)
vs new thin delegator (rtk rewrite) and prints actionable warning:

  ⚠️  Hook: ~/.claude/hooks/rtk-rewrite.sh (outdated — inline logic, not thin delegator)
     → Run `rtk init --global` to upgrade to the single source of truth hook

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs: update hook references for thin delegator (0.24.0)

- ARCHITECTURE.md: fix hook description (shell script → thin delegator)
- INSTALL.md: add upgrade path for old hook users (pre-0.24 breaking change)
- SECURITY.md: add registry.rs + hook files to Tier 1 critical files

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* docs(arch): fix module count 52→55, add aws/psql/rewrite to module map

Adds aws_cmd, psql_cmd (PR #216) and rewrite_cmd (this PR) to the
Complete Module Map table. Updates total from 52 to 55 to match main.rs.

Fixes CI validate-docs.sh module count mismatch.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ci: fix hook coverage check to search rules.rs instead of registry.rs

After the PR #241 refactor, rewrite_prefixes constants moved from
registry.rs to rules.rs. Update grep to search the whole discover/
directory so it finds them in the right file.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-05 14:20:01 +01:00
Florian BRUNIAUX 965ed4d166 docs: add ASCII diagrams to README, INSTALL and ARCHITECTURE
Three documentation gaps identified and filled:

- README.md: replace 4-bullet "How It Works" with proxy flow diagram;
  add hook rewrite flow diagram under "Auto-Rewrite Hook" section
- INSTALL.md: add mode-selection decision tree before init options;
  add sequence diagram showing PreToolUse hook lifecycle
- ARCHITECTURE.md: add "Hook Architecture" section with full ASCII
  diagram covering auto-rewrite vs suggest hook strategies

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-02-22 14:43:45 +01:00
patrick szymkowiak c84fa3c060 fix: add website URL (rtk-ai.app) across project metadata (#81)
- Cargo.toml: add homepage field
- README.md: add website/github/install links
- Formula/rtk.rb: update homepage to website
- release.yml: update homepage and docs link in formula template

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 12:28:37 +01:00
patrick szymkowiak 55d010ad5e fix: update stale repo URLs from pszymkowiak/rtk to rtk-ai/rtk (#78)
Closes #77

- install.sh: update REPO to rtk-ai/rtk (was using old fork name)
- INSTALL.md: fix curl URL from /blob/ (returns HTML) to raw URL
- Cargo.toml: update repository field
- Formula/rtk.rb: update all download URLs and tap reference

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 12:17:37 +01:00
Florian BRUNIAUX 848a63dfac feat(init): auto-patch settings.json for frictionless hook installation
## Summary

Eliminates manual settings.json setup friction by automating hook
registration with safety (backup, atomic writes, idempotency).

## Changes

### Core Features
- **Auto-patch**: Default `rtk init -g` prompts to patch settings.json [y/N]
- **CLI flags**: `--auto-patch` (no prompt), `--no-patch` (manual), `--uninstall` (full cleanup)
- **Safety**: Automatic backup to `settings.json.bak` before modification
- **Idempotency**: Detects existing hook, skips modification
- **Status check**: `rtk init --show` now displays settings.json registration

### Implementation
- New types: `PatchMode` (Ask/Auto/Skip), `PatchResult` (tracking outcomes)
- New functions in `src/init.rs`:
  - `hook_already_present()` - Detects RTK hook via substring match
  - `insert_hook_entry()` - Deep-merges hook using idiomatic `entry()` API
  - `atomic_write()` - Crash-safe writes with tempfile
  - `patch_settings_json()` - Main orchestrator
  - `uninstall()` - Complete cleanup (hook, RTK.md, settings.json)
- Modified functions: `run()`, `run_default_mode()`, `run_hook_only_mode()`, `show_config()`

### Code Quality Improvements
- Refactored `insert_hook_entry()` to use Rust `entry()` API (no manual unwraps)
- Simplified `hook_already_present()` with iterator chains (3x shorter)
- Improved error messages with file paths and actionable hints
- Fixed string allocation (to_str() vs to_string())

### Dependencies
- Added `preserve_order` feature to `serde_json` (key order preservation)
- Moved `tempfile` to production dependencies (atomic writes)

### Documentation
- **README.md**: Updated Quick Install, added Installation Flags, Uninstalling, Troubleshooting, What Are Hooks sections
- **INSTALL.md**: Updated Recommended Setup, added Common User Flows, Uninstalling sections
- **CHANGELOG.md**: Documented new feature under Unreleased

### Testing
- 11 new unit tests for hook detection, insertion, atomic writes, cleanup
- All 249 tests passing
- Smoke tested: install, idempotency, show, uninstall

## User Impact

**Before**: Users had to manually copy JSON snippet to settings.json
**After**: Single command with prompt, automatic backup, clean uninstall

## Breaking Changes

None. Backwards compatible - manual setup still works via `--no-patch`.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 16:12:40 +01:00
Florian BRUNIAUX 8c67a2f1e7 docs: update for hook-first installation mode
## README.md Updates

**Quick Start section:**
- Clear 3-step process: verify → install hook → test
- Prominently recommend `rtk init -g` (hook-first mode)
- Explain 99.5% token savings (2000 → 10 tokens)
- Show alternative modes (--claude-md, local init)

**Configuration section:**
- New comparison table: 4 modes with token costs
- Migration instructions for existing users
- Clarify hook vs CLAUDE.md injection differences

**Auto-Rewrite Hook section:**
- Promote automated install (`rtk init -g`) as primary method
- Keep manual install as fallback
- Add verification step (`rtk init --show`)

## INSTALL.md Updates

**Project Initialization:**
- Recommend global hook-first setup (with rationale)
- Show token savings: 99.5% reduction
- Document local setup as alternative
- Add upgrade/migration guide for existing users

## TROUBLESHOOTING.md Updates

**RTK not working section:**
- Option A: Automated (`rtk init -g`) - recommended
- Option B: Manual install - fallback
- Clarify absolute path requirement in settings.json
- Add verification step

## Fixes Documentation Gaps

Before:
- ❌ No mode comparison
- ❌ No migration guide
- ❌ Manual install only
- ❌ Unclear token impact

After:
- ✅ Clear mode comparison with use cases
- ✅ Automatic migration documented
- ✅ Automated install prioritized
- ✅ Quantified token savings (99.5%)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-07 15:28:39 +01:00
patrick szymkowiak b1f15cf494 Fix repository link in INSTALL.md
Updated repository links for Rust Token Killer installation instructions.
2026-02-02 20:22:25 +01:00
Florian BRUNIAUX 00623cb80e docs: point all documentation to upstream instead of fork
## Problem
Documentation incorrectly promoted the fork over upstream for installation,
creating confusion about which repository is the source of truth.

## Changes

### Installation Instructions
- **README.md**: Restored curl install pointing to upstream (pszymkowiak/rtk)
- **README.md**: Removed "Fork with All Features" section
- **INSTALL.md**: Added curl install, removed fork recommendation
- **TROUBLESHOOTING.md**: All installation paths → upstream

### Repository References
- **README.md**: Removed fork from repo list, issues → rtk-ai/rtk
- **CLAUDE.md**: Removed fork mention from project list
- **CHANGELOG.md**: Repository and issues → rtk-ai/rtk
- **ROADMAP.md**: Installation instructions → upstream curl

### Scripts
- **check-installation.sh**: Install instructions → upstream curl

## Result
All documentation now consistently points to upstream (rtk-ai/rtk, pszymkowiak/rtk)
as the source of truth for installation and issues.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 18:39:18 +01:00
Florian BRUNIAUX e2e8be42a7 docs: clarify rtk name collision and fix installation confusion
## Problem
Users are accidentally installing the wrong "rtk" package:
- Rust Type Kit (reachingforthejack/rtk) - type generation tool
- Rust Token Killer (rtk-ai/rtk) - LLM token optimizer

This causes confusion when `rtk gain` doesn't exist after installation.

## Changes

### Documentation Updates
- **README.md**: Add prominent warning about name collision at top
- **README.md**: Fix installation instructions with mandatory verification
- **CLAUDE.md**: Add name collision warning with verification steps
- **INSTALL.md**: Clarify pre-installation checks and wrong package handling

### New Files
- **docs/TROUBLESHOOTING.md**: Comprehensive troubleshooting guide covering:
  - Wrong rtk installed (Type Kit vs Token Killer)
  - cargo install rtk pitfalls
  - Missing commands (vitest, pnpm, etc.)
  - PATH issues and compilation errors

- **scripts/check-installation.sh**: Automated diagnostic script that verifies:
  - RTK installed and in PATH
  - Correct version (Token Killer with `rtk gain`)
  - Available features
  - Claude Code integration status
  - Auto-rewrite hook configuration

## Verification
After these changes, users can quickly diagnose installation issues:
```bash
bash scripts/check-installation.sh
```

Fixes installation confusion reported by multiple users.

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-02 15:20:39 +01:00
Florian BRUNIAUX da5233f85c docs: add installation guide for AI coding assistants
- Add INSTALL.md with step-by-step installation instructions
- Mandatory pre-installation verification check (rtk --version)
- Troubleshooting section for common issues
- Production-validated token savings metrics (anonymized)
- AI assistant integration checklist
- Fork vs upstream installation strategy
2026-01-28 17:00:50 +01:00