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.

30.1 KB
Raw Blame
//! The per-harness readers, against the frame shapes each harness's source
//! confirms (see the research notes in the PR that added them). Where a real
//! recording exists it is pinned in `real_recordings`; these pin the readers
//! for harnesses we have read but not yet recorded.

use crate::domain::model::{
    AnsiText, Harness, MessagePart, SubagentResult, ToolDetail, ToolName, ToolStatus, ToolUseId,
};
use crate::domain::test::util::Frame;
use agent_client_protocol::schema::v1::ToolKind;
use serde_json::{Value, json};

fn native(name: &str) -> ToolName {
    ToolName::native(name)
}

// --- Claude Code (@agentclientprotocol/claude-agent-acp) ---

/// `AskUserQuestion` through `elicitation/create`: the `question_N_custom`
/// companion carries the shared marker; without one its name and title say.
#[test]
fn claude_code_recognizes_its_custom_answer_companion() {
    let reader = Harness::ClaudeCode.reader();
    let marked = json!({"type": "string", "title": "Other", "description": "Type your own answer instead of choosing an option above (optional).", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "question_0", "isCustomAnswer": true}}});
    assert_eq!(
        reader.custom_answer_for("question_0_custom", &marked),
        Some("question_0".to_owned())
    );
    let unset = json!({"type": "string", "title": "Other", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "question_0", "isCustomAnswer": false}}});
    assert_eq!(reader.custom_answer_for("question_0_custom", &unset), None);
    let bare = json!({"type": "string", "title": "Other"});
    assert_eq!(
        reader.custom_answer_for("question_0_custom", &bare),
        Some("question_0".to_owned())
    );
    let select =
        json!({"type": "string", "title": "Other", "oneOf": [{"const": "a", "title": "a"}]});
    assert_eq!(
        reader.custom_answer_for("question_0_custom", &select),
        None,
        "a select titled Other is a question, not a companion"
    );
    let retitled = json!({"type": "string", "title": "Notes"});
    assert_eq!(
        reader.custom_answer_for("question_0_custom", &retitled),
        None
    );
    assert_eq!(reader.custom_answer_for("_custom", &bare), None);
}

/// The adapter reports the answer it settled on through the asking tool's
/// `toolResponse`, keyed by question text.
#[test]
fn claude_code_reports_the_answer_it_took_on_the_tool_frame() {
    let reader = Harness::ClaudeCode.reader();
    let reported = Frame::new().meta(json!({"claudeCode": {"toolName": "AskUserQuestion", "toolResponse": {"questions": [], "answers": {"What is the best colour?": "blue"}}}}));
    assert_eq!(
        reader.reported_elicitation_answer(&reported.view()),
        Some(json!({"What is the best colour?": "blue"}))
    );
    let streaming = Frame::new().meta(json!({"claudeCode": {"toolName": "AskUserQuestion"}}));
    assert_eq!(reader.reported_elicitation_answer(&streaming.view()), None);
    let other_tool = Frame::new()
        .meta(json!({"claudeCode": {"toolName": "Bash", "toolResponse": {"stdout": "x"}}}));
    assert_eq!(reader.reported_elicitation_answer(&other_tool.view()), None);
}

/// The neutral reading knows the shared marker and nothing else: no
/// namespace, no naming convention.
#[test]
fn the_generic_reader_knows_only_the_shared_marker() {
    let reader = Harness::Unknown.reader();
    let shared = json!({"type": "string", "title": "Other", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "q", "isCustomAnswer": true}}});
    assert_eq!(reader.custom_answer_for("x", &shared), Some("q".to_owned()));
    let bare = json!({"type": "string", "title": "Other"});
    assert_eq!(reader.custom_answer_for("q_custom", &bare), None);
    assert_eq!(reader.custom_answer_for("q__other", &bare), None);
    let codex = json!({"type": "string", "title": "Other", "_meta": {"codex": {"questionId": "q", "isOtherAnswer": true}}});
    assert_eq!(reader.custom_answer_for("q__other", &codex), None);
}

// --- Codex (@agentclientprotocol/codex-acp, legacy collaboration mode) ---

