Skip to content
Merged
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
25 changes: 18 additions & 7 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,15 @@ Clean up in this order, every time:
`ps -p $(tmux display-message -p -t <window id> '#{pane_pid}') -wwE -o command=`, with the
investigation's `@` id from `tmux list-windows -t qa -F '#{window_id} #{window_name}'`.
- **`#{pane_start_command}` is the exact command tmux was handed**, which is what
to assert against when the change affects how an investigation is launched.
to assert against when the change affects how an investigation is launched. tmux prints it
quoted and escaped, starting `"\"\$HUB_LAUNCHER\" --permission-mode auto --strict-mcp-config`.
The launcher it names is in the pane process's environment, which the `ps … -wwE` command above
reads; `tmux show-environment` does not show it.
- **A configured launcher can make a launch wait.** On a device whose `hub.toml` sets
`[investigation] launcher`, the launcher runs before `claude` starts, and `cc.bash` can stop at
a browser login there. The launch worked: leave the login for the user and report it. Until
`claude` starts, no process for this window matches the `pgrep` commands in Rex pitfalls, and
`pgrep -n` answers with an older investigation's `claude`.
- **An investigation can open at Claude Code's "trust this folder" prompt
instead of a session.** Each investigation runs in a new worktree, and Claude
Code checks the trust recorded for the worktree's repository, here the bare
Expand All @@ -390,19 +398,22 @@ Clean up in this order, every time:
Clear the line with `rex send-key -s "$S" -b "$B" ctrl+c`; Rex refuses `ctrl-c`.
- **There is no `#{pane_start_command}`.** Read an investigation's launch
command off its process. `pgrep -n` takes the newest, so an investigation
left open from earlier answers if this one did not start. When a cleanup
step follows `claude`, `/bin/sh` stays as its parent and holds hub's command:
left open from earlier answers if this one did not start, or has not started yet
because a configured launcher is still running. These notes assume the launcher
is `claude` or `exec`s it, as `cc.bash` does; a launcher that runs `claude` as a
child is its parent instead. When a cleanup step follows the launcher, `/bin/sh`
stays as `claude`'s parent and holds hub's command:

```bash
ps -p $(ps -o ppid= -p $(pgrep -n -f "claude --permission-mode auto")) -ww -o command=
ps -p $(ps -o ppid= -p $(pgrep -n -f "claude .*--strict-mcp-config")) -ww -o command=
```

When `claude` is the whole command, as in every PR investigation, `/bin/sh`
hands itself to `claude`, so the parent is Rex's own process. Read `claude`
When the launcher is the whole command, as in every PR investigation, `/bin/sh`
hands itself to it, so `claude`'s parent is Rex's own process. Read `claude`
itself, whose environment carries the prompts:

```bash
ps -p $(pgrep -n -f "claude --permission-mode auto") -wwE -o command=
ps -p $(pgrep -n -f "claude .*--strict-mcp-config") -wwE -o command=
```

