magi-code 0.96.1

Repository-aware CLI coding agent for terminal work
Documentation
use super::*;

fn seed_startup_fixture() -> anyhow::Result<(TempDir, McPaths, PathBuf)> {
    let temp = TempDir::new()?;
    let mc_root = temp.path().join("mc-home");
    let repo_root = temp.path().join("repo");
    let paths = McPaths::from_root(mc_root.clone());
    paths.ensure_runtime_dirs()?;
    fs::create_dir_all(&paths.skills)?;
    fs::create_dir_all(&paths.prompts)?;
    fs::create_dir_all(repo_root.join(".agents/skills/repo-review"))?;
    fs::create_dir_all(paths.skills.join("local-plan"))?;
    fs::create_dir_all(&paths.sessions)?;
    fs::write(
        &paths.settings_file,
        r#"{"selected_model":{"provider":"openai-codex","model":"codex-local"},"file_autocomplete_respects_gitignore":true}"#,
    )?;
    fs::write(&paths.user_agents, "User synthetic instruction.\n")?;
    fs::write(repo_root.join("AGENTS.md"), "Repo synthetic instruction.\n")?;
    fs::write(
        paths.skills.join("local-plan/SKILL.md"),
        "---\ndescription: Synthetic planning skill\n---\n# Local plan\n",
    )?;
    fs::write(
        repo_root.join(".agents/skills/repo-review/SKILL.md"),
        "---\ndescription: Synthetic review skill\n---\n# Repo review\n",
    )?;
    for index in 0..50 {
        let id = format!("00000000-0000-4000-8000-{index:012}");
        fs::write(
            paths.sessions.join(format!("{id}.jsonl")),
            format!(r#"{{"event_type":"user","text":"synthetic prompt {index}"}}\n"#),
        )?;
    }
    write_catalog_cache(
        &paths,
        "openai-codex",
        &[ModelCatalogEntry {
            context_window: Some(128_000),
            ..ModelCatalogEntry::new_codex("codex-local")
        }],
    )?;
    Ok((temp, paths, repo_root))
}

struct SkillDiscoveryFixture {
    _temp: TempDir,
    roots: SkillRoots,
    expected_skills: usize,
    aggregate_body_bytes: u64,
    first_read_skill: String,
}

fn seed_skill_discovery_fixture() -> anyhow::Result<SkillDiscoveryFixture> {
    let temp = TempDir::new()?;
    let root = temp.path().join("skills");
    let mut aggregate_body_bytes = 0u64;

    let mut write_skill = |relative_dir: &str, frontmatter: &str, body: Vec<u8>| {
        let directory = root.join(relative_dir);
        fs::create_dir_all(&directory)?;
        let mut content = frontmatter.as_bytes().to_vec();
        content.extend_from_slice(&body);
        aggregate_body_bytes = aggregate_body_bytes.saturating_add(body.len() as u64);
        fs::write(directory.join("SKILL.md"), content)?;
        anyhow::Ok(())
    };

    write_skill(
        "small",
        "---\ndescription: Small synthetic skill\n---\n",
        b"# Small\n".to_vec(),
    )?;
    for index in 0..24 {
        write_skill(
            &format!("empty-group/empty-{index:02}"),
            "---\ndescription: Empty-body fixture\n---\n",
            Vec::new(),
        )?;
    }
    for index in 0..24 {
        write_skill(
            &format!("representative-group/representative-{index:02}"),
            "---\ndescription: Representative-body fixture\n---\n",
            vec![b'r'; 8 * 1024],
        )?;
    }
    for index in 0..4 {
        let frontmatter = "---\ndescription: Near-limit fixture\n---\n";
        let body_len = crate::skills::DISCOVERY_SKILL_MAX_BYTES as usize - frontmatter.len();
        write_skill(
            &format!("near-group/near-{index}"),
            frontmatter,
            vec![b'n'; body_len],
        )?;
    }
    write_skill(
        "disabled",
        "---\ndescription: Disabled mixed fixture\n---\n",
        b"disabled body".to_vec(),
    )?;
    write_skill("mixed-a/collision", "", b"first collision".to_vec())?;
    write_skill("mixed-b/collision", "", b"second collision".to_vec())?;
    write_skill("malformed", "---\nbad-line\n", b"malformed body".to_vec())?;
    write_skill(
        "oversized",
        "",
        vec![b'x'; crate::skills::DISCOVERY_SKILL_MAX_BYTES as usize + 1],
    )?;

    Ok(SkillDiscoveryFixture {
        roots: SkillRoots {
            mc_skills: root,
            repo_skills: temp.path().join("missing-repo"),
            legacy_agents_skills: temp.path().join("missing-legacy"),
            additional_paths: Vec::new(),
        },
        _temp: temp,
        expected_skills: 55,
        aggregate_body_bytes,
        first_read_skill: "near-0".to_string(),
    })
}

fn discover_skills_once(roots: &SkillRoots) -> u64 {
    let discovery = black_box(discover_skills(black_box(roots)));
    black_box((discovery.skills.len() + discovery.diagnostics.len()) as u64)
}

fn startup_discovery_once(paths: &McPaths, repo_root: &Path) -> anyhow::Result<u64> {
    let settings = read_settings(paths)?;
    let instructions = discover_agents_with_additional_markdown(
        &paths.user_agents,
        repo_root,
        &settings.instructions.additional_markdown_paths,
    )?;
    let skills = discover_skills(&SkillRoots {
        mc_skills: paths.skills.clone(),
        repo_skills: repo_root.join(".agents/skills"),
        legacy_agents_skills: repo_root.join("missing-legacy"),
        additional_paths: Vec::new(),
    });
    let sessions = SessionManager::new(paths.sessions.clone()).list()?;
    let context = cached_model_context_window(paths, "openai-codex", "codex-local").unwrap_or(0);
    Ok(settings
        .selected_model
        .provider
        .as_deref()
        .unwrap_or_default()
        .len() as u64
        + instructions.len() as u64
        + skills.skills.len() as u64
        + sessions.len() as u64
        + context as u64)
}

fn parse_sse_once() -> anyhow::Result<u64> {
    let mut events = Vec::new();
    for fixture in [RESPONSES_SSE, CHAT_COMPLETIONS_SSE] {
        let mut parser = StreamParser::default();
        for chunk in fixture.as_bytes().chunks(37) {
            let chunk = std::str::from_utf8(chunk)?;
            events.extend(parser.push_chunk(chunk)?);
        }
        events.extend(parser.finish()?);
    }
    let text_events = events
        .iter()
        .filter(|event| matches!(event, ProviderEvent::TextDelta(_)))
        .count();
    let tool_events = events
        .iter()
        .filter(|event| matches!(event, ProviderEvent::ToolCall(_)))
        .count();
    Ok((text_events + tool_events + events.len()) as u64)
}

fn heavy_transcript_once() -> u64 {
    let mut state = MissionControlState::default();
    for index in 0..40 {
        state.apply_output_event(&OutputEvent::UserPrompt {
            text: format!("inspect synthetic turn {index}"),
        });
        state.apply_output_event(&OutputEvent::AssistantComplete {
            text: RENDERING_TRANSCRIPT.to_string(),
        });
    }
    let lines = state.cached_transcript_lines(80);
    let visual_rows = state.transcript_visual_rows(96);
    black_box(lines.len() as u64 + visual_rows as u64)
}

fn streaming_simulation_once() -> u64 {
    let mut state = MissionControlState::default();
    state.apply_output_event(&OutputEvent::UserPrompt {
        text: "stream synthetic assistant response".to_string(),
    });
    for index in 0..250 {
        state.apply_output_event(&OutputEvent::AssistantDelta {
            text: format!("delta-{index} "),
        });
        let id = ActivityId::new(format!("tool-{index}"));
        state.apply_activity_event(ActivityEvent::Started {
            id: id.clone(),
            parent_id: None,
            kind: ActivityKind::Tool,
            status: ActivityStatus::Running,
            metadata: ActivityMetadata::new(format!("synthetic tool {index}")),
        });
        state.apply_activity_event(ActivityEvent::Delta {
            id,
            preview: format!("preview line {index}"),
        });
    }
    state.apply_output_event(&OutputEvent::AssistantComplete {
        text: "final synthetic assistant response".repeat(20),
    });
    let transcript = state.cached_transcript_lines(80).len();
    let nodes = state.visible_nodes().len();
    let detail_rows = state.detail_visual_rows(80);
    black_box((transcript + nodes + detail_rows) as u64)
}
#[cfg(unix)]
fn timeout_cleanup_once() -> anyhow::Result<u64> {
    use std::os::unix::process::CommandExt;
    let mut child = Command::new("/bin/bash")
        .arg("-lc")
        .arg("(sleep 5) & wait")
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .process_group(0)
        .spawn()?;
    std::thread::sleep(Duration::from_millis(5));
    let cleanup = terminate_child_tree_and_wait(&mut child)?;
    Ok(u64::from(cleanup.cleanup_warning.is_some()) + u64::from(cleanup.status.is_some()))
}

#[cfg(not(unix))]
fn timeout_cleanup_once() -> anyhow::Result<u64> {
    let mut child = Command::new("cmd")
        .args(["/C", "ping", "127.0.0.1", "-n", "5"])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()?;
    std::thread::sleep(Duration::from_millis(5));
    let cleanup = terminate_child_tree_and_wait(&mut child)?;
    Ok(u64::from(cleanup.cleanup_warning.is_some()) + u64::from(cleanup.status.is_some()))
}

#[test]
#[ignore = "CPU profiling harness; run explicitly with --ignored --nocapture"]
fn profile_cpu_startup_discovery() {
    let (_temp, paths, repo_root) = seed_startup_fixture().expect("seed startup fixture");
    let result = run_profile(
        "startup_discovery",
        "discovered_items",
        "target/profiling/issue-48/startup-discovery",
        || startup_discovery_once(&paths, &repo_root).expect("startup discovery"),
    );
    assert!(result.metric_value > 0);
    result.print();
}

#[test]
#[ignore = "CPU profiling harness; run explicitly with --ignored --nocapture"]
fn profile_cpu_discover_skills() {
    let fixture = seed_skill_discovery_fixture().expect("seed skill discovery fixture");
    let discovery = discover_skills(&fixture.roots);
    assert_eq!(discovery.skills.len(), fixture.expected_skills);
    assert_eq!(discovery.diagnostics.len(), 3);

    let runtime = ToolRuntime::new(fixture._temp.path())
        .expect("tool runtime")
        .with_skills(&discovery);
    let first_read_started = Instant::now();
    let first_read = runtime.dispatch(
        "read",
        json!({"path": format!("skill://{}", fixture.first_read_skill)}),
    );
    let first_read_elapsed = first_read_started.elapsed();
    assert!(first_read.success, "{}", first_read.content);
    println!(
        "profile_cpu_first_skill_read skill={} elapsed_us={} bytes={}",
        fixture.first_read_skill,
        first_read_elapsed.as_micros(),
        first_read.metadata["bytes"]
    );

    let mut result = run_profile(
        "discover_skills",
        "discovered_items",
        "target/profiling/issue-381/discover-skills",
        || discover_skills_once(&fixture.roots),
    );
    result.counters.extend([
        ("fixture_skills", fixture.expected_skills as u64),
        ("fixture_body_bytes", fixture.aggregate_body_bytes),
        ("fixture_diagnostics", 3),
    ]);
    assert!(result.metric_value > 0);
    result.print();
}

#[test]
#[ignore = "CPU profiling harness; run explicitly with --ignored --nocapture"]
fn profile_cpu_sse_parser() {
    let result = run_profile(
        "provider_sse_parser",
        "events_parsed",
        "target/profiling/issue-48/sse-parser",
        || parse_sse_once().expect("parse sse"),
    );
    assert!(result.metric_value > 0);
    result.print();
}

#[test]
#[ignore = "CPU profiling harness; run explicitly with --ignored --nocapture"]
fn profile_cpu_rendering_heavy_transcript() {
    let result = run_profile(
        "rendering_heavy_transcript",
        "rendered_units",
        "target/profiling/issue-48/rendering-heavy-transcript",
        heavy_transcript_once,
    );
    assert!(result.metric_value > 0);
    result.print();
}

#[test]
#[ignore = "CPU profiling harness; run explicitly with --ignored --nocapture"]
fn profile_cpu_tui_streaming_simulation() {
    let result = run_profile(
        "tui_streaming_simulation",
        "state_units",
        "target/profiling/issue-48/tui-streaming-simulation",
        streaming_simulation_once,
    );
    assert!(result.metric_value > 0);
    result.print();
}

#[test]
#[ignore = "CPU profiling harness; run explicitly with --ignored --nocapture"]
fn profile_cpu_tool_timeout_cleanup() {
    let result = run_profile(
        "tool_timeout_cleanup",
        "cleanup_units",
        "target/profiling/issue-48/tool-timeout-cleanup",
        || timeout_cleanup_once().expect("timeout cleanup"),
    );
    result.print();
}