Compare commits
21
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a7de76d7c9 | ||
|
|
9c1cf2f403 | ||
|
|
2425ad68e5 | ||
|
|
8465ca953f | ||
|
|
1177c9c873 | ||
|
|
7571c8e101 | ||
|
|
62f4452276 | ||
|
|
1481bc5909 | ||
|
|
7dbef2ce00 | ||
|
|
374fe64cfb | ||
|
|
09b3ff9424 | ||
|
|
d44fd3e034 | ||
|
|
7217562355 | ||
|
|
eefeae4565 | ||
|
|
158c74527f | ||
|
|
d9ef47f998 | ||
|
|
402c48e669 | ||
|
|
41a6c6bf6d | ||
|
|
e1f2845df0 | ||
|
|
09979cf297 | ||
|
|
d1b37ced01 |
No files matched your search
@@ -5,6 +5,14 @@ All notable changes to rtk (Rust Token Killer) will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Features
|
||||
|
||||
* **aws:** expand CLI filters from 8 to 25 subcommands — CloudWatch Logs, CloudFormation events, Lambda, IAM, DynamoDB (with type unwrapping), ECS tasks, EC2 security groups, S3API objects, S3 sync/cp, EKS, SQS, Secrets Manager ([#885](https://github.com/rtk-ai/rtk/pull/885))
|
||||
* **aws:** add shared runner `run_aws_filtered()` eliminating per-handler boilerplate
|
||||
* **tee:** add `force_tee_hint()` — truncated output saves full data to file with recovery hint
|
||||
|
||||
## [0.34.1](https://github.com/rtk-ai/rtk/compare/v0.34.0...v0.34.1) (2026-03-28)
|
||||
|
||||
|
||||
|
||||
@@ -201,6 +201,18 @@ rtk bundle install # Ruby gems (strip Using lines)
|
||||
rtk prisma generate # Schema generation (no ASCII art)
|
||||
```
|
||||
|
||||
### AWS
|
||||
```bash
|
||||
rtk aws sts get-caller-identity # One-line identity
|
||||
rtk aws ec2 describe-instances # Compact instance list
|
||||
rtk aws lambda list-functions # Name/runtime/memory (strips secrets)
|
||||
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
|
||||
```
|
||||
|
||||
### Containers
|
||||
```bash
|
||||
rtk docker ps # Compact container list
|
||||
@@ -419,6 +431,7 @@ Blocked on upstream BeforeToolCallback support ([mistral-vibe#531](https://githu
|
||||
| `rspec` / `bundle exec rspec` | `rtk rspec` |
|
||||
| `rubocop` / `bundle exec rubocop` | `rtk rubocop` |
|
||||
| `bundle install/update` | `rtk bundle ...` |
|
||||
| `aws sts/ec2/lambda/...` | `rtk aws ...` |
|
||||
| `docker ps/images/logs` | `rtk docker ...` |
|
||||
| `kubectl get/logs` | `rtk kubectl ...` |
|
||||
| `curl` | `rtk curl` |
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
## Specifics
|
||||
|
||||
- `aws_cmd.rs` forces `--output json` for structured parsing
|
||||
- `aws_cmd.rs` — 25 specialized filters covering STS, S3, EC2, ECS, RDS, CloudFormation, CloudWatch Logs, Lambda, IAM, DynamoDB, EKS, SQS, Secrets Manager. Forces `--output json` for structured parsing, uses `force_tee_hint()` for truncation recovery, strips Lambda secrets. Shared runner `run_aws_filtered()` handles boilerplate for JSON-based filters; text-based filters (S3 ls, S3 sync/cp) have dedicated runners
|
||||
- `container.rs` handles both Docker and Kubernetes; `DockerCommands` and `KubectlCommands` sub-enums in `main.rs` route to `container::run()` -- uses passthrough for unknown subcommands
|
||||
- `curl_cmd.rs` auto-detects JSON responses and shows schema (structure without values)
|
||||
- `wget_cmd.rs` wraps wget with output filtering
|
||||
|
||||
+2156
-155
File diff suppressed because it is too large.
Load diff
+18
-31
@@ -54,35 +54,30 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
|
||||
fn filter_curl_output(output: &str) -> String {
|
||||
let trimmed = output.trim();
|
||||
|
||||
// Try JSON detection: starts with { or [
|
||||
// JSON output: pass through unchanged to preserve validity for piping (#1015)
|
||||
if (trimmed.starts_with('{') || trimmed.starts_with('['))
|
||||
&& (trimmed.ends_with('}') || trimmed.ends_with(']'))
|
||||
{
|
||||
if let Ok(schema) = json_cmd::filter_json_string(trimmed, 5) {
|
||||
// Only use schema if it's actually shorter than the original (#297)
|
||||
if schema.len() <= trimmed.len() {
|
||||
return schema;
|
||||
}
|
||||
}
|
||||
return trimmed.to_string();
|
||||
}
|
||||
|
||||
// Not JSON: truncate long output
|
||||
// Non-JSON: truncate long output
|
||||
let lines: Vec<&str> = trimmed.lines().collect();
|
||||
if lines.len() > 30 {
|
||||
let mut result: Vec<&str> = lines[..30].to_vec();
|
||||
if lines.len() > 50 {
|
||||
let mut result: Vec<&str> = lines[..50].to_vec();
|
||||
result.push("");
|
||||
let msg = format!(
|
||||
"... ({} more lines, {} bytes total)",
|
||||
lines.len() - 30,
|
||||
lines.len() - 50,
|
||||
trimmed.len()
|
||||
);
|
||||
return format!("{}\n{}", result.join("\n"), msg);
|
||||
}
|
||||
|
||||
// Short output: return as-is but truncate long lines
|
||||
// Short non-JSON output: truncate long lines
|
||||
lines
|
||||
.iter()
|
||||
.map(|l| truncate(l, 200))
|
||||
.map(|l| truncate(l, 300))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
@@ -92,20 +87,15 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_json() {
|
||||
// Large JSON where schema is shorter than original — schema should be returned
|
||||
let output = r#"{"name": "a very long user name here", "count": 42, "items": [1, 2, 3], "description": "a very long description that takes up many characters in the original JSON payload", "status": "active", "url": "https://example.com/api/v1/users/123"}"#;
|
||||
fn test_filter_curl_json_preserves_valid_json() {
|
||||
// curl output must remain valid JSON for downstream parsers (#1015)
|
||||
let output = r#"{"name": "test", "count": 42, "items": [1, 2, 3]}"#;
|
||||
let result = filter_curl_output(output);
|
||||
assert!(result.contains("name"));
|
||||
assert!(result.contains("string"));
|
||||
assert!(result.contains("int"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_json_array() {
|
||||
let output = r#"[{"id": 1}, {"id": 2}]"#;
|
||||
let result = filter_curl_output(output);
|
||||
assert!(result.contains("id"));
|
||||
assert!(result.contains("\"name\""));
|
||||
assert!(result.contains("42"));
|
||||
// Must be parseable as JSON
|
||||
assert!(serde_json::from_str::<serde_json::Value>(&result).is_ok(),
|
||||
"curl output must be valid JSON: {}", result);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -118,21 +108,18 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_json_small_returns_original() {
|
||||
// Small JSON where schema would be larger than original (issue #297)
|
||||
let output = r#"{"r2Ready":true,"status":"ok"}"#;
|
||||
let result = filter_curl_output(output);
|
||||
// Schema would be "{\n r2Ready: bool,\n status: string\n}" which is longer
|
||||
// Should return the original JSON unchanged
|
||||
assert_eq!(result.trim(), output.trim());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_curl_long_output() {
|
||||
let lines: Vec<String> = (0..50).map(|i| format!("Line {}", i)).collect();
|
||||
let lines: Vec<String> = (0..80).map(|i| format!("Line {}", i)).collect();
|
||||
let output = lines.join("\n");
|
||||
let result = filter_curl_output(&output);
|
||||
assert!(result.contains("Line 0"));
|
||||
assert!(result.contains("Line 29"));
|
||||
assert!(result.contains("Line 49"));
|
||||
assert!(result.contains("more lines"));
|
||||
}
|
||||
}
|
||||
+7
-25
@@ -785,31 +785,13 @@ fn pr_create(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
}
|
||||
|
||||
fn pr_merge(args: &[String], _verbose: u8) -> Result<i32> {
|
||||
let pr_num = args
|
||||
.iter()
|
||||
.find(|a| !a.starts_with('-'))
|
||||
.map(|s| s.as_str())
|
||||
.unwrap_or("")
|
||||
.to_string();
|
||||
let mut cmd = resolved_command("gh");
|
||||
cmd.args(["pr", "merge"]);
|
||||
for arg in args {
|
||||
cmd.arg(arg);
|
||||
}
|
||||
runner::run_filtered(
|
||||
cmd,
|
||||
"gh",
|
||||
"pr merge",
|
||||
move |_stdout| {
|
||||
let detail = if !pr_num.is_empty() {
|
||||
format!("#{}", pr_num)
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
ok_confirmation("merged", &detail)
|
||||
},
|
||||
RunOptions::stdout_only().early_exit_on_failure(),
|
||||
)
|
||||
// gh pr merge is a destructive action — pass through the real output
|
||||
// so the user (or AI agent) sees exactly what happened.
|
||||
run_passthrough("gh", "pr", &{
|
||||
let mut a = vec!["merge".to_string()];
|
||||
a.extend_from_slice(args);
|
||||
a
|
||||
})
|
||||
}
|
||||
|
||||
/// Flags that change `gh pr diff` output from unified diff to a different format.
|
||||
|
||||
+21
-2
@@ -330,8 +330,9 @@ pub(crate) fn compact_diff(diff: &str, max_lines: usize) -> String {
|
||||
}
|
||||
in_hunk = true;
|
||||
hunk_shown = 0;
|
||||
let hunk_info = line.split("@@").nth(1).unwrap_or("").trim();
|
||||
result.push(format!(" @@ {} @@", hunk_info));
|
||||
// Preserve the full unified diff hunk header, including trailing
|
||||
// function / symbol context after the second @@ marker.
|
||||
result.push(format!(" {}", line));
|
||||
} else if in_hunk {
|
||||
if line.starts_with('+') && !line.starts_with("+++") {
|
||||
added += 1;
|
||||
@@ -1744,6 +1745,24 @@ mod tests {
|
||||
assert!(result.contains("+"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_diff_preserves_full_hunk_header_context() {
|
||||
let diff = r#"diff --git a/foo.rs b/foo.rs
|
||||
--- a/foo.rs
|
||||
+++ b/foo.rs
|
||||
@@ -10,3 +10,4 @@ fn important_context() {
|
||||
fn main() {
|
||||
+ println!("hello");
|
||||
}
|
||||
"#;
|
||||
let result = compact_diff(diff, 100);
|
||||
assert!(
|
||||
result.contains("@@ -10,3 +10,4 @@ fn important_context() {"),
|
||||
"Expected full hunk header with trailing context, got:\n{}",
|
||||
result
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compact_diff_increased_hunk_limit() {
|
||||
// Build a hunk with 25 changed lines — should NOT be truncated with limit 30
|
||||
|
||||
+254
-33
@@ -439,25 +439,8 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
for (test, outputs) in &pkg_result.failed_tests {
|
||||
result.push_str(&format!(" [FAIL] {}\n", test));
|
||||
|
||||
// Show failure output (limit to key lines)
|
||||
let relevant_lines: Vec<&String> = outputs
|
||||
.iter()
|
||||
.filter(|line| {
|
||||
let lower = line.to_lowercase();
|
||||
!line.trim().is_empty()
|
||||
&& !line.starts_with("=== RUN")
|
||||
&& !line.starts_with("--- FAIL")
|
||||
&& (lower.contains("error")
|
||||
|| lower.contains("expected")
|
||||
|| lower.contains("got")
|
||||
|| lower.contains("panic")
|
||||
|| line.trim().starts_with("at "))
|
||||
})
|
||||
.take(5)
|
||||
.collect();
|
||||
|
||||
for line in relevant_lines {
|
||||
result.push_str(&format!(" {}\n", truncate(line, 100)));
|
||||
for line in select_go_test_failure_lines(outputs) {
|
||||
result.push_str(&format!(" {}\n", truncate(&line, 100)));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -465,26 +448,86 @@ fn filter_go_test_json(output: &str) -> String {
|
||||
result.trim().to_string()
|
||||
}
|
||||
|
||||
fn select_go_test_failure_lines(outputs: &[String]) -> Vec<String> {
|
||||
let mut relevant = Vec::new();
|
||||
let mut keep_next_context_line = false;
|
||||
|
||||
for line in outputs {
|
||||
let trimmed = line.trim();
|
||||
|
||||
if trimmed.is_empty()
|
||||
|| trimmed.starts_with("=== RUN")
|
||||
|| trimmed.starts_with("--- FAIL")
|
||||
|| trimmed.starts_with("--- PASS")
|
||||
{
|
||||
keep_next_context_line = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
let is_location = is_go_test_location_line(trimmed);
|
||||
let is_failure = is_go_test_failure_line(trimmed);
|
||||
|
||||
if is_location || is_failure || keep_next_context_line {
|
||||
relevant.push(trimmed.to_string());
|
||||
keep_next_context_line = is_location;
|
||||
} else {
|
||||
keep_next_context_line = false;
|
||||
}
|
||||
|
||||
if relevant.len() >= 5 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if relevant.is_empty() {
|
||||
if let Some(line) = outputs.iter().map(|line| line.trim()).find(|line| {
|
||||
!line.is_empty()
|
||||
&& !line.starts_with("=== RUN")
|
||||
&& !line.starts_with("--- FAIL")
|
||||
&& !line.starts_with("--- PASS")
|
||||
}) {
|
||||
relevant.push(line.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
relevant
|
||||
}
|
||||
|
||||
fn is_go_test_location_line(line: &str) -> bool {
|
||||
if let Some((_, rest)) = line.split_once(".go:") {
|
||||
rest.chars()
|
||||
.next()
|
||||
.map(|c| c.is_ascii_digit())
|
||||
.unwrap_or(false)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn is_go_test_failure_line(line: &str) -> bool {
|
||||
let lower = line.to_lowercase();
|
||||
|
||||
lower.starts_with("panic:")
|
||||
|| lower.starts_with("error:")
|
||||
|| lower.contains(" error:")
|
||||
|| lower.contains("expected")
|
||||
|| lower.contains("got")
|
||||
|| lower.contains("want")
|
||||
|| lower.contains("actual")
|
||||
|| lower.contains("assert")
|
||||
|| lower.contains("mismatch")
|
||||
|| lower.contains("unexpected")
|
||||
|| lower.contains("fatal")
|
||||
|| line.starts_with("at ")
|
||||
}
|
||||
|
||||
/// Filter go build output - show only errors
|
||||
fn filter_go_build(output: &str) -> String {
|
||||
let mut errors: Vec<String> = Vec::new();
|
||||
|
||||
for line in output.lines() {
|
||||
let trimmed = line.trim();
|
||||
let lower = trimmed.to_lowercase();
|
||||
|
||||
// Skip package markers (# package/name lines without errors)
|
||||
if trimmed.starts_with('#') && !lower.contains("error") {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Collect error lines (file:line:col format or error keywords)
|
||||
if !trimmed.is_empty()
|
||||
&& (lower.contains("error")
|
||||
|| trimmed.contains(".go:")
|
||||
|| lower.contains("undefined")
|
||||
|| lower.contains("cannot"))
|
||||
{
|
||||
if is_go_build_error_line(trimmed) {
|
||||
errors.push(trimmed.to_string());
|
||||
}
|
||||
}
|
||||
@@ -508,6 +551,63 @@ fn filter_go_build(output: &str) -> String {
|
||||
result.trim().to_string()
|
||||
}
|
||||
|
||||
fn is_go_build_error_line(line: &str) -> bool {
|
||||
let trimmed = line.trim();
|
||||
if trimmed.is_empty() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let lower = trimmed.to_lowercase();
|
||||
|
||||
// Go download/progress lines often contain package names like pkg/errors,
|
||||
// xerrors, or multierror. These are not compilation failures.
|
||||
if lower.starts_with("go: downloading ")
|
||||
|| lower.starts_with("go: finding ")
|
||||
|| lower.starts_with("go: extracting ")
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
// Package headers are context, not errors by themselves.
|
||||
if trimmed.starts_with('#') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Canonical compiler/config error locations: file:line:col: ...
|
||||
let is_go_config_location = !lower.starts_with("go: ")
|
||||
&& (lower.contains("go.mod:")
|
||||
|| lower.contains("go.work:")
|
||||
|| lower.contains("go.sum:"));
|
||||
if trimmed.contains(".go:") || is_go_config_location {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Some compiler/module failures do not include a file.go:line:col location.
|
||||
let non_file_error_prefixes = [
|
||||
"undefined: ",
|
||||
"cannot use ",
|
||||
"cannot find package ",
|
||||
"no required module provides package ",
|
||||
"missing go.sum entry for module providing package ",
|
||||
"found packages ",
|
||||
"go: go.mod file not found in current directory or any parent directory",
|
||||
"go: cannot load module ",
|
||||
"go: build failed",
|
||||
"go: error ",
|
||||
"error: ",
|
||||
"go: updates to go.mod needed",
|
||||
"go: inconsistent vendoring",
|
||||
"no go files in ",
|
||||
];
|
||||
|
||||
non_file_error_prefixes
|
||||
.iter()
|
||||
.any(|prefix| lower.starts_with(prefix))
|
||||
|| lower.contains("import cycle not allowed")
|
||||
|| lower.contains("build constraints exclude all go files")
|
||||
|| lower.contains("function main is undeclared in the main package")
|
||||
}
|
||||
|
||||
/// Filter go vet output - show issues
|
||||
fn filter_go_vet(output: &str) -> String {
|
||||
let mut issues: Vec<String> = Vec::new();
|
||||
@@ -581,6 +681,20 @@ mod tests {
|
||||
assert!(result.contains("expected 5, got 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_test_preserves_file_location_and_followup_context() {
|
||||
let output = r#"{"Time":"2024-01-01T10:00:00Z","Action":"run","Package":"example.com/foo","Test":"TestFail"}
|
||||
{"Time":"2024-01-01T10:00:01Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":"=== RUN TestFail\n"}
|
||||
{"Time":"2024-01-01T10:00:02Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" foo_test.go:42:\n"}
|
||||
{"Time":"2024-01-01T10:00:03Z","Action":"output","Package":"example.com/foo","Test":"TestFail","Output":" values differ after normalization\n"}
|
||||
{"Time":"2024-01-01T10:00:04Z","Action":"fail","Package":"example.com/foo","Test":"TestFail","Elapsed":0.5}
|
||||
{"Time":"2024-01-01T10:00:04Z","Action":"fail","Package":"example.com/foo","Elapsed":0.5}"#;
|
||||
|
||||
let result = filter_go_test_json(output);
|
||||
assert!(result.contains("foo_test.go:42:"));
|
||||
assert!(result.contains("values differ after normalization"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_success() {
|
||||
let output = "";
|
||||
@@ -601,6 +715,113 @@ main.go:15:2: cannot use x (type int) as type string"#;
|
||||
assert!(result.contains("cannot use x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_ignores_download_lines_with_error_in_package_names() {
|
||||
let output = r#"go: downloading github.com/go-errors/errors v1.5.1
|
||||
go: finding module for package example.com/foo
|
||||
go: extracting github.com/pkg/errors v0.9.1
|
||||
go: downloading github.com/pkg/errors v0.9.1
|
||||
go: downloading github.com/hashicorp/go-multierror v1.1.1
|
||||
go: downloading golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert_eq!(result, "Go build: Success");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_is_go_build_error_line_recognizes_real_compiler_errors() {
|
||||
assert!(is_go_build_error_line("undefined: missingFunc"));
|
||||
assert!(is_go_build_error_line(
|
||||
"cannot find package \"foo/bar\""
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"found packages a (a.go) and b (b.go) in /tmp/rtk-go-build-probe-mix"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"imports example.com/cycle/a: import cycle not allowed"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"package example.com/buildtag: build constraints exclude all Go files in /tmp/rtk-go-build-probe-buildtag"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"go.mod:3: invalid go version 'not-a-version': must match format 1.23.0"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"go.work:1: invalid go version 'not-a-version': must match format 1.23.0"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"go: go.mod file not found in current directory or any parent directory; see 'go help modules'"
|
||||
));
|
||||
assert!(is_go_build_error_line("no Go files in /tmp/example"));
|
||||
assert!(is_go_build_error_line(
|
||||
"go: cannot load module missing listed in go.work file: open missing/go.mod: no such file or directory"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"runtime.main_main·f: function main is undeclared in the main package"
|
||||
));
|
||||
assert!(is_go_build_error_line(
|
||||
"main.go:10:5: undefined: missingFunc"
|
||||
));
|
||||
assert!(is_go_build_error_line("error: failed to load module"));
|
||||
assert!(!is_go_build_error_line(
|
||||
"go: downloading github.com/pkg/errors v0.9.1"
|
||||
));
|
||||
assert!(!is_go_build_error_line(
|
||||
"go: finding module for package example.com/foo"
|
||||
));
|
||||
assert!(!is_go_build_error_line(
|
||||
"go: extracting github.com/pkg/errors v0.9.1"
|
||||
));
|
||||
assert!(!is_go_build_error_line("# example.com/foo"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_preserves_non_file_error_shapes() {
|
||||
let output = r#"undefined: missingFunc
|
||||
cannot find package "foo/bar"
|
||||
found packages a (a.go) and b (b.go) in /tmp/rtk-go-build-probe-mix
|
||||
imports example.com/cycle/a: import cycle not allowed
|
||||
package example.com/buildtag: build constraints exclude all Go files in /tmp/rtk-go-build-probe-buildtag
|
||||
runtime.main_main·f: function main is undeclared in the main package"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("6 errors"));
|
||||
assert!(result.contains("undefined: missingFunc"));
|
||||
assert!(result.contains("cannot find package \"foo/bar\""));
|
||||
assert!(result.contains("found packages a (a.go) and b (b.go)"));
|
||||
assert!(result.contains("import cycle not allowed"));
|
||||
assert!(result.contains("build constraints exclude all Go files"));
|
||||
assert!(result.contains("function main is undeclared in the main package"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_preserves_go_config_parse_errors() {
|
||||
let output = r#"go: errors parsing go.mod:
|
||||
go.mod:3: invalid go version 'not-a-version': must match format 1.23.0
|
||||
go: errors parsing go.work:
|
||||
go.work:1: invalid go version 'not-a-version': must match format 1.23.0"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("2 errors"));
|
||||
assert!(result.contains("go.mod:3: invalid go version"));
|
||||
assert!(result.contains("go.work:1: invalid go version"));
|
||||
assert!(!result.contains("go: errors parsing go.mod:"));
|
||||
assert!(!result.contains("go: errors parsing go.work:"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_build_preserves_module_root_and_workspace_errors() {
|
||||
let output = r#"go: go.mod file not found in current directory or any parent directory; see 'go help modules'
|
||||
no Go files in /tmp/example
|
||||
go: cannot load module missing listed in go.work file: open missing/go.mod: no such file or directory"#;
|
||||
|
||||
let result = filter_go_build(output);
|
||||
assert!(result.contains("3 errors"));
|
||||
assert!(result.contains("go.mod file not found in current directory or any parent directory"));
|
||||
assert!(result.contains("no Go files in /tmp/example"));
|
||||
assert!(result.contains("go: cannot load module missing listed in go.work file"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_filter_go_vet_no_issues() {
|
||||
let output = "";
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::core::utils::{exit_code_from_output, resolved_command};
|
||||
use anyhow::{Context, Result};
|
||||
use regex::Regex;
|
||||
use std::collections::HashMap;
|
||||
use std::process::Stdio;
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn run(
|
||||
@@ -28,7 +29,9 @@ pub fn run(
|
||||
let rg_pattern = pattern.replace(r"\|", "|");
|
||||
|
||||
let mut rg_cmd = resolved_command("rg");
|
||||
rg_cmd.args(["-n", "--no-heading", &rg_pattern, path]);
|
||||
rg_cmd
|
||||
.args(["-n", "--no-heading", &rg_pattern, path])
|
||||
.stdin(Stdio::null());
|
||||
|
||||
if let Some(ft) = file_type {
|
||||
rg_cmd.arg("--type").arg(ft);
|
||||
@@ -47,6 +50,7 @@ pub fn run(
|
||||
.or_else(|_| {
|
||||
resolved_command("grep")
|
||||
.args(["-rn", pattern, path])
|
||||
.stdin(Stdio::null())
|
||||
.output()
|
||||
})
|
||||
.context("grep/rg failed")?;
|
||||
|
||||
@@ -250,12 +250,12 @@ fn extract_schema(value: &Value, depth: usize, max_depth: usize) -> String {
|
||||
|
||||
if is_simple {
|
||||
if i < keys.len() - 1 {
|
||||
lines.push(format!("{} {}: {},", indent, key, val_trimmed));
|
||||
lines.push(format!("{} \"{}\": {},", indent, key, val_trimmed));
|
||||
} else {
|
||||
lines.push(format!("{} {}: {}", indent, key, val_trimmed));
|
||||
lines.push(format!("{} \"{}\": {}", indent, key, val_trimmed));
|
||||
}
|
||||
} else {
|
||||
lines.push(format!("{} {}:", indent, key));
|
||||
lines.push(format!("{} \"{}\":", indent, key));
|
||||
lines.push(val_schema);
|
||||
}
|
||||
|
||||
@@ -316,16 +316,30 @@ mod tests {
|
||||
fn test_extract_schema_simple() {
|
||||
let json: Value = serde_json::from_str(r#"{"name": "test", "count": 42}"#).unwrap();
|
||||
let schema = extract_schema(&json, 0, 5);
|
||||
assert!(schema.contains("name"));
|
||||
assert!(schema.contains("\"name\""));
|
||||
assert!(schema.contains("string"));
|
||||
assert!(schema.contains("int"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_schema_keys_are_quoted() {
|
||||
let json: Value =
|
||||
serde_json::from_str(r#"{"id": 1, "status": "open", "nested": {"key": "val"}}"#)
|
||||
.unwrap();
|
||||
let schema = extract_schema(&json, 0, 5);
|
||||
assert!(schema.contains("\"id\":"), "keys must be double-quoted: {}", schema);
|
||||
assert!(schema.contains("\"status\":"), "keys must be double-quoted: {}", schema);
|
||||
assert!(schema.contains("\"nested\":"), "keys must be double-quoted: {}", schema);
|
||||
assert!(schema.contains("\"key\":"), "nested keys must be double-quoted: {}", schema);
|
||||
// Verify the output is parseable as valid JSON (values replaced with types)
|
||||
// At minimum, keys should be properly quoted
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_extract_schema_array() {
|
||||
let json: Value = serde_json::from_str(r#"{"items": [1, 2, 3]}"#).unwrap();
|
||||
let schema = extract_schema(&json, 0, 5);
|
||||
assert!(schema.contains("items"));
|
||||
assert!(schema.contains("\"items\""));
|
||||
assert!(schema.contains("(3)"));
|
||||
}
|
||||
}
|
||||
@@ -119,5 +119,7 @@ Consumers must call `timer.track()` on **all** code paths — success, failure,
|
||||
|
||||
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()`.
|
||||
|
||||
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.
|
||||
|
||||
## Adding New Functionality
|
||||
Place new infrastructure code here if it meets **all** of these criteria: (1) it has no dependencies on command modules or hooks, (2) it is used by two or more other modules, and (3) it provides a general-purpose utility rather than command-specific logic. Follow the existing pattern of lazy-initialized resources (`lazy_static!` for regex, on-demand config loading) to preserve the <10ms startup target. Add `#[cfg(test)] mod tests` with unit tests in the same file.
|
||||
@@ -184,6 +184,44 @@ pub fn tee_and_hint(raw: &str, command_slug: &str, exit_code: i32) -> Option<Str
|
||||
Some(format_hint(&path))
|
||||
}
|
||||
|
||||
/// Force tee output regardless of exit code (used when filters truncate).
|
||||
/// Always writes file if size >= MIN_TEE_SIZE and tee is enabled.
|
||||
/// Returns hint string if file was written, None if skipped/disabled.
|
||||
///
|
||||
/// Used by AWS filters when FilterResult.truncated = true, ensuring
|
||||
/// the LLM has access to full untruncated output via the hint path.
|
||||
pub fn force_tee_hint(raw: &str, command_slug: &str) -> Option<String> {
|
||||
// Check RTK_TEE=0 env override (disable)
|
||||
if std::env::var("RTK_TEE").ok().as_deref() == Some("0") {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Skip if output too small
|
||||
if raw.len() < MIN_TEE_SIZE {
|
||||
return None;
|
||||
}
|
||||
|
||||
let config = Config::load().ok()?;
|
||||
|
||||
// Respect enabled flag but ignore mode (force tee)
|
||||
if !config.tee.enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
let tee_dir = get_tee_dir(&config)?;
|
||||
let tee_dir = std::fs::create_dir_all(&tee_dir).ok().and(Some(tee_dir))?;
|
||||
|
||||
let path = write_tee_file(
|
||||
raw,
|
||||
command_slug,
|
||||
&tee_dir,
|
||||
config.tee.max_file_size,
|
||||
config.tee.max_files,
|
||||
)?;
|
||||
|
||||
Some(format_hint(&path))
|
||||
}
|
||||
|
||||
/// TeeMode controls when tee writes files.
|
||||
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Default)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
@@ -400,4 +438,22 @@ directory = "/tmp/rtk-tee"
|
||||
let mode: TeeMode = serde_json::from_str(r#""never""#).unwrap();
|
||||
assert_eq!(mode, TeeMode::Never);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_force_tee_hint_skip_small_output() {
|
||||
// force_tee_hint should respect MIN_TEE_SIZE
|
||||
let small_output = "short error";
|
||||
let hint = force_tee_hint(small_output, "test_cmd");
|
||||
assert!(hint.is_none(), "Should skip output < MIN_TEE_SIZE");
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
}
|
||||
@@ -368,6 +368,42 @@ pub fn tool_exists(name: &str) -> bool {
|
||||
which::which(name).is_ok()
|
||||
}
|
||||
|
||||
/// Extract short name from AWS ARN.
|
||||
/// Example: `arn:aws:ecs:region:acct:service/cluster/name` -> `name`
|
||||
/// For simple ARNs like `arn:aws:iam::123:user/alice`, returns `alice`.
|
||||
pub fn shorten_arn(arn: &str) -> &str {
|
||||
// ARNs use "/" or ":" as separators. Try "/" first (service/cluster/name pattern),
|
||||
// then fall back to ":" for Lambda/IAM ARNs.
|
||||
let slash_result = arn.rsplit('/').next().unwrap_or(arn);
|
||||
// If rsplit('/') returned the whole string (no '/' found), try ':'
|
||||
if slash_result == arn {
|
||||
arn.rsplit(':').next().unwrap_or(arn)
|
||||
} else {
|
||||
slash_result
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert bytes to human-readable format (KB, MB, GB, TB).
|
||||
/// Used for S3 object sizes.
|
||||
pub fn human_bytes(bytes: u64) -> String {
|
||||
const KB: u64 = 1024;
|
||||
const MB: u64 = KB * 1024;
|
||||
const GB: u64 = MB * 1024;
|
||||
const TB: u64 = GB * 1024;
|
||||
|
||||
if bytes >= TB {
|
||||
format!("{:.1} TB", bytes as f64 / TB as f64)
|
||||
} else if bytes >= GB {
|
||||
format!("{:.1} GB", bytes as f64 / GB as f64)
|
||||
} else if bytes >= MB {
|
||||
format!("{:.1} MB", bytes as f64 / MB as f64)
|
||||
} else if bytes >= KB {
|
||||
format!("{:.1} KB", bytes as f64 / KB as f64)
|
||||
} else {
|
||||
format!("{} B", bytes)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -748,4 +784,82 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ===== AWS helper function tests =====
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_ecs_service() {
|
||||
assert_eq!(
|
||||
shorten_arn("arn:aws:ecs:us-east-1:123:service/cluster/api-service"),
|
||||
"api-service"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_iam_user() {
|
||||
assert_eq!(shorten_arn("arn:aws:iam::123456789012:user/alice"), "alice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_lambda() {
|
||||
assert_eq!(
|
||||
shorten_arn("arn:aws:lambda:us-west-2:123:function:my-function"),
|
||||
"my-function"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_shorten_arn_fallback() {
|
||||
// Non-ARN string - return as-is
|
||||
assert_eq!(shorten_arn("simple-name"), "simple-name");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_bytes() {
|
||||
assert_eq!(human_bytes(0), "0 B");
|
||||
assert_eq!(human_bytes(512), "512 B");
|
||||
assert_eq!(human_bytes(1023), "1023 B");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_kb() {
|
||||
assert_eq!(human_bytes(1024), "1.0 KB");
|
||||
assert_eq!(human_bytes(2048), "2.0 KB");
|
||||
assert_eq!(human_bytes(1536), "1.5 KB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_mb() {
|
||||
assert_eq!(human_bytes(1_048_576), "1.0 MB");
|
||||
assert_eq!(human_bytes(5_242_880), "5.0 MB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_gb() {
|
||||
assert_eq!(human_bytes(1_073_741_824), "1.0 GB");
|
||||
assert_eq!(human_bytes(2_147_483_648), "2.0 GB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_human_bytes_tb() {
|
||||
assert_eq!(human_bytes(1_099_511_627_776), "1.0 TB");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_count_tokens_basic() {
|
||||
assert_eq!(count_tokens("hello world"), 2);
|
||||
assert_eq!(count_tokens("one two three four"), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_count_tokens_empty() {
|
||||
assert_eq!(count_tokens(""), 0);
|
||||
assert_eq!(count_tokens(" "), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_count_tokens_multiple_spaces() {
|
||||
assert_eq!(count_tokens("hello world"), 2);
|
||||
assert_eq!(count_tokens(" hello world "), 2);
|
||||
}
|
||||
}
|
||||
+16
-1
@@ -332,7 +332,22 @@ pub const RULES: &[RtkRule] = &[
|
||||
rewrite_prefixes: &["aws"],
|
||||
category: "Infra",
|
||||
savings_pct: 80.0,
|
||||
subcmd_savings: &[],
|
||||
subcmd_savings: &[
|
||||
("sts", 80.0),
|
||||
("s3", 60.0),
|
||||
("ec2", 85.0),
|
||||
("ecs", 90.0),
|
||||
("rds", 80.0),
|
||||
("cloudformation", 90.0),
|
||||
("logs", 88.0),
|
||||
("lambda", 90.0),
|
||||
("iam", 85.0),
|
||||
("dynamodb", 70.0),
|
||||
("s3api", 75.0),
|
||||
("eks", 87.0),
|
||||
("sqs", 78.0),
|
||||
("secretsmanager", 75.0),
|
||||
],
|
||||
subcmd_status: &[],
|
||||
},
|
||||
RtkRule {
|
||||
|
||||
@@ -61,6 +61,39 @@ Controls how `rtk init` modifies agent settings files:
|
||||
|
||||
All file operations use atomic writes (tempfile + rename) to prevent corruption on crash. Settings files are backed up to `.bak` before modification. All operations are idempotent -- running `rtk init` multiple times is safe.
|
||||
|
||||
## Permission Model
|
||||
|
||||
RTK enforces a permission precedence that matches Claude Code's least-privilege default:
|
||||
|
||||
```
|
||||
Deny > Ask > Allow (explicit) > Default (ask)
|
||||
```
|
||||
|
||||
Rules are loaded from all Claude Code `settings.json` files (project + global, including `.local` variants). Only `Bash(...)` rules are extracted; other scopes (Read, Write) are ignored.
|
||||
|
||||
| Verdict | Trigger | rewrite_cmd exit | Hook behavior |
|
||||
|---------|---------|-----------------|---------------|
|
||||
| Deny | `permissions.deny` rule matched | 2 | Passthrough — host tool handles denial |
|
||||
| Ask | `permissions.ask` rule matched | 3 | Rewrite + let host tool prompt user |
|
||||
| Allow | `permissions.allow` rule matched | 0 | Rewrite + auto-allow |
|
||||
| Default | No rule matched | 3 | Rewrite + let host tool prompt user |
|
||||
|
||||
### Per-tool support
|
||||
|
||||
| Tool | ask support | Behavior on Default |
|
||||
|------|------------|-------------------|
|
||||
| Claude Code (rtk-rewrite.sh) | Yes | `permissionDecision: "ask"` — user prompted |
|
||||
| Copilot VS Code (rtk hook copilot) | Yes | `permissionDecision: "ask"` — user prompted |
|
||||
| Gemini CLI (rtk hook gemini) | No (allow/deny only) | allow (limitation — no ask mode in Gemini) |
|
||||
| Copilot CLI (rtk hook copilot) | No updatedInput | deny-with-suggestion (unchanged) |
|
||||
| Codex | ask parsed but no-op | allow (limitation — fails open) |
|
||||
|
||||
### Implementation
|
||||
|
||||
- `permissions.rs` — loads deny/ask/allow rules, evaluates precedence, returns `PermissionVerdict`
|
||||
- `rewrite_cmd.rs` — maps verdict to exit code (consumed by shell hook)
|
||||
- `hook_cmd.rs` — maps verdict to JSON `permissionDecision` field (Copilot/Gemini)
|
||||
|
||||
## Exit Code Contract
|
||||
|
||||
Hook processors in `hook_cmd.rs` must return `Ok(())` on every path — success, no-match, parse error, and unexpected input. Returning `Err` propagates to `main()` and exits non-zero, which blocks the agent's command from executing. This violates the non-blocking guarantee documented in `hooks/README.md`.
|
||||
|
||||
+22
-1
@@ -6,6 +6,7 @@ use serde_json::{json, Value};
|
||||
use std::io::{self, Read};
|
||||
|
||||
use crate::discover::registry::rewrite_command;
|
||||
use crate::hooks::permissions::{check_command, PermissionVerdict};
|
||||
|
||||
// ── Copilot hook (VS Code + Copilot CLI) ──────────────────────
|
||||
|
||||
@@ -111,10 +112,24 @@ fn handle_vscode(cmd: &str) -> Result<()> {
|
||||
None => return Ok(()),
|
||||
};
|
||||
|
||||
let verdict = check_command(cmd);
|
||||
|
||||
// Deny: pass through without rewrite — let the host tool handle it.
|
||||
if verdict == PermissionVerdict::Deny {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Allow (explicit rule matched): auto-allow the rewritten command.
|
||||
// Ask/Default (no allow rule matched): rewrite but let the host tool prompt.
|
||||
let decision = match verdict {
|
||||
PermissionVerdict::Allow => "allow",
|
||||
_ => "ask",
|
||||
};
|
||||
|
||||
let output = json!({
|
||||
"hookSpecificOutput": {
|
||||
"hookEventName": PRE_TOOL_USE_KEY,
|
||||
"permissionDecision": "allow",
|
||||
"permissionDecision": decision,
|
||||
"permissionDecisionReason": "RTK auto-rewrite",
|
||||
"updatedInput": { "command": rewritten }
|
||||
}
|
||||
@@ -170,6 +185,12 @@ pub fn run_gemini() -> Result<()> {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Check deny rules — Gemini CLI only supports allow/deny (no ask mode).
|
||||
if check_command(cmd) == PermissionVerdict::Deny {
|
||||
println!(r#"{{"decision":"deny","reason":"Blocked by RTK permission rule"}}"#);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
// Delegate to the single source of truth for command rewriting
|
||||
match rewrite_command(cmd, &[]) {
|
||||
Some(rewritten) => print_rewrite(&rewritten),
|
||||
|
||||
@@ -11,7 +11,6 @@ use super::constants::{
|
||||
REWRITE_HOOK_FILE, SETTINGS_JSON,
|
||||
};
|
||||
use super::integrity;
|
||||
use crate::core::config;
|
||||
|
||||
// Embedded hook script (guards before set -euo pipefail)
|
||||
const REWRITE_HOOK: &str = include_str!("../../hooks/claude/rtk-rewrite.sh");
|
||||
@@ -293,14 +292,6 @@ pub fn run(
|
||||
}
|
||||
|
||||
println!();
|
||||
let env_disabled = std::env::var("RTK_TELEMETRY_DISABLED").unwrap_or_default() == "1";
|
||||
let config_disabled = matches!(config::telemetry_enabled(), Some(false));
|
||||
if env_disabled || config_disabled {
|
||||
println!(" [info] Anonymous telemetry is disabled");
|
||||
} else {
|
||||
println!(" [info] Anonymous telemetry is enabled by default (opt-out: RTK_TELEMETRY_DISABLED=1)");
|
||||
}
|
||||
println!(" [info] See: https://github.com/rtk-ai/rtk#privacy--telemetry");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
+103
-30
@@ -5,22 +5,24 @@ use std::path::PathBuf;
|
||||
/// Verdict from checking a command against Claude Code's permission rules.
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub enum PermissionVerdict {
|
||||
/// No deny/ask rules matched — safe to auto-allow.
|
||||
/// An explicit allow rule matched — safe to auto-allow.
|
||||
Allow,
|
||||
/// A deny rule matched — pass through to Claude Code's native deny handling.
|
||||
Deny,
|
||||
/// An ask rule matched — rewrite the command but let Claude Code prompt the user.
|
||||
Ask,
|
||||
/// No rule matched — default to ask (matches Claude Code's least-privilege default).
|
||||
Default,
|
||||
}
|
||||
|
||||
/// Check `cmd` against Claude Code's deny/ask permission rules.
|
||||
/// Check `cmd` against Claude Code's deny/ask/allow permission rules.
|
||||
///
|
||||
/// Returns `Allow` when no rules match (preserves existing behavior),
|
||||
/// `Deny` when a deny rule matches, or `Ask` when an ask rule matches.
|
||||
/// Deny takes priority over Ask if both match the same command.
|
||||
/// Precedence: Deny > Ask > Allow > Default (ask).
|
||||
/// Returns `Default` when no rules match — callers should treat this as ask
|
||||
/// to match Claude Code's least-privilege default.
|
||||
pub fn check_command(cmd: &str) -> PermissionVerdict {
|
||||
let (deny_rules, ask_rules) = load_deny_ask_rules();
|
||||
check_command_with_rules(cmd, &deny_rules, &ask_rules)
|
||||
let (deny_rules, ask_rules, allow_rules) = load_permission_rules();
|
||||
check_command_with_rules(cmd, &deny_rules, &ask_rules, &allow_rules)
|
||||
}
|
||||
|
||||
/// Internal implementation allowing tests to inject rules without file I/O.
|
||||
@@ -28,9 +30,11 @@ pub(crate) fn check_command_with_rules(
|
||||
cmd: &str,
|
||||
deny_rules: &[String],
|
||||
ask_rules: &[String],
|
||||
allow_rules: &[String],
|
||||
) -> PermissionVerdict {
|
||||
let segments = split_compound_command(cmd);
|
||||
let mut any_ask = false;
|
||||
let mut any_allow = false;
|
||||
|
||||
for segment in &segments {
|
||||
let segment = segment.trim();
|
||||
@@ -38,6 +42,7 @@ pub(crate) fn check_command_with_rules(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Deny takes highest priority
|
||||
for pattern in deny_rules {
|
||||
if command_matches_pattern(segment, pattern) {
|
||||
return PermissionVerdict::Deny;
|
||||
@@ -52,16 +57,28 @@ pub(crate) fn check_command_with_rules(
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !any_allow && !any_ask {
|
||||
for pattern in allow_rules {
|
||||
if command_matches_pattern(segment, pattern) {
|
||||
any_allow = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Precedence: Deny > Ask > Allow > Default (ask)
|
||||
if any_ask {
|
||||
PermissionVerdict::Ask
|
||||
} else {
|
||||
} else if any_allow {
|
||||
PermissionVerdict::Allow
|
||||
} else {
|
||||
PermissionVerdict::Default
|
||||
}
|
||||
}
|
||||
|
||||
/// Load deny and ask Bash rules from all Claude Code settings files.
|
||||
/// Load deny, ask, and allow Bash rules from all Claude Code settings files.
|
||||
///
|
||||
/// Files read (in order, later files do not override earlier ones — all are merged):
|
||||
/// 1. `$PROJECT_ROOT/.claude/settings.json`
|
||||
@@ -70,9 +87,10 @@ pub(crate) fn check_command_with_rules(
|
||||
/// 4. `~/.claude/settings.local.json`
|
||||
///
|
||||
/// Missing files and malformed JSON are silently skipped.
|
||||
fn load_deny_ask_rules() -> (Vec<String>, Vec<String>) {
|
||||
fn load_permission_rules() -> (Vec<String>, Vec<String>, Vec<String>) {
|
||||
let mut deny_rules = Vec::new();
|
||||
let mut ask_rules = Vec::new();
|
||||
let mut allow_rules = Vec::new();
|
||||
|
||||
for path in get_settings_paths() {
|
||||
let Ok(content) = std::fs::read_to_string(&path) else {
|
||||
@@ -87,9 +105,10 @@ fn load_deny_ask_rules() -> (Vec<String>, Vec<String>) {
|
||||
|
||||
append_bash_rules(permissions.get("deny"), &mut deny_rules);
|
||||
append_bash_rules(permissions.get("ask"), &mut ask_rules);
|
||||
append_bash_rules(permissions.get("allow"), &mut allow_rules);
|
||||
}
|
||||
|
||||
(deny_rules, ask_rules)
|
||||
(deny_rules, ask_rules, allow_rules)
|
||||
}
|
||||
|
||||
/// Extract Bash-scoped patterns from a JSON array and append them to `target`.
|
||||
@@ -293,31 +312,28 @@ mod tests {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
let ask = vec!["git push --force".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &deny, &ask),
|
||||
check_command_with_rules("git push --force", &deny, &ask, &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_bash_rules_ignored() {
|
||||
// Non-Bash rules (e.g. Read, Write) must not match Bash commands.
|
||||
// In load_deny_ask_rules, only Bash( rules are kept — we verify that
|
||||
// extract_bash_pattern returns the original string for non-Bash rules.
|
||||
assert_eq!(extract_bash_pattern("Read(**/.env*)"), "Read(**/.env*)");
|
||||
|
||||
// With empty rule sets (what you get after filtering out non-Bash rules),
|
||||
// verdict is always Allow.
|
||||
// With empty rule sets, verdict is Default (not Allow).
|
||||
assert_eq!(
|
||||
check_command_with_rules("cat .env", &[], &[]),
|
||||
PermissionVerdict::Allow
|
||||
check_command_with_rules("cat .env", &[], &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_empty_permissions() {
|
||||
// No rules at all → Default (ask), not Allow.
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &[], &[]),
|
||||
PermissionVerdict::Allow
|
||||
check_command_with_rules("git push --force", &[], &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
@@ -348,7 +364,7 @@ mod tests {
|
||||
fn test_compound_command_deny() {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status && git push --force", &deny, &[]),
|
||||
check_command_with_rules("git status && git push --force", &deny, &[], &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
@@ -357,7 +373,7 @@ mod tests {
|
||||
fn test_compound_command_ask() {
|
||||
let ask = vec!["git push".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status && git push origin main", &[], &ask),
|
||||
check_command_with_rules("git status && git push origin main", &[], &ask, &[]),
|
||||
PermissionVerdict::Ask
|
||||
);
|
||||
}
|
||||
@@ -366,9 +382,8 @@ mod tests {
|
||||
fn test_compound_command_deny_overrides_ask() {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
let ask = vec!["git status".to_string()];
|
||||
// deny in compound cmd takes priority even if ask also matches a segment
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status && git push --force", &deny, &ask),
|
||||
check_command_with_rules("git status && git push --force", &deny, &ask, &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
@@ -377,7 +392,7 @@ mod tests {
|
||||
fn test_ask_verdict() {
|
||||
let ask = vec!["git push".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push origin main", &[], &ask),
|
||||
check_command_with_rules("git push origin main", &[], &ask, &[]),
|
||||
PermissionVerdict::Ask
|
||||
);
|
||||
}
|
||||
@@ -441,12 +456,12 @@ mod tests {
|
||||
fn test_deny_with_leading_wildcard() {
|
||||
let deny = vec!["* --force".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &deny, &[]),
|
||||
check_command_with_rules("git push --force", &deny, &[], &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push", &deny, &[]),
|
||||
PermissionVerdict::Allow
|
||||
check_command_with_rules("git push", &deny, &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
@@ -455,8 +470,66 @@ mod tests {
|
||||
fn test_deny_star_colon_star() {
|
||||
let deny = vec!["*:*".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("rm -rf /", &deny, &[]),
|
||||
check_command_with_rules("rm -rf /", &deny, &[], &[]),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
|
||||
// --- Allow rules tests ---
|
||||
|
||||
#[test]
|
||||
fn test_explicit_allow_rule() {
|
||||
let allow = vec!["git status".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git status", &[], &[], &allow),
|
||||
PermissionVerdict::Allow
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_allow_wildcard() {
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git log --oneline", &[], &[], &allow),
|
||||
PermissionVerdict::Allow
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_deny_overrides_allow() {
|
||||
let deny = vec!["git push --force".to_string()];
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push --force", &deny, &[], &allow),
|
||||
PermissionVerdict::Deny
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ask_overrides_allow() {
|
||||
let ask = vec!["git push".to_string()];
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("git push origin main", &[], &ask, &allow),
|
||||
PermissionVerdict::Ask
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_no_rules_returns_default() {
|
||||
assert_eq!(
|
||||
check_command_with_rules("cargo test", &[], &[], &[]),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_default_not_allow_when_unmatched() {
|
||||
// Commands not in any list should get Default, not Allow
|
||||
let allow = vec!["git *".to_string()];
|
||||
assert_eq!(
|
||||
check_command_with_rules("cargo build", &[], &[], &allow),
|
||||
PermissionVerdict::Default
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ pub fn run(cmd: &str) -> anyhow::Result<()> {
|
||||
let _ = std::io::stdout().flush();
|
||||
Ok(())
|
||||
}
|
||||
PermissionVerdict::Ask => {
|
||||
PermissionVerdict::Ask | PermissionVerdict::Default => {
|
||||
print!("{}", rewritten);
|
||||
let _ = std::io::stdout().flush();
|
||||
std::process::exit(3);
|
||||
|
||||
Reference in new issue
Block a user