**tmux send-keys pitfalls**
Expand Down
5 changes: 5 additions & 0 deletions config/schemas/hub.toml.schema.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,11 @@
"description": "What every investigation launched on this device receives.",
"additionalProperties": false,
"properties": {
"launcher": {
"type": "string",
"pattern": "^/",
"description": "The absolute path of an executable every investigation runs in place of claude, with the arguments hub would pass claude, which it passes on. The TUI refuses to start when it can't run. Absent means claude from PATH. See docs/decisions/034-investigations-start-through-the-launcher-hub-toml-names.md."
},
"mcp_servers": {
"type": "object",
"description": "MCP servers investigations may use, keyed by the name Claude Code lists each under. Investigations ignore every other MCP config, including the investigated repository's .mcp.json. Absent means none.",
Expand Down
73 changes: 69 additions & 4 deletions config/src/config_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,43 @@ pub struct ConfigFile {
projects: crate::Projects,
monitor: Option<toml::Monitor>,
investigation_mcp_servers: domain::InvestigationMcpServers,
investigation_launcher: domain::InvestigationLauncher,
}

impl ConfigFile {
/// Reads `hub.toml` from the working directory.
///
/// # Errors
/// Returns an error if `hub.toml` is missing or malformed, lacks a required credential, or
/// gives a project a label hub refuses.
/// Returns an error if `hub.toml` is missing or malformed, lacks a required credential, names
/// an investigation launcher that is not an absolute path, or gives a project a label hub
/// refuses.
pub fn read() -> Result<Self> {
let hub_toml = toml::parse_file("hub.toml")?;
Self::read_from("hub.toml")
}

/// Reads the `hub.toml` at `path`, as [`ConfigFile::read`] does.
pub(crate) fn read_from(path: &str) -> Result<Self> {
let hub_toml = toml::parse_file(path)?;
validate_required(&hub_toml.credentials)?;
let investigation_mcp_servers = hub_toml.investigation.mcp_servers()?;
let investigation_launcher = hub_toml.investigation.launcher()?;
let projects = crate::Projects::resolve(hub_toml.project)
.context("hub.toml has a [[project]] hub cannot use")?;
Ok(Self {
credentials: hub_toml.credentials,
projects,
monitor: hub_toml.monitor,
investigation_mcp_servers,
investigation_launcher,
})
}

/// What investigations run in place of `claude`, from `[investigation] launcher`.
#[must_use]
pub(crate) const fn investigation_launcher(&self) -> &domain::InvestigationLauncher {
&self.investigation_launcher
}

/// Resolves every credential, asking 1Password for each `op://` reference through an `op`
/// started as `responsibility` allows, and says which ways of starting `op` answered.
///
Expand Down Expand Up @@ -75,6 +90,7 @@ impl ConfigFile {
projects: self.projects.clone(),
monitor: self.monitor.clone(),
investigation_mcp_servers: self.investigation_mcp_servers.clone(),
investigation_launcher: self.investigation_launcher.clone(),
};
Ok(Resolved {
config,
Expand All @@ -94,7 +110,7 @@ fn validate_required(creds: &toml::CredentialsToml) -> Result<()> {
}

#[cfg(test)]
mod tests {
pub(crate) mod tests {
use rstest::rstest;
use secrecy::ExposeSecret;

Expand All @@ -121,6 +137,7 @@ mod tests {
projects: crate::Projects::default(),
monitor: None,
investigation_mcp_servers: domain::InvestigationMcpServers::default(),
investigation_launcher: domain::InvestigationLauncher::Claude,
};

// A plain value never reaches a spawn, so either responsibility will do.
Expand All @@ -140,6 +157,54 @@ mod tests {
assert_eq!(config.extra_credentials["media"].expose_secret(), "key");
}

/// A `hub.toml` holding `body` under plain credentials, in a folder of its own under the
/// system's temporary directory. Returns the folder, for the caller to remove, and the file.
pub(crate) fn hub_toml_with(name: &str, body: &str) -> (std::path::PathBuf, String) {
let dir = std::env::temp_dir().join(format!("hub-config-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("hub.toml");
std::fs::write(
&path,
format!("[credentials]\ngithub_token = \"tok\"\ngithub_username = \"user\"\n\n{body}"),
)
.unwrap();
(dir, path.to_str().unwrap().to_string())
}

#[test]
fn reading_refuses_a_launcher_that_is_not_absolute_naming_the_setting() {
let (dir, path) = hub_toml_with(
"relative-launcher",
"[investigation]\nlauncher = \"tools/cc.bash\"\n",
);

let result = ConfigFile::read_from(&path);

std::fs::remove_dir_all(&dir).unwrap();
let message = format!("{:#}", result.unwrap_err());
assert!(message.contains("[investigation] launcher"), "{message}");
assert!(message.contains("\"tools/cc.bash\""), "{message}");
}

/// The daemon reads `hub.toml` this way and launches no investigation, so a launcher that
/// is absolute but missing must not stop it.
#[test]
fn reading_accepts_an_absolute_launcher_that_does_not_exist() {
let (dir, path) = hub_toml_with(
"missing-launcher",
"[investigation]\nlauncher = \"/nonexistent/cc.bash\"\n",
);

let result = ConfigFile::read_from(&path);

std::fs::remove_dir_all(&dir).unwrap();
assert_eq!(
result.unwrap().investigation_launcher().program(),
"/nonexistent/cc.bash"
);
}

#[test]
fn validate_required_passes_with_both_fields_set() {
assert!(validate_required(&credentials("tok", "user")).is_ok());
Expand Down
140 changes: 139 additions & 1 deletion config/src/investigation.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use anyhow::{anyhow, Context, Result};
use domain::{InvestigationMcpServers, McpServer, McpServerName};
use domain::{InvestigationLauncher, InvestigationMcpServers, McpServer, McpServerName};
use serde::Deserialize;
use std::collections::BTreeMap;

Expand All @@ -12,6 +12,9 @@ pub struct InvestigationToml {
/// Code lists the server under. Absent means no MCP servers.
#[serde(default)]
pub mcp_servers: BTreeMap<String, McpServerToml>,
/// The absolute path of an executable every investigation runs in place
/// of `claude`. Absent means `claude`.
pub launcher: Option<String>,
}

/// One `[investigation.mcp_servers.<name>]` table.
Expand Down Expand Up @@ -45,6 +48,48 @@ impl InvestigationToml {
}
Ok(InvestigationMcpServers::new(servers))
}

/// # Errors
/// Returns an error naming the setting if `launcher` is not an absolute path.
pub fn launcher(&self) -> Result<InvestigationLauncher> {
match &self.launcher {
None => Ok(InvestigationLauncher::Claude),
Some(path) => InvestigationLauncher::executable(path)
.map_err(|e| anyhow!("{e}"))
.context("invalid [investigation] launcher in hub.toml"),
}
}
}

/// Checks the launcher is a file with an execute bit.
///
/// The TUI checks at start and at each launch, so it refuses rather than open
/// windows that fail. `claude` is looked up on each window's `PATH` when it
/// opens, so it has nothing to check here.
///
/// # Errors
/// Returns an error naming the setting and the path if the path is missing,
/// is not a file, or has no execute bit.
pub fn ensure_launcher_runs(launcher: &InvestigationLauncher) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;

let Some(path) = launcher.path() else {
return Ok(());
};
let context = || {
format!(
"[investigation] launcher \"{}\" in hub.toml can't run",
path.display()
)
};
let metadata = std::fs::metadata(path).with_context(context)?;
if !metadata.is_file() {
return Err(anyhow!("it is not a file")).with_context(context);
}
if metadata.permissions().mode() & 0o111 == 0 {
return Err(anyhow!("it has no execute bit")).with_context(context);
Comment on lines +89 to +90
}
Ok(())
}

#[cfg(test)]
Expand Down Expand Up @@ -110,6 +155,99 @@ mod tests {
assert!(message.contains("\"not a url\""), "{message}");
}

#[test]
fn no_launcher_means_claude() {
assert_eq!(
parse("").unwrap().launcher().unwrap(),
InvestigationLauncher::Claude
);
}

#[test]
fn an_absolute_launcher_path_is_the_launcher() {
let launcher = parse("launcher = \"/opt/tools/cc.bash\"")
.unwrap()
.launcher()
.unwrap();
assert_eq!(launcher.program(), "/opt/tools/cc.bash");
}

#[rstest]
#[case::empty("")]
#[case::relative("tools/cc.bash")]
fn a_launcher_that_is_not_absolute_is_rejected_naming_the_setting(#[case] value: &str) {
let err = parse(&format!("launcher = {value:?}"))
.unwrap()
.launcher()
.unwrap_err();
let message = format!("{err:#}");
assert!(message.contains("[investigation] launcher"), "{message}");
assert!(message.contains(&format!("{value:?}")), "{message}");
}

/// A folder of its own under the system's temporary directory, removed
/// when dropped.
struct Scratch(std::path::PathBuf);

impl Scratch {
fn new(name: &str) -> Self {
let dir =
std::env::temp_dir().join(format!("hub-launcher-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
Self(dir)
}

fn file(&self, name: &str, mode: u32) -> std::path::PathBuf {
use std::os::unix::fs::PermissionsExt as _;

let path = self.0.join(name);
std::fs::write(&path, "#!/bin/sh\n").unwrap();
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode)).unwrap();
path
}
}

impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}

fn launcher_at(path: &std::path::Path) -> InvestigationLauncher {
InvestigationLauncher::executable(path.to_str().unwrap()).unwrap()
}

#[test]
fn claude_and_an_executable_file_can_run() {
let scratch = Scratch::new("runs");
assert!(ensure_launcher_runs(&InvestigationLauncher::Claude).is_ok());
assert!(ensure_launcher_runs(&launcher_at(&scratch.file("cc.bash", 0o755))).is_ok());
}

#[rstest]
#[case::missing("missing")]
#[case::a_folder("folder")]
#[case::not_executable("not-executable")]
fn a_launcher_that_cant_run_is_refused_naming_the_setting_and_path(#[case] kind: &str) {
let scratch = Scratch::new(kind);
let path = match kind {
"missing" => scratch.0.join("cc.bash"),
"folder" => scratch.0.clone(),
"not-executable" => scratch.file("cc.bash", 0o644),
other => unreachable!("no such case: {other}"),
};

let err = ensure_launcher_runs(&launcher_at(&path)).unwrap_err();

let message = format!("{err:#}");
assert!(message.contains("[investigation] launcher"), "{message}");
assert!(
message.contains(&format!("\"{}\"", path.display())),
"{message}"
);
}

#[test]
fn an_invalid_name_is_rejected_naming_the_server() {
let err = parse("[mcp_servers.\"has space\"]\ntype = \"http\"\nurl = \"https://e.com\"")
Expand Down
Loading
Loading