Compare commits

...
Author SHA1 Message Date
dependabot[bot] 806c0df361 build(deps): bump actions/github-script from 7.1.0 to 9.0.0
Bumps [actions/github-script](https://github.com/actions/github-script) from 7.1.0 to 9.0.0.
- [Release notes](https://github.com/actions/github-script/releases)
- [Commits](https://github.com/actions/github-script/compare/f28e40c7f34bde8b3046d885e986cb6290c5673b...3a2844b7e9c422d3c10d287c895573f7108da1b3)

---
updated-dependencies:
- dependency-name: actions/github-script
  dependency-version: 9.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-09-09 00:30:42 +00:00
Nicolas Le Cam 8e9aa04cb2 Merge pull request #3258 from breisnerlopez/fix/grep-l-max-len-collision
test(grep): pin -l/-L parity with grep, including numeric patterns
2026-09-09 02:06:09 +02:00
Nicolas Le CamandClaude Opus 5 d554bef221 test(grep): cover the numeric pattern that -l silently swallowed
A non-numeric pattern stops at clap's parse error and falls back to raw
grep, so rtk and grep agree byte-for-byte whether or not `-l` is bound to
--max-len: the three existing cases still pass with the bug reintroduced.
Only a numeric pattern reaches the wrong answer -- rtk printed nothing and
exited 1 where grep listed the file.

Drop the clap-level test and the comment sentence with it. Develop's
test_grep_parse_files_with_matches_l already fails under the same mutation,
and -L never had a short binding on --max-len, so src/main.rs is untouched.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 01:53:30 +02:00
Nicolas Le Cam 77ba5c9aca Merge pull request #3278 from rtk-ai/feat/retriever-recall
feat(recall): SQLite recall system
2026-09-09 01:34:28 +02:00
Nicolas Le CamandClaude Opus 5 ab09904e10 refactor(recall): drop the unreachable no-hash arm in run_recall
The usage guard returns early when no hash and no --list is given, and
--list returns before this match, so the arm could never run. Removing it
keeps the usage string in one place.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-09 01:08:31 +02:00
Adrien EpplingandClaude Opus 5 ddc2182609 feat(recall): name an over-recalled filter, and clear its counters on gain --reset
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 20:36:57 +02:00
Adrien EpplingandClaude Opus 5 7c10f7791c fix(benchmark): ignore the recall hints when counting find entries
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 16:53:02 +02:00
Adrien EpplingandClaude Opus 5 473edaf247 fix(recall): keep tee mode free of any sqlite artifact
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 16:52:59 +02:00
breisnerlopez 74ec07017f fix(grep): put --max-len before positionals in bench; reuse assert_eq_grep
Address review:
- benchmark.sh: with trailing_var_arg on extra_args, --max-len after the
  positionals was swallowed and forwarded raw to grep (unknown option ->
  bench FAIL). Move it before -rn/pattern so rtk parses it; verified 320KB
  -> 14.8KB (~95%) and that --max-len 40 vs 200 changes output size.
- grep_faithful_format_test: the inline cmp closure duplicated the existing
  assert_eq_grep helper (rtk_grep + grep_plain, same stdout/exit asserts);
  drop it in.
2026-09-08 15:30:49 +02:00
breisnerlopez 5681008ca9 fix(grep): free -l for GNU --files-with-matches instead of --max-len
`-l` was bound to RTK's `--max-len`, colliding with GNU grep where `-l`
means `--files-with-matches`. Running `grep -l <pattern>` made clap read
the pattern as a usize and error (`invalid value '<pattern>' for
'--max-len'`), dropping the command to a raw-grep fallback at 0% savings.

Drop the short binding. `-l`/`-L` now flow to `extra_args`, where the
existing `has_format_flag` already routes them to the grep passthrough
(GNU semantics, minimal output). `--max-len` keeps its long form and its
default of 80; nothing internal used the short.

- src/main.rs: remove `short = 'l'` from `Grep::max_len` + clap-parse
  regression test.
- tests/grep_faithful_format_test.rs: end-to-end test asserting
  `rtk grep -l/-L` is byte-identical to `grep -l/-L`, covering `-l`
  leading and trailing.
- scripts/benchmark.sh: the max-len bench used the old `-l 40` alias ->
  `--max-len 40`.
- docs/usage/FEATURES.md: drop the `-l` short from the grep options table.
2026-09-08 15:30:49 +02:00
Adrien EpplingandClaude Opus 5 a882419bac fix(recall): keep legacy tee always semantics, sqlite stays failure driven
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:29 +02:00
Adrien EpplingandClaude Opus 5 2b13d80c37 fix(recall): store the hidden tail when the cap cannot hold the shown prefix
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:28 +02:00
Adrien EpplingandClaude Fable 5 feb8aeb644 revert(recall): drop tee_on_success, recovery stays failure and truncation driven
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:27 +02:00
Adrien EpplingandClaude Fable 5 9f37717319 fix(config): single shared legacy-tee mapping for load and config recall
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:26 +02:00
Adrien EpplingandClaude Fable 5 dd1c21a473 fix(recall): hidden-lines hint reflects what recall can actually return
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:26 +02:00
Adrien EpplingandClaude Fable 5 8969fa49c5 feat(recall): tee_on_success restores legacy always behavior, accurate migration notices
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:25 +02:00
Adrien EpplingandClaude Fable 5 d93fd4fff5 fix(recall): byte-faithful --grep, cached store connection, serialized env tests
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:24 +02:00
Adrien EpplingandClaude Fable 5 7c743443ff fix(recall): read paths never create the database
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:23 +02:00
Adrien EpplingandClaude Fable 5 1dcb7ecd54 fix(recall): evict by recency excluding the just-stored hash
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:22 +02:00
Adrien EpplingandClaude Fable 5 439c25164d fix(recall): adapt upstream ctest/ls/tsc integration after rebase
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:22 +02:00
Adrien EpplingandClaude Fable 5 d8a80dfab5 fix(recall): review nits — literal-grep note, dead aws hint branch, doc drift, sorted families
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:21 +02:00
Adrien EpplingandClaude Fable 5 817e230e97 fix(recall): store NULL exit code on truncation paths instead of fake 0
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:20 +02:00
Adrien EpplingandClaude Fable 5 bdfdeea37a fix(recall): evict by rowid so same-second bursts keep the newest entry
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:20 +02:00
Adrien EpplingandClaude Fable 5 c09d63eed8 fix(config): merge legacy tee fields when a retriever section coexists
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:19 +02:00
Adrien EpplingandClaude Fable 5 e7447e1f06 fix(recall): honor kill switches in hook-side tee read tracking
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:18 +02:00
Adrien EpplingandClaude Fable 5 6633d66c5f fix(recall): preserve recalled flag when identical output is re-stored
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:18 +02:00
Adrien EpplingandClaude Fable 5 bfc630995f fix(recall): canonicalize stats keys across elision, recall and TOML paths
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MNqtCagEUryc1fgw62APkm
2026-09-08 14:12:17 +02:00
Adrien Eppling b158152ef7 feat(telemetry): report recall efficiency counters per filter family 2026-09-08 14:12:16 +02:00
Adrien Eppling a53373191d feat(recall): content-addressed recall store with selectable [retriever] mode
sqlite (default) queried by 'rtk recall'; tee (legacy files) and disabled modes retained.
2026-09-08 14:12:15 +02:00
Nicolas Le Cam f7495466ed Merge pull request #2515 from allanbatista/codex/fix-native-test-expression
[codex] fix native test expression passthrough
2026-09-08 03:37:13 +02:00
Nicolas Le CamandClaude Opus 5 80e45683be test(test): cover Commands::Test routing end to end
The unit tests exercise `is_native_test_expression` directly, so inverting or
dropping the branch that calls it left the suite green while `rtk test -d dir`
went back to `sh: 0: Illegal option -d`.

Run the binary instead: native expressions carry the system `test` exit code,
`!` is neither answered backwards nor allowed to swallow a command, argument
boundaries survive, and a command still reaches the test runner.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 03:23:44 +02:00
Nicolas Le CamandClaude Opus 5 98e66e0540 fix(test): treat ! and ( as native only when what follows is
`!` and `(` are shell syntax as well as `test` syntax, so matching them on
the first token alone captured invocations the shell path ran correctly:
`rtk test ! false` returned 1 instead of 0, and `rtk test ! cargo --version`
stopped running cargo and reported `test: missing argument after '--version'`.

Recurse instead, so `!` and `(` mark a native expression only when what they
apply to is one. Measured against `/usr/bin/test` over 526 generated
expressions: unchanged at 212 mismatches (down from 411 before the fix), with
the shell-command forms back to their previous exit codes.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 03:23:44 +02:00
Allan Batista b02b56715b fix native test expression passthrough 2026-06-19 13:39:50 -03:00
31 changed files with 3403 additions and 762 deletions

No files matched your search

+1 -1
View File
@@ -21,7 +21,7 @@ jobs:
permission-pull-requests: write
- name: Add wrong-base label and comment
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
with:
github-token: ${{ steps.app-token.outputs.token }}
script: |
Generated
+1
View File
@@ -953,6 +953,7 @@ dependencies = [
"sha2",
"tempfile",
"toml",
"toml_edit",
"ureq",
"walkdir",
"which",
+1
View File
@@ -32,6 +32,7 @@ colored = "3"
dirs = "5"
rusqlite = { version = "0.31", features = ["bundled"] }
toml = "0.8"
toml_edit = "0.22"
chrono = "0.4"
tempfile = "3"
sha2 = "0.10"
+7 -6
View File
@@ -254,7 +254,7 @@ rtk aws logs get-log-events # Timestamped messages only
rtk aws cloudformation describe-stack-events # Failures first
rtk aws dynamodb scan # Unwraps type annotations
rtk aws iam list-roles # Strips policy documents
rtk aws s3 ls # Truncated with tee recovery
rtk aws s3 ls # Truncated with recall recovery
```
### Containers
@@ -435,18 +435,19 @@ For per-agent setup details, override controls, and graceful degradation, see th
[hooks]
exclude_commands = ["curl", "playwright"] # skip rewrite for these (matches `npx playwright` too)
[tee]
enabled = true # save raw output on failure (default: true)
mode = "failures" # "failures", "always", or "never"
[retriever]
mode = "sqlite" # sqlite (default) | tee (legacy files) | disabled
```
When a command fails, RTK saves the full unfiltered output so the LLM can read it without re-executing:
When a command fails, RTK saves the full unfiltered output so the LLM can recall it without re-executing:
```
FAILED: 2/15 tests
[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log]
[full output: rtk recall 3f9c2a81d4e7]
```
Legacy `[tee]` config sections are still honored: they map to `mode = "tee"` (file-based recovery on failure/truncation), or `mode = "disabled"` if you had `enabled = false`. The former `mode = "always"` keeps its behaviour and maps to `tee_on_success = true`, which archives successful runs too. The sqlite store stays failure/truncation-driven.
For the full config reference (all sections, env vars, per-project filters), see the [Configuration guide](https://www.rtk-ai.app/guide/getting-started/configuration).
### Uninstall
+2
View File
@@ -64,6 +64,8 @@ This data directly drives our roadmap. For example, if telemetry shows that 40%
| `parse_failures_24h` | `3` | Filter fragility — high count means filters are breaking |
| `low_savings_commands` | `["rtk docker ps:25%"]` | Commands averaging <30% savings — filters to improve |
| `avg_savings_per_command` | `68.5` | Unweighted average (vs global which is volume-biased) |
| `recall_mode` | `sqlite` | Which recovery mode is active (`sqlite`/`tee`/`disabled`) |
| `recall_stats` | `[{"filter":"grep","mode":"sqlite","elisions":142,"recalls":9}]` | Per-filter counters: how often elided output is retrieved — calibrates filter caps. Filter names come from a fixed allowlist of rtk filter families; anything else is folded into `other`. No hashes, no paths, no command arguments, no output content. |
### Ecosystem distribution
+3 -3
View File
@@ -181,14 +181,14 @@ Savings by ecosystem:
### Module Breakdown
- **Command Modules**: `src/cmds/` — organized by ecosystem (git, rust, js, python, go, dotnet, cloud, system, ruby). Each ecosystem README lists its files.
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, tee, config, toml_filter, display_helpers, telemetry
- **Core Infrastructure**: `src/core/` — utils, filter, tracking, retriever (recall store), tee, tee_file, config, toml_filter, display_helpers, telemetry
- **Hook System**: `src/hooks/` — init, rewrite, permissions, hook_cmd, hook_check, hook_audit, verify, trust, integrity
- **Analytics**: `src/analytics/` — gain, cc_economics, ccusage, session_cmd
### Module Count Breakdown
- **Command Modules**: 42 (directly exposed to users)
- **Infrastructure Modules**: 22 (utils, filter, tracking, tee, config, init, gain, toml_filter, verify_cmd, etc.)
- **Infrastructure Modules**: utils, filter, tracking, retriever, tee, tee_file, config, init, gain, toml_filter, verify_cmd, etc.
- **Git Commands**: 7 operations (status, diff, log, add, commit, push, branch/checkout)
- **JS/TS Tooling**: 8 modules (modern frontend/fullstack development)
- **Python Tooling**: 3 modules (ruff, pytest, pip)
@@ -872,7 +872,7 @@ Modules with Exit Code Preservation:
### Configuration
> For config file format, tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](src/core/README.md).
> For config file format, recall/tee settings, tracking database path, and TOML filter tiers, see [src/core/README.md](src/core/README.md).
Two tiers: **User settings** (`~/.config/rtk/config.toml`) and **LLM integration** (CLAUDE.md via `rtk init`).
+7 -7
View File
@@ -278,17 +278,17 @@ Analytics commands (`rtk gain`, `rtk cc-economics`, `rtk session`) query this da
> **Details**: [`src/analytics/README.md`](../src/analytics/README.md) covers the analytics modules, and [`src/core/README.md`](../src/core/README.md) covers the tracking database schema.
### 3.7 Tee Recovery
### 3.7 Output Recovery (recall store)
On command failure (non-zero exit code):
On command failure (non-zero exit code) — or when a filter truncates a long list:
1. Raw unfiltered output is saved to `~/.local/share/rtk/tee/{epoch}_{slug}.log`
2. A hint line is printed: `[full output: ~/.../tee/1234_cargo_test.log]`
3. LLM agents can re-read the file instead of re-running the failed command
1. Raw unfiltered output is stored in a content-addressed sqlite database (`~/.local/share/rtk/recall.db`, gzip, byte-faithful)
2. A hint line is printed: `[full output: rtk recall 3f9c2a81d4e7]` (failures) or `[+N hidden: rtk recall <hash>]` (truncated lists)
3. LLM agents run `rtk recall <hash>` to get back exactly what was elided instead of re-running the command
Tee is configurable (enabled/disabled, min size, max files, max file size) and never affects command output or exit code on failure.
The mode is selectable via `rtk config recall <sqlite|tee|disabled>` — `tee` keeps the legacy per-file behavior (`~/.local/share/rtk/tee/{epoch}_{slug}.log`). Recovery never affects command output or exit code. `rtk gain --recalls` reports how often elided output is actually consulted, per filter.
> **Details**: [`src/core/README.md`](../src/core/README.md) covers tee configuration and the rotation strategy.
> **Details**: [`src/core/README.md`](../src/core/README.md) covers the recall store, tee mode configuration, and the rotation strategy.
---
+35
View File
@@ -28,6 +28,7 @@ rtk gain --graph # ASCII graph, last 30 days
rtk gain --history # last 10 commands
rtk gain --quota # monthly quota savings estimate (default tier: 20x)
rtk gain --quota -t pro # use pro tier token budget for estimate
rtk gain --recalls # recall efficiency per filter (calibration)
# Export
rtk gain --all --format json > savings.json
@@ -200,6 +201,40 @@ The tiers (`pro`, `5x`, `20x`) correspond to Anthropic Claude API subscription l
`rtk gain` shows what RTK saved. To find commands that ran *without* RTK and calculate what you lost, see [rtk discover](./discover.md).
:::
## Recall efficiency
`--recalls` measures how often your AI assistant goes back for output a filter elided — the signal that a filter's cap is too aggressive for your workflow. Every time a filter stores elided output (an *elision*) and every time the assistant retrieves it (a *recall*), RTK counts it per filter:
```bash
rtk gain --recalls
```
```
Recall efficiency (current mode: sqlite)
SQLITE (exact — reads go through rtk recall)
FILTER ELISIONS RECALLED RATE
vitest 67 29 43%
docker-images 142 3 2%
TEE (approximate — bash-observed reads only)
FILTER ELISIONS RECALLED RATE
cargo_test 38 4 ≥10%
```
How to read it:
- **RATE** is the share of elided outputs the assistant went back for. Re-reading the same entry counts once — the rate measures *entries consulted*, not read commands.
- A **high rate** (say above 30%) means that filter regularly hides output the assistant needs: every recall is an extra API round-trip you paid for. Consider raising that filter's cap.
- A **low rate** means the filter's cap is well calibrated — the elided output was noise.
The two sections are never merged because the data quality differs:
- **SQLITE (exact)**: reads go through `rtk recall <hash>`, the only access path, so the count is exact.
- **TEE (approximate)**: in legacy [tee mode](../getting-started/configuration.md#recall-system), reads are shell commands (`tail`, `cat`, `grep`, …) observed by the rewrite hook before execution. Editor or assistant file-tool reads are invisible, denied commands are not counted, and the per-file dedup window is finite — so the `≥` rate is approximate, not exact. A high rate is still a reliable signal that the cap is too aggressive.
Stats survive entry eviction and retention cleanup: calibration data is kept even after the underlying outputs are purged.
## Troubleshooting
**No data showing:**
+42 -15
View File
@@ -38,12 +38,17 @@ max_width = 120 # maximum output width
ignore_dirs = [".git", "node_modules", "target", "__pycache__", ".venv", "vendor"]
ignore_files = ["*.lock", "*.min.js", "*.min.css"]
[tee]
enabled = true # save raw output on failure
mode = "failures" # "failures" (default), "always", "never"
max_files = 20 # rotation: keep last N files
max_file_size = 1048576 # 1 MB in bytes
# directory = "/custom/tee/path" # optional override
[retriever]
mode = "sqlite" # sqlite (default) | tee (legacy files) | disabled
max_entry_bytes = 10485760 # sqlite: 10 MiB per entry
max_entries = 200 # sqlite: FIFO cap (0 = no cap)
retention_days = 30 # sqlite: age eviction (0 = off)
compression = true # sqlite: gzip blobs (lossless)
# database_path = "/custom/recall.db"
tee_max_files = 20 # tee mode: rotation
tee_max_file_size = 1048576 # tee mode: per-file cap
tee_on_success = false # tee mode: legacy `mode = "always"`, archive successful runs too
# tee_directory = "/custom/tee/dir"
[telemetry]
enabled = true # anonymous daily ping — see Telemetry & Privacy for full details
@@ -83,28 +88,50 @@ since the agent must type `rtk` itself. `rtk init` prints a note when it does th
| Variable | Description |
|----------|-------------|
| `RTK_DISABLED=1` | Disable RTK for a single command (`RTK_DISABLED=1 git status`) |
| `RTK_TEE_DIR` | Override the tee directory |
| `RTK_RECALL=0` | Disable the recall store for a single command |
| `RTK_RECALL_DB` | Override the recall database path |
| `RTK_TEE=0` | Legacy alias of `RTK_RECALL=0` (still honored) |
| `RTK_TEE_DIR` | Override the tee directory (tee mode) |
| `RTK_TELEMETRY_DISABLED=1` | Disable telemetry |
| `RTK_HOOK_AUDIT=1` | Enable hook audit logging |
| `SKIP_ENV_VALIDATION=1` | Skip env validation (useful with Next.js) |
## Tee system
## Recall system
When a command fails, RTK saves the full raw output to a local file and prints the path:
When a command fails — or a filter trims a long list — RTK persists the full output to an embedded database and prints a recall hint:
```
FAILED: 2/15 tests
[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log]
[full output: rtk recall 36365b69eda6]
```
Your AI assistant can then read the file if it needs more detail, without re-running the command.
Your AI assistant runs `rtk recall <hash>` exactly as printed in the hint — that is the whole agent interface. For humans inspecting the store: `rtk recall <hash> --full | --from N | --lines N | --grep PAT` and `rtk recall --list`. Storage is byte-faithful (`BLOB` + lossless gzip); the stored input is the captured command text, as with the previous tee files.
### Choosing the recovery mode
The simplest way is the CLI — no file editing needed:
```bash
rtk config recall # show the active mode and its source
rtk config recall sqlite # hash-addressed sqlite store (default)
rtk config recall tee # legacy .log files in ~/.local/share/rtk/tee/
rtk config recall disabled # no recovery storage
```
Setting a mode rewrites only the relevant keys in `config.toml` (comments and other sections are preserved), and migrates a legacy `[tee]` section — its `max_files`/`max_file_size`/`directory` values are carried over. The equivalent config field, if you prefer editing the file directly, is `[retriever] mode = "sqlite" | "tee" | "disabled"` (see the full structure above).
To see how often your assistant actually goes back for elided output — and which filter caps deserve tuning — see [`rtk gain --recalls`](../analytics/gain.md#recall-efficiency).
| Setting | Default | Description |
|---------|---------|-------------|
| `tee.enabled` | `true` | Enable/disable |
| `tee.mode` | `"failures"` | `"failures"`, `"always"`, `"never"` |
| `tee.max_files` | `20` | Rotation: keep last N files |
| Min size | 500 bytes | Outputs shorter than this are not saved |
| `retriever.mode` | `"sqlite"` | `sqlite` (default), `tee` (legacy files), `disabled` |
| `retriever.max_entry_bytes` | `10485760` | Per-entry storage cap (10 MiB) |
| `retriever.max_entries` | `200` | FIFO cap on retained entries (0 = no cap) |
| `retriever.retention_days` | `30` | Age eviction in days (0 = off) |
| `retriever.compression` | `true` | gzip stored blobs (lossless) |
| `retriever.tee_max_files` | `20` | tee mode: how many files are kept before rotation |
| `retriever.tee_max_file_size` | `1048576` | tee mode: per-file cap (1 MiB) |
| `retriever.tee_on_success` | `false` | tee mode: also archive successful runs — the legacy `[tee] mode = "always"` |
| Max file size | 1 MB | Truncated above this |
## Excluding commands from auto-rewrite
+1 -1
View File
@@ -66,7 +66,7 @@ See [Discover and Session](./analytics/discover.md) for details.
## Further reading
- [Configuration](./getting-started/configuration.md) — config.toml, global flags, env vars, tee recovery
- [Configuration](./getting-started/configuration.md) — config.toml, global flags, env vars, recall recovery
- [Troubleshooting](./resources/troubleshooting.md) — common issues and fixes
- [Telemetry & Privacy](./resources/telemetry.md) — what RTK collects and how to opt out
- [ARCHITECTURE.md](https://github.com/rtk-ai/rtk/blob/master/ARCHITECTURE.md) — system design for contributors
+40 -22
View File
@@ -1335,11 +1335,13 @@ max_width = 120 # Largeur maximale de sortie
ignore_dirs = [".git", "node_modules", "target", "__pycache__", ".venv", "vendor"]
ignore_files = ["*.lock", "*.min.js", "*.min.css"]
[tee]
enabled = true # Activer la sauvegarde de sortie brute
mode = "failures" # "failures" (defaut), "always", ou "never"
max_files = 20 # Rotation : garder les N derniers fichiers
# directory = "/custom/tee/path" # Chemin personnalise (optionnel)
[retriever]
mode = "sqlite" # sqlite (defaut) | tee (fichiers legacy) | disabled
max_entries = 200 # Nombre max d'entrees dans la base recall
retention_days = 30 # Retention des entrees
# database_path = "/custom/recall.db" # Chemin personnalise (optionnel)
# Une ancienne section [tee] reste reconnue : mappee vers mode = "tee",
# ou "disabled" si enabled = false
[telemetry]
enabled = false # Telemetrie anonyme (1 ping/jour, requiert consentement)
@@ -1354,40 +1356,56 @@ exclude_commands = [] # Commandes a exclure de la recriture automatique
| Variable | Description |
|----------|-------------|
| `RTK_TEE_DIR` | Surcharge le repertoire tee |
| `RTK_RECALL=0` | Desactiver la sauvegarde recall |
| `RTK_TEE_DIR` | Surcharge le repertoire tee (mode "tee") |
| `RTK_TELEMETRY_DISABLED=1` | Desactiver la telemetrie |
| `RTK_HOOK_AUDIT=1` | Activer l'audit du hook |
| `SKIP_ENV_VALIDATION=1` | Desactiver la validation d'env (Next.js, etc.) |
---
## Systeme Tee
## Systeme Recall
### Recuperation de sortie brute
Quand une commande echoue, RTK sauvegarde automatiquement la sortie brute complete dans un fichier log. Cela permet au LLM de lire la sortie sans re-executer la commande.
Quand une commande echoue (ou qu'un filtre tronque une liste), RTK sauvegarde la sortie brute complete dans une base SQLite locale, adressee par hash de contenu. Cela permet au LLM de recuperer la sortie sans re-executer la commande.
**Fonctionnement :**
1. La commande echoue (exit code != 0)
2. RTK sauvegarde la sortie brute dans `~/.local/share/rtk/tee/`
3. Le chemin du fichier est affiche dans la sortie filtree
4. Le LLM peut lire le fichier si besoin de plus de details
1. La commande echoue (exit code != 0) ou la sortie est tronquee
2. RTK stocke la sortie brute (gzip) dans `~/.local/share/rtk/recall.db`
3. Un hint avec le hash est affiche : `[full output: rtk recall <hash>]` ou `[+N hidden: rtk recall <hash>]`
4. `rtk recall <hash>` restitue la partie manquante (delta), `--full` la sortie complete
**Sortie :**
```
FAILED: 2/15 tests
[full output: ~/.local/share/rtk/tee/1707753600_cargo_test.log]
**Commandes :**
```bash
rtk recall <hash> # Partie non montree (delta)
rtk recall <hash> --full # Sortie complete
rtk recall <hash> --grep RE # Filtrer par regex
rtk recall --list # Lister les entrees
rtk gain --recalls # Taux de consultation par filtre (calibration des caps)
rtk config recall <mode> # Changer de mode sans editer la config (sqlite|tee|disabled)
```
`rtk gain --recalls` separe strictement les donnees par mode : taux exact en sqlite
(la lecture passe par `rtk recall`), approximation (`≥`) en tee (seules les lectures
bash sont detectables via le hook, pas l'outil Read). Un taux eleve signale un filtre
qui cache des sorties que l'agent revient chercher.
**Configuration :**
| Parametre | Defaut | Description |
|-----------|--------|-------------|
| `tee.enabled` | `true` | Activer/desactiver |
| `tee.mode` | `"failures"` | `"failures"`, `"always"`, `"never"` |
| `tee.max_files` | `20` | Rotation : garder les N derniers |
| Taille min | 500 octets | Les sorties trop courtes ne sont pas sauvegardees |
| Taille max fichier | 1 Mo | Troncature au-dela |
| `retriever.mode` | `"sqlite"` | `"sqlite"`, `"tee"` (fichiers legacy), `"disabled"` |
| `retriever.max_entries` | `200` | Eviction FIFO au-dela |
| `retriever.retention_days` | `30` | Purge des entrees anciennes |
| `retriever.max_entry_bytes` | `10 Mo` | Troncature au-dela (a la derniere ligne complete) |
| Taille min | 500 octets | Les echecs trop courts ne sont pas sauvegardes |
Le mode `"tee"` conserve l'ancien comportement (fichiers `.log` dans `~/.local/share/rtk/tee/`, rotation `tee_max_files`). Une ancienne section `[tee]` en config est automatiquement mappee (voir plus haut).
Le mode se change avec `rtk config recall <sqlite|tee|disabled>` (edition chirurgicale de
config.toml, commentaires preserves, champs `[tee]` legacy migres) — le champ equivalent
en edition manuelle est `[retriever] mode`.
---
@@ -1395,7 +1413,7 @@ FAILED: 2/15 tests
RTK peut envoyer un ping anonyme une fois par jour (23h d'intervalle) pour des statistiques d'utilisation. La telemetrie est **desactivee par defaut** et requiert un consentement explicite (RGPD Art. 6, 7).
**Donnees envoyees :** hash de device (SHA-256 d'un sel aleatoire), version, OS, architecture, nombre de commandes/24h, top commandes, pourcentage de reduction de sortie bash.
**Donnees envoyees :** hash de device (SHA-256 d'un sel aleatoire), version, OS, architecture, nombre de commandes/24h, top commandes, pourcentage de reduction de sortie bash, compteurs recall par famille de filtre (elisions/consultations — noms issus d'une allowlist fermee, jamais de hash, chemin, argument ou contenu).
**Responsable du traitement :** `RTK AI Labs`, contact@rtk-ai.app
+4
View File
@@ -215,6 +215,8 @@ count_find_names() {
/^ext: / { next } # extension histogram footer
/^\.\.\. \(/ { next } # "... (8 filtered)" disclosure note
/^\[see remaining: / { next } # tee pointer for the disclosed entries
/^\[\+[0-9]+ hidden: / { next } # sqlite recall pointer, same role
/^\[full output: / { next } # sqlite recall pointer for a whole capture
NF == 0 { next }
{ n += NF - ($1 ~ /\/$/ ? 1 : 0) } # grouped lines lead with "dir/"
END { print n + 0 }
@@ -230,6 +232,8 @@ count_find_total() {
/^ext: / { next }
/^\.\.\. \(/ { next }
/^\[see remaining: / { next }
/^\[\+[0-9]+ hidden: / { next }
/^\[full output: / { next }
NF == 0 { next }
{ shown += NF - ($1 ~ /\/$/ ? 1 : 0) }
END { print (total ? total : shown + more) + 0 }
+153 -2
View File
@@ -24,10 +24,14 @@ pub fn run(
all: bool,
format: &str,
failures: bool,
recalls: bool,
reset: bool,
yes: bool,
_verbose: u8,
) -> Result<()> {
if recalls && !reset {
return show_recall_stats();
}
let tracker = Tracker::new().context("Failed to initialize tracking database")?;
let project_scope = resolve_project_scope(project)?; // added: resolve project path
@@ -39,7 +43,11 @@ pub fn run(
tracker
.reset_all()
.context("Failed to reset token savings")?;
println!("{}", styled("Token savings stats reset to zero.", true));
crate::core::retriever::reset_stats().context("Failed to reset recall stats")?;
println!(
"{}",
styled("Token savings and recall stats reset to zero.", true)
);
return Ok(());
}
@@ -76,6 +84,14 @@ pub fn run(
.get_summary_filtered(project_scope.as_deref()) // changed: use filtered variant
.context("Failed to load token savings summary from database")?;
if crate::core::tee_file::legacy_tee_migration_pending() {
eprintln!(
"{}",
format!("[rtk] {}", crate::core::tee_file::LEGACY_TEE_NOTICE).yellow()
);
eprintln!();
}
if summary.total_commands == 0 {
println!("No tracking data yet.");
println!("Run some rtk commands to start tracking savings.");
@@ -419,6 +435,113 @@ fn print_efficiency_meter(pct: f64) {
}
}
const VERDICT_MIN_ELISIONS: i64 = 5;
const VERDICT_WIDTH: usize = 14;
const ISSUES_URL: &str = "https://github.com/rtk-ai/rtk/issues";
/// Bands match `colorize_recall_rate` so the colour and the wording never disagree.
fn recall_verdict(elisions: i64, recalls: i64) -> &'static str {
if elisions < VERDICT_MIN_ELISIONS {
return "-";
}
match recalls * 100 / elisions {
p if p >= 30 => "too aggressive",
p if p >= 10 => "watch",
_ => "ok",
}
}
fn colorize_recall_rate(pct: i64, padded: &str) -> String {
if !std::io::stdout().is_terminal() {
return padded.to_string();
}
if pct >= 30 {
padded.red().bold().to_string()
} else if pct >= 10 {
padded.yellow().bold().to_string()
} else {
padded.green().bold().to_string()
}
}
fn show_recall_stats() -> Result<()> {
use crate::core::retriever::RecoveryMode;
let mode = crate::core::config::Config::load()
.unwrap_or_default()
.retriever
.mode;
let mode_label = match mode {
RecoveryMode::Sqlite => "sqlite",
RecoveryMode::Tee => "tee",
RecoveryMode::Disabled => "disabled",
};
let stats = crate::core::retriever::stats_snapshot()?;
println!("{}", styled("RTK Recall Efficiency", true));
println!("{}", "═".repeat(60));
println!("Mode: {mode_label}");
println!();
if stats.is_empty() {
println!("No recall activity recorded yet.");
println!("Stats appear once filters elide output (failures, trimmed lists).");
return Ok(());
}
let slug_width = stats
.iter()
.map(|s| s.slug.chars().count())
.max()
.unwrap_or(6)
.clamp(6, 24);
let table_width = slug_width + 2 + 8 + 2 + 8 + 2 + 6 + 2 + VERDICT_WIDTH;
let render = |title: &str, mode_key: &str, prefix: &str| {
let rows: Vec<_> = stats.iter().filter(|s| s.mode == mode_key).collect();
if rows.is_empty() {
return;
}
println!("{}", styled(title, true));
println!("{}", "─".repeat(table_width));
println!(
"{:<slug_width$} {:>8} {:>8} {:>6} Verdict",
"Filter", "Elisions", "Recalled", "Rate"
);
println!("{}", "─".repeat(table_width));
for s in rows {
let (pct, rate) = if s.elisions > 0 {
let pct = s.recalls * 100 / s.elisions;
(pct, format!("{prefix}{pct}%"))
} else {
(0, "-".to_string())
};
println!(
"{} {:>8} {:>8} {} {}",
truncate_for_column(&s.slug, slug_width),
s.elisions,
s.recalls,
colorize_recall_rate(pct, &format!("{rate:>6}")),
colorize_recall_rate(pct, recall_verdict(s.elisions, s.recalls))
);
}
println!();
};
render("Sqlite (exact — reads go through rtk recall)", "sqlite", "");
render("Tee (approximate — bash-observed reads only)", "tee", "≥");
println!("\"too aggressive\" means the filter hides output the agent comes back for.");
println!("Each recall costs an extra API turn plus the full output, so it cancels");
println!("the savings on that command instead of adding to them.");
println!(
"\"-\" means fewer than {VERDICT_MIN_ELISIONS} elisions so far: not enough data to judge."
);
println!();
println!("Raise that filter's cap, or report it: {ISSUES_URL}");
Ok(())
}
/// Resolve project scope from --project flag. // added
fn resolve_project_scope(project: bool) -> Result<Option<String>> {
if !project {
@@ -743,7 +866,7 @@ fn show_failures(tracker: &Tracker) -> Result<()> {
fn confirm_reset() -> Result<bool> {
use std::io::{self, BufRead, IsTerminal, Write};
eprint!("This will permanently delete all tracking data. Continue? [y/N] ");
eprint!("This will permanently delete all tracking data and recall counters (stored outputs are kept). Continue? [y/N] ");
io::stderr().flush().ok();
if !io::stdin().is_terminal() {
@@ -760,3 +883,31 @@ fn confirm_reset() -> Result<bool> {
Ok(matches!(line.trim().to_lowercase().as_str(), "y" | "yes"))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_recall_verdict_needs_a_sample_before_judging() {
assert_eq!(recall_verdict(4, 4), "-");
assert_eq!(recall_verdict(0, 0), "-");
assert_eq!(recall_verdict(5, 5), "too aggressive");
}
#[test]
fn test_recall_verdict_bands_match_the_colour_bands() {
assert_eq!(recall_verdict(100, 29), "watch");
assert_eq!(recall_verdict(100, 30), "too aggressive");
assert_eq!(recall_verdict(100, 9), "ok");
assert_eq!(recall_verdict(100, 10), "watch");
assert_eq!(recall_verdict(100, 0), "ok");
}
#[test]
fn test_recall_verdict_fits_its_column() {
for v in ["-", "ok", "watch", "too aggressive"] {
assert!(v.len() <= VERDICT_WIDTH, "{v} overflows the column");
}
}
}
+1 -1
View File
@@ -265,7 +265,7 @@ When a filter caps a list at N items (e.g. `take(20)`), the remaining items must
**Cap values come from `src/core/truncate.rs`.** Pick the `CAP_*` matching your data class (`CAP_ERRORS`, `CAP_WARNINGS`, `CAP_LIST`, `CAP_INVENTORY`) and bind it to a local `const MAX_XXX: usize = CAP_Y;`. Derive `take(MAX_XXX)`, `> MAX_XXX`, and the offset `MAX_XXX + 1` from the local. These CAPs will later become the configuration surface for per-filter cap tuning (user-overridable via config) — keep all truncation values routed through them so that hook lands as a single switch rather than a codebase-wide hunt. A filter that genuinely needs to deviate uses **`truncate::reduced(CAP_Y, n)`** (e.g. `reduced(CAP_WARNINGS, 5)`) so it still tracks the global when reconfigured — never a bare literal, never `cap - n` (underflows once caps are runtime-configurable), and never `*`/`/` (those scale unboundedly). `reduced` falls back to the full cap if the reduction would empty the list. Each deviation needs a one-line comment stating why; if there's no real reason, just use the plain CAP. See `src/core/README.md` ("Truncation Caps") for the full rationale.
**The tee content must match what `tail` produces.** For `force_tee_tail_hint`, build the tee from the same formatted values shown in the output — not raw/intermediate data. If the filter reformats items before displaying them, pre-build a `Vec<String>` of formatted lines and use it for both the display loop and the tee.
**The stored content must match what was shown.** For `force_tee_tail_hint`, build the recall blob from the same formatted values displayed — not raw/intermediate data — and pass the 1-based first-hidden line as `offset`. `rtk recall <hash>` slices the stored content from that offset, so the agent gets exactly the hidden items. If the filter reformats items before displaying them, pre-build a `Vec<String>` of formatted lines and use it for both the display loop and the recall blob.
### Stderr Handling
+5 -2
View File
@@ -1773,7 +1773,10 @@ some unrelated tail
assert_eq!(
filtered
.lines()
.filter(|line| line.trim_start().starts_with("[see remaining:"))
.filter(|line| {
let t = line.trim_start();
t.starts_with("[see remaining:") || t.starts_with("[+")
})
.count(),
1
);
@@ -1801,7 +1804,7 @@ some unrelated tail
MAX_FAILED_LIST_LINES
);
assert!(filtered.contains(" ... +5 more skipped"));
assert!(filtered.contains(" [see remaining:"));
assert!(filtered.contains(" [see remaining:") || filtered.contains(" [+"));
}
#[test]
+4 -4
View File
@@ -516,12 +516,12 @@ mod tests {
!hint.contains("full output"),
"must not point at already-seen output: {hint}"
);
// Tee availability depends on environment; when present the hint is
// the standard one-shot retrieval command over the hidden-only file.
// Recovery availability depends on environment; when present the hint
// is the standard one-shot retrieval command over the hidden entries.
if hint.lines().count() > 1 {
assert!(
hint.contains("[see remaining: tail -n +1 "),
"tee hint must be the standard tail form: {hint}"
hint.contains("[see remaining: tail -n +1 ") || hint.contains("hidden: rtk recall "),
"recovery hint must be a standard retrieval form: {hint}"
);
}
}
+14 -10
View File
@@ -71,12 +71,16 @@ colors = true
emoji = true
max_width = 120
[tee]
enabled = true
mode = "failures" # failures | always | never
max_files = 20
max_file_size = 1048576
directory = "/custom/tee/dir"
[retriever]
mode = "sqlite" # sqlite (default) | tee (legacy files) | disabled
max_entry_bytes = 10485760 # sqlite: 10 MiB per entry
max_entries = 200 # sqlite: FIFO cap
retention_days = 30 # sqlite: 0 disables age eviction
compression = true # sqlite: gzip blobs (lossless)
# database_path = "/custom/recall.db"
tee_max_files = 20 # tee mode: rotation
tee_max_file_size = 1048576 # tee mode: per-file cap
# tee_directory = "/custom/tee/dir"
[telemetry]
enabled = true
@@ -115,13 +119,13 @@ Core provides infrastructure that `cmds/` and other components consume. These co
Consumers must call `timer.track()` on **all** code paths — success, failure, and fallback. Calling `std::process::exit()` before `track()` loses metrics. The raw string passed to `track()` should include both stdout and stderr to produce accurate savings percentages.
### Tee (`tee_and_hint`)
### Output recovery (`tee_and_hint` + recall store)
Consumers that parse structured output (JSON, NDJSON, state machines) should call `tee::tee_and_hint()` to save raw output for LLM recovery on failure. Tee must be called before `std::process::exit()`.
Consumers that parse structured output (JSON, NDJSON, state machines) should call `tee::tee_and_hint()` to persist raw output for LLM recovery on failure. It must be called before `std::process::exit()`.
For truncation recovery on **success** (e.g., list truncated at 20 items), use `tee::force_tee_hint()` which bypasses the tee mode check and writes regardless of exit code. This ensures LLMs always have a `[full output: ...]` recovery path instead of burning tokens working around missing data.
For truncation recovery on **success** (e.g. a list capped at 20 items), use `tee::force_tee_hint()` (multi-line blocks) or `tee::force_tee_tail_hint(content, slug, offset)` (flat lists). All three persist the full output to the content-addressed recall store ([`retriever.rs`](retriever.rs)) and emit a runnable hint — `[full output: rtk recall <hash>]` or `[+N hidden: rtk recall <hash>]` — instead of burning tokens working around missing data.
When the truncated output is a **flat list** and the hidden items start at a predictable line, prefer `tee::force_tee_tail_hint(content, slug, offset)`. It writes the same tee file but emits a directly runnable hint — `[see remaining: tail -n +{offset} ~/path]` — so the agent jumps to exactly the first hidden item without scanning the whole file. The offset is `header_lines + MAX_CAP + 1`. Use `force_tee_hint` instead when the output has multiple sections (e.g. running + stopped containers) and no single offset cleanly covers the gap.
The agent runs `rtk recall <hash>` to get back exactly what was elided. For `force_tee_tail_hint`, `offset` is the 1-based first hidden line (`header_lines + MAX_CAP + 1`); it is stored so the default recall returns only the hidden tail. Storage is byte-faithful (`BLOB` + lossless gzip); tune limits via the `[retriever]` config section.
### Truncation Caps (`truncate`)
+438 -3
View File
@@ -14,7 +14,13 @@ pub struct Config {
#[serde(default)]
pub filters: FilterConfig,
#[serde(default)]
pub tee: crate::core::tee::TeeConfig,
pub retriever: crate::core::retriever::RetrieverConfig,
#[serde(default, skip_serializing_if = "Option::is_none")]
tee: Option<LegacyTeeConfig>,
#[serde(skip)]
pub migrated_from_legacy_tee: bool,
#[serde(skip)]
pub legacy_tee_fields_merged: bool,
#[serde(default)]
pub telemetry: TelemetryConfig,
#[serde(default)]
@@ -62,6 +68,51 @@ pub struct AwarenessConfig {
pub level: AwarenessLevel,
}
#[derive(Debug, Serialize, Deserialize, Default)]
#[serde(default)]
struct LegacyTeeConfig {
enabled: Option<bool>,
mode: Option<String>,
max_files: Option<usize>,
max_file_size: Option<usize>,
directory: Option<PathBuf>,
}
struct LegacyMapping {
mode: Option<crate::core::retriever::RecoveryMode>,
tee_on_success: Option<bool>,
tee_max_files: Option<usize>,
tee_max_file_size: Option<usize>,
tee_directory: Option<PathBuf>,
}
/// The single source of truth for mapping a legacy `[tee]` section onto
/// `[retriever]`, shared by `Config::load()` and `rtk config recall` so the
/// two paths can never disagree on the same input.
fn map_legacy_tee(
tee: &LegacyTeeConfig,
has_retriever: bool,
explicit_retriever_keys: &[String],
) -> LegacyMapping {
use crate::core::retriever::RecoveryMode;
let explicit = |key: &str| explicit_retriever_keys.iter().any(|k| k == key);
let mode = if has_retriever {
None
} else if tee.enabled == Some(false) || tee.mode.as_deref() == Some("never") {
Some(RecoveryMode::Disabled)
} else {
Some(RecoveryMode::Tee)
};
LegacyMapping {
mode,
tee_on_success: (tee.mode.as_deref() == Some("always") && !explicit("tee_on_success"))
.then_some(true),
tee_max_files: tee.max_files.filter(|_| !explicit("tee_max_files")),
tee_max_file_size: tee.max_file_size.filter(|_| !explicit("tee_max_file_size")),
tee_directory: tee.directory.clone().filter(|_| !explicit("tee_directory")),
}
}
#[derive(Debug, Serialize, Deserialize, Default)]
pub struct HooksConfig {
/// Commands to exclude from auto-rewrite (e.g. ["curl", "playwright"]).
@@ -229,13 +280,58 @@ impl Config {
if path.exists() {
let content = std::fs::read_to_string(&path)?;
let config: Config = toml::from_str(&content)?;
Ok(config)
Self::from_toml(&content)
} else {
Ok(Config::default())
}
}
fn from_toml(content: &str) -> Result<Self> {
let value: toml::Value = toml::from_str(content)?;
let explicit: Vec<String> = value
.get("retriever")
.and_then(|r| r.as_table())
.map(|t| t.keys().cloned().collect())
.unwrap_or_default();
let has_retriever = value.get("retriever").is_some();
let mut config = Config::deserialize(value)?;
config.migrate_legacy_tee(has_retriever, &explicit);
Ok(config)
}
fn migrate_legacy_tee(&mut self, has_retriever: bool, explicit_retriever_keys: &[String]) {
let Some(tee) = self.tee.take() else {
return;
};
use crate::core::retriever::RecoveryMode;
let mapping = map_legacy_tee(&tee, has_retriever, explicit_retriever_keys);
let r = &mut self.retriever;
if let Some(mode) = mapping.mode {
r.mode = mode;
if mode == RecoveryMode::Tee {
self.migrated_from_legacy_tee = true;
}
}
if let Some(v) = mapping.tee_on_success {
r.tee_on_success = v;
}
let merged = mapping.tee_max_files.is_some()
|| mapping.tee_max_file_size.is_some()
|| mapping.tee_directory.is_some();
if let Some(v) = mapping.tee_max_files {
r.tee_max_files = v;
}
if let Some(v) = mapping.tee_max_file_size {
r.tee_max_file_size = v;
}
if let Some(d) = mapping.tee_directory {
r.tee_directory = Some(d);
}
if has_retriever && merged {
self.legacy_tee_fields_merged = true;
}
}
pub fn save(&self) -> Result<()> {
let path = get_config_path()?;
@@ -255,6 +351,110 @@ impl Config {
}
}
fn apply_recall_mode(content: &str, mode: crate::core::retriever::RecoveryMode) -> Result<String> {
use crate::core::retriever::RecoveryMode;
let mut doc: toml_edit::DocumentMut = content
.parse()
.map_err(|e| anyhow::anyhow!("config.toml is not valid TOML: {e}"))?;
let legacy = doc.remove("tee");
let retriever_is_table = doc
.get("retriever")
.is_some_and(|item| item.as_table_like().is_some());
if !retriever_is_table {
doc["retriever"] = toml_edit::Item::Table(toml_edit::Table::new());
}
let mode_str = match mode {
RecoveryMode::Sqlite => "sqlite",
RecoveryMode::Tee => "tee",
RecoveryMode::Disabled => "disabled",
};
doc["retriever"]["mode"] = toml_edit::value(mode_str);
if let Some(legacy) = legacy.as_ref().and_then(|i| i.as_table_like()) {
let tee = LegacyTeeConfig {
enabled: legacy
.get("enabled")
.and_then(|i| i.as_value())
.and_then(|v| v.as_bool()),
mode: legacy
.get("mode")
.and_then(|i| i.as_value())
.and_then(|v| v.as_str())
.map(str::to_string),
max_files: legacy
.get("max_files")
.and_then(|i| i.as_value())
.and_then(|v| v.as_integer())
.map(|n| n as usize),
max_file_size: legacy
.get("max_file_size")
.and_then(|i| i.as_value())
.and_then(|v| v.as_integer())
.map(|n| n as usize),
directory: legacy
.get("directory")
.and_then(|i| i.as_value())
.and_then(|v| v.as_str())
.map(PathBuf::from),
};
let explicit_keys: Vec<String> = doc["retriever"]
.as_table_like()
.map(|t| t.iter().map(|(k, _)| k.to_string()).collect())
.unwrap_or_default();
let mapping = map_legacy_tee(&tee, true, &explicit_keys);
if let Some(v) = mapping.tee_max_files {
doc["retriever"]["tee_max_files"] = toml_edit::value(v as i64);
}
if let Some(v) = mapping.tee_max_file_size {
doc["retriever"]["tee_max_file_size"] = toml_edit::value(v as i64);
}
if let Some(d) = mapping.tee_directory {
doc["retriever"]["tee_directory"] = toml_edit::value(d.to_string_lossy().as_ref());
}
if mapping.tee_on_success == Some(true) && mode == RecoveryMode::Tee {
doc["retriever"]["tee_on_success"] = toml_edit::value(true);
}
}
Ok(doc.to_string())
}
pub fn set_recall_mode(mode: crate::core::retriever::RecoveryMode) -> Result<PathBuf> {
let path = get_config_path()?;
let content = if path.exists() {
std::fs::read_to_string(&path)?
} else {
String::new()
};
let updated = apply_recall_mode(&content, mode)?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(&path, updated)?;
Ok(path)
}
pub fn show_recall_mode() -> Result<()> {
use crate::core::retriever::RecoveryMode;
let config = Config::load().unwrap_or_default();
let mode = match config.retriever.mode {
RecoveryMode::Sqlite => "sqlite",
RecoveryMode::Tee => "tee",
RecoveryMode::Disabled => "disabled",
};
println!("recall mode: {mode}");
if config.migrated_from_legacy_tee {
println!("source: legacy [tee] section (auto-migrated at load)");
}
if std::env::var("RTK_RECALL").ok().as_deref() == Some("0")
|| std::env::var("RTK_TEE").ok().as_deref() == Some("0")
{
println!("note: RTK_RECALL=0/RTK_TEE=0 is set — recovery disabled for this environment");
}
println!("change with: rtk config recall <sqlite|tee|disabled>");
Ok(())
}
fn get_config_path() -> Result<PathBuf> {
let config_dir = dirs::config_dir().unwrap_or_else(|| PathBuf::from("."));
Ok(config_dir.join(RTK_DATA_DIR).join(CONFIG_TOML))
@@ -418,4 +618,239 @@ consent_date = "2026-04-10T12:00:00Z"
Some("2026-04-10T12:00:00Z")
);
}
#[test]
fn test_legacy_tee_disabled_maps_to_disabled_mode() {
use crate::core::retriever::RecoveryMode;
let toml = r#"
[tee]
enabled = false
"#;
let config = Config::from_toml(toml).expect("valid toml");
assert_eq!(config.retriever.mode, RecoveryMode::Disabled);
}
#[test]
fn test_legacy_tee_never_mode_maps_to_disabled_mode() {
use crate::core::retriever::RecoveryMode;
let toml = r#"
[tee]
mode = "never"
"#;
let config = Config::from_toml(toml).expect("valid toml");
assert_eq!(config.retriever.mode, RecoveryMode::Disabled);
}
#[test]
fn test_legacy_tee_section_maps_to_tee_mode_with_fields() {
use crate::core::retriever::RecoveryMode;
let toml = r#"
[tee]
enabled = true
mode = "failures"
max_files = 7
max_file_size = 4096
directory = "/custom/tee"
"#;
let config = Config::from_toml(toml).expect("valid toml");
assert_eq!(config.retriever.mode, RecoveryMode::Tee);
assert_eq!(config.retriever.tee_max_files, 7);
assert_eq!(config.retriever.tee_max_file_size, 4096);
assert_eq!(
config.retriever.tee_directory,
Some(PathBuf::from("/custom/tee"))
);
}
#[test]
fn test_retriever_section_wins_over_legacy_tee() {
use crate::core::retriever::RecoveryMode;
let toml = r#"
[retriever]
mode = "sqlite"
[tee]
enabled = false
"#;
let config = Config::from_toml(toml).expect("valid toml");
assert_eq!(config.retriever.mode, RecoveryMode::Sqlite);
}
#[test]
fn test_migrated_flag_set_only_on_legacy_migration() {
let migrated = Config::from_toml("[tee]\nenabled = true\n").expect("valid");
assert!(migrated.migrated_from_legacy_tee);
let explicit = Config::from_toml("[retriever]\nmode = \"tee\"\n\n[tee]\nenabled = true\n")
.expect("valid");
assert!(!explicit.migrated_from_legacy_tee);
let fresh = Config::from_toml("").expect("valid");
assert!(!fresh.migrated_from_legacy_tee);
}
#[test]
fn test_coexisting_tee_fields_merge_as_fallback() {
use crate::core::retriever::RecoveryMode;
let toml = "[retriever]\nretention_days = 90\nmode = \"tee\"\n\n[tee]\nmax_files = 100\ndirectory = \"/mnt/big-disk/tee\"\n";
let config = Config::from_toml(toml).expect("valid");
assert_eq!(config.retriever.mode, RecoveryMode::Tee);
assert_eq!(config.retriever.retention_days, 90);
assert_eq!(config.retriever.tee_max_files, 100);
assert_eq!(
config.retriever.tee_directory,
Some(PathBuf::from("/mnt/big-disk/tee"))
);
assert!(!config.migrated_from_legacy_tee);
}
#[test]
fn test_explicit_retriever_field_beats_legacy_tee_field() {
let toml = "[retriever]\ntee_max_files = 5\n\n[tee]\nmax_files = 100\n";
let config = Config::from_toml(toml).expect("valid");
assert_eq!(config.retriever.tee_max_files, 5);
}
#[test]
fn test_legacy_always_is_preserved_not_downgraded() {
use crate::core::retriever::RecoveryMode;
let config = Config::from_toml("[tee]\nmode = \"always\"\n").expect("valid");
assert_eq!(config.retriever.mode, RecoveryMode::Tee);
assert!(
config.retriever.tee_on_success,
"legacy always must keep archiving successful runs"
);
let failures = Config::from_toml("[tee]\nmode = \"failures\"\n").expect("valid");
assert!(!failures.retriever.tee_on_success);
let rewritten = apply_recall_mode("[tee]\nmode = \"always\"\n", RecoveryMode::Tee)
.expect("valid rewrite");
assert!(
Config::from_toml(&rewritten)
.unwrap()
.retriever
.tee_on_success,
"rtk config recall must carry the always intent over too"
);
}
#[test]
fn test_notice_flags_track_migration_outcome() {
let disabled = Config::from_toml("[tee]\nenabled = false\n").expect("valid");
assert!(
!disabled.migrated_from_legacy_tee,
"a user who disabled tee must not get the file-mode-kept notice"
);
let kept = Config::from_toml("[tee]\nenabled = true\n").expect("valid");
assert!(kept.migrated_from_legacy_tee);
let merged =
Config::from_toml("[retriever]\nretention_days = 90\n\n[tee]\nmax_files = 100\n")
.expect("valid");
assert!(
merged.legacy_tee_fields_merged,
"coexisting legacy values still in effect must be disclosed"
);
assert!(!merged.migrated_from_legacy_tee);
let clean = Config::from_toml("[retriever]\nmode = \"sqlite\"\n").expect("valid");
assert!(!clean.legacy_tee_fields_merged);
}
#[test]
fn test_migration_paths_agree_on_every_legacy_shape() {
let modes = [
"",
"mode = \"failures\"\n",
"mode = \"always\"\n",
"mode = \"never\"\n",
];
let enableds = ["", "enabled = true\n", "enabled = false\n"];
let retrievers = [
"",
"[retriever]\nretention_days = 90\n\n",
"[retriever]\ntee_max_files = 5\n\n",
];
for m in modes {
for e in enableds {
for r in retrievers {
let orig = format!("{r}[tee]\n{m}{e}max_files = 100\ndirectory = \"/big\"\n");
let loaded = Config::from_toml(&orig).expect("load").retriever;
let rewritten = apply_recall_mode(&orig, loaded.mode).expect("apply");
let reloaded = Config::from_toml(&rewritten).expect("reload").retriever;
assert_eq!(
(
loaded.mode,
loaded.tee_max_files,
loaded.tee_max_file_size,
loaded.tee_directory.clone()
),
(
reloaded.mode,
reloaded.tee_max_files,
reloaded.tee_max_file_size,
reloaded.tee_directory.clone()
),
"Config::load and rtk config recall must agree on: {orig}"
);
}
}
}
}
#[test]
fn test_no_tee_section_defaults_to_sqlite() {
use crate::core::retriever::RecoveryMode;
let config = Config::from_toml("").expect("valid toml");
assert_eq!(config.retriever.mode, RecoveryMode::Sqlite);
}
#[test]
fn test_apply_recall_mode_preserves_other_content() {
use crate::core::retriever::RecoveryMode;
let input = "# my personal notes\n[hooks]\nexclude_commands = [\"curl\"]\n\n[tee]\nenabled = true\nmode = \"failures\"\n";
let out = apply_recall_mode(input, RecoveryMode::Sqlite).expect("valid");
assert!(out.contains("# my personal notes"));
assert!(out.contains("exclude_commands = [\"curl\"]"));
assert!(!out.contains("[tee]"), "legacy section must be removed");
assert!(out.contains("[retriever]"));
assert!(out.contains("mode = \"sqlite\""));
let reparsed = Config::from_toml(&out).expect("output must stay valid");
assert_eq!(reparsed.retriever.mode, RecoveryMode::Sqlite);
}
#[test]
fn test_apply_recall_mode_updates_existing_retriever() {
use crate::core::retriever::RecoveryMode;
let input = "[retriever]\nmode = \"sqlite\"\nmax_entries = 50\n";
let out = apply_recall_mode(input, RecoveryMode::Tee).expect("valid");
assert!(out.contains("mode = \"tee\""));
assert!(out.contains("max_entries = 50"), "sibling keys preserved");
}
#[test]
fn test_apply_recall_mode_replaces_scalar_retriever_key() {
use crate::core::retriever::RecoveryMode;
let out = apply_recall_mode("retriever = \"sqlite\"\n", RecoveryMode::Tee)
.expect("must not panic on a scalar retriever key");
let reparsed = Config::from_toml(&out).expect("valid output");
assert_eq!(reparsed.retriever.mode, RecoveryMode::Tee);
}
#[test]
fn test_apply_recall_mode_from_empty_file() {
use crate::core::retriever::RecoveryMode;
let out = apply_recall_mode("", RecoveryMode::Disabled).expect("valid");
let reparsed = Config::from_toml(&out).expect("valid output");
assert_eq!(reparsed.retriever.mode, RecoveryMode::Disabled);
}
#[test]
fn test_apply_recall_mode_carries_legacy_tee_fields() {
use crate::core::retriever::RecoveryMode;
let input = "[tee]\nmax_files = 7\ndirectory = \"/custom/tee\"\n";
let out = apply_recall_mode(input, RecoveryMode::Tee).expect("valid");
let reparsed = Config::from_toml(&out).expect("valid output");
assert_eq!(reparsed.retriever.mode, RecoveryMode::Tee);
assert_eq!(reparsed.retriever.tee_max_files, 7);
assert_eq!(
reparsed.retriever.tee_directory,
Some(PathBuf::from("/custom/tee"))
);
}
}
+2
View File
@@ -1,5 +1,6 @@
pub const RTK_DATA_DIR: &str = "rtk";
pub const HISTORY_DB: &str = "history.db";
pub const RECALL_DB: &str = "recall.db";
pub const CONFIG_TOML: &str = "config.toml";
pub const FILTERS_TOML: &str = "filters.toml";
pub const TRUSTED_FILTERS_JSON: &str = "trusted_filters.json";
@@ -14,6 +15,7 @@ pub const RTK_META_COMMANDS: &[&str] = &[
"init",
"config",
"proxy",
"recall",
"run",
"hook",
"hook-audit",
+2
View File
@@ -6,9 +6,11 @@ pub mod constants;
pub mod display_helpers;
pub mod filter;
pub mod guard;
pub mod retriever;
pub mod runner;
pub mod stream;
pub mod tee;
pub mod tee_file;
pub mod telemetry;
pub mod telemetry_cmd;
pub mod toml_filter;
File diff suppressed because it is too large. Load diff
+129 -674
View File
@@ -1,353 +1,107 @@
//! Raw output recovery -- saves unfiltered output to disk on command failure.
//! Recovery-hint dispatch — routes to the sqlite store or legacy tee per `[retriever] mode`.
use super::constants::RTK_DATA_DIR;
use crate::core::config::Config;
use std::path::PathBuf;
pub(crate) use crate::core::retriever::MIN_FAILURE_BYTES as MIN_TEE_SIZE;
use crate::core::retriever::{self, RecoveryMode, RetrieverConfig, Stored, MIN_FAILURE_BYTES};
/// Minimum output size to tee (smaller outputs don't need recovery)
pub(crate) const MIN_TEE_SIZE: usize = 500;
/// Default max files to keep in tee directory
const DEFAULT_MAX_FILES: usize = 20;
/// Default max file size (1MB)
const DEFAULT_MAX_FILE_SIZE: usize = 1_048_576;
/// Sanitize a command slug for use in filenames.
/// Replaces non-alphanumeric chars (except underscore/hyphen) with underscore.
/// Long slugs (usually an embedded file path that duplicates the command the LLM
/// already issued) collapse to a short readable prefix plus a short disambiguating
/// hash, keeping recovery filenames unique but compact — fewer tokens per tee hint.
fn sanitize_slug(slug: &str) -> String {
let sanitized: String = slug
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
c
} else {
'_'
}
})
.collect();
const MAX_READABLE: usize = 24;
if sanitized.len() <= MAX_READABLE {
return sanitized;
}
let prefix: String = sanitized.chars().take(8).collect();
format!("{}_{}", prefix, short_hash(&sanitized))
}
/// First 6 hex chars (24 bits) of the SHA-256 of `s` — a compact tag to keep
/// shortened slugs distinct. Not collision-resistant on its own: 24 bits hits a
/// birthday collision after only a few thousand distinct slugs. It's safe here
/// because a clash also requires the identical readable prefix *and* the same
/// epoch second, which together scope tee writes exactly as before.
fn short_hash(s: &str) -> String {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(s.as_bytes()))[..6].to_string()
}
/// Get the tee directory, respecting config and env overrides.
fn get_tee_dir(config: &Config) -> Option<PathBuf> {
// Env var override
if let Ok(dir) = std::env::var("RTK_TEE_DIR") {
return Some(PathBuf::from(dir));
}
// Config override
if let Some(ref dir) = config.tee.directory {
return Some(dir.clone());
}
// Default: ~/.local/share/rtk/tee/
dirs::data_local_dir().map(|d| d.join(RTK_DATA_DIR).join("tee"))
}
/// Rotate old tee files: keep only the last `max_files`, delete oldest.
fn cleanup_old_files(dir: &std::path::Path, max_files: usize) {
let mut entries: Vec<_> = std::fs::read_dir(dir)
.ok()
.into_iter()
.flatten()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|ext| ext == "log"))
.collect();
if entries.len() <= max_files {
return;
}
// Sort by filename (which starts with epoch timestamp = chronological)
entries.sort_by_key(|e| e.file_name());
let to_remove = entries.len() - max_files;
for entry in entries.iter().take(to_remove) {
let _ = std::fs::remove_file(entry.path());
}
}
/// Check if tee should be skipped based on config, mode, exit code, and size.
/// Returns None if should skip, Some(tee_dir) if should proceed.
fn should_tee(
config: &TeeConfig,
raw_len: usize,
exit_code: i32,
tee_dir: Option<PathBuf>,
) -> Option<PathBuf> {
if !config.enabled {
fn active() -> Option<(RecoveryMode, RetrieverConfig)> {
if retriever::recovery_disabled_by_env() {
return None;
}
match Config::load().ok().map(|c| (c.retriever.mode, c.retriever)) {
Some((RecoveryMode::Disabled, _)) | None => None,
some => some,
}
}
match config.mode {
TeeMode::Never => return None,
TeeMode::Failures => {
fn store_hint(
cfg: &RetrieverConfig,
content: &str,
slug: &str,
exit_code: Option<i32>,
) -> Option<String> {
match retriever::store(cfg, content.as_bytes(), slug, exit_code, 1) {
Stored::Saved(s) => Some(format!("[full output: rtk recall {}]", s.hash)),
Stored::Unavailable | Stored::Empty => None,
}
}
/// Takes the resolved mode and config so tests never reach `Config::load()`,
/// mirroring `hooks::rewrite_cmd::evaluate_with_verdict` (#3146).
fn tee_and_hint_with(
mode: RecoveryMode,
cfg: &RetrieverConfig,
raw: &str,
command_slug: &str,
exit_code: i32,
) -> Option<String> {
match mode {
RecoveryMode::Disabled => None,
// Legacy tee semantics, unchanged: `failures` writes on failure only,
// `always` also archives successful runs whose output the filter shrank.
RecoveryMode::Tee => {
if exit_code == 0 && !cfg.tee_on_success {
return None;
}
super::tee_file::tee_and_hint(cfg, raw, command_slug).inspect(|_| {
if exit_code != 0 {
retriever::record_tee_elision(cfg, command_slug);
}
})
}
RecoveryMode::Sqlite => {
if exit_code == 0 {
return None;
}
}
TeeMode::Always => {}
}
if raw_len < MIN_TEE_SIZE {
return None;
}
tee_dir
}
/// Creates the parent as its own step, otherwise `create_dir_all` leaves the
/// data root at the umask as an intermediate.
fn create_tee_dir(tee_dir: &std::path::Path) -> Option<()> {
if let Some(parent) = tee_dir.parent() {
let _ = crate::core::utils::create_private_dir(parent);
}
crate::core::utils::create_private_dir(tee_dir).ok()
}
/// Write raw output to a tee file in the given directory.
/// Returns file path on success.
fn write_tee_file(
raw: &str,
command_slug: &str,
tee_dir: &std::path::Path,
max_file_size: usize,
max_files: usize,
) -> Option<PathBuf> {
create_tee_dir(tee_dir)?;
let slug = sanitize_slug(command_slug);
let epoch = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.ok()?
.as_secs();
let filename = format!("{}_{}.log", epoch, slug);
let filepath = tee_dir.join(filename);
// Truncate at max_file_size (find a safe UTF-8 char boundary)
let content = if raw.len() > max_file_size {
let boundary = raw
.char_indices()
.take_while(|(i, _)| *i < max_file_size)
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
format!(
"{}\n\n--- truncated at {} bytes ---",
&raw[..boundary],
max_file_size
)
} else {
raw.to_string()
};
let mut file = crate::core::utils::open_private(
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true),
&filepath,
)
.ok()?;
use std::io::Write;
file.write_all(content.as_bytes()).ok()?;
// Rotate old files
cleanup_old_files(tee_dir, max_files);
Some(filepath)
}
/// Write raw output to tee file if conditions are met.
/// Returns file path on success, None if skipped/failed.
pub fn tee_raw(raw: &str, command_slug: &str, exit_code: i32) -> Option<PathBuf> {
// Check RTK_TEE=0 env override (disable)
if std::env::var("RTK_TEE").ok().as_deref() == Some("0") {
return None;
}
let config = Config::load().ok()?;
let tee_dir = get_tee_dir(&config)?;
let tee_dir = should_tee(&config.tee, raw.len(), exit_code, Some(tee_dir))?;
write_tee_file(
raw,
command_slug,
&tee_dir,
config.tee.max_file_size,
config.tee.max_files,
)
}
fn display_path(path: &std::path::Path) -> String {
if let Some(home) = dirs::home_dir() {
if let Ok(relative) = path.strip_prefix(&home) {
return format!("~/{}", relative.display());
store_hint(cfg, raw, command_slug, Some(exit_code))
}
}
path.display().to_string()
}
fn needs_shell_quoting(path: &str) -> bool {
path.chars().any(|c| {
c.is_whitespace()
|| matches!(
c,
'\'' | '"'
| '\\'
| '$'
| '`'
| '!'
| '#'
| '&'
| '('
| ')'
| ';'
| '<'
| '>'
| '?'
| '['
| ']'
| '{'
| '}'
| '|'
| '*'
)
})
}
fn escape_double_quoted_path(path: &str) -> String {
let mut escaped = String::with_capacity(path.len());
for c in path.chars() {
if matches!(c, '\\' | '"' | '$' | '`') {
escaped.push('\\');
}
escaped.push(c);
}
escaped
}
fn display_shell_path(path: &std::path::Path) -> String {
let display = display_path(path);
if !needs_shell_quoting(&display) {
return display;
}
if let Some(relative) = display.strip_prefix("~/") {
let relative = relative.replace(std::path::MAIN_SEPARATOR, "/");
return format!("\"$HOME/{}\"", escape_double_quoted_path(&relative));
}
format!("\"{}\"", escape_double_quoted_path(&display))
}
fn format_hint(path: &std::path::Path) -> String {
format!("[full output: {}]", display_shell_path(path))
}
/// Convenience: tee + format hint in one call.
/// Returns hint string if file was written, None if skipped.
pub fn tee_and_hint(raw: &str, command_slug: &str, exit_code: i32) -> Option<String> {
let path = tee_raw(raw, command_slug, exit_code)?;
Some(format_hint(&path))
}
fn force_tee_path(content: &str, command_slug: &str) -> Option<PathBuf> {
if std::env::var("RTK_TEE").ok().as_deref() == Some("0") {
if raw.len() < MIN_FAILURE_BYTES {
return None;
}
let (mode, cfg) = active()?;
tee_and_hint_with(mode, &cfg, raw, command_slug, exit_code)
}
pub fn force_tee_hint(content: &str, command_slug: &str) -> Option<String> {
if content.is_empty() {
return None;
}
let config = Config::load().ok()?;
if !config.tee.enabled {
return None;
let (mode, cfg) = active()?;
match mode {
RecoveryMode::Disabled => None,
RecoveryMode::Tee => super::tee_file::force_tee_hint(&cfg, content, command_slug)
.inspect(|_| retriever::record_tee_elision(&cfg, command_slug)),
RecoveryMode::Sqlite => store_hint(&cfg, content, command_slug, None),
}
let tee_dir = get_tee_dir(&config)?;
let tee_dir = create_tee_dir(&tee_dir).and(Some(tee_dir))?;
write_tee_file(
content,
command_slug,
&tee_dir,
config.tee.max_file_size,
config.tee.max_files,
)
}
/// Returns `[full output: ~/path]`, or None if tee is disabled/skipped.
pub fn force_tee_hint(raw: &str, command_slug: &str) -> Option<String> {
let path = force_tee_path(raw, command_slug)?;
Some(format_hint(&path))
}
/// Returns `[see remaining: tail -n +{line_offset} ~/path]`, or None if tee is disabled/skipped.
pub fn force_tee_tail_hint(
content: &str,
command_slug: &str,
line_offset: usize,
) -> Option<String> {
let path = force_tee_path(content, command_slug)?;
Some(format!(
"[see remaining: tail -n +{} {}]",
line_offset,
display_shell_path(&path)
))
}
/// TeeMode controls when tee writes files.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum TeeMode {
#[default]
Failures,
Always,
Never,
}
/// Configuration for the tee feature.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct TeeConfig {
pub enabled: bool,
pub mode: TeeMode,
pub max_files: usize,
pub max_file_size: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub directory: Option<PathBuf>,
}
impl Default for TeeConfig {
fn default() -> Self {
Self {
enabled: true,
mode: TeeMode::default(),
max_files: DEFAULT_MAX_FILES,
max_file_size: DEFAULT_MAX_FILE_SIZE,
directory: None,
if content.is_empty() {
return None;
}
let (mode, cfg) = active()?;
match mode {
RecoveryMode::Disabled => None,
RecoveryMode::Tee => {
super::tee_file::force_tee_tail_hint(&cfg, content, command_slug, line_offset)
.inspect(|_| retriever::record_tee_elision(&cfg, command_slug))
}
RecoveryMode::Sqlite => {
match retriever::store(&cfg, content.as_bytes(), command_slug, None, line_offset) {
Stored::Saved(s) if s.hidden_lines > 0 => Some(format!(
"[+{} hidden: rtk recall {}]",
s.hidden_lines, s.hash
)),
Stored::Saved(_) | Stored::Unavailable | Stored::Empty => None,
}
}
}
}
@@ -355,378 +109,79 @@ impl Default for TeeConfig {
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
#[test]
fn test_sanitize_slug() {
assert_eq!(sanitize_slug("cargo_test"), "cargo_test");
assert_eq!(sanitize_slug("cargo test"), "cargo_test");
assert_eq!(sanitize_slug("cargo-test"), "cargo-test");
assert_eq!(sanitize_slug("go/test/./pkg"), "go_test___pkg");
// Long slugs (embedded paths) collapse to a readable prefix + hash, staying short.
let long = format!("grep_0_{}", "a".repeat(50));
let short = sanitize_slug(&long);
fn test_disabled_env_emits_nothing() {
let _guard = crate::core::utils::TEST_ENV_LOCK.lock().unwrap();
std::env::set_var("RTK_RECALL", "0");
let big = "x".repeat(1000);
let hint = tee_and_hint(&big, "cmd", 1);
let forced = force_tee_hint(&big, "cmd");
let tail = force_tee_tail_hint(&big, "cmd", 5);
std::env::remove_var("RTK_RECALL");
assert!(hint.is_none(), "disabled must never emit tokens");
assert!(forced.is_none());
assert!(tail.is_none());
}
#[test]
fn test_sqlite_never_stores_a_successful_run() {
let dir = tempfile::tempdir().unwrap();
let cfg = RetrieverConfig {
database_path: Some(dir.path().join("s.db")),
tee_on_success: true,
..RetrieverConfig::default()
};
let big = "x".repeat(1000);
assert!(
short.len() < 24,
"long slug should shorten, got '{}'",
short
tee_and_hint_with(RecoveryMode::Sqlite, &cfg, &big, "cmd", 0).is_none(),
"the sqlite store only records failures and truncations"
);
assert!(!dir.path().join("s.db").exists());
}
#[test]
fn test_tee_mode_honors_legacy_always() {
let dir = tempfile::tempdir().unwrap();
let base = RetrieverConfig {
tee_directory: Some(dir.path().to_path_buf()),
database_path: Some(dir.path().join("s.db")),
..RetrieverConfig::default()
};
let big = "x".repeat(1000);
assert!(
short.starts_with("grep_0_a"),
"keeps a readable prefix, got '{}'",
short
tee_and_hint_with(RecoveryMode::Tee, &base, &big, "cmd", 0).is_none(),
"failures-only is the legacy default"
);
// Deterministic, and different slugs never collide onto the same filename.
assert_eq!(sanitize_slug(&long), short);
let other = sanitize_slug(&format!("grep_1_{}", "a".repeat(50)));
assert_ne!(other, short, "distinct slugs must not collide");
}
#[test]
fn test_should_tee_disabled() {
let config = TeeConfig {
enabled: false,
..TeeConfig::default()
let always = RetrieverConfig {
tee_on_success: true,
..base
};
let dir = PathBuf::from("/tmp/tee");
assert!(should_tee(&config, 1000, 1, Some(dir)).is_none());
}
#[test]
fn test_should_tee_never_mode() {
let config = TeeConfig {
mode: TeeMode::Never,
..TeeConfig::default()
};
let dir = PathBuf::from("/tmp/tee");
assert!(should_tee(&config, 1000, 1, Some(dir)).is_none());
}
#[test]
fn test_should_tee_skip_small_output() {
let config = TeeConfig::default();
let dir = PathBuf::from("/tmp/tee");
// Below MIN_TEE_SIZE (500)
assert!(should_tee(&config, 100, 1, Some(dir)).is_none());
}
#[test]
fn test_should_tee_skip_success_in_failures_mode() {
let config = TeeConfig::default(); // mode = Failures
let dir = PathBuf::from("/tmp/tee");
assert!(should_tee(&config, 1000, 0, Some(dir)).is_none());
}
#[test]
fn test_should_tee_proceed_on_failure() {
let config = TeeConfig::default(); // mode = Failures
let dir = PathBuf::from("/tmp/tee");
assert!(should_tee(&config, 1000, 1, Some(dir)).is_some());
}
#[test]
fn test_should_tee_always_mode_success() {
let config = TeeConfig {
mode: TeeMode::Always,
..TeeConfig::default()
};
let dir = PathBuf::from("/tmp/tee");
assert!(should_tee(&config, 1000, 0, Some(dir)).is_some());
}
#[test]
fn test_write_tee_file_creates_file() {
let tmpdir = tempfile::tempdir().unwrap();
let content = "error: test failed\n".repeat(50);
let result = write_tee_file(
&content,
"cargo_test",
tmpdir.path(),
DEFAULT_MAX_FILE_SIZE,
20,
);
assert!(result.is_some());
let path = result.unwrap();
assert!(path.exists());
let written = fs::read_to_string(&path).unwrap();
assert!(written.contains("error: test failed"));
}
#[test]
#[cfg(unix)]
fn test_write_tee_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let tmpdir = tempfile::tempdir().unwrap();
let tee_dir = tmpdir.path().join("tee");
let path = write_tee_file(
"secret output\n",
"grep",
&tee_dir,
DEFAULT_MAX_FILE_SIZE,
20,
)
.expect("tee file written");
let mode = |p: &std::path::Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&path), 0o600, "tee file must be owner-only");
assert_eq!(mode(&tee_dir), 0o700, "tee dir must be owner-only");
}
// umask is process-global, so this must not run alongside another test that
// depends on it. Restored before the assertion can unwind.
#[test]
#[cfg(unix)]
#[allow(unsafe_code)]
fn test_write_tee_file_owner_only_under_permissive_umask() {
use std::os::unix::fs::PermissionsExt;
// nosemgrep: unsafe-block
let previous = unsafe { libc::umask(0o000) };
let tmpdir = tempfile::tempdir().unwrap();
let tee_dir = tmpdir.path().join("tee");
let written = write_tee_file("secret\n", "grep", &tee_dir, DEFAULT_MAX_FILE_SIZE, 20);
// nosemgrep: unsafe-block
unsafe { libc::umask(previous) };
let path = written.expect("tee file written");
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "umask 000 must not widen the tee file");
}
#[test]
fn test_write_tee_file_truncation() {
let tmpdir = tempfile::tempdir().unwrap();
let big_output = "x".repeat(2000);
// Set max_file_size to 1000 bytes
let result = write_tee_file(&big_output, "test", tmpdir.path(), 1000, 20);
assert!(result.is_some());
let path = result.unwrap();
let content = fs::read_to_string(&path).unwrap();
assert!(content.contains("--- truncated at 1000 bytes ---"));
assert!(content.len() < 2000);
}
#[test]
fn test_write_tee_file_truncation_utf8_boundary() {
let tmpdir = tempfile::tempdir().unwrap();
// Create a string where the truncation point falls inside a multi-byte char.
// Japanese chars are 3 bytes each in UTF-8.
// 332 chars * 3 bytes = 996 bytes, then one more = 999 bytes.
// With max_file_size=998, the cut falls mid-character.
let japanese = "\u{6F22}".repeat(333); // 999 bytes of 3-byte chars
assert_eq!(japanese.len(), 999);
// Truncate at 998 — falls in the middle of the 333rd character
let result = write_tee_file(&japanese, "test_utf8", tmpdir.path(), 998, 20);
assert!(result.is_some());
let path = result.unwrap();
let content = fs::read_to_string(&path).unwrap();
assert!(content.contains("--- truncated at 998 bytes ---"));
// Should contain 332 full characters (996 bytes), not panic
assert!(content.starts_with(&"\u{6F22}".repeat(332)));
}
#[test]
fn test_write_tee_file_truncation_emoji() {
let tmpdir = tempfile::tempdir().unwrap();
// Emoji are 4 bytes each in UTF-8
let emojis = "\u{1F600}".repeat(100); // 400 bytes
assert_eq!(emojis.len(), 400);
// Truncate at 201 — falls mid-emoji (4-byte boundary is at 200, 204)
let result = write_tee_file(&emojis, "test_emoji", tmpdir.path(), 201, 20);
assert!(result.is_some());
let path = result.unwrap();
let content = fs::read_to_string(&path).unwrap();
assert!(content.contains("--- truncated at 201 bytes ---"));
// The emoji portion should be exactly 200 bytes (50 emojis),
// rounded down from 201 to the nearest char boundary
let target = "\u{1F600}".repeat(50);
assert!(content.starts_with(&target));
}
#[test]
fn test_cleanup_old_files() {
let tmpdir = tempfile::tempdir().unwrap();
let dir = tmpdir.path();
// Create 25 .log files
for i in 0..25 {
let filename = format!("{:010}_{}.log", 1000000 + i, "test");
fs::write(dir.join(&filename), "content").unwrap();
}
cleanup_old_files(dir, 20);
let remaining: Vec<_> = fs::read_dir(dir).unwrap().filter_map(|e| e.ok()).collect();
assert_eq!(remaining.len(), 20);
// Oldest 5 should be removed
for i in 0..5 {
let filename = format!("{:010}_{}.log", 1000000 + i, "test");
assert!(!dir.join(&filename).exists());
}
// Newest 20 should remain
for i in 5..25 {
let filename = format!("{:010}_{}.log", 1000000 + i, "test");
assert!(dir.join(&filename).exists());
}
}
#[test]
fn test_format_hint() {
let path = PathBuf::from("/tmp/rtk/tee/123_cargo_test.log");
let hint = format_hint(&path);
assert!(hint.starts_with("[full output: "));
assert!(hint.ends_with(']'));
assert!(hint.contains("123_cargo_test.log"));
}
#[test]
fn test_display_shell_path_preserves_simple_paths() {
let path = PathBuf::from("/tmp/rtk/tee/123_cargo_test.log");
assert_eq!(display_shell_path(&path), "/tmp/rtk/tee/123_cargo_test.log");
}
#[test]
fn test_display_shell_path_quotes_paths_with_spaces() {
let path = PathBuf::from("/tmp/rtk/Application Support/123_go_test.log");
assert_eq!(
display_shell_path(&path),
"\"/tmp/rtk/Application Support/123_go_test.log\""
);
}
#[test]
fn test_display_shell_path_quotes_backslashes() {
let path = PathBuf::from(r"/tmp/rtk/tee/path\segment.log");
assert_eq!(
display_shell_path(&path),
r#""/tmp/rtk/tee/path\\segment.log""#
);
}
#[test]
fn test_display_shell_path_uses_home_var_for_home_paths_with_spaces() {
let Some(home) = dirs::home_dir() else {
return;
};
let path = home
.join("Library")
.join("Application Support")
.join("rtk")
.join("tee")
.join("123_go_test.log");
assert_eq!(
display_shell_path(&path),
"\"$HOME/Library/Application Support/rtk/tee/123_go_test.log\""
);
}
#[test]
fn test_format_hint_avoids_backslash_escaped_whitespace() {
let Some(home) = dirs::home_dir() else {
return;
};
let path = home
.join("Library")
.join("Application Support")
.join("rtk")
.join("tee")
.join("123_go_test.log");
let hint = format_hint(&path);
assert_eq!(
hint,
"[full output: \"$HOME/Library/Application Support/rtk/tee/123_go_test.log\"]"
);
assert!(
!hint.contains("\\ "),
"hint should not encourage backslash-escaped whitespace"
tee_and_hint_with(RecoveryMode::Tee, &always, &big, "cmd", 0).is_some(),
"legacy always still archives successful runs"
);
}
#[test]
fn test_tee_config_default() {
let config = TeeConfig::default();
assert!(config.enabled);
assert_eq!(config.mode, TeeMode::Failures);
assert_eq!(config.max_files, 20);
assert_eq!(config.max_file_size, 1_048_576);
assert!(config.directory.is_none());
fn test_tee_and_hint_skips_success() {
let big = "x".repeat(1000);
let cfg = RetrieverConfig::default();
assert!(tee_and_hint_with(RecoveryMode::Sqlite, &cfg, &big, "cmd", 0).is_none());
}
#[test]
fn test_tee_config_deserialize() {
let toml_str = r#"
enabled = true
mode = "always"
max_files = 10
max_file_size = 524288
directory = "/tmp/rtk-tee"
"#;
let config: TeeConfig = toml::from_str(toml_str).unwrap();
assert!(config.enabled);
assert_eq!(config.mode, TeeMode::Always);
assert_eq!(config.max_files, 10);
assert_eq!(config.max_file_size, 524288);
assert_eq!(config.directory, Some(PathBuf::from("/tmp/rtk-tee")));
// Round-trip
let serialized = toml::to_string_pretty(&config).unwrap();
let deserialized: TeeConfig = toml::from_str(&serialized).unwrap();
assert_eq!(deserialized.mode, TeeMode::Always);
assert_eq!(deserialized.max_files, 10);
fn test_tee_and_hint_skips_tiny_failure() {
assert!(tee_and_hint("tiny", "cmd", 1).is_none());
}
#[test]
fn test_tee_mode_serde() {
// Test all modes via JSON
let mode: TeeMode = serde_json::from_str(r#""always""#).unwrap();
assert_eq!(mode, TeeMode::Always);
let mode: TeeMode = serde_json::from_str(r#""failures""#).unwrap();
assert_eq!(mode, TeeMode::Failures);
let mode: TeeMode = serde_json::from_str(r#""never""#).unwrap();
assert_eq!(mode, TeeMode::Never);
fn test_force_tee_hint_skips_empty() {
assert!(force_tee_hint("", "cmd").is_none());
}
#[test]
fn test_force_tee_hint_skip_empty() {
let hint = force_tee_hint("", "test_cmd");
assert!(hint.is_none(), "Should skip empty content");
}
#[test]
fn test_force_tee_hint_respects_env_disable() {
// When RTK_TEE=0, force_tee_hint should return None
std::env::set_var("RTK_TEE", "0");
let large_output = "x".repeat(1000);
let hint = force_tee_hint(&large_output, "test_cmd");
std::env::remove_var("RTK_TEE");
assert!(hint.is_none(), "Should respect RTK_TEE=0");
}
#[test]
fn test_force_tee_tail_hint_skip_empty() {
let hint = force_tee_tail_hint("", "test_cmd", 22);
assert!(hint.is_none(), "Should skip empty content");
}
#[test]
fn test_force_tee_tail_hint_format() {
let path = std::path::PathBuf::from("/tmp/rtk/tee/123_docker_images.log");
let display = display_path(&path);
let hint = format!("[see remaining: tail -n +{} {}]", 22, display);
assert!(hint.starts_with("[see remaining: tail -n +22 "));
assert!(hint.ends_with(']'));
assert!(hint.contains("123_docker_images.log"));
fn test_force_tee_tail_hint_skips_empty() {
assert!(force_tee_tail_hint("", "cmd", 5).is_none());
}
}
+448
View File
@@ -0,0 +1,448 @@
//! Legacy file-based recovery ("tee" mode) — may be deprecated. Prefer the
//! sqlite recall store (`[retriever] mode = "sqlite"`); see retriever.rs.
use crate::core::config::Config;
use crate::core::constants::RTK_DATA_DIR;
use crate::core::retriever::RetrieverConfig;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
/// Sanitize a command slug for use in filenames.
/// Replaces non-alphanumeric chars (except underscore/hyphen) with underscore.
/// Long slugs (usually an embedded file path that duplicates the command the LLM
/// already issued) collapse to a short readable prefix plus a short disambiguating
/// hash, keeping recovery filenames unique but compact — fewer tokens per tee hint.
pub(crate) fn sanitize_slug(slug: &str) -> String {
let sanitized: String = slug
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
c
} else {
'_'
}
})
.collect();
const MAX_READABLE: usize = 24;
if sanitized.len() <= MAX_READABLE {
return sanitized;
}
let prefix: String = sanitized.chars().take(8).collect();
format!("{}_{}", prefix, short_hash(&sanitized))
}
/// First 6 hex chars (24 bits) of the SHA-256 of `s` — a compact tag to keep
/// shortened slugs distinct. Not collision-resistant on its own: 24 bits hits a
/// birthday collision after only a few thousand distinct slugs. It's safe here
/// because a clash also requires the identical readable prefix *and* the same
/// epoch second, which together scope tee writes exactly as before.
fn short_hash(s: &str) -> String {
use sha2::{Digest, Sha256};
format!("{:x}", Sha256::digest(s.as_bytes()))[..6].to_string()
}
const LEGACY_ACTIVITY_WINDOW_SECS: u64 = 30 * 86_400;
fn has_recent_logs(dir: &Path, now: SystemTime) -> bool {
std::fs::read_dir(dir)
.ok()
.into_iter()
.flatten()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|ext| ext == "log"))
.filter_map(|e| e.metadata().ok())
.filter_map(|m| m.modified().ok())
.any(|mtime| {
now.duration_since(mtime)
.map(|age| age.as_secs() < LEGACY_ACTIVITY_WINDOW_SECS)
.unwrap_or(false)
})
}
pub fn legacy_tee_migration_pending() -> bool {
let Ok(config) = Config::load() else {
return false;
};
if config.retriever.mode != crate::core::retriever::RecoveryMode::Sqlite {
return false;
}
let Some(dir) = get_tee_dir(&config.retriever) else {
return false;
};
has_recent_logs(&dir, SystemTime::now())
}
pub const LEGACY_TEE_NOTICE: &str = "Recovery hints moved to a sqlite store: read them with `rtk recall <hash>`.\nRecent tee .log files were found; to keep the legacy file mode, run\n`rtk config recall tee`.";
pub const LEGACY_TEE_CONFIG_NOTICE: &str = "Legacy [tee] config detected — file mode kept. A sqlite recall store is now\navailable: run `rtk config recall sqlite` to adopt it (hints become\n`rtk recall <hash>`, see `rtk gain --recalls`).";
pub fn legacy_tee_config_in_use() -> bool {
Config::load()
.map(|c| c.migrated_from_legacy_tee)
.unwrap_or(false)
}
pub const LEGACY_TEE_MERGED_NOTICE: &str = "Legacy [tee] values are still applied alongside your [retriever] section.\nMove them to [retriever] (tee_max_files, tee_max_file_size, tee_directory)\nand remove the [tee] section.";
pub fn legacy_tee_fields_merged_in_use() -> bool {
Config::load()
.map(|c| c.legacy_tee_fields_merged)
.unwrap_or(false)
}
pub(crate) fn resolved_tee_dir() -> Option<PathBuf> {
let cfg = Config::load().ok()?.retriever;
get_tee_dir(&cfg)
}
fn get_tee_dir(cfg: &RetrieverConfig) -> Option<PathBuf> {
if let Ok(dir) = std::env::var("RTK_TEE_DIR") {
return Some(PathBuf::from(dir));
}
if let Some(ref dir) = cfg.tee_directory {
return Some(dir.clone());
}
dirs::data_local_dir().map(|d| d.join(RTK_DATA_DIR).join("tee"))
}
fn cleanup_old_files(dir: &Path, max_files: usize) {
let mut entries: Vec<_> = std::fs::read_dir(dir)
.ok()
.into_iter()
.flatten()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().is_some_and(|ext| ext == "log"))
.collect();
if entries.len() <= max_files {
return;
}
entries.sort_by_key(|e| e.file_name());
let to_remove = entries.len() - max_files;
for entry in entries.iter().take(to_remove) {
// nosemgrep: filesystem-deletion
let _ = std::fs::remove_file(entry.path());
}
}
fn create_tee_dir(tee_dir: &Path) -> Option<()> {
if let Some(parent) = tee_dir.parent() {
let _ = crate::core::utils::create_private_dir(parent);
}
crate::core::utils::create_private_dir(tee_dir).ok()
}
fn write_tee_file(
raw: &str,
slug: &str,
dir: &Path,
max_file_size: usize,
max_files: usize,
) -> Option<PathBuf> {
create_tee_dir(dir)?;
let slug = sanitize_slug(slug);
let epoch = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();
let filepath = dir.join(format!("{}_{}.log", epoch, slug));
let content = if raw.len() > max_file_size {
let boundary = raw
.char_indices()
.take_while(|(i, _)| *i < max_file_size)
.last()
.map(|(i, c)| i + c.len_utf8())
.unwrap_or(0);
format!(
"{}\n\n--- truncated at {} bytes ---",
&raw[..boundary],
max_file_size
)
} else {
raw.to_string()
};
let mut file = crate::core::utils::open_private(
std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true),
&filepath,
)
.ok()?;
use std::io::Write;
file.write_all(content.as_bytes()).ok()?;
cleanup_old_files(dir, max_files);
Some(filepath)
}
fn display_path(path: &Path) -> String {
if let Some(home) = dirs::home_dir() {
if let Ok(relative) = path.strip_prefix(&home) {
return format!("~/{}", relative.display());
}
}
path.display().to_string()
}
fn needs_shell_quoting(path: &str) -> bool {
path.chars().any(|c| {
c.is_whitespace()
|| matches!(
c,
'\'' | '"'
| '\\'
| '$'
| '`'
| '!'
| '#'
| '&'
| '('
| ')'
| ';'
| '<'
| '>'
| '?'
| '['
| ']'
| '{'
| '}'
| '|'
| '*'
)
})
}
fn escape_double_quoted_path(path: &str) -> String {
let mut escaped = String::with_capacity(path.len());
for c in path.chars() {
if matches!(c, '\\' | '"' | '$' | '`') {
escaped.push('\\');
}
escaped.push(c);
}
escaped
}
fn display_shell_path(path: &Path) -> String {
let display = display_path(path);
if !needs_shell_quoting(&display) {
return display;
}
if let Some(relative) = display.strip_prefix("~/") {
let relative = relative.replace(std::path::MAIN_SEPARATOR, "/");
return format!("\"$HOME/{}\"", escape_double_quoted_path(&relative));
}
format!("\"{}\"", escape_double_quoted_path(&display))
}
fn write(cfg: &RetrieverConfig, content: &str, slug: &str) -> Option<PathBuf> {
let dir = get_tee_dir(cfg)?;
write_tee_file(
content,
slug,
&dir,
cfg.tee_max_file_size,
cfg.tee_max_files,
)
}
pub fn tee_and_hint(cfg: &RetrieverConfig, raw: &str, slug: &str) -> Option<String> {
let path = write(cfg, raw, slug)?;
Some(format!("[full output: {}]", display_shell_path(&path)))
}
pub fn force_tee_hint(cfg: &RetrieverConfig, content: &str, slug: &str) -> Option<String> {
let path = write(cfg, content, slug)?;
Some(format!("[full output: {}]", display_shell_path(&path)))
}
pub fn force_tee_tail_hint(
cfg: &RetrieverConfig,
content: &str,
slug: &str,
line_offset: usize,
) -> Option<String> {
let path = write(cfg, content, slug)?;
Some(format!(
"[see remaining: tail -n +{} {}]",
line_offset,
display_shell_path(&path)
))
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
const MAX_FILE_SIZE: usize = 1_048_576;
#[test]
fn test_sanitize_slug() {
assert_eq!(sanitize_slug("cargo_test"), "cargo_test");
assert_eq!(sanitize_slug("cargo test"), "cargo_test");
assert_eq!(sanitize_slug("cargo-test"), "cargo-test");
assert_eq!(sanitize_slug("go/test/./pkg"), "go_test___pkg");
let long = format!("grep_0_{}", "a".repeat(50));
let short = sanitize_slug(&long);
assert!(short.len() < 24, "long slug should shorten, got '{short}'");
assert!(
short.starts_with("grep_0_a"),
"keeps a readable prefix, got '{short}'"
);
assert_eq!(sanitize_slug(&long), short);
let other = sanitize_slug(&format!("grep_1_{}", "a".repeat(50)));
assert_ne!(other, short, "distinct slugs must not collide");
}
#[test]
fn test_write_tee_file_creates_file() {
let tmpdir = tempfile::tempdir().unwrap();
let content = "error: test failed\n".repeat(50);
let result = write_tee_file(&content, "cargo_test", tmpdir.path(), MAX_FILE_SIZE, 20);
let path = result.expect("tee file written");
assert!(path.exists());
let written = fs::read_to_string(&path).unwrap();
assert!(written.contains("error: test failed"));
}
#[test]
#[cfg(unix)]
fn test_write_tee_file_is_owner_only() {
use std::os::unix::fs::PermissionsExt;
let tmpdir = tempfile::tempdir().unwrap();
let tee_dir = tmpdir.path().join("tee");
let path = write_tee_file("secret output\n", "grep", &tee_dir, MAX_FILE_SIZE, 20)
.expect("tee file written");
let mode = |p: &std::path::Path| fs::metadata(p).unwrap().permissions().mode() & 0o777;
assert_eq!(mode(&path), 0o600, "tee file must be owner-only");
assert_eq!(mode(&tee_dir), 0o700, "tee dir must be owner-only");
}
#[test]
#[cfg(unix)]
#[allow(unsafe_code)]
fn test_write_tee_file_owner_only_under_permissive_umask() {
use std::os::unix::fs::PermissionsExt;
// nosemgrep: unsafe-block
let previous = unsafe { libc::umask(0o000) };
let tmpdir = tempfile::tempdir().unwrap();
let tee_dir = tmpdir.path().join("tee");
let written = write_tee_file("secret\n", "grep", &tee_dir, MAX_FILE_SIZE, 20);
// nosemgrep: unsafe-block
unsafe { libc::umask(previous) };
let path = written.expect("tee file written");
let mode = fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600, "umask 000 must not widen the tee file");
}
#[test]
fn test_write_tee_file_truncation() {
let tmpdir = tempfile::tempdir().unwrap();
let big_output = "x".repeat(2000);
let result = write_tee_file(&big_output, "test", tmpdir.path(), 1000, 20);
let path = result.expect("tee file written");
let content = fs::read_to_string(&path).unwrap();
assert!(content.contains("--- truncated at 1000 bytes ---"));
assert!(content.len() < 2000);
}
#[test]
fn test_write_tee_file_truncation_utf8_boundary() {
let tmpdir = tempfile::tempdir().unwrap();
let japanese = "\u{6F22}".repeat(333);
assert_eq!(japanese.len(), 999);
let result = write_tee_file(&japanese, "test_utf8", tmpdir.path(), 998, 20);
let path = result.expect("tee file written");
let content = fs::read_to_string(&path).unwrap();
assert!(content.contains("--- truncated at 998 bytes ---"));
assert!(content.starts_with(&"\u{6F22}".repeat(332)));
}
#[test]
fn test_cleanup_old_files() {
let tmpdir = tempfile::tempdir().unwrap();
let dir = tmpdir.path();
for i in 0..25 {
let filename = format!("{:010}_{}.log", 1000000 + i, "test");
fs::write(dir.join(&filename), "content").unwrap();
}
cleanup_old_files(dir, 20);
let remaining: Vec<_> = fs::read_dir(dir).unwrap().filter_map(|e| e.ok()).collect();
assert_eq!(remaining.len(), 20);
for i in 0..5 {
let filename = format!("{:010}_{}.log", 1000000 + i, "test");
assert!(!dir.join(&filename).exists());
}
}
#[test]
fn test_has_recent_logs_detects_fresh_log() {
let tmpdir = tempfile::tempdir().unwrap();
fs::write(tmpdir.path().join("1755590000_cargo_test.log"), "x").unwrap();
assert!(has_recent_logs(tmpdir.path(), SystemTime::now()));
}
#[test]
fn test_has_recent_logs_ignores_old_logs() {
let tmpdir = tempfile::tempdir().unwrap();
fs::write(tmpdir.path().join("1_old.log"), "x").unwrap();
let future = SystemTime::now() + std::time::Duration::from_secs(31 * 86_400);
assert!(!has_recent_logs(tmpdir.path(), future));
}
#[test]
fn test_has_recent_logs_ignores_non_log_files_and_missing_dir() {
let tmpdir = tempfile::tempdir().unwrap();
fs::write(tmpdir.path().join("notes.txt"), "x").unwrap();
assert!(!has_recent_logs(tmpdir.path(), SystemTime::now()));
assert!(!has_recent_logs(
&tmpdir.path().join("missing"),
SystemTime::now()
));
}
#[test]
fn test_display_shell_path_preserves_simple_paths() {
let path = PathBuf::from("/tmp/rtk/tee/123_cargo_test.log");
assert_eq!(display_shell_path(&path), "/tmp/rtk/tee/123_cargo_test.log");
}
#[test]
fn test_display_shell_path_quotes_paths_with_spaces() {
let path = PathBuf::from("/tmp/rtk/Application Support/123_go_test.log");
assert_eq!(
display_shell_path(&path),
"\"/tmp/rtk/Application Support/123_go_test.log\""
);
}
#[test]
fn test_display_shell_path_quotes_backslashes() {
let path = PathBuf::from(r"/tmp/rtk/tee/path\segment.log");
assert_eq!(
display_shell_path(&path),
r#""/tmp/rtk/tee/path\\segment.log""#
);
}
#[test]
fn test_display_shell_path_uses_home_var_for_home_paths_with_spaces() {
let Some(home) = dirs::home_dir() else {
return;
};
let path = home
.join("Library")
.join("Application Support")
.join("rtk")
.join("tee")
.join("123_go_test.log");
assert_eq!(
display_shell_path(&path),
"\"$HOME/Library/Application Support/rtk/tee/123_go_test.log\""
);
}
}
+164
View File
@@ -150,6 +150,11 @@ fn send_ping() -> Result<(), Box<dyn std::error::Error>> {
"projects_count": enriched.projects_count,
// Meta-commands: feature adoption
"meta_usage": enriched.meta_usage,
// Recall efficiency: which filter caps to tune (counters per filter family only)
"recall_mode": recall_mode_label(),
"recall_stats": build_recall_stats(
&crate::core::retriever::stats_snapshot().unwrap_or_default()
),
});
let mut req = ureq::post(url).set("Content-Type", "application/json");
@@ -331,6 +336,107 @@ fn get_enriched_stats(tracker: &tracking::Tracker) -> EnrichedStats {
}
/// Build meta-command usage counts (gain, discover, proxy, verify, learn, init).
fn recall_mode_label() -> &'static str {
use crate::core::retriever::RecoveryMode;
match crate::core::config::Config::load()
.unwrap_or_default()
.retriever
.mode
{
RecoveryMode::Sqlite => "sqlite",
RecoveryMode::Tee => "tee",
RecoveryMode::Disabled => "disabled",
}
}
const RECALL_FAMILIES: &[&str] = &[
"artisan",
"aws",
"cargo",
"compose",
"curl",
"docker",
"dotnet",
"ecs",
"err",
"eslint",
"gh",
"git",
"glab",
"go",
"gradlew",
"grep",
"gt",
"jest",
"kubectl",
"lint",
"mvn",
"mypy",
"next",
"npm",
"npx",
"paratest",
"pest",
"php",
"phpstan",
"phpunit",
"pint",
"pip",
"playwright",
"pnpm",
"prettier",
"prisma",
"pylint",
"pytest",
"rake",
"rspec",
"rubocop",
"ruff",
"run",
"sbt",
"test",
"tsc",
"uv",
"vitest",
"wget",
];
fn recall_slug_is_public(slug: &str) -> bool {
slug.len() <= 32
&& slug
.chars()
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_' || c == '-')
&& RECALL_FAMILIES.contains(&slug.split(['_', '-']).next().unwrap_or(""))
}
fn build_recall_stats(stats: &[crate::core::retriever::RecallStat]) -> serde_json::Value {
let mut rows: Vec<serde_json::Value> = Vec::new();
let mut other: std::collections::BTreeMap<&str, (i64, i64)> = std::collections::BTreeMap::new();
for s in stats {
if recall_slug_is_public(&s.slug) {
rows.push(serde_json::json!({
"filter": s.slug,
"mode": s.mode,
"elisions": s.elisions,
"recalls": s.recalls,
}));
} else {
let e = other.entry(s.mode.as_str()).or_insert((0, 0));
e.0 += s.elisions;
e.1 += s.recalls;
}
}
for (mode, (elisions, recalls)) in other {
rows.push(serde_json::json!({
"filter": "other",
"mode": mode,
"elisions": elisions,
"recalls": recalls,
}));
}
serde_json::Value::Array(rows)
}
fn build_meta_usage(tracker: &tracking::Tracker) -> serde_json::Value {
let meta_cmds = ["gain", "discover", "proxy", "verify", "learn", "init"];
let mut usage = serde_json::Map::new();
@@ -464,6 +570,64 @@ fn touch_marker(path: &PathBuf) {
mod tests {
use super::*;
fn stat(
slug: &str,
mode: &str,
elisions: i64,
recalls: i64,
) -> crate::core::retriever::RecallStat {
crate::core::retriever::RecallStat {
slug: slug.to_string(),
mode: mode.to_string(),
elisions,
recalls,
}
}
#[test]
fn test_recall_stats_known_families_pass_named() {
let stats = vec![
stat("grep", "sqlite", 142, 9),
stat("cargo_test", "sqlite", 12, 4),
stat("docker-images", "tee", 6, 1),
];
let v = build_recall_stats(&stats);
let arr = v.as_array().expect("array");
let names: Vec<&str> = arr.iter().map(|e| e["filter"].as_str().unwrap()).collect();
assert!(names.contains(&"grep"));
assert!(names.contains(&"cargo_test"));
assert!(names.contains(&"docker-images"));
}
#[test]
fn test_recall_stats_unknown_or_suspicious_slugs_fold_into_other_per_mode() {
let stats = vec![
stat("mysecretproject", "sqlite", 3, 1),
stat("grep__tmpEz7w0", "sqlite", 2, 0),
stat("a/b/path", "tee", 1, 0),
stat(&"x".repeat(40), "sqlite", 1, 1),
];
let v = build_recall_stats(&stats);
let arr = v.as_array().unwrap();
assert_eq!(arr.len(), 2, "one other row per mode, never mixed: {v}");
let sqlite = arr.iter().find(|e| e["mode"] == "sqlite").unwrap();
let tee = arr.iter().find(|e| e["mode"] == "tee").unwrap();
assert_eq!(sqlite["filter"], "other");
assert_eq!(sqlite["elisions"], 6);
assert_eq!(sqlite["recalls"], 2);
assert_eq!(tee["elisions"], 1);
}
#[test]
fn test_recall_stats_payload_has_only_expected_keys() {
let stats = vec![stat("grep", "sqlite", 1, 1)];
let v = build_recall_stats(&stats);
let obj = v.as_array().unwrap()[0].as_object().unwrap();
let mut keys: Vec<&str> = obj.keys().map(|s| s.as_str()).collect();
keys.sort_unstable();
assert_eq!(keys, ["elisions", "filter", "mode", "recalls"]);
}
#[test]
fn test_device_hash_is_stable() {
let h1 = generate_device_hash();
+6
View File
@@ -284,6 +284,12 @@ pub fn fallback_tail(output: &str, label: &str, n: usize) -> String {
}
/// Create a directory owner-only (0700 on Unix), tightening one that already exists.
/// Serializes tests across modules that mutate process-global recall env vars
/// (`RTK_RECALL`, `RTK_TEE`): a static declared inside one test module is not
/// shared with other modules, so those tests would not actually serialize.
#[cfg(test)]
pub(crate) static TEST_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
pub fn create_private_dir(path: &std::path::Path) -> std::io::Result<()> {
fs::create_dir_all(path)?;
set_owner_only(path, 0o700);
+1
View File
@@ -260,6 +260,7 @@ fn decide_from_verdict(cmd: &str, verdict: PermissionVerdict) -> HookDecision {
if verdict == PermissionVerdict::Deny {
return HookDecision::Deny;
}
crate::hooks::rewrite_cmd::track_tee_read(cmd);
if crate::discover::lexer::contains_unattestable_construct(cmd) {
return HookDecision::Defer;
}
+11
View File
@@ -479,6 +479,17 @@ pub fn run(
println!();
}
if crate::core::tee_file::legacy_tee_migration_pending() {
println!("{}", crate::core::tee_file::LEGACY_TEE_NOTICE);
println!();
} else if crate::core::tee_file::legacy_tee_config_in_use() {
println!("{}", crate::core::tee_file::LEGACY_TEE_CONFIG_NOTICE);
println!();
} else if crate::core::tee_file::legacy_tee_fields_merged_in_use() {
println!("{}", crate::core::tee_file::LEGACY_TEE_MERGED_NOTICE);
println!();
}
Ok(())
}
+122 -1
View File
@@ -15,10 +15,70 @@ use std::io::Write;
/// | 1 | (none) | No RTK equivalent — hook passes through unchanged. |
/// | 2 | (none) | Deny rule matched — hook defers to Claude Code native deny. |
/// | 3 | rewritten| Ask rule matched — hook rewrites but lets Claude Code prompt.|
const TEE_READERS: &[&str] = &[
"cat", "tail", "head", "less", "more", "bat", "grep", "rg", "sed", "awk",
];
fn expand_home(token: &str) -> String {
if let Some(rest) = token.strip_prefix("~/") {
if let Some(home) = dirs::home_dir() {
return home.join(rest).to_string_lossy().into_owned();
}
}
if let Some(rest) = token.strip_prefix("$HOME/") {
if let Some(home) = dirs::home_dir() {
return home.join(rest).to_string_lossy().into_owned();
}
}
token.to_string()
}
fn tee_read_slug(cmd: &str, tee_dir: &std::path::Path) -> Option<(String, String)> {
let first = cmd.split_whitespace().next()?;
let reader = first.rsplit('/').next().unwrap_or(first);
if !TEE_READERS.contains(&reader) {
return None;
}
for token in cmd.split_whitespace() {
let t = token.trim_matches(|c| c == '"' || c == '\'');
if !t.ends_with(".log") {
continue;
}
let expanded = expand_home(t);
let path = std::path::Path::new(&expanded);
if !path.starts_with(tee_dir) {
continue;
}
let stem = path.file_stem()?.to_str()?;
if let Some((epoch, slug)) = stem.split_once('_') {
if !epoch.is_empty() && epoch.chars().all(|c| c.is_ascii_digit()) && !slug.is_empty() {
return Some((slug.to_string(), expanded));
}
}
}
None
}
pub(crate) fn track_tee_read(cmd: &str) {
if !cmd.contains(".log") {
return;
}
let Some(tee_dir) = crate::core::tee_file::resolved_tee_dir() else {
return;
};
if let Some((slug, path)) = tee_read_slug(cmd, &tee_dir) {
crate::core::retriever::record_tee_recall(&slug, &path);
}
}
pub fn run(cmd: &str) -> anyhow::Result<()> {
let (excluded, transparent_prefixes) = crate::core::config::hook_rewrite_params();
match evaluate(cmd, &excluded, &transparent_prefixes) {
let outcome = evaluate(cmd, &excluded, &transparent_prefixes);
if !matches!(outcome, RewriteOutcome::Deny) {
track_tee_read(cmd);
}
match outcome {
RewriteOutcome::Allow(rewritten) => {
print!("{}", rewritten);
let _ = std::io::stdout().flush();
@@ -80,6 +140,67 @@ fn evaluate_with_verdict(
mod tests {
use super::*;
#[test]
fn test_tee_read_slug_detects_tail_hint_command() {
let dir = std::path::Path::new("/home/u/.local/share/rtk/tee");
let cmd = "tail -n +52 /home/u/.local/share/rtk/tee/1755590000_docker-images.log";
assert_eq!(
tee_read_slug(cmd, dir),
Some((
"docker-images".to_string(),
"/home/u/.local/share/rtk/tee/1755590000_docker-images.log".to_string()
))
);
}
#[test]
fn test_tee_read_slug_detects_quoted_and_grep() {
let dir = std::path::Path::new("/home/u/.local/share/rtk/tee");
let cmd = r#"grep error "/home/u/.local/share/rtk/tee/1755590000_cargo_test.log""#;
assert_eq!(
tee_read_slug(cmd, dir).map(|(s, _)| s),
Some("cargo_test".to_string())
);
}
#[test]
fn test_tee_read_slug_ignores_non_readers() {
let dir = std::path::Path::new("/home/u/.local/share/rtk/tee");
for cmd in [
"rm /home/u/.local/share/rtk/tee/1755590000_x.log",
"ls /home/u/.local/share/rtk/tee",
"mv /home/u/.local/share/rtk/tee/1755590000_x.log /tmp/",
] {
assert_eq!(tee_read_slug(cmd, dir), None, "{cmd}");
}
}
#[test]
fn test_tee_read_slug_ignores_logs_outside_tee_dir() {
let dir = std::path::Path::new("/home/u/.local/share/rtk/tee");
assert_eq!(tee_read_slug("cat /var/log/app_server.log", dir), None);
assert_eq!(tee_read_slug("tail -f ./build_1234_out.log", dir), None);
}
#[test]
fn test_tee_read_slug_requires_epoch_prefix() {
let dir = std::path::Path::new("/home/u/.local/share/rtk/tee");
assert_eq!(
tee_read_slug("cat /home/u/.local/share/rtk/tee/notes_perso.log", dir),
None
);
}
#[test]
fn test_tee_read_slug_reader_with_absolute_path() {
let dir = std::path::Path::new("/home/u/.local/share/rtk/tee");
let cmd = "/usr/bin/tail -n +5 /home/u/.local/share/rtk/tee/17_gh-prs.log";
assert_eq!(
tee_read_slug(cmd, dir).map(|(s, _)| s),
Some("gh-prs".to_string())
);
}
fn rewrite_command_no_prefixes(cmd: &str) -> Option<String> {
registry::rewrite_command(cmd, &[], &[])
}
+122 -10
View File
@@ -471,7 +471,10 @@ enum Commands {
/// Show parse failure log (commands that fell back to raw execution)
#[arg(short = 'F', long)]
failures: bool,
/// Reset all token savings stats to zero
/// Show recall efficiency per filter (elisions vs agent recalls)
#[arg(long)]
recalls: bool,
/// Reset token savings and recall stats to zero
#[arg(long)]
reset: bool,
/// Skip confirmation prompt when resetting
@@ -498,11 +501,13 @@ enum Commands {
format: String,
},
/// Show or create configuration file
/// Show or modify configuration
Config {
/// Create default config file
#[arg(long)]
create: bool,
#[command(subcommand)]
action: Option<ConfigAction>,
},
/// Jest commands with compact output
@@ -685,6 +690,27 @@ enum Commands {
args: Vec<OsString>,
},
/// Recall output a filter elided, by content hash
Recall {
/// Hash from a recovery hint (a unique prefix is enough)
hash: Option<String>,
/// Return the complete output, not just the missed part
#[arg(long)]
full: bool,
/// Start from this 1-based line of the full output
#[arg(long)]
from: Option<usize>,
/// Return only the first N lines of the full output
#[arg(long, conflicts_with = "from")]
lines: Option<usize>,
/// Filter recalled lines by regex
#[arg(long)]
grep: Option<String>,
/// List stored entries
#[arg(long)]
list: bool,
},
/// Read stdin, apply filter, print filtered output (Unix pipe mode)
Pipe {
/// Filter name (cargo-test, pytest, phpunit, phpstan, pint, grep, find, git-log, etc.)
@@ -1326,6 +1352,15 @@ enum GoCommands {
Other(Vec<OsString>),
}
#[derive(Debug, Subcommand)]
enum ConfigAction {
/// Show or set the recovery mode (sqlite | tee | disabled)
Recall {
/// New mode; omit to show the current one
mode: Option<String>,
},
}
#[derive(Debug, Subcommand)]
enum SbtCommands {
/// Run tests with compact output (90% token reduction via ScalaTest filtering)
@@ -1788,6 +1823,16 @@ where
}
}
fn is_native_test_expression(command: &[String]) -> bool {
match command.first().map(String::as_str) {
// `!` and `(` are shell syntax too, so they only mark a native
// expression when what they apply to is one.
Some("!") | Some("(") => is_native_test_expression(&command[1..]),
Some(arg) => arg.starts_with('-'),
None => false,
}
}
fn run_cli() -> Result<i32> {
// Fire-and-forget telemetry ping (1/day, non-blocking)
core::telemetry::maybe_ping();
@@ -2061,8 +2106,13 @@ fn run_cli() -> Result<i32> {
}
Commands::Test { command } => {
let cmd = command.join(" ");
runner::run_test(&cmd, cli.verbose)?
if is_native_test_expression(&command) {
let args: Vec<OsString> = command.into_iter().map(OsString::from).collect();
core::runner::run_passthrough("test", &args, cli.verbose)?
} else {
let cmd = command.join(" ");
runner::run_test(&cmd, cli.verbose)?
}
}
Commands::Json {
@@ -2350,6 +2400,7 @@ fn run_cli() -> Result<i32> {
all,
format,
failures,
recalls,
reset,
yes,
} => {
@@ -2365,6 +2416,7 @@ fn run_cli() -> Result<i32> {
all,
&format,
failures,
recalls,
reset,
yes,
cli.verbose,
@@ -2383,12 +2435,32 @@ fn run_cli() -> Result<i32> {
0
}
Commands::Config { create } => {
if create {
let path = core::config::Config::create_default()?;
println!("Created: {}", path.display());
} else {
core::config::show_config()?;
Commands::Config { create, action } => {
match action {
Some(ConfigAction::Recall { mode: None }) => {
core::config::show_recall_mode()?;
}
Some(ConfigAction::Recall { mode: Some(mode) }) => {
use core::retriever::RecoveryMode;
let parsed = match mode.as_str() {
"sqlite" => RecoveryMode::Sqlite,
"tee" => RecoveryMode::Tee,
"disabled" => RecoveryMode::Disabled,
other => anyhow::bail!(
"unknown recall mode '{other}' (expected: sqlite, tee, disabled)"
),
};
let path = core::config::set_recall_mode(parsed)?;
println!("recall mode set to {mode} in {}", path.display());
}
None => {
if create {
let path = core::config::Config::create_default()?;
println!("Created: {}", path.display());
} else {
core::config::show_config()?;
}
}
}
0
}
@@ -2768,6 +2840,22 @@ fn run_cli() -> Result<i32> {
}
}
Commands::Recall {
hash,
full,
from,
lines,
grep,
list,
} => core::retriever::run_recall(core::retriever::RecallArgs {
hash: hash.as_deref(),
full,
from,
lines,
grep: grep.as_deref(),
list,
})?,
Commands::Proxy { args } => {
use std::io::{Read, Write};
use std::process::Stdio;
@@ -3392,6 +3480,30 @@ mod tests {
}
}
#[test]
fn test_dash_d_routes_to_native_test_expression() {
let command = vec!["-d".to_string(), "graphify-out".to_string()];
assert!(is_native_test_expression(&command));
}
#[test]
fn test_bang_before_command_is_not_a_native_expression() {
let command = vec!["!".to_string(), "false".to_string()];
assert!(!is_native_test_expression(&command));
}
#[test]
fn test_bang_before_operator_is_a_native_expression() {
let command = vec!["!".to_string(), "-d".to_string(), "dir".to_string()];
assert!(is_native_test_expression(&command));
}
#[test]
fn test_cargo_test_stays_test_runner() {
let command = vec!["cargo".to_string(), "test".to_string()];
assert!(!is_native_test_expression(&command));
}
#[test]
fn test_try_parse_git_with_dash_c_succeeds() {
let result = Cli::try_parse_from(["rtk", "git", "-C", "/path", "status"]);
+26
View File
@@ -209,3 +209,29 @@ fn dash_m_max_count_is_per_file_like_grep_n() {
let f2 = write(d.path(), "b.txt", "hit\nhit\nhit\n");
assert_eq_grep_with_and_without_n(&["-m", "2", "hit", &f1, &f2]); // 2 per file, both files
}
// Regression: the `-l` short used to be bound to RTK's --max-len, so `grep -l PAT`
// made clap read PAT as a usize and error out (0% savings via raw fallback).
// `-l` is GNU grep's --files-with-matches; `rtk grep -l` must match `grep -l`
// byte-for-byte (explicit file args => deterministic order). Also covers `-l`
// trailing (arg-order sensitivity) and `-L` (--files-without-match).
#[test]
fn dash_l_and_dash_cap_l_match_grep() {
let d = tempfile::tempdir().unwrap();
let f1 = write(d.path(), "hit1.txt", "alpha\ntenant_id here\n");
let f2 = write(d.path(), "miss.txt", "nothing to see\n");
let f3 = write(d.path(), "hit2.txt", "tenant_id again\n");
let f4 = write(d.path(), "port.txt", "listen on 8080\n");
assert_eq_grep(&["-l", "tenant_id", &f1, &f2, &f3]); // -l leading (the token that broke)
assert_eq_grep(&["tenant_id", &f1, &f2, &f3, "-l"]); // -l trailing
assert_eq_grep(&["-L", "tenant_id", &f1, &f2, &f3]); // -L files-without-match
// A numeric pattern is the only form that failed silently: bound to `usize`,
// `-l` swallowed it as max_len and read the first path as the pattern, so rtk
// printed nothing and exited 1 while grep listed the file. A non-numeric
// pattern stops at clap's parse error and falls back to raw grep, which is
// byte-identical here and so invisible to the assertions above.
assert_eq_grep(&["-l", "8080", &f4, &f2]);
assert_eq_grep(&["-L", "8080", &f4, &f2]);
}
+91
View File
@@ -0,0 +1,91 @@
#![cfg(unix)]
//! End-to-end coverage for `Commands::Test` routing.
//!
//! `rtk test` doubles as a wrapper around a test runner and as the POSIX `test`
//! utility. The unit tests in `main.rs` cover `is_native_test_expression` on its
//! own; these run the binary so an inverted or removed branch in the `Commands::Test`
//! arm fails here instead of shipping.
use std::path::Path;
use std::process::Command;
use tempfile::TempDir;
fn exit_code(cwd: &Path, args: &[&str]) -> i32 {
Command::new(env!("CARGO_BIN_EXE_rtk"))
.env("LC_ALL", "C")
.env("HOME", cwd.join("home"))
.args(args)
.current_dir(cwd)
.output()
.expect("spawn rtk")
.status
.code()
.expect("rtk exited via signal")
}
fn fixture() -> TempDir {
let dir = TempDir::new().expect("create tempdir");
std::fs::create_dir(dir.path().join("home")).expect("create home");
std::fs::create_dir(dir.path().join("adir")).expect("create adir");
std::fs::write(dir.path().join("afile"), b"").expect("create afile");
dir
}
/// A native expression must reach the system `test`, whose exit code is the answer.
/// Routing it through the shell wrapper instead yields `sh: 0: Illegal option -d`
/// and exit 2 for every one of these.
#[test]
fn native_expressions_carry_the_test_exit_code() {
let dir = fixture();
let cwd = dir.path();
assert_eq!(exit_code(cwd, &["test", "-d", "adir"]), 0);
assert_eq!(exit_code(cwd, &["test", "-d", "nodir"]), 1);
assert_eq!(exit_code(cwd, &["test", "-f", "afile"]), 0);
assert_eq!(exit_code(cwd, &["test", "-f", "nofile"]), 1);
assert_eq!(exit_code(cwd, &["test", "-e", "adir"]), 0);
}
/// `!` negates, so these are the cases the shell wrapper answered backwards
/// rather than loudly: it reported "not a directory" as true for a directory
/// that exists, because `-d` was a missing command and `!` inverted its 127.
#[test]
fn negated_expressions_are_not_answered_backwards() {
let dir = fixture();
let cwd = dir.path();
assert_eq!(exit_code(cwd, &["test", "!", "-d", "adir"]), 1);
assert_eq!(exit_code(cwd, &["test", "!", "-d", "nodir"]), 0);
}
/// `!` and `(` are shell syntax as well as `test` syntax. They mark a native
/// expression only when what they apply to is one, so a command behind `!` still
/// runs under the shell and keeps the exit code negation it had before.
#[test]
fn bang_before_a_command_still_runs_the_command() {
let dir = fixture();
let cwd = dir.path();
assert_eq!(exit_code(cwd, &["test", "!", "false"]), 0);
assert_eq!(exit_code(cwd, &["test", "!", "true"]), 1);
}
/// Argument boundaries survive: the passthrough passes argv through, where the
/// shell wrapper re-split a joined string and saw three arguments here.
#[test]
fn native_expressions_keep_argument_boundaries() {
let dir = fixture();
std::fs::write(dir.path().join("a file"), b"").expect("create spaced file");
assert_eq!(exit_code(dir.path(), &["test", "-f", "a file"]), 0);
}
/// The other direction: a command to run under the test filter still goes to the
/// filter, not to the system `test`, which would reject it as too many arguments.
#[test]
fn commands_still_reach_the_test_runner() {
let dir = fixture();
assert_eq!(exit_code(dir.path(), &["test", "echo", "hello"]), 0);
}