Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,21 @@ are scoped or reviewed.

### Fixed

- Advisory command strings rendered into first-pr start-here packets, agent
workflow manifests, and preflight recovery messages now escape the full bash
metacharacter set inside double quotes. The `shell_arg` helper previously
escaped only `\` and `"`, leaving `$`, backtick, and `!` live inside the
quoted form; in addition, thirteen `format!` sites in `first_pr.rs` bypassed
the helper entirely and interpolated paths, refs, and gap-ids raw. The
highest-impact case was a `>`-containing gap-id rendered unquoted into an
agent-packet command, where bash would parse the `>` as a redirect and
truncate a sibling file. The helper now backslash-escapes `$`, backtick, and
`!` in the quote path, and every advisory command builder routes its
interpolated values through it. The `python-preview-gap` start-here fixture
is re-blessed so its gap-id renders double-quoted, reflecting the corrected
(redirect-safe) shape. These commands remain advisory text for humans and
agents; ripr does not execute them (#2347).

Comment on lines +26 to +40

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Changelog describes double-quote escaping; actual fix is total single-quoting.

This entry says shell_arg "backslash-escapes $, backtick, and ! in the quote path" and that the gap-id "renders double-quoted." The shipped implementation does neither: shell_arg renders non-safe values as single-quoted Bash tokens ('...' with '\'' for embedded quotes), and the re-blessed python-preview-gap fixture shows the gap-id single-quoted, not double-quoted. This text appears to be stale wording carried over from the prior double-quote-based draft rather than the single-quote approach actually implemented here.

📝 Proposed changelog correction
-- Advisory command strings rendered into first-pr start-here packets, agent
-  workflow manifests, and preflight recovery messages now escape the full bash
-  metacharacter set inside double quotes. The `shell_arg` helper previously
-  escaped only `\` and `"`, leaving `$`, backtick, and `!` live inside the
-  quoted form; in addition, thirteen `format!` sites in `first_pr.rs` bypassed
-  the helper entirely and interpolated paths, refs, and gap-ids raw. The
-  highest-impact case was a `>`-containing gap-id rendered unquoted into an
-  agent-packet command, where bash would parse the `>` as a redirect and
-  truncate a sibling file. The helper now backslash-escapes `$`, backtick, and
-  `!` in the quote path, and every advisory command builder routes its
-  interpolated values through it. The `python-preview-gap` start-here fixture
-  is re-blessed so its gap-id renders double-quoted, reflecting the corrected
-  (redirect-safe) shape. These commands remain advisory text for humans and
-  agents; ripr does not execute them (`#2347`).
+- Advisory command strings rendered into first-pr start-here packets, agent
+  workflow manifests, and preflight recovery messages now use total Bash
+  single-quoting for any non-trivially-safe value. `shell_arg` previously used
+  a different escaping strategy that left some metacharacters live inside the
+  quoted form; in addition, thirteen `format!` sites in `first_pr.rs` bypassed
+  the helper entirely and interpolated paths, refs, and gap-ids raw. The
+  highest-impact case was a `>`-containing gap-id rendered unquoted into an
+  agent-packet command, where bash would parse the `>` as a redirect and
+  truncate a sibling file. The helper now wraps every non-safe value in single
+  quotes (with the standard `'\''` splice for embedded quotes), and every
+  advisory command builder routes its interpolated values through it. The
+  `python-preview-gap` start-here fixture is re-blessed so its gap-id renders
+  single-quoted, reflecting the corrected (redirect-safe) shape. These
+  commands remain advisory text for humans and agents; ripr does not execute
+  them (`#2347`).
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
- Advisory command strings rendered into first-pr start-here packets, agent
workflow manifests, and preflight recovery messages now escape the full bash
metacharacter set inside double quotes. The `shell_arg` helper previously
escaped only `\` and `"`, leaving `$`, backtick, and `!` live inside the
quoted form; in addition, thirteen `format!` sites in `first_pr.rs` bypassed
the helper entirely and interpolated paths, refs, and gap-ids raw. The
highest-impact case was a `>`-containing gap-id rendered unquoted into an
agent-packet command, where bash would parse the `>` as a redirect and
truncate a sibling file. The helper now backslash-escapes `$`, backtick, and
`!` in the quote path, and every advisory command builder routes its
interpolated values through it. The `python-preview-gap` start-here fixture
is re-blessed so its gap-id renders double-quoted, reflecting the corrected
(redirect-safe) shape. These commands remain advisory text for humans and
agents; ripr does not execute them (#2347).
- Advisory command strings rendered into first-pr start-here packets, agent
workflow manifests, and preflight recovery messages now use total Bash
single-quoting for any non-trivially-safe value. `shell_arg` previously used
a different escaping strategy that left some metacharacters live inside the
quoted form; in addition, thirteen `format!` sites in `first_pr.rs` bypassed
the helper entirely and interpolated paths, refs, and gap-ids raw. The
highest-impact case was a `>`-containing gap-id rendered unquoted into an
agent-packet command, where bash would parse the `>` as a redirect and
truncate a sibling file. The helper now wraps every non-safe value in single
quotes (with the standard `'\''` splice for embedded quotes), and every
advisory command builder routes its interpolated values through it. The
`python-preview-gap` start-here fixture is re-blessed so its gap-id renders
single-quoted, reflecting the corrected (redirect-safe) shape. These
commands remain advisory text for humans and agents; ripr does not execute
them (`#2347`).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@CHANGELOG.md` around lines 26 - 40, Correct the CHANGELOG entry to describe
the shipped single-quote behavior: state that shell_arg renders non-safe values
as single-quoted Bash tokens and escapes embedded single quotes using the
implemented form, and update the python-preview-gap fixture description to say
the gap-id is single-quoted. Remove references to backslash-escaping `$`,
backticks, and `!` in double quotes.

- Rust equality-boundary analysis now credits exact, source-ordered direct
field assignments from same-file literal constants and bounded `+/-` integer
offsets. Other owners, fields, similarly named constants, helper-only writes,
Expand Down
161 changes: 150 additions & 11 deletions crates/ripr/src/agent/loop_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,14 +196,23 @@ pub(crate) fn shell_path(path: &Path) -> String {
shell_arg(&display_path(path))
}

/// Render `value` as one complete Bash argv token for advisory command text.
///
/// Non-empty `[A-Za-z0-9./_:-]` values remain readable without quotes. Every
/// other value uses Bash's single-quote form, with embedded single quotes
/// represented by the standard `'\''` splice. Single quotes are the only Bash
/// quoting form with no interpretation inside, so `$`, backticks, `!`,
/// backslashes, newlines, redirect characters, and empty values all round-trip
/// without expansion or token loss.
pub(crate) fn shell_arg(value: &str) -> String {
if value
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '/' | '\\' | '_' | '-' | ':'))
if !value.is_empty()
&& value
.chars()
.all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '.' | '/' | '_' | '-' | ':'))
{
return value.to_string();
}
format!("\"{}\"", value.replace('\\', "\\\\").replace('"', "\\\""))
format!("'{}'", value.replace('\'', "'\\''"))
}

fn append_redirect(command: String, out_path: Option<&str>) -> String {
Expand Down Expand Up @@ -301,23 +310,23 @@ mod tests {

#[test]
fn command_args_quote_spaces_without_touching_plain_tokens() {
assert_eq!(shell_arg("repo root"), "\"repo root\"");
assert_eq!(shell_arg("repo root"), "'repo root'");
assert_eq!(shell_arg("target/ripr/workflow"), "target/ripr/workflow");
assert_eq!(
workflow_artifact_path(Path::new("target/ripr/workflow"), "workflow.json"),
"target/ripr/workflow/workflow.json"
);
assert_eq!(
agent_seam_packets_command(".", "draft mode", "target/ripr/workflow/packets.json"),
"ripr check --root . --mode \"draft mode\" --format agent-seam-packets-json > target/ripr/workflow/packets.json"
"ripr check --root . --mode 'draft mode' --format agent-seam-packets-json > target/ripr/workflow/packets.json"
);
assert_eq!(
agent_start_command("repo root", "seam a", "target/ripr/work flow"),
"ripr agent start --root \"repo root\" --seam-id \"seam a\" --out \"target/ripr/work flow\""
"ripr agent start --root 'repo root' --seam-id 'seam a' --out 'target/ripr/work flow'"
);
assert_eq!(
check_repo_exposure_command("repo root", "draft", "target/ripr/work flow/before.json"),
"ripr check --root \"repo root\" --mode draft --format repo-exposure-json > \"target/ripr/work flow/before.json\""
"ripr check --root 'repo root' --mode draft --format repo-exposure-json > 'target/ripr/work flow/before.json'"
);
assert_eq!(
check_repo_exposure_command_with_base(
Expand All @@ -326,7 +335,7 @@ mod tests {
"draft",
"target/ripr/work flow/before.json",
),
"ripr check --root \"repo root\" --base \"origin/main with space\" --mode draft --format repo-exposure-json > \"target/ripr/work flow/before.json\""
"ripr check --root 'repo root' --base 'origin/main with space' --mode draft --format repo-exposure-json > 'target/ripr/work flow/before.json'"
);
assert_eq!(
agent_verify_command(
Expand All @@ -335,7 +344,7 @@ mod tests {
"target/ripr/work flow/after.json",
Some("target/ripr/work flow/verify.json"),
),
"ripr agent verify --root \"repo root\" --before \"target/ripr/work flow/before.json\" --after \"target/ripr/work flow/after.json\" --json > \"target/ripr/work flow/verify.json\""
"ripr agent verify --root 'repo root' --before 'target/ripr/work flow/before.json' --after 'target/ripr/work flow/after.json' --json > 'target/ripr/work flow/verify.json'"
);
assert_eq!(
agent_receipt_command(
Expand All @@ -344,7 +353,137 @@ mod tests {
"seam a",
Some("target/ripr/work flow/receipt.json"),
),
"ripr agent receipt --root \"repo root\" --verify-json \"target/ripr/work flow/verify.json\" --seam-id \"seam a\" --json --out \"target/ripr/work flow/receipt.json\""
"ripr agent receipt --root 'repo root' --verify-json 'target/ripr/work flow/verify.json' --seam-id 'seam a' --json --out 'target/ripr/work flow/receipt.json'"
);
}

#[test]
fn shell_arg_is_total_for_empty_backslash_quotes_and_metacharacters() {
assert_eq!(shell_arg(""), "''");
assert_eq!(shell_arg("plain/path:one-two"), "plain/path:one-two");
assert_eq!(shell_arg("a\\b"), "'a\\b'");
assert_eq!(shell_arg("a'b"), "'a'\\''b'");
assert_eq!(shell_arg("$HOME"), "'$HOME'");
assert_eq!(shell_arg("`id`"), "'`id`'");
assert_eq!(shell_arg("with!bang"), "'with!bang'");
assert_eq!(
shell_arg("gap:pr:amount>=threshold"),
"'gap:pr:amount>=threshold'"
);
}

#[cfg(unix)]
fn run_bash(
script: &str,
cwd: Option<&std::path::Path>,
) -> Result<std::process::Output, String> {
let mut command = std::process::Command::new("bash");
command
.args(["--noprofile", "--norc", "-c", script])
.env_remove("BASH_ENV")
.env_remove("ENV");
if let Some(cwd) = cwd {
command.current_dir(cwd);
}
command
.output()
.map_err(|err| format!("run Bash argv proof failed: {err}"))
}

#[cfg(unix)]
#[test]
fn shell_arg_round_trips_hostile_values_through_real_bash() -> Result<(), String> {
for value in [
"",
"plain",
"repo root",
"a\\b",
"a'b",
"a\"b",
"$HOME",
"$(printf injected)",
"`printf injected`",
"with!bang",
"gap:pr:amount>=threshold",
"line\nbreak",
] {
let script = format!("set -- {}; printf '%s' \"$1\"", shell_arg(value));
let output = run_bash(&script, None)?;
if !output.status.success() {
return Err(format!(
"Bash rejected shell_arg({value:?}): {}",
String::from_utf8_lossy(&output.stderr)
));
}
if output.stdout != value.as_bytes() {
return Err(format!(
"shell_arg did not round-trip: input={value:?} output={:?} token={}",
String::from_utf8_lossy(&output.stdout),
shell_arg(value)
));
}
}
Ok(())
}

#[cfg(unix)]
#[test]
fn redirect_shaped_gap_id_cannot_open_a_second_redirect() -> Result<(), String> {
let stamp = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_err(|err| format!("system clock before UNIX_EPOCH: {err}"))?
.as_nanos();
let root = std::env::temp_dir().join(format!(
"ripr-shell-arg-redirect-{}-{stamp}",
std::process::id()
));
std::fs::create_dir_all(&root)
.map_err(|err| format!("create redirect proof root failed: {err}"))?;

let proof = (|| {
let value = "gap:pr:amount>=threshold";
let script = format!("printf '%s' {} > result.txt", shell_arg(value));
let output = run_bash(&script, Some(&root))?;
if !output.status.success() {
return Err(format!(
"Bash rejected redirect proof: {}",
String::from_utf8_lossy(&output.stderr)
));
}
let actual = std::fs::read(root.join("result.txt"))
.map_err(|err| format!("read redirect proof result failed: {err}"))?;
if actual != value.as_bytes() {
return Err(format!(
"redirect proof changed the gap id: {:?}",
String::from_utf8_lossy(&actual)
));
}
let mut entries = std::fs::read_dir(&root)
.map_err(|err| format!("read redirect proof root failed: {err}"))?
.map(|entry| {
entry
.map(|entry| entry.file_name().to_string_lossy().into_owned())
.map_err(|err| format!("read redirect proof entry failed: {err}"))
})
.collect::<Result<Vec<_>, _>>()?;
entries.sort();
if entries != ["result.txt"] {
return Err(format!(
"redirect-shaped gap id created unexpected files: {entries:?}"
));
}
Ok(())
})();

let cleanup = std::fs::remove_dir_all(&root)
.map_err(|err| format!("remove redirect proof root failed: {err}"));
match (proof, cleanup) {
(Ok(()), Ok(())) => Ok(()),
(Err(error), Ok(())) => Err(error),
(Ok(()), Err(cleanup_error)) => Err(cleanup_error),
(Err(error), Err(cleanup_error)) => {
Err(format!("{error}; cleanup also failed: {cleanup_error}"))
}
}
}
}
4 changes: 2 additions & 2 deletions crates/ripr/src/app/agent_status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -660,7 +660,7 @@ mod tests {
assert!(report.missing_commands.iter().any(|command| {
command.step == "agent_packet"
&& command.command
== "ripr agent packet --root \"repo root\" --seam-id 67fc764ba37d77bd --json > target/ripr/workflow/agent-packet.json"
== "ripr agent packet --root 'repo root' --seam-id 67fc764ba37d77bd --json > target/ripr/workflow/agent-packet.json"
}));

std::fs::remove_dir_all(&root).map_err(|err| format!("remove root: {err}"))?;
Expand Down Expand Up @@ -795,7 +795,7 @@ mod tests {
fn agent_status_quotes_paths_with_spaces() {
assert_eq!(
agent_packet_command("repo root", "seam-a", WORKFLOW_AGENT_PACKET_ARTIFACT),
"ripr agent packet --root \"repo root\" --seam-id seam-a --json > target/ripr/workflow/agent-packet.json"
"ripr agent packet --root 'repo root' --seam-id seam-a --json > target/ripr/workflow/agent-packet.json"
);
}
}
2 changes: 1 addition & 1 deletion crates/ripr/src/lsp/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5744,7 +5744,7 @@ fn agent_loop_command_payloads_stay_workspace_relative_for_platform_roots() -> R
COPY_AFTER_SNAPSHOT_COMMAND,
"after_snapshot",
"target/ripr/pilot/after.repo-exposure.json",
"ripr check --root . --base \"origin/main with space\" --mode ready --format repo-exposure-json > target/ripr/pilot/after.repo-exposure.json"
"ripr check --root . --base 'origin/main with space' --mode ready --format repo-exposure-json > target/ripr/pilot/after.repo-exposure.json"
.to_string(),
),
(
Expand Down
Loading
Loading