#[test]
fn codex_names_mcp_tools_from_its_dotted_title_and_flag() {
    let reader = Harness::Codex.reader();
    let flagged = Frame::new()
        .meta(json!({"is_mcp_tool_call": true}))
        .title("mcp.macro.ReadContent");
    assert_eq!(
        reader.reported_tool_name(&flagged.view()),
        Some(ToolName::Mcp {
            server: "macro".to_owned(),
            tool: "ReadContent".to_owned()
        })
    );
    // Without the flag a dotted title is just a title.
    let unflagged = Frame::new().title("mcp.macro.ReadContent");
    assert_eq!(reader.reported_tool_name(&unflagged.view()), None);
    let prose = Frame::new()
        .meta(json!({"is_mcp_tool_call": true}))
        .title("Editing files");
    assert_eq!(reader.reported_tool_name(&prose.view()), None);
}

#[test]
fn codex_spawn_agent_is_a_subagent_and_carries_its_result_in_raw_input() {
    let reader = Harness::Codex.reader();
    let collaboration =
        |tool: &str| {
            Frame::new().kind(ToolKind::Other).meta(json!({"codex": {"collaboration": {
            "tool": tool, "senderThreadId": "thread-main", "receiverThreadIds": ["thread-paris"]
        }}}))
        };
    assert!(reader.is_subagent(&native("spawnAgent"), &collaboration("spawnAgent").view()));
    assert!(
        !reader.is_subagent(&native("wait"), &collaboration("wait").view()),
        "steering an existing subagent is not a delegation"
    );
    assert!(!reader.is_subagent(
        &native("spawnAgent"),
        &Frame::new().kind(ToolKind::Other).view()
    ));

    let frame = Frame::new().title("spawnAgent").raw_input(json!({
        "prompt": "Find the current weather in Paris.",
        "senderThreadId": "thread-main",
        "receiverThreadIds": ["thread-paris"],
        "agentsStates": {"thread-paris": {"status": "completed", "message": "Sunny, 24C"}},
        "model": "gpt-5.4",
        "reasoningEffort": null,
        "status": "completed"
    }));
    let input = reader.subagent_input(&frame.view());
    assert_eq!(
        input.prompt.as_deref(),
        Some("Find the current weather in Paris.")
    );
    let result = reader.subagent_result(&frame.view()).expect("reported");
    assert_eq!(
        result,
        SubagentResult {
            text: Some("Sunny, 24C".to_owned()),
            agent_id: Some("thread-paris".to_owned()),
            model: Some("gpt-5.4".to_owned()),
            ..SubagentResult::default()
        }
    );

    // The opening frame: no child yet, an empty model string means none.
    let opening = Frame::new().raw_input(json!({
        "prompt": "…", "senderThreadId": "thread-main", "receiverThreadIds": [],
        "agentsStates": {}, "model": "", "status": "inProgress"
    }));
    assert_eq!(reader.subagent_result(&opening.view()), None);

    let failed = Frame::new().raw_input(json!({
        "receiverThreadIds": ["t"], "agentsStates": {"t": {"status": "errored", "message": "boom"}},
        "status": "failed"
    }));
    let result = reader.subagent_result(&failed.view()).unwrap();
    assert_eq!(result.error.as_deref(), Some("boom"));
    assert_eq!(result.text, None);
}

/// Codex leaves two marks on its frames; either is enough to recognize it.
#[test]
fn codex_is_sniffed_from_either_of_its_meta_signals() {
    let namespaced = Frame::new().meta(json!({"codex": {"collaboration": {"tool": "wait"}}}));
    assert_eq!(Harness::sniff(&namespaced.view()), Some(Harness::Codex));
    let flagged = Frame::new().meta(json!({"is_mcp_tool_call": true}));
    assert_eq!(Harness::sniff(&flagged.view()), Some(Harness::Codex));
    let unflagged = Frame::new().meta(json!({"is_mcp_tool_call": false}));
    assert_eq!(Harness::sniff(&unflagged.view()), None);
}

