Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
116 changes: 73 additions & 43 deletions src/cmds/cloud/container.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,18 @@ where
fn docker_ps(_verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();

// Baseline the LLM would otherwise see.
let raw = exec_capture(resolved_command("docker").args(["ps"]))
.map(|r| r.stdout)
.unwrap_or_default();

// One structured call over *all* containers (`-a`) — splitting on the State
// field lets us list crashed/exited ones too, which plain `docker ps` hides.
let result = exec_capture(resolved_command("docker").args([
"ps",
"-a",
"--format",
"{{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Image}}\t{{.Ports}}",
"{{.State}}\t{{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Image}}\t{{.Ports}}",
]))
.context("Failed to run docker ps")?;

Expand All @@ -71,43 +75,66 @@ fn docker_ps(_verbose: u8) -> Result<i32> {
return Ok(result.exit_code);
}

let stdout = result.stdout;
let mut rtk = String::new();
let format_line = |parts: &[&str], with_ports: bool| -> Option<String> {
// parts: State, ID, Names, Status, Image, Ports
if parts.len() < 5 {
return None;
}
let id = &parts[1][..12.min(parts[1].len())];
let name = parts[2];
// Keep the Status verbatim — it carries health ("Up 4s (unhealthy)")
// and exit-code/restart info an agent needs to judge service health.
let status = parts[3].trim();
let short_image = parts[4].split('/').next_back().unwrap_or("");
let port_suffix = if with_ports {
let ports = compact_ports(parts.get(5).unwrap_or(&""));
if ports == "-" {
String::new()
} else {
format!(" [{}]", ports)
}
} else {
String::new()
};
Some(format!(
" {} {} ({}) {}{}\n",
id, name, short_image, status, port_suffix
))
};

if stdout.trim().is_empty() {
rtk.push_str("[docker] 0 containers");
println!("{}", rtk);
timer.track("docker ps", "rtk docker ps", &raw, &rtk);
return Ok(0);
let mut running: Vec<Vec<&str>> = Vec::new();
let mut stopped: Vec<Vec<&str>> = Vec::new();
for line in result.stdout.lines().filter(|l| !l.trim().is_empty()) {
let parts: Vec<&str> = line.split('\t').collect();
let state = parts.first().copied().unwrap_or("");
if matches!(state, "running" | "restarting") {
running.push(parts);
} else {
stopped.push(parts);
}
}

let count = stdout.lines().count();
rtk.push_str(&format!("[docker] {} containers:\n", count));
let mut rtk = String::new();
rtk.push_str(&format!("[docker] {} running:\n", running.len()));
for parts in running.iter().take(20) {
if let Some(l) = format_line(parts, true) {
rtk.push_str(&l);
}
}
if running.len() > 20 {
rtk.push_str(&format!(" ... +{} more\n", running.len() - 20));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick, prefer utf8 character …

Suggested change
rtk.push_str(&format!(" ... +{} more\n", running.len() - 20));
rtk.push_str(&format!(" … +{} more\n", running.len() - 20));

}

for line in stdout.lines().take(15) {
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 4 {
let id = &parts[0][..12.min(parts[0].len())];
let name = parts[1];
let short_image = parts
.get(3)
.unwrap_or(&"")
.split('/')
.next_back()
.unwrap_or("");
let ports = compact_ports(parts.get(4).unwrap_or(&""));
if ports == "-" {
rtk.push_str(&format!(" {} {} ({})\n", id, name, short_image));
} else {
rtk.push_str(&format!(
" {} {} ({}) [{}]\n",
id, name, short_image, ports
));
if !stopped.is_empty() {
rtk.push_str(&format!("[docker] {} stopped/exited:\n", stopped.len()));
for parts in stopped.iter().take(20) {
if let Some(l) = format_line(parts, false) {
rtk.push_str(&l);
}
}
}
if count > 15 {
rtk.push_str(&format!(" ... +{} more", count - 15));
if stopped.len() > 20 {
rtk.push_str(&format!(" ... +{} more\n", stopped.len() - 20));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
rtk.push_str(&format!(" ... +{} more\n", stopped.len() - 20));
rtk.push_str(&format!(" … +{} more\n", stopped.len() - 20));

}
}

print!("{}", rtk);
Expand Down Expand Up @@ -173,21 +200,22 @@ fn docker_images(_verbose: u8) -> Result<i32> {
total_display
));

for line in lines.iter().take(15) {
// Show images with their full `repository:tag` name — truncating the
// registry/user prefix to "..." breaks exact-match lookups against
// deployment manifests and CI configs. The list is generously capped (a
// higher bound than before, and only the count, never the names, is
// abbreviated) so token savings still hold on machines with many images.
const MAX_IMAGES: usize = 60;
for line in lines.iter().take(MAX_IMAGES) {
let parts: Vec<&str> = line.split('\t').collect();
if !parts.is_empty() {
let image = parts[0];
let size = parts.get(1).unwrap_or(&"");
let short = if image.len() > 40 {
format!("...{}", &image[image.len() - 37..])
} else {
image.to_string()
};
rtk.push_str(&format!(" {} [{}]\n", short, size));
rtk.push_str(&format!(" {} [{}]\n", image, size));
}
}
if lines.len() > 15 {
rtk.push_str(&format!(" ... +{} more", lines.len() - 15));
if lines.len() > MAX_IMAGES {
rtk.push_str(&format!(" ... +{} more\n", lines.len() - MAX_IMAGES));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
rtk.push_str(&format!(" ... +{} more\n", lines.len() - MAX_IMAGES));
rtk.push_str(&format!(" … +{} more\n", lines.len() - MAX_IMAGES));

}

print!("{}", rtk);
Expand Down Expand Up @@ -526,8 +554,9 @@ pub fn run_docker_passthrough(args: &[OsString], verbose: u8) -> Result<i32> {
pub fn run_compose_ps(verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();

// Raw output for token tracking
let raw_result = exec_capture(resolved_command("docker").args(["compose", "ps"]))
// Use `-a` so stopped/exited services stay visible — a worker that crashed
// on startup must not silently vanish from the agent's view.
let raw_result = exec_capture(resolved_command("docker").args(["compose", "ps", "-a"]))
.context("Failed to run docker compose ps")?;

if !raw_result.success() {
Expand All @@ -540,6 +569,7 @@ pub fn run_compose_ps(verbose: u8) -> Result<i32> {
let result = exec_capture(resolved_command("docker").args([
"compose",
"ps",
"-a",
"--format",
"{{.Name}}\t{{.Image}}\t{{.Status}}\t{{.Ports}}",
]))
Expand Down
55 changes: 49 additions & 6 deletions src/cmds/git/git.rs
Original file line number Diff line number Diff line change
Expand Up @@ -807,6 +807,20 @@ fn extract_state_header(raw: &str) -> Option<String> {
None
}

/// Extract the explicit "HEAD detached at/from <ref>" line from plain
/// `git status` output.
///
/// Porcelain `-b` collapses a detached HEAD to the opaque `## HEAD (no branch)`,
/// which an agent (or a distracted human) can misread as a branch literally
/// named `HEAD`. The plain-status output keeps the explicit SHA/ref, so we
/// surface that instead. Returns `None` when HEAD is on a branch.
fn extract_detached_head(raw: &str) -> Option<String> {
raw.lines()
.map(str::trim)
.find(|l| l.starts_with("HEAD detached "))
.map(str::to_string)
}

/// Minimal filtering for git status with user-provided args
fn filter_status_with_args(output: &str) -> String {
let mut result = Vec::new();
Expand Down Expand Up @@ -911,7 +925,13 @@ fn run_status(args: &[String], verbose: u8, global_args: &[String]) -> Result<i3
return Ok(result.exit_code);
}

let formatted = format_status_output(&result.stdout);
let mut formatted = format_status_output(&result.stdout);

// Porcelain `-b` reduces a detached HEAD to "## HEAD (no branch)"; restore
// the explicit "HEAD detached at <sha>" from the plain status we captured.
if let Some(detached) = extract_detached_head(&raw_output) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't it be better to check that before calling format_status_output and pass it detached instead of replacing the result afterward?

formatted = formatted.replacen("* HEAD (no branch)", &format!("* {detached}"), 1);
}

// Surface in-progress state (rebase/merge/cherry-pick/bisect/am) from the
// plain-status output we already captured for tracking. Porcelain omits it
Expand Down Expand Up @@ -968,8 +988,11 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32>
stat_cmd.args(["diff", "--cached", "--stat", "--shortstat"]);
let stat_result = exec_capture(&mut stat_cmd).context("Failed to check staged files")?;

// Mirror git's own behaviour: a no-op `git add` is silent. Emitting a
// generic "ok" here is misleading — an agent can't tell "staged N files"
// from "staged nothing" when both print "ok".
let compact = if stat_result.stdout.trim().is_empty() {
"ok (nothing to add)".to_string()
String::new()
} else {
// Parse "1 file changed, 5 insertions(+)" format
let short = stat_result.stdout.lines().last().unwrap_or("").trim();
Expand All @@ -980,7 +1003,9 @@ fn run_add(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32>
}
};

println!("{}", compact);
if !compact.is_empty() {
println!("{}", compact);
}

timer.track(
&format!("git add {}", args.join(" ")),
Expand Down Expand Up @@ -1478,9 +1503,12 @@ fn run_fetch(args: &[String], verbose: u8, global_args: &[String]) -> Result<i32
fn format_stash_message(subcommand: Option<&str>, result: &CaptureResult) -> String {
match subcommand {
None | Some("push") | Some("save") => {
// Create operations check for "no local changes"
if result.stdout.contains("No local changes") {
"ok (nothing to stash)".to_string()
// A successful stash collapses to "ok stashed" (the WIP ref/sha git
// prints isn't needed to `git stash pop`). But a no-op must NOT look
// like success — pass git's "No local changes to save" through so the
// agent can tell nothing was stashed.
if result.combined().contains("No local changes") {
"No local changes to save".to_string()
} else {
"ok stashed".to_string()
}
Expand Down Expand Up @@ -2737,6 +2765,21 @@ no changes added to commit (use "git add" and/or "git commit -a")
);
}

#[test]
fn test_extract_detached_head_returns_line() {
let raw = "HEAD detached at abc1234\nnothing to commit, working tree clean\n";
assert_eq!(
extract_detached_head(raw),
Some("HEAD detached at abc1234".to_string())
);
}

#[test]
fn test_extract_detached_head_on_branch_is_none() {
let raw = "On branch main\nnothing to commit, working tree clean\n";
assert!(extract_detached_head(raw).is_none());
}

#[test]
fn test_filter_log_output_body_omission_indicator() {
// Commit with 6 meaningful body lines: only 3 shown, must signal "+3 lines omitted"
Expand Down
5 changes: 1 addition & 4 deletions src/cmds/js/lint_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -281,23 +281,20 @@ fn filter_eslint_json(output: &str) -> String {
result.push('\n');
}

// Show top files with most issues
// Show top files with most issues, plus the top rules in each
result.push_str("Top files:\n");
for (file_result, count) in by_file.iter().take(10) {
let short_path = compact_path(&file_result.file_path);
result.push_str(&format!(" {} ({} issues)\n", short_path, count));

// Show top 3 rules in this file
let mut file_rules: HashMap<String, usize> = HashMap::new();
for msg in &file_result.messages {
if let Some(rule) = &msg.rule_id {
*file_rules.entry(rule.clone()).or_insert(0) += 1;
}
}

let mut file_rule_counts: Vec<_> = file_rules.iter().collect();
file_rule_counts.sort_by(|a, b| b.1.cmp(a.1));

for (rule, count) in file_rule_counts.iter().take(3) {
result.push_str(&format!(" {} ({})\n", rule, count));
}
Expand Down
21 changes: 15 additions & 6 deletions src/cmds/python/pip_cmd.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,16 @@ struct Package {
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let timer = tracking::TimedExecution::start();

// Auto-detect uv vs pip
let use_uv = tool_exists("uv");
// The user ran `pip` — run `pip` so RTK stays transparent and reports the
// *same* environment the bare command would. Only fall back to `uv pip` when
// `pip` genuinely isn't on PATH (uv-only environments). Auto-substituting
// `uv pip` unconditionally made `pip list` show uv's discovered env instead
// of the active one — often just the 2-package base interpreter.
let use_uv = !tool_exists("pip") && tool_exists("uv");
let base_cmd = if use_uv { "uv" } else { "pip" };

if verbose > 0 && use_uv {
eprintln!("Using uv (pip-compatible)");
eprintln!("pip not found — falling back to `uv pip`");
}

// Detect subcommand
Expand Down Expand Up @@ -162,16 +166,21 @@ fn filter_pip_list(output: &str) -> String {
let mut letters: Vec<_> = by_letter.keys().collect();
letters.sort();

// `pip list` is an inventory query — dependency audits need every package
// visible. The compression here is structural (drop the alignment padding,
// group by initial); the per-group cap is just a safety bound for
// pathological environments, not a normal-case truncation.
const MAX_PER_LETTER: usize = 50;
for letter in letters {
let pkgs = by_letter.get(letter).unwrap();
result.push_str(&format!("\n[{}]\n", letter.to_uppercase()));

for pkg in pkgs.iter().take(10) {
for pkg in pkgs.iter().take(MAX_PER_LETTER) {
result.push_str(&format!(" {} ({})\n", pkg.name, pkg.version));
}

if pkgs.len() > 10 {
result.push_str(&format!(" ... +{} more\n", pkgs.len() - 10));
if pkgs.len() > MAX_PER_LETTER {
result.push_str(&format!(" ... +{} more\n", pkgs.len() - MAX_PER_LETTER));

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

while you're at it:

Suggested change
result.push_str(&format!(" ... +{} more\n", pkgs.len() - MAX_PER_LETTER));
result.push_str(&format!(" … +{} more\n", pkgs.len() - MAX_PER_LETTER));

}
}

Expand Down
Loading
Loading