Files
clawmates/crates/cm-api/tests/mission_orchestrator.rs
T
Omar Sobh d8c8793c4a
ci / gates (push) Successful in 8s
ci / frontend (push) Successful in 26s
ci / rust (push) Successful in 4m25s
ci / e2e (push) Skipped
ci / publish (push) Successful in 2m46s
ci fixes: cargo fmt, eslint entities, max-lines split
CI on 6ffbe97 failed on two auto-fixable gates. Both fixed:

  * cargo fmt --all — rustfmt applied across the surface touched
    by the last ~20 commits (world.rs, security_scan.rs,
    routes/{missions,nodes,terminal}.rs, fleet_herdr.rs,
    mission_workspace.rs, benchmark_runner.rs, mission_refiner.rs,
    lib.rs, tests/mission_orchestrator.rs, cm-db/repo/{missions,teams}.rs,
    bins/clawmates-node/src/main.rs)
  * eslint apostrophe escapes in HerdrSessions + MissionWizard
  * eslint max-lines: extracted EditMissionModal + RefineDiffModal
    (each ~200 LoC) into their own files. MissionCanvas drops from
    1424 to 1026, comfortably under both the 1250 eslint cap and the
    1500 CI budget.

New files:
  frontend/src/components/dashboard/EditMissionModal.tsx  (211 LoC)
  frontend/src/components/dashboard/RefineDiffModal.tsx   (208 LoC)

Verified locally: cargo fmt --check clean, cargo check clean,
mission_orchestrator test 3/3 pass, tsc + eslint --quiet both silent.
2026-07-20 12:03:43 -07:00

258 lines
8.6 KiB
Rust