/// `request_user_input` through `elicitation/create`: the `__other`
/// companion carries Codex's own marker, and is recognized by it first, by
/// the shared marker second, and by its name and title last.
#[test]
fn codex_recognizes_its_other_answer_companion() {
    let reader = Harness::Codex.reader();
    let marked = json!({"type": "string", "title": "Other", "_meta": {"codex": {"questionId": "target", "isOtherAnswer": true, "isSecret": false}}});
    assert_eq!(
        reader.custom_answer_for("target__other", &marked),
        Some("target".to_owned())
    );
    // The marker names the question; the property's own name need not.
    assert_eq!(
        reader.custom_answer_for("anything", &marked),
        Some("target".to_owned())
    );
    let select = json!({"type": "string", "title": "Target", "oneOf": [{"const": "a", "title": "a"}], "_meta": {"codex": {"isOther": true, "isSecret": false}}});
    assert_eq!(
        reader.custom_answer_for("target", &select),
        None,
        "the select itself is not a companion"
    );
    let shared = json!({"type": "string", "title": "Other", "_meta": {"_askUserQuestionCustomAnswer": {"questionId": "q", "isCustomAnswer": true}}});
    assert_eq!(
        reader.custom_answer_for("q__other", &shared),
        Some("q".to_owned())
    );
    let bare = json!({"type": "string", "title": "Other"});
    assert_eq!(
        reader.custom_answer_for("target__other", &bare),
        Some("target".to_owned()),
        "a recording that lost its _meta still collapses by name"
    );
    assert_eq!(
        reader.custom_answer_for("target_custom", &bare),
        None,
        "Claude Code's suffix is not Codex's"
    );
    assert_eq!(
        reader.reported_elicitation_answer(&Frame::new().view()),
        None,
        "Codex sends no tool call for a question, so nothing reports back"
    );
}

// --- Cursor (cursor_cloud_agents) ---

#[test]
fn cursor_task_reads_its_oneof_subagent_type_and_ids() {
    let reader = Harness::Cursor.reader();
    assert!(reader.is_subagent(&native("task"), &Frame::new().kind(ToolKind::Other).view()));

    let frame = Frame::new().title("task").raw_input(json!({
        "description": "Find SSE decoding",
        "prompt": "Find where SSE decoding happens.",
        "subagentType": {"explore": {}},
        "model": "composer-2.5-fast",
        "agentId": "bc-f6167deb"
    }));
    let input = reader.subagent_input(&frame.view());
    assert_eq!(input.agent_type.as_deref(), Some("explore"));
    assert_eq!(input.description.as_deref(), Some("Find SSE decoding"));
    assert_eq!(
        input.prompt.as_deref(),
        Some("Find where SSE decoding happens.")
    );

    let result = reader
        .subagent_result(&frame.view())
        .expect("ids are a result even before the answer");
    assert_eq!(result.agent_id.as_deref(), Some("bc-f6167deb"));
    assert_eq!(result.model.as_deref(), Some("composer-2.5-fast"));
    assert_eq!(result.text, None);

    // The other spellings of the oneof.
    let agent_type = |raw_input: serde_json::Value| {
        reader
            .subagent_input(&Frame::new().raw_input(raw_input).view())
            .agent_type
    };
    assert_eq!(
        agent_type(json!({"subagentType": {"kind": "custom", "name": "reviewer"}})).as_deref(),
        Some("reviewer")
    );
    assert_eq!(
        agent_type(json!({"subagentType": {"kind": "explore"}})).as_deref(),
        Some("explore")
    );

    // Proto defaults say nothing: no agent type, no model.
    let defaults = Frame::new().raw_input(
        json!({"subagentType": {"unspecified": {}}, "model": "default", "agentId": "bc-1"}),
    );
    assert_eq!(reader.subagent_input(&defaults.view()).agent_type, None);
    let result = reader.subagent_result(&defaults.view()).unwrap();
    assert_eq!(result.model, None);
    assert_eq!(result.agent_id.as_deref(), Some("bc-1"));
}

