Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(macrod): dispatch repositories into Herdr-managed worktrees (#7363)

Eric Hayes47301f9a5a97
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index 28793286d8..f220d410f5 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -125,6 +125,22 @@ pub struct RequestedExternalSession {
/// reaches the runtime the way the persona's own does: recorded on the
/// session, then selected when the session binds on its first prompt.
pub model: Option<String>,
+ /// Remote repository selected for this external coding session.
+ pub repo_url: Option<String>,
+}
+
+/// Validate the base branch supported by external repository provisioning.
+/// External runtimes currently create every new worktree from origin/main.
+pub fn external_repository(
+ repo_url: Option<String>,
+ branch: Option<&str>,
+) -> super::error::Result<Option<String>> {
+ if branch.is_some_and(|branch| !matches!(branch, "main" | "origin/main")) {
+ return Err(super::error::AgentSessionError::InvalidRepositorySelection(
+ "external coding sessions start from origin/main",
+ ));
+ }
+ Ok(repo_url.filter(|url| !url.trim().is_empty()))
}
/// Hands a composer request to the bot's own runtime and waits for the
diff --git a/crates/agent_session/src/domain/routines/service.rs b/crates/agent_session/src/domain/routines/service.rs
index e7d3e2007f..578247b612 100644
--- a/crates/agent_session/src/domain/routines/service.rs
+++ b/crates/agent_session/src/domain/routines/service.rs
@@ -150,6 +150,7 @@ where
session_id: command.session_id,
bot_id,
owner: selection.owner,
+ repo_url: None,
model: selection.model.clone(),
})
.await
diff --git a/crates/agent_session/src/domain/routines/service/test.rs b/crates/agent_session/src/domain/routines/service/test.rs
index 2967e4726a..c35766b981 100644
--- a/crates/agent_session/src/domain/routines/service/test.rs
+++ b/crates/agent_session/src/domain/routines/service/test.rs
@@ -293,6 +293,7 @@ async fn external_preparation_uses_requested_identity_and_model() {
assert_eq!(
requests.as_slice(),
&[RequestedExternalSession {
+ repo_url: None,
session_id: fx.session.id,
bot_id: fx.session.bot_id,
owner: fx.session.owner_user().unwrap().clone(),
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index b4711a9133..42181d6423 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -2046,13 +2046,10 @@ pub async fn create_agent_session_handler<
// caller delivers its first prompt through the control
// endpoint once this answers, as it does for a managed one.
SelectedPersona::External { bot_id } => {
- if request.repo_url.is_some() || request.repo_branch.is_some() {
- return Err(CreateSessionApiError::Domain(
- AgentSessionError::InvalidRepositorySelection(
- "repository selection is supported for Cursor coding agents",
- ),
- ));
- }
+ let repo_url = crate::domain::ports::external_repository(
+ request.repo_url,
+ request.repo_branch.as_deref(),
+ )?;
// Refused rather than dropped: nothing delivers it, and a
// caller that sent one would otherwise never learn it was
// ignored. A model is different - it is applied when the
@@ -2075,6 +2072,7 @@ pub async fn create_agent_session_handler<
.map(AgentSessionId::new_from_uuid)
.unwrap_or_else(AgentSessionId::new),
bot_id,
+ repo_url,
owner,
model: request.model.filter(|model| !model.trim().is_empty()),
})
diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rs
index 6c8bf617c2..34dc2700af 100644
--- a/crates/agent_session/src/inbound/axum_router/test.rs
+++ b/crates/agent_session/src/inbound/axum_router/test.rs
@@ -1107,6 +1107,8 @@ async fn an_owner_starts_their_macrod_agent_from_the_composer() {
"id": minted,
"botId": BotId::TEST_A.as_uuid(),
"model": "claude-opus-5",
+ "repoUrl": "https://github.com/org/project",
+ "repoBranch": "main",
})
.to_string(),
);
@@ -1127,6 +1129,10 @@ async fn an_owner_starts_their_macrod_agent_from_the_composer() {
let requested = requests.requested.lock().unwrap();
assert_eq!(requested.len(), 1);
assert_eq!(requested[0].bot_id, BotId::TEST_A);
+ assert_eq!(
+ requested[0].repo_url.as_deref(),
+ Some("https://github.com/org/project")
+ );
assert_eq!(requested[0].owner.as_ref(), OWNER);
assert_eq!(requested[0].session_id.as_uuid(), minted);
assert_eq!(requested[0].model.as_deref(), Some("claude-opus-5"));
@@ -1400,3 +1406,26 @@ async fn invalid_repository_branch_is_rejected_before_opening() {
assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
assert!(opener.managed.lock().unwrap().is_empty());
}
+
+#[tokio::test]
+async fn macrod_rejects_an_unsupported_base_before_dispatch() {
+ let requests = Arc::new(RecordingRequester::default());
+ let response = router_with_requests(
+ Arc::new(RecordingOpener::default()),
+ OneBotDirectory::macrod_agent(),
+ requests.clone(),
+ )
+ .oneshot(as_user(
+ OWNER,
+ serde_json::json!({
+ "botId": BotId::TEST_A.as_uuid(),
+ "repoUrl": "https://github.com/org/project",
+ "repoBranch": "feature/other"
+ })
+ .to_string(),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(response.status(), StatusCode::UNPROCESSABLE_ENTITY);
+ assert!(requests.requested.lock().unwrap().is_empty());
+}
diff --git a/crates/agent_trigger/src/domain/broker_events.rs b/crates/agent_trigger/src/domain/broker_events.rs
index 1d127c971b..10c29295f6 100644
--- a/crates/agent_trigger/src/domain/broker_events.rs
+++ b/crates/agent_trigger/src/domain/broker_events.rs
@@ -89,6 +89,9 @@ pub struct AgentSessionRequestedEvent {
pub session_id: AgentSessionId,
/// Who asked; owns the session the runtime creates.
pub owner: String,
+ /// Repository selected by the requester, absent on older producers.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub repo_url: Option<String>,
}
/// Events that open a new session.
diff --git a/crates/coding_agent_worker/README.md b/crates/coding_agent_worker/README.md
new file mode 100644
index 0000000000..e417363506
--- /dev/null
+++ b/crates/coding_agent_worker/README.md
@@ -0,0 +1,14 @@
+
+### Repositories in native Herdr sessions
+
+Macro can include `repoUrl` when opening a session on macrod. Native Herdr
+sessions look for the matching origin in the configured workspace directory
+(and its child directories), then in this daemon's repository cache. A missing
+repository is cloned using the operator's Git credentials. New worktrees start
+from a fresh fetch of `origin/main`; macrod never pulls into the operator's
+working branch. A repository without `main` produces an error.
+
+Herdr creates and registers the worktree. The session ID determines its path
+and branch, so redelivery reuses existing work without resetting edits. Cached
+repositories and worktrees live under `~/.macrod/herdr/<harness-id>/`. Each
+paired macrod instance has one configuration and its own storage directory.
diff --git a/crates/coding_agent_worker/src/daemon.rs b/crates/coding_agent_worker/src/daemon.rs
index a0f3ac87de..16ebafca2b 100644
--- a/crates/coding_agent_worker/src/daemon.rs
+++ b/crates/coding_agent_worker/src/daemon.rs
@@ -54,6 +54,33 @@ impl Daemon {
#[cfg(not(unix))]
let tap = None;
+ #[cfg(unix)]
+ let workspaces = if crate::herdr::drives_herdr(&config.harness) {
+ let root = crate::herdr::instance_directory(credentials.harness_id)?;
+ let herdr = crate::herdr::HerdrSession::detect()
+ .ok_or_else(|| rootcause::report!("start macrod inside a Herdr pane"))?;
+ let index = config
+ .harness
+ .args
+ .iter()
+ .position(|arg| arg == "--")
+ .unwrap_or(config.harness.args.len());
+ config.harness.args.splice(
+ index..index,
+ [
+ "--state-dir".to_owned(),
+ root.to_string_lossy().into_owned(),
+ ],
+ );
+ Some(crate::herdr::repositories::Workspaces::new(
+ config.workspace.path.clone(),
+ root,
+ crate::herdr::cli::HerdrCli::new(herdr.bin, herdr.workspace_id),
+ ))
+ } else {
+ None
+ };
+
let runtime = Runtime::start(
&config.macro_api,
&credentials,
@@ -63,6 +90,8 @@ impl Daemon {
);
let executor = Dispatcher::new(api, runtime, config.workspace.clone());
#[cfg(unix)]
+ let executor = executor.with_workspaces(workspaces);
+ #[cfg(unix)]
let executor = match herdr {
Some(hub) => executor.with_herdr(hub),
None => executor,
@@ -127,9 +156,11 @@ impl Daemon {
#[cfg(unix)]
fn start_herdr(config: &mut Config, credentials: &HarnessCredentials) -> Option<crate::herdr::Hub> {
let herdr = crate::herdr::HerdrSession::detect()?;
- match std::env::current_dir() {
- Ok(cwd) => config.workspace.path = cwd,
- Err(error) => tracing::warn!(error = %error, "could not read the working directory"),
+ if !crate::herdr::drives_herdr(&config.harness) {
+ match std::env::current_dir() {
+ Ok(cwd) => config.workspace.path = cwd,
+ Err(error) => tracing::warn!(error = %error, "could not read the working directory"),
+ }
}
if crate::herdr::drives_herdr(&config.harness) {
tracing::info!("herdr detected; the harness opens a herdr window per session");
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index 49684a66e5..bc2d27b94e 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -13,6 +13,9 @@ use crate::trigger::{TriggerWork, WorkExecutor};
/// A failure doing an event's work.
#[derive(Debug, thiserror::Error)]
pub enum DispatchError {
+ /// The repository or Herdr worktree could not be prepared.
+ #[error("workspace preparation failed: {0}")]
+ Workspace(String),
/// The service refused or could not be reached.
#[error(transparent)]
Api(#[from] ApiError),
@@ -27,6 +30,8 @@ pub struct Dispatcher {
runtime: Runtime,
workspace: Workspace,
#[cfg(unix)]
+ workspaces: Option<crate::herdr::repositories::Workspaces>,
+ #[cfg(unix)]
herdr: Option<crate::herdr::Hub>,
}
@@ -38,6 +43,8 @@ impl Dispatcher {
runtime,
workspace,
#[cfg(unix)]
+ workspaces: None,
+ #[cfg(unix)]
herdr: None,
}
}
@@ -51,6 +58,53 @@ impl Dispatcher {
self
}
+ /// Configure Herdr-managed repository preparation for this daemon.
+ #[cfg(unix)]
+ pub fn with_workspaces(
+ mut self,
+ workspaces: Option<crate::herdr::repositories::Workspaces>,
+ ) -> Self {
+ self.workspaces = workspaces;
+ self
+ }
+
+ async fn workspace_for(
+ &self,
+ session: AgentSessionId,
+ repo_url: Option<&str>,
+ ) -> Result<String, DispatchError> {
+ #[cfg(unix)]
+ if let Some(workspaces) = &self.workspaces {
+ let inferred;
+ let url = match repo_url.or(self.workspace.repo_url.as_deref()) {
+ Some(url) => url,
+ None => {
+ inferred = crate::outbound::git::git(
+ &self.workspace.path,
+ &["remote", "get-url", "origin"],
+ )
+ .await
+ .map_err(|error| {
+ DispatchError::Workspace(format!("select a repository in Macro: {error}"))
+ })?;
+ &inferred
+ }
+ };
+ return workspaces
+ .prepare(&session.to_string(), url)
+ .await
+ .map(|path| path.to_string_lossy().into_owned())
+ .map_err(|error| DispatchError::Workspace(error.to_string()));
+ }
+ if repo_url.is_some() && repo_url != self.workspace.repo_url.as_deref() {
+ return Err(DispatchError::Workspace(
+ "this runtime does not manage repositories; choose a Herdr agent in macrod"
+ .to_owned(),
+ ));
+ }
+ Ok(self.workspace.path.to_string_lossy().into_owned())
+ }
+
fn created(&self, session: AgentSessionId, sender: &MacroUserIdStr<'static>) {
#[cfg(unix)]
if let Some(hub) = &self.herdr {
@@ -82,15 +136,20 @@ impl WorkExecutor for Dispatcher {
message_id,
content,
} => {
+ let session = AgentSessionId::new_from_uuid(uuid::Uuid::new_v5(
+ &bot.as_uuid(),
+ thread_id.as_bytes(),
+ ));
+ let workspace = self.workspace_for(session, None).await?;
let request = CreateAgentSessionRequest {
// The service mints the id: nothing here opens a surface
// on it before the create answers.
- id: None,
+ id: Some(session.as_uuid()),
// A harness serves many agents, so the token implies no
// bot: name the mentioned agent, and the service verifies
// it is bound to this harness.
bot_id: Some(bot.as_uuid()),
- workspace: Some(self.workspace.path.to_string_lossy().into_owned()),
+ workspace: Some(workspace),
// External sessions carry no first prompt: this daemon is
// the runtime, and it delivers the mention itself through
// the control endpoint. Sending one here is refused.
@@ -169,10 +228,12 @@ impl WorkExecutor for Dispatcher {
Ok(())
}
TriggerWork::OpenRequested {
+ repo_url,
session,
bot,
sender,
} => {
+ let workspace = self.workspace_for(session, repo_url.as_deref()).await?;
// Same create as a mention, minus the thread: the requester is
// waiting on this id, so the session is created under it. No
// prompt here - whoever asked sends their own through the
@@ -180,9 +241,9 @@ impl WorkExecutor for Dispatcher {
let request = CreateAgentSessionRequest {
id: Some(session.as_uuid()),
bot_id: Some(bot.as_uuid()),
- workspace: Some(self.workspace.path.to_string_lossy().into_owned()),
+ workspace: Some(workspace),
prompt: None,
- repo_url: self.workspace.repo_url.clone(),
+ repo_url: repo_url.or_else(|| self.workspace.repo_url.clone()),
repo_branch: None,
owner: Some(sender.as_ref().to_owned()),
thread: None,
diff --git a/crates/coding_agent_worker/src/herdr.rs b/crates/coding_agent_worker/src/herdr.rs
index 4c95bd8012..19a70be741 100644
--- a/crates/coding_agent_worker/src/herdr.rs
+++ b/crates/coding_agent_worker/src/herdr.rs
@@ -16,8 +16,9 @@
//! [`acp_agent`]).
pub(crate) mod acp_agent;
-mod cli;
+pub(crate) mod cli;
mod hub;
+pub(crate) mod repositories;
mod tap;
pub(crate) mod wire;
@@ -56,6 +57,9 @@ pub(crate) fn herdr_agent(harness: &Harness) -> Option<acp_agent::TuiAgent> {
}
mod environment {
+ macro_env_var::maybe_env_var! {
+ pub struct Home;
+ }
macro_env_var::maybe_env_var! {
pub struct HerdrEnv;
}
@@ -67,6 +71,14 @@ mod environment {
}
}
+/// Private state for one paired daemon; shared by its dispatcher and ACP process.
+pub(crate) fn instance_directory(id: impl std::fmt::Display) -> rootcause::Result<PathBuf> {
+ let home = environment::Home::new()
+ .and_then(|value| value.value().map(PathBuf::from))
+ .ok_or_else(|| rootcause::report!("HOME is required for Herdr storage"))?;
+ Ok(home.join(".macrod/herdr").join(id.to_string()))
+}
+
/// The herdr session macrod was started in.
#[derive(Debug, Clone)]
pub(crate) struct HerdrSession {
diff --git a/crates/coding_agent_worker/src/herdr/acp_agent.rs b/crates/coding_agent_worker/src/herdr/acp_agent.rs
index 737463d5eb..b5a4da3913 100644
--- a/crates/coding_agent_worker/src/herdr/acp_agent.rs
+++ b/crates/coding_agent_worker/src/herdr/acp_agent.rs
@@ -118,6 +118,8 @@ impl Transcript {
/// How `macrod herdr-acp` runs its agents.
#[derive(Debug, Clone, Default)]
pub(crate) struct AdapterOptions {
+ /// Private storage shared with the dispatcher's repository preparation.
+ pub state_dir: Option<PathBuf>,
/// The agent TUI sessions run.
pub kind: TuiAgent,
/// Passed to Claude Code as `--permission-mode`.
@@ -438,9 +440,23 @@ impl Adapter {
) -> Result<Live, RpcError> {
let kind = self.options.kind;
let label = title_from(first_prompt).unwrap_or_else(|| kind.herdr_kind().to_owned());
- let window = herdr
- .open_window(&session.cwd, &label, !self.options.no_focus)
- .await?;
+ let window = if self
+ .options
+ .state_dir
+ .as_ref()
+ .is_some_and(|root| session.cwd.starts_with(root.join("worktrees")))
+ {
+ let source = crate::outbound::git::primary_worktree(&session.cwd)
+ .await
+ .map_err(|error| RpcError::internal(error.to_string()))?;
+ herdr
+ .open_worktree(&source, &session.cwd, &label, !self.options.no_focus)
+ .await?
+ } else {
+ herdr
+ .open_window(&session.cwd, &label, !self.options.no_focus)
+ .await?
+ };
// The tab's shell must reach its prompt before an agent can start.
tokio::time::sleep(Duration::from_millis(800)).await;
diff --git a/crates/coding_agent_worker/src/herdr/cli.rs b/crates/coding_agent_worker/src/herdr/cli.rs
index 922609ebb4..69920a7e09 100644
--- a/crates/coding_agent_worker/src/herdr/cli.rs
+++ b/crates/coding_agent_worker/src/herdr/cli.rs
@@ -65,6 +65,54 @@ pub(crate) struct HerdrCli {
}
impl HerdrCli {
+ /// Let Herdr create and register a fresh worktree from the fetched main ref.
+ pub(crate) async fn create_worktree(
+ &self,
+ source: &Path,
+ path: &Path,
+ branch: &str,
+ ) -> Result<(), HerdrError> {
+ self.run(&[
+ "worktree",
+ "create",
+ "--cwd",
+ &source.to_string_lossy(),
+ "--path",
+ &path.to_string_lossy(),
+ "--branch",
+ branch,
+ "--base",
+ "origin/main",
+ "--no-focus",
+ ])
+ .await
+ .map(drop)
+ }
+
+ /// Reuse Herdr's workspace and its shell pane for a managed session worktree.
+ pub(crate) async fn open_worktree(
+ &self,
+ source: &Path,
+ path: &Path,
+ label: &str,
+ focus: bool,
+ ) -> Result<Window, HerdrError> {
+ let path = path.to_string_lossy();
+ let output = self
+ .run(&[
+ "worktree",
+ "open",
+ "--cwd",
+ &source.to_string_lossy(),
+ "--path",
+ &path,
+ "--label",
+ label,
+ if focus { "--focus" } else { "--no-focus" },
+ ])
+ .await?;
+ parse_window(&output)
+ }
/// Drive the session the given binary is attached to, opening windows in
/// `workspace_id` (herdr's focused workspace when absent).
pub(crate) fn new(bin: impl Into<PathBuf>, workspace_id: Option<String>) -> Self {
diff --git a/crates/coding_agent_worker/src/herdr/repositories.rs b/crates/coding_agent_worker/src/herdr/repositories.rs
new file mode 100644
index 0000000000..436c103b59
--- /dev/null
+++ b/crates/coding_agent_worker/src/herdr/repositories.rs
@@ -0,0 +1,49 @@
+//! Session workspaces: the repository store refreshes Git; Herdr owns worktrees.
+
+use super::cli::HerdrCli;
+use crate::outbound::git::{GitRepositories, git, primary_worktree};
+use crate::repository::{Repository, prepare};
+use std::path::{Path, PathBuf};
+
+/// Serializes repository preparation within one macrod instance.
+pub(crate) struct Workspaces {
+ git: GitRepositories,
+ herdr: HerdrCli,
+ root: PathBuf,
+ preparing: tokio::sync::Mutex<()>,
+}
+
+impl Workspaces {
+ pub(crate) fn new(search: PathBuf, root: PathBuf, herdr: HerdrCli) -> Self {
+ Self {
+ git: GitRepositories {
+ search,
+ cache: root.join("repos"),
+ },
+ herdr,
+ root,
+ preparing: tokio::sync::Mutex::new(()),
+ }
+ }
+
+ pub(crate) async fn prepare(&self, session: &str, url: &str) -> rootcause::Result<PathBuf> {
+ let repository = Repository::parse(url)?;
+ let _guard = self.preparing.lock().await;
+ let path = self.root.join("worktrees").join(session);
+ if path.exists() {
+ let remote = git(&path, &["remote", "get-url", "origin"]).await?;
+ if Repository::parse(&remote)?.key != repository.key {
+ rootcause::bail!("the existing session worktree belongs to another repository");
+ }
+ // Redelivery and reconnect preserve the session's edits and base.
+ return Ok(path);
+ }
+ let clone = prepare(&self.git, &repository).await?;
+ let source = primary_worktree(&clone).await?;
+ std::fs::create_dir_all(path.parent().unwrap_or(Path::new(".")))?;
+ self.herdr
+ .create_worktree(&source, &path, &format!("macro/{session}"))
+ .await?;
+ Ok(path)
+ }
+}
diff --git a/crates/coding_agent_worker/src/main.rs b/crates/coding_agent_worker/src/main.rs
index 9493318fcc..965fe8073b 100644
--- a/crates/coding_agent_worker/src/main.rs
+++ b/crates/coding_agent_worker/src/main.rs
@@ -22,6 +22,7 @@ mod harness;
#[cfg(unix)]
mod herdr;
mod outbound;
+mod repository;
mod runtime;
mod trigger;
mod tui;
@@ -60,6 +61,9 @@ enum Command {
/// its own herdr window. Set as the harness of a macrod run inside herdr.
#[cfg(unix)]
HerdrAcp {
+ /// Private storage for this paired macrod instance.
+ #[arg(long)]
+ state_dir: Option<std::path::PathBuf>,
/// Which agent TUI each session runs.
#[arg(long, value_enum, default_value_t)]
kind: herdr::acp_agent::TuiAgent,
@@ -106,6 +110,7 @@ async fn main() -> ExitCode {
};
}
Some(Command::HerdrAcp {
+ state_dir,
kind,
permission_mode,
no_focus,
@@ -116,6 +121,7 @@ async fn main() -> ExitCode {
.with_writer(std::io::stderr)
.init();
return match herdr::acp_agent::run(herdr::acp_agent::AdapterOptions {
+ state_dir,
kind,
permission_mode,
no_focus,
diff --git a/crates/coding_agent_worker/src/outbound/git.rs b/crates/coding_agent_worker/src/outbound/git.rs
new file mode 100644
index 0000000000..428d2d9661
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/git.rs
@@ -0,0 +1,126 @@
+//! Git-backed repository discovery and cache. Never checks out a user's branch.
+
+use crate::repository::{Repository, RepositoryStore};
+
+#[cfg(test)]
+mod test;
+use std::path::{Path, PathBuf};
+
+/// Local clones beneath the configured directory and the daemon's private cache.
+pub struct GitRepositories {
+ /// Existing clone or directory containing clones (searched two levels deep).
+ pub search: PathBuf,
+ /// Private cache root.
+ pub cache: PathBuf,
+}
+
+/// Run Git without a shell or an interactive credential prompt.
+pub async fn git(path: &Path, args: &[&str]) -> rootcause::Result<String> {
+ let output = tokio::time::timeout(
+ std::time::Duration::from_secs(120),
+ tokio::process::Command::new("git")
+ .arg("-C")
+ .arg(path)
+ .args(args)
+ .env("GIT_TERMINAL_PROMPT", "0")
+ .env("GIT_SSH_COMMAND", "ssh -oBatchMode=yes")
+ .stdin(std::process::Stdio::null())
+ .kill_on_drop(true)
+ .output(),
+ )
+ .await??;
+ if !output.status.success() {
+ rootcause::bail!(
+ "git {} failed: {}",
+ args.first().unwrap_or(&""),
+ String::from_utf8_lossy(&output.stderr).trim()
+ );
+ }
+ Ok(String::from_utf8(output.stdout)?.trim().to_owned())
+}
+
+impl RepositoryStore for GitRepositories {
+ async fn find(&self, repository: &Repository) -> rootcause::Result<Option<PathBuf>> {
+ let mut candidates = vec![
+ (self.search.clone(), 0),
+ (self.cache.join(&repository.key), 2),
+ ];
+ while let Some((path, depth)) = candidates.pop() {
+ if path.join(".git").exists() {
+ if let Ok(remote) = git(&path, &["remote", "get-url", "origin"]).await
+ && Repository::parse(&remote).is_ok_and(|remote| remote.key == repository.key)
+ {
+ return Ok(Some(path));
+ }
+ continue;
+ }
+ if depth >= 2 {
+ continue;
+ }
+ if let Ok(entries) = std::fs::read_dir(&path) {
+ for entry in entries.flatten() {
+ if entry.file_type().is_ok_and(|kind| kind.is_dir())
+ && !entry.file_name().to_string_lossy().starts_with('.')
+ {
+ candidates.push((entry.path(), depth + 1));
+ }
+ }
+ }
+ }
+ Ok(None)
+ }
+
+ async fn clone_repository(&self, repository: &Repository) -> rootcause::Result<PathBuf> {
+ let target = self.cache.join(&repository.key);
+ let parent = target
+ .parent()
+ .ok_or_else(|| rootcause::report!("invalid repository cache path"))?;
+ std::fs::create_dir_all(parent)?;
+ // A failed clone never makes a partial destination look reusable.
+ let pending = parent.join(format!(".clone-{}", uuid::Uuid::new_v4()));
+ let result = git(
+ parent,
+ &[
+ "clone",
+ "--no-checkout",
+ "--",
+ &repository.url,
+ &pending.to_string_lossy(),
+ ],
+ )
+ .await;
+ if let Err(error) = result {
+ let _ = std::fs::remove_dir_all(&pending);
+ return Err(error);
+ }
+ std::fs::rename(&pending, &target)?;
+ Ok(target)
+ }
+
+ async fn refresh_main(&self, path: &Path) -> rootcause::Result<()> {
+ git(
+ path,
+ &[
+ "fetch",
+ "--no-tags",
+ "origin",
+ "+refs/heads/main:refs/remotes/origin/main",
+ ],
+ )
+ .await?;
+ Ok(())
+ }
+}
+
+/// Find the repository's main checkout, which Herdr requires as the source of
+/// a worktree-open action even when reopening an already managed worktree.
+pub async fn primary_worktree(path: &Path) -> rootcause::Result<PathBuf> {
+ let listing = git(path, &["worktree", "list", "--porcelain", "-z"]).await?;
+ let source = listing
+ .split('\0')
+ .next()
+ .and_then(|entry| entry.strip_prefix("worktree "))
+ .filter(|path| !path.is_empty())
+ .ok_or_else(|| rootcause::report!("git did not report the repository's main worktree"))?;
+ Ok(PathBuf::from(source))
+}
diff --git a/crates/coding_agent_worker/src/outbound/git/test.rs b/crates/coding_agent_worker/src/outbound/git/test.rs
new file mode 100644
index 0000000000..a948cd06cb
--- /dev/null
+++ b/crates/coding_agent_worker/src/outbound/git/test.rs
@@ -0,0 +1,116 @@
+use super::*;
+
+#[tokio::test]
+async fn finds_an_existing_ssh_clone_for_an_https_request() {
+ let root = tempfile::tempdir().unwrap();
+ let clone = root.path().join("existing");
+ std::fs::create_dir(&clone).unwrap();
+ git(&clone, &["init"]).await.unwrap();
+ git(
+ &clone,
+ &["remote", "add", "origin", "[email protected]:org/project.git"],
+ )
+ .await
+ .unwrap();
+ let store = GitRepositories {
+ search: root.path().to_owned(),
+ cache: root.path().join("cache"),
+ };
+ assert_eq!(
+ store
+ .find(&Repository::parse("https://github.com/org/project").unwrap())
+ .await
+ .unwrap(),
+ Some(clone)
+ );
+ assert!(
+ store
+ .find(&Repository::parse("https://github.com/other/project").unwrap())
+ .await
+ .unwrap()
+ .is_none()
+ );
+}
+
+#[tokio::test]
+async fn refreshes_origin_main_without_changing_the_users_branch_or_files() {
+ let root = tempfile::tempdir().unwrap();
+ let source = root.path().join("source");
+ std::fs::create_dir(&source).unwrap();
+ git(&source, &["init", "--initial-branch=main"])
+ .await
+ .unwrap();
+ git(&source, &["config", "user.email", "[email protected]"])
+ .await
+ .unwrap();
+ git(&source, &["config", "user.name", "Test"])
+ .await
+ .unwrap();
+ std::fs::write(source.join("file"), "first").unwrap();
+ git(&source, &["add", "file"]).await.unwrap();
+ git(&source, &["commit", "-m", "initial"]).await.unwrap();
+ let clone = root.path().join("clone");
+ git(
+ root.path(),
+ &["clone", &source.to_string_lossy(), &clone.to_string_lossy()],
+ )
+ .await
+ .unwrap();
+ git(&clone, &["checkout", "-b", "users-work"])
+ .await
+ .unwrap();
+ std::fs::write(clone.join("file"), "uncommitted work").unwrap();
+ std::fs::write(source.join("file"), "latest main").unwrap();
+ git(&source, &["commit", "-am", "advance"]).await.unwrap();
+ let latest = git(&source, &["rev-parse", "HEAD"]).await.unwrap();
+ let store = GitRepositories {
+ search: clone.clone(),
+ cache: root.path().join("cache"),
+ };
+ store.refresh_main(&clone).await.unwrap();
+ assert_eq!(
+ git(&clone, &["rev-parse", "origin/main"]).await.unwrap(),
+ latest
+ );
+ assert_eq!(
+ git(&clone, &["branch", "--show-current"]).await.unwrap(),
+ "users-work"
+ );
+ assert_eq!(
+ std::fs::read_to_string(clone.join("file")).unwrap(),
+ "uncommitted work"
+ );
+}
+
+#[tokio::test]
+async fn reopening_a_linked_worktree_uses_the_main_checkout_as_herdr_source() {
+ let root = tempfile::tempdir().unwrap();
+ let source = root.path().join("source with spaces");
+ let linked = root.path().join("linked");
+ std::fs::create_dir(&source).unwrap();
+ git(&source, &["init", "--initial-branch=main"])
+ .await
+ .unwrap();
+ git(
+ &source,
+ &[
+ "-c",
+ "user.name=Test",
+ "-c",
+ "commit",
+ "--allow-empty",
+ "-m",
+ "initial",
+ ],
+ )
+ .await
+ .unwrap();
+ git(
+ &source,
+ &["worktree", "add", "-b", "session", linked.to_str().unwrap()],
+ )
+ .await
+ .unwrap();
+ assert_eq!(primary_worktree(&linked).await.unwrap(), source);
+}
diff --git a/crates/coding_agent_worker/src/outbound/mod.rs b/crates/coding_agent_worker/src/outbound/mod.rs
index 40ab3bb2e5..bd2c16ea06 100644
--- a/crates/coding_agent_worker/src/outbound/mod.rs
+++ b/crates/coding_agent_worker/src/outbound/mod.rs
@@ -12,3 +12,6 @@ pub mod agent_session;
pub mod link;
pub mod pairing;
pub mod stream;
+
+/// Git repository discovery and remote refresh.
+pub mod git;
diff --git a/crates/coding_agent_worker/src/repository.rs b/crates/coding_agent_worker/src/repository.rs
new file mode 100644
index 0000000000..64945bcc74
--- /dev/null
+++ b/crates/coding_agent_worker/src/repository.rs
@@ -0,0 +1,92 @@
+//! Repository identity and the policy for preparing a fresh session checkout.
+
+use std::path::{Path, PathBuf};
+
+#[cfg(test)]
+mod test;
+
+/// A remote repository, normalized independently of its HTTPS/SSH transport.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct Repository {
+ /// URL used when a clone does not exist yet.
+ pub url: String,
+ /// Host and repository path, safe as a relative cache directory.
+ pub key: String,
+}
+
+impl Repository {
+ /// Accept HTTPS or SSH remotes, excluding credentials and local Git transports.
+ pub fn parse(input: &str) -> rootcause::Result<Self> {
+ let input = input.trim();
+ let url = if let Some(ssh) = input.strip_prefix("git@") {
+ let (host, path) = ssh
+ .split_once(':')
+ .ok_or_else(|| rootcause::report!("invalid SSH repository"))?;
+ format!("ssh://git@{host}/{path}")
+ } else if input.starts_with("github.com/") {
+ format!("https://{input}")
+ } else {
+ input.to_owned()
+ };
+ let parsed = reqwest::Url::parse(&url)?;
+ if !matches!(parsed.scheme(), "https" | "ssh")
+ || parsed.password().is_some()
+ || parsed.query().is_some()
+ || parsed.fragment().is_some()
+ || parsed.port().is_some()
+ || (parsed.scheme() == "https" && !parsed.username().is_empty())
+ || (parsed.scheme() == "ssh" && parsed.username() != "git")
+ {
+ rootcause::bail!("use an HTTPS or git@host repository URL without credentials");
+ }
+ let host = parsed
+ .host_str()
+ .ok_or_else(|| rootcause::report!("repository host is missing"))?;
+ let path = parsed.path().trim_matches('/').trim_end_matches(".git");
+ if path.is_empty()
+ || !path.split('/').all(|part| {
+ !part.is_empty()
+ && part != "."
+ && part != ".."
+ && part
+ .chars()
+ .all(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '-' | '_' | '.'))
+ })
+ {
+ rootcause::bail!("invalid repository path");
+ }
+ Ok(Self {
+ url,
+ key: format!("{host}/{path}"),
+ })
+ }
+}
+
+/// Git operations needed to prepare a repository without changing its working tree.
+pub trait RepositoryStore {
+ /// Find a clone with the same origin among the configured search roots.
+ fn find(
+ &self,
+ repository: &Repository,
+ ) -> impl Future<Output = rootcause::Result<Option<PathBuf>>> + Send;
+ /// Clone into the private repository cache, returning its path.
+ fn clone_repository(
+ &self,
+ repository: &Repository,
+ ) -> impl Future<Output = rootcause::Result<PathBuf>> + Send;
+ /// Fetch the latest origin/main, failing when the remote has no main branch.
+ fn refresh_main(&self, path: &Path) -> impl Future<Output = rootcause::Result<()>> + Send;
+}
+
+/// Resolve a clone and refresh the base before Herdr creates a new worktree.
+pub async fn prepare(
+ store: &impl RepositoryStore,
+ repository: &Repository,
+) -> rootcause::Result<PathBuf> {
+ let path = match store.find(repository).await? {
+ Some(path) => path,
+ None => store.clone_repository(repository).await?,
+ };
+ store.refresh_main(&path).await?;
+ Ok(path)
+}
diff --git a/crates/coding_agent_worker/src/repository/test.rs b/crates/coding_agent_worker/src/repository/test.rs
new file mode 100644
index 0000000000..6dd7aec6ac
--- /dev/null
+++ b/crates/coding_agent_worker/src/repository/test.rs
@@ -0,0 +1,24 @@
+use super::*;
+
+#[test]
+fn transport_does_not_change_repository_identity() {
+ let https = Repository::parse("https://github.com/macro-inc/macro.git").unwrap();
+ let ssh = Repository::parse("[email protected]:macro-inc/macro.git").unwrap();
+ assert_eq!(https.key, ssh.key);
+ assert_eq!(https.key, "github.com/macro-inc/macro");
+}
+
+#[test]
+fn rejects_local_transports_credentials_and_options() {
+ for input in [
+ "/tmp/repo",
+ "file:///tmp/repo",
+ "ext::sh -c evil",
+ "--upload-pack=evil",
+ "https://[email protected]/a/b",
+ "https://github.com/a/b?x=y",
+ "ssh://[email protected]/a",
+ ] {
+ assert!(Repository::parse(input).is_err(), "{input}");
+ }
+}
diff --git a/crates/coding_agent_worker/src/trigger.rs b/crates/coding_agent_worker/src/trigger.rs
index b408f527e0..625191014a 100644
--- a/crates/coding_agent_worker/src/trigger.rs
+++ b/crates/coding_agent_worker/src/trigger.rs
@@ -49,6 +49,8 @@ pub enum TriggerWork {
/// the app shows the session directly and sends its own first prompt
/// through the session once this create answers.
OpenRequested {
+ /// Remote repository supplied by Macro, if selected.
+ repo_url: Option<String>,
/// The id to create the session under.
session: AgentSessionId,
/// The agent the session runs for.
@@ -86,6 +88,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
match event {
AgentTriggerTopicEvent::New(NewAgentSessionEvent::Requested(
AgentSessionRequestedEvent {
+ repo_url,
bot_id,
session_id,
owner,
@@ -93,6 +96,7 @@ pub fn trigger_to_work(event: AgentTriggerTopicEvent) -> Result<TriggerWork, Ski
)) => {
let sender = MacroUserIdStr::try_from(owner).map_err(|_| Skipped::NotFromUser)?;
Ok(TriggerWork::OpenRequested {
+ repo_url,
session: session_id,
bot: bot_id,
sender,
diff --git a/crates/coding_agent_worker/src/trigger/test.rs b/crates/coding_agent_worker/src/trigger/test.rs
index aad52a5ef9..98ce07f764 100644
--- a/crates/coding_agent_worker/src/trigger/test.rs
+++ b/crates/coding_agent_worker/src/trigger/test.rs
@@ -11,6 +11,22 @@ use messages::domain::events::MessagePostedMetadata;
use messages::domain::models::MessageParent;
use std::sync::Mutex;
+#[test]
+fn repository_selection_survives_dispatch_and_older_events_still_decode() {
+ let mut wire = serde_json::json!({"bot_id": bot_id::BotId::TEST_A, "session_id": test_session(), "owner": sender().to_string()});
+ let old: AgentSessionRequestedEvent = serde_json::from_value(wire.clone()).unwrap();
+ assert!(old.repo_url.is_none());
+ wire["repo_url"] = serde_json::json!("https://github.com/org/project");
+ let event: AgentSessionRequestedEvent = serde_json::from_value(wire).unwrap();
+ let work = trigger_to_work(AgentTriggerTopicEvent::New(
+ NewAgentSessionEvent::Requested(event),
+ ))
+ .unwrap();
+ assert!(
+ matches!(work, TriggerWork::OpenRequested { repo_url: Some(url), .. } if url == "https://github.com/org/project")
+ );
+}
+
fn test_session() -> AgentSessionId {
AgentSessionId::new_from_uuid(Uuid::from_u128(0xA))
}
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 555f2811b4..9784dc229c 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -1394,6 +1394,7 @@ fn agent_trigger_requested_event()
Event::new(AgentTriggerTopicEvent::New(
NewAgentSessionEvent::Requested(AgentSessionRequestedEvent {
+ repo_url: None,
bot_id: bot_id::BotId::new_from_uuid(uuid::Uuid::from_u128(0xB07)),
session_id: agent_session::domain::model::AgentSessionId::new_from_uuid(
uuid::Uuid::from_u128(0x5E55),
diff --git a/services/agent_harness_service/src/external_session_requests.rs b/services/agent_harness_service/src/external_session_requests.rs
index 96ef2061bd..2541f6920b 100644
--- a/services/agent_harness_service/src/external_session_requests.rs
+++ b/services/agent_harness_service/src/external_session_requests.rs
@@ -18,7 +18,7 @@ use macro_event_broker::MacroEventBroker;
/// How long a runtime gets to create the session before the request is
/// refused. A daemon that is up answers well inside this; one that is down
/// or too old to know the event never will.
-const RUNTIME_ANSWER_TIMEOUT: Duration = Duration::from_secs(8);
+const RUNTIME_ANSWER_TIMEOUT: Duration = Duration::from_secs(180);
const POLL_INTERVAL: Duration = Duration::from_millis(250);
/// [`ExternalSessionRequester`] over the trigger topic and the session table.
@@ -46,6 +46,7 @@ where
let session_id = request.session_id;
let event = AgentSessionMacroEvent::requested_event(AgentSessionRequestedEvent {
bot_id: request.bot_id,
+ repo_url: request.repo_url,
session_id,
owner: request.owner.as_ref().to_owned(),
});