//! End-to-end coverage for `mission_orchestrator::on_launch` — the
//! draft→running transition that materializes a team from a template,
//! inserts agents, seeds brains, records template lineage, and binds
//! members via team_members. Runs against a real Postgres (cm-testkit).
//!
//! What this test locks in:
//! * Given a mission with `team_template_id` and no `team_id`,
//! `on_launch` materializes exactly one team per role in the
//! template.
//! * The materialized team carries `template_id` + `template_version`
//! + `risk_profile` + `mcp_bundles` from the template row.
//! * Every role produces one `agents` row + one
//! `agent_template_link` row (seeded=true).
//! * `team_members` binds every claw to a topology node id.
//! * The mission row's `team_id` gets updated.
//! * Re-invoking is a no-op (returns the existing team_id, doesn't
//! duplicate agents).
use cm_api::mission_orchestrator;
use cm_db::repo::{team_templates, users, workspaces};
use cm_domain::{Role, User, UserId, Workspace, WorkspaceId};
use serde_json::json;
use sqlx::Row;
use uuid::Uuid;
async fn seed_workspace(pool: &sqlx::PgPool) -> WorkspaceId {
let ws = Workspace {
id: WorkspaceId::new(),
name: "Missions Test".into(),
plan: "team".into(),
};
workspaces::insert(pool, &ws).await.unwrap();
ws.id
}
async fn seed_owner(pool: &sqlx::PgPool, ws: WorkspaceId) -> UserId {
let user = User {
id: UserId::new(),
workspace_id: ws,
email: "[email protected]".into(),
role: Role::Owner,
display_name: "Owner".into(),
created_at: time::OffsetDateTime::UNIX_EPOCH,
};
users::insert(pool, &user).await.unwrap();
user.id
}
async fn seed_test_template(pool: &sqlx::PgPool) -> Uuid {
let id = Uuid::now_v7();
team_templates::upsert_builtin(
pool,
team_templates::UpsertBuiltin {
id,
key: "test_backend",
name: "Test Backend Team",
stack: vec!["rust".into(), "postgres".into()],
default_topology: "pipeline",
risk_profile: "medium",
mcp_bundles: vec!["clawmates_skills".into()],
version: 1,
description: Some("Fixture template for orchestrator test"),
config: json!({}),
roles: vec![
team_templates::UpsertBuiltinRole {
slot: "planner",
order_idx: 0,
system_prompt: "Plan the feature. Break it into INT-XX items.",
skills: vec!["decompose-int-items".into()],
brain_seed: Some("# Planner\nBreak features into INT items."),
},
team_templates::UpsertBuiltinRole {
slot: "coder",
order_idx: 1,
system_prompt: "Implement one INT item at a time.",
skills: vec!["write-rust-current-edition".into()],
brain_seed: Some("# Coder\nOne INT per commit."),
},
team_templates::UpsertBuiltinRole {
slot: "reviewer",
order_idx: 2,
system_prompt: "Review each commit before merge.",
skills: vec!["code-review-checklist".into()],
brain_seed: None,
},
],
},
)
.await
.unwrap();
id
}
async fn seed_mission(
pool: &sqlx::PgPool,
ws: WorkspaceId,
template_id: Uuid,
title: &str,
) -> Uuid {
let id = Uuid::now_v7();
sqlx::query(
"INSERT INTO missions
(id, workspace_id, title, template_kind, team_template_id, schedule, status, config)
VALUES ($1, $2, $3, 'research_and_code', $4, '{\"kind\":\"one_shot\"}'::jsonb,
'draft', '{}'::jsonb)",
)
.bind(id)
.bind(ws.as_uuid())
.bind(title)
.bind(template_id)
.execute(pool)
.await
.unwrap();
id
}
#[tokio::test]
async fn on_launch_materializes_team_from_template() {
let pool = cm_testkit::test_pool().await;
let ws = seed_workspace(&pool).await;
let owner = seed_owner(&pool, ws).await;
let template_id = seed_test_template(&pool).await;
let mission_id = seed_mission(&pool, ws, template_id, "Test Mission").await;
let team_id = mission_orchestrator::on_launch(&pool, ws, owner, mission_id, None)
.await
.expect("on_launch succeeds")
.expect("returns a team id");
// Team row exists with template lineage stamped.
let team_row = sqlx::query(
"SELECT template_id, template_version, risk_profile, mcp_bundles
FROM teams WHERE id = $1",
)
.bind(team_id)
.fetch_one(&pool)
.await
.unwrap();
let stamped_template_id: Uuid = team_row.get("template_id");
let stamped_version: i32 = team_row.get("template_version");
let stamped_risk: String = team_row.get("risk_profile");
assert_eq!(stamped_template_id, template_id);
assert_eq!(stamped_version, 1);
assert_eq!(stamped_risk, "medium");
// One agent per role — three total.
let agent_count: i64 =
sqlx::query_scalar("SELECT count(*)::bigint FROM team_members WHERE team_id = $1")
.bind(team_id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(agent_count, 3, "expected one member per role");
// Every member has a matching agents row + role_slot binding.
let member_slots: Vec<String> = sqlx::query_scalar(
"SELECT tm.role FROM team_members tm
JOIN agents a ON a.id = tm.claw_id
WHERE tm.team_id = $1
ORDER BY tm.role",
)
.bind(team_id)
.fetch_all(&pool)
.await
.unwrap();
assert_eq!(member_slots, vec!["coder", "planner", "reviewer"]);
// Every claw has an agent_template_link row with seeded=true.
let seeded_count: i64 = sqlx::query_scalar(
"SELECT count(*)::bigint FROM agent_template_link atl
JOIN team_members tm ON tm.claw_id = atl.agent_id
WHERE tm.team_id = $1
AND atl.template_id = $2",
)
.bind(team_id)
.bind(template_id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(
seeded_count, 3,
"expected every claw to have seeded lineage"
);
// Mission row was updated to point at the new team.
let bound_team_id: Uuid = sqlx::query_scalar("SELECT team_id FROM missions WHERE id = $1")
.bind(mission_id)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(bound_team_id, team_id);
}
#[tokio::test]
async fn on_launch_is_idempotent() {
let pool = cm_testkit::test_pool().await;
let ws = seed_workspace(&pool).await;
let owner = seed_owner(&pool, ws).await;
let template_id = seed_test_template(&pool).await;
let mission_id = seed_mission(&pool, ws, template_id, "Idempotency Mission").await;
let team_a = mission_orchestrator::on_launch(&pool, ws, owner, mission_id, None)
.await
.unwrap()
.unwrap();
let team_b = mission_orchestrator::on_launch(&pool, ws, owner, mission_id, None)
.await
.unwrap()
.unwrap();
assert_eq!(
team_a, team_b,
"second invocation should return the same team_id"
);
// Still exactly three agents — no duplication.
let agent_count: i64 =
sqlx::query_scalar("SELECT count(*)::bigint FROM team_members WHERE team_id = $1")
.bind(team_a)
.fetch_one(&pool)
.await
.unwrap();
assert_eq!(agent_count, 3);
}
#[tokio::test]
async fn on_launch_no_template_returns_none() {
let pool = cm_testkit::test_pool().await;
let ws = seed_workspace(&pool).await;
let owner = seed_owner(&pool, ws).await;
// Mission with no team_template_id.
let mission_id = Uuid::now_v7();
sqlx::query(
"INSERT INTO missions
(id, workspace_id, title, template_kind, schedule, status, config)
VALUES ($1, $2, 'no template', 'refactor', '{\"kind\":\"one_shot\"}'::jsonb,
'draft', '{}'::jsonb)",
)
.bind(mission_id)
.bind(ws.as_uuid())
.execute(&pool)
.await
.unwrap();
let result = mission_orchestrator::on_launch(&pool, ws, owner, mission_id, None)
.await
.unwrap();
assert!(result.is_none(), "no template + no team should return None");
// Mission stays with team_id NULL.
let team_id: Option<Uuid> = sqlx::query_scalar("SELECT team_id FROM missions WHERE id = $1")
.bind(mission_id)
.fetch_one(&pool)
.await
.unwrap();
assert!(team_id.is_none());
}