/// The finished `task` call carries the child's transcript whole; it folds to
/// nested parts, and the closing prose is the answer rather than a child.
#[test]
fn cursor_task_result_unfolds_the_childs_transcript() {
    let reader = Harness::Cursor.reader();
    let frame = Frame::new().raw_output(json!({"result": {"success": {
        "agentId": "bc-child",
        "durationMs": "12978",
        "conversationSteps": [
            {"thinkingMessage": {"text": "Use the shell.", "durationMs": 1168}},
            {"assistantMessage": {"text": "Computing."}},
            {"toolCall": {
                "toolCallId": "call_1\nfc_1",
                "shellToolCall": {
                    "args": {"command": "python3 -c 'import sympy'"},
                    "result": {"failure": {"stderr": "No module named 'sympy'\n", "exitCode": 1}, "isBackground": false}
                }
            }},
            {"toolCall": {
                "toolCallId": "call_2\nfc_2",
                "shellToolCall": {
                    "args": {"command": "python3 -c 'print(124/3)'"},
                    "result": {"success": {"stdout": "41.3\n", "interleavedOutput": "41.3\n"}}
                }
            }},
            {"toolCall": {
                "toolCallId": "call_3",
                "readToolCall": {"args": {"path": "/workspace/README.md"}, "result": {"success": {"path": "/workspace/README.md"}}}
            }},
            {"toolCall": {
                "toolCallId": "call_4",
                "brandNewToolCall": {"args": {"anything": 1}, "result": {"success": {}}}
            }},
            {"somethingElse": {"text": "a step kind this reader has never seen"}},
            {"assistantMessage": {"text": "The exact value is **124/3**."}}
        ]
    }}}));

    let result = reader.subagent_result(&frame.view()).unwrap();
    assert_eq!(
        result,
        SubagentResult {
            text: Some("The exact value is **124/3**.".to_owned()),
            agent_id: Some("bc-child".to_owned()),
            duration_ms: Some(12978),
            tool_uses: Some(4),
            ..SubagentResult::default()
        }
    );

    let children = reader.subagent_transcript(&frame.view());
    assert_eq!(
        children,
        vec![
            MessagePart::Thought {
                text: "Use the shell.".to_owned()
            },
            MessagePart::Text {
                text: "Computing.".to_owned()
            },
            MessagePart::ToolUse {
                id: ToolUseId("call_1 fc_1".to_owned()),
                name: native("shell"),
                status: ToolStatus::Failed,
                detail: ToolDetail::Terminal {
                    command: Some("python3 -c 'import sympy'".to_owned()),
                    output: Some(AnsiText("No module named 'sympy'\n".to_owned())),
                    exit_code: Some(1),
                },
            },
            MessagePart::ToolUse {
                id: ToolUseId("call_2 fc_2".to_owned()),
                name: native("shell"),
                status: ToolStatus::Completed,
                detail: ToolDetail::Terminal {
                    command: Some("python3 -c 'print(124/3)'".to_owned()),
                    output: Some(AnsiText("41.3\n".to_owned())),
                    exit_code: Some(0),
                },
            },
            MessagePart::ToolUse {
                id: ToolUseId("call_3".to_owned()),
                name: native("read"),
                status: ToolStatus::Completed,
                detail: ToolDetail::Read {
                    paths: vec!["/workspace/README.md".into()],
                },
            },
            // An unknown tool is kept by name; an unknown step kind is skipped.
            MessagePart::ToolUse {
                id: ToolUseId("call_4".to_owned()),
                name: native("brandNew"),
                status: ToolStatus::Pending,
                detail: ToolDetail::Other {
                    kind: "other".to_owned(),
                    output: None,
                    input: None,
                    result: None,
                    error: None,
                },
            },
        ]
    );

    // A failed task is an error, with nothing to nest.
    let failed = Frame::new().raw_output(json!({"result": {"error": "agent crashed"}}));
    let result = reader.subagent_result(&failed.view()).unwrap();
    assert_eq!(result.error.as_deref(), Some("agent crashed"));
    assert_eq!(result.text, None);
    assert_eq!(reader.subagent_transcript(&failed.view()), vec![]);

    // The opening frame carries no result and so no transcript.
    assert_eq!(reader.subagent_transcript(&Frame::new().view()), vec![]);
}

