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
1 change: 1 addition & 0 deletions services/gateway/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ async fn main() -> Result<(), Error> {
"/repos/:owner/:name/regenerate",
post(routes::api::regenerate_repo),
)
.route("/repos/:owner/:name/role", post(routes::api::set_repo_role))
.route(
"/integrations/jira/check",
get(routes::api::get_jira_integration_check)
Expand Down
49 changes: 49 additions & 0 deletions services/gateway/src/routes/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1450,6 +1450,7 @@ pub async fn list_repos(
"ticket_source": item.get("ticket_source").and_then(|v| v.as_s().ok()),
"onboard_status": item.get("onboard_status").and_then(|v| v.as_s().ok()),
"onboard_error": item.get("onboard_error").and_then(|v| v.as_s().ok()),
"role": item.get("role").and_then(|v| v.as_s().ok()),
}))
})
.collect();
Expand Down Expand Up @@ -2491,6 +2492,54 @@ pub async fn validate_jira_integration_payload(
})))
}

/// Valid repo role designations. A repo's role tells the Jira repo-selector which
/// repo owns a domain, so an ambiguous ticket (e.g. a Tailwind change matching two
/// frontends) resolves to the team's designated repo instead of an LLM guess.
pub const VALID_REPO_ROLES: &[&str] = &["web", "backend", "mobile", "cms", "infra", "data"];

/// POST /api/repos/:owner/:name/role — set (or clear, with "") a repo's role.
pub async fn set_repo_role(
State(state): State<Arc<AppState>>,
Extension(claims): Extension<Claims>,
axum::extract::Path((owner, name)): axum::extract::Path<(String, String)>,
Json(body): Json<Value>,
) -> Result<StatusCode, StatusCode> {
claims.require_role(3)?; // admin+
let repo = format!("{owner}/{name}");
validate_repo_name(&repo)?;
let role = body["role"].as_str().unwrap_or("").trim().to_lowercase();
let now = chrono::Utc::now().to_rfc3339();

let base = state
.dynamo
.update_item()
.table_name(&state.config.repos_table_name)
.key("pk", attr_s(&claims.team_id))
.key("sk", attr_s(&format!("REPO#{repo}")))
// Only designate a repo that exists (was synced) — never mint a stub.
.condition_expression("attribute_exists(sk)")
.expression_attribute_names("#role", "role")
.expression_attribute_values(":ua", attr_s(&now));

let update = if role.is_empty() {
base.update_expression("SET updated_at = :ua REMOVE #role")
} else {
if !VALID_REPO_ROLES.contains(&role.as_str()) {
return Err(StatusCode::BAD_REQUEST);
}
base.update_expression("SET #role = :role, updated_at = :ua")
.expression_attribute_values(":role", attr_s(&role))
};

update.send().await.map_err(|e| {
error!("Failed to set repo role for {repo}: {e}");
// ConditionalCheckFailed (unknown repo) is a client error.
StatusCode::BAD_REQUEST
})?;

Ok(StatusCode::OK)
}

/// POST /api/repos/:owner/:name — update repo config.
pub async fn update_repo(
State(state): State<Arc<AppState>>,
Expand Down
43 changes: 43 additions & 0 deletions services/worker/src/passes/plan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -650,6 +650,49 @@ pub async fn fetch_team_repos(state: &WorkerState, team_id: &str) -> Vec<String>
}
}

/// Fetch human-assigned repo roles (repo_name → role) for a team. Only repos
/// that have a role set are returned. Used by Jira repo selection to resolve
/// ambiguous tickets to the team's designated repo for that domain.
pub async fn fetch_team_repo_roles(
state: &WorkerState,
team_id: &str,
) -> std::collections::HashMap<String, String> {
let result = state
.dynamo
.query()
.table_name(&state.config.repos_table_name)
.key_condition_expression("pk = :pk AND begins_with(sk, :prefix)")
.expression_attribute_values(
":pk",
aws_sdk_dynamodb::types::AttributeValue::S(team_id.to_string()),
)
.expression_attribute_values(
":prefix",
aws_sdk_dynamodb::types::AttributeValue::S("REPO#".to_string()),
)
.send()
.await;

match result {
Ok(output) => output
.items()
.iter()
.filter_map(|item| {
let name = item.get("repo_name").and_then(|v| v.as_s().ok())?;
let role = item
.get("role")
.and_then(|v| v.as_s().ok())
.filter(|s| !s.is_empty())?;
Some((name.clone(), role.clone()))
})
.collect(),
Err(e) => {
tracing::warn!(error = %e, "Failed to fetch repo roles");
std::collections::HashMap::new()
}
}
}

// ─── Combined tool executor (read-only + MCP) ──────────────

struct CombinedToolExecutor<'a> {
Expand Down
33 changes: 30 additions & 3 deletions services/worker/src/passes/triage.rs
Original file line number Diff line number Diff line change
Expand Up @@ -396,6 +396,33 @@ pub async fn select_repo(
)
};

// Human-assigned repo roles are the AUTHORITATIVE tiebreak for ambiguous
// tickets (e.g. two frontends that both use Tailwind): the team designates
// which repo owns each domain, so selection follows that instead of guessing
// from auto-generated descriptions.
let roles = crate::passes::plan::fetch_team_repo_roles(state, &msg.team_id).await;
let roles_section = {
let mut lines: Vec<String> = repos
.iter()
.filter_map(|r| roles.get(r).map(|role| format!("- {r} → {role}")))
.collect();
lines.sort();
if lines.is_empty() {
String::new()
} else {
format!(
"\n## Repo roles (human-assigned — AUTHORITATIVE)\n{}\n\
Meanings: web=primary web frontend, backend=primary API/backend, \
mobile=mobile app, cms=content/CMS, infra=infrastructure, data=data/ETL.\n\
These roles OVERRIDE repo descriptions and incidental code matches — a human set \
them to resolve exactly the cases where several repos could match. Classify the \
ticket's domain and pick the repo whose role matches it, unless the ticket \
explicitly names a different repo.\n",
lines.join("\n")
)
}
};

let global_agents = super::load_content(state, &msg.team_id, "AGENTS#GLOBAL").await;

let context_section = if global_agents.is_empty() {
Expand All @@ -416,10 +443,10 @@ Description:
{context_section}
## Available repositories
{repo_list}
{evidence_section}
{evidence_section}{roles_section}
Think step by step:
1. What is this ticket about? (one sentence)
2. Which repo owns that feature area? Weigh the CODE EVIDENCE above (which repo actually contains the ticket's identifiers) ABOVE the repo descriptions.
1. What is this ticket about, and what DOMAIN is it — web/frontend, backend/API, mobile, cms, infra, or data? (one sentence)
2. If a repo has a ROLE matching that domain (see Repo roles), pick it — roles are authoritative and override descriptions. Otherwise weigh the CODE EVIDENCE (which repo actually contains the ticket's identifiers) ABOVE the repo descriptions.
3. Why is it NOT any of the other repos?

Then on the LAST line, return ONLY the repository in `owner/name` format."#,
Expand Down
Loading