/// Every MCP call goes through Cursor's `mcp` dispatcher, whose arguments
/// say which server and tool; the reader names the call for those and hands
/// on the tool's own arguments without the dispatcher's.
#[test]
fn cursor_names_mcp_calls_from_the_dispatchers_arguments() {
    let reader = Harness::Cursor.reader();
    let dispatched = Frame::new().title("mcp").raw_input(json!({
        "name": "macro-ReadContent",
        "toolCallId": "call-1 fc_1",
        "providerIdentifier": "macro",
        "toolName": "ReadContent",
        "serverIdentifier": "macro",
        "args": {"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}
    }));
    assert_eq!(
        reader.reported_tool_name(&dispatched.view()),
        Some(ToolName::Mcp {
            server: "macro".to_owned(),
            tool: "ReadContent".to_owned()
        })
    );
    assert_eq!(
        reader.tool_input(&dispatched.view()),
        Some(json!({"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}))
    );

    // The announcement carries no arguments: nothing to name it by yet.
    let announced = Frame::new().title("mcp");
    assert_eq!(reader.reported_tool_name(&announced.view()), None);
    assert_eq!(reader.tool_input(&announced.view()), None);

    // A tool that takes nothing, as recorded: the dispatcher's keys alone,
    // and only `providerIdentifier` in an older recording.
    let bare = Frame::new().title("mcp").raw_input(json!({
        "name": "cursor-cloud-get-message-queue",
        "toolCallId": "call-2 fc_2",
        "providerIdentifier": "cursor-cloud",
        "toolName": "get-message-queue"
    }));
    assert_eq!(
        reader.reported_tool_name(&bare.view()),
        Some(ToolName::Mcp {
            server: "cursor-cloud".to_owned(),
            tool: "get-message-queue".to_owned()
        })
    );
    assert_eq!(reader.tool_input(&bare.view()), Some(json!({})));

    // Any other tool's arguments are its own already, and its title is its
    // name - `get_mcp_tools` names a tool too, but is not the dispatcher.
    let listing = Frame::new().title("get_mcp_tools").raw_input(
        json!({"server": "cursor-cloud", "toolName": "get-message-queue", "toolCallId": "c"}),
    );
    assert_eq!(reader.reported_tool_name(&listing.view()), None);
    assert_eq!(
        reader.tool_input(&listing.view()),
        Some(json!({"server": "cursor-cloud", "toolName": "get-message-queue", "toolCallId": "c"}))
    );
    let shell = Frame::new()
        .title("run_terminal_cmd")
        .raw_input(json!({"command": "ls"}));
    assert_eq!(reader.reported_tool_name(&shell.view()), None);
    assert_eq!(
        reader.tool_input(&shell.view()),
        Some(json!({"command": "ls"}))
    );
}

/// A call's `rawOutput` is Cursor's result under `result`; for an MCP call
/// that is MCP's `CallToolResult` in Cursor's spelling, and the reader
/// unwraps it to what the tool returned.
#[test]
fn cursor_unwraps_mcp_results_from_its_envelope() {
    let reader = Harness::Cursor.reader();

    // Structured content wins, as in the standard envelope.
    let structured = json!({"result": {"success": {
        "content": [{"text": {"text": "Cursor Cloud message queue (0 queued).\n{\"hasQueuedMessages\": false}"}}],
        "structuredContent": {"hasQueuedMessages": false, "queuedMessageCount": 0}
    }}});
    assert_eq!(
        reader.unwrap_tool_output(&structured),
        (
            json!({"hasQueuedMessages": false, "queuedMessageCount": 0}),
            None
        )
    );

    // Else the text, parsed when it is JSON, as text when it is not.
    let json_text = json!({"result": {"success": {
        "content": [{"text": {"text": "{\"content\":{\"text\":\"Q3 plan\"},\"comments\":[]}"}}]
    }}});
    assert_eq!(
        reader.unwrap_tool_output(&json_text),
        (
            json!({"content": {"text": "Q3 plan"}, "comments": []}),
            None
        )
    );
    let prose = json!({"result": {"success": {
        "content": [{"text": {"text": "first"}}, {"image": {"data": "…"}}, {"text": {"text": "second"}}]
    }}});
    assert_eq!(
        reader.unwrap_tool_output(&prose),
        (json!("first\nsecond"), None)
    );

    // Content as one string - how `get_mcp_tools` reports its catalog.
    let catalog =
        json!({"result": {"success": {"content": "{\"mode\": \"catalog\", \"servers\": []}"}}});
    assert_eq!(
        reader.unwrap_tool_output(&catalog),
        (json!({"mode": "catalog", "servers": []}), None)
    );

    // A result that marks itself an error is one, and still a result.
    let marked = json!({"result": {"success": {
        "content": [{"text": {"text": "no such document"}}], "isError": true
    }}});
    assert_eq!(
        reader.unwrap_tool_output(&marked),
        (
            json!("no such document"),
            Some("no such document".to_owned())
        )
    );

    // The dispatcher's own failures, each as its text.
    let error =
        json!({"result": {"error": {"error": "MCP tool \"x\" not found on server \"y\"."}}});
    assert_eq!(
        reader.unwrap_tool_output(&error),
        (
            Value::Null,
            Some("MCP tool \"x\" not found on server \"y\".".to_owned())
        )
    );
    let rejected =
        json!({"result": {"rejected": {"reason": "user declined", "isReadonly": false}}});
    assert_eq!(
        reader.unwrap_tool_output(&rejected),
        (Value::Null, Some("user declined".to_owned()))
    );
    let denied = json!({"result": {"permissionDenied": {"error": "not allowed"}}});
    assert_eq!(
        reader.unwrap_tool_output(&denied),
        (Value::Null, Some("not allowed".to_owned()))
    );
    let missing = json!({"result": {"toolNotFound": {"name": "x", "availableTools": ["y"]}}});
    assert_eq!(
        reader.unwrap_tool_output(&missing),
        (
            Value::Null,
            Some("{\"name\":\"x\",\"availableTools\":[\"y\"]}".to_owned())
        )
    );

    // A native tool's payload is not MCP's and comes through as Cursor wrote
    // it; a shell failure is both the result and, as text, the error.
    let path = json!({"result": {"success": {"path": "/workspace/README.md"}}});
    assert_eq!(
        reader.unwrap_tool_output(&path),
        (json!({"path": "/workspace/README.md"}), None)
    );
    let failure =
        json!({"result": {"failure": {"stderr": "No module named 'sympy'\n", "exitCode": 1}}});
    assert_eq!(
        reader.unwrap_tool_output(&failure),
        (
            json!({"stderr": "No module named 'sympy'\n", "exitCode": 1}),
            Some("No module named 'sympy'\n".to_owned())
        )
    );

    // Not Cursor's envelope at all: the neutral reading.
    let standard =
        json!({"content": [{"type": "text", "text": "{\"ok\":true}"}], "isError": false});
    assert_eq!(
        reader.unwrap_tool_output(&standard),
        (json!({"ok": true}), None)
    );
    assert_eq!(
        reader.unwrap_tool_output(&json!({"result": {}})),
        (json!({"result": {}}), None)
    );
}

/// A child's `mcpToolCall` step is read the same way as a top-level call.
#[test]
fn cursor_child_mcp_calls_are_named_and_unwrapped() {
    let reader = Harness::Cursor.reader();
    let frame = Frame::new().raw_output(json!({"result": {"success": {
        "agentId": "bc-child",
        "conversationSteps": [
            {"toolCall": {
                "toolCallId": "call_m",
                "mcpToolCall": {
                    "args": {
                        "name": "macro-ReadContent",
                        "toolCallId": "call_m",
                        "providerIdentifier": "macro",
                        "toolName": "ReadContent",
                        "serverIdentifier": "macro",
                        "args": {"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"}
                    },
                    "result": {"success": {
                        "content": [{"text": {"text": "{\"content\":{\"text\":\"Q3 plan\"}}"}}]
                    }}
                }
            }},
            {"toolCall": {
                "toolCallId": "call_n",
                "mcpToolCall": {
                    "args": {"toolName": "deploy", "serverIdentifier": "ops", "toolCallId": "call_n"},
                    "result": {"rejected": {"reason": "user declined"}}
                }
            }},
            {"assistantMessage": {"text": "Done."}}
        ]
    }}}));
    assert_eq!(
        reader.subagent_transcript(&frame.view()),
        vec![
            MessagePart::ToolUse {
                id: ToolUseId("call_m".to_owned()),
                name: ToolName::Mcp {
                    server: "macro".to_owned(),
                    tool: "ReadContent".to_owned()
                },
                status: ToolStatus::Completed,
                detail: ToolDetail::Other {
                    kind: "other".to_owned(),
                    output: None,
                    input: Some(json!({"documentId": "4a4886d8-9f4b-4f7e-a5a3-3f5c8b6c0e46"})),
                    result: Some(json!({"content": {"text": "Q3 plan"}})),
                    error: None,
                },
            },
            MessagePart::ToolUse {
                id: ToolUseId("call_n".to_owned()),
                name: ToolName::Mcp {
                    server: "ops".to_owned(),
                    tool: "deploy".to_owned()
                },
                status: ToolStatus::Failed,
                detail: ToolDetail::Other {
                    kind: "other".to_owned(),
                    output: None,
                    input: Some(json!({})),
                    result: None,
                    error: Some("user declined".to_owned()),
                },
            },
        ]
    );
}

// --- Hermes (hermes-agent) ---

#[test]
fn hermes_delegations_are_recognized_from_their_titles() {
    let reader = Harness::Hermes.reader();
    for title in [
        "delegate: Find the flaky test",
        "delegate batch (3 tasks)",
        "delegate task",
    ] {
        let frame = Frame::new().title(title).kind(ToolKind::Execute);
        let name = reader
            .reported_tool_name(&frame.view())
            .unwrap_or_else(|| panic!("{title:?} names delegate_task"));
        assert_eq!(name, native("delegate_task"));
        assert!(
            reader.is_subagent(&name, &frame.view()),
            "{title:?} is a delegation despite kind execute"
        );
    }
    let shell = Frame::new().title("ls -la").kind(ToolKind::Execute);
    assert_eq!(reader.reported_tool_name(&shell.view()), None);
    assert!(!reader.is_subagent(&native("ls -la"), &shell.view()));

    let input = reader.subagent_input(&Frame::new().title("delegate: Find the flaky test").view());
    assert_eq!(input.prompt.as_deref(), Some("Find the flaky test"));
    assert_eq!(
        input.description.as_deref(),
        Some("delegate: Find the flaky test")
    );

    let ok = reader
        .subagent_result(
            &Frame::new()
                .text("Delegation results: 1 task(s) in 4s")
                .view(),
        )
        .unwrap();
    assert_eq!(
        ok.text.as_deref(),
        Some("Delegation results: 1 task(s) in 4s")
    );
    let failed = reader
        .subagent_result(
            &Frame::new()
                .text("Delegation failed: pool exhausted")
                .view(),
        )
        .unwrap();
    assert_eq!(failed.error.as_deref(), Some("pool exhausted"));
    assert_eq!(failed.text, None);
}

// --- OpenClaw (openclaw-acp) ---

#[test]
fn openclaw_names_tools_from_its_titles_and_reads_spawns() {
    let reader = Harness::OpenClaw.reader();
    let title =
        "sessions_spawn: task: Investigate flaky test, label: flaky-test, runtime: subagent";
    assert_eq!(
        reader.reported_tool_name(&Frame::new().title(title).view()),
        Some(native("sessions_spawn"))
    );
    assert_eq!(
        reader.reported_tool_name(&Frame::new().title("read: path: /etc/hosts").view()),
        Some(native("read"))
    );
    assert_eq!(
        reader.reported_tool_name(&Frame::new().title("Plain title").view()),
        None
    );
    let other = Frame::new().kind(ToolKind::Other);
    assert!(reader.is_subagent(&native("sessions_spawn"), &other.view()));
    assert!(!reader.is_subagent(&native("sessions_send"), &other.view()));

    let frame = Frame::new().title(title).raw_input(json!({
        "task": "Investigate flaky test",
        "label": "flaky-test",
        "runtime": "subagent"
    }));
    let input = reader.subagent_input(&frame.view());
    assert_eq!(input.prompt.as_deref(), Some("Investigate flaky test"));
    assert_eq!(input.description.as_deref(), Some("flaky-test"));
    assert_eq!(input.agent_type.as_deref(), Some("subagent"));

    let frame = frame.raw_output(json!({
        "content": [{"type": "text", "text": "{\"status\":\"accepted\",\"childSessionKey\":\"agent:main:subagent:1f2e\",\"runId\":\"r1\"}"}],
        "details": {"status": "accepted", "childSessionKey": "agent:main:subagent:1f2e", "runId": "r1"}
    }));
    let result = reader.subagent_result(&frame.view()).unwrap();
    assert_eq!(result.agent_id.as_deref(), Some("agent:main:subagent:1f2e"));
    assert_eq!(result.text, None, "an accepted spawn has no answer yet");

    // Without `details`, the text block's JSON is read instead.
    let text_only = Frame::new()
        .raw_output(json!({"content": [{"type": "text", "text": "{\"childSessionKey\":\"k\"}"}]}));
    assert_eq!(
        reader
            .subagent_result(&text_only.view())
            .unwrap()
            .agent_id
            .as_deref(),
        Some("k")
    );
}

/// The harnesses that leave nothing distinctive on their tool frames cannot
/// be sniffed; they are recognized from `initialize` alone.
#[test]
fn title_only_harnesses_are_not_sniffed() {
    let anonymous = Frame::new()
        .meta(json!({"terminal_output": {"data": "x"}}))
        .title("task")
        .kind(ToolKind::Other)
        .raw_input(json!({"description": "d", "prompt": "p"}));
    assert_eq!(Harness::sniff(&anonymous.view()), None);
    for harness in [
        Harness::OpenCode,
        Harness::Cursor,
        Harness::Hermes,
        Harness::OpenClaw,
    ] {
        assert!(!harness.reader().wrote(&anonymous.view()), "{harness:?}");